_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 |
|---|---|---|---|---|---|---|---|---|
1e4b6e09f55452e46cf2d6d5e98191f270846dc67b95bb281642a8a299d74059 | turquoise-hexagon/euler | solution.scm | (import
(chicken fixnum)
(euler))
(define-constant limit #e5e6)
(define factorials (list->vector (map factorial (range 0 9))))
(define (f n)
(let loop ((n n) (acc 0))
(if (fx= n 0)
acc
(loop (fx/ n 10) (fx+ acc (vector-ref factorials (fxmod n 10)))))))
(define chain
(let ((cache (make-vector limit)))
(lambda (n)
(let loop ((n n) (acc '()))
(let ((_ (vector-ref cache n)))
(if (number? _)
_
(if (member n acc)
0
(let ((_ (fx+ (loop (f n) (cons n acc)) 1)))
(vector-set! cache n _)
_))))))))
(define (solve n)
(let loop ((i 1) (acc 0))
(if (fx> i n)
acc
(loop (fx+ i 1)
(if (fx= (chain i) 60)
(fx+ acc 1)
acc)))))
(let ((_ (solve #e1e6)))
(print _) (assert (= _ 402)))
| null | https://raw.githubusercontent.com/turquoise-hexagon/euler/46f1ec42385096a704bfe66e201c70b3fae8d306/src/074/solution.scm | scheme | (import
(chicken fixnum)
(euler))
(define-constant limit #e5e6)
(define factorials (list->vector (map factorial (range 0 9))))
(define (f n)
(let loop ((n n) (acc 0))
(if (fx= n 0)
acc
(loop (fx/ n 10) (fx+ acc (vector-ref factorials (fxmod n 10)))))))
(define chain
(let ((cache (make-vector limit)))
(lambda (n)
(let loop ((n n) (acc '()))
(let ((_ (vector-ref cache n)))
(if (number? _)
_
(if (member n acc)
0
(let ((_ (fx+ (loop (f n) (cons n acc)) 1)))
(vector-set! cache n _)
_))))))))
(define (solve n)
(let loop ((i 1) (acc 0))
(if (fx> i n)
acc
(loop (fx+ i 1)
(if (fx= (chain i) 60)
(fx+ acc 1)
acc)))))
(let ((_ (solve #e1e6)))
(print _) (assert (= _ 402)))
| |
98782f55715e98de646b3bc0f96153c984c8f04c17572c4c798d2d707e9698d0 | slyrus/clem | test-gaussian-convolve-1.lisp |
(in-package :matrix)
(let ((x (normalize (random-matrix 3 3)))
(h (matrix::gaussian-kernel 2 1)))
(print-matrix x)
; (print-matrix h)
; (print (sum h))
(let* ((rowstart (floor (/ (1- (matrix::rows h)) 2)))
(rowend (floor (/ (matrix::rows h) 2)))
(colstart (floor (/ (1- (matrix::cols h)) 2)))
(colend (floor (/ (matrix::cols h) 2)))
(h1 (matrix::subset-matrix h rowstart rowend 0 (1- (matrix::cols h))))
(h2 (matrix::subset-matrix h 0 (1- (matrix::rows h)) colstart colend)))
(matrix::scalar-divide h1 (matrix::sum h1))
(matrix::scalar-divide h2 (matrix::sum h2))
(matrix::print-matrix h1)
(matrix::print-matrix h2)
(let*
((x1 (matrix::discrete-convolve-ppc x h1))
(x2 (matrix::discrete-convolve-ppc x1 h2)))
(matrix::print-matrix x1)
(matrix::print-matrix x2))
)
(print-matrix (gaussian-blur x 2 1))
)
;(in-package :cl-user)
;(defvar h)
( setf h ( matrix::gaussian - kernel 1 1 ) )
( setf k ( matrix::gaussian - kernel 1 1 ) )
;(matrix::print-matrix (matrix::gradmag h)) | null | https://raw.githubusercontent.com/slyrus/clem/5eb055bb3f45840b24fd44825b975aa36bd6d97c/test/test-gaussian-convolve-1.lisp | lisp | (print-matrix h)
(print (sum h))
(in-package :cl-user)
(defvar h)
(matrix::print-matrix (matrix::gradmag h)) |
(in-package :matrix)
(let ((x (normalize (random-matrix 3 3)))
(h (matrix::gaussian-kernel 2 1)))
(print-matrix x)
(let* ((rowstart (floor (/ (1- (matrix::rows h)) 2)))
(rowend (floor (/ (matrix::rows h) 2)))
(colstart (floor (/ (1- (matrix::cols h)) 2)))
(colend (floor (/ (matrix::cols h) 2)))
(h1 (matrix::subset-matrix h rowstart rowend 0 (1- (matrix::cols h))))
(h2 (matrix::subset-matrix h 0 (1- (matrix::rows h)) colstart colend)))
(matrix::scalar-divide h1 (matrix::sum h1))
(matrix::scalar-divide h2 (matrix::sum h2))
(matrix::print-matrix h1)
(matrix::print-matrix h2)
(let*
((x1 (matrix::discrete-convolve-ppc x h1))
(x2 (matrix::discrete-convolve-ppc x1 h2)))
(matrix::print-matrix x1)
(matrix::print-matrix x2))
)
(print-matrix (gaussian-blur x 2 1))
)
( setf h ( matrix::gaussian - kernel 1 1 ) )
( setf k ( matrix::gaussian - kernel 1 1 ) ) |
282ca87c410100486fdd3ac3d82619e46145bd7e3a1c988a56f172f1f1b215c2 | ygrek/mldonkey | hashtbl2.mli | Copyright 2001 , 2002 b8_bavard , b8_fee_carabine ,
This file is part of mldonkey .
mldonkey is free software ; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation ; either version 2 of the License , or
( at your option ) any later version .
mldonkey 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 mldonkey ; if not , write to the Free Software
Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA
This file is part of mldonkey.
mldonkey is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
mldonkey 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 mldonkey; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*)
val to_list : ('a, 'b) Hashtbl.t -> 'b list
val to_list2 : ('a, 'b) Hashtbl.t -> ('a * 'b) list
(* can be used with a function that can modify the hashtbl *)
val safe_iter : ('a -> unit) -> ('b, 'a) Hashtbl.t -> unit
(*
(* Module [Hashtbl2]: hash tables and hash functions *)
(* Hash tables are hashed association tables, with in-place modification. *)
(*** Generic interface *)
type ('a, 'b) t
(* The type of hash tables from type ['a] to type ['b]. *)
val create : int -> ('a,'b) t
(* [Hashtbl.create n] creates a new, empty hash table, with
initial size [n]. For best results, [n] should be on the
order of the expected number of elements that will be in
the table. The table grows as needed, so [n] is just an
initial guess. *)
val clear : ('a, 'b) t -> unit
(* Empty a hash table. *)
val add : ('a, 'b) t -> 'a -> 'b -> unit
[ Hashtbl.add tbl x y ] adds a binding of [ x ] to [ y ] in table [ tbl ] .
Previous bindings for [ x ] are not removed , but simply
hidden . That is , after performing [ Hashtbl.remove x ] ,
the previous binding for [ x ] , if any , is restored .
( Same behavior as with association lists . )
Previous bindings for [x] are not removed, but simply
hidden. That is, after performing [Hashtbl.remove tbl x],
the previous binding for [x], if any, is restored.
(Same behavior as with association lists.) *)
val find : ('a, 'b) t -> 'a -> 'b
(* [Hashtbl.find tbl x] returns the current binding of [x] in [tbl],
or raises [Not_found] if no such binding exists. *)
val find_all : ('a, 'b) t -> 'a -> 'b list
[ Hashtbl.find_all tbl x ] returns the list of all data
associated with [ x ] in [ tbl ] .
The current binding is returned first , then the previous
bindings , in reverse order of introduction in the table .
associated with [x] in [tbl].
The current binding is returned first, then the previous
bindings, in reverse order of introduction in the table. *)
val mem : ('a, 'b) t -> 'a -> bool
[ tbl x ] checks if [ x ] is bound in [ tbl ] .
val remove : ('a, 'b) t -> 'a -> unit
[ Hashtbl.remove x ] removes the current binding of [ x ] in [ tbl ] ,
restoring the previous binding if it exists .
It does nothing if [ x ] is not bound in [ tbl ] .
restoring the previous binding if it exists.
It does nothing if [x] is not bound in [tbl]. *)
val replace : ('a, 'b) t -> 'a -> 'b -> unit
[ Hashtbl.replace tbl x y ] replaces the current binding of [ x ]
in [ tbl ] by a binding of [ x ] to [ y ] . If [ x ] is unbound in [ tbl ] ,
a binding of [ x ] to [ y ] is added to [ tbl ] .
This is functionally equivalent to [ Hashtbl.remove x ]
followed by [ Hashtbl.add tbl x y ] .
in [tbl] by a binding of [x] to [y]. If [x] is unbound in [tbl],
a binding of [x] to [y] is added to [tbl].
This is functionally equivalent to [Hashtbl.remove tbl x]
followed by [Hashtbl.add tbl x y]. *)
val iter : ('a -> 'b -> unit) -> ('a, 'b) t -> unit
[ Hashtbl.iter f tbl ] applies [ f ] to all bindings in table [ tbl ] .
[ f ] receives the key as first argument , and the associated value
as second argument . The order in which the bindings are passed to
[ f ] is unspecified . Each binding is presented exactly once
to [ f ] .
[f] receives the key as first argument, and the associated value
as second argument. The order in which the bindings are passed to
[f] is unspecified. Each binding is presented exactly once
to [f]. *)
val fold : ('a -> 'b -> 'c -> 'c) -> ('a, 'b) t -> 'c -> 'c
(* [Hashtbl.fold f tbl init] computes
[(f kN dN ... (f k1 d1 init)...)],
where [k1 ... kN] are the keys of all bindings in [tbl],
and [d1 ... dN] are the associated values.
The order in which the bindings are passed to
[f] is unspecified. Each binding is presented exactly once
to [f]. *)
val to_list : ('a, 'b) t -> 'b list
(*** Functorial interface *)
module type HashedType =
sig
type t
val equal: t -> t -> bool
val hash: t -> int
end
The input signature of the functor [ . Make ] .
[ t ] is the type of keys .
[ equal ] is the equality predicate used to compare keys .
[ hash ] is a hashing function on keys , returning a non - negative
integer . It must be such that if two keys are equal according
to [ equal ] , then they must have identical hash values as computed
by [ hash ] .
Examples : suitable ( [ equal ] , [ hash ] ) pairs for arbitrary key
types include
( [ ( =) ] , [ Hashtbl.hash ] ) for comparing objects by structure , and
( [ (= =) ] , [ Hashtbl.hash ] ) for comparing objects by addresses
( e.g. for mutable or cyclic keys ) .
[t] is the type of keys.
[equal] is the equality predicate used to compare keys.
[hash] is a hashing function on keys, returning a non-negative
integer. It must be such that if two keys are equal according
to [equal], then they must have identical hash values as computed
by [hash].
Examples: suitable ([equal], [hash]) pairs for arbitrary key
types include
([(=)], [Hashtbl.hash]) for comparing objects by structure, and
([(==)], [Hashtbl.hash]) for comparing objects by addresses
(e.g. for mutable or cyclic keys). *)
module type S =
sig
type key
type 'a t
val create: int -> 'a t
val clear: 'a t -> unit
val add: 'a t -> key -> 'a -> unit
val remove: 'a t -> key -> unit
val find: 'a t -> key -> 'a
val find_all: 'a t -> key -> 'a list
val replace: 'a t -> key -> 'a -> unit
val mem: 'a t -> key -> bool
val iter: (key -> 'a -> unit) -> 'a t -> unit
val fold: (key -> 'a -> 'b -> 'b) -> 'a t -> 'b -> 'b
end
module Make(H: HashedType): (S with type key = H.t)
The functor [ . Make ] returns a structure containing
a type [ key ] of keys and a type [ ' a t ] of hash tables
associating data of type [ ' a ] to keys of type [ key ] .
The operations perform similarly to those of the generic
interface , but use the hashing and equality functions
specified in the functor argument [ H ] instead of generic
equality and hashing .
a type [key] of keys and a type ['a t] of hash tables
associating data of type ['a] to keys of type [key].
The operations perform similarly to those of the generic
interface, but use the hashing and equality functions
specified in the functor argument [H] instead of generic
equality and hashing. *)
(*** The polymorphic hash primitive *)
val hash : 'a -> int
(* [Hashtbl.hash x] associates a positive integer to any value of
any type. It is guaranteed that
if [x = y], then [hash x = hash y].
Moreover, [hash] always terminates, even on cyclic
structures. *)
external hash_param : int -> int -> 'a -> int = "hash_univ_param" "noalloc"
[ Hashtbl.hash_param n m x ] computes a hash value for [ x ] , with the
same properties as for [ hash ] . The two extra parameters [ n ] and
[ m ] give more precise control over hashing . Hashing performs a
depth - first , right - to - left traversal of the structure [ x ] , stopping
after [ n ] meaningful nodes were encountered , or [ m ] nodes ,
meaningful or not , were encountered . Meaningful nodes are : integers ;
floating - point numbers ; strings ; characters ; booleans ; and constant
constructors . Larger values of [ m ] and [ n ] means that more
nodes are taken into account to compute the final hash
value , and therefore collisions are less likely to happen .
However , hashing takes longer . The parameters [ m ] and [ n ]
govern the tradeoff between accuracy and speed .
same properties as for [hash]. The two extra parameters [n] and
[m] give more precise control over hashing. Hashing performs a
depth-first, right-to-left traversal of the structure [x], stopping
after [n] meaningful nodes were encountered, or [m] nodes,
meaningful or not, were encountered. Meaningful nodes are: integers;
floating-point numbers; strings; characters; booleans; and constant
constructors. Larger values of [m] and [n] means that more
nodes are taken into account to compute the final hash
value, and therefore collisions are less likely to happen.
However, hashing takes longer. The parameters [m] and [n]
govern the tradeoff between accuracy and speed. *)
*)
| null | https://raw.githubusercontent.com/ygrek/mldonkey/333868a12bb6cd25fed49391dd2c3a767741cb51/src/utils/cdk/hashtbl2.mli | ocaml | can be used with a function that can modify the hashtbl
(* Module [Hashtbl2]: hash tables and hash functions
Hash tables are hashed association tables, with in-place modification.
** Generic interface
The type of hash tables from type ['a] to type ['b].
[Hashtbl.create n] creates a new, empty hash table, with
initial size [n]. For best results, [n] should be on the
order of the expected number of elements that will be in
the table. The table grows as needed, so [n] is just an
initial guess.
Empty a hash table.
[Hashtbl.find tbl x] returns the current binding of [x] in [tbl],
or raises [Not_found] if no such binding exists.
[Hashtbl.fold f tbl init] computes
[(f kN dN ... (f k1 d1 init)...)],
where [k1 ... kN] are the keys of all bindings in [tbl],
and [d1 ... dN] are the associated values.
The order in which the bindings are passed to
[f] is unspecified. Each binding is presented exactly once
to [f].
** Functorial interface
** The polymorphic hash primitive
[Hashtbl.hash x] associates a positive integer to any value of
any type. It is guaranteed that
if [x = y], then [hash x = hash y].
Moreover, [hash] always terminates, even on cyclic
structures. | Copyright 2001 , 2002 b8_bavard , b8_fee_carabine ,
This file is part of mldonkey .
mldonkey is free software ; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation ; either version 2 of the License , or
( at your option ) any later version .
mldonkey 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 mldonkey ; if not , write to the Free Software
Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA
This file is part of mldonkey.
mldonkey is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
mldonkey 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 mldonkey; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*)
val to_list : ('a, 'b) Hashtbl.t -> 'b list
val to_list2 : ('a, 'b) Hashtbl.t -> ('a * 'b) list
val safe_iter : ('a -> unit) -> ('b, 'a) Hashtbl.t -> unit
type ('a, 'b) t
val create : int -> ('a,'b) t
val clear : ('a, 'b) t -> unit
val add : ('a, 'b) t -> 'a -> 'b -> unit
[ Hashtbl.add tbl x y ] adds a binding of [ x ] to [ y ] in table [ tbl ] .
Previous bindings for [ x ] are not removed , but simply
hidden . That is , after performing [ Hashtbl.remove x ] ,
the previous binding for [ x ] , if any , is restored .
( Same behavior as with association lists . )
Previous bindings for [x] are not removed, but simply
hidden. That is, after performing [Hashtbl.remove tbl x],
the previous binding for [x], if any, is restored.
(Same behavior as with association lists.) *)
val find : ('a, 'b) t -> 'a -> 'b
val find_all : ('a, 'b) t -> 'a -> 'b list
[ Hashtbl.find_all tbl x ] returns the list of all data
associated with [ x ] in [ tbl ] .
The current binding is returned first , then the previous
bindings , in reverse order of introduction in the table .
associated with [x] in [tbl].
The current binding is returned first, then the previous
bindings, in reverse order of introduction in the table. *)
val mem : ('a, 'b) t -> 'a -> bool
[ tbl x ] checks if [ x ] is bound in [ tbl ] .
val remove : ('a, 'b) t -> 'a -> unit
[ Hashtbl.remove x ] removes the current binding of [ x ] in [ tbl ] ,
restoring the previous binding if it exists .
It does nothing if [ x ] is not bound in [ tbl ] .
restoring the previous binding if it exists.
It does nothing if [x] is not bound in [tbl]. *)
val replace : ('a, 'b) t -> 'a -> 'b -> unit
[ Hashtbl.replace tbl x y ] replaces the current binding of [ x ]
in [ tbl ] by a binding of [ x ] to [ y ] . If [ x ] is unbound in [ tbl ] ,
a binding of [ x ] to [ y ] is added to [ tbl ] .
This is functionally equivalent to [ Hashtbl.remove x ]
followed by [ Hashtbl.add tbl x y ] .
in [tbl] by a binding of [x] to [y]. If [x] is unbound in [tbl],
a binding of [x] to [y] is added to [tbl].
This is functionally equivalent to [Hashtbl.remove tbl x]
followed by [Hashtbl.add tbl x y]. *)
val iter : ('a -> 'b -> unit) -> ('a, 'b) t -> unit
[ Hashtbl.iter f tbl ] applies [ f ] to all bindings in table [ tbl ] .
[ f ] receives the key as first argument , and the associated value
as second argument . The order in which the bindings are passed to
[ f ] is unspecified . Each binding is presented exactly once
to [ f ] .
[f] receives the key as first argument, and the associated value
as second argument. The order in which the bindings are passed to
[f] is unspecified. Each binding is presented exactly once
to [f]. *)
val fold : ('a -> 'b -> 'c -> 'c) -> ('a, 'b) t -> 'c -> 'c
val to_list : ('a, 'b) t -> 'b list
module type HashedType =
sig
type t
val equal: t -> t -> bool
val hash: t -> int
end
The input signature of the functor [ . Make ] .
[ t ] is the type of keys .
[ equal ] is the equality predicate used to compare keys .
[ hash ] is a hashing function on keys , returning a non - negative
integer . It must be such that if two keys are equal according
to [ equal ] , then they must have identical hash values as computed
by [ hash ] .
Examples : suitable ( [ equal ] , [ hash ] ) pairs for arbitrary key
types include
( [ ( =) ] , [ Hashtbl.hash ] ) for comparing objects by structure , and
( [ (= =) ] , [ Hashtbl.hash ] ) for comparing objects by addresses
( e.g. for mutable or cyclic keys ) .
[t] is the type of keys.
[equal] is the equality predicate used to compare keys.
[hash] is a hashing function on keys, returning a non-negative
integer. It must be such that if two keys are equal according
to [equal], then they must have identical hash values as computed
by [hash].
Examples: suitable ([equal], [hash]) pairs for arbitrary key
types include
([(=)], [Hashtbl.hash]) for comparing objects by structure, and
([(==)], [Hashtbl.hash]) for comparing objects by addresses
(e.g. for mutable or cyclic keys). *)
module type S =
sig
type key
type 'a t
val create: int -> 'a t
val clear: 'a t -> unit
val add: 'a t -> key -> 'a -> unit
val remove: 'a t -> key -> unit
val find: 'a t -> key -> 'a
val find_all: 'a t -> key -> 'a list
val replace: 'a t -> key -> 'a -> unit
val mem: 'a t -> key -> bool
val iter: (key -> 'a -> unit) -> 'a t -> unit
val fold: (key -> 'a -> 'b -> 'b) -> 'a t -> 'b -> 'b
end
module Make(H: HashedType): (S with type key = H.t)
The functor [ . Make ] returns a structure containing
a type [ key ] of keys and a type [ ' a t ] of hash tables
associating data of type [ ' a ] to keys of type [ key ] .
The operations perform similarly to those of the generic
interface , but use the hashing and equality functions
specified in the functor argument [ H ] instead of generic
equality and hashing .
a type [key] of keys and a type ['a t] of hash tables
associating data of type ['a] to keys of type [key].
The operations perform similarly to those of the generic
interface, but use the hashing and equality functions
specified in the functor argument [H] instead of generic
equality and hashing. *)
val hash : 'a -> int
external hash_param : int -> int -> 'a -> int = "hash_univ_param" "noalloc"
[ Hashtbl.hash_param n m x ] computes a hash value for [ x ] , with the
same properties as for [ hash ] . The two extra parameters [ n ] and
[ m ] give more precise control over hashing . Hashing performs a
depth - first , right - to - left traversal of the structure [ x ] , stopping
after [ n ] meaningful nodes were encountered , or [ m ] nodes ,
meaningful or not , were encountered . Meaningful nodes are : integers ;
floating - point numbers ; strings ; characters ; booleans ; and constant
constructors . Larger values of [ m ] and [ n ] means that more
nodes are taken into account to compute the final hash
value , and therefore collisions are less likely to happen .
However , hashing takes longer . The parameters [ m ] and [ n ]
govern the tradeoff between accuracy and speed .
same properties as for [hash]. The two extra parameters [n] and
[m] give more precise control over hashing. Hashing performs a
depth-first, right-to-left traversal of the structure [x], stopping
after [n] meaningful nodes were encountered, or [m] nodes,
meaningful or not, were encountered. Meaningful nodes are: integers;
floating-point numbers; strings; characters; booleans; and constant
constructors. Larger values of [m] and [n] means that more
nodes are taken into account to compute the final hash
value, and therefore collisions are less likely to happen.
However, hashing takes longer. The parameters [m] and [n]
govern the tradeoff between accuracy and speed. *)
*)
|
e5f1a05b030004dab40264c52413568842aa9c99bf06f8386f192efee4186f50 | dsheets/ocaml-unix-errno | errno.mli |
* Copyright ( c ) 2014 - 2015 < >
*
* Permission to use , copy , modify , and 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 .
*
* Copyright (c) 2014-2015 David Sheets <>
*
* Permission to use, copy, modify, and 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.
*
*)
type t =
| E2BIG
| EACCES
| EADDRINUSE
| EADDRNOTAVAIL
| EAFNOSUPPORT
| EAGAIN
| EALREADY
| EBADF
| EBADMSG
| EBUSY
| ECANCELED
| ECHILD
| ECONNABORTED
| ECONNREFUSED
| ECONNRESET
| EDEADLK
| EDESTADDRREQ
| EDOM
| EDQUOT
| EEXIST
| EFAULT
| EFBIG
| EHOSTDOWN
| EHOSTUNREACH
| EIDRM
| EILSEQ
| EINPROGRESS
| EINTR
| EINVAL
| EIO
| EISCONN
| EISDIR
| ELOOP
| EMFILE
| EMLINK
| EMSGSIZE
| EMULTIHOP
| ENAMETOOLONG
| ENETDOWN
| ENETRESET
| ENETUNREACH
| ENFILE
| ENOBUFS
| ENODEV
| ENOENT
| ENOEXEC
| ENOLCK
| ENOLINK
| ENOMEM
| ENOMSG
| ENOPROTOOPT
| ENOSPC
| ENOSYS
| ENOTBLK
| ENOTCONN
| ENOTDIR
| ENOTEMPTY
| ENOTRECOVERABLE
| ENOTSOCK
| ENOTSUP
| ENOTTY
| ENXIO
| EOPNOTSUPP
| EOVERFLOW
| EOWNERDEAD
| EPERM
| EPFNOSUPPORT
| EPIPE
| EPROTO
| EPROTONOSUPPORT
| EPROTOTYPE
| ERANGE
| EREMOTE
| EROFS
| ESHUTDOWN
| ESOCKTNOSUPPORT
| ESPIPE
| ESRCH
| ESTALE
| ETIMEDOUT
| ETOOMANYREFS
| ETXTBSY
| EUSERS
| EWOULDBLOCK
| EXDEV
| ECHRNG
| EL2NSYNC
| EL3HLT
| EL3RST
| ELNRNG
| EUNATCH
| ENOCSI
| EL2HLT
| EBADE
| EBADR
| EXFULL
| ENOANO
| EBADRQC
| EBADSLT
| EBFONT
| ENONET
| ENOPKG
| EADV
| ESRMNT
| ECOMM
| EDOTDOT
| ENOTUNIQ
| EBADFD
| EREMCHG
| ELIBACC
| ELIBBAD
| ELIBSCN
| ELIBMAX
| ELIBEXEC
| ERESTART
| ESTRPIPE
| EUCLEAN
| ENOTNAM
| ENAVAIL
| EISNAM
| EREMOTEIO
| ENOMEDIUM
| EMEDIUMTYPE
| ENOKEY
| EKEYEXPIRED
| EKEYREVOKED
| EKEYREJECTED
| ERFKILL
| EHWPOISON
| EPWROFF
| EDEVERR
| EBADEXEC
| EBADARCH
| ESHLIBVERS
| EBADMACHO
| ENOPOLICY
| EQFULL
| EDOOFUS
| ENOTCAPABLE
| ECAPMODE
| EPROCLIM
| EBADRPC
| ERPCMISMATCH
| EPROGUNAVAIL
| EPROGMISMATCH
| EPROCUNAVAIL
| EFTYPE
| EAUTH
| ENEEDAUTH
| ENOATTR
| ENOSTR
| ENODATA
| ETIME
| ENOSR
| EUNKNOWNERR of Signed.sint
type error = {
errno : t list;
call : string;
label : string;
}
exception Error of error
(** NB: This module registers a printer for the [Error] exception. *)
type defns = {
e2big : Signed.sint option;
eacces : Signed.sint option;
eaddrinuse : Signed.sint option;
eaddrnotavail : Signed.sint option;
eafnosupport : Signed.sint option;
eagain : Signed.sint option;
ealready : Signed.sint option;
ebadf : Signed.sint option;
ebadmsg : Signed.sint option;
ebusy : Signed.sint option;
ecanceled : Signed.sint option;
echild : Signed.sint option;
econnaborted : Signed.sint option;
econnrefused : Signed.sint option;
econnreset : Signed.sint option;
edeadlk : Signed.sint option;
edestaddrreq : Signed.sint option;
edom : Signed.sint option;
edquot : Signed.sint option;
eexist : Signed.sint option;
efault : Signed.sint option;
efbig : Signed.sint option;
ehostdown : Signed.sint option;
ehostunreach : Signed.sint option;
eidrm : Signed.sint option;
eilseq : Signed.sint option;
einprogress : Signed.sint option;
eintr : Signed.sint option;
einval : Signed.sint option;
eio : Signed.sint option;
eisconn : Signed.sint option;
eisdir : Signed.sint option;
eloop : Signed.sint option;
emfile : Signed.sint option;
emlink : Signed.sint option;
emsgsize : Signed.sint option;
emultihop : Signed.sint option;
enametoolong : Signed.sint option;
enetdown : Signed.sint option;
enetreset : Signed.sint option;
enetunreach : Signed.sint option;
enfile : Signed.sint option;
enobufs : Signed.sint option;
enodev : Signed.sint option;
enoent : Signed.sint option;
enoexec : Signed.sint option;
enolck : Signed.sint option;
enolink : Signed.sint option;
enomem : Signed.sint option;
enomsg : Signed.sint option;
enoprotoopt : Signed.sint option;
enospc : Signed.sint option;
enosys : Signed.sint option;
enotblk : Signed.sint option;
enotconn : Signed.sint option;
enotdir : Signed.sint option;
enotempty : Signed.sint option;
enotrecoverable : Signed.sint option;
enotsock : Signed.sint option;
enotsup : Signed.sint option;
enotty : Signed.sint option;
enxio : Signed.sint option;
eopnotsupp : Signed.sint option;
eoverflow : Signed.sint option;
eownerdead : Signed.sint option;
eperm : Signed.sint option;
epfnosupport : Signed.sint option;
epipe : Signed.sint option;
eproto : Signed.sint option;
eprotonosupport : Signed.sint option;
eprototype : Signed.sint option;
erange : Signed.sint option;
eremote : Signed.sint option;
erofs : Signed.sint option;
eshutdown : Signed.sint option;
esocktnosupport : Signed.sint option;
espipe : Signed.sint option;
esrch : Signed.sint option;
estale : Signed.sint option;
etimedout : Signed.sint option;
etoomanyrefs : Signed.sint option;
etxtbsy : Signed.sint option;
eusers : Signed.sint option;
ewouldblock : Signed.sint option;
exdev : Signed.sint option;
echrng : Signed.sint option;
el2nsync : Signed.sint option;
el3hlt : Signed.sint option;
el3rst : Signed.sint option;
elnrng : Signed.sint option;
eunatch : Signed.sint option;
enocsi : Signed.sint option;
el2hlt : Signed.sint option;
ebade : Signed.sint option;
ebadr : Signed.sint option;
exfull : Signed.sint option;
enoano : Signed.sint option;
ebadrqc : Signed.sint option;
ebadslt : Signed.sint option;
ebfont : Signed.sint option;
enonet : Signed.sint option;
enopkg : Signed.sint option;
eadv : Signed.sint option;
esrmnt : Signed.sint option;
ecomm : Signed.sint option;
edotdot : Signed.sint option;
enotuniq : Signed.sint option;
ebadfd : Signed.sint option;
eremchg : Signed.sint option;
elibacc : Signed.sint option;
elibbad : Signed.sint option;
elibscn : Signed.sint option;
elibmax : Signed.sint option;
elibexec : Signed.sint option;
erestart : Signed.sint option;
estrpipe : Signed.sint option;
euclean : Signed.sint option;
enotnam : Signed.sint option;
enavail : Signed.sint option;
eisnam : Signed.sint option;
eremoteio : Signed.sint option;
enomedium : Signed.sint option;
emediumtype : Signed.sint option;
enokey : Signed.sint option;
ekeyexpired : Signed.sint option;
ekeyrevoked : Signed.sint option;
ekeyrejected : Signed.sint option;
erfkill : Signed.sint option;
ehwpoison : Signed.sint option;
epwroff : Signed.sint option;
edeverr : Signed.sint option;
ebadexec : Signed.sint option;
ebadarch : Signed.sint option;
eshlibvers : Signed.sint option;
ebadmacho : Signed.sint option;
enopolicy : Signed.sint option;
eqfull : Signed.sint option;
edoofus : Signed.sint option;
enotcapable : Signed.sint option;
ecapmode : Signed.sint option;
eproclim : Signed.sint option;
ebadrpc : Signed.sint option;
erpcmismatch : Signed.sint option;
eprogunavail : Signed.sint option;
eprogmismatch : Signed.sint option;
eprocunavail : Signed.sint option;
eftype : Signed.sint option;
eauth : Signed.sint option;
eneedauth : Signed.sint option;
enoattr : Signed.sint option;
enostr : Signed.sint option;
enodata : Signed.sint option;
etime : Signed.sint option;
enosr : Signed.sint option;
}
module Host : sig
type t
val of_defns : defns -> t
val to_defns : t -> defns
end
val to_code : host:Host.t -> t -> Signed.sint option
val of_code : host:Host.t -> Signed.sint -> t list
val to_string : t -> string
val iter_defns : defns -> (Signed.sint -> t -> unit) -> (t -> unit) -> unit
val string_of_defns : defns -> string
val defns_of_string : string -> defns
val check_errno : (unit -> 'a) -> ('a, error) Result.result
val string_of_error : error -> string
| null | https://raw.githubusercontent.com/dsheets/ocaml-unix-errno/0878418c45e25b5a1fb0a461ce8e55d67c5c42ab/lib/errno.mli | ocaml | * NB: This module registers a printer for the [Error] exception. |
* Copyright ( c ) 2014 - 2015 < >
*
* Permission to use , copy , modify , and 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 .
*
* Copyright (c) 2014-2015 David Sheets <>
*
* Permission to use, copy, modify, and 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.
*
*)
type t =
| E2BIG
| EACCES
| EADDRINUSE
| EADDRNOTAVAIL
| EAFNOSUPPORT
| EAGAIN
| EALREADY
| EBADF
| EBADMSG
| EBUSY
| ECANCELED
| ECHILD
| ECONNABORTED
| ECONNREFUSED
| ECONNRESET
| EDEADLK
| EDESTADDRREQ
| EDOM
| EDQUOT
| EEXIST
| EFAULT
| EFBIG
| EHOSTDOWN
| EHOSTUNREACH
| EIDRM
| EILSEQ
| EINPROGRESS
| EINTR
| EINVAL
| EIO
| EISCONN
| EISDIR
| ELOOP
| EMFILE
| EMLINK
| EMSGSIZE
| EMULTIHOP
| ENAMETOOLONG
| ENETDOWN
| ENETRESET
| ENETUNREACH
| ENFILE
| ENOBUFS
| ENODEV
| ENOENT
| ENOEXEC
| ENOLCK
| ENOLINK
| ENOMEM
| ENOMSG
| ENOPROTOOPT
| ENOSPC
| ENOSYS
| ENOTBLK
| ENOTCONN
| ENOTDIR
| ENOTEMPTY
| ENOTRECOVERABLE
| ENOTSOCK
| ENOTSUP
| ENOTTY
| ENXIO
| EOPNOTSUPP
| EOVERFLOW
| EOWNERDEAD
| EPERM
| EPFNOSUPPORT
| EPIPE
| EPROTO
| EPROTONOSUPPORT
| EPROTOTYPE
| ERANGE
| EREMOTE
| EROFS
| ESHUTDOWN
| ESOCKTNOSUPPORT
| ESPIPE
| ESRCH
| ESTALE
| ETIMEDOUT
| ETOOMANYREFS
| ETXTBSY
| EUSERS
| EWOULDBLOCK
| EXDEV
| ECHRNG
| EL2NSYNC
| EL3HLT
| EL3RST
| ELNRNG
| EUNATCH
| ENOCSI
| EL2HLT
| EBADE
| EBADR
| EXFULL
| ENOANO
| EBADRQC
| EBADSLT
| EBFONT
| ENONET
| ENOPKG
| EADV
| ESRMNT
| ECOMM
| EDOTDOT
| ENOTUNIQ
| EBADFD
| EREMCHG
| ELIBACC
| ELIBBAD
| ELIBSCN
| ELIBMAX
| ELIBEXEC
| ERESTART
| ESTRPIPE
| EUCLEAN
| ENOTNAM
| ENAVAIL
| EISNAM
| EREMOTEIO
| ENOMEDIUM
| EMEDIUMTYPE
| ENOKEY
| EKEYEXPIRED
| EKEYREVOKED
| EKEYREJECTED
| ERFKILL
| EHWPOISON
| EPWROFF
| EDEVERR
| EBADEXEC
| EBADARCH
| ESHLIBVERS
| EBADMACHO
| ENOPOLICY
| EQFULL
| EDOOFUS
| ENOTCAPABLE
| ECAPMODE
| EPROCLIM
| EBADRPC
| ERPCMISMATCH
| EPROGUNAVAIL
| EPROGMISMATCH
| EPROCUNAVAIL
| EFTYPE
| EAUTH
| ENEEDAUTH
| ENOATTR
| ENOSTR
| ENODATA
| ETIME
| ENOSR
| EUNKNOWNERR of Signed.sint
type error = {
errno : t list;
call : string;
label : string;
}
exception Error of error
type defns = {
e2big : Signed.sint option;
eacces : Signed.sint option;
eaddrinuse : Signed.sint option;
eaddrnotavail : Signed.sint option;
eafnosupport : Signed.sint option;
eagain : Signed.sint option;
ealready : Signed.sint option;
ebadf : Signed.sint option;
ebadmsg : Signed.sint option;
ebusy : Signed.sint option;
ecanceled : Signed.sint option;
echild : Signed.sint option;
econnaborted : Signed.sint option;
econnrefused : Signed.sint option;
econnreset : Signed.sint option;
edeadlk : Signed.sint option;
edestaddrreq : Signed.sint option;
edom : Signed.sint option;
edquot : Signed.sint option;
eexist : Signed.sint option;
efault : Signed.sint option;
efbig : Signed.sint option;
ehostdown : Signed.sint option;
ehostunreach : Signed.sint option;
eidrm : Signed.sint option;
eilseq : Signed.sint option;
einprogress : Signed.sint option;
eintr : Signed.sint option;
einval : Signed.sint option;
eio : Signed.sint option;
eisconn : Signed.sint option;
eisdir : Signed.sint option;
eloop : Signed.sint option;
emfile : Signed.sint option;
emlink : Signed.sint option;
emsgsize : Signed.sint option;
emultihop : Signed.sint option;
enametoolong : Signed.sint option;
enetdown : Signed.sint option;
enetreset : Signed.sint option;
enetunreach : Signed.sint option;
enfile : Signed.sint option;
enobufs : Signed.sint option;
enodev : Signed.sint option;
enoent : Signed.sint option;
enoexec : Signed.sint option;
enolck : Signed.sint option;
enolink : Signed.sint option;
enomem : Signed.sint option;
enomsg : Signed.sint option;
enoprotoopt : Signed.sint option;
enospc : Signed.sint option;
enosys : Signed.sint option;
enotblk : Signed.sint option;
enotconn : Signed.sint option;
enotdir : Signed.sint option;
enotempty : Signed.sint option;
enotrecoverable : Signed.sint option;
enotsock : Signed.sint option;
enotsup : Signed.sint option;
enotty : Signed.sint option;
enxio : Signed.sint option;
eopnotsupp : Signed.sint option;
eoverflow : Signed.sint option;
eownerdead : Signed.sint option;
eperm : Signed.sint option;
epfnosupport : Signed.sint option;
epipe : Signed.sint option;
eproto : Signed.sint option;
eprotonosupport : Signed.sint option;
eprototype : Signed.sint option;
erange : Signed.sint option;
eremote : Signed.sint option;
erofs : Signed.sint option;
eshutdown : Signed.sint option;
esocktnosupport : Signed.sint option;
espipe : Signed.sint option;
esrch : Signed.sint option;
estale : Signed.sint option;
etimedout : Signed.sint option;
etoomanyrefs : Signed.sint option;
etxtbsy : Signed.sint option;
eusers : Signed.sint option;
ewouldblock : Signed.sint option;
exdev : Signed.sint option;
echrng : Signed.sint option;
el2nsync : Signed.sint option;
el3hlt : Signed.sint option;
el3rst : Signed.sint option;
elnrng : Signed.sint option;
eunatch : Signed.sint option;
enocsi : Signed.sint option;
el2hlt : Signed.sint option;
ebade : Signed.sint option;
ebadr : Signed.sint option;
exfull : Signed.sint option;
enoano : Signed.sint option;
ebadrqc : Signed.sint option;
ebadslt : Signed.sint option;
ebfont : Signed.sint option;
enonet : Signed.sint option;
enopkg : Signed.sint option;
eadv : Signed.sint option;
esrmnt : Signed.sint option;
ecomm : Signed.sint option;
edotdot : Signed.sint option;
enotuniq : Signed.sint option;
ebadfd : Signed.sint option;
eremchg : Signed.sint option;
elibacc : Signed.sint option;
elibbad : Signed.sint option;
elibscn : Signed.sint option;
elibmax : Signed.sint option;
elibexec : Signed.sint option;
erestart : Signed.sint option;
estrpipe : Signed.sint option;
euclean : Signed.sint option;
enotnam : Signed.sint option;
enavail : Signed.sint option;
eisnam : Signed.sint option;
eremoteio : Signed.sint option;
enomedium : Signed.sint option;
emediumtype : Signed.sint option;
enokey : Signed.sint option;
ekeyexpired : Signed.sint option;
ekeyrevoked : Signed.sint option;
ekeyrejected : Signed.sint option;
erfkill : Signed.sint option;
ehwpoison : Signed.sint option;
epwroff : Signed.sint option;
edeverr : Signed.sint option;
ebadexec : Signed.sint option;
ebadarch : Signed.sint option;
eshlibvers : Signed.sint option;
ebadmacho : Signed.sint option;
enopolicy : Signed.sint option;
eqfull : Signed.sint option;
edoofus : Signed.sint option;
enotcapable : Signed.sint option;
ecapmode : Signed.sint option;
eproclim : Signed.sint option;
ebadrpc : Signed.sint option;
erpcmismatch : Signed.sint option;
eprogunavail : Signed.sint option;
eprogmismatch : Signed.sint option;
eprocunavail : Signed.sint option;
eftype : Signed.sint option;
eauth : Signed.sint option;
eneedauth : Signed.sint option;
enoattr : Signed.sint option;
enostr : Signed.sint option;
enodata : Signed.sint option;
etime : Signed.sint option;
enosr : Signed.sint option;
}
module Host : sig
type t
val of_defns : defns -> t
val to_defns : t -> defns
end
val to_code : host:Host.t -> t -> Signed.sint option
val of_code : host:Host.t -> Signed.sint -> t list
val to_string : t -> string
val iter_defns : defns -> (Signed.sint -> t -> unit) -> (t -> unit) -> unit
val string_of_defns : defns -> string
val defns_of_string : string -> defns
val check_errno : (unit -> 'a) -> ('a, error) Result.result
val string_of_error : error -> string
|
1a8b1a72797629e6f9dd9a01d6abf9a5286ce3ba9d6fe8fc66d3918c112c29c1 | earl-ducaine/cl-garnet | formulas.lisp | (setf garnetdraw::*DRAW-AGG*
(create-instance 'FORMULAS OPAL:AGGREGADGET
(:LEFT 0)
(:TOP 0)
(:WIDTH (o-formula (GVL :WINDOW :WIDTH) 680))
(:HEIGHT (o-formula (GVL :WINDOW :HEIGHT) 410))
(:CONSTANT `(:COMPONENTS ))
(:FUNCTION-FOR-OK NIL)
(:EXPORT-P T)
(:WINDOW-TITLE "FORMULAS FIGURE")
(:PACKAGE-NAME "USER")
(:WINDOW-HEIGHT 300)
(:WINDOW-WIDTH 450)
(:WINDOW-TOP 0)
(:WINDOW-LEFT 0)
(:parts `(
(NIL ,GARNETDRAW::MOVING-AGG
(:CONSTANT (:KNOWN-AS :COMPONENTS ))
(:OLD-HEIGHT 31)
(:OLD-WIDTH 130)
(:OLD-TOP 31)
(:OLD-LEFT 55)
(:parts (
(NIL ,OPAL:TEXT
(:LEFT ,(o-formula (FIRST (GVL :BOX)) 55))
(:TOP ,(o-formula (SECOND (GVL :BOX)) 40))
(:CONSTANT (:KNOWN-AS T ))
(:FRAC-HEIGHT 14)
(:FRAC-WIDTH 48)
(:FRAC-TOP 40)
(:FRAC-LEFT 55)
(:STRING "POINT-1")
(:BOX (55 40 3 3 ))
(:BEHAVIORS NIL)
(:GILT-REF "TYPE-TEXT"))
(NIL ,OPAL:CIRCLE
(:LEFT ,(o-formula (FIRST (GVL :BOX)) 109))
(:TOP ,(o-formula (SECOND (GVL :BOX)) 31))
(:WIDTH ,(o-formula (THIRD (GVL :BOX)) 30))
(:HEIGHT ,(o-formula (FOURTH (GVL :BOX)) 30))
(:CONSTANT (:KNOWN-AS T ))
(:FRAC-HEIGHT 30)
(:FRAC-WIDTH 30)
(:FRAC-TOP 31)
(:FRAC-LEFT 109)
(:GROW-P T)
(:BOX (109 31 30 30 ))
(:BEHAVIORS NIL)
(:GILT-REF "TYPE-RECTANGLE"))
(NIL ,OPAL:TEXT
(:LEFT ,(o-formula (FIRST (GVL :BOX)) 147))
(:TOP ,(o-formula (SECOND (GVL :BOX)) 31))
(:CONSTANT (:KNOWN-AS T ))
(:FRAC-HEIGHT 14)
(:FRAC-WIDTH 38)
(:FRAC-TOP 31)
(:FRAC-LEFT 147)
(:STRING ":y1 10")
(:BOX (147 31 38 14 ))
(:BEHAVIORS NIL)
(:GILT-REF "TYPE-TEXT"))
(NIL ,OPAL:TEXT
(:LEFT ,(o-formula (FIRST (GVL :BOX)) 147))
(:TOP ,(o-formula (SECOND (GVL :BOX)) 48))
(:CONSTANT (:KNOWN-AS T ))
(:FRAC-HEIGHT 14)
(:FRAC-WIDTH 38)
(:FRAC-TOP 48)
(:FRAC-LEFT 147)
(:STRING ":y2 40")
(:BOX (147 48 38 14 ))
(:BEHAVIORS NIL)
(:GILT-REF "TYPE-TEXT")))))
(NIL ,OPAL:TEXT
(:LEFT ,(o-formula (FIRST (GVL :BOX)) 26))
(:TOP ,(o-formula (SECOND (GVL :BOX)) 144))
(:CONSTANT (:KNOWN-AS T ))
(:TEMP-BOX (18 148 48 14 ))
(:DRAW-FUNCTION :COPY)
(:LINE-STYLE ,OPAL:DEFAULT-LINE-STYLE)
(:FRAC-HEIGHT 14)
(:FRAC-WIDTH 48)
(:FRAC-TOP 144)
(:FRAC-LEFT 26)
(:STRING "POINT-1")
(:BOX (26 144 48 14 ))
(:BEHAVIORS NIL)
(:GILT-REF "TYPE-TEXT"))
(NIL ,GARNETDRAW::MOVING-AGG
(:CONSTANT (:KNOWN-AS :COMPONENTS ))
(:BOX (22 160 76 31 ))
(:OLD-HEIGHT 31)
(:OLD-WIDTH 76)
(:OLD-TOP 160)
(:OLD-LEFT 22)
(:parts (
(NIL ,OPAL:CIRCLE
(:LEFT ,(o-formula (FIRST (GVL :BOX)) 22))
(:TOP ,(o-formula (SECOND (GVL :BOX)) 160))
(:WIDTH ,(o-formula (THIRD (GVL :BOX)) 30))
(:HEIGHT ,(o-formula (FOURTH (GVL :BOX)) 30))
(:CONSTANT (:KNOWN-AS T ))
(:TEMP-BOX (22 160 30 30 ))
(:DRAW-FUNCTION :COPY)
(:LINE-STYLE ,OPAL:DEFAULT-LINE-STYLE)
(:FRAC-HEIGHT 30)
(:FRAC-WIDTH 30)
(:FRAC-TOP 160)
(:FRAC-LEFT 22)
(:GROW-P T)
(:BOX (22 160 30 30 ))
(:BEHAVIORS NIL)
(:GILT-REF "TYPE-RECTANGLE"))
(NIL ,OPAL:TEXT
(:LEFT ,(o-formula (FIRST (GVL :BOX)) 60))
(:TOP ,(o-formula (SECOND (GVL :BOX)) 160))
(:CONSTANT (:KNOWN-AS T ))
(:TEMP-BOX (60 160 38 14 ))
(:DRAW-FUNCTION :COPY)
(:LINE-STYLE ,OPAL:DEFAULT-LINE-STYLE)
(:FRAC-HEIGHT 14)
(:FRAC-WIDTH 38)
(:FRAC-TOP 160)
(:FRAC-LEFT 60)
(:STRING ":y1 10")
(:BOX (60 160 38 14 ))
(:BEHAVIORS NIL)
(:GILT-REF "TYPE-TEXT"))
(NIL ,OPAL:TEXT
(:LEFT ,(o-formula (FIRST (GVL :BOX)) 60))
(:TOP ,(o-formula (SECOND (GVL :BOX)) 177))
(:CONSTANT (:KNOWN-AS T ))
(:TEMP-BOX (60 177 38 14 ))
(:DRAW-FUNCTION :COPY)
(:LINE-STYLE ,OPAL:DEFAULT-LINE-STYLE)
(:FRAC-HEIGHT 14)
(:FRAC-WIDTH 38)
(:FRAC-TOP 177)
(:FRAC-LEFT 60)
(:STRING ":y2 40")
(:BOX (60 177 38 14 ))
(:BEHAVIORS NIL)
(:GILT-REF "TYPE-TEXT")))))
(NIL ,GARNETDRAW::MOVING-AGG
(:CONSTANT (:KNOWN-AS :COMPONENTS ))
(:HEY 0)
(:BOX (22 216 118 37 ))
(:OLD-HEIGHT 37)
(:OLD-WIDTH 125)
(:OLD-TOP 216)
(:OLD-LEFT 22)
(:parts (
(NIL ,OPAL:CIRCLE
(:LEFT ,(o-formula (FIRST (GVL :BOX)) 22))
(:TOP ,(o-formula (SECOND (GVL :BOX)) 217))
(:WIDTH ,(o-formula (THIRD (GVL :BOX)) 30))
(:HEIGHT ,(o-formula (FOURTH (GVL :BOX)) 30))
(:CONSTANT (:KNOWN-AS T ))
(:TEMP-BOX (22 217 30 30 ))
(:FRAC-HEIGHT 30)
(:FRAC-WIDTH 30)
(:FRAC-TOP 217)
(:FRAC-LEFT 22)
(:GROW-P T)
(:BOX (22 217 30 30 ))
(:BEHAVIORS NIL)
(:GILT-REF "TYPE-RECTANGLE"))
(NIL ,OPAL:TEXT
(:LEFT ,(o-formula (FIRST (GVL :BOX)) 56))
(:TOP ,(o-formula (SECOND (GVL :BOX)) 226))
(:CONSTANT (:KNOWN-AS T ))
(:TEMP-BOX (56 226 11 14 ))
(:FRAC-HEIGHT 14)
(:FRAC-WIDTH 11)
(:FRAC-TOP 226)
(:FRAC-LEFT 56)
(:STRING ":y")
(:BOX (56 226 11 14 ))
(:BEHAVIORS NIL)
(:GILT-REF "TYPE-TEXT"))
(NIL ,OPAL:TEXT
(:LEFT ,(o-formula (FIRST (GVL :BOX)) 78))
(:TOP ,(o-formula (SECOND (GVL :BOX)) 216))
(:CONSTANT (:KNOWN-AS T ))
(:TEMP-BOX (78 216 61 14 ))
(:FRAC-HEIGHT 14)
(:FRAC-WIDTH 61)
(:FRAC-TOP 216)
(:FRAC-LEFT 78)
(:STRING "CACHED 25")
(:BOX (78 216 61 14 ))
(:BEHAVIORS NIL)
(:GILT-REF "TYPE-TEXT"))
(NIL ,OPAL:TEXT
(:LEFT ,(o-formula (FIRST (GVL :BOX)) 78))
(:TOP ,(o-formula (SECOND (GVL :BOX)) 239))
(:CONSTANT (:KNOWN-AS T ))
(:TEMP-BOX (78 239 62 14 ))
(:FRAC-HEIGHT 14)
(:FRAC-WIDTH 62)
(:FRAC-TOP 239)
(:FRAC-LEFT 78)
(:STRING "VALID yes")
(:BOX (78 239 62 14 ))
(:BEHAVIORS NIL)
(:GILT-REF "TYPE-TEXT"))
(NIL ,OPAL:LINE
(:CONSTANT (:KNOWN-AS T ))
(:TEMP-POINTS (68 233 8 6 ))
(:FRAC-Y2 239)
(:FRAC-X2 76)
(:FRAC-Y1 233)
(:FRAC-X1 68)
(:Y2 ,(o-formula (FOURTH (GVL :POINTS)) 239))
(:X2 ,(o-formula (THIRD (GVL :POINTS)) 76))
(:Y1 ,(o-formula (SECOND (GVL :POINTS)) 233))
(:X1 ,(o-formula (FIRST (GVL :POINTS)) 68))
(:GROW-P T)
(:LINE-P T)
(:POINTS (68 233 76 239 ))
(:BEHAVIORS NIL)
(:GILT-REF "TYPE-LINE"))
(NIL ,OPAL:LINE
(:CONSTANT (:KNOWN-AS T ))
(:TEMP-POINTS (68 233 8 -6 ))
(:FRAC-Y2 227)
(:FRAC-X2 76)
(:FRAC-Y1 233)
(:FRAC-X1 68)
(:Y2 ,(o-formula (FOURTH (GVL :POINTS)) 227))
(:X2 ,(o-formula (THIRD (GVL :POINTS)) 76))
(:Y1 ,(o-formula (SECOND (GVL :POINTS)) 233))
(:X1 ,(o-formula (FIRST (GVL :POINTS)) 68))
(:GROW-P T)
(:LINE-P T)
(:POINTS (68 233 76 227 ))
(:BEHAVIORS NIL)
(:GILT-REF "TYPE-LINE")))))
(NIL ,GARNETDRAW::MOVING-AGG
(:CONSTANT (:KNOWN-AS :COMPONENTS ))
(:BOX (298 216 118 37 ))
(:OLD-HEIGHT 37)
(:OLD-WIDTH 118)
(:OLD-TOP 216)
(:OLD-LEFT 298)
(:parts (
(NIL ,OPAL:CIRCLE
(:LEFT ,(o-formula (FIRST (GVL :BOX)) 298))
(:TOP ,(o-formula (SECOND (GVL :BOX)) 217))
(:WIDTH ,(o-formula (THIRD (GVL :BOX)) 30))
(:HEIGHT ,(o-formula (FOURTH (GVL :BOX)) 30))
(:CONSTANT (:KNOWN-AS T ))
(:TEMP-BOX (298 217 30 30 ))
(:DRAW-FUNCTION :COPY)
(:LINE-STYLE ,OPAL:DEFAULT-LINE-STYLE)
(:FRAC-HEIGHT 30)
(:FRAC-WIDTH 30)
(:FRAC-TOP 217)
(:FRAC-LEFT 298)
(:GROW-P T)
(:BOX (298 217 30 30 ))
(:BEHAVIORS NIL)
(:GILT-REF "TYPE-RECTANGLE"))
(NIL ,OPAL:TEXT
(:LEFT ,(o-formula (FIRST (GVL :BOX)) 332))
(:TOP ,(o-formula (SECOND (GVL :BOX)) 226))
(:CONSTANT (:KNOWN-AS T ))
(:TEMP-BOX (332 226 11 14 ))
(:DRAW-FUNCTION :COPY)
(:LINE-STYLE ,OPAL:DEFAULT-LINE-STYLE)
(:FRAC-HEIGHT 14)
(:FRAC-WIDTH 11)
(:FRAC-TOP 226)
(:FRAC-LEFT 332)
(:STRING ":y")
(:BOX (332 226 11 14 ))
(:BEHAVIORS NIL)
(:GILT-REF "TYPE-TEXT"))
(NIL ,OPAL:TEXT
(:LEFT ,(o-formula (FIRST (GVL :BOX)) 354))
(:TOP ,(o-formula (SECOND (GVL :BOX)) 216))
(:CONSTANT (:KNOWN-AS T ))
(:TEMP-BOX (354 216 61 14 ))
(:DRAW-FUNCTION :COPY)
(:LINE-STYLE ,OPAL:DEFAULT-LINE-STYLE)
(:FRAC-HEIGHT 14)
(:FRAC-WIDTH 61)
(:FRAC-TOP 216)
(:FRAC-LEFT 354)
(:STRING "CACHED 25")
(:BOX (354 216 61 14 ))
(:BEHAVIORS NIL)
(:GILT-REF "TYPE-TEXT"))
(NIL ,OPAL:TEXT
(:LEFT ,(o-formula (FIRST (GVL :BOX)) 354))
(:TOP ,(o-formula (SECOND (GVL :BOX)) 239))
(:CONSTANT (:KNOWN-AS T ))
(:TEMP-BOX (354 239 62 14 ))
(:DRAW-FUNCTION :COPY)
(:LINE-STYLE ,OPAL:DEFAULT-LINE-STYLE)
(:FRAC-HEIGHT 14)
(:FRAC-WIDTH 62)
(:FRAC-TOP 239)
(:FRAC-LEFT 354)
(:STRING "VALID no")
(:BOX (354 239 62 14 ))
(:BEHAVIORS NIL)
(:GILT-REF "TYPE-TEXT"))
(NIL ,OPAL:LINE
(:CONSTANT (:KNOWN-AS T ))
(:TEMP-POINTS (344 233 8 6 ))
(:DRAW-FUNCTION :COPY)
(:LINE-STYLE ,OPAL:DEFAULT-LINE-STYLE)
(:FRAC-Y2 239)
(:FRAC-X2 352)
(:FRAC-Y1 233)
(:FRAC-X1 344)
(:Y2 ,(o-formula (FOURTH (GVL :POINTS)) 239))
(:X2 ,(o-formula (THIRD (GVL :POINTS)) 352))
(:Y1 ,(o-formula (SECOND (GVL :POINTS)) 233))
(:X1 ,(o-formula (FIRST (GVL :POINTS)) 344))
(:GROW-P T)
(:LINE-P T)
(:POINTS (344 233 352 239 ))
(:BEHAVIORS NIL)
(:GILT-REF "TYPE-LINE"))
(NIL ,OPAL:LINE
(:CONSTANT (:KNOWN-AS T ))
(:TEMP-POINTS (344 233 8 -6 ))
(:DRAW-FUNCTION :COPY)
(:LINE-STYLE ,OPAL:DEFAULT-LINE-STYLE)
(:FRAC-Y2 227)
(:FRAC-X2 352)
(:FRAC-Y1 233)
(:FRAC-X1 344)
(:Y2 ,(o-formula (FOURTH (GVL :POINTS)) 227))
(:X2 ,(o-formula (THIRD (GVL :POINTS)) 352))
(:Y1 ,(o-formula (SECOND (GVL :POINTS)) 233))
(:X1 ,(o-formula (FIRST (GVL :POINTS)) 344))
(:GROW-P T)
(:LINE-P T)
(:POINTS (344 233 352 227 ))
(:BEHAVIORS NIL)
(:GILT-REF "TYPE-LINE")))))
(NIL ,GARNETDRAW::MOVING-AGG
(:CONSTANT (:KNOWN-AS :COMPONENTS ))
(:BOX (436 160 76 31 ))
(:OLD-HEIGHT 31)
(:OLD-WIDTH 76)
(:OLD-TOP 160)
(:OLD-LEFT 436)
(:parts (
(NIL ,OPAL:CIRCLE
(:LEFT ,(o-formula (FIRST (GVL :BOX)) 436))
(:TOP ,(o-formula (SECOND (GVL :BOX)) 160))
(:WIDTH ,(o-formula (THIRD (GVL :BOX)) 30))
(:HEIGHT ,(o-formula (FOURTH (GVL :BOX)) 30))
(:CONSTANT (:KNOWN-AS T ))
(:TEMP-BOX (436 160 30 30 ))
(:DRAW-FUNCTION :COPY)
(:LINE-STYLE ,OPAL:DEFAULT-LINE-STYLE)
(:FRAC-HEIGHT 30)
(:FRAC-WIDTH 30)
(:FRAC-TOP 160)
(:FRAC-LEFT 436)
(:GROW-P T)
(:BOX (436 160 30 30 ))
(:BEHAVIORS NIL)
(:GILT-REF "TYPE-RECTANGLE"))
(NIL ,OPAL:TEXT
(:LEFT ,(o-formula (FIRST (GVL :BOX)) 474))
(:TOP ,(o-formula (SECOND (GVL :BOX)) 160))
(:CONSTANT (:KNOWN-AS T ))
(:TEMP-BOX (474 160 38 14 ))
(:DRAW-FUNCTION :COPY)
(:LINE-STYLE ,OPAL:DEFAULT-LINE-STYLE)
(:FRAC-HEIGHT 14)
(:FRAC-WIDTH 38)
(:FRAC-TOP 160)
(:FRAC-LEFT 474)
(:STRING ":y1 0")
(:BOX (474 160 38 14 ))
(:BEHAVIORS NIL)
(:GILT-REF "TYPE-TEXT"))
(NIL ,OPAL:TEXT
(:LEFT ,(o-formula (FIRST (GVL :BOX)) 474))
(:TOP ,(o-formula (SECOND (GVL :BOX)) 177))
(:CONSTANT (:KNOWN-AS T ))
(:TEMP-BOX (474 177 38 14 ))
(:DRAW-FUNCTION :COPY)
(:LINE-STYLE ,OPAL:DEFAULT-LINE-STYLE)
(:FRAC-HEIGHT 14)
(:FRAC-WIDTH 38)
(:FRAC-TOP 177)
(:FRAC-LEFT 474)
(:STRING ":y2 60")
(:BOX (474 177 38 14 ))
(:BEHAVIORS NIL)
(:GILT-REF "TYPE-TEXT")))))
(NIL ,OPAL:TEXT
(:LEFT ,(o-formula (FIRST (GVL :BOX)) 26))
(:TOP ,(o-formula (SECOND (GVL :BOX)) 200))
(:CONSTANT (:KNOWN-AS ))
(:FRAC-HEIGHT 14)
(:FRAC-WIDTH 48)
(:FRAC-TOP 200)
(:FRAC-LEFT 26)
(:BOX (26 200 48 14 ))
(:STRING "POINT-2")
(:TEXT-P T)
(:FONT ,OPAL:DEFAULT-FONT)
(:LINE-STYLE ,OPAL:DEFAULT-LINE-STYLE))
(NIL ,GARNETDRAW::MOVING-AGG
(:CONSTANT (:KNOWN-AS :COMPONENTS ))
(:OLD-HEIGHT 44)
(:OLD-WIDTH 133)
(:OLD-TOP 213)
(:OLD-LEFT 436)
(:BOX (436 213 133 44 ))
(:parts (
(NIL ,OPAL:CIRCLE
(:LEFT ,(o-formula (FIRST (GVL :BOX)) 436))
(:TOP ,(o-formula (SECOND (GVL :BOX)) 217))
(:WIDTH ,(o-formula (THIRD (GVL :BOX)) 30))
(:HEIGHT ,(o-formula (FOURTH (GVL :BOX)) 30))
(:CONSTANT (:KNOWN-AS T ))
(:TEMP-BOX (436 217 30 30 ))
(:DRAW-FUNCTION :COPY)
(:LINE-STYLE ,OPAL:DEFAULT-LINE-STYLE)
(:FRAC-HEIGHT 30)
(:FRAC-WIDTH 30)
(:FRAC-TOP 217)
(:FRAC-LEFT 436)
(:GROW-P T)
(:BOX (436 217 30 30 ))
(:BEHAVIORS NIL)
(:GILT-REF "TYPE-RECTANGLE"))
(NIL ,OPAL:TEXT
(:LEFT ,(o-formula (FIRST (GVL :BOX)) 470))
(:TOP ,(o-formula (SECOND (GVL :BOX)) 226))
(:CONSTANT (:KNOWN-AS T ))
(:TEMP-BOX (470 226 11 14 ))
(:DRAW-FUNCTION :COPY)
(:LINE-STYLE ,OPAL:DEFAULT-LINE-STYLE)
(:FRAC-HEIGHT 14)
(:FRAC-WIDTH 11)
(:FRAC-TOP 226)
(:FRAC-LEFT 470)
(:STRING ":y")
(:BOX (470 226 11 14 ))
(:BEHAVIORS NIL)
(:GILT-REF "TYPE-TEXT"))
(NIL ,OPAL:TEXT
(:LEFT ,(o-formula (FIRST (GVL :BOX)) 492))
(:TOP ,(o-formula (SECOND (GVL :BOX)) 216))
(:CONSTANT (:KNOWN-AS T ))
(:TEMP-BOX (492 216 61 14 ))
(:DRAW-FUNCTION :COPY)
(:LINE-STYLE ,OPAL:DEFAULT-LINE-STYLE)
(:FRAC-HEIGHT 14)
(:FRAC-WIDTH 61)
(:FRAC-TOP 216)
(:FRAC-LEFT 492)
(:STRING "CACHED 30")
(:BOX (492 216 61 14 ))
(:BEHAVIORS NIL)
(:GILT-REF "TYPE-TEXT"))
(NIL ,OPAL:TEXT
(:LEFT ,(o-formula (FIRST (GVL :BOX)) 492))
(:TOP ,(o-formula (SECOND (GVL :BOX)) 239))
(:CONSTANT (:KNOWN-AS T ))
(:TEMP-BOX (492 239 62 14 ))
(:DRAW-FUNCTION :COPY)
(:LINE-STYLE ,OPAL:DEFAULT-LINE-STYLE)
(:FRAC-HEIGHT 14)
(:FRAC-WIDTH 62)
(:FRAC-TOP 239)
(:FRAC-LEFT 492)
(:STRING "VALID yes")
(:BOX (492 239 62 14 ))
(:BEHAVIORS NIL)
(:GILT-REF "TYPE-TEXT"))
(NIL ,OPAL:LINE
(:CONSTANT (:KNOWN-AS T ))
(:TEMP-POINTS (482 233 8 6 ))
(:DRAW-FUNCTION :COPY)
(:LINE-STYLE ,OPAL:DEFAULT-LINE-STYLE)
(:FRAC-Y2 239)
(:FRAC-X2 490)
(:FRAC-Y1 233)
(:FRAC-X1 482)
(:Y2 ,(o-formula (FOURTH (GVL :POINTS)) 239))
(:X2 ,(o-formula (THIRD (GVL :POINTS)) 490))
(:Y1 ,(o-formula (SECOND (GVL :POINTS)) 233))
(:X1 ,(o-formula (FIRST (GVL :POINTS)) 482))
(:GROW-P T)
(:LINE-P T)
(:POINTS (482 233 490 239 ))
(:BEHAVIORS NIL)
(:GILT-REF "TYPE-LINE"))
(NIL ,OPAL:LINE
(:CONSTANT (:KNOWN-AS T ))
(:TEMP-POINTS (482 233 8 -6 ))
(:DRAW-FUNCTION :COPY)
(:LINE-STYLE ,OPAL:DEFAULT-LINE-STYLE)
(:FRAC-Y2 227)
(:FRAC-X2 490)
(:FRAC-Y1 233)
(:FRAC-X1 482)
(:Y2 ,(o-formula (FOURTH (GVL :POINTS)) 227))
(:X2 ,(o-formula (THIRD (GVL :POINTS)) 490))
(:Y1 ,(o-formula (SECOND (GVL :POINTS)) 233))
(:X1 ,(o-formula (FIRST (GVL :POINTS)) 482))
(:GROW-P T)
(:LINE-P T)
(:POINTS (482 233 490 227 ))
(:BEHAVIORS NIL)
(:GILT-REF "TYPE-LINE"))
(NIL ,GARNETDRAW::MOVING-RECT
(:CONSTANT (:KNOWN-AS ))
(:LINE-STYLE ,(create-instance nil OPAL:LINE-STYLE
(:FOREGROUND-COLOR (create-instance nil OPAL:COLOR
(:BLUE 0)
(:GREEN 0)
(:RED 0)))))
(:FILLING-STYLE NIL)
(:DRAW-FUNCTION :COPY)
(:BOX (535 238 34 19 ))
(:FRAC-LEFT 535)
(:FRAC-TOP 238)
(:FRAC-WIDTH 34)
(:FRAC-HEIGHT 19)
(:BEHAVIORS NIL)
(:TEMP-BOX (535 238 34 19 )))
(NIL ,GARNETDRAW::MOVING-RECT
(:CONSTANT (:KNOWN-AS ))
(:LINE-STYLE ,(create-instance nil OPAL:LINE-STYLE
(:FOREGROUND-COLOR (create-instance nil OPAL:COLOR
(:BLUE 0)
(:GREEN 0)
(:RED 0)))))
(:FILLING-STYLE NIL)
(:DRAW-FUNCTION :COPY)
(:BOX (535 213 34 19 ))
(:FRAC-LEFT 535)
(:FRAC-TOP 213)
(:FRAC-WIDTH 34)
(:FRAC-HEIGHT 19)
(:BEHAVIORS NIL)
(:TEMP-BOX (535 213 34 19 ))))))
(NIL ,GARNETDRAW::MOVING-AGG
(:CONSTANT (:KNOWN-AS :COMPONENTS ))
(:OLD-HEIGHT 40)
(:OLD-WIDTH 129)
(:OLD-TOP 216)
(:OLD-LEFT 160)
(:BOX (160 216 129 40 ))
(:parts (
(NIL ,OPAL:CIRCLE
(:LEFT ,(o-formula (FIRST (GVL :BOX)) 160))
(:TOP ,(o-formula (SECOND (GVL :BOX)) 217))
(:WIDTH ,(o-formula (THIRD (GVL :BOX)) 30))
(:HEIGHT ,(o-formula (FOURTH (GVL :BOX)) 30))
(:CONSTANT (:KNOWN-AS T ))
(:TEMP-BOX (160 217 30 30 ))
(:DRAW-FUNCTION :COPY)
(:LINE-STYLE ,OPAL:DEFAULT-LINE-STYLE)
(:FRAC-HEIGHT 30)
(:FRAC-WIDTH 30)
(:FRAC-TOP 217)
(:FRAC-LEFT 160)
(:GROW-P T)
(:BOX (160 217 30 30 ))
(:BEHAVIORS NIL)
(:GILT-REF "TYPE-RECTANGLE"))
(NIL ,OPAL:TEXT
(:LEFT ,(o-formula (FIRST (GVL :BOX)) 194))
(:TOP ,(o-formula (SECOND (GVL :BOX)) 226))
(:CONSTANT (:KNOWN-AS T ))
(:TEMP-BOX (194 226 11 14 ))
(:DRAW-FUNCTION :COPY)
(:LINE-STYLE ,OPAL:DEFAULT-LINE-STYLE)
(:FRAC-HEIGHT 14)
(:FRAC-WIDTH 11)
(:FRAC-TOP 226)
(:FRAC-LEFT 194)
(:STRING ":y")
(:BOX (194 226 11 14 ))
(:BEHAVIORS NIL)
(:GILT-REF "TYPE-TEXT"))
(NIL ,OPAL:TEXT
(:LEFT ,(o-formula (FIRST (GVL :BOX)) 216))
(:TOP ,(o-formula (SECOND (GVL :BOX)) 216))
(:CONSTANT (:KNOWN-AS T ))
(:TEMP-BOX (216 216 61 14 ))
(:DRAW-FUNCTION :COPY)
(:LINE-STYLE ,OPAL:DEFAULT-LINE-STYLE)
(:FRAC-HEIGHT 14)
(:FRAC-WIDTH 61)
(:FRAC-TOP 216)
(:FRAC-LEFT 216)
(:STRING "CACHED 25")
(:BOX (216 216 61 14 ))
(:BEHAVIORS NIL)
(:GILT-REF "TYPE-TEXT"))
(NIL ,OPAL:TEXT
(:LEFT ,(o-formula (FIRST (GVL :BOX)) 216))
(:TOP ,(o-formula (SECOND (GVL :BOX)) 239))
(:CONSTANT (:KNOWN-AS T ))
(:TEMP-BOX (216 239 62 14 ))
(:DRAW-FUNCTION :COPY)
(:LINE-STYLE ,OPAL:DEFAULT-LINE-STYLE)
(:FRAC-HEIGHT 14)
(:FRAC-WIDTH 62)
(:FRAC-TOP 239)
(:FRAC-LEFT 216)
(:STRING "VALID no")
(:BOX (216 239 62 14 ))
(:BEHAVIORS NIL)
(:GILT-REF "TYPE-TEXT"))
(NIL ,OPAL:LINE
(:CONSTANT (:KNOWN-AS T ))
(:TEMP-POINTS (206 233 8 6 ))
(:DRAW-FUNCTION :COPY)
(:LINE-STYLE ,OPAL:DEFAULT-LINE-STYLE)
(:FRAC-Y2 239)
(:FRAC-X2 214)
(:FRAC-Y1 233)
(:FRAC-X1 206)
(:Y2 ,(o-formula (FOURTH (GVL :POINTS)) 239))
(:X2 ,(o-formula (THIRD (GVL :POINTS)) 214))
(:Y1 ,(o-formula (SECOND (GVL :POINTS)) 233))
(:X1 ,(o-formula (FIRST (GVL :POINTS)) 206))
(:GROW-P T)
(:LINE-P T)
(:POINTS (206 233 214 239 ))
(:BEHAVIORS NIL)
(:GILT-REF "TYPE-LINE"))
(NIL ,OPAL:LINE
(:CONSTANT (:KNOWN-AS T ))
(:TEMP-POINTS (206 233 8 -6 ))
(:DRAW-FUNCTION :COPY)
(:LINE-STYLE ,OPAL:DEFAULT-LINE-STYLE)
(:FRAC-Y2 227)
(:FRAC-X2 214)
(:FRAC-Y1 233)
(:FRAC-X1 206)
(:Y2 ,(o-formula (FOURTH (GVL :POINTS)) 227))
(:X2 ,(o-formula (THIRD (GVL :POINTS)) 214))
(:Y1 ,(o-formula (SECOND (GVL :POINTS)) 233))
(:X1 ,(o-formula (FIRST (GVL :POINTS)) 206))
(:GROW-P T)
(:LINE-P T)
(:POINTS (206 233 214 227 ))
(:BEHAVIORS NIL)
(:GILT-REF "TYPE-LINE"))
(NIL ,GARNETDRAW::MOVING-RECT
(:CONSTANT (:KNOWN-AS ))
(:LINE-STYLE ,(create-instance nil OPAL:LINE-STYLE
(:FOREGROUND-COLOR (create-instance nil OPAL:COLOR
(:BLUE 0)
(:GREEN 0)
(:RED 0)))))
(:FILLING-STYLE NIL)
(:DRAW-FUNCTION :COPY)
(:BOX (255 237 34 19 ))
(:FRAC-LEFT 255)
(:FRAC-TOP 237)
(:FRAC-WIDTH 34)
(:FRAC-HEIGHT 19)
(:BEHAVIORS NIL)
(:TEMP-BOX (255 237 34 19 ))))))
(NIL ,GARNETDRAW::MOVING-AGG
(:CONSTANT (:KNOWN-AS :COMPONENTS ))
(:OLD-HEIGHT 33)
(:OLD-WIDTH 80)
(:OLD-TOP 158)
(:OLD-LEFT 160)
(:parts (
(NIL ,OPAL:CIRCLE
(:LEFT ,(o-formula (FIRST (GVL :BOX)) 160))
(:TOP ,(o-formula (SECOND (GVL :BOX)) 160))
(:WIDTH ,(o-formula (THIRD (GVL :BOX)) 30))
(:HEIGHT ,(o-formula (FOURTH (GVL :BOX)) 30))
(:CONSTANT (:KNOWN-AS T ))
(:TEMP-BOX (160 160 30 30 ))
(:DRAW-FUNCTION :COPY)
(:LINE-STYLE ,OPAL:DEFAULT-LINE-STYLE)
(:FRAC-HEIGHT 30)
(:FRAC-WIDTH 30)
(:FRAC-TOP 160)
(:FRAC-LEFT 160)
(:GROW-P T)
(:BOX (160 160 30 30 ))
(:BEHAVIORS NIL)
(:GILT-REF "TYPE-RECTANGLE"))
(NIL ,OPAL:TEXT
(:LEFT ,(o-formula (FIRST (GVL :BOX)) 198))
(:TOP ,(o-formula (SECOND (GVL :BOX)) 160))
(:CONSTANT (:KNOWN-AS T ))
(:TEMP-BOX (198 160 38 14 ))
(:DRAW-FUNCTION :COPY)
(:LINE-STYLE ,OPAL:DEFAULT-LINE-STYLE)
(:FRAC-HEIGHT 14)
(:FRAC-WIDTH 38)
(:FRAC-TOP 160)
(:FRAC-LEFT 198)
(:STRING ":y1 0")
(:BOX (198 160 38 14 ))
(:BEHAVIORS NIL)
(:GILT-REF "TYPE-TEXT"))
(NIL ,OPAL:TEXT
(:LEFT ,(o-formula (FIRST (GVL :BOX)) 198))
(:TOP ,(o-formula (SECOND (GVL :BOX)) 177))
(:CONSTANT (:KNOWN-AS T ))
(:TEMP-BOX (198 177 38 14 ))
(:DRAW-FUNCTION :COPY)
(:LINE-STYLE ,OPAL:DEFAULT-LINE-STYLE)
(:FRAC-HEIGHT 14)
(:FRAC-WIDTH 38)
(:FRAC-TOP 177)
(:FRAC-LEFT 198)
(:STRING ":y2 40")
(:BOX (198 177 38 14 ))
(:BEHAVIORS NIL)
(:GILT-REF "TYPE-TEXT"))
(NIL ,GARNETDRAW::MOVING-RECT
(:CONSTANT (:KNOWN-AS ))
(:LINE-STYLE ,(create-instance nil OPAL:LINE-STYLE
(:FOREGROUND-COLOR (create-instance nil OPAL:COLOR
(:BLUE 0)
(:GREEN 0)
(:RED 0)))))
(:FILLING-STYLE NIL)
(:DRAW-FUNCTION :COPY)
(:BOX (193 158 47 19 ))
(:FRAC-LEFT 193)
(:FRAC-TOP 158)
(:FRAC-WIDTH 47)
(:FRAC-HEIGHT 19)))))
(NIL ,GARNETDRAW::MOVING-AGG
(:CONSTANT (:KNOWN-AS :COMPONENTS ))
(:OLD-HEIGHT 33)
(:OLD-WIDTH 81)
(:OLD-TOP 160)
(:OLD-LEFT 298)
(:parts (
(NIL ,OPAL:CIRCLE
(:LEFT ,(o-formula (FIRST (GVL :BOX)) 298))
(:TOP ,(o-formula (SECOND (GVL :BOX)) 160))
(:WIDTH ,(o-formula (THIRD (GVL :BOX)) 30))
(:HEIGHT ,(o-formula (FOURTH (GVL :BOX)) 30))
(:CONSTANT (:KNOWN-AS T ))
(:TEMP-BOX (298 160 30 30 ))
(:DRAW-FUNCTION :COPY)
(:LINE-STYLE ,OPAL:DEFAULT-LINE-STYLE)
(:FRAC-HEIGHT 30)
(:FRAC-WIDTH 30)
(:FRAC-TOP 160)
(:FRAC-LEFT 298)
(:GROW-P T)
(:BOX (298 160 30 30 ))
(:BEHAVIORS NIL)
(:GILT-REF "TYPE-RECTANGLE"))
(NIL ,OPAL:TEXT
(:LEFT ,(o-formula (FIRST (GVL :BOX)) 336))
(:TOP ,(o-formula (SECOND (GVL :BOX)) 160))
(:CONSTANT (:KNOWN-AS T ))
(:TEMP-BOX (336 160 38 14 ))
(:DRAW-FUNCTION :COPY)
(:LINE-STYLE ,OPAL:DEFAULT-LINE-STYLE)
(:FRAC-HEIGHT 14)
(:FRAC-WIDTH 38)
(:FRAC-TOP 160)
(:FRAC-LEFT 336)
(:STRING ":y1 0")
(:BOX (336 160 38 14 ))
(:BEHAVIORS NIL)
(:GILT-REF "TYPE-TEXT"))
(NIL ,OPAL:TEXT
(:LEFT ,(o-formula (FIRST (GVL :BOX)) 336))
(:TOP ,(o-formula (SECOND (GVL :BOX)) 177))
(:CONSTANT (:KNOWN-AS T ))
(:TEMP-BOX (336 177 38 14 ))
(:DRAW-FUNCTION :COPY)
(:LINE-STYLE ,OPAL:DEFAULT-LINE-STYLE)
(:FRAC-HEIGHT 14)
(:FRAC-WIDTH 38)
(:FRAC-TOP 177)
(:FRAC-LEFT 336)
(:STRING ":y2 60")
(:BOX (336 177 38 14 ))
(:BEHAVIORS NIL)
(:GILT-REF "TYPE-TEXT"))
(NIL ,GARNETDRAW::MOVING-RECT
(:CONSTANT (:KNOWN-AS ))
(:LINE-STYLE ,(create-instance nil OPAL:LINE-STYLE
(:FOREGROUND-COLOR (create-instance nil OPAL:COLOR
(:BLUE 0)
(:GREEN 0)
(:RED 0)))))
(:FILLING-STYLE NIL)
(:DRAW-FUNCTION :COPY)
(:BOX (332 174 47 19 ))
(:FRAC-LEFT 332)
(:FRAC-TOP 174)
(:FRAC-WIDTH 47)
(:FRAC-HEIGHT 19)
(:BEHAVIORS NIL)))))
(NIL ,GARNETDRAW::MOVING-AGG
(:CONSTANT (:KNOWN-AS :COMPONENTS ))
(:OLD-HEIGHT 31)
(:OLD-WIDTH 527)
(:OLD-TOP 76)
(:OLD-LEFT 53)
(:parts (
(NIL ,OPAL:TEXT
(:LEFT ,(o-formula (FIRST (GVL :BOX)) 53))
(:TOP ,(o-formula (SECOND (GVL :BOX)) 85))
(:CONSTANT (:KNOWN-AS T ))
(:TEMP-BOX (53 85 48 14 ))
(:DRAW-FUNCTION :COPY)
(:LINE-STYLE ,OPAL:DEFAULT-LINE-STYLE)
(:FRAC-HEIGHT 14)
(:FRAC-WIDTH 48)
(:FRAC-TOP 85)
(:FRAC-LEFT 53)
(:STRING "POINT-2")
(:BOX (53 85 48 14 ))
(:BEHAVIORS NIL)
(:GILT-REF "TYPE-TEXT"))
(NIL ,OPAL:CIRCLE
(:LEFT ,(o-formula (FIRST (GVL :BOX)) 107))
(:TOP ,(o-formula (SECOND (GVL :BOX)) 76))
(:WIDTH ,(o-formula (THIRD (GVL :BOX)) 30))
(:HEIGHT ,(o-formula (FOURTH (GVL :BOX)) 30))
(:CONSTANT (:KNOWN-AS T ))
(:TEMP-BOX (107 76 30 30 ))
(:DRAW-FUNCTION :COPY)
(:LINE-STYLE ,OPAL:DEFAULT-LINE-STYLE)
(:FRAC-HEIGHT 30)
(:FRAC-WIDTH 30)
(:FRAC-TOP 76)
(:FRAC-LEFT 107)
(:GROW-P T)
(:BOX (107 76 30 30 ))
(:BEHAVIORS NIL)
(:GILT-REF "TYPE-RECTANGLE"))
(NIL ,OPAL:TEXT
(:LEFT ,(o-formula (FIRST (GVL :BOX)) 145))
(:TOP ,(o-formula (SECOND (GVL :BOX)) 76))
(:CONSTANT (:KNOWN-AS T ))
(:TEMP-BOX (145 76 38 14 ))
(:DRAW-FUNCTION :COPY)
(:LINE-STYLE ,OPAL:DEFAULT-LINE-STYLE)
(:FRAC-HEIGHT 14)
(:FRAC-WIDTH 38)
(:FRAC-TOP 76)
(:FRAC-LEFT 145)
(:STRING ":parent POINT-1")
(:BOX (145 76 38 14 ))
(:BEHAVIORS NIL)
(:GILT-REF "TYPE-TEXT"))
(NIL ,OPAL:TEXT
(:LEFT ,(o-formula (FIRST (GVL :BOX)) 145))
(:TOP ,(o-formula (SECOND (GVL :BOX)) 93))
(:CONSTANT (:KNOWN-AS T ))
(:TEMP-BOX (145 93 38 14 ))
(:DRAW-FUNCTION :COPY)
(:LINE-STYLE ,OPAL:DEFAULT-LINE-STYLE)
(:FRAC-HEIGHT 14)
(:FRAC-WIDTH 38)
(:FRAC-TOP 93)
(:FRAC-LEFT 145)
(:STRING ":y (formula '(floor (+ (gvl :parent :y1) (gvl :parent :y2)) 2))")
(:BOX (145 93 38 14 ))
(:BEHAVIORS NIL)
(:GILT-REF "TYPE-TEXT")))))
(NIL ,OPAL:CURSOR-MULTI-TEXT
(:LEFT ,(o-formula (FIRST (GVL :BOX)) 16))
(:TOP ,(o-formula (SECOND (GVL :BOX)) 60))
(:LINE-STYLE ,(create-instance nil OPAL:LINE-STYLE
(:FOREGROUND-COLOR (create-instance nil OPAL:COLOR
(:BLUE 0)
(:GREEN 0)
(:RED 0)))))
(:FONT ,(create-instance nil OPAL:FONT
(:SIZE :LARGE)
(:FACE :BOLD)))
(:TEXT-P T)
(:STRING "(a)")
(:BOX (16 60 0 0 ))
(:FRAC-LEFT 16)
(:FRAC-TOP 60)
(:FRAC-WIDTH 14)
(:FRAC-HEIGHT 11))
(NIL ,OPAL:CURSOR-MULTI-TEXT
(:LEFT ,(o-formula (FIRST (GVL :BOX)) 490))
(:TOP ,(o-formula (SECOND (GVL :BOX)) 123))
(:LINE-STYLE ,(create-instance nil OPAL:LINE-STYLE
(:FOREGROUND-COLOR (create-instance nil OPAL:COLOR
(:BLUE 0)
(:GREEN 0)
(:RED 0)))))
(:FONT ,(create-instance nil OPAL:FONT
(:SIZE :LARGE)
(:FACE :BOLD)))
(:TEXT-P T)
(:STRING "(e)")
(:BOX (490 123 24 20 ))
(:FRAC-LEFT 490)
(:FRAC-TOP 123)
(:FRAC-WIDTH 24)
(:FRAC-HEIGHT 20)
(:BEHAVIORS NIL)
(:DRAW-FUNCTION :COPY)
(:CURSOR-INDEX NIL)
(:SAVED-CURSOR-INDEX 2))
(NIL ,OPAL:CURSOR-MULTI-TEXT
(:LEFT ,(o-formula (FIRST (GVL :BOX)) 345))
(:TOP ,(o-formula (SECOND (GVL :BOX)) 123))
(:LINE-STYLE ,(create-instance nil OPAL:LINE-STYLE
(:FOREGROUND-COLOR (create-instance nil OPAL:COLOR
(:BLUE 0)
(:GREEN 0)
(:RED 0)))))
(:FONT ,(create-instance nil OPAL:FONT
(:SIZE :LARGE)
(:FACE :BOLD)))
(:TEXT-P T)
(:STRING "(d)")
(:BOX (345 123 24 20 ))
(:FRAC-LEFT 345)
(:FRAC-TOP 123)
(:FRAC-WIDTH 24)
(:FRAC-HEIGHT 20)
(:BEHAVIORS NIL)
(:DRAW-FUNCTION :COPY)
(:CURSOR-INDEX NIL)
(:SAVED-CURSOR-INDEX 2))
(NIL ,OPAL:CURSOR-MULTI-TEXT
(:LEFT ,(o-formula (FIRST (GVL :BOX)) 212))
(:TOP ,(o-formula (SECOND (GVL :BOX)) 123))
(:LINE-STYLE ,(create-instance nil OPAL:LINE-STYLE
(:FOREGROUND-COLOR (create-instance nil OPAL:COLOR
(:BLUE 0)
(:GREEN 0)
(:RED 0)))))
(:FONT ,(create-instance nil OPAL:FONT
(:SIZE :LARGE)
(:FACE :BOLD)))
(:TEXT-P T)
(:STRING "(c)")
(:BOX (212 123 24 20 ))
(:FRAC-LEFT 212)
(:FRAC-TOP 123)
(:FRAC-WIDTH 24)
(:FRAC-HEIGHT 20)
(:BEHAVIORS NIL)
(:DRAW-FUNCTION :COPY)
(:CURSOR-INDEX NIL)
(:SAVED-CURSOR-INDEX 2))
(NIL ,OPAL:CURSOR-MULTI-TEXT
(:LEFT ,(o-formula (FIRST (GVL :BOX)) 69))
(:TOP ,(o-formula (SECOND (GVL :BOX)) 123))
(:LINE-STYLE ,(create-instance nil OPAL:LINE-STYLE
(:FOREGROUND-COLOR (create-instance nil OPAL:COLOR
(:BLUE 0)
(:GREEN 0)
(:RED 0)))))
(:FONT ,(create-instance nil OPAL:FONT
(:SIZE :LARGE)
(:FACE :BOLD)))
(:TEXT-P T)
(:STRING "(b)")
(:BOX (69 123 24 20 ))
(:FRAC-LEFT 69)
(:FRAC-TOP 123)
(:FRAC-WIDTH 24)
(:FRAC-HEIGHT 20)
(:BEHAVIORS NIL)
(:DRAW-FUNCTION :COPY)
(:CURSOR-INDEX NIL)
(:SAVED-CURSOR-INDEX 2)))))
)
| null | https://raw.githubusercontent.com/earl-ducaine/cl-garnet/f0095848513ba69c370ed1dc51ee01f0bb4dd108/doc/previous-version/src/kr/garnet-code/formulas.lisp | lisp | (setf garnetdraw::*DRAW-AGG*
(create-instance 'FORMULAS OPAL:AGGREGADGET
(:LEFT 0)
(:TOP 0)
(:WIDTH (o-formula (GVL :WINDOW :WIDTH) 680))
(:HEIGHT (o-formula (GVL :WINDOW :HEIGHT) 410))
(:CONSTANT `(:COMPONENTS ))
(:FUNCTION-FOR-OK NIL)
(:EXPORT-P T)
(:WINDOW-TITLE "FORMULAS FIGURE")
(:PACKAGE-NAME "USER")
(:WINDOW-HEIGHT 300)
(:WINDOW-WIDTH 450)
(:WINDOW-TOP 0)
(:WINDOW-LEFT 0)
(:parts `(
(NIL ,GARNETDRAW::MOVING-AGG
(:CONSTANT (:KNOWN-AS :COMPONENTS ))
(:OLD-HEIGHT 31)
(:OLD-WIDTH 130)
(:OLD-TOP 31)
(:OLD-LEFT 55)
(:parts (
(NIL ,OPAL:TEXT
(:LEFT ,(o-formula (FIRST (GVL :BOX)) 55))
(:TOP ,(o-formula (SECOND (GVL :BOX)) 40))
(:CONSTANT (:KNOWN-AS T ))
(:FRAC-HEIGHT 14)
(:FRAC-WIDTH 48)
(:FRAC-TOP 40)
(:FRAC-LEFT 55)
(:STRING "POINT-1")
(:BOX (55 40 3 3 ))
(:BEHAVIORS NIL)
(:GILT-REF "TYPE-TEXT"))
(NIL ,OPAL:CIRCLE
(:LEFT ,(o-formula (FIRST (GVL :BOX)) 109))
(:TOP ,(o-formula (SECOND (GVL :BOX)) 31))
(:WIDTH ,(o-formula (THIRD (GVL :BOX)) 30))
(:HEIGHT ,(o-formula (FOURTH (GVL :BOX)) 30))
(:CONSTANT (:KNOWN-AS T ))
(:FRAC-HEIGHT 30)
(:FRAC-WIDTH 30)
(:FRAC-TOP 31)
(:FRAC-LEFT 109)
(:GROW-P T)
(:BOX (109 31 30 30 ))
(:BEHAVIORS NIL)
(:GILT-REF "TYPE-RECTANGLE"))
(NIL ,OPAL:TEXT
(:LEFT ,(o-formula (FIRST (GVL :BOX)) 147))
(:TOP ,(o-formula (SECOND (GVL :BOX)) 31))
(:CONSTANT (:KNOWN-AS T ))
(:FRAC-HEIGHT 14)
(:FRAC-WIDTH 38)
(:FRAC-TOP 31)
(:FRAC-LEFT 147)
(:STRING ":y1 10")
(:BOX (147 31 38 14 ))
(:BEHAVIORS NIL)
(:GILT-REF "TYPE-TEXT"))
(NIL ,OPAL:TEXT
(:LEFT ,(o-formula (FIRST (GVL :BOX)) 147))
(:TOP ,(o-formula (SECOND (GVL :BOX)) 48))
(:CONSTANT (:KNOWN-AS T ))
(:FRAC-HEIGHT 14)
(:FRAC-WIDTH 38)
(:FRAC-TOP 48)
(:FRAC-LEFT 147)
(:STRING ":y2 40")
(:BOX (147 48 38 14 ))
(:BEHAVIORS NIL)
(:GILT-REF "TYPE-TEXT")))))
(NIL ,OPAL:TEXT
(:LEFT ,(o-formula (FIRST (GVL :BOX)) 26))
(:TOP ,(o-formula (SECOND (GVL :BOX)) 144))
(:CONSTANT (:KNOWN-AS T ))
(:TEMP-BOX (18 148 48 14 ))
(:DRAW-FUNCTION :COPY)
(:LINE-STYLE ,OPAL:DEFAULT-LINE-STYLE)
(:FRAC-HEIGHT 14)
(:FRAC-WIDTH 48)
(:FRAC-TOP 144)
(:FRAC-LEFT 26)
(:STRING "POINT-1")
(:BOX (26 144 48 14 ))
(:BEHAVIORS NIL)
(:GILT-REF "TYPE-TEXT"))
(NIL ,GARNETDRAW::MOVING-AGG
(:CONSTANT (:KNOWN-AS :COMPONENTS ))
(:BOX (22 160 76 31 ))
(:OLD-HEIGHT 31)
(:OLD-WIDTH 76)
(:OLD-TOP 160)
(:OLD-LEFT 22)
(:parts (
(NIL ,OPAL:CIRCLE
(:LEFT ,(o-formula (FIRST (GVL :BOX)) 22))
(:TOP ,(o-formula (SECOND (GVL :BOX)) 160))
(:WIDTH ,(o-formula (THIRD (GVL :BOX)) 30))
(:HEIGHT ,(o-formula (FOURTH (GVL :BOX)) 30))
(:CONSTANT (:KNOWN-AS T ))
(:TEMP-BOX (22 160 30 30 ))
(:DRAW-FUNCTION :COPY)
(:LINE-STYLE ,OPAL:DEFAULT-LINE-STYLE)
(:FRAC-HEIGHT 30)
(:FRAC-WIDTH 30)
(:FRAC-TOP 160)
(:FRAC-LEFT 22)
(:GROW-P T)
(:BOX (22 160 30 30 ))
(:BEHAVIORS NIL)
(:GILT-REF "TYPE-RECTANGLE"))
(NIL ,OPAL:TEXT
(:LEFT ,(o-formula (FIRST (GVL :BOX)) 60))
(:TOP ,(o-formula (SECOND (GVL :BOX)) 160))
(:CONSTANT (:KNOWN-AS T ))
(:TEMP-BOX (60 160 38 14 ))
(:DRAW-FUNCTION :COPY)
(:LINE-STYLE ,OPAL:DEFAULT-LINE-STYLE)
(:FRAC-HEIGHT 14)
(:FRAC-WIDTH 38)
(:FRAC-TOP 160)
(:FRAC-LEFT 60)
(:STRING ":y1 10")
(:BOX (60 160 38 14 ))
(:BEHAVIORS NIL)
(:GILT-REF "TYPE-TEXT"))
(NIL ,OPAL:TEXT
(:LEFT ,(o-formula (FIRST (GVL :BOX)) 60))
(:TOP ,(o-formula (SECOND (GVL :BOX)) 177))
(:CONSTANT (:KNOWN-AS T ))
(:TEMP-BOX (60 177 38 14 ))
(:DRAW-FUNCTION :COPY)
(:LINE-STYLE ,OPAL:DEFAULT-LINE-STYLE)
(:FRAC-HEIGHT 14)
(:FRAC-WIDTH 38)
(:FRAC-TOP 177)
(:FRAC-LEFT 60)
(:STRING ":y2 40")
(:BOX (60 177 38 14 ))
(:BEHAVIORS NIL)
(:GILT-REF "TYPE-TEXT")))))
(NIL ,GARNETDRAW::MOVING-AGG
(:CONSTANT (:KNOWN-AS :COMPONENTS ))
(:HEY 0)
(:BOX (22 216 118 37 ))
(:OLD-HEIGHT 37)
(:OLD-WIDTH 125)
(:OLD-TOP 216)
(:OLD-LEFT 22)
(:parts (
(NIL ,OPAL:CIRCLE
(:LEFT ,(o-formula (FIRST (GVL :BOX)) 22))
(:TOP ,(o-formula (SECOND (GVL :BOX)) 217))
(:WIDTH ,(o-formula (THIRD (GVL :BOX)) 30))
(:HEIGHT ,(o-formula (FOURTH (GVL :BOX)) 30))
(:CONSTANT (:KNOWN-AS T ))
(:TEMP-BOX (22 217 30 30 ))
(:FRAC-HEIGHT 30)
(:FRAC-WIDTH 30)
(:FRAC-TOP 217)
(:FRAC-LEFT 22)
(:GROW-P T)
(:BOX (22 217 30 30 ))
(:BEHAVIORS NIL)
(:GILT-REF "TYPE-RECTANGLE"))
(NIL ,OPAL:TEXT
(:LEFT ,(o-formula (FIRST (GVL :BOX)) 56))
(:TOP ,(o-formula (SECOND (GVL :BOX)) 226))
(:CONSTANT (:KNOWN-AS T ))
(:TEMP-BOX (56 226 11 14 ))
(:FRAC-HEIGHT 14)
(:FRAC-WIDTH 11)
(:FRAC-TOP 226)
(:FRAC-LEFT 56)
(:STRING ":y")
(:BOX (56 226 11 14 ))
(:BEHAVIORS NIL)
(:GILT-REF "TYPE-TEXT"))
(NIL ,OPAL:TEXT
(:LEFT ,(o-formula (FIRST (GVL :BOX)) 78))
(:TOP ,(o-formula (SECOND (GVL :BOX)) 216))
(:CONSTANT (:KNOWN-AS T ))
(:TEMP-BOX (78 216 61 14 ))
(:FRAC-HEIGHT 14)
(:FRAC-WIDTH 61)
(:FRAC-TOP 216)
(:FRAC-LEFT 78)
(:STRING "CACHED 25")
(:BOX (78 216 61 14 ))
(:BEHAVIORS NIL)
(:GILT-REF "TYPE-TEXT"))
(NIL ,OPAL:TEXT
(:LEFT ,(o-formula (FIRST (GVL :BOX)) 78))
(:TOP ,(o-formula (SECOND (GVL :BOX)) 239))
(:CONSTANT (:KNOWN-AS T ))
(:TEMP-BOX (78 239 62 14 ))
(:FRAC-HEIGHT 14)
(:FRAC-WIDTH 62)
(:FRAC-TOP 239)
(:FRAC-LEFT 78)
(:STRING "VALID yes")
(:BOX (78 239 62 14 ))
(:BEHAVIORS NIL)
(:GILT-REF "TYPE-TEXT"))
(NIL ,OPAL:LINE
(:CONSTANT (:KNOWN-AS T ))
(:TEMP-POINTS (68 233 8 6 ))
(:FRAC-Y2 239)
(:FRAC-X2 76)
(:FRAC-Y1 233)
(:FRAC-X1 68)
(:Y2 ,(o-formula (FOURTH (GVL :POINTS)) 239))
(:X2 ,(o-formula (THIRD (GVL :POINTS)) 76))
(:Y1 ,(o-formula (SECOND (GVL :POINTS)) 233))
(:X1 ,(o-formula (FIRST (GVL :POINTS)) 68))
(:GROW-P T)
(:LINE-P T)
(:POINTS (68 233 76 239 ))
(:BEHAVIORS NIL)
(:GILT-REF "TYPE-LINE"))
(NIL ,OPAL:LINE
(:CONSTANT (:KNOWN-AS T ))
(:TEMP-POINTS (68 233 8 -6 ))
(:FRAC-Y2 227)
(:FRAC-X2 76)
(:FRAC-Y1 233)
(:FRAC-X1 68)
(:Y2 ,(o-formula (FOURTH (GVL :POINTS)) 227))
(:X2 ,(o-formula (THIRD (GVL :POINTS)) 76))
(:Y1 ,(o-formula (SECOND (GVL :POINTS)) 233))
(:X1 ,(o-formula (FIRST (GVL :POINTS)) 68))
(:GROW-P T)
(:LINE-P T)
(:POINTS (68 233 76 227 ))
(:BEHAVIORS NIL)
(:GILT-REF "TYPE-LINE")))))
(NIL ,GARNETDRAW::MOVING-AGG
(:CONSTANT (:KNOWN-AS :COMPONENTS ))
(:BOX (298 216 118 37 ))
(:OLD-HEIGHT 37)
(:OLD-WIDTH 118)
(:OLD-TOP 216)
(:OLD-LEFT 298)
(:parts (
(NIL ,OPAL:CIRCLE
(:LEFT ,(o-formula (FIRST (GVL :BOX)) 298))
(:TOP ,(o-formula (SECOND (GVL :BOX)) 217))
(:WIDTH ,(o-formula (THIRD (GVL :BOX)) 30))
(:HEIGHT ,(o-formula (FOURTH (GVL :BOX)) 30))
(:CONSTANT (:KNOWN-AS T ))
(:TEMP-BOX (298 217 30 30 ))
(:DRAW-FUNCTION :COPY)
(:LINE-STYLE ,OPAL:DEFAULT-LINE-STYLE)
(:FRAC-HEIGHT 30)
(:FRAC-WIDTH 30)
(:FRAC-TOP 217)
(:FRAC-LEFT 298)
(:GROW-P T)
(:BOX (298 217 30 30 ))
(:BEHAVIORS NIL)
(:GILT-REF "TYPE-RECTANGLE"))
(NIL ,OPAL:TEXT
(:LEFT ,(o-formula (FIRST (GVL :BOX)) 332))
(:TOP ,(o-formula (SECOND (GVL :BOX)) 226))
(:CONSTANT (:KNOWN-AS T ))
(:TEMP-BOX (332 226 11 14 ))
(:DRAW-FUNCTION :COPY)
(:LINE-STYLE ,OPAL:DEFAULT-LINE-STYLE)
(:FRAC-HEIGHT 14)
(:FRAC-WIDTH 11)
(:FRAC-TOP 226)
(:FRAC-LEFT 332)
(:STRING ":y")
(:BOX (332 226 11 14 ))
(:BEHAVIORS NIL)
(:GILT-REF "TYPE-TEXT"))
(NIL ,OPAL:TEXT
(:LEFT ,(o-formula (FIRST (GVL :BOX)) 354))
(:TOP ,(o-formula (SECOND (GVL :BOX)) 216))
(:CONSTANT (:KNOWN-AS T ))
(:TEMP-BOX (354 216 61 14 ))
(:DRAW-FUNCTION :COPY)
(:LINE-STYLE ,OPAL:DEFAULT-LINE-STYLE)
(:FRAC-HEIGHT 14)
(:FRAC-WIDTH 61)
(:FRAC-TOP 216)
(:FRAC-LEFT 354)
(:STRING "CACHED 25")
(:BOX (354 216 61 14 ))
(:BEHAVIORS NIL)
(:GILT-REF "TYPE-TEXT"))
(NIL ,OPAL:TEXT
(:LEFT ,(o-formula (FIRST (GVL :BOX)) 354))
(:TOP ,(o-formula (SECOND (GVL :BOX)) 239))
(:CONSTANT (:KNOWN-AS T ))
(:TEMP-BOX (354 239 62 14 ))
(:DRAW-FUNCTION :COPY)
(:LINE-STYLE ,OPAL:DEFAULT-LINE-STYLE)
(:FRAC-HEIGHT 14)
(:FRAC-WIDTH 62)
(:FRAC-TOP 239)
(:FRAC-LEFT 354)
(:STRING "VALID no")
(:BOX (354 239 62 14 ))
(:BEHAVIORS NIL)
(:GILT-REF "TYPE-TEXT"))
(NIL ,OPAL:LINE
(:CONSTANT (:KNOWN-AS T ))
(:TEMP-POINTS (344 233 8 6 ))
(:DRAW-FUNCTION :COPY)
(:LINE-STYLE ,OPAL:DEFAULT-LINE-STYLE)
(:FRAC-Y2 239)
(:FRAC-X2 352)
(:FRAC-Y1 233)
(:FRAC-X1 344)
(:Y2 ,(o-formula (FOURTH (GVL :POINTS)) 239))
(:X2 ,(o-formula (THIRD (GVL :POINTS)) 352))
(:Y1 ,(o-formula (SECOND (GVL :POINTS)) 233))
(:X1 ,(o-formula (FIRST (GVL :POINTS)) 344))
(:GROW-P T)
(:LINE-P T)
(:POINTS (344 233 352 239 ))
(:BEHAVIORS NIL)
(:GILT-REF "TYPE-LINE"))
(NIL ,OPAL:LINE
(:CONSTANT (:KNOWN-AS T ))
(:TEMP-POINTS (344 233 8 -6 ))
(:DRAW-FUNCTION :COPY)
(:LINE-STYLE ,OPAL:DEFAULT-LINE-STYLE)
(:FRAC-Y2 227)
(:FRAC-X2 352)
(:FRAC-Y1 233)
(:FRAC-X1 344)
(:Y2 ,(o-formula (FOURTH (GVL :POINTS)) 227))
(:X2 ,(o-formula (THIRD (GVL :POINTS)) 352))
(:Y1 ,(o-formula (SECOND (GVL :POINTS)) 233))
(:X1 ,(o-formula (FIRST (GVL :POINTS)) 344))
(:GROW-P T)
(:LINE-P T)
(:POINTS (344 233 352 227 ))
(:BEHAVIORS NIL)
(:GILT-REF "TYPE-LINE")))))
(NIL ,GARNETDRAW::MOVING-AGG
(:CONSTANT (:KNOWN-AS :COMPONENTS ))
(:BOX (436 160 76 31 ))
(:OLD-HEIGHT 31)
(:OLD-WIDTH 76)
(:OLD-TOP 160)
(:OLD-LEFT 436)
(:parts (
(NIL ,OPAL:CIRCLE
(:LEFT ,(o-formula (FIRST (GVL :BOX)) 436))
(:TOP ,(o-formula (SECOND (GVL :BOX)) 160))
(:WIDTH ,(o-formula (THIRD (GVL :BOX)) 30))
(:HEIGHT ,(o-formula (FOURTH (GVL :BOX)) 30))
(:CONSTANT (:KNOWN-AS T ))
(:TEMP-BOX (436 160 30 30 ))
(:DRAW-FUNCTION :COPY)
(:LINE-STYLE ,OPAL:DEFAULT-LINE-STYLE)
(:FRAC-HEIGHT 30)
(:FRAC-WIDTH 30)
(:FRAC-TOP 160)
(:FRAC-LEFT 436)
(:GROW-P T)
(:BOX (436 160 30 30 ))
(:BEHAVIORS NIL)
(:GILT-REF "TYPE-RECTANGLE"))
(NIL ,OPAL:TEXT
(:LEFT ,(o-formula (FIRST (GVL :BOX)) 474))
(:TOP ,(o-formula (SECOND (GVL :BOX)) 160))
(:CONSTANT (:KNOWN-AS T ))
(:TEMP-BOX (474 160 38 14 ))
(:DRAW-FUNCTION :COPY)
(:LINE-STYLE ,OPAL:DEFAULT-LINE-STYLE)
(:FRAC-HEIGHT 14)
(:FRAC-WIDTH 38)
(:FRAC-TOP 160)
(:FRAC-LEFT 474)
(:STRING ":y1 0")
(:BOX (474 160 38 14 ))
(:BEHAVIORS NIL)
(:GILT-REF "TYPE-TEXT"))
(NIL ,OPAL:TEXT
(:LEFT ,(o-formula (FIRST (GVL :BOX)) 474))
(:TOP ,(o-formula (SECOND (GVL :BOX)) 177))
(:CONSTANT (:KNOWN-AS T ))
(:TEMP-BOX (474 177 38 14 ))
(:DRAW-FUNCTION :COPY)
(:LINE-STYLE ,OPAL:DEFAULT-LINE-STYLE)
(:FRAC-HEIGHT 14)
(:FRAC-WIDTH 38)
(:FRAC-TOP 177)
(:FRAC-LEFT 474)
(:STRING ":y2 60")
(:BOX (474 177 38 14 ))
(:BEHAVIORS NIL)
(:GILT-REF "TYPE-TEXT")))))
(NIL ,OPAL:TEXT
(:LEFT ,(o-formula (FIRST (GVL :BOX)) 26))
(:TOP ,(o-formula (SECOND (GVL :BOX)) 200))
(:CONSTANT (:KNOWN-AS ))
(:FRAC-HEIGHT 14)
(:FRAC-WIDTH 48)
(:FRAC-TOP 200)
(:FRAC-LEFT 26)
(:BOX (26 200 48 14 ))
(:STRING "POINT-2")
(:TEXT-P T)
(:FONT ,OPAL:DEFAULT-FONT)
(:LINE-STYLE ,OPAL:DEFAULT-LINE-STYLE))
(NIL ,GARNETDRAW::MOVING-AGG
(:CONSTANT (:KNOWN-AS :COMPONENTS ))
(:OLD-HEIGHT 44)
(:OLD-WIDTH 133)
(:OLD-TOP 213)
(:OLD-LEFT 436)
(:BOX (436 213 133 44 ))
(:parts (
(NIL ,OPAL:CIRCLE
(:LEFT ,(o-formula (FIRST (GVL :BOX)) 436))
(:TOP ,(o-formula (SECOND (GVL :BOX)) 217))
(:WIDTH ,(o-formula (THIRD (GVL :BOX)) 30))
(:HEIGHT ,(o-formula (FOURTH (GVL :BOX)) 30))
(:CONSTANT (:KNOWN-AS T ))
(:TEMP-BOX (436 217 30 30 ))
(:DRAW-FUNCTION :COPY)
(:LINE-STYLE ,OPAL:DEFAULT-LINE-STYLE)
(:FRAC-HEIGHT 30)
(:FRAC-WIDTH 30)
(:FRAC-TOP 217)
(:FRAC-LEFT 436)
(:GROW-P T)
(:BOX (436 217 30 30 ))
(:BEHAVIORS NIL)
(:GILT-REF "TYPE-RECTANGLE"))
(NIL ,OPAL:TEXT
(:LEFT ,(o-formula (FIRST (GVL :BOX)) 470))
(:TOP ,(o-formula (SECOND (GVL :BOX)) 226))
(:CONSTANT (:KNOWN-AS T ))
(:TEMP-BOX (470 226 11 14 ))
(:DRAW-FUNCTION :COPY)
(:LINE-STYLE ,OPAL:DEFAULT-LINE-STYLE)
(:FRAC-HEIGHT 14)
(:FRAC-WIDTH 11)
(:FRAC-TOP 226)
(:FRAC-LEFT 470)
(:STRING ":y")
(:BOX (470 226 11 14 ))
(:BEHAVIORS NIL)
(:GILT-REF "TYPE-TEXT"))
(NIL ,OPAL:TEXT
(:LEFT ,(o-formula (FIRST (GVL :BOX)) 492))
(:TOP ,(o-formula (SECOND (GVL :BOX)) 216))
(:CONSTANT (:KNOWN-AS T ))
(:TEMP-BOX (492 216 61 14 ))
(:DRAW-FUNCTION :COPY)
(:LINE-STYLE ,OPAL:DEFAULT-LINE-STYLE)
(:FRAC-HEIGHT 14)
(:FRAC-WIDTH 61)
(:FRAC-TOP 216)
(:FRAC-LEFT 492)
(:STRING "CACHED 30")
(:BOX (492 216 61 14 ))
(:BEHAVIORS NIL)
(:GILT-REF "TYPE-TEXT"))
(NIL ,OPAL:TEXT
(:LEFT ,(o-formula (FIRST (GVL :BOX)) 492))
(:TOP ,(o-formula (SECOND (GVL :BOX)) 239))
(:CONSTANT (:KNOWN-AS T ))
(:TEMP-BOX (492 239 62 14 ))
(:DRAW-FUNCTION :COPY)
(:LINE-STYLE ,OPAL:DEFAULT-LINE-STYLE)
(:FRAC-HEIGHT 14)
(:FRAC-WIDTH 62)
(:FRAC-TOP 239)
(:FRAC-LEFT 492)
(:STRING "VALID yes")
(:BOX (492 239 62 14 ))
(:BEHAVIORS NIL)
(:GILT-REF "TYPE-TEXT"))
(NIL ,OPAL:LINE
(:CONSTANT (:KNOWN-AS T ))
(:TEMP-POINTS (482 233 8 6 ))
(:DRAW-FUNCTION :COPY)
(:LINE-STYLE ,OPAL:DEFAULT-LINE-STYLE)
(:FRAC-Y2 239)
(:FRAC-X2 490)
(:FRAC-Y1 233)
(:FRAC-X1 482)
(:Y2 ,(o-formula (FOURTH (GVL :POINTS)) 239))
(:X2 ,(o-formula (THIRD (GVL :POINTS)) 490))
(:Y1 ,(o-formula (SECOND (GVL :POINTS)) 233))
(:X1 ,(o-formula (FIRST (GVL :POINTS)) 482))
(:GROW-P T)
(:LINE-P T)
(:POINTS (482 233 490 239 ))
(:BEHAVIORS NIL)
(:GILT-REF "TYPE-LINE"))
(NIL ,OPAL:LINE
(:CONSTANT (:KNOWN-AS T ))
(:TEMP-POINTS (482 233 8 -6 ))
(:DRAW-FUNCTION :COPY)
(:LINE-STYLE ,OPAL:DEFAULT-LINE-STYLE)
(:FRAC-Y2 227)
(:FRAC-X2 490)
(:FRAC-Y1 233)
(:FRAC-X1 482)
(:Y2 ,(o-formula (FOURTH (GVL :POINTS)) 227))
(:X2 ,(o-formula (THIRD (GVL :POINTS)) 490))
(:Y1 ,(o-formula (SECOND (GVL :POINTS)) 233))
(:X1 ,(o-formula (FIRST (GVL :POINTS)) 482))
(:GROW-P T)
(:LINE-P T)
(:POINTS (482 233 490 227 ))
(:BEHAVIORS NIL)
(:GILT-REF "TYPE-LINE"))
(NIL ,GARNETDRAW::MOVING-RECT
(:CONSTANT (:KNOWN-AS ))
(:LINE-STYLE ,(create-instance nil OPAL:LINE-STYLE
(:FOREGROUND-COLOR (create-instance nil OPAL:COLOR
(:BLUE 0)
(:GREEN 0)
(:RED 0)))))
(:FILLING-STYLE NIL)
(:DRAW-FUNCTION :COPY)
(:BOX (535 238 34 19 ))
(:FRAC-LEFT 535)
(:FRAC-TOP 238)
(:FRAC-WIDTH 34)
(:FRAC-HEIGHT 19)
(:BEHAVIORS NIL)
(:TEMP-BOX (535 238 34 19 )))
(NIL ,GARNETDRAW::MOVING-RECT
(:CONSTANT (:KNOWN-AS ))
(:LINE-STYLE ,(create-instance nil OPAL:LINE-STYLE
(:FOREGROUND-COLOR (create-instance nil OPAL:COLOR
(:BLUE 0)
(:GREEN 0)
(:RED 0)))))
(:FILLING-STYLE NIL)
(:DRAW-FUNCTION :COPY)
(:BOX (535 213 34 19 ))
(:FRAC-LEFT 535)
(:FRAC-TOP 213)
(:FRAC-WIDTH 34)
(:FRAC-HEIGHT 19)
(:BEHAVIORS NIL)
(:TEMP-BOX (535 213 34 19 ))))))
(NIL ,GARNETDRAW::MOVING-AGG
(:CONSTANT (:KNOWN-AS :COMPONENTS ))
(:OLD-HEIGHT 40)
(:OLD-WIDTH 129)
(:OLD-TOP 216)
(:OLD-LEFT 160)
(:BOX (160 216 129 40 ))
(:parts (
(NIL ,OPAL:CIRCLE
(:LEFT ,(o-formula (FIRST (GVL :BOX)) 160))
(:TOP ,(o-formula (SECOND (GVL :BOX)) 217))
(:WIDTH ,(o-formula (THIRD (GVL :BOX)) 30))
(:HEIGHT ,(o-formula (FOURTH (GVL :BOX)) 30))
(:CONSTANT (:KNOWN-AS T ))
(:TEMP-BOX (160 217 30 30 ))
(:DRAW-FUNCTION :COPY)
(:LINE-STYLE ,OPAL:DEFAULT-LINE-STYLE)
(:FRAC-HEIGHT 30)
(:FRAC-WIDTH 30)
(:FRAC-TOP 217)
(:FRAC-LEFT 160)
(:GROW-P T)
(:BOX (160 217 30 30 ))
(:BEHAVIORS NIL)
(:GILT-REF "TYPE-RECTANGLE"))
(NIL ,OPAL:TEXT
(:LEFT ,(o-formula (FIRST (GVL :BOX)) 194))
(:TOP ,(o-formula (SECOND (GVL :BOX)) 226))
(:CONSTANT (:KNOWN-AS T ))
(:TEMP-BOX (194 226 11 14 ))
(:DRAW-FUNCTION :COPY)
(:LINE-STYLE ,OPAL:DEFAULT-LINE-STYLE)
(:FRAC-HEIGHT 14)
(:FRAC-WIDTH 11)
(:FRAC-TOP 226)
(:FRAC-LEFT 194)
(:STRING ":y")
(:BOX (194 226 11 14 ))
(:BEHAVIORS NIL)
(:GILT-REF "TYPE-TEXT"))
(NIL ,OPAL:TEXT
(:LEFT ,(o-formula (FIRST (GVL :BOX)) 216))
(:TOP ,(o-formula (SECOND (GVL :BOX)) 216))
(:CONSTANT (:KNOWN-AS T ))
(:TEMP-BOX (216 216 61 14 ))
(:DRAW-FUNCTION :COPY)
(:LINE-STYLE ,OPAL:DEFAULT-LINE-STYLE)
(:FRAC-HEIGHT 14)
(:FRAC-WIDTH 61)
(:FRAC-TOP 216)
(:FRAC-LEFT 216)
(:STRING "CACHED 25")
(:BOX (216 216 61 14 ))
(:BEHAVIORS NIL)
(:GILT-REF "TYPE-TEXT"))
(NIL ,OPAL:TEXT
(:LEFT ,(o-formula (FIRST (GVL :BOX)) 216))
(:TOP ,(o-formula (SECOND (GVL :BOX)) 239))
(:CONSTANT (:KNOWN-AS T ))
(:TEMP-BOX (216 239 62 14 ))
(:DRAW-FUNCTION :COPY)
(:LINE-STYLE ,OPAL:DEFAULT-LINE-STYLE)
(:FRAC-HEIGHT 14)
(:FRAC-WIDTH 62)
(:FRAC-TOP 239)
(:FRAC-LEFT 216)
(:STRING "VALID no")
(:BOX (216 239 62 14 ))
(:BEHAVIORS NIL)
(:GILT-REF "TYPE-TEXT"))
(NIL ,OPAL:LINE
(:CONSTANT (:KNOWN-AS T ))
(:TEMP-POINTS (206 233 8 6 ))
(:DRAW-FUNCTION :COPY)
(:LINE-STYLE ,OPAL:DEFAULT-LINE-STYLE)
(:FRAC-Y2 239)
(:FRAC-X2 214)
(:FRAC-Y1 233)
(:FRAC-X1 206)
(:Y2 ,(o-formula (FOURTH (GVL :POINTS)) 239))
(:X2 ,(o-formula (THIRD (GVL :POINTS)) 214))
(:Y1 ,(o-formula (SECOND (GVL :POINTS)) 233))
(:X1 ,(o-formula (FIRST (GVL :POINTS)) 206))
(:GROW-P T)
(:LINE-P T)
(:POINTS (206 233 214 239 ))
(:BEHAVIORS NIL)
(:GILT-REF "TYPE-LINE"))
(NIL ,OPAL:LINE
(:CONSTANT (:KNOWN-AS T ))
(:TEMP-POINTS (206 233 8 -6 ))
(:DRAW-FUNCTION :COPY)
(:LINE-STYLE ,OPAL:DEFAULT-LINE-STYLE)
(:FRAC-Y2 227)
(:FRAC-X2 214)
(:FRAC-Y1 233)
(:FRAC-X1 206)
(:Y2 ,(o-formula (FOURTH (GVL :POINTS)) 227))
(:X2 ,(o-formula (THIRD (GVL :POINTS)) 214))
(:Y1 ,(o-formula (SECOND (GVL :POINTS)) 233))
(:X1 ,(o-formula (FIRST (GVL :POINTS)) 206))
(:GROW-P T)
(:LINE-P T)
(:POINTS (206 233 214 227 ))
(:BEHAVIORS NIL)
(:GILT-REF "TYPE-LINE"))
(NIL ,GARNETDRAW::MOVING-RECT
(:CONSTANT (:KNOWN-AS ))
(:LINE-STYLE ,(create-instance nil OPAL:LINE-STYLE
(:FOREGROUND-COLOR (create-instance nil OPAL:COLOR
(:BLUE 0)
(:GREEN 0)
(:RED 0)))))
(:FILLING-STYLE NIL)
(:DRAW-FUNCTION :COPY)
(:BOX (255 237 34 19 ))
(:FRAC-LEFT 255)
(:FRAC-TOP 237)
(:FRAC-WIDTH 34)
(:FRAC-HEIGHT 19)
(:BEHAVIORS NIL)
(:TEMP-BOX (255 237 34 19 ))))))
(NIL ,GARNETDRAW::MOVING-AGG
(:CONSTANT (:KNOWN-AS :COMPONENTS ))
(:OLD-HEIGHT 33)
(:OLD-WIDTH 80)
(:OLD-TOP 158)
(:OLD-LEFT 160)
(:parts (
(NIL ,OPAL:CIRCLE
(:LEFT ,(o-formula (FIRST (GVL :BOX)) 160))
(:TOP ,(o-formula (SECOND (GVL :BOX)) 160))
(:WIDTH ,(o-formula (THIRD (GVL :BOX)) 30))
(:HEIGHT ,(o-formula (FOURTH (GVL :BOX)) 30))
(:CONSTANT (:KNOWN-AS T ))
(:TEMP-BOX (160 160 30 30 ))
(:DRAW-FUNCTION :COPY)
(:LINE-STYLE ,OPAL:DEFAULT-LINE-STYLE)
(:FRAC-HEIGHT 30)
(:FRAC-WIDTH 30)
(:FRAC-TOP 160)
(:FRAC-LEFT 160)
(:GROW-P T)
(:BOX (160 160 30 30 ))
(:BEHAVIORS NIL)
(:GILT-REF "TYPE-RECTANGLE"))
(NIL ,OPAL:TEXT
(:LEFT ,(o-formula (FIRST (GVL :BOX)) 198))
(:TOP ,(o-formula (SECOND (GVL :BOX)) 160))
(:CONSTANT (:KNOWN-AS T ))
(:TEMP-BOX (198 160 38 14 ))
(:DRAW-FUNCTION :COPY)
(:LINE-STYLE ,OPAL:DEFAULT-LINE-STYLE)
(:FRAC-HEIGHT 14)
(:FRAC-WIDTH 38)
(:FRAC-TOP 160)
(:FRAC-LEFT 198)
(:STRING ":y1 0")
(:BOX (198 160 38 14 ))
(:BEHAVIORS NIL)
(:GILT-REF "TYPE-TEXT"))
(NIL ,OPAL:TEXT
(:LEFT ,(o-formula (FIRST (GVL :BOX)) 198))
(:TOP ,(o-formula (SECOND (GVL :BOX)) 177))
(:CONSTANT (:KNOWN-AS T ))
(:TEMP-BOX (198 177 38 14 ))
(:DRAW-FUNCTION :COPY)
(:LINE-STYLE ,OPAL:DEFAULT-LINE-STYLE)
(:FRAC-HEIGHT 14)
(:FRAC-WIDTH 38)
(:FRAC-TOP 177)
(:FRAC-LEFT 198)
(:STRING ":y2 40")
(:BOX (198 177 38 14 ))
(:BEHAVIORS NIL)
(:GILT-REF "TYPE-TEXT"))
(NIL ,GARNETDRAW::MOVING-RECT
(:CONSTANT (:KNOWN-AS ))
(:LINE-STYLE ,(create-instance nil OPAL:LINE-STYLE
(:FOREGROUND-COLOR (create-instance nil OPAL:COLOR
(:BLUE 0)
(:GREEN 0)
(:RED 0)))))
(:FILLING-STYLE NIL)
(:DRAW-FUNCTION :COPY)
(:BOX (193 158 47 19 ))
(:FRAC-LEFT 193)
(:FRAC-TOP 158)
(:FRAC-WIDTH 47)
(:FRAC-HEIGHT 19)))))
(NIL ,GARNETDRAW::MOVING-AGG
(:CONSTANT (:KNOWN-AS :COMPONENTS ))
(:OLD-HEIGHT 33)
(:OLD-WIDTH 81)
(:OLD-TOP 160)
(:OLD-LEFT 298)
(:parts (
(NIL ,OPAL:CIRCLE
(:LEFT ,(o-formula (FIRST (GVL :BOX)) 298))
(:TOP ,(o-formula (SECOND (GVL :BOX)) 160))
(:WIDTH ,(o-formula (THIRD (GVL :BOX)) 30))
(:HEIGHT ,(o-formula (FOURTH (GVL :BOX)) 30))
(:CONSTANT (:KNOWN-AS T ))
(:TEMP-BOX (298 160 30 30 ))
(:DRAW-FUNCTION :COPY)
(:LINE-STYLE ,OPAL:DEFAULT-LINE-STYLE)
(:FRAC-HEIGHT 30)
(:FRAC-WIDTH 30)
(:FRAC-TOP 160)
(:FRAC-LEFT 298)
(:GROW-P T)
(:BOX (298 160 30 30 ))
(:BEHAVIORS NIL)
(:GILT-REF "TYPE-RECTANGLE"))
(NIL ,OPAL:TEXT
(:LEFT ,(o-formula (FIRST (GVL :BOX)) 336))
(:TOP ,(o-formula (SECOND (GVL :BOX)) 160))
(:CONSTANT (:KNOWN-AS T ))
(:TEMP-BOX (336 160 38 14 ))
(:DRAW-FUNCTION :COPY)
(:LINE-STYLE ,OPAL:DEFAULT-LINE-STYLE)
(:FRAC-HEIGHT 14)
(:FRAC-WIDTH 38)
(:FRAC-TOP 160)
(:FRAC-LEFT 336)
(:STRING ":y1 0")
(:BOX (336 160 38 14 ))
(:BEHAVIORS NIL)
(:GILT-REF "TYPE-TEXT"))
(NIL ,OPAL:TEXT
(:LEFT ,(o-formula (FIRST (GVL :BOX)) 336))
(:TOP ,(o-formula (SECOND (GVL :BOX)) 177))
(:CONSTANT (:KNOWN-AS T ))
(:TEMP-BOX (336 177 38 14 ))
(:DRAW-FUNCTION :COPY)
(:LINE-STYLE ,OPAL:DEFAULT-LINE-STYLE)
(:FRAC-HEIGHT 14)
(:FRAC-WIDTH 38)
(:FRAC-TOP 177)
(:FRAC-LEFT 336)
(:STRING ":y2 60")
(:BOX (336 177 38 14 ))
(:BEHAVIORS NIL)
(:GILT-REF "TYPE-TEXT"))
(NIL ,GARNETDRAW::MOVING-RECT
(:CONSTANT (:KNOWN-AS ))
(:LINE-STYLE ,(create-instance nil OPAL:LINE-STYLE
(:FOREGROUND-COLOR (create-instance nil OPAL:COLOR
(:BLUE 0)
(:GREEN 0)
(:RED 0)))))
(:FILLING-STYLE NIL)
(:DRAW-FUNCTION :COPY)
(:BOX (332 174 47 19 ))
(:FRAC-LEFT 332)
(:FRAC-TOP 174)
(:FRAC-WIDTH 47)
(:FRAC-HEIGHT 19)
(:BEHAVIORS NIL)))))
(NIL ,GARNETDRAW::MOVING-AGG
(:CONSTANT (:KNOWN-AS :COMPONENTS ))
(:OLD-HEIGHT 31)
(:OLD-WIDTH 527)
(:OLD-TOP 76)
(:OLD-LEFT 53)
(:parts (
(NIL ,OPAL:TEXT
(:LEFT ,(o-formula (FIRST (GVL :BOX)) 53))
(:TOP ,(o-formula (SECOND (GVL :BOX)) 85))
(:CONSTANT (:KNOWN-AS T ))
(:TEMP-BOX (53 85 48 14 ))
(:DRAW-FUNCTION :COPY)
(:LINE-STYLE ,OPAL:DEFAULT-LINE-STYLE)
(:FRAC-HEIGHT 14)
(:FRAC-WIDTH 48)
(:FRAC-TOP 85)
(:FRAC-LEFT 53)
(:STRING "POINT-2")
(:BOX (53 85 48 14 ))
(:BEHAVIORS NIL)
(:GILT-REF "TYPE-TEXT"))
(NIL ,OPAL:CIRCLE
(:LEFT ,(o-formula (FIRST (GVL :BOX)) 107))
(:TOP ,(o-formula (SECOND (GVL :BOX)) 76))
(:WIDTH ,(o-formula (THIRD (GVL :BOX)) 30))
(:HEIGHT ,(o-formula (FOURTH (GVL :BOX)) 30))
(:CONSTANT (:KNOWN-AS T ))
(:TEMP-BOX (107 76 30 30 ))
(:DRAW-FUNCTION :COPY)
(:LINE-STYLE ,OPAL:DEFAULT-LINE-STYLE)
(:FRAC-HEIGHT 30)
(:FRAC-WIDTH 30)
(:FRAC-TOP 76)
(:FRAC-LEFT 107)
(:GROW-P T)
(:BOX (107 76 30 30 ))
(:BEHAVIORS NIL)
(:GILT-REF "TYPE-RECTANGLE"))
(NIL ,OPAL:TEXT
(:LEFT ,(o-formula (FIRST (GVL :BOX)) 145))
(:TOP ,(o-formula (SECOND (GVL :BOX)) 76))
(:CONSTANT (:KNOWN-AS T ))
(:TEMP-BOX (145 76 38 14 ))
(:DRAW-FUNCTION :COPY)
(:LINE-STYLE ,OPAL:DEFAULT-LINE-STYLE)
(:FRAC-HEIGHT 14)
(:FRAC-WIDTH 38)
(:FRAC-TOP 76)
(:FRAC-LEFT 145)
(:STRING ":parent POINT-1")
(:BOX (145 76 38 14 ))
(:BEHAVIORS NIL)
(:GILT-REF "TYPE-TEXT"))
(NIL ,OPAL:TEXT
(:LEFT ,(o-formula (FIRST (GVL :BOX)) 145))
(:TOP ,(o-formula (SECOND (GVL :BOX)) 93))
(:CONSTANT (:KNOWN-AS T ))
(:TEMP-BOX (145 93 38 14 ))
(:DRAW-FUNCTION :COPY)
(:LINE-STYLE ,OPAL:DEFAULT-LINE-STYLE)
(:FRAC-HEIGHT 14)
(:FRAC-WIDTH 38)
(:FRAC-TOP 93)
(:FRAC-LEFT 145)
(:STRING ":y (formula '(floor (+ (gvl :parent :y1) (gvl :parent :y2)) 2))")
(:BOX (145 93 38 14 ))
(:BEHAVIORS NIL)
(:GILT-REF "TYPE-TEXT")))))
(NIL ,OPAL:CURSOR-MULTI-TEXT
(:LEFT ,(o-formula (FIRST (GVL :BOX)) 16))
(:TOP ,(o-formula (SECOND (GVL :BOX)) 60))
(:LINE-STYLE ,(create-instance nil OPAL:LINE-STYLE
(:FOREGROUND-COLOR (create-instance nil OPAL:COLOR
(:BLUE 0)
(:GREEN 0)
(:RED 0)))))
(:FONT ,(create-instance nil OPAL:FONT
(:SIZE :LARGE)
(:FACE :BOLD)))
(:TEXT-P T)
(:STRING "(a)")
(:BOX (16 60 0 0 ))
(:FRAC-LEFT 16)
(:FRAC-TOP 60)
(:FRAC-WIDTH 14)
(:FRAC-HEIGHT 11))
(NIL ,OPAL:CURSOR-MULTI-TEXT
(:LEFT ,(o-formula (FIRST (GVL :BOX)) 490))
(:TOP ,(o-formula (SECOND (GVL :BOX)) 123))
(:LINE-STYLE ,(create-instance nil OPAL:LINE-STYLE
(:FOREGROUND-COLOR (create-instance nil OPAL:COLOR
(:BLUE 0)
(:GREEN 0)
(:RED 0)))))
(:FONT ,(create-instance nil OPAL:FONT
(:SIZE :LARGE)
(:FACE :BOLD)))
(:TEXT-P T)
(:STRING "(e)")
(:BOX (490 123 24 20 ))
(:FRAC-LEFT 490)
(:FRAC-TOP 123)
(:FRAC-WIDTH 24)
(:FRAC-HEIGHT 20)
(:BEHAVIORS NIL)
(:DRAW-FUNCTION :COPY)
(:CURSOR-INDEX NIL)
(:SAVED-CURSOR-INDEX 2))
(NIL ,OPAL:CURSOR-MULTI-TEXT
(:LEFT ,(o-formula (FIRST (GVL :BOX)) 345))
(:TOP ,(o-formula (SECOND (GVL :BOX)) 123))
(:LINE-STYLE ,(create-instance nil OPAL:LINE-STYLE
(:FOREGROUND-COLOR (create-instance nil OPAL:COLOR
(:BLUE 0)
(:GREEN 0)
(:RED 0)))))
(:FONT ,(create-instance nil OPAL:FONT
(:SIZE :LARGE)
(:FACE :BOLD)))
(:TEXT-P T)
(:STRING "(d)")
(:BOX (345 123 24 20 ))
(:FRAC-LEFT 345)
(:FRAC-TOP 123)
(:FRAC-WIDTH 24)
(:FRAC-HEIGHT 20)
(:BEHAVIORS NIL)
(:DRAW-FUNCTION :COPY)
(:CURSOR-INDEX NIL)
(:SAVED-CURSOR-INDEX 2))
(NIL ,OPAL:CURSOR-MULTI-TEXT
(:LEFT ,(o-formula (FIRST (GVL :BOX)) 212))
(:TOP ,(o-formula (SECOND (GVL :BOX)) 123))
(:LINE-STYLE ,(create-instance nil OPAL:LINE-STYLE
(:FOREGROUND-COLOR (create-instance nil OPAL:COLOR
(:BLUE 0)
(:GREEN 0)
(:RED 0)))))
(:FONT ,(create-instance nil OPAL:FONT
(:SIZE :LARGE)
(:FACE :BOLD)))
(:TEXT-P T)
(:STRING "(c)")
(:BOX (212 123 24 20 ))
(:FRAC-LEFT 212)
(:FRAC-TOP 123)
(:FRAC-WIDTH 24)
(:FRAC-HEIGHT 20)
(:BEHAVIORS NIL)
(:DRAW-FUNCTION :COPY)
(:CURSOR-INDEX NIL)
(:SAVED-CURSOR-INDEX 2))
(NIL ,OPAL:CURSOR-MULTI-TEXT
(:LEFT ,(o-formula (FIRST (GVL :BOX)) 69))
(:TOP ,(o-formula (SECOND (GVL :BOX)) 123))
(:LINE-STYLE ,(create-instance nil OPAL:LINE-STYLE
(:FOREGROUND-COLOR (create-instance nil OPAL:COLOR
(:BLUE 0)
(:GREEN 0)
(:RED 0)))))
(:FONT ,(create-instance nil OPAL:FONT
(:SIZE :LARGE)
(:FACE :BOLD)))
(:TEXT-P T)
(:STRING "(b)")
(:BOX (69 123 24 20 ))
(:FRAC-LEFT 69)
(:FRAC-TOP 123)
(:FRAC-WIDTH 24)
(:FRAC-HEIGHT 20)
(:BEHAVIORS NIL)
(:DRAW-FUNCTION :COPY)
(:CURSOR-INDEX NIL)
(:SAVED-CURSOR-INDEX 2)))))
)
| |
7e167abd6deb10cce58fc14adb9604bf7265233b7340574c823af716275e27be | erlyaws/yaws | basic_echo_callback.erl | %%%===========================================================
%%% compiled using erlc -I include src/basic_echo_callback.erl
%%%===========================================================
-module(basic_echo_callback).
%% Export for websocket callbacks
-export([handle_message/1]).
%% Export for apply
-export([say_hi/1]).
handle_message({text, <<"bye">>}) ->
io:format("User said bye.~n", []),
{close, normal};
handle_message({text, <<"something">>}) ->
io:format("Some action without a reply~n", []),
noreply;
handle_message({text, <<"say hi later">>}) ->
io:format("saying hi in 3s.~n", []),
timer:apply_after(3000, ?MODULE, say_hi, [self()]),
{reply, {text, <<"I'll say hi in a bit...">>}};
handle_message({text, Message}) ->
io:format("basic echo handler got ~p~n", [Message]),
{reply, {text, <<Message/binary>>}};
handle_message({binary, Message}) ->
{reply, {binary, Message}};
handle_message({close, Status, _Reason}) ->
{close, Status}.
say_hi(Pid) ->
io:format("asynchronous greeting~n", []),
yaws_api:websocket_send(Pid, {text, <<"hi there!">>}).
| null | https://raw.githubusercontent.com/erlyaws/yaws/da198c828e9d95ca2137da7884cddadd73941d13/examples/src/basic_echo_callback.erl | erlang | ===========================================================
compiled using erlc -I include src/basic_echo_callback.erl
===========================================================
Export for websocket callbacks
Export for apply |
-module(basic_echo_callback).
-export([handle_message/1]).
-export([say_hi/1]).
handle_message({text, <<"bye">>}) ->
io:format("User said bye.~n", []),
{close, normal};
handle_message({text, <<"something">>}) ->
io:format("Some action without a reply~n", []),
noreply;
handle_message({text, <<"say hi later">>}) ->
io:format("saying hi in 3s.~n", []),
timer:apply_after(3000, ?MODULE, say_hi, [self()]),
{reply, {text, <<"I'll say hi in a bit...">>}};
handle_message({text, Message}) ->
io:format("basic echo handler got ~p~n", [Message]),
{reply, {text, <<Message/binary>>}};
handle_message({binary, Message}) ->
{reply, {binary, Message}};
handle_message({close, Status, _Reason}) ->
{close, Status}.
say_hi(Pid) ->
io:format("asynchronous greeting~n", []),
yaws_api:websocket_send(Pid, {text, <<"hi there!">>}).
|
c8399ea8869250c150a2b639aa43df60a76021ac92e37e5edb27aff75d4d320e | facebookarchive/pfff | class_type.ml | class type t_item = object
method sel : bool
end
| null | https://raw.githubusercontent.com/facebookarchive/pfff/ec21095ab7d445559576513a63314e794378c367/tests/ml/parsing/class_type.ml | ocaml | class type t_item = object
method sel : bool
end
| |
9bc59de37d6eca038eba421cffb133e32bfe4fde70c4cf0fac63fc02b304a24c | ucsd-progsys/nate | unixLabels.mli | (***********************************************************************)
(* *)
(* Objective Caml *)
(* *)
, projet Cristal , INRIA Rocquencourt
(* *)
Copyright 1996 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the GNU Library General Public License , with
(* the special exception on linking described in file ../../LICENSE. *)
(* *)
(***********************************************************************)
$ I d : unixLabels.mli , v 1.15.4.1 2007/11/19 21:27:56 doligez Exp $
* Interface to the Unix system .
To use as replacement to default { ! Unix } module ,
add [ module Unix = UnixLabels ] in your implementation .
To use as replacement to default {!Unix} module,
add [module Unix = UnixLabels] in your implementation.
*)
* { 6 Error report }
type error = Unix.error =
E2BIG (** Argument list too long *)
| EACCES (** Permission denied *)
| EAGAIN (** Resource temporarily unavailable; try again *)
| EBADF (** Bad file descriptor *)
| EBUSY (** Resource unavailable *)
| ECHILD (** No child process *)
| EDEADLK (** Resource deadlock would occur *)
| EDOM (** Domain error for math functions, etc. *)
| EEXIST (** File exists *)
| EFAULT (** Bad address *)
| EFBIG (** File too large *)
| EINTR (** Function interrupted by signal *)
| EINVAL (** Invalid argument *)
| EIO (** Hardware I/O error *)
| EISDIR (** Is a directory *)
| EMFILE (** Too many open files by the process *)
| EMLINK (** Too many links *)
| ENAMETOOLONG (** Filename too long *)
| ENFILE (** Too many open files in the system *)
| ENODEV (** No such device *)
| ENOENT (** No such file or directory *)
| ENOEXEC (** Not an executable file *)
| ENOLCK (** No locks available *)
| ENOMEM (** Not enough memory *)
| ENOSPC (** No space left on device *)
| ENOSYS (** Function not supported *)
| ENOTDIR (** Not a directory *)
| ENOTEMPTY (** Directory not empty *)
| ENOTTY (** Inappropriate I/O control operation *)
| ENXIO (** No such device or address *)
| EPERM (** Operation not permitted *)
| EPIPE (** Broken pipe *)
| ERANGE (** Result too large *)
| EROFS (** Read-only file system *)
| ESPIPE (** Invalid seek e.g. on a pipe *)
| ESRCH (** No such process *)
| EXDEV (** Invalid link *)
| EWOULDBLOCK (** Operation would block *)
| EINPROGRESS (** Operation now in progress *)
| EALREADY (** Operation already in progress *)
| ENOTSOCK (** Socket operation on non-socket *)
| EDESTADDRREQ (** Destination address required *)
| EMSGSIZE (** Message too long *)
| EPROTOTYPE (** Protocol wrong type for socket *)
| ENOPROTOOPT (** Protocol not available *)
| EPROTONOSUPPORT (** Protocol not supported *)
| ESOCKTNOSUPPORT (** Socket type not supported *)
| EOPNOTSUPP (** Operation not supported on socket *)
| EPFNOSUPPORT (** Protocol family not supported *)
| EAFNOSUPPORT (** Address family not supported by protocol family *)
| EADDRINUSE (** Address already in use *)
| EADDRNOTAVAIL (** Can't assign requested address *)
| ENETDOWN (** Network is down *)
| ENETUNREACH (** Network is unreachable *)
| ENETRESET (** Network dropped connection on reset *)
| ECONNABORTED (** Software caused connection abort *)
| ECONNRESET (** Connection reset by peer *)
| ENOBUFS (** No buffer space available *)
| EISCONN (** Socket is already connected *)
| ENOTCONN (** Socket is not connected *)
| ESHUTDOWN (** Can't send after socket shutdown *)
| ETOOMANYREFS (** Too many references: can't splice *)
| ETIMEDOUT (** Connection timed out *)
| ECONNREFUSED (** Connection refused *)
| EHOSTDOWN (** Host is down *)
| EHOSTUNREACH (** No route to host *)
| ELOOP (** Too many levels of symbolic links *)
| EOVERFLOW (** File size or position not representable *)
| EUNKNOWNERR of int (** Unknown error *)
* The type of error codes .
Errors defined in the POSIX standard
and additional errors from UNIX98 and BSD .
All other errors are mapped to EUNKNOWNERR .
Errors defined in the POSIX standard
and additional errors from UNIX98 and BSD.
All other errors are mapped to EUNKNOWNERR.
*)
exception Unix_error of error * string * string
* Raised by the system calls below when an error is encountered .
The first component is the error code ; the second component
is the function name ; the third component is the string parameter
to the function , if it has one , or the empty string otherwise .
The first component is the error code; the second component
is the function name; the third component is the string parameter
to the function, if it has one, or the empty string otherwise. *)
val error_message : error -> string
(** Return a string describing the given error code. *)
val handle_unix_error : ('a -> 'b) -> 'a -> 'b
* [ handle_unix_error f x ] applies [ f ] to [ x ] and returns the result .
If the exception [ Unix_error ] is raised , it prints a message
describing the error and exits with code 2 .
If the exception [Unix_error] is raised, it prints a message
describing the error and exits with code 2. *)
* { 6 Access to the process environment }
val environment : unit -> string array
(** Return the process environment, as an array of strings
with the format ``variable=value''. *)
val getenv : string -> string
(** Return the value associated to a variable in the process
environment. Raise [Not_found] if the variable is unbound.
(This function is identical to [Sys.getenv].) *)
val putenv : string -> string -> unit
* [ Unix.putenv name value ] sets the value associated to a
variable in the process environment .
[ name ] is the name of the environment variable ,
and [ value ] its new associated value .
variable in the process environment.
[name] is the name of the environment variable,
and [value] its new associated value. *)
* { 6 Process handling }
type process_status = Unix.process_status =
WEXITED of int
(** The process terminated normally by [exit];
the argument is the return code. *)
| WSIGNALED of int
(** The process was killed by a signal;
the argument is the signal number. *)
| WSTOPPED of int
(** The process was stopped by a signal; the argument is the
signal number. *)
(** The termination status of a process. *)
type wait_flag = Unix.wait_flag =
* do not block if no child has
died yet , but immediately return with a pid equal to 0 .
died yet, but immediately return with a pid equal to 0.*)
| WUNTRACED (** report also the children that receive stop signals. *)
(** Flags for {!Unix.waitpid}. *)
val execv : prog:string -> args:string array -> 'a
* [ execv prog args ] execute the program in file [ prog ] , with
the arguments [ args ] , and the current process environment .
These [ execv * ] functions never return : on success , the current
program is replaced by the new one ;
on failure , a { ! UnixLabels . Unix_error } exception is raised .
the arguments [args], and the current process environment.
These [execv*] functions never return: on success, the current
program is replaced by the new one;
on failure, a {!UnixLabels.Unix_error} exception is raised. *)
val execve : prog:string -> args:string array -> env:string array -> 'a
* Same as { ! UnixLabels.execv } , except that the third argument provides the
environment to the program executed .
environment to the program executed. *)
val execvp : prog:string -> args:string array -> 'a
(** Same as {!UnixLabels.execv} respectively, except that
the program is searched in the path. *)
val execvpe : prog:string -> args:string array -> env:string array -> 'a
* Same as { ! } respectively , except that
the program is searched in the path .
the program is searched in the path. *)
val fork : unit -> int
(** Fork a new process. The returned integer is 0 for the child
process, the pid of the child process for the parent process. *)
val wait : unit -> int * process_status
* Wait until one of the children processes die , and return its pid
and termination status .
and termination status. *)
val waitpid : mode:wait_flag list -> int -> int * process_status
(** Same as {!UnixLabels.wait}, but waits for the process whose pid is given.
A pid of [-1] means wait for any child.
A pid of [0] means wait for any child in the same process group
as the current process.
Negative pid arguments represent process groups.
The list of options indicates whether [waitpid] should return
immediately without waiting, or also report stopped children. *)
val system : string -> process_status
* Execute the given command , wait until it terminates , and return
its termination status . The string is interpreted by the shell
[ /bin / sh ] and therefore can contain redirections , quotes , variables ,
etc . The result [ 127 ] indicates that the shell could n't
be executed .
its termination status. The string is interpreted by the shell
[/bin/sh] and therefore can contain redirections, quotes, variables,
etc. The result [WEXITED 127] indicates that the shell couldn't
be executed. *)
val getpid : unit -> int
(** Return the pid of the process. *)
val getppid : unit -> int
(** Return the pid of the parent process. *)
val nice : int -> int
(** Change the process priority. The integer argument is added to the
``nice'' value. (Higher values of the ``nice'' value mean
lower priorities.) Return the new nice value. *)
* { 6 Basic file input / output }
type file_descr = Unix.file_descr
(** The abstract type of file descriptors. *)
val stdin : file_descr
(** File descriptor for standard input.*)
val stdout : file_descr
(** File descriptor for standard output.*)
val stderr : file_descr
(** File descriptor for standard error. *)
type open_flag = Unix.open_flag =
O_RDONLY (** Open for reading *)
| O_WRONLY (** Open for writing *)
| O_RDWR (** Open for reading and writing *)
| O_NONBLOCK (** Open in non-blocking mode *)
| O_APPEND (** Open for append *)
| O_CREAT (** Create if nonexistent *)
* to 0 length if existing
| O_EXCL (** Fail if existing *)
| O_NOCTTY (** Don't make this dev a controlling tty *)
| O_DSYNC (** Writes complete as `Synchronised I/O data integrity completion' *)
| O_SYNC (** Writes complete as `Synchronised I/O file integrity completion' *)
| O_RSYNC (** Reads complete as writes (depending on O_SYNC/O_DSYNC) *)
(** The flags to {!UnixLabels.openfile}. *)
type file_perm = int
* The type of file access rights , e.g. [ 0o640 ] is read and write for user ,
read for group , none for others
read for group, none for others *)
val openfile : string -> mode:open_flag list -> perm:file_perm -> file_descr
* Open the named file with the given flags . Third argument is
the permissions to give to the file if it is created . Return
a file descriptor on the named file .
the permissions to give to the file if it is created. Return
a file descriptor on the named file. *)
val close : file_descr -> unit
(** Close a file descriptor. *)
val read : file_descr -> buf:string -> pos:int -> len:int -> int
* [ read fd ] reads [ len ] characters from descriptor
[ fd ] , storing them in string [ buff ] , starting at position [ ofs ]
in string [ buff ] . Return the number of characters actually read .
[fd], storing them in string [buff], starting at position [ofs]
in string [buff]. Return the number of characters actually read. *)
val write : file_descr -> buf:string -> pos:int -> len:int -> int
* [ write fd ] writes [ len ] characters to descriptor
[ fd ] , taking them from string [ buff ] , starting at position [ ofs ]
in string [ buff ] . Return the number of characters actually
written . [ write ] repeats the writing operation until all characters
have been written or an error occurs .
[fd], taking them from string [buff], starting at position [ofs]
in string [buff]. Return the number of characters actually
written. [write] repeats the writing operation until all characters
have been written or an error occurs. *)
val single_write : file_descr -> buf:string -> pos:int -> len:int -> int
(** Same as [write], but attempts to write only once.
Thus, if an error occurs, [single_write] guarantees that no data
has been written. *)
* { 6 Interfacing with the standard input / output library }
val in_channel_of_descr : file_descr -> in_channel
(** Create an input channel reading from the given descriptor.
The channel is initially in binary mode; use
[set_binary_mode_in ic false] if text mode is desired. *)
val out_channel_of_descr : file_descr -> out_channel
(** Create an output channel writing on the given descriptor.
The channel is initially in binary mode; use
[set_binary_mode_out oc false] if text mode is desired. *)
val descr_of_in_channel : in_channel -> file_descr
(** Return the descriptor corresponding to an input channel. *)
val descr_of_out_channel : out_channel -> file_descr
(** Return the descriptor corresponding to an output channel. *)
* { 6 Seeking and truncating }
type seek_command = Unix.seek_command =
SEEK_SET (** indicates positions relative to the beginning of the file *)
| SEEK_CUR (** indicates positions relative to the current position *)
| SEEK_END (** indicates positions relative to the end of the file *)
(** Positioning modes for {!UnixLabels.lseek}. *)
val lseek : file_descr -> int -> mode:seek_command -> int
(** Set the current position for a file descriptor *)
val truncate : string -> len:int -> unit
(** Truncates the named file to the given size. *)
val ftruncate : file_descr -> len:int -> unit
(** Truncates the file corresponding to the given descriptor
to the given size. *)
* { 6 File status }
type file_kind = Unix.file_kind =
S_REG (** Regular file *)
| S_DIR (** Directory *)
| S_CHR (** Character device *)
| S_BLK (** Block device *)
| S_LNK (** Symbolic link *)
| S_FIFO (** Named pipe *)
| S_SOCK (** Socket *)
type stats = Unix.stats =
{ st_dev : int; (** Device number *)
* number
st_kind : file_kind; (** Kind of the file *)
st_perm : file_perm; (** Access rights *)
st_nlink : int; (** Number of links *)
st_uid : int; (** User id of the owner *)
st_gid : int; (** Group ID of the file's group *)
st_rdev : int; (** Device minor number *)
st_size : int; (** Size in bytes *)
st_atime : float; (** Last access time *)
st_mtime : float; (** Last modification time *)
st_ctime : float; (** Last status change time *)
}
(** The informations returned by the {!UnixLabels.stat} calls. *)
val stat : string -> stats
(** Return the information for the named file. *)
val lstat : string -> stats
(** Same as {!UnixLabels.stat}, but in case the file is a symbolic link,
return the information for the link itself. *)
val fstat : file_descr -> stats
(** Return the information for the file associated with the given
descriptor. *)
val isatty : file_descr -> bool
(** Return [true] if the given file descriptor refers to a terminal or
console window, [false] otherwise. *)
* { 6 File operations on large files }
module LargeFile :
sig
val lseek : file_descr -> int64 -> mode:seek_command -> int64
val truncate : string -> len:int64 -> unit
val ftruncate : file_descr -> len:int64 -> unit
type stats = Unix.LargeFile.stats =
{ st_dev : int; (** Device number *)
* number
st_kind : file_kind; (** Kind of the file *)
st_perm : file_perm; (** Access rights *)
st_nlink : int; (** Number of links *)
st_uid : int; (** User id of the owner *)
st_gid : int; (** Group ID of the file's group *)
st_rdev : int; (** Device minor number *)
st_size : int64; (** Size in bytes *)
st_atime : float; (** Last access time *)
st_mtime : float; (** Last modification time *)
st_ctime : float; (** Last status change time *)
}
val stat : string -> stats
val lstat : string -> stats
val fstat : file_descr -> stats
end
* File operations on large files .
This sub - module provides 64 - bit variants of the functions
{ ! UnixLabels.lseek } ( for positioning a file descriptor ) ,
{ ! UnixLabels.truncate } and { ! UnixLabels.ftruncate }
( for changing the size of a file ) ,
and { ! UnixLabels.stat } , { ! UnixLabels.lstat } and { ! UnixLabels.fstat }
( for obtaining information on files ) . These alternate functions represent
positions and sizes by 64 - bit integers ( type [ int64 ] ) instead of
regular integers ( type [ int ] ) , thus allowing operating on files
whose sizes are greater than [ max_int ] .
This sub-module provides 64-bit variants of the functions
{!UnixLabels.lseek} (for positioning a file descriptor),
{!UnixLabels.truncate} and {!UnixLabels.ftruncate}
(for changing the size of a file),
and {!UnixLabels.stat}, {!UnixLabels.lstat} and {!UnixLabels.fstat}
(for obtaining information on files). These alternate functions represent
positions and sizes by 64-bit integers (type [int64]) instead of
regular integers (type [int]), thus allowing operating on files
whose sizes are greater than [max_int]. *)
* { 6 Operations on file names }
val unlink : string -> unit
(** Removes the named file *)
val rename : src:string -> dst:string -> unit
(** [rename old new] changes the name of a file from [old] to [new]. *)
val link : src:string -> dst:string -> unit
(** [link source dest] creates a hard link named [dest] to the file
named [source]. *)
* { 6 File permissions and ownership }
type access_permission = Unix.access_permission =
R_OK (** Read permission *)
| W_OK (** Write permission *)
| X_OK (** Execution permission *)
| F_OK (** File exists *)
(** Flags for the {!UnixLabels.access} call. *)
val chmod : string -> perm:file_perm -> unit
(** Change the permissions of the named file. *)
val fchmod : file_descr -> perm:file_perm -> unit
(** Change the permissions of an opened file. *)
val chown : string -> uid:int -> gid:int -> unit
* Change the owner uid and owner gid of the named file .
val fchown : file_descr -> uid:int -> gid:int -> unit
* Change the owner uid and owner gid of an opened file .
val umask : int -> int
(** Set the process's file mode creation mask, and return the previous
mask. *)
val access : string -> perm:access_permission list -> unit
(** Check that the process has the given permissions over the named
file. Raise [Unix_error] otherwise. *)
* { 6 Operations on file descriptors }
val dup : file_descr -> file_descr
(** Return a new file descriptor referencing the same file as
the given descriptor. *)
val dup2 : src:file_descr -> dst:file_descr -> unit
(** [dup2 fd1 fd2] duplicates [fd1] to [fd2], closing [fd2] if already
opened. *)
val set_nonblock : file_descr -> unit
(** Set the ``non-blocking'' flag on the given descriptor.
When the non-blocking flag is set, reading on a descriptor
on which there is temporarily no data available raises the
[EAGAIN] or [EWOULDBLOCK] error instead of blocking;
writing on a descriptor on which there is temporarily no room
for writing also raises [EAGAIN] or [EWOULDBLOCK]. *)
val clear_nonblock : file_descr -> unit
* Clear the ` ` non - blocking '' flag on the given descriptor .
See { ! } .
See {!UnixLabels.set_nonblock}.*)
val set_close_on_exec : file_descr -> unit
(** Set the ``close-on-exec'' flag on the given descriptor.
A descriptor with the close-on-exec flag is automatically
closed when the current process starts another program with
one of the [exec] functions. *)
val clear_close_on_exec : file_descr -> unit
(** Clear the ``close-on-exec'' flag on the given descriptor.
See {!UnixLabels.set_close_on_exec}.*)
(** {6 Directories} *)
val mkdir : string -> perm:file_perm -> unit
(** Create a directory with the given permissions. *)
val rmdir : string -> unit
(** Remove an empty directory. *)
val chdir : string -> unit
(** Change the process working directory. *)
val getcwd : unit -> string
(** Return the name of the current working directory. *)
val chroot : string -> unit
(** Change the process root directory. *)
type dir_handle = Unix.dir_handle
(** The type of descriptors over opened directories. *)
val opendir : string -> dir_handle
(** Open a descriptor on a directory *)
val readdir : dir_handle -> string
(** Return the next entry in a directory.
@raise End_of_file when the end of the directory has been reached. *)
val rewinddir : dir_handle -> unit
(** Reposition the descriptor to the beginning of the directory *)
val closedir : dir_handle -> unit
(** Close a directory descriptor. *)
* { 6 Pipes and redirections }
val pipe : unit -> file_descr * file_descr
* Create a pipe . The first component of the result is opened
for reading , that 's the exit to the pipe . The second component is
opened for writing , that 's the entrance to the pipe .
for reading, that's the exit to the pipe. The second component is
opened for writing, that's the entrance to the pipe. *)
val mkfifo : string -> perm:file_perm -> unit
(** Create a named pipe with the given permissions. *)
* { 6 High - level process and redirection management }
val create_process :
prog:string -> args:string array -> stdin:file_descr -> stdout:file_descr ->
stderr:file_descr -> int
* [ create_process prog args new_stdin ]
forks a new process that executes the program
in file [ prog ] , with arguments [ args ] . The pid of the new
process is returned immediately ; the new process executes
concurrently with the current process .
The standard input and outputs of the new process are connected
to the descriptors [ new_stdin ] , [ new_stdout ] and [ new_stderr ] .
Passing e.g. [ stdout ] for [ new_stdout ] prevents the redirection
and causes the new process to have the same standard output
as the current process .
The executable file [ prog ] is searched in the path .
The new process has the same environment as the current process .
forks a new process that executes the program
in file [prog], with arguments [args]. The pid of the new
process is returned immediately; the new process executes
concurrently with the current process.
The standard input and outputs of the new process are connected
to the descriptors [new_stdin], [new_stdout] and [new_stderr].
Passing e.g. [stdout] for [new_stdout] prevents the redirection
and causes the new process to have the same standard output
as the current process.
The executable file [prog] is searched in the path.
The new process has the same environment as the current process. *)
val create_process_env :
prog:string -> args:string array -> env:string array -> stdin:file_descr ->
stdout:file_descr -> stderr:file_descr -> int
* [ create_process_env prog args env new_stdin new_stdout new_stderr ]
works as { ! UnixLabels.create_process } , except that the extra argument
[ env ] specifies the environment passed to the program .
works as {!UnixLabels.create_process}, except that the extra argument
[env] specifies the environment passed to the program. *)
val open_process_in : string -> in_channel
(** High-level pipe and process management. This function
runs the given command in parallel with the program.
The standard output of the command is redirected to a pipe,
which can be read via the returned input channel.
The command is interpreted by the shell [/bin/sh] (cf. [system]). *)
val open_process_out : string -> out_channel
* Same as { ! UnixLabels.open_process_in } , but redirect the standard input of
the command to a pipe . Data written to the returned output channel
is sent to the standard input of the command .
Warning : writes on output channels are buffered , hence be careful
to call { ! Pervasives.flush } at the right times to ensure
correct synchronization .
the command to a pipe. Data written to the returned output channel
is sent to the standard input of the command.
Warning: writes on output channels are buffered, hence be careful
to call {!Pervasives.flush} at the right times to ensure
correct synchronization. *)
val open_process : string -> in_channel * out_channel
* Same as { ! UnixLabels.open_process_out } , but redirects both the standard
input and standard output of the command to pipes connected to the two
returned channels . The input channel is connected to the output
of the command , and the output channel to the input of the command .
input and standard output of the command to pipes connected to the two
returned channels. The input channel is connected to the output
of the command, and the output channel to the input of the command. *)
val open_process_full :
string -> env:string array -> in_channel * out_channel * in_channel
* Similar to { ! UnixLabels.open_process } , but the second argument specifies
the environment passed to the command . The result is a triple
of channels connected respectively to the standard output , standard input ,
and standard error of the command .
the environment passed to the command. The result is a triple
of channels connected respectively to the standard output, standard input,
and standard error of the command. *)
val close_process_in : in_channel -> process_status
(** Close channels opened by {!UnixLabels.open_process_in},
wait for the associated command to terminate,
and return its termination status. *)
val close_process_out : out_channel -> process_status
(** Close channels opened by {!UnixLabels.open_process_out},
wait for the associated command to terminate,
and return its termination status. *)
val close_process : in_channel * out_channel -> process_status
(** Close channels opened by {!UnixLabels.open_process},
wait for the associated command to terminate,
and return its termination status. *)
val close_process_full :
in_channel * out_channel * in_channel -> process_status
(** Close channels opened by {!UnixLabels.open_process_full},
wait for the associated command to terminate,
and return its termination status. *)
* { 6 Symbolic links }
val symlink : src:string -> dst:string -> unit
(** [symlink source dest] creates the file [dest] as a symbolic link
to the file [source]. *)
val readlink : string -> string
(** Read the contents of a link. *)
* { 6 Polling }
val select :
read:file_descr list -> write:file_descr list -> except:file_descr list ->
timeout:float -> file_descr list * file_descr list * file_descr list
* Wait until some input / output operations become possible on
some channels . The three list arguments are , respectively , a set
of descriptors to check for reading ( first argument ) , for writing
( second argument ) , or for exceptional conditions ( third argument ) .
The fourth argument is the maximal timeout , in seconds ; a
negative fourth argument means no timeout ( unbounded wait ) .
The result is composed of three sets of descriptors : those ready
for reading ( first component ) , ready for writing ( second component ) ,
and over which an exceptional condition is pending ( third
component ) .
some channels. The three list arguments are, respectively, a set
of descriptors to check for reading (first argument), for writing
(second argument), or for exceptional conditions (third argument).
The fourth argument is the maximal timeout, in seconds; a
negative fourth argument means no timeout (unbounded wait).
The result is composed of three sets of descriptors: those ready
for reading (first component), ready for writing (second component),
and over which an exceptional condition is pending (third
component). *)
* { 6 Locking }
type lock_command = Unix.lock_command =
F_ULOCK (** Unlock a region *)
| F_LOCK (** Lock a region for writing, and block if already locked *)
| F_TLOCK (** Lock a region for writing, or fail if already locked *)
| F_TEST (** Test a region for other process locks *)
| F_RLOCK (** Lock a region for reading, and block if already locked *)
| F_TRLOCK (** Lock a region for reading, or fail if already locked *)
(** Commands for {!UnixLabels.lockf}. *)
val lockf : file_descr -> mode:lock_command -> len:int -> unit
* [ lockf fd cmd size ] puts a lock on a region of the file opened
as [ fd ] . The region starts at the current read / write position for
[ fd ] ( as set by { ! UnixLabels.lseek } ) , and extends [ size ] bytes forward if
[ size ] is positive , [ size ] bytes backwards if [ size ] is negative ,
or to the end of the file if [ size ] is zero .
A write lock prevents any other
process from acquiring a read or write lock on the region .
A read lock prevents any other
process from acquiring a write lock on the region , but lets
other processes acquire read locks on it .
The [ F_LOCK ] and [ F_TLOCK ] commands attempts to put a write lock
on the specified region .
The [ F_RLOCK ] and [ F_TRLOCK ] commands attempts to put a read lock
on the specified region .
If one or several locks put by another process prevent the current process
from acquiring the lock , [ F_LOCK ] and [ F_RLOCK ] block until these locks
are removed , while [ F_TLOCK ] and [ F_TRLOCK ] fail immediately with an
exception .
The [ F_ULOCK ] removes whatever locks the current process has on
the specified region .
Finally , the [ F_TEST ] command tests whether a write lock can be
acquired on the specified region , without actually putting a lock .
It returns immediately if successful , or fails otherwise .
as [fd]. The region starts at the current read/write position for
[fd] (as set by {!UnixLabels.lseek}), and extends [size] bytes forward if
[size] is positive, [size] bytes backwards if [size] is negative,
or to the end of the file if [size] is zero.
A write lock prevents any other
process from acquiring a read or write lock on the region.
A read lock prevents any other
process from acquiring a write lock on the region, but lets
other processes acquire read locks on it.
The [F_LOCK] and [F_TLOCK] commands attempts to put a write lock
on the specified region.
The [F_RLOCK] and [F_TRLOCK] commands attempts to put a read lock
on the specified region.
If one or several locks put by another process prevent the current process
from acquiring the lock, [F_LOCK] and [F_RLOCK] block until these locks
are removed, while [F_TLOCK] and [F_TRLOCK] fail immediately with an
exception.
The [F_ULOCK] removes whatever locks the current process has on
the specified region.
Finally, the [F_TEST] command tests whether a write lock can be
acquired on the specified region, without actually putting a lock.
It returns immediately if successful, or fails otherwise. *)
* { 6 Signals }
Note : installation of signal handlers is performed via
the functions { ! Sys.signal } and { ! Sys.set_signal } .
Note: installation of signal handlers is performed via
the functions {!Sys.signal} and {!Sys.set_signal}.
*)
val kill : pid:int -> signal:int -> unit
(** [kill pid sig] sends signal number [sig] to the process
with id [pid]. *)
type sigprocmask_command = Unix.sigprocmask_command =
SIG_SETMASK
| SIG_BLOCK
| SIG_UNBLOCK
val sigprocmask : mode:sigprocmask_command -> int list -> int list
* [ sigprocmask cmd sigs ] changes the set of blocked signals .
If [ cmd ] is [ SIG_SETMASK ] , blocked signals are set to those in
the list [ ] .
If [ cmd ] is [ SIG_BLOCK ] , the signals in [ sigs ] are added to
the set of blocked signals .
If [ cmd ] is [ SIG_UNBLOCK ] , the signals in [ sigs ] are removed
from the set of blocked signals .
[ sigprocmask ] returns the set of previously blocked signals .
If [cmd] is [SIG_SETMASK], blocked signals are set to those in
the list [sigs].
If [cmd] is [SIG_BLOCK], the signals in [sigs] are added to
the set of blocked signals.
If [cmd] is [SIG_UNBLOCK], the signals in [sigs] are removed
from the set of blocked signals.
[sigprocmask] returns the set of previously blocked signals. *)
val sigpending : unit -> int list
(** Return the set of blocked signals that are currently pending. *)
val sigsuspend : int list -> unit
(** [sigsuspend sigs] atomically sets the blocked signals to [sigs]
and waits for a non-ignored, non-blocked signal to be delivered.
On return, the blocked signals are reset to their initial value. *)
val pause : unit -> unit
(** Wait until a non-ignored, non-blocked signal is delivered. *)
* { 6 Time functions }
type process_times = Unix.process_times =
{ tms_utime : float; (** User time for the process *)
tms_stime : float; (** System time for the process *)
tms_cutime : float; (** User time for the children processes *)
tms_cstime : float; (** System time for the children processes *)
}
(** The execution times (CPU times) of a process. *)
type tm = Unix.tm =
* Seconds 0 .. 60
* Minutes 0 .. 59
* Hours 0 .. 23
tm_mday : int; (** Day of month 1..31 *)
* Month of year 0 .. 11
* Year - 1900
* Day of week ( Sunday is 0 )
tm_yday : int; (** Day of year 0..365 *)
tm_isdst : bool; (** Daylight time savings in effect *)
}
(** The type representing wallclock time and calendar date. *)
val time : unit -> float
* Return the current time since 00:00:00 GMT , Jan. 1 , 1970 ,
in seconds .
in seconds. *)
val gettimeofday : unit -> float
(** Same as {!UnixLabels.time}, but with resolution better than 1 second. *)
val gmtime : float -> tm
* Convert a time in seconds , as returned by { ! UnixLabels.time } , into a date
and a time . Assumes UTC ( Coordinated Universal Time ) , also known as GMT .
and a time. Assumes UTC (Coordinated Universal Time), also known as GMT. *)
val localtime : float -> tm
* Convert a time in seconds , as returned by { ! UnixLabels.time } , into a date
and a time . Assumes the local time zone .
and a time. Assumes the local time zone. *)
val mktime : tm -> float * tm
* Convert a date and time , specified by the [ tm ] argument , into
a time in seconds , as returned by { ! UnixLabels.time } . The [ tm_isdst ] ,
[ tm_wday ] and [ tm_yday ] fields of [ tm ] are ignored . Also return a
normalized copy of the given [ tm ] record , with the [ tm_wday ] ,
[ tm_yday ] , and [ tm_isdst ] fields recomputed from the other fields ,
and the other fields normalized ( so that , e.g. , 40 October is
changed into 9 November ) . The [ tm ] argument is interpreted in the
local time zone .
a time in seconds, as returned by {!UnixLabels.time}. The [tm_isdst],
[tm_wday] and [tm_yday] fields of [tm] are ignored. Also return a
normalized copy of the given [tm] record, with the [tm_wday],
[tm_yday], and [tm_isdst] fields recomputed from the other fields,
and the other fields normalized (so that, e.g., 40 October is
changed into 9 November). The [tm] argument is interpreted in the
local time zone. *)
val alarm : int -> int
* Schedule a [ SIGALRM ] signal after the given number of seconds .
val sleep : int -> unit
(** Stop execution for the given number of seconds. *)
val times : unit -> process_times
(** Return the execution times of the process. *)
val utimes : string -> access:float -> modif:float -> unit
* Set the last access time ( second arg ) and last modification time
( third arg ) for a file . Times are expressed in seconds from
00:00:00 GMT , Jan. 1 , 1970 .
(third arg) for a file. Times are expressed in seconds from
00:00:00 GMT, Jan. 1, 1970. *)
type interval_timer = Unix.interval_timer =
ITIMER_REAL
* decrements in real time , and sends the signal [ SIGALRM ] when expired .
| ITIMER_VIRTUAL
* decrements in process virtual time , and sends [ SIGVTALRM ] when expired .
| ITIMER_PROF
(** (for profiling) decrements both when the process
is running and when the system is running on behalf of the
process; it sends [SIGPROF] when expired. *)
* The three kinds of interval timers .
type interval_timer_status = Unix.interval_timer_status =
{ it_interval : float; (** Period *)
it_value : float; (** Current value of the timer *)
}
(** The type describing the status of an interval timer *)
val getitimer : interval_timer -> interval_timer_status
(** Return the current status of the given interval timer. *)
val setitimer :
interval_timer -> interval_timer_status -> interval_timer_status
* [ setitimer t s ] sets the interval timer [ t ] and returns
its previous status . The [ s ] argument is interpreted as follows :
[ s.it_value ] , if nonzero , is the time to the next timer expiration ;
[ s.it_interval ] , if nonzero , specifies a value to
be used in reloading it_value when the timer expires .
Setting [ s.it_value ] to zero disable the timer .
Setting [ s.it_interval ] to zero causes the timer to be disabled
after its next expiration .
its previous status. The [s] argument is interpreted as follows:
[s.it_value], if nonzero, is the time to the next timer expiration;
[s.it_interval], if nonzero, specifies a value to
be used in reloading it_value when the timer expires.
Setting [s.it_value] to zero disable the timer.
Setting [s.it_interval] to zero causes the timer to be disabled
after its next expiration. *)
* { 6 User i d , group i d }
val getuid : unit -> int
(** Return the user id of the user executing the process. *)
val geteuid : unit -> int
(** Return the effective user id under which the process runs. *)
val setuid : int -> unit
(** Set the real user id and effective user id for the process. *)
val getgid : unit -> int
(** Return the group id of the user executing the process. *)
val getegid : unit -> int
(** Return the effective group id under which the process runs. *)
val setgid : int -> unit
(** Set the real group id and effective group id for the process. *)
val getgroups : unit -> int array
(** Return the list of groups to which the user executing the process
belongs. *)
type passwd_entry = Unix.passwd_entry =
{ pw_name : string;
pw_passwd : string;
pw_uid : int;
pw_gid : int;
pw_gecos : string;
pw_dir : string;
pw_shell : string
}
(** Structure of entries in the [passwd] database. *)
type group_entry = Unix.group_entry =
{ gr_name : string;
gr_passwd : string;
gr_gid : int;
gr_mem : string array
}
(** Structure of entries in the [groups] database. *)
val getlogin : unit -> string
(** Return the login name of the user executing the process. *)
val getpwnam : string -> passwd_entry
(** Find an entry in [passwd] with the given name, or raise
[Not_found]. *)
val getgrnam : string -> group_entry
(** Find an entry in [group] with the given name, or raise
[Not_found]. *)
val getpwuid : int -> passwd_entry
(** Find an entry in [passwd] with the given user id, or raise
[Not_found]. *)
val getgrgid : int -> group_entry
(** Find an entry in [group] with the given group id, or raise
[Not_found]. *)
* { 6 Internet addresses }
type inet_addr = Unix.inet_addr
(** The abstract type of Internet addresses. *)
val inet_addr_of_string : string -> inet_addr
* Conversion from the printable representation of an Internet
address to its internal representation . The argument string
consists of 4 numbers separated by periods ( [ XXX.YYY.ZZZ.TTT ] )
for IPv4 addresses , and up to 8 numbers separated by colons
for IPv6 addresses . Raise [ Failure ] when given a string that
does not match these formats .
address to its internal representation. The argument string
consists of 4 numbers separated by periods ([XXX.YYY.ZZZ.TTT])
for IPv4 addresses, and up to 8 numbers separated by colons
for IPv6 addresses. Raise [Failure] when given a string that
does not match these formats. *)
val string_of_inet_addr : inet_addr -> string
(** Return the printable representation of the given Internet address.
See {!Unix.inet_addr_of_string} for a description of the
printable representation. *)
val inet_addr_any : inet_addr
* A special IPv4 address , for use only with [ bind ] , representing
all the Internet addresses that the host machine possesses .
all the Internet addresses that the host machine possesses. *)
val inet_addr_loopback : inet_addr
* A special IPv4 address representing the host machine ( [ 127.0.0.1 ] ) .
val inet6_addr_any : inet_addr
(** A special IPv6 address, for use only with [bind], representing
all the Internet addresses that the host machine possesses. *)
val inet6_addr_loopback : inet_addr
(** A special IPv6 address representing the host machine ([::1]). *)
* { 6 Sockets }
type socket_domain = Unix.socket_domain =
PF_UNIX (** Unix domain *)
| PF_INET (** Internet domain (IPv4) *)
| PF_INET6 (** Internet domain (IPv6) *)
(** The type of socket domains. *)
type socket_type = Unix.socket_type =
SOCK_STREAM (** Stream socket *)
| SOCK_DGRAM (** Datagram socket *)
| SOCK_RAW (** Raw socket *)
| SOCK_SEQPACKET (** Sequenced packets socket *)
(** The type of socket kinds, specifying the semantics of
communications. *)
type sockaddr = Unix.sockaddr =
ADDR_UNIX of string
| ADDR_INET of inet_addr * int
* The type of socket addresses . [ ADDR_UNIX name ] is a socket
address in the Unix domain ; [ name ] is a file name in the file
system . [ ADDR_INET(addr , port ) ] is a socket address in the Internet
domain ; [ addr ] is the Internet address of the machine , and
[ port ] is the port number .
address in the Unix domain; [name] is a file name in the file
system. [ADDR_INET(addr,port)] is a socket address in the Internet
domain; [addr] is the Internet address of the machine, and
[port] is the port number. *)
val socket :
domain:socket_domain -> kind:socket_type -> protocol:int -> file_descr
* Create a new socket in the given domain , and with the
given kind . The third argument is the protocol type ; 0 selects
the default protocol for that kind of sockets .
given kind. The third argument is the protocol type; 0 selects
the default protocol for that kind of sockets. *)
val domain_of_sockaddr: sockaddr -> socket_domain
(** Return the socket domain adequate for the given socket address. *)
val socketpair :
domain:socket_domain -> kind:socket_type -> protocol:int ->
file_descr * file_descr
(** Create a pair of unnamed sockets, connected together. *)
val accept : file_descr -> file_descr * sockaddr
(** Accept connections on the given socket. The returned descriptor
is a socket connected to the client; the returned address is
the address of the connecting client. *)
val bind : file_descr -> addr:sockaddr -> unit
(** Bind a socket to an address. *)
val connect : file_descr -> addr:sockaddr -> unit
(** Connect a socket to an address. *)
val listen : file_descr -> max:int -> unit
(** Set up a socket for receiving connection requests. The integer
argument is the maximal number of pending requests. *)
type shutdown_command = Unix.shutdown_command =
SHUTDOWN_RECEIVE (** Close for receiving *)
| SHUTDOWN_SEND (** Close for sending *)
| SHUTDOWN_ALL (** Close both *)
(** The type of commands for [shutdown]. *)
val shutdown : file_descr -> mode:shutdown_command -> unit
* Shutdown a socket connection . [ SHUTDOWN_SEND ] as second argument
causes reads on the other end of the connection to return
an end - of - file condition .
[ SHUTDOWN_RECEIVE ] causes writes on the other end of the connection
to return a closed pipe condition ( [ ] signal ) .
causes reads on the other end of the connection to return
an end-of-file condition.
[SHUTDOWN_RECEIVE] causes writes on the other end of the connection
to return a closed pipe condition ([SIGPIPE] signal). *)
val getsockname : file_descr -> sockaddr
(** Return the address of the given socket. *)
val getpeername : file_descr -> sockaddr
(** Return the address of the host connected to the given socket. *)
type msg_flag = Unix.msg_flag =
MSG_OOB
| MSG_DONTROUTE
| MSG_PEEK
(** The flags for {!UnixLabels.recv}, {!UnixLabels.recvfrom},
{!UnixLabels.send} and {!UnixLabels.sendto}. *)
val recv :
file_descr -> buf:string -> pos:int -> len:int -> mode:msg_flag list -> int
(** Receive data from a connected socket. *)
val recvfrom :
file_descr -> buf:string -> pos:int -> len:int -> mode:msg_flag list ->
int * sockaddr
(** Receive data from an unconnected socket. *)
val send :
file_descr -> buf:string -> pos:int -> len:int -> mode:msg_flag list -> int
(** Send data over a connected socket. *)
val sendto :
file_descr -> buf:string -> pos:int -> len:int -> mode:msg_flag list ->
addr:sockaddr -> int
(** Send data over an unconnected socket. *)
* { 6 Socket options }
type socket_bool_option =
SO_DEBUG (** Record debugging information *)
| SO_BROADCAST (** Permit sending of broadcast messages *)
| SO_REUSEADDR (** Allow reuse of local addresses for bind *)
| SO_KEEPALIVE (** Keep connection active *)
| SO_DONTROUTE (** Bypass the standard routing algorithms *)
| SO_OOBINLINE (** Leave out-of-band data in line *)
| SO_ACCEPTCONN (** Report whether socket listening is enabled *)
(** The socket options that can be consulted with {!UnixLabels.getsockopt}
and modified with {!UnixLabels.setsockopt}. These options have a boolean
([true]/[false]) value. *)
type socket_int_option =
SO_SNDBUF (** Size of send buffer *)
| SO_RCVBUF (** Size of received buffer *)
| SO_ERROR (** Report the error status and clear it *)
| SO_TYPE (** Report the socket type *)
| SO_RCVLOWAT (** Minimum number of bytes to process for input operations *)
| SO_SNDLOWAT (** Minimum number of bytes to process for output operations *)
(** The socket options that can be consulted with {!UnixLabels.getsockopt_int}
and modified with {!UnixLabels.setsockopt_int}. These options have an
integer value. *)
type socket_optint_option =
* Whether to linger on closed connections
that have data present , and for how long
( in seconds )
that have data present, and for how long
(in seconds) *)
(** The socket options that can be consulted with {!Unix.getsockopt_optint}
and modified with {!Unix.setsockopt_optint}. These options have a
value of type [int option], with [None] meaning ``disabled''. *)
type socket_float_option =
SO_RCVTIMEO (** Timeout for input operations *)
| SO_SNDTIMEO (** Timeout for output operations *)
* The socket options that can be consulted with { ! UnixLabels.getsockopt_float }
and modified with { ! UnixLabels.setsockopt_float } . These options have a
floating - point value representing a time in seconds .
The value 0 means infinite timeout .
and modified with {!UnixLabels.setsockopt_float}. These options have a
floating-point value representing a time in seconds.
The value 0 means infinite timeout. *)
val getsockopt : file_descr -> socket_bool_option -> bool
(** Return the current status of a boolean-valued option
in the given socket. *)
val setsockopt : file_descr -> socket_bool_option -> bool -> unit
(** Set or clear a boolean-valued option in the given socket. *)
external getsockopt_int :
file_descr -> socket_int_option -> int = "unix_getsockopt_int"
(** Same as {!UnixLabels.getsockopt} for an integer-valued socket option. *)
external setsockopt_int :
file_descr -> socket_int_option -> int -> unit = "unix_setsockopt_int"
(** Same as {!UnixLabels.setsockopt} for an integer-valued socket option. *)
external getsockopt_optint :
file_descr -> socket_optint_option -> int option = "unix_getsockopt_optint"
(** Same as {!UnixLabels.getsockopt} for a socket option whose value is an [int option]. *)
external setsockopt_optint :
file_descr -> socket_optint_option -> int option ->
unit = "unix_setsockopt_optint"
(** Same as {!UnixLabels.setsockopt} for a socket option whose value is an [int option]. *)
external getsockopt_float :
file_descr -> socket_float_option -> float = "unix_getsockopt_float"
(** Same as {!UnixLabels.getsockopt} for a socket option whose value is a floating-point number. *)
external setsockopt_float :
file_descr -> socket_float_option -> float -> unit = "unix_setsockopt_float"
(** Same as {!UnixLabels.setsockopt} for a socket option whose value is a floating-point number. *)
* { 6 High - level network connection functions }
val open_connection : sockaddr -> in_channel * out_channel
(** Connect to a server at the given address.
Return a pair of buffered channels connected to the server.
Remember to call {!Pervasives.flush} on the output channel at the right
times to ensure correct synchronization. *)
val shutdown_connection : in_channel -> unit
(** ``Shut down'' a connection established with {!UnixLabels.open_connection};
that is, transmit an end-of-file condition to the server reading
on the other side of the connection. *)
val establish_server :
(in_channel -> out_channel -> unit) -> addr:sockaddr -> unit
* Establish a server on the given address .
The function given as first argument is called for each connection
with two buffered channels connected to the client . A new process
is created for each connection . The function { ! UnixLabels.establish_server }
never returns normally .
The function given as first argument is called for each connection
with two buffered channels connected to the client. A new process
is created for each connection. The function {!UnixLabels.establish_server}
never returns normally. *)
* { 6 Host and protocol databases }
type host_entry = Unix.host_entry =
{ h_name : string;
h_aliases : string array;
h_addrtype : socket_domain;
h_addr_list : inet_addr array
}
(** Structure of entries in the [hosts] database. *)
type protocol_entry = Unix.protocol_entry =
{ p_name : string;
p_aliases : string array;
p_proto : int
}
(** Structure of entries in the [protocols] database. *)
type service_entry = Unix.service_entry =
{ s_name : string;
s_aliases : string array;
s_port : int;
s_proto : string
}
(** Structure of entries in the [services] database. *)
val gethostname : unit -> string
(** Return the name of the local host. *)
val gethostbyname : string -> host_entry
(** Find an entry in [hosts] with the given name, or raise
[Not_found]. *)
val gethostbyaddr : inet_addr -> host_entry
(** Find an entry in [hosts] with the given address, or raise
[Not_found]. *)
val getprotobyname : string -> protocol_entry
(** Find an entry in [protocols] with the given name, or raise
[Not_found]. *)
val getprotobynumber : int -> protocol_entry
(** Find an entry in [protocols] with the given protocol number,
or raise [Not_found]. *)
val getservbyname : string -> protocol:string -> service_entry
(** Find an entry in [services] with the given name, or raise
[Not_found]. *)
val getservbyport : int -> protocol:string -> service_entry
(** Find an entry in [services] with the given service number,
or raise [Not_found]. *)
type addr_info =
{ ai_family : socket_domain; (** Socket domain *)
ai_socktype : socket_type; (** Socket type *)
ai_protocol : int; (** Socket protocol number *)
ai_addr : sockaddr; (** Address *)
ai_canonname : string (** Canonical host name *)
}
(** Address information returned by {!Unix.getaddrinfo}. *)
type getaddrinfo_option =
AI_FAMILY of socket_domain (** Impose the given socket domain *)
| AI_SOCKTYPE of socket_type (** Impose the given socket type *)
| AI_PROTOCOL of int (** Impose the given protocol *)
| AI_NUMERICHOST (** Do not call name resolver,
expect numeric IP address *)
| AI_CANONNAME (** Fill the [ai_canonname] field
of the result *)
| AI_PASSIVE (** Set address to ``any'' address
for use with {!Unix.bind} *)
(** Options to {!Unix.getaddrinfo}. *)
val getaddrinfo:
string -> string -> getaddrinfo_option list -> addr_info list
* [ host service opts ] returns a list of { ! Unix.addr_info }
records describing socket parameters and addresses suitable for
communicating with the given host and service . The empty list is
returned if the host or service names are unknown , or the constraints
expressed in [ opts ] can not be satisfied .
[ host ] is either a host name or the string representation of an IP
address . [ host ] can be given as the empty string ; in this case ,
the ` ` any '' address or the ` ` loopback '' address are used ,
depending whether [ opts ] contains [ AI_PASSIVE ] .
[ service ] is either a service name or the string representation of
a port number . [ service ] can be given as the empty string ;
in this case , the port field of the returned addresses is set to 0 .
[ opts ] is a possibly empty list of options that allows the caller
to force a particular socket domain ( e.g. IPv6 only or IPv4 only )
or a particular socket type ( e.g. TCP only or UDP only ) .
records describing socket parameters and addresses suitable for
communicating with the given host and service. The empty list is
returned if the host or service names are unknown, or the constraints
expressed in [opts] cannot be satisfied.
[host] is either a host name or the string representation of an IP
address. [host] can be given as the empty string; in this case,
the ``any'' address or the ``loopback'' address are used,
depending whether [opts] contains [AI_PASSIVE].
[service] is either a service name or the string representation of
a port number. [service] can be given as the empty string;
in this case, the port field of the returned addresses is set to 0.
[opts] is a possibly empty list of options that allows the caller
to force a particular socket domain (e.g. IPv6 only or IPv4 only)
or a particular socket type (e.g. TCP only or UDP only). *)
type name_info =
{ ni_hostname : string; (** Name or IP address of host *)
ni_service : string } (** Name of service or port number *)
(** Host and service information returned by {!Unix.getnameinfo}. *)
type getnameinfo_option =
NI_NOFQDN (** Do not qualify local host names *)
| NI_NUMERICHOST (** Always return host as IP address *)
| NI_NAMEREQD (** Fail if host name cannot be determined *)
| NI_NUMERICSERV (** Always return service as port number *)
* Consider the service as UDP - based
instead of the default TCP
instead of the default TCP *)
(** Options to {!Unix.getnameinfo}. *)
val getnameinfo : sockaddr -> getnameinfo_option list -> name_info
* [ getnameinfo opts ] returns the host name and service name
corresponding to the socket address [ addr ] . [ opts ] is a possibly
empty list of options that governs how these names are obtained .
Raise [ Not_found ] if an error occurs .
corresponding to the socket address [addr]. [opts] is a possibly
empty list of options that governs how these names are obtained.
Raise [Not_found] if an error occurs. *)
* { 6 Terminal interface }
(** The following functions implement the POSIX standard terminal
interface. They provide control over asynchronous communication ports
and pseudo-terminals. Refer to the [termios] man page for a
complete description. *)
type terminal_io = Unix.terminal_io =
{
(* input modes *)
mutable c_ignbrk : bool; (** Ignore the break condition. *)
mutable c_brkint : bool; (** Signal interrupt on break condition. *)
mutable c_ignpar : bool; (** Ignore characters with parity errors. *)
* parity errors .
mutable c_inpck : bool; (** Enable parity check on input. *)
mutable c_istrip : bool; (** Strip 8th bit on input characters. *)
* Map NL to CR on input .
mutable c_igncr : bool; (** Ignore CR on input. *)
* Map CR to NL on input .
mutable c_ixon : bool; (** Recognize XON/XOFF characters on input. *)
mutable c_ixoff : bool; (** Emit XON/XOFF chars to control input flow. *)
(* Output modes: *)
mutable c_opost : bool; (** Enable output processing. *)
(* Control modes: *)
mutable c_obaud : int; (** Output baud rate (0 means close connection).*)
mutable c_ibaud : int; (** Input baud rate. *)
mutable c_csize : int; (** Number of bits per character (5-8). *)
* Number of stop bits ( 1 - 2 ) .
mutable c_cread : bool; (** Reception is enabled. *)
mutable c_parenb : bool; (** Enable parity generation and detection. *)
mutable c_parodd : bool; (** Specify odd parity instead of even. *)
mutable c_hupcl : bool; (** Hang up on last close. *)
mutable c_clocal : bool; (** Ignore modem status lines. *)
(* Local modes: *)
* Generate signal on INTR , QUIT , SUSP .
mutable c_icanon : bool; (** Enable canonical processing
(line buffering and editing) *)
* Disable flush after INTR , QUIT , SUSP .
mutable c_echo : bool; (** Echo input characters. *)
mutable c_echoe : bool; (** Echo ERASE (to erase previous character). *)
mutable c_echok : bool; (** Echo KILL (to erase the current line). *)
* Echo NL even if c_echo is not set .
(* Control characters: *)
mutable c_vintr : char; (** Interrupt character (usually ctrl-C). *)
mutable c_vquit : char; (** Quit character (usually ctrl-\). *)
* Erase character ( usually DEL or ctrl - H ) .
mutable c_vkill : char; (** Kill line character (usually ctrl-U). *)
mutable c_veof : char; (** End-of-file character (usually ctrl-D). *)
mutable c_veol : char; (** Alternate end-of-line char. (usually none). *)
mutable c_vmin : int; (** Minimum number of characters to read
before the read request is satisfied. *)
* Maximum read wait ( in 0.1s units ) .
mutable c_vstart : char; (** Start character (usually ctrl-Q). *)
mutable c_vstop : char; (** Stop character (usually ctrl-S). *)
}
val tcgetattr : file_descr -> terminal_io
(** Return the status of the terminal referred to by the given
file descriptor. *)
type setattr_when = Unix.setattr_when =
TCSANOW
| TCSADRAIN
| TCSAFLUSH
val tcsetattr : file_descr -> mode:setattr_when -> terminal_io -> unit
* Set the status of the terminal referred to by the given
file descriptor . The second argument indicates when the
status change takes place : immediately ( [ TCSANOW ] ) ,
when all pending output has been transmitted ( [ TCSADRAIN ] ) ,
or after flushing all input that has been received but not
read ( [ TCSAFLUSH ] ) . [ TCSADRAIN ] is recommended when changing
the output parameters ; [ TCSAFLUSH ] , when changing the input
parameters .
file descriptor. The second argument indicates when the
status change takes place: immediately ([TCSANOW]),
when all pending output has been transmitted ([TCSADRAIN]),
or after flushing all input that has been received but not
read ([TCSAFLUSH]). [TCSADRAIN] is recommended when changing
the output parameters; [TCSAFLUSH], when changing the input
parameters. *)
val tcsendbreak : file_descr -> duration:int -> unit
* Send a break condition on the given file descriptor .
The second argument is the duration of the break , in 0.1s units ;
0 means standard duration ( 0.25s ) .
The second argument is the duration of the break, in 0.1s units;
0 means standard duration (0.25s). *)
val tcdrain : file_descr -> unit
(** Waits until all output written on the given file descriptor
has been transmitted. *)
type flush_queue = Unix.flush_queue =
TCIFLUSH
| TCOFLUSH
| TCIOFLUSH
val tcflush : file_descr -> mode:flush_queue -> unit
* Discard data written on the given file descriptor but not yet
transmitted , or data received but not yet read , depending on the
second argument : [ TCIFLUSH ] flushes data received but not read ,
[ TCOFLUSH ] flushes data written but not transmitted , and
[ TCIOFLUSH ] flushes both .
transmitted, or data received but not yet read, depending on the
second argument: [TCIFLUSH] flushes data received but not read,
[TCOFLUSH] flushes data written but not transmitted, and
[TCIOFLUSH] flushes both. *)
type flow_action = Unix.flow_action =
TCOOFF
| TCOON
| TCIOFF
| TCION
val tcflow : file_descr -> mode:flow_action -> unit
* Suspend or restart reception or transmission of data on
the given file descriptor , depending on the second argument :
[ TCOOFF ] suspends output , [ TCOON ] restarts output ,
[ TCIOFF ] transmits a STOP character to suspend input ,
and [ TCION ] transmits a START character to restart input .
the given file descriptor, depending on the second argument:
[TCOOFF] suspends output, [TCOON] restarts output,
[TCIOFF] transmits a STOP character to suspend input,
and [TCION] transmits a START character to restart input. *)
val setsid : unit -> int
(** Put the calling process in a new session and detach it from
its controlling terminal. *)
| null | https://raw.githubusercontent.com/ucsd-progsys/nate/8b1267cd8b10283d8bc239d16a28c654a4cb8942/eval/sherrloc/easyocaml%2B%2B/otherlibs/unix/unixLabels.mli | ocaml | *********************************************************************
Objective Caml
the special exception on linking described in file ../../LICENSE.
*********************************************************************
* Argument list too long
* Permission denied
* Resource temporarily unavailable; try again
* Bad file descriptor
* Resource unavailable
* No child process
* Resource deadlock would occur
* Domain error for math functions, etc.
* File exists
* Bad address
* File too large
* Function interrupted by signal
* Invalid argument
* Hardware I/O error
* Is a directory
* Too many open files by the process
* Too many links
* Filename too long
* Too many open files in the system
* No such device
* No such file or directory
* Not an executable file
* No locks available
* Not enough memory
* No space left on device
* Function not supported
* Not a directory
* Directory not empty
* Inappropriate I/O control operation
* No such device or address
* Operation not permitted
* Broken pipe
* Result too large
* Read-only file system
* Invalid seek e.g. on a pipe
* No such process
* Invalid link
* Operation would block
* Operation now in progress
* Operation already in progress
* Socket operation on non-socket
* Destination address required
* Message too long
* Protocol wrong type for socket
* Protocol not available
* Protocol not supported
* Socket type not supported
* Operation not supported on socket
* Protocol family not supported
* Address family not supported by protocol family
* Address already in use
* Can't assign requested address
* Network is down
* Network is unreachable
* Network dropped connection on reset
* Software caused connection abort
* Connection reset by peer
* No buffer space available
* Socket is already connected
* Socket is not connected
* Can't send after socket shutdown
* Too many references: can't splice
* Connection timed out
* Connection refused
* Host is down
* No route to host
* Too many levels of symbolic links
* File size or position not representable
* Unknown error
* Return a string describing the given error code.
* Return the process environment, as an array of strings
with the format ``variable=value''.
* Return the value associated to a variable in the process
environment. Raise [Not_found] if the variable is unbound.
(This function is identical to [Sys.getenv].)
* The process terminated normally by [exit];
the argument is the return code.
* The process was killed by a signal;
the argument is the signal number.
* The process was stopped by a signal; the argument is the
signal number.
* The termination status of a process.
* report also the children that receive stop signals.
* Flags for {!Unix.waitpid}.
* Same as {!UnixLabels.execv} respectively, except that
the program is searched in the path.
* Fork a new process. The returned integer is 0 for the child
process, the pid of the child process for the parent process.
* Same as {!UnixLabels.wait}, but waits for the process whose pid is given.
A pid of [-1] means wait for any child.
A pid of [0] means wait for any child in the same process group
as the current process.
Negative pid arguments represent process groups.
The list of options indicates whether [waitpid] should return
immediately without waiting, or also report stopped children.
* Return the pid of the process.
* Return the pid of the parent process.
* Change the process priority. The integer argument is added to the
``nice'' value. (Higher values of the ``nice'' value mean
lower priorities.) Return the new nice value.
* The abstract type of file descriptors.
* File descriptor for standard input.
* File descriptor for standard output.
* File descriptor for standard error.
* Open for reading
* Open for writing
* Open for reading and writing
* Open in non-blocking mode
* Open for append
* Create if nonexistent
* Fail if existing
* Don't make this dev a controlling tty
* Writes complete as `Synchronised I/O data integrity completion'
* Writes complete as `Synchronised I/O file integrity completion'
* Reads complete as writes (depending on O_SYNC/O_DSYNC)
* The flags to {!UnixLabels.openfile}.
* Close a file descriptor.
* Same as [write], but attempts to write only once.
Thus, if an error occurs, [single_write] guarantees that no data
has been written.
* Create an input channel reading from the given descriptor.
The channel is initially in binary mode; use
[set_binary_mode_in ic false] if text mode is desired.
* Create an output channel writing on the given descriptor.
The channel is initially in binary mode; use
[set_binary_mode_out oc false] if text mode is desired.
* Return the descriptor corresponding to an input channel.
* Return the descriptor corresponding to an output channel.
* indicates positions relative to the beginning of the file
* indicates positions relative to the current position
* indicates positions relative to the end of the file
* Positioning modes for {!UnixLabels.lseek}.
* Set the current position for a file descriptor
* Truncates the named file to the given size.
* Truncates the file corresponding to the given descriptor
to the given size.
* Regular file
* Directory
* Character device
* Block device
* Symbolic link
* Named pipe
* Socket
* Device number
* Kind of the file
* Access rights
* Number of links
* User id of the owner
* Group ID of the file's group
* Device minor number
* Size in bytes
* Last access time
* Last modification time
* Last status change time
* The informations returned by the {!UnixLabels.stat} calls.
* Return the information for the named file.
* Same as {!UnixLabels.stat}, but in case the file is a symbolic link,
return the information for the link itself.
* Return the information for the file associated with the given
descriptor.
* Return [true] if the given file descriptor refers to a terminal or
console window, [false] otherwise.
* Device number
* Kind of the file
* Access rights
* Number of links
* User id of the owner
* Group ID of the file's group
* Device minor number
* Size in bytes
* Last access time
* Last modification time
* Last status change time
* Removes the named file
* [rename old new] changes the name of a file from [old] to [new].
* [link source dest] creates a hard link named [dest] to the file
named [source].
* Read permission
* Write permission
* Execution permission
* File exists
* Flags for the {!UnixLabels.access} call.
* Change the permissions of the named file.
* Change the permissions of an opened file.
* Set the process's file mode creation mask, and return the previous
mask.
* Check that the process has the given permissions over the named
file. Raise [Unix_error] otherwise.
* Return a new file descriptor referencing the same file as
the given descriptor.
* [dup2 fd1 fd2] duplicates [fd1] to [fd2], closing [fd2] if already
opened.
* Set the ``non-blocking'' flag on the given descriptor.
When the non-blocking flag is set, reading on a descriptor
on which there is temporarily no data available raises the
[EAGAIN] or [EWOULDBLOCK] error instead of blocking;
writing on a descriptor on which there is temporarily no room
for writing also raises [EAGAIN] or [EWOULDBLOCK].
* Set the ``close-on-exec'' flag on the given descriptor.
A descriptor with the close-on-exec flag is automatically
closed when the current process starts another program with
one of the [exec] functions.
* Clear the ``close-on-exec'' flag on the given descriptor.
See {!UnixLabels.set_close_on_exec}.
* {6 Directories}
* Create a directory with the given permissions.
* Remove an empty directory.
* Change the process working directory.
* Return the name of the current working directory.
* Change the process root directory.
* The type of descriptors over opened directories.
* Open a descriptor on a directory
* Return the next entry in a directory.
@raise End_of_file when the end of the directory has been reached.
* Reposition the descriptor to the beginning of the directory
* Close a directory descriptor.
* Create a named pipe with the given permissions.
* High-level pipe and process management. This function
runs the given command in parallel with the program.
The standard output of the command is redirected to a pipe,
which can be read via the returned input channel.
The command is interpreted by the shell [/bin/sh] (cf. [system]).
* Close channels opened by {!UnixLabels.open_process_in},
wait for the associated command to terminate,
and return its termination status.
* Close channels opened by {!UnixLabels.open_process_out},
wait for the associated command to terminate,
and return its termination status.
* Close channels opened by {!UnixLabels.open_process},
wait for the associated command to terminate,
and return its termination status.
* Close channels opened by {!UnixLabels.open_process_full},
wait for the associated command to terminate,
and return its termination status.
* [symlink source dest] creates the file [dest] as a symbolic link
to the file [source].
* Read the contents of a link.
* Unlock a region
* Lock a region for writing, and block if already locked
* Lock a region for writing, or fail if already locked
* Test a region for other process locks
* Lock a region for reading, and block if already locked
* Lock a region for reading, or fail if already locked
* Commands for {!UnixLabels.lockf}.
* [kill pid sig] sends signal number [sig] to the process
with id [pid].
* Return the set of blocked signals that are currently pending.
* [sigsuspend sigs] atomically sets the blocked signals to [sigs]
and waits for a non-ignored, non-blocked signal to be delivered.
On return, the blocked signals are reset to their initial value.
* Wait until a non-ignored, non-blocked signal is delivered.
* User time for the process
* System time for the process
* User time for the children processes
* System time for the children processes
* The execution times (CPU times) of a process.
* Day of month 1..31
* Day of year 0..365
* Daylight time savings in effect
* The type representing wallclock time and calendar date.
* Same as {!UnixLabels.time}, but with resolution better than 1 second.
* Stop execution for the given number of seconds.
* Return the execution times of the process.
* (for profiling) decrements both when the process
is running and when the system is running on behalf of the
process; it sends [SIGPROF] when expired.
* Period
* Current value of the timer
* The type describing the status of an interval timer
* Return the current status of the given interval timer.
* Return the user id of the user executing the process.
* Return the effective user id under which the process runs.
* Set the real user id and effective user id for the process.
* Return the group id of the user executing the process.
* Return the effective group id under which the process runs.
* Set the real group id and effective group id for the process.
* Return the list of groups to which the user executing the process
belongs.
* Structure of entries in the [passwd] database.
* Structure of entries in the [groups] database.
* Return the login name of the user executing the process.
* Find an entry in [passwd] with the given name, or raise
[Not_found].
* Find an entry in [group] with the given name, or raise
[Not_found].
* Find an entry in [passwd] with the given user id, or raise
[Not_found].
* Find an entry in [group] with the given group id, or raise
[Not_found].
* The abstract type of Internet addresses.
* Return the printable representation of the given Internet address.
See {!Unix.inet_addr_of_string} for a description of the
printable representation.
* A special IPv6 address, for use only with [bind], representing
all the Internet addresses that the host machine possesses.
* A special IPv6 address representing the host machine ([::1]).
* Unix domain
* Internet domain (IPv4)
* Internet domain (IPv6)
* The type of socket domains.
* Stream socket
* Datagram socket
* Raw socket
* Sequenced packets socket
* The type of socket kinds, specifying the semantics of
communications.
* Return the socket domain adequate for the given socket address.
* Create a pair of unnamed sockets, connected together.
* Accept connections on the given socket. The returned descriptor
is a socket connected to the client; the returned address is
the address of the connecting client.
* Bind a socket to an address.
* Connect a socket to an address.
* Set up a socket for receiving connection requests. The integer
argument is the maximal number of pending requests.
* Close for receiving
* Close for sending
* Close both
* The type of commands for [shutdown].
* Return the address of the given socket.
* Return the address of the host connected to the given socket.
* The flags for {!UnixLabels.recv}, {!UnixLabels.recvfrom},
{!UnixLabels.send} and {!UnixLabels.sendto}.
* Receive data from a connected socket.
* Receive data from an unconnected socket.
* Send data over a connected socket.
* Send data over an unconnected socket.
* Record debugging information
* Permit sending of broadcast messages
* Allow reuse of local addresses for bind
* Keep connection active
* Bypass the standard routing algorithms
* Leave out-of-band data in line
* Report whether socket listening is enabled
* The socket options that can be consulted with {!UnixLabels.getsockopt}
and modified with {!UnixLabels.setsockopt}. These options have a boolean
([true]/[false]) value.
* Size of send buffer
* Size of received buffer
* Report the error status and clear it
* Report the socket type
* Minimum number of bytes to process for input operations
* Minimum number of bytes to process for output operations
* The socket options that can be consulted with {!UnixLabels.getsockopt_int}
and modified with {!UnixLabels.setsockopt_int}. These options have an
integer value.
* The socket options that can be consulted with {!Unix.getsockopt_optint}
and modified with {!Unix.setsockopt_optint}. These options have a
value of type [int option], with [None] meaning ``disabled''.
* Timeout for input operations
* Timeout for output operations
* Return the current status of a boolean-valued option
in the given socket.
* Set or clear a boolean-valued option in the given socket.
* Same as {!UnixLabels.getsockopt} for an integer-valued socket option.
* Same as {!UnixLabels.setsockopt} for an integer-valued socket option.
* Same as {!UnixLabels.getsockopt} for a socket option whose value is an [int option].
* Same as {!UnixLabels.setsockopt} for a socket option whose value is an [int option].
* Same as {!UnixLabels.getsockopt} for a socket option whose value is a floating-point number.
* Same as {!UnixLabels.setsockopt} for a socket option whose value is a floating-point number.
* Connect to a server at the given address.
Return a pair of buffered channels connected to the server.
Remember to call {!Pervasives.flush} on the output channel at the right
times to ensure correct synchronization.
* ``Shut down'' a connection established with {!UnixLabels.open_connection};
that is, transmit an end-of-file condition to the server reading
on the other side of the connection.
* Structure of entries in the [hosts] database.
* Structure of entries in the [protocols] database.
* Structure of entries in the [services] database.
* Return the name of the local host.
* Find an entry in [hosts] with the given name, or raise
[Not_found].
* Find an entry in [hosts] with the given address, or raise
[Not_found].
* Find an entry in [protocols] with the given name, or raise
[Not_found].
* Find an entry in [protocols] with the given protocol number,
or raise [Not_found].
* Find an entry in [services] with the given name, or raise
[Not_found].
* Find an entry in [services] with the given service number,
or raise [Not_found].
* Socket domain
* Socket type
* Socket protocol number
* Address
* Canonical host name
* Address information returned by {!Unix.getaddrinfo}.
* Impose the given socket domain
* Impose the given socket type
* Impose the given protocol
* Do not call name resolver,
expect numeric IP address
* Fill the [ai_canonname] field
of the result
* Set address to ``any'' address
for use with {!Unix.bind}
* Options to {!Unix.getaddrinfo}.
* Name or IP address of host
* Name of service or port number
* Host and service information returned by {!Unix.getnameinfo}.
* Do not qualify local host names
* Always return host as IP address
* Fail if host name cannot be determined
* Always return service as port number
* Options to {!Unix.getnameinfo}.
* The following functions implement the POSIX standard terminal
interface. They provide control over asynchronous communication ports
and pseudo-terminals. Refer to the [termios] man page for a
complete description.
input modes
* Ignore the break condition.
* Signal interrupt on break condition.
* Ignore characters with parity errors.
* Enable parity check on input.
* Strip 8th bit on input characters.
* Ignore CR on input.
* Recognize XON/XOFF characters on input.
* Emit XON/XOFF chars to control input flow.
Output modes:
* Enable output processing.
Control modes:
* Output baud rate (0 means close connection).
* Input baud rate.
* Number of bits per character (5-8).
* Reception is enabled.
* Enable parity generation and detection.
* Specify odd parity instead of even.
* Hang up on last close.
* Ignore modem status lines.
Local modes:
* Enable canonical processing
(line buffering and editing)
* Echo input characters.
* Echo ERASE (to erase previous character).
* Echo KILL (to erase the current line).
Control characters:
* Interrupt character (usually ctrl-C).
* Quit character (usually ctrl-\).
* Kill line character (usually ctrl-U).
* End-of-file character (usually ctrl-D).
* Alternate end-of-line char. (usually none).
* Minimum number of characters to read
before the read request is satisfied.
* Start character (usually ctrl-Q).
* Stop character (usually ctrl-S).
* Return the status of the terminal referred to by the given
file descriptor.
* Waits until all output written on the given file descriptor
has been transmitted.
* Put the calling process in a new session and detach it from
its controlling terminal. | , projet Cristal , INRIA Rocquencourt
Copyright 1996 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the GNU Library General Public License , with
$ I d : unixLabels.mli , v 1.15.4.1 2007/11/19 21:27:56 doligez Exp $
* Interface to the Unix system .
To use as replacement to default { ! Unix } module ,
add [ module Unix = UnixLabels ] in your implementation .
To use as replacement to default {!Unix} module,
add [module Unix = UnixLabels] in your implementation.
*)
* { 6 Error report }
type error = Unix.error =
* The type of error codes .
Errors defined in the POSIX standard
and additional errors from UNIX98 and BSD .
All other errors are mapped to EUNKNOWNERR .
Errors defined in the POSIX standard
and additional errors from UNIX98 and BSD.
All other errors are mapped to EUNKNOWNERR.
*)
exception Unix_error of error * string * string
* Raised by the system calls below when an error is encountered .
The first component is the error code ; the second component
is the function name ; the third component is the string parameter
to the function , if it has one , or the empty string otherwise .
The first component is the error code; the second component
is the function name; the third component is the string parameter
to the function, if it has one, or the empty string otherwise. *)
val error_message : error -> string
val handle_unix_error : ('a -> 'b) -> 'a -> 'b
* [ handle_unix_error f x ] applies [ f ] to [ x ] and returns the result .
If the exception [ Unix_error ] is raised , it prints a message
describing the error and exits with code 2 .
If the exception [Unix_error] is raised, it prints a message
describing the error and exits with code 2. *)
* { 6 Access to the process environment }
val environment : unit -> string array
val getenv : string -> string
val putenv : string -> string -> unit
* [ Unix.putenv name value ] sets the value associated to a
variable in the process environment .
[ name ] is the name of the environment variable ,
and [ value ] its new associated value .
variable in the process environment.
[name] is the name of the environment variable,
and [value] its new associated value. *)
* { 6 Process handling }
type process_status = Unix.process_status =
WEXITED of int
| WSIGNALED of int
| WSTOPPED of int
type wait_flag = Unix.wait_flag =
* do not block if no child has
died yet , but immediately return with a pid equal to 0 .
died yet, but immediately return with a pid equal to 0.*)
val execv : prog:string -> args:string array -> 'a
* [ execv prog args ] execute the program in file [ prog ] , with
the arguments [ args ] , and the current process environment .
These [ execv * ] functions never return : on success , the current
program is replaced by the new one ;
on failure , a { ! UnixLabels . Unix_error } exception is raised .
the arguments [args], and the current process environment.
These [execv*] functions never return: on success, the current
program is replaced by the new one;
on failure, a {!UnixLabels.Unix_error} exception is raised. *)
val execve : prog:string -> args:string array -> env:string array -> 'a
* Same as { ! UnixLabels.execv } , except that the third argument provides the
environment to the program executed .
environment to the program executed. *)
val execvp : prog:string -> args:string array -> 'a
val execvpe : prog:string -> args:string array -> env:string array -> 'a
* Same as { ! } respectively , except that
the program is searched in the path .
the program is searched in the path. *)
val fork : unit -> int
val wait : unit -> int * process_status
* Wait until one of the children processes die , and return its pid
and termination status .
and termination status. *)
val waitpid : mode:wait_flag list -> int -> int * process_status
val system : string -> process_status
* Execute the given command , wait until it terminates , and return
its termination status . The string is interpreted by the shell
[ /bin / sh ] and therefore can contain redirections , quotes , variables ,
etc . The result [ 127 ] indicates that the shell could n't
be executed .
its termination status. The string is interpreted by the shell
[/bin/sh] and therefore can contain redirections, quotes, variables,
etc. The result [WEXITED 127] indicates that the shell couldn't
be executed. *)
val getpid : unit -> int
val getppid : unit -> int
val nice : int -> int
* { 6 Basic file input / output }
type file_descr = Unix.file_descr
val stdin : file_descr
val stdout : file_descr
val stderr : file_descr
type open_flag = Unix.open_flag =
* to 0 length if existing
type file_perm = int
* The type of file access rights , e.g. [ 0o640 ] is read and write for user ,
read for group , none for others
read for group, none for others *)
val openfile : string -> mode:open_flag list -> perm:file_perm -> file_descr
* Open the named file with the given flags . Third argument is
the permissions to give to the file if it is created . Return
a file descriptor on the named file .
the permissions to give to the file if it is created. Return
a file descriptor on the named file. *)
val close : file_descr -> unit
val read : file_descr -> buf:string -> pos:int -> len:int -> int
* [ read fd ] reads [ len ] characters from descriptor
[ fd ] , storing them in string [ buff ] , starting at position [ ofs ]
in string [ buff ] . Return the number of characters actually read .
[fd], storing them in string [buff], starting at position [ofs]
in string [buff]. Return the number of characters actually read. *)
val write : file_descr -> buf:string -> pos:int -> len:int -> int
* [ write fd ] writes [ len ] characters to descriptor
[ fd ] , taking them from string [ buff ] , starting at position [ ofs ]
in string [ buff ] . Return the number of characters actually
written . [ write ] repeats the writing operation until all characters
have been written or an error occurs .
[fd], taking them from string [buff], starting at position [ofs]
in string [buff]. Return the number of characters actually
written. [write] repeats the writing operation until all characters
have been written or an error occurs. *)
val single_write : file_descr -> buf:string -> pos:int -> len:int -> int
* { 6 Interfacing with the standard input / output library }
val in_channel_of_descr : file_descr -> in_channel
val out_channel_of_descr : file_descr -> out_channel
val descr_of_in_channel : in_channel -> file_descr
val descr_of_out_channel : out_channel -> file_descr
* { 6 Seeking and truncating }
type seek_command = Unix.seek_command =
val lseek : file_descr -> int -> mode:seek_command -> int
val truncate : string -> len:int -> unit
val ftruncate : file_descr -> len:int -> unit
* { 6 File status }
type file_kind = Unix.file_kind =
type stats = Unix.stats =
* number
}
val stat : string -> stats
val lstat : string -> stats
val fstat : file_descr -> stats
val isatty : file_descr -> bool
* { 6 File operations on large files }
module LargeFile :
sig
val lseek : file_descr -> int64 -> mode:seek_command -> int64
val truncate : string -> len:int64 -> unit
val ftruncate : file_descr -> len:int64 -> unit
type stats = Unix.LargeFile.stats =
* number
}
val stat : string -> stats
val lstat : string -> stats
val fstat : file_descr -> stats
end
* File operations on large files .
This sub - module provides 64 - bit variants of the functions
{ ! UnixLabels.lseek } ( for positioning a file descriptor ) ,
{ ! UnixLabels.truncate } and { ! UnixLabels.ftruncate }
( for changing the size of a file ) ,
and { ! UnixLabels.stat } , { ! UnixLabels.lstat } and { ! UnixLabels.fstat }
( for obtaining information on files ) . These alternate functions represent
positions and sizes by 64 - bit integers ( type [ int64 ] ) instead of
regular integers ( type [ int ] ) , thus allowing operating on files
whose sizes are greater than [ max_int ] .
This sub-module provides 64-bit variants of the functions
{!UnixLabels.lseek} (for positioning a file descriptor),
{!UnixLabels.truncate} and {!UnixLabels.ftruncate}
(for changing the size of a file),
and {!UnixLabels.stat}, {!UnixLabels.lstat} and {!UnixLabels.fstat}
(for obtaining information on files). These alternate functions represent
positions and sizes by 64-bit integers (type [int64]) instead of
regular integers (type [int]), thus allowing operating on files
whose sizes are greater than [max_int]. *)
* { 6 Operations on file names }
val unlink : string -> unit
val rename : src:string -> dst:string -> unit
val link : src:string -> dst:string -> unit
* { 6 File permissions and ownership }
type access_permission = Unix.access_permission =
val chmod : string -> perm:file_perm -> unit
val fchmod : file_descr -> perm:file_perm -> unit
val chown : string -> uid:int -> gid:int -> unit
* Change the owner uid and owner gid of the named file .
val fchown : file_descr -> uid:int -> gid:int -> unit
* Change the owner uid and owner gid of an opened file .
val umask : int -> int
val access : string -> perm:access_permission list -> unit
* { 6 Operations on file descriptors }
val dup : file_descr -> file_descr
val dup2 : src:file_descr -> dst:file_descr -> unit
val set_nonblock : file_descr -> unit
val clear_nonblock : file_descr -> unit
* Clear the ` ` non - blocking '' flag on the given descriptor .
See { ! } .
See {!UnixLabels.set_nonblock}.*)
val set_close_on_exec : file_descr -> unit
val clear_close_on_exec : file_descr -> unit
val mkdir : string -> perm:file_perm -> unit
val rmdir : string -> unit
val chdir : string -> unit
val getcwd : unit -> string
val chroot : string -> unit
type dir_handle = Unix.dir_handle
val opendir : string -> dir_handle
val readdir : dir_handle -> string
val rewinddir : dir_handle -> unit
val closedir : dir_handle -> unit
* { 6 Pipes and redirections }
val pipe : unit -> file_descr * file_descr
* Create a pipe . The first component of the result is opened
for reading , that 's the exit to the pipe . The second component is
opened for writing , that 's the entrance to the pipe .
for reading, that's the exit to the pipe. The second component is
opened for writing, that's the entrance to the pipe. *)
val mkfifo : string -> perm:file_perm -> unit
* { 6 High - level process and redirection management }
val create_process :
prog:string -> args:string array -> stdin:file_descr -> stdout:file_descr ->
stderr:file_descr -> int
* [ create_process prog args new_stdin ]
forks a new process that executes the program
in file [ prog ] , with arguments [ args ] . The pid of the new
process is returned immediately ; the new process executes
concurrently with the current process .
The standard input and outputs of the new process are connected
to the descriptors [ new_stdin ] , [ new_stdout ] and [ new_stderr ] .
Passing e.g. [ stdout ] for [ new_stdout ] prevents the redirection
and causes the new process to have the same standard output
as the current process .
The executable file [ prog ] is searched in the path .
The new process has the same environment as the current process .
forks a new process that executes the program
in file [prog], with arguments [args]. The pid of the new
process is returned immediately; the new process executes
concurrently with the current process.
The standard input and outputs of the new process are connected
to the descriptors [new_stdin], [new_stdout] and [new_stderr].
Passing e.g. [stdout] for [new_stdout] prevents the redirection
and causes the new process to have the same standard output
as the current process.
The executable file [prog] is searched in the path.
The new process has the same environment as the current process. *)
val create_process_env :
prog:string -> args:string array -> env:string array -> stdin:file_descr ->
stdout:file_descr -> stderr:file_descr -> int
* [ create_process_env prog args env new_stdin new_stdout new_stderr ]
works as { ! UnixLabels.create_process } , except that the extra argument
[ env ] specifies the environment passed to the program .
works as {!UnixLabels.create_process}, except that the extra argument
[env] specifies the environment passed to the program. *)
val open_process_in : string -> in_channel
val open_process_out : string -> out_channel
* Same as { ! UnixLabels.open_process_in } , but redirect the standard input of
the command to a pipe . Data written to the returned output channel
is sent to the standard input of the command .
Warning : writes on output channels are buffered , hence be careful
to call { ! Pervasives.flush } at the right times to ensure
correct synchronization .
the command to a pipe. Data written to the returned output channel
is sent to the standard input of the command.
Warning: writes on output channels are buffered, hence be careful
to call {!Pervasives.flush} at the right times to ensure
correct synchronization. *)
val open_process : string -> in_channel * out_channel
* Same as { ! UnixLabels.open_process_out } , but redirects both the standard
input and standard output of the command to pipes connected to the two
returned channels . The input channel is connected to the output
of the command , and the output channel to the input of the command .
input and standard output of the command to pipes connected to the two
returned channels. The input channel is connected to the output
of the command, and the output channel to the input of the command. *)
val open_process_full :
string -> env:string array -> in_channel * out_channel * in_channel
* Similar to { ! UnixLabels.open_process } , but the second argument specifies
the environment passed to the command . The result is a triple
of channels connected respectively to the standard output , standard input ,
and standard error of the command .
the environment passed to the command. The result is a triple
of channels connected respectively to the standard output, standard input,
and standard error of the command. *)
val close_process_in : in_channel -> process_status
val close_process_out : out_channel -> process_status
val close_process : in_channel * out_channel -> process_status
val close_process_full :
in_channel * out_channel * in_channel -> process_status
* { 6 Symbolic links }
val symlink : src:string -> dst:string -> unit
val readlink : string -> string
* { 6 Polling }
val select :
read:file_descr list -> write:file_descr list -> except:file_descr list ->
timeout:float -> file_descr list * file_descr list * file_descr list
* Wait until some input / output operations become possible on
some channels . The three list arguments are , respectively , a set
of descriptors to check for reading ( first argument ) , for writing
( second argument ) , or for exceptional conditions ( third argument ) .
The fourth argument is the maximal timeout , in seconds ; a
negative fourth argument means no timeout ( unbounded wait ) .
The result is composed of three sets of descriptors : those ready
for reading ( first component ) , ready for writing ( second component ) ,
and over which an exceptional condition is pending ( third
component ) .
some channels. The three list arguments are, respectively, a set
of descriptors to check for reading (first argument), for writing
(second argument), or for exceptional conditions (third argument).
The fourth argument is the maximal timeout, in seconds; a
negative fourth argument means no timeout (unbounded wait).
The result is composed of three sets of descriptors: those ready
for reading (first component), ready for writing (second component),
and over which an exceptional condition is pending (third
component). *)
* { 6 Locking }
type lock_command = Unix.lock_command =
val lockf : file_descr -> mode:lock_command -> len:int -> unit
* [ lockf fd cmd size ] puts a lock on a region of the file opened
as [ fd ] . The region starts at the current read / write position for
[ fd ] ( as set by { ! UnixLabels.lseek } ) , and extends [ size ] bytes forward if
[ size ] is positive , [ size ] bytes backwards if [ size ] is negative ,
or to the end of the file if [ size ] is zero .
A write lock prevents any other
process from acquiring a read or write lock on the region .
A read lock prevents any other
process from acquiring a write lock on the region , but lets
other processes acquire read locks on it .
The [ F_LOCK ] and [ F_TLOCK ] commands attempts to put a write lock
on the specified region .
The [ F_RLOCK ] and [ F_TRLOCK ] commands attempts to put a read lock
on the specified region .
If one or several locks put by another process prevent the current process
from acquiring the lock , [ F_LOCK ] and [ F_RLOCK ] block until these locks
are removed , while [ F_TLOCK ] and [ F_TRLOCK ] fail immediately with an
exception .
The [ F_ULOCK ] removes whatever locks the current process has on
the specified region .
Finally , the [ F_TEST ] command tests whether a write lock can be
acquired on the specified region , without actually putting a lock .
It returns immediately if successful , or fails otherwise .
as [fd]. The region starts at the current read/write position for
[fd] (as set by {!UnixLabels.lseek}), and extends [size] bytes forward if
[size] is positive, [size] bytes backwards if [size] is negative,
or to the end of the file if [size] is zero.
A write lock prevents any other
process from acquiring a read or write lock on the region.
A read lock prevents any other
process from acquiring a write lock on the region, but lets
other processes acquire read locks on it.
The [F_LOCK] and [F_TLOCK] commands attempts to put a write lock
on the specified region.
The [F_RLOCK] and [F_TRLOCK] commands attempts to put a read lock
on the specified region.
If one or several locks put by another process prevent the current process
from acquiring the lock, [F_LOCK] and [F_RLOCK] block until these locks
are removed, while [F_TLOCK] and [F_TRLOCK] fail immediately with an
exception.
The [F_ULOCK] removes whatever locks the current process has on
the specified region.
Finally, the [F_TEST] command tests whether a write lock can be
acquired on the specified region, without actually putting a lock.
It returns immediately if successful, or fails otherwise. *)
* { 6 Signals }
Note : installation of signal handlers is performed via
the functions { ! Sys.signal } and { ! Sys.set_signal } .
Note: installation of signal handlers is performed via
the functions {!Sys.signal} and {!Sys.set_signal}.
*)
val kill : pid:int -> signal:int -> unit
type sigprocmask_command = Unix.sigprocmask_command =
SIG_SETMASK
| SIG_BLOCK
| SIG_UNBLOCK
val sigprocmask : mode:sigprocmask_command -> int list -> int list
* [ sigprocmask cmd sigs ] changes the set of blocked signals .
If [ cmd ] is [ SIG_SETMASK ] , blocked signals are set to those in
the list [ ] .
If [ cmd ] is [ SIG_BLOCK ] , the signals in [ sigs ] are added to
the set of blocked signals .
If [ cmd ] is [ SIG_UNBLOCK ] , the signals in [ sigs ] are removed
from the set of blocked signals .
[ sigprocmask ] returns the set of previously blocked signals .
If [cmd] is [SIG_SETMASK], blocked signals are set to those in
the list [sigs].
If [cmd] is [SIG_BLOCK], the signals in [sigs] are added to
the set of blocked signals.
If [cmd] is [SIG_UNBLOCK], the signals in [sigs] are removed
from the set of blocked signals.
[sigprocmask] returns the set of previously blocked signals. *)
val sigpending : unit -> int list
val sigsuspend : int list -> unit
val pause : unit -> unit
* { 6 Time functions }
type process_times = Unix.process_times =
}
type tm = Unix.tm =
* Seconds 0 .. 60
* Minutes 0 .. 59
* Hours 0 .. 23
* Month of year 0 .. 11
* Year - 1900
* Day of week ( Sunday is 0 )
}
val time : unit -> float
* Return the current time since 00:00:00 GMT , Jan. 1 , 1970 ,
in seconds .
in seconds. *)
val gettimeofday : unit -> float
val gmtime : float -> tm
* Convert a time in seconds , as returned by { ! UnixLabels.time } , into a date
and a time . Assumes UTC ( Coordinated Universal Time ) , also known as GMT .
and a time. Assumes UTC (Coordinated Universal Time), also known as GMT. *)
val localtime : float -> tm
* Convert a time in seconds , as returned by { ! UnixLabels.time } , into a date
and a time . Assumes the local time zone .
and a time. Assumes the local time zone. *)
val mktime : tm -> float * tm
* Convert a date and time , specified by the [ tm ] argument , into
a time in seconds , as returned by { ! UnixLabels.time } . The [ tm_isdst ] ,
[ tm_wday ] and [ tm_yday ] fields of [ tm ] are ignored . Also return a
normalized copy of the given [ tm ] record , with the [ tm_wday ] ,
[ tm_yday ] , and [ tm_isdst ] fields recomputed from the other fields ,
and the other fields normalized ( so that , e.g. , 40 October is
changed into 9 November ) . The [ tm ] argument is interpreted in the
local time zone .
a time in seconds, as returned by {!UnixLabels.time}. The [tm_isdst],
[tm_wday] and [tm_yday] fields of [tm] are ignored. Also return a
normalized copy of the given [tm] record, with the [tm_wday],
[tm_yday], and [tm_isdst] fields recomputed from the other fields,
and the other fields normalized (so that, e.g., 40 October is
changed into 9 November). The [tm] argument is interpreted in the
local time zone. *)
val alarm : int -> int
* Schedule a [ SIGALRM ] signal after the given number of seconds .
val sleep : int -> unit
val times : unit -> process_times
val utimes : string -> access:float -> modif:float -> unit
* Set the last access time ( second arg ) and last modification time
( third arg ) for a file . Times are expressed in seconds from
00:00:00 GMT , Jan. 1 , 1970 .
(third arg) for a file. Times are expressed in seconds from
00:00:00 GMT, Jan. 1, 1970. *)
type interval_timer = Unix.interval_timer =
ITIMER_REAL
* decrements in real time , and sends the signal [ SIGALRM ] when expired .
| ITIMER_VIRTUAL
* decrements in process virtual time , and sends [ SIGVTALRM ] when expired .
| ITIMER_PROF
* The three kinds of interval timers .
type interval_timer_status = Unix.interval_timer_status =
}
val getitimer : interval_timer -> interval_timer_status
val setitimer :
interval_timer -> interval_timer_status -> interval_timer_status
* [ setitimer t s ] sets the interval timer [ t ] and returns
its previous status . The [ s ] argument is interpreted as follows :
[ s.it_value ] , if nonzero , is the time to the next timer expiration ;
[ s.it_interval ] , if nonzero , specifies a value to
be used in reloading it_value when the timer expires .
Setting [ s.it_value ] to zero disable the timer .
Setting [ s.it_interval ] to zero causes the timer to be disabled
after its next expiration .
its previous status. The [s] argument is interpreted as follows:
[s.it_value], if nonzero, is the time to the next timer expiration;
[s.it_interval], if nonzero, specifies a value to
be used in reloading it_value when the timer expires.
Setting [s.it_value] to zero disable the timer.
Setting [s.it_interval] to zero causes the timer to be disabled
after its next expiration. *)
* { 6 User i d , group i d }
val getuid : unit -> int
val geteuid : unit -> int
val setuid : int -> unit
val getgid : unit -> int
val getegid : unit -> int
val setgid : int -> unit
val getgroups : unit -> int array
type passwd_entry = Unix.passwd_entry =
{ pw_name : string;
pw_passwd : string;
pw_uid : int;
pw_gid : int;
pw_gecos : string;
pw_dir : string;
pw_shell : string
}
type group_entry = Unix.group_entry =
{ gr_name : string;
gr_passwd : string;
gr_gid : int;
gr_mem : string array
}
val getlogin : unit -> string
val getpwnam : string -> passwd_entry
val getgrnam : string -> group_entry
val getpwuid : int -> passwd_entry
val getgrgid : int -> group_entry
* { 6 Internet addresses }
type inet_addr = Unix.inet_addr
val inet_addr_of_string : string -> inet_addr
* Conversion from the printable representation of an Internet
address to its internal representation . The argument string
consists of 4 numbers separated by periods ( [ XXX.YYY.ZZZ.TTT ] )
for IPv4 addresses , and up to 8 numbers separated by colons
for IPv6 addresses . Raise [ Failure ] when given a string that
does not match these formats .
address to its internal representation. The argument string
consists of 4 numbers separated by periods ([XXX.YYY.ZZZ.TTT])
for IPv4 addresses, and up to 8 numbers separated by colons
for IPv6 addresses. Raise [Failure] when given a string that
does not match these formats. *)
val string_of_inet_addr : inet_addr -> string
val inet_addr_any : inet_addr
* A special IPv4 address , for use only with [ bind ] , representing
all the Internet addresses that the host machine possesses .
all the Internet addresses that the host machine possesses. *)
val inet_addr_loopback : inet_addr
* A special IPv4 address representing the host machine ( [ 127.0.0.1 ] ) .
val inet6_addr_any : inet_addr
val inet6_addr_loopback : inet_addr
* { 6 Sockets }
type socket_domain = Unix.socket_domain =
type socket_type = Unix.socket_type =
type sockaddr = Unix.sockaddr =
ADDR_UNIX of string
| ADDR_INET of inet_addr * int
* The type of socket addresses . [ ADDR_UNIX name ] is a socket
address in the Unix domain ; [ name ] is a file name in the file
system . [ ADDR_INET(addr , port ) ] is a socket address in the Internet
domain ; [ addr ] is the Internet address of the machine , and
[ port ] is the port number .
address in the Unix domain; [name] is a file name in the file
system. [ADDR_INET(addr,port)] is a socket address in the Internet
domain; [addr] is the Internet address of the machine, and
[port] is the port number. *)
val socket :
domain:socket_domain -> kind:socket_type -> protocol:int -> file_descr
* Create a new socket in the given domain , and with the
given kind . The third argument is the protocol type ; 0 selects
the default protocol for that kind of sockets .
given kind. The third argument is the protocol type; 0 selects
the default protocol for that kind of sockets. *)
val domain_of_sockaddr: sockaddr -> socket_domain
val socketpair :
domain:socket_domain -> kind:socket_type -> protocol:int ->
file_descr * file_descr
val accept : file_descr -> file_descr * sockaddr
val bind : file_descr -> addr:sockaddr -> unit
val connect : file_descr -> addr:sockaddr -> unit
val listen : file_descr -> max:int -> unit
type shutdown_command = Unix.shutdown_command =
val shutdown : file_descr -> mode:shutdown_command -> unit
* Shutdown a socket connection . [ SHUTDOWN_SEND ] as second argument
causes reads on the other end of the connection to return
an end - of - file condition .
[ SHUTDOWN_RECEIVE ] causes writes on the other end of the connection
to return a closed pipe condition ( [ ] signal ) .
causes reads on the other end of the connection to return
an end-of-file condition.
[SHUTDOWN_RECEIVE] causes writes on the other end of the connection
to return a closed pipe condition ([SIGPIPE] signal). *)
val getsockname : file_descr -> sockaddr
val getpeername : file_descr -> sockaddr
type msg_flag = Unix.msg_flag =
MSG_OOB
| MSG_DONTROUTE
| MSG_PEEK
val recv :
file_descr -> buf:string -> pos:int -> len:int -> mode:msg_flag list -> int
val recvfrom :
file_descr -> buf:string -> pos:int -> len:int -> mode:msg_flag list ->
int * sockaddr
val send :
file_descr -> buf:string -> pos:int -> len:int -> mode:msg_flag list -> int
val sendto :
file_descr -> buf:string -> pos:int -> len:int -> mode:msg_flag list ->
addr:sockaddr -> int
* { 6 Socket options }
type socket_bool_option =
type socket_int_option =
type socket_optint_option =
* Whether to linger on closed connections
that have data present , and for how long
( in seconds )
that have data present, and for how long
(in seconds) *)
type socket_float_option =
* The socket options that can be consulted with { ! UnixLabels.getsockopt_float }
and modified with { ! UnixLabels.setsockopt_float } . These options have a
floating - point value representing a time in seconds .
The value 0 means infinite timeout .
and modified with {!UnixLabels.setsockopt_float}. These options have a
floating-point value representing a time in seconds.
The value 0 means infinite timeout. *)
val getsockopt : file_descr -> socket_bool_option -> bool
val setsockopt : file_descr -> socket_bool_option -> bool -> unit
external getsockopt_int :
file_descr -> socket_int_option -> int = "unix_getsockopt_int"
external setsockopt_int :
file_descr -> socket_int_option -> int -> unit = "unix_setsockopt_int"
external getsockopt_optint :
file_descr -> socket_optint_option -> int option = "unix_getsockopt_optint"
external setsockopt_optint :
file_descr -> socket_optint_option -> int option ->
unit = "unix_setsockopt_optint"
external getsockopt_float :
file_descr -> socket_float_option -> float = "unix_getsockopt_float"
external setsockopt_float :
file_descr -> socket_float_option -> float -> unit = "unix_setsockopt_float"
* { 6 High - level network connection functions }
val open_connection : sockaddr -> in_channel * out_channel
val shutdown_connection : in_channel -> unit
val establish_server :
(in_channel -> out_channel -> unit) -> addr:sockaddr -> unit
* Establish a server on the given address .
The function given as first argument is called for each connection
with two buffered channels connected to the client . A new process
is created for each connection . The function { ! UnixLabels.establish_server }
never returns normally .
The function given as first argument is called for each connection
with two buffered channels connected to the client. A new process
is created for each connection. The function {!UnixLabels.establish_server}
never returns normally. *)
* { 6 Host and protocol databases }
type host_entry = Unix.host_entry =
{ h_name : string;
h_aliases : string array;
h_addrtype : socket_domain;
h_addr_list : inet_addr array
}
type protocol_entry = Unix.protocol_entry =
{ p_name : string;
p_aliases : string array;
p_proto : int
}
type service_entry = Unix.service_entry =
{ s_name : string;
s_aliases : string array;
s_port : int;
s_proto : string
}
val gethostname : unit -> string
val gethostbyname : string -> host_entry
val gethostbyaddr : inet_addr -> host_entry
val getprotobyname : string -> protocol_entry
val getprotobynumber : int -> protocol_entry
val getservbyname : string -> protocol:string -> service_entry
val getservbyport : int -> protocol:string -> service_entry
type addr_info =
}
type getaddrinfo_option =
val getaddrinfo:
string -> string -> getaddrinfo_option list -> addr_info list
* [ host service opts ] returns a list of { ! Unix.addr_info }
records describing socket parameters and addresses suitable for
communicating with the given host and service . The empty list is
returned if the host or service names are unknown , or the constraints
expressed in [ opts ] can not be satisfied .
[ host ] is either a host name or the string representation of an IP
address . [ host ] can be given as the empty string ; in this case ,
the ` ` any '' address or the ` ` loopback '' address are used ,
depending whether [ opts ] contains [ AI_PASSIVE ] .
[ service ] is either a service name or the string representation of
a port number . [ service ] can be given as the empty string ;
in this case , the port field of the returned addresses is set to 0 .
[ opts ] is a possibly empty list of options that allows the caller
to force a particular socket domain ( e.g. IPv6 only or IPv4 only )
or a particular socket type ( e.g. TCP only or UDP only ) .
records describing socket parameters and addresses suitable for
communicating with the given host and service. The empty list is
returned if the host or service names are unknown, or the constraints
expressed in [opts] cannot be satisfied.
[host] is either a host name or the string representation of an IP
address. [host] can be given as the empty string; in this case,
the ``any'' address or the ``loopback'' address are used,
depending whether [opts] contains [AI_PASSIVE].
[service] is either a service name or the string representation of
a port number. [service] can be given as the empty string;
in this case, the port field of the returned addresses is set to 0.
[opts] is a possibly empty list of options that allows the caller
to force a particular socket domain (e.g. IPv6 only or IPv4 only)
or a particular socket type (e.g. TCP only or UDP only). *)
type name_info =
type getnameinfo_option =
* Consider the service as UDP - based
instead of the default TCP
instead of the default TCP *)
val getnameinfo : sockaddr -> getnameinfo_option list -> name_info
* [ getnameinfo opts ] returns the host name and service name
corresponding to the socket address [ addr ] . [ opts ] is a possibly
empty list of options that governs how these names are obtained .
Raise [ Not_found ] if an error occurs .
corresponding to the socket address [addr]. [opts] is a possibly
empty list of options that governs how these names are obtained.
Raise [Not_found] if an error occurs. *)
* { 6 Terminal interface }
type terminal_io = Unix.terminal_io =
{
* parity errors .
* Map NL to CR on input .
* Map CR to NL on input .
* Number of stop bits ( 1 - 2 ) .
* Generate signal on INTR , QUIT , SUSP .
* Disable flush after INTR , QUIT , SUSP .
* Echo NL even if c_echo is not set .
* Erase character ( usually DEL or ctrl - H ) .
* Maximum read wait ( in 0.1s units ) .
}
val tcgetattr : file_descr -> terminal_io
type setattr_when = Unix.setattr_when =
TCSANOW
| TCSADRAIN
| TCSAFLUSH
val tcsetattr : file_descr -> mode:setattr_when -> terminal_io -> unit
* Set the status of the terminal referred to by the given
file descriptor . The second argument indicates when the
status change takes place : immediately ( [ TCSANOW ] ) ,
when all pending output has been transmitted ( [ TCSADRAIN ] ) ,
or after flushing all input that has been received but not
read ( [ TCSAFLUSH ] ) . [ TCSADRAIN ] is recommended when changing
the output parameters ; [ TCSAFLUSH ] , when changing the input
parameters .
file descriptor. The second argument indicates when the
status change takes place: immediately ([TCSANOW]),
when all pending output has been transmitted ([TCSADRAIN]),
or after flushing all input that has been received but not
read ([TCSAFLUSH]). [TCSADRAIN] is recommended when changing
the output parameters; [TCSAFLUSH], when changing the input
parameters. *)
val tcsendbreak : file_descr -> duration:int -> unit
* Send a break condition on the given file descriptor .
The second argument is the duration of the break , in 0.1s units ;
0 means standard duration ( 0.25s ) .
The second argument is the duration of the break, in 0.1s units;
0 means standard duration (0.25s). *)
val tcdrain : file_descr -> unit
type flush_queue = Unix.flush_queue =
TCIFLUSH
| TCOFLUSH
| TCIOFLUSH
val tcflush : file_descr -> mode:flush_queue -> unit
* Discard data written on the given file descriptor but not yet
transmitted , or data received but not yet read , depending on the
second argument : [ TCIFLUSH ] flushes data received but not read ,
[ TCOFLUSH ] flushes data written but not transmitted , and
[ TCIOFLUSH ] flushes both .
transmitted, or data received but not yet read, depending on the
second argument: [TCIFLUSH] flushes data received but not read,
[TCOFLUSH] flushes data written but not transmitted, and
[TCIOFLUSH] flushes both. *)
type flow_action = Unix.flow_action =
TCOOFF
| TCOON
| TCIOFF
| TCION
val tcflow : file_descr -> mode:flow_action -> unit
* Suspend or restart reception or transmission of data on
the given file descriptor , depending on the second argument :
[ TCOOFF ] suspends output , [ TCOON ] restarts output ,
[ TCIOFF ] transmits a STOP character to suspend input ,
and [ TCION ] transmits a START character to restart input .
the given file descriptor, depending on the second argument:
[TCOOFF] suspends output, [TCOON] restarts output,
[TCIOFF] transmits a STOP character to suspend input,
and [TCION] transmits a START character to restart input. *)
val setsid : unit -> int
|
8038c261e2957abbd66966c5b616f6536f2c69f613639fa51d2c11f57013aefb | mbutterick/beautiful-racket | stackerizer.rkt | #lang br/quicklang
(provide + *)
(define-macro (stackerizer-mb EXPR)
#'(#%module-begin
(for-each displayln (reverse (flatten EXPR)))))
(provide (rename-out [stackerizer-mb #%module-begin]))
(define-macro (define-ops OP ...)
#'(begin
(define-macro-cases OP
[(OP FIRST) #'FIRST]
[(OP FIRST NEXT (... ...))
#'(list 'OP FIRST (OP NEXT (... ...)))])
...))
(define-ops + *) | null | https://raw.githubusercontent.com/mbutterick/beautiful-racket/f0e2cb5b325733b3f9cbd554cc7d2bb236af9ee9/beautiful-racket-demo/stackerizer-demo/stackerizer.rkt | racket | #lang br/quicklang
(provide + *)
(define-macro (stackerizer-mb EXPR)
#'(#%module-begin
(for-each displayln (reverse (flatten EXPR)))))
(provide (rename-out [stackerizer-mb #%module-begin]))
(define-macro (define-ops OP ...)
#'(begin
(define-macro-cases OP
[(OP FIRST) #'FIRST]
[(OP FIRST NEXT (... ...))
#'(list 'OP FIRST (OP NEXT (... ...)))])
...))
(define-ops + *) | |
ddf788f0c6abdb8f83e8e01fd926817549454d01e03125c4907c924d6142ea90 | B-Lang-org/bsc | IntegerUtil.hs | module IntegerUtil(mask, ext, integerFormat, integerFormatPref,
integerInvert, integerXor, integerSelect, aaaa,
integerAnd, integerOr, integerToString) where
import ErrorUtil(internalError)
-- generate N bits of repeating 'aaaa' pattern
aaaa :: Integer -> Integer
aaaa 0 = 0
aaaa 1 = 0
aaaa 2 = 2
aaaa 3 = 2
aaaa sz | sz >= 4 = let higher_bits = (aaaa (sz - 4))
lower_bits = 10
offset = (2 :: Integer) ^ (4 :: Integer)
in (offset * higher_bits) + lower_bits
aaaa _ = internalError "aaaa not defined for negative sizes"
aaaa : : Integer - > Integer
aaaa 0 = 0
aaaa 1 = 0
aaaa n | n < 0 = internalError " aaaa not defined for negative sizes "
| even n = ( 2 ^ ( n - 1 ) ) + ( aaaa ( n - 2 ) )
| otherwise = aaaa ( n - 1 )
aaaa :: Integer -> Integer
aaaa 0 = 0
aaaa 1 = 0
aaaa n | n < 0 = internalError "aaaa not defined for negative sizes"
| even n = (2 ^ (n - 1)) + (aaaa (n - 2))
| otherwise = aaaa (n - 1)
-}
-- mask to s bits
mask :: Integer -> Integer -> Integer
mask s i | s >= 0 = i `mod` 2^s
mask s i = internalError ("mask " ++ show (s, i))
-- sign extend to s bits
ext :: Integer -> Integer -> Integer
ext s i | s >= 1 = if i >= 2^(s-1) then i - 2^s else i
ext 0 i = i
ext _ _ = internalError "ext only defined for non-negative size"
integerInvert :: Integer -> Integer
integerInvert x = -x - 1
integerAnd :: Integer -> Integer -> Integer
integerAnd x y = loop 1 0 x y
where loop :: Integer -> Integer -> Integer -> Integer -> Integer
loop bit acc x y =
if x == 0 || y == 0 then
acc
else if x == -1 && y == -1 then
-bit + acc
else
let (x', xb) = divMod x 2
(y', yb) = divMod y 2
in if xb == 1 && yb == 1 then
loop (bit*2) (acc+bit) x' y'
else
loop (bit*2) acc x' y'
integerOr :: Integer -> Integer -> Integer
integerOr x y = loop 1 0 x y
where loop :: Integer -> Integer -> Integer -> Integer -> Integer
loop bit acc x y =
if x == 0 && y == 0 then
acc
else if x == -1 || y == -1 then
-bit + acc
else
let (x', xb) = divMod x 2
(y', yb) = divMod y 2
in if xb == 1 || yb == 1 then
loop (bit*2) (acc+bit) x' y'
else
loop (bit*2) acc x' y'
integerXor :: Integer -> Integer -> Integer
integerXor x y = (x `integerOr` y) `integerAnd` integerInvert (x `integerAnd` y)
-- select k bits at position m
integerSelect :: Integer -> Integer -> Integer -> Integer
integerSelect k m i | k >= 0 && m >= 0 = mask k (i `div` 2^m)
integerSelect k m i = internalError ("integerSelect " ++ show (k, m, i))
integerFormat :: Integer -> Integer -> Integer -> String
integerFormat width base value =
if value < 0 then
'-' : integerFormat width base (-value)
else
let s = integerToString (fromInteger base) value
l = length s
w = fromInteger width
pad = if l < w then replicate (w-l) '0' else ""
in pad ++ s
integerFormatPref :: Integer -> Integer -> Integer -> String
integerFormatPref width 2 value = "0b" ++ integerFormat width 2 value
integerFormatPref width 8 value = "0o" ++ integerFormat width 8 value
integerFormatPref width 10 value = integerFormat width 10 value
integerFormatPref width 16 value = "0x" ++ integerFormat width 16 value
-- otherwise, use decimal
integerFormatPref width _ value = integerFormatPref width 10 value
integerToString :: Int -> Integer -> String
integerToString b i | b < 2 = error "integerToString: base must be >= 2"
| i < 0 = '-' : showIntBase (toInteger b) (negate i) ""
| otherwise = showIntBase (toInteger b) i ""
mostly duplicates the function in the Prelude from the Haskell 98 Report
showIntBase :: Integer -> Integer -> String -> String
showIntBase b n r | n < 0 = error "Numeric.showInt: can't show negative numbers"
| otherwise =
let (n',d) = quotRem n b
r' = digit d : r
digit d | d < 10 = toEnum (fromEnum '0' + fromIntegral d)
| otherwise = toEnum (fromEnum 'A' + fromIntegral d - 10)
in if n' == 0 then r' else showIntBase b n' r'
| null | https://raw.githubusercontent.com/B-Lang-org/bsc/bd141b505394edc5a4bdd3db442a9b0a8c101f0f/src/comp/IntegerUtil.hs | haskell | generate N bits of repeating 'aaaa' pattern
mask to s bits
sign extend to s bits
select k bits at position m
otherwise, use decimal | module IntegerUtil(mask, ext, integerFormat, integerFormatPref,
integerInvert, integerXor, integerSelect, aaaa,
integerAnd, integerOr, integerToString) where
import ErrorUtil(internalError)
aaaa :: Integer -> Integer
aaaa 0 = 0
aaaa 1 = 0
aaaa 2 = 2
aaaa 3 = 2
aaaa sz | sz >= 4 = let higher_bits = (aaaa (sz - 4))
lower_bits = 10
offset = (2 :: Integer) ^ (4 :: Integer)
in (offset * higher_bits) + lower_bits
aaaa _ = internalError "aaaa not defined for negative sizes"
aaaa : : Integer - > Integer
aaaa 0 = 0
aaaa 1 = 0
aaaa n | n < 0 = internalError " aaaa not defined for negative sizes "
| even n = ( 2 ^ ( n - 1 ) ) + ( aaaa ( n - 2 ) )
| otherwise = aaaa ( n - 1 )
aaaa :: Integer -> Integer
aaaa 0 = 0
aaaa 1 = 0
aaaa n | n < 0 = internalError "aaaa not defined for negative sizes"
| even n = (2 ^ (n - 1)) + (aaaa (n - 2))
| otherwise = aaaa (n - 1)
-}
mask :: Integer -> Integer -> Integer
mask s i | s >= 0 = i `mod` 2^s
mask s i = internalError ("mask " ++ show (s, i))
ext :: Integer -> Integer -> Integer
ext s i | s >= 1 = if i >= 2^(s-1) then i - 2^s else i
ext 0 i = i
ext _ _ = internalError "ext only defined for non-negative size"
integerInvert :: Integer -> Integer
integerInvert x = -x - 1
integerAnd :: Integer -> Integer -> Integer
integerAnd x y = loop 1 0 x y
where loop :: Integer -> Integer -> Integer -> Integer -> Integer
loop bit acc x y =
if x == 0 || y == 0 then
acc
else if x == -1 && y == -1 then
-bit + acc
else
let (x', xb) = divMod x 2
(y', yb) = divMod y 2
in if xb == 1 && yb == 1 then
loop (bit*2) (acc+bit) x' y'
else
loop (bit*2) acc x' y'
integerOr :: Integer -> Integer -> Integer
integerOr x y = loop 1 0 x y
where loop :: Integer -> Integer -> Integer -> Integer -> Integer
loop bit acc x y =
if x == 0 && y == 0 then
acc
else if x == -1 || y == -1 then
-bit + acc
else
let (x', xb) = divMod x 2
(y', yb) = divMod y 2
in if xb == 1 || yb == 1 then
loop (bit*2) (acc+bit) x' y'
else
loop (bit*2) acc x' y'
integerXor :: Integer -> Integer -> Integer
integerXor x y = (x `integerOr` y) `integerAnd` integerInvert (x `integerAnd` y)
integerSelect :: Integer -> Integer -> Integer -> Integer
integerSelect k m i | k >= 0 && m >= 0 = mask k (i `div` 2^m)
integerSelect k m i = internalError ("integerSelect " ++ show (k, m, i))
integerFormat :: Integer -> Integer -> Integer -> String
integerFormat width base value =
if value < 0 then
'-' : integerFormat width base (-value)
else
let s = integerToString (fromInteger base) value
l = length s
w = fromInteger width
pad = if l < w then replicate (w-l) '0' else ""
in pad ++ s
integerFormatPref :: Integer -> Integer -> Integer -> String
integerFormatPref width 2 value = "0b" ++ integerFormat width 2 value
integerFormatPref width 8 value = "0o" ++ integerFormat width 8 value
integerFormatPref width 10 value = integerFormat width 10 value
integerFormatPref width 16 value = "0x" ++ integerFormat width 16 value
integerFormatPref width _ value = integerFormatPref width 10 value
integerToString :: Int -> Integer -> String
integerToString b i | b < 2 = error "integerToString: base must be >= 2"
| i < 0 = '-' : showIntBase (toInteger b) (negate i) ""
| otherwise = showIntBase (toInteger b) i ""
mostly duplicates the function in the Prelude from the Haskell 98 Report
showIntBase :: Integer -> Integer -> String -> String
showIntBase b n r | n < 0 = error "Numeric.showInt: can't show negative numbers"
| otherwise =
let (n',d) = quotRem n b
r' = digit d : r
digit d | d < 10 = toEnum (fromEnum '0' + fromIntegral d)
| otherwise = toEnum (fromEnum 'A' + fromIntegral d - 10)
in if n' == 0 then r' else showIntBase b n' r'
|
fa3a1fe88b3205c407a50792d4bffc2874c9ed4d9969ec943a272f9d505014bc | dcy/epush | epush_apns.erl | -module(epush_apns).
-export([handle_http/2,
loop/4, handle_info/2
]).
-include_lib("eutil/include/eutil.hrl").
handle_push(ApnsName, Timeout, Headers, #{<<"push_method">> := <<"general_notification">>,
<<"device_token">> := DeviceToken,
<<"title">> := _Title, <<"content">> := Content} = Payload) ->
Aps = #{alert => Content, badge => 1},
Sound = maps:get(<<"sound">>, Payload, <<"default">>),
SoundAps = Aps#{sound => Sound},
Notification = #{aps => SoundAps},
do_push(ApnsName, Timeout, Headers, DeviceToken, Notification);
handle_push(ApnsName, Timeout, Headers, #{<<"push_method">> := <<"general_app_msg">>,
<<"device_token">> := DeviceToken, <<"msg">> := Msg}) ->
Notification = #{aps => #{alert => Msg, badge => 1}},
do_push(ApnsName, Timeout, Headers, DeviceToken, Notification);
handle_push(ApnsName, Timeout, Headers, #{<<"token">> := DeviceToken, <<"content">> := Content}) ->
Notification = #{aps => #{alert => Content, badge => 1}},
do_push(ApnsName, Timeout, Headers, DeviceToken, Notification).
loop(_RoutingKey, _ContentType, Payload, #{pool_name := PoolName, headers := Headers,
timeout := Timeout} = State) ->
case handle_push(PoolName, Timeout, Headers, eutil:json_decode(Payload)) of
reject -> {reject, State};
_ -> {ack, State}
end.
handle_info(Info, State) ->
?INFO_MSG("*******Info: ~p~n", [Info]),
{ok, State}.
handle_http(#{id := ApnsName, headers := Headers, timeout := Timeout}, Payload) ->
PoolName = list_to_atom(lists:concat([ApnsName, "_pool"])),
handle_push(PoolName, Timeout, Headers, Payload).
do_push(ApnsName , Headers , DeviceToken , Notification ) - >
% try
case apns : push_notification(ApnsName , DeviceToken , Notification , Headers ) of
{ 200 , _ , _ } - >
% ok;
% {Code, Info, Reason} ->
? ERROR_MSG("apns push error , Code : ~p , : ~p , Info : ~p , Reason : ~p " ,
[ Code , DeviceToken , Info , Reason ] ) ,
% {error, Reason}
% end
% catch
% exit:{timeout, _} ->
? ERROR_MSG("apns push timeout , DeviceToken : ~p " , [ DeviceToken ] ) ,
% reject;
% Error:ErrReason ->
? ERROR_MSG("Error : ~p , ErrReason : ~p " , [ Error , ErrReason ] ) ,
% {error, ErrReason}
% end.
do_push(ApnsName, Timeout, Headers, DeviceToken, Notification) ->
case epush_pool:push(ApnsName, DeviceToken, Notification, Headers, Timeout+1000) of
{200, _, _} ->
ok;
{timeout, _} ->
?ERROR_MSG("apns do_push timeout, DeviceToken: ~p", [DeviceToken]),
reject;
{Code, Info, Reason} ->
?ERROR_MSG("apns do_push error, Code: ~p, DeviceToken: ~p, Info: ~p, Reason: ~p",
[Code, DeviceToken, Info, Reason]),
{error, Reason};
Error ->
?ERROR_MSG("apns do_push error, Error: ~p", [Error])
end.
| null | https://raw.githubusercontent.com/dcy/epush/cbd59fd769e86d4f600e06ff31926f1e9c2602cf/src/epush_apns.erl | erlang | try
ok;
{Code, Info, Reason} ->
{error, Reason}
end
catch
exit:{timeout, _} ->
reject;
Error:ErrReason ->
{error, ErrReason}
end. | -module(epush_apns).
-export([handle_http/2,
loop/4, handle_info/2
]).
-include_lib("eutil/include/eutil.hrl").
handle_push(ApnsName, Timeout, Headers, #{<<"push_method">> := <<"general_notification">>,
<<"device_token">> := DeviceToken,
<<"title">> := _Title, <<"content">> := Content} = Payload) ->
Aps = #{alert => Content, badge => 1},
Sound = maps:get(<<"sound">>, Payload, <<"default">>),
SoundAps = Aps#{sound => Sound},
Notification = #{aps => SoundAps},
do_push(ApnsName, Timeout, Headers, DeviceToken, Notification);
handle_push(ApnsName, Timeout, Headers, #{<<"push_method">> := <<"general_app_msg">>,
<<"device_token">> := DeviceToken, <<"msg">> := Msg}) ->
Notification = #{aps => #{alert => Msg, badge => 1}},
do_push(ApnsName, Timeout, Headers, DeviceToken, Notification);
handle_push(ApnsName, Timeout, Headers, #{<<"token">> := DeviceToken, <<"content">> := Content}) ->
Notification = #{aps => #{alert => Content, badge => 1}},
do_push(ApnsName, Timeout, Headers, DeviceToken, Notification).
loop(_RoutingKey, _ContentType, Payload, #{pool_name := PoolName, headers := Headers,
timeout := Timeout} = State) ->
case handle_push(PoolName, Timeout, Headers, eutil:json_decode(Payload)) of
reject -> {reject, State};
_ -> {ack, State}
end.
handle_info(Info, State) ->
?INFO_MSG("*******Info: ~p~n", [Info]),
{ok, State}.
handle_http(#{id := ApnsName, headers := Headers, timeout := Timeout}, Payload) ->
PoolName = list_to_atom(lists:concat([ApnsName, "_pool"])),
handle_push(PoolName, Timeout, Headers, Payload).
do_push(ApnsName , Headers , DeviceToken , Notification ) - >
case apns : push_notification(ApnsName , DeviceToken , Notification , Headers ) of
{ 200 , _ , _ } - >
? ERROR_MSG("apns push error , Code : ~p , : ~p , Info : ~p , Reason : ~p " ,
[ Code , DeviceToken , Info , Reason ] ) ,
? ERROR_MSG("apns push timeout , DeviceToken : ~p " , [ DeviceToken ] ) ,
? ERROR_MSG("Error : ~p , ErrReason : ~p " , [ Error , ErrReason ] ) ,
do_push(ApnsName, Timeout, Headers, DeviceToken, Notification) ->
case epush_pool:push(ApnsName, DeviceToken, Notification, Headers, Timeout+1000) of
{200, _, _} ->
ok;
{timeout, _} ->
?ERROR_MSG("apns do_push timeout, DeviceToken: ~p", [DeviceToken]),
reject;
{Code, Info, Reason} ->
?ERROR_MSG("apns do_push error, Code: ~p, DeviceToken: ~p, Info: ~p, Reason: ~p",
[Code, DeviceToken, Info, Reason]),
{error, Reason};
Error ->
?ERROR_MSG("apns do_push error, Error: ~p", [Error])
end.
|
a2f72a9f48cb153107cd6cc08276a2254f0ff653f34a6f52bebeb697ee677a3b | unclebob/clojureOrbit | world_test.clj | (ns world-test
(:use clojure.test orbit.world))
(deftest world-test
(testing "collision aging"
(is (= (age-collisions [[5 :x]]) [[4 :x]]))
(is (= (age-collisions [[1 :x] [2 :y]]) [[1 :y]]))))
| null | https://raw.githubusercontent.com/unclebob/clojureOrbit/82d59297dc8c54fccb37b92725f0547def0d6157/src/orbit/world_test.clj | clojure | (ns world-test
(:use clojure.test orbit.world))
(deftest world-test
(testing "collision aging"
(is (= (age-collisions [[5 :x]]) [[4 :x]]))
(is (= (age-collisions [[1 :x] [2 :y]]) [[1 :y]]))))
| |
00d8cfa9ce58adcc10d90f99c75f896cdef6aaecb59356bb53103708608e2cd5 | jgoerzen/magic-haskell | genconsts.hs | -*- Mode : haskell ; Haskell Magic Interface
Copyright ( C ) 2005 < >
This code is under a 3 - clause BSD license ; see COPYING for details .
Haskell Magic Interface
Copyright (C) 2005 John Goerzen <>
This code is under a 3-clause BSD license; see COPYING for details.
-}
import Data.Char
import Data.List
const2HS (x:xs) =
x : c2hs xs
where c2hs [] = []
c2hs ('_':x:xs) = x : c2hs xs
c2hs (x:xs) = toLower x : c2hs xs
getC const = "#{const " ++ const ++ "}"
errorClause name consts =
"data " ++ name ++ " =\n " ++
concat (intersperse "\n | " (map toDecl consts)) ++
"\n | Unknown" ++ name ++ " Int\n" ++
"\n deriving (Show)" ++
"\n\ninstance Enum " ++ name ++ " where\n" ++
concat (intersperse "\n" (map toenums consts)) ++
"\n toEnum x = Unknown" ++ name ++ " x\n" ++
"\n" ++ concat (intersperse "\n" (map fromenums consts)) ++
"\n fromEnum (Unknown" ++ name ++ " x) = x\n" ++
"\ninstance Ord " ++ name ++ " where\n" ++
" compare x y = compare (fromEnum x) (fromEnum y)\n\n" ++
"instance Eq " ++ name ++ " where\n" ++
" x == y = (fromEnum x) == (fromEnum y)\n\n"
where
toDecl = const2HS
toenums i =
" toEnum (" ++ getC i ++ ") = " ++ (const2HS i)
fromenums i =
" fromEnum " ++ (const2HS i) ++ " = (" ++ getC i ++ ")"
modHeader =
"-- AUTO-GENERATED FILE, DO NOT EDIT. GENERATED BY utils/genconsts.hs\n" ++
"{- |\n" ++
" Module : Magic.Data\n" ++
" Copyright : Copyright (C) 2005 John Goerzen\n" ++
" License : BSD\n" ++
"\n" ++
" Maintainer : John Goerzen,\n" ++
" Maintainer : \n" ++
" Stability : provisional\n" ++
" Portability: portable\n" ++
"\n" ++
"Haskell types for libmagic constants\n" ++
"\n" ++
"Written by John Goerzen, jgoerzen\\@complete.org\n" ++
"-}\n\n" ++
"module Magic.Data (module Magic.Data) where\n" ++
"\n#include \"magic.h\"\n\n"
main =
do putStrLn modHeader
putStrLn (errorClause "MagicFlag" magicFlags)
magicFlags = ["MAGIC_NONE", "MAGIC_DEBUG", "MAGIC_SYMLINK",
"MAGIC_COMPRESS", "MAGIC_DEVICES", "MAGIC_MIME",
"MAGIC_CONTINUE", "MAGIC_CHECK",
"MAGIC_PRESERVE_ATIME", "MAGIC_RAW", "MAGIC_ERROR"]
| null | https://raw.githubusercontent.com/jgoerzen/magic-haskell/fd6178dc4db05c2a6033c3845b7ef149d997e62a/utils/genconsts.hs | haskell | -*- Mode : haskell ; Haskell Magic Interface
Copyright ( C ) 2005 < >
This code is under a 3 - clause BSD license ; see COPYING for details .
Haskell Magic Interface
Copyright (C) 2005 John Goerzen <>
This code is under a 3-clause BSD license; see COPYING for details.
-}
import Data.Char
import Data.List
const2HS (x:xs) =
x : c2hs xs
where c2hs [] = []
c2hs ('_':x:xs) = x : c2hs xs
c2hs (x:xs) = toLower x : c2hs xs
getC const = "#{const " ++ const ++ "}"
errorClause name consts =
"data " ++ name ++ " =\n " ++
concat (intersperse "\n | " (map toDecl consts)) ++
"\n | Unknown" ++ name ++ " Int\n" ++
"\n deriving (Show)" ++
"\n\ninstance Enum " ++ name ++ " where\n" ++
concat (intersperse "\n" (map toenums consts)) ++
"\n toEnum x = Unknown" ++ name ++ " x\n" ++
"\n" ++ concat (intersperse "\n" (map fromenums consts)) ++
"\n fromEnum (Unknown" ++ name ++ " x) = x\n" ++
"\ninstance Ord " ++ name ++ " where\n" ++
" compare x y = compare (fromEnum x) (fromEnum y)\n\n" ++
"instance Eq " ++ name ++ " where\n" ++
" x == y = (fromEnum x) == (fromEnum y)\n\n"
where
toDecl = const2HS
toenums i =
" toEnum (" ++ getC i ++ ") = " ++ (const2HS i)
fromenums i =
" fromEnum " ++ (const2HS i) ++ " = (" ++ getC i ++ ")"
modHeader =
"-- AUTO-GENERATED FILE, DO NOT EDIT. GENERATED BY utils/genconsts.hs\n" ++
"{- |\n" ++
" Module : Magic.Data\n" ++
" Copyright : Copyright (C) 2005 John Goerzen\n" ++
" License : BSD\n" ++
"\n" ++
" Maintainer : John Goerzen,\n" ++
" Maintainer : \n" ++
" Stability : provisional\n" ++
" Portability: portable\n" ++
"\n" ++
"Haskell types for libmagic constants\n" ++
"\n" ++
"Written by John Goerzen, jgoerzen\\@complete.org\n" ++
"-}\n\n" ++
"module Magic.Data (module Magic.Data) where\n" ++
"\n#include \"magic.h\"\n\n"
main =
do putStrLn modHeader
putStrLn (errorClause "MagicFlag" magicFlags)
magicFlags = ["MAGIC_NONE", "MAGIC_DEBUG", "MAGIC_SYMLINK",
"MAGIC_COMPRESS", "MAGIC_DEVICES", "MAGIC_MIME",
"MAGIC_CONTINUE", "MAGIC_CHECK",
"MAGIC_PRESERVE_ATIME", "MAGIC_RAW", "MAGIC_ERROR"]
| |
914446c186ce5cd9c6974792db6de3fbacd4275fa8e3a61fc1ee06e1e7967657 | camlp5/camlp5 | plexer.ml | (* camlp5r *)
(* plexer.ml,v *)
Copyright ( c ) INRIA 2007 - 2017
(* #load "pa_lexer.cmo" *)
open Versdep;;
let simplest_raw_strings = ref false;;
let no_quotations = ref false;;
let error_on_unknown_keywords = ref false;;
let dollar_for_antiquotation = ref true;;
let specific_space_dot = ref false;;
let force_antiquot_loc = ref false;;
type context =
{ mutable after_space : bool;
simplest_raw_strings : bool;
dollar_for_antiquotation : bool;
specific_space_dot : bool;
find_kwd : string -> string;
line_cnt : int -> char -> unit;
set_line_nb : unit -> unit;
make_lined_loc : int * int -> string -> Ploc.t }
;;
let err ctx loc msg =
Ploc.raise (ctx.make_lined_loc loc "") (Plexing.Error msg)
;;
let keyword_or_error ctx loc s =
try "", ctx.find_kwd s with
Not_found ->
if !error_on_unknown_keywords then err ctx loc ("illegal token: " ^ s)
else "", s
;;
let rev_implode l =
let s = string_create (List.length l) in
let rec loop i =
function
c :: l -> string_unsafe_set s i c; loop (i - 1) l
| [] -> s
in
bytes_to_string (loop (string_length s - 1) l)
;;
let implode l = rev_implode (List.rev l);;
let stream_peek_nth n strm =
let rec loop n =
function
[] -> None
| [x] -> if n == 1 then Some x else None
| _ :: l -> loop (n - 1) l
in
loop n (Stream.npeek n strm)
;;
let utf8_lexing = ref false;;
let greek_tab =
["α"; "β"; "γ"; "δ"; "ε"; "ζ"; "η"; "θ"; "ι"; "κ"; "λ"; "μ"; "ν"; "ξ"; "ο";
"π"; "ρ"; "σ"; "τ"; "υ"; "φ"; "χ"; "ψ"; "ω"]
;;
let greek_letter buf strm =
if !utf8_lexing then
match Stream.peek strm with
Some c ->
if Char.code c >= 128 then
let x = implode (Stream.npeek 2 strm) in
if List.mem x greek_tab then
begin Stream.junk strm; Plexing.Lexbuf.add c buf end
else raise Stream.Failure
else raise Stream.Failure
| None -> raise Stream.Failure
else raise Stream.Failure
;;
let misc_letter buf strm =
if !utf8_lexing then
match Stream.peek strm with
Some c ->
if Char.code c >= 128 then
match implode (Stream.npeek 3 strm) with
"→" | "≤" | "≥" -> raise Stream.Failure
| _ -> Stream.junk strm; Plexing.Lexbuf.add c buf
else raise Stream.Failure
| None -> raise Stream.Failure
else
let (strm__ : _ Stream.t) = strm in
match Stream.peek strm__ with
Some ('\128'..'\225' as c) ->
Stream.junk strm__; Plexing.Lexbuf.add c buf
| Some ('\227'..'\255' as c) ->
Stream.junk strm__; Plexing.Lexbuf.add c buf
| _ -> raise Stream.Failure
;;
let misc_punct buf strm =
if !utf8_lexing then
let (strm__ : _ Stream.t) = strm in
match Stream.peek strm__ with
Some '\226' ->
Stream.junk strm__;
begin match Stream.peek strm__ with
Some c ->
Stream.junk strm__;
begin match Stream.peek strm__ with
Some c1 ->
Stream.junk strm__;
Plexing.Lexbuf.add c1
(Plexing.Lexbuf.add c (Plexing.Lexbuf.add '\226' buf))
| _ -> raise (Stream.Error "")
end
| _ -> raise (Stream.Error "")
end
| _ -> raise Stream.Failure
else let (_ : _ Stream.t) = strm in raise Stream.Failure
;;
let utf8_equiv ctx bp buf strm =
if !utf8_lexing then
let (strm__ : _ Stream.t) = strm in
match Stream.peek strm__ with
Some '\226' ->
Stream.junk strm__;
begin try
match Stream.peek strm__ with
Some '\134' ->
Stream.junk strm__;
begin match Stream.peek strm__ with
Some '\146' ->
Stream.junk strm__;
keyword_or_error ctx (bp, Stream.count strm__) "->"
| _ -> raise (Stream.Error "")
end
| Some '\137' ->
Stream.junk strm__;
begin try
match Stream.peek strm__ with
Some '\164' ->
Stream.junk strm__;
keyword_or_error ctx (bp, Stream.count strm__) "<="
| Some '\165' ->
Stream.junk strm__;
keyword_or_error ctx (bp, Stream.count strm__) ">="
| _ -> raise Stream.Failure
with Stream.Failure -> raise (Stream.Error "")
end
| _ -> raise Stream.Failure
with Stream.Failure -> raise (Stream.Error "")
end
| _ -> raise Stream.Failure
else let (_ : _ Stream.t) = strm in raise Stream.Failure
;;
let rec ident buf (strm__ : _ Stream.t) =
match
try
Some
(match Stream.peek strm__ with
Some ('A'..'Z' | 'a'..'z' | '0'..'9' | '_' | '\'' as c) ->
Stream.junk strm__; Plexing.Lexbuf.add c buf
| _ -> misc_letter buf strm__)
with Stream.Failure -> None
with
Some buf -> ident buf strm__
| _ -> buf
;;
let rec ident2_or other buf (strm__ : _ Stream.t) =
match
try
Some
(match Stream.peek strm__ with
Some
('!' | '?' | '~' | '=' | '@' | '^' | '&' | '+' | '-' | '*' |
'/' | '%' | '.' | ':' | '<' | '>' | '|' | '$' as c) ->
Stream.junk strm__; Plexing.Lexbuf.add c buf
| _ ->
try other buf strm__ with
Stream.Failure -> misc_punct buf strm__)
with Stream.Failure -> None
with
Some buf -> ident2_or other buf strm__
| _ -> buf
;;
let ident2 = ident2_or (fun buf strm -> raise Stream.Failure);;
let hash_follower_chars =
ident2_or
(fun buf (strm__ : _ Stream.t) ->
match Stream.peek strm__ with
Some '#' -> Stream.junk strm__; Plexing.Lexbuf.add '#' buf
| _ -> raise Stream.Failure)
;;
let rec ident3 buf (strm__ : _ Stream.t) =
match Stream.peek strm__ with
Some
('0'..'9' | 'A'..'Z' | 'a'..'z' | '_' | '!' | '%' | '&' | '*' | '+' |
'-' | '.' | '/' | ':' | '<' | '=' | '>' | '?' | '@' | '^' | '|' | '~' |
'\'' | '$' | '\128'..'\255' as c) ->
Stream.junk strm__; ident3 (Plexing.Lexbuf.add c buf) strm__
| _ -> buf
;;
let binary buf (strm__ : _ Stream.t) =
match Stream.peek strm__ with
Some ('0' | '1' as c) -> Stream.junk strm__; Plexing.Lexbuf.add c buf
| _ -> raise Stream.Failure
;;
let octal buf (strm__ : _ Stream.t) =
match Stream.peek strm__ with
Some ('0'..'7' as c) -> Stream.junk strm__; Plexing.Lexbuf.add c buf
| _ -> raise Stream.Failure
;;
let decimal buf (strm__ : _ Stream.t) =
match Stream.peek strm__ with
Some ('0'..'9' as c) -> Stream.junk strm__; Plexing.Lexbuf.add c buf
| _ -> raise Stream.Failure
;;
let hexa buf (strm__ : _ Stream.t) =
match Stream.peek strm__ with
Some ('0'..'9' | 'a'..'f' | 'A'..'F' as c) ->
Stream.junk strm__; Plexing.Lexbuf.add c buf
| _ -> raise Stream.Failure
;;
let end_integer buf (strm__ : _ Stream.t) =
match Stream.peek strm__ with
Some 'l' -> Stream.junk strm__; "INT_l", Plexing.Lexbuf.get buf
| Some 'L' -> Stream.junk strm__; "INT_L", Plexing.Lexbuf.get buf
| Some 'n' -> Stream.junk strm__; "INT_n", Plexing.Lexbuf.get buf
| _ -> "INT", Plexing.Lexbuf.get buf
;;
let rec digits_under kind buf (strm__ : _ Stream.t) =
match try Some (kind buf strm__) with Stream.Failure -> None with
Some buf -> digits_under kind buf strm__
| _ ->
match Stream.peek strm__ with
Some '_' ->
Stream.junk strm__;
digits_under kind (Plexing.Lexbuf.add '_' buf) strm__
| _ -> end_integer buf strm__
;;
let digits kind buf (strm__ : _ Stream.t) =
let buf =
try kind buf strm__ with
Stream.Failure -> raise (Stream.Error "ill-formed integer constant")
in
digits_under kind buf strm__
;;
let rec decimal_digits_under buf (strm__ : _ Stream.t) =
match Stream.peek strm__ with
Some ('0'..'9' | '_' as c) ->
Stream.junk strm__;
decimal_digits_under (Plexing.Lexbuf.add c buf) strm__
| _ -> buf
;;
let exponent_part buf (strm__ : _ Stream.t) =
match Stream.peek strm__ with
Some ('e' | 'E' as c) ->
Stream.junk strm__;
let buf = Plexing.Lexbuf.add c buf in
let buf =
match Stream.peek strm__ with
Some ('+' | '-' as c) ->
Stream.junk strm__; Plexing.Lexbuf.add c buf
| _ -> buf
in
begin match Stream.peek strm__ with
Some ('0'..'9' as c) ->
Stream.junk strm__;
decimal_digits_under (Plexing.Lexbuf.add c buf) strm__
| _ -> raise (Stream.Error "ill-formed floating-point constant")
end
| _ -> raise Stream.Failure
;;
let number buf (strm__ : _ Stream.t) =
let buf = decimal_digits_under buf strm__ in
match Stream.peek strm__ with
Some '.' ->
Stream.junk strm__;
let buf = decimal_digits_under (Plexing.Lexbuf.add '.' buf) strm__ in
begin match
(try Some (exponent_part buf strm__) with Stream.Failure -> None)
with
Some buf -> "FLOAT", Plexing.Lexbuf.get buf
| _ -> "FLOAT", Plexing.Lexbuf.get buf
end
| _ ->
match
try Some (exponent_part buf strm__) with Stream.Failure -> None
with
Some buf -> "FLOAT", Plexing.Lexbuf.get buf
| _ -> end_integer buf strm__
;;
(*
let hex_float_literal =
'0' ['x' 'X']
['0'-'9' 'A'-'F' 'a'-'f'] ['0'-'9' 'A'-'F' 'a'-'f' '_']*
('.' ['0'-'9' 'A'-'F' 'a'-'f' '_']* )?
(['p' 'P'] ['+' '-']? ['0'-'9'] ['0'-'9' '_']* )?
let literal_modifier = ['G'-'Z' 'g'-'z']
let hex_float_literal =
'0' ['x' 'X']
['0'-'9' 'A'-'F' 'a'-'f'] ['0'-'9' 'A'-'F' 'a'-'f' '_']*
('.' ['0'-'9' 'A'-'F' 'a'-'f' '_']* )?
(['p' 'P'] ['+' '-']? ['0'-'9'] ['0'-'9' '_']* )?
let literal_modifier = ['G'-'Z' 'g'-'z']
*)
(* hex_digits* *)
let rec hex_digits_under_star buf (strm__ : _ Stream.t) =
match Stream.peek strm__ with
Some ('0'..'9' | 'a'..'f' | 'A'..'F' | '_' as c) ->
Stream.junk strm__;
hex_digits_under_star (Plexing.Lexbuf.add c buf) strm__
| _ -> buf
;;
let rec hex_under_integer buf (strm__ : _ Stream.t) =
match Stream.peek strm__ with
Some ('0'..'9' | 'a'..'f' | 'A'..'F' as c) ->
Stream.junk strm__;
begin try hex_digits_under_star (Plexing.Lexbuf.add c buf) strm__ with
Stream.Failure -> raise (Stream.Error "")
end
| _ -> raise Stream.Failure
;;
let rec decimal_under_integer buf (strm__ : _ Stream.t) =
let buf =
match Stream.peek strm__ with
Some ('0'..'9' as c) -> Stream.junk strm__; Plexing.Lexbuf.add c buf
| _ -> buf
in
decimal_digits_under buf strm__
;;
let hex_exponent_part buf (strm__ : _ Stream.t) =
match Stream.peek strm__ with
Some ('p' | 'P' as c) ->
Stream.junk strm__;
let buf = Plexing.Lexbuf.add c buf in
let buf =
match Stream.peek strm__ with
Some ('+' | '-' as c) ->
Stream.junk strm__; Plexing.Lexbuf.add c buf
| _ -> buf
in
decimal_under_integer buf strm__
| _ -> raise Stream.Failure
;;
let hex_number buf (strm__ : _ Stream.t) =
let buf = hex_under_integer buf strm__ in
match Stream.peek strm__ with
Some '.' ->
Stream.junk strm__;
let buf = hex_digits_under_star (Plexing.Lexbuf.add '.' buf) strm__ in
begin match
(try Some (hex_exponent_part buf strm__) with Stream.Failure -> None)
with
Some buf -> "FLOAT", Plexing.Lexbuf.get buf
| _ -> "FLOAT", Plexing.Lexbuf.get buf
end
| _ ->
match
try Some (hex_exponent_part buf strm__) with Stream.Failure -> None
with
Some buf -> "FLOAT", Plexing.Lexbuf.get buf
| _ ->
match
try Some (exponent_part buf strm__) with Stream.Failure -> None
with
Some buf -> "FLOAT", Plexing.Lexbuf.get buf
| _ -> end_integer buf strm__
;;
let char_after_bslash buf (strm__ : _ Stream.t) =
match Stream.peek strm__ with
Some '\'' -> Stream.junk strm__; buf
| Some c ->
Stream.junk strm__;
let buf = Plexing.Lexbuf.add c buf in
begin try
match Stream.peek strm__ with
Some '\'' -> Stream.junk strm__; buf
| Some c ->
Stream.junk strm__;
let buf = Plexing.Lexbuf.add c buf in
begin match Stream.peek strm__ with
Some '\'' -> Stream.junk strm__; buf
| _ -> buf
end
| _ -> raise Stream.Failure
with Stream.Failure -> raise (Stream.Error "")
end
| _ -> raise Stream.Failure
;;
let char ctx bp buf (strm__ : _ Stream.t) =
match Stream.peek strm__ with
Some '\\' ->
Stream.junk strm__;
begin match Stream.peek strm__ with
Some c ->
Stream.junk strm__;
char_after_bslash
(Plexing.Lexbuf.add c (Plexing.Lexbuf.add '\\' buf)) strm__
| _ -> err ctx (bp, Stream.count strm__) "char not terminated"
end
| _ ->
match Stream.npeek 2 strm__ with
[_; '\''] ->
begin match Stream.peek strm__ with
Some c ->
Stream.junk strm__;
begin match Stream.peek strm__ with
Some '\'' -> Stream.junk strm__; Plexing.Lexbuf.add c buf
| _ -> raise (Stream.Error "")
end
| _ -> raise Stream.Failure
end
| _ -> raise Stream.Failure
;;
let any ctx buf (strm__ : _ Stream.t) =
let bp = Stream.count strm__ in
match Stream.peek strm__ with
Some c -> Stream.junk strm__; ctx.line_cnt bp c; Plexing.Lexbuf.add c buf
| _ -> raise Stream.Failure
;;
let rec skiplws buf (strm__ : _ Stream.t) =
match Stream.peek strm__ with
Some ' ' -> Stream.junk strm__; skiplws buf strm__
| Some '\t' -> Stream.junk strm__; skiplws buf strm__
| _ -> buf
;;
let incrline ctx buf (strm__ : _ Stream.t) =
let bp = Stream.count strm__ in ctx.line_cnt (bp - 1) '\n'; buf
;;
let rec string ctx bp buf (strm__ : _ Stream.t) =
match Stream.peek strm__ with
Some '"' -> Stream.junk strm__; buf
| Some '\\' ->
Stream.junk strm__;
begin try
match Stream.npeek 1 strm__ with
['\n'] ->
begin match Stream.peek strm__ with
Some '\n' ->
Stream.junk strm__;
let buf = incrline ctx buf strm__ in
let buf = skiplws buf strm__ in string ctx bp buf strm__
| _ -> raise (Stream.Error "")
end
| _ ->
match Stream.npeek 1 strm__ with
['\n'] | [' '] ->
let buf =
try any ctx buf strm__ with
Stream.Failure -> raise (Stream.Error "")
in
string ctx bp buf strm__
| _ ->
let buf = any ctx (Plexing.Lexbuf.add '\\' buf) strm__ in
string ctx bp buf strm__
with Stream.Failure -> raise (Stream.Error "")
end
| _ ->
match try Some (any ctx buf strm__) with Stream.Failure -> None with
Some buf -> string ctx bp buf strm__
| _ -> err ctx (bp, Stream.count strm__) "string not terminated"
;;
let rec quotation ctx bp buf (strm__ : _ Stream.t) =
match Stream.peek strm__ with
Some '>' ->
Stream.junk strm__;
begin match Stream.peek strm__ with
Some '>' -> Stream.junk strm__; buf
| _ -> quotation ctx bp (Plexing.Lexbuf.add '>' buf) strm__
end
| Some '<' ->
Stream.junk strm__;
begin match Stream.peek strm__ with
Some '<' ->
Stream.junk strm__;
let buf =
quotation ctx bp
(Plexing.Lexbuf.add '<' (Plexing.Lexbuf.add '<' buf)) strm__
in
let buf = Plexing.Lexbuf.add '>' (Plexing.Lexbuf.add '>' buf) in
quotation ctx bp buf strm__
| Some ':' ->
Stream.junk strm__;
let buf =
ident (Plexing.Lexbuf.add ':' (Plexing.Lexbuf.add '<' buf)) strm__
in
begin match Stream.peek strm__ with
Some '<' ->
Stream.junk strm__;
let buf =
quotation ctx bp (Plexing.Lexbuf.add '<' buf) strm__
in
let buf = Plexing.Lexbuf.add '>' (Plexing.Lexbuf.add '>' buf) in
quotation ctx bp buf strm__
| _ -> quotation ctx bp buf strm__
end
| _ -> quotation ctx bp (Plexing.Lexbuf.add '<' buf) strm__
end
| Some '\\' ->
Stream.junk strm__;
begin match Stream.peek strm__ with
Some ('>' | '<' | '\\' as c) ->
Stream.junk strm__;
quotation ctx bp (Plexing.Lexbuf.add c buf) strm__
| _ -> quotation ctx bp (Plexing.Lexbuf.add '\\' buf) strm__
end
| _ ->
match try Some (any ctx buf strm__) with Stream.Failure -> None with
Some buf -> quotation ctx bp buf strm__
| _ -> err ctx (bp, Stream.count strm__) "quotation not terminated"
;;
let less_expected = "character '<' expected";;
let less ctx bp buf strm =
if !no_quotations then
let (strm__ : _ Stream.t) = strm in
let buf = Plexing.Lexbuf.add '<' buf in
let buf = ident2 buf strm__ in
keyword_or_error ctx (bp, Stream.count strm__) (Plexing.Lexbuf.get buf)
else
let (strm__ : _ Stream.t) = strm in
match Stream.peek strm__ with
Some '<' ->
Stream.junk strm__;
let buf =
try quotation ctx bp buf strm__ with
Stream.Failure -> raise (Stream.Error "")
in
"QUOTATION", ":" ^ Plexing.Lexbuf.get buf
| Some ':' ->
Stream.junk strm__;
let buf = ident buf strm__ in
begin try
match Stream.peek strm__ with
Some '<' ->
Stream.junk strm__;
let buf = Plexing.Lexbuf.add ':' buf in
let buf =
try quotation ctx bp buf strm__ with
Stream.Failure -> raise (Stream.Error "")
in
"QUOTATION", Plexing.Lexbuf.get buf
| _ ->
match Stream.peek strm__ with
Some ':' ->
Stream.junk strm__;
begin match Stream.peek strm__ with
Some '<' ->
Stream.junk strm__;
let buf = Plexing.Lexbuf.add '@' buf in
let buf =
try quotation ctx bp buf strm__ with
Stream.Failure -> raise (Stream.Error "")
in
"QUOTATION", Plexing.Lexbuf.get buf
| _ -> raise (Stream.Error less_expected)
end
| _ -> raise Stream.Failure
with Stream.Failure -> raise (Stream.Error "")
end
| _ ->
let buf = Plexing.Lexbuf.add '<' buf in
let buf = ident2 buf strm__ in
keyword_or_error ctx (bp, Stream.count strm__)
(Plexing.Lexbuf.get buf)
;;
let rec antiquot_rest ctx bp buf (strm__ : _ Stream.t) =
match Stream.peek strm__ with
Some '$' -> Stream.junk strm__; buf
| Some '\\' ->
Stream.junk strm__;
let buf =
try any ctx buf strm__ with Stream.Failure -> raise (Stream.Error "")
in
antiquot_rest ctx bp buf strm__
| _ ->
match try Some (any ctx buf strm__) with Stream.Failure -> None with
Some buf -> antiquot_rest ctx bp buf strm__
| _ -> err ctx (bp, Stream.count strm__) "antiquotation not terminated"
;;
let rec antiquot ctx bp buf (strm__ : _ Stream.t) =
match Stream.peek strm__ with
Some '$' -> Stream.junk strm__; ":" ^ Plexing.Lexbuf.get buf
| Some ('a'..'z' | 'A'..'Z' | '0'..'9' | '!' | '_' as c) ->
Stream.junk strm__; antiquot ctx bp (Plexing.Lexbuf.add c buf) strm__
| Some ':' ->
Stream.junk strm__;
let buf = antiquot_rest ctx bp (Plexing.Lexbuf.add ':' buf) strm__ in
Plexing.Lexbuf.get buf
| Some '\\' ->
Stream.junk strm__;
let buf =
try any ctx buf strm__ with Stream.Failure -> raise (Stream.Error "")
in
let buf = antiquot_rest ctx bp buf strm__ in
":" ^ Plexing.Lexbuf.get buf
| _ ->
match try Some (any ctx buf strm__) with Stream.Failure -> None with
Some buf ->
let buf = antiquot_rest ctx bp buf strm__ in
":" ^ Plexing.Lexbuf.get buf
| _ -> err ctx (bp, Stream.count strm__) "antiquotation not terminated"
;;
let antiloc bp ep s = Printf.sprintf "%d,%d:%s" bp ep s;;
let skip_to_next_colon s i =
let rec loop j =
if j = String.length s then i, 0
else
match s.[j] with
':' -> j, j - i - 1
| 'a'..'z' | 'A'..'Z' | '0'..'9' | '!' | '_' -> loop (j + 1)
| _ -> i, 0
in
loop (i + 1)
;;
let parse_antiquot s =
try
let i = String.index s ':' in
let kind = String.sub s 0 i in
let name = String.sub s (i + 1) (String.length s - (i + 1)) in
Some (kind, name)
with Not_found | Failure _ -> None
;;
let parse_antiloc s =
try
let i = String.index s ':' in
let (j, len) = skip_to_next_colon s i in
let kind = String.sub s (i + 1) len in
let loc =
let k = String.index s ',' in
let bp = int_of_string (String.sub s 0 k) in
let ep = int_of_string (String.sub s (k + 1) (i - k - 1)) in
Ploc.make_unlined (bp, ep)
in
Some (loc, kind, String.sub s (j + 1) (String.length s - j - 1))
with Not_found | Failure _ -> None
;;
let rec antiquot_loc ctx bp buf (strm__ : _ Stream.t) =
match Stream.peek strm__ with
Some '$' ->
Stream.junk strm__;
antiloc bp (Stream.count strm__) (":" ^ Plexing.Lexbuf.get buf)
| Some ('a'..'z' | 'A'..'Z' | '0'..'9' | '!' | '_' as c) ->
Stream.junk strm__;
antiquot_loc ctx bp (Plexing.Lexbuf.add c buf) strm__
| Some ':' ->
Stream.junk strm__;
let buf = antiquot_rest ctx bp (Plexing.Lexbuf.add ':' buf) strm__ in
antiloc bp (Stream.count strm__) (Plexing.Lexbuf.get buf)
| Some '\\' ->
Stream.junk strm__;
let buf =
try any ctx buf strm__ with Stream.Failure -> raise (Stream.Error "")
in
let buf = antiquot_rest ctx bp buf strm__ in
antiloc bp (Stream.count strm__) (":" ^ Plexing.Lexbuf.get buf)
| _ ->
match try Some (any ctx buf strm__) with Stream.Failure -> None with
Some buf ->
let buf = antiquot_rest ctx bp buf strm__ in
antiloc bp (Stream.count strm__) (":" ^ Plexing.Lexbuf.get buf)
| _ -> err ctx (bp, Stream.count strm__) "antiquotation not terminated"
;;
let dollar ctx bp buf strm =
if not !no_quotations && ctx.dollar_for_antiquotation then
"ANTIQUOT", antiquot ctx bp buf strm
else if !force_antiquot_loc then
"ANTIQUOT_LOC", antiquot_loc ctx bp buf strm
else
let (strm__ : _ Stream.t) = strm in
let buf = Plexing.Lexbuf.add '$' buf in
let buf = ident2 buf strm__ in "", Plexing.Lexbuf.get buf
;;
- specific case for QUESTIONIDENT and QUESTIONIDENTCOLON
input expr patt
----- ---- ----
? $ abc : d$ ? abc : d ? abc
? $ abc : d$ : ? abc : d : ? abc :
? ? : d ?
? : ? : d : ? :
input expr patt
----- ---- ----
?$abc:d$ ?abc:d ?abc
?$abc:d$: ?abc:d: ?abc:
?$d$ ?:d ?
?$d$: ?:d: ?:
*)
ANTIQUOT_LOC - specific case for QUESTIONIDENT and QUESTIONIDENTCOLON
input expr patt
----- ---- ----
? $ abc : d$ ? 8,13 : abc : d ? abc
? $ abc : d$ : ? 8,13 : abc : d : ? abc :
? ? 8,9::d ?
? : ? 8,9::d : ? :
input expr patt
----- ---- ----
?$abc:d$ ?8,13:abc:d ?abc
?$abc:d$: ?8,13:abc:d: ?abc:
?$d$ ?8,9::d ?
?$d$: ?8,9::d: ?:
*)
let question ctx bp buf strm =
if ctx.dollar_for_antiquotation then
let (strm__ : _ Stream.t) = strm in
match Stream.peek strm__ with
Some '$' ->
Stream.junk strm__;
let s =
try antiquot ctx bp Plexing.Lexbuf.empty strm__ with
Stream.Failure -> raise (Stream.Error "")
in
begin match Stream.peek strm__ with
Some ':' -> Stream.junk strm__; "ANTIQUOT", "?" ^ s ^ ":"
| _ -> "ANTIQUOT", "?" ^ s
end
| _ ->
let (strm__ : _ Stream.t) = strm in
let buf = hash_follower_chars buf strm__ in
keyword_or_error ctx (bp, Stream.count strm__)
(Plexing.Lexbuf.get buf)
else if !force_antiquot_loc then
let (strm__ : _ Stream.t) = strm in
match Stream.peek strm__ with
Some '$' ->
Stream.junk strm__;
let s =
try antiquot_loc ctx bp Plexing.Lexbuf.empty strm__ with
Stream.Failure -> raise (Stream.Error "")
in
begin match Stream.peek strm__ with
Some ':' -> Stream.junk strm__; "ANTIQUOT_LOC", "?" ^ s ^ ":"
| _ -> "ANTIQUOT_LOC", "?" ^ s
end
| _ ->
let (strm__ : _ Stream.t) = strm in
let buf = hash_follower_chars buf strm__ in
keyword_or_error ctx (bp, Stream.count strm__)
(Plexing.Lexbuf.get buf)
else
let (strm__ : _ Stream.t) = strm in
let buf = hash_follower_chars buf strm__ in
keyword_or_error ctx (bp, Stream.count strm__) (Plexing.Lexbuf.get buf)
;;
let tilde ctx bp buf strm =
if ctx.dollar_for_antiquotation then
let (strm__ : _ Stream.t) = strm in
match Stream.peek strm__ with
Some '$' ->
Stream.junk strm__;
let s =
try antiquot ctx bp Plexing.Lexbuf.empty strm__ with
Stream.Failure -> raise (Stream.Error "")
in
begin match Stream.peek strm__ with
Some ':' -> Stream.junk strm__; "ANTIQUOT", "~" ^ s ^ ":"
| _ -> "ANTIQUOT", "~" ^ s
end
| _ ->
let (strm__ : _ Stream.t) = strm in
let buf = hash_follower_chars buf strm__ in
keyword_or_error ctx (bp, Stream.count strm__)
(Plexing.Lexbuf.get buf)
else if !force_antiquot_loc then
let (strm__ : _ Stream.t) = strm in
match Stream.peek strm__ with
Some '$' ->
Stream.junk strm__;
let s =
try antiquot_loc ctx bp Plexing.Lexbuf.empty strm__ with
Stream.Failure -> raise (Stream.Error "")
in
begin match Stream.peek strm__ with
Some ':' -> Stream.junk strm__; "ANTIQUOT_LOC", "~" ^ s ^ ":"
| _ -> "ANTIQUOT_LOC", "~" ^ s
end
| _ ->
let (strm__ : _ Stream.t) = strm in
let buf = hash_follower_chars buf strm__ in
keyword_or_error ctx (bp, Stream.count strm__)
(Plexing.Lexbuf.get buf)
else
let (strm__ : _ Stream.t) = strm in
let buf = hash_follower_chars buf strm__ in
keyword_or_error ctx (bp, Stream.count strm__) (Plexing.Lexbuf.get buf)
;;
let tildeident buf (strm__ : _ Stream.t) =
match Stream.peek strm__ with
Some ':' -> Stream.junk strm__; "TILDEIDENTCOLON", Plexing.Lexbuf.get buf
| _ -> "TILDEIDENT", Plexing.Lexbuf.get buf
;;
let questionident buf (strm__ : _ Stream.t) =
match Stream.peek strm__ with
Some ':' ->
Stream.junk strm__; "QUESTIONIDENTCOLON", Plexing.Lexbuf.get buf
| _ -> "QUESTIONIDENT", Plexing.Lexbuf.get buf
;;
let rec linedir n s =
match stream_peek_nth n s with
Some (' ' | '\t') -> linedir (n + 1) s
| Some ('0'..'9') -> linedir_digits (n + 1) s
| _ -> false
and linedir_digits n s =
match stream_peek_nth n s with
Some ('0'..'9') -> linedir_digits (n + 1) s
| _ -> linedir_quote n s
and linedir_quote n s =
match stream_peek_nth n s with
Some (' ' | '\t') -> linedir_quote (n + 1) s
| Some '"' -> true
| _ -> false
;;
let rec any_to_nl buf (strm__ : _ Stream.t) =
match Stream.peek strm__ with
Some ('\r' | '\n' as c) -> Stream.junk strm__; Plexing.Lexbuf.add c buf
| Some c -> Stream.junk strm__; any_to_nl (Plexing.Lexbuf.add c buf) strm__
| _ -> buf
;;
let rec rawstring1 delimtok (ofs, delim) ctx buf (strm__ : _ Stream.t) =
let bp = Stream.count strm__ in
match Stream.peek strm__ with
Some c ->
Stream.junk strm__;
let strm = strm__ in
ctx.line_cnt bp c;
let buf = Plexing.Lexbuf.add c buf in
if String.get delim ofs <> c then
if String.get delim 0 = c then
rawstring1 delimtok (1, delim) ctx buf strm
else rawstring1 delimtok (0, delim) ctx buf strm
else if ofs + 1 < String.length delim then
rawstring1 delimtok (ofs + 1, delim) ctx buf strm
else
let s = Plexing.Lexbuf.get buf in
let slen = String.length s in
delimtok, String.sub s 0 (slen - String.length delim)
| _ -> raise Stream.Failure
;;
let rec rawstring0 ctx bp buf (strm__ : _ Stream.t) =
let bp = Stream.count strm__ in
match Stream.peek strm__ with
Some '|' ->
Stream.junk strm__;
let strm = strm__ in
rawstring1 (Plexing.Lexbuf.get buf)
(0, "|" ^ Plexing.Lexbuf.get buf ^ "}") ctx Plexing.Lexbuf.empty strm
| Some ('a'..'z' | '_' as c) ->
Stream.junk strm__;
let strm = strm__ in rawstring0 ctx bp (Plexing.Lexbuf.add c buf) strm
| _ -> raise Stream.Failure
;;
let add_string buf s =
let slen = String.length s in
let rec addrec buf i =
if i = slen then buf
else addrec (Plexing.Lexbuf.add (String.get s i) buf) (i + 1)
in
addrec buf 0
;;
(*
* This predicate checks that the stream contains a valid raw-string starter.
* The definition of "valid raw string starter" depends on the value of
* the variable [simplest_raw_strings]: if it is [False], then a valid
* raw-string starter is "[:alpha:]+|"; if it is [True], a valid raw-string
* starter is "[:alpha:]*|". [simplest_raw_strings] is set to True in
* original syntax.
* This predicate gets called when the main lexer has already seen a "{".
*)
let raw_string_starter_p ctx strm =
let rec predrec n =
match stream_peek_nth n strm with
None -> false
| Some ('a'..'z' | '_') -> predrec (n + 1)
| Some '|' when ctx.simplest_raw_strings || n > 1 -> true
| Some _ -> false
in
predrec 1
;;
let comment_rawstring ctx bp (buf : Plexing.Lexbuf.t) strm =
if not (raw_string_starter_p ctx strm) then buf
else
let (delim, s) = rawstring0 ctx bp Plexing.Lexbuf.empty strm in
let rs = Printf.sprintf "{%s|%s|%s}" delim s delim in add_string buf rs
;;
let comment ctx bp =
let rec comment buf (strm__ : _ Stream.t) =
match Stream.peek strm__ with
Some '*' ->
Stream.junk strm__;
begin match Stream.peek strm__ with
Some ')' ->
Stream.junk strm__;
Plexing.Lexbuf.add ')' (Plexing.Lexbuf.add '*' buf)
| _ -> comment (Plexing.Lexbuf.add '*' buf) strm__
end
| Some '{' ->
Stream.junk strm__;
let buf =
comment_rawstring ctx bp (Plexing.Lexbuf.add '{' buf) strm__
in
comment buf strm__
| Some '(' ->
Stream.junk strm__;
begin match Stream.peek strm__ with
Some '*' ->
Stream.junk strm__;
let buf =
comment (Plexing.Lexbuf.add '*' (Plexing.Lexbuf.add '(' buf))
strm__
in
comment buf strm__
| _ -> comment (Plexing.Lexbuf.add '(' buf) strm__
end
| Some '"' ->
Stream.junk strm__;
let buf = string ctx bp (Plexing.Lexbuf.add '"' buf) strm__ in
let buf = Plexing.Lexbuf.add '"' buf in comment buf strm__
| Some '\'' ->
Stream.junk strm__;
begin try
match Stream.peek strm__ with
Some '*' ->
Stream.junk strm__;
begin match Stream.peek strm__ with
Some ')' ->
Stream.junk strm__;
Plexing.Lexbuf.add ')'
(Plexing.Lexbuf.add '*' (Plexing.Lexbuf.add '\'' buf))
| _ ->
comment
(Plexing.Lexbuf.add '*' (Plexing.Lexbuf.add '\'' buf))
strm__
end
| _ ->
let buf = any ctx (Plexing.Lexbuf.add '\'' buf) strm__ in
comment buf strm__
with Stream.Failure -> raise (Stream.Error "")
end
| _ ->
match try Some (any ctx buf strm__) with Stream.Failure -> None with
Some buf -> comment buf strm__
| _ -> err ctx (bp, Stream.count strm__) "comment not terminated"
in
comment
;;
let keyword_or_error_or_rawstring ctx bp (loc, s) buf strm =
if not (raw_string_starter_p ctx strm) then
match stream_peek_nth 1 strm with
Some '|' when not ctx.simplest_raw_strings ->
Stream.junk strm; keyword_or_error ctx loc "{|"
| _ -> keyword_or_error ctx loc "{"
else
let (delim, s) = rawstring0 ctx bp Plexing.Lexbuf.empty strm in
"STRING", String.escaped s
;;
let zerobuf f buf strm = f Plexing.Lexbuf.empty strm;;
let rec ws buf (strm__ : _ Stream.t) =
let buf =
match Stream.peek strm__ with
Some ' ' -> Stream.junk strm__; buf
| Some '\t' -> Stream.junk strm__; buf
| Some '\n' -> Stream.junk strm__; buf
| _ -> raise Stream.Failure
in
try ws buf strm__ with Stream.Failure -> buf
;;
let rec extattrident buf (strm__ : _ Stream.t) =
let buf = ident buf strm__ in
match Stream.peek strm__ with
Some '.' ->
Stream.junk strm__;
begin try extattrident (Plexing.Lexbuf.add '.' buf) strm__ with
Stream.Failure -> raise (Stream.Error "")
end
| _ -> buf
;;
let quoted_extension1 ctx (bp, _) extid buf strm =
let (delim, s) = rawstring0 ctx bp Plexing.Lexbuf.empty strm in
"QUOTEDEXTENSION", extid ^ ":" ^ String.escaped s
;;
let quoted_extension0 ctx (bp, _) extid buf (strm__ : _ Stream.t) =
match try Some (ws buf strm__) with Stream.Failure -> None with
Some buf ->
begin try
zerobuf (quoted_extension1 ctx (bp, Stream.count strm__) extid) buf
strm__
with Stream.Failure -> raise (Stream.Error "")
end
| _ ->
zerobuf (quoted_extension1 ctx (bp, Stream.count strm__) extid) buf
strm__
;;
let quoted_extension ctx (bp, _) buf (strm__ : _ Stream.t) =
let buf = extattrident buf strm__ in
try
zerobuf
(quoted_extension0 ctx (bp, Stream.count strm__)
(Plexing.Lexbuf.get buf))
buf strm__
with Stream.Failure -> raise (Stream.Error "")
;;
let dotsymbolchar buf (strm__ : _ Stream.t) =
match Stream.peek strm__ with
Some
('!' | '$' | '%' | '&' | '*' | '+' | '-' | '/' | ':' | '=' | '>' | '?' |
'@' | '^' | '|' as c) ->
Stream.junk strm__; Plexing.Lexbuf.add c buf
| _ -> raise Stream.Failure
;;
let rec dotsymbolchar_star buf (strm__ : _ Stream.t) =
match try Some (dotsymbolchar buf strm__) with Stream.Failure -> None with
Some buf ->
begin try dotsymbolchar_star buf strm__ with
Stream.Failure -> raise (Stream.Error "")
end
| _ -> buf
;;
let kwdopchar buf (strm__ : _ Stream.t) =
match Stream.peek strm__ with
Some
('$' | '&' | '*' | '+' | '-' | '/' | '<' | '=' | '>' | '@' | '^' |
'|' as c) ->
Stream.junk strm__; Plexing.Lexbuf.add c buf
| _ -> raise Stream.Failure
;;
let symbolchar buf (strm__ : _ Stream.t) =
match Stream.peek strm__ with
Some
('!' | '$' | '%' | '&' | '*' | '+' | '-' | '.' | '/' | ':' | '<' | '=' |
'>' | '?' | '@' | '^' | '|' | '~' as c) ->
Stream.junk strm__; Plexing.Lexbuf.add c buf
| _ -> raise Stream.Failure
;;
let rec symbolchar_star buf (strm__ : _ Stream.t) =
match try Some (symbolchar buf strm__) with Stream.Failure -> None with
Some buf ->
begin try symbolchar_star buf strm__ with
Stream.Failure -> raise (Stream.Error "")
end
| _ -> buf
;;
let word_operators ctx id buf (strm__ : _ Stream.t) =
match try Some (kwdopchar buf strm__) with Stream.Failure -> None with
Some buf ->
let buf =
try dotsymbolchar_star buf strm__ with
Stream.Failure -> raise (Stream.Error "")
in
"", id ^ Plexing.Lexbuf.get buf
| _ -> try "", ctx.find_kwd id with Not_found -> "LIDENT", id
;;
let keyword ctx buf strm =
let id = Plexing.Lexbuf.get buf in
if id = "let" || id = "and" then
word_operators ctx id Plexing.Lexbuf.empty strm
else try "", ctx.find_kwd id with Not_found -> "LIDENT", id
;;
let dot ctx (bp, pos) buf strm =
match Stream.peek strm with
None ->
let id =
if ctx.specific_space_dot && ctx.after_space then " ." else "."
in
keyword_or_error ctx (bp, pos) id
| _ ->
let (strm__ : _ Stream.t) = strm in
let buf = Plexing.Lexbuf.add '.' buf in
let buf = dotsymbolchar_star buf strm__ in
keyword_or_error ctx (bp, Stream.count strm__) (Plexing.Lexbuf.get buf)
;;
let next_token_after_spaces ctx bp buf (strm__ : _ Stream.t) =
match Stream.peek strm__ with
Some ('A'..'Z' as c) ->
Stream.junk strm__;
let buf = ident (Plexing.Lexbuf.add c buf) strm__ in
let id = Plexing.Lexbuf.get buf in
(try "", ctx.find_kwd id with Not_found -> "UIDENT", id)
| _ ->
match
try Some (greek_letter buf strm__) with Stream.Failure -> None
with
Some buf ->
let buf = ident buf strm__ in "GIDENT", Plexing.Lexbuf.get buf
| _ ->
match
try
Some
(match Stream.peek strm__ with
Some ('a'..'z' | '_' as c) ->
Stream.junk strm__; Plexing.Lexbuf.add c buf
| _ -> misc_letter buf strm__)
with Stream.Failure -> None
with
Some buf ->
let buf = ident buf strm__ in
begin try keyword ctx buf strm__ with
Stream.Failure -> raise (Stream.Error "")
end
| _ ->
match Stream.peek strm__ with
Some ('1'..'9' as c) ->
Stream.junk strm__; number (Plexing.Lexbuf.add c buf) strm__
| Some '0' ->
Stream.junk strm__;
begin match Stream.peek strm__ with
Some ('o' | 'O' as c) ->
Stream.junk strm__;
digits octal
(Plexing.Lexbuf.add c (Plexing.Lexbuf.add '0' buf))
strm__
| Some ('x' | 'X' as c) ->
Stream.junk strm__;
hex_number
(Plexing.Lexbuf.add c (Plexing.Lexbuf.add '0' buf))
strm__
| Some ('b' | 'B' as c) ->
Stream.junk strm__;
digits binary
(Plexing.Lexbuf.add c (Plexing.Lexbuf.add '0' buf))
strm__
| _ -> number (Plexing.Lexbuf.add '0' buf) strm__
end
| Some '\'' ->
Stream.junk strm__;
begin match Stream.npeek 3 strm__ with
['\\'; 'a'..'z'; 'a'..'z'] ->
keyword_or_error ctx (bp, Stream.count strm__) "'"
| _ ->
match
try Some (char ctx bp buf strm__) with
Stream.Failure -> None
with
Some buf -> "CHAR", Plexing.Lexbuf.get buf
| _ ->
keyword_or_error ctx (bp, Stream.count strm__) "'"
end
| Some '"' ->
Stream.junk strm__;
let buf = string ctx bp buf strm__ in
"STRING", Plexing.Lexbuf.get buf
| Some '$' -> Stream.junk strm__; dollar ctx bp buf strm__
| Some
('=' | '@' | '^' | '&' | '+' | '-' | '*' | '/' |
'%' as c) ->
Stream.junk strm__;
let buf = ident2 (Plexing.Lexbuf.add c buf) strm__ in
keyword_or_error ctx (bp, Stream.count strm__)
(Plexing.Lexbuf.get buf)
| Some '!' ->
Stream.junk strm__;
let buf =
hash_follower_chars (Plexing.Lexbuf.add '!' buf) strm__
in
keyword_or_error ctx (bp, Stream.count strm__)
(Plexing.Lexbuf.get buf)
| Some '~' ->
Stream.junk strm__;
begin try
match Stream.peek strm__ with
Some ('a'..'z' as c) ->
Stream.junk strm__;
let buf = ident (Plexing.Lexbuf.add c buf) strm__ in
tildeident buf strm__
| Some '_' ->
Stream.junk strm__;
let buf = ident (Plexing.Lexbuf.add '_' buf) strm__ in
tildeident buf strm__
| _ -> tilde ctx bp (Plexing.Lexbuf.add '~' buf) strm__
with Stream.Failure -> raise (Stream.Error "")
end
| Some '?' ->
Stream.junk strm__;
begin match Stream.peek strm__ with
Some ('a'..'z' as c) ->
Stream.junk strm__;
let buf = ident (Plexing.Lexbuf.add c buf) strm__ in
questionident buf strm__
| _ -> question ctx bp (Plexing.Lexbuf.add '?' buf) strm__
end
| Some '<' -> Stream.junk strm__; less ctx bp buf strm__
| Some ':' ->
Stream.junk strm__;
begin match Stream.peek strm__ with
Some ']' ->
Stream.junk strm__;
keyword_or_error ctx (bp, Stream.count strm__)
(Plexing.Lexbuf.get
(Plexing.Lexbuf.add ']'
(Plexing.Lexbuf.add ':' buf)))
| Some ':' ->
Stream.junk strm__;
keyword_or_error ctx (bp, Stream.count strm__)
(Plexing.Lexbuf.get
(Plexing.Lexbuf.add ':'
(Plexing.Lexbuf.add ':' buf)))
| Some '=' ->
Stream.junk strm__;
keyword_or_error ctx (bp, Stream.count strm__)
(Plexing.Lexbuf.get
(Plexing.Lexbuf.add '='
(Plexing.Lexbuf.add ':' buf)))
| Some '>' ->
Stream.junk strm__;
keyword_or_error ctx (bp, Stream.count strm__)
(Plexing.Lexbuf.get
(Plexing.Lexbuf.add '>'
(Plexing.Lexbuf.add ':' buf)))
| _ ->
keyword_or_error ctx (bp, Stream.count strm__)
(Plexing.Lexbuf.get (Plexing.Lexbuf.add ':' buf))
end
| Some '>' ->
Stream.junk strm__;
begin match Stream.peek strm__ with
Some ']' ->
Stream.junk strm__;
keyword_or_error ctx (bp, Stream.count strm__)
(Plexing.Lexbuf.get
(Plexing.Lexbuf.add ']'
(Plexing.Lexbuf.add '>' buf)))
| Some '}' ->
Stream.junk strm__;
keyword_or_error ctx (bp, Stream.count strm__)
(Plexing.Lexbuf.get
(Plexing.Lexbuf.add '}'
(Plexing.Lexbuf.add '>' buf)))
| _ ->
let buf = ident2 (Plexing.Lexbuf.add '>' buf) strm__ in
keyword_or_error ctx (bp, Stream.count strm__)
(Plexing.Lexbuf.get buf)
end
| Some '|' ->
Stream.junk strm__;
begin match Stream.peek strm__ with
Some ']' ->
Stream.junk strm__;
keyword_or_error ctx (bp, Stream.count strm__)
(Plexing.Lexbuf.get
(Plexing.Lexbuf.add ']'
(Plexing.Lexbuf.add '|' buf)))
| Some '}' ->
Stream.junk strm__;
keyword_or_error ctx (bp, Stream.count strm__)
(Plexing.Lexbuf.get
(Plexing.Lexbuf.add '}'
(Plexing.Lexbuf.add '|' buf)))
| _ ->
let buf = ident2 (Plexing.Lexbuf.add '|' buf) strm__ in
keyword_or_error ctx (bp, Stream.count strm__)
(Plexing.Lexbuf.get buf)
end
| Some '[' ->
Stream.junk strm__;
begin match Stream.npeek 2 strm__ with
['<'; '<'] | ['<'; ':'] ->
keyword_or_error ctx (bp, Stream.count strm__)
(Plexing.Lexbuf.get (Plexing.Lexbuf.add '[' buf))
| _ ->
match Stream.peek strm__ with
Some '@' ->
Stream.junk strm__;
begin match Stream.peek strm__ with
Some '@' ->
Stream.junk strm__;
begin match Stream.peek strm__ with
Some '@' ->
Stream.junk strm__;
keyword_or_error ctx
(bp, Stream.count strm__)
(Plexing.Lexbuf.get
(Plexing.Lexbuf.add '@'
(Plexing.Lexbuf.add '@'
(Plexing.Lexbuf.add '@'
(Plexing.Lexbuf.add '['
buf)))))
| _ ->
keyword_or_error ctx
(bp, Stream.count strm__)
(Plexing.Lexbuf.get
(Plexing.Lexbuf.add '@'
(Plexing.Lexbuf.add '@'
(Plexing.Lexbuf.add '[' buf))))
end
| _ ->
keyword_or_error ctx (bp, Stream.count strm__)
(Plexing.Lexbuf.get
(Plexing.Lexbuf.add '@'
(Plexing.Lexbuf.add '[' buf)))
end
| Some '%' ->
Stream.junk strm__;
begin match Stream.peek strm__ with
Some '%' ->
Stream.junk strm__;
keyword_or_error ctx (bp, Stream.count strm__)
(Plexing.Lexbuf.get
(Plexing.Lexbuf.add '%'
(Plexing.Lexbuf.add '%'
(Plexing.Lexbuf.add '[' buf))))
| _ ->
keyword_or_error ctx (bp, Stream.count strm__)
(Plexing.Lexbuf.get
(Plexing.Lexbuf.add '%'
(Plexing.Lexbuf.add '[' buf)))
end
| Some '|' ->
Stream.junk strm__;
keyword_or_error ctx (bp, Stream.count strm__)
(Plexing.Lexbuf.get
(Plexing.Lexbuf.add '|'
(Plexing.Lexbuf.add '[' buf)))
| Some '<' ->
Stream.junk strm__;
keyword_or_error ctx (bp, Stream.count strm__)
(Plexing.Lexbuf.get
(Plexing.Lexbuf.add '<'
(Plexing.Lexbuf.add '[' buf)))
| Some ':' ->
Stream.junk strm__;
keyword_or_error ctx (bp, Stream.count strm__)
(Plexing.Lexbuf.get
(Plexing.Lexbuf.add ':'
(Plexing.Lexbuf.add '[' buf)))
| _ ->
keyword_or_error ctx (bp, Stream.count strm__)
(Plexing.Lexbuf.get (Plexing.Lexbuf.add '[' buf))
end
| Some '{' ->
Stream.junk strm__;
begin try
match Stream.npeek 2 strm__ with
['<'; '<'] | ['<'; ':'] ->
keyword_or_error ctx (bp, Stream.count strm__)
(Plexing.Lexbuf.get (Plexing.Lexbuf.add '{' buf))
| _ ->
match Stream.peek strm__ with
Some '<' ->
Stream.junk strm__;
keyword_or_error ctx (bp, Stream.count strm__)
(Plexing.Lexbuf.get
(Plexing.Lexbuf.add '<'
(Plexing.Lexbuf.add '{' buf)))
| Some '%' ->
Stream.junk strm__;
begin try
zerobuf
(quoted_extension ctx
(bp, Stream.count strm__))
buf strm__
with Stream.Failure -> raise (Stream.Error "")
end
| Some ':' ->
Stream.junk strm__;
keyword_or_error ctx (bp, Stream.count strm__)
(Plexing.Lexbuf.get
(Plexing.Lexbuf.add ':'
(Plexing.Lexbuf.add '{' buf)))
| _ ->
keyword_or_error_or_rawstring ctx bp
((bp, Stream.count strm__),
Plexing.Lexbuf.get buf)
(Plexing.Lexbuf.add '{' buf) strm__
with Stream.Failure -> raise (Stream.Error "")
end
| Some '.' ->
Stream.junk strm__;
begin match Stream.peek strm__ with
Some '.' ->
Stream.junk strm__;
keyword_or_error ctx (bp, Stream.count strm__) ".."
| _ ->
match
try
Some
(dotsymbolchar (Plexing.Lexbuf.add '.' buf)
strm__)
with Stream.Failure -> None
with
Some buf ->
let buf =
try symbolchar_star buf strm__ with
Stream.Failure -> raise (Stream.Error "")
in
keyword_or_error ctx (bp, Stream.count strm__)
(Plexing.Lexbuf.get buf)
| _ ->
let id =
if ctx.specific_space_dot && ctx.after_space then
" ."
else "."
in
keyword_or_error ctx (bp, Stream.count strm__) id
end
| Some ';' ->
Stream.junk strm__;
begin match Stream.peek strm__ with
Some ';' ->
Stream.junk strm__;
keyword_or_error ctx (bp, Stream.count strm__) ";;"
| _ -> keyword_or_error ctx (bp, Stream.count strm__) ";"
end
| _ ->
try utf8_equiv ctx bp buf strm__ with
Stream.Failure ->
match
try Some (misc_punct buf strm__) with
Stream.Failure -> None
with
Some buf ->
let buf = ident2 buf strm__ in
keyword_or_error ctx (bp, Stream.count strm__)
(Plexing.Lexbuf.get buf)
| _ ->
match Stream.peek strm__ with
Some '\\' ->
Stream.junk strm__;
let buf = ident3 buf strm__ in
"LIDENT", Plexing.Lexbuf.get buf
| Some '#' ->
Stream.junk strm__;
let buf =
hash_follower_chars
(Plexing.Lexbuf.add '#' buf) strm__
in
keyword_or_error ctx (bp, Stream.count strm__)
(Plexing.Lexbuf.get buf)
| _ ->
let buf = any ctx buf strm__ in
keyword_or_error ctx (bp, Stream.count strm__)
(Plexing.Lexbuf.get buf)
;;
let get_comment buf strm = Plexing.Lexbuf.get buf;;
let rec next_token ctx buf (strm__ : _ Stream.t) =
let bp = Stream.count strm__ in
match Stream.peek strm__ with
Some ('\n' | '\r' as c) ->
Stream.junk strm__;
let s = strm__ in
let ep = Stream.count strm__ in
if c = '\n' then incr !(Plexing.line_nb);
!(Plexing.bol_pos) := ep;
ctx.set_line_nb ();
ctx.after_space <- true;
next_token ctx (Plexing.Lexbuf.add c buf) s
| Some (' ' | '\t' | '\026' | '\012' as c) ->
Stream.junk strm__;
let s = strm__ in
ctx.after_space <- true; next_token ctx (Plexing.Lexbuf.add c buf) s
| Some '#' when bp = !(!(Plexing.bol_pos)) ->
Stream.junk strm__;
let s = strm__ in
let comm = get_comment buf () in
if linedir 1 s then
let buf = any_to_nl (Plexing.Lexbuf.add '#' buf) s in
incr !(Plexing.line_nb);
!(Plexing.bol_pos) := Stream.count s;
ctx.set_line_nb ();
ctx.after_space <- true;
next_token ctx buf s
else
let loc = ctx.make_lined_loc (bp, bp + 1) comm in
keyword_or_error ctx (bp, bp + 1) "#", loc
| Some '(' ->
Stream.junk strm__;
begin match Stream.peek strm__ with
Some '*' ->
Stream.junk strm__;
let buf =
comment ctx bp
(Plexing.Lexbuf.add '*' (Plexing.Lexbuf.add '(' buf)) strm__
in
let s = strm__ in
ctx.set_line_nb (); ctx.after_space <- true; next_token ctx buf s
| _ ->
let ep = Stream.count strm__ in
let loc = ctx.make_lined_loc (bp, ep) (Plexing.Lexbuf.get buf) in
keyword_or_error ctx (bp, ep) "(", loc
end
| _ ->
let comm = get_comment buf strm__ in
try
match
try
Some (next_token_after_spaces ctx bp Plexing.Lexbuf.empty strm__)
with Stream.Failure -> None
with
Some tok ->
let ep = Stream.count strm__ in
let loc = ctx.make_lined_loc (bp, max (bp + 1) ep) comm in
tok, loc
| _ ->
let _ = Stream.empty strm__ in
let loc = ctx.make_lined_loc (bp, bp + 1) comm in ("EOI", ""), loc
with Stream.Failure -> raise (Stream.Error "")
;;
let next_token_fun ctx glexr (cstrm, s_line_nb, s_bol_pos) =
try
begin match !(Plexing.restore_lexing_info) with
Some (line_nb, bol_pos) ->
s_line_nb := line_nb;
s_bol_pos := bol_pos;
Plexing.restore_lexing_info := None
| None -> ()
end;
Plexing.line_nb := s_line_nb;
Plexing.bol_pos := s_bol_pos;
let comm_bp = Stream.count cstrm in
ctx.set_line_nb ();
ctx.after_space <- false;
let (r, loc) = next_token ctx Plexing.Lexbuf.empty cstrm in
begin match !glexr.Plexing.tok_comm with
Some list ->
if Ploc.first_pos loc > comm_bp then
let comm_loc = Ploc.make_unlined (comm_bp, Ploc.last_pos loc) in
!glexr.Plexing.tok_comm <- Some (comm_loc :: list)
| None -> ()
end;
r, loc
with Stream.Error str ->
err ctx (Stream.count cstrm, Stream.count cstrm + 1) str
;;
let make_ctx kwd_table =
let line_nb = ref 0 in
let bol_pos = ref 0 in
{after_space = false; dollar_for_antiquotation = !dollar_for_antiquotation;
simplest_raw_strings = !simplest_raw_strings;
specific_space_dot = !specific_space_dot;
find_kwd = Hashtbl.find kwd_table;
line_cnt =
(fun bp1 c ->
match c with
'\n' | '\r' ->
if c = '\n' then incr !(Plexing.line_nb);
!(Plexing.bol_pos) := bp1 + 1
| c -> ());
set_line_nb =
(fun () ->
line_nb := !(!(Plexing.line_nb)); bol_pos := !(!(Plexing.bol_pos)));
make_lined_loc =
fun loc comm ->
Ploc.make_loc !(Plexing.input_file) !line_nb !bol_pos loc comm}
;;
let func ctx kwd_table glexr =
Plexing.lexer_func_of_parser (next_token_fun ctx glexr)
;;
let rec check_keyword_stream (strm__ : _ Stream.t) =
let _ = check Plexing.Lexbuf.empty strm__ in
let _ =
try Stream.empty strm__ with Stream.Failure -> raise (Stream.Error "")
in
true
and check buf (strm__ : _ Stream.t) =
match
try
Some
(match Stream.peek strm__ with
Some ('A'..'Z' | 'a'..'z' as c) ->
Stream.junk strm__; Plexing.Lexbuf.add c buf
| _ -> misc_letter buf strm__)
with Stream.Failure -> None
with
Some buf -> check_ident buf strm__
| _ ->
match Stream.peek strm__ with
Some
('!' | '?' | '~' | '=' | '@' | '^' | '&' | '+' | '-' | '*' | '/' |
'%' | '.' as c) ->
Stream.junk strm__; check_ident2 (Plexing.Lexbuf.add c buf) strm__
| Some '$' ->
Stream.junk strm__; check_ident2 (Plexing.Lexbuf.add '$' buf) strm__
| Some '<' ->
Stream.junk strm__;
begin match Stream.npeek 1 strm__ with
[':'] | ['<'] -> Plexing.Lexbuf.add '<' buf
| _ -> check_ident2 (Plexing.Lexbuf.add '<' buf) strm__
end
| Some ':' ->
Stream.junk strm__;
begin match Stream.peek strm__ with
Some ']' ->
Stream.junk strm__;
Plexing.Lexbuf.add ']' (Plexing.Lexbuf.add ':' buf)
| Some ':' ->
Stream.junk strm__;
Plexing.Lexbuf.add ':' (Plexing.Lexbuf.add ':' buf)
| Some '=' ->
Stream.junk strm__;
Plexing.Lexbuf.add '=' (Plexing.Lexbuf.add ':' buf)
| Some '>' ->
Stream.junk strm__;
Plexing.Lexbuf.add '>' (Plexing.Lexbuf.add ':' buf)
| _ -> Plexing.Lexbuf.add ':' buf
end
| Some '>' ->
Stream.junk strm__;
begin match Stream.peek strm__ with
Some ']' ->
Stream.junk strm__;
Plexing.Lexbuf.add ']' (Plexing.Lexbuf.add '>' buf)
| Some '}' ->
Stream.junk strm__;
Plexing.Lexbuf.add '}' (Plexing.Lexbuf.add '>' buf)
| _ -> check_ident2 (Plexing.Lexbuf.add '>' buf) strm__
end
| Some '|' ->
Stream.junk strm__;
begin match Stream.peek strm__ with
Some ']' ->
Stream.junk strm__;
Plexing.Lexbuf.add ']' (Plexing.Lexbuf.add '|' buf)
| Some '}' ->
Stream.junk strm__;
Plexing.Lexbuf.add '}' (Plexing.Lexbuf.add '|' buf)
| _ -> check_ident2 (Plexing.Lexbuf.add '|' buf) strm__
end
| Some '[' ->
Stream.junk strm__;
begin match Stream.npeek 2 strm__ with
['<'; '<'] | ['<'; ':'] -> Plexing.Lexbuf.add '[' buf
| _ ->
match Stream.peek strm__ with
Some '@' ->
Stream.junk strm__;
begin match Stream.peek strm__ with
Some '@' ->
Stream.junk strm__;
begin match Stream.peek strm__ with
Some '@' ->
Stream.junk strm__;
Plexing.Lexbuf.add '@'
(Plexing.Lexbuf.add '@'
(Plexing.Lexbuf.add '@'
(Plexing.Lexbuf.add '[' buf)))
| _ ->
Plexing.Lexbuf.add '@'
(Plexing.Lexbuf.add '@'
(Plexing.Lexbuf.add '[' buf))
end
| _ -> Plexing.Lexbuf.add '@' (Plexing.Lexbuf.add '[' buf)
end
| Some '%' ->
Stream.junk strm__;
begin match Stream.peek strm__ with
Some '%' ->
Stream.junk strm__;
Plexing.Lexbuf.add '%'
(Plexing.Lexbuf.add '%' (Plexing.Lexbuf.add '[' buf))
| _ -> Plexing.Lexbuf.add '%' (Plexing.Lexbuf.add '[' buf)
end
| Some '|' ->
Stream.junk strm__;
Plexing.Lexbuf.add '|' (Plexing.Lexbuf.add '[' buf)
| Some '<' ->
Stream.junk strm__;
Plexing.Lexbuf.add '<' (Plexing.Lexbuf.add '[' buf)
| Some ':' ->
Stream.junk strm__;
Plexing.Lexbuf.add ':' (Plexing.Lexbuf.add '[' buf)
| _ -> Plexing.Lexbuf.add '[' buf
end
| Some '{' ->
Stream.junk strm__;
begin match Stream.npeek 2 strm__ with
['<'; '<'] | ['<'; ':'] -> Plexing.Lexbuf.add '{' buf
| _ ->
match Stream.peek strm__ with
Some '|' ->
Stream.junk strm__;
Plexing.Lexbuf.add '|' (Plexing.Lexbuf.add '{' buf)
| Some '<' ->
Stream.junk strm__;
Plexing.Lexbuf.add '<' (Plexing.Lexbuf.add '{' buf)
| Some ':' ->
Stream.junk strm__;
Plexing.Lexbuf.add ':' (Plexing.Lexbuf.add '{' buf)
| _ -> Plexing.Lexbuf.add '{' buf
end
| Some ';' ->
Stream.junk strm__;
begin match Stream.peek strm__ with
Some ';' ->
Stream.junk strm__;
Plexing.Lexbuf.add ';' (Plexing.Lexbuf.add ';' buf)
| _ -> Plexing.Lexbuf.add ';' buf
end
| _ ->
match
try Some (misc_punct buf strm__) with Stream.Failure -> None
with
Some buf -> check_ident2 buf strm__
| _ ->
match Stream.peek strm__ with
Some c -> Stream.junk strm__; Plexing.Lexbuf.add c buf
| _ -> raise Stream.Failure
and check_ident buf (strm__ : _ Stream.t) =
match
try
Some
(match Stream.peek strm__ with
Some ('A'..'Z' | 'a'..'z' | '0'..'9' | '_' | '\'' as c) ->
Stream.junk strm__; Plexing.Lexbuf.add c buf
| _ -> misc_letter buf strm__)
with Stream.Failure -> None
with
Some buf -> check_ident buf strm__
| _ -> buf
and check_ident2 buf (strm__ : _ Stream.t) =
match
try
Some
(match Stream.peek strm__ with
Some
('!' | '?' | '~' | '=' | '@' | '^' | '&' | '+' | '-' | '*' |
'/' | '%' | '.' | ':' | '<' | '>' | '|' as c) ->
Stream.junk strm__; Plexing.Lexbuf.add c buf
| _ -> misc_punct buf strm__)
with Stream.Failure -> None
with
Some buf -> check_ident2 buf strm__
| _ -> buf
;;
let check_keyword ctx s =
if ctx.simplest_raw_strings && (s = "{|" || s = "|}") then false
else try check_keyword_stream (Stream.of_string s) with _ -> false
;;
let error_no_respect_rules p_con p_prm =
raise
(Plexing.Error
("the token " ^
(if p_con = "" then "\"" ^ p_prm ^ "\""
else if p_prm = "" then p_con
else p_con ^ " \"" ^ p_prm ^ "\"") ^
" does not respect Plexer rules"))
;;
let using_token ctx kwd_table (p_con, p_prm) =
match p_con with
"" ->
if not (hashtbl_mem kwd_table p_prm) then
if check_keyword ctx p_prm then Hashtbl.add kwd_table p_prm p_prm
else error_no_respect_rules p_con p_prm
| "LIDENT" ->
if p_prm = "" then ()
else
begin match p_prm.[0] with
'A'..'Z' -> error_no_respect_rules p_con p_prm
| _ -> ()
end
| "UIDENT" ->
if p_prm = "" then ()
else
begin match p_prm.[0] with
'a'..'z' -> error_no_respect_rules p_con p_prm
| _ -> ()
end
| "TILDEIDENT" | "TILDEIDENTCOLON" | "QUESTIONIDENT" |
"QUESTIONIDENTCOLON" | "INT" | "INT_l" | "INT_L" | "INT_n" | "FLOAT" |
"QUOTEDEXTENSION" | "CHAR" | "STRING" | "QUOTATION" | "GIDENT" |
"ANTIQUOT" | "ANTIQUOT_LOC" | "EOI" ->
()
| _ ->
raise
(Plexing.Error
("the constructor \"" ^ p_con ^ "\" is not recognized by Plexer"))
;;
let removing_token kwd_table (p_con, p_prm) =
match p_con with
"" -> Hashtbl.remove kwd_table p_prm
| _ -> ()
;;
let text =
function
"", t -> "'" ^ t ^ "'"
| "LIDENT", "" -> "lowercase identifier"
| "LIDENT", t -> "'" ^ t ^ "'"
| "UIDENT", "" -> "uppercase identifier"
| "UIDENT", t -> "'" ^ t ^ "'"
| "INT", "" -> "integer"
| "INT", s -> "'" ^ s ^ "'"
| "FLOAT", "" -> "float"
| "STRING", "" -> "string"
| "CHAR", "" -> "char"
| "QUOTATION", "" -> "quotation"
| "ANTIQUOT", k -> "antiquot \"" ^ k ^ "\""
| "EOI", "" -> "end of input"
| con, "" -> con
| con, prm -> con ^ " \"" ^ prm ^ "\""
;;
let eq_before_colon p e =
let rec loop i =
if i == String.length e then
failwith "Internal error in Plexer: incorrect ANTIQUOT"
else if i == String.length p then e.[i] == ':'
else if p.[i] == e.[i] then loop (i + 1)
else false
in
loop 0
;;
let after_colon e =
try
let i = String.index e ':' in
String.sub e (i + 1) (String.length e - i - 1)
with Not_found -> ""
;;
let after_colon_except_last e =
try
let i = String.index e ':' in
String.sub e (i + 1) (String.length e - i - 2)
with Not_found -> ""
;;
let tok_match =
function
"ANTIQUOT", p_prm ->
if p_prm <> "" && (p_prm.[0] = '~' || p_prm.[0] = '?') then
if p_prm.[String.length p_prm - 1] = ':' then
let p_prm = String.sub p_prm 0 (String.length p_prm - 1) in
function
"ANTIQUOT", prm ->
if prm <> "" && prm.[String.length prm - 1] = ':' then
if eq_before_colon p_prm prm then after_colon_except_last prm
else raise Stream.Failure
else raise Stream.Failure
| _ -> raise Stream.Failure
else
function
"ANTIQUOT", prm ->
if prm <> "" && prm.[String.length prm - 1] = ':' then
raise Stream.Failure
else if eq_before_colon p_prm prm then after_colon prm
else raise Stream.Failure
| _ -> raise Stream.Failure
else
(function
"ANTIQUOT", prm when eq_before_colon p_prm prm -> after_colon prm
| _ -> raise Stream.Failure)
| "LIDENT", p_prm ->
also treats the case when a is also a keyword
(fun (con, prm) ->
if con = "LIDENT" then
if p_prm = "" || prm = p_prm then prm else raise Stream.Failure
else if con = "" && prm = p_prm then prm
else raise Stream.Failure)
| "UIDENT", p_prm ->
also treats the case when a UIDENT is also a keyword
(fun (con, prm) ->
if con = "UIDENT" then
if p_prm = "" || prm = p_prm then prm else raise Stream.Failure
else if con = "" && prm = p_prm then prm
else raise Stream.Failure)
| tok -> Plexing.default_match tok
;;
let gmake () =
let kwd_table = Hashtbl.create 301 in
let ctx = make_ctx kwd_table in
let glexr =
ref
{Plexing.tok_func =
(fun _ -> raise (Match_failure ("plexer.ml", 1016, 25)));
tok_using = (fun _ -> raise (Match_failure ("plexer.ml", 1016, 45)));
tok_removing =
(fun _ -> raise (Match_failure ("plexer.ml", 1016, 68)));
tok_match = (fun _ -> raise (Match_failure ("plexer.ml", 1017, 18)));
tok_text = (fun _ -> raise (Match_failure ("plexer.ml", 1017, 37)));
tok_comm = None}
in
let glex =
{Plexing.tok_func = func ctx kwd_table glexr;
tok_using = using_token ctx kwd_table;
tok_removing = removing_token kwd_table; tok_match = tok_match;
tok_text = text; tok_comm = None}
in
glexr := glex; glex
;;
| null | https://raw.githubusercontent.com/camlp5/camlp5/9e8155f8ae5a584bbb4ad96d10d6fec63ed8204c/ocaml_src/lib/plexer.ml | ocaml | camlp5r
plexer.ml,v
#load "pa_lexer.cmo"
let hex_float_literal =
'0' ['x' 'X']
['0'-'9' 'A'-'F' 'a'-'f'] ['0'-'9' 'A'-'F' 'a'-'f' '_']*
('.' ['0'-'9' 'A'-'F' 'a'-'f' '_']* )?
(['p' 'P'] ['+' '-']? ['0'-'9'] ['0'-'9' '_']* )?
let literal_modifier = ['G'-'Z' 'g'-'z']
let hex_float_literal =
'0' ['x' 'X']
['0'-'9' 'A'-'F' 'a'-'f'] ['0'-'9' 'A'-'F' 'a'-'f' '_']*
('.' ['0'-'9' 'A'-'F' 'a'-'f' '_']* )?
(['p' 'P'] ['+' '-']? ['0'-'9'] ['0'-'9' '_']* )?
let literal_modifier = ['G'-'Z' 'g'-'z']
hex_digits*
* This predicate checks that the stream contains a valid raw-string starter.
* The definition of "valid raw string starter" depends on the value of
* the variable [simplest_raw_strings]: if it is [False], then a valid
* raw-string starter is "[:alpha:]+|"; if it is [True], a valid raw-string
* starter is "[:alpha:]*|". [simplest_raw_strings] is set to True in
* original syntax.
* This predicate gets called when the main lexer has already seen a "{".
| Copyright ( c ) INRIA 2007 - 2017
open Versdep;;
let simplest_raw_strings = ref false;;
let no_quotations = ref false;;
let error_on_unknown_keywords = ref false;;
let dollar_for_antiquotation = ref true;;
let specific_space_dot = ref false;;
let force_antiquot_loc = ref false;;
type context =
{ mutable after_space : bool;
simplest_raw_strings : bool;
dollar_for_antiquotation : bool;
specific_space_dot : bool;
find_kwd : string -> string;
line_cnt : int -> char -> unit;
set_line_nb : unit -> unit;
make_lined_loc : int * int -> string -> Ploc.t }
;;
let err ctx loc msg =
Ploc.raise (ctx.make_lined_loc loc "") (Plexing.Error msg)
;;
let keyword_or_error ctx loc s =
try "", ctx.find_kwd s with
Not_found ->
if !error_on_unknown_keywords then err ctx loc ("illegal token: " ^ s)
else "", s
;;
let rev_implode l =
let s = string_create (List.length l) in
let rec loop i =
function
c :: l -> string_unsafe_set s i c; loop (i - 1) l
| [] -> s
in
bytes_to_string (loop (string_length s - 1) l)
;;
let implode l = rev_implode (List.rev l);;
let stream_peek_nth n strm =
let rec loop n =
function
[] -> None
| [x] -> if n == 1 then Some x else None
| _ :: l -> loop (n - 1) l
in
loop n (Stream.npeek n strm)
;;
let utf8_lexing = ref false;;
let greek_tab =
["α"; "β"; "γ"; "δ"; "ε"; "ζ"; "η"; "θ"; "ι"; "κ"; "λ"; "μ"; "ν"; "ξ"; "ο";
"π"; "ρ"; "σ"; "τ"; "υ"; "φ"; "χ"; "ψ"; "ω"]
;;
let greek_letter buf strm =
if !utf8_lexing then
match Stream.peek strm with
Some c ->
if Char.code c >= 128 then
let x = implode (Stream.npeek 2 strm) in
if List.mem x greek_tab then
begin Stream.junk strm; Plexing.Lexbuf.add c buf end
else raise Stream.Failure
else raise Stream.Failure
| None -> raise Stream.Failure
else raise Stream.Failure
;;
let misc_letter buf strm =
if !utf8_lexing then
match Stream.peek strm with
Some c ->
if Char.code c >= 128 then
match implode (Stream.npeek 3 strm) with
"→" | "≤" | "≥" -> raise Stream.Failure
| _ -> Stream.junk strm; Plexing.Lexbuf.add c buf
else raise Stream.Failure
| None -> raise Stream.Failure
else
let (strm__ : _ Stream.t) = strm in
match Stream.peek strm__ with
Some ('\128'..'\225' as c) ->
Stream.junk strm__; Plexing.Lexbuf.add c buf
| Some ('\227'..'\255' as c) ->
Stream.junk strm__; Plexing.Lexbuf.add c buf
| _ -> raise Stream.Failure
;;
let misc_punct buf strm =
if !utf8_lexing then
let (strm__ : _ Stream.t) = strm in
match Stream.peek strm__ with
Some '\226' ->
Stream.junk strm__;
begin match Stream.peek strm__ with
Some c ->
Stream.junk strm__;
begin match Stream.peek strm__ with
Some c1 ->
Stream.junk strm__;
Plexing.Lexbuf.add c1
(Plexing.Lexbuf.add c (Plexing.Lexbuf.add '\226' buf))
| _ -> raise (Stream.Error "")
end
| _ -> raise (Stream.Error "")
end
| _ -> raise Stream.Failure
else let (_ : _ Stream.t) = strm in raise Stream.Failure
;;
let utf8_equiv ctx bp buf strm =
if !utf8_lexing then
let (strm__ : _ Stream.t) = strm in
match Stream.peek strm__ with
Some '\226' ->
Stream.junk strm__;
begin try
match Stream.peek strm__ with
Some '\134' ->
Stream.junk strm__;
begin match Stream.peek strm__ with
Some '\146' ->
Stream.junk strm__;
keyword_or_error ctx (bp, Stream.count strm__) "->"
| _ -> raise (Stream.Error "")
end
| Some '\137' ->
Stream.junk strm__;
begin try
match Stream.peek strm__ with
Some '\164' ->
Stream.junk strm__;
keyword_or_error ctx (bp, Stream.count strm__) "<="
| Some '\165' ->
Stream.junk strm__;
keyword_or_error ctx (bp, Stream.count strm__) ">="
| _ -> raise Stream.Failure
with Stream.Failure -> raise (Stream.Error "")
end
| _ -> raise Stream.Failure
with Stream.Failure -> raise (Stream.Error "")
end
| _ -> raise Stream.Failure
else let (_ : _ Stream.t) = strm in raise Stream.Failure
;;
let rec ident buf (strm__ : _ Stream.t) =
match
try
Some
(match Stream.peek strm__ with
Some ('A'..'Z' | 'a'..'z' | '0'..'9' | '_' | '\'' as c) ->
Stream.junk strm__; Plexing.Lexbuf.add c buf
| _ -> misc_letter buf strm__)
with Stream.Failure -> None
with
Some buf -> ident buf strm__
| _ -> buf
;;
let rec ident2_or other buf (strm__ : _ Stream.t) =
match
try
Some
(match Stream.peek strm__ with
Some
('!' | '?' | '~' | '=' | '@' | '^' | '&' | '+' | '-' | '*' |
'/' | '%' | '.' | ':' | '<' | '>' | '|' | '$' as c) ->
Stream.junk strm__; Plexing.Lexbuf.add c buf
| _ ->
try other buf strm__ with
Stream.Failure -> misc_punct buf strm__)
with Stream.Failure -> None
with
Some buf -> ident2_or other buf strm__
| _ -> buf
;;
let ident2 = ident2_or (fun buf strm -> raise Stream.Failure);;
let hash_follower_chars =
ident2_or
(fun buf (strm__ : _ Stream.t) ->
match Stream.peek strm__ with
Some '#' -> Stream.junk strm__; Plexing.Lexbuf.add '#' buf
| _ -> raise Stream.Failure)
;;
let rec ident3 buf (strm__ : _ Stream.t) =
match Stream.peek strm__ with
Some
('0'..'9' | 'A'..'Z' | 'a'..'z' | '_' | '!' | '%' | '&' | '*' | '+' |
'-' | '.' | '/' | ':' | '<' | '=' | '>' | '?' | '@' | '^' | '|' | '~' |
'\'' | '$' | '\128'..'\255' as c) ->
Stream.junk strm__; ident3 (Plexing.Lexbuf.add c buf) strm__
| _ -> buf
;;
let binary buf (strm__ : _ Stream.t) =
match Stream.peek strm__ with
Some ('0' | '1' as c) -> Stream.junk strm__; Plexing.Lexbuf.add c buf
| _ -> raise Stream.Failure
;;
let octal buf (strm__ : _ Stream.t) =
match Stream.peek strm__ with
Some ('0'..'7' as c) -> Stream.junk strm__; Plexing.Lexbuf.add c buf
| _ -> raise Stream.Failure
;;
let decimal buf (strm__ : _ Stream.t) =
match Stream.peek strm__ with
Some ('0'..'9' as c) -> Stream.junk strm__; Plexing.Lexbuf.add c buf
| _ -> raise Stream.Failure
;;
let hexa buf (strm__ : _ Stream.t) =
match Stream.peek strm__ with
Some ('0'..'9' | 'a'..'f' | 'A'..'F' as c) ->
Stream.junk strm__; Plexing.Lexbuf.add c buf
| _ -> raise Stream.Failure
;;
let end_integer buf (strm__ : _ Stream.t) =
match Stream.peek strm__ with
Some 'l' -> Stream.junk strm__; "INT_l", Plexing.Lexbuf.get buf
| Some 'L' -> Stream.junk strm__; "INT_L", Plexing.Lexbuf.get buf
| Some 'n' -> Stream.junk strm__; "INT_n", Plexing.Lexbuf.get buf
| _ -> "INT", Plexing.Lexbuf.get buf
;;
let rec digits_under kind buf (strm__ : _ Stream.t) =
match try Some (kind buf strm__) with Stream.Failure -> None with
Some buf -> digits_under kind buf strm__
| _ ->
match Stream.peek strm__ with
Some '_' ->
Stream.junk strm__;
digits_under kind (Plexing.Lexbuf.add '_' buf) strm__
| _ -> end_integer buf strm__
;;
let digits kind buf (strm__ : _ Stream.t) =
let buf =
try kind buf strm__ with
Stream.Failure -> raise (Stream.Error "ill-formed integer constant")
in
digits_under kind buf strm__
;;
let rec decimal_digits_under buf (strm__ : _ Stream.t) =
match Stream.peek strm__ with
Some ('0'..'9' | '_' as c) ->
Stream.junk strm__;
decimal_digits_under (Plexing.Lexbuf.add c buf) strm__
| _ -> buf
;;
let exponent_part buf (strm__ : _ Stream.t) =
match Stream.peek strm__ with
Some ('e' | 'E' as c) ->
Stream.junk strm__;
let buf = Plexing.Lexbuf.add c buf in
let buf =
match Stream.peek strm__ with
Some ('+' | '-' as c) ->
Stream.junk strm__; Plexing.Lexbuf.add c buf
| _ -> buf
in
begin match Stream.peek strm__ with
Some ('0'..'9' as c) ->
Stream.junk strm__;
decimal_digits_under (Plexing.Lexbuf.add c buf) strm__
| _ -> raise (Stream.Error "ill-formed floating-point constant")
end
| _ -> raise Stream.Failure
;;
let number buf (strm__ : _ Stream.t) =
let buf = decimal_digits_under buf strm__ in
match Stream.peek strm__ with
Some '.' ->
Stream.junk strm__;
let buf = decimal_digits_under (Plexing.Lexbuf.add '.' buf) strm__ in
begin match
(try Some (exponent_part buf strm__) with Stream.Failure -> None)
with
Some buf -> "FLOAT", Plexing.Lexbuf.get buf
| _ -> "FLOAT", Plexing.Lexbuf.get buf
end
| _ ->
match
try Some (exponent_part buf strm__) with Stream.Failure -> None
with
Some buf -> "FLOAT", Plexing.Lexbuf.get buf
| _ -> end_integer buf strm__
;;
let rec hex_digits_under_star buf (strm__ : _ Stream.t) =
match Stream.peek strm__ with
Some ('0'..'9' | 'a'..'f' | 'A'..'F' | '_' as c) ->
Stream.junk strm__;
hex_digits_under_star (Plexing.Lexbuf.add c buf) strm__
| _ -> buf
;;
let rec hex_under_integer buf (strm__ : _ Stream.t) =
match Stream.peek strm__ with
Some ('0'..'9' | 'a'..'f' | 'A'..'F' as c) ->
Stream.junk strm__;
begin try hex_digits_under_star (Plexing.Lexbuf.add c buf) strm__ with
Stream.Failure -> raise (Stream.Error "")
end
| _ -> raise Stream.Failure
;;
let rec decimal_under_integer buf (strm__ : _ Stream.t) =
let buf =
match Stream.peek strm__ with
Some ('0'..'9' as c) -> Stream.junk strm__; Plexing.Lexbuf.add c buf
| _ -> buf
in
decimal_digits_under buf strm__
;;
let hex_exponent_part buf (strm__ : _ Stream.t) =
match Stream.peek strm__ with
Some ('p' | 'P' as c) ->
Stream.junk strm__;
let buf = Plexing.Lexbuf.add c buf in
let buf =
match Stream.peek strm__ with
Some ('+' | '-' as c) ->
Stream.junk strm__; Plexing.Lexbuf.add c buf
| _ -> buf
in
decimal_under_integer buf strm__
| _ -> raise Stream.Failure
;;
let hex_number buf (strm__ : _ Stream.t) =
let buf = hex_under_integer buf strm__ in
match Stream.peek strm__ with
Some '.' ->
Stream.junk strm__;
let buf = hex_digits_under_star (Plexing.Lexbuf.add '.' buf) strm__ in
begin match
(try Some (hex_exponent_part buf strm__) with Stream.Failure -> None)
with
Some buf -> "FLOAT", Plexing.Lexbuf.get buf
| _ -> "FLOAT", Plexing.Lexbuf.get buf
end
| _ ->
match
try Some (hex_exponent_part buf strm__) with Stream.Failure -> None
with
Some buf -> "FLOAT", Plexing.Lexbuf.get buf
| _ ->
match
try Some (exponent_part buf strm__) with Stream.Failure -> None
with
Some buf -> "FLOAT", Plexing.Lexbuf.get buf
| _ -> end_integer buf strm__
;;
let char_after_bslash buf (strm__ : _ Stream.t) =
match Stream.peek strm__ with
Some '\'' -> Stream.junk strm__; buf
| Some c ->
Stream.junk strm__;
let buf = Plexing.Lexbuf.add c buf in
begin try
match Stream.peek strm__ with
Some '\'' -> Stream.junk strm__; buf
| Some c ->
Stream.junk strm__;
let buf = Plexing.Lexbuf.add c buf in
begin match Stream.peek strm__ with
Some '\'' -> Stream.junk strm__; buf
| _ -> buf
end
| _ -> raise Stream.Failure
with Stream.Failure -> raise (Stream.Error "")
end
| _ -> raise Stream.Failure
;;
let char ctx bp buf (strm__ : _ Stream.t) =
match Stream.peek strm__ with
Some '\\' ->
Stream.junk strm__;
begin match Stream.peek strm__ with
Some c ->
Stream.junk strm__;
char_after_bslash
(Plexing.Lexbuf.add c (Plexing.Lexbuf.add '\\' buf)) strm__
| _ -> err ctx (bp, Stream.count strm__) "char not terminated"
end
| _ ->
match Stream.npeek 2 strm__ with
[_; '\''] ->
begin match Stream.peek strm__ with
Some c ->
Stream.junk strm__;
begin match Stream.peek strm__ with
Some '\'' -> Stream.junk strm__; Plexing.Lexbuf.add c buf
| _ -> raise (Stream.Error "")
end
| _ -> raise Stream.Failure
end
| _ -> raise Stream.Failure
;;
let any ctx buf (strm__ : _ Stream.t) =
let bp = Stream.count strm__ in
match Stream.peek strm__ with
Some c -> Stream.junk strm__; ctx.line_cnt bp c; Plexing.Lexbuf.add c buf
| _ -> raise Stream.Failure
;;
let rec skiplws buf (strm__ : _ Stream.t) =
match Stream.peek strm__ with
Some ' ' -> Stream.junk strm__; skiplws buf strm__
| Some '\t' -> Stream.junk strm__; skiplws buf strm__
| _ -> buf
;;
let incrline ctx buf (strm__ : _ Stream.t) =
let bp = Stream.count strm__ in ctx.line_cnt (bp - 1) '\n'; buf
;;
let rec string ctx bp buf (strm__ : _ Stream.t) =
match Stream.peek strm__ with
Some '"' -> Stream.junk strm__; buf
| Some '\\' ->
Stream.junk strm__;
begin try
match Stream.npeek 1 strm__ with
['\n'] ->
begin match Stream.peek strm__ with
Some '\n' ->
Stream.junk strm__;
let buf = incrline ctx buf strm__ in
let buf = skiplws buf strm__ in string ctx bp buf strm__
| _ -> raise (Stream.Error "")
end
| _ ->
match Stream.npeek 1 strm__ with
['\n'] | [' '] ->
let buf =
try any ctx buf strm__ with
Stream.Failure -> raise (Stream.Error "")
in
string ctx bp buf strm__
| _ ->
let buf = any ctx (Plexing.Lexbuf.add '\\' buf) strm__ in
string ctx bp buf strm__
with Stream.Failure -> raise (Stream.Error "")
end
| _ ->
match try Some (any ctx buf strm__) with Stream.Failure -> None with
Some buf -> string ctx bp buf strm__
| _ -> err ctx (bp, Stream.count strm__) "string not terminated"
;;
let rec quotation ctx bp buf (strm__ : _ Stream.t) =
match Stream.peek strm__ with
Some '>' ->
Stream.junk strm__;
begin match Stream.peek strm__ with
Some '>' -> Stream.junk strm__; buf
| _ -> quotation ctx bp (Plexing.Lexbuf.add '>' buf) strm__
end
| Some '<' ->
Stream.junk strm__;
begin match Stream.peek strm__ with
Some '<' ->
Stream.junk strm__;
let buf =
quotation ctx bp
(Plexing.Lexbuf.add '<' (Plexing.Lexbuf.add '<' buf)) strm__
in
let buf = Plexing.Lexbuf.add '>' (Plexing.Lexbuf.add '>' buf) in
quotation ctx bp buf strm__
| Some ':' ->
Stream.junk strm__;
let buf =
ident (Plexing.Lexbuf.add ':' (Plexing.Lexbuf.add '<' buf)) strm__
in
begin match Stream.peek strm__ with
Some '<' ->
Stream.junk strm__;
let buf =
quotation ctx bp (Plexing.Lexbuf.add '<' buf) strm__
in
let buf = Plexing.Lexbuf.add '>' (Plexing.Lexbuf.add '>' buf) in
quotation ctx bp buf strm__
| _ -> quotation ctx bp buf strm__
end
| _ -> quotation ctx bp (Plexing.Lexbuf.add '<' buf) strm__
end
| Some '\\' ->
Stream.junk strm__;
begin match Stream.peek strm__ with
Some ('>' | '<' | '\\' as c) ->
Stream.junk strm__;
quotation ctx bp (Plexing.Lexbuf.add c buf) strm__
| _ -> quotation ctx bp (Plexing.Lexbuf.add '\\' buf) strm__
end
| _ ->
match try Some (any ctx buf strm__) with Stream.Failure -> None with
Some buf -> quotation ctx bp buf strm__
| _ -> err ctx (bp, Stream.count strm__) "quotation not terminated"
;;
let less_expected = "character '<' expected";;
let less ctx bp buf strm =
if !no_quotations then
let (strm__ : _ Stream.t) = strm in
let buf = Plexing.Lexbuf.add '<' buf in
let buf = ident2 buf strm__ in
keyword_or_error ctx (bp, Stream.count strm__) (Plexing.Lexbuf.get buf)
else
let (strm__ : _ Stream.t) = strm in
match Stream.peek strm__ with
Some '<' ->
Stream.junk strm__;
let buf =
try quotation ctx bp buf strm__ with
Stream.Failure -> raise (Stream.Error "")
in
"QUOTATION", ":" ^ Plexing.Lexbuf.get buf
| Some ':' ->
Stream.junk strm__;
let buf = ident buf strm__ in
begin try
match Stream.peek strm__ with
Some '<' ->
Stream.junk strm__;
let buf = Plexing.Lexbuf.add ':' buf in
let buf =
try quotation ctx bp buf strm__ with
Stream.Failure -> raise (Stream.Error "")
in
"QUOTATION", Plexing.Lexbuf.get buf
| _ ->
match Stream.peek strm__ with
Some ':' ->
Stream.junk strm__;
begin match Stream.peek strm__ with
Some '<' ->
Stream.junk strm__;
let buf = Plexing.Lexbuf.add '@' buf in
let buf =
try quotation ctx bp buf strm__ with
Stream.Failure -> raise (Stream.Error "")
in
"QUOTATION", Plexing.Lexbuf.get buf
| _ -> raise (Stream.Error less_expected)
end
| _ -> raise Stream.Failure
with Stream.Failure -> raise (Stream.Error "")
end
| _ ->
let buf = Plexing.Lexbuf.add '<' buf in
let buf = ident2 buf strm__ in
keyword_or_error ctx (bp, Stream.count strm__)
(Plexing.Lexbuf.get buf)
;;
let rec antiquot_rest ctx bp buf (strm__ : _ Stream.t) =
match Stream.peek strm__ with
Some '$' -> Stream.junk strm__; buf
| Some '\\' ->
Stream.junk strm__;
let buf =
try any ctx buf strm__ with Stream.Failure -> raise (Stream.Error "")
in
antiquot_rest ctx bp buf strm__
| _ ->
match try Some (any ctx buf strm__) with Stream.Failure -> None with
Some buf -> antiquot_rest ctx bp buf strm__
| _ -> err ctx (bp, Stream.count strm__) "antiquotation not terminated"
;;
let rec antiquot ctx bp buf (strm__ : _ Stream.t) =
match Stream.peek strm__ with
Some '$' -> Stream.junk strm__; ":" ^ Plexing.Lexbuf.get buf
| Some ('a'..'z' | 'A'..'Z' | '0'..'9' | '!' | '_' as c) ->
Stream.junk strm__; antiquot ctx bp (Plexing.Lexbuf.add c buf) strm__
| Some ':' ->
Stream.junk strm__;
let buf = antiquot_rest ctx bp (Plexing.Lexbuf.add ':' buf) strm__ in
Plexing.Lexbuf.get buf
| Some '\\' ->
Stream.junk strm__;
let buf =
try any ctx buf strm__ with Stream.Failure -> raise (Stream.Error "")
in
let buf = antiquot_rest ctx bp buf strm__ in
":" ^ Plexing.Lexbuf.get buf
| _ ->
match try Some (any ctx buf strm__) with Stream.Failure -> None with
Some buf ->
let buf = antiquot_rest ctx bp buf strm__ in
":" ^ Plexing.Lexbuf.get buf
| _ -> err ctx (bp, Stream.count strm__) "antiquotation not terminated"
;;
let antiloc bp ep s = Printf.sprintf "%d,%d:%s" bp ep s;;
let skip_to_next_colon s i =
let rec loop j =
if j = String.length s then i, 0
else
match s.[j] with
':' -> j, j - i - 1
| 'a'..'z' | 'A'..'Z' | '0'..'9' | '!' | '_' -> loop (j + 1)
| _ -> i, 0
in
loop (i + 1)
;;
let parse_antiquot s =
try
let i = String.index s ':' in
let kind = String.sub s 0 i in
let name = String.sub s (i + 1) (String.length s - (i + 1)) in
Some (kind, name)
with Not_found | Failure _ -> None
;;
let parse_antiloc s =
try
let i = String.index s ':' in
let (j, len) = skip_to_next_colon s i in
let kind = String.sub s (i + 1) len in
let loc =
let k = String.index s ',' in
let bp = int_of_string (String.sub s 0 k) in
let ep = int_of_string (String.sub s (k + 1) (i - k - 1)) in
Ploc.make_unlined (bp, ep)
in
Some (loc, kind, String.sub s (j + 1) (String.length s - j - 1))
with Not_found | Failure _ -> None
;;
let rec antiquot_loc ctx bp buf (strm__ : _ Stream.t) =
match Stream.peek strm__ with
Some '$' ->
Stream.junk strm__;
antiloc bp (Stream.count strm__) (":" ^ Plexing.Lexbuf.get buf)
| Some ('a'..'z' | 'A'..'Z' | '0'..'9' | '!' | '_' as c) ->
Stream.junk strm__;
antiquot_loc ctx bp (Plexing.Lexbuf.add c buf) strm__
| Some ':' ->
Stream.junk strm__;
let buf = antiquot_rest ctx bp (Plexing.Lexbuf.add ':' buf) strm__ in
antiloc bp (Stream.count strm__) (Plexing.Lexbuf.get buf)
| Some '\\' ->
Stream.junk strm__;
let buf =
try any ctx buf strm__ with Stream.Failure -> raise (Stream.Error "")
in
let buf = antiquot_rest ctx bp buf strm__ in
antiloc bp (Stream.count strm__) (":" ^ Plexing.Lexbuf.get buf)
| _ ->
match try Some (any ctx buf strm__) with Stream.Failure -> None with
Some buf ->
let buf = antiquot_rest ctx bp buf strm__ in
antiloc bp (Stream.count strm__) (":" ^ Plexing.Lexbuf.get buf)
| _ -> err ctx (bp, Stream.count strm__) "antiquotation not terminated"
;;
let dollar ctx bp buf strm =
if not !no_quotations && ctx.dollar_for_antiquotation then
"ANTIQUOT", antiquot ctx bp buf strm
else if !force_antiquot_loc then
"ANTIQUOT_LOC", antiquot_loc ctx bp buf strm
else
let (strm__ : _ Stream.t) = strm in
let buf = Plexing.Lexbuf.add '$' buf in
let buf = ident2 buf strm__ in "", Plexing.Lexbuf.get buf
;;
- specific case for QUESTIONIDENT and QUESTIONIDENTCOLON
input expr patt
----- ---- ----
? $ abc : d$ ? abc : d ? abc
? $ abc : d$ : ? abc : d : ? abc :
? ? : d ?
? : ? : d : ? :
input expr patt
----- ---- ----
?$abc:d$ ?abc:d ?abc
?$abc:d$: ?abc:d: ?abc:
?$d$ ?:d ?
?$d$: ?:d: ?:
*)
ANTIQUOT_LOC - specific case for QUESTIONIDENT and QUESTIONIDENTCOLON
input expr patt
----- ---- ----
? $ abc : d$ ? 8,13 : abc : d ? abc
? $ abc : d$ : ? 8,13 : abc : d : ? abc :
? ? 8,9::d ?
? : ? 8,9::d : ? :
input expr patt
----- ---- ----
?$abc:d$ ?8,13:abc:d ?abc
?$abc:d$: ?8,13:abc:d: ?abc:
?$d$ ?8,9::d ?
?$d$: ?8,9::d: ?:
*)
let question ctx bp buf strm =
if ctx.dollar_for_antiquotation then
let (strm__ : _ Stream.t) = strm in
match Stream.peek strm__ with
Some '$' ->
Stream.junk strm__;
let s =
try antiquot ctx bp Plexing.Lexbuf.empty strm__ with
Stream.Failure -> raise (Stream.Error "")
in
begin match Stream.peek strm__ with
Some ':' -> Stream.junk strm__; "ANTIQUOT", "?" ^ s ^ ":"
| _ -> "ANTIQUOT", "?" ^ s
end
| _ ->
let (strm__ : _ Stream.t) = strm in
let buf = hash_follower_chars buf strm__ in
keyword_or_error ctx (bp, Stream.count strm__)
(Plexing.Lexbuf.get buf)
else if !force_antiquot_loc then
let (strm__ : _ Stream.t) = strm in
match Stream.peek strm__ with
Some '$' ->
Stream.junk strm__;
let s =
try antiquot_loc ctx bp Plexing.Lexbuf.empty strm__ with
Stream.Failure -> raise (Stream.Error "")
in
begin match Stream.peek strm__ with
Some ':' -> Stream.junk strm__; "ANTIQUOT_LOC", "?" ^ s ^ ":"
| _ -> "ANTIQUOT_LOC", "?" ^ s
end
| _ ->
let (strm__ : _ Stream.t) = strm in
let buf = hash_follower_chars buf strm__ in
keyword_or_error ctx (bp, Stream.count strm__)
(Plexing.Lexbuf.get buf)
else
let (strm__ : _ Stream.t) = strm in
let buf = hash_follower_chars buf strm__ in
keyword_or_error ctx (bp, Stream.count strm__) (Plexing.Lexbuf.get buf)
;;
let tilde ctx bp buf strm =
if ctx.dollar_for_antiquotation then
let (strm__ : _ Stream.t) = strm in
match Stream.peek strm__ with
Some '$' ->
Stream.junk strm__;
let s =
try antiquot ctx bp Plexing.Lexbuf.empty strm__ with
Stream.Failure -> raise (Stream.Error "")
in
begin match Stream.peek strm__ with
Some ':' -> Stream.junk strm__; "ANTIQUOT", "~" ^ s ^ ":"
| _ -> "ANTIQUOT", "~" ^ s
end
| _ ->
let (strm__ : _ Stream.t) = strm in
let buf = hash_follower_chars buf strm__ in
keyword_or_error ctx (bp, Stream.count strm__)
(Plexing.Lexbuf.get buf)
else if !force_antiquot_loc then
let (strm__ : _ Stream.t) = strm in
match Stream.peek strm__ with
Some '$' ->
Stream.junk strm__;
let s =
try antiquot_loc ctx bp Plexing.Lexbuf.empty strm__ with
Stream.Failure -> raise (Stream.Error "")
in
begin match Stream.peek strm__ with
Some ':' -> Stream.junk strm__; "ANTIQUOT_LOC", "~" ^ s ^ ":"
| _ -> "ANTIQUOT_LOC", "~" ^ s
end
| _ ->
let (strm__ : _ Stream.t) = strm in
let buf = hash_follower_chars buf strm__ in
keyword_or_error ctx (bp, Stream.count strm__)
(Plexing.Lexbuf.get buf)
else
let (strm__ : _ Stream.t) = strm in
let buf = hash_follower_chars buf strm__ in
keyword_or_error ctx (bp, Stream.count strm__) (Plexing.Lexbuf.get buf)
;;
let tildeident buf (strm__ : _ Stream.t) =
match Stream.peek strm__ with
Some ':' -> Stream.junk strm__; "TILDEIDENTCOLON", Plexing.Lexbuf.get buf
| _ -> "TILDEIDENT", Plexing.Lexbuf.get buf
;;
let questionident buf (strm__ : _ Stream.t) =
match Stream.peek strm__ with
Some ':' ->
Stream.junk strm__; "QUESTIONIDENTCOLON", Plexing.Lexbuf.get buf
| _ -> "QUESTIONIDENT", Plexing.Lexbuf.get buf
;;
let rec linedir n s =
match stream_peek_nth n s with
Some (' ' | '\t') -> linedir (n + 1) s
| Some ('0'..'9') -> linedir_digits (n + 1) s
| _ -> false
and linedir_digits n s =
match stream_peek_nth n s with
Some ('0'..'9') -> linedir_digits (n + 1) s
| _ -> linedir_quote n s
and linedir_quote n s =
match stream_peek_nth n s with
Some (' ' | '\t') -> linedir_quote (n + 1) s
| Some '"' -> true
| _ -> false
;;
let rec any_to_nl buf (strm__ : _ Stream.t) =
match Stream.peek strm__ with
Some ('\r' | '\n' as c) -> Stream.junk strm__; Plexing.Lexbuf.add c buf
| Some c -> Stream.junk strm__; any_to_nl (Plexing.Lexbuf.add c buf) strm__
| _ -> buf
;;
let rec rawstring1 delimtok (ofs, delim) ctx buf (strm__ : _ Stream.t) =
let bp = Stream.count strm__ in
match Stream.peek strm__ with
Some c ->
Stream.junk strm__;
let strm = strm__ in
ctx.line_cnt bp c;
let buf = Plexing.Lexbuf.add c buf in
if String.get delim ofs <> c then
if String.get delim 0 = c then
rawstring1 delimtok (1, delim) ctx buf strm
else rawstring1 delimtok (0, delim) ctx buf strm
else if ofs + 1 < String.length delim then
rawstring1 delimtok (ofs + 1, delim) ctx buf strm
else
let s = Plexing.Lexbuf.get buf in
let slen = String.length s in
delimtok, String.sub s 0 (slen - String.length delim)
| _ -> raise Stream.Failure
;;
let rec rawstring0 ctx bp buf (strm__ : _ Stream.t) =
let bp = Stream.count strm__ in
match Stream.peek strm__ with
Some '|' ->
Stream.junk strm__;
let strm = strm__ in
rawstring1 (Plexing.Lexbuf.get buf)
(0, "|" ^ Plexing.Lexbuf.get buf ^ "}") ctx Plexing.Lexbuf.empty strm
| Some ('a'..'z' | '_' as c) ->
Stream.junk strm__;
let strm = strm__ in rawstring0 ctx bp (Plexing.Lexbuf.add c buf) strm
| _ -> raise Stream.Failure
;;
let add_string buf s =
let slen = String.length s in
let rec addrec buf i =
if i = slen then buf
else addrec (Plexing.Lexbuf.add (String.get s i) buf) (i + 1)
in
addrec buf 0
;;
let raw_string_starter_p ctx strm =
let rec predrec n =
match stream_peek_nth n strm with
None -> false
| Some ('a'..'z' | '_') -> predrec (n + 1)
| Some '|' when ctx.simplest_raw_strings || n > 1 -> true
| Some _ -> false
in
predrec 1
;;
let comment_rawstring ctx bp (buf : Plexing.Lexbuf.t) strm =
if not (raw_string_starter_p ctx strm) then buf
else
let (delim, s) = rawstring0 ctx bp Plexing.Lexbuf.empty strm in
let rs = Printf.sprintf "{%s|%s|%s}" delim s delim in add_string buf rs
;;
let comment ctx bp =
let rec comment buf (strm__ : _ Stream.t) =
match Stream.peek strm__ with
Some '*' ->
Stream.junk strm__;
begin match Stream.peek strm__ with
Some ')' ->
Stream.junk strm__;
Plexing.Lexbuf.add ')' (Plexing.Lexbuf.add '*' buf)
| _ -> comment (Plexing.Lexbuf.add '*' buf) strm__
end
| Some '{' ->
Stream.junk strm__;
let buf =
comment_rawstring ctx bp (Plexing.Lexbuf.add '{' buf) strm__
in
comment buf strm__
| Some '(' ->
Stream.junk strm__;
begin match Stream.peek strm__ with
Some '*' ->
Stream.junk strm__;
let buf =
comment (Plexing.Lexbuf.add '*' (Plexing.Lexbuf.add '(' buf))
strm__
in
comment buf strm__
| _ -> comment (Plexing.Lexbuf.add '(' buf) strm__
end
| Some '"' ->
Stream.junk strm__;
let buf = string ctx bp (Plexing.Lexbuf.add '"' buf) strm__ in
let buf = Plexing.Lexbuf.add '"' buf in comment buf strm__
| Some '\'' ->
Stream.junk strm__;
begin try
match Stream.peek strm__ with
Some '*' ->
Stream.junk strm__;
begin match Stream.peek strm__ with
Some ')' ->
Stream.junk strm__;
Plexing.Lexbuf.add ')'
(Plexing.Lexbuf.add '*' (Plexing.Lexbuf.add '\'' buf))
| _ ->
comment
(Plexing.Lexbuf.add '*' (Plexing.Lexbuf.add '\'' buf))
strm__
end
| _ ->
let buf = any ctx (Plexing.Lexbuf.add '\'' buf) strm__ in
comment buf strm__
with Stream.Failure -> raise (Stream.Error "")
end
| _ ->
match try Some (any ctx buf strm__) with Stream.Failure -> None with
Some buf -> comment buf strm__
| _ -> err ctx (bp, Stream.count strm__) "comment not terminated"
in
comment
;;
let keyword_or_error_or_rawstring ctx bp (loc, s) buf strm =
if not (raw_string_starter_p ctx strm) then
match stream_peek_nth 1 strm with
Some '|' when not ctx.simplest_raw_strings ->
Stream.junk strm; keyword_or_error ctx loc "{|"
| _ -> keyword_or_error ctx loc "{"
else
let (delim, s) = rawstring0 ctx bp Plexing.Lexbuf.empty strm in
"STRING", String.escaped s
;;
let zerobuf f buf strm = f Plexing.Lexbuf.empty strm;;
let rec ws buf (strm__ : _ Stream.t) =
let buf =
match Stream.peek strm__ with
Some ' ' -> Stream.junk strm__; buf
| Some '\t' -> Stream.junk strm__; buf
| Some '\n' -> Stream.junk strm__; buf
| _ -> raise Stream.Failure
in
try ws buf strm__ with Stream.Failure -> buf
;;
let rec extattrident buf (strm__ : _ Stream.t) =
let buf = ident buf strm__ in
match Stream.peek strm__ with
Some '.' ->
Stream.junk strm__;
begin try extattrident (Plexing.Lexbuf.add '.' buf) strm__ with
Stream.Failure -> raise (Stream.Error "")
end
| _ -> buf
;;
let quoted_extension1 ctx (bp, _) extid buf strm =
let (delim, s) = rawstring0 ctx bp Plexing.Lexbuf.empty strm in
"QUOTEDEXTENSION", extid ^ ":" ^ String.escaped s
;;
let quoted_extension0 ctx (bp, _) extid buf (strm__ : _ Stream.t) =
match try Some (ws buf strm__) with Stream.Failure -> None with
Some buf ->
begin try
zerobuf (quoted_extension1 ctx (bp, Stream.count strm__) extid) buf
strm__
with Stream.Failure -> raise (Stream.Error "")
end
| _ ->
zerobuf (quoted_extension1 ctx (bp, Stream.count strm__) extid) buf
strm__
;;
let quoted_extension ctx (bp, _) buf (strm__ : _ Stream.t) =
let buf = extattrident buf strm__ in
try
zerobuf
(quoted_extension0 ctx (bp, Stream.count strm__)
(Plexing.Lexbuf.get buf))
buf strm__
with Stream.Failure -> raise (Stream.Error "")
;;
let dotsymbolchar buf (strm__ : _ Stream.t) =
match Stream.peek strm__ with
Some
('!' | '$' | '%' | '&' | '*' | '+' | '-' | '/' | ':' | '=' | '>' | '?' |
'@' | '^' | '|' as c) ->
Stream.junk strm__; Plexing.Lexbuf.add c buf
| _ -> raise Stream.Failure
;;
let rec dotsymbolchar_star buf (strm__ : _ Stream.t) =
match try Some (dotsymbolchar buf strm__) with Stream.Failure -> None with
Some buf ->
begin try dotsymbolchar_star buf strm__ with
Stream.Failure -> raise (Stream.Error "")
end
| _ -> buf
;;
let kwdopchar buf (strm__ : _ Stream.t) =
match Stream.peek strm__ with
Some
('$' | '&' | '*' | '+' | '-' | '/' | '<' | '=' | '>' | '@' | '^' |
'|' as c) ->
Stream.junk strm__; Plexing.Lexbuf.add c buf
| _ -> raise Stream.Failure
;;
let symbolchar buf (strm__ : _ Stream.t) =
match Stream.peek strm__ with
Some
('!' | '$' | '%' | '&' | '*' | '+' | '-' | '.' | '/' | ':' | '<' | '=' |
'>' | '?' | '@' | '^' | '|' | '~' as c) ->
Stream.junk strm__; Plexing.Lexbuf.add c buf
| _ -> raise Stream.Failure
;;
let rec symbolchar_star buf (strm__ : _ Stream.t) =
match try Some (symbolchar buf strm__) with Stream.Failure -> None with
Some buf ->
begin try symbolchar_star buf strm__ with
Stream.Failure -> raise (Stream.Error "")
end
| _ -> buf
;;
let word_operators ctx id buf (strm__ : _ Stream.t) =
match try Some (kwdopchar buf strm__) with Stream.Failure -> None with
Some buf ->
let buf =
try dotsymbolchar_star buf strm__ with
Stream.Failure -> raise (Stream.Error "")
in
"", id ^ Plexing.Lexbuf.get buf
| _ -> try "", ctx.find_kwd id with Not_found -> "LIDENT", id
;;
let keyword ctx buf strm =
let id = Plexing.Lexbuf.get buf in
if id = "let" || id = "and" then
word_operators ctx id Plexing.Lexbuf.empty strm
else try "", ctx.find_kwd id with Not_found -> "LIDENT", id
;;
let dot ctx (bp, pos) buf strm =
match Stream.peek strm with
None ->
let id =
if ctx.specific_space_dot && ctx.after_space then " ." else "."
in
keyword_or_error ctx (bp, pos) id
| _ ->
let (strm__ : _ Stream.t) = strm in
let buf = Plexing.Lexbuf.add '.' buf in
let buf = dotsymbolchar_star buf strm__ in
keyword_or_error ctx (bp, Stream.count strm__) (Plexing.Lexbuf.get buf)
;;
let next_token_after_spaces ctx bp buf (strm__ : _ Stream.t) =
match Stream.peek strm__ with
Some ('A'..'Z' as c) ->
Stream.junk strm__;
let buf = ident (Plexing.Lexbuf.add c buf) strm__ in
let id = Plexing.Lexbuf.get buf in
(try "", ctx.find_kwd id with Not_found -> "UIDENT", id)
| _ ->
match
try Some (greek_letter buf strm__) with Stream.Failure -> None
with
Some buf ->
let buf = ident buf strm__ in "GIDENT", Plexing.Lexbuf.get buf
| _ ->
match
try
Some
(match Stream.peek strm__ with
Some ('a'..'z' | '_' as c) ->
Stream.junk strm__; Plexing.Lexbuf.add c buf
| _ -> misc_letter buf strm__)
with Stream.Failure -> None
with
Some buf ->
let buf = ident buf strm__ in
begin try keyword ctx buf strm__ with
Stream.Failure -> raise (Stream.Error "")
end
| _ ->
match Stream.peek strm__ with
Some ('1'..'9' as c) ->
Stream.junk strm__; number (Plexing.Lexbuf.add c buf) strm__
| Some '0' ->
Stream.junk strm__;
begin match Stream.peek strm__ with
Some ('o' | 'O' as c) ->
Stream.junk strm__;
digits octal
(Plexing.Lexbuf.add c (Plexing.Lexbuf.add '0' buf))
strm__
| Some ('x' | 'X' as c) ->
Stream.junk strm__;
hex_number
(Plexing.Lexbuf.add c (Plexing.Lexbuf.add '0' buf))
strm__
| Some ('b' | 'B' as c) ->
Stream.junk strm__;
digits binary
(Plexing.Lexbuf.add c (Plexing.Lexbuf.add '0' buf))
strm__
| _ -> number (Plexing.Lexbuf.add '0' buf) strm__
end
| Some '\'' ->
Stream.junk strm__;
begin match Stream.npeek 3 strm__ with
['\\'; 'a'..'z'; 'a'..'z'] ->
keyword_or_error ctx (bp, Stream.count strm__) "'"
| _ ->
match
try Some (char ctx bp buf strm__) with
Stream.Failure -> None
with
Some buf -> "CHAR", Plexing.Lexbuf.get buf
| _ ->
keyword_or_error ctx (bp, Stream.count strm__) "'"
end
| Some '"' ->
Stream.junk strm__;
let buf = string ctx bp buf strm__ in
"STRING", Plexing.Lexbuf.get buf
| Some '$' -> Stream.junk strm__; dollar ctx bp buf strm__
| Some
('=' | '@' | '^' | '&' | '+' | '-' | '*' | '/' |
'%' as c) ->
Stream.junk strm__;
let buf = ident2 (Plexing.Lexbuf.add c buf) strm__ in
keyword_or_error ctx (bp, Stream.count strm__)
(Plexing.Lexbuf.get buf)
| Some '!' ->
Stream.junk strm__;
let buf =
hash_follower_chars (Plexing.Lexbuf.add '!' buf) strm__
in
keyword_or_error ctx (bp, Stream.count strm__)
(Plexing.Lexbuf.get buf)
| Some '~' ->
Stream.junk strm__;
begin try
match Stream.peek strm__ with
Some ('a'..'z' as c) ->
Stream.junk strm__;
let buf = ident (Plexing.Lexbuf.add c buf) strm__ in
tildeident buf strm__
| Some '_' ->
Stream.junk strm__;
let buf = ident (Plexing.Lexbuf.add '_' buf) strm__ in
tildeident buf strm__
| _ -> tilde ctx bp (Plexing.Lexbuf.add '~' buf) strm__
with Stream.Failure -> raise (Stream.Error "")
end
| Some '?' ->
Stream.junk strm__;
begin match Stream.peek strm__ with
Some ('a'..'z' as c) ->
Stream.junk strm__;
let buf = ident (Plexing.Lexbuf.add c buf) strm__ in
questionident buf strm__
| _ -> question ctx bp (Plexing.Lexbuf.add '?' buf) strm__
end
| Some '<' -> Stream.junk strm__; less ctx bp buf strm__
| Some ':' ->
Stream.junk strm__;
begin match Stream.peek strm__ with
Some ']' ->
Stream.junk strm__;
keyword_or_error ctx (bp, Stream.count strm__)
(Plexing.Lexbuf.get
(Plexing.Lexbuf.add ']'
(Plexing.Lexbuf.add ':' buf)))
| Some ':' ->
Stream.junk strm__;
keyword_or_error ctx (bp, Stream.count strm__)
(Plexing.Lexbuf.get
(Plexing.Lexbuf.add ':'
(Plexing.Lexbuf.add ':' buf)))
| Some '=' ->
Stream.junk strm__;
keyword_or_error ctx (bp, Stream.count strm__)
(Plexing.Lexbuf.get
(Plexing.Lexbuf.add '='
(Plexing.Lexbuf.add ':' buf)))
| Some '>' ->
Stream.junk strm__;
keyword_or_error ctx (bp, Stream.count strm__)
(Plexing.Lexbuf.get
(Plexing.Lexbuf.add '>'
(Plexing.Lexbuf.add ':' buf)))
| _ ->
keyword_or_error ctx (bp, Stream.count strm__)
(Plexing.Lexbuf.get (Plexing.Lexbuf.add ':' buf))
end
| Some '>' ->
Stream.junk strm__;
begin match Stream.peek strm__ with
Some ']' ->
Stream.junk strm__;
keyword_or_error ctx (bp, Stream.count strm__)
(Plexing.Lexbuf.get
(Plexing.Lexbuf.add ']'
(Plexing.Lexbuf.add '>' buf)))
| Some '}' ->
Stream.junk strm__;
keyword_or_error ctx (bp, Stream.count strm__)
(Plexing.Lexbuf.get
(Plexing.Lexbuf.add '}'
(Plexing.Lexbuf.add '>' buf)))
| _ ->
let buf = ident2 (Plexing.Lexbuf.add '>' buf) strm__ in
keyword_or_error ctx (bp, Stream.count strm__)
(Plexing.Lexbuf.get buf)
end
| Some '|' ->
Stream.junk strm__;
begin match Stream.peek strm__ with
Some ']' ->
Stream.junk strm__;
keyword_or_error ctx (bp, Stream.count strm__)
(Plexing.Lexbuf.get
(Plexing.Lexbuf.add ']'
(Plexing.Lexbuf.add '|' buf)))
| Some '}' ->
Stream.junk strm__;
keyword_or_error ctx (bp, Stream.count strm__)
(Plexing.Lexbuf.get
(Plexing.Lexbuf.add '}'
(Plexing.Lexbuf.add '|' buf)))
| _ ->
let buf = ident2 (Plexing.Lexbuf.add '|' buf) strm__ in
keyword_or_error ctx (bp, Stream.count strm__)
(Plexing.Lexbuf.get buf)
end
| Some '[' ->
Stream.junk strm__;
begin match Stream.npeek 2 strm__ with
['<'; '<'] | ['<'; ':'] ->
keyword_or_error ctx (bp, Stream.count strm__)
(Plexing.Lexbuf.get (Plexing.Lexbuf.add '[' buf))
| _ ->
match Stream.peek strm__ with
Some '@' ->
Stream.junk strm__;
begin match Stream.peek strm__ with
Some '@' ->
Stream.junk strm__;
begin match Stream.peek strm__ with
Some '@' ->
Stream.junk strm__;
keyword_or_error ctx
(bp, Stream.count strm__)
(Plexing.Lexbuf.get
(Plexing.Lexbuf.add '@'
(Plexing.Lexbuf.add '@'
(Plexing.Lexbuf.add '@'
(Plexing.Lexbuf.add '['
buf)))))
| _ ->
keyword_or_error ctx
(bp, Stream.count strm__)
(Plexing.Lexbuf.get
(Plexing.Lexbuf.add '@'
(Plexing.Lexbuf.add '@'
(Plexing.Lexbuf.add '[' buf))))
end
| _ ->
keyword_or_error ctx (bp, Stream.count strm__)
(Plexing.Lexbuf.get
(Plexing.Lexbuf.add '@'
(Plexing.Lexbuf.add '[' buf)))
end
| Some '%' ->
Stream.junk strm__;
begin match Stream.peek strm__ with
Some '%' ->
Stream.junk strm__;
keyword_or_error ctx (bp, Stream.count strm__)
(Plexing.Lexbuf.get
(Plexing.Lexbuf.add '%'
(Plexing.Lexbuf.add '%'
(Plexing.Lexbuf.add '[' buf))))
| _ ->
keyword_or_error ctx (bp, Stream.count strm__)
(Plexing.Lexbuf.get
(Plexing.Lexbuf.add '%'
(Plexing.Lexbuf.add '[' buf)))
end
| Some '|' ->
Stream.junk strm__;
keyword_or_error ctx (bp, Stream.count strm__)
(Plexing.Lexbuf.get
(Plexing.Lexbuf.add '|'
(Plexing.Lexbuf.add '[' buf)))
| Some '<' ->
Stream.junk strm__;
keyword_or_error ctx (bp, Stream.count strm__)
(Plexing.Lexbuf.get
(Plexing.Lexbuf.add '<'
(Plexing.Lexbuf.add '[' buf)))
| Some ':' ->
Stream.junk strm__;
keyword_or_error ctx (bp, Stream.count strm__)
(Plexing.Lexbuf.get
(Plexing.Lexbuf.add ':'
(Plexing.Lexbuf.add '[' buf)))
| _ ->
keyword_or_error ctx (bp, Stream.count strm__)
(Plexing.Lexbuf.get (Plexing.Lexbuf.add '[' buf))
end
| Some '{' ->
Stream.junk strm__;
begin try
match Stream.npeek 2 strm__ with
['<'; '<'] | ['<'; ':'] ->
keyword_or_error ctx (bp, Stream.count strm__)
(Plexing.Lexbuf.get (Plexing.Lexbuf.add '{' buf))
| _ ->
match Stream.peek strm__ with
Some '<' ->
Stream.junk strm__;
keyword_or_error ctx (bp, Stream.count strm__)
(Plexing.Lexbuf.get
(Plexing.Lexbuf.add '<'
(Plexing.Lexbuf.add '{' buf)))
| Some '%' ->
Stream.junk strm__;
begin try
zerobuf
(quoted_extension ctx
(bp, Stream.count strm__))
buf strm__
with Stream.Failure -> raise (Stream.Error "")
end
| Some ':' ->
Stream.junk strm__;
keyword_or_error ctx (bp, Stream.count strm__)
(Plexing.Lexbuf.get
(Plexing.Lexbuf.add ':'
(Plexing.Lexbuf.add '{' buf)))
| _ ->
keyword_or_error_or_rawstring ctx bp
((bp, Stream.count strm__),
Plexing.Lexbuf.get buf)
(Plexing.Lexbuf.add '{' buf) strm__
with Stream.Failure -> raise (Stream.Error "")
end
| Some '.' ->
Stream.junk strm__;
begin match Stream.peek strm__ with
Some '.' ->
Stream.junk strm__;
keyword_or_error ctx (bp, Stream.count strm__) ".."
| _ ->
match
try
Some
(dotsymbolchar (Plexing.Lexbuf.add '.' buf)
strm__)
with Stream.Failure -> None
with
Some buf ->
let buf =
try symbolchar_star buf strm__ with
Stream.Failure -> raise (Stream.Error "")
in
keyword_or_error ctx (bp, Stream.count strm__)
(Plexing.Lexbuf.get buf)
| _ ->
let id =
if ctx.specific_space_dot && ctx.after_space then
" ."
else "."
in
keyword_or_error ctx (bp, Stream.count strm__) id
end
| Some ';' ->
Stream.junk strm__;
begin match Stream.peek strm__ with
Some ';' ->
Stream.junk strm__;
keyword_or_error ctx (bp, Stream.count strm__) ";;"
| _ -> keyword_or_error ctx (bp, Stream.count strm__) ";"
end
| _ ->
try utf8_equiv ctx bp buf strm__ with
Stream.Failure ->
match
try Some (misc_punct buf strm__) with
Stream.Failure -> None
with
Some buf ->
let buf = ident2 buf strm__ in
keyword_or_error ctx (bp, Stream.count strm__)
(Plexing.Lexbuf.get buf)
| _ ->
match Stream.peek strm__ with
Some '\\' ->
Stream.junk strm__;
let buf = ident3 buf strm__ in
"LIDENT", Plexing.Lexbuf.get buf
| Some '#' ->
Stream.junk strm__;
let buf =
hash_follower_chars
(Plexing.Lexbuf.add '#' buf) strm__
in
keyword_or_error ctx (bp, Stream.count strm__)
(Plexing.Lexbuf.get buf)
| _ ->
let buf = any ctx buf strm__ in
keyword_or_error ctx (bp, Stream.count strm__)
(Plexing.Lexbuf.get buf)
;;
let get_comment buf strm = Plexing.Lexbuf.get buf;;
let rec next_token ctx buf (strm__ : _ Stream.t) =
let bp = Stream.count strm__ in
match Stream.peek strm__ with
Some ('\n' | '\r' as c) ->
Stream.junk strm__;
let s = strm__ in
let ep = Stream.count strm__ in
if c = '\n' then incr !(Plexing.line_nb);
!(Plexing.bol_pos) := ep;
ctx.set_line_nb ();
ctx.after_space <- true;
next_token ctx (Plexing.Lexbuf.add c buf) s
| Some (' ' | '\t' | '\026' | '\012' as c) ->
Stream.junk strm__;
let s = strm__ in
ctx.after_space <- true; next_token ctx (Plexing.Lexbuf.add c buf) s
| Some '#' when bp = !(!(Plexing.bol_pos)) ->
Stream.junk strm__;
let s = strm__ in
let comm = get_comment buf () in
if linedir 1 s then
let buf = any_to_nl (Plexing.Lexbuf.add '#' buf) s in
incr !(Plexing.line_nb);
!(Plexing.bol_pos) := Stream.count s;
ctx.set_line_nb ();
ctx.after_space <- true;
next_token ctx buf s
else
let loc = ctx.make_lined_loc (bp, bp + 1) comm in
keyword_or_error ctx (bp, bp + 1) "#", loc
| Some '(' ->
Stream.junk strm__;
begin match Stream.peek strm__ with
Some '*' ->
Stream.junk strm__;
let buf =
comment ctx bp
(Plexing.Lexbuf.add '*' (Plexing.Lexbuf.add '(' buf)) strm__
in
let s = strm__ in
ctx.set_line_nb (); ctx.after_space <- true; next_token ctx buf s
| _ ->
let ep = Stream.count strm__ in
let loc = ctx.make_lined_loc (bp, ep) (Plexing.Lexbuf.get buf) in
keyword_or_error ctx (bp, ep) "(", loc
end
| _ ->
let comm = get_comment buf strm__ in
try
match
try
Some (next_token_after_spaces ctx bp Plexing.Lexbuf.empty strm__)
with Stream.Failure -> None
with
Some tok ->
let ep = Stream.count strm__ in
let loc = ctx.make_lined_loc (bp, max (bp + 1) ep) comm in
tok, loc
| _ ->
let _ = Stream.empty strm__ in
let loc = ctx.make_lined_loc (bp, bp + 1) comm in ("EOI", ""), loc
with Stream.Failure -> raise (Stream.Error "")
;;
let next_token_fun ctx glexr (cstrm, s_line_nb, s_bol_pos) =
try
begin match !(Plexing.restore_lexing_info) with
Some (line_nb, bol_pos) ->
s_line_nb := line_nb;
s_bol_pos := bol_pos;
Plexing.restore_lexing_info := None
| None -> ()
end;
Plexing.line_nb := s_line_nb;
Plexing.bol_pos := s_bol_pos;
let comm_bp = Stream.count cstrm in
ctx.set_line_nb ();
ctx.after_space <- false;
let (r, loc) = next_token ctx Plexing.Lexbuf.empty cstrm in
begin match !glexr.Plexing.tok_comm with
Some list ->
if Ploc.first_pos loc > comm_bp then
let comm_loc = Ploc.make_unlined (comm_bp, Ploc.last_pos loc) in
!glexr.Plexing.tok_comm <- Some (comm_loc :: list)
| None -> ()
end;
r, loc
with Stream.Error str ->
err ctx (Stream.count cstrm, Stream.count cstrm + 1) str
;;
let make_ctx kwd_table =
let line_nb = ref 0 in
let bol_pos = ref 0 in
{after_space = false; dollar_for_antiquotation = !dollar_for_antiquotation;
simplest_raw_strings = !simplest_raw_strings;
specific_space_dot = !specific_space_dot;
find_kwd = Hashtbl.find kwd_table;
line_cnt =
(fun bp1 c ->
match c with
'\n' | '\r' ->
if c = '\n' then incr !(Plexing.line_nb);
!(Plexing.bol_pos) := bp1 + 1
| c -> ());
set_line_nb =
(fun () ->
line_nb := !(!(Plexing.line_nb)); bol_pos := !(!(Plexing.bol_pos)));
make_lined_loc =
fun loc comm ->
Ploc.make_loc !(Plexing.input_file) !line_nb !bol_pos loc comm}
;;
let func ctx kwd_table glexr =
Plexing.lexer_func_of_parser (next_token_fun ctx glexr)
;;
let rec check_keyword_stream (strm__ : _ Stream.t) =
let _ = check Plexing.Lexbuf.empty strm__ in
let _ =
try Stream.empty strm__ with Stream.Failure -> raise (Stream.Error "")
in
true
and check buf (strm__ : _ Stream.t) =
match
try
Some
(match Stream.peek strm__ with
Some ('A'..'Z' | 'a'..'z' as c) ->
Stream.junk strm__; Plexing.Lexbuf.add c buf
| _ -> misc_letter buf strm__)
with Stream.Failure -> None
with
Some buf -> check_ident buf strm__
| _ ->
match Stream.peek strm__ with
Some
('!' | '?' | '~' | '=' | '@' | '^' | '&' | '+' | '-' | '*' | '/' |
'%' | '.' as c) ->
Stream.junk strm__; check_ident2 (Plexing.Lexbuf.add c buf) strm__
| Some '$' ->
Stream.junk strm__; check_ident2 (Plexing.Lexbuf.add '$' buf) strm__
| Some '<' ->
Stream.junk strm__;
begin match Stream.npeek 1 strm__ with
[':'] | ['<'] -> Plexing.Lexbuf.add '<' buf
| _ -> check_ident2 (Plexing.Lexbuf.add '<' buf) strm__
end
| Some ':' ->
Stream.junk strm__;
begin match Stream.peek strm__ with
Some ']' ->
Stream.junk strm__;
Plexing.Lexbuf.add ']' (Plexing.Lexbuf.add ':' buf)
| Some ':' ->
Stream.junk strm__;
Plexing.Lexbuf.add ':' (Plexing.Lexbuf.add ':' buf)
| Some '=' ->
Stream.junk strm__;
Plexing.Lexbuf.add '=' (Plexing.Lexbuf.add ':' buf)
| Some '>' ->
Stream.junk strm__;
Plexing.Lexbuf.add '>' (Plexing.Lexbuf.add ':' buf)
| _ -> Plexing.Lexbuf.add ':' buf
end
| Some '>' ->
Stream.junk strm__;
begin match Stream.peek strm__ with
Some ']' ->
Stream.junk strm__;
Plexing.Lexbuf.add ']' (Plexing.Lexbuf.add '>' buf)
| Some '}' ->
Stream.junk strm__;
Plexing.Lexbuf.add '}' (Plexing.Lexbuf.add '>' buf)
| _ -> check_ident2 (Plexing.Lexbuf.add '>' buf) strm__
end
| Some '|' ->
Stream.junk strm__;
begin match Stream.peek strm__ with
Some ']' ->
Stream.junk strm__;
Plexing.Lexbuf.add ']' (Plexing.Lexbuf.add '|' buf)
| Some '}' ->
Stream.junk strm__;
Plexing.Lexbuf.add '}' (Plexing.Lexbuf.add '|' buf)
| _ -> check_ident2 (Plexing.Lexbuf.add '|' buf) strm__
end
| Some '[' ->
Stream.junk strm__;
begin match Stream.npeek 2 strm__ with
['<'; '<'] | ['<'; ':'] -> Plexing.Lexbuf.add '[' buf
| _ ->
match Stream.peek strm__ with
Some '@' ->
Stream.junk strm__;
begin match Stream.peek strm__ with
Some '@' ->
Stream.junk strm__;
begin match Stream.peek strm__ with
Some '@' ->
Stream.junk strm__;
Plexing.Lexbuf.add '@'
(Plexing.Lexbuf.add '@'
(Plexing.Lexbuf.add '@'
(Plexing.Lexbuf.add '[' buf)))
| _ ->
Plexing.Lexbuf.add '@'
(Plexing.Lexbuf.add '@'
(Plexing.Lexbuf.add '[' buf))
end
| _ -> Plexing.Lexbuf.add '@' (Plexing.Lexbuf.add '[' buf)
end
| Some '%' ->
Stream.junk strm__;
begin match Stream.peek strm__ with
Some '%' ->
Stream.junk strm__;
Plexing.Lexbuf.add '%'
(Plexing.Lexbuf.add '%' (Plexing.Lexbuf.add '[' buf))
| _ -> Plexing.Lexbuf.add '%' (Plexing.Lexbuf.add '[' buf)
end
| Some '|' ->
Stream.junk strm__;
Plexing.Lexbuf.add '|' (Plexing.Lexbuf.add '[' buf)
| Some '<' ->
Stream.junk strm__;
Plexing.Lexbuf.add '<' (Plexing.Lexbuf.add '[' buf)
| Some ':' ->
Stream.junk strm__;
Plexing.Lexbuf.add ':' (Plexing.Lexbuf.add '[' buf)
| _ -> Plexing.Lexbuf.add '[' buf
end
| Some '{' ->
Stream.junk strm__;
begin match Stream.npeek 2 strm__ with
['<'; '<'] | ['<'; ':'] -> Plexing.Lexbuf.add '{' buf
| _ ->
match Stream.peek strm__ with
Some '|' ->
Stream.junk strm__;
Plexing.Lexbuf.add '|' (Plexing.Lexbuf.add '{' buf)
| Some '<' ->
Stream.junk strm__;
Plexing.Lexbuf.add '<' (Plexing.Lexbuf.add '{' buf)
| Some ':' ->
Stream.junk strm__;
Plexing.Lexbuf.add ':' (Plexing.Lexbuf.add '{' buf)
| _ -> Plexing.Lexbuf.add '{' buf
end
| Some ';' ->
Stream.junk strm__;
begin match Stream.peek strm__ with
Some ';' ->
Stream.junk strm__;
Plexing.Lexbuf.add ';' (Plexing.Lexbuf.add ';' buf)
| _ -> Plexing.Lexbuf.add ';' buf
end
| _ ->
match
try Some (misc_punct buf strm__) with Stream.Failure -> None
with
Some buf -> check_ident2 buf strm__
| _ ->
match Stream.peek strm__ with
Some c -> Stream.junk strm__; Plexing.Lexbuf.add c buf
| _ -> raise Stream.Failure
and check_ident buf (strm__ : _ Stream.t) =
match
try
Some
(match Stream.peek strm__ with
Some ('A'..'Z' | 'a'..'z' | '0'..'9' | '_' | '\'' as c) ->
Stream.junk strm__; Plexing.Lexbuf.add c buf
| _ -> misc_letter buf strm__)
with Stream.Failure -> None
with
Some buf -> check_ident buf strm__
| _ -> buf
and check_ident2 buf (strm__ : _ Stream.t) =
match
try
Some
(match Stream.peek strm__ with
Some
('!' | '?' | '~' | '=' | '@' | '^' | '&' | '+' | '-' | '*' |
'/' | '%' | '.' | ':' | '<' | '>' | '|' as c) ->
Stream.junk strm__; Plexing.Lexbuf.add c buf
| _ -> misc_punct buf strm__)
with Stream.Failure -> None
with
Some buf -> check_ident2 buf strm__
| _ -> buf
;;
let check_keyword ctx s =
if ctx.simplest_raw_strings && (s = "{|" || s = "|}") then false
else try check_keyword_stream (Stream.of_string s) with _ -> false
;;
let error_no_respect_rules p_con p_prm =
raise
(Plexing.Error
("the token " ^
(if p_con = "" then "\"" ^ p_prm ^ "\""
else if p_prm = "" then p_con
else p_con ^ " \"" ^ p_prm ^ "\"") ^
" does not respect Plexer rules"))
;;
let using_token ctx kwd_table (p_con, p_prm) =
match p_con with
"" ->
if not (hashtbl_mem kwd_table p_prm) then
if check_keyword ctx p_prm then Hashtbl.add kwd_table p_prm p_prm
else error_no_respect_rules p_con p_prm
| "LIDENT" ->
if p_prm = "" then ()
else
begin match p_prm.[0] with
'A'..'Z' -> error_no_respect_rules p_con p_prm
| _ -> ()
end
| "UIDENT" ->
if p_prm = "" then ()
else
begin match p_prm.[0] with
'a'..'z' -> error_no_respect_rules p_con p_prm
| _ -> ()
end
| "TILDEIDENT" | "TILDEIDENTCOLON" | "QUESTIONIDENT" |
"QUESTIONIDENTCOLON" | "INT" | "INT_l" | "INT_L" | "INT_n" | "FLOAT" |
"QUOTEDEXTENSION" | "CHAR" | "STRING" | "QUOTATION" | "GIDENT" |
"ANTIQUOT" | "ANTIQUOT_LOC" | "EOI" ->
()
| _ ->
raise
(Plexing.Error
("the constructor \"" ^ p_con ^ "\" is not recognized by Plexer"))
;;
let removing_token kwd_table (p_con, p_prm) =
match p_con with
"" -> Hashtbl.remove kwd_table p_prm
| _ -> ()
;;
let text =
function
"", t -> "'" ^ t ^ "'"
| "LIDENT", "" -> "lowercase identifier"
| "LIDENT", t -> "'" ^ t ^ "'"
| "UIDENT", "" -> "uppercase identifier"
| "UIDENT", t -> "'" ^ t ^ "'"
| "INT", "" -> "integer"
| "INT", s -> "'" ^ s ^ "'"
| "FLOAT", "" -> "float"
| "STRING", "" -> "string"
| "CHAR", "" -> "char"
| "QUOTATION", "" -> "quotation"
| "ANTIQUOT", k -> "antiquot \"" ^ k ^ "\""
| "EOI", "" -> "end of input"
| con, "" -> con
| con, prm -> con ^ " \"" ^ prm ^ "\""
;;
let eq_before_colon p e =
let rec loop i =
if i == String.length e then
failwith "Internal error in Plexer: incorrect ANTIQUOT"
else if i == String.length p then e.[i] == ':'
else if p.[i] == e.[i] then loop (i + 1)
else false
in
loop 0
;;
let after_colon e =
try
let i = String.index e ':' in
String.sub e (i + 1) (String.length e - i - 1)
with Not_found -> ""
;;
let after_colon_except_last e =
try
let i = String.index e ':' in
String.sub e (i + 1) (String.length e - i - 2)
with Not_found -> ""
;;
let tok_match =
function
"ANTIQUOT", p_prm ->
if p_prm <> "" && (p_prm.[0] = '~' || p_prm.[0] = '?') then
if p_prm.[String.length p_prm - 1] = ':' then
let p_prm = String.sub p_prm 0 (String.length p_prm - 1) in
function
"ANTIQUOT", prm ->
if prm <> "" && prm.[String.length prm - 1] = ':' then
if eq_before_colon p_prm prm then after_colon_except_last prm
else raise Stream.Failure
else raise Stream.Failure
| _ -> raise Stream.Failure
else
function
"ANTIQUOT", prm ->
if prm <> "" && prm.[String.length prm - 1] = ':' then
raise Stream.Failure
else if eq_before_colon p_prm prm then after_colon prm
else raise Stream.Failure
| _ -> raise Stream.Failure
else
(function
"ANTIQUOT", prm when eq_before_colon p_prm prm -> after_colon prm
| _ -> raise Stream.Failure)
| "LIDENT", p_prm ->
also treats the case when a is also a keyword
(fun (con, prm) ->
if con = "LIDENT" then
if p_prm = "" || prm = p_prm then prm else raise Stream.Failure
else if con = "" && prm = p_prm then prm
else raise Stream.Failure)
| "UIDENT", p_prm ->
also treats the case when a UIDENT is also a keyword
(fun (con, prm) ->
if con = "UIDENT" then
if p_prm = "" || prm = p_prm then prm else raise Stream.Failure
else if con = "" && prm = p_prm then prm
else raise Stream.Failure)
| tok -> Plexing.default_match tok
;;
let gmake () =
let kwd_table = Hashtbl.create 301 in
let ctx = make_ctx kwd_table in
let glexr =
ref
{Plexing.tok_func =
(fun _ -> raise (Match_failure ("plexer.ml", 1016, 25)));
tok_using = (fun _ -> raise (Match_failure ("plexer.ml", 1016, 45)));
tok_removing =
(fun _ -> raise (Match_failure ("plexer.ml", 1016, 68)));
tok_match = (fun _ -> raise (Match_failure ("plexer.ml", 1017, 18)));
tok_text = (fun _ -> raise (Match_failure ("plexer.ml", 1017, 37)));
tok_comm = None}
in
let glex =
{Plexing.tok_func = func ctx kwd_table glexr;
tok_using = using_token ctx kwd_table;
tok_removing = removing_token kwd_table; tok_match = tok_match;
tok_text = text; tok_comm = None}
in
glexr := glex; glex
;;
|
1728d8ccb7a31470a27bcc2a701bcccc4782d2101d6e10ae06418b08be984dbb | replikativ/replikativ | impl.cljc | (ns replikativ.crdt.ormap.impl
(:require [replikativ.protocols :refer [POpBasedCRDT -downstream
PExternalValues -missing-commits
PPullOp -pull]]
[replikativ.crdt.ormap.core :refer [downstream]]
[konserve.core :as k]
#?(:clj [superv.async :refer [go-try go-loop-try <?]])
#?(:clj [clojure.core.async :as async
:refer [>! timeout chan put! pub sub unsub close!]]
:cljs [cljs.core.async :as async
:refer [>! timeout chan put! pub sub unsub close!]])
[clojure.set :as set])
#?(:cljs (:require-macros [superv.async :refer [go-try go-loop-try <?]])))
(defn all-commits [ormap]
(for [[_ uid->cid] (concat (:adds ormap) (:removals ormap))
[_ cid] uid->cid]
cid))
similar to CDVCS
(defn missing-commits [S store ormap op]
(let [missing (all-commits op)]
(go-loop-try S [not-in-store #{}
[f & r] (seq missing)]
(if f
(recur (if (not (<? S (k/exists? store f)))
(conj not-in-store f) not-in-store) r)
not-in-store))))
(extend-type replikativ.crdt.ORMap
PExternalValues
(-missing-commits [this S store out fetched-ch op]
(missing-commits S store this op))
POpBasedCRDT
(-handshake [this S] (into {} this))
(-downstream [this op] (downstream this op)))
(comment
(require '[konserve.memory :refer [new-mem-store]]
'[full.async :refer :all]
'[clojure.core.async :refer [chan]]
'[replikativ.crdt.simple-ormap.core :refer [new-simple-ormap or-assoc or-dissoc]])
(def ormap (new-simple-ormap))
(def store (<?? (new-mem-store)))
(def foo
(-downstream
(-downstream (:state ormap)
(get-in (-> ormap (or-assoc 12 [['+ 42]] "john")) [:downstream :op]))
(get-in (-> ormap (or-assoc 12 [['+ 42]] "john")
(or-dissoc 12 [['- 42]] "john")) [:downstream :op])))
(<??(-missing-commits #_foo (:state ormap) store (chan) (chan)
(get-in (-> ormap (or-assoc 12 [['+ 42]] "john")) [:downstream :op])))
)
| null | https://raw.githubusercontent.com/replikativ/replikativ/1533a7e43e46bfb70e8c8eb34dc5708e611a478d/src/replikativ/crdt/ormap/impl.cljc | clojure | (ns replikativ.crdt.ormap.impl
(:require [replikativ.protocols :refer [POpBasedCRDT -downstream
PExternalValues -missing-commits
PPullOp -pull]]
[replikativ.crdt.ormap.core :refer [downstream]]
[konserve.core :as k]
#?(:clj [superv.async :refer [go-try go-loop-try <?]])
#?(:clj [clojure.core.async :as async
:refer [>! timeout chan put! pub sub unsub close!]]
:cljs [cljs.core.async :as async
:refer [>! timeout chan put! pub sub unsub close!]])
[clojure.set :as set])
#?(:cljs (:require-macros [superv.async :refer [go-try go-loop-try <?]])))
(defn all-commits [ormap]
(for [[_ uid->cid] (concat (:adds ormap) (:removals ormap))
[_ cid] uid->cid]
cid))
similar to CDVCS
(defn missing-commits [S store ormap op]
(let [missing (all-commits op)]
(go-loop-try S [not-in-store #{}
[f & r] (seq missing)]
(if f
(recur (if (not (<? S (k/exists? store f)))
(conj not-in-store f) not-in-store) r)
not-in-store))))
(extend-type replikativ.crdt.ORMap
PExternalValues
(-missing-commits [this S store out fetched-ch op]
(missing-commits S store this op))
POpBasedCRDT
(-handshake [this S] (into {} this))
(-downstream [this op] (downstream this op)))
(comment
(require '[konserve.memory :refer [new-mem-store]]
'[full.async :refer :all]
'[clojure.core.async :refer [chan]]
'[replikativ.crdt.simple-ormap.core :refer [new-simple-ormap or-assoc or-dissoc]])
(def ormap (new-simple-ormap))
(def store (<?? (new-mem-store)))
(def foo
(-downstream
(-downstream (:state ormap)
(get-in (-> ormap (or-assoc 12 [['+ 42]] "john")) [:downstream :op]))
(get-in (-> ormap (or-assoc 12 [['+ 42]] "john")
(or-dissoc 12 [['- 42]] "john")) [:downstream :op])))
(<??(-missing-commits #_foo (:state ormap) store (chan) (chan)
(get-in (-> ormap (or-assoc 12 [['+ 42]] "john")) [:downstream :op])))
)
| |
3f2a887abc4c1549dfd7663d2926b7f1f3c528dc1d30c0ef92d21de928eaa902 | SKA-ScienceDataProcessor/RC | Multicast.hs | -- | Multicast utilities
# OPTIONS_GHC -fno - warn - orphans #
# LANGUAGE RankNTypes , CPP #
module DNA.SimpleLocalnet.Internal.Multicast (initMulticast) where
import Data.Function (on)
import Data.Map (Map)
import qualified Data.Map as Map (empty)
import Data.Binary (Binary, decode, encode)
import Data.IORef (IORef, newIORef, readIORef, modifyIORef)
import qualified Data.ByteString as BSS (ByteString, concat)
import qualified Data.ByteString.Lazy as BSL
( ByteString
, empty
, append
, fromChunks
, toChunks
, length
, splitAt
)
import Data.Accessor (Accessor, (^:), (^.), (^=))
import qualified Data.Accessor.Container as DAC (mapDefault)
import Control.Applicative ((<$>))
import Network.Socket (HostName, PortNumber, Socket, SockAddr)
import qualified Network.Socket.ByteString as NBS (recvFrom, sendManyTo)
import Network.Transport.Internal (decodeInt32, encodeInt32)
import Network.Multicast (multicastSender, multicastReceiver)
--------------------------------------------------------------------------------
-- Top-level API --
--------------------------------------------------------------------------------
-- | Given a hostname and a port number, initialize the multicast system.
--
-- Note: it is important that you never send messages larger than the maximum
-- message size; if you do, all subsequent communication will probably fail.
--
-- Returns a reader and a writer.
--
NOTE : By rights the two functions should be " locally " polymorphic in ' a ' ,
-- but this requires impredicative types.
initMulticast :: forall a. Binary a
=> HostName -- ^ Multicast IP
-> PortNumber -- ^ Port number
-> Int -- ^ Maximum message size
-> IO (IO (a, SockAddr), a -> IO ())
initMulticast host port bufferSize = do
(sendSock, sendAddr) <- multicastSender host port
readSock <- multicastReceiver host port
st <- newIORef Map.empty
return (recvBinary readSock st bufferSize, writer sendSock sendAddr)
where
writer :: forall a. Binary a => Socket -> SockAddr -> a -> IO ()
writer sock addr val = do
let bytes = encode val
len = encodeInt32 (BSL.length bytes)
NBS.sendManyTo sock (len : BSL.toChunks bytes) addr
--------------------------------------------------------------------------------
UDP multicast read , dealing with multiple senders --
--------------------------------------------------------------------------------
type UDPState = Map SockAddr BSL.ByteString
#if MIN_VERSION_network(2,4,0)
network-2.4.0 provides the instance for us
#else
instance Ord SockAddr where
compare = compare `on` show
#endif
bufferFor :: SockAddr -> Accessor UDPState BSL.ByteString
bufferFor = DAC.mapDefault BSL.empty
bufferAppend :: SockAddr -> BSS.ByteString -> UDPState -> UDPState
bufferAppend addr bytes =
bufferFor addr ^: flip BSL.append (BSL.fromChunks [bytes])
recvBinary :: Binary a => Socket -> IORef UDPState -> Int -> IO (a, SockAddr)
recvBinary sock st bufferSize = do
(bytes, addr) <- recvWithLength sock st bufferSize
return (decode bytes, addr)
recvWithLength :: Socket
-> IORef UDPState
-> Int
-> IO (BSL.ByteString, SockAddr)
recvWithLength sock st bufferSize = do
(len, addr) <- recvExact sock 4 st bufferSize
let n = decodeInt32 . BSS.concat . BSL.toChunks $ len
bytes <- recvExactFrom addr sock n st bufferSize
return (bytes, addr)
-- Receive all bytes currently in the buffer
recvAll :: Socket -> IORef UDPState -> Int -> IO SockAddr
recvAll sock st bufferSize = do
(bytes, addr) <- NBS.recvFrom sock bufferSize
modifyIORef st $ bufferAppend addr bytes
return addr
recvExact :: Socket
-> Int
-> IORef UDPState
-> Int
-> IO (BSL.ByteString, SockAddr)
recvExact sock n st bufferSize = do
addr <- recvAll sock st bufferSize
bytes <- recvExactFrom addr sock n st bufferSize
return (bytes, addr)
recvExactFrom :: SockAddr
-> Socket
-> Int
-> IORef UDPState
-> Int
-> IO BSL.ByteString
recvExactFrom addr sock n st bufferSize = go
where
go :: IO BSL.ByteString
go = do
accAddr <- (^. bufferFor addr) <$> readIORef st
if BSL.length accAddr >= fromIntegral n
then do
let (bytes, accAddr') = BSL.splitAt (fromIntegral n) accAddr
modifyIORef st $ bufferFor addr ^= accAddr'
return bytes
else do
_ <- recvAll sock st bufferSize
go
| null | https://raw.githubusercontent.com/SKA-ScienceDataProcessor/RC/1b5e25baf9204a9f7ef40ed8ee94a86cc6c674af/MS1/ddp-erlang-style/DNA/SimpleLocalnet/Internal/Multicast.hs | haskell | | Multicast utilities
------------------------------------------------------------------------------
Top-level API --
------------------------------------------------------------------------------
| Given a hostname and a port number, initialize the multicast system.
Note: it is important that you never send messages larger than the maximum
message size; if you do, all subsequent communication will probably fail.
Returns a reader and a writer.
but this requires impredicative types.
^ Multicast IP
^ Port number
^ Maximum message size
------------------------------------------------------------------------------
------------------------------------------------------------------------------
Receive all bytes currently in the buffer | # OPTIONS_GHC -fno - warn - orphans #
# LANGUAGE RankNTypes , CPP #
module DNA.SimpleLocalnet.Internal.Multicast (initMulticast) where
import Data.Function (on)
import Data.Map (Map)
import qualified Data.Map as Map (empty)
import Data.Binary (Binary, decode, encode)
import Data.IORef (IORef, newIORef, readIORef, modifyIORef)
import qualified Data.ByteString as BSS (ByteString, concat)
import qualified Data.ByteString.Lazy as BSL
( ByteString
, empty
, append
, fromChunks
, toChunks
, length
, splitAt
)
import Data.Accessor (Accessor, (^:), (^.), (^=))
import qualified Data.Accessor.Container as DAC (mapDefault)
import Control.Applicative ((<$>))
import Network.Socket (HostName, PortNumber, Socket, SockAddr)
import qualified Network.Socket.ByteString as NBS (recvFrom, sendManyTo)
import Network.Transport.Internal (decodeInt32, encodeInt32)
import Network.Multicast (multicastSender, multicastReceiver)
NOTE : By rights the two functions should be " locally " polymorphic in ' a ' ,
initMulticast :: forall a. Binary a
-> IO (IO (a, SockAddr), a -> IO ())
initMulticast host port bufferSize = do
(sendSock, sendAddr) <- multicastSender host port
readSock <- multicastReceiver host port
st <- newIORef Map.empty
return (recvBinary readSock st bufferSize, writer sendSock sendAddr)
where
writer :: forall a. Binary a => Socket -> SockAddr -> a -> IO ()
writer sock addr val = do
let bytes = encode val
len = encodeInt32 (BSL.length bytes)
NBS.sendManyTo sock (len : BSL.toChunks bytes) addr
type UDPState = Map SockAddr BSL.ByteString
#if MIN_VERSION_network(2,4,0)
network-2.4.0 provides the instance for us
#else
instance Ord SockAddr where
compare = compare `on` show
#endif
bufferFor :: SockAddr -> Accessor UDPState BSL.ByteString
bufferFor = DAC.mapDefault BSL.empty
bufferAppend :: SockAddr -> BSS.ByteString -> UDPState -> UDPState
bufferAppend addr bytes =
bufferFor addr ^: flip BSL.append (BSL.fromChunks [bytes])
recvBinary :: Binary a => Socket -> IORef UDPState -> Int -> IO (a, SockAddr)
recvBinary sock st bufferSize = do
(bytes, addr) <- recvWithLength sock st bufferSize
return (decode bytes, addr)
recvWithLength :: Socket
-> IORef UDPState
-> Int
-> IO (BSL.ByteString, SockAddr)
recvWithLength sock st bufferSize = do
(len, addr) <- recvExact sock 4 st bufferSize
let n = decodeInt32 . BSS.concat . BSL.toChunks $ len
bytes <- recvExactFrom addr sock n st bufferSize
return (bytes, addr)
recvAll :: Socket -> IORef UDPState -> Int -> IO SockAddr
recvAll sock st bufferSize = do
(bytes, addr) <- NBS.recvFrom sock bufferSize
modifyIORef st $ bufferAppend addr bytes
return addr
recvExact :: Socket
-> Int
-> IORef UDPState
-> Int
-> IO (BSL.ByteString, SockAddr)
recvExact sock n st bufferSize = do
addr <- recvAll sock st bufferSize
bytes <- recvExactFrom addr sock n st bufferSize
return (bytes, addr)
recvExactFrom :: SockAddr
-> Socket
-> Int
-> IORef UDPState
-> Int
-> IO BSL.ByteString
recvExactFrom addr sock n st bufferSize = go
where
go :: IO BSL.ByteString
go = do
accAddr <- (^. bufferFor addr) <$> readIORef st
if BSL.length accAddr >= fromIntegral n
then do
let (bytes, accAddr') = BSL.splitAt (fromIntegral n) accAddr
modifyIORef st $ bufferFor addr ^= accAddr'
return bytes
else do
_ <- recvAll sock st bufferSize
go
|
d560f1d4f1f24c6728cde1cd902d661abcf2ea85692d28d6b360470d7d399979 | racket/plai | morse.rkt | #lang plai/gc2/mutator
(allocator-setup "../good-collectors/good-collector.rkt" 24)
(define a '(1 2 3 4 5))
| null | https://raw.githubusercontent.com/racket/plai/164f3b763116fcfa7bd827be511650e71fa04319/plai-lib/tests/gc2/other-mutators/morse.rkt | racket | #lang plai/gc2/mutator
(allocator-setup "../good-collectors/good-collector.rkt" 24)
(define a '(1 2 3 4 5))
| |
1a8f78f94dd63d96100911a2e2119d839cbc596d0da3d8d048be7eb23e085718 | anmonteiro/ocaml-mongodb | config.ml | type t =
{ db : string
; collection : string
; host : string
; port : int
; max_connections : int
}
let create
?(host = "127.0.0.1")
?(port = 27017)
?(max_connections = 16)
~db
~collection
()
=
{ db; collection; host; port; max_connections }
| null | https://raw.githubusercontent.com/anmonteiro/ocaml-mongodb/535ae1b003b9c8a3844b92a78d2123881f2d404b/src/config.ml | ocaml | type t =
{ db : string
; collection : string
; host : string
; port : int
; max_connections : int
}
let create
?(host = "127.0.0.1")
?(port = 27017)
?(max_connections = 16)
~db
~collection
()
=
{ db; collection; host; port; max_connections }
| |
d952b7b23860f22d77e8535e8334fe88982a2328aa2cc1f75081c64f2e8b0e0a | alan-turing-institute/advent-of-code-2021 | day5.rkt | #lang racket
(struct line (x0 y0 x1 y1))
;; Step through [start, end], with a step size depending on the sign
of end - start . Step size of zero means repeat forever ( presumably
;; the *other* coordinate doesn't!)
(define (in-coord start end)
(define step (sgn (- end start)))
(in-inclusive-range start end step))
(define (line->points l)
(sequence->list
(sequence-map list (in-parallel (in-coord (line-x0 l) (line-x1 l))
(in-coord (line-y0 l) (line-y1 l))))))
(define (count-overlapping lines)
(count (λ (grp) (>= (length grp) 2))
(group-by values (append-map line->points lines))))
(define (part1 lines)
(count-overlapping
(filter (λ (l) (or (= (line-x0 l) (line-x1 l))
(= (line-y0 l) (line-y1 l))))
lines)))
(define part2 count-overlapping)
(define (parse-line str)
(define pattern #rx"([0-9]*),([0-9]*) -> ([0-9]*),([0-9]*)")
(define regexp-group-matches (cdr (regexp-match pattern str)))
(apply line (map string->number regexp-group-matches)))
(define (read-input) (map parse-line (port->lines)))
(module+ test
(require rackunit)
(define test-input (with-input-from-file "test.in" read-input))
(check-equal? (part1 test-input) 5)
(check-equal? (part2 test-input) 12))
(module+ main
(define input (with-input-from-file "5.in" read-input))
(part1 input)
(part2 input))
| null | https://raw.githubusercontent.com/alan-turing-institute/advent-of-code-2021/1053541fbd2598591c5042f18c034fbc17995284/day-05/racket_ots22/day5.rkt | racket | Step through [start, end], with a step size depending on the sign
the *other* coordinate doesn't!) | #lang racket
(struct line (x0 y0 x1 y1))
of end - start . Step size of zero means repeat forever ( presumably
(define (in-coord start end)
(define step (sgn (- end start)))
(in-inclusive-range start end step))
(define (line->points l)
(sequence->list
(sequence-map list (in-parallel (in-coord (line-x0 l) (line-x1 l))
(in-coord (line-y0 l) (line-y1 l))))))
(define (count-overlapping lines)
(count (λ (grp) (>= (length grp) 2))
(group-by values (append-map line->points lines))))
(define (part1 lines)
(count-overlapping
(filter (λ (l) (or (= (line-x0 l) (line-x1 l))
(= (line-y0 l) (line-y1 l))))
lines)))
(define part2 count-overlapping)
(define (parse-line str)
(define pattern #rx"([0-9]*),([0-9]*) -> ([0-9]*),([0-9]*)")
(define regexp-group-matches (cdr (regexp-match pattern str)))
(apply line (map string->number regexp-group-matches)))
(define (read-input) (map parse-line (port->lines)))
(module+ test
(require rackunit)
(define test-input (with-input-from-file "test.in" read-input))
(check-equal? (part1 test-input) 5)
(check-equal? (part2 test-input) 12))
(module+ main
(define input (with-input-from-file "5.in" read-input))
(part1 input)
(part2 input))
|
f90997f67975c44259c223d75b255851fbb5827b217baee7d260d5f958e1323c | erikd/vector-algorithms | Insertion.hs | # LANGUAGE TypeFamilies #
-- ---------------------------------------------------------------------------
-- |
-- Module : Data.Vector.Algorithms.Insertion
Copyright : ( c ) 2008 - 2010
Maintainer :
-- Stability : Experimental
-- Portability : Portable
--
-- A simple insertion sort. Though it's O(n^2), its iterative nature can be
-- beneficial for small arrays. It is used to sort small segments of an array
-- by some of the more heavy-duty, recursive algorithms.
module Data.Vector.Algorithms.Insertion
( sort
, sortUniq
, sortBy
, sortUniqBy
, sortByBounds
, sortByBounds'
, Comparison
) where
import Prelude hiding (read, length)
import Control.Monad.Primitive
import Data.Vector.Generic.Mutable
import Data.Vector.Algorithms.Common (Comparison, uniqueMutableBy)
import qualified Data.Vector.Algorithms.Optimal as O
-- | Sorts an entire array using the default comparison for the type
sort :: (PrimMonad m, MVector v e, Ord e) => v (PrimState m) e -> m ()
sort = sortBy compare
# INLINABLE sort #
-- | A variant on `sort` that returns a vector of unique elements.
sortUniq :: (PrimMonad m, MVector v e, Ord e) => v (PrimState m) e -> m (v (PrimState m) e)
sortUniq = sortUniqBy compare
# INLINABLE sortUniq #
-- | Sorts an entire array using a given comparison
sortBy :: (PrimMonad m, MVector v e) => Comparison e -> v (PrimState m) e -> m ()
sortBy cmp a = sortByBounds cmp a 0 (length a)
# INLINE sortBy #
-- | A variant on `sortBy` which returns a vector of unique elements.
sortUniqBy :: (PrimMonad m, MVector v e) => Comparison e -> v (PrimState m) e -> m (v (PrimState m) e)
sortUniqBy cmp a = do
sortByBounds cmp a 0 (length a)
uniqueMutableBy cmp a
{-# INLINE sortUniqBy #-}
-- | Sorts the portion of an array delimited by [l,u)
sortByBounds :: (PrimMonad m, MVector v e)
=> Comparison e -> v (PrimState m) e -> Int -> Int -> m ()
sortByBounds cmp a l u
| len < 2 = return ()
| len == 2 = O.sort2ByOffset cmp a l
| len == 3 = O.sort3ByOffset cmp a l
| len == 4 = O.sort4ByOffset cmp a l
| otherwise = O.sort4ByOffset cmp a l >> sortByBounds' cmp a l (l + 4) u
where
len = u - l
# INLINE sortByBounds #
-- | Sorts the portion of the array delimited by [l,u) under the assumption
-- that [l,m) is already sorted.
sortByBounds' :: (PrimMonad m, MVector v e)
=> Comparison e -> v (PrimState m) e -> Int -> Int -> Int -> m ()
sortByBounds' cmp a l m u = sort m
where
sort i
| i < u = do v <- unsafeRead a i
insert cmp a l v i
sort (i+1)
| otherwise = return ()
# INLINE sortByBounds ' #
-- Given a sorted array in [l,u), inserts val into its proper position,
-- yielding a sorted [l,u]
insert :: (PrimMonad m, MVector v e)
=> Comparison e -> v (PrimState m) e -> Int -> e -> Int -> m ()
insert cmp a l = loop
where
loop val j
| j <= l = unsafeWrite a l val
| otherwise = do e <- unsafeRead a (j - 1)
case cmp val e of
LT -> unsafeWrite a j e >> loop val (j - 1)
_ -> unsafeWrite a j val
# INLINE insert #
| null | https://raw.githubusercontent.com/erikd/vector-algorithms/a8b985c16ae9d6560376f57eb7a9a175b4e3ea78/src/Data/Vector/Algorithms/Insertion.hs | haskell | ---------------------------------------------------------------------------
|
Module : Data.Vector.Algorithms.Insertion
Stability : Experimental
Portability : Portable
A simple insertion sort. Though it's O(n^2), its iterative nature can be
beneficial for small arrays. It is used to sort small segments of an array
by some of the more heavy-duty, recursive algorithms.
| Sorts an entire array using the default comparison for the type
| A variant on `sort` that returns a vector of unique elements.
| Sorts an entire array using a given comparison
| A variant on `sortBy` which returns a vector of unique elements.
# INLINE sortUniqBy #
| Sorts the portion of an array delimited by [l,u)
| Sorts the portion of the array delimited by [l,u) under the assumption
that [l,m) is already sorted.
Given a sorted array in [l,u), inserts val into its proper position,
yielding a sorted [l,u] | # LANGUAGE TypeFamilies #
Copyright : ( c ) 2008 - 2010
Maintainer :
module Data.Vector.Algorithms.Insertion
( sort
, sortUniq
, sortBy
, sortUniqBy
, sortByBounds
, sortByBounds'
, Comparison
) where
import Prelude hiding (read, length)
import Control.Monad.Primitive
import Data.Vector.Generic.Mutable
import Data.Vector.Algorithms.Common (Comparison, uniqueMutableBy)
import qualified Data.Vector.Algorithms.Optimal as O
sort :: (PrimMonad m, MVector v e, Ord e) => v (PrimState m) e -> m ()
sort = sortBy compare
# INLINABLE sort #
sortUniq :: (PrimMonad m, MVector v e, Ord e) => v (PrimState m) e -> m (v (PrimState m) e)
sortUniq = sortUniqBy compare
# INLINABLE sortUniq #
sortBy :: (PrimMonad m, MVector v e) => Comparison e -> v (PrimState m) e -> m ()
sortBy cmp a = sortByBounds cmp a 0 (length a)
# INLINE sortBy #
sortUniqBy :: (PrimMonad m, MVector v e) => Comparison e -> v (PrimState m) e -> m (v (PrimState m) e)
sortUniqBy cmp a = do
sortByBounds cmp a 0 (length a)
uniqueMutableBy cmp a
sortByBounds :: (PrimMonad m, MVector v e)
=> Comparison e -> v (PrimState m) e -> Int -> Int -> m ()
sortByBounds cmp a l u
| len < 2 = return ()
| len == 2 = O.sort2ByOffset cmp a l
| len == 3 = O.sort3ByOffset cmp a l
| len == 4 = O.sort4ByOffset cmp a l
| otherwise = O.sort4ByOffset cmp a l >> sortByBounds' cmp a l (l + 4) u
where
len = u - l
# INLINE sortByBounds #
sortByBounds' :: (PrimMonad m, MVector v e)
=> Comparison e -> v (PrimState m) e -> Int -> Int -> Int -> m ()
sortByBounds' cmp a l m u = sort m
where
sort i
| i < u = do v <- unsafeRead a i
insert cmp a l v i
sort (i+1)
| otherwise = return ()
# INLINE sortByBounds ' #
insert :: (PrimMonad m, MVector v e)
=> Comparison e -> v (PrimState m) e -> Int -> e -> Int -> m ()
insert cmp a l = loop
where
loop val j
| j <= l = unsafeWrite a l val
| otherwise = do e <- unsafeRead a (j - 1)
case cmp val e of
LT -> unsafeWrite a j e >> loop val (j - 1)
_ -> unsafeWrite a j val
# INLINE insert #
|
a5605f3d823f01b59b27f608086036de494cefbdea1321722d5539d49da6ce3a | david-christiansen/pudding | rewindable-streams.rkt | #lang racket/base
(require racket/contract)
(provide make-rstream list->rstream rstream-forever
rstream-next
rstream-snapshot rstream-rewind!)
(module+ test
(require rackunit))
(struct rstream (contents))
(define the-streams (box (make-weak-hasheq)))
(define/contract (make-rstream contents)
(-> (-> exact-nonnegative-integer? any/c) rstream?)
(define s (rstream contents))
(hash-set! (unbox the-streams) s 0)
s)
(define (rstream-next s)
(define pos (hash-ref (unbox the-streams) s))
(hash-set! (unbox the-streams) s (add1 pos) )
((rstream-contents s) pos))
(define (rstream-snapshot)
(hash-copy (unbox the-streams)))
(define (rstream-rewind! snapshot)
(for ([(s pos) (in-hash snapshot)])
(hash-set! (unbox the-streams) s pos)))
(define (rstream-forever x)
(make-rstream (lambda (i) x)))
(define (list->rstream xs (default #f))
(define l (length xs))
(make-rstream (lambda (i)
(if (< i l)
(list-ref xs i)
default))))
(module+ test
(define nums (list 1 2 3 4 5))
(define num-stream (list->rstream nums))
(check-equal? (rstream-next num-stream) 1)
(check-equal? (rstream-next num-stream) 2)
(check-equal? (rstream-next num-stream) 3)
(define s (rstream-snapshot))
(check-equal? (rstream-next num-stream) 4)
(check-equal? (rstream-next num-stream) 5)
(check-equal? (rstream-next num-stream) #f)
(check-equal? (rstream-next num-stream) #f)
(check-equal? (rstream-next num-stream) #f)
(rstream-rewind! s)
(check-equal? (rstream-next num-stream) 4)
(check-equal? (rstream-next num-stream) 5)
(check-equal? (rstream-next num-stream) #f)
(check-equal? (rstream-next num-stream) #f)
(check-equal? (rstream-next num-stream) #f)
(rstream-rewind! s)
(check-equal? (rstream-next num-stream) 4)
(check-equal? (rstream-next num-stream) 5)
(check-equal? (rstream-next num-stream) #f)
(check-equal? (rstream-next num-stream) #f)
(check-equal? (rstream-next num-stream) #f))
| null | https://raw.githubusercontent.com/david-christiansen/pudding/ead4e1a2e8e0d77a884211adcc4466edcf65e406/rewindable-streams.rkt | racket | #lang racket/base
(require racket/contract)
(provide make-rstream list->rstream rstream-forever
rstream-next
rstream-snapshot rstream-rewind!)
(module+ test
(require rackunit))
(struct rstream (contents))
(define the-streams (box (make-weak-hasheq)))
(define/contract (make-rstream contents)
(-> (-> exact-nonnegative-integer? any/c) rstream?)
(define s (rstream contents))
(hash-set! (unbox the-streams) s 0)
s)
(define (rstream-next s)
(define pos (hash-ref (unbox the-streams) s))
(hash-set! (unbox the-streams) s (add1 pos) )
((rstream-contents s) pos))
(define (rstream-snapshot)
(hash-copy (unbox the-streams)))
(define (rstream-rewind! snapshot)
(for ([(s pos) (in-hash snapshot)])
(hash-set! (unbox the-streams) s pos)))
(define (rstream-forever x)
(make-rstream (lambda (i) x)))
(define (list->rstream xs (default #f))
(define l (length xs))
(make-rstream (lambda (i)
(if (< i l)
(list-ref xs i)
default))))
(module+ test
(define nums (list 1 2 3 4 5))
(define num-stream (list->rstream nums))
(check-equal? (rstream-next num-stream) 1)
(check-equal? (rstream-next num-stream) 2)
(check-equal? (rstream-next num-stream) 3)
(define s (rstream-snapshot))
(check-equal? (rstream-next num-stream) 4)
(check-equal? (rstream-next num-stream) 5)
(check-equal? (rstream-next num-stream) #f)
(check-equal? (rstream-next num-stream) #f)
(check-equal? (rstream-next num-stream) #f)
(rstream-rewind! s)
(check-equal? (rstream-next num-stream) 4)
(check-equal? (rstream-next num-stream) 5)
(check-equal? (rstream-next num-stream) #f)
(check-equal? (rstream-next num-stream) #f)
(check-equal? (rstream-next num-stream) #f)
(rstream-rewind! s)
(check-equal? (rstream-next num-stream) 4)
(check-equal? (rstream-next num-stream) 5)
(check-equal? (rstream-next num-stream) #f)
(check-equal? (rstream-next num-stream) #f)
(check-equal? (rstream-next num-stream) #f))
| |
9752c082fb23da6d92d8b20670a55ebd2d4783a54e08e7518b2e364e0e441633 | tfausak/advent-of-code | 1.hs | -- stack --resolver lts-12.0 script
import qualified Data.List as List
import qualified Data.Ord as Ord
import qualified Text.ParserCombinators.ReadP as Parse
main = do
nanobots <- map read . lines <$> readFile "input.txt"
let strongest = List.maximumBy (Ord.comparing r) nanobots
print . length $ filter (inRange strongest) nanobots
inRange a b = distance a b <= r a
distance a b = abs (x a - x b) + abs (y a - y b) + abs (z a - z b)
data Nanobot = Nanobot { x, y, z, r :: Int } deriving (Show)
instance Read Nanobot where
readsPrec n = Parse.readP_to_S (Nanobot
<$> (Parse.string "pos=<" *> Parse.readS_to_P (readsPrec n))
<*> (Parse.char ',' *> Parse.readS_to_P (readsPrec n))
<*> (Parse.char ',' *> Parse.readS_to_P (readsPrec n))
<*> (Parse.string ">, r=" *> Parse.readS_to_P (readsPrec n)))
| null | https://raw.githubusercontent.com/tfausak/advent-of-code/26f0d9726b019ff7b97fa7e0f2f995269b399578/2018/23/1.hs | haskell | stack --resolver lts-12.0 script | import qualified Data.List as List
import qualified Data.Ord as Ord
import qualified Text.ParserCombinators.ReadP as Parse
main = do
nanobots <- map read . lines <$> readFile "input.txt"
let strongest = List.maximumBy (Ord.comparing r) nanobots
print . length $ filter (inRange strongest) nanobots
inRange a b = distance a b <= r a
distance a b = abs (x a - x b) + abs (y a - y b) + abs (z a - z b)
data Nanobot = Nanobot { x, y, z, r :: Int } deriving (Show)
instance Read Nanobot where
readsPrec n = Parse.readP_to_S (Nanobot
<$> (Parse.string "pos=<" *> Parse.readS_to_P (readsPrec n))
<*> (Parse.char ',' *> Parse.readS_to_P (readsPrec n))
<*> (Parse.char ',' *> Parse.readS_to_P (readsPrec n))
<*> (Parse.string ">, r=" *> Parse.readS_to_P (readsPrec n)))
|
44bf32bd79fe68769b67f785773a39f8da31833eb919370d7347a863275ec5f4 | aarkerio/ZentaurLMS | test_runner.cljs | (ns zentaur.test-runner
(:require [cljs.test]
[cljs-test-display.core]
[zentaur.core-test])
(:require-macros
[cljs.test]))
(defn test-run []
;; where "app" is the HTML node where you want to mount the tests
(cljs.test/run-tests
(cljs-test-display.core/init! "app") ;;<-- initialize cljs-test-display here
;; 'zentaur.post-test
'zentaur.core-test))
| null | https://raw.githubusercontent.com/aarkerio/ZentaurLMS/adb43fb879b88d6a35f7f556cb225f7930d524f9/test/cljs/zentaur/test_runner.cljs | clojure | where "app" is the HTML node where you want to mount the tests
<-- initialize cljs-test-display here
'zentaur.post-test | (ns zentaur.test-runner
(:require [cljs.test]
[cljs-test-display.core]
[zentaur.core-test])
(:require-macros
[cljs.test]))
(defn test-run []
(cljs.test/run-tests
'zentaur.core-test))
|
76603952356012ed0205ad5a668e97b4cb18947f6c5705a2877786c22d0df1ec | ubf/ubf | ebf_tests.erl | %%% The MIT License
%%%
Copyright ( C ) 2011 - 2016 by < >
Copyright ( C ) 2002 by
%%%
%%% Permission is hereby granted, free of charge, to any person obtaining a copy
%%% of this software and associated documentation files (the "Software"), to deal
in the Software without restriction , including without limitation the rights
%%% to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software , and to permit persons to whom the Software is
%%% furnished to do so, subject to the following conditions:
%%%
%%% The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software .
%%%
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
%%% IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
%%% FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
%%% AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING FROM ,
%%% OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
%%% THE SOFTWARE.
-module(ebf_tests).
-compile(export_all).
-include("ubf.hrl").
-include_lib("eunit/include/eunit.hrl").
-import(lists, [map/2, foldl/3, filter/2]).
-import(ubf_client, [rpc/2, sendEvent/2, install_default_handler/1, install_handler/2]).
defaultPlugins() -> [test_plugin, irc_plugin, file_plugin].
defaultOptions() -> [{plugins, defaultPlugins()}].
defaultTimeout() -> 10000.
defaultPort() -> server_port(test_ebf_tcp_port).
server_port(Name) ->
case proc_socket_server:server_port(Name) of
Port when is_integer(Port) ->
Port;
_ ->
timer:sleep(10),
server_port(Name)
end.
test_ebf() ->
ss(),
run(),
ok = application:stop(test),
true.
ss() ->
_ = application:start(sasl),
_ = application:stop(test),
ok = application:start(test).
run() ->
{ok, Pid, _Name} = ubf_client:connect(host(), defaultPort(), [{proto,ebf}], defaultTimeout()),
Info = ubf_client:rpc(Pid, info),
io:format("Info=~p~n",[Info]),
Services = ubf_client:rpc(Pid, services),
io:format("Services=~p~n",[Services]),
%% Try to start a missing service
R1 = ubf_client:rpc(Pid, {startSession, ?S("missing"), []}),
io:format("R1=~p~n",[R1]),
%% Try to start the test server with the wrong password
R2 = ubf_client:rpc(Pid, {startSession, ?S("test"), guess}),
io:format("R2=~p~n",[R2]),
%% Now the correct password
R3 = ubf_client:rpc(Pid, {startSession, ?S("test"), secret}),
io:format("R3=~p~n",[R3]),
rpc(Pid, {logon,?S("joe")}),
{reply, {files, _}, active} = rpc(Pid, ls),
%% async. event server -> client
install_single_callback_handler(Pid),
Term = {1,2,cat,rain,dogs},
{reply, callbackOnItsWay, active} = rpc(Pid, {callback,Term}),
{callback, Term} = expect_callback(Pid),
%% async. event client -> server
install_single_callback_handler(Pid),
Term = {1,2,cat,rain,dogs},
sendEvent(Pid, {callback,Term}),
{callback, Term} = expect_callback(Pid),
{reply, yes, funny} = rpc(Pid, testAmbiguities),
{reply, ?S("ABC"), funny} = rpc(Pid, ?S("abc")),
{reply, ?P([]), funny} = rpc(Pid, ?P([])),
{reply, ?P([{a,b}]), funny} = rpc(Pid, ?P([{a,b}])),
{reply, ?P([{a,b},{c,d}]), funny} = rpc(Pid, ?P([{a,b},{c,d}])),
{reply, [400,800], funny} = rpc(Pid, [200,400]),
{reply, [194,196], funny} = rpc(Pid, "ab"),
ubf_client:stop(Pid),
io:format("test_ebf worked~n").
host() ->
case os:getenv("WHERE") of
"WORK" -> "p2p.sics.se";
_ -> "localhost"
end.
install_single_callback_handler(Pid) ->
Parent = self(),
install_handler(Pid,
fun(Msg) ->
Parent ! {singleCallback, Msg},
install_default_handler(Pid)
end).
expect_callback(_Pid) ->
receive
{singleCallback, X} ->
X
end.
sleep(T) ->
receive
after T * 1000 ->
true
end.
| null | https://raw.githubusercontent.com/ubf/ubf/c876f684fbd4959548ace1eb1cfc91941f93d377/test/unit/ebf_tests.erl | erlang | The MIT License
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
Try to start a missing service
Try to start the test server with the wrong password
Now the correct password
async. event server -> client
async. event client -> server | Copyright ( C ) 2011 - 2016 by < >
Copyright ( C ) 2002 by
in the Software without restriction , including without limitation the rights
copies of the Software , and to permit persons to whom the Software is
all copies or substantial portions of the Software .
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING FROM ,
-module(ebf_tests).
-compile(export_all).
-include("ubf.hrl").
-include_lib("eunit/include/eunit.hrl").
-import(lists, [map/2, foldl/3, filter/2]).
-import(ubf_client, [rpc/2, sendEvent/2, install_default_handler/1, install_handler/2]).
defaultPlugins() -> [test_plugin, irc_plugin, file_plugin].
defaultOptions() -> [{plugins, defaultPlugins()}].
defaultTimeout() -> 10000.
defaultPort() -> server_port(test_ebf_tcp_port).
server_port(Name) ->
case proc_socket_server:server_port(Name) of
Port when is_integer(Port) ->
Port;
_ ->
timer:sleep(10),
server_port(Name)
end.
test_ebf() ->
ss(),
run(),
ok = application:stop(test),
true.
ss() ->
_ = application:start(sasl),
_ = application:stop(test),
ok = application:start(test).
run() ->
{ok, Pid, _Name} = ubf_client:connect(host(), defaultPort(), [{proto,ebf}], defaultTimeout()),
Info = ubf_client:rpc(Pid, info),
io:format("Info=~p~n",[Info]),
Services = ubf_client:rpc(Pid, services),
io:format("Services=~p~n",[Services]),
R1 = ubf_client:rpc(Pid, {startSession, ?S("missing"), []}),
io:format("R1=~p~n",[R1]),
R2 = ubf_client:rpc(Pid, {startSession, ?S("test"), guess}),
io:format("R2=~p~n",[R2]),
R3 = ubf_client:rpc(Pid, {startSession, ?S("test"), secret}),
io:format("R3=~p~n",[R3]),
rpc(Pid, {logon,?S("joe")}),
{reply, {files, _}, active} = rpc(Pid, ls),
install_single_callback_handler(Pid),
Term = {1,2,cat,rain,dogs},
{reply, callbackOnItsWay, active} = rpc(Pid, {callback,Term}),
{callback, Term} = expect_callback(Pid),
install_single_callback_handler(Pid),
Term = {1,2,cat,rain,dogs},
sendEvent(Pid, {callback,Term}),
{callback, Term} = expect_callback(Pid),
{reply, yes, funny} = rpc(Pid, testAmbiguities),
{reply, ?S("ABC"), funny} = rpc(Pid, ?S("abc")),
{reply, ?P([]), funny} = rpc(Pid, ?P([])),
{reply, ?P([{a,b}]), funny} = rpc(Pid, ?P([{a,b}])),
{reply, ?P([{a,b},{c,d}]), funny} = rpc(Pid, ?P([{a,b},{c,d}])),
{reply, [400,800], funny} = rpc(Pid, [200,400]),
{reply, [194,196], funny} = rpc(Pid, "ab"),
ubf_client:stop(Pid),
io:format("test_ebf worked~n").
host() ->
case os:getenv("WHERE") of
"WORK" -> "p2p.sics.se";
_ -> "localhost"
end.
install_single_callback_handler(Pid) ->
Parent = self(),
install_handler(Pid,
fun(Msg) ->
Parent ! {singleCallback, Msg},
install_default_handler(Pid)
end).
expect_callback(_Pid) ->
receive
{singleCallback, X} ->
X
end.
sleep(T) ->
receive
after T * 1000 ->
true
end.
|
7015bab4bf2df6b64ce8e43d86e4f989cbc72afd5472150f274781921d3506f3 | may-liu/qtalk | http_sendmessage.erl | %% Feel free to use, reuse and abuse the code in this file.
-module(http_sendmessage).
-export([init/3]).
-export([handle/2]).
-export([terminate/3]).
-include("logger.hrl").
-include("http_req.hrl").
-include("ejb_http_server.hrl").
init(_Transport, Req, []) ->
{ok, Req, undefined}.
handle(Req, State) ->
catch ejb_monitor:monitor_count(<<"http_sendmessage">>,1),
handle(Req, State, true).
handle(Req, State, false) ->
Req_Res = Req#http_req{resp_compress = true},
Res = http_utils:gen_result(false, <<"3">>, <<"ip is limited">>),
{ok, NewReq} = cowboy_req:reply(200, [
{<<"content-type">>, <<"text/plain; charset=utf-8">>}
], Res, Req_Res),
{ok, NewReq, State};
handle(Req, State, _) ->
{Method, _} = cowboy_req:method(Req),
case Method of
<<"GET">> ->
{Host,_} = cowboy_req:host(Req),
{ok, Req1} = get_echo(Method,Host,Req),
{ok, Req1, State};
<<"POST">> ->
HasBody = cowboy_req:has_body(Req),
{ok, Req1} = post_echo(Method, HasBody, Req),
{ok, Req1, State};
_ ->
{ok,Req1} = echo(undefined, Req),
{ok, Req1, State}
end.
get_echo(<<"GET">>,_,Req) ->
cowboy_req:reply(200, [
{<<"content-type">>, <<"text/json; charset=utf-8">>}
], <<"No GET method">>, Req).
post_echo(<<"POST">>, true, Req) ->
{ok, Body, _} = cowboy_req:body(Req),
Ret =
case rfc4627:decode(Body) of
{ok,[{obj,Args}],[]} ->
User = proplists:get_value("From",Args),
case User of
<<"menpiaonotice1">> ->
?DEBUG("menpiaonotice in blacklist ~n",[]),
http_utils:gen_result(false, <<"4">>, <<"ip is in blacklist">>);
_ ->
case iplimit_util : check_ips_limit_with_args(Req,<<"1">>,User , ) of
case true of
true ->
case rpc_send_message(Args) of
{error,_Reason} ->
do_http_send_message(Body);
V ->
V
end;
_ ->
http_utils:gen_result(false, <<"3">>, <<"ip is limited">>)
end
end;
_ ->
http_utils:gen_result(false, <<"-1">>, <<"Josn parse error">>)
end,
cowboy_req:reply(200, [ {<<"content-type">>, <<"text/json; charset=utf-8">>}], Ret, Req);
post_echo(<<"POST">>, false, Req) ->
cowboy_req:reply(400, [], <<"Missing Post body.">>, Req);
post_echo(_, _, Req) ->
cowboy_req:reply(405, Req).
echo(undefined, Req) ->
cowboy_req:reply(400, [], <<"Missing parameter.">>, Req);
echo(Echo, Req) ->
cowboy_req:reply(200, [
{<<"content-type">>, <<"text/json; charset=utf-8">>}
], Echo, Req).
terminate(_Reason, _Req, _State) ->
ok.
rpc_send_message(Args) ->
case catch ets:lookup(ejabberd_config,<<"node">>) of
[Ejb_node] when is_record(Ejb_node,ejabberd_config) ->
case rpc:call(Ejb_node#ejabberd_config.val,http_sendmessage,http_send_message,[Args]) of
{badrpc,Reason} ->
?DEBUG("Reason ~p ~n",[Reason]),
{error,Reason};
V ->
V
end;
_ ->
http_utils : gen_result(false , < < " 4 " > > , < < " rpc run error " > > )
{error,<<"no found node">>}
end.
do_http_send_message(Body) ->
Url1 =
case catch ets:lookup(ejabberd_config,<<"http_server">>) of
[Http_server] when is_record(Http_server,ejabberd_config) ->
Http_server#ejabberd_config.val;
_ ->
":10050/"
end,
Url = Url1 ++ "sendmessage",
Header = [],
Type = "application/json",
HTTPOptions = [],
Options = [],
case http_client:http_post(Url,Header,Type,Body,HTTPOptions,Options) of
{ok, {_Status,_Headers, Rslt}} ->
Rslt;
_ ->
rfc4627:encode({obj,[{"data",<<"Send Message Error">>}]})
end.
| null | https://raw.githubusercontent.com/may-liu/qtalk/f5431e5a7123975e9656e7ab239e674ce33713cd/qtalk_opensource/scripts/ejb_http_server/src/http_sendmessage.erl | erlang | Feel free to use, reuse and abuse the code in this file. |
-module(http_sendmessage).
-export([init/3]).
-export([handle/2]).
-export([terminate/3]).
-include("logger.hrl").
-include("http_req.hrl").
-include("ejb_http_server.hrl").
init(_Transport, Req, []) ->
{ok, Req, undefined}.
handle(Req, State) ->
catch ejb_monitor:monitor_count(<<"http_sendmessage">>,1),
handle(Req, State, true).
handle(Req, State, false) ->
Req_Res = Req#http_req{resp_compress = true},
Res = http_utils:gen_result(false, <<"3">>, <<"ip is limited">>),
{ok, NewReq} = cowboy_req:reply(200, [
{<<"content-type">>, <<"text/plain; charset=utf-8">>}
], Res, Req_Res),
{ok, NewReq, State};
handle(Req, State, _) ->
{Method, _} = cowboy_req:method(Req),
case Method of
<<"GET">> ->
{Host,_} = cowboy_req:host(Req),
{ok, Req1} = get_echo(Method,Host,Req),
{ok, Req1, State};
<<"POST">> ->
HasBody = cowboy_req:has_body(Req),
{ok, Req1} = post_echo(Method, HasBody, Req),
{ok, Req1, State};
_ ->
{ok,Req1} = echo(undefined, Req),
{ok, Req1, State}
end.
get_echo(<<"GET">>,_,Req) ->
cowboy_req:reply(200, [
{<<"content-type">>, <<"text/json; charset=utf-8">>}
], <<"No GET method">>, Req).
post_echo(<<"POST">>, true, Req) ->
{ok, Body, _} = cowboy_req:body(Req),
Ret =
case rfc4627:decode(Body) of
{ok,[{obj,Args}],[]} ->
User = proplists:get_value("From",Args),
case User of
<<"menpiaonotice1">> ->
?DEBUG("menpiaonotice in blacklist ~n",[]),
http_utils:gen_result(false, <<"4">>, <<"ip is in blacklist">>);
_ ->
case iplimit_util : check_ips_limit_with_args(Req,<<"1">>,User , ) of
case true of
true ->
case rpc_send_message(Args) of
{error,_Reason} ->
do_http_send_message(Body);
V ->
V
end;
_ ->
http_utils:gen_result(false, <<"3">>, <<"ip is limited">>)
end
end;
_ ->
http_utils:gen_result(false, <<"-1">>, <<"Josn parse error">>)
end,
cowboy_req:reply(200, [ {<<"content-type">>, <<"text/json; charset=utf-8">>}], Ret, Req);
post_echo(<<"POST">>, false, Req) ->
cowboy_req:reply(400, [], <<"Missing Post body.">>, Req);
post_echo(_, _, Req) ->
cowboy_req:reply(405, Req).
echo(undefined, Req) ->
cowboy_req:reply(400, [], <<"Missing parameter.">>, Req);
echo(Echo, Req) ->
cowboy_req:reply(200, [
{<<"content-type">>, <<"text/json; charset=utf-8">>}
], Echo, Req).
terminate(_Reason, _Req, _State) ->
ok.
rpc_send_message(Args) ->
case catch ets:lookup(ejabberd_config,<<"node">>) of
[Ejb_node] when is_record(Ejb_node,ejabberd_config) ->
case rpc:call(Ejb_node#ejabberd_config.val,http_sendmessage,http_send_message,[Args]) of
{badrpc,Reason} ->
?DEBUG("Reason ~p ~n",[Reason]),
{error,Reason};
V ->
V
end;
_ ->
http_utils : gen_result(false , < < " 4 " > > , < < " rpc run error " > > )
{error,<<"no found node">>}
end.
do_http_send_message(Body) ->
Url1 =
case catch ets:lookup(ejabberd_config,<<"http_server">>) of
[Http_server] when is_record(Http_server,ejabberd_config) ->
Http_server#ejabberd_config.val;
_ ->
":10050/"
end,
Url = Url1 ++ "sendmessage",
Header = [],
Type = "application/json",
HTTPOptions = [],
Options = [],
case http_client:http_post(Url,Header,Type,Body,HTTPOptions,Options) of
{ok, {_Status,_Headers, Rslt}} ->
Rslt;
_ ->
rfc4627:encode({obj,[{"data",<<"Send Message Error">>}]})
end.
|
ab0428eaa27990836c7eb6e513bae9c7b47c7065f0e4ca646b48d9804f80f399 | dbenoit17/dynamic-ffi | export.rkt | ;; This module provides functions for exporting
FFI bindings as shippable racket files .
#lang racket/base
(require
racket/string
racket/port
racket/runtime-path
racket/contract
(only-in ffi/unsafe ffi-lib _byte get-ffi-obj)
(for-syntax racket/base)
(prefix-in dffi: "meta.rkt"))
(provide
create-mapped-static-ffi
create-static-ffi
(contract-out
[generate-static-ffi
(->* ((or/c string? symbol?)
(or/c string? path?)
(or/c string? path? (listof string?)))
(#:prune-undefined? any/c)
#:rest (listof (or/c string? path?))
any)]
[generate-mapped-static-ffi
(->* ((or/c string? symbol?)
(or/c string? path?)
(or/c string? path? (listof string?)))
(#:prune-undefined? any/c)
#:rest (listof (or/c string? path?))
any)]))
(define-runtime-path mapped-ffi-template-path
(build-path "template-files" "mapped-ffi-template"))
(define-runtime-path defined-ffi-template-path
(build-path "template-files" "defined-ffi-template"))
(define (format-list l)
(format "(list ~a)"
(string-join
(for/list ([e l])
(format "~a" e)))))
(define (format-string-list l)
(format "(list ~a)"
(string-join
(for/list ([e l])
(format "\"~a\"" e)))))
(define (format-ffi-int ct-int)
(define width (dffi:ctype-width ct-int))
(unless (and (modulo width 8) (<= width 64) (>= width 0))
(error "incompatible int width: " width))
(define ints (vector '_int8 '_int16 '_int32 '_int64))
(define uints (vector '_uint8 '_uint16 '_uint32 '_uint64))
(define category
(if (dffi:ctype-int-signed? ct-int) ints uints))
(define index (- (inexact->exact (log width 2)) 3))
(vector-ref category index))
(define (format-ffi-float ct-float)
(define width (dffi:ctype-width ct-float))
(cond [(eq? width 32) '_float]
[(eq? width 64) '_double*]
[(eq? width 80) '_longdouble]
[(eq? width 128) '_longdouble]
[else (error "incompatible float width: " width)]))
(define (format-ffi-pointer ct-pointer)
(define pointee (dffi:ctype-pointer->pointee ct-pointer))
(cond [(dffi:ctype-void? pointee) '_pointer]
[(and (dffi:ctype-int? pointee)
(eq? (dffi:ctype-width pointee) 8))
'_string]
;; all pointers opaque for now to
;; prevent type conflicts
[else '_pointer]))
;; would be cool to do it this way
;;[else (_cpointer (format-dffi-obj pointee))]))
(define (format-ffi-array ct-array)
(define element (dffi:ctype-array-element ct-array))
(format "(make-array-type ~a ~a)"
(format-dffi-obj element)
(quotient (dffi:ctype-width ct-array)
(dffi:ctype-width element))))
(define (format-ffi-struct ct-struct)
(define struct-members
(for/list ([mem (dffi:ctype-record-members ct-struct)])
(format-dffi-obj mem)))
( define member - names ( dffi : ctype - record - members ct - struct ) )
(if (null? struct-members) #f
(format "(apply _list-struct ~a)" (format-list struct-members))))
(define (format-ffi-union ct-union)
(define union-members
(for/list ([mem (dffi:ctype-record-members ct-union)])
(format-dffi-obj mem)))
(if (null? union-members) #f
(format "(apply _union ~a)" (format-list union-members))))
(define (format-ffi-function ct-function)
(define params
(for/list ([param (dffi:ctype-function-params ct-function)])
(format-dffi-obj param)))
(define maybe-return (dffi:ctype-function-return ct-function))
(define return
(if (dffi:ctype-void? maybe-return)
'_void
(format-dffi-obj maybe-return)))
(format "(_cprocedure ~a ~a)" (format-list params) return))
(define (format-dffi-obj ct)
(unless (dffi:ctype? ct)
(error "expected dynamic-ffi ctype"))
(cond
[(dffi:ctype-int? ct) (format-ffi-int ct)]
[(dffi:ctype-pointer? ct) (format-ffi-pointer ct)]
[(dffi:ctype-float? ct) (format-ffi-float ct)]
[(dffi:ctype-struct? ct) (format-ffi-struct ct)]
[(dffi:ctype-union? ct) (format-ffi-union ct)]
[(dffi:ctype-array? ct) (format-ffi-array ct)]
[(dffi:ctype-function? ct) (format-ffi-function ct)]
[(dffi:ctype-void? ct)
(error "void only allowed as pointer or function return")]
[else (error "unimplemented type")]))
;; This is equivalent to build-ffi-obj-map in ffi.rkt,
;; except it produces racket source code instead
;; of runtime ffi objects.
;; ffi-lib-obj is either #f or a foreign-library value where #f means
;; don't check whether a symbol is defined.
(define (format-ffi-obj-map ffi-data lib ffi-lib-obj . headers)
(define pairs
(for/list ([decl ffi-data])
(define name (dffi:declaration-name decl))
(define type (dffi:declaration-type decl))
(define ffi-obj
(cond [(dffi:enum-decl? decl)
(format "~a" (dffi:declaration-literal-value decl))]
[(or (dffi:record-decl? decl)
(dffi:typedef-decl? decl))
(format-dffi-obj type)]
[(or (dffi:function-decl? decl)
(dffi:var-decl? decl))
(cond
[(or (not ffi-lib-obj)
(get-ffi-obj (string->symbol name) ffi-lib-obj _byte (λ () #f)))
;; NOTE: use _byte as a dummy type which will return a Racket integer
;; when the symbol exists, #f otherwise
(format "(get-ffi-obj '~a ~a\n ~a \n (warn-undefined-symbol '~a))"
name lib (format-dffi-obj type) name)]
[else
(eprintf "warning: ~a is undefined\n" name)
#f])]
[else
(eprintf "warning: unimplemented delcaration type: ~a\n" decl)
#f]))
(cons (string->symbol name) ffi-obj)))
(make-hash (filter (λ (x) (cdr x)) pairs)))
;; The following functions feel ambiguously named to me, so I'll
;; document their exact usage in more detail.
;; The export ffi functions are the core exporting functions
;; They take a formatted ffi map produced by format-ffi-obj-map
;; and export an ffi to an output file
(define (export-mapped-ffi file ffi-name library-name lib headers ffi-map)
(define template-port (open-input-file mapped-ffi-template-path))
(define template (port->string template-port))
(define formatted-pairs
(format "(make-hash\n ~a)"
(format-list
(for/list ([pr (filter (λ (x) (cdr x)) (hash->list ffi-map))])
(format "\n (cons '~a\n ~a)" (car pr) (cdr pr))))))
(close-input-port template-port)
(with-output-to-file file #:exists 'replace
(λ () (printf template
library-name lib ffi-name (format-string-list headers)
ffi-name formatted-pairs ffi-name))))
(define (export-ffi file ffi-name library-name lib headers ffi-map)
(define template-port (open-input-file defined-ffi-template-path))
(define template (port->string template-port))
(define formatted-definitions
(string-join
(for/list ([pr (filter (λ (x) (cdr x)) (hash->list ffi-map))])
(format "(define ~a-~a\n ~a)\n\n" ffi-name (car pr) (cdr pr)))
""))
(close-input-port template-port)
(with-output-to-file file #:exists 'replace
(λ () (printf template
library-name lib ffi-name (format-string-list headers)
ffi-name formatted-definitions))))
The create ffi functions take unformatted ffi metadata produced by
;; dffi:dynamic-ffi-parse, format the data for export, and wrap the export
ffi functions . These are useful when ffi - data is generated earlier
;; in a routine and used by other functions than just export.
;; define-dynamic-ffi/cached in cached.rkt is an example of this.
(define (create-static-ffi-generic dispatch ffi-data prune-undefined?
file ffi-name lib headers)
(define library-name (format "~a-ffi-lib" ffi-name))
(define-values (ffi-library ffi-lib-obj)
(cond [(or (string? lib) (path? lib))
(values (format "(ffi-lib \"~a\")" lib)
(and prune-undefined? (ffi-lib lib)))]
[(pair? lib)
(values (format "(ffi-lib \"~a\" ~a)" (car lib) (format-string-list (cdr lib)))
(and prune-undefined? (ffi-lib (car lib) (cdr lib))))]))
(define ffi-map (apply format-ffi-obj-map ffi-data library-name ffi-lib-obj headers))
(dispatch file ffi-name library-name ffi-library headers ffi-map))
(define (create-mapped-static-ffi #:prune-undefined? [prune-undefined? #f]
ffi-data file ffi-name lib . headers)
(create-static-ffi-generic export-mapped-ffi ffi-data prune-undefined?
file ffi-name lib headers))
(define (create-static-ffi #:prune-undefined? [prune-undefined? #f]
ffi-data file ffi-name lib . headers)
(create-static-ffi-generic export-ffi ffi-data prune-undefined?
file ffi-name lib headers))
;; The generate ffi functions are the only user-facing export functions
;; provided by dynamic-ffi/unsafe. These functions take only the
desired ffi name , the lib file , and the header files , and invoke
;; dffi:dynamic-ffi-parse themselves to export a static ffi.
(define (generate-mapped-static-ffi #:prune-undefined? [prune-undefined? #f]
ffi-name file lib-path . headers)
(define ffi-data (apply dffi:dynamic-ffi-parse headers))
(apply create-mapped-static-ffi ffi-data file ffi-name lib-path headers
#:prune-undefined? prune-undefined?))
(define (generate-static-ffi #:prune-undefined? [prune-undefined? #f]
ffi-name file lib-path . headers)
(define ffi-data (apply dffi:dynamic-ffi-parse headers))
(apply create-static-ffi ffi-data file ffi-name lib-path headers
#:prune-undefined? prune-undefined?))
| null | https://raw.githubusercontent.com/dbenoit17/dynamic-ffi/c82f5cb25932e9cab31844569b1364e23a02f205/export.rkt | racket | This module provides functions for exporting
all pointers opaque for now to
prevent type conflicts
would be cool to do it this way
[else (_cpointer (format-dffi-obj pointee))]))
This is equivalent to build-ffi-obj-map in ffi.rkt,
except it produces racket source code instead
of runtime ffi objects.
ffi-lib-obj is either #f or a foreign-library value where #f means
don't check whether a symbol is defined.
NOTE: use _byte as a dummy type which will return a Racket integer
when the symbol exists, #f otherwise
The following functions feel ambiguously named to me, so I'll
document their exact usage in more detail.
The export ffi functions are the core exporting functions
They take a formatted ffi map produced by format-ffi-obj-map
and export an ffi to an output file
dffi:dynamic-ffi-parse, format the data for export, and wrap the export
in a routine and used by other functions than just export.
define-dynamic-ffi/cached in cached.rkt is an example of this.
The generate ffi functions are the only user-facing export functions
provided by dynamic-ffi/unsafe. These functions take only the
dffi:dynamic-ffi-parse themselves to export a static ffi. | FFI bindings as shippable racket files .
#lang racket/base
(require
racket/string
racket/port
racket/runtime-path
racket/contract
(only-in ffi/unsafe ffi-lib _byte get-ffi-obj)
(for-syntax racket/base)
(prefix-in dffi: "meta.rkt"))
(provide
create-mapped-static-ffi
create-static-ffi
(contract-out
[generate-static-ffi
(->* ((or/c string? symbol?)
(or/c string? path?)
(or/c string? path? (listof string?)))
(#:prune-undefined? any/c)
#:rest (listof (or/c string? path?))
any)]
[generate-mapped-static-ffi
(->* ((or/c string? symbol?)
(or/c string? path?)
(or/c string? path? (listof string?)))
(#:prune-undefined? any/c)
#:rest (listof (or/c string? path?))
any)]))
(define-runtime-path mapped-ffi-template-path
(build-path "template-files" "mapped-ffi-template"))
(define-runtime-path defined-ffi-template-path
(build-path "template-files" "defined-ffi-template"))
(define (format-list l)
(format "(list ~a)"
(string-join
(for/list ([e l])
(format "~a" e)))))
(define (format-string-list l)
(format "(list ~a)"
(string-join
(for/list ([e l])
(format "\"~a\"" e)))))
(define (format-ffi-int ct-int)
(define width (dffi:ctype-width ct-int))
(unless (and (modulo width 8) (<= width 64) (>= width 0))
(error "incompatible int width: " width))
(define ints (vector '_int8 '_int16 '_int32 '_int64))
(define uints (vector '_uint8 '_uint16 '_uint32 '_uint64))
(define category
(if (dffi:ctype-int-signed? ct-int) ints uints))
(define index (- (inexact->exact (log width 2)) 3))
(vector-ref category index))
(define (format-ffi-float ct-float)
(define width (dffi:ctype-width ct-float))
(cond [(eq? width 32) '_float]
[(eq? width 64) '_double*]
[(eq? width 80) '_longdouble]
[(eq? width 128) '_longdouble]
[else (error "incompatible float width: " width)]))
(define (format-ffi-pointer ct-pointer)
(define pointee (dffi:ctype-pointer->pointee ct-pointer))
(cond [(dffi:ctype-void? pointee) '_pointer]
[(and (dffi:ctype-int? pointee)
(eq? (dffi:ctype-width pointee) 8))
'_string]
[else '_pointer]))
(define (format-ffi-array ct-array)
(define element (dffi:ctype-array-element ct-array))
(format "(make-array-type ~a ~a)"
(format-dffi-obj element)
(quotient (dffi:ctype-width ct-array)
(dffi:ctype-width element))))
(define (format-ffi-struct ct-struct)
(define struct-members
(for/list ([mem (dffi:ctype-record-members ct-struct)])
(format-dffi-obj mem)))
( define member - names ( dffi : ctype - record - members ct - struct ) )
(if (null? struct-members) #f
(format "(apply _list-struct ~a)" (format-list struct-members))))
(define (format-ffi-union ct-union)
(define union-members
(for/list ([mem (dffi:ctype-record-members ct-union)])
(format-dffi-obj mem)))
(if (null? union-members) #f
(format "(apply _union ~a)" (format-list union-members))))
(define (format-ffi-function ct-function)
(define params
(for/list ([param (dffi:ctype-function-params ct-function)])
(format-dffi-obj param)))
(define maybe-return (dffi:ctype-function-return ct-function))
(define return
(if (dffi:ctype-void? maybe-return)
'_void
(format-dffi-obj maybe-return)))
(format "(_cprocedure ~a ~a)" (format-list params) return))
(define (format-dffi-obj ct)
(unless (dffi:ctype? ct)
(error "expected dynamic-ffi ctype"))
(cond
[(dffi:ctype-int? ct) (format-ffi-int ct)]
[(dffi:ctype-pointer? ct) (format-ffi-pointer ct)]
[(dffi:ctype-float? ct) (format-ffi-float ct)]
[(dffi:ctype-struct? ct) (format-ffi-struct ct)]
[(dffi:ctype-union? ct) (format-ffi-union ct)]
[(dffi:ctype-array? ct) (format-ffi-array ct)]
[(dffi:ctype-function? ct) (format-ffi-function ct)]
[(dffi:ctype-void? ct)
(error "void only allowed as pointer or function return")]
[else (error "unimplemented type")]))
(define (format-ffi-obj-map ffi-data lib ffi-lib-obj . headers)
(define pairs
(for/list ([decl ffi-data])
(define name (dffi:declaration-name decl))
(define type (dffi:declaration-type decl))
(define ffi-obj
(cond [(dffi:enum-decl? decl)
(format "~a" (dffi:declaration-literal-value decl))]
[(or (dffi:record-decl? decl)
(dffi:typedef-decl? decl))
(format-dffi-obj type)]
[(or (dffi:function-decl? decl)
(dffi:var-decl? decl))
(cond
[(or (not ffi-lib-obj)
(get-ffi-obj (string->symbol name) ffi-lib-obj _byte (λ () #f)))
(format "(get-ffi-obj '~a ~a\n ~a \n (warn-undefined-symbol '~a))"
name lib (format-dffi-obj type) name)]
[else
(eprintf "warning: ~a is undefined\n" name)
#f])]
[else
(eprintf "warning: unimplemented delcaration type: ~a\n" decl)
#f]))
(cons (string->symbol name) ffi-obj)))
(make-hash (filter (λ (x) (cdr x)) pairs)))
(define (export-mapped-ffi file ffi-name library-name lib headers ffi-map)
(define template-port (open-input-file mapped-ffi-template-path))
(define template (port->string template-port))
(define formatted-pairs
(format "(make-hash\n ~a)"
(format-list
(for/list ([pr (filter (λ (x) (cdr x)) (hash->list ffi-map))])
(format "\n (cons '~a\n ~a)" (car pr) (cdr pr))))))
(close-input-port template-port)
(with-output-to-file file #:exists 'replace
(λ () (printf template
library-name lib ffi-name (format-string-list headers)
ffi-name formatted-pairs ffi-name))))
(define (export-ffi file ffi-name library-name lib headers ffi-map)
(define template-port (open-input-file defined-ffi-template-path))
(define template (port->string template-port))
(define formatted-definitions
(string-join
(for/list ([pr (filter (λ (x) (cdr x)) (hash->list ffi-map))])
(format "(define ~a-~a\n ~a)\n\n" ffi-name (car pr) (cdr pr)))
""))
(close-input-port template-port)
(with-output-to-file file #:exists 'replace
(λ () (printf template
library-name lib ffi-name (format-string-list headers)
ffi-name formatted-definitions))))
The create ffi functions take unformatted ffi metadata produced by
ffi functions . These are useful when ffi - data is generated earlier
(define (create-static-ffi-generic dispatch ffi-data prune-undefined?
file ffi-name lib headers)
(define library-name (format "~a-ffi-lib" ffi-name))
(define-values (ffi-library ffi-lib-obj)
(cond [(or (string? lib) (path? lib))
(values (format "(ffi-lib \"~a\")" lib)
(and prune-undefined? (ffi-lib lib)))]
[(pair? lib)
(values (format "(ffi-lib \"~a\" ~a)" (car lib) (format-string-list (cdr lib)))
(and prune-undefined? (ffi-lib (car lib) (cdr lib))))]))
(define ffi-map (apply format-ffi-obj-map ffi-data library-name ffi-lib-obj headers))
(dispatch file ffi-name library-name ffi-library headers ffi-map))
(define (create-mapped-static-ffi #:prune-undefined? [prune-undefined? #f]
ffi-data file ffi-name lib . headers)
(create-static-ffi-generic export-mapped-ffi ffi-data prune-undefined?
file ffi-name lib headers))
(define (create-static-ffi #:prune-undefined? [prune-undefined? #f]
ffi-data file ffi-name lib . headers)
(create-static-ffi-generic export-ffi ffi-data prune-undefined?
file ffi-name lib headers))
desired ffi name , the lib file , and the header files , and invoke
(define (generate-mapped-static-ffi #:prune-undefined? [prune-undefined? #f]
ffi-name file lib-path . headers)
(define ffi-data (apply dffi:dynamic-ffi-parse headers))
(apply create-mapped-static-ffi ffi-data file ffi-name lib-path headers
#:prune-undefined? prune-undefined?))
(define (generate-static-ffi #:prune-undefined? [prune-undefined? #f]
ffi-name file lib-path . headers)
(define ffi-data (apply dffi:dynamic-ffi-parse headers))
(apply create-static-ffi ffi-data file ffi-name lib-path headers
#:prune-undefined? prune-undefined?))
|
bc275c6623b77508142f5a0594390a36044d4e84b8204d1227054f50ec412c37 | yetibot/yetibot | http_status.clj | (ns yetibot.commands.http-status
(:require
[yetibot.core.hooks :refer [cmd-hook]]))
(defn status-code
"http <code> # look up http status code"
{:yb/cat #{:fun :img}}
[{code :match}]
(format "" code))
(cmd-hook #"http"
#"^\w+$" status-code)
| null | https://raw.githubusercontent.com/yetibot/yetibot/2fb5c1182b1a53ab0e433d6bab2775ebd43367de/src/yetibot/commands/http_status.clj | clojure | (ns yetibot.commands.http-status
(:require
[yetibot.core.hooks :refer [cmd-hook]]))
(defn status-code
"http <code> # look up http status code"
{:yb/cat #{:fun :img}}
[{code :match}]
(format "" code))
(cmd-hook #"http"
#"^\w+$" status-code)
| |
3a08466cb60f263415f71d1e87fb1759e8dbb9ee0518c13614ea71fe7b894054 | rmculpepper/racket-http123 | test2.rkt | Copyright 2021
SPDX - License - Identifier : Apache-2.0
#lang racket/base
(require (for-syntax racket/base)
racket/match
racket/class
syntax/srcloc
rackunit
http123
http123/private/http2
http123/private/h2-frame
http123/private/hpack)
;; Test various error conditions for HTTP/2 actual connections using a
;; fake server that sends scripted sequences of frames.
(define TEST-TIMEOUT? #f)
(define prelude
(make-parameter
(list (frame type:SETTINGS 0 0 (fp:settings null))
(frame type:SETTINGS 1 0 (fp:settings null))
'sleep)))
;; An Action is Frame | 'sleep | Real | ???.
(define (make-server actions server-in server-out)
(thread
(lambda ()
(parameterize ((current-output-port server-out))
(for ([action (append (prelude) actions)])
(match action
[(? frame? fr)
(write-frame server-out fr)
(flush-output server-out)]
[(list 'buggy (? exact-integer? adjustlen) (? frame? fr))
(buggy-write-frame server-out fr adjustlen)
(flush-output server-out)]
[(? real? t) (sleep t)]
['sleep (sleep 0.02)]))
(close-output-port server-out)
(close-input-port server-in)))))
(define (buggy-write-frame out fr adjustlen)
(match-define (frame type flags streamid payload) fr)
(write-frame-header out (+ adjustlen (payload-length flags payload)) type flags streamid)
(write-frame-payload out flags payload))
(define (setup actions)
(define-values (server-in out-to-server) (make-pipe))
(define-values (client-in out-to-client) (make-pipe))
(define server (make-server actions server-in out-to-client))
(new http2-actual-connection% (in client-in) (out out-to-server) (parent #f)))
(begin-for-syntax
(define ((make-test-case-wrapper proc-id) stx)
(syntax-case stx ()
[(_ arg ...)
#`(test-case (source-location->string (quote-syntax #,stx))
(#,proc-id arg ...))])))
;; ============================================================
;; Error tests
(define (run-expects expects e)
(for ([expect expects])
(match expect
['raise (raise e)]
[(? regexp?) (check regexp-match? expect (exn-message e))]
[(? hash?) (for ([(expkey expval) (in-hash expect)])
(check-equal? (hash-ref (exn:fail:http123-info e) expkey #f)
expval))])))
(define (test1e* expects actions)
(define ac (setup actions))
(define r1 (send ac open-request (request 'GET "" null #f)))
(check-exn (lambda (e) (run-expects expects e))
(lambda () ((sync r1)))))
(define-syntax test1e (make-test-case-wrapper #'test1e*))
(define (test1ok* proc actions)
(define ac (setup actions))
(define r1 (send ac open-request (request 'GET "" null #f)))
(void (proc ((sync r1)))))
(define-syntax test1ok (make-test-case-wrapper #'test1ok*))
(define conn-err (hasheq 'code 'ua-connection-error 'version 'http/2))
(define conn-proto-err (hash-set conn-err 'http2-error 'PROTOCOL_ERROR))
(define stream-err (hasheq 'code 'ua-stream-error 'version 'http/2))
(define stream-proto-err (hash-set stream-err 'http2-error 'PROTOCOL_ERROR))
;; ----------------------------------------
;; from http2.rkt:
;; handle-frame-or-other:
(test1e (list #rx"frame size error")
(list (frame type:DATA 0 3 (fp:data 0 (make-bytes (add1 DEFAULT-MAX-FRAME-SIZE))))))
(test1e (list #rx"bad padding")
(list (list 'buggy -50 (frame type:DATA flag:PADDED 3 (fp:data 100 #"")))))
;; get-stream:
(test1e (list #rx"reference to stream 0" conn-proto-err)
(list (frame type:HEADERS flag:END_HEADERS 0 (fp:headers #f #f #f #""))))
(test1e (list #rx"unknown stream" conn-err (hasheq 'http2-error 'STREAM_CLOSED))
(list (frame type:DATA 0 99 (fp:data 0 #"abc"))))
;; handle-frame:
(test1e (list #rx"expected CONTINUATION frame" conn-proto-err)
(list (frame type:HEADERS 0 3 (fp:headers #f #f #f #""))
(frame type:DATA 0 3 (fp:data 0 #"abc"))))
;; handle-multipart-frame:
(test1e (list #rx"error decoding header" conn-err
(hasheq 'received 'yes 'http2-error 'COMPRESSION_ERROR))
(list (frame type:HEADERS flag:END_HEADERS 3 (fp:headers #f #f #f #"bad"))))
;; handle-frame:
(test1e (list #rx"requires stream 0" conn-proto-err)
(list (frame type:PING 0 3 (fp:ping (make-bytes 8 0)))))
(test1e (list #rx"requires stream 0" conn-proto-err)
(list (frame type:GOAWAY 0 3 (fp:goaway 3 error:NO_ERROR #"bye"))))
(test1e (list #rx"reference to stream 0" conn-proto-err)
(list (frame type:DATA 0 0 (fp:data 0 #"abc"))))
(test1e (list #rx"non-empty SETTINGS ack" conn-err (hasheq 'http2-error 'FRAME_SIZE_ERROR))
(list (frame type:SETTINGS flag:ACK 0 (fp:settings (list (setting 'enable-push 0))))))
(test1e (list #rx"unexpected SETTINGS ack" conn-proto-err)
(list (frame type:SETTINGS flag:ACK 0 (fp:settings (list)))))
(test1e (list #rx"push not enabled" conn-proto-err)
(list (frame type:PUSH_PROMISE flag:END_HEADERS 3 (fp:push_promise 0 6 #""))))
(test1e (list #rx"unexpected CONTINUATION frame" conn-proto-err)
(list (frame type:CONTINUATION 0 3 (fp:continuation #""))))
;; handle-settings:
(test1e (list #rx"bad enable_push value" conn-proto-err)
(list (frame type:SETTINGS 0 0 (fp:settings (list (setting 'enable-push 99))))))
(test1e (list #rx"window too large" conn-err (hasheq 'http2-error 'FLOW_CONTROL_ERROR))
(list (frame type:SETTINGS 0 0
(fp:settings (list (setting 'initial-window-size (sub1 (expt 2 32))))))))
;; adjust-out-flow-window:
(test1e (list #rx"window too large" conn-err (hasheq 'http2-error 'FLOW_CONTROL_ERROR))
(list (frame type:WINDOW_UPDATE 0 0 (fp:window_update (sub1 (expt 2 31))))))
;; timeout
(when TEST-TIMEOUT?
(test1e (list #rx"connection closed by user agent \\(timeout\\)"
(hasheq 'code 'ua-timeout))
(list 60))
(test1e (list 'raise #rx"connection closed by server (RST_STREAM)"
(hasheq 'code 'server-reset-stream 'http2-error 'NO_ERROR))
(list 12 (frame type:PING flag:ACK 0 (fp:ping (make-bytes 8 0)))
10 (frame type:RST_STREAM 0 3 (fp:rst_stream error:NO_ERROR)))))
;; ----------------------------------------
;; from h2-stream:
;; adjust-out-flow-window:
(test1e (list stream-err (hasheq 'http2-error 'FLOW_CONTROL_ERROR))
(list (frame type:WINDOW_UPDATE 0 3 (fp:window_update (sub1 (expt 2 31))))))
;; check-state:
FIXME
;; handle-user-abort:
FIXME
;; make-header-promise:
(define (new-dt) (make-dtable 4096))
(define (mkheaders hs) (fp:headers #f #f #f (encode-header hs (new-dt))))
(test1e (list #rx"bad or missing status from server")
(list (frame type:HEADERS flag:END_HEADERS 3 (mkheaders '((#"bad key" #"value"))))))
(test1e (list #rx"error processing header")
(list (frame type:HEADERS flag:END_HEADERS 3
(mkheaders '((#":status" #"200") (#"bad key" #"value"))))))
(test1ok (lambda (r) 'ok)
(list (frame type:HEADERS (+ flag:END_STREAM flag:END_HEADERS) 3
(mkheaders '((#":status" #"200" never-add) (#"key" #"value" never-add))))))
;; pstate-base% bad-tx:
(test1e (list #rx"unexpected DATA frame"
stream-proto-err)
(list (frame type:DATA 0 3 (fp:data 0 #"abc"))))
;; pstate-base% handle-rst_stream:
(test1e (list #rx"stream closed by server \\(RST_STREAM\\)"
(hasheq 'version 'http/2 'code 'server-reset-stream 'received 'unknown
'http2-error 'ENHANCE_YOUR_CALM))
(list (frame type:RST_STREAM 0 3 (fp:rst_stream error:ENHANCE_YOUR_CALM))))
(test1e (list #rx"stream closed by server \\(RST_STREAM\\)"
(hasheq 'version 'http/2 'code 'server-reset-stream 'received 'unknown
'http2-error 'CONNECT_ERROR))
(list (frame type:RST_STREAM 0 3 (fp:rst_stream error:CONNECT_ERROR))))
(test1e (list #rx"connection closed by server \\(GOAWAY\\)"
(hasheq 'version 'http/2 'code 'server-closed 'received 'no 'http2-error 'NO_ERROR))
(list (frame type:GOAWAY 0 0 (fp:goaway 1 error:NO_ERROR #"bye"))))
(test1e (list #rx"connection closed by server \\(EOF\\)"
(hasheq 'code 'server-EOF 'received 'unknown 'version 'http/2))
(list))
(test1e (list #rx"connection closed by server \\(EOF\\)"
(hasheq 'code 'server-EOF 'received 'unknown 'version 'http/2))
Note : last - streamid = 3 means stream 3 wo n't get the GOAWAY .
(list (frame type:GOAWAY 0 0 (fp:goaway 3 error:NO_ERROR #"bye"))))
;; expect-header-pstate%:
(test1e (list #rx"bad or missing status"
(hasheq 'version 'http/2 'code 'bad-status 'received 'yes))
(list (frame type:HEADERS flag:END_HEADERS 3 (mkheaders null))))
(test1e (list #rx"bad or missing status"
(hasheq 'version 'http/2 'code 'bad-status 'received 'yes))
(list (frame type:HEADERS flag:END_HEADERS 3 (mkheaders '((#":status" #"fine"))))))
(test1e (list #rx"bad or missing status"
(hasheq 'version 'http/2 'code 'bad-status 'received 'yes))
(list (frame type:HEADERS flag:END_HEADERS 3 (mkheaders '((#":status" #"892"))))))
;; reading-response-pstate%
FIXME
;; ============================================================
;; Error tests for errors sending data
(define (test1de* expects actions #:data data)
(define ac (setup actions))
(define r (send ac open-request (request 'GET "" null data)))
(check-exn (lambda (e) (run-expects expects e))
(lambda () ((sync r)))))
(define-syntax test1de (make-test-case-wrapper #'test1de*))
(test1de (list #rx"request canceled by exception from data procedure"
stream-err (hasheq 'http2-error 'CANCEL 'received 'unknown))
(list)
#:data (lambda (put)
(put #"hello")
(error 'nevermind)))
;; ============================================================
(define (test1r* hh actions #:data [data #f])
(define ac (setup actions))
(define r ((sync (send ac open-request (request 'GET "/" null data)))))
r)
(define-syntax test1r (make-test-case-wrapper #'test1r*))
| null | https://raw.githubusercontent.com/rmculpepper/racket-http123/313fecf225bf74d8a9a006601048ab76446b800b/http123/tests/test2.rkt | racket | Test various error conditions for HTTP/2 actual connections using a
fake server that sends scripted sequences of frames.
An Action is Frame | 'sleep | Real | ???.
============================================================
Error tests
----------------------------------------
from http2.rkt:
handle-frame-or-other:
get-stream:
handle-frame:
handle-multipart-frame:
handle-frame:
handle-settings:
adjust-out-flow-window:
timeout
----------------------------------------
from h2-stream:
adjust-out-flow-window:
check-state:
handle-user-abort:
make-header-promise:
pstate-base% bad-tx:
pstate-base% handle-rst_stream:
expect-header-pstate%:
reading-response-pstate%
============================================================
Error tests for errors sending data
============================================================ | Copyright 2021
SPDX - License - Identifier : Apache-2.0
#lang racket/base
(require (for-syntax racket/base)
racket/match
racket/class
syntax/srcloc
rackunit
http123
http123/private/http2
http123/private/h2-frame
http123/private/hpack)
(define TEST-TIMEOUT? #f)
(define prelude
(make-parameter
(list (frame type:SETTINGS 0 0 (fp:settings null))
(frame type:SETTINGS 1 0 (fp:settings null))
'sleep)))
(define (make-server actions server-in server-out)
(thread
(lambda ()
(parameterize ((current-output-port server-out))
(for ([action (append (prelude) actions)])
(match action
[(? frame? fr)
(write-frame server-out fr)
(flush-output server-out)]
[(list 'buggy (? exact-integer? adjustlen) (? frame? fr))
(buggy-write-frame server-out fr adjustlen)
(flush-output server-out)]
[(? real? t) (sleep t)]
['sleep (sleep 0.02)]))
(close-output-port server-out)
(close-input-port server-in)))))
(define (buggy-write-frame out fr adjustlen)
(match-define (frame type flags streamid payload) fr)
(write-frame-header out (+ adjustlen (payload-length flags payload)) type flags streamid)
(write-frame-payload out flags payload))
(define (setup actions)
(define-values (server-in out-to-server) (make-pipe))
(define-values (client-in out-to-client) (make-pipe))
(define server (make-server actions server-in out-to-client))
(new http2-actual-connection% (in client-in) (out out-to-server) (parent #f)))
(begin-for-syntax
(define ((make-test-case-wrapper proc-id) stx)
(syntax-case stx ()
[(_ arg ...)
#`(test-case (source-location->string (quote-syntax #,stx))
(#,proc-id arg ...))])))
(define (run-expects expects e)
(for ([expect expects])
(match expect
['raise (raise e)]
[(? regexp?) (check regexp-match? expect (exn-message e))]
[(? hash?) (for ([(expkey expval) (in-hash expect)])
(check-equal? (hash-ref (exn:fail:http123-info e) expkey #f)
expval))])))
(define (test1e* expects actions)
(define ac (setup actions))
(define r1 (send ac open-request (request 'GET "" null #f)))
(check-exn (lambda (e) (run-expects expects e))
(lambda () ((sync r1)))))
(define-syntax test1e (make-test-case-wrapper #'test1e*))
(define (test1ok* proc actions)
(define ac (setup actions))
(define r1 (send ac open-request (request 'GET "" null #f)))
(void (proc ((sync r1)))))
(define-syntax test1ok (make-test-case-wrapper #'test1ok*))
(define conn-err (hasheq 'code 'ua-connection-error 'version 'http/2))
(define conn-proto-err (hash-set conn-err 'http2-error 'PROTOCOL_ERROR))
(define stream-err (hasheq 'code 'ua-stream-error 'version 'http/2))
(define stream-proto-err (hash-set stream-err 'http2-error 'PROTOCOL_ERROR))
(test1e (list #rx"frame size error")
(list (frame type:DATA 0 3 (fp:data 0 (make-bytes (add1 DEFAULT-MAX-FRAME-SIZE))))))
(test1e (list #rx"bad padding")
(list (list 'buggy -50 (frame type:DATA flag:PADDED 3 (fp:data 100 #"")))))
(test1e (list #rx"reference to stream 0" conn-proto-err)
(list (frame type:HEADERS flag:END_HEADERS 0 (fp:headers #f #f #f #""))))
(test1e (list #rx"unknown stream" conn-err (hasheq 'http2-error 'STREAM_CLOSED))
(list (frame type:DATA 0 99 (fp:data 0 #"abc"))))
(test1e (list #rx"expected CONTINUATION frame" conn-proto-err)
(list (frame type:HEADERS 0 3 (fp:headers #f #f #f #""))
(frame type:DATA 0 3 (fp:data 0 #"abc"))))
(test1e (list #rx"error decoding header" conn-err
(hasheq 'received 'yes 'http2-error 'COMPRESSION_ERROR))
(list (frame type:HEADERS flag:END_HEADERS 3 (fp:headers #f #f #f #"bad"))))
(test1e (list #rx"requires stream 0" conn-proto-err)
(list (frame type:PING 0 3 (fp:ping (make-bytes 8 0)))))
(test1e (list #rx"requires stream 0" conn-proto-err)
(list (frame type:GOAWAY 0 3 (fp:goaway 3 error:NO_ERROR #"bye"))))
(test1e (list #rx"reference to stream 0" conn-proto-err)
(list (frame type:DATA 0 0 (fp:data 0 #"abc"))))
(test1e (list #rx"non-empty SETTINGS ack" conn-err (hasheq 'http2-error 'FRAME_SIZE_ERROR))
(list (frame type:SETTINGS flag:ACK 0 (fp:settings (list (setting 'enable-push 0))))))
(test1e (list #rx"unexpected SETTINGS ack" conn-proto-err)
(list (frame type:SETTINGS flag:ACK 0 (fp:settings (list)))))
(test1e (list #rx"push not enabled" conn-proto-err)
(list (frame type:PUSH_PROMISE flag:END_HEADERS 3 (fp:push_promise 0 6 #""))))
(test1e (list #rx"unexpected CONTINUATION frame" conn-proto-err)
(list (frame type:CONTINUATION 0 3 (fp:continuation #""))))
(test1e (list #rx"bad enable_push value" conn-proto-err)
(list (frame type:SETTINGS 0 0 (fp:settings (list (setting 'enable-push 99))))))
(test1e (list #rx"window too large" conn-err (hasheq 'http2-error 'FLOW_CONTROL_ERROR))
(list (frame type:SETTINGS 0 0
(fp:settings (list (setting 'initial-window-size (sub1 (expt 2 32))))))))
(test1e (list #rx"window too large" conn-err (hasheq 'http2-error 'FLOW_CONTROL_ERROR))
(list (frame type:WINDOW_UPDATE 0 0 (fp:window_update (sub1 (expt 2 31))))))
(when TEST-TIMEOUT?
(test1e (list #rx"connection closed by user agent \\(timeout\\)"
(hasheq 'code 'ua-timeout))
(list 60))
(test1e (list 'raise #rx"connection closed by server (RST_STREAM)"
(hasheq 'code 'server-reset-stream 'http2-error 'NO_ERROR))
(list 12 (frame type:PING flag:ACK 0 (fp:ping (make-bytes 8 0)))
10 (frame type:RST_STREAM 0 3 (fp:rst_stream error:NO_ERROR)))))
(test1e (list stream-err (hasheq 'http2-error 'FLOW_CONTROL_ERROR))
(list (frame type:WINDOW_UPDATE 0 3 (fp:window_update (sub1 (expt 2 31))))))
FIXME
FIXME
(define (new-dt) (make-dtable 4096))
(define (mkheaders hs) (fp:headers #f #f #f (encode-header hs (new-dt))))
(test1e (list #rx"bad or missing status from server")
(list (frame type:HEADERS flag:END_HEADERS 3 (mkheaders '((#"bad key" #"value"))))))
(test1e (list #rx"error processing header")
(list (frame type:HEADERS flag:END_HEADERS 3
(mkheaders '((#":status" #"200") (#"bad key" #"value"))))))
(test1ok (lambda (r) 'ok)
(list (frame type:HEADERS (+ flag:END_STREAM flag:END_HEADERS) 3
(mkheaders '((#":status" #"200" never-add) (#"key" #"value" never-add))))))
(test1e (list #rx"unexpected DATA frame"
stream-proto-err)
(list (frame type:DATA 0 3 (fp:data 0 #"abc"))))
(test1e (list #rx"stream closed by server \\(RST_STREAM\\)"
(hasheq 'version 'http/2 'code 'server-reset-stream 'received 'unknown
'http2-error 'ENHANCE_YOUR_CALM))
(list (frame type:RST_STREAM 0 3 (fp:rst_stream error:ENHANCE_YOUR_CALM))))
(test1e (list #rx"stream closed by server \\(RST_STREAM\\)"
(hasheq 'version 'http/2 'code 'server-reset-stream 'received 'unknown
'http2-error 'CONNECT_ERROR))
(list (frame type:RST_STREAM 0 3 (fp:rst_stream error:CONNECT_ERROR))))
(test1e (list #rx"connection closed by server \\(GOAWAY\\)"
(hasheq 'version 'http/2 'code 'server-closed 'received 'no 'http2-error 'NO_ERROR))
(list (frame type:GOAWAY 0 0 (fp:goaway 1 error:NO_ERROR #"bye"))))
(test1e (list #rx"connection closed by server \\(EOF\\)"
(hasheq 'code 'server-EOF 'received 'unknown 'version 'http/2))
(list))
(test1e (list #rx"connection closed by server \\(EOF\\)"
(hasheq 'code 'server-EOF 'received 'unknown 'version 'http/2))
Note : last - streamid = 3 means stream 3 wo n't get the GOAWAY .
(list (frame type:GOAWAY 0 0 (fp:goaway 3 error:NO_ERROR #"bye"))))
(test1e (list #rx"bad or missing status"
(hasheq 'version 'http/2 'code 'bad-status 'received 'yes))
(list (frame type:HEADERS flag:END_HEADERS 3 (mkheaders null))))
(test1e (list #rx"bad or missing status"
(hasheq 'version 'http/2 'code 'bad-status 'received 'yes))
(list (frame type:HEADERS flag:END_HEADERS 3 (mkheaders '((#":status" #"fine"))))))
(test1e (list #rx"bad or missing status"
(hasheq 'version 'http/2 'code 'bad-status 'received 'yes))
(list (frame type:HEADERS flag:END_HEADERS 3 (mkheaders '((#":status" #"892"))))))
FIXME
(define (test1de* expects actions #:data data)
(define ac (setup actions))
(define r (send ac open-request (request 'GET "" null data)))
(check-exn (lambda (e) (run-expects expects e))
(lambda () ((sync r)))))
(define-syntax test1de (make-test-case-wrapper #'test1de*))
(test1de (list #rx"request canceled by exception from data procedure"
stream-err (hasheq 'http2-error 'CANCEL 'received 'unknown))
(list)
#:data (lambda (put)
(put #"hello")
(error 'nevermind)))
(define (test1r* hh actions #:data [data #f])
(define ac (setup actions))
(define r ((sync (send ac open-request (request 'GET "/" null data)))))
r)
(define-syntax test1r (make-test-case-wrapper #'test1r*))
|
ab96d108ea678e05fb617e245d564d1fb89527bb2b86f7ab66a4ff93eb196584 | metaocaml/ber-metaocaml | genprintval.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. *)
(* *)
(**************************************************************************)
(* Printing of values *)
open Types
open Format
module type OBJ =
sig
type t
val repr : 'a -> t
val obj : t -> 'a
val is_block : t -> bool
val tag : t -> int
val size : t -> int
val field : t -> int -> t
val double_array_tag : int
val double_field : t -> int -> float
end
module type EVALPATH =
sig
type valu
val eval_address: Env.address -> valu
exception Error
val same_value: valu -> valu -> bool
end
type ('a, 'b) gen_printer =
| Zero of 'b
| Succ of ('a -> ('a, 'b) gen_printer)
module type S =
sig
type t
val install_printer :
Path.t -> Types.type_expr -> (formatter -> t -> unit) -> unit
val install_generic_printer :
Path.t -> Path.t ->
(int -> (int -> t -> Outcometree.out_value,
t -> Outcometree.out_value) gen_printer) ->
unit
val install_generic_printer' :
Path.t -> Path.t ->
(formatter -> t -> unit,
formatter -> t -> unit) gen_printer ->
unit
(** [install_generic_printer' function_path constructor_path printer]
function_path is used to remove the printer. *)
val remove_printer : Path.t -> unit
val outval_of_untyped_exception : t -> Outcometree.out_value
val outval_of_value :
int -> int ->
(int -> t -> Types.type_expr -> Outcometree.out_value option) ->
Env.t -> t -> type_expr -> Outcometree.out_value
end
module Make(O : OBJ)(_ : EVALPATH with type valu = O.t) :
(S with type t = O.t)
| null | https://raw.githubusercontent.com/metaocaml/ber-metaocaml/4992d1f87fc08ccb958817926cf9d1d739caf3a2/toplevel/genprintval.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.
************************************************************************
Printing of values
* [install_generic_printer' function_path constructor_path printer]
function_path is used to remove the printer. | , projet Cristal , INRIA Rocquencourt
Copyright 1996 Institut National de Recherche en Informatique et
the GNU Lesser General Public License version 2.1 , with the
open Types
open Format
module type OBJ =
sig
type t
val repr : 'a -> t
val obj : t -> 'a
val is_block : t -> bool
val tag : t -> int
val size : t -> int
val field : t -> int -> t
val double_array_tag : int
val double_field : t -> int -> float
end
module type EVALPATH =
sig
type valu
val eval_address: Env.address -> valu
exception Error
val same_value: valu -> valu -> bool
end
type ('a, 'b) gen_printer =
| Zero of 'b
| Succ of ('a -> ('a, 'b) gen_printer)
module type S =
sig
type t
val install_printer :
Path.t -> Types.type_expr -> (formatter -> t -> unit) -> unit
val install_generic_printer :
Path.t -> Path.t ->
(int -> (int -> t -> Outcometree.out_value,
t -> Outcometree.out_value) gen_printer) ->
unit
val install_generic_printer' :
Path.t -> Path.t ->
(formatter -> t -> unit,
formatter -> t -> unit) gen_printer ->
unit
val remove_printer : Path.t -> unit
val outval_of_untyped_exception : t -> Outcometree.out_value
val outval_of_value :
int -> int ->
(int -> t -> Types.type_expr -> Outcometree.out_value option) ->
Env.t -> t -> type_expr -> Outcometree.out_value
end
module Make(O : OBJ)(_ : EVALPATH with type valu = O.t) :
(S with type t = O.t)
|
06d4cc65c0fc6bf51bb7b703bd261545f95e1f4e55f7835aa78dbe47203f8320 | mjrusso/joy-of-clojure-examples | core.clj | (ns joc.core)
(defn hello-world [name]
(println "Hello, " name))
| null | https://raw.githubusercontent.com/mjrusso/joy-of-clojure-examples/d59fddbb416ff613af63d540d3f1076de0c79bc0/src/joc/core.clj | clojure | (ns joc.core)
(defn hello-world [name]
(println "Hello, " name))
| |
b719a9c41fb5ffbeef500d021abde76d939cbf3706166b9629d99bf728de4e7b | onedata/op-worker | session_offline_test_SUITE.erl | %%%-------------------------------------------------------------------
@author
( C ) 2021 ACK CYFRONET AGH
This software is released under the MIT license
cited in ' LICENSE.txt ' .
%%% @end
%%%-------------------------------------------------------------------
%%% @doc
%%% This file contains tests concerning offline access management.
%%% @end
%%%-------------------------------------------------------------------
-module(session_offline_test_SUITE).
-author("Bartosz Walkowicz").
-include("api_file_test_utils.hrl").
-include("modules/auth/offline_access_manager.hrl").
-include("modules/fslogic/fslogic_common.hrl").
-include("modules/logical_file_manager/lfm.hrl").
-include_lib("cluster_worker/include/graph_sync/graph_sync.hrl").
-export([
all/0,
init_per_suite/1, end_per_suite/1,
init_per_testcase/2, end_per_testcase/2
]).
-export([
offline_session_creation_for_root_should_fail_test/1,
offline_session_creation_for_guest_should_fail_test/1,
offline_session_should_work_as_any_other_session_test/1,
offline_token_should_be_renewed_if_needed_test/1,
offline_session_should_properly_react_to_time_warps_test/1
]).
all() -> [
offline_session_creation_for_root_should_fail_test,
offline_session_creation_for_guest_should_fail_test,
offline_session_should_work_as_any_other_session_test,
offline_token_should_be_renewed_if_needed_test,
offline_session_should_properly_react_to_time_warps_test
].
-define(HOUR, 3600).
-define(DAY, 24 * ?HOUR).
-define(PROVIDER_TOKEN_TTL, 3).
-define(OFFLINE_ACCESS_TOKEN_TTL, 7 * ?DAY).
-define(RAND_JOB_ID(), str_utils:rand_hex(10)).
-define(NODE, hd(oct_background:get_provider_nodes(krakow))).
-define(ATTEMPTS, 30).
%%%===================================================================
%%% Test functions
%%%===================================================================
offline_session_creation_for_root_should_fail_test(_Config) ->
?assertMatch(?ERROR_TOKEN_SUBJECT_INVALID, init_offline_session(?RAND_JOB_ID(), ?ROOT_CREDENTIALS)).
offline_session_creation_for_guest_should_fail_test(_Config) ->
?assertMatch(?ERROR_TOKEN_SUBJECT_INVALID, init_offline_session(?RAND_JOB_ID(), ?GUEST_CREDENTIALS)).
offline_session_should_work_as_any_other_session_test(_Config) ->
JobId = ?RAND_JOB_ID(),
UserId = oct_background:get_user_id(user1),
UserCredentials = get_user_credentials(),
{ok, SessionId} = ?assertMatch({ok, _}, init_offline_session(JobId, UserCredentials)),
SpaceKrkId = oct_background:get_space_id(space_krk),
SpaceKrkGuid = fslogic_file_id:spaceid_to_space_dir_guid(SpaceKrkId),
UserRootDirGuid = fslogic_file_id:user_root_dir_guid(UserId),
{ok, ListedSpaces} = ?assertMatch(
{ok, [_ | _]},
lfm_proxy:get_children(?NODE, SessionId, ?FILE_REF(UserRootDirGuid), 0, 100)
),
{ListedSpacesGuids, _} = lists:unzip(ListedSpaces),
?assert(lists:member(SpaceKrkGuid, ListedSpacesGuids)),
% Check that even in case of various environment situations everything is resolved
% internally and session works properly (possibly after some time though)
lists:foreach(fun(MessUpSthFun) ->
MessUpSthFun(),
?assertMatch(
{ok, #file_attr{guid = SpaceKrkGuid}},
lfm_proxy:stat(?NODE, SessionId, ?FILE_REF(SpaceKrkGuid)),
?ATTEMPTS
)
end, [
fun clear_auth_cache/0,
fun force_oz_connection_restart/0,
fun() -> ozw_test_rpc:simulate_downtime(5) end
]).
offline_token_should_be_renewed_if_needed_test(_Config) ->
JobId = ?RAND_JOB_ID(),
UserCredentials = get_user_credentials(),
{ok, SessionId} = ?assertMatch({ok, _}, init_offline_session(JobId, UserCredentials)),
OfflineCredentials1 = get_session_credentials(SessionId),
% Credentials renew is attempted on call to `offline_access_manager:get_session_id`
but only if at least 1/3 of token TTL has passed
time_test_utils:simulate_seconds_passing(?HOUR),
?assertMatch({ok, SessionId}, get_offline_session_id(JobId)),
?assertEqual(OfflineCredentials1, get_session_credentials(SessionId)),
force_session_validity_check(SessionId),
?assertEqual(true, session_exists(SessionId)),
% After that time token renewal should be attempted. In case of failure
% (e.g. lost connection to oz) old credentials should be returned (they
% would be still valid for some time).
time_test_utils:simulate_seconds_passing(4 * ?DAY),
mock_acquire_offline_user_access_token_failure(),
AssertRenewalFailureFun = fun() ->
?assertMatch({ok, SessionId}, get_offline_session_id(JobId)),
?assertEqual(OfflineCredentials1, get_session_credentials(SessionId))
end,
lists:foreach(fun(BackoffInterval) ->
AssertRenewalFailureFun(),
?assertEqual(1, count_offline_token_acquisition_attempts()),
% Credentials renewal failure sets backoff so that next attempt wouldn't be
% tried immediately
time_test_utils:simulate_seconds_passing(BackoffInterval - 1),
lists:foreach(fun(_) -> AssertRenewalFailureFun() end, lists:seq(1, 100)),
?assertEqual(0, count_offline_token_acquisition_attempts()),
time_test_utils:simulate_seconds_passing(2)
end, get_offline_token_renewal_backoff_Intervals(
?MIN_OFFLINE_TOKEN_RENEWAL_INTERVAL_SEC, []
)),
unmock_acquire_offline_user_access_token_failure(),
% If there are no such failures and backoff interval has passed,
% then token should be properly renewed
time_test_utils:simulate_seconds_passing(?MAX_OFFLINE_TOKEN_RENEWAL_INTERVAL_SEC + 1),
?assertMatch({ok, SessionId}, get_offline_session_id(JobId)),
?assertNotEqual(OfflineCredentials1, get_session_credentials(SessionId)),
force_session_validity_check(SessionId),
?assertEqual(true, session_exists(SessionId)),
ok.
offline_session_should_properly_react_to_time_warps_test(_Config) ->
JobId = ?RAND_JOB_ID(),
UserCredentials = get_user_credentials(),
{ok, SessionId} = ?assertMatch({ok, _}, init_offline_session(JobId, UserCredentials)),
OfflineCredentials1 = get_session_credentials(SessionId),
% Offline session/token shouldn't react to backward time warp as it will
% just extend the token validity period.
time_test_utils:simulate_seconds_passing(-6 * ?DAY),
?assertMatch({ok, SessionId}, get_offline_session_id(JobId)),
?assertEqual(OfflineCredentials1, get_session_credentials(SessionId)),
With previous backward time warp session should still exist even after 8 day passage
( offline_access_token_ttl is set to 7 days by default ) . Also no token renewal should
be performed until 1/3 of token TTL has elapsed after original acquirement timestamp
time_test_utils:simulate_seconds_passing(8 * ?DAY),
?assertMatch({ok, SessionId}, get_offline_session_id(JobId)),
?assertEqual(OfflineCredentials1, get_session_credentials(SessionId)),
% In case of forward time warp token may expire and session may terminate (after some
% time of inertia) but offline credentials docs are not automatically removed - it is
% responsibility of offline job to do so by calling `offline_access_manager:close_session`.
time_test_utils:simulate_seconds_passing(7 * ?DAY),
?assertMatch(?ERROR_TOKEN_CAVEAT_UNVERIFIED(#cv_time{}), get_offline_session_id(JobId)),
force_session_validity_check(SessionId),
?assertEqual(false, session_exists(SessionId), ?ATTEMPTS),
?assert(offline_credentials_exist(JobId)),
% close_session hasn't been called yet, it is still possible to recreate session
% if backward time warp happens
time_test_utils:simulate_seconds_passing(-3 * ?DAY),
?assertMatch({ok, SessionId}, get_offline_session_id(JobId), ?ATTEMPTS),
?assertEqual(true, session_exists(SessionId)),
?assertEqual(true, offline_credentials_exist(JobId)),
% If `close_session` is called the session is terminated and credentials removed even
% if token has not expired yet
close_offline_session(JobId),
?assertEqual(false, session_exists(SessionId), ?ATTEMPTS),
?assertEqual(false, offline_credentials_exist(JobId)),
% After offline session credentials are deleted it should be impossible to
% recreate offline session
?assertMatch(?ERROR_NOT_FOUND, get_offline_session_id(JobId)),
?assertEqual(false, session_exists(SessionId)),
?assertEqual(false, offline_credentials_exist(JobId)),
ok.
%%%===================================================================
%%% Helper functions
%%%===================================================================
@private
-spec get_user_credentials() -> auth_manager:credentials().
get_user_credentials() ->
auth_manager:build_token_credentials(
oct_background:get_user_access_token(user1), undefined,
initializer:local_ip_v4(), oneclient, allow_data_access_caveats
).
@private
-spec init_offline_session(offline_access_manager:offline_job_id(), auth_manager:credentials()) ->
{ok, session:id()} | {error, term()}.
init_offline_session(JobId, UserCredentials) ->
rpc:call(?NODE, offline_access_manager, init_session, [JobId, UserCredentials]).
@private
-spec get_offline_session_id(offline_access_manager:offline_job_id()) ->
{ok, session:id()} | {error, term()}.
get_offline_session_id(JobId) ->
rpc:call(?NODE, offline_access_manager, get_session_id, [JobId]).
@private
-spec close_offline_session(offline_access_manager:offline_job_id()) -> ok.
close_offline_session(JobId) ->
rpc:call(?NODE, offline_access_manager, close_session, [JobId]).
@private
-spec get_session_credentials(session:id()) -> auth_manager:credentials().
get_session_credentials(SessionId) ->
{ok, #document{value = #session{credentials = Credentials}}} = get_session_doc(SessionId),
Credentials.
@private
-spec force_session_validity_check(session:id()) -> ok.
force_session_validity_check(SessionId) ->
{ok, #document{value = #session{watcher = Watcher}}} = get_session_doc(SessionId),
Watcher ! check_session_validity,
ok.
@private
-spec session_exists(session:id()) -> boolean().
session_exists(SessionId) ->
rpc:call(?NODE, session, exists, [SessionId]).
@private
-spec get_session_doc(session:id()) -> {ok, session:doc()} | {error, term()}.
get_session_doc(SessionId) ->
rpc:call(?NODE, session, get, [SessionId]).
@private
-spec offline_credentials_exist(offline_access_credentials:id()) -> boolean().
offline_credentials_exist(JobId) ->
case rpc:call(?NODE, offline_access_credentials, get, [JobId]) of
{ok, _} -> true;
?ERROR_NOT_FOUND -> false
end.
@private
-spec clear_auth_cache() -> ok.
clear_auth_cache() ->
rpc:call(?NODE, ets, delete_all_objects, [auth_cache]).
@private
-spec force_oz_connection_restart() -> ok.
force_oz_connection_restart() ->
rpc:call(?NODE, gs_channel_service, force_restart_connection, []).
@private
-spec mock_verify_token_to_inform_about_consumer_token_used(tokens:serialized()) -> ok.
mock_verify_token_to_inform_about_consumer_token_used(OfflineAccessToken) ->
Self = self(),
test_utils:mock_new(?NODE, token_logic, [passthrough]),
test_utils:mock_expect(?NODE, token_logic, verify_access_token,
fun(AccessToken, ConsumerToken, PeerIp, Interface, DataAccessCaveatsPolicy) ->
case AccessToken == OfflineAccessToken of
true -> Self ! {consumer_token, ConsumerToken};
false -> ok
end,
meck:passthrough([AccessToken, ConsumerToken, PeerIp, Interface, DataAccessCaveatsPolicy])
end
).
@private
-spec unmock_verify_token_to_inform_about_consumer_token_used() -> ok.
unmock_verify_token_to_inform_about_consumer_token_used() ->
test_utils:mock_unload(?NODE, token_logic).
@private
-spec mock_acquire_offline_user_access_token_failure() -> ok.
mock_acquire_offline_user_access_token_failure() ->
Self = self(),
test_utils:mock_new(?NODE, auth_manager, [passthrough]),
test_utils:mock_expect(?NODE, auth_manager, acquire_offline_user_access_token, fun(_) ->
Self ! acquire_offline_access_token,
?ERROR_NO_CONNECTION_TO_ONEZONE
end).
@private
-spec unmock_acquire_offline_user_access_token_failure() -> ok.
unmock_acquire_offline_user_access_token_failure() ->
test_utils:mock_unload(?NODE, auth_manager).
@private
-spec count_offline_token_acquisition_attempts() -> non_neg_integer().
count_offline_token_acquisition_attempts() ->
count_offline_token_acquisition_attempts(0).
@private
-spec count_offline_token_acquisition_attempts(non_neg_integer()) -> non_neg_integer().
count_offline_token_acquisition_attempts(Num) ->
receive acquire_offline_access_token ->
count_offline_token_acquisition_attempts(Num + 1)
after 100 ->
Num
end.
@private
-spec get_offline_token_renewal_backoff_Intervals(time:seconds(), [time:seconds()]) ->
[time:seconds()].
get_offline_token_renewal_backoff_Intervals(?MAX_OFFLINE_TOKEN_RENEWAL_INTERVAL_SEC, Intervals) ->
lists:reverse([
Test 3 times maximum backoff to assert that it will not be increased
% infinitely but will stop at tha value
?MAX_OFFLINE_TOKEN_RENEWAL_INTERVAL_SEC,
?MAX_OFFLINE_TOKEN_RENEWAL_INTERVAL_SEC,
?MAX_OFFLINE_TOKEN_RENEWAL_INTERVAL_SEC
| Intervals]);
get_offline_token_renewal_backoff_Intervals(Interval, Intervals) ->
get_offline_token_renewal_backoff_Intervals(
min(
Interval * ?OFFLINE_TOKEN_RENEWAL_BACKOFF_RATE,
?MAX_OFFLINE_TOKEN_RENEWAL_INTERVAL_SEC
),
[Interval | Intervals]
).
%%%===================================================================
SetUp and TearDown functions
%%%===================================================================
init_per_suite(Config) ->
oct_background:init_per_suite(Config, #onenv_test_config{
onenv_scenario = "1op",
envs = [
{oz_worker, oz_worker, [{offline_access_token_ttl, ?OFFLINE_ACCESS_TOKEN_TTL}]},
{op_worker, op_worker, [
{provider_token_ttl_sec, ?PROVIDER_TOKEN_TTL},
{fuse_session_grace_period_seconds, ?DAY}
]}
]
}).
end_per_suite(_Config) ->
oct_background:end_per_suite().
init_per_testcase(Case, Config) when
Case == offline_token_should_be_renewed_if_needed_test;
Case == offline_session_should_properly_react_to_time_warps_test
->
ok = time_test_utils:freeze_time(Config),
CurrTime = time_test_utils:get_frozen_time_seconds(),
init_per_testcase(?DEFAULT_CASE(Case), [{frozen_time, CurrTime} | Config]);
init_per_testcase(_Case, Config) ->
unmock_acquire_offline_user_access_token_failure(),
ct:timetrap({minutes, 20}),
lfm_proxy:init(Config).
end_per_testcase(offline_session_should_work_as_any_other_session_test = Case, Config) ->
% Await renewal of oz connection (it is teardown as part of test).
?assertMatch(true, rpc:call(?NODE, gs_channel_service, is_connected, []), ?ATTEMPTS),
end_per_testcase(?DEFAULT_CASE(Case), Config);
end_per_testcase(Case, Config) when
Case == offline_token_should_be_renewed_if_needed_test;
Case == offline_session_should_properly_react_to_time_warps_test
->
OriginalTime = ?config(frozen_time, Config),
time_test_utils:set_current_time_seconds(OriginalTime),
ok = time_test_utils:unfreeze_time(Config),
end_per_testcase(?DEFAULT_CASE(Case), Config);
end_per_testcase(_Case, Config) ->
lfm_proxy:teardown(Config).
| null | https://raw.githubusercontent.com/onedata/op-worker/239b30c6510ccf0f2f429dc5c48ecf04d192549a/test_distributed/suites/session/session_offline_test_SUITE.erl | erlang | -------------------------------------------------------------------
@end
-------------------------------------------------------------------
@doc
This file contains tests concerning offline access management.
@end
-------------------------------------------------------------------
===================================================================
Test functions
===================================================================
Check that even in case of various environment situations everything is resolved
internally and session works properly (possibly after some time though)
Credentials renew is attempted on call to `offline_access_manager:get_session_id`
After that time token renewal should be attempted. In case of failure
(e.g. lost connection to oz) old credentials should be returned (they
would be still valid for some time).
Credentials renewal failure sets backoff so that next attempt wouldn't be
tried immediately
If there are no such failures and backoff interval has passed,
then token should be properly renewed
Offline session/token shouldn't react to backward time warp as it will
just extend the token validity period.
In case of forward time warp token may expire and session may terminate (after some
time of inertia) but offline credentials docs are not automatically removed - it is
responsibility of offline job to do so by calling `offline_access_manager:close_session`.
close_session hasn't been called yet, it is still possible to recreate session
if backward time warp happens
If `close_session` is called the session is terminated and credentials removed even
if token has not expired yet
After offline session credentials are deleted it should be impossible to
recreate offline session
===================================================================
Helper functions
===================================================================
infinitely but will stop at tha value
===================================================================
===================================================================
Await renewal of oz connection (it is teardown as part of test). | @author
( C ) 2021 ACK CYFRONET AGH
This software is released under the MIT license
cited in ' LICENSE.txt ' .
-module(session_offline_test_SUITE).
-author("Bartosz Walkowicz").
-include("api_file_test_utils.hrl").
-include("modules/auth/offline_access_manager.hrl").
-include("modules/fslogic/fslogic_common.hrl").
-include("modules/logical_file_manager/lfm.hrl").
-include_lib("cluster_worker/include/graph_sync/graph_sync.hrl").
-export([
all/0,
init_per_suite/1, end_per_suite/1,
init_per_testcase/2, end_per_testcase/2
]).
-export([
offline_session_creation_for_root_should_fail_test/1,
offline_session_creation_for_guest_should_fail_test/1,
offline_session_should_work_as_any_other_session_test/1,
offline_token_should_be_renewed_if_needed_test/1,
offline_session_should_properly_react_to_time_warps_test/1
]).
all() -> [
offline_session_creation_for_root_should_fail_test,
offline_session_creation_for_guest_should_fail_test,
offline_session_should_work_as_any_other_session_test,
offline_token_should_be_renewed_if_needed_test,
offline_session_should_properly_react_to_time_warps_test
].
-define(HOUR, 3600).
-define(DAY, 24 * ?HOUR).
-define(PROVIDER_TOKEN_TTL, 3).
-define(OFFLINE_ACCESS_TOKEN_TTL, 7 * ?DAY).
-define(RAND_JOB_ID(), str_utils:rand_hex(10)).
-define(NODE, hd(oct_background:get_provider_nodes(krakow))).
-define(ATTEMPTS, 30).
offline_session_creation_for_root_should_fail_test(_Config) ->
?assertMatch(?ERROR_TOKEN_SUBJECT_INVALID, init_offline_session(?RAND_JOB_ID(), ?ROOT_CREDENTIALS)).
offline_session_creation_for_guest_should_fail_test(_Config) ->
?assertMatch(?ERROR_TOKEN_SUBJECT_INVALID, init_offline_session(?RAND_JOB_ID(), ?GUEST_CREDENTIALS)).
offline_session_should_work_as_any_other_session_test(_Config) ->
JobId = ?RAND_JOB_ID(),
UserId = oct_background:get_user_id(user1),
UserCredentials = get_user_credentials(),
{ok, SessionId} = ?assertMatch({ok, _}, init_offline_session(JobId, UserCredentials)),
SpaceKrkId = oct_background:get_space_id(space_krk),
SpaceKrkGuid = fslogic_file_id:spaceid_to_space_dir_guid(SpaceKrkId),
UserRootDirGuid = fslogic_file_id:user_root_dir_guid(UserId),
{ok, ListedSpaces} = ?assertMatch(
{ok, [_ | _]},
lfm_proxy:get_children(?NODE, SessionId, ?FILE_REF(UserRootDirGuid), 0, 100)
),
{ListedSpacesGuids, _} = lists:unzip(ListedSpaces),
?assert(lists:member(SpaceKrkGuid, ListedSpacesGuids)),
lists:foreach(fun(MessUpSthFun) ->
MessUpSthFun(),
?assertMatch(
{ok, #file_attr{guid = SpaceKrkGuid}},
lfm_proxy:stat(?NODE, SessionId, ?FILE_REF(SpaceKrkGuid)),
?ATTEMPTS
)
end, [
fun clear_auth_cache/0,
fun force_oz_connection_restart/0,
fun() -> ozw_test_rpc:simulate_downtime(5) end
]).
offline_token_should_be_renewed_if_needed_test(_Config) ->
JobId = ?RAND_JOB_ID(),
UserCredentials = get_user_credentials(),
{ok, SessionId} = ?assertMatch({ok, _}, init_offline_session(JobId, UserCredentials)),
OfflineCredentials1 = get_session_credentials(SessionId),
but only if at least 1/3 of token TTL has passed
time_test_utils:simulate_seconds_passing(?HOUR),
?assertMatch({ok, SessionId}, get_offline_session_id(JobId)),
?assertEqual(OfflineCredentials1, get_session_credentials(SessionId)),
force_session_validity_check(SessionId),
?assertEqual(true, session_exists(SessionId)),
time_test_utils:simulate_seconds_passing(4 * ?DAY),
mock_acquire_offline_user_access_token_failure(),
AssertRenewalFailureFun = fun() ->
?assertMatch({ok, SessionId}, get_offline_session_id(JobId)),
?assertEqual(OfflineCredentials1, get_session_credentials(SessionId))
end,
lists:foreach(fun(BackoffInterval) ->
AssertRenewalFailureFun(),
?assertEqual(1, count_offline_token_acquisition_attempts()),
time_test_utils:simulate_seconds_passing(BackoffInterval - 1),
lists:foreach(fun(_) -> AssertRenewalFailureFun() end, lists:seq(1, 100)),
?assertEqual(0, count_offline_token_acquisition_attempts()),
time_test_utils:simulate_seconds_passing(2)
end, get_offline_token_renewal_backoff_Intervals(
?MIN_OFFLINE_TOKEN_RENEWAL_INTERVAL_SEC, []
)),
unmock_acquire_offline_user_access_token_failure(),
time_test_utils:simulate_seconds_passing(?MAX_OFFLINE_TOKEN_RENEWAL_INTERVAL_SEC + 1),
?assertMatch({ok, SessionId}, get_offline_session_id(JobId)),
?assertNotEqual(OfflineCredentials1, get_session_credentials(SessionId)),
force_session_validity_check(SessionId),
?assertEqual(true, session_exists(SessionId)),
ok.
offline_session_should_properly_react_to_time_warps_test(_Config) ->
JobId = ?RAND_JOB_ID(),
UserCredentials = get_user_credentials(),
{ok, SessionId} = ?assertMatch({ok, _}, init_offline_session(JobId, UserCredentials)),
OfflineCredentials1 = get_session_credentials(SessionId),
time_test_utils:simulate_seconds_passing(-6 * ?DAY),
?assertMatch({ok, SessionId}, get_offline_session_id(JobId)),
?assertEqual(OfflineCredentials1, get_session_credentials(SessionId)),
With previous backward time warp session should still exist even after 8 day passage
( offline_access_token_ttl is set to 7 days by default ) . Also no token renewal should
be performed until 1/3 of token TTL has elapsed after original acquirement timestamp
time_test_utils:simulate_seconds_passing(8 * ?DAY),
?assertMatch({ok, SessionId}, get_offline_session_id(JobId)),
?assertEqual(OfflineCredentials1, get_session_credentials(SessionId)),
time_test_utils:simulate_seconds_passing(7 * ?DAY),
?assertMatch(?ERROR_TOKEN_CAVEAT_UNVERIFIED(#cv_time{}), get_offline_session_id(JobId)),
force_session_validity_check(SessionId),
?assertEqual(false, session_exists(SessionId), ?ATTEMPTS),
?assert(offline_credentials_exist(JobId)),
time_test_utils:simulate_seconds_passing(-3 * ?DAY),
?assertMatch({ok, SessionId}, get_offline_session_id(JobId), ?ATTEMPTS),
?assertEqual(true, session_exists(SessionId)),
?assertEqual(true, offline_credentials_exist(JobId)),
close_offline_session(JobId),
?assertEqual(false, session_exists(SessionId), ?ATTEMPTS),
?assertEqual(false, offline_credentials_exist(JobId)),
?assertMatch(?ERROR_NOT_FOUND, get_offline_session_id(JobId)),
?assertEqual(false, session_exists(SessionId)),
?assertEqual(false, offline_credentials_exist(JobId)),
ok.
@private
-spec get_user_credentials() -> auth_manager:credentials().
get_user_credentials() ->
auth_manager:build_token_credentials(
oct_background:get_user_access_token(user1), undefined,
initializer:local_ip_v4(), oneclient, allow_data_access_caveats
).
@private
-spec init_offline_session(offline_access_manager:offline_job_id(), auth_manager:credentials()) ->
{ok, session:id()} | {error, term()}.
init_offline_session(JobId, UserCredentials) ->
rpc:call(?NODE, offline_access_manager, init_session, [JobId, UserCredentials]).
@private
-spec get_offline_session_id(offline_access_manager:offline_job_id()) ->
{ok, session:id()} | {error, term()}.
get_offline_session_id(JobId) ->
rpc:call(?NODE, offline_access_manager, get_session_id, [JobId]).
@private
-spec close_offline_session(offline_access_manager:offline_job_id()) -> ok.
close_offline_session(JobId) ->
rpc:call(?NODE, offline_access_manager, close_session, [JobId]).
@private
-spec get_session_credentials(session:id()) -> auth_manager:credentials().
get_session_credentials(SessionId) ->
{ok, #document{value = #session{credentials = Credentials}}} = get_session_doc(SessionId),
Credentials.
@private
-spec force_session_validity_check(session:id()) -> ok.
force_session_validity_check(SessionId) ->
{ok, #document{value = #session{watcher = Watcher}}} = get_session_doc(SessionId),
Watcher ! check_session_validity,
ok.
@private
-spec session_exists(session:id()) -> boolean().
session_exists(SessionId) ->
rpc:call(?NODE, session, exists, [SessionId]).
@private
-spec get_session_doc(session:id()) -> {ok, session:doc()} | {error, term()}.
get_session_doc(SessionId) ->
rpc:call(?NODE, session, get, [SessionId]).
@private
-spec offline_credentials_exist(offline_access_credentials:id()) -> boolean().
offline_credentials_exist(JobId) ->
case rpc:call(?NODE, offline_access_credentials, get, [JobId]) of
{ok, _} -> true;
?ERROR_NOT_FOUND -> false
end.
@private
-spec clear_auth_cache() -> ok.
clear_auth_cache() ->
rpc:call(?NODE, ets, delete_all_objects, [auth_cache]).
@private
-spec force_oz_connection_restart() -> ok.
force_oz_connection_restart() ->
rpc:call(?NODE, gs_channel_service, force_restart_connection, []).
@private
-spec mock_verify_token_to_inform_about_consumer_token_used(tokens:serialized()) -> ok.
mock_verify_token_to_inform_about_consumer_token_used(OfflineAccessToken) ->
Self = self(),
test_utils:mock_new(?NODE, token_logic, [passthrough]),
test_utils:mock_expect(?NODE, token_logic, verify_access_token,
fun(AccessToken, ConsumerToken, PeerIp, Interface, DataAccessCaveatsPolicy) ->
case AccessToken == OfflineAccessToken of
true -> Self ! {consumer_token, ConsumerToken};
false -> ok
end,
meck:passthrough([AccessToken, ConsumerToken, PeerIp, Interface, DataAccessCaveatsPolicy])
end
).
@private
-spec unmock_verify_token_to_inform_about_consumer_token_used() -> ok.
unmock_verify_token_to_inform_about_consumer_token_used() ->
test_utils:mock_unload(?NODE, token_logic).
@private
-spec mock_acquire_offline_user_access_token_failure() -> ok.
mock_acquire_offline_user_access_token_failure() ->
Self = self(),
test_utils:mock_new(?NODE, auth_manager, [passthrough]),
test_utils:mock_expect(?NODE, auth_manager, acquire_offline_user_access_token, fun(_) ->
Self ! acquire_offline_access_token,
?ERROR_NO_CONNECTION_TO_ONEZONE
end).
@private
-spec unmock_acquire_offline_user_access_token_failure() -> ok.
unmock_acquire_offline_user_access_token_failure() ->
test_utils:mock_unload(?NODE, auth_manager).
@private
-spec count_offline_token_acquisition_attempts() -> non_neg_integer().
count_offline_token_acquisition_attempts() ->
count_offline_token_acquisition_attempts(0).
@private
-spec count_offline_token_acquisition_attempts(non_neg_integer()) -> non_neg_integer().
count_offline_token_acquisition_attempts(Num) ->
receive acquire_offline_access_token ->
count_offline_token_acquisition_attempts(Num + 1)
after 100 ->
Num
end.
@private
-spec get_offline_token_renewal_backoff_Intervals(time:seconds(), [time:seconds()]) ->
[time:seconds()].
get_offline_token_renewal_backoff_Intervals(?MAX_OFFLINE_TOKEN_RENEWAL_INTERVAL_SEC, Intervals) ->
lists:reverse([
Test 3 times maximum backoff to assert that it will not be increased
?MAX_OFFLINE_TOKEN_RENEWAL_INTERVAL_SEC,
?MAX_OFFLINE_TOKEN_RENEWAL_INTERVAL_SEC,
?MAX_OFFLINE_TOKEN_RENEWAL_INTERVAL_SEC
| Intervals]);
get_offline_token_renewal_backoff_Intervals(Interval, Intervals) ->
get_offline_token_renewal_backoff_Intervals(
min(
Interval * ?OFFLINE_TOKEN_RENEWAL_BACKOFF_RATE,
?MAX_OFFLINE_TOKEN_RENEWAL_INTERVAL_SEC
),
[Interval | Intervals]
).
SetUp and TearDown functions
init_per_suite(Config) ->
oct_background:init_per_suite(Config, #onenv_test_config{
onenv_scenario = "1op",
envs = [
{oz_worker, oz_worker, [{offline_access_token_ttl, ?OFFLINE_ACCESS_TOKEN_TTL}]},
{op_worker, op_worker, [
{provider_token_ttl_sec, ?PROVIDER_TOKEN_TTL},
{fuse_session_grace_period_seconds, ?DAY}
]}
]
}).
end_per_suite(_Config) ->
oct_background:end_per_suite().
init_per_testcase(Case, Config) when
Case == offline_token_should_be_renewed_if_needed_test;
Case == offline_session_should_properly_react_to_time_warps_test
->
ok = time_test_utils:freeze_time(Config),
CurrTime = time_test_utils:get_frozen_time_seconds(),
init_per_testcase(?DEFAULT_CASE(Case), [{frozen_time, CurrTime} | Config]);
init_per_testcase(_Case, Config) ->
unmock_acquire_offline_user_access_token_failure(),
ct:timetrap({minutes, 20}),
lfm_proxy:init(Config).
end_per_testcase(offline_session_should_work_as_any_other_session_test = Case, Config) ->
?assertMatch(true, rpc:call(?NODE, gs_channel_service, is_connected, []), ?ATTEMPTS),
end_per_testcase(?DEFAULT_CASE(Case), Config);
end_per_testcase(Case, Config) when
Case == offline_token_should_be_renewed_if_needed_test;
Case == offline_session_should_properly_react_to_time_warps_test
->
OriginalTime = ?config(frozen_time, Config),
time_test_utils:set_current_time_seconds(OriginalTime),
ok = time_test_utils:unfreeze_time(Config),
end_per_testcase(?DEFAULT_CASE(Case), Config);
end_per_testcase(_Case, Config) ->
lfm_proxy:teardown(Config).
|
022d62c411ccb68fbba410286dc00d3549cbf10e95bff7334d18bf84e0ccd663 | morpheusgraphql/morpheus-graphql | Ext.hs | # LANGUAGE NoImplicitPrelude #
module Data.Morpheus.Internal.Ext
( PushEvents (..),
Result (..),
ResultT (..),
cleanEvents,
resultOr,
mapEvent,
sortErrors,
unsafeFromList,
(<:>),
resolveWith,
runResolutionT,
toEither,
Merge (..),
GQLResult,
)
where
import Data.Mergeable
import Data.Morpheus.Ext.Result
import Data.Morpheus.Internal.Utils
| null | https://raw.githubusercontent.com/morpheusgraphql/morpheus-graphql/1d422eb1c2c40fee1148d236fc848144a0b08e11/morpheus-graphql-core/src/Data/Morpheus/Internal/Ext.hs | haskell | # LANGUAGE NoImplicitPrelude #
module Data.Morpheus.Internal.Ext
( PushEvents (..),
Result (..),
ResultT (..),
cleanEvents,
resultOr,
mapEvent,
sortErrors,
unsafeFromList,
(<:>),
resolveWith,
runResolutionT,
toEither,
Merge (..),
GQLResult,
)
where
import Data.Mergeable
import Data.Morpheus.Ext.Result
import Data.Morpheus.Internal.Utils
| |
998714b1c16e90008af245845abd782a8a8e068666a177ccc9a08c14146639e3 | tov/dssl2 | printer.rkt | #lang racket/base
(provide dssl-print
dssl-fprintf
dssl-printf
dssl-format
dssl-contract-name)
(require "struct.rkt")
(require "object.rkt")
(require "generic.rkt")
(require "errors.rkt")
(require (only-in racket/contract
contract-name
contract?)
(only-in racket/set
mutable-seteq
set-member?
set-add!)
(only-in racket/contract/base contract-name)
(only-in racket/string string-contains?)
(only-in racket/math nan?)
(only-in racket/class is-a?)
(only-in racket/snip snip%))
(define current-printer-state (make-parameter #f))
(define (dssl-contract-name c)
(cond
[(or (boolean? c) (number? c) (string? c) (char? c) (void? c))
(dssl-format "%p" c)]
[else
(contract-name c)]))
(current-dssl-contract-name dssl-contract-name)
(define (dssl-printf fmt . params)
(apply dssl-fprintf (current-output-port) fmt params))
(define (dssl-format fmt . params)
(let ([port (open-output-string)])
(apply dssl-fprintf port fmt params)
(get-output-string port)))
(current-dssl-error-format dssl-format)
(define (dssl-fprintf port fmt . params)
(define parsed-fmt (parse-format-string fmt))
(define expected-params (length (filter symbol? parsed-fmt)))
(define actual-params (length params))
(unless (= expected-params actual-params)
(dssl-error
(string-append
"dssl2-printer: format string did not match number of params\n"
" format string: %p\n"
" expected params: %p\n"
" actual params: %p")
fmt expected-params actual-params))
(let loop ([commands parsed-fmt]
[params params])
(unless (null? commands)
(define command (car commands))
(cond
[(eq? command 'string)
(dssl-display-string (car params) port)
(loop (cdr commands) (cdr params))]
[(eq? command 'debug)
(dssl-print (car params) port #t)
(loop (cdr commands) (cdr params))]
[(eq? command 'print)
(dssl-print (car params) port #f)
(loop (cdr commands) (cdr params))]
[else
(display command port)
(loop (cdr commands) params)]))))
String - > ( List - of ( Or ' debug ' print ' string ) )
(define (parse-format-string s)
(unless (string? s)
(dssl-error "dssl2-printer: bad format string ~s" s))
(for/list ([chunk (in-list (regexp-match* #rx"[^%]+|%.|%$" s))])
(cond
[(string=? chunk "%d") 'debug]
[(string=? chunk "%p") 'print]
[(string=? chunk "%s") 'string]
[(string=? chunk "%%") "%"]
[(regexp-match? #rx"^%" chunk)
(dssl-error "dssl2-printer: bad format string code ~s" chunk)]
[else chunk])))
Dssl2Value ( OutputPort ) - > Void
(define (dssl-display-string value [port (current-output-port)])
(cond
[(or (string? value) (char? value) (symbol? value))
(display value port)]
[(procedure? value)
(display (or (procedure-name value) "#<proc>") port)]
[else (dssl-print value port #f)]))
Dssl2Value ( OutputPort Boolean ) - > Void
(define (dssl-print value0 [port (current-output-port)] [debug? #f])
(parameterize
([current-printer-state (or (current-printer-state)
(cons (mutable-seteq)
(find-cycles value0)))])
(define seen (car (current-printer-state)))
(define cycle-info (cdr (current-printer-state)))
(define (seen!? value)
(define info (hash-ref cycle-info value #false))
(cond
[(set-member? seen value)
(fprintf port "#~a#" info)
#true]
[(number? info)
(set-add! seen value)
(fprintf port "#~a=" info)
#false]
[else
#false]))
(let visit ([value value0])
(cond
[(real? value)
(cond
[(= +inf.0 value) (display "inf" port)]
[(= -inf.0 value) (display "-inf" port)]
[(nan? value) (display "nan" port)]
[else (display value port)])]
[(boolean? value)
(cond
[value (display "True" port)]
[else (display "False" port)])]
[(char? value)
(fprintf port "char(~a)" (char->integer value))]
[(string? value)
(let
([contains-sq (string-contains? value "'")]
[contains-dq (string-contains? value "\"")])
(if (and contains-sq (not contains-dq))
(dssl-debug-string #\" value port)
(dssl-debug-string #\' value port)))]
[(vector? value)
(unless (seen!? value)
(define first #t)
(display #\[ port)
(for ([element (in-vector value)])
(if first
(set! first #f)
(display ", " port))
(visit element))
(display #\] port))]
[(struct-base? value)
(unless (seen!? value)
(write-struct value port visit))]
[(object-base? value)
(unless (seen!? value)
(cond
[(and (not debug?)
(get-method-value/fun value '__print__))
=>
(λ (value.__print__) (value.__print__ (make-print port)))]
[else (write-object value port visit)]))]
[(generic-proc? value)
(fprintf port "#<~a:~a>"
(generic-proc-tag value)
(generic-base-name value))]
[(procedure? value)
(define name (procedure-name value))
(if name
(fprintf port "#<proc:~a>" name)
(fprintf port "#<proc>"))]
[(contract? value)
(fprintf port "#<contract:~a>" (contract-name value))]
[(void? value) (display "None" port)]
[(is-a? value snip%) (display value port)]
[else (display "#<unprintable>" port)]))))
(define (procedure-name value)
(cond
[(contract? value)
(define name (contract-name value))
(if (eq? name '???) #f name)]
[else (object-name value)]))
(define (make-print port)
(λ (fmt . args)
(apply dssl-fprintf port fmt args)))
Dssl2Value - > [ HashEq Dssl2Value [ Or # true Natural ] ]
(define (find-cycles value0)
(define table (make-hasheq))
(define revisited-count 0)
(define (seen!? value)
(define value-info (hash-ref table value #false))
(cond
[(number? value-info) #true]
[value-info
(hash-set! table value revisited-count)
(set! revisited-count (add1 revisited-count))
#true]
[else
(hash-set! table value #true)
#false]))
(define (visit value)
(cond
[(vector? value)
(unless (seen!? value)
(for ([element (in-vector value)])
(visit element)))]
[(struct-base? value)
(unless (seen!? value)
(define info (struct-base-struct-info value))
(for ([field (in-vector (struct-info-field-infos info))])
(visit ((field-info-getter field) value))))]
[(object-base? value)
(unless (seen!? value)
(for ([field-pair (in-vector ((object-base-reflect value)))])
(visit (cdr field-pair))))]))
(visit value0)
table)
(define (dssl-debug-string q str port)
(define (esc c)
(display #\\ port)
(display c port))
(display q port)
(for ([c (in-string str)])
(case c
[(#\\) (esc #\\)]
[(#\007) (esc #\a)]
[(#\backspace) (esc #\b)]
[(#\page) (esc #\f)]
[(#\newline) (esc #\n)]
[(#\return) (esc #\r)]
[(#\tab) (esc #\t)]
[(#\vtab) (esc #\v)]
[(#\space) (display #\space port)]
[else
(cond
[(char=? c q) (esc c)]
[(not (char-graphic? c))
(define hex (format "~x" (char->integer c)))
(fprintf port
(if (= 1 (string-length hex)) "\\x0~a" "\\x~a")
hex)]
[else (display c port)])]))
(display q port))
| null | https://raw.githubusercontent.com/tov/dssl2/e85691b5ea4959feb117f21d96dfe8a1b05afe5c/private/printer.rkt | racket | #lang racket/base
(provide dssl-print
dssl-fprintf
dssl-printf
dssl-format
dssl-contract-name)
(require "struct.rkt")
(require "object.rkt")
(require "generic.rkt")
(require "errors.rkt")
(require (only-in racket/contract
contract-name
contract?)
(only-in racket/set
mutable-seteq
set-member?
set-add!)
(only-in racket/contract/base contract-name)
(only-in racket/string string-contains?)
(only-in racket/math nan?)
(only-in racket/class is-a?)
(only-in racket/snip snip%))
(define current-printer-state (make-parameter #f))
(define (dssl-contract-name c)
(cond
[(or (boolean? c) (number? c) (string? c) (char? c) (void? c))
(dssl-format "%p" c)]
[else
(contract-name c)]))
(current-dssl-contract-name dssl-contract-name)
(define (dssl-printf fmt . params)
(apply dssl-fprintf (current-output-port) fmt params))
(define (dssl-format fmt . params)
(let ([port (open-output-string)])
(apply dssl-fprintf port fmt params)
(get-output-string port)))
(current-dssl-error-format dssl-format)
(define (dssl-fprintf port fmt . params)
(define parsed-fmt (parse-format-string fmt))
(define expected-params (length (filter symbol? parsed-fmt)))
(define actual-params (length params))
(unless (= expected-params actual-params)
(dssl-error
(string-append
"dssl2-printer: format string did not match number of params\n"
" format string: %p\n"
" expected params: %p\n"
" actual params: %p")
fmt expected-params actual-params))
(let loop ([commands parsed-fmt]
[params params])
(unless (null? commands)
(define command (car commands))
(cond
[(eq? command 'string)
(dssl-display-string (car params) port)
(loop (cdr commands) (cdr params))]
[(eq? command 'debug)
(dssl-print (car params) port #t)
(loop (cdr commands) (cdr params))]
[(eq? command 'print)
(dssl-print (car params) port #f)
(loop (cdr commands) (cdr params))]
[else
(display command port)
(loop (cdr commands) params)]))))
String - > ( List - of ( Or ' debug ' print ' string ) )
(define (parse-format-string s)
(unless (string? s)
(dssl-error "dssl2-printer: bad format string ~s" s))
(for/list ([chunk (in-list (regexp-match* #rx"[^%]+|%.|%$" s))])
(cond
[(string=? chunk "%d") 'debug]
[(string=? chunk "%p") 'print]
[(string=? chunk "%s") 'string]
[(string=? chunk "%%") "%"]
[(regexp-match? #rx"^%" chunk)
(dssl-error "dssl2-printer: bad format string code ~s" chunk)]
[else chunk])))
Dssl2Value ( OutputPort ) - > Void
(define (dssl-display-string value [port (current-output-port)])
(cond
[(or (string? value) (char? value) (symbol? value))
(display value port)]
[(procedure? value)
(display (or (procedure-name value) "#<proc>") port)]
[else (dssl-print value port #f)]))
Dssl2Value ( OutputPort Boolean ) - > Void
(define (dssl-print value0 [port (current-output-port)] [debug? #f])
(parameterize
([current-printer-state (or (current-printer-state)
(cons (mutable-seteq)
(find-cycles value0)))])
(define seen (car (current-printer-state)))
(define cycle-info (cdr (current-printer-state)))
(define (seen!? value)
(define info (hash-ref cycle-info value #false))
(cond
[(set-member? seen value)
(fprintf port "#~a#" info)
#true]
[(number? info)
(set-add! seen value)
(fprintf port "#~a=" info)
#false]
[else
#false]))
(let visit ([value value0])
(cond
[(real? value)
(cond
[(= +inf.0 value) (display "inf" port)]
[(= -inf.0 value) (display "-inf" port)]
[(nan? value) (display "nan" port)]
[else (display value port)])]
[(boolean? value)
(cond
[value (display "True" port)]
[else (display "False" port)])]
[(char? value)
(fprintf port "char(~a)" (char->integer value))]
[(string? value)
(let
([contains-sq (string-contains? value "'")]
[contains-dq (string-contains? value "\"")])
(if (and contains-sq (not contains-dq))
(dssl-debug-string #\" value port)
(dssl-debug-string #\' value port)))]
[(vector? value)
(unless (seen!? value)
(define first #t)
(display #\[ port)
(for ([element (in-vector value)])
(if first
(set! first #f)
(display ", " port))
(visit element))
(display #\] port))]
[(struct-base? value)
(unless (seen!? value)
(write-struct value port visit))]
[(object-base? value)
(unless (seen!? value)
(cond
[(and (not debug?)
(get-method-value/fun value '__print__))
=>
(λ (value.__print__) (value.__print__ (make-print port)))]
[else (write-object value port visit)]))]
[(generic-proc? value)
(fprintf port "#<~a:~a>"
(generic-proc-tag value)
(generic-base-name value))]
[(procedure? value)
(define name (procedure-name value))
(if name
(fprintf port "#<proc:~a>" name)
(fprintf port "#<proc>"))]
[(contract? value)
(fprintf port "#<contract:~a>" (contract-name value))]
[(void? value) (display "None" port)]
[(is-a? value snip%) (display value port)]
[else (display "#<unprintable>" port)]))))
(define (procedure-name value)
(cond
[(contract? value)
(define name (contract-name value))
(if (eq? name '???) #f name)]
[else (object-name value)]))
(define (make-print port)
(λ (fmt . args)
(apply dssl-fprintf port fmt args)))
Dssl2Value - > [ HashEq Dssl2Value [ Or # true Natural ] ]
(define (find-cycles value0)
(define table (make-hasheq))
(define revisited-count 0)
(define (seen!? value)
(define value-info (hash-ref table value #false))
(cond
[(number? value-info) #true]
[value-info
(hash-set! table value revisited-count)
(set! revisited-count (add1 revisited-count))
#true]
[else
(hash-set! table value #true)
#false]))
(define (visit value)
(cond
[(vector? value)
(unless (seen!? value)
(for ([element (in-vector value)])
(visit element)))]
[(struct-base? value)
(unless (seen!? value)
(define info (struct-base-struct-info value))
(for ([field (in-vector (struct-info-field-infos info))])
(visit ((field-info-getter field) value))))]
[(object-base? value)
(unless (seen!? value)
(for ([field-pair (in-vector ((object-base-reflect value)))])
(visit (cdr field-pair))))]))
(visit value0)
table)
(define (dssl-debug-string q str port)
(define (esc c)
(display #\\ port)
(display c port))
(display q port)
(for ([c (in-string str)])
(case c
[(#\\) (esc #\\)]
[(#\007) (esc #\a)]
[(#\backspace) (esc #\b)]
[(#\page) (esc #\f)]
[(#\newline) (esc #\n)]
[(#\return) (esc #\r)]
[(#\tab) (esc #\t)]
[(#\vtab) (esc #\v)]
[(#\space) (display #\space port)]
[else
(cond
[(char=? c q) (esc c)]
[(not (char-graphic? c))
(define hex (format "~x" (char->integer c)))
(fprintf port
(if (= 1 (string-length hex)) "\\x0~a" "\\x~a")
hex)]
[else (display c port)])]))
(display q port))
| |
e88a1a81ec6abde057b91b5885313d7573fd5a51d3280f0d73b1bf18de21db33 | irr/erl-tutorials | etrader_stats.erl | -module(etrader_stats).
-vsn(1.0).
-author('').
-export([sma/2, ema/2]).
-export_type([ma_t/0]).
-type ma_t() :: {queue(), array()}.
-include("etrader.hrl").
-ifdef(TEST).
-include_lib("eunit/include/eunit.hrl").
-endif.
%% R:
%% library(quantmod)
%% uol <- read.csv(file="/data/bovespa/etrader.csv", header=FALSE)
%% EMA(uol[[5]][1:100], n=21)
%% dialyzer -Wno_opaque -c ../ebin/*.beam
-spec mm (integer(), integer(), integer(), ma_t()) -> ma_t().
mm(I, N, N, {Q, MA}) when is_integer(I),
is_integer(N),
is_tuple(Q),
is_tuple(MA) ->
Sum = lists:foldl(fun(X, A) -> X + A end, 0, queue:to_list(Q)),
{_, NewQ} = queue:out(Q),
{NewQ, array:set(I, Sum / N, MA)};
mm(_, _, _, T) when is_tuple(T) ->
T.
-spec em (integer(), integer(), integer(), ma_t()) -> ma_t().
em(I, N, N, {Q, MA}) when is_integer(I),
is_integer(N),
is_tuple(Q),
is_tuple(MA) ->
case array:get(N - 1, MA) of
undefined ->
mm(I, N, N, {Q, MA});
_ ->
X = 2 / (N + 1),
PM = array:get(I - 1, MA),
{{value, V}, NewQ} = queue:out_r(Q),
EMA = V * X + PM * (1 - X),
{NewQ, array:set(I, EMA, MA)}
end;
em(_, _, _, T) when is_tuple(T) ->
T.
-spec ma (integer(), array(), integer(), integer(), ma_t(), function()) -> array().
ma(0, _, _, _, _, _) ->
array:new();
ma(L, _, _, I, {_, MA}, _) when I =:= L,
is_integer(I),
is_integer(L),
is_tuple(MA) ->
MA;
ma(L, A, N, I, {Q, MA}, F) when is_integer(L),
is_tuple(A),
is_integer(N),
is_integer(I),
is_tuple(Q),
is_tuple(MA),
is_function(F, 4)->
T = array:get(I, A),
Val = T#ohlc.close,
NewQ = queue:in(Val, Q),
ma(L, A, N, I + 1, F(I, N, queue:len(NewQ), {NewQ, MA}), F).
-spec sma (array(), integer()) -> array().
sma(A, N) ->
ma(array:size(A), A, N, 0, {queue:new(), array:new(array:size(A))}, fun mm/4).
-spec ema (array(), integer()) -> array().
ema(A, N) ->
ma(array:size(A), A, N, 0, {queue:new(), array:new(array:size(A))}, fun em/4).
-ifdef(TEST).
erl -make & & erl -pa .. /ebin + K true + A 42 + B -run etrader_app start -etrader limit 100
ps . : limit MUST BE 100 to pass tests !
1 > : test ( ) .
%% Test passed.
%% ok
2 > eunit : test({inparallel , } ) .
%% Test passed.
%% ok
ma_test() ->
{ok, [DATA]} = file:consult(?TEST_DATA),
EMA = ema(DATA, 21),
{ok, [EMA_TEST]} = file:consult(?TEST_EMA21),
?assertEqual(EMA, EMA_TEST),
SMA = sma(DATA, 21),
{ok, [SMA_TEST]} = file:consult(?TEST_SMA21),
?assertEqual(SMA, SMA_TEST).
-endif.
| null | https://raw.githubusercontent.com/irr/erl-tutorials/da68b1c08baf6bdf46e7e8d3381d796e93c0357c/et/src/etrader_stats.erl | erlang | R:
library(quantmod)
uol <- read.csv(file="/data/bovespa/etrader.csv", header=FALSE)
EMA(uol[[5]][1:100], n=21)
dialyzer -Wno_opaque -c ../ebin/*.beam
Test passed.
ok
Test passed.
ok | -module(etrader_stats).
-vsn(1.0).
-author('').
-export([sma/2, ema/2]).
-export_type([ma_t/0]).
-type ma_t() :: {queue(), array()}.
-include("etrader.hrl").
-ifdef(TEST).
-include_lib("eunit/include/eunit.hrl").
-endif.
-spec mm (integer(), integer(), integer(), ma_t()) -> ma_t().
mm(I, N, N, {Q, MA}) when is_integer(I),
is_integer(N),
is_tuple(Q),
is_tuple(MA) ->
Sum = lists:foldl(fun(X, A) -> X + A end, 0, queue:to_list(Q)),
{_, NewQ} = queue:out(Q),
{NewQ, array:set(I, Sum / N, MA)};
mm(_, _, _, T) when is_tuple(T) ->
T.
-spec em (integer(), integer(), integer(), ma_t()) -> ma_t().
em(I, N, N, {Q, MA}) when is_integer(I),
is_integer(N),
is_tuple(Q),
is_tuple(MA) ->
case array:get(N - 1, MA) of
undefined ->
mm(I, N, N, {Q, MA});
_ ->
X = 2 / (N + 1),
PM = array:get(I - 1, MA),
{{value, V}, NewQ} = queue:out_r(Q),
EMA = V * X + PM * (1 - X),
{NewQ, array:set(I, EMA, MA)}
end;
em(_, _, _, T) when is_tuple(T) ->
T.
-spec ma (integer(), array(), integer(), integer(), ma_t(), function()) -> array().
ma(0, _, _, _, _, _) ->
array:new();
ma(L, _, _, I, {_, MA}, _) when I =:= L,
is_integer(I),
is_integer(L),
is_tuple(MA) ->
MA;
ma(L, A, N, I, {Q, MA}, F) when is_integer(L),
is_tuple(A),
is_integer(N),
is_integer(I),
is_tuple(Q),
is_tuple(MA),
is_function(F, 4)->
T = array:get(I, A),
Val = T#ohlc.close,
NewQ = queue:in(Val, Q),
ma(L, A, N, I + 1, F(I, N, queue:len(NewQ), {NewQ, MA}), F).
-spec sma (array(), integer()) -> array().
sma(A, N) ->
ma(array:size(A), A, N, 0, {queue:new(), array:new(array:size(A))}, fun mm/4).
-spec ema (array(), integer()) -> array().
ema(A, N) ->
ma(array:size(A), A, N, 0, {queue:new(), array:new(array:size(A))}, fun em/4).
-ifdef(TEST).
erl -make & & erl -pa .. /ebin + K true + A 42 + B -run etrader_app start -etrader limit 100
ps . : limit MUST BE 100 to pass tests !
1 > : test ( ) .
2 > eunit : test({inparallel , } ) .
ma_test() ->
{ok, [DATA]} = file:consult(?TEST_DATA),
EMA = ema(DATA, 21),
{ok, [EMA_TEST]} = file:consult(?TEST_EMA21),
?assertEqual(EMA, EMA_TEST),
SMA = sma(DATA, 21),
{ok, [SMA_TEST]} = file:consult(?TEST_SMA21),
?assertEqual(SMA, SMA_TEST).
-endif.
|
aeeb777278a488fea44ec4e524d729d1f03824485d9a38c30a0b7178b5e8d23a | foretspaisibles/lemonade-sqlite | main.ml | Main -- Unit testing
Lemonade Sqlite ( -sqlite )
This file is part of Lemonade Sqlite
Copyright © 2016
This file must be used under the terms of the CeCILL - B.
This source file is licensed as described in the file COPYING , which
you should have received as part of this distribution . The terms
are also available at
-B_V1-en.txt
Lemonade Sqlite (-sqlite)
This file is part of Lemonade Sqlite
Copyright © 2016 Michael Grünewald
This file must be used under the terms of the CeCILL-B.
This source file is licensed as described in the file COPYING, which
you should have received as part of this distribution. The terms
are also available at
-B_V1-en.txt *)
let () = Broken.main ()
| null | https://raw.githubusercontent.com/foretspaisibles/lemonade-sqlite/a1fcdf49afc3d902ddd7f0d58ef1fdc894f92965/testsuite/main.ml | ocaml | Main -- Unit testing
Lemonade Sqlite ( -sqlite )
This file is part of Lemonade Sqlite
Copyright © 2016
This file must be used under the terms of the CeCILL - B.
This source file is licensed as described in the file COPYING , which
you should have received as part of this distribution . The terms
are also available at
-B_V1-en.txt
Lemonade Sqlite (-sqlite)
This file is part of Lemonade Sqlite
Copyright © 2016 Michael Grünewald
This file must be used under the terms of the CeCILL-B.
This source file is licensed as described in the file COPYING, which
you should have received as part of this distribution. The terms
are also available at
-B_V1-en.txt *)
let () = Broken.main ()
| |
c7ed6784e6ee603f1c2251e368ce8f359b6e3cb3cbf37f67cc5fc899d4964857 | mirleft/ocaml-asn1-combinators | test.ml | Copyright ( c ) 2014 - 2019 . All rights reserved .
See LICENSE.md .
See LICENSE.md. *)
let pp_hex_cs ppf =
let pp ppf cs =
for i = 0 to Cstruct.length cs - 1 do
Format.fprintf ppf "%02x@ " (Cstruct.get_uint8 cs i)
done in
Format.fprintf ppf "@[%a@]" pp
let pp_hex_s ppf =
let pp ppf = String.iter @@ fun c ->
Format.fprintf ppf "%02x@ " (Char.code c) in
Format.fprintf ppf "@[%a@]" pp
let x s =
let rec go buf sb =
match Scanf.bscanf sb " %02x" Char.chr with
b -> Buffer.add_char buf b; go buf sb
| exception End_of_file -> Buffer.contents buf in
go (Buffer.create 17) (Scanf.Scanning.from_string s)
let x_cs s = Cstruct.of_string (x s)
let cstruct = Alcotest.testable pp_hex_cs Cstruct.equal
let err = Alcotest.testable Asn.pp_error (fun (`Parse _) (`Parse _) -> true)
let dec t = Alcotest.(result (pair t cstruct) err)
let testable ?(pp = fun ppf _ -> Fmt.pf ppf "*shrug*") ?(cmp = (=)) () =
Alcotest.testable pp cmp
let pp_e ppf = function
| #Asn.error as e -> Asn.pp_error ppf e
| `Leftover b -> Format.fprintf ppf "Leftover: %a" pp_hex_cs b
let get = function Some x -> x | _ -> assert false
type 'a cmp = 'a -> 'a -> bool
type case_eq =
CEQ : string * 'a Alcotest.testable * 'a Asn.t * ('a * string) list -> case_eq
let case_eq name ?pp ?cmp asn examples =
CEQ (name, testable ?pp ?cmp (), asn, examples)
type case = C : string * 'a Asn.t * string list -> case
let case name asn examples = C (name, asn, examples)
let accepts_eq name enc cases =
let tests = cases |> List.map @@ fun (CEQ (name, alc, asn, xs)) ->
let codec = Asn.codec enc asn
and t = dec alc in
let f () = xs |> List.iter @@ fun (x, s) ->
Alcotest.check t name (Ok (x, Cstruct.empty)) (Asn.decode codec (x_cs s)) in
(name, `Quick, f) in
(name, tests)
let rejects name enc cases =
let tests = cases |> List.map @@ fun (C (name, asn, ss)) ->
let codec = Asn.codec enc asn
and t = dec (testable ()) in
let f () = ss |> List.iter @@ fun s ->
Alcotest.check t name (Error (`Parse "...")) (Asn.decode codec (x_cs s)) in
(name, `Quick, f) in
(name, tests)
let accepts name enc cases =
let tests = cases |> List.map @@ fun (C (name, asn, ss)) ->
let f () = ss |> List.iter @@ fun s ->
match Asn.(decode (codec enc asn)) (x_cs s) with
Ok (_, t) ->
Alcotest.check cstruct "no remainder" Cstruct.empty t
| Error e ->
Alcotest.failf "decode failed with: %a" pp_e e in
(name, `Quick, f) in
(name, tests)
let inverts1 ?(iters = 1000) name enc cases =
let tests = cases |> List.map @@ fun (CEQ (name, alc, asn, _)) ->
let codec = Asn.codec enc asn and t = dec alc in
let f () =
for _ = 1 to iters do
let x = Asn.random asn in
Alcotest.check t "invert" (Ok (x, Cstruct.empty))
(Asn.decode codec (Asn.encode codec x))
done in
(name, `Quick, f) in
(name, tests)
let time ?(frac=0) dtz =
Ptime.(add_span (of_date_time dtz |> get)
(Span.v (0, Int64.(mul (of_int frac) 1_000_000_000L))) |> get)
let v32 = Z.of_int32
let (<+) z1 i64 = Z.((z1 lsl 64) lor (extract (of_int64 i64) 0 64))
let cases = [
case_eq "bool" Asn.S.bool [
false, "010100" ;
true , "0101ff"
];
case_eq "integer" Asn.S.integer [
v32 0x000000_00l, "0201 00";
v32 0x000000_7fl, "0201 7f";
v32 0xffffff_80l, "0201 80";
v32 0xffffff_ffl, "0201 ff";
v32 0x0000_0080l, "0202 0080";
v32 0x0000_7fffl, "0202 7fff";
v32 0xffff_8000l, "0202 8000";
v32 0xffff_ff7fl, "0202 ff7f";
v32 0x00_008000l, "0203 008000";
v32 0x00_00ffffl, "0203 00ffff";
v32 0xff_800000l, "0203 800000";
v32 0xff_ff7fffl, "0203 ff7fff";
v32 0x00800000l, "0204 00800000";
v32 0x7fffffffl, "0204 7fffffff";
v32 0x80000000l, "0204 80000000";
v32 0xff7fffffl, "0204 ff7fffff";
v32 0x00800000l <+ 0x00000000_00000000L, "020c 00800000 00000000 00000000";
v32 0x00ffffffl <+ 0xffffffff_ffffffffL, "020c 00ffffff ffffffff ffffffff";
v32 0x00ffffffl <+ 0x7fffffff_ffffffffL, "020c 00ffffff 7fffffff ffffffff";
v32 0x00ffffffl <+ 0xffffffff_7fffffffL, "020c 00ffffff ffffffff 7fffffff";
v32 0x80ffffffl <+ 0xffffffff_ffffffffL, "020c 80ffffff ffffffff ffffffff";
v32 0xff7fffffl <+ 0xffffffff_ffffffffL, "020c ff7fffff ffffffff ffffffff";
];
case_eq "null" Asn.S.null [
(), "0500";
(), "058100"
];
case_eq "singleton seq"
Asn.S.(sequence (single @@ required bool))
[ true, "30030101ff";
true, "30800101ff0000" ; ];
case_eq "rename stack"
Asn.S.(implicit 1 @@ implicit 2 @@ explicit 3 @@ implicit 4 @@ int)
[ 42, "a18084012a0000";
42, "a10384012a" ];
case_eq "sequence with implicits"
Asn.S.(sequence3
(required int)
(required @@ implicit 1 bool)
(required bool))
[ (42, false, true), "3009 02012a 810100 0101ff";
(42, false, true), "3080 02012a 810100 0101ff 0000" ];
case_eq "sequence with optional and explicit fields"
Asn.S.(sequence3
(required @@ implicit 1 int)
(optional @@ explicit 2 bool)
(optional @@ implicit 3 bool))
[ (255, Some true, Some false),
"300c 810200ff a203 0101f0 830100" ;
(255, Some true, Some false),
"3080 810200ff a203 0101f0 830100 0000";
(255, Some true, Some false),
"3080 810200ff a280 0101f0 0000 830100 0000" ];
case_eq "sequence with missing optional and choice fields"
Asn.S.(sequence3 (required @@ choice2 bool int)
(optional @@ choice2 bool int)
(optional @@ explicit 0
@@ choice2 int (implicit 1 int)))
[ (`C1 true, None, None), "30030101ff" ;
(`C1 false, Some (`C2 42), None), "3006 010100 02012a";
(`C1 true, None, Some (`C1 42)), "3008 0101ff a003 02012a" ;
(`C2 (-2), Some (`C2 42), Some (`C2 42)), "300b 0201fe 02012a a003 81012a";
(`C2 (-3), None, Some (`C2 42)), "300a 0201fd a080 81012a0000";
(`C2 (-4), None, Some (`C1 42)), "3080 0201fc a080 02012a0000 0000" ];
case_eq "sequence with sequence"
Asn.S.(sequence2
(required @@
sequence2
(optional @@ implicit 1 bool)
(optional bool))
(required bool))
[ ((Some true, Some false), true), "300b 3006 8101ff 010100 0101ff";
((None, Some false), true), "3008 3003 010100 0101ff";
((Some true, None), true), "3008 3003 8101ff 0101ff" ;
((Some true, None), true), "3080 3080 8101ff 0000 0101ff 0000";
((None, None), true), "3007308000000101ff";
((None, None), true), "300530000101ff" ];
case_eq "sequence_of choice"
Asn.S.(sequence2
(required @@
sequence_of
(choice2 bool (implicit 0 bool)))
(required @@ bool))
[ ([`C2 true; `C2 false; `C1 true], true),
"300e 3009 8001ff 800100 0101ff 0101ff";
([`C2 true; `C2 false; `C1 true], true),
"3080 3080 8001ff 800100 0101ff 0000 0101ff 0000" ];
case_eq "sets"
Asn.S.(set4 (required @@ implicit 1 bool)
(required @@ implicit 2 bool)
(required @@ implicit 3 int )
(optional @@ implicit 4 int ))
[ (true, false, 42, None), "3109 8101ff 820100 83012a";
(true, false, 42, Some (-1)), "310c 820100 8401ff 8101ff 83012a";
(true, false, 42, None), "3109 820100 83012a 8101ff";
(true, false, 42, Some 15), "310c 83012a 820100 8101ff 84010f";
(true, false, 42, None), "3180 820100 83012a 8101ff 0000";
(true, false, 42, Some 15), "3180 83012a 820100 8101ff 84010f 0000" ];
case_eq "set or seq"
Asn.S.(choice2 (set2 (optional int ) (optional bool))
(sequence2 (optional int ) (optional bool)))
[ (`C1 (None, Some true)), "3103 0101ff";
(`C1 (Some 42, None)), "3103 02012a";
(`C1 (Some 42, Some true)), "3106 0101ff 02012a";
(`C2 (None, Some true)), "3003 0101ff";
(`C2 (Some 42, None)), "3003 02012a";
(`C2 (Some 42, Some true)), "3006 02012a 0101ff" ];
case_eq
"large tag"
Asn.S.(implicit 6666666 bool)
[ true , "9f8396f32a01ff";
false, "9f8396f32a0100";
];
case_eq
"recursive encoding"
Asn.S.(
fix @@ fun list ->
map (function `C1 () -> [] | `C2 (x, xs) -> x::xs)
(function [] -> `C1 () | x::xs -> `C2 (x, xs)) @@
choice2 null (sequence2 (required bool) (required list)))
[ [], "0500" ;
[true], "3005 0101ff 0500" ;
[true; false; true],
"300f 0101ff 300a 010100 3005 0101ff 0500";
[false; true; false],
"3080 010100 3080 0101ff 3080 010100 0500 0000 0000 0000";
[false; true; false],
"3080 010100 3080 0101ff 3080 010100 0500 0000 0000 0000" ];
case_eq "ia5 string" Asn.S.ia5_string
[ "abc", "1603616263";
"abcd", "360a 160161 160162 16026364";
"abcd", "3680 160161 160162 16026364 0000";
"abcd", "3680 3606 160161 160162 16026364 0000";
"", "160d7465737431407273 612e636f6d";
"", "16810d 7465737431407273612e636f6d" ;
"", "3613 16057465737431 160140 16077273612e636f6d" ];
case_eq "bit string" Asn.S.bit_string
( let example =
[| false; true; true; false; true; true; true; false; false;
true; false; true; true; true; false; true; true; true |] in
[ example, "0304066e5dc0";
example, "0304066e5de0";
example, "038104066e5dc0";
example, "2309 0303006e5d 030206c0" ] );
case_eq "bit flags"
(Asn.S.bit_string_flags [(2, `A); (4, `C); (8, `B); (10, `E); (12, `D)])
[ [`A; `B; `C], "030304ffdf";
[`A; `B; `C; `D], "030303ffdf"; ];
( let open Asn.OID in
let rsa = base 1 2 <| 840 <| 113549 in
case_eq "oid" Asn.S.oid [
( rsa ), "06062a864886f70d";
( rsa <| 1 <| 7 <| 2 ), "06092a864886f70d010702";
( rsa <| 1 <| 7 <| 1 ), "06092a864886f70d010701";
( base 1 3 <| 14 <| 3 <| 2 <| 26 ), "06052b0e03021a";
( base 2 5 <| 4 <| 3 ), "0603550403";
( base 2 5 <| 29 <| 15 ), "0603551d0f";
( base 1 2 <| 99999 ), "06042a868d1f";
] );
case_eq "octets" Asn.S.octet_string [
x_cs "0123456789abcdef", "0408 0123456789abcdef" ;
x_cs "0123456789abcdef", "048108 0123456789abcdef";
x_cs "0123456789abcdef", "240c 040401234567 040489abcdef" ];
case_eq "utc time" ~cmp:Ptime.equal Asn.S.utc_time [
( time ((1991, 5, 6), ((23, 45, 40), 0)),
"170d3931303530363233343534305a " ) ;
( time ((1991, 5, 6), ((16, 45, 40), -7 * 3600)),
"17113931303530363136343534302D30373030 " );
( time ((1991, 5, 6), ((16, 45, 0), 9000)),
"170f393130353036313634352b30323330");
] ;
case_eq "generalized time" ~cmp:Ptime.equal Asn.S.generalized_time [
( time ((1991, 5, 6), ((16, 0, 0), 0)),
"180a313939313035303631 36");
( time ((1991, 5, 6), ((16, 0, 0), 0)),
"180b313939313035303631 365a ");
( time ((1991, 5, 6), ((16, 0, 0), 15 * 60)),
"180f313939313035303631 362b30303135");
( time ((1991, 5, 6), ((16, 45, 0), 15 * 60)),
"1811313939313035303631 3634352b30303135");
( time ((1991, 5, 6), ((16, 45, 40), -15 * 60)),
"1813313939313035303631 36343534302d30303135");
( time ~frac:001 ((1991, 5, 6), ((16, 45, 40), -(10 * 3600 + 10 * 60))),
"1817313939313035303631 36343534302e3030312d31 303130");
( Ptime.min,
"1817303030303031303130 30303030302e3030302b30 303030");
( Ptime.(truncate ~frac_s:3 max),
"1817393939393132333132 33353935392e3939392b30 303030")
] ;
]
let anticases = [
thx @alpha-60
case "tag overflow" Asn.S.bool
[ "1f a080 8080 8080 8080 8001 01ff" ];
case "leading zero" Asn.S.(implicit 127 bool)
[ "9f807f01ff" ];
case "length overflow" Asn.S.bool
[ "01 88 8000000000000001 ff" ] ;
case "oid overflow" Asn.S.oid
[ "06 0b 2a bfffffffffffffffff7f" ] ;
case "empty integer" Asn.S.integer [ "0200" ];
case "redundant int form" Asn.S.integer [
"02020000"; "0202007f"; "0202ff80"; "0202ffff";
"0203000000"; "0203007fff"; "0203ff8000"; "0203ffffff";
];
case "redundant oid form" Asn.S.oid
[ "06028001"; "06032a8001" ];
case "length overflow" Asn.S.integer
[ "02890100000000000000012a" ];
case "silly bit strings" Asn.S.bit_string
[ "0300"; "030101"; "030208ff" ];
case "null with indefinite length" Asn.S.null
[ "0580"; "058000"; "05800000" ];
case "32 bit length overflow"
Asn.S.(sequence2 (required integer) (required integer))
[ "30850100000006020180020180" ];
]
let der_anticases = [
case "constructed string 1" Asn.S.octet_string
[ "2400"; "24 06 04 04 46 55 43 4b" ];
case "constructed string 2" Asn.S.utf8_string
[ "2c00"; "2c060c044655434b" ];
case "expanded length" Asn.S.integer
[ "0281012a" ];
case "redundant length" Asn.S.octet_string
[ "048200ff" ^
Format.asprintf "%a" pp_hex_s (String.init 0xff (fun _ -> '\xaa')) ];
]
let certs = List.map (fun s -> case "cert" X509.certificate [s]) X509.examples
let () = Alcotest.run ~and_exit:false "BER" [
accepts_eq "value samples" Asn.ber cases;
rejects "- BER antisamples" Asn.ber anticases;
accepts "+ DER antisamples" Asn.ber der_anticases;
accepts "certs" Asn.ber certs;
inverts1 "inv" Asn.ber cases;
(* invert certs *)
]
let () = Alcotest.run "DER" [
(* accepts_eq "value samples" Asn.der cases; *)
rejects "- BER antisamples" Asn.der anticases;
rejects "- DER antisamples" Asn.der der_anticases;
accepts "certs" Asn.der certs;
inverts1 "inv" Asn.der cases;
(* invert certs *)
(* injectivity *)
]
| null | https://raw.githubusercontent.com/mirleft/ocaml-asn1-combinators/f10fc1d869be293a16a31b272fc71794849007a2/tests/test.ml | ocaml | invert certs
accepts_eq "value samples" Asn.der cases;
invert certs
injectivity | Copyright ( c ) 2014 - 2019 . All rights reserved .
See LICENSE.md .
See LICENSE.md. *)
let pp_hex_cs ppf =
let pp ppf cs =
for i = 0 to Cstruct.length cs - 1 do
Format.fprintf ppf "%02x@ " (Cstruct.get_uint8 cs i)
done in
Format.fprintf ppf "@[%a@]" pp
let pp_hex_s ppf =
let pp ppf = String.iter @@ fun c ->
Format.fprintf ppf "%02x@ " (Char.code c) in
Format.fprintf ppf "@[%a@]" pp
let x s =
let rec go buf sb =
match Scanf.bscanf sb " %02x" Char.chr with
b -> Buffer.add_char buf b; go buf sb
| exception End_of_file -> Buffer.contents buf in
go (Buffer.create 17) (Scanf.Scanning.from_string s)
let x_cs s = Cstruct.of_string (x s)
let cstruct = Alcotest.testable pp_hex_cs Cstruct.equal
let err = Alcotest.testable Asn.pp_error (fun (`Parse _) (`Parse _) -> true)
let dec t = Alcotest.(result (pair t cstruct) err)
let testable ?(pp = fun ppf _ -> Fmt.pf ppf "*shrug*") ?(cmp = (=)) () =
Alcotest.testable pp cmp
let pp_e ppf = function
| #Asn.error as e -> Asn.pp_error ppf e
| `Leftover b -> Format.fprintf ppf "Leftover: %a" pp_hex_cs b
let get = function Some x -> x | _ -> assert false
type 'a cmp = 'a -> 'a -> bool
type case_eq =
CEQ : string * 'a Alcotest.testable * 'a Asn.t * ('a * string) list -> case_eq
let case_eq name ?pp ?cmp asn examples =
CEQ (name, testable ?pp ?cmp (), asn, examples)
type case = C : string * 'a Asn.t * string list -> case
let case name asn examples = C (name, asn, examples)
let accepts_eq name enc cases =
let tests = cases |> List.map @@ fun (CEQ (name, alc, asn, xs)) ->
let codec = Asn.codec enc asn
and t = dec alc in
let f () = xs |> List.iter @@ fun (x, s) ->
Alcotest.check t name (Ok (x, Cstruct.empty)) (Asn.decode codec (x_cs s)) in
(name, `Quick, f) in
(name, tests)
let rejects name enc cases =
let tests = cases |> List.map @@ fun (C (name, asn, ss)) ->
let codec = Asn.codec enc asn
and t = dec (testable ()) in
let f () = ss |> List.iter @@ fun s ->
Alcotest.check t name (Error (`Parse "...")) (Asn.decode codec (x_cs s)) in
(name, `Quick, f) in
(name, tests)
let accepts name enc cases =
let tests = cases |> List.map @@ fun (C (name, asn, ss)) ->
let f () = ss |> List.iter @@ fun s ->
match Asn.(decode (codec enc asn)) (x_cs s) with
Ok (_, t) ->
Alcotest.check cstruct "no remainder" Cstruct.empty t
| Error e ->
Alcotest.failf "decode failed with: %a" pp_e e in
(name, `Quick, f) in
(name, tests)
let inverts1 ?(iters = 1000) name enc cases =
let tests = cases |> List.map @@ fun (CEQ (name, alc, asn, _)) ->
let codec = Asn.codec enc asn and t = dec alc in
let f () =
for _ = 1 to iters do
let x = Asn.random asn in
Alcotest.check t "invert" (Ok (x, Cstruct.empty))
(Asn.decode codec (Asn.encode codec x))
done in
(name, `Quick, f) in
(name, tests)
let time ?(frac=0) dtz =
Ptime.(add_span (of_date_time dtz |> get)
(Span.v (0, Int64.(mul (of_int frac) 1_000_000_000L))) |> get)
let v32 = Z.of_int32
let (<+) z1 i64 = Z.((z1 lsl 64) lor (extract (of_int64 i64) 0 64))
let cases = [
case_eq "bool" Asn.S.bool [
false, "010100" ;
true , "0101ff"
];
case_eq "integer" Asn.S.integer [
v32 0x000000_00l, "0201 00";
v32 0x000000_7fl, "0201 7f";
v32 0xffffff_80l, "0201 80";
v32 0xffffff_ffl, "0201 ff";
v32 0x0000_0080l, "0202 0080";
v32 0x0000_7fffl, "0202 7fff";
v32 0xffff_8000l, "0202 8000";
v32 0xffff_ff7fl, "0202 ff7f";
v32 0x00_008000l, "0203 008000";
v32 0x00_00ffffl, "0203 00ffff";
v32 0xff_800000l, "0203 800000";
v32 0xff_ff7fffl, "0203 ff7fff";
v32 0x00800000l, "0204 00800000";
v32 0x7fffffffl, "0204 7fffffff";
v32 0x80000000l, "0204 80000000";
v32 0xff7fffffl, "0204 ff7fffff";
v32 0x00800000l <+ 0x00000000_00000000L, "020c 00800000 00000000 00000000";
v32 0x00ffffffl <+ 0xffffffff_ffffffffL, "020c 00ffffff ffffffff ffffffff";
v32 0x00ffffffl <+ 0x7fffffff_ffffffffL, "020c 00ffffff 7fffffff ffffffff";
v32 0x00ffffffl <+ 0xffffffff_7fffffffL, "020c 00ffffff ffffffff 7fffffff";
v32 0x80ffffffl <+ 0xffffffff_ffffffffL, "020c 80ffffff ffffffff ffffffff";
v32 0xff7fffffl <+ 0xffffffff_ffffffffL, "020c ff7fffff ffffffff ffffffff";
];
case_eq "null" Asn.S.null [
(), "0500";
(), "058100"
];
case_eq "singleton seq"
Asn.S.(sequence (single @@ required bool))
[ true, "30030101ff";
true, "30800101ff0000" ; ];
case_eq "rename stack"
Asn.S.(implicit 1 @@ implicit 2 @@ explicit 3 @@ implicit 4 @@ int)
[ 42, "a18084012a0000";
42, "a10384012a" ];
case_eq "sequence with implicits"
Asn.S.(sequence3
(required int)
(required @@ implicit 1 bool)
(required bool))
[ (42, false, true), "3009 02012a 810100 0101ff";
(42, false, true), "3080 02012a 810100 0101ff 0000" ];
case_eq "sequence with optional and explicit fields"
Asn.S.(sequence3
(required @@ implicit 1 int)
(optional @@ explicit 2 bool)
(optional @@ implicit 3 bool))
[ (255, Some true, Some false),
"300c 810200ff a203 0101f0 830100" ;
(255, Some true, Some false),
"3080 810200ff a203 0101f0 830100 0000";
(255, Some true, Some false),
"3080 810200ff a280 0101f0 0000 830100 0000" ];
case_eq "sequence with missing optional and choice fields"
Asn.S.(sequence3 (required @@ choice2 bool int)
(optional @@ choice2 bool int)
(optional @@ explicit 0
@@ choice2 int (implicit 1 int)))
[ (`C1 true, None, None), "30030101ff" ;
(`C1 false, Some (`C2 42), None), "3006 010100 02012a";
(`C1 true, None, Some (`C1 42)), "3008 0101ff a003 02012a" ;
(`C2 (-2), Some (`C2 42), Some (`C2 42)), "300b 0201fe 02012a a003 81012a";
(`C2 (-3), None, Some (`C2 42)), "300a 0201fd a080 81012a0000";
(`C2 (-4), None, Some (`C1 42)), "3080 0201fc a080 02012a0000 0000" ];
case_eq "sequence with sequence"
Asn.S.(sequence2
(required @@
sequence2
(optional @@ implicit 1 bool)
(optional bool))
(required bool))
[ ((Some true, Some false), true), "300b 3006 8101ff 010100 0101ff";
((None, Some false), true), "3008 3003 010100 0101ff";
((Some true, None), true), "3008 3003 8101ff 0101ff" ;
((Some true, None), true), "3080 3080 8101ff 0000 0101ff 0000";
((None, None), true), "3007308000000101ff";
((None, None), true), "300530000101ff" ];
case_eq "sequence_of choice"
Asn.S.(sequence2
(required @@
sequence_of
(choice2 bool (implicit 0 bool)))
(required @@ bool))
[ ([`C2 true; `C2 false; `C1 true], true),
"300e 3009 8001ff 800100 0101ff 0101ff";
([`C2 true; `C2 false; `C1 true], true),
"3080 3080 8001ff 800100 0101ff 0000 0101ff 0000" ];
case_eq "sets"
Asn.S.(set4 (required @@ implicit 1 bool)
(required @@ implicit 2 bool)
(required @@ implicit 3 int )
(optional @@ implicit 4 int ))
[ (true, false, 42, None), "3109 8101ff 820100 83012a";
(true, false, 42, Some (-1)), "310c 820100 8401ff 8101ff 83012a";
(true, false, 42, None), "3109 820100 83012a 8101ff";
(true, false, 42, Some 15), "310c 83012a 820100 8101ff 84010f";
(true, false, 42, None), "3180 820100 83012a 8101ff 0000";
(true, false, 42, Some 15), "3180 83012a 820100 8101ff 84010f 0000" ];
case_eq "set or seq"
Asn.S.(choice2 (set2 (optional int ) (optional bool))
(sequence2 (optional int ) (optional bool)))
[ (`C1 (None, Some true)), "3103 0101ff";
(`C1 (Some 42, None)), "3103 02012a";
(`C1 (Some 42, Some true)), "3106 0101ff 02012a";
(`C2 (None, Some true)), "3003 0101ff";
(`C2 (Some 42, None)), "3003 02012a";
(`C2 (Some 42, Some true)), "3006 02012a 0101ff" ];
case_eq
"large tag"
Asn.S.(implicit 6666666 bool)
[ true , "9f8396f32a01ff";
false, "9f8396f32a0100";
];
case_eq
"recursive encoding"
Asn.S.(
fix @@ fun list ->
map (function `C1 () -> [] | `C2 (x, xs) -> x::xs)
(function [] -> `C1 () | x::xs -> `C2 (x, xs)) @@
choice2 null (sequence2 (required bool) (required list)))
[ [], "0500" ;
[true], "3005 0101ff 0500" ;
[true; false; true],
"300f 0101ff 300a 010100 3005 0101ff 0500";
[false; true; false],
"3080 010100 3080 0101ff 3080 010100 0500 0000 0000 0000";
[false; true; false],
"3080 010100 3080 0101ff 3080 010100 0500 0000 0000 0000" ];
case_eq "ia5 string" Asn.S.ia5_string
[ "abc", "1603616263";
"abcd", "360a 160161 160162 16026364";
"abcd", "3680 160161 160162 16026364 0000";
"abcd", "3680 3606 160161 160162 16026364 0000";
"", "160d7465737431407273 612e636f6d";
"", "16810d 7465737431407273612e636f6d" ;
"", "3613 16057465737431 160140 16077273612e636f6d" ];
case_eq "bit string" Asn.S.bit_string
( let example =
[| false; true; true; false; true; true; true; false; false;
true; false; true; true; true; false; true; true; true |] in
[ example, "0304066e5dc0";
example, "0304066e5de0";
example, "038104066e5dc0";
example, "2309 0303006e5d 030206c0" ] );
case_eq "bit flags"
(Asn.S.bit_string_flags [(2, `A); (4, `C); (8, `B); (10, `E); (12, `D)])
[ [`A; `B; `C], "030304ffdf";
[`A; `B; `C; `D], "030303ffdf"; ];
( let open Asn.OID in
let rsa = base 1 2 <| 840 <| 113549 in
case_eq "oid" Asn.S.oid [
( rsa ), "06062a864886f70d";
( rsa <| 1 <| 7 <| 2 ), "06092a864886f70d010702";
( rsa <| 1 <| 7 <| 1 ), "06092a864886f70d010701";
( base 1 3 <| 14 <| 3 <| 2 <| 26 ), "06052b0e03021a";
( base 2 5 <| 4 <| 3 ), "0603550403";
( base 2 5 <| 29 <| 15 ), "0603551d0f";
( base 1 2 <| 99999 ), "06042a868d1f";
] );
case_eq "octets" Asn.S.octet_string [
x_cs "0123456789abcdef", "0408 0123456789abcdef" ;
x_cs "0123456789abcdef", "048108 0123456789abcdef";
x_cs "0123456789abcdef", "240c 040401234567 040489abcdef" ];
case_eq "utc time" ~cmp:Ptime.equal Asn.S.utc_time [
( time ((1991, 5, 6), ((23, 45, 40), 0)),
"170d3931303530363233343534305a " ) ;
( time ((1991, 5, 6), ((16, 45, 40), -7 * 3600)),
"17113931303530363136343534302D30373030 " );
( time ((1991, 5, 6), ((16, 45, 0), 9000)),
"170f393130353036313634352b30323330");
] ;
case_eq "generalized time" ~cmp:Ptime.equal Asn.S.generalized_time [
( time ((1991, 5, 6), ((16, 0, 0), 0)),
"180a313939313035303631 36");
( time ((1991, 5, 6), ((16, 0, 0), 0)),
"180b313939313035303631 365a ");
( time ((1991, 5, 6), ((16, 0, 0), 15 * 60)),
"180f313939313035303631 362b30303135");
( time ((1991, 5, 6), ((16, 45, 0), 15 * 60)),
"1811313939313035303631 3634352b30303135");
( time ((1991, 5, 6), ((16, 45, 40), -15 * 60)),
"1813313939313035303631 36343534302d30303135");
( time ~frac:001 ((1991, 5, 6), ((16, 45, 40), -(10 * 3600 + 10 * 60))),
"1817313939313035303631 36343534302e3030312d31 303130");
( Ptime.min,
"1817303030303031303130 30303030302e3030302b30 303030");
( Ptime.(truncate ~frac_s:3 max),
"1817393939393132333132 33353935392e3939392b30 303030")
] ;
]
let anticases = [
thx @alpha-60
case "tag overflow" Asn.S.bool
[ "1f a080 8080 8080 8080 8001 01ff" ];
case "leading zero" Asn.S.(implicit 127 bool)
[ "9f807f01ff" ];
case "length overflow" Asn.S.bool
[ "01 88 8000000000000001 ff" ] ;
case "oid overflow" Asn.S.oid
[ "06 0b 2a bfffffffffffffffff7f" ] ;
case "empty integer" Asn.S.integer [ "0200" ];
case "redundant int form" Asn.S.integer [
"02020000"; "0202007f"; "0202ff80"; "0202ffff";
"0203000000"; "0203007fff"; "0203ff8000"; "0203ffffff";
];
case "redundant oid form" Asn.S.oid
[ "06028001"; "06032a8001" ];
case "length overflow" Asn.S.integer
[ "02890100000000000000012a" ];
case "silly bit strings" Asn.S.bit_string
[ "0300"; "030101"; "030208ff" ];
case "null with indefinite length" Asn.S.null
[ "0580"; "058000"; "05800000" ];
case "32 bit length overflow"
Asn.S.(sequence2 (required integer) (required integer))
[ "30850100000006020180020180" ];
]
let der_anticases = [
case "constructed string 1" Asn.S.octet_string
[ "2400"; "24 06 04 04 46 55 43 4b" ];
case "constructed string 2" Asn.S.utf8_string
[ "2c00"; "2c060c044655434b" ];
case "expanded length" Asn.S.integer
[ "0281012a" ];
case "redundant length" Asn.S.octet_string
[ "048200ff" ^
Format.asprintf "%a" pp_hex_s (String.init 0xff (fun _ -> '\xaa')) ];
]
let certs = List.map (fun s -> case "cert" X509.certificate [s]) X509.examples
let () = Alcotest.run ~and_exit:false "BER" [
accepts_eq "value samples" Asn.ber cases;
rejects "- BER antisamples" Asn.ber anticases;
accepts "+ DER antisamples" Asn.ber der_anticases;
accepts "certs" Asn.ber certs;
inverts1 "inv" Asn.ber cases;
]
let () = Alcotest.run "DER" [
rejects "- BER antisamples" Asn.der anticases;
rejects "- DER antisamples" Asn.der der_anticases;
accepts "certs" Asn.der certs;
inverts1 "inv" Asn.der cases;
]
|
2162fa0b1f3e01f7877f2c1ce0ce3b037816d582e79223e8ddd4f1de568ca087 | alanz/ghc-exactprint | T9858c.hs | # LANGUAGE KindSignatures #
module Main(main) where
import Data.Typeable
import GHC.Exts
test1 :: Bool
test1 = typeRep (Proxy :: Proxy (() :: *)) ==
typeRep (Proxy :: Proxy (() :: Constraint))
test2 :: Bool
test2 = typeRepTyCon (typeRep (Proxy :: Proxy (Int,Int))) ==
typeRepTyCon (typeRep (Proxy :: Proxy (Eq Int, Eq Int)))
main :: IO ()
main = print (test1,test2)
| null | https://raw.githubusercontent.com/alanz/ghc-exactprint/b6b75027811fa4c336b34122a7a7b1a8df462563/tests/examples/ghc80/T9858c.hs | haskell | # LANGUAGE KindSignatures #
module Main(main) where
import Data.Typeable
import GHC.Exts
test1 :: Bool
test1 = typeRep (Proxy :: Proxy (() :: *)) ==
typeRep (Proxy :: Proxy (() :: Constraint))
test2 :: Bool
test2 = typeRepTyCon (typeRep (Proxy :: Proxy (Int,Int))) ==
typeRepTyCon (typeRep (Proxy :: Proxy (Eq Int, Eq Int)))
main :: IO ()
main = print (test1,test2)
| |
6cfad2f46cd5ebf2bcff62d996cbb420cecc0d4d349ae2c7bc8d38b5ecd1a081 | mojombo/egitd | log.erl | -module(log).
-export([init_log/1, write/2]).
init_log(Log) ->
ets:insert(db, {log, Log}).
write(Type, Messages) ->
write_log(ets:lookup(db, log), Type, Messages).
write_log([{log, Log}], Type, Messages) ->
{ok, F} = file:open(Log, [append]),
Message = string:join(Messages, "\t"),
Line = io_lib:fwrite("~s\t~s\t~s\n", [timestamp(), Type, Message]),
file:write(F, Line),
file:close(F),
ok;
write_log([], _Type, _Messages) ->
ok.
timestamp() ->
{{Year, Month, Day}, {Hour, Min, Sec}} = erlang:localtime(),
io_lib:fwrite("~4B-~2.10.0B-~2.10.0B ~2.10.0B:~2.10.0B:~2.10.0B", [Year, Month, Day, Hour, Min, Sec]). | null | https://raw.githubusercontent.com/mojombo/egitd/5309fe5f9a5908cd741f8dedf13790eea5d7528d/elibs/log.erl | erlang | -module(log).
-export([init_log/1, write/2]).
init_log(Log) ->
ets:insert(db, {log, Log}).
write(Type, Messages) ->
write_log(ets:lookup(db, log), Type, Messages).
write_log([{log, Log}], Type, Messages) ->
{ok, F} = file:open(Log, [append]),
Message = string:join(Messages, "\t"),
Line = io_lib:fwrite("~s\t~s\t~s\n", [timestamp(), Type, Message]),
file:write(F, Line),
file:close(F),
ok;
write_log([], _Type, _Messages) ->
ok.
timestamp() ->
{{Year, Month, Day}, {Hour, Min, Sec}} = erlang:localtime(),
io_lib:fwrite("~4B-~2.10.0B-~2.10.0B ~2.10.0B:~2.10.0B:~2.10.0B", [Year, Month, Day, Hour, Min, Sec]). | |
ab9c48b5d2edb6f7ad6bc53b0e688bbdb792150014c4c9828fa253de8d76ee52 | hipsleek/hipsleek | cil.mli |
*
* Copyright ( c ) 2001 - 2002 ,
* < >
* < >
* < >
* 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 names of the contributors may not be used to endorse or promote
* products derived from this software without specific prior written
* permission .
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS
* IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT LIMITED
* TO , THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED . IN NO EVENT SHALL THE COPYRIGHT OWNER
* OR 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) 2001-2002,
* George C. Necula <>
* Scott McPeak <>
* Wes Weimer <>
* 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 names of the contributors may not be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
* OR 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.
*
*)
* CIL : An intermediate language for analyzing C programs .
*
* *
* CIL: An intermediate language for analyzing C programs.
*
* George Necula
*
*)
open Cilint
(** {b CIL API Documentation.} An html version of this document
* can be found at *)
(** Call this function to perform some initialization. Call if after you have
* set {!Cil.msvcMode}. *)
val initCIL: unit -> unit
(** These are the CIL version numbers. A CIL version is a number of the form
* M.m.r (major, minor and release) *)
val cilVersion: string
val cilVersionMajor: int
val cilVersionMinor: int
val cilVersionRevision: int
* This module defines the abstract syntax of CIL . It also provides utility
* functions for traversing the CIL data structures , and pretty - printing
* them . The parser for both the GCC and MSVC front - ends can be invoked as
* [ Frontc.parse : string - > unit - > ] { ! Cil.file } . This function must be given
* the name of a preprocessed C file and will return the top - level data
* structure that describes a whole source file . By default the parsing and
* elaboration into CIL is done as for GCC source . If you want to use MSVC
* source you must set the { ! Cil.msvcMode } to [ true ] and must also invoke the
* function [ Frontc.setMSVCMode : unit - > unit ] .
* functions for traversing the CIL data structures, and pretty-printing
* them. The parser for both the GCC and MSVC front-ends can be invoked as
* [Frontc.parse: string -> unit ->] {!Cil.file}. This function must be given
* the name of a preprocessed C file and will return the top-level data
* structure that describes a whole source file. By default the parsing and
* elaboration into CIL is done as for GCC source. If you want to use MSVC
* source you must set the {!Cil.msvcMode} to [true] and must also invoke the
* function [Frontc.setMSVCMode: unit -> unit]. *)
(** {b The Abstract Syntax of CIL} *)
(** The top-level representation of a CIL source file (and the result of the
* parsing and elaboration). Its main contents is the list of global
* declarations and definitions. You can iterate over the globals in a
* {!Cil.file} using the following iterators: {!Cil.mapGlobals},
* {!Cil.iterGlobals} and {!Cil.foldGlobals}. You can also use the
* {!Cil.dummyFile} when you need a {!Cil.file} as a placeholder. For each
* global item CIL stores the source location where it appears (using the
* type {!Cil.location}) *)
type file =
{ mutable fileName: string; (** The complete file name *)
mutable globals: global list; (** List of globals as they will appear
in the printed file *)
mutable globinit: fundec option;
(** An optional global initializer function. This is a function where
* you can put stuff that must be executed before the program is
* started. This function is conceptually at the end of the file,
* although it is not part of the globals list. Use {!Cil.getGlobInit}
* to create/get one. *)
mutable globinitcalled: bool;
* Whether the global initialization function is called in main . This
* should always be false if there is no global initializer . When you
* create a global initialization CIL will try to insert code in main
* to call it . This will not happen if your file does not contain a
* function called " main "
* should always be false if there is no global initializer. When you
* create a global initialization CIL will try to insert code in main
* to call it. This will not happen if your file does not contain a
* function called "main" *)
}
(** Top-level representation of a C source file *)
and comment = location * string
(** {b Globals}. The main type for representing global declarations and
* definitions. A list of these form a CIL file. The order of globals in the
* file is generally important. *)
(** A global declaration or definition *)
and global =
| GType of typeinfo * location
(** A typedef. All uses of type names (through the [TNamed] constructor)
must be preceded in the file by a definition of the name. The string
is the defined name and always not-empty. *)
| GCompTag of compinfo * location
* Defines a struct / union tag with some fields . There must be one of
these for each struct / union tag that you use ( through the [ TComp ]
constructor ) since this is the only context in which the fields are
printed . Consequently nested structure tag definitions must be
broken into individual definitions with the innermost structure
defined first .
these for each struct/union tag that you use (through the [TComp]
constructor) since this is the only context in which the fields are
printed. Consequently nested structure tag definitions must be
broken into individual definitions with the innermost structure
defined first. *)
| GCompTagDecl of compinfo * location
(** Declares a struct/union tag. Use as a forward declaration. This is
* printed without the fields. *)
| GEnumTag of enuminfo * location
(** Declares an enumeration tag with some fields. There must be one of
these for each enumeration tag that you use (through the [TEnum]
constructor) since this is the only context in which the items are
printed. *)
| GEnumTagDecl of enuminfo * location
(** Declares an enumeration tag. Use as a forward declaration. This is
* printed without the items. *)
| GVarDecl of varinfo * location
* A variable declaration ( not a definition ) . If the variable has a
function type then this is a prototype . There can be several
declarations and at most one definition for a given variable . If both
forms appear then they must share the same varinfo structure . A
prototype shares the varinfo with the fundec of the definition . Either
has storage Extern or there must be a definition in this file
function type then this is a prototype. There can be several
declarations and at most one definition for a given variable. If both
forms appear then they must share the same varinfo structure. A
prototype shares the varinfo with the fundec of the definition. Either
has storage Extern or there must be a definition in this file *)
| GVar of varinfo * initinfo * location
* A variable definition . Can have an initializer . The initializer is
* updateable so that you can change it without requiring to recreate
* the list of globals . There can be at most one definition for a
* variable in an entire program . Can not have storage Extern or function
* type .
* updateable so that you can change it without requiring to recreate
* the list of globals. There can be at most one definition for a
* variable in an entire program. Cannot have storage Extern or function
* type. *)
| GFun of fundec * location
(** A function definition. *)
| GAsm of string * location (** Global asm statement. These ones
can contain only a template *)
* at top level . Use the same
syntax as attributes
syntax as attributes *)
| GText of string (** Some text (printed verbatim) at
top level. E.g., this way you can
put comments in the output. *)
| GHipProgSpec of Iast.prog_decl * location (** HIP prog *)
* { b Types } . A C type is represented in CIL using the type { ! Cil.typ } .
* Among types we differentiate the integral types ( with different kinds
* denoting the sign and precision ) , floating point types , enumeration types ,
* array and pointer types , and function types . Every type is associated with
* a list of attributes , which are always kept in sorted order . Use
* { ! Cil.addAttribute } and { ! Cil.addAttributes } to construct list of
* attributes . If you want to inspect a type , you should use
* { ! } or { ! Cil.unrollTypeDeep } to see through the uses of
* named types .
* Among types we differentiate the integral types (with different kinds
* denoting the sign and precision), floating point types, enumeration types,
* array and pointer types, and function types. Every type is associated with
* a list of attributes, which are always kept in sorted order. Use
* {!Cil.addAttribute} and {!Cil.addAttributes} to construct list of
* attributes. If you want to inspect a type, you should use
* {!Cil.unrollType} or {!Cil.unrollTypeDeep} to see through the uses of
* named types. *)
* CIL is configured at build - time with the sizes and alignments of the
* underlying compiler ( GCC or MSVC ) . CIL contains functions that can compute
* the size of a type ( in bits ) { ! } , the alignment of a type
* ( in bytes ) { ! Cil.alignOf_int } , and can convert an offset into a start and
* width ( both in bits ) using the function { ! Cil.bitsOffset } . At the moment
* these functions do not take into account the [ packed ] attributes and
* pragmas .
* underlying compiler (GCC or MSVC). CIL contains functions that can compute
* the size of a type (in bits) {!Cil.bitsSizeOf}, the alignment of a type
* (in bytes) {!Cil.alignOf_int}, and can convert an offset into a start and
* width (both in bits) using the function {!Cil.bitsOffset}. At the moment
* these functions do not take into account the [packed] attributes and
* pragmas. *)
and typ =
TVoid of attributes (** Void type. Also predefined as {!Cil.voidType} *)
| TInt of ikind * attributes
* An integer type . The kind specifies the sign and width . Several
* useful variants are predefined as { ! Cil.intType } , { ! Cil.uintType } ,
* { ! Cil.longType } , { ! Cil.charType } .
* useful variants are predefined as {!Cil.intType}, {!Cil.uintType},
* {!Cil.longType}, {!Cil.charType}. *)
| TFloat of fkind * attributes
(** A floating-point type. The kind specifies the precision. You can
* also use the predefined constant {!Cil.doubleType}. *)
| TPtr of typ * attributes
* Pointer type . Several useful variants are predefined as
* { ! Cil.charPtrType } , { ! } ( pointer to a
* constant character ) , { ! } ,
* { ! Cil.intPtrType }
* {!Cil.charPtrType}, {!Cil.charConstPtrType} (pointer to a
* constant character), {!Cil.voidPtrType},
* {!Cil.intPtrType} *)
| TArray of typ * exp option * attributes
(** Array type. It indicates the base type and the array length. *)
| TFun of typ * (string * typ * attributes) list option * bool * attributes
(** Function type. Indicates the type of the result, the name, type
* and name attributes of the formal arguments ([None] if no
* arguments were specified, as in a function whose definition or
* prototype we have not seen; [Some \[\]] means void). Use
* {!Cil.argsToList} to obtain a list of arguments. The boolean
* indicates if it is a variable-argument function. If this is the
* type of a varinfo for which we have a function declaration then
* the information for the formals must match that in the
* function's sformals. Use {!Cil.setFormals}, or
* {!Cil.setFunctionType}, or {!Cil.makeFormalVar} for this
* purpose. *)
| TNamed of typeinfo * attributes
* The use of a named type . Each such type name must be preceded
* in the file by a [ GType ] global . This is printed as just the
* type name . The actual referred type is not printed here and is
* carried only to simplify processing . To see through a sequence
* of named type references , use { ! } or
* { ! Cil.unrollTypeDeep } . The attributes are in addition to those
* given when the type name was defined .
* in the file by a [GType] global. This is printed as just the
* type name. The actual referred type is not printed here and is
* carried only to simplify processing. To see through a sequence
* of named type references, use {!Cil.unrollType} or
* {!Cil.unrollTypeDeep}. The attributes are in addition to those
* given when the type name was defined. *)
| TComp of compinfo * attributes
* The most delicate issue for C types is that recursion that is possible by
* using structures and pointers . To address this issue we have a more
* complex representation for structured types ( struct and union ) . Each such
* type is represented using the { ! } type . For each composite
* type the { ! } structure must be declared at top level using
* [ GCompTag ] and all references to it must share the same copy of the
* structure . The attributes given are those pertaining to this use of the
* type and are in addition to the attributes that were given at the
* definition of the type and which are stored in the { ! } .
* using structures and pointers. To address this issue we have a more
* complex representation for structured types (struct and union). Each such
* type is represented using the {!Cil.compinfo} type. For each composite
* type the {!Cil.compinfo} structure must be declared at top level using
* [GCompTag] and all references to it must share the same copy of the
* structure. The attributes given are those pertaining to this use of the
* type and are in addition to the attributes that were given at the
* definition of the type and which are stored in the {!Cil.compinfo}. *)
| TEnum of enuminfo * attributes
(** A reference to an enumeration type. All such references must
share the enuminfo among them and with a [GEnumTag] global that
precedes all uses. The attributes refer to this use of the
enumeration and are in addition to the attributes of the
enumeration itself, which are stored inside the enuminfo *)
| TBuiltin_va_list of attributes
(** This is the same as the gcc's type with the same name *)
*
There are a number of functions for querying the kind of a type . These are
{ ! Cil.isIntegralType } ,
{ ! Cil.isArithmeticType } ,
{ ! Cil.isPointerType } ,
{ ! } ,
{ ! } ,
{ ! } .
There are two easy ways to scan a type . First , you can use the
{ ! to return a boolean answer about a type . This function
is controlled by a user - provided function that is queried for each type that is
used to construct the current type . The function can specify whether to
terminate the scan with a boolean result or to continue the scan for the
nested types .
The other method for scanning types is provided by the visitor interface ( see
{ ! Cil.cilVisitor } ) .
If you want to compare types ( or to use them as hash - values ) then you should
use instead type signatures ( represented as { ! Cil.typsig } ) . These
contain the same information as types but canonicalized such that simple Ocaml
structural equality will tell whether two types are equal . Use
{ ! Cil.typeSig } to compute the signature of a type . If you want to ignore
certain type attributes then use { ! Cil.typeSigWithAttrs } .
There are a number of functions for querying the kind of a type. These are
{!Cil.isIntegralType},
{!Cil.isArithmeticType},
{!Cil.isPointerType},
{!Cil.isScalarType},
{!Cil.isFunctionType},
{!Cil.isArrayType}.
There are two easy ways to scan a type. First, you can use the
{!Cil.existsType} to return a boolean answer about a type. This function
is controlled by a user-provided function that is queried for each type that is
used to construct the current type. The function can specify whether to
terminate the scan with a boolean result or to continue the scan for the
nested types.
The other method for scanning types is provided by the visitor interface (see
{!Cil.cilVisitor}).
If you want to compare types (or to use them as hash-values) then you should
use instead type signatures (represented as {!Cil.typsig}). These
contain the same information as types but canonicalized such that simple Ocaml
structural equality will tell whether two types are equal. Use
{!Cil.typeSig} to compute the signature of a type. If you want to ignore
certain type attributes then use {!Cil.typeSigWithAttrs}.
*)
(** Various kinds of integers *)
and ikind =
IChar (** [char] *)
| ISChar (** [signed char] *)
| IUChar (** [unsigned char] *)
* [ _ ( C99 ) ]
| IInt (** [int] *)
| IUInt (** [unsigned int] *)
| IShort (** [short] *)
| IUShort (** [unsigned short] *)
| ILong (** [long] *)
| IULong (** [unsigned long] *)
* [ long long ] ( or [ _ int64 ] on Microsoft Visual C )
* [ unsigned long long ] ( or [ unsigned _ int64 ] on Microsoft
Visual C )
Visual C) *)
(** Various kinds of floating-point numbers*)
and fkind =
FFloat (** [float] *)
| FDouble (** [double] *)
| FLongDouble (** [long double] *)
(** {b Attributes.} *)
and attribute = Attr of string * attrparam list
(** An attribute has a name and some optional parameters. The name should not
* start or end with underscore. When CIL parses attribute names it will
* strip leading and ending underscores (to ensure that the multitude of GCC
* attributes such as const, __const and __const__ all mean the same thing.) *)
(** Attributes are lists sorted by the attribute name. Use the functions
* {!Cil.addAttribute} and {!Cil.addAttributes} to insert attributes in an
* attribute list and maintain the sortedness. *)
and attributes = attribute list
(** The type of parameters of attributes *)
and attrparam =
| AInt of int (** An integer constant *)
| AStr of string (** A string constant *)
| ACons of string * attrparam list (** Constructed attributes. These
are printed [foo(a1,a2,...,an)].
The list of parameters can be
empty and in that case the
parentheses are not printed. *)
| ASizeOf of typ (** A way to talk about types *)
| ASizeOfE of attrparam
| ASizeOfS of typsig (** Replacement for ASizeOf in type
signatures. Only used for
attributes inside typsigs.*)
| AAlignOf of typ
| AAlignOfE of attrparam
| AAlignOfS of typsig
| AUnOp of unop * attrparam
| ABinOp of binop * attrparam * attrparam
| ADot of attrparam * string (** a.foo **)
| AStar of attrparam (** * a *)
| AAddrOf of attrparam (** & a **)
| AIndex of attrparam * attrparam (** a1[a2] *)
| AQuestion of attrparam * attrparam * attrparam (** a1 ? a2 : a3 **)
* { b Structures . } The { ! } describes the definition of a
* structure or union type . Each such { ! } must be defined at the
* top - level using the [ GCompTag ] constructor and must be shared by all
* references to this type ( using either the [ TComp ] type constructor or from
* the definition of the fields .
If all you need is to scan the definition of each
* composite type once , you can do that by scanning all top - level [ GCompTag ] .
* Constructing a { ! } can be tricky since it must contain fields
* that might refer to the host { ! } and furthermore the type of
* the field might need to refer to the { ! } for recursive types .
* Use the { ! Cil.mkCompInfo } function to create a { ! } . You can
* easily fetch the { ! Cil.fieldinfo } for a given field in a structure with
* { ! Cil.getCompField } .
* structure or union type. Each such {!Cil.compinfo} must be defined at the
* top-level using the [GCompTag] constructor and must be shared by all
* references to this type (using either the [TComp] type constructor or from
* the definition of the fields.
If all you need is to scan the definition of each
* composite type once, you can do that by scanning all top-level [GCompTag].
* Constructing a {!Cil.compinfo} can be tricky since it must contain fields
* that might refer to the host {!Cil.compinfo} and furthermore the type of
* the field might need to refer to the {!Cil.compinfo} for recursive types.
* Use the {!Cil.mkCompInfo} function to create a {!Cil.compinfo}. You can
* easily fetch the {!Cil.fieldinfo} for a given field in a structure with
* {!Cil.getCompField}. *)
* The definition of a structure or union type . Use { ! Cil.mkCompInfo } to
* make one and use { ! Cil.copyCompInfo } to copy one ( this ensures that a new
* key is assigned and that the fields have the right pointers to parents . ) .
* make one and use {!Cil.copyCompInfo} to copy one (this ensures that a new
* key is assigned and that the fields have the right pointers to parents.). *)
and compinfo = {
mutable cstruct: bool;
(** True if struct, False if union *)
mutable cname: string;
(** The name. Always non-empty. Use {!Cil.compFullName} to get the full
* name of a comp (along with the struct or union) *)
mutable ckey: int;
* A unique integer . This is assigned by { ! Cil.mkCompInfo } using a
* global variable in the module . Thus two identical structs in two
* different files might have different keys . Use { ! Cil.copyCompInfo } to
* copy structures so that a new key is assigned .
* global variable in the Cil module. Thus two identical structs in two
* different files might have different keys. Use {!Cil.copyCompInfo} to
* copy structures so that a new key is assigned. *)
mutable cfields: fieldinfo list;
* Information about the fields . Notice that each fieldinfo has a
* pointer back to the host compinfo . This means that you should not
* share 's between two compinfo 's
* pointer back to the host compinfo. This means that you should not
* share fieldinfo's between two compinfo's *)
mutable cattr: attributes;
* The attributes that are defined at the same time as the composite
* type . These attributes can be supplemented individually at each
* reference to this [ compinfo ] using the [ TComp ] type constructor .
* type. These attributes can be supplemented individually at each
* reference to this [compinfo] using the [TComp] type constructor. *)
mutable cdefined: bool;
(** This boolean flag can be used to distinguish between structures
that have not been defined and those that have been defined but have
no fields (such things are allowed in gcc). *)
mutable creferenced: bool;
(** True if used. Initially set to false. *)
}
* { b Structure fields . } The { ! Cil.fieldinfo } structure is used to describe
* a structure or union field . , just like variables , can have
* attributes associated with the field itself or associated with the type of
* the field ( stored along with the type of the field ) .
* a structure or union field. Fields, just like variables, can have
* attributes associated with the field itself or associated with the type of
* the field (stored along with the type of the field). *)
(** Information about a struct/union field *)
and fieldinfo = {
mutable fcomp: compinfo;
* The host structure that contains this field . There can be only one
* [ compinfo ] that contains the field .
* [compinfo] that contains the field. *)
mutable fname: string;
(** The name of the field. Might be the value of {!Cil.missingFieldName}
* in which case it must be a bitfield and is not printed and it does not
* participate in initialization *)
mutable ftype: typ;
(** The type *)
mutable fbitfield: int option;
* If a bitfield then ftype should be an integer type and the width of
* the bitfield must be 0 or a positive integer smaller or equal to the
* width of the integer type . A field of width 0 is used in C to control
* the alignment of fields .
* the bitfield must be 0 or a positive integer smaller or equal to the
* width of the integer type. A field of width 0 is used in C to control
* the alignment of fields. *)
mutable fattr: attributes;
(** The attributes for this field (not for its type) *)
mutable fdefn: location;
(** The location where this field is defined *)
}
(** {b Enumerations.} Information about an enumeration. This is shared by all
* references to an enumeration. Make sure you have a [GEnumTag] for each of
* of these. *)
(** Information about an enumeration *)
and enuminfo = {
mutable ename: string;
(** The name. Always non-empty. *)
mutable eitems: (string * exp * location) list;
(** Items with names and values. This list should be non-empty. The item
* values must be compile-time constants. *)
mutable eattr: attributes;
(** The attributes that are defined at the same time as the enumeration
* type. These attributes can be supplemented individually at each
* reference to this [enuminfo] using the [TEnum] type constructor. *)
mutable ereferenced: bool;
(** True if used. Initially set to false*)
mutable ekind: ikind;
* The integer kind used to represent this enum . Per ANSI - C , this
* should always be IInt , but gcc allows other integer kinds
* should always be IInt, but gcc allows other integer kinds *)
}
(** {b Enumerations.} Information about an enumeration. This is shared by all
* references to an enumeration. Make sure you have a [GEnumTag] for each of
* of these. *)
(** Information about a defined type *)
and typeinfo = {
mutable tname: string;
* The name . Can be empty only in a [ GType ] when introducing a composite
* or enumeration tag . If empty can not be referred to from the file
* or enumeration tag. If empty cannot be referred to from the file *)
mutable ttype: typ;
(** The actual type. This includes the attributes that were present in
* the typedef *)
mutable treferenced: bool;
(** True if used. Initially set to false*)
}
* { b Variables . }
Each local or global variable is represented by a unique { ! Cil.varinfo }
structure . A global { ! Cil.varinfo } can be introduced with the [ GVarDecl ] or
[ GVar ] or [ GFun ] globals . A local varinfo can be introduced as part of a
function definition { ! Cil.fundec } .
All references to a given global or local variable must refer to the same
copy of the [ varinfo ] . Each [ varinfo ] has a globally unique identifier that
can be used to index maps and hashtables ( the name can also be used for this
purpose , except for locals from different functions ) . This identifier is
constructor using a global counter .
It is very important that you construct [ varinfo ] structures using only one
of the following functions :
- { ! Cil.makeGlobalVar } : to make a global variable
- { ! } : to make a temporary local variable whose name
will be generated so that to avoid conflict with other locals .
- { ! } : like { ! } but you can specify the
exact name to be used .
- { ! Cil.copyVarinfo } : make a shallow copy of a varinfo assigning a new name
and a new unique identifier
A [ varinfo ] is also used in a function type to denote the list of formals .
Each local or global variable is represented by a unique {!Cil.varinfo}
structure. A global {!Cil.varinfo} can be introduced with the [GVarDecl] or
[GVar] or [GFun] globals. A local varinfo can be introduced as part of a
function definition {!Cil.fundec}.
All references to a given global or local variable must refer to the same
copy of the [varinfo]. Each [varinfo] has a globally unique identifier that
can be used to index maps and hashtables (the name can also be used for this
purpose, except for locals from different functions). This identifier is
constructor using a global counter.
It is very important that you construct [varinfo] structures using only one
of the following functions:
- {!Cil.makeGlobalVar} : to make a global variable
- {!Cil.makeTempVar} : to make a temporary local variable whose name
will be generated so that to avoid conflict with other locals.
- {!Cil.makeLocalVar} : like {!Cil.makeTempVar} but you can specify the
exact name to be used.
- {!Cil.copyVarinfo}: make a shallow copy of a varinfo assigning a new name
and a new unique identifier
A [varinfo] is also used in a function type to denote the list of formals.
*)
(** Information about a variable. *)
and varinfo = {
mutable vname: string;
* The name of the variable . Can not be empty . It is primarily your
* responsibility to ensure the uniqueness of a variable name . For local
* variables { ! Cil.makeTempVar } helps you ensure that the name is unique .
* responsibility to ensure the uniqueness of a variable name. For local
* variables {!Cil.makeTempVar} helps you ensure that the name is unique.
*)
mutable vtype: typ;
(** The declared type of the variable. *)
mutable vattr: attributes;
(** A list of attributes associated with the variable.*)
mutable vstorage: storage;
(** The storage-class *)
mutable vglob: bool;
(** True if this is a global variable*)
mutable vinline: bool;
(** Whether this varinfo is for an inline function. *)
mutable vdecl: location;
(** Location of variable declaration. *)
mutable vid: int;
* A unique integer identifier . This field will be
* set for you if you use one of the { ! Cil.makeFormalVar } ,
* { ! } , { ! } , { ! Cil.makeGlobalVar } , or
* { ! Cil.copyVarinfo } .
* set for you if you use one of the {!Cil.makeFormalVar},
* {!Cil.makeLocalVar}, {!Cil.makeTempVar}, {!Cil.makeGlobalVar}, or
* {!Cil.copyVarinfo}. *)
mutable vaddrof: bool;
* True if the address of this variable is taken . CIL will set these
* flags when it parses C , but you should make sure to set the flag
* whenever your transformation create [ ] expression .
* flags when it parses C, but you should make sure to set the flag
* whenever your transformation create [AddrOf] expression. *)
mutable vreferenced: bool;
* True if this variable is ever referenced . This is computed by
* { ! } . It is safe to just initialize this to False
* {!Rmtmps.removeUnusedTemps}. It is safe to just initialize this to False *)
mutable vdescr: Pretty.doc;
(** For most temporary variables, a description of what the var holds.
* (e.g. for temporaries used for function call results, this string
* is a representation of the function call.) *)
mutable vdescrpure: bool;
* Indicates whether the vdescr above is a pure expression or call .
* Printing a non - pure vdescr more than once may yield incorrect
* results .
* Printing a non-pure vdescr more than once may yield incorrect
* results. *)
}
(** Storage-class information *)
and storage =
NoStorage (** The default storage. Nothing is printed *)
| Static
| Register
| Extern
* { b Expressions . } The CIL expression language contains only the side - effect free expressions of
C. They are represented as the type { ! Cil.exp } . There are several
interesting aspects of CIL expressions :
Integer and floating point constants can carry their textual representation .
This way the integer 15 can be printed as 0xF if that is how it occurred in the
source .
CIL uses 64 bits to represent the integer constants and also stores the width
of the integer type . Care must be taken to ensure that the constant is
representable with the given width . Use the functions { ! Cil.kinteger } ,
{ ! Cil.kinteger64 } and { ! Cil.integer } to construct constant
expressions . CIL predefines the constants { ! Cil.zero } ,
{ ! Cil.one } and { ! Cil.mone } ( for -1 ) .
Use the functions { ! Cil.isConstant } and { ! Cil.isInteger } to test if
an expression is a constant and a constant integer respectively .
CIL keeps the type of all unary and binary expressions . You can think of that
type qualifying the operator . Furthermore there are different operators for
arithmetic and comparisons on arithmetic types and on pointers .
Another unusual aspect of CIL is that the implicit conversion between an
expression of array type and one of pointer type is made explicit , using the
[ StartOf ] expression constructor ( which is not printed ) . If you apply the
[ AddrOf}]constructor to an lvalue of type [ T ] then you will be getting an
expression of type [ TPtr(T ) ] .
You can find the type of an expression with { ! Cil.typeOf } .
You can perform constant folding on expressions using the function
{ ! } .
C. They are represented as the type {!Cil.exp}. There are several
interesting aspects of CIL expressions:
Integer and floating point constants can carry their textual representation.
This way the integer 15 can be printed as 0xF if that is how it occurred in the
source.
CIL uses 64 bits to represent the integer constants and also stores the width
of the integer type. Care must be taken to ensure that the constant is
representable with the given width. Use the functions {!Cil.kinteger},
{!Cil.kinteger64} and {!Cil.integer} to construct constant
expressions. CIL predefines the constants {!Cil.zero},
{!Cil.one} and {!Cil.mone} (for -1).
Use the functions {!Cil.isConstant} and {!Cil.isInteger} to test if
an expression is a constant and a constant integer respectively.
CIL keeps the type of all unary and binary expressions. You can think of that
type qualifying the operator. Furthermore there are different operators for
arithmetic and comparisons on arithmetic types and on pointers.
Another unusual aspect of CIL is that the implicit conversion between an
expression of array type and one of pointer type is made explicit, using the
[StartOf] expression constructor (which is not printed). If you apply the
[AddrOf}]constructor to an lvalue of type [T] then you will be getting an
expression of type [TPtr(T)].
You can find the type of an expression with {!Cil.typeOf}.
You can perform constant folding on expressions using the function
{!Cil.constFold}.
*)
(** Expressions (Side-effect free)*)
and exp =
Const of constant * location (** Constant *)
*
| SizeOf of typ * location
(** sizeof(<type>). Has [unsigned int] type (ISO 6.5.3.4). This is not
* turned into a constant because some transformations might want to
* change types *)
| SizeOfE of exp * location
(** sizeof(<expression>) *)
| SizeOfStr of string * location
(** sizeof(string_literal). We separate this case out because this is the
* only instance in which a string literal should not be treated as
* having type pointer to character. *)
| AlignOf of typ * location
(** This corresponds to the GCC __alignof_. Has [unsigned int] type *)
| AlignOfE of exp * location
| UnOp of unop * exp * typ * location
(** Unary operation. Includes the type of the result. *)
| BinOp of binop * exp * exp * typ * location
(** Binary operation. Includes the type of the result. The arithmetic
* conversions are made explicit for the arguments. *)
| Question of exp * exp * exp * typ * location
(** (a ? b : c) operation. Includes the type of the result *)
| CastE of typ * exp * location
(** Use {!Cil.mkCast} to make casts. *)
| AddrOf of lval * location
* Always use { ! Cil.mkAddrOf } to construct one of these . Apply to an
* lvalue of type [ T ] yields an expression of type [ TPtr(T ) ] . Use
* { ! Cil.mkAddrOrStartOf } to make one of these if you are not sure which
* one to use .
* lvalue of type [T] yields an expression of type [TPtr(T)]. Use
* {!Cil.mkAddrOrStartOf} to make one of these if you are not sure which
* one to use. *)
| StartOf of lval * location
* Conversion from an array to a pointer to the beginning of the array .
* Given an lval of type [ TArray(T ) ] produces an expression of type
* [ TPtr(T ) ] . Use { ! Cil.mkAddrOrStartOf } to make one of these if you are
* not sure which one to use . In C this operation is implicit , the
* [ StartOf ] operator is not printed . We have it in CIL because it makes
* the typing rules simpler .
* Given an lval of type [TArray(T)] produces an expression of type
* [TPtr(T)]. Use {!Cil.mkAddrOrStartOf} to make one of these if you are
* not sure which one to use. In C this operation is implicit, the
* [StartOf] operator is not printed. We have it in CIL because it makes
* the typing rules simpler. *)
(** {b Constants.} *)
(** Literal constants *)
and constant =
| CInt64 of int64 * ikind * string option
* Integer constant . Give the ikind ( see ISO9899 6.1.3.2 ) and the
* textual representation , if available . ( This allows us to print a
* constant as , for example , 0xF instead of 15 . ) Use { ! Cil.integer } or
* { ! Cil.kinteger } to create these . Watch out for integers that can not be
* represented on 64 bits . OCAML does not give Overflow exceptions .
* textual representation, if available. (This allows us to print a
* constant as, for example, 0xF instead of 15.) Use {!Cil.integer} or
* {!Cil.kinteger} to create these. Watch out for integers that cannot be
* represented on 64 bits. OCAML does not give Overflow exceptions. *)
| CStr of string
(** String constant. The escape characters inside the string have been
* already interpreted. This constant has pointer to character type! The
* only case when you would like a string literal to have an array type
* is when it is an argument to sizeof. In that case you should use
* SizeOfStr. *)
| CWStr of int64 list
* Wide character string constant . Note that the local interpretation
* of such a literal depends on { ! } and { ! } .
* Such a constant has type pointer to { ! } . The
* escape characters in the string have not been " interpreted " in
* the sense that L"A\xabcd " remains " A\xabcd " rather than being
* represented as the wide character list with two elements : 65 and
* 43981 . That " interpretation " depends on the underlying wide
* character type .
* of such a literal depends on {!Cil.wcharType} and {!Cil.wcharKind}.
* Such a constant has type pointer to {!Cil.wcharType}. The
* escape characters in the string have not been "interpreted" in
* the sense that L"A\xabcd" remains "A\xabcd" rather than being
* represented as the wide character list with two elements: 65 and
* 43981. That "interpretation" depends on the underlying wide
* character type. *)
| CChr of char
* Character constant . This has type int , so use charConstToInt
* to read the value in case sign - extension is needed .
* to read the value in case sign-extension is needed. *)
| CReal of float * fkind * string option
* Floating point constant . Give the fkind ( see ISO 6.4.4.2 ) and also
* the textual representation , if available .
* the textual representation, if available. *)
| CEnum of exp * string * enuminfo
(** An enumeration constant with the given value, name, from the given
* enuminfo. This is used only if {!Cil.lowerConstants} is true
* (default). Use {!Cil.constFoldVisitor} to replace these with integer
* constants. *)
(** Unary operators *)
and unop =
Neg (** Unary minus *)
| BNot (** Bitwise complement (~) *)
| LNot (** Logical Not (!) *)
(** Binary operations *)
and binop =
PlusA (** arithmetic + *)
| PlusPI (** pointer + integer *)
| IndexPI (** pointer + integer but only when
* it arises from an expression
* [e\[i\]] when [e] is a pointer and
* not an array. This is semantically
* the same as PlusPI but CCured uses
* this as a hint that the integer is
* probably positive. *)
| MinusA (** arithmetic - *)
| MinusPI (** pointer - integer *)
| MinusPP (** pointer - pointer *)
| Mult (** * *)
| Div (** / *)
| Mod (** % *)
| Shiftlt (** shift left *)
| Shiftrt (** shift right *)
| Lt (** < (arithmetic comparison) *)
| Gt (** > (arithmetic comparison) *)
| Le (** <= (arithmetic comparison) *)
| Ge (** > (arithmetic comparison) *)
| Eq (** == (arithmetic comparison) *)
| Ne (** != (arithmetic comparison) *)
| BAnd (** bitwise and *)
| BXor (** exclusive-or *)
| BOr (** inclusive-or *)
| LAnd (** logical and. Unlike other
* expressions this one does not
* always evaluate both operands. If
* you want to use these, you must
* set {!Cil.useLogicalOperators}. *)
| LOr (** logical or. Unlike other
* expressions this one does not
* always evaluate both operands. If
* you want to use these, you must
* set {!Cil.useLogicalOperators}. *)
* { b Lvalues . } Lvalues are the sublanguage of expressions that can appear at the left of an assignment or as operand to the address - of operator .
In C the syntax for is not always a good indication of the meaning
of the lvalue . For example the C value
{ v
]
v }
might involve 1 , 2 or 3 memory reads when used in an expression context ,
depending on the declared type of the variable [ a ] . If [ a ] has type [ int
\[4\]\[4\]\[4\ ] ] then we have one memory read from somewhere inside the area
that stores the array [ a ] . On the other hand if [ a ] has type [ int * * * ] then
the expression really means [ * ( * ( * ( a + 0 ) + 1 ) + 2 ) ] , in which case it is
clear that it involves three separate memory operations .
An lvalue denotes the contents of a range of memory addresses . This range
is denoted as a host object along with an offset within the object . The
host object can be of two kinds : a local or global variable , or an object
whose address is in a pointer expression . We distinguish the two cases so
that we can tell quickly whether we are accessing some component of a
variable directly or we are accessing a memory location through a pointer .
To make it easy to
tell what an lvalue means CIL represents as a host object and an
offset ( see { ! Cil.lval } ) . The host object ( represented as
{ ! Cil.lhost } ) can be a local or global variable or can be the object
pointed - to by a pointer expression . The offset ( represented as
{ ! Cil.offset } ) is a sequence of field or array index designators .
Both the typing rules and the meaning of an lvalue is very precisely
specified in CIL .
The following are a few useful function for operating on lvalues :
- { ! Cil.mkMem } - makes an lvalue of [ Mem ] kind . Use this to ensure
that certain equivalent forms of are canonized .
For example , [ * & x = x ] .
- { ! Cil.typeOfLval } - the type of an lvalue
- { ! Cil.typeOffset } - the type of an offset , given the type of the
host .
- { ! Cil.addOffset } and { ! Cil.addOffsetLval } - extend sequences
of offsets .
- { ! Cil.removeOffset } and { ! Cil.removeOffsetLval } - shrink sequences
of offsets .
The following equivalences hold { v
a , aoff ) ) , off = Mem a , aoff + off
Mem(AddrOf(Var v , aoff ) ) , off = v , aoff + off
( Mem a , NoOffset ) = a
v }
In C the syntax for lvalues is not always a good indication of the meaning
of the lvalue. For example the C value
{v
a[0][1][2]
v}
might involve 1, 2 or 3 memory reads when used in an expression context,
depending on the declared type of the variable [a]. If [a] has type [int
\[4\]\[4\]\[4\]] then we have one memory read from somewhere inside the area
that stores the array [a]. On the other hand if [a] has type [int ***] then
the expression really means [* ( * ( * (a + 0) + 1) + 2)], in which case it is
clear that it involves three separate memory operations.
An lvalue denotes the contents of a range of memory addresses. This range
is denoted as a host object along with an offset within the object. The
host object can be of two kinds: a local or global variable, or an object
whose address is in a pointer expression. We distinguish the two cases so
that we can tell quickly whether we are accessing some component of a
variable directly or we are accessing a memory location through a pointer.
To make it easy to
tell what an lvalue means CIL represents lvalues as a host object and an
offset (see {!Cil.lval}). The host object (represented as
{!Cil.lhost}) can be a local or global variable or can be the object
pointed-to by a pointer expression. The offset (represented as
{!Cil.offset}) is a sequence of field or array index designators.
Both the typing rules and the meaning of an lvalue is very precisely
specified in CIL.
The following are a few useful function for operating on lvalues:
- {!Cil.mkMem} - makes an lvalue of [Mem] kind. Use this to ensure
that certain equivalent forms of lvalues are canonized.
For example, [*&x = x].
- {!Cil.typeOfLval} - the type of an lvalue
- {!Cil.typeOffset} - the type of an offset, given the type of the
host.
- {!Cil.addOffset} and {!Cil.addOffsetLval} - extend sequences
of offsets.
- {!Cil.removeOffset} and {!Cil.removeOffsetLval} - shrink sequences
of offsets.
The following equivalences hold {v
Mem(AddrOf(Mem a, aoff)), off = Mem a, aoff + off
Mem(AddrOf(Var v, aoff)), off = Var v, aoff + off
AddrOf (Mem a, NoOffset) = a
v}
*)
(** An lvalue *)
and lval =
lhost * offset * location
(** The host part of an {!Cil.lval}. *)
and lhost =
| Var of varinfo * location
(** The host is a variable. *)
| Mem of exp
* The host is an object of type [ T ] when the expression has pointer
* [ TPtr(T ) ] .
* [TPtr(T)]. *)
* The offset part of an { ! Cil.lval } . Each offset can be applied to certain
* kinds of lvalues and its effect is that it advances the starting address
* of the lvalue and changes the denoted type , essentially focusing to some
* smaller lvalue that is contained in the original one .
* kinds of lvalues and its effect is that it advances the starting address
* of the lvalue and changes the denoted type, essentially focusing to some
* smaller lvalue that is contained in the original one. *)
and offset =
| NoOffset (** No offset. Can be applied to any lvalue and does
* not change either the starting address or the type.
* This is used when the lval consists of just a host
* or as a terminator in a list of other kinds of
* offsets. *)
| Field of (fieldinfo * location) * offset * location
(** A field offset. Can be applied only to an lvalue
* that denotes a structure or a union that contains
* the mentioned field. This advances the offset to the
* beginning of the mentioned field and changes the
* type to the type of the mentioned field. *)
| Index of exp * offset * location
(** An array index offset. Can be applied only to an
* lvalue that denotes an array. This advances the
* starting address of the lval to the beginning of the
* mentioned array element and changes the denoted type
* to be the type of the array element *)
* { b Initializers . } A special kind of expressions are those that can appear
* as initializers for global variables ( initialization of local variables is
* turned into assignments ) . The initializers are represented as type
* { ! } . You can create initializers with { ! Cil.makeZeroInit } and you
* can conveniently scan compound initializers them with
* { ! } .
* as initializers for global variables (initialization of local variables is
* turned into assignments). The initializers are represented as type
* {!Cil.init}. You can create initializers with {!Cil.makeZeroInit} and you
* can conveniently scan compound initializers them with
* {!Cil.foldLeftCompound}. *)
(** Initializers for global variables. *)
and init =
| SingleInit of exp (** A single initializer *)
| CompoundInit of typ * (offset * init) list
* Used only for initializers of structures , unions and arrays . The
* offsets are all of the form [ Field(f , ) ] or [ Index(i ,
* ) ] and specify the field or the index being initialized . For
* structures all fields must have an initializer ( except the unnamed
* bitfields ) , in the proper order . This is necessary since the offsets
* are not printed . For unions there must be exactly one initializer . If
* the initializer is not for the first field then a field designator is
* printed , so you better be on GCC since MSVC does not understand this .
* For arrays , however , we allow you to give only a prefix of the
* initializers . You can scan an initializer list with
* { ! } .
* offsets are all of the form [Field(f, NoOffset)] or [Index(i,
* NoOffset)] and specify the field or the index being initialized. For
* structures all fields must have an initializer (except the unnamed
* bitfields), in the proper order. This is necessary since the offsets
* are not printed. For unions there must be exactly one initializer. If
* the initializer is not for the first field then a field designator is
* printed, so you better be on GCC since MSVC does not understand this.
* For arrays, however, we allow you to give only a prefix of the
* initializers. You can scan an initializer list with
* {!Cil.foldLeftCompound}. *)
(** We want to be able to update an initializer in a global variable, so we
* define it as a mutable field *)
and initinfo = {
mutable init : init option;
}
(** {b Function definitions.}
A function definition is always introduced with a [GFun] constructor at the
top level. All the information about the function is stored into a
{!Cil.fundec}. Some of the information (e.g. its name, type,
storage, attributes) is stored as a {!Cil.varinfo} that is a field of the
[fundec]. To refer to the function from the expression language you must use
the [varinfo].
The function definition contains, in addition to the body, a list of all the
local variables and separately a list of the formals. Both kind of variables
can be referred to in the body of the function. The formals must also be shared
with the formals that appear in the function type. For that reason, to
manipulate formals you should use the provided functions
{!Cil.makeFormalVar} and {!Cil.setFormals} and {!Cil.makeFormalVar}.
*)
(** Function definitions. *)
and fundec =
{ mutable svar: varinfo;
(** Holds the name and type as a variable, so we can refer to it
* easily from the program. All references to this function either
* in a function call or in a prototype must point to the same
* [varinfo]. *)
mutable sformals: varinfo list;
* Formals . These must be in the same order and with the same
* information as the formal information in the type of the function .
* Use { ! } or
* { ! Cil.setFunctionType } or { ! Cil.makeFormalVar }
* to set these formals and ensure that they
* are reflected in the function type . Do not make copies of these
* because the body refers to them .
* information as the formal information in the type of the function.
* Use {!Cil.setFormals} or
* {!Cil.setFunctionType} or {!Cil.makeFormalVar}
* to set these formals and ensure that they
* are reflected in the function type. Do not make copies of these
* because the body refers to them. *)
mutable slocals: varinfo list;
(** Locals. Does NOT include the sformals. Do not make copies of
* these because the body refers to them. *)
* local i d. Starts at 0 . Used for
* creating the names of new temporary
* variables . Updated by
* { ! } and
* { ! } . You can also use
* { ! Cil.setMaxId } to set it after you
* have added the formals and locals .
* creating the names of new temporary
* variables. Updated by
* {!Cil.makeLocalVar} and
* {!Cil.makeTempVar}. You can also use
* {!Cil.setMaxId} to set it after you
* have added the formals and locals. *)
mutable sbody: block; (** The function body. *)
mutable smaxstmtid: int option; (** max id of a (reachable) statement
* in this function, if we have
* computed it. range = 0 ...
* (smaxstmtid-1). This is computed by
* {!Cil.computeCFGInfo}. *)
mutable sallstmts: stmt list; (** After you call {!Cil.computeCFGInfo}
* this field is set to contain all
* statements in the function *)
mutable hipfuncspec: Iformula.struc_formula; (** static specs of function, used by hip/sleek system *)
}
(** A block is a sequence of statements with the control falling through from
one element to the next *)
and block =
{ mutable battrs: attributes; (** Attributes for the block *)
mutable bstmts: stmt list; (** The statements comprising the block*)
mutable bloc: location;
}
* { b Statements } .
CIL statements are the structural elements that make the CFG . They are
represented using the type { ! Cil.stmt } . Every
statement has a ( possibly empty ) list of labels . The
{ ! Cil.stmtkind } field of a statement indicates what kind of statement it
is .
Use { ! Cil.mkStmt } to make a statement and the fill - in the fields .
CIL also comes with support for control - flow graphs . The [ sid ] field in
[ stmt ] can be used to give unique numbers to statements , and the [ succs ]
and [ preds ] fields can be used to maintain a list of successors and
predecessors for every statement . The CFG information is not computed by
default . Instead you must explicitly use the functions
{ ! Cil.prepareCFG } and { ! Cil.computeCFGInfo } to do it .
CIL statements are the structural elements that make the CFG. They are
represented using the type {!Cil.stmt}. Every
statement has a (possibly empty) list of labels. The
{!Cil.stmtkind} field of a statement indicates what kind of statement it
is.
Use {!Cil.mkStmt} to make a statement and the fill-in the fields.
CIL also comes with support for control-flow graphs. The [sid] field in
[stmt] can be used to give unique numbers to statements, and the [succs]
and [preds] fields can be used to maintain a list of successors and
predecessors for every statement. The CFG information is not computed by
default. Instead you must explicitly use the functions
{!Cil.prepareCFG} and {!Cil.computeCFGInfo} to do it.
*)
(** Statements. *)
and stmt = {
mutable labels: label list;
(** Whether the statement starts with some labels, case statements or
* default statements. *)
mutable skind: stmtkind;
(** The kind of statement *)
mutable sid: int;
* A number ( > = 0 ) that is unique in a function . Filled in only after
* the CFG is computed .
* the CFG is computed. *)
mutable succs: stmt list;
* The successor statements . They can always be computed from the skind
* and the context in which this statement appears . Filled in only after
* the CFG is computed .
* and the context in which this statement appears. Filled in only after
* the CFG is computed. *)
mutable preds: stmt list;
* The inverse of the succs function .
}
(** Labels *)
and label =
Label of string * location * bool
(** A real label. If the bool is "true", the label is from the
* input source program. If the bool is "false", the label was
* created by CIL or some other transformation *)
| Case of exp * location (** A case statement. This expression
* is lowered into a constant if
* {!Cil.lowerConstants} is set to
* true. *)
| Default of location (** A default statement *)
(** The various kinds of control-flow statements statements *)
and stmtkind =
| Instr of instr list
(** A group of instructions that do not contain control flow. Control
* implicitly falls through. *)
| Return of exp option * location
* The return statement . This is a leaf in the CFG .
| Goto of stmt ref * location
* A goto statement . Appears from actual 's in the code or from
* 's that have been inserted during elaboration . The reference
* points to the statement that is the target of the . This means that
* you have to update the reference whenever you replace the target
* statement . The target statement MUST have at least a label .
* goto's that have been inserted during elaboration. The reference
* points to the statement that is the target of the Goto. This means that
* you have to update the reference whenever you replace the target
* statement. The target statement MUST have at least a label. *)
| Break of location
* A break to the end of the nearest enclosing Loop or Switch
| Continue of location
(** A continue to the start of the nearest enclosing [Loop] *)
| If of exp * block * block * location
* A conditional . Two successors , the " then " and the " else " branches .
* Both branches fall - through to the successor of the If statement .
* Both branches fall-through to the successor of the If statement. *)
| Switch of exp * block * (stmt list) * location
(** A switch statement. The statements that implement the cases can be
* reached through the provided list. For each such target you can find
* among its labels what cases it implements. The statements that
* implement the cases are somewhere within the provided [block]. *)
| Loop of block * Iformula.struc_formula * location * (stmt option) * (stmt option)
* A [ while(1 ) ] loop . The termination test is implemented in the body of
* a loop using a [ Break ] statement . If prepareCFG has been called ,
* the first stmt option will point to the stmt containing the continue
* label for this loop and the second will point to the stmt containing
* the break label for this loop .
* a loop using a [Break] statement. If prepareCFG has been called,
* the first stmt option will point to the stmt containing the continue
* label for this loop and the second will point to the stmt containing
* the break label for this loop. *)
| Block of block
(** Just a block of statements. Use it as a way to keep some block
* attributes local *)
* On MSVC we support structured exception handling . This is what you
* might expect . Control can get into the finally block either from the
* end of the body block , or if an exception is thrown .
* might expect. Control can get into the finally block either from the
* end of the body block, or if an exception is thrown. *)
| TryFinally of block * block * location
* On MSVC we support structured exception handling . The try / except
* statement is a bit tricky :
[ _ _ try { blk }
_ _ except ( e ) {
handler
} ]
The argument to _ _ except must be an expression . However , we keep a
list of instructions AND an expression in case you need to make
function calls . We 'll print those as a comma expression . The control
can get to the _ _ except expression only if an exception is thrown .
After that , depending on the value of the expression the control
goes to the handler , propagates the exception , or retries the
exception ! ! !
* statement is a bit tricky:
[__try { blk }
__except (e) {
handler
}]
The argument to __except must be an expression. However, we keep a
list of instructions AND an expression in case you need to make
function calls. We'll print those as a comma expression. The control
can get to the __except expression only if an exception is thrown.
After that, depending on the value of the expression the control
goes to the handler, propagates the exception, or retries the
exception !!!
*)
| TryExcept of block * (instr list * exp) * block * location
| HipStmt of Iast.exp * location
(** {b Instructions}.
An instruction {!Cil.instr} is a statement that has no local
(intraprocedural) control flow. It can be either an assignment,
function call, or an inline assembly instruction. *)
(** Instructions. *)
and instr =
Set of lval * exp * location
(** An assignment. The type of the expression is guaranteed to be the same
* with that of the lvalue *)
| Call of lval option * exp * exp list * location
* A function call with the ( optional ) result placed in an lval . It is
* possible that the returned type of the function is not identical to
* that of the lvalue . In that case a cast is printed . The type of the
* actual arguments are identical to those of the declared formals . The
* number of arguments is the same as that of the declared formals , except
* for vararg functions . This construct is also used to encode a call to
* " _ _ builtin_va_arg " . In this case the second argument ( which should be a
* type T ) is encoded SizeOf(T )
* possible that the returned type of the function is not identical to
* that of the lvalue. In that case a cast is printed. The type of the
* actual arguments are identical to those of the declared formals. The
* number of arguments is the same as that of the declared formals, except
* for vararg functions. This construct is also used to encode a call to
* "__builtin_va_arg". In this case the second argument (which should be a
* type T) is encoded SizeOf(T) *)
| Asm of attributes * (* Really only const and volatile can appear
* here *)
string list * (* templates (CR-separated) *)
(string option * string * lval) list *
outputs must be lvals with
* optional names and constraints .
* I would like these
* to be actually variables , but I
* run into some trouble with ASMs
* in the Linux sources
* optional names and constraints.
* I would like these
* to be actually variables, but I
* run into some trouble with ASMs
* in the Linux sources *)
(string option * string * exp) list *
(* inputs with optional names and constraints *)
string list * (* register clobbers *)
location
* There are for storing inline assembly . They follow the GCC
* specification :
{ v
asm [ volatile ] ( " ... template ... " " .. template .. "
: " c1 " ( o1 ) , " c2 " ( o2 ) , ... , " cN " ( oN )
: " d1 " ( i1 ) , " d2 " ( i2 ) , ... , " dM " ( iM )
: " r1 " , " r2 " , ... , " nL " ) ;
v }
where the parts are
- [ volatile ] ( optional ): when present , the assembler instruction
can not be removed , moved , or otherwise optimized
- template : a sequence of strings , with % 0 , % 1 , % 2 , etc . in the string to
refer to the input and output expressions . I think they 're numbered
consecutively , but the docs do n't specify . Each string is printed on
a separate line . This is the only part that is present for MSVC inline
assembly .
- " ci " ( oi ): pairs of constraint - string and output - lval ; the
constraint specifies that the register used must have some
property , like being a floating - point register ; the constraint
string for outputs also has " = " to indicate it is written , or
" + " to indicate it is both read and written ; ' oi ' is the
name of a C lvalue ( probably a variable name ) to be used as
the output destination
- " dj " ( ij ): pairs of constraint and input expression ; the constraint
is similar to the " ci"s . the ' ij ' is an arbitrary C expression
to be loaded into the corresponding register
- " rk " : registers to be regarded as " clobbered " by the instruction ;
" memory " may be specified for arbitrary memory effects
an example ( from gcc manual ):
{ v
asm volatile ( " % 0,%1,%2 "
: / * no outputs * /
: " g " ( from ) , " g " ( to ) , " g " ( count )
: " r0 " , " r1 " , " r2 " , " r3 " , " r4 " , " r5 " ) ;
v }
Starting with gcc 3.1 , the operands may have names :
{ v
asm volatile ( " % [ in0],%1,%2 "
: / * no outputs * /
: [ in0 ] " g " ( from ) , " g " ( to ) , " g " ( count )
: " r0 " , " r1 " , " r2 " , " r3 " , " r4 " , " r5 " ) ;
v }
* specification:
{v
asm [volatile] ("...template..." "..template.."
: "c1" (o1), "c2" (o2), ..., "cN" (oN)
: "d1" (i1), "d2" (i2), ..., "dM" (iM)
: "r1", "r2", ..., "nL" );
v}
where the parts are
- [volatile] (optional): when present, the assembler instruction
cannot be removed, moved, or otherwise optimized
- template: a sequence of strings, with %0, %1, %2, etc. in the string to
refer to the input and output expressions. I think they're numbered
consecutively, but the docs don't specify. Each string is printed on
a separate line. This is the only part that is present for MSVC inline
assembly.
- "ci" (oi): pairs of constraint-string and output-lval; the
constraint specifies that the register used must have some
property, like being a floating-point register; the constraint
string for outputs also has "=" to indicate it is written, or
"+" to indicate it is both read and written; 'oi' is the
name of a C lvalue (probably a variable name) to be used as
the output destination
- "dj" (ij): pairs of constraint and input expression; the constraint
is similar to the "ci"s. the 'ij' is an arbitrary C expression
to be loaded into the corresponding register
- "rk": registers to be regarded as "clobbered" by the instruction;
"memory" may be specified for arbitrary memory effects
an example (from gcc manual):
{v
asm volatile ("movc3 %0,%1,%2"
: /* no outputs */
: "g" (from), "g" (to), "g" (count)
: "r0", "r1", "r2", "r3", "r4", "r5");
v}
Starting with gcc 3.1, the operands may have names:
{v
asm volatile ("movc3 %[in0],%1,%2"
: /* no outputs */
: [in0] "g" (from), "g" (to), "g" (count)
: "r0", "r1", "r2", "r3", "r4", "r5");
v}
*)
(** Describes a position in a source file *)
and position = {
line: int; (** The line number. -1 means "do not know" *)
file: string; (** The name of the source file*)
line_begin: int; (** The begin of line position in the source file *)
byte: int; (** The byte position in the source file *)
}
(** Describes a location in a source file *)
and location = {
start_pos: position;
end_pos: position;
}
* Type signatures . Two types are identical iff they have identical
* signatures . These contain the same information as types but canonicalized .
* For example , two function types that are identical except for the name of
* the formal arguments are given the same signature . Also , [ TNamed ]
* constructors are unrolled .
* signatures. These contain the same information as types but canonicalized.
* For example, two function types that are identical except for the name of
* the formal arguments are given the same signature. Also, [TNamed]
* constructors are unrolled. *)
and typsig =
TSArray of typsig * int64 option * attribute list
| TSPtr of typsig * attribute list
| TSComp of bool * string * attribute list
| TSFun of typsig * typsig list * bool * attribute list
| TSEnum of string * attribute list
| TSBase of typ
(** {b Lowering Options} *)
val lowerConstants: bool ref
(** Do lower constants (default true) *)
val insertImplicitCasts: bool ref
(** Do insert implicit casts (default true) *)
(** To be able to add/remove features easily, each feature should be package
* as an interface with the following interface. These features should be *)
type featureDescr = {
fd_enabled: bool ref;
(** The enable flag. Set to default value *)
fd_name: string;
(** This is used to construct an option "--doxxx" and "--dontxxx" that
* enable and disable the feature *)
fd_description: string;
(** A longer name that can be used to document the new options *)
fd_extraopt: (string * Arg.spec * string) list;
(** Additional command line options. The description strings should
usually start with a space for Arg.align to print the --help nicely. *)
fd_doit: (file -> unit);
(** This performs the transformation *)
fd_post_check: bool;
(** Whether to perform a CIL consistency checking after this stage, if
* checking is enabled (--check is passed to cilly). Set this to true if
* your feature makes any changes for the program. *)
}
* Comparison function for position .
* * Compares first by filename , then line , then byte
** Compares first by filename, then line, then byte *)
(* val compareLoc: position -> position -> int *)
* Comparison function for locations .
* * Compares first by start_pos , then end_pos
** Compares first by start_pos, then end_pos *)
val compareLoc: location -> location -> int
(** {b Values for manipulating globals} *)
(** Make an empty function *)
val emptyFunction: string -> fundec
(** Update the formals of a [fundec] and make sure that the function type
has the same information. Will copy the name as well into the type. *)
val setFormals: fundec -> varinfo list -> unit
* Set the types of arguments and results as given by the function type
* passed as the second argument . Will not copy the names from the function
* type to the formals
* passed as the second argument. Will not copy the names from the function
* type to the formals *)
val setFunctionType: fundec -> typ -> unit
(** Set the type of the function and make formal arguments for them *)
val setFunctionTypeMakeFormals: fundec -> typ -> unit
* Update the smaxid after you have populated with locals and formals
* ( unless you constructed those using { ! } or
* { ! } .
* (unless you constructed those using {!Cil.makeLocalVar} or
* {!Cil.makeTempVar}. *)
val setMaxId: fundec -> unit
(** A dummy function declaration handy when you need one as a placeholder. It
* contains inside a dummy varinfo. *)
val dummyFunDec: fundec
(** A dummy file *)
val dummyFile: file
* Write a { ! Cil.file } in binary form to the filesystem . The file can be
* read back in later using { ! Cil.loadBinaryFile } , possibly saving parsing
* time . The second argument is the name of the file that should be
* created .
* read back in later using {!Cil.loadBinaryFile}, possibly saving parsing
* time. The second argument is the name of the file that should be
* created. *)
val saveBinaryFile : file -> string -> unit
(** Write a {!Cil.file} in binary form to the filesystem. The file can be
* read back in later using {!Cil.loadBinaryFile}, possibly saving parsing
* time. Does not close the channel. *)
val saveBinaryFileChannel : file -> out_channel -> unit
* Read a { ! Cil.file } in binary form from the filesystem . The first
* argument is the name of a file previously created by
* { ! Cil.saveBinaryFile } . Because this also reads some global state ,
* this should be called before any other CIL code is parsed or generated .
* argument is the name of a file previously created by
* {!Cil.saveBinaryFile}. Because this also reads some global state,
* this should be called before any other CIL code is parsed or generated. *)
val loadBinaryFile : string -> file
(** Get the global initializer and create one if it does not already exist.
* When it creates a global initializer it attempts to place a call to it in
* the main function named by the optional argument (default "main") *)
val getGlobInit: ?main_name:string -> file -> fundec
(** Iterate over all globals, including the global initializer *)
val iterGlobals: file -> (global -> unit) -> unit
(** Fold over all globals, including the global initializer *)
val foldGlobals: file -> ('a -> global -> 'a) -> 'a -> 'a
(** Map over all globals, including the global initializer and change things
in place *)
val mapGlobals: file -> (global -> global) -> unit
(** Find a function or function prototype with the given name in the file.
* If it does not exist, create a prototype with the given type, and return
* the new varinfo. This is useful when you need to call a libc function
* whose prototype may or may not already exist in the file.
*
* Because the new prototype is added to the start of the file, you shouldn't
* refer to any struct or union types in the function type.*)
val findOrCreateFunc: file -> string -> typ -> varinfo
val new_sid : unit -> int
* Prepare a function for CFG information computation by
* { ! Cil.computeCFGInfo } . This function converts all [ Break ] , [ Switch ] ,
* [ Default ] and [ Continue ] { ! and { ! Cil.label}s into [ If]s
* and [ Goto]s , giving the function body a very CFG - like character . This
* function modifies its argument in place .
* {!Cil.computeCFGInfo}. This function converts all [Break], [Switch],
* [Default] and [Continue] {!Cil.stmtkind}s and {!Cil.label}s into [If]s
* and [Goto]s, giving the function body a very CFG-like character. This
* function modifies its argument in place. *)
val prepareCFG: fundec -> unit
* Compute the CFG information for all statements in a fundec and return a
* list of the statements . The input fundec can not have [ Break ] , [ Switch ] ,
* [ Default ] , or [ Continue ] { ! or { ! Cil.label}s . Use
* { ! Cil.prepareCFG } to transform them away . The second argument should
* be [ true ] if you wish a global statement number , [ false ] if you wish a
* local ( per - function ) statement numbering . The list of statements is set
* in the sallstmts field of a fundec .
*
* NOTE : unless you want the simpler control - flow graph provided by
* prepareCFG , or you need the function 's smaxstmtid and
* filled in , we recommend you use { ! Cfg.computeFileCFG } instead of this
* function to compute control - flow information .
* { ! Cfg.computeFileCFG } is newer and will handle switch , break , and
* continue correctly .
* list of the statements. The input fundec cannot have [Break], [Switch],
* [Default], or [Continue] {!Cil.stmtkind}s or {!Cil.label}s. Use
* {!Cil.prepareCFG} to transform them away. The second argument should
* be [true] if you wish a global statement number, [false] if you wish a
* local (per-function) statement numbering. The list of statements is set
* in the sallstmts field of a fundec.
*
* NOTE: unless you want the simpler control-flow graph provided by
* prepareCFG, or you need the function's smaxstmtid and sallstmt fields
* filled in, we recommend you use {!Cfg.computeFileCFG} instead of this
* function to compute control-flow information.
* {!Cfg.computeFileCFG} is newer and will handle switch, break, and
* continue correctly.*)
val computeCFGInfo: fundec -> bool -> unit
(** Create a deep copy of a function. There should be no sharing between the
* copy and the original function *)
val copyFunction: fundec -> string -> fundec
(** CIL keeps the types at the beginning of the file and the variables at the
* end of the file. This function will take a global and add it to the
* corresponding stack. Its operation is actually more complicated because if
* the global declares a type that contains references to variables (e.g. in
* sizeof in an array length) then it will also add declarations for the
* variables to the types stack *)
val pushGlobal: global -> types: global list ref
-> variables: global list ref -> unit
(** An empty statement. Used in pretty printing *)
val invalidStmt: stmt
* A list of the built - in functions for the current compiler ( GCC or
* MSVC , depending on [ ! msvcMode ] ) . Maps the name to the
* result and argument types , and whether it is vararg .
* Initialized by { ! Cil.initCIL }
*
* This map replaces [ gccBuiltins ] and [ msvcBuiltins ] in previous
* versions of CIL .
* MSVC, depending on [!msvcMode]). Maps the name to the
* result and argument types, and whether it is vararg.
* Initialized by {!Cil.initCIL}
*
* This map replaces [gccBuiltins] and [msvcBuiltins] in previous
* versions of CIL.*)
val builtinFunctions : (string, typ * typ list * bool) Hashtbl.t
(** This is used as the location of the prototypes of builtin functions. *)
val builtinLoc: location
(** {b Values for manipulating initializers} *)
* Make a initializer for zero - ing a data type
val makeZeroInit: typ -> init
* Fold over the list of initializers in a Compound ( not also the nested
* ones ) . [ doinit ] is called on every present initializer , even if it is of
* compound type . The parameters of [ doinit ] are : the offset in the compound
* ( this is [ Field(f , ) ] or [ Index(i , ) ] ) , the initializer
* value , expected type of the initializer value , accumulator . In the case of
* arrays there might be missing zero - initializers at the end of the list .
* These are scanned only if [ implicit ] is true . This is much like
* [ List.fold_left ] except we also pass the type of the initializer .
* This is a good way to use it to scan even nested initializers :
{ v
let rec myInit ( lv : lval ) ( i : init ) ( acc : ' a ) : ' a =
match i with
SingleInit e - > ... do something with lv and e and acc ...
| CompoundInit ( ct , ) - >
foldLeftCompound ~implicit : false
~doinit:(fun off ' i ' t ' acc - >
myInit ( addOffsetLval lv off ' ) i ' acc )
~ct : ct
~initl : initl
~acc : acc
v }
* ones). [doinit] is called on every present initializer, even if it is of
* compound type. The parameters of [doinit] are: the offset in the compound
* (this is [Field(f,NoOffset)] or [Index(i,NoOffset)]), the initializer
* value, expected type of the initializer value, accumulator. In the case of
* arrays there might be missing zero-initializers at the end of the list.
* These are scanned only if [implicit] is true. This is much like
* [List.fold_left] except we also pass the type of the initializer.
* This is a good way to use it to scan even nested initializers :
{v
let rec myInit (lv: lval) (i: init) (acc: 'a) : 'a =
match i with
SingleInit e -> ... do something with lv and e and acc ...
| CompoundInit (ct, initl) ->
foldLeftCompound ~implicit:false
~doinit:(fun off' i' t' acc ->
myInit (addOffsetLval lv off') i' acc)
~ct:ct
~initl:initl
~acc:acc
v}
*)
val foldLeftCompound:
implicit:bool ->
doinit: (offset -> init -> typ -> 'a -> 'a) ->
ct: typ ->
initl: (offset * init) list ->
acc: 'a -> 'a
(** {b Values for manipulating types} *)
(** void *)
val voidType: typ
(** is the given type "void"? *)
val isVoidType: typ -> bool
(** is the given type "void *"? *)
val isVoidPtrType: typ -> bool
(** int *)
val intType: typ
(** unsigned int *)
val uintType: typ
(** long *)
val longType: typ
(** unsigned long *)
val ulongType: typ
(** char *)
val charType: typ
(** char * *)
val charPtrType: typ
* wchar_t ( depends on architecture ) and is set when you call
* { ! Cil.initCIL } .
* {!Cil.initCIL}. *)
val wcharKind: ikind ref
val wcharType: typ ref
(** char const * *)
val charConstPtrType: typ
(** void * *)
val voidPtrType: typ
(** int * *)
val intPtrType: typ
(** unsigned int * *)
val uintPtrType: typ
(** double *)
val doubleType: typ
* An unsigned integer type that fits pointers . Depends on { ! Cil.msvcMode }
* and is set when you call { ! Cil.initCIL } .
* and is set when you call {!Cil.initCIL}. *)
val upointType: typ ref
* An unsigned integer type that fits pointer difference . Depends on
* { ! Cil.msvcMode } and is set when you call { ! Cil.initCIL } .
* {!Cil.msvcMode} and is set when you call {!Cil.initCIL}. *)
val ptrdiffType: typ ref
* An unsigned integer type that is the type of sizeof . Depends on
* { ! Cil.msvcMode } and is set when you call { ! Cil.initCIL } .
* {!Cil.msvcMode} and is set when you call {!Cil.initCIL}. *)
val typeOfSizeOf: typ ref
* The integer kind of { ! } .
* Set when you call { ! Cil.initCIL } .
* Set when you call {!Cil.initCIL}. *)
val kindOfSizeOf: ikind ref
(** Returns true if and only if the given integer type is signed. *)
val isSigned: ikind -> bool
* Creates a a ( potentially recursive ) composite type . The arguments are :
* ( 1 ) a boolean indicating whether it is a struct or a union , ( 2 ) the name
* ( always non - empty ) , ( 3 ) a function that when given a representation of the
* structure type constructs the type of the fields recursive type ( the first
* argument is only useful when some fields need to refer to the type of the
* structure itself ) , and ( 4 ) a list of attributes to be associated with the
* composite type . The resulting compinfo has the field " cdefined " only if
* the list of fields is non - empty .
* (1) a boolean indicating whether it is a struct or a union, (2) the name
* (always non-empty), (3) a function that when given a representation of the
* structure type constructs the type of the fields recursive type (the first
* argument is only useful when some fields need to refer to the type of the
* structure itself), and (4) a list of attributes to be associated with the
* composite type. The resulting compinfo has the field "cdefined" only if
* the list of fields is non-empty. *)
val mkCompInfo: bool -> (* whether it is a struct or a union *)
string -> (* name of the composite type; cannot be empty *)
(compinfo ->
(string * typ * int option * attributes * location * location) list) ->
(* a function that when given a forward
representation of the structure type constructs the type of
the fields. The function can ignore this argument if not
constructing a recursive type. *)
attributes -> compinfo
* Makes a shallow copy of a { ! } changing the name and the key .
val copyCompInfo: compinfo -> string -> compinfo
(** This is a constant used as the name of an unnamed bitfield. These fields
do not participate in initialization and their name is not printed. *)
val missingFieldName: string
(** Get the full name of a comp *)
val compFullName: compinfo -> string
(** Returns true if this is a complete type.
This means that sizeof(t) makes sense.
Incomplete types are not yet defined
structures and empty arrays. *)
val isCompleteType: typ -> bool
(** Unroll a type until it exposes a non
* [TNamed]. Will collect all attributes appearing in [TNamed]!!! *)
val unrollType: typ -> typ
* Unroll all the TNamed in a type ( even under type constructors such as
* [ TPtr ] , [ TFun ] or [ TArray ] . Does not unroll the types of fields in [ TComp ]
* types . Will collect all attributes
* [TPtr], [TFun] or [TArray]. Does not unroll the types of fields in [TComp]
* types. Will collect all attributes *)
val unrollTypeDeep: typ -> typ
(** Separate out the storage-modifier name attributes *)
val separateStorageModifiers: attribute list -> attribute list * attribute list
(** True if the argument is an integral type (i.e. integer or enum) *)
val isIntegralType: typ -> bool
(** True if the argument is an arithmetic type (i.e. integer, enum or
floating point *)
val isArithmeticType: typ -> bool
(**True if the argument is a pointer type *)
val isPointerType: typ -> bool
(**True if the argument is a scalar type *)
val isScalarType: typ -> bool
(** True if the argument is a function type *)
val isFunctionType: typ -> bool
(** Obtain the argument list ([] if None) *)
val argsToList: (string * typ * attributes) list option
-> (string * typ * attributes) list
(** True if the argument is an array type *)
val isArrayType: typ -> bool
(** Raised when {!Cil.lenOfArray} fails either because the length is [None]
* or because it is a non-constant expression *)
exception LenOfArray
* Call to compute the array length as present in the array type , to an
* integer . Raises { ! . LenOfArray } if not able to compute the length , such
* as when there is no length or the length is not a constant .
* integer. Raises {!Cil.LenOfArray} if not able to compute the length, such
* as when there is no length or the length is not a constant. *)
val lenOfArray: exp option -> int
* Return a named fieldinfo in , or raise Not_found
val getCompField: compinfo -> string -> fieldinfo
(** A datatype to be used in conjunction with [existsType] *)
type existsAction =
ExistsTrue (** We have found it *)
| ExistsFalse (** Stop processing this branch *)
| ExistsMaybe (** This node is not what we are
* looking for but maybe its
* successors are *)
* Scans a type by applying the function on all elements .
When the function returns ExistsTrue , the scan stops with
true . When the function returns ExistsFalse then the current branch is not
scanned anymore . Care is taken to
apply the function only once on each composite type , thus avoiding
circularity . When the function returns ExistsMaybe then the types that
construct the current type are scanned ( e.g. the base type for TPtr and
TArray , the type of fields for a TComp , etc ) .
When the function returns ExistsTrue, the scan stops with
true. When the function returns ExistsFalse then the current branch is not
scanned anymore. Care is taken to
apply the function only once on each composite type, thus avoiding
circularity. When the function returns ExistsMaybe then the types that
construct the current type are scanned (e.g. the base type for TPtr and
TArray, the type of fields for a TComp, etc). *)
val existsType: (typ -> existsAction) -> typ -> bool
(** Given a function type split it into return type,
* arguments, is_vararg and attributes. An error is raised if the type is not
* a function type *)
val splitFunctionType:
typ -> typ * (string * typ * attributes) list option * bool * attributes
(** Same as {!Cil.splitFunctionType} but takes a varinfo. Prints a nicer
* error message if the varinfo is not for a function *)
val splitFunctionTypeVI:
varinfo -> typ * (string * typ * attributes) list option * bool * attributes
(** {b Type signatures} *)
* Type signatures . Two types are identical iff they have identical
* signatures . These contain the same information as types but canonicalized .
* For example , two function types that are identical except for the name of
* the formal arguments are given the same signature . Also , [ TNamed ]
* constructors are unrolled .
* signatures. These contain the same information as types but canonicalized.
* For example, two function types that are identical except for the name of
* the formal arguments are given the same signature. Also, [TNamed]
* constructors are unrolled. *)
(** Print a type signature *)
val d_typsig: unit -> typsig -> Pretty.doc
(** Compute a type signature *)
val typeSig: typ -> typsig
(** Like {!Cil.typeSig} but customize the incorporation of attributes.
Use ~ignoreSign:true to convert all signed integer types to unsigned,
so that signed and unsigned will compare the same. *)
val typeSigWithAttrs: ?ignoreSign:bool -> (attributes -> attributes) -> typ -> typsig
(** Replace the attributes of a signature (only at top level) *)
val setTypeSigAttrs: attributes -> typsig -> typsig
(** Get the top-level attributes of a signature *)
val typeSigAttrs: typsig -> attributes
(*********************************************************)
(** {b Lvalues} *)
* Make a varinfo . Use this ( rarely ) to make a raw varinfo . Use other
* functions to make locals ( { ! } or { ! Cil.makeFormalVar } or
* { ! } ) and globals ( { ! Cil.makeGlobalVar } ) . Note that this
* function will assign a new identifier . The first argument specifies
* whether the varinfo is for a global .
* functions to make locals ({!Cil.makeLocalVar} or {!Cil.makeFormalVar} or
* {!Cil.makeTempVar}) and globals ({!Cil.makeGlobalVar}). Note that this
* function will assign a new identifier. The first argument specifies
* whether the varinfo is for a global. *)
val makeVarinfo: bool -> string -> typ -> varinfo
* Make a formal variable for a function . Insert it in both the sformals
and the type of the function . You can optionally specify where to insert
this one . If where = " ^ " then it is inserted first . If where = " $ " then
it is inserted last . Otherwise where must be the name of a formal after
which to insert this . By default it is inserted at the end .
and the type of the function. You can optionally specify where to insert
this one. If where = "^" then it is inserted first. If where = "$" then
it is inserted last. Otherwise where must be the name of a formal after
which to insert this. By default it is inserted at the end. *)
val makeFormalVar: fundec -> ?where:string -> string -> typ -> varinfo
(** Make a local variable and add it to a function's slocals (only if insert =
true, which is the default). Make sure you know what you are doing if you
set insert=false. *)
val makeLocalVar: fundec -> ?insert:bool -> string -> typ -> varinfo
* Make a temporary variable and add it to a function 's slocals . CIL will
ensure that the name of the new variable is unique in this function , and
will generate this name by appending a number to the specified string
( " _ _ cil_tmp " by default ) .
The variable will be added to the function 's slocals unless you explicitly
set insert = false . ( Make sure you know what you are doing if you set
insert = false . )
Optionally , you can give the variable a description of its contents
that will be printed by descriptiveCilPrinter .
ensure that the name of the new variable is unique in this function, and
will generate this name by appending a number to the specified string
("__cil_tmp" by default).
The variable will be added to the function's slocals unless you explicitly
set insert=false. (Make sure you know what you are doing if you set
insert=false.)
Optionally, you can give the variable a description of its contents
that will be printed by descriptiveCilPrinter.
*)
val makeTempVar: fundec -> ?insert:bool -> ?name: string ->
?descr:Pretty.doc -> ?descrpure:bool -> typ -> varinfo
(** Make a global variable. Your responsibility to make sure that the name
is unique *)
val makeGlobalVar: string -> typ -> varinfo
(** Make a shallow copy of a [varinfo] and assign a new identifier *)
val copyVarinfo: varinfo -> string -> varinfo
* Generate a new variable ID . This will be different than any variable ID
* that is generated by { ! } and friends
* that is generated by {!Cil.makeLocalVar} and friends *)
val newVID: unit -> int
(** Add an offset at the end of an lvalue. Make sure the type of the lvalue
* and the offset are compatible. *)
val addOffsetLval: offset -> lval -> lval
(** [addOffset o1 o2] adds [o1] to the end of [o2]. *)
val addOffset: offset -> offset -> offset
* Remove ONE offset from the end of an lvalue . Returns the lvalue with the
* trimmed offset and the final offset . If the final offset is [ NoOffset ]
* then the original [ lval ] did not have an offset .
* trimmed offset and the final offset. If the final offset is [NoOffset]
* then the original [lval] did not have an offset. *)
val removeOffsetLval: lval -> lval * offset
* Remove ONE offset from the end of an offset sequence . Returns the
* trimmed offset and the final offset . If the final offset is [ NoOffset ]
* then the original [ lval ] did not have an offset .
* trimmed offset and the final offset. If the final offset is [NoOffset]
* then the original [lval] did not have an offset. *)
val removeOffset: offset -> offset * offset
(** Compute the type of an lvalue *)
val typeOfLval: lval -> typ
(** Compute the type of an offset from a base type *)
val typeOffset: typ -> offset -> typ
(*******************************************************)
(** {b Values for manipulating expressions} *)
Construct integer constants
* 0
val zero: location -> exp
* 1
val one: location -> exp
(** -1 *)
val mone: location -> exp
(** Construct an integer of a given kind, from a cilint. If needed it
* will truncate the integer to be within the representable range for
* the given kind. *)
val kintegerCilint: ikind -> cilint -> location -> exp
* Construct an integer of a given kind , using OCaml 's int64 type . If needed
* it will truncate the integer to be within the representable range for the
* given kind .
* it will truncate the integer to be within the representable range for the
* given kind. *)
val kinteger64: ikind -> int64 -> location -> exp
* Construct an integer of a given kind . Converts the integer to int64 and
* then uses kinteger64 . This might truncate the value if you use a kind
* that can not represent the given integer . This can only happen for one of
* the or Short kinds
* then uses kinteger64. This might truncate the value if you use a kind
* that cannot represent the given integer. This can only happen for one of
* the Char or Short kinds *)
val kinteger: ikind -> int -> location -> exp
* Construct an integer of kind IInt . On targets where C 's ' int ' is 16 - bits ,
the integer may get truncated .
the integer may get truncated. *)
val integer: int -> location -> exp
(** If the given expression is an integer constant or a CastE'd
integer constant, return that constant's value.
Otherwise return None. *)
val getInteger: exp -> cilint option
* Convert a 64 - bit int to an OCaml int , or raise an exception if that
ca n't be done .
can't be done. *)
val i64_to_int: int64 -> int
(** Convert a cilint int to an OCaml int, or raise an exception if that
can't be done. *)
val cilint_to_int: cilint -> int
(** True if the expression is a compile-time constant *)
val isConstant: exp -> bool
(** True if the given offset contains only field nanmes or constant indices. *)
val isConstantOffset: offset -> bool
* True if the given expression is a ( possibly cast'ed ) integer or character
constant with value zero
constant with value zero *)
val isZero: exp -> bool
* Given the character c in a ( CChr c ) , sign - extend it to 32 bits .
( This is the official way of interpreting character constants , according to
ISO C 6.4.4.4.10 , which says that character constants are chars cast to ints )
Returns CInt64(sign - extened c , IInt , None )
(This is the official way of interpreting character constants, according to
ISO C 6.4.4.4.10, which says that character constants are chars cast to ints)
Returns CInt64(sign-extened c, IInt, None) *)
val charConstToInt: char -> constant
* Do constant folding on an expression . If the first argument is true then
will also compute compiler - dependent expressions such as sizeof .
See also { ! Cil.constFoldVisitor } , which will run constFold on all
expressions in a given AST node .
will also compute compiler-dependent expressions such as sizeof.
See also {!Cil.constFoldVisitor}, which will run constFold on all
expressions in a given AST node.*)
val constFold: bool -> exp -> exp
* Do constant folding on a binary operation . The bulk of the work done by
[ constFold ] is done here . If the first argument is true then
will also compute compiler - dependent expressions such as sizeof
[constFold] is done here. If the first argument is true then
will also compute compiler-dependent expressions such as sizeof *)
val constFoldBinOp: bool -> binop -> exp -> exp -> typ -> location -> exp
(** Increment an expression. Can be arithmetic or pointer type *)
val increm: exp -> int -> exp
(** Makes an lvalue out of a given variable *)
val var: varinfo -> location -> lval
* Make an . Given an lvalue of type T will give back an expression of
type ptr(T ) . It optimizes somewhat expressions like " & v " and " & v[0 ] "
type ptr(T). It optimizes somewhat expressions like "& v" and "& v[0]" *)
val mkAddrOf: lval -> location -> exp
(** Like mkAddrOf except if the type of lval is an array then it uses
StartOf. This is the right operation for getting a pointer to the start
of the storage denoted by lval. *)
val mkAddrOrStartOf: lval -> location -> exp
* Make a Mem , while optimizing . The type of the addr must be
TPtr(t ) and the type of the resulting lval is t. Note that in CIL the
implicit conversion between an array and the pointer to the first
element does not apply . You must do the conversion yourself using
StartOf
TPtr(t) and the type of the resulting lval is t. Note that in CIL the
implicit conversion between an array and the pointer to the first
element does not apply. You must do the conversion yourself using
StartOf *)
val mkMem: addr:exp -> off:offset -> lval
(** Make an expression that is a string constant (of pointer type) *)
val mkString: string -> exp
(** Construct a cast when having the old type of the expression. If the new
* type is the same as the old type, then no cast is added. *)
val mkCastT: e:exp -> oldt:typ -> newt:typ -> exp
* Like { ! Cil.mkCastT } but uses to get [ oldt ]
val mkCast: e:exp -> newt:typ -> exp
* Removes casts from this expression , but ignores casts within
other expression constructs . So we delete the ( A ) and ( B ) casts from
" ( A)(B)(x + ( C)y ) " , but leave the ( C ) cast .
other expression constructs. So we delete the (A) and (B) casts from
"(A)(B)(x + (C)y)", but leave the (C) cast. *)
val stripCasts: exp -> exp
(** Compute the type of an expression *)
val typeOf: exp -> typ
* Convert a string representing a C integer literal to an expression .
* Handles the prefixes 0x and 0 and the suffixes L , U , UL , LL , ULL
* Handles the prefixes 0x and 0 and the suffixes L, U, UL, LL, ULL *)
val parseInt: string -> location -> exp
(**********************************************)
(** {b Values for manipulating statements} *)
* Construct a statement , given its kind . Initialize the [ sid ] field to -1 ,
and [ labels ] , [ succs ] and [ ] to the empty list
and [labels], [succs] and [preds] to the empty list *)
val mkStmt: stmtkind -> stmt
(** Construct a block with no attributes, given a list of statements *)
val mkBlock: stmt list -> block
* Construct a statement consisting of just one instruction
val mkStmtOneInstr: instr -> stmt
* Try to compress statements so as to get maximal basic blocks .
* use this instead of List.@ because you get fewer basic blocks
* use this instead of List.@ because you get fewer basic blocks *)
val compactStmts: stmt list -> stmt list
(** Returns an empty statement (of kind [Instr]) *)
val mkEmptyStmt: unit -> stmt
(** A instr to serve as a placeholder *)
val dummyInstr: instr
(** A statement consisting of just [dummyInstr] *)
val dummyStmt: stmt
(** Make a while loop. Can contain Break or Continue *)
val mkWhile: guard:exp -> body:stmt list -> hspecs: Iformula.struc_formula -> stmt list
* Make a for loop for(i = start ; i < past ; i + = incr ) \ { ... \ } . The body
can contain Break but not Continue . Can be used with i a pointer
or an integer . Start and done must have the same type but incr
must be an integer
can contain Break but not Continue. Can be used with i a pointer
or an integer. Start and done must have the same type but incr
must be an integer *)
val mkForIncr: iter:varinfo -> first:exp -> stopat:exp -> incr:exp
-> body:stmt list -> hspecs: Iformula.struc_formula -> stmt list
(** Make a for loop for(start; guard; next) \{ ... \}. The body can
contain Break but not Continue !!! *)
val mkFor: start:stmt list -> guard:exp -> next: stmt list ->
body: stmt list -> hspecs: Iformula.struc_formula -> stmt list
(**************************************************)
(** {b Values for manipulating attributes} *)
(** Various classes of attributes *)
type attributeClass =
AttrName of bool
* Attribute of a name . If argument is true and we are on MSVC then
the attribute is printed using _ _ as part of the storage
specifier
the attribute is printed using __declspec as part of the storage
specifier *)
| AttrFunType of bool
* Attribute of a function type . If argument is true and we are on
MSVC then the attribute is printed just before the function name
MSVC then the attribute is printed just before the function name *)
| AttrType (** Attribute of a type *)
(** This table contains the mapping of predefined attributes to classes.
Extend this table with more attributes as you need. This table is used to
determine how to associate attributes with names or types *)
val attributeHash: (string, attributeClass) Hashtbl.t
(** Partition the attributes into classes:name attributes, function type,
and type attributes *)
val partitionAttributes: default:attributeClass ->
attributes -> attribute list * (* AttrName *)
attribute list * (* AttrFunType *)
AttrType
* Add an attribute . Maintains the attributes in sorted order of the second
argument
argument *)
val addAttribute: attribute -> attributes -> attributes
* Add a list of attributes . Maintains the attributes in sorted order . The
second argument must be sorted , but not necessarily the first
second argument must be sorted, but not necessarily the first *)
val addAttributes: attribute list -> attributes -> attributes
(** Remove all attributes with the given name. Maintains the attributes in
sorted order. *)
val dropAttribute: string -> attributes -> attributes
(** Remove all attributes with names appearing in the string list.
* Maintains the attributes in sorted order *)
val dropAttributes: string list -> attributes -> attributes
(** Retains attributes with the given name *)
val filterAttributes: string -> attributes -> attributes
(** True if the named attribute appears in the attribute list. The list of
attributes must be sorted. *)
val hasAttribute: string -> attributes -> bool
(** Returns all the attributes contained in a type. This requires a traversal
of the type structure, in case of composite, enumeration and named types *)
val typeAttrs: typ -> attribute list
val setTypeAttrs: typ -> attributes -> typ (* Resets the attributes *)
(** Add some attributes to a type *)
val typeAddAttributes: attribute list -> typ -> typ
(** Remove all attributes with the given names from a type. Note that this
does not remove attributes from typedef and tag definitions, just from
their uses *)
val typeRemoveAttributes: string list -> typ -> typ
(** Convert an expression into an attrparam, if possible. Otherwise raise
NotAnAttrParam with the offending subexpression *)
val expToAttrParam: exp -> attrparam
exception NotAnAttrParam of exp
(******************
****************** VISITOR
******************)
(** {b The visitor} *)
(** Different visiting actions. 'a will be instantiated with [exp], [instr],
etc. *)
type 'a visitAction =
SkipChildren (** Do not visit the children. Return
the node as it is. *)
| DoChildren (** Continue with the children of this
node. Rebuild the node on return
if any of the children changes
(use == test) *)
* Replace the expression with the
given one
given one *)
* First consider that the entire
exp is replaced by the first
parameter . Then continue with
the children . On return rebuild
the node if any of the children
has changed and then apply the
function on the node
exp is replaced by the first
parameter. Then continue with
the children. On return rebuild
the node if any of the children
has changed and then apply the
function on the node *)
* A visitor interface for traversing CIL trees . Create instantiations of
* this type by specializing the class { ! Cil.nopCilVisitor } . Each of the
* specialized visiting functions can also call the [ queueInstr ] to specify
* that some instructions should be inserted before the current instruction
* or statement . Use syntax like [ self#queueInstr ] to call a method
* associated with the current object .
* this type by specializing the class {!Cil.nopCilVisitor}. Each of the
* specialized visiting functions can also call the [queueInstr] to specify
* that some instructions should be inserted before the current instruction
* or statement. Use syntax like [self#queueInstr] to call a method
* associated with the current object. *)
class type cilVisitor = object
method vvdec: varinfo -> varinfo visitAction
* Invoked for each variable declaration . The subtrees to be traversed
* are those corresponding to the type and attributes of the variable .
* Note that variable declarations are all the [ GVar ] , [ GVarDecl ] , [ GFun ] ,
* all the [ varinfo ] in formals of function types , and the formals and
* locals for function definitions . This means that the list of formals
* in a function definition will be traversed twice , once as part of the
* function type and second as part of the formals in a function
* definition .
* are those corresponding to the type and attributes of the variable.
* Note that variable declarations are all the [GVar], [GVarDecl], [GFun],
* all the [varinfo] in formals of function types, and the formals and
* locals for function definitions. This means that the list of formals
* in a function definition will be traversed twice, once as part of the
* function type and second as part of the formals in a function
* definition. *)
method vvrbl: varinfo -> varinfo visitAction
* Invoked on each variable use . Here only the [ SkipChildren ] and
* [ ChangeTo ] actions make sense since there are no subtrees . Note that
* the type and attributes of the variable are not traversed for a
* variable use
* [ChangeTo] actions make sense since there are no subtrees. Note that
* the type and attributes of the variable are not traversed for a
* variable use *)
method vexpr: exp -> exp visitAction
(** Invoked on each expression occurrence. The subtrees are the
* subexpressions, the types (for a [Cast] or [SizeOf] expression) or the
* variable use. *)
method vlval: lval -> lval visitAction
(** Invoked on each lvalue occurrence *)
method voffs: offset -> offset visitAction
(** Invoked on each offset occurrence that is *not* as part
* of an initializer list specification, i.e. in an lval or
* recursively inside an offset. *)
method vinitoffs: offset -> offset visitAction
* Invoked on each offset appearing in the list of a
* CompoundInit initializer .
* CompoundInit initializer. *)
method vinst: instr -> instr list visitAction
(** Invoked on each instruction occurrence. The [ChangeTo] action can
* replace this instruction with a list of instructions *)
method vstmt: stmt -> stmt visitAction
* Control - flow statement . The default [ DoChildren ] action does not
* create a new statement when the components change . Instead it updates
* the contents of the original statement . This is done to preserve the
* sharing with [ ] and [ Case ] statements that point to the original
* statement . If you use the [ ChangeTo ] action then you should take care
* of preserving that sharing yourself .
* create a new statement when the components change. Instead it updates
* the contents of the original statement. This is done to preserve the
* sharing with [Goto] and [Case] statements that point to the original
* statement. If you use the [ChangeTo] action then you should take care
* of preserving that sharing yourself. *)
method vblock: block -> block visitAction (** Block. *)
method vfunc: fundec -> fundec visitAction (** Function definition.
Replaced in place. *)
method vglob: global -> global list visitAction (** Global (vars, types,
etc.) *)
method vinit: varinfo -> offset -> init -> init visitAction
(** Initializers for globals,
* pass the global where this
* occurs, and the offset *)
method vtype: typ -> typ visitAction (** Use of some type. Note
* that for structure/union
* and enumeration types the
* definition of the
* composite type is not
* visited. Use [vglob] to
* visit it. *)
method vattr: attribute -> attribute list visitAction
(** Attribute. Each attribute can be replaced by a list *)
method vattrparam: attrparam -> attrparam visitAction
(** Attribute parameters. *)
(** Add here instructions while visiting to queue them to preceede the
* current statement or instruction being processed. Use this method only
* when you are visiting an expression that is inside a function body, or
* a statement, because otherwise there will no place for the visitor to
* place your instructions. *)
method queueInstr: instr list -> unit
(** Gets the queue of instructions and resets the queue. This is done
* automatically for you when you visit statments. *)
method unqueueInstr: unit -> instr list
end
(** Default Visitor. Traverses the CIL tree without modifying anything *)
class nopCilVisitor: cilVisitor
other cil constructs
(** Visit a file. This will will re-cons all globals TWICE (so that it is
* tail-recursive). Use {!Cil.visitCilFileSameGlobals} if your visitor will
* not change the list of globals. *)
val visitCilFile: cilVisitor -> file -> unit
(** A visitor for the whole file that does not change the globals (but maybe
* changes things inside the globals). Use this function instead of
* {!Cil.visitCilFile} whenever appropriate because it is more efficient for
* long files. *)
val visitCilFileSameGlobals: cilVisitor -> file -> unit
(** Visit a global *)
val visitCilGlobal: cilVisitor -> global -> global list
(** Visit a function definition *)
val visitCilFunction: cilVisitor -> fundec -> fundec
(* Visit an expression *)
val visitCilExpr: cilVisitor -> exp -> exp
(** Visit an lvalue *)
val visitCilLval: cilVisitor -> lval -> lval
(** Visit an lvalue or recursive offset *)
val visitCilOffset: cilVisitor -> offset -> offset
(** Visit an initializer offset *)
val visitCilInitOffset: cilVisitor -> offset -> offset
(** Visit an instruction *)
val visitCilInstr: cilVisitor -> instr -> instr list
(** Visit a statement *)
val visitCilStmt: cilVisitor -> stmt -> stmt
(** Visit a block *)
val visitCilBlock: cilVisitor -> block -> block
(** Visit a type *)
val visitCilType: cilVisitor -> typ -> typ
(** Visit a variable declaration *)
val visitCilVarDecl: cilVisitor -> varinfo -> varinfo
(** Visit an initializer, pass also the global to which this belongs and the
* offset. *)
val visitCilInit: cilVisitor -> varinfo -> offset -> init -> init
(** Visit a list of attributes *)
val visitCilAttributes: cilVisitor -> attribute list -> attribute list
(* And some generic visitors. The above are built with these *)
(** {b Utility functions} *)
* Whether the pretty printer should print output for the MS VC compiler .
Default is GCC . After you set this function you should call { ! Cil.initCIL } .
Default is GCC. After you set this function you should call {!Cil.initCIL}. *)
val msvcMode: bool ref
* Whether to use the logical operands LAnd and LOr . By default , do not use
* them because they are unlike other expressions and do not evaluate both of
* their operands
* them because they are unlike other expressions and do not evaluate both of
* their operands *)
val useLogicalOperators: bool ref
* Set this to true to get old - style handling of gcc 's extern inline C extension :
old - style : the extern inline definition is used until the actual definition is
seen ( as long as optimization is enabled )
new - style : the extern inline definition is used only if there is no actual
definition ( as long as optimization is enabled )
Note that CIL assumes that optimization is always enabled ;-)
old-style: the extern inline definition is used until the actual definition is
seen (as long as optimization is enabled)
new-style: the extern inline definition is used only if there is no actual
definition (as long as optimization is enabled)
Note that CIL assumes that optimization is always enabled ;-) *)
val oldstyleExternInline : bool ref
(** A visitor that does constant folding. Pass as argument whether you want
* machine specific simplifications to be done, or not. *)
val constFoldVisitor: bool -> cilVisitor
(** Styles of printing line directives *)
type lineDirectiveStyle =
| LineComment (** Before every element, print the line
* number in comments. This is ignored by
* processing tools (thus errors are reproted
* in the CIL output), but useful for
* visual inspection *)
| LineCommentSparse (** Like LineComment but only print a line
* directive for a new source line *)
| LinePreprocessorInput (** Use # nnn directives (in gcc mode) *)
* Use # line directives
(** How to print line directives *)
val lineDirectiveStyle: lineDirectiveStyle option ref
(** Whether we print something that will only be used as input to our own
* parser. In that case we are a bit more liberal in what we print *)
val print_CIL_Input: bool ref
* Whether to print the CIL as they are , without trying to be smart and
* print nicer code . Normally this is false , in which case the pretty
* printer will turn the while(1 ) loops of CIL into nicer loops , will not
* print empty " else " blocks , etc . There is one case howewer in which if you
* turn this on you will get code that does not compile : if you use varargs
* the _ _ builtin_va_arg function will be printed in its internal form .
* print nicer code. Normally this is false, in which case the pretty
* printer will turn the while(1) loops of CIL into nicer loops, will not
* print empty "else" blocks, etc. There is one case howewer in which if you
* turn this on you will get code that does not compile: if you use varargs
* the __builtin_va_arg function will be printed in its internal form. *)
val printCilAsIs: bool ref
(** The length used when wrapping output lines. Setting this variable to
* a large integer will prevent wrapping and make #line directives more
* accurate.
*)
val lineLength: int ref
* Return the string 's ' if we 're printing output for gcc , suppres
* it if we 're printing for CIL to parse back in . the purpose is to
* hide things from gcc that it complains about , but still be able
* to do lossless transformations when CIL is the consumer
* it if we're printing for CIL to parse back in. the purpose is to
* hide things from gcc that it complains about, but still be able
* to do lossless transformations when CIL is the consumer *)
val forgcc: string -> string
(** {b Debugging support} *)
(** A reference to the current location. If you are careful to set this to
* the current location then you can use some built-in logging functions that
* will print the location. *)
val currentLoc: location ref
(** A reference to the current global being visited *)
val currentGlobal: global ref
* CIL has a fairly easy to use mechanism for printing error messages . This
* mechanism is built on top of the pretty - printer mechanism ( see
* { ! Pretty.doc } ) and the error - message modules ( see { ! Errormsg.error } ) .
Here is a typical example for printing a log message : { v
ignore ( Errormsg.log " Expression % a is not positive ( at % s:%i)\n "
d_exp e loc.file loc.line )
v }
and here is an example of how you print a fatal error message that stop the
* execution : { v
Errormsg.s ( " Why am I here ? " )
v }
Notice that you can use C format strings with some extension . The most
useful extension is " % a " that means to consumer the next two argument from
the argument list and to apply the first to [ unit ] and then to the second
and to print the resulting { ! Pretty.doc } . For each major type in CIL there is
a corresponding function that pretty - prints an element of that type :
* mechanism is built on top of the pretty-printer mechanism (see
* {!Pretty.doc}) and the error-message modules (see {!Errormsg.error}).
Here is a typical example for printing a log message: {v
ignore (Errormsg.log "Expression %a is not positive (at %s:%i)\n"
d_exp e loc.file loc.line)
v}
and here is an example of how you print a fatal error message that stop the
* execution: {v
Errormsg.s (Errormsg.bug "Why am I here?")
v}
Notice that you can use C format strings with some extension. The most
useful extension is "%a" that means to consumer the next two argument from
the argument list and to apply the first to [unit] and then to the second
and to print the resulting {!Pretty.doc}. For each major type in CIL there is
a corresponding function that pretty-prints an element of that type:
*)
(** Pretty-print a location *)
val d_loc: unit -> location -> Pretty.doc
(** Pretty-print the {!Cil.currentLoc} *)
val d_thisloc: unit -> Pretty.doc
(** Pretty-print an integer of a given kind *)
val d_ikind: unit -> ikind -> Pretty.doc
(** Pretty-print a floating-point kind *)
val d_fkind: unit -> fkind -> Pretty.doc
(** Pretty-print storage-class information *)
val d_storage: unit -> storage -> Pretty.doc
(** Pretty-print a constant *)
val d_const: unit -> constant -> Pretty.doc
val derefStarLevel: int
val indexLevel: int
val arrowLevel: int
val addrOfLevel: int
val additiveLevel: int
val comparativeLevel: int
val bitwiseLevel: int
(** Parentheses level. An expression "a op b" is printed parenthesized if its
* parentheses level is >= that that of its context. Identifiers have the
* lowest level and weakly binding operators (e.g. |) have the largest level.
* The correctness criterion is that a smaller level MUST correspond to a
* stronger precedence!
*)
val getParenthLevel: exp -> int
(** A printer interface for CIL trees. Create instantiations of
* this type by specializing the class {!Cil.defaultCilPrinterClass}. *)
class type cilPrinter = object
method setCurrentFormals : varinfo list -> unit
method setPrintInstrTerminator : string -> unit
method getPrintInstrTerminator : unit -> string
method pVDecl: unit -> varinfo -> Pretty.doc
(** Invoked for each variable declaration. Note that variable
* declarations are all the [GVar], [GVarDecl], [GFun], all the [varinfo]
* in formals of function types, and the formals and locals for function
* definitions. *)
method pVar: varinfo -> Pretty.doc
(** Invoked on each variable use. *)
method pLval: unit -> lval -> Pretty.doc
(** Invoked on each lvalue occurrence *)
method pOffset: Pretty.doc -> offset -> Pretty.doc
* Invoked on each offset occurrence . The second argument is the base .
method pInstr: unit -> instr -> Pretty.doc
(** Invoked on each instruction occurrence. *)
method pLabel: unit -> label -> Pretty.doc
(** Print a label. *)
method pStmt: unit -> stmt -> Pretty.doc
(** Control-flow statement. This is used by
* {!Cil.printGlobal} and by {!Cil.dumpGlobal}. *)
method dStmt: out_channel -> int -> stmt -> unit
(** Dump a control-flow statement to a file with a given indentation.
* This is used by {!Cil.dumpGlobal}. *)
method dBlock: out_channel -> int -> block -> unit
(** Dump a control-flow block to a file with a given indentation.
* This is used by {!Cil.dumpGlobal}. *)
method pBlock: unit -> block -> Pretty.doc
(** Print a block. *)
method pFunDecl: unit -> fundec -> Pretty.doc
method pGlobal: unit -> global -> Pretty.doc
(** Global (vars, types, etc.). This can be slow and is used only by
* {!Cil.printGlobal} but not by {!Cil.dumpGlobal}. *)
method dGlobal: out_channel -> global -> unit
(** Dump a global to a file with a given indentation. This is used by
* {!Cil.dumpGlobal} *)
method pFieldDecl: unit -> fieldinfo -> Pretty.doc
(** A field declaration *)
method pType: Pretty.doc option -> unit -> typ -> Pretty.doc
* Use of some type in some declaration . The first argument is used to print
* the declared element , or is None if we are just printing a type with no
* name being declared . Note that for structure / union and enumeration types
* the definition of the composite type is not visited . Use [ vglob ] to
* visit it .
* the declared element, or is None if we are just printing a type with no
* name being declared. Note that for structure/union and enumeration types
* the definition of the composite type is not visited. Use [vglob] to
* visit it. *)
method pAttr: attribute -> Pretty.doc * bool
(** Attribute. Also return an indication whether this attribute must be
* printed inside the __attribute__ list or not. *)
method pAttrParam: unit -> attrparam -> Pretty.doc
(** Attribute parameter *)
method pAttrs: unit -> attributes -> Pretty.doc
(** Attribute lists *)
method pLineDirective: ?forcefile:bool -> location -> Pretty.doc
(** Print a line-number. This is assumed to come always on an empty line.
* If the forcefile argument is present and is true then the file name
* will be printed always. Otherwise the file name is printed only if it
* is different from the last time time this function is called. The last
* file name is stored in a private field inside the cilPrinter object. *)
method pStmtKind: stmt -> unit -> stmtkind -> Pretty.doc
* Print a statement kind . The code to be printed is given in the
* { ! Cil.stmtkind } argument . The initial { ! Cil.stmt } argument
* records the statement which follows the one being printed ;
* { ! Cil.defaultCilPrinterClass } uses this information to prettify
* statement printing in certain special cases .
* {!Cil.stmtkind} argument. The initial {!Cil.stmt} argument
* records the statement which follows the one being printed;
* {!Cil.defaultCilPrinterClass} uses this information to prettify
* statement printing in certain special cases. *)
method pExp: unit -> exp -> Pretty.doc
(** Print expressions *)
method pLoc: unit -> location -> Pretty.doc
(** Print location *)
method pInit: unit -> init -> Pretty.doc
(** Print initializers. This can be slow and is used by
* {!Cil.printGlobal} but not by {!Cil.dumpGlobal}. *)
method dInit: out_channel -> int -> init -> unit
(** Dump a global to a file with a given indentation. This is used by
* {!Cil.dumpGlobal} *)
end
class defaultCilPrinterClass: cilPrinter
val defaultCilPrinter: cilPrinter
(** These are pretty-printers that will show you more details on the internal
* CIL representation, without trying hard to make it look like C *)
class plainCilPrinterClass: cilPrinter
val plainCilPrinter: cilPrinter
class type descriptiveCilPrinter = object
inherit cilPrinter
method startTemps: unit -> unit
method stopTemps: unit -> unit
method pTemps: unit -> Pretty.doc
end
class descriptiveCilPrinterClass : bool -> descriptiveCilPrinter
(** Like defaultCilPrinterClass, but instead of temporary variable
names it prints the description that was provided when the temp was
created. This is usually better for messages that are printed for end
users, although you may want the temporary names for debugging.
The boolean here enables descriptive printing. Usually use true
here, but you can set enable to false to make this class behave
like defaultCilPrinterClass. This allows subclasses to turn the
feature off. *)
val descriptiveCilPrinter: descriptiveCilPrinter
* zra : This is the pretty printer that Maincil will use .
by default it is set to defaultCilPrinter
by default it is set to defaultCilPrinter *)
val printerForMaincil: cilPrinter ref
(* Top-level printing functions *)
(** Print a type given a pretty printer *)
val printType: cilPrinter -> unit -> typ -> Pretty.doc
(** Print an expression given a pretty printer *)
val printExp: cilPrinter -> unit -> exp -> Pretty.doc
(** Print an lvalue given a pretty printer *)
val printLval: cilPrinter -> unit -> lval -> Pretty.doc
(** Print a global given a pretty printer *)
val printGlobal: cilPrinter -> unit -> global -> Pretty.doc
(** Print an attribute given a pretty printer *)
val printAttr: cilPrinter -> unit -> attribute -> Pretty.doc
(** Print a set of attributes given a pretty printer *)
val printAttrs: cilPrinter -> unit -> attributes -> Pretty.doc
(** Print an instruction given a pretty printer *)
val printInstr: cilPrinter -> unit -> instr -> Pretty.doc
* Print a statement given a pretty printer . This can take very long
* ( or even overflow the stack ) for huge statements . Use { ! }
* instead .
* (or even overflow the stack) for huge statements. Use {!Cil.dumpStmt}
* instead. *)
val printStmt: cilPrinter -> unit -> stmt -> Pretty.doc
(** Print a block given a pretty printer. This can take very long
* (or even overflow the stack) for huge block. Use {!Cil.dumpBlock}
* instead. *)
val printBlock: cilPrinter -> unit -> block -> Pretty.doc
(** Dump a statement to a file using a given indentation. Use this instead of
* {!Cil.printStmt} whenever possible. *)
val dumpStmt: cilPrinter -> out_channel -> int -> stmt -> unit
(** Dump a block to a file using a given indentation. Use this instead of
* {!Cil.printBlock} whenever possible. *)
val dumpBlock: cilPrinter -> out_channel -> int -> block -> unit
(** Print an initializer given a pretty printer. This can take very long
* (or even overflow the stack) for huge initializers. Use {!Cil.dumpInit}
* instead. *)
val printInit: cilPrinter -> unit -> init -> Pretty.doc
(** Dump an initializer to a file using a given indentation. Use this instead of
* {!Cil.printInit} whenever possible. *)
val dumpInit: cilPrinter -> out_channel -> int -> init -> unit
* Pretty - print a type using { ! }
val d_type: unit -> typ -> Pretty.doc
* Pretty - print an expression using { ! }
val d_exp: unit -> exp -> Pretty.doc
* Pretty - print an location using { ! }
val d_loc: unit -> location -> Pretty.doc
* Pretty - print an lvalue using { ! }
val d_lval: unit -> lval -> Pretty.doc
* Pretty - print an offset using { ! } , given the pretty
* printing for the base .
* printing for the base. *)
val d_offset: Pretty.doc -> unit -> offset -> Pretty.doc
* Pretty - print an initializer using { ! } . This can be
* extremely slow ( or even overflow the stack ) for huge initializers . Use
* { ! Cil.dumpInit } instead .
* extremely slow (or even overflow the stack) for huge initializers. Use
* {!Cil.dumpInit} instead. *)
val d_init: unit -> init -> Pretty.doc
(** Pretty-print a binary operator *)
val d_binop: unit -> binop -> Pretty.doc
(** Pretty-print a unary operator *)
val d_unop: unit -> unop -> Pretty.doc
* Pretty - print an attribute using { ! }
val d_attr: unit -> attribute -> Pretty.doc
* Pretty - print an argument of an attribute using { ! }
val d_attrparam: unit -> attrparam -> Pretty.doc
* Pretty - print a list of attributes using { ! }
val d_attrlist: unit -> attributes -> Pretty.doc
* Pretty - print an instruction using { ! }
val d_instr: unit -> instr -> Pretty.doc
* Pretty - print a label using { ! }
val d_label: unit -> label -> Pretty.doc
* Pretty - print a statement using { ! } . This can be
* extremely slow ( or even overflow the stack ) for huge statements . Use
* { ! } instead .
* extremely slow (or even overflow the stack) for huge statements. Use
* {!Cil.dumpStmt} instead. *)
val d_stmt: unit -> stmt -> Pretty.doc
* Pretty - print a block using { ! } . This can be
* extremely slow ( or even overflow the stack ) for huge blocks . Use
* { ! Cil.dumpBlock } instead .
* extremely slow (or even overflow the stack) for huge blocks. Use
* {!Cil.dumpBlock} instead. *)
val d_block: unit -> block -> Pretty.doc
val d_fundec: unit -> fundec -> Pretty.doc
* Pretty - print the internal representation of a global using
* { ! } . This can be extremely slow ( or even overflow the
* stack ) for huge globals ( such as arrays with lots of initializers ) . Use
* { ! Cil.dumpGlobal } instead .
* {!Cil.defaultCilPrinter}. This can be extremely slow (or even overflow the
* stack) for huge globals (such as arrays with lots of initializers). Use
* {!Cil.dumpGlobal} instead. *)
val d_global: unit -> global -> Pretty.doc
(** Versions of the above pretty printers, that don't print #line directives *)
val dn_exp : unit -> exp -> Pretty.doc
val dn_lval : unit -> lval -> Pretty.doc
(* dn_offset is missing because it has a different interface *)
val dn_init : unit -> init -> Pretty.doc
val dn_type : unit -> typ -> Pretty.doc
val dn_global : unit -> global -> Pretty.doc
val dn_attrlist : unit -> attributes -> Pretty.doc
val dn_attr : unit -> attribute -> Pretty.doc
val dn_attrparam : unit -> attrparam -> Pretty.doc
val dn_stmt : unit -> stmt -> Pretty.doc
val dn_instr : unit -> instr -> Pretty.doc
(** Pretty-print a short description of the global. This is useful for error
* messages *)
val d_shortglobal: unit -> global -> Pretty.doc
(** Pretty-print a global. Here you give the channel where the printout
* should be sent. *)
val dumpGlobal: cilPrinter -> out_channel -> global -> unit
(** Pretty-print an entire file. Here you give the channel where the printout
* should be sent. *)
val dumpFile: cilPrinter -> out_channel -> string -> file -> unit
* the following error message producing functions also print a location in
* the code . use { ! } and { ! Errormsg.unimp } if you do not want
* that
* the code. use {!Errormsg.bug} and {!Errormsg.unimp} if you do not want
* that *)
* Like { ! } except that { ! } is also printed
val bug: ('a,unit,Pretty.doc) format -> 'a
(** Like {!Errormsg.unimp} except that {!Cil.currentLoc}is also printed *)
val unimp: ('a,unit,Pretty.doc) format -> 'a
* Like { ! Errormsg.error } except that { ! } is also printed
val error: ('a,unit,Pretty.doc) format -> 'a
(** Like {!Cil.error} except that it explicitly takes a location argument,
* instead of using the {!Cil.currentLoc} *)
val errorLoc: location -> ('a,unit,Pretty.doc) format -> 'a
* Like { ! Errormsg.warn } except that { ! } is also printed
val warn: ('a,unit,Pretty.doc) format -> 'a
* Like { ! Errormsg.warnOpt } except that { ! } is also printed .
* This warning is printed only of { ! } is set .
* This warning is printed only of {!Errormsg.warnFlag} is set. *)
val warnOpt: ('a,unit,Pretty.doc) format -> 'a
* Like { ! Errormsg.warn } except that { ! } and context
is also printed
is also printed *)
val warnContext: ('a,unit,Pretty.doc) format -> 'a
* Like { ! Errormsg.warn } except that { ! } and context is also
* printed . This warning is printed only of { ! } is set .
* printed. This warning is printed only of {!Errormsg.warnFlag} is set. *)
val warnContextOpt: ('a,unit,Pretty.doc) format -> 'a
(** Like {!Cil.warn} except that it explicitly takes a location argument,
* instead of using the {!Cil.currentLoc} *)
val warnLoc: location -> ('a,unit,Pretty.doc) format -> 'a
(** Sometimes you do not want to see the syntactic sugar that the above
* pretty-printing functions add. In that case you can use the following
* pretty-printing functions. But note that the output of these functions is
* not valid C *)
(** Pretty-print the internal representation of an expression *)
val d_plainexp: unit -> exp -> Pretty.doc
(** Pretty-print the internal representation of an integer *)
val d_plaininit: unit -> init -> Pretty.doc
(** Pretty-print the internal representation of an lvalue *)
val d_plainlval: unit -> lval -> Pretty.doc
(** Pretty-print the internal representation of an lvalue offset
val d_plainoffset: unit -> offset -> Pretty.doc *)
(** Pretty-print the internal representation of a type *)
val d_plaintype: unit -> typ -> Pretty.doc
(** Pretty-print an expression while printing descriptions rather than names
of temporaries. *)
val dd_exp: unit -> exp -> Pretty.doc
(** Pretty-print an lvalue on the left side of an assignment.
If there is an offset or memory dereference, temporaries will
be replaced by descriptions as in dd_exp. If the lval is a temp var,
that var will not be replaced by a description; use "dd_exp () (Lval lv)"
if that's what you want. *)
val dd_lval: unit -> lval -> Pretty.doc
(** String conversation functions *)
val string_of_exp: exp -> string
val string_of_loc: location -> string
val string_of_lval: lval -> string
val string_of_offset: offset -> string
val string_of_init: init -> string
val string_of_typ: typ -> string
val string_of_attrlist: attributes -> string
val string_of_attr: attribute -> string
val string_of_attrparam: attrparam -> string
val string_of_label: label -> string
val string_of_stmt: stmt -> string
val string_of_block: block -> string
val string_of_instr: instr -> string
val string_of_global: global -> string
(** {b ALPHA conversion} has been moved to the Alpha module. *)
* Assign unique names to local variables . This might be necessary after you
* transformed the code and added or renamed some new variables . Names are
* not used by CIL internally , but once you print the file out the compiler
* downstream might be confused . You might
* have added a new global that happens to have the same name as a local in
* some function . Rename the local to ensure that there would never be
* confusioin . Or , viceversa , you might have added a local with a name that
* conflicts with a global
* transformed the code and added or renamed some new variables. Names are
* not used by CIL internally, but once you print the file out the compiler
* downstream might be confused. You might
* have added a new global that happens to have the same name as a local in
* some function. Rename the local to ensure that there would never be
* confusioin. Or, viceversa, you might have added a local with a name that
* conflicts with a global *)
val uniqueVarNames: file -> unit
(** {b Optimization Passes} *)
* A peephole optimizer that processes two adjacent instructions and possibly
replaces them both . If some replacement happens , then the new instructions
are themselves subject to optimization
replaces them both. If some replacement happens, then the new instructions
are themselves subject to optimization *)
val peepHole2: (instr * instr -> instr list option) -> stmt list -> unit
* Similar to [ peepHole2 ] except that the optimization window consists of
one instruction , not two
one instruction, not two *)
val peepHole1: (instr -> instr list option) -> stmt list -> unit
(** {b Machine dependency} *)
* Raised when one of the bitsSizeOf functions can not compute the size of a
* type . This can happen because the type contains array - length expressions
* that we do n't know how to compute or because it is a type whose size is
* not defined ( e.g. TFun or an undefined ) . The string is an
* explanation of the error
* type. This can happen because the type contains array-length expressions
* that we don't know how to compute or because it is a type whose size is
* not defined (e.g. TFun or an undefined compinfo). The string is an
* explanation of the error *)
exception SizeOfError of string * typ
(** Give the unsigned kind corresponding to any integer kind *)
val unsignedVersionOf : ikind -> ikind
(** Give the signed kind corresponding to any integer kind *)
val signedVersionOf : ikind -> ikind
(** Return the integer conversion rank of an integer kind *)
val intRank : ikind -> int
* Return the common integer kind of the two integer arguments , as
defined in ISO C 6.3.1.8 ( " Usual arithmetic conversions " )
defined in ISO C 6.3.1.8 ("Usual arithmetic conversions") *)
val commonIntKind : ikind -> ikind -> ikind
* The signed integer kind for a given size ( unsigned if second argument
* is true ) . Raises Not_found if no such kind exists
* is true). Raises Not_found if no such kind exists *)
val intKindForSize : int -> bool -> ikind
(** The float kind for a given size. Raises Not_found
* if no such kind exists *)
val floatKindForSize : int-> fkind
(** The size in bytes of the given int kind. *)
val bytesSizeOfInt: ikind -> int
* The size of a type , in bits . Trailing padding is added for structs and
* arrays . Raises { ! . SizeOfError } when it can not compute the size . This
* function is architecture dependent , so you should only call this after you
* call { ! Cil.initCIL } . Remember that on GCC sizeof(void ) is 1 !
* arrays. Raises {!Cil.SizeOfError} when it cannot compute the size. This
* function is architecture dependent, so you should only call this after you
* call {!Cil.initCIL}. Remember that on GCC sizeof(void) is 1! *)
val bitsSizeOf: typ -> int
* Represents an integer as for a given kind . Returns a truncation
* flag saying that the value fit in the kind ( NoTruncation ) , did n't
* fit but no " interesting " bits ( all-0 or all-1 ) were lost
* ( ValueTruncation ) or that bits were lost ( BitTruncation ) . Another
* way to look at the ValueTruncation result is that if you had used
* the kind of opposite signedness ( e.g. IUInt rather than IInt ) , you
* would gave got ...
* flag saying that the value fit in the kind (NoTruncation), didn't
* fit but no "interesting" bits (all-0 or all-1) were lost
* (ValueTruncation) or that bits were lost (BitTruncation). Another
* way to look at the ValueTruncation result is that if you had used
* the kind of opposite signedness (e.g. IUInt rather than IInt), you
* would gave got NoTruncation... *)
val truncateCilint: ikind -> cilint -> cilint * truncation
(** True if the integer fits within the kind's range *)
val fitsInInt: ikind -> cilint -> bool
* Return the smallest kind that will hold the integer 's value . The
* kind will be unsigned if the 2nd argument is true , signed
* otherwise . Note that if the value does n't fit in any of the
* available types , you will get ILongLong ( 2nd argument false ) or
* ( 2nd argument true ) .
* kind will be unsigned if the 2nd argument is true, signed
* otherwise. Note that if the value doesn't fit in any of the
* available types, you will get ILongLong (2nd argument false) or
* IULongLong (2nd argument true). *)
val intKindForValue: cilint -> bool -> ikind
* Construct a cilint from an integer kind and int64 value . Used for
* getting the actual constant value from a CInt64(n , , _ )
* constant .
* getting the actual constant value from a CInt64(n, ik, _)
* constant. *)
val mkCilint : ikind -> int64 -> cilint
* The size of a type , in bytes . Returns a constant expression or a
* " sizeof " expression if it can not compute the size . This function
* is architecture dependent , so you should only call this after you
* call { ! Cil.initCIL } .
* "sizeof" expression if it cannot compute the size. This function
* is architecture dependent, so you should only call this after you
* call {!Cil.initCIL}. *)
val sizeOf: typ * location -> exp
* The minimum alignment ( in bytes ) for a type . This function is
* architecture dependent , so you should only call this after you call
* { ! Cil.initCIL } .
* architecture dependent, so you should only call this after you call
* {!Cil.initCIL}. *)
val alignOf_int: typ -> int
* Give a type of a base and an offset , returns the number of bits from the
* base address and the width ( also expressed in bits ) for the subobject
* denoted by the offset . Raises { ! . SizeOfError } when it can not compute
* the size . This function is architecture dependent , so you should only call
* this after you call { ! Cil.initCIL } .
* base address and the width (also expressed in bits) for the subobject
* denoted by the offset. Raises {!Cil.SizeOfError} when it cannot compute
* the size. This function is architecture dependent, so you should only call
* this after you call {!Cil.initCIL}. *)
val bitsOffset: typ -> offset -> int * int
* Whether " char " is unsigned . Set after you call { ! Cil.initCIL }
val char_is_unsigned: bool ref
* Whether the machine is little endian . Set after you call { ! Cil.initCIL }
val little_endian: bool ref
* Whether the compiler generates assembly labels by prepending " _ " to the
identifier . That is , will function foo ( ) have the label " foo " , or " _ foo " ?
Set after you call { ! Cil.initCIL }
identifier. That is, will function foo() have the label "foo", or "_foo"?
Set after you call {!Cil.initCIL} *)
val underscore_name: bool ref
(** Represents a location that cannot be determined *)
val posUnknown: position
(** Represents a location that cannot be determined *)
val locUnknown: location
(** Return the starting position of a location *)
val startPos: location -> position
(** Return the ending position of a location *)
val endPos: location -> position
* Create a location from 2 position
val makeLoc: position -> position -> location
(** Return the location of an instruction *)
val get_instrLoc: instr -> location
* Return the location of a global , or locUnknown
val get_globalLoc: global -> location
* Return the location of a statement , or locUnknown
val get_stmtLoc: stmtkind -> location
* Return the location of an expression , or locUnknown
val get_expLoc: exp -> location
val get_lvalLoc: lval -> location
val get_offsetLoc: offset -> location
val get_lhostLoc: lhost -> location
(** Generate an {!Cil.exp} to be used in case of errors. *)
val dExp: Pretty.doc -> exp
(** Generate an {!Cil.instr} to be used in case of errors. *)
val dInstr: Pretty.doc -> location -> instr
* Generate a { ! Cil.global } to be used in case of errors .
val dGlobal: Pretty.doc -> location -> global
(** Like map but try not to make a copy of the list *)
val mapNoCopy: ('a -> 'a) -> 'a list -> 'a list
(** Like map but each call can return a list. Try not to make a copy of the
list *)
val mapNoCopyList: ('a -> 'a list) -> 'a list -> 'a list
* sm : return true if the first is a prefix of the second string
val startsWith: string -> string -> bool
* return true if the first is a suffix of the second string
val endsWith: string -> string -> bool
(** If string has leading and trailing __, strip them. *)
val stripUnderscores: string -> string
(** {b An Interpreter for constructing CIL constructs} *)
(** The type of argument for the interpreter *)
type formatArg =
Fe of exp
| Feo of exp option (** For array lengths *)
| Fu of unop
| Fb of binop
| Fk of ikind
| FE of exp list (** For arguments in a function call *)
| Ff of (string * typ * attributes) (** For a formal argument *)
| FF of (string * typ * attributes) list (** For formal argument lists *)
| Fva of bool (** For the ellipsis in a function type *)
| Fv of varinfo
| Fl of lval
| Flo of lval option
| Fo of offset
| Fc of compinfo
| Fi of instr
| FI of instr list
| Ft of typ
| Fd of int
| Fg of string
| Fs of stmt
| FS of stmt list
| FA of attributes
| Fp of attrparam
| FP of attrparam list
| FX of string
(** Pretty-prints a format arg *)
val d_formatarg: unit -> formatArg -> Pretty.doc
(** Emit warnings when truncating integer constants (default true) *)
val warnTruncate: bool ref
(** Machine model specified via CIL_MACHINE environment variable *)
val envMachine : Machdep.mach option ref
(* ------------------------------------------------------------------------- *)
(* DEPRECATED FUNCTIONS *)
(* These will eventually go away *)
(* ------------------------------------------------------------------------- *)
* @deprecated . Convert two int64 / kind pairs to a common int64 / int64 / kind triple .
val convertInts: int64 -> ikind -> int64 -> ikind -> int64 * int64 * ikind
* @deprecated . Ca n't handle large 64 - bit unsigned constants
correctly - use getInteger instead . If the given expression
is a ( possibly cast'ed ) character or an integer constant , return
that integer . Otherwise , return None .
correctly - use getInteger instead. If the given expression
is a (possibly cast'ed) character or an integer constant, return
that integer. Otherwise, return None. *)
val isInteger: exp -> int64 option
(** @deprecated. Use truncateCilint instead. Represents an integer as
* for a given kind. Returns a flag saying whether the value was
* changed during truncation (because it was too large to fit in k). *)
val truncateInteger64: ikind -> int64 -> int64 * bool
(** @deprecated. For compatibility with older programs, these are
aliases for {!Cil.builtinFunctions} *)
val gccBuiltins: (string, typ * typ list * bool) Hashtbl.t
(** @deprecated. For compatibility with older programs, these are
aliases for {!Cil.builtinFunctions} *)
val msvcBuiltins: (string, typ * typ list * bool) Hashtbl.t
val string_of_loc: location -> string
| null | https://raw.githubusercontent.com/hipsleek/hipsleek/596f7fa7f67444c8309da2ca86ba4c47d376618c/cil/src/cil.mli | ocaml | * {b CIL API Documentation.} An html version of this document
* can be found at
* Call this function to perform some initialization. Call if after you have
* set {!Cil.msvcMode}.
* These are the CIL version numbers. A CIL version is a number of the form
* M.m.r (major, minor and release)
* {b The Abstract Syntax of CIL}
* The top-level representation of a CIL source file (and the result of the
* parsing and elaboration). Its main contents is the list of global
* declarations and definitions. You can iterate over the globals in a
* {!Cil.file} using the following iterators: {!Cil.mapGlobals},
* {!Cil.iterGlobals} and {!Cil.foldGlobals}. You can also use the
* {!Cil.dummyFile} when you need a {!Cil.file} as a placeholder. For each
* global item CIL stores the source location where it appears (using the
* type {!Cil.location})
* The complete file name
* List of globals as they will appear
in the printed file
* An optional global initializer function. This is a function where
* you can put stuff that must be executed before the program is
* started. This function is conceptually at the end of the file,
* although it is not part of the globals list. Use {!Cil.getGlobInit}
* to create/get one.
* Top-level representation of a C source file
* {b Globals}. The main type for representing global declarations and
* definitions. A list of these form a CIL file. The order of globals in the
* file is generally important.
* A global declaration or definition
* A typedef. All uses of type names (through the [TNamed] constructor)
must be preceded in the file by a definition of the name. The string
is the defined name and always not-empty.
* Declares a struct/union tag. Use as a forward declaration. This is
* printed without the fields.
* Declares an enumeration tag with some fields. There must be one of
these for each enumeration tag that you use (through the [TEnum]
constructor) since this is the only context in which the items are
printed.
* Declares an enumeration tag. Use as a forward declaration. This is
* printed without the items.
* A function definition.
* Global asm statement. These ones
can contain only a template
* Some text (printed verbatim) at
top level. E.g., this way you can
put comments in the output.
* HIP prog
* Void type. Also predefined as {!Cil.voidType}
* A floating-point type. The kind specifies the precision. You can
* also use the predefined constant {!Cil.doubleType}.
* Array type. It indicates the base type and the array length.
* Function type. Indicates the type of the result, the name, type
* and name attributes of the formal arguments ([None] if no
* arguments were specified, as in a function whose definition or
* prototype we have not seen; [Some \[\]] means void). Use
* {!Cil.argsToList} to obtain a list of arguments. The boolean
* indicates if it is a variable-argument function. If this is the
* type of a varinfo for which we have a function declaration then
* the information for the formals must match that in the
* function's sformals. Use {!Cil.setFormals}, or
* {!Cil.setFunctionType}, or {!Cil.makeFormalVar} for this
* purpose.
* A reference to an enumeration type. All such references must
share the enuminfo among them and with a [GEnumTag] global that
precedes all uses. The attributes refer to this use of the
enumeration and are in addition to the attributes of the
enumeration itself, which are stored inside the enuminfo
* This is the same as the gcc's type with the same name
* Various kinds of integers
* [char]
* [signed char]
* [unsigned char]
* [int]
* [unsigned int]
* [short]
* [unsigned short]
* [long]
* [unsigned long]
* Various kinds of floating-point numbers
* [float]
* [double]
* [long double]
* {b Attributes.}
* An attribute has a name and some optional parameters. The name should not
* start or end with underscore. When CIL parses attribute names it will
* strip leading and ending underscores (to ensure that the multitude of GCC
* attributes such as const, __const and __const__ all mean the same thing.)
* Attributes are lists sorted by the attribute name. Use the functions
* {!Cil.addAttribute} and {!Cil.addAttributes} to insert attributes in an
* attribute list and maintain the sortedness.
* The type of parameters of attributes
* An integer constant
* A string constant
* Constructed attributes. These
are printed [foo(a1,a2,...,an)].
The list of parameters can be
empty and in that case the
parentheses are not printed.
* A way to talk about types
* Replacement for ASizeOf in type
signatures. Only used for
attributes inside typsigs.
* a.foo *
* * a
* & a *
* a1[a2]
* a1 ? a2 : a3 *
* True if struct, False if union
* The name. Always non-empty. Use {!Cil.compFullName} to get the full
* name of a comp (along with the struct or union)
* This boolean flag can be used to distinguish between structures
that have not been defined and those that have been defined but have
no fields (such things are allowed in gcc).
* True if used. Initially set to false.
* Information about a struct/union field
* The name of the field. Might be the value of {!Cil.missingFieldName}
* in which case it must be a bitfield and is not printed and it does not
* participate in initialization
* The type
* The attributes for this field (not for its type)
* The location where this field is defined
* {b Enumerations.} Information about an enumeration. This is shared by all
* references to an enumeration. Make sure you have a [GEnumTag] for each of
* of these.
* Information about an enumeration
* The name. Always non-empty.
* Items with names and values. This list should be non-empty. The item
* values must be compile-time constants.
* The attributes that are defined at the same time as the enumeration
* type. These attributes can be supplemented individually at each
* reference to this [enuminfo] using the [TEnum] type constructor.
* True if used. Initially set to false
* {b Enumerations.} Information about an enumeration. This is shared by all
* references to an enumeration. Make sure you have a [GEnumTag] for each of
* of these.
* Information about a defined type
* The actual type. This includes the attributes that were present in
* the typedef
* True if used. Initially set to false
* Information about a variable.
* The declared type of the variable.
* A list of attributes associated with the variable.
* The storage-class
* True if this is a global variable
* Whether this varinfo is for an inline function.
* Location of variable declaration.
* For most temporary variables, a description of what the var holds.
* (e.g. for temporaries used for function call results, this string
* is a representation of the function call.)
* Storage-class information
* The default storage. Nothing is printed
* Expressions (Side-effect free)
* Constant
* sizeof(<type>). Has [unsigned int] type (ISO 6.5.3.4). This is not
* turned into a constant because some transformations might want to
* change types
* sizeof(<expression>)
* sizeof(string_literal). We separate this case out because this is the
* only instance in which a string literal should not be treated as
* having type pointer to character.
* This corresponds to the GCC __alignof_. Has [unsigned int] type
* Unary operation. Includes the type of the result.
* Binary operation. Includes the type of the result. The arithmetic
* conversions are made explicit for the arguments.
* (a ? b : c) operation. Includes the type of the result
* Use {!Cil.mkCast} to make casts.
* {b Constants.}
* Literal constants
* String constant. The escape characters inside the string have been
* already interpreted. This constant has pointer to character type! The
* only case when you would like a string literal to have an array type
* is when it is an argument to sizeof. In that case you should use
* SizeOfStr.
* An enumeration constant with the given value, name, from the given
* enuminfo. This is used only if {!Cil.lowerConstants} is true
* (default). Use {!Cil.constFoldVisitor} to replace these with integer
* constants.
* Unary operators
* Unary minus
* Bitwise complement (~)
* Logical Not (!)
* Binary operations
* arithmetic +
* pointer + integer
* pointer + integer but only when
* it arises from an expression
* [e\[i\]] when [e] is a pointer and
* not an array. This is semantically
* the same as PlusPI but CCured uses
* this as a hint that the integer is
* probably positive.
* arithmetic -
* pointer - integer
* pointer - pointer
* *
* /
* %
* shift left
* shift right
* < (arithmetic comparison)
* > (arithmetic comparison)
* <= (arithmetic comparison)
* > (arithmetic comparison)
* == (arithmetic comparison)
* != (arithmetic comparison)
* bitwise and
* exclusive-or
* inclusive-or
* logical and. Unlike other
* expressions this one does not
* always evaluate both operands. If
* you want to use these, you must
* set {!Cil.useLogicalOperators}.
* logical or. Unlike other
* expressions this one does not
* always evaluate both operands. If
* you want to use these, you must
* set {!Cil.useLogicalOperators}.
* An lvalue
* The host part of an {!Cil.lval}.
* The host is a variable.
* No offset. Can be applied to any lvalue and does
* not change either the starting address or the type.
* This is used when the lval consists of just a host
* or as a terminator in a list of other kinds of
* offsets.
* A field offset. Can be applied only to an lvalue
* that denotes a structure or a union that contains
* the mentioned field. This advances the offset to the
* beginning of the mentioned field and changes the
* type to the type of the mentioned field.
* An array index offset. Can be applied only to an
* lvalue that denotes an array. This advances the
* starting address of the lval to the beginning of the
* mentioned array element and changes the denoted type
* to be the type of the array element
* Initializers for global variables.
* A single initializer
* We want to be able to update an initializer in a global variable, so we
* define it as a mutable field
* {b Function definitions.}
A function definition is always introduced with a [GFun] constructor at the
top level. All the information about the function is stored into a
{!Cil.fundec}. Some of the information (e.g. its name, type,
storage, attributes) is stored as a {!Cil.varinfo} that is a field of the
[fundec]. To refer to the function from the expression language you must use
the [varinfo].
The function definition contains, in addition to the body, a list of all the
local variables and separately a list of the formals. Both kind of variables
can be referred to in the body of the function. The formals must also be shared
with the formals that appear in the function type. For that reason, to
manipulate formals you should use the provided functions
{!Cil.makeFormalVar} and {!Cil.setFormals} and {!Cil.makeFormalVar}.
* Function definitions.
* Holds the name and type as a variable, so we can refer to it
* easily from the program. All references to this function either
* in a function call or in a prototype must point to the same
* [varinfo].
* Locals. Does NOT include the sformals. Do not make copies of
* these because the body refers to them.
* The function body.
* max id of a (reachable) statement
* in this function, if we have
* computed it. range = 0 ...
* (smaxstmtid-1). This is computed by
* {!Cil.computeCFGInfo}.
* After you call {!Cil.computeCFGInfo}
* this field is set to contain all
* statements in the function
* static specs of function, used by hip/sleek system
* A block is a sequence of statements with the control falling through from
one element to the next
* Attributes for the block
* The statements comprising the block
* Statements.
* Whether the statement starts with some labels, case statements or
* default statements.
* The kind of statement
* Labels
* A real label. If the bool is "true", the label is from the
* input source program. If the bool is "false", the label was
* created by CIL or some other transformation
* A case statement. This expression
* is lowered into a constant if
* {!Cil.lowerConstants} is set to
* true.
* A default statement
* The various kinds of control-flow statements statements
* A group of instructions that do not contain control flow. Control
* implicitly falls through.
* A continue to the start of the nearest enclosing [Loop]
* A switch statement. The statements that implement the cases can be
* reached through the provided list. For each such target you can find
* among its labels what cases it implements. The statements that
* implement the cases are somewhere within the provided [block].
* Just a block of statements. Use it as a way to keep some block
* attributes local
* {b Instructions}.
An instruction {!Cil.instr} is a statement that has no local
(intraprocedural) control flow. It can be either an assignment,
function call, or an inline assembly instruction.
* Instructions.
* An assignment. The type of the expression is guaranteed to be the same
* with that of the lvalue
Really only const and volatile can appear
* here
templates (CR-separated)
inputs with optional names and constraints
register clobbers
* Describes a position in a source file
* The line number. -1 means "do not know"
* The name of the source file
* The begin of line position in the source file
* The byte position in the source file
* Describes a location in a source file
* {b Lowering Options}
* Do lower constants (default true)
* Do insert implicit casts (default true)
* To be able to add/remove features easily, each feature should be package
* as an interface with the following interface. These features should be
* The enable flag. Set to default value
* This is used to construct an option "--doxxx" and "--dontxxx" that
* enable and disable the feature
* A longer name that can be used to document the new options
* Additional command line options. The description strings should
usually start with a space for Arg.align to print the --help nicely.
* This performs the transformation
* Whether to perform a CIL consistency checking after this stage, if
* checking is enabled (--check is passed to cilly). Set this to true if
* your feature makes any changes for the program.
val compareLoc: position -> position -> int
* {b Values for manipulating globals}
* Make an empty function
* Update the formals of a [fundec] and make sure that the function type
has the same information. Will copy the name as well into the type.
* Set the type of the function and make formal arguments for them
* A dummy function declaration handy when you need one as a placeholder. It
* contains inside a dummy varinfo.
* A dummy file
* Write a {!Cil.file} in binary form to the filesystem. The file can be
* read back in later using {!Cil.loadBinaryFile}, possibly saving parsing
* time. Does not close the channel.
* Get the global initializer and create one if it does not already exist.
* When it creates a global initializer it attempts to place a call to it in
* the main function named by the optional argument (default "main")
* Iterate over all globals, including the global initializer
* Fold over all globals, including the global initializer
* Map over all globals, including the global initializer and change things
in place
* Find a function or function prototype with the given name in the file.
* If it does not exist, create a prototype with the given type, and return
* the new varinfo. This is useful when you need to call a libc function
* whose prototype may or may not already exist in the file.
*
* Because the new prototype is added to the start of the file, you shouldn't
* refer to any struct or union types in the function type.
* Create a deep copy of a function. There should be no sharing between the
* copy and the original function
* CIL keeps the types at the beginning of the file and the variables at the
* end of the file. This function will take a global and add it to the
* corresponding stack. Its operation is actually more complicated because if
* the global declares a type that contains references to variables (e.g. in
* sizeof in an array length) then it will also add declarations for the
* variables to the types stack
* An empty statement. Used in pretty printing
* This is used as the location of the prototypes of builtin functions.
* {b Values for manipulating initializers}
* {b Values for manipulating types}
* void
* is the given type "void"?
* is the given type "void *"?
* int
* unsigned int
* long
* unsigned long
* char
* char *
* char const *
* void *
* int *
* unsigned int *
* double
* Returns true if and only if the given integer type is signed.
whether it is a struct or a union
name of the composite type; cannot be empty
a function that when given a forward
representation of the structure type constructs the type of
the fields. The function can ignore this argument if not
constructing a recursive type.
* This is a constant used as the name of an unnamed bitfield. These fields
do not participate in initialization and their name is not printed.
* Get the full name of a comp
* Returns true if this is a complete type.
This means that sizeof(t) makes sense.
Incomplete types are not yet defined
structures and empty arrays.
* Unroll a type until it exposes a non
* [TNamed]. Will collect all attributes appearing in [TNamed]!!!
* Separate out the storage-modifier name attributes
* True if the argument is an integral type (i.e. integer or enum)
* True if the argument is an arithmetic type (i.e. integer, enum or
floating point
*True if the argument is a pointer type
*True if the argument is a scalar type
* True if the argument is a function type
* Obtain the argument list ([] if None)
* True if the argument is an array type
* Raised when {!Cil.lenOfArray} fails either because the length is [None]
* or because it is a non-constant expression
* A datatype to be used in conjunction with [existsType]
* We have found it
* Stop processing this branch
* This node is not what we are
* looking for but maybe its
* successors are
* Given a function type split it into return type,
* arguments, is_vararg and attributes. An error is raised if the type is not
* a function type
* Same as {!Cil.splitFunctionType} but takes a varinfo. Prints a nicer
* error message if the varinfo is not for a function
* {b Type signatures}
* Print a type signature
* Compute a type signature
* Like {!Cil.typeSig} but customize the incorporation of attributes.
Use ~ignoreSign:true to convert all signed integer types to unsigned,
so that signed and unsigned will compare the same.
* Replace the attributes of a signature (only at top level)
* Get the top-level attributes of a signature
*******************************************************
* {b Lvalues}
* Make a local variable and add it to a function's slocals (only if insert =
true, which is the default). Make sure you know what you are doing if you
set insert=false.
* Make a global variable. Your responsibility to make sure that the name
is unique
* Make a shallow copy of a [varinfo] and assign a new identifier
* Add an offset at the end of an lvalue. Make sure the type of the lvalue
* and the offset are compatible.
* [addOffset o1 o2] adds [o1] to the end of [o2].
* Compute the type of an lvalue
* Compute the type of an offset from a base type
*****************************************************
* {b Values for manipulating expressions}
* -1
* Construct an integer of a given kind, from a cilint. If needed it
* will truncate the integer to be within the representable range for
* the given kind.
* If the given expression is an integer constant or a CastE'd
integer constant, return that constant's value.
Otherwise return None.
* Convert a cilint int to an OCaml int, or raise an exception if that
can't be done.
* True if the expression is a compile-time constant
* True if the given offset contains only field nanmes or constant indices.
* Increment an expression. Can be arithmetic or pointer type
* Makes an lvalue out of a given variable
* Like mkAddrOf except if the type of lval is an array then it uses
StartOf. This is the right operation for getting a pointer to the start
of the storage denoted by lval.
* Make an expression that is a string constant (of pointer type)
* Construct a cast when having the old type of the expression. If the new
* type is the same as the old type, then no cast is added.
* Compute the type of an expression
********************************************
* {b Values for manipulating statements}
* Construct a block with no attributes, given a list of statements
* Returns an empty statement (of kind [Instr])
* A instr to serve as a placeholder
* A statement consisting of just [dummyInstr]
* Make a while loop. Can contain Break or Continue
* Make a for loop for(start; guard; next) \{ ... \}. The body can
contain Break but not Continue !!!
************************************************
* {b Values for manipulating attributes}
* Various classes of attributes
* Attribute of a type
* This table contains the mapping of predefined attributes to classes.
Extend this table with more attributes as you need. This table is used to
determine how to associate attributes with names or types
* Partition the attributes into classes:name attributes, function type,
and type attributes
AttrName
AttrFunType
* Remove all attributes with the given name. Maintains the attributes in
sorted order.
* Remove all attributes with names appearing in the string list.
* Maintains the attributes in sorted order
* Retains attributes with the given name
* True if the named attribute appears in the attribute list. The list of
attributes must be sorted.
* Returns all the attributes contained in a type. This requires a traversal
of the type structure, in case of composite, enumeration and named types
Resets the attributes
* Add some attributes to a type
* Remove all attributes with the given names from a type. Note that this
does not remove attributes from typedef and tag definitions, just from
their uses
* Convert an expression into an attrparam, if possible. Otherwise raise
NotAnAttrParam with the offending subexpression
*****************
****************** VISITOR
*****************
* {b The visitor}
* Different visiting actions. 'a will be instantiated with [exp], [instr],
etc.
* Do not visit the children. Return
the node as it is.
* Continue with the children of this
node. Rebuild the node on return
if any of the children changes
(use == test)
* Invoked on each expression occurrence. The subtrees are the
* subexpressions, the types (for a [Cast] or [SizeOf] expression) or the
* variable use.
* Invoked on each lvalue occurrence
* Invoked on each offset occurrence that is *not* as part
* of an initializer list specification, i.e. in an lval or
* recursively inside an offset.
* Invoked on each instruction occurrence. The [ChangeTo] action can
* replace this instruction with a list of instructions
* Block.
* Function definition.
Replaced in place.
* Global (vars, types,
etc.)
* Initializers for globals,
* pass the global where this
* occurs, and the offset
* Use of some type. Note
* that for structure/union
* and enumeration types the
* definition of the
* composite type is not
* visited. Use [vglob] to
* visit it.
* Attribute. Each attribute can be replaced by a list
* Attribute parameters.
* Add here instructions while visiting to queue them to preceede the
* current statement or instruction being processed. Use this method only
* when you are visiting an expression that is inside a function body, or
* a statement, because otherwise there will no place for the visitor to
* place your instructions.
* Gets the queue of instructions and resets the queue. This is done
* automatically for you when you visit statments.
* Default Visitor. Traverses the CIL tree without modifying anything
* Visit a file. This will will re-cons all globals TWICE (so that it is
* tail-recursive). Use {!Cil.visitCilFileSameGlobals} if your visitor will
* not change the list of globals.
* A visitor for the whole file that does not change the globals (but maybe
* changes things inside the globals). Use this function instead of
* {!Cil.visitCilFile} whenever appropriate because it is more efficient for
* long files.
* Visit a global
* Visit a function definition
Visit an expression
* Visit an lvalue
* Visit an lvalue or recursive offset
* Visit an initializer offset
* Visit an instruction
* Visit a statement
* Visit a block
* Visit a type
* Visit a variable declaration
* Visit an initializer, pass also the global to which this belongs and the
* offset.
* Visit a list of attributes
And some generic visitors. The above are built with these
* {b Utility functions}
* A visitor that does constant folding. Pass as argument whether you want
* machine specific simplifications to be done, or not.
* Styles of printing line directives
* Before every element, print the line
* number in comments. This is ignored by
* processing tools (thus errors are reproted
* in the CIL output), but useful for
* visual inspection
* Like LineComment but only print a line
* directive for a new source line
* Use # nnn directives (in gcc mode)
* How to print line directives
* Whether we print something that will only be used as input to our own
* parser. In that case we are a bit more liberal in what we print
* The length used when wrapping output lines. Setting this variable to
* a large integer will prevent wrapping and make #line directives more
* accurate.
* {b Debugging support}
* A reference to the current location. If you are careful to set this to
* the current location then you can use some built-in logging functions that
* will print the location.
* A reference to the current global being visited
* Pretty-print a location
* Pretty-print the {!Cil.currentLoc}
* Pretty-print an integer of a given kind
* Pretty-print a floating-point kind
* Pretty-print storage-class information
* Pretty-print a constant
* Parentheses level. An expression "a op b" is printed parenthesized if its
* parentheses level is >= that that of its context. Identifiers have the
* lowest level and weakly binding operators (e.g. |) have the largest level.
* The correctness criterion is that a smaller level MUST correspond to a
* stronger precedence!
* A printer interface for CIL trees. Create instantiations of
* this type by specializing the class {!Cil.defaultCilPrinterClass}.
* Invoked for each variable declaration. Note that variable
* declarations are all the [GVar], [GVarDecl], [GFun], all the [varinfo]
* in formals of function types, and the formals and locals for function
* definitions.
* Invoked on each variable use.
* Invoked on each lvalue occurrence
* Invoked on each instruction occurrence.
* Print a label.
* Control-flow statement. This is used by
* {!Cil.printGlobal} and by {!Cil.dumpGlobal}.
* Dump a control-flow statement to a file with a given indentation.
* This is used by {!Cil.dumpGlobal}.
* Dump a control-flow block to a file with a given indentation.
* This is used by {!Cil.dumpGlobal}.
* Print a block.
* Global (vars, types, etc.). This can be slow and is used only by
* {!Cil.printGlobal} but not by {!Cil.dumpGlobal}.
* Dump a global to a file with a given indentation. This is used by
* {!Cil.dumpGlobal}
* A field declaration
* Attribute. Also return an indication whether this attribute must be
* printed inside the __attribute__ list or not.
* Attribute parameter
* Attribute lists
* Print a line-number. This is assumed to come always on an empty line.
* If the forcefile argument is present and is true then the file name
* will be printed always. Otherwise the file name is printed only if it
* is different from the last time time this function is called. The last
* file name is stored in a private field inside the cilPrinter object.
* Print expressions
* Print location
* Print initializers. This can be slow and is used by
* {!Cil.printGlobal} but not by {!Cil.dumpGlobal}.
* Dump a global to a file with a given indentation. This is used by
* {!Cil.dumpGlobal}
* These are pretty-printers that will show you more details on the internal
* CIL representation, without trying hard to make it look like C
* Like defaultCilPrinterClass, but instead of temporary variable
names it prints the description that was provided when the temp was
created. This is usually better for messages that are printed for end
users, although you may want the temporary names for debugging.
The boolean here enables descriptive printing. Usually use true
here, but you can set enable to false to make this class behave
like defaultCilPrinterClass. This allows subclasses to turn the
feature off.
Top-level printing functions
* Print a type given a pretty printer
* Print an expression given a pretty printer
* Print an lvalue given a pretty printer
* Print a global given a pretty printer
* Print an attribute given a pretty printer
* Print a set of attributes given a pretty printer
* Print an instruction given a pretty printer
* Print a block given a pretty printer. This can take very long
* (or even overflow the stack) for huge block. Use {!Cil.dumpBlock}
* instead.
* Dump a statement to a file using a given indentation. Use this instead of
* {!Cil.printStmt} whenever possible.
* Dump a block to a file using a given indentation. Use this instead of
* {!Cil.printBlock} whenever possible.
* Print an initializer given a pretty printer. This can take very long
* (or even overflow the stack) for huge initializers. Use {!Cil.dumpInit}
* instead.
* Dump an initializer to a file using a given indentation. Use this instead of
* {!Cil.printInit} whenever possible.
* Pretty-print a binary operator
* Pretty-print a unary operator
* Versions of the above pretty printers, that don't print #line directives
dn_offset is missing because it has a different interface
* Pretty-print a short description of the global. This is useful for error
* messages
* Pretty-print a global. Here you give the channel where the printout
* should be sent.
* Pretty-print an entire file. Here you give the channel where the printout
* should be sent.
* Like {!Errormsg.unimp} except that {!Cil.currentLoc}is also printed
* Like {!Cil.error} except that it explicitly takes a location argument,
* instead of using the {!Cil.currentLoc}
* Like {!Cil.warn} except that it explicitly takes a location argument,
* instead of using the {!Cil.currentLoc}
* Sometimes you do not want to see the syntactic sugar that the above
* pretty-printing functions add. In that case you can use the following
* pretty-printing functions. But note that the output of these functions is
* not valid C
* Pretty-print the internal representation of an expression
* Pretty-print the internal representation of an integer
* Pretty-print the internal representation of an lvalue
* Pretty-print the internal representation of an lvalue offset
val d_plainoffset: unit -> offset -> Pretty.doc
* Pretty-print the internal representation of a type
* Pretty-print an expression while printing descriptions rather than names
of temporaries.
* Pretty-print an lvalue on the left side of an assignment.
If there is an offset or memory dereference, temporaries will
be replaced by descriptions as in dd_exp. If the lval is a temp var,
that var will not be replaced by a description; use "dd_exp () (Lval lv)"
if that's what you want.
* String conversation functions
* {b ALPHA conversion} has been moved to the Alpha module.
* {b Optimization Passes}
* {b Machine dependency}
* Give the unsigned kind corresponding to any integer kind
* Give the signed kind corresponding to any integer kind
* Return the integer conversion rank of an integer kind
* The float kind for a given size. Raises Not_found
* if no such kind exists
* The size in bytes of the given int kind.
* True if the integer fits within the kind's range
* Represents a location that cannot be determined
* Represents a location that cannot be determined
* Return the starting position of a location
* Return the ending position of a location
* Return the location of an instruction
* Generate an {!Cil.exp} to be used in case of errors.
* Generate an {!Cil.instr} to be used in case of errors.
* Like map but try not to make a copy of the list
* Like map but each call can return a list. Try not to make a copy of the
list
* If string has leading and trailing __, strip them.
* {b An Interpreter for constructing CIL constructs}
* The type of argument for the interpreter
* For array lengths
* For arguments in a function call
* For a formal argument
* For formal argument lists
* For the ellipsis in a function type
* Pretty-prints a format arg
* Emit warnings when truncating integer constants (default true)
* Machine model specified via CIL_MACHINE environment variable
-------------------------------------------------------------------------
DEPRECATED FUNCTIONS
These will eventually go away
-------------------------------------------------------------------------
* @deprecated. Use truncateCilint instead. Represents an integer as
* for a given kind. Returns a flag saying whether the value was
* changed during truncation (because it was too large to fit in k).
* @deprecated. For compatibility with older programs, these are
aliases for {!Cil.builtinFunctions}
* @deprecated. For compatibility with older programs, these are
aliases for {!Cil.builtinFunctions} |
*
* Copyright ( c ) 2001 - 2002 ,
* < >
* < >
* < >
* 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 names of the contributors may not be used to endorse or promote
* products derived from this software without specific prior written
* permission .
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS
* IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT LIMITED
* TO , THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED . IN NO EVENT SHALL THE COPYRIGHT OWNER
* OR 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) 2001-2002,
* George C. Necula <>
* Scott McPeak <>
* Wes Weimer <>
* 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 names of the contributors may not be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
* OR 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.
*
*)
* CIL : An intermediate language for analyzing C programs .
*
* *
* CIL: An intermediate language for analyzing C programs.
*
* George Necula
*
*)
open Cilint
val initCIL: unit -> unit
val cilVersion: string
val cilVersionMajor: int
val cilVersionMinor: int
val cilVersionRevision: int
* This module defines the abstract syntax of CIL . It also provides utility
* functions for traversing the CIL data structures , and pretty - printing
* them . The parser for both the GCC and MSVC front - ends can be invoked as
* [ Frontc.parse : string - > unit - > ] { ! Cil.file } . This function must be given
* the name of a preprocessed C file and will return the top - level data
* structure that describes a whole source file . By default the parsing and
* elaboration into CIL is done as for GCC source . If you want to use MSVC
* source you must set the { ! Cil.msvcMode } to [ true ] and must also invoke the
* function [ Frontc.setMSVCMode : unit - > unit ] .
* functions for traversing the CIL data structures, and pretty-printing
* them. The parser for both the GCC and MSVC front-ends can be invoked as
* [Frontc.parse: string -> unit ->] {!Cil.file}. This function must be given
* the name of a preprocessed C file and will return the top-level data
* structure that describes a whole source file. By default the parsing and
* elaboration into CIL is done as for GCC source. If you want to use MSVC
* source you must set the {!Cil.msvcMode} to [true] and must also invoke the
* function [Frontc.setMSVCMode: unit -> unit]. *)
type file =
mutable globinit: fundec option;
mutable globinitcalled: bool;
* Whether the global initialization function is called in main . This
* should always be false if there is no global initializer . When you
* create a global initialization CIL will try to insert code in main
* to call it . This will not happen if your file does not contain a
* function called " main "
* should always be false if there is no global initializer. When you
* create a global initialization CIL will try to insert code in main
* to call it. This will not happen if your file does not contain a
* function called "main" *)
}
and comment = location * string
and global =
| GType of typeinfo * location
| GCompTag of compinfo * location
* Defines a struct / union tag with some fields . There must be one of
these for each struct / union tag that you use ( through the [ TComp ]
constructor ) since this is the only context in which the fields are
printed . Consequently nested structure tag definitions must be
broken into individual definitions with the innermost structure
defined first .
these for each struct/union tag that you use (through the [TComp]
constructor) since this is the only context in which the fields are
printed. Consequently nested structure tag definitions must be
broken into individual definitions with the innermost structure
defined first. *)
| GCompTagDecl of compinfo * location
| GEnumTag of enuminfo * location
| GEnumTagDecl of enuminfo * location
| GVarDecl of varinfo * location
* A variable declaration ( not a definition ) . If the variable has a
function type then this is a prototype . There can be several
declarations and at most one definition for a given variable . If both
forms appear then they must share the same varinfo structure . A
prototype shares the varinfo with the fundec of the definition . Either
has storage Extern or there must be a definition in this file
function type then this is a prototype. There can be several
declarations and at most one definition for a given variable. If both
forms appear then they must share the same varinfo structure. A
prototype shares the varinfo with the fundec of the definition. Either
has storage Extern or there must be a definition in this file *)
| GVar of varinfo * initinfo * location
* A variable definition . Can have an initializer . The initializer is
* updateable so that you can change it without requiring to recreate
* the list of globals . There can be at most one definition for a
* variable in an entire program . Can not have storage Extern or function
* type .
* updateable so that you can change it without requiring to recreate
* the list of globals. There can be at most one definition for a
* variable in an entire program. Cannot have storage Extern or function
* type. *)
| GFun of fundec * location
* at top level . Use the same
syntax as attributes
syntax as attributes *)
* { b Types } . A C type is represented in CIL using the type { ! Cil.typ } .
* Among types we differentiate the integral types ( with different kinds
* denoting the sign and precision ) , floating point types , enumeration types ,
* array and pointer types , and function types . Every type is associated with
* a list of attributes , which are always kept in sorted order . Use
* { ! Cil.addAttribute } and { ! Cil.addAttributes } to construct list of
* attributes . If you want to inspect a type , you should use
* { ! } or { ! Cil.unrollTypeDeep } to see through the uses of
* named types .
* Among types we differentiate the integral types (with different kinds
* denoting the sign and precision), floating point types, enumeration types,
* array and pointer types, and function types. Every type is associated with
* a list of attributes, which are always kept in sorted order. Use
* {!Cil.addAttribute} and {!Cil.addAttributes} to construct list of
* attributes. If you want to inspect a type, you should use
* {!Cil.unrollType} or {!Cil.unrollTypeDeep} to see through the uses of
* named types. *)
* CIL is configured at build - time with the sizes and alignments of the
* underlying compiler ( GCC or MSVC ) . CIL contains functions that can compute
* the size of a type ( in bits ) { ! } , the alignment of a type
* ( in bytes ) { ! Cil.alignOf_int } , and can convert an offset into a start and
* width ( both in bits ) using the function { ! Cil.bitsOffset } . At the moment
* these functions do not take into account the [ packed ] attributes and
* pragmas .
* underlying compiler (GCC or MSVC). CIL contains functions that can compute
* the size of a type (in bits) {!Cil.bitsSizeOf}, the alignment of a type
* (in bytes) {!Cil.alignOf_int}, and can convert an offset into a start and
* width (both in bits) using the function {!Cil.bitsOffset}. At the moment
* these functions do not take into account the [packed] attributes and
* pragmas. *)
and typ =
| TInt of ikind * attributes
* An integer type . The kind specifies the sign and width . Several
* useful variants are predefined as { ! Cil.intType } , { ! Cil.uintType } ,
* { ! Cil.longType } , { ! Cil.charType } .
* useful variants are predefined as {!Cil.intType}, {!Cil.uintType},
* {!Cil.longType}, {!Cil.charType}. *)
| TFloat of fkind * attributes
| TPtr of typ * attributes
* Pointer type . Several useful variants are predefined as
* { ! Cil.charPtrType } , { ! } ( pointer to a
* constant character ) , { ! } ,
* { ! Cil.intPtrType }
* {!Cil.charPtrType}, {!Cil.charConstPtrType} (pointer to a
* constant character), {!Cil.voidPtrType},
* {!Cil.intPtrType} *)
| TArray of typ * exp option * attributes
| TFun of typ * (string * typ * attributes) list option * bool * attributes
| TNamed of typeinfo * attributes
* The use of a named type . Each such type name must be preceded
* in the file by a [ GType ] global . This is printed as just the
* type name . The actual referred type is not printed here and is
* carried only to simplify processing . To see through a sequence
* of named type references , use { ! } or
* { ! Cil.unrollTypeDeep } . The attributes are in addition to those
* given when the type name was defined .
* in the file by a [GType] global. This is printed as just the
* type name. The actual referred type is not printed here and is
* carried only to simplify processing. To see through a sequence
* of named type references, use {!Cil.unrollType} or
* {!Cil.unrollTypeDeep}. The attributes are in addition to those
* given when the type name was defined. *)
| TComp of compinfo * attributes
* The most delicate issue for C types is that recursion that is possible by
* using structures and pointers . To address this issue we have a more
* complex representation for structured types ( struct and union ) . Each such
* type is represented using the { ! } type . For each composite
* type the { ! } structure must be declared at top level using
* [ GCompTag ] and all references to it must share the same copy of the
* structure . The attributes given are those pertaining to this use of the
* type and are in addition to the attributes that were given at the
* definition of the type and which are stored in the { ! } .
* using structures and pointers. To address this issue we have a more
* complex representation for structured types (struct and union). Each such
* type is represented using the {!Cil.compinfo} type. For each composite
* type the {!Cil.compinfo} structure must be declared at top level using
* [GCompTag] and all references to it must share the same copy of the
* structure. The attributes given are those pertaining to this use of the
* type and are in addition to the attributes that were given at the
* definition of the type and which are stored in the {!Cil.compinfo}. *)
| TEnum of enuminfo * attributes
| TBuiltin_va_list of attributes
*
There are a number of functions for querying the kind of a type . These are
{ ! Cil.isIntegralType } ,
{ ! Cil.isArithmeticType } ,
{ ! Cil.isPointerType } ,
{ ! } ,
{ ! } ,
{ ! } .
There are two easy ways to scan a type . First , you can use the
{ ! to return a boolean answer about a type . This function
is controlled by a user - provided function that is queried for each type that is
used to construct the current type . The function can specify whether to
terminate the scan with a boolean result or to continue the scan for the
nested types .
The other method for scanning types is provided by the visitor interface ( see
{ ! Cil.cilVisitor } ) .
If you want to compare types ( or to use them as hash - values ) then you should
use instead type signatures ( represented as { ! Cil.typsig } ) . These
contain the same information as types but canonicalized such that simple Ocaml
structural equality will tell whether two types are equal . Use
{ ! Cil.typeSig } to compute the signature of a type . If you want to ignore
certain type attributes then use { ! Cil.typeSigWithAttrs } .
There are a number of functions for querying the kind of a type. These are
{!Cil.isIntegralType},
{!Cil.isArithmeticType},
{!Cil.isPointerType},
{!Cil.isScalarType},
{!Cil.isFunctionType},
{!Cil.isArrayType}.
There are two easy ways to scan a type. First, you can use the
{!Cil.existsType} to return a boolean answer about a type. This function
is controlled by a user-provided function that is queried for each type that is
used to construct the current type. The function can specify whether to
terminate the scan with a boolean result or to continue the scan for the
nested types.
The other method for scanning types is provided by the visitor interface (see
{!Cil.cilVisitor}).
If you want to compare types (or to use them as hash-values) then you should
use instead type signatures (represented as {!Cil.typsig}). These
contain the same information as types but canonicalized such that simple Ocaml
structural equality will tell whether two types are equal. Use
{!Cil.typeSig} to compute the signature of a type. If you want to ignore
certain type attributes then use {!Cil.typeSigWithAttrs}.
*)
and ikind =
* [ _ ( C99 ) ]
* [ long long ] ( or [ _ int64 ] on Microsoft Visual C )
* [ unsigned long long ] ( or [ unsigned _ int64 ] on Microsoft
Visual C )
Visual C) *)
and fkind =
and attribute = Attr of string * attrparam list
and attributes = attribute list
and attrparam =
| ASizeOfE of attrparam
| AAlignOf of typ
| AAlignOfE of attrparam
| AAlignOfS of typsig
| AUnOp of unop * attrparam
| ABinOp of binop * attrparam * attrparam
* { b Structures . } The { ! } describes the definition of a
* structure or union type . Each such { ! } must be defined at the
* top - level using the [ GCompTag ] constructor and must be shared by all
* references to this type ( using either the [ TComp ] type constructor or from
* the definition of the fields .
If all you need is to scan the definition of each
* composite type once , you can do that by scanning all top - level [ GCompTag ] .
* Constructing a { ! } can be tricky since it must contain fields
* that might refer to the host { ! } and furthermore the type of
* the field might need to refer to the { ! } for recursive types .
* Use the { ! Cil.mkCompInfo } function to create a { ! } . You can
* easily fetch the { ! Cil.fieldinfo } for a given field in a structure with
* { ! Cil.getCompField } .
* structure or union type. Each such {!Cil.compinfo} must be defined at the
* top-level using the [GCompTag] constructor and must be shared by all
* references to this type (using either the [TComp] type constructor or from
* the definition of the fields.
If all you need is to scan the definition of each
* composite type once, you can do that by scanning all top-level [GCompTag].
* Constructing a {!Cil.compinfo} can be tricky since it must contain fields
* that might refer to the host {!Cil.compinfo} and furthermore the type of
* the field might need to refer to the {!Cil.compinfo} for recursive types.
* Use the {!Cil.mkCompInfo} function to create a {!Cil.compinfo}. You can
* easily fetch the {!Cil.fieldinfo} for a given field in a structure with
* {!Cil.getCompField}. *)
* The definition of a structure or union type . Use { ! Cil.mkCompInfo } to
* make one and use { ! Cil.copyCompInfo } to copy one ( this ensures that a new
* key is assigned and that the fields have the right pointers to parents . ) .
* make one and use {!Cil.copyCompInfo} to copy one (this ensures that a new
* key is assigned and that the fields have the right pointers to parents.). *)
and compinfo = {
mutable cstruct: bool;
mutable cname: string;
mutable ckey: int;
* A unique integer . This is assigned by { ! Cil.mkCompInfo } using a
* global variable in the module . Thus two identical structs in two
* different files might have different keys . Use { ! Cil.copyCompInfo } to
* copy structures so that a new key is assigned .
* global variable in the Cil module. Thus two identical structs in two
* different files might have different keys. Use {!Cil.copyCompInfo} to
* copy structures so that a new key is assigned. *)
mutable cfields: fieldinfo list;
* Information about the fields . Notice that each fieldinfo has a
* pointer back to the host compinfo . This means that you should not
* share 's between two compinfo 's
* pointer back to the host compinfo. This means that you should not
* share fieldinfo's between two compinfo's *)
mutable cattr: attributes;
* The attributes that are defined at the same time as the composite
* type . These attributes can be supplemented individually at each
* reference to this [ compinfo ] using the [ TComp ] type constructor .
* type. These attributes can be supplemented individually at each
* reference to this [compinfo] using the [TComp] type constructor. *)
mutable cdefined: bool;
mutable creferenced: bool;
}
* { b Structure fields . } The { ! Cil.fieldinfo } structure is used to describe
* a structure or union field . , just like variables , can have
* attributes associated with the field itself or associated with the type of
* the field ( stored along with the type of the field ) .
* a structure or union field. Fields, just like variables, can have
* attributes associated with the field itself or associated with the type of
* the field (stored along with the type of the field). *)
and fieldinfo = {
mutable fcomp: compinfo;
* The host structure that contains this field . There can be only one
* [ compinfo ] that contains the field .
* [compinfo] that contains the field. *)
mutable fname: string;
mutable ftype: typ;
mutable fbitfield: int option;
* If a bitfield then ftype should be an integer type and the width of
* the bitfield must be 0 or a positive integer smaller or equal to the
* width of the integer type . A field of width 0 is used in C to control
* the alignment of fields .
* the bitfield must be 0 or a positive integer smaller or equal to the
* width of the integer type. A field of width 0 is used in C to control
* the alignment of fields. *)
mutable fattr: attributes;
mutable fdefn: location;
}
and enuminfo = {
mutable ename: string;
mutable eitems: (string * exp * location) list;
mutable eattr: attributes;
mutable ereferenced: bool;
mutable ekind: ikind;
* The integer kind used to represent this enum . Per ANSI - C , this
* should always be IInt , but gcc allows other integer kinds
* should always be IInt, but gcc allows other integer kinds *)
}
and typeinfo = {
mutable tname: string;
* The name . Can be empty only in a [ GType ] when introducing a composite
* or enumeration tag . If empty can not be referred to from the file
* or enumeration tag. If empty cannot be referred to from the file *)
mutable ttype: typ;
mutable treferenced: bool;
}
* { b Variables . }
Each local or global variable is represented by a unique { ! Cil.varinfo }
structure . A global { ! Cil.varinfo } can be introduced with the [ GVarDecl ] or
[ GVar ] or [ GFun ] globals . A local varinfo can be introduced as part of a
function definition { ! Cil.fundec } .
All references to a given global or local variable must refer to the same
copy of the [ varinfo ] . Each [ varinfo ] has a globally unique identifier that
can be used to index maps and hashtables ( the name can also be used for this
purpose , except for locals from different functions ) . This identifier is
constructor using a global counter .
It is very important that you construct [ varinfo ] structures using only one
of the following functions :
- { ! Cil.makeGlobalVar } : to make a global variable
- { ! } : to make a temporary local variable whose name
will be generated so that to avoid conflict with other locals .
- { ! } : like { ! } but you can specify the
exact name to be used .
- { ! Cil.copyVarinfo } : make a shallow copy of a varinfo assigning a new name
and a new unique identifier
A [ varinfo ] is also used in a function type to denote the list of formals .
Each local or global variable is represented by a unique {!Cil.varinfo}
structure. A global {!Cil.varinfo} can be introduced with the [GVarDecl] or
[GVar] or [GFun] globals. A local varinfo can be introduced as part of a
function definition {!Cil.fundec}.
All references to a given global or local variable must refer to the same
copy of the [varinfo]. Each [varinfo] has a globally unique identifier that
can be used to index maps and hashtables (the name can also be used for this
purpose, except for locals from different functions). This identifier is
constructor using a global counter.
It is very important that you construct [varinfo] structures using only one
of the following functions:
- {!Cil.makeGlobalVar} : to make a global variable
- {!Cil.makeTempVar} : to make a temporary local variable whose name
will be generated so that to avoid conflict with other locals.
- {!Cil.makeLocalVar} : like {!Cil.makeTempVar} but you can specify the
exact name to be used.
- {!Cil.copyVarinfo}: make a shallow copy of a varinfo assigning a new name
and a new unique identifier
A [varinfo] is also used in a function type to denote the list of formals.
*)
and varinfo = {
mutable vname: string;
* The name of the variable . Can not be empty . It is primarily your
* responsibility to ensure the uniqueness of a variable name . For local
* variables { ! Cil.makeTempVar } helps you ensure that the name is unique .
* responsibility to ensure the uniqueness of a variable name. For local
* variables {!Cil.makeTempVar} helps you ensure that the name is unique.
*)
mutable vtype: typ;
mutable vattr: attributes;
mutable vstorage: storage;
mutable vglob: bool;
mutable vinline: bool;
mutable vdecl: location;
mutable vid: int;
* A unique integer identifier . This field will be
* set for you if you use one of the { ! Cil.makeFormalVar } ,
* { ! } , { ! } , { ! Cil.makeGlobalVar } , or
* { ! Cil.copyVarinfo } .
* set for you if you use one of the {!Cil.makeFormalVar},
* {!Cil.makeLocalVar}, {!Cil.makeTempVar}, {!Cil.makeGlobalVar}, or
* {!Cil.copyVarinfo}. *)
mutable vaddrof: bool;
* True if the address of this variable is taken . CIL will set these
* flags when it parses C , but you should make sure to set the flag
* whenever your transformation create [ ] expression .
* flags when it parses C, but you should make sure to set the flag
* whenever your transformation create [AddrOf] expression. *)
mutable vreferenced: bool;
* True if this variable is ever referenced . This is computed by
* { ! } . It is safe to just initialize this to False
* {!Rmtmps.removeUnusedTemps}. It is safe to just initialize this to False *)
mutable vdescr: Pretty.doc;
mutable vdescrpure: bool;
* Indicates whether the vdescr above is a pure expression or call .
* Printing a non - pure vdescr more than once may yield incorrect
* results .
* Printing a non-pure vdescr more than once may yield incorrect
* results. *)
}
and storage =
| Static
| Register
| Extern
* { b Expressions . } The CIL expression language contains only the side - effect free expressions of
C. They are represented as the type { ! Cil.exp } . There are several
interesting aspects of CIL expressions :
Integer and floating point constants can carry their textual representation .
This way the integer 15 can be printed as 0xF if that is how it occurred in the
source .
CIL uses 64 bits to represent the integer constants and also stores the width
of the integer type . Care must be taken to ensure that the constant is
representable with the given width . Use the functions { ! Cil.kinteger } ,
{ ! Cil.kinteger64 } and { ! Cil.integer } to construct constant
expressions . CIL predefines the constants { ! Cil.zero } ,
{ ! Cil.one } and { ! Cil.mone } ( for -1 ) .
Use the functions { ! Cil.isConstant } and { ! Cil.isInteger } to test if
an expression is a constant and a constant integer respectively .
CIL keeps the type of all unary and binary expressions . You can think of that
type qualifying the operator . Furthermore there are different operators for
arithmetic and comparisons on arithmetic types and on pointers .
Another unusual aspect of CIL is that the implicit conversion between an
expression of array type and one of pointer type is made explicit , using the
[ StartOf ] expression constructor ( which is not printed ) . If you apply the
[ AddrOf}]constructor to an lvalue of type [ T ] then you will be getting an
expression of type [ TPtr(T ) ] .
You can find the type of an expression with { ! Cil.typeOf } .
You can perform constant folding on expressions using the function
{ ! } .
C. They are represented as the type {!Cil.exp}. There are several
interesting aspects of CIL expressions:
Integer and floating point constants can carry their textual representation.
This way the integer 15 can be printed as 0xF if that is how it occurred in the
source.
CIL uses 64 bits to represent the integer constants and also stores the width
of the integer type. Care must be taken to ensure that the constant is
representable with the given width. Use the functions {!Cil.kinteger},
{!Cil.kinteger64} and {!Cil.integer} to construct constant
expressions. CIL predefines the constants {!Cil.zero},
{!Cil.one} and {!Cil.mone} (for -1).
Use the functions {!Cil.isConstant} and {!Cil.isInteger} to test if
an expression is a constant and a constant integer respectively.
CIL keeps the type of all unary and binary expressions. You can think of that
type qualifying the operator. Furthermore there are different operators for
arithmetic and comparisons on arithmetic types and on pointers.
Another unusual aspect of CIL is that the implicit conversion between an
expression of array type and one of pointer type is made explicit, using the
[StartOf] expression constructor (which is not printed). If you apply the
[AddrOf}]constructor to an lvalue of type [T] then you will be getting an
expression of type [TPtr(T)].
You can find the type of an expression with {!Cil.typeOf}.
You can perform constant folding on expressions using the function
{!Cil.constFold}.
*)
and exp =
*
| SizeOf of typ * location
| SizeOfE of exp * location
| SizeOfStr of string * location
| AlignOf of typ * location
| AlignOfE of exp * location
| UnOp of unop * exp * typ * location
| BinOp of binop * exp * exp * typ * location
| Question of exp * exp * exp * typ * location
| CastE of typ * exp * location
| AddrOf of lval * location
* Always use { ! Cil.mkAddrOf } to construct one of these . Apply to an
* lvalue of type [ T ] yields an expression of type [ TPtr(T ) ] . Use
* { ! Cil.mkAddrOrStartOf } to make one of these if you are not sure which
* one to use .
* lvalue of type [T] yields an expression of type [TPtr(T)]. Use
* {!Cil.mkAddrOrStartOf} to make one of these if you are not sure which
* one to use. *)
| StartOf of lval * location
* Conversion from an array to a pointer to the beginning of the array .
* Given an lval of type [ TArray(T ) ] produces an expression of type
* [ TPtr(T ) ] . Use { ! Cil.mkAddrOrStartOf } to make one of these if you are
* not sure which one to use . In C this operation is implicit , the
* [ StartOf ] operator is not printed . We have it in CIL because it makes
* the typing rules simpler .
* Given an lval of type [TArray(T)] produces an expression of type
* [TPtr(T)]. Use {!Cil.mkAddrOrStartOf} to make one of these if you are
* not sure which one to use. In C this operation is implicit, the
* [StartOf] operator is not printed. We have it in CIL because it makes
* the typing rules simpler. *)
and constant =
| CInt64 of int64 * ikind * string option
* Integer constant . Give the ikind ( see ISO9899 6.1.3.2 ) and the
* textual representation , if available . ( This allows us to print a
* constant as , for example , 0xF instead of 15 . ) Use { ! Cil.integer } or
* { ! Cil.kinteger } to create these . Watch out for integers that can not be
* represented on 64 bits . OCAML does not give Overflow exceptions .
* textual representation, if available. (This allows us to print a
* constant as, for example, 0xF instead of 15.) Use {!Cil.integer} or
* {!Cil.kinteger} to create these. Watch out for integers that cannot be
* represented on 64 bits. OCAML does not give Overflow exceptions. *)
| CStr of string
| CWStr of int64 list
* Wide character string constant . Note that the local interpretation
* of such a literal depends on { ! } and { ! } .
* Such a constant has type pointer to { ! } . The
* escape characters in the string have not been " interpreted " in
* the sense that L"A\xabcd " remains " A\xabcd " rather than being
* represented as the wide character list with two elements : 65 and
* 43981 . That " interpretation " depends on the underlying wide
* character type .
* of such a literal depends on {!Cil.wcharType} and {!Cil.wcharKind}.
* Such a constant has type pointer to {!Cil.wcharType}. The
* escape characters in the string have not been "interpreted" in
* the sense that L"A\xabcd" remains "A\xabcd" rather than being
* represented as the wide character list with two elements: 65 and
* 43981. That "interpretation" depends on the underlying wide
* character type. *)
| CChr of char
* Character constant . This has type int , so use charConstToInt
* to read the value in case sign - extension is needed .
* to read the value in case sign-extension is needed. *)
| CReal of float * fkind * string option
* Floating point constant . Give the fkind ( see ISO 6.4.4.2 ) and also
* the textual representation , if available .
* the textual representation, if available. *)
| CEnum of exp * string * enuminfo
and unop =
and binop =
* { b Lvalues . } Lvalues are the sublanguage of expressions that can appear at the left of an assignment or as operand to the address - of operator .
In C the syntax for is not always a good indication of the meaning
of the lvalue . For example the C value
{ v
]
v }
might involve 1 , 2 or 3 memory reads when used in an expression context ,
depending on the declared type of the variable [ a ] . If [ a ] has type [ int
\[4\]\[4\]\[4\ ] ] then we have one memory read from somewhere inside the area
that stores the array [ a ] . On the other hand if [ a ] has type [ int * * * ] then
the expression really means [ * ( * ( * ( a + 0 ) + 1 ) + 2 ) ] , in which case it is
clear that it involves three separate memory operations .
An lvalue denotes the contents of a range of memory addresses . This range
is denoted as a host object along with an offset within the object . The
host object can be of two kinds : a local or global variable , or an object
whose address is in a pointer expression . We distinguish the two cases so
that we can tell quickly whether we are accessing some component of a
variable directly or we are accessing a memory location through a pointer .
To make it easy to
tell what an lvalue means CIL represents as a host object and an
offset ( see { ! Cil.lval } ) . The host object ( represented as
{ ! Cil.lhost } ) can be a local or global variable or can be the object
pointed - to by a pointer expression . The offset ( represented as
{ ! Cil.offset } ) is a sequence of field or array index designators .
Both the typing rules and the meaning of an lvalue is very precisely
specified in CIL .
The following are a few useful function for operating on lvalues :
- { ! Cil.mkMem } - makes an lvalue of [ Mem ] kind . Use this to ensure
that certain equivalent forms of are canonized .
For example , [ * & x = x ] .
- { ! Cil.typeOfLval } - the type of an lvalue
- { ! Cil.typeOffset } - the type of an offset , given the type of the
host .
- { ! Cil.addOffset } and { ! Cil.addOffsetLval } - extend sequences
of offsets .
- { ! Cil.removeOffset } and { ! Cil.removeOffsetLval } - shrink sequences
of offsets .
The following equivalences hold { v
a , aoff ) ) , off = Mem a , aoff + off
Mem(AddrOf(Var v , aoff ) ) , off = v , aoff + off
( Mem a , NoOffset ) = a
v }
In C the syntax for lvalues is not always a good indication of the meaning
of the lvalue. For example the C value
{v
a[0][1][2]
v}
might involve 1, 2 or 3 memory reads when used in an expression context,
depending on the declared type of the variable [a]. If [a] has type [int
\[4\]\[4\]\[4\]] then we have one memory read from somewhere inside the area
that stores the array [a]. On the other hand if [a] has type [int ***] then
the expression really means [* ( * ( * (a + 0) + 1) + 2)], in which case it is
clear that it involves three separate memory operations.
An lvalue denotes the contents of a range of memory addresses. This range
is denoted as a host object along with an offset within the object. The
host object can be of two kinds: a local or global variable, or an object
whose address is in a pointer expression. We distinguish the two cases so
that we can tell quickly whether we are accessing some component of a
variable directly or we are accessing a memory location through a pointer.
To make it easy to
tell what an lvalue means CIL represents lvalues as a host object and an
offset (see {!Cil.lval}). The host object (represented as
{!Cil.lhost}) can be a local or global variable or can be the object
pointed-to by a pointer expression. The offset (represented as
{!Cil.offset}) is a sequence of field or array index designators.
Both the typing rules and the meaning of an lvalue is very precisely
specified in CIL.
The following are a few useful function for operating on lvalues:
- {!Cil.mkMem} - makes an lvalue of [Mem] kind. Use this to ensure
that certain equivalent forms of lvalues are canonized.
For example, [*&x = x].
- {!Cil.typeOfLval} - the type of an lvalue
- {!Cil.typeOffset} - the type of an offset, given the type of the
host.
- {!Cil.addOffset} and {!Cil.addOffsetLval} - extend sequences
of offsets.
- {!Cil.removeOffset} and {!Cil.removeOffsetLval} - shrink sequences
of offsets.
The following equivalences hold {v
Mem(AddrOf(Mem a, aoff)), off = Mem a, aoff + off
Mem(AddrOf(Var v, aoff)), off = Var v, aoff + off
AddrOf (Mem a, NoOffset) = a
v}
*)
and lval =
lhost * offset * location
and lhost =
| Var of varinfo * location
| Mem of exp
* The host is an object of type [ T ] when the expression has pointer
* [ TPtr(T ) ] .
* [TPtr(T)]. *)
* The offset part of an { ! Cil.lval } . Each offset can be applied to certain
* kinds of lvalues and its effect is that it advances the starting address
* of the lvalue and changes the denoted type , essentially focusing to some
* smaller lvalue that is contained in the original one .
* kinds of lvalues and its effect is that it advances the starting address
* of the lvalue and changes the denoted type, essentially focusing to some
* smaller lvalue that is contained in the original one. *)
and offset =
| Field of (fieldinfo * location) * offset * location
| Index of exp * offset * location
* { b Initializers . } A special kind of expressions are those that can appear
* as initializers for global variables ( initialization of local variables is
* turned into assignments ) . The initializers are represented as type
* { ! } . You can create initializers with { ! Cil.makeZeroInit } and you
* can conveniently scan compound initializers them with
* { ! } .
* as initializers for global variables (initialization of local variables is
* turned into assignments). The initializers are represented as type
* {!Cil.init}. You can create initializers with {!Cil.makeZeroInit} and you
* can conveniently scan compound initializers them with
* {!Cil.foldLeftCompound}. *)
and init =
| CompoundInit of typ * (offset * init) list
* Used only for initializers of structures , unions and arrays . The
* offsets are all of the form [ Field(f , ) ] or [ Index(i ,
* ) ] and specify the field or the index being initialized . For
* structures all fields must have an initializer ( except the unnamed
* bitfields ) , in the proper order . This is necessary since the offsets
* are not printed . For unions there must be exactly one initializer . If
* the initializer is not for the first field then a field designator is
* printed , so you better be on GCC since MSVC does not understand this .
* For arrays , however , we allow you to give only a prefix of the
* initializers . You can scan an initializer list with
* { ! } .
* offsets are all of the form [Field(f, NoOffset)] or [Index(i,
* NoOffset)] and specify the field or the index being initialized. For
* structures all fields must have an initializer (except the unnamed
* bitfields), in the proper order. This is necessary since the offsets
* are not printed. For unions there must be exactly one initializer. If
* the initializer is not for the first field then a field designator is
* printed, so you better be on GCC since MSVC does not understand this.
* For arrays, however, we allow you to give only a prefix of the
* initializers. You can scan an initializer list with
* {!Cil.foldLeftCompound}. *)
and initinfo = {
mutable init : init option;
}
and fundec =
{ mutable svar: varinfo;
mutable sformals: varinfo list;
* Formals . These must be in the same order and with the same
* information as the formal information in the type of the function .
* Use { ! } or
* { ! Cil.setFunctionType } or { ! Cil.makeFormalVar }
* to set these formals and ensure that they
* are reflected in the function type . Do not make copies of these
* because the body refers to them .
* information as the formal information in the type of the function.
* Use {!Cil.setFormals} or
* {!Cil.setFunctionType} or {!Cil.makeFormalVar}
* to set these formals and ensure that they
* are reflected in the function type. Do not make copies of these
* because the body refers to them. *)
mutable slocals: varinfo list;
* local i d. Starts at 0 . Used for
* creating the names of new temporary
* variables . Updated by
* { ! } and
* { ! } . You can also use
* { ! Cil.setMaxId } to set it after you
* have added the formals and locals .
* creating the names of new temporary
* variables. Updated by
* {!Cil.makeLocalVar} and
* {!Cil.makeTempVar}. You can also use
* {!Cil.setMaxId} to set it after you
* have added the formals and locals. *)
}
and block =
mutable bloc: location;
}
* { b Statements } .
CIL statements are the structural elements that make the CFG . They are
represented using the type { ! Cil.stmt } . Every
statement has a ( possibly empty ) list of labels . The
{ ! Cil.stmtkind } field of a statement indicates what kind of statement it
is .
Use { ! Cil.mkStmt } to make a statement and the fill - in the fields .
CIL also comes with support for control - flow graphs . The [ sid ] field in
[ stmt ] can be used to give unique numbers to statements , and the [ succs ]
and [ preds ] fields can be used to maintain a list of successors and
predecessors for every statement . The CFG information is not computed by
default . Instead you must explicitly use the functions
{ ! Cil.prepareCFG } and { ! Cil.computeCFGInfo } to do it .
CIL statements are the structural elements that make the CFG. They are
represented using the type {!Cil.stmt}. Every
statement has a (possibly empty) list of labels. The
{!Cil.stmtkind} field of a statement indicates what kind of statement it
is.
Use {!Cil.mkStmt} to make a statement and the fill-in the fields.
CIL also comes with support for control-flow graphs. The [sid] field in
[stmt] can be used to give unique numbers to statements, and the [succs]
and [preds] fields can be used to maintain a list of successors and
predecessors for every statement. The CFG information is not computed by
default. Instead you must explicitly use the functions
{!Cil.prepareCFG} and {!Cil.computeCFGInfo} to do it.
*)
and stmt = {
mutable labels: label list;
mutable skind: stmtkind;
mutable sid: int;
* A number ( > = 0 ) that is unique in a function . Filled in only after
* the CFG is computed .
* the CFG is computed. *)
mutable succs: stmt list;
* The successor statements . They can always be computed from the skind
* and the context in which this statement appears . Filled in only after
* the CFG is computed .
* and the context in which this statement appears. Filled in only after
* the CFG is computed. *)
mutable preds: stmt list;
* The inverse of the succs function .
}
and label =
Label of string * location * bool
and stmtkind =
| Instr of instr list
| Return of exp option * location
* The return statement . This is a leaf in the CFG .
| Goto of stmt ref * location
* A goto statement . Appears from actual 's in the code or from
* 's that have been inserted during elaboration . The reference
* points to the statement that is the target of the . This means that
* you have to update the reference whenever you replace the target
* statement . The target statement MUST have at least a label .
* goto's that have been inserted during elaboration. The reference
* points to the statement that is the target of the Goto. This means that
* you have to update the reference whenever you replace the target
* statement. The target statement MUST have at least a label. *)
| Break of location
* A break to the end of the nearest enclosing Loop or Switch
| Continue of location
| If of exp * block * block * location
* A conditional . Two successors , the " then " and the " else " branches .
* Both branches fall - through to the successor of the If statement .
* Both branches fall-through to the successor of the If statement. *)
| Switch of exp * block * (stmt list) * location
| Loop of block * Iformula.struc_formula * location * (stmt option) * (stmt option)
* A [ while(1 ) ] loop . The termination test is implemented in the body of
* a loop using a [ Break ] statement . If prepareCFG has been called ,
* the first stmt option will point to the stmt containing the continue
* label for this loop and the second will point to the stmt containing
* the break label for this loop .
* a loop using a [Break] statement. If prepareCFG has been called,
* the first stmt option will point to the stmt containing the continue
* label for this loop and the second will point to the stmt containing
* the break label for this loop. *)
| Block of block
* On MSVC we support structured exception handling . This is what you
* might expect . Control can get into the finally block either from the
* end of the body block , or if an exception is thrown .
* might expect. Control can get into the finally block either from the
* end of the body block, or if an exception is thrown. *)
| TryFinally of block * block * location
* On MSVC we support structured exception handling . The try / except
* statement is a bit tricky :
[ _ _ try { blk }
_ _ except ( e ) {
handler
} ]
The argument to _ _ except must be an expression . However , we keep a
list of instructions AND an expression in case you need to make
function calls . We 'll print those as a comma expression . The control
can get to the _ _ except expression only if an exception is thrown .
After that , depending on the value of the expression the control
goes to the handler , propagates the exception , or retries the
exception ! ! !
* statement is a bit tricky:
[__try { blk }
__except (e) {
handler
}]
The argument to __except must be an expression. However, we keep a
list of instructions AND an expression in case you need to make
function calls. We'll print those as a comma expression. The control
can get to the __except expression only if an exception is thrown.
After that, depending on the value of the expression the control
goes to the handler, propagates the exception, or retries the
exception !!!
*)
| TryExcept of block * (instr list * exp) * block * location
| HipStmt of Iast.exp * location
and instr =
Set of lval * exp * location
| Call of lval option * exp * exp list * location
* A function call with the ( optional ) result placed in an lval . It is
* possible that the returned type of the function is not identical to
* that of the lvalue . In that case a cast is printed . The type of the
* actual arguments are identical to those of the declared formals . The
* number of arguments is the same as that of the declared formals , except
* for vararg functions . This construct is also used to encode a call to
* " _ _ builtin_va_arg " . In this case the second argument ( which should be a
* type T ) is encoded SizeOf(T )
* possible that the returned type of the function is not identical to
* that of the lvalue. In that case a cast is printed. The type of the
* actual arguments are identical to those of the declared formals. The
* number of arguments is the same as that of the declared formals, except
* for vararg functions. This construct is also used to encode a call to
* "__builtin_va_arg". In this case the second argument (which should be a
* type T) is encoded SizeOf(T) *)
(string option * string * lval) list *
outputs must be lvals with
* optional names and constraints .
* I would like these
* to be actually variables , but I
* run into some trouble with ASMs
* in the Linux sources
* optional names and constraints.
* I would like these
* to be actually variables, but I
* run into some trouble with ASMs
* in the Linux sources *)
(string option * string * exp) list *
location
* There are for storing inline assembly . They follow the GCC
* specification :
{ v
asm [ volatile ] ( " ... template ... " " .. template .. "
: " c1 " ( o1 ) , " c2 " ( o2 ) , ... , " cN " ( oN )
: " d1 " ( i1 ) , " d2 " ( i2 ) , ... , " dM " ( iM )
: " r1 " , " r2 " , ... , " nL " ) ;
v }
where the parts are
- [ volatile ] ( optional ): when present , the assembler instruction
can not be removed , moved , or otherwise optimized
- template : a sequence of strings , with % 0 , % 1 , % 2 , etc . in the string to
refer to the input and output expressions . I think they 're numbered
consecutively , but the docs do n't specify . Each string is printed on
a separate line . This is the only part that is present for MSVC inline
assembly .
- " ci " ( oi ): pairs of constraint - string and output - lval ; the
constraint specifies that the register used must have some
property , like being a floating - point register ; the constraint
string for outputs also has " = " to indicate it is written , or
" + " to indicate it is both read and written ; ' oi ' is the
name of a C lvalue ( probably a variable name ) to be used as
the output destination
- " dj " ( ij ): pairs of constraint and input expression ; the constraint
is similar to the " ci"s . the ' ij ' is an arbitrary C expression
to be loaded into the corresponding register
- " rk " : registers to be regarded as " clobbered " by the instruction ;
" memory " may be specified for arbitrary memory effects
an example ( from gcc manual ):
{ v
asm volatile ( " % 0,%1,%2 "
: / * no outputs * /
: " g " ( from ) , " g " ( to ) , " g " ( count )
: " r0 " , " r1 " , " r2 " , " r3 " , " r4 " , " r5 " ) ;
v }
Starting with gcc 3.1 , the operands may have names :
{ v
asm volatile ( " % [ in0],%1,%2 "
: / * no outputs * /
: [ in0 ] " g " ( from ) , " g " ( to ) , " g " ( count )
: " r0 " , " r1 " , " r2 " , " r3 " , " r4 " , " r5 " ) ;
v }
* specification:
{v
asm [volatile] ("...template..." "..template.."
: "c1" (o1), "c2" (o2), ..., "cN" (oN)
: "d1" (i1), "d2" (i2), ..., "dM" (iM)
: "r1", "r2", ..., "nL" );
v}
where the parts are
- [volatile] (optional): when present, the assembler instruction
cannot be removed, moved, or otherwise optimized
- template: a sequence of strings, with %0, %1, %2, etc. in the string to
refer to the input and output expressions. I think they're numbered
consecutively, but the docs don't specify. Each string is printed on
a separate line. This is the only part that is present for MSVC inline
assembly.
- "ci" (oi): pairs of constraint-string and output-lval; the
constraint specifies that the register used must have some
property, like being a floating-point register; the constraint
string for outputs also has "=" to indicate it is written, or
"+" to indicate it is both read and written; 'oi' is the
name of a C lvalue (probably a variable name) to be used as
the output destination
- "dj" (ij): pairs of constraint and input expression; the constraint
is similar to the "ci"s. the 'ij' is an arbitrary C expression
to be loaded into the corresponding register
- "rk": registers to be regarded as "clobbered" by the instruction;
"memory" may be specified for arbitrary memory effects
an example (from gcc manual):
{v
asm volatile ("movc3 %0,%1,%2"
: /* no outputs */
: "g" (from), "g" (to), "g" (count)
: "r0", "r1", "r2", "r3", "r4", "r5");
v}
Starting with gcc 3.1, the operands may have names:
{v
asm volatile ("movc3 %[in0],%1,%2"
: /* no outputs */
: [in0] "g" (from), "g" (to), "g" (count)
: "r0", "r1", "r2", "r3", "r4", "r5");
v}
*)
and position = {
}
and location = {
start_pos: position;
end_pos: position;
}
* Type signatures . Two types are identical iff they have identical
* signatures . These contain the same information as types but canonicalized .
* For example , two function types that are identical except for the name of
* the formal arguments are given the same signature . Also , [ TNamed ]
* constructors are unrolled .
* signatures. These contain the same information as types but canonicalized.
* For example, two function types that are identical except for the name of
* the formal arguments are given the same signature. Also, [TNamed]
* constructors are unrolled. *)
and typsig =
TSArray of typsig * int64 option * attribute list
| TSPtr of typsig * attribute list
| TSComp of bool * string * attribute list
| TSFun of typsig * typsig list * bool * attribute list
| TSEnum of string * attribute list
| TSBase of typ
val lowerConstants: bool ref
val insertImplicitCasts: bool ref
type featureDescr = {
fd_enabled: bool ref;
fd_name: string;
fd_description: string;
fd_extraopt: (string * Arg.spec * string) list;
fd_doit: (file -> unit);
fd_post_check: bool;
}
* Comparison function for position .
* * Compares first by filename , then line , then byte
** Compares first by filename, then line, then byte *)
* Comparison function for locations .
* * Compares first by start_pos , then end_pos
** Compares first by start_pos, then end_pos *)
val compareLoc: location -> location -> int
val emptyFunction: string -> fundec
val setFormals: fundec -> varinfo list -> unit
* Set the types of arguments and results as given by the function type
* passed as the second argument . Will not copy the names from the function
* type to the formals
* passed as the second argument. Will not copy the names from the function
* type to the formals *)
val setFunctionType: fundec -> typ -> unit
val setFunctionTypeMakeFormals: fundec -> typ -> unit
* Update the smaxid after you have populated with locals and formals
* ( unless you constructed those using { ! } or
* { ! } .
* (unless you constructed those using {!Cil.makeLocalVar} or
* {!Cil.makeTempVar}. *)
val setMaxId: fundec -> unit
val dummyFunDec: fundec
val dummyFile: file
* Write a { ! Cil.file } in binary form to the filesystem . The file can be
* read back in later using { ! Cil.loadBinaryFile } , possibly saving parsing
* time . The second argument is the name of the file that should be
* created .
* read back in later using {!Cil.loadBinaryFile}, possibly saving parsing
* time. The second argument is the name of the file that should be
* created. *)
val saveBinaryFile : file -> string -> unit
val saveBinaryFileChannel : file -> out_channel -> unit
* Read a { ! Cil.file } in binary form from the filesystem . The first
* argument is the name of a file previously created by
* { ! Cil.saveBinaryFile } . Because this also reads some global state ,
* this should be called before any other CIL code is parsed or generated .
* argument is the name of a file previously created by
* {!Cil.saveBinaryFile}. Because this also reads some global state,
* this should be called before any other CIL code is parsed or generated. *)
val loadBinaryFile : string -> file
val getGlobInit: ?main_name:string -> file -> fundec
val iterGlobals: file -> (global -> unit) -> unit
val foldGlobals: file -> ('a -> global -> 'a) -> 'a -> 'a
val mapGlobals: file -> (global -> global) -> unit
val findOrCreateFunc: file -> string -> typ -> varinfo
val new_sid : unit -> int
* Prepare a function for CFG information computation by
* { ! Cil.computeCFGInfo } . This function converts all [ Break ] , [ Switch ] ,
* [ Default ] and [ Continue ] { ! and { ! Cil.label}s into [ If]s
* and [ Goto]s , giving the function body a very CFG - like character . This
* function modifies its argument in place .
* {!Cil.computeCFGInfo}. This function converts all [Break], [Switch],
* [Default] and [Continue] {!Cil.stmtkind}s and {!Cil.label}s into [If]s
* and [Goto]s, giving the function body a very CFG-like character. This
* function modifies its argument in place. *)
val prepareCFG: fundec -> unit
* Compute the CFG information for all statements in a fundec and return a
* list of the statements . The input fundec can not have [ Break ] , [ Switch ] ,
* [ Default ] , or [ Continue ] { ! or { ! Cil.label}s . Use
* { ! Cil.prepareCFG } to transform them away . The second argument should
* be [ true ] if you wish a global statement number , [ false ] if you wish a
* local ( per - function ) statement numbering . The list of statements is set
* in the sallstmts field of a fundec .
*
* NOTE : unless you want the simpler control - flow graph provided by
* prepareCFG , or you need the function 's smaxstmtid and
* filled in , we recommend you use { ! Cfg.computeFileCFG } instead of this
* function to compute control - flow information .
* { ! Cfg.computeFileCFG } is newer and will handle switch , break , and
* continue correctly .
* list of the statements. The input fundec cannot have [Break], [Switch],
* [Default], or [Continue] {!Cil.stmtkind}s or {!Cil.label}s. Use
* {!Cil.prepareCFG} to transform them away. The second argument should
* be [true] if you wish a global statement number, [false] if you wish a
* local (per-function) statement numbering. The list of statements is set
* in the sallstmts field of a fundec.
*
* NOTE: unless you want the simpler control-flow graph provided by
* prepareCFG, or you need the function's smaxstmtid and sallstmt fields
* filled in, we recommend you use {!Cfg.computeFileCFG} instead of this
* function to compute control-flow information.
* {!Cfg.computeFileCFG} is newer and will handle switch, break, and
* continue correctly.*)
val computeCFGInfo: fundec -> bool -> unit
val copyFunction: fundec -> string -> fundec
val pushGlobal: global -> types: global list ref
-> variables: global list ref -> unit
val invalidStmt: stmt
* A list of the built - in functions for the current compiler ( GCC or
* MSVC , depending on [ ! msvcMode ] ) . Maps the name to the
* result and argument types , and whether it is vararg .
* Initialized by { ! Cil.initCIL }
*
* This map replaces [ gccBuiltins ] and [ msvcBuiltins ] in previous
* versions of CIL .
* MSVC, depending on [!msvcMode]). Maps the name to the
* result and argument types, and whether it is vararg.
* Initialized by {!Cil.initCIL}
*
* This map replaces [gccBuiltins] and [msvcBuiltins] in previous
* versions of CIL.*)
val builtinFunctions : (string, typ * typ list * bool) Hashtbl.t
val builtinLoc: location
* Make a initializer for zero - ing a data type
val makeZeroInit: typ -> init
* Fold over the list of initializers in a Compound ( not also the nested
* ones ) . [ doinit ] is called on every present initializer , even if it is of
* compound type . The parameters of [ doinit ] are : the offset in the compound
* ( this is [ Field(f , ) ] or [ Index(i , ) ] ) , the initializer
* value , expected type of the initializer value , accumulator . In the case of
* arrays there might be missing zero - initializers at the end of the list .
* These are scanned only if [ implicit ] is true . This is much like
* [ List.fold_left ] except we also pass the type of the initializer .
* This is a good way to use it to scan even nested initializers :
{ v
let rec myInit ( lv : lval ) ( i : init ) ( acc : ' a ) : ' a =
match i with
SingleInit e - > ... do something with lv and e and acc ...
| CompoundInit ( ct , ) - >
foldLeftCompound ~implicit : false
~doinit:(fun off ' i ' t ' acc - >
myInit ( addOffsetLval lv off ' ) i ' acc )
~ct : ct
~initl : initl
~acc : acc
v }
* ones). [doinit] is called on every present initializer, even if it is of
* compound type. The parameters of [doinit] are: the offset in the compound
* (this is [Field(f,NoOffset)] or [Index(i,NoOffset)]), the initializer
* value, expected type of the initializer value, accumulator. In the case of
* arrays there might be missing zero-initializers at the end of the list.
* These are scanned only if [implicit] is true. This is much like
* [List.fold_left] except we also pass the type of the initializer.
* This is a good way to use it to scan even nested initializers :
{v
let rec myInit (lv: lval) (i: init) (acc: 'a) : 'a =
match i with
SingleInit e -> ... do something with lv and e and acc ...
| CompoundInit (ct, initl) ->
foldLeftCompound ~implicit:false
~doinit:(fun off' i' t' acc ->
myInit (addOffsetLval lv off') i' acc)
~ct:ct
~initl:initl
~acc:acc
v}
*)
val foldLeftCompound:
implicit:bool ->
doinit: (offset -> init -> typ -> 'a -> 'a) ->
ct: typ ->
initl: (offset * init) list ->
acc: 'a -> 'a
val voidType: typ
val isVoidType: typ -> bool
val isVoidPtrType: typ -> bool
val intType: typ
val uintType: typ
val longType: typ
val ulongType: typ
val charType: typ
val charPtrType: typ
* wchar_t ( depends on architecture ) and is set when you call
* { ! Cil.initCIL } .
* {!Cil.initCIL}. *)
val wcharKind: ikind ref
val wcharType: typ ref
val charConstPtrType: typ
val voidPtrType: typ
val intPtrType: typ
val uintPtrType: typ
val doubleType: typ
* An unsigned integer type that fits pointers . Depends on { ! Cil.msvcMode }
* and is set when you call { ! Cil.initCIL } .
* and is set when you call {!Cil.initCIL}. *)
val upointType: typ ref
* An unsigned integer type that fits pointer difference . Depends on
* { ! Cil.msvcMode } and is set when you call { ! Cil.initCIL } .
* {!Cil.msvcMode} and is set when you call {!Cil.initCIL}. *)
val ptrdiffType: typ ref
* An unsigned integer type that is the type of sizeof . Depends on
* { ! Cil.msvcMode } and is set when you call { ! Cil.initCIL } .
* {!Cil.msvcMode} and is set when you call {!Cil.initCIL}. *)
val typeOfSizeOf: typ ref
* The integer kind of { ! } .
* Set when you call { ! Cil.initCIL } .
* Set when you call {!Cil.initCIL}. *)
val kindOfSizeOf: ikind ref
val isSigned: ikind -> bool
* Creates a a ( potentially recursive ) composite type . The arguments are :
* ( 1 ) a boolean indicating whether it is a struct or a union , ( 2 ) the name
* ( always non - empty ) , ( 3 ) a function that when given a representation of the
* structure type constructs the type of the fields recursive type ( the first
* argument is only useful when some fields need to refer to the type of the
* structure itself ) , and ( 4 ) a list of attributes to be associated with the
* composite type . The resulting compinfo has the field " cdefined " only if
* the list of fields is non - empty .
* (1) a boolean indicating whether it is a struct or a union, (2) the name
* (always non-empty), (3) a function that when given a representation of the
* structure type constructs the type of the fields recursive type (the first
* argument is only useful when some fields need to refer to the type of the
* structure itself), and (4) a list of attributes to be associated with the
* composite type. The resulting compinfo has the field "cdefined" only if
* the list of fields is non-empty. *)
(compinfo ->
(string * typ * int option * attributes * location * location) list) ->
attributes -> compinfo
* Makes a shallow copy of a { ! } changing the name and the key .
val copyCompInfo: compinfo -> string -> compinfo
val missingFieldName: string
val compFullName: compinfo -> string
val isCompleteType: typ -> bool
val unrollType: typ -> typ
* Unroll all the TNamed in a type ( even under type constructors such as
* [ TPtr ] , [ TFun ] or [ TArray ] . Does not unroll the types of fields in [ TComp ]
* types . Will collect all attributes
* [TPtr], [TFun] or [TArray]. Does not unroll the types of fields in [TComp]
* types. Will collect all attributes *)
val unrollTypeDeep: typ -> typ
val separateStorageModifiers: attribute list -> attribute list * attribute list
val isIntegralType: typ -> bool
val isArithmeticType: typ -> bool
val isPointerType: typ -> bool
val isScalarType: typ -> bool
val isFunctionType: typ -> bool
val argsToList: (string * typ * attributes) list option
-> (string * typ * attributes) list
val isArrayType: typ -> bool
exception LenOfArray
* Call to compute the array length as present in the array type , to an
* integer . Raises { ! . LenOfArray } if not able to compute the length , such
* as when there is no length or the length is not a constant .
* integer. Raises {!Cil.LenOfArray} if not able to compute the length, such
* as when there is no length or the length is not a constant. *)
val lenOfArray: exp option -> int
* Return a named fieldinfo in , or raise Not_found
val getCompField: compinfo -> string -> fieldinfo
type existsAction =
* Scans a type by applying the function on all elements .
When the function returns ExistsTrue , the scan stops with
true . When the function returns ExistsFalse then the current branch is not
scanned anymore . Care is taken to
apply the function only once on each composite type , thus avoiding
circularity . When the function returns ExistsMaybe then the types that
construct the current type are scanned ( e.g. the base type for TPtr and
TArray , the type of fields for a TComp , etc ) .
When the function returns ExistsTrue, the scan stops with
true. When the function returns ExistsFalse then the current branch is not
scanned anymore. Care is taken to
apply the function only once on each composite type, thus avoiding
circularity. When the function returns ExistsMaybe then the types that
construct the current type are scanned (e.g. the base type for TPtr and
TArray, the type of fields for a TComp, etc). *)
val existsType: (typ -> existsAction) -> typ -> bool
val splitFunctionType:
typ -> typ * (string * typ * attributes) list option * bool * attributes
val splitFunctionTypeVI:
varinfo -> typ * (string * typ * attributes) list option * bool * attributes
* Type signatures . Two types are identical iff they have identical
* signatures . These contain the same information as types but canonicalized .
* For example , two function types that are identical except for the name of
* the formal arguments are given the same signature . Also , [ TNamed ]
* constructors are unrolled .
* signatures. These contain the same information as types but canonicalized.
* For example, two function types that are identical except for the name of
* the formal arguments are given the same signature. Also, [TNamed]
* constructors are unrolled. *)
val d_typsig: unit -> typsig -> Pretty.doc
val typeSig: typ -> typsig
val typeSigWithAttrs: ?ignoreSign:bool -> (attributes -> attributes) -> typ -> typsig
val setTypeSigAttrs: attributes -> typsig -> typsig
val typeSigAttrs: typsig -> attributes
* Make a varinfo . Use this ( rarely ) to make a raw varinfo . Use other
* functions to make locals ( { ! } or { ! Cil.makeFormalVar } or
* { ! } ) and globals ( { ! Cil.makeGlobalVar } ) . Note that this
* function will assign a new identifier . The first argument specifies
* whether the varinfo is for a global .
* functions to make locals ({!Cil.makeLocalVar} or {!Cil.makeFormalVar} or
* {!Cil.makeTempVar}) and globals ({!Cil.makeGlobalVar}). Note that this
* function will assign a new identifier. The first argument specifies
* whether the varinfo is for a global. *)
val makeVarinfo: bool -> string -> typ -> varinfo
* Make a formal variable for a function . Insert it in both the sformals
and the type of the function . You can optionally specify where to insert
this one . If where = " ^ " then it is inserted first . If where = " $ " then
it is inserted last . Otherwise where must be the name of a formal after
which to insert this . By default it is inserted at the end .
and the type of the function. You can optionally specify where to insert
this one. If where = "^" then it is inserted first. If where = "$" then
it is inserted last. Otherwise where must be the name of a formal after
which to insert this. By default it is inserted at the end. *)
val makeFormalVar: fundec -> ?where:string -> string -> typ -> varinfo
val makeLocalVar: fundec -> ?insert:bool -> string -> typ -> varinfo
* Make a temporary variable and add it to a function 's slocals . CIL will
ensure that the name of the new variable is unique in this function , and
will generate this name by appending a number to the specified string
( " _ _ cil_tmp " by default ) .
The variable will be added to the function 's slocals unless you explicitly
set insert = false . ( Make sure you know what you are doing if you set
insert = false . )
Optionally , you can give the variable a description of its contents
that will be printed by descriptiveCilPrinter .
ensure that the name of the new variable is unique in this function, and
will generate this name by appending a number to the specified string
("__cil_tmp" by default).
The variable will be added to the function's slocals unless you explicitly
set insert=false. (Make sure you know what you are doing if you set
insert=false.)
Optionally, you can give the variable a description of its contents
that will be printed by descriptiveCilPrinter.
*)
val makeTempVar: fundec -> ?insert:bool -> ?name: string ->
?descr:Pretty.doc -> ?descrpure:bool -> typ -> varinfo
val makeGlobalVar: string -> typ -> varinfo
val copyVarinfo: varinfo -> string -> varinfo
* Generate a new variable ID . This will be different than any variable ID
* that is generated by { ! } and friends
* that is generated by {!Cil.makeLocalVar} and friends *)
val newVID: unit -> int
val addOffsetLval: offset -> lval -> lval
val addOffset: offset -> offset -> offset
* Remove ONE offset from the end of an lvalue . Returns the lvalue with the
* trimmed offset and the final offset . If the final offset is [ NoOffset ]
* then the original [ lval ] did not have an offset .
* trimmed offset and the final offset. If the final offset is [NoOffset]
* then the original [lval] did not have an offset. *)
val removeOffsetLval: lval -> lval * offset
* Remove ONE offset from the end of an offset sequence . Returns the
* trimmed offset and the final offset . If the final offset is [ NoOffset ]
* then the original [ lval ] did not have an offset .
* trimmed offset and the final offset. If the final offset is [NoOffset]
* then the original [lval] did not have an offset. *)
val removeOffset: offset -> offset * offset
val typeOfLval: lval -> typ
val typeOffset: typ -> offset -> typ
Construct integer constants
* 0
val zero: location -> exp
* 1
val one: location -> exp
val mone: location -> exp
val kintegerCilint: ikind -> cilint -> location -> exp
* Construct an integer of a given kind , using OCaml 's int64 type . If needed
* it will truncate the integer to be within the representable range for the
* given kind .
* it will truncate the integer to be within the representable range for the
* given kind. *)
val kinteger64: ikind -> int64 -> location -> exp
* Construct an integer of a given kind . Converts the integer to int64 and
* then uses kinteger64 . This might truncate the value if you use a kind
* that can not represent the given integer . This can only happen for one of
* the or Short kinds
* then uses kinteger64. This might truncate the value if you use a kind
* that cannot represent the given integer. This can only happen for one of
* the Char or Short kinds *)
val kinteger: ikind -> int -> location -> exp
* Construct an integer of kind IInt . On targets where C 's ' int ' is 16 - bits ,
the integer may get truncated .
the integer may get truncated. *)
val integer: int -> location -> exp
val getInteger: exp -> cilint option
* Convert a 64 - bit int to an OCaml int , or raise an exception if that
ca n't be done .
can't be done. *)
val i64_to_int: int64 -> int
val cilint_to_int: cilint -> int
val isConstant: exp -> bool
val isConstantOffset: offset -> bool
* True if the given expression is a ( possibly cast'ed ) integer or character
constant with value zero
constant with value zero *)
val isZero: exp -> bool
* Given the character c in a ( CChr c ) , sign - extend it to 32 bits .
( This is the official way of interpreting character constants , according to
ISO C 6.4.4.4.10 , which says that character constants are chars cast to ints )
Returns CInt64(sign - extened c , IInt , None )
(This is the official way of interpreting character constants, according to
ISO C 6.4.4.4.10, which says that character constants are chars cast to ints)
Returns CInt64(sign-extened c, IInt, None) *)
val charConstToInt: char -> constant
* Do constant folding on an expression . If the first argument is true then
will also compute compiler - dependent expressions such as sizeof .
See also { ! Cil.constFoldVisitor } , which will run constFold on all
expressions in a given AST node .
will also compute compiler-dependent expressions such as sizeof.
See also {!Cil.constFoldVisitor}, which will run constFold on all
expressions in a given AST node.*)
val constFold: bool -> exp -> exp
* Do constant folding on a binary operation . The bulk of the work done by
[ constFold ] is done here . If the first argument is true then
will also compute compiler - dependent expressions such as sizeof
[constFold] is done here. If the first argument is true then
will also compute compiler-dependent expressions such as sizeof *)
val constFoldBinOp: bool -> binop -> exp -> exp -> typ -> location -> exp
val increm: exp -> int -> exp
val var: varinfo -> location -> lval
* Make an . Given an lvalue of type T will give back an expression of
type ptr(T ) . It optimizes somewhat expressions like " & v " and " & v[0 ] "
type ptr(T). It optimizes somewhat expressions like "& v" and "& v[0]" *)
val mkAddrOf: lval -> location -> exp
val mkAddrOrStartOf: lval -> location -> exp
* Make a Mem , while optimizing . The type of the addr must be
TPtr(t ) and the type of the resulting lval is t. Note that in CIL the
implicit conversion between an array and the pointer to the first
element does not apply . You must do the conversion yourself using
StartOf
TPtr(t) and the type of the resulting lval is t. Note that in CIL the
implicit conversion between an array and the pointer to the first
element does not apply. You must do the conversion yourself using
StartOf *)
val mkMem: addr:exp -> off:offset -> lval
val mkString: string -> exp
val mkCastT: e:exp -> oldt:typ -> newt:typ -> exp
* Like { ! Cil.mkCastT } but uses to get [ oldt ]
val mkCast: e:exp -> newt:typ -> exp
* Removes casts from this expression , but ignores casts within
other expression constructs . So we delete the ( A ) and ( B ) casts from
" ( A)(B)(x + ( C)y ) " , but leave the ( C ) cast .
other expression constructs. So we delete the (A) and (B) casts from
"(A)(B)(x + (C)y)", but leave the (C) cast. *)
val stripCasts: exp -> exp
val typeOf: exp -> typ
* Convert a string representing a C integer literal to an expression .
* Handles the prefixes 0x and 0 and the suffixes L , U , UL , LL , ULL
* Handles the prefixes 0x and 0 and the suffixes L, U, UL, LL, ULL *)
val parseInt: string -> location -> exp
* Construct a statement , given its kind . Initialize the [ sid ] field to -1 ,
and [ labels ] , [ succs ] and [ ] to the empty list
and [labels], [succs] and [preds] to the empty list *)
val mkStmt: stmtkind -> stmt
val mkBlock: stmt list -> block
* Construct a statement consisting of just one instruction
val mkStmtOneInstr: instr -> stmt
* Try to compress statements so as to get maximal basic blocks .
* use this instead of List.@ because you get fewer basic blocks
* use this instead of List.@ because you get fewer basic blocks *)
val compactStmts: stmt list -> stmt list
val mkEmptyStmt: unit -> stmt
val dummyInstr: instr
val dummyStmt: stmt
val mkWhile: guard:exp -> body:stmt list -> hspecs: Iformula.struc_formula -> stmt list
* Make a for loop for(i = start ; i < past ; i + = incr ) \ { ... \ } . The body
can contain Break but not Continue . Can be used with i a pointer
or an integer . Start and done must have the same type but incr
must be an integer
can contain Break but not Continue. Can be used with i a pointer
or an integer. Start and done must have the same type but incr
must be an integer *)
val mkForIncr: iter:varinfo -> first:exp -> stopat:exp -> incr:exp
-> body:stmt list -> hspecs: Iformula.struc_formula -> stmt list
val mkFor: start:stmt list -> guard:exp -> next: stmt list ->
body: stmt list -> hspecs: Iformula.struc_formula -> stmt list
type attributeClass =
AttrName of bool
* Attribute of a name . If argument is true and we are on MSVC then
the attribute is printed using _ _ as part of the storage
specifier
the attribute is printed using __declspec as part of the storage
specifier *)
| AttrFunType of bool
* Attribute of a function type . If argument is true and we are on
MSVC then the attribute is printed just before the function name
MSVC then the attribute is printed just before the function name *)
val attributeHash: (string, attributeClass) Hashtbl.t
val partitionAttributes: default:attributeClass ->
AttrType
* Add an attribute . Maintains the attributes in sorted order of the second
argument
argument *)
val addAttribute: attribute -> attributes -> attributes
* Add a list of attributes . Maintains the attributes in sorted order . The
second argument must be sorted , but not necessarily the first
second argument must be sorted, but not necessarily the first *)
val addAttributes: attribute list -> attributes -> attributes
val dropAttribute: string -> attributes -> attributes
val dropAttributes: string list -> attributes -> attributes
val filterAttributes: string -> attributes -> attributes
val hasAttribute: string -> attributes -> bool
val typeAttrs: typ -> attribute list
val typeAddAttributes: attribute list -> typ -> typ
val typeRemoveAttributes: string list -> typ -> typ
val expToAttrParam: exp -> attrparam
exception NotAnAttrParam of exp
type 'a visitAction =
* Replace the expression with the
given one
given one *)
* First consider that the entire
exp is replaced by the first
parameter . Then continue with
the children . On return rebuild
the node if any of the children
has changed and then apply the
function on the node
exp is replaced by the first
parameter. Then continue with
the children. On return rebuild
the node if any of the children
has changed and then apply the
function on the node *)
* A visitor interface for traversing CIL trees . Create instantiations of
* this type by specializing the class { ! Cil.nopCilVisitor } . Each of the
* specialized visiting functions can also call the [ queueInstr ] to specify
* that some instructions should be inserted before the current instruction
* or statement . Use syntax like [ self#queueInstr ] to call a method
* associated with the current object .
* this type by specializing the class {!Cil.nopCilVisitor}. Each of the
* specialized visiting functions can also call the [queueInstr] to specify
* that some instructions should be inserted before the current instruction
* or statement. Use syntax like [self#queueInstr] to call a method
* associated with the current object. *)
class type cilVisitor = object
method vvdec: varinfo -> varinfo visitAction
* Invoked for each variable declaration . The subtrees to be traversed
* are those corresponding to the type and attributes of the variable .
* Note that variable declarations are all the [ GVar ] , [ GVarDecl ] , [ GFun ] ,
* all the [ varinfo ] in formals of function types , and the formals and
* locals for function definitions . This means that the list of formals
* in a function definition will be traversed twice , once as part of the
* function type and second as part of the formals in a function
* definition .
* are those corresponding to the type and attributes of the variable.
* Note that variable declarations are all the [GVar], [GVarDecl], [GFun],
* all the [varinfo] in formals of function types, and the formals and
* locals for function definitions. This means that the list of formals
* in a function definition will be traversed twice, once as part of the
* function type and second as part of the formals in a function
* definition. *)
method vvrbl: varinfo -> varinfo visitAction
* Invoked on each variable use . Here only the [ SkipChildren ] and
* [ ChangeTo ] actions make sense since there are no subtrees . Note that
* the type and attributes of the variable are not traversed for a
* variable use
* [ChangeTo] actions make sense since there are no subtrees. Note that
* the type and attributes of the variable are not traversed for a
* variable use *)
method vexpr: exp -> exp visitAction
method vlval: lval -> lval visitAction
method voffs: offset -> offset visitAction
method vinitoffs: offset -> offset visitAction
* Invoked on each offset appearing in the list of a
* CompoundInit initializer .
* CompoundInit initializer. *)
method vinst: instr -> instr list visitAction
method vstmt: stmt -> stmt visitAction
* Control - flow statement . The default [ DoChildren ] action does not
* create a new statement when the components change . Instead it updates
* the contents of the original statement . This is done to preserve the
* sharing with [ ] and [ Case ] statements that point to the original
* statement . If you use the [ ChangeTo ] action then you should take care
* of preserving that sharing yourself .
* create a new statement when the components change. Instead it updates
* the contents of the original statement. This is done to preserve the
* sharing with [Goto] and [Case] statements that point to the original
* statement. If you use the [ChangeTo] action then you should take care
* of preserving that sharing yourself. *)
method vinit: varinfo -> offset -> init -> init visitAction
method vattr: attribute -> attribute list visitAction
method vattrparam: attrparam -> attrparam visitAction
method queueInstr: instr list -> unit
method unqueueInstr: unit -> instr list
end
class nopCilVisitor: cilVisitor
other cil constructs
val visitCilFile: cilVisitor -> file -> unit
val visitCilFileSameGlobals: cilVisitor -> file -> unit
val visitCilGlobal: cilVisitor -> global -> global list
val visitCilFunction: cilVisitor -> fundec -> fundec
val visitCilExpr: cilVisitor -> exp -> exp
val visitCilLval: cilVisitor -> lval -> lval
val visitCilOffset: cilVisitor -> offset -> offset
val visitCilInitOffset: cilVisitor -> offset -> offset
val visitCilInstr: cilVisitor -> instr -> instr list
val visitCilStmt: cilVisitor -> stmt -> stmt
val visitCilBlock: cilVisitor -> block -> block
val visitCilType: cilVisitor -> typ -> typ
val visitCilVarDecl: cilVisitor -> varinfo -> varinfo
val visitCilInit: cilVisitor -> varinfo -> offset -> init -> init
val visitCilAttributes: cilVisitor -> attribute list -> attribute list
* Whether the pretty printer should print output for the MS VC compiler .
Default is GCC . After you set this function you should call { ! Cil.initCIL } .
Default is GCC. After you set this function you should call {!Cil.initCIL}. *)
val msvcMode: bool ref
* Whether to use the logical operands LAnd and LOr . By default , do not use
* them because they are unlike other expressions and do not evaluate both of
* their operands
* them because they are unlike other expressions and do not evaluate both of
* their operands *)
val useLogicalOperators: bool ref
* Set this to true to get old - style handling of gcc 's extern inline C extension :
old - style : the extern inline definition is used until the actual definition is
seen ( as long as optimization is enabled )
new - style : the extern inline definition is used only if there is no actual
definition ( as long as optimization is enabled )
Note that CIL assumes that optimization is always enabled ;-)
old-style: the extern inline definition is used until the actual definition is
seen (as long as optimization is enabled)
new-style: the extern inline definition is used only if there is no actual
definition (as long as optimization is enabled)
Note that CIL assumes that optimization is always enabled ;-) *)
val oldstyleExternInline : bool ref
val constFoldVisitor: bool -> cilVisitor
type lineDirectiveStyle =
* Use # line directives
val lineDirectiveStyle: lineDirectiveStyle option ref
val print_CIL_Input: bool ref
* Whether to print the CIL as they are , without trying to be smart and
* print nicer code . Normally this is false , in which case the pretty
* printer will turn the while(1 ) loops of CIL into nicer loops , will not
* print empty " else " blocks , etc . There is one case howewer in which if you
* turn this on you will get code that does not compile : if you use varargs
* the _ _ builtin_va_arg function will be printed in its internal form .
* print nicer code. Normally this is false, in which case the pretty
* printer will turn the while(1) loops of CIL into nicer loops, will not
* print empty "else" blocks, etc. There is one case howewer in which if you
* turn this on you will get code that does not compile: if you use varargs
* the __builtin_va_arg function will be printed in its internal form. *)
val printCilAsIs: bool ref
val lineLength: int ref
* Return the string 's ' if we 're printing output for gcc , suppres
* it if we 're printing for CIL to parse back in . the purpose is to
* hide things from gcc that it complains about , but still be able
* to do lossless transformations when CIL is the consumer
* it if we're printing for CIL to parse back in. the purpose is to
* hide things from gcc that it complains about, but still be able
* to do lossless transformations when CIL is the consumer *)
val forgcc: string -> string
val currentLoc: location ref
val currentGlobal: global ref
* CIL has a fairly easy to use mechanism for printing error messages . This
* mechanism is built on top of the pretty - printer mechanism ( see
* { ! Pretty.doc } ) and the error - message modules ( see { ! Errormsg.error } ) .
Here is a typical example for printing a log message : { v
ignore ( Errormsg.log " Expression % a is not positive ( at % s:%i)\n "
d_exp e loc.file loc.line )
v }
and here is an example of how you print a fatal error message that stop the
* execution : { v
Errormsg.s ( " Why am I here ? " )
v }
Notice that you can use C format strings with some extension . The most
useful extension is " % a " that means to consumer the next two argument from
the argument list and to apply the first to [ unit ] and then to the second
and to print the resulting { ! Pretty.doc } . For each major type in CIL there is
a corresponding function that pretty - prints an element of that type :
* mechanism is built on top of the pretty-printer mechanism (see
* {!Pretty.doc}) and the error-message modules (see {!Errormsg.error}).
Here is a typical example for printing a log message: {v
ignore (Errormsg.log "Expression %a is not positive (at %s:%i)\n"
d_exp e loc.file loc.line)
v}
and here is an example of how you print a fatal error message that stop the
* execution: {v
Errormsg.s (Errormsg.bug "Why am I here?")
v}
Notice that you can use C format strings with some extension. The most
useful extension is "%a" that means to consumer the next two argument from
the argument list and to apply the first to [unit] and then to the second
and to print the resulting {!Pretty.doc}. For each major type in CIL there is
a corresponding function that pretty-prints an element of that type:
*)
val d_loc: unit -> location -> Pretty.doc
val d_thisloc: unit -> Pretty.doc
val d_ikind: unit -> ikind -> Pretty.doc
val d_fkind: unit -> fkind -> Pretty.doc
val d_storage: unit -> storage -> Pretty.doc
val d_const: unit -> constant -> Pretty.doc
val derefStarLevel: int
val indexLevel: int
val arrowLevel: int
val addrOfLevel: int
val additiveLevel: int
val comparativeLevel: int
val bitwiseLevel: int
val getParenthLevel: exp -> int
class type cilPrinter = object
method setCurrentFormals : varinfo list -> unit
method setPrintInstrTerminator : string -> unit
method getPrintInstrTerminator : unit -> string
method pVDecl: unit -> varinfo -> Pretty.doc
method pVar: varinfo -> Pretty.doc
method pLval: unit -> lval -> Pretty.doc
method pOffset: Pretty.doc -> offset -> Pretty.doc
* Invoked on each offset occurrence . The second argument is the base .
method pInstr: unit -> instr -> Pretty.doc
method pLabel: unit -> label -> Pretty.doc
method pStmt: unit -> stmt -> Pretty.doc
method dStmt: out_channel -> int -> stmt -> unit
method dBlock: out_channel -> int -> block -> unit
method pBlock: unit -> block -> Pretty.doc
method pFunDecl: unit -> fundec -> Pretty.doc
method pGlobal: unit -> global -> Pretty.doc
method dGlobal: out_channel -> global -> unit
method pFieldDecl: unit -> fieldinfo -> Pretty.doc
method pType: Pretty.doc option -> unit -> typ -> Pretty.doc
* Use of some type in some declaration . The first argument is used to print
* the declared element , or is None if we are just printing a type with no
* name being declared . Note that for structure / union and enumeration types
* the definition of the composite type is not visited . Use [ vglob ] to
* visit it .
* the declared element, or is None if we are just printing a type with no
* name being declared. Note that for structure/union and enumeration types
* the definition of the composite type is not visited. Use [vglob] to
* visit it. *)
method pAttr: attribute -> Pretty.doc * bool
method pAttrParam: unit -> attrparam -> Pretty.doc
method pAttrs: unit -> attributes -> Pretty.doc
method pLineDirective: ?forcefile:bool -> location -> Pretty.doc
method pStmtKind: stmt -> unit -> stmtkind -> Pretty.doc
* Print a statement kind . The code to be printed is given in the
* { ! Cil.stmtkind } argument . The initial { ! Cil.stmt } argument
* records the statement which follows the one being printed ;
* { ! Cil.defaultCilPrinterClass } uses this information to prettify
* statement printing in certain special cases .
* {!Cil.stmtkind} argument. The initial {!Cil.stmt} argument
* records the statement which follows the one being printed;
* {!Cil.defaultCilPrinterClass} uses this information to prettify
* statement printing in certain special cases. *)
method pExp: unit -> exp -> Pretty.doc
method pLoc: unit -> location -> Pretty.doc
method pInit: unit -> init -> Pretty.doc
method dInit: out_channel -> int -> init -> unit
end
class defaultCilPrinterClass: cilPrinter
val defaultCilPrinter: cilPrinter
class plainCilPrinterClass: cilPrinter
val plainCilPrinter: cilPrinter
class type descriptiveCilPrinter = object
inherit cilPrinter
method startTemps: unit -> unit
method stopTemps: unit -> unit
method pTemps: unit -> Pretty.doc
end
class descriptiveCilPrinterClass : bool -> descriptiveCilPrinter
val descriptiveCilPrinter: descriptiveCilPrinter
* zra : This is the pretty printer that Maincil will use .
by default it is set to defaultCilPrinter
by default it is set to defaultCilPrinter *)
val printerForMaincil: cilPrinter ref
val printType: cilPrinter -> unit -> typ -> Pretty.doc
val printExp: cilPrinter -> unit -> exp -> Pretty.doc
val printLval: cilPrinter -> unit -> lval -> Pretty.doc
val printGlobal: cilPrinter -> unit -> global -> Pretty.doc
val printAttr: cilPrinter -> unit -> attribute -> Pretty.doc
val printAttrs: cilPrinter -> unit -> attributes -> Pretty.doc
val printInstr: cilPrinter -> unit -> instr -> Pretty.doc
* Print a statement given a pretty printer . This can take very long
* ( or even overflow the stack ) for huge statements . Use { ! }
* instead .
* (or even overflow the stack) for huge statements. Use {!Cil.dumpStmt}
* instead. *)
val printStmt: cilPrinter -> unit -> stmt -> Pretty.doc
val printBlock: cilPrinter -> unit -> block -> Pretty.doc
val dumpStmt: cilPrinter -> out_channel -> int -> stmt -> unit
val dumpBlock: cilPrinter -> out_channel -> int -> block -> unit
val printInit: cilPrinter -> unit -> init -> Pretty.doc
val dumpInit: cilPrinter -> out_channel -> int -> init -> unit
* Pretty - print a type using { ! }
val d_type: unit -> typ -> Pretty.doc
* Pretty - print an expression using { ! }
val d_exp: unit -> exp -> Pretty.doc
* Pretty - print an location using { ! }
val d_loc: unit -> location -> Pretty.doc
* Pretty - print an lvalue using { ! }
val d_lval: unit -> lval -> Pretty.doc
* Pretty - print an offset using { ! } , given the pretty
* printing for the base .
* printing for the base. *)
val d_offset: Pretty.doc -> unit -> offset -> Pretty.doc
* Pretty - print an initializer using { ! } . This can be
* extremely slow ( or even overflow the stack ) for huge initializers . Use
* { ! Cil.dumpInit } instead .
* extremely slow (or even overflow the stack) for huge initializers. Use
* {!Cil.dumpInit} instead. *)
val d_init: unit -> init -> Pretty.doc
val d_binop: unit -> binop -> Pretty.doc
val d_unop: unit -> unop -> Pretty.doc
* Pretty - print an attribute using { ! }
val d_attr: unit -> attribute -> Pretty.doc
* Pretty - print an argument of an attribute using { ! }
val d_attrparam: unit -> attrparam -> Pretty.doc
* Pretty - print a list of attributes using { ! }
val d_attrlist: unit -> attributes -> Pretty.doc
* Pretty - print an instruction using { ! }
val d_instr: unit -> instr -> Pretty.doc
* Pretty - print a label using { ! }
val d_label: unit -> label -> Pretty.doc
* Pretty - print a statement using { ! } . This can be
* extremely slow ( or even overflow the stack ) for huge statements . Use
* { ! } instead .
* extremely slow (or even overflow the stack) for huge statements. Use
* {!Cil.dumpStmt} instead. *)
val d_stmt: unit -> stmt -> Pretty.doc
* Pretty - print a block using { ! } . This can be
* extremely slow ( or even overflow the stack ) for huge blocks . Use
* { ! Cil.dumpBlock } instead .
* extremely slow (or even overflow the stack) for huge blocks. Use
* {!Cil.dumpBlock} instead. *)
val d_block: unit -> block -> Pretty.doc
val d_fundec: unit -> fundec -> Pretty.doc
* Pretty - print the internal representation of a global using
* { ! } . This can be extremely slow ( or even overflow the
* stack ) for huge globals ( such as arrays with lots of initializers ) . Use
* { ! Cil.dumpGlobal } instead .
* {!Cil.defaultCilPrinter}. This can be extremely slow (or even overflow the
* stack) for huge globals (such as arrays with lots of initializers). Use
* {!Cil.dumpGlobal} instead. *)
val d_global: unit -> global -> Pretty.doc
val dn_exp : unit -> exp -> Pretty.doc
val dn_lval : unit -> lval -> Pretty.doc
val dn_init : unit -> init -> Pretty.doc
val dn_type : unit -> typ -> Pretty.doc
val dn_global : unit -> global -> Pretty.doc
val dn_attrlist : unit -> attributes -> Pretty.doc
val dn_attr : unit -> attribute -> Pretty.doc
val dn_attrparam : unit -> attrparam -> Pretty.doc
val dn_stmt : unit -> stmt -> Pretty.doc
val dn_instr : unit -> instr -> Pretty.doc
val d_shortglobal: unit -> global -> Pretty.doc
val dumpGlobal: cilPrinter -> out_channel -> global -> unit
val dumpFile: cilPrinter -> out_channel -> string -> file -> unit
* the following error message producing functions also print a location in
* the code . use { ! } and { ! Errormsg.unimp } if you do not want
* that
* the code. use {!Errormsg.bug} and {!Errormsg.unimp} if you do not want
* that *)
* Like { ! } except that { ! } is also printed
val bug: ('a,unit,Pretty.doc) format -> 'a
val unimp: ('a,unit,Pretty.doc) format -> 'a
* Like { ! Errormsg.error } except that { ! } is also printed
val error: ('a,unit,Pretty.doc) format -> 'a
val errorLoc: location -> ('a,unit,Pretty.doc) format -> 'a
* Like { ! Errormsg.warn } except that { ! } is also printed
val warn: ('a,unit,Pretty.doc) format -> 'a
* Like { ! Errormsg.warnOpt } except that { ! } is also printed .
* This warning is printed only of { ! } is set .
* This warning is printed only of {!Errormsg.warnFlag} is set. *)
val warnOpt: ('a,unit,Pretty.doc) format -> 'a
* Like { ! Errormsg.warn } except that { ! } and context
is also printed
is also printed *)
val warnContext: ('a,unit,Pretty.doc) format -> 'a
* Like { ! Errormsg.warn } except that { ! } and context is also
* printed . This warning is printed only of { ! } is set .
* printed. This warning is printed only of {!Errormsg.warnFlag} is set. *)
val warnContextOpt: ('a,unit,Pretty.doc) format -> 'a
val warnLoc: location -> ('a,unit,Pretty.doc) format -> 'a
val d_plainexp: unit -> exp -> Pretty.doc
val d_plaininit: unit -> init -> Pretty.doc
val d_plainlval: unit -> lval -> Pretty.doc
val d_plaintype: unit -> typ -> Pretty.doc
val dd_exp: unit -> exp -> Pretty.doc
val dd_lval: unit -> lval -> Pretty.doc
val string_of_exp: exp -> string
val string_of_loc: location -> string
val string_of_lval: lval -> string
val string_of_offset: offset -> string
val string_of_init: init -> string
val string_of_typ: typ -> string
val string_of_attrlist: attributes -> string
val string_of_attr: attribute -> string
val string_of_attrparam: attrparam -> string
val string_of_label: label -> string
val string_of_stmt: stmt -> string
val string_of_block: block -> string
val string_of_instr: instr -> string
val string_of_global: global -> string
* Assign unique names to local variables . This might be necessary after you
* transformed the code and added or renamed some new variables . Names are
* not used by CIL internally , but once you print the file out the compiler
* downstream might be confused . You might
* have added a new global that happens to have the same name as a local in
* some function . Rename the local to ensure that there would never be
* confusioin . Or , viceversa , you might have added a local with a name that
* conflicts with a global
* transformed the code and added or renamed some new variables. Names are
* not used by CIL internally, but once you print the file out the compiler
* downstream might be confused. You might
* have added a new global that happens to have the same name as a local in
* some function. Rename the local to ensure that there would never be
* confusioin. Or, viceversa, you might have added a local with a name that
* conflicts with a global *)
val uniqueVarNames: file -> unit
* A peephole optimizer that processes two adjacent instructions and possibly
replaces them both . If some replacement happens , then the new instructions
are themselves subject to optimization
replaces them both. If some replacement happens, then the new instructions
are themselves subject to optimization *)
val peepHole2: (instr * instr -> instr list option) -> stmt list -> unit
* Similar to [ peepHole2 ] except that the optimization window consists of
one instruction , not two
one instruction, not two *)
val peepHole1: (instr -> instr list option) -> stmt list -> unit
* Raised when one of the bitsSizeOf functions can not compute the size of a
* type . This can happen because the type contains array - length expressions
* that we do n't know how to compute or because it is a type whose size is
* not defined ( e.g. TFun or an undefined ) . The string is an
* explanation of the error
* type. This can happen because the type contains array-length expressions
* that we don't know how to compute or because it is a type whose size is
* not defined (e.g. TFun or an undefined compinfo). The string is an
* explanation of the error *)
exception SizeOfError of string * typ
val unsignedVersionOf : ikind -> ikind
val signedVersionOf : ikind -> ikind
val intRank : ikind -> int
* Return the common integer kind of the two integer arguments , as
defined in ISO C 6.3.1.8 ( " Usual arithmetic conversions " )
defined in ISO C 6.3.1.8 ("Usual arithmetic conversions") *)
val commonIntKind : ikind -> ikind -> ikind
* The signed integer kind for a given size ( unsigned if second argument
* is true ) . Raises Not_found if no such kind exists
* is true). Raises Not_found if no such kind exists *)
val intKindForSize : int -> bool -> ikind
val floatKindForSize : int-> fkind
val bytesSizeOfInt: ikind -> int
* The size of a type , in bits . Trailing padding is added for structs and
* arrays . Raises { ! . SizeOfError } when it can not compute the size . This
* function is architecture dependent , so you should only call this after you
* call { ! Cil.initCIL } . Remember that on GCC sizeof(void ) is 1 !
* arrays. Raises {!Cil.SizeOfError} when it cannot compute the size. This
* function is architecture dependent, so you should only call this after you
* call {!Cil.initCIL}. Remember that on GCC sizeof(void) is 1! *)
val bitsSizeOf: typ -> int
* Represents an integer as for a given kind . Returns a truncation
* flag saying that the value fit in the kind ( NoTruncation ) , did n't
* fit but no " interesting " bits ( all-0 or all-1 ) were lost
* ( ValueTruncation ) or that bits were lost ( BitTruncation ) . Another
* way to look at the ValueTruncation result is that if you had used
* the kind of opposite signedness ( e.g. IUInt rather than IInt ) , you
* would gave got ...
* flag saying that the value fit in the kind (NoTruncation), didn't
* fit but no "interesting" bits (all-0 or all-1) were lost
* (ValueTruncation) or that bits were lost (BitTruncation). Another
* way to look at the ValueTruncation result is that if you had used
* the kind of opposite signedness (e.g. IUInt rather than IInt), you
* would gave got NoTruncation... *)
val truncateCilint: ikind -> cilint -> cilint * truncation
val fitsInInt: ikind -> cilint -> bool
* Return the smallest kind that will hold the integer 's value . The
* kind will be unsigned if the 2nd argument is true , signed
* otherwise . Note that if the value does n't fit in any of the
* available types , you will get ILongLong ( 2nd argument false ) or
* ( 2nd argument true ) .
* kind will be unsigned if the 2nd argument is true, signed
* otherwise. Note that if the value doesn't fit in any of the
* available types, you will get ILongLong (2nd argument false) or
* IULongLong (2nd argument true). *)
val intKindForValue: cilint -> bool -> ikind
* Construct a cilint from an integer kind and int64 value . Used for
* getting the actual constant value from a CInt64(n , , _ )
* constant .
* getting the actual constant value from a CInt64(n, ik, _)
* constant. *)
val mkCilint : ikind -> int64 -> cilint
* The size of a type , in bytes . Returns a constant expression or a
* " sizeof " expression if it can not compute the size . This function
* is architecture dependent , so you should only call this after you
* call { ! Cil.initCIL } .
* "sizeof" expression if it cannot compute the size. This function
* is architecture dependent, so you should only call this after you
* call {!Cil.initCIL}. *)
val sizeOf: typ * location -> exp
* The minimum alignment ( in bytes ) for a type . This function is
* architecture dependent , so you should only call this after you call
* { ! Cil.initCIL } .
* architecture dependent, so you should only call this after you call
* {!Cil.initCIL}. *)
val alignOf_int: typ -> int
* Give a type of a base and an offset , returns the number of bits from the
* base address and the width ( also expressed in bits ) for the subobject
* denoted by the offset . Raises { ! . SizeOfError } when it can not compute
* the size . This function is architecture dependent , so you should only call
* this after you call { ! Cil.initCIL } .
* base address and the width (also expressed in bits) for the subobject
* denoted by the offset. Raises {!Cil.SizeOfError} when it cannot compute
* the size. This function is architecture dependent, so you should only call
* this after you call {!Cil.initCIL}. *)
val bitsOffset: typ -> offset -> int * int
* Whether " char " is unsigned . Set after you call { ! Cil.initCIL }
val char_is_unsigned: bool ref
* Whether the machine is little endian . Set after you call { ! Cil.initCIL }
val little_endian: bool ref
* Whether the compiler generates assembly labels by prepending " _ " to the
identifier . That is , will function foo ( ) have the label " foo " , or " _ foo " ?
Set after you call { ! Cil.initCIL }
identifier. That is, will function foo() have the label "foo", or "_foo"?
Set after you call {!Cil.initCIL} *)
val underscore_name: bool ref
val posUnknown: position
val locUnknown: location
val startPos: location -> position
val endPos: location -> position
* Create a location from 2 position
val makeLoc: position -> position -> location
val get_instrLoc: instr -> location
* Return the location of a global , or locUnknown
val get_globalLoc: global -> location
* Return the location of a statement , or locUnknown
val get_stmtLoc: stmtkind -> location
* Return the location of an expression , or locUnknown
val get_expLoc: exp -> location
val get_lvalLoc: lval -> location
val get_offsetLoc: offset -> location
val get_lhostLoc: lhost -> location
val dExp: Pretty.doc -> exp
val dInstr: Pretty.doc -> location -> instr
* Generate a { ! Cil.global } to be used in case of errors .
val dGlobal: Pretty.doc -> location -> global
val mapNoCopy: ('a -> 'a) -> 'a list -> 'a list
val mapNoCopyList: ('a -> 'a list) -> 'a list -> 'a list
* sm : return true if the first is a prefix of the second string
val startsWith: string -> string -> bool
* return true if the first is a suffix of the second string
val endsWith: string -> string -> bool
val stripUnderscores: string -> string
type formatArg =
Fe of exp
| Fu of unop
| Fb of binop
| Fk of ikind
| Fv of varinfo
| Fl of lval
| Flo of lval option
| Fo of offset
| Fc of compinfo
| Fi of instr
| FI of instr list
| Ft of typ
| Fd of int
| Fg of string
| Fs of stmt
| FS of stmt list
| FA of attributes
| Fp of attrparam
| FP of attrparam list
| FX of string
val d_formatarg: unit -> formatArg -> Pretty.doc
val warnTruncate: bool ref
val envMachine : Machdep.mach option ref
* @deprecated . Convert two int64 / kind pairs to a common int64 / int64 / kind triple .
val convertInts: int64 -> ikind -> int64 -> ikind -> int64 * int64 * ikind
* @deprecated . Ca n't handle large 64 - bit unsigned constants
correctly - use getInteger instead . If the given expression
is a ( possibly cast'ed ) character or an integer constant , return
that integer . Otherwise , return None .
correctly - use getInteger instead. If the given expression
is a (possibly cast'ed) character or an integer constant, return
that integer. Otherwise, return None. *)
val isInteger: exp -> int64 option
val truncateInteger64: ikind -> int64 -> int64 * bool
val gccBuiltins: (string, typ * typ list * bool) Hashtbl.t
val msvcBuiltins: (string, typ * typ list * bool) Hashtbl.t
val string_of_loc: location -> string
|
f431d3526fbb1feaffaec729e665a8b09b387cc0d4d51612dd1c13e4d36c15db | byteally/webapi | MockSpec.hs | # OPTIONS_GHC -fno - warn - unused - binds #
# LANGUAGE MultiParamTypeClasses , TypeFamilies , OverloadedStrings , DataKinds , TypeOperators , TypeSynonymInstances , FlexibleInstances , DeriveGeneric #
module WebApi.MockSpec (spec) where
import Data.Aeson
import GHC.Generics
import WebApi hiding (get, post, put)
import Test.Hspec
import Test.Hspec.Wai
import Test.QuickCheck
import qualified Network.Wai as Wai
withApp :: SpecWith ((), Wai.Application) -> Spec
--withApp :: Wai.Application -> Spec
withApp = with (return mockApp)
mockApp :: Wai.Application
mockApp = mockServer serverSettings (MockServer mockServerSettings :: MockServer MockSpec)
data MockSpec
type MockApi = Static "mock"
data QP = QP { qp1 :: Int, qp2 :: Bool }
deriving (Show, Eq, Generic)
data MockOut = MockOut { out1 :: Int
, out2 :: Bool
, out3 :: Char
} deriving (Show, Eq, Generic)
instance ToJSON MockOut where
instance FromParam 'QueryParam QP where
instance Arbitrary MockOut where
arbitrary = MockOut <$> arbitrary
<*> arbitrary
<*> arbitrary
instance WebApi MockSpec where
type Apis MockSpec = '[ Route '[GET] MockApi ]
instance ApiContract MockSpec GET MockApi where
type QueryParam GET MockApi = QP
type ApiOut GET MockApi = MockOut
type ApiErr GET MockApi = ()
spec :: Spec
spec = withApp $ describe "WebApi mockserver" $ do
it "should be 200 ok" $ do
get "mock?qp1=5&qp2=True" `shouldRespondWith` 200
| null | https://raw.githubusercontent.com/byteally/webapi/8d712d0ae786475b177beacee32dc40db320af4c/webapi/tests/WebApi/MockSpec.hs | haskell | withApp :: Wai.Application -> Spec | # OPTIONS_GHC -fno - warn - unused - binds #
# LANGUAGE MultiParamTypeClasses , TypeFamilies , OverloadedStrings , DataKinds , TypeOperators , TypeSynonymInstances , FlexibleInstances , DeriveGeneric #
module WebApi.MockSpec (spec) where
import Data.Aeson
import GHC.Generics
import WebApi hiding (get, post, put)
import Test.Hspec
import Test.Hspec.Wai
import Test.QuickCheck
import qualified Network.Wai as Wai
withApp :: SpecWith ((), Wai.Application) -> Spec
withApp = with (return mockApp)
mockApp :: Wai.Application
mockApp = mockServer serverSettings (MockServer mockServerSettings :: MockServer MockSpec)
data MockSpec
type MockApi = Static "mock"
data QP = QP { qp1 :: Int, qp2 :: Bool }
deriving (Show, Eq, Generic)
data MockOut = MockOut { out1 :: Int
, out2 :: Bool
, out3 :: Char
} deriving (Show, Eq, Generic)
instance ToJSON MockOut where
instance FromParam 'QueryParam QP where
instance Arbitrary MockOut where
arbitrary = MockOut <$> arbitrary
<*> arbitrary
<*> arbitrary
instance WebApi MockSpec where
type Apis MockSpec = '[ Route '[GET] MockApi ]
instance ApiContract MockSpec GET MockApi where
type QueryParam GET MockApi = QP
type ApiOut GET MockApi = MockOut
type ApiErr GET MockApi = ()
spec :: Spec
spec = withApp $ describe "WebApi mockserver" $ do
it "should be 200 ok" $ do
get "mock?qp1=5&qp2=True" `shouldRespondWith` 200
|
e7656b1c28323d5d72dad7bbad1aa78c28bef02e761cb1737e78fca0dc543ecc | wesen/ruinwesen | twitter.lisp | (in-package :ruinwesen)
(defparameter *last-twitters* nil)
(defparameter *last-twitters-ruin* nil)
(defun gather-twitters ()
(let ((twitter (get-twitter "wesen" :count 3)))
(when twitter
(setf *last-twitters* twitter)))
(let ((twitter (get-twitter "RuinMusic" :count 3)))
(when twitter
(setf *last-twitters-ruin* twitter))))
(defun get-text-body (node)
(unless (= (length (dom:child-nodes node)) 0)
(dom:node-value (aref (dom:child-nodes node) 0) )))
(defun get-twitter (user &key (count 5))
(let (res
(doc (cxml:parse-octets
(drakma:http-request (format nil
"/~A.xml?count=~A" user count))
(cxml-dom:make-dom-builder))))
(dom:do-node-list (node (dom:get-elements-by-tag-name doc "status"))
(let ((text (aref (dom:get-elements-by-tag-name node "text") 0))
(id (aref (dom:get-elements-by-tag-name node "id") 0))
(date (aref (dom:get-elements-by-tag-name node "created_at") 0)))
(push (list (twitter-date-to-string (get-text-body date))
(get-text-body text)
(get-text-body id)) res)))
(nreverse res)))
(defvar *months*
'(("Jan" . 1)
("Feb" . 2)
("Mar" . 3)
("Apr" . 4)
("May" . 5)
("Jun" . 6)
("Jul" . 7)
("Aug" . 8)
("Sep" . 9)
("Oct" . 10)
("Nov" . 11)
("Dec" . 12)))
(defun twitter-date-to-string (date)
(twitter-difference (twitter-date date)))
(defun twitter-date (date)
(let* ((elts (cl-ppcre:split "\\s+" date))
(month (cdr (assoc (second elts) *months* :test #'string-equal)))
(day (parse-integer (third elts)))
(year (parse-integer (sixth elts)))
(time (fourth elts)))
(+ 3600 (parse-time (format nil "~A/~A/~A ~A" month day year time)))))
(defun twitter-difference (date)
(let ((diff (- (get-universal-time) date)))
(twitter-diff-to-string diff)))
(defun twitter-diff-to-string (diff)
(cond
((< diff 5)
"less than 5 seconds ago")
((< diff 10)
"less than 10 seconds ago")
((< diff 30)
"less than 30 seconds ago")
((< diff 60)
"less than one minute ago")
((< diff (* 45 60))
(format nil "~A minutes ago" (truncate diff 60)))
((< diff (+ 3600 (* 45 60)))
(format nil "about one hour ago"))
((< (+ diff (* 15 60)) (* 24 3600))
(format nil "about ~A hours ago" (truncate (+ diff (* 15 60)) 3600)))
((< diff (* 7 24 3600))
(format nil "~A days ago" (truncate (+ diff (* 15 60)) (* 24 3600))))
((< diff (* 2 7 24 3600))
"one week ago")
(t
(format nil "~A weeks ago" (truncate diff (* 7 24 3600))))))
| null | https://raw.githubusercontent.com/wesen/ruinwesen/9f3ccea85425cf46b57e76144b3114ca342bad0f/ruinwesen/src/twitter.lisp | lisp | (in-package :ruinwesen)
(defparameter *last-twitters* nil)
(defparameter *last-twitters-ruin* nil)
(defun gather-twitters ()
(let ((twitter (get-twitter "wesen" :count 3)))
(when twitter
(setf *last-twitters* twitter)))
(let ((twitter (get-twitter "RuinMusic" :count 3)))
(when twitter
(setf *last-twitters-ruin* twitter))))
(defun get-text-body (node)
(unless (= (length (dom:child-nodes node)) 0)
(dom:node-value (aref (dom:child-nodes node) 0) )))
(defun get-twitter (user &key (count 5))
(let (res
(doc (cxml:parse-octets
(drakma:http-request (format nil
"/~A.xml?count=~A" user count))
(cxml-dom:make-dom-builder))))
(dom:do-node-list (node (dom:get-elements-by-tag-name doc "status"))
(let ((text (aref (dom:get-elements-by-tag-name node "text") 0))
(id (aref (dom:get-elements-by-tag-name node "id") 0))
(date (aref (dom:get-elements-by-tag-name node "created_at") 0)))
(push (list (twitter-date-to-string (get-text-body date))
(get-text-body text)
(get-text-body id)) res)))
(nreverse res)))
(defvar *months*
'(("Jan" . 1)
("Feb" . 2)
("Mar" . 3)
("Apr" . 4)
("May" . 5)
("Jun" . 6)
("Jul" . 7)
("Aug" . 8)
("Sep" . 9)
("Oct" . 10)
("Nov" . 11)
("Dec" . 12)))
(defun twitter-date-to-string (date)
(twitter-difference (twitter-date date)))
(defun twitter-date (date)
(let* ((elts (cl-ppcre:split "\\s+" date))
(month (cdr (assoc (second elts) *months* :test #'string-equal)))
(day (parse-integer (third elts)))
(year (parse-integer (sixth elts)))
(time (fourth elts)))
(+ 3600 (parse-time (format nil "~A/~A/~A ~A" month day year time)))))
(defun twitter-difference (date)
(let ((diff (- (get-universal-time) date)))
(twitter-diff-to-string diff)))
(defun twitter-diff-to-string (diff)
(cond
((< diff 5)
"less than 5 seconds ago")
((< diff 10)
"less than 10 seconds ago")
((< diff 30)
"less than 30 seconds ago")
((< diff 60)
"less than one minute ago")
((< diff (* 45 60))
(format nil "~A minutes ago" (truncate diff 60)))
((< diff (+ 3600 (* 45 60)))
(format nil "about one hour ago"))
((< (+ diff (* 15 60)) (* 24 3600))
(format nil "about ~A hours ago" (truncate (+ diff (* 15 60)) 3600)))
((< diff (* 7 24 3600))
(format nil "~A days ago" (truncate (+ diff (* 15 60)) (* 24 3600))))
((< diff (* 2 7 24 3600))
"one week ago")
(t
(format nil "~A weeks ago" (truncate diff (* 7 24 3600))))))
| |
34e05f605f3442e70d04f808328472597ceab17bb6a0628b699b529e8b5fbb7c | sjoerdvisscher/free-functors | HFree.hs | # OPTIONS_GHC -fno - warn - unused - matches #
# LANGUAGE
RankNTypes
, TypeOperators
, , TemplateHaskell
, UndecidableInstances
, QuantifiedConstraints
#
RankNTypes
, TypeOperators
, ConstraintKinds
, TemplateHaskell
, UndecidableInstances
, QuantifiedConstraints
#-}
-----------------------------------------------------------------------------
-- |
Module : Data . Functor . HFree
-- License : BSD-style (see the file LICENSE)
--
-- Maintainer :
-- Stability : experimental
-- Portability : non-portable
--
-- A free functor is left adjoint to a forgetful functor.
-- In this package the forgetful functor forgets class constraints.
--
-- Compared to @Data.Functor.Free@ we're going up a level.
-- These free functors go between categories of functors and the natural
-- transformations between them.
-----------------------------------------------------------------------------
module Data.Functor.HFree where
import Control.Applicative
import Control.Monad (join)
import Control.Monad.Trans.Class
import Data.Functor.Identity
import Data.Functor.Contravariant
import Data.Functor.Contravariant.Divisible
import Language.Haskell.TH.Syntax (Q, Name, Dec)
import Data.Functor.Free.Internal
-- | Natural transformations.
type f :~> g = forall b. f b -> g b
| The higher order free functor for constraint
newtype HFree c f a = HFree { runHFree :: forall g. c g => (f :~> g) -> g a }
-- | The free monad of a functor.
instance (c ~=> Monad, c (HFree c f)) => Monad (HFree c f) where
return = pure
HFree f >>= g = HFree $ \k -> f k >>= rightAdjunct k . g
HFree f >> HFree g = HFree $ \k -> f k >> g k
| Derive the instance of @`HFree ` c f a@ for the class @c@ , .
--
-- For example:
--
-- @deriveHFreeInstance ''Functor@
deriveHFreeInstance :: Name -> Q [Dec]
deriveHFreeInstance = deriveFreeInstance' ''HFree 'HFree 'runHFree
unit :: f :~> HFree c f
unit fa = HFree $ \k -> k fa
rightAdjunct :: c g => (f :~> g) -> HFree c f :~> g
rightAdjunct f h = runHFree h f
| @counit =
counit :: c f => HFree c f :~> f
counit = rightAdjunct id
-- | @leftAdjunct f = f . unit@
leftAdjunct :: (HFree c f :~> g) -> f :~> g
leftAdjunct f = f . unit
transform :: (forall r. c r => (g :~> r) -> f :~> r) -> HFree c f :~> HFree c g
transform t h = HFree $ \k -> rightAdjunct (t k) h
-- transform t = HFree . (. t) . runHFree
hfmap :: (f :~> g) -> HFree c f :~> HFree c g
hfmap f = transform (\g -> g . f)
bind :: (f :~> HFree c g) -> HFree c f :~> HFree c g
bind f = transform (\k -> rightAdjunct k . f)
liftFree :: f a -> HFree c f a
liftFree = unit
lowerFree :: c f => HFree c f a -> f a
lowerFree = counit
convert :: (c (t f), Monad f, MonadTrans t) => HFree c f a -> t f a
convert = rightAdjunct lift
iter :: c Identity => (forall b. f b -> b) -> HFree c f a -> a
iter f = runIdentity . rightAdjunct (Identity . f)
wrap :: f (HFree Monad f a) -> HFree Monad f a
wrap as = join (unit as)
deriveFreeInstance' ''HFree 'HFree 'runHFree ''Functor
deriveFreeInstance' ''HFree 'HFree 'runHFree ''Applicative
deriveFreeInstance' ''HFree 'HFree 'runHFree ''Alternative
is only a monad transformer if is called with monad morphisms .
F.e . lift . return = = return fails if the results are inspected with ( const Nothing ) .
deriveFreeInstance' ''HFree 'HFree 'runHFree ''Contravariant
deriveFreeInstance' ''HFree 'HFree 'runHFree ''Divisible
deriveFreeInstance' ''HFree 'HFree 'runHFree ''Decidable
| null | https://raw.githubusercontent.com/sjoerdvisscher/free-functors/78bff2949e2f54afb4a0b59cd105a30645742b3a/src/Data/Functor/HFree.hs | haskell | ---------------------------------------------------------------------------
|
License : BSD-style (see the file LICENSE)
Maintainer :
Stability : experimental
Portability : non-portable
A free functor is left adjoint to a forgetful functor.
In this package the forgetful functor forgets class constraints.
Compared to @Data.Functor.Free@ we're going up a level.
These free functors go between categories of functors and the natural
transformations between them.
---------------------------------------------------------------------------
| Natural transformations.
| The free monad of a functor.
For example:
@deriveHFreeInstance ''Functor@
| @leftAdjunct f = f . unit@
transform t = HFree . (. t) . runHFree | # OPTIONS_GHC -fno - warn - unused - matches #
# LANGUAGE
RankNTypes
, TypeOperators
, , TemplateHaskell
, UndecidableInstances
, QuantifiedConstraints
#
RankNTypes
, TypeOperators
, ConstraintKinds
, TemplateHaskell
, UndecidableInstances
, QuantifiedConstraints
#-}
Module : Data . Functor . HFree
module Data.Functor.HFree where
import Control.Applicative
import Control.Monad (join)
import Control.Monad.Trans.Class
import Data.Functor.Identity
import Data.Functor.Contravariant
import Data.Functor.Contravariant.Divisible
import Language.Haskell.TH.Syntax (Q, Name, Dec)
import Data.Functor.Free.Internal
type f :~> g = forall b. f b -> g b
| The higher order free functor for constraint
newtype HFree c f a = HFree { runHFree :: forall g. c g => (f :~> g) -> g a }
instance (c ~=> Monad, c (HFree c f)) => Monad (HFree c f) where
return = pure
HFree f >>= g = HFree $ \k -> f k >>= rightAdjunct k . g
HFree f >> HFree g = HFree $ \k -> f k >> g k
| Derive the instance of @`HFree ` c f a@ for the class @c@ , .
deriveHFreeInstance :: Name -> Q [Dec]
deriveHFreeInstance = deriveFreeInstance' ''HFree 'HFree 'runHFree
unit :: f :~> HFree c f
unit fa = HFree $ \k -> k fa
rightAdjunct :: c g => (f :~> g) -> HFree c f :~> g
rightAdjunct f h = runHFree h f
| @counit =
counit :: c f => HFree c f :~> f
counit = rightAdjunct id
leftAdjunct :: (HFree c f :~> g) -> f :~> g
leftAdjunct f = f . unit
transform :: (forall r. c r => (g :~> r) -> f :~> r) -> HFree c f :~> HFree c g
transform t h = HFree $ \k -> rightAdjunct (t k) h
hfmap :: (f :~> g) -> HFree c f :~> HFree c g
hfmap f = transform (\g -> g . f)
bind :: (f :~> HFree c g) -> HFree c f :~> HFree c g
bind f = transform (\k -> rightAdjunct k . f)
liftFree :: f a -> HFree c f a
liftFree = unit
lowerFree :: c f => HFree c f a -> f a
lowerFree = counit
convert :: (c (t f), Monad f, MonadTrans t) => HFree c f a -> t f a
convert = rightAdjunct lift
iter :: c Identity => (forall b. f b -> b) -> HFree c f a -> a
iter f = runIdentity . rightAdjunct (Identity . f)
wrap :: f (HFree Monad f a) -> HFree Monad f a
wrap as = join (unit as)
deriveFreeInstance' ''HFree 'HFree 'runHFree ''Functor
deriveFreeInstance' ''HFree 'HFree 'runHFree ''Applicative
deriveFreeInstance' ''HFree 'HFree 'runHFree ''Alternative
is only a monad transformer if is called with monad morphisms .
F.e . lift . return = = return fails if the results are inspected with ( const Nothing ) .
deriveFreeInstance' ''HFree 'HFree 'runHFree ''Contravariant
deriveFreeInstance' ''HFree 'HFree 'runHFree ''Divisible
deriveFreeInstance' ''HFree 'HFree 'runHFree ''Decidable
|
513ba6b2de3c23dc9c0eb75248109de37e35f23a7c6809d71936c9c512a2792b | kupl/FixML | sol.ml | let rec sigma (f,a,b) =
if(a>b) then 0 else (f a)+sigma (f,a+1,b) | null | https://raw.githubusercontent.com/kupl/FixML/0a032a733d68cd8ccc8b1034d2908cd43b241fce/benchmarks/sigma/sigma/sol.ml | ocaml | let rec sigma (f,a,b) =
if(a>b) then 0 else (f a)+sigma (f,a+1,b) | |
1e30d8e2de353602f5702ba1459a6eafcd55f5d08c39a7b1aa4c6d33624355c4 | bobzhang/ocaml-book | myocamlbuild.ml | open Ocamlbuild_plugin
open Command
let run_and_read = Ocamlbuild_pack.My_unix.run_and_read
let blank_sep_strings = Ocamlbuild_pack.Lexers.blank_sep_strings
let find_packages () =
blank_sep_strings &
Lexing.from_string &
run_and_read "ocamlfind list | cut -d' ' -f1"
* ocamlfind can only handle these two flags
let find_syntaxes () = ["camlp4o"; "camlp4r"]
let trim_endline str =
let len = String.length (str) in
if len = 0 then str
else if str.[len-1] = '\n'
then String.sub str 0 (len-1)
else str
(** list extensions, but not used here *)
let extensions () =
let pas = List.filter
(fun x ->
String.contains_string x 0 "pa_" <> None) (find_packages ()) in
let tbl = List.map
(fun pkg ->
let dir =
trim_endline (run_and_read ("ocamlfind query " ^ pkg))in
(pkg, dir)) pas in
tbl
let debug = ref false
let site_lib () =
trim_endline (run_and_read ("ocamlfind printconf destdir"))
let _ =
if !debug then begin
List.iter (fun (pkg,dir) -> Printf.printf "%s,%s\n" pkg dir)
(extensions ());
Printf.printf "%s\n" (site_lib())
end
Menhir options
let menhir_opts = S
[A"--dump";A"--explain"; A"--infer";]
let ocamlfind x = S[A"ocamlfind"; x]
module Default = struct
let before_options () =
Options.ocamlc := ocamlfind & A"ocamlc";
Options.ocamlopt := ocamlfind & A"ocamlopt";
Options.ocamldep := ocamlfind & A"ocamldep";
Options.ocamldoc := ocamlfind & A"ocamldoc";
Options.ocamlmktop := ocamlfind & A"ocamlmktop"
let after_rules () =
when one link an ocaml library / binary / package , should use -linkpkg
flag ["ocaml"; "byte"; "link";"program"] & A"-linkpkg";
flag ["ocaml"; "native"; "link";"program"] & A"-linkpkg";
List.iter begin fun pkg ->
flag ["ocaml"; "compile"; "pkg_"^pkg] & S[A"-package"; A pkg];
flag ["ocaml"; "ocamldep"; "pkg_"^pkg] & S[A"-package"; A pkg];
flag ["ocaml"; "doc"; "pkg_"^pkg] & S[A"-package"; A pkg];
flag ["ocaml"; "link"; "pkg_"^pkg] & S[A"-package"; A pkg];
flag ["ocaml"; "infer_interface"; "pkg_"^pkg] & S[A"-package"; A pkg];
add support for menhir
end (find_packages ());
Like -package but for extensions syntax . -syntax is
* useless when linking .
* useless when linking. *)
List.iter begin fun syntax ->
flag ["ocaml"; "compile"; "syntax_"^syntax] & S[A"-syntax"; A syntax];
flag ["ocaml"; "ocamldep"; "syntax_"^syntax] & S[A"-syntax"; A syntax];
flag ["ocaml"; "doc"; "syntax_"^syntax] & S[A"-syntax"; A syntax];
flag ["ocaml"; "infer_interface"; "syntax_"^syntax] & S[A"-syntax"; A syntax];
end (find_syntaxes ());
The default " thread " tag is not compatible with ocamlfind .
Indeed , the default rules add the " threads.cma " or
" threads.cmxa " options when using this tag . When using the
" -linkpkg " option with ocamlfind , this module will then be
added twice on the command line .
To solve this , one approach is to add the " -thread " option when using
the " threads " package using the previous plugin .
Indeed, the default rules add the "threads.cma" or
"threads.cmxa" options when using this tag. When using the
"-linkpkg" option with ocamlfind, this module will then be
added twice on the command line.
To solve this, one approach is to add the "-thread" option when using
the "threads" package using the previous plugin.
*)
flag ["ocaml"; "pkg_threads"; "compile"] (S[A "-thread"]);
flag ["ocaml"; "pkg_threads"; "link"] (S[A "-thread"]);
flag ["ocaml"; "pkg_threads"; "infer_interface"] (S[A "-thread"])
end
type actions = (unit -> unit) list ref
let before_options : actions = ref []
and after_options : actions = ref []
and before_rules : actions = ref []
and after_rules : actions = ref []
let (+>) x l =
l := x :: !l
let apply plugin = begin
Default.before_options +> before_options;
Default.after_rules +> after_rules;
(fun _ -> begin
(** for pa_ulex, you must create the symbol link by yourself*)
flag ["ocaml"; "pp"; "use_ulex"] (A"pa_ulex.cma");
(** for bolt logger *)
flag ["ocaml"; "pp"; "use_bolt"] (A"bolt_pp.cmo");
(** for bitstring *)
flag ["ocaml"; "pp"; "use_bitstring"]
(S[A"bitstring.cma"; A"bitstring_persistent.cma"; A"pa_bitstring.cmo"]);
flag ["ocaml"; "pp"; "use_xstrp4"]
(S[A"xstrp4.cma"]);
flag ["ocaml"; "pp"; "use_sexp"]
(S[A"Pa_type_conv.cma"; A"pa_sexp_conv.cma"]);
flag ["ocaml"; "pp"; "use_mikmatch"]
(S[A"pa_mikmatch_pcre.cma"]);
flag ["ocaml"; "pp"; "use_meta"]
(S[A"lift_filter.cma"]);
(** demo how to use dep
dep ["ocamldep"; "file:test/test_string.ml"]
["test/test_data/string.txt";
"test/test_data/char.txt"];
flag ["ocaml"; "pp"; "use_lambda"] (A"pa_lambda.cmo");
dep ["ocamldep"; "use_lambda"]
["pa_lambda.cmo"];
*)
end) +> after_rules;
plugin ();
dispatch begin function
| Before_options -> begin
List.iter (fun f -> f () ) !before_options;
end
| After_rules -> begin
List.iter (fun f -> f ()) !after_rules;
end
| _ -> ()
end ;
end
let _ =
(** customize your plugin here *)
let plugin = (fun _ -> ()) in
apply plugin
(**
customized local filter
*)
(* let _ = dispatch begin function *)
(* |After_rules -> begin *)
flag [ " ocaml " ; " pp " ; " use_filter " ] ( A"pa_filter.cma " ) ;
dep [ " ocaml " ; " ocamldep " ; " use_filter " ] [ " pa_filter.cma " ] ;
(* end *)
(* |_ -> () *)
(* end *)
| null | https://raw.githubusercontent.com/bobzhang/ocaml-book/09a575b0d1fedfce565ecb9a0ae9cf0df37fdc75/library/code/bitstring/myocamlbuild.ml | ocaml | * list extensions, but not used here
* for pa_ulex, you must create the symbol link by yourself
* for bolt logger
* for bitstring
* demo how to use dep
dep ["ocamldep"; "file:test/test_string.ml"]
["test/test_data/string.txt";
"test/test_data/char.txt"];
flag ["ocaml"; "pp"; "use_lambda"] (A"pa_lambda.cmo");
dep ["ocamldep"; "use_lambda"]
["pa_lambda.cmo"];
* customize your plugin here
*
customized local filter
let _ = dispatch begin function
|After_rules -> begin
end
|_ -> ()
end | open Ocamlbuild_plugin
open Command
let run_and_read = Ocamlbuild_pack.My_unix.run_and_read
let blank_sep_strings = Ocamlbuild_pack.Lexers.blank_sep_strings
let find_packages () =
blank_sep_strings &
Lexing.from_string &
run_and_read "ocamlfind list | cut -d' ' -f1"
* ocamlfind can only handle these two flags
let find_syntaxes () = ["camlp4o"; "camlp4r"]
let trim_endline str =
let len = String.length (str) in
if len = 0 then str
else if str.[len-1] = '\n'
then String.sub str 0 (len-1)
else str
let extensions () =
let pas = List.filter
(fun x ->
String.contains_string x 0 "pa_" <> None) (find_packages ()) in
let tbl = List.map
(fun pkg ->
let dir =
trim_endline (run_and_read ("ocamlfind query " ^ pkg))in
(pkg, dir)) pas in
tbl
let debug = ref false
let site_lib () =
trim_endline (run_and_read ("ocamlfind printconf destdir"))
let _ =
if !debug then begin
List.iter (fun (pkg,dir) -> Printf.printf "%s,%s\n" pkg dir)
(extensions ());
Printf.printf "%s\n" (site_lib())
end
Menhir options
let menhir_opts = S
[A"--dump";A"--explain"; A"--infer";]
let ocamlfind x = S[A"ocamlfind"; x]
module Default = struct
let before_options () =
Options.ocamlc := ocamlfind & A"ocamlc";
Options.ocamlopt := ocamlfind & A"ocamlopt";
Options.ocamldep := ocamlfind & A"ocamldep";
Options.ocamldoc := ocamlfind & A"ocamldoc";
Options.ocamlmktop := ocamlfind & A"ocamlmktop"
let after_rules () =
when one link an ocaml library / binary / package , should use -linkpkg
flag ["ocaml"; "byte"; "link";"program"] & A"-linkpkg";
flag ["ocaml"; "native"; "link";"program"] & A"-linkpkg";
List.iter begin fun pkg ->
flag ["ocaml"; "compile"; "pkg_"^pkg] & S[A"-package"; A pkg];
flag ["ocaml"; "ocamldep"; "pkg_"^pkg] & S[A"-package"; A pkg];
flag ["ocaml"; "doc"; "pkg_"^pkg] & S[A"-package"; A pkg];
flag ["ocaml"; "link"; "pkg_"^pkg] & S[A"-package"; A pkg];
flag ["ocaml"; "infer_interface"; "pkg_"^pkg] & S[A"-package"; A pkg];
add support for menhir
end (find_packages ());
Like -package but for extensions syntax . -syntax is
* useless when linking .
* useless when linking. *)
List.iter begin fun syntax ->
flag ["ocaml"; "compile"; "syntax_"^syntax] & S[A"-syntax"; A syntax];
flag ["ocaml"; "ocamldep"; "syntax_"^syntax] & S[A"-syntax"; A syntax];
flag ["ocaml"; "doc"; "syntax_"^syntax] & S[A"-syntax"; A syntax];
flag ["ocaml"; "infer_interface"; "syntax_"^syntax] & S[A"-syntax"; A syntax];
end (find_syntaxes ());
The default " thread " tag is not compatible with ocamlfind .
Indeed , the default rules add the " threads.cma " or
" threads.cmxa " options when using this tag . When using the
" -linkpkg " option with ocamlfind , this module will then be
added twice on the command line .
To solve this , one approach is to add the " -thread " option when using
the " threads " package using the previous plugin .
Indeed, the default rules add the "threads.cma" or
"threads.cmxa" options when using this tag. When using the
"-linkpkg" option with ocamlfind, this module will then be
added twice on the command line.
To solve this, one approach is to add the "-thread" option when using
the "threads" package using the previous plugin.
*)
flag ["ocaml"; "pkg_threads"; "compile"] (S[A "-thread"]);
flag ["ocaml"; "pkg_threads"; "link"] (S[A "-thread"]);
flag ["ocaml"; "pkg_threads"; "infer_interface"] (S[A "-thread"])
end
type actions = (unit -> unit) list ref
let before_options : actions = ref []
and after_options : actions = ref []
and before_rules : actions = ref []
and after_rules : actions = ref []
let (+>) x l =
l := x :: !l
let apply plugin = begin
Default.before_options +> before_options;
Default.after_rules +> after_rules;
(fun _ -> begin
flag ["ocaml"; "pp"; "use_ulex"] (A"pa_ulex.cma");
flag ["ocaml"; "pp"; "use_bolt"] (A"bolt_pp.cmo");
flag ["ocaml"; "pp"; "use_bitstring"]
(S[A"bitstring.cma"; A"bitstring_persistent.cma"; A"pa_bitstring.cmo"]);
flag ["ocaml"; "pp"; "use_xstrp4"]
(S[A"xstrp4.cma"]);
flag ["ocaml"; "pp"; "use_sexp"]
(S[A"Pa_type_conv.cma"; A"pa_sexp_conv.cma"]);
flag ["ocaml"; "pp"; "use_mikmatch"]
(S[A"pa_mikmatch_pcre.cma"]);
flag ["ocaml"; "pp"; "use_meta"]
(S[A"lift_filter.cma"]);
end) +> after_rules;
plugin ();
dispatch begin function
| Before_options -> begin
List.iter (fun f -> f () ) !before_options;
end
| After_rules -> begin
List.iter (fun f -> f ()) !after_rules;
end
| _ -> ()
end ;
end
let _ =
let plugin = (fun _ -> ()) in
apply plugin
flag [ " ocaml " ; " pp " ; " use_filter " ] ( A"pa_filter.cma " ) ;
dep [ " ocaml " ; " ocamldep " ; " use_filter " ] [ " pa_filter.cma " ] ;
|
4532019aa317e417c63c93efe4a7ab8757aada07aaeb58485e307fa40943dcd4 | picnic/RelationExtraction | host_stuff.mli | (****************************************************************************)
RelationExtraction - Extraction of inductive relations for Coq
(* *)
(* 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 </>. *)
(* *)
Copyright 2011 , 2012 CNAM - ENSIIE
< >
< >
< >
(****************************************************************************)
Host is the host language ( Coq or ) . In order to generate
functions , we need to keep information from these languages . Some part
( mostly typing information ) is kept into the AST we manipulate by compiling
the predicates and the remaining part is kept into an host environment .
functions, we need to keep information from these languages. Some part
(mostly typing information) is kept into the AST we manipulate by compiling
the predicates and the remaining part is kept into an host environment.
*)
Type information for a term . This is kept into the AST .
type 'htyp host_term_type = 'htyp
val th : 'htyp -> 'htyp host_term_type
val ht : 'htyp host_term_type -> 'htyp
(* Environment for host stuff. *)
type 'henv host_env = 'henv
val he : 'henv -> 'henv host_env
val eh : 'henv host_env -> 'henv
(* Functions for host langage manipulations. *)
type ('htyp, 'henv) host_functions = {
h_get_fake_type : unit -> 'htyp host_term_type;
h_get_bool_type : unit -> string list * 'htyp host_term_type;
}
| null | https://raw.githubusercontent.com/picnic/RelationExtraction/a4cee37d0a8e5f0eff2e010e6305e037aa0d2564/host_stuff.mli | ocaml | **************************************************************************
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
along with this program. If not, see </>.
**************************************************************************
Environment for host stuff.
Functions for host langage manipulations. | RelationExtraction - Extraction of inductive relations for Coq
it under the terms of the GNU General Public License as published by
the Free Software Foundation , either version 3 of the License , or
You should have received a copy of the GNU General Public License
Copyright 2011 , 2012 CNAM - ENSIIE
< >
< >
< >
Host is the host language ( Coq or ) . In order to generate
functions , we need to keep information from these languages . Some part
( mostly typing information ) is kept into the AST we manipulate by compiling
the predicates and the remaining part is kept into an host environment .
functions, we need to keep information from these languages. Some part
(mostly typing information) is kept into the AST we manipulate by compiling
the predicates and the remaining part is kept into an host environment.
*)
Type information for a term . This is kept into the AST .
type 'htyp host_term_type = 'htyp
val th : 'htyp -> 'htyp host_term_type
val ht : 'htyp host_term_type -> 'htyp
type 'henv host_env = 'henv
val he : 'henv -> 'henv host_env
val eh : 'henv host_env -> 'henv
type ('htyp, 'henv) host_functions = {
h_get_fake_type : unit -> 'htyp host_term_type;
h_get_bool_type : unit -> string list * 'htyp host_term_type;
}
|
2c5c74067551de3c3e01b06488e9aab3560c86ab9ad8d2561cd1acd3bc754b94 | borkdude/jet | main.clj | (ns jet.main
{:no-doc true}
(:require
[babashka.cli :as cli]
[camel-snake-kebab.core :as csk]
[clojure.edn :as edn]
[clojure.java.io :as io]
[clojure.string :as str]
[jet.base64 :refer [base64-namespace]]
[jet.data-readers]
[jet.formats :as formats]
[jet.jeti :refer [start-jeti!]]
[jet.query :as q]
[jet.specter :as specter :refer [config]]
[sci.core :as sci])
(:gen-class))
(set! *warn-on-reflection* true)
(defn -paths [m opts]
(cond
(map? m)
(vec
(concat (map vector (keys m))
(mapcat (fn [[k v]]
(let [sub (-paths v opts)
nested (map #(into [k] %) (filter (comp not empty?) sub))]
(when (seq nested)
nested)))
m)))
(vector? m)
(vec (concat (map vector (range (count m)))
(mapcat (fn [idx]
(let [sub (-paths (get m idx) opts)
nested (map #(into [idx] %) (filter (comp not empty?) sub))]
(when (seq nested)
nested)))
(range (count m)))))
:else []))
(defn paths
[m]
(let [paths (-paths m nil)
paths (mapv (fn [path]
(let [v (get-in m path)]
{:path path
:val v}))
paths)]
paths))
(defn when-pred [pred]
(fn [x]
(try (when (pred x)
x)
(catch Exception _ nil))))
(def ctx
(-> (sci/init {:namespaces {'camel-snake-kebab.core
{'->PascalCase csk/->PascalCase
'->camelCase csk/->camelCase
'->SCREAMING_SNAKE_CASE csk/->SCREAMING_SNAKE_CASE
'->snake_case csk/->snake_case
'->kebab-case csk/->kebab-case
'->Camel_Snake_Case csk/->Camel_Snake_Case
'->HTTP-Header-Case csk/->HTTP-Header-Case}
'com.rpl.specter
{}
'base64 base64-namespace
'jet {'paths paths
'when-pred when-pred}}
:aliases '{str clojure.string
s com.rpl.specter
csk camel-snake-kebab.core}})
(sci/merge-opts config)))
(defn coerce-file [s]
(if (.exists (io/as-file s))
(slurp s)
s))
(defn coerce-eval-string [x]
(->> x coerce-file (sci/eval-string* ctx)))
(defn coerce-keywordize [x]
(cli/coerce x (fn [x]
(cond (= "true" x) true
(= "false" x) false
:else (coerce-eval-string x)))))
(defn coerce-query [query]
(edn/read-string
{:readers *data-readers*}
(format "[%s]" query)))
(defn coerce-thread-last [s]
(->> s coerce-file
(format "(fn [edn] (->> edn %s))")
(sci/eval-string* ctx)))
(defn coerce-thread-first [s]
(->> s coerce-file
(format "(fn [edn] (-> edn %s))")
(sci/eval-string* ctx)))
(defn coerce-interactive [interactive]
(not-empty (str/join " " interactive)))
(def cli-spec
{:from {:coerce :keyword
:alias :i
:ref "[ edn | transit | json | yaml ]"
:desc "defaults to edn."}
:to {:coerce :keyword
:alias :o
:ref "[ edn | transit | json | yaml ]"
:desc "defaults to edn."}
:colors {:ref "[ auto | true | false]"
:desc "use colored output while pretty-printing. Defaults to auto."}
:thread-last {:alias :t
:desc "implicit thread last"}
:thread-first {:alias :T
:desc "implicit thread first"}
:func {:alias :f
:desc "a single-arg Clojure function, or a path to a file that contains a function, that transforms input."}
:query {:alias :q
:desc "DEPRECATED, prefer -t, -T or -f. Given a jet-lang query, transforms input."}
:collect {:alias :c
:desc "given separate values, collects them in a vector."}
:version {:alias :v
:desc "print the current version of jet."}
:help {:alias :h
:desc "print this help text."}
:keywordize {:alias :k
:ref "[ <key-fn> ]"
:desc "if present, keywordizes JSON/YAML keys. The default transformation function is keyword unless you provide your own."}
:no-pretty {:coerce :boolean
:desc "disable pretty printing"}
:edn-reader-opts {:desc "options passed to the EDN reader."}})
(def cli-opts
{:spec cli-spec
:order (let [first-ks [:from :to
:thread-last :thread-first :func]]
(into first-ks (remove (set first-ks) (keys cli-spec))))
:no-keyword-opts true})
(defn parse-opts [args]
(cli/parse-opts
args
cli-opts))
(defn get-version
"Gets the current version of the tool"
[]
(str/trim (slurp (io/resource "JET_VERSION"))))
(defn print-help
"Prints the help text"
[]
(println (str "jet v" (get-version)))
(println)
(println "Options:")
(println)
(println (cli/format-opts cli-opts))
(println))
(defn exec [{:keys [from to keywordize
no-pretty version query
func thread-first thread-last interactive collect
edn-reader-opts
help colors]
:or {from :edn
to :edn
colors :auto}}]
(let [[func thread-first thread-last keywordize edn-reader-opts query]
[(cli/coerce func coerce-eval-string) (cli/coerce thread-first coerce-thread-first)
(cli/coerce thread-last coerce-thread-last)
(cli/coerce keywordize coerce-eval-string)
(cli/coerce edn-reader-opts coerce-eval-string)
(cli/coerce query coerce-query)]]
(cond
version (println (get-version))
interactive (start-jeti! interactive colors)
help (print-help)
:else
(let [reader (case from
:json (formats/json-parser)
:transit (formats/transit-reader)
:yaml nil
:edn nil)
next-val (case from
:edn #(formats/parse-edn edn-reader-opts *in*)
:json #(formats/parse-json reader keywordize)
:transit #(formats/parse-transit reader)
:yaml #(formats/parse-yaml *in* keywordize))
collected (when collect (vec (take-while #(not= % ::formats/EOF)
(repeatedly next-val))))
func (or func thread-first thread-last)]
(loop []
(let [input (if collect collected (next-val))]
(when-not (identical? ::formats/EOF input)
(let [input (if query (q/query input query)
input)
input (if func
(func input)
input)]
(case to
:edn (some->
input
(formats/generate-edn (not no-pretty) colors)
println)
:json (some->
input
(formats/generate-json (not no-pretty))
println)
:transit (some->
(formats/generate-transit input)
println)
:yaml (some->
input
(formats/generate-yaml (not no-pretty))
println)))
(when-not collect (recur)))))))))
(defn main [& args]
(let [opts (parse-opts args)]
(exec opts)))
;; enable println, prn etc.
(sci/alter-var-root sci/out (constantly *out*))
(sci/alter-var-root sci/err (constantly *err*))
(vreset! specter/sci-ctx ctx)
(when (System/getProperty "jet.native")
(require 'jet.patches))
(def musl?
"Captured at compile time, to know if we are running inside a
statically compiled executable with musl."
(and (= "true" (System/getenv "BABASHKA_STATIC"))
(= "true" (System/getenv "BABASHKA_MUSL"))))
(defmacro run [args]
(if musl?
;; When running in musl-compiled static executable we lift execution of bb
;; inside a thread, so we have a larger than default stack size, set by an
;; argument to the linker. See
`(let [v# (volatile! nil)
f# (fn []
(vreset! v# (apply main ~args)))]
(doto (Thread. nil f# "main")
(.start)
(.join))
@v#)
`(apply main ~args)))
(defn -main
[& args]
(run args))
| null | https://raw.githubusercontent.com/borkdude/jet/fea03680f50846a808afbb22b00dc732f98ebaeb/src/jet/main.clj | clojure | enable println, prn etc.
When running in musl-compiled static executable we lift execution of bb
inside a thread, so we have a larger than default stack size, set by an
argument to the linker. See | (ns jet.main
{:no-doc true}
(:require
[babashka.cli :as cli]
[camel-snake-kebab.core :as csk]
[clojure.edn :as edn]
[clojure.java.io :as io]
[clojure.string :as str]
[jet.base64 :refer [base64-namespace]]
[jet.data-readers]
[jet.formats :as formats]
[jet.jeti :refer [start-jeti!]]
[jet.query :as q]
[jet.specter :as specter :refer [config]]
[sci.core :as sci])
(:gen-class))
(set! *warn-on-reflection* true)
(defn -paths [m opts]
(cond
(map? m)
(vec
(concat (map vector (keys m))
(mapcat (fn [[k v]]
(let [sub (-paths v opts)
nested (map #(into [k] %) (filter (comp not empty?) sub))]
(when (seq nested)
nested)))
m)))
(vector? m)
(vec (concat (map vector (range (count m)))
(mapcat (fn [idx]
(let [sub (-paths (get m idx) opts)
nested (map #(into [idx] %) (filter (comp not empty?) sub))]
(when (seq nested)
nested)))
(range (count m)))))
:else []))
(defn paths
[m]
(let [paths (-paths m nil)
paths (mapv (fn [path]
(let [v (get-in m path)]
{:path path
:val v}))
paths)]
paths))
(defn when-pred [pred]
(fn [x]
(try (when (pred x)
x)
(catch Exception _ nil))))
(def ctx
(-> (sci/init {:namespaces {'camel-snake-kebab.core
{'->PascalCase csk/->PascalCase
'->camelCase csk/->camelCase
'->SCREAMING_SNAKE_CASE csk/->SCREAMING_SNAKE_CASE
'->snake_case csk/->snake_case
'->kebab-case csk/->kebab-case
'->Camel_Snake_Case csk/->Camel_Snake_Case
'->HTTP-Header-Case csk/->HTTP-Header-Case}
'com.rpl.specter
{}
'base64 base64-namespace
'jet {'paths paths
'when-pred when-pred}}
:aliases '{str clojure.string
s com.rpl.specter
csk camel-snake-kebab.core}})
(sci/merge-opts config)))
(defn coerce-file [s]
(if (.exists (io/as-file s))
(slurp s)
s))
(defn coerce-eval-string [x]
(->> x coerce-file (sci/eval-string* ctx)))
(defn coerce-keywordize [x]
(cli/coerce x (fn [x]
(cond (= "true" x) true
(= "false" x) false
:else (coerce-eval-string x)))))
(defn coerce-query [query]
(edn/read-string
{:readers *data-readers*}
(format "[%s]" query)))
(defn coerce-thread-last [s]
(->> s coerce-file
(format "(fn [edn] (->> edn %s))")
(sci/eval-string* ctx)))
(defn coerce-thread-first [s]
(->> s coerce-file
(format "(fn [edn] (-> edn %s))")
(sci/eval-string* ctx)))
(defn coerce-interactive [interactive]
(not-empty (str/join " " interactive)))
(def cli-spec
{:from {:coerce :keyword
:alias :i
:ref "[ edn | transit | json | yaml ]"
:desc "defaults to edn."}
:to {:coerce :keyword
:alias :o
:ref "[ edn | transit | json | yaml ]"
:desc "defaults to edn."}
:colors {:ref "[ auto | true | false]"
:desc "use colored output while pretty-printing. Defaults to auto."}
:thread-last {:alias :t
:desc "implicit thread last"}
:thread-first {:alias :T
:desc "implicit thread first"}
:func {:alias :f
:desc "a single-arg Clojure function, or a path to a file that contains a function, that transforms input."}
:query {:alias :q
:desc "DEPRECATED, prefer -t, -T or -f. Given a jet-lang query, transforms input."}
:collect {:alias :c
:desc "given separate values, collects them in a vector."}
:version {:alias :v
:desc "print the current version of jet."}
:help {:alias :h
:desc "print this help text."}
:keywordize {:alias :k
:ref "[ <key-fn> ]"
:desc "if present, keywordizes JSON/YAML keys. The default transformation function is keyword unless you provide your own."}
:no-pretty {:coerce :boolean
:desc "disable pretty printing"}
:edn-reader-opts {:desc "options passed to the EDN reader."}})
(def cli-opts
{:spec cli-spec
:order (let [first-ks [:from :to
:thread-last :thread-first :func]]
(into first-ks (remove (set first-ks) (keys cli-spec))))
:no-keyword-opts true})
(defn parse-opts [args]
(cli/parse-opts
args
cli-opts))
(defn get-version
"Gets the current version of the tool"
[]
(str/trim (slurp (io/resource "JET_VERSION"))))
(defn print-help
"Prints the help text"
[]
(println (str "jet v" (get-version)))
(println)
(println "Options:")
(println)
(println (cli/format-opts cli-opts))
(println))
(defn exec [{:keys [from to keywordize
no-pretty version query
func thread-first thread-last interactive collect
edn-reader-opts
help colors]
:or {from :edn
to :edn
colors :auto}}]
(let [[func thread-first thread-last keywordize edn-reader-opts query]
[(cli/coerce func coerce-eval-string) (cli/coerce thread-first coerce-thread-first)
(cli/coerce thread-last coerce-thread-last)
(cli/coerce keywordize coerce-eval-string)
(cli/coerce edn-reader-opts coerce-eval-string)
(cli/coerce query coerce-query)]]
(cond
version (println (get-version))
interactive (start-jeti! interactive colors)
help (print-help)
:else
(let [reader (case from
:json (formats/json-parser)
:transit (formats/transit-reader)
:yaml nil
:edn nil)
next-val (case from
:edn #(formats/parse-edn edn-reader-opts *in*)
:json #(formats/parse-json reader keywordize)
:transit #(formats/parse-transit reader)
:yaml #(formats/parse-yaml *in* keywordize))
collected (when collect (vec (take-while #(not= % ::formats/EOF)
(repeatedly next-val))))
func (or func thread-first thread-last)]
(loop []
(let [input (if collect collected (next-val))]
(when-not (identical? ::formats/EOF input)
(let [input (if query (q/query input query)
input)
input (if func
(func input)
input)]
(case to
:edn (some->
input
(formats/generate-edn (not no-pretty) colors)
println)
:json (some->
input
(formats/generate-json (not no-pretty))
println)
:transit (some->
(formats/generate-transit input)
println)
:yaml (some->
input
(formats/generate-yaml (not no-pretty))
println)))
(when-not collect (recur)))))))))
(defn main [& args]
(let [opts (parse-opts args)]
(exec opts)))
(sci/alter-var-root sci/out (constantly *out*))
(sci/alter-var-root sci/err (constantly *err*))
(vreset! specter/sci-ctx ctx)
(when (System/getProperty "jet.native")
(require 'jet.patches))
(def musl?
"Captured at compile time, to know if we are running inside a
statically compiled executable with musl."
(and (= "true" (System/getenv "BABASHKA_STATIC"))
(= "true" (System/getenv "BABASHKA_MUSL"))))
(defmacro run [args]
(if musl?
`(let [v# (volatile! nil)
f# (fn []
(vreset! v# (apply main ~args)))]
(doto (Thread. nil f# "main")
(.start)
(.join))
@v#)
`(apply main ~args)))
(defn -main
[& args]
(run args))
|
56f164e5007a340de06577a71b5a8f35352ae40bf91871709c798906d4547c07 | seanomlor/programming-in-haskell | take.hs | import Prelude hiding (take)
take :: Int -> [a] -> [a]
take 0 _ = []
take _ [] = []
take n (x:xs) = x : take (n - 1) xs
| null | https://raw.githubusercontent.com/seanomlor/programming-in-haskell/e05142e6709eeba2e95cf86f376a32c9e629df88/06-recursive-functions/take.hs | haskell | import Prelude hiding (take)
take :: Int -> [a] -> [a]
take 0 _ = []
take _ [] = []
take n (x:xs) = x : take (n - 1) xs
| |
947596348f2b330dd2a27c8b46cfc40cbc2b400efad694f8a4db2e8dec79fe42 | clojure-emacs/sayid | test_utils.clj | (ns com.billpiel.sayid.test-utils)
;; #L356
(defn swap-pair!
"Like swap! but returns a pair [old-val new-val]"
([a f]
(loop []
(let [old-val @a
new-val (f old-val)]
(if (compare-and-set! a old-val new-val)
[old-val new-val]
(recur)))))
([a f & args]
(swap-pair! a #(apply f % args))))
(defn make-mock-series-fn
[f s]
(let [a (atom s)]
(fn [& args]
(let [v (-> a
(swap-pair! subvec 1)
first
first)]
(apply f (into [v] args))))))
(let [[f & r] (range 1 100)] [f r])
(defn make-mock-series-lazy-fn
[f s]
(let [a (atom s)]
(fn [& args]
(let [v (-> a
(swap-pair! rest)
first
first)]
(apply f (into [v] args))))))
(def mock-now-fn #(make-mock-series-fn identity
(vec (range 0 1000))))
(def mock-gensym-fn (fn []
(make-mock-series-fn
(fn [id & [pre]]
(str (or pre "") id))
(vec (map str (range 10 1000))))))
(defn remove-iso-ctrl [s] (apply str (remove #(Character/isISOControl %) s)))
(def ansi-colors [:black :red :green :yellow :blue :magenta :cyan :white])
(defn kw->bg [kw] (->> kw name (str "bg-") keyword))
(defn ansi->kw
[a]
(try (let [a' (if (string? a)
(Integer/parseInt a)
a)]
(cond (= a' 0) :bold-off
(= a' 1) :bold
(<= 30 a' 39) (nth ansi-colors (mod a' 10))
(<= 40 a' 49) (->> (mod a' 10)
(nth ansi-colors)
kw->bg)))
(catch Exception ex nil)))
(defn replace-ansi*
[s coll]
(if-let [[both text code] (re-find (re-pattern (format "(?is)^(.*?)(%s\\[[\\d;]*m)" \u001B))
s)]
(do [s both (count both) text (count text) code (count code)]
(recur (subs s (count both))
(into coll [text code])))
(into coll [s])))
(defn tag-ansi
[s]
(if-let [[_ code] (re-find (re-pattern (format "%s\\[([\\d;]*)m" \u001B))
s)]
(let [codes (clojure.string/split code #";")]
(mapv ansi->kw codes))
s))
(defn replace-ansi
[s]
(let [v (replace-ansi* s [])]
(mapv tag-ansi v)))
(defn redact-file-fn
[& paths]
(fn [v]
(loop [v v
[f & r] paths]
(if (nil? f)
v
(recur (update-in v f (constantly "FILE"))
r)))))
| null | https://raw.githubusercontent.com/clojure-emacs/sayid/27f35778de9509067716a7bed14306787334a589/test/com/billpiel/sayid/test_utils.clj | clojure | #L356 | (ns com.billpiel.sayid.test-utils)
(defn swap-pair!
"Like swap! but returns a pair [old-val new-val]"
([a f]
(loop []
(let [old-val @a
new-val (f old-val)]
(if (compare-and-set! a old-val new-val)
[old-val new-val]
(recur)))))
([a f & args]
(swap-pair! a #(apply f % args))))
(defn make-mock-series-fn
[f s]
(let [a (atom s)]
(fn [& args]
(let [v (-> a
(swap-pair! subvec 1)
first
first)]
(apply f (into [v] args))))))
(let [[f & r] (range 1 100)] [f r])
(defn make-mock-series-lazy-fn
[f s]
(let [a (atom s)]
(fn [& args]
(let [v (-> a
(swap-pair! rest)
first
first)]
(apply f (into [v] args))))))
(def mock-now-fn #(make-mock-series-fn identity
(vec (range 0 1000))))
(def mock-gensym-fn (fn []
(make-mock-series-fn
(fn [id & [pre]]
(str (or pre "") id))
(vec (map str (range 10 1000))))))
(defn remove-iso-ctrl [s] (apply str (remove #(Character/isISOControl %) s)))
(def ansi-colors [:black :red :green :yellow :blue :magenta :cyan :white])
(defn kw->bg [kw] (->> kw name (str "bg-") keyword))
(defn ansi->kw
[a]
(try (let [a' (if (string? a)
(Integer/parseInt a)
a)]
(cond (= a' 0) :bold-off
(= a' 1) :bold
(<= 30 a' 39) (nth ansi-colors (mod a' 10))
(<= 40 a' 49) (->> (mod a' 10)
(nth ansi-colors)
kw->bg)))
(catch Exception ex nil)))
(defn replace-ansi*
[s coll]
(if-let [[both text code] (re-find (re-pattern (format "(?is)^(.*?)(%s\\[[\\d;]*m)" \u001B))
s)]
(do [s both (count both) text (count text) code (count code)]
(recur (subs s (count both))
(into coll [text code])))
(into coll [s])))
(defn tag-ansi
[s]
(if-let [[_ code] (re-find (re-pattern (format "%s\\[([\\d;]*)m" \u001B))
s)]
(let [codes (clojure.string/split code #";")]
(mapv ansi->kw codes))
s))
(defn replace-ansi
[s]
(let [v (replace-ansi* s [])]
(mapv tag-ansi v)))
(defn redact-file-fn
[& paths]
(fn [v]
(loop [v v
[f & r] paths]
(if (nil? f)
v
(recur (update-in v f (constantly "FILE"))
r)))))
|
6882818534addb433daf7380c8bf9c19c6c981de4a4b403f03f7b21ccfdffbec | squaresLab/footpatch | patch.ml | module L = Logging
type t =
(* change is a range of lines to delete, or a starting line and string list *)
{ change : Change.t
(* diff is only the textual difference, with indentation *)
; diff: string
(* the original absolute filename *)
; filename: string
(* the command used to indent files *)
; indent: Indent.t option
}
let exec_cmd ?(fail_if_fail = true) cmd =
match Sys.command cmd with
| 0 -> ()
| _ when fail_if_fail ->
let err = Format.sprintf "Error executing %s" cmd in
failwith err
| _ -> L.out "Error executing %s" cmd
let copy f1 f2 = Utils.copy_file f1 f2 |> ignore
let unified_patch_diff f1 f2 =
try
(* e.g., /tmp/diff123.diff *)
let dst_file = Filename.temp_file ~temp_dir:"/tmp" "udiff_" ".footpatch" in
let cmd_str = Format.sprintf "diff -u %s %s > %s" in
let cmd = cmd_str f1 f2 dst_file in
exec_cmd ~fail_if_fail:false cmd;
(* Fix up patch format wrt source and destination files *)
Footpatch_log.log @@ Format.sprintf "\t\t[p] Patch command 1: %S " cmd;
let cmd = Format.sprintf "sed -i '1p;2d' %s" dst_file in
Footpatch_log.log @@ Format.sprintf "\t\t[p] Patch command 2: %S " cmd;
exec_cmd ~fail_if_fail:true cmd;
exec_cmd ~fail_if_fail:true @@ Format.sprintf "echo >> %s" dst_file;
match Utils.read_file dst_file with
| Some res -> Some (String.concat "\n" res)
| None -> failwith @@ Format.sprintf "No file %s" dst_file
with
| Failure _ -> None
let do_indent ?indent filename =
match indent with
| Some i -> Indent.apply ~filename i
| None -> ()
(**
replace is for when we want to replace/write over the
line where we're inserting. E.g., when
if (foo) dothing();
becomes
if (foo) {
fix();
dothing();
}
XXX This can be replaced in future.
*)
let insert ?(replace=false) ~(this:string list) ~at ~content =
List.mapi
(fun i line ->
if i = at then
if replace then
this
else
this @ [line]
else
[line])
content
|> List.flatten
|> String.concat "\n"
let write_to_file file content =
try
let oc = open_out file in
Printf.fprintf oc "%s\n" content;
close_out oc;
Footpatch_log.log @@ Format.sprintf "Wrote to file %s" file;
Some ()
with
| _ ->
Footpatch_log.log @@ Format.sprintf "Could not write to file %s" file;
None
let insert_in_file ?replace pos lines file =
try
Footpatch_log.log @@ Format.sprintf "Reading from file %s@." file;
match Utils.read_file file with
| Some file_content ->
let result = insert ?replace ~this:lines ~at:pos ~content:file_content in
write_to_file file result
| None ->
Footpatch_log.log
@@ Format.sprintf
"Could not read from file %s when trying to insert content@."
file;
None
with | _ ->
Footpatch_log.log @@
Format.sprintf "Could not insert in file.";
None
let remove_in_file _ _ _ = failwith "Removal not implemented"
let apply_change ?replace change file =
let open Change in
match change with
| Insert (pos, lines) -> insert_in_file ?replace pos lines file
| Remove { start_line; end_line } -> remove_in_file start_line end_line file
let indent_maybe ?indent change file =
let open Change in
match change with
| Insert _ -> do_indent ?indent file
| Remove _ -> ()
let unified_diff_of_change ?replace filename change =
let dst_filename = "/tmp/"^(Filename.basename filename) in
let tmp_patched_diff = dst_filename^"_tmp_patched_diff" in
copy filename tmp_patched_diff;
match apply_change ?replace change tmp_patched_diff with
| Some _ -> unified_patch_diff filename tmp_patched_diff
| None -> None
let create ?indent ?replace ~filename change =
(* temporary copy of the original file which we can apply the patch to,
for when we want to dump tmp files in the directory of the file being patched *)
let dst_fname = ((Filename.basename filename)^"_") in
let tmp_original =
Filename.temp_file ~temp_dir:"/tmp"
(dst_fname^"_tmp_original_") ".footpatch"
in
let tmp_patched =
Filename.temp_file ~temp_dir:"/tmp"
(dst_fname^"tmp_patched_") ".footpatch"
in
copy filename tmp_original;
copy filename tmp_patched;
indent_maybe change tmp_patched; (* TODO: should use ?indent *)
indent_maybe change tmp_original;
begin
match unified_diff_of_change ?replace filename change with
| Some diff -> Some {change; diff; filename; indent}
| None -> None
end
let dump ~dir ~id patch =
let filename = Format.sprintf "%s/%s.patch" dir id in
let oc = open_out filename in
let fmt = Format.formatter_of_out_channel oc in
Format.fprintf fmt "%s" patch.diff;
close_out oc
let to_string (patch : t) = Format.sprintf "%s" patch.diff
let pp ppf patch = Format.fprintf ppf "%s" (to_string patch)
let pps () patch = to_string patch
| null | https://raw.githubusercontent.com/squaresLab/footpatch/8b79c1964d89b833179aed7ed4fde0638a435782/infer/src/footpatch/patch.ml | ocaml | change is a range of lines to delete, or a starting line and string list
diff is only the textual difference, with indentation
the original absolute filename
the command used to indent files
e.g., /tmp/diff123.diff
Fix up patch format wrt source and destination files
*
replace is for when we want to replace/write over the
line where we're inserting. E.g., when
if (foo) dothing();
becomes
if (foo) {
fix();
dothing();
}
XXX This can be replaced in future.
temporary copy of the original file which we can apply the patch to,
for when we want to dump tmp files in the directory of the file being patched
TODO: should use ?indent | module L = Logging
type t =
{ change : Change.t
; diff: string
; filename: string
; indent: Indent.t option
}
let exec_cmd ?(fail_if_fail = true) cmd =
match Sys.command cmd with
| 0 -> ()
| _ when fail_if_fail ->
let err = Format.sprintf "Error executing %s" cmd in
failwith err
| _ -> L.out "Error executing %s" cmd
let copy f1 f2 = Utils.copy_file f1 f2 |> ignore
let unified_patch_diff f1 f2 =
try
let dst_file = Filename.temp_file ~temp_dir:"/tmp" "udiff_" ".footpatch" in
let cmd_str = Format.sprintf "diff -u %s %s > %s" in
let cmd = cmd_str f1 f2 dst_file in
exec_cmd ~fail_if_fail:false cmd;
Footpatch_log.log @@ Format.sprintf "\t\t[p] Patch command 1: %S " cmd;
let cmd = Format.sprintf "sed -i '1p;2d' %s" dst_file in
Footpatch_log.log @@ Format.sprintf "\t\t[p] Patch command 2: %S " cmd;
exec_cmd ~fail_if_fail:true cmd;
exec_cmd ~fail_if_fail:true @@ Format.sprintf "echo >> %s" dst_file;
match Utils.read_file dst_file with
| Some res -> Some (String.concat "\n" res)
| None -> failwith @@ Format.sprintf "No file %s" dst_file
with
| Failure _ -> None
let do_indent ?indent filename =
match indent with
| Some i -> Indent.apply ~filename i
| None -> ()
let insert ?(replace=false) ~(this:string list) ~at ~content =
List.mapi
(fun i line ->
if i = at then
if replace then
this
else
this @ [line]
else
[line])
content
|> List.flatten
|> String.concat "\n"
let write_to_file file content =
try
let oc = open_out file in
Printf.fprintf oc "%s\n" content;
close_out oc;
Footpatch_log.log @@ Format.sprintf "Wrote to file %s" file;
Some ()
with
| _ ->
Footpatch_log.log @@ Format.sprintf "Could not write to file %s" file;
None
let insert_in_file ?replace pos lines file =
try
Footpatch_log.log @@ Format.sprintf "Reading from file %s@." file;
match Utils.read_file file with
| Some file_content ->
let result = insert ?replace ~this:lines ~at:pos ~content:file_content in
write_to_file file result
| None ->
Footpatch_log.log
@@ Format.sprintf
"Could not read from file %s when trying to insert content@."
file;
None
with | _ ->
Footpatch_log.log @@
Format.sprintf "Could not insert in file.";
None
let remove_in_file _ _ _ = failwith "Removal not implemented"
let apply_change ?replace change file =
let open Change in
match change with
| Insert (pos, lines) -> insert_in_file ?replace pos lines file
| Remove { start_line; end_line } -> remove_in_file start_line end_line file
let indent_maybe ?indent change file =
let open Change in
match change with
| Insert _ -> do_indent ?indent file
| Remove _ -> ()
let unified_diff_of_change ?replace filename change =
let dst_filename = "/tmp/"^(Filename.basename filename) in
let tmp_patched_diff = dst_filename^"_tmp_patched_diff" in
copy filename tmp_patched_diff;
match apply_change ?replace change tmp_patched_diff with
| Some _ -> unified_patch_diff filename tmp_patched_diff
| None -> None
let create ?indent ?replace ~filename change =
let dst_fname = ((Filename.basename filename)^"_") in
let tmp_original =
Filename.temp_file ~temp_dir:"/tmp"
(dst_fname^"_tmp_original_") ".footpatch"
in
let tmp_patched =
Filename.temp_file ~temp_dir:"/tmp"
(dst_fname^"tmp_patched_") ".footpatch"
in
copy filename tmp_original;
copy filename tmp_patched;
indent_maybe change tmp_original;
begin
match unified_diff_of_change ?replace filename change with
| Some diff -> Some {change; diff; filename; indent}
| None -> None
end
let dump ~dir ~id patch =
let filename = Format.sprintf "%s/%s.patch" dir id in
let oc = open_out filename in
let fmt = Format.formatter_of_out_channel oc in
Format.fprintf fmt "%s" patch.diff;
close_out oc
let to_string (patch : t) = Format.sprintf "%s" patch.diff
let pp ppf patch = Format.fprintf ppf "%s" (to_string patch)
let pps () patch = to_string patch
|
7d37eced024312b0a4a844438b10b4a36d01bfb2fcdc9ae970dee130d51684af | patperry/hs-linear-algebra | LinearAlgebra.hs | -----------------------------------------------------------------------------
-- |
Module : Numeric . LinearAlgebra
Copyright : Copyright ( c ) 2010 , < >
-- License : BSD3
Maintainer : < >
-- Stability : experimental
--
Linear algebra types and operations
--
module Numeric.LinearAlgebra (
-- * Vector types
Vector,
RVector,
STVector,
IOVector,
-- * Matrix types
Matrix,
RMatrix,
STMatrix,
IOMatrix,
-- * Packed matrix types
Packed,
RPacked,
STPacked,
IOPacked,
module Numeric.LinearAlgebra.Types,
) where
import Numeric.LinearAlgebra.Types
import Numeric.LinearAlgebra.Vector( Vector, RVector, STVector, IOVector )
import Numeric.LinearAlgebra.Matrix( Matrix, RMatrix, STMatrix, IOMatrix )
import Numeric.LinearAlgebra.Packed( Packed, RPacked, STPacked, IOPacked )
| null | https://raw.githubusercontent.com/patperry/hs-linear-algebra/887939175e03687b12eabe2fce5904b494242a1a/lib/Numeric/LinearAlgebra.hs | haskell | ---------------------------------------------------------------------------
|
License : BSD3
Stability : experimental
* Vector types
* Matrix types
* Packed matrix types | Module : Numeric . LinearAlgebra
Copyright : Copyright ( c ) 2010 , < >
Maintainer : < >
Linear algebra types and operations
module Numeric.LinearAlgebra (
Vector,
RVector,
STVector,
IOVector,
Matrix,
RMatrix,
STMatrix,
IOMatrix,
Packed,
RPacked,
STPacked,
IOPacked,
module Numeric.LinearAlgebra.Types,
) where
import Numeric.LinearAlgebra.Types
import Numeric.LinearAlgebra.Vector( Vector, RVector, STVector, IOVector )
import Numeric.LinearAlgebra.Matrix( Matrix, RMatrix, STMatrix, IOMatrix )
import Numeric.LinearAlgebra.Packed( Packed, RPacked, STPacked, IOPacked )
|
e8bb1636373a57a81e31a2571d33da6945af253c2e44f7aba4ad13b6a30ab719 | cnuernber/charred | json_test_suite_test.clj | (ns charred.json-test-suite-test
(:require [charred.api :refer [read-json]]
[clojure.test :refer :all]
[clojure.string :as str]))
(deftest i-number-double-huge-neg-exp-test
(is (= [0.0] (read-json "[123.456e-789]"))))
(deftest i-number-huge-exp-test
(is (= [##Inf]
(read-json "[0.4e00669999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999969999999006]"))))
(deftest i-number-neg-int-huge-exp-test
(is (= [##-Inf] (read-json "[-1e+9999]"))))
(deftest i-number-pos-double-huge-exp-test
(is (= [##Inf] (read-json "[1.5e+9999]"))))
(deftest i-number-real-neg-overflow-test
(is (= [##-Inf] (read-json "[-123123e100000]"))))
(deftest i-number-real-pos-overflow-test
(is (= [##Inf] (read-json "[123123e100000]"))))
(deftest i-number-real-underflow-test
(is (= [0.0] (read-json "[123e-10000000]"))))
(deftest i-number-too-big-neg-int-test
(is (= [-123123123123123123123123123123N]
(read-json "[-123123123123123123123123123123]"))))
(deftest i-number-too-big-pos-int-test
(is (= [100000000000000000000N] (read-json "[100000000000000000000]"))))
(deftest i-number-very-big-negative-int-test
(is (= [-237462374673276894279832749832423479823246327846N]
(read-json "[-237462374673276894279832749832423479823246327846]"))))
(deftest n-array-1-true-without-comma-test
(is (thrown? Exception (read-json "[1 true]"))))
(deftest n-array-colon-instead-of-comma-test
(is (thrown? Exception (read-json "[\"\": 1]"))))
(deftest n-array-comma-and-number-test
(is (thrown? Exception (read-json "[,1]"))))
(deftest n-array-double-comma-test
(is (thrown? Exception (read-json "[1,,2]"))))
(deftest n-array-double-extra-comma-test
(is (thrown? Exception (read-json "[\"x\",,]"))))
(deftest n-array-extra-comma-test
(is (thrown? Exception (read-json "[\"\",]"))))
(deftest n-array-incomplete-invalid-value-test
(is (thrown? Exception (read-json "[x"))))
(deftest n-array-incomplete-test
(is (thrown? Exception (read-json "[\"x\""))))
(deftest n-array-inner-array-no-comma-test
(is (thrown? Exception (read-json "[3[4]]"))))
(deftest n-array-items-separated-by-semicolon-test
(is (thrown? Exception (read-json "[1:2]"))))
(deftest n-array-just-comma-test
(is (thrown? Exception (read-json "[,]"))))
(deftest n-array-just-minus-test
(is (thrown? Exception (read-json "[-]"))))
(deftest n-array-missing-value-test
(is (thrown? Exception (read-json "[ , \"\"]"))))
(deftest n-array-newlines-unclosed-test
(is (thrown? Exception (read-json "[\"a\",\n4\n,1,"))))
(deftest n-array-number-and-comma-test
(is (thrown? Exception (read-json "[1,]"))))
(deftest n-array-number-and-several-commas-test
(is (thrown? Exception (read-json "[1,,]"))))
(deftest n-array-spaces-vertical-tab-formfeed-test
(is (thrown? Exception (read-json "[\"a\"\\f]"))))
(deftest n-array-star-inside-test
(is (thrown? Exception (read-json "[*]"))))
(deftest n-array-unclosed-test
(is (thrown? Exception (read-json "[\"\""))))
(deftest n-array-unclosed-trailing-comma-test
(is (thrown? Exception (read-json "[1,"))))
(deftest n-array-unclosed-with-new-lines-test
(is (thrown? Exception (read-json "[1,\n1\n,1"))))
(deftest n-array-unclosed-with-object-inside-test
(is (thrown? Exception (read-json "[{}"))))
(deftest n-number-++-test
(is (thrown? Exception (read-json "[++1234]"))))
(deftest n-number-+1-test
(is (thrown? Exception (read-json "[+1]"))))
(deftest n-number-+Inf-test
(is (thrown? Exception (read-json "[+Inf]"))))
(deftest n-number--01-test
(is (thrown? Exception (read-json "[-01]"))))
(deftest n-number--1.0.-test
(is (thrown? Exception (read-json "[-1.0.]"))))
(deftest n-number--2.-test
(is (thrown? Exception (read-json "[-2.]"))))
(deftest n-number--NaN-test
(is (thrown? Exception (read-json "[-NaN]"))))
(deftest n-number-.-1-test
(is (thrown? Exception (read-json "[.-1]"))))
(deftest n-number-.2e-3-test
(is (thrown? Exception (read-json "[.2e-3]"))))
(deftest n-number-0-capital-E+-test
(is (thrown? Exception (read-json "[0E+]"))))
(deftest n-number-0-capital-E-test
(is (thrown? Exception (read-json "[0E]"))))
(deftest n-number-0.1.2-test
(is (thrown? Exception (read-json "[0.1.2]"))))
(deftest n-number-0.3e+-test
(is (thrown? Exception (read-json "[0.3e+]"))))
(deftest n-number-0.3e-test
(is (thrown? Exception (read-json "[0.3e]"))))
(deftest n-number-0.e1-test
(is (thrown? Exception (read-json "[0.e1]"))))
(deftest n-number-0e+-test
(is (thrown? Exception (read-json "[0e+]"))))
(deftest n-number-0e-test
(is (thrown? Exception (read-json "[0e]"))))
(deftest n-number-1-000-test
(is (thrown? Exception (read-json "[1 000.0]"))))
(deftest n-number-1.0e+-test
(is (thrown? Exception (read-json "[1.0e+]"))))
(deftest n-number-1.0e--test
(is (thrown? Exception (read-json "[1.0e-]"))))
(deftest n-number-1.0e-test
(is (thrown? Exception (read-json "[1.0e]"))))
(deftest n-number-1eE2-test
(is (thrown? Exception (read-json "[1eE2]"))))
(deftest n-number-2.e+3-test
(is (thrown? Exception (read-json "[2.e+3]"))))
(deftest n-number-2.e-3-test
(is (thrown? Exception (read-json "[2.e-3]"))))
(deftest n-number-2.e3-test
(is (thrown? Exception (read-json "[2.e3]"))))
(deftest n-number-9.e+-test
(is (thrown? Exception (read-json "[9.e+]"))))
(deftest n-number-Inf-test
(is (thrown? Exception (read-json "[Inf]"))))
(deftest n-number-NaN-test
(is (thrown? Exception (read-json "[NaN]"))))
(deftest n-number-expression-test
(is (thrown? Exception (read-json "[1+2]"))))
(deftest n-number-hex-1-digit-test
(is (thrown? Exception (read-json "[0x1]"))))
(deftest n-number-hex-2-digits-test
(is (thrown? Exception (read-json "[0x42]"))))
(deftest n-number-infinity-test
(is (thrown? Exception (read-json "[Infinity]"))))
(deftest n-number-invalid+--test
(is (thrown? Exception (read-json "[0e+-1]"))))
(deftest n-number-invalid-negative-real-test
(is (thrown? Exception (read-json "[-123.123foo]"))))
(deftest n-number-minus-infinity-test
(is (thrown? Exception (read-json "[-Infinity]"))))
(deftest n-number-minus-sign-with-trailing-garbage-test
(is (thrown? Exception (read-json "[-foo]"))))
(deftest n-number-minus-space-1-test
(is (thrown? Exception (read-json "[- 1]"))))
(deftest n-number-neg-int-starting-with-zero-test
(is (thrown? Exception (read-json "[-012]"))))
(deftest n-number-neg-real-without-int-part-test
(is (thrown? Exception (read-json "[-.123]"))))
(deftest n-number-neg-with-garbage-at-end-test
(is (thrown? Exception (read-json "[-1x]"))))
(deftest n-number-real-garbage-after-e-test
(is (thrown? Exception (read-json "[1ea]"))))
(deftest n-number-real-without-fractional-part-test
(is (thrown? Exception (read-json "[1.]"))))
(deftest n-number-starting-with-dot-test
(is (thrown? Exception (read-json "[.123]"))))
(deftest n-number-with-alpha-char-test
(is (thrown? Exception (read-json "[1.8011670033376514H-308]"))))
(deftest n-number-with-alpha-test
(is (thrown? Exception (read-json "[1.2a-3]"))))
(deftest n-number-with-leading-zero-test
(is (thrown? Exception (read-json "[012]"))))
(deftest n-object-non-string-key-but-huge-number-instead-test
(is (thrown? Exception (read-json "{9999E9999:1}"))))
(deftest n-structure-array-with-unclosed-string-test
(is (thrown? Exception (read-json "[\"asd]"))))
(deftest n-structure-end-array-test
(is (thrown? Exception (read-json "]"))))
(deftest n-structure-number-with-trailing-garbage-test
(is (thrown? Exception (read-json "2@"))))
(deftest n-structure-open-array-apostrophe-test
(is (thrown? Exception (read-json "['"))))
(deftest n-structure-open-array-comma-test
(is (thrown? Exception (read-json "[,"))))
(deftest n-structure-open-array-open-object-test
(is (thrown? Exception (read-json "[{"))))
(deftest n-structure-open-array-open-string-test
(is (thrown? Exception (read-json "[\"a"))))
(deftest n-structure-open-array-string-test
(is (thrown? Exception (read-json "[\"a\""))))
(deftest n-structure-open-object-close-array-test
(is (thrown? Exception (read-json "{]"))))
(deftest n-structure-open-object-open-array-test
(is (thrown? Exception (read-json "{["))))
(deftest n-structure-unclosed-array-partial-null-test
(is (thrown? Exception (read-json "[ false, nul"))))
(deftest n-structure-unclosed-array-test
(is (thrown? Exception (read-json "[1"))))
(deftest n-structure-unclosed-array-unfinished-false-test
(is (thrown? Exception (read-json "[ true, fals"))))
(deftest n-structure-unclosed-array-unfinished-true-test
(is (thrown? Exception (read-json "[ false, tru"))))
(deftest y-array-arraysWithSpaces-test
(is (= [[]] (read-json "[[] ]"))))
(deftest y-array-empty-string-test
(is (= [""] (read-json "[\"\"]"))))
(deftest y-array-empty-test
(is (= [] (read-json "[]"))))
(deftest y-array-ending-with-newline-test
(is (= ["a"] (read-json "[\"a\"]"))))
(deftest y-array-false-test
(is (= [false] (read-json "[false]"))))
(deftest y-array-heterogeneous-test
(is (= [nil 1 "1" {}] (read-json "[null, 1, \"1\", {}]"))))
(deftest y-array-null-test
(is (= [nil] (read-json "[null]"))))
(deftest y-array-with-1-and-newline-test
(is (= [1] (read-json "[1\n]"))))
(deftest y-array-with-leading-space-test
(is (= [1] (read-json " [1]"))))
(deftest y-array-with-several-null-test
(is (= [1 nil nil nil 2] (read-json "[1,null,null,null,2]"))))
(deftest y-array-with-trailing-space-test
(is (= [2] (read-json "[2] "))))
(deftest y-number-0e+1-test
(is (= [0.0] (read-json "[0e+1]"))))
(deftest y-number-0e1-test
(is (= [0.0] (read-json "[0e1]"))))
(deftest y-number-after-space-test
(is (= [4] (read-json "[ 4]"))))
(deftest y-number-double-close-to-zero-test
(is (= [-1.0E-78]
(read-json "[-0.000000000000000000000000000000000000000000000000000000000000000000000000000001]"))))
(deftest y-number-int-with-exp-test
(is (= [200.0] (read-json "[20e1]"))))
(deftest y-number-minus-zero-test
(is (= [0] (read-json "[-0]"))))
(deftest y-number-negative-int-test
(is (= [-123] (read-json "[-123]"))))
(deftest y-number-negative-one-test
(is (= [-1] (read-json "[-1]"))))
(deftest y-number-negative-zero-test
(is (= [0] (read-json "[-0]"))))
(deftest y-number-real-capital-e-neg-exp-test
(is (= [0.01] (read-json "[1E-2]"))))
(deftest y-number-real-capital-e-pos-exp-test
(is (= [100.0] (read-json "[1E+2]"))))
(deftest y-number-real-capital-e-test
(is (= [1.0E22] (read-json "[1E22]"))))
(deftest y-number-real-exponent-test
(is (= [1.23E47] (read-json "[123e45]"))))
(deftest y-number-real-fraction-exponent-test
(is (= [1.23456E80] (read-json "[123.456e78]"))))
(deftest y-number-real-neg-exp-test
(is (= [0.01] (read-json "[1e-2]"))))
(deftest y-number-real-pos-exponent-test
(is (= [100.0] (read-json "[1e+2]"))))
(deftest y-number-simple-int-test
(is (= [123] (read-json "[123]"))))
(deftest y-number-simple-real-test
(is (= [123.456789] (read-json "[123.456789]"))))
(deftest y-number-test
(is (= [1.23E67] (read-json "[123e65]"))))
(deftest y-object-extreme-numbers-test
(is (= {"min" -1.0E28, "max" 1.0E28}
(read-json "{\"min\": -1.0e+28, \"max\": 1.0e+28}"))))
(deftest y-string-in-array-test
(is (= ["asd"] (read-json "[\"asd\"]"))))
(deftest y-string-in-array-with-leading-space-test
(is (= ["asd"] (read-json "[ \"asd\"]"))))
(deftest y-structure-true-in-array-test
(is (= [true] (read-json "[true]"))))
(deftest y-structure-whitespace-array-test
(is (= [] (read-json " [] "))))
| null | https://raw.githubusercontent.com/cnuernber/charred/836e6d009b94821f90717ae64350c7f28a547a03/test/charred/json_test_suite_test.clj | clojure | (ns charred.json-test-suite-test
(:require [charred.api :refer [read-json]]
[clojure.test :refer :all]
[clojure.string :as str]))
(deftest i-number-double-huge-neg-exp-test
(is (= [0.0] (read-json "[123.456e-789]"))))
(deftest i-number-huge-exp-test
(is (= [##Inf]
(read-json "[0.4e00669999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999969999999006]"))))
(deftest i-number-neg-int-huge-exp-test
(is (= [##-Inf] (read-json "[-1e+9999]"))))
(deftest i-number-pos-double-huge-exp-test
(is (= [##Inf] (read-json "[1.5e+9999]"))))
(deftest i-number-real-neg-overflow-test
(is (= [##-Inf] (read-json "[-123123e100000]"))))
(deftest i-number-real-pos-overflow-test
(is (= [##Inf] (read-json "[123123e100000]"))))
(deftest i-number-real-underflow-test
(is (= [0.0] (read-json "[123e-10000000]"))))
(deftest i-number-too-big-neg-int-test
(is (= [-123123123123123123123123123123N]
(read-json "[-123123123123123123123123123123]"))))
(deftest i-number-too-big-pos-int-test
(is (= [100000000000000000000N] (read-json "[100000000000000000000]"))))
(deftest i-number-very-big-negative-int-test
(is (= [-237462374673276894279832749832423479823246327846N]
(read-json "[-237462374673276894279832749832423479823246327846]"))))
(deftest n-array-1-true-without-comma-test
(is (thrown? Exception (read-json "[1 true]"))))
(deftest n-array-colon-instead-of-comma-test
(is (thrown? Exception (read-json "[\"\": 1]"))))
(deftest n-array-comma-and-number-test
(is (thrown? Exception (read-json "[,1]"))))
(deftest n-array-double-comma-test
(is (thrown? Exception (read-json "[1,,2]"))))
(deftest n-array-double-extra-comma-test
(is (thrown? Exception (read-json "[\"x\",,]"))))
(deftest n-array-extra-comma-test
(is (thrown? Exception (read-json "[\"\",]"))))
(deftest n-array-incomplete-invalid-value-test
(is (thrown? Exception (read-json "[x"))))
(deftest n-array-incomplete-test
(is (thrown? Exception (read-json "[\"x\""))))
(deftest n-array-inner-array-no-comma-test
(is (thrown? Exception (read-json "[3[4]]"))))
(deftest n-array-items-separated-by-semicolon-test
(is (thrown? Exception (read-json "[1:2]"))))
(deftest n-array-just-comma-test
(is (thrown? Exception (read-json "[,]"))))
(deftest n-array-just-minus-test
(is (thrown? Exception (read-json "[-]"))))
(deftest n-array-missing-value-test
(is (thrown? Exception (read-json "[ , \"\"]"))))
(deftest n-array-newlines-unclosed-test
(is (thrown? Exception (read-json "[\"a\",\n4\n,1,"))))
(deftest n-array-number-and-comma-test
(is (thrown? Exception (read-json "[1,]"))))
(deftest n-array-number-and-several-commas-test
(is (thrown? Exception (read-json "[1,,]"))))
(deftest n-array-spaces-vertical-tab-formfeed-test
(is (thrown? Exception (read-json "[\"a\"\\f]"))))
(deftest n-array-star-inside-test
(is (thrown? Exception (read-json "[*]"))))
(deftest n-array-unclosed-test
(is (thrown? Exception (read-json "[\"\""))))
(deftest n-array-unclosed-trailing-comma-test
(is (thrown? Exception (read-json "[1,"))))
(deftest n-array-unclosed-with-new-lines-test
(is (thrown? Exception (read-json "[1,\n1\n,1"))))
(deftest n-array-unclosed-with-object-inside-test
(is (thrown? Exception (read-json "[{}"))))
(deftest n-number-++-test
(is (thrown? Exception (read-json "[++1234]"))))
(deftest n-number-+1-test
(is (thrown? Exception (read-json "[+1]"))))
(deftest n-number-+Inf-test
(is (thrown? Exception (read-json "[+Inf]"))))
(deftest n-number--01-test
(is (thrown? Exception (read-json "[-01]"))))
(deftest n-number--1.0.-test
(is (thrown? Exception (read-json "[-1.0.]"))))
(deftest n-number--2.-test
(is (thrown? Exception (read-json "[-2.]"))))
(deftest n-number--NaN-test
(is (thrown? Exception (read-json "[-NaN]"))))
(deftest n-number-.-1-test
(is (thrown? Exception (read-json "[.-1]"))))
(deftest n-number-.2e-3-test
(is (thrown? Exception (read-json "[.2e-3]"))))
(deftest n-number-0-capital-E+-test
(is (thrown? Exception (read-json "[0E+]"))))
(deftest n-number-0-capital-E-test
(is (thrown? Exception (read-json "[0E]"))))
(deftest n-number-0.1.2-test
(is (thrown? Exception (read-json "[0.1.2]"))))
(deftest n-number-0.3e+-test
(is (thrown? Exception (read-json "[0.3e+]"))))
(deftest n-number-0.3e-test
(is (thrown? Exception (read-json "[0.3e]"))))
(deftest n-number-0.e1-test
(is (thrown? Exception (read-json "[0.e1]"))))
(deftest n-number-0e+-test
(is (thrown? Exception (read-json "[0e+]"))))
(deftest n-number-0e-test
(is (thrown? Exception (read-json "[0e]"))))
(deftest n-number-1-000-test
(is (thrown? Exception (read-json "[1 000.0]"))))
(deftest n-number-1.0e+-test
(is (thrown? Exception (read-json "[1.0e+]"))))
(deftest n-number-1.0e--test
(is (thrown? Exception (read-json "[1.0e-]"))))
(deftest n-number-1.0e-test
(is (thrown? Exception (read-json "[1.0e]"))))
(deftest n-number-1eE2-test
(is (thrown? Exception (read-json "[1eE2]"))))
(deftest n-number-2.e+3-test
(is (thrown? Exception (read-json "[2.e+3]"))))
(deftest n-number-2.e-3-test
(is (thrown? Exception (read-json "[2.e-3]"))))
(deftest n-number-2.e3-test
(is (thrown? Exception (read-json "[2.e3]"))))
(deftest n-number-9.e+-test
(is (thrown? Exception (read-json "[9.e+]"))))
(deftest n-number-Inf-test
(is (thrown? Exception (read-json "[Inf]"))))
(deftest n-number-NaN-test
(is (thrown? Exception (read-json "[NaN]"))))
(deftest n-number-expression-test
(is (thrown? Exception (read-json "[1+2]"))))
(deftest n-number-hex-1-digit-test
(is (thrown? Exception (read-json "[0x1]"))))
(deftest n-number-hex-2-digits-test
(is (thrown? Exception (read-json "[0x42]"))))
(deftest n-number-infinity-test
(is (thrown? Exception (read-json "[Infinity]"))))
(deftest n-number-invalid+--test
(is (thrown? Exception (read-json "[0e+-1]"))))
(deftest n-number-invalid-negative-real-test
(is (thrown? Exception (read-json "[-123.123foo]"))))
(deftest n-number-minus-infinity-test
(is (thrown? Exception (read-json "[-Infinity]"))))
(deftest n-number-minus-sign-with-trailing-garbage-test
(is (thrown? Exception (read-json "[-foo]"))))
(deftest n-number-minus-space-1-test
(is (thrown? Exception (read-json "[- 1]"))))
(deftest n-number-neg-int-starting-with-zero-test
(is (thrown? Exception (read-json "[-012]"))))
(deftest n-number-neg-real-without-int-part-test
(is (thrown? Exception (read-json "[-.123]"))))
(deftest n-number-neg-with-garbage-at-end-test
(is (thrown? Exception (read-json "[-1x]"))))
(deftest n-number-real-garbage-after-e-test
(is (thrown? Exception (read-json "[1ea]"))))
(deftest n-number-real-without-fractional-part-test
(is (thrown? Exception (read-json "[1.]"))))
(deftest n-number-starting-with-dot-test
(is (thrown? Exception (read-json "[.123]"))))
(deftest n-number-with-alpha-char-test
(is (thrown? Exception (read-json "[1.8011670033376514H-308]"))))
(deftest n-number-with-alpha-test
(is (thrown? Exception (read-json "[1.2a-3]"))))
(deftest n-number-with-leading-zero-test
(is (thrown? Exception (read-json "[012]"))))
(deftest n-object-non-string-key-but-huge-number-instead-test
(is (thrown? Exception (read-json "{9999E9999:1}"))))
(deftest n-structure-array-with-unclosed-string-test
(is (thrown? Exception (read-json "[\"asd]"))))
(deftest n-structure-end-array-test
(is (thrown? Exception (read-json "]"))))
(deftest n-structure-number-with-trailing-garbage-test
(is (thrown? Exception (read-json "2@"))))
(deftest n-structure-open-array-apostrophe-test
(is (thrown? Exception (read-json "['"))))
(deftest n-structure-open-array-comma-test
(is (thrown? Exception (read-json "[,"))))
(deftest n-structure-open-array-open-object-test
(is (thrown? Exception (read-json "[{"))))
(deftest n-structure-open-array-open-string-test
(is (thrown? Exception (read-json "[\"a"))))
(deftest n-structure-open-array-string-test
(is (thrown? Exception (read-json "[\"a\""))))
(deftest n-structure-open-object-close-array-test
(is (thrown? Exception (read-json "{]"))))
(deftest n-structure-open-object-open-array-test
(is (thrown? Exception (read-json "{["))))
(deftest n-structure-unclosed-array-partial-null-test
(is (thrown? Exception (read-json "[ false, nul"))))
(deftest n-structure-unclosed-array-test
(is (thrown? Exception (read-json "[1"))))
(deftest n-structure-unclosed-array-unfinished-false-test
(is (thrown? Exception (read-json "[ true, fals"))))
(deftest n-structure-unclosed-array-unfinished-true-test
(is (thrown? Exception (read-json "[ false, tru"))))
(deftest y-array-arraysWithSpaces-test
(is (= [[]] (read-json "[[] ]"))))
(deftest y-array-empty-string-test
(is (= [""] (read-json "[\"\"]"))))
(deftest y-array-empty-test
(is (= [] (read-json "[]"))))
(deftest y-array-ending-with-newline-test
(is (= ["a"] (read-json "[\"a\"]"))))
(deftest y-array-false-test
(is (= [false] (read-json "[false]"))))
(deftest y-array-heterogeneous-test
(is (= [nil 1 "1" {}] (read-json "[null, 1, \"1\", {}]"))))
(deftest y-array-null-test
(is (= [nil] (read-json "[null]"))))
(deftest y-array-with-1-and-newline-test
(is (= [1] (read-json "[1\n]"))))
(deftest y-array-with-leading-space-test
(is (= [1] (read-json " [1]"))))
(deftest y-array-with-several-null-test
(is (= [1 nil nil nil 2] (read-json "[1,null,null,null,2]"))))
(deftest y-array-with-trailing-space-test
(is (= [2] (read-json "[2] "))))
(deftest y-number-0e+1-test
(is (= [0.0] (read-json "[0e+1]"))))
(deftest y-number-0e1-test
(is (= [0.0] (read-json "[0e1]"))))
(deftest y-number-after-space-test
(is (= [4] (read-json "[ 4]"))))
(deftest y-number-double-close-to-zero-test
(is (= [-1.0E-78]
(read-json "[-0.000000000000000000000000000000000000000000000000000000000000000000000000000001]"))))
(deftest y-number-int-with-exp-test
(is (= [200.0] (read-json "[20e1]"))))
(deftest y-number-minus-zero-test
(is (= [0] (read-json "[-0]"))))
(deftest y-number-negative-int-test
(is (= [-123] (read-json "[-123]"))))
(deftest y-number-negative-one-test
(is (= [-1] (read-json "[-1]"))))
(deftest y-number-negative-zero-test
(is (= [0] (read-json "[-0]"))))
(deftest y-number-real-capital-e-neg-exp-test
(is (= [0.01] (read-json "[1E-2]"))))
(deftest y-number-real-capital-e-pos-exp-test
(is (= [100.0] (read-json "[1E+2]"))))
(deftest y-number-real-capital-e-test
(is (= [1.0E22] (read-json "[1E22]"))))
(deftest y-number-real-exponent-test
(is (= [1.23E47] (read-json "[123e45]"))))
(deftest y-number-real-fraction-exponent-test
(is (= [1.23456E80] (read-json "[123.456e78]"))))
(deftest y-number-real-neg-exp-test
(is (= [0.01] (read-json "[1e-2]"))))
(deftest y-number-real-pos-exponent-test
(is (= [100.0] (read-json "[1e+2]"))))
(deftest y-number-simple-int-test
(is (= [123] (read-json "[123]"))))
(deftest y-number-simple-real-test
(is (= [123.456789] (read-json "[123.456789]"))))
(deftest y-number-test
(is (= [1.23E67] (read-json "[123e65]"))))
(deftest y-object-extreme-numbers-test
(is (= {"min" -1.0E28, "max" 1.0E28}
(read-json "{\"min\": -1.0e+28, \"max\": 1.0e+28}"))))
(deftest y-string-in-array-test
(is (= ["asd"] (read-json "[\"asd\"]"))))
(deftest y-string-in-array-with-leading-space-test
(is (= ["asd"] (read-json "[ \"asd\"]"))))
(deftest y-structure-true-in-array-test
(is (= [true] (read-json "[true]"))))
(deftest y-structure-whitespace-array-test
(is (= [] (read-json " [] "))))
| |
b1af017441cbbdb2f68d424eb64b5f50ff7e492720c63cd79af1e9c8f25f17a6 | okuoku/nausicaa | test-net-ipv4-address.sps | -*- coding : utf-8 -*-
;;;
Part of : / Scheme
Contents : tests for IPv4 address object
Date : Fri Jun 11 , 2010
;;;
;;;Abstract
;;;
;;;
;;;
Copyright ( c ) 2010 , 2011 < >
;;;
;;;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 </>.
;;;
#!r6rs
(import (nausicaa)
(nausicaa net ipv4-addresses)
(prefix (nausicaa silex lexer) lex.)
(nausicaa parser-tools)
(nausicaa net helpers ipv4-address-lexer)
(prefix (nausicaa net helpers ipv4-address-parser) parser.)
(nausicaa checks))
(check-set-mode! 'report-failed)
(display "*** testing net IPv4 address\n")
(parametrise ((check-test-name 'lexing))
(define (tokenise-address string)
(let* ((IS (lex.make-IS (lex.string: string) (lex.counters: 'all)))
(lexer (lex.make-lexer ipv4-address-lexer-table IS))
(out '()))
(define (push-token! (T <lexical-token>))
(set-cons! out (cons T.category T.value)))
(do (((token <lexical-token>) (lexer) (lexer)))
(token.special?
(push-token! token)
(reverse out))
;;;(write token)(newline)
(push-token! token))
))
(define eoi `(*eoi* . ,(eof-object)))
;;; --------------------------------------------------------------------
(check
(tokenise-address "1.2.3.4")
=> `((NUMBER . 1)
(DOT . #\.)
(NUMBER . 2)
(DOT . #\.)
(NUMBER . 3)
(DOT . #\.)
(NUMBER . 4)
,eoi))
(check
(tokenise-address "1.Zciao")
=> '((NUMBER . 1)
(DOT . #\.)
(*lexer-error* . "Zciao")))
;;; --------------------------------------------------------------------
(check
(tokenise-address "1")
=> `((NUMBER . 1)
,eoi))
(check
(tokenise-address "10")
=> `((NUMBER . 10)
,eoi))
(check
(tokenise-address "100")
=> `((NUMBER . 100)
,eoi))
(check
(tokenise-address "190")
=> `((NUMBER . 190)
,eoi))
(check
(tokenise-address "210")
=> `((NUMBER . 210)
,eoi))
(check
(tokenise-address "250")
=> `((NUMBER . 250)
,eoi))
(check
(tokenise-address "255")
=> `((NUMBER . 255)
,eoi))
(check
(tokenise-address "256")
=> `((NUMBER . 25)
(NUMBER . 6)
,eoi))
(check
(tokenise-address "500")
=> `((NUMBER . 50)
(NUMBER . 0)
,eoi))
;;; --------------------------------------------------------------------
;; (check
( tokenise - address " 0xa " )
= > ` ( ( NUMBER . 10 )
;; ,eoi))
;; (check
( tokenise - address " 0xFE " )
= > ` ( ( NUMBER . 254 )
;; ,eoi))
;;; --------------------------------------------------------------------
;; (check
;; (tokenise-address "02")
= > ` ( ( NUMBER . 2 )
;; ,eoi))
;; (check
( tokenise - address " 012 " )
= > ` ( ( NUMBER . 10 )
;; ,eoi))
;; (check
;; (tokenise-address "0123")
= > ` ( ( NUMBER . 83 )
;; ,eoi))
#t)
(parametrise ((check-test-name 'parsing))
(define-condition &parser-error
(parent &assertion))
(define (make-ipv4-address-parser-error-handler who string)
(lambda (message (token <lexical-token>))
(raise
(condition
(make-parser-error-condition)
(make-who-condition who)
(make-message-condition
(let (((pos <source-location>) token.location))
(string-append "invalid Ipv4 address input at column "
pos.column-string ": " message)))
(make-irritants-condition (list string token.value))))))
(define (parse-address string)
(let* ((IS (lex.make-IS (lex.string: string) (lex.counters: 'all)))
(lexer (lex.make-lexer ipv4-address-lexer-table IS))
(parser (parser.make-ipv4-address-parser)))
(parser lexer (make-ipv4-address-parser-error-handler 'parse-address string))))
;;; --------------------------------------------------------------------
;;; plain addresses
(check
(parse-address "1.2.3.4")
=> '(1 2 3 4))
;; (check
;; (parse-address "0x1.0x2.0x3.0x4")
= > ' ( 1 2 3 4 ) )
;; (check
( parse - address " 01.02.03.04 " )
= > ' ( 1 2 3 4 ) )
(check
(parse-address "192.168.99.1")
=> '(192 168 99 1))
;;; --------------------------------------------------------------------
;;; prefix
(check
(parse-address "1.2.3.4/8")
=> '(1 2 3 4 (8)))
;; (check
( parse - address " 0x1.0x2.0x3.0x4/8 " )
;; => '(1 2 3 4 8))
;; (check
( parse - address " 01.02.03.04/8 " )
;; => '(1 2 3 4 8))
(check
(parse-address "192.168.99.1/8")
=> '(192 168 99 1 (8)))
;;; --------------------------------------------------------------------
;;; errors
(check
(guard (E ((parser-error-condition? E)
( display ( condition - message E))(newline )
#t)
(else #f))
(parse-address "1.2.3.4.5"))
=> #t)
(check
(guard (E ((parser-error-condition? E)
( display ( condition - message E))(newline )
#t)
(else #f))
(parse-address "1,"))
=> #t)
(check
(guard (E ((parser-error-condition? E)
( display ( condition - message E))(newline )
#t)
(else #f))
(parse-address "1..2..3"))
=> #t)
(check
(guard (E ((parser-error-condition? E)
( display ( condition - message E))(newline )
#t)
(else #f))
(parse-address "1..2.."))
=> #t)
(check
(guard (E ((parser-error-condition? E)
( display ( condition - message E))(newline )
#t)
(else #f))
(parse-address "..2..3"))
=> #t)
#t)
(parametrise ((check-test-name 'class-address))
(check
(let (((o <ipv4-address>)
(make* <ipv4-address> (ipv4-address-parse "1.2.3.4"))))
(list o.third o.second o.first o.zeroth))
=> '(1 2 3 4))
;; (check
;; (let (((o <ipv4-address>)
;; (make* <ipv4-address> (ipv4-address-parse "0x1.0x2.0x3.0x4"))))
o.bignum )
;; => #x01020304)
(check
(let (((o <ipv4-address>)
(make* <ipv4-address> (ipv4-address-parse "1.2.3.4"))))
o.string)
=> "1.2.3.4")
;;; --------------------------------------------------------------------
(check
(let (((o <ipv4-address>) (make* <ipv4-address> (ipv4-address-parse "10.0.0.1"))))
o.private?)
=> #t)
(check
(let (((o <ipv4-address>) (make* <ipv4-address> (ipv4-address-parse "172.16.0.1"))))
o.private?)
=> #t)
(check
(let (((o <ipv4-address>) (make* <ipv4-address> (ipv4-address-parse "172.20.0.1"))))
o.private?)
=> #t)
(check
(let (((o <ipv4-address>) (make* <ipv4-address> (ipv4-address-parse "192.168.0.1"))))
o.private?)
=> #t)
(check
(let (((o <ipv4-address>) (make* <ipv4-address> (ipv4-address-parse "123.0.0.1"))))
o.private?)
=> #f)
;;; --------------------------------------------------------------------
(check
(let (((o <ipv4-address>) (make* <ipv4-address> (ipv4-address-parse "127.0.0.1"))))
o.loopback?)
=> #t)
(check
(let (((o <ipv4-address>) (make* <ipv4-address> (ipv4-address-parse "100.0.0.1"))))
o.loopback?)
=> #f)
;;; --------------------------------------------------------------------
(check
(let (((o <ipv4-address>) (make* <ipv4-address> (ipv4-address-parse "127.0.0.1"))))
o.localhost?)
=> #t)
(check
(let (((o <ipv4-address>) (make* <ipv4-address> (ipv4-address-parse "100.0.0.1"))))
o.localhost?)
=> #f)
;;; --------------------------------------------------------------------
(check
(let (((o <ipv4-address>) (make* <ipv4-address> (ipv4-address-parse "169.254.0.1"))))
o.link-local?)
=> #t)
(check
(let (((o <ipv4-address>) (make* <ipv4-address> (ipv4-address-parse "100.0.0.1"))))
o.link-local?)
=> #f)
;;; --------------------------------------------------------------------
(check
(let (((o <ipv4-address>) (make* <ipv4-address> (ipv4-address-parse "192.0.0.1"))))
o.reserved?)
=> #t)
(check
(let (((o <ipv4-address>) (make* <ipv4-address> (ipv4-address-parse "240.0.0.1"))))
o.reserved?)
=> #t)
(check
(let (((o <ipv4-address>) (make* <ipv4-address> (ipv4-address-parse "100.0.0.1"))))
o.reserved?)
=> #f)
;;; --------------------------------------------------------------------
(check
(let (((o <ipv4-address>) (make* <ipv4-address> (ipv4-address-parse "192.0.2.1"))))
o.test-net-1?)
=> #t)
(check
(let (((o <ipv4-address>) (make* <ipv4-address> (ipv4-address-parse "100.0.0.1"))))
o.test-net-1?)
=> #f)
;;; --------------------------------------------------------------------
(check
(let (((o <ipv4-address>) (make* <ipv4-address> (ipv4-address-parse "192.88.99.1"))))
o.six-to-four-relay-anycast?)
=> #t)
(check
(let (((o <ipv4-address>) (make* <ipv4-address> (ipv4-address-parse "100.0.0.1"))))
o.six-to-four-relay-anycast?)
=> #f)
;;; --------------------------------------------------------------------
(check
(let (((o <ipv4-address>) (make* <ipv4-address> (ipv4-address-parse "198.18.0.1"))))
o.benchmark-tests?)
=> #t)
(check
(let (((o <ipv4-address>) (make* <ipv4-address> (ipv4-address-parse "100.0.0.1"))))
o.benchmark-tests?)
=> #f)
;;; --------------------------------------------------------------------
(check
(let (((o <ipv4-address>) (make* <ipv4-address> (ipv4-address-parse "198.51.100.1"))))
o.test-net-2?)
=> #t)
(check
(let (((o <ipv4-address>) (make* <ipv4-address> (ipv4-address-parse "100.0.0.1"))))
o.test-net-2?)
=> #f)
;;; --------------------------------------------------------------------
(check
(let (((o <ipv4-address>) (make* <ipv4-address> (ipv4-address-parse "203.0.113.1"))))
o.test-net-3?)
=> #t)
(check
(let (((o <ipv4-address>) (make* <ipv4-address> (ipv4-address-parse "100.0.0.1"))))
o.test-net-3?)
=> #f)
;;; --------------------------------------------------------------------
(check
(let (((o <ipv4-address>) (make* <ipv4-address> (ipv4-address-parse "224.0.113.1"))))
o.multicast?)
=> #t)
(check
(let (((o <ipv4-address>) (make* <ipv4-address> (ipv4-address-parse "100.0.0.1"))))
o.multicast?)
=> #f)
;;; --------------------------------------------------------------------
(check
(let (((o <ipv4-address>) (make* <ipv4-address> (ipv4-address-parse "255.255.255.255"))))
o.limited-broadcast?)
=> #t)
(check
(let (((o <ipv4-address>) (make* <ipv4-address> (ipv4-address-parse "100.0.0.1"))))
o.limited-broadcast?)
=> #f)
#t)
(parametrise ((check-test-name 'class-prefix))
(check
(let (((o <ipv4-address-prefix>)
(receive (addr len)
(ipv4-address-prefix-parse "1.2.3.4/10")
(make* <ipv4-address-prefix> addr len))))
(list o.third o.second o.first o.zeroth o.prefix-length))
=> '(1 2 3 4 10))
(check
(let (((o <ipv4-address-prefix>)
(receive (addr len)
(ipv4-address-prefix-parse "1.2.3.4/8")
(make* <ipv4-address-prefix> addr len))))
o.string)
=> "1.2.3.4/8")
#t)
;;;; done
(check-report)
;;; end of file
| null | https://raw.githubusercontent.com/okuoku/nausicaa/50e7b4d4141ad4d81051588608677223fe9fb715/scheme/tests/test-net-ipv4-address.sps | scheme |
Abstract
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
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
along with this program. If not, see </>.
(write token)(newline)
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
(check
,eoi))
(check
,eoi))
--------------------------------------------------------------------
(check
(tokenise-address "02")
,eoi))
(check
,eoi))
(check
(tokenise-address "0123")
,eoi))
--------------------------------------------------------------------
plain addresses
(check
(parse-address "0x1.0x2.0x3.0x4")
(check
--------------------------------------------------------------------
prefix
(check
=> '(1 2 3 4 8))
(check
=> '(1 2 3 4 8))
--------------------------------------------------------------------
errors
(check
(let (((o <ipv4-address>)
(make* <ipv4-address> (ipv4-address-parse "0x1.0x2.0x3.0x4"))))
=> #x01020304)
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
done
end of file | -*- coding : utf-8 -*-
Part of : / Scheme
Contents : tests for IPv4 address object
Date : Fri Jun 11 , 2010
Copyright ( c ) 2010 , 2011 < >
the Free Software Foundation , either version 3 of the License , or ( at
General Public License for more details .
You should have received a copy of the GNU General Public License
#!r6rs
(import (nausicaa)
(nausicaa net ipv4-addresses)
(prefix (nausicaa silex lexer) lex.)
(nausicaa parser-tools)
(nausicaa net helpers ipv4-address-lexer)
(prefix (nausicaa net helpers ipv4-address-parser) parser.)
(nausicaa checks))
(check-set-mode! 'report-failed)
(display "*** testing net IPv4 address\n")
(parametrise ((check-test-name 'lexing))
(define (tokenise-address string)
(let* ((IS (lex.make-IS (lex.string: string) (lex.counters: 'all)))
(lexer (lex.make-lexer ipv4-address-lexer-table IS))
(out '()))
(define (push-token! (T <lexical-token>))
(set-cons! out (cons T.category T.value)))
(do (((token <lexical-token>) (lexer) (lexer)))
(token.special?
(push-token! token)
(reverse out))
(push-token! token))
))
(define eoi `(*eoi* . ,(eof-object)))
(check
(tokenise-address "1.2.3.4")
=> `((NUMBER . 1)
(DOT . #\.)
(NUMBER . 2)
(DOT . #\.)
(NUMBER . 3)
(DOT . #\.)
(NUMBER . 4)
,eoi))
(check
(tokenise-address "1.Zciao")
=> '((NUMBER . 1)
(DOT . #\.)
(*lexer-error* . "Zciao")))
(check
(tokenise-address "1")
=> `((NUMBER . 1)
,eoi))
(check
(tokenise-address "10")
=> `((NUMBER . 10)
,eoi))
(check
(tokenise-address "100")
=> `((NUMBER . 100)
,eoi))
(check
(tokenise-address "190")
=> `((NUMBER . 190)
,eoi))
(check
(tokenise-address "210")
=> `((NUMBER . 210)
,eoi))
(check
(tokenise-address "250")
=> `((NUMBER . 250)
,eoi))
(check
(tokenise-address "255")
=> `((NUMBER . 255)
,eoi))
(check
(tokenise-address "256")
=> `((NUMBER . 25)
(NUMBER . 6)
,eoi))
(check
(tokenise-address "500")
=> `((NUMBER . 50)
(NUMBER . 0)
,eoi))
( tokenise - address " 0xa " )
= > ` ( ( NUMBER . 10 )
( tokenise - address " 0xFE " )
= > ` ( ( NUMBER . 254 )
= > ` ( ( NUMBER . 2 )
( tokenise - address " 012 " )
= > ` ( ( NUMBER . 10 )
= > ` ( ( NUMBER . 83 )
#t)
(parametrise ((check-test-name 'parsing))
(define-condition &parser-error
(parent &assertion))
(define (make-ipv4-address-parser-error-handler who string)
(lambda (message (token <lexical-token>))
(raise
(condition
(make-parser-error-condition)
(make-who-condition who)
(make-message-condition
(let (((pos <source-location>) token.location))
(string-append "invalid Ipv4 address input at column "
pos.column-string ": " message)))
(make-irritants-condition (list string token.value))))))
(define (parse-address string)
(let* ((IS (lex.make-IS (lex.string: string) (lex.counters: 'all)))
(lexer (lex.make-lexer ipv4-address-lexer-table IS))
(parser (parser.make-ipv4-address-parser)))
(parser lexer (make-ipv4-address-parser-error-handler 'parse-address string))))
(check
(parse-address "1.2.3.4")
=> '(1 2 3 4))
= > ' ( 1 2 3 4 ) )
( parse - address " 01.02.03.04 " )
= > ' ( 1 2 3 4 ) )
(check
(parse-address "192.168.99.1")
=> '(192 168 99 1))
(check
(parse-address "1.2.3.4/8")
=> '(1 2 3 4 (8)))
( parse - address " 0x1.0x2.0x3.0x4/8 " )
( parse - address " 01.02.03.04/8 " )
(check
(parse-address "192.168.99.1/8")
=> '(192 168 99 1 (8)))
(check
(guard (E ((parser-error-condition? E)
( display ( condition - message E))(newline )
#t)
(else #f))
(parse-address "1.2.3.4.5"))
=> #t)
(check
(guard (E ((parser-error-condition? E)
( display ( condition - message E))(newline )
#t)
(else #f))
(parse-address "1,"))
=> #t)
(check
(guard (E ((parser-error-condition? E)
( display ( condition - message E))(newline )
#t)
(else #f))
(parse-address "1..2..3"))
=> #t)
(check
(guard (E ((parser-error-condition? E)
( display ( condition - message E))(newline )
#t)
(else #f))
(parse-address "1..2.."))
=> #t)
(check
(guard (E ((parser-error-condition? E)
( display ( condition - message E))(newline )
#t)
(else #f))
(parse-address "..2..3"))
=> #t)
#t)
(parametrise ((check-test-name 'class-address))
(check
(let (((o <ipv4-address>)
(make* <ipv4-address> (ipv4-address-parse "1.2.3.4"))))
(list o.third o.second o.first o.zeroth))
=> '(1 2 3 4))
o.bignum )
(check
(let (((o <ipv4-address>)
(make* <ipv4-address> (ipv4-address-parse "1.2.3.4"))))
o.string)
=> "1.2.3.4")
(check
(let (((o <ipv4-address>) (make* <ipv4-address> (ipv4-address-parse "10.0.0.1"))))
o.private?)
=> #t)
(check
(let (((o <ipv4-address>) (make* <ipv4-address> (ipv4-address-parse "172.16.0.1"))))
o.private?)
=> #t)
(check
(let (((o <ipv4-address>) (make* <ipv4-address> (ipv4-address-parse "172.20.0.1"))))
o.private?)
=> #t)
(check
(let (((o <ipv4-address>) (make* <ipv4-address> (ipv4-address-parse "192.168.0.1"))))
o.private?)
=> #t)
(check
(let (((o <ipv4-address>) (make* <ipv4-address> (ipv4-address-parse "123.0.0.1"))))
o.private?)
=> #f)
(check
(let (((o <ipv4-address>) (make* <ipv4-address> (ipv4-address-parse "127.0.0.1"))))
o.loopback?)
=> #t)
(check
(let (((o <ipv4-address>) (make* <ipv4-address> (ipv4-address-parse "100.0.0.1"))))
o.loopback?)
=> #f)
(check
(let (((o <ipv4-address>) (make* <ipv4-address> (ipv4-address-parse "127.0.0.1"))))
o.localhost?)
=> #t)
(check
(let (((o <ipv4-address>) (make* <ipv4-address> (ipv4-address-parse "100.0.0.1"))))
o.localhost?)
=> #f)
(check
(let (((o <ipv4-address>) (make* <ipv4-address> (ipv4-address-parse "169.254.0.1"))))
o.link-local?)
=> #t)
(check
(let (((o <ipv4-address>) (make* <ipv4-address> (ipv4-address-parse "100.0.0.1"))))
o.link-local?)
=> #f)
(check
(let (((o <ipv4-address>) (make* <ipv4-address> (ipv4-address-parse "192.0.0.1"))))
o.reserved?)
=> #t)
(check
(let (((o <ipv4-address>) (make* <ipv4-address> (ipv4-address-parse "240.0.0.1"))))
o.reserved?)
=> #t)
(check
(let (((o <ipv4-address>) (make* <ipv4-address> (ipv4-address-parse "100.0.0.1"))))
o.reserved?)
=> #f)
(check
(let (((o <ipv4-address>) (make* <ipv4-address> (ipv4-address-parse "192.0.2.1"))))
o.test-net-1?)
=> #t)
(check
(let (((o <ipv4-address>) (make* <ipv4-address> (ipv4-address-parse "100.0.0.1"))))
o.test-net-1?)
=> #f)
(check
(let (((o <ipv4-address>) (make* <ipv4-address> (ipv4-address-parse "192.88.99.1"))))
o.six-to-four-relay-anycast?)
=> #t)
(check
(let (((o <ipv4-address>) (make* <ipv4-address> (ipv4-address-parse "100.0.0.1"))))
o.six-to-four-relay-anycast?)
=> #f)
(check
(let (((o <ipv4-address>) (make* <ipv4-address> (ipv4-address-parse "198.18.0.1"))))
o.benchmark-tests?)
=> #t)
(check
(let (((o <ipv4-address>) (make* <ipv4-address> (ipv4-address-parse "100.0.0.1"))))
o.benchmark-tests?)
=> #f)
(check
(let (((o <ipv4-address>) (make* <ipv4-address> (ipv4-address-parse "198.51.100.1"))))
o.test-net-2?)
=> #t)
(check
(let (((o <ipv4-address>) (make* <ipv4-address> (ipv4-address-parse "100.0.0.1"))))
o.test-net-2?)
=> #f)
(check
(let (((o <ipv4-address>) (make* <ipv4-address> (ipv4-address-parse "203.0.113.1"))))
o.test-net-3?)
=> #t)
(check
(let (((o <ipv4-address>) (make* <ipv4-address> (ipv4-address-parse "100.0.0.1"))))
o.test-net-3?)
=> #f)
(check
(let (((o <ipv4-address>) (make* <ipv4-address> (ipv4-address-parse "224.0.113.1"))))
o.multicast?)
=> #t)
(check
(let (((o <ipv4-address>) (make* <ipv4-address> (ipv4-address-parse "100.0.0.1"))))
o.multicast?)
=> #f)
(check
(let (((o <ipv4-address>) (make* <ipv4-address> (ipv4-address-parse "255.255.255.255"))))
o.limited-broadcast?)
=> #t)
(check
(let (((o <ipv4-address>) (make* <ipv4-address> (ipv4-address-parse "100.0.0.1"))))
o.limited-broadcast?)
=> #f)
#t)
(parametrise ((check-test-name 'class-prefix))
(check
(let (((o <ipv4-address-prefix>)
(receive (addr len)
(ipv4-address-prefix-parse "1.2.3.4/10")
(make* <ipv4-address-prefix> addr len))))
(list o.third o.second o.first o.zeroth o.prefix-length))
=> '(1 2 3 4 10))
(check
(let (((o <ipv4-address-prefix>)
(receive (addr len)
(ipv4-address-prefix-parse "1.2.3.4/8")
(make* <ipv4-address-prefix> addr len))))
o.string)
=> "1.2.3.4/8")
#t)
(check-report)
|
ac2583b4606a0dec36504fdf021d840f092a8153584902476dc3f2132beac505 | dongcarl/guix | libunwind.scm | ;;; GNU Guix --- Functional package management for GNU
Copyright © 2013 , 2014 < >
Copyright © 2015 < >
Copyright © 2019 < >
;;;
;;; This file is part of GNU Guix.
;;;
GNU is free software ; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation ; either version 3 of the License , or ( at
;;; your option) any later version.
;;;
;;; GNU Guix is distributed in the hope that it will be useful, but
;;; WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;;; GNU General Public License for more details.
;;;
You should have received a copy of the GNU General Public License
along with GNU . If not , see < / > .
(define-module (gnu packages libunwind)
#:use-module (guix packages)
#:use-module (gnu packages)
#:use-module (guix download)
#:use-module (guix build-system gnu)
#:use-module (guix licenses))
(define-public libunwind
(package
(name "libunwind")
(version "1.5.0")
(source (origin
(method url-fetch)
(uri (string-append "mirror-"
version ".tar.gz"))
(sha256
(base32
"05qhzcg1xag3l5m3c805np6k342gc0f3g087b7g16jidv59pccwh"))))
(build-system gnu-build-system)
(arguments
FIXME : As of glibc 2.25 , we get 1 out of 34 test failures ( 2 are
;; expected to fail).
;; Report them upstream.
'(#:tests? #f))
(home-page "")
(synopsis "Determining the call chain of a program")
(description
"The primary goal of this project is to define a portable and efficient C
programming interface (API) to determine the call-chain of a program. The API
additionally provides the means to manipulate the preserved (callee-saved)
state of each call-frame and to resume execution at any point in the
call-chain (non-local goto). The API supports both local (same-process) and
remote (across-process) operation. As such, the API is useful in a number of
applications.")
(license x11)))
| null | https://raw.githubusercontent.com/dongcarl/guix/82543e9649da2da9a5285ede4ec4f718fd740fcb/gnu/packages/libunwind.scm | scheme | GNU Guix --- Functional package management for GNU
This file is part of GNU Guix.
you can redistribute it and/or modify it
either version 3 of the License , or ( at
your option) any later version.
GNU Guix is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
expected to fail).
Report them upstream. | Copyright © 2013 , 2014 < >
Copyright © 2015 < >
Copyright © 2019 < >
under the terms of the GNU General Public License as published by
You should have received a copy of the GNU General Public License
along with GNU . If not , see < / > .
(define-module (gnu packages libunwind)
#:use-module (guix packages)
#:use-module (gnu packages)
#:use-module (guix download)
#:use-module (guix build-system gnu)
#:use-module (guix licenses))
(define-public libunwind
(package
(name "libunwind")
(version "1.5.0")
(source (origin
(method url-fetch)
(uri (string-append "mirror-"
version ".tar.gz"))
(sha256
(base32
"05qhzcg1xag3l5m3c805np6k342gc0f3g087b7g16jidv59pccwh"))))
(build-system gnu-build-system)
(arguments
FIXME : As of glibc 2.25 , we get 1 out of 34 test failures ( 2 are
'(#:tests? #f))
(home-page "")
(synopsis "Determining the call chain of a program")
(description
"The primary goal of this project is to define a portable and efficient C
programming interface (API) to determine the call-chain of a program. The API
additionally provides the means to manipulate the preserved (callee-saved)
state of each call-frame and to resume execution at any point in the
call-chain (non-local goto). The API supports both local (same-process) and
remote (across-process) operation. As such, the API is useful in a number of
applications.")
(license x11)))
|
586647c503a0ca30c292cdc862645032fc82c32674cf8f84bbedc1e8b3ccd6d9 | psg-mit/probzelus-haskell | SymbolicLL.hs | module SymbolicLL where
import Prelude
import Data.Foldable (asum)
import Data.List (partition)
import Data.Maybe (fromMaybe)
import Data.IORef
import Control.Arrow (second)
import Control.Monad ((>=>), void)
import Control.Monad.State
import Debug.Trace (traceShow, trace)
import Distributions hiding (factor)
import Util.MStream hiding (Ret)
import qualified Util.MStream as M
import Util.ZStream (ZStream)
import qualified Util.ZStream as Z
import SymbolicArithmetic
data PProg v a where
Ret :: a -> PProg v a
FactorThen :: Exp v Double -> PProg v a -> PProg v a
SampleThen :: (Exp v a -> Exp v Double) -> (Exp v a -> PProg v b) -> PProg v b
instance Functor (PProg v) where
fmap f (Ret x) = Ret (f x)
fmap f (FactorThen w k) = FactorThen w (fmap f k)
fmap f (SampleThen d k) = SampleThen d (fmap f . k)
instance Applicative (PProg v) where
pure = Ret
f <*> x = do
f' <- f
x' <- x
pure (f' x')
instance Monad (PProg v) where
Ret x >>= f = f x
FactorThen w k >>= f = FactorThen w (k >>= f)
SampleThen d k >>= f = SampleThen d (\x -> k x >>= f)
factor :: Exp v Double -> PProg v ()
factor w = FactorThen w $ Ret ()
sample' :: (Exp v a -> Exp v Double) -> PProg v (Exp v a)
sample' s = SampleThen s (\x -> Ret x)
getVarFromProduct' :: (Num a, Eq env) => env -> [Exp env a] -> Maybe (Exp env a, [Exp env a])
getVarFromProduct' i es = case Data.List.partition (varIn i) es of
([], _) -> Nothing
(is, es') -> Just (prod1 is, es')
getVarFromProduct :: (Eq env, Eq a, Num a, Show env, Show a) => env -> [Exp env a] -> Either Bool (Exp env a, [Exp env a])
--getVarFromProduct i es| traceShow ("getVarFromProduct", i, es) False = undefined
getVarFromProduct i es = case getVarFromProduct' i es of
Just (e, es') -> if all (Var i `notIn`) es'
then Right (e, es')
else Left True
Nothing -> Left False
getFromList :: Eq a => a -> [(a, k)] -> Maybe (k, [(a, k)])
getFromList i [] = Nothing
getFromList i ((j, x) : xs) = if i == j
then Just (x, xs)
else fmap (second ((j, x) :)) (getFromList i xs)
matchPattern :: (Eq a, Show a, Show k) => [(a, k)] -> [a] -> Maybe [[k]]
matchPattern es xs | traceShow ( es , xs ) False = undefined
matchPattern [] [] = Just []
matchPattern (_ : _) [] = Nothing
matchPattern es (x : xs) =
let (esx, esnotx) = Data.List.partition (\(k, v) -> k == x) es in
(map snd esx :) <$> matchPattern esnotx xs
getDist1 :: Int -> [(Exp Int Double, [Exp Int Double])] -> Maybe String
--getDist1 i xs | traceShow ("getDist1", i, xs) False = undefined
getDist1 i xs = asum [ f' . map (sum1 . map prod1) =<< (matchPattern xs (map (mapVars (\_ -> i)) f)) | (f, f') <- fs] where
fs = map efFunc exponentialFamilies
efFunc (Some ef) = (suffStats ef, fmap (efDescribe ef) . mapM getConstant)
-- at :: Int -> [a] -> Maybe a
-- at _ [] = Nothing
-- at 0 (x : _) = Just x
-- at i (_ : xs) = lookup (i - 1) xs
getDist :: Exp Int Double -> Exp Int Double -> Maybe String
--getDist e i | traceShow ("getDist", e, i) False = undefined
getDist e i = do
i' <- getVar i
let e' = getSumOfProd e
xs <- getRelevants (map (getVarFromProduct i') e')
getDist1 i' xs
where
getRelevants [] = Just []
getRelevants (x : xs) = case x of
Left False -> getRelevants xs
Left True -> Nothing
Right y -> fmap (y :) (getRelevants xs)
run'' :: Monad m => PProg Int a -> StateT (Int, Exp Int Double) m a
run'' (Ret x) = pure x
run'' (SampleThen d f) = do
(nvars, e) <- get
put (nvars + 1, e + d (Var nvars))
run'' (f (Var nvars))
run'' (FactorThen ll x) = do
modify (second (+ ll))
run'' x
run :: Monad m => MStream (PProg Int) (Exp Int Double) a -> MStream m (Maybe String) a
run = apState . M.mapyieldM evalDist . M.liftM run'' where
apState :: Monad m => MStream (StateT (Int, Exp Int Double) m) (Maybe String) a -> MStream m (Maybe String) a
apState = fmap snd . M.runState (0, 0)
evalDist :: Monad m => Exp Int Double -> StateT (Int, Exp Int Double) m (Maybe String)
evalDist y = do
(_, e) <- get
pure (getDist e y)
runZ :: Monad m => ZStream (PProg Int) a b -> ZStream m a b
runZ = Z.runState (0, 0) . Z.liftM run''
betaBernoulliModel :: MStream (PProg v) (Exp v Double) a
betaBernoulliModel = do
p <- M.lift $ sample' (beta_ll 1 1)
step True p
where
step b p = do
yield p
M.lift $ factor (bernoulli_ll p (if b then 1 else 0))
step (not b) p
gaussianGaussianModel :: MStream (PProg v) (Exp v Double) a
gaussianGaussianModel = do
mu <- M.lift $ sample' (gaussian_ll 0 100)
step mu
where
step mu = do
yield mu
M.lift $ factor (gaussian_ll (2 * mu) 1 3.5)
step mu
runModel :: MStream (PProg Int) (Exp Int Double) a -> IO ()
runModel = void . runStream (putStrLn . fromMaybe "Nothing") . run | null | https://raw.githubusercontent.com/psg-mit/probzelus-haskell/a4b66631451b6156938a9c5420cfff2999ecbbc6/haskell/src/SymbolicLL.hs | haskell | getVarFromProduct i es| traceShow ("getVarFromProduct", i, es) False = undefined
getDist1 i xs | traceShow ("getDist1", i, xs) False = undefined
at :: Int -> [a] -> Maybe a
at _ [] = Nothing
at 0 (x : _) = Just x
at i (_ : xs) = lookup (i - 1) xs
getDist e i | traceShow ("getDist", e, i) False = undefined | module SymbolicLL where
import Prelude
import Data.Foldable (asum)
import Data.List (partition)
import Data.Maybe (fromMaybe)
import Data.IORef
import Control.Arrow (second)
import Control.Monad ((>=>), void)
import Control.Monad.State
import Debug.Trace (traceShow, trace)
import Distributions hiding (factor)
import Util.MStream hiding (Ret)
import qualified Util.MStream as M
import Util.ZStream (ZStream)
import qualified Util.ZStream as Z
import SymbolicArithmetic
data PProg v a where
Ret :: a -> PProg v a
FactorThen :: Exp v Double -> PProg v a -> PProg v a
SampleThen :: (Exp v a -> Exp v Double) -> (Exp v a -> PProg v b) -> PProg v b
instance Functor (PProg v) where
fmap f (Ret x) = Ret (f x)
fmap f (FactorThen w k) = FactorThen w (fmap f k)
fmap f (SampleThen d k) = SampleThen d (fmap f . k)
instance Applicative (PProg v) where
pure = Ret
f <*> x = do
f' <- f
x' <- x
pure (f' x')
instance Monad (PProg v) where
Ret x >>= f = f x
FactorThen w k >>= f = FactorThen w (k >>= f)
SampleThen d k >>= f = SampleThen d (\x -> k x >>= f)
factor :: Exp v Double -> PProg v ()
factor w = FactorThen w $ Ret ()
sample' :: (Exp v a -> Exp v Double) -> PProg v (Exp v a)
sample' s = SampleThen s (\x -> Ret x)
getVarFromProduct' :: (Num a, Eq env) => env -> [Exp env a] -> Maybe (Exp env a, [Exp env a])
getVarFromProduct' i es = case Data.List.partition (varIn i) es of
([], _) -> Nothing
(is, es') -> Just (prod1 is, es')
getVarFromProduct :: (Eq env, Eq a, Num a, Show env, Show a) => env -> [Exp env a] -> Either Bool (Exp env a, [Exp env a])
getVarFromProduct i es = case getVarFromProduct' i es of
Just (e, es') -> if all (Var i `notIn`) es'
then Right (e, es')
else Left True
Nothing -> Left False
getFromList :: Eq a => a -> [(a, k)] -> Maybe (k, [(a, k)])
getFromList i [] = Nothing
getFromList i ((j, x) : xs) = if i == j
then Just (x, xs)
else fmap (second ((j, x) :)) (getFromList i xs)
matchPattern :: (Eq a, Show a, Show k) => [(a, k)] -> [a] -> Maybe [[k]]
matchPattern es xs | traceShow ( es , xs ) False = undefined
matchPattern [] [] = Just []
matchPattern (_ : _) [] = Nothing
matchPattern es (x : xs) =
let (esx, esnotx) = Data.List.partition (\(k, v) -> k == x) es in
(map snd esx :) <$> matchPattern esnotx xs
getDist1 :: Int -> [(Exp Int Double, [Exp Int Double])] -> Maybe String
getDist1 i xs = asum [ f' . map (sum1 . map prod1) =<< (matchPattern xs (map (mapVars (\_ -> i)) f)) | (f, f') <- fs] where
fs = map efFunc exponentialFamilies
efFunc (Some ef) = (suffStats ef, fmap (efDescribe ef) . mapM getConstant)
getDist :: Exp Int Double -> Exp Int Double -> Maybe String
getDist e i = do
i' <- getVar i
let e' = getSumOfProd e
xs <- getRelevants (map (getVarFromProduct i') e')
getDist1 i' xs
where
getRelevants [] = Just []
getRelevants (x : xs) = case x of
Left False -> getRelevants xs
Left True -> Nothing
Right y -> fmap (y :) (getRelevants xs)
run'' :: Monad m => PProg Int a -> StateT (Int, Exp Int Double) m a
run'' (Ret x) = pure x
run'' (SampleThen d f) = do
(nvars, e) <- get
put (nvars + 1, e + d (Var nvars))
run'' (f (Var nvars))
run'' (FactorThen ll x) = do
modify (second (+ ll))
run'' x
run :: Monad m => MStream (PProg Int) (Exp Int Double) a -> MStream m (Maybe String) a
run = apState . M.mapyieldM evalDist . M.liftM run'' where
apState :: Monad m => MStream (StateT (Int, Exp Int Double) m) (Maybe String) a -> MStream m (Maybe String) a
apState = fmap snd . M.runState (0, 0)
evalDist :: Monad m => Exp Int Double -> StateT (Int, Exp Int Double) m (Maybe String)
evalDist y = do
(_, e) <- get
pure (getDist e y)
runZ :: Monad m => ZStream (PProg Int) a b -> ZStream m a b
runZ = Z.runState (0, 0) . Z.liftM run''
betaBernoulliModel :: MStream (PProg v) (Exp v Double) a
betaBernoulliModel = do
p <- M.lift $ sample' (beta_ll 1 1)
step True p
where
step b p = do
yield p
M.lift $ factor (bernoulli_ll p (if b then 1 else 0))
step (not b) p
gaussianGaussianModel :: MStream (PProg v) (Exp v Double) a
gaussianGaussianModel = do
mu <- M.lift $ sample' (gaussian_ll 0 100)
step mu
where
step mu = do
yield mu
M.lift $ factor (gaussian_ll (2 * mu) 1 3.5)
step mu
runModel :: MStream (PProg Int) (Exp Int Double) a -> IO ()
runModel = void . runStream (putStrLn . fromMaybe "Nothing") . run |
ead69b26bf4c6ab2cb8aa2fd28a48ffb18fcd4893136181df360122c554d453c | ocsigen/ocaml-eliom | test_big_ints.ml | (**************************************************************************)
(* *)
(* OCaml *)
(* *)
, projet Cristal , INRIA Rocquencourt
(* *)
Copyright 1996 Institut National de Recherche en Informatique et
(* en Automatique. *)
(* *)
(* All rights reserved. This file is distributed under the terms of *)
the GNU Lesser General Public License version 2.1 , with the
(* special exception on linking described in the file LICENSE. *)
(* *)
(**************************************************************************)
open Test;;
open Nat;;
open Big_int;;
open List;;
testing_function "compare_big_int";;
test 1
eq_int (compare_big_int zero_big_int zero_big_int, 0);;
test 2
eq_int (compare_big_int zero_big_int (big_int_of_int 1), (-1));;
test 3
eq_int (compare_big_int zero_big_int (big_int_of_int (-1)), 1);;
test 4
eq_int (compare_big_int (big_int_of_int 1) zero_big_int, 1);;
test 5
eq_int (compare_big_int (big_int_of_int (-1)) zero_big_int, (-1));;
test 6
eq_int (compare_big_int (big_int_of_int 1) (big_int_of_int 1), 0);;
test 7
eq_int (compare_big_int (big_int_of_int (-1)) (big_int_of_int (-1)), 0);;
test 8
eq_int (compare_big_int (big_int_of_int 1) (big_int_of_int (-1)), 1);;
test 9
eq_int (compare_big_int (big_int_of_int (-1)) (big_int_of_int 1), (-1));;
test 10
eq_int (compare_big_int (big_int_of_int 1) (big_int_of_int 2), (-1));;
test 11
eq_int (compare_big_int (big_int_of_int 2) (big_int_of_int 1), 1);;
test 12
eq_int (compare_big_int (big_int_of_int (-1)) (big_int_of_int (-2)), 1);;
test 13
eq_int (compare_big_int (big_int_of_int (-2)) (big_int_of_int (-1)), (-1));;
testing_function "pred_big_int";;
test 1
eq_big_int (pred_big_int zero_big_int, big_int_of_int (-1));;
test 2
eq_big_int (pred_big_int unit_big_int, zero_big_int);;
test 3
eq_big_int (pred_big_int (big_int_of_int (-1)), big_int_of_int (-2));;
testing_function "succ_big_int";;
test 1
eq_big_int (succ_big_int zero_big_int, unit_big_int);;
test 2
eq_big_int (succ_big_int unit_big_int, big_int_of_int 2);;
test 3
eq_big_int (succ_big_int (big_int_of_int (-1)), zero_big_int);;
testing_function "add_big_int";;
test 1
eq_big_int (add_big_int zero_big_int zero_big_int, zero_big_int);;
test 2
eq_big_int (add_big_int zero_big_int (big_int_of_int 1),
big_int_of_int 1);;
test 3
eq_big_int (add_big_int (big_int_of_int 1) zero_big_int,
big_int_of_int 1);;
test 4
eq_big_int (add_big_int zero_big_int (big_int_of_int (-1)),
big_int_of_int (-1));;
test 5
eq_big_int (add_big_int (big_int_of_int (-1)) zero_big_int,
big_int_of_int (-1));;
test 6
eq_big_int (add_big_int (big_int_of_int 1) (big_int_of_int 1),
big_int_of_int 2);;
test 7
eq_big_int (add_big_int (big_int_of_int 1) (big_int_of_int 2),
big_int_of_int 3);;
test 8
eq_big_int (add_big_int (big_int_of_int 2) (big_int_of_int 1),
big_int_of_int 3);;
test 9
eq_big_int (add_big_int (big_int_of_int (-1)) (big_int_of_int (-1)),
big_int_of_int (-2));;
test 10
eq_big_int (add_big_int (big_int_of_int (-1)) (big_int_of_int (-2)),
big_int_of_int (-3));;
test 11
eq_big_int (add_big_int (big_int_of_int (-2)) (big_int_of_int (-1)),
big_int_of_int (-3));;
test 12
eq_big_int (add_big_int (big_int_of_int 1) (big_int_of_int (-1)),
zero_big_int);;
test 13
eq_big_int (add_big_int (big_int_of_int (-1)) (big_int_of_int 1),
zero_big_int);;
test 14
eq_big_int (add_big_int (big_int_of_int 1) (big_int_of_int (-2)),
big_int_of_int (-1));;
test 15
eq_big_int (add_big_int (big_int_of_int (-2)) (big_int_of_int 1),
big_int_of_int (-1));;
test 16
eq_big_int (add_big_int (big_int_of_int (-1)) (big_int_of_int 2),
big_int_of_int 1);;
test 17
eq_big_int (add_big_int (big_int_of_int 2) (big_int_of_int (-1)),
big_int_of_int 1);;
testing_function "sub_big_int";;
test 1
eq_big_int (sub_big_int zero_big_int zero_big_int, zero_big_int);;
test 2
eq_big_int (sub_big_int zero_big_int (big_int_of_int 1),
big_int_of_int (-1));;
test 3
eq_big_int (sub_big_int (big_int_of_int 1) zero_big_int,
big_int_of_int 1);;
test 4
eq_big_int (sub_big_int zero_big_int (big_int_of_int (-1)),
big_int_of_int 1);;
test 5
eq_big_int (sub_big_int (big_int_of_int (-1)) zero_big_int,
big_int_of_int (-1));;
test 6
eq_big_int (sub_big_int (big_int_of_int 1) (big_int_of_int 1),
zero_big_int);;
test 7
eq_big_int (sub_big_int (big_int_of_int 1) (big_int_of_int 2),
big_int_of_int (-1));;
test 8
eq_big_int (sub_big_int (big_int_of_int 2) (big_int_of_int 1),
big_int_of_int 1);;
test 9
eq_big_int (sub_big_int (big_int_of_int (-1)) (big_int_of_int (-1)),
zero_big_int);;
test 10
eq_big_int (sub_big_int (big_int_of_int (-1)) (big_int_of_int (-2)),
big_int_of_int 1);;
test 11
eq_big_int (sub_big_int (big_int_of_int (-2)) (big_int_of_int (-1)),
big_int_of_int (-1));;
test 12
eq_big_int (sub_big_int (big_int_of_int 1) (big_int_of_int (-1)),
big_int_of_int 2);;
test 13
eq_big_int (sub_big_int (big_int_of_int (-1)) (big_int_of_int 1),
big_int_of_int (-2));;
test 14
eq_big_int (sub_big_int (big_int_of_int 1) (big_int_of_int (-2)),
big_int_of_int 3);;
test 15
eq_big_int (sub_big_int (big_int_of_int (-2)) (big_int_of_int 1),
big_int_of_int (-3));;
test 16
eq_big_int (sub_big_int (big_int_of_int (-1)) (big_int_of_int 2),
big_int_of_int (-3));;
test 17
eq_big_int (sub_big_int (big_int_of_int 2) (big_int_of_int (-1)),
big_int_of_int 3);;
testing_function "mult_int_big_int";;
test 1
eq_big_int (mult_int_big_int 0 (big_int_of_int 3), zero_big_int);;
test 2
eq_big_int (mult_int_big_int 1 (big_int_of_int 3), big_int_of_int 3);;
test 3
eq_big_int (mult_int_big_int 1 zero_big_int, zero_big_int);;
test 4
eq_big_int (mult_int_big_int 2 (big_int_of_int 3), big_int_of_int 6);;
testing_function "mult_big_int";;
test 1
eq_big_int (mult_big_int zero_big_int zero_big_int,
zero_big_int);;
test 2
eq_big_int (mult_big_int (big_int_of_int 2) (big_int_of_int 3),
big_int_of_int 6);;
test 3
eq_big_int (mult_big_int (big_int_of_int 2) (big_int_of_int (-3)),
big_int_of_int (-6));;
test 4
eq_big_int (mult_big_int (big_int_of_string "12724951")
(big_int_of_string "81749606400"),
big_int_of_string "1040259735709286400");;
test 5
eq_big_int (mult_big_int (big_int_of_string "26542080")
(big_int_of_string "81749606400"),
big_int_of_string "2169804593037312000");;
testing_function "quomod_big_int";;
let (quotient, modulo) =
quomod_big_int (big_int_of_int 1) (big_int_of_int 1) in
test 1 eq_big_int (quotient, big_int_of_int 1) &&
test 2 eq_big_int (modulo, zero_big_int);;
let (quotient, modulo) =
quomod_big_int (big_int_of_int 1) (big_int_of_int (-1)) in
test 3 eq_big_int (quotient, big_int_of_int (-1)) &&
test 4 eq_big_int (modulo, zero_big_int);;
let (quotient, modulo) =
quomod_big_int (big_int_of_int (-1)) (big_int_of_int 1) in
test 5 eq_big_int (quotient, big_int_of_int (-1)) &&
test 6 eq_big_int (modulo, zero_big_int);;
let (quotient, modulo) =
quomod_big_int (big_int_of_int 3) (big_int_of_int 2) in
test 7 eq_big_int (quotient, big_int_of_int 1) &&
test 8 eq_big_int (modulo, big_int_of_int 1);;
let (quotient, modulo) =
quomod_big_int (big_int_of_int 5) (big_int_of_int 3) in
test 9 eq_big_int (quotient, big_int_of_int 1) &&
test 10 eq_big_int (modulo, big_int_of_int 2);;
let (quotient, modulo) =
quomod_big_int (big_int_of_int (-5)) (big_int_of_int 3) in
test 11 eq_big_int (quotient, big_int_of_int (-2)) &&
test 12 eq_big_int (modulo, big_int_of_int 1);;
let (quotient, modulo) =
quomod_big_int (big_int_of_int 1) (big_int_of_int 2) in
test 13 eq_big_int (quotient, zero_big_int) &&
test 14 eq_big_int (modulo, big_int_of_int 1);;
let (quotient, modulo) =
quomod_big_int (big_int_of_int (-1)) (big_int_of_int 3) in
test 15 eq_big_int (quotient, minus_big_int unit_big_int) &&
test 16 eq_big_int (modulo, big_int_of_int 2);;
failwith_test 17
(quomod_big_int (big_int_of_int 1)) zero_big_int
Division_by_zero
;;
let (quotient, modulo) =
quomod_big_int (big_int_of_int 10) (big_int_of_int 20) in
test 18 eq_big_int (quotient, big_int_of_int 0) &&
test 19 eq_big_int (modulo, big_int_of_int 10);;
let (quotient, modulo) =
quomod_big_int (big_int_of_int (-10)) (big_int_of_int 20) in
test 20 eq_big_int (quotient, big_int_of_int (-1)) &&
test 21 eq_big_int (modulo, big_int_of_int 10);;
let (quotient, modulo) =
quomod_big_int (big_int_of_int 10) (big_int_of_int (-20)) in
test 22 eq_big_int (quotient, big_int_of_int 0) &&
test 23 eq_big_int (modulo, big_int_of_int 10);;
let (quotient, modulo) =
quomod_big_int (big_int_of_int (-10)) (big_int_of_int (-20)) in
test 24 eq_big_int (quotient, big_int_of_int 1) &&
test 25 eq_big_int (modulo, big_int_of_int 10);;
testing_function "gcd_big_int";;
test 1
eq_big_int (gcd_big_int zero_big_int zero_big_int,
zero_big_int);;
test 2
eq_big_int (gcd_big_int zero_big_int (big_int_of_int 1),
big_int_of_int 1);;
test 3
eq_big_int (gcd_big_int (big_int_of_int 1) zero_big_int,
big_int_of_int 1);;
test 4
eq_big_int (gcd_big_int (big_int_of_int 1) (big_int_of_int 2),
big_int_of_int 1);;
test 5
eq_big_int (gcd_big_int (big_int_of_int 2) (big_int_of_int 1),
big_int_of_int 1);;
test 6
eq_big_int (gcd_big_int (big_int_of_int 1) (big_int_of_int 1),
big_int_of_int 1);;
test 7
eq_big_int (gcd_big_int (big_int_of_int 9) (big_int_of_int 16),
big_int_of_int 1);;
test 8
eq_big_int (gcd_big_int (big_int_of_int 12) (big_int_of_int 16),
big_int_of_int 4);;
for i = 9 to 28 do
let n1 = Random.int 1000000000
and n2 = Random.int 100000 in
let _ =
test i eq
(int_of_big_int (gcd_big_int (big_int_of_int n1) (big_int_of_int n2)),
gcd_int n1 n2) in
()
done;;
testing_function "int_of_big_int";;
test 1
eq_int (int_of_big_int (big_int_of_int 1), 1);;
test 2
eq_int (int_of_big_int (big_int_of_int(-1)), -1);;
test 3
eq_int (int_of_big_int zero_big_int, 0);;
test 4
eq_int (int_of_big_int (big_int_of_int max_int), max_int);;
test 5
eq_int (int_of_big_int (big_int_of_int min_int), min_int);;
failwith_test 6
(fun () -> int_of_big_int (succ_big_int (big_int_of_int max_int)))
() (Failure "int_of_big_int");;
failwith_test 7
(fun () -> int_of_big_int (pred_big_int (big_int_of_int min_int)))
() (Failure "int_of_big_int");;
failwith_test 8
(fun () -> int_of_big_int (mult_big_int (big_int_of_int min_int)
(big_int_of_int 2)))
() (Failure "int_of_big_int");;
testing_function "is_int_big_int";;
test 1
eq (is_int_big_int (big_int_of_int 1), true);;
test 2
eq (is_int_big_int (big_int_of_int (-1)), true);;
test 3
eq (is_int_big_int (succ_big_int (big_int_of_int biggest_int)), false);;
test 4
eq (int_of_big_int (big_int_of_int monster_int), monster_int);;
(* Should be true *)
test 5
eq (is_int_big_int (big_int_of_string (string_of_int biggest_int)), true);;
test 6
eq (is_int_big_int (big_int_of_string (string_of_int least_int)), true);;
test 7
eq (is_int_big_int (big_int_of_string (string_of_int monster_int)), true);;
(* Should be false *)
(* Successor of biggest_int is not an int *)
test 8
eq (is_int_big_int (succ_big_int (big_int_of_int (biggest_int))), false);;
test 9
eq (is_int_big_int
(succ_big_int (succ_big_int (big_int_of_int (biggest_int)))), false);;
(* Negation of monster_int (as a big_int) is not an int *)
test 10
eq (is_int_big_int
(minus_big_int (big_int_of_string (string_of_int monster_int))), false);;
testing_function "sys_string_of_big_int";;
test 1
eq_string (string_of_big_int (big_int_of_int 1), "1");;
testing_function "big_int_of_string";;
test 1
eq_big_int (big_int_of_string "1", big_int_of_int 1);;
test 2
eq_big_int (big_int_of_string "-1", big_int_of_int (-1));;
test 4
eq_big_int (big_int_of_string "0", zero_big_int);;
failwith_test 5 big_int_of_string "sdjdkfighdgf"
(Failure "invalid digit");;
test 6
eq_big_int (big_int_of_string "123", big_int_of_int 123);;
test 7
eq_big_int (big_int_of_string "+3456", big_int_of_int 3456);;
test 9
eq_big_int (big_int_of_string "-3456", big_int_of_int (-3456));;
let implode = List.fold_left (^) "";; (* To hell with efficiency *)
let l = rev [
"174679877494298468451661416292903906557638850173895426081611831060970135303";
"044177587617233125776581034213405720474892937404345377707655788096850784519";
"539374048533324740018513057210881137248587265169064879918339714405948322501";
"445922724181830422326068913963858377101914542266807281471620827145038901025";
"322784396182858865537924078131032036927586614781817695777639491934361211399";
"888524140253852859555118862284235219972858420374290985423899099648066366558";
"238523612660414395240146528009203942793935957539186742012316630755300111472";
"852707974927265572257203394961525316215198438466177260614187266288417996647";
"132974072337956513457924431633191471716899014677585762010115338540738783163";
"739223806648361958204720897858193606022290696766988489073354139289154127309";
"916985231051926209439373780384293513938376175026016587144157313996556653811";
"793187841050456120649717382553450099049321059330947779485538381272648295449";
"847188233356805715432460040567660999184007627415398722991790542115164516290";
"619821378529926683447345857832940144982437162642295073360087284113248737998";
"046564369129742074737760485635495880623324782103052289938185453627547195245";
"688272436219215066430533447287305048225780425168823659431607654712261368560";
"702129351210471250717394128044019490336608558608922841794819375031757643448";
"32"
] in
let bi1 = big_int_of_string (implode (rev l)) in
let bi2 = big_int_of_string (implode (rev ("3" :: tl l))) in
test 10
eq_big_int (bi1, (add_big_int (mult_big_int bi2 (big_int_of_string "10"))
(big_int_of_string "2")))
test 11
& &
eq_big_int ( bi1 , ( add_big_int ( mult_big_int bi2 ( big_int_of_string " 10e0 " ) )
( big_int_of_string " 20e-1 " ) ) ) & &
test 12
eq_big_int ( minus_big_int bi1 ,
( add_big_int ( mult_big_int bi2 ( big_int_of_string " -10e0 " ) )
( big_int_of_string " -20e-1 " ) ) ) & &
test 13
eq_big_int ( bi1 , ( add_big_int ( mult_big_int bi2 ( big_int_of_string " +10e0 " ) )
( big_int_of_string " +20e-1 " ) ) ) & &
test 14
eq_big_int ( minus_big_int bi1 ,
( add_big_int ( mult_big_int bi2 ( big_int_of_string " -10e+0 " ) )
( big_int_of_string " -20e-1 " ) ) ) & &
test 15
eq_big_int ( minus_big_int bi1 ,
( add_big_int ( mult_big_int bi2 ( big_int_of_string " -1e+1 " ) )
( big_int_of_string " -2e-0 " ) ) ) & &
test 16
eq_big_int ( minus_big_int bi1 ,
( add_big_int ( mult_big_int bi2 ( big_int_of_string " -0.1e+2 " ) )
( big_int_of_string " -2.0e-0 " ) ) ) & &
test 17
eq_big_int ( minus_big_int bi1 ,
( add_big_int ( mult_big_int bi2 ( big_int_of_string " -1.000e+1 " ) )
( big_int_of_string " -0.02e2 " ) ) )
&&
eq_big_int (bi1, (add_big_int (mult_big_int bi2 (big_int_of_string "10e0"))
(big_int_of_string "20e-1"))) &&
test 12
eq_big_int (minus_big_int bi1,
(add_big_int (mult_big_int bi2 (big_int_of_string "-10e0"))
(big_int_of_string "-20e-1"))) &&
test 13
eq_big_int (bi1, (add_big_int (mult_big_int bi2 (big_int_of_string "+10e0"))
(big_int_of_string "+20e-1"))) &&
test 14
eq_big_int (minus_big_int bi1,
(add_big_int (mult_big_int bi2 (big_int_of_string "-10e+0"))
(big_int_of_string "-20e-1"))) &&
test 15
eq_big_int (minus_big_int bi1,
(add_big_int (mult_big_int bi2 (big_int_of_string "-1e+1"))
(big_int_of_string "-2e-0"))) &&
test 16
eq_big_int (minus_big_int bi1,
(add_big_int (mult_big_int bi2 (big_int_of_string "-0.1e+2"))
(big_int_of_string "-2.0e-0"))) &&
test 17
eq_big_int (minus_big_int bi1,
(add_big_int (mult_big_int bi2 (big_int_of_string "-1.000e+1"))
(big_int_of_string "-0.02e2")))*)
;;
test 18
eq_big_int (big_int_of_string "0xAbC", big_int_of_int 0xABC);;
test 19
eq_big_int (big_int_of_string "-0o452", big_int_of_int (-0o452));;
test 20
eq_big_int (big_int_of_string "0B110101", big_int_of_int 53);;
test 21
eq_big_int (big_int_of_string "0b11_01_01", big_int_of_int 53);;
testing_function "power_base_int";;
test 1
eq_big_int (big_int_of_nat (power_base_int 10 0), unit_big_int)
;;
test 2
eq_big_int (big_int_of_nat (power_base_int 10 8), big_int_of_int 100000000)
;;
test 3
eq_big_int (big_int_of_nat (power_base_int 2 (length_of_int + 2)),
big_int_of_nat (let nat = make_nat 2 in
set_digit_nat nat 1 1;
nat))
;;
testing_function "base_power_big_int";;
test 1
eq_big_int (base_power_big_int 10 0 (big_int_of_int 2), big_int_of_int 2);;
test 2
eq_big_int (base_power_big_int 10 2 (big_int_of_int 2), big_int_of_int 200);;
test 3
eq_big_int (base_power_big_int 10 1 (big_int_of_int 123), big_int_of_int 1230)
;;
testing_function "power_int_positive_big_int";;
test 1
eq_big_int (power_int_positive_big_int 2 (big_int_of_int 10),
big_int_of_int 1024);;
test 2
eq_big_int
(power_int_positive_big_int 2 (big_int_of_int 65),
big_int_of_string "36893488147419103232");;
test 3
eq_big_int
(power_int_positive_big_int 3 (big_int_of_string "47"),
big_int_of_string "26588814358957503287787");;
test 4
eq_big_int
(power_int_positive_big_int 1 (big_int_of_string "1000000000000000000000"),
big_int_of_int 1);;
test 5
eq_big_int
(power_int_positive_big_int (-1) (big_int_of_string "1000000000000000000000"),
big_int_of_int 1);;
test 6
eq_big_int
(power_int_positive_big_int (-1) (big_int_of_string "1000000000000000000001"),
big_int_of_int (-1));;
test 7
eq_big_int
(power_int_positive_big_int 0 (big_int_of_string "1000000000000000000000"),
big_int_of_int 0);;
testing_function "power_big_int_positive_int";;
test 1
eq_big_int (power_big_int_positive_int (big_int_of_int 2) 10,
big_int_of_int 1024);;
test 2
eq_big_int
(power_big_int_positive_int (big_int_of_int 100) 20,
big_int_of_string "10000000000000000000000000000000000000000");;
test 3
eq_big_int
(power_big_int_positive_int (big_int_of_string "3") 47,
big_int_of_string "26588814358957503287787");;
test 4
eq_big_int
(power_big_int_positive_int (big_int_of_string "200000000000000") 34,
big_int_of_string
"17179869184000000000000000000000000000000000000000000000000000000000\
00000000000000000000000000000000000000000000000000000000000000000000\
00000000000000000000000000000000000000000000000000000000000000000000\
00000000000000000000000000000000000000000000000000000000000000000000\
00000000000000000000000000000000000000000000000000000000000000000000\
00000000000000000000000000000000000000000000000000000000000000000000\
00000000000000000000000000000000000000000000000000000000000000000000\
00000000000");;
test 5
eq_big_int
(power_big_int_positive_int (big_int_of_string "2197609328765") 243,
big_int_of_string
"12415638672345366257764851943822299490113545698929764576040102857365\
27920436565335427676982530274588056944387957287793378051852205028658\
73008292720317554332284838709453634119919368441951233982592586680844\
20765201140575612595182857026804842796931784944918059630667794516774\
58498235838834599150657873894983300999081942159304585449505963892008\
97855706440206825609657816209327492197604711437269361628626691080334\
38432768885637928268354258860147333786379766583179851226375449161073\
10396958979998161989562418169797611757651190037273397850239552735199\
63719988832594486235837899145390948533078339399890545062510060406048\
61331200657727576638170520036143007285549092686618686739320973444703\
33342725604091818763255601206325426337211467746377586080108631634250\
11232258578207762608797108802386708549785680783113606089879687396654\
54004281165259352412815385041917713969718327109245777066079665194617\
29230093411050053217775067781725651590160086483960457766025246936489\
92234225900994076609973190516835778346886551506344097474301175288686\
25662752919718480402972207084177612056491949911377568680526080633587\
33230060757162252611388973328501680433819585006035301408574879645573\
47126018243568976860515247053858204554293343161581801846081341003624\
22906934772131205632200433218165757307182816260714026614324014553342\
77303133877636489457498062819003614421295692889321460150481573909330\
77301946991278225819671075907191359721824291923283322225480199446258\
03302645587072103949599624444368321734975586414930425964782010567575\
43333331963876294983400462908871215572514487548352925949663431718284\
14589547315559936497408670231851521193150991888789948397029796279240\
53117024758684807981605608837291399377902947471927467827290844733264\
70881963357258978768427852958888430774360783419404195056122644913454\
24537375432013012467418602205343636983874410969339344956536142566292\
67710105053213729008973121773436382170956191942409859915563249876601\
97309463059908818473774872128141896864070835259683384180928526600888\
17480854811931632353621014638284918544379784608050029606475137979896\
79160729736625134310450643341951675749112836007180865039256361941093\
99844921135320096085772541537129637055451495234892640418746420370197\
76655592198723057553855194566534999101921182723711243608938705766658\
35660299983828999383637476407321955462859142012030390036241831962713\
40429407146441598507165243069127531565881439971034178400174881243483\
00001434950666035560134867554719667076133414445044258086968145695386\
00575860256380332451841441394317283433596457253185221717167880159573\
60478649571700878049257386910142909926740023800166057094445463624601\
79490246367497489548435683835329410376623483996271147060314994344869\
89606855219181727424853876740423210027967733989284801813769926906846\
45570461348452758744643550541290031199432061998646306091218518879810\
17848488755494879341886158379140088252013009193050706458824793551984\
39285914868159111542391208521561221610797141925061986437418522494485\
59871215531081904861310222368465288125816137210222223075106739997863\
76953125");;
testing_function "power_big_int_positive_big_int";;
test 1
eq_big_int
(power_big_int_positive_big_int (big_int_of_int 2) (big_int_of_int 10),
big_int_of_int 1024);;
test 2
eq_big_int
(power_big_int_positive_big_int (big_int_of_int 2) (big_int_of_int 65),
big_int_of_string "36893488147419103232");;
test 3
eq_big_int
(power_big_int_positive_big_int
(big_int_of_string "3") (big_int_of_string "47"),
big_int_of_string "26588814358957503287787");;
test 4
eq_big_int
(power_big_int_positive_big_int
(big_int_of_string "200000000000000") (big_int_of_int 34),
big_int_of_string
"17179869184000000000000000000000000000000000000000000000000000000000\
00000000000000000000000000000000000000000000000000000000000000000000\
00000000000000000000000000000000000000000000000000000000000000000000\
00000000000000000000000000000000000000000000000000000000000000000000\
00000000000000000000000000000000000000000000000000000000000000000000\
00000000000000000000000000000000000000000000000000000000000000000000\
00000000000000000000000000000000000000000000000000000000000000000000\
00000000000");;
test 5
eq_big_int
(power_big_int_positive_big_int (big_int_of_string "2197609328765")
(big_int_of_string "243"),
big_int_of_string
"12415638672345366257764851943822299490113545698929764576040102857365\
27920436565335427676982530274588056944387957287793378051852205028658\
73008292720317554332284838709453634119919368441951233982592586680844\
20765201140575612595182857026804842796931784944918059630667794516774\
58498235838834599150657873894983300999081942159304585449505963892008\
97855706440206825609657816209327492197604711437269361628626691080334\
38432768885637928268354258860147333786379766583179851226375449161073\
10396958979998161989562418169797611757651190037273397850239552735199\
63719988832594486235837899145390948533078339399890545062510060406048\
61331200657727576638170520036143007285549092686618686739320973444703\
33342725604091818763255601206325426337211467746377586080108631634250\
11232258578207762608797108802386708549785680783113606089879687396654\
54004281165259352412815385041917713969718327109245777066079665194617\
29230093411050053217775067781725651590160086483960457766025246936489\
92234225900994076609973190516835778346886551506344097474301175288686\
25662752919718480402972207084177612056491949911377568680526080633587\
33230060757162252611388973328501680433819585006035301408574879645573\
47126018243568976860515247053858204554293343161581801846081341003624\
22906934772131205632200433218165757307182816260714026614324014553342\
77303133877636489457498062819003614421295692889321460150481573909330\
77301946991278225819671075907191359721824291923283322225480199446258\
03302645587072103949599624444368321734975586414930425964782010567575\
43333331963876294983400462908871215572514487548352925949663431718284\
14589547315559936497408670231851521193150991888789948397029796279240\
53117024758684807981605608837291399377902947471927467827290844733264\
70881963357258978768427852958888430774360783419404195056122644913454\
24537375432013012467418602205343636983874410969339344956536142566292\
67710105053213729008973121773436382170956191942409859915563249876601\
97309463059908818473774872128141896864070835259683384180928526600888\
17480854811931632353621014638284918544379784608050029606475137979896\
79160729736625134310450643341951675749112836007180865039256361941093\
99844921135320096085772541537129637055451495234892640418746420370197\
76655592198723057553855194566534999101921182723711243608938705766658\
35660299983828999383637476407321955462859142012030390036241831962713\
40429407146441598507165243069127531565881439971034178400174881243483\
00001434950666035560134867554719667076133414445044258086968145695386\
00575860256380332451841441394317283433596457253185221717167880159573\
60478649571700878049257386910142909926740023800166057094445463624601\
79490246367497489548435683835329410376623483996271147060314994344869\
89606855219181727424853876740423210027967733989284801813769926906846\
45570461348452758744643550541290031199432061998646306091218518879810\
17848488755494879341886158379140088252013009193050706458824793551984\
39285914868159111542391208521561221610797141925061986437418522494485\
59871215531081904861310222368465288125816137210222223075106739997863\
76953125");;
test 6
eq_big_int
(power_big_int_positive_big_int (big_int_of_int 1)
(big_int_of_string "1000000000000000000000"),
big_int_of_int 1);;
test 7
eq_big_int
(power_big_int_positive_big_int (big_int_of_int (-1))
(big_int_of_string "1000000000000000000000"),
big_int_of_int 1);;
test 8
eq_big_int
(power_big_int_positive_big_int (big_int_of_int (-1))
(big_int_of_string "1000000000000000000001"),
big_int_of_int (-1));;
test 9
eq_big_int
(power_big_int_positive_big_int (big_int_of_int 0)
(big_int_of_string "1000000000000000000000"),
big_int_of_int 0);;
testing_function "square_big_int";;
test 1 eq_big_int
(square_big_int (big_int_of_string "0"), big_int_of_string "0");;
test 2 eq_big_int
(square_big_int (big_int_of_string "1"), big_int_of_string "1");;
test 3 eq_big_int
(square_big_int (big_int_of_string "-1"), big_int_of_string "1");;
test 4 eq_big_int
(square_big_int (big_int_of_string "-7"), big_int_of_string "49");;
testing_function "big_int_of_nativeint";;
test 1 eq_big_int
(big_int_of_nativeint 0n, zero_big_int);;
test 2 eq_big_int
(big_int_of_nativeint 1234n, big_int_of_string "1234");;
test 3 eq_big_int
(big_int_of_nativeint (-1234n), big_int_of_string "-1234");;
testing_function "nativeint_of_big_int";;
test 1 eq_nativeint
(nativeint_of_big_int zero_big_int, 0n);;
test 2 eq_nativeint
(nativeint_of_big_int (big_int_of_string "1234"), 1234n);;
test 2 eq_nativeint
(nativeint_of_big_int (big_int_of_string "-1234"), -1234n);;
testing_function "big_int_of_int32";;
test 1 eq_big_int
(big_int_of_int32 0l, zero_big_int);;
test 2 eq_big_int
(big_int_of_int32 2147483647l, big_int_of_string "2147483647");;
test 3 eq_big_int
(big_int_of_int32 (-2147483648l), big_int_of_string "-2147483648");;
testing_function "int32_of_big_int";;
test 1 eq_int32
(int32_of_big_int zero_big_int, 0l);;
test 2 eq_int32
(int32_of_big_int (big_int_of_string "2147483647"), 2147483647l);;
test 3 eq_int32
(int32_of_big_int (big_int_of_string "-2147483648"), -2147483648l);;
test 4 eq_int32
(int32_of_big_int (big_int_of_string "-2147"), -2147l);;
let should_fail s =
try ignore (int32_of_big_int (big_int_of_string s)); 0
with Failure _ -> 1;;
test 5 eq_int
(should_fail "2147483648", 1);;
test 6 eq_int
(should_fail "-2147483649", 1);;
test 7 eq_int
(should_fail "4294967296", 1);;
test 8 eq_int
(should_fail "18446744073709551616", 1);;
testing_function "big_int_of_int64";;
test 1 eq_big_int
(big_int_of_int64 0L, zero_big_int);;
test 2 eq_big_int
(big_int_of_int64 9223372036854775807L,
big_int_of_string "9223372036854775807");;
test 3 eq_big_int
(big_int_of_int64 (-9223372036854775808L),
big_int_of_string "-9223372036854775808");;
test 4 eq_big_int (*PR#4792*)
(big_int_of_int64 (Int64.of_int32 Int32.min_int),
big_int_of_string "-2147483648");;
test 5 eq_big_int
(big_int_of_int64 1234L, big_int_of_string "1234");;
test 6 eq_big_int
(big_int_of_int64 0x1234567890ABCDEFL,
big_int_of_string "1311768467294899695");;
test 7 eq_big_int
(big_int_of_int64 (-1234L), big_int_of_string "-1234");;
test 8 eq_big_int
(big_int_of_int64 (-0x1234567890ABCDEFL),
big_int_of_string "-1311768467294899695");;
testing_function "int64_of_big_int";;
test 1 eq_int64
(int64_of_big_int zero_big_int, 0L);;
test 2 eq_int64
(int64_of_big_int (big_int_of_string "9223372036854775807"),
9223372036854775807L);;
test 3 eq_int64
(int64_of_big_int (big_int_of_string "-9223372036854775808"),
-9223372036854775808L);;
test 4 eq_int64
(int64_of_big_int (big_int_of_string "-9223372036854775"),
-9223372036854775L);;
test 5 eq_int64 (* PR#4804 *)
(int64_of_big_int (big_int_of_string "2147483648"), 2147483648L);;
let should_fail s =
try ignore (int64_of_big_int (big_int_of_string s)); 0
with Failure _ -> 1;;
test 6 eq_int
(should_fail "9223372036854775808", 1);;
test 7 eq_int
(should_fail "-9223372036854775809", 1);;
test 8 eq_int
(should_fail "18446744073709551616", 1);;
build a 128 - bit big int from two int64
let big_int_128 hi lo =
add_big_int (mult_big_int (big_int_of_int64 hi)
(big_int_of_string "18446744073709551616"))
(big_int_of_int64 lo);;
let h1 = 0x7fd05b7ee46a29f8L
and h2 = 0x64b28b8ee70b6e6dL
and h3 = 0x58546e563f5b44f0L
and h4 = 0x1db72f6377ff3ec6L
and h5 = 0x4f9bb0a19c543cb1L;;
testing_function "and_big_int";;
test 1 eq_big_int
(and_big_int unit_big_int zero_big_int, zero_big_int);;
test 2 eq_big_int
(and_big_int zero_big_int unit_big_int, zero_big_int);;
test 3 eq_big_int
(and_big_int unit_big_int unit_big_int, unit_big_int);;
test 4 eq_big_int
(and_big_int (big_int_128 h1 h2) (big_int_128 h3 h4),
big_int_128 (Int64.logand h1 h3) (Int64.logand h2 h4));;
test 5 eq_big_int
(and_big_int (big_int_128 h1 h2) (big_int_of_int64 h5),
big_int_of_int64 (Int64.logand h2 h5));;
test 6 eq_big_int
(and_big_int (big_int_of_int64 h5) (big_int_128 h3 h4) ,
big_int_of_int64 (Int64.logand h5 h4));;
testing_function "or_big_int";;
test 1 eq_big_int
(or_big_int unit_big_int zero_big_int, unit_big_int);;
test 2 eq_big_int
(or_big_int zero_big_int unit_big_int, unit_big_int);;
test 3 eq_big_int
(or_big_int unit_big_int unit_big_int, unit_big_int);;
test 4 eq_big_int
(or_big_int (big_int_128 h1 h2) (big_int_128 h3 h4),
big_int_128 (Int64.logor h1 h3) (Int64.logor h2 h4));;
test 5 eq_big_int
(or_big_int (big_int_128 h1 h2) (big_int_of_int64 h5),
big_int_128 h1 (Int64.logor h2 h5));;
test 6 eq_big_int
(or_big_int (big_int_of_int64 h5) (big_int_128 h3 h4) ,
big_int_128 h3 (Int64.logor h5 h4));;
testing_function "xor_big_int";;
test 1 eq_big_int
(xor_big_int unit_big_int zero_big_int, unit_big_int);;
test 2 eq_big_int
(xor_big_int zero_big_int unit_big_int, unit_big_int);;
test 3 eq_big_int
(xor_big_int unit_big_int unit_big_int, zero_big_int);;
test 4 eq_big_int
(xor_big_int (big_int_128 h1 h2) (big_int_128 h3 h4),
big_int_128 (Int64.logxor h1 h3) (Int64.logxor h2 h4));;
test 5 eq_big_int
(xor_big_int (big_int_128 h1 h2) (big_int_of_int64 h5),
big_int_128 h1 (Int64.logxor h2 h5));;
test 6 eq_big_int
(xor_big_int (big_int_of_int64 h5) (big_int_128 h3 h4) ,
big_int_128 h3 (Int64.logxor h5 h4));;
testing_function "shift_left_big_int";;
test 1 eq_big_int
(shift_left_big_int unit_big_int 0,
unit_big_int);;
test 2 eq_big_int
(shift_left_big_int unit_big_int 1,
big_int_of_int 2);;
test 2 eq_big_int
(shift_left_big_int unit_big_int 31,
big_int_of_string "2147483648");;
test 3 eq_big_int
(shift_left_big_int unit_big_int 64,
big_int_of_string "18446744073709551616");;
test 4 eq_big_int
(shift_left_big_int unit_big_int 95,
big_int_of_string "39614081257132168796771975168");;
test 5 eq_big_int
(shift_left_big_int (big_int_of_string "39614081257132168796771975168") 67,
big_int_of_string "5846006549323611672814739330865132078623730171904");;
test 6 eq_big_int
(shift_left_big_int (big_int_of_string "-39614081257132168796771975168") 67,
big_int_of_string "-5846006549323611672814739330865132078623730171904");;
testing_function "shift_right_big_int";;
test 1 eq_big_int
(shift_right_big_int unit_big_int 0,
unit_big_int);;
test 2 eq_big_int
(shift_right_big_int (big_int_of_int 12345678) 3,
big_int_of_int 1543209);;
test 3 eq_big_int
(shift_right_big_int (big_int_of_string "5299989648942") 32,
big_int_of_int 1234);;
test 4 eq_big_int
(shift_right_big_int (big_int_of_string
"5846006549323611672814739330865132078623730171904")
67,
big_int_of_string "39614081257132168796771975168");;
test 5 eq_big_int
(shift_right_big_int (big_int_of_string "-5299989648942") 32,
big_int_of_int (-1235));;
test 6 eq_big_int
(shift_right_big_int (big_int_of_string "-16570089876543209725755392") 27,
big_int_of_string "-123456790123456789");;
testing_function "shift_right_towards_zero_big_int";;
test 1 eq_big_int
(shift_right_towards_zero_big_int (big_int_of_string "-5299989648942") 32,
big_int_of_int (-1234));;
test 2 eq_big_int
(shift_right_towards_zero_big_int (big_int_of_string
"-16570089876543209725755392")
27,
big_int_of_string "-123456790123456789");;
testing_function "extract_big_int";;
test 1 eq_big_int
(extract_big_int (big_int_of_int64 0x123456789ABCDEFL) 3 13,
big_int_of_int 6589);;
test 2 eq_big_int
(extract_big_int (big_int_128 h1 h2) 67 12,
big_int_of_int 1343);;
test 3 eq_big_int
(extract_big_int (big_int_of_string "-1844674407370955178") 37 9,
big_int_of_int 307);;
test 4 eq_big_int
(extract_big_int unit_big_int 2048 254,
zero_big_int);;
test 5 eq_big_int
(extract_big_int (big_int_of_int64 0x123456789ABCDEFL) 0 32,
big_int_of_int64 2309737967L);;
test 6 eq_big_int
(extract_big_int (big_int_of_int (-1)) 0 16,
big_int_of_int 0xFFFF);;
test 7 eq_big_int
(extract_big_int (big_int_of_int (-1)) 1027 12,
big_int_of_int 0xFFF);;
test 8 eq_big_int
(extract_big_int (big_int_of_int (-1234567)) 0 16,
big_int_of_int 10617);;
test 9 eq_big_int
(extract_big_int (minus_big_int (power_int_positive_int 2 64)) 64 20,
big_int_of_int 0xFFFFF);;
test 10 eq_big_int
(extract_big_int (pred_big_int (minus_big_int (power_int_positive_int 2 64)))
64 20,
big_int_of_int 0xFFFFE);;
testing_function "hashing of big integers";;
test 1 eq_int (Hashtbl.hash zero_big_int,
955772237);;
test 2 eq_int (Hashtbl.hash unit_big_int,
992063522);;
test 3 eq_int (Hashtbl.hash (minus_big_int unit_big_int),
161678167);;
test 4 eq_int (Hashtbl.hash (big_int_of_string "123456789123456789"),
755417385);;
test 5 eq_int (Hashtbl.hash (sub_big_int
(big_int_of_string "123456789123456789")
(big_int_of_string "123456789123456789")),
955772237);;
test 6 eq_int (Hashtbl.hash (sub_big_int
(big_int_of_string "123456789123456789")
(big_int_of_string "123456789123456788")),
992063522);;
testing_function "float_of_big_int";;
test 1 eq_float (float_of_big_int zero_big_int, 0.0);;
test 2 eq_float (float_of_big_int unit_big_int, 1.0);;
test 3 eq_float (float_of_big_int (minus_big_int unit_big_int), -1.0);;
test 4 eq_float (float_of_big_int (shift_left_big_int unit_big_int 1024),
infinity);;
test 5 eq_float (float_of_big_int (shift_left_big_int unit_big_int 1023),
ldexp 1.0 1023);;
Some random int64 values
let ok = ref true in
for i = 1 to 100 do
let n = Random.int64 Int64.max_int in
if not (eq_float (float_of_big_int (big_int_of_int64 n)) (Int64.to_float n))
then ok := false;
let n = Int64.neg n in
if not (eq_float (float_of_big_int (big_int_of_int64 n)) (Int64.to_float n))
then ok := false
done;
test 6 eq (!ok, true);;
Some random int64 values scaled by some random power of 2
let ok = ref true in
for i = 1 to 1000 do
let n = Random.int64 Int64.max_int in
let exp = Random.int 1200 in
if not (eq_float
(float_of_big_int
(shift_left_big_int (big_int_of_int64 n) exp))
(ldexp (Int64.to_float n) exp))
then ok := false;
let n = Int64.neg n in
if not (eq_float
(float_of_big_int
(shift_left_big_int (big_int_of_int64 n) exp))
(ldexp (Int64.to_float n) exp))
then ok := false
done;
test 7 eq (!ok, true);;
(* Round to nearest even *)
let ok = ref true in
for i = 0 to 15 do
let n = Int64.(add 0xfffffffffffff0L (of_int i)) in
if not (eq_float
(float_of_big_int
(shift_left_big_int (big_int_of_int64 n) 32))
(ldexp (Int64.to_float n) 32))
then ok := false
done;
test 8 eq (!ok, true);;
| null | https://raw.githubusercontent.com/ocsigen/ocaml-eliom/497c6707f477cb3086dc6d8124384e74a8c379ae/testsuite/tests/lib-num/test_big_ints.ml | ocaml | ************************************************************************
OCaml
en Automatique.
All rights reserved. This file is distributed under the terms of
special exception on linking described in the file LICENSE.
************************************************************************
Should be true
Should be false
Successor of biggest_int is not an int
Negation of monster_int (as a big_int) is not an int
To hell with efficiency
PR#4792
PR#4804
Round to nearest even | , projet Cristal , INRIA Rocquencourt
Copyright 1996 Institut National de Recherche en Informatique et
the GNU Lesser General Public License version 2.1 , with the
open Test;;
open Nat;;
open Big_int;;
open List;;
testing_function "compare_big_int";;
test 1
eq_int (compare_big_int zero_big_int zero_big_int, 0);;
test 2
eq_int (compare_big_int zero_big_int (big_int_of_int 1), (-1));;
test 3
eq_int (compare_big_int zero_big_int (big_int_of_int (-1)), 1);;
test 4
eq_int (compare_big_int (big_int_of_int 1) zero_big_int, 1);;
test 5
eq_int (compare_big_int (big_int_of_int (-1)) zero_big_int, (-1));;
test 6
eq_int (compare_big_int (big_int_of_int 1) (big_int_of_int 1), 0);;
test 7
eq_int (compare_big_int (big_int_of_int (-1)) (big_int_of_int (-1)), 0);;
test 8
eq_int (compare_big_int (big_int_of_int 1) (big_int_of_int (-1)), 1);;
test 9
eq_int (compare_big_int (big_int_of_int (-1)) (big_int_of_int 1), (-1));;
test 10
eq_int (compare_big_int (big_int_of_int 1) (big_int_of_int 2), (-1));;
test 11
eq_int (compare_big_int (big_int_of_int 2) (big_int_of_int 1), 1);;
test 12
eq_int (compare_big_int (big_int_of_int (-1)) (big_int_of_int (-2)), 1);;
test 13
eq_int (compare_big_int (big_int_of_int (-2)) (big_int_of_int (-1)), (-1));;
testing_function "pred_big_int";;
test 1
eq_big_int (pred_big_int zero_big_int, big_int_of_int (-1));;
test 2
eq_big_int (pred_big_int unit_big_int, zero_big_int);;
test 3
eq_big_int (pred_big_int (big_int_of_int (-1)), big_int_of_int (-2));;
testing_function "succ_big_int";;
test 1
eq_big_int (succ_big_int zero_big_int, unit_big_int);;
test 2
eq_big_int (succ_big_int unit_big_int, big_int_of_int 2);;
test 3
eq_big_int (succ_big_int (big_int_of_int (-1)), zero_big_int);;
testing_function "add_big_int";;
test 1
eq_big_int (add_big_int zero_big_int zero_big_int, zero_big_int);;
test 2
eq_big_int (add_big_int zero_big_int (big_int_of_int 1),
big_int_of_int 1);;
test 3
eq_big_int (add_big_int (big_int_of_int 1) zero_big_int,
big_int_of_int 1);;
test 4
eq_big_int (add_big_int zero_big_int (big_int_of_int (-1)),
big_int_of_int (-1));;
test 5
eq_big_int (add_big_int (big_int_of_int (-1)) zero_big_int,
big_int_of_int (-1));;
test 6
eq_big_int (add_big_int (big_int_of_int 1) (big_int_of_int 1),
big_int_of_int 2);;
test 7
eq_big_int (add_big_int (big_int_of_int 1) (big_int_of_int 2),
big_int_of_int 3);;
test 8
eq_big_int (add_big_int (big_int_of_int 2) (big_int_of_int 1),
big_int_of_int 3);;
test 9
eq_big_int (add_big_int (big_int_of_int (-1)) (big_int_of_int (-1)),
big_int_of_int (-2));;
test 10
eq_big_int (add_big_int (big_int_of_int (-1)) (big_int_of_int (-2)),
big_int_of_int (-3));;
test 11
eq_big_int (add_big_int (big_int_of_int (-2)) (big_int_of_int (-1)),
big_int_of_int (-3));;
test 12
eq_big_int (add_big_int (big_int_of_int 1) (big_int_of_int (-1)),
zero_big_int);;
test 13
eq_big_int (add_big_int (big_int_of_int (-1)) (big_int_of_int 1),
zero_big_int);;
test 14
eq_big_int (add_big_int (big_int_of_int 1) (big_int_of_int (-2)),
big_int_of_int (-1));;
test 15
eq_big_int (add_big_int (big_int_of_int (-2)) (big_int_of_int 1),
big_int_of_int (-1));;
test 16
eq_big_int (add_big_int (big_int_of_int (-1)) (big_int_of_int 2),
big_int_of_int 1);;
test 17
eq_big_int (add_big_int (big_int_of_int 2) (big_int_of_int (-1)),
big_int_of_int 1);;
testing_function "sub_big_int";;
test 1
eq_big_int (sub_big_int zero_big_int zero_big_int, zero_big_int);;
test 2
eq_big_int (sub_big_int zero_big_int (big_int_of_int 1),
big_int_of_int (-1));;
test 3
eq_big_int (sub_big_int (big_int_of_int 1) zero_big_int,
big_int_of_int 1);;
test 4
eq_big_int (sub_big_int zero_big_int (big_int_of_int (-1)),
big_int_of_int 1);;
test 5
eq_big_int (sub_big_int (big_int_of_int (-1)) zero_big_int,
big_int_of_int (-1));;
test 6
eq_big_int (sub_big_int (big_int_of_int 1) (big_int_of_int 1),
zero_big_int);;
test 7
eq_big_int (sub_big_int (big_int_of_int 1) (big_int_of_int 2),
big_int_of_int (-1));;
test 8
eq_big_int (sub_big_int (big_int_of_int 2) (big_int_of_int 1),
big_int_of_int 1);;
test 9
eq_big_int (sub_big_int (big_int_of_int (-1)) (big_int_of_int (-1)),
zero_big_int);;
test 10
eq_big_int (sub_big_int (big_int_of_int (-1)) (big_int_of_int (-2)),
big_int_of_int 1);;
test 11
eq_big_int (sub_big_int (big_int_of_int (-2)) (big_int_of_int (-1)),
big_int_of_int (-1));;
test 12
eq_big_int (sub_big_int (big_int_of_int 1) (big_int_of_int (-1)),
big_int_of_int 2);;
test 13
eq_big_int (sub_big_int (big_int_of_int (-1)) (big_int_of_int 1),
big_int_of_int (-2));;
test 14
eq_big_int (sub_big_int (big_int_of_int 1) (big_int_of_int (-2)),
big_int_of_int 3);;
test 15
eq_big_int (sub_big_int (big_int_of_int (-2)) (big_int_of_int 1),
big_int_of_int (-3));;
test 16
eq_big_int (sub_big_int (big_int_of_int (-1)) (big_int_of_int 2),
big_int_of_int (-3));;
test 17
eq_big_int (sub_big_int (big_int_of_int 2) (big_int_of_int (-1)),
big_int_of_int 3);;
testing_function "mult_int_big_int";;
test 1
eq_big_int (mult_int_big_int 0 (big_int_of_int 3), zero_big_int);;
test 2
eq_big_int (mult_int_big_int 1 (big_int_of_int 3), big_int_of_int 3);;
test 3
eq_big_int (mult_int_big_int 1 zero_big_int, zero_big_int);;
test 4
eq_big_int (mult_int_big_int 2 (big_int_of_int 3), big_int_of_int 6);;
testing_function "mult_big_int";;
test 1
eq_big_int (mult_big_int zero_big_int zero_big_int,
zero_big_int);;
test 2
eq_big_int (mult_big_int (big_int_of_int 2) (big_int_of_int 3),
big_int_of_int 6);;
test 3
eq_big_int (mult_big_int (big_int_of_int 2) (big_int_of_int (-3)),
big_int_of_int (-6));;
test 4
eq_big_int (mult_big_int (big_int_of_string "12724951")
(big_int_of_string "81749606400"),
big_int_of_string "1040259735709286400");;
test 5
eq_big_int (mult_big_int (big_int_of_string "26542080")
(big_int_of_string "81749606400"),
big_int_of_string "2169804593037312000");;
testing_function "quomod_big_int";;
let (quotient, modulo) =
quomod_big_int (big_int_of_int 1) (big_int_of_int 1) in
test 1 eq_big_int (quotient, big_int_of_int 1) &&
test 2 eq_big_int (modulo, zero_big_int);;
let (quotient, modulo) =
quomod_big_int (big_int_of_int 1) (big_int_of_int (-1)) in
test 3 eq_big_int (quotient, big_int_of_int (-1)) &&
test 4 eq_big_int (modulo, zero_big_int);;
let (quotient, modulo) =
quomod_big_int (big_int_of_int (-1)) (big_int_of_int 1) in
test 5 eq_big_int (quotient, big_int_of_int (-1)) &&
test 6 eq_big_int (modulo, zero_big_int);;
let (quotient, modulo) =
quomod_big_int (big_int_of_int 3) (big_int_of_int 2) in
test 7 eq_big_int (quotient, big_int_of_int 1) &&
test 8 eq_big_int (modulo, big_int_of_int 1);;
let (quotient, modulo) =
quomod_big_int (big_int_of_int 5) (big_int_of_int 3) in
test 9 eq_big_int (quotient, big_int_of_int 1) &&
test 10 eq_big_int (modulo, big_int_of_int 2);;
let (quotient, modulo) =
quomod_big_int (big_int_of_int (-5)) (big_int_of_int 3) in
test 11 eq_big_int (quotient, big_int_of_int (-2)) &&
test 12 eq_big_int (modulo, big_int_of_int 1);;
let (quotient, modulo) =
quomod_big_int (big_int_of_int 1) (big_int_of_int 2) in
test 13 eq_big_int (quotient, zero_big_int) &&
test 14 eq_big_int (modulo, big_int_of_int 1);;
let (quotient, modulo) =
quomod_big_int (big_int_of_int (-1)) (big_int_of_int 3) in
test 15 eq_big_int (quotient, minus_big_int unit_big_int) &&
test 16 eq_big_int (modulo, big_int_of_int 2);;
failwith_test 17
(quomod_big_int (big_int_of_int 1)) zero_big_int
Division_by_zero
;;
let (quotient, modulo) =
quomod_big_int (big_int_of_int 10) (big_int_of_int 20) in
test 18 eq_big_int (quotient, big_int_of_int 0) &&
test 19 eq_big_int (modulo, big_int_of_int 10);;
let (quotient, modulo) =
quomod_big_int (big_int_of_int (-10)) (big_int_of_int 20) in
test 20 eq_big_int (quotient, big_int_of_int (-1)) &&
test 21 eq_big_int (modulo, big_int_of_int 10);;
let (quotient, modulo) =
quomod_big_int (big_int_of_int 10) (big_int_of_int (-20)) in
test 22 eq_big_int (quotient, big_int_of_int 0) &&
test 23 eq_big_int (modulo, big_int_of_int 10);;
let (quotient, modulo) =
quomod_big_int (big_int_of_int (-10)) (big_int_of_int (-20)) in
test 24 eq_big_int (quotient, big_int_of_int 1) &&
test 25 eq_big_int (modulo, big_int_of_int 10);;
testing_function "gcd_big_int";;
test 1
eq_big_int (gcd_big_int zero_big_int zero_big_int,
zero_big_int);;
test 2
eq_big_int (gcd_big_int zero_big_int (big_int_of_int 1),
big_int_of_int 1);;
test 3
eq_big_int (gcd_big_int (big_int_of_int 1) zero_big_int,
big_int_of_int 1);;
test 4
eq_big_int (gcd_big_int (big_int_of_int 1) (big_int_of_int 2),
big_int_of_int 1);;
test 5
eq_big_int (gcd_big_int (big_int_of_int 2) (big_int_of_int 1),
big_int_of_int 1);;
test 6
eq_big_int (gcd_big_int (big_int_of_int 1) (big_int_of_int 1),
big_int_of_int 1);;
test 7
eq_big_int (gcd_big_int (big_int_of_int 9) (big_int_of_int 16),
big_int_of_int 1);;
test 8
eq_big_int (gcd_big_int (big_int_of_int 12) (big_int_of_int 16),
big_int_of_int 4);;
for i = 9 to 28 do
let n1 = Random.int 1000000000
and n2 = Random.int 100000 in
let _ =
test i eq
(int_of_big_int (gcd_big_int (big_int_of_int n1) (big_int_of_int n2)),
gcd_int n1 n2) in
()
done;;
testing_function "int_of_big_int";;
test 1
eq_int (int_of_big_int (big_int_of_int 1), 1);;
test 2
eq_int (int_of_big_int (big_int_of_int(-1)), -1);;
test 3
eq_int (int_of_big_int zero_big_int, 0);;
test 4
eq_int (int_of_big_int (big_int_of_int max_int), max_int);;
test 5
eq_int (int_of_big_int (big_int_of_int min_int), min_int);;
failwith_test 6
(fun () -> int_of_big_int (succ_big_int (big_int_of_int max_int)))
() (Failure "int_of_big_int");;
failwith_test 7
(fun () -> int_of_big_int (pred_big_int (big_int_of_int min_int)))
() (Failure "int_of_big_int");;
failwith_test 8
(fun () -> int_of_big_int (mult_big_int (big_int_of_int min_int)
(big_int_of_int 2)))
() (Failure "int_of_big_int");;
testing_function "is_int_big_int";;
test 1
eq (is_int_big_int (big_int_of_int 1), true);;
test 2
eq (is_int_big_int (big_int_of_int (-1)), true);;
test 3
eq (is_int_big_int (succ_big_int (big_int_of_int biggest_int)), false);;
test 4
eq (int_of_big_int (big_int_of_int monster_int), monster_int);;
test 5
eq (is_int_big_int (big_int_of_string (string_of_int biggest_int)), true);;
test 6
eq (is_int_big_int (big_int_of_string (string_of_int least_int)), true);;
test 7
eq (is_int_big_int (big_int_of_string (string_of_int monster_int)), true);;
test 8
eq (is_int_big_int (succ_big_int (big_int_of_int (biggest_int))), false);;
test 9
eq (is_int_big_int
(succ_big_int (succ_big_int (big_int_of_int (biggest_int)))), false);;
test 10
eq (is_int_big_int
(minus_big_int (big_int_of_string (string_of_int monster_int))), false);;
testing_function "sys_string_of_big_int";;
test 1
eq_string (string_of_big_int (big_int_of_int 1), "1");;
testing_function "big_int_of_string";;
test 1
eq_big_int (big_int_of_string "1", big_int_of_int 1);;
test 2
eq_big_int (big_int_of_string "-1", big_int_of_int (-1));;
test 4
eq_big_int (big_int_of_string "0", zero_big_int);;
failwith_test 5 big_int_of_string "sdjdkfighdgf"
(Failure "invalid digit");;
test 6
eq_big_int (big_int_of_string "123", big_int_of_int 123);;
test 7
eq_big_int (big_int_of_string "+3456", big_int_of_int 3456);;
test 9
eq_big_int (big_int_of_string "-3456", big_int_of_int (-3456));;
let l = rev [
"174679877494298468451661416292903906557638850173895426081611831060970135303";
"044177587617233125776581034213405720474892937404345377707655788096850784519";
"539374048533324740018513057210881137248587265169064879918339714405948322501";
"445922724181830422326068913963858377101914542266807281471620827145038901025";
"322784396182858865537924078131032036927586614781817695777639491934361211399";
"888524140253852859555118862284235219972858420374290985423899099648066366558";
"238523612660414395240146528009203942793935957539186742012316630755300111472";
"852707974927265572257203394961525316215198438466177260614187266288417996647";
"132974072337956513457924431633191471716899014677585762010115338540738783163";
"739223806648361958204720897858193606022290696766988489073354139289154127309";
"916985231051926209439373780384293513938376175026016587144157313996556653811";
"793187841050456120649717382553450099049321059330947779485538381272648295449";
"847188233356805715432460040567660999184007627415398722991790542115164516290";
"619821378529926683447345857832940144982437162642295073360087284113248737998";
"046564369129742074737760485635495880623324782103052289938185453627547195245";
"688272436219215066430533447287305048225780425168823659431607654712261368560";
"702129351210471250717394128044019490336608558608922841794819375031757643448";
"32"
] in
let bi1 = big_int_of_string (implode (rev l)) in
let bi2 = big_int_of_string (implode (rev ("3" :: tl l))) in
test 10
eq_big_int (bi1, (add_big_int (mult_big_int bi2 (big_int_of_string "10"))
(big_int_of_string "2")))
test 11
& &
eq_big_int ( bi1 , ( add_big_int ( mult_big_int bi2 ( big_int_of_string " 10e0 " ) )
( big_int_of_string " 20e-1 " ) ) ) & &
test 12
eq_big_int ( minus_big_int bi1 ,
( add_big_int ( mult_big_int bi2 ( big_int_of_string " -10e0 " ) )
( big_int_of_string " -20e-1 " ) ) ) & &
test 13
eq_big_int ( bi1 , ( add_big_int ( mult_big_int bi2 ( big_int_of_string " +10e0 " ) )
( big_int_of_string " +20e-1 " ) ) ) & &
test 14
eq_big_int ( minus_big_int bi1 ,
( add_big_int ( mult_big_int bi2 ( big_int_of_string " -10e+0 " ) )
( big_int_of_string " -20e-1 " ) ) ) & &
test 15
eq_big_int ( minus_big_int bi1 ,
( add_big_int ( mult_big_int bi2 ( big_int_of_string " -1e+1 " ) )
( big_int_of_string " -2e-0 " ) ) ) & &
test 16
eq_big_int ( minus_big_int bi1 ,
( add_big_int ( mult_big_int bi2 ( big_int_of_string " -0.1e+2 " ) )
( big_int_of_string " -2.0e-0 " ) ) ) & &
test 17
eq_big_int ( minus_big_int bi1 ,
( add_big_int ( mult_big_int bi2 ( big_int_of_string " -1.000e+1 " ) )
( big_int_of_string " -0.02e2 " ) ) )
&&
eq_big_int (bi1, (add_big_int (mult_big_int bi2 (big_int_of_string "10e0"))
(big_int_of_string "20e-1"))) &&
test 12
eq_big_int (minus_big_int bi1,
(add_big_int (mult_big_int bi2 (big_int_of_string "-10e0"))
(big_int_of_string "-20e-1"))) &&
test 13
eq_big_int (bi1, (add_big_int (mult_big_int bi2 (big_int_of_string "+10e0"))
(big_int_of_string "+20e-1"))) &&
test 14
eq_big_int (minus_big_int bi1,
(add_big_int (mult_big_int bi2 (big_int_of_string "-10e+0"))
(big_int_of_string "-20e-1"))) &&
test 15
eq_big_int (minus_big_int bi1,
(add_big_int (mult_big_int bi2 (big_int_of_string "-1e+1"))
(big_int_of_string "-2e-0"))) &&
test 16
eq_big_int (minus_big_int bi1,
(add_big_int (mult_big_int bi2 (big_int_of_string "-0.1e+2"))
(big_int_of_string "-2.0e-0"))) &&
test 17
eq_big_int (minus_big_int bi1,
(add_big_int (mult_big_int bi2 (big_int_of_string "-1.000e+1"))
(big_int_of_string "-0.02e2")))*)
;;
test 18
eq_big_int (big_int_of_string "0xAbC", big_int_of_int 0xABC);;
test 19
eq_big_int (big_int_of_string "-0o452", big_int_of_int (-0o452));;
test 20
eq_big_int (big_int_of_string "0B110101", big_int_of_int 53);;
test 21
eq_big_int (big_int_of_string "0b11_01_01", big_int_of_int 53);;
testing_function "power_base_int";;
test 1
eq_big_int (big_int_of_nat (power_base_int 10 0), unit_big_int)
;;
test 2
eq_big_int (big_int_of_nat (power_base_int 10 8), big_int_of_int 100000000)
;;
test 3
eq_big_int (big_int_of_nat (power_base_int 2 (length_of_int + 2)),
big_int_of_nat (let nat = make_nat 2 in
set_digit_nat nat 1 1;
nat))
;;
testing_function "base_power_big_int";;
test 1
eq_big_int (base_power_big_int 10 0 (big_int_of_int 2), big_int_of_int 2);;
test 2
eq_big_int (base_power_big_int 10 2 (big_int_of_int 2), big_int_of_int 200);;
test 3
eq_big_int (base_power_big_int 10 1 (big_int_of_int 123), big_int_of_int 1230)
;;
testing_function "power_int_positive_big_int";;
test 1
eq_big_int (power_int_positive_big_int 2 (big_int_of_int 10),
big_int_of_int 1024);;
test 2
eq_big_int
(power_int_positive_big_int 2 (big_int_of_int 65),
big_int_of_string "36893488147419103232");;
test 3
eq_big_int
(power_int_positive_big_int 3 (big_int_of_string "47"),
big_int_of_string "26588814358957503287787");;
test 4
eq_big_int
(power_int_positive_big_int 1 (big_int_of_string "1000000000000000000000"),
big_int_of_int 1);;
test 5
eq_big_int
(power_int_positive_big_int (-1) (big_int_of_string "1000000000000000000000"),
big_int_of_int 1);;
test 6
eq_big_int
(power_int_positive_big_int (-1) (big_int_of_string "1000000000000000000001"),
big_int_of_int (-1));;
test 7
eq_big_int
(power_int_positive_big_int 0 (big_int_of_string "1000000000000000000000"),
big_int_of_int 0);;
testing_function "power_big_int_positive_int";;
test 1
eq_big_int (power_big_int_positive_int (big_int_of_int 2) 10,
big_int_of_int 1024);;
test 2
eq_big_int
(power_big_int_positive_int (big_int_of_int 100) 20,
big_int_of_string "10000000000000000000000000000000000000000");;
test 3
eq_big_int
(power_big_int_positive_int (big_int_of_string "3") 47,
big_int_of_string "26588814358957503287787");;
test 4
eq_big_int
(power_big_int_positive_int (big_int_of_string "200000000000000") 34,
big_int_of_string
"17179869184000000000000000000000000000000000000000000000000000000000\
00000000000000000000000000000000000000000000000000000000000000000000\
00000000000000000000000000000000000000000000000000000000000000000000\
00000000000000000000000000000000000000000000000000000000000000000000\
00000000000000000000000000000000000000000000000000000000000000000000\
00000000000000000000000000000000000000000000000000000000000000000000\
00000000000000000000000000000000000000000000000000000000000000000000\
00000000000");;
test 5
eq_big_int
(power_big_int_positive_int (big_int_of_string "2197609328765") 243,
big_int_of_string
"12415638672345366257764851943822299490113545698929764576040102857365\
27920436565335427676982530274588056944387957287793378051852205028658\
73008292720317554332284838709453634119919368441951233982592586680844\
20765201140575612595182857026804842796931784944918059630667794516774\
58498235838834599150657873894983300999081942159304585449505963892008\
97855706440206825609657816209327492197604711437269361628626691080334\
38432768885637928268354258860147333786379766583179851226375449161073\
10396958979998161989562418169797611757651190037273397850239552735199\
63719988832594486235837899145390948533078339399890545062510060406048\
61331200657727576638170520036143007285549092686618686739320973444703\
33342725604091818763255601206325426337211467746377586080108631634250\
11232258578207762608797108802386708549785680783113606089879687396654\
54004281165259352412815385041917713969718327109245777066079665194617\
29230093411050053217775067781725651590160086483960457766025246936489\
92234225900994076609973190516835778346886551506344097474301175288686\
25662752919718480402972207084177612056491949911377568680526080633587\
33230060757162252611388973328501680433819585006035301408574879645573\
47126018243568976860515247053858204554293343161581801846081341003624\
22906934772131205632200433218165757307182816260714026614324014553342\
77303133877636489457498062819003614421295692889321460150481573909330\
77301946991278225819671075907191359721824291923283322225480199446258\
03302645587072103949599624444368321734975586414930425964782010567575\
43333331963876294983400462908871215572514487548352925949663431718284\
14589547315559936497408670231851521193150991888789948397029796279240\
53117024758684807981605608837291399377902947471927467827290844733264\
70881963357258978768427852958888430774360783419404195056122644913454\
24537375432013012467418602205343636983874410969339344956536142566292\
67710105053213729008973121773436382170956191942409859915563249876601\
97309463059908818473774872128141896864070835259683384180928526600888\
17480854811931632353621014638284918544379784608050029606475137979896\
79160729736625134310450643341951675749112836007180865039256361941093\
99844921135320096085772541537129637055451495234892640418746420370197\
76655592198723057553855194566534999101921182723711243608938705766658\
35660299983828999383637476407321955462859142012030390036241831962713\
40429407146441598507165243069127531565881439971034178400174881243483\
00001434950666035560134867554719667076133414445044258086968145695386\
00575860256380332451841441394317283433596457253185221717167880159573\
60478649571700878049257386910142909926740023800166057094445463624601\
79490246367497489548435683835329410376623483996271147060314994344869\
89606855219181727424853876740423210027967733989284801813769926906846\
45570461348452758744643550541290031199432061998646306091218518879810\
17848488755494879341886158379140088252013009193050706458824793551984\
39285914868159111542391208521561221610797141925061986437418522494485\
59871215531081904861310222368465288125816137210222223075106739997863\
76953125");;
testing_function "power_big_int_positive_big_int";;
test 1
eq_big_int
(power_big_int_positive_big_int (big_int_of_int 2) (big_int_of_int 10),
big_int_of_int 1024);;
test 2
eq_big_int
(power_big_int_positive_big_int (big_int_of_int 2) (big_int_of_int 65),
big_int_of_string "36893488147419103232");;
test 3
eq_big_int
(power_big_int_positive_big_int
(big_int_of_string "3") (big_int_of_string "47"),
big_int_of_string "26588814358957503287787");;
test 4
eq_big_int
(power_big_int_positive_big_int
(big_int_of_string "200000000000000") (big_int_of_int 34),
big_int_of_string
"17179869184000000000000000000000000000000000000000000000000000000000\
00000000000000000000000000000000000000000000000000000000000000000000\
00000000000000000000000000000000000000000000000000000000000000000000\
00000000000000000000000000000000000000000000000000000000000000000000\
00000000000000000000000000000000000000000000000000000000000000000000\
00000000000000000000000000000000000000000000000000000000000000000000\
00000000000000000000000000000000000000000000000000000000000000000000\
00000000000");;
test 5
eq_big_int
(power_big_int_positive_big_int (big_int_of_string "2197609328765")
(big_int_of_string "243"),
big_int_of_string
"12415638672345366257764851943822299490113545698929764576040102857365\
27920436565335427676982530274588056944387957287793378051852205028658\
73008292720317554332284838709453634119919368441951233982592586680844\
20765201140575612595182857026804842796931784944918059630667794516774\
58498235838834599150657873894983300999081942159304585449505963892008\
97855706440206825609657816209327492197604711437269361628626691080334\
38432768885637928268354258860147333786379766583179851226375449161073\
10396958979998161989562418169797611757651190037273397850239552735199\
63719988832594486235837899145390948533078339399890545062510060406048\
61331200657727576638170520036143007285549092686618686739320973444703\
33342725604091818763255601206325426337211467746377586080108631634250\
11232258578207762608797108802386708549785680783113606089879687396654\
54004281165259352412815385041917713969718327109245777066079665194617\
29230093411050053217775067781725651590160086483960457766025246936489\
92234225900994076609973190516835778346886551506344097474301175288686\
25662752919718480402972207084177612056491949911377568680526080633587\
33230060757162252611388973328501680433819585006035301408574879645573\
47126018243568976860515247053858204554293343161581801846081341003624\
22906934772131205632200433218165757307182816260714026614324014553342\
77303133877636489457498062819003614421295692889321460150481573909330\
77301946991278225819671075907191359721824291923283322225480199446258\
03302645587072103949599624444368321734975586414930425964782010567575\
43333331963876294983400462908871215572514487548352925949663431718284\
14589547315559936497408670231851521193150991888789948397029796279240\
53117024758684807981605608837291399377902947471927467827290844733264\
70881963357258978768427852958888430774360783419404195056122644913454\
24537375432013012467418602205343636983874410969339344956536142566292\
67710105053213729008973121773436382170956191942409859915563249876601\
97309463059908818473774872128141896864070835259683384180928526600888\
17480854811931632353621014638284918544379784608050029606475137979896\
79160729736625134310450643341951675749112836007180865039256361941093\
99844921135320096085772541537129637055451495234892640418746420370197\
76655592198723057553855194566534999101921182723711243608938705766658\
35660299983828999383637476407321955462859142012030390036241831962713\
40429407146441598507165243069127531565881439971034178400174881243483\
00001434950666035560134867554719667076133414445044258086968145695386\
00575860256380332451841441394317283433596457253185221717167880159573\
60478649571700878049257386910142909926740023800166057094445463624601\
79490246367497489548435683835329410376623483996271147060314994344869\
89606855219181727424853876740423210027967733989284801813769926906846\
45570461348452758744643550541290031199432061998646306091218518879810\
17848488755494879341886158379140088252013009193050706458824793551984\
39285914868159111542391208521561221610797141925061986437418522494485\
59871215531081904861310222368465288125816137210222223075106739997863\
76953125");;
test 6
eq_big_int
(power_big_int_positive_big_int (big_int_of_int 1)
(big_int_of_string "1000000000000000000000"),
big_int_of_int 1);;
test 7
eq_big_int
(power_big_int_positive_big_int (big_int_of_int (-1))
(big_int_of_string "1000000000000000000000"),
big_int_of_int 1);;
test 8
eq_big_int
(power_big_int_positive_big_int (big_int_of_int (-1))
(big_int_of_string "1000000000000000000001"),
big_int_of_int (-1));;
test 9
eq_big_int
(power_big_int_positive_big_int (big_int_of_int 0)
(big_int_of_string "1000000000000000000000"),
big_int_of_int 0);;
testing_function "square_big_int";;
test 1 eq_big_int
(square_big_int (big_int_of_string "0"), big_int_of_string "0");;
test 2 eq_big_int
(square_big_int (big_int_of_string "1"), big_int_of_string "1");;
test 3 eq_big_int
(square_big_int (big_int_of_string "-1"), big_int_of_string "1");;
test 4 eq_big_int
(square_big_int (big_int_of_string "-7"), big_int_of_string "49");;
testing_function "big_int_of_nativeint";;
test 1 eq_big_int
(big_int_of_nativeint 0n, zero_big_int);;
test 2 eq_big_int
(big_int_of_nativeint 1234n, big_int_of_string "1234");;
test 3 eq_big_int
(big_int_of_nativeint (-1234n), big_int_of_string "-1234");;
testing_function "nativeint_of_big_int";;
test 1 eq_nativeint
(nativeint_of_big_int zero_big_int, 0n);;
test 2 eq_nativeint
(nativeint_of_big_int (big_int_of_string "1234"), 1234n);;
test 2 eq_nativeint
(nativeint_of_big_int (big_int_of_string "-1234"), -1234n);;
testing_function "big_int_of_int32";;
test 1 eq_big_int
(big_int_of_int32 0l, zero_big_int);;
test 2 eq_big_int
(big_int_of_int32 2147483647l, big_int_of_string "2147483647");;
test 3 eq_big_int
(big_int_of_int32 (-2147483648l), big_int_of_string "-2147483648");;
testing_function "int32_of_big_int";;
test 1 eq_int32
(int32_of_big_int zero_big_int, 0l);;
test 2 eq_int32
(int32_of_big_int (big_int_of_string "2147483647"), 2147483647l);;
test 3 eq_int32
(int32_of_big_int (big_int_of_string "-2147483648"), -2147483648l);;
test 4 eq_int32
(int32_of_big_int (big_int_of_string "-2147"), -2147l);;
let should_fail s =
try ignore (int32_of_big_int (big_int_of_string s)); 0
with Failure _ -> 1;;
test 5 eq_int
(should_fail "2147483648", 1);;
test 6 eq_int
(should_fail "-2147483649", 1);;
test 7 eq_int
(should_fail "4294967296", 1);;
test 8 eq_int
(should_fail "18446744073709551616", 1);;
testing_function "big_int_of_int64";;
test 1 eq_big_int
(big_int_of_int64 0L, zero_big_int);;
test 2 eq_big_int
(big_int_of_int64 9223372036854775807L,
big_int_of_string "9223372036854775807");;
test 3 eq_big_int
(big_int_of_int64 (-9223372036854775808L),
big_int_of_string "-9223372036854775808");;
(big_int_of_int64 (Int64.of_int32 Int32.min_int),
big_int_of_string "-2147483648");;
test 5 eq_big_int
(big_int_of_int64 1234L, big_int_of_string "1234");;
test 6 eq_big_int
(big_int_of_int64 0x1234567890ABCDEFL,
big_int_of_string "1311768467294899695");;
test 7 eq_big_int
(big_int_of_int64 (-1234L), big_int_of_string "-1234");;
test 8 eq_big_int
(big_int_of_int64 (-0x1234567890ABCDEFL),
big_int_of_string "-1311768467294899695");;
testing_function "int64_of_big_int";;
test 1 eq_int64
(int64_of_big_int zero_big_int, 0L);;
test 2 eq_int64
(int64_of_big_int (big_int_of_string "9223372036854775807"),
9223372036854775807L);;
test 3 eq_int64
(int64_of_big_int (big_int_of_string "-9223372036854775808"),
-9223372036854775808L);;
test 4 eq_int64
(int64_of_big_int (big_int_of_string "-9223372036854775"),
-9223372036854775L);;
(int64_of_big_int (big_int_of_string "2147483648"), 2147483648L);;
let should_fail s =
try ignore (int64_of_big_int (big_int_of_string s)); 0
with Failure _ -> 1;;
test 6 eq_int
(should_fail "9223372036854775808", 1);;
test 7 eq_int
(should_fail "-9223372036854775809", 1);;
test 8 eq_int
(should_fail "18446744073709551616", 1);;
build a 128 - bit big int from two int64
let big_int_128 hi lo =
add_big_int (mult_big_int (big_int_of_int64 hi)
(big_int_of_string "18446744073709551616"))
(big_int_of_int64 lo);;
let h1 = 0x7fd05b7ee46a29f8L
and h2 = 0x64b28b8ee70b6e6dL
and h3 = 0x58546e563f5b44f0L
and h4 = 0x1db72f6377ff3ec6L
and h5 = 0x4f9bb0a19c543cb1L;;
testing_function "and_big_int";;
test 1 eq_big_int
(and_big_int unit_big_int zero_big_int, zero_big_int);;
test 2 eq_big_int
(and_big_int zero_big_int unit_big_int, zero_big_int);;
test 3 eq_big_int
(and_big_int unit_big_int unit_big_int, unit_big_int);;
test 4 eq_big_int
(and_big_int (big_int_128 h1 h2) (big_int_128 h3 h4),
big_int_128 (Int64.logand h1 h3) (Int64.logand h2 h4));;
test 5 eq_big_int
(and_big_int (big_int_128 h1 h2) (big_int_of_int64 h5),
big_int_of_int64 (Int64.logand h2 h5));;
test 6 eq_big_int
(and_big_int (big_int_of_int64 h5) (big_int_128 h3 h4) ,
big_int_of_int64 (Int64.logand h5 h4));;
testing_function "or_big_int";;
test 1 eq_big_int
(or_big_int unit_big_int zero_big_int, unit_big_int);;
test 2 eq_big_int
(or_big_int zero_big_int unit_big_int, unit_big_int);;
test 3 eq_big_int
(or_big_int unit_big_int unit_big_int, unit_big_int);;
test 4 eq_big_int
(or_big_int (big_int_128 h1 h2) (big_int_128 h3 h4),
big_int_128 (Int64.logor h1 h3) (Int64.logor h2 h4));;
test 5 eq_big_int
(or_big_int (big_int_128 h1 h2) (big_int_of_int64 h5),
big_int_128 h1 (Int64.logor h2 h5));;
test 6 eq_big_int
(or_big_int (big_int_of_int64 h5) (big_int_128 h3 h4) ,
big_int_128 h3 (Int64.logor h5 h4));;
testing_function "xor_big_int";;
test 1 eq_big_int
(xor_big_int unit_big_int zero_big_int, unit_big_int);;
test 2 eq_big_int
(xor_big_int zero_big_int unit_big_int, unit_big_int);;
test 3 eq_big_int
(xor_big_int unit_big_int unit_big_int, zero_big_int);;
test 4 eq_big_int
(xor_big_int (big_int_128 h1 h2) (big_int_128 h3 h4),
big_int_128 (Int64.logxor h1 h3) (Int64.logxor h2 h4));;
test 5 eq_big_int
(xor_big_int (big_int_128 h1 h2) (big_int_of_int64 h5),
big_int_128 h1 (Int64.logxor h2 h5));;
test 6 eq_big_int
(xor_big_int (big_int_of_int64 h5) (big_int_128 h3 h4) ,
big_int_128 h3 (Int64.logxor h5 h4));;
testing_function "shift_left_big_int";;
test 1 eq_big_int
(shift_left_big_int unit_big_int 0,
unit_big_int);;
test 2 eq_big_int
(shift_left_big_int unit_big_int 1,
big_int_of_int 2);;
test 2 eq_big_int
(shift_left_big_int unit_big_int 31,
big_int_of_string "2147483648");;
test 3 eq_big_int
(shift_left_big_int unit_big_int 64,
big_int_of_string "18446744073709551616");;
test 4 eq_big_int
(shift_left_big_int unit_big_int 95,
big_int_of_string "39614081257132168796771975168");;
test 5 eq_big_int
(shift_left_big_int (big_int_of_string "39614081257132168796771975168") 67,
big_int_of_string "5846006549323611672814739330865132078623730171904");;
test 6 eq_big_int
(shift_left_big_int (big_int_of_string "-39614081257132168796771975168") 67,
big_int_of_string "-5846006549323611672814739330865132078623730171904");;
testing_function "shift_right_big_int";;
test 1 eq_big_int
(shift_right_big_int unit_big_int 0,
unit_big_int);;
test 2 eq_big_int
(shift_right_big_int (big_int_of_int 12345678) 3,
big_int_of_int 1543209);;
test 3 eq_big_int
(shift_right_big_int (big_int_of_string "5299989648942") 32,
big_int_of_int 1234);;
test 4 eq_big_int
(shift_right_big_int (big_int_of_string
"5846006549323611672814739330865132078623730171904")
67,
big_int_of_string "39614081257132168796771975168");;
test 5 eq_big_int
(shift_right_big_int (big_int_of_string "-5299989648942") 32,
big_int_of_int (-1235));;
test 6 eq_big_int
(shift_right_big_int (big_int_of_string "-16570089876543209725755392") 27,
big_int_of_string "-123456790123456789");;
testing_function "shift_right_towards_zero_big_int";;
test 1 eq_big_int
(shift_right_towards_zero_big_int (big_int_of_string "-5299989648942") 32,
big_int_of_int (-1234));;
test 2 eq_big_int
(shift_right_towards_zero_big_int (big_int_of_string
"-16570089876543209725755392")
27,
big_int_of_string "-123456790123456789");;
testing_function "extract_big_int";;
test 1 eq_big_int
(extract_big_int (big_int_of_int64 0x123456789ABCDEFL) 3 13,
big_int_of_int 6589);;
test 2 eq_big_int
(extract_big_int (big_int_128 h1 h2) 67 12,
big_int_of_int 1343);;
test 3 eq_big_int
(extract_big_int (big_int_of_string "-1844674407370955178") 37 9,
big_int_of_int 307);;
test 4 eq_big_int
(extract_big_int unit_big_int 2048 254,
zero_big_int);;
test 5 eq_big_int
(extract_big_int (big_int_of_int64 0x123456789ABCDEFL) 0 32,
big_int_of_int64 2309737967L);;
test 6 eq_big_int
(extract_big_int (big_int_of_int (-1)) 0 16,
big_int_of_int 0xFFFF);;
test 7 eq_big_int
(extract_big_int (big_int_of_int (-1)) 1027 12,
big_int_of_int 0xFFF);;
test 8 eq_big_int
(extract_big_int (big_int_of_int (-1234567)) 0 16,
big_int_of_int 10617);;
test 9 eq_big_int
(extract_big_int (minus_big_int (power_int_positive_int 2 64)) 64 20,
big_int_of_int 0xFFFFF);;
test 10 eq_big_int
(extract_big_int (pred_big_int (minus_big_int (power_int_positive_int 2 64)))
64 20,
big_int_of_int 0xFFFFE);;
testing_function "hashing of big integers";;
test 1 eq_int (Hashtbl.hash zero_big_int,
955772237);;
test 2 eq_int (Hashtbl.hash unit_big_int,
992063522);;
test 3 eq_int (Hashtbl.hash (minus_big_int unit_big_int),
161678167);;
test 4 eq_int (Hashtbl.hash (big_int_of_string "123456789123456789"),
755417385);;
test 5 eq_int (Hashtbl.hash (sub_big_int
(big_int_of_string "123456789123456789")
(big_int_of_string "123456789123456789")),
955772237);;
test 6 eq_int (Hashtbl.hash (sub_big_int
(big_int_of_string "123456789123456789")
(big_int_of_string "123456789123456788")),
992063522);;
testing_function "float_of_big_int";;
test 1 eq_float (float_of_big_int zero_big_int, 0.0);;
test 2 eq_float (float_of_big_int unit_big_int, 1.0);;
test 3 eq_float (float_of_big_int (minus_big_int unit_big_int), -1.0);;
test 4 eq_float (float_of_big_int (shift_left_big_int unit_big_int 1024),
infinity);;
test 5 eq_float (float_of_big_int (shift_left_big_int unit_big_int 1023),
ldexp 1.0 1023);;
Some random int64 values
let ok = ref true in
for i = 1 to 100 do
let n = Random.int64 Int64.max_int in
if not (eq_float (float_of_big_int (big_int_of_int64 n)) (Int64.to_float n))
then ok := false;
let n = Int64.neg n in
if not (eq_float (float_of_big_int (big_int_of_int64 n)) (Int64.to_float n))
then ok := false
done;
test 6 eq (!ok, true);;
Some random int64 values scaled by some random power of 2
let ok = ref true in
for i = 1 to 1000 do
let n = Random.int64 Int64.max_int in
let exp = Random.int 1200 in
if not (eq_float
(float_of_big_int
(shift_left_big_int (big_int_of_int64 n) exp))
(ldexp (Int64.to_float n) exp))
then ok := false;
let n = Int64.neg n in
if not (eq_float
(float_of_big_int
(shift_left_big_int (big_int_of_int64 n) exp))
(ldexp (Int64.to_float n) exp))
then ok := false
done;
test 7 eq (!ok, true);;
let ok = ref true in
for i = 0 to 15 do
let n = Int64.(add 0xfffffffffffff0L (of_int i)) in
if not (eq_float
(float_of_big_int
(shift_left_big_int (big_int_of_int64 n) 32))
(ldexp (Int64.to_float n) 32))
then ok := false
done;
test 8 eq (!ok, true);;
|
efd6187ef818fd636a2b904ee970881cfc8966f4c3e46157eed58ed854e4b88a | RichiH/git-annex | MetaData.hs | git - annex command
-
- Copyright 2014 - 2016 < >
-
- Licensed under the GNU GPL version 3 or higher .
-
- Copyright 2014-2016 Joey Hess <>
-
- Licensed under the GNU GPL version 3 or higher.
-}
module Command.MetaData where
import Command
import Annex.MetaData
import Annex.VectorClock
import Logs.MetaData
import Annex.WorkTree
import Messages.JSON (JSONActionItem(..))
import Types.Messages
import qualified Data.Set as S
import qualified Data.Map as M
import qualified Data.Text as T
import qualified Data.ByteString.Lazy.UTF8 as BU
import Data.Aeson
import Control.Concurrent
cmd :: Command
cmd = withGlobalOptions ([jsonOption] ++ annexedMatchingOptions) $
command "metadata" SectionMetaData
"sets or gets metadata of a file"
paramPaths (seek <$$> optParser)
data MetaDataOptions = MetaDataOptions
{ forFiles :: CmdParams
, getSet :: GetSet
, keyOptions :: Maybe KeyOptions
, batchOption :: BatchMode
}
data GetSet = Get MetaField | GetAll | Set [ModMeta]
optParser :: CmdParamsDesc -> Parser MetaDataOptions
optParser desc = MetaDataOptions
<$> cmdParams desc
<*> ((Get <$> getopt) <|> (Set <$> some modopts) <|> pure GetAll)
<*> optional parseKeyOptions
<*> parseBatchOption
where
getopt = option (eitherReader mkMetaField)
( long "get" <> short 'g' <> metavar paramField
<> help "get single metadata field"
)
modopts = option (eitherReader parseModMeta)
( long "set" <> short 's' <> metavar "FIELD[+-]=VALUE"
<> help "set or unset metadata value"
)
<|> (AddMeta tagMetaField . toMetaValue <$> strOption
( long "tag" <> short 't' <> metavar "TAG"
<> help "set a tag"
))
<|> (DelMeta tagMetaField . Just . toMetaValue <$> strOption
( long "untag" <> short 'u' <> metavar "TAG"
<> help "remove a tag"
))
<|> option (eitherReader (\f -> DelMeta <$> mkMetaField f <*> pure Nothing))
( long "remove" <> short 'r' <> metavar "FIELD"
<> help "remove all values of a field"
)
<|> flag' DelAllMeta
( long "remove-all"
<> help "remove all metadata"
)
seek :: MetaDataOptions -> CommandSeek
seek o = case batchOption o of
NoBatch -> do
c <- liftIO currentVectorClock
let seeker = case getSet o of
Get _ -> withFilesInGit
GetAll -> withFilesInGit
Set _ -> withFilesInGitNonRecursive
"Not recursively setting metadata. Use --force to do that."
withKeyOptions (keyOptions o) False
(startKeys c o)
(seeker $ whenAnnexed $ start c o)
=<< workTreeItems (forFiles o)
Batch -> withMessageState $ \s -> case outputType s of
JSONOutput _ -> batchInput parseJSONInput $
commandAction . startBatch
_ -> giveup "--batch is currently only supported in --json mode"
start :: VectorClock -> MetaDataOptions -> FilePath -> Key -> CommandStart
start c o file k = startKeys c o k (mkActionItem afile)
where
afile = AssociatedFile (Just file)
startKeys :: VectorClock -> MetaDataOptions -> Key -> ActionItem -> CommandStart
startKeys c o k ai = case getSet o of
Get f -> do
l <- S.toList . currentMetaDataValues f <$> getCurrentMetaData k
liftIO $ forM_ l $
putStrLn . fromMetaValue
stop
_ -> do
showStart' "metadata" k ai
next $ perform c o k
perform :: VectorClock -> MetaDataOptions -> Key -> CommandPerform
perform c o k = case getSet o of
Set ms -> do
oldm <- getCurrentMetaData k
let m = combineMetaData $ map (modMeta oldm) ms
addMetaData' k m c
next $ cleanup k
_ -> next $ cleanup k
cleanup :: Key -> CommandCleanup
cleanup k = do
m <- getCurrentMetaData k
let Object o = toJSON (MetaDataFields m)
maybeShowJSON $ AesonObject o
showLongNote $ unlines $ concatMap showmeta $
map unwrapmeta (fromMetaData m)
return True
where
unwrapmeta (f, v) = (fromMetaField f, map fromMetaValue (S.toList v))
showmeta (f, vs) = map ((f ++ "=") ++) vs
Metadata serialized to JSON in the field named " fields " of
-- a larger object.
newtype MetaDataFields = MetaDataFields MetaData
deriving (Show)
instance ToJSON MetaDataFields where
toJSON (MetaDataFields m) = object [ (fieldsField, toJSON m) ]
instance FromJSON MetaDataFields where
parseJSON (Object v) = do
f <- v .: fieldsField
case f of
Nothing -> return (MetaDataFields emptyMetaData)
Just v' -> MetaDataFields <$> parseJSON v'
parseJSON _ = fail "expected an object"
fieldsField :: T.Text
fieldsField = T.pack "fields"
parseJSONInput :: String -> Either String (Either FilePath Key, MetaData)
parseJSONInput i = do
v <- eitherDecode (BU.fromString i)
let m = case itemAdded v of
Nothing -> emptyMetaData
Just (MetaDataFields m') -> m'
case (itemKey v, itemFile v) of
(Just k, _) -> Right (Right k, m)
(Nothing, Just f) -> Right (Left f, m)
(Nothing, Nothing) -> Left "JSON input is missing either file or key"
startBatch :: (Either FilePath Key, MetaData) -> CommandStart
startBatch (i, (MetaData m)) = case i of
Left f -> do
mk <- lookupFile f
case mk of
Just k -> go k (mkActionItem (AssociatedFile (Just f)))
Nothing -> giveup $ "not an annexed file: " ++ f
Right k -> go k (mkActionItem k)
where
go k ai = do
showStart' "metadata" k ai
let o = MetaDataOptions
{ forFiles = []
, getSet = if MetaData m == emptyMetaData
then GetAll
else Set $ map mkModMeta (M.toList m)
, keyOptions = Nothing
, batchOption = NoBatch
}
t <- liftIO currentVectorClock
It would be bad if two batch mode changes used exactly
-- the same timestamp, since the order of adds and removals
-- of the same metadata value would then be indeterminate.
To guarantee that never happens , delay 1 microsecond ,
-- so the timestamp will always be different. This is
-- probably less expensive than cleaner methods,
-- such as taking from a list of increasing timestamps.
liftIO $ threadDelay 1
next $ perform t o k
mkModMeta (f, s)
| S.null s = DelMeta f Nothing
| otherwise = SetMeta f s
| null | https://raw.githubusercontent.com/RichiH/git-annex/bbcad2b0af8cd9264d0cb86e6ca126ae626171f3/Command/MetaData.hs | haskell | a larger object.
the same timestamp, since the order of adds and removals
of the same metadata value would then be indeterminate.
so the timestamp will always be different. This is
probably less expensive than cleaner methods,
such as taking from a list of increasing timestamps. | git - annex command
-
- Copyright 2014 - 2016 < >
-
- Licensed under the GNU GPL version 3 or higher .
-
- Copyright 2014-2016 Joey Hess <>
-
- Licensed under the GNU GPL version 3 or higher.
-}
module Command.MetaData where
import Command
import Annex.MetaData
import Annex.VectorClock
import Logs.MetaData
import Annex.WorkTree
import Messages.JSON (JSONActionItem(..))
import Types.Messages
import qualified Data.Set as S
import qualified Data.Map as M
import qualified Data.Text as T
import qualified Data.ByteString.Lazy.UTF8 as BU
import Data.Aeson
import Control.Concurrent
cmd :: Command
cmd = withGlobalOptions ([jsonOption] ++ annexedMatchingOptions) $
command "metadata" SectionMetaData
"sets or gets metadata of a file"
paramPaths (seek <$$> optParser)
data MetaDataOptions = MetaDataOptions
{ forFiles :: CmdParams
, getSet :: GetSet
, keyOptions :: Maybe KeyOptions
, batchOption :: BatchMode
}
data GetSet = Get MetaField | GetAll | Set [ModMeta]
optParser :: CmdParamsDesc -> Parser MetaDataOptions
optParser desc = MetaDataOptions
<$> cmdParams desc
<*> ((Get <$> getopt) <|> (Set <$> some modopts) <|> pure GetAll)
<*> optional parseKeyOptions
<*> parseBatchOption
where
getopt = option (eitherReader mkMetaField)
( long "get" <> short 'g' <> metavar paramField
<> help "get single metadata field"
)
modopts = option (eitherReader parseModMeta)
( long "set" <> short 's' <> metavar "FIELD[+-]=VALUE"
<> help "set or unset metadata value"
)
<|> (AddMeta tagMetaField . toMetaValue <$> strOption
( long "tag" <> short 't' <> metavar "TAG"
<> help "set a tag"
))
<|> (DelMeta tagMetaField . Just . toMetaValue <$> strOption
( long "untag" <> short 'u' <> metavar "TAG"
<> help "remove a tag"
))
<|> option (eitherReader (\f -> DelMeta <$> mkMetaField f <*> pure Nothing))
( long "remove" <> short 'r' <> metavar "FIELD"
<> help "remove all values of a field"
)
<|> flag' DelAllMeta
( long "remove-all"
<> help "remove all metadata"
)
seek :: MetaDataOptions -> CommandSeek
seek o = case batchOption o of
NoBatch -> do
c <- liftIO currentVectorClock
let seeker = case getSet o of
Get _ -> withFilesInGit
GetAll -> withFilesInGit
Set _ -> withFilesInGitNonRecursive
"Not recursively setting metadata. Use --force to do that."
withKeyOptions (keyOptions o) False
(startKeys c o)
(seeker $ whenAnnexed $ start c o)
=<< workTreeItems (forFiles o)
Batch -> withMessageState $ \s -> case outputType s of
JSONOutput _ -> batchInput parseJSONInput $
commandAction . startBatch
_ -> giveup "--batch is currently only supported in --json mode"
start :: VectorClock -> MetaDataOptions -> FilePath -> Key -> CommandStart
start c o file k = startKeys c o k (mkActionItem afile)
where
afile = AssociatedFile (Just file)
startKeys :: VectorClock -> MetaDataOptions -> Key -> ActionItem -> CommandStart
startKeys c o k ai = case getSet o of
Get f -> do
l <- S.toList . currentMetaDataValues f <$> getCurrentMetaData k
liftIO $ forM_ l $
putStrLn . fromMetaValue
stop
_ -> do
showStart' "metadata" k ai
next $ perform c o k
perform :: VectorClock -> MetaDataOptions -> Key -> CommandPerform
perform c o k = case getSet o of
Set ms -> do
oldm <- getCurrentMetaData k
let m = combineMetaData $ map (modMeta oldm) ms
addMetaData' k m c
next $ cleanup k
_ -> next $ cleanup k
cleanup :: Key -> CommandCleanup
cleanup k = do
m <- getCurrentMetaData k
let Object o = toJSON (MetaDataFields m)
maybeShowJSON $ AesonObject o
showLongNote $ unlines $ concatMap showmeta $
map unwrapmeta (fromMetaData m)
return True
where
unwrapmeta (f, v) = (fromMetaField f, map fromMetaValue (S.toList v))
showmeta (f, vs) = map ((f ++ "=") ++) vs
Metadata serialized to JSON in the field named " fields " of
newtype MetaDataFields = MetaDataFields MetaData
deriving (Show)
instance ToJSON MetaDataFields where
toJSON (MetaDataFields m) = object [ (fieldsField, toJSON m) ]
instance FromJSON MetaDataFields where
parseJSON (Object v) = do
f <- v .: fieldsField
case f of
Nothing -> return (MetaDataFields emptyMetaData)
Just v' -> MetaDataFields <$> parseJSON v'
parseJSON _ = fail "expected an object"
fieldsField :: T.Text
fieldsField = T.pack "fields"
parseJSONInput :: String -> Either String (Either FilePath Key, MetaData)
parseJSONInput i = do
v <- eitherDecode (BU.fromString i)
let m = case itemAdded v of
Nothing -> emptyMetaData
Just (MetaDataFields m') -> m'
case (itemKey v, itemFile v) of
(Just k, _) -> Right (Right k, m)
(Nothing, Just f) -> Right (Left f, m)
(Nothing, Nothing) -> Left "JSON input is missing either file or key"
startBatch :: (Either FilePath Key, MetaData) -> CommandStart
startBatch (i, (MetaData m)) = case i of
Left f -> do
mk <- lookupFile f
case mk of
Just k -> go k (mkActionItem (AssociatedFile (Just f)))
Nothing -> giveup $ "not an annexed file: " ++ f
Right k -> go k (mkActionItem k)
where
go k ai = do
showStart' "metadata" k ai
let o = MetaDataOptions
{ forFiles = []
, getSet = if MetaData m == emptyMetaData
then GetAll
else Set $ map mkModMeta (M.toList m)
, keyOptions = Nothing
, batchOption = NoBatch
}
t <- liftIO currentVectorClock
It would be bad if two batch mode changes used exactly
To guarantee that never happens , delay 1 microsecond ,
liftIO $ threadDelay 1
next $ perform t o k
mkModMeta (f, s)
| S.null s = DelMeta f Nothing
| otherwise = SetMeta f s
|
c20e30a079000086c603fc03f4738343a5641178aace7aa8518192ba80eb6cfc | nervous-systems/cljs-lambda | args.clj | (ns leiningen.cljs-lambda.args)
(def ^:dynamic *region* nil)
(def ^:dynamic *aws-profile* nil)
(let [coercions {:create #(Boolean/parseBoolean %)
:timeout #(Integer/parseInt %)
:memory-size #(Integer/parseInt %)
:parallel #(Integer/parseInt %)}
->arg #(keyword (subs % 1))]
(defn split-args [l bool-arg?]
(loop [pos [] kw {} [k & l] l]
(cond (not k) [pos kw]
(not= \: (first k)) (recur (conj pos k) kw l)
:else (let [arg (->arg k)]
(if (bool-arg? arg)
(recur pos (assoc kw arg true) l)
(let [[v & l] l
coerce (coercions arg identity)]
(recur pos (assoc kw arg (coerce v)) l))))))))
| null | https://raw.githubusercontent.com/nervous-systems/cljs-lambda/ecd74ec7046e619b3c097c222124fea4b9973241/plugin/src/leiningen/cljs_lambda/args.clj | clojure | (ns leiningen.cljs-lambda.args)
(def ^:dynamic *region* nil)
(def ^:dynamic *aws-profile* nil)
(let [coercions {:create #(Boolean/parseBoolean %)
:timeout #(Integer/parseInt %)
:memory-size #(Integer/parseInt %)
:parallel #(Integer/parseInt %)}
->arg #(keyword (subs % 1))]
(defn split-args [l bool-arg?]
(loop [pos [] kw {} [k & l] l]
(cond (not k) [pos kw]
(not= \: (first k)) (recur (conj pos k) kw l)
:else (let [arg (->arg k)]
(if (bool-arg? arg)
(recur pos (assoc kw arg true) l)
(let [[v & l] l
coerce (coercions arg identity)]
(recur pos (assoc kw arg (coerce v)) l))))))))
| |
b4632b6554fdb78c7e2fbdf11cf31b318ff4acf681b3aaadcc069f30cf037902 | haskell-distributed/network-transport-tcp | JustPingTwoSocketPairs.hs | # LANGUAGE CPP , BangPatterns #
module Main where
import Control.Monad
import Data.Int
import Network.Socket
( AddrInfo, AddrInfoFlag (AI_PASSIVE), HostName, ServiceName, Socket
, SocketType (Stream), SocketOption (ReuseAddr, NoDelay)
, accept, addrAddress, addrFlags, addrFamily, bindSocket, defaultProtocol
, defaultHints
, getAddrInfo, listen, setSocketOption, socket, sClose, withSocketsDo )
import System.Environment (getArgs, withArgs)
import Data.Time (getCurrentTime, diffUTCTime, NominalDiffTime)
import System.IO (withFile, IOMode(..), hPutStrLn, Handle, stderr)
import Control.Concurrent (forkIO)
import Control.Concurrent.MVar (newEmptyMVar, takeMVar, putMVar)
import qualified Network.Socket as N
import Debug.Trace
import Data.ByteString (ByteString)
import Data.ByteString.Char8 (pack, unpack)
import qualified Data.ByteString as BS
import qualified Network.Socket.ByteString as NBS
import Data.Time (getCurrentTime, diffUTCTime, NominalDiffTime)
import Data.ByteString.Internal as BSI
import Foreign.Storable (pokeByteOff, peekByteOff)
import Foreign.C (CInt(..))
import Foreign.ForeignPtr (withForeignPtr)
import Control.Concurrent.Chan (Chan, newChan, readChan, writeChan)
foreign import ccall unsafe "htonl" htonl :: CInt -> CInt
foreign import ccall unsafe "ntohl" ntohl :: CInt -> CInt
passive :: Maybe AddrInfo
passive = Just (defaultHints { addrFlags = [AI_PASSIVE] })
main = do
pingsStr:args <- getArgs
serverReady <- newEmptyMVar
clientReady <- newEmptyMVar
clientDone <- newEmptyMVar
-- Start the server
forkIO $ do
Initialize the server
serverAddr:_ <- getAddrInfo passive Nothing (Just "8080")
sock <- socket (addrFamily serverAddr) Stream defaultProtocol
setSocketOption sock ReuseAddr 1
bindSocket sock (addrAddress serverAddr)
listen sock 1
-- Set up multiplexing channel
multiplexChannel <- newChan
Connect to the client ( to reply )
forkIO $ do
takeMVar clientReady
clientAddr:_ <- getAddrInfo Nothing (Just "127.0.0.1") (Just "8081")
pongSock <- socket (addrFamily clientAddr) Stream defaultProtocol
N.connect pongSock (addrAddress clientAddr)
when ("--NoDelay" `elem` args) $ setSocketOption pongSock NoDelay 1
forever $ readChan multiplexChannel >>= send pongSock
-- Wait for incoming connections (pings from the client)
putMVar serverReady ()
(pingSock, pingAddr) <- accept sock
socketToChan pingSock multiplexChannel
-- Start the client
forkIO $ do
clientAddr:_ <- getAddrInfo passive Nothing (Just "8081")
sock <- socket (addrFamily clientAddr) Stream defaultProtocol
setSocketOption sock ReuseAddr 1
bindSocket sock (addrAddress clientAddr)
listen sock 1
-- Set up multiplexing channel
multiplexChannel <- newChan
Connect to the server ( to send pings )
forkIO $ do
takeMVar serverReady
serverAddr:_ <- getAddrInfo Nothing (Just "127.0.0.1") (Just "8080")
pingSock <- socket (addrFamily serverAddr) Stream defaultProtocol
N.connect pingSock (addrAddress serverAddr)
when ("--NoDelay" `elem` args) $ setSocketOption pingSock NoDelay 1
ping pingSock multiplexChannel (read pingsStr)
putMVar clientDone ()
-- Wait for incoming connections (pongs from the server)
putMVar clientReady ()
(pongSock, pongAddr) <- accept sock
socketToChan pongSock multiplexChannel
-- Wait for the client to finish
takeMVar clientDone
socketToChan :: Socket -> Chan ByteString -> IO ()
socketToChan sock chan = go
where
go = do bs <- recv sock
when (BS.length bs > 0) $ do
writeChan chan bs
go
pingMessage :: ByteString
pingMessage = pack "ping123"
ping :: Socket -> Chan ByteString -> Int -> IO ()
ping sock chan pings = go pings
where
go :: Int -> IO ()
go 0 = do
putStrLn $ "client did " ++ show pings ++ " pings"
go !i = do
before <- getCurrentTime
send sock pingMessage
bs <- readChan chan
after <- getCurrentTime
-- putStrLn $ "client received " ++ unpack bs
let latency = (1e6 :: Double) * realToFrac (diffUTCTime after before)
hPutStrLn stderr $ show i ++ " " ++ show latency
go (i - 1)
-- | Receive a package
recv :: Socket -> IO ByteString
recv sock = do
header <- NBS.recv sock 4
length <- decodeLength header
NBS.recv sock (fromIntegral (length :: Int32))
-- | Send a package
send :: Socket -> ByteString -> IO ()
send sock bs = do
length <- encodeLength (fromIntegral (BS.length bs))
NBS.sendMany sock [length, bs]
-- | Encode length (manual for now)
encodeLength :: Int32 -> IO ByteString
encodeLength i32 =
BSI.create 4 $ \p ->
pokeByteOff p 0 (htonl (fromIntegral i32))
-- | Decode length (manual for now)
decodeLength :: ByteString -> IO Int32
decodeLength bs =
let (fp, _, _) = BSI.toForeignPtr bs in
withForeignPtr fp $ \p -> do
w32 <- peekByteOff p 0
return (fromIntegral (ntohl w32))
| null | https://raw.githubusercontent.com/haskell-distributed/network-transport-tcp/2cb34ba7102cfa68ec86b562a96b07c1a64016f3/benchmarks/JustPingTwoSocketPairs.hs | haskell | Start the server
Set up multiplexing channel
Wait for incoming connections (pings from the client)
Start the client
Set up multiplexing channel
Wait for incoming connections (pongs from the server)
Wait for the client to finish
putStrLn $ "client received " ++ unpack bs
| Receive a package
| Send a package
| Encode length (manual for now)
| Decode length (manual for now) | # LANGUAGE CPP , BangPatterns #
module Main where
import Control.Monad
import Data.Int
import Network.Socket
( AddrInfo, AddrInfoFlag (AI_PASSIVE), HostName, ServiceName, Socket
, SocketType (Stream), SocketOption (ReuseAddr, NoDelay)
, accept, addrAddress, addrFlags, addrFamily, bindSocket, defaultProtocol
, defaultHints
, getAddrInfo, listen, setSocketOption, socket, sClose, withSocketsDo )
import System.Environment (getArgs, withArgs)
import Data.Time (getCurrentTime, diffUTCTime, NominalDiffTime)
import System.IO (withFile, IOMode(..), hPutStrLn, Handle, stderr)
import Control.Concurrent (forkIO)
import Control.Concurrent.MVar (newEmptyMVar, takeMVar, putMVar)
import qualified Network.Socket as N
import Debug.Trace
import Data.ByteString (ByteString)
import Data.ByteString.Char8 (pack, unpack)
import qualified Data.ByteString as BS
import qualified Network.Socket.ByteString as NBS
import Data.Time (getCurrentTime, diffUTCTime, NominalDiffTime)
import Data.ByteString.Internal as BSI
import Foreign.Storable (pokeByteOff, peekByteOff)
import Foreign.C (CInt(..))
import Foreign.ForeignPtr (withForeignPtr)
import Control.Concurrent.Chan (Chan, newChan, readChan, writeChan)
foreign import ccall unsafe "htonl" htonl :: CInt -> CInt
foreign import ccall unsafe "ntohl" ntohl :: CInt -> CInt
passive :: Maybe AddrInfo
passive = Just (defaultHints { addrFlags = [AI_PASSIVE] })
main = do
pingsStr:args <- getArgs
serverReady <- newEmptyMVar
clientReady <- newEmptyMVar
clientDone <- newEmptyMVar
forkIO $ do
Initialize the server
serverAddr:_ <- getAddrInfo passive Nothing (Just "8080")
sock <- socket (addrFamily serverAddr) Stream defaultProtocol
setSocketOption sock ReuseAddr 1
bindSocket sock (addrAddress serverAddr)
listen sock 1
multiplexChannel <- newChan
Connect to the client ( to reply )
forkIO $ do
takeMVar clientReady
clientAddr:_ <- getAddrInfo Nothing (Just "127.0.0.1") (Just "8081")
pongSock <- socket (addrFamily clientAddr) Stream defaultProtocol
N.connect pongSock (addrAddress clientAddr)
when ("--NoDelay" `elem` args) $ setSocketOption pongSock NoDelay 1
forever $ readChan multiplexChannel >>= send pongSock
putMVar serverReady ()
(pingSock, pingAddr) <- accept sock
socketToChan pingSock multiplexChannel
forkIO $ do
clientAddr:_ <- getAddrInfo passive Nothing (Just "8081")
sock <- socket (addrFamily clientAddr) Stream defaultProtocol
setSocketOption sock ReuseAddr 1
bindSocket sock (addrAddress clientAddr)
listen sock 1
multiplexChannel <- newChan
Connect to the server ( to send pings )
forkIO $ do
takeMVar serverReady
serverAddr:_ <- getAddrInfo Nothing (Just "127.0.0.1") (Just "8080")
pingSock <- socket (addrFamily serverAddr) Stream defaultProtocol
N.connect pingSock (addrAddress serverAddr)
when ("--NoDelay" `elem` args) $ setSocketOption pingSock NoDelay 1
ping pingSock multiplexChannel (read pingsStr)
putMVar clientDone ()
putMVar clientReady ()
(pongSock, pongAddr) <- accept sock
socketToChan pongSock multiplexChannel
takeMVar clientDone
socketToChan :: Socket -> Chan ByteString -> IO ()
socketToChan sock chan = go
where
go = do bs <- recv sock
when (BS.length bs > 0) $ do
writeChan chan bs
go
pingMessage :: ByteString
pingMessage = pack "ping123"
ping :: Socket -> Chan ByteString -> Int -> IO ()
ping sock chan pings = go pings
where
go :: Int -> IO ()
go 0 = do
putStrLn $ "client did " ++ show pings ++ " pings"
go !i = do
before <- getCurrentTime
send sock pingMessage
bs <- readChan chan
after <- getCurrentTime
let latency = (1e6 :: Double) * realToFrac (diffUTCTime after before)
hPutStrLn stderr $ show i ++ " " ++ show latency
go (i - 1)
recv :: Socket -> IO ByteString
recv sock = do
header <- NBS.recv sock 4
length <- decodeLength header
NBS.recv sock (fromIntegral (length :: Int32))
send :: Socket -> ByteString -> IO ()
send sock bs = do
length <- encodeLength (fromIntegral (BS.length bs))
NBS.sendMany sock [length, bs]
encodeLength :: Int32 -> IO ByteString
encodeLength i32 =
BSI.create 4 $ \p ->
pokeByteOff p 0 (htonl (fromIntegral i32))
decodeLength :: ByteString -> IO Int32
decodeLength bs =
let (fp, _, _) = BSI.toForeignPtr bs in
withForeignPtr fp $ \p -> do
w32 <- peekByteOff p 0
return (fromIntegral (ntohl w32))
|
cb812129473c980220f83fa311c252cbbdced2ae9abe30e0b5f080642a3f2657 | borkdude/advent-of-cljc | clashthebunny.cljc | (ns aoc.y2018.d05.clashthebunny
(:refer-clojure :exclude [read-string format])
(:require
[aoc.utils :as u :refer [deftest read-string format]]
[aoc.y2018.d05.data :refer [input answer-1 answer-2]]
[clojure.test :refer [is testing]]
[clojure.string :as s]
[clojure.core.reducers :as r]))
(defn parse [string]
(-> string
s/trim
seq))
snagged from mfikes
(defn reacts? [x y]
(and (not= x y)
(= (s/lower-case x) (s/lower-case y))))
(defn check-letter
([] [])
([elim]
[])
([result current-letter]
(cond
(= 0 (count result)) [current-letter]
(reacts? (peek result) current-letter) (pop result)
:else (conj result current-letter)))
([elim result current-letter]
(cond
(= elim (s/lower-case current-letter)) result
:else (check-letter result current-letter))))
(defn react
([checked polymer]
(r/fold 15000 check-letter check-letter polymer))
([checked polymer elim]
(r/fold 15000 (partial check-letter elim) (partial check-letter elim) polymer)))
(defn find-elements [polymer]
(into #{} (map s/lower-case (into #{} polymer))))
(defn try-elim-elem [polymer]
(into {} (for [elem (find-elements polymer)]
{elem (count (react [] polymer elem))})))
(defn solve-1 []
(count (react [] (parse input))))
(defn solve-2 []
(val (apply min-key val (try-elim-elem (parse input)))))
(deftest part-1
(is (= (str answer-1)
(str (solve-1)))))
(deftest part-2
(is (= (str answer-2)
(str (solve-2)))))
| null | https://raw.githubusercontent.com/borkdude/advent-of-cljc/17c8abb876b95ab01eee418f1da2e402e845c596/src/aoc/y2018/d05/clashthebunny.cljc | clojure | (ns aoc.y2018.d05.clashthebunny
(:refer-clojure :exclude [read-string format])
(:require
[aoc.utils :as u :refer [deftest read-string format]]
[aoc.y2018.d05.data :refer [input answer-1 answer-2]]
[clojure.test :refer [is testing]]
[clojure.string :as s]
[clojure.core.reducers :as r]))
(defn parse [string]
(-> string
s/trim
seq))
snagged from mfikes
(defn reacts? [x y]
(and (not= x y)
(= (s/lower-case x) (s/lower-case y))))
(defn check-letter
([] [])
([elim]
[])
([result current-letter]
(cond
(= 0 (count result)) [current-letter]
(reacts? (peek result) current-letter) (pop result)
:else (conj result current-letter)))
([elim result current-letter]
(cond
(= elim (s/lower-case current-letter)) result
:else (check-letter result current-letter))))
(defn react
([checked polymer]
(r/fold 15000 check-letter check-letter polymer))
([checked polymer elim]
(r/fold 15000 (partial check-letter elim) (partial check-letter elim) polymer)))
(defn find-elements [polymer]
(into #{} (map s/lower-case (into #{} polymer))))
(defn try-elim-elem [polymer]
(into {} (for [elem (find-elements polymer)]
{elem (count (react [] polymer elem))})))
(defn solve-1 []
(count (react [] (parse input))))
(defn solve-2 []
(val (apply min-key val (try-elim-elem (parse input)))))
(deftest part-1
(is (= (str answer-1)
(str (solve-1)))))
(deftest part-2
(is (= (str answer-2)
(str (solve-2)))))
| |
5d22a9e18c80c4d32f34c2e53fc8277f45d4ab018c83dce347fef7efe173e97d | VincentToups/racket-lib | initial-state.rkt | #lang racket
(require pure-lands/utilities/nested-dicts)
(define initial-letters
(>> 'f 2 'o 4 'd 2))
(define initial-plot
(>> 'wet #f
'planted #f
'weeds 0
'harvest #f
'time-since-planting #f))
(define initial-state
(>> 'stamina 6
'turn 0
'points 0
'weather 'clear
'letters initial-letters
'items '()
'field '()
'random-state
#(1 2 3 4 5 6)))
(provide initial-state initial-plot)
| null | https://raw.githubusercontent.com/VincentToups/racket-lib/d8aed0959fd148615b000ceecd7b8a6128cfcfa8/pure-lands/chapter-01/agrilex/initial-state.rkt | racket | #lang racket
(require pure-lands/utilities/nested-dicts)
(define initial-letters
(>> 'f 2 'o 4 'd 2))
(define initial-plot
(>> 'wet #f
'planted #f
'weeds 0
'harvest #f
'time-since-planting #f))
(define initial-state
(>> 'stamina 6
'turn 0
'points 0
'weather 'clear
'letters initial-letters
'items '()
'field '()
'random-state
#(1 2 3 4 5 6)))
(provide initial-state initial-plot)
| |
3cc12d27bd13b683f7232beac392b372fcddad5c15f4ebe529a5cffacd1a3058 | byorgey/comprog-hs | NumberTheory.hs | -programming-in-haskell-primes-and-factoring/
-- -programming-in-haskell-modular-arithmetic-part-1/
-- -programming-in-haskell-modular-arithmetic-part-2/
module NumberTheory where
import Data.Map (Map)
import qualified Data.Map as M
import Control.Arrow
import Data.List (group, sort)
------------------------------------------------------------
Modular exponentiation
modexp :: Integer -> Integer -> Integer -> Integer
modexp _ 0 _ = 1
modexp b e m
| even e = (r*r) `mod` m
| otherwise = (b*r*r) `mod` m
where
r = modexp b (e `div` 2) m
------------------------------------------------------------
( Extended ) Euclidean algorithm
-- egcd a b = (g,x,y)
-- g is the gcd of a and b, and ax + by = g
egcd :: Integer -> Integer -> (Integer, Integer, Integer)
egcd a 0
| a < 0 = (-a,-1,0)
| otherwise = (a,1,0)
egcd a b = (g, y, x - (a `div` b) * y)
where
(g,x,y) = egcd b (a `mod` b)
-- g = bx + (a mod b)y
-- = bx + (a - b(a/b))y
-- = ay + b(x - (a/b)y)
inverse p a is the multiplicative inverse of a mod p
inverse :: Integer -> Integer -> Integer
inverse p a = y `mod` p
where
(_,_,y) = egcd p a
------------------------------------------------------------
-- Primes, factoring, and divisors
factorMap :: Integer -> Map Integer Int
factorMap = factor >>> M.fromList
factor :: Integer -> [(Integer, Int)]
factor = listFactors >>> group >>> map (head &&& length)
primes :: [Integer]
primes = 2 : sieve primes [3..]
where
sieve (p:ps) xs =
let (h,t) = span (< p*p) xs
in h ++ sieve ps (filter ((/=0).(`mod`p)) t)
listFactors :: Integer -> [Integer]
listFactors = go primes
where
go _ 1 = []
go (p:ps) n
| p*p > n = [n]
| n `mod` p == 0 = p : go (p:ps) (n `div` p)
| otherwise = go ps n
divisors :: Integer -> [Integer]
divisors = factor >>> map (\(p,k) -> take (k+1) (iterate (*p) 1)) >>>
sequence >>> map product
totient :: Integer -> Integer
totient = factor >>> map (\(p,k) -> p^(k-1) * (p-1)) >>> product
------------------------------------------------------------
-- Solving modular equations
-- solveMod a b m solves ax = b (mod m), returning (y,k) such that all
-- solutions are equivalent to y (mod k)
solveMod :: Integer -> Integer -> Integer -> Maybe (Integer, Integer)
solveMod a b m
| g == 1 = Just ((b * inverse m a) `mod` m, m)
| b `mod` g == 0 = solveMod (a `div` g) (b `div` g) (m `div` g)
| otherwise = Nothing
where
g = gcd a m
-- gcrt solves a system of modular equations. Each equation x = a
-- (mod n) is given as a pair (a,n). Returns a pair (z, k) such that
-- 0 <= z < k and solutions for x satisfy x = z (mod k), that is,
solutions are of the form x = z + kt for
gcrt :: [(Integer, Integer)] -> Maybe (Integer, Integer)
gcrt [e] = Just e
gcrt (e1:e2:es) = gcrt2 e1 e2 >>= \e -> gcrt (e:es)
( a , n ) ( b , m ) solves the pair of modular equations
--
-- x = a (mod n)
-- x = b (mod m)
--
-- It returns a pair (c, k) such that 0 <= c < k and all solutions for
-- x satisfy x = c (mod k), that is, solutions are of the form x = c +
-- kt for integer t.
gcrt2 :: (Integer, Integer) -> (Integer, Integer) -> Maybe (Integer, Integer)
gcrt2 (a,n) (b,m)
| a `mod` g == b `mod` g = Just (((a*v*m + b*u*n) `div` g) `mod` k, k)
| otherwise = Nothing
where
(g,u,v) = egcd n m
k = (m*n) `div` g
| null | https://raw.githubusercontent.com/byorgey/comprog-hs/a42d35bdaef6fb555cc896f6c7e509b0cb9b7cd7/NumberTheory.hs | haskell | -programming-in-haskell-modular-arithmetic-part-1/
-programming-in-haskell-modular-arithmetic-part-2/
----------------------------------------------------------
----------------------------------------------------------
egcd a b = (g,x,y)
g is the gcd of a and b, and ax + by = g
g = bx + (a mod b)y
= bx + (a - b(a/b))y
= ay + b(x - (a/b)y)
----------------------------------------------------------
Primes, factoring, and divisors
----------------------------------------------------------
Solving modular equations
solveMod a b m solves ax = b (mod m), returning (y,k) such that all
solutions are equivalent to y (mod k)
gcrt solves a system of modular equations. Each equation x = a
(mod n) is given as a pair (a,n). Returns a pair (z, k) such that
0 <= z < k and solutions for x satisfy x = z (mod k), that is,
x = a (mod n)
x = b (mod m)
It returns a pair (c, k) such that 0 <= c < k and all solutions for
x satisfy x = c (mod k), that is, solutions are of the form x = c +
kt for integer t. | -programming-in-haskell-primes-and-factoring/
module NumberTheory where
import Data.Map (Map)
import qualified Data.Map as M
import Control.Arrow
import Data.List (group, sort)
Modular exponentiation
modexp :: Integer -> Integer -> Integer -> Integer
modexp _ 0 _ = 1
modexp b e m
| even e = (r*r) `mod` m
| otherwise = (b*r*r) `mod` m
where
r = modexp b (e `div` 2) m
( Extended ) Euclidean algorithm
egcd :: Integer -> Integer -> (Integer, Integer, Integer)
egcd a 0
| a < 0 = (-a,-1,0)
| otherwise = (a,1,0)
egcd a b = (g, y, x - (a `div` b) * y)
where
(g,x,y) = egcd b (a `mod` b)
inverse p a is the multiplicative inverse of a mod p
inverse :: Integer -> Integer -> Integer
inverse p a = y `mod` p
where
(_,_,y) = egcd p a
factorMap :: Integer -> Map Integer Int
factorMap = factor >>> M.fromList
factor :: Integer -> [(Integer, Int)]
factor = listFactors >>> group >>> map (head &&& length)
primes :: [Integer]
primes = 2 : sieve primes [3..]
where
sieve (p:ps) xs =
let (h,t) = span (< p*p) xs
in h ++ sieve ps (filter ((/=0).(`mod`p)) t)
listFactors :: Integer -> [Integer]
listFactors = go primes
where
go _ 1 = []
go (p:ps) n
| p*p > n = [n]
| n `mod` p == 0 = p : go (p:ps) (n `div` p)
| otherwise = go ps n
divisors :: Integer -> [Integer]
divisors = factor >>> map (\(p,k) -> take (k+1) (iterate (*p) 1)) >>>
sequence >>> map product
totient :: Integer -> Integer
totient = factor >>> map (\(p,k) -> p^(k-1) * (p-1)) >>> product
solveMod :: Integer -> Integer -> Integer -> Maybe (Integer, Integer)
solveMod a b m
| g == 1 = Just ((b * inverse m a) `mod` m, m)
| b `mod` g == 0 = solveMod (a `div` g) (b `div` g) (m `div` g)
| otherwise = Nothing
where
g = gcd a m
solutions are of the form x = z + kt for
gcrt :: [(Integer, Integer)] -> Maybe (Integer, Integer)
gcrt [e] = Just e
gcrt (e1:e2:es) = gcrt2 e1 e2 >>= \e -> gcrt (e:es)
( a , n ) ( b , m ) solves the pair of modular equations
gcrt2 :: (Integer, Integer) -> (Integer, Integer) -> Maybe (Integer, Integer)
gcrt2 (a,n) (b,m)
| a `mod` g == b `mod` g = Just (((a*v*m + b*u*n) `div` g) `mod` k, k)
| otherwise = Nothing
where
(g,u,v) = egcd n m
k = (m*n) `div` g
|
6ff965c480c8bac3bee665580783c8efbf559399e8c09e4ed4fd85306d2e1e79 | tezos/tezos-mirror | irmin_store.ml | (*****************************************************************************)
(* *)
(* Open Source License *)
Copyright ( c ) 2022 Nomadic Labs , < >
Copyright ( c ) 2022 , < >
(* *)
(* Permission is hereby granted, free of charge, to any person obtaining a *)
(* copy of this software and associated documentation files (the "Software"),*)
to deal in the Software without restriction , including without limitation
(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)
and/or sell copies of the Software , and to permit persons to whom the
(* Software is furnished to do so, subject to the following conditions: *)
(* *)
(* The above copyright notice and this permission notice shall be included *)
(* in all copies or substantial portions of the Software. *)
(* *)
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)
(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)
(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING
(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)
(* DEALINGS IN THE SOFTWARE. *)
(* *)
(*****************************************************************************)
open Store_sigs
module Make (N : sig
val name : string
end) =
struct
module Maker = Irmin_pack_unix.Maker (Tezos_context_encoding.Context.Conf)
include Maker.Make (Tezos_context_encoding.Context.Schema)
let make_key_path path key = path @ [key]
type nonrec +'a t = t
let name = N.name
let load : type a. a mode -> string -> a t tzresult Lwt.t =
fun mode data_dir ->
let open Lwt_result_syntax in
trace (Store_errors.Cannot_load_store {name = N.name; path = data_dir})
@@ protect
@@ fun () ->
let readonly = match mode with Read_only -> true | Read_write -> false in
let*! repo = Repo.v (Irmin_pack.config ~readonly data_dir) in
let*! main = main repo in
return main
let flush store =
try Ok (flush (repo store))
with exn ->
Error
TzTrace.(
cons (Store_errors.Cannot_write_to_store N.name) @@ make (Exn exn))
let close store =
let open Lwt_result_syntax in
trace (Store_errors.Cannot_close_store N.name)
@@ protect
@@ fun () ->
let*! () = Repo.close (repo store) in
return_unit
let info message =
let date =
Tezos_base.Time.(
System.now () |> System.to_protocol |> Protocol.to_seconds)
in
Irmin.Info.Default.v ~author:N.name ~message date
let path_to_string path = String.concat "/" path
let set store path bytes =
let open Lwt_result_syntax in
trace (Store_errors.Cannot_write_to_store N.name)
@@ protect
@@ fun () ->
let full_path = path_to_string path in
let info () = info full_path in
let*! () = set_exn ~info store path bytes in
return_unit
let get store path =
let open Lwt_result_syntax in
trace (Store_errors.Cannot_read_from_store N.name)
@@ protect
@@ fun () ->
let*! bytes = get store path in
return bytes
let readonly = Fun.id
let mem store path =
let open Lwt_result_syntax in
trace (Store_errors.Cannot_read_from_store N.name)
@@ protect
@@ fun () ->
let*! is_present = mem store path in
return is_present
let find store path =
let open Lwt_result_syntax in
trace (Store_errors.Cannot_read_from_store N.name)
@@ protect
@@ fun () ->
let*! bytes_opt = find store path in
return bytes_opt
end
| null | https://raw.githubusercontent.com/tezos/tezos-mirror/aa878d424fddb85745e5445ed89432dd9d6380cc/src/lib_layer2_store/irmin_store.ml | ocaml | ***************************************************************************
Open Source License
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
the rights to use, copy, modify, merge, publish, distribute, sublicense,
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*************************************************************************** | Copyright ( c ) 2022 Nomadic Labs , < >
Copyright ( c ) 2022 , < >
to deal in the Software without restriction , including without limitation
and/or sell copies of the Software , and to permit persons to whom the
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING
open Store_sigs
module Make (N : sig
val name : string
end) =
struct
module Maker = Irmin_pack_unix.Maker (Tezos_context_encoding.Context.Conf)
include Maker.Make (Tezos_context_encoding.Context.Schema)
let make_key_path path key = path @ [key]
type nonrec +'a t = t
let name = N.name
let load : type a. a mode -> string -> a t tzresult Lwt.t =
fun mode data_dir ->
let open Lwt_result_syntax in
trace (Store_errors.Cannot_load_store {name = N.name; path = data_dir})
@@ protect
@@ fun () ->
let readonly = match mode with Read_only -> true | Read_write -> false in
let*! repo = Repo.v (Irmin_pack.config ~readonly data_dir) in
let*! main = main repo in
return main
let flush store =
try Ok (flush (repo store))
with exn ->
Error
TzTrace.(
cons (Store_errors.Cannot_write_to_store N.name) @@ make (Exn exn))
let close store =
let open Lwt_result_syntax in
trace (Store_errors.Cannot_close_store N.name)
@@ protect
@@ fun () ->
let*! () = Repo.close (repo store) in
return_unit
let info message =
let date =
Tezos_base.Time.(
System.now () |> System.to_protocol |> Protocol.to_seconds)
in
Irmin.Info.Default.v ~author:N.name ~message date
let path_to_string path = String.concat "/" path
let set store path bytes =
let open Lwt_result_syntax in
trace (Store_errors.Cannot_write_to_store N.name)
@@ protect
@@ fun () ->
let full_path = path_to_string path in
let info () = info full_path in
let*! () = set_exn ~info store path bytes in
return_unit
let get store path =
let open Lwt_result_syntax in
trace (Store_errors.Cannot_read_from_store N.name)
@@ protect
@@ fun () ->
let*! bytes = get store path in
return bytes
let readonly = Fun.id
let mem store path =
let open Lwt_result_syntax in
trace (Store_errors.Cannot_read_from_store N.name)
@@ protect
@@ fun () ->
let*! is_present = mem store path in
return is_present
let find store path =
let open Lwt_result_syntax in
trace (Store_errors.Cannot_read_from_store N.name)
@@ protect
@@ fun () ->
let*! bytes_opt = find store path in
return bytes_opt
end
|
bdaf5d42a93f59c5b759ac2ff5671dc8523083bd460bcf571f6efdf597d896e7 | synduce/Synduce | obfuscated_length.ml | * @synduce --no - gropt
type 'a list =
| Elt of 'a
| Cons of 'a * 'a list
(* Representation function: sort a list. *)
let rec repr = function
| Elt x -> Elt x
| Cons (hd, tl) -> insert hd (repr tl)
and insert y = function
| Elt x -> if y < x then Cons (y, Elt x) else Cons (x, Elt y)
| Cons (hd, tl) -> if y < hd then Cons (y, Cons (hd, tl)) else Cons (hd, insert y tl)
;;
: length > = 2
let rec is_length_lt2 l = len l >= 2
and len = function
| Elt x -> 1
| Cons (hd, tl) -> 1 + len tl
;;
let rec spec = function
| Elt x -> 1
| Cons (hd, tl) -> 1 + spec tl
;;
let rec target = function
| Elt x -> 1
| Cons (hd, tl) -> [%synt join] (target tl)
[@@requires is_length_lt2]
;;
| null | https://raw.githubusercontent.com/synduce/Synduce/d453b04cfb507395908a270b1906f5ac34298d29/benchmarks/constraints/size/obfuscated_length.ml | ocaml | Representation function: sort a list. | * @synduce --no - gropt
type 'a list =
| Elt of 'a
| Cons of 'a * 'a list
let rec repr = function
| Elt x -> Elt x
| Cons (hd, tl) -> insert hd (repr tl)
and insert y = function
| Elt x -> if y < x then Cons (y, Elt x) else Cons (x, Elt y)
| Cons (hd, tl) -> if y < hd then Cons (y, Cons (hd, tl)) else Cons (hd, insert y tl)
;;
: length > = 2
let rec is_length_lt2 l = len l >= 2
and len = function
| Elt x -> 1
| Cons (hd, tl) -> 1 + len tl
;;
let rec spec = function
| Elt x -> 1
| Cons (hd, tl) -> 1 + spec tl
;;
let rec target = function
| Elt x -> 1
| Cons (hd, tl) -> [%synt join] (target tl)
[@@requires is_length_lt2]
;;
|
1bbe612837134256fa917a358694afb9593720c047e208192112838bf3069a5f | facebook/pyre-check | abstractRootedTreeDomain.ml |
* Copyright ( c ) Meta Platforms , Inc. and affiliates .
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree .
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
(* TODO(T132410158) Add a module-level doc comment. *)
open AbstractTreeDomain
module Make (Config : CONFIG) (Root : AbstractDomainCore.S) (Element : ELEMENT) () = struct
module Tree = AbstractTreeDomain.Make (Config) (Element) ()
module ProductConfig = struct
type 'a slot =
| Tree : Tree.t slot
| Root : Root.t slot
let slots = 2
let slot_name (type a) (slot : a slot) =
match slot with
| Tree -> "tree"
| Root -> "root"
let slot_domain (type a) (slot : a slot) : a AbstractDomainCore.abstract_domain =
match slot with
| Tree -> (module Tree : AbstractDomainCore.S with type t = Tree.t)
| Root -> (module Root : AbstractDomainCore.S with type t = Root.t)
let strict (type a) (slot : a slot) =
match slot with
| Tree -> true
| Root -> false
end
module Product = AbstractProductDomain.Make (ProductConfig)
type _ AbstractDomainCore.part += Root = Root.Self | Path = Tree.Path
include Product
let create_leaf root element =
create AbstractDomainCore.[Part (Root.Self, root); Part (Tree.Self, Tree.create_leaf element)]
let prepend path product =
update ProductConfig.Tree (Tree.prepend path (get ProductConfig.Tree product)) product
let assign ?weak ~tree path ~subtree =
create
AbstractDomainCore.
[
Part (Root.Self, Root.join (get ProductConfig.Root tree) (get ProductConfig.Root subtree));
Part
( Tree.Self,
Tree.assign
?weak
~tree:(get ProductConfig.Tree tree)
path
~subtree:(get ProductConfig.Tree subtree) );
]
let read ?transform_non_leaves path product =
let tree = Tree.read ?transform_non_leaves path (get ProductConfig.Tree product) in
update ProductConfig.Tree tree product
let read_raw ?transform_non_leaves ?use_precise_labels path product =
let element, tree =
Tree.read_raw ?transform_non_leaves ?use_precise_labels path (get ProductConfig.Tree product)
in
element, update ProductConfig.Tree tree product
let min_depth product = Tree.min_depth (get ProductConfig.Tree product)
let max_depth product = Tree.max_depth (get ProductConfig.Tree product)
let collapse ?transform product = Tree.collapse ?transform (get ProductConfig.Tree product)
let collapse_to ?transform ~depth product =
update
ProductConfig.Tree
(Tree.collapse_to ?transform ~depth (get ProductConfig.Tree product))
product
let limit_to ?transform ~width product =
update
ProductConfig.Tree
(Tree.limit_to ?transform ~width (get ProductConfig.Tree product))
product
let shape ?transform product ~mold =
let mold = get ProductConfig.Tree mold in
update ProductConfig.Tree (Tree.shape ?transform ~mold (get ProductConfig.Tree product)) product
let cut_tree_after ~depth product =
update ProductConfig.Tree (Tree.cut_tree_after ~depth (get ProductConfig.Tree product)) product
let get_root product =
get ProductConfig.Root product, Tree.get_root (get ProductConfig.Tree product)
let set_root product root = update ProductConfig.Root root product
let labels product = Tree.labels (get ProductConfig.Tree product)
end
| null | https://raw.githubusercontent.com/facebook/pyre-check/98b8362ffa5c715c708676c1a37a52647ce79fe0/source/domains/abstractRootedTreeDomain.ml | ocaml | TODO(T132410158) Add a module-level doc comment. |
* Copyright ( c ) Meta Platforms , Inc. and affiliates .
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree .
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
open AbstractTreeDomain
module Make (Config : CONFIG) (Root : AbstractDomainCore.S) (Element : ELEMENT) () = struct
module Tree = AbstractTreeDomain.Make (Config) (Element) ()
module ProductConfig = struct
type 'a slot =
| Tree : Tree.t slot
| Root : Root.t slot
let slots = 2
let slot_name (type a) (slot : a slot) =
match slot with
| Tree -> "tree"
| Root -> "root"
let slot_domain (type a) (slot : a slot) : a AbstractDomainCore.abstract_domain =
match slot with
| Tree -> (module Tree : AbstractDomainCore.S with type t = Tree.t)
| Root -> (module Root : AbstractDomainCore.S with type t = Root.t)
let strict (type a) (slot : a slot) =
match slot with
| Tree -> true
| Root -> false
end
module Product = AbstractProductDomain.Make (ProductConfig)
type _ AbstractDomainCore.part += Root = Root.Self | Path = Tree.Path
include Product
let create_leaf root element =
create AbstractDomainCore.[Part (Root.Self, root); Part (Tree.Self, Tree.create_leaf element)]
let prepend path product =
update ProductConfig.Tree (Tree.prepend path (get ProductConfig.Tree product)) product
let assign ?weak ~tree path ~subtree =
create
AbstractDomainCore.
[
Part (Root.Self, Root.join (get ProductConfig.Root tree) (get ProductConfig.Root subtree));
Part
( Tree.Self,
Tree.assign
?weak
~tree:(get ProductConfig.Tree tree)
path
~subtree:(get ProductConfig.Tree subtree) );
]
let read ?transform_non_leaves path product =
let tree = Tree.read ?transform_non_leaves path (get ProductConfig.Tree product) in
update ProductConfig.Tree tree product
let read_raw ?transform_non_leaves ?use_precise_labels path product =
let element, tree =
Tree.read_raw ?transform_non_leaves ?use_precise_labels path (get ProductConfig.Tree product)
in
element, update ProductConfig.Tree tree product
let min_depth product = Tree.min_depth (get ProductConfig.Tree product)
let max_depth product = Tree.max_depth (get ProductConfig.Tree product)
let collapse ?transform product = Tree.collapse ?transform (get ProductConfig.Tree product)
let collapse_to ?transform ~depth product =
update
ProductConfig.Tree
(Tree.collapse_to ?transform ~depth (get ProductConfig.Tree product))
product
let limit_to ?transform ~width product =
update
ProductConfig.Tree
(Tree.limit_to ?transform ~width (get ProductConfig.Tree product))
product
let shape ?transform product ~mold =
let mold = get ProductConfig.Tree mold in
update ProductConfig.Tree (Tree.shape ?transform ~mold (get ProductConfig.Tree product)) product
let cut_tree_after ~depth product =
update ProductConfig.Tree (Tree.cut_tree_after ~depth (get ProductConfig.Tree product)) product
let get_root product =
get ProductConfig.Root product, Tree.get_root (get ProductConfig.Tree product)
let set_root product root = update ProductConfig.Root root product
let labels product = Tree.labels (get ProductConfig.Tree product)
end
|
515ebd35b5d3cf3b7114c8443c401aa4cc9992e0702579134c3c46fb920bbfab | auser/beehive | bees.erl | -module (bees).
-include ("beehive.hrl").
-include ("common.hrl").
-include_lib("stdlib/include/qlc.hrl").
-include_lib("kernel/include/file.hrl").
%% DATABASE STUFF
-export ([
create/1,
read/1,
save/1,
update/2,
delete/1,
find_by_name/1,
find_by_id/1,
find_all_by_id/1,
find_all_by_name/1,
find_all_by_host/1,
find_all_grouped_by_host/0,
all/0
]).
-export ([
new/1,
is_same_as/2
]).
%% APPLICATION STUFF
-export ([
meta_data/2,
build_app_env/1, build_app_env/2,
from_bee_object/2
]).
-define (DB, beehive_db_srv).
-export ([validate_bee/1]).
META DATA
meta_data(FileLocation, MetaFile) ->
BeeSize = case file:read_file_info(FileLocation) of
{ok, FileInfo} -> FileInfo#file_info.size;
_E -> 0.0
end,
OtherProps = case filelib:is_file(MetaFile) of
true -> {ok, MetaProps} = file:consult(MetaFile), MetaProps;
false -> []
end,
lists:flatten([{bee_size, BeeSize}, OtherProps]).
%% Create a new bee
create(Bee) ->
case new(Bee) of
NewBee when is_record(NewBee, bee) ->
save(validate_bee(NewBee));
E -> {error, E}
end.
%% Save the bee
save(Bee) when is_record(Bee, bee) ->
NewBee = validate_bee(Bee),
case ?DB:write(bee, NewBee#bee.id, NewBee) of
ok -> {ok, NewBee};
{'EXIT',{aborted,{no_exists,_}}} ->
?NOTIFY({db, database_not_initialized, bee}),
timer:sleep(100),
{error, database_not_initialized};
E ->
%% TODO: Investigate why this EVER happens...
{error, {did_not_write, E}}
end;
save([]) -> invalid;
save(Proplists) when is_list(Proplists) ->
case from_proplists(Proplists) of
{error, _} = T -> T;
Bee ->
save(Bee)
end;
save(Func) when is_function(Func) ->
?DB:save(Func);
save(Else) -> {error, {cannot_save, Else}}.
new([]) -> error;
new(Bee) when is_record(Bee, bee) -> Bee;
new(Proplist) when is_list(Proplist) ->
from_proplists(Proplist);
new(Else) -> {error, {cannot_make_new_bee, Else}}.
read(Name) ->
case find_by_name(Name) of
Bee when is_record(Bee, bee) -> Bee;
_E -> {error, not_found}
end.
delete(Bee) when is_record(Bee, bee) ->
?DB:delete(bee, Bee#bee.id);
delete(Name) when is_list(Name) ->
case bees:find_by_name(Name) of
not_found -> invalid;
Bee -> delete(Bee)
end;
delete([]) -> invalid;
delete(Else) -> {error, {cannot_delete, Else}}.
all() -> ?DB:all(bee).
find_by_name(Name) ->
case find_all_by_name(Name) of
[H|_Rest] -> H;
[] -> not_found;
%% This should ALWAYS be not_found, but just to be safe
E -> E
end.
find_by_id(Id) ->
case find_all_by_id(Id) of
[] -> not_found;
[H|_Rest] -> H;
E -> E
end.
%% Find alls
find_all_by_id(Id) -> ?DB:match(#bee{id = Id, _='_'}).
find_all_by_name(Name) -> ?DB:match(#bee{app_name = Name, _='_'}).
find_all_by_host(Host) -> ?DB:match(#bee{host = Host, _='_'}).
find_all_grouped_by_host() ->
Q = qlc:keysort(#bee.host, bees:all()),
qlc:fold(fun find_all_grouped_by_host1/2, [], Q).
find_all_grouped_by_host1(#bee{host=Host} = B, [{Host, Backends, Sum} | Acc]) ->
[{Host, [B|Backends], Sum + 1} | Acc];
find_all_grouped_by_host1(#bee{host=Host} = B, Acc) ->
[{Host, [B], 1}|Acc].
update([], _) -> ok;
update(Bee, OtherBee) when
is_record(Bee, bee) andalso is_record(OtherBee, bee) ->
update(Bee, lists:flatten(to_proplist(OtherBee)));
update(Bee, NewProps) when is_record(Bee, bee) ->
NewBee = misc_utils:update_proplist(to_proplist(Bee), NewProps),
{ok, NewBee1} = save(NewBee),
{updated, NewBee1};
update(Name, NewProps) ->
Bee = find_by_name(Name),
update(Bee, NewProps).
%% There has got to be a better way?
is_same_as(Bee, Otherbee) ->
Bee#bee.id == Otherbee#bee.id.
%%-------------------------------------------------------------------
%% @spec (Bee::bee()) -> {ok, Value}
%% @doc Build environment variables for the application
%%
%% @end
%%-------------------------------------------------------------------
build_app_env(Bee) ->
case apps:find_by_name(Bee#bee.app_name) of
App when is_record(App, app) -> build_app_env(Bee, App);
_ -> build_app_env(Bee, no_app)
end.
build_app_env(#bee{app_name = AppName} = Bee, no_app) ->
build_app_env(Bee, #app{name = AppName});
build_app_env( #bee{ port = Port,
host = HostIp,
app_name = AppName,
revision = Sha,
start_time = StartedAt
} = _Bee, App) ->
ScratchDisk = config:search_for_application_value(scratch_dir,
?BEEHIVE_DIR("tmp")),
RunningDisk = config:search_for_application_value(run_dir,
?BEEHIVE_DIR("run")),
LogDisk =
config:search_for_application_value(log_path,
?BEEHIVE_DIR("application_logs")),
WorkingDir = filename:join([ScratchDisk, AppName]),
RunningDir = filename:join([RunningDisk, AppName]),
LogDir = filename:join([LogDisk, AppName]),
OtherOpts = [
{name, AppName},
{host_ip, HostIp},
{sha, Sha},
{port, misc_utils:to_list(Port)},
{start_time, misc_utils:to_list(StartedAt)},
{log_directory, LogDir},
{working_directory, WorkingDir},
{run_directory, RunningDir}
],
EnvOpts = apps:build_app_env(App, OtherOpts),
lists:foreach(fun(Dir) -> file:make_dir(Dir) end,
[ScratchDisk, WorkingDir, RunningDisk,
RunningDir, LogDisk, LogDir]),
Opts = lists:flatten([{cd, RunningDir}, EnvOpts]),
{ok, App, Opts}.
If erlang had ' meta - programming , ' we would n't have to do all this
work to validate the proplists
from_proplists(Proplists) -> from_proplists(Proplists, #bee{}).
from_proplists([], Bee) -> Bee;
from_proplists([{id, V}|Rest], Bee) ->
from_proplists(Rest, Bee#bee{id = V});
from_proplists([{app_name, V}|Rest], Bee) ->
from_proplists(Rest, Bee#bee{app_name = V});
from_proplists([{host, V}|Rest], Bee) ->
from_proplists(Rest, Bee#bee{host = V});
from_proplists([{host_node, V}|Rest], Bee) ->
from_proplists(Rest, Bee#bee{host_node = V});
from_proplists([{port, V}|Rest], Bee) ->
from_proplists(Rest, Bee#bee{port = V});
from_proplists([{revision, V}|Rest], Bee) ->
from_proplists(Rest, Bee#bee{revision = V});
from_proplists([{bee_size, V}|Rest], Bee) ->
from_proplists(Rest, Bee#bee{bee_size = V});
from_proplists([{start_time, V}|Rest], Bee) ->
from_proplists(Rest, Bee#bee{start_time = V});
from_proplists([{pid, V}|Rest], Bee) ->
from_proplists(Rest, Bee#bee{pid = V});
from_proplists([{os_pid, V}|Rest], Bee) ->
from_proplists(Rest, Bee#bee{os_pid = V});
from_proplists([{sticky, V}|Rest], Bee) ->
from_proplists(Rest, Bee#bee{sticky = V});
from_proplists([{lastresp_time, V}|Rest], Bee) ->
from_proplists(Rest, Bee#bee{lastresp_time = V});
from_proplists([{lasterr, V}|Rest], Bee) ->
from_proplists(Rest, Bee#bee{lasterr = V});
from_proplists([{lasterr_time, V}|Rest], Bee) ->
from_proplists(Rest, Bee#bee{lasterr_time = V});
from_proplists([{act_time, V}|Rest], Bee) ->
from_proplists(Rest, Bee#bee{act_time = V});
from_proplists([{status, V}|Rest], Bee) ->
from_proplists(Rest, Bee#bee{status = V});
from_proplists([{maxconn, V}|Rest], Bee) ->
from_proplists(Rest, Bee#bee{maxconn = V});
from_proplists([{act_count, V}|Rest], Bee) ->
from_proplists(Rest, Bee#bee{act_count = V});
from_proplists([_Other|Rest], Bee) -> from_proplists(Rest, Bee).
to_proplist(Bee) -> to_proplist(record_info(fields, bee), Bee, []).
to_proplist([], _Bee, Acc) -> Acc;
to_proplist([id|Rest], #bee{id = Id} = Bee, Acc) ->
to_proplist(Rest, Bee, [{id, Id}|Acc]);
to_proplist([app_name|Rest], #bee{app_name = Value} = Bee, Acc) ->
to_proplist(Rest, Bee, [{app_name, Value}|Acc]);
to_proplist([host|Rest], #bee{host = Value} = Bee, Acc) ->
to_proplist(Rest, Bee, [{host, Value}|Acc]);
to_proplist([host_node|Rest], #bee{host_node = Value} = Bee, Acc) ->
to_proplist(Rest, Bee, [{host_node, Value}|Acc]);
to_proplist([port|Rest], #bee{port = Value} = Bee, Acc) ->
to_proplist(Rest, Bee, [{port, Value}|Acc]);
to_proplist([revision|Rest], #bee{revision = Value} = Bee, Acc) ->
to_proplist(Rest, Bee, [{revision, Value}|Acc]);
to_proplist([bee_size|Rest], #bee{bee_size = Value} = Bee, Acc) ->
to_proplist(Rest, Bee, [{bee_size, Value}|Acc]);
to_proplist([start_time|Rest], #bee{start_time = Value} = Bee, Acc) ->
to_proplist(Rest, Bee, [{start_time, Value}|Acc]);
to_proplist([pid|Rest], #bee{pid = Value} = Bee, Acc) ->
to_proplist(Rest, Bee, [{pid, Value}|Acc]);
to_proplist([os_pid|Rest], #bee{os_pid = Value} = Bee, Acc) ->
to_proplist(Rest, Bee, [{os_pid, Value}|Acc]);
to_proplist([sticky|Rest], #bee{sticky = Value} = Bee, Acc) ->
to_proplist(Rest, Bee, [{sticky, Value}|Acc]);
to_proplist([lastresp_time|Rest], #bee{lastresp_time = Value} = Bee, Acc) ->
to_proplist(Rest, Bee, [{lastresp_time, Value}|Acc]);
to_proplist([lasterr|Rest], #bee{lasterr = Value} = Bee, Acc) ->
to_proplist(Rest, Bee, [{lasterr, Value}|Acc]);
to_proplist([lasterr_time|Rest], #bee{lasterr_time = Value} = Bee, Acc) ->
to_proplist(Rest, Bee, [{lasterr_time, Value}|Acc]);
to_proplist([act_time|Rest], #bee{act_time = Value} = Bee, Acc) ->
to_proplist(Rest, Bee, [{act_time, Value}|Acc]);
to_proplist([status|Rest], #bee{status = Value} = Bee, Acc) ->
to_proplist(Rest, Bee, [{status, Value}|Acc]);
to_proplist([maxconn|Rest], #bee{maxconn = Value} = Bee, Acc) ->
to_proplist(Rest, Bee, [{maxconn, Value}|Acc]);
to_proplist([act_count|Rest], #bee{act_count = Value} = Bee, Acc) ->
to_proplist(Rest, Bee, [{act_count, Value}|Acc]);
to_proplist([_H|T], Bee, Acc) -> to_proplist(T, Bee, Acc).
from_bee_object(Bo, App) when is_record(Bo, bee_object) ->
fbo(record_info(fields, bee_object), Bo, App, #bee{}).
fbo([], _Bo, _App, Bee) -> validate_bee(Bee);
fbo([name|Rest], #bee_object{name = Name} = Bo, App, Bee) ->
fbo(Rest, Bo, App, Bee#bee{app_name = Name});
fbo([revision|Rest], #bee_object{revision = Rev} = Bo, App, Bee) ->
fbo(Rest, Bo, App, Bee#bee{revision = Rev});
fbo([bee_size|Rest], #bee_object{bee_size = V} = Bo, App, Bee) ->
fbo(Rest, Bo, App, Bee#bee{bee_size = V});
fbo([template|Rest], #bee_object{template = undefined} = Bo,
#app{template = Type} = App, Bee) ->
fbo(Rest, Bo, App, Bee#bee{template = Type});
fbo([template|Rest], #bee_object{template = V} = Bo, App, Bee) ->
fbo(Rest, Bo, App, Bee#bee{template = V});
fbo([bee_file|Rest], #bee_object{bee_file = V} = Bo, App, Bee) ->
fbo(Rest, Bo, App, Bee#bee{bee_file = V});
fbo([port|Rest], #bee_object{port = V} = Bo, App, Bee) ->
fbo(Rest, Bo, App, Bee#bee{port = V});
fbo([host|Rest], #bee_object{port = V} = Bo, App, Bee) ->
fbo(Rest, Bo, App, Bee#bee{port = V});
fbo([os_pid|Rest], #bee_object{os_pid = V} = Bo, App, Bee) ->
fbo(Rest, Bo, App, Bee#bee{os_pid = V});
fbo([pid|Rest], #bee_object{pid = V} = Bo, App, Bee) ->
fbo(Rest, Bo, App, Bee#bee{pid = V});
fbo([_H|Rest], Bo, App, Bee) -> fbo(Rest, Bo, App, Bee).
%%-------------------------------------------------------------------
( Proplist ) - > ValidProplist
@doc Validate the proplist to create a new bee record
%%
%% @end
%%-------------------------------------------------------------------
validate_bee(Bee) when is_record(Bee, bee) ->
ValidatedBee = validate_bee(lists:reverse(record_info(fields, bee)), Bee),
ValidatedBee;
validate_bee(Else) -> Else.
validate_bee([], Bee) -> Bee;
Validate the i d
validate_bee([id|Rest],
#bee{id = undefined, app_name = AppName,
host = Host, port = Port} = Bee) ->
validate_bee(Rest, Bee#bee{id = {AppName, Host, Port}});
validate_bee([id|Rest], Bee) ->
validate_bee(Rest, Bee);
Validate the app_name
validate_bee([app_name|_Rest], #bee{app_name = undefined} = _Bee) ->
{error, bee_not_associated_with_an_application};
validate_bee([app_name|Rest], Bee) -> validate_bee(Rest, Bee);
Validate sticky - ness
validate_bee([sticky|Rest], #bee{sticky = false} = Bee) ->
validate_bee(Rest, Bee);
validate_bee([sticky|Rest], #bee{sticky = true} = Bee) ->
validate_bee(Rest, Bee);
validate_bee([sticky|_Rest], _Bee) ->
{error, invalid_sticky_value};
Validate the host
validate_bee([host|Rest], #bee{host = undefined} = Bee) ->
validate_bee(Rest, Bee#bee{host = bh_host:myip()});
Validate others ?
validate_bee([_H|Rest], Bee) -> validate_bee(Rest, Bee).
| null | https://raw.githubusercontent.com/auser/beehive/dfe257701b21c56a50af73c8203ecac60ed21991/lib/erlang/apps/beehive/src/bh_models/bees.erl | erlang | DATABASE STUFF
APPLICATION STUFF
Create a new bee
Save the bee
TODO: Investigate why this EVER happens...
This should ALWAYS be not_found, but just to be safe
Find alls
There has got to be a better way?
-------------------------------------------------------------------
@spec (Bee::bee()) -> {ok, Value}
@doc Build environment variables for the application
@end
-------------------------------------------------------------------
-------------------------------------------------------------------
@end
------------------------------------------------------------------- | -module (bees).
-include ("beehive.hrl").
-include ("common.hrl").
-include_lib("stdlib/include/qlc.hrl").
-include_lib("kernel/include/file.hrl").
-export ([
create/1,
read/1,
save/1,
update/2,
delete/1,
find_by_name/1,
find_by_id/1,
find_all_by_id/1,
find_all_by_name/1,
find_all_by_host/1,
find_all_grouped_by_host/0,
all/0
]).
-export ([
new/1,
is_same_as/2
]).
-export ([
meta_data/2,
build_app_env/1, build_app_env/2,
from_bee_object/2
]).
-define (DB, beehive_db_srv).
-export ([validate_bee/1]).
META DATA
meta_data(FileLocation, MetaFile) ->
BeeSize = case file:read_file_info(FileLocation) of
{ok, FileInfo} -> FileInfo#file_info.size;
_E -> 0.0
end,
OtherProps = case filelib:is_file(MetaFile) of
true -> {ok, MetaProps} = file:consult(MetaFile), MetaProps;
false -> []
end,
lists:flatten([{bee_size, BeeSize}, OtherProps]).
create(Bee) ->
case new(Bee) of
NewBee when is_record(NewBee, bee) ->
save(validate_bee(NewBee));
E -> {error, E}
end.
save(Bee) when is_record(Bee, bee) ->
NewBee = validate_bee(Bee),
case ?DB:write(bee, NewBee#bee.id, NewBee) of
ok -> {ok, NewBee};
{'EXIT',{aborted,{no_exists,_}}} ->
?NOTIFY({db, database_not_initialized, bee}),
timer:sleep(100),
{error, database_not_initialized};
E ->
{error, {did_not_write, E}}
end;
save([]) -> invalid;
save(Proplists) when is_list(Proplists) ->
case from_proplists(Proplists) of
{error, _} = T -> T;
Bee ->
save(Bee)
end;
save(Func) when is_function(Func) ->
?DB:save(Func);
save(Else) -> {error, {cannot_save, Else}}.
new([]) -> error;
new(Bee) when is_record(Bee, bee) -> Bee;
new(Proplist) when is_list(Proplist) ->
from_proplists(Proplist);
new(Else) -> {error, {cannot_make_new_bee, Else}}.
read(Name) ->
case find_by_name(Name) of
Bee when is_record(Bee, bee) -> Bee;
_E -> {error, not_found}
end.
delete(Bee) when is_record(Bee, bee) ->
?DB:delete(bee, Bee#bee.id);
delete(Name) when is_list(Name) ->
case bees:find_by_name(Name) of
not_found -> invalid;
Bee -> delete(Bee)
end;
delete([]) -> invalid;
delete(Else) -> {error, {cannot_delete, Else}}.
all() -> ?DB:all(bee).
find_by_name(Name) ->
case find_all_by_name(Name) of
[H|_Rest] -> H;
[] -> not_found;
E -> E
end.
find_by_id(Id) ->
case find_all_by_id(Id) of
[] -> not_found;
[H|_Rest] -> H;
E -> E
end.
find_all_by_id(Id) -> ?DB:match(#bee{id = Id, _='_'}).
find_all_by_name(Name) -> ?DB:match(#bee{app_name = Name, _='_'}).
find_all_by_host(Host) -> ?DB:match(#bee{host = Host, _='_'}).
find_all_grouped_by_host() ->
Q = qlc:keysort(#bee.host, bees:all()),
qlc:fold(fun find_all_grouped_by_host1/2, [], Q).
find_all_grouped_by_host1(#bee{host=Host} = B, [{Host, Backends, Sum} | Acc]) ->
[{Host, [B|Backends], Sum + 1} | Acc];
find_all_grouped_by_host1(#bee{host=Host} = B, Acc) ->
[{Host, [B], 1}|Acc].
update([], _) -> ok;
update(Bee, OtherBee) when
is_record(Bee, bee) andalso is_record(OtherBee, bee) ->
update(Bee, lists:flatten(to_proplist(OtherBee)));
update(Bee, NewProps) when is_record(Bee, bee) ->
NewBee = misc_utils:update_proplist(to_proplist(Bee), NewProps),
{ok, NewBee1} = save(NewBee),
{updated, NewBee1};
update(Name, NewProps) ->
Bee = find_by_name(Name),
update(Bee, NewProps).
is_same_as(Bee, Otherbee) ->
Bee#bee.id == Otherbee#bee.id.
build_app_env(Bee) ->
case apps:find_by_name(Bee#bee.app_name) of
App when is_record(App, app) -> build_app_env(Bee, App);
_ -> build_app_env(Bee, no_app)
end.
build_app_env(#bee{app_name = AppName} = Bee, no_app) ->
build_app_env(Bee, #app{name = AppName});
build_app_env( #bee{ port = Port,
host = HostIp,
app_name = AppName,
revision = Sha,
start_time = StartedAt
} = _Bee, App) ->
ScratchDisk = config:search_for_application_value(scratch_dir,
?BEEHIVE_DIR("tmp")),
RunningDisk = config:search_for_application_value(run_dir,
?BEEHIVE_DIR("run")),
LogDisk =
config:search_for_application_value(log_path,
?BEEHIVE_DIR("application_logs")),
WorkingDir = filename:join([ScratchDisk, AppName]),
RunningDir = filename:join([RunningDisk, AppName]),
LogDir = filename:join([LogDisk, AppName]),
OtherOpts = [
{name, AppName},
{host_ip, HostIp},
{sha, Sha},
{port, misc_utils:to_list(Port)},
{start_time, misc_utils:to_list(StartedAt)},
{log_directory, LogDir},
{working_directory, WorkingDir},
{run_directory, RunningDir}
],
EnvOpts = apps:build_app_env(App, OtherOpts),
lists:foreach(fun(Dir) -> file:make_dir(Dir) end,
[ScratchDisk, WorkingDir, RunningDisk,
RunningDir, LogDisk, LogDir]),
Opts = lists:flatten([{cd, RunningDir}, EnvOpts]),
{ok, App, Opts}.
If erlang had ' meta - programming , ' we would n't have to do all this
work to validate the proplists
from_proplists(Proplists) -> from_proplists(Proplists, #bee{}).
from_proplists([], Bee) -> Bee;
from_proplists([{id, V}|Rest], Bee) ->
from_proplists(Rest, Bee#bee{id = V});
from_proplists([{app_name, V}|Rest], Bee) ->
from_proplists(Rest, Bee#bee{app_name = V});
from_proplists([{host, V}|Rest], Bee) ->
from_proplists(Rest, Bee#bee{host = V});
from_proplists([{host_node, V}|Rest], Bee) ->
from_proplists(Rest, Bee#bee{host_node = V});
from_proplists([{port, V}|Rest], Bee) ->
from_proplists(Rest, Bee#bee{port = V});
from_proplists([{revision, V}|Rest], Bee) ->
from_proplists(Rest, Bee#bee{revision = V});
from_proplists([{bee_size, V}|Rest], Bee) ->
from_proplists(Rest, Bee#bee{bee_size = V});
from_proplists([{start_time, V}|Rest], Bee) ->
from_proplists(Rest, Bee#bee{start_time = V});
from_proplists([{pid, V}|Rest], Bee) ->
from_proplists(Rest, Bee#bee{pid = V});
from_proplists([{os_pid, V}|Rest], Bee) ->
from_proplists(Rest, Bee#bee{os_pid = V});
from_proplists([{sticky, V}|Rest], Bee) ->
from_proplists(Rest, Bee#bee{sticky = V});
from_proplists([{lastresp_time, V}|Rest], Bee) ->
from_proplists(Rest, Bee#bee{lastresp_time = V});
from_proplists([{lasterr, V}|Rest], Bee) ->
from_proplists(Rest, Bee#bee{lasterr = V});
from_proplists([{lasterr_time, V}|Rest], Bee) ->
from_proplists(Rest, Bee#bee{lasterr_time = V});
from_proplists([{act_time, V}|Rest], Bee) ->
from_proplists(Rest, Bee#bee{act_time = V});
from_proplists([{status, V}|Rest], Bee) ->
from_proplists(Rest, Bee#bee{status = V});
from_proplists([{maxconn, V}|Rest], Bee) ->
from_proplists(Rest, Bee#bee{maxconn = V});
from_proplists([{act_count, V}|Rest], Bee) ->
from_proplists(Rest, Bee#bee{act_count = V});
from_proplists([_Other|Rest], Bee) -> from_proplists(Rest, Bee).
to_proplist(Bee) -> to_proplist(record_info(fields, bee), Bee, []).
to_proplist([], _Bee, Acc) -> Acc;
to_proplist([id|Rest], #bee{id = Id} = Bee, Acc) ->
to_proplist(Rest, Bee, [{id, Id}|Acc]);
to_proplist([app_name|Rest], #bee{app_name = Value} = Bee, Acc) ->
to_proplist(Rest, Bee, [{app_name, Value}|Acc]);
to_proplist([host|Rest], #bee{host = Value} = Bee, Acc) ->
to_proplist(Rest, Bee, [{host, Value}|Acc]);
to_proplist([host_node|Rest], #bee{host_node = Value} = Bee, Acc) ->
to_proplist(Rest, Bee, [{host_node, Value}|Acc]);
to_proplist([port|Rest], #bee{port = Value} = Bee, Acc) ->
to_proplist(Rest, Bee, [{port, Value}|Acc]);
to_proplist([revision|Rest], #bee{revision = Value} = Bee, Acc) ->
to_proplist(Rest, Bee, [{revision, Value}|Acc]);
to_proplist([bee_size|Rest], #bee{bee_size = Value} = Bee, Acc) ->
to_proplist(Rest, Bee, [{bee_size, Value}|Acc]);
to_proplist([start_time|Rest], #bee{start_time = Value} = Bee, Acc) ->
to_proplist(Rest, Bee, [{start_time, Value}|Acc]);
to_proplist([pid|Rest], #bee{pid = Value} = Bee, Acc) ->
to_proplist(Rest, Bee, [{pid, Value}|Acc]);
to_proplist([os_pid|Rest], #bee{os_pid = Value} = Bee, Acc) ->
to_proplist(Rest, Bee, [{os_pid, Value}|Acc]);
to_proplist([sticky|Rest], #bee{sticky = Value} = Bee, Acc) ->
to_proplist(Rest, Bee, [{sticky, Value}|Acc]);
to_proplist([lastresp_time|Rest], #bee{lastresp_time = Value} = Bee, Acc) ->
to_proplist(Rest, Bee, [{lastresp_time, Value}|Acc]);
to_proplist([lasterr|Rest], #bee{lasterr = Value} = Bee, Acc) ->
to_proplist(Rest, Bee, [{lasterr, Value}|Acc]);
to_proplist([lasterr_time|Rest], #bee{lasterr_time = Value} = Bee, Acc) ->
to_proplist(Rest, Bee, [{lasterr_time, Value}|Acc]);
to_proplist([act_time|Rest], #bee{act_time = Value} = Bee, Acc) ->
to_proplist(Rest, Bee, [{act_time, Value}|Acc]);
to_proplist([status|Rest], #bee{status = Value} = Bee, Acc) ->
to_proplist(Rest, Bee, [{status, Value}|Acc]);
to_proplist([maxconn|Rest], #bee{maxconn = Value} = Bee, Acc) ->
to_proplist(Rest, Bee, [{maxconn, Value}|Acc]);
to_proplist([act_count|Rest], #bee{act_count = Value} = Bee, Acc) ->
to_proplist(Rest, Bee, [{act_count, Value}|Acc]);
to_proplist([_H|T], Bee, Acc) -> to_proplist(T, Bee, Acc).
from_bee_object(Bo, App) when is_record(Bo, bee_object) ->
fbo(record_info(fields, bee_object), Bo, App, #bee{}).
fbo([], _Bo, _App, Bee) -> validate_bee(Bee);
fbo([name|Rest], #bee_object{name = Name} = Bo, App, Bee) ->
fbo(Rest, Bo, App, Bee#bee{app_name = Name});
fbo([revision|Rest], #bee_object{revision = Rev} = Bo, App, Bee) ->
fbo(Rest, Bo, App, Bee#bee{revision = Rev});
fbo([bee_size|Rest], #bee_object{bee_size = V} = Bo, App, Bee) ->
fbo(Rest, Bo, App, Bee#bee{bee_size = V});
fbo([template|Rest], #bee_object{template = undefined} = Bo,
#app{template = Type} = App, Bee) ->
fbo(Rest, Bo, App, Bee#bee{template = Type});
fbo([template|Rest], #bee_object{template = V} = Bo, App, Bee) ->
fbo(Rest, Bo, App, Bee#bee{template = V});
fbo([bee_file|Rest], #bee_object{bee_file = V} = Bo, App, Bee) ->
fbo(Rest, Bo, App, Bee#bee{bee_file = V});
fbo([port|Rest], #bee_object{port = V} = Bo, App, Bee) ->
fbo(Rest, Bo, App, Bee#bee{port = V});
fbo([host|Rest], #bee_object{port = V} = Bo, App, Bee) ->
fbo(Rest, Bo, App, Bee#bee{port = V});
fbo([os_pid|Rest], #bee_object{os_pid = V} = Bo, App, Bee) ->
fbo(Rest, Bo, App, Bee#bee{os_pid = V});
fbo([pid|Rest], #bee_object{pid = V} = Bo, App, Bee) ->
fbo(Rest, Bo, App, Bee#bee{pid = V});
fbo([_H|Rest], Bo, App, Bee) -> fbo(Rest, Bo, App, Bee).
( Proplist ) - > ValidProplist
@doc Validate the proplist to create a new bee record
validate_bee(Bee) when is_record(Bee, bee) ->
ValidatedBee = validate_bee(lists:reverse(record_info(fields, bee)), Bee),
ValidatedBee;
validate_bee(Else) -> Else.
validate_bee([], Bee) -> Bee;
Validate the i d
validate_bee([id|Rest],
#bee{id = undefined, app_name = AppName,
host = Host, port = Port} = Bee) ->
validate_bee(Rest, Bee#bee{id = {AppName, Host, Port}});
validate_bee([id|Rest], Bee) ->
validate_bee(Rest, Bee);
Validate the app_name
validate_bee([app_name|_Rest], #bee{app_name = undefined} = _Bee) ->
{error, bee_not_associated_with_an_application};
validate_bee([app_name|Rest], Bee) -> validate_bee(Rest, Bee);
Validate sticky - ness
validate_bee([sticky|Rest], #bee{sticky = false} = Bee) ->
validate_bee(Rest, Bee);
validate_bee([sticky|Rest], #bee{sticky = true} = Bee) ->
validate_bee(Rest, Bee);
validate_bee([sticky|_Rest], _Bee) ->
{error, invalid_sticky_value};
Validate the host
validate_bee([host|Rest], #bee{host = undefined} = Bee) ->
validate_bee(Rest, Bee#bee{host = bh_host:myip()});
Validate others ?
validate_bee([_H|Rest], Bee) -> validate_bee(Rest, Bee).
|
b3148900002ff4658d06f754a594b3708740a1f13edc6628fec89dd6986836f3 | yzh44yzh/practical_erlang | server3.erl | -module(server3).
-export([start/0, start/1, server/1, accept/2]).
start() ->
start(1234).
start(Port) ->
spawn(?MODULE, server, [Port]),
ok.
server(Port) ->
io:format("start server at port ~p~n", [Port]),
{ok, ListenSocket} = gen_tcp:listen(Port, [binary, {active, false}, {packet, 2}]),
[spawn(?MODULE, accept, [Id, ListenSocket]) || Id <- lists:seq(1, 5)],
timer:sleep(infinity),
ok.
accept(Id, ListenSocket) ->
io:format("Socket #~p wait for client~n", [Id]),
{ok, Socket} = gen_tcp:accept(ListenSocket),
io:format("Socket #~p, session started~n", [Id]),
handle_connection(Id, ListenSocket, Socket).
handle_connection(Id, ListenSocket, Socket) ->
case gen_tcp:recv(Socket, 0) of
{ok, Msg} -> io:format("Socket #~p got message: ~p~n", [Id, Msg]),
gen_tcp:send(Socket, Msg),
handle_connection(Id, ListenSocket, Socket);
{error, closed} ->
io:format("Socket #~p, session closed ~n", [Id]),
accept(Id, ListenSocket)
end.
| null | https://raw.githubusercontent.com/yzh44yzh/practical_erlang/c9eec8cf44e152bf50d9bc6d5cb87fee4764f609/16_sockets/server3.erl | erlang | -module(server3).
-export([start/0, start/1, server/1, accept/2]).
start() ->
start(1234).
start(Port) ->
spawn(?MODULE, server, [Port]),
ok.
server(Port) ->
io:format("start server at port ~p~n", [Port]),
{ok, ListenSocket} = gen_tcp:listen(Port, [binary, {active, false}, {packet, 2}]),
[spawn(?MODULE, accept, [Id, ListenSocket]) || Id <- lists:seq(1, 5)],
timer:sleep(infinity),
ok.
accept(Id, ListenSocket) ->
io:format("Socket #~p wait for client~n", [Id]),
{ok, Socket} = gen_tcp:accept(ListenSocket),
io:format("Socket #~p, session started~n", [Id]),
handle_connection(Id, ListenSocket, Socket).
handle_connection(Id, ListenSocket, Socket) ->
case gen_tcp:recv(Socket, 0) of
{ok, Msg} -> io:format("Socket #~p got message: ~p~n", [Id, Msg]),
gen_tcp:send(Socket, Msg),
handle_connection(Id, ListenSocket, Socket);
{error, closed} ->
io:format("Socket #~p, session closed ~n", [Id]),
accept(Id, ListenSocket)
end.
| |
f5f6cc77bd9107351ac11bc7e1adda3de38b08d1b8a3fa0e87f66bb3320cdb97 | c-cube/funarith | Prime_zarith.mli |
include Funarith.Prime.S with type Z.t = Z.t
| null | https://raw.githubusercontent.com/c-cube/funarith/1c86ac45e9608efaa761e3f14455402730885339/src/zarith/Prime_zarith.mli | ocaml |
include Funarith.Prime.S with type Z.t = Z.t
| |
d99850e91ba104f1babea86d3b092574284fdb926524b06ccfa3840a1e365819 | camfort/camfort | ReprintSpec.hs | {-# OPTIONS -Wno-orphans #-}
# LANGUAGE FlexibleInstances #
module Camfort.ReprintSpec (spec) where
import Camfort.Reprint
import qualified Data.ByteString.Char8 as B
import qualified Language.Fortran.Util.Position as FU
import Test.Hspec
import Test.QuickCheck
spec :: Spec
spec =
describe "subtext function tests" $ do
it "(unit test) first line of sample text" $
subtext (1, 1) (1, 1) (2, 1) btext `shouldBe`
(B.pack (text !! 0 ++ "\n"), B.pack (unlines . tail $ text))
it "(unit test) second line of sample text" $
subtext (1, 1) (2, 1) (3, 1) btext `shouldBe`
(B.pack (text !! 1 ++ "\n"), B.pack (unlines . tail . tail $ text))
it "(unit test) third line of sample text" $
subtext (1, 1) (4, 1) (5, 1) btext `shouldBe`
(B.pack (text !! 3 ++ "\n"), B.empty)
it "(unit test) fourth line, middle, of sample text" $
subtext (1, 1) (4, 2) (4, 5) btext `shouldBe`
(B.pack "G H", B.pack " I J K L\n")
it "(unit test) relative test (third line)" $
subtext (3, 1) (5, 1) (6, 1) btext `shouldBe`
(B.pack " E F\n", B.pack " G H I J K L\n")
it "(unit test) relative test (third line fragment)" $
subtext (3, 1) (5, 1) (5, 4) btext `shouldBe`
(B.pack " E", B.pack " F\n G H I J K L\n")
it "zero-length span at start yields empty string" $ property $
\s -> subtext (0, 0) (0, 0) (0, 0) s == (B.empty, s)
it "zero-length span yields empty substring" $ property $
\(l,c) -> \s -> (fst $ subtext (l,c) (l,c) (l,c) s) == B.empty
it " takeBounds is the same as old one " $ property $
\p - > takeBoundsOld ( FU.initPosition , p ) btext
= = takeBounds ( FU.initPosition , p ) btext
it " takeBounds is the same as old one , with different start pos " $ property $
\p - > takeBoundsOld ( FU.Position 0 2 2 , ) btext
= = takeBounds ( FU.Position 0 2 2 , ) btext
it "takeBounds is the same as old one" $ property $
\p -> takeBoundsOld (FU.initPosition, p) btext
== takeBounds (FU.initPosition, p) btext
it "takeBounds is the same as old one, with different start pos" $ property $
\p -> takeBoundsOld (FU.Position 0 2 2, unwrapPO p) btext
== takeBounds (FU.Position 0 2 2, unwrapPO p) btext
-}
it "takeBounds test 1" $
(fst $ takeBounds (FU.Position 0 2 2 "" Nothing, FU.Position 0 5 2 "" Nothing) btext)
`shouldBe` (B.pack "A B")
it "takeBounds test 2" $
(fst $ takeBounds (FU.Position 0 2 2 "" Nothing, FU.Position 0 1 3 "" Nothing) btext)
`shouldBe` (B.pack "A B C D\n")
it "takeBound test 3" $
(fst $ takeBounds (FU.Position 1 1 1 "" Nothing, FU.Position 1 5 3 "" Nothing) btext2)
`shouldBe` (B.pack $ unlines $ take 3 text2)
-- TODO: Fix this
-- context "Integration test with synthesising a spec" $ do
let simpleDir = " tests " < / > " fixtures "
-- simpleIn = simpleDir </> "simple.f90"
simpleExpected = simpleDir < / > " simple.expected.f90 "
simpleOut = simpleDir < / > " "
runIO $ unitsSynth simpleIn ( Just simpleIn ) [ ]
-- LitMixed False
simpleOut
-- actual <- runIO $ readFile simpleOut
-- expected <- runIO $ readFile simpleExpected
it " Unit synth " $ actual ` shouldBe ` expected
----
data PlusOne a = PlusOne { _unwrapPO :: a } deriving Show
instance Arbitrary (PlusOne FU.Position) where
arbitrary = do
FU.Position offset col line f p <- arbitrary
let col' = if line == 1 then col+1 else col
return $ PlusOne $ FU.Position offset col' (line + 1) f p
instance Arbitrary FU.Position where
arbitrary = do
offset <- arbitrary `suchThat` (>0)
line <- arbitrary `suchThat` (\x -> x >= 1 && x <= (length text))
col <- choose (1, orOne $ length (text !! (line - 1)))
return $ FU.Position offset col line "<generated>" Nothing
orOne :: (Eq p, Num p) => p -> p
orOne x | x == 0 = 1
| otherwise = x
Arbtirary ByteString
instance Arbitrary B.ByteString where
arbitrary = do
numLines <- choose (0, 3)
return . B.pack . concat $ take numLines text
btext :: B.ByteString
btext = B.pack . unlines $ text
text :: [[Char]]
text = ["A B C D"
,""
," E F"
," G H I J K L"]
btext2 :: B.ByteString
btext2 = B.pack . unlines $ text2
text2 :: [[Char]]
text2 = ["A B C D"
,"E F"
,"G H"
,"I J K L"]
-- Given a lower - bound and upper - bound pair of FU.Positions , split the
-- incoming SourceText based on the distanceF between the FU.Position pairs
takeBoundsOld : : ( FU.Position , FU.Position ) - > SourceText - > ( SourceText , SourceText )
takeBoundsOld ( l , u ) = takeBounds ' ( ( ll , lc ) , ( ul , ) ) B.empty
where ( FU.Position _ lc ll ) = l
( FU.Position _ uc ul ) = u
( ( ll , lc ) , ( ul , ) ) tk inp =
if ( ll = = ul & & lc = = uc ) || ( ll > ul ) then ( B.reverse tk , inp )
else
case B.uncons inp of
Nothing - > ( B.reverse tk , inp )
Just ( ' \n ' , ys ) - > takeBounds ' ( ( ll+1 , 1 ) , ( ul , ) ) ( B.cons ' \n ' tk ) ys
Just ( x , xs ) - > takeBounds ' ( ( ll , lc+1 ) , ( ul , ) ) ( B.cons x tk ) xs
-- Given a lower-bound and upper-bound pair of FU.Positions, split the
-- incoming SourceText based on the distanceF between the FU.Position pairs
takeBoundsOld :: (FU.Position, FU.Position) -> SourceText -> (SourceText, SourceText)
takeBoundsOld (l, u) = takeBounds' ((ll, lc), (ul, uc)) B.empty
where (FU.Position _ lc ll) = l
(FU.Position _ uc ul) = u
takeBounds' ((ll, lc), (ul, uc)) tk inp =
if (ll == ul && lc == uc) || (ll > ul) then (B.reverse tk, inp)
else
case B.uncons inp of
Nothing -> (B.reverse tk, inp)
Just ('\n', ys) -> takeBounds' ((ll+1, 1), (ul, uc)) (B.cons '\n' tk) ys
Just (x, xs) -> takeBounds' ((ll, lc+1), (ul, uc)) (B.cons x tk) xs
-}
| null | https://raw.githubusercontent.com/camfort/camfort/3421e85f6fbbcaa6503a266b3fae029a09d2ff24/tests/Camfort/ReprintSpec.hs | haskell | # OPTIONS -Wno-orphans #
TODO: Fix this
context "Integration test with synthesising a spec" $ do
simpleIn = simpleDir </> "simple.f90"
LitMixed False
actual <- runIO $ readFile simpleOut
expected <- runIO $ readFile simpleExpected
--
Given a lower - bound and upper - bound pair of FU.Positions , split the
incoming SourceText based on the distanceF between the FU.Position pairs
Given a lower-bound and upper-bound pair of FU.Positions, split the
incoming SourceText based on the distanceF between the FU.Position pairs | # LANGUAGE FlexibleInstances #
module Camfort.ReprintSpec (spec) where
import Camfort.Reprint
import qualified Data.ByteString.Char8 as B
import qualified Language.Fortran.Util.Position as FU
import Test.Hspec
import Test.QuickCheck
spec :: Spec
spec =
describe "subtext function tests" $ do
it "(unit test) first line of sample text" $
subtext (1, 1) (1, 1) (2, 1) btext `shouldBe`
(B.pack (text !! 0 ++ "\n"), B.pack (unlines . tail $ text))
it "(unit test) second line of sample text" $
subtext (1, 1) (2, 1) (3, 1) btext `shouldBe`
(B.pack (text !! 1 ++ "\n"), B.pack (unlines . tail . tail $ text))
it "(unit test) third line of sample text" $
subtext (1, 1) (4, 1) (5, 1) btext `shouldBe`
(B.pack (text !! 3 ++ "\n"), B.empty)
it "(unit test) fourth line, middle, of sample text" $
subtext (1, 1) (4, 2) (4, 5) btext `shouldBe`
(B.pack "G H", B.pack " I J K L\n")
it "(unit test) relative test (third line)" $
subtext (3, 1) (5, 1) (6, 1) btext `shouldBe`
(B.pack " E F\n", B.pack " G H I J K L\n")
it "(unit test) relative test (third line fragment)" $
subtext (3, 1) (5, 1) (5, 4) btext `shouldBe`
(B.pack " E", B.pack " F\n G H I J K L\n")
it "zero-length span at start yields empty string" $ property $
\s -> subtext (0, 0) (0, 0) (0, 0) s == (B.empty, s)
it "zero-length span yields empty substring" $ property $
\(l,c) -> \s -> (fst $ subtext (l,c) (l,c) (l,c) s) == B.empty
it " takeBounds is the same as old one " $ property $
\p - > takeBoundsOld ( FU.initPosition , p ) btext
= = takeBounds ( FU.initPosition , p ) btext
it " takeBounds is the same as old one , with different start pos " $ property $
\p - > takeBoundsOld ( FU.Position 0 2 2 , ) btext
= = takeBounds ( FU.Position 0 2 2 , ) btext
it "takeBounds is the same as old one" $ property $
\p -> takeBoundsOld (FU.initPosition, p) btext
== takeBounds (FU.initPosition, p) btext
it "takeBounds is the same as old one, with different start pos" $ property $
\p -> takeBoundsOld (FU.Position 0 2 2, unwrapPO p) btext
== takeBounds (FU.Position 0 2 2, unwrapPO p) btext
-}
it "takeBounds test 1" $
(fst $ takeBounds (FU.Position 0 2 2 "" Nothing, FU.Position 0 5 2 "" Nothing) btext)
`shouldBe` (B.pack "A B")
it "takeBounds test 2" $
(fst $ takeBounds (FU.Position 0 2 2 "" Nothing, FU.Position 0 1 3 "" Nothing) btext)
`shouldBe` (B.pack "A B C D\n")
it "takeBound test 3" $
(fst $ takeBounds (FU.Position 1 1 1 "" Nothing, FU.Position 1 5 3 "" Nothing) btext2)
`shouldBe` (B.pack $ unlines $ take 3 text2)
let simpleDir = " tests " < / > " fixtures "
simpleExpected = simpleDir < / > " simple.expected.f90 "
simpleOut = simpleDir < / > " "
runIO $ unitsSynth simpleIn ( Just simpleIn ) [ ]
simpleOut
it " Unit synth " $ actual ` shouldBe ` expected
data PlusOne a = PlusOne { _unwrapPO :: a } deriving Show
instance Arbitrary (PlusOne FU.Position) where
arbitrary = do
FU.Position offset col line f p <- arbitrary
let col' = if line == 1 then col+1 else col
return $ PlusOne $ FU.Position offset col' (line + 1) f p
instance Arbitrary FU.Position where
arbitrary = do
offset <- arbitrary `suchThat` (>0)
line <- arbitrary `suchThat` (\x -> x >= 1 && x <= (length text))
col <- choose (1, orOne $ length (text !! (line - 1)))
return $ FU.Position offset col line "<generated>" Nothing
orOne :: (Eq p, Num p) => p -> p
orOne x | x == 0 = 1
| otherwise = x
Arbtirary ByteString
instance Arbitrary B.ByteString where
arbitrary = do
numLines <- choose (0, 3)
return . B.pack . concat $ take numLines text
btext :: B.ByteString
btext = B.pack . unlines $ text
text :: [[Char]]
text = ["A B C D"
,""
," E F"
," G H I J K L"]
btext2 :: B.ByteString
btext2 = B.pack . unlines $ text2
text2 :: [[Char]]
text2 = ["A B C D"
,"E F"
,"G H"
,"I J K L"]
takeBoundsOld : : ( FU.Position , FU.Position ) - > SourceText - > ( SourceText , SourceText )
takeBoundsOld ( l , u ) = takeBounds ' ( ( ll , lc ) , ( ul , ) ) B.empty
where ( FU.Position _ lc ll ) = l
( FU.Position _ uc ul ) = u
( ( ll , lc ) , ( ul , ) ) tk inp =
if ( ll = = ul & & lc = = uc ) || ( ll > ul ) then ( B.reverse tk , inp )
else
case B.uncons inp of
Nothing - > ( B.reverse tk , inp )
Just ( ' \n ' , ys ) - > takeBounds ' ( ( ll+1 , 1 ) , ( ul , ) ) ( B.cons ' \n ' tk ) ys
Just ( x , xs ) - > takeBounds ' ( ( ll , lc+1 ) , ( ul , ) ) ( B.cons x tk ) xs
takeBoundsOld :: (FU.Position, FU.Position) -> SourceText -> (SourceText, SourceText)
takeBoundsOld (l, u) = takeBounds' ((ll, lc), (ul, uc)) B.empty
where (FU.Position _ lc ll) = l
(FU.Position _ uc ul) = u
takeBounds' ((ll, lc), (ul, uc)) tk inp =
if (ll == ul && lc == uc) || (ll > ul) then (B.reverse tk, inp)
else
case B.uncons inp of
Nothing -> (B.reverse tk, inp)
Just ('\n', ys) -> takeBounds' ((ll+1, 1), (ul, uc)) (B.cons '\n' tk) ys
Just (x, xs) -> takeBounds' ((ll, lc+1), (ul, uc)) (B.cons x tk) xs
-}
|
de6f9d860c030af0e8b5337ffe0e1cc633a8437760e29402ad2b7a83076f821e | nikomatsakis/a-mir-formality | substitution.rkt | #lang racket
(require redex/reduction-semantics
"grammar.rkt"
"env.rkt"
)
(provide substitution-to-fresh-vars
apply-substitution
apply-substitution-from-env
apply-substitution-to-env
create-substitution
env-fix
substitution-fix
substitution-concat-disjoint
substitution-domain
substitution-without-vars
substitution-maps-var
substitution-valid?
env-with-var-mapped-to
)
(define-metafunction formality-logic
Returns an ` Env ` where ` VarId ` is mapped to ` Parameter ` ( ` VarId ` must not yet be mapped )
env-with-var-mapped-to : Env_in VarId_in Parameter_in -> Env_out
#:pre (env-contains-unmapped-existential-var Env_in VarId_in)
[(env-with-var-mapped-to Env VarId Parameter)
(Hook Universe VarBinders ((VarId Parameter) (VarId_env Parameter_env) ...) VarInequalities Hypotheses)
(where/error (Hook Universe VarBinders ((VarId_env Parameter_env) ...) VarInequalities Hypotheses) Env)
]
)
(define-metafunction formality-logic
True if the substitution includes ` VarId ` in its domain
substitution-maps-var : Substitution VarId -> boolean
[(substitution-maps-var (_ ... (VarId _) _ ...) VarId) #t]
[(substitution-maps-var (_ ...) VarId) #f]
)
(define-metafunction formality-logic
;; Returns the variables that are mapped by a substitution.
substitution-domain : Substitution -> VarIds
[(substitution-domain ((VarId Parameter) ...))
(VarId ...)
]
)
(define-metafunction formality-logic
;; Given a set of kinded-var-ids, creates a substituion map that maps them to
;; fresh names.
substitution-to-fresh-vars : Term KindedVarIds -> Substitution
[(substitution-to-fresh-vars Term ((ParameterKind VarId) ...))
((VarId VarId_fresh) ...)
(where/error (VarId_fresh ...) (fresh-var-ids Term (VarId ...)))
]
)
(define-metafunction formality-logic
;; Given a set of kinded-var-ids and values for those var-ids, creates a substitution.
create-substitution : KindedVarIds Parameters -> Substitution
[(create-substitution ((ParameterKind VarId) ..._1) (Parameter ..._1))
((VarId Parameter) ...)
]
)
(define-metafunction formality-logic
Concatenates various substitutions that have disjoint domains .
substitution-concat-disjoint : Substitution ... -> Substitution
[(substitution-concat-disjoint Substitution ...)
,(apply append (term (Substitution ...)))]
)
(define-metafunction formality-logic
;; Substitute substitution-map any ==> applies a substitution map to anything
apply-substitution : Substitution Term -> Term
[(apply-substitution () Term) Term]
[(apply-substitution ((VarId_0 Term_0) (VarId_1 Term_1) ...) Term_term)
(apply-substitution ((VarId_1 Term_1) ...) (substitute Term_term VarId_0 Term_0))]
)
(define-metafunction formality-logic
;; Substitute the values for any inference variables found in Env to Term.
apply-substitution-from-env : Env Term -> Term
[(apply-substitution-from-env Env Term)
(apply-substitution Substitution Term)
(where/error Substitution (env-substitution Env))]
)
(define-metafunction formality-logic
;; A substitution is *valid* in the environment if
;;
;; * it maps distinct variables
;; * the keys are existentially bound variables
;; * the values for each variable do not reference anything outside of its universe
substitution-valid? : Env Substitution -> boolean
FIXME this is incomplete
(substitution-valid? Env ((VarId_!_1 Parameter) ...)) #t]
)
(define-metafunction formality-logic
;; Substitute substitution-map any ==> applies a substitution map to anything
substitution-without-vars : Substitution VarIds -> Substitution
[(substitution-without-vars () VarIds)
()
]
[(substitution-without-vars ((VarId_0 Term_0) (VarId_1 Term_1) ...) VarIds)
(substitution-without-vars ((VarId_1 Term_1) ...) VarIds)
(where (_ ... VarId_0 _ ...) VarIds)
]
[(substitution-without-vars ((VarId_0 Term_0) (VarId_1 Term_1) ...) VarIds)
((VarId_0 Term_0) (VarId_2 Term_2) ...)
(where/error ((VarId_2 Term_2) ...) (substitution-without-vars ((VarId_1 Term_1) ...) VarIds))
]
)
(define-metafunction formality-logic
;; Apply the environment's substitution to itself until a fixed point is reached.
;; Return the new environment with this fixed point.
env-fix : Env -> Env
[(env-fix Env)
(apply-substitution-to-env Substitution_fix Env)
(where Substitution_fix (subsitution-fix (env-substitution Env)))
]
)
(define-metafunction formality-logic
;; Applies the substitution to *itself* until a fixed point is reached.
substitution-fix : Substitution -> Substitution
[; if the result of applying substitution to itself has no change, all done
(substitution-fix Substitution_0)
Substitution_0
(where Substitution_0 (apply-substitution-to-substitution Substitution_0 Substitution_0))
]
[; otherwise recursively apply
(substitution-fix Substitution_0)
(substitution-fix Substitution_1)
(where/error Substitution_1 (apply-substitution-to-substitution Substitution_0 Substitution_0))
]
)
(define-metafunction formality-logic
;; Applies the substitution to an environment (not all parts of the
;; environment ought to be substituted).
apply-substitution-to-env : Substitution Env -> Env
[(apply-substitution-to-env Substitution (Hook Universe VarBinders Substitution_env VarInequalities Hypotheses))
(Hook
Universe
VarBinders
(apply-substitution-to-substitution Substitution Substitution_env)
(apply-substitution Substitution VarInequalities) ; the domain of the inequality *ought* to be disjoint from domain of substitution
(apply-substitution Substitution Hypotheses))]
)
(define-metafunction formality-logic
;; Applies the substitution to an environment (not all parts of the
;; environment ought to be substituted).
apply-substitution-to-substitution : Substitution Substitution -> Substitution
[(apply-substitution-to-substitution Substitution_0 ((VarId_0 Parameter_0) ...))
((VarId_0 Parameter_1) ...)
(where/error (Parameter_1 ...) (apply-substitution Substitution_0 (Parameter_0 ...)))
]
)
(module+ test
(test-equal (term (apply-substitution
((x x1) (y y1))
(x (∀ (type x) (x y) y))))
(term (x1 (∀ (type x1) (x1 y1) y1))))
(test-equal (term (apply-substitution
((x x1) (y y1))
(x (∀ (type z) (x y z) y))))
(term (x1 (∀ (type z) (x1 y1 z) y1))))
(test-equal (term (substitution-fix
((x (rigid-ty SomeType (y)))
(y y1)
(z x))))
(term ((x (rigid-ty SomeType (y1)))
(y y1)
(z (rigid-ty SomeType (y1))))))
(test-equal (term (substitution-without-vars
((x x1) (y y1) (z z1))
(y)))
(term ((x x1) (z z1))))
) | null | https://raw.githubusercontent.com/nikomatsakis/a-mir-formality/71be4d5c4bd5e91d326277eaedd19a7abe3ac76a/racket-src/logic/substitution.rkt | racket | Returns the variables that are mapped by a substitution.
Given a set of kinded-var-ids, creates a substituion map that maps them to
fresh names.
Given a set of kinded-var-ids and values for those var-ids, creates a substitution.
Substitute substitution-map any ==> applies a substitution map to anything
Substitute the values for any inference variables found in Env to Term.
A substitution is *valid* in the environment if
* it maps distinct variables
* the keys are existentially bound variables
* the values for each variable do not reference anything outside of its universe
Substitute substitution-map any ==> applies a substitution map to anything
Apply the environment's substitution to itself until a fixed point is reached.
Return the new environment with this fixed point.
Applies the substitution to *itself* until a fixed point is reached.
if the result of applying substitution to itself has no change, all done
otherwise recursively apply
Applies the substitution to an environment (not all parts of the
environment ought to be substituted).
the domain of the inequality *ought* to be disjoint from domain of substitution
Applies the substitution to an environment (not all parts of the
environment ought to be substituted). | #lang racket
(require redex/reduction-semantics
"grammar.rkt"
"env.rkt"
)
(provide substitution-to-fresh-vars
apply-substitution
apply-substitution-from-env
apply-substitution-to-env
create-substitution
env-fix
substitution-fix
substitution-concat-disjoint
substitution-domain
substitution-without-vars
substitution-maps-var
substitution-valid?
env-with-var-mapped-to
)
(define-metafunction formality-logic
Returns an ` Env ` where ` VarId ` is mapped to ` Parameter ` ( ` VarId ` must not yet be mapped )
env-with-var-mapped-to : Env_in VarId_in Parameter_in -> Env_out
#:pre (env-contains-unmapped-existential-var Env_in VarId_in)
[(env-with-var-mapped-to Env VarId Parameter)
(Hook Universe VarBinders ((VarId Parameter) (VarId_env Parameter_env) ...) VarInequalities Hypotheses)
(where/error (Hook Universe VarBinders ((VarId_env Parameter_env) ...) VarInequalities Hypotheses) Env)
]
)
(define-metafunction formality-logic
True if the substitution includes ` VarId ` in its domain
substitution-maps-var : Substitution VarId -> boolean
[(substitution-maps-var (_ ... (VarId _) _ ...) VarId) #t]
[(substitution-maps-var (_ ...) VarId) #f]
)
(define-metafunction formality-logic
substitution-domain : Substitution -> VarIds
[(substitution-domain ((VarId Parameter) ...))
(VarId ...)
]
)
(define-metafunction formality-logic
substitution-to-fresh-vars : Term KindedVarIds -> Substitution
[(substitution-to-fresh-vars Term ((ParameterKind VarId) ...))
((VarId VarId_fresh) ...)
(where/error (VarId_fresh ...) (fresh-var-ids Term (VarId ...)))
]
)
(define-metafunction formality-logic
create-substitution : KindedVarIds Parameters -> Substitution
[(create-substitution ((ParameterKind VarId) ..._1) (Parameter ..._1))
((VarId Parameter) ...)
]
)
(define-metafunction formality-logic
Concatenates various substitutions that have disjoint domains .
substitution-concat-disjoint : Substitution ... -> Substitution
[(substitution-concat-disjoint Substitution ...)
,(apply append (term (Substitution ...)))]
)
(define-metafunction formality-logic
apply-substitution : Substitution Term -> Term
[(apply-substitution () Term) Term]
[(apply-substitution ((VarId_0 Term_0) (VarId_1 Term_1) ...) Term_term)
(apply-substitution ((VarId_1 Term_1) ...) (substitute Term_term VarId_0 Term_0))]
)
(define-metafunction formality-logic
apply-substitution-from-env : Env Term -> Term
[(apply-substitution-from-env Env Term)
(apply-substitution Substitution Term)
(where/error Substitution (env-substitution Env))]
)
(define-metafunction formality-logic
substitution-valid? : Env Substitution -> boolean
FIXME this is incomplete
(substitution-valid? Env ((VarId_!_1 Parameter) ...)) #t]
)
(define-metafunction formality-logic
substitution-without-vars : Substitution VarIds -> Substitution
[(substitution-without-vars () VarIds)
()
]
[(substitution-without-vars ((VarId_0 Term_0) (VarId_1 Term_1) ...) VarIds)
(substitution-without-vars ((VarId_1 Term_1) ...) VarIds)
(where (_ ... VarId_0 _ ...) VarIds)
]
[(substitution-without-vars ((VarId_0 Term_0) (VarId_1 Term_1) ...) VarIds)
((VarId_0 Term_0) (VarId_2 Term_2) ...)
(where/error ((VarId_2 Term_2) ...) (substitution-without-vars ((VarId_1 Term_1) ...) VarIds))
]
)
(define-metafunction formality-logic
env-fix : Env -> Env
[(env-fix Env)
(apply-substitution-to-env Substitution_fix Env)
(where Substitution_fix (subsitution-fix (env-substitution Env)))
]
)
(define-metafunction formality-logic
substitution-fix : Substitution -> Substitution
(substitution-fix Substitution_0)
Substitution_0
(where Substitution_0 (apply-substitution-to-substitution Substitution_0 Substitution_0))
]
(substitution-fix Substitution_0)
(substitution-fix Substitution_1)
(where/error Substitution_1 (apply-substitution-to-substitution Substitution_0 Substitution_0))
]
)
(define-metafunction formality-logic
apply-substitution-to-env : Substitution Env -> Env
[(apply-substitution-to-env Substitution (Hook Universe VarBinders Substitution_env VarInequalities Hypotheses))
(Hook
Universe
VarBinders
(apply-substitution-to-substitution Substitution Substitution_env)
(apply-substitution Substitution Hypotheses))]
)
(define-metafunction formality-logic
apply-substitution-to-substitution : Substitution Substitution -> Substitution
[(apply-substitution-to-substitution Substitution_0 ((VarId_0 Parameter_0) ...))
((VarId_0 Parameter_1) ...)
(where/error (Parameter_1 ...) (apply-substitution Substitution_0 (Parameter_0 ...)))
]
)
(module+ test
(test-equal (term (apply-substitution
((x x1) (y y1))
(x (∀ (type x) (x y) y))))
(term (x1 (∀ (type x1) (x1 y1) y1))))
(test-equal (term (apply-substitution
((x x1) (y y1))
(x (∀ (type z) (x y z) y))))
(term (x1 (∀ (type z) (x1 y1 z) y1))))
(test-equal (term (substitution-fix
((x (rigid-ty SomeType (y)))
(y y1)
(z x))))
(term ((x (rigid-ty SomeType (y1)))
(y y1)
(z (rigid-ty SomeType (y1))))))
(test-equal (term (substitution-without-vars
((x x1) (y y1) (z z1))
(y)))
(term ((x x1) (z z1))))
) |
9200ea4823dd91574f75b5bd21f8e8f154db0551849219e00bfcc2a059baec87 | nyinyithann/favemarks | common.ml | open Core
module T = ANSITerminal
let is_whitespace s = s |> String.strip |> String.is_empty
let strip_and_lowercase s = String.(lowercase @@ strip s)
let epoch_str () = Time_unix.to_string Time_unix.epoch
let map_input_to_result input =
if String.(strip_and_lowercase input = "") then Error "" else Ok input
;;
let result_to_msg_opt (r : (string, string) result) =
match r with
| Ok s ->
if String.(s = "") then None else Some (T.sprintf [ T.Foreground T.Green ] "%s" s)
| Error e ->
if String.(e = "") then None else Some (T.sprintf [ T.Foreground T.Red ] "%s" e)
;;
let time_of_string str =
try Time_unix.of_string str with
| _ -> Time_unix.epoch
;;
let string_of_time (time : Time_unix.t) =
try
let time_str =
Time_unix.format time "%H:%M" ~zone:(Lazy.force Time_unix.Zone.local)
in
let date_str =
Time_unix.format time "%d/%m/%y" ~zone:(Lazy.force Time_unix.Zone.local)
in
let h = int_of_string @@ String.slice time_str 0 2 in
sprintf
"%s %2d:%s %s"
date_str
(if h >= 12 then h - 12 else h)
(String.slice time_str 3 5)
(if h >= 12 then "PM" else "AM")
with
| _ -> epoch_str ()
;;
let strip_space_and_concat ~sep str =
str |> String.split ~on:',' |> List.map ~f:String.strip |> String.concat ~sep
;;
let is_url_valid url =
let re =
Re.Perl.re
{|((http|https)://)?(www.)?[a-zA-Z0-9@:%._\+~#?&//=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%._\+~#?&//=]*)|}
|> Re.compile
in
Re.execp re url
;;
let validate_tags tags =
(not @@ is_whitespace tags)
&& (not
@@ String.(
split tags ~on:','
|> List.exists ~f:(fun x ->
let sx = strip x in
sx = "" || exists sx ~f:Char.is_whitespace)))
;;
let validate_fields fields input =
fields
|> List.exists ~f:(fun x -> String.(strip_and_lowercase x = strip_and_lowercase input))
;;
let tuple_of_first_two = function
| f :: s :: _ -> Some (f, s)
| _ -> None
;;
let get_os_type () =
if String.(Sys.os_type = "Unix")
then (
try
let ic = Caml_unix.open_process_in "uname -s" in
let r = In_channel.input_line ic in
In_channel.close ic;
match r with
| Some name when String.(name = "Darwin") -> Ok `MacOS
| _ -> Ok `Linux
with
| e -> Error (Exn.to_string e))
else Error "The OS is not supported."
;;
let normalize_url url =
if String.(is_prefix ~prefix:"http://" url || is_prefix ~prefix:"https://" url)
then url
else "https://" ^ url
;;
module Browser = struct
let chrome_key = "Chrome"
let safari_key = "Safari"
let edge_key = "Edge"
let firefox_key = "Firefox"
let brave_key = "Brave"
let mac_browsers =
[ chrome_key, "Google Chrome"
; safari_key, "Safari"
; edge_key, "Microsoft Edge"
; firefox_key, "Firefox"
; brave_key, "Brave Browser"
]
;;
(* Just a name *)
let other_os_default_browser = "Default Browser"
let mac_browser_keys =
sprintf "%s, %s, %s, %s, %s" chrome_key safari_key edge_key firefox_key brave_key
;;
let mac_browser_key_list =
String.
[ lowercase chrome_key
; lowercase safari_key
; lowercase edge_key
; lowercase firefox_key
; lowercase brave_key
]
;;
let get_browser_keys () =
match get_os_type () with
| Ok `MacOS -> mac_browser_keys
| Ok `Linux -> other_os_default_browser
| _ -> ""
;;
let get_browser_key_list () =
match get_os_type () with
| Ok `MacOS -> mac_browser_key_list
| Ok `Linux -> [ other_os_default_browser ]
| _ -> []
;;
let get_browser_name key =
match
(other_os_default_browser, other_os_default_browser) :: mac_browsers
|> List.find ~f:(fun (k, _) -> String.(lowercase key = lowercase k))
with
| Some (_, n) -> Ok n
| None -> Error (sprintf "%s is not found." key)
;;
end
| null | https://raw.githubusercontent.com/nyinyithann/favemarks/55fb52d4f3efeae8ef478f1fe098456196e80dea/src/common/common.ml | ocaml | Just a name | open Core
module T = ANSITerminal
let is_whitespace s = s |> String.strip |> String.is_empty
let strip_and_lowercase s = String.(lowercase @@ strip s)
let epoch_str () = Time_unix.to_string Time_unix.epoch
let map_input_to_result input =
if String.(strip_and_lowercase input = "") then Error "" else Ok input
;;
let result_to_msg_opt (r : (string, string) result) =
match r with
| Ok s ->
if String.(s = "") then None else Some (T.sprintf [ T.Foreground T.Green ] "%s" s)
| Error e ->
if String.(e = "") then None else Some (T.sprintf [ T.Foreground T.Red ] "%s" e)
;;
let time_of_string str =
try Time_unix.of_string str with
| _ -> Time_unix.epoch
;;
let string_of_time (time : Time_unix.t) =
try
let time_str =
Time_unix.format time "%H:%M" ~zone:(Lazy.force Time_unix.Zone.local)
in
let date_str =
Time_unix.format time "%d/%m/%y" ~zone:(Lazy.force Time_unix.Zone.local)
in
let h = int_of_string @@ String.slice time_str 0 2 in
sprintf
"%s %2d:%s %s"
date_str
(if h >= 12 then h - 12 else h)
(String.slice time_str 3 5)
(if h >= 12 then "PM" else "AM")
with
| _ -> epoch_str ()
;;
let strip_space_and_concat ~sep str =
str |> String.split ~on:',' |> List.map ~f:String.strip |> String.concat ~sep
;;
let is_url_valid url =
let re =
Re.Perl.re
{|((http|https)://)?(www.)?[a-zA-Z0-9@:%._\+~#?&//=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%._\+~#?&//=]*)|}
|> Re.compile
in
Re.execp re url
;;
let validate_tags tags =
(not @@ is_whitespace tags)
&& (not
@@ String.(
split tags ~on:','
|> List.exists ~f:(fun x ->
let sx = strip x in
sx = "" || exists sx ~f:Char.is_whitespace)))
;;
let validate_fields fields input =
fields
|> List.exists ~f:(fun x -> String.(strip_and_lowercase x = strip_and_lowercase input))
;;
let tuple_of_first_two = function
| f :: s :: _ -> Some (f, s)
| _ -> None
;;
let get_os_type () =
if String.(Sys.os_type = "Unix")
then (
try
let ic = Caml_unix.open_process_in "uname -s" in
let r = In_channel.input_line ic in
In_channel.close ic;
match r with
| Some name when String.(name = "Darwin") -> Ok `MacOS
| _ -> Ok `Linux
with
| e -> Error (Exn.to_string e))
else Error "The OS is not supported."
;;
let normalize_url url =
if String.(is_prefix ~prefix:"http://" url || is_prefix ~prefix:"https://" url)
then url
else "https://" ^ url
;;
module Browser = struct
let chrome_key = "Chrome"
let safari_key = "Safari"
let edge_key = "Edge"
let firefox_key = "Firefox"
let brave_key = "Brave"
let mac_browsers =
[ chrome_key, "Google Chrome"
; safari_key, "Safari"
; edge_key, "Microsoft Edge"
; firefox_key, "Firefox"
; brave_key, "Brave Browser"
]
;;
let other_os_default_browser = "Default Browser"
let mac_browser_keys =
sprintf "%s, %s, %s, %s, %s" chrome_key safari_key edge_key firefox_key brave_key
;;
let mac_browser_key_list =
String.
[ lowercase chrome_key
; lowercase safari_key
; lowercase edge_key
; lowercase firefox_key
; lowercase brave_key
]
;;
let get_browser_keys () =
match get_os_type () with
| Ok `MacOS -> mac_browser_keys
| Ok `Linux -> other_os_default_browser
| _ -> ""
;;
let get_browser_key_list () =
match get_os_type () with
| Ok `MacOS -> mac_browser_key_list
| Ok `Linux -> [ other_os_default_browser ]
| _ -> []
;;
let get_browser_name key =
match
(other_os_default_browser, other_os_default_browser) :: mac_browsers
|> List.find ~f:(fun (k, _) -> String.(lowercase key = lowercase k))
with
| Some (_, n) -> Ok n
| None -> Error (sprintf "%s is not found." key)
;;
end
|
09f9c14f8431617a5dbbf818cef3bbec5bc45d81ae0e7222026fc25c2d233352 | TyOverby/mono | request.ml | include Cohttp.Request
| null | https://raw.githubusercontent.com/TyOverby/mono/8d6b3484d5db63f2f5472c7367986ea30290764d/vendor/mirage-ocaml-cohttp/cohttp-async/src/request.ml | ocaml | include Cohttp.Request
| |
0cea5c12e7f8dad4393f4133201c9fc13723d9ad2f3e598e9e94cbc4c5769a7d | stathissideris/positano | time.clj | (ns positano.time
(:require [clojure.string :as str]))
(def second-in-millis 1000)
(def minute (* 60 second-in-millis))
(def hour (* 60 minute))
(def day (* 24 hour))
(def month (* 30 day))
(def year (* 365 day))
(defn to-millis [x]
(.getTime x))
(defn duration [millis]
(let [years (int (/ millis year))
millis (mod millis year)
months (int (/ millis month))
millis (mod millis month)
days (int (/ millis day))
millis (mod millis day)
hours (int (/ millis hour))
millis (mod millis hour)
minutes (int (/ millis minute))
millis (mod millis minute)
seconds (int (/ millis second-in-millis))
millis (mod millis second-in-millis)]
(merge
(when-not (zero? years) {:years years})
(when-not (zero? months) {:months months})
(when-not (zero? days) {:days days})
(when-not (zero? hours) {:hours hours})
(when-not (zero? minutes) {:minutes minutes})
(when-not (zero? seconds) {:seconds seconds})
{:millis millis})))
(defn difference [a b]
(duration
(- (to-millis b) (to-millis a))))
(defn duration-string [{:keys [years months days hours minutes seconds millis] :as d}]
(let [has? (fn [x] (and x (not (zero? x))))]
(if (and (= 1 (count d)) (:millis d)) (str millis "msec")
(str/join
", "
(remove nil?
[(when (has? years) (str years " years"))
(when (has? months) (str months " months"))
(when (has? days) (str days " days"))
(when (has? hours) (str hours "h"))
(when (has? minutes) (str minutes "min"))
(when (has? seconds) (str seconds "sec"))
(when (has? millis) (str millis "msec"))])))))
| null | https://raw.githubusercontent.com/stathissideris/positano/ca5126714b4bcf108726d930ab61a875759214ae/src/positano/time.clj | clojure | (ns positano.time
(:require [clojure.string :as str]))
(def second-in-millis 1000)
(def minute (* 60 second-in-millis))
(def hour (* 60 minute))
(def day (* 24 hour))
(def month (* 30 day))
(def year (* 365 day))
(defn to-millis [x]
(.getTime x))
(defn duration [millis]
(let [years (int (/ millis year))
millis (mod millis year)
months (int (/ millis month))
millis (mod millis month)
days (int (/ millis day))
millis (mod millis day)
hours (int (/ millis hour))
millis (mod millis hour)
minutes (int (/ millis minute))
millis (mod millis minute)
seconds (int (/ millis second-in-millis))
millis (mod millis second-in-millis)]
(merge
(when-not (zero? years) {:years years})
(when-not (zero? months) {:months months})
(when-not (zero? days) {:days days})
(when-not (zero? hours) {:hours hours})
(when-not (zero? minutes) {:minutes minutes})
(when-not (zero? seconds) {:seconds seconds})
{:millis millis})))
(defn difference [a b]
(duration
(- (to-millis b) (to-millis a))))
(defn duration-string [{:keys [years months days hours minutes seconds millis] :as d}]
(let [has? (fn [x] (and x (not (zero? x))))]
(if (and (= 1 (count d)) (:millis d)) (str millis "msec")
(str/join
", "
(remove nil?
[(when (has? years) (str years " years"))
(when (has? months) (str months " months"))
(when (has? days) (str days " days"))
(when (has? hours) (str hours "h"))
(when (has? minutes) (str minutes "min"))
(when (has? seconds) (str seconds "sec"))
(when (has? millis) (str millis "msec"))])))))
| |
66c0fb680b89029284ed77edd5279414c44e17355b2d792a38dbaa6f73c41ffc | snoyberg/conduit | Conduit.hs | # OPTIONS_HADDOCK not - home #
# LANGUAGE DeriveFunctor #
# LANGUAGE FlexibleInstances #
# LANGUAGE FlexibleContexts #
# LANGUAGE CPP #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE UndecidableInstances #
{-# LANGUAGE RankNTypes #-}
# LANGUAGE TupleSections #
# LANGUAGE Trustworthy #
# LANGUAGE TypeFamilies #
module Data.Conduit.Internal.Conduit
( -- ** Types
ConduitT (..)
, ConduitM
, Source
, Producer
, Sink
, Consumer
, Conduit
, Flush (..)
* * * Newtype wrappers
, ZipSource (..)
, ZipSink (..)
, ZipConduit (..)
-- ** Sealed
, SealedConduitT (..)
, sealConduitT
, unsealConduitT
-- ** Primitives
, await
, awaitForever
, yield
, yieldM
, leftover
, runConduit
, runConduitPure
, runConduitRes
, fuse
, connect
, unconsM
, unconsEitherM
-- ** Composition
, connectResume
, connectResumeConduit
, fuseLeftovers
, fuseReturnLeftovers
, ($$+)
, ($$++)
, ($$+-)
, ($=+)
, (=$$+)
, (=$$++)
, (=$$+-)
, ($$)
, ($=)
, (=$)
, (=$=)
, (.|)
-- ** Generalizing
, sourceToPipe
, sinkToPipe
, conduitToPipe
, toProducer
, toConsumer
-- ** Cleanup
, bracketP
-- ** Exceptions
, catchC
, handleC
, tryC
-- ** Utilities
, Data.Conduit.Internal.Conduit.transPipe
, Data.Conduit.Internal.Conduit.mapOutput
, Data.Conduit.Internal.Conduit.mapOutputMaybe
, Data.Conduit.Internal.Conduit.mapInput
, Data.Conduit.Internal.Conduit.mapInputM
, zipSinks
, zipSources
, zipSourcesApp
, zipConduitApp
, mergeSource
, passthroughSink
, sourceToList
, fuseBoth
, fuseBothMaybe
, fuseUpstream
, sequenceSources
, sequenceSinks
, sequenceConduits
) where
import Control.Applicative (Applicative (..))
import Control.Exception (Exception)
import qualified Control.Exception as E (catch)
import Control.Monad (liftM, liftM2, ap)
import Control.Monad.Fail(MonadFail(..))
import Control.Monad.Error.Class(MonadError(..))
import Control.Monad.Reader.Class(MonadReader(..))
import Control.Monad.RWS.Class(MonadRWS())
import Control.Monad.Writer.Class(MonadWriter(..), censor)
import Control.Monad.State.Class(MonadState(..))
import Control.Monad.Trans.Class (MonadTrans (lift))
import Control.Monad.IO.Unlift (MonadIO (liftIO), MonadUnliftIO, withRunInIO)
import Control.Monad.Primitive (PrimMonad, PrimState, primitive)
import Data.Functor.Identity (Identity, runIdentity)
import Data.Void (Void, absurd)
import Data.Monoid (Monoid (mappend, mempty))
import Data.Semigroup (Semigroup ((<>)))
import Control.Monad.Trans.Resource
import Data.Conduit.Internal.Pipe hiding (yield, mapOutput, leftover, yieldM, await, awaitForever, bracketP, unconsM, unconsEitherM)
import qualified Data.Conduit.Internal.Pipe as CI
import Control.Monad (forever)
import Data.Traversable (Traversable (..))
-- | Core datatype of the conduit package. This type represents a general
component which can consume a stream of input values @i@ , produce a stream
of output values @o@ , perform actions in the @m@ monad , and produce a final
result @r@. The type synonyms provided here are simply wrappers around this
-- type.
--
-- Since 1.3.0
newtype ConduitT i o m r = ConduitT
{ unConduitT :: forall b.
(r -> Pipe i i o () m b) -> Pipe i i o () m b
}
-- | In order to provide for efficient monadic composition, the
-- @ConduitT@ type is implemented internally using a technique known
-- as the codensity transform. This allows for cheap appending, but
makes one case much more expensive : partially running a @ConduitT@
-- and that capturing the new state.
--
-- This data type is the same as @ConduitT@, but does not use the
-- codensity transform technique.
--
-- @since 1.3.0
newtype SealedConduitT i o m r = SealedConduitT (Pipe i i o () m r)
-- | Same as 'ConduitT', for backwards compat
type ConduitM = ConduitT
instance Functor (ConduitT i o m) where
fmap f (ConduitT c) = ConduitT $ \rest -> c (rest . f)
instance Applicative (ConduitT i o m) where
pure x = ConduitT ($ x)
# INLINE pure #
(<*>) = ap
{-# INLINE (<*>) #-}
(*>) = (>>)
{-# INLINE (*>) #-}
instance Monad (ConduitT i o m) where
return = pure
ConduitT f >>= g = ConduitT $ \h -> f $ \a -> unConduitT (g a) h
-- | @since 1.3.1
instance MonadFail m => MonadFail (ConduitT i o m) where
fail = lift . Control.Monad.Fail.fail
instance MonadThrow m => MonadThrow (ConduitT i o m) where
throwM = lift . throwM
instance MonadIO m => MonadIO (ConduitT i o m) where
liftIO = lift . liftIO
# INLINE liftIO #
instance MonadReader r m => MonadReader r (ConduitT i o m) where
ask = lift ask
# INLINE ask #
local f (ConduitT c0) = ConduitT $ \rest ->
let go (HaveOutput p o) = HaveOutput (go p) o
go (NeedInput p c) = NeedInput (\i -> go (p i)) (\u -> go (c u))
go (Done x) = rest x
go (PipeM mp) = PipeM (liftM go $ local f mp)
go (Leftover p i) = Leftover (go p) i
in go (c0 Done)
#ifndef MIN_VERSION_mtl
#define MIN_VERSION_mtl(x, y, z) 0
#endif
instance MonadWriter w m => MonadWriter w (ConduitT i o m) where
#if MIN_VERSION_mtl(2, 1, 0)
writer = lift . writer
#endif
tell = lift . tell
listen (ConduitT c0) = ConduitT $ \rest ->
let go front (HaveOutput p o) = HaveOutput (go front p) o
go front (NeedInput p c) = NeedInput (\i -> go front (p i)) (\u -> go front (c u))
go front (Done x) = rest (x, front)
go front (PipeM mp) = PipeM $ do
(p,w) <- listen mp
return $ go (front `mappend` w) p
go front (Leftover p i) = Leftover (go front p) i
in go mempty (c0 Done)
pass (ConduitT c0) = ConduitT $ \rest ->
let go front (HaveOutput p o) = HaveOutput (go front p) o
go front (NeedInput p c) = NeedInput (\i -> go front (p i)) (\u -> go front (c u))
go front (PipeM mp) = PipeM $ do
(p,w) <- censor (const mempty) (listen mp)
return $ go (front `mappend` w) p
go front (Done (x,f)) = PipeM $ do
tell (f front)
return $ rest x
go front (Leftover p i) = Leftover (go front p) i
in go mempty (c0 Done)
instance MonadState s m => MonadState s (ConduitT i o m) where
get = lift get
put = lift . put
#if MIN_VERSION_mtl(2, 1, 0)
state = lift . state
#endif
instance MonadRWS r w s m => MonadRWS r w s (ConduitT i o m)
instance MonadError e m => MonadError e (ConduitT i o m) where
throwError = lift . throwError
catchError (ConduitT c0) f = ConduitT $ \rest ->
let go (HaveOutput p o) = HaveOutput (go p) o
go (NeedInput p c) = NeedInput (\i -> go (p i)) (\u -> go (c u))
go (Done x) = rest x
go (PipeM mp) =
PipeM $ catchError (liftM go mp) $ \e -> do
return $ unConduitT (f e) rest
go (Leftover p i) = Leftover (go p) i
in go (c0 Done)
instance MonadTrans (ConduitT i o) where
lift mr = ConduitT $ \rest -> PipeM (liftM rest mr)
# INLINE [ 1 ] lift #
instance MonadResource m => MonadResource (ConduitT i o m) where
liftResourceT = lift . liftResourceT
# INLINE liftResourceT #
instance Monad m => Semigroup (ConduitT i o m ()) where
(<>) = (>>)
{-# INLINE (<>) #-}
instance Monad m => Monoid (ConduitT i o m ()) where
mempty = return ()
# INLINE mempty #
#if !(MIN_VERSION_base(4,11,0))
mappend = (<>)
# INLINE mappend #
#endif
instance PrimMonad m => PrimMonad (ConduitT i o m) where
type PrimState (ConduitT i o m) = PrimState m
primitive = lift . primitive
-- | Provides a stream of output values, without consuming any input or
-- producing a final result.
--
Since 0.5.0
type Source m o = ConduitT () o m ()
{-# DEPRECATED Source "Use ConduitT directly" #-}
-- | A component which produces a stream of output values, regardless of the
-- input stream. A @Producer@ is a generalization of a @Source@, and can be
-- used as either a @Source@ or a @Conduit@.
--
-- Since 1.0.0
type Producer m o = forall i. ConduitT i o m ()
{-# DEPRECATED Producer "Use ConduitT directly" #-}
-- | Consumes a stream of input values and produces a final result, without
-- producing any output.
--
-- > type Sink i m r = ConduitT i Void m r
--
Since 0.5.0
type Sink i = ConduitT i Void
{-# DEPRECATED Sink "Use ConduitT directly" #-}
-- | A component which consumes a stream of input values and produces a final
-- result, regardless of the output stream. A @Consumer@ is a generalization of
a @Sink@ , and can be used as either a @Sink@ or a @Conduit@.
--
-- Since 1.0.0
type Consumer i m r = forall o. ConduitT i o m r
{-# DEPRECATED Consumer "Use ConduitT directly" #-}
-- | Consumes a stream of input values and produces a stream of output values,
-- without producing a final result.
--
Since 0.5.0
type Conduit i m o = ConduitT i o m ()
{-# DEPRECATED Conduit "Use ConduitT directly" #-}
sealConduitT :: ConduitT i o m r -> SealedConduitT i o m r
sealConduitT (ConduitT f) = SealedConduitT (f Done)
unsealConduitT :: Monad m => SealedConduitT i o m r -> ConduitT i o m r
unsealConduitT (SealedConduitT f) = ConduitT (f >>=)
| Connect a @Source@ to a @Sink@ until the latter closes . Returns both the
most recent state of the @Source@ and the result of the
--
Since 0.5.0
connectResume :: Monad m
=> SealedConduitT () a m ()
-> ConduitT a Void m r
-> m (SealedConduitT () a m (), r)
connectResume (SealedConduitT left0) (ConduitT right0) =
goRight left0 (right0 Done)
where
goRight left right =
case right of
HaveOutput _ o -> absurd o
NeedInput rp rc -> goLeft rp rc left
Done r2 -> return (SealedConduitT left, r2)
PipeM mp -> mp >>= goRight left
Leftover p i -> goRight (HaveOutput left i) p
goLeft rp rc left =
case left of
HaveOutput left' o -> goRight left' (rp o)
NeedInput _ lc -> recurse (lc ())
Done () -> goRight (Done ()) (rc ())
PipeM mp -> mp >>= recurse
Leftover p () -> recurse p
where
recurse = goLeft rp rc
sourceToPipe :: Monad m => ConduitT () o m () -> Pipe l i o u m ()
sourceToPipe (ConduitT k) =
go $ k Done
where
go (HaveOutput p o) = HaveOutput (go p) o
go (NeedInput _ c) = go $ c ()
go (Done ()) = Done ()
go (PipeM mp) = PipeM (liftM go mp)
go (Leftover p ()) = go p
sinkToPipe :: Monad m => ConduitT i Void m r -> Pipe l i o u m r
sinkToPipe (ConduitT k) =
go $ injectLeftovers $ k Done
where
go (HaveOutput _ o) = absurd o
go (NeedInput p c) = NeedInput (go . p) (const $ go $ c ())
go (Done r) = Done r
go (PipeM mp) = PipeM (liftM go mp)
go (Leftover _ l) = absurd l
conduitToPipe :: Monad m => ConduitT i o m () -> Pipe l i o u m ()
conduitToPipe (ConduitT k) =
go $ injectLeftovers $ k Done
where
go (HaveOutput p o) = HaveOutput (go p) o
go (NeedInput p c) = NeedInput (go . p) (const $ go $ c ())
go (Done ()) = Done ()
go (PipeM mp) = PipeM (liftM go mp)
go (Leftover _ l) = absurd l
| a ' Source ' to a ' Producer ' .
--
-- Since 1.0.0
toProducer :: Monad m => ConduitT () a m () -> ConduitT i a m ()
toProducer (ConduitT c0) = ConduitT $ \rest -> let
go (HaveOutput p o) = HaveOutput (go p) o
go (NeedInput _ c) = go (c ())
go (Done r) = rest r
go (PipeM mp) = PipeM (liftM go mp)
go (Leftover p ()) = go p
in go (c0 Done)
| a ' Sink ' to a ' Consumer ' .
--
-- Since 1.0.0
toConsumer :: Monad m => ConduitT a Void m b -> ConduitT a o m b
toConsumer (ConduitT c0) = ConduitT $ \rest -> let
go (HaveOutput _ o) = absurd o
go (NeedInput p c) = NeedInput (go . p) (go . c)
go (Done r) = rest r
go (PipeM mp) = PipeM (liftM go mp)
go (Leftover p l) = Leftover (go p) l
in go (c0 Done)
-- | Catch all exceptions thrown by the current component of the pipeline.
--
Note : this will /not/ catch exceptions thrown by other components ! For
example , if an exception is thrown in a @Source@ feeding to a @Sink@ , and
the @Sink@ uses @catchC@ , the exception will /not/ be caught .
--
-- Due to this behavior (as well as lack of async exception safety), you
-- should not try to implement combinators such as @onException@ in terms of this
-- primitive function.
--
Note also that the exception handling will /not/ be applied to any
-- finalizers generated by this conduit.
--
Since 1.0.11
catchC :: (MonadUnliftIO m, Exception e)
=> ConduitT i o m r
-> (e -> ConduitT i o m r)
-> ConduitT i o m r
catchC (ConduitT p0) onErr = ConduitT $ \rest -> let
go (Done r) = rest r
go (PipeM mp) = PipeM $ withRunInIO $ \ run ->
run (liftM go mp) `E.catch` \ e ->
return $ onErr e `unConduitT` rest
go (Leftover p i) = Leftover (go p) i
go (NeedInput x y) = NeedInput (go . x) (go . y)
go (HaveOutput p o) = HaveOutput (go p) o
in go (p0 Done)
# INLINE catchC #
| The same as catchC@.
--
Since 1.0.11
handleC :: (MonadUnliftIO m, Exception e)
=> (e -> ConduitT i o m r)
-> ConduitT i o m r
-> ConduitT i o m r
handleC = flip catchC
# INLINE handleC #
| A version of @try@ for use within a pipeline . See the comments in @catchC@
-- for more details.
--
Since 1.0.11
tryC :: (MonadUnliftIO m, Exception e)
=> ConduitT i o m r
-> ConduitT i o m (Either e r)
tryC c = fmap Right c `catchC` (return . Left)
# INLINE tryC #
| Combines two sinks . The new sink will complete when both input sinks have
-- completed.
--
-- Any leftovers are discarded.
--
Since 0.4.1
zipSinks :: Monad m => ConduitT i Void m r -> ConduitT i Void m r' -> ConduitT i Void m (r, r')
zipSinks (ConduitT x0) (ConduitT y0) = ConduitT $ \rest -> let
Leftover _ i >< _ = absurd i
_ >< Leftover _ i = absurd i
HaveOutput _ o >< _ = absurd o
_ >< HaveOutput _ o = absurd o
PipeM mx >< y = PipeM (liftM (>< y) mx)
x >< PipeM my = PipeM (liftM (x ><) my)
Done x >< Done y = rest (x, y)
NeedInput px cx >< NeedInput py cy = NeedInput (\i -> px i >< py i) (\() -> cx () >< cy ())
NeedInput px cx >< y@Done{} = NeedInput (\i -> px i >< y) (\u -> cx u >< y)
x@Done{} >< NeedInput py cy = NeedInput (\i -> x >< py i) (\u -> x >< cy u)
in injectLeftovers (x0 Done) >< injectLeftovers (y0 Done)
| Combines two sources . The new source will stop producing once either
-- source has been exhausted.
--
Since 1.0.13
zipSources :: Monad m => ConduitT () a m () -> ConduitT () b m () -> ConduitT () (a, b) m ()
zipSources (ConduitT left0) (ConduitT right0) = ConduitT $ \rest -> let
go (Leftover left ()) right = go left right
go left (Leftover right ()) = go left right
go (Done ()) (Done ()) = rest ()
go (Done ()) (HaveOutput _ _) = rest ()
go (HaveOutput _ _) (Done ()) = rest ()
go (Done ()) (PipeM _) = rest ()
go (PipeM _) (Done ()) = rest ()
go (PipeM mx) (PipeM my) = PipeM (liftM2 go mx my)
go (PipeM mx) y@HaveOutput{} = PipeM (liftM (\x -> go x y) mx)
go x@HaveOutput{} (PipeM my) = PipeM (liftM (go x) my)
go (HaveOutput srcx x) (HaveOutput srcy y) = HaveOutput (go srcx srcy) (x, y)
go (NeedInput _ c) right = go (c ()) right
go left (NeedInput _ c) = go left (c ())
in go (left0 Done) (right0 Done)
| Combines two sources . The new source will stop producing once either
-- source has been exhausted.
--
Since 1.0.13
zipSourcesApp :: Monad m => ConduitT () (a -> b) m () -> ConduitT () a m () -> ConduitT () b m ()
zipSourcesApp (ConduitT left0) (ConduitT right0) = ConduitT $ \rest -> let
go (Leftover left ()) right = go left right
go left (Leftover right ()) = go left right
go (Done ()) (Done ()) = rest ()
go (Done ()) (HaveOutput _ _) = rest ()
go (HaveOutput _ _) (Done ()) = rest ()
go (Done ()) (PipeM _) = rest ()
go (PipeM _) (Done ()) = rest ()
go (PipeM mx) (PipeM my) = PipeM (liftM2 go mx my)
go (PipeM mx) y@HaveOutput{} = PipeM (liftM (\x -> go x y) mx)
go x@HaveOutput{} (PipeM my) = PipeM (liftM (go x) my)
go (HaveOutput srcx x) (HaveOutput srcy y) = HaveOutput (go srcx srcy) (x y)
go (NeedInput _ c) right = go (c ()) right
go left (NeedInput _ c) = go left (c ())
in go (left0 Done) (right0 Done)
-- |
--
-- Since 1.0.17
zipConduitApp
:: Monad m
=> ConduitT i o m (x -> y)
-> ConduitT i o m x
-> ConduitT i o m y
zipConduitApp (ConduitT left0) (ConduitT right0) = ConduitT $ \rest -> let
go (Done f) (Done x) = rest (f x)
go (PipeM mx) y = PipeM (flip go y `liftM` mx)
go x (PipeM my) = PipeM (go x `liftM` my)
go (HaveOutput x o) y = HaveOutput (go x y) o
go x (HaveOutput y o) = HaveOutput (go x y) o
go (Leftover _ i) _ = absurd i
go _ (Leftover _ i) = absurd i
go (NeedInput px cx) (NeedInput py cy) = NeedInput
(\i -> go (px i) (py i))
(\u -> go (cx u) (cy u))
go (NeedInput px cx) (Done y) = NeedInput
(\i -> go (px i) (Done y))
(\u -> go (cx u) (Done y))
go (Done x) (NeedInput py cy) = NeedInput
(\i -> go (Done x) (py i))
(\u -> go (Done x) (cy u))
in go (injectLeftovers $ left0 Done) (injectLeftovers $ right0 Done)
-- | Same as normal fusion (e.g. @=$=@), except instead of discarding leftovers
-- from the downstream component, return them.
--
-- Since 1.0.17
fuseReturnLeftovers :: Monad m
=> ConduitT a b m ()
-> ConduitT b c m r
-> ConduitT a c m (r, [b])
fuseReturnLeftovers (ConduitT left0) (ConduitT right0) = ConduitT $ \rest -> let
goRight bs left right =
case right of
HaveOutput p o -> HaveOutput (recurse p) o
NeedInput rp rc ->
case bs of
[] -> goLeft rp rc left
b:bs' -> goRight bs' left (rp b)
Done r2 -> rest (r2, bs)
PipeM mp -> PipeM (liftM recurse mp)
Leftover p b -> goRight (b:bs) left p
where
recurse = goRight bs left
goLeft rp rc left =
case left of
HaveOutput left' o -> goRight [] left' (rp o)
NeedInput left' lc -> NeedInput (recurse . left') (recurse . lc)
Done r1 -> goRight [] (Done r1) (rc r1)
PipeM mp -> PipeM (liftM recurse mp)
Leftover left' i -> Leftover (recurse left') i
where
recurse = goLeft rp rc
in goRight [] (left0 Done) (right0 Done)
-- | Similar to @fuseReturnLeftovers@, but use the provided function to convert
-- downstream leftovers to upstream leftovers.
--
-- Since 1.0.17
fuseLeftovers
:: Monad m
=> ([b] -> [a])
-> ConduitT a b m ()
-> ConduitT b c m r
-> ConduitT a c m r
fuseLeftovers f left right = do
(r, bs) <- fuseReturnLeftovers left right
mapM_ leftover $ reverse $ f bs
return r
| Connect a ' Conduit ' to a sink and return the output of the sink
together with a new ' Conduit ' .
--
-- Since 1.0.17
connectResumeConduit
:: Monad m
=> SealedConduitT i o m ()
-> ConduitT o Void m r
-> ConduitT i Void m (SealedConduitT i o m (), r)
connectResumeConduit (SealedConduitT left0) (ConduitT right0) = ConduitT $ \rest -> let
goRight left right =
case right of
HaveOutput _ o -> absurd o
NeedInput rp rc -> goLeft rp rc left
Done r2 -> rest (SealedConduitT left, r2)
PipeM mp -> PipeM (liftM (goRight left) mp)
Leftover p i -> goRight (HaveOutput left i) p
goLeft rp rc left =
case left of
HaveOutput left' o -> goRight left' (rp o)
NeedInput left' lc -> NeedInput (recurse . left') (recurse . lc)
Done () -> goRight (Done ()) (rc ())
PipeM mp -> PipeM (liftM recurse mp)
Leftover left' i -> Leftover (recurse left') i -- recurse p
where
recurse = goLeft rp rc
in goRight left0 (right0 Done)
-- | Merge a @Source@ into a @Conduit@.
-- The new conduit will stop processing once either source or upstream have been exhausted.
mergeSource
:: Monad m
=> ConduitT () i m ()
-> ConduitT a (i, a) m ()
mergeSource = loop . sealConduitT
where
loop :: Monad m => SealedConduitT () i m () -> ConduitT a (i, a) m ()
loop src0 = await >>= maybe (return ()) go
where
go a = do
(src1, mi) <- lift $ src0 $$++ await
case mi of
Nothing -> return ()
Just i -> yield (i, a) >> loop src1
| Turn a @Sink@ into a @Conduit@ in the following way :
--
* All input passed to the @Sink@ is yielded downstream .
--
* When the @Sink@ finishes processing , the result is passed to the provided to the finalizer function .
--
Note that the @Sink@ will stop receiving input as soon as the downstream it
-- is connected to shuts down.
--
An example usage would be to write the result of a @Sink@ to some mutable
-- variable while allowing other processing to continue.
--
-- Since 1.1.0
passthroughSink :: Monad m
=> ConduitT i Void m r
-> (r -> m ()) -- ^ finalizer
-> ConduitT i i m ()
passthroughSink (ConduitT sink0) final = ConduitT $ \rest -> let
-- A bit of explanation is in order, this function is
-- non-obvious. The purpose of go is to keep track of the sink
-- we're passing values to, and then yield values downstream. The
third argument to go is the current state of that sink . That 's
-- relatively straightforward.
--
The second value is the leftover buffer . These are values that
-- the sink itself has called leftover on, and must be provided
-- back to the sink the next time it awaits. _However_, these
-- values should _not_ be reyielded downstream: we have already
-- yielded them downstream ourself, and it is the responsibility
-- of the functions wrapping around passthroughSink to handle the
-- leftovers from downstream.
--
The trickiest bit is the first argument , which is a solution to
bug . The issue
-- is that, once we get a value, we need to provide it to both the
-- inner sink _and_ yield it downstream. The obvious thing to do
is yield first and then recursively call go . Unfortunately ,
-- this doesn't work in all cases: if the downstream component
-- never calls await again, our yield call will never return, and
-- our sink will not get the last value. This results is confusing
-- behavior where the sink and downstream component receive a
-- different number of values.
--
-- Solution: keep a buffer of the next value to yield downstream,
and only yield it downstream in one of two cases : our sink is
-- asking for another value, or our sink is done. This way, we
-- ensure that, in all cases, we pass exactly the same number of
-- values to the inner sink as to downstream.
go mbuf _ (Done r) = do
maybe (return ()) CI.yield mbuf
lift $ final r
unConduitT (awaitForever yield) rest
go mbuf is (Leftover sink i) = go mbuf (i:is) sink
go _ _ (HaveOutput _ o) = absurd o
go mbuf is (PipeM mx) = do
x <- lift mx
go mbuf is x
go mbuf (i:is) (NeedInput next _) = go mbuf is (next i)
go mbuf [] (NeedInput next done) = do
maybe (return ()) CI.yield mbuf
mx <- CI.await
case mx of
Nothing -> go Nothing [] (done ())
Just x -> go (Just x) [] (next x)
in go Nothing [] (sink0 Done)
-- | Convert a @Source@ into a list. The basic functionality can be explained as:
--
> sourceToList src = src $ $ Data.Conduit.List.consume
--
However , @sourceToList@ is able to produce its results lazily , which can not
-- be done when running a conduit pipeline in general. Unlike the
@Data . Conduit . Lazy@ module ( in conduit - extra ) , this function performs no
unsafe I\/O operations , and therefore can only be as lazy as the
-- underlying monad.
--
-- Since 1.2.6
sourceToList :: Monad m => ConduitT () a m () -> m [a]
sourceToList (ConduitT k) =
go $ k Done
where
go (Done _) = return []
go (HaveOutput src x) = liftM (x:) (go src)
go (PipeM msrc) = msrc >>= go
go (NeedInput _ c) = go (c ())
go (Leftover p _) = go p
-- Define fixity of all our operators
infixr 0 $$
infixl 1 $=
infixr 2 =$
infixr 2 =$=
infixr 0 $$+
infixr 0 $$++
infixr 0 $$+-
infixl 1 $=+
infixr 2 .|
| Equivalent to using ' runConduit ' and ' .| ' together .
--
Since 1.2.3
connect :: Monad m
=> ConduitT () a m ()
-> ConduitT a Void m r
-> m r
connect = ($$)
-- | Split a conduit into head and tail.
--
Note that you have to ' sealConduitT ' it first .
--
-- Since 1.3.3
unconsM :: Monad m
=> SealedConduitT () o m ()
-> m (Maybe (o, SealedConduitT () o m ()))
unconsM (SealedConduitT p) = go p
where
-- This function is the same as @Pipe.unconsM@ but it ignores leftovers.
go (HaveOutput p o) = pure $ Just (o, SealedConduitT p)
go (NeedInput _ c) = go $ c ()
go (Done ()) = pure Nothing
go (PipeM mp) = mp >>= go
go (Leftover p ()) = go p
-- | Split a conduit into head and tail or return its result if it is done.
--
Note that you have to ' sealConduitT ' it first .
--
-- Since 1.3.3
unconsEitherM :: Monad m
=> SealedConduitT () o m r
-> m (Either r (o, SealedConduitT () o m r))
unconsEitherM (SealedConduitT p) = go p
where
This function is the same as @Pipe.unconsEitherM@ but it ignores leftovers .
go (HaveOutput p o) = pure $ Right (o, SealedConduitT p)
go (NeedInput _ c) = go $ c ()
go (Done r) = pure $ Left r
go (PipeM mp) = mp >>= go
go (Leftover p ()) = go p
-- | Named function synonym for '.|'
--
-- Equivalent to '.|' and '=$='. However, the latter is
-- deprecated and will be removed in a future version.
--
Since 1.2.3
fuse :: Monad m => ConduitT a b m () -> ConduitT b c m r -> ConduitT a c m r
fuse = (=$=)
| Combine two @Conduit@s together into a new @Conduit@ ( aka ' fuse ' ) .
--
-- Output from the upstream (left) conduit will be fed into the
-- downstream (right) conduit. Processing will terminate when
-- downstream (right) returns.
-- Leftover data returned from the right @Conduit@ will be discarded.
--
-- Equivalent to 'fuse' and '=$=', however the latter is deprecated and will
-- be removed in a future version.
--
-- Note that, while this operator looks like categorical composition
-- (from "Control.Category"), there are a few reasons it's different:
--
-- * The position of the type parameters to 'ConduitT' do not
match . We would need to change @ConduitT i o m r@ to @ConduitT r
-- m i o@, which would preclude a 'Monad' or 'MonadTrans' instance.
--
-- * The result value from upstream and downstream are allowed to
-- differ between upstream and downstream. In other words, we would
-- need the type signature here to look like @ConduitT a b m r ->
-- ConduitT b c m r -> ConduitT a c m r@.
--
* Due to leftovers , we do not have a left identity in Conduit . This
-- can be achieved with the underlying @Pipe@ datatype, but this is
not generally recommended . See < > .
--
@since 1.2.8
(.|) :: Monad m
=> ConduitT a b m () -- ^ upstream
-> ConduitT b c m r -- ^ downstream
-> ConduitT a c m r
(.|) = fuse
# INLINE ( .| ) #
-- | The connect operator, which pulls data from a source and pushes to a sink.
-- If you would like to keep the @Source@ open to be used for other
operations , use the connect - and - resume operator ' $ $ + ' .
--
Since 0.4.0
($$) :: Monad m => Source m a -> Sink a m b -> m b
src $$ sink = do
(rsrc, res) <- src $$+ sink
rsrc $$+- return ()
return res
# INLINE [ 1 ] ( $ $ ) #
{-# DEPRECATED ($$) "Use runConduit and .|" #-}
-- | A synonym for '=$=' for backwards compatibility.
--
Since 0.4.0
($=) :: Monad m => Conduit a m b -> ConduitT b c m r -> ConduitT a c m r
($=) = (=$=)
{-# INLINE [0] ($=) #-}
{-# RULES "conduit: $= is =$=" ($=) = (=$=) #-}
{-# DEPRECATED ($=) "Use .|" #-}
-- | A synonym for '=$=' for backwards compatibility.
--
Since 0.4.0
(=$) :: Monad m => Conduit a m b -> ConduitT b c m r -> ConduitT a c m r
(=$) = (=$=)
{-# INLINE [0] (=$) #-}
{-# RULES "conduit: =$ is =$=" (=$) = (=$=) #-}
{-# DEPRECATED (=$) "Use .|" #-}
-- | Deprecated fusion operator.
--
Since 0.4.0
(=$=) :: Monad m => Conduit a m b -> ConduitT b c m r -> ConduitT a c m r
ConduitT left0 =$= ConduitT right0 = ConduitT $ \rest ->
let goRight left right =
case right of
HaveOutput p o -> HaveOutput (recurse p) o
NeedInput rp rc -> goLeft rp rc left
Done r2 -> rest r2
PipeM mp -> PipeM (liftM recurse mp)
Leftover right' i -> goRight (HaveOutput left i) right'
where
recurse = goRight left
goLeft rp rc left =
case left of
HaveOutput left' o -> goRight left' (rp o)
NeedInput left' lc -> NeedInput (recurse . left') (recurse . lc)
Done r1 -> goRight (Done r1) (rc r1)
PipeM mp -> PipeM (liftM recurse mp)
Leftover left' i -> Leftover (recurse left') i
where
recurse = goLeft rp rc
in goRight (left0 Done) (right0 Done)
# INLINE [ 1 ] (= $ =) #
{-# DEPRECATED (=$=) "Use .|" #-}
-- | Wait for a single input value from upstream. If no data is available,
returns @Nothing@. Once @await@ returns @Nothing@ , subsequent calls will
also return @Nothing@.
--
Since 0.5.0
await :: Monad m => ConduitT i o m (Maybe i)
await = ConduitT $ \f -> NeedInput (f . Just) (const $ f Nothing)
{-# INLINE [0] await #-}
await' :: Monad m
=> ConduitT i o m r
-> (i -> ConduitT i o m r)
-> ConduitT i o m r
await' f g = ConduitT $ \rest -> NeedInput
(\i -> unConduitT (g i) rest)
(const $ unConduitT f rest)
{-# INLINE await' #-}
{-# RULES "conduit: await >>= maybe" forall x y. await >>= maybe x y = await' x y #-}
-- | Send a value downstream to the next component to consume. If the
-- downstream component terminates, this call will never return control.
--
Since 0.5.0
yield :: Monad m
=> o -- ^ output value
-> ConduitT i o m ()
yield o = ConduitT $ \rest -> HaveOutput (rest ()) o
{-# INLINE yield #-}
-- | Send a monadic value downstream for the next component to consume.
--
-- @since 1.2.7
yieldM :: Monad m => m o -> ConduitT i o m ()
yieldM mo = lift mo >>= yield
# INLINE yieldM #
FIXME rule wo n't fire , see FIXME in .Pipe ; " mapM _ yield " mapM _ yield = ConduitT . sourceList
-- | Provide a single piece of leftover input to be consumed by the next
-- component in the current monadic binding.
--
-- /Note/: it is highly encouraged to only return leftover values from input
-- already consumed from upstream.
--
-- @since 0.5.0
leftover :: i -> ConduitT i o m ()
leftover i = ConduitT $ \rest -> Leftover (rest ()) i
# INLINE leftover #
-- | Run a pipeline until processing completes.
--
Since 1.2.1
runConduit :: Monad m => ConduitT () Void m r -> m r
runConduit (ConduitT p) = runPipe $ injectLeftovers $ p Done
{-# INLINE [0] runConduit #-}
-- | Bracket a conduit computation between allocation and release of a
resource . Two guarantees are given about resource finalization :
--
1 . It will be /prompt/. The finalization will be run as early as possible .
--
2 . It is exception safe . Due to usage of @resourcet@ , the finalization will
-- be run in the event of any exceptions.
--
Since 0.5.0
bracketP :: MonadResource m
=> IO a
^ computation to run first ( \"acquire resource\ " )
-> (a -> IO ())
-- ^ computation to run last (\"release resource\")
-> (a -> ConduitT i o m r)
-- ^ computation to run in-between
-> ConduitT i o m r
-- returns the value from the in-between computation
bracketP alloc free inside = ConduitT $ \rest -> do
(key, seed) <- allocate alloc free
unConduitT (inside seed) $ \res -> do
release key
rest res
-- | Wait for input forever, calling the given inner component for each piece of
-- new input.
--
-- This function is provided as a convenience for the common pattern of
-- @await@ing input, checking if it's @Just@ and then looping.
--
Since 0.5.0
awaitForever :: Monad m => (i -> ConduitT i o m r) -> ConduitT i o m ()
awaitForever f = ConduitT $ \rest ->
let go = NeedInput (\i -> unConduitT (f i) (const go)) rest
in go
-- | Transform the monad that a @ConduitT@ lives in.
--
-- Note that the monad transforming function will be run multiple times,
-- resulting in unintuitive behavior in some cases. For a fuller treatment,
-- please see:
--
-- <-with-monad-transformers>
--
Since 0.4.0
transPipe :: Monad m => (forall a. m a -> n a) -> ConduitT i o m r -> ConduitT i o n r
transPipe f (ConduitT c0) = ConduitT $ \rest -> let
go (HaveOutput p o) = HaveOutput (go p) o
go (NeedInput p c) = NeedInput (go . p) (go . c)
go (Done r) = rest r
go (PipeM mp) =
PipeM (f $ liftM go $ collapse mp)
where
Combine a series of monadic actions into a single action . Since we
-- throw away side effects between different actions, an arbitrary break
-- between actions will lead to a violation of the monad transformer laws.
-- Example available at:
--
--
collapse mpipe = do
pipe' <- mpipe
case pipe' of
PipeM mpipe' -> collapse mpipe'
_ -> return pipe'
go (Leftover p i) = Leftover (go p) i
in go (c0 Done)
-- | Apply a function to all the output values of a @ConduitT@.
--
This mimics the behavior of ` fmap ` for a ` Source ` and ` Conduit ` in pre-0.4
-- days. It can also be simulated by fusing with the @map@ conduit from
" Data . Conduit . List " .
--
Since 0.4.1
mapOutput :: Monad m => (o1 -> o2) -> ConduitT i o1 m r -> ConduitT i o2 m r
mapOutput f (ConduitT c0) = ConduitT $ \rest -> let
go (HaveOutput p o) = HaveOutput (go p) (f o)
go (NeedInput p c) = NeedInput (go . p) (go . c)
go (Done r) = rest r
go (PipeM mp) = PipeM (liftM (go) mp)
go (Leftover p i) = Leftover (go p) i
in go (c0 Done)
| Same as , but use a function that returns @Maybe@ values .
--
Since 0.5.0
mapOutputMaybe :: Monad m => (o1 -> Maybe o2) -> ConduitT i o1 m r -> ConduitT i o2 m r
mapOutputMaybe f (ConduitT c0) = ConduitT $ \rest -> let
go (HaveOutput p o) = maybe id (\o' p' -> HaveOutput p' o') (f o) (go p)
go (NeedInput p c) = NeedInput (go . p) (go . c)
go (Done r) = rest r
go (PipeM mp) = PipeM (liftM (go) mp)
go (Leftover p i) = Leftover (go p) i
in go (c0 Done)
-- | Apply a function to all the input values of a @ConduitT@.
--
Since 0.5.0
mapInput :: Monad m
=> (i1 -> i2) -- ^ map initial input to new input
-> (i2 -> Maybe i1) -- ^ map new leftovers to initial leftovers
-> ConduitT i2 o m r
-> ConduitT i1 o m r
mapInput f f' (ConduitT c0) = ConduitT $ \rest -> let
go (HaveOutput p o) = HaveOutput (go p) o
go (NeedInput p c) = NeedInput (go . p . f) (go . c)
go (Done r) = rest r
go (PipeM mp) = PipeM $ liftM go mp
go (Leftover p i) = maybe id (flip Leftover) (f' i) (go p)
in go (c0 Done)
-- | Apply a monadic action to all the input values of a @ConduitT@.
--
Since 1.3.2
mapInputM :: Monad m
=> (i1 -> m i2) -- ^ map initial input to new input
-> (i2 -> m (Maybe i1)) -- ^ map new leftovers to initial leftovers
-> ConduitT i2 o m r
-> ConduitT i1 o m r
mapInputM f f' (ConduitT c0) = ConduitT $ \rest -> let
go (HaveOutput p o) = HaveOutput (go p) o
go (NeedInput p c) = NeedInput (\i -> PipeM $ go . p <$> f i) (go . c)
go (Done r) = rest r
go (PipeM mp) = PipeM $ fmap go mp
go (Leftover p i) = PipeM $ (\x -> maybe id (flip Leftover) x (go p)) <$> f' i
in go (c0 Done)
-- | The connect-and-resume operator. This does not close the @Source@, but
-- instead returns it to be used again. This allows a @Source@ to be used
-- incrementally in a large program, without forcing the entire program to live
in the @Sink@ monad .
--
-- Mnemonic: connect + do more.
--
Since 0.5.0
($$+) :: Monad m => ConduitT () a m () -> ConduitT a Void m b -> m (SealedConduitT () a m (), b)
src $$+ sink = connectResume (sealConduitT src) sink
# INLINE ( $ $ + ) #
-- | Continue processing after usage of @$$+@.
--
Since 0.5.0
($$++) :: Monad m => SealedConduitT () a m () -> ConduitT a Void m b -> m (SealedConduitT () a m (), b)
($$++) = connectResume
# INLINE ( $ $ + + ) #
-- | Same as @$$++@ and @connectResume@, but doesn't include the
updated
--
-- /NOTE/ In previous versions, this would cause finalizers to
-- run. Since version 1.3.0, there are no finalizers in conduit.
--
Since 0.5.0
($$+-) :: Monad m => SealedConduitT () a m () -> ConduitT a Void m b -> m b
rsrc $$+- sink = do
(_, res) <- connectResume rsrc sink
return res
# INLINE ( $ $ + - ) #
-- | Left fusion for a sealed source.
--
Since 1.0.16
($=+) :: Monad m => SealedConduitT () a m () -> ConduitT a b m () -> SealedConduitT () b m ()
SealedConduitT src $=+ ConduitT sink = SealedConduitT (src `pipeL` sink Done)
-- | Provide for a stream of data that can be flushed.
--
A number of @Conduit@s ( e.g. , ) need the ability to flush
-- the stream at some point. This provides a single wrapper datatype to be used
-- in all such circumstances.
--
Since 0.3.0
data Flush a = Chunk a | Flush
deriving (Show, Eq, Ord)
instance Functor Flush where
fmap _ Flush = Flush
fmap f (Chunk a) = Chunk (f a)
-- | A wrapper for defining an 'Applicative' instance for 'Source's which allows
to combine sources together , generalizing ' ' . A combined source
-- will take input yielded from each of its @Source@s until any of them stop
-- producing output.
--
Since 1.0.13
newtype ZipSource m o = ZipSource { getZipSource :: ConduitT () o m () }
instance Monad m => Functor (ZipSource m) where
fmap f = ZipSource . mapOutput f . getZipSource
instance Monad m => Applicative (ZipSource m) where
pure = ZipSource . forever . yield
(ZipSource f) <*> (ZipSource x) = ZipSource $ zipSourcesApp f x
| Coalesce all values yielded by all of the @Source@s .
--
-- Implemented on top of @ZipSource@ and as such, it exhibits the same
-- short-circuiting behavior as @ZipSource@. See that data type for more
-- details. If you want to create a source that yields *all* values from
-- multiple sources, use `sequence_`.
--
Since 1.0.13
sequenceSources :: (Traversable f, Monad m) => f (ConduitT () o m ()) -> ConduitT () (f o) m ()
sequenceSources = getZipSource . sequenceA . fmap ZipSource
-- | A wrapper for defining an 'Applicative' instance for 'Sink's which allows
to combine sinks together , generalizing ' ' . A combined sink
-- distributes the input to all its participants and when all finish, produces
-- the result. This allows to define functions like
--
-- @
-- sequenceSinks :: (Monad m)
-- => [ConduitT i Void m r] -> ConduitT i Void m [r]
sequenceSinks = getZipSink . sequenceA . fmap ZipSink
-- @
--
-- Note that the standard 'Applicative' instance for conduits works
differently . It feeds one sink with input until it finishes , then switches
-- to another, etc., and at the end combines their results.
--
This newtype is in fact a type constrained version of ' ZipConduit ' , and has
the same behavior . It 's presented as a separate type since ( 1 ) it
historically predates @ZipConduit@ , and ( 2 ) the type constraining can make
-- your code clearer (and thereby make your error messages more easily
-- understood).
--
Since 1.0.13
newtype ZipSink i m r = ZipSink { getZipSink :: ConduitT i Void m r }
instance Monad m => Functor (ZipSink i m) where
fmap f (ZipSink x) = ZipSink (liftM f x)
instance Monad m => Applicative (ZipSink i m) where
pure = ZipSink . return
(ZipSink f) <*> (ZipSink x) =
ZipSink $ liftM (uncurry ($)) $ zipSinks f x
| Send incoming values to all of the @Sink@ providing , and ultimately
-- coalesce together all return values.
--
-- Implemented on top of @ZipSink@, see that data type for more details.
--
Since 1.0.13
sequenceSinks :: (Traversable f, Monad m) => f (ConduitT i Void m r) -> ConduitT i Void m (f r)
sequenceSinks = getZipSink . sequenceA . fmap ZipSink
-- | The connect-and-resume operator. This does not close the @Conduit@, but
-- instead returns it to be used again. This allows a @Conduit@ to be used
-- incrementally in a large program, without forcing the entire program to live
in the @Sink@ monad .
--
Leftover data returned from the @Sink@ will be discarded .
--
-- Mnemonic: connect + do more.
--
-- Since 1.0.17
(=$$+) :: Monad m
=> ConduitT a b m ()
-> ConduitT b Void m r
-> ConduitT a Void m (SealedConduitT a b m (), r)
(=$$+) conduit = connectResumeConduit (sealConduitT conduit)
# INLINE (= $ $ + ) #
| Continue processing after usage of ' = $ $ + ' . Connect a ' SealedConduitT ' to
-- a sink and return the output of the sink together with a new
' SealedConduitT ' .
--
-- Since 1.0.17
(=$$++) :: Monad m => SealedConduitT i o m () -> ConduitT o Void m r -> ConduitT i Void m (SealedConduitT i o m (), r)
(=$$++) = connectResumeConduit
# INLINE (= $ $ + + ) #
| Same as @=$$++@ , but does n't include the updated
--
-- /NOTE/ In previous versions, this would cause finalizers to
-- run. Since version 1.3.0, there are no finalizers in conduit.
--
-- Since 1.0.17
(=$$+-) :: Monad m => SealedConduitT i o m () -> ConduitT o Void m r -> ConduitT i Void m r
rsrc =$$+- sink = do
(_, res) <- connectResumeConduit rsrc sink
return res
# INLINE (= $ $ + - ) #
infixr 0 =$$+
infixr 0 =$$++
infixr 0 =$$+-
| Provides an alternative @Applicative@ instance for @ConduitT@. In this instance ,
-- every incoming value is provided to all @ConduitT@s, and output is coalesced together.
Leftovers from individual @ConduitT@s will be used within that component , and then discarded
-- at the end of their computation. Output and finalizers will both be handled in a left-biased manner.
--
-- As an example, take the following program:
--
-- @
-- main :: IO ()
-- main = do
let src = mapM _ yield [ 1 .. 3 : : Int ]
= CL.map ( +1 )
= CL.concatMap ( replicate 2 )
conduit = getZipConduit $ < *
-- sink = CL.mapM_ print
-- src $$ conduit =$ sink
-- @
--
It will produce the output : 2 , 1 , 1 , 3 , 2 , 2 , 4 , 3 , 3
--
-- Since 1.0.17
newtype ZipConduit i o m r = ZipConduit { getZipConduit :: ConduitT i o m r }
deriving Functor
instance Monad m => Applicative (ZipConduit i o m) where
pure = ZipConduit . pure
ZipConduit left <*> ZipConduit right = ZipConduit (zipConduitApp left right)
-- | Provide identical input to all of the @Conduit@s and combine their outputs
-- into a single stream.
--
Implemented on top of @ZipConduit@ , see that data type for more details .
--
-- Since 1.0.17
sequenceConduits :: (Traversable f, Monad m) => f (ConduitT i o m r) -> ConduitT i o m (f r)
sequenceConduits = getZipConduit . sequenceA . fmap ZipConduit
| Fuse two @ConduitT@s together , and provide the return value of both . Note
-- that this will force the entire upstream @ConduitT@ to be run to produce the
-- result value, even if the downstream terminates early.
--
Since 1.1.5
fuseBoth :: Monad m => ConduitT a b m r1 -> ConduitT b c m r2 -> ConduitT a c m (r1, r2)
fuseBoth (ConduitT up) (ConduitT down) =
ConduitT (pipeL (up Done) (withUpstream $ generalizeUpstream $ down Done) >>=)
# INLINE fuseBoth #
-- | Like 'fuseBoth', but does not force consumption of the @Producer@.
-- In the case that the @Producer@ terminates, the result value is
-- provided as a @Just@ value. If it does not terminate, then a
-- @Nothing@ value is returned.
--
One thing to note here is that " termination " here only occurs if the
-- @Producer@ actually yields a @Nothing@ value. For example, with the
@Producer@ @mapM _ yield [ 1 .. 5]@ , if five values are requested , the
-- @Producer@ has not yet terminated. Termination only occurs when the
sixth value is awaited for and the @Producer@ signals termination .
--
Since 1.2.4
fuseBothMaybe
:: Monad m
=> ConduitT a b m r1
-> ConduitT b c m r2
-> ConduitT a c m (Maybe r1, r2)
fuseBothMaybe (ConduitT up) (ConduitT down) =
ConduitT (pipeL (up Done) (go Nothing $ down Done) >>=)
where
go mup (Done r) = Done (mup, r)
go mup (PipeM mp) = PipeM $ liftM (go mup) mp
go mup (HaveOutput p o) = HaveOutput (go mup p) o
go _ (NeedInput p c) = NeedInput
(\i -> go Nothing (p i))
(\u -> go (Just u) (c ()))
go mup (Leftover p i) = Leftover (go mup p) i
{-# INLINABLE fuseBothMaybe #-}
-- | Same as @fuseBoth@, but ignore the return value from the downstream
-- @Conduit@. Same caveats of forced consumption apply.
--
Since 1.1.5
fuseUpstream :: Monad m => ConduitT a b m r -> ConduitT b c m () -> ConduitT a c m r
fuseUpstream up down = fmap fst (fuseBoth up down)
# INLINE fuseUpstream #
-- Rewrite rules
FIXME
{ - # RULES " conduit : ConduitT : lift x > > = f " forall > > = f = ConduitT ( PipeM ( liftM ( unConduitT . f ) m ) ) #
{-# RULES "conduit: ConduitT: lift x >>= f" forall m f. lift m >>= f = ConduitT (PipeM (liftM (unConduitT . f) m)) #-}
# RULES " conduit : ConduitT : lift x > > f " forall > > f = ConduitT ( PipeM ( liftM ( \ _ - > unConduitT f ) m ) ) #
{-# RULES "conduit: ConduitT: liftIO x >>= f" forall m (f :: MonadIO m => a -> ConduitT i o m r). liftIO m >>= f = ConduitT (PipeM (liftM (unConduitT . f) (liftIO m))) #-}
{-# RULES "conduit: ConduitT: liftIO x >> f" forall m (f :: MonadIO m => ConduitT i o m r). liftIO m >> f = ConduitT (PipeM (liftM (\_ -> unConduitT f) (liftIO m))) #-}
# RULES " conduit : ConduitT : liftBase x > > = f " forall m ( f : : MonadBase b m = > a - > ConduitT i o m r ) . liftBase m > > = f = ConduitT ( PipeM ( liftM ( unConduitT . f ) ( liftBase m ) ) ) #
# RULES " conduit : ConduitT : liftBase x > > f " forall m ( f : : MonadBase b m = > ConduitT i o m r ) . liftBase m > > f = ConduitT ( PipeM ( liftM ( \ _ - > unConduitT f ) ( liftBase m ) ) ) #
# RULES
" yield o > > p " forall o ( p : : ConduitT i o m r ) . yield o > > p = ConduitT ( HaveOutput ( unConduitT p ) o )
; " when yield next " forall b o p. when b ( yield o ) > > p =
if b then ConduitT ( HaveOutput ( unConduitT p ) o ) else ; " unless yield next " forall b o p. unless b ( yield o ) > > p =
if b then p else ConduitT ( HaveOutput ( unConduitT p ) o )
; " lift m > > = yield " forall m. lift m > > = yield = yieldM m
#
"yield o >> p" forall o (p :: ConduitT i o m r). yield o >> p = ConduitT (HaveOutput (unConduitT p) o)
; "when yield next" forall b o p. when b (yield o) >> p =
if b then ConduitT (HaveOutput (unConduitT p) o) else p
; "unless yield next" forall b o p. unless b (yield o) >> p =
if b then p else ConduitT (HaveOutput (unConduitT p) o)
; "lift m >>= yield" forall m. lift m >>= yield = yieldM m
#-}
{-# RULES "conduit: leftover l >> p" forall l (p :: ConduitT i o m r). leftover l >> p =
ConduitT (Leftover (unConduitT p) l) #-}
-}
-- | Run a pure pipeline until processing completes, i.e. a pipeline
with @Identity@ as the base monad . This is equivalient to
-- @runIdentity . runConduit@.
--
@since 1.2.8
runConduitPure :: ConduitT () Void Identity r -> r
runConduitPure = runIdentity . runConduit
{-# INLINE runConduitPure #-}
-- | Run a pipeline which acquires resources with @ResourceT@, and
-- then run the @ResourceT@ transformer. This is equivalent to
-- @runResourceT . runConduit@.
--
@since 1.2.8
runConduitRes :: MonadUnliftIO m
=> ConduitT () Void (ResourceT m) r
-> m r
runConduitRes = runResourceT . runConduit
# INLINE runConduitRes #
| null | https://raw.githubusercontent.com/snoyberg/conduit/28fac5e999f201b8fe99b941932725e4201a3774/conduit/src/Data/Conduit/Internal/Conduit.hs | haskell | # LANGUAGE RankNTypes #
** Types
** Sealed
** Primitives
** Composition
** Generalizing
** Cleanup
** Exceptions
** Utilities
| Core datatype of the conduit package. This type represents a general
type.
Since 1.3.0
| In order to provide for efficient monadic composition, the
@ConduitT@ type is implemented internally using a technique known
as the codensity transform. This allows for cheap appending, but
and that capturing the new state.
This data type is the same as @ConduitT@, but does not use the
codensity transform technique.
@since 1.3.0
| Same as 'ConduitT', for backwards compat
# INLINE (<*>) #
# INLINE (*>) #
| @since 1.3.1
# INLINE (<>) #
| Provides a stream of output values, without consuming any input or
producing a final result.
# DEPRECATED Source "Use ConduitT directly" #
| A component which produces a stream of output values, regardless of the
input stream. A @Producer@ is a generalization of a @Source@, and can be
used as either a @Source@ or a @Conduit@.
Since 1.0.0
# DEPRECATED Producer "Use ConduitT directly" #
| Consumes a stream of input values and produces a final result, without
producing any output.
> type Sink i m r = ConduitT i Void m r
# DEPRECATED Sink "Use ConduitT directly" #
| A component which consumes a stream of input values and produces a final
result, regardless of the output stream. A @Consumer@ is a generalization of
Since 1.0.0
# DEPRECATED Consumer "Use ConduitT directly" #
| Consumes a stream of input values and produces a stream of output values,
without producing a final result.
# DEPRECATED Conduit "Use ConduitT directly" #
Since 1.0.0
Since 1.0.0
| Catch all exceptions thrown by the current component of the pipeline.
Due to this behavior (as well as lack of async exception safety), you
should not try to implement combinators such as @onException@ in terms of this
primitive function.
finalizers generated by this conduit.
for more details.
completed.
Any leftovers are discarded.
source has been exhausted.
source has been exhausted.
|
Since 1.0.17
| Same as normal fusion (e.g. @=$=@), except instead of discarding leftovers
from the downstream component, return them.
Since 1.0.17
| Similar to @fuseReturnLeftovers@, but use the provided function to convert
downstream leftovers to upstream leftovers.
Since 1.0.17
Since 1.0.17
recurse p
| Merge a @Source@ into a @Conduit@.
The new conduit will stop processing once either source or upstream have been exhausted.
is connected to shuts down.
variable while allowing other processing to continue.
Since 1.1.0
^ finalizer
A bit of explanation is in order, this function is
non-obvious. The purpose of go is to keep track of the sink
we're passing values to, and then yield values downstream. The
relatively straightforward.
the sink itself has called leftover on, and must be provided
back to the sink the next time it awaits. _However_, these
values should _not_ be reyielded downstream: we have already
yielded them downstream ourself, and it is the responsibility
of the functions wrapping around passthroughSink to handle the
leftovers from downstream.
is that, once we get a value, we need to provide it to both the
inner sink _and_ yield it downstream. The obvious thing to do
this doesn't work in all cases: if the downstream component
never calls await again, our yield call will never return, and
our sink will not get the last value. This results is confusing
behavior where the sink and downstream component receive a
different number of values.
Solution: keep a buffer of the next value to yield downstream,
asking for another value, or our sink is done. This way, we
ensure that, in all cases, we pass exactly the same number of
values to the inner sink as to downstream.
| Convert a @Source@ into a list. The basic functionality can be explained as:
be done when running a conduit pipeline in general. Unlike the
underlying monad.
Since 1.2.6
Define fixity of all our operators
| Split a conduit into head and tail.
Since 1.3.3
This function is the same as @Pipe.unconsM@ but it ignores leftovers.
| Split a conduit into head and tail or return its result if it is done.
Since 1.3.3
| Named function synonym for '.|'
Equivalent to '.|' and '=$='. However, the latter is
deprecated and will be removed in a future version.
Output from the upstream (left) conduit will be fed into the
downstream (right) conduit. Processing will terminate when
downstream (right) returns.
Leftover data returned from the right @Conduit@ will be discarded.
Equivalent to 'fuse' and '=$=', however the latter is deprecated and will
be removed in a future version.
Note that, while this operator looks like categorical composition
(from "Control.Category"), there are a few reasons it's different:
* The position of the type parameters to 'ConduitT' do not
m i o@, which would preclude a 'Monad' or 'MonadTrans' instance.
* The result value from upstream and downstream are allowed to
differ between upstream and downstream. In other words, we would
need the type signature here to look like @ConduitT a b m r ->
ConduitT b c m r -> ConduitT a c m r@.
can be achieved with the underlying @Pipe@ datatype, but this is
^ upstream
^ downstream
| The connect operator, which pulls data from a source and pushes to a sink.
If you would like to keep the @Source@ open to be used for other
# DEPRECATED ($$) "Use runConduit and .|" #
| A synonym for '=$=' for backwards compatibility.
# INLINE [0] ($=) #
# RULES "conduit: $= is =$=" ($=) = (=$=) #
# DEPRECATED ($=) "Use .|" #
| A synonym for '=$=' for backwards compatibility.
# INLINE [0] (=$) #
# RULES "conduit: =$ is =$=" (=$) = (=$=) #
# DEPRECATED (=$) "Use .|" #
| Deprecated fusion operator.
# DEPRECATED (=$=) "Use .|" #
| Wait for a single input value from upstream. If no data is available,
# INLINE [0] await #
# INLINE await' #
# RULES "conduit: await >>= maybe" forall x y. await >>= maybe x y = await' x y #
| Send a value downstream to the next component to consume. If the
downstream component terminates, this call will never return control.
^ output value
# INLINE yield #
| Send a monadic value downstream for the next component to consume.
@since 1.2.7
| Provide a single piece of leftover input to be consumed by the next
component in the current monadic binding.
/Note/: it is highly encouraged to only return leftover values from input
already consumed from upstream.
@since 0.5.0
| Run a pipeline until processing completes.
# INLINE [0] runConduit #
| Bracket a conduit computation between allocation and release of a
be run in the event of any exceptions.
^ computation to run last (\"release resource\")
^ computation to run in-between
returns the value from the in-between computation
| Wait for input forever, calling the given inner component for each piece of
new input.
This function is provided as a convenience for the common pattern of
@await@ing input, checking if it's @Just@ and then looping.
| Transform the monad that a @ConduitT@ lives in.
Note that the monad transforming function will be run multiple times,
resulting in unintuitive behavior in some cases. For a fuller treatment,
please see:
<-with-monad-transformers>
throw away side effects between different actions, an arbitrary break
between actions will lead to a violation of the monad transformer laws.
Example available at:
| Apply a function to all the output values of a @ConduitT@.
days. It can also be simulated by fusing with the @map@ conduit from
| Apply a function to all the input values of a @ConduitT@.
^ map initial input to new input
^ map new leftovers to initial leftovers
| Apply a monadic action to all the input values of a @ConduitT@.
^ map initial input to new input
^ map new leftovers to initial leftovers
| The connect-and-resume operator. This does not close the @Source@, but
instead returns it to be used again. This allows a @Source@ to be used
incrementally in a large program, without forcing the entire program to live
Mnemonic: connect + do more.
| Continue processing after usage of @$$+@.
| Same as @$$++@ and @connectResume@, but doesn't include the
/NOTE/ In previous versions, this would cause finalizers to
run. Since version 1.3.0, there are no finalizers in conduit.
| Left fusion for a sealed source.
| Provide for a stream of data that can be flushed.
the stream at some point. This provides a single wrapper datatype to be used
in all such circumstances.
| A wrapper for defining an 'Applicative' instance for 'Source's which allows
will take input yielded from each of its @Source@s until any of them stop
producing output.
Implemented on top of @ZipSource@ and as such, it exhibits the same
short-circuiting behavior as @ZipSource@. See that data type for more
details. If you want to create a source that yields *all* values from
multiple sources, use `sequence_`.
| A wrapper for defining an 'Applicative' instance for 'Sink's which allows
distributes the input to all its participants and when all finish, produces
the result. This allows to define functions like
@
sequenceSinks :: (Monad m)
=> [ConduitT i Void m r] -> ConduitT i Void m [r]
@
Note that the standard 'Applicative' instance for conduits works
to another, etc., and at the end combines their results.
your code clearer (and thereby make your error messages more easily
understood).
coalesce together all return values.
Implemented on top of @ZipSink@, see that data type for more details.
| The connect-and-resume operator. This does not close the @Conduit@, but
instead returns it to be used again. This allows a @Conduit@ to be used
incrementally in a large program, without forcing the entire program to live
Mnemonic: connect + do more.
Since 1.0.17
a sink and return the output of the sink together with a new
Since 1.0.17
/NOTE/ In previous versions, this would cause finalizers to
run. Since version 1.3.0, there are no finalizers in conduit.
Since 1.0.17
every incoming value is provided to all @ConduitT@s, and output is coalesced together.
at the end of their computation. Output and finalizers will both be handled in a left-biased manner.
As an example, take the following program:
@
main :: IO ()
main = do
sink = CL.mapM_ print
src $$ conduit =$ sink
@
Since 1.0.17
| Provide identical input to all of the @Conduit@s and combine their outputs
into a single stream.
Since 1.0.17
that this will force the entire upstream @ConduitT@ to be run to produce the
result value, even if the downstream terminates early.
| Like 'fuseBoth', but does not force consumption of the @Producer@.
In the case that the @Producer@ terminates, the result value is
provided as a @Just@ value. If it does not terminate, then a
@Nothing@ value is returned.
@Producer@ actually yields a @Nothing@ value. For example, with the
@Producer@ has not yet terminated. Termination only occurs when the
# INLINABLE fuseBothMaybe #
| Same as @fuseBoth@, but ignore the return value from the downstream
@Conduit@. Same caveats of forced consumption apply.
Rewrite rules
# RULES "conduit: ConduitT: lift x >>= f" forall m f. lift m >>= f = ConduitT (PipeM (liftM (unConduitT . f) m)) #
# RULES "conduit: ConduitT: liftIO x >>= f" forall m (f :: MonadIO m => a -> ConduitT i o m r). liftIO m >>= f = ConduitT (PipeM (liftM (unConduitT . f) (liftIO m))) #
# RULES "conduit: ConduitT: liftIO x >> f" forall m (f :: MonadIO m => ConduitT i o m r). liftIO m >> f = ConduitT (PipeM (liftM (\_ -> unConduitT f) (liftIO m))) #
# RULES "conduit: leftover l >> p" forall l (p :: ConduitT i o m r). leftover l >> p =
ConduitT (Leftover (unConduitT p) l) #
| Run a pure pipeline until processing completes, i.e. a pipeline
@runIdentity . runConduit@.
# INLINE runConduitPure #
| Run a pipeline which acquires resources with @ResourceT@, and
then run the @ResourceT@ transformer. This is equivalent to
@runResourceT . runConduit@.
| # OPTIONS_HADDOCK not - home #
# LANGUAGE DeriveFunctor #
# LANGUAGE FlexibleInstances #
# LANGUAGE FlexibleContexts #
# LANGUAGE CPP #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE UndecidableInstances #
# LANGUAGE TupleSections #
# LANGUAGE Trustworthy #
# LANGUAGE TypeFamilies #
module Data.Conduit.Internal.Conduit
ConduitT (..)
, ConduitM
, Source
, Producer
, Sink
, Consumer
, Conduit
, Flush (..)
* * * Newtype wrappers
, ZipSource (..)
, ZipSink (..)
, ZipConduit (..)
, SealedConduitT (..)
, sealConduitT
, unsealConduitT
, await
, awaitForever
, yield
, yieldM
, leftover
, runConduit
, runConduitPure
, runConduitRes
, fuse
, connect
, unconsM
, unconsEitherM
, connectResume
, connectResumeConduit
, fuseLeftovers
, fuseReturnLeftovers
, ($$+)
, ($$++)
, ($$+-)
, ($=+)
, (=$$+)
, (=$$++)
, (=$$+-)
, ($$)
, ($=)
, (=$)
, (=$=)
, (.|)
, sourceToPipe
, sinkToPipe
, conduitToPipe
, toProducer
, toConsumer
, bracketP
, catchC
, handleC
, tryC
, Data.Conduit.Internal.Conduit.transPipe
, Data.Conduit.Internal.Conduit.mapOutput
, Data.Conduit.Internal.Conduit.mapOutputMaybe
, Data.Conduit.Internal.Conduit.mapInput
, Data.Conduit.Internal.Conduit.mapInputM
, zipSinks
, zipSources
, zipSourcesApp
, zipConduitApp
, mergeSource
, passthroughSink
, sourceToList
, fuseBoth
, fuseBothMaybe
, fuseUpstream
, sequenceSources
, sequenceSinks
, sequenceConduits
) where
import Control.Applicative (Applicative (..))
import Control.Exception (Exception)
import qualified Control.Exception as E (catch)
import Control.Monad (liftM, liftM2, ap)
import Control.Monad.Fail(MonadFail(..))
import Control.Monad.Error.Class(MonadError(..))
import Control.Monad.Reader.Class(MonadReader(..))
import Control.Monad.RWS.Class(MonadRWS())
import Control.Monad.Writer.Class(MonadWriter(..), censor)
import Control.Monad.State.Class(MonadState(..))
import Control.Monad.Trans.Class (MonadTrans (lift))
import Control.Monad.IO.Unlift (MonadIO (liftIO), MonadUnliftIO, withRunInIO)
import Control.Monad.Primitive (PrimMonad, PrimState, primitive)
import Data.Functor.Identity (Identity, runIdentity)
import Data.Void (Void, absurd)
import Data.Monoid (Monoid (mappend, mempty))
import Data.Semigroup (Semigroup ((<>)))
import Control.Monad.Trans.Resource
import Data.Conduit.Internal.Pipe hiding (yield, mapOutput, leftover, yieldM, await, awaitForever, bracketP, unconsM, unconsEitherM)
import qualified Data.Conduit.Internal.Pipe as CI
import Control.Monad (forever)
import Data.Traversable (Traversable (..))
component which can consume a stream of input values @i@ , produce a stream
of output values @o@ , perform actions in the @m@ monad , and produce a final
result @r@. The type synonyms provided here are simply wrappers around this
newtype ConduitT i o m r = ConduitT
{ unConduitT :: forall b.
(r -> Pipe i i o () m b) -> Pipe i i o () m b
}
makes one case much more expensive : partially running a @ConduitT@
newtype SealedConduitT i o m r = SealedConduitT (Pipe i i o () m r)
type ConduitM = ConduitT
instance Functor (ConduitT i o m) where
fmap f (ConduitT c) = ConduitT $ \rest -> c (rest . f)
instance Applicative (ConduitT i o m) where
pure x = ConduitT ($ x)
# INLINE pure #
(<*>) = ap
(*>) = (>>)
instance Monad (ConduitT i o m) where
return = pure
ConduitT f >>= g = ConduitT $ \h -> f $ \a -> unConduitT (g a) h
instance MonadFail m => MonadFail (ConduitT i o m) where
fail = lift . Control.Monad.Fail.fail
instance MonadThrow m => MonadThrow (ConduitT i o m) where
throwM = lift . throwM
instance MonadIO m => MonadIO (ConduitT i o m) where
liftIO = lift . liftIO
# INLINE liftIO #
instance MonadReader r m => MonadReader r (ConduitT i o m) where
ask = lift ask
# INLINE ask #
local f (ConduitT c0) = ConduitT $ \rest ->
let go (HaveOutput p o) = HaveOutput (go p) o
go (NeedInput p c) = NeedInput (\i -> go (p i)) (\u -> go (c u))
go (Done x) = rest x
go (PipeM mp) = PipeM (liftM go $ local f mp)
go (Leftover p i) = Leftover (go p) i
in go (c0 Done)
#ifndef MIN_VERSION_mtl
#define MIN_VERSION_mtl(x, y, z) 0
#endif
instance MonadWriter w m => MonadWriter w (ConduitT i o m) where
#if MIN_VERSION_mtl(2, 1, 0)
writer = lift . writer
#endif
tell = lift . tell
listen (ConduitT c0) = ConduitT $ \rest ->
let go front (HaveOutput p o) = HaveOutput (go front p) o
go front (NeedInput p c) = NeedInput (\i -> go front (p i)) (\u -> go front (c u))
go front (Done x) = rest (x, front)
go front (PipeM mp) = PipeM $ do
(p,w) <- listen mp
return $ go (front `mappend` w) p
go front (Leftover p i) = Leftover (go front p) i
in go mempty (c0 Done)
pass (ConduitT c0) = ConduitT $ \rest ->
let go front (HaveOutput p o) = HaveOutput (go front p) o
go front (NeedInput p c) = NeedInput (\i -> go front (p i)) (\u -> go front (c u))
go front (PipeM mp) = PipeM $ do
(p,w) <- censor (const mempty) (listen mp)
return $ go (front `mappend` w) p
go front (Done (x,f)) = PipeM $ do
tell (f front)
return $ rest x
go front (Leftover p i) = Leftover (go front p) i
in go mempty (c0 Done)
instance MonadState s m => MonadState s (ConduitT i o m) where
get = lift get
put = lift . put
#if MIN_VERSION_mtl(2, 1, 0)
state = lift . state
#endif
instance MonadRWS r w s m => MonadRWS r w s (ConduitT i o m)
instance MonadError e m => MonadError e (ConduitT i o m) where
throwError = lift . throwError
catchError (ConduitT c0) f = ConduitT $ \rest ->
let go (HaveOutput p o) = HaveOutput (go p) o
go (NeedInput p c) = NeedInput (\i -> go (p i)) (\u -> go (c u))
go (Done x) = rest x
go (PipeM mp) =
PipeM $ catchError (liftM go mp) $ \e -> do
return $ unConduitT (f e) rest
go (Leftover p i) = Leftover (go p) i
in go (c0 Done)
instance MonadTrans (ConduitT i o) where
lift mr = ConduitT $ \rest -> PipeM (liftM rest mr)
# INLINE [ 1 ] lift #
instance MonadResource m => MonadResource (ConduitT i o m) where
liftResourceT = lift . liftResourceT
# INLINE liftResourceT #
instance Monad m => Semigroup (ConduitT i o m ()) where
(<>) = (>>)
instance Monad m => Monoid (ConduitT i o m ()) where
mempty = return ()
# INLINE mempty #
#if !(MIN_VERSION_base(4,11,0))
mappend = (<>)
# INLINE mappend #
#endif
instance PrimMonad m => PrimMonad (ConduitT i o m) where
type PrimState (ConduitT i o m) = PrimState m
primitive = lift . primitive
Since 0.5.0
type Source m o = ConduitT () o m ()
type Producer m o = forall i. ConduitT i o m ()
Since 0.5.0
type Sink i = ConduitT i Void
a @Sink@ , and can be used as either a @Sink@ or a @Conduit@.
type Consumer i m r = forall o. ConduitT i o m r
Since 0.5.0
type Conduit i m o = ConduitT i o m ()
sealConduitT :: ConduitT i o m r -> SealedConduitT i o m r
sealConduitT (ConduitT f) = SealedConduitT (f Done)
unsealConduitT :: Monad m => SealedConduitT i o m r -> ConduitT i o m r
unsealConduitT (SealedConduitT f) = ConduitT (f >>=)
| Connect a @Source@ to a @Sink@ until the latter closes . Returns both the
most recent state of the @Source@ and the result of the
Since 0.5.0
connectResume :: Monad m
=> SealedConduitT () a m ()
-> ConduitT a Void m r
-> m (SealedConduitT () a m (), r)
connectResume (SealedConduitT left0) (ConduitT right0) =
goRight left0 (right0 Done)
where
goRight left right =
case right of
HaveOutput _ o -> absurd o
NeedInput rp rc -> goLeft rp rc left
Done r2 -> return (SealedConduitT left, r2)
PipeM mp -> mp >>= goRight left
Leftover p i -> goRight (HaveOutput left i) p
goLeft rp rc left =
case left of
HaveOutput left' o -> goRight left' (rp o)
NeedInput _ lc -> recurse (lc ())
Done () -> goRight (Done ()) (rc ())
PipeM mp -> mp >>= recurse
Leftover p () -> recurse p
where
recurse = goLeft rp rc
sourceToPipe :: Monad m => ConduitT () o m () -> Pipe l i o u m ()
sourceToPipe (ConduitT k) =
go $ k Done
where
go (HaveOutput p o) = HaveOutput (go p) o
go (NeedInput _ c) = go $ c ()
go (Done ()) = Done ()
go (PipeM mp) = PipeM (liftM go mp)
go (Leftover p ()) = go p
sinkToPipe :: Monad m => ConduitT i Void m r -> Pipe l i o u m r
sinkToPipe (ConduitT k) =
go $ injectLeftovers $ k Done
where
go (HaveOutput _ o) = absurd o
go (NeedInput p c) = NeedInput (go . p) (const $ go $ c ())
go (Done r) = Done r
go (PipeM mp) = PipeM (liftM go mp)
go (Leftover _ l) = absurd l
conduitToPipe :: Monad m => ConduitT i o m () -> Pipe l i o u m ()
conduitToPipe (ConduitT k) =
go $ injectLeftovers $ k Done
where
go (HaveOutput p o) = HaveOutput (go p) o
go (NeedInput p c) = NeedInput (go . p) (const $ go $ c ())
go (Done ()) = Done ()
go (PipeM mp) = PipeM (liftM go mp)
go (Leftover _ l) = absurd l
| a ' Source ' to a ' Producer ' .
toProducer :: Monad m => ConduitT () a m () -> ConduitT i a m ()
toProducer (ConduitT c0) = ConduitT $ \rest -> let
go (HaveOutput p o) = HaveOutput (go p) o
go (NeedInput _ c) = go (c ())
go (Done r) = rest r
go (PipeM mp) = PipeM (liftM go mp)
go (Leftover p ()) = go p
in go (c0 Done)
| a ' Sink ' to a ' Consumer ' .
toConsumer :: Monad m => ConduitT a Void m b -> ConduitT a o m b
toConsumer (ConduitT c0) = ConduitT $ \rest -> let
go (HaveOutput _ o) = absurd o
go (NeedInput p c) = NeedInput (go . p) (go . c)
go (Done r) = rest r
go (PipeM mp) = PipeM (liftM go mp)
go (Leftover p l) = Leftover (go p) l
in go (c0 Done)
Note : this will /not/ catch exceptions thrown by other components ! For
example , if an exception is thrown in a @Source@ feeding to a @Sink@ , and
the @Sink@ uses @catchC@ , the exception will /not/ be caught .
Note also that the exception handling will /not/ be applied to any
Since 1.0.11
catchC :: (MonadUnliftIO m, Exception e)
=> ConduitT i o m r
-> (e -> ConduitT i o m r)
-> ConduitT i o m r
catchC (ConduitT p0) onErr = ConduitT $ \rest -> let
go (Done r) = rest r
go (PipeM mp) = PipeM $ withRunInIO $ \ run ->
run (liftM go mp) `E.catch` \ e ->
return $ onErr e `unConduitT` rest
go (Leftover p i) = Leftover (go p) i
go (NeedInput x y) = NeedInput (go . x) (go . y)
go (HaveOutput p o) = HaveOutput (go p) o
in go (p0 Done)
# INLINE catchC #
| The same as catchC@.
Since 1.0.11
handleC :: (MonadUnliftIO m, Exception e)
=> (e -> ConduitT i o m r)
-> ConduitT i o m r
-> ConduitT i o m r
handleC = flip catchC
# INLINE handleC #
| A version of @try@ for use within a pipeline . See the comments in @catchC@
Since 1.0.11
tryC :: (MonadUnliftIO m, Exception e)
=> ConduitT i o m r
-> ConduitT i o m (Either e r)
tryC c = fmap Right c `catchC` (return . Left)
# INLINE tryC #
| Combines two sinks . The new sink will complete when both input sinks have
Since 0.4.1
zipSinks :: Monad m => ConduitT i Void m r -> ConduitT i Void m r' -> ConduitT i Void m (r, r')
zipSinks (ConduitT x0) (ConduitT y0) = ConduitT $ \rest -> let
Leftover _ i >< _ = absurd i
_ >< Leftover _ i = absurd i
HaveOutput _ o >< _ = absurd o
_ >< HaveOutput _ o = absurd o
PipeM mx >< y = PipeM (liftM (>< y) mx)
x >< PipeM my = PipeM (liftM (x ><) my)
Done x >< Done y = rest (x, y)
NeedInput px cx >< NeedInput py cy = NeedInput (\i -> px i >< py i) (\() -> cx () >< cy ())
NeedInput px cx >< y@Done{} = NeedInput (\i -> px i >< y) (\u -> cx u >< y)
x@Done{} >< NeedInput py cy = NeedInput (\i -> x >< py i) (\u -> x >< cy u)
in injectLeftovers (x0 Done) >< injectLeftovers (y0 Done)
| Combines two sources . The new source will stop producing once either
Since 1.0.13
zipSources :: Monad m => ConduitT () a m () -> ConduitT () b m () -> ConduitT () (a, b) m ()
zipSources (ConduitT left0) (ConduitT right0) = ConduitT $ \rest -> let
go (Leftover left ()) right = go left right
go left (Leftover right ()) = go left right
go (Done ()) (Done ()) = rest ()
go (Done ()) (HaveOutput _ _) = rest ()
go (HaveOutput _ _) (Done ()) = rest ()
go (Done ()) (PipeM _) = rest ()
go (PipeM _) (Done ()) = rest ()
go (PipeM mx) (PipeM my) = PipeM (liftM2 go mx my)
go (PipeM mx) y@HaveOutput{} = PipeM (liftM (\x -> go x y) mx)
go x@HaveOutput{} (PipeM my) = PipeM (liftM (go x) my)
go (HaveOutput srcx x) (HaveOutput srcy y) = HaveOutput (go srcx srcy) (x, y)
go (NeedInput _ c) right = go (c ()) right
go left (NeedInput _ c) = go left (c ())
in go (left0 Done) (right0 Done)
| Combines two sources . The new source will stop producing once either
Since 1.0.13
zipSourcesApp :: Monad m => ConduitT () (a -> b) m () -> ConduitT () a m () -> ConduitT () b m ()
zipSourcesApp (ConduitT left0) (ConduitT right0) = ConduitT $ \rest -> let
go (Leftover left ()) right = go left right
go left (Leftover right ()) = go left right
go (Done ()) (Done ()) = rest ()
go (Done ()) (HaveOutput _ _) = rest ()
go (HaveOutput _ _) (Done ()) = rest ()
go (Done ()) (PipeM _) = rest ()
go (PipeM _) (Done ()) = rest ()
go (PipeM mx) (PipeM my) = PipeM (liftM2 go mx my)
go (PipeM mx) y@HaveOutput{} = PipeM (liftM (\x -> go x y) mx)
go x@HaveOutput{} (PipeM my) = PipeM (liftM (go x) my)
go (HaveOutput srcx x) (HaveOutput srcy y) = HaveOutput (go srcx srcy) (x y)
go (NeedInput _ c) right = go (c ()) right
go left (NeedInput _ c) = go left (c ())
in go (left0 Done) (right0 Done)
zipConduitApp
:: Monad m
=> ConduitT i o m (x -> y)
-> ConduitT i o m x
-> ConduitT i o m y
zipConduitApp (ConduitT left0) (ConduitT right0) = ConduitT $ \rest -> let
go (Done f) (Done x) = rest (f x)
go (PipeM mx) y = PipeM (flip go y `liftM` mx)
go x (PipeM my) = PipeM (go x `liftM` my)
go (HaveOutput x o) y = HaveOutput (go x y) o
go x (HaveOutput y o) = HaveOutput (go x y) o
go (Leftover _ i) _ = absurd i
go _ (Leftover _ i) = absurd i
go (NeedInput px cx) (NeedInput py cy) = NeedInput
(\i -> go (px i) (py i))
(\u -> go (cx u) (cy u))
go (NeedInput px cx) (Done y) = NeedInput
(\i -> go (px i) (Done y))
(\u -> go (cx u) (Done y))
go (Done x) (NeedInput py cy) = NeedInput
(\i -> go (Done x) (py i))
(\u -> go (Done x) (cy u))
in go (injectLeftovers $ left0 Done) (injectLeftovers $ right0 Done)
fuseReturnLeftovers :: Monad m
=> ConduitT a b m ()
-> ConduitT b c m r
-> ConduitT a c m (r, [b])
fuseReturnLeftovers (ConduitT left0) (ConduitT right0) = ConduitT $ \rest -> let
goRight bs left right =
case right of
HaveOutput p o -> HaveOutput (recurse p) o
NeedInput rp rc ->
case bs of
[] -> goLeft rp rc left
b:bs' -> goRight bs' left (rp b)
Done r2 -> rest (r2, bs)
PipeM mp -> PipeM (liftM recurse mp)
Leftover p b -> goRight (b:bs) left p
where
recurse = goRight bs left
goLeft rp rc left =
case left of
HaveOutput left' o -> goRight [] left' (rp o)
NeedInput left' lc -> NeedInput (recurse . left') (recurse . lc)
Done r1 -> goRight [] (Done r1) (rc r1)
PipeM mp -> PipeM (liftM recurse mp)
Leftover left' i -> Leftover (recurse left') i
where
recurse = goLeft rp rc
in goRight [] (left0 Done) (right0 Done)
fuseLeftovers
:: Monad m
=> ([b] -> [a])
-> ConduitT a b m ()
-> ConduitT b c m r
-> ConduitT a c m r
fuseLeftovers f left right = do
(r, bs) <- fuseReturnLeftovers left right
mapM_ leftover $ reverse $ f bs
return r
| Connect a ' Conduit ' to a sink and return the output of the sink
together with a new ' Conduit ' .
connectResumeConduit
:: Monad m
=> SealedConduitT i o m ()
-> ConduitT o Void m r
-> ConduitT i Void m (SealedConduitT i o m (), r)
connectResumeConduit (SealedConduitT left0) (ConduitT right0) = ConduitT $ \rest -> let
goRight left right =
case right of
HaveOutput _ o -> absurd o
NeedInput rp rc -> goLeft rp rc left
Done r2 -> rest (SealedConduitT left, r2)
PipeM mp -> PipeM (liftM (goRight left) mp)
Leftover p i -> goRight (HaveOutput left i) p
goLeft rp rc left =
case left of
HaveOutput left' o -> goRight left' (rp o)
NeedInput left' lc -> NeedInput (recurse . left') (recurse . lc)
Done () -> goRight (Done ()) (rc ())
PipeM mp -> PipeM (liftM recurse mp)
where
recurse = goLeft rp rc
in goRight left0 (right0 Done)
mergeSource
:: Monad m
=> ConduitT () i m ()
-> ConduitT a (i, a) m ()
mergeSource = loop . sealConduitT
where
loop :: Monad m => SealedConduitT () i m () -> ConduitT a (i, a) m ()
loop src0 = await >>= maybe (return ()) go
where
go a = do
(src1, mi) <- lift $ src0 $$++ await
case mi of
Nothing -> return ()
Just i -> yield (i, a) >> loop src1
| Turn a @Sink@ into a @Conduit@ in the following way :
* All input passed to the @Sink@ is yielded downstream .
* When the @Sink@ finishes processing , the result is passed to the provided to the finalizer function .
Note that the @Sink@ will stop receiving input as soon as the downstream it
An example usage would be to write the result of a @Sink@ to some mutable
passthroughSink :: Monad m
=> ConduitT i Void m r
-> ConduitT i i m ()
passthroughSink (ConduitT sink0) final = ConduitT $ \rest -> let
third argument to go is the current state of that sink . That 's
The second value is the leftover buffer . These are values that
The trickiest bit is the first argument , which is a solution to
bug . The issue
is yield first and then recursively call go . Unfortunately ,
and only yield it downstream in one of two cases : our sink is
go mbuf _ (Done r) = do
maybe (return ()) CI.yield mbuf
lift $ final r
unConduitT (awaitForever yield) rest
go mbuf is (Leftover sink i) = go mbuf (i:is) sink
go _ _ (HaveOutput _ o) = absurd o
go mbuf is (PipeM mx) = do
x <- lift mx
go mbuf is x
go mbuf (i:is) (NeedInput next _) = go mbuf is (next i)
go mbuf [] (NeedInput next done) = do
maybe (return ()) CI.yield mbuf
mx <- CI.await
case mx of
Nothing -> go Nothing [] (done ())
Just x -> go (Just x) [] (next x)
in go Nothing [] (sink0 Done)
> sourceToList src = src $ $ Data.Conduit.List.consume
However , @sourceToList@ is able to produce its results lazily , which can not
@Data . Conduit . Lazy@ module ( in conduit - extra ) , this function performs no
unsafe I\/O operations , and therefore can only be as lazy as the
sourceToList :: Monad m => ConduitT () a m () -> m [a]
sourceToList (ConduitT k) =
go $ k Done
where
go (Done _) = return []
go (HaveOutput src x) = liftM (x:) (go src)
go (PipeM msrc) = msrc >>= go
go (NeedInput _ c) = go (c ())
go (Leftover p _) = go p
infixr 0 $$
infixl 1 $=
infixr 2 =$
infixr 2 =$=
infixr 0 $$+
infixr 0 $$++
infixr 0 $$+-
infixl 1 $=+
infixr 2 .|
| Equivalent to using ' runConduit ' and ' .| ' together .
Since 1.2.3
connect :: Monad m
=> ConduitT () a m ()
-> ConduitT a Void m r
-> m r
connect = ($$)
Note that you have to ' sealConduitT ' it first .
unconsM :: Monad m
=> SealedConduitT () o m ()
-> m (Maybe (o, SealedConduitT () o m ()))
unconsM (SealedConduitT p) = go p
where
go (HaveOutput p o) = pure $ Just (o, SealedConduitT p)
go (NeedInput _ c) = go $ c ()
go (Done ()) = pure Nothing
go (PipeM mp) = mp >>= go
go (Leftover p ()) = go p
Note that you have to ' sealConduitT ' it first .
unconsEitherM :: Monad m
=> SealedConduitT () o m r
-> m (Either r (o, SealedConduitT () o m r))
unconsEitherM (SealedConduitT p) = go p
where
This function is the same as @Pipe.unconsEitherM@ but it ignores leftovers .
go (HaveOutput p o) = pure $ Right (o, SealedConduitT p)
go (NeedInput _ c) = go $ c ()
go (Done r) = pure $ Left r
go (PipeM mp) = mp >>= go
go (Leftover p ()) = go p
Since 1.2.3
fuse :: Monad m => ConduitT a b m () -> ConduitT b c m r -> ConduitT a c m r
fuse = (=$=)
| Combine two @Conduit@s together into a new @Conduit@ ( aka ' fuse ' ) .
match . We would need to change @ConduitT i o m r@ to @ConduitT r
* Due to leftovers , we do not have a left identity in Conduit . This
not generally recommended . See < > .
@since 1.2.8
(.|) :: Monad m
-> ConduitT a c m r
(.|) = fuse
# INLINE ( .| ) #
operations , use the connect - and - resume operator ' $ $ + ' .
Since 0.4.0
($$) :: Monad m => Source m a -> Sink a m b -> m b
src $$ sink = do
(rsrc, res) <- src $$+ sink
rsrc $$+- return ()
return res
# INLINE [ 1 ] ( $ $ ) #
Since 0.4.0
($=) :: Monad m => Conduit a m b -> ConduitT b c m r -> ConduitT a c m r
($=) = (=$=)
Since 0.4.0
(=$) :: Monad m => Conduit a m b -> ConduitT b c m r -> ConduitT a c m r
(=$) = (=$=)
Since 0.4.0
(=$=) :: Monad m => Conduit a m b -> ConduitT b c m r -> ConduitT a c m r
ConduitT left0 =$= ConduitT right0 = ConduitT $ \rest ->
let goRight left right =
case right of
HaveOutput p o -> HaveOutput (recurse p) o
NeedInput rp rc -> goLeft rp rc left
Done r2 -> rest r2
PipeM mp -> PipeM (liftM recurse mp)
Leftover right' i -> goRight (HaveOutput left i) right'
where
recurse = goRight left
goLeft rp rc left =
case left of
HaveOutput left' o -> goRight left' (rp o)
NeedInput left' lc -> NeedInput (recurse . left') (recurse . lc)
Done r1 -> goRight (Done r1) (rc r1)
PipeM mp -> PipeM (liftM recurse mp)
Leftover left' i -> Leftover (recurse left') i
where
recurse = goLeft rp rc
in goRight (left0 Done) (right0 Done)
# INLINE [ 1 ] (= $ =) #
returns @Nothing@. Once @await@ returns @Nothing@ , subsequent calls will
also return @Nothing@.
Since 0.5.0
await :: Monad m => ConduitT i o m (Maybe i)
await = ConduitT $ \f -> NeedInput (f . Just) (const $ f Nothing)
await' :: Monad m
=> ConduitT i o m r
-> (i -> ConduitT i o m r)
-> ConduitT i o m r
await' f g = ConduitT $ \rest -> NeedInput
(\i -> unConduitT (g i) rest)
(const $ unConduitT f rest)
Since 0.5.0
yield :: Monad m
-> ConduitT i o m ()
yield o = ConduitT $ \rest -> HaveOutput (rest ()) o
yieldM :: Monad m => m o -> ConduitT i o m ()
yieldM mo = lift mo >>= yield
# INLINE yieldM #
FIXME rule wo n't fire , see FIXME in .Pipe ; " mapM _ yield " mapM _ yield = ConduitT . sourceList
leftover :: i -> ConduitT i o m ()
leftover i = ConduitT $ \rest -> Leftover (rest ()) i
# INLINE leftover #
Since 1.2.1
runConduit :: Monad m => ConduitT () Void m r -> m r
runConduit (ConduitT p) = runPipe $ injectLeftovers $ p Done
resource . Two guarantees are given about resource finalization :
1 . It will be /prompt/. The finalization will be run as early as possible .
2 . It is exception safe . Due to usage of @resourcet@ , the finalization will
Since 0.5.0
bracketP :: MonadResource m
=> IO a
^ computation to run first ( \"acquire resource\ " )
-> (a -> IO ())
-> (a -> ConduitT i o m r)
-> ConduitT i o m r
bracketP alloc free inside = ConduitT $ \rest -> do
(key, seed) <- allocate alloc free
unConduitT (inside seed) $ \res -> do
release key
rest res
Since 0.5.0
awaitForever :: Monad m => (i -> ConduitT i o m r) -> ConduitT i o m ()
awaitForever f = ConduitT $ \rest ->
let go = NeedInput (\i -> unConduitT (f i) (const go)) rest
in go
Since 0.4.0
transPipe :: Monad m => (forall a. m a -> n a) -> ConduitT i o m r -> ConduitT i o n r
transPipe f (ConduitT c0) = ConduitT $ \rest -> let
go (HaveOutput p o) = HaveOutput (go p) o
go (NeedInput p c) = NeedInput (go . p) (go . c)
go (Done r) = rest r
go (PipeM mp) =
PipeM (f $ liftM go $ collapse mp)
where
Combine a series of monadic actions into a single action . Since we
collapse mpipe = do
pipe' <- mpipe
case pipe' of
PipeM mpipe' -> collapse mpipe'
_ -> return pipe'
go (Leftover p i) = Leftover (go p) i
in go (c0 Done)
This mimics the behavior of ` fmap ` for a ` Source ` and ` Conduit ` in pre-0.4
" Data . Conduit . List " .
Since 0.4.1
mapOutput :: Monad m => (o1 -> o2) -> ConduitT i o1 m r -> ConduitT i o2 m r
mapOutput f (ConduitT c0) = ConduitT $ \rest -> let
go (HaveOutput p o) = HaveOutput (go p) (f o)
go (NeedInput p c) = NeedInput (go . p) (go . c)
go (Done r) = rest r
go (PipeM mp) = PipeM (liftM (go) mp)
go (Leftover p i) = Leftover (go p) i
in go (c0 Done)
| Same as , but use a function that returns @Maybe@ values .
Since 0.5.0
mapOutputMaybe :: Monad m => (o1 -> Maybe o2) -> ConduitT i o1 m r -> ConduitT i o2 m r
mapOutputMaybe f (ConduitT c0) = ConduitT $ \rest -> let
go (HaveOutput p o) = maybe id (\o' p' -> HaveOutput p' o') (f o) (go p)
go (NeedInput p c) = NeedInput (go . p) (go . c)
go (Done r) = rest r
go (PipeM mp) = PipeM (liftM (go) mp)
go (Leftover p i) = Leftover (go p) i
in go (c0 Done)
Since 0.5.0
mapInput :: Monad m
-> ConduitT i2 o m r
-> ConduitT i1 o m r
mapInput f f' (ConduitT c0) = ConduitT $ \rest -> let
go (HaveOutput p o) = HaveOutput (go p) o
go (NeedInput p c) = NeedInput (go . p . f) (go . c)
go (Done r) = rest r
go (PipeM mp) = PipeM $ liftM go mp
go (Leftover p i) = maybe id (flip Leftover) (f' i) (go p)
in go (c0 Done)
Since 1.3.2
mapInputM :: Monad m
-> ConduitT i2 o m r
-> ConduitT i1 o m r
mapInputM f f' (ConduitT c0) = ConduitT $ \rest -> let
go (HaveOutput p o) = HaveOutput (go p) o
go (NeedInput p c) = NeedInput (\i -> PipeM $ go . p <$> f i) (go . c)
go (Done r) = rest r
go (PipeM mp) = PipeM $ fmap go mp
go (Leftover p i) = PipeM $ (\x -> maybe id (flip Leftover) x (go p)) <$> f' i
in go (c0 Done)
in the @Sink@ monad .
Since 0.5.0
($$+) :: Monad m => ConduitT () a m () -> ConduitT a Void m b -> m (SealedConduitT () a m (), b)
src $$+ sink = connectResume (sealConduitT src) sink
# INLINE ( $ $ + ) #
Since 0.5.0
($$++) :: Monad m => SealedConduitT () a m () -> ConduitT a Void m b -> m (SealedConduitT () a m (), b)
($$++) = connectResume
# INLINE ( $ $ + + ) #
updated
Since 0.5.0
($$+-) :: Monad m => SealedConduitT () a m () -> ConduitT a Void m b -> m b
rsrc $$+- sink = do
(_, res) <- connectResume rsrc sink
return res
# INLINE ( $ $ + - ) #
Since 1.0.16
($=+) :: Monad m => SealedConduitT () a m () -> ConduitT a b m () -> SealedConduitT () b m ()
SealedConduitT src $=+ ConduitT sink = SealedConduitT (src `pipeL` sink Done)
A number of @Conduit@s ( e.g. , ) need the ability to flush
Since 0.3.0
data Flush a = Chunk a | Flush
deriving (Show, Eq, Ord)
instance Functor Flush where
fmap _ Flush = Flush
fmap f (Chunk a) = Chunk (f a)
to combine sources together , generalizing ' ' . A combined source
Since 1.0.13
newtype ZipSource m o = ZipSource { getZipSource :: ConduitT () o m () }
instance Monad m => Functor (ZipSource m) where
fmap f = ZipSource . mapOutput f . getZipSource
instance Monad m => Applicative (ZipSource m) where
pure = ZipSource . forever . yield
(ZipSource f) <*> (ZipSource x) = ZipSource $ zipSourcesApp f x
| Coalesce all values yielded by all of the @Source@s .
Since 1.0.13
sequenceSources :: (Traversable f, Monad m) => f (ConduitT () o m ()) -> ConduitT () (f o) m ()
sequenceSources = getZipSource . sequenceA . fmap ZipSource
to combine sinks together , generalizing ' ' . A combined sink
sequenceSinks = getZipSink . sequenceA . fmap ZipSink
differently . It feeds one sink with input until it finishes , then switches
This newtype is in fact a type constrained version of ' ZipConduit ' , and has
the same behavior . It 's presented as a separate type since ( 1 ) it
historically predates @ZipConduit@ , and ( 2 ) the type constraining can make
Since 1.0.13
newtype ZipSink i m r = ZipSink { getZipSink :: ConduitT i Void m r }
instance Monad m => Functor (ZipSink i m) where
fmap f (ZipSink x) = ZipSink (liftM f x)
instance Monad m => Applicative (ZipSink i m) where
pure = ZipSink . return
(ZipSink f) <*> (ZipSink x) =
ZipSink $ liftM (uncurry ($)) $ zipSinks f x
| Send incoming values to all of the @Sink@ providing , and ultimately
Since 1.0.13
sequenceSinks :: (Traversable f, Monad m) => f (ConduitT i Void m r) -> ConduitT i Void m (f r)
sequenceSinks = getZipSink . sequenceA . fmap ZipSink
in the @Sink@ monad .
Leftover data returned from the @Sink@ will be discarded .
(=$$+) :: Monad m
=> ConduitT a b m ()
-> ConduitT b Void m r
-> ConduitT a Void m (SealedConduitT a b m (), r)
(=$$+) conduit = connectResumeConduit (sealConduitT conduit)
# INLINE (= $ $ + ) #
| Continue processing after usage of ' = $ $ + ' . Connect a ' SealedConduitT ' to
' SealedConduitT ' .
(=$$++) :: Monad m => SealedConduitT i o m () -> ConduitT o Void m r -> ConduitT i Void m (SealedConduitT i o m (), r)
(=$$++) = connectResumeConduit
# INLINE (= $ $ + + ) #
| Same as @=$$++@ , but does n't include the updated
(=$$+-) :: Monad m => SealedConduitT i o m () -> ConduitT o Void m r -> ConduitT i Void m r
rsrc =$$+- sink = do
(_, res) <- connectResumeConduit rsrc sink
return res
# INLINE (= $ $ + - ) #
infixr 0 =$$+
infixr 0 =$$++
infixr 0 =$$+-
| Provides an alternative @Applicative@ instance for @ConduitT@. In this instance ,
Leftovers from individual @ConduitT@s will be used within that component , and then discarded
let src = mapM _ yield [ 1 .. 3 : : Int ]
= CL.map ( +1 )
= CL.concatMap ( replicate 2 )
conduit = getZipConduit $ < *
It will produce the output : 2 , 1 , 1 , 3 , 2 , 2 , 4 , 3 , 3
newtype ZipConduit i o m r = ZipConduit { getZipConduit :: ConduitT i o m r }
deriving Functor
instance Monad m => Applicative (ZipConduit i o m) where
pure = ZipConduit . pure
ZipConduit left <*> ZipConduit right = ZipConduit (zipConduitApp left right)
Implemented on top of @ZipConduit@ , see that data type for more details .
sequenceConduits :: (Traversable f, Monad m) => f (ConduitT i o m r) -> ConduitT i o m (f r)
sequenceConduits = getZipConduit . sequenceA . fmap ZipConduit
| Fuse two @ConduitT@s together , and provide the return value of both . Note
Since 1.1.5
fuseBoth :: Monad m => ConduitT a b m r1 -> ConduitT b c m r2 -> ConduitT a c m (r1, r2)
fuseBoth (ConduitT up) (ConduitT down) =
ConduitT (pipeL (up Done) (withUpstream $ generalizeUpstream $ down Done) >>=)
# INLINE fuseBoth #
One thing to note here is that " termination " here only occurs if the
@Producer@ @mapM _ yield [ 1 .. 5]@ , if five values are requested , the
sixth value is awaited for and the @Producer@ signals termination .
Since 1.2.4
fuseBothMaybe
:: Monad m
=> ConduitT a b m r1
-> ConduitT b c m r2
-> ConduitT a c m (Maybe r1, r2)
fuseBothMaybe (ConduitT up) (ConduitT down) =
ConduitT (pipeL (up Done) (go Nothing $ down Done) >>=)
where
go mup (Done r) = Done (mup, r)
go mup (PipeM mp) = PipeM $ liftM (go mup) mp
go mup (HaveOutput p o) = HaveOutput (go mup p) o
go _ (NeedInput p c) = NeedInput
(\i -> go Nothing (p i))
(\u -> go (Just u) (c ()))
go mup (Leftover p i) = Leftover (go mup p) i
Since 1.1.5
fuseUpstream :: Monad m => ConduitT a b m r -> ConduitT b c m () -> ConduitT a c m r
fuseUpstream up down = fmap fst (fuseBoth up down)
# INLINE fuseUpstream #
FIXME
{ - # RULES " conduit : ConduitT : lift x > > = f " forall > > = f = ConduitT ( PipeM ( liftM ( unConduitT . f ) m ) ) #
# RULES " conduit : ConduitT : lift x > > f " forall > > f = ConduitT ( PipeM ( liftM ( \ _ - > unConduitT f ) m ) ) #
# RULES " conduit : ConduitT : liftBase x > > = f " forall m ( f : : MonadBase b m = > a - > ConduitT i o m r ) . liftBase m > > = f = ConduitT ( PipeM ( liftM ( unConduitT . f ) ( liftBase m ) ) ) #
# RULES " conduit : ConduitT : liftBase x > > f " forall m ( f : : MonadBase b m = > ConduitT i o m r ) . liftBase m > > f = ConduitT ( PipeM ( liftM ( \ _ - > unConduitT f ) ( liftBase m ) ) ) #
# RULES
" yield o > > p " forall o ( p : : ConduitT i o m r ) . yield o > > p = ConduitT ( HaveOutput ( unConduitT p ) o )
; " when yield next " forall b o p. when b ( yield o ) > > p =
if b then ConduitT ( HaveOutput ( unConduitT p ) o ) else ; " unless yield next " forall b o p. unless b ( yield o ) > > p =
if b then p else ConduitT ( HaveOutput ( unConduitT p ) o )
; " lift m > > = yield " forall m. lift m > > = yield = yieldM m
#
"yield o >> p" forall o (p :: ConduitT i o m r). yield o >> p = ConduitT (HaveOutput (unConduitT p) o)
; "when yield next" forall b o p. when b (yield o) >> p =
if b then ConduitT (HaveOutput (unConduitT p) o) else p
; "unless yield next" forall b o p. unless b (yield o) >> p =
if b then p else ConduitT (HaveOutput (unConduitT p) o)
; "lift m >>= yield" forall m. lift m >>= yield = yieldM m
#-}
-}
with @Identity@ as the base monad . This is equivalient to
@since 1.2.8
runConduitPure :: ConduitT () Void Identity r -> r
runConduitPure = runIdentity . runConduit
@since 1.2.8
runConduitRes :: MonadUnliftIO m
=> ConduitT () Void (ResourceT m) r
-> m r
runConduitRes = runResourceT . runConduit
# INLINE runConduitRes #
|
8def97ad40478bb0a0573f0382fd2c376cea90cbfbb7eb935df172bb69363eb0 | bsansouci/bsb-native | frames.ml | (***********************************************************************)
(* *)
(* OCaml *)
(* *)
, projet Cristal , INRIA Rocquencourt
OCaml port by and
(* *)
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 .
(* *)
(***********************************************************************)
(***************************** Frames **********************************)
open Instruct
open Debugcom
open Events
open Symbols
(* Current frame number *)
let current_frame = ref 0
(* Event at selected position *)
let selected_event = ref (None : debug_event option)
(* Selected position in source. *)
(* Raise `Not_found' if not on an event. *)
let selected_point () =
match !selected_event with
None ->
raise Not_found
| Some ev ->
(ev.ev_module,
(Events.get_pos ev).Lexing.pos_lnum,
(Events.get_pos ev).Lexing.pos_cnum - (Events.get_pos ev).Lexing.pos_bol)
let selected_event_is_before () =
match !selected_event with
None ->
raise Not_found
| Some {ev_kind = Event_before} ->
true
| _ ->
false
(* Move up `frame_count' frames, assuming current frame pointer
corresponds to event `event'. Return event of final frame. *)
let rec move_up frame_count event =
if frame_count <= 0 then event else begin
let (sp, pc) = up_frame event.ev_stacksize in
if sp < 0 then raise Not_found;
move_up (frame_count - 1) (any_event_at_pc pc)
end
(* Select a frame. *)
(* Raise `Not_found' if no such frame. *)
(* --- Assume the current events have already been updated. *)
let select_frame frame_number =
if frame_number < 0 then raise Not_found;
let (initial_sp, _) = get_frame() in
try
match !current_event with
None ->
raise Not_found
| Some curr_event ->
match !selected_event with
Some sel_event when frame_number >= !current_frame ->
selected_event :=
Some(move_up (frame_number - !current_frame) sel_event);
current_frame := frame_number
| _ ->
set_initial_frame();
selected_event := Some(move_up frame_number curr_event);
current_frame := frame_number
with Not_found ->
set_frame initial_sp;
raise Not_found
(* Select a frame. *)
(* Same as `select_frame' but raise no exception if the frame is not found. *)
(* --- Assume the currents events have already been updated. *)
let try_select_frame frame_number =
try
select_frame frame_number
with
Not_found ->
()
(* Return to default frame (frame 0). *)
let reset_frame () =
set_initial_frame();
selected_event := !current_event;
current_frame := 0
(* Perform a stack backtrace.
Call the given function with the events for each stack frame,
or None if we've encountered a stack frame with no debugging info
attached. Stop when the function returns false, or frame with no
debugging info reached, or top of stack reached. *)
let do_backtrace action =
match !current_event with
None -> Misc.fatal_error "Frames.do_backtrace"
| Some curr_ev ->
let (initial_sp, _) = get_frame() in
set_initial_frame();
let event = ref curr_ev in
begin try
while action (Some !event) do
let (sp, pc) = up_frame !event.ev_stacksize in
if sp < 0 then raise Exit;
event := any_event_at_pc pc
done
with Exit -> ()
| Not_found -> ignore (action None)
end;
set_frame initial_sp
(* Return the number of frames in the stack *)
let stack_depth () =
let num_frames = ref 0 in
do_backtrace (function Some ev -> incr num_frames; true
| None -> num_frames := -1; false);
!num_frames
| null | https://raw.githubusercontent.com/bsansouci/bsb-native/9a89457783d6e80deb0fba9ca7372c10a768a9ea/vendor/ocaml/debugger/frames.ml | ocaml | *********************************************************************
OCaml
*********************************************************************
**************************** Frames *********************************
Current frame number
Event at selected position
Selected position in source.
Raise `Not_found' if not on an event.
Move up `frame_count' frames, assuming current frame pointer
corresponds to event `event'. Return event of final frame.
Select a frame.
Raise `Not_found' if no such frame.
--- Assume the current events have already been updated.
Select a frame.
Same as `select_frame' but raise no exception if the frame is not found.
--- Assume the currents events have already been updated.
Return to default frame (frame 0).
Perform a stack backtrace.
Call the given function with the events for each stack frame,
or None if we've encountered a stack frame with no debugging info
attached. Stop when the function returns false, or frame with no
debugging info reached, or top of stack reached.
Return the number of frames in the stack | , projet Cristal , INRIA Rocquencourt
OCaml port by and
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 .
open Instruct
open Debugcom
open Events
open Symbols
let current_frame = ref 0
let selected_event = ref (None : debug_event option)
let selected_point () =
match !selected_event with
None ->
raise Not_found
| Some ev ->
(ev.ev_module,
(Events.get_pos ev).Lexing.pos_lnum,
(Events.get_pos ev).Lexing.pos_cnum - (Events.get_pos ev).Lexing.pos_bol)
let selected_event_is_before () =
match !selected_event with
None ->
raise Not_found
| Some {ev_kind = Event_before} ->
true
| _ ->
false
let rec move_up frame_count event =
if frame_count <= 0 then event else begin
let (sp, pc) = up_frame event.ev_stacksize in
if sp < 0 then raise Not_found;
move_up (frame_count - 1) (any_event_at_pc pc)
end
let select_frame frame_number =
if frame_number < 0 then raise Not_found;
let (initial_sp, _) = get_frame() in
try
match !current_event with
None ->
raise Not_found
| Some curr_event ->
match !selected_event with
Some sel_event when frame_number >= !current_frame ->
selected_event :=
Some(move_up (frame_number - !current_frame) sel_event);
current_frame := frame_number
| _ ->
set_initial_frame();
selected_event := Some(move_up frame_number curr_event);
current_frame := frame_number
with Not_found ->
set_frame initial_sp;
raise Not_found
let try_select_frame frame_number =
try
select_frame frame_number
with
Not_found ->
()
let reset_frame () =
set_initial_frame();
selected_event := !current_event;
current_frame := 0
let do_backtrace action =
match !current_event with
None -> Misc.fatal_error "Frames.do_backtrace"
| Some curr_ev ->
let (initial_sp, _) = get_frame() in
set_initial_frame();
let event = ref curr_ev in
begin try
while action (Some !event) do
let (sp, pc) = up_frame !event.ev_stacksize in
if sp < 0 then raise Exit;
event := any_event_at_pc pc
done
with Exit -> ()
| Not_found -> ignore (action None)
end;
set_frame initial_sp
let stack_depth () =
let num_frames = ref 0 in
do_backtrace (function Some ev -> incr num_frames; true
| None -> num_frames := -1; false);
!num_frames
|
6d458735b6b5025eed7cdf7a28b51d94cf6be6e189de618ba9f38dd657747bbb | thi-ng/geom | core.cljc | (ns thi.ng.geom.viz.core
(:require
[thi.ng.geom.core :as g]
[thi.ng.geom.vector :as v :refer [vec2 vec3]]
[thi.ng.geom.utils :as gu]
[thi.ng.geom.svg.core :as svg]
[thi.ng.ndarray.core :as nd]
[thi.ng.ndarray.contours :as contours]
[thi.ng.math.core :as m]
[thi.ng.strf.core :as f]))
;; This module currently consists of this single namespace dedicated
;; to creating 2D (and soon 3D too) data visualizations in an output
;; format agnostic way. To achieve that, an overall declarative and
;; pipelined approach has been taken to create these visualizations:
;;
1 . We first define a configuration map , supplying all data points ,
;; axis definitions, layout arguments/handlers, styling options etc.
2 . This map is then transformed into a tree / scenegraph of geometric
;; primitives (shapes & groups) representing the visualization.
3 . This tree of still pure Clojure data is then further converted into
the final output format , e.g. for SVG first into
and then actual SVG / XML ...
;;
;; The declarative nature has several benefits:
;;
;; - place multiple data series w/ potentially different layout methods
;; into same visualization
;; - create template/preset specs (e.g. pre-styled, only inject new data
;; points)
;; - easy to integrate in central state atom pattern, compatible w/
Om / Reagent based setups
;; - support multiple output targets from the same visualization spec
;;
;; Apart from SVG (the only target supported at the moment), this
module also aims to support OpenGL / WebGL scenegraph generation
;; and scene exports for rendering visualizations
;; with .
;;
;; Visualization spec format
;;
;; The main configuration map should have at least the following keys,
;; common to all supported visualization methods. Visualizations are
;; created by taking a series of data points and mapping them from
;; their source `:domain` into new coordinate system (`:range`).
;; Furthermore, this target coordinate system itself can be
;; transformed via projections, e.g. to translate from cartesian into
polar coordinates ( e.g. see Radar plot and other polar examples
;; above).
;;
;; | *Key* | *Value* | *Required* | *Description* |
;; |-----------+--------------------------+------------+-------------------------------------------|
;; | `:x-axis` | horizontal axis spec map | Y | X-axis behavior & representation details |
;; | `:y-axis` | vertical axis spec map | Y | Y-axis behavior & representation details |
;; | `:grid` | grid spec map | N | Optional background axis grid |
;; | `:data` | vector of dataset specs | Y | Allows multiple datasets in visualization |
;;
;; The following options are only used for visualizations using
;; `svg-plot2d-polar`:
;;
;; | *Key* | *Value* | *Required* | *Description* |
;; |-----------+-------------------------+------------+--------------------------------------------------------------------------------------|
| ` : origin ` | 2D vector , e.g. =[ x y]= | Y | Center pos of radial layout , only required for polar projection |
| ` : circle ` | boolean | N | true if axis & grid should be using full circles , only required for polar projection |
;;
;; Axis definitions (:x-axis / :y-axis)
;;
Axis specs are usually created via one of the available axis
;; generator functions (`linear-axis`, `log-axis`, `lens-axis`). These
;; functions too take a map w/ some of the same keys, but replace some
;; vals with transformed data and autofill default values for others.
;;
;; | *Key* | *Value* | *Required* | *Default* | *Description* |
|----------------+----------------------+------------+----------------------------------------+--------------------------------------------------------------------------|
;; | `:scale` | scale function | Y | nil | Scale function to translate domain values into visualization coordinates |
;; | `:domain` | vec of domain bounds | Y | nil | Lower & upper bound of data source interval |
;; | `:range` | vec of range bounds | Y | nil | Lower & upper bound of projected coordinates |
;; | `:pos` | number | Y | nil | Draw position of the axis (ypos for X-axis, xpos for Y-axis) |
;; | `:major` | seq of domain values | N | nil | Seq of domain positions at which to draw labeled tick marks |
;; | `:minor` | seq of domain values | N | nil | Seq of domain positions at which to draw minor tick marks |
| ` : major - size ` | number | N | 10 | Length of major tick marks |
;; | `:minor-size` | number | N | 5 | Length of minor tick marks |
;; | `:label` | function | N | =(default-svg-label (value-format 2))= | Function to format & emit tick labels |
;; | `:label-dist` | number | N | 10 + major-size | Distance of value labels from axis |
;; | `:label-style` | map | N | see next section | Style attribute map for value labels |
;; | `:label-y` | number | N | 0 | Vertical offset for Y-axis labels |
| ` : attribs ` | map | N | = { : stroke " black"}= | Axis line attribs attributes |
;; | `:visible` | boolean | N | true | Flag if axis will be visible in visualization |
;;
About tick marks
;;
;; The `linear-axis` & `lens-axis` interpret the given `:major` and
;; `:minor` values as the intended step distance between ticks and
;; generate ticks at multiples of the given value.
;;
;; The `log-axis` generator auto-creates ticks based on the `:base` of
;; the logarithm.
;;
;; Notes for polar projection
;;
;; - the `:range` interval of the x-axis must be an angle interval in radians (see above example)
;; - the `:range` interval of the y-axis must be a radius interval
;;
;; Same goes for `:pos` values: The `:pos` for x-axis is a radius, the
;; `:pos` for y-axis is an angle in radians
;;
;; Default axis label styling
;;
;; For SVG export, each axis is exported as its own group (incl. tick
;; marks & labels). By default the following label style is applied to
;; each group, however this can be overridden for individual labels by
;; specifying a custom `:label` function.
;;
;; ```
;; {:fill "black"
;; :stroke "none"
: font - family " Arial , sans - serif "
: font - size 10
;; :text-anchor "middle"}
;; ```
;;
;; *** Axis grid definition (:grid)
;;
;; *Note:* If no `:grid` spec is given in the main spec, no background
;; *grid will be displayed. If the axis is not `:visible`, the grid
;; *will still be displayed as long as either `:major` or `:minor`
;; *ticks are defined in the axis spec.
;;
;; | *Key* | *Value* | *Required* | *Default* | *Description* |
|------------+---------+------------+-----------------+----------------------------------------------------------|
| ` : attribs ` | hashmap | N | default attribs | allows extra attributes to be injected ( e.g. for SVG ) |
;; | `:minor-x` | boolean | N | false | if `false` only uses major tick mark positions on X axis |
;; | `:minor-y` | boolean | N | false | if `false` only uses major tick mark positions on Y axis |
;;
Dataset specs (: data )
;;
;; The format of these maps is largely dependent on the concrete
;; visualization methods used, but most have the following keys in
;; common:
;;
;; | *Key* | *Required* | *Default* | *Description* |
;; |-------------+------------+------------+----------------------------------------------------------------|
;; | `:layout` | Y | nil | Layout function to map data points |
;; | `:values` | Y | nil | Data points to be mapped |
| ` : attribs ` | N | nil | Styling & other attributes to attach to surrounding group node |
| ` : item - pos ` | N | ` identity ` | Function returning domain position of single data point |
;;
;; The `:item-pos` key is only needed if the data items are in a
;; non-standard format. By the default most layout functions expect
the data points to be a 2 - element vector ` [ domain - pos value ] ` .
;; Using an `:item-pos` lookup fn however, data items can be supplied
;; in other form (eg. as maps). Also see examples above...
;;
;; Scales
;;
;; Scaling functions merely provide a means to map values from a source
;; interval (domain) to a target interval (range). The latter usually
;; represents values in the visualization space (e.g. partial screen
;; coordinates).
;;
;; These functions can be useful also outside a visualization
;; context, but here are used in conjunction with their related axis
;; definition functions described below. When creating visualizations,
;; we would not usually use these scaling functions directly, but use
;; them implicitly via our defined axis specs.
;; Value transformations
(defn value-mapper
[scale-x scale-y] (fn [[x y]] [(scale-x x) (scale-y y)]))
(defn value-transducer
[{:keys [cull-domain cull-range scale-x scale-y project shape item-pos]}]
(let [mapper (value-mapper scale-x scale-y)
item-pos (or item-pos identity)]
(cond-> (map (juxt item-pos identity))
cull-domain (comp (filter #(m/in-range? cull-domain (ffirst %))))
:always (comp (map (fn [[p i]] [(mapper p) i])))
cull-range (comp (filter #(m/in-range? cull-range (peek (first %)))))
project (comp (map (fn [[p i]] [(project p) i])))
shape (comp (map shape)))))
(defn process-points
[{:keys [x-axis y-axis project]} {:keys [values item-pos shape]}]
(let [[ry1 ry2] (:range y-axis)]
(->> (if item-pos
(sort-by (comp first item-pos) values)
(sort-by first values))
(sequence
(value-transducer
{:cull-domain (:domain x-axis)
:cull-range (if (< ry1 ry2) [ry1 ry2] [ry2 ry1])
:item-pos item-pos
:scale-x (:scale x-axis)
:scale-y (:scale y-axis)
:project project
:shape shape})))))
(defn points->path-segments
[[p & more]]
(->> more
(reduce #(conj! % [:L %2]) (transient [[:M p]]))
persistent!))
;; Projections
(defn polar-projection
[origin]
(let [o (vec2 origin)]
(fn [[x y]] (m/+ o (g/as-cartesian (vec2 y x))))))
;; Value formatting
(defn value-formatter
[prec]
(let [fmt [(f/float prec)]]
(fn [x] (f/format fmt x))))
(defn format-percent
[x] (str (int (* x 100)) "%"))
(defn default-svg-label
[f] (fn [p x] (svg/text p (f x))))
;; Domain analysis ops
;;
;; Raw values to domain point conversion
;;
;; Most of the visualization methods in this module expect a seq of
;; data points in the format: `[domain-position value]`. The function
;; `uniform-domain-points` is useful to convert a sequence of pure
;; values (without position) into a seq of uniformly spaced data
;; points along the full breadth of the given domain:
(defn uniform-domain-points
"Given a vector of domain bounds and a collection of data values
(without domain position), produces a lazy-seq of 2-element vectors
representing the values of the original coll uniformly spread over
the full domain range, with each of the form: [domain-pos value]."
[[d1 d2] values]
(map
(fn [t v] [(m/mix* d1 d2 t) v])
(m/norm-range (dec (count values)))
values))
;; Domain bounds
(def domain-bounds-x #(gu/axis-bounds 0 %))
(def domain-bounds-y #(gu/axis-bounds 1 %))
(def domain-bounds-z #(gu/axis-bounds 2 %))
(defn total-domain-bounds
[f & colls]
(transduce
(map f)
(completing (fn [[aa ab] [xa xb]] [(min aa xa) (max ab xb)]))
[m/INF+ m/INF-] colls))
;; Matrix value domain
(defn value-domain-bounds
[mat]
(let [vals (seq mat)]
[(reduce min vals) (reduce max vals)]))
Linear scaling
(defn linear-scale
[domain range]
(fn [x] (m/map-interval x domain range)))
;; Logorithmic scaling
(defn log
[base]
(let [lb (Math/log base)]
#(/ (cond
(pos? %) (Math/log %)
(neg? %) (- (Math/log (- %)))
:else 0)
lb)))
(defn log-scale
[base [d1 d2 :as domain] [r1 r2 :as range]]
(let [log* (log base)
d1l (log* d1)
dr (- (log* d2) d1l)]
(fn [x] (m/mix* r1 r2 (/ (- (log* x) d1l) dr)))))
;; Lens scale (dilating / bundling)
;;
;; The =lens-scale= defines a non-linear mapping by specifying a focal
;; position in the domain interval, as well as a lens strength which
;; controls the compression or expansion of the domain space around
;; this focal point. If strength is positive, the lens is dilating. If
negative , it is bundling ( compressing ) . A strength of zero causes a
;; normal/linear scaling behavior.
;;
The two animations below show the effect of individually adjusting
;; the focus and lens strength:
;;
;; -focus-2.gif
Focus shift , constant strength = 0.5
;;
;; -strength-4.gif
Lens strength adjustment , constant focus = 0.0
(defn lens-scale
[focus strength [d1 d2] [r1 r2]]
(let [dr (- d2 d1)
f (/ (- focus d1) dr)]
(fn [x] (m/mix-lens r1 r2 (/ (- x d1) dr) f strength))))
Axis & tick generators
;; Common axis factory
(defn axis-common*
[{:keys [visible major-size minor-size label attribs label-style label-dist]
:or {visible true major-size 10, minor-size 5}
:as spec}]
(assoc spec
:visible visible
:major-size major-size
:minor-size minor-size
:label (or label (default-svg-label (value-formatter 2)))
:attribs (merge
{:stroke "black"}
attribs)
:label-style (merge
{:fill "black"
:stroke "none"
:font-family "Arial, sans-serif"
:font-size 10
:text-anchor "middle"}
label-style)
:label-dist (or label-dist (+ 10 major-size))))
Linear
(defn lin-tick-marks
[[d1 d2] delta]
(if (m/delta= delta 0.0 m/*eps*)
'()
(let [dr (- d2 d1)
d1' (m/roundto d1 delta)]
(filter #(m/in-range? d1 d2 %) (range d1' (+ d2 delta) delta)))))
(defn linear-axis
[{:keys [domain range major minor] :as spec}]
(let [major' (if major (lin-tick-marks domain major))
minor' (if minor (lin-tick-marks domain minor))
minor' (if (and major' minor')
(filter (complement (set major')) minor')
minor')]
(-> spec
(assoc
:scale (linear-scale domain range)
:major major'
:minor minor')
(axis-common*))))
;; Logarithmic
(defn log-ticks-domain
[base d1 d2]
(let [log* (log base)] [(m/floor (log* d1)) (m/ceil (log* d2))]))
(defn log-tick-marks-major
[base [d1 d2]]
(let [[d1l d2l] (log-ticks-domain base d1 d2)]
(->> (for [i (range d1l (inc d2l))]
(if (>= i 0)
(* (/ 1 base) (Math/pow base i))
(* (/ 1 base) (- (Math/pow base (- i))))))
(filter #(m/in-range? d1 d2 %)))))
(defn log-tick-marks-minor
[base [d1 d2]]
(let [[d1l d2l] (log-ticks-domain base d1 d2)
ticks (if (== 2 base) [0.75] (range 2 base))]
(->> (for [i (range d1l (inc d2l)) j ticks]
(if (>= i 0)
(* (/ j base) (Math/pow base i))
(* (/ j base) (- (Math/pow base (- i))))))
(filter #(m/in-range? d1 d2 %)))))
(defn log-axis
[{:keys [base domain range] :or {base 10} :as spec}]
(-> spec
(assoc
:scale (log-scale base domain range)
:major (log-tick-marks-major base domain)
:minor (log-tick-marks-minor base domain))
(axis-common*)))
Lens axis
;;
The lens axis is a modified ` linear - axis ` with two additional
;; required attributes to control the domain space deformation in
;; order to compress or expand the space around a given focal point
;; and therefore introduce a non-linear arrangement. See `lens-scale`
;; above for further details.
;;
;; - `:focus` - the domain value acting as lens focus
;; (by default the center of the domain is used)
;; - `:strength` - the lens strength & direction
( normalized values -1.0 ... + 1.0 , default = 0.5 )
(defn lens-axis
[{:keys [domain range focus strength major minor]
:or {strength 0.5} :as spec}]
(let [major' (if major (lin-tick-marks domain major))
minor' (if minor (lin-tick-marks domain minor))
minor' (if (and major' minor')
(filter (complement (set major')) minor')
minor')
focus (or focus (/ (apply + domain) 2.0))]
(-> spec
(assoc
:scale (lens-scale focus strength domain range)
:major major'
:minor minor'
:focus focus
:strength strength)
(axis-common*))))
;; Custom shapes
;; Some preset shape functions for use with scatter plots
(defn svg-triangle-up
[w]
(let [h (* w (Math/sin m/THIRD_PI))
w (* 0.5 w)]
(fn [[[x y]]] (svg/polygon [[(- x w) (+ y h)] [(+ x w) (+ y h)] [x y]]))))
(defn svg-triangle-down
[w]
(let [h (* w (Math/sin m/THIRD_PI))
w (* 0.5 w)]
(fn [[[x y]]] (svg/polygon [[(- x w) (- y h)] [(+ x w) (- y h)] [x y]]))))
(defn svg-square
[r] (let [d (* r 2.0)] (fn [[[x y]]] (svg/rect (vec2 (- x r) (- y r)) d d))))
(defn labeled-rect-horizontal
[{:keys [h r label fill min-width base-line]}]
(let [r2 (* -2 r)
h2 (* 0.5 h)]
(fn [[[ax ay :as a] [bx :as b] item]]
(svg/group
{}
(svg/rect
(vec2 (- ax r) (- ay h2)) (- bx ax r2) h
{:fill (fill item) :rx r :ry r})
(if (< min-width (- bx ax))
(svg/text (vec2 ax (+ base-line ay)) (label item)))))))
(defn circle-cell
[a b c d col]
(svg/circle (gu/centroid [a b c d]) (* 0.5 (g/dist a b)) {:fill col}))
;; Axial visualization methods
;;
;; This section defines the various layout/plotting methods, each with
;; a brief description and lists of custom `:data` spec options. See
the " Dataset specs " section and examples above for details about
;; other (required) keys...
;; Line plot
;;
;; This method simply represents the mapped values as a single
;; line-strip (polyline). Values are automatically sorted by domain
;; position, so can be initially unordered.
(defn svg-line-plot
[v-spec d-spec]
(svg/line-strip (map first (process-points v-spec d-spec)) (:attribs d-spec)))
;; Area plot
;;
;; Similar to the line plot method above, however resulting points are
represented as closed polygon ( and hence an ` : attribs ` key should
;; be supplied w/ a `:fill` color).
;;
;; *Note:* When using polar coordinate mapping (via
;; `svg-plot2d-polar`), a `:res` option should be given too in order
;; to create an arc approximation closing the polygon along the X-axis
( e.g. ` : res 20 ` ) .
;;
;; | *Key* | *Required* | *Default* | *Description* |
;; |--------+------------+-----------+-----------------------------------------------------|
| ` : res ` | N | 1 | Number of points used to close polygon along X - axis |
(defn svg-area-plot
[{:keys [y-axis project] :as v-spec} {:keys [res] :as d-spec}]
(let [ry1 (first (:range y-axis))
points (mapv first (process-points (assoc v-spec :project vec2) d-spec))
p (vec2 (first (peek points)) ry1)
q (vec2 (ffirst points) ry1)
points (concat points (mapv (partial m/mix p q) (m/norm-range (or res 1))))]
(svg/polygon (mapv project points) (:attribs d-spec))))
Radar plot
;;
;; This plot method is intended to be only used with `svg-plot2d-polar`.
;;
;; | *Key* | *Required* | *Default* | *Description* |
;; |----------+------------+-------------+------------------------------------------------------|
;; | `:shape` | N | svg/polygon | Shape function receiving seq of all points & attribs |
(defn svg-radar-plot
[v-spec {:keys [shape] :or {shape svg/polygon} :as d-spec}]
(shape (mapv first (process-points v-spec d-spec)) (:attribs d-spec)))
radar plot
;;
;; This version of the radar plot expects a min/max interval for each
data item . For example a single data point of ` [ 2 0.25 0.75 ] ` would
define a domain position at x=2 and an interval of 0.25 - 0.75 . If no
` : item - pos- * ` options are supplied this 3 - element vector format is
;; assumed for each data point.
;;
;; | *Key* | *Required* | *Default* | *Description* |
;; |-----------------+------------+-----------+------------------------------------------------------------------|
;; | `:item-pos-min` | N | `[x min]` | Function to provide min. data point |
| ` : item - pos - max ` | N | ` [ x max ] ` | Function to provide . data point |
| ` : shape ` | N | svg / path | Shape function receiving seq of outer & inner points and attribs |
(defn svg-radar-plot-minmax
[v-spec
{:keys [item-pos-min item-pos-max shape]
:or {shape #(svg/path (concat % [[:Z]] %2 [[:Z]]) %3)}
:as d-spec}]
(let [min-points (->> (assoc d-spec :item-pos (or item-pos-min (fn [i] (take 2 i))))
(process-points v-spec)
(mapv first)
(points->path-segments))
max-points (->> (assoc d-spec :item-pos (or item-pos-max (fn [i] [(first i) (nth i 2)])))
(process-points v-spec)
(mapv first)
(points->path-segments))]
(shape max-points min-points (assoc (:attribs d-spec) :fill-rule "evenodd"))))
;; Scatter plot
;;
;; | *Key* | *Required* | *Default* | *Description* |
;; |----------+------------+-----------+--------------------------------------------------------|
;; | `:shape` | N | `circle` | Function returning shape primitive for each data point |
(defn svg-scatter-plot
[v-spec {:keys [attribs shape] :as d-spec}]
(->> (assoc d-spec :shape (or shape (fn [[p]] (svg/circle p 3))))
(process-points v-spec)
(apply svg/group attribs)))
;; Bar plot
;;
;; | *Key* | *Required* | *Default* | *Description* |
;; |---------------+------------+------------+---------------------------------------------------------|
;; | `:item-pos` | N | `identity` | Function returning domain position of single data point |
;; | `:shape` | N | `line` | Function returning shape primitive for each data point |
;; | `:interleave` | N | 1 | Number of bars per domain position |
;; | `:offset` | N | 0 | Only used for interleaved bars, index position |
;; | `:bar-width` | N | 0 | Only used for interleaved bars, width of single bar |
;; | `:shape` | Y | svg/line | Function returning shape primitive for each data point |
(defn svg-bar-plot
[{:keys [x-axis y-axis project] :or {project vec2}}
{:keys [values attribs shape item-pos interleave offset bar-width]
:or {shape (fn [a b _] (svg/line a b))
item-pos identity
interleave 1
bar-width 0
offset 0}}]
(let [domain (:domain x-axis)
base-y ((:scale y-axis) (first (:domain y-axis)))
mapper (value-mapper (:scale x-axis) (:scale y-axis))
offset (+ (* -0.5 (* interleave bar-width)) (* (+ offset 0.5) bar-width))]
(->> values
(sequence
(comp
(map (juxt item-pos identity))
(filter #(m/in-range? domain (ffirst %)))
(map
(fn [[p i]]
(let [[ax ay] (mapper p)
ax (+ ax offset)]
(shape (project [ax ay]) (project [ax base-y]) i))))))
(apply svg/group attribs))))
Heatmap
;;
;; | *Key* | *Required* | *Default* | *Description* |
;; |------------------+------------+--------------+----------------------------------------------------|
| ` : matrix ` | Y | nil | NDArray instance of data grid |
;; | `:palette` | Y | nil | Color list |
;; | `:palette-scale` | N | linear-scale | Mapping function of matrix values to palette index |
;; | `:value-domain` | N | [0 1] | Domain interval of matrix values |
;; | `:clamp` | N | false | If true, matrix values are clamped to value domain |
;;
;; *Note:* If `:clamp` is not enabled, the `:value-domain` acts as
;; filter and will not include cells with values outside the domain,
;; resulting in holes in the visualization. On the other hand, if
;; `:clamp` is enabled, the `:value-domain` acts as a kind of
;; amplification or compression function.
(defn svg-heatmap
[{:keys [x-axis y-axis project]}
{:keys [matrix value-domain clamp palette palette-scale attribs shape]
:or {value-domain [0.0 1.0]
palette-scale linear-scale
shape #(svg/polygon [%1 %2 %3 %4] {:fill %5})}
:as d-spec}]
(let [scale-x (:scale x-axis)
scale-y (:scale y-axis)
pmax (dec (count palette))
scale-v (palette-scale value-domain [0 pmax])]
(apply svg/group
attribs
(for [p (nd/position-seq matrix)
:let [[y x] p
v (nd/get-at matrix y x)]
:when (or clamp (m/in-range? value-domain v))]
(shape
(project [(scale-x x) (scale-y y)])
(project [(scale-x (inc x)) (scale-y y)])
(project [(scale-x (inc x)) (scale-y (inc y))])
(project [(scale-x x) (scale-y (inc y))])
(palette (m/clamp (int (scale-v v)) 0 pmax)))))))
Contour lines
;;
Given a 2D matrix ( a ` thi.ng.ndarray.core . NDArray ` instance ) of data
;; values and a seq of thresholds, this function computes number of
;; polygons for each threshold level.
;;
;; *Note:* Since the data format for this method is different to the
;; other layouts, we're using the `:matrix` key instead of `:values` to
;; emphasize this difference...
;;
;; | *Key* | *Required* | *Default* | *Description* |
;; |--------------------+------------+--------------+----------------------------------------------------------------|
| ` : matrix ` | Y | nil | NDArray instance of data grid |
;; | `:levels` | Y | nil | Seq of threshold values to find contours for |
;; | `:palette` | Y | nil | Color list |
;; | `:palette-scale` | N | linear-scale | Mapping function of matrix values to palette index |
;; | `:value-domain` | N | [0 1] | Domain interval of matrix values |
;; | `:contour-attribs` | N | nil | Function to produce shape attribs map for each threshold level |
(defn matrix-2d
[w h values] (nd/ndarray :float32 values [h w]))
(defn contour-matrix
[w h values]
(contours/set-border-2d (matrix-2d w h values) -1e9))
(defn contour->svg
[scale-x scale-y project]
(fn [attribs contour]
(let [contour (map (fn [[y x]] [(scale-x x) (scale-y y)]) contour)]
(svg/polygon (map project contour) attribs))))
(defn svg-contour-plot
[{:keys [x-axis y-axis project]}
{:keys [matrix attribs levels palette palette-scale value-domain contour-attribs]
:or {value-domain [0.0 1.0]
palette [[1 1 1]]
palette-scale linear-scale
contour-attribs (constantly nil)}}]
(let [pmax (dec (count palette))
scale-v (palette-scale value-domain [0 pmax])
contour-fn (contour->svg (:scale x-axis) (:scale y-axis) project)]
(->> levels
(sort)
(mapv
(fn [iso]
(let [c-attribs (contour-attribs (palette (m/clamp (int (scale-v iso)) 0 pmax)))]
(apply svg/group
{} (mapv
(partial contour-fn c-attribs)
(contours/find-contours-2d matrix iso))))))
(apply svg/group attribs))))
;; Stacked intervals
;;
;; | *Key* | *Required* | *Default* | *Description* |
|---------------+------------+------------+-------------------------------------------------------|
;; | `:item-range` | N | `identity` | Function returning domain interval for each data item |
;; | `:offset` | N | 0 | Y-axis offset for this data series |
;; | `:shape` | N | `svg/line` | Function returning shape primitive for each data item |
(defn overlap? [[a b] [c d]] (and (<= a d) (>= b c)))
(defn compute-row-stacking
[item-range coll]
(reduce
(fn [grid x]
(let [r (item-range x)]
(loop [[row & more] grid idx 0]
(if (or (nil? row) (not (some #(overlap? r (item-range %)) row)))
(update-in grid [idx] #(conj (or % []) x))
(recur more (inc idx))))))
[] coll))
(defn process-interval-row
[item-range mapper [d1 d2]]
(fn [i row]
(map
(fn [item]
(let [[a b] (item-range item)]
[(mapper [(max d1 a) i]) (mapper [(min d2 b) i]) item]))
row)))
(defn svg-stacked-interval-plot
[{:keys [x-axis y-axis]}
{:keys [values attribs shape item-range offset]
:or {shape (fn [[a b]] (svg/line (vec2 a) (vec2 b)))
item-range identity
offset 0}}]
(let [scale-x (:scale x-axis)
scale-y (:scale y-axis)
domain (:domain x-axis)
mapper (value-mapper scale-x scale-y)]
(->> values
(filter #(overlap? domain (item-range %)))
(sort-by (comp first item-range))
(compute-row-stacking item-range)
(mapcat (process-interval-row item-range mapper domain) (range offset 1e6))
(mapv shape)
(apply svg/group attribs))))
;; 2D Cartesian Plotting (SVG)
;; SVG axis generators
(defn svg-axis*
[{:keys [major minor attribs label-style]} axis tick1-fn tick2-fn label-fn]
(svg/group
(merge {:stroke "#000"} attribs)
(seq (map tick1-fn major))
(seq (map tick2-fn minor))
(apply svg/group (merge {:stroke "none"} label-style) (mapv label-fn major))
axis))
(defn svg-x-axis-cartesian
[{:keys [scale major-size minor-size label-dist pos label] [r1 r2] :range
:as spec}]
(let [y-major (+ pos major-size)
y-minor (+ pos minor-size)
y-label (+ pos label-dist)]
(svg-axis*
spec (svg/line (vec2 r1 pos) (vec2 r2 pos))
#(let [x (scale %)] (svg/line (vec2 x pos) (vec2 x y-major)))
#(let [x (scale %)] (svg/line (vec2 x pos) (vec2 x y-minor)))
#(label (vec2 (scale %) y-label) %))))
(defn svg-y-axis-cartesian
[{:keys [scale major-size minor-size label-dist label-y pos label] [r1 r2] :range
:or {label-y 0}
:as spec}]
(let [x-major (- pos major-size)
x-minor (- pos minor-size)
x-label (- pos label-dist)]
(svg-axis*
spec (svg/line (vec2 pos r1) (vec2 pos r2))
#(let [y (scale %)] (svg/line (vec2 pos y) (vec2 x-major y)))
#(let [y (scale %)] (svg/line (vec2 pos y) (vec2 x-minor y)))
#(label (vec2 x-label (+ (scale %) label-y)) %))))
Generic plotting helpers
(defn select-ticks
[axis minor?] (if minor? (concat (:minor axis) (:major axis)) (:major axis)))
(defn svg-axis-grid2d-cartesian
[x-axis y-axis {:keys [attribs minor-x minor-y]}]
(let [[x1 x2] (:range x-axis)
[y1 y2] (:range y-axis)
scale-x (:scale x-axis)
scale-y (:scale y-axis)]
(svg/group
(merge {:stroke "#ccc" :stroke-dasharray "1 1"} attribs)
(if (or (:major x-axis) (:minor x-axis))
(map #(let [x (scale-x %)] (svg/line (vec2 x y1) (vec2 x y2))) (select-ticks x-axis minor-x)))
(if (or (:major y-axis) (:minor y-axis))
(map #(let [y (scale-y %)] (svg/line (vec2 x1 y) (vec2 x2 y))) (select-ticks y-axis minor-y))))))
(defn svg-plot2d-cartesian
[{:keys [x-axis y-axis grid data] :as opts}]
(let [opts (assoc opts :project vec2)]
(svg/group
{}
(if grid (svg-axis-grid2d-cartesian x-axis y-axis grid))
(map (fn [spec] ((:layout spec) opts spec)) data)
(if (:visible x-axis) (svg-x-axis-cartesian x-axis))
(if (:visible y-axis) (svg-y-axis-cartesian y-axis)))))
;; 2D Polar Plotting (SVG)
;; SVG axis generators
(defn svg-x-axis-polar
[{:keys [x-axis project circle origin]}]
(let [{:keys [scale major-size minor-size label-dist pos]} x-axis
label (or (:label x-axis) (default-svg-label (value-formatter 2)))
[r1 r2] (:range x-axis)
o origin]
(svg-axis*
x-axis
(if circle
(svg/circle o pos {:fill "none"})
(svg/arc o pos r1 r2 (> (m/abs-diff r1 r2) m/PI) true {:fill "none"}))
#(let [x (scale %)]
(svg/line (project [x pos]) (project [x (+ pos major-size)])))
#(let [x (scale %)]
(svg/line (project [x pos]) (project [x (+ pos minor-size)])))
#(let [x (scale %)]
(label (project [x (+ pos label-dist)]) %)))))
(defn svg-y-axis-polar
[{:keys [y-axis project]}]
(let [{:keys [scale label-y pos] :or {label-y 0}} y-axis
label (or (:label y-axis) (default-svg-label (value-formatter 2)))
[r1 r2] (:range y-axis)
a (project [pos r1])
b (project [pos r2])
nl (m/normalize (g/normal (m/- a b)) (:label-dist y-axis))
n1 (m/normalize nl (:major-size y-axis))
n2 (m/normalize nl (:minor-size y-axis))]
(svg-axis*
y-axis
(svg/line a b)
#(let [p (project [pos (scale %)])]
(svg/line p (m/+ p n1)))
#(let [p (project [pos (scale %)])]
(svg/line p (m/+ p n2)))
#(let [p (project [pos (+ (scale %) label-y)])]
(label (m/+ p nl) %)))))
(defn svg-axis-grid2d-polar
[{:keys [x-axis y-axis origin circle project] {:keys [attribs minor-x minor-y]} :grid}]
(let [[x1 x2] (:range x-axis)
[y1 y2] (:range y-axis)
scale-x (:scale x-axis)
scale-y (:scale y-axis)
great? (> (m/abs-diff x1 x2) m/PI)]
(svg/group
(merge {:stroke "#ccc" :stroke-dasharray "1 1"} attribs)
(if (or (:major x-axis) (:minor x-axis))
(map
#(let [x (scale-x %)] (svg/line (project [x y1]) (project [x y2])))
(select-ticks x-axis minor-x)))
(if (or (:major y-axis) (:minor y-axis))
(map
#(let [y (scale-y %)]
(if circle
(svg/circle origin y {:fill "none"})
(svg/arc origin y x1 x2 great? true {:fill "none"})))
(select-ticks y-axis minor-y))))))
(defn svg-plot2d-polar
[{:keys [x-axis y-axis grid data origin] :as spec}]
(let [spec (assoc spec :project (polar-projection origin))]
(svg/group
{}
(if grid (svg-axis-grid2d-polar spec))
(map (fn [spec'] ((:layout spec') spec spec')) data)
(if (:visible x-axis) (svg-x-axis-polar spec))
(if (:visible y-axis) (svg-y-axis-polar spec)))))
;; (currently unused) date & time helpers
(comment
(defn clear-day-of-week [^GregorianCalendar cal] (.set cal Calendar/DAY_OF_WEEK 1) (clear-hour cal))
(defn clear-month [^GregorianCalendar cal] (.set cal Calendar/MONTH 0) (clear-day-of-month cal))
(defn year [^GregorianCalendar cal] (.get cal Calendar/YEAR))
(defn month [^GregorianCalendar cal] (.get cal Calendar/MONTH))
(defn day-of-month [^GregorianCalendar cal] (.get cal Calendar/DAY_OF_MONTH))
(defn day-of-week [^GregorianCalendar cal] (.get cal Calendar/DAY_OF_WEEK))
(defn hour [^GregorianCalendar cal] (.get cal Calendar/HOUR))
(defn minute [^GregorianCalendar cal] (.get cal Calendar/MINUTE))
(defn second [^GregorianCalendar cal] (.get cal Calendar/SECOND))
(defn round-to-year
[epoch]
(let [cal (epoch->cal epoch)]
(doto cal
(.add Calendar/MONTH 6)
(clear-month))))
(defn round-to-month
[epoch]
(doto (epoch->cal epoch)
(.setTimeInMillis (long epoch))
(.add Calendar/DAY_OF_MONTH 16)
(clear-day-of-month)))
(defn round-to-week
[epoch]
(doto (epoch->cal epoch)
(.setTimeInMillis (long epoch))
(.add Calendar/DAY_OF_WEEK 4)
(clear-day-of-week)))
(defn round-to-day-of-month
[epoch]
(doto (epoch->cal epoch)
(.add Calendar/HOUR 12)
(clear-hour)))
(defn round-to-day-of-week
[epoch]
(doto (epoch->cal epoch)
(.add Calendar/HOUR 12)
(clear-hour)))
(defn round-to-hour
[epoch]
(doto (epoch->cal epoch)
(.add Calendar/MINUTE 30)
(clear-minute)))
)
| null | https://raw.githubusercontent.com/thi-ng/geom/85783a1f87670c5821473298fa0b491bd40c3028/src/thi/ng/geom/viz/core.cljc | clojure | This module currently consists of this single namespace dedicated
to creating 2D (and soon 3D too) data visualizations in an output
format agnostic way. To achieve that, an overall declarative and
pipelined approach has been taken to create these visualizations:
axis definitions, layout arguments/handlers, styling options etc.
primitives (shapes & groups) representing the visualization.
The declarative nature has several benefits:
- place multiple data series w/ potentially different layout methods
into same visualization
- create template/preset specs (e.g. pre-styled, only inject new data
points)
- easy to integrate in central state atom pattern, compatible w/
- support multiple output targets from the same visualization spec
Apart from SVG (the only target supported at the moment), this
and scene exports for rendering visualizations
with .
Visualization spec format
The main configuration map should have at least the following keys,
common to all supported visualization methods. Visualizations are
created by taking a series of data points and mapping them from
their source `:domain` into new coordinate system (`:range`).
Furthermore, this target coordinate system itself can be
transformed via projections, e.g. to translate from cartesian into
above).
| *Key* | *Value* | *Required* | *Description* |
|-----------+--------------------------+------------+-------------------------------------------|
| `:x-axis` | horizontal axis spec map | Y | X-axis behavior & representation details |
| `:y-axis` | vertical axis spec map | Y | Y-axis behavior & representation details |
| `:grid` | grid spec map | N | Optional background axis grid |
| `:data` | vector of dataset specs | Y | Allows multiple datasets in visualization |
The following options are only used for visualizations using
`svg-plot2d-polar`:
| *Key* | *Value* | *Required* | *Description* |
|-----------+-------------------------+------------+--------------------------------------------------------------------------------------|
Axis definitions (:x-axis / :y-axis)
generator functions (`linear-axis`, `log-axis`, `lens-axis`). These
functions too take a map w/ some of the same keys, but replace some
vals with transformed data and autofill default values for others.
| *Key* | *Value* | *Required* | *Default* | *Description* |
| `:scale` | scale function | Y | nil | Scale function to translate domain values into visualization coordinates |
| `:domain` | vec of domain bounds | Y | nil | Lower & upper bound of data source interval |
| `:range` | vec of range bounds | Y | nil | Lower & upper bound of projected coordinates |
| `:pos` | number | Y | nil | Draw position of the axis (ypos for X-axis, xpos for Y-axis) |
| `:major` | seq of domain values | N | nil | Seq of domain positions at which to draw labeled tick marks |
| `:minor` | seq of domain values | N | nil | Seq of domain positions at which to draw minor tick marks |
| `:minor-size` | number | N | 5 | Length of minor tick marks |
| `:label` | function | N | =(default-svg-label (value-format 2))= | Function to format & emit tick labels |
| `:label-dist` | number | N | 10 + major-size | Distance of value labels from axis |
| `:label-style` | map | N | see next section | Style attribute map for value labels |
| `:label-y` | number | N | 0 | Vertical offset for Y-axis labels |
| `:visible` | boolean | N | true | Flag if axis will be visible in visualization |
The `linear-axis` & `lens-axis` interpret the given `:major` and
`:minor` values as the intended step distance between ticks and
generate ticks at multiples of the given value.
The `log-axis` generator auto-creates ticks based on the `:base` of
the logarithm.
Notes for polar projection
- the `:range` interval of the x-axis must be an angle interval in radians (see above example)
- the `:range` interval of the y-axis must be a radius interval
Same goes for `:pos` values: The `:pos` for x-axis is a radius, the
`:pos` for y-axis is an angle in radians
Default axis label styling
For SVG export, each axis is exported as its own group (incl. tick
marks & labels). By default the following label style is applied to
each group, however this can be overridden for individual labels by
specifying a custom `:label` function.
```
{:fill "black"
:stroke "none"
:text-anchor "middle"}
```
*** Axis grid definition (:grid)
*Note:* If no `:grid` spec is given in the main spec, no background
*grid will be displayed. If the axis is not `:visible`, the grid
*will still be displayed as long as either `:major` or `:minor`
*ticks are defined in the axis spec.
| *Key* | *Value* | *Required* | *Default* | *Description* |
| `:minor-x` | boolean | N | false | if `false` only uses major tick mark positions on X axis |
| `:minor-y` | boolean | N | false | if `false` only uses major tick mark positions on Y axis |
The format of these maps is largely dependent on the concrete
visualization methods used, but most have the following keys in
common:
| *Key* | *Required* | *Default* | *Description* |
|-------------+------------+------------+----------------------------------------------------------------|
| `:layout` | Y | nil | Layout function to map data points |
| `:values` | Y | nil | Data points to be mapped |
The `:item-pos` key is only needed if the data items are in a
non-standard format. By the default most layout functions expect
Using an `:item-pos` lookup fn however, data items can be supplied
in other form (eg. as maps). Also see examples above...
Scales
Scaling functions merely provide a means to map values from a source
interval (domain) to a target interval (range). The latter usually
represents values in the visualization space (e.g. partial screen
coordinates).
These functions can be useful also outside a visualization
context, but here are used in conjunction with their related axis
definition functions described below. When creating visualizations,
we would not usually use these scaling functions directly, but use
them implicitly via our defined axis specs.
Value transformations
Projections
Value formatting
Domain analysis ops
Raw values to domain point conversion
Most of the visualization methods in this module expect a seq of
data points in the format: `[domain-position value]`. The function
`uniform-domain-points` is useful to convert a sequence of pure
values (without position) into a seq of uniformly spaced data
points along the full breadth of the given domain:
Domain bounds
Matrix value domain
Logorithmic scaling
Lens scale (dilating / bundling)
The =lens-scale= defines a non-linear mapping by specifying a focal
position in the domain interval, as well as a lens strength which
controls the compression or expansion of the domain space around
this focal point. If strength is positive, the lens is dilating. If
normal/linear scaling behavior.
the focus and lens strength:
-focus-2.gif
-strength-4.gif
Common axis factory
Logarithmic
required attributes to control the domain space deformation in
order to compress or expand the space around a given focal point
and therefore introduce a non-linear arrangement. See `lens-scale`
above for further details.
- `:focus` - the domain value acting as lens focus
(by default the center of the domain is used)
- `:strength` - the lens strength & direction
Custom shapes
Some preset shape functions for use with scatter plots
Axial visualization methods
This section defines the various layout/plotting methods, each with
a brief description and lists of custom `:data` spec options. See
other (required) keys...
Line plot
This method simply represents the mapped values as a single
line-strip (polyline). Values are automatically sorted by domain
position, so can be initially unordered.
Area plot
Similar to the line plot method above, however resulting points are
be supplied w/ a `:fill` color).
*Note:* When using polar coordinate mapping (via
`svg-plot2d-polar`), a `:res` option should be given too in order
to create an arc approximation closing the polygon along the X-axis
| *Key* | *Required* | *Default* | *Description* |
|--------+------------+-----------+-----------------------------------------------------|
This plot method is intended to be only used with `svg-plot2d-polar`.
| *Key* | *Required* | *Default* | *Description* |
|----------+------------+-------------+------------------------------------------------------|
| `:shape` | N | svg/polygon | Shape function receiving seq of all points & attribs |
This version of the radar plot expects a min/max interval for each
assumed for each data point.
| *Key* | *Required* | *Default* | *Description* |
|-----------------+------------+-----------+------------------------------------------------------------------|
| `:item-pos-min` | N | `[x min]` | Function to provide min. data point |
Scatter plot
| *Key* | *Required* | *Default* | *Description* |
|----------+------------+-----------+--------------------------------------------------------|
| `:shape` | N | `circle` | Function returning shape primitive for each data point |
Bar plot
| *Key* | *Required* | *Default* | *Description* |
|---------------+------------+------------+---------------------------------------------------------|
| `:item-pos` | N | `identity` | Function returning domain position of single data point |
| `:shape` | N | `line` | Function returning shape primitive for each data point |
| `:interleave` | N | 1 | Number of bars per domain position |
| `:offset` | N | 0 | Only used for interleaved bars, index position |
| `:bar-width` | N | 0 | Only used for interleaved bars, width of single bar |
| `:shape` | Y | svg/line | Function returning shape primitive for each data point |
| *Key* | *Required* | *Default* | *Description* |
|------------------+------------+--------------+----------------------------------------------------|
| `:palette` | Y | nil | Color list |
| `:palette-scale` | N | linear-scale | Mapping function of matrix values to palette index |
| `:value-domain` | N | [0 1] | Domain interval of matrix values |
| `:clamp` | N | false | If true, matrix values are clamped to value domain |
*Note:* If `:clamp` is not enabled, the `:value-domain` acts as
filter and will not include cells with values outside the domain,
resulting in holes in the visualization. On the other hand, if
`:clamp` is enabled, the `:value-domain` acts as a kind of
amplification or compression function.
values and a seq of thresholds, this function computes number of
polygons for each threshold level.
*Note:* Since the data format for this method is different to the
other layouts, we're using the `:matrix` key instead of `:values` to
emphasize this difference...
| *Key* | *Required* | *Default* | *Description* |
|--------------------+------------+--------------+----------------------------------------------------------------|
| `:levels` | Y | nil | Seq of threshold values to find contours for |
| `:palette` | Y | nil | Color list |
| `:palette-scale` | N | linear-scale | Mapping function of matrix values to palette index |
| `:value-domain` | N | [0 1] | Domain interval of matrix values |
| `:contour-attribs` | N | nil | Function to produce shape attribs map for each threshold level |
Stacked intervals
| *Key* | *Required* | *Default* | *Description* |
| `:item-range` | N | `identity` | Function returning domain interval for each data item |
| `:offset` | N | 0 | Y-axis offset for this data series |
| `:shape` | N | `svg/line` | Function returning shape primitive for each data item |
2D Cartesian Plotting (SVG)
SVG axis generators
2D Polar Plotting (SVG)
SVG axis generators
(currently unused) date & time helpers | (ns thi.ng.geom.viz.core
(:require
[thi.ng.geom.core :as g]
[thi.ng.geom.vector :as v :refer [vec2 vec3]]
[thi.ng.geom.utils :as gu]
[thi.ng.geom.svg.core :as svg]
[thi.ng.ndarray.core :as nd]
[thi.ng.ndarray.contours :as contours]
[thi.ng.math.core :as m]
[thi.ng.strf.core :as f]))
1 . We first define a configuration map , supplying all data points ,
2 . This map is then transformed into a tree / scenegraph of geometric
3 . This tree of still pure Clojure data is then further converted into
the final output format , e.g. for SVG first into
and then actual SVG / XML ...
Om / Reagent based setups
module also aims to support OpenGL / WebGL scenegraph generation
polar coordinates ( e.g. see Radar plot and other polar examples
| ` : origin ` | 2D vector , e.g. =[ x y]= | Y | Center pos of radial layout , only required for polar projection |
| ` : circle ` | boolean | N | true if axis & grid should be using full circles , only required for polar projection |
Axis specs are usually created via one of the available axis
|----------------+----------------------+------------+----------------------------------------+--------------------------------------------------------------------------|
| ` : major - size ` | number | N | 10 | Length of major tick marks |
| ` : attribs ` | map | N | = { : stroke " black"}= | Axis line attribs attributes |
About tick marks
: font - family " Arial , sans - serif "
: font - size 10
|------------+---------+------------+-----------------+----------------------------------------------------------|
| ` : attribs ` | hashmap | N | default attribs | allows extra attributes to be injected ( e.g. for SVG ) |
Dataset specs (: data )
| ` : attribs ` | N | nil | Styling & other attributes to attach to surrounding group node |
| ` : item - pos ` | N | ` identity ` | Function returning domain position of single data point |
the data points to be a 2 - element vector ` [ domain - pos value ] ` .
(defn value-mapper
[scale-x scale-y] (fn [[x y]] [(scale-x x) (scale-y y)]))
(defn value-transducer
[{:keys [cull-domain cull-range scale-x scale-y project shape item-pos]}]
(let [mapper (value-mapper scale-x scale-y)
item-pos (or item-pos identity)]
(cond-> (map (juxt item-pos identity))
cull-domain (comp (filter #(m/in-range? cull-domain (ffirst %))))
:always (comp (map (fn [[p i]] [(mapper p) i])))
cull-range (comp (filter #(m/in-range? cull-range (peek (first %)))))
project (comp (map (fn [[p i]] [(project p) i])))
shape (comp (map shape)))))
(defn process-points
[{:keys [x-axis y-axis project]} {:keys [values item-pos shape]}]
(let [[ry1 ry2] (:range y-axis)]
(->> (if item-pos
(sort-by (comp first item-pos) values)
(sort-by first values))
(sequence
(value-transducer
{:cull-domain (:domain x-axis)
:cull-range (if (< ry1 ry2) [ry1 ry2] [ry2 ry1])
:item-pos item-pos
:scale-x (:scale x-axis)
:scale-y (:scale y-axis)
:project project
:shape shape})))))
(defn points->path-segments
[[p & more]]
(->> more
(reduce #(conj! % [:L %2]) (transient [[:M p]]))
persistent!))
(defn polar-projection
[origin]
(let [o (vec2 origin)]
(fn [[x y]] (m/+ o (g/as-cartesian (vec2 y x))))))
(defn value-formatter
[prec]
(let [fmt [(f/float prec)]]
(fn [x] (f/format fmt x))))
(defn format-percent
[x] (str (int (* x 100)) "%"))
(defn default-svg-label
[f] (fn [p x] (svg/text p (f x))))
(defn uniform-domain-points
"Given a vector of domain bounds and a collection of data values
(without domain position), produces a lazy-seq of 2-element vectors
representing the values of the original coll uniformly spread over
the full domain range, with each of the form: [domain-pos value]."
[[d1 d2] values]
(map
(fn [t v] [(m/mix* d1 d2 t) v])
(m/norm-range (dec (count values)))
values))
(def domain-bounds-x #(gu/axis-bounds 0 %))
(def domain-bounds-y #(gu/axis-bounds 1 %))
(def domain-bounds-z #(gu/axis-bounds 2 %))
(defn total-domain-bounds
[f & colls]
(transduce
(map f)
(completing (fn [[aa ab] [xa xb]] [(min aa xa) (max ab xb)]))
[m/INF+ m/INF-] colls))
(defn value-domain-bounds
[mat]
(let [vals (seq mat)]
[(reduce min vals) (reduce max vals)]))
Linear scaling
(defn linear-scale
[domain range]
(fn [x] (m/map-interval x domain range)))
(defn log
[base]
(let [lb (Math/log base)]
#(/ (cond
(pos? %) (Math/log %)
(neg? %) (- (Math/log (- %)))
:else 0)
lb)))
(defn log-scale
[base [d1 d2 :as domain] [r1 r2 :as range]]
(let [log* (log base)
d1l (log* d1)
dr (- (log* d2) d1l)]
(fn [x] (m/mix* r1 r2 (/ (- (log* x) d1l) dr)))))
negative , it is bundling ( compressing ) . A strength of zero causes a
The two animations below show the effect of individually adjusting
Focus shift , constant strength = 0.5
Lens strength adjustment , constant focus = 0.0
(defn lens-scale
[focus strength [d1 d2] [r1 r2]]
(let [dr (- d2 d1)
f (/ (- focus d1) dr)]
(fn [x] (m/mix-lens r1 r2 (/ (- x d1) dr) f strength))))
Axis & tick generators
(defn axis-common*
[{:keys [visible major-size minor-size label attribs label-style label-dist]
:or {visible true major-size 10, minor-size 5}
:as spec}]
(assoc spec
:visible visible
:major-size major-size
:minor-size minor-size
:label (or label (default-svg-label (value-formatter 2)))
:attribs (merge
{:stroke "black"}
attribs)
:label-style (merge
{:fill "black"
:stroke "none"
:font-family "Arial, sans-serif"
:font-size 10
:text-anchor "middle"}
label-style)
:label-dist (or label-dist (+ 10 major-size))))
Linear
(defn lin-tick-marks
[[d1 d2] delta]
(if (m/delta= delta 0.0 m/*eps*)
'()
(let [dr (- d2 d1)
d1' (m/roundto d1 delta)]
(filter #(m/in-range? d1 d2 %) (range d1' (+ d2 delta) delta)))))
(defn linear-axis
[{:keys [domain range major minor] :as spec}]
(let [major' (if major (lin-tick-marks domain major))
minor' (if minor (lin-tick-marks domain minor))
minor' (if (and major' minor')
(filter (complement (set major')) minor')
minor')]
(-> spec
(assoc
:scale (linear-scale domain range)
:major major'
:minor minor')
(axis-common*))))
(defn log-ticks-domain
[base d1 d2]
(let [log* (log base)] [(m/floor (log* d1)) (m/ceil (log* d2))]))
(defn log-tick-marks-major
[base [d1 d2]]
(let [[d1l d2l] (log-ticks-domain base d1 d2)]
(->> (for [i (range d1l (inc d2l))]
(if (>= i 0)
(* (/ 1 base) (Math/pow base i))
(* (/ 1 base) (- (Math/pow base (- i))))))
(filter #(m/in-range? d1 d2 %)))))
(defn log-tick-marks-minor
[base [d1 d2]]
(let [[d1l d2l] (log-ticks-domain base d1 d2)
ticks (if (== 2 base) [0.75] (range 2 base))]
(->> (for [i (range d1l (inc d2l)) j ticks]
(if (>= i 0)
(* (/ j base) (Math/pow base i))
(* (/ j base) (- (Math/pow base (- i))))))
(filter #(m/in-range? d1 d2 %)))))
(defn log-axis
[{:keys [base domain range] :or {base 10} :as spec}]
(-> spec
(assoc
:scale (log-scale base domain range)
:major (log-tick-marks-major base domain)
:minor (log-tick-marks-minor base domain))
(axis-common*)))
Lens axis
The lens axis is a modified ` linear - axis ` with two additional
( normalized values -1.0 ... + 1.0 , default = 0.5 )
(defn lens-axis
[{:keys [domain range focus strength major minor]
:or {strength 0.5} :as spec}]
(let [major' (if major (lin-tick-marks domain major))
minor' (if minor (lin-tick-marks domain minor))
minor' (if (and major' minor')
(filter (complement (set major')) minor')
minor')
focus (or focus (/ (apply + domain) 2.0))]
(-> spec
(assoc
:scale (lens-scale focus strength domain range)
:major major'
:minor minor'
:focus focus
:strength strength)
(axis-common*))))
(defn svg-triangle-up
[w]
(let [h (* w (Math/sin m/THIRD_PI))
w (* 0.5 w)]
(fn [[[x y]]] (svg/polygon [[(- x w) (+ y h)] [(+ x w) (+ y h)] [x y]]))))
(defn svg-triangle-down
[w]
(let [h (* w (Math/sin m/THIRD_PI))
w (* 0.5 w)]
(fn [[[x y]]] (svg/polygon [[(- x w) (- y h)] [(+ x w) (- y h)] [x y]]))))
(defn svg-square
[r] (let [d (* r 2.0)] (fn [[[x y]]] (svg/rect (vec2 (- x r) (- y r)) d d))))
(defn labeled-rect-horizontal
[{:keys [h r label fill min-width base-line]}]
(let [r2 (* -2 r)
h2 (* 0.5 h)]
(fn [[[ax ay :as a] [bx :as b] item]]
(svg/group
{}
(svg/rect
(vec2 (- ax r) (- ay h2)) (- bx ax r2) h
{:fill (fill item) :rx r :ry r})
(if (< min-width (- bx ax))
(svg/text (vec2 ax (+ base-line ay)) (label item)))))))
(defn circle-cell
[a b c d col]
(svg/circle (gu/centroid [a b c d]) (* 0.5 (g/dist a b)) {:fill col}))
the " Dataset specs " section and examples above for details about
(defn svg-line-plot
[v-spec d-spec]
(svg/line-strip (map first (process-points v-spec d-spec)) (:attribs d-spec)))
represented as closed polygon ( and hence an ` : attribs ` key should
( e.g. ` : res 20 ` ) .
| ` : res ` | N | 1 | Number of points used to close polygon along X - axis |
(defn svg-area-plot
[{:keys [y-axis project] :as v-spec} {:keys [res] :as d-spec}]
(let [ry1 (first (:range y-axis))
points (mapv first (process-points (assoc v-spec :project vec2) d-spec))
p (vec2 (first (peek points)) ry1)
q (vec2 (ffirst points) ry1)
points (concat points (mapv (partial m/mix p q) (m/norm-range (or res 1))))]
(svg/polygon (mapv project points) (:attribs d-spec))))
Radar plot
(defn svg-radar-plot
[v-spec {:keys [shape] :or {shape svg/polygon} :as d-spec}]
(shape (mapv first (process-points v-spec d-spec)) (:attribs d-spec)))
radar plot
data item . For example a single data point of ` [ 2 0.25 0.75 ] ` would
define a domain position at x=2 and an interval of 0.25 - 0.75 . If no
` : item - pos- * ` options are supplied this 3 - element vector format is
| ` : item - pos - max ` | N | ` [ x max ] ` | Function to provide . data point |
| ` : shape ` | N | svg / path | Shape function receiving seq of outer & inner points and attribs |
(defn svg-radar-plot-minmax
[v-spec
{:keys [item-pos-min item-pos-max shape]
:or {shape #(svg/path (concat % [[:Z]] %2 [[:Z]]) %3)}
:as d-spec}]
(let [min-points (->> (assoc d-spec :item-pos (or item-pos-min (fn [i] (take 2 i))))
(process-points v-spec)
(mapv first)
(points->path-segments))
max-points (->> (assoc d-spec :item-pos (or item-pos-max (fn [i] [(first i) (nth i 2)])))
(process-points v-spec)
(mapv first)
(points->path-segments))]
(shape max-points min-points (assoc (:attribs d-spec) :fill-rule "evenodd"))))
(defn svg-scatter-plot
[v-spec {:keys [attribs shape] :as d-spec}]
(->> (assoc d-spec :shape (or shape (fn [[p]] (svg/circle p 3))))
(process-points v-spec)
(apply svg/group attribs)))
(defn svg-bar-plot
[{:keys [x-axis y-axis project] :or {project vec2}}
{:keys [values attribs shape item-pos interleave offset bar-width]
:or {shape (fn [a b _] (svg/line a b))
item-pos identity
interleave 1
bar-width 0
offset 0}}]
(let [domain (:domain x-axis)
base-y ((:scale y-axis) (first (:domain y-axis)))
mapper (value-mapper (:scale x-axis) (:scale y-axis))
offset (+ (* -0.5 (* interleave bar-width)) (* (+ offset 0.5) bar-width))]
(->> values
(sequence
(comp
(map (juxt item-pos identity))
(filter #(m/in-range? domain (ffirst %)))
(map
(fn [[p i]]
(let [[ax ay] (mapper p)
ax (+ ax offset)]
(shape (project [ax ay]) (project [ax base-y]) i))))))
(apply svg/group attribs))))
Heatmap
| ` : matrix ` | Y | nil | NDArray instance of data grid |
(defn svg-heatmap
[{:keys [x-axis y-axis project]}
{:keys [matrix value-domain clamp palette palette-scale attribs shape]
:or {value-domain [0.0 1.0]
palette-scale linear-scale
shape #(svg/polygon [%1 %2 %3 %4] {:fill %5})}
:as d-spec}]
(let [scale-x (:scale x-axis)
scale-y (:scale y-axis)
pmax (dec (count palette))
scale-v (palette-scale value-domain [0 pmax])]
(apply svg/group
attribs
(for [p (nd/position-seq matrix)
:let [[y x] p
v (nd/get-at matrix y x)]
:when (or clamp (m/in-range? value-domain v))]
(shape
(project [(scale-x x) (scale-y y)])
(project [(scale-x (inc x)) (scale-y y)])
(project [(scale-x (inc x)) (scale-y (inc y))])
(project [(scale-x x) (scale-y (inc y))])
(palette (m/clamp (int (scale-v v)) 0 pmax)))))))
Contour lines
Given a 2D matrix ( a ` thi.ng.ndarray.core . NDArray ` instance ) of data
| ` : matrix ` | Y | nil | NDArray instance of data grid |
(defn matrix-2d
[w h values] (nd/ndarray :float32 values [h w]))
(defn contour-matrix
[w h values]
(contours/set-border-2d (matrix-2d w h values) -1e9))
(defn contour->svg
[scale-x scale-y project]
(fn [attribs contour]
(let [contour (map (fn [[y x]] [(scale-x x) (scale-y y)]) contour)]
(svg/polygon (map project contour) attribs))))
(defn svg-contour-plot
[{:keys [x-axis y-axis project]}
{:keys [matrix attribs levels palette palette-scale value-domain contour-attribs]
:or {value-domain [0.0 1.0]
palette [[1 1 1]]
palette-scale linear-scale
contour-attribs (constantly nil)}}]
(let [pmax (dec (count palette))
scale-v (palette-scale value-domain [0 pmax])
contour-fn (contour->svg (:scale x-axis) (:scale y-axis) project)]
(->> levels
(sort)
(mapv
(fn [iso]
(let [c-attribs (contour-attribs (palette (m/clamp (int (scale-v iso)) 0 pmax)))]
(apply svg/group
{} (mapv
(partial contour-fn c-attribs)
(contours/find-contours-2d matrix iso))))))
(apply svg/group attribs))))
|---------------+------------+------------+-------------------------------------------------------|
(defn overlap? [[a b] [c d]] (and (<= a d) (>= b c)))
(defn compute-row-stacking
[item-range coll]
(reduce
(fn [grid x]
(let [r (item-range x)]
(loop [[row & more] grid idx 0]
(if (or (nil? row) (not (some #(overlap? r (item-range %)) row)))
(update-in grid [idx] #(conj (or % []) x))
(recur more (inc idx))))))
[] coll))
(defn process-interval-row
[item-range mapper [d1 d2]]
(fn [i row]
(map
(fn [item]
(let [[a b] (item-range item)]
[(mapper [(max d1 a) i]) (mapper [(min d2 b) i]) item]))
row)))
(defn svg-stacked-interval-plot
[{:keys [x-axis y-axis]}
{:keys [values attribs shape item-range offset]
:or {shape (fn [[a b]] (svg/line (vec2 a) (vec2 b)))
item-range identity
offset 0}}]
(let [scale-x (:scale x-axis)
scale-y (:scale y-axis)
domain (:domain x-axis)
mapper (value-mapper scale-x scale-y)]
(->> values
(filter #(overlap? domain (item-range %)))
(sort-by (comp first item-range))
(compute-row-stacking item-range)
(mapcat (process-interval-row item-range mapper domain) (range offset 1e6))
(mapv shape)
(apply svg/group attribs))))
(defn svg-axis*
[{:keys [major minor attribs label-style]} axis tick1-fn tick2-fn label-fn]
(svg/group
(merge {:stroke "#000"} attribs)
(seq (map tick1-fn major))
(seq (map tick2-fn minor))
(apply svg/group (merge {:stroke "none"} label-style) (mapv label-fn major))
axis))
(defn svg-x-axis-cartesian
[{:keys [scale major-size minor-size label-dist pos label] [r1 r2] :range
:as spec}]
(let [y-major (+ pos major-size)
y-minor (+ pos minor-size)
y-label (+ pos label-dist)]
(svg-axis*
spec (svg/line (vec2 r1 pos) (vec2 r2 pos))
#(let [x (scale %)] (svg/line (vec2 x pos) (vec2 x y-major)))
#(let [x (scale %)] (svg/line (vec2 x pos) (vec2 x y-minor)))
#(label (vec2 (scale %) y-label) %))))
(defn svg-y-axis-cartesian
[{:keys [scale major-size minor-size label-dist label-y pos label] [r1 r2] :range
:or {label-y 0}
:as spec}]
(let [x-major (- pos major-size)
x-minor (- pos minor-size)
x-label (- pos label-dist)]
(svg-axis*
spec (svg/line (vec2 pos r1) (vec2 pos r2))
#(let [y (scale %)] (svg/line (vec2 pos y) (vec2 x-major y)))
#(let [y (scale %)] (svg/line (vec2 pos y) (vec2 x-minor y)))
#(label (vec2 x-label (+ (scale %) label-y)) %))))
Generic plotting helpers
(defn select-ticks
[axis minor?] (if minor? (concat (:minor axis) (:major axis)) (:major axis)))
(defn svg-axis-grid2d-cartesian
[x-axis y-axis {:keys [attribs minor-x minor-y]}]
(let [[x1 x2] (:range x-axis)
[y1 y2] (:range y-axis)
scale-x (:scale x-axis)
scale-y (:scale y-axis)]
(svg/group
(merge {:stroke "#ccc" :stroke-dasharray "1 1"} attribs)
(if (or (:major x-axis) (:minor x-axis))
(map #(let [x (scale-x %)] (svg/line (vec2 x y1) (vec2 x y2))) (select-ticks x-axis minor-x)))
(if (or (:major y-axis) (:minor y-axis))
(map #(let [y (scale-y %)] (svg/line (vec2 x1 y) (vec2 x2 y))) (select-ticks y-axis minor-y))))))
(defn svg-plot2d-cartesian
[{:keys [x-axis y-axis grid data] :as opts}]
(let [opts (assoc opts :project vec2)]
(svg/group
{}
(if grid (svg-axis-grid2d-cartesian x-axis y-axis grid))
(map (fn [spec] ((:layout spec) opts spec)) data)
(if (:visible x-axis) (svg-x-axis-cartesian x-axis))
(if (:visible y-axis) (svg-y-axis-cartesian y-axis)))))
(defn svg-x-axis-polar
[{:keys [x-axis project circle origin]}]
(let [{:keys [scale major-size minor-size label-dist pos]} x-axis
label (or (:label x-axis) (default-svg-label (value-formatter 2)))
[r1 r2] (:range x-axis)
o origin]
(svg-axis*
x-axis
(if circle
(svg/circle o pos {:fill "none"})
(svg/arc o pos r1 r2 (> (m/abs-diff r1 r2) m/PI) true {:fill "none"}))
#(let [x (scale %)]
(svg/line (project [x pos]) (project [x (+ pos major-size)])))
#(let [x (scale %)]
(svg/line (project [x pos]) (project [x (+ pos minor-size)])))
#(let [x (scale %)]
(label (project [x (+ pos label-dist)]) %)))))
(defn svg-y-axis-polar
[{:keys [y-axis project]}]
(let [{:keys [scale label-y pos] :or {label-y 0}} y-axis
label (or (:label y-axis) (default-svg-label (value-formatter 2)))
[r1 r2] (:range y-axis)
a (project [pos r1])
b (project [pos r2])
nl (m/normalize (g/normal (m/- a b)) (:label-dist y-axis))
n1 (m/normalize nl (:major-size y-axis))
n2 (m/normalize nl (:minor-size y-axis))]
(svg-axis*
y-axis
(svg/line a b)
#(let [p (project [pos (scale %)])]
(svg/line p (m/+ p n1)))
#(let [p (project [pos (scale %)])]
(svg/line p (m/+ p n2)))
#(let [p (project [pos (+ (scale %) label-y)])]
(label (m/+ p nl) %)))))
(defn svg-axis-grid2d-polar
[{:keys [x-axis y-axis origin circle project] {:keys [attribs minor-x minor-y]} :grid}]
(let [[x1 x2] (:range x-axis)
[y1 y2] (:range y-axis)
scale-x (:scale x-axis)
scale-y (:scale y-axis)
great? (> (m/abs-diff x1 x2) m/PI)]
(svg/group
(merge {:stroke "#ccc" :stroke-dasharray "1 1"} attribs)
(if (or (:major x-axis) (:minor x-axis))
(map
#(let [x (scale-x %)] (svg/line (project [x y1]) (project [x y2])))
(select-ticks x-axis minor-x)))
(if (or (:major y-axis) (:minor y-axis))
(map
#(let [y (scale-y %)]
(if circle
(svg/circle origin y {:fill "none"})
(svg/arc origin y x1 x2 great? true {:fill "none"})))
(select-ticks y-axis minor-y))))))
(defn svg-plot2d-polar
[{:keys [x-axis y-axis grid data origin] :as spec}]
(let [spec (assoc spec :project (polar-projection origin))]
(svg/group
{}
(if grid (svg-axis-grid2d-polar spec))
(map (fn [spec'] ((:layout spec') spec spec')) data)
(if (:visible x-axis) (svg-x-axis-polar spec))
(if (:visible y-axis) (svg-y-axis-polar spec)))))
(comment
(defn clear-day-of-week [^GregorianCalendar cal] (.set cal Calendar/DAY_OF_WEEK 1) (clear-hour cal))
(defn clear-month [^GregorianCalendar cal] (.set cal Calendar/MONTH 0) (clear-day-of-month cal))
(defn year [^GregorianCalendar cal] (.get cal Calendar/YEAR))
(defn month [^GregorianCalendar cal] (.get cal Calendar/MONTH))
(defn day-of-month [^GregorianCalendar cal] (.get cal Calendar/DAY_OF_MONTH))
(defn day-of-week [^GregorianCalendar cal] (.get cal Calendar/DAY_OF_WEEK))
(defn hour [^GregorianCalendar cal] (.get cal Calendar/HOUR))
(defn minute [^GregorianCalendar cal] (.get cal Calendar/MINUTE))
(defn second [^GregorianCalendar cal] (.get cal Calendar/SECOND))
(defn round-to-year
[epoch]
(let [cal (epoch->cal epoch)]
(doto cal
(.add Calendar/MONTH 6)
(clear-month))))
(defn round-to-month
[epoch]
(doto (epoch->cal epoch)
(.setTimeInMillis (long epoch))
(.add Calendar/DAY_OF_MONTH 16)
(clear-day-of-month)))
(defn round-to-week
[epoch]
(doto (epoch->cal epoch)
(.setTimeInMillis (long epoch))
(.add Calendar/DAY_OF_WEEK 4)
(clear-day-of-week)))
(defn round-to-day-of-month
[epoch]
(doto (epoch->cal epoch)
(.add Calendar/HOUR 12)
(clear-hour)))
(defn round-to-day-of-week
[epoch]
(doto (epoch->cal epoch)
(.add Calendar/HOUR 12)
(clear-hour)))
(defn round-to-hour
[epoch]
(doto (epoch->cal epoch)
(.add Calendar/MINUTE 30)
(clear-minute)))
)
|
22060a5aed4bdb1d9aa39ffc2866088b5019ff48a99b64e37aeeae76e4d2fe4e | raptazure/experiments | MyList.hs | module MyList where
data MyList a
= Cons a (MyList a)
| MyNil
deriving (Show, Eq)
A simple linked list module
Some examples :
mylist = ( Cons 10 ( Cons 99 ( Cons 11 ( Cons 1 MyNil ) ) ) )
myHead myList # = > 10
myTail myList # = > Cons 99 ( Cons 11 ( Cons 1 MyNil ) )
myLength myList # = > 4
myToList myList # = > [ 10,99,11,1 ]
myFromList [ 10,99,11,1 ] # = > ( Cons 10 ( Cons 99 ( Cons 11 ( Cons 1 MyNil ) ) ) )
myIndex 2 myList # = > 11
myMapList ( \x - > x*x ) myList # = > Cons 100 ( Cons 9801 ( Cons 121 ( Cons 1 MyNil ) ) )
... etc ..
A simple linked list module
Some examples:
mylist = (Cons 10 (Cons 99 (Cons 11 (Cons 1 MyNil))))
myHead myList # => 10
myTail myList # => Cons 99 (Cons 11 (Cons 1 MyNil))
myLength myList # => 4
myToList myList # => [10,99,11,1]
myFromList [10,99,11,1] # => (Cons 10 (Cons 99 (Cons 11 (Cons 1 MyNil))))
myIndex 2 myList # => 11
myMapList (\x -> x*x) myList # => Cons 100 (Cons 9801 (Cons 121 (Cons 1 MyNil)))
...etc..
-}
myHead :: MyList a -> a
myHead l = case l of
Cons a _ -> a
myTail :: MyList a -> MyList a
myTail MyNil = MyNil
myTail l = case l of
Cons _ a -> a
myIndex :: Int -> MyList a -> a
myIndex 0 xs = myHead xs
myIndex x xs = myHead (myIndexTail x xs)
where
myIndexTail 0 xs = xs
myIndexTail i xs = myIndexTail (i -1) (myTail xs)
myLength :: MyList a -> Int
myLength MyNil = 0
myLength xs = 1 + (myLength (myTail xs))
myLast :: MyList a -> a
myLast (Cons a MyNil) = a
myLast l = myLast (myTail l)
myInsert :: a -> MyList a -> MyList a
myInsert x xs = Cons x xs
myConcat :: MyList a -> MyList a -> MyList a
myConcat (Cons a MyNil) bs = Cons a bs
myConcat as bs = myInsert (myHead as) (myConcat (myTail as) bs)
myAppend :: a -> MyList a -> MyList a
myAppend x (Cons a MyNil) = Cons a (Cons x MyNil)
myAppend x xs = myInsert (myHead xs) (myAppend x (myTail xs))
myToList :: MyList a -> [a]
myToList MyNil = []
myToList (Cons a l) = a : (myToList l)
myFromList :: [a] -> MyList a
myFromList [] = MyNil
myFromList l = Cons (head l) (myFromList (tail l))
myMapList :: (t -> a) -> MyList t -> MyList a
myMapList f (Cons x MyNil) = Cons (f x) MyNil
myMapList f l = Cons (f (myHead l)) (myMapList f (myTail l)) | null | https://raw.githubusercontent.com/raptazure/experiments/c48263980d1ce22ee9407ff8dcf0cf5091b01c70/haskell/wiwinwlh/dataStructures/src/MyList.hs | haskell | module MyList where
data MyList a
= Cons a (MyList a)
| MyNil
deriving (Show, Eq)
A simple linked list module
Some examples :
mylist = ( Cons 10 ( Cons 99 ( Cons 11 ( Cons 1 MyNil ) ) ) )
myHead myList # = > 10
myTail myList # = > Cons 99 ( Cons 11 ( Cons 1 MyNil ) )
myLength myList # = > 4
myToList myList # = > [ 10,99,11,1 ]
myFromList [ 10,99,11,1 ] # = > ( Cons 10 ( Cons 99 ( Cons 11 ( Cons 1 MyNil ) ) ) )
myIndex 2 myList # = > 11
myMapList ( \x - > x*x ) myList # = > Cons 100 ( Cons 9801 ( Cons 121 ( Cons 1 MyNil ) ) )
... etc ..
A simple linked list module
Some examples:
mylist = (Cons 10 (Cons 99 (Cons 11 (Cons 1 MyNil))))
myHead myList # => 10
myTail myList # => Cons 99 (Cons 11 (Cons 1 MyNil))
myLength myList # => 4
myToList myList # => [10,99,11,1]
myFromList [10,99,11,1] # => (Cons 10 (Cons 99 (Cons 11 (Cons 1 MyNil))))
myIndex 2 myList # => 11
myMapList (\x -> x*x) myList # => Cons 100 (Cons 9801 (Cons 121 (Cons 1 MyNil)))
...etc..
-}
myHead :: MyList a -> a
myHead l = case l of
Cons a _ -> a
myTail :: MyList a -> MyList a
myTail MyNil = MyNil
myTail l = case l of
Cons _ a -> a
myIndex :: Int -> MyList a -> a
myIndex 0 xs = myHead xs
myIndex x xs = myHead (myIndexTail x xs)
where
myIndexTail 0 xs = xs
myIndexTail i xs = myIndexTail (i -1) (myTail xs)
myLength :: MyList a -> Int
myLength MyNil = 0
myLength xs = 1 + (myLength (myTail xs))
myLast :: MyList a -> a
myLast (Cons a MyNil) = a
myLast l = myLast (myTail l)
myInsert :: a -> MyList a -> MyList a
myInsert x xs = Cons x xs
myConcat :: MyList a -> MyList a -> MyList a
myConcat (Cons a MyNil) bs = Cons a bs
myConcat as bs = myInsert (myHead as) (myConcat (myTail as) bs)
myAppend :: a -> MyList a -> MyList a
myAppend x (Cons a MyNil) = Cons a (Cons x MyNil)
myAppend x xs = myInsert (myHead xs) (myAppend x (myTail xs))
myToList :: MyList a -> [a]
myToList MyNil = []
myToList (Cons a l) = a : (myToList l)
myFromList :: [a] -> MyList a
myFromList [] = MyNil
myFromList l = Cons (head l) (myFromList (tail l))
myMapList :: (t -> a) -> MyList t -> MyList a
myMapList f (Cons x MyNil) = Cons (f x) MyNil
myMapList f l = Cons (f (myHead l)) (myMapList f (myTail l)) | |
89c70cb18c0707ba801e9342553daa22c9fb1f1ebff3409286e4e1fec9cd8b4f | Frechmatz/cl-synthesizer | agent.lisp | (in-package :cl-synthesizer-monitor-csv-file-agent)
(defun make-symbol-impl (name num package)
(if num
(intern (format nil "~a-~a" (string-upcase name) num) package)
(intern (string-upcase name) package)))
(defun make-keyword (name num)
(make-symbol-impl name num "KEYWORD"))
(defun make-keyword-list (name count)
"Returns list of keywords ordered by number of keyword: (:<name>-1, :<name>-2, ..., <name>-<count>.
The numbering starts by one."
(let ((l nil))
(dotimes (i count)
(push (make-keyword name (+ i 1)) l))
(nreverse l)))
(defun make-backend (name environment inputs &rest rest &key filename &allow-other-keys)
"Creates a monitor backend which writes its inputs into a CSV file.
<p>The function has the following parameters:
<ul>
<li>name A name.</li>
<li>environment The synthesizer environment.</li>
<li>inputs The column input settings as provided by the Monitor component.</li>
<li>:filename A file path relative to the output directory as defined by the environment.</li>
</ul></p>
<p>The function returns a values object consisting of
<ul>
<li>A property list that implements a module (this is the Monitor-Backend).</li>
<li>An ordered list of input sockets of the module.</li>
</ul></p>
<p>See also cl-synthesizer-modules:csv-file-writer.</p>"
(let* ((handler
(apply #'cl-synthesizer-modules-csv-file-writer:make-module
name
environment
:filename filename
:columns inputs
rest)))
(values
handler
;; Ordered list of channels (we do not want to depend on order of input keys
;; provided by the :inputs function of the csv file writer module.)
(make-keyword-list "column" (length inputs)))))
| null | https://raw.githubusercontent.com/Frechmatz/cl-synthesizer/679eb91d1814ad24c915b39b12685af6ffd4292f/src/monitor/csv-file/agent.lisp | lisp | Ordered list of channels (we do not want to depend on order of input keys
provided by the :inputs function of the csv file writer module.) | (in-package :cl-synthesizer-monitor-csv-file-agent)
(defun make-symbol-impl (name num package)
(if num
(intern (format nil "~a-~a" (string-upcase name) num) package)
(intern (string-upcase name) package)))
(defun make-keyword (name num)
(make-symbol-impl name num "KEYWORD"))
(defun make-keyword-list (name count)
"Returns list of keywords ordered by number of keyword: (:<name>-1, :<name>-2, ..., <name>-<count>.
The numbering starts by one."
(let ((l nil))
(dotimes (i count)
(push (make-keyword name (+ i 1)) l))
(nreverse l)))
(defun make-backend (name environment inputs &rest rest &key filename &allow-other-keys)
"Creates a monitor backend which writes its inputs into a CSV file.
<p>The function has the following parameters:
<ul>
<li>name A name.</li>
<li>environment The synthesizer environment.</li>
<li>inputs The column input settings as provided by the Monitor component.</li>
<li>:filename A file path relative to the output directory as defined by the environment.</li>
</ul></p>
<p>The function returns a values object consisting of
<ul>
<li>A property list that implements a module (this is the Monitor-Backend).</li>
<li>An ordered list of input sockets of the module.</li>
</ul></p>
<p>See also cl-synthesizer-modules:csv-file-writer.</p>"
(let* ((handler
(apply #'cl-synthesizer-modules-csv-file-writer:make-module
name
environment
:filename filename
:columns inputs
rest)))
(values
handler
(make-keyword-list "column" (length inputs)))))
|
d0812562d5b7888aad37d87f762c9dee3b451f9f2d1d1bcb171368bb6b436113 | dym/movitz | bignums.lisp | ;;;;------------------------------------------------------------------
;;;;
Copyright ( C ) 2003 - 2005 ,
Department of Computer Science , University of Tromso , Norway .
;;;;
;;;; For distribution policy, see the accompanying file COPYING.
;;;;
;;;; Filename: bignums.lisp
;;;; Description:
Author : < >
Created at : Sat Jul 17 19:42:57 2004
;;;;
$ I d : bignums.lisp , v 1.18 2008/02/04 15:11:16 Exp $
;;;;
;;;;------------------------------------------------------------------
(require :muerte/basic-macros)
(require :muerte/typep)
(require :muerte/arithmetic-macros)
(provide :muerte/bignums)
(in-package muerte)
(defun %bignum-bigits (x)
(%bignum-bigits x))
(defun bignum-canonicalize (x)
"Assuming x is a bignum, return the canonical integer value. That is,
either return a fixnum, or destructively modify the bignum's length so
that the msb isn't zero. DO NOT APPLY TO NON-BIGNUM VALUES!"
(check-type x bignum)
(macrolet
((do-it ()
`(with-inline-assembly (:returns :eax)
(:load-lexical (:lexical-binding x) :eax)
(:movl (:eax ,movitz:+other-type-offset+) :ecx)
(:shrl 16 :ecx)
(:jz '(:sub-program (should-never-happen)
(:int 63)))
shrink-loop
(:cmpl 4 :ecx)
(:je 'shrink-no-more)
(:cmpl 0 (:eax :ecx ,(+ -4 (bt:slot-offset 'movitz:movitz-bignum 'movitz::bigit0))))
(:jnz 'shrink-done)
(:subl 4 :ecx)
(:jmp 'shrink-loop)
shrink-no-more
(:cmpl ,(1+ movitz:+movitz-most-positive-fixnum+)
(:eax ,(bt:slot-offset 'movitz:movitz-bignum 'movitz::bigit0)))
(:jc '(:sub-program (fixnum-result)
(:movl (:eax ,(bt:slot-offset 'movitz:movitz-bignum 'movitz::bigit0))
:ecx)
(:leal ((:ecx ,movitz:+movitz-fixnum-factor+)) :eax)
(:jmp 'done)))
shrink-done
(:testb 3 :cl)
(:jnz '(:sub-program () (:int 63)))
(:testw :cx :cx)
(:jz '(:sub-program () (:int 63)))
(:movw :cx (:eax ,(bt:slot-offset 'movitz:movitz-bignum 'movitz::length)))
done
)))
(do-it)))
(defun copy-bignum (old)
(check-type old bignum)
(%shallow-copy-object old (1+ (%bignum-bigits old))))
(defun %make-bignum (bigits &optional fill)
(numargs-case
(1 (bigits)
(check-type bigits (unsigned-byte 14))
(macrolet
((do-it ()
`(let ((words (1+ bigits)))
(with-non-pointer-allocation-assembly (words :fixed-size-p t
:object-register :eax)
(:load-lexical (:lexical-binding bigits) :ecx)
(:shll 16 :ecx)
(:orl ,(movitz:tag :bignum 0) :ecx)
(:movl :ecx (:eax (:offset movitz-bignum type)))))))
(do-it)))
(t (bigits &optional fill)
(let ((bignum (%make-bignum bigits)))
(when fill
(check-type fill (unsigned-byte 8))
(dotimes (i (* 4 bigits))
(setf (memref bignum (movitz-type-slot-offset 'movitz-bignum 'bigit0)
:index i :type :unsigned-byte8)
fill)))
bignum))))
(defun print-bignum (x)
(check-type x bignum)
(dotimes (i (1+ (%bignum-bigits x)))
(format t "~8,'0X " (memref x -6 :index i :type :unsigned-byte32)))
(terpri)
(values))
(defun bignum-add-fixnum (bignum delta)
"Non-destructively add an unsigned fixnum delta to an (unsigned) bignum."
(check-type bignum bignum)
(check-type delta fixnum)
(macrolet
((do-it ()
`(with-inline-assembly (:returns :eax :labels (not-size1
copy-bignum-loop
add-bignum-loop
add-bignum-done
no-expansion
pfix-pbig-done))
(:compile-two-forms (:eax :ebx) bignum delta)
(:testl :ebx :ebx)
(:jz 'pfix-pbig-done) ; EBX=0 => nothing to do.
(:movzxw (:eax (:offset movitz-bignum length)) :ecx)
(:cmpl ,movitz:+movitz-fixnum-factor+ :ecx)
(:jne 'not-size1)
(:compile-form (:result-mode :ecx) delta)
(:shrl ,movitz:+movitz-fixnum-shift+ :ecx)
(:addl (:eax (:offset movitz-bignum bigit0)) :ecx)
(:jc 'not-size1)
(:call-local-pf box-u32-ecx)
(:jmp 'pfix-pbig-done)
not-size1
;; Set up atomically continuation.
(:declare-label-set restart-jumper (restart-addition))
(:locally (:pushl (:edi (:edi-offset :dynamic-env))))
(:pushl 'restart-jumper)
;; ..this allows us to detect recursive atomicallies.
(:locally (:pushl (:edi (:edi-offset :atomically-continuation))))
(:pushl :ebp)
restart-addition
(:movl (:esp) :ebp)
(:compile-form (:result-mode :eax) bignum)
(:movzxw (:eax (:offset movitz-bignum length)) :ecx)
(:locally (:movl :esp (:edi (:edi-offset :atomically-continuation))))
;; Now inside atomically section.
(:leal ((:ecx 1) ,(* 2 movitz:+movitz-fixnum-factor+))
:eax) ; Number of words
(:call-local-pf cons-non-pointer)
(:load-lexical (:lexical-binding bignum) :ebx) ; bignum
(:movzxw (:ebx (:offset movitz-bignum length)) :ecx)
(:leal ((:ecx 1) ,movitz:+movitz-fixnum-factor+)
:edx)
MSB
copy-bignum-loop
(:subl ,movitz:+movitz-fixnum-factor+ :edx)
(:movl (:ebx :edx ,movitz:+other-type-offset+) :ecx)
(:movl :ecx (:eax :edx ,movitz:+other-type-offset+))
(:jnz 'copy-bignum-loop)
(:load-lexical (:lexical-binding delta) :ecx)
(:shrl ,movitz:+movitz-fixnum-shift+ :ecx)
(:xorl :ebx :ebx)
(:addl :ecx (:eax (:offset movitz-bignum bigit0)))
(:jnc 'add-bignum-done)
add-bignum-loop
(:addl 4 :ebx)
(:addl 1 (:eax :ebx (:offset movitz-bignum bigit0)))
(:jc 'add-bignum-loop)
add-bignum-done
(:movzxw (:eax (:offset movitz-bignum length)) :ecx)
(:leal ((:ecx 1) ,movitz:+movitz-fixnum-factor+) :ecx)
(:cmpl 0 (:eax :ecx (:offset movitz-bignum bigit0 -4)))
(:je 'no-expansion)
(:addl #x40000 (:eax ,movitz:+other-type-offset+))
(:addl ,movitz:+movitz-fixnum-factor+ :ecx)
no-expansion
(:call-local-pf cons-commit-non-pointer)
Exit atomically block .
(:locally (:movl 0 (:edi (:edi-offset atomically-continuation))))
(:leal (:esp 16) :esp)
pfix-pbig-done)))
(do-it)))
(defun bignum-addf-fixnum (bignum delta)
"Destructively add a fixnum delta (negative or positive) to an (unsigned) bignum."
(check-type delta fixnum)
(check-type bignum bignum)
(macrolet
((do-it ()
`(with-inline-assembly (:returns :eax :labels (add-bignum-loop add-bignum-done))
(:load-lexical (:lexical-binding delta) :ecx)
(:load-lexical (:lexical-binding bignum) :eax)
(:movzxw (:eax ,(bt:slot-offset 'movitz::movitz-bignum 'movitz::length)) :ebx) ; length
(:xorl :edx :edx) ; counter
(:sarl ,movitz:+movitz-fixnum-shift+ :ecx)
(:jns 'positive-delta)
;; negative-delta
(:negl :ecx)
(:subl :ecx (:eax ,(bt:slot-offset 'movitz::movitz-bignum 'movitz::bigit0)))
(:jnc 'add-bignum-done)
sub-bignum-loop
(:addl 4 :edx)
(:cmpl :edx :ebx)
(:je '(:sub-program (overflow) (:int 4)))
(:subl 1 (:eax :edx ,(bt:slot-offset 'movitz::movitz-bignum 'movitz::bigit0)))
(:jc 'sub-bignum-loop)
(:jmp 'add-bignum-done)
positive-delta
(:addl :ecx (:eax ,(bt:slot-offset 'movitz::movitz-bignum 'movitz::bigit0)))
(:jnc 'add-bignum-done)
add-bignum-loop
(:addl 4 :edx)
(:cmpl :edx :ebx)
(:je '(:sub-program (overflow) (:int 4)))
(:addl 1 (:eax :edx ,(bt:slot-offset 'movitz::movitz-bignum 'movitz::bigit0)))
(:jc 'add-bignum-loop)
add-bignum-done)))
(do-it)))
(defun bignum-addf (bignum delta)
"Destructively add (abs delta) to bignum."
(check-type bignum bignum)
(etypecase delta
(positive-fixnum
(bignum-addf-fixnum bignum delta))
(negative-fixnum
(bignum-addf-fixnum bignum (- delta)))
(bignum
(macrolet
((do-it ()
`(with-inline-assembly (:returns :eax)
not-size1
EAX = bignum
EBX = delta
(:xorl :edx :edx) ; Counter
(:xorl :ecx :ecx) ; Carry
add-bignum-loop
(:addl (:ebx :edx (:offset movitz-bignum :bigit0))
:ecx)
(:jz 'carry+digit-overflowed) ; If CF=1, then ECX=0.
(:cmpw :dx (:eax (:offset movitz-bignum length)))
(:jbe '(:sub-program (overflow) (:int 4)))
(:addl :ecx (:eax :edx (:offset movitz-bignum bigit0)))
carry+digit-overflowed
(:sbbl :ecx :ecx)
ECX = Add 's Carry .
(:addl 4 :edx)
(:cmpw :dx (:ebx (:offset movitz-bignum length)))
(:ja 'add-bignum-loop)
;; Now, if there's a carry we must propagate it.
(:jecxz 'add-bignum-done)
carry-propagate-loop
(:cmpw :dx (:eax (:offset movitz-bignum length)))
(:jbe '(:sub-program (overflow) (:int 4)))
(:addl 4 :edx)
(:addl 1 (:eax :edx (:offset movitz-bignum bigit0 -4)))
(:jc 'carry-propagate-loop)
add-bignum-done)))
(do-it)))))
(defun bignum-subf (bignum delta)
"Destructively subtract (abs delta) from bignum."
(check-type bignum bignum)
(etypecase delta
(positive-fixnum
(bignum-addf-fixnum bignum (- delta)))
(negative-fixnum
(bignum-addf-fixnum bignum delta))
(bignum
(macrolet
((do-it ()
`(with-inline-assembly (:returns :eax)
not-size1
EAX = bignum
EBX = delta
(:xorl :edx :edx) ; Counter
(:xorl :ecx :ecx) ; Carry
sub-bignum-loop
(:cmpw :dx (:eax (:offset movitz-bignum length)))
(:jbe '(:sub-program (overflow) (:int 4)))
(:addl (:ebx :edx (:offset movitz-bignum :bigit0))
:ecx)
(:jz 'carry+digit-overflowed) ; If CF=1, then ECX=0.
(:subl :ecx (:eax :edx (:offset movitz-bignum bigit0)))
carry+digit-overflowed
(:sbbl :ecx :ecx)
ECX = Add 's Carry .
(:addl 4 :edx)
(:cmpw :dx (:ebx (:offset movitz-bignum length)))
(:ja 'sub-bignum-loop)
;; Now, if there's a carry we must propagate it.
(:jecxz 'sub-bignum-done)
carry-propagate-loop
(:cmpw :dx (:eax (:offset movitz-bignum length)))
(:jbe '(:sub-program (overflow) (:int 4)))
(:addl 4 :edx)
(:subl 1 (:eax :edx (:offset movitz-bignum bigit0 -4)))
(:jc 'carry-propagate-loop)
sub-bignum-done)))
(do-it)))))
(defun bignum-shift-rightf (bignum count)
"Destructively right-shift bignum by count bits."
(check-type bignum bignum)
(check-type count positive-fixnum)
(multiple-value-bind (long-shift short-shift)
(truncate count 32)
(macrolet
((do-it ()
`(with-inline-assembly (:returns :ebx)
(:compile-two-forms (:edx :ebx) long-shift bignum)
(:xorl :eax :eax)
shift-long-loop
(:cmpw :dx (:ebx (:offset movitz-bignum length)))
(:jbe 'zero-msb-loop)
(:movl (:ebx :edx (:offset movitz-bignum bigit0)) :ecx)
(:movl :ecx (:ebx :eax (:offset movitz-bignum bigit0)))
(:addl 4 :eax)
(:addl 4 :edx)
(:jmp 'shift-long-loop)
zero-msb-loop
(:cmpw :ax (:ebx (:offset movitz-bignum length)))
(:jbe 'long-shift-done)
(:movl 0 (:ebx :eax (:offset movitz-bignum bigit0)))
(:addl 4 :eax)
(:jmp 'zero-msb-loop)
long-shift-done
(:compile-form (:result-mode :ecx) short-shift)
(:xorl :edx :edx) ; counter
We need to use EAX for u32 storage .
(:shrl ,movitz:+movitz-fixnum-shift+ :ecx)
(:std)
shift-short-loop
(:addl 4 :edx)
(:cmpw :dx (:ebx (:offset movitz-bignum length)))
(:jbe 'end-shift-short-loop)
(:movl (:ebx :edx (:offset movitz-bignum bigit0))
:eax)
(:shrdl :cl :eax
(:ebx :edx (:offset movitz-bignum bigit0 -4)))
(:jmp 'shift-short-loop)
end-shift-short-loop
(:movl :edx :eax) ; Safe EAX
(:shrl :cl (:ebx :edx (:offset movitz-bignum bigit0 -4)))
(:cld))))
(do-it))))
(defun bignum-shift-leftf (bignum count)
"Destructively left-shift bignum by count bits."
(check-type bignum bignum)
(check-type count positive-fixnum)
(multiple-value-bind (long-shift short-shift)
(truncate count 32)
(macrolet
((do-it ()
`(with-inline-assembly (:returns :ebx)
(:compile-two-forms (:ecx :ebx) long-shift bignum)
(:jecxz 'long-shift-done)
(:xorl :eax :eax)
(:movw (:ebx (:offset movitz-bignum length)) :ax)
(:subl 4 :eax) ; destination pointer
(:movl :eax :edx)
;; Overflow check
overflow-check-loop
(:cmpl 0 (:ebx :edx (:offset movitz-bignum bigit0)))
(:jne '(:sub-program (overflow) (:int 4)))
(:subl 4 :edx)
(:subl 4 :ecx)
(:jnz 'overflow-check-loop)
;; (:subl :ecx :edx) ; source = EDX = (- dest long-shift)
(:jc '(:sub-program (overflow) (:int 4)))
shift-long-loop
(:movl (:ebx :edx (:offset movitz-bignum bigit0)) :ecx)
(:movl :ecx (:ebx :eax (:offset movitz-bignum bigit0)))
(:subl 4 :eax)
(:subl 4 :edx)
(:jnc 'shift-long-loop)
zero-lsb-loop
(:movl 0 (:ebx :eax (:offset movitz-bignum bigit0))) ; EDX=0
(:subl 4 :eax)
(:jnc 'zero-lsb-loop)
long-shift-done
(:compile-form (:result-mode :ecx) short-shift)
(:shrl ,movitz:+movitz-fixnum-shift+ :ecx)
(:jz 'done)
(:xorl :esi :esi) ; counter
(:movw (:ebx (:offset movitz-bignum length)) :si)
(:subl 4 :esi)
(:jz 'shift-short-lsb)
(:xorl :eax :eax)
(:std)
;; Overflow check
(:movl (:ebx :esi (:offset movitz-bignum bigit0))
:eax)
(:xorl :edx :edx)
(:shldl :cl :eax :edx)
(:jnz 'overflow)
shift-short-loop
(:movl (:ebx :esi (:offset movitz-bignum bigit0 -4))
:eax)
(:shldl :cl :eax (:ebx :esi (:offset movitz-bignum bigit0)))
(:subl 4 :esi)
(:jnz 'shift-short-loop)
(:movl :edi :edx)
(:movl :edi :eax) ; Safe EAX
(:cld)
shift-short-lsb
(:shll :cl (:ebx (:offset movitz-bignum bigit0)))
done
(:movl (:ebp -4) :esi)
)))
(do-it))))
(defun bignum-mulf (bignum factor)
"Destructively multiply bignum by (abs factor)."
(check-type bignum bignum)
(etypecase factor
(bignum
(error "not yet"))
(negative-fixnum
(bignum-mulf bignum (- factor)))
(positive-fixnum
(macrolet
((do-it ()
`(with-inline-assembly (:returns :ebx)
(:load-lexical (:lexical-binding bignum) :ebx) ; bignum
(:compile-form (:result-mode :ecx) factor)
(:sarl ,movitz:+movitz-fixnum-shift+ :ecx)
(:locally (:movl :ecx (:edi (:edi-offset raw-scratch0))))
Counter ( by 4 )
(:xorl :edx :edx) ; Initial carry
Make EAX , EDX non - GC - roots .
multiply-loop
(:movl (:ebx :esi (:offset movitz-bignum bigit0))
:eax)
Save carry in ECX
EDX : EAX = scratch0*EAX
(:addl :ecx :eax) ; Add carry
Compute next carry
(:jc '(:sub-program (should-not-happen) (:int 63)))
(:movl :eax (:ebx :esi (:offset movitz-bignum bigit0)))
(:addl 4 :esi)
(:cmpw :si (:ebx (:offset movitz-bignum length)))
(:ja 'multiply-loop)
Carry into ECX
(:movl :edi :eax)
(:movl :edi :edx)
(:cld)
(:movl (:ebp -4) :esi)
(:testl :ecx :ecx) ; Carry overflow?
(:jnz '(:sub-program (overflow) (:int 4)))
)))
(do-it)))))
(defun bignum-truncatef (bignum divisor)
(etypecase divisor
(positive-fixnum
(macrolet
((do-it ()
`(with-inline-assembly (:returns :ebx)
(:compile-two-forms (:ebx :ecx) bignum divisor)
(:xorl :edx :edx) ; hi-digit
(:sarl ,movitz:+movitz-fixnum-shift+ :ecx)
ESI is counter by 4
(:movw (:ebx (:offset movitz-bignum length)) :si)
(:std)
divide-loop
(:movl (:ebx :esi (:offset movitz-bignum bigit0 -4))
:eax) ; lo-digit
EDX : EAX = EDX : EAX / ECX
(:movl :eax (:ebx :esi (:offset movitz-bignum bigit0 -4)))
(:subl 4 :esi)
(:jnz 'divide-loop)
(:movl (:ebp -4) :esi)
(:movl :edi :edx)
(:movl :ebx :eax)
(:cld))))
(do-it)))))
(defun bignum-set-zerof (bignum)
(check-type bignum bignum)
(dotimes (i (%bignum-bigits bignum))
(setf (memref bignum (movitz-type-slot-offset 'movitz-bignum 'bigit0)
:index i :type :unsigned-byte32) 0))
bignum)
(defun %bignum= (x y)
(check-type x bignum)
(check-type y bignum)
(compiler-macro-call %bignum= x y))
(defun %bignum< (x y)
(check-type x bignum)
(check-type y bignum)
(compiler-macro-call %bignum< x y))
(defun %bignum-zerop (x)
(compiler-macro-call %bignum-zerop x))
(defun bignum-integer-length (x)
"Compute (integer-length (abs x))."
(check-type x bignum)
(macrolet
((do-it ()
`(with-inline-assembly (:returns :eax)
(:compile-form (:result-mode :ebx) x)
(:movzxw (:ebx (:offset movitz-bignum length))
:edx)
(:xorl :eax :eax)
bigit-scan-loop
(:subl 4 :edx)
(:jc 'done)
(:cmpl 0 (:ebx :edx (:offset movitz-bignum bigit0)))
(:jz 'bigit-scan-loop)
Now , EAX must be loaded with ( + ( * EDX 32 ) bit - index 1 ) .
Factor 8
(:bsrl (:ebx :edx (:offset movitz-bignum bigit0))
:ecx)
Factor 4
(:leal ((:ecx 4) :eax 4) :eax)
done)))
(do-it)))
(defun bignum-logcount (x)
"Compute (logcount (abs x))."
(check-type x bignum)
(macrolet
((do-it ()
`(with-inline-assembly (:returns :eax)
(:compile-form (:result-mode :ebx) x)
(:xorl :eax :eax)
(:xorl :edx :edx)
(:movw (:ebx (:offset movitz-bignum length)) :dx)
word-loop
(:movl (:ebx :edx (:offset movitz-bignum bigit0 -4)) :ecx)
bit-loop
(:jecxz 'end-bit-loop)
(:shrl 1 :ecx)
(:jnc 'bit-loop)
(:addl ,movitz:+movitz-fixnum-factor+ :eax)
(:jmp 'bit-loop)
end-bit-loop
(:subl 4 :edx)
(:jnz 'word-loop))))
(do-it)))
(defun %bignum-negate (x)
(compiler-macro-call %bignum-negate x))
(defun %bignum-plus-fixnum-size (x fixnum-delta)
(compiler-macro-call %bignum-plus-fixnum-size x fixnum-delta))
(defun bignum-notf (x)
(check-type x bignum)
(macrolet
((do-it ()
`(with-inline-assembly (:returns :eax)
(:load-lexical (:lexical-binding x) :eax)
(:xorl :edx :edx)
(:xorl :ecx :ecx)
(:movw (:eax (:offset movitz-bignum length)) :cx)
loop
(:notl (:eax :edx (:offset movitz-bignum bigit0)))
(:addl 4 :edx)
(:cmpl :edx :ecx)
(:ja 'loop))))
(do-it)))
| null | https://raw.githubusercontent.com/dym/movitz/56176e1ebe3eabc15c768df92eca7df3c197cb3d/losp/muerte/bignums.lisp | lisp | ------------------------------------------------------------------
For distribution policy, see the accompanying file COPYING.
Filename: bignums.lisp
Description:
------------------------------------------------------------------
EBX=0 => nothing to do.
Set up atomically continuation.
..this allows us to detect recursive atomicallies.
Now inside atomically section.
Number of words
bignum
length
counter
negative-delta
Counter
Carry
If CF=1, then ECX=0.
Now, if there's a carry we must propagate it.
Counter
Carry
If CF=1, then ECX=0.
Now, if there's a carry we must propagate it.
counter
Safe EAX
destination pointer
Overflow check
(:subl :ecx :edx) ; source = EDX = (- dest long-shift)
EDX=0
counter
Overflow check
Safe EAX
bignum
Initial carry
Add carry
Carry overflow?
hi-digit
lo-digit | Copyright ( C ) 2003 - 2005 ,
Department of Computer Science , University of Tromso , Norway .
Author : < >
Created at : Sat Jul 17 19:42:57 2004
$ I d : bignums.lisp , v 1.18 2008/02/04 15:11:16 Exp $
(require :muerte/basic-macros)
(require :muerte/typep)
(require :muerte/arithmetic-macros)
(provide :muerte/bignums)
(in-package muerte)
(defun %bignum-bigits (x)
(%bignum-bigits x))
(defun bignum-canonicalize (x)
"Assuming x is a bignum, return the canonical integer value. That is,
either return a fixnum, or destructively modify the bignum's length so
that the msb isn't zero. DO NOT APPLY TO NON-BIGNUM VALUES!"
(check-type x bignum)
(macrolet
((do-it ()
`(with-inline-assembly (:returns :eax)
(:load-lexical (:lexical-binding x) :eax)
(:movl (:eax ,movitz:+other-type-offset+) :ecx)
(:shrl 16 :ecx)
(:jz '(:sub-program (should-never-happen)
(:int 63)))
shrink-loop
(:cmpl 4 :ecx)
(:je 'shrink-no-more)
(:cmpl 0 (:eax :ecx ,(+ -4 (bt:slot-offset 'movitz:movitz-bignum 'movitz::bigit0))))
(:jnz 'shrink-done)
(:subl 4 :ecx)
(:jmp 'shrink-loop)
shrink-no-more
(:cmpl ,(1+ movitz:+movitz-most-positive-fixnum+)
(:eax ,(bt:slot-offset 'movitz:movitz-bignum 'movitz::bigit0)))
(:jc '(:sub-program (fixnum-result)
(:movl (:eax ,(bt:slot-offset 'movitz:movitz-bignum 'movitz::bigit0))
:ecx)
(:leal ((:ecx ,movitz:+movitz-fixnum-factor+)) :eax)
(:jmp 'done)))
shrink-done
(:testb 3 :cl)
(:jnz '(:sub-program () (:int 63)))
(:testw :cx :cx)
(:jz '(:sub-program () (:int 63)))
(:movw :cx (:eax ,(bt:slot-offset 'movitz:movitz-bignum 'movitz::length)))
done
)))
(do-it)))
(defun copy-bignum (old)
(check-type old bignum)
(%shallow-copy-object old (1+ (%bignum-bigits old))))
(defun %make-bignum (bigits &optional fill)
(numargs-case
(1 (bigits)
(check-type bigits (unsigned-byte 14))
(macrolet
((do-it ()
`(let ((words (1+ bigits)))
(with-non-pointer-allocation-assembly (words :fixed-size-p t
:object-register :eax)
(:load-lexical (:lexical-binding bigits) :ecx)
(:shll 16 :ecx)
(:orl ,(movitz:tag :bignum 0) :ecx)
(:movl :ecx (:eax (:offset movitz-bignum type)))))))
(do-it)))
(t (bigits &optional fill)
(let ((bignum (%make-bignum bigits)))
(when fill
(check-type fill (unsigned-byte 8))
(dotimes (i (* 4 bigits))
(setf (memref bignum (movitz-type-slot-offset 'movitz-bignum 'bigit0)
:index i :type :unsigned-byte8)
fill)))
bignum))))
(defun print-bignum (x)
(check-type x bignum)
(dotimes (i (1+ (%bignum-bigits x)))
(format t "~8,'0X " (memref x -6 :index i :type :unsigned-byte32)))
(terpri)
(values))
(defun bignum-add-fixnum (bignum delta)
"Non-destructively add an unsigned fixnum delta to an (unsigned) bignum."
(check-type bignum bignum)
(check-type delta fixnum)
(macrolet
((do-it ()
`(with-inline-assembly (:returns :eax :labels (not-size1
copy-bignum-loop
add-bignum-loop
add-bignum-done
no-expansion
pfix-pbig-done))
(:compile-two-forms (:eax :ebx) bignum delta)
(:testl :ebx :ebx)
(:movzxw (:eax (:offset movitz-bignum length)) :ecx)
(:cmpl ,movitz:+movitz-fixnum-factor+ :ecx)
(:jne 'not-size1)
(:compile-form (:result-mode :ecx) delta)
(:shrl ,movitz:+movitz-fixnum-shift+ :ecx)
(:addl (:eax (:offset movitz-bignum bigit0)) :ecx)
(:jc 'not-size1)
(:call-local-pf box-u32-ecx)
(:jmp 'pfix-pbig-done)
not-size1
(:declare-label-set restart-jumper (restart-addition))
(:locally (:pushl (:edi (:edi-offset :dynamic-env))))
(:pushl 'restart-jumper)
(:locally (:pushl (:edi (:edi-offset :atomically-continuation))))
(:pushl :ebp)
restart-addition
(:movl (:esp) :ebp)
(:compile-form (:result-mode :eax) bignum)
(:movzxw (:eax (:offset movitz-bignum length)) :ecx)
(:locally (:movl :esp (:edi (:edi-offset :atomically-continuation))))
(:leal ((:ecx 1) ,(* 2 movitz:+movitz-fixnum-factor+))
(:call-local-pf cons-non-pointer)
(:movzxw (:ebx (:offset movitz-bignum length)) :ecx)
(:leal ((:ecx 1) ,movitz:+movitz-fixnum-factor+)
:edx)
MSB
copy-bignum-loop
(:subl ,movitz:+movitz-fixnum-factor+ :edx)
(:movl (:ebx :edx ,movitz:+other-type-offset+) :ecx)
(:movl :ecx (:eax :edx ,movitz:+other-type-offset+))
(:jnz 'copy-bignum-loop)
(:load-lexical (:lexical-binding delta) :ecx)
(:shrl ,movitz:+movitz-fixnum-shift+ :ecx)
(:xorl :ebx :ebx)
(:addl :ecx (:eax (:offset movitz-bignum bigit0)))
(:jnc 'add-bignum-done)
add-bignum-loop
(:addl 4 :ebx)
(:addl 1 (:eax :ebx (:offset movitz-bignum bigit0)))
(:jc 'add-bignum-loop)
add-bignum-done
(:movzxw (:eax (:offset movitz-bignum length)) :ecx)
(:leal ((:ecx 1) ,movitz:+movitz-fixnum-factor+) :ecx)
(:cmpl 0 (:eax :ecx (:offset movitz-bignum bigit0 -4)))
(:je 'no-expansion)
(:addl #x40000 (:eax ,movitz:+other-type-offset+))
(:addl ,movitz:+movitz-fixnum-factor+ :ecx)
no-expansion
(:call-local-pf cons-commit-non-pointer)
Exit atomically block .
(:locally (:movl 0 (:edi (:edi-offset atomically-continuation))))
(:leal (:esp 16) :esp)
pfix-pbig-done)))
(do-it)))
(defun bignum-addf-fixnum (bignum delta)
"Destructively add a fixnum delta (negative or positive) to an (unsigned) bignum."
(check-type delta fixnum)
(check-type bignum bignum)
(macrolet
((do-it ()
`(with-inline-assembly (:returns :eax :labels (add-bignum-loop add-bignum-done))
(:load-lexical (:lexical-binding delta) :ecx)
(:load-lexical (:lexical-binding bignum) :eax)
(:sarl ,movitz:+movitz-fixnum-shift+ :ecx)
(:jns 'positive-delta)
(:negl :ecx)
(:subl :ecx (:eax ,(bt:slot-offset 'movitz::movitz-bignum 'movitz::bigit0)))
(:jnc 'add-bignum-done)
sub-bignum-loop
(:addl 4 :edx)
(:cmpl :edx :ebx)
(:je '(:sub-program (overflow) (:int 4)))
(:subl 1 (:eax :edx ,(bt:slot-offset 'movitz::movitz-bignum 'movitz::bigit0)))
(:jc 'sub-bignum-loop)
(:jmp 'add-bignum-done)
positive-delta
(:addl :ecx (:eax ,(bt:slot-offset 'movitz::movitz-bignum 'movitz::bigit0)))
(:jnc 'add-bignum-done)
add-bignum-loop
(:addl 4 :edx)
(:cmpl :edx :ebx)
(:je '(:sub-program (overflow) (:int 4)))
(:addl 1 (:eax :edx ,(bt:slot-offset 'movitz::movitz-bignum 'movitz::bigit0)))
(:jc 'add-bignum-loop)
add-bignum-done)))
(do-it)))
(defun bignum-addf (bignum delta)
"Destructively add (abs delta) to bignum."
(check-type bignum bignum)
(etypecase delta
(positive-fixnum
(bignum-addf-fixnum bignum delta))
(negative-fixnum
(bignum-addf-fixnum bignum (- delta)))
(bignum
(macrolet
((do-it ()
`(with-inline-assembly (:returns :eax)
not-size1
EAX = bignum
EBX = delta
add-bignum-loop
(:addl (:ebx :edx (:offset movitz-bignum :bigit0))
:ecx)
(:cmpw :dx (:eax (:offset movitz-bignum length)))
(:jbe '(:sub-program (overflow) (:int 4)))
(:addl :ecx (:eax :edx (:offset movitz-bignum bigit0)))
carry+digit-overflowed
(:sbbl :ecx :ecx)
ECX = Add 's Carry .
(:addl 4 :edx)
(:cmpw :dx (:ebx (:offset movitz-bignum length)))
(:ja 'add-bignum-loop)
(:jecxz 'add-bignum-done)
carry-propagate-loop
(:cmpw :dx (:eax (:offset movitz-bignum length)))
(:jbe '(:sub-program (overflow) (:int 4)))
(:addl 4 :edx)
(:addl 1 (:eax :edx (:offset movitz-bignum bigit0 -4)))
(:jc 'carry-propagate-loop)
add-bignum-done)))
(do-it)))))
(defun bignum-subf (bignum delta)
"Destructively subtract (abs delta) from bignum."
(check-type bignum bignum)
(etypecase delta
(positive-fixnum
(bignum-addf-fixnum bignum (- delta)))
(negative-fixnum
(bignum-addf-fixnum bignum delta))
(bignum
(macrolet
((do-it ()
`(with-inline-assembly (:returns :eax)
not-size1
EAX = bignum
EBX = delta
sub-bignum-loop
(:cmpw :dx (:eax (:offset movitz-bignum length)))
(:jbe '(:sub-program (overflow) (:int 4)))
(:addl (:ebx :edx (:offset movitz-bignum :bigit0))
:ecx)
(:subl :ecx (:eax :edx (:offset movitz-bignum bigit0)))
carry+digit-overflowed
(:sbbl :ecx :ecx)
ECX = Add 's Carry .
(:addl 4 :edx)
(:cmpw :dx (:ebx (:offset movitz-bignum length)))
(:ja 'sub-bignum-loop)
(:jecxz 'sub-bignum-done)
carry-propagate-loop
(:cmpw :dx (:eax (:offset movitz-bignum length)))
(:jbe '(:sub-program (overflow) (:int 4)))
(:addl 4 :edx)
(:subl 1 (:eax :edx (:offset movitz-bignum bigit0 -4)))
(:jc 'carry-propagate-loop)
sub-bignum-done)))
(do-it)))))
(defun bignum-shift-rightf (bignum count)
"Destructively right-shift bignum by count bits."
(check-type bignum bignum)
(check-type count positive-fixnum)
(multiple-value-bind (long-shift short-shift)
(truncate count 32)
(macrolet
((do-it ()
`(with-inline-assembly (:returns :ebx)
(:compile-two-forms (:edx :ebx) long-shift bignum)
(:xorl :eax :eax)
shift-long-loop
(:cmpw :dx (:ebx (:offset movitz-bignum length)))
(:jbe 'zero-msb-loop)
(:movl (:ebx :edx (:offset movitz-bignum bigit0)) :ecx)
(:movl :ecx (:ebx :eax (:offset movitz-bignum bigit0)))
(:addl 4 :eax)
(:addl 4 :edx)
(:jmp 'shift-long-loop)
zero-msb-loop
(:cmpw :ax (:ebx (:offset movitz-bignum length)))
(:jbe 'long-shift-done)
(:movl 0 (:ebx :eax (:offset movitz-bignum bigit0)))
(:addl 4 :eax)
(:jmp 'zero-msb-loop)
long-shift-done
(:compile-form (:result-mode :ecx) short-shift)
We need to use EAX for u32 storage .
(:shrl ,movitz:+movitz-fixnum-shift+ :ecx)
(:std)
shift-short-loop
(:addl 4 :edx)
(:cmpw :dx (:ebx (:offset movitz-bignum length)))
(:jbe 'end-shift-short-loop)
(:movl (:ebx :edx (:offset movitz-bignum bigit0))
:eax)
(:shrdl :cl :eax
(:ebx :edx (:offset movitz-bignum bigit0 -4)))
(:jmp 'shift-short-loop)
end-shift-short-loop
(:shrl :cl (:ebx :edx (:offset movitz-bignum bigit0 -4)))
(:cld))))
(do-it))))
(defun bignum-shift-leftf (bignum count)
"Destructively left-shift bignum by count bits."
(check-type bignum bignum)
(check-type count positive-fixnum)
(multiple-value-bind (long-shift short-shift)
(truncate count 32)
(macrolet
((do-it ()
`(with-inline-assembly (:returns :ebx)
(:compile-two-forms (:ecx :ebx) long-shift bignum)
(:jecxz 'long-shift-done)
(:xorl :eax :eax)
(:movw (:ebx (:offset movitz-bignum length)) :ax)
(:movl :eax :edx)
overflow-check-loop
(:cmpl 0 (:ebx :edx (:offset movitz-bignum bigit0)))
(:jne '(:sub-program (overflow) (:int 4)))
(:subl 4 :edx)
(:subl 4 :ecx)
(:jnz 'overflow-check-loop)
(:jc '(:sub-program (overflow) (:int 4)))
shift-long-loop
(:movl (:ebx :edx (:offset movitz-bignum bigit0)) :ecx)
(:movl :ecx (:ebx :eax (:offset movitz-bignum bigit0)))
(:subl 4 :eax)
(:subl 4 :edx)
(:jnc 'shift-long-loop)
zero-lsb-loop
(:subl 4 :eax)
(:jnc 'zero-lsb-loop)
long-shift-done
(:compile-form (:result-mode :ecx) short-shift)
(:shrl ,movitz:+movitz-fixnum-shift+ :ecx)
(:jz 'done)
(:movw (:ebx (:offset movitz-bignum length)) :si)
(:subl 4 :esi)
(:jz 'shift-short-lsb)
(:xorl :eax :eax)
(:std)
(:movl (:ebx :esi (:offset movitz-bignum bigit0))
:eax)
(:xorl :edx :edx)
(:shldl :cl :eax :edx)
(:jnz 'overflow)
shift-short-loop
(:movl (:ebx :esi (:offset movitz-bignum bigit0 -4))
:eax)
(:shldl :cl :eax (:ebx :esi (:offset movitz-bignum bigit0)))
(:subl 4 :esi)
(:jnz 'shift-short-loop)
(:movl :edi :edx)
(:cld)
shift-short-lsb
(:shll :cl (:ebx (:offset movitz-bignum bigit0)))
done
(:movl (:ebp -4) :esi)
)))
(do-it))))
(defun bignum-mulf (bignum factor)
"Destructively multiply bignum by (abs factor)."
(check-type bignum bignum)
(etypecase factor
(bignum
(error "not yet"))
(negative-fixnum
(bignum-mulf bignum (- factor)))
(positive-fixnum
(macrolet
((do-it ()
`(with-inline-assembly (:returns :ebx)
(:compile-form (:result-mode :ecx) factor)
(:sarl ,movitz:+movitz-fixnum-shift+ :ecx)
(:locally (:movl :ecx (:edi (:edi-offset raw-scratch0))))
Counter ( by 4 )
Make EAX , EDX non - GC - roots .
multiply-loop
(:movl (:ebx :esi (:offset movitz-bignum bigit0))
:eax)
Save carry in ECX
EDX : EAX = scratch0*EAX
Compute next carry
(:jc '(:sub-program (should-not-happen) (:int 63)))
(:movl :eax (:ebx :esi (:offset movitz-bignum bigit0)))
(:addl 4 :esi)
(:cmpw :si (:ebx (:offset movitz-bignum length)))
(:ja 'multiply-loop)
Carry into ECX
(:movl :edi :eax)
(:movl :edi :edx)
(:cld)
(:movl (:ebp -4) :esi)
(:jnz '(:sub-program (overflow) (:int 4)))
)))
(do-it)))))
(defun bignum-truncatef (bignum divisor)
(etypecase divisor
(positive-fixnum
(macrolet
((do-it ()
`(with-inline-assembly (:returns :ebx)
(:compile-two-forms (:ebx :ecx) bignum divisor)
(:sarl ,movitz:+movitz-fixnum-shift+ :ecx)
ESI is counter by 4
(:movw (:ebx (:offset movitz-bignum length)) :si)
(:std)
divide-loop
(:movl (:ebx :esi (:offset movitz-bignum bigit0 -4))
EDX : EAX = EDX : EAX / ECX
(:movl :eax (:ebx :esi (:offset movitz-bignum bigit0 -4)))
(:subl 4 :esi)
(:jnz 'divide-loop)
(:movl (:ebp -4) :esi)
(:movl :edi :edx)
(:movl :ebx :eax)
(:cld))))
(do-it)))))
(defun bignum-set-zerof (bignum)
(check-type bignum bignum)
(dotimes (i (%bignum-bigits bignum))
(setf (memref bignum (movitz-type-slot-offset 'movitz-bignum 'bigit0)
:index i :type :unsigned-byte32) 0))
bignum)
(defun %bignum= (x y)
(check-type x bignum)
(check-type y bignum)
(compiler-macro-call %bignum= x y))
(defun %bignum< (x y)
(check-type x bignum)
(check-type y bignum)
(compiler-macro-call %bignum< x y))
(defun %bignum-zerop (x)
(compiler-macro-call %bignum-zerop x))
(defun bignum-integer-length (x)
"Compute (integer-length (abs x))."
(check-type x bignum)
(macrolet
((do-it ()
`(with-inline-assembly (:returns :eax)
(:compile-form (:result-mode :ebx) x)
(:movzxw (:ebx (:offset movitz-bignum length))
:edx)
(:xorl :eax :eax)
bigit-scan-loop
(:subl 4 :edx)
(:jc 'done)
(:cmpl 0 (:ebx :edx (:offset movitz-bignum bigit0)))
(:jz 'bigit-scan-loop)
Now , EAX must be loaded with ( + ( * EDX 32 ) bit - index 1 ) .
Factor 8
(:bsrl (:ebx :edx (:offset movitz-bignum bigit0))
:ecx)
Factor 4
(:leal ((:ecx 4) :eax 4) :eax)
done)))
(do-it)))
(defun bignum-logcount (x)
"Compute (logcount (abs x))."
(check-type x bignum)
(macrolet
((do-it ()
`(with-inline-assembly (:returns :eax)
(:compile-form (:result-mode :ebx) x)
(:xorl :eax :eax)
(:xorl :edx :edx)
(:movw (:ebx (:offset movitz-bignum length)) :dx)
word-loop
(:movl (:ebx :edx (:offset movitz-bignum bigit0 -4)) :ecx)
bit-loop
(:jecxz 'end-bit-loop)
(:shrl 1 :ecx)
(:jnc 'bit-loop)
(:addl ,movitz:+movitz-fixnum-factor+ :eax)
(:jmp 'bit-loop)
end-bit-loop
(:subl 4 :edx)
(:jnz 'word-loop))))
(do-it)))
(defun %bignum-negate (x)
(compiler-macro-call %bignum-negate x))
(defun %bignum-plus-fixnum-size (x fixnum-delta)
(compiler-macro-call %bignum-plus-fixnum-size x fixnum-delta))
(defun bignum-notf (x)
(check-type x bignum)
(macrolet
((do-it ()
`(with-inline-assembly (:returns :eax)
(:load-lexical (:lexical-binding x) :eax)
(:xorl :edx :edx)
(:xorl :ecx :ecx)
(:movw (:eax (:offset movitz-bignum length)) :cx)
loop
(:notl (:eax :edx (:offset movitz-bignum bigit0)))
(:addl 4 :edx)
(:cmpl :edx :ecx)
(:ja 'loop))))
(do-it)))
|
223758094e463d639b2a1d09e4b3ffa55f2fa4e9fca562b67190f24909cdf23d | ambuc/pipes | Types.hs | # LANGUAGE TemplateHaskell #
module Types where
import qualified Data.Array
import qualified Lens.Micro.TH
data Difficulty = Easy | Mid | Hard deriving (Eq)
data Dir = N | E | W | S
data FlowDir = In | Out deriving (Eq, Show)
type Tile = (Bool, Bool, Bool, Bool) -- N E W S
type Flow = (FlowDir, FlowDir, FlowDir, FlowDir) -- N E W S
data Square = Square { _tile :: Tile
, _flow :: Maybe Flow
, _distance :: Maybe Int
, _hascursor :: Bool
, _isborder :: Bool
} deriving (Show)
type Board = Data.Array.Array (Int, Int) Square -- (Y, X)
data GameState = GameState { _board :: Board
, _tap :: (Int, Int) -- (Y, X)
, _drain :: (Int, Int) -- (Y, X)
, _cursor :: (Int, Int) -- (Y, X)
, _time :: Int -- tick time
, _timer :: Int -- game time
, _over :: Bool
, _maxdist :: Int
, _moves :: Int
, _difficulty :: Difficulty
}
Lens.Micro.TH.makeLenses ''Square
Lens.Micro.TH.makeLenses ''GameState
| null | https://raw.githubusercontent.com/ambuc/pipes/92cd66b4036c8e64d44171c546fe6f5d8858d738/src/Types.hs | haskell | N E W S
N E W S
(Y, X)
(Y, X)
(Y, X)
(Y, X)
tick time
game time | # LANGUAGE TemplateHaskell #
module Types where
import qualified Data.Array
import qualified Lens.Micro.TH
data Difficulty = Easy | Mid | Hard deriving (Eq)
data Dir = N | E | W | S
data FlowDir = In | Out deriving (Eq, Show)
data Square = Square { _tile :: Tile
, _flow :: Maybe Flow
, _distance :: Maybe Int
, _hascursor :: Bool
, _isborder :: Bool
} deriving (Show)
data GameState = GameState { _board :: Board
, _over :: Bool
, _maxdist :: Int
, _moves :: Int
, _difficulty :: Difficulty
}
Lens.Micro.TH.makeLenses ''Square
Lens.Micro.TH.makeLenses ''GameState
|
785a366bb283a7f0ea6b65515bf8a625c2d636a25d681d560e1708c01da3f742 | backtracking/bibtex2html | latexmacros.ml | (**************************************************************************)
(* bibtex2html - A BibTeX to HTML translator *)
Copyright ( C ) 1997 - 2014 and
(* *)
(* This software is free software; you can redistribute it and/or *)
modify it under the terms of the GNU General Public
License version 2 , as published by the Free Software Foundation .
(* *)
(* This software 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 version 2 for more details
(* (enclosed in the file GPL). *)
(**************************************************************************)
This code is an adaptation of a code written by in
1995 - 1997 , in his own made latex2html translator . See
@inproceedings{Leroy - latex2html ,
author = " " ,
title = " Lessons learned from the translation of
documentation from \LaTeX\ to { HTML } " ,
booktitle = " ERCIM / W4 G Int . Workshop on WWW
Authoring and Integration Tools " ,
year = 1995 ,
month = feb }
1995-1997, in his own made latex2html translator. See
@inproceedings{Leroy-latex2html,
author = "Xavier Leroy",
title = "Lessons learned from the translation of
documentation from \LaTeX\ to {HTML}",
booktitle = "ERCIM/W4G Int. Workshop on WWW
Authoring and Integration Tools",
year = 1995,
month = feb}
*)
open Printf
open Options
(*s Output functions. *)
let out_channel = ref stdout
let print_s s = output_string !out_channel s
let print_c c = output_char !out_channel c
(*s Actions and translations table. *)
type action =
| Print of string
| Print_arg
| Skip_arg
| Raw_arg of (string -> unit)
| Parameterized of (string -> action list)
r piece of LaTeX to analyze recursively
let cmdtable = (Hashtbl.create 19 : (string, action list) Hashtbl.t)
let def name action =
Hashtbl.add cmdtable name action
let find_macro name =
try
Hashtbl.find cmdtable name
with Not_found ->
if not !quiet then eprintf "Unknown macro: %s\n" name;
[]
;;
s Translations of general LaTeX macros .
(* Sectioning *)
def "\\part"
[Print "<H0>"; Print_arg; Print "</H0>\n"];
def "\\chapter"
[Print "<H1>"; Print_arg; Print "</H1>\n"];
def "\\chapter*"
[Print "<H1>"; Print_arg; Print "</H1>\n"];
def "\\section"
[Print "<H2>"; Print_arg; Print "</H2>\n"];
def "\\section*"
[Print "<H2>"; Print_arg; Print "</H2>\n"];
def "\\subsection"
[Print "<H3>"; Print_arg; Print "</H3>\n"];
def "\\subsection*"
[Print "<H3>"; Print_arg; Print "</H3>\n"];
def "\\subsubsection"
[Print "<H4>"; Print_arg; Print "</H4>\n"];
def "\\subsubsection*"
[Print "<H4>"; Print_arg; Print "</H4>\n"];
def "\\paragraph"
[Print "<H5>"; Print_arg; Print "</H5>\n"];
(* Text formatting *)
def "\\begin{alltt}" [Print "<pre>"];
def "\\end{alltt}" [Print "</pre>"];
def "\\textbf" [Print "<b>" ; Print_arg ; Print "</b>"];
def "\\mathbf" [Print "<b>" ; Print_arg ; Print "</b>"];
def "\\texttt" [Print "<tt>" ; Print_arg ; Print "</tt>"];
def "\\mathtt" [Print "<tt>" ; Print_arg ; Print "</tt>"];
def "\\textit" [Print "<i>" ; Print_arg ; Print "</i>"];
def "\\mathit" [Print "<i>" ; Print_arg ; Print "</i>"];
def "\\textsl" [Print "<i>" ; Print_arg ; Print "</i>"];
def "\\textem" [Print "<em>" ; Print_arg ; Print "</em>"];
def "\\textrm" [Print_arg];
def "\\mathrm" [Print_arg];
def "\\textmd" [Print_arg];
def "\\textup" [Print_arg];
def "\\textnormal" [Print_arg];
def "\\mathnormal" [Print "<i>" ; Print_arg ; Print "</i>"];
def "\\mathcal" [Print_arg];
def "\\mathbb" [Print_arg];
def "\\mathfrak" [Print_arg];
def "\\textin" [Print "<sub>"; Print_arg; Print "</sub>"];
def "\\textsu" [Print "<sup>"; Print_arg; Print "</sup>"];
def "\\textsuperscript" [Print "<sup>"; Print_arg; Print "</sup>"];
def "\\textsi" [Print "<i>" ; Print_arg ; Print "</i>"];
(* Basic color support. *)
def "\\textcolor" [ Parameterized (function name ->
match String.lowercase_ascii name with
At the moment , we support only the 16 named colors defined in HTML 4.01 .
| "black" | "silver" | "gray" | "white" | "maroon" | "red" | "purple" | "fuchsia"
| "green" | "lime" | "olive" | "yellow" | "navy" | "blue" | "teal" | "aqua" ->
[ Print (Printf.sprintf "<font color=%s>" name);
Print_arg ;
Print "</font>"
]
(* Other, unknown colors have no effect. *)
| _ ->
[ Print_arg ]
)];
(* Fonts without HTML equivalent *)
def "\\textsf" [Print "<b>" ; Print_arg ; Print "</b>"];
def "\\mathsf" [Print "<b>" ; Print_arg ; Print "</b>"];
def "\\textsc" [Print_arg];
def "\\textln" [Print_arg];
def "\\textos" [Print_arg];
def "\\textdf" [Print_arg];
def "\\textsw" [Print_arg];
def "\\rm" [];
def "\\cal" [];
def "\\emph" [Print "<em>" ; Print_arg ; Print "</em>"];
def "\\mbox" [Print_arg];
def "\\footnotesize" [];
def "\\etalchar" [ Print "<sup>" ; Raw_arg print_s ; Print "</sup>" ];
def "\\newblock" [Print " "];
(* Environments *)
def "\\begin{itemize}" [Print "<p><ul>"];
def "\\end{itemize}" [Print "</ul>"];
def "\\begin{enumerate}" [Print "<p><ol>"];
def "\\end{enumerate}" [Print "</ol>"];
def "\\begin{description}" [Print "<p><dl>"];
def "\\end{description}" [Print "</dl>"];
def "\\begin{center}" [Print "<blockquote>"];
def "\\end{center}" [Print "</blockquote>"];
def "\\begin{htmlonly}" [];
def "\\end{htmlonly}" [];
def "\\begin{flushleft}" [Print "<blockquote>"];
def "\\end{flushleft}" [Print "</blockquote>"];
(* Special characters *)
def "\\ " [Print " "];
def "\\\n" [Print " "];
def "\\{" [Print "{"];
def "\\}" [Print "}"];
def "\\l" [Print "l"];
def "\\L" [Print "L"];
def "\\oe" [Print "œ"];
def "\\OE" [Print "Œ"];
def "\\o" [Print "ø"];
def "\\O" [Print "Ø"];
def "\\ae" [Print "æ"];
def "\\AE" [Print "Æ"];
def "\\aa" [Print "å"];
def "\\AA" [Print "Å"];
def "\\i" [Print "i"];
def "\\j" [Print "j"];
def "\\&" [Print "&"];
def "\\$" [Print "$"];
def "\\%" [Print "%"];
def "\\_" [Print "_"];
def "\\slash" [Print "/"];
def "\\copyright" [Print "(c)"];
def "\\th" [Print "þ"];
def "\\TH" [Print "Þ"];
def "\\dh" [Print "ð"];
def "\\DH" [Print "Ð"];
def "\\dj" [Print "đ"];
def "\\DJ" [Print "Đ"];
def "\\ss" [Print "ß"];
def "\\rq" [Print "’"];
def "\\spadesuit" [Print "♠"];
def "\\heartsuit" [Print "♡"];
def "\\diamondsuit" [Print "♢"];
def "\\clubsuit" [Print "♣"];
def "\\flat" [Print "♭"];
def "\\natural" [Print "♮"];
def "\\sharp" [Print "♯"];
def "\\'" [Raw_arg(function "e" -> print_s "é"
| "E" -> print_s "É"
| "a" -> print_s "á"
| "A" -> print_s "Á"
| "o" -> print_s "ó"
| "O" -> print_s "Ó"
| "i" -> print_s "í"
| "\\i" -> print_s "í"
| "I" -> print_s "Í"
| "u" -> print_s "ú"
| "U" -> print_s "Ú"
| "'" -> print_s "”"
| "c" -> print_s "ć"
| "C" -> print_s "Ć"
| "g" -> print_s "ǵ"
| "G" -> print_s "G"
| "l" -> print_s "ĺ"
| "L" -> print_s "Ĺ"
| "n" -> print_s "ń"
| "N" -> print_s "Ń"
| "r" -> print_s "ŕ"
| "R" -> print_s "Ŕ"
| "s" -> print_s "ś"
| "S" -> print_s "Ś"
| "y" -> print_s "ý"
| "Y" -> print_s "Ý"
| "z" -> print_s "Ź"
| "Z" -> print_s "ź"
| "" -> print_c '\''
| s -> print_s s ; print_s "́")];
def "\\`" [Raw_arg(function "e" -> print_s "è"
| "E" -> print_s "È"
| "a" -> print_s "à"
| "A" -> print_s "À"
| "o" -> print_s "ò"
| "O" -> print_s "Ò"
| "i" -> print_s "ì"
| "\\i" -> print_s "ì"
| "I" -> print_s "Ì"
| "u" -> print_s "ù"
| "U" -> print_s "Ù"
| "`" -> print_s "“"
| "" -> print_s "‘"
| s -> print_s s ; print_s "̀")];
def "\\~" [Raw_arg(function "n" -> print_s "ñ"
| "N" -> print_s "Ñ"
| "o" -> print_s "õ"
| "O" -> print_s "Õ"
| "i" -> print_s "ĩ"
| "\\i" -> print_s "ĩ"
| "I" -> print_s "Ĩ"
| "a" -> print_s "ã"
| "A" -> print_s "Ã"
| "u" -> print_s "ũ"
| "U" -> print_s "Ũ"
| "" -> print_s "˜"
| s -> print_s s ; print_s "̃")];
def "\\=" [Raw_arg(function s -> print_s s ; print_s "̄")];
def "\\k" [Raw_arg(function "A" -> print_s "Ą"
| "a" -> print_s "ą"
| "i" -> print_s "Į"
| "I" -> print_s "į"
| s -> print_s s)];
def "\\c" [Raw_arg(function "c" -> print_s "ç"
| "C" -> print_s "Ç"
| s -> print_s s)];
def "\\^" [Raw_arg(function "a" -> print_s "â"
| "A" -> print_s "Â"
| "e" -> print_s "ê"
| "E" -> print_s "Ê"
| "i" -> print_s "î"
| "\\i" -> print_s "î"
| "I" -> print_s "Î"
| "o" -> print_s "ô"
| "O" -> print_s "Ô"
| "u" -> print_s "û"
| "U" -> print_s "Û"
| "w" -> print_s "ŵ"
| "W" -> print_s "Ŵ"
| "y" -> print_s "ŷ"
| "Y" -> print_s "Ŷ"
| "" -> print_c '^'
| "j" -> print_s "ȷ̂"
| s -> print_s s ; print_s "̂")];
def "\\c" [Raw_arg(function "C" -> print_s "Ç" (* cedilla accent *)
| "C" -> print_s "Ç"
| "c" -> print_s "ç"
| "D" -> print_s "Ḑ"
| "d" -> print_s "ḑ"
| "E" -> print_s "Ȩ"
| "e" -> print_s "ȩ"
| "G" -> print_s "Ģ"
| "g" -> print_s "ģ"
| "H" -> print_s "Ḩ"
| "h" -> print_s "ḩ"
| "K" -> print_s "Ķ"
| "k" -> print_s "ķ"
| "L" -> print_s "Ļ"
| "l" -> print_s "ļ"
| "N" -> print_s "Ņ"
| "n" -> print_s "ņ"
| "R" -> print_s "Ŗ"
| "r" -> print_s "ŗ"
| "S" -> print_s "Ş"
| "s" -> print_s "ş"
| "T" -> print_s "Ţ"
| "t" -> print_s "ţ"
| s -> print_s s ; print_s "̧")];
def "\\d" [Raw_arg(function "A" -> print_s "Ạ" (* dot-under accent *)
| "a" -> print_s "ạ"
| "B" -> print_s "Ḅ"
| "b" -> print_s "ḅ"
| "D" -> print_s "Ḍ"
| "d" -> print_s "ḍ"
| "E" -> print_s "Ẹ"
| "e" -> print_s "ẹ"
| "H" -> print_s "Ḥ"
| "h" -> print_s "ḥ"
| "I" -> print_s "Ị"
| "i" -> print_s "ị"
| "K" -> print_s "Ḳ"
| "k" -> print_s "ḳ"
| "L" -> print_s "Ḷ"
| "l" -> print_s "ḷ"
| "M" -> print_s "Ṃ"
| "m" -> print_s "ṃ"
| "N" -> print_s "Ṇ"
| "n" -> print_s "ṇ"
| "O" -> print_s "Ọ"
| "o" -> print_s "ọ"
| "R" -> print_s "Ṛ"
| "r" -> print_s "ṛ"
| "S" -> print_s "Ṣ"
| "s" -> print_s "ṣ"
| "T" -> print_s "Ṭ"
| "t" -> print_s "ṭ"
| "U" -> print_s "Ụ"
| "u" -> print_s "ụ"
| "V" -> print_s "Ṿ"
| "v" -> print_s "ṿ"
| "W" -> print_s "Ẉ"
| "w" -> print_s "ẉ"
| "Y" -> print_s "Ỵ"
| "y" -> print_s "ỵ"
| "Z" -> print_s "Ẓ"
| "z" -> print_s "ẓ"
| s -> print_s s ; print_s "̣")];
def "\\b" [Raw_arg(function "B" -> print_s "Ḇ" (* bar-under accent *)
| "b" -> print_s "ḇ"
| "D" -> print_s "Ḏ"
| "d" -> print_s "ḏ"
| "h" -> print_s "ẖ"
| "K" -> print_s "Ḵ"
| "k" -> print_s "ḵ"
| "L" -> print_s "Ḻ"
| "l" -> print_s "ḻ"
| "N" -> print_s "Ṉ"
| "n" -> print_s "ṉ"
| "R" -> print_s "Ṟ"
| "r" -> print_s "ṟ"
| "T" -> print_s "Ṯ"
| "t" -> print_s "ṯ"
| "Z" -> print_s "Ẕ"
| "z" -> print_s "ẕ"
| s -> print_s s ; print_s "̱")];
def "\\t" [Raw_arg(function s -> print_s s ; print_s "͡")]; (* tie-after accent *)
def "\\tilde" [Raw_arg (function "i" -> print_s "<em>ĩ</em>"
| "j" -> print_s "<em>ȷ̃</em>"
| s -> print_s "<em>" ; print_s s ; print_s "̃</em>")];
def "\\bar" [Raw_arg (function "i" -> print_s "<em>ı̄</em>"
| "j" -> print_s "<em>ȷ̄</em>"
| s -> print_s "<em>" ; print_s s ; print_s "̄</em>")];
def "\\overbar" [Raw_arg (function "i" -> print_s "<em>ı̅</em>"
| "j" -> print_s "<em>ȷ̅</em>"
| s -> print_s "<em>" ; print_s s ; print_s "̅</em>")];
def "\\vec" [Raw_arg (function "i" -> print_s "<em>ı⃗</em>"
| "j" -> print_s "<em>ȷ⃗</em>"
| s -> print_s "<em>" ; print_s s ; print_s "⃗</em>")];
def "\\overrightarrow" [Raw_arg (function "i" -> print_s "<em>ı⃗</em>"
| "j" -> print_s "<em>ȷ⃗</em>"
| s -> print_s "<em>" ; print_s s ; print_s "⃗</em>")];
def "\\overleftarrow" [Raw_arg (function "i" -> print_s "<em>ı⃖</em>"
| "j" -> print_s "<em>ȷ⃖</em>"
| s -> print_s "<em>" ; print_s s ; print_s "⃖</em>")];
def "\\grave" [Raw_arg(function s -> print_s "<em>" ; print_s s ; print_s "̀</em>")];
def "\\acute" [Raw_arg(function s -> print_s "<em>" ; print_s s ; print_s "́</em>")];
def "\\hat" [Raw_arg(function "a" -> print_s "<em>â</em>"
| "A" -> print_s "<em>Â</em>"
| "e" -> print_s "<em>ê</em>"
| "E" -> print_s "<em>Ê</em>"
| "i" -> print_s "<em>î</em>"
| "\\i" -> print_s "<em>î</em>"
| "I" -> print_s "<em>Î</em>"
| "o" -> print_s "<em>ô</em>"
| "O" -> print_s "<em>Ô</em>"
| "u" -> print_s "<em>û</em>"
| "U" -> print_s "<em>Û</em>"
| "" -> print_c '^'
| s -> print_s "<em>" ; print_s s ; print_s "̂</em>")];
def "\\breve" [Raw_arg(function "a" -> print_s "<em>ă</em>"
| "A" -> print_s "<em>Ă</em>"
| "u" -> print_s "<em>ŭ</em>"
| "U" -> print_s "<em>Ŭ</em>"
| "" -> print_c '^'
| s -> print_s "<em>" ; print_s s ; print_s "̆</em>")];
def "\\dot" [Raw_arg(function "C" -> print_s "<em>Ċ</em>"
| "c" -> print_s "<em>ċ</em>"
| "e" -> print_s "<em>ė</em>"
| "E" -> print_s "<em>Ė</em>"
| "g" -> print_s "<em>ġ</em>"
| "G" -> print_s "<em>Ġ</em>"
| "I" -> print_s "<em>İ</em>"
| "Z" -> print_s "<em>Ż</em>"
| "z" -> print_s "<em>ż</em>"
| "" -> print_s "<em>˙</em>"
| s -> print_s "<em>" ; print_s s ; print_s "̇</em>")];
def "\\ddot" [Raw_arg(function "i" -> print_s "<em>ı̈</em>"
| "j" -> print_s "<em>ȷ̈</em>"
| s -> print_s "<em>" ; print_s s ; print_s "̈</em>")];
def "\\check" [Raw_arg(function "C" -> print_s "<em>Č</em>"
| "c" -> print_s "<em>č</em>"
| "D" -> print_s "<em>Ď</em>"
| "d" -> print_s "<em>ď</em>"
| "E" -> print_s "<em>Ě</em>"
| "e" -> print_s "<em>ě</em>"
| "L" -> print_s "<em>Ľ</em>"
| "l" -> print_s "<em>ľ</em>"
| "N" -> print_s "<em>Ň</em>"
| "n" -> print_s "<em>ň</em>"
| "R" -> print_s "<em>Ř</em>"
| "r" -> print_s "<em>ř</em>"
| "S" -> print_s "<em>Š</em>"
| "s" -> print_s "<em>š</em>"
| "T" -> print_s "<em>Ť</em>"
| "t" -> print_s "<em>ť</em>"
| "Z" -> print_s "<em>Ž</em>"
| "z" -> print_s "<em>ž</em>"
| "" -> print_s "<em>ˇ</em>"
| s -> print_s "<em>" ; print_s s ; print_s "̌</em>")];
def "\\\"" [Raw_arg(function "e" -> print_s "ë"
| "E" -> print_s "Ë"
| "a" -> print_s "ä"
| "A" -> print_s "Ä"
| "\\i" -> print_s "ï"
| "i" -> print_s "ï"
| "I" -> print_s "Ï"
| "o" -> print_s "ö"
| "O" -> print_s "Ö"
| "u" -> print_s "ü"
| "U" -> print_s "Ü"
| "y" -> print_s "ÿ"
| "Y" -> print_s "Ÿ"
| s -> print_s s ; print_s "̈")];
def "\\d" [Raw_arg print_s ];
def "\\." [Raw_arg (function "a" -> print_s "ȧ"
| "A" -> print_s "Ȧ"
| "c" -> print_s "ċ"
| "C" -> print_s "Ċ"
| "e" -> print_s "ė"
| "E" -> print_s "Ė"
| "g" -> print_s "ġ"
| "G" -> print_s "Ġ"
| "i" -> print_s "i"
| "\\i" -> print_s "i"
| "I" -> print_s "İ"
| "o" -> print_s "ȯ"
| "O" -> print_s "Ȯ"
| "z" -> print_s "ż"
| "Z" -> print_s "Ż"
| s -> print_s s ; print_s "̇")];
def "\\u" [Raw_arg(function "a" -> print_s "ă"
| "A" -> print_s "Ă"
| "e" -> print_s "ĕ"
| "E" -> print_s "Ĕ"
| "i" -> print_s "ĭ"
| "\\i" -> print_s "ĭ"
| "I" -> print_s "Ĭ"
| "g" -> print_s "ğ"
| "G" -> print_s "Ğ"
| "o" -> print_s "ŏ"
| "O" -> print_s "Ŏ"
| "u" -> print_s "ŭ"
| "U" -> print_s "Ŭ"
| s -> print_s s ; print_s "̆")];
def "\\v" [Raw_arg(function
| "C" -> print_s "Č"
| "c" -> print_s "č"
| "D" -> print_s "Ď"
| "d" -> print_s "ď"
| "E" -> print_s "Ě"
| "e" -> print_s "ě"
| "N" -> print_s "Ň"
| "n" -> print_s "ň"
| "r" -> print_s "ř"
| "R" -> print_s "Ř"
| "s" -> print_s "š" (*"š"*)
| "S" -> print_s "Š" (*"Š"*)
| "T" -> print_s "Ť"
| "t" -> print_s "ť"
| "\\i" -> print_s "ĭ"
| "i" -> print_s "ĭ"
| "I" -> print_s "Ĭ"
| "Z" -> print_s "Ž"
| "z" -> print_s "ž"
| s -> print_s s ; print_s "̌")];
def "\\H" [Raw_arg (function
| "O" -> print_s "Ő"
| "o" -> print_s "ő"
| "U" -> print_s "Ű"
| "u" -> print_s "ű"
| s -> print_s s ; print_s "̋")];
def "\\r" [Raw_arg (function
| "U" -> print_s "Ů"
| "u" -> print_s "ů"
| s -> print_s s)];
(* Math macros *)
def "\\[" [Print "<blockquote>"];
def "\\]" [Print "\n</blockquote>"];
def "\\le" [Print "<="];
def "\\leq" [Print "<="];
def "\\log" [Print "log "];
def "\\ge" [Print ">="];
def "\\geq" [Print ">="];
def "\\neq" [Print "<>"];
def "\\circ" [Print "o"];
def "\\bigcirc" [Print "O"];
def "\\sim" [Print "~"];
def "\\(" [Print "<I>"];
def "\\)" [Print "</I>"];
def "\\mapsto" [Print "<tt>|-></tt>"];
def "\\times" [Print "×"];
def "\\neg" [Print "¬"];
def "\\frac" [Print "("; Print_arg; Print ")/("; Print_arg; Print ")"];
def "\\not" [Print "not "];
def "\\arccos" [Print "arccos "];
def "\\arcsin" [Print "arcsin "];
def "\\arctan" [Print "arctan "];
def "\\arg" [Print "arg "];
def "\\cos" [Print "cos "];
def "\\cosh" [Print "cosh "];
def "\\coth" [Print "coth "];
def "\\cot" [Print "cot "];
def "\\csc" [Print "csc "];
def "\\deg" [Print "deg "];
def "\\det" [Print "det "];
def "\\dim" [Print "dim "];
def "\\exp" [Print "exp "];
def "\\gcd" [Print "gcd "];
def "\\hom" [Print "hom "];
def "\\inf" [Print "inf "];
def "\\ker" [Print "ker "];
def "\\lg" [Print "lg "];
def "\\lim" [Print "lim "];
def "\\liminf" [Print "liminf "];
def "\\limsup" [Print "limsup "];
def "\\ln" [Print "ln "];
def "\\max" [Print "max "];
def "\\min" [Print "min "];
def "\\Pr" [Print "Pr "];
def "\\sec" [Print "sec "];
def "\\sin" [Print "sin "];
def "\\sinh" [Print "sinh "];
def "\\sup" [Print "sup "];
def "\\tanh" [Print "tanh "];
def "\\tan" [Print "tan "];
def "\\over" [Print "/"];
def "\\lbrace" [Print "{"];
def "\\rbrace" [Print "}"];
def "\\cap" [Print "∩"];
def "\\wr" [Print "≀"];
def "\\uplus" [Print "⊎"];
def "\\sqcap" [Print "⊓"];
def "\\sqcup" [Print "⊔"];
def "\\ominus" [Print "⊖"];
def "\\oslash" [Print "⊘"];
def "\\odot" [Print "⊙"];
def "\\star" [Print "⋆"];
def "\\bigtriangleup" [Print "△"];
def "\\bigtriangleright" [Print "▷"];
def "\\bigtriangledown" [Print "▽"];
def "\\bigtriangleleft" [Print "◁"];
def "\\setminus" [Print "⧵"];
def "\\amalg" [Print "⨿"];
def "\\prime" [Print "′"];
def "\\surd" [Print "√"];
def "\\top" [Print "⊤"];
def "\\bot" [Print "⊥"];
def "\\hookleftarrow" [Print "↩"];
def "\\hookrightarrow" [Print "↪"];
def "\\leftharpoonup" [Print "↼"];
def "\\leftharpoondown" [Print "↽"];
def "\\rightharpoonup" [Print "⇀"];
def "\\rightharpoondown" [Print "⇁"];
def "\\imath" [Print "𝚤"];
def "\\jmath" [Print "𝚥"];
(* Math symbols printed as texts (could we do better?) *)
def "\\ne" [Print "=/="];
def "\\in" [Print "in"];
def "\\forall" [Print "for all"];
def "\\exists" [Print "there exists"];
def "\\vdash" [Print "|-"];
def "\\ln" [Print "ln"];
def "\\gcd" [Print "gcd"];
def "\\min" [Print "min"];
def "\\max" [Print "max"];
def "\\exp" [Print "exp"];
def "\\rightarrow" [Print "->"];
def "\\to" [Print "->"];
def "\\longrightarrow" [Print "-->"];
def "\\Rightarrow" [Print "=>"];
def "\\leftarrow" [Print "<-"];
def "\\longleftarrow" [Print "<--"];
def "\\Leftarrow" [Print "<="];
def "\\leftrightarrow" [Print "<->"];
def "\\sqrt" [Print "sqrt("; Print_arg; Print ")"];
def "\\vee" [Print "V"];
def "\\lor" [Print "V"];
def "\\wedge" [Print "/\\"];
def "\\land" [Print "/\\"];
def "\\Vert" [Print "||"];
def "\\parallel" [Print "||"];
def "\\mid" [Print "|"];
def "\\cup" [Print "U"];
def "\\inf" [Print "inf"];
def "\\div" [Print "/"];
def "\\quad" [Print " "];
def "\\qquad" [Print " "];
(* Misc. macros. *)
def "\\TeX" [Print "T<sub>E</sub>X"];
def "\\LaTeX" [Print "L<sup>A</sup>T<sub>E</sub>X"];
def "\\LaTeXe"
[Print "L<sup>A</sup>T<sub>E</sub>X 2<FONT FACE=symbol>e</FONT>"];
def "\\tm" [Print "<sup><font size=-1>TM</font></sup>"];
def "\\par" [Print "<p>"];
def "\\@" [Print " "];
def "\\#" [Print "#"];
def "\\/" [];
def "\\-" [];
def "\\left" [];
def "\\right" [];
def "\\smallskip" [];
def "\\medskip" [];
def "\\bigskip" [];
def "\\relax" [];
def "\\markboth" [Skip_arg; Skip_arg];
def "\\dots" [Print "..."];
def "\\simeq" [Print "˜="];
def "\\approx" [Print "˜"];
def "\\^circ" [Print "°"];
def "\\ldots" [Print "..."];
def "\\cdot" [Print "·"];
def "\\cdots" [Print "..."];
def "\\newpage" [];
def "\\hbox" [Print_arg];
def "\\noindent" [];
def "\\label" [Print "<A name=\""; Print_arg; Print "\"></A>"];
def "\\ref" [Print "<A href=\"#"; Print_arg; Print "\">(ref)</A>"];
def "\\index" [Skip_arg];
def "\\\\" [Print "<br>"];
def "\\," [];
def "\\;" [];
def "\\!" [];
def "\\hspace" [Skip_arg; Print " "];
def "\\symbol"
[Raw_arg (function s ->
try let n = int_of_string s in print_c (Char.chr n)
with _ -> ())];
def "\\html" [Raw_arg print_s];
def "\\textcopyright" [Print "©"];
def "\\textordfeminine" [Print "ª"];
def "\\textordmasculine" [Print "º"];
def "\\backslash" [Print "\"];
(* hyperref *)
def "\\href"
[Print "<a href=\""; Raw_arg print_s;
Print "\">"; Print_arg; Print "</a>"];
(* Bibliography *)
def "\\begin{thebibliography}" [Print "<H2>References</H2>\n<dl>\n"; Skip_arg];
def "\\end{thebibliography}" [Print "</dl>"];
def "\\bibitem" [Raw_arg (function r ->
print_s "<dt><A name=\""; print_s r; print_s "\">[";
print_s r; print_s "]</A>\n";
print_s "<dd>")];
Greek letters
* *
List.iter
( fun symbol - > def ( " \\ " ^ symbol ) [ Print ( " < EM > " ^ symbol ^ " < /EM > " ) ] )
[ " alpha";"beta";"gamma";"delta";"epsilon";"varepsilon";"zeta";"eta " ;
" theta";"vartheta";"iota";"kappa";"lambda";"mu";"nu";"xi";"pi";"varpi " ;
" rho";"varrho";"sigma";"varsigma";"tau";"upsilon";"phi";"varphi " ;
" chi";"psi";"omega";"Gamma";"Delta";"Theta";"Lambda";"Xi";"Pi " ;
" " ] ;
* *
List.iter
(fun symbol -> def ("\\" ^ symbol) [Print ("<EM>" ^ symbol ^ "</EM>")])
["alpha";"beta";"gamma";"delta";"epsilon";"varepsilon";"zeta";"eta";
"theta";"vartheta";"iota";"kappa";"lambda";"mu";"nu";"xi";"pi";"varpi";
"rho";"varrho";"sigma";"varsigma";"tau";"upsilon";"phi";"varphi";
"chi";"psi";"omega";"Gamma";"Delta";"Theta";"Lambda";"Xi";"Pi";
"Sigma";"Upsilon";"Phi";"Psi";"Omega"];
***)
def "\\alpha" [Print "α"];
def "\\beta" [Print "β"];
def "\\gamma" [Print "γ"];
def "\\delta" [Print "δ"];
def "\\epsilon" [Print "ε"];
def "\\varepsilon" [Print "ε"];
def "\\zeta" [Print "ζ"];
def "\\eta" [Print "η"];
def "\\theta" [Print "θ"];
def "\\vartheta" [Print "θ"];
def "\\iota" [Print "ι"];
def "\\kappa" [Print "κ"];
def "\\lambda" [Print "λ"];
def "\\mu" [Print "μ"];
def "\\nu" [Print "ν"];
def "\\xi" [Print "ξ"];
def "\\pi" [Print "π"];
def "\\varpi" [Print "ϖ"];
def "\\rho" [Print "ρ"];
def "\\varrho" [Print "ρ"];
def "\\sigma" [Print "σ"];
def "\\varsigma" [Print "ς"];
def "\\tau" [Print "τ"];
def "\\upsilon" [Print "υ"];
def "\\phi" [Print "φ"];
def "\\varphi" [Print "φ"];
def "\\chi" [Print "χ"];
def "\\psi" [Print "ψ"];
def "\\omega" [Print "ω"];
def "\\Gamma" [Print "Γ"];
def "\\Delta" [Print "Δ"];
def "\\Theta" [Print "Θ"];
def "\\Lambda" [Print "Λ"];
def "\\Xi" [Print "Ξ"];
def "\\Pi" [Print "Π"];
def "\\Sigma" [Print "Σ"];
def "\\Upsilon" [Print "Υ"];
def "\\Phi" [Print "Φ"];
def "\\Psi" [Print "Ψ"];
def "\\Omega" [Print "Ω"];
macros for the AMS styles
def "\\bysame" [Print "<u> </u>"];
def "\\MR"
[Raw_arg (fun s ->
let mr =
try
let i = String.index s ' ' in
if i=0 then raise Not_found;
String.sub s 0 i
with Not_found -> s
in
print_s "<a href=\"-getitem?mr=";
print_s mr; print_s "\">MR "; print_s s; print_s "</a>")];
def "\\MRhref"
[Print "<a href=\"-getitem?mr=";
Print_arg; Print "\">"; Print_arg; Print "</a>"];
macros for the aaai - named style
def "\\em" [];
def "\\protect" [];
def "\\bgroup" []; (* should go into latexscan? *)
def "\\egroup" []; (* should go into latexscan? *)
def "\\citename" [];
(* dashes *)
def "--" [Print "--"];
def "---" [Print "---"];
()
(* Unicode entities *)
let unicode_entities () =
def "\\models" [Print "⊧"];
def "\\curlyvee" [Print "⋎"];
def "\\curlywedge" [Print "⋏"];
def "\\bigcirc" [Print "◯"];
def "\\varepsilon" [Print "ɛ"];
def "--" [Print "–"];
def "---" [Print "—"];
def "\\ddagger" [Print "‡"];
def "\\leftarrow" [Print "←"];
def "\\uparrow" [Print "↑"];
def "\\rightarrow" [Print "→"];
def "\\downarrow" [Print "↓"];
def "\\leftrightarrow" [Print "↔"];
def "\\updownarrow" [Print "↕"];
def "\\nwarrow" [Print "↖"];
def "\\nearrow" [Print "↗"];
def "\\searrow" [Print "↘"];
def "\\swarrow" [Print "↙"];
def "\\mapsto" [Print "↦"];
def "\\cup" [Print "∪"];
def "\\infty" [Print "∞"];
def "\\angle" [Print "∠"];
def "\\Leftarrow" [Print "⇐"];
def "\\Uparrow" [Print "⇑"];
def "\\Rightarrow" [Print "⇒"];
def "\\Downarrow" [Print "⇓"];
def "\\Leftrightarrow" [Print "⇔"];
def "\\Updownarrow" [Print "⇕"];
def "\\propto" [Print "∝"];
def "\\mid" [Print "∣"];
def "\\parallel" [Print "∥"];
def "\\sim" [Print "∼"];
def "\\simeq" [Print "≃"];
def "\\approx" [Print "≈"];
def "\\asymp" [Print "≍"];
def "\\ne" [Print "≠"];
def "\\equiv" [Print "≡"];
def "\\le" [Print "≤"];
def "\\leq" [Print "≤"];
def "\\ge" [Print "≥"];
def "\\geq" [Print "≥"];
def "\\ll" [Print "≪"];
def "\\gg" [Print "≫"];
def "\\ell" [Print "ℓ"];
def "\\int" [Print "∫"];
def "\\sum" [Print "∑"];
def "\\prod" [Print "∏"];
def "\\langle" [Print "⟨"];
def "\\rangle" [Print "⟩"];
def "\\prec" [Print "≺"];
def "\\succ" [Print "≻"];
def "\\subset" [Print "⊂"];
def "\\supset" [Print "⊃"];
def "\\subseteq" [Print "⊆"];
def "\\supseteq" [Print "⊇"];
def "\\sqsubseteq" [Print "⊑"];
def "\\sqsupseteq" [Print "⊒"];
def "\\vdash" [Print "⊢"];
def "\\dashv" [Print "⊣"];
def "\\bowtie" [Print "⋈"];
def "\\vdots" [Print "⋮"];
def "\\ddots" [Print "⋱"];
def "\\frown" [Print "⌢"];
def "\\smile" [Print "⌣"];
def "\\perp" [Print "⟂"];
def "\\longleftarrow" [Print "⟵"];
def "\\longrightarrow" [Print "⟶"];
def "\\longleftrightarrow" [Print "⟷"];
def "\\Longleftarrow" [Print "⟸"];
def "\\Longrightarrow" [Print "⟹"];
def "\\Longleftrightarrow" [Print "⟺"];
def "\\longmapsto" [Print "⟼"];
def "\\preceq" [Print "⪯"];
def "\\succeq" [Print "⪰"];
def "\\Im" [Print "ℑ"];
def "\\wp" [Print "℘"];
def "\\Re" [Print "ℜ"];
def "\\aleph" [Print "ℵ"];
def "\\partial" [Print "∂"];
def "\\nabla" [Print "∇"];
def "\\not" [Raw_arg (function s -> print_s "not "; print_s s)];
def "\\i" [Print "ı"];
def "\\j" [Print "ȷ"];
()
let html_entities () =
def "\\sqrt" [Print "√("; Print_arg; Print ")"];
def "\\copyright" [Print "©"];
def "\\tm" [Print "™"];
def "\\lang" [Print "⟨"];
def "\\rang" [Print "⟩"];
def "\\lceil" [Print "⌈"];
def "\\rceil" [Print "⌉"];
def "\\lfloor" [Print "⌊"];
def "\\rfloor" [Print "⌋"];
def "\\le" [Print "≤"];
def "\\leq" [Print "≤"];
def "\\ge" [Print "≥"];
def "\\geq" [Print "≥"];
def "\\ll" [Print "≪"];
def "\\gg" [Print "≫"];
def "\\prec" [Print "≺"];
def "\\succ" [Print "≻"];
def "\\neq" [Print "≠"];
def "\\approx" [Print "≈"];
def "\\asymp" [Print "≍"];
def "\\cong" [Print "≅"];
def "\\equiv" [Print "≡"];
def "\\propto" [Print "∝"];
def "\\subset" [Print "⊂"];
def "\\subseteq" [Print "⊆"];
def "\\supset" [Print "⊃"];
def "\\supseteq" [Print "⊇"];
def "\\sqsubseteq" [Print "⊑"];
def "\\sqsupseteq" [Print "⊒"];
def "\\vdash" [Print "⊢"];
def "\\dashv" [Print "⊣"];
def "\\bowtie" [Print "⋈"];
def "\\vdots" [Print "⋮"]; (* fails: def "\\vdots" [Print "&velip;"]; *)
def "\\ddots" [Print "⋱"];
def "\\frown" [Print "⌢"];
def "\\smile" [Print "⌣"];
def "\\ang" [Print "∠"];
def "\\perp" [Print "⊥"];
def "\\therefore" [Print "∴"];
def "\\sim" [Print "∼"];
def "\\div" [Print "÷"];
def "\\times" [Print "×"];
def "\\ast" [Print "∗"];
def "\\otimes" [Print "⊗"];
def "\\oplus" [Print "⊕"];
def "\\lozenge" [Print "◊"];
def "\\diamond" [Print "◊"];
def "\\neg" [Print "¬"];
def "\\pm" [Print "±"];
def "\\dagger" [Print "†"];
def "\\ddagger" [Print "‡"];
def "\\ne" [Print "≠"];
def "\\in" [Print "∈"];
def "\\notin" [Print "∉"];
def "\\ni" [Print "∋"];
def "\\forall" [Print "∀"];
def "\\exists" [Print "∃"];
def "\\Re" [Print "ℜ"];
def "\\Im" [Print "ℑ"];
def "\\aleph" [Print "ℵ"];
def "\\wp" [Print "℘"];
def "\\emptyset" [Print "∅"];
def "\\nabla" [Print "∇"];
def "\\to" [Print "→"];
def "\\longleftarrow" [Print "⟵"];
def "\\longrightarrow" [Print "⟶"];
def "\\longleftrightarrow" [Print "⟷"];
def "\\Longleftarrow" [Print "⟸"];
def "\\Longrightarrow" [Print "⟹"];
def "\\Longleftrightarrow" [Print "⟺"];
def "\\longmapsto" [Print "⟼"];
def "\\preceq" [Print "⪯"];
def "\\succeq" [Print "⪰"];
def "\\leftarrow" [Print "←"];
def "\\uparrow"[Print "↑"];
def "\\rightarrow" [Print "→"];
def "\\downarrow"[Print "↓"];
def "\\leftrightarrow" [Print "↔"];
def "\\updownarrow" [Print "↕"];
def "\\nwarrow" [Print "↖"];
def "\\nearrow" [Print "↗"];
def "\\searrow" [Print "↘"];
def "\\swarrow" [Print "↙"];
def "\\mapsto" [Print "↦"];
def "\\Leftarrow" [Print "⇐"];
def "\\Uparrow" [Print "⇑"];
def "\\Rightarrow" [Print "⇒"];
def "\\Downarrow" [Print "⇓"];
def "\\sum" [Print "∑"];
def "\\prod" [Print "∏"];
def "\\int" [Print "∫"];
def "\\partial" [Print "∂"];
def "\\vee" [Print "∨"];
def "\\lor" [Print "∨"];
def "\\wedge" [Print "∧"];
def "\\land" [Print "∧"];
def "\\cup" [Print "∪"];
def "\\infty" [Print "∞"];
def "\\simeq" [Print "≅"];
def "\\cdot" [Print "⋅"];
def "\\cdots" [Print "⋅⋅⋅"];
def "\\vartheta" [Print "ϑ"];
def "\\angle" [Print "∠"];
def "--" [Print "–"];
def "---" [Print "—"];
def "\\ll" [Print "≪"];
def "\\gg" [Print "≫"];
def "\\ell" [Print "ℓ"];
def "\\langle" [Print "⟨"];
def "\\rangle" [Print "⟩"];
def "\\i" [Print "ı"];
def "\\j" [Print "ȷ"];
()
s Macros for German BibTeX style .
let is_german_style = function
| "gerabbrv" | "geralpha" | "gerapali" | "gerplain" | "gerunsrt" -> true
| _ -> false
let init_style_macros st =
if is_german_style st then begin
List.iter (fun (m,s) -> def m [ Print s; Print_arg ])
[ "\\btxetalshort", "et al" ;
"\\btxeditorshort", "Hrsg";
"\\Btxeditorshort", "Hrsg";
"\\btxeditorsshort", "Hrsg";
"\\Btxeditorsshort", "Hrsg";
"\\btxvolumeshort", "Bd";
"\\Btxvolumeshort", "Bd";
"\\btxnumbershort", "Nr";
"\\Btxnumbershort", "Nr";
"\\btxeditionshort", "Aufl";
"\\Btxeditionshort", "Aufl";
"\\btxchaptershort", "Kap";
"\\Btxchaptershort", "Kap";
"\\btxpageshort", "S";
"\\Btxpageshort", "S";
"\\btxpagesshort", "S";
"\\Btxpagesshort", "S";
"\\btxtechrepshort", "Techn. Ber";
"\\Btxtechrepshort", "Techn. Ber";
"\\btxmonjanshort", "Jan";
"\\btxmonfebshort", "Feb";
"\\btxmonaprshort", "Apr";
"\\btxmonaugshort", "Aug";
"\\btxmonsepshort", "Sep";
"\\btxmonoctshort", "Okt";
"\\btxmonnovshort", "Nov";
"\\btxmondecshort", "Dez";
];
List.iter (fun (m,s) -> def m [ Skip_arg; Print s])
[ "\\btxetallong", "et alii";
"\\btxandshort", "und";
"\\btxandlong", "und";
"\\btxinlong", "in:";
"\\btxinshort", "in:";
"\\btxofseriesshort", "d. Reihe";
"\\btxinseriesshort", "in";
"\\btxofserieslong", "der Reihe";
"\\btxinserieslong", "in";
"\\btxeditorlong", "Herausgeber";
"\\Btxeditorlong", "Herausgeber";
"\\btxeditorslong", "Herausgeber";
"\\Btxeditorslong", "Herausgeber";
"\\btxvolumelong", "Band";
"\\Btxvolumelong", "Band";
"\\btxnumberlong", "Nummer";
"\\Btxnumberlong", "Nummer";
"\\btxeditionlong", "Auflage";
"\\Btxeditionlong", "Auflage";
"\\btxchapterlong", "Kapitel";
"\\Btxchapterlong", "Kapitel";
"\\btxpagelong", "Seite";
"\\Btxpagelong", "Seite";
"\\btxpageslong", "Seiten";
"\\Btxpageslong", "Seiten";
"\\btxmastthesis", "Diplomarbeit";
"\\btxphdthesis", "Doktorarbeit";
"\\btxtechreplong", "Technischer Bericht";
"\\Btxtechreplong", "Technischer Bericht";
"\\btxmonjanlong", "Januar";
"\\btxmonfeblong", "Februar";
"\\btxmonmarlong", "März";
"\\btxmonaprlong", "April";
"\\btxmonmaylong", "Mai";
"\\btxmonjunlong", "Juni";
"\\btxmonjullong", "Juli";
"\\btxmonauglong", "August";
"\\btxmonseplong", "September";
"\\btxmonoctlong", "Oktober";
"\\btxmonnovlong", "November";
"\\btxmondeclong", "Dezember";
"\\btxmonmarshort", "März";
"\\btxmonmayshort", "Mai";
"\\btxmonjunshort", "Juni";
"\\btxmonjulshort", "Juli";
"\\Btxinlong", "In:";
"\\Btxinshort", "In:";
]
end
| null | https://raw.githubusercontent.com/backtracking/bibtex2html/7c9547da79a13c3accffc9947c846df96a6edd68/latexmacros.ml | ocaml | ************************************************************************
bibtex2html - A BibTeX to HTML translator
This software is free software; you can redistribute it and/or
This software 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.
(enclosed in the file GPL).
************************************************************************
s Output functions.
s Actions and translations table.
Sectioning
Text formatting
Basic color support.
Other, unknown colors have no effect.
Fonts without HTML equivalent
Environments
Special characters
cedilla accent
dot-under accent
bar-under accent
tie-after accent
"š"
"Š"
Math macros
Math symbols printed as texts (could we do better?)
Misc. macros.
hyperref
Bibliography
should go into latexscan?
should go into latexscan?
dashes
Unicode entities
fails: def "\\vdots" [Print "&velip;"]; | Copyright ( C ) 1997 - 2014 and
modify it under the terms of the GNU General Public
License version 2 , as published by the Free Software Foundation .
See the GNU General Public License version 2 for more details
This code is an adaptation of a code written by in
1995 - 1997 , in his own made latex2html translator . See
@inproceedings{Leroy - latex2html ,
author = " " ,
title = " Lessons learned from the translation of
documentation from \LaTeX\ to { HTML } " ,
booktitle = " ERCIM / W4 G Int . Workshop on WWW
Authoring and Integration Tools " ,
year = 1995 ,
month = feb }
1995-1997, in his own made latex2html translator. See
@inproceedings{Leroy-latex2html,
author = "Xavier Leroy",
title = "Lessons learned from the translation of
documentation from \LaTeX\ to {HTML}",
booktitle = "ERCIM/W4G Int. Workshop on WWW
Authoring and Integration Tools",
year = 1995,
month = feb}
*)
open Printf
open Options
let out_channel = ref stdout
let print_s s = output_string !out_channel s
let print_c c = output_char !out_channel c
type action =
| Print of string
| Print_arg
| Skip_arg
| Raw_arg of (string -> unit)
| Parameterized of (string -> action list)
r piece of LaTeX to analyze recursively
let cmdtable = (Hashtbl.create 19 : (string, action list) Hashtbl.t)
let def name action =
Hashtbl.add cmdtable name action
let find_macro name =
try
Hashtbl.find cmdtable name
with Not_found ->
if not !quiet then eprintf "Unknown macro: %s\n" name;
[]
;;
s Translations of general LaTeX macros .
def "\\part"
[Print "<H0>"; Print_arg; Print "</H0>\n"];
def "\\chapter"
[Print "<H1>"; Print_arg; Print "</H1>\n"];
def "\\chapter*"
[Print "<H1>"; Print_arg; Print "</H1>\n"];
def "\\section"
[Print "<H2>"; Print_arg; Print "</H2>\n"];
def "\\section*"
[Print "<H2>"; Print_arg; Print "</H2>\n"];
def "\\subsection"
[Print "<H3>"; Print_arg; Print "</H3>\n"];
def "\\subsection*"
[Print "<H3>"; Print_arg; Print "</H3>\n"];
def "\\subsubsection"
[Print "<H4>"; Print_arg; Print "</H4>\n"];
def "\\subsubsection*"
[Print "<H4>"; Print_arg; Print "</H4>\n"];
def "\\paragraph"
[Print "<H5>"; Print_arg; Print "</H5>\n"];
def "\\begin{alltt}" [Print "<pre>"];
def "\\end{alltt}" [Print "</pre>"];
def "\\textbf" [Print "<b>" ; Print_arg ; Print "</b>"];
def "\\mathbf" [Print "<b>" ; Print_arg ; Print "</b>"];
def "\\texttt" [Print "<tt>" ; Print_arg ; Print "</tt>"];
def "\\mathtt" [Print "<tt>" ; Print_arg ; Print "</tt>"];
def "\\textit" [Print "<i>" ; Print_arg ; Print "</i>"];
def "\\mathit" [Print "<i>" ; Print_arg ; Print "</i>"];
def "\\textsl" [Print "<i>" ; Print_arg ; Print "</i>"];
def "\\textem" [Print "<em>" ; Print_arg ; Print "</em>"];
def "\\textrm" [Print_arg];
def "\\mathrm" [Print_arg];
def "\\textmd" [Print_arg];
def "\\textup" [Print_arg];
def "\\textnormal" [Print_arg];
def "\\mathnormal" [Print "<i>" ; Print_arg ; Print "</i>"];
def "\\mathcal" [Print_arg];
def "\\mathbb" [Print_arg];
def "\\mathfrak" [Print_arg];
def "\\textin" [Print "<sub>"; Print_arg; Print "</sub>"];
def "\\textsu" [Print "<sup>"; Print_arg; Print "</sup>"];
def "\\textsuperscript" [Print "<sup>"; Print_arg; Print "</sup>"];
def "\\textsi" [Print "<i>" ; Print_arg ; Print "</i>"];
def "\\textcolor" [ Parameterized (function name ->
match String.lowercase_ascii name with
At the moment , we support only the 16 named colors defined in HTML 4.01 .
| "black" | "silver" | "gray" | "white" | "maroon" | "red" | "purple" | "fuchsia"
| "green" | "lime" | "olive" | "yellow" | "navy" | "blue" | "teal" | "aqua" ->
[ Print (Printf.sprintf "<font color=%s>" name);
Print_arg ;
Print "</font>"
]
| _ ->
[ Print_arg ]
)];
def "\\textsf" [Print "<b>" ; Print_arg ; Print "</b>"];
def "\\mathsf" [Print "<b>" ; Print_arg ; Print "</b>"];
def "\\textsc" [Print_arg];
def "\\textln" [Print_arg];
def "\\textos" [Print_arg];
def "\\textdf" [Print_arg];
def "\\textsw" [Print_arg];
def "\\rm" [];
def "\\cal" [];
def "\\emph" [Print "<em>" ; Print_arg ; Print "</em>"];
def "\\mbox" [Print_arg];
def "\\footnotesize" [];
def "\\etalchar" [ Print "<sup>" ; Raw_arg print_s ; Print "</sup>" ];
def "\\newblock" [Print " "];
def "\\begin{itemize}" [Print "<p><ul>"];
def "\\end{itemize}" [Print "</ul>"];
def "\\begin{enumerate}" [Print "<p><ol>"];
def "\\end{enumerate}" [Print "</ol>"];
def "\\begin{description}" [Print "<p><dl>"];
def "\\end{description}" [Print "</dl>"];
def "\\begin{center}" [Print "<blockquote>"];
def "\\end{center}" [Print "</blockquote>"];
def "\\begin{htmlonly}" [];
def "\\end{htmlonly}" [];
def "\\begin{flushleft}" [Print "<blockquote>"];
def "\\end{flushleft}" [Print "</blockquote>"];
def "\\ " [Print " "];
def "\\\n" [Print " "];
def "\\{" [Print "{"];
def "\\}" [Print "}"];
def "\\l" [Print "l"];
def "\\L" [Print "L"];
def "\\oe" [Print "œ"];
def "\\OE" [Print "Œ"];
def "\\o" [Print "ø"];
def "\\O" [Print "Ø"];
def "\\ae" [Print "æ"];
def "\\AE" [Print "Æ"];
def "\\aa" [Print "å"];
def "\\AA" [Print "Å"];
def "\\i" [Print "i"];
def "\\j" [Print "j"];
def "\\&" [Print "&"];
def "\\$" [Print "$"];
def "\\%" [Print "%"];
def "\\_" [Print "_"];
def "\\slash" [Print "/"];
def "\\copyright" [Print "(c)"];
def "\\th" [Print "þ"];
def "\\TH" [Print "Þ"];
def "\\dh" [Print "ð"];
def "\\DH" [Print "Ð"];
def "\\dj" [Print "đ"];
def "\\DJ" [Print "Đ"];
def "\\ss" [Print "ß"];
def "\\rq" [Print "’"];
def "\\spadesuit" [Print "♠"];
def "\\heartsuit" [Print "♡"];
def "\\diamondsuit" [Print "♢"];
def "\\clubsuit" [Print "♣"];
def "\\flat" [Print "♭"];
def "\\natural" [Print "♮"];
def "\\sharp" [Print "♯"];
def "\\'" [Raw_arg(function "e" -> print_s "é"
| "E" -> print_s "É"
| "a" -> print_s "á"
| "A" -> print_s "Á"
| "o" -> print_s "ó"
| "O" -> print_s "Ó"
| "i" -> print_s "í"
| "\\i" -> print_s "í"
| "I" -> print_s "Í"
| "u" -> print_s "ú"
| "U" -> print_s "Ú"
| "'" -> print_s "”"
| "c" -> print_s "ć"
| "C" -> print_s "Ć"
| "g" -> print_s "ǵ"
| "G" -> print_s "G"
| "l" -> print_s "ĺ"
| "L" -> print_s "Ĺ"
| "n" -> print_s "ń"
| "N" -> print_s "Ń"
| "r" -> print_s "ŕ"
| "R" -> print_s "Ŕ"
| "s" -> print_s "ś"
| "S" -> print_s "Ś"
| "y" -> print_s "ý"
| "Y" -> print_s "Ý"
| "z" -> print_s "Ź"
| "Z" -> print_s "ź"
| "" -> print_c '\''
| s -> print_s s ; print_s "́")];
def "\\`" [Raw_arg(function "e" -> print_s "è"
| "E" -> print_s "È"
| "a" -> print_s "à"
| "A" -> print_s "À"
| "o" -> print_s "ò"
| "O" -> print_s "Ò"
| "i" -> print_s "ì"
| "\\i" -> print_s "ì"
| "I" -> print_s "Ì"
| "u" -> print_s "ù"
| "U" -> print_s "Ù"
| "`" -> print_s "“"
| "" -> print_s "‘"
| s -> print_s s ; print_s "̀")];
def "\\~" [Raw_arg(function "n" -> print_s "ñ"
| "N" -> print_s "Ñ"
| "o" -> print_s "õ"
| "O" -> print_s "Õ"
| "i" -> print_s "ĩ"
| "\\i" -> print_s "ĩ"
| "I" -> print_s "Ĩ"
| "a" -> print_s "ã"
| "A" -> print_s "Ã"
| "u" -> print_s "ũ"
| "U" -> print_s "Ũ"
| "" -> print_s "˜"
| s -> print_s s ; print_s "̃")];
def "\\=" [Raw_arg(function s -> print_s s ; print_s "̄")];
def "\\k" [Raw_arg(function "A" -> print_s "Ą"
| "a" -> print_s "ą"
| "i" -> print_s "Į"
| "I" -> print_s "į"
| s -> print_s s)];
def "\\c" [Raw_arg(function "c" -> print_s "ç"
| "C" -> print_s "Ç"
| s -> print_s s)];
def "\\^" [Raw_arg(function "a" -> print_s "â"
| "A" -> print_s "Â"
| "e" -> print_s "ê"
| "E" -> print_s "Ê"
| "i" -> print_s "î"
| "\\i" -> print_s "î"
| "I" -> print_s "Î"
| "o" -> print_s "ô"
| "O" -> print_s "Ô"
| "u" -> print_s "û"
| "U" -> print_s "Û"
| "w" -> print_s "ŵ"
| "W" -> print_s "Ŵ"
| "y" -> print_s "ŷ"
| "Y" -> print_s "Ŷ"
| "" -> print_c '^'
| "j" -> print_s "ȷ̂"
| s -> print_s s ; print_s "̂")];
| "C" -> print_s "Ç"
| "c" -> print_s "ç"
| "D" -> print_s "Ḑ"
| "d" -> print_s "ḑ"
| "E" -> print_s "Ȩ"
| "e" -> print_s "ȩ"
| "G" -> print_s "Ģ"
| "g" -> print_s "ģ"
| "H" -> print_s "Ḩ"
| "h" -> print_s "ḩ"
| "K" -> print_s "Ķ"
| "k" -> print_s "ķ"
| "L" -> print_s "Ļ"
| "l" -> print_s "ļ"
| "N" -> print_s "Ņ"
| "n" -> print_s "ņ"
| "R" -> print_s "Ŗ"
| "r" -> print_s "ŗ"
| "S" -> print_s "Ş"
| "s" -> print_s "ş"
| "T" -> print_s "Ţ"
| "t" -> print_s "ţ"
| s -> print_s s ; print_s "̧")];
| "a" -> print_s "ạ"
| "B" -> print_s "Ḅ"
| "b" -> print_s "ḅ"
| "D" -> print_s "Ḍ"
| "d" -> print_s "ḍ"
| "E" -> print_s "Ẹ"
| "e" -> print_s "ẹ"
| "H" -> print_s "Ḥ"
| "h" -> print_s "ḥ"
| "I" -> print_s "Ị"
| "i" -> print_s "ị"
| "K" -> print_s "Ḳ"
| "k" -> print_s "ḳ"
| "L" -> print_s "Ḷ"
| "l" -> print_s "ḷ"
| "M" -> print_s "Ṃ"
| "m" -> print_s "ṃ"
| "N" -> print_s "Ṇ"
| "n" -> print_s "ṇ"
| "O" -> print_s "Ọ"
| "o" -> print_s "ọ"
| "R" -> print_s "Ṛ"
| "r" -> print_s "ṛ"
| "S" -> print_s "Ṣ"
| "s" -> print_s "ṣ"
| "T" -> print_s "Ṭ"
| "t" -> print_s "ṭ"
| "U" -> print_s "Ụ"
| "u" -> print_s "ụ"
| "V" -> print_s "Ṿ"
| "v" -> print_s "ṿ"
| "W" -> print_s "Ẉ"
| "w" -> print_s "ẉ"
| "Y" -> print_s "Ỵ"
| "y" -> print_s "ỵ"
| "Z" -> print_s "Ẓ"
| "z" -> print_s "ẓ"
| s -> print_s s ; print_s "̣")];
| "b" -> print_s "ḇ"
| "D" -> print_s "Ḏ"
| "d" -> print_s "ḏ"
| "h" -> print_s "ẖ"
| "K" -> print_s "Ḵ"
| "k" -> print_s "ḵ"
| "L" -> print_s "Ḻ"
| "l" -> print_s "ḻ"
| "N" -> print_s "Ṉ"
| "n" -> print_s "ṉ"
| "R" -> print_s "Ṟ"
| "r" -> print_s "ṟ"
| "T" -> print_s "Ṯ"
| "t" -> print_s "ṯ"
| "Z" -> print_s "Ẕ"
| "z" -> print_s "ẕ"
| s -> print_s s ; print_s "̱")];
def "\\tilde" [Raw_arg (function "i" -> print_s "<em>ĩ</em>"
| "j" -> print_s "<em>ȷ̃</em>"
| s -> print_s "<em>" ; print_s s ; print_s "̃</em>")];
def "\\bar" [Raw_arg (function "i" -> print_s "<em>ı̄</em>"
| "j" -> print_s "<em>ȷ̄</em>"
| s -> print_s "<em>" ; print_s s ; print_s "̄</em>")];
def "\\overbar" [Raw_arg (function "i" -> print_s "<em>ı̅</em>"
| "j" -> print_s "<em>ȷ̅</em>"
| s -> print_s "<em>" ; print_s s ; print_s "̅</em>")];
def "\\vec" [Raw_arg (function "i" -> print_s "<em>ı⃗</em>"
| "j" -> print_s "<em>ȷ⃗</em>"
| s -> print_s "<em>" ; print_s s ; print_s "⃗</em>")];
def "\\overrightarrow" [Raw_arg (function "i" -> print_s "<em>ı⃗</em>"
| "j" -> print_s "<em>ȷ⃗</em>"
| s -> print_s "<em>" ; print_s s ; print_s "⃗</em>")];
def "\\overleftarrow" [Raw_arg (function "i" -> print_s "<em>ı⃖</em>"
| "j" -> print_s "<em>ȷ⃖</em>"
| s -> print_s "<em>" ; print_s s ; print_s "⃖</em>")];
def "\\grave" [Raw_arg(function s -> print_s "<em>" ; print_s s ; print_s "̀</em>")];
def "\\acute" [Raw_arg(function s -> print_s "<em>" ; print_s s ; print_s "́</em>")];
def "\\hat" [Raw_arg(function "a" -> print_s "<em>â</em>"
| "A" -> print_s "<em>Â</em>"
| "e" -> print_s "<em>ê</em>"
| "E" -> print_s "<em>Ê</em>"
| "i" -> print_s "<em>î</em>"
| "\\i" -> print_s "<em>î</em>"
| "I" -> print_s "<em>Î</em>"
| "o" -> print_s "<em>ô</em>"
| "O" -> print_s "<em>Ô</em>"
| "u" -> print_s "<em>û</em>"
| "U" -> print_s "<em>Û</em>"
| "" -> print_c '^'
| s -> print_s "<em>" ; print_s s ; print_s "̂</em>")];
def "\\breve" [Raw_arg(function "a" -> print_s "<em>ă</em>"
| "A" -> print_s "<em>Ă</em>"
| "u" -> print_s "<em>ŭ</em>"
| "U" -> print_s "<em>Ŭ</em>"
| "" -> print_c '^'
| s -> print_s "<em>" ; print_s s ; print_s "̆</em>")];
def "\\dot" [Raw_arg(function "C" -> print_s "<em>Ċ</em>"
| "c" -> print_s "<em>ċ</em>"
| "e" -> print_s "<em>ė</em>"
| "E" -> print_s "<em>Ė</em>"
| "g" -> print_s "<em>ġ</em>"
| "G" -> print_s "<em>Ġ</em>"
| "I" -> print_s "<em>İ</em>"
| "Z" -> print_s "<em>Ż</em>"
| "z" -> print_s "<em>ż</em>"
| "" -> print_s "<em>˙</em>"
| s -> print_s "<em>" ; print_s s ; print_s "̇</em>")];
def "\\ddot" [Raw_arg(function "i" -> print_s "<em>ı̈</em>"
| "j" -> print_s "<em>ȷ̈</em>"
| s -> print_s "<em>" ; print_s s ; print_s "̈</em>")];
def "\\check" [Raw_arg(function "C" -> print_s "<em>Č</em>"
| "c" -> print_s "<em>č</em>"
| "D" -> print_s "<em>Ď</em>"
| "d" -> print_s "<em>ď</em>"
| "E" -> print_s "<em>Ě</em>"
| "e" -> print_s "<em>ě</em>"
| "L" -> print_s "<em>Ľ</em>"
| "l" -> print_s "<em>ľ</em>"
| "N" -> print_s "<em>Ň</em>"
| "n" -> print_s "<em>ň</em>"
| "R" -> print_s "<em>Ř</em>"
| "r" -> print_s "<em>ř</em>"
| "S" -> print_s "<em>Š</em>"
| "s" -> print_s "<em>š</em>"
| "T" -> print_s "<em>Ť</em>"
| "t" -> print_s "<em>ť</em>"
| "Z" -> print_s "<em>Ž</em>"
| "z" -> print_s "<em>ž</em>"
| "" -> print_s "<em>ˇ</em>"
| s -> print_s "<em>" ; print_s s ; print_s "̌</em>")];
def "\\\"" [Raw_arg(function "e" -> print_s "ë"
| "E" -> print_s "Ë"
| "a" -> print_s "ä"
| "A" -> print_s "Ä"
| "\\i" -> print_s "ï"
| "i" -> print_s "ï"
| "I" -> print_s "Ï"
| "o" -> print_s "ö"
| "O" -> print_s "Ö"
| "u" -> print_s "ü"
| "U" -> print_s "Ü"
| "y" -> print_s "ÿ"
| "Y" -> print_s "Ÿ"
| s -> print_s s ; print_s "̈")];
def "\\d" [Raw_arg print_s ];
def "\\." [Raw_arg (function "a" -> print_s "ȧ"
| "A" -> print_s "Ȧ"
| "c" -> print_s "ċ"
| "C" -> print_s "Ċ"
| "e" -> print_s "ė"
| "E" -> print_s "Ė"
| "g" -> print_s "ġ"
| "G" -> print_s "Ġ"
| "i" -> print_s "i"
| "\\i" -> print_s "i"
| "I" -> print_s "İ"
| "o" -> print_s "ȯ"
| "O" -> print_s "Ȯ"
| "z" -> print_s "ż"
| "Z" -> print_s "Ż"
| s -> print_s s ; print_s "̇")];
def "\\u" [Raw_arg(function "a" -> print_s "ă"
| "A" -> print_s "Ă"
| "e" -> print_s "ĕ"
| "E" -> print_s "Ĕ"
| "i" -> print_s "ĭ"
| "\\i" -> print_s "ĭ"
| "I" -> print_s "Ĭ"
| "g" -> print_s "ğ"
| "G" -> print_s "Ğ"
| "o" -> print_s "ŏ"
| "O" -> print_s "Ŏ"
| "u" -> print_s "ŭ"
| "U" -> print_s "Ŭ"
| s -> print_s s ; print_s "̆")];
def "\\v" [Raw_arg(function
| "C" -> print_s "Č"
| "c" -> print_s "č"
| "D" -> print_s "Ď"
| "d" -> print_s "ď"
| "E" -> print_s "Ě"
| "e" -> print_s "ě"
| "N" -> print_s "Ň"
| "n" -> print_s "ň"
| "r" -> print_s "ř"
| "R" -> print_s "Ř"
| "T" -> print_s "Ť"
| "t" -> print_s "ť"
| "\\i" -> print_s "ĭ"
| "i" -> print_s "ĭ"
| "I" -> print_s "Ĭ"
| "Z" -> print_s "Ž"
| "z" -> print_s "ž"
| s -> print_s s ; print_s "̌")];
def "\\H" [Raw_arg (function
| "O" -> print_s "Ő"
| "o" -> print_s "ő"
| "U" -> print_s "Ű"
| "u" -> print_s "ű"
| s -> print_s s ; print_s "̋")];
def "\\r" [Raw_arg (function
| "U" -> print_s "Ů"
| "u" -> print_s "ů"
| s -> print_s s)];
def "\\[" [Print "<blockquote>"];
def "\\]" [Print "\n</blockquote>"];
def "\\le" [Print "<="];
def "\\leq" [Print "<="];
def "\\log" [Print "log "];
def "\\ge" [Print ">="];
def "\\geq" [Print ">="];
def "\\neq" [Print "<>"];
def "\\circ" [Print "o"];
def "\\bigcirc" [Print "O"];
def "\\sim" [Print "~"];
def "\\(" [Print "<I>"];
def "\\)" [Print "</I>"];
def "\\mapsto" [Print "<tt>|-></tt>"];
def "\\times" [Print "×"];
def "\\neg" [Print "¬"];
def "\\frac" [Print "("; Print_arg; Print ")/("; Print_arg; Print ")"];
def "\\not" [Print "not "];
def "\\arccos" [Print "arccos "];
def "\\arcsin" [Print "arcsin "];
def "\\arctan" [Print "arctan "];
def "\\arg" [Print "arg "];
def "\\cos" [Print "cos "];
def "\\cosh" [Print "cosh "];
def "\\coth" [Print "coth "];
def "\\cot" [Print "cot "];
def "\\csc" [Print "csc "];
def "\\deg" [Print "deg "];
def "\\det" [Print "det "];
def "\\dim" [Print "dim "];
def "\\exp" [Print "exp "];
def "\\gcd" [Print "gcd "];
def "\\hom" [Print "hom "];
def "\\inf" [Print "inf "];
def "\\ker" [Print "ker "];
def "\\lg" [Print "lg "];
def "\\lim" [Print "lim "];
def "\\liminf" [Print "liminf "];
def "\\limsup" [Print "limsup "];
def "\\ln" [Print "ln "];
def "\\max" [Print "max "];
def "\\min" [Print "min "];
def "\\Pr" [Print "Pr "];
def "\\sec" [Print "sec "];
def "\\sin" [Print "sin "];
def "\\sinh" [Print "sinh "];
def "\\sup" [Print "sup "];
def "\\tanh" [Print "tanh "];
def "\\tan" [Print "tan "];
def "\\over" [Print "/"];
def "\\lbrace" [Print "{"];
def "\\rbrace" [Print "}"];
def "\\cap" [Print "∩"];
def "\\wr" [Print "≀"];
def "\\uplus" [Print "⊎"];
def "\\sqcap" [Print "⊓"];
def "\\sqcup" [Print "⊔"];
def "\\ominus" [Print "⊖"];
def "\\oslash" [Print "⊘"];
def "\\odot" [Print "⊙"];
def "\\star" [Print "⋆"];
def "\\bigtriangleup" [Print "△"];
def "\\bigtriangleright" [Print "▷"];
def "\\bigtriangledown" [Print "▽"];
def "\\bigtriangleleft" [Print "◁"];
def "\\setminus" [Print "⧵"];
def "\\amalg" [Print "⨿"];
def "\\prime" [Print "′"];
def "\\surd" [Print "√"];
def "\\top" [Print "⊤"];
def "\\bot" [Print "⊥"];
def "\\hookleftarrow" [Print "↩"];
def "\\hookrightarrow" [Print "↪"];
def "\\leftharpoonup" [Print "↼"];
def "\\leftharpoondown" [Print "↽"];
def "\\rightharpoonup" [Print "⇀"];
def "\\rightharpoondown" [Print "⇁"];
def "\\imath" [Print "𝚤"];
def "\\jmath" [Print "𝚥"];
def "\\ne" [Print "=/="];
def "\\in" [Print "in"];
def "\\forall" [Print "for all"];
def "\\exists" [Print "there exists"];
def "\\vdash" [Print "|-"];
def "\\ln" [Print "ln"];
def "\\gcd" [Print "gcd"];
def "\\min" [Print "min"];
def "\\max" [Print "max"];
def "\\exp" [Print "exp"];
def "\\rightarrow" [Print "->"];
def "\\to" [Print "->"];
def "\\longrightarrow" [Print "-->"];
def "\\Rightarrow" [Print "=>"];
def "\\leftarrow" [Print "<-"];
def "\\longleftarrow" [Print "<--"];
def "\\Leftarrow" [Print "<="];
def "\\leftrightarrow" [Print "<->"];
def "\\sqrt" [Print "sqrt("; Print_arg; Print ")"];
def "\\vee" [Print "V"];
def "\\lor" [Print "V"];
def "\\wedge" [Print "/\\"];
def "\\land" [Print "/\\"];
def "\\Vert" [Print "||"];
def "\\parallel" [Print "||"];
def "\\mid" [Print "|"];
def "\\cup" [Print "U"];
def "\\inf" [Print "inf"];
def "\\div" [Print "/"];
def "\\quad" [Print " "];
def "\\qquad" [Print " "];
def "\\TeX" [Print "T<sub>E</sub>X"];
def "\\LaTeX" [Print "L<sup>A</sup>T<sub>E</sub>X"];
def "\\LaTeXe"
[Print "L<sup>A</sup>T<sub>E</sub>X 2<FONT FACE=symbol>e</FONT>"];
def "\\tm" [Print "<sup><font size=-1>TM</font></sup>"];
def "\\par" [Print "<p>"];
def "\\@" [Print " "];
def "\\#" [Print "#"];
def "\\/" [];
def "\\-" [];
def "\\left" [];
def "\\right" [];
def "\\smallskip" [];
def "\\medskip" [];
def "\\bigskip" [];
def "\\relax" [];
def "\\markboth" [Skip_arg; Skip_arg];
def "\\dots" [Print "..."];
def "\\simeq" [Print "˜="];
def "\\approx" [Print "˜"];
def "\\^circ" [Print "°"];
def "\\ldots" [Print "..."];
def "\\cdot" [Print "·"];
def "\\cdots" [Print "..."];
def "\\newpage" [];
def "\\hbox" [Print_arg];
def "\\noindent" [];
def "\\label" [Print "<A name=\""; Print_arg; Print "\"></A>"];
def "\\ref" [Print "<A href=\"#"; Print_arg; Print "\">(ref)</A>"];
def "\\index" [Skip_arg];
def "\\\\" [Print "<br>"];
def "\\," [];
def "\\;" [];
def "\\!" [];
def "\\hspace" [Skip_arg; Print " "];
def "\\symbol"
[Raw_arg (function s ->
try let n = int_of_string s in print_c (Char.chr n)
with _ -> ())];
def "\\html" [Raw_arg print_s];
def "\\textcopyright" [Print "©"];
def "\\textordfeminine" [Print "ª"];
def "\\textordmasculine" [Print "º"];
def "\\backslash" [Print "\"];
def "\\href"
[Print "<a href=\""; Raw_arg print_s;
Print "\">"; Print_arg; Print "</a>"];
def "\\begin{thebibliography}" [Print "<H2>References</H2>\n<dl>\n"; Skip_arg];
def "\\end{thebibliography}" [Print "</dl>"];
def "\\bibitem" [Raw_arg (function r ->
print_s "<dt><A name=\""; print_s r; print_s "\">[";
print_s r; print_s "]</A>\n";
print_s "<dd>")];
Greek letters
* *
List.iter
( fun symbol - > def ( " \\ " ^ symbol ) [ Print ( " < EM > " ^ symbol ^ " < /EM > " ) ] )
[ " alpha";"beta";"gamma";"delta";"epsilon";"varepsilon";"zeta";"eta " ;
" theta";"vartheta";"iota";"kappa";"lambda";"mu";"nu";"xi";"pi";"varpi " ;
" rho";"varrho";"sigma";"varsigma";"tau";"upsilon";"phi";"varphi " ;
" chi";"psi";"omega";"Gamma";"Delta";"Theta";"Lambda";"Xi";"Pi " ;
" " ] ;
* *
List.iter
(fun symbol -> def ("\\" ^ symbol) [Print ("<EM>" ^ symbol ^ "</EM>")])
["alpha";"beta";"gamma";"delta";"epsilon";"varepsilon";"zeta";"eta";
"theta";"vartheta";"iota";"kappa";"lambda";"mu";"nu";"xi";"pi";"varpi";
"rho";"varrho";"sigma";"varsigma";"tau";"upsilon";"phi";"varphi";
"chi";"psi";"omega";"Gamma";"Delta";"Theta";"Lambda";"Xi";"Pi";
"Sigma";"Upsilon";"Phi";"Psi";"Omega"];
***)
def "\\alpha" [Print "α"];
def "\\beta" [Print "β"];
def "\\gamma" [Print "γ"];
def "\\delta" [Print "δ"];
def "\\epsilon" [Print "ε"];
def "\\varepsilon" [Print "ε"];
def "\\zeta" [Print "ζ"];
def "\\eta" [Print "η"];
def "\\theta" [Print "θ"];
def "\\vartheta" [Print "θ"];
def "\\iota" [Print "ι"];
def "\\kappa" [Print "κ"];
def "\\lambda" [Print "λ"];
def "\\mu" [Print "μ"];
def "\\nu" [Print "ν"];
def "\\xi" [Print "ξ"];
def "\\pi" [Print "π"];
def "\\varpi" [Print "ϖ"];
def "\\rho" [Print "ρ"];
def "\\varrho" [Print "ρ"];
def "\\sigma" [Print "σ"];
def "\\varsigma" [Print "ς"];
def "\\tau" [Print "τ"];
def "\\upsilon" [Print "υ"];
def "\\phi" [Print "φ"];
def "\\varphi" [Print "φ"];
def "\\chi" [Print "χ"];
def "\\psi" [Print "ψ"];
def "\\omega" [Print "ω"];
def "\\Gamma" [Print "Γ"];
def "\\Delta" [Print "Δ"];
def "\\Theta" [Print "Θ"];
def "\\Lambda" [Print "Λ"];
def "\\Xi" [Print "Ξ"];
def "\\Pi" [Print "Π"];
def "\\Sigma" [Print "Σ"];
def "\\Upsilon" [Print "Υ"];
def "\\Phi" [Print "Φ"];
def "\\Psi" [Print "Ψ"];
def "\\Omega" [Print "Ω"];
macros for the AMS styles
def "\\bysame" [Print "<u> </u>"];
def "\\MR"
[Raw_arg (fun s ->
let mr =
try
let i = String.index s ' ' in
if i=0 then raise Not_found;
String.sub s 0 i
with Not_found -> s
in
print_s "<a href=\"-getitem?mr=";
print_s mr; print_s "\">MR "; print_s s; print_s "</a>")];
def "\\MRhref"
[Print "<a href=\"-getitem?mr=";
Print_arg; Print "\">"; Print_arg; Print "</a>"];
macros for the aaai - named style
def "\\em" [];
def "\\protect" [];
def "\\citename" [];
def "--" [Print "--"];
def "---" [Print "---"];
()
let unicode_entities () =
def "\\models" [Print "⊧"];
def "\\curlyvee" [Print "⋎"];
def "\\curlywedge" [Print "⋏"];
def "\\bigcirc" [Print "◯"];
def "\\varepsilon" [Print "ɛ"];
def "--" [Print "–"];
def "---" [Print "—"];
def "\\ddagger" [Print "‡"];
def "\\leftarrow" [Print "←"];
def "\\uparrow" [Print "↑"];
def "\\rightarrow" [Print "→"];
def "\\downarrow" [Print "↓"];
def "\\leftrightarrow" [Print "↔"];
def "\\updownarrow" [Print "↕"];
def "\\nwarrow" [Print "↖"];
def "\\nearrow" [Print "↗"];
def "\\searrow" [Print "↘"];
def "\\swarrow" [Print "↙"];
def "\\mapsto" [Print "↦"];
def "\\cup" [Print "∪"];
def "\\infty" [Print "∞"];
def "\\angle" [Print "∠"];
def "\\Leftarrow" [Print "⇐"];
def "\\Uparrow" [Print "⇑"];
def "\\Rightarrow" [Print "⇒"];
def "\\Downarrow" [Print "⇓"];
def "\\Leftrightarrow" [Print "⇔"];
def "\\Updownarrow" [Print "⇕"];
def "\\propto" [Print "∝"];
def "\\mid" [Print "∣"];
def "\\parallel" [Print "∥"];
def "\\sim" [Print "∼"];
def "\\simeq" [Print "≃"];
def "\\approx" [Print "≈"];
def "\\asymp" [Print "≍"];
def "\\ne" [Print "≠"];
def "\\equiv" [Print "≡"];
def "\\le" [Print "≤"];
def "\\leq" [Print "≤"];
def "\\ge" [Print "≥"];
def "\\geq" [Print "≥"];
def "\\ll" [Print "≪"];
def "\\gg" [Print "≫"];
def "\\ell" [Print "ℓ"];
def "\\int" [Print "∫"];
def "\\sum" [Print "∑"];
def "\\prod" [Print "∏"];
def "\\langle" [Print "⟨"];
def "\\rangle" [Print "⟩"];
def "\\prec" [Print "≺"];
def "\\succ" [Print "≻"];
def "\\subset" [Print "⊂"];
def "\\supset" [Print "⊃"];
def "\\subseteq" [Print "⊆"];
def "\\supseteq" [Print "⊇"];
def "\\sqsubseteq" [Print "⊑"];
def "\\sqsupseteq" [Print "⊒"];
def "\\vdash" [Print "⊢"];
def "\\dashv" [Print "⊣"];
def "\\bowtie" [Print "⋈"];
def "\\vdots" [Print "⋮"];
def "\\ddots" [Print "⋱"];
def "\\frown" [Print "⌢"];
def "\\smile" [Print "⌣"];
def "\\perp" [Print "⟂"];
def "\\longleftarrow" [Print "⟵"];
def "\\longrightarrow" [Print "⟶"];
def "\\longleftrightarrow" [Print "⟷"];
def "\\Longleftarrow" [Print "⟸"];
def "\\Longrightarrow" [Print "⟹"];
def "\\Longleftrightarrow" [Print "⟺"];
def "\\longmapsto" [Print "⟼"];
def "\\preceq" [Print "⪯"];
def "\\succeq" [Print "⪰"];
def "\\Im" [Print "ℑ"];
def "\\wp" [Print "℘"];
def "\\Re" [Print "ℜ"];
def "\\aleph" [Print "ℵ"];
def "\\partial" [Print "∂"];
def "\\nabla" [Print "∇"];
def "\\not" [Raw_arg (function s -> print_s "not "; print_s s)];
def "\\i" [Print "ı"];
def "\\j" [Print "ȷ"];
()
let html_entities () =
def "\\sqrt" [Print "√("; Print_arg; Print ")"];
def "\\copyright" [Print "©"];
def "\\tm" [Print "™"];
def "\\lang" [Print "⟨"];
def "\\rang" [Print "⟩"];
def "\\lceil" [Print "⌈"];
def "\\rceil" [Print "⌉"];
def "\\lfloor" [Print "⌊"];
def "\\rfloor" [Print "⌋"];
def "\\le" [Print "≤"];
def "\\leq" [Print "≤"];
def "\\ge" [Print "≥"];
def "\\geq" [Print "≥"];
def "\\ll" [Print "≪"];
def "\\gg" [Print "≫"];
def "\\prec" [Print "≺"];
def "\\succ" [Print "≻"];
def "\\neq" [Print "≠"];
def "\\approx" [Print "≈"];
def "\\asymp" [Print "≍"];
def "\\cong" [Print "≅"];
def "\\equiv" [Print "≡"];
def "\\propto" [Print "∝"];
def "\\subset" [Print "⊂"];
def "\\subseteq" [Print "⊆"];
def "\\supset" [Print "⊃"];
def "\\supseteq" [Print "⊇"];
def "\\sqsubseteq" [Print "⊑"];
def "\\sqsupseteq" [Print "⊒"];
def "\\vdash" [Print "⊢"];
def "\\dashv" [Print "⊣"];
def "\\bowtie" [Print "⋈"];
def "\\ddots" [Print "⋱"];
def "\\frown" [Print "⌢"];
def "\\smile" [Print "⌣"];
def "\\ang" [Print "∠"];
def "\\perp" [Print "⊥"];
def "\\therefore" [Print "∴"];
def "\\sim" [Print "∼"];
def "\\div" [Print "÷"];
def "\\times" [Print "×"];
def "\\ast" [Print "∗"];
def "\\otimes" [Print "⊗"];
def "\\oplus" [Print "⊕"];
def "\\lozenge" [Print "◊"];
def "\\diamond" [Print "◊"];
def "\\neg" [Print "¬"];
def "\\pm" [Print "±"];
def "\\dagger" [Print "†"];
def "\\ddagger" [Print "‡"];
def "\\ne" [Print "≠"];
def "\\in" [Print "∈"];
def "\\notin" [Print "∉"];
def "\\ni" [Print "∋"];
def "\\forall" [Print "∀"];
def "\\exists" [Print "∃"];
def "\\Re" [Print "ℜ"];
def "\\Im" [Print "ℑ"];
def "\\aleph" [Print "ℵ"];
def "\\wp" [Print "℘"];
def "\\emptyset" [Print "∅"];
def "\\nabla" [Print "∇"];
def "\\to" [Print "→"];
def "\\longleftarrow" [Print "⟵"];
def "\\longrightarrow" [Print "⟶"];
def "\\longleftrightarrow" [Print "⟷"];
def "\\Longleftarrow" [Print "⟸"];
def "\\Longrightarrow" [Print "⟹"];
def "\\Longleftrightarrow" [Print "⟺"];
def "\\longmapsto" [Print "⟼"];
def "\\preceq" [Print "⪯"];
def "\\succeq" [Print "⪰"];
def "\\leftarrow" [Print "←"];
def "\\uparrow"[Print "↑"];
def "\\rightarrow" [Print "→"];
def "\\downarrow"[Print "↓"];
def "\\leftrightarrow" [Print "↔"];
def "\\updownarrow" [Print "↕"];
def "\\nwarrow" [Print "↖"];
def "\\nearrow" [Print "↗"];
def "\\searrow" [Print "↘"];
def "\\swarrow" [Print "↙"];
def "\\mapsto" [Print "↦"];
def "\\Leftarrow" [Print "⇐"];
def "\\Uparrow" [Print "⇑"];
def "\\Rightarrow" [Print "⇒"];
def "\\Downarrow" [Print "⇓"];
def "\\sum" [Print "∑"];
def "\\prod" [Print "∏"];
def "\\int" [Print "∫"];
def "\\partial" [Print "∂"];
def "\\vee" [Print "∨"];
def "\\lor" [Print "∨"];
def "\\wedge" [Print "∧"];
def "\\land" [Print "∧"];
def "\\cup" [Print "∪"];
def "\\infty" [Print "∞"];
def "\\simeq" [Print "≅"];
def "\\cdot" [Print "⋅"];
def "\\cdots" [Print "⋅⋅⋅"];
def "\\vartheta" [Print "ϑ"];
def "\\angle" [Print "∠"];
def "--" [Print "–"];
def "---" [Print "—"];
def "\\ll" [Print "≪"];
def "\\gg" [Print "≫"];
def "\\ell" [Print "ℓ"];
def "\\langle" [Print "⟨"];
def "\\rangle" [Print "⟩"];
def "\\i" [Print "ı"];
def "\\j" [Print "ȷ"];
()
s Macros for German BibTeX style .
let is_german_style = function
| "gerabbrv" | "geralpha" | "gerapali" | "gerplain" | "gerunsrt" -> true
| _ -> false
let init_style_macros st =
if is_german_style st then begin
List.iter (fun (m,s) -> def m [ Print s; Print_arg ])
[ "\\btxetalshort", "et al" ;
"\\btxeditorshort", "Hrsg";
"\\Btxeditorshort", "Hrsg";
"\\btxeditorsshort", "Hrsg";
"\\Btxeditorsshort", "Hrsg";
"\\btxvolumeshort", "Bd";
"\\Btxvolumeshort", "Bd";
"\\btxnumbershort", "Nr";
"\\Btxnumbershort", "Nr";
"\\btxeditionshort", "Aufl";
"\\Btxeditionshort", "Aufl";
"\\btxchaptershort", "Kap";
"\\Btxchaptershort", "Kap";
"\\btxpageshort", "S";
"\\Btxpageshort", "S";
"\\btxpagesshort", "S";
"\\Btxpagesshort", "S";
"\\btxtechrepshort", "Techn. Ber";
"\\Btxtechrepshort", "Techn. Ber";
"\\btxmonjanshort", "Jan";
"\\btxmonfebshort", "Feb";
"\\btxmonaprshort", "Apr";
"\\btxmonaugshort", "Aug";
"\\btxmonsepshort", "Sep";
"\\btxmonoctshort", "Okt";
"\\btxmonnovshort", "Nov";
"\\btxmondecshort", "Dez";
];
List.iter (fun (m,s) -> def m [ Skip_arg; Print s])
[ "\\btxetallong", "et alii";
"\\btxandshort", "und";
"\\btxandlong", "und";
"\\btxinlong", "in:";
"\\btxinshort", "in:";
"\\btxofseriesshort", "d. Reihe";
"\\btxinseriesshort", "in";
"\\btxofserieslong", "der Reihe";
"\\btxinserieslong", "in";
"\\btxeditorlong", "Herausgeber";
"\\Btxeditorlong", "Herausgeber";
"\\btxeditorslong", "Herausgeber";
"\\Btxeditorslong", "Herausgeber";
"\\btxvolumelong", "Band";
"\\Btxvolumelong", "Band";
"\\btxnumberlong", "Nummer";
"\\Btxnumberlong", "Nummer";
"\\btxeditionlong", "Auflage";
"\\Btxeditionlong", "Auflage";
"\\btxchapterlong", "Kapitel";
"\\Btxchapterlong", "Kapitel";
"\\btxpagelong", "Seite";
"\\Btxpagelong", "Seite";
"\\btxpageslong", "Seiten";
"\\Btxpageslong", "Seiten";
"\\btxmastthesis", "Diplomarbeit";
"\\btxphdthesis", "Doktorarbeit";
"\\btxtechreplong", "Technischer Bericht";
"\\Btxtechreplong", "Technischer Bericht";
"\\btxmonjanlong", "Januar";
"\\btxmonfeblong", "Februar";
"\\btxmonmarlong", "März";
"\\btxmonaprlong", "April";
"\\btxmonmaylong", "Mai";
"\\btxmonjunlong", "Juni";
"\\btxmonjullong", "Juli";
"\\btxmonauglong", "August";
"\\btxmonseplong", "September";
"\\btxmonoctlong", "Oktober";
"\\btxmonnovlong", "November";
"\\btxmondeclong", "Dezember";
"\\btxmonmarshort", "März";
"\\btxmonmayshort", "Mai";
"\\btxmonjunshort", "Juni";
"\\btxmonjulshort", "Juli";
"\\Btxinlong", "In:";
"\\Btxinshort", "In:";
]
end
|
2bf760f177933901b7cb4006b4449e0f2320b46dfe521adff61f5175da4f43f6 | charlieg/Sparser | object.lisp | ;;; -*- Mode:Lisp; Syntax:Common-Lisp; Package:SPARSER -*-
copyright ( c ) 1993 -- all rights reserved
;;;
;;; File: "object"
;;; module: "interface;windows:articles:"
Version : November 1993
;; initiated 11/11/93
(in-package :sparser)
;;;--------
;;; window
;;;--------
(defclass text-output-window (ccl::fred-window)
()
(:default-initargs
:window-type :document-with-grow
:window-title "test"
:scratch-p t
:view-position #@(2 40)
:view-size #@(500 100)
:view-font '("courier" 10 :plain)))
" courier " prints both ss and eos characters -- as boxes
; "times" prints them as close brackets
" new york " prints just ss
; "monaco" prints both -- as glifs for shift-option or something
(defparameter *text-out* (make-instance 'text-output-window))
;;;--------------------------
;;; displaying to the window
;;;--------------------------
(defun write-to-text-window (string)
(write-string string *text-out*)
(force-output *text-out*))
;(setq *display-text-to-special-window* t)
;(setq *display-text-to-special-window* nil)
; selection-range (w) -- returns the bounds of the selection
; set-selection-range (w start end) -- establishes the selection
(defun select-text-region (start end)
(ccl::set-selection-range *text-out* start end)
(ccl::fred-update *text-out*))
(defun clear-special-text-display-window ()
(ccl::select-all *text-out*)
(ccl::clear *text-out*))
| null | https://raw.githubusercontent.com/charlieg/Sparser/b9bb7d01d2e40f783f3214fc104062db3d15e608/Sparser/code/s/interface/workbench/object.lisp | lisp | -*- Mode:Lisp; Syntax:Common-Lisp; Package:SPARSER -*-
File: "object"
module: "interface;windows:articles:"
initiated 11/11/93
--------
window
--------
"times" prints them as close brackets
"monaco" prints both -- as glifs for shift-option or something
--------------------------
displaying to the window
--------------------------
(setq *display-text-to-special-window* t)
(setq *display-text-to-special-window* nil)
selection-range (w) -- returns the bounds of the selection
set-selection-range (w start end) -- establishes the selection | copyright ( c ) 1993 -- all rights reserved
Version : November 1993
(in-package :sparser)
(defclass text-output-window (ccl::fred-window)
()
(:default-initargs
:window-type :document-with-grow
:window-title "test"
:scratch-p t
:view-position #@(2 40)
:view-size #@(500 100)
:view-font '("courier" 10 :plain)))
" courier " prints both ss and eos characters -- as boxes
" new york " prints just ss
(defparameter *text-out* (make-instance 'text-output-window))
(defun write-to-text-window (string)
(write-string string *text-out*)
(force-output *text-out*))
(defun select-text-region (start end)
(ccl::set-selection-range *text-out* start end)
(ccl::fred-update *text-out*))
(defun clear-special-text-display-window ()
(ccl::select-all *text-out*)
(ccl::clear *text-out*))
|
06adfbf99841c88496bb1ebf2966d700363b1191af0217c849ff43751ad5c4a3 | gfngfn/Sesterl | constructorAttribute.ml |
open MyUtil
open Syntax
type t = {
target_atom : (string ranged) option;
}
let default =
{ target_atom = None }
let decode (attrs : attribute list) : t * attribute_warning list =
let (acc, warn_acc) =
attrs |> List.fold_left (fun (acc, warn_acc) attr ->
let Attribute((rng, attr_main)) = attr in
match attr_main with
| ("atom", utast_opt) ->
begin
match utast_opt with
| Some((rngs, BaseConst(BinaryByString(s)))) ->
({ target_atom = Some((rngs, s)) }, warn_acc)
| _ ->
let warn =
{
position = rng;
tag = "atom";
message = "argument should be a string literal"
}
in
(acc, Alist.extend warn_acc warn)
end
| (tag, _) ->
let warn =
{
position = rng;
tag = tag;
message = "unsupported attribute";
}
in
(acc, Alist.extend warn_acc warn)
) (default, Alist.empty)
in
(acc, Alist.to_list warn_acc)
| null | https://raw.githubusercontent.com/gfngfn/Sesterl/4ac4d84e844c093da82759be8f27cc2c89a7ced6/src/constructorAttribute.ml | ocaml |
open MyUtil
open Syntax
type t = {
target_atom : (string ranged) option;
}
let default =
{ target_atom = None }
let decode (attrs : attribute list) : t * attribute_warning list =
let (acc, warn_acc) =
attrs |> List.fold_left (fun (acc, warn_acc) attr ->
let Attribute((rng, attr_main)) = attr in
match attr_main with
| ("atom", utast_opt) ->
begin
match utast_opt with
| Some((rngs, BaseConst(BinaryByString(s)))) ->
({ target_atom = Some((rngs, s)) }, warn_acc)
| _ ->
let warn =
{
position = rng;
tag = "atom";
message = "argument should be a string literal"
}
in
(acc, Alist.extend warn_acc warn)
end
| (tag, _) ->
let warn =
{
position = rng;
tag = tag;
message = "unsupported attribute";
}
in
(acc, Alist.extend warn_acc warn)
) (default, Alist.empty)
in
(acc, Alist.to_list warn_acc)
| |
fe4d24493c5e9b731845835343fd8af7d62a5ba24644c248b521839fc5a3bb75 | spell-music/csound-expression | TabQueue.hs | module Csound.Typed.Plugins.TabQueue(
tabQueue2_append, tabQueue2_delete, tabQueue2_hasElements, tabQueue2_readLastElement
) where
import Data.Boolean
import Control.Monad.Trans.Class
import Csound.Dynamic
import Csound.Typed.Types
import Csound.Typed.GlobalState
import qualified Csound.Typed.GlobalState.Elements as E(tabQueue2Plugin)
-------------------------------------------------------------------------------
-- table queue for midi notes
-- |
> tabQueue2_append table ( pch , vol )
tabQueue2_append :: Tab -> (D, D) -> SE ()
tabQueue2_append tab (pch, vol) = SE $ (depT_ =<<) $ lift $ do
addUdoPlugin E.tabQueue2Plugin
f <$> toGE tab <*> toGE pch <*> toGE vol
where f tab' pch' vol' = opcs "TabQueue2_Append" [(Xr, [Ir, Ir, Ir])] [tab', pch', vol']
-- | Delete by pitch
--
> tabQueue2_delete table pch
tabQueue2_delete :: Tab -> D -> SE ()
tabQueue2_delete tab pch = SE $ (depT_ =<<) $ lift $ do
addUdoPlugin E.tabQueue2Plugin
f <$> toGE tab <*> toGE pch
where f tab' pch' = opcs "TabQueue2_Delete" [(Xr, [Ir, Ir])] [tab', pch']
-- | Queue is not empty
tabQueue2_hasElements :: Tab -> BoolSig
tabQueue2_hasElements = (==* 1) . tabQueue2_hasElements'
tabQueue2_hasElements' :: Tab -> Sig
tabQueue2_hasElements' tab = fromGE $ do
addUdoPlugin E.tabQueue2Plugin
f <$> toGE tab
where f tab' = opcs "TabQueue2_HasElements" [(Kr, [Ir])] [tab']
tabQueue2_readLastElement :: Tab -> (Sig, Sig)
tabQueue2_readLastElement tab = toTuple $ fmap ($ 2) $ do
addUdoPlugin E.tabQueue2Plugin
f <$> toGE tab
where f tab' = mopcs "TabQueue2_ReadLastElement" ([Kr, Kr], [Ir]) [tab']
| null | https://raw.githubusercontent.com/spell-music/csound-expression/29c1611172153347b16d0b6b133e4db61a7218d5/csound-expression-typed/src/Csound/Typed/Plugins/TabQueue.hs | haskell | -----------------------------------------------------------------------------
table queue for midi notes
|
| Delete by pitch
| Queue is not empty | module Csound.Typed.Plugins.TabQueue(
tabQueue2_append, tabQueue2_delete, tabQueue2_hasElements, tabQueue2_readLastElement
) where
import Data.Boolean
import Control.Monad.Trans.Class
import Csound.Dynamic
import Csound.Typed.Types
import Csound.Typed.GlobalState
import qualified Csound.Typed.GlobalState.Elements as E(tabQueue2Plugin)
> tabQueue2_append table ( pch , vol )
tabQueue2_append :: Tab -> (D, D) -> SE ()
tabQueue2_append tab (pch, vol) = SE $ (depT_ =<<) $ lift $ do
addUdoPlugin E.tabQueue2Plugin
f <$> toGE tab <*> toGE pch <*> toGE vol
where f tab' pch' vol' = opcs "TabQueue2_Append" [(Xr, [Ir, Ir, Ir])] [tab', pch', vol']
> tabQueue2_delete table pch
tabQueue2_delete :: Tab -> D -> SE ()
tabQueue2_delete tab pch = SE $ (depT_ =<<) $ lift $ do
addUdoPlugin E.tabQueue2Plugin
f <$> toGE tab <*> toGE pch
where f tab' pch' = opcs "TabQueue2_Delete" [(Xr, [Ir, Ir])] [tab', pch']
tabQueue2_hasElements :: Tab -> BoolSig
tabQueue2_hasElements = (==* 1) . tabQueue2_hasElements'
tabQueue2_hasElements' :: Tab -> Sig
tabQueue2_hasElements' tab = fromGE $ do
addUdoPlugin E.tabQueue2Plugin
f <$> toGE tab
where f tab' = opcs "TabQueue2_HasElements" [(Kr, [Ir])] [tab']
tabQueue2_readLastElement :: Tab -> (Sig, Sig)
tabQueue2_readLastElement tab = toTuple $ fmap ($ 2) $ do
addUdoPlugin E.tabQueue2Plugin
f <$> toGE tab
where f tab' = mopcs "TabQueue2_ReadLastElement" ([Kr, Kr], [Ir]) [tab']
|
cc73ee3ba0009762465e8ad3a3a6d1190b7a0eb853477c6f81899a9249deed20 | opencog/pln | conditional-partial-instantiation.scm | ;; =======================================================================
Conditional Partial Instantiation Meta Rule
;;
;; ImplicationScopeLink
V1 , V2 , V3
;; P
;; Q
;; |-
;; T2
;; T3
;; |-
;; ImplicationScopeLink
;; V1
;; P[V2->T2,V3->T3]
;; Q[V2->T2,V3->T3]
;;
The fact that there 3 variables is hardcoded for now .
;; -----------------------------------------------------------------------
(use-modules (srfi srfi-1))
(use-modules (opencog exec))
(use-modules (opencog logger))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Conditional partial instantiation rule ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
Hard code a 3 - ary ImplicationScope turning into a unary
ImplicationScope where V2 and V3 are substituted by terms .
(define conditional-partial-instantiation-meta-rule
(let* ((V1 (Variable "$V1"))
(V2 (Variable "$V2"))
(V3 (Variable "$V3"))
(V1Type (Variable "$V1Type"))
(V2Type (Variable "$V2Type"))
(V3Type (Variable "$V3Type"))
(VariableT (Type "VariableNode"))
(TypeChoiceT (Type "TypeChoice"))
(TypeT (Type "TypeNode"))
(VariableTypeT (TypeChoice TypeChoiceT TypeT))
(TypedV1 (TypedVariable V1 VariableT))
(TypedV2 (TypedVariable V2 VariableT))
(TypedV3 (TypedVariable V3 VariableT))
(TypedV1Type (TypedVariable V1Type VariableTypeT))
(TypedV2Type (TypedVariable V2Type VariableTypeT))
(TypedV3Type (TypedVariable V3Type VariableTypeT))
(P (Variable "$P"))
(Q (Variable "$Q"))
Meta rule variable declaration
(meta-vardecl (VariableList
TypedV1 TypedV2 TypedV3
TypedV1Type TypedV2Type TypedV3Type
P Q))
Meta rule main clause
(implication (Quote
(ImplicationScope
(Unquote (VariableList
(TypedVariable V1 V1Type)
(TypedVariable V2 V2Type)
(TypedVariable V3 V3Type)))
(Unquote P)
(Unquote Q))))
Meta rule precondition
(meta-precondition (Evaluation
(GroundedPredicate "scm: gt-zero-confidence")
implication))
Meta rule pattern
(meta-pattern (And (Present implication) meta-precondition))
Produced rule variable declaration . V2 and V3 are to be
;; substituted.
(produced-vardecl (VariableList
(TypedVariable V2 V2Type)
(TypedVariable V3 V3Type)))
Produced rule pattern . Just look for groundings of V2 and V3
(produced-pattern (And V2 V3))
;; Produced rule rewrite. Apply formula to calculate the TV
;; over the partially substituted ImplicationScope.
(produced-rewrite (ExecutionOutput
(GroundedSchema "scm: conditional-partial-instantiation-formula")
(Unquote
(List
;; Conclusion
(Quote
(ImplicationScope
(Unquote
(TypedVariable V1 V1Type)) ; only V1 remains
(Unquote P)
(Unquote Q)))
;; Premise
implication))))
Meta rule rewrite
(meta-rewrite (Quote (Bind
(Unquote produced-vardecl)
(Unquote produced-pattern)
produced-rewrite ; the Unquote appears
; inside it, to avoid
; running the
ExecutionOutput
))))
(Bind
meta-vardecl
meta-pattern
meta-rewrite)))
(define (conditional-partial-instantiation-formula PImpl Impl)
;; For now merely put the TV of Impl on PImpl
(cog-set-tv! PImpl (cog-tv Impl)))
;; Name the meta rule
(define conditional-partial-instantiation-meta-rule-name
(DefinedSchemaNode "conditional-partial-instantiation-meta-rule"))
(DefineLink conditional-partial-instantiation-meta-rule-name
conditional-partial-instantiation-meta-rule)
| null | https://raw.githubusercontent.com/opencog/pln/52dc099e21393892cf5529fef687a69682436b2d/opencog/pln/meta-rules/predicate/conditional-partial-instantiation.scm | scheme | =======================================================================
ImplicationScopeLink
P
Q
|-
T2
T3
|-
ImplicationScopeLink
V1
P[V2->T2,V3->T3]
Q[V2->T2,V3->T3]
-----------------------------------------------------------------------
Conditional partial instantiation rule ;;
substituted.
Produced rule rewrite. Apply formula to calculate the TV
over the partially substituted ImplicationScope.
Conclusion
only V1 remains
Premise
the Unquote appears
inside it, to avoid
running the
For now merely put the TV of Impl on PImpl
Name the meta rule | Conditional Partial Instantiation Meta Rule
V1 , V2 , V3
The fact that there 3 variables is hardcoded for now .
(use-modules (srfi srfi-1))
(use-modules (opencog exec))
(use-modules (opencog logger))
Hard code a 3 - ary ImplicationScope turning into a unary
ImplicationScope where V2 and V3 are substituted by terms .
(define conditional-partial-instantiation-meta-rule
(let* ((V1 (Variable "$V1"))
(V2 (Variable "$V2"))
(V3 (Variable "$V3"))
(V1Type (Variable "$V1Type"))
(V2Type (Variable "$V2Type"))
(V3Type (Variable "$V3Type"))
(VariableT (Type "VariableNode"))
(TypeChoiceT (Type "TypeChoice"))
(TypeT (Type "TypeNode"))
(VariableTypeT (TypeChoice TypeChoiceT TypeT))
(TypedV1 (TypedVariable V1 VariableT))
(TypedV2 (TypedVariable V2 VariableT))
(TypedV3 (TypedVariable V3 VariableT))
(TypedV1Type (TypedVariable V1Type VariableTypeT))
(TypedV2Type (TypedVariable V2Type VariableTypeT))
(TypedV3Type (TypedVariable V3Type VariableTypeT))
(P (Variable "$P"))
(Q (Variable "$Q"))
Meta rule variable declaration
(meta-vardecl (VariableList
TypedV1 TypedV2 TypedV3
TypedV1Type TypedV2Type TypedV3Type
P Q))
Meta rule main clause
(implication (Quote
(ImplicationScope
(Unquote (VariableList
(TypedVariable V1 V1Type)
(TypedVariable V2 V2Type)
(TypedVariable V3 V3Type)))
(Unquote P)
(Unquote Q))))
Meta rule precondition
(meta-precondition (Evaluation
(GroundedPredicate "scm: gt-zero-confidence")
implication))
Meta rule pattern
(meta-pattern (And (Present implication) meta-precondition))
Produced rule variable declaration . V2 and V3 are to be
(produced-vardecl (VariableList
(TypedVariable V2 V2Type)
(TypedVariable V3 V3Type)))
Produced rule pattern . Just look for groundings of V2 and V3
(produced-pattern (And V2 V3))
(produced-rewrite (ExecutionOutput
(GroundedSchema "scm: conditional-partial-instantiation-formula")
(Unquote
(List
(Quote
(ImplicationScope
(Unquote
(Unquote P)
(Unquote Q)))
implication))))
Meta rule rewrite
(meta-rewrite (Quote (Bind
(Unquote produced-vardecl)
(Unquote produced-pattern)
ExecutionOutput
))))
(Bind
meta-vardecl
meta-pattern
meta-rewrite)))
(define (conditional-partial-instantiation-formula PImpl Impl)
(cog-set-tv! PImpl (cog-tv Impl)))
(define conditional-partial-instantiation-meta-rule-name
(DefinedSchemaNode "conditional-partial-instantiation-meta-rule"))
(DefineLink conditional-partial-instantiation-meta-rule-name
conditional-partial-instantiation-meta-rule)
|
9c20726586234802133ec7c845fe9a4e0d97776a17cdbcb5e34d2c6b55a3fe28 | shayan-najd/NativeMetaprogramming | T5236.hs | # LANGUAGE MultiParamTypeClasses , FunctionalDependencies , FlexibleContexts #
module T5236 where
data A
data B
class Id a b | a -> b, b -> a
instance Id A A
instance Id B B
loop :: Id A B => Bool
loop = True
f : :
-- f = loop
| null | https://raw.githubusercontent.com/shayan-najd/NativeMetaprogramming/24e5f85990642d3f0b0044be4327b8f52fce2ba3/testsuite/tests/typecheck/should_fail/T5236.hs | haskell | f = loop | # LANGUAGE MultiParamTypeClasses , FunctionalDependencies , FlexibleContexts #
module T5236 where
data A
data B
class Id a b | a -> b, b -> a
instance Id A A
instance Id B B
loop :: Id A B => Bool
loop = True
f : :
|
a35548795b23b05244b5247a2ed4952ac9100a2b339d321ab165018141a4f909 | electric-sql/vaxine | prop_flag_dw.erl | %% -------------------------------------------------------------------
%%
Copyright < 2013 - 2018 > <
Technische Universität Kaiserslautern , Germany
, France
Universidade NOVA de Lisboa , Portugal
Université catholique de Louvain ( UCL ) , Belgique
, Portugal
%% >
%%
This file is provided to you under the Apache License ,
%% Version 2.0 (the "License"); you may not use this file
except in compliance with the License . You may obtain
%% a copy of the License at
%%
%% -2.0
%%
%% Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
" AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY
%% KIND, either expressed or implied. See the License for the
%% specific language governing permissions and limitations
%% under the License.
%%
List of the contributors to the development of Antidote : see file .
%% Description and complete License: see LICENSE file.
%% -------------------------------------------------------------------
-module(prop_flag_dw).
-define(PROPER_NO_TRANS, true).
-include_lib("proper/include/proper.hrl").
%% API
-export([prop_flag_dw_spec/0, op/0, spec/1]).
prop_flag_dw_spec() ->
crdt_properties:crdt_satisfies_spec(antidote_crdt_flag_dw, fun op/0, fun spec/1).
spec(Operations) ->
LatestOps = crdt_properties:latest_operations(Operations),
Enables = [enable || {enable, {}} <- LatestOps],
Disables = [disable || {disable, {}} <- LatestOps],
% returns true, when there is an enable-operation and no disable operation among the latest operations:
Enables =/= [] andalso Disables == [].
% generates a random operation
op() ->
oneof([
{enable, {}},
{disable, {}},
{reset, {}}
]).
| null | https://raw.githubusercontent.com/electric-sql/vaxine/872a83ea8d4935a52c7b850bb17ab099ee9c346b/apps/antidote_crdt/test/prop_flag_dw.erl | erlang | -------------------------------------------------------------------
>
Version 2.0 (the "License"); you may not use this file
a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing,
KIND, either expressed or implied. See the License for the
specific language governing permissions and limitations
under the License.
Description and complete License: see LICENSE file.
-------------------------------------------------------------------
API
returns true, when there is an enable-operation and no disable operation among the latest operations:
generates a random operation | Copyright < 2013 - 2018 > <
Technische Universität Kaiserslautern , Germany
, France
Universidade NOVA de Lisboa , Portugal
Université catholique de Louvain ( UCL ) , Belgique
, Portugal
This file is provided to you under the Apache License ,
except in compliance with the License . You may obtain
software distributed under the License is distributed on an
" AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY
List of the contributors to the development of Antidote : see file .
-module(prop_flag_dw).
-define(PROPER_NO_TRANS, true).
-include_lib("proper/include/proper.hrl").
-export([prop_flag_dw_spec/0, op/0, spec/1]).
prop_flag_dw_spec() ->
crdt_properties:crdt_satisfies_spec(antidote_crdt_flag_dw, fun op/0, fun spec/1).
spec(Operations) ->
LatestOps = crdt_properties:latest_operations(Operations),
Enables = [enable || {enable, {}} <- LatestOps],
Disables = [disable || {disable, {}} <- LatestOps],
Enables =/= [] andalso Disables == [].
op() ->
oneof([
{enable, {}},
{disable, {}},
{reset, {}}
]).
|
11026efc10dabd323ac71dbd35cfba957de18abaa21ea4df4681b6450b2b5691 | jonase/eastwood | priority_map.clj | Copyright ( c ) , and contributors . All rights reserved .
;; The use and distribution terms for this software are covered by the
;; Eclipse Public License 1.0 (-1.0.php)
;; which can be found in the file epl-v10.html at the root of this distribution.
;; By using this software in any fashion, you are agreeing to be bound by
;; the terms of this license.
;; You must not remove this notice, or any other, from this software.
;; A priority map is a map from items to priorities,
;; offering queue-like peek/pop as well as the map-like ability to
;; easily reassign priorities and other conveniences.
by ( )
Last update - July 9 , 2018
(ns
^{:author "Mark Engelberg",
:doc "A priority map is very similar to a sorted map, but whereas a sorted map produces a
sequence of the entries sorted by key, a priority map produces the entries sorted by value.
In addition to supporting all the functions a sorted map supports, a priority map
can also be thought of as a queue of [item priority] pairs. To support usage as
a versatile priority queue, priority maps also support conj/peek/pop operations.
The standard way to construct a priority map is with priority-map:
user=> (def p (priority-map :a 2 :b 1 :c 3 :d 5 :e 4 :f 3))
#'user/p
user=> p
{:b 1, :a 2, :c 3, :f 3, :e 4, :d 5}
So :b has priority 1, :a has priority 2, and so on.
Notice how the priority map prints in an order sorted by its priorities (i.e., the map's values)
We can use assoc to assign a priority to a new item:
user=> (assoc p :g 1)
{:b 1, :g 1, :a 2, :c 3, :f 3, :e 4, :d 5}
or to assign a new priority to an extant item:
user=> (assoc p :c 4)
{:b 1, :a 2, :f 3, :c 4, :e 4, :d 5}
We can remove an item from the priority map:
user=> (dissoc p :e)
{:b 1, :a 2, :c 3, :f 3, :d 5}
An alternative way to add to the priority map is to conj a [item priority] pair:
user=> (conj p [:g 0])
{:g 0, :b 1, :a 2, :c 3, :f 3, :e 4, :d 5}
or use into:
user=> (into p [[:g 0] [:h 1] [:i 2]])
{:g 0, :b 1, :h 1, :a 2, :i 2, :c 3, :f 3, :e 4, :d 5}
Priority maps are countable:
user=> (count p)
6
Like other maps, equivalence is based not on type, but on contents.
In other words, just as a sorted-map can be equal to a hash-map,
so can a priority-map.
user=> (= p {:b 1, :a 2, :c 3, :f 3, :e 4, :d 5})
true
You can test them for emptiness:
user=> (empty? (priority-map))
true
user=> (empty? p)
false
You can test whether an item is in the priority map:
user=> (contains? p :a)
true
user=> (contains? p :g)
false
It is easy to look up the priority of a given item, using any of the standard map mechanisms:
user=> (get p :a)
2
user=> (get p :g 10)
10
user=> (p :a)
2
user=> (:a p)
2
Priority maps derive much of their utility by providing priority-based seq.
Note that no guarantees are made about the order in which items of the same priority appear.
user=> (seq p)
([:b 1] [:a 2] [:c 3] [:f 3] [:e 4] [:d 5])
Because no guarantees are made about the order of same-priority items, note that
rseq might not be an exact reverse of the seq. It is only guaranteed to be in
descending order.
user=> (rseq p)
([:d 5] [:e 4] [:c 3] [:f 3] [:a 2] [:b 1])
This means first/rest/next/for/map/etc. all operate in priority order.
user=> (first p)
[:b 1]
user=> (rest p)
([:a 2] [:c 3] [:f 3] [:e 4] [:d 5])
Priority maps also support subseq and rsubseq, however, *you must use the subseq and rsubseq
defined in the eastwood.copieddeps.dep5.clojure.data.priority-map namespace*, which patches longstanding JIRA issue
[CLJ-428](-428). These patched versions
of subseq and rsubseq will work on Clojure's other sorted collections as well, so you can
use them as a drop-in replacement for the subseq and rsubseq found in core.
user=> (subseq p < 3)
([:b 1] [:a 2])
user=> (subseq p >= 3)
([:c 3] [:f 3] [:e 4] [:d 5])
user=> (subseq p >= 2 < 4)
([:a 2] [:c 3] [:f 3])
user=> (rsubseq p < 4)
([:c 3] [:f 3] [:a 2] [:b 1])
user=> (rsubseq p >= 4)
([:d 5] [:e 4])
Priority maps support metadata:
user=> (meta (with-meta p {:extra :info}))
{:extra :info}
But perhaps most importantly, priority maps can also function as priority queues.
peek, like first, gives you the first [item priority] pair in the collection.
pop removes the first [item priority] from the collection.
(Note that unlike rest, which returns a seq, pop returns a priority map).
user=> (peek p)
[:b 1]
user=> (pop p)
{:a 2, :c 3, :f 3, :e 4, :d 5}
It is also possible to use a custom comparator:
user=> (priority-map-by > :a 1 :b 2 :c 3)
{:c 3, :b 2, :a 1}
Sometimes, it is desirable to have a map where the values contain more information
than just the priority. For example, let's say you want a map like:
{:a [2 :apple], :b [1 :banana], :c [3 :carrot]}
and you want to sort the map by the numeric priority found in the pair.
A common mistake is to try to solve this with a custom comparator:
(priority-map-by
(fn [[priority1 _] [priority2 _]] (< priority1 priority2))
:a [2 :apple], :b [1 :banana], :c [3 :carrot])
This will not work! Although it may appear to work with these particular values, it is not safe.
In Clojure, like Java, all comparators must be *total orders*,
meaning that you can't have a tie unless the objects you are comparing are
in fact equal. The above comparator breaks that rule because objects such as
`[2 :apple]` and `[2 :apricot]` would tie, but are not equal.
The correct way to construct such a priority map is by specifying a keyfn, which is used
to extract the true priority from the priority map's vals. (Note: It might seem a little odd
that the priority-extraction function is called a *key*fn, even though it is applied to the
map's values. This terminology is based on the docstring of clojure.core/sort-by, which
uses `keyfn` for the function which extracts the sort order.)
In the above example,
user=> (priority-map-keyfn first :a [2 :apple], :b [1 :banana], :c [3 :carrot])
{:b [1 :banana], :a [2 :apple], :c [3 :carrot]}
You can also combine a keyfn with a comparator that operates on the extracted priorities:
user=> (priority-map-keyfn-by
first >
:a [2 :apple], :b [1 :banana], :c [3 :carrot])
{:c [3 :carrot], :a [2 :apple], :b [1 :banana]}
All of these operations are efficient. Generally speaking, most operations
are O(log n) where n is the number of distinct priorities. Some operations
(for example, straightforward lookup of an item's priority, or testing
whether a given item is in the priority map) are as efficient
as Clojure's built-in map.
The key to this efficiency is that internally, not only does the priority map store
an ordinary hash map of items to priority, but it also stores a sorted map that
maps priorities to sets of items with that priority.
A typical textbook priority queue data structure supports at the ability to add
a [item priority] pair to the queue, and to pop/peek the next [item priority] pair.
But many real-world applications of priority queues require more features, such
as the ability to test whether something is already in the queue, or to reassign
a priority. For example, a standard formulation of Dijkstra's algorithm requires the
ability to reduce the priority number associated with a given item. Once you
throw persistence into the mix with the desire to adjust priorities, the traditional
structures just don't work that well.
This particular blend of Clojure's built-in hash sets, hash maps, and sorted maps
proved to be a great way to implement an especially flexible persistent priority queue.
Connoisseurs of algorithms will note that this structure's peek operation is not O(1) as
it would be if based upon a heap data structure, but I feel this is a small concession for
the blend of persistence, priority reassignment, and priority-sorted seq, which can be
quite expensive to achieve with a heap (I did actually try this for comparison). Furthermore,
this peek's logarithmic behavior is quite good (on my computer I can do a million
peeks at a priority map with a million items in 750ms). Also, consider that peek and pop
usually follow one another, and even with a heap, pop is logarithmic. So the net combination
of peek and pop is not much different between this versatile formulation of a priority map and
a more limited heap-based one. In a nutshell, peek, although not O(1), is unlikely to be the
bottleneck in your program.
All in all, I hope you will find priority maps to be an easy-to-use and useful addition
to Clojure's assortment of built-in maps (hash-map and sorted-map).
"}
eastwood.copieddeps.dep5.clojure.data.priority-map
(:refer-clojure :exclude [subseq rsubseq])
(:import clojure.lang.MapEntry java.util.Map clojure.lang.PersistentTreeMap))
(declare pm-empty)
(defmacro apply-keyfn [x]
`(if ~'keyfn (~'keyfn ~x) ~x))
(defmacro ^:private compile-if [test then else]
(if (eval test)
then
else))
We create a patched version of subseq and rsubseq from core , that works on ordinary sorted collections , as well as priority maps
;; See -428
(defn mk-bound-fn
{:private true}
[^clojure.lang.Sorted sc test key]
(fn [e] (test (.. sc comparator (compare (. sc entryKey e) key)) 0)))
(defn subseq
"sc must be a sorted collection, test(s) one of <, <=, > or
>=. Returns a seq of those entries with keys ek for
which (test (.. sc comparator (compare ek key)) 0) is true"
([^clojure.lang.Sorted sc test key]
(let [include (mk-bound-fn sc test key)]
(if (#{> >=} test)
(when-let [[e :as s] (. sc seqFrom key true)]
(seq (drop-while #(not (include %)) s)))
(seq (take-while include (. sc seq true))))))
([^clojure.lang.Sorted sc start-test start-key end-test end-key]
(when-let [[e :as s] (. sc seqFrom start-key true)]
(seq (take-while (mk-bound-fn sc end-test end-key)
(drop-while (complement (mk-bound-fn sc start-test start-key)) s))))))
(defn rsubseq
"sc must be a sorted collection, test(s) one of <, <=, > or
>=. Returns a reverse seq of those entries with keys ek for
which (test (.. sc comparator (compare ek key)) 0) is true"
([^clojure.lang.Sorted sc test key]
(let [include (mk-bound-fn sc test key)]
(if (#{< <=} test)
(when-let [[e :as s] (. sc seqFrom key false)]
(seq (drop-while #(not (include %)) s)))
(seq (take-while include (. sc seq false))))))
([^clojure.lang.Sorted sc start-test start-key end-test end-key]
(when-let [[e :as s] (. sc seqFrom end-key false)]
(seq (take-while (mk-bound-fn sc start-test start-key)
(drop-while (complement (mk-bound-fn sc end-test end-key)) s))))))
;; A Priority Map is comprised of a sorted map that maps priorities to hash sets of items
;; with that priority (priority->set-of-items),
;; as well as a hash map that maps items to priorities (item->priority)
;; Priority maps may also have metadata
;; Priority maps can also have a keyfn which is applied to the "priorities" found as values in
;; the item->priority map to get the actual sortable priority keys used in priority->set-of-items.
(deftype PersistentPriorityMap [priority->set-of-items item->priority _meta keyfn]
Object
(toString [this] (str (.seq this)))
clojure.lang.ILookup
;; valAt gives (get pm key) and (get pm key not-found) behavior
(valAt [this item] (get item->priority item))
(valAt [this item not-found] (get item->priority item not-found))
clojure.lang.IPersistentMap
(count [this] (count item->priority))
(assoc [this item priority]
(let [current-priority (get item->priority item nil)]
(if current-priority
Case 1 - item is already in priority map , so this is a reassignment
(if (= current-priority priority)
1 - no change in priority , do nothing
this
(let [priority-key (apply-keyfn priority)
current-priority-key (apply-keyfn current-priority)
item-set (get priority->set-of-items current-priority-key)]
(if (= (count item-set) 1)
2 - it was the only item of this priority
;;so remove old priority entirely
and item onto new priority 's set
(PersistentPriorityMap.
(assoc (dissoc priority->set-of-items current-priority-key)
priority-key (conj (get priority->set-of-items priority-key #{}) item))
(assoc item->priority item priority)
(meta this)
keyfn)
3 - there were many items associated with the item 's original priority ,
;;so remove it from the old set and conj it onto the new one.
(PersistentPriorityMap.
(assoc priority->set-of-items
current-priority-key (disj (get priority->set-of-items current-priority-key) item)
priority-key (conj (get priority->set-of-items priority-key #{}) item))
(assoc item->priority item priority)
(meta this)
keyfn))))
;; Case 2: Item is new to the priority map, so just add it.
(let [priority-key (apply-keyfn priority)]
(PersistentPriorityMap.
(assoc priority->set-of-items
priority-key (conj (get priority->set-of-items priority-key #{}) item))
(assoc item->priority item priority)
(meta this)
keyfn)))))
(empty [this] (PersistentPriorityMap. (empty priority->set-of-items) {} _meta keyfn))
;; cons defines conj behavior
(cons [this e]
(if (map? e)
(into this e)
(let [[item priority] e] (.assoc this item priority))))
;; Like sorted maps, priority maps are equal to other maps provided
;; their key-value pairs are the same.
(equiv [this o] (= item->priority o))
(hashCode [this] (.hashCode item->priority))
(equals [this o] (or (identical? this o) (.equals item->priority o)))
;;containsKey implements (contains? pm k) behavior
(containsKey [this item] (contains? item->priority item))
(entryAt [this k]
(let [v (.valAt this k this)]
(when-not (identical? v this)
(MapEntry. k v))))
(seq [this]
(if keyfn
(seq (for [[priority item-set] priority->set-of-items, item item-set]
(MapEntry. item (item->priority item))))
(seq (for [[priority item-set] priority->set-of-items, item item-set]
(MapEntry. item priority)))))
;;without implements (dissoc pm k) behavior
(without
[this item]
(let [priority (item->priority item ::not-found)]
(if (= priority ::not-found)
;; If item is not in map, return the map unchanged.
this
(let [priority-key (apply-keyfn priority)
item-set (priority->set-of-items priority-key)]
(if (= (count item-set) 1)
;;If it is the only item with this priority, remove that priority's set completely
(PersistentPriorityMap. (dissoc priority->set-of-items priority-key)
(dissoc item->priority item)
(meta this)
keyfn)
;;Otherwise, just remove the item from the priority's set.
(PersistentPriorityMap.
(assoc priority->set-of-items priority-key (disj item-set item)),
(dissoc item->priority item)
(meta this)
keyfn))))))
clojure.lang.IHashEq
(hasheq [this]
(compile-if (resolve 'clojure.core/hash-unordered-coll)
(hash-unordered-coll this)
(.hashCode this)))
java.io.Serializable ;Serialization comes for free with the other things implemented
clojure.lang.MapEquivalence
Makes this compatible with java 's map
(size [this] (count item->priority))
(isEmpty [this] (zero? (count item->priority)))
(containsValue [this v]
(if keyfn
(some (partial = v) (vals this)) ; no shortcut if there is a keyfn
(contains? priority->set-of-items v)))
(get [this k] (.valAt this k))
(put [this k v] (throw (UnsupportedOperationException.)))
(remove [this k] (throw (UnsupportedOperationException.)))
(putAll [this m] (throw (UnsupportedOperationException.)))
(clear [this] (throw (UnsupportedOperationException.)))
(keySet [this] (set (keys this)))
(values [this] (vals this))
(entrySet [this] (set this))
Iterable
(iterator [this] (clojure.lang.SeqIterator. (seq this)))
clojure.core.protocols/IKVReduce
(kv-reduce [this f init]
(if keyfn
(reduce-kv (fn [a k v]
(reduce (fn [a v] (f a v (item->priority v))) a v))
init priority->set-of-items)
(reduce-kv (fn [a k v]
(reduce (fn [a v] (f a v k)) a v))
init priority->set-of-items)))
clojure.lang.IPersistentStack
(peek [this]
(when-not (.isEmpty this)
(let [f (first priority->set-of-items)
item (first (val f))]
(if keyfn
(MapEntry. item (item->priority item))
(MapEntry. item (key f))))))
(pop [this]
(if (.isEmpty this) (throw (IllegalStateException. "Can't pop empty priority map"))
(let [f (first priority->set-of-items),
item-set (val f)
item (first item-set),
priority-key (key f)]
(if (= (count item-set) 1)
If the first item is the only item with its priority , remove that priority 's set completely
(PersistentPriorityMap.
(dissoc priority->set-of-items priority-key)
(dissoc item->priority item)
(meta this)
keyfn)
;;Otherwise, just remove the item from the priority's set.
(PersistentPriorityMap.
(assoc priority->set-of-items priority-key (disj item-set item)),
(dissoc item->priority item)
(meta this)
keyfn)))))
clojure.lang.IFn
;;makes priority map usable as a function
(invoke [this k] (.valAt this k))
(invoke [this k not-found] (.valAt this k not-found))
clojure.lang.IObj
;;adds metadata support
(meta [this] _meta)
(withMeta [this m] (PersistentPriorityMap. priority->set-of-items item->priority m keyfn))
clojure.lang.Reversible
(rseq [this]
(if keyfn
(seq (for [[priority item-set] (rseq priority->set-of-items), item item-set]
(MapEntry. item (item->priority item))))
(seq (for [[priority item-set] (rseq priority->set-of-items), item item-set]
(MapEntry. item priority)))))
clojure.lang.Sorted
These methods provide support for subseq and rsubseq
(comparator [this] (.comparator ^PersistentTreeMap priority->set-of-items))
(entryKey [this entry] (if keyfn (keyfn (val entry)) (val entry)))
(seqFrom [this k ascending]
(let [sets (if ascending (subseq priority->set-of-items >= k) (rsubseq priority->set-of-items <= k))]
(if keyfn
(seq (for [[priority item-set] sets, item item-set]
(MapEntry. item (item->priority item))))
(seq (for [[priority item-set] sets, item item-set]
(MapEntry. item priority))))))
(seq [this ascending]
(if ascending (seq this) (rseq this))))
(def ^:private pm-empty (PersistentPriorityMap. (sorted-map) {} {} nil))
(defn- pm-empty-by [comparator] (PersistentPriorityMap. (sorted-map-by comparator) {} {} nil))
(defn- pm-empty-keyfn
([keyfn] (PersistentPriorityMap. (sorted-map) {} {} keyfn))
([keyfn comparator] (PersistentPriorityMap. (sorted-map-by comparator) {} {} keyfn)))
;; The main way to build priority maps
(defn priority-map
"Usage: (priority-map key val key val ...)
Returns a new priority map with optional supplied mappings.
(priority-map) returns an empty priority map."
[& keyvals]
{:pre [(even? (count keyvals))]}
(reduce conj pm-empty (partition 2 keyvals)))
(defn priority-map-by
"Usage: (priority-map comparator key val key val ...)
Returns a new priority map with custom comparator and optional supplied mappings.
(priority-map-by comparator) yields an empty priority map with custom comparator."
[comparator & keyvals]
{:pre [(even? (count keyvals))]}
(reduce conj (pm-empty-by comparator) (partition 2 keyvals)))
(defn priority-map-keyfn
"Usage: (priority-map-keyfn keyfn key val key val ...)
Returns a new priority map with custom keyfn and optional supplied mappings.
The priority is determined by comparing (keyfn val).
(priority-map-keyfn keyfn) yields an empty priority map with custom keyfn."
[keyfn & keyvals]
{:pre [(even? (count keyvals))]}
(reduce conj (pm-empty-keyfn keyfn) (partition 2 keyvals)))
(defn priority-map-keyfn-by
"Usage: (priority-map-keyfn-by keyfn comparator key val key val ...)
Returns a new priority map with custom keyfn, custom comparator, and optional supplied mappings.
The priority is determined by comparing (keyfn val).
(priority-map-keyfn-by keyfn comparator) yields an empty priority map with custom keyfn and comparator."
[keyfn comparator & keyvals]
{:pre [(even? (count keyvals))]}
(reduce conj (pm-empty-keyfn keyfn comparator) (partition 2 keyvals)))
(defn priority->set-of-items
"Takes a priority map p, and returns a sorted map from each priority
to the set of items with that priority in p"
[^PersistentPriorityMap p]
(.priority->set-of-items p))
| null | https://raw.githubusercontent.com/jonase/eastwood/caf87206706d51d59b04c5ad0c61ff7683d70cb1/copied-deps/eastwood/copieddeps/dep5/clojure/data/priority_map.clj | clojure | The use and distribution terms for this software are covered by the
Eclipse Public License 1.0 (-1.0.php)
which can be found in the file epl-v10.html at the root of this distribution.
By using this software in any fashion, you are agreeing to be bound by
the terms of this license.
You must not remove this notice, or any other, from this software.
A priority map is a map from items to priorities,
offering queue-like peek/pop as well as the map-like ability to
easily reassign priorities and other conveniences.
See -428
A Priority Map is comprised of a sorted map that maps priorities to hash sets of items
with that priority (priority->set-of-items),
as well as a hash map that maps items to priorities (item->priority)
Priority maps may also have metadata
Priority maps can also have a keyfn which is applied to the "priorities" found as values in
the item->priority map to get the actual sortable priority keys used in priority->set-of-items.
valAt gives (get pm key) and (get pm key not-found) behavior
so remove old priority entirely
so remove it from the old set and conj it onto the new one.
Case 2: Item is new to the priority map, so just add it.
cons defines conj behavior
Like sorted maps, priority maps are equal to other maps provided
their key-value pairs are the same.
containsKey implements (contains? pm k) behavior
without implements (dissoc pm k) behavior
If item is not in map, return the map unchanged.
If it is the only item with this priority, remove that priority's set completely
Otherwise, just remove the item from the priority's set.
Serialization comes for free with the other things implemented
no shortcut if there is a keyfn
Otherwise, just remove the item from the priority's set.
makes priority map usable as a function
adds metadata support
The main way to build priority maps | Copyright ( c ) , and contributors . All rights reserved .
by ( )
Last update - July 9 , 2018
(ns
^{:author "Mark Engelberg",
:doc "A priority map is very similar to a sorted map, but whereas a sorted map produces a
sequence of the entries sorted by key, a priority map produces the entries sorted by value.
In addition to supporting all the functions a sorted map supports, a priority map
can also be thought of as a queue of [item priority] pairs. To support usage as
a versatile priority queue, priority maps also support conj/peek/pop operations.
The standard way to construct a priority map is with priority-map:
user=> (def p (priority-map :a 2 :b 1 :c 3 :d 5 :e 4 :f 3))
#'user/p
user=> p
{:b 1, :a 2, :c 3, :f 3, :e 4, :d 5}
So :b has priority 1, :a has priority 2, and so on.
Notice how the priority map prints in an order sorted by its priorities (i.e., the map's values)
We can use assoc to assign a priority to a new item:
user=> (assoc p :g 1)
{:b 1, :g 1, :a 2, :c 3, :f 3, :e 4, :d 5}
or to assign a new priority to an extant item:
user=> (assoc p :c 4)
{:b 1, :a 2, :f 3, :c 4, :e 4, :d 5}
We can remove an item from the priority map:
user=> (dissoc p :e)
{:b 1, :a 2, :c 3, :f 3, :d 5}
An alternative way to add to the priority map is to conj a [item priority] pair:
user=> (conj p [:g 0])
{:g 0, :b 1, :a 2, :c 3, :f 3, :e 4, :d 5}
or use into:
user=> (into p [[:g 0] [:h 1] [:i 2]])
{:g 0, :b 1, :h 1, :a 2, :i 2, :c 3, :f 3, :e 4, :d 5}
Priority maps are countable:
user=> (count p)
6
Like other maps, equivalence is based not on type, but on contents.
In other words, just as a sorted-map can be equal to a hash-map,
so can a priority-map.
user=> (= p {:b 1, :a 2, :c 3, :f 3, :e 4, :d 5})
true
You can test them for emptiness:
user=> (empty? (priority-map))
true
user=> (empty? p)
false
You can test whether an item is in the priority map:
user=> (contains? p :a)
true
user=> (contains? p :g)
false
It is easy to look up the priority of a given item, using any of the standard map mechanisms:
user=> (get p :a)
2
user=> (get p :g 10)
10
user=> (p :a)
2
user=> (:a p)
2
Priority maps derive much of their utility by providing priority-based seq.
Note that no guarantees are made about the order in which items of the same priority appear.
user=> (seq p)
([:b 1] [:a 2] [:c 3] [:f 3] [:e 4] [:d 5])
Because no guarantees are made about the order of same-priority items, note that
rseq might not be an exact reverse of the seq. It is only guaranteed to be in
descending order.
user=> (rseq p)
([:d 5] [:e 4] [:c 3] [:f 3] [:a 2] [:b 1])
This means first/rest/next/for/map/etc. all operate in priority order.
user=> (first p)
[:b 1]
user=> (rest p)
([:a 2] [:c 3] [:f 3] [:e 4] [:d 5])
Priority maps also support subseq and rsubseq, however, *you must use the subseq and rsubseq
defined in the eastwood.copieddeps.dep5.clojure.data.priority-map namespace*, which patches longstanding JIRA issue
[CLJ-428](-428). These patched versions
of subseq and rsubseq will work on Clojure's other sorted collections as well, so you can
use them as a drop-in replacement for the subseq and rsubseq found in core.
user=> (subseq p < 3)
([:b 1] [:a 2])
user=> (subseq p >= 3)
([:c 3] [:f 3] [:e 4] [:d 5])
user=> (subseq p >= 2 < 4)
([:a 2] [:c 3] [:f 3])
user=> (rsubseq p < 4)
([:c 3] [:f 3] [:a 2] [:b 1])
user=> (rsubseq p >= 4)
([:d 5] [:e 4])
Priority maps support metadata:
user=> (meta (with-meta p {:extra :info}))
{:extra :info}
But perhaps most importantly, priority maps can also function as priority queues.
peek, like first, gives you the first [item priority] pair in the collection.
pop removes the first [item priority] from the collection.
(Note that unlike rest, which returns a seq, pop returns a priority map).
user=> (peek p)
[:b 1]
user=> (pop p)
{:a 2, :c 3, :f 3, :e 4, :d 5}
It is also possible to use a custom comparator:
user=> (priority-map-by > :a 1 :b 2 :c 3)
{:c 3, :b 2, :a 1}
Sometimes, it is desirable to have a map where the values contain more information
than just the priority. For example, let's say you want a map like:
{:a [2 :apple], :b [1 :banana], :c [3 :carrot]}
and you want to sort the map by the numeric priority found in the pair.
A common mistake is to try to solve this with a custom comparator:
(priority-map-by
(fn [[priority1 _] [priority2 _]] (< priority1 priority2))
:a [2 :apple], :b [1 :banana], :c [3 :carrot])
This will not work! Although it may appear to work with these particular values, it is not safe.
In Clojure, like Java, all comparators must be *total orders*,
meaning that you can't have a tie unless the objects you are comparing are
in fact equal. The above comparator breaks that rule because objects such as
`[2 :apple]` and `[2 :apricot]` would tie, but are not equal.
The correct way to construct such a priority map is by specifying a keyfn, which is used
to extract the true priority from the priority map's vals. (Note: It might seem a little odd
that the priority-extraction function is called a *key*fn, even though it is applied to the
map's values. This terminology is based on the docstring of clojure.core/sort-by, which
uses `keyfn` for the function which extracts the sort order.)
In the above example,
user=> (priority-map-keyfn first :a [2 :apple], :b [1 :banana], :c [3 :carrot])
{:b [1 :banana], :a [2 :apple], :c [3 :carrot]}
You can also combine a keyfn with a comparator that operates on the extracted priorities:
user=> (priority-map-keyfn-by
first >
:a [2 :apple], :b [1 :banana], :c [3 :carrot])
{:c [3 :carrot], :a [2 :apple], :b [1 :banana]}
All of these operations are efficient. Generally speaking, most operations
are O(log n) where n is the number of distinct priorities. Some operations
(for example, straightforward lookup of an item's priority, or testing
whether a given item is in the priority map) are as efficient
as Clojure's built-in map.
The key to this efficiency is that internally, not only does the priority map store
an ordinary hash map of items to priority, but it also stores a sorted map that
maps priorities to sets of items with that priority.
A typical textbook priority queue data structure supports at the ability to add
a [item priority] pair to the queue, and to pop/peek the next [item priority] pair.
But many real-world applications of priority queues require more features, such
as the ability to test whether something is already in the queue, or to reassign
a priority. For example, a standard formulation of Dijkstra's algorithm requires the
ability to reduce the priority number associated with a given item. Once you
throw persistence into the mix with the desire to adjust priorities, the traditional
structures just don't work that well.
This particular blend of Clojure's built-in hash sets, hash maps, and sorted maps
proved to be a great way to implement an especially flexible persistent priority queue.
Connoisseurs of algorithms will note that this structure's peek operation is not O(1) as
it would be if based upon a heap data structure, but I feel this is a small concession for
the blend of persistence, priority reassignment, and priority-sorted seq, which can be
quite expensive to achieve with a heap (I did actually try this for comparison). Furthermore,
this peek's logarithmic behavior is quite good (on my computer I can do a million
peeks at a priority map with a million items in 750ms). Also, consider that peek and pop
usually follow one another, and even with a heap, pop is logarithmic. So the net combination
of peek and pop is not much different between this versatile formulation of a priority map and
a more limited heap-based one. In a nutshell, peek, although not O(1), is unlikely to be the
bottleneck in your program.
All in all, I hope you will find priority maps to be an easy-to-use and useful addition
to Clojure's assortment of built-in maps (hash-map and sorted-map).
"}
eastwood.copieddeps.dep5.clojure.data.priority-map
(:refer-clojure :exclude [subseq rsubseq])
(:import clojure.lang.MapEntry java.util.Map clojure.lang.PersistentTreeMap))
(declare pm-empty)
(defmacro apply-keyfn [x]
`(if ~'keyfn (~'keyfn ~x) ~x))
(defmacro ^:private compile-if [test then else]
(if (eval test)
then
else))
We create a patched version of subseq and rsubseq from core , that works on ordinary sorted collections , as well as priority maps
(defn mk-bound-fn
{:private true}
[^clojure.lang.Sorted sc test key]
(fn [e] (test (.. sc comparator (compare (. sc entryKey e) key)) 0)))
(defn subseq
"sc must be a sorted collection, test(s) one of <, <=, > or
>=. Returns a seq of those entries with keys ek for
which (test (.. sc comparator (compare ek key)) 0) is true"
([^clojure.lang.Sorted sc test key]
(let [include (mk-bound-fn sc test key)]
(if (#{> >=} test)
(when-let [[e :as s] (. sc seqFrom key true)]
(seq (drop-while #(not (include %)) s)))
(seq (take-while include (. sc seq true))))))
([^clojure.lang.Sorted sc start-test start-key end-test end-key]
(when-let [[e :as s] (. sc seqFrom start-key true)]
(seq (take-while (mk-bound-fn sc end-test end-key)
(drop-while (complement (mk-bound-fn sc start-test start-key)) s))))))
(defn rsubseq
"sc must be a sorted collection, test(s) one of <, <=, > or
>=. Returns a reverse seq of those entries with keys ek for
which (test (.. sc comparator (compare ek key)) 0) is true"
([^clojure.lang.Sorted sc test key]
(let [include (mk-bound-fn sc test key)]
(if (#{< <=} test)
(when-let [[e :as s] (. sc seqFrom key false)]
(seq (drop-while #(not (include %)) s)))
(seq (take-while include (. sc seq false))))))
([^clojure.lang.Sorted sc start-test start-key end-test end-key]
(when-let [[e :as s] (. sc seqFrom end-key false)]
(seq (take-while (mk-bound-fn sc start-test start-key)
(drop-while (complement (mk-bound-fn sc end-test end-key)) s))))))
(deftype PersistentPriorityMap [priority->set-of-items item->priority _meta keyfn]
Object
(toString [this] (str (.seq this)))
clojure.lang.ILookup
(valAt [this item] (get item->priority item))
(valAt [this item not-found] (get item->priority item not-found))
clojure.lang.IPersistentMap
(count [this] (count item->priority))
(assoc [this item priority]
(let [current-priority (get item->priority item nil)]
(if current-priority
Case 1 - item is already in priority map , so this is a reassignment
(if (= current-priority priority)
1 - no change in priority , do nothing
this
(let [priority-key (apply-keyfn priority)
current-priority-key (apply-keyfn current-priority)
item-set (get priority->set-of-items current-priority-key)]
(if (= (count item-set) 1)
2 - it was the only item of this priority
and item onto new priority 's set
(PersistentPriorityMap.
(assoc (dissoc priority->set-of-items current-priority-key)
priority-key (conj (get priority->set-of-items priority-key #{}) item))
(assoc item->priority item priority)
(meta this)
keyfn)
3 - there were many items associated with the item 's original priority ,
(PersistentPriorityMap.
(assoc priority->set-of-items
current-priority-key (disj (get priority->set-of-items current-priority-key) item)
priority-key (conj (get priority->set-of-items priority-key #{}) item))
(assoc item->priority item priority)
(meta this)
keyfn))))
(let [priority-key (apply-keyfn priority)]
(PersistentPriorityMap.
(assoc priority->set-of-items
priority-key (conj (get priority->set-of-items priority-key #{}) item))
(assoc item->priority item priority)
(meta this)
keyfn)))))
(empty [this] (PersistentPriorityMap. (empty priority->set-of-items) {} _meta keyfn))
(cons [this e]
(if (map? e)
(into this e)
(let [[item priority] e] (.assoc this item priority))))
(equiv [this o] (= item->priority o))
(hashCode [this] (.hashCode item->priority))
(equals [this o] (or (identical? this o) (.equals item->priority o)))
(containsKey [this item] (contains? item->priority item))
(entryAt [this k]
(let [v (.valAt this k this)]
(when-not (identical? v this)
(MapEntry. k v))))
(seq [this]
(if keyfn
(seq (for [[priority item-set] priority->set-of-items, item item-set]
(MapEntry. item (item->priority item))))
(seq (for [[priority item-set] priority->set-of-items, item item-set]
(MapEntry. item priority)))))
(without
[this item]
(let [priority (item->priority item ::not-found)]
(if (= priority ::not-found)
this
(let [priority-key (apply-keyfn priority)
item-set (priority->set-of-items priority-key)]
(if (= (count item-set) 1)
(PersistentPriorityMap. (dissoc priority->set-of-items priority-key)
(dissoc item->priority item)
(meta this)
keyfn)
(PersistentPriorityMap.
(assoc priority->set-of-items priority-key (disj item-set item)),
(dissoc item->priority item)
(meta this)
keyfn))))))
clojure.lang.IHashEq
(hasheq [this]
(compile-if (resolve 'clojure.core/hash-unordered-coll)
(hash-unordered-coll this)
(.hashCode this)))
clojure.lang.MapEquivalence
Makes this compatible with java 's map
(size [this] (count item->priority))
(isEmpty [this] (zero? (count item->priority)))
(containsValue [this v]
(if keyfn
(contains? priority->set-of-items v)))
(get [this k] (.valAt this k))
(put [this k v] (throw (UnsupportedOperationException.)))
(remove [this k] (throw (UnsupportedOperationException.)))
(putAll [this m] (throw (UnsupportedOperationException.)))
(clear [this] (throw (UnsupportedOperationException.)))
(keySet [this] (set (keys this)))
(values [this] (vals this))
(entrySet [this] (set this))
Iterable
(iterator [this] (clojure.lang.SeqIterator. (seq this)))
clojure.core.protocols/IKVReduce
(kv-reduce [this f init]
(if keyfn
(reduce-kv (fn [a k v]
(reduce (fn [a v] (f a v (item->priority v))) a v))
init priority->set-of-items)
(reduce-kv (fn [a k v]
(reduce (fn [a v] (f a v k)) a v))
init priority->set-of-items)))
clojure.lang.IPersistentStack
(peek [this]
(when-not (.isEmpty this)
(let [f (first priority->set-of-items)
item (first (val f))]
(if keyfn
(MapEntry. item (item->priority item))
(MapEntry. item (key f))))))
(pop [this]
(if (.isEmpty this) (throw (IllegalStateException. "Can't pop empty priority map"))
(let [f (first priority->set-of-items),
item-set (val f)
item (first item-set),
priority-key (key f)]
(if (= (count item-set) 1)
If the first item is the only item with its priority , remove that priority 's set completely
(PersistentPriorityMap.
(dissoc priority->set-of-items priority-key)
(dissoc item->priority item)
(meta this)
keyfn)
(PersistentPriorityMap.
(assoc priority->set-of-items priority-key (disj item-set item)),
(dissoc item->priority item)
(meta this)
keyfn)))))
clojure.lang.IFn
(invoke [this k] (.valAt this k))
(invoke [this k not-found] (.valAt this k not-found))
clojure.lang.IObj
(meta [this] _meta)
(withMeta [this m] (PersistentPriorityMap. priority->set-of-items item->priority m keyfn))
clojure.lang.Reversible
(rseq [this]
(if keyfn
(seq (for [[priority item-set] (rseq priority->set-of-items), item item-set]
(MapEntry. item (item->priority item))))
(seq (for [[priority item-set] (rseq priority->set-of-items), item item-set]
(MapEntry. item priority)))))
clojure.lang.Sorted
These methods provide support for subseq and rsubseq
(comparator [this] (.comparator ^PersistentTreeMap priority->set-of-items))
(entryKey [this entry] (if keyfn (keyfn (val entry)) (val entry)))
(seqFrom [this k ascending]
(let [sets (if ascending (subseq priority->set-of-items >= k) (rsubseq priority->set-of-items <= k))]
(if keyfn
(seq (for [[priority item-set] sets, item item-set]
(MapEntry. item (item->priority item))))
(seq (for [[priority item-set] sets, item item-set]
(MapEntry. item priority))))))
(seq [this ascending]
(if ascending (seq this) (rseq this))))
(def ^:private pm-empty (PersistentPriorityMap. (sorted-map) {} {} nil))
(defn- pm-empty-by [comparator] (PersistentPriorityMap. (sorted-map-by comparator) {} {} nil))
(defn- pm-empty-keyfn
([keyfn] (PersistentPriorityMap. (sorted-map) {} {} keyfn))
([keyfn comparator] (PersistentPriorityMap. (sorted-map-by comparator) {} {} keyfn)))
(defn priority-map
"Usage: (priority-map key val key val ...)
Returns a new priority map with optional supplied mappings.
(priority-map) returns an empty priority map."
[& keyvals]
{:pre [(even? (count keyvals))]}
(reduce conj pm-empty (partition 2 keyvals)))
(defn priority-map-by
"Usage: (priority-map comparator key val key val ...)
Returns a new priority map with custom comparator and optional supplied mappings.
(priority-map-by comparator) yields an empty priority map with custom comparator."
[comparator & keyvals]
{:pre [(even? (count keyvals))]}
(reduce conj (pm-empty-by comparator) (partition 2 keyvals)))
(defn priority-map-keyfn
"Usage: (priority-map-keyfn keyfn key val key val ...)
Returns a new priority map with custom keyfn and optional supplied mappings.
The priority is determined by comparing (keyfn val).
(priority-map-keyfn keyfn) yields an empty priority map with custom keyfn."
[keyfn & keyvals]
{:pre [(even? (count keyvals))]}
(reduce conj (pm-empty-keyfn keyfn) (partition 2 keyvals)))
(defn priority-map-keyfn-by
"Usage: (priority-map-keyfn-by keyfn comparator key val key val ...)
Returns a new priority map with custom keyfn, custom comparator, and optional supplied mappings.
The priority is determined by comparing (keyfn val).
(priority-map-keyfn-by keyfn comparator) yields an empty priority map with custom keyfn and comparator."
[keyfn comparator & keyvals]
{:pre [(even? (count keyvals))]}
(reduce conj (pm-empty-keyfn keyfn comparator) (partition 2 keyvals)))
(defn priority->set-of-items
"Takes a priority map p, and returns a sorted map from each priority
to the set of items with that priority in p"
[^PersistentPriorityMap p]
(.priority->set-of-items p))
|
62568dcb79a062e626ac1548ca41d007dde0c09c3f0969259cf72b5c7e558a01 | l-x/deeperl | deeperl_glossary_delete.erl | @private
-module(deeperl_glossary_delete).
-behaviour(gen_deeperl_method).
%% API
-export([request/1, response/1]).
request({GlossaryId}) ->
{
delete,
{
"/v2/glossaries/" ++ GlossaryId,
[]
}
}.
response(_Body) ->
ok.
| null | https://raw.githubusercontent.com/l-x/deeperl/834fd8101e7057e090d5ab17b2a68c75f8e1656f/src/deeperl_glossary_delete.erl | erlang | API | @private
-module(deeperl_glossary_delete).
-behaviour(gen_deeperl_method).
-export([request/1, response/1]).
request({GlossaryId}) ->
{
delete,
{
"/v2/glossaries/" ++ GlossaryId,
[]
}
}.
response(_Body) ->
ok.
|
469ef5950de28d71a5545ea345a1be937d2e1ada67c7eccb18f014954e560502 | processone/ejabberd | prosody2ejabberd.erl | %%%-------------------------------------------------------------------
%%% File : prosody2ejabberd.erl
Author : < >
Created : 20 Jan 2016 by < >
%%%
%%%
ejabberd , Copyright ( C ) 2002 - 2023 ProcessOne
%%%
%%% This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation ; either version 2 of the
%%% License, or (at your option) any later version.
%%%
%%% This program is distributed in the hope that it will be useful,
%%% but WITHOUT ANY WARRANTY; without even the implied warranty of
%%% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
%%% General Public License for more details.
%%%
You should have received a copy of the GNU General Public License along
with this program ; if not , write to the Free Software Foundation , Inc. ,
51 Franklin Street , Fifth Floor , Boston , USA .
%%%
%%%----------------------------------------------------------------------
-module(prosody2ejabberd).
%% API
-export([from_dir/1]).
-include_lib("xmpp/include/scram.hrl").
-include_lib("xmpp/include/xmpp.hrl").
-include("logger.hrl").
-include("mod_roster.hrl").
-include("mod_offline.hrl").
-include("mod_privacy.hrl").
%%%===================================================================
%%% API
%%%===================================================================
from_dir(ProsodyDir) ->
case code:ensure_loaded(luerl) of
{module, _} ->
case file:list_dir(ProsodyDir) of
{ok, HostDirs} ->
lists:foreach(
fun(HostDir) ->
Host = list_to_binary(HostDir),
lists:foreach(
fun(SubDir) ->
Path = filename:join(
[ProsodyDir, HostDir, SubDir]),
convert_dir(Path, Host, SubDir)
end, ["vcard", "accounts", "roster",
"private", "config", "offline",
"privacy", "pep", "pubsub"])
end, HostDirs);
{error, Why} = Err ->
?ERROR_MSG("Failed to list ~ts: ~ts",
[ProsodyDir, file:format_error(Why)]),
Err
end;
{error, _} = Err ->
?ERROR_MSG("The file 'luerl.beam' is not found: maybe "
"ejabberd is not compiled with Lua support", []),
Err
end.
%%%===================================================================
Internal functions
%%%===================================================================
convert_dir(Path, Host, Type) ->
case file:list_dir(Path) of
{ok, Files} ->
lists:foreach(
fun(File) ->
FilePath = filename:join(Path, File),
case Type of
"pep" ->
case filelib:is_dir(FilePath) of
true ->
JID = list_to_binary(File ++ "@" ++ Host),
convert_dir(FilePath, JID, "pubsub");
false ->
ok
end;
_ ->
case eval_file(FilePath) of
{ok, Data} ->
Name = iolist_to_binary(filename:rootname(File)),
convert_data(url_decode(Host), Type,
url_decode(Name), Data);
Err ->
Err
end
end
end, Files);
{error, enoent} ->
ok;
{error, Why} = Err ->
?ERROR_MSG("Failed to list ~ts: ~ts",
[Path, file:format_error(Why)]),
Err
end.
eval_file(Path) ->
case file:read_file(Path) of
{ok, Data} ->
State0 = luerl:init(),
State1 = luerl:set_table([item],
fun([X], State) -> {[X], State} end,
State0),
NewData = case filename:extension(Path) of
".list" ->
<<"return {", Data/binary, "};">>;
_ ->
Data
end,
case luerl:eval(NewData, State1) of
{ok, _} = Res ->
Res;
{error, Why, _} = Err ->
?ERROR_MSG("Failed to eval ~ts: ~p", [Path, Why]),
Err
end;
{error, Why} = Err ->
?ERROR_MSG("Failed to read file ~ts: ~ts",
[Path, file:format_error(Why)]),
Err
end.
maybe_get_scram_auth(Data) ->
case proplists:get_value(<<"iteration_count">>, Data, no_ic) of
IC when is_number(IC) ->
#scram{
storedkey = misc:hex_to_base64(proplists:get_value(<<"stored_key">>, Data, <<"">>)),
serverkey = misc:hex_to_base64(proplists:get_value(<<"server_key">>, Data, <<"">>)),
salt = base64:encode(proplists:get_value(<<"salt">>, Data, <<"">>)),
iterationcount = round(IC)
};
_ -> <<"">>
end.
convert_data(Host, "accounts", User, [Data]) ->
Password = case proplists:get_value(<<"password">>, Data, no_pass) of
no_pass ->
maybe_get_scram_auth(Data);
Pass when is_binary(Pass) ->
Pass
end,
case ejabberd_auth:try_register(User, Host, Password) of
ok ->
ok;
Err ->
?ERROR_MSG("Failed to register user ~ts@~ts: ~p",
[User, Host, Err]),
Err
end;
convert_data(Host, "roster", User, [Data]) ->
LUser = jid:nodeprep(User),
LServer = jid:nameprep(Host),
Rosters =
lists:flatmap(
fun({<<"pending">>, L}) ->
convert_pending_item(LUser, LServer, L);
({S, L}) when is_binary(S) ->
convert_roster_item(LUser, LServer, S, L);
(_) ->
[]
end, Data),
lists:foreach(fun mod_roster:set_roster/1, Rosters);
convert_data(Host, "private", User, [Data]) ->
PrivData = lists:flatmap(
fun({_TagXMLNS, Raw}) ->
case deserialize(Raw) of
[El] ->
XMLNS = fxml:get_tag_attr_s(<<"xmlns">>, El),
[{XMLNS, El}];
_ ->
[]
end
end, Data),
mod_private:set_data(jid:make(User, Host), PrivData);
convert_data(Host, "vcard", User, [Data]) ->
LServer = jid:nameprep(Host),
case deserialize(Data) of
[VCard] ->
mod_vcard:set_vcard(User, LServer, VCard);
_ ->
ok
end;
convert_data(_Host, "config", _User, [Data]) ->
RoomJID1 = case proplists:get_value(<<"jid">>, Data, not_found) of
not_found -> proplists:get_value(<<"_jid">>, Data, room_jid_not_found);
A when is_binary(A) -> A
end,
RoomJID = jid:decode(RoomJID1),
Config = proplists:get_value(<<"_data">>, Data, []),
RoomCfg = convert_room_config(Data),
case proplists:get_bool(<<"persistent">>, Config) of
true when RoomJID /= error ->
mod_muc:store_room(find_serverhost(RoomJID#jid.lserver), RoomJID#jid.lserver,
RoomJID#jid.luser, RoomCfg);
_ ->
ok
end;
convert_data(Host, "offline", User, [Data]) ->
LUser = jid:nodeprep(User),
LServer = jid:nameprep(Host),
lists:foreach(
fun({_, RawXML}) ->
case deserialize(RawXML) of
[El] ->
case el_to_offline_msg(LUser, LServer, El) of
[Msg] -> ok = mod_offline:store_offline_msg(Msg);
[] -> ok
end;
_ ->
ok
end
end, Data);
convert_data(Host, "privacy", User, [Data]) ->
LUser = jid:nodeprep(User),
LServer = jid:nameprep(Host),
Lists = proplists:get_value(<<"lists">>, Data, []),
Priv = #privacy{
us = {LUser, LServer},
default = proplists:get_value(<<"default">>, Data, none),
lists = lists:flatmap(
fun({Name, Vals}) ->
Items = proplists:get_value(<<"items">>, Vals, []),
case lists:map(fun convert_privacy_item/1,
Items) of
[] -> [];
ListItems -> [{Name, ListItems}]
end
end, Lists)},
mod_privacy:set_list(Priv);
convert_data(HostStr, "pubsub", Node, [Data]) ->
case decode_pubsub_host(HostStr) of
Host when is_binary(Host);
is_tuple(Host) ->
Type = node_type(Host),
NodeData = convert_node_config(HostStr, Data),
DefaultConfig = mod_pubsub:config(Host, default_node_config, []),
Owner = proplists:get_value(owner, NodeData),
Options = lists:foldl(
fun({_Opt, undefined}, Acc) ->
Acc;
({Opt, Val}, Acc) ->
lists:keystore(Opt, 1, Acc, {Opt, Val})
end, DefaultConfig, proplists:get_value(options, NodeData)),
case mod_pubsub:tree_action(Host, create_node, [Host, Node, Type, Owner, Options, []]) of
{ok, Nidx} ->
case mod_pubsub:node_action(Host, Type, create_node, [Nidx, Owner]) of
{result, _} ->
Access = open, % always allow subscriptions proplists:get_value(access_model, Options),
Publish = open, % always allow publications proplists:get_value(publish_model, Options),
MaxItems = proplists:get_value(max_items, Options),
Affiliations = proplists:get_value(affiliations, NodeData),
Subscriptions = proplists:get_value(subscriptions, NodeData),
Items = proplists:get_value(items, NodeData),
[mod_pubsub:node_action(Host, Type, set_affiliation,
[Nidx, Entity, Aff])
|| {Entity, Aff} <- Affiliations, Entity =/= Owner],
[mod_pubsub:node_action(Host, Type, subscribe_node,
[Nidx, jid:make(Entity), Entity, Access, never, [], [], []])
|| Entity <- Subscriptions],
[mod_pubsub:node_action(Host, Type, publish_item,
[Nidx, Publisher, Publish, MaxItems, ItemId, Payload, []])
|| {ItemId, Publisher, Payload} <- Items];
Error ->
Error
end;
Error ->
?ERROR_MSG("Failed to import pubsub node ~ts on ~p:~n~p",
[Node, Host, NodeData]),
Error
end;
Error ->
?ERROR_MSG("Failed to import pubsub node: ~p", [Error]),
Error
end;
convert_data(_Host, _Type, _User, _Data) ->
ok.
convert_pending_item(LUser, LServer, LuaList) ->
lists:flatmap(
fun({S, true}) ->
try jid:decode(S) of
J ->
LJID = jid:tolower(J),
[#roster{usj = {LUser, LServer, LJID},
us = {LUser, LServer},
jid = LJID,
ask = in}]
catch _:{bad_jid, _} ->
[]
end;
(_) ->
[]
end, LuaList).
convert_roster_item(LUser, LServer, JIDstring, LuaList) ->
try jid:decode(JIDstring) of
JID ->
LJID = jid:tolower(JID),
InitR = #roster{usj = {LUser, LServer, LJID},
us = {LUser, LServer},
jid = LJID},
lists:foldl(
fun({<<"groups">>, Val}, [R]) ->
Gs = lists:flatmap(
fun({G, true}) -> [G];
(_) -> []
end, Val),
[R#roster{groups = Gs}];
({<<"subscription">>, Sub}, [R]) ->
[R#roster{subscription = misc:binary_to_atom(Sub)}];
({<<"ask">>, <<"subscribe">>}, [R]) ->
[R#roster{ask = out}];
({<<"name">>, Name}, [R]) ->
[R#roster{name = Name}];
({<<"persist">>, false}, _) ->
[];
(_, []) ->
[]
end, [InitR], LuaList)
catch _:{bad_jid, _} ->
[]
end.
convert_room_affiliations(Data) ->
lists:flatmap(
fun({J, Aff}) ->
try jid:decode(J) of
#jid{luser = U, lserver = S} ->
[{{U, S, <<>>}, misc:binary_to_atom(Aff)}]
catch _:{bad_jid, _} ->
[]
end
end, proplists:get_value(<<"_affiliations">>, Data, [])).
convert_room_config(Data) ->
Config = proplists:get_value(<<"_data">>, Data, []),
Pass = case proplists:get_value(<<"password">>, Config, <<"">>) of
<<"">> ->
[];
Password ->
[{password_protected, true},
{password, Password}]
end,
Subj = try jid:decode(
proplists:get_value(
<<"subject_from">>, Config, <<"">>)) of
#jid{lresource = Nick} when Nick /= <<"">> ->
[{subject, proplists:get_value(<<"subject">>, Config, <<"">>)},
{subject_author, Nick}]
catch _:{bad_jid, _} ->
[]
end,
Anonymous = case proplists:get_value(<<"whois">>, Config, <<"moderators">>) of
<<"moderators">> -> true;
_ -> false
end,
[{affiliations, convert_room_affiliations(Data)},
{allow_change_subj, proplists:get_bool(<<"changesubject">>, Config)},
{mam, proplists:get_bool(<<"archiving">>, Config)},
{description, proplists:get_value(<<"description">>, Config, <<"">>)},
{members_only, proplists:get_bool(<<"members_only">>, Config)},
{moderated, proplists:get_bool(<<"moderated">>, Config)},
{persistent, proplists:get_bool(<<"persistent">>, Config)},
{anonymous, Anonymous}] ++ Pass ++ Subj.
convert_privacy_item({_, Item}) ->
Action = proplists:get_value(<<"action">>, Item, <<"allow">>),
Order = proplists:get_value(<<"order">>, Item, 0),
T = misc:binary_to_atom(proplists:get_value(<<"type">>, Item, <<"none">>)),
V = proplists:get_value(<<"value">>, Item, <<"">>),
MatchIQ = proplists:get_bool(<<"iq">>, Item),
MatchMsg = proplists:get_bool(<<"message">>, Item),
MatchPresIn = proplists:get_bool(<<"presence-in">>, Item),
MatchPresOut = proplists:get_bool(<<"presence-out">>, Item),
MatchAll = if (MatchIQ == false) and (MatchMsg == false) and
(MatchPresIn == false) and (MatchPresOut == false) ->
true;
true ->
false
end,
{Type, Value} = try case T of
none -> {T, none};
group -> {T, V};
jid -> {T, jid:tolower(jid:decode(V))};
subscription -> {T, misc:binary_to_atom(V)}
end
catch _:_ ->
{none, none}
end,
#listitem{type = Type,
value = Value,
action = misc:binary_to_atom(Action),
order = erlang:trunc(Order),
match_all = MatchAll,
match_iq = MatchIQ,
match_message = MatchMsg,
match_presence_in = MatchPresIn,
match_presence_out = MatchPresOut}.
url_decode(Encoded) ->
url_decode(Encoded, <<>>).
, Hi , , Tail / binary > > , Acc ) - >
Hex = list_to_integer([Hi, Lo], 16),
url_decode(Tail, <<Acc/binary, Hex>>);
url_decode(<<H, Tail/binary>>, Acc) ->
url_decode(Tail, <<Acc/binary, H>>);
url_decode(<<>>, Acc) ->
Acc.
decode_pubsub_host(Host) ->
try jid:decode(Host) of
#jid{luser = <<>>, lserver = LServer} -> LServer;
#jid{luser = LUser, lserver = LServer} -> {LUser, LServer, <<>>}
catch _:{bad_jid, _} -> bad_jid
end.
node_type({_U, _S, _R}) -> <<"pep">>;
node_type(Host) -> hd(mod_pubsub:plugins(Host)).
max_items(Config, Default) ->
case round(proplists:get_value(<<"max_items">>, Config, Default)) of
I when I =< 0 -> Default;
I -> I
end.
convert_node_affiliations(Data) ->
lists:flatmap(
fun({J, Aff}) ->
try jid:decode(J) of
JID ->
[{JID, misc:binary_to_atom(Aff)}]
catch _:{bad_jid, _} ->
[]
end
end, proplists:get_value(<<"affiliations">>, Data, [])).
convert_node_subscriptions(Data) ->
lists:flatmap(
fun({J, true}) ->
try jid:decode(J) of
JID ->
[jid:tolower(JID)]
catch _:{bad_jid, _} ->
[]
end;
(_) ->
[]
end, proplists:get_value(<<"subscribers">>, Data, [])).
convert_node_items(Host, Data) ->
Authors = proplists:get_value(<<"data_author">>, Data, []),
lists:flatmap(
fun({ItemId, Item}) ->
try jid:decode(proplists:get_value(ItemId, Authors, Host)) of
JID ->
[El] = deserialize(Item),
[{ItemId, JID, El#xmlel.children}]
catch _:{bad_jid, _} ->
[]
end
end, proplists:get_value(<<"data">>, Data, [])).
convert_node_config(Host, Data) ->
Config = proplists:get_value(<<"config">>, Data, []),
[{affiliations, convert_node_affiliations(Data)},
{subscriptions, convert_node_subscriptions(Data)},
{owner, jid:decode(proplists:get_value(<<"creator">>, Config, Host))},
{items, convert_node_items(Host, Data)},
{options, [
{deliver_notifications,
proplists:get_value(<<"deliver_notifications">>, Config, true)},
{deliver_payloads,
proplists:get_value(<<"deliver_payloads">>, Config, true)},
{persist_items,
proplists:get_value(<<"persist_items">>, Config, true)},
{max_items,
max_items(Config, 10)},
{access_model,
misc:binary_to_atom(proplists:get_value(<<"access_model">>, Config, <<"open">>))},
{publish_model,
misc:binary_to_atom(proplists:get_value(<<"publish_model">>, Config, <<"publishers">>))},
{title,
proplists:get_value(<<"title">>, Config, <<"">>)}
]}
].
el_to_offline_msg(LUser, LServer, #xmlel{attrs = Attrs} = El) ->
try
TS = xmpp_util:decode_timestamp(
fxml:get_attr_s(<<"stamp">>, Attrs)),
Attrs1 = lists:filter(
fun({<<"stamp">>, _}) -> false;
({<<"stamp_legacy">>, _}) -> false;
(_) -> true
end, Attrs),
El1 = El#xmlel{attrs = Attrs1},
case xmpp:decode(El1, ?NS_CLIENT, [ignore_els]) of
#message{from = #jid{} = From, to = #jid{} = To} = Packet ->
[#offline_msg{
us = {LUser, LServer},
timestamp = TS,
expire = never,
from = From,
to = To,
packet = Packet}];
_ ->
[]
end
catch _:{bad_timestamp, _} ->
[];
_:{bad_jid, _} ->
[];
_:{xmpp_codec, _} ->
[]
end.
find_serverhost(Host) ->
[ServerHost] =
lists:filter(
fun(ServerHost) ->
case gen_mod:is_loaded(ServerHost, mod_muc) of
true ->
lists:member(Host, gen_mod:get_module_opt_hosts(ServerHost, mod_muc));
false ->
false
end
end, ejabberd_option:hosts()),
ServerHost.
deserialize(L) ->
deserialize(L, #xmlel{}, []).
deserialize([{Other, _}|T], El, Acc)
when (Other == <<"key">>)
or (Other == <<"when">>)
or (Other == <<"with">>) ->
deserialize(T, El, Acc);
deserialize([{<<"attr">>, Attrs}|T], El, Acc) ->
deserialize(T, El#xmlel{attrs = Attrs ++ El#xmlel.attrs}, Acc);
deserialize([{<<"name">>, Name}|T], El, Acc) ->
deserialize(T, El#xmlel{name = Name}, Acc);
deserialize([{_, S}|T], #xmlel{children = Els} = El, Acc) when is_binary(S) ->
deserialize(T, El#xmlel{children = [{xmlcdata, S}|Els]}, Acc);
deserialize([{_, L}|T], #xmlel{children = Els} = El, Acc) when is_list(L) ->
deserialize(T, El#xmlel{children = deserialize(L) ++ Els}, Acc);
deserialize([], #xmlel{children = Els} = El, Acc) ->
[El#xmlel{children = lists:reverse(Els)}|Acc].
| null | https://raw.githubusercontent.com/processone/ejabberd/c103182bc7e5b8a8ab123ce02d1959a54e939480/src/prosody2ejabberd.erl | erlang | -------------------------------------------------------------------
File : prosody2ejabberd.erl
This program is free software; you can redistribute it and/or
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
----------------------------------------------------------------------
API
===================================================================
API
===================================================================
===================================================================
===================================================================
always allow subscriptions proplists:get_value(access_model, Options),
always allow publications proplists:get_value(publish_model, Options), | Author : < >
Created : 20 Jan 2016 by < >
ejabberd , Copyright ( C ) 2002 - 2023 ProcessOne
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation ; either version 2 of the
You should have received a copy of the GNU General Public License along
with this program ; if not , write to the Free Software Foundation , Inc. ,
51 Franklin Street , Fifth Floor , Boston , USA .
-module(prosody2ejabberd).
-export([from_dir/1]).
-include_lib("xmpp/include/scram.hrl").
-include_lib("xmpp/include/xmpp.hrl").
-include("logger.hrl").
-include("mod_roster.hrl").
-include("mod_offline.hrl").
-include("mod_privacy.hrl").
from_dir(ProsodyDir) ->
case code:ensure_loaded(luerl) of
{module, _} ->
case file:list_dir(ProsodyDir) of
{ok, HostDirs} ->
lists:foreach(
fun(HostDir) ->
Host = list_to_binary(HostDir),
lists:foreach(
fun(SubDir) ->
Path = filename:join(
[ProsodyDir, HostDir, SubDir]),
convert_dir(Path, Host, SubDir)
end, ["vcard", "accounts", "roster",
"private", "config", "offline",
"privacy", "pep", "pubsub"])
end, HostDirs);
{error, Why} = Err ->
?ERROR_MSG("Failed to list ~ts: ~ts",
[ProsodyDir, file:format_error(Why)]),
Err
end;
{error, _} = Err ->
?ERROR_MSG("The file 'luerl.beam' is not found: maybe "
"ejabberd is not compiled with Lua support", []),
Err
end.
Internal functions
convert_dir(Path, Host, Type) ->
case file:list_dir(Path) of
{ok, Files} ->
lists:foreach(
fun(File) ->
FilePath = filename:join(Path, File),
case Type of
"pep" ->
case filelib:is_dir(FilePath) of
true ->
JID = list_to_binary(File ++ "@" ++ Host),
convert_dir(FilePath, JID, "pubsub");
false ->
ok
end;
_ ->
case eval_file(FilePath) of
{ok, Data} ->
Name = iolist_to_binary(filename:rootname(File)),
convert_data(url_decode(Host), Type,
url_decode(Name), Data);
Err ->
Err
end
end
end, Files);
{error, enoent} ->
ok;
{error, Why} = Err ->
?ERROR_MSG("Failed to list ~ts: ~ts",
[Path, file:format_error(Why)]),
Err
end.
eval_file(Path) ->
case file:read_file(Path) of
{ok, Data} ->
State0 = luerl:init(),
State1 = luerl:set_table([item],
fun([X], State) -> {[X], State} end,
State0),
NewData = case filename:extension(Path) of
".list" ->
<<"return {", Data/binary, "};">>;
_ ->
Data
end,
case luerl:eval(NewData, State1) of
{ok, _} = Res ->
Res;
{error, Why, _} = Err ->
?ERROR_MSG("Failed to eval ~ts: ~p", [Path, Why]),
Err
end;
{error, Why} = Err ->
?ERROR_MSG("Failed to read file ~ts: ~ts",
[Path, file:format_error(Why)]),
Err
end.
maybe_get_scram_auth(Data) ->
case proplists:get_value(<<"iteration_count">>, Data, no_ic) of
IC when is_number(IC) ->
#scram{
storedkey = misc:hex_to_base64(proplists:get_value(<<"stored_key">>, Data, <<"">>)),
serverkey = misc:hex_to_base64(proplists:get_value(<<"server_key">>, Data, <<"">>)),
salt = base64:encode(proplists:get_value(<<"salt">>, Data, <<"">>)),
iterationcount = round(IC)
};
_ -> <<"">>
end.
convert_data(Host, "accounts", User, [Data]) ->
Password = case proplists:get_value(<<"password">>, Data, no_pass) of
no_pass ->
maybe_get_scram_auth(Data);
Pass when is_binary(Pass) ->
Pass
end,
case ejabberd_auth:try_register(User, Host, Password) of
ok ->
ok;
Err ->
?ERROR_MSG("Failed to register user ~ts@~ts: ~p",
[User, Host, Err]),
Err
end;
convert_data(Host, "roster", User, [Data]) ->
LUser = jid:nodeprep(User),
LServer = jid:nameprep(Host),
Rosters =
lists:flatmap(
fun({<<"pending">>, L}) ->
convert_pending_item(LUser, LServer, L);
({S, L}) when is_binary(S) ->
convert_roster_item(LUser, LServer, S, L);
(_) ->
[]
end, Data),
lists:foreach(fun mod_roster:set_roster/1, Rosters);
convert_data(Host, "private", User, [Data]) ->
PrivData = lists:flatmap(
fun({_TagXMLNS, Raw}) ->
case deserialize(Raw) of
[El] ->
XMLNS = fxml:get_tag_attr_s(<<"xmlns">>, El),
[{XMLNS, El}];
_ ->
[]
end
end, Data),
mod_private:set_data(jid:make(User, Host), PrivData);
convert_data(Host, "vcard", User, [Data]) ->
LServer = jid:nameprep(Host),
case deserialize(Data) of
[VCard] ->
mod_vcard:set_vcard(User, LServer, VCard);
_ ->
ok
end;
convert_data(_Host, "config", _User, [Data]) ->
RoomJID1 = case proplists:get_value(<<"jid">>, Data, not_found) of
not_found -> proplists:get_value(<<"_jid">>, Data, room_jid_not_found);
A when is_binary(A) -> A
end,
RoomJID = jid:decode(RoomJID1),
Config = proplists:get_value(<<"_data">>, Data, []),
RoomCfg = convert_room_config(Data),
case proplists:get_bool(<<"persistent">>, Config) of
true when RoomJID /= error ->
mod_muc:store_room(find_serverhost(RoomJID#jid.lserver), RoomJID#jid.lserver,
RoomJID#jid.luser, RoomCfg);
_ ->
ok
end;
convert_data(Host, "offline", User, [Data]) ->
LUser = jid:nodeprep(User),
LServer = jid:nameprep(Host),
lists:foreach(
fun({_, RawXML}) ->
case deserialize(RawXML) of
[El] ->
case el_to_offline_msg(LUser, LServer, El) of
[Msg] -> ok = mod_offline:store_offline_msg(Msg);
[] -> ok
end;
_ ->
ok
end
end, Data);
convert_data(Host, "privacy", User, [Data]) ->
LUser = jid:nodeprep(User),
LServer = jid:nameprep(Host),
Lists = proplists:get_value(<<"lists">>, Data, []),
Priv = #privacy{
us = {LUser, LServer},
default = proplists:get_value(<<"default">>, Data, none),
lists = lists:flatmap(
fun({Name, Vals}) ->
Items = proplists:get_value(<<"items">>, Vals, []),
case lists:map(fun convert_privacy_item/1,
Items) of
[] -> [];
ListItems -> [{Name, ListItems}]
end
end, Lists)},
mod_privacy:set_list(Priv);
convert_data(HostStr, "pubsub", Node, [Data]) ->
case decode_pubsub_host(HostStr) of
Host when is_binary(Host);
is_tuple(Host) ->
Type = node_type(Host),
NodeData = convert_node_config(HostStr, Data),
DefaultConfig = mod_pubsub:config(Host, default_node_config, []),
Owner = proplists:get_value(owner, NodeData),
Options = lists:foldl(
fun({_Opt, undefined}, Acc) ->
Acc;
({Opt, Val}, Acc) ->
lists:keystore(Opt, 1, Acc, {Opt, Val})
end, DefaultConfig, proplists:get_value(options, NodeData)),
case mod_pubsub:tree_action(Host, create_node, [Host, Node, Type, Owner, Options, []]) of
{ok, Nidx} ->
case mod_pubsub:node_action(Host, Type, create_node, [Nidx, Owner]) of
{result, _} ->
MaxItems = proplists:get_value(max_items, Options),
Affiliations = proplists:get_value(affiliations, NodeData),
Subscriptions = proplists:get_value(subscriptions, NodeData),
Items = proplists:get_value(items, NodeData),
[mod_pubsub:node_action(Host, Type, set_affiliation,
[Nidx, Entity, Aff])
|| {Entity, Aff} <- Affiliations, Entity =/= Owner],
[mod_pubsub:node_action(Host, Type, subscribe_node,
[Nidx, jid:make(Entity), Entity, Access, never, [], [], []])
|| Entity <- Subscriptions],
[mod_pubsub:node_action(Host, Type, publish_item,
[Nidx, Publisher, Publish, MaxItems, ItemId, Payload, []])
|| {ItemId, Publisher, Payload} <- Items];
Error ->
Error
end;
Error ->
?ERROR_MSG("Failed to import pubsub node ~ts on ~p:~n~p",
[Node, Host, NodeData]),
Error
end;
Error ->
?ERROR_MSG("Failed to import pubsub node: ~p", [Error]),
Error
end;
convert_data(_Host, _Type, _User, _Data) ->
ok.
convert_pending_item(LUser, LServer, LuaList) ->
lists:flatmap(
fun({S, true}) ->
try jid:decode(S) of
J ->
LJID = jid:tolower(J),
[#roster{usj = {LUser, LServer, LJID},
us = {LUser, LServer},
jid = LJID,
ask = in}]
catch _:{bad_jid, _} ->
[]
end;
(_) ->
[]
end, LuaList).
convert_roster_item(LUser, LServer, JIDstring, LuaList) ->
try jid:decode(JIDstring) of
JID ->
LJID = jid:tolower(JID),
InitR = #roster{usj = {LUser, LServer, LJID},
us = {LUser, LServer},
jid = LJID},
lists:foldl(
fun({<<"groups">>, Val}, [R]) ->
Gs = lists:flatmap(
fun({G, true}) -> [G];
(_) -> []
end, Val),
[R#roster{groups = Gs}];
({<<"subscription">>, Sub}, [R]) ->
[R#roster{subscription = misc:binary_to_atom(Sub)}];
({<<"ask">>, <<"subscribe">>}, [R]) ->
[R#roster{ask = out}];
({<<"name">>, Name}, [R]) ->
[R#roster{name = Name}];
({<<"persist">>, false}, _) ->
[];
(_, []) ->
[]
end, [InitR], LuaList)
catch _:{bad_jid, _} ->
[]
end.
convert_room_affiliations(Data) ->
lists:flatmap(
fun({J, Aff}) ->
try jid:decode(J) of
#jid{luser = U, lserver = S} ->
[{{U, S, <<>>}, misc:binary_to_atom(Aff)}]
catch _:{bad_jid, _} ->
[]
end
end, proplists:get_value(<<"_affiliations">>, Data, [])).
convert_room_config(Data) ->
Config = proplists:get_value(<<"_data">>, Data, []),
Pass = case proplists:get_value(<<"password">>, Config, <<"">>) of
<<"">> ->
[];
Password ->
[{password_protected, true},
{password, Password}]
end,
Subj = try jid:decode(
proplists:get_value(
<<"subject_from">>, Config, <<"">>)) of
#jid{lresource = Nick} when Nick /= <<"">> ->
[{subject, proplists:get_value(<<"subject">>, Config, <<"">>)},
{subject_author, Nick}]
catch _:{bad_jid, _} ->
[]
end,
Anonymous = case proplists:get_value(<<"whois">>, Config, <<"moderators">>) of
<<"moderators">> -> true;
_ -> false
end,
[{affiliations, convert_room_affiliations(Data)},
{allow_change_subj, proplists:get_bool(<<"changesubject">>, Config)},
{mam, proplists:get_bool(<<"archiving">>, Config)},
{description, proplists:get_value(<<"description">>, Config, <<"">>)},
{members_only, proplists:get_bool(<<"members_only">>, Config)},
{moderated, proplists:get_bool(<<"moderated">>, Config)},
{persistent, proplists:get_bool(<<"persistent">>, Config)},
{anonymous, Anonymous}] ++ Pass ++ Subj.
convert_privacy_item({_, Item}) ->
Action = proplists:get_value(<<"action">>, Item, <<"allow">>),
Order = proplists:get_value(<<"order">>, Item, 0),
T = misc:binary_to_atom(proplists:get_value(<<"type">>, Item, <<"none">>)),
V = proplists:get_value(<<"value">>, Item, <<"">>),
MatchIQ = proplists:get_bool(<<"iq">>, Item),
MatchMsg = proplists:get_bool(<<"message">>, Item),
MatchPresIn = proplists:get_bool(<<"presence-in">>, Item),
MatchPresOut = proplists:get_bool(<<"presence-out">>, Item),
MatchAll = if (MatchIQ == false) and (MatchMsg == false) and
(MatchPresIn == false) and (MatchPresOut == false) ->
true;
true ->
false
end,
{Type, Value} = try case T of
none -> {T, none};
group -> {T, V};
jid -> {T, jid:tolower(jid:decode(V))};
subscription -> {T, misc:binary_to_atom(V)}
end
catch _:_ ->
{none, none}
end,
#listitem{type = Type,
value = Value,
action = misc:binary_to_atom(Action),
order = erlang:trunc(Order),
match_all = MatchAll,
match_iq = MatchIQ,
match_message = MatchMsg,
match_presence_in = MatchPresIn,
match_presence_out = MatchPresOut}.
url_decode(Encoded) ->
url_decode(Encoded, <<>>).
, Hi , , Tail / binary > > , Acc ) - >
Hex = list_to_integer([Hi, Lo], 16),
url_decode(Tail, <<Acc/binary, Hex>>);
url_decode(<<H, Tail/binary>>, Acc) ->
url_decode(Tail, <<Acc/binary, H>>);
url_decode(<<>>, Acc) ->
Acc.
decode_pubsub_host(Host) ->
try jid:decode(Host) of
#jid{luser = <<>>, lserver = LServer} -> LServer;
#jid{luser = LUser, lserver = LServer} -> {LUser, LServer, <<>>}
catch _:{bad_jid, _} -> bad_jid
end.
node_type({_U, _S, _R}) -> <<"pep">>;
node_type(Host) -> hd(mod_pubsub:plugins(Host)).
max_items(Config, Default) ->
case round(proplists:get_value(<<"max_items">>, Config, Default)) of
I when I =< 0 -> Default;
I -> I
end.
convert_node_affiliations(Data) ->
lists:flatmap(
fun({J, Aff}) ->
try jid:decode(J) of
JID ->
[{JID, misc:binary_to_atom(Aff)}]
catch _:{bad_jid, _} ->
[]
end
end, proplists:get_value(<<"affiliations">>, Data, [])).
convert_node_subscriptions(Data) ->
lists:flatmap(
fun({J, true}) ->
try jid:decode(J) of
JID ->
[jid:tolower(JID)]
catch _:{bad_jid, _} ->
[]
end;
(_) ->
[]
end, proplists:get_value(<<"subscribers">>, Data, [])).
convert_node_items(Host, Data) ->
Authors = proplists:get_value(<<"data_author">>, Data, []),
lists:flatmap(
fun({ItemId, Item}) ->
try jid:decode(proplists:get_value(ItemId, Authors, Host)) of
JID ->
[El] = deserialize(Item),
[{ItemId, JID, El#xmlel.children}]
catch _:{bad_jid, _} ->
[]
end
end, proplists:get_value(<<"data">>, Data, [])).
convert_node_config(Host, Data) ->
Config = proplists:get_value(<<"config">>, Data, []),
[{affiliations, convert_node_affiliations(Data)},
{subscriptions, convert_node_subscriptions(Data)},
{owner, jid:decode(proplists:get_value(<<"creator">>, Config, Host))},
{items, convert_node_items(Host, Data)},
{options, [
{deliver_notifications,
proplists:get_value(<<"deliver_notifications">>, Config, true)},
{deliver_payloads,
proplists:get_value(<<"deliver_payloads">>, Config, true)},
{persist_items,
proplists:get_value(<<"persist_items">>, Config, true)},
{max_items,
max_items(Config, 10)},
{access_model,
misc:binary_to_atom(proplists:get_value(<<"access_model">>, Config, <<"open">>))},
{publish_model,
misc:binary_to_atom(proplists:get_value(<<"publish_model">>, Config, <<"publishers">>))},
{title,
proplists:get_value(<<"title">>, Config, <<"">>)}
]}
].
el_to_offline_msg(LUser, LServer, #xmlel{attrs = Attrs} = El) ->
try
TS = xmpp_util:decode_timestamp(
fxml:get_attr_s(<<"stamp">>, Attrs)),
Attrs1 = lists:filter(
fun({<<"stamp">>, _}) -> false;
({<<"stamp_legacy">>, _}) -> false;
(_) -> true
end, Attrs),
El1 = El#xmlel{attrs = Attrs1},
case xmpp:decode(El1, ?NS_CLIENT, [ignore_els]) of
#message{from = #jid{} = From, to = #jid{} = To} = Packet ->
[#offline_msg{
us = {LUser, LServer},
timestamp = TS,
expire = never,
from = From,
to = To,
packet = Packet}];
_ ->
[]
end
catch _:{bad_timestamp, _} ->
[];
_:{bad_jid, _} ->
[];
_:{xmpp_codec, _} ->
[]
end.
find_serverhost(Host) ->
[ServerHost] =
lists:filter(
fun(ServerHost) ->
case gen_mod:is_loaded(ServerHost, mod_muc) of
true ->
lists:member(Host, gen_mod:get_module_opt_hosts(ServerHost, mod_muc));
false ->
false
end
end, ejabberd_option:hosts()),
ServerHost.
deserialize(L) ->
deserialize(L, #xmlel{}, []).
deserialize([{Other, _}|T], El, Acc)
when (Other == <<"key">>)
or (Other == <<"when">>)
or (Other == <<"with">>) ->
deserialize(T, El, Acc);
deserialize([{<<"attr">>, Attrs}|T], El, Acc) ->
deserialize(T, El#xmlel{attrs = Attrs ++ El#xmlel.attrs}, Acc);
deserialize([{<<"name">>, Name}|T], El, Acc) ->
deserialize(T, El#xmlel{name = Name}, Acc);
deserialize([{_, S}|T], #xmlel{children = Els} = El, Acc) when is_binary(S) ->
deserialize(T, El#xmlel{children = [{xmlcdata, S}|Els]}, Acc);
deserialize([{_, L}|T], #xmlel{children = Els} = El, Acc) when is_list(L) ->
deserialize(T, El#xmlel{children = deserialize(L) ++ Els}, Acc);
deserialize([], #xmlel{children = Els} = El, Acc) ->
[El#xmlel{children = lists:reverse(Els)}|Acc].
|
4fd9a72ed064e02801abf364c10ff93d4916325719cb9bbdb7f745480f09bc5b | defndaines/meiro | nethack.clj | (ns meiro.nethack
"Generate a NetHack-style ASCII representation of a maze."
(:require [clojure.string :as string]))
(def ^:private horizontal-wall "-")
(def ^:private verticle-wall "|")
(def ^:private inside-cell ".")
(def ^:private cell-link ".")
; (def ^:private start-cell "@"
; (def ^:private end-cell "$")
(def ^:private corridor "#")
(def ^:private corridor-wall " ")
(defn- top-level
"Render the top edge of the maze."
[maze]
(string/join
(repeat
(inc (* 2 (count (first maze))))
horizontal-wall)))
(defn- cell-room-level
"Render the cell level, i.e., where the 'inside' of the cell is displayed."
([cell] (cell-room-level cell inside-cell))
([cell inside]
(concat inside
(if (some #{:east} cell) cell-link verticle-wall))))
(defn- bottom-room-level
"Render the bottom edge of a cell, or precisely the south and south-east
edge."
[cell]
(concat
(if (some #{:south} cell) cell-link horizontal-wall)
(if (some #{:south} cell)
(if (not-any? #{:east} cell) verticle-wall horizontal-wall)
horizontal-wall)))
(defn render-room
"Render a maze in NetHack style as if it was the interior of a room."
([maze]
(apply str
(top-level maze) \newline
(mapcat
(fn [row]
(concat verticle-wall (mapcat cell-room-level row) "\n"
verticle-wall (mapcat bottom-room-level row) "\n"))
maze))))
(defn cell-corridor-level
"Render the cell level, i.e., where the 'inside of the cell is displayed."
[cell]
(concat corridor
(if (some #{:east} cell) corridor corridor-wall)))
(defn bottom-corridor-level
"Render the bottom edge of a cell, or precisely the south and south-east
edge."
[cell]
(concat
(if (some #{:south} cell) corridor corridor-wall)
corridor-wall))
(defn render-corridor
"Render a maze in NetHack style as if it was a series of corridors."
[maze]
(clojure.string/join
(mapcat
(fn [row]
(concat (mapcat cell-corridor-level row) "\n"
(mapcat bottom-corridor-level row) "\n"))
maze)))
| null | https://raw.githubusercontent.com/defndaines/meiro/f91d4dee2842c056a162c861baf8b71bb4fb140c/src/meiro/nethack.clj | clojure | (def ^:private start-cell "@"
(def ^:private end-cell "$") | (ns meiro.nethack
"Generate a NetHack-style ASCII representation of a maze."
(:require [clojure.string :as string]))
(def ^:private horizontal-wall "-")
(def ^:private verticle-wall "|")
(def ^:private inside-cell ".")
(def ^:private cell-link ".")
(def ^:private corridor "#")
(def ^:private corridor-wall " ")
(defn- top-level
"Render the top edge of the maze."
[maze]
(string/join
(repeat
(inc (* 2 (count (first maze))))
horizontal-wall)))
(defn- cell-room-level
"Render the cell level, i.e., where the 'inside' of the cell is displayed."
([cell] (cell-room-level cell inside-cell))
([cell inside]
(concat inside
(if (some #{:east} cell) cell-link verticle-wall))))
(defn- bottom-room-level
"Render the bottom edge of a cell, or precisely the south and south-east
edge."
[cell]
(concat
(if (some #{:south} cell) cell-link horizontal-wall)
(if (some #{:south} cell)
(if (not-any? #{:east} cell) verticle-wall horizontal-wall)
horizontal-wall)))
(defn render-room
"Render a maze in NetHack style as if it was the interior of a room."
([maze]
(apply str
(top-level maze) \newline
(mapcat
(fn [row]
(concat verticle-wall (mapcat cell-room-level row) "\n"
verticle-wall (mapcat bottom-room-level row) "\n"))
maze))))
(defn cell-corridor-level
"Render the cell level, i.e., where the 'inside of the cell is displayed."
[cell]
(concat corridor
(if (some #{:east} cell) corridor corridor-wall)))
(defn bottom-corridor-level
"Render the bottom edge of a cell, or precisely the south and south-east
edge."
[cell]
(concat
(if (some #{:south} cell) corridor corridor-wall)
corridor-wall))
(defn render-corridor
"Render a maze in NetHack style as if it was a series of corridors."
[maze]
(clojure.string/join
(mapcat
(fn [row]
(concat (mapcat cell-corridor-level row) "\n"
(mapcat bottom-corridor-level row) "\n"))
maze)))
|
0987ec05c7b7890d37da4e6b0ab8f8c461e604d8c996aa172c648cc1f2ac354c | jorgenschaefer/prometheus | account.scm | ;;; This is a simple account-keeping object.
;;; It's just like a normal object
(define account (*the-root-object* 'clone))
;;; But it has a balance
(account 'add-value-slot! 'balance 'set-balance! 0)
;;; Which can be modified
(account 'add-method-slot! 'payment!
(lambda (self resend amount)
(self 'set-balance!
(+ (self 'balance)
amount))))
;;; Some tests:
(define a1 (account 'clone))
(define a2 (account 'clone))
(a1 'payment! 100)
(a2 'payment! 200)
(a1 'balance)
= > 100
(a2 'balance)
= > 200
(a1 'payment! -20)
(a1 'balance)
= > 80
;;; The typing for the slot definitions above can be rather tedious.
Prometheus provides syntactic sugar for those operations .
;;; A method can be added with the DEFINE-METHOD syntax. This code is
;;; equivalent to the code above which adds the PAYMENT! method:
(define-method (account 'payment! self resend amount)
(self 'set-balance!
(+ (self 'balance)
amount)))
;;; And this defines the whole object with the BALANCE slot and the
;;; PAYMENT! method just as above:
(define-object account (*the-root-object*)
(balance set-balance! 0)
((payment! self resend amount)
(self 'set-balance!
(+ (self 'balance)
amount))))
| null | https://raw.githubusercontent.com/jorgenschaefer/prometheus/d5e40cd2403a118ee48f5b37d5d65966d60bc4ac/examples/account.scm | scheme | This is a simple account-keeping object.
It's just like a normal object
But it has a balance
Which can be modified
Some tests:
The typing for the slot definitions above can be rather tedious.
A method can be added with the DEFINE-METHOD syntax. This code is
equivalent to the code above which adds the PAYMENT! method:
And this defines the whole object with the BALANCE slot and the
PAYMENT! method just as above: |
(define account (*the-root-object* 'clone))
(account 'add-value-slot! 'balance 'set-balance! 0)
(account 'add-method-slot! 'payment!
(lambda (self resend amount)
(self 'set-balance!
(+ (self 'balance)
amount))))
(define a1 (account 'clone))
(define a2 (account 'clone))
(a1 'payment! 100)
(a2 'payment! 200)
(a1 'balance)
= > 100
(a2 'balance)
= > 200
(a1 'payment! -20)
(a1 'balance)
= > 80
Prometheus provides syntactic sugar for those operations .
(define-method (account 'payment! self resend amount)
(self 'set-balance!
(+ (self 'balance)
amount)))
(define-object account (*the-root-object*)
(balance set-balance! 0)
((payment! self resend amount)
(self 'set-balance!
(+ (self 'balance)
amount))))
|
670d19f6103f64b88cb178833d946d4edd34a2ff64f53ea6781e5d5216415cd7 | zadean/xqerl | fn_codepoints_to_string_SUITE.erl | -module('fn_codepoints_to_string_SUITE').
-include_lib("common_test/include/ct.hrl").
-export([
all/0,
groups/0,
suite/0
]).
-export([
init_per_suite/1,
init_per_group/2,
end_per_group/2,
end_per_suite/1
]).
-export(['fn-codepoints-to-string1args-1'/1]).
-export(['fn-codepoints-to-string1args-2'/1]).
-export(['fn-codepoints-to-string1args-3'/1]).
-export(['fn-codepoints-to-string1args-4'/1]).
-export(['fn-codepoints-to-string-1'/1]).
-export(['fn-codepoints-to-string-2'/1]).
-export(['fn-codepoints-to-string-3'/1]).
-export(['fn-codepoints-to-string-4'/1]).
-export(['fn-codepoints-to-string-5'/1]).
-export(['fn-codepoints-to-string-6'/1]).
-export(['fn-codepoints-to-string-7'/1]).
-export(['fn-codepoints-to-string-8'/1]).
-export(['fn-codepoints-to-string-9'/1]).
-export(['fn-codepoints-to-string-10'/1]).
-export(['fn-codepoints-to-string-11'/1]).
-export(['fn-codepoints-to-string-12'/1]).
-export(['fn-codepoints-to-string-13'/1]).
-export(['fn-codepoints-to-string-14'/1]).
-export(['fn-codepoints-to-string-15'/1]).
-export(['fn-codepoints-to-string-16'/1]).
-export(['K-CodepointToStringFunc-1'/1]).
-export(['K-CodepointToStringFunc-2'/1]).
-export(['K-CodepointToStringFunc-3'/1]).
-export(['K-CodepointToStringFunc-4'/1]).
-export(['K-CodepointToStringFunc-5'/1]).
-export(['K-CodepointToStringFunc-6'/1]).
-export(['K-CodepointToStringFunc-7'/1]).
-export(['K-CodepointToStringFunc-8'/1]).
-export(['K-CodepointToStringFunc-8a'/1]).
-export(['K-CodepointToStringFunc-9'/1]).
-export(['K-CodepointToStringFunc-10'/1]).
-export(['K-CodepointToStringFunc-11'/1]).
-export(['K-CodepointToStringFunc-11b'/1]).
-export(['K-CodepointToStringFunc-12'/1]).
-export(['K-CodepointToStringFunc-12b'/1]).
-export(['K-CodepointToStringFunc-13'/1]).
-export(['K-CodepointToStringFunc-14'/1]).
-export(['K-CodepointToStringFunc-15'/1]).
-export(['K-CodepointToStringFunc-16'/1]).
-export(['K-CodepointToStringFunc-17'/1]).
-export(['K-CodepointToStringFunc-18'/1]).
-export(['K-CodepointToStringFunc-19'/1]).
-export(['K-CodepointToStringFunc-20'/1]).
-export(['K-CodepointToStringFunc-21'/1]).
-export(['K-CodepointToStringFunc-22'/1]).
-export(['K-CodepointToStringFunc-23'/1]).
-export(['K-CodepointToStringFunc-24'/1]).
-export(['K-CodepointToStringFunc-25'/1]).
-export(['K-CodepointToStringFunc-26'/1]).
-export(['K-CodepointToStringFunc-27'/1]).
-export(['K-CodepointToStringFunc-28'/1]).
-export(['K-CodepointToStringFunc-29'/1]).
-export(['cbcl-codepoints-to-string-001'/1]).
-export(['cbcl-codepoints-to-string-002'/1]).
-export(['cbcl-codepoints-to-string-003'/1]).
-export(['cbcl-codepoints-to-string-004'/1]).
-export(['cbcl-codepoints-to-string-005'/1]).
-export(['cbcl-codepoints-to-string-006'/1]).
-export(['cbcl-codepoints-to-string-007'/1]).
-export(['cbcl-codepoints-to-string-008'/1]).
-export(['cbcl-codepoints-to-string-009'/1]).
-export(['cbcl-codepoints-to-string-010'/1]).
-export(['cbcl-codepoints-to-string-011'/1]).
-export(['cbcl-codepoints-to-string-012'/1]).
-export(['cbcl-codepoints-to-string-013'/1]).
-export(['cbcl-codepoints-to-string-014'/1]).
-export(['cbcl-codepoints-to-string-015'/1]).
-export(['cbcl-codepoints-to-string-016'/1]).
-export(['cbcl-codepoints-to-string-017'/1]).
-export(['cbcl-codepoints-to-string-018'/1]).
-export(['cbcl-codepoints-to-string-019'/1]).
-export(['cbcl-codepoints-to-string-020'/1]).
-export(['cbcl-codepoints-to-string-021'/1]).
-export(['cbcl-codepoints-to-string-022'/1]).
-export(['cbcl-codepoints-to-string-023'/1]).
-export(['cbcl-codepoints-to-string-024'/1]).
-export(['cbcl-codepoints-to-string-025'/1]).
-export(['cbcl-codepoints-to-string-026'/1]).
-export(['cbcl-codepoints-to-string-027'/1]).
suite() -> [{timetrap, {seconds, 180}}].
init_per_group(_, Config) -> Config.
end_per_group(_, _Config) ->
xqerl_code_server:unload(all).
end_per_suite(_Config) ->
ct:timetrap({seconds, 60}),
xqerl_code_server:unload(all).
init_per_suite(Config) ->
{ok, _} = application:ensure_all_started(xqerl),
DD = filename:dirname(filename:dirname(filename:dirname(?config(data_dir, Config)))),
TD = filename:join(DD, "QT3-test-suite"),
__BaseDir = filename:join(TD, "fn"),
[{base_dir, __BaseDir} | Config].
all() ->
[
{group, group_0},
{group, group_1},
{group, group_2},
{group, group_3}
].
groups() ->
[
{group_0, [parallel], [
'fn-codepoints-to-string1args-1',
'fn-codepoints-to-string1args-2',
'fn-codepoints-to-string1args-3',
'fn-codepoints-to-string1args-4',
'fn-codepoints-to-string-1',
'fn-codepoints-to-string-2',
'fn-codepoints-to-string-3',
'fn-codepoints-to-string-4',
'fn-codepoints-to-string-5',
'fn-codepoints-to-string-6',
'fn-codepoints-to-string-7',
'fn-codepoints-to-string-8',
'fn-codepoints-to-string-9',
'fn-codepoints-to-string-10',
'fn-codepoints-to-string-11',
'fn-codepoints-to-string-12',
'fn-codepoints-to-string-13',
'fn-codepoints-to-string-14',
'fn-codepoints-to-string-15',
'fn-codepoints-to-string-16',
'K-CodepointToStringFunc-1',
'K-CodepointToStringFunc-2',
'K-CodepointToStringFunc-3'
]},
{group_1, [parallel], [
'K-CodepointToStringFunc-4',
'K-CodepointToStringFunc-5',
'K-CodepointToStringFunc-6',
'K-CodepointToStringFunc-7',
'K-CodepointToStringFunc-8',
'K-CodepointToStringFunc-8a',
'K-CodepointToStringFunc-9',
'K-CodepointToStringFunc-10',
'K-CodepointToStringFunc-11',
'K-CodepointToStringFunc-11b',
'K-CodepointToStringFunc-12',
'K-CodepointToStringFunc-12b',
'K-CodepointToStringFunc-13',
'K-CodepointToStringFunc-14',
'K-CodepointToStringFunc-15',
'K-CodepointToStringFunc-16',
'K-CodepointToStringFunc-17',
'K-CodepointToStringFunc-18',
'K-CodepointToStringFunc-19',
'K-CodepointToStringFunc-20',
'K-CodepointToStringFunc-21',
'K-CodepointToStringFunc-22',
'K-CodepointToStringFunc-23',
'K-CodepointToStringFunc-24'
]},
{group_2, [parallel], [
'K-CodepointToStringFunc-25',
'K-CodepointToStringFunc-26',
'K-CodepointToStringFunc-27',
'K-CodepointToStringFunc-28',
'K-CodepointToStringFunc-29',
'cbcl-codepoints-to-string-001',
'cbcl-codepoints-to-string-002',
'cbcl-codepoints-to-string-003',
'cbcl-codepoints-to-string-004',
'cbcl-codepoints-to-string-005',
'cbcl-codepoints-to-string-006',
'cbcl-codepoints-to-string-007',
'cbcl-codepoints-to-string-008',
'cbcl-codepoints-to-string-009',
'cbcl-codepoints-to-string-010',
'cbcl-codepoints-to-string-011',
'cbcl-codepoints-to-string-012',
'cbcl-codepoints-to-string-013',
'cbcl-codepoints-to-string-014',
'cbcl-codepoints-to-string-015',
'cbcl-codepoints-to-string-016',
'cbcl-codepoints-to-string-017',
'cbcl-codepoints-to-string-018',
'cbcl-codepoints-to-string-019'
]},
{group_3, [parallel], [
'cbcl-codepoints-to-string-020',
'cbcl-codepoints-to-string-021',
'cbcl-codepoints-to-string-022',
'cbcl-codepoints-to-string-023',
'cbcl-codepoints-to-string-024',
'cbcl-codepoints-to-string-025',
'cbcl-codepoints-to-string-026',
'cbcl-codepoints-to-string-027'
]}
].
'fn-codepoints-to-string1args-1'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "codepoints-to-string((98,223,1682,12365,63744))",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "fn-codepoints-to-string1args-1.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_string_value(Res, "bßڒき豈") of
true -> {comment, "String correct"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'fn-codepoints-to-string1args-2'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "codepoints-to-string(())",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "fn-codepoints-to-string1args-2.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_string_value(Res, "") of
true -> {comment, "String correct"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'fn-codepoints-to-string1args-3'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "codepoints-to-string('hello')",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "fn-codepoints-to-string1args-3.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "XPTY0004") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XPTY0004 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'fn-codepoints-to-string1args-4'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "codepoints-to-string((),())",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "fn-codepoints-to-string1args-4.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "XPST0017") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XPST0017 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'fn-codepoints-to-string-1'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "fn:codepoints-to-string(0)",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "fn-codepoints-to-string-1.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "FOCH0001") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: FOCH0001 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'fn-codepoints-to-string-2'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "fn:codepoints-to-string(10000000)",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "fn-codepoints-to-string-2.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "FOCH0001") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: FOCH0001 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'fn-codepoints-to-string-3'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "fn:codepoints-to-string(49)",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "fn-codepoints-to-string-3.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_string_value(Res, "1") of
true -> {comment, "String correct"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'fn-codepoints-to-string-4'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "fn:codepoints-to-string(97)",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "fn-codepoints-to-string-4.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_string_value(Res, "a") of
true -> {comment, "String correct"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'fn-codepoints-to-string-5'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "fn:codepoints-to-string((49,97))",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "fn-codepoints-to-string-5.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_string_value(Res, "1a") of
true -> {comment, "String correct"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'fn-codepoints-to-string-6'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "fn:codepoints-to-string((35, 42, 94, 36))",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "fn-codepoints-to-string-6.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_string_value(Res, "#*^$") of
true -> {comment, "String correct"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'fn-codepoints-to-string-7'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"fn:codepoints-to-string((99,111,100,101,112,111,105,110,116,115,45,116,111,45,115,116,114,105,110,103))",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "fn-codepoints-to-string-7.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_string_value(Res, "codepoints-to-string") of
true -> {comment, "String correct"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'fn-codepoints-to-string-8'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "xs:string(fn:codepoints-to-string((65,32,83,116,114,105,110,103)))",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "fn-codepoints-to-string-8.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_string_value(Res, "A String") of
true -> {comment, "String correct"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'fn-codepoints-to-string-9'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "fn:upper-case(fn:codepoints-to-string((65,32,83,84,82,73,78,71)))",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "fn-codepoints-to-string-9.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_string_value(Res, "A STRING") of
true -> {comment, "String correct"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'fn-codepoints-to-string-10'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "fn:lower-case(fn:codepoints-to-string((97,32,115,116,114,105,110,103)))",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "fn-codepoints-to-string-10.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_string_value(Res, "a string") of
true -> {comment, "String correct"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'fn-codepoints-to-string-11'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "fn:codepoints-to-string(xs:integer(97))",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "fn-codepoints-to-string-11.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_string_value(Res, "a") of
true -> {comment, "String correct"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'fn-codepoints-to-string-12'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "fn:codepoints-to-string(xs:integer(fn:avg((65,32,83,116,114,105,110,103))))",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "fn-codepoints-to-string-12.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_string_value(Res, "[") of
true -> {comment, "String correct"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'fn-codepoints-to-string-13'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "fn:concat(fn:codepoints-to-string((49,97)),\"1a\")",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "fn-codepoints-to-string-13.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_string_value(Res, "1a1a") of
true -> {comment, "String correct"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'fn-codepoints-to-string-14'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "fn:string-to-codepoints(fn:codepoints-to-string((49,97)))",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "fn-codepoints-to-string-14.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_deep_eq(Res, "49, 97") of
true -> {comment, "Deep equal"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'fn-codepoints-to-string-15'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "fn:string-length(fn:codepoints-to-string((49,97)))",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "fn-codepoints-to-string-15.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_eq(Res, "2") of
true -> {comment, "Equal"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'fn-codepoints-to-string-16'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "fn:string-join((fn:codepoints-to-string((49,97)),'ab'),'')",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "fn-codepoints-to-string-16.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_string_value(Res, "1aab") of
true -> {comment, "String correct"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'K-CodepointToStringFunc-1'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "codepoints-to-string()",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "K-CodepointToStringFunc-1.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "XPST0017") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XPST0017 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'K-CodepointToStringFunc-2'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "codepoints-to-string((84, 104), \"INVALID\")",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "K-CodepointToStringFunc-2.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "XPST0017") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XPST0017 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'K-CodepointToStringFunc-3'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "codepoints-to-string(()) eq \"\"",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "K-CodepointToStringFunc-3.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_true(Res) of
true -> {comment, "Empty"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'K-CodepointToStringFunc-4'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "codepoints-to-string((87, 36, 56, 87, 102, 96)) eq \"W$8Wf`\"",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "K-CodepointToStringFunc-4.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_true(Res) of
true -> {comment, "Empty"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'K-CodepointToStringFunc-5'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "codepoints-to-string(57343)",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "K-CodepointToStringFunc-5.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "FOCH0001") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: FOCH0001 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'K-CodepointToStringFunc-6'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "codepoints-to-string(-500)",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "K-CodepointToStringFunc-6.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "FOCH0001") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: FOCH0001 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'K-CodepointToStringFunc-7'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "codepoints-to-string(0)",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "K-CodepointToStringFunc-7.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "FOCH0001") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: FOCH0001 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'K-CodepointToStringFunc-8'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "codepoints-to-string(8)",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "K-CodepointToStringFunc-8.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case
lists:any(
fun
({comment, _}) -> true;
(_) -> false
end,
[
case xqerl_test:assert_error(Res, "FOCH0001") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: FOCH0001 " ++ binary_to_list(F)};
{false, F} -> F
end
]
)
of
true -> {comment, "any-of"};
_ -> false
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'K-CodepointToStringFunc-8a'(Config) ->
__BaseDir = ?config(base_dir, Config),
{skip, "xml-version:1.1"}.
'K-CodepointToStringFunc-9'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "codepoints-to-string(9) eq \" \"",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "K-CodepointToStringFunc-9.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_true(Res) of
true -> {comment, "Empty"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'K-CodepointToStringFunc-10'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"codepoints-to-string(10) eq \"\n"
"\"",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "K-CodepointToStringFunc-10.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_true(Res) of
true -> {comment, "Empty"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'K-CodepointToStringFunc-11'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "codepoints-to-string(11)",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "K-CodepointToStringFunc-11.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "FOCH0001") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: FOCH0001 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'K-CodepointToStringFunc-11b'(Config) ->
__BaseDir = ?config(base_dir, Config),
{skip, "xml-version:1.1"}.
'K-CodepointToStringFunc-12'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "codepoints-to-string(12)",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "K-CodepointToStringFunc-12.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "FOCH0001") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: FOCH0001 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'K-CodepointToStringFunc-12b'(Config) ->
__BaseDir = ?config(base_dir, Config),
{skip, "xml-version:1.1"}.
'K-CodepointToStringFunc-13'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "codepoints-to-string(13) eq \"
\"",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "K-CodepointToStringFunc-13.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_true(Res) of
true -> {comment, "Empty"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'K-CodepointToStringFunc-14'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "string-to-codepoints(codepoints-to-string(14))",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "K-CodepointToStringFunc-14.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case
lists:any(
fun
({comment, _}) -> true;
(_) -> false
end,
[
case xqerl_test:assert_eq(Res, "14") of
true -> {comment, "Equal"};
{false, F} -> F
end,
case xqerl_test:assert_error(Res, "FOCH0001") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: FOCH0001 " ++ binary_to_list(F)};
{false, F} -> F
end
]
)
of
true -> {comment, "any-of"};
_ -> false
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'K-CodepointToStringFunc-15'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "string-to-codepoints(codepoints-to-string(31))",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "K-CodepointToStringFunc-15.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case
lists:any(
fun
({comment, _}) -> true;
(_) -> false
end,
[
case xqerl_test:assert_eq(Res, "31") of
true -> {comment, "Equal"};
{false, F} -> F
end,
case xqerl_test:assert_error(Res, "FOCH0001") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: FOCH0001 " ++ binary_to_list(F)};
{false, F} -> F
end
]
)
of
true -> {comment, "any-of"};
_ -> false
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'K-CodepointToStringFunc-16'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "codepoints-to-string(32) eq \" \"",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "K-CodepointToStringFunc-16.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_true(Res) of
true -> {comment, "Empty"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'K-CodepointToStringFunc-17'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "codepoints-to-string(27637) eq \"毵\"",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "K-CodepointToStringFunc-17.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_true(Res) of
true -> {comment, "Empty"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'K-CodepointToStringFunc-18'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "codepoints-to-string(55295) eq \"\"",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "K-CodepointToStringFunc-18.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_true(Res) of
true -> {comment, "Empty"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'K-CodepointToStringFunc-19'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "codepoints-to-string(55296)",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "K-CodepointToStringFunc-19.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "FOCH0001") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: FOCH0001 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'K-CodepointToStringFunc-20'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "codepoints-to-string(57343)",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "K-CodepointToStringFunc-20.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "FOCH0001") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: FOCH0001 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'K-CodepointToStringFunc-21'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "codepoints-to-string(57344) eq \"\"",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "K-CodepointToStringFunc-21.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_true(Res) of
true -> {comment, "Empty"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'K-CodepointToStringFunc-22'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "codepoints-to-string(61438) eq \"\"",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "K-CodepointToStringFunc-22.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_true(Res) of
true -> {comment, "Empty"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'K-CodepointToStringFunc-23'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "codepoints-to-string(65533) eq \"�\"",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "K-CodepointToStringFunc-23.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_true(Res) of
true -> {comment, "Empty"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'K-CodepointToStringFunc-24'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "codepoints-to-string(65534)",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "K-CodepointToStringFunc-24.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "FOCH0001") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: FOCH0001 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'K-CodepointToStringFunc-25'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "codepoints-to-string(65535)",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "K-CodepointToStringFunc-25.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "FOCH0001") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: FOCH0001 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'K-CodepointToStringFunc-26'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "codepoints-to-string(65536) eq \"𐀀\"",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "K-CodepointToStringFunc-26.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_true(Res) of
true -> {comment, "Empty"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'K-CodepointToStringFunc-27'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "codepoints-to-string(589823) eq \"\"",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "K-CodepointToStringFunc-27.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_true(Res) of
true -> {comment, "Empty"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'K-CodepointToStringFunc-28'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "codepoints-to-string(1114111) eq \"\"",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "K-CodepointToStringFunc-28.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_true(Res) of
true -> {comment, "Empty"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'K-CodepointToStringFunc-29'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "codepoints-to-string(1114112)",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "K-CodepointToStringFunc-29.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "FOCH0001") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: FOCH0001 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'cbcl-codepoints-to-string-001'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare function local:test($test as xs:integer) as xs:integer? { \n"
" if ($test = 1) then ( 0 ) else if ($test = 2) then ( 9 ) else if ($test = 3) then ( 13 ) else if ($test = 4) then ( 16 ) else () \n"
" }; \n"
" fn:codepoints-to-string( local:test(1) to 32 )",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "cbcl-codepoints-to-string-001.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "FOCH0001") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: FOCH0001 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'cbcl-codepoints-to-string-002'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare function local:test($test as xs:integer) as xs:integer? { \n"
" if ($test = 1) then ( 0 ) else if ($test = 2) then ( 9 ) else if ($test = 3) then ( 13 ) else if ($test = 4) then ( 16 ) else () \n"
" }; \n"
" fn:codepoints-to-string( local:test(2) to 32 )",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "cbcl-codepoints-to-string-002.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "FOCH0001") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: FOCH0001 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'cbcl-codepoints-to-string-003'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare function local:test($test as xs:integer) as xs:integer? { \n"
" if ($test = 1) then ( 0 ) else if ($test = 2) then ( 9 ) else if ($test = 3) then ( 13 )else if ($test = 4) then ( 16 ) else () \n"
" }; \n"
" fn:codepoints-to-string( local:test(3) to 32 )",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "cbcl-codepoints-to-string-003.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "FOCH0001") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: FOCH0001 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'cbcl-codepoints-to-string-004'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"declare function local:test($test as xs:integer) as xs:integer? { \n"
" if ($test = 1) then ( 0 ) else if ($test = 2) then ( 9 ) else if ($test = 3) then ( 13 ) else if ($test = 4) then ( 16 ) else () \n"
" }; \n"
" fn:codepoints-to-string( local:test(4) to 32 )",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "cbcl-codepoints-to-string-004.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "FOCH0001") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: FOCH0001 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'cbcl-codepoints-to-string-005'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "fn:codepoints-to-string( 65536 to 1114112 )",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "cbcl-codepoints-to-string-005.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "FOCH0001") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: FOCH0001 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'cbcl-codepoints-to-string-006'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "fn:codepoints-to-string( 55295 to 55297 )",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "cbcl-codepoints-to-string-006.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "FOCH0001") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: FOCH0001 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'cbcl-codepoints-to-string-007'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "fn:codepoints-to-string( 55296 to 57343 )",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "cbcl-codepoints-to-string-007.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "FOCH0001") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: FOCH0001 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'cbcl-codepoints-to-string-008'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "fn:codepoints-to-string( 65535 to 70000 )",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "cbcl-codepoints-to-string-008.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "FOCH0001") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: FOCH0001 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'cbcl-codepoints-to-string-009'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "fn:codepoints-to-string( 65530 to 70000 )",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "cbcl-codepoints-to-string-009.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "FOCH0001") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: FOCH0001 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'cbcl-codepoints-to-string-010'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "fn:boolean(fn:codepoints-to-string( 65 to 76 ))",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "cbcl-codepoints-to-string-010.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_true(Res) of
true -> {comment, "Empty"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'cbcl-codepoints-to-string-011'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "fn:boolean(fn:codepoints-to-string( 0 ))",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "cbcl-codepoints-to-string-011.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "FOCH0001") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: FOCH0001 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'cbcl-codepoints-to-string-012'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "fn:boolean(fn:codepoints-to-string( 999999999 ))",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "cbcl-codepoints-to-string-012.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "FOCH0001") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: FOCH0001 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'cbcl-codepoints-to-string-013'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "fn:boolean(fn:codepoints-to-string( 65 ))",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "cbcl-codepoints-to-string-013.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_true(Res) of
true -> {comment, "Empty"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'cbcl-codepoints-to-string-014'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "fn:boolean(fn:codepoints-to-string( () ))",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "cbcl-codepoints-to-string-014.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_false(Res) of
true -> {comment, "Empty"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'cbcl-codepoints-to-string-015'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"deep-equal( fn:string-to-codepoints(fn:codepoints-to-string(65536 to 66000)), 65536 to 66000 )",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "cbcl-codepoints-to-string-015.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_true(Res) of
true -> {comment, "Empty"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'cbcl-codepoints-to-string-016'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"deep-equal( fn:string-to-codepoints(fn:codepoints-to-string(65536 to 100000)), 65536 to 100000 )",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "cbcl-codepoints-to-string-016.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_true(Res) of
true -> {comment, "Empty"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'cbcl-codepoints-to-string-017'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "for $x in 32 to 64 return boolean(codepoints-to-string($x to $x + 10))",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "cbcl-codepoints-to-string-017.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case
xqerl_test:assert_string_value(
Res,
"true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true"
)
of
true -> {comment, "String correct"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'cbcl-codepoints-to-string-018'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"if(5 < exactly-one((1 to 10)[. div 2 = 5])) then codepoints-to-string(32 to exactly-one((1 to 100)[. div 2 = 40])) else ()",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "cbcl-codepoints-to-string-018.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case
xqerl_test:assert_string_value(
Res,
" !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOP"
)
of
true -> {comment, "String correct"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'cbcl-codepoints-to-string-019'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "for $x in 65 to 75 return string-length(codepoints-to-string($x to $x+10))",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "cbcl-codepoints-to-string-019.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_string_value(Res, "11 11 11 11 11 11 11 11 11 11 11") of
true -> {comment, "String correct"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'cbcl-codepoints-to-string-020'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"for $x in 65 to 75 return boolean(codepoints-to-string($x[. mod 2 = 0] to ($x+9)[. mod 2 = 0]))",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "cbcl-codepoints-to-string-020.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case
xqerl_test:assert_string_value(
Res,
"false false false false false false false false false false false"
)
of
true -> {comment, "String correct"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'cbcl-codepoints-to-string-021'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"let $y := 65536*65536 return for $x in $y to $y+10 return codepoints-to-string(65 to $x)",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "cbcl-codepoints-to-string-021.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case
lists:any(
fun
({comment, _}) -> true;
(_) -> false
end,
[
case xqerl_test:assert_error(Res, "FOCH0001") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: FOCH0001 " ++ binary_to_list(F)};
{false, F} -> F
end,
case xqerl_test:assert_error(Res, "XPDY0130") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XPDY0130 " ++ binary_to_list(F)};
{false, F} -> F
end
]
)
of
true -> {comment, "any-of"};
_ -> false
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'cbcl-codepoints-to-string-022'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"let $y := 65536*65536 return for $x in $y to $y+10 return codepoints-to-string($x to $x+10)",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "cbcl-codepoints-to-string-022.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "FOCH0001") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: FOCH0001 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'cbcl-codepoints-to-string-023'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "for $x in 9 to 15 return codepoints-to-string($x to $x)",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "cbcl-codepoints-to-string-023.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "FOCH0001") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: FOCH0001 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'cbcl-codepoints-to-string-024'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "for $x in 13 to 15 return codepoints-to-string($x to $x)",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "cbcl-codepoints-to-string-024.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "FOCH0001") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: FOCH0001 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'cbcl-codepoints-to-string-025'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "for $x in 9 to 9 return codepoints-to-string($x to $x+1)",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "cbcl-codepoints-to-string-025.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case
xqerl_test:assert_eq(
Res,
"' \n"
"'"
)
of
true -> {comment, "Equal"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'cbcl-codepoints-to-string-026'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "for $x in 13 to 13 return codepoints-to-string($x to $x)",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "cbcl-codepoints-to-string-026.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_string_value(Res, "
") of
true -> {comment, "String correct"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'cbcl-codepoints-to-string-027'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "for $x in (13), $y in (13,9,10) return codepoints-to-string($x to $y)",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "cbcl-codepoints-to-string-027.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_string_value(Res, "
") of
true -> {comment, "String correct"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
| null | https://raw.githubusercontent.com/zadean/xqerl/1a94833e996435495922346010ce918b4b0717f2/test/fn/fn_codepoints_to_string_SUITE.erl | erlang | &'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOP" | -module('fn_codepoints_to_string_SUITE').
-include_lib("common_test/include/ct.hrl").
-export([
all/0,
groups/0,
suite/0
]).
-export([
init_per_suite/1,
init_per_group/2,
end_per_group/2,
end_per_suite/1
]).
-export(['fn-codepoints-to-string1args-1'/1]).
-export(['fn-codepoints-to-string1args-2'/1]).
-export(['fn-codepoints-to-string1args-3'/1]).
-export(['fn-codepoints-to-string1args-4'/1]).
-export(['fn-codepoints-to-string-1'/1]).
-export(['fn-codepoints-to-string-2'/1]).
-export(['fn-codepoints-to-string-3'/1]).
-export(['fn-codepoints-to-string-4'/1]).
-export(['fn-codepoints-to-string-5'/1]).
-export(['fn-codepoints-to-string-6'/1]).
-export(['fn-codepoints-to-string-7'/1]).
-export(['fn-codepoints-to-string-8'/1]).
-export(['fn-codepoints-to-string-9'/1]).
-export(['fn-codepoints-to-string-10'/1]).
-export(['fn-codepoints-to-string-11'/1]).
-export(['fn-codepoints-to-string-12'/1]).
-export(['fn-codepoints-to-string-13'/1]).
-export(['fn-codepoints-to-string-14'/1]).
-export(['fn-codepoints-to-string-15'/1]).
-export(['fn-codepoints-to-string-16'/1]).
-export(['K-CodepointToStringFunc-1'/1]).
-export(['K-CodepointToStringFunc-2'/1]).
-export(['K-CodepointToStringFunc-3'/1]).
-export(['K-CodepointToStringFunc-4'/1]).
-export(['K-CodepointToStringFunc-5'/1]).
-export(['K-CodepointToStringFunc-6'/1]).
-export(['K-CodepointToStringFunc-7'/1]).
-export(['K-CodepointToStringFunc-8'/1]).
-export(['K-CodepointToStringFunc-8a'/1]).
-export(['K-CodepointToStringFunc-9'/1]).
-export(['K-CodepointToStringFunc-10'/1]).
-export(['K-CodepointToStringFunc-11'/1]).
-export(['K-CodepointToStringFunc-11b'/1]).
-export(['K-CodepointToStringFunc-12'/1]).
-export(['K-CodepointToStringFunc-12b'/1]).
-export(['K-CodepointToStringFunc-13'/1]).
-export(['K-CodepointToStringFunc-14'/1]).
-export(['K-CodepointToStringFunc-15'/1]).
-export(['K-CodepointToStringFunc-16'/1]).
-export(['K-CodepointToStringFunc-17'/1]).
-export(['K-CodepointToStringFunc-18'/1]).
-export(['K-CodepointToStringFunc-19'/1]).
-export(['K-CodepointToStringFunc-20'/1]).
-export(['K-CodepointToStringFunc-21'/1]).
-export(['K-CodepointToStringFunc-22'/1]).
-export(['K-CodepointToStringFunc-23'/1]).
-export(['K-CodepointToStringFunc-24'/1]).
-export(['K-CodepointToStringFunc-25'/1]).
-export(['K-CodepointToStringFunc-26'/1]).
-export(['K-CodepointToStringFunc-27'/1]).
-export(['K-CodepointToStringFunc-28'/1]).
-export(['K-CodepointToStringFunc-29'/1]).
-export(['cbcl-codepoints-to-string-001'/1]).
-export(['cbcl-codepoints-to-string-002'/1]).
-export(['cbcl-codepoints-to-string-003'/1]).
-export(['cbcl-codepoints-to-string-004'/1]).
-export(['cbcl-codepoints-to-string-005'/1]).
-export(['cbcl-codepoints-to-string-006'/1]).
-export(['cbcl-codepoints-to-string-007'/1]).
-export(['cbcl-codepoints-to-string-008'/1]).
-export(['cbcl-codepoints-to-string-009'/1]).
-export(['cbcl-codepoints-to-string-010'/1]).
-export(['cbcl-codepoints-to-string-011'/1]).
-export(['cbcl-codepoints-to-string-012'/1]).
-export(['cbcl-codepoints-to-string-013'/1]).
-export(['cbcl-codepoints-to-string-014'/1]).
-export(['cbcl-codepoints-to-string-015'/1]).
-export(['cbcl-codepoints-to-string-016'/1]).
-export(['cbcl-codepoints-to-string-017'/1]).
-export(['cbcl-codepoints-to-string-018'/1]).
-export(['cbcl-codepoints-to-string-019'/1]).
-export(['cbcl-codepoints-to-string-020'/1]).
-export(['cbcl-codepoints-to-string-021'/1]).
-export(['cbcl-codepoints-to-string-022'/1]).
-export(['cbcl-codepoints-to-string-023'/1]).
-export(['cbcl-codepoints-to-string-024'/1]).
-export(['cbcl-codepoints-to-string-025'/1]).
-export(['cbcl-codepoints-to-string-026'/1]).
-export(['cbcl-codepoints-to-string-027'/1]).
suite() -> [{timetrap, {seconds, 180}}].
init_per_group(_, Config) -> Config.
end_per_group(_, _Config) ->
xqerl_code_server:unload(all).
end_per_suite(_Config) ->
ct:timetrap({seconds, 60}),
xqerl_code_server:unload(all).
init_per_suite(Config) ->
{ok, _} = application:ensure_all_started(xqerl),
DD = filename:dirname(filename:dirname(filename:dirname(?config(data_dir, Config)))),
TD = filename:join(DD, "QT3-test-suite"),
__BaseDir = filename:join(TD, "fn"),
[{base_dir, __BaseDir} | Config].
all() ->
[
{group, group_0},
{group, group_1},
{group, group_2},
{group, group_3}
].
groups() ->
[
{group_0, [parallel], [
'fn-codepoints-to-string1args-1',
'fn-codepoints-to-string1args-2',
'fn-codepoints-to-string1args-3',
'fn-codepoints-to-string1args-4',
'fn-codepoints-to-string-1',
'fn-codepoints-to-string-2',
'fn-codepoints-to-string-3',
'fn-codepoints-to-string-4',
'fn-codepoints-to-string-5',
'fn-codepoints-to-string-6',
'fn-codepoints-to-string-7',
'fn-codepoints-to-string-8',
'fn-codepoints-to-string-9',
'fn-codepoints-to-string-10',
'fn-codepoints-to-string-11',
'fn-codepoints-to-string-12',
'fn-codepoints-to-string-13',
'fn-codepoints-to-string-14',
'fn-codepoints-to-string-15',
'fn-codepoints-to-string-16',
'K-CodepointToStringFunc-1',
'K-CodepointToStringFunc-2',
'K-CodepointToStringFunc-3'
]},
{group_1, [parallel], [
'K-CodepointToStringFunc-4',
'K-CodepointToStringFunc-5',
'K-CodepointToStringFunc-6',
'K-CodepointToStringFunc-7',
'K-CodepointToStringFunc-8',
'K-CodepointToStringFunc-8a',
'K-CodepointToStringFunc-9',
'K-CodepointToStringFunc-10',
'K-CodepointToStringFunc-11',
'K-CodepointToStringFunc-11b',
'K-CodepointToStringFunc-12',
'K-CodepointToStringFunc-12b',
'K-CodepointToStringFunc-13',
'K-CodepointToStringFunc-14',
'K-CodepointToStringFunc-15',
'K-CodepointToStringFunc-16',
'K-CodepointToStringFunc-17',
'K-CodepointToStringFunc-18',
'K-CodepointToStringFunc-19',
'K-CodepointToStringFunc-20',
'K-CodepointToStringFunc-21',
'K-CodepointToStringFunc-22',
'K-CodepointToStringFunc-23',
'K-CodepointToStringFunc-24'
]},
{group_2, [parallel], [
'K-CodepointToStringFunc-25',
'K-CodepointToStringFunc-26',
'K-CodepointToStringFunc-27',
'K-CodepointToStringFunc-28',
'K-CodepointToStringFunc-29',
'cbcl-codepoints-to-string-001',
'cbcl-codepoints-to-string-002',
'cbcl-codepoints-to-string-003',
'cbcl-codepoints-to-string-004',
'cbcl-codepoints-to-string-005',
'cbcl-codepoints-to-string-006',
'cbcl-codepoints-to-string-007',
'cbcl-codepoints-to-string-008',
'cbcl-codepoints-to-string-009',
'cbcl-codepoints-to-string-010',
'cbcl-codepoints-to-string-011',
'cbcl-codepoints-to-string-012',
'cbcl-codepoints-to-string-013',
'cbcl-codepoints-to-string-014',
'cbcl-codepoints-to-string-015',
'cbcl-codepoints-to-string-016',
'cbcl-codepoints-to-string-017',
'cbcl-codepoints-to-string-018',
'cbcl-codepoints-to-string-019'
]},
{group_3, [parallel], [
'cbcl-codepoints-to-string-020',
'cbcl-codepoints-to-string-021',
'cbcl-codepoints-to-string-022',
'cbcl-codepoints-to-string-023',
'cbcl-codepoints-to-string-024',
'cbcl-codepoints-to-string-025',
'cbcl-codepoints-to-string-026',
'cbcl-codepoints-to-string-027'
]}
].
'fn-codepoints-to-string1args-1'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "codepoints-to-string((98,223,1682,12365,63744))",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "fn-codepoints-to-string1args-1.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_string_value(Res, "bßڒき豈") of
true -> {comment, "String correct"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'fn-codepoints-to-string1args-2'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "codepoints-to-string(())",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "fn-codepoints-to-string1args-2.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_string_value(Res, "") of
true -> {comment, "String correct"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'fn-codepoints-to-string1args-3'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "codepoints-to-string('hello')",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "fn-codepoints-to-string1args-3.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "XPTY0004") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XPTY0004 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'fn-codepoints-to-string1args-4'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "codepoints-to-string((),())",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "fn-codepoints-to-string1args-4.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "XPST0017") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XPST0017 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'fn-codepoints-to-string-1'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "fn:codepoints-to-string(0)",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "fn-codepoints-to-string-1.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "FOCH0001") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: FOCH0001 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'fn-codepoints-to-string-2'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "fn:codepoints-to-string(10000000)",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "fn-codepoints-to-string-2.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "FOCH0001") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: FOCH0001 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'fn-codepoints-to-string-3'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "fn:codepoints-to-string(49)",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "fn-codepoints-to-string-3.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_string_value(Res, "1") of
true -> {comment, "String correct"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'fn-codepoints-to-string-4'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "fn:codepoints-to-string(97)",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "fn-codepoints-to-string-4.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_string_value(Res, "a") of
true -> {comment, "String correct"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'fn-codepoints-to-string-5'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "fn:codepoints-to-string((49,97))",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "fn-codepoints-to-string-5.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_string_value(Res, "1a") of
true -> {comment, "String correct"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'fn-codepoints-to-string-6'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "fn:codepoints-to-string((35, 42, 94, 36))",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "fn-codepoints-to-string-6.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_string_value(Res, "#*^$") of
true -> {comment, "String correct"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'fn-codepoints-to-string-7'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"fn:codepoints-to-string((99,111,100,101,112,111,105,110,116,115,45,116,111,45,115,116,114,105,110,103))",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "fn-codepoints-to-string-7.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_string_value(Res, "codepoints-to-string") of
true -> {comment, "String correct"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'fn-codepoints-to-string-8'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "xs:string(fn:codepoints-to-string((65,32,83,116,114,105,110,103)))",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "fn-codepoints-to-string-8.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_string_value(Res, "A String") of
true -> {comment, "String correct"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'fn-codepoints-to-string-9'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "fn:upper-case(fn:codepoints-to-string((65,32,83,84,82,73,78,71)))",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "fn-codepoints-to-string-9.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_string_value(Res, "A STRING") of
true -> {comment, "String correct"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'fn-codepoints-to-string-10'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "fn:lower-case(fn:codepoints-to-string((97,32,115,116,114,105,110,103)))",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "fn-codepoints-to-string-10.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_string_value(Res, "a string") of
true -> {comment, "String correct"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'fn-codepoints-to-string-11'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "fn:codepoints-to-string(xs:integer(97))",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "fn-codepoints-to-string-11.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_string_value(Res, "a") of
true -> {comment, "String correct"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'fn-codepoints-to-string-12'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "fn:codepoints-to-string(xs:integer(fn:avg((65,32,83,116,114,105,110,103))))",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "fn-codepoints-to-string-12.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_string_value(Res, "[") of
true -> {comment, "String correct"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'fn-codepoints-to-string-13'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "fn:concat(fn:codepoints-to-string((49,97)),\"1a\")",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "fn-codepoints-to-string-13.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_string_value(Res, "1a1a") of
true -> {comment, "String correct"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'fn-codepoints-to-string-14'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "fn:string-to-codepoints(fn:codepoints-to-string((49,97)))",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "fn-codepoints-to-string-14.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_deep_eq(Res, "49, 97") of
true -> {comment, "Deep equal"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'fn-codepoints-to-string-15'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "fn:string-length(fn:codepoints-to-string((49,97)))",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "fn-codepoints-to-string-15.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_eq(Res, "2") of
true -> {comment, "Equal"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'fn-codepoints-to-string-16'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "fn:string-join((fn:codepoints-to-string((49,97)),'ab'),'')",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "fn-codepoints-to-string-16.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_string_value(Res, "1aab") of
true -> {comment, "String correct"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'K-CodepointToStringFunc-1'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "codepoints-to-string()",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "K-CodepointToStringFunc-1.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "XPST0017") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XPST0017 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'K-CodepointToStringFunc-2'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "codepoints-to-string((84, 104), \"INVALID\")",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "K-CodepointToStringFunc-2.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "XPST0017") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XPST0017 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'K-CodepointToStringFunc-3'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "codepoints-to-string(()) eq \"\"",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "K-CodepointToStringFunc-3.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_true(Res) of
true -> {comment, "Empty"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'K-CodepointToStringFunc-4'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "codepoints-to-string((87, 36, 56, 87, 102, 96)) eq \"W$8Wf`\"",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "K-CodepointToStringFunc-4.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_true(Res) of
true -> {comment, "Empty"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'K-CodepointToStringFunc-5'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "codepoints-to-string(57343)",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "K-CodepointToStringFunc-5.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "FOCH0001") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: FOCH0001 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'K-CodepointToStringFunc-6'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "codepoints-to-string(-500)",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "K-CodepointToStringFunc-6.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "FOCH0001") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: FOCH0001 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'K-CodepointToStringFunc-7'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "codepoints-to-string(0)",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "K-CodepointToStringFunc-7.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "FOCH0001") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: FOCH0001 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'K-CodepointToStringFunc-8'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "codepoints-to-string(8)",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "K-CodepointToStringFunc-8.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case
lists:any(
fun
({comment, _}) -> true;
(_) -> false
end,
[
case xqerl_test:assert_error(Res, "FOCH0001") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: FOCH0001 " ++ binary_to_list(F)};
{false, F} -> F
end
]
)
of
true -> {comment, "any-of"};
_ -> false
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'K-CodepointToStringFunc-8a'(Config) ->
__BaseDir = ?config(base_dir, Config),
{skip, "xml-version:1.1"}.
'K-CodepointToStringFunc-9'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "codepoints-to-string(9) eq \" \"",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "K-CodepointToStringFunc-9.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_true(Res) of
true -> {comment, "Empty"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'K-CodepointToStringFunc-10'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"codepoints-to-string(10) eq \"\n"
"\"",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "K-CodepointToStringFunc-10.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_true(Res) of
true -> {comment, "Empty"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'K-CodepointToStringFunc-11'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "codepoints-to-string(11)",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "K-CodepointToStringFunc-11.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "FOCH0001") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: FOCH0001 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'K-CodepointToStringFunc-11b'(Config) ->
__BaseDir = ?config(base_dir, Config),
{skip, "xml-version:1.1"}.
'K-CodepointToStringFunc-12'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "codepoints-to-string(12)",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "K-CodepointToStringFunc-12.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "FOCH0001") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: FOCH0001 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'K-CodepointToStringFunc-12b'(Config) ->
__BaseDir = ?config(base_dir, Config),
{skip, "xml-version:1.1"}.
'K-CodepointToStringFunc-13'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "codepoints-to-string(13) eq \"
\"",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "K-CodepointToStringFunc-13.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_true(Res) of
true -> {comment, "Empty"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'K-CodepointToStringFunc-14'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "string-to-codepoints(codepoints-to-string(14))",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "K-CodepointToStringFunc-14.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case
lists:any(
fun
({comment, _}) -> true;
(_) -> false
end,
[
case xqerl_test:assert_eq(Res, "14") of
true -> {comment, "Equal"};
{false, F} -> F
end,
case xqerl_test:assert_error(Res, "FOCH0001") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: FOCH0001 " ++ binary_to_list(F)};
{false, F} -> F
end
]
)
of
true -> {comment, "any-of"};
_ -> false
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'K-CodepointToStringFunc-15'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "string-to-codepoints(codepoints-to-string(31))",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "K-CodepointToStringFunc-15.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case
lists:any(
fun
({comment, _}) -> true;
(_) -> false
end,
[
case xqerl_test:assert_eq(Res, "31") of
true -> {comment, "Equal"};
{false, F} -> F
end,
case xqerl_test:assert_error(Res, "FOCH0001") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: FOCH0001 " ++ binary_to_list(F)};
{false, F} -> F
end
]
)
of
true -> {comment, "any-of"};
_ -> false
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'K-CodepointToStringFunc-16'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "codepoints-to-string(32) eq \" \"",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "K-CodepointToStringFunc-16.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_true(Res) of
true -> {comment, "Empty"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'K-CodepointToStringFunc-17'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "codepoints-to-string(27637) eq \"毵\"",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "K-CodepointToStringFunc-17.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_true(Res) of
true -> {comment, "Empty"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'K-CodepointToStringFunc-18'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "codepoints-to-string(55295) eq \"\"",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "K-CodepointToStringFunc-18.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_true(Res) of
true -> {comment, "Empty"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'K-CodepointToStringFunc-19'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "codepoints-to-string(55296)",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "K-CodepointToStringFunc-19.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "FOCH0001") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: FOCH0001 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'K-CodepointToStringFunc-20'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "codepoints-to-string(57343)",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "K-CodepointToStringFunc-20.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "FOCH0001") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: FOCH0001 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'K-CodepointToStringFunc-21'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "codepoints-to-string(57344) eq \"\"",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "K-CodepointToStringFunc-21.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_true(Res) of
true -> {comment, "Empty"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'K-CodepointToStringFunc-22'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "codepoints-to-string(61438) eq \"\"",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "K-CodepointToStringFunc-22.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_true(Res) of
true -> {comment, "Empty"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'K-CodepointToStringFunc-23'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "codepoints-to-string(65533) eq \"�\"",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "K-CodepointToStringFunc-23.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_true(Res) of
true -> {comment, "Empty"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'K-CodepointToStringFunc-24'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "codepoints-to-string(65534)",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "K-CodepointToStringFunc-24.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "FOCH0001") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: FOCH0001 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'K-CodepointToStringFunc-25'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "codepoints-to-string(65535)",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "K-CodepointToStringFunc-25.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "FOCH0001") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: FOCH0001 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'K-CodepointToStringFunc-26'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "codepoints-to-string(65536) eq \"𐀀\"",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "K-CodepointToStringFunc-26.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_true(Res) of
true -> {comment, "Empty"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'K-CodepointToStringFunc-27'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "codepoints-to-string(589823) eq \"\"",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "K-CodepointToStringFunc-27.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_true(Res) of
true -> {comment, "Empty"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'K-CodepointToStringFunc-28'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "codepoints-to-string(1114111) eq \"\"",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "K-CodepointToStringFunc-28.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_true(Res) of
true -> {comment, "Empty"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'K-CodepointToStringFunc-29'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "codepoints-to-string(1114112)",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "K-CodepointToStringFunc-29.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "FOCH0001") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: FOCH0001 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'cbcl-codepoints-to-string-001'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare function local:test($test as xs:integer) as xs:integer? { \n"
" if ($test = 1) then ( 0 ) else if ($test = 2) then ( 9 ) else if ($test = 3) then ( 13 ) else if ($test = 4) then ( 16 ) else () \n"
" }; \n"
" fn:codepoints-to-string( local:test(1) to 32 )",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "cbcl-codepoints-to-string-001.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "FOCH0001") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: FOCH0001 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'cbcl-codepoints-to-string-002'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare function local:test($test as xs:integer) as xs:integer? { \n"
" if ($test = 1) then ( 0 ) else if ($test = 2) then ( 9 ) else if ($test = 3) then ( 13 ) else if ($test = 4) then ( 16 ) else () \n"
" }; \n"
" fn:codepoints-to-string( local:test(2) to 32 )",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "cbcl-codepoints-to-string-002.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "FOCH0001") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: FOCH0001 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'cbcl-codepoints-to-string-003'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare function local:test($test as xs:integer) as xs:integer? { \n"
" if ($test = 1) then ( 0 ) else if ($test = 2) then ( 9 ) else if ($test = 3) then ( 13 )else if ($test = 4) then ( 16 ) else () \n"
" }; \n"
" fn:codepoints-to-string( local:test(3) to 32 )",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "cbcl-codepoints-to-string-003.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "FOCH0001") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: FOCH0001 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'cbcl-codepoints-to-string-004'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"declare function local:test($test as xs:integer) as xs:integer? { \n"
" if ($test = 1) then ( 0 ) else if ($test = 2) then ( 9 ) else if ($test = 3) then ( 13 ) else if ($test = 4) then ( 16 ) else () \n"
" }; \n"
" fn:codepoints-to-string( local:test(4) to 32 )",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "cbcl-codepoints-to-string-004.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "FOCH0001") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: FOCH0001 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'cbcl-codepoints-to-string-005'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "fn:codepoints-to-string( 65536 to 1114112 )",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "cbcl-codepoints-to-string-005.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "FOCH0001") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: FOCH0001 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'cbcl-codepoints-to-string-006'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "fn:codepoints-to-string( 55295 to 55297 )",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "cbcl-codepoints-to-string-006.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "FOCH0001") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: FOCH0001 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'cbcl-codepoints-to-string-007'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "fn:codepoints-to-string( 55296 to 57343 )",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "cbcl-codepoints-to-string-007.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "FOCH0001") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: FOCH0001 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'cbcl-codepoints-to-string-008'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "fn:codepoints-to-string( 65535 to 70000 )",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "cbcl-codepoints-to-string-008.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "FOCH0001") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: FOCH0001 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'cbcl-codepoints-to-string-009'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "fn:codepoints-to-string( 65530 to 70000 )",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "cbcl-codepoints-to-string-009.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "FOCH0001") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: FOCH0001 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'cbcl-codepoints-to-string-010'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "fn:boolean(fn:codepoints-to-string( 65 to 76 ))",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "cbcl-codepoints-to-string-010.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_true(Res) of
true -> {comment, "Empty"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'cbcl-codepoints-to-string-011'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "fn:boolean(fn:codepoints-to-string( 0 ))",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "cbcl-codepoints-to-string-011.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "FOCH0001") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: FOCH0001 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'cbcl-codepoints-to-string-012'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "fn:boolean(fn:codepoints-to-string( 999999999 ))",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "cbcl-codepoints-to-string-012.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "FOCH0001") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: FOCH0001 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'cbcl-codepoints-to-string-013'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "fn:boolean(fn:codepoints-to-string( 65 ))",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "cbcl-codepoints-to-string-013.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_true(Res) of
true -> {comment, "Empty"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'cbcl-codepoints-to-string-014'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "fn:boolean(fn:codepoints-to-string( () ))",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "cbcl-codepoints-to-string-014.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_false(Res) of
true -> {comment, "Empty"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'cbcl-codepoints-to-string-015'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"deep-equal( fn:string-to-codepoints(fn:codepoints-to-string(65536 to 66000)), 65536 to 66000 )",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "cbcl-codepoints-to-string-015.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_true(Res) of
true -> {comment, "Empty"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'cbcl-codepoints-to-string-016'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"deep-equal( fn:string-to-codepoints(fn:codepoints-to-string(65536 to 100000)), 65536 to 100000 )",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "cbcl-codepoints-to-string-016.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_true(Res) of
true -> {comment, "Empty"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'cbcl-codepoints-to-string-017'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "for $x in 32 to 64 return boolean(codepoints-to-string($x to $x + 10))",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "cbcl-codepoints-to-string-017.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case
xqerl_test:assert_string_value(
Res,
"true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true"
)
of
true -> {comment, "String correct"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'cbcl-codepoints-to-string-018'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"if(5 < exactly-one((1 to 10)[. div 2 = 5])) then codepoints-to-string(32 to exactly-one((1 to 100)[. div 2 = 40])) else ()",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "cbcl-codepoints-to-string-018.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case
xqerl_test:assert_string_value(
Res,
)
of
true -> {comment, "String correct"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'cbcl-codepoints-to-string-019'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "for $x in 65 to 75 return string-length(codepoints-to-string($x to $x+10))",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "cbcl-codepoints-to-string-019.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_string_value(Res, "11 11 11 11 11 11 11 11 11 11 11") of
true -> {comment, "String correct"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'cbcl-codepoints-to-string-020'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"for $x in 65 to 75 return boolean(codepoints-to-string($x[. mod 2 = 0] to ($x+9)[. mod 2 = 0]))",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "cbcl-codepoints-to-string-020.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case
xqerl_test:assert_string_value(
Res,
"false false false false false false false false false false false"
)
of
true -> {comment, "String correct"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'cbcl-codepoints-to-string-021'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"let $y := 65536*65536 return for $x in $y to $y+10 return codepoints-to-string(65 to $x)",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "cbcl-codepoints-to-string-021.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case
lists:any(
fun
({comment, _}) -> true;
(_) -> false
end,
[
case xqerl_test:assert_error(Res, "FOCH0001") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: FOCH0001 " ++ binary_to_list(F)};
{false, F} -> F
end,
case xqerl_test:assert_error(Res, "XPDY0130") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XPDY0130 " ++ binary_to_list(F)};
{false, F} -> F
end
]
)
of
true -> {comment, "any-of"};
_ -> false
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'cbcl-codepoints-to-string-022'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"let $y := 65536*65536 return for $x in $y to $y+10 return codepoints-to-string($x to $x+10)",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "cbcl-codepoints-to-string-022.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "FOCH0001") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: FOCH0001 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'cbcl-codepoints-to-string-023'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "for $x in 9 to 15 return codepoints-to-string($x to $x)",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "cbcl-codepoints-to-string-023.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "FOCH0001") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: FOCH0001 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'cbcl-codepoints-to-string-024'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "for $x in 13 to 15 return codepoints-to-string($x to $x)",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "cbcl-codepoints-to-string-024.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "FOCH0001") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: FOCH0001 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'cbcl-codepoints-to-string-025'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "for $x in 9 to 9 return codepoints-to-string($x to $x+1)",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "cbcl-codepoints-to-string-025.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case
xqerl_test:assert_eq(
Res,
"' \n"
"'"
)
of
true -> {comment, "Equal"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'cbcl-codepoints-to-string-026'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "for $x in 13 to 13 return codepoints-to-string($x to $x)",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "cbcl-codepoints-to-string-026.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_string_value(Res, "
") of
true -> {comment, "String correct"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'cbcl-codepoints-to-string-027'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "for $x in (13), $y in (13,9,10) return codepoints-to-string($x to $y)",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "cbcl-codepoints-to-string-027.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_string_value(Res, "
") of
true -> {comment, "String correct"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
|
486560c17a660ad8d6dc6f944a4c89ebb20d605f74a3e03aaa4531f368fdc956 | grin-compiler/grin | Lint.hs | # LANGUAGE ViewPatterns , LambdaCase , TupleSections , RecordWildCards , OverloadedStrings , ScopedTypeVariables #
{-# LANGUAGE MultiWayIf #-}
module Grin.ExtendedSyntax.Lint
( lint
, allWarnings
, noDDEWarnings
, Error(..)
) where
import Text.Printf
import Data.Functor.Foldable as Foldable
import qualified Data.Foldable
import Control.Comonad.Cofree
import Control.Monad.State
import Control.Monad.Writer hiding (Alt)
import qualified Control.Comonad.Trans.Cofree as CCTC
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Set (Set)
import qualified Data.Set as Set
import Data.List (findIndices)
import Lens.Micro.Platform
import Lens.Micro.Extra
import Text.PrettyPrint.ANSI.Leijen (Pretty, plain)
import Data.String
import Control.Comonad (extract)
import qualified Data.Vector as Vector
import Control.Applicative (liftA2)
import Data.Functor.Infix ((<$$>))
import Grin.ExtendedSyntax.Grin
import Grin.ExtendedSyntax.Pretty
import Grin.ExtendedSyntax.TypeEnv hiding (typeOfVal)
import Transformations.ExtendedSyntax.Util
import Debug.Trace
import Data.Maybe
-- TODO: remove redundant syntaxE s
{-
Linter is responsible for the semantical checks of the program.
-}
- AST shape ( syntax )
done - exp
- val
- recognise primitive functions
- scope checking ; requires monad ( full traversal )
- type checking ( using the type env )
- pattern checking
- node item checking ( no node in node )
- case :
- overlapping alternatives
- uncovered cases
- fully saturated alternatives
- fully saturated node creation eg ( CPair 1 2 ) vs ( CPair 1 )
- AST shape (syntax)
done - exp
- val
- recognise primitive functions
- scope checking ; requires monad (full traversal)
- type checking (using the type env)
- pattern checking
- node item checking (no node in node)
- case:
- overlapping alternatives
- uncovered cases
- fully saturated alternatives
- fully saturated node creation eg (CPair 1 2) vs (CPair 1)
-}
{-
question:
how to show errors?
- annotate expressions with the error using cofree
- annotate expressionf with id using cofree, then build error map referencing to expressions
-}
data Error = Error
{ before :: Bool
, message :: String
}
msg :: String -> Error
msg = Error False
beforeMsg :: String -> Error
beforeMsg = Error True
data ExpCtx
= ProgramCtx
| DefCtx
| ExpCtx
| SimpleExpCtx
| SEWithoutNodesCtx
| AltCtx
deriving Eq
data ValCtx
= ValCtx
| SimpleValCtx
deriving Eq
showExpCtx :: ExpCtx -> String
showExpCtx = \case
ProgramCtx -> "Program"
DefCtx -> "Def"
ExpCtx -> "Exp"
SimpleExpCtx -> "SimpleExp"
SEWithoutNodesCtx -> "SimpleExp without nodes"
AltCtx -> "Alt"
showValCtx :: ValCtx -> String
showValCtx = \case
ValCtx -> "Val"
SimpleValCtx -> "SimpleVal"
data Env
= Env
{ envNextId :: Int
, envVars :: Map Name Int -- exp id
, envErrors :: Map Int [Error]
, envDefinedNames :: Map Name DefRole
, envFunArity :: Map Name Int
, envWarningKinds :: [WarningKind] -- Allowed warning kinds
}
emptyEnv = Env
{ envNextId = 0
, envVars = mempty
, envErrors = mempty
, envDefinedNames = mempty
, envFunArity = mempty
, envWarningKinds = []
}
type Lint = State Env
type Check = WriterT [Error] Lint
type TypedExp = Cofree ExpF (Maybe Type)
expId :: Lint Int
expId = gets envNextId
nextId :: Lint ()
nextId = modify' $ \env@Env{..} -> env {envNextId = succ envNextId}
{-
TODO:
type check
-}
data WarningKind
= Syntax
| Semantics
| DDE
deriving (Enum, Eq, Ord, Show)
allWarnings :: [WarningKind]
allWarnings = [Syntax .. DDE]
noDDEWarnings :: [WarningKind]
noDDEWarnings = [Syntax, Semantics]
warning :: WarningKind -> [Error] -> Check ()
warning w m = do
ws <- gets envWarningKinds
when (w `elem` ws) $
tell m
syntaxVal :: ValCtx -> Val -> Check Bool
syntaxVal ctx = \case
Lit{} -> pure True
Var{} -> pure True
Undefined (T_NodeSet{})
| ctx == ValCtx -> pure True
_ | ctx == ValCtx -> pure True
_ -> warning Syntax [msg $ "Syntax error - expected " ++ showValCtx ctx] >> pure False
syntaxVal_ :: ValCtx -> Val -> Check ()
syntaxVal_ = void <$$> syntaxVal
ConstTagNode Tag [ SimpleVal ] -- complete node ( constant tag ) ; HIGH level
VarTagNode Name [ SimpleVal ] -- complete node ( variable tag )
ValTag Tag
Unit -- HIGH level
Lit Lit -- HIGH level
Var Name -- HIGH level
ConstTagNode Tag [SimpleVal] -- complete node (constant tag) ; HIGH level GRIN
VarTagNode Name [SimpleVal] -- complete node (variable tag)
ValTag Tag
Unit -- HIGH level GRIN
Lit Lit -- HIGH level GRIN
Var Name -- HIGH level GRIN
-}
syntaxExp :: ExpCtx -> ExpCtx -> Check ()
syntaxExp expected given | given == expected = pure ()
syntaxExp ExpCtx SimpleExpCtx = pure ()
syntaxExp SimpleExpCtx SEWithoutNodesCtx = pure ()
syntaxExp ExpCtx SEWithoutNodesCtx = pure ()
syntaxExp expected _ = warning Syntax [msg $ "Syntax error - expected " ++ showExpCtx expected]
checkNameDef :: DefRole -> Name -> Check ()
checkNameDef role name = do
defined <- state $ \env@Env{..} ->
( Map.member name envDefinedNames
, env {envDefinedNames = Map.insert name role envDefinedNames}
)
when defined $ do
warning Semantics [msg $ printf "multiple defintion of %s" name]
-- TODO: state -> gets
checkNameUse :: Name -> Check ()
checkNameUse name = do
defined <- state $ \env@Env{..} -> (Map.member name envDefinedNames, env)
unless defined $ do
warning Syntax [msg $ printf "undefined variable: %s" name]
checkVarScopeM :: ExpF a -> Check ()
checkVarScopeM exp = do
case exp of
DefF _ _ _ -> pure () -- Function definitions are already registered
_ -> mapM_ (uncurry checkNameDef) $ foldNameDefExpF (\r n -> [(r,n)]) exp
mapM_ checkNameUse $ foldNameUseExpF (:[]) exp
plainShow :: (Pretty p) => p -> String
plainShow = show . plain . pretty
unionSType :: SimpleType -> SimpleType -> Maybe SimpleType
unionSType (T_Location l1) (T_Location l2) = Just $ T_Location (l1 ++ l2)
unionSType T_Dead t = Just t
unionSType t T_Dead = Just t
unionSType t1 t2
| t1 == t2 = Just t1
| otherwise = Nothing
unionType :: Type -> Type -> Maybe Type
unionType (T_SimpleType t1) (T_SimpleType t2) = T_SimpleType <$> unionSType t1 t2
unionType (T_NodeSet ns1) (T_NodeSet ns2) =
fmap T_NodeSet
$ sequenceA
$ Map.map (fmap Vector.fromList . sequenceA)
$ Map.unionWith (zipWith (join <$$> liftA2 unionSType)) (Map.map (map Just . Vector.toList) ns1) (Map.map (map Just . Vector.toList) ns2)
unionType _ _ = Nothing
annotate :: TypeEnv -> Exp -> TypedExp
annotate te = cata builder where
builder :: ExpF TypedExp -> TypedExp
builder = \case
ProgramF exts defs -> Nothing :< ProgramF exts defs
DefF n ps body -> (te ^? function . at n . _Just . _1) :< DefF n ps body
SReturnF val -> mTypeOfValTE te val :< SReturnF val
SStoreF val -> Nothing :< SStoreF val -- Store returns a location type that is associated in its binded variable
SUpdateF name val -> Just unit_t :< SUpdateF name val
SFetchF var ->
(do locs <- mTypeOfValTE te (Var var) ^? _Just . _T_SimpleType . _T_Location
let (n:ns) = catMaybes $ map (\l -> te ^? location . at l . _Just . to T_NodeSet) locs
foldM unionType n ns
)
:< SFetchF var -- Fetch returns a value based on its arguments that is associated in its binded variable
SAppF name params -> (te ^? function . at name . _Just . _1) :< SAppF name params
AltF cpat n body -> extract body :< AltF cpat n body
ECaseF var alts ->
(do case catMaybes $ map extract alts of
[] -> Nothing
(t:ts) -> foldM unionType t ts)
:< ECaseF var alts
EBindF lhs pat rhs -> extract rhs :< EBindF lhs pat rhs
SBlockF body -> extract body :< SBlockF body
noAnnotation :: Exp -> TypedExp
noAnnotation = cata (Nothing :<)
check :: ExpF (ExpCtx, TypedExp) -> Check () -> Lint (CCTC.CofreeF ExpF Int (ExpCtx, TypedExp))
check exp nodeCheckM = do
idx <- expId
errors <- execWriterT (nodeCheckM >> checkVarScopeM exp)
unless (null errors) $ do
modify' $ \env@Env{..} -> env {envErrors = Map.insert idx errors envErrors}
nextId
pure (idx CCTC.:< exp )
lint :: [WarningKind] -> Maybe TypeEnv -> Exp -> (Cofree ExpF Int, Map Int [Error])
lint warningKinds mTypeEnv exp@(Program exts _) =
fmap envErrors $ flip runState (emptyEnv { envWarningKinds = warningKinds }) $ do
forM_ exts $ \External{..} -> do
modify' $ \env@Env{..} -> env { envDefinedNames = Map.insert eName FunName envDefinedNames }
cata functionNames exp
anaM builder (ProgramCtx, maybe noAnnotation annotate mTypeEnv exp)
where
functionNames :: ExpF (Lint ()) -> Lint ()
functionNames = \case
ProgramF exts defs -> sequence_ defs
DefF name args body -> do
modify' $ \env@Env{..} -> env
{ envDefinedNames = Map.insert name FunName envDefinedNames
, envFunArity = Map.insert name (length args) envFunArity
}
forM_ args $ \p -> modify' $ \env@Env{..} -> env { envDefinedNames = Map.insert p FunParam envDefinedNames }
body
rest -> pure ()
builder :: (ExpCtx, TypedExp) -> Lint (CCTC.CofreeF ExpF Int (ExpCtx, TypedExp))
builder (ctx, e) = case e of
(_ :< ProgramF{}) -> checkWithChild DefCtx $ do
syntaxE ProgramCtx
(_ :< DefF name args _) -> checkWithChild ExpCtx $ do
syntaxE DefCtx
-- Exp
-- The result Fetch should be bound to a variable to make DDE simpler
(_ :< EBindF leftExp bPat rightExp) -> do
-- TODO: is this really needed?
let lhsCtx = if isn't _OnlyVarPat bPat then SEWithoutNodesCtx else SimpleExpCtx
check (EBindF (lhsCtx, leftExp) bPat (ExpCtx, rightExp)) $ do
syntaxE ExpCtx
-- QUESTION: Is this needed wit hthe new syntax? Undefined introduction is still an open question.
when (isFetchF leftExp && isn't _OnlyVarPat bPat) (warning DDE [msg $ "The result of Fetch can only be bound to a variable: " ++ plainShow bPat])
when (isn't _OnlyVarPat bPat) $ do
forM_ mTypeEnv $ \typeEnv -> do
fromMaybe (pure ()) $ case bPat of
AsPat tag fields v -> do -- Maybe
expectedPatType <- normalizeType <$> mTypeOfValTE typeEnv (ConstTagNode tag fields)
lhsType <- normalizeType <$> extract leftExp
NOTE : This can still give false positive errors , because bottom - up typing can only approximate the result of HPT .
when (sameType expectedPatType lhsType == Just False) $ do
warning Semantics $ [beforeMsg $ unwords
["Invalid pattern match for", plainShow bPat ++ "." , "Expected pattern of type:", plainShow expectedPatType ++ ",", "but got:", plainShow lhsType]]
(_ :< ECaseF scrut alts0) -> checkWithChild AltCtx $ do
syntaxE SEWithoutNodesCtx
let alts = getF <$> alts0
-- Overlapping node alternatives
let tagOccurences =
Map.unionsWith (+) $
map (`Map.singleton` 1) $
concatMap (^.. _AltFCPat . _CPatNodeTag) alts
forM_ (Map.keys $ Map.filter (>1) tagOccurences) $ \(tag :: Tag) ->
warning Semantics [beforeMsg $ printf "case has overlapping node alternatives %s" (plainShow tag)]
-- Overlapping literal alternatives
let literalOccurences =
Map.unionsWith (+) $
map (`Map.singleton` 1) $
concatMap (^.. _AltFCPat . _CPatLit) alts
forM_ (Map.keys $ Map.filter (>1) literalOccurences) $ \(lit :: Lit) ->
warning Semantics [beforeMsg $ printf "case has overlapping literal alternatives %s" (plainShow lit)]
let noOfDefaults = length $ findIndices (has (_AltFCPat . _CPatDefault)) alts
More than one default
when (noOfDefaults > 1) $ do
warning Semantics [beforeMsg $ "case has more than one default alternatives"]
forM_ mTypeEnv $ \typeEnv -> do
-- Case variable has a location type
let mSt = typeEnv ^? variable . at scrut . _Just . _T_SimpleType
case mSt of
Just st
| has _T_Location st || has _T_String st || has _T_Float st
-> warning Semantics [beforeMsg $ printf "case variable %s has non-supported pattern match type: %s" scrut (plainShow st)]
TODO
-- Non-covered alternatives
when (noOfDefaults == 0) $ do
let mTags = typeEnv ^? variable . at scrut . _Just . _T_NodeSet . to Map.keys
case mTags of
Just tags -> do
forM_ tags $ \tag -> when (Map.notMember tag tagOccurences) $ do
warning Semantics [beforeMsg $ printf "case has non-covered alternative %s" (plainShow tag)]
TODO
-- Simple Exp
(_ :< SAppF name args) -> checkWithChild ctx $ do
syntaxE SEWithoutNodesCtx
-- Test existence of the function.
Env{..} <- get
when (not $ isExternalName exts name) $
case Map.lookup name envDefinedNames of
(Just FunName) -> pure ()
(Just _) -> warning Syntax [msg $ printf "non-function in function call: %s" name]
Nothing -> warning Syntax [msg $ printf "non-defined function is called: %s" name]
-- Non saturated function call
forM_ (Map.lookup name envFunArity) $ \n -> when (n /= length args) $ do
warning Syntax [msg $ printf "non-saturated function call: %s" name]
-- Only simple values should be returned,
-- unless the returned value is bound to a variable.
-- In that case the Return node is a left-hand side of a binding,
which means it is inside a SimpleExpCtx .
This is becuase only binding left - hand sides can be in SimpleExpCtx .
(_ :< SReturnF val) -> checkWithChild ctx $ do
(onlySimpleVals,errs) <- censorListen $ syntaxVal SimpleValCtx val
let hasNoNodes = val == Unit || onlySimpleVals
case ctx of
-- last expression in a binding sequence or a single, standalone expression
ExpCtx | hasNoNodes -> syntaxE SEWithoutNodesCtx
| otherwise -> warning DDE [msg $ "Last return expressions can only return non-node values: " ++ plainShow (SReturn val)]
lhs of a binding
SimpleExpCtx | hasNoNodes -> syntaxE SEWithoutNodesCtx
lhs of a bidning where the LPat is not a variable
SEWithoutNodesCtx | hasNoNodes -> syntaxE SEWithoutNodesCtx
_ -> syntaxE SimpleExpCtx
(_ :< SStoreF arg) -> checkWithChild ctx $ do
syntaxE SEWithoutNodesCtx
forM_ mTypeEnv $ \typeEnv -> do
-- Store has given a primitive type
let mTags = typeEnv ^? variable . at arg . _Just . _T_NodeSet . to Map.keys
mSt = typeEnv ^? variable . at arg . _Just . _T_SimpleType
case (mTags,mSt) of
(Just tags,_) -> pure ()
(_, Just st) | st /= T_Dead ->
warning Semantics [msg $ printf "store has given a primitive value: %s :: %s" (plainShow arg) (plainShow st)]
_ -> pure ()
(_ :< SFetchF name) -> checkWithChild ctx $ do
syntaxE SEWithoutNodesCtx
-- Non location parameter for fetch
forM_ mTypeEnv $ \typeEnv -> if
| Just _ <- typeEnv ^? variable . at name . _Just . _T_SimpleType . _T_Location
-> pure ()
| Just st <- typeEnv ^? variable . at name . _Just . _T_SimpleType
-> when (st /= T_Dead) $ warning Semantics [msg $ printf "the parameter of fetch is a primitive type: %s :: %s" (plainShow name) (plainShow st)]
| Just ns <- typeEnv ^? variable . at name . _Just . _T_NodeSet
-> warning Semantics [msg $ printf "the parameter of fetch is a node type: %s" (plainShow name)]
| otherwise -> pure ()
(_ :< SUpdateF name arg) -> checkWithChild ctx $ do
syntaxE SEWithoutNodesCtx
-- Non location parameter for update
forM_ mTypeEnv $ \typeEnv -> if
| Just _ <- typeEnv ^? variable . at name . _Just . _T_SimpleType . _T_Location
-> pure ()
| Just st <- typeEnv ^? variable . at name . _Just . _T_SimpleType
-> when (st /= T_Dead) $ warning Semantics [msg $ printf "the parameter of update is a primitive type: %s :: %s" (plainShow name) (plainShow st)]
| Just ns <- typeEnv ^? variable . at name . _Just . _T_NodeSet
-> warning Semantics [msg $ printf "the parameter of update is a node type: %s" (plainShow name)]
| otherwise -> pure ()
forM_ mTypeEnv $ \typeEnv -> do
-- Update has given a primitive type
let mTags = typeEnv ^? variable . at arg . _Just . _T_NodeSet . to Map.keys
mSt = typeEnv ^? variable . at arg . _Just . _T_SimpleType
case (mTags,mSt) of
(Just tags,_) -> pure ()
(_, Just st) | st /= T_Dead ->
warning Semantics [msg $ printf "update has given a primitive value: %s :: %s" (plainShow arg) (plainShow st)]
_ -> pure ()
(_ :< SBlockF{}) -> checkWithChild ExpCtx $ do
syntaxE SEWithoutNodesCtx
-- Alt
-- TODO: Define some checks for the alt name.
-- For example, that it is a fresh variable.
(_ :< AltF cpat n _) -> checkWithChild ExpCtx $ do
syntaxE AltCtx
where
syntaxE = syntaxExp ctx
checkWithChild childCtx m = check ((childCtx,) <$> (getF e)) m
getF (_ :< f) = f
isFetchF (getF -> SFetchF{}) = True
isFetchF _ = False
-- Collects the side-effects without appending it to the output.
censorListen :: (Monoid w, Monad m) => WriterT w m a -> WriterT w m (a,w)
censorListen = censor (const mempty) . listen
| null | https://raw.githubusercontent.com/grin-compiler/grin/44ac2958810ecee969c8028d2d2a082d47fba51b/grin/src/Grin/ExtendedSyntax/Lint.hs | haskell | # LANGUAGE MultiWayIf #
TODO: remove redundant syntaxE s
Linter is responsible for the semantical checks of the program.
question:
how to show errors?
- annotate expressions with the error using cofree
- annotate expressionf with id using cofree, then build error map referencing to expressions
exp id
Allowed warning kinds
TODO:
type check
complete node ( constant tag ) ; HIGH level
complete node ( variable tag )
HIGH level
HIGH level
HIGH level
complete node (constant tag) ; HIGH level GRIN
complete node (variable tag)
HIGH level GRIN
HIGH level GRIN
HIGH level GRIN
TODO: state -> gets
Function definitions are already registered
Store returns a location type that is associated in its binded variable
Fetch returns a value based on its arguments that is associated in its binded variable
Exp
The result Fetch should be bound to a variable to make DDE simpler
TODO: is this really needed?
QUESTION: Is this needed wit hthe new syntax? Undefined introduction is still an open question.
Maybe
Overlapping node alternatives
Overlapping literal alternatives
Case variable has a location type
Non-covered alternatives
Simple Exp
Test existence of the function.
Non saturated function call
Only simple values should be returned,
unless the returned value is bound to a variable.
In that case the Return node is a left-hand side of a binding,
last expression in a binding sequence or a single, standalone expression
Store has given a primitive type
Non location parameter for fetch
Non location parameter for update
Update has given a primitive type
Alt
TODO: Define some checks for the alt name.
For example, that it is a fresh variable.
Collects the side-effects without appending it to the output. | # LANGUAGE ViewPatterns , LambdaCase , TupleSections , RecordWildCards , OverloadedStrings , ScopedTypeVariables #
module Grin.ExtendedSyntax.Lint
( lint
, allWarnings
, noDDEWarnings
, Error(..)
) where
import Text.Printf
import Data.Functor.Foldable as Foldable
import qualified Data.Foldable
import Control.Comonad.Cofree
import Control.Monad.State
import Control.Monad.Writer hiding (Alt)
import qualified Control.Comonad.Trans.Cofree as CCTC
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Set (Set)
import qualified Data.Set as Set
import Data.List (findIndices)
import Lens.Micro.Platform
import Lens.Micro.Extra
import Text.PrettyPrint.ANSI.Leijen (Pretty, plain)
import Data.String
import Control.Comonad (extract)
import qualified Data.Vector as Vector
import Control.Applicative (liftA2)
import Data.Functor.Infix ((<$$>))
import Grin.ExtendedSyntax.Grin
import Grin.ExtendedSyntax.Pretty
import Grin.ExtendedSyntax.TypeEnv hiding (typeOfVal)
import Transformations.ExtendedSyntax.Util
import Debug.Trace
import Data.Maybe
- AST shape ( syntax )
done - exp
- val
- recognise primitive functions
- scope checking ; requires monad ( full traversal )
- type checking ( using the type env )
- pattern checking
- node item checking ( no node in node )
- case :
- overlapping alternatives
- uncovered cases
- fully saturated alternatives
- fully saturated node creation eg ( CPair 1 2 ) vs ( CPair 1 )
- AST shape (syntax)
done - exp
- val
- recognise primitive functions
- scope checking ; requires monad (full traversal)
- type checking (using the type env)
- pattern checking
- node item checking (no node in node)
- case:
- overlapping alternatives
- uncovered cases
- fully saturated alternatives
- fully saturated node creation eg (CPair 1 2) vs (CPair 1)
-}
data Error = Error
{ before :: Bool
, message :: String
}
msg :: String -> Error
msg = Error False
beforeMsg :: String -> Error
beforeMsg = Error True
data ExpCtx
= ProgramCtx
| DefCtx
| ExpCtx
| SimpleExpCtx
| SEWithoutNodesCtx
| AltCtx
deriving Eq
data ValCtx
= ValCtx
| SimpleValCtx
deriving Eq
showExpCtx :: ExpCtx -> String
showExpCtx = \case
ProgramCtx -> "Program"
DefCtx -> "Def"
ExpCtx -> "Exp"
SimpleExpCtx -> "SimpleExp"
SEWithoutNodesCtx -> "SimpleExp without nodes"
AltCtx -> "Alt"
showValCtx :: ValCtx -> String
showValCtx = \case
ValCtx -> "Val"
SimpleValCtx -> "SimpleVal"
data Env
= Env
{ envNextId :: Int
, envErrors :: Map Int [Error]
, envDefinedNames :: Map Name DefRole
, envFunArity :: Map Name Int
}
emptyEnv = Env
{ envNextId = 0
, envVars = mempty
, envErrors = mempty
, envDefinedNames = mempty
, envFunArity = mempty
, envWarningKinds = []
}
type Lint = State Env
type Check = WriterT [Error] Lint
type TypedExp = Cofree ExpF (Maybe Type)
expId :: Lint Int
expId = gets envNextId
nextId :: Lint ()
nextId = modify' $ \env@Env{..} -> env {envNextId = succ envNextId}
data WarningKind
= Syntax
| Semantics
| DDE
deriving (Enum, Eq, Ord, Show)
allWarnings :: [WarningKind]
allWarnings = [Syntax .. DDE]
noDDEWarnings :: [WarningKind]
noDDEWarnings = [Syntax, Semantics]
warning :: WarningKind -> [Error] -> Check ()
warning w m = do
ws <- gets envWarningKinds
when (w `elem` ws) $
tell m
syntaxVal :: ValCtx -> Val -> Check Bool
syntaxVal ctx = \case
Lit{} -> pure True
Var{} -> pure True
Undefined (T_NodeSet{})
| ctx == ValCtx -> pure True
_ | ctx == ValCtx -> pure True
_ -> warning Syntax [msg $ "Syntax error - expected " ++ showValCtx ctx] >> pure False
syntaxVal_ :: ValCtx -> Val -> Check ()
syntaxVal_ = void <$$> syntaxVal
ValTag Tag
ValTag Tag
-}
syntaxExp :: ExpCtx -> ExpCtx -> Check ()
syntaxExp expected given | given == expected = pure ()
syntaxExp ExpCtx SimpleExpCtx = pure ()
syntaxExp SimpleExpCtx SEWithoutNodesCtx = pure ()
syntaxExp ExpCtx SEWithoutNodesCtx = pure ()
syntaxExp expected _ = warning Syntax [msg $ "Syntax error - expected " ++ showExpCtx expected]
checkNameDef :: DefRole -> Name -> Check ()
checkNameDef role name = do
defined <- state $ \env@Env{..} ->
( Map.member name envDefinedNames
, env {envDefinedNames = Map.insert name role envDefinedNames}
)
when defined $ do
warning Semantics [msg $ printf "multiple defintion of %s" name]
checkNameUse :: Name -> Check ()
checkNameUse name = do
defined <- state $ \env@Env{..} -> (Map.member name envDefinedNames, env)
unless defined $ do
warning Syntax [msg $ printf "undefined variable: %s" name]
checkVarScopeM :: ExpF a -> Check ()
checkVarScopeM exp = do
case exp of
_ -> mapM_ (uncurry checkNameDef) $ foldNameDefExpF (\r n -> [(r,n)]) exp
mapM_ checkNameUse $ foldNameUseExpF (:[]) exp
plainShow :: (Pretty p) => p -> String
plainShow = show . plain . pretty
unionSType :: SimpleType -> SimpleType -> Maybe SimpleType
unionSType (T_Location l1) (T_Location l2) = Just $ T_Location (l1 ++ l2)
unionSType T_Dead t = Just t
unionSType t T_Dead = Just t
unionSType t1 t2
| t1 == t2 = Just t1
| otherwise = Nothing
unionType :: Type -> Type -> Maybe Type
unionType (T_SimpleType t1) (T_SimpleType t2) = T_SimpleType <$> unionSType t1 t2
unionType (T_NodeSet ns1) (T_NodeSet ns2) =
fmap T_NodeSet
$ sequenceA
$ Map.map (fmap Vector.fromList . sequenceA)
$ Map.unionWith (zipWith (join <$$> liftA2 unionSType)) (Map.map (map Just . Vector.toList) ns1) (Map.map (map Just . Vector.toList) ns2)
unionType _ _ = Nothing
annotate :: TypeEnv -> Exp -> TypedExp
annotate te = cata builder where
builder :: ExpF TypedExp -> TypedExp
builder = \case
ProgramF exts defs -> Nothing :< ProgramF exts defs
DefF n ps body -> (te ^? function . at n . _Just . _1) :< DefF n ps body
SReturnF val -> mTypeOfValTE te val :< SReturnF val
SUpdateF name val -> Just unit_t :< SUpdateF name val
SFetchF var ->
(do locs <- mTypeOfValTE te (Var var) ^? _Just . _T_SimpleType . _T_Location
let (n:ns) = catMaybes $ map (\l -> te ^? location . at l . _Just . to T_NodeSet) locs
foldM unionType n ns
)
SAppF name params -> (te ^? function . at name . _Just . _1) :< SAppF name params
AltF cpat n body -> extract body :< AltF cpat n body
ECaseF var alts ->
(do case catMaybes $ map extract alts of
[] -> Nothing
(t:ts) -> foldM unionType t ts)
:< ECaseF var alts
EBindF lhs pat rhs -> extract rhs :< EBindF lhs pat rhs
SBlockF body -> extract body :< SBlockF body
noAnnotation :: Exp -> TypedExp
noAnnotation = cata (Nothing :<)
check :: ExpF (ExpCtx, TypedExp) -> Check () -> Lint (CCTC.CofreeF ExpF Int (ExpCtx, TypedExp))
check exp nodeCheckM = do
idx <- expId
errors <- execWriterT (nodeCheckM >> checkVarScopeM exp)
unless (null errors) $ do
modify' $ \env@Env{..} -> env {envErrors = Map.insert idx errors envErrors}
nextId
pure (idx CCTC.:< exp )
lint :: [WarningKind] -> Maybe TypeEnv -> Exp -> (Cofree ExpF Int, Map Int [Error])
lint warningKinds mTypeEnv exp@(Program exts _) =
fmap envErrors $ flip runState (emptyEnv { envWarningKinds = warningKinds }) $ do
forM_ exts $ \External{..} -> do
modify' $ \env@Env{..} -> env { envDefinedNames = Map.insert eName FunName envDefinedNames }
cata functionNames exp
anaM builder (ProgramCtx, maybe noAnnotation annotate mTypeEnv exp)
where
functionNames :: ExpF (Lint ()) -> Lint ()
functionNames = \case
ProgramF exts defs -> sequence_ defs
DefF name args body -> do
modify' $ \env@Env{..} -> env
{ envDefinedNames = Map.insert name FunName envDefinedNames
, envFunArity = Map.insert name (length args) envFunArity
}
forM_ args $ \p -> modify' $ \env@Env{..} -> env { envDefinedNames = Map.insert p FunParam envDefinedNames }
body
rest -> pure ()
builder :: (ExpCtx, TypedExp) -> Lint (CCTC.CofreeF ExpF Int (ExpCtx, TypedExp))
builder (ctx, e) = case e of
(_ :< ProgramF{}) -> checkWithChild DefCtx $ do
syntaxE ProgramCtx
(_ :< DefF name args _) -> checkWithChild ExpCtx $ do
syntaxE DefCtx
(_ :< EBindF leftExp bPat rightExp) -> do
let lhsCtx = if isn't _OnlyVarPat bPat then SEWithoutNodesCtx else SimpleExpCtx
check (EBindF (lhsCtx, leftExp) bPat (ExpCtx, rightExp)) $ do
syntaxE ExpCtx
when (isFetchF leftExp && isn't _OnlyVarPat bPat) (warning DDE [msg $ "The result of Fetch can only be bound to a variable: " ++ plainShow bPat])
when (isn't _OnlyVarPat bPat) $ do
forM_ mTypeEnv $ \typeEnv -> do
fromMaybe (pure ()) $ case bPat of
expectedPatType <- normalizeType <$> mTypeOfValTE typeEnv (ConstTagNode tag fields)
lhsType <- normalizeType <$> extract leftExp
NOTE : This can still give false positive errors , because bottom - up typing can only approximate the result of HPT .
when (sameType expectedPatType lhsType == Just False) $ do
warning Semantics $ [beforeMsg $ unwords
["Invalid pattern match for", plainShow bPat ++ "." , "Expected pattern of type:", plainShow expectedPatType ++ ",", "but got:", plainShow lhsType]]
(_ :< ECaseF scrut alts0) -> checkWithChild AltCtx $ do
syntaxE SEWithoutNodesCtx
let alts = getF <$> alts0
let tagOccurences =
Map.unionsWith (+) $
map (`Map.singleton` 1) $
concatMap (^.. _AltFCPat . _CPatNodeTag) alts
forM_ (Map.keys $ Map.filter (>1) tagOccurences) $ \(tag :: Tag) ->
warning Semantics [beforeMsg $ printf "case has overlapping node alternatives %s" (plainShow tag)]
let literalOccurences =
Map.unionsWith (+) $
map (`Map.singleton` 1) $
concatMap (^.. _AltFCPat . _CPatLit) alts
forM_ (Map.keys $ Map.filter (>1) literalOccurences) $ \(lit :: Lit) ->
warning Semantics [beforeMsg $ printf "case has overlapping literal alternatives %s" (plainShow lit)]
let noOfDefaults = length $ findIndices (has (_AltFCPat . _CPatDefault)) alts
More than one default
when (noOfDefaults > 1) $ do
warning Semantics [beforeMsg $ "case has more than one default alternatives"]
forM_ mTypeEnv $ \typeEnv -> do
let mSt = typeEnv ^? variable . at scrut . _Just . _T_SimpleType
case mSt of
Just st
| has _T_Location st || has _T_String st || has _T_Float st
-> warning Semantics [beforeMsg $ printf "case variable %s has non-supported pattern match type: %s" scrut (plainShow st)]
TODO
when (noOfDefaults == 0) $ do
let mTags = typeEnv ^? variable . at scrut . _Just . _T_NodeSet . to Map.keys
case mTags of
Just tags -> do
forM_ tags $ \tag -> when (Map.notMember tag tagOccurences) $ do
warning Semantics [beforeMsg $ printf "case has non-covered alternative %s" (plainShow tag)]
TODO
(_ :< SAppF name args) -> checkWithChild ctx $ do
syntaxE SEWithoutNodesCtx
Env{..} <- get
when (not $ isExternalName exts name) $
case Map.lookup name envDefinedNames of
(Just FunName) -> pure ()
(Just _) -> warning Syntax [msg $ printf "non-function in function call: %s" name]
Nothing -> warning Syntax [msg $ printf "non-defined function is called: %s" name]
forM_ (Map.lookup name envFunArity) $ \n -> when (n /= length args) $ do
warning Syntax [msg $ printf "non-saturated function call: %s" name]
which means it is inside a SimpleExpCtx .
This is becuase only binding left - hand sides can be in SimpleExpCtx .
(_ :< SReturnF val) -> checkWithChild ctx $ do
(onlySimpleVals,errs) <- censorListen $ syntaxVal SimpleValCtx val
let hasNoNodes = val == Unit || onlySimpleVals
case ctx of
ExpCtx | hasNoNodes -> syntaxE SEWithoutNodesCtx
| otherwise -> warning DDE [msg $ "Last return expressions can only return non-node values: " ++ plainShow (SReturn val)]
lhs of a binding
SimpleExpCtx | hasNoNodes -> syntaxE SEWithoutNodesCtx
lhs of a bidning where the LPat is not a variable
SEWithoutNodesCtx | hasNoNodes -> syntaxE SEWithoutNodesCtx
_ -> syntaxE SimpleExpCtx
(_ :< SStoreF arg) -> checkWithChild ctx $ do
syntaxE SEWithoutNodesCtx
forM_ mTypeEnv $ \typeEnv -> do
let mTags = typeEnv ^? variable . at arg . _Just . _T_NodeSet . to Map.keys
mSt = typeEnv ^? variable . at arg . _Just . _T_SimpleType
case (mTags,mSt) of
(Just tags,_) -> pure ()
(_, Just st) | st /= T_Dead ->
warning Semantics [msg $ printf "store has given a primitive value: %s :: %s" (plainShow arg) (plainShow st)]
_ -> pure ()
(_ :< SFetchF name) -> checkWithChild ctx $ do
syntaxE SEWithoutNodesCtx
forM_ mTypeEnv $ \typeEnv -> if
| Just _ <- typeEnv ^? variable . at name . _Just . _T_SimpleType . _T_Location
-> pure ()
| Just st <- typeEnv ^? variable . at name . _Just . _T_SimpleType
-> when (st /= T_Dead) $ warning Semantics [msg $ printf "the parameter of fetch is a primitive type: %s :: %s" (plainShow name) (plainShow st)]
| Just ns <- typeEnv ^? variable . at name . _Just . _T_NodeSet
-> warning Semantics [msg $ printf "the parameter of fetch is a node type: %s" (plainShow name)]
| otherwise -> pure ()
(_ :< SUpdateF name arg) -> checkWithChild ctx $ do
syntaxE SEWithoutNodesCtx
forM_ mTypeEnv $ \typeEnv -> if
| Just _ <- typeEnv ^? variable . at name . _Just . _T_SimpleType . _T_Location
-> pure ()
| Just st <- typeEnv ^? variable . at name . _Just . _T_SimpleType
-> when (st /= T_Dead) $ warning Semantics [msg $ printf "the parameter of update is a primitive type: %s :: %s" (plainShow name) (plainShow st)]
| Just ns <- typeEnv ^? variable . at name . _Just . _T_NodeSet
-> warning Semantics [msg $ printf "the parameter of update is a node type: %s" (plainShow name)]
| otherwise -> pure ()
forM_ mTypeEnv $ \typeEnv -> do
let mTags = typeEnv ^? variable . at arg . _Just . _T_NodeSet . to Map.keys
mSt = typeEnv ^? variable . at arg . _Just . _T_SimpleType
case (mTags,mSt) of
(Just tags,_) -> pure ()
(_, Just st) | st /= T_Dead ->
warning Semantics [msg $ printf "update has given a primitive value: %s :: %s" (plainShow arg) (plainShow st)]
_ -> pure ()
(_ :< SBlockF{}) -> checkWithChild ExpCtx $ do
syntaxE SEWithoutNodesCtx
(_ :< AltF cpat n _) -> checkWithChild ExpCtx $ do
syntaxE AltCtx
where
syntaxE = syntaxExp ctx
checkWithChild childCtx m = check ((childCtx,) <$> (getF e)) m
getF (_ :< f) = f
isFetchF (getF -> SFetchF{}) = True
isFetchF _ = False
censorListen :: (Monoid w, Monad m) => WriterT w m a -> WriterT w m (a,w)
censorListen = censor (const mempty) . listen
|
4fa4e879dd1987a4f4e11bf872b5e6a3ad03877a559ee5ed93574138660fead4 | mpenet/flex | playground.clj | (ns playground
(:require [ring.adapter.jetty :as j]
[exoscale.ex :as ex]
[s-exp.flex.limit.aimd :as limit]
[s-exp.flex :as f]
[s-exp.flex.interceptor :as ix]
[s-exp.flex.middleware]
[exoscale.interceptor]))
;; (def tf (bound-fn* println))
;; (remove-tap tf)
;; (add-tap tf)
(defn ok-response [s]
{:status 200
:body (pr-str s)})
(defn rejected-response [s]
{:status 420
:body (format "Enhance your calm - %s" (ex-message s))})
(def limit (s-exp.flex.limit.aimd/make
{:initial-limit 10
:max-limit 20
:min-limit 1}))
(def limiter (f/limiter {:limit limit}))
(def ix (ix/interceptor {:limiter limiter}))
(defn interceptor-handler [request]
(exoscale.interceptor/execute
{:request request}
[{:error (fn [_ctx err]
(if (ex/type? err :s-exp.flex/rejected)
(rejected-response @limiter)
{:status 500
:body (str "boom -" err)}))
:leave :response}
#'ix
{:enter (fn [ctx]
(Thread/sleep (rand-int 1000))
(assoc ctx
:response
(ok-response @limiter)))}]))
(defn server+interceptor
[]
(j/run-jetty #'interceptor-handler
{:port 8080
:join? false}))
(def resp-time (atom 500))
(defn server+middleware []
(let [handler (s-exp.flex.middleware/with-limiter
(fn [_]
(Thread/sleep
1000 ; simulate stable
(max 1 (swap! resp-time inc)) ; simulate slowing down
( max 1 ( swap ! resp - time dec ) ) ; simulate faster resp times
)
(ok-response @limiter))
{:limiter limiter})]
(j/run-jetty (fn [request]
(ex/try+ (handler request)
(catch :s-exp.flex/rejected _
(rejected-response @limiter))))
{:port 8080
:join? false})))
(declare server)
(try (.stop server) (catch Exception _ :boom))
(def server (server+middleware))
| null | https://raw.githubusercontent.com/mpenet/flex/1a26ccc4c6aacd449bae7b6404802e0553445d59/dev/playground.clj | clojure | (def tf (bound-fn* println))
(remove-tap tf)
(add-tap tf)
simulate stable
simulate slowing down
simulate faster resp times | (ns playground
(:require [ring.adapter.jetty :as j]
[exoscale.ex :as ex]
[s-exp.flex.limit.aimd :as limit]
[s-exp.flex :as f]
[s-exp.flex.interceptor :as ix]
[s-exp.flex.middleware]
[exoscale.interceptor]))
(defn ok-response [s]
{:status 200
:body (pr-str s)})
(defn rejected-response [s]
{:status 420
:body (format "Enhance your calm - %s" (ex-message s))})
(def limit (s-exp.flex.limit.aimd/make
{:initial-limit 10
:max-limit 20
:min-limit 1}))
(def limiter (f/limiter {:limit limit}))
(def ix (ix/interceptor {:limiter limiter}))
(defn interceptor-handler [request]
(exoscale.interceptor/execute
{:request request}
[{:error (fn [_ctx err]
(if (ex/type? err :s-exp.flex/rejected)
(rejected-response @limiter)
{:status 500
:body (str "boom -" err)}))
:leave :response}
#'ix
{:enter (fn [ctx]
(Thread/sleep (rand-int 1000))
(assoc ctx
:response
(ok-response @limiter)))}]))
(defn server+interceptor
[]
(j/run-jetty #'interceptor-handler
{:port 8080
:join? false}))
(def resp-time (atom 500))
(defn server+middleware []
(let [handler (s-exp.flex.middleware/with-limiter
(fn [_]
(Thread/sleep
)
(ok-response @limiter))
{:limiter limiter})]
(j/run-jetty (fn [request]
(ex/try+ (handler request)
(catch :s-exp.flex/rejected _
(rejected-response @limiter))))
{:port 8080
:join? false})))
(declare server)
(try (.stop server) (catch Exception _ :boom))
(def server (server+middleware))
|
8d52e3ea7d7feea21dba2c5b4971b82a474bc41b93b34911522baa8797a57af4 | ocsigen/ocsigenserver | ocsigen_multipart.ml | This code is inspired by mimestring.ml from OcamlNet
Copyright ,
Modified for Ocsigen / Lwt by and
VVV Check wether we should support int64 for large files ?
open Lwt.Infix
module S = Ocsigen_lib.Netstring_pcre
let section = Lwt_log.Section.make "ocsigen:server:multipart"
exception Multipart_error of string
exception Ocsigen_upload_forbidden
let match_end result = snd (Pcre.get_substring_ofs result 0)
let cr_or_lf_re = S.regexp "[\013\n]"
let header_stripped_re =
S.regexp
"([^ \t\r\n:]+):[ \t]*((.*[^ \t\r\n])?([ \t\r]*\n[ \t](.*[^ \t\r\n])?)*)[ \t\r]*\n"
let header_unstripped_re = S.regexp "([^ \t\r\n:]+):([ \t]*.*\n([ \t].*\n)*)"
This much simpler expression returns the name and the unstripped
value .
value. *)
let empty_line_re = S.regexp "\013?\n"
let end_of_header_re = S.regexp "\n\013?\n"
let scan_header ?(downcase = true) ?(unfold = true) ?(strip = false) parstr
~start_pos ~end_pos
=
let header_re =
if unfold || strip then header_stripped_re else header_unstripped_re
in
let rec parse_header i l =
match S.string_match header_re parstr i with
| Some r ->
let i' = match_end r in
if i' > end_pos then raise (Multipart_error "Mimestring.scan_header");
let name =
if downcase
then String.lowercase_ascii (S.matched_group r 1 parstr)
else S.matched_group r 1 parstr
in
let value_with_crlf = S.matched_group r 2 parstr in
let value =
if unfold
then S.global_replace cr_or_lf_re "" value_with_crlf
else value_with_crlf
in
parse_header i' ((name, value) :: l)
| None -> (
(* The header must end with an empty line *)
match S.string_match empty_line_re parstr i with
| Some r' -> List.rev l, match_end r'
| None -> raise (Multipart_error "Mimestring.scan_header"))
in
parse_header start_pos []
let read_header ?downcase ?unfold ?strip s =
let rec find_end_of_header s =
Lwt.catch
(fun () ->
let b = Ocsigen_stream.current_buffer s in
(* Maybe the header is empty. In this case, there is an empty
line right at the beginning *)
match S.string_match empty_line_re b 0 with
| Some r -> Lwt.return (s, match_end r)
| None ->
(* Search for an empty line *)
Lwt.return
(s, match_end (snd (S.search_forward end_of_header_re b 0))))
(function
| Not_found -> (
Ocsigen_stream.enlarge_stream s >>= function
| Ocsigen_stream.Finished _ ->
Lwt.fail Ocsigen_stream.Stream_too_small
| Ocsigen_stream.Cont _ as s -> find_end_of_header s)
| e -> Lwt.fail e)
in
find_end_of_header s >>= fun (s, end_pos) ->
let b = Ocsigen_stream.current_buffer s in
let h, _ = scan_header ?downcase ?unfold ?strip b ~start_pos:0 ~end_pos in
Ocsigen_stream.skip s (Int64.of_int end_pos) >>= fun s -> Lwt.return (s, h)
let lf_re = S.regexp "[\n]"
let rec search_window s re start =
try
Lwt.return
(s, snd (S.search_forward re (Ocsigen_stream.current_buffer s) start))
with Not_found -> (
Ocsigen_stream.enlarge_stream s >>= function
| Ocsigen_stream.Finished _ -> Lwt.fail Ocsigen_stream.Stream_too_small
| Ocsigen_stream.Cont _ as s -> search_window s re start)
let search_end_of_line s k =
Search LF beginning at position k
Lwt.catch
(fun () ->
search_window s lf_re k >>= fun (s, x) -> Lwt.return (s, match_end x))
(function
| Not_found ->
Lwt.fail
(Multipart_error
"read_multipart_body: MIME boundary without line end")
| e -> Lwt.fail e)
let search_first_boundary ~boundary s =
(* Search boundary per regexp; return the position of the
character immediately following the boundary (on the same
line), or raise Not_found. *)
let re = S.regexp ("\n--" ^ Pcre.quote boundary) in
search_window s re 0 >>= fun (s, x) -> Lwt.return (s, match_end x)
let check_beginning_is_boundary ~boundary s =
let del = "--" ^ boundary in
let ldel = String.length del in
Ocsigen_stream.stream_want s (ldel + 2) >>= function
| Ocsigen_stream.Finished _ as str2 -> Lwt.return (str2, false, false)
| Ocsigen_stream.Cont (ss, _f) as str2 ->
let long = String.length ss in
let isdelim = long >= ldel && String.sub ss 0 ldel = del in
let islast = isdelim && String.sub ss ldel 2 = "--" in
Lwt.return (str2, isdelim, islast)
let rec parse_parts ~boundary ~decode_part s uses_crlf =
PRE : [ s ] is at the beginning of the next part . [ uses_crlf ] must
be true if CRLF is used as EOL sequence , and false if only LF is
used as EOL sequence .
be true if CRLF is used as EOL sequence, and false if only LF is
used as EOL sequence. *)
let delimiter = (if uses_crlf then "\r" else "") ^ "\n--" ^ boundary in
Ocsigen_stream.substream delimiter s >>= fun a ->
decode_part a >>= fun (y, s) ->
(* Now the position of [s] is at the beginning of the delimiter.
Check if there is a "--" after the delimiter (==> last part) *)
let l_delimiter = String.length delimiter in
Ocsigen_stream.next s >>= fun s ->
Ocsigen_stream.stream_want s (l_delimiter + 2) >>= fun s ->
let last_part =
match s with
| Ocsigen_stream.Finished _ -> false
| Ocsigen_stream.Cont (ss, _f) ->
let long = String.length ss in
long >= l_delimiter + 2
&& ss.[l_delimiter] = '-'
&& ss.[l_delimiter + 1] = '-'
in
if last_part
then Lwt.return [y]
else
search_end_of_line s 2 >>= fun (s, k) ->
(* [k]: Beginning of next part *)
Ocsigen_stream.skip s (Int64.of_int k) >>= fun s ->
parse_parts ~boundary ~decode_part s uses_crlf >>= fun l ->
Lwt.return (y :: l)
let read_multipart_body ~boundary ~decode_part s =
(* Check whether s directly begins with a boundary *)
check_beginning_is_boundary ~boundary s >>= fun (s, b, islast) ->
if islast
then Lwt.return []
else if b
then
Move to the beginning of the next line
search_end_of_line s 0 >>= fun (s, k_eol) ->
let uses_crlf = (Ocsigen_stream.current_buffer s).[k_eol - 2] = '\r' in
Ocsigen_stream.skip s (Int64.of_int k_eol) >>= fun s ->
Begin with first part :
parse_parts ~boundary ~decode_part s uses_crlf
else
Look for the first boundary
Lwt.catch
(fun () ->
search_first_boundary ~boundary s >>= fun (s, k_eob) ->
search_end_of_line s k_eob >>= fun (s, k_eol) ->
let uses_crlf = (Ocsigen_stream.current_buffer s).[k_eol - 2] = '\r' in
(* Printf.printf "k_eol=%d\n" k_eol; *)
Ocsigen_stream.skip s (Int64.of_int k_eol) >>= fun s ->
Begin with first part :
parse_parts ~boundary ~decode_part s uses_crlf)
(function
| Not_found ->
(* No boundary at all, empty body *)
Lwt.return []
| e -> Lwt.fail e)
let empty_stream =
Ocsigen_stream.get (Ocsigen_stream.make (fun () -> Ocsigen_stream.empty None))
let decode_part ~max_size ~create ~add ~stop stream =
read_header stream >>= fun (s, header) ->
let p = create header in
let rec while_stream size = function
| Ocsigen_stream.Finished None -> Lwt.return (size, empty_stream)
| Ocsigen_stream.Finished (Some ss) -> Lwt.return (size, ss)
| Ocsigen_stream.Cont (stri, f) ->
let long = String.length stri in
let size2 = Int64.add size (Int64.of_int long) in
if match max_size with
| None -> false
| Some m -> Int64.compare size2 m > 0
then Lwt.fail Ocsigen_lib.Ocsigen_Request_too_long
else if stri = ""
then Ocsigen_stream.next f >>= while_stream size
else
add p stri >>= fun () -> Ocsigen_stream.next f >>= while_stream size2
in
Lwt.catch
(fun () ->
while_stream Int64.zero s >>= fun (size, s) ->
stop size p >>= fun r -> Lwt.return (r, s))
(fun error -> stop Int64.zero p >>= fun _ -> Lwt.fail error)
let scan_multipart_body_from_stream ?max_size ~boundary ~create ~add ~stop s =
let decode_part = decode_part ~max_size ~create ~add ~stop in
Lwt.catch
(fun () ->
(* read the multipart body: *)
Ocsigen_stream.next s >>= fun s ->
read_multipart_body ~boundary ~decode_part s >>= fun _ -> Lwt.return ())
(function
| Ocsigen_stream.Stream_too_small ->
Lwt.fail Ocsigen_lib.Ocsigen_Bad_Request
| e -> Lwt.fail e)
let get_boundary ctparams = List.assoc "boundary" ctparams
let counter =
let c = ref (Random.int 1000000) in
fun () ->
c := !c + 1;
!c
let field field content_disp =
let _, res =
S.search_forward (S.regexp (field ^ "=.([^\"]*).;?")) content_disp 0
in
S.matched_group res 1 content_disp
let parse_content_type s =
match Ocsigen_lib.String.split ';' s with
| [] -> None
| a :: l -> (
try
let typ, subtype = Ocsigen_lib.String.sep '/' a in
let params =
try List.map (Ocsigen_lib.String.sep '=') l with Not_found -> []
in
VVV If syntax error , we return no parameter at all
Some ((typ, subtype), params)
VVV If syntax error in type , we return None
with Not_found -> None)
type content_type = (string * string) * (string * string) list
type file_info =
{ tmp_filename : string
; filesize : int64
; raw_original_filename : string
; file_content_type : ((string * string) * (string * string) list) option }
type post_data = (string * string) list * (string * file_info) list
let post_params_form_urlencoded body_gen _ _ =
Lwt.catch
(fun () ->
let body = Ocsigen_stream.get body_gen in
(* BY, adapted from a previous comment. Should this stream be
consumed in case of error? *)
Ocsigen_stream.string_of_stream
(Ocsigen_config.get_maxrequestbodysizeinmemory ())
body
>>= fun r ->
let r = Ocsigen_lib.Url.fixup_url_string r in
let l =
Uri.query_of_encoded r
|> List.map (fun (s, l) -> List.map (fun v -> s, v) l)
|> List.concat
in
Lwt.return (l, []))
(function
| Ocsigen_stream.String_too_large ->
Lwt.fail Ocsigen_lib.Input_is_too_large
| e -> Lwt.fail e)
let post_params_multipart_form_data ctparams body_gen upload_dir max_size =
(* Same question here, should this stream be consumed after an
error? *)
let body = Ocsigen_stream.get body_gen
and boundary = get_boundary ctparams
and params = ref []
and files = ref []
and filenames = ref [] in
let rec add p s =
match p with
| _, `No_file to_buf -> Buffer.add_string to_buf s; Lwt.return ()
| _, `Some_file (_, _, wh, _) ->
let len = String.length s in
let r = Unix.write_substring wh s 0 len in
if r < len
then (*XXXX Inefficient if s is long *)
add p (String.sub s r (len - r))
else Lwt.pause ()
in
let create hs =
let content_type =
try
let ct = List.assoc "content-type" hs in
parse_content_type ct
with _ -> None
in
let cd = List.assoc "content-disposition" hs in
let p_name = field "name" cd in
try
let store = field "filename" cd in
match upload_dir with
| Some dname ->
let fname =
Printf.sprintf "%s/%f-%d" dname (Unix.gettimeofday ()) (counter ())
in
let fd =
Unix.openfile fname
[Unix.O_CREAT; Unix.O_TRUNC; Unix.O_WRONLY; Unix.O_NONBLOCK]
0o666
in
Lwt_log.ign_info ~section ("Upload file opened: " ^ fname);
filenames := fname :: !filenames;
p_name, `Some_file (fname, store, fd, content_type)
| None -> raise Ocsigen_upload_forbidden
with Not_found -> p_name, `No_file (Buffer.create 1024)
and stop filesize = function
| p_name, `No_file to_buf ->
params := !params @ [p_name, Buffer.contents to_buf];
Lwt.return ()
(* in the end ? *)
| ( p_name
, `Some_file (tmp_filename, raw_original_filename, wh, file_content_type)
) ->
let file_info =
{tmp_filename; filesize; raw_original_filename; file_content_type}
in
files := !files @ [p_name, file_info];
Unix.close wh;
Lwt.return ()
in
scan_multipart_body_from_stream ?max_size ~boundary ~create ~add ~stop body
>>= fun () ->
VVV Does scan_multipart_body_from_stream read until the end or
only what it needs ? If we do not consume here , the following
request will be read only when this one is finished ...
only what it needs? If we do not consume here, the following
request will be read only when this one is finished ... *)
Ocsigen_stream.consume body_gen >>= fun () -> Lwt.return (!params, !files)
let post_params ~content_type body_gen =
let (ct, cst), ctparams = content_type in
match String.lowercase_ascii ct, String.lowercase_ascii cst with
| "application", "x-www-form-urlencoded" ->
Some
(body_gen |> Cohttp_lwt.Body.to_stream |> Ocsigen_stream.of_lwt_stream
|> post_params_form_urlencoded)
| "multipart", "form-data" ->
Some
(body_gen |> Cohttp_lwt.Body.to_stream |> Ocsigen_stream.of_lwt_stream
|> post_params_multipart_form_data ctparams)
| _ -> None
| null | https://raw.githubusercontent.com/ocsigen/ocsigenserver/d468cf464dcc9f05f820c35f346ffdbe6b9c7931/src/server/ocsigen_multipart.ml | ocaml | The header must end with an empty line
Maybe the header is empty. In this case, there is an empty
line right at the beginning
Search for an empty line
Search boundary per regexp; return the position of the
character immediately following the boundary (on the same
line), or raise Not_found.
Now the position of [s] is at the beginning of the delimiter.
Check if there is a "--" after the delimiter (==> last part)
[k]: Beginning of next part
Check whether s directly begins with a boundary
Printf.printf "k_eol=%d\n" k_eol;
No boundary at all, empty body
read the multipart body:
BY, adapted from a previous comment. Should this stream be
consumed in case of error?
Same question here, should this stream be consumed after an
error?
XXXX Inefficient if s is long
in the end ? | This code is inspired by mimestring.ml from OcamlNet
Copyright ,
Modified for Ocsigen / Lwt by and
VVV Check wether we should support int64 for large files ?
open Lwt.Infix
module S = Ocsigen_lib.Netstring_pcre
let section = Lwt_log.Section.make "ocsigen:server:multipart"
exception Multipart_error of string
exception Ocsigen_upload_forbidden
let match_end result = snd (Pcre.get_substring_ofs result 0)
let cr_or_lf_re = S.regexp "[\013\n]"
let header_stripped_re =
S.regexp
"([^ \t\r\n:]+):[ \t]*((.*[^ \t\r\n])?([ \t\r]*\n[ \t](.*[^ \t\r\n])?)*)[ \t\r]*\n"
let header_unstripped_re = S.regexp "([^ \t\r\n:]+):([ \t]*.*\n([ \t].*\n)*)"
This much simpler expression returns the name and the unstripped
value .
value. *)
let empty_line_re = S.regexp "\013?\n"
let end_of_header_re = S.regexp "\n\013?\n"
let scan_header ?(downcase = true) ?(unfold = true) ?(strip = false) parstr
~start_pos ~end_pos
=
let header_re =
if unfold || strip then header_stripped_re else header_unstripped_re
in
let rec parse_header i l =
match S.string_match header_re parstr i with
| Some r ->
let i' = match_end r in
if i' > end_pos then raise (Multipart_error "Mimestring.scan_header");
let name =
if downcase
then String.lowercase_ascii (S.matched_group r 1 parstr)
else S.matched_group r 1 parstr
in
let value_with_crlf = S.matched_group r 2 parstr in
let value =
if unfold
then S.global_replace cr_or_lf_re "" value_with_crlf
else value_with_crlf
in
parse_header i' ((name, value) :: l)
| None -> (
match S.string_match empty_line_re parstr i with
| Some r' -> List.rev l, match_end r'
| None -> raise (Multipart_error "Mimestring.scan_header"))
in
parse_header start_pos []
let read_header ?downcase ?unfold ?strip s =
let rec find_end_of_header s =
Lwt.catch
(fun () ->
let b = Ocsigen_stream.current_buffer s in
match S.string_match empty_line_re b 0 with
| Some r -> Lwt.return (s, match_end r)
| None ->
Lwt.return
(s, match_end (snd (S.search_forward end_of_header_re b 0))))
(function
| Not_found -> (
Ocsigen_stream.enlarge_stream s >>= function
| Ocsigen_stream.Finished _ ->
Lwt.fail Ocsigen_stream.Stream_too_small
| Ocsigen_stream.Cont _ as s -> find_end_of_header s)
| e -> Lwt.fail e)
in
find_end_of_header s >>= fun (s, end_pos) ->
let b = Ocsigen_stream.current_buffer s in
let h, _ = scan_header ?downcase ?unfold ?strip b ~start_pos:0 ~end_pos in
Ocsigen_stream.skip s (Int64.of_int end_pos) >>= fun s -> Lwt.return (s, h)
let lf_re = S.regexp "[\n]"
let rec search_window s re start =
try
Lwt.return
(s, snd (S.search_forward re (Ocsigen_stream.current_buffer s) start))
with Not_found -> (
Ocsigen_stream.enlarge_stream s >>= function
| Ocsigen_stream.Finished _ -> Lwt.fail Ocsigen_stream.Stream_too_small
| Ocsigen_stream.Cont _ as s -> search_window s re start)
let search_end_of_line s k =
Search LF beginning at position k
Lwt.catch
(fun () ->
search_window s lf_re k >>= fun (s, x) -> Lwt.return (s, match_end x))
(function
| Not_found ->
Lwt.fail
(Multipart_error
"read_multipart_body: MIME boundary without line end")
| e -> Lwt.fail e)
let search_first_boundary ~boundary s =
let re = S.regexp ("\n--" ^ Pcre.quote boundary) in
search_window s re 0 >>= fun (s, x) -> Lwt.return (s, match_end x)
let check_beginning_is_boundary ~boundary s =
let del = "--" ^ boundary in
let ldel = String.length del in
Ocsigen_stream.stream_want s (ldel + 2) >>= function
| Ocsigen_stream.Finished _ as str2 -> Lwt.return (str2, false, false)
| Ocsigen_stream.Cont (ss, _f) as str2 ->
let long = String.length ss in
let isdelim = long >= ldel && String.sub ss 0 ldel = del in
let islast = isdelim && String.sub ss ldel 2 = "--" in
Lwt.return (str2, isdelim, islast)
let rec parse_parts ~boundary ~decode_part s uses_crlf =
PRE : [ s ] is at the beginning of the next part . [ uses_crlf ] must
be true if CRLF is used as EOL sequence , and false if only LF is
used as EOL sequence .
be true if CRLF is used as EOL sequence, and false if only LF is
used as EOL sequence. *)
let delimiter = (if uses_crlf then "\r" else "") ^ "\n--" ^ boundary in
Ocsigen_stream.substream delimiter s >>= fun a ->
decode_part a >>= fun (y, s) ->
let l_delimiter = String.length delimiter in
Ocsigen_stream.next s >>= fun s ->
Ocsigen_stream.stream_want s (l_delimiter + 2) >>= fun s ->
let last_part =
match s with
| Ocsigen_stream.Finished _ -> false
| Ocsigen_stream.Cont (ss, _f) ->
let long = String.length ss in
long >= l_delimiter + 2
&& ss.[l_delimiter] = '-'
&& ss.[l_delimiter + 1] = '-'
in
if last_part
then Lwt.return [y]
else
search_end_of_line s 2 >>= fun (s, k) ->
Ocsigen_stream.skip s (Int64.of_int k) >>= fun s ->
parse_parts ~boundary ~decode_part s uses_crlf >>= fun l ->
Lwt.return (y :: l)
let read_multipart_body ~boundary ~decode_part s =
check_beginning_is_boundary ~boundary s >>= fun (s, b, islast) ->
if islast
then Lwt.return []
else if b
then
Move to the beginning of the next line
search_end_of_line s 0 >>= fun (s, k_eol) ->
let uses_crlf = (Ocsigen_stream.current_buffer s).[k_eol - 2] = '\r' in
Ocsigen_stream.skip s (Int64.of_int k_eol) >>= fun s ->
Begin with first part :
parse_parts ~boundary ~decode_part s uses_crlf
else
Look for the first boundary
Lwt.catch
(fun () ->
search_first_boundary ~boundary s >>= fun (s, k_eob) ->
search_end_of_line s k_eob >>= fun (s, k_eol) ->
let uses_crlf = (Ocsigen_stream.current_buffer s).[k_eol - 2] = '\r' in
Ocsigen_stream.skip s (Int64.of_int k_eol) >>= fun s ->
Begin with first part :
parse_parts ~boundary ~decode_part s uses_crlf)
(function
| Not_found ->
Lwt.return []
| e -> Lwt.fail e)
let empty_stream =
Ocsigen_stream.get (Ocsigen_stream.make (fun () -> Ocsigen_stream.empty None))
let decode_part ~max_size ~create ~add ~stop stream =
read_header stream >>= fun (s, header) ->
let p = create header in
let rec while_stream size = function
| Ocsigen_stream.Finished None -> Lwt.return (size, empty_stream)
| Ocsigen_stream.Finished (Some ss) -> Lwt.return (size, ss)
| Ocsigen_stream.Cont (stri, f) ->
let long = String.length stri in
let size2 = Int64.add size (Int64.of_int long) in
if match max_size with
| None -> false
| Some m -> Int64.compare size2 m > 0
then Lwt.fail Ocsigen_lib.Ocsigen_Request_too_long
else if stri = ""
then Ocsigen_stream.next f >>= while_stream size
else
add p stri >>= fun () -> Ocsigen_stream.next f >>= while_stream size2
in
Lwt.catch
(fun () ->
while_stream Int64.zero s >>= fun (size, s) ->
stop size p >>= fun r -> Lwt.return (r, s))
(fun error -> stop Int64.zero p >>= fun _ -> Lwt.fail error)
let scan_multipart_body_from_stream ?max_size ~boundary ~create ~add ~stop s =
let decode_part = decode_part ~max_size ~create ~add ~stop in
Lwt.catch
(fun () ->
Ocsigen_stream.next s >>= fun s ->
read_multipart_body ~boundary ~decode_part s >>= fun _ -> Lwt.return ())
(function
| Ocsigen_stream.Stream_too_small ->
Lwt.fail Ocsigen_lib.Ocsigen_Bad_Request
| e -> Lwt.fail e)
let get_boundary ctparams = List.assoc "boundary" ctparams
let counter =
let c = ref (Random.int 1000000) in
fun () ->
c := !c + 1;
!c
let field field content_disp =
let _, res =
S.search_forward (S.regexp (field ^ "=.([^\"]*).;?")) content_disp 0
in
S.matched_group res 1 content_disp
let parse_content_type s =
match Ocsigen_lib.String.split ';' s with
| [] -> None
| a :: l -> (
try
let typ, subtype = Ocsigen_lib.String.sep '/' a in
let params =
try List.map (Ocsigen_lib.String.sep '=') l with Not_found -> []
in
VVV If syntax error , we return no parameter at all
Some ((typ, subtype), params)
VVV If syntax error in type , we return None
with Not_found -> None)
type content_type = (string * string) * (string * string) list
type file_info =
{ tmp_filename : string
; filesize : int64
; raw_original_filename : string
; file_content_type : ((string * string) * (string * string) list) option }
type post_data = (string * string) list * (string * file_info) list
let post_params_form_urlencoded body_gen _ _ =
Lwt.catch
(fun () ->
let body = Ocsigen_stream.get body_gen in
Ocsigen_stream.string_of_stream
(Ocsigen_config.get_maxrequestbodysizeinmemory ())
body
>>= fun r ->
let r = Ocsigen_lib.Url.fixup_url_string r in
let l =
Uri.query_of_encoded r
|> List.map (fun (s, l) -> List.map (fun v -> s, v) l)
|> List.concat
in
Lwt.return (l, []))
(function
| Ocsigen_stream.String_too_large ->
Lwt.fail Ocsigen_lib.Input_is_too_large
| e -> Lwt.fail e)
let post_params_multipart_form_data ctparams body_gen upload_dir max_size =
let body = Ocsigen_stream.get body_gen
and boundary = get_boundary ctparams
and params = ref []
and files = ref []
and filenames = ref [] in
let rec add p s =
match p with
| _, `No_file to_buf -> Buffer.add_string to_buf s; Lwt.return ()
| _, `Some_file (_, _, wh, _) ->
let len = String.length s in
let r = Unix.write_substring wh s 0 len in
if r < len
add p (String.sub s r (len - r))
else Lwt.pause ()
in
let create hs =
let content_type =
try
let ct = List.assoc "content-type" hs in
parse_content_type ct
with _ -> None
in
let cd = List.assoc "content-disposition" hs in
let p_name = field "name" cd in
try
let store = field "filename" cd in
match upload_dir with
| Some dname ->
let fname =
Printf.sprintf "%s/%f-%d" dname (Unix.gettimeofday ()) (counter ())
in
let fd =
Unix.openfile fname
[Unix.O_CREAT; Unix.O_TRUNC; Unix.O_WRONLY; Unix.O_NONBLOCK]
0o666
in
Lwt_log.ign_info ~section ("Upload file opened: " ^ fname);
filenames := fname :: !filenames;
p_name, `Some_file (fname, store, fd, content_type)
| None -> raise Ocsigen_upload_forbidden
with Not_found -> p_name, `No_file (Buffer.create 1024)
and stop filesize = function
| p_name, `No_file to_buf ->
params := !params @ [p_name, Buffer.contents to_buf];
Lwt.return ()
| ( p_name
, `Some_file (tmp_filename, raw_original_filename, wh, file_content_type)
) ->
let file_info =
{tmp_filename; filesize; raw_original_filename; file_content_type}
in
files := !files @ [p_name, file_info];
Unix.close wh;
Lwt.return ()
in
scan_multipart_body_from_stream ?max_size ~boundary ~create ~add ~stop body
>>= fun () ->
VVV Does scan_multipart_body_from_stream read until the end or
only what it needs ? If we do not consume here , the following
request will be read only when this one is finished ...
only what it needs? If we do not consume here, the following
request will be read only when this one is finished ... *)
Ocsigen_stream.consume body_gen >>= fun () -> Lwt.return (!params, !files)
let post_params ~content_type body_gen =
let (ct, cst), ctparams = content_type in
match String.lowercase_ascii ct, String.lowercase_ascii cst with
| "application", "x-www-form-urlencoded" ->
Some
(body_gen |> Cohttp_lwt.Body.to_stream |> Ocsigen_stream.of_lwt_stream
|> post_params_form_urlencoded)
| "multipart", "form-data" ->
Some
(body_gen |> Cohttp_lwt.Body.to_stream |> Ocsigen_stream.of_lwt_stream
|> post_params_multipart_form_data ctparams)
| _ -> None
|
5d2f447d3bafab5660448b005f455c8052406378f8734e3d4095c4d437958cfd | lehins/massiv | doctests.hs | # LANGUAGE CPP #
module Main where
#if __GLASGOW_HASKELL__ >= 802 && __GLASGOW_HASKELL__ < 810
import Test.DocTest (doctest)
main :: IO ()
main = doctest ["-Iinclude","src"]
#else
-- TODO: fix doctest support
main :: IO ()
main =
putStrLn "\nDoctests are not supported for ghc version 8.2 and prior as well as 8.10 and newer\n"
#endif
| null | https://raw.githubusercontent.com/lehins/massiv/67a920d4403f210d0bfdad1acc4bec208d80a588/massiv/tests/doctests.hs | haskell | TODO: fix doctest support | # LANGUAGE CPP #
module Main where
#if __GLASGOW_HASKELL__ >= 802 && __GLASGOW_HASKELL__ < 810
import Test.DocTest (doctest)
main :: IO ()
main = doctest ["-Iinclude","src"]
#else
main :: IO ()
main =
putStrLn "\nDoctests are not supported for ghc version 8.2 and prior as well as 8.10 and newer\n"
#endif
|
2d011ae3bad41f6486ed6e9b757e324e7369d2133d28da5263a0526ce6d5ac78 | qfpl/reflex-realworld-example | Comments.hs | # LANGUAGE FlexibleContexts , OverloadedStrings #
module Backend.Conduit.Database.Comments
( create
, destroy
, find
, forArticle
) where
import Control.Lens (view, (^.), _1, _2)
import Control.Monad.Error.Class (MonadError)
import Control.Monad.IO.Class (MonadIO, liftIO)
import Control.Monad.Reader.Class (MonadReader, ask)
import Control.Monad.Trans.Control (MonadBaseControl)
import Data.Functor (void)
import Data.Maybe (fromMaybe)
import Data.Text (Text)
import Data.Time (UTCTime, getCurrentTime)
import Database.Beam.Postgres.Extended (PgInsertReturning, PgQExpr, PgSelectSyntax, Q, all_, default_, delete,
guard_, insertExpressions, insertReturning, onConflictDefault,
primaryKey, runDelete, runInsertReturning, runSelect, select, val_,
(==.))
import Database.PostgreSQL.Simple (Connection)
import Backend.Conduit.Database (ConduitDb (conduitArticles, conduitComments),
QueryError, conduitDb, maybeRow, rowList,
singleRow)
import Backend.Conduit.Database.Articles.Article (ArticleId)
import qualified Backend.Conduit.Database.Articles.Article as PersistedArticle
import Backend.Conduit.Database.Comments.Comment (PrimaryKey (CommentId))
import qualified Backend.Conduit.Database.Comments.Comment as Persisted
import Backend.Conduit.Database.Users (ProfileResult, ProfileRow, selectProfiles)
import Backend.Conduit.Database.Users.User (UserId)
import qualified Backend.Conduit.Database.Users.User as User
import Common.Conduit.Api.Articles.Comment (Comment (Comment))
import Common.Conduit.Api.Profiles.Profile (Profile (Profile))
insertComment
:: UserId -> ArticleId -> Text -> UTCTime -> PgInsertReturning Persisted.Comment
insertComment authorId articleId body currentTime
= insertReturning
(conduitComments conduitDb)
(insertExpressions
[ Persisted.Comment
{ Persisted.id = default_
, Persisted.body = val_ body
, Persisted.article = val_ articleId
, Persisted.author = val_ authorId
, Persisted.createdAt = val_ currentTime
, Persisted.updatedAt = val_ currentTime
}
]
)
onConflictDefault
(Just id)
create
:: ( MonadReader Connection m
, MonadError QueryError m
, MonadIO m
, MonadBaseControl IO m
)
=> UserId
-> ArticleId
-> Text
-> m Comment
create authorId articleId body = do
conn <- ask
currentTime <- liftIO getCurrentTime
inserted <-
runInsertReturning
conn
(insertComment authorId articleId body currentTime)
singleRow
unsafeFind (Just authorId) (Persisted.id inserted)
destroy :: (MonadIO m, MonadReader Connection m) => Int -> m ()
destroy comment = do
conn <- ask
void $ runDelete conn $ delete (conduitComments conduitDb) $ \candidate ->
primaryKey candidate ==. val_ (CommentId comment)
type CommentRow s =
( Persisted.CommentT (PgQExpr s)
, ProfileRow s
)
type CommentResult =
( Persisted.Comment
, ProfileResult
)
toComment :: CommentResult -> Comment
toComment =
Comment
<$> (Persisted.id . view _1)
<*> (Persisted.createdAt . view _1)
<*> (Persisted.updatedAt . view _1)
<*> (Persisted.body . view _1)
<*> (Profile
<$> (User.id . view (_2 . _1))
<*> (User.username . view (_2 . _1))
<*> (User.bio . view (_2 . _1))
<*> (User.image . view (_2 . _1))
<*> (fromMaybe False . view (_2 . _2))
)
selectComments
:: Maybe UserId
-> Q PgSelectSyntax ConduitDb s (CommentRow s)
selectComments currentUserId = do
comment <- all_ (conduitComments conduitDb)
profile <- selectProfiles currentUserId
guard_ (Persisted.author comment ==. primaryKey (profile ^. _1))
pure (comment, profile)
selectComment
:: Maybe UserId
-> Int
-> Q PgSelectSyntax ConduitDb s (CommentRow s)
selectComment currentUserId commentId = do
commentRow <- selectComments currentUserId
guard_ (Persisted.id (commentRow ^. _1) ==. val_ commentId)
pure commentRow
find
:: (MonadReader Connection m, MonadIO m, MonadBaseControl IO m)
=> Maybe UserId
-> Int
-> m (Maybe Comment)
find currentUserId commentId = do
conn <- ask
fmap toComment <$> runSelect conn (select (selectComment currentUserId commentId)) maybeRow
unsafeFind
:: ( MonadReader Connection m
, MonadIO m
, MonadBaseControl IO m
, MonadError QueryError m
)
=> Maybe UserId
-> Int
-> m Comment
unsafeFind currentUserId commentId = do
conn <- ask
toComment <$> runSelect conn (select (selectComment currentUserId commentId)) singleRow
selectCommentsForArticle
:: Maybe UserId
-> Text
-> Q PgSelectSyntax ConduitDb s (CommentRow s)
selectCommentsForArticle currentUserId slug = do
commentRow <- selectComments currentUserId
article <- all_ (conduitArticles conduitDb)
guard_ (PersistedArticle.slug article ==. val_ slug)
guard_ (Persisted.article (commentRow ^. _1) ==. primaryKey article)
pure commentRow
forArticle
:: (MonadReader Connection m, MonadIO m, MonadBaseControl IO m)
=> Maybe UserId
-> Text
-> m [Comment]
forArticle currentUserId slug = do
conn <- ask
fmap toComment <$> runSelect conn (select (selectCommentsForArticle currentUserId slug)) rowList
| null | https://raw.githubusercontent.com/qfpl/reflex-realworld-example/aca3125e036fbb5edd3a20d0e5a13ec73eaa6fcb/backend/src/Backend/Conduit/Database/Comments.hs | haskell | # LANGUAGE FlexibleContexts , OverloadedStrings #
module Backend.Conduit.Database.Comments
( create
, destroy
, find
, forArticle
) where
import Control.Lens (view, (^.), _1, _2)
import Control.Monad.Error.Class (MonadError)
import Control.Monad.IO.Class (MonadIO, liftIO)
import Control.Monad.Reader.Class (MonadReader, ask)
import Control.Monad.Trans.Control (MonadBaseControl)
import Data.Functor (void)
import Data.Maybe (fromMaybe)
import Data.Text (Text)
import Data.Time (UTCTime, getCurrentTime)
import Database.Beam.Postgres.Extended (PgInsertReturning, PgQExpr, PgSelectSyntax, Q, all_, default_, delete,
guard_, insertExpressions, insertReturning, onConflictDefault,
primaryKey, runDelete, runInsertReturning, runSelect, select, val_,
(==.))
import Database.PostgreSQL.Simple (Connection)
import Backend.Conduit.Database (ConduitDb (conduitArticles, conduitComments),
QueryError, conduitDb, maybeRow, rowList,
singleRow)
import Backend.Conduit.Database.Articles.Article (ArticleId)
import qualified Backend.Conduit.Database.Articles.Article as PersistedArticle
import Backend.Conduit.Database.Comments.Comment (PrimaryKey (CommentId))
import qualified Backend.Conduit.Database.Comments.Comment as Persisted
import Backend.Conduit.Database.Users (ProfileResult, ProfileRow, selectProfiles)
import Backend.Conduit.Database.Users.User (UserId)
import qualified Backend.Conduit.Database.Users.User as User
import Common.Conduit.Api.Articles.Comment (Comment (Comment))
import Common.Conduit.Api.Profiles.Profile (Profile (Profile))
insertComment
:: UserId -> ArticleId -> Text -> UTCTime -> PgInsertReturning Persisted.Comment
insertComment authorId articleId body currentTime
= insertReturning
(conduitComments conduitDb)
(insertExpressions
[ Persisted.Comment
{ Persisted.id = default_
, Persisted.body = val_ body
, Persisted.article = val_ articleId
, Persisted.author = val_ authorId
, Persisted.createdAt = val_ currentTime
, Persisted.updatedAt = val_ currentTime
}
]
)
onConflictDefault
(Just id)
create
:: ( MonadReader Connection m
, MonadError QueryError m
, MonadIO m
, MonadBaseControl IO m
)
=> UserId
-> ArticleId
-> Text
-> m Comment
create authorId articleId body = do
conn <- ask
currentTime <- liftIO getCurrentTime
inserted <-
runInsertReturning
conn
(insertComment authorId articleId body currentTime)
singleRow
unsafeFind (Just authorId) (Persisted.id inserted)
destroy :: (MonadIO m, MonadReader Connection m) => Int -> m ()
destroy comment = do
conn <- ask
void $ runDelete conn $ delete (conduitComments conduitDb) $ \candidate ->
primaryKey candidate ==. val_ (CommentId comment)
type CommentRow s =
( Persisted.CommentT (PgQExpr s)
, ProfileRow s
)
type CommentResult =
( Persisted.Comment
, ProfileResult
)
toComment :: CommentResult -> Comment
toComment =
Comment
<$> (Persisted.id . view _1)
<*> (Persisted.createdAt . view _1)
<*> (Persisted.updatedAt . view _1)
<*> (Persisted.body . view _1)
<*> (Profile
<$> (User.id . view (_2 . _1))
<*> (User.username . view (_2 . _1))
<*> (User.bio . view (_2 . _1))
<*> (User.image . view (_2 . _1))
<*> (fromMaybe False . view (_2 . _2))
)
selectComments
:: Maybe UserId
-> Q PgSelectSyntax ConduitDb s (CommentRow s)
selectComments currentUserId = do
comment <- all_ (conduitComments conduitDb)
profile <- selectProfiles currentUserId
guard_ (Persisted.author comment ==. primaryKey (profile ^. _1))
pure (comment, profile)
selectComment
:: Maybe UserId
-> Int
-> Q PgSelectSyntax ConduitDb s (CommentRow s)
selectComment currentUserId commentId = do
commentRow <- selectComments currentUserId
guard_ (Persisted.id (commentRow ^. _1) ==. val_ commentId)
pure commentRow
find
:: (MonadReader Connection m, MonadIO m, MonadBaseControl IO m)
=> Maybe UserId
-> Int
-> m (Maybe Comment)
find currentUserId commentId = do
conn <- ask
fmap toComment <$> runSelect conn (select (selectComment currentUserId commentId)) maybeRow
unsafeFind
:: ( MonadReader Connection m
, MonadIO m
, MonadBaseControl IO m
, MonadError QueryError m
)
=> Maybe UserId
-> Int
-> m Comment
unsafeFind currentUserId commentId = do
conn <- ask
toComment <$> runSelect conn (select (selectComment currentUserId commentId)) singleRow
selectCommentsForArticle
:: Maybe UserId
-> Text
-> Q PgSelectSyntax ConduitDb s (CommentRow s)
selectCommentsForArticle currentUserId slug = do
commentRow <- selectComments currentUserId
article <- all_ (conduitArticles conduitDb)
guard_ (PersistedArticle.slug article ==. val_ slug)
guard_ (Persisted.article (commentRow ^. _1) ==. primaryKey article)
pure commentRow
forArticle
:: (MonadReader Connection m, MonadIO m, MonadBaseControl IO m)
=> Maybe UserId
-> Text
-> m [Comment]
forArticle currentUserId slug = do
conn <- ask
fmap toComment <$> runSelect conn (select (selectCommentsForArticle currentUserId slug)) rowList
| |
cf4593d0201b1d05ff0b8ea30c3cac522408a8ffd0b1a953c9902b0983c00431 | fulcrologic/fulcro-rad-kvstore | database_queries.clj | (ns com.example.components.database-queries
"`server-queries` would be a better name but constrained by no alterations to model allowed, so we can always easily
copy over the latest RAD Demo"
(:require
[com.example.components.queries :as queries]
[com.fulcrologic.rad.database-adapters.key-value :as key-value]
[com.fulcrologic.rad.database-adapters.key-value.key-store :as kv-key-store]
[taoensso.encore :as enc]
[taoensso.timbre :as log]
[konserve.core :as k]
[clojure.core.async :refer [<!! <! go]]
[com.fulcrologic.rad.database-adapters.key-value.pathom :as kv-pathom]))
(defn get-all-accounts-1
[env query-params]
(when-let [key-store (kv-pathom/env->key-store env)]
(<!!
(queries/get-all-accounts key-store query-params))))
(defn get-all-accounts-2
[env query-params]
(when-let [{::kv-key-store/keys [table->ident-rows table->rows]} (kv-pathom/env->key-store env)]
(if (:show-inactive? query-params)
(->> (table->ident-rows :account/id)
(mapv (fn [[table id]] {table id})))
(->> (table->rows :account/id)
(filter :account/active?)
(mapv #(select-keys % [:account/id]))))))
(def get-all-accounts get-all-accounts-1)
(defn get-all-items
[env query-params]
(when-let [key-store (kv-pathom/env->key-store env)]
(<!!
(queries/get-all-items key-store query-params))))
(defn get-customer-invoices
[env query-params]
(when-let [key-store (kv-pathom/env->key-store env)]
(<!!
(queries/get-customer-invoices key-store query-params))))
(defn get-all-invoices
[env query-params]
(when-let [key-store (kv-pathom/env->key-store env)]
(<!!
(queries/get-all-invoices key-store))))
(defn get-invoice-customer-id
[env invoice-id]
(when-let [key-store (kv-pathom/env->key-store env)]
(<!!
(queries/get-invoice-customer-id key-store invoice-id))))
(defn get-all-categories
[env query-params]
(when-let [key-store (kv-pathom/env->key-store env)]
(<!!
(queries/get-all-categories key-store))))
(defn get-line-item-category
[env line-item-id]
(when-let [key-store (kv-pathom/env->key-store env)]
(<!!
(queries/get-line-item-category key-store line-item-id))))
;; Just created for testing
(defn get-all-line-items
[env query-params]
(when-let [key-store (kv-pathom/env->key-store env)]
(<!!
(queries/get-all-line-items key-store))))
(defn get-login-info
"Get the account name, time zone, and password info via a username (email)."
[{::key-value/keys [databases] :as env} username]
(let [key-store @(:production databases)]
(<!!
(queries/get-login-info key-store username))))
(defn d-pull [db pull eid]
(log/error "datomic pull with id" pull eid))
;;
;; Keeping to show that above we are not outputting the name of the time-zone
;; (rather the keyword)
Not working code as has : db / ident in it which is Datomic specific !
;;
(defn get-login-info-2
"Get the account name, time zone, and password info via a username (email)."
[{::key-value/keys [databases] :as env} username]
(enc/if-let [db @(:production databases)]
(d-pull db [:account/name
{:time-zone/zone-id [:db/ident]}
:password/hashed-value
:password/salt
:password/iterations]
[:account/email username]))) | null | https://raw.githubusercontent.com/fulcrologic/fulcro-rad-kvstore/d0dff827ee2200090d70768a9e581ba91f84f937/src/demo-project/com/example/components/database_queries.clj | clojure | Just created for testing
Keeping to show that above we are not outputting the name of the time-zone
(rather the keyword)
| (ns com.example.components.database-queries
"`server-queries` would be a better name but constrained by no alterations to model allowed, so we can always easily
copy over the latest RAD Demo"
(:require
[com.example.components.queries :as queries]
[com.fulcrologic.rad.database-adapters.key-value :as key-value]
[com.fulcrologic.rad.database-adapters.key-value.key-store :as kv-key-store]
[taoensso.encore :as enc]
[taoensso.timbre :as log]
[konserve.core :as k]
[clojure.core.async :refer [<!! <! go]]
[com.fulcrologic.rad.database-adapters.key-value.pathom :as kv-pathom]))
(defn get-all-accounts-1
[env query-params]
(when-let [key-store (kv-pathom/env->key-store env)]
(<!!
(queries/get-all-accounts key-store query-params))))
(defn get-all-accounts-2
[env query-params]
(when-let [{::kv-key-store/keys [table->ident-rows table->rows]} (kv-pathom/env->key-store env)]
(if (:show-inactive? query-params)
(->> (table->ident-rows :account/id)
(mapv (fn [[table id]] {table id})))
(->> (table->rows :account/id)
(filter :account/active?)
(mapv #(select-keys % [:account/id]))))))
(def get-all-accounts get-all-accounts-1)
(defn get-all-items
[env query-params]
(when-let [key-store (kv-pathom/env->key-store env)]
(<!!
(queries/get-all-items key-store query-params))))
(defn get-customer-invoices
[env query-params]
(when-let [key-store (kv-pathom/env->key-store env)]
(<!!
(queries/get-customer-invoices key-store query-params))))
(defn get-all-invoices
[env query-params]
(when-let [key-store (kv-pathom/env->key-store env)]
(<!!
(queries/get-all-invoices key-store))))
(defn get-invoice-customer-id
[env invoice-id]
(when-let [key-store (kv-pathom/env->key-store env)]
(<!!
(queries/get-invoice-customer-id key-store invoice-id))))
(defn get-all-categories
[env query-params]
(when-let [key-store (kv-pathom/env->key-store env)]
(<!!
(queries/get-all-categories key-store))))
(defn get-line-item-category
[env line-item-id]
(when-let [key-store (kv-pathom/env->key-store env)]
(<!!
(queries/get-line-item-category key-store line-item-id))))
(defn get-all-line-items
[env query-params]
(when-let [key-store (kv-pathom/env->key-store env)]
(<!!
(queries/get-all-line-items key-store))))
(defn get-login-info
"Get the account name, time zone, and password info via a username (email)."
[{::key-value/keys [databases] :as env} username]
(let [key-store @(:production databases)]
(<!!
(queries/get-login-info key-store username))))
(defn d-pull [db pull eid]
(log/error "datomic pull with id" pull eid))
Not working code as has : db / ident in it which is Datomic specific !
(defn get-login-info-2
"Get the account name, time zone, and password info via a username (email)."
[{::key-value/keys [databases] :as env} username]
(enc/if-let [db @(:production databases)]
(d-pull db [:account/name
{:time-zone/zone-id [:db/ident]}
:password/hashed-value
:password/salt
:password/iterations]
[:account/email username]))) |
ebf9c159356295867f0fd7034dcd468be0a239cba9ca23bd63fec7cd86b4f36f | backtracking/mlpost | matrix.mli | type point = Ctypes.point
type t = Ctypes.matrix = {
mutable xx : float;
mutable yx : float;
mutable xy : float;
mutable yy : float;
mutable x0 : float;
mutable y0 : float;
}
val scale : float -> t
val rotation : float -> t
val xscaled : float -> t
val yscaled : float -> t
val slanted : float -> t
val translation : point -> t
val zscaled : point -> t
val reflect : point -> point -> t
val rotate_around : point -> float -> t
val identity : t
val multiply : t -> t -> t
val xy_translation : float -> float -> t
val remove_translation : t -> t
val linear : float -> float -> float -> float -> t
val print : Format.formatter -> t -> unit
| null | https://raw.githubusercontent.com/backtracking/mlpost/bd4305289fd64d531b9f42d64dd641d72ab82fd5/src/matrix.mli | ocaml | type point = Ctypes.point
type t = Ctypes.matrix = {
mutable xx : float;
mutable yx : float;
mutable xy : float;
mutable yy : float;
mutable x0 : float;
mutable y0 : float;
}
val scale : float -> t
val rotation : float -> t
val xscaled : float -> t
val yscaled : float -> t
val slanted : float -> t
val translation : point -> t
val zscaled : point -> t
val reflect : point -> point -> t
val rotate_around : point -> float -> t
val identity : t
val multiply : t -> t -> t
val xy_translation : float -> float -> t
val remove_translation : t -> t
val linear : float -> float -> float -> float -> t
val print : Format.formatter -> t -> unit
| |
79590791dd6a7d85792ab269baa1663d07078479dc6247bba6e53563fcda6ed2 | phylogeography/spread | macros.cljc | (ns shared.macros
(:require #?(:clj [cljs.core]
:default [taoensso.timbre]))
#?(:cljs (:require-macros [shared.macros])))
(defn compiletime-info
[_ and-form ns]
(let [meta-info (meta and-form)]
{:ns (str (ns-name ns))
:line (:line meta-info)
:file (:file meta-info)}))
(defmacro promise->
"Takes `thenable` functions as arguments (i.e. functions returning a JS/Promise) and chains them,
taking care of error handling
Example:
(promise-> (thenable-1)
(thenable-2))"
[promise & body]
`(.catch
(-> ~promise
~@(map (fn [expr] (list '.then expr)) body))
(fn [error#]
(taoensso.timbre/error "Promise rejected" (merge {:error error#}
(ex-data error#)
~(compiletime-info &env &form *ns*))))))
(defmacro try-catch [& body]
`(try
~@body
(catch js/Object e#
(taoensso.timbre/error "Unexpected exception" (merge {:error e#}
(ex-data e#)
~(compiletime-info &env &form *ns*))))))
(defmacro try-catch-throw [& body]
`(try
~@body
(catch js/Object e#
(taoensso.timbre/error "Unexpected exception" (merge {:error e#}
(ex-data e#)
~(compiletime-info &env &form *ns*)))
(throw (js/Error. e#)))))
#?(:clj
(defmacro get-env-variable
[var-name & [required?]]
(let [var-name (System/getenv var-name)]
(if (and (empty? var-name)
required?)
(throw (Exception. (str "MISSING ENV VARIABLE: " var-name " not defined in environment")))
var-name))))
| null | https://raw.githubusercontent.com/phylogeography/spread/56f3500e6d83e0ebd50041dc336ffa0697d7baf8/src/cljc/shared/macros.cljc | clojure | (ns shared.macros
(:require #?(:clj [cljs.core]
:default [taoensso.timbre]))
#?(:cljs (:require-macros [shared.macros])))
(defn compiletime-info
[_ and-form ns]
(let [meta-info (meta and-form)]
{:ns (str (ns-name ns))
:line (:line meta-info)
:file (:file meta-info)}))
(defmacro promise->
"Takes `thenable` functions as arguments (i.e. functions returning a JS/Promise) and chains them,
taking care of error handling
Example:
(promise-> (thenable-1)
(thenable-2))"
[promise & body]
`(.catch
(-> ~promise
~@(map (fn [expr] (list '.then expr)) body))
(fn [error#]
(taoensso.timbre/error "Promise rejected" (merge {:error error#}
(ex-data error#)
~(compiletime-info &env &form *ns*))))))
(defmacro try-catch [& body]
`(try
~@body
(catch js/Object e#
(taoensso.timbre/error "Unexpected exception" (merge {:error e#}
(ex-data e#)
~(compiletime-info &env &form *ns*))))))
(defmacro try-catch-throw [& body]
`(try
~@body
(catch js/Object e#
(taoensso.timbre/error "Unexpected exception" (merge {:error e#}
(ex-data e#)
~(compiletime-info &env &form *ns*)))
(throw (js/Error. e#)))))
#?(:clj
(defmacro get-env-variable
[var-name & [required?]]
(let [var-name (System/getenv var-name)]
(if (and (empty? var-name)
required?)
(throw (Exception. (str "MISSING ENV VARIABLE: " var-name " not defined in environment")))
var-name))))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.