_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
|
---|---|---|---|---|---|---|---|---|
b4a5f122b2c056bbac102f42fd7ea00f24a3a0e969ee0e518126823c8df52937
|
ocaml/omd
|
strSlice.mli
|
(* Implementation of string slices over a base string via an offset *)
type t
val of_string : ?off:int -> string -> t
val to_string : t -> string
val offset : int -> t -> t
val lexbuf : t -> Lexing.lexbuf
val contains : string -> t -> bool
val length : t -> int
val index : (char -> bool) -> t -> int option
* [ index c s ] is [ Some i ] where [ i ] is the index of the character in [ s ] for
which [ f ] is first true , or [ None ] if [ f ] holds for no characters in [ s ] .
which [f] is first true, or [None] if [f] holds for no characters in [s]. *)
val index_unescaped : char -> t -> int option
* [ index_unescaped c s ] is [ Some i ] where [ i ] is index of the first
occurrence of the character [ c ] in [ s ] that is not preceeded by a
backslash [ ' \\ ' ] and not within a verbatim inline , or [ None ] if
there is no such [ c ] in [ s ] .
occurrence of the character [c] in [s] that is not preceeded by a
backslash ['\\'] and not within a verbatim inline, or [None] if
there is no such [c] in [s]. *)
val print : Format.formatter -> t -> unit
val head : t -> char option
val tail : t -> t
val uncons : t -> (char * t) option
(** [uncons s] is [Some (h, t)] where [h] is [head s] and [t] is [tail s],
or [None] if [is_empty s] *)
val last : t -> char option
(** [last s] is the [Some c] if [c] is the last character of [s], or else [None] if [s] is empty *)
val drop_last : t -> t
(** [drop_last s] is the [s] without its last character *)
val take : int -> t -> char list
* [ take n s ] is a list of the first [ n ] characters of [ s ]
val take_prefix : int -> t -> t
* [ take_prefix n s ] is the slice consisting of the first [ n ]
characters of [ s ] .
characters of [s]. *)
val drop : int -> t -> t
* [ drop n s ] is [ s ] with the first [ n ] characters dropped
val drop_while : (char -> bool) -> t -> t
(** [drop_while f s] is [s] with the longest prefix for which [f] is true for
every character dropped *)
val drop_last_while : (char -> bool) -> t -> t
(** [drop_last_while f s] is [s] with the longest suffix for which [f] is true for
every character dropped *)
val split_at : (char -> bool) -> t -> t * t
* [ split_at f s ] is [ ( taken , rest ) ] where [ taken ] is the prefix of [ s ] for
which [ f ] is [ false ] and [ rest ] is remainder , including the first character
for which [ f ] is [ true ] .
E.g. ,
{ [
let ( ) =
let f x = x = ' c ' in
let before , rest = split_at f ( of_string " abcdef " ) in
assert ( " ab " = to_string before ) ;
assert ( " cdef " = to_string rest ) ;
let before , rest = split_at f ( of_string " cab " ) in
assert ( " " = to_string before ) ;
assert ( " cab " = to_string rest ) ;
let before , rest = split_at f ( of_string " aaa " ) in
assert ( " aaa " = to_string before ) ;
assert ( " " = to_string rest )
] }
which [f] is [false] and [rest] is remainder, including the first character
for which [f] is [true].
E.g.,
{[
let () =
let f x = x = 'c' in
let before, rest = split_at f (of_string "abcdef") in
assert ("ab" = to_string before);
assert ("cdef" = to_string rest);
let before, rest = split_at f (of_string "cab") in
assert ("" = to_string before);
assert ("cab" = to_string rest);
let before, rest = split_at f (of_string "aaa") in
assert ("aaa" = to_string before);
assert ("" = to_string rest)
]}
*)
val fold_left : (char -> 'a -> 'a) -> 'a -> t -> 'a
val for_all : (char -> bool) -> t -> bool
val exists : (char -> bool) -> t -> bool
val is_empty : t -> bool
val get_offset : t -> int
val sub : len:int -> t -> t
val trim : t -> t
(** [trim s] returns the slice that skips any whitespace at the start
or the end of [s]. *)
| null |
https://raw.githubusercontent.com/ocaml/omd/8cc423be8d090cae230dfa1307602ad7ea1b7db8/src/strSlice.mli
|
ocaml
|
Implementation of string slices over a base string via an offset
* [uncons s] is [Some (h, t)] where [h] is [head s] and [t] is [tail s],
or [None] if [is_empty s]
* [last s] is the [Some c] if [c] is the last character of [s], or else [None] if [s] is empty
* [drop_last s] is the [s] without its last character
* [drop_while f s] is [s] with the longest prefix for which [f] is true for
every character dropped
* [drop_last_while f s] is [s] with the longest suffix for which [f] is true for
every character dropped
* [trim s] returns the slice that skips any whitespace at the start
or the end of [s].
|
type t
val of_string : ?off:int -> string -> t
val to_string : t -> string
val offset : int -> t -> t
val lexbuf : t -> Lexing.lexbuf
val contains : string -> t -> bool
val length : t -> int
val index : (char -> bool) -> t -> int option
* [ index c s ] is [ Some i ] where [ i ] is the index of the character in [ s ] for
which [ f ] is first true , or [ None ] if [ f ] holds for no characters in [ s ] .
which [f] is first true, or [None] if [f] holds for no characters in [s]. *)
val index_unescaped : char -> t -> int option
* [ index_unescaped c s ] is [ Some i ] where [ i ] is index of the first
occurrence of the character [ c ] in [ s ] that is not preceeded by a
backslash [ ' \\ ' ] and not within a verbatim inline , or [ None ] if
there is no such [ c ] in [ s ] .
occurrence of the character [c] in [s] that is not preceeded by a
backslash ['\\'] and not within a verbatim inline, or [None] if
there is no such [c] in [s]. *)
val print : Format.formatter -> t -> unit
val head : t -> char option
val tail : t -> t
val uncons : t -> (char * t) option
val last : t -> char option
val drop_last : t -> t
val take : int -> t -> char list
* [ take n s ] is a list of the first [ n ] characters of [ s ]
val take_prefix : int -> t -> t
* [ take_prefix n s ] is the slice consisting of the first [ n ]
characters of [ s ] .
characters of [s]. *)
val drop : int -> t -> t
* [ drop n s ] is [ s ] with the first [ n ] characters dropped
val drop_while : (char -> bool) -> t -> t
val drop_last_while : (char -> bool) -> t -> t
val split_at : (char -> bool) -> t -> t * t
* [ split_at f s ] is [ ( taken , rest ) ] where [ taken ] is the prefix of [ s ] for
which [ f ] is [ false ] and [ rest ] is remainder , including the first character
for which [ f ] is [ true ] .
E.g. ,
{ [
let ( ) =
let f x = x = ' c ' in
let before , rest = split_at f ( of_string " abcdef " ) in
assert ( " ab " = to_string before ) ;
assert ( " cdef " = to_string rest ) ;
let before , rest = split_at f ( of_string " cab " ) in
assert ( " " = to_string before ) ;
assert ( " cab " = to_string rest ) ;
let before , rest = split_at f ( of_string " aaa " ) in
assert ( " aaa " = to_string before ) ;
assert ( " " = to_string rest )
] }
which [f] is [false] and [rest] is remainder, including the first character
for which [f] is [true].
E.g.,
{[
let () =
let f x = x = 'c' in
let before, rest = split_at f (of_string "abcdef") in
assert ("ab" = to_string before);
assert ("cdef" = to_string rest);
let before, rest = split_at f (of_string "cab") in
assert ("" = to_string before);
assert ("cab" = to_string rest);
let before, rest = split_at f (of_string "aaa") in
assert ("aaa" = to_string before);
assert ("" = to_string rest)
]}
*)
val fold_left : (char -> 'a -> 'a) -> 'a -> t -> 'a
val for_all : (char -> bool) -> t -> bool
val exists : (char -> bool) -> t -> bool
val is_empty : t -> bool
val get_offset : t -> int
val sub : len:int -> t -> t
val trim : t -> t
|
52027bf9faa9383c4b37a89a6292d58bdb35da7f3467930d920ce9a515f174fd
|
soulomoon/SICP
|
Exercise 2.84.scm
|
(load "/home/soulomoon/Documents/git/SICP/Chapter2/source.scm")
Exercise 2.84 : Using the raise operation of Exercise 2.83 , modify the apply - generic procedure so that it coerces its arguments to have the same type by the method of successive raising , as discussed in this section . You will need to devise a way to test which of two types is higher in the tower . Do this in a manner that is “ compatible ” with the rest of the system and will not lead to problems in adding new levels to the tower .
(define (apply-generic op . args)
(let ((type-tags (map type-tag args)))
(let ((proc (get op type-tags)))
(if proc
(apply proc (map contents args))
(cond
((> (length args) 2)
(apply apply-generic
(cons op
(list (car args)
(apply apply-generic
(cons op
(cdr args)))) )))
((= (length args) 2)
(let ((type1 (car type-tags))
(type2 (cadr type-tags))
(a1 (car args))
(a2 (cadr args)))
(let ((level1 (get-level type1 'level))
(level2 (get-level type2 'level)))
(cond
((< level1 level2)
(apply-generic
op (raise a1) a2))
((> level1 level2)
(apply-generic
op a1 (raise a2)))
(else
(error
"No method for
these types"
(list
op
type-tags)))))))
(else (error
"No method for these types"
(list op type-tags))))))))
(define (install_transform_package)
(define integer->rational
(lambda (x) (make-rational (cdr x) 1))
)
(define rational->scheme-number
(lambda (x) (div (numer x) (denom x)))
)
(define scheme-number->complex
(lambda (x) (make-complex-from-real-imag x 0))
)
(define complex->scheme-number
(lambda (x) (real-part x))
)
(put-coercion 'integer 'rational
integer->rational)
(put-coercion 'rational 'scheme-number
rational->scheme-number)
(put-coercion 'scheme-number 'complex
scheme-number->complex)
(put-coercion 'integer 'raise
integer->rational)
(put-coercion 'scheme-number 'raise
scheme-number->complex)
(put-coercion 'rational 'raise
rational->scheme-number)
(put-level 'integer 'level 1)
(put-level 'rational 'level 2)
(put-level 'scheme-number 'level 3)
(put-level 'complex 'level 4)
'install_transform_done)
(install_transform_package)
(define (raise x)
(let ((raise (get-coercion (type-tag x) 'raise)))
(if raise
(raise x)
(error
"No raise for this types"
(type-tag x))
)
)
)
; (define (drop x)
; )
(display (make-integer 1.1))(newline)
(define a (make-complex-from-real-imag 0 0))
(define b (make-complex-from-real-imag 24 5))
(define c (make-rational 0 3))
(define d (make-rational 1 3))
(define e (make-integer 3.5))
(define f (make-integer 4))
; (raise a)
; (raise b)
(display (raise d))(newline)
(display (raise (raise c)))(newline)
(display (raise 1))(newline)
(display (raise 1))(newline)
(display (add 1 a))(newline)
(display (add 1 e))(newline)
(display (add c e))(newline)
Welcome to , version 6.7 [ 3 m ] .
Language : SICP ( PLaneT 1.18 ) ; memory limit : 128 MB .
; 'install_transform_done
( integer . 1.0 )
1/3
( complex rectangular 0 . 0 )
( complex rectangular 1 . 0 )
( complex rectangular 1 . 0 )
( complex rectangular 1 . 0 )
5.0
( rational 4.0 . 1.0 )
; >
| null |
https://raw.githubusercontent.com/soulomoon/SICP/1c6cbf5ecf6397eaeb990738a938d48c193af1bb/Chapter2/Exercise%202.84.scm
|
scheme
|
(define (drop x)
)
(raise a)
(raise b)
memory limit : 128 MB .
'install_transform_done
>
|
(load "/home/soulomoon/Documents/git/SICP/Chapter2/source.scm")
Exercise 2.84 : Using the raise operation of Exercise 2.83 , modify the apply - generic procedure so that it coerces its arguments to have the same type by the method of successive raising , as discussed in this section . You will need to devise a way to test which of two types is higher in the tower . Do this in a manner that is “ compatible ” with the rest of the system and will not lead to problems in adding new levels to the tower .
(define (apply-generic op . args)
(let ((type-tags (map type-tag args)))
(let ((proc (get op type-tags)))
(if proc
(apply proc (map contents args))
(cond
((> (length args) 2)
(apply apply-generic
(cons op
(list (car args)
(apply apply-generic
(cons op
(cdr args)))) )))
((= (length args) 2)
(let ((type1 (car type-tags))
(type2 (cadr type-tags))
(a1 (car args))
(a2 (cadr args)))
(let ((level1 (get-level type1 'level))
(level2 (get-level type2 'level)))
(cond
((< level1 level2)
(apply-generic
op (raise a1) a2))
((> level1 level2)
(apply-generic
op a1 (raise a2)))
(else
(error
"No method for
these types"
(list
op
type-tags)))))))
(else (error
"No method for these types"
(list op type-tags))))))))
(define (install_transform_package)
(define integer->rational
(lambda (x) (make-rational (cdr x) 1))
)
(define rational->scheme-number
(lambda (x) (div (numer x) (denom x)))
)
(define scheme-number->complex
(lambda (x) (make-complex-from-real-imag x 0))
)
(define complex->scheme-number
(lambda (x) (real-part x))
)
(put-coercion 'integer 'rational
integer->rational)
(put-coercion 'rational 'scheme-number
rational->scheme-number)
(put-coercion 'scheme-number 'complex
scheme-number->complex)
(put-coercion 'integer 'raise
integer->rational)
(put-coercion 'scheme-number 'raise
scheme-number->complex)
(put-coercion 'rational 'raise
rational->scheme-number)
(put-level 'integer 'level 1)
(put-level 'rational 'level 2)
(put-level 'scheme-number 'level 3)
(put-level 'complex 'level 4)
'install_transform_done)
(install_transform_package)
(define (raise x)
(let ((raise (get-coercion (type-tag x) 'raise)))
(if raise
(raise x)
(error
"No raise for this types"
(type-tag x))
)
)
)
(display (make-integer 1.1))(newline)
(define a (make-complex-from-real-imag 0 0))
(define b (make-complex-from-real-imag 24 5))
(define c (make-rational 0 3))
(define d (make-rational 1 3))
(define e (make-integer 3.5))
(define f (make-integer 4))
(display (raise d))(newline)
(display (raise (raise c)))(newline)
(display (raise 1))(newline)
(display (raise 1))(newline)
(display (add 1 a))(newline)
(display (add 1 e))(newline)
(display (add c e))(newline)
Welcome to , version 6.7 [ 3 m ] .
( integer . 1.0 )
1/3
( complex rectangular 0 . 0 )
( complex rectangular 1 . 0 )
( complex rectangular 1 . 0 )
( complex rectangular 1 . 0 )
5.0
( rational 4.0 . 1.0 )
|
4ec93ab9862cb157581bc1d16cf082ea0aee0e996fce457990fb0ea2d039438e
|
Ramarren/cells
|
01a-dataflow.lisp
|
(defpackage #:tu-dataflow (:use :cl :cells))
(in-package #:tu-dataflow)
(defmodel rectangle ()
((len :initarg :len :accessor len
:initform (c? (* 2 (width self))))
(width :initarg :width :initform nil :accessor width))
(:default-initargs
:width (c? (/ (len self) 2))))
#+test
(let ((r (make-instance 'rectangle :len (c-in 42))))
(cells::ct-assert (eql 21 (width r)))
make sure we did not break SETF , which must return the value set
(cells::ct-assert (eql 500 (width r)))) ;; make sure new value propagated
| null |
https://raw.githubusercontent.com/Ramarren/cells/cced2e55c363572914358c0a693ebac2caed4e22/tutorial/01a-dataflow.lisp
|
lisp
|
make sure new value propagated
|
(defpackage #:tu-dataflow (:use :cl :cells))
(in-package #:tu-dataflow)
(defmodel rectangle ()
((len :initarg :len :accessor len
:initform (c? (* 2 (width self))))
(width :initarg :width :initform nil :accessor width))
(:default-initargs
:width (c? (/ (len self) 2))))
#+test
(let ((r (make-instance 'rectangle :len (c-in 42))))
(cells::ct-assert (eql 21 (width r)))
make sure we did not break SETF , which must return the value set
|
3bd08530800b03c752c8a7ec1b0495d0da3b9e3017e2e7f52c4d1a9f5f5b0a2f
|
poscat0x04/telegram-types
|
Sticker.hs
|
module Web.Telegram.Types.Internal.Sticker where
import Common
import Web.Telegram.Types.Internal.MaskPosition
import Web.Telegram.Types.Internal.PhotoSize
data Sticker = Sticker
{ fileId :: Text,
fileUniqueId :: Text,
width :: Int,
height :: Int,
isAnimated :: Bool,
thumb :: Maybe PhotoSize,
emoji :: Maybe Text,
setName :: Maybe Text,
maskPosition :: Maybe MaskPosition,
fileSize :: Maybe Int
}
deriving stock (Show, Eq)
mkLabel ''Sticker
deriveJSON snake ''Sticker
| null |
https://raw.githubusercontent.com/poscat0x04/telegram-types/c09ccc81cff10399538894cf2d1273022c797e18/src/Web/Telegram/Types/Internal/Sticker.hs
|
haskell
|
module Web.Telegram.Types.Internal.Sticker where
import Common
import Web.Telegram.Types.Internal.MaskPosition
import Web.Telegram.Types.Internal.PhotoSize
data Sticker = Sticker
{ fileId :: Text,
fileUniqueId :: Text,
width :: Int,
height :: Int,
isAnimated :: Bool,
thumb :: Maybe PhotoSize,
emoji :: Maybe Text,
setName :: Maybe Text,
maskPosition :: Maybe MaskPosition,
fileSize :: Maybe Int
}
deriving stock (Show, Eq)
mkLabel ''Sticker
deriveJSON snake ''Sticker
|
|
37bd3a3fe2476de576229d05845c8ae3381f9c26abd4917e924d878184d1f0af
|
polymeris/cljs-aws
|
kinesis_example.cljs
|
(ns cljs-aws.kinesis-example
(:require [cljs-aws.kinesis :as kinesis]
[cljs.core.async :refer [go <! timeout]]
[cljs-aws.examples-util :as util :refer [throw-or-print]]))
(enable-console-print!)
(def stream-name "my-stream")
(defn -main
"Example cljs script using cljs-aws."
[& args]
(go
(util/override-endpoint-with-env)
(throw-or-print (<! (kinesis/create-stream {:stream-name stream-name, :shard-count 1})))
(throw-or-print (<! (kinesis/list-streams {})))
(throw-or-print (<! (kinesis/describe-stream {:stream-name stream-name})))
(println "Waiting for stream to be created...")
(loop []
(<! (timeout 3000))
(let [stream-status (-> (<! (kinesis/describe-stream {:stream-name stream-name}))
:stream-description
:stream-status)]
(println "Stream is" stream-status)
(when (= stream-status "CREATING") (recur))))
(throw-or-print (<! (kinesis/put-record {:stream-name stream-name
:data "my data"
:partition-key (str (random-uuid))})))
(throw-or-print (<! (kinesis/put-records {:stream-name stream-name
:records [{:partition-key "x5h2ch", :data "foo"}
{:partition-key "x5j3ak", :data "quux"}]})))
(let [shard-iterator (-> (<! (kinesis/get-shard-iterator {:stream-name stream-name
:shard-id "shardId-000000000000"
:shard-iterator-type "TRIM_HORIZON"}))
(throw-or-print)
:shard-iterator)]
(throw-or-print (<! (kinesis/get-records {:shard-iterator shard-iterator}))))
(throw-or-print (<! (kinesis/delete-stream {:stream-name stream-name})))))
(set! *main-cli-fn* -main)
| null |
https://raw.githubusercontent.com/polymeris/cljs-aws/3326e7c4db4dfc36dcb80770610c14c8a7fd0d66/node-examples/src/cljs_aws/kinesis_example.cljs
|
clojure
|
(ns cljs-aws.kinesis-example
(:require [cljs-aws.kinesis :as kinesis]
[cljs.core.async :refer [go <! timeout]]
[cljs-aws.examples-util :as util :refer [throw-or-print]]))
(enable-console-print!)
(def stream-name "my-stream")
(defn -main
"Example cljs script using cljs-aws."
[& args]
(go
(util/override-endpoint-with-env)
(throw-or-print (<! (kinesis/create-stream {:stream-name stream-name, :shard-count 1})))
(throw-or-print (<! (kinesis/list-streams {})))
(throw-or-print (<! (kinesis/describe-stream {:stream-name stream-name})))
(println "Waiting for stream to be created...")
(loop []
(<! (timeout 3000))
(let [stream-status (-> (<! (kinesis/describe-stream {:stream-name stream-name}))
:stream-description
:stream-status)]
(println "Stream is" stream-status)
(when (= stream-status "CREATING") (recur))))
(throw-or-print (<! (kinesis/put-record {:stream-name stream-name
:data "my data"
:partition-key (str (random-uuid))})))
(throw-or-print (<! (kinesis/put-records {:stream-name stream-name
:records [{:partition-key "x5h2ch", :data "foo"}
{:partition-key "x5j3ak", :data "quux"}]})))
(let [shard-iterator (-> (<! (kinesis/get-shard-iterator {:stream-name stream-name
:shard-id "shardId-000000000000"
:shard-iterator-type "TRIM_HORIZON"}))
(throw-or-print)
:shard-iterator)]
(throw-or-print (<! (kinesis/get-records {:shard-iterator shard-iterator}))))
(throw-or-print (<! (kinesis/delete-stream {:stream-name stream-name})))))
(set! *main-cli-fn* -main)
|
|
310abe1c6838367f7fc46ca9c75a1cd497be1346463688ba6464073b232e0f1b
|
igorhvr/bedlam
|
eval.scm
|
" eval.scm " , proposed by ( Bill ) for R5RS .
Copyright ( C ) 1997 , 1998
;
;Permission to copy this software, to modify it, to redistribute it,
;to distribute modified versions, and to use it for any purpose is
;granted, subject to the following restrictions and understandings.
;
1 . Any copy made of this software must include this copyright notice
;in full.
;
2 . I have made no warranty or representation that the operation of
;this software will be error-free, and I am under no obligation to
;provide any services, by way of maintenance, update, or otherwise.
;
3 . In conjunction with products arising from the use of this
;material, there shall be no use of my name in any advertising,
;promotional, or sales literature without prior written consent in
;each case.
;;; Rather than worry over the status of all the optional procedures,
;;; just require as many as possible.
(require 'rev4-optional-procedures)
(require 'dynamic-wind)
(require 'transcript)
(require 'with-file)
(require 'values)
(define eval:make-environment
(let ((eval-1 slib:eval))
(lambda (identifiers)
((lambda args args)
#f
identifiers
(lambda (expression)
(eval-1 `(lambda ,identifiers ,expression)))))))
(define eval:capture-environment!
(let ((set-car! set-car!)
(eval-1 slib:eval)
(apply apply))
(lambda (environment)
(set-car!
environment
(apply (lambda (environment-values identifiers procedure)
(eval-1 `((lambda args args) ,@identifiers)))
environment)))))
;@
(define interaction-environment
(let ((env (eval:make-environment '())))
(lambda () env)))
@ null - environment is set by first call to scheme - report - environment at
;;; the end of this file.
(define null-environment #f)
;@
(define scheme-report-environment
(let* ((r4rs-procedures
(append
(cond ((provided? 'inexact)
(append
'(acos angle asin atan cos exact->inexact exp
expt imag-part inexact->exact log magnitude
make-polar make-rectangular real-part sin
sqrt tan)
(if (let ((n (string->number "1/3")))
(and (number? n) (exact? n)))
'(denominator numerator)
'())))
(else '()))
(cond ((provided? 'rationalize)
'(rationalize))
(else '()))
(cond ((provided? 'delay)
'(force))
(else '()))
(cond ((provided? 'char-ready?)
'(char-ready?))
(else '()))
'(* + - / < <= = > >= abs append apply assoc assq assv boolean?
caaaar caaadr caaar caadar caaddr caadr caar cadaar cadadr cadar
caddar cadddr caddr cadr call-with-current-continuation
call-with-input-file call-with-output-file car cdaaar cdaadr
cdaar cdadar cdaddr cdadr cdar cddaar cddadr cddar cdddar cddddr
cdddr cddr cdr ceiling char->integer char-alphabetic? char-ci<=?
char-ci<? char-ci=? char-ci>=? char-ci>? char-downcase
char-lower-case? char-numeric? char-upcase char-upper-case?
char-whitespace? char<=? char<? char=? char>=? char>? char?
close-input-port close-output-port complex? cons
current-input-port current-output-port display eof-object? eq?
equal? eqv? even? exact? floor for-each gcd inexact?
input-port? integer->char integer? lcm length list list->string
list->vector list-ref list-tail list? load make-string
make-vector map max member memq memv min modulo negative?
newline not null? number->string number? odd? open-input-file
open-output-file output-port? pair? peek-char positive?
procedure? quotient rational? read read-char real? remainder
reverse round set-car! set-cdr! string string->list
string->number string->symbol string-append string-ci<=?
string-ci<? string-ci=? string-ci>=? string-ci>? string-copy
string-fill! string-length string-ref string-set! string<=?
string<? string=? string>=? string>? string? substring
symbol->string symbol? transcript-off transcript-on truncate
vector vector->list vector-fill! vector-length vector-ref
vector-set! vector? with-input-from-file with-output-to-file
write write-char zero?
)))
(r5rs-procedures
(append
'(call-with-values dynamic-wind eval interaction-environment
null-environment scheme-report-environment values)
r4rs-procedures))
(r4rs-environment (eval:make-environment r4rs-procedures))
(r5rs-environment (eval:make-environment r5rs-procedures)))
(let ((car car))
(lambda (version)
(cond ((car r5rs-environment))
(else
(let ((null-env (eval:make-environment r5rs-procedures)))
(set-car! null-env (map (lambda (i) #f) r5rs-procedures))
(set! null-environment (lambda version null-env)))
(eval:capture-environment! r4rs-environment)
(eval:capture-environment! r5rs-environment)))
(case version
((4) r4rs-environment)
((5) r5rs-environment)
(else (slib:error 'eval 'version version 'not 'available)))))))
;@
(define eval
(let ((eval-1 slib:eval)
(apply apply)
(null? null?)
(eq? eq?))
(lambda (expression . environment)
(if (null? environment) (eval-1 expression)
(apply
(lambda (environment)
(if (eq? (interaction-environment) environment) (eval-1 expression)
(apply (lambda (environment-values identifiers procedure)
(apply (procedure expression) environment-values))
environment)))
environment)))))
(set! slib:eval eval)
Now that all the R5RS procedures are defined , capture r5rs - environment .
(and (scheme-report-environment 5) #t)
| null |
https://raw.githubusercontent.com/igorhvr/bedlam/b62e0d047105bb0473bdb47c58b23f6ca0f79a4e/iasylum/slib/3b2/eval.scm
|
scheme
|
Permission to copy this software, to modify it, to redistribute it,
to distribute modified versions, and to use it for any purpose is
granted, subject to the following restrictions and understandings.
in full.
this software will be error-free, and I am under no obligation to
provide any services, by way of maintenance, update, or otherwise.
material, there shall be no use of my name in any advertising,
promotional, or sales literature without prior written consent in
each case.
Rather than worry over the status of all the optional procedures,
just require as many as possible.
@
the end of this file.
@
@
|
" eval.scm " , proposed by ( Bill ) for R5RS .
Copyright ( C ) 1997 , 1998
1 . Any copy made of this software must include this copyright notice
2 . I have made no warranty or representation that the operation of
3 . In conjunction with products arising from the use of this
(require 'rev4-optional-procedures)
(require 'dynamic-wind)
(require 'transcript)
(require 'with-file)
(require 'values)
(define eval:make-environment
(let ((eval-1 slib:eval))
(lambda (identifiers)
((lambda args args)
#f
identifiers
(lambda (expression)
(eval-1 `(lambda ,identifiers ,expression)))))))
(define eval:capture-environment!
(let ((set-car! set-car!)
(eval-1 slib:eval)
(apply apply))
(lambda (environment)
(set-car!
environment
(apply (lambda (environment-values identifiers procedure)
(eval-1 `((lambda args args) ,@identifiers)))
environment)))))
(define interaction-environment
(let ((env (eval:make-environment '())))
(lambda () env)))
@ null - environment is set by first call to scheme - report - environment at
(define null-environment #f)
(define scheme-report-environment
(let* ((r4rs-procedures
(append
(cond ((provided? 'inexact)
(append
'(acos angle asin atan cos exact->inexact exp
expt imag-part inexact->exact log magnitude
make-polar make-rectangular real-part sin
sqrt tan)
(if (let ((n (string->number "1/3")))
(and (number? n) (exact? n)))
'(denominator numerator)
'())))
(else '()))
(cond ((provided? 'rationalize)
'(rationalize))
(else '()))
(cond ((provided? 'delay)
'(force))
(else '()))
(cond ((provided? 'char-ready?)
'(char-ready?))
(else '()))
'(* + - / < <= = > >= abs append apply assoc assq assv boolean?
caaaar caaadr caaar caadar caaddr caadr caar cadaar cadadr cadar
caddar cadddr caddr cadr call-with-current-continuation
call-with-input-file call-with-output-file car cdaaar cdaadr
cdaar cdadar cdaddr cdadr cdar cddaar cddadr cddar cdddar cddddr
cdddr cddr cdr ceiling char->integer char-alphabetic? char-ci<=?
char-ci<? char-ci=? char-ci>=? char-ci>? char-downcase
char-lower-case? char-numeric? char-upcase char-upper-case?
char-whitespace? char<=? char<? char=? char>=? char>? char?
close-input-port close-output-port complex? cons
current-input-port current-output-port display eof-object? eq?
equal? eqv? even? exact? floor for-each gcd inexact?
input-port? integer->char integer? lcm length list list->string
list->vector list-ref list-tail list? load make-string
make-vector map max member memq memv min modulo negative?
newline not null? number->string number? odd? open-input-file
open-output-file output-port? pair? peek-char positive?
procedure? quotient rational? read read-char real? remainder
reverse round set-car! set-cdr! string string->list
string->number string->symbol string-append string-ci<=?
string-ci<? string-ci=? string-ci>=? string-ci>? string-copy
string-fill! string-length string-ref string-set! string<=?
string<? string=? string>=? string>? string? substring
symbol->string symbol? transcript-off transcript-on truncate
vector vector->list vector-fill! vector-length vector-ref
vector-set! vector? with-input-from-file with-output-to-file
write write-char zero?
)))
(r5rs-procedures
(append
'(call-with-values dynamic-wind eval interaction-environment
null-environment scheme-report-environment values)
r4rs-procedures))
(r4rs-environment (eval:make-environment r4rs-procedures))
(r5rs-environment (eval:make-environment r5rs-procedures)))
(let ((car car))
(lambda (version)
(cond ((car r5rs-environment))
(else
(let ((null-env (eval:make-environment r5rs-procedures)))
(set-car! null-env (map (lambda (i) #f) r5rs-procedures))
(set! null-environment (lambda version null-env)))
(eval:capture-environment! r4rs-environment)
(eval:capture-environment! r5rs-environment)))
(case version
((4) r4rs-environment)
((5) r5rs-environment)
(else (slib:error 'eval 'version version 'not 'available)))))))
(define eval
(let ((eval-1 slib:eval)
(apply apply)
(null? null?)
(eq? eq?))
(lambda (expression . environment)
(if (null? environment) (eval-1 expression)
(apply
(lambda (environment)
(if (eq? (interaction-environment) environment) (eval-1 expression)
(apply (lambda (environment-values identifiers procedure)
(apply (procedure expression) environment-values))
environment)))
environment)))))
(set! slib:eval eval)
Now that all the R5RS procedures are defined , capture r5rs - environment .
(and (scheme-report-environment 5) #t)
|
82c7890f902c1a4ea452037570c4da03973414b072259186b7f623e2b18be8b4
|
input-output-hk/cardano-sl
|
Payload.hs
|
module Pos.Chain.Ssc.Payload
( SscPayload (..)
, checkSscPayload
, spVss
) where
import Universum hiding (id)
import Control.Monad.Except (MonadError)
import qualified Data.HashMap.Strict as HM
import Data.SafeCopy (base, deriveSafeCopySimple)
import Data.Text.Lazy.Builder (Builder)
import Formatting (Format, bprint, int, (%))
import qualified Formatting.Buildable as Buildable
import Serokell.Util (listJson)
import Pos.Crypto (ProtocolMagic, shortHashF)
import Pos.Binary.Class (Cons (..), Field (..), deriveIndexedBi)
import Pos.Chain.Ssc.CommitmentsMap
import Pos.Chain.Ssc.OpeningsMap
import Pos.Chain.Ssc.SharesMap
import Pos.Chain.Ssc.VssCertificate (VssCertificate (vcExpiryEpoch))
import Pos.Chain.Ssc.VssCertificatesMap
import Pos.Util.Util (cborError)
-- | Payload included into blocks.
data SscPayload
= CommitmentsPayload
!CommitmentsMap
!VssCertificatesMap
| OpeningsPayload
!OpeningsMap
!VssCertificatesMap
| SharesPayload
!SharesMap
!VssCertificatesMap
| CertificatesPayload
!VssCertificatesMap
deriving (Eq, Show, Generic)
instance NFData SscPayload
instance Buildable SscPayload where
build gp
| isEmptySscPayload gp = " no SSC payload"
| otherwise =
case gp of
CommitmentsPayload comms certs ->
formatTwo formatCommitments comms certs
OpeningsPayload openings certs ->
formatTwo formatOpenings openings certs
SharesPayload shares certs ->
formatTwo formatShares shares certs
CertificatesPayload certs -> formatCertificates certs
where
formatIfNotNull
:: Container c
=> Format Builder (c -> Builder) -> c -> Builder
formatIfNotNull formatter l
| null l = mempty
| otherwise = bprint formatter l
formatCommitments (getCommitmentsMap -> comms) =
formatIfNotNull
(" commitments from: " %listJson % "\n")
(HM.keys comms)
formatOpenings openings =
formatIfNotNull
(" openings from: " %listJson % "\n")
(HM.keys openings)
formatShares shares =
formatIfNotNull
(" shares from: " %listJson % "\n")
(HM.keys shares)
formatCertificates (getVssCertificatesMap -> certs) =
formatIfNotNull
(" certificates from: " %listJson % "\n")
(map formatVssCert $ HM.toList certs)
formatVssCert (id, cert) =
bprint (shortHashF%":"%int) id (vcExpiryEpoch cert)
formatTwo formatter hm certs =
mconcat [formatter hm, formatCertificates certs]
isEmptySscPayload :: SscPayload -> Bool
isEmptySscPayload (CommitmentsPayload comms certs) = null comms && null certs
isEmptySscPayload (OpeningsPayload opens certs) = null opens && null certs
isEmptySscPayload (SharesPayload shares certs) = null shares && null certs
isEmptySscPayload (CertificatesPayload certs) = null certs
spVss :: SscPayload -> VssCertificatesMap
spVss (CommitmentsPayload _ vss) = vss
spVss (OpeningsPayload _ vss) = vss
spVss (SharesPayload _ vss) = vss
spVss (CertificatesPayload vss) = vss
checkSscPayload
:: MonadError Text m
=> ProtocolMagic
-> SscPayload
-> m ()
checkSscPayload pm payload = checkVssCertificatesMap pm (spVss payload)
TH - generated instances go to the end of the file
deriveIndexedBi ''SscPayload [
Cons 'CommitmentsPayload [
Field [| 0 :: CommitmentsMap |],
Field [| 1 :: VssCertificatesMap |] ],
Cons 'OpeningsPayload [
Field [| 0 :: OpeningsMap |],
Field [| 1 :: VssCertificatesMap |] ],
Cons 'SharesPayload [
Field [| 0 :: SharesMap |],
Field [| 1 :: VssCertificatesMap |] ],
Cons 'CertificatesPayload [
Field [| 0 :: VssCertificatesMap |] ]
]
deriveSafeCopySimple 0 'base ''SscPayload
| null |
https://raw.githubusercontent.com/input-output-hk/cardano-sl/1499214d93767b703b9599369a431e67d83f10a2/chain/src/Pos/Chain/Ssc/Payload.hs
|
haskell
|
| Payload included into blocks.
|
module Pos.Chain.Ssc.Payload
( SscPayload (..)
, checkSscPayload
, spVss
) where
import Universum hiding (id)
import Control.Monad.Except (MonadError)
import qualified Data.HashMap.Strict as HM
import Data.SafeCopy (base, deriveSafeCopySimple)
import Data.Text.Lazy.Builder (Builder)
import Formatting (Format, bprint, int, (%))
import qualified Formatting.Buildable as Buildable
import Serokell.Util (listJson)
import Pos.Crypto (ProtocolMagic, shortHashF)
import Pos.Binary.Class (Cons (..), Field (..), deriveIndexedBi)
import Pos.Chain.Ssc.CommitmentsMap
import Pos.Chain.Ssc.OpeningsMap
import Pos.Chain.Ssc.SharesMap
import Pos.Chain.Ssc.VssCertificate (VssCertificate (vcExpiryEpoch))
import Pos.Chain.Ssc.VssCertificatesMap
import Pos.Util.Util (cborError)
data SscPayload
= CommitmentsPayload
!CommitmentsMap
!VssCertificatesMap
| OpeningsPayload
!OpeningsMap
!VssCertificatesMap
| SharesPayload
!SharesMap
!VssCertificatesMap
| CertificatesPayload
!VssCertificatesMap
deriving (Eq, Show, Generic)
instance NFData SscPayload
instance Buildable SscPayload where
build gp
| isEmptySscPayload gp = " no SSC payload"
| otherwise =
case gp of
CommitmentsPayload comms certs ->
formatTwo formatCommitments comms certs
OpeningsPayload openings certs ->
formatTwo formatOpenings openings certs
SharesPayload shares certs ->
formatTwo formatShares shares certs
CertificatesPayload certs -> formatCertificates certs
where
formatIfNotNull
:: Container c
=> Format Builder (c -> Builder) -> c -> Builder
formatIfNotNull formatter l
| null l = mempty
| otherwise = bprint formatter l
formatCommitments (getCommitmentsMap -> comms) =
formatIfNotNull
(" commitments from: " %listJson % "\n")
(HM.keys comms)
formatOpenings openings =
formatIfNotNull
(" openings from: " %listJson % "\n")
(HM.keys openings)
formatShares shares =
formatIfNotNull
(" shares from: " %listJson % "\n")
(HM.keys shares)
formatCertificates (getVssCertificatesMap -> certs) =
formatIfNotNull
(" certificates from: " %listJson % "\n")
(map formatVssCert $ HM.toList certs)
formatVssCert (id, cert) =
bprint (shortHashF%":"%int) id (vcExpiryEpoch cert)
formatTwo formatter hm certs =
mconcat [formatter hm, formatCertificates certs]
isEmptySscPayload :: SscPayload -> Bool
isEmptySscPayload (CommitmentsPayload comms certs) = null comms && null certs
isEmptySscPayload (OpeningsPayload opens certs) = null opens && null certs
isEmptySscPayload (SharesPayload shares certs) = null shares && null certs
isEmptySscPayload (CertificatesPayload certs) = null certs
spVss :: SscPayload -> VssCertificatesMap
spVss (CommitmentsPayload _ vss) = vss
spVss (OpeningsPayload _ vss) = vss
spVss (SharesPayload _ vss) = vss
spVss (CertificatesPayload vss) = vss
checkSscPayload
:: MonadError Text m
=> ProtocolMagic
-> SscPayload
-> m ()
checkSscPayload pm payload = checkVssCertificatesMap pm (spVss payload)
TH - generated instances go to the end of the file
deriveIndexedBi ''SscPayload [
Cons 'CommitmentsPayload [
Field [| 0 :: CommitmentsMap |],
Field [| 1 :: VssCertificatesMap |] ],
Cons 'OpeningsPayload [
Field [| 0 :: OpeningsMap |],
Field [| 1 :: VssCertificatesMap |] ],
Cons 'SharesPayload [
Field [| 0 :: SharesMap |],
Field [| 1 :: VssCertificatesMap |] ],
Cons 'CertificatesPayload [
Field [| 0 :: VssCertificatesMap |] ]
]
deriveSafeCopySimple 0 'base ''SscPayload
|
5689c0c68105c21608fa91f8d2110bec74409946aa1e35a1bc4b0d574d763e29
|
ChrisPenner/wc
|
Strict.hs
|
module Strict where
import qualified Data.ByteString.Char8 as BS
import Types
import Control.Monad
import Control.Arrow
import Data.Traversable
strictBytestream :: [FilePath] -> IO [(FilePath, Counts)]
strictBytestream paths = for paths $ \fp -> do
count <- strictBytestreamCountFile <$> BS.readFile fp
return (fp, count)
strictBytestreamCountFile :: BS.ByteString -> Counts
strictBytestreamCountFile = BS.foldl' (flip (mappend . countChar)) mempty
| null |
https://raw.githubusercontent.com/ChrisPenner/wc/7a77329164c7b8e7f7d511539e75bce1a74651af/src/Strict.hs
|
haskell
|
module Strict where
import qualified Data.ByteString.Char8 as BS
import Types
import Control.Monad
import Control.Arrow
import Data.Traversable
strictBytestream :: [FilePath] -> IO [(FilePath, Counts)]
strictBytestream paths = for paths $ \fp -> do
count <- strictBytestreamCountFile <$> BS.readFile fp
return (fp, count)
strictBytestreamCountFile :: BS.ByteString -> Counts
strictBytestreamCountFile = BS.foldl' (flip (mappend . countChar)) mempty
|
|
e26ba3d2caf348d1a41631f48501db46617d10c537382b3116f6e52ade0ae73b
|
ndmitchell/catch
|
Apply2.hs
|
module Apply2 where
main = apply id False True
apply f x y = f x && f y
| null |
https://raw.githubusercontent.com/ndmitchell/catch/5d834416a27b4df3f7ce7830c4757d4505aaf96e/examples/Example/Apply2.hs
|
haskell
|
module Apply2 where
main = apply id False True
apply f x y = f x && f y
|
|
a4a200bf6c77fc21872565fdab11309a70a912ba0ab5d733a70b2cb5454ec678
|
locusmath/locus
|
object.clj
|
(ns locus.lawvere.metric.core.object
(:require [locus.set.logic.core.set :refer :all]
[locus.set.logic.limit.product :refer :all]
[locus.set.logic.structure.protocols :refer :all]
[locus.set.mapping.general.core.object :refer :all]
[locus.con.core.setpart :refer :all]
[locus.con.core.object :refer [projection]]
[locus.set.quiver.structure.core.protocols :refer :all]
[locus.set.copresheaf.structure.core.protocols :refer :all]
[locus.set.quiver.relation.binary.product :refer :all]
[locus.set.quiver.binary.core.object :refer :all]
[locus.set.copresheaf.quiver.unital.object :refer :all]
[locus.algebra.category.core.object :refer :all]))
; Categories can be seen as intuitive abstractions of motion and of change. A morphism f: A -> B
is a change from one point A to another point B , in either space or time . Categories are
; the best means we have of modeling change. How fitting then that distance should be modeled
; by categories. Distances describe a property of a motion f: A -> B from a point A to another
; point B. To describe distances categorically, we can establish a hom number to each motion
; of a hom class.
; The generally accepted way of describing distances categorically was provided by Lawvere.
; A Lawvere metric is a category enriched over the monoidal category of the extended
; real numbers with addition and its usual ordering. The result are Lawvere metrics, which
; are extended pseudoquasimetrics. The more familiar types of metric spaces have to be
; introduced as special cases and so predicates are defined to deal with them.
(deftype LawvereMetric [coll distance]
ConcreteObject
(underlying-set [this] coll)
StructuredDiset
(first-set [this] (->CompleteRelation coll))
(second-set [this] coll)
StructuredQuiver
(underlying-quiver [this] (complete-relational-quiver coll))
(source-fn [this] first)
(target-fn [this] second)
(transition [this e] e)
StructuredUnitalQuiver
(underlying-unital-quiver [this] (complete-relational-unital-quiver coll))
(identity-morphism-of [this obj] (list obj obj))
ConcreteMorphism
(inputs [this] (composability-relation this))
(outputs [this] (morphisms this))
clojure.lang.IFn
(invoke [this [[a b] [c d]]] (list c b))
(applyTo [this args] (clojure.lang.AFn/applyToHelper this args)))
(derive LawvereMetric :locus.set.copresheaf.structure.core.protocols/structured-category)
; Get the underlying relations and multirelations of lawvere metrics
(defmethod underlying-relation LawvereMetric
[^LawvereMetric metric] (morphisms metric))
(defmethod underlying-multirelation LawvereMetric
[^LawvereMetric metric] (underlying-relation metric))
(defmethod visualize LawvereMetric
[^LawvereMetric metric] (visualize (underlying-relation metric)))
Get the distance between two points in a metric space
(defmulti distance (fn [metric a b] (type metric)))
(defmethod distance LawvereMetric
[^LawvereMetric metric, a, b]
((.distance metric) a b))
; Get the hom number in a distance enriched category
(defn hom-number
[metric morphism]
(distance metric (first morphism) (second morphism)))
; The discrete metric is a rather simple example in metric space theory
(defn discrete-metric
[coll]
(LawvereMetric.
coll
(fn [x y]
(if (= x y) 0 1))))
; A notable property of pseudometrics is that they can be used to describe
; the dual of the lattice of partitions of a set. This lattice is naturally
; associated to the lattice of congruences of a set.
(defn equivalence-pseudometric
[rel]
(LawvereMetric.
(vertices rel)
(fn [x y]
(if (rel (list x y))
0
1))))
(defn partition-pseudometric
[family]
(LawvereMetric.
(dimembers family)
(fn [x y]
(if (= (projection family x) (projection family y))
0
1))))
; The equivalence properties of pseudometrics can also be applied in the
; other direction so that we can get for a given pseudometric an equivalence
; relation associated to it.
(defn metric-equal?
[metric a b]
(zero? (distance metric a b)))
(defn metric-equality
[metric]
(->Universal
(fn [[a b]]
(metric-equal? metric a b))))
(defn equal-component-of
[metric x]
(set
(filter
(fn [i]
(zero? (distance metric i x)))
(underlying-set metric))))
(defn equal-components
[metric]
(let [coll (underlying-set metric)]
(set
(loop [remaining-elements coll
rval #{}]
(if (empty? remaining-elements)
rval
(let [next-element (first remaining-elements)
next-component (equal-component-of metric next-element)]
(recur
(difference remaining-elements next-component)
(conj rval next-component))))))))
; Every mapping from a set S to a lawvere metric space is going to provide an induced
; metric defined by distance between values of S under the mapping. This is the
; induced metric of the space.
(defn induced-metric
[source-set target-metric func]
(LawvereMetric.
source-set
(fn [x y]
(distance target-metric (func x) (func y)))))
; The class of metric spaces is naturally partially ordered by distance, so that
; metrics with larger distances between each of their pairs of points are larger
; than one another. This metric is the fundamental partial order upon which
; the category of metric spaces and short maps is derived.
(defn submetric?
[a b]
(let [a-elements (underlying-set a)
b-elements (underlying-set b)]
(and
(equal-universals? a-elements b-elements)
(every?
(fn [[x y]]
(<= (distance a x y)
(distance b x y)))
(cartesian-power a-elements 2)))))
; Create a space of real vectors to be used with various metrics
(defn real-vector-space
[n]
(->Universal
(fn [coll]
(and
(vector? coll)
(= (count coll) n)
(every? real-number? coll)))))
; The most common metric space
(defn euclidean-metric-space
[n]
(LawvereMetric.
(real-vector-space n)
(fn [x y]
(Math/sqrt
(apply
+
(map
(fn [i]
(let [d (- (nth x i) (nth y i))]
(* d d)))
(range n)))))))
; The taxicab metric is another kind of metric on the real numbers
(defn taxicab-metric
[n]
(LawvereMetric.
(real-vector-space n)
(fn [x y]
(apply
+
(map
(fn [i]
(let [d (- (nth x n) (nth y n))]
(if (neg? d) (- d) d)))
(range n))))))
; Get the chebyshev metric on affine space
(defn chebyshev-metric
[n]
(LawvereMetric.
(real-vector-space n)
(fn [x y]
(apply
max
(map
(fn [i]
(let [d (- (nth x n) (nth y n))]
(if (neg? d) (- d) d)))
(range n))))))
One dimensional and two dimensional euclidean spaces have corresponding
; apache commons math geometry
(def one-dimensional-euclidean-space
(euclidean-metric-space 1))
(def two-dimensional-euclidean-space
(euclidean-metric-space 2))
(def three-dimensional-euclidean-space
(euclidean-metric-space 3))
; Get the distance between components of a real vector space as a pseudometric
(defn component-distance
[n i]
(LawvereMetric.
(real-vector-space n)
(fn [x y]
(let [d (- (nth x i) (nth y i))]
(if (neg? d) (- d) d)))))
; The sequence of all distances produced by the metric.
(defn all-distances
[metric]
(seq
(map
(fn [[a b]]
(distance metric a b))
(cartesian-power (underlying-set metric) 2))))
; Ontology of metrically enriched categories
(defn lawvere-metric?
[metric]
(= (type metric) LawvereMetric))
(defn pseudoquasimetric?
[metric]
(and
(lawvere-metric? metric)
(every?
(fn [i]
(not= i ##Inf))
(all-distances metric))))
(defn pseudometric?
[metric]
(and
(pseudoquasimetric? metric)
(every?
(fn [[a b]]
(= (distance metric a b)
(distance metric b a)))
(cartesian-power (underlying-set metric) 2))))
(defn quasimetric?
[metric]
(and
(pseudoquasimetric? metric)
(every?
(fn [[a b]]
(or
(= a b)
(not= (distance metric a b) 0)))
(cartesian-power (underlying-set metric) 2))))
(defn metric?
[metric]
(and
(pseudoquasimetric? metric)
(every?
(fn [[a b]]
(and
(= (distance metric a b) (distance metric b a))
(or
(= a b)
(not= (distance metric a b) 0))))
(cartesian-power (underlying-set metric) 2))))
| null |
https://raw.githubusercontent.com/locusmath/locus/c8409c998e5b062b407b0b72a87e8ea325ae3e6a/src/clojure/locus/lawvere/metric/core/object.clj
|
clojure
|
Categories can be seen as intuitive abstractions of motion and of change. A morphism f: A -> B
the best means we have of modeling change. How fitting then that distance should be modeled
by categories. Distances describe a property of a motion f: A -> B from a point A to another
point B. To describe distances categorically, we can establish a hom number to each motion
of a hom class.
The generally accepted way of describing distances categorically was provided by Lawvere.
A Lawvere metric is a category enriched over the monoidal category of the extended
real numbers with addition and its usual ordering. The result are Lawvere metrics, which
are extended pseudoquasimetrics. The more familiar types of metric spaces have to be
introduced as special cases and so predicates are defined to deal with them.
Get the underlying relations and multirelations of lawvere metrics
Get the hom number in a distance enriched category
The discrete metric is a rather simple example in metric space theory
A notable property of pseudometrics is that they can be used to describe
the dual of the lattice of partitions of a set. This lattice is naturally
associated to the lattice of congruences of a set.
The equivalence properties of pseudometrics can also be applied in the
other direction so that we can get for a given pseudometric an equivalence
relation associated to it.
Every mapping from a set S to a lawvere metric space is going to provide an induced
metric defined by distance between values of S under the mapping. This is the
induced metric of the space.
The class of metric spaces is naturally partially ordered by distance, so that
metrics with larger distances between each of their pairs of points are larger
than one another. This metric is the fundamental partial order upon which
the category of metric spaces and short maps is derived.
Create a space of real vectors to be used with various metrics
The most common metric space
The taxicab metric is another kind of metric on the real numbers
Get the chebyshev metric on affine space
apache commons math geometry
Get the distance between components of a real vector space as a pseudometric
The sequence of all distances produced by the metric.
Ontology of metrically enriched categories
|
(ns locus.lawvere.metric.core.object
(:require [locus.set.logic.core.set :refer :all]
[locus.set.logic.limit.product :refer :all]
[locus.set.logic.structure.protocols :refer :all]
[locus.set.mapping.general.core.object :refer :all]
[locus.con.core.setpart :refer :all]
[locus.con.core.object :refer [projection]]
[locus.set.quiver.structure.core.protocols :refer :all]
[locus.set.copresheaf.structure.core.protocols :refer :all]
[locus.set.quiver.relation.binary.product :refer :all]
[locus.set.quiver.binary.core.object :refer :all]
[locus.set.copresheaf.quiver.unital.object :refer :all]
[locus.algebra.category.core.object :refer :all]))
is a change from one point A to another point B , in either space or time . Categories are
(deftype LawvereMetric [coll distance]
ConcreteObject
(underlying-set [this] coll)
StructuredDiset
(first-set [this] (->CompleteRelation coll))
(second-set [this] coll)
StructuredQuiver
(underlying-quiver [this] (complete-relational-quiver coll))
(source-fn [this] first)
(target-fn [this] second)
(transition [this e] e)
StructuredUnitalQuiver
(underlying-unital-quiver [this] (complete-relational-unital-quiver coll))
(identity-morphism-of [this obj] (list obj obj))
ConcreteMorphism
(inputs [this] (composability-relation this))
(outputs [this] (morphisms this))
clojure.lang.IFn
(invoke [this [[a b] [c d]]] (list c b))
(applyTo [this args] (clojure.lang.AFn/applyToHelper this args)))
(derive LawvereMetric :locus.set.copresheaf.structure.core.protocols/structured-category)
(defmethod underlying-relation LawvereMetric
[^LawvereMetric metric] (morphisms metric))
(defmethod underlying-multirelation LawvereMetric
[^LawvereMetric metric] (underlying-relation metric))
(defmethod visualize LawvereMetric
[^LawvereMetric metric] (visualize (underlying-relation metric)))
Get the distance between two points in a metric space
(defmulti distance (fn [metric a b] (type metric)))
(defmethod distance LawvereMetric
[^LawvereMetric metric, a, b]
((.distance metric) a b))
(defn hom-number
[metric morphism]
(distance metric (first morphism) (second morphism)))
(defn discrete-metric
[coll]
(LawvereMetric.
coll
(fn [x y]
(if (= x y) 0 1))))
(defn equivalence-pseudometric
[rel]
(LawvereMetric.
(vertices rel)
(fn [x y]
(if (rel (list x y))
0
1))))
(defn partition-pseudometric
[family]
(LawvereMetric.
(dimembers family)
(fn [x y]
(if (= (projection family x) (projection family y))
0
1))))
(defn metric-equal?
[metric a b]
(zero? (distance metric a b)))
(defn metric-equality
[metric]
(->Universal
(fn [[a b]]
(metric-equal? metric a b))))
(defn equal-component-of
[metric x]
(set
(filter
(fn [i]
(zero? (distance metric i x)))
(underlying-set metric))))
(defn equal-components
[metric]
(let [coll (underlying-set metric)]
(set
(loop [remaining-elements coll
rval #{}]
(if (empty? remaining-elements)
rval
(let [next-element (first remaining-elements)
next-component (equal-component-of metric next-element)]
(recur
(difference remaining-elements next-component)
(conj rval next-component))))))))
(defn induced-metric
[source-set target-metric func]
(LawvereMetric.
source-set
(fn [x y]
(distance target-metric (func x) (func y)))))
(defn submetric?
[a b]
(let [a-elements (underlying-set a)
b-elements (underlying-set b)]
(and
(equal-universals? a-elements b-elements)
(every?
(fn [[x y]]
(<= (distance a x y)
(distance b x y)))
(cartesian-power a-elements 2)))))
(defn real-vector-space
[n]
(->Universal
(fn [coll]
(and
(vector? coll)
(= (count coll) n)
(every? real-number? coll)))))
(defn euclidean-metric-space
[n]
(LawvereMetric.
(real-vector-space n)
(fn [x y]
(Math/sqrt
(apply
+
(map
(fn [i]
(let [d (- (nth x i) (nth y i))]
(* d d)))
(range n)))))))
(defn taxicab-metric
[n]
(LawvereMetric.
(real-vector-space n)
(fn [x y]
(apply
+
(map
(fn [i]
(let [d (- (nth x n) (nth y n))]
(if (neg? d) (- d) d)))
(range n))))))
(defn chebyshev-metric
[n]
(LawvereMetric.
(real-vector-space n)
(fn [x y]
(apply
max
(map
(fn [i]
(let [d (- (nth x n) (nth y n))]
(if (neg? d) (- d) d)))
(range n))))))
One dimensional and two dimensional euclidean spaces have corresponding
(def one-dimensional-euclidean-space
(euclidean-metric-space 1))
(def two-dimensional-euclidean-space
(euclidean-metric-space 2))
(def three-dimensional-euclidean-space
(euclidean-metric-space 3))
(defn component-distance
[n i]
(LawvereMetric.
(real-vector-space n)
(fn [x y]
(let [d (- (nth x i) (nth y i))]
(if (neg? d) (- d) d)))))
(defn all-distances
[metric]
(seq
(map
(fn [[a b]]
(distance metric a b))
(cartesian-power (underlying-set metric) 2))))
(defn lawvere-metric?
[metric]
(= (type metric) LawvereMetric))
(defn pseudoquasimetric?
[metric]
(and
(lawvere-metric? metric)
(every?
(fn [i]
(not= i ##Inf))
(all-distances metric))))
(defn pseudometric?
[metric]
(and
(pseudoquasimetric? metric)
(every?
(fn [[a b]]
(= (distance metric a b)
(distance metric b a)))
(cartesian-power (underlying-set metric) 2))))
(defn quasimetric?
[metric]
(and
(pseudoquasimetric? metric)
(every?
(fn [[a b]]
(or
(= a b)
(not= (distance metric a b) 0)))
(cartesian-power (underlying-set metric) 2))))
(defn metric?
[metric]
(and
(pseudoquasimetric? metric)
(every?
(fn [[a b]]
(and
(= (distance metric a b) (distance metric b a))
(or
(= a b)
(not= (distance metric a b) 0))))
(cartesian-power (underlying-set metric) 2))))
|
030ab5459be77a2fe951ab50aedd559f92b9f995ea57dee7b1569d089d16b74e
|
cedlemo/OCaml-GI-ctypes-bindings-generator
|
Toggle_action.ml
|
open Ctypes
open Foreign
type t = unit ptr
let t_typ : t typ = ptr void
let create =
foreign "gtk_toggle_action_new" (string @-> string_opt @-> string_opt @-> string_opt @-> returning (ptr t_typ))
let get_active =
foreign "gtk_toggle_action_get_active" (t_typ @-> returning (bool))
let get_draw_as_radio =
foreign "gtk_toggle_action_get_draw_as_radio" (t_typ @-> returning (bool))
let set_active =
foreign "gtk_toggle_action_set_active" (t_typ @-> bool @-> returning (void))
let set_draw_as_radio =
foreign "gtk_toggle_action_set_draw_as_radio" (t_typ @-> bool @-> returning (void))
let toggled =
foreign "gtk_toggle_action_toggled" (t_typ @-> returning (void))
| null |
https://raw.githubusercontent.com/cedlemo/OCaml-GI-ctypes-bindings-generator/21a4d449f9dbd6785131979b91aa76877bad2615/tools/Gtk3/Toggle_action.ml
|
ocaml
|
open Ctypes
open Foreign
type t = unit ptr
let t_typ : t typ = ptr void
let create =
foreign "gtk_toggle_action_new" (string @-> string_opt @-> string_opt @-> string_opt @-> returning (ptr t_typ))
let get_active =
foreign "gtk_toggle_action_get_active" (t_typ @-> returning (bool))
let get_draw_as_radio =
foreign "gtk_toggle_action_get_draw_as_radio" (t_typ @-> returning (bool))
let set_active =
foreign "gtk_toggle_action_set_active" (t_typ @-> bool @-> returning (void))
let set_draw_as_radio =
foreign "gtk_toggle_action_set_draw_as_radio" (t_typ @-> bool @-> returning (void))
let toggled =
foreign "gtk_toggle_action_toggled" (t_typ @-> returning (void))
|
|
79f2c4f33027565cbc62b614e0338805a5ea1b3bbbc1ee0fbabf21928fcea21d
|
HugoPeters1024/hs-sleuth
|
Stream.hs
|
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE CPP #-}
# LANGUAGE ExistentialQuantification #
{-# LANGUAGE TypeOperators #-}
-- |
-- Module : Data.Stream
Copyright : ( c ) 2007
( c ) 2007 - 2013
-- License : BSD-style
-- Maintainer :
-- Stability : experimental
Portability : portable , requires
Tested with : GHC 6.6
--
-- Stream fusion for sequences. Described in:
--
-- * /Stream Fusion: From Lists to Streams to Nothing at All/, by
, and , ICFP 2007 .
-- </~dons/papers/CLS07.html>
--
* /Rewriting Haskell Strings/ , by , and
Roman Leshchinskiy , Practical Aspects of Declarative Languages
8th International Symposium , PADL 2007 , 2007 .
-- </~dons/papers/CSL06.html>
--
-- See the source for the complete story:
--
-- * </~dons/code/streams/list/Data/Stream.hs>
--
module Data.Stream (
#ifndef __HADDOCK__
-- * The stream data type
Stream(Stream),
Step(..),
-- * Conversions with lists
stream, -- :: [a] -> Stream a
unstream, -- :: Stream a -> [a]
-- internal grunge
L(L), -- hmm, does this affect whether these get removed?
-- * Basic stream functions
append, -- :: Stream a -> Stream a -> Stream a
append1, -- :: Stream a -> [a] -> [a]
cons, -- :: a -> Stream a -> Stream a
snoc, -- :: Stream a -> a -> Stream a
head, -- :: Stream a -> a
last, -- :: Stream a -> a
tail, -- :: Stream a -> Stream a
init, -- :: Stream a -> Stream a
null, -- :: Stream a -> Bool
length, -- :: Stream a -> Int
-- * Stream transformations
map, -- :: (a -> b) -> Stream a -> Stream b
-- reverse, -- :: Stream a -> Stream a
intersperse, -- :: a -> Stream a -> Stream a
-- intercalate, -- :: Stream a -> Stream (Stream a) -> Stream a
-- transpose, -- :: Stream (Stream a) -> Stream (Stream a)
-- * Reducing streams (folds)
foldl, -- :: (b -> a -> b) -> b -> Stream a -> b
foldl', -- :: (b -> a -> b) -> b -> Stream a -> b
foldl1, -- :: (a -> a -> a) -> Stream a -> a
foldl1', -- :: (a -> a -> a) -> Stream a -> a
foldr, -- :: (a -> b -> b) -> b -> Stream a -> b
foldr1, -- :: (a -> a -> a) -> Stream a -> a
-- ** Special folds
concat, -- :: Stream [a] -> [a]
concatMap, -- :: (a -> Stream b) -> Stream a -> Stream b
and, -- :: Stream Bool -> Bool
or, -- :: Stream Bool -> Bool
any, -- :: (a -> Bool) -> Stream a -> Bool
all, -- :: (a -> Bool) -> Stream a -> Bool
: : a = > Stream a - > a
: : a = > Stream a - > a
: : a = > Stream a - > a
: : a = > Stream a - > a
: : a = > Stream a - > a
: : a = > Stream a - > a
-- * Building lists
-- ** Scans
scanl, -- :: (a -> b -> a) -> a -> Stream b -> Stream a
scanl1, -- :: (a -> a -> a) -> Stream a -> Stream a
{-
scanr, -- :: (a -> b -> b) -> b -> Stream a -> Stream b
scanr1, -- :: (a -> a -> a) -> Stream a -> Stream a
-}
-- * * Accumulating maps
mapAccumL , -- : : ( acc - > x - > ( acc , y ) ) - > acc - > Stream x - > ( acc , Stream y )
mapAccumR , -- : : ( acc - > x - > ( acc , y ) ) - > acc - > Stream x - > ( acc , Stream y )
-- ** Accumulating maps
mapAccumL, -- :: (acc -> x -> (acc, y)) -> acc -> Stream x -> (acc, Stream y)
mapAccumR, -- :: (acc -> x -> (acc, y)) -> acc -> Stream x -> (acc, Stream y)
-}
-- ** Infinite streams
iterate, -- :: (a -> a) -> a -> Stream a
repeat, -- :: a -> Stream a
replicate, -- :: Int -> a -> Stream a
cycle, -- :: Stream a -> Stream a
-- ** Unfolding
unfoldr, -- :: (b -> Maybe (a, b)) -> b -> Stream a
-- * Substreams
-- ** Extracting substreams
take, -- :: Int -> Stream a -> Stream a
drop, -- :: Int -> Stream a -> Stream a
splitAt, -- :: Int -> Stream a -> ([a], [a])
takeWhile, -- :: (a -> Bool) -> Stream a -> Stream a
dropWhile, -- :: (a -> Bool) -> Stream a -> Stream a
{-
span, -- :: (a -> Bool) -> Stream a -> (Stream a, Stream a)
break, -- :: (a -> Bool) -> Stream a -> (Stream a, Stream a)
group, -- :: Eq a => Stream a -> Stream (Stream a)
inits, -- :: Stream a -> Stream (Stream a)
tails, -- :: Stream a -> Stream (Stream a)
-}
-- * Predicates
isPrefixOf, -- :: Eq a => Stream a -> Stream a -> Bool
isSuffixOf , -- : : Eq a = > Stream a - > Stream a - > Bool
isInfixOf , -- : : Eq a = > Stream a - > Stream a - > Bool
isSuffixOf, -- :: Eq a => Stream a -> Stream a -> Bool
isInfixOf, -- :: Eq a => Stream a -> Stream a -> Bool
-}
-- * Searching streams
-- ** Searching by equality
elem, -- :: Eq a => a -> Stream a -> Bool
lookup, -- :: Eq a => a -> Stream (a, b) -> Maybe b
-- ** Searching with a predicate
find, -- :: (a -> Bool) -> Stream a -> Maybe a
filter, -- :: (a -> Bool) -> Stream a -> Stream a
-- partition, -- :: (a -> Bool) -> Stream a -> ([a], [a])
-- * Indexing streams
index, -- :: Stream a -> Int -> a
findIndex, -- :: (a -> Bool) -> Stream a -> Maybe Int
elemIndex, -- :: Eq a => a -> Stream a -> Maybe Int
elemIndices, -- :: Eq a => a -> Stream a -> Stream Int
findIndices, -- :: (a -> Bool) -> Stream a -> Stream Int
-- * Zipping and unzipping streams
zip, -- :: Stream a -> Stream b -> Stream (a, b)
zip3, -- :: Stream a -> Stream b -> Stream c -> Stream (a, b, c)
zip4,
zipWith, -- :: (a -> b -> c) -> Stream a -> Stream b -> Stream c
zipWith3, -- :: (a -> b -> c -> d) -> Stream a -> Stream b -> Stream c -> Stream d
zipWith4,
zip4 , , zip6 , zip7 ,
zipWith4 , zipWith5 , zipWith6 , zipWith7 ,
zip4, zip5, zip6, zip7,
zipWith4, zipWith5, zipWith6, zipWith7,
-}
unzip, -- :: Stream (a, b) -> (Stream a, Stream b)
unzip3 , -- : : Stream ( a , b , c ) - > ( Stream a , Stream b , Stream c )
, unzip5 , unzip6 , ,
unzip3, -- :: Stream (a, b, c) -> (Stream a, Stream b, Stream c)
unzip4, unzip5, unzip6, unzip7,
-}
-- * Special streams
-- ** Functions on strings
lines , -- : : Stream Char - > Stream [ Char ]
unlines , -- : : Stream ( Stream ) - > Stream Char
words , -- : : Stream Char - > Stream ( Stream Char )
unwords , -- : : Stream ( Stream ) - > Stream
lines, -- :: Stream Char -> Stream [Char]
unlines, -- :: Stream (Stream Char) -> Stream Char
words, -- :: Stream Char -> Stream (Stream Char)
unwords, -- :: Stream (Stream Char) -> Stream Char
-}
{-
-- ** \"Set\" operations
nub, -- :: Eq a => Stream a -> Stream a
delete, -- :: Eq a => a -> Stream a -> Stream a
(\\), -- :: Eq a => Stream a -> Stream a -> Stream a
union, -- :: Eq a => Stream a -> Stream a -> Stream a
intersect, -- :: Eq a => Stream a -> Stream a -> Stream a
-}
-- * * Ordered streams
sort , -- : : a = > Stream a - > Stream a
insert , -- : : a = > a - > Stream a - > Stream a
-- ** Ordered streams
sort, -- :: Ord a => Stream a -> Stream a
insert, -- :: Ord a => a -> Stream a -> Stream a
-}
-- * Generalized functions
-- * * The \"By\ " operations
-- * * * User - supplied equality ( replacing an Eq context )
nubBy , -- : : ( a - > a - > Bool ) - > Stream a - > Stream a
deleteBy , -- : : ( a - > a - > Bool ) - > a - > Stream a - > Stream a
deleteFirstsBy , -- : : ( a - > a - > Bool ) - > Stream a - > Stream a - > Stream a
unionBy , -- : : ( a - > a - > Bool ) - > Stream a - > Stream a - > Stream a
intersectBy , -- : : ( a - > a - > Bool ) - > Stream a - > Stream a - > Stream a
groupBy , -- : : ( a - > a - > Bool ) - > Stream a - > Stream ( Stream a )
-- * Generalized functions
-- ** The \"By\" operations
-- *** User-supplied equality (replacing an Eq context)
nubBy, -- :: (a -> a -> Bool) -> Stream a -> Stream a
deleteBy, -- :: (a -> a -> Bool) -> a -> Stream a -> Stream a
deleteFirstsBy, -- :: (a -> a -> Bool) -> Stream a -> Stream a -> Stream a
unionBy, -- :: (a -> a -> Bool) -> Stream a -> Stream a -> Stream a
intersectBy, -- :: (a -> a -> Bool) -> Stream a -> Stream a -> Stream a
groupBy, -- :: (a -> a -> Bool) -> Stream a -> Stream (Stream a)
-}
* * * User - supplied comparison ( replacing an context )
insertBy, -- :: (a -> a -> Ordering) -> a -> Stream a -> Stream a
{-
sortBy, -- :: (a -> a -> Ordering) -> Stream a -> Stream a
-}
maximumBy, -- :: (a -> a -> Ordering) -> Stream a -> a
minimumBy, -- :: (a -> a -> Ordering) -> Stream a -> a
-- * The \"generic\" operations
: : i = > Stream b - > i
genericTake, -- :: Integral i => i -> Stream a -> Stream a
genericDrop, -- :: Integral i => i -> Stream a -> Stream a
genericIndex, -- :: Integral a => Stream b -> a -> b
genericSplitAt, -- :: Integral i => i -> Stream a -> ([a], [a])
*
enumFromToInt, -- :: Int -> Int -> Stream Int
: : Stream
enumDeltaInteger, -- :: Integer -> Integer -> Stream Integer
-- * Monad
: : = > ( b - > a - > m b ) - > b - > Stream a - > m b
: : = > ( b - > a - > m b ) - > b - > Stream a - > m ( )
-- * List comprehension desugaring
return, -- :: a -> Stream a
guard, -- :: Bool -> Stream a -> Stream a
bind, -- :: (a -> Bool) -> (a -> [b]) -> [a] -> [b]
mapFilter, -- :: (a -> Bool) -> (a -> b) -> [a] -> [b]
declare -- :: (a -> Stream b) -> a -> Stream b
#endif
) where
#ifndef __HADDOCK__
#ifndef EXTERNAL_PACKAGE
import {-# SOURCE #-} GHC.Err (error)
import {-# SOURCE #-} GHC.Num (Num(..),Integer)
import {-# SOURCE #-} GHC.Real (Integral(..))
import GHC.Base (Int, Char, Eq(..), Ord(..), Functor(..), Bool(..), (&&),
Ordering(..),
(||),(&&), ($),
seq, otherwise, ord, chr,
Monad((>>=), (>>)), -- why >> ? we're not using it
-- for error messages:
String, (++))
import qualified GHC.Base as Monad (Monad(return))
import Data.Tuple ()
#else
import Prelude (
error,
Num(..),
Integral(..),
Integer,
Int, Char, Eq(..), Ord(..), Functor(..), Ordering(..), Bool(..),
(&&), (||), ($),
seq, otherwise,
Monad((>>=)),
-- for error messages:
String, (++))
import qualified Prelude as Monad (Monad(return))
import Data.Char (ord,chr)
#endif
import qualified Data.Maybe (Maybe(..))
------------------------------------------------------------------------
-- The stream data type
-- | A stream.
--
-- It is important that we never construct a bottom stream, because the
-- fusion rule is not true for bottom streams.
--
> ( replicate 1 True ) + + ( tail undefined )
--
-- The suspicion is that under fusion the append will force the bottom.
--
data Stream a = forall s. Unlifted s =>
Stream !(s -> Step a s) -- a stepper function
!s -- an initial state
-- | A stream step.
--
-- A step either ends a stream, skips a value, or yields a value
--
data Step a s = Yield a !s
| Skip !s
| Done
instance Functor Stream where fmap = map
| A class of strict unlifted types . The Unlifted constraint in the
-- Stream type above enforces a separation between user's types and the
-- types used in stream states.
--
class Unlifted a where
-- | This expose function needs to be called in folds/loops that consume
-- streams to expose the structure of the stream state to the simplifier
In particular , to SpecConstr .
--
expose :: a -> b -> b
expose = seq
| This makes GHC 's optimiser happier ; it sometimes produces really bad
-- code for single-method dictionaries
--
unlifted_dummy :: a
unlifted_dummy = error "unlifted_dummy"
--
| Unlifted versions of ( ) and for use in Stream states .
--
data None = None
instance Unlifted None
-- | A useful unlifted type
data Switch = S1 | S2
instance Unlifted Switch
-- | Unlifted pairs, Maybe and Either
--
data a :!: b = !a :!: !b
instance (Unlifted a, Unlifted b) => Unlifted (a :!: b) where
expose (a :!: b) s = expose a (expose b s)
{-# INLINE expose #-}
-- | Unlifted Maybes
data Maybe a = Nothing | Just !a
instance Unlifted a => Unlifted (Maybe a) where
expose (Just a) s = expose a s
expose Nothing s = s
{-# INLINE expose #-}
-- | Unlifted sums
data Either a b = Left !a | Right !b
instance (Unlifted a, Unlifted b) => Unlifted (Either a b) where
expose (Left a) s = expose a s
expose (Right b) s = expose b s
{-# INLINE expose #-}
-- | Some stream functions (notably concatMap) need to use a stream as a state
--
instance Unlifted (Stream a) where
expose (Stream next s0) s = seq next (seq s0 s)
{-# INLINE expose #-}
-- | Boxes for user's state. This is the gateway for user's types into unlifted
-- stream states. The L is always safe since it's lifted/lazy, exposing/seqing
-- it does nothing.
-- S is unlifted and so is only suitable for users states that we know we can
-- be strict in. This requires attention and auditing.
--
data L a = L a -- lazy / lifted
newtype S a = S a -- strict / unlifted
instance Unlifted (L a) where
expose (L _) s = s
{-# INLINE expose #-}
instance Unlifted (S a) where
expose (S a) s = seq a s
{-# INLINE expose #-}
--
-- coding conventions;
--
-- * we tag local loops with their wrapper's name, so they're easier to
spot in Core output
--
-- ---------------------------------------------------------------------
-- List/Stream conversion
-- | Construct an abstract stream from a list.
stream :: [a] -> Stream a
stream xs0 = Stream next (L xs0)
where
# INLINE next #
next (L []) = Done
next (L (x:xs)) = Yield x (L xs)
{-# INLINE [0] stream #-}
-- | Flatten a stream back into a list.
unstream :: Stream a -> [a]
unstream (Stream next s0) = unfold_unstream s0
where
unfold_unstream !s = case next s of
Done -> []
Skip s' -> expose s' $ unfold_unstream s'
Yield x s' -> expose s' $ x : unfold_unstream s'
{-# INLINE [0] unstream #-}
--
-- /The/ stream fusion rule
--
# RULES
" STREAM stream / unstream fusion " forall s.
stream ( unstream s ) = s
#
"STREAM stream/unstream fusion" forall s.
stream (unstream s) = s
#-}
-- ---------------------------------------------------------------------
-- Basic stream functions
-- (++)
append :: Stream a -> Stream a -> Stream a
append (Stream next0 s01) (Stream next1 s02) = Stream next (Left s01)
where
# INLINE next #
next (Left s1) = case next0 s1 of
Done -> Skip (Right s02)
Skip s1' -> Skip (Left s1')
Yield x s1' -> Yield x (Left s1')
next (Right s2) = case next1 s2 of
Done -> Done
Skip s2' -> Skip (Right s2')
Yield x s2' -> Yield x (Right s2')
{-# INLINE [0] append #-}
version that can share the second list arg , really very similar
-- to unstream, but conses onto a given list rather than []:
unstream s = append1 s [ ]
--
append1 :: Stream a -> [a] -> [a]
append1 (Stream next s0) xs = loop_append1 s0
where
loop_append1 !s = case next s of
Done -> xs
Skip s' -> expose s' loop_append1 s'
Yield x s' -> expose s' $ x : loop_append1 s'
{-# INLINE [0] append1 #-}
snoc :: Stream a -> a -> Stream a
snoc (Stream next0 xs0) w = Stream next (Just xs0)
where
# INLINE next #
next (Just xs) = case next0 xs of
Done -> Yield w Nothing
Skip xs' -> Skip (Just xs')
Yield x xs' -> Yield x (Just xs')
next Nothing = Done
{-# INLINE [0] snoc #-}
cons :: a -> Stream a -> Stream a
cons w (Stream next0 s0) = Stream next (S2 :!: s0)
where
# INLINE next #
next (S2 :!: s) = Yield w (S1 :!: s)
next (S1 :!: s) = case next0 s of
Done -> Done
Skip s' -> Skip (S1 :!: s')
Yield x s' -> Yield x (S1 :!: s')
{-# INLINE [0] cons #-}
-- head
head :: Stream a -> a
head (Stream next s0) = loop_head s0
where
loop_head !s = case next s of
Yield x _ -> x
Skip s' -> expose s' $ loop_head s'
Done -> errorEmptyStream "head"
{-# INLINE [0] head #-}
-- last
last :: Stream a -> a
last (Stream next s0) = loop0_last s0
where
loop0_last !s = case next s of
Done -> errorEmptyStream "last"
Skip s' -> expose s' $ loop0_last s'
Yield x s' -> expose s' $ loop_last x s'
loop_last x !s = case next s of
Done -> x
Skip s' -> expose s' $ loop_last x s'
Yield x' s' -> expose s' $ loop_last x' s'
{-# INLINE [0] last #-}
-- tail
tail :: Stream a -> Stream a
tail (Stream next0 s0) = Stream next (S1 :!: s0)
where
# INLINE next #
next (S1 :!: s) = case next0 s of
Done -> errorEmptyStream "tail"
Skip s' -> Skip (S1 :!: s')
Yield _ s' -> Skip (S2 :!: s') -- drop the head
next (S2 :!: s) = case next0 s of
Done -> Done
Skip s' -> Skip (S2 :!: s')
Yield x s' -> Yield x (S2 :!: s')
{-# INLINE [0] tail #-}
-- init
init :: Stream a -> Stream a
init (Stream next0 s0) = Stream next (Nothing :!: s0)
where
# INLINE next #
next (Nothing :!: s) = case next0 s of
Done -> errorEmptyStream "init"
Skip s' -> Skip (Nothing :!: s')
Yield x s' -> Skip (Just (L x) :!: s')
next (Just (L x) :!: s) = case next0 s of
Done -> Done
Skip s' -> Skip (Just (L x) :!: s')
Yield x' s' -> Yield x (Just (L x') :!: s')
{-# INLINE [0] init #-}
-- null
null :: Stream a -> Bool
null (Stream next s0) = loop_null s0
where
loop_null !s = case next s of
Done -> True
Yield _ _ -> False
Skip s' -> expose s' $ loop_null s'
{-# INLINE [0] null #-}
-- length
length :: Stream a -> Int
length (Stream next s0) = loop_length (0::Int) s0
where
loop_length !z !s = case next s of
Done -> z
Skip s' -> expose s' $ loop_length z s'
Yield _ s' -> expose s' $ loop_length (z+1) s'
{-# INLINE [0] length #-}
{-
-- For lazy bytestrings
length64 :: Stream a -> Int64
length64 (Stream next s0) = loop (0::Int64) s0
where
loop z !s = case next s of
Done -> z
Skip s' -> loop z s'
Yield _ s' -> loop (z+1) s'
{-# INLINE [0] length64 #-}
-}
-- ---------------------------------------------------------------------
-- Stream transformations
-- map
map :: (a -> b) -> Stream a -> Stream b
map f (Stream next0 s0) = Stream next s0
where
# INLINE next #
next !s = case next0 s of
Done -> Done
Skip s' -> Skip s'
Yield x s' -> Yield (f x) s'
{-# INLINE [0] map #-}
--
-- a convenient rule for map
--
# RULES
" STREAM map / map fusion " forall f g s.
map f ( map s ) = map ( \x - > f ( g x ) ) s
#
"STREAM map/map fusion" forall f g s.
map f (map g s) = map (\x -> f (g x)) s
#-}
--
relies strongly on SpecConstr
--
intersperse :: a -> Stream a -> Stream a
intersperse sep (Stream next0 s0) = Stream next (s0 :!: Nothing :!: S1)
where
# INLINE next #
next (s :!: Nothing :!: S1) = case next0 s of
Done -> Done
Skip s' -> Skip (s' :!: Nothing :!: S1)
Yield x s' -> Skip (s' :!: Just (L x) :!: S1)
next (s :!: Just (L x) :!: S1) = Yield x (s :!: Nothing :!: S2)
next (s :!: Nothing :!: S2) = case next0 s of
Done -> Done
Skip s' -> Skip (s' :!: Nothing :!: S2)
Yield x s' -> Yield sep (s' :!: Just (L x) :!: S1)
-- next (_ :!: (Just (L _))) :!: S2 -- can't happen
{-
intersperse :: a -> Stream a -> [a]
intersperse sep (Stream next s0) = loop_intersperse_start s0
where
loop_intersperse_start !s = case next s of
Done -> []
Skip s' -> expose s' $ loop_intersperse_start s'
Yield x s' -> expose s' $ x : loop_intersperse_go s'
loop_intersperse_go !s = case next s of
Done -> []
Skip s' -> expose s' $ loop_intersperse_go s'
Yield x s' -> expose s' $ sep : x : loop_intersperse_go s'
-}
-- intercalate :: Stream a -> Stream (Stream a) -> Stream a
-- transpose :: Stream (Stream a) -> Stream (Stream a)
------------------------------------------------------------------------
-- * Reducing streams (folds)
foldl :: (b -> a -> b) -> b -> Stream a -> b
foldl f z0 (Stream next s0) = loop_foldl z0 s0
where
loop_foldl z !s = case next s of
Done -> z
Skip s' -> expose s' $ loop_foldl z s'
Yield x s' -> expose s' $ loop_foldl (f z x) s'
{-# INLINE [0] foldl #-}
foldl' :: (b -> a -> b) -> b -> Stream a -> b
foldl' f z0 (Stream next s0) = loop_foldl' z0 s0
where
loop_foldl' !z !s = case next s of
Done -> z
Skip s' -> expose s' $ loop_foldl' z s'
Yield x s' -> expose s' $ loop_foldl' (f z x) s'
{-# INLINE [0] foldl' #-}
foldl1 :: (a -> a -> a) -> Stream a -> a
foldl1 f (Stream next s0) = loop0_foldl1 s0
where
loop0_foldl1 !s = case next s of
Skip s' -> expose s' $ loop0_foldl1 s'
Yield x s' -> expose s' $ loop_foldl1 x s'
Done -> errorEmptyStream "foldl1"
loop_foldl1 z !s = expose s $ case next s of
Done -> z
Skip s' -> expose s' $ loop_foldl1 z s'
Yield x s' -> expose s' $ loop_foldl1 (f z x) s'
{-# INLINE [0] foldl1 #-}
foldl1' :: (a -> a -> a) -> Stream a -> a
foldl1' f (Stream next s0) = loop0_foldl1' s0
where
loop0_foldl1' !s = case next s of
Skip s' -> expose s' $ loop0_foldl1' s'
Yield x s' -> expose s' $ loop_foldl1' x s'
Done -> errorEmptyStream "foldl1"
loop_foldl1' !z !s = case next s of
Done -> z
Skip s' -> expose s' $ loop_foldl1' z s'
Yield x s' -> expose s' $ loop_foldl1' (f z x) s'
# INLINE [ 0 ] foldl1 ' #
foldr :: (a -> b -> b) -> b -> Stream a -> b
foldr f z (Stream next s0) = loop_foldr s0
where
loop_foldr !s = case next s of
Done -> z
Skip s' -> expose s' $ loop_foldr s'
Yield x s' -> expose s' $ f x (loop_foldr s')
{-# INLINE [0] foldr #-}
foldr1 :: (a -> a -> a) -> Stream a -> a
foldr1 f (Stream next s0) = loop0_foldr1 s0
where
loop0_foldr1 !s = case next s of
Done -> errorEmptyStream "foldr1"
Skip s' -> expose s' $ loop0_foldr1 s'
Yield x s' -> expose s' $ loop_foldr1 x s'
loop_foldr1 x !s = case next s of
Done -> x
Skip s' -> expose s' $ loop_foldr1 x s'
Yield x' s' -> expose s' $ f x (loop_foldr1 x' s')
{-# INLINE [0] foldr1 #-}
------------------------------------------------------------------------
-- ** Special folds
-- concat
--
concat :: Stream [a] -> [a]
concat (Stream next s0) = loop_concat_to s0
where
loop_concat_go [] !s = expose s $ loop_concat_to s
loop_concat_go (x:xs) !s = expose s $ x : loop_concat_go xs s
loop_concat_to !s = case next s of
Done -> []
Skip s' -> expose s' $ loop_concat_to s'
Yield xs s' -> expose s' $ loop_concat_go xs s'
{-# INLINE [0] concat #-}
{-
concat :: Stream [a] -> Stream a
concat (Stream next0 s0) = Stream next (Nothing :!: s0)
where
{-# INLINE next #-}
next (Just (L []) :!: s) = expose s $ Skip (Nothing :!: s)
next (Just (L (x:xs)) :!: s) = expose s $ Yield x (Just (L xs) :!: s)
next (Nothing :!: s) = case next0 s of
Done -> Done
Skip s' -> expose s' $ Skip (Nothing :!: s')
Yield xs s' -> expose s' $ Skip (Just (L xs) :!: s')
-}
{-
concatMap :: (a -> [b]) -> Stream a -> [b]
concatMap f (Stream next s0) = loop_concatMap_to s0
where
loop_concatMap_go [] !s = expose s $ loop_concatMap_to s
loop_concatMap_go (b:bs) !s = expose s $ b : loop_concatMap_go bs s
loop_concatMap_to !s = case next s of
Done -> []
Skip s' -> expose s' $ loop_concatMap_to s'
Yield a s' -> expose s' $ loop_concatMap_go (f a) s'
{-# INLINE [0] concatMap #-}
-}
{-
concatMap :: (a -> [b]) -> Stream a -> Stream b
concatMap f (Stream next0 s0) = Stream next (Nothing :!: s0)
where
{-# INLINE next #-}
next (Just (L []) :!: s) = expose s $ Skip (Nothing :!: s)
next (Just (L (b:bs)) :!: s) = expose s $ Yield b (Just (L bs) :!: s)
next (Nothing :!: s) = case next0 s of
Done -> Done
Skip s' -> expose s' $ Skip (Nothing :!: s')
Yield a s' -> expose s' $ Skip (Just (L (f a)) :!: s')
-}
{-
Here's an approach to fusing concatMap fully:
we try and match the Stream inside in the argument to concatMap and pass that
directly to a concatMap' variant. The point here is that the step function does
not depend on 'x', something which the rule below does not enforce :-)
-}
RULES
" dodgy concatMap rule " forall step concatMap ( \x - > unstream ( Stream step ( f x ) ) ) = \y - > unstream ( concatMap ' step f y )
"dodgy concatMap rule" forall step f.
concatMap (\x -> unstream (Stream step (f x))) = \y -> unstream (concatMap' step f y)
-}
{-
concatMap' :: Unlifted s => (s -> Step b s) -> (a -> s) -> Stream a -> Stream b
concatMap' nextb f (Stream nexta sa0) = Stream next (sa0 :!: Nothing)
where
{-# INLINE next #-}
next (sa :!: Just sb) = case nextb sb of
Done -> Skip (sa :!: Nothing)
Skip sb' -> Skip (sa :!: Just sb')
Yield b sb' -> Yield b (sa :!: Just sb')
next (sa :!: Nothing) = case nexta sa of
Done -> Done
Skip sa' -> Skip (sa' :!: Nothing)
Yield a sa' -> Skip (sa' :!: Just (f a))
-}
{-
-- note the nested stream is a little hard to construct in a fusible
-- manner
--
concat :: Stream (Stream a) -> Stream a
concat (Stream next0 s0) = Stream next (Right s0)
where
{-# INLINE next #-}
next (Left (Stream f t :!: s)) = case f t of
Done -> Skip (Right s)
Skip t' -> Skip (Left (Stream f t' :!: s))
Yield x t' -> Yield x (Left (Stream f t' :!: s))
next (Right s) = case next0 s of
Done -> Done
Skip s' -> Skip (Right s')
Yield x s' -> Skip (Left (x :!: s'))
{-# INLINE [0] concat #-}
-}
concatMap :: (a -> Stream b) -> Stream a -> Stream b
concatMap f (Stream next0 s0) = Stream next (s0 :!: Nothing)
where
# INLINE next #
next (s :!: Nothing) = case next0 s of
Done -> Done
Skip s' -> Skip (s' :!: Nothing)
Yield x s' -> Skip (s' :!: Just (f x))
next (s :!: Just (Stream g t)) = case g t of
Done -> Skip (s :!: Nothing)
Skip t' -> Skip (s :!: Just (Stream g t'))
Yield x t' -> Yield x (s :!: Just (Stream g t'))
{-# INLINE [0] concatMap #-}
and :: Stream Bool -> Bool
and = foldr (&&) True
# INLINE and #
or :: Stream Bool -> Bool
or = foldr (||) False
# INLINE or #
any :: (a -> Bool) -> Stream a -> Bool
any p (Stream next s0) = loop_any s0
where
loop_any !s = case next s of
Done -> False
Skip s' -> expose s' $ loop_any s'
Yield x s' | p x -> True
| otherwise -> expose s' $ loop_any s'
{-# INLINE [0] any #-}
all :: (a -> Bool) -> Stream a -> Bool
all p (Stream next s0) = loop_all s0
where
loop_all !s = case next s of
Done -> True
Skip s' -> expose s' $ loop_all s'
Yield x s' | p x -> expose s' $ loop_all s'
| otherwise -> False
{-# INLINE [0] all #-}
sum :: Num a => Stream a -> a
sum (Stream next s0) = loop_sum 0 s0
where
loop_sum !a !s = case next s of -- note: strict in the accumulator!
Done -> a
Skip s' -> expose s' $ loop_sum a s'
Yield x s' -> expose s' $ loop_sum (a + x) s'
{-# INLINE [0] sum #-}
product :: Num a => Stream a -> a
product (Stream next s0) = loop_product 1 s0 -- note: strict in the accumulator!
where
loop_product !a !s = case next s of
Done -> a
Skip s' -> expose s' $ loop_product a s'
Yield x s' -> expose s' $ loop_product (a * x) s'
{-# INLINE [0] product #-}
maximum :: Ord a => Stream a -> a
maximum (Stream next s0) = loop0_maximum s0
where
loop0_maximum !s = case next s of
Done -> errorEmptyStream "maximum"
Skip s' -> expose s' $ loop0_maximum s'
Yield x s' -> expose s' $ loop_maximum x s'
loop_maximum z !s = case next s of -- note, lazy in the accumulator
Done -> z
Skip s' -> expose s' $ loop_maximum z s'
Yield x s' -> expose s' $ loop_maximum (max z x) s'
{-# INLINE [0] maximum #-}
{-# RULES
"maximumInt" maximum = (strictMaximum :: Stream Int -> Int);
"maximumChar" maximum = (strictMaximum :: Stream Char -> Char)
#-}
strictMaximum :: Ord a => Stream a -> a
strictMaximum (Stream next s0) = loop0_strictMaximum s0
where
loop0_strictMaximum !s = case next s of
Done -> errorEmptyStream "maximum"
Skip s' -> expose s' $ loop0_strictMaximum s'
Yield x s' -> expose s' $ loop_strictMaximum x s'
loop_strictMaximum !z !s = case next s of
Done -> z
Skip s' -> expose s' $ loop_strictMaximum z s'
Yield x s' -> expose s' $ loop_strictMaximum (max z x) s'
{-# INLINE [0] strictMaximum #-}
minimum :: Ord a => Stream a -> a
minimum (Stream next s0) = loop0_minimum s0
where
loop0_minimum !s = case next s of
Done -> errorEmptyStream "minimum"
Skip s' -> expose s' $ loop0_minimum s'
Yield x s' -> expose s' $ loop_minimum x s'
loop_minimum z !s = case next s of
Done -> z
Skip s' -> expose s' $ loop_minimum z s'
Yield x s' -> expose s' $ loop_minimum (min z x) s'
{-# INLINE [0] minimum #-}
{-# RULES
"minimumInt" minimum = (strictMinimum :: Stream Int -> Int);
"minimumChar" minimum = (strictMinimum :: Stream Char -> Char)
#-}
strictMinimum :: Ord a => Stream a -> a
strictMinimum (Stream next s0) = loop0_strictMinimum s0
where
loop0_strictMinimum !s = case next s of
Done -> errorEmptyStream "minimum"
Skip s' -> expose s' $ loop0_strictMinimum s'
Yield x s' -> expose s' $ loop_strictMinimum x s'
loop_strictMinimum !z !s = case next s of
Done -> z
Skip s' -> expose s' $ loop_strictMinimum z s'
Yield x s' -> expose s' $ loop_strictMinimum (min z x) s'
{-# INLINE [0] strictMinimum #-}
------------------------------------------------------------------------
-- * Building lists
-- ** Scans
--
FIXME : not a proper . expects a list one longer than the input list ,
-- in order to get the z0th element
--
scanl :: (b -> a -> b) -> b -> Stream a -> Stream b
scanl f z0 (Stream next0 s0) = Stream next (L z0 :!: s0)
where
# INLINE next #
next (L z :!: s) = case next0 s of
Done -> Done
Skip s' -> Skip (L z :!: s')
Yield x s' -> Yield z (L (f z x) :!: s')
# INLINE [ 0 ] #
scanl1 :: (a -> a -> a) -> Stream a -> Stream a
scanl1 f (Stream next0 s0) = Stream next (Nothing :!: s0)
where
# INLINE next #
next (Nothing :!: s) = case next0 s of
Done -> Done
Skip s' -> Skip (Nothing :!: s')
Yield x s' -> Skip (Just (L x) :!: s')
next (Just (L z) :!: s) = case next0 s of
Done -> Done
Skip s' -> Skip (Just (L z) :!: s')
Yield x s' -> Yield z (Just (L (f z x)) :!: s')
{-# INLINE [0] scanl1 #-}
--
-- hmm. hard.
--
scanr : : ( b - > a - > b ) - > b - > Stream a - > Stream b
( Stream next s0 ) = Stream next ' ( Just s0 )
where
next ' ( Just s ) = case next s of
Done - > Yield z0 ( Nothing , s )
Skip s ' - > Skip ( Just s ' )
Yield x s ' - > -- hmm .
next ' Nothing = Done
{ - # INLINE [ 0 ] #
scanr :: (b -> a -> b) -> b -> Stream a -> Stream b
scanr f z0 (Stream next s0) = Stream next' (Just s0)
where
next' (Just s) = case next s of
Done -> Yield z0 (Nothing, s)
Skip s' -> Skip (Just s')
Yield x s' -> -- hmm.
next' Nothing = Done
{-# INLINE [0] scanl #-}
-}
scanr : : ( a - > b - > b ) - > b - > Stream a - > Stream b
( Stream next s0 ) = Stream next ' ( z0 , s0 ) -- should be using strict pairs ? ?
where
next ' ( z , s ) = case next s of
Done - > Done
Skip s ' - > Skip ( z , s ' )
Yield x s ' - > Yield z ( f x z , s ' ) -- flip f
{ - # INLINE [ 0 ] scanr #
scanr :: (a -> b -> b) -> b -> Stream a -> Stream b
scanr f z0 (Stream next s0) = Stream next' (z0, s0) -- should be using strict pairs??
where
next' (z, s) = case next s of
Done -> Done
Skip s' -> Skip (z, s')
Yield x s' -> Yield z (f x z, s') -- flip f
{-# INLINE [0] scanr #-}
-}
: : ( a - > a - > a ) - > Stream a - > Stream a
scanr1 : : ( a - > a - > a ) - > Stream a - > Stream a
scanl1 :: (a -> a -> a) -> Stream a -> Stream a
scanr1 :: (a -> a -> a) -> Stream a -> Stream a
-}
------------------------------------------------------------------------
-- ** Accumulating maps
--
-- not right :
--
mapAccumL : : ( acc - > x - > ( acc , y ) ) - > acc - > Stream x - > ( acc , Stream y )
mapAccumL f acc ( Stream step s ) = Stream step ' ( s , acc )
where
step ' ( s , acc ) = case step s of
Done - > Done
Skip s ' - > Skip ( s ' , acc )
Yield x s ' - > let ( acc ' , y ) = f acc x in Yield y ( s ' , acc ' )
{ - # INLINE [ 0 ] mapAccumL #
--
-- not right:
--
mapAccumL :: (acc -> x -> (acc, y)) -> acc -> Stream x -> (acc, Stream y)
mapAccumL f acc (Stream step s) = Stream step' (s, acc)
where
step' (s, acc) = case step s of
Done -> Done
Skip s' -> Skip (s', acc)
Yield x s' -> let (acc', y) = f acc x in Yield y (s', acc')
{-# INLINE [0] mapAccumL #-}
-}
mapAccumR : : ( acc - > x - > ( acc , y ) ) - > acc - > Stream x - > ( acc , Stream y )
mapAccumR :: (acc -> x -> (acc, y)) -> acc -> Stream x -> (acc, Stream y)
-}
------------------------------------------------------------------------
-- ** Infinite streams
iterate :: (a -> a) -> a -> Stream a
iterate f x0 = Stream next (L x0)
where
# INLINE next #
next (L x) = Yield x (L (f x))
{-# INLINE [0] iterate #-}
repeat :: a -> Stream a
repeat x = Stream next None
where
# INLINE next #
next _ = Yield x None
{-# INLINE [0] repeat #-}
{-# RULES
"map/repeat" forall f x. map f (repeat x) = repeat (f x)
#-}
replicate :: Int -> a -> Stream a
replicate n x = Stream next (L n)
where
# INLINE next #
next (L !i) | i <= 0 = Done
| otherwise = Yield x (L (i-1))
{-# INLINE [0] replicate #-}
{-# RULES
"map/replicate" forall f n x. map f (replicate n x) = replicate n (f x)
#-}
--"reverse/replicate" forall n x. reverse (replicate n x) = replicate n x
cycle :: Stream a -> Stream a
cycle (Stream next0 s0) = Stream next (s0 :!: S1)
where
# INLINE next #
next (s :!: S1) = case next0 s of
Done -> errorEmptyStream "cycle"
Skip s' -> Skip (s' :!: S1)
Yield x s' -> Yield x (s' :!: S2)
next (s :!: S2) = case next0 s of
Done -> Skip (s0 :!: S2)
Skip s' -> Skip (s' :!: S2)
Yield x s' -> Yield x (s' :!: S2)
{-# INLINE [0] cycle #-}
------------------------------------------------------------------------
-- ** Unfolding
unfoldr :: (b -> Data.Maybe.Maybe (a, b)) -> b -> Stream a
unfoldr f s0 = Stream next (L s0)
where
# INLINE next #
next (L s) = case f s of
Data.Maybe.Nothing -> Done
Data.Maybe.Just (w, s') -> Yield w (L s')
{-# INLINE [0] unfoldr #-}
------------------------------------------------------------------------
-- * Substreams
-- ** Extracting substreams
take :: Int -> Stream a -> Stream a
take n0 (Stream next0 s0) = Stream next (L n0 :!: s0)
where
# INLINE next #
next (L !n :!: s)
| n <= 0 = Done
| otherwise = case next0 s of
Done -> Done
Skip s' -> Skip (L n :!: s')
Yield x s' -> Yield x (L (n-1) :!: s')
{-# INLINE [0] take #-}
drop :: Int -> Stream a -> Stream a
drop n0 (Stream next0 s0) = Stream next (Just (L (max 0 n0)) :!: s0)
where
# INLINE next #
next (Just (L !n) :!: s)
| n == 0 = Skip (Nothing :!: s)
| otherwise = case next0 s of
Done -> Done
Skip s' -> Skip (Just (L n) :!: s')
Yield _ s' -> Skip (Just (L (n-1)) :!: s')
next (Nothing :!: s) = case next0 s of
Done -> Done
Skip s' -> Skip (Nothing :!: s')
Yield x s' -> Yield x (Nothing :!: s')
{-# INLINE [0] drop #-}
--TODO: could perhaps use 0 instead of Nothing, so long as
-- spec constr works with that
splitAt :: Int -> Stream a -> ([a], [a])
splitAt n0 (Stream next s0)
--TODO: we should not need this special case, (n < 0) should be as
cheap as pattern matching n against 0
| n0 < 0 = ([], expose s0 $ unstream (Stream next s0))
| otherwise = loop_splitAt n0 s0
where
loop_splitAt 0 !s = ([], expose s $ unstream (Stream next s))
loop_splitAt !n !s = case next s of
Done -> ([], [])
Skip s' -> expose s $ loop_splitAt n s'
Yield x s' -> (x:xs', xs'')
where
(xs', xs'') = expose s $ loop_splitAt (n-1) s'
{-# INLINE [0] splitAt #-}
takeWhile :: (a -> Bool) -> Stream a -> Stream a
takeWhile p (Stream next0 s0) = Stream next s0
where
# INLINE next #
next !s = case next0 s of
Done -> Done
Skip s' -> Skip s'
Yield x s' | p x -> Yield x s'
| otherwise -> Done
{-# INLINE [0] takeWhile #-}
dropWhile :: (a -> Bool) -> Stream a -> Stream a
dropWhile p (Stream next0 s0) = Stream next (S1 :!: s0)
where
# INLINE next #
next (S1 :!: s) = case next0 s of
Done -> Done
Skip s' -> Skip (S1 :!: s')
Yield x s' | p x -> Skip (S1 :!: s')
| otherwise -> Yield x (S2 :!: s')
next (S2 :!: s) = case next0 s of
Done -> Done
Skip s' -> Skip (S2 :!: s')
Yield x s' -> Yield x (S2 :!: s')
{-# INLINE [0] dropWhile #-}
{-
span :: (a -> Bool) -> Stream a -> (Stream a, Stream a)
break :: (a -> Bool) -> Stream a -> (Stream a, Stream a)
group :: Eq a => Stream a -> Stream (Stream a)
inits :: Stream a -> Stream (Stream a)
tails :: Stream a -> Stream (Stream a)
-}
------------------------------------------------------------------------
-- * Predicates
isPrefixOf :: Eq a => Stream a -> Stream a -> Bool
isPrefixOf (Stream stepa sa0) (Stream stepb sb0) = loop_isPrefixOf sa0 sb0 Nothing
where
loop_isPrefixOf !sa !sb Nothing = case stepa sa of
Done -> True
Skip sa' -> expose sa' $ loop_isPrefixOf sa' sb Nothing
Yield x sa' -> expose sa' $ loop_isPrefixOf sa' sb (Just (L x))
loop_isPrefixOf !sa !sb (Just (L x)) = case stepb sb of
Done -> False
Skip sb' -> expose sb' $ loop_isPrefixOf sa sb' (Just (L x))
Yield y sb' | x == y -> expose sb' $ loop_isPrefixOf sa sb' Nothing
| otherwise -> False
{-# INLINE [0] isPrefixOf #-}
{-
isSuffixOf :: Eq a => Stream a -> Stream a -> Bool
isInfixOf :: Eq a => Stream a -> Stream a -> Bool
-}
------------------------------------------------------------------------
-- * Searching streams
-- ** Searching by equality
elem :: Eq a => a -> Stream a -> Bool
elem x (Stream next s0) = loop_elem s0
where
loop_elem !s = case next s of
Done -> False
Skip s' -> expose s' $ loop_elem s'
Yield y s'
| x == y -> True
| otherwise -> expose s' $ loop_elem s'
{-# INLINE [0] elem #-}
{-
--
-- No need to provide notElem, as not . elem is just as fusible.
-- You can only fuse on the rhs of elem anyway.
--
notElem :: Eq a => a -> Stream a -> Bool
notElem x (Stream next s0) = loop s0
where
loop !s = case next s of
Done -> True
Skip s' -> loop s'
Yield y s' | x == y -> False
| otherwise -> loop s'
{-# INLINE [0] notElem #-}
-}
lookup :: Eq a => a -> Stream (a, b) -> Data.Maybe.Maybe b
lookup key (Stream next s0) = loop_lookup s0
where
loop_lookup !s = case next s of
Done -> Data.Maybe.Nothing
Skip s' -> expose s' $ loop_lookup s'
Yield (x, y) s' | key == x -> Data.Maybe.Just y
| otherwise -> expose s' $ loop_lookup s'
{-# INLINE [0] lookup #-}
------------------------------------------------------------------------
-- ** Searching with a predicate
find :: (a -> Bool) -> Stream a -> Data.Maybe.Maybe a
find p (Stream next s0) = loop_find s0
where
loop_find !s = case next s of
Done -> Data.Maybe.Nothing
Skip s' -> expose s' $ loop_find s'
Yield x s' | p x -> Data.Maybe.Just x
| otherwise -> expose s' $ loop_find s'
{-# INLINE [0] find #-}
filter :: (a -> Bool) -> Stream a -> Stream a
filter p (Stream next0 s0) = Stream next s0
where
# INLINE next #
next !s = case next0 s of
Done -> Done
Skip s' -> Skip s'
Yield x s' | p x -> Yield x s'
| otherwise -> Skip s'
{-# INLINE [0] filter #-}
# RULES
" Stream filter / filter fusion " forall p q s.
filter p ( filter q s ) = filter ( \x - > q x & & p x ) s
#
"Stream filter/filter fusion" forall p q s.
filter p (filter q s) = filter (\x -> q x && p x) s
#-}
--partition :: (a -> Bool) -> Stream a -> (Stream a, Stream a)
------------------------------------------------------------------------
-- * Indexing streams
index :: Stream a -> Int -> a
index (Stream next s0) n0
| n0 < 0 = error "Stream.(!!): negative index"
| otherwise = loop_index n0 s0
where
loop_index !n !s = case next s of
Done -> error "Stream.(!!): index too large"
Skip s' -> expose s' $ loop_index n s'
Yield x s' | n == 0 -> x
| otherwise -> expose s' $ loop_index (n-1) s'
{-# INLINE [0] index #-}
findIndex :: (a -> Bool) -> Stream a -> Data.Maybe.Maybe Int
findIndex p (Stream next s0) = loop_findIndex 0 s0
where
loop_findIndex !i !s = case next s of
Done -> Data.Maybe.Nothing
Skip s' -> expose s' $ loop_findIndex i s' -- hmm. not caught by QC
Yield x s' | p x -> Data.Maybe.Just i
| otherwise -> expose s' $ loop_findIndex (i+1) s'
{-# INLINE [0] findIndex #-}
elemIndex :: Eq a => a -> Stream a -> Data.Maybe.Maybe Int
elemIndex a (Stream next s0) = loop_elemIndex 0 s0
where
loop_elemIndex !i !s = case next s of
Done -> Data.Maybe.Nothing
Skip s' -> expose s' $ loop_elemIndex i s'
Yield x s' | a == x -> Data.Maybe.Just i
| otherwise -> expose s' $ loop_elemIndex (i+1) s'
{-# INLINE [0] elemIndex #-}
elemIndices :: Eq a => a -> Stream a -> Stream Int
elemIndices a (Stream next0 s0) = Stream next (S 0 :!: s0)
where
# INLINE next #
next (S n :!: s) = case next0 s of
Done -> Done
Skip s' -> Skip (S n :!: s')
Yield x s' | x == a -> Yield n (S (n+1) :!: s')
| otherwise -> Skip (S (n+1) :!: s')
{-# INLINE [0] elemIndices #-}
findIndices :: (a -> Bool) -> Stream a -> Stream Int
findIndices p (Stream next0 s0) = Stream next (S 0 :!: s0)
where
# INLINE next #
next (S n :!: s) = case next0 s of
Done -> Done
Skip s' -> Skip (S n :!: s')
Yield x s' | p x -> Yield n (S (n+1) :!: s')
| otherwise -> Skip (S (n+1) :!: s')
{-# INLINE [0] findIndices #-}
------------------------------------------------------------------------
-- * Zipping and unzipping streams
zip :: Stream a -> Stream b -> Stream (a, b)
zip = zipWith (,)
# INLINE zip #
zip3 :: Stream a -> Stream b -> Stream c -> Stream (a, b, c)
zip3 = zipWith3 (,,)
# INLINE zip3 #
zip4 :: Stream a -> Stream b -> Stream c -> Stream d -> Stream (a, b, c, d)
zip4 = zipWith4 (,,,)
# INLINE zip4 #
zip5 : : Stream a - > Stream b - > Stream c - > Stream d - > Stream e - > [ ( a , b , c , d , e ) ]
: : Stream a - > Stream b - > Stream c - > Stream d - > Stream e - > Stream f - > [ ( a , b , c , d , e , f ) ]
zip7 : : Stream a - > Stream b - > Stream c - > Stream d - > Stream e - > Stream f - > Stream g - > [ ( a , b , c , d , e , f , ) ]
zip5 :: Stream a -> Stream b -> Stream c -> Stream d -> Stream e -> [(a, b, c, d, e)]
zip6 :: Stream a -> Stream b -> Stream c -> Stream d -> Stream e -> Stream f -> [(a, b, c, d, e, f)]
zip7 :: Stream a -> Stream b -> Stream c -> Stream d -> Stream e -> Stream f -> Stream g -> [(a, b, c, d, e, f, g)]
-}
zipWith :: (a -> b -> c) -> Stream a -> Stream b -> Stream c
zipWith f (Stream next0 sa0) (Stream next1 sb0) = Stream next (sa0 :!: sb0 :!: Nothing)
where
# INLINE next #
next (sa :!: sb :!: Nothing) = case next0 sa of
Done -> Done
Skip sa' -> Skip (sa' :!: sb :!: Nothing)
Yield a sa' -> Skip (sa' :!: sb :!: Just (L a))
next (sa' :!: sb :!: Just (L a)) = case next1 sb of
Done -> Done
Skip sb' -> Skip (sa' :!: sb' :!: Just (L a))
Yield b sb' -> Yield (f a b) (sa' :!: sb' :!: Nothing)
{-# INLINE [0] zipWith #-}
zipWith3 :: (a -> b -> c -> d) -> Stream a -> Stream b -> Stream c -> Stream d
zipWith3 f (Stream nexta sa0)
(Stream nextb sb0)
(Stream nextc sc0) = Stream next (sa0 :!: sb0 :!: sc0 :!: Nothing)
where
# INLINE next #
next (sa :!: sb :!: sc :!: Nothing) = case nexta sa of
Done -> Done
Skip sa' -> Skip (sa' :!: sb :!: sc :!: Nothing)
Yield a sa' -> Skip (sa' :!: sb :!: sc :!: Just (L a :!: Nothing))
next (sa' :!: sb :!: sc :!: Just (L a :!: Nothing)) = case nextb sb of
Done -> Done
Skip sb' -> Skip (sa' :!: sb' :!: sc :!: Just (L a :!: Nothing))
Yield b sb' -> Skip (sa' :!: sb' :!: sc :!: Just (L a :!: Just (L b)))
next (sa' :!: sb' :!: sc :!: Just (L a :!: Just (L b))) = case nextc sc of
Done -> Done
Skip sc' -> Skip (sa' :!: sb' :!: sc' :!: Just (L a :!: Just (L b)))
Yield c sc' -> Yield (f a b c) (sa' :!: sb' :!: sc' :!: Nothing)
{-# INLINE [0] zipWith3 #-}
zipWith4 :: (a -> b -> c -> d -> e) -> Stream a -> Stream b -> Stream c -> Stream d -> Stream e
zipWith4 f (Stream nexta sa0)
(Stream nextb sb0)
(Stream nextc sc0)
(Stream nextd sd0) = Stream next (sa0 :!: sb0 :!: sc0 :!: sd0 :!: Nothing)
where
# INLINE next #
next (sa :!: sb :!: sc :!: sd :!: Nothing) =
case nexta sa of
Done -> Done
Skip sa' -> Skip (sa' :!: sb :!: sc :!: sd :!: Nothing)
Yield a sa' -> Skip (sa' :!: sb :!: sc :!: sd :!: Just (L a :!: Nothing))
next (sa' :!: sb :!: sc :!: sd :!: Just (L a :!: Nothing)) =
case nextb sb of
Done -> Done
Skip sb' -> Skip (sa' :!: sb' :!: sc :!: sd :!: Just (L a :!: Nothing))
Yield b sb' -> Skip (sa' :!: sb' :!: sc :!: sd :!: Just (L a :!: Just (L b :!: Nothing)))
next (sa' :!: sb' :!: sc :!: sd :!: Just (L a :!: (Just (L b :!: Nothing)))) =
case nextc sc of
Done -> Done
Skip sc' -> Skip (sa' :!: sb' :!: sc' :!: sd :!: Just (L a :!: (Just (L b :!: Nothing))))
Yield c sc' -> Skip (sa' :!: sb' :!: sc' :!: sd :!: Just (L a :!: (Just (L b :!: Just (L c)))))
next (sa' :!: sb' :!: sc' :!: sd :!: Just (L a :!: (Just (L b :!: Just (L c))))) =
case nextd sd of
Done -> Done
Skip sd' -> Skip (sa' :!: sb' :!: sc' :!: sd' :!: Just (L a :!: (Just (L b :!: Just (L c)))))
Yield d sd' -> Yield (f a b c d) (sa' :!: sb' :!: sc' :!: sd' :!: Nothing)
{-# INLINE [0] zipWith4 #-}
unzip :: Stream (a, b) -> ([a], [b])
unzip = foldr (\(a,b) ~(as, bs) -> (a:as, b:bs)) ([], [])
# INLINE unzip #
------------------------------------------------------------------------
-- * Special streams
-- ** Functions on strings
--
-- As a concatMap ( snoc ' \n ' )
--
unlines : : Stream ( Stream ) - > Stream ( Stream next s0 ) = Stream next ' ( Right s0 )
where
next ' ( Left ( Stream g t , s ) ) = case g t of
Done - > Skip ( Right s )
Skip t ' - > Skip ( Left ( Stream g t ' , s ) )
Yield x t ' - > Yield x ( Left ( Stream g t ' , s ) )
next ' ( Right s ) = case next s of
Done - > Done
Skip s ' - > Skip ( Right s ' )
Yield x s ' - > Skip ( Left ( ( snoc x ' \n ' ) , s ' ) )
{ - # INLINE [ 0 ] unlines #
--
-- As a concatMap (snoc '\n')
--
unlines :: Stream (Stream Char) -> Stream Char
unlines (Stream next s0) = Stream next' (Right s0)
where
next' (Left (Stream g t, s)) = case g t of
Done -> Skip (Right s)
Skip t' -> Skip (Left (Stream g t', s))
Yield x t' -> Yield x (Left (Stream g t', s))
next' (Right s) = case next s of
Done -> Done
Skip s' -> Skip (Right s')
Yield x s' -> Skip (Left ((snoc x '\n'), s'))
{-# INLINE [0] unlines #-}
-}
--
-- As a concat . intersperse
--
unlines ( Stream next s0 ) = Stream next ' ( Right s0 )
where
-- go
next ' ( Left ( Stream f t , s ) ) = case f t of
Done - > Yield ' \n ' ( Right s )
Skip t ' - > Skip ( Left ( Stream f t ' , s ) )
Yield x t ' - > Yield x ( Left ( Stream f t ' , s ) )
-- to
next ' ( Right s ) = case next s of
Done - > Done
Skip s ' - > Skip ( Right s ' )
Yield x s ' - > Skip ( Left ( x , s ' ) )
--
-- As a concat . intersperse
--
unlines (Stream next s0) = Stream next' (Right s0)
where
-- go
next' (Left (Stream f t, s)) = case f t of
Done -> Yield '\n' (Right s)
Skip t' -> Skip (Left (Stream f t', s))
Yield x t' -> Yield x (Left (Stream f t', s))
-- to
next' (Right s) = case next s of
Done -> Done
Skip s' -> Skip (Right s')
Yield x s' -> Skip (Left (x, s'))
-}
{-
lines :: Stream Char -> Stream [Char]
lines (Stream next0 s0) = Stream next (Nothing :!: s0)
where
{-# INLINE next #-}
next (Nothing :!: s) = case next0 s of
Done -> Done
Skip s' -> Skip (Nothing :!: s')
Yield _ _ -> Skip (Just (S []) :!: s) -- !
next (Just (S acc) :!: s) = case next0 s of
Done -> Yield (reverse acc) (Nothing :!: s) -- !
Skip s' -> Skip (Just (S acc) :!: s')
reuse first state
Yield x s' -> Skip (Just (S (x:acc)) :!: s')
# INLINE reverse #
reverse :: [Char] -> [Char]
reverse l = rev l []
where
rev [] a = a
rev (x:xs) a = rev xs (x:a)
-}
{-
lines :: Stream Char -> Stream (Stream Char)
lines (Stream next s0 len) = Stream next' s0 len
where
next' s = case next s of
Done -> Done
Skip s' -> Skip s'
-}
{-
lines' [] = []
lines' s = let (l, s') = break (== '\n') s
in l : case s' of
[] -> []
(_:s'') -> lines' s''
-}
{-
words :: String -> [String]
unlines :: [String] -> String
unwords :: [String] -> String
-}
------------------------------------------------------------------------
-- ** \"Set\" operations
{-
nub :: Eq a => Stream a -> Stream a
delete :: Eq a => a -> Stream a -> Stream a
difference :: Eq a => Stream a -> Stream a -> Stream a
union :: Eq a => Stream a -> Stream a -> Stream a
intersect :: Eq a => Stream a -> Stream a -> Stream a
-}
-- ** Ordered streams
sort : : a = > Stream a - > Stream a
insert : : a = > a - > Stream a - > Stream a
sort :: Ord a => Stream a -> Stream a
insert :: Ord a => a -> Stream a -> Stream a
-}
------------------------------------------------------------------------
-- * Generalized functions
-- ** The \"By\" operations
* * * User - supplied equality ( replacing an Eq context )
{-
nubBy :: (a -> a -> Bool) -> Stream a -> Stream a
deleteBy :: (a -> a -> Bool) -> a -> Stream a -> Stream a
deleteFirstsBy :: (a -> a -> Bool) -> Stream a -> Stream a -> Stream a
unionBy :: (a -> a -> Bool) -> Stream a -> Stream a -> Stream a
intersectBy :: (a -> a -> Bool) -> Stream a -> Stream a -> Stream a
groupBy :: (a -> a -> Bool) -> Stream a -> Stream (Stream a)
-}
------------------------------------------------------------------------
* * * User - supplied comparison ( replacing an context )
{-
sortBy :: (a -> a -> Ordering) -> Stream a -> Stream a
-}
insertBy :: (a -> a -> Ordering) -> a -> Stream a -> Stream a
insertBy cmp x (Stream next0 s0) = Stream next (S2 :!: s0)
where
# INLINE next #
-- find the insertion point
next (S2 :!: s) = case next0 s of
Done -> Yield x (S1 :!: s) -- a snoc
Skip s' -> Skip (S2 :!: s')
Yield y s' | GT == cmp x y -> Yield y (S2 :!: s')
| otherwise -> Yield x (S1 :!: s) -- insert
-- we've inserted, now just yield the rest of the stream
next (S1 :!: s) = case next0 s of
Done -> Done
Skip s' -> Skip (S1 :!: s')
Yield y s' -> Yield y (S1 :!: s')
{-# INLINE [0] insertBy #-}
maximumBy :: (a -> a -> Ordering) -> Stream a -> a
maximumBy cmp (Stream next s0) = loop0_maximumBy s0
where
loop0_maximumBy !s = case next s of
Skip s' -> expose s' $ loop0_maximumBy s'
Yield x s' -> expose s' $ loop_maximumBy x s'
Done -> errorEmptyStream "maximumBy"
loop_maximumBy z !s = case next s of
Done -> z
Skip s' -> expose s' $ loop_maximumBy z s'
Yield x s' -> expose s' $ loop_maximumBy (max' z x) s'
max' x y = case cmp x y of
GT -> x
_ -> y
{-# INLINE [0] maximumBy #-}
minimumBy :: (a -> a -> Ordering) -> Stream a -> a
minimumBy cmp (Stream next s0) = loop0_minimumBy s0
where
loop0_minimumBy !s = case next s of
Skip s' -> expose s' $ loop0_minimumBy s'
Yield x s' -> expose s' $ loop_minimumBy x s'
Done -> errorEmptyStream "minimum"
loop_minimumBy z !s = case next s of
Done -> z
Skip s' -> expose s' $ loop_minimumBy z s'
Yield x s' -> expose s' $ loop_minimumBy (min' z x) s'
min' x y = case cmp x y of
GT -> y
_ -> x
{-# INLINE [0] minimumBy #-}
------------------------------------------------------------------------
-- * The \"generic\" operations
-- length
genericLength :: Num i => Stream b -> i
genericLength (Stream next s0) = loop_genericLength s0
where
loop_genericLength !s = case next s of
Done -> 0
Skip s' -> expose s' $ loop_genericLength s'
Yield _ s' -> expose s' $ 1 + loop_genericLength s'
# INLINE [ 0 ] genericLength #
TODO : specialised generic Length for strict / atomic and associative
instances like and Integer
genericTake :: Integral i => i -> Stream a -> Stream a
genericTake n0 (Stream next0 s0) = Stream next (L n0 :!: s0)
where
# INLINE next #
next (L 0 :!: _) = Done
next (L n :!: s) = case next0 s of
Done -> Done
Skip s' -> Skip (L n :!: s')
Yield x s'
| n > 0 -> Yield x (L (n-1) :!: s')
| otherwise -> error "List.genericTake: negative argument"
{-# INLINE [0] genericTake #-}
-- genericTake is defined so bizzarely!
genericDrop :: Integral i => i -> Stream a -> Stream a
genericDrop n0 (Stream next0 s0) = Stream next (Just (L n0) :!: s0)
where
# INLINE next #
next (Just (L 0) :!: s) = Skip (Nothing :!: s)
next (Just (L n) :!: s) = case next0 s of
Done -> Done
Skip s' -> Skip (Just (L n) :!: s')
Yield _ s' | n > 0 -> Skip (Just (L (n-1)) :!: s')
| otherwise -> error "List.genericDrop: negative argument"
next (Nothing :!: s) = case next0 s of
Done -> Done
Skip s' -> Skip (Nothing :!: s')
Yield x s' -> Yield x (Nothing :!: s')
{-# INLINE [0] genericDrop #-}
genericIndex :: Integral a => Stream b -> a -> b
genericIndex (Stream next s0) i0 = loop_genericIndex i0 s0
where
loop_genericIndex i !s = case next s of
Done -> error "List.genericIndex: index too large."
Skip s' -> expose s' $ loop_genericIndex i s'
Yield x s' | i == 0 -> x
| i > 0 -> expose s' $ loop_genericIndex (i-1) s'
| otherwise -> error "List.genericIndex: negative argument."
{-# INLINE [0] genericIndex #-}
-- can we pull the n > 0 test out and do it just once?
-- probably not since we don't know what n-1 does!!
-- can only specialise it for sane Integral instances :-(
genericSplitAt :: Integral i => i -> Stream a -> ([a], [a])
genericSplitAt n0 (Stream next s0) = loop_genericSplitAt n0 s0
where
loop_genericSplitAt 0 !s = ([], expose s $ unstream (Stream next s))
loop_genericSplitAt n !s = case next s of
Done -> ([], [])
Skip s' -> expose s $ loop_genericSplitAt n s'
Yield x s'
| n > 0 -> (x:xs', xs'')
| otherwise -> error "List.genericSplitAt: negative argument"
where
(xs', xs'') = expose s $ loop_genericSplitAt (n-1) s'
{-# INLINE [0] genericSplitAt #-}
{-
-- No need:
genericReplicate -- :: Integral i => i -> a -> Stream a
-}
-- ---------------------------------------------------------------------
enumFromToNum : : ( a , a ) = > a - > a - > Stream a
enumFromToNum x y = Stream next ( L x )
where
{ - # INLINE next #
enumFromToNum :: (Ord a, Num a) => a -> a -> Stream a
enumFromToNum x y = Stream next (L x)
where
{-# INLINE next #-}
next (L !n)
| n > y = Done
| otherwise = Yield n (L (n+1))
{-# INLINE [0] enumFromToNum #-}
-}
enumFromToInt :: Int -> Int -> Stream Int
enumFromToInt x y = Stream next (L x)
where
# INLINE next #
next (L !n)
| n > y = Done
| otherwise = Yield n (L (n+1))
{-# INLINE [0] enumFromToInt #-}
enumDeltaInteger :: Integer -> Integer -> Stream Integer
enumDeltaInteger a d = Stream next (L a)
where
# INLINE next #
next (L !x) = Yield x (L (x+d))
{-# INLINE [0] enumDeltaInteger #-}
enumFromToChar :: Char -> Char -> Stream Char
enumFromToChar x y = Stream next (L (ord x))
where
m = ord y
# INLINE next #
next (L !n)
| n > m = Done
| otherwise = Yield (chr n) (L (n+1))
{-# INLINE [0] enumFromToChar #-}
-- ---------------------------------------------------------------------
Monadic stuff
-- Most monadic list functions can be defined in terms of foldr so don't
need explicit stream implementations . The one exception is foldM :
--
foldM :: Monad m => (b -> a -> m b) -> b -> Stream a -> m b
foldM f z0 (Stream next s0) = loop_foldl z0 s0
where
loop_foldl z !s = case next s of
Done -> Monad.return z
Skip s' -> expose s' $ loop_foldl z s'
Yield x s' -> expose s' $ f z x >>= \z' -> loop_foldl z' s'
{-# INLINE [0] foldM #-}
foldM_ :: Monad m => (b -> a -> m b) -> b -> Stream a -> m ()
foldM_ f z0 (Stream next s0) = loop_foldl z0 s0
where
loop_foldl z !s = case next s of
Done -> Monad.return ()
Skip s' -> expose s' $ loop_foldl z s'
Yield x s' -> expose s' $ f z x >>= \z' -> loop_foldl z' s'
{-# INLINE [0] foldM_ #-}
-- ---------------------------------------------------------------------
-- List comprehension desugaring
return :: a -> Stream a
return e = Stream next S1
where
# INLINE next #
next S1 = Yield e S2
next S2 = Done
{-# INLINE [0] return #-}
guard :: Bool -> Stream a -> Stream a
guard b (Stream next0 s0) = Stream next (S1 :!: s0)
where
# INLINE next #
next (S1 :!: s) = if b then Skip (S2 :!: s) else Done
next (S2 :!: s) = case next0 s of
Done -> Done
Skip s' -> Skip (S2 :!: s')
Yield x s' -> Yield x (S2 :!: s')
{-# INLINE [0] guard #-}
bind :: (a -> Bool) -> (a -> Stream b) -> Stream a -> Stream b
bind b f (Stream next0 s0) = Stream next (s0 :!: Nothing)
where
# INLINE next #
next (s :!: Nothing) = case next0 s of
Done -> Done
Skip s' -> Skip (s' :!: Nothing)
Yield x s'
| b x -> Skip (s' :!: Just (f x))
| otherwise -> Skip (s' :!: Nothing)
next (s :!: Just (Stream next1 s1)) = case next1 s1 of
Done -> Skip (s :!: Nothing)
Skip s1' -> Skip (s :!: Just (Stream next1 s1'))
Yield x s1' -> Yield x (s :!: Just (Stream next1 s1'))
{-# INLINE [0] bind #-}
mapFilter :: (a -> Bool) -> (a -> b) -> Stream a -> Stream b
mapFilter b f (Stream next0 s0) = Stream next s0
where
# INLINE next #
next s = case next0 s of
Done -> Done
Skip s' -> Skip s'
Yield x s'
| b x -> Yield (f x) s'
| otherwise -> Skip s'
{-# INLINE [0] mapFilter #-}
declare :: (a -> Stream b) -> a -> Stream b
declare f bs = Stream next (f bs)
where
# INLINE next #
next (Stream next0 s) = case next0 s of
Done -> Done
Skip s' -> Skip (Stream next0 s')
Yield x s' -> Yield x (Stream next0 s')
{-# INLINE [0] declare #-}
-- ---------------------------------------------------------------------
Internal utilities
-- Common up near identical calls to `error' to reduce the number
-- constant strings created when compiled:
errorEmptyStream :: String -> a
errorEmptyStream fun = moduleError fun "empty list"
# NOINLINE errorEmptyStream #
moduleError :: String -> String -> a
moduleError fun msg = error ("List." ++ fun ++ ':':' ':msg)
# NOINLINE moduleError #
#endif
| null |
https://raw.githubusercontent.com/HugoPeters1024/hs-sleuth/91aa2806ea71b7a26add3801383b3133200971a5/test-project/stream-fusion/Data/Stream.hs
|
haskell
|
# LANGUAGE BangPatterns #
# LANGUAGE CPP #
# LANGUAGE TypeOperators #
|
Module : Data.Stream
License : BSD-style
Maintainer :
Stability : experimental
Stream fusion for sequences. Described in:
* /Stream Fusion: From Lists to Streams to Nothing at All/, by
</~dons/papers/CLS07.html>
</~dons/papers/CSL06.html>
See the source for the complete story:
* </~dons/code/streams/list/Data/Stream.hs>
* The stream data type
* Conversions with lists
:: [a] -> Stream a
:: Stream a -> [a]
internal grunge
hmm, does this affect whether these get removed?
* Basic stream functions
:: Stream a -> Stream a -> Stream a
:: Stream a -> [a] -> [a]
:: a -> Stream a -> Stream a
:: Stream a -> a -> Stream a
:: Stream a -> a
:: Stream a -> a
:: Stream a -> Stream a
:: Stream a -> Stream a
:: Stream a -> Bool
:: Stream a -> Int
* Stream transformations
:: (a -> b) -> Stream a -> Stream b
reverse, -- :: Stream a -> Stream a
:: a -> Stream a -> Stream a
intercalate, -- :: Stream a -> Stream (Stream a) -> Stream a
transpose, -- :: Stream (Stream a) -> Stream (Stream a)
* Reducing streams (folds)
:: (b -> a -> b) -> b -> Stream a -> b
:: (b -> a -> b) -> b -> Stream a -> b
:: (a -> a -> a) -> Stream a -> a
:: (a -> a -> a) -> Stream a -> a
:: (a -> b -> b) -> b -> Stream a -> b
:: (a -> a -> a) -> Stream a -> a
** Special folds
:: Stream [a] -> [a]
:: (a -> Stream b) -> Stream a -> Stream b
:: Stream Bool -> Bool
:: Stream Bool -> Bool
:: (a -> Bool) -> Stream a -> Bool
:: (a -> Bool) -> Stream a -> Bool
* Building lists
** Scans
:: (a -> b -> a) -> a -> Stream b -> Stream a
:: (a -> a -> a) -> Stream a -> Stream a
scanr, -- :: (a -> b -> b) -> b -> Stream a -> Stream b
scanr1, -- :: (a -> a -> a) -> Stream a -> Stream a
* * Accumulating maps
: : ( acc - > x - > ( acc , y ) ) - > acc - > Stream x - > ( acc , Stream y )
: : ( acc - > x - > ( acc , y ) ) - > acc - > Stream x - > ( acc , Stream y )
** Accumulating maps
:: (acc -> x -> (acc, y)) -> acc -> Stream x -> (acc, Stream y)
:: (acc -> x -> (acc, y)) -> acc -> Stream x -> (acc, Stream y)
** Infinite streams
:: (a -> a) -> a -> Stream a
:: a -> Stream a
:: Int -> a -> Stream a
:: Stream a -> Stream a
** Unfolding
:: (b -> Maybe (a, b)) -> b -> Stream a
* Substreams
** Extracting substreams
:: Int -> Stream a -> Stream a
:: Int -> Stream a -> Stream a
:: Int -> Stream a -> ([a], [a])
:: (a -> Bool) -> Stream a -> Stream a
:: (a -> Bool) -> Stream a -> Stream a
span, -- :: (a -> Bool) -> Stream a -> (Stream a, Stream a)
break, -- :: (a -> Bool) -> Stream a -> (Stream a, Stream a)
group, -- :: Eq a => Stream a -> Stream (Stream a)
inits, -- :: Stream a -> Stream (Stream a)
tails, -- :: Stream a -> Stream (Stream a)
* Predicates
:: Eq a => Stream a -> Stream a -> Bool
: : Eq a = > Stream a - > Stream a - > Bool
: : Eq a = > Stream a - > Stream a - > Bool
:: Eq a => Stream a -> Stream a -> Bool
:: Eq a => Stream a -> Stream a -> Bool
* Searching streams
** Searching by equality
:: Eq a => a -> Stream a -> Bool
:: Eq a => a -> Stream (a, b) -> Maybe b
** Searching with a predicate
:: (a -> Bool) -> Stream a -> Maybe a
:: (a -> Bool) -> Stream a -> Stream a
partition, -- :: (a -> Bool) -> Stream a -> ([a], [a])
* Indexing streams
:: Stream a -> Int -> a
:: (a -> Bool) -> Stream a -> Maybe Int
:: Eq a => a -> Stream a -> Maybe Int
:: Eq a => a -> Stream a -> Stream Int
:: (a -> Bool) -> Stream a -> Stream Int
* Zipping and unzipping streams
:: Stream a -> Stream b -> Stream (a, b)
:: Stream a -> Stream b -> Stream c -> Stream (a, b, c)
:: (a -> b -> c) -> Stream a -> Stream b -> Stream c
:: (a -> b -> c -> d) -> Stream a -> Stream b -> Stream c -> Stream d
:: Stream (a, b) -> (Stream a, Stream b)
: : Stream ( a , b , c ) - > ( Stream a , Stream b , Stream c )
:: Stream (a, b, c) -> (Stream a, Stream b, Stream c)
* Special streams
** Functions on strings
: : Stream Char - > Stream [ Char ]
: : Stream ( Stream ) - > Stream Char
: : Stream Char - > Stream ( Stream Char )
: : Stream ( Stream ) - > Stream
:: Stream Char -> Stream [Char]
:: Stream (Stream Char) -> Stream Char
:: Stream Char -> Stream (Stream Char)
:: Stream (Stream Char) -> Stream Char
-- ** \"Set\" operations
nub, -- :: Eq a => Stream a -> Stream a
delete, -- :: Eq a => a -> Stream a -> Stream a
(\\), -- :: Eq a => Stream a -> Stream a -> Stream a
union, -- :: Eq a => Stream a -> Stream a -> Stream a
intersect, -- :: Eq a => Stream a -> Stream a -> Stream a
* * Ordered streams
: : a = > Stream a - > Stream a
: : a = > a - > Stream a - > Stream a
** Ordered streams
:: Ord a => Stream a -> Stream a
:: Ord a => a -> Stream a -> Stream a
* Generalized functions
* * The \"By\ " operations
* * * User - supplied equality ( replacing an Eq context )
: : ( a - > a - > Bool ) - > Stream a - > Stream a
: : ( a - > a - > Bool ) - > a - > Stream a - > Stream a
: : ( a - > a - > Bool ) - > Stream a - > Stream a - > Stream a
: : ( a - > a - > Bool ) - > Stream a - > Stream a - > Stream a
: : ( a - > a - > Bool ) - > Stream a - > Stream a - > Stream a
: : ( a - > a - > Bool ) - > Stream a - > Stream ( Stream a )
* Generalized functions
** The \"By\" operations
*** User-supplied equality (replacing an Eq context)
:: (a -> a -> Bool) -> Stream a -> Stream a
:: (a -> a -> Bool) -> a -> Stream a -> Stream a
:: (a -> a -> Bool) -> Stream a -> Stream a -> Stream a
:: (a -> a -> Bool) -> Stream a -> Stream a -> Stream a
:: (a -> a -> Bool) -> Stream a -> Stream a -> Stream a
:: (a -> a -> Bool) -> Stream a -> Stream (Stream a)
:: (a -> a -> Ordering) -> a -> Stream a -> Stream a
sortBy, -- :: (a -> a -> Ordering) -> Stream a -> Stream a
:: (a -> a -> Ordering) -> Stream a -> a
:: (a -> a -> Ordering) -> Stream a -> a
* The \"generic\" operations
:: Integral i => i -> Stream a -> Stream a
:: Integral i => i -> Stream a -> Stream a
:: Integral a => Stream b -> a -> b
:: Integral i => i -> Stream a -> ([a], [a])
:: Int -> Int -> Stream Int
:: Integer -> Integer -> Stream Integer
* Monad
* List comprehension desugaring
:: a -> Stream a
:: Bool -> Stream a -> Stream a
:: (a -> Bool) -> (a -> [b]) -> [a] -> [b]
:: (a -> Bool) -> (a -> b) -> [a] -> [b]
:: (a -> Stream b) -> a -> Stream b
# SOURCE #
# SOURCE #
# SOURCE #
why >> ? we're not using it
for error messages:
for error messages:
----------------------------------------------------------------------
The stream data type
| A stream.
It is important that we never construct a bottom stream, because the
fusion rule is not true for bottom streams.
The suspicion is that under fusion the append will force the bottom.
a stepper function
an initial state
| A stream step.
A step either ends a stream, skips a value, or yields a value
Stream type above enforces a separation between user's types and the
types used in stream states.
| This expose function needs to be called in folds/loops that consume
streams to expose the structure of the stream state to the simplifier
code for single-method dictionaries
| A useful unlifted type
| Unlifted pairs, Maybe and Either
# INLINE expose #
| Unlifted Maybes
# INLINE expose #
| Unlifted sums
# INLINE expose #
| Some stream functions (notably concatMap) need to use a stream as a state
# INLINE expose #
| Boxes for user's state. This is the gateway for user's types into unlifted
stream states. The L is always safe since it's lifted/lazy, exposing/seqing
it does nothing.
S is unlifted and so is only suitable for users states that we know we can
be strict in. This requires attention and auditing.
lazy / lifted
strict / unlifted
# INLINE expose #
# INLINE expose #
coding conventions;
* we tag local loops with their wrapper's name, so they're easier to
---------------------------------------------------------------------
List/Stream conversion
| Construct an abstract stream from a list.
# INLINE [0] stream #
| Flatten a stream back into a list.
# INLINE [0] unstream #
/The/ stream fusion rule
---------------------------------------------------------------------
Basic stream functions
(++)
# INLINE [0] append #
to unstream, but conses onto a given list rather than []:
# INLINE [0] append1 #
# INLINE [0] snoc #
# INLINE [0] cons #
head
# INLINE [0] head #
last
# INLINE [0] last #
tail
drop the head
# INLINE [0] tail #
init
# INLINE [0] init #
null
# INLINE [0] null #
length
# INLINE [0] length #
-- For lazy bytestrings
length64 :: Stream a -> Int64
length64 (Stream next s0) = loop (0::Int64) s0
where
loop z !s = case next s of
Done -> z
Skip s' -> loop z s'
Yield _ s' -> loop (z+1) s'
{-# INLINE [0] length64 #
---------------------------------------------------------------------
Stream transformations
map
# INLINE [0] map #
a convenient rule for map
next (_ :!: (Just (L _))) :!: S2 -- can't happen
intersperse :: a -> Stream a -> [a]
intersperse sep (Stream next s0) = loop_intersperse_start s0
where
loop_intersperse_start !s = case next s of
Done -> []
Skip s' -> expose s' $ loop_intersperse_start s'
Yield x s' -> expose s' $ x : loop_intersperse_go s'
loop_intersperse_go !s = case next s of
Done -> []
Skip s' -> expose s' $ loop_intersperse_go s'
Yield x s' -> expose s' $ sep : x : loop_intersperse_go s'
intercalate :: Stream a -> Stream (Stream a) -> Stream a
transpose :: Stream (Stream a) -> Stream (Stream a)
----------------------------------------------------------------------
* Reducing streams (folds)
# INLINE [0] foldl #
# INLINE [0] foldl' #
# INLINE [0] foldl1 #
# INLINE [0] foldr #
# INLINE [0] foldr1 #
----------------------------------------------------------------------
** Special folds
concat
# INLINE [0] concat #
concat :: Stream [a] -> Stream a
concat (Stream next0 s0) = Stream next (Nothing :!: s0)
where
{-# INLINE next #
concatMap :: (a -> [b]) -> Stream a -> [b]
concatMap f (Stream next s0) = loop_concatMap_to s0
where
loop_concatMap_go [] !s = expose s $ loop_concatMap_to s
loop_concatMap_go (b:bs) !s = expose s $ b : loop_concatMap_go bs s
loop_concatMap_to !s = case next s of
Done -> []
Skip s' -> expose s' $ loop_concatMap_to s'
Yield a s' -> expose s' $ loop_concatMap_go (f a) s'
{-# INLINE [0] concatMap #
concatMap :: (a -> [b]) -> Stream a -> Stream b
concatMap f (Stream next0 s0) = Stream next (Nothing :!: s0)
where
{-# INLINE next #
Here's an approach to fusing concatMap fully:
we try and match the Stream inside in the argument to concatMap and pass that
directly to a concatMap' variant. The point here is that the step function does
not depend on 'x', something which the rule below does not enforce :-)
concatMap' :: Unlifted s => (s -> Step b s) -> (a -> s) -> Stream a -> Stream b
concatMap' nextb f (Stream nexta sa0) = Stream next (sa0 :!: Nothing)
where
{-# INLINE next #
-- note the nested stream is a little hard to construct in a fusible
-- manner
--
concat :: Stream (Stream a) -> Stream a
concat (Stream next0 s0) = Stream next (Right s0)
where
{-# INLINE next #
# INLINE [0] concat #
# INLINE [0] concatMap #
# INLINE [0] any #
# INLINE [0] all #
note: strict in the accumulator!
# INLINE [0] sum #
note: strict in the accumulator!
# INLINE [0] product #
note, lazy in the accumulator
# INLINE [0] maximum #
# RULES
"maximumInt" maximum = (strictMaximum :: Stream Int -> Int);
"maximumChar" maximum = (strictMaximum :: Stream Char -> Char)
#
# INLINE [0] strictMaximum #
# INLINE [0] minimum #
# RULES
"minimumInt" minimum = (strictMinimum :: Stream Int -> Int);
"minimumChar" minimum = (strictMinimum :: Stream Char -> Char)
#
# INLINE [0] strictMinimum #
----------------------------------------------------------------------
* Building lists
** Scans
in order to get the z0th element
# INLINE [0] scanl1 #
hmm. hard.
hmm .
hmm.
# INLINE [0] scanl #
should be using strict pairs ? ?
flip f
should be using strict pairs??
flip f
# INLINE [0] scanr #
----------------------------------------------------------------------
** Accumulating maps
not right :
not right:
# INLINE [0] mapAccumL #
----------------------------------------------------------------------
** Infinite streams
# INLINE [0] iterate #
# INLINE [0] repeat #
# RULES
"map/repeat" forall f x. map f (repeat x) = repeat (f x)
#
# INLINE [0] replicate #
# RULES
"map/replicate" forall f n x. map f (replicate n x) = replicate n (f x)
#
"reverse/replicate" forall n x. reverse (replicate n x) = replicate n x
# INLINE [0] cycle #
----------------------------------------------------------------------
** Unfolding
# INLINE [0] unfoldr #
----------------------------------------------------------------------
* Substreams
** Extracting substreams
# INLINE [0] take #
# INLINE [0] drop #
TODO: could perhaps use 0 instead of Nothing, so long as
spec constr works with that
TODO: we should not need this special case, (n < 0) should be as
# INLINE [0] splitAt #
# INLINE [0] takeWhile #
# INLINE [0] dropWhile #
span :: (a -> Bool) -> Stream a -> (Stream a, Stream a)
break :: (a -> Bool) -> Stream a -> (Stream a, Stream a)
group :: Eq a => Stream a -> Stream (Stream a)
inits :: Stream a -> Stream (Stream a)
tails :: Stream a -> Stream (Stream a)
----------------------------------------------------------------------
* Predicates
# INLINE [0] isPrefixOf #
isSuffixOf :: Eq a => Stream a -> Stream a -> Bool
isInfixOf :: Eq a => Stream a -> Stream a -> Bool
----------------------------------------------------------------------
* Searching streams
** Searching by equality
# INLINE [0] elem #
--
-- No need to provide notElem, as not . elem is just as fusible.
-- You can only fuse on the rhs of elem anyway.
--
notElem :: Eq a => a -> Stream a -> Bool
notElem x (Stream next s0) = loop s0
where
loop !s = case next s of
Done -> True
Skip s' -> loop s'
Yield y s' | x == y -> False
| otherwise -> loop s'
{-# INLINE [0] notElem #
# INLINE [0] lookup #
----------------------------------------------------------------------
** Searching with a predicate
# INLINE [0] find #
# INLINE [0] filter #
partition :: (a -> Bool) -> Stream a -> (Stream a, Stream a)
----------------------------------------------------------------------
* Indexing streams
# INLINE [0] index #
hmm. not caught by QC
# INLINE [0] findIndex #
# INLINE [0] elemIndex #
# INLINE [0] elemIndices #
# INLINE [0] findIndices #
----------------------------------------------------------------------
* Zipping and unzipping streams
# INLINE [0] zipWith #
# INLINE [0] zipWith3 #
# INLINE [0] zipWith4 #
----------------------------------------------------------------------
* Special streams
** Functions on strings
As a concatMap ( snoc ' \n ' )
As a concatMap (snoc '\n')
# INLINE [0] unlines #
As a concat . intersperse
go
to
As a concat . intersperse
go
to
lines :: Stream Char -> Stream [Char]
lines (Stream next0 s0) = Stream next (Nothing :!: s0)
where
{-# INLINE next #
!
!
lines :: Stream Char -> Stream (Stream Char)
lines (Stream next s0 len) = Stream next' s0 len
where
next' s = case next s of
Done -> Done
Skip s' -> Skip s'
lines' [] = []
lines' s = let (l, s') = break (== '\n') s
in l : case s' of
[] -> []
(_:s'') -> lines' s''
words :: String -> [String]
unlines :: [String] -> String
unwords :: [String] -> String
----------------------------------------------------------------------
** \"Set\" operations
nub :: Eq a => Stream a -> Stream a
delete :: Eq a => a -> Stream a -> Stream a
difference :: Eq a => Stream a -> Stream a -> Stream a
union :: Eq a => Stream a -> Stream a -> Stream a
intersect :: Eq a => Stream a -> Stream a -> Stream a
** Ordered streams
----------------------------------------------------------------------
* Generalized functions
** The \"By\" operations
nubBy :: (a -> a -> Bool) -> Stream a -> Stream a
deleteBy :: (a -> a -> Bool) -> a -> Stream a -> Stream a
deleteFirstsBy :: (a -> a -> Bool) -> Stream a -> Stream a -> Stream a
unionBy :: (a -> a -> Bool) -> Stream a -> Stream a -> Stream a
intersectBy :: (a -> a -> Bool) -> Stream a -> Stream a -> Stream a
groupBy :: (a -> a -> Bool) -> Stream a -> Stream (Stream a)
----------------------------------------------------------------------
sortBy :: (a -> a -> Ordering) -> Stream a -> Stream a
find the insertion point
a snoc
insert
we've inserted, now just yield the rest of the stream
# INLINE [0] insertBy #
# INLINE [0] maximumBy #
# INLINE [0] minimumBy #
----------------------------------------------------------------------
* The \"generic\" operations
length
# INLINE [0] genericTake #
genericTake is defined so bizzarely!
# INLINE [0] genericDrop #
# INLINE [0] genericIndex #
can we pull the n > 0 test out and do it just once?
probably not since we don't know what n-1 does!!
can only specialise it for sane Integral instances :-(
# INLINE [0] genericSplitAt #
-- No need:
genericReplicate -- :: Integral i => i -> a -> Stream a
---------------------------------------------------------------------
# INLINE next #
# INLINE [0] enumFromToNum #
# INLINE [0] enumFromToInt #
# INLINE [0] enumDeltaInteger #
# INLINE [0] enumFromToChar #
---------------------------------------------------------------------
Most monadic list functions can be defined in terms of foldr so don't
# INLINE [0] foldM #
# INLINE [0] foldM_ #
---------------------------------------------------------------------
List comprehension desugaring
# INLINE [0] return #
# INLINE [0] guard #
# INLINE [0] bind #
# INLINE [0] mapFilter #
# INLINE [0] declare #
---------------------------------------------------------------------
Common up near identical calls to `error' to reduce the number
constant strings created when compiled:
|
# LANGUAGE ExistentialQuantification #
Copyright : ( c ) 2007
( c ) 2007 - 2013
Portability : portable , requires
Tested with : GHC 6.6
, and , ICFP 2007 .
* /Rewriting Haskell Strings/ , by , and
Roman Leshchinskiy , Practical Aspects of Declarative Languages
8th International Symposium , PADL 2007 , 2007 .
module Data.Stream (
#ifndef __HADDOCK__
Stream(Stream),
Step(..),
: : a = > Stream a - > a
: : a = > Stream a - > a
: : a = > Stream a - > a
: : a = > Stream a - > a
: : a = > Stream a - > a
: : a = > Stream a - > a
-}
-}
zip4,
zipWith4,
zip4 , , zip6 , zip7 ,
zipWith4 , zipWith5 , zipWith6 , zipWith7 ,
zip4, zip5, zip6, zip7,
zipWith4, zipWith5, zipWith6, zipWith7,
-}
, unzip5 , unzip6 , ,
unzip4, unzip5, unzip6, unzip7,
-}
-}
-}
-}
* * * User - supplied comparison ( replacing an context )
: : i = > Stream b - > i
*
: : Stream
: : = > ( b - > a - > m b ) - > b - > Stream a - > m b
: : = > ( b - > a - > m b ) - > b - > Stream a - > m ( )
#endif
) where
#ifndef __HADDOCK__
#ifndef EXTERNAL_PACKAGE
import GHC.Base (Int, Char, Eq(..), Ord(..), Functor(..), Bool(..), (&&),
Ordering(..),
(||),(&&), ($),
seq, otherwise, ord, chr,
String, (++))
import qualified GHC.Base as Monad (Monad(return))
import Data.Tuple ()
#else
import Prelude (
error,
Num(..),
Integral(..),
Integer,
Int, Char, Eq(..), Ord(..), Functor(..), Ordering(..), Bool(..),
(&&), (||), ($),
seq, otherwise,
Monad((>>=)),
String, (++))
import qualified Prelude as Monad (Monad(return))
import Data.Char (ord,chr)
#endif
import qualified Data.Maybe (Maybe(..))
> ( replicate 1 True ) + + ( tail undefined )
data Stream a = forall s. Unlifted s =>
data Step a s = Yield a !s
| Skip !s
| Done
instance Functor Stream where fmap = map
| A class of strict unlifted types . The Unlifted constraint in the
class Unlifted a where
In particular , to SpecConstr .
expose :: a -> b -> b
expose = seq
| This makes GHC 's optimiser happier ; it sometimes produces really bad
unlifted_dummy :: a
unlifted_dummy = error "unlifted_dummy"
| Unlifted versions of ( ) and for use in Stream states .
data None = None
instance Unlifted None
data Switch = S1 | S2
instance Unlifted Switch
data a :!: b = !a :!: !b
instance (Unlifted a, Unlifted b) => Unlifted (a :!: b) where
expose (a :!: b) s = expose a (expose b s)
data Maybe a = Nothing | Just !a
instance Unlifted a => Unlifted (Maybe a) where
expose (Just a) s = expose a s
expose Nothing s = s
data Either a b = Left !a | Right !b
instance (Unlifted a, Unlifted b) => Unlifted (Either a b) where
expose (Left a) s = expose a s
expose (Right b) s = expose b s
instance Unlifted (Stream a) where
expose (Stream next s0) s = seq next (seq s0 s)
instance Unlifted (L a) where
expose (L _) s = s
instance Unlifted (S a) where
expose (S a) s = seq a s
spot in Core output
stream :: [a] -> Stream a
stream xs0 = Stream next (L xs0)
where
# INLINE next #
next (L []) = Done
next (L (x:xs)) = Yield x (L xs)
unstream :: Stream a -> [a]
unstream (Stream next s0) = unfold_unstream s0
where
unfold_unstream !s = case next s of
Done -> []
Skip s' -> expose s' $ unfold_unstream s'
Yield x s' -> expose s' $ x : unfold_unstream s'
# RULES
" STREAM stream / unstream fusion " forall s.
stream ( unstream s ) = s
#
"STREAM stream/unstream fusion" forall s.
stream (unstream s) = s
#-}
append :: Stream a -> Stream a -> Stream a
append (Stream next0 s01) (Stream next1 s02) = Stream next (Left s01)
where
# INLINE next #
next (Left s1) = case next0 s1 of
Done -> Skip (Right s02)
Skip s1' -> Skip (Left s1')
Yield x s1' -> Yield x (Left s1')
next (Right s2) = case next1 s2 of
Done -> Done
Skip s2' -> Skip (Right s2')
Yield x s2' -> Yield x (Right s2')
version that can share the second list arg , really very similar
unstream s = append1 s [ ]
append1 :: Stream a -> [a] -> [a]
append1 (Stream next s0) xs = loop_append1 s0
where
loop_append1 !s = case next s of
Done -> xs
Skip s' -> expose s' loop_append1 s'
Yield x s' -> expose s' $ x : loop_append1 s'
snoc :: Stream a -> a -> Stream a
snoc (Stream next0 xs0) w = Stream next (Just xs0)
where
# INLINE next #
next (Just xs) = case next0 xs of
Done -> Yield w Nothing
Skip xs' -> Skip (Just xs')
Yield x xs' -> Yield x (Just xs')
next Nothing = Done
cons :: a -> Stream a -> Stream a
cons w (Stream next0 s0) = Stream next (S2 :!: s0)
where
# INLINE next #
next (S2 :!: s) = Yield w (S1 :!: s)
next (S1 :!: s) = case next0 s of
Done -> Done
Skip s' -> Skip (S1 :!: s')
Yield x s' -> Yield x (S1 :!: s')
head :: Stream a -> a
head (Stream next s0) = loop_head s0
where
loop_head !s = case next s of
Yield x _ -> x
Skip s' -> expose s' $ loop_head s'
Done -> errorEmptyStream "head"
last :: Stream a -> a
last (Stream next s0) = loop0_last s0
where
loop0_last !s = case next s of
Done -> errorEmptyStream "last"
Skip s' -> expose s' $ loop0_last s'
Yield x s' -> expose s' $ loop_last x s'
loop_last x !s = case next s of
Done -> x
Skip s' -> expose s' $ loop_last x s'
Yield x' s' -> expose s' $ loop_last x' s'
tail :: Stream a -> Stream a
tail (Stream next0 s0) = Stream next (S1 :!: s0)
where
# INLINE next #
next (S1 :!: s) = case next0 s of
Done -> errorEmptyStream "tail"
Skip s' -> Skip (S1 :!: s')
next (S2 :!: s) = case next0 s of
Done -> Done
Skip s' -> Skip (S2 :!: s')
Yield x s' -> Yield x (S2 :!: s')
init :: Stream a -> Stream a
init (Stream next0 s0) = Stream next (Nothing :!: s0)
where
# INLINE next #
next (Nothing :!: s) = case next0 s of
Done -> errorEmptyStream "init"
Skip s' -> Skip (Nothing :!: s')
Yield x s' -> Skip (Just (L x) :!: s')
next (Just (L x) :!: s) = case next0 s of
Done -> Done
Skip s' -> Skip (Just (L x) :!: s')
Yield x' s' -> Yield x (Just (L x') :!: s')
null :: Stream a -> Bool
null (Stream next s0) = loop_null s0
where
loop_null !s = case next s of
Done -> True
Yield _ _ -> False
Skip s' -> expose s' $ loop_null s'
length :: Stream a -> Int
length (Stream next s0) = loop_length (0::Int) s0
where
loop_length !z !s = case next s of
Done -> z
Skip s' -> expose s' $ loop_length z s'
Yield _ s' -> expose s' $ loop_length (z+1) s'
-}
map :: (a -> b) -> Stream a -> Stream b
map f (Stream next0 s0) = Stream next s0
where
# INLINE next #
next !s = case next0 s of
Done -> Done
Skip s' -> Skip s'
Yield x s' -> Yield (f x) s'
# RULES
" STREAM map / map fusion " forall f g s.
map f ( map s ) = map ( \x - > f ( g x ) ) s
#
"STREAM map/map fusion" forall f g s.
map f (map g s) = map (\x -> f (g x)) s
#-}
relies strongly on SpecConstr
intersperse :: a -> Stream a -> Stream a
intersperse sep (Stream next0 s0) = Stream next (s0 :!: Nothing :!: S1)
where
# INLINE next #
next (s :!: Nothing :!: S1) = case next0 s of
Done -> Done
Skip s' -> Skip (s' :!: Nothing :!: S1)
Yield x s' -> Skip (s' :!: Just (L x) :!: S1)
next (s :!: Just (L x) :!: S1) = Yield x (s :!: Nothing :!: S2)
next (s :!: Nothing :!: S2) = case next0 s of
Done -> Done
Skip s' -> Skip (s' :!: Nothing :!: S2)
Yield x s' -> Yield sep (s' :!: Just (L x) :!: S1)
foldl :: (b -> a -> b) -> b -> Stream a -> b
foldl f z0 (Stream next s0) = loop_foldl z0 s0
where
loop_foldl z !s = case next s of
Done -> z
Skip s' -> expose s' $ loop_foldl z s'
Yield x s' -> expose s' $ loop_foldl (f z x) s'
foldl' :: (b -> a -> b) -> b -> Stream a -> b
foldl' f z0 (Stream next s0) = loop_foldl' z0 s0
where
loop_foldl' !z !s = case next s of
Done -> z
Skip s' -> expose s' $ loop_foldl' z s'
Yield x s' -> expose s' $ loop_foldl' (f z x) s'
foldl1 :: (a -> a -> a) -> Stream a -> a
foldl1 f (Stream next s0) = loop0_foldl1 s0
where
loop0_foldl1 !s = case next s of
Skip s' -> expose s' $ loop0_foldl1 s'
Yield x s' -> expose s' $ loop_foldl1 x s'
Done -> errorEmptyStream "foldl1"
loop_foldl1 z !s = expose s $ case next s of
Done -> z
Skip s' -> expose s' $ loop_foldl1 z s'
Yield x s' -> expose s' $ loop_foldl1 (f z x) s'
foldl1' :: (a -> a -> a) -> Stream a -> a
foldl1' f (Stream next s0) = loop0_foldl1' s0
where
loop0_foldl1' !s = case next s of
Skip s' -> expose s' $ loop0_foldl1' s'
Yield x s' -> expose s' $ loop_foldl1' x s'
Done -> errorEmptyStream "foldl1"
loop_foldl1' !z !s = case next s of
Done -> z
Skip s' -> expose s' $ loop_foldl1' z s'
Yield x s' -> expose s' $ loop_foldl1' (f z x) s'
# INLINE [ 0 ] foldl1 ' #
foldr :: (a -> b -> b) -> b -> Stream a -> b
foldr f z (Stream next s0) = loop_foldr s0
where
loop_foldr !s = case next s of
Done -> z
Skip s' -> expose s' $ loop_foldr s'
Yield x s' -> expose s' $ f x (loop_foldr s')
foldr1 :: (a -> a -> a) -> Stream a -> a
foldr1 f (Stream next s0) = loop0_foldr1 s0
where
loop0_foldr1 !s = case next s of
Done -> errorEmptyStream "foldr1"
Skip s' -> expose s' $ loop0_foldr1 s'
Yield x s' -> expose s' $ loop_foldr1 x s'
loop_foldr1 x !s = case next s of
Done -> x
Skip s' -> expose s' $ loop_foldr1 x s'
Yield x' s' -> expose s' $ f x (loop_foldr1 x' s')
concat :: Stream [a] -> [a]
concat (Stream next s0) = loop_concat_to s0
where
loop_concat_go [] !s = expose s $ loop_concat_to s
loop_concat_go (x:xs) !s = expose s $ x : loop_concat_go xs s
loop_concat_to !s = case next s of
Done -> []
Skip s' -> expose s' $ loop_concat_to s'
Yield xs s' -> expose s' $ loop_concat_go xs s'
next (Just (L []) :!: s) = expose s $ Skip (Nothing :!: s)
next (Just (L (x:xs)) :!: s) = expose s $ Yield x (Just (L xs) :!: s)
next (Nothing :!: s) = case next0 s of
Done -> Done
Skip s' -> expose s' $ Skip (Nothing :!: s')
Yield xs s' -> expose s' $ Skip (Just (L xs) :!: s')
-}
-}
next (Just (L []) :!: s) = expose s $ Skip (Nothing :!: s)
next (Just (L (b:bs)) :!: s) = expose s $ Yield b (Just (L bs) :!: s)
next (Nothing :!: s) = case next0 s of
Done -> Done
Skip s' -> expose s' $ Skip (Nothing :!: s')
Yield a s' -> expose s' $ Skip (Just (L (f a)) :!: s')
-}
RULES
" dodgy concatMap rule " forall step concatMap ( \x - > unstream ( Stream step ( f x ) ) ) = \y - > unstream ( concatMap ' step f y )
"dodgy concatMap rule" forall step f.
concatMap (\x -> unstream (Stream step (f x))) = \y -> unstream (concatMap' step f y)
-}
next (sa :!: Just sb) = case nextb sb of
Done -> Skip (sa :!: Nothing)
Skip sb' -> Skip (sa :!: Just sb')
Yield b sb' -> Yield b (sa :!: Just sb')
next (sa :!: Nothing) = case nexta sa of
Done -> Done
Skip sa' -> Skip (sa' :!: Nothing)
Yield a sa' -> Skip (sa' :!: Just (f a))
-}
next (Left (Stream f t :!: s)) = case f t of
Done -> Skip (Right s)
Skip t' -> Skip (Left (Stream f t' :!: s))
Yield x t' -> Yield x (Left (Stream f t' :!: s))
next (Right s) = case next0 s of
Done -> Done
Skip s' -> Skip (Right s')
Yield x s' -> Skip (Left (x :!: s'))
-}
concatMap :: (a -> Stream b) -> Stream a -> Stream b
concatMap f (Stream next0 s0) = Stream next (s0 :!: Nothing)
where
# INLINE next #
next (s :!: Nothing) = case next0 s of
Done -> Done
Skip s' -> Skip (s' :!: Nothing)
Yield x s' -> Skip (s' :!: Just (f x))
next (s :!: Just (Stream g t)) = case g t of
Done -> Skip (s :!: Nothing)
Skip t' -> Skip (s :!: Just (Stream g t'))
Yield x t' -> Yield x (s :!: Just (Stream g t'))
and :: Stream Bool -> Bool
and = foldr (&&) True
# INLINE and #
or :: Stream Bool -> Bool
or = foldr (||) False
# INLINE or #
any :: (a -> Bool) -> Stream a -> Bool
any p (Stream next s0) = loop_any s0
where
loop_any !s = case next s of
Done -> False
Skip s' -> expose s' $ loop_any s'
Yield x s' | p x -> True
| otherwise -> expose s' $ loop_any s'
all :: (a -> Bool) -> Stream a -> Bool
all p (Stream next s0) = loop_all s0
where
loop_all !s = case next s of
Done -> True
Skip s' -> expose s' $ loop_all s'
Yield x s' | p x -> expose s' $ loop_all s'
| otherwise -> False
sum :: Num a => Stream a -> a
sum (Stream next s0) = loop_sum 0 s0
where
Done -> a
Skip s' -> expose s' $ loop_sum a s'
Yield x s' -> expose s' $ loop_sum (a + x) s'
product :: Num a => Stream a -> a
where
loop_product !a !s = case next s of
Done -> a
Skip s' -> expose s' $ loop_product a s'
Yield x s' -> expose s' $ loop_product (a * x) s'
maximum :: Ord a => Stream a -> a
maximum (Stream next s0) = loop0_maximum s0
where
loop0_maximum !s = case next s of
Done -> errorEmptyStream "maximum"
Skip s' -> expose s' $ loop0_maximum s'
Yield x s' -> expose s' $ loop_maximum x s'
Done -> z
Skip s' -> expose s' $ loop_maximum z s'
Yield x s' -> expose s' $ loop_maximum (max z x) s'
strictMaximum :: Ord a => Stream a -> a
strictMaximum (Stream next s0) = loop0_strictMaximum s0
where
loop0_strictMaximum !s = case next s of
Done -> errorEmptyStream "maximum"
Skip s' -> expose s' $ loop0_strictMaximum s'
Yield x s' -> expose s' $ loop_strictMaximum x s'
loop_strictMaximum !z !s = case next s of
Done -> z
Skip s' -> expose s' $ loop_strictMaximum z s'
Yield x s' -> expose s' $ loop_strictMaximum (max z x) s'
minimum :: Ord a => Stream a -> a
minimum (Stream next s0) = loop0_minimum s0
where
loop0_minimum !s = case next s of
Done -> errorEmptyStream "minimum"
Skip s' -> expose s' $ loop0_minimum s'
Yield x s' -> expose s' $ loop_minimum x s'
loop_minimum z !s = case next s of
Done -> z
Skip s' -> expose s' $ loop_minimum z s'
Yield x s' -> expose s' $ loop_minimum (min z x) s'
strictMinimum :: Ord a => Stream a -> a
strictMinimum (Stream next s0) = loop0_strictMinimum s0
where
loop0_strictMinimum !s = case next s of
Done -> errorEmptyStream "minimum"
Skip s' -> expose s' $ loop0_strictMinimum s'
Yield x s' -> expose s' $ loop_strictMinimum x s'
loop_strictMinimum !z !s = case next s of
Done -> z
Skip s' -> expose s' $ loop_strictMinimum z s'
Yield x s' -> expose s' $ loop_strictMinimum (min z x) s'
FIXME : not a proper . expects a list one longer than the input list ,
scanl :: (b -> a -> b) -> b -> Stream a -> Stream b
scanl f z0 (Stream next0 s0) = Stream next (L z0 :!: s0)
where
# INLINE next #
next (L z :!: s) = case next0 s of
Done -> Done
Skip s' -> Skip (L z :!: s')
Yield x s' -> Yield z (L (f z x) :!: s')
# INLINE [ 0 ] #
scanl1 :: (a -> a -> a) -> Stream a -> Stream a
scanl1 f (Stream next0 s0) = Stream next (Nothing :!: s0)
where
# INLINE next #
next (Nothing :!: s) = case next0 s of
Done -> Done
Skip s' -> Skip (Nothing :!: s')
Yield x s' -> Skip (Just (L x) :!: s')
next (Just (L z) :!: s) = case next0 s of
Done -> Done
Skip s' -> Skip (Just (L z) :!: s')
Yield x s' -> Yield z (Just (L (f z x)) :!: s')
scanr : : ( b - > a - > b ) - > b - > Stream a - > Stream b
( Stream next s0 ) = Stream next ' ( Just s0 )
where
next ' ( Just s ) = case next s of
Done - > Yield z0 ( Nothing , s )
Skip s ' - > Skip ( Just s ' )
next ' Nothing = Done
{ - # INLINE [ 0 ] #
scanr :: (b -> a -> b) -> b -> Stream a -> Stream b
scanr f z0 (Stream next s0) = Stream next' (Just s0)
where
next' (Just s) = case next s of
Done -> Yield z0 (Nothing, s)
Skip s' -> Skip (Just s')
next' Nothing = Done
-}
scanr : : ( a - > b - > b ) - > b - > Stream a - > Stream b
where
next ' ( z , s ) = case next s of
Done - > Done
Skip s ' - > Skip ( z , s ' )
{ - # INLINE [ 0 ] scanr #
scanr :: (a -> b -> b) -> b -> Stream a -> Stream b
where
next' (z, s) = case next s of
Done -> Done
Skip s' -> Skip (z, s')
-}
: : ( a - > a - > a ) - > Stream a - > Stream a
scanr1 : : ( a - > a - > a ) - > Stream a - > Stream a
scanl1 :: (a -> a -> a) -> Stream a -> Stream a
scanr1 :: (a -> a -> a) -> Stream a -> Stream a
-}
mapAccumL : : ( acc - > x - > ( acc , y ) ) - > acc - > Stream x - > ( acc , Stream y )
mapAccumL f acc ( Stream step s ) = Stream step ' ( s , acc )
where
step ' ( s , acc ) = case step s of
Done - > Done
Skip s ' - > Skip ( s ' , acc )
Yield x s ' - > let ( acc ' , y ) = f acc x in Yield y ( s ' , acc ' )
{ - # INLINE [ 0 ] mapAccumL #
mapAccumL :: (acc -> x -> (acc, y)) -> acc -> Stream x -> (acc, Stream y)
mapAccumL f acc (Stream step s) = Stream step' (s, acc)
where
step' (s, acc) = case step s of
Done -> Done
Skip s' -> Skip (s', acc)
Yield x s' -> let (acc', y) = f acc x in Yield y (s', acc')
-}
mapAccumR : : ( acc - > x - > ( acc , y ) ) - > acc - > Stream x - > ( acc , Stream y )
mapAccumR :: (acc -> x -> (acc, y)) -> acc -> Stream x -> (acc, Stream y)
-}
iterate :: (a -> a) -> a -> Stream a
iterate f x0 = Stream next (L x0)
where
# INLINE next #
next (L x) = Yield x (L (f x))
repeat :: a -> Stream a
repeat x = Stream next None
where
# INLINE next #
next _ = Yield x None
replicate :: Int -> a -> Stream a
replicate n x = Stream next (L n)
where
# INLINE next #
next (L !i) | i <= 0 = Done
| otherwise = Yield x (L (i-1))
cycle :: Stream a -> Stream a
cycle (Stream next0 s0) = Stream next (s0 :!: S1)
where
# INLINE next #
next (s :!: S1) = case next0 s of
Done -> errorEmptyStream "cycle"
Skip s' -> Skip (s' :!: S1)
Yield x s' -> Yield x (s' :!: S2)
next (s :!: S2) = case next0 s of
Done -> Skip (s0 :!: S2)
Skip s' -> Skip (s' :!: S2)
Yield x s' -> Yield x (s' :!: S2)
unfoldr :: (b -> Data.Maybe.Maybe (a, b)) -> b -> Stream a
unfoldr f s0 = Stream next (L s0)
where
# INLINE next #
next (L s) = case f s of
Data.Maybe.Nothing -> Done
Data.Maybe.Just (w, s') -> Yield w (L s')
take :: Int -> Stream a -> Stream a
take n0 (Stream next0 s0) = Stream next (L n0 :!: s0)
where
# INLINE next #
next (L !n :!: s)
| n <= 0 = Done
| otherwise = case next0 s of
Done -> Done
Skip s' -> Skip (L n :!: s')
Yield x s' -> Yield x (L (n-1) :!: s')
drop :: Int -> Stream a -> Stream a
drop n0 (Stream next0 s0) = Stream next (Just (L (max 0 n0)) :!: s0)
where
# INLINE next #
next (Just (L !n) :!: s)
| n == 0 = Skip (Nothing :!: s)
| otherwise = case next0 s of
Done -> Done
Skip s' -> Skip (Just (L n) :!: s')
Yield _ s' -> Skip (Just (L (n-1)) :!: s')
next (Nothing :!: s) = case next0 s of
Done -> Done
Skip s' -> Skip (Nothing :!: s')
Yield x s' -> Yield x (Nothing :!: s')
splitAt :: Int -> Stream a -> ([a], [a])
splitAt n0 (Stream next s0)
cheap as pattern matching n against 0
| n0 < 0 = ([], expose s0 $ unstream (Stream next s0))
| otherwise = loop_splitAt n0 s0
where
loop_splitAt 0 !s = ([], expose s $ unstream (Stream next s))
loop_splitAt !n !s = case next s of
Done -> ([], [])
Skip s' -> expose s $ loop_splitAt n s'
Yield x s' -> (x:xs', xs'')
where
(xs', xs'') = expose s $ loop_splitAt (n-1) s'
takeWhile :: (a -> Bool) -> Stream a -> Stream a
takeWhile p (Stream next0 s0) = Stream next s0
where
# INLINE next #
next !s = case next0 s of
Done -> Done
Skip s' -> Skip s'
Yield x s' | p x -> Yield x s'
| otherwise -> Done
dropWhile :: (a -> Bool) -> Stream a -> Stream a
dropWhile p (Stream next0 s0) = Stream next (S1 :!: s0)
where
# INLINE next #
next (S1 :!: s) = case next0 s of
Done -> Done
Skip s' -> Skip (S1 :!: s')
Yield x s' | p x -> Skip (S1 :!: s')
| otherwise -> Yield x (S2 :!: s')
next (S2 :!: s) = case next0 s of
Done -> Done
Skip s' -> Skip (S2 :!: s')
Yield x s' -> Yield x (S2 :!: s')
isPrefixOf :: Eq a => Stream a -> Stream a -> Bool
isPrefixOf (Stream stepa sa0) (Stream stepb sb0) = loop_isPrefixOf sa0 sb0 Nothing
where
loop_isPrefixOf !sa !sb Nothing = case stepa sa of
Done -> True
Skip sa' -> expose sa' $ loop_isPrefixOf sa' sb Nothing
Yield x sa' -> expose sa' $ loop_isPrefixOf sa' sb (Just (L x))
loop_isPrefixOf !sa !sb (Just (L x)) = case stepb sb of
Done -> False
Skip sb' -> expose sb' $ loop_isPrefixOf sa sb' (Just (L x))
Yield y sb' | x == y -> expose sb' $ loop_isPrefixOf sa sb' Nothing
| otherwise -> False
elem :: Eq a => a -> Stream a -> Bool
elem x (Stream next s0) = loop_elem s0
where
loop_elem !s = case next s of
Done -> False
Skip s' -> expose s' $ loop_elem s'
Yield y s'
| x == y -> True
| otherwise -> expose s' $ loop_elem s'
-}
lookup :: Eq a => a -> Stream (a, b) -> Data.Maybe.Maybe b
lookup key (Stream next s0) = loop_lookup s0
where
loop_lookup !s = case next s of
Done -> Data.Maybe.Nothing
Skip s' -> expose s' $ loop_lookup s'
Yield (x, y) s' | key == x -> Data.Maybe.Just y
| otherwise -> expose s' $ loop_lookup s'
find :: (a -> Bool) -> Stream a -> Data.Maybe.Maybe a
find p (Stream next s0) = loop_find s0
where
loop_find !s = case next s of
Done -> Data.Maybe.Nothing
Skip s' -> expose s' $ loop_find s'
Yield x s' | p x -> Data.Maybe.Just x
| otherwise -> expose s' $ loop_find s'
filter :: (a -> Bool) -> Stream a -> Stream a
filter p (Stream next0 s0) = Stream next s0
where
# INLINE next #
next !s = case next0 s of
Done -> Done
Skip s' -> Skip s'
Yield x s' | p x -> Yield x s'
| otherwise -> Skip s'
# RULES
" Stream filter / filter fusion " forall p q s.
filter p ( filter q s ) = filter ( \x - > q x & & p x ) s
#
"Stream filter/filter fusion" forall p q s.
filter p (filter q s) = filter (\x -> q x && p x) s
#-}
index :: Stream a -> Int -> a
index (Stream next s0) n0
| n0 < 0 = error "Stream.(!!): negative index"
| otherwise = loop_index n0 s0
where
loop_index !n !s = case next s of
Done -> error "Stream.(!!): index too large"
Skip s' -> expose s' $ loop_index n s'
Yield x s' | n == 0 -> x
| otherwise -> expose s' $ loop_index (n-1) s'
findIndex :: (a -> Bool) -> Stream a -> Data.Maybe.Maybe Int
findIndex p (Stream next s0) = loop_findIndex 0 s0
where
loop_findIndex !i !s = case next s of
Done -> Data.Maybe.Nothing
Yield x s' | p x -> Data.Maybe.Just i
| otherwise -> expose s' $ loop_findIndex (i+1) s'
elemIndex :: Eq a => a -> Stream a -> Data.Maybe.Maybe Int
elemIndex a (Stream next s0) = loop_elemIndex 0 s0
where
loop_elemIndex !i !s = case next s of
Done -> Data.Maybe.Nothing
Skip s' -> expose s' $ loop_elemIndex i s'
Yield x s' | a == x -> Data.Maybe.Just i
| otherwise -> expose s' $ loop_elemIndex (i+1) s'
elemIndices :: Eq a => a -> Stream a -> Stream Int
elemIndices a (Stream next0 s0) = Stream next (S 0 :!: s0)
where
# INLINE next #
next (S n :!: s) = case next0 s of
Done -> Done
Skip s' -> Skip (S n :!: s')
Yield x s' | x == a -> Yield n (S (n+1) :!: s')
| otherwise -> Skip (S (n+1) :!: s')
findIndices :: (a -> Bool) -> Stream a -> Stream Int
findIndices p (Stream next0 s0) = Stream next (S 0 :!: s0)
where
# INLINE next #
next (S n :!: s) = case next0 s of
Done -> Done
Skip s' -> Skip (S n :!: s')
Yield x s' | p x -> Yield n (S (n+1) :!: s')
| otherwise -> Skip (S (n+1) :!: s')
zip :: Stream a -> Stream b -> Stream (a, b)
zip = zipWith (,)
# INLINE zip #
zip3 :: Stream a -> Stream b -> Stream c -> Stream (a, b, c)
zip3 = zipWith3 (,,)
# INLINE zip3 #
zip4 :: Stream a -> Stream b -> Stream c -> Stream d -> Stream (a, b, c, d)
zip4 = zipWith4 (,,,)
# INLINE zip4 #
zip5 : : Stream a - > Stream b - > Stream c - > Stream d - > Stream e - > [ ( a , b , c , d , e ) ]
: : Stream a - > Stream b - > Stream c - > Stream d - > Stream e - > Stream f - > [ ( a , b , c , d , e , f ) ]
zip7 : : Stream a - > Stream b - > Stream c - > Stream d - > Stream e - > Stream f - > Stream g - > [ ( a , b , c , d , e , f , ) ]
zip5 :: Stream a -> Stream b -> Stream c -> Stream d -> Stream e -> [(a, b, c, d, e)]
zip6 :: Stream a -> Stream b -> Stream c -> Stream d -> Stream e -> Stream f -> [(a, b, c, d, e, f)]
zip7 :: Stream a -> Stream b -> Stream c -> Stream d -> Stream e -> Stream f -> Stream g -> [(a, b, c, d, e, f, g)]
-}
zipWith :: (a -> b -> c) -> Stream a -> Stream b -> Stream c
zipWith f (Stream next0 sa0) (Stream next1 sb0) = Stream next (sa0 :!: sb0 :!: Nothing)
where
# INLINE next #
next (sa :!: sb :!: Nothing) = case next0 sa of
Done -> Done
Skip sa' -> Skip (sa' :!: sb :!: Nothing)
Yield a sa' -> Skip (sa' :!: sb :!: Just (L a))
next (sa' :!: sb :!: Just (L a)) = case next1 sb of
Done -> Done
Skip sb' -> Skip (sa' :!: sb' :!: Just (L a))
Yield b sb' -> Yield (f a b) (sa' :!: sb' :!: Nothing)
zipWith3 :: (a -> b -> c -> d) -> Stream a -> Stream b -> Stream c -> Stream d
zipWith3 f (Stream nexta sa0)
(Stream nextb sb0)
(Stream nextc sc0) = Stream next (sa0 :!: sb0 :!: sc0 :!: Nothing)
where
# INLINE next #
next (sa :!: sb :!: sc :!: Nothing) = case nexta sa of
Done -> Done
Skip sa' -> Skip (sa' :!: sb :!: sc :!: Nothing)
Yield a sa' -> Skip (sa' :!: sb :!: sc :!: Just (L a :!: Nothing))
next (sa' :!: sb :!: sc :!: Just (L a :!: Nothing)) = case nextb sb of
Done -> Done
Skip sb' -> Skip (sa' :!: sb' :!: sc :!: Just (L a :!: Nothing))
Yield b sb' -> Skip (sa' :!: sb' :!: sc :!: Just (L a :!: Just (L b)))
next (sa' :!: sb' :!: sc :!: Just (L a :!: Just (L b))) = case nextc sc of
Done -> Done
Skip sc' -> Skip (sa' :!: sb' :!: sc' :!: Just (L a :!: Just (L b)))
Yield c sc' -> Yield (f a b c) (sa' :!: sb' :!: sc' :!: Nothing)
zipWith4 :: (a -> b -> c -> d -> e) -> Stream a -> Stream b -> Stream c -> Stream d -> Stream e
zipWith4 f (Stream nexta sa0)
(Stream nextb sb0)
(Stream nextc sc0)
(Stream nextd sd0) = Stream next (sa0 :!: sb0 :!: sc0 :!: sd0 :!: Nothing)
where
# INLINE next #
next (sa :!: sb :!: sc :!: sd :!: Nothing) =
case nexta sa of
Done -> Done
Skip sa' -> Skip (sa' :!: sb :!: sc :!: sd :!: Nothing)
Yield a sa' -> Skip (sa' :!: sb :!: sc :!: sd :!: Just (L a :!: Nothing))
next (sa' :!: sb :!: sc :!: sd :!: Just (L a :!: Nothing)) =
case nextb sb of
Done -> Done
Skip sb' -> Skip (sa' :!: sb' :!: sc :!: sd :!: Just (L a :!: Nothing))
Yield b sb' -> Skip (sa' :!: sb' :!: sc :!: sd :!: Just (L a :!: Just (L b :!: Nothing)))
next (sa' :!: sb' :!: sc :!: sd :!: Just (L a :!: (Just (L b :!: Nothing)))) =
case nextc sc of
Done -> Done
Skip sc' -> Skip (sa' :!: sb' :!: sc' :!: sd :!: Just (L a :!: (Just (L b :!: Nothing))))
Yield c sc' -> Skip (sa' :!: sb' :!: sc' :!: sd :!: Just (L a :!: (Just (L b :!: Just (L c)))))
next (sa' :!: sb' :!: sc' :!: sd :!: Just (L a :!: (Just (L b :!: Just (L c))))) =
case nextd sd of
Done -> Done
Skip sd' -> Skip (sa' :!: sb' :!: sc' :!: sd' :!: Just (L a :!: (Just (L b :!: Just (L c)))))
Yield d sd' -> Yield (f a b c d) (sa' :!: sb' :!: sc' :!: sd' :!: Nothing)
unzip :: Stream (a, b) -> ([a], [b])
unzip = foldr (\(a,b) ~(as, bs) -> (a:as, b:bs)) ([], [])
# INLINE unzip #
unlines : : Stream ( Stream ) - > Stream ( Stream next s0 ) = Stream next ' ( Right s0 )
where
next ' ( Left ( Stream g t , s ) ) = case g t of
Done - > Skip ( Right s )
Skip t ' - > Skip ( Left ( Stream g t ' , s ) )
Yield x t ' - > Yield x ( Left ( Stream g t ' , s ) )
next ' ( Right s ) = case next s of
Done - > Done
Skip s ' - > Skip ( Right s ' )
Yield x s ' - > Skip ( Left ( ( snoc x ' \n ' ) , s ' ) )
{ - # INLINE [ 0 ] unlines #
unlines :: Stream (Stream Char) -> Stream Char
unlines (Stream next s0) = Stream next' (Right s0)
where
next' (Left (Stream g t, s)) = case g t of
Done -> Skip (Right s)
Skip t' -> Skip (Left (Stream g t', s))
Yield x t' -> Yield x (Left (Stream g t', s))
next' (Right s) = case next s of
Done -> Done
Skip s' -> Skip (Right s')
Yield x s' -> Skip (Left ((snoc x '\n'), s'))
-}
unlines ( Stream next s0 ) = Stream next ' ( Right s0 )
where
next ' ( Left ( Stream f t , s ) ) = case f t of
Done - > Yield ' \n ' ( Right s )
Skip t ' - > Skip ( Left ( Stream f t ' , s ) )
Yield x t ' - > Yield x ( Left ( Stream f t ' , s ) )
next ' ( Right s ) = case next s of
Done - > Done
Skip s ' - > Skip ( Right s ' )
Yield x s ' - > Skip ( Left ( x , s ' ) )
unlines (Stream next s0) = Stream next' (Right s0)
where
next' (Left (Stream f t, s)) = case f t of
Done -> Yield '\n' (Right s)
Skip t' -> Skip (Left (Stream f t', s))
Yield x t' -> Yield x (Left (Stream f t', s))
next' (Right s) = case next s of
Done -> Done
Skip s' -> Skip (Right s')
Yield x s' -> Skip (Left (x, s'))
-}
next (Nothing :!: s) = case next0 s of
Done -> Done
Skip s' -> Skip (Nothing :!: s')
next (Just (S acc) :!: s) = case next0 s of
Skip s' -> Skip (Just (S acc) :!: s')
reuse first state
Yield x s' -> Skip (Just (S (x:acc)) :!: s')
# INLINE reverse #
reverse :: [Char] -> [Char]
reverse l = rev l []
where
rev [] a = a
rev (x:xs) a = rev xs (x:a)
-}
sort : : a = > Stream a - > Stream a
insert : : a = > a - > Stream a - > Stream a
sort :: Ord a => Stream a -> Stream a
insert :: Ord a => a -> Stream a -> Stream a
-}
* * * User - supplied equality ( replacing an Eq context )
* * * User - supplied comparison ( replacing an context )
insertBy :: (a -> a -> Ordering) -> a -> Stream a -> Stream a
insertBy cmp x (Stream next0 s0) = Stream next (S2 :!: s0)
where
# INLINE next #
next (S2 :!: s) = case next0 s of
Skip s' -> Skip (S2 :!: s')
Yield y s' | GT == cmp x y -> Yield y (S2 :!: s')
next (S1 :!: s) = case next0 s of
Done -> Done
Skip s' -> Skip (S1 :!: s')
Yield y s' -> Yield y (S1 :!: s')
maximumBy :: (a -> a -> Ordering) -> Stream a -> a
maximumBy cmp (Stream next s0) = loop0_maximumBy s0
where
loop0_maximumBy !s = case next s of
Skip s' -> expose s' $ loop0_maximumBy s'
Yield x s' -> expose s' $ loop_maximumBy x s'
Done -> errorEmptyStream "maximumBy"
loop_maximumBy z !s = case next s of
Done -> z
Skip s' -> expose s' $ loop_maximumBy z s'
Yield x s' -> expose s' $ loop_maximumBy (max' z x) s'
max' x y = case cmp x y of
GT -> x
_ -> y
minimumBy :: (a -> a -> Ordering) -> Stream a -> a
minimumBy cmp (Stream next s0) = loop0_minimumBy s0
where
loop0_minimumBy !s = case next s of
Skip s' -> expose s' $ loop0_minimumBy s'
Yield x s' -> expose s' $ loop_minimumBy x s'
Done -> errorEmptyStream "minimum"
loop_minimumBy z !s = case next s of
Done -> z
Skip s' -> expose s' $ loop_minimumBy z s'
Yield x s' -> expose s' $ loop_minimumBy (min' z x) s'
min' x y = case cmp x y of
GT -> y
_ -> x
genericLength :: Num i => Stream b -> i
genericLength (Stream next s0) = loop_genericLength s0
where
loop_genericLength !s = case next s of
Done -> 0
Skip s' -> expose s' $ loop_genericLength s'
Yield _ s' -> expose s' $ 1 + loop_genericLength s'
# INLINE [ 0 ] genericLength #
TODO : specialised generic Length for strict / atomic and associative
instances like and Integer
genericTake :: Integral i => i -> Stream a -> Stream a
genericTake n0 (Stream next0 s0) = Stream next (L n0 :!: s0)
where
# INLINE next #
next (L 0 :!: _) = Done
next (L n :!: s) = case next0 s of
Done -> Done
Skip s' -> Skip (L n :!: s')
Yield x s'
| n > 0 -> Yield x (L (n-1) :!: s')
| otherwise -> error "List.genericTake: negative argument"
genericDrop :: Integral i => i -> Stream a -> Stream a
genericDrop n0 (Stream next0 s0) = Stream next (Just (L n0) :!: s0)
where
# INLINE next #
next (Just (L 0) :!: s) = Skip (Nothing :!: s)
next (Just (L n) :!: s) = case next0 s of
Done -> Done
Skip s' -> Skip (Just (L n) :!: s')
Yield _ s' | n > 0 -> Skip (Just (L (n-1)) :!: s')
| otherwise -> error "List.genericDrop: negative argument"
next (Nothing :!: s) = case next0 s of
Done -> Done
Skip s' -> Skip (Nothing :!: s')
Yield x s' -> Yield x (Nothing :!: s')
genericIndex :: Integral a => Stream b -> a -> b
genericIndex (Stream next s0) i0 = loop_genericIndex i0 s0
where
loop_genericIndex i !s = case next s of
Done -> error "List.genericIndex: index too large."
Skip s' -> expose s' $ loop_genericIndex i s'
Yield x s' | i == 0 -> x
| i > 0 -> expose s' $ loop_genericIndex (i-1) s'
| otherwise -> error "List.genericIndex: negative argument."
genericSplitAt :: Integral i => i -> Stream a -> ([a], [a])
genericSplitAt n0 (Stream next s0) = loop_genericSplitAt n0 s0
where
loop_genericSplitAt 0 !s = ([], expose s $ unstream (Stream next s))
loop_genericSplitAt n !s = case next s of
Done -> ([], [])
Skip s' -> expose s $ loop_genericSplitAt n s'
Yield x s'
| n > 0 -> (x:xs', xs'')
| otherwise -> error "List.genericSplitAt: negative argument"
where
(xs', xs'') = expose s $ loop_genericSplitAt (n-1) s'
enumFromToNum : : ( a , a ) = > a - > a - > Stream a
enumFromToNum x y = Stream next ( L x )
where
{ - # INLINE next #
enumFromToNum :: (Ord a, Num a) => a -> a -> Stream a
enumFromToNum x y = Stream next (L x)
where
next (L !n)
| n > y = Done
| otherwise = Yield n (L (n+1))
-}
enumFromToInt :: Int -> Int -> Stream Int
enumFromToInt x y = Stream next (L x)
where
# INLINE next #
next (L !n)
| n > y = Done
| otherwise = Yield n (L (n+1))
enumDeltaInteger :: Integer -> Integer -> Stream Integer
enumDeltaInteger a d = Stream next (L a)
where
# INLINE next #
next (L !x) = Yield x (L (x+d))
enumFromToChar :: Char -> Char -> Stream Char
enumFromToChar x y = Stream next (L (ord x))
where
m = ord y
# INLINE next #
next (L !n)
| n > m = Done
| otherwise = Yield (chr n) (L (n+1))
Monadic stuff
need explicit stream implementations . The one exception is foldM :
foldM :: Monad m => (b -> a -> m b) -> b -> Stream a -> m b
foldM f z0 (Stream next s0) = loop_foldl z0 s0
where
loop_foldl z !s = case next s of
Done -> Monad.return z
Skip s' -> expose s' $ loop_foldl z s'
Yield x s' -> expose s' $ f z x >>= \z' -> loop_foldl z' s'
foldM_ :: Monad m => (b -> a -> m b) -> b -> Stream a -> m ()
foldM_ f z0 (Stream next s0) = loop_foldl z0 s0
where
loop_foldl z !s = case next s of
Done -> Monad.return ()
Skip s' -> expose s' $ loop_foldl z s'
Yield x s' -> expose s' $ f z x >>= \z' -> loop_foldl z' s'
return :: a -> Stream a
return e = Stream next S1
where
# INLINE next #
next S1 = Yield e S2
next S2 = Done
guard :: Bool -> Stream a -> Stream a
guard b (Stream next0 s0) = Stream next (S1 :!: s0)
where
# INLINE next #
next (S1 :!: s) = if b then Skip (S2 :!: s) else Done
next (S2 :!: s) = case next0 s of
Done -> Done
Skip s' -> Skip (S2 :!: s')
Yield x s' -> Yield x (S2 :!: s')
bind :: (a -> Bool) -> (a -> Stream b) -> Stream a -> Stream b
bind b f (Stream next0 s0) = Stream next (s0 :!: Nothing)
where
# INLINE next #
next (s :!: Nothing) = case next0 s of
Done -> Done
Skip s' -> Skip (s' :!: Nothing)
Yield x s'
| b x -> Skip (s' :!: Just (f x))
| otherwise -> Skip (s' :!: Nothing)
next (s :!: Just (Stream next1 s1)) = case next1 s1 of
Done -> Skip (s :!: Nothing)
Skip s1' -> Skip (s :!: Just (Stream next1 s1'))
Yield x s1' -> Yield x (s :!: Just (Stream next1 s1'))
mapFilter :: (a -> Bool) -> (a -> b) -> Stream a -> Stream b
mapFilter b f (Stream next0 s0) = Stream next s0
where
# INLINE next #
next s = case next0 s of
Done -> Done
Skip s' -> Skip s'
Yield x s'
| b x -> Yield (f x) s'
| otherwise -> Skip s'
declare :: (a -> Stream b) -> a -> Stream b
declare f bs = Stream next (f bs)
where
# INLINE next #
next (Stream next0 s) = case next0 s of
Done -> Done
Skip s' -> Skip (Stream next0 s')
Yield x s' -> Yield x (Stream next0 s')
Internal utilities
errorEmptyStream :: String -> a
errorEmptyStream fun = moduleError fun "empty list"
# NOINLINE errorEmptyStream #
moduleError :: String -> String -> a
moduleError fun msg = error ("List." ++ fun ++ ':':' ':msg)
# NOINLINE moduleError #
#endif
|
c20e7bba77a13e73a1a94ed2fe0d0594f5d8ebbc65b29a473e722d8c7270d755
|
garrigue/lablgtk
|
dtd.mli
|
* , an small Xml parser / printer with DTD support .
* Copyright ( C ) 2003 ( )
*
* This library is free software ; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation ; either
* version 2.1 of the License , or ( at your option ) any later version .
*
* This library is distributed in the hope that it will be useful ,
* but WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU
* Lesser General Public License for more details .
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library ; if not , write to the Free Software
* Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA
* Xml Light, an small Xml parser/printer with DTD support.
* Copyright (C) 2003 Nicolas Cannasse ()
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*)
* Xml Light DTD
This module provide several functions to create , check , and use
to prove Xml documents : { ul
{ li using the DTD types , you can directly create your own DTD structure }
{ li the { ! Dtd.check } function can then be used to check that all
states have been declared , that no attributes are declared twice ,
and so on . }
{ li the { ! Dtd.prove } function can be used to check an { ! Xml } data
structure with a checked DTD . The function will return the
expanded Xml document or raise an exception if the DTD proving
fails . }
}
{ i Note about ENTITIES :}
While parsing Xml , PCDATA is always parsed and
the Xml entities & amp ; & gt ; & lt ; ; & quot ; are replaced by their
corresponding ASCII characters . For attributes , theses can be
put between either double or simple quotes , and the backslash character
can be used to escape inner quotes . There is no support for CDATA Xml
nodes or PCDATA attributes declarations in DTD , and no support for
user - defined entities using the ENTITY DTD element .
This module provide several functions to create, check, and use DTD
to prove Xml documents : {ul
{li using the DTD types, you can directly create your own DTD structure}
{li the {!Dtd.check} function can then be used to check that all DTD
states have been declared, that no attributes are declared twice,
and so on.}
{li the {!Dtd.prove} function can be used to check an {!Xml} data
structure with a checked DTD. The function will return the
expanded Xml document or raise an exception if the DTD proving
fails.}
}
{i Note about ENTITIES:}
While parsing Xml, PCDATA is always parsed and
the Xml entities & > < ' " are replaced by their
corresponding ASCII characters. For Xml attributes, theses can be
put between either double or simple quotes, and the backslash character
can be used to escape inner quotes. There is no support for CDATA Xml
nodes or PCDATA attributes declarations in DTD, and no support for
user-defined entities using the ENTITY DTD element.
*)
* { 6 The DTD Types }
type dtd_child =
| DTDTag of string
| DTDPCData
| DTDOptional of dtd_child
| DTDZeroOrMore of dtd_child
| DTDOneOrMore of dtd_child
| DTDChoice of dtd_child list
| DTDChildren of dtd_child list
type dtd_element_type =
| DTDEmpty
| DTDAny
| DTDChild of dtd_child
type dtd_attr_default =
| DTDDefault of string
| DTDRequired
| DTDImplied
| DTDFixed of string
type dtd_attr_type =
| DTDCData
| DTDNMToken
| DTDEnum of string list
type dtd_item =
| DTDAttribute of string * string * dtd_attr_type * dtd_attr_default
| DTDElement of string * dtd_element_type
type dtd = dtd_item list
type checked
* { 6 The DTD Functions }
* the named file into a data structure . Raise
{ ! Xml . File_not_found } if an error occured while opening the file .
Raise { ! Dtd . Parse_error } if parsing failed .
{!Xml.File_not_found} if an error occured while opening the file.
Raise {!Dtd.Parse_error} if parsing failed. *)
val parse_file : string -> dtd
* Read the content of the in_channel and parse it into a data
structure . Raise { ! Dtd . Parse_error } if parsing failed .
structure. Raise {!Dtd.Parse_error} if parsing failed. *)
val parse_in : in_channel -> dtd
* the string containing a document into a data
structure . Raise { ! Dtd . Parse_error } if parsing failed .
structure. Raise {!Dtd.Parse_error} if parsing failed. *)
val parse_string : string -> dtd
* Check the data structure declaration and return a checked
. Raise { ! . Check_error } if the DTD checking failed .
DTD. Raise {!Dtd.Check_error} if the DTD checking failed. *)
val check : dtd -> checked
* Prove an Xml document using a checked DTD and an entry point .
The entry point is the first excepted tag of the Xml document ,
the returned Xml document has the same structure has the original
one , excepted that non declared optional attributes have been set
to their default value specified in the DTD .
Raise { ! . Check_error } [ ElementNotDeclared ] if the entry point
is not found , raise { ! } if the Xml document failed
to be proved with the DTD .
The entry point is the first excepted tag of the Xml document,
the returned Xml document has the same structure has the original
one, excepted that non declared optional attributes have been set
to their default value specified in the DTD.
Raise {!Dtd.Check_error} [ElementNotDeclared] if the entry point
is not found, raise {!Dtd.Prove_error} if the Xml document failed
to be proved with the DTD. *)
val prove : checked -> string -> Xml.xml -> Xml.xml
* Print a DTD element into a string . You can easily get a DTD
document from a DTD data structure using for example
[ String.concat " \n " ( ) my_dtd ]
document from a DTD data structure using for example
[String.concat "\n" (List.map Dtd.to_string) my_dtd] *)
val to_string : dtd_item -> string
* { 6 The DTD Exceptions }
* There is three types of DTD excecptions : { ul
{ li { ! Dtd . Parse_error } is raised when an error occured while
parsing a DTD document into a DTD data structure . }
{ li { ! . Check_error } is raised when an error occured while
checking a DTD data structure for completeness , or when the
prove entry point is not found when calling { ! Dtd.prove } . }
{ li { ! } is raised when an error occured while
proving an Xml document . }
}
Several string conversion functions are provided to enable you
to report errors to the user .
{li {!Dtd.Parse_error} is raised when an error occured while
parsing a DTD document into a DTD data structure.}
{li {!Dtd.Check_error} is raised when an error occured while
checking a DTD data structure for completeness, or when the
prove entry point is not found when calling {!Dtd.prove}.}
{li {!Dtd.Prove_error} is raised when an error occured while
proving an Xml document.}
}
Several string conversion functions are provided to enable you
to report errors to the user.
*)
type parse_error_msg =
| InvalidDTDDecl
| InvalidDTDElement
| InvalidDTDAttribute
| InvalidDTDTag
| DTDItemExpected
type check_error =
| ElementDefinedTwice of string
| AttributeDefinedTwice of string * string
| ElementEmptyContructor of string
| ElementReferenced of string * string
| ElementNotDeclared of string
type prove_error =
| UnexpectedPCData
| UnexpectedTag of string
| UnexpectedAttribute of string
| InvalidAttributeValue of string
| RequiredAttribute of string
| ChildExpected of string
| EmptyExpected
type parse_error = parse_error_msg * Xml.error_pos
exception Parse_error of parse_error
exception Check_error of check_error
exception Prove_error of prove_error
val parse_error : parse_error -> string
val check_error : check_error -> string
val prove_error : prove_error -> string
(**/**)
(* internal usage only... *)
val _raises : (string -> exn) -> unit
| null |
https://raw.githubusercontent.com/garrigue/lablgtk/504fac1257e900e6044c638025a4d6c5a321284c/tools/introspection/xml-light/dtd.mli
|
ocaml
|
*/*
internal usage only...
|
* , an small Xml parser / printer with DTD support .
* Copyright ( C ) 2003 ( )
*
* This library is free software ; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation ; either
* version 2.1 of the License , or ( at your option ) any later version .
*
* This library is distributed in the hope that it will be useful ,
* but WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU
* Lesser General Public License for more details .
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library ; if not , write to the Free Software
* Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA
* Xml Light, an small Xml parser/printer with DTD support.
* Copyright (C) 2003 Nicolas Cannasse ()
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*)
* Xml Light DTD
This module provide several functions to create , check , and use
to prove Xml documents : { ul
{ li using the DTD types , you can directly create your own DTD structure }
{ li the { ! Dtd.check } function can then be used to check that all
states have been declared , that no attributes are declared twice ,
and so on . }
{ li the { ! Dtd.prove } function can be used to check an { ! Xml } data
structure with a checked DTD . The function will return the
expanded Xml document or raise an exception if the DTD proving
fails . }
}
{ i Note about ENTITIES :}
While parsing Xml , PCDATA is always parsed and
the Xml entities & amp ; & gt ; & lt ; ; & quot ; are replaced by their
corresponding ASCII characters . For attributes , theses can be
put between either double or simple quotes , and the backslash character
can be used to escape inner quotes . There is no support for CDATA Xml
nodes or PCDATA attributes declarations in DTD , and no support for
user - defined entities using the ENTITY DTD element .
This module provide several functions to create, check, and use DTD
to prove Xml documents : {ul
{li using the DTD types, you can directly create your own DTD structure}
{li the {!Dtd.check} function can then be used to check that all DTD
states have been declared, that no attributes are declared twice,
and so on.}
{li the {!Dtd.prove} function can be used to check an {!Xml} data
structure with a checked DTD. The function will return the
expanded Xml document or raise an exception if the DTD proving
fails.}
}
{i Note about ENTITIES:}
While parsing Xml, PCDATA is always parsed and
the Xml entities & > < ' " are replaced by their
corresponding ASCII characters. For Xml attributes, theses can be
put between either double or simple quotes, and the backslash character
can be used to escape inner quotes. There is no support for CDATA Xml
nodes or PCDATA attributes declarations in DTD, and no support for
user-defined entities using the ENTITY DTD element.
*)
* { 6 The DTD Types }
type dtd_child =
| DTDTag of string
| DTDPCData
| DTDOptional of dtd_child
| DTDZeroOrMore of dtd_child
| DTDOneOrMore of dtd_child
| DTDChoice of dtd_child list
| DTDChildren of dtd_child list
type dtd_element_type =
| DTDEmpty
| DTDAny
| DTDChild of dtd_child
type dtd_attr_default =
| DTDDefault of string
| DTDRequired
| DTDImplied
| DTDFixed of string
type dtd_attr_type =
| DTDCData
| DTDNMToken
| DTDEnum of string list
type dtd_item =
| DTDAttribute of string * string * dtd_attr_type * dtd_attr_default
| DTDElement of string * dtd_element_type
type dtd = dtd_item list
type checked
* { 6 The DTD Functions }
* the named file into a data structure . Raise
{ ! Xml . File_not_found } if an error occured while opening the file .
Raise { ! Dtd . Parse_error } if parsing failed .
{!Xml.File_not_found} if an error occured while opening the file.
Raise {!Dtd.Parse_error} if parsing failed. *)
val parse_file : string -> dtd
* Read the content of the in_channel and parse it into a data
structure . Raise { ! Dtd . Parse_error } if parsing failed .
structure. Raise {!Dtd.Parse_error} if parsing failed. *)
val parse_in : in_channel -> dtd
* the string containing a document into a data
structure . Raise { ! Dtd . Parse_error } if parsing failed .
structure. Raise {!Dtd.Parse_error} if parsing failed. *)
val parse_string : string -> dtd
* Check the data structure declaration and return a checked
. Raise { ! . Check_error } if the DTD checking failed .
DTD. Raise {!Dtd.Check_error} if the DTD checking failed. *)
val check : dtd -> checked
* Prove an Xml document using a checked DTD and an entry point .
The entry point is the first excepted tag of the Xml document ,
the returned Xml document has the same structure has the original
one , excepted that non declared optional attributes have been set
to their default value specified in the DTD .
Raise { ! . Check_error } [ ElementNotDeclared ] if the entry point
is not found , raise { ! } if the Xml document failed
to be proved with the DTD .
The entry point is the first excepted tag of the Xml document,
the returned Xml document has the same structure has the original
one, excepted that non declared optional attributes have been set
to their default value specified in the DTD.
Raise {!Dtd.Check_error} [ElementNotDeclared] if the entry point
is not found, raise {!Dtd.Prove_error} if the Xml document failed
to be proved with the DTD. *)
val prove : checked -> string -> Xml.xml -> Xml.xml
* Print a DTD element into a string . You can easily get a DTD
document from a DTD data structure using for example
[ String.concat " \n " ( ) my_dtd ]
document from a DTD data structure using for example
[String.concat "\n" (List.map Dtd.to_string) my_dtd] *)
val to_string : dtd_item -> string
* { 6 The DTD Exceptions }
* There is three types of DTD excecptions : { ul
{ li { ! Dtd . Parse_error } is raised when an error occured while
parsing a DTD document into a DTD data structure . }
{ li { ! . Check_error } is raised when an error occured while
checking a DTD data structure for completeness , or when the
prove entry point is not found when calling { ! Dtd.prove } . }
{ li { ! } is raised when an error occured while
proving an Xml document . }
}
Several string conversion functions are provided to enable you
to report errors to the user .
{li {!Dtd.Parse_error} is raised when an error occured while
parsing a DTD document into a DTD data structure.}
{li {!Dtd.Check_error} is raised when an error occured while
checking a DTD data structure for completeness, or when the
prove entry point is not found when calling {!Dtd.prove}.}
{li {!Dtd.Prove_error} is raised when an error occured while
proving an Xml document.}
}
Several string conversion functions are provided to enable you
to report errors to the user.
*)
type parse_error_msg =
| InvalidDTDDecl
| InvalidDTDElement
| InvalidDTDAttribute
| InvalidDTDTag
| DTDItemExpected
type check_error =
| ElementDefinedTwice of string
| AttributeDefinedTwice of string * string
| ElementEmptyContructor of string
| ElementReferenced of string * string
| ElementNotDeclared of string
type prove_error =
| UnexpectedPCData
| UnexpectedTag of string
| UnexpectedAttribute of string
| InvalidAttributeValue of string
| RequiredAttribute of string
| ChildExpected of string
| EmptyExpected
type parse_error = parse_error_msg * Xml.error_pos
exception Parse_error of parse_error
exception Check_error of check_error
exception Prove_error of prove_error
val parse_error : parse_error -> string
val check_error : check_error -> string
val prove_error : prove_error -> string
val _raises : (string -> exn) -> unit
|
5dab9e77f8ccf6b5e3fdb0a2eb6d1898deda0f24febb4bcdbad60b13ec3b9855
|
fakedata-haskell/fakedata
|
StreetFighter.hs
|
# LANGUAGE TemplateHaskell #
{-# LANGUAGE OverloadedStrings #-}
module Faker.Game.StreetFighter where
import Data.Text (Text)
import Faker (Fake(..))
import Faker.Provider.StreetFighter
import Faker.TH
$(generateFakeField "streetFighter" "characters")
$(generateFakeField "streetFighter" "stages")
$(generateFakeField "streetFighter" "quotes")
$(generateFakeField "streetFighter" "moves")
| null |
https://raw.githubusercontent.com/fakedata-haskell/fakedata/e6fbc16cfa27b2d17aa449ea8140788196ca135b/src/Faker/Game/StreetFighter.hs
|
haskell
|
# LANGUAGE OverloadedStrings #
|
# LANGUAGE TemplateHaskell #
module Faker.Game.StreetFighter where
import Data.Text (Text)
import Faker (Fake(..))
import Faker.Provider.StreetFighter
import Faker.TH
$(generateFakeField "streetFighter" "characters")
$(generateFakeField "streetFighter" "stages")
$(generateFakeField "streetFighter" "quotes")
$(generateFakeField "streetFighter" "moves")
|
152e41dbb48492d3ff27d81c13c0eafec69d4888b4d49cbfe573931beacb2d20
|
alt-romes/ghengin
|
Property.hs
|
# LANGUAGE AllowAmbiguousTypes #
# LANGUAGE UndecidableInstances #
# LANGUAGE OverloadedRecordDot #
module Ghengin.Core.Render.Property where
import Control.Lens ((^.), Lens, Lens', lens)
import GHC.TypeLits ( KnownNat, type (+), Nat, natVal )
import Data.Kind ( Type, Constraint )
import Data.Foldable ( foldrM )
-- TODO: Remove dependency on Ghengin non-core
import Ghengin.Asset.Texture
( freeTexture, Texture2D(referenceCount) )
import Ghengin.Utils
( Storable(sizeOf), Proxy(Proxy), incRefCount, GHList )
TODO : Remove dependency on Vulkan
import Ghengin.Vulkan (Renderer)
import Ghengin.Vulkan.Buffer
( createMappedBuffer, writeMappedBuffer, MappedBuffer )
import Ghengin.Vulkan.DescriptorSet
( getUniformBuffer,
updateDescriptorSet,
DescriptorResource(Texture2DResource, UniformResource),
DescriptorSet(_descriptorSet),
ResourceMap )
import qualified Data.IntMap as IM
TODO : Core should n't depend on any specific renderer implementation external to Core
import qualified Unsafe.Coerce
data PropertyBinding α where
DynamicBinding :: ∀ α. (Storable α) -- Storable to write the buffers
=> α -- ^ A dynamic binding is written (necessarily because of linearity) to a mapped buffer based on the value of the constructor
-> PropertyBinding α
StaticBinding :: ∀ α. (Storable α) -- Storable to write the buffers
=> α -- ^ A dynamic binding is written (necessarily because of linearity) to a mapped buffer based on the value of the constructor
-> PropertyBinding α
Texture2DBinding :: Texture2D -> PropertyBinding Texture2D
instance Eq α => Eq (PropertyBinding α) where
(==) (DynamicBinding x) (DynamicBinding y) = x == y
(==) (StaticBinding x) (StaticBinding y) = x == y
(==) (Texture2DBinding x) (Texture2DBinding y) = x == y
(==) _ _ = False
type PropertyBindings α = GHList PropertyBinding α
propertyValue :: PropertyBinding α -> α
propertyValue = \case
DynamicBinding x -> x
StaticBinding x -> x
Texture2DBinding x -> x
-- | Recursively make the descriptor set resource map from the list of properties. This
-- will create some resources
--
-- * Dynamic buffers: It will create a mapped buffer but write nothing to it - these buffers are written every frame.
-- * Static buffer: It will create and write a buffer that can be manually updated
-- * Texture2D: It will simply add the already existing texture that was created (and engine prepared) on texture creation
--
-- Additionally, update the reference counts of resources that are reference
-- counted:
-- * Texture2D
makeResources :: ∀ α χ. PropertyBindings α -> Renderer χ ResourceMap
See Note [ Coerce HList to List ]
where
go :: ∀ β χ1. ResourceMap -> Int -> PropertyBinding β -> Renderer χ1 ResourceMap
go resources i = \case
DynamicBinding x -> do
-- Allocate the associated buffers
mb <- createMappedBuffer (fromIntegral $ sizeOf x) Vk.DESCRIPTOR_TYPE_UNIFORM_BUFFER
pure $ IM.insert i (UniformResource mb) resources
StaticBinding x -> do
-- Allocate the associated buffers
mb <- createMappedBuffer (fromIntegral $ sizeOf x) Vk.DESCRIPTOR_TYPE_UNIFORM_BUFFER -- TODO: Should this be a deviceLocalBuffer?
-- Write the static information to this buffer right away
writeMappedBuffer mb x
-- TODO: instead -> createDeviceLocalBuffer Vk.BUFFER_USAGE_UNIFORM_BUFFER_BIT x
pure $ IM.insert i (UniformResource mb) resources
Texture2DBinding t -> do
incRefCount t
-- Image has already been allocated when the texture was created, we
-- simply pass add it to the resource map
pure $ IM.insert i (Texture2DResource t) resources
-- | Write a property binding value to a mapped buffer. Eventually we might
-- want to associate the binding set and binding #number and get them directly
-- from the mapped buffers
--
( 1 ) For each binding
( 1.1 ) If it 's dynamic , write the buffer
( 1.2 ) If it 's static , do nothing because the buffer is already written
( 1.3 ) If it 's a texture , do nothing because the texture is written only once and has already been bound
--
-- The property bindings function should be created from a compatible pipeline
writeProperty :: MappedBuffer -> PropertyBinding α -> Renderer χ ()
writeProperty buf = \case
StaticBinding _ ->
-- Already has been written to, we simply bind it together with the rest of
-- the set at draw time and do nothing here.
pure ()
Texture2DBinding _ ->
-- As above. Static bindings don't get written every frame.
pure ()
DynamicBinding (a :: α) ->
-- Dynamic bindings are written every frame
writeMappedBuffer @α buf a
# INLINE writeProperty #
-- | Class of types that have property bindings.
Instances include ' Mesh ' , ' Material ' and ' RenderPipeline ' .
--
-- We can fetch their descriptor set resources, as well as edit their
-- individual properties through 'HasPropertyAt'.
--
Consider as an alternative to HasProperties a list - like type of properties
-- with an χ parameter for the extra information at the list's end.
class HasProperties φ where
properties :: φ α -> PropertyBindings α
descriptorSet :: Lens' (φ α) DescriptorSet
puncons :: φ (α:β) -> (PropertyBinding α, φ β)
pcons :: PropertyBinding α -> φ β -> φ (α:β)
-- | If we know that a type (φ α) has property of type (β) at binding (#n), we
-- can edit that property or get its value
--
Instanced by Material , Mesh and RenderPipeline
type HasPropertyAt :: Nat -- ^ Position at which the structure has the property
-> Type -- ^ Property it has at the position
-> ([Type] -> Type) -- ^ Structure with list of properties
-> [Type] -- ^ Type level list of properties
-> Constraint
class HasProperties φ => HasPropertyAt n β φ α where
-- | Lens to get and edit a φ that holds a list of bindings.
φ might be a ' Material ' , a ' RenderPipeline ' , or a ' Mesh '
--
-- Most materials are (existentially) stored within a render packet, and thus
-- cannot be edited without checking what material is what, even if we, at the
apecs level , only query for entities that we are sure to have that material .
--
-- To introduce a local equality constraint proving that the material we looked
up is in fact the one we want to edit , we must use @Data . Typeable@ 's @eqT@ function .
--
-- Example
-- @
RenderPacket oldMesh ( someMaterial : : Material mt ) pp _ < - C.get planetEntity
--
-- Pattern match on to introduce the mt ~ PlanetMaterial local equality
-- Just Refl <- pure $ eqT @mt @PlanetMaterial
--
-- We can now edit the material 's second binding using the ' propertyAt '
-- -- lens, because we know the material to be a PlanetMaterial
newMat < - someMaterial & propertyAt @2 % ~ \(WithVec3 x y z ) - > pure ( vec3 x ( y+1 ) z )
-- C.set planetEntity (renderPacket oldMesh newMat pp)
-- @
--
-- The nice thing about introducing equality constraints is that we can edit
-- the material and then re-create the render packet with the same pipeline as
-- it was originally created despite us not knowing anything about its type:
-- The local equality simply allowed us to edit the Material with at specific
-- type, but the information regarding compatibility between *that same type
-- (that we previously didn't know enough about to edit)* is preserved!
--
-- Additionally, when the material is edited through this function
-- resources can be automatically managed if needed
--
-- Previously we would have to recreate and reallocate all the descriptors and
-- buffers for a material, now we can simply rewrite the exact buffer without
-- doing a single allocation, or update the dset with the new texture
--
-- Another great thing, previously we would need to allocate a new descriptor
-- set every time we wanted to edit a material, but we didn't discard it
-- because freeing descriptor sets is actually freeing the pool (or using a
-- specific slower flag for freeing individual sets if i'm not mistaken).
-- This way, we always re-use the same set by simply writing over the e.g.
-- texture bindings if need be
propertyAt :: Lens (φ α) (Renderer χ (φ α)) β (Renderer χ β)
instance (HasPropertyAt' n 0 φ α β, HasProperties φ) => HasPropertyAt n β φ α where
propertyAt = propertyAt' @n @0 @φ @α @β
-- | Helper class to instance 'HasPropertyAt'.
--
-- There is a default implementation for 'HasPropertyAt' and instances are only
-- required for this class
class HasPropertyAt' n m φ α β where
propertyAt' :: Lens (φ α) (Renderer χ (φ α)) β (Renderer χ β)
-- This instance should always overlap the recursive instance below because we
-- want to stop when we find the binding
instance {-# OVERLAPPING #-}
( HasProperties φ
, KnownNat n
) => HasPropertyAt' n n φ (β:αs) β where
propertyAt' :: Lens (φ (β:αs)) (Renderer χ (φ (β:αs))) β (Renderer χ β)
propertyAt' = lens get' set' where
get' :: φ (β:αs) -> β
get' = propertyValue . fst . puncons
set' :: φ (β:αs) -> Renderer χ β -> Renderer χ (φ (β:αs))
set' (puncons -> (prop, xs)) rb =
pcons <$>
editProperty prop (const rb) (fromIntegral (natVal $ Proxy @n)) (xs ^. descriptorSet) <*>
pure xs
instance {-# OVERLAPPABLE #-}
( HasProperties φ
, HasPropertyAt' n (m+1) φ αs β
) => HasPropertyAt' n m φ (α ': αs) β where
propertyAt' :: Lens (φ (α:αs)) (Renderer χ (φ (α:αs))) β (Renderer χ β)
propertyAt' f (puncons -> (prop, xs)) =
fmap (pcons prop) <$> propertyAt' @n @(m+1) @φ @αs @β f xs
-- Does it make sense to have this?
-- instance
-- ( Length α ~ m
-- , TypeError (Text "Failed to get property binding #" :<>: ShowType n :<>: Text " from properties " :<>: ShowType α)
-- ) => HasPropertyAt' n m φ α b where
-- propertyAt' = undefined
-- | Edit the value of a property. You most likely don't need this function.
-- See 'pedit' and 'peditM' in 'HasPropertyAt'
editProperty :: ∀ α χ
. PropertyBinding α -- ^ Property to edit/update
-> (α -> Renderer χ α) -- ^ Update function
-> Int -- ^ Property index in descriptor set
-> DescriptorSet -- ^ The descriptor set with corresponding index and property resources
-> Renderer χ (PropertyBinding α) -- ^ Returns the updated property binding
editProperty prop update i dset = case prop of
DynamicBinding x -> do
ux <- update x
writeDynamicBinding ux
pure $ DynamicBinding ux
StaticBinding x -> do
ux <- update x
writeStaticBinding ux
pure $ StaticBinding ux
Texture2DBinding x -> do
ux <- update x
updateTextureBinding ux
-- We free the texture that was previously bound
freeTexture x
-- We increase the texture reference count that was just now bound
incRefCount ux
pure $ Texture2DBinding ux
where
writeDynamicBinding :: Storable α => α -> Renderer χ ()
writeDynamicBinding = writeMappedBuffer @α (getUniformBuffer dset i)
-- For now, static bindings use a mapped buffer as well
writeStaticBinding :: Storable α => α -> Renderer χ ()
writeStaticBinding = writeMappedBuffer @α (getUniformBuffer dset i)
-- | Overwrite the texture bound on a descriptor set at binding #n
--
-- TODO: Is it OK to overwrite previously written descriptor sets at specific points?
updateTextureBinding :: Texture2D -> Renderer χ ()
updateTextureBinding = updateDescriptorSet (dset._descriptorSet) . IM.singleton i . Texture2DResource
freeProperty :: PropertyBinding α -> Renderer χ ()
freeProperty = \case
DynamicBinding _ -> pure ()
StaticBinding _ -> pure ()
Texture2DBinding x -> freeTexture x
| null |
https://raw.githubusercontent.com/alt-romes/ghengin/f821fcf60f1f78e1f63d28d9a749597d844af994/src/Ghengin/Core/Render/Property.hs
|
haskell
|
TODO: Remove dependency on Ghengin non-core
Storable to write the buffers
^ A dynamic binding is written (necessarily because of linearity) to a mapped buffer based on the value of the constructor
Storable to write the buffers
^ A dynamic binding is written (necessarily because of linearity) to a mapped buffer based on the value of the constructor
| Recursively make the descriptor set resource map from the list of properties. This
will create some resources
* Dynamic buffers: It will create a mapped buffer but write nothing to it - these buffers are written every frame.
* Static buffer: It will create and write a buffer that can be manually updated
* Texture2D: It will simply add the already existing texture that was created (and engine prepared) on texture creation
Additionally, update the reference counts of resources that are reference
counted:
* Texture2D
Allocate the associated buffers
Allocate the associated buffers
TODO: Should this be a deviceLocalBuffer?
Write the static information to this buffer right away
TODO: instead -> createDeviceLocalBuffer Vk.BUFFER_USAGE_UNIFORM_BUFFER_BIT x
Image has already been allocated when the texture was created, we
simply pass add it to the resource map
| Write a property binding value to a mapped buffer. Eventually we might
want to associate the binding set and binding #number and get them directly
from the mapped buffers
The property bindings function should be created from a compatible pipeline
Already has been written to, we simply bind it together with the rest of
the set at draw time and do nothing here.
As above. Static bindings don't get written every frame.
Dynamic bindings are written every frame
| Class of types that have property bindings.
We can fetch their descriptor set resources, as well as edit their
individual properties through 'HasPropertyAt'.
with an χ parameter for the extra information at the list's end.
| If we know that a type (φ α) has property of type (β) at binding (#n), we
can edit that property or get its value
^ Position at which the structure has the property
^ Property it has at the position
^ Structure with list of properties
^ Type level list of properties
| Lens to get and edit a φ that holds a list of bindings.
Most materials are (existentially) stored within a render packet, and thus
cannot be edited without checking what material is what, even if we, at the
To introduce a local equality constraint proving that the material we looked
Example
@
Pattern match on to introduce the mt ~ PlanetMaterial local equality
Just Refl <- pure $ eqT @mt @PlanetMaterial
We can now edit the material 's second binding using the ' propertyAt '
-- lens, because we know the material to be a PlanetMaterial
C.set planetEntity (renderPacket oldMesh newMat pp)
@
The nice thing about introducing equality constraints is that we can edit
the material and then re-create the render packet with the same pipeline as
it was originally created despite us not knowing anything about its type:
The local equality simply allowed us to edit the Material with at specific
type, but the information regarding compatibility between *that same type
(that we previously didn't know enough about to edit)* is preserved!
Additionally, when the material is edited through this function
resources can be automatically managed if needed
Previously we would have to recreate and reallocate all the descriptors and
buffers for a material, now we can simply rewrite the exact buffer without
doing a single allocation, or update the dset with the new texture
Another great thing, previously we would need to allocate a new descriptor
set every time we wanted to edit a material, but we didn't discard it
because freeing descriptor sets is actually freeing the pool (or using a
specific slower flag for freeing individual sets if i'm not mistaken).
This way, we always re-use the same set by simply writing over the e.g.
texture bindings if need be
| Helper class to instance 'HasPropertyAt'.
There is a default implementation for 'HasPropertyAt' and instances are only
required for this class
This instance should always overlap the recursive instance below because we
want to stop when we find the binding
# OVERLAPPING #
# OVERLAPPABLE #
Does it make sense to have this?
instance
( Length α ~ m
, TypeError (Text "Failed to get property binding #" :<>: ShowType n :<>: Text " from properties " :<>: ShowType α)
) => HasPropertyAt' n m φ α b where
propertyAt' = undefined
| Edit the value of a property. You most likely don't need this function.
See 'pedit' and 'peditM' in 'HasPropertyAt'
^ Property to edit/update
^ Update function
^ Property index in descriptor set
^ The descriptor set with corresponding index and property resources
^ Returns the updated property binding
We free the texture that was previously bound
We increase the texture reference count that was just now bound
For now, static bindings use a mapped buffer as well
| Overwrite the texture bound on a descriptor set at binding #n
TODO: Is it OK to overwrite previously written descriptor sets at specific points?
|
# LANGUAGE AllowAmbiguousTypes #
# LANGUAGE UndecidableInstances #
# LANGUAGE OverloadedRecordDot #
module Ghengin.Core.Render.Property where
import Control.Lens ((^.), Lens, Lens', lens)
import GHC.TypeLits ( KnownNat, type (+), Nat, natVal )
import Data.Kind ( Type, Constraint )
import Data.Foldable ( foldrM )
import Ghengin.Asset.Texture
( freeTexture, Texture2D(referenceCount) )
import Ghengin.Utils
( Storable(sizeOf), Proxy(Proxy), incRefCount, GHList )
TODO : Remove dependency on Vulkan
import Ghengin.Vulkan (Renderer)
import Ghengin.Vulkan.Buffer
( createMappedBuffer, writeMappedBuffer, MappedBuffer )
import Ghengin.Vulkan.DescriptorSet
( getUniformBuffer,
updateDescriptorSet,
DescriptorResource(Texture2DResource, UniformResource),
DescriptorSet(_descriptorSet),
ResourceMap )
import qualified Data.IntMap as IM
TODO : Core should n't depend on any specific renderer implementation external to Core
import qualified Unsafe.Coerce
data PropertyBinding α where
-> PropertyBinding α
-> PropertyBinding α
Texture2DBinding :: Texture2D -> PropertyBinding Texture2D
instance Eq α => Eq (PropertyBinding α) where
(==) (DynamicBinding x) (DynamicBinding y) = x == y
(==) (StaticBinding x) (StaticBinding y) = x == y
(==) (Texture2DBinding x) (Texture2DBinding y) = x == y
(==) _ _ = False
type PropertyBindings α = GHList PropertyBinding α
propertyValue :: PropertyBinding α -> α
propertyValue = \case
DynamicBinding x -> x
StaticBinding x -> x
Texture2DBinding x -> x
makeResources :: ∀ α χ. PropertyBindings α -> Renderer χ ResourceMap
See Note [ Coerce HList to List ]
where
go :: ∀ β χ1. ResourceMap -> Int -> PropertyBinding β -> Renderer χ1 ResourceMap
go resources i = \case
DynamicBinding x -> do
mb <- createMappedBuffer (fromIntegral $ sizeOf x) Vk.DESCRIPTOR_TYPE_UNIFORM_BUFFER
pure $ IM.insert i (UniformResource mb) resources
StaticBinding x -> do
writeMappedBuffer mb x
pure $ IM.insert i (UniformResource mb) resources
Texture2DBinding t -> do
incRefCount t
pure $ IM.insert i (Texture2DResource t) resources
( 1 ) For each binding
( 1.1 ) If it 's dynamic , write the buffer
( 1.2 ) If it 's static , do nothing because the buffer is already written
( 1.3 ) If it 's a texture , do nothing because the texture is written only once and has already been bound
writeProperty :: MappedBuffer -> PropertyBinding α -> Renderer χ ()
writeProperty buf = \case
StaticBinding _ ->
pure ()
Texture2DBinding _ ->
pure ()
DynamicBinding (a :: α) ->
writeMappedBuffer @α buf a
# INLINE writeProperty #
Instances include ' Mesh ' , ' Material ' and ' RenderPipeline ' .
Consider as an alternative to HasProperties a list - like type of properties
class HasProperties φ where
properties :: φ α -> PropertyBindings α
descriptorSet :: Lens' (φ α) DescriptorSet
puncons :: φ (α:β) -> (PropertyBinding α, φ β)
pcons :: PropertyBinding α -> φ β -> φ (α:β)
Instanced by Material , Mesh and RenderPipeline
-> Constraint
class HasProperties φ => HasPropertyAt n β φ α where
φ might be a ' Material ' , a ' RenderPipeline ' , or a ' Mesh '
apecs level , only query for entities that we are sure to have that material .
up is in fact the one we want to edit , we must use @Data . Typeable@ 's @eqT@ function .
RenderPacket oldMesh ( someMaterial : : Material mt ) pp _ < - C.get planetEntity
newMat < - someMaterial & propertyAt @2 % ~ \(WithVec3 x y z ) - > pure ( vec3 x ( y+1 ) z )
propertyAt :: Lens (φ α) (Renderer χ (φ α)) β (Renderer χ β)
instance (HasPropertyAt' n 0 φ α β, HasProperties φ) => HasPropertyAt n β φ α where
propertyAt = propertyAt' @n @0 @φ @α @β
class HasPropertyAt' n m φ α β where
propertyAt' :: Lens (φ α) (Renderer χ (φ α)) β (Renderer χ β)
( HasProperties φ
, KnownNat n
) => HasPropertyAt' n n φ (β:αs) β where
propertyAt' :: Lens (φ (β:αs)) (Renderer χ (φ (β:αs))) β (Renderer χ β)
propertyAt' = lens get' set' where
get' :: φ (β:αs) -> β
get' = propertyValue . fst . puncons
set' :: φ (β:αs) -> Renderer χ β -> Renderer χ (φ (β:αs))
set' (puncons -> (prop, xs)) rb =
pcons <$>
editProperty prop (const rb) (fromIntegral (natVal $ Proxy @n)) (xs ^. descriptorSet) <*>
pure xs
( HasProperties φ
, HasPropertyAt' n (m+1) φ αs β
) => HasPropertyAt' n m φ (α ': αs) β where
propertyAt' :: Lens (φ (α:αs)) (Renderer χ (φ (α:αs))) β (Renderer χ β)
propertyAt' f (puncons -> (prop, xs)) =
fmap (pcons prop) <$> propertyAt' @n @(m+1) @φ @αs @β f xs
editProperty :: ∀ α χ
editProperty prop update i dset = case prop of
DynamicBinding x -> do
ux <- update x
writeDynamicBinding ux
pure $ DynamicBinding ux
StaticBinding x -> do
ux <- update x
writeStaticBinding ux
pure $ StaticBinding ux
Texture2DBinding x -> do
ux <- update x
updateTextureBinding ux
freeTexture x
incRefCount ux
pure $ Texture2DBinding ux
where
writeDynamicBinding :: Storable α => α -> Renderer χ ()
writeDynamicBinding = writeMappedBuffer @α (getUniformBuffer dset i)
writeStaticBinding :: Storable α => α -> Renderer χ ()
writeStaticBinding = writeMappedBuffer @α (getUniformBuffer dset i)
updateTextureBinding :: Texture2D -> Renderer χ ()
updateTextureBinding = updateDescriptorSet (dset._descriptorSet) . IM.singleton i . Texture2DResource
freeProperty :: PropertyBinding α -> Renderer χ ()
freeProperty = \case
DynamicBinding _ -> pure ()
StaticBinding _ -> pure ()
Texture2DBinding x -> freeTexture x
|
c390ff730b5d09730752b6066e8d7cbcd07698a02f681f2ef1d6f2ba2906441f
|
sjl/euler
|
005.lisp
|
(defpackage :euler/005 #.euler:*use*)
(in-package :euler/005)
2520 is the smallest number that can be divided by each of the numbers from
1 to 10 without any remainder .
;;
;; What is the smallest positive number that is evenly divisible by all of the
numbers from 1 to 20 ?
(define-problem (5 232792560)
(iterate
all numbers are divisible by 1 and we can skip checking everything < = 10
;; because:
;;
anything divisible by 12 is automatically divisible by 2
anything divisible by 12 is automatically divisible by 3
anything divisible by 12 is automatically divisible by 4
anything divisible by 15 is automatically divisible by 5
anything divisible by 12 is automatically divisible by 6
anything divisible by 14 is automatically divisible by 7
anything divisible by 16 is automatically divisible by 8
anything divisible by 18 is automatically divisible by 9
anything divisible by 20 is automatically divisible by 10
(with divisors = (range 11 20))
it must be divisible by 20
(finding i :such-that (every (curry #'dividesp i) divisors))))
| null |
https://raw.githubusercontent.com/sjl/euler/29cd8242172a2d11128439bb99217a0a859057ed/src/problems/005.lisp
|
lisp
|
What is the smallest positive number that is evenly divisible by all of the
because:
|
(defpackage :euler/005 #.euler:*use*)
(in-package :euler/005)
2520 is the smallest number that can be divided by each of the numbers from
1 to 10 without any remainder .
numbers from 1 to 20 ?
(define-problem (5 232792560)
(iterate
all numbers are divisible by 1 and we can skip checking everything < = 10
anything divisible by 12 is automatically divisible by 2
anything divisible by 12 is automatically divisible by 3
anything divisible by 12 is automatically divisible by 4
anything divisible by 15 is automatically divisible by 5
anything divisible by 12 is automatically divisible by 6
anything divisible by 14 is automatically divisible by 7
anything divisible by 16 is automatically divisible by 8
anything divisible by 18 is automatically divisible by 9
anything divisible by 20 is automatically divisible by 10
(with divisors = (range 11 20))
it must be divisible by 20
(finding i :such-that (every (curry #'dividesp i) divisors))))
|
b06bc073e59bd0715f2fd6e00fe49d400736befdfbd047603b876f80bd7be0f0
|
Yomguithereal/clj-fuzzy
|
caverphone_test.clj
|
;; -------------------------------------------------------------------
clj - fuzzy Caverphone Tests
;; -------------------------------------------------------------------
;;
;;
Author : ( Yomguithereal )
Version : 0.1
;;
(ns clj-fuzzy.caverphone-test
(:require [clojure.test :refer :all]
[clj-fuzzy.caverphone :refer :all]))
(def process-revisited (fn [word] (process word :revisited)))
(deftest process-test
(is (= "ANRKSN1111" (process "Henrichsen")))
(is (= "ANRKSN1111" (process "Henricsson")))
(is (= "ANRKSN1111" (process "Henriksson")))
(is (= "ANRKSN1111" (process "Hinrichsen")))
(is (= "ASKKA11111" (process "Izchaki")))
(is (= "MKLFTA1111" (process "Maclaverty")))
(is (= "MKLFTA1111" (process "Macleverty")))
(is (= "MKLFTA1111" (process "Mcclifferty")))
(is (= "MKLFTA1111" (process "Mclafferty")))
(is (= "MKLFTA1111" (process "Mclaverty")))
(is (= "SLKMP11111" (process "Slocomb")))
(is (= "SLKMP11111" (process "Slocombe")))
(is (= "SLKMP11111" (process "Slocumb")))
(is (= "WTLM111111" (process "Whitlam"))))
(deftest process-revisited-test
(is (= "PTA1111111" (process-revisited "Peter")))
(is (= "ANRKSN1111" (process-revisited "Henrichsen")))
(is (= "STFNSN1111" (process-revisited "Stevenson"))))
| null |
https://raw.githubusercontent.com/Yomguithereal/clj-fuzzy/ce7c57dfb14f6ddc99bf4d9ab74c778128438d8b/test/clj_fuzzy/caverphone_test.clj
|
clojure
|
-------------------------------------------------------------------
-------------------------------------------------------------------
|
clj - fuzzy Caverphone Tests
Author : ( Yomguithereal )
Version : 0.1
(ns clj-fuzzy.caverphone-test
(:require [clojure.test :refer :all]
[clj-fuzzy.caverphone :refer :all]))
(def process-revisited (fn [word] (process word :revisited)))
(deftest process-test
(is (= "ANRKSN1111" (process "Henrichsen")))
(is (= "ANRKSN1111" (process "Henricsson")))
(is (= "ANRKSN1111" (process "Henriksson")))
(is (= "ANRKSN1111" (process "Hinrichsen")))
(is (= "ASKKA11111" (process "Izchaki")))
(is (= "MKLFTA1111" (process "Maclaverty")))
(is (= "MKLFTA1111" (process "Macleverty")))
(is (= "MKLFTA1111" (process "Mcclifferty")))
(is (= "MKLFTA1111" (process "Mclafferty")))
(is (= "MKLFTA1111" (process "Mclaverty")))
(is (= "SLKMP11111" (process "Slocomb")))
(is (= "SLKMP11111" (process "Slocombe")))
(is (= "SLKMP11111" (process "Slocumb")))
(is (= "WTLM111111" (process "Whitlam"))))
(deftest process-revisited-test
(is (= "PTA1111111" (process-revisited "Peter")))
(is (= "ANRKSN1111" (process-revisited "Henrichsen")))
(is (= "STFNSN1111" (process-revisited "Stevenson"))))
|
b2b6a92bca3ee2cd0f381669ada5b1f6d4b2c09809bf1354ad8156f1ad4d8d46
|
RefactoringTools/HaRe
|
Prelude.hs
|
---------------------------------------------------------------------------
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
|| || || || || || || _ _ Hugs 98 : The Nottingham and Yale Haskell system
||___|| ||__|| ||__|| _ _ || Copyright ( c ) 1994 - 1999
||---|| _ _ _ || World Wide Web :
|| || Report bugs to :
|| || Version : February 1999 _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
This is the Hugs 98 Standard Prelude , based very closely on the Standard
Prelude for 98 .
WARNING : This file is an integral part of the Hugs source code . Changes to
the definitions in this file without corresponding modifications in other
parts of the program may cause the interpreter to fail unexpectedly . Under
normal circumstances , you should not attempt to modify this file in any way !
-----------------------------------------------------------------------------
The Hugs 98 system is Copyright ( c ) , , the
Yale Haskell Group , and the Oregon Graduate Institute of Science and
Technology , 1994 - 1999 , All rights reserved . It is distributed as
free software under the license in the file " License " , which is
included in the distribution .
---------------------------------------------------------------------------
__ __ __ __ ____ ___ _______________________________________________
|| || || || || || ||__ Hugs 98: The Nottingham and Yale Haskell system
||___|| ||__|| ||__|| __|| Copyright (c) 1994-1999
||---|| ___|| World Wide Web:
|| || Report bugs to:
|| || Version: February 1999_______________________________________________
This is the Hugs 98 Standard Prelude, based very closely on the Standard
Prelude for Haskell 98.
WARNING: This file is an integral part of the Hugs source code. Changes to
the definitions in this file without corresponding modifications in other
parts of the program may cause the interpreter to fail unexpectedly. Under
normal circumstances, you should not attempt to modify this file in any way!
-----------------------------------------------------------------------------
The Hugs 98 system is Copyright (c) Mark P Jones, Alastair Reid, the
Yale Haskell Group, and the Oregon Graduate Institute of Science and
Technology, 1994-1999, All rights reserved. It is distributed as
free software under the license in the file "License", which is
included in the distribution.
----------------------------------------------------------------------------}
(
-- module PreludeList ,
map , ( + + ) , concat , filter ,
head , last , tail , init , null , length , ( ! ! ) ,
foldl , foldl1 , , scanl1 , foldr , foldr1 , , scanr1 ,
iterate , repeat , replicate , cycle ,
take , drop , splitAt , takeWhile , dropWhile , span , break ,
lines , words , unlines , unwords , reverse , and , or ,
any , all , elem , notElem , lookup ,
sum , product , maximum , minimum , concatMap ,
zip , zip3 , zipWith , zipWith3 , unzip , unzip3 ,
-- module PreludeText ,
ReadS , ,
Read(readsPrec , readList ) ,
Show(show , showsPrec , showList ) ,
reads , shows , read , lex ,
showChar , showString , readParen , showParen ,
-- module PreludeIO ,
FilePath , IOError , ioError , userError , catch ,
putChar , putStr , putStrLn , print ,
getChar , getLine , getContents , interact ,
readFile , writeFile , appendFile , readIO , readLn ,
-- module Ix ,
Ix(range , index , inRange , rangeSize ) ,
-- module ,
isAscii , isControl , isPrint , isSpace , isUpper , isLower ,
isAlpha , isDigit , isOctDigit , isHexDigit , isAlphaNum ,
digitToInt , intToDigit ,
toUpper , toLower ,
ord , chr ,
readLitChar , , lexLitChar ,
-- module Numeric
showSigned , showInt ,
readSigned , readInt ,
readDec , readOct , readHex , readSigned ,
readFloat , lexDigits ,
-- module Ratio ,
Ratio , Rational , ( % ) , numerator , denominator , approxRational ,
-- Non - standard exports
IO ( .. ) , ( .. ) , primExitWith , ,
Bool(False , True ) ,
Maybe(Nothing , Just ) ,
Either(Left , Right ) ,
Ordering(LT , EQ , GT ) ,
Char , String , Int , Integer , Float , Double , IO ,
-- List type : [ ] ( (: ) , [ ] )
-- ( :) ,
-- Tuple types : ( , ) , ( , , ) , etc .
-- Trivial type : ( )
-- Functions : ( - > )
Rec , EmptyRec , EmptyRow , -- non - standard , should only be exported if TREX
Eq((== ) , ( /= ) ) ,
Ord(compare , ( < ) , ( < =) , ( > =) , ( > ) , , min ) ,
, pred , toEnum , fromEnum , enumFrom , enumFromThen ,
enumFromTo , enumFromThenTo ) ,
Bounded(minBound , maxBound ) ,
-- Num((+ ) , ( - ) , ( * ) , negate , abs , signum , fromInteger ) ,
Num((+ ) , ( - ) , ( * ) , negate , abs , signum , fromInteger , fromInt ) ,
Real(toRational ) ,
-- Integral(quot , rem , div , mod , quotRem , divMod , toInteger ) ,
Integral(quot , rem , div , mod , quotRem , divMod , even , odd , toInteger , toInt ) ,
-- ) , recip , fromRational ) ,
) , recip , fromRational , fromDouble ) ,
Floating(pi , exp , log , sqrt , ( * * ) , logBase , sin , cos , tan ,
asin , acos , atan , sinh , , tanh , asinh , acosh , atanh ) ,
RealFrac(properFraction , truncate , round , ceiling , floor ) ,
RealFloat(floatRadix , floatDigits , floatRange , decodeFloat ,
encodeFloat , exponent , significand , scaleFloat , isNaN ,
isInfinite , isDenormalized , isIEEE , isNegativeZero , atan2 ) ,
Monad((>>= ) , ( > > ) , return , fail ) ,
Functor(fmap ) ,
mapM , mapM _ , sequence , sequence _ , (= < < ) ,
maybe , either ,
( & & ) , ( || ) , not , otherwise ,
subtract , even , odd , gcd , lcm , ( ^ ) , ( ^^ ) ,
fromIntegral , realToFrac ,
fst , snd , curry , uncurry , i d , const , ( . ) , flip , ( $ ) , until ,
asTypeOf , error , undefined ,
seq , ( $ ! )
)
-- module PreludeList,
map, (++), concat, filter,
head, last, tail, init, null, length, (!!),
foldl, foldl1, scanl, scanl1, foldr, foldr1, scanr, scanr1,
iterate, repeat, replicate, cycle,
take, drop, splitAt, takeWhile, dropWhile, span, break,
lines, words, unlines, unwords, reverse, and, or,
any, all, elem, notElem, lookup,
sum, product, maximum, minimum, concatMap,
zip, zip3, zipWith, zipWith3, unzip, unzip3,
-- module PreludeText,
ReadS, ShowS,
Read(readsPrec, readList),
Show(show, showsPrec, showList),
reads, shows, read, lex,
showChar, showString, readParen, showParen,
-- module PreludeIO,
FilePath, IOError, ioError, userError, catch,
putChar, putStr, putStrLn, print,
getChar, getLine, getContents, interact,
readFile, writeFile, appendFile, readIO, readLn,
-- module Ix,
Ix(range, index, inRange, rangeSize),
-- module Char,
isAscii, isControl, isPrint, isSpace, isUpper, isLower,
isAlpha, isDigit, isOctDigit, isHexDigit, isAlphaNum,
digitToInt, intToDigit,
toUpper, toLower,
ord, chr,
readLitChar, showLitChar, lexLitChar,
-- module Numeric
showSigned, showInt,
readSigned, readInt,
readDec, readOct, readHex, readSigned,
readFloat, lexDigits,
-- module Ratio,
Ratio, Rational, (%), numerator, denominator, approxRational,
-- Non-standard exports
IO(..), IOResult(..), primExitWith, Addr,
Bool(False, True),
Maybe(Nothing, Just),
Either(Left, Right),
Ordering(LT, EQ, GT),
Char, String, Int, Integer, Float, Double, IO,
-- List type: []((:), [])
-- (:),
-- Tuple types: (,), (,,), etc.
-- Trivial type: ()
-- Functions: (->)
Rec, EmptyRec, EmptyRow, -- non-standard, should only be exported if TREX
Eq((==), (/=)),
Ord(compare, (<), (<=), (>=), (>), max, min),
Enum(succ, pred, toEnum, fromEnum, enumFrom, enumFromThen,
enumFromTo, enumFromThenTo),
Bounded(minBound, maxBound),
-- Num((+), (-), (*), negate, abs, signum, fromInteger),
Num((+), (-), (*), negate, abs, signum, fromInteger, fromInt),
Real(toRational),
-- Integral(quot, rem, div, mod, quotRem, divMod, toInteger),
Integral(quot, rem, div, mod, quotRem, divMod, even, odd, toInteger, toInt),
-- Fractional((/), recip, fromRational),
Fractional((/), recip, fromRational, fromDouble),
Floating(pi, exp, log, sqrt, (**), logBase, sin, cos, tan,
asin, acos, atan, sinh, cosh, tanh, asinh, acosh, atanh),
RealFrac(properFraction, truncate, round, ceiling, floor),
RealFloat(floatRadix, floatDigits, floatRange, decodeFloat,
encodeFloat, exponent, significand, scaleFloat, isNaN,
isInfinite, isDenormalized, isIEEE, isNegativeZero, atan2),
Monad((>>=), (>>), return, fail),
Functor(fmap),
mapM, mapM_, sequence, sequence_, (=<<),
maybe, either,
(&&), (||), not, otherwise,
subtract, even, odd, gcd, lcm, (^), (^^),
fromIntegral, realToFrac,
fst, snd, curry, uncurry, id, const, (.), flip, ($), until,
asTypeOf, error, undefined,
seq, ($!)
) -} where
-- Standard value bindings {Prelude} ----------------------------------------
infixr 9 .
infixl 9 !!
infixr 8 ^, ^^, **
infixl 7 *, /, `quot`, `rem`, `div`, `mod`, :%, %
infixl 6 +, -
infixr 5 : -- this fixity declaration is hard - wired into Hugs
infixr 5 ++
infix 4 ==, /=, <, <=, >=, >, `elem`, `notElem`
infixr 3 &&
infixr 2 ||
infixl 1 >>, >>=
infixr 1 =<<
infixr 0 $, $!, `seq`
-- Equality and Ordered classes ---------------------------------------------
class Eq a where
(==), (/=) :: a -> a -> Bool
-- Minimal complete definition: (==) or (/=)
x == y = not (x/=y)
x /= y = not (x==y)
class (Eq a) => Ord a where
compare :: a -> a -> Ordering
(<), (<=), (>=), (>) :: a -> a -> Bool
max, min :: a -> a -> a
-- Minimal complete definition: (<=) or compare
-- using compare can be more efficient for complex types
compare x y | x==y = EQ
| x<=y = LT
| otherwise = GT
x <= y = compare x y /= GT
x < y = compare x y == LT
x >= y = compare x y /= LT
x > y = compare x y == GT
max x y | x >= y = x
| otherwise = y
min x y | x <= y = x
| otherwise = y
class Bounded a where
minBound, maxBound :: a
-- Minimal complete definition: All
-- Numeric classes ----------------------------------------------------------
class (Eq a, Show a) => Num a where
(+), (-), (*) :: a -> a -> a
negate :: a -> a
abs, signum :: a -> a
fromInteger :: Integer -> a
fromInt :: Int -> a
-- Minimal complete definition: All, except negate or (-)
x - y = x + negate y
fromInt = fromIntegral
negate x = 0 - x
class (Num a, Ord a) => Real a where
toRational :: a -> Rational
class (Real a, Enum a) => Integral a where
quot, rem, div, mod :: a -> a -> a
quotRem, divMod :: a -> a -> (a,a)
even, odd :: a -> Bool
toInteger :: a -> Integer
toInt :: a -> Int
-- Minimal complete definition: quotRem and toInteger
n `quot` d = q where (q,r) = quotRem n d
n `rem` d = r where (q,r) = quotRem n d
n `div` d = q where (q,r) = divMod n d
n `mod` d = r where (q,r) = divMod n d
divMod n d = if signum r == - signum d then (q-1, r+d) else qr
where qr@(q,r) = quotRem n d
even n = n `rem` 2 == 0
odd = not . even
toInt = toInt . toInteger
class (Num a) => Fractional a where
(/) :: a -> a -> a
recip :: a -> a
fromRational :: Rational -> a
fromDouble :: Double -> a
-- Minimal complete definition: fromRational and ((/) or recip)
recip x = 1 / x
fromDouble = fromRational . toRational
x / y = x * recip y
class (Fractional a) => Floating a where
pi :: a
exp, log, sqrt :: a -> a
(**), logBase :: a -> a -> a
sin, cos, tan :: a -> a
asin, acos, atan :: a -> a
sinh, cosh, tanh :: a -> a
asinh, acosh, atanh :: a -> a
Minimal complete definition : pi , exp , log , sin , cos , sinh , cosh ,
asinh , acosh , atanh
pi = 4 * atan 1
x ** y = exp (log x * y)
logBase x y = log y / log x
sqrt x = x ** 0.5
tan x = sin x / cos x
sinh x = (exp x - exp (-x)) / 2
cosh x = (exp x + exp (-x)) / 2
tanh x = sinh x / cosh x
asinh x = log (x + sqrt (x*x + 1))
acosh x = log (x + sqrt (x*x - 1))
atanh x = (log (1 + x) - log (1 - x)) / 2
class (Real a, Fractional a) => RealFrac a where
properFraction :: (Integral b) => a -> (b,a)
truncate, round :: (Integral b) => a -> b
ceiling, floor :: (Integral b) => a -> b
-- Minimal complete definition: properFraction
truncate x = m where (m,_) = properFraction x
round x = let (n,r) = properFraction x
m = if r < 0 then n - 1 else n + 1
in case signum (abs r - 0.5) of
-1 -> n
0 -> if even n then n else m
1 -> m
ceiling x = if r > 0 then n + 1 else n
where (n,r) = properFraction x
floor x = if r < 0 then n - 1 else n
where (n,r) = properFraction x
class (RealFrac a, Floating a) => RealFloat a where
floatRadix :: a -> Integer
floatDigits :: a -> Int
floatRange :: a -> (Int,Int)
decodeFloat :: a -> (Integer,Int)
encodeFloat :: Integer -> Int -> a
exponent :: a -> Int
significand :: a -> a
scaleFloat :: Int -> a -> a
isNaN, isInfinite, isDenormalized, isNegativeZero, isIEEE
:: a -> Bool
atan2 :: a -> a -> a
-- Minimal complete definition: All, except exponent, signficand,
scaleFloat , atan2
exponent x = if m==0 then 0 else n + floatDigits x
where (m,n) = decodeFloat x
significand x = encodeFloat m (- floatDigits x)
where (m,_) = decodeFloat x
scaleFloat k x = encodeFloat m (n+k)
where (m,n) = decodeFloat x
atan2 y x
| x>0 = atan (y/x)
| x==0 && y>0 = pi/2
| x<0 && y>0 = pi + atan (y/x)
| (x<=0 && y<0) ||
(x<0 && isNegativeZero y) ||
(isNegativeZero x && isNegativeZero y)
= - atan2 (-y) x
| y==0 && (x<0 || isNegativeZero x)
must be after the previous test on zero y
must be after the other double zero tests
x or y is a NaN , return a NaN ( via + )
-- Numeric functions --------------------------------------------------------
subtract :: Num a => a -> a -> a
subtract = flip (-)
gcd :: Integral a => a -> a -> a
gcd 0 0 = error "Prelude.gcd: gcd 0 0 is undefined"
gcd x y = gcd' (abs x) (abs y)
where gcd' x 0 = x
gcd' x y = gcd' y (x `rem` y)
lcm :: (Integral a) => a -> a -> a
lcm _ 0 = 0
lcm 0 _ = 0
lcm x y = abs ((x `quot` gcd x y) * y)
(^) :: (Num a, Integral b) => a -> b -> a
x ^ 0 = 1
x ^ n | n > 0 = f x (n-1) x
where f _ 0 y = y
f x n y = g x n where
g x n | even n = g (x*x) (n`quot`2)
| otherwise = f x (n-1) (x*y)
_ ^ _ = error "Prelude.^: negative exponent"
(^^) :: (Fractional a, Integral b) => a -> b -> a
x ^^ n = if n >= 0 then x ^ n else recip (x^(-n))
fromIntegral :: (Integral a, Num b) => a -> b
fromIntegral = fromInteger . toInteger
realToFrac :: (Real a, Fractional b) => a -> b
realToFrac = fromRational . toRational
-- Index and Enumeration classes --------------------------------------------
class (Ord a) => Ix a where
range :: (a,a) -> [a]
index :: (a,a) -> a -> Int
inRange :: (a,a) -> a -> Bool
rangeSize :: (a,a) -> Int
rangeSize r@(l,u)
| l > u = 0
| otherwise = index r u + 1
class Enum a where
succ, pred :: a -> a
toEnum :: Int -> a
fromEnum :: a -> Int
enumFrom :: a -> [a] -- [n..]
enumFromThen :: a -> a -> [a] -- [n,m..]
enumFromTo :: a -> a -> [a] -- [n..m]
enumFromThenTo :: a -> a -> a -> [a] -- [n,n'..m]
-- Minimal complete definition: toEnum, fromEnum
succ = toEnum . (1+) . fromEnum
pred = toEnum . subtract 1 . fromEnum
enumFromTo x y = map toEnum [ fromEnum x .. fromEnum y ]
enumFromThenTo x y z = map toEnum [ fromEnum x, fromEnum y .. fromEnum z ]
-- Read and Show classes ------------------------------------------------------
type ReadS a = String -> [(a,String)]
type ShowS = String -> String
class Read a where
readsPrec :: Int -> ReadS a
readList :: ReadS [a]
-- Minimal complete definition: readsPrec
readList = readParen False (\r -> [pr | ("[",s) <- lex r,
pr <- readl s ])
where readl s = [([],t) | ("]",t) <- lex s] ++
[(x:xs,u) | (x,t) <- reads s,
(xs,u) <- readl' t]
readl' s = [([],t) | ("]",t) <- lex s] ++
[(x:xs,v) | (",",t) <- lex s,
(x,u) <- reads t,
(xs,v) <- readl' u]
class Show a where
show :: a -> String
showsPrec :: Int -> a -> ShowS
showList :: [a] -> ShowS
-- Minimal complete definition: show or showsPrec
show x = showsPrec 0 x ""
showsPrec _ x s = show x ++ s
showList [] = showString "[]"
showList (x:xs) = showChar '[' . shows x . showl xs
where showl [] = showChar ']'
showl (x:xs) = showChar ',' . shows x . showl xs
Monad classes ------------------------------------------------------------
class Functor f where
fmap :: (a -> b) -> (f a -> f b)
class Monad m where
return :: a -> m a
(>>=) :: m a -> (a -> m b) -> m b
(>>) :: m a -> m b -> m b
fail :: String -> m a
-- Minimal complete definition: (>>=), return
p >> q = p >>= \ _ -> q
fail s = error s
sequence :: Monad m => [m a] -> m [a]
sequence [] = return []
sequence (c:cs) = do x <- c
xs <- sequence cs
return (x:xs)
sequence_ :: Monad m => [m a] -> m ()
sequence_ = foldr (>>) (return ())
mapM :: Monad m => (a -> m b) -> [a] -> m [b]
mapM f = sequence . map f
mapM_ :: Monad m => (a -> m b) -> [a] -> m ()
mapM_ f = sequence_ . map f
(=<<) :: Monad m => (a -> m b) -> m a -> m b
f =<< x = x >>= f
-- Evaluation and strictness ------------------------------------------------
primitive seq :: a -> b -> b
primitive ($!) :: (a -> b) -> a -> b
-- f $! x = x `seq` f x
-- Trivial type -------------------------------------------------------------
data ( ) = ( ) deriving ( Eq , Ord , Ix , , Read , Show , Bounded )
instance Eq () where
() == () = True
instance Ord () where
compare () () = EQ
instance Ix () where
range ((),()) = [()]
index ((),()) () = 0
inRange ((),()) () = True
instance Enum () where
toEnum 0 = ()
fromEnum () = 0
enumFrom () = [()]
enumFromThen () () = [()]
instance Read () where
readsPrec p = readParen False (\r -> [((),t) | ("(",s) <- lex r,
(")",t) <- lex s ])
instance Show () where
showsPrec p () = showString "()"
instance Bounded () where
minBound = ()
maxBound = ()
Boolean type -------------------------------------------------------------
data Bool = False | True
deriving (Eq, Ord, Ix, Enum, Read, Show, Bounded)
(&&), (||) :: Bool -> Bool -> Bool
False && x = False
True && x = x
False || x = x
True || x = True
not :: Bool -> Bool
not True = False
not False = True
otherwise :: Bool
otherwise = True
-- Character type -----------------------------------------------------------
builtin datatype of ISO Latin characters
type String = [Char] -- strings are lists of characters
primitive primEqChar :: Char -> Char -> Bool
primitive primCmpChar :: Char -> Char -> Ordering
instance Eq Char where (==) = primEqChar
instance Ord Char where compare = primCmpChar
primitive primCharToInt :: Char -> Int
primitive primIntToChar :: Int -> Char
instance Enum Char where
toEnum = primIntToChar
fromEnum = primCharToInt
enumFrom c = map toEnum [fromEnum c .. fromEnum (maxBound::Char)]
enumFromThen c d = map toEnum [fromEnum c, fromEnum d .. fromEnum (lastChar::Char)]
where lastChar = if d < c then minBound else maxBound
instance Ix Char where
range (c,c') = [c..c']
index b@(c,c') ci
| inRange b ci = fromEnum ci - fromEnum c
| otherwise = error "Ix.index: Index out of range."
inRange (c,c') ci = fromEnum c <= i && i <= fromEnum c'
where i = fromEnum ci
instance Read Char where
readsPrec p = readParen False
(\r -> [(c,t) | ('\'':s,t) <- lex r,
(c,"\'") <- readLitChar s ])
readList = readParen False (\r -> [(l,t) | ('"':s, t) <- lex r,
(l,_) <- readl s ])
where readl ('"':s) = [("",s)]
readl ('\\':'&':s) = readl s
readl s = [(c:cs,u) | (c ,t) <- readLitChar s,
(cs,u) <- readl t ]
instance Show Char where
showsPrec p '\'' = showString "'\\''"
showsPrec p c = showChar '\'' . showLitChar c . showChar '\''
showList cs = showChar '"' . showl cs
where showl "" = showChar '"'
showl ('"':cs) = showString "\\\"" . showl cs
showl (c:cs) = showLitChar c . showl cs
instance Bounded Char where
minBound = 'a'
maxBound = 'z'
isAscii, isControl, isPrint, isSpace :: Char -> Bool
isUpper, isLower, isAlpha, isDigit, isAlphaNum :: Char -> Bool
isAscii c = fromEnum c < 128
isControl c = c < ' ' || c == '\DEL'
isPrint c = c >= ' ' && c <= '~'
isSpace c = c == ' ' || c == '\t' || c == '\n' ||
c == '\r' || c == '\f' || c == '\v'
isUpper c = c >= 'A' && c <= 'Z'
isLower c = c >= 'a' && c <= 'z'
isAlpha c = isUpper c || isLower c
isDigit c = c >= '0' && c <= '9'
isAlphaNum c = isAlpha c || isDigit c
Digit conversion operations
digitToInt :: Char -> Int
digitToInt c
| isDigit c = fromEnum c - fromEnum '0'
| c >= 'a' && c <= 'f' = fromEnum c - fromEnum 'a' + 10
| c >= 'A' && c <= 'F' = fromEnum c - fromEnum 'A' + 10
| otherwise = error "Char.digitToInt: not a digit"
intToDigit :: Int -> Char
intToDigit i
| i >= 0 && i <= 9 = toEnum (fromEnum '0' + i)
| i >= 10 && i <= 15 = toEnum (fromEnum 'a' + i - 10)
| otherwise = error "Char.intToDigit: not a digit"
toUpper, toLower :: Char -> Char
toUpper c | isLower c = toEnum (fromEnum c - fromEnum 'a' + fromEnum 'A')
| otherwise = c
toLower c | isUpper c = toEnum (fromEnum c - fromEnum 'A' + fromEnum 'a')
| otherwise = c
ord :: Char -> Int
ord = fromEnum
chr :: Int -> Char
chr = toEnum
-- Maybe type ---------------------------------------------------------------
data Maybe a = Nothing | Just a
deriving (Eq, Ord, Read, Show)
maybe :: b -> (a -> b) -> Maybe a -> b
maybe n f Nothing = n
maybe n f (Just x) = f x
instance Functor Maybe where
fmap f Nothing = Nothing
fmap f (Just x) = Just (f x)
instance Monad Maybe where
Just x >>= k = k x
Nothing >>= k = Nothing
return = Just
fail s = Nothing
-- Either type --------------------------------------------------------------
data Either a b = Left a | Right b
deriving (Eq, Ord, Read, Show)
either :: (a -> c) -> (b -> c) -> Either a b -> c
either l r (Left x) = l x
either l r (Right y) = r y
-- Ordering type ------------------------------------------------------------
data Ordering = LT | EQ | GT
deriving (Eq, Ord, Ix, Enum, Read, Show, Bounded)
-- Lists --------------------------------------------------------------------
data [ a ] = [ ] | a : [ a ] deriving ( Eq , Ord )
instance Eq a => Eq [a] where
[] == [] = True
(x:xs) == (y:ys) = x==y && xs==ys
_ == _ = False
instance Ord a => Ord [a] where
compare [] (_:_) = LT
compare [] [] = EQ
compare (_:_) [] = GT
compare (x:xs) (y:ys) = primCompAux x y (compare xs ys)
instance Functor [] where
fmap = map
instance Monad [ ] where
(x:xs) >>= f = f x ++ (xs >>= f)
[] >>= f = []
return x = [x]
fail s = []
instance Read a => Read [a] where
readsPrec p = readList
instance Show a => Show [a] where
showsPrec p = showList
Tuples -------------------------------------------------------------------
data ( a , b ) = ( a , b ) deriving ( Eq , Ord , Ix , Read , Show )
-- etc..
Standard Integral types --------------------------------------------------
data Int -- builtin datatype of fixed size integers
data Integer -- builtin datatype of arbitrary size integers
primitive primEqInt :: Int -> Int -> Bool
primitive primCmpInt :: Int -> Int -> Ordering
primitive primEqInteger :: Integer -> Integer -> Bool
primitive primCmpInteger :: Integer -> Integer -> Ordering
instance Eq Int where (==) = primEqInt
instance Eq Integer where (==) = primEqInteger
instance Ord Int where compare = primCmpInt
instance Ord Integer where compare = primCmpInteger
primitive primPlusInt :: Int -> Int -> Int
primitive primMinusInt :: Int -> Int -> Int
primitive primMulInt :: Int -> Int -> Int
primitive primNegInt :: Int -> Int
primitive primIntegerToInt :: Integer -> Int
instance Num Int where
(+) = primPlusInt
(-) = primMinusInt
negate = primNegInt
(*) = primMulInt
abs = absReal
signum = signumReal
fromInteger = primIntegerToInt
fromInt x = x
primitive primMinInt :: Int
primitive primMaxInt :: Int
instance Bounded Int where
minBound = primMinInt
maxBound = primMaxInt
primitive primPlusInteger :: Integer -> Integer -> Integer
primitive primMinusInteger :: Integer -> Integer -> Integer
primitive primMulInteger :: Integer -> Integer -> Integer
primitive primNegInteger :: Integer -> Integer
primitive primIntToInteger :: Int -> Integer
instance Num Integer where
(+) = primPlusInteger
(-) = primMinusInteger
negate = primNegInteger
(*) = primMulInteger
abs = absReal
signum = signumReal
fromInteger x = x
fromInt = primIntToInteger
absReal x | x >= 0 = x
| otherwise = -x
signumReal x | x == 0 = 0
| x > 0 = 1
| otherwise = -1
instance Real Int where
toRational x = toInteger x % 1
instance Real Integer where
toRational x = x % 1
primitive primDivInt :: Int -> Int -> Int
primitive primQuotInt :: Int -> Int -> Int
primitive primRemInt :: Int -> Int -> Int
primitive primModInt :: Int -> Int -> Int
primitive primQrmInt :: Int -> Int -> (Int,Int)
primitive primEvenInt :: Int -> Bool
instance Integral Int where
div = primDivInt
quot = primQuotInt
rem = primRemInt
mod = primModInt
quotRem = primQrmInt
even = primEvenInt
toInteger = primIntToInteger
toInt x = x
primitive primQrmInteger :: Integer -> Integer -> (Integer,Integer)
primitive primEvenInteger :: Integer -> Bool
instance Integral Integer where
quotRem = primQrmInteger
even = primEvenInteger
toInteger x = x
toInt = primIntegerToInt
instance Ix Int where
range (m,n) = [m..n]
index b@(m,n) i
| inRange b i = i - m
| otherwise = error "index: Index out of range"
inRange (m,n) i = m <= i && i <= n
instance Ix Integer where
range (m,n) = [m..n]
index b@(m,n) i
| inRange b i = fromInteger (i - m)
| otherwise = error "index: Index out of range"
inRange (m,n) i = m <= i && i <= n
instance Enum Int where
toEnum = id
fromEnum = id
enumFrom = numericEnumFrom
enumFromTo = numericEnumFromTo
enumFromThen = numericEnumFromThen
enumFromThenTo = numericEnumFromThenTo
instance Enum Integer where
toEnum = primIntToInteger
fromEnum = primIntegerToInt
enumFrom = numericEnumFrom
enumFromTo = numericEnumFromTo
enumFromThen = numericEnumFromThen
enumFromThenTo = numericEnumFromThenTo
numericEnumFrom :: Real a => a -> [a]
numericEnumFromThen :: Real a => a -> a -> [a]
numericEnumFromTo :: Real a => a -> a -> [a]
numericEnumFromThenTo :: Real a => a -> a -> a -> [a]
numericEnumFrom n = n : (numericEnumFrom $! (n+1))
numericEnumFromThen n m = iterate ((m-n)+) n
numericEnumFromTo n m = takeWhile (<= m) (numericEnumFrom n)
numericEnumFromThenTo n n' m = takeWhile p (numericEnumFromThen n n')
where p | n' >= n = (<= m)
| otherwise = (>= m)
primitive primShowsInt :: Int -> Int -> ShowS
instance Read Int where
readsPrec p = readSigned readDec
instance Show Int where
showsPrec = primShowsInt
primitive primShowsInteger :: Int -> Integer -> ShowS
instance Read Integer where
readsPrec p = readSigned readDec
instance Show Integer where
showsPrec = primShowsInteger
-- Standard Floating types --------------------------------------------------
data Float -- builtin datatype of single precision floating point numbers
data Double -- builtin datatype of double precision floating point numbers
primitive primEqFloat :: Float -> Float -> Bool
primitive primCmpFloat :: Float -> Float -> Ordering
primitive primEqDouble :: Double -> Double -> Bool
primitive primCmpDouble :: Double -> Double -> Ordering
instance Eq Float where (==) = primEqFloat
instance Eq Double where (==) = primEqDouble
instance Ord Float where compare = primCmpFloat
instance Ord Double where compare = primCmpDouble
primitive primPlusFloat :: Float -> Float -> Float
primitive primMinusFloat :: Float -> Float -> Float
primitive primMulFloat :: Float -> Float -> Float
primitive primNegFloat :: Float -> Float
primitive primIntToFloat :: Int -> Float
primitive primIntegerToFloat :: Integer -> Float
instance Num Float where
(+) = primPlusFloat
(-) = primMinusFloat
negate = primNegFloat
(*) = primMulFloat
abs = absReal
signum = signumReal
fromInteger = primIntegerToFloat
fromInt = primIntToFloat
primitive primPlusDouble :: Double -> Double -> Double
primitive primMinusDouble :: Double -> Double -> Double
primitive primMulDouble :: Double -> Double -> Double
primitive primNegDouble :: Double -> Double
primitive primIntToDouble :: Int -> Double
primitive primIntegerToDouble :: Integer -> Double
instance Num Double where
(+) = primPlusDouble
(-) = primMinusDouble
negate = primNegDouble
(*) = primMulDouble
abs = absReal
signum = signumReal
fromInteger = primIntegerToDouble
fromInt = primIntToDouble
instance Real Float where
toRational = floatToRational
instance Real Double where
toRational = doubleToRational
-- Calls to these functions are optimised when passed as arguments to
-- fromRational.
floatToRational :: Float -> Rational
doubleToRational :: Double -> Rational
floatToRational x = realFloatToRational x
doubleToRational x = realFloatToRational x
realFloatToRational x = (m%1)*(b%1)^^n
where (m,n) = decodeFloat x
b = floatRadix x
primitive primDivFloat :: Float -> Float -> Float
primitive doubleToFloat :: Double -> Float
instance Fractional Float where
(/) = primDivFloat
fromRational = primRationalToFloat
fromDouble = doubleToFloat
primitive primDivDouble :: Double -> Double -> Double
instance Fractional Double where
(/) = primDivDouble
fromRational = primRationalToDouble
fromDouble x = x
-- These primitives are equivalent to (and are defined using)
-- rationalTo{Float,Double}. The difference is that they test to see
-- if their argument is of the form (fromDouble x) - which allows a much
-- more efficient implementation.
primitive primRationalToFloat :: Rational -> Float
primitive primRationalToDouble :: Rational -> Double
-- These functions are used by Hugs - don't change their types.
rationalToFloat :: Rational -> Float
rationalToDouble :: Rational -> Double
rationalToFloat = rationalToRealFloat
rationalToDouble = rationalToRealFloat
rationalToRealFloat x = x'
where x' = f e
f e = if e' == e then y else f e'
where y = encodeFloat (round (x * (1%b)^^e)) e
(_,e') = decodeFloat y
(_,e) = decodeFloat (fromInteger (numerator x) `asTypeOf` x'
/ fromInteger (denominator x))
b = floatRadix x'
primitive primSinFloat :: Float -> Float
primitive primAsinFloat :: Float -> Float
primitive primCosFloat :: Float -> Float
primitive primAcosFloat :: Float -> Float
primitive primTanFloat :: Float -> Float
primitive primAtanFloat :: Float -> Float
primitive primLogFloat :: Float -> Float
primitive primExpFloat :: Float -> Float
primitive primSqrtFloat :: Float -> Float
instance Floating Float where
exp = primExpFloat
log = primLogFloat
sqrt = primSqrtFloat
sin = primSinFloat
cos = primCosFloat
tan = primTanFloat
asin = primAsinFloat
acos = primAcosFloat
atan = primAtanFloat
primitive primSinDouble :: Double -> Double
primitive primAsinDouble :: Double -> Double
primitive primCosDouble :: Double -> Double
primitive primAcosDouble :: Double -> Double
primitive primTanDouble :: Double -> Double
primitive primAtanDouble :: Double -> Double
primitive primLogDouble :: Double -> Double
primitive primExpDouble :: Double -> Double
primitive primSqrtDouble :: Double -> Double
instance Floating Double where
exp = primExpDouble
log = primLogDouble
sqrt = primSqrtDouble
sin = primSinDouble
cos = primCosDouble
tan = primTanDouble
asin = primAsinDouble
acos = primAcosDouble
atan = primAtanDouble
instance RealFrac Float where
properFraction = floatProperFraction
instance RealFrac Double where
properFraction = floatProperFraction
floatProperFraction x
| n >= 0 = (fromInteger m * fromInteger b ^ n, 0)
| otherwise = (fromInteger w, encodeFloat r n)
where (m,n) = decodeFloat x
b = floatRadix x
(w,r) = quotRem m (b^(-n))
primitive primFloatRadix :: Integer
primitive primFloatDigits :: Int
primitive primFloatMinExp :: Int
primitive primFloatMaxExp :: Int
primitive primFloatEncode :: Integer -> Int -> Float
primitive primFloatDecode :: Float -> (Integer, Int)
instance RealFloat Float where
floatRadix _ = primFloatRadix
floatDigits _ = primFloatDigits
floatRange _ = (primFloatMinExp, primFloatMaxExp)
encodeFloat = primFloatEncode
decodeFloat = primFloatDecode
isNaN _ = False
isInfinite _ = False
isDenormalized _ = False
isNegativeZero _ = False
isIEEE _ = False
primitive primDoubleRadix :: Integer
primitive primDoubleDigits :: Int
primitive primDoubleMinExp :: Int
primitive primDoubleMaxExp :: Int
primitive primDoubleEncode :: Integer -> Int -> Double
primitive primDoubleDecode :: Double -> (Integer, Int)
instance RealFloat Double where
floatRadix _ = primDoubleRadix
floatDigits _ = primDoubleDigits
floatRange _ = (primDoubleMinExp, primDoubleMaxExp)
encodeFloat = primDoubleEncode
decodeFloat = primDoubleDecode
isNaN _ = False
isInfinite _ = False
isDenormalized _ = False
isNegativeZero _ = False
isIEEE _ = False
instance Enum Float where
toEnum = primIntToFloat
fromEnum = truncate
enumFrom = numericEnumFrom
enumFromThen = numericEnumFromThen
enumFromTo n m = numericEnumFromTo n (m+1/2)
enumFromThenTo n n' m = numericEnumFromThenTo n n' (m + (n'-n)/2)
instance Enum Double where
toEnum = primIntToDouble
fromEnum = truncate
enumFrom = numericEnumFrom
enumFromThen = numericEnumFromThen
enumFromTo n m = numericEnumFromTo n (m+1/2)
enumFromThenTo n n' m = numericEnumFromThenTo n n' (m + (n'-n)/2)
primitive primShowsFloat :: Int -> Float -> ShowS
instance Read Float where
readsPrec p = readSigned readFloat
-- Note that showFloat in Numeric isn't used here
instance Show Float where
showsPrec = primShowsFloat
primitive primShowsDouble :: Int -> Double -> ShowS
instance Read Double where
readsPrec p = readSigned readFloat
-- Note that showFloat in Numeric isn't used here
instance Show Double where
showsPrec = primShowsDouble
-- Some standard functions --------------------------------------------------
fst :: (a,b) -> a
fst (x,_) = x
snd :: (a,b) -> b
snd (_,y) = y
curry :: ((a,b) -> c) -> (a -> b -> c)
curry f x y = f (x,y)
uncurry :: (a -> b -> c) -> ((a,b) -> c)
uncurry f p = f (fst p) (snd p)
id :: a -> a
id x = x
const :: a -> b -> a
const k _ = k
(.) :: (b -> c) -> (a -> b) -> (a -> c)
(f . g) x = f (g x)
flip :: (a -> b -> c) -> b -> a -> c
flip f x y = f y x
($) :: (a -> b) -> a -> b
f $ x = f x
until :: (a -> Bool) -> (a -> a) -> a -> a
until p f x = if p x then x else until p f (f x)
asTypeOf :: a -> a -> a
asTypeOf = const
primitive error :: String -> a
undefined :: a
undefined | False = undefined
-- Standard functions on rational numbers {PreludeRatio} --------------------
data (Integral a) => Ratio a = a :% a deriving (Eq)
type Rational = Ratio Integer
(%) :: Integral a => a -> a -> Ratio a
x % y = reduce (x * signum y) (abs y)
reduce :: Integral a => a -> a -> Ratio a
reduce x y | y == 0 = error "Ratio.%: zero denominator"
| otherwise = (x `quot` d) :% (y `quot` d)
where d = gcd x y
numerator, denominator :: Integral a => Ratio a -> a
numerator (x :% y) = x
denominator (x :% y) = y
instance Integral a => Ord (Ratio a) where
compare (x:%y) (x':%y') = compare (x*y') (x'*y)
instance Integral a => Num (Ratio a) where
(x:%y) + (x':%y') = reduce (x*y' + x'*y) (y*y')
(x:%y) * (x':%y') = reduce (x*x') (y*y')
negate (x :% y) = negate x :% y
abs (x :% y) = abs x :% y
signum (x :% y) = signum x :% 1
fromInteger x = fromInteger x :% 1
fromInt = intToRatio
-- Hugs optimises code of the form fromRational (intToRatio x)
intToRatio :: Integral a => Int -> Ratio a
intToRatio x = fromInt x :% 1
instance Integral a => Real (Ratio a) where
toRational (x:%y) = toInteger x :% toInteger y
instance Integral a => Fractional (Ratio a) where
(x:%y) / (x':%y') = (x*y') % (y*x')
recip (x:%y) = if x < 0 then (-y) :% (-x) else y :% x
fromRational (x:%y) = fromInteger x :% fromInteger y
fromDouble = doubleToRatio
-- Hugs optimises code of the form fromRational (doubleToRatio x)
doubleToRatio :: Integral a => Double -> Ratio a
doubleToRatio x
| n>=0 = (fromInteger m * fromInteger b ^ n) % 1
| otherwise = fromInteger m % (fromInteger b ^ (-n))
where (m,n) = decodeFloat x
b = floatRadix x
instance Integral a => RealFrac (Ratio a) where
properFraction (x:%y) = (fromIntegral q, r:%y)
where (q,r) = quotRem x y
instance Integral a => Enum (Ratio a) where
toEnum = fromInt
fromEnum = truncate
enumFrom = numericEnumFrom
enumFromThen = numericEnumFromThen
instance (Read a, Integral a) => Read (Ratio a) where
readsPrec p = readParen (p > 7)
(\r -> [(x%y,u) | (x,s) <- reads r,
("%",t) <- lex s,
(y,u) <- reads t ])
instance Integral a => Show (Ratio a) where
showsPrec p (x:%y) = showParen (p > 7)
(shows x . showString " % " . shows y)
approxRational :: RealFrac a => a -> a -> Rational
approxRational x eps = simplest (x-eps) (x+eps)
where simplest x y | y < x = simplest y x
| x == y = xr
| x > 0 = simplest' n d n' d'
| y < 0 = - simplest' (-n') d' (-n) d
| otherwise = 0 :% 1
where xr@(n:%d) = toRational x
(n':%d') = toRational y
simplest' n d n' d' -- assumes 0 < n%d < n'%d'
| r == 0 = q :% 1
| q /= q' = (q+1) :% 1
| otherwise = (q*n''+d'') :% n''
where (q,r) = quotRem n d
(q',r') = quotRem n' d'
(n'':%d'') = simplest' d' r' d r
Standard list functions { PreludeList } ------------------------------------
head :: [a] -> a
head (x:_) = x
last :: [a] -> a
last [x] = x
last (_:xs) = last xs
tail :: [a] -> [a]
tail (_:xs) = xs
init :: [a] -> [a]
init [x] = []
init (x:xs) = x : init xs
null :: [a] -> Bool
null [] = True
null (_:_) = False
(++) :: [a] -> [a] -> [a]
[] ++ ys = ys
(x:xs) ++ ys = x : (xs ++ ys)
map :: (a -> b) -> [a] -> [b]
map f xs = [ f x | x <- xs ]
filter :: (a -> Bool) -> [a] -> [a]
filter p xs = [ x | x <- xs, p x ]
concat :: [[a]] -> [a]
concat = foldr (++) []
length :: [a] -> Int
length = foldl' (\n _ -> n + 1) 0
(!!) :: [b] -> Int -> b
(x:_) !! 0 = x
(_:xs) !! n | n>0 = xs !! (n-1)
(_:_) !! _ = error "Prelude.!!: negative index"
[] !! _ = error "Prelude.!!: index too large"
foldl :: (a -> b -> a) -> a -> [b] -> a
foldl f z [] = z
foldl f z (x:xs) = foldl f (f z x) xs
foldl' :: (a -> b -> a) -> a -> [b] -> a
foldl' f a [] = a
foldl' f a (x:xs) = (foldl' f $! f a x) xs
foldl1 :: (a -> a -> a) -> [a] -> a
foldl1 f (x:xs) = foldl f x xs
scanl :: (a -> b -> a) -> a -> [b] -> [a]
scanl f q xs = q : (case xs of
[] -> []
x:xs -> scanl f (f q x) xs)
scanl1 :: (a -> a -> a) -> [a] -> [a]
scanl1 f (x:xs) = scanl f x xs
foldr :: (a -> b -> b) -> b -> [a] -> b
foldr f z [] = z
foldr f z (x:xs) = f x (foldr f z xs)
foldr1 :: (a -> a -> a) -> [a] -> a
foldr1 f [x] = x
foldr1 f (x:xs) = f x (foldr1 f xs)
scanr :: (a -> b -> b) -> b -> [a] -> [b]
scanr f q0 [] = [q0]
scanr f q0 (x:xs) = f x q : qs
where qs@(q:_) = scanr f q0 xs
scanr1 :: (a -> a -> a) -> [a] -> [a]
scanr1 f [x] = [x]
scanr1 f (x:xs) = f x q : qs
where qs@(q:_) = scanr1 f xs
iterate :: (a -> a) -> a -> [a]
iterate f x = x : iterate f (f x)
repeat :: a -> [a]
repeat x = xs where xs = x:xs
replicate :: Int -> a -> [a]
replicate n x = take n (repeat x)
cycle :: [a] -> [a]
cycle [] = error "Prelude.cycle: empty list"
cycle xs = xs' where xs'=xs++xs'
take :: Int -> [a] -> [a]
take 0 _ = []
take _ [] = []
take n (x:xs) | n>0 = x : take (n-1) xs
take _ _ = error "Prelude.take: negative argument"
drop :: Int -> [a] -> [a]
drop 0 xs = xs
drop _ [] = []
drop n (_:xs) | n>0 = drop (n-1) xs
drop _ _ = error "Prelude.drop: negative argument"
splitAt :: Int -> [a] -> ([a], [a])
splitAt 0 xs = ([],xs)
splitAt _ [] = ([],[])
splitAt n (x:xs) | n>0 = (x:xs',xs'') where (xs',xs'') = splitAt (n-1) xs
splitAt _ _ = error "Prelude.splitAt: negative argument"
takeWhile :: (a -> Bool) -> [a] -> [a]
takeWhile p [] = []
takeWhile p (x:xs)
| p x = x : takeWhile p xs
| otherwise = []
dropWhile :: (a -> Bool) -> [a] -> [a]
dropWhile p [] = []
dropWhile p xs@(x:xs')
| p x = dropWhile p xs'
| otherwise = xs
span, break :: (a -> Bool) -> [a] -> ([a],[a])
span p [] = ([],[])
span p xs@(x:xs')
| p x = (x:ys, zs)
| otherwise = ([],xs)
where (ys,zs) = span p xs'
break p = span (not . p)
lines :: String -> [String]
lines "" = []
lines s = let (l,s') = break ('\n'==) s
in l : case s' of [] -> []
(_:s'') -> lines s''
words :: String -> [String]
words s = case dropWhile isSpace s of
"" -> []
s' -> w : words s''
where (w,s'') = break isSpace s'
unlines :: [String] -> String
unlines = concatMap (\l -> l ++ "\n")
unwords :: [String] -> String
unwords [] = []
unwords ws = foldr1 (\w s -> w ++ ' ':s) ws
reverse :: [a] -> [a]
reverse = foldl (flip (:)) []
and, or :: [Bool] -> Bool
and = foldr (&&) True
or = foldr (||) False
any, all :: (a -> Bool) -> [a] -> Bool
any p = or . map p
all p = and . map p
elem, notElem :: Eq a => a -> [a] -> Bool
elem = any . (==)
notElem = all . (/=)
lookup :: Eq a => a -> [(a,b)] -> Maybe b
lookup k [] = Nothing
lookup k ((x,y):xys)
| k==x = Just y
| otherwise = lookup k xys
sum, product :: Num a => [a] -> a
sum = foldl' (+) 0
product = foldl' (*) 1
maximum, minimum :: Ord a => [a] -> a
maximum = foldl1 max
minimum = foldl1 min
concatMap :: (a -> [b]) -> [a] -> [b]
concatMap f = concat . map f
zip :: [a] -> [b] -> [(a,b)]
zip = zipWith (\a b -> (a,b))
zip3 :: [a] -> [b] -> [c] -> [(a,b,c)]
zip3 = zipWith3 (\a b c -> (a,b,c))
zipWith :: (a->b->c) -> [a]->[b]->[c]
zipWith z (a:as) (b:bs) = z a b : zipWith z as bs
zipWith _ _ _ = []
zipWith3 :: (a->b->c->d) -> [a]->[b]->[c]->[d]
zipWith3 z (a:as) (b:bs) (c:cs)
= z a b c : zipWith3 z as bs cs
zipWith3 _ _ _ _ = []
unzip :: [(a,b)] -> ([a],[b])
unzip = foldr (\(a,b) ~(as,bs) -> (a:as, b:bs)) ([], [])
unzip3 :: [(a,b,c)] -> ([a],[b],[c])
unzip3 = foldr (\(a,b,c) ~(as,bs,cs) -> (a:as,b:bs,c:cs))
([],[],[])
PreludeText ----------------------------------------------------------------
reads :: Read a => ReadS a
reads = readsPrec 0
shows :: Show a => a -> ShowS
shows = showsPrec 0
read :: Read a => String -> a
read s = case [x | (x,t) <- reads s, ("","") <- lex t] of
[x] -> x
[] -> error "Prelude.read: no parse"
_ -> error "Prelude.read: ambiguous parse"
showChar :: Char -> ShowS
showChar = (:)
showString :: String -> ShowS
showString = (++)
showParen :: Bool -> ShowS -> ShowS
showParen b p = if b then showChar '(' . p . showChar ')' else p
showField :: Show a => String -> a -> ShowS
showField m v = showString m . showChar '=' . shows v
readParen :: Bool -> ReadS a -> ReadS a
readParen b g = if b then mandatory else optional
where optional r = g r ++ mandatory r
mandatory r = [(x,u) | ("(",s) <- lex r,
(x,t) <- optional s,
(")",u) <- lex t ]
readField :: Read a => String -> ReadS a
readField m s0 = [ r | (t, s1) <- lex s0, t == m,
("=",s2) <- lex s1,
r <- reads s2 ]
lex :: ReadS String
lex "" = [("","")]
lex (c:s) | isSpace c = lex (dropWhile isSpace s)
lex ('\'':s) = [('\'':ch++"'", t) | (ch,'\'':t) <- lexLitChar s,
ch /= "'" ]
lex ('"':s) = [('"':str, t) | (str,t) <- lexString s]
where
lexString ('"':s) = [("\"",s)]
lexString s = [(ch++str, u)
| (ch,t) <- lexStrItem s,
(str,u) <- lexString t ]
lexStrItem ('\\':'&':s) = [("\\&",s)]
lexStrItem ('\\':c:s) | isSpace c
= [("",t) | '\\':t <- [dropWhile isSpace s]]
lexStrItem s = lexLitChar s
lex (c:s) | isSingle c = [([c],s)]
| isSym c = [(c:sym,t) | (sym,t) <- [span isSym s]]
| isAlpha c = [(c:nam,t) | (nam,t) <- [span isIdChar s]]
| isDigit c = [(c:ds++fe,t) | (ds,s) <- [span isDigit s],
(fe,t) <- lexFracExp s ]
| otherwise = [] -- bad character
where
isSingle c = c `elem` ",;()[]{}_`"
isSym c = c `elem` "!@#$%&*+./<=>?\\^|:-~"
isIdChar c = isAlphaNum c || c `elem` "_'"
lexFracExp ('.':s) = [('.':ds++e,u) | (ds,t) <- lexDigits s,
(e,u) <- lexExp t ]
lexFracExp s = [("",s)]
lexExp (e:s) | e `elem` "eE"
= [(e:c:ds,u) | (c:t) <- [s], c `elem` "+-",
(ds,u) <- lexDigits t] ++
[(e:ds,t) | (ds,t) <- lexDigits s]
lexExp s = [("",s)]
lexDigits :: ReadS String
lexDigits = nonnull isDigit
nonnull :: (Char -> Bool) -> ReadS String
nonnull p s = [(cs,t) | (cs@(_:_),t) <- [span p s]]
lexLitChar :: ReadS String
lexLitChar ('\\':s) = [('\\':esc, t) | (esc,t) <- lexEsc s]
where
lexEsc (c:s) | c `elem` "abfnrtv\\\"'" = [([c],s)]
lexEsc ('^':c:s) | c >= '@' && c <= '_' = [(['^',c],s)]
lexEsc s@(d:_) | isDigit d = lexDigits s
lexEsc s@(c:_) | isUpper c
= let table = ('\DEL',"DEL") : asciiTab
in case [(mne,s') | (c, mne) <- table,
([],s') <- [lexmatch mne s]]
of (pr:_) -> [pr]
[] -> []
lexEsc _ = []
lexLitChar (c:s) = [([c],s)]
lexLitChar "" = []
isOctDigit c = c >= '0' && c <= '7'
isHexDigit c = isDigit c || c >= 'A' && c <= 'F'
|| c >= 'a' && c <= 'f'
lexmatch :: (Eq a) => [a] -> [a] -> ([a],[a])
lexmatch (x:xs) (y:ys) | x == y = lexmatch xs ys
lexmatch xs ys = (xs,ys)
asciiTab = zip ['\NUL'..' ']
["NUL", "SOH", "STX", "ETX", "EOT", "ENQ", "ACK", "BEL",
"BS", "HT", "LF", "VT", "FF", "CR", "SO", "SI",
"DLE", "DC1", "DC2", "DC3", "DC4", "NAK", "SYN", "ETB",
"CAN", "EM", "SUB", "ESC", "FS", "GS", "RS", "US",
"SP"]
readLitChar :: ReadS Char
readLitChar ('\\':s) = readEsc s
where
readEsc ('a':s) = [('\a',s)]
readEsc ('b':s) = [('\b',s)]
readEsc ('f':s) = [('\f',s)]
readEsc ('n':s) = [('\n',s)]
readEsc ('r':s) = [('\r',s)]
readEsc ('t':s) = [('\t',s)]
readEsc ('v':s) = [('\v',s)]
readEsc ('\\':s) = [('\\',s)]
readEsc ('"':s) = [('"',s)]
readEsc ('\'':s) = [('\'',s)]
readEsc ('^':c:s) | c >= '@' && c <= '_'
= [(toEnum (fromEnum c - fromEnum '@'), s)]
readEsc s@(d:_) | isDigit d
= [(toEnum n, t) | (n,t) <- readDec s]
readEsc ('o':s) = [(toEnum n, t) | (n,t) <- readOct s]
readEsc ('x':s) = [(toEnum n, t) | (n,t) <- readHex s]
readEsc s@(c:_) | isUpper c
= let table = ('\DEL',"DEL") : asciiTab
in case [(c,s') | (c, mne) <- table,
([],s') <- [lexmatch mne s]]
of (pr:_) -> [pr]
[] -> []
readEsc _ = []
readLitChar (c:s) = [(c,s)]
showLitChar :: Char -> ShowS
showLitChar c | c > '\DEL' = showChar '\\' .
protectEsc isDigit (shows (fromEnum c))
showLitChar '\DEL' = showString "\\DEL"
showLitChar '\\' = showString "\\\\"
showLitChar c | c >= ' ' = showChar c
showLitChar '\a' = showString "\\a"
showLitChar '\b' = showString "\\b"
showLitChar '\f' = showString "\\f"
showLitChar '\n' = showString "\\n"
showLitChar '\r' = showString "\\r"
showLitChar '\t' = showString "\\t"
showLitChar '\v' = showString "\\v"
showLitChar '\SO' = protectEsc ('H'==) (showString "\\SO")
showLitChar c = showString ('\\' : snd (asciiTab!!fromEnum c))
protectEsc p f = f . cont
where cont s@(c:_) | p c = "\\&" ++ s
cont s = s
-- Unsigned readers for various bases
readDec, readOct, readHex :: Integral a => ReadS a
readDec = readInt 10 isDigit (\d -> fromEnum d - fromEnum '0')
readOct = readInt 8 isOctDigit (\d -> fromEnum d - fromEnum '0')
readHex = readInt 16 isHexDigit hex
where hex d = fromEnum d -
(if isDigit d
then fromEnum '0'
else fromEnum (if isUpper d then 'A' else 'a') - 10)
-- readInt reads a string of digits using an arbitrary base.
-- Leading minus signs must be handled elsewhere.
readInt :: Integral a => a -> (Char -> Bool) -> (Char -> Int) -> ReadS a
readInt radix isDig digToInt s =
[(foldl1 (\n d -> n * radix + d) (map (fromIntegral . digToInt) ds), r)
| (ds,r) <- nonnull isDig s ]
-- showInt is used for positive numbers only
showInt :: Integral a => a -> ShowS
showInt n r | n < 0 = error "Numeric.showInt: can't show negative numbers"
| otherwise =
let (n',d) = quotRem n 10
r' = toEnum (fromEnum '0' + fromIntegral d) : r
in if n' == 0 then r' else showInt n' r'
readSigned:: Real a => ReadS a -> ReadS a
readSigned readPos = readParen False read'
where read' r = read'' r ++
[(-x,t) | ("-",s) <- lex r,
(x,t) <- read'' s]
read'' r = [(n,s) | (str,s) <- lex r,
(n,"") <- readPos str]
showSigned :: Real a => (a -> ShowS) -> Int -> a -> ShowS
showSigned showPos p x = if x < 0 then showParen (p > 6)
(showChar '-' . showPos (-x))
else showPos x
readFloat :: RealFloat a => ReadS a
readFloat r = [(fromRational ((n%1)*10^^(k-d)),t) | (n,d,s) <- readFix r,
(k,t) <- readExp s]
where readFix r = [(read (ds++ds'), length ds', t)
| (ds, s) <- lexDigits r
, (ds',t) <- lexFrac s ]
lexFrac ('.':s) = lexDigits s
lexFrac s = [("",s)]
readExp (e:s) | e `elem` "eE" = readExp' s
readExp s = [(0,s)]
readExp' ('-':s) = [(-k,t) | (k,t) <- readDec s]
readExp' ('+':s) = readDec s
readExp' s = readDec s
-- Monadic I/O: --------------------------------------------------------------
data IO a -- builtin datatype of IO actions
builtin datatype of IO error codes
type FilePath = String -- file pathnames are represented by strings
instance Show (IO a) where
showsPrec p f = showString "<<IO action>>"
primitive primbindIO :: IO a -> (a -> IO b) -> IO b
primitive primretIO :: a -> IO a
primitive catch :: IO a -> (IOError -> IO a) -> IO a
primitive ioError :: IOError -> IO a
primitive putChar :: Char -> IO ()
primitive putStr :: String -> IO ()
primitive getChar :: IO Char
primitive userError :: String -> IOError
print :: Show a => a -> IO ()
print = putStrLn . show
putStrLn :: String -> IO ()
putStrLn s = do putStr s
putChar '\n'
getLine :: IO String
getLine = do c <- getChar
if c=='\n' then return ""
else do cs <- getLine
return (c:cs)
-- raises an exception instead of an error
readIO :: Read a => String -> IO a
readIO s = case [x | (x,t) <- reads s, ("","") <- lex t] of
[x] -> return x
[] -> ioError (userError "PreludeIO.readIO: no parse")
_ -> ioError (userError
"PreludeIO.readIO: ambiguous parse")
readLn :: Read a => IO a
readLn = do l <- getLine
r <- readIO l
return r
primitive getContents :: IO String
primitive writeFile :: FilePath -> String -> IO ()
primitive appendFile :: FilePath -> String -> IO ()
primitive readFile :: FilePath -> IO String
interact :: (String -> String) -> IO ()
interact f = getContents >>= (putStr . f)
instance Functor IO where
fmap f x = x >>= (return . f)
instance Monad IO where
(>>=) = primbindIO
return = primretIO
-- Hooks for primitives: -----------------------------------------------------
-- Do not mess with these!
data Addr -- builtin datatype of C pointers
newtype IO a = IO ((IOError -> IOResult a) -> (a -> IOResult a) -> IOResult a)
data IOResult a
= Hugs_ExitWith Int
| Hugs_SuspendThread
| Hugs_Error IOError
| Hugs_Return a
hugsPutStr :: String -> IO ()
hugsPutStr = putStr
hugsIORun :: IO a -> Either Int a
hugsIORun m = performIO (runAndShowError m)
where
performIO :: IO a -> Either Int a
performIO (IO m) = case m Hugs_Error Hugs_Return of
Hugs_Return a -> Right a
Hugs_ExitWith e -> Left e
_ -> Left 1
runAndShowError :: IO a -> IO a
runAndShowError m =
m `catch` \err -> do
putChar '\n'
putStr (ioeGetErrorString err)
primExitWith 1 -- alternatively: (IO (\f s -> Hugs_SuspendThread))
primExitWith :: Int -> IO a
primExitWith c = IO (\ f s -> Hugs_ExitWith c)
primitive ioeGetErrorString :: IOError -> String
instance Show IOError where
showsPrec p x = showString (ioeGetErrorString x)
primCompAux :: Ord a => a -> a -> Ordering -> Ordering
primCompAux x y o = case compare x y of EQ -> o; LT -> LT; GT -> GT
primPmInt :: Num a => Int -> a -> Bool
primPmInt n x = fromInt n == x
primPmInteger :: Num a => Integer -> a -> Bool
primPmInteger n x = fromInteger n == x
primPmFlt :: Fractional a => Double -> a -> Bool
primPmFlt n x = fromDouble n == x
-- The following primitives are only needed if (n+k) patterns are enabled:
primPmNpk :: Integral a => Int -> a -> Maybe a
primPmNpk n x = if n'<=x then Just (x-n') else Nothing
where n' = fromInt n
primPmSub :: Integral a => Int -> a -> a
primPmSub n x = x - fromInt n
End of Hugs standard prelude ----------------------------------------------
| null |
https://raw.githubusercontent.com/RefactoringTools/HaRe/ef5dee64c38fb104e6e5676095946279fbce381c/old/tools/base/tests/prelude/Prelude.hs
|
haskell
|
-------------------------------------------------------------------------
-|| _ _ _ || World Wide Web :
---------------------------------------------------------------------------
-------------------------------------------------------------------------
-|| ___|| World Wide Web:
---------------------------------------------------------------------------
--------------------------------------------------------------------------}
module PreludeList ,
module PreludeText ,
module PreludeIO ,
module Ix ,
module ,
module Numeric
module Ratio ,
Non - standard exports
List type : [ ] ( (: ) , [ ] )
( :) ,
Tuple types : ( , ) , ( , , ) , etc .
Trivial type : ( )
Functions : ( - > )
non - standard , should only be exported if TREX
Num((+ ) , ( - ) , ( * ) , negate , abs , signum , fromInteger ) ,
Integral(quot , rem , div , mod , quotRem , divMod , toInteger ) ,
) , recip , fromRational ) ,
module PreludeList,
module PreludeText,
module PreludeIO,
module Ix,
module Char,
module Numeric
module Ratio,
Non-standard exports
List type: []((:), [])
(:),
Tuple types: (,), (,,), etc.
Trivial type: ()
Functions: (->)
non-standard, should only be exported if TREX
Num((+), (-), (*), negate, abs, signum, fromInteger),
Integral(quot, rem, div, mod, quotRem, divMod, toInteger),
Fractional((/), recip, fromRational),
Standard value bindings {Prelude} ----------------------------------------
this fixity declaration is hard - wired into Hugs
Equality and Ordered classes ---------------------------------------------
Minimal complete definition: (==) or (/=)
Minimal complete definition: (<=) or compare
using compare can be more efficient for complex types
Minimal complete definition: All
Numeric classes ----------------------------------------------------------
Minimal complete definition: All, except negate or (-)
Minimal complete definition: quotRem and toInteger
Minimal complete definition: fromRational and ((/) or recip)
Minimal complete definition: properFraction
Minimal complete definition: All, except exponent, signficand,
Numeric functions --------------------------------------------------------
Index and Enumeration classes --------------------------------------------
[n..]
[n,m..]
[n..m]
[n,n'..m]
Minimal complete definition: toEnum, fromEnum
Read and Show classes ------------------------------------------------------
Minimal complete definition: readsPrec
Minimal complete definition: show or showsPrec
----------------------------------------------------------
Minimal complete definition: (>>=), return
Evaluation and strictness ------------------------------------------------
f $! x = x `seq` f x
Trivial type -------------------------------------------------------------
-----------------------------------------------------------
Character type -----------------------------------------------------------
strings are lists of characters
Maybe type ---------------------------------------------------------------
Either type --------------------------------------------------------------
Ordering type ------------------------------------------------------------
Lists --------------------------------------------------------------------
-----------------------------------------------------------------
etc..
------------------------------------------------
builtin datatype of fixed size integers
builtin datatype of arbitrary size integers
Standard Floating types --------------------------------------------------
builtin datatype of single precision floating point numbers
builtin datatype of double precision floating point numbers
Calls to these functions are optimised when passed as arguments to
fromRational.
These primitives are equivalent to (and are defined using)
rationalTo{Float,Double}. The difference is that they test to see
if their argument is of the form (fromDouble x) - which allows a much
more efficient implementation.
These functions are used by Hugs - don't change their types.
Note that showFloat in Numeric isn't used here
Note that showFloat in Numeric isn't used here
Some standard functions --------------------------------------------------
Standard functions on rational numbers {PreludeRatio} --------------------
Hugs optimises code of the form fromRational (intToRatio x)
Hugs optimises code of the form fromRational (doubleToRatio x)
assumes 0 < n%d < n'%d'
----------------------------------
--------------------------------------------------------------
bad character
Unsigned readers for various bases
readInt reads a string of digits using an arbitrary base.
Leading minus signs must be handled elsewhere.
showInt is used for positive numbers only
Monadic I/O: --------------------------------------------------------------
builtin datatype of IO actions
file pathnames are represented by strings
raises an exception instead of an error
Hooks for primitives: -----------------------------------------------------
Do not mess with these!
builtin datatype of C pointers
alternatively: (IO (\f s -> Hugs_SuspendThread))
The following primitives are only needed if (n+k) patterns are enabled:
--------------------------------------------
|
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
|| || || || || || || _ _ Hugs 98 : The Nottingham and Yale Haskell system
||___|| ||__|| ||__|| _ _ || Copyright ( c ) 1994 - 1999
|| || Report bugs to :
|| || Version : February 1999 _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
This is the Hugs 98 Standard Prelude , based very closely on the Standard
Prelude for 98 .
WARNING : This file is an integral part of the Hugs source code . Changes to
the definitions in this file without corresponding modifications in other
parts of the program may cause the interpreter to fail unexpectedly . Under
normal circumstances , you should not attempt to modify this file in any way !
The Hugs 98 system is Copyright ( c ) , , the
Yale Haskell Group , and the Oregon Graduate Institute of Science and
Technology , 1994 - 1999 , All rights reserved . It is distributed as
free software under the license in the file " License " , which is
included in the distribution .
__ __ __ __ ____ ___ _______________________________________________
|| || || || || || ||__ Hugs 98: The Nottingham and Yale Haskell system
||___|| ||__|| ||__|| __|| Copyright (c) 1994-1999
|| || Report bugs to:
|| || Version: February 1999_______________________________________________
This is the Hugs 98 Standard Prelude, based very closely on the Standard
Prelude for Haskell 98.
WARNING: This file is an integral part of the Hugs source code. Changes to
the definitions in this file without corresponding modifications in other
parts of the program may cause the interpreter to fail unexpectedly. Under
normal circumstances, you should not attempt to modify this file in any way!
The Hugs 98 system is Copyright (c) Mark P Jones, Alastair Reid, the
Yale Haskell Group, and the Oregon Graduate Institute of Science and
Technology, 1994-1999, All rights reserved. It is distributed as
free software under the license in the file "License", which is
included in the distribution.
(
map , ( + + ) , concat , filter ,
head , last , tail , init , null , length , ( ! ! ) ,
foldl , foldl1 , , scanl1 , foldr , foldr1 , , scanr1 ,
iterate , repeat , replicate , cycle ,
take , drop , splitAt , takeWhile , dropWhile , span , break ,
lines , words , unlines , unwords , reverse , and , or ,
any , all , elem , notElem , lookup ,
sum , product , maximum , minimum , concatMap ,
zip , zip3 , zipWith , zipWith3 , unzip , unzip3 ,
ReadS , ,
Read(readsPrec , readList ) ,
Show(show , showsPrec , showList ) ,
reads , shows , read , lex ,
showChar , showString , readParen , showParen ,
FilePath , IOError , ioError , userError , catch ,
putChar , putStr , putStrLn , print ,
getChar , getLine , getContents , interact ,
readFile , writeFile , appendFile , readIO , readLn ,
Ix(range , index , inRange , rangeSize ) ,
isAscii , isControl , isPrint , isSpace , isUpper , isLower ,
isAlpha , isDigit , isOctDigit , isHexDigit , isAlphaNum ,
digitToInt , intToDigit ,
toUpper , toLower ,
ord , chr ,
readLitChar , , lexLitChar ,
showSigned , showInt ,
readSigned , readInt ,
readDec , readOct , readHex , readSigned ,
readFloat , lexDigits ,
Ratio , Rational , ( % ) , numerator , denominator , approxRational ,
IO ( .. ) , ( .. ) , primExitWith , ,
Bool(False , True ) ,
Maybe(Nothing , Just ) ,
Either(Left , Right ) ,
Ordering(LT , EQ , GT ) ,
Char , String , Int , Integer , Float , Double , IO ,
Eq((== ) , ( /= ) ) ,
Ord(compare , ( < ) , ( < =) , ( > =) , ( > ) , , min ) ,
, pred , toEnum , fromEnum , enumFrom , enumFromThen ,
enumFromTo , enumFromThenTo ) ,
Bounded(minBound , maxBound ) ,
Num((+ ) , ( - ) , ( * ) , negate , abs , signum , fromInteger , fromInt ) ,
Real(toRational ) ,
Integral(quot , rem , div , mod , quotRem , divMod , even , odd , toInteger , toInt ) ,
) , recip , fromRational , fromDouble ) ,
Floating(pi , exp , log , sqrt , ( * * ) , logBase , sin , cos , tan ,
asin , acos , atan , sinh , , tanh , asinh , acosh , atanh ) ,
RealFrac(properFraction , truncate , round , ceiling , floor ) ,
RealFloat(floatRadix , floatDigits , floatRange , decodeFloat ,
encodeFloat , exponent , significand , scaleFloat , isNaN ,
isInfinite , isDenormalized , isIEEE , isNegativeZero , atan2 ) ,
Monad((>>= ) , ( > > ) , return , fail ) ,
Functor(fmap ) ,
mapM , mapM _ , sequence , sequence _ , (= < < ) ,
maybe , either ,
( & & ) , ( || ) , not , otherwise ,
subtract , even , odd , gcd , lcm , ( ^ ) , ( ^^ ) ,
fromIntegral , realToFrac ,
fst , snd , curry , uncurry , i d , const , ( . ) , flip , ( $ ) , until ,
asTypeOf , error , undefined ,
seq , ( $ ! )
)
map, (++), concat, filter,
head, last, tail, init, null, length, (!!),
foldl, foldl1, scanl, scanl1, foldr, foldr1, scanr, scanr1,
iterate, repeat, replicate, cycle,
take, drop, splitAt, takeWhile, dropWhile, span, break,
lines, words, unlines, unwords, reverse, and, or,
any, all, elem, notElem, lookup,
sum, product, maximum, minimum, concatMap,
zip, zip3, zipWith, zipWith3, unzip, unzip3,
ReadS, ShowS,
Read(readsPrec, readList),
Show(show, showsPrec, showList),
reads, shows, read, lex,
showChar, showString, readParen, showParen,
FilePath, IOError, ioError, userError, catch,
putChar, putStr, putStrLn, print,
getChar, getLine, getContents, interact,
readFile, writeFile, appendFile, readIO, readLn,
Ix(range, index, inRange, rangeSize),
isAscii, isControl, isPrint, isSpace, isUpper, isLower,
isAlpha, isDigit, isOctDigit, isHexDigit, isAlphaNum,
digitToInt, intToDigit,
toUpper, toLower,
ord, chr,
readLitChar, showLitChar, lexLitChar,
showSigned, showInt,
readSigned, readInt,
readDec, readOct, readHex, readSigned,
readFloat, lexDigits,
Ratio, Rational, (%), numerator, denominator, approxRational,
IO(..), IOResult(..), primExitWith, Addr,
Bool(False, True),
Maybe(Nothing, Just),
Either(Left, Right),
Ordering(LT, EQ, GT),
Char, String, Int, Integer, Float, Double, IO,
Eq((==), (/=)),
Ord(compare, (<), (<=), (>=), (>), max, min),
Enum(succ, pred, toEnum, fromEnum, enumFrom, enumFromThen,
enumFromTo, enumFromThenTo),
Bounded(minBound, maxBound),
Num((+), (-), (*), negate, abs, signum, fromInteger, fromInt),
Real(toRational),
Integral(quot, rem, div, mod, quotRem, divMod, even, odd, toInteger, toInt),
Fractional((/), recip, fromRational, fromDouble),
Floating(pi, exp, log, sqrt, (**), logBase, sin, cos, tan,
asin, acos, atan, sinh, cosh, tanh, asinh, acosh, atanh),
RealFrac(properFraction, truncate, round, ceiling, floor),
RealFloat(floatRadix, floatDigits, floatRange, decodeFloat,
encodeFloat, exponent, significand, scaleFloat, isNaN,
isInfinite, isDenormalized, isIEEE, isNegativeZero, atan2),
Monad((>>=), (>>), return, fail),
Functor(fmap),
mapM, mapM_, sequence, sequence_, (=<<),
maybe, either,
(&&), (||), not, otherwise,
subtract, even, odd, gcd, lcm, (^), (^^),
fromIntegral, realToFrac,
fst, snd, curry, uncurry, id, const, (.), flip, ($), until,
asTypeOf, error, undefined,
seq, ($!)
) -} where
infixr 9 .
infixl 9 !!
infixr 8 ^, ^^, **
infixl 7 *, /, `quot`, `rem`, `div`, `mod`, :%, %
infixl 6 +, -
infixr 5 ++
infix 4 ==, /=, <, <=, >=, >, `elem`, `notElem`
infixr 3 &&
infixr 2 ||
infixl 1 >>, >>=
infixr 1 =<<
infixr 0 $, $!, `seq`
class Eq a where
(==), (/=) :: a -> a -> Bool
x == y = not (x/=y)
x /= y = not (x==y)
class (Eq a) => Ord a where
compare :: a -> a -> Ordering
(<), (<=), (>=), (>) :: a -> a -> Bool
max, min :: a -> a -> a
compare x y | x==y = EQ
| x<=y = LT
| otherwise = GT
x <= y = compare x y /= GT
x < y = compare x y == LT
x >= y = compare x y /= LT
x > y = compare x y == GT
max x y | x >= y = x
| otherwise = y
min x y | x <= y = x
| otherwise = y
class Bounded a where
minBound, maxBound :: a
class (Eq a, Show a) => Num a where
(+), (-), (*) :: a -> a -> a
negate :: a -> a
abs, signum :: a -> a
fromInteger :: Integer -> a
fromInt :: Int -> a
x - y = x + negate y
fromInt = fromIntegral
negate x = 0 - x
class (Num a, Ord a) => Real a where
toRational :: a -> Rational
class (Real a, Enum a) => Integral a where
quot, rem, div, mod :: a -> a -> a
quotRem, divMod :: a -> a -> (a,a)
even, odd :: a -> Bool
toInteger :: a -> Integer
toInt :: a -> Int
n `quot` d = q where (q,r) = quotRem n d
n `rem` d = r where (q,r) = quotRem n d
n `div` d = q where (q,r) = divMod n d
n `mod` d = r where (q,r) = divMod n d
divMod n d = if signum r == - signum d then (q-1, r+d) else qr
where qr@(q,r) = quotRem n d
even n = n `rem` 2 == 0
odd = not . even
toInt = toInt . toInteger
class (Num a) => Fractional a where
(/) :: a -> a -> a
recip :: a -> a
fromRational :: Rational -> a
fromDouble :: Double -> a
recip x = 1 / x
fromDouble = fromRational . toRational
x / y = x * recip y
class (Fractional a) => Floating a where
pi :: a
exp, log, sqrt :: a -> a
(**), logBase :: a -> a -> a
sin, cos, tan :: a -> a
asin, acos, atan :: a -> a
sinh, cosh, tanh :: a -> a
asinh, acosh, atanh :: a -> a
Minimal complete definition : pi , exp , log , sin , cos , sinh , cosh ,
asinh , acosh , atanh
pi = 4 * atan 1
x ** y = exp (log x * y)
logBase x y = log y / log x
sqrt x = x ** 0.5
tan x = sin x / cos x
sinh x = (exp x - exp (-x)) / 2
cosh x = (exp x + exp (-x)) / 2
tanh x = sinh x / cosh x
asinh x = log (x + sqrt (x*x + 1))
acosh x = log (x + sqrt (x*x - 1))
atanh x = (log (1 + x) - log (1 - x)) / 2
class (Real a, Fractional a) => RealFrac a where
properFraction :: (Integral b) => a -> (b,a)
truncate, round :: (Integral b) => a -> b
ceiling, floor :: (Integral b) => a -> b
truncate x = m where (m,_) = properFraction x
round x = let (n,r) = properFraction x
m = if r < 0 then n - 1 else n + 1
in case signum (abs r - 0.5) of
-1 -> n
0 -> if even n then n else m
1 -> m
ceiling x = if r > 0 then n + 1 else n
where (n,r) = properFraction x
floor x = if r < 0 then n - 1 else n
where (n,r) = properFraction x
class (RealFrac a, Floating a) => RealFloat a where
floatRadix :: a -> Integer
floatDigits :: a -> Int
floatRange :: a -> (Int,Int)
decodeFloat :: a -> (Integer,Int)
encodeFloat :: Integer -> Int -> a
exponent :: a -> Int
significand :: a -> a
scaleFloat :: Int -> a -> a
isNaN, isInfinite, isDenormalized, isNegativeZero, isIEEE
:: a -> Bool
atan2 :: a -> a -> a
scaleFloat , atan2
exponent x = if m==0 then 0 else n + floatDigits x
where (m,n) = decodeFloat x
significand x = encodeFloat m (- floatDigits x)
where (m,_) = decodeFloat x
scaleFloat k x = encodeFloat m (n+k)
where (m,n) = decodeFloat x
atan2 y x
| x>0 = atan (y/x)
| x==0 && y>0 = pi/2
| x<0 && y>0 = pi + atan (y/x)
| (x<=0 && y<0) ||
(x<0 && isNegativeZero y) ||
(isNegativeZero x && isNegativeZero y)
= - atan2 (-y) x
| y==0 && (x<0 || isNegativeZero x)
must be after the previous test on zero y
must be after the other double zero tests
x or y is a NaN , return a NaN ( via + )
subtract :: Num a => a -> a -> a
subtract = flip (-)
gcd :: Integral a => a -> a -> a
gcd 0 0 = error "Prelude.gcd: gcd 0 0 is undefined"
gcd x y = gcd' (abs x) (abs y)
where gcd' x 0 = x
gcd' x y = gcd' y (x `rem` y)
lcm :: (Integral a) => a -> a -> a
lcm _ 0 = 0
lcm 0 _ = 0
lcm x y = abs ((x `quot` gcd x y) * y)
(^) :: (Num a, Integral b) => a -> b -> a
x ^ 0 = 1
x ^ n | n > 0 = f x (n-1) x
where f _ 0 y = y
f x n y = g x n where
g x n | even n = g (x*x) (n`quot`2)
| otherwise = f x (n-1) (x*y)
_ ^ _ = error "Prelude.^: negative exponent"
(^^) :: (Fractional a, Integral b) => a -> b -> a
x ^^ n = if n >= 0 then x ^ n else recip (x^(-n))
fromIntegral :: (Integral a, Num b) => a -> b
fromIntegral = fromInteger . toInteger
realToFrac :: (Real a, Fractional b) => a -> b
realToFrac = fromRational . toRational
class (Ord a) => Ix a where
range :: (a,a) -> [a]
index :: (a,a) -> a -> Int
inRange :: (a,a) -> a -> Bool
rangeSize :: (a,a) -> Int
rangeSize r@(l,u)
| l > u = 0
| otherwise = index r u + 1
class Enum a where
succ, pred :: a -> a
toEnum :: Int -> a
fromEnum :: a -> Int
succ = toEnum . (1+) . fromEnum
pred = toEnum . subtract 1 . fromEnum
enumFromTo x y = map toEnum [ fromEnum x .. fromEnum y ]
enumFromThenTo x y z = map toEnum [ fromEnum x, fromEnum y .. fromEnum z ]
type ReadS a = String -> [(a,String)]
type ShowS = String -> String
class Read a where
readsPrec :: Int -> ReadS a
readList :: ReadS [a]
readList = readParen False (\r -> [pr | ("[",s) <- lex r,
pr <- readl s ])
where readl s = [([],t) | ("]",t) <- lex s] ++
[(x:xs,u) | (x,t) <- reads s,
(xs,u) <- readl' t]
readl' s = [([],t) | ("]",t) <- lex s] ++
[(x:xs,v) | (",",t) <- lex s,
(x,u) <- reads t,
(xs,v) <- readl' u]
class Show a where
show :: a -> String
showsPrec :: Int -> a -> ShowS
showList :: [a] -> ShowS
show x = showsPrec 0 x ""
showsPrec _ x s = show x ++ s
showList [] = showString "[]"
showList (x:xs) = showChar '[' . shows x . showl xs
where showl [] = showChar ']'
showl (x:xs) = showChar ',' . shows x . showl xs
class Functor f where
fmap :: (a -> b) -> (f a -> f b)
class Monad m where
return :: a -> m a
(>>=) :: m a -> (a -> m b) -> m b
(>>) :: m a -> m b -> m b
fail :: String -> m a
p >> q = p >>= \ _ -> q
fail s = error s
sequence :: Monad m => [m a] -> m [a]
sequence [] = return []
sequence (c:cs) = do x <- c
xs <- sequence cs
return (x:xs)
sequence_ :: Monad m => [m a] -> m ()
sequence_ = foldr (>>) (return ())
mapM :: Monad m => (a -> m b) -> [a] -> m [b]
mapM f = sequence . map f
mapM_ :: Monad m => (a -> m b) -> [a] -> m ()
mapM_ f = sequence_ . map f
(=<<) :: Monad m => (a -> m b) -> m a -> m b
f =<< x = x >>= f
primitive seq :: a -> b -> b
primitive ($!) :: (a -> b) -> a -> b
data ( ) = ( ) deriving ( Eq , Ord , Ix , , Read , Show , Bounded )
instance Eq () where
() == () = True
instance Ord () where
compare () () = EQ
instance Ix () where
range ((),()) = [()]
index ((),()) () = 0
inRange ((),()) () = True
instance Enum () where
toEnum 0 = ()
fromEnum () = 0
enumFrom () = [()]
enumFromThen () () = [()]
instance Read () where
readsPrec p = readParen False (\r -> [((),t) | ("(",s) <- lex r,
(")",t) <- lex s ])
instance Show () where
showsPrec p () = showString "()"
instance Bounded () where
minBound = ()
maxBound = ()
data Bool = False | True
deriving (Eq, Ord, Ix, Enum, Read, Show, Bounded)
(&&), (||) :: Bool -> Bool -> Bool
False && x = False
True && x = x
False || x = x
True || x = True
not :: Bool -> Bool
not True = False
not False = True
otherwise :: Bool
otherwise = True
builtin datatype of ISO Latin characters
primitive primEqChar :: Char -> Char -> Bool
primitive primCmpChar :: Char -> Char -> Ordering
instance Eq Char where (==) = primEqChar
instance Ord Char where compare = primCmpChar
primitive primCharToInt :: Char -> Int
primitive primIntToChar :: Int -> Char
instance Enum Char where
toEnum = primIntToChar
fromEnum = primCharToInt
enumFrom c = map toEnum [fromEnum c .. fromEnum (maxBound::Char)]
enumFromThen c d = map toEnum [fromEnum c, fromEnum d .. fromEnum (lastChar::Char)]
where lastChar = if d < c then minBound else maxBound
instance Ix Char where
range (c,c') = [c..c']
index b@(c,c') ci
| inRange b ci = fromEnum ci - fromEnum c
| otherwise = error "Ix.index: Index out of range."
inRange (c,c') ci = fromEnum c <= i && i <= fromEnum c'
where i = fromEnum ci
instance Read Char where
readsPrec p = readParen False
(\r -> [(c,t) | ('\'':s,t) <- lex r,
(c,"\'") <- readLitChar s ])
readList = readParen False (\r -> [(l,t) | ('"':s, t) <- lex r,
(l,_) <- readl s ])
where readl ('"':s) = [("",s)]
readl ('\\':'&':s) = readl s
readl s = [(c:cs,u) | (c ,t) <- readLitChar s,
(cs,u) <- readl t ]
instance Show Char where
showsPrec p '\'' = showString "'\\''"
showsPrec p c = showChar '\'' . showLitChar c . showChar '\''
showList cs = showChar '"' . showl cs
where showl "" = showChar '"'
showl ('"':cs) = showString "\\\"" . showl cs
showl (c:cs) = showLitChar c . showl cs
instance Bounded Char where
minBound = 'a'
maxBound = 'z'
isAscii, isControl, isPrint, isSpace :: Char -> Bool
isUpper, isLower, isAlpha, isDigit, isAlphaNum :: Char -> Bool
isAscii c = fromEnum c < 128
isControl c = c < ' ' || c == '\DEL'
isPrint c = c >= ' ' && c <= '~'
isSpace c = c == ' ' || c == '\t' || c == '\n' ||
c == '\r' || c == '\f' || c == '\v'
isUpper c = c >= 'A' && c <= 'Z'
isLower c = c >= 'a' && c <= 'z'
isAlpha c = isUpper c || isLower c
isDigit c = c >= '0' && c <= '9'
isAlphaNum c = isAlpha c || isDigit c
Digit conversion operations
digitToInt :: Char -> Int
digitToInt c
| isDigit c = fromEnum c - fromEnum '0'
| c >= 'a' && c <= 'f' = fromEnum c - fromEnum 'a' + 10
| c >= 'A' && c <= 'F' = fromEnum c - fromEnum 'A' + 10
| otherwise = error "Char.digitToInt: not a digit"
intToDigit :: Int -> Char
intToDigit i
| i >= 0 && i <= 9 = toEnum (fromEnum '0' + i)
| i >= 10 && i <= 15 = toEnum (fromEnum 'a' + i - 10)
| otherwise = error "Char.intToDigit: not a digit"
toUpper, toLower :: Char -> Char
toUpper c | isLower c = toEnum (fromEnum c - fromEnum 'a' + fromEnum 'A')
| otherwise = c
toLower c | isUpper c = toEnum (fromEnum c - fromEnum 'A' + fromEnum 'a')
| otherwise = c
ord :: Char -> Int
ord = fromEnum
chr :: Int -> Char
chr = toEnum
data Maybe a = Nothing | Just a
deriving (Eq, Ord, Read, Show)
maybe :: b -> (a -> b) -> Maybe a -> b
maybe n f Nothing = n
maybe n f (Just x) = f x
instance Functor Maybe where
fmap f Nothing = Nothing
fmap f (Just x) = Just (f x)
instance Monad Maybe where
Just x >>= k = k x
Nothing >>= k = Nothing
return = Just
fail s = Nothing
data Either a b = Left a | Right b
deriving (Eq, Ord, Read, Show)
either :: (a -> c) -> (b -> c) -> Either a b -> c
either l r (Left x) = l x
either l r (Right y) = r y
data Ordering = LT | EQ | GT
deriving (Eq, Ord, Ix, Enum, Read, Show, Bounded)
data [ a ] = [ ] | a : [ a ] deriving ( Eq , Ord )
instance Eq a => Eq [a] where
[] == [] = True
(x:xs) == (y:ys) = x==y && xs==ys
_ == _ = False
instance Ord a => Ord [a] where
compare [] (_:_) = LT
compare [] [] = EQ
compare (_:_) [] = GT
compare (x:xs) (y:ys) = primCompAux x y (compare xs ys)
instance Functor [] where
fmap = map
instance Monad [ ] where
(x:xs) >>= f = f x ++ (xs >>= f)
[] >>= f = []
return x = [x]
fail s = []
instance Read a => Read [a] where
readsPrec p = readList
instance Show a => Show [a] where
showsPrec p = showList
data ( a , b ) = ( a , b ) deriving ( Eq , Ord , Ix , Read , Show )
primitive primEqInt :: Int -> Int -> Bool
primitive primCmpInt :: Int -> Int -> Ordering
primitive primEqInteger :: Integer -> Integer -> Bool
primitive primCmpInteger :: Integer -> Integer -> Ordering
instance Eq Int where (==) = primEqInt
instance Eq Integer where (==) = primEqInteger
instance Ord Int where compare = primCmpInt
instance Ord Integer where compare = primCmpInteger
primitive primPlusInt :: Int -> Int -> Int
primitive primMinusInt :: Int -> Int -> Int
primitive primMulInt :: Int -> Int -> Int
primitive primNegInt :: Int -> Int
primitive primIntegerToInt :: Integer -> Int
instance Num Int where
(+) = primPlusInt
(-) = primMinusInt
negate = primNegInt
(*) = primMulInt
abs = absReal
signum = signumReal
fromInteger = primIntegerToInt
fromInt x = x
primitive primMinInt :: Int
primitive primMaxInt :: Int
instance Bounded Int where
minBound = primMinInt
maxBound = primMaxInt
primitive primPlusInteger :: Integer -> Integer -> Integer
primitive primMinusInteger :: Integer -> Integer -> Integer
primitive primMulInteger :: Integer -> Integer -> Integer
primitive primNegInteger :: Integer -> Integer
primitive primIntToInteger :: Int -> Integer
instance Num Integer where
(+) = primPlusInteger
(-) = primMinusInteger
negate = primNegInteger
(*) = primMulInteger
abs = absReal
signum = signumReal
fromInteger x = x
fromInt = primIntToInteger
absReal x | x >= 0 = x
| otherwise = -x
signumReal x | x == 0 = 0
| x > 0 = 1
| otherwise = -1
instance Real Int where
toRational x = toInteger x % 1
instance Real Integer where
toRational x = x % 1
primitive primDivInt :: Int -> Int -> Int
primitive primQuotInt :: Int -> Int -> Int
primitive primRemInt :: Int -> Int -> Int
primitive primModInt :: Int -> Int -> Int
primitive primQrmInt :: Int -> Int -> (Int,Int)
primitive primEvenInt :: Int -> Bool
instance Integral Int where
div = primDivInt
quot = primQuotInt
rem = primRemInt
mod = primModInt
quotRem = primQrmInt
even = primEvenInt
toInteger = primIntToInteger
toInt x = x
primitive primQrmInteger :: Integer -> Integer -> (Integer,Integer)
primitive primEvenInteger :: Integer -> Bool
instance Integral Integer where
quotRem = primQrmInteger
even = primEvenInteger
toInteger x = x
toInt = primIntegerToInt
instance Ix Int where
range (m,n) = [m..n]
index b@(m,n) i
| inRange b i = i - m
| otherwise = error "index: Index out of range"
inRange (m,n) i = m <= i && i <= n
instance Ix Integer where
range (m,n) = [m..n]
index b@(m,n) i
| inRange b i = fromInteger (i - m)
| otherwise = error "index: Index out of range"
inRange (m,n) i = m <= i && i <= n
instance Enum Int where
toEnum = id
fromEnum = id
enumFrom = numericEnumFrom
enumFromTo = numericEnumFromTo
enumFromThen = numericEnumFromThen
enumFromThenTo = numericEnumFromThenTo
instance Enum Integer where
toEnum = primIntToInteger
fromEnum = primIntegerToInt
enumFrom = numericEnumFrom
enumFromTo = numericEnumFromTo
enumFromThen = numericEnumFromThen
enumFromThenTo = numericEnumFromThenTo
numericEnumFrom :: Real a => a -> [a]
numericEnumFromThen :: Real a => a -> a -> [a]
numericEnumFromTo :: Real a => a -> a -> [a]
numericEnumFromThenTo :: Real a => a -> a -> a -> [a]
numericEnumFrom n = n : (numericEnumFrom $! (n+1))
numericEnumFromThen n m = iterate ((m-n)+) n
numericEnumFromTo n m = takeWhile (<= m) (numericEnumFrom n)
numericEnumFromThenTo n n' m = takeWhile p (numericEnumFromThen n n')
where p | n' >= n = (<= m)
| otherwise = (>= m)
primitive primShowsInt :: Int -> Int -> ShowS
instance Read Int where
readsPrec p = readSigned readDec
instance Show Int where
showsPrec = primShowsInt
primitive primShowsInteger :: Int -> Integer -> ShowS
instance Read Integer where
readsPrec p = readSigned readDec
instance Show Integer where
showsPrec = primShowsInteger
primitive primEqFloat :: Float -> Float -> Bool
primitive primCmpFloat :: Float -> Float -> Ordering
primitive primEqDouble :: Double -> Double -> Bool
primitive primCmpDouble :: Double -> Double -> Ordering
instance Eq Float where (==) = primEqFloat
instance Eq Double where (==) = primEqDouble
instance Ord Float where compare = primCmpFloat
instance Ord Double where compare = primCmpDouble
primitive primPlusFloat :: Float -> Float -> Float
primitive primMinusFloat :: Float -> Float -> Float
primitive primMulFloat :: Float -> Float -> Float
primitive primNegFloat :: Float -> Float
primitive primIntToFloat :: Int -> Float
primitive primIntegerToFloat :: Integer -> Float
instance Num Float where
(+) = primPlusFloat
(-) = primMinusFloat
negate = primNegFloat
(*) = primMulFloat
abs = absReal
signum = signumReal
fromInteger = primIntegerToFloat
fromInt = primIntToFloat
primitive primPlusDouble :: Double -> Double -> Double
primitive primMinusDouble :: Double -> Double -> Double
primitive primMulDouble :: Double -> Double -> Double
primitive primNegDouble :: Double -> Double
primitive primIntToDouble :: Int -> Double
primitive primIntegerToDouble :: Integer -> Double
instance Num Double where
(+) = primPlusDouble
(-) = primMinusDouble
negate = primNegDouble
(*) = primMulDouble
abs = absReal
signum = signumReal
fromInteger = primIntegerToDouble
fromInt = primIntToDouble
instance Real Float where
toRational = floatToRational
instance Real Double where
toRational = doubleToRational
floatToRational :: Float -> Rational
doubleToRational :: Double -> Rational
floatToRational x = realFloatToRational x
doubleToRational x = realFloatToRational x
realFloatToRational x = (m%1)*(b%1)^^n
where (m,n) = decodeFloat x
b = floatRadix x
primitive primDivFloat :: Float -> Float -> Float
primitive doubleToFloat :: Double -> Float
instance Fractional Float where
(/) = primDivFloat
fromRational = primRationalToFloat
fromDouble = doubleToFloat
primitive primDivDouble :: Double -> Double -> Double
instance Fractional Double where
(/) = primDivDouble
fromRational = primRationalToDouble
fromDouble x = x
primitive primRationalToFloat :: Rational -> Float
primitive primRationalToDouble :: Rational -> Double
rationalToFloat :: Rational -> Float
rationalToDouble :: Rational -> Double
rationalToFloat = rationalToRealFloat
rationalToDouble = rationalToRealFloat
rationalToRealFloat x = x'
where x' = f e
f e = if e' == e then y else f e'
where y = encodeFloat (round (x * (1%b)^^e)) e
(_,e') = decodeFloat y
(_,e) = decodeFloat (fromInteger (numerator x) `asTypeOf` x'
/ fromInteger (denominator x))
b = floatRadix x'
primitive primSinFloat :: Float -> Float
primitive primAsinFloat :: Float -> Float
primitive primCosFloat :: Float -> Float
primitive primAcosFloat :: Float -> Float
primitive primTanFloat :: Float -> Float
primitive primAtanFloat :: Float -> Float
primitive primLogFloat :: Float -> Float
primitive primExpFloat :: Float -> Float
primitive primSqrtFloat :: Float -> Float
instance Floating Float where
exp = primExpFloat
log = primLogFloat
sqrt = primSqrtFloat
sin = primSinFloat
cos = primCosFloat
tan = primTanFloat
asin = primAsinFloat
acos = primAcosFloat
atan = primAtanFloat
primitive primSinDouble :: Double -> Double
primitive primAsinDouble :: Double -> Double
primitive primCosDouble :: Double -> Double
primitive primAcosDouble :: Double -> Double
primitive primTanDouble :: Double -> Double
primitive primAtanDouble :: Double -> Double
primitive primLogDouble :: Double -> Double
primitive primExpDouble :: Double -> Double
primitive primSqrtDouble :: Double -> Double
instance Floating Double where
exp = primExpDouble
log = primLogDouble
sqrt = primSqrtDouble
sin = primSinDouble
cos = primCosDouble
tan = primTanDouble
asin = primAsinDouble
acos = primAcosDouble
atan = primAtanDouble
instance RealFrac Float where
properFraction = floatProperFraction
instance RealFrac Double where
properFraction = floatProperFraction
floatProperFraction x
| n >= 0 = (fromInteger m * fromInteger b ^ n, 0)
| otherwise = (fromInteger w, encodeFloat r n)
where (m,n) = decodeFloat x
b = floatRadix x
(w,r) = quotRem m (b^(-n))
primitive primFloatRadix :: Integer
primitive primFloatDigits :: Int
primitive primFloatMinExp :: Int
primitive primFloatMaxExp :: Int
primitive primFloatEncode :: Integer -> Int -> Float
primitive primFloatDecode :: Float -> (Integer, Int)
instance RealFloat Float where
floatRadix _ = primFloatRadix
floatDigits _ = primFloatDigits
floatRange _ = (primFloatMinExp, primFloatMaxExp)
encodeFloat = primFloatEncode
decodeFloat = primFloatDecode
isNaN _ = False
isInfinite _ = False
isDenormalized _ = False
isNegativeZero _ = False
isIEEE _ = False
primitive primDoubleRadix :: Integer
primitive primDoubleDigits :: Int
primitive primDoubleMinExp :: Int
primitive primDoubleMaxExp :: Int
primitive primDoubleEncode :: Integer -> Int -> Double
primitive primDoubleDecode :: Double -> (Integer, Int)
instance RealFloat Double where
floatRadix _ = primDoubleRadix
floatDigits _ = primDoubleDigits
floatRange _ = (primDoubleMinExp, primDoubleMaxExp)
encodeFloat = primDoubleEncode
decodeFloat = primDoubleDecode
isNaN _ = False
isInfinite _ = False
isDenormalized _ = False
isNegativeZero _ = False
isIEEE _ = False
instance Enum Float where
toEnum = primIntToFloat
fromEnum = truncate
enumFrom = numericEnumFrom
enumFromThen = numericEnumFromThen
enumFromTo n m = numericEnumFromTo n (m+1/2)
enumFromThenTo n n' m = numericEnumFromThenTo n n' (m + (n'-n)/2)
instance Enum Double where
toEnum = primIntToDouble
fromEnum = truncate
enumFrom = numericEnumFrom
enumFromThen = numericEnumFromThen
enumFromTo n m = numericEnumFromTo n (m+1/2)
enumFromThenTo n n' m = numericEnumFromThenTo n n' (m + (n'-n)/2)
primitive primShowsFloat :: Int -> Float -> ShowS
instance Read Float where
readsPrec p = readSigned readFloat
instance Show Float where
showsPrec = primShowsFloat
primitive primShowsDouble :: Int -> Double -> ShowS
instance Read Double where
readsPrec p = readSigned readFloat
instance Show Double where
showsPrec = primShowsDouble
fst :: (a,b) -> a
fst (x,_) = x
snd :: (a,b) -> b
snd (_,y) = y
curry :: ((a,b) -> c) -> (a -> b -> c)
curry f x y = f (x,y)
uncurry :: (a -> b -> c) -> ((a,b) -> c)
uncurry f p = f (fst p) (snd p)
id :: a -> a
id x = x
const :: a -> b -> a
const k _ = k
(.) :: (b -> c) -> (a -> b) -> (a -> c)
(f . g) x = f (g x)
flip :: (a -> b -> c) -> b -> a -> c
flip f x y = f y x
($) :: (a -> b) -> a -> b
f $ x = f x
until :: (a -> Bool) -> (a -> a) -> a -> a
until p f x = if p x then x else until p f (f x)
asTypeOf :: a -> a -> a
asTypeOf = const
primitive error :: String -> a
undefined :: a
undefined | False = undefined
data (Integral a) => Ratio a = a :% a deriving (Eq)
type Rational = Ratio Integer
(%) :: Integral a => a -> a -> Ratio a
x % y = reduce (x * signum y) (abs y)
reduce :: Integral a => a -> a -> Ratio a
reduce x y | y == 0 = error "Ratio.%: zero denominator"
| otherwise = (x `quot` d) :% (y `quot` d)
where d = gcd x y
numerator, denominator :: Integral a => Ratio a -> a
numerator (x :% y) = x
denominator (x :% y) = y
instance Integral a => Ord (Ratio a) where
compare (x:%y) (x':%y') = compare (x*y') (x'*y)
instance Integral a => Num (Ratio a) where
(x:%y) + (x':%y') = reduce (x*y' + x'*y) (y*y')
(x:%y) * (x':%y') = reduce (x*x') (y*y')
negate (x :% y) = negate x :% y
abs (x :% y) = abs x :% y
signum (x :% y) = signum x :% 1
fromInteger x = fromInteger x :% 1
fromInt = intToRatio
intToRatio :: Integral a => Int -> Ratio a
intToRatio x = fromInt x :% 1
instance Integral a => Real (Ratio a) where
toRational (x:%y) = toInteger x :% toInteger y
instance Integral a => Fractional (Ratio a) where
(x:%y) / (x':%y') = (x*y') % (y*x')
recip (x:%y) = if x < 0 then (-y) :% (-x) else y :% x
fromRational (x:%y) = fromInteger x :% fromInteger y
fromDouble = doubleToRatio
doubleToRatio :: Integral a => Double -> Ratio a
doubleToRatio x
| n>=0 = (fromInteger m * fromInteger b ^ n) % 1
| otherwise = fromInteger m % (fromInteger b ^ (-n))
where (m,n) = decodeFloat x
b = floatRadix x
instance Integral a => RealFrac (Ratio a) where
properFraction (x:%y) = (fromIntegral q, r:%y)
where (q,r) = quotRem x y
instance Integral a => Enum (Ratio a) where
toEnum = fromInt
fromEnum = truncate
enumFrom = numericEnumFrom
enumFromThen = numericEnumFromThen
instance (Read a, Integral a) => Read (Ratio a) where
readsPrec p = readParen (p > 7)
(\r -> [(x%y,u) | (x,s) <- reads r,
("%",t) <- lex s,
(y,u) <- reads t ])
instance Integral a => Show (Ratio a) where
showsPrec p (x:%y) = showParen (p > 7)
(shows x . showString " % " . shows y)
approxRational :: RealFrac a => a -> a -> Rational
approxRational x eps = simplest (x-eps) (x+eps)
where simplest x y | y < x = simplest y x
| x == y = xr
| x > 0 = simplest' n d n' d'
| y < 0 = - simplest' (-n') d' (-n) d
| otherwise = 0 :% 1
where xr@(n:%d) = toRational x
(n':%d') = toRational y
| r == 0 = q :% 1
| q /= q' = (q+1) :% 1
| otherwise = (q*n''+d'') :% n''
where (q,r) = quotRem n d
(q',r') = quotRem n' d'
(n'':%d'') = simplest' d' r' d r
head :: [a] -> a
head (x:_) = x
last :: [a] -> a
last [x] = x
last (_:xs) = last xs
tail :: [a] -> [a]
tail (_:xs) = xs
init :: [a] -> [a]
init [x] = []
init (x:xs) = x : init xs
null :: [a] -> Bool
null [] = True
null (_:_) = False
(++) :: [a] -> [a] -> [a]
[] ++ ys = ys
(x:xs) ++ ys = x : (xs ++ ys)
map :: (a -> b) -> [a] -> [b]
map f xs = [ f x | x <- xs ]
filter :: (a -> Bool) -> [a] -> [a]
filter p xs = [ x | x <- xs, p x ]
concat :: [[a]] -> [a]
concat = foldr (++) []
length :: [a] -> Int
length = foldl' (\n _ -> n + 1) 0
(!!) :: [b] -> Int -> b
(x:_) !! 0 = x
(_:xs) !! n | n>0 = xs !! (n-1)
(_:_) !! _ = error "Prelude.!!: negative index"
[] !! _ = error "Prelude.!!: index too large"
foldl :: (a -> b -> a) -> a -> [b] -> a
foldl f z [] = z
foldl f z (x:xs) = foldl f (f z x) xs
foldl' :: (a -> b -> a) -> a -> [b] -> a
foldl' f a [] = a
foldl' f a (x:xs) = (foldl' f $! f a x) xs
foldl1 :: (a -> a -> a) -> [a] -> a
foldl1 f (x:xs) = foldl f x xs
scanl :: (a -> b -> a) -> a -> [b] -> [a]
scanl f q xs = q : (case xs of
[] -> []
x:xs -> scanl f (f q x) xs)
scanl1 :: (a -> a -> a) -> [a] -> [a]
scanl1 f (x:xs) = scanl f x xs
foldr :: (a -> b -> b) -> b -> [a] -> b
foldr f z [] = z
foldr f z (x:xs) = f x (foldr f z xs)
foldr1 :: (a -> a -> a) -> [a] -> a
foldr1 f [x] = x
foldr1 f (x:xs) = f x (foldr1 f xs)
scanr :: (a -> b -> b) -> b -> [a] -> [b]
scanr f q0 [] = [q0]
scanr f q0 (x:xs) = f x q : qs
where qs@(q:_) = scanr f q0 xs
scanr1 :: (a -> a -> a) -> [a] -> [a]
scanr1 f [x] = [x]
scanr1 f (x:xs) = f x q : qs
where qs@(q:_) = scanr1 f xs
iterate :: (a -> a) -> a -> [a]
iterate f x = x : iterate f (f x)
repeat :: a -> [a]
repeat x = xs where xs = x:xs
replicate :: Int -> a -> [a]
replicate n x = take n (repeat x)
cycle :: [a] -> [a]
cycle [] = error "Prelude.cycle: empty list"
cycle xs = xs' where xs'=xs++xs'
take :: Int -> [a] -> [a]
take 0 _ = []
take _ [] = []
take n (x:xs) | n>0 = x : take (n-1) xs
take _ _ = error "Prelude.take: negative argument"
drop :: Int -> [a] -> [a]
drop 0 xs = xs
drop _ [] = []
drop n (_:xs) | n>0 = drop (n-1) xs
drop _ _ = error "Prelude.drop: negative argument"
splitAt :: Int -> [a] -> ([a], [a])
splitAt 0 xs = ([],xs)
splitAt _ [] = ([],[])
splitAt n (x:xs) | n>0 = (x:xs',xs'') where (xs',xs'') = splitAt (n-1) xs
splitAt _ _ = error "Prelude.splitAt: negative argument"
takeWhile :: (a -> Bool) -> [a] -> [a]
takeWhile p [] = []
takeWhile p (x:xs)
| p x = x : takeWhile p xs
| otherwise = []
dropWhile :: (a -> Bool) -> [a] -> [a]
dropWhile p [] = []
dropWhile p xs@(x:xs')
| p x = dropWhile p xs'
| otherwise = xs
span, break :: (a -> Bool) -> [a] -> ([a],[a])
span p [] = ([],[])
span p xs@(x:xs')
| p x = (x:ys, zs)
| otherwise = ([],xs)
where (ys,zs) = span p xs'
break p = span (not . p)
lines :: String -> [String]
lines "" = []
lines s = let (l,s') = break ('\n'==) s
in l : case s' of [] -> []
(_:s'') -> lines s''
words :: String -> [String]
words s = case dropWhile isSpace s of
"" -> []
s' -> w : words s''
where (w,s'') = break isSpace s'
unlines :: [String] -> String
unlines = concatMap (\l -> l ++ "\n")
unwords :: [String] -> String
unwords [] = []
unwords ws = foldr1 (\w s -> w ++ ' ':s) ws
reverse :: [a] -> [a]
reverse = foldl (flip (:)) []
and, or :: [Bool] -> Bool
and = foldr (&&) True
or = foldr (||) False
any, all :: (a -> Bool) -> [a] -> Bool
any p = or . map p
all p = and . map p
elem, notElem :: Eq a => a -> [a] -> Bool
elem = any . (==)
notElem = all . (/=)
lookup :: Eq a => a -> [(a,b)] -> Maybe b
lookup k [] = Nothing
lookup k ((x,y):xys)
| k==x = Just y
| otherwise = lookup k xys
sum, product :: Num a => [a] -> a
sum = foldl' (+) 0
product = foldl' (*) 1
maximum, minimum :: Ord a => [a] -> a
maximum = foldl1 max
minimum = foldl1 min
concatMap :: (a -> [b]) -> [a] -> [b]
concatMap f = concat . map f
zip :: [a] -> [b] -> [(a,b)]
zip = zipWith (\a b -> (a,b))
zip3 :: [a] -> [b] -> [c] -> [(a,b,c)]
zip3 = zipWith3 (\a b c -> (a,b,c))
zipWith :: (a->b->c) -> [a]->[b]->[c]
zipWith z (a:as) (b:bs) = z a b : zipWith z as bs
zipWith _ _ _ = []
zipWith3 :: (a->b->c->d) -> [a]->[b]->[c]->[d]
zipWith3 z (a:as) (b:bs) (c:cs)
= z a b c : zipWith3 z as bs cs
zipWith3 _ _ _ _ = []
unzip :: [(a,b)] -> ([a],[b])
unzip = foldr (\(a,b) ~(as,bs) -> (a:as, b:bs)) ([], [])
unzip3 :: [(a,b,c)] -> ([a],[b],[c])
unzip3 = foldr (\(a,b,c) ~(as,bs,cs) -> (a:as,b:bs,c:cs))
([],[],[])
reads :: Read a => ReadS a
reads = readsPrec 0
shows :: Show a => a -> ShowS
shows = showsPrec 0
read :: Read a => String -> a
read s = case [x | (x,t) <- reads s, ("","") <- lex t] of
[x] -> x
[] -> error "Prelude.read: no parse"
_ -> error "Prelude.read: ambiguous parse"
showChar :: Char -> ShowS
showChar = (:)
showString :: String -> ShowS
showString = (++)
showParen :: Bool -> ShowS -> ShowS
showParen b p = if b then showChar '(' . p . showChar ')' else p
showField :: Show a => String -> a -> ShowS
showField m v = showString m . showChar '=' . shows v
readParen :: Bool -> ReadS a -> ReadS a
readParen b g = if b then mandatory else optional
where optional r = g r ++ mandatory r
mandatory r = [(x,u) | ("(",s) <- lex r,
(x,t) <- optional s,
(")",u) <- lex t ]
readField :: Read a => String -> ReadS a
readField m s0 = [ r | (t, s1) <- lex s0, t == m,
("=",s2) <- lex s1,
r <- reads s2 ]
lex :: ReadS String
lex "" = [("","")]
lex (c:s) | isSpace c = lex (dropWhile isSpace s)
lex ('\'':s) = [('\'':ch++"'", t) | (ch,'\'':t) <- lexLitChar s,
ch /= "'" ]
lex ('"':s) = [('"':str, t) | (str,t) <- lexString s]
where
lexString ('"':s) = [("\"",s)]
lexString s = [(ch++str, u)
| (ch,t) <- lexStrItem s,
(str,u) <- lexString t ]
lexStrItem ('\\':'&':s) = [("\\&",s)]
lexStrItem ('\\':c:s) | isSpace c
= [("",t) | '\\':t <- [dropWhile isSpace s]]
lexStrItem s = lexLitChar s
lex (c:s) | isSingle c = [([c],s)]
| isSym c = [(c:sym,t) | (sym,t) <- [span isSym s]]
| isAlpha c = [(c:nam,t) | (nam,t) <- [span isIdChar s]]
| isDigit c = [(c:ds++fe,t) | (ds,s) <- [span isDigit s],
(fe,t) <- lexFracExp s ]
where
isSingle c = c `elem` ",;()[]{}_`"
isSym c = c `elem` "!@#$%&*+./<=>?\\^|:-~"
isIdChar c = isAlphaNum c || c `elem` "_'"
lexFracExp ('.':s) = [('.':ds++e,u) | (ds,t) <- lexDigits s,
(e,u) <- lexExp t ]
lexFracExp s = [("",s)]
lexExp (e:s) | e `elem` "eE"
= [(e:c:ds,u) | (c:t) <- [s], c `elem` "+-",
(ds,u) <- lexDigits t] ++
[(e:ds,t) | (ds,t) <- lexDigits s]
lexExp s = [("",s)]
lexDigits :: ReadS String
lexDigits = nonnull isDigit
nonnull :: (Char -> Bool) -> ReadS String
nonnull p s = [(cs,t) | (cs@(_:_),t) <- [span p s]]
lexLitChar :: ReadS String
lexLitChar ('\\':s) = [('\\':esc, t) | (esc,t) <- lexEsc s]
where
lexEsc (c:s) | c `elem` "abfnrtv\\\"'" = [([c],s)]
lexEsc ('^':c:s) | c >= '@' && c <= '_' = [(['^',c],s)]
lexEsc s@(d:_) | isDigit d = lexDigits s
lexEsc s@(c:_) | isUpper c
= let table = ('\DEL',"DEL") : asciiTab
in case [(mne,s') | (c, mne) <- table,
([],s') <- [lexmatch mne s]]
of (pr:_) -> [pr]
[] -> []
lexEsc _ = []
lexLitChar (c:s) = [([c],s)]
lexLitChar "" = []
isOctDigit c = c >= '0' && c <= '7'
isHexDigit c = isDigit c || c >= 'A' && c <= 'F'
|| c >= 'a' && c <= 'f'
lexmatch :: (Eq a) => [a] -> [a] -> ([a],[a])
lexmatch (x:xs) (y:ys) | x == y = lexmatch xs ys
lexmatch xs ys = (xs,ys)
asciiTab = zip ['\NUL'..' ']
["NUL", "SOH", "STX", "ETX", "EOT", "ENQ", "ACK", "BEL",
"BS", "HT", "LF", "VT", "FF", "CR", "SO", "SI",
"DLE", "DC1", "DC2", "DC3", "DC4", "NAK", "SYN", "ETB",
"CAN", "EM", "SUB", "ESC", "FS", "GS", "RS", "US",
"SP"]
readLitChar :: ReadS Char
readLitChar ('\\':s) = readEsc s
where
readEsc ('a':s) = [('\a',s)]
readEsc ('b':s) = [('\b',s)]
readEsc ('f':s) = [('\f',s)]
readEsc ('n':s) = [('\n',s)]
readEsc ('r':s) = [('\r',s)]
readEsc ('t':s) = [('\t',s)]
readEsc ('v':s) = [('\v',s)]
readEsc ('\\':s) = [('\\',s)]
readEsc ('"':s) = [('"',s)]
readEsc ('\'':s) = [('\'',s)]
readEsc ('^':c:s) | c >= '@' && c <= '_'
= [(toEnum (fromEnum c - fromEnum '@'), s)]
readEsc s@(d:_) | isDigit d
= [(toEnum n, t) | (n,t) <- readDec s]
readEsc ('o':s) = [(toEnum n, t) | (n,t) <- readOct s]
readEsc ('x':s) = [(toEnum n, t) | (n,t) <- readHex s]
readEsc s@(c:_) | isUpper c
= let table = ('\DEL',"DEL") : asciiTab
in case [(c,s') | (c, mne) <- table,
([],s') <- [lexmatch mne s]]
of (pr:_) -> [pr]
[] -> []
readEsc _ = []
readLitChar (c:s) = [(c,s)]
showLitChar :: Char -> ShowS
showLitChar c | c > '\DEL' = showChar '\\' .
protectEsc isDigit (shows (fromEnum c))
showLitChar '\DEL' = showString "\\DEL"
showLitChar '\\' = showString "\\\\"
showLitChar c | c >= ' ' = showChar c
showLitChar '\a' = showString "\\a"
showLitChar '\b' = showString "\\b"
showLitChar '\f' = showString "\\f"
showLitChar '\n' = showString "\\n"
showLitChar '\r' = showString "\\r"
showLitChar '\t' = showString "\\t"
showLitChar '\v' = showString "\\v"
showLitChar '\SO' = protectEsc ('H'==) (showString "\\SO")
showLitChar c = showString ('\\' : snd (asciiTab!!fromEnum c))
protectEsc p f = f . cont
where cont s@(c:_) | p c = "\\&" ++ s
cont s = s
readDec, readOct, readHex :: Integral a => ReadS a
readDec = readInt 10 isDigit (\d -> fromEnum d - fromEnum '0')
readOct = readInt 8 isOctDigit (\d -> fromEnum d - fromEnum '0')
readHex = readInt 16 isHexDigit hex
where hex d = fromEnum d -
(if isDigit d
then fromEnum '0'
else fromEnum (if isUpper d then 'A' else 'a') - 10)
readInt :: Integral a => a -> (Char -> Bool) -> (Char -> Int) -> ReadS a
readInt radix isDig digToInt s =
[(foldl1 (\n d -> n * radix + d) (map (fromIntegral . digToInt) ds), r)
| (ds,r) <- nonnull isDig s ]
showInt :: Integral a => a -> ShowS
showInt n r | n < 0 = error "Numeric.showInt: can't show negative numbers"
| otherwise =
let (n',d) = quotRem n 10
r' = toEnum (fromEnum '0' + fromIntegral d) : r
in if n' == 0 then r' else showInt n' r'
readSigned:: Real a => ReadS a -> ReadS a
readSigned readPos = readParen False read'
where read' r = read'' r ++
[(-x,t) | ("-",s) <- lex r,
(x,t) <- read'' s]
read'' r = [(n,s) | (str,s) <- lex r,
(n,"") <- readPos str]
showSigned :: Real a => (a -> ShowS) -> Int -> a -> ShowS
showSigned showPos p x = if x < 0 then showParen (p > 6)
(showChar '-' . showPos (-x))
else showPos x
readFloat :: RealFloat a => ReadS a
readFloat r = [(fromRational ((n%1)*10^^(k-d)),t) | (n,d,s) <- readFix r,
(k,t) <- readExp s]
where readFix r = [(read (ds++ds'), length ds', t)
| (ds, s) <- lexDigits r
, (ds',t) <- lexFrac s ]
lexFrac ('.':s) = lexDigits s
lexFrac s = [("",s)]
readExp (e:s) | e `elem` "eE" = readExp' s
readExp s = [(0,s)]
readExp' ('-':s) = [(-k,t) | (k,t) <- readDec s]
readExp' ('+':s) = readDec s
readExp' s = readDec s
builtin datatype of IO error codes
instance Show (IO a) where
showsPrec p f = showString "<<IO action>>"
primitive primbindIO :: IO a -> (a -> IO b) -> IO b
primitive primretIO :: a -> IO a
primitive catch :: IO a -> (IOError -> IO a) -> IO a
primitive ioError :: IOError -> IO a
primitive putChar :: Char -> IO ()
primitive putStr :: String -> IO ()
primitive getChar :: IO Char
primitive userError :: String -> IOError
print :: Show a => a -> IO ()
print = putStrLn . show
putStrLn :: String -> IO ()
putStrLn s = do putStr s
putChar '\n'
getLine :: IO String
getLine = do c <- getChar
if c=='\n' then return ""
else do cs <- getLine
return (c:cs)
readIO :: Read a => String -> IO a
readIO s = case [x | (x,t) <- reads s, ("","") <- lex t] of
[x] -> return x
[] -> ioError (userError "PreludeIO.readIO: no parse")
_ -> ioError (userError
"PreludeIO.readIO: ambiguous parse")
readLn :: Read a => IO a
readLn = do l <- getLine
r <- readIO l
return r
primitive getContents :: IO String
primitive writeFile :: FilePath -> String -> IO ()
primitive appendFile :: FilePath -> String -> IO ()
primitive readFile :: FilePath -> IO String
interact :: (String -> String) -> IO ()
interact f = getContents >>= (putStr . f)
instance Functor IO where
fmap f x = x >>= (return . f)
instance Monad IO where
(>>=) = primbindIO
return = primretIO
newtype IO a = IO ((IOError -> IOResult a) -> (a -> IOResult a) -> IOResult a)
data IOResult a
= Hugs_ExitWith Int
| Hugs_SuspendThread
| Hugs_Error IOError
| Hugs_Return a
hugsPutStr :: String -> IO ()
hugsPutStr = putStr
hugsIORun :: IO a -> Either Int a
hugsIORun m = performIO (runAndShowError m)
where
performIO :: IO a -> Either Int a
performIO (IO m) = case m Hugs_Error Hugs_Return of
Hugs_Return a -> Right a
Hugs_ExitWith e -> Left e
_ -> Left 1
runAndShowError :: IO a -> IO a
runAndShowError m =
m `catch` \err -> do
putChar '\n'
putStr (ioeGetErrorString err)
primExitWith :: Int -> IO a
primExitWith c = IO (\ f s -> Hugs_ExitWith c)
primitive ioeGetErrorString :: IOError -> String
instance Show IOError where
showsPrec p x = showString (ioeGetErrorString x)
primCompAux :: Ord a => a -> a -> Ordering -> Ordering
primCompAux x y o = case compare x y of EQ -> o; LT -> LT; GT -> GT
primPmInt :: Num a => Int -> a -> Bool
primPmInt n x = fromInt n == x
primPmInteger :: Num a => Integer -> a -> Bool
primPmInteger n x = fromInteger n == x
primPmFlt :: Fractional a => Double -> a -> Bool
primPmFlt n x = fromDouble n == x
primPmNpk :: Integral a => Int -> a -> Maybe a
primPmNpk n x = if n'<=x then Just (x-n') else Nothing
where n' = fromInt n
primPmSub :: Integral a => Int -> a -> a
primPmSub n x = x - fromInt n
|
41830e2ed135d98fd31777142d6a18391c7cf1b0e64545837ace18062854ee96
|
rjray/advent-2020-clojure
|
day05bis.clj
|
(ns advent-of-code.day05bis
(:require [clojure.string :as str]
[clojure.math.numeric-tower :as math]))
(defn- bin-partition [parts]
(let [hi (dec (math/expt 2 (count parts)))]
(loop [[part & parts] parts, lo 0, hi hi]
(let [gap (/ (+ lo hi 1) 2)]
(cond
(nil? part) lo
(= part \F) (recur parts lo (dec gap))
(= part \L) (recur parts lo (dec gap))
(= part \B) (recur parts gap hi)
(= part \R) (recur parts gap hi))))))
(defn- get-id [pass]
(let [row (take 7 pass)
seat (drop 7 pass)]
(+ (* 8 (bin-partition row)) (bin-partition seat))))
(defn part-1
"Day 05 Part 1"
[input]
(->> input
str/split-lines
(map get-id)
sort
last))
(defn- find-gap [lst]
(let [[init & lst] lst]
(loop [[l & lst] lst, init init]
(cond
(nil? l) nil
(= (inc init) l) (recur lst l)
:else (dec l)))))
(defn part-2
"Day 05 Part 2"
[input]
(->> input
str/split-lines
(map get-id)
sort
find-gap))
| null |
https://raw.githubusercontent.com/rjray/advent-2020-clojure/631b36545ae1efdebd11ca3dd4dca032346e8601/src/advent_of_code/day05bis.clj
|
clojure
|
(ns advent-of-code.day05bis
(:require [clojure.string :as str]
[clojure.math.numeric-tower :as math]))
(defn- bin-partition [parts]
(let [hi (dec (math/expt 2 (count parts)))]
(loop [[part & parts] parts, lo 0, hi hi]
(let [gap (/ (+ lo hi 1) 2)]
(cond
(nil? part) lo
(= part \F) (recur parts lo (dec gap))
(= part \L) (recur parts lo (dec gap))
(= part \B) (recur parts gap hi)
(= part \R) (recur parts gap hi))))))
(defn- get-id [pass]
(let [row (take 7 pass)
seat (drop 7 pass)]
(+ (* 8 (bin-partition row)) (bin-partition seat))))
(defn part-1
"Day 05 Part 1"
[input]
(->> input
str/split-lines
(map get-id)
sort
last))
(defn- find-gap [lst]
(let [[init & lst] lst]
(loop [[l & lst] lst, init init]
(cond
(nil? l) nil
(= (inc init) l) (recur lst l)
:else (dec l)))))
(defn part-2
"Day 05 Part 2"
[input]
(->> input
str/split-lines
(map get-id)
sort
find-gap))
|
|
6062a83adca258ad686ae8be0d1502d73094c60caa3b94eb733011f8ed9e1015
|
brite-code/brite
|
CLI.hs
|
module Brite.CLI (main) where
import Brite.Dev
import Brite.DiagnosticMarkup (toANSIDoc)
import Brite.Exception
import Brite.Project.Build (buildProject, buildProjectFiles)
import Brite.Project.Cache (withCache)
import Brite.Project.Files
import System.Directory (removeDirectoryRecursive)
import System.Environment
import System.Exit
import System.IO (stdout)
import Text.PrettyPrint.ANSI.Leijen (Doc)
import qualified Text.PrettyPrint.ANSI.Leijen as Doc
The main function for the Brite CLI .
main :: IO ()
main = do
args <- getArgs
exitWith =<< case parseArgs args of
Right command -> do
result <- catchEverything (execute command)
case result of
Left message -> displayDoc (errorMessage (toANSIDoc message)) *> return (ExitFailure 1)
Right exitCode -> return exitCode
Left arg -> do
displayDoc $
errorMessage
(Doc.text "Unrecognized argument " <>
Doc.bold (Doc.text arg) <>
Doc.text ". See below for the correct usage.") <>
Doc.hardline <>
helpMessage
return (ExitFailure 1)
-- Displays a pretty print ANSI document.
displayDoc :: Doc -> IO ()
displayDoc x = Doc.displayIO stdout (Doc.renderPretty 1 80 x)
{--------------------------------------------------------------------------------------------------}
{- Commands -}
{--------------------------------------------------------------------------------------------------}
A Brite command to be executed by the CLI .
data Command
-- An empty command means the user did not specify any command line arguments. Here we print out
-- the help message and return a failure exit code.
= EmptyCommand
-- If the user ran the help command then they are looking to see the help message. Here we print
-- out the help message and exit successfully.
| HelpCommand
If the user ran the “ new ” command then they want to create a new Brite project in the
-- provided directory.
| NewCommand
-- If the user ran the “build” command they want to build the provided file paths.
| BuildCommand [String]
-- If the user ran the “reset” command then we delete their cache and any generated resources.
| ResetCommand
-- Executes a command and returns an exit code.
execute :: Command -> IO ExitCode
-- An empty command will print out the help text and exit with a failure. We exit with a failure to
inform other CLI tools that this is not a correct usage of the Brite CLI .
execute EmptyCommand = do
displayDoc helpMessage
return (ExitFailure 1)
-- Print the help message and exit successfully.
execute HelpCommand = do
displayDoc helpMessage
return ExitSuccess
-- TODO: Actually implement the `new` command...
execute NewCommand = do
displayDoc (errorMessage (Doc.text "The `new` command is currently unimplemented."))
return (ExitFailure 1)
Build some Brite code !
--
-- If no source file paths were provided to the command then we will search for the project
-- directory in our current directory. If we find the project directory then we will build the
-- entire project.
--
-- If some source file paths were provided we will search for the project directory in our current
-- directory. Then we will convert all the paths we were provided into source file paths. Finally
-- we will build only those project files.
--
-- NOTE: The build command will accept files that don’t exist in the file system. This way you can
-- delete files from your cache that no longer exist in the file system.
--
-- TODO: Progress indicator showing how much work we’ve done so far in building the project. This
way Brite ’s not a black box . Also consider telling the user when we ’re retrying their
-- transaction? `withImmediateTransaction` has retry logic in case someone is trying to read from
-- the database while we’re trying to commit a large transaction. This could potentially take a long
-- time we should let the user know if it does.
execute (BuildCommand initialSourceFilePaths) =
if null initialSourceFilePaths then do
projectDirectory <- findProjectDirectoryOrThrow "."
withCache projectDirectory buildProject
return ExitSuccess
else do
projectDirectory <- findProjectDirectoryOrThrow "."
sourceFilePaths <- traverse (intoSourceFilePathOrThrow projectDirectory) initialSourceFilePaths
withCache projectDirectory (flip buildProjectFiles sourceFilePaths)
return ExitSuccess
-- Cleans the current project’s cache.
--
-- NOTE: We use the name `reset` instead of the traditional `clean` to imply this is a hard reset of
-- the programmer’s project. We’d prefer that the programmer does not run `reset` if possible since
-- that will delete their cache slowing down future builds. We’d prefer the user run `brite build`
-- to make sure all their files are rebuilt. `clean` implies that user is deleting generated
-- resources so re-generating those resources should not take more time, but in fact the resources
-- we delete when the programmer calls `brite reset` significantly improves the performance of
-- their builds.
execute ResetCommand = do
projectDirectory <- findProjectDirectoryOrThrow "."
projectCacheDirectory <- findProjectCacheDirectory projectDirectory
removeDirectoryRecursive projectCacheDirectory
return ExitSuccess
-- Parses a list of CLI arguments and returns either a command or an error. An error could be an
-- unrecognized argument, for instance.
parseArgs :: [String] -> Either String Command
parseArgs = loop EmptyCommand
where
-- If we see common help flags then the user is asking for the help command.
loop EmptyCommand ("-h" : args) = loop HelpCommand args
loop EmptyCommand ("--help" : args) = loop HelpCommand args
-- Parse the “new” command.
loop EmptyCommand ("new" : args) = loop NewCommand args
Parse a build command when we see the text ` build ` . Add every argument to our list of paths
-- that doesn’t start with `-`. When we reach the end of our arguments reverse the list of paths
-- since while parsing we added them in reverse.
loop EmptyCommand ("build" : args) = loop (BuildCommand []) args
loop (BuildCommand paths) (arg : args) | take 1 arg /= "-" = loop (BuildCommand (arg : paths)) args
loop (BuildCommand paths) [] = Right (BuildCommand (reverse paths))
-- Parse the “reset” command.
loop EmptyCommand ("reset" : args) = loop ResetCommand args
-- If no one handled this argument then we have an unexpected argument.
loop _ (arg : _) = Left arg
We successfully parsed a command ! ! Return it .
loop command [] = Right command
{--------------------------------------------------------------------------------------------------}
{- Messages -}
{--------------------------------------------------------------------------------------------------}
-- An operational error message logged by the CLI.
errorMessage :: Doc -> Doc
errorMessage x =
Doc.bold (Doc.red (Doc.text "Error:")) <> Doc.text " " <> x <> Doc.hardline
The help text for Brite . Prints a nice little box which is reminiscent of a postcard . Also allows
-- us to do clever work with alignment since we clearly have a left-hand-side.
helpMessage :: Doc
helpMessage =
Doc.black (Doc.text "┌" <> Doc.text (replicate 78 '─') <> Doc.text "┐") <> Doc.hardline <>
boxContent <>
Doc.black (Doc.text "└" <> Doc.text (replicate 78 '─') <> Doc.text "┘") <> Doc.hardline
where
boxContent = mconcat $
map
(\a ->
case a of
Nothing ->
Doc.black (Doc.text "│") <>
Doc.fill 78 mempty <>
Doc.black (Doc.text "│") <>
Doc.hardline
Just b ->
Doc.black (Doc.text "│") <>
Doc.fill 78 (Doc.text " " <> b) <>
Doc.black (Doc.text "│") <> Doc.hardline) $
[ Just $ Doc.bold (Doc.text "Brite")
, Just $ Doc.text "A tool for product development."
, Nothing
, Just $ Doc.bold (Doc.text "Usage:")
] ++
(map
(\(a, b) -> Just $
Doc.black (Doc.text "$") <>
Doc.text " " <>
Doc.fill 32 (Doc.text (if isDev then "brite-dev" else "brite") <> Doc.text " " <> Doc.text a) <>
Doc.black (Doc.text "# " <> Doc.text b))
[ ("new {name}", "Create a new Brite project.")
, ("build", "Build the code in your project.")
, ("build {path...}", "Build the code at these paths.")
-- TODO: Add format command. Also, combine `build` and `build {path...}` documentation.
-- NOTE: We intentionally don’t document `brite reset` here. We don’t want programmers
-- using `brite reset` except in dire circumstances where they absolutely need to reset
-- their project since `brite reset` throws away their cache which slows down everything.
-- We would prefer the user to run `brite build`.
])
| null |
https://raw.githubusercontent.com/brite-code/brite/154d7fc93be050626af48051f71a446ec329f612/old/src/Brite/CLI.hs
|
haskell
|
Displays a pretty print ANSI document.
------------------------------------------------------------------------------------------------
Commands
------------------------------------------------------------------------------------------------
An empty command means the user did not specify any command line arguments. Here we print out
the help message and return a failure exit code.
If the user ran the help command then they are looking to see the help message. Here we print
out the help message and exit successfully.
provided directory.
If the user ran the “build” command they want to build the provided file paths.
If the user ran the “reset” command then we delete their cache and any generated resources.
Executes a command and returns an exit code.
An empty command will print out the help text and exit with a failure. We exit with a failure to
Print the help message and exit successfully.
TODO: Actually implement the `new` command...
If no source file paths were provided to the command then we will search for the project
directory in our current directory. If we find the project directory then we will build the
entire project.
If some source file paths were provided we will search for the project directory in our current
directory. Then we will convert all the paths we were provided into source file paths. Finally
we will build only those project files.
NOTE: The build command will accept files that don’t exist in the file system. This way you can
delete files from your cache that no longer exist in the file system.
TODO: Progress indicator showing how much work we’ve done so far in building the project. This
transaction? `withImmediateTransaction` has retry logic in case someone is trying to read from
the database while we’re trying to commit a large transaction. This could potentially take a long
time we should let the user know if it does.
Cleans the current project’s cache.
NOTE: We use the name `reset` instead of the traditional `clean` to imply this is a hard reset of
the programmer’s project. We’d prefer that the programmer does not run `reset` if possible since
that will delete their cache slowing down future builds. We’d prefer the user run `brite build`
to make sure all their files are rebuilt. `clean` implies that user is deleting generated
resources so re-generating those resources should not take more time, but in fact the resources
we delete when the programmer calls `brite reset` significantly improves the performance of
their builds.
Parses a list of CLI arguments and returns either a command or an error. An error could be an
unrecognized argument, for instance.
If we see common help flags then the user is asking for the help command.
Parse the “new” command.
that doesn’t start with `-`. When we reach the end of our arguments reverse the list of paths
since while parsing we added them in reverse.
Parse the “reset” command.
If no one handled this argument then we have an unexpected argument.
------------------------------------------------------------------------------------------------
Messages
------------------------------------------------------------------------------------------------
An operational error message logged by the CLI.
us to do clever work with alignment since we clearly have a left-hand-side.
TODO: Add format command. Also, combine `build` and `build {path...}` documentation.
NOTE: We intentionally don’t document `brite reset` here. We don’t want programmers
using `brite reset` except in dire circumstances where they absolutely need to reset
their project since `brite reset` throws away their cache which slows down everything.
We would prefer the user to run `brite build`.
|
module Brite.CLI (main) where
import Brite.Dev
import Brite.DiagnosticMarkup (toANSIDoc)
import Brite.Exception
import Brite.Project.Build (buildProject, buildProjectFiles)
import Brite.Project.Cache (withCache)
import Brite.Project.Files
import System.Directory (removeDirectoryRecursive)
import System.Environment
import System.Exit
import System.IO (stdout)
import Text.PrettyPrint.ANSI.Leijen (Doc)
import qualified Text.PrettyPrint.ANSI.Leijen as Doc
The main function for the Brite CLI .
main :: IO ()
main = do
args <- getArgs
exitWith =<< case parseArgs args of
Right command -> do
result <- catchEverything (execute command)
case result of
Left message -> displayDoc (errorMessage (toANSIDoc message)) *> return (ExitFailure 1)
Right exitCode -> return exitCode
Left arg -> do
displayDoc $
errorMessage
(Doc.text "Unrecognized argument " <>
Doc.bold (Doc.text arg) <>
Doc.text ". See below for the correct usage.") <>
Doc.hardline <>
helpMessage
return (ExitFailure 1)
displayDoc :: Doc -> IO ()
displayDoc x = Doc.displayIO stdout (Doc.renderPretty 1 80 x)
A Brite command to be executed by the CLI .
data Command
= EmptyCommand
| HelpCommand
If the user ran the “ new ” command then they want to create a new Brite project in the
| NewCommand
| BuildCommand [String]
| ResetCommand
execute :: Command -> IO ExitCode
inform other CLI tools that this is not a correct usage of the Brite CLI .
execute EmptyCommand = do
displayDoc helpMessage
return (ExitFailure 1)
execute HelpCommand = do
displayDoc helpMessage
return ExitSuccess
execute NewCommand = do
displayDoc (errorMessage (Doc.text "The `new` command is currently unimplemented."))
return (ExitFailure 1)
Build some Brite code !
way Brite ’s not a black box . Also consider telling the user when we ’re retrying their
execute (BuildCommand initialSourceFilePaths) =
if null initialSourceFilePaths then do
projectDirectory <- findProjectDirectoryOrThrow "."
withCache projectDirectory buildProject
return ExitSuccess
else do
projectDirectory <- findProjectDirectoryOrThrow "."
sourceFilePaths <- traverse (intoSourceFilePathOrThrow projectDirectory) initialSourceFilePaths
withCache projectDirectory (flip buildProjectFiles sourceFilePaths)
return ExitSuccess
execute ResetCommand = do
projectDirectory <- findProjectDirectoryOrThrow "."
projectCacheDirectory <- findProjectCacheDirectory projectDirectory
removeDirectoryRecursive projectCacheDirectory
return ExitSuccess
parseArgs :: [String] -> Either String Command
parseArgs = loop EmptyCommand
where
loop EmptyCommand ("-h" : args) = loop HelpCommand args
loop EmptyCommand ("--help" : args) = loop HelpCommand args
loop EmptyCommand ("new" : args) = loop NewCommand args
Parse a build command when we see the text ` build ` . Add every argument to our list of paths
loop EmptyCommand ("build" : args) = loop (BuildCommand []) args
loop (BuildCommand paths) (arg : args) | take 1 arg /= "-" = loop (BuildCommand (arg : paths)) args
loop (BuildCommand paths) [] = Right (BuildCommand (reverse paths))
loop EmptyCommand ("reset" : args) = loop ResetCommand args
loop _ (arg : _) = Left arg
We successfully parsed a command ! ! Return it .
loop command [] = Right command
errorMessage :: Doc -> Doc
errorMessage x =
Doc.bold (Doc.red (Doc.text "Error:")) <> Doc.text " " <> x <> Doc.hardline
The help text for Brite . Prints a nice little box which is reminiscent of a postcard . Also allows
helpMessage :: Doc
helpMessage =
Doc.black (Doc.text "┌" <> Doc.text (replicate 78 '─') <> Doc.text "┐") <> Doc.hardline <>
boxContent <>
Doc.black (Doc.text "└" <> Doc.text (replicate 78 '─') <> Doc.text "┘") <> Doc.hardline
where
boxContent = mconcat $
map
(\a ->
case a of
Nothing ->
Doc.black (Doc.text "│") <>
Doc.fill 78 mempty <>
Doc.black (Doc.text "│") <>
Doc.hardline
Just b ->
Doc.black (Doc.text "│") <>
Doc.fill 78 (Doc.text " " <> b) <>
Doc.black (Doc.text "│") <> Doc.hardline) $
[ Just $ Doc.bold (Doc.text "Brite")
, Just $ Doc.text "A tool for product development."
, Nothing
, Just $ Doc.bold (Doc.text "Usage:")
] ++
(map
(\(a, b) -> Just $
Doc.black (Doc.text "$") <>
Doc.text " " <>
Doc.fill 32 (Doc.text (if isDev then "brite-dev" else "brite") <> Doc.text " " <> Doc.text a) <>
Doc.black (Doc.text "# " <> Doc.text b))
[ ("new {name}", "Create a new Brite project.")
, ("build", "Build the code in your project.")
, ("build {path...}", "Build the code at these paths.")
])
|
331321431306e09e92d43101589e293e9ecfb29e39e0bc2d1e0c1b7aeb2fe528
|
frenchy64/fully-satisfies
|
test.clj
|
Copyright ( c ) . All rights reserved .
; The use and distribution terms for this software are covered by the
; Eclipse Public License 1.0 (-1.0.php)
; which can be found in the file epl-v10.html at the root of this distribution.
; By using this software in any fashion, you are agreeing to be bound by
; the terms of this license.
; You must not remove this notice, or any other, from this software.
(ns io.github.frenchy64.fully-satisfies.non-leaky-macros.clojure.test
"Implementations of clojure.test macros that don't leak implementation details."
(:require [clojure.test :as ct]))
(defmacro non-leaky-with-test-out
"Like clojure.test/with-test-out, except body does not leak try/catch syntax."
[& body]
`(ct/with-test-out
(do ~@body)))
(defmacro with-test-out
[& body]
`(non-leaky-with-test-out ~@body))
(defmacro non-leaky-testing
"Like clojure.test/testing, except body does not leak try/catch syntax."
[string & body]
`(ct/testing ~string
(do ~@body)))
(defmacro testing
[& args]
`(non-leaky-testing ~@args))
(defmacro non-leaky-deftest
"Like clojure.test/deftest, except body does not have access to a recur target."
[name & body]
`(ct/deftest ~name
(let [res# (do ~@body)]
res#)))
(defmacro deftest
[& args]
`(non-leaky-deftest ~@args))
(defmacro non-leaky-deftest-
"Like clojure.test/deftest-, except body does not have access to a recur target."
[name & body]
`(ct/deftest- ~name
(let [res# (do ~@body)]
res#)))
(defmacro deftest-
[& args]
`(non-leaky-deftest- ~@args))
(defmacro non-leaky-with-test
"Like clojure.test/with-test, except body does not have access to a recur target."
[definition & body]
`(ct/with-test ~definition
(let [res# (do ~@body)]
res#)))
(defmacro with-test
[& args]
`(non-leaky-with-test ~@args))
(defmacro non-leaky-set-test
"Like clojure.test/set-test, except body does not have access to a recur target."
[name & body]
`(ct/set-test ~name
(let [res# (do ~@body)]
res#)))
(defmacro set-test
[& args]
`(non-leaky-set-test ~@args))
| null |
https://raw.githubusercontent.com/frenchy64/fully-satisfies/c51413a17c432710b81cb05af19ce595803b8de2/src/io/github/frenchy64/fully_satisfies/non_leaky_macros/clojure/test.clj
|
clojure
|
The use and distribution terms for this software are covered by the
Eclipse Public License 1.0 (-1.0.php)
which can be found in the file epl-v10.html at the root of this distribution.
By using this software in any fashion, you are agreeing to be bound by
the terms of this license.
You must not remove this notice, or any other, from this software.
|
Copyright ( c ) . All rights reserved .
(ns io.github.frenchy64.fully-satisfies.non-leaky-macros.clojure.test
"Implementations of clojure.test macros that don't leak implementation details."
(:require [clojure.test :as ct]))
(defmacro non-leaky-with-test-out
"Like clojure.test/with-test-out, except body does not leak try/catch syntax."
[& body]
`(ct/with-test-out
(do ~@body)))
(defmacro with-test-out
[& body]
`(non-leaky-with-test-out ~@body))
(defmacro non-leaky-testing
"Like clojure.test/testing, except body does not leak try/catch syntax."
[string & body]
`(ct/testing ~string
(do ~@body)))
(defmacro testing
[& args]
`(non-leaky-testing ~@args))
(defmacro non-leaky-deftest
"Like clojure.test/deftest, except body does not have access to a recur target."
[name & body]
`(ct/deftest ~name
(let [res# (do ~@body)]
res#)))
(defmacro deftest
[& args]
`(non-leaky-deftest ~@args))
(defmacro non-leaky-deftest-
"Like clojure.test/deftest-, except body does not have access to a recur target."
[name & body]
`(ct/deftest- ~name
(let [res# (do ~@body)]
res#)))
(defmacro deftest-
[& args]
`(non-leaky-deftest- ~@args))
(defmacro non-leaky-with-test
"Like clojure.test/with-test, except body does not have access to a recur target."
[definition & body]
`(ct/with-test ~definition
(let [res# (do ~@body)]
res#)))
(defmacro with-test
[& args]
`(non-leaky-with-test ~@args))
(defmacro non-leaky-set-test
"Like clojure.test/set-test, except body does not have access to a recur target."
[name & body]
`(ct/set-test ~name
(let [res# (do ~@body)]
res#)))
(defmacro set-test
[& args]
`(non-leaky-set-test ~@args))
|
67510bff547d46be549e453f5a545ecc39caf919eea4705305c8315bc55449eb
|
stassats/lisp-bots
|
xml-paste.lisp
|
(in-package :lisppaste)
(defun ip-to-string (ip)
(when ip
(format nil "~{~A~^.~}" (coerce ip 'list))))
(defun paste-xml-list (paste &optional contents)
; (format t "collecting paste number ~A~%" (paste-number paste))
(list* (paste-number paste)
(s-xml-rpc:xml-rpc-time (paste-universal-time paste))
(paste-user paste)
(paste-channel paste)
(paste-title paste)
(length (paste-annotations paste))
(if contents
(list (remove #\return (paste-contents paste))))))
(defun xmlrpc-method-newpaste (args)
(flet ((fail (reason)
(return-from xmlrpc-method-newpaste reason)))
(format *trace-output* "Looking for ~S~%" (ip-to-string s-xml-rpc:*xml-peer-address*))
(unless (paste-allowed-from-ip-p (ip-to-string s-xml-rpc:*xml-peer-address*))
(fail "Naughty boy!"))
(destructuring-bind
(paste-channel paste-user paste-title paste-contents
&optional annotate-or-colorize-as) args
;; Why not (every (lambda (s) (and (stringp s) (> (length s) 0))) ...)?
(unless (every #'stringp (list paste-channel paste-user
paste-title paste-contents))
(fail "Error: all arguments must be strings."))
(unless (every (lambda (s) (> (length s) 0))
(list paste-channel paste-user
paste-title paste-contents))
(fail "Error: all arguments must be non-empty strings."))
(unless (<= (length paste-contents)
*paste-maximum-size*)
(fail "Error: paste too large."))
(let* ((annotate (if (numberp annotate-or-colorize-as) annotate-or-colorize-as))
(colorize-as (if (stringp annotate-or-colorize-as) annotate-or-colorize-as ""))
(annotate-this (if annotate (find-paste annotate)))
(paste-contents (remove #\return paste-contents)))
(when (and annotate (not annotate-this))
(fail "Error: bad annotation number."))
(unless (if annotate-this
(string-equal paste-channel (paste-channel annotate-this))
(member paste-channel *channels* :test #'string-equal))
(fail (format nil "Error: invalid channel ~S." paste-channel)))
(when (some (lambda (regexp)
(or (cl-ppcre:scan regexp paste-contents)
(cl-ppcre:scan regexp paste-title)
(cl-ppcre:scan regexp paste-user))) *banned-content-regexps*)
(format *trace-output* "Banned content from ~S~%" (ip-to-string s-xml-rpc:*xml-peer-address*))
(when s-xml-rpc:*xml-peer-address*
(ban-ip (ip-to-string s-xml-rpc:*xml-peer-address*)))
(fail "Naughty boy!"))
(let ((paste (make-new-paste annotate-this
:user paste-user
:title paste-title
:contents paste-contents
:channel paste-channel
:colorization-mode colorize-as)))
(log-new-paste (ip-to-string s-xml-rpc:*xml-peer-address*)
(paste-number paste) annotate paste-title)
(format nil "Your paste has been announced to ~A and is available at ~A ."
paste-channel (paste-display-url paste)))))))
(defun xmlrpc-method-pasteheaders (args)
(destructuring-bind
(length &optional supplied-start) args
(mapcar #'paste-xml-list
(list-pastes :starting-from supplied-start
:limit length))))
(defun xmlrpc-method-pasteheadersbychannel (args)
(destructuring-bind
(channel length &optional supplied-start) args
(mapcar #'paste-xml-list
(list-pastes :in-channel channel
:starting-from supplied-start
:limit length))))
(defun xmlrpc-method-pasteannotationheaders (args)
(nreverse
(mapcar #'paste-xml-list
(paste-annotations (find-paste (car args))))))
(defun xmlrpc-method-pastedetails (args)
(destructuring-bind
(paste-number &optional annotation) args
(let ((paste (find-paste paste-number)))
(if (not annotation)
(paste-xml-list paste t)
(paste-xml-list (find annotation
(paste-annotations paste)
:key #'paste-number :test #'eql)
t)))))
(defun xmlrpc-method-listchannels (args)
*channels*)
(defparameter *xmlrpc-methods*
'(("newpaste" xmlrpc-method-newpaste)
("pasteheaders" xmlrpc-method-pasteheaders)
("pasteheadersbychannel" xmlrpc-method-pasteheadersbychannel)
("pasteannotationheaders" xmlrpc-method-pasteannotationheaders)
("pastedetails" xmlrpc-method-pastedetails)
("listchannels" xmlrpc-method-listchannels)))
(defun xmlrpc-dispatch-method (method-name &rest args)
(format t "Handling XML-RPC request for ~S from ~S~%" method-name s-xml-rpc:*xml-peer-address*)
(handler-bind
((condition #'(lambda (c)
(return-from xmlrpc-dispatch-method
(format nil "Error encountered: ~S" c)))))
(if (find (ip-to-string s-xml-rpc:*xml-peer-address*)
*banned-ips* :test #'equal)
"Naughty boy!"
(let ((method (find method-name *xmlrpc-methods*
:test #'string-equal
:key #'car)))
(if method
(funcall (cadr method) args)
(format nil "Error: unimplemented method ~S." method-name))))))
(setf s-xml-rpc:*xml-rpc-call-hook* #'xmlrpc-dispatch-method)
| null |
https://raw.githubusercontent.com/stassats/lisp-bots/09bfce724afd20c91a08acde8816be6faf5f54b2/xml-paste.lisp
|
lisp
|
(format t "collecting paste number ~A~%" (paste-number paste))
Why not (every (lambda (s) (and (stringp s) (> (length s) 0))) ...)?
|
(in-package :lisppaste)
(defun ip-to-string (ip)
(when ip
(format nil "~{~A~^.~}" (coerce ip 'list))))
(defun paste-xml-list (paste &optional contents)
(list* (paste-number paste)
(s-xml-rpc:xml-rpc-time (paste-universal-time paste))
(paste-user paste)
(paste-channel paste)
(paste-title paste)
(length (paste-annotations paste))
(if contents
(list (remove #\return (paste-contents paste))))))
(defun xmlrpc-method-newpaste (args)
(flet ((fail (reason)
(return-from xmlrpc-method-newpaste reason)))
(format *trace-output* "Looking for ~S~%" (ip-to-string s-xml-rpc:*xml-peer-address*))
(unless (paste-allowed-from-ip-p (ip-to-string s-xml-rpc:*xml-peer-address*))
(fail "Naughty boy!"))
(destructuring-bind
(paste-channel paste-user paste-title paste-contents
&optional annotate-or-colorize-as) args
(unless (every #'stringp (list paste-channel paste-user
paste-title paste-contents))
(fail "Error: all arguments must be strings."))
(unless (every (lambda (s) (> (length s) 0))
(list paste-channel paste-user
paste-title paste-contents))
(fail "Error: all arguments must be non-empty strings."))
(unless (<= (length paste-contents)
*paste-maximum-size*)
(fail "Error: paste too large."))
(let* ((annotate (if (numberp annotate-or-colorize-as) annotate-or-colorize-as))
(colorize-as (if (stringp annotate-or-colorize-as) annotate-or-colorize-as ""))
(annotate-this (if annotate (find-paste annotate)))
(paste-contents (remove #\return paste-contents)))
(when (and annotate (not annotate-this))
(fail "Error: bad annotation number."))
(unless (if annotate-this
(string-equal paste-channel (paste-channel annotate-this))
(member paste-channel *channels* :test #'string-equal))
(fail (format nil "Error: invalid channel ~S." paste-channel)))
(when (some (lambda (regexp)
(or (cl-ppcre:scan regexp paste-contents)
(cl-ppcre:scan regexp paste-title)
(cl-ppcre:scan regexp paste-user))) *banned-content-regexps*)
(format *trace-output* "Banned content from ~S~%" (ip-to-string s-xml-rpc:*xml-peer-address*))
(when s-xml-rpc:*xml-peer-address*
(ban-ip (ip-to-string s-xml-rpc:*xml-peer-address*)))
(fail "Naughty boy!"))
(let ((paste (make-new-paste annotate-this
:user paste-user
:title paste-title
:contents paste-contents
:channel paste-channel
:colorization-mode colorize-as)))
(log-new-paste (ip-to-string s-xml-rpc:*xml-peer-address*)
(paste-number paste) annotate paste-title)
(format nil "Your paste has been announced to ~A and is available at ~A ."
paste-channel (paste-display-url paste)))))))
(defun xmlrpc-method-pasteheaders (args)
(destructuring-bind
(length &optional supplied-start) args
(mapcar #'paste-xml-list
(list-pastes :starting-from supplied-start
:limit length))))
(defun xmlrpc-method-pasteheadersbychannel (args)
(destructuring-bind
(channel length &optional supplied-start) args
(mapcar #'paste-xml-list
(list-pastes :in-channel channel
:starting-from supplied-start
:limit length))))
(defun xmlrpc-method-pasteannotationheaders (args)
(nreverse
(mapcar #'paste-xml-list
(paste-annotations (find-paste (car args))))))
(defun xmlrpc-method-pastedetails (args)
(destructuring-bind
(paste-number &optional annotation) args
(let ((paste (find-paste paste-number)))
(if (not annotation)
(paste-xml-list paste t)
(paste-xml-list (find annotation
(paste-annotations paste)
:key #'paste-number :test #'eql)
t)))))
(defun xmlrpc-method-listchannels (args)
*channels*)
(defparameter *xmlrpc-methods*
'(("newpaste" xmlrpc-method-newpaste)
("pasteheaders" xmlrpc-method-pasteheaders)
("pasteheadersbychannel" xmlrpc-method-pasteheadersbychannel)
("pasteannotationheaders" xmlrpc-method-pasteannotationheaders)
("pastedetails" xmlrpc-method-pastedetails)
("listchannels" xmlrpc-method-listchannels)))
(defun xmlrpc-dispatch-method (method-name &rest args)
(format t "Handling XML-RPC request for ~S from ~S~%" method-name s-xml-rpc:*xml-peer-address*)
(handler-bind
((condition #'(lambda (c)
(return-from xmlrpc-dispatch-method
(format nil "Error encountered: ~S" c)))))
(if (find (ip-to-string s-xml-rpc:*xml-peer-address*)
*banned-ips* :test #'equal)
"Naughty boy!"
(let ((method (find method-name *xmlrpc-methods*
:test #'string-equal
:key #'car)))
(if method
(funcall (cadr method) args)
(format nil "Error: unimplemented method ~S." method-name))))))
(setf s-xml-rpc:*xml-rpc-call-hook* #'xmlrpc-dispatch-method)
|
cd6cc32bd91de64c76285601e6ed186db556a7b3ba4a049babd38b064410c5fc
|
witan-org/witan
|
sysutil.mli
|
(********************************************************************)
(* *)
The Why3 Verification Platform / The Why3 Development Team
Copyright 2010 - 2017 -- INRIA - CNRS - Paris - Sud University
(* *)
(* This software is distributed under the terms of the GNU Lesser *)
General Public License version 2.1 , with the special exception
(* on linking described in file LICENSE. *)
(* *)
(********************************************************************)
(* create a backup copy of a file if it exists *)
val backup_file : string -> unit
(* return the content of an in-channel *)
val channel_contents : in_channel -> string
(* return the content of an in_channel in a buffer *)
val channel_contents_buf : in_channel -> Buffer.t
(* put the content of an in_channel in a formatter *)
val channel_contents_fmt : in_channel -> Format.formatter -> unit
(* fold on the line of a file *)
val fold_channel : ('a -> string -> 'a) -> 'a -> in_channel -> 'a
(* return the content of a file *)
val file_contents : string -> string
(* return the content of a file in a buffer *)
val file_contents_buf : string -> Buffer.t
(* put the content of a file in a formatter *)
val file_contents_fmt : string -> Format.formatter -> unit
val open_temp_file :
?debug:bool -> (* don't remove the file *)
string -> (string -> out_channel -> 'a) -> 'a
open_temp_file suffix usefile
Create a temporary file with suffix suffix ,
and call usefile on this file ( filename and ) .
usefile can close the file
Create a temporary file with suffix suffix,
and call usefile on this file (filename and open_out).
usefile can close the file *)
val copy_file : string -> string -> unit
(** [copy_file from to] copy the file from [from] to [to] *)
val copy_dir : string -> string -> unit
(** [copy_dir from to] copy the directory recursively from [from] to [to],
currently the directory must contains only directories and common files
*)
val path_of_file : string -> string list
(** [path_of_file filename] return the absolute path of [filename] *)
val relativize_filename : string -> string -> string
(** [relativize_filename base filename] relativize the filename
[filename] according to [base] *)
val absolutize_filename : string -> string -> string
(** [absolutize_filename base filename] absolutize the filename
[filename] according to [base] *)
val uniquify : string -> string
(** find filename that doesn't exists based on the given filename.
Be careful the file can be taken after the return of this function.
*)
| null |
https://raw.githubusercontent.com/witan-org/witan/d26f9f810fc34bf44daccb91f71ad3258eb62037/src/popop_lib/sysutil.mli
|
ocaml
|
******************************************************************
This software is distributed under the terms of the GNU Lesser
on linking described in file LICENSE.
******************************************************************
create a backup copy of a file if it exists
return the content of an in-channel
return the content of an in_channel in a buffer
put the content of an in_channel in a formatter
fold on the line of a file
return the content of a file
return the content of a file in a buffer
put the content of a file in a formatter
don't remove the file
* [copy_file from to] copy the file from [from] to [to]
* [copy_dir from to] copy the directory recursively from [from] to [to],
currently the directory must contains only directories and common files
* [path_of_file filename] return the absolute path of [filename]
* [relativize_filename base filename] relativize the filename
[filename] according to [base]
* [absolutize_filename base filename] absolutize the filename
[filename] according to [base]
* find filename that doesn't exists based on the given filename.
Be careful the file can be taken after the return of this function.
|
The Why3 Verification Platform / The Why3 Development Team
Copyright 2010 - 2017 -- INRIA - CNRS - Paris - Sud University
General Public License version 2.1 , with the special exception
val backup_file : string -> unit
val channel_contents : in_channel -> string
val channel_contents_buf : in_channel -> Buffer.t
val channel_contents_fmt : in_channel -> Format.formatter -> unit
val fold_channel : ('a -> string -> 'a) -> 'a -> in_channel -> 'a
val file_contents : string -> string
val file_contents_buf : string -> Buffer.t
val file_contents_fmt : string -> Format.formatter -> unit
val open_temp_file :
string -> (string -> out_channel -> 'a) -> 'a
open_temp_file suffix usefile
Create a temporary file with suffix suffix ,
and call usefile on this file ( filename and ) .
usefile can close the file
Create a temporary file with suffix suffix,
and call usefile on this file (filename and open_out).
usefile can close the file *)
val copy_file : string -> string -> unit
val copy_dir : string -> string -> unit
val path_of_file : string -> string list
val relativize_filename : string -> string -> string
val absolutize_filename : string -> string -> string
val uniquify : string -> string
|
e99327e34fc934093e4b93e58f4f2db185086b2d02db18c2e193d56c31ec9b2b
|
hipsleek/hipsleek
|
cvpermUtils.ml
|
#include "xdebug.cppo"
open VarGen
open Gen
open Globals
open Cpure
let remove_dups = Gen.BList.remove_dups_eq eq_spec_var_ident
let check_dups = Gen.BList.check_dups_eq eq_spec_var_ident
let diff = Gen.BList.difference_eq eq_spec_var_ident
let intersect = Gen.BList.intersect_eq eq_spec_var_ident
let overlap = Gen.BList.overlap_eq eq_spec_var_ident
let mem = Gen.BList.mem_eq eq_spec_var_ident
(* To store vperm of variables *)
type vperm_sets = {
vperm_unprimed_flag: bool;
vperm_is_false : bool;
vperm_zero_vars: spec_var list;
vperm_lend_vars: spec_var list;
vperm_value_vars: spec_var list;
vperm_full_vars: spec_var list;
(* vperm_frac_vars: (Frac.frac * spec_var list) list; *)
vperm_frac_vars: (Frac.frac * spec_var) list; (*simpler*)
}
let print_vperm_sets = ref (fun (vps: vperm_sets) -> "vperm_sets printer has not been initialized")
(* unused cos of ivperm? *)
let build_vperm ?zero:(zero=[]) ?lend:(lend=[]) ?value:(value=[])
?frac:(frac=[]) full
=
let cnt = (List.length zero) + (List.length lend) + (List.length value) + (List.length frac) + (List.length full) in
{
vperm_unprimed_flag = if cnt=0 then true else false;
vperm_is_false = false;
vperm_zero_vars = List.map sp_rm_prime zero;
vperm_lend_vars = List.map sp_rm_prime lend;
vperm_value_vars = List.map sp_rm_prime value;
vperm_full_vars = List.map sp_rm_prime full;
vperm_frac_vars = List.map (fun (a,v) -> (a,sp_rm_prime v)) frac;
}
let vperm_unprime vp = { vp with vperm_unprimed_flag = false}
let vperm_rm_prime vp = vp
if vp.vperm_unprimed_flag then vp
(* else *)
(* { vp with *)
(* vperm_unprimed_flag = true; *)
vperm_zero_vars = List.map sp_rm_prime vp.vperm_zero_vars ;
vperm_lend_vars = ;
vperm_value_vars = List.map sp_rm_prime vp.vperm_value_vars ;
vperm_full_vars = List.map sp_rm_prime vp.vperm_full_vars ;
vperm_frac_vars = List.map ( fun ( a , vs ) - > ( a , sp_rm_prime vs ) ) vp.vperm_frac_vars ;
(* } *)
(* let vperm_rm_prime vps = *)
(* let pr = !print_vperm_sets in *)
Debug.no_1 " vperm_rm_prime " pr pr
ZH : it is redundant ?
let vperm_rm_prime vp =
if vp.vperm_unprimed_flag then vp
else vperm_rm_prime vp
let empty_vperm_sets = build_vperm []
let is_empty_frac fr =
let xs = ( fun ( f , _ ) - > not(Frac.is_zero f ) ) fr in
(* is_empty xs *)
List.for_all (fun (f,_) -> Frac.is_zero f) fr
let is_empty_vperm_sets vps =
not (!Globals.ann_vp) ||
((is_empty vps.vperm_full_vars) &&
(is_empty vps.vperm_lend_vars) &&
(is_empty vps.vperm_value_vars) &&
(* (is_empty vps.vperm_zero_vars) && *)
(is_empty_frac vps.vperm_frac_vars))
let is_empty_frac_leak fr =
let xs = ( fun ( f , _ ) - > not(Frac.is_zero f || Frac.is_value f ) ) fr in
(* is_empty xs *)
List.for_all (fun (f,_) -> Frac.is_zero f || Frac.is_value f) fr
WN : need to filter frac list
let is_leak_vperm vps =
match vps with
| { vperm_full_vars = full; vperm_frac_vars = frac } ->
not(is_empty full) || not(is_empty_frac_leak frac)
let rec partition_by_key key_of key_eq ls =
match ls with
| [] -> []
| e::es ->
let ke = key_of e in
let same_es, other_es = List.partition (fun e -> key_eq ke (key_of e)) es in
(ke, e::same_es)::(partition_by_key key_of key_eq other_es)
let is_Zero ann =
match ann with
| VP_Zero -> true
| VP_Frac f -> Frac.is_zero f
| _ -> false
let norm_frac_list xs =
let rec aux xs fr sv =
match xs with
| [] -> [(fr,sv)]
| (fr2,sv2)::xs ->
if eq_spec_var_ident sv sv2 then aux xs (Frac.add fr fr2) sv
else (fr,sv)::(aux xs fr2 sv2)
in match xs with
| [] -> []
| (fr,sv)::xs -> aux xs fr sv
let norm_frac_list frac_vars =
let frac_vars = List.sort (fun (_,sv1) (_,sv2) ->
String.compare (get_unprime sv1) (get_unprime sv2)) frac_vars in
let frac_vars2 = norm_frac_list frac_vars in
frac_vars2
let check_dupl svl =
let rec aux svl p =
match svl with
| [] -> false
| v::vs -> if eq_spec_var_ident p v then true else aux vs v
in match svl with
| [] -> false
| v::vs -> aux vs v
let norm_list svl =
let svl2 = List.sort (fun v1 v2 -> String.compare (get_unprime v1) (get_unprime v2)) svl in
(svl2,check_dupl svl2)
let check_dupl_two s1 s2 =
let rec aux s1 s2 =
match s1,s2 with
| [],_ -> false
| _,[] -> false
| (v1::t1),(v2::t2) ->
let c = String.compare (get_unprime v1) (get_unprime v2) in
if c=0 then true
else if c<0 then aux t1 s2
else aux s1 t2 in
aux s1 s2
let norm_full_value full value =
let svl1,f1 = norm_list full in
let svl2,f2 = norm_list value in
let f = f1||f2 in
if f then (svl1,svl2,f)
else (svl1,svl2,check_dupl_two svl1 svl2)
let is_frac_false xs =
List.exists (Frac.is_false) (List.map fst xs)
let frac_vars =
( fun ( f , v ) - > not(Frac.is_zero f ) ) frac_vars
let is_false_frac_other frac_vars full_vars value_vars =
let vs = full_vars@value_vars in
List.exists (fun (f,v) -> not(Frac.is_zero f) && mem v vs) frac_vars
let norm_vperm_sets vps =
let vps = vperm_rm_prime vps in
let (full_vars,value_vars,flag1) = norm_full_value vps.vperm_full_vars vps.vperm_value_vars in
let zero_vars = remove_dups vps.vperm_zero_vars in (* @zero[x] * @zero[x] -> @zero[x] *)
let lend_vars = remove_dups vps.vperm_lend_vars in (* @lend[x] * @lend[x] -> @lend[x] *)
let full_vars = ( \ * remove_dups * \ ) vps.vperm_full_vars in ( \ * ] * @full[x ] - > false * \ )
let frac_vars2 = norm_frac_list vps.vperm_frac_vars in
let false_flag = flag1 || (is_frac_false frac_vars2)
|| (is_false_frac_other frac_vars2 full_vars value_vars) in
WN : need to check if below correct !
(* let frac_vars_set = List.map (fun (frac, group) -> *)
let m_group = List.concat ( List.map snd group ) in
(* (frac, m_group)) group_frac_vars_sets *)
{ vps with
vperm_full_vars = full_vars;
vperm_is_false = false_flag;
vperm_lend_vars = diff lend_vars full_vars; (* TO FIX Value? *)
vperm_value_vars = value_vars;
vperm_zero_vars = diff zero_vars (full_vars @ lend_vars);
vperm_frac_vars = frac_vars2; }
let norm_vperm_sets vps =
if not (!Globals.ann_vp) then vps
else
let pr = !print_vperm_sets in
Debug.no_1 "norm_vperm_sets" pr pr norm_vperm_sets vps
let quick_is_false vps = vps.vperm_is_false
let merge_vperm_sets vps_list =
if not (!Globals.ann_vp) then empty_vperm_sets
else
let rec helper vps_list =
match vps_list with
| [] -> empty_vperm_sets
| v::vs ->
let mvs = helper vs in
{
vperm_unprimed_flag = (v.vperm_unprimed_flag && mvs.vperm_unprimed_flag);
vperm_is_false = v.vperm_is_false || mvs.vperm_is_false;
vperm_zero_vars = v.vperm_zero_vars @ mvs.vperm_zero_vars;
vperm_lend_vars = v.vperm_lend_vars @ mvs.vperm_lend_vars;
vperm_value_vars = v.vperm_value_vars @ mvs.vperm_value_vars;
vperm_full_vars = v.vperm_full_vars @ mvs.vperm_full_vars;
vperm_frac_vars = v.vperm_frac_vars @ mvs.vperm_frac_vars; }
in norm_vperm_sets (helper vps_list)
let merge_vperm_sets vps_list =
let vps_list = List.filter (fun x -> not (is_empty_vperm_sets x)) vps_list in
if (List.length vps_list)<=1 then merge_vperm_sets vps_list
else
let pr = !print_vperm_sets in
Debug.no_1 "merge_vperm_sets" (pr_list pr) pr merge_vperm_sets vps_list
@full[x ] * ] - > ERR
(* @full[x] * @lend[x] -> ERR *)
(* @full[x] * @zero[x] -> @full[x] *)
(* @lend[x] * @lend[x] -> @lend[x] => remove_dups *)
(* @lend[x] * @zero[x] -> @lend[x] *)
(* @zero[x] * @zero[x] -> @zero[x] => remove_dups *)
let combine_vperm_sets vps_list =
if not (!Globals.ann_vp) then empty_vperm_sets
else
let rec helper vps_list =
match vps_list with
| [] -> empty_vperm_sets
| v::vs ->
let v = vperm_rm_prime v in
let mvs = helper vs in
{
vperm_unprimed_flag = (v.vperm_unprimed_flag && mvs.vperm_unprimed_flag);
vperm_is_false = v.vperm_is_false || mvs.vperm_is_false;
vperm_zero_vars = v.vperm_zero_vars @ mvs.vperm_zero_vars;
vperm_lend_vars = v.vperm_lend_vars @ mvs.vperm_lend_vars;
vperm_value_vars = v.vperm_value_vars @ mvs.vperm_value_vars;
vperm_full_vars = v.vperm_full_vars @ mvs.vperm_full_vars;
vperm_frac_vars = norm_frac_list (v.vperm_frac_vars @ mvs.vperm_frac_vars); }
in
let comb_vps = helper vps_list in
let full_vars = comb_vps.vperm_full_vars in
let lend_vars = comb_vps.vperm_lend_vars in
let zero_vars = comb_vps.vperm_zero_vars in
let msg = "Combination of vperm sets causes contradiction" in
let err = ({ Error.error_loc = proving_loc # get; Error.error_text = msg }) in
let ( ) = x_binfo_pp " inside combine_vperm_sets " no_pos in
if (check_dups full_vars) (* || (overlap full_vars lend_vars) *)
then Error.report_error err
else
{ comb_vps with
vperm_zero_vars = remove_dups (diff zero_vars (full_vars @ lend_vars));
vperm_lend_vars = remove_dups lend_vars; }
let combine_vperm_sets vps_list =
let vps_list = List.filter (fun x -> not (is_empty_vperm_sets x)) vps_list in
if (List.length vps_list)<=1 then combine_vperm_sets vps_list
else
let pr = !print_vperm_sets in
Debug.no_1 "combine_vperm_sets" (pr_list pr) pr combine_vperm_sets vps_list
@full[x ] or ] - > @full[x ]
(* @full[x] or @lend[x] -> @lend[x] *)
(* @full[x] or @zero[x] -> @zero[x] *)
(* @lend[x] or @lend[x] -> @lend[x] *)
(* @lend[x] or @zero[x] -> @zero[x] *)
(* @zero[x] or @zero[x] -> @zero[x] *)
(* this method loses too much information ; it should not be used *)
let combine_or_vperm_sets vps1 vps2 =
let f1, f2 = vps1.vperm_full_vars, vps2.vperm_full_vars in
let l1, l2 = vps1.vperm_lend_vars, vps2.vperm_lend_vars in
let z1, z2 = vps1.vperm_zero_vars, vps2.vperm_zero_vars in
let v1, v2 = f1 @ l1 @ z1, f2 @ l2 @ z2 in
let alone_vars = diff (v1 @ v2) (intersect v1 v2) in
let z = remove_dups (z1 @ z2 @ alone_vars) in
let l = remove_dups (diff (l1 @ l2) z) in
let f = remove_dups (diff (f1 @ f2) (l @ z)) in
{
vperm_unprimed_flag = (vps1.vperm_unprimed_flag && vps2.vperm_unprimed_flag);
vperm_is_false = vps1.vperm_is_false && vps2.vperm_is_false;
vperm_zero_vars = z;
vperm_lend_vars = l;
vperm_full_vars = f;
TODO
TODO
let vperm_sets_of_anns ann_list =
let rec helper ann_list =
match ann_list with
| [] -> empty_vperm_sets
| (ann, svl)::vs ->
let mvs = helper vs in
match ann with
| VP_Zero -> { mvs with vperm_zero_vars = mvs.vperm_zero_vars @ svl; }
| VP_Full -> { mvs with vperm_full_vars = mvs.vperm_full_vars @ svl; }
| VP_Value -> { mvs with vperm_value_vars = mvs.vperm_value_vars @ svl; }
| VP_Lend -> { mvs with vperm_lend_vars = mvs.vperm_lend_vars @ svl; }
| VP_Frac frac -> { mvs with vperm_frac_vars = mvs.vperm_frac_vars @ (List.map (fun v -> (frac, v)) svl); }
in norm_vperm_sets (helper ann_list)
(* This seems to be removing vps of some ids *)
let clear_vperm_sets ann_list vps =
let rec helper ann_list =
match ann_list with
| [] -> vps
| (ann, svl)::vs ->
let cvs = helper vs in
match ann with
| VP_Zero -> { cvs with vperm_zero_vars = diff cvs.vperm_zero_vars svl; }
| VP_Full -> { cvs with vperm_full_vars = diff cvs.vperm_full_vars svl; }
| VP_Value -> { cvs with vperm_value_vars = diff cvs.vperm_value_vars svl; }
| VP_Lend -> { cvs with vperm_lend_vars = diff cvs.vperm_lend_vars svl; }
| VP_Frac frac -> { cvs with vperm_frac_vars =
TODO : WN
let frac_sets , others = List.partition ( fun ( f , _ ) - >
Frac.eq_frac f frac ) cvs.vperm_frac_vars in
let frac_svl = List.concat ( List.map snd frac_sets ) in
(* let frac_svl = (frac, diff frac_svl svl) in *)
{ cvs with vperm_frac_vars = ( frac , svl)::others ; }
in helper ann_list
let fv vps =
remove_dups (vps.vperm_zero_vars @ vps.vperm_full_vars @ vps.vperm_value_vars @
vps.vperm_lend_vars @ (List.map snd vps.vperm_frac_vars))
let subst_f f sst vps =
let f_list vl = List.map (fun v -> f sst v) vl in
{ vps with
vperm_zero_vars = f_list vps.vperm_zero_vars;
vperm_lend_vars = f_list vps.vperm_lend_vars;
vperm_value_vars = f_list vps.vperm_value_vars;
vperm_full_vars = f_list vps.vperm_full_vars;
vperm_frac_vars = List.map (fun (frac, v) -> (frac, f sst v)) vps.vperm_frac_vars; }
let subst_par sst vps =
subst_f subst_var_par sst vps
type : ( Cpure.spec_var * Cpure.spec_var ) list - > vperm_sets - > vperm_sets
let subst_par sst vps =
let pr = pr_list (pr_pair Cpure.string_of_spec_var Cpure.string_of_spec_var) in
let pr2 = !print_vperm_sets in
Debug.no_2 "subst_par" pr pr2 pr2 subst_par sst vps
let subst_one sst vps =
subst_f subst_var sst vps
let subst_one sst vps =
let pr = (pr_pair Cpure.string_of_spec_var Cpure.string_of_spec_var) in
let pr2 = !print_vperm_sets in
Debug.no_2 "subst_one" pr pr2 pr2 subst_one sst vps
let subst_avoid_capture f t vps =
let sst = List.combine f t in
subst_f subs_one sst vps
let is_false_vperm_sets vps =
vps.vperm_is_false
let norm_is_false_vperm_sets vps =
let vps = norm_vperm_sets vps in
(vps,vps.vperm_is_false)
(* let full_vars = vps.vperm_full_vars in *)
(* check_dups full_vars *)
let get_vperm_spec_var sv vps =
if mem sv vps.vperm_full_vars then VP_Full
else if mem sv vps.vperm_lend_vars then VP_Lend
else if mem sv vps.vperm_value_vars then VP_Value
else
try
let frac_perm, _ = List.find (fun (_, s) -> eq_spec_var_ident sv s) vps.vperm_frac_vars in
VP_Frac frac_perm
with _ -> VP_Zero
| null |
https://raw.githubusercontent.com/hipsleek/hipsleek/596f7fa7f67444c8309da2ca86ba4c47d376618c/bef_indent/cvpermUtils.ml
|
ocaml
|
To store vperm of variables
vperm_frac_vars: (Frac.frac * spec_var list) list;
simpler
unused cos of ivperm?
else
{ vp with
vperm_unprimed_flag = true;
}
let vperm_rm_prime vps =
let pr = !print_vperm_sets in
is_empty xs
(is_empty vps.vperm_zero_vars) &&
is_empty xs
@zero[x] * @zero[x] -> @zero[x]
@lend[x] * @lend[x] -> @lend[x]
let frac_vars_set = List.map (fun (frac, group) ->
(frac, m_group)) group_frac_vars_sets
TO FIX Value?
@full[x] * @lend[x] -> ERR
@full[x] * @zero[x] -> @full[x]
@lend[x] * @lend[x] -> @lend[x] => remove_dups
@lend[x] * @zero[x] -> @lend[x]
@zero[x] * @zero[x] -> @zero[x] => remove_dups
|| (overlap full_vars lend_vars)
@full[x] or @lend[x] -> @lend[x]
@full[x] or @zero[x] -> @zero[x]
@lend[x] or @lend[x] -> @lend[x]
@lend[x] or @zero[x] -> @zero[x]
@zero[x] or @zero[x] -> @zero[x]
this method loses too much information ; it should not be used
This seems to be removing vps of some ids
let frac_svl = (frac, diff frac_svl svl) in
let full_vars = vps.vperm_full_vars in
check_dups full_vars
|
#include "xdebug.cppo"
open VarGen
open Gen
open Globals
open Cpure
let remove_dups = Gen.BList.remove_dups_eq eq_spec_var_ident
let check_dups = Gen.BList.check_dups_eq eq_spec_var_ident
let diff = Gen.BList.difference_eq eq_spec_var_ident
let intersect = Gen.BList.intersect_eq eq_spec_var_ident
let overlap = Gen.BList.overlap_eq eq_spec_var_ident
let mem = Gen.BList.mem_eq eq_spec_var_ident
type vperm_sets = {
vperm_unprimed_flag: bool;
vperm_is_false : bool;
vperm_zero_vars: spec_var list;
vperm_lend_vars: spec_var list;
vperm_value_vars: spec_var list;
vperm_full_vars: spec_var list;
}
let print_vperm_sets = ref (fun (vps: vperm_sets) -> "vperm_sets printer has not been initialized")
let build_vperm ?zero:(zero=[]) ?lend:(lend=[]) ?value:(value=[])
?frac:(frac=[]) full
=
let cnt = (List.length zero) + (List.length lend) + (List.length value) + (List.length frac) + (List.length full) in
{
vperm_unprimed_flag = if cnt=0 then true else false;
vperm_is_false = false;
vperm_zero_vars = List.map sp_rm_prime zero;
vperm_lend_vars = List.map sp_rm_prime lend;
vperm_value_vars = List.map sp_rm_prime value;
vperm_full_vars = List.map sp_rm_prime full;
vperm_frac_vars = List.map (fun (a,v) -> (a,sp_rm_prime v)) frac;
}
let vperm_unprime vp = { vp with vperm_unprimed_flag = false}
let vperm_rm_prime vp = vp
if vp.vperm_unprimed_flag then vp
vperm_zero_vars = List.map sp_rm_prime vp.vperm_zero_vars ;
vperm_lend_vars = ;
vperm_value_vars = List.map sp_rm_prime vp.vperm_value_vars ;
vperm_full_vars = List.map sp_rm_prime vp.vperm_full_vars ;
vperm_frac_vars = List.map ( fun ( a , vs ) - > ( a , sp_rm_prime vs ) ) vp.vperm_frac_vars ;
Debug.no_1 " vperm_rm_prime " pr pr
ZH : it is redundant ?
let vperm_rm_prime vp =
if vp.vperm_unprimed_flag then vp
else vperm_rm_prime vp
let empty_vperm_sets = build_vperm []
let is_empty_frac fr =
let xs = ( fun ( f , _ ) - > not(Frac.is_zero f ) ) fr in
List.for_all (fun (f,_) -> Frac.is_zero f) fr
let is_empty_vperm_sets vps =
not (!Globals.ann_vp) ||
((is_empty vps.vperm_full_vars) &&
(is_empty vps.vperm_lend_vars) &&
(is_empty vps.vperm_value_vars) &&
(is_empty_frac vps.vperm_frac_vars))
let is_empty_frac_leak fr =
let xs = ( fun ( f , _ ) - > not(Frac.is_zero f || Frac.is_value f ) ) fr in
List.for_all (fun (f,_) -> Frac.is_zero f || Frac.is_value f) fr
WN : need to filter frac list
let is_leak_vperm vps =
match vps with
| { vperm_full_vars = full; vperm_frac_vars = frac } ->
not(is_empty full) || not(is_empty_frac_leak frac)
let rec partition_by_key key_of key_eq ls =
match ls with
| [] -> []
| e::es ->
let ke = key_of e in
let same_es, other_es = List.partition (fun e -> key_eq ke (key_of e)) es in
(ke, e::same_es)::(partition_by_key key_of key_eq other_es)
let is_Zero ann =
match ann with
| VP_Zero -> true
| VP_Frac f -> Frac.is_zero f
| _ -> false
let norm_frac_list xs =
let rec aux xs fr sv =
match xs with
| [] -> [(fr,sv)]
| (fr2,sv2)::xs ->
if eq_spec_var_ident sv sv2 then aux xs (Frac.add fr fr2) sv
else (fr,sv)::(aux xs fr2 sv2)
in match xs with
| [] -> []
| (fr,sv)::xs -> aux xs fr sv
let norm_frac_list frac_vars =
let frac_vars = List.sort (fun (_,sv1) (_,sv2) ->
String.compare (get_unprime sv1) (get_unprime sv2)) frac_vars in
let frac_vars2 = norm_frac_list frac_vars in
frac_vars2
let check_dupl svl =
let rec aux svl p =
match svl with
| [] -> false
| v::vs -> if eq_spec_var_ident p v then true else aux vs v
in match svl with
| [] -> false
| v::vs -> aux vs v
let norm_list svl =
let svl2 = List.sort (fun v1 v2 -> String.compare (get_unprime v1) (get_unprime v2)) svl in
(svl2,check_dupl svl2)
let check_dupl_two s1 s2 =
let rec aux s1 s2 =
match s1,s2 with
| [],_ -> false
| _,[] -> false
| (v1::t1),(v2::t2) ->
let c = String.compare (get_unprime v1) (get_unprime v2) in
if c=0 then true
else if c<0 then aux t1 s2
else aux s1 t2 in
aux s1 s2
let norm_full_value full value =
let svl1,f1 = norm_list full in
let svl2,f2 = norm_list value in
let f = f1||f2 in
if f then (svl1,svl2,f)
else (svl1,svl2,check_dupl_two svl1 svl2)
let is_frac_false xs =
List.exists (Frac.is_false) (List.map fst xs)
let frac_vars =
( fun ( f , v ) - > not(Frac.is_zero f ) ) frac_vars
let is_false_frac_other frac_vars full_vars value_vars =
let vs = full_vars@value_vars in
List.exists (fun (f,v) -> not(Frac.is_zero f) && mem v vs) frac_vars
let norm_vperm_sets vps =
let vps = vperm_rm_prime vps in
let (full_vars,value_vars,flag1) = norm_full_value vps.vperm_full_vars vps.vperm_value_vars in
let full_vars = ( \ * remove_dups * \ ) vps.vperm_full_vars in ( \ * ] * @full[x ] - > false * \ )
let frac_vars2 = norm_frac_list vps.vperm_frac_vars in
let false_flag = flag1 || (is_frac_false frac_vars2)
|| (is_false_frac_other frac_vars2 full_vars value_vars) in
WN : need to check if below correct !
let m_group = List.concat ( List.map snd group ) in
{ vps with
vperm_full_vars = full_vars;
vperm_is_false = false_flag;
vperm_value_vars = value_vars;
vperm_zero_vars = diff zero_vars (full_vars @ lend_vars);
vperm_frac_vars = frac_vars2; }
let norm_vperm_sets vps =
if not (!Globals.ann_vp) then vps
else
let pr = !print_vperm_sets in
Debug.no_1 "norm_vperm_sets" pr pr norm_vperm_sets vps
let quick_is_false vps = vps.vperm_is_false
let merge_vperm_sets vps_list =
if not (!Globals.ann_vp) then empty_vperm_sets
else
let rec helper vps_list =
match vps_list with
| [] -> empty_vperm_sets
| v::vs ->
let mvs = helper vs in
{
vperm_unprimed_flag = (v.vperm_unprimed_flag && mvs.vperm_unprimed_flag);
vperm_is_false = v.vperm_is_false || mvs.vperm_is_false;
vperm_zero_vars = v.vperm_zero_vars @ mvs.vperm_zero_vars;
vperm_lend_vars = v.vperm_lend_vars @ mvs.vperm_lend_vars;
vperm_value_vars = v.vperm_value_vars @ mvs.vperm_value_vars;
vperm_full_vars = v.vperm_full_vars @ mvs.vperm_full_vars;
vperm_frac_vars = v.vperm_frac_vars @ mvs.vperm_frac_vars; }
in norm_vperm_sets (helper vps_list)
let merge_vperm_sets vps_list =
let vps_list = List.filter (fun x -> not (is_empty_vperm_sets x)) vps_list in
if (List.length vps_list)<=1 then merge_vperm_sets vps_list
else
let pr = !print_vperm_sets in
Debug.no_1 "merge_vperm_sets" (pr_list pr) pr merge_vperm_sets vps_list
@full[x ] * ] - > ERR
let combine_vperm_sets vps_list =
if not (!Globals.ann_vp) then empty_vperm_sets
else
let rec helper vps_list =
match vps_list with
| [] -> empty_vperm_sets
| v::vs ->
let v = vperm_rm_prime v in
let mvs = helper vs in
{
vperm_unprimed_flag = (v.vperm_unprimed_flag && mvs.vperm_unprimed_flag);
vperm_is_false = v.vperm_is_false || mvs.vperm_is_false;
vperm_zero_vars = v.vperm_zero_vars @ mvs.vperm_zero_vars;
vperm_lend_vars = v.vperm_lend_vars @ mvs.vperm_lend_vars;
vperm_value_vars = v.vperm_value_vars @ mvs.vperm_value_vars;
vperm_full_vars = v.vperm_full_vars @ mvs.vperm_full_vars;
vperm_frac_vars = norm_frac_list (v.vperm_frac_vars @ mvs.vperm_frac_vars); }
in
let comb_vps = helper vps_list in
let full_vars = comb_vps.vperm_full_vars in
let lend_vars = comb_vps.vperm_lend_vars in
let zero_vars = comb_vps.vperm_zero_vars in
let msg = "Combination of vperm sets causes contradiction" in
let err = ({ Error.error_loc = proving_loc # get; Error.error_text = msg }) in
let ( ) = x_binfo_pp " inside combine_vperm_sets " no_pos in
then Error.report_error err
else
{ comb_vps with
vperm_zero_vars = remove_dups (diff zero_vars (full_vars @ lend_vars));
vperm_lend_vars = remove_dups lend_vars; }
let combine_vperm_sets vps_list =
let vps_list = List.filter (fun x -> not (is_empty_vperm_sets x)) vps_list in
if (List.length vps_list)<=1 then combine_vperm_sets vps_list
else
let pr = !print_vperm_sets in
Debug.no_1 "combine_vperm_sets" (pr_list pr) pr combine_vperm_sets vps_list
@full[x ] or ] - > @full[x ]
let combine_or_vperm_sets vps1 vps2 =
let f1, f2 = vps1.vperm_full_vars, vps2.vperm_full_vars in
let l1, l2 = vps1.vperm_lend_vars, vps2.vperm_lend_vars in
let z1, z2 = vps1.vperm_zero_vars, vps2.vperm_zero_vars in
let v1, v2 = f1 @ l1 @ z1, f2 @ l2 @ z2 in
let alone_vars = diff (v1 @ v2) (intersect v1 v2) in
let z = remove_dups (z1 @ z2 @ alone_vars) in
let l = remove_dups (diff (l1 @ l2) z) in
let f = remove_dups (diff (f1 @ f2) (l @ z)) in
{
vperm_unprimed_flag = (vps1.vperm_unprimed_flag && vps2.vperm_unprimed_flag);
vperm_is_false = vps1.vperm_is_false && vps2.vperm_is_false;
vperm_zero_vars = z;
vperm_lend_vars = l;
vperm_full_vars = f;
TODO
TODO
let vperm_sets_of_anns ann_list =
let rec helper ann_list =
match ann_list with
| [] -> empty_vperm_sets
| (ann, svl)::vs ->
let mvs = helper vs in
match ann with
| VP_Zero -> { mvs with vperm_zero_vars = mvs.vperm_zero_vars @ svl; }
| VP_Full -> { mvs with vperm_full_vars = mvs.vperm_full_vars @ svl; }
| VP_Value -> { mvs with vperm_value_vars = mvs.vperm_value_vars @ svl; }
| VP_Lend -> { mvs with vperm_lend_vars = mvs.vperm_lend_vars @ svl; }
| VP_Frac frac -> { mvs with vperm_frac_vars = mvs.vperm_frac_vars @ (List.map (fun v -> (frac, v)) svl); }
in norm_vperm_sets (helper ann_list)
let clear_vperm_sets ann_list vps =
let rec helper ann_list =
match ann_list with
| [] -> vps
| (ann, svl)::vs ->
let cvs = helper vs in
match ann with
| VP_Zero -> { cvs with vperm_zero_vars = diff cvs.vperm_zero_vars svl; }
| VP_Full -> { cvs with vperm_full_vars = diff cvs.vperm_full_vars svl; }
| VP_Value -> { cvs with vperm_value_vars = diff cvs.vperm_value_vars svl; }
| VP_Lend -> { cvs with vperm_lend_vars = diff cvs.vperm_lend_vars svl; }
| VP_Frac frac -> { cvs with vperm_frac_vars =
TODO : WN
let frac_sets , others = List.partition ( fun ( f , _ ) - >
Frac.eq_frac f frac ) cvs.vperm_frac_vars in
let frac_svl = List.concat ( List.map snd frac_sets ) in
{ cvs with vperm_frac_vars = ( frac , svl)::others ; }
in helper ann_list
let fv vps =
remove_dups (vps.vperm_zero_vars @ vps.vperm_full_vars @ vps.vperm_value_vars @
vps.vperm_lend_vars @ (List.map snd vps.vperm_frac_vars))
let subst_f f sst vps =
let f_list vl = List.map (fun v -> f sst v) vl in
{ vps with
vperm_zero_vars = f_list vps.vperm_zero_vars;
vperm_lend_vars = f_list vps.vperm_lend_vars;
vperm_value_vars = f_list vps.vperm_value_vars;
vperm_full_vars = f_list vps.vperm_full_vars;
vperm_frac_vars = List.map (fun (frac, v) -> (frac, f sst v)) vps.vperm_frac_vars; }
let subst_par sst vps =
subst_f subst_var_par sst vps
type : ( Cpure.spec_var * Cpure.spec_var ) list - > vperm_sets - > vperm_sets
let subst_par sst vps =
let pr = pr_list (pr_pair Cpure.string_of_spec_var Cpure.string_of_spec_var) in
let pr2 = !print_vperm_sets in
Debug.no_2 "subst_par" pr pr2 pr2 subst_par sst vps
let subst_one sst vps =
subst_f subst_var sst vps
let subst_one sst vps =
let pr = (pr_pair Cpure.string_of_spec_var Cpure.string_of_spec_var) in
let pr2 = !print_vperm_sets in
Debug.no_2 "subst_one" pr pr2 pr2 subst_one sst vps
let subst_avoid_capture f t vps =
let sst = List.combine f t in
subst_f subs_one sst vps
let is_false_vperm_sets vps =
vps.vperm_is_false
let norm_is_false_vperm_sets vps =
let vps = norm_vperm_sets vps in
(vps,vps.vperm_is_false)
let get_vperm_spec_var sv vps =
if mem sv vps.vperm_full_vars then VP_Full
else if mem sv vps.vperm_lend_vars then VP_Lend
else if mem sv vps.vperm_value_vars then VP_Value
else
try
let frac_perm, _ = List.find (fun (_, s) -> eq_spec_var_ident sv s) vps.vperm_frac_vars in
VP_Frac frac_perm
with _ -> VP_Zero
|
f92b5c7b2022969e32b0aff47ac20d1087f14e94909bf3a01b3986e688cd7935
|
functionally/pigy-genetics
|
Drawing.hs
|
-----------------------------------------------------------------------------
--
-- Module : $Headers
Copyright : ( c ) 2021
License : MIT
--
Maintainer : < >
-- Stability : Experimental
Portability : Portable
--
-- | Drawing pig images.
--
-----------------------------------------------------------------------------
# LANGUAGE RecordWildCards #
module Pigy.Image.Drawing (
-- * Drawing
drawBody
, drawEars
, drawEyes
, drawHead
, drawNose
-- * Scaling
, withAspect
, withScale
-- * Colors
, skin
-- * Dimensions
, enlarge
, width
, height
) where
import Codec.Picture (PixelRGBA8(..))
import Data.Colour.RGBSpace.HSL (hsl)
import Data.Colour.SRGB (RGB(..))
import Graphics.Rasterific (Cap(..), Drawing, Join(..), Texture, V2(..), circle, cubicBezierFromPath, fill, line, roundedRectangle, stroke, withClipping, withTexture, withTransformation)
import Graphics.Rasterific.Transformations (scale, translate)
-- | Image enlargment factor, relative to nominal dimensions.
enlarge :: Float
enlarge = 2
-- | Nominal image width.
width :: Float
width = 245
-- | Nominal image height.
height :: Float
height = 287
-- | Draw the body.
drawBody :: Float -- ^ The scale for the body.
-> Texture px -- ^ The torso color.
-> Texture px -- ^ The belly color.
-> Texture px -- ^ The bottom color.
-> Drawing px () -- ^ The drawing.
drawBody bodyScale torsoColor bellyColor bottomColor =
do
withTexture bottomColor
. fill
$ roundedRectangle (V2 16.163944 215.98409) 212.15131 99.693665 55 55
withScale (bodyScale, 1) (width / 2, 215)
. withTexture torsoColor
. fill
$ roundedRectangle (V2 58.40379 139.59184) 126.36129 153.8943 80 80
withTexture bellyColor
. withClipping (fill $ roundedRectangle (V2 16.163944 215.98409) 212.15131 99.693665 55 55)
. fill
$ roundedRectangle (V2 58.40379 139.59184) 126.36129 153.8943 80 80
-- | Draw the head.
drawHead :: Texture px -- ^ The unshadowed color.
-> Texture px -- ^ The shadowed color.
-> Drawing px () -- ^ The drawing.
drawHead frontColor backColor =
do
withTexture backColor
. fill
$ roundedRectangle (V2 20.827299 50.318928) 201.86699 116.59785 60 60
withTexture frontColor
. fill
$ roundedRectangle (V2 20.827299 34.955734) 201.86699 116.59785 60 60
-- | Draw the eyes.
drawEyes :: (Float, Float) -- ^ The pupil position in radial coordinates.
-> (Float, Float) -- ^ The scaling of the eye.
-> Texture px -- ^ The eye color.
-> Texture px -- ^ The pupil color.
-> Drawing px () -- ^ The drawing.
drawEyes (eyeFraction, eyeAngle) eyeScale eyeColor pupilColor =
do
withScale eyeScale (75, 100)
$ do
withTexture eyeColor
. fill
$ circle (V2 75.04925 101.45342) 9.72327
withTexture pupilColor
. fill
$ circle (V2 (75.04925 + 6.03059 * eyeFraction * cos eyeAngle) (101.45342 + 6.03059 * eyeFraction * sin eyeAngle)) 3.64652
withScale eyeScale (170, 100)
$ do
withTexture eyeColor
. fill
$ circle (V2 (width - 75.04925) 101.45342) 9.72327
withTexture pupilColor
. fill
$ circle (V2 (width - 75.04925 + 6.03059 * eyeFraction * cos eyeAngle) (101.45342 + 6.03059 * eyeFraction * sin eyeAngle)) 3.64652
-- | Draw the ears.
drawEars :: (Float, Float) -- ^ The scaling of the ears.
-> Texture px -- ^ The unshadowed color.
-> Texture px -- ^ The shadowed color.
-> Drawing px () -- ^ The drawing.
drawEars earScale frontColor backColor =
do
withScale earScale (54, 47)
$ do
withTexture backColor
. fill
$ cubicBezierFromPath
[
V2 0 0
, V2 34.875935 0.42684743
, V2 69.101494 15.066973
, V2 85.434346 34.902808
, V2 69.497156 38.440122
, V2 51.422301 45.66022
, V2 37.471204 58.134955
, V2 42.774045 32.747291
, V2 31.658189 11.934829
, V2 0 0
]
withTexture frontColor
. fill
$ cubicBezierFromPath
[
V2 0 0
, V2 50.861558 15.800834
, V2 38.191333 57.31195
, V2 37.471204 58.134955
, V2 33.553602 63.778565
, V2 30.631682 69.593209
, V2 27.302137 75.122339
, V2 14.99146 52.777337
, V2 18.687946 21.667265
, V2 0 0
]
withScale earScale (187, 47)
$ do
withTexture backColor
. fill
$ cubicBezierFromPath
[
V2 width 0
, V2 (width - 34.875935) 0.42684743
, V2 (width - 69.101494) 15.066973
, V2 (width - 85.434346) 34.902808
, V2 (width - 69.497156) 38.440122
, V2 (width - 51.422301) 45.66022
, V2 (width - 37.471204) 58.134955
, V2 (width - 42.774045) 32.747291
, V2 (width - 31.658189) 11.934829
, V2 width 0
]
withTexture frontColor
. fill
$ cubicBezierFromPath
[
V2 width 0
, V2 (width - 50.861558) 15.800834
, V2 (width - 38.191333) 57.31195
, V2 (width - 37.471204) 58.134955
, V2 (width - 33.553602) 63.778565
, V2 (width - 30.631682) 69.593209
, V2 (width - 27.302137) 75.122339
, V2 (width - 14.99146 ) 52.777337
, V2 (width - 18.687946) 21.667265
, V2 width 0
]
-- | Draw the nose.
drawNose :: Texture px -- ^ The unshadowed color.
-> Texture px -- ^ The shadowed color.
-> Texture px -- ^ The centerline color.
-> Texture px -- ^ The nostril color.
-> Drawing px () -- ^ The drawing.
drawNose frontColor backColor centerColor nostrilColor =
do
withTexture backColor
. fill
$ roundedRectangle (V2 86.188965 111.72396) 71.934334 39.709103 15 15
withTexture frontColor
. fill
$ roundedRectangle (V2 86.188965 107.60213) 71.934334 39.709103 15 15
withTexture centerColor
. stroke 1 JoinRound (CapStraight 0, CapStraight 0)
$ line (V2 122.53 107.60213) (V2 122.53 (107.60213+39.709103))
withTexture nostrilColor
$ do
fill
$ roundedRectangle (V2 101.65501 117.96757) 10.00565 16.56616 3.8053 3.8053
fill
$ roundedRectangle (V2 (width - 101.65501-10.00565) 117.96757) 10.00565 16.56616 3.8053 3.8053
-- | Scale a drawing according to an aspect ratio.
withAspect :: Float -- ^ The aspect ratio.
-> (Float, Float) -- ^ The center of the scaling.
-> Drawing px () -- ^ The original drawing.
-> Drawing px () -- ^ The scaled drawing.
withAspect ratio =
withScale
(
minimum [1, ratio]
, minimum [1, 1 / ratio]
)
-- | Scale a drawing.
withScale :: (Float, Float) -- ^ The scales.
-> (Float, Float) -- ^ The center of the scaling.
-> Drawing px () -- ^ The original drawing.
-> Drawing px () -- ^ The scaled drawing.
withScale (sx, sy) (cx, cy) =
withTransformation
$ translate (V2 cx cy )
<> scale sx sy
<> translate (V2 (- cx) (- cy))
-- | Compute the skin color.
skin :: Float -- ^ The hue.
-> Float -- ^ The luminosity.
-> PixelRGBA8 -- ^ The skin color.
skin h l =
let
RGB{..} = hsl h 0.7 l
q x = round $ 255 * x
in
PixelRGBA8
(q channelRed )
(q channelGreen)
(q channelBlue )
0xFF
| null |
https://raw.githubusercontent.com/functionally/pigy-genetics/8ec2b9437a0ae14aabb166020f5c2707b2c9aa37/app/Pigy/Image/Drawing.hs
|
haskell
|
---------------------------------------------------------------------------
Module : $Headers
Stability : Experimental
| Drawing pig images.
---------------------------------------------------------------------------
* Drawing
* Scaling
* Colors
* Dimensions
| Image enlargment factor, relative to nominal dimensions.
| Nominal image width.
| Nominal image height.
| Draw the body.
^ The scale for the body.
^ The torso color.
^ The belly color.
^ The bottom color.
^ The drawing.
| Draw the head.
^ The unshadowed color.
^ The shadowed color.
^ The drawing.
| Draw the eyes.
^ The pupil position in radial coordinates.
^ The scaling of the eye.
^ The eye color.
^ The pupil color.
^ The drawing.
| Draw the ears.
^ The scaling of the ears.
^ The unshadowed color.
^ The shadowed color.
^ The drawing.
| Draw the nose.
^ The unshadowed color.
^ The shadowed color.
^ The centerline color.
^ The nostril color.
^ The drawing.
| Scale a drawing according to an aspect ratio.
^ The aspect ratio.
^ The center of the scaling.
^ The original drawing.
^ The scaled drawing.
| Scale a drawing.
^ The scales.
^ The center of the scaling.
^ The original drawing.
^ The scaled drawing.
| Compute the skin color.
^ The hue.
^ The luminosity.
^ The skin color.
|
Copyright : ( c ) 2021
License : MIT
Maintainer : < >
Portability : Portable
# LANGUAGE RecordWildCards #
module Pigy.Image.Drawing (
drawBody
, drawEars
, drawEyes
, drawHead
, drawNose
, withAspect
, withScale
, skin
, enlarge
, width
, height
) where
import Codec.Picture (PixelRGBA8(..))
import Data.Colour.RGBSpace.HSL (hsl)
import Data.Colour.SRGB (RGB(..))
import Graphics.Rasterific (Cap(..), Drawing, Join(..), Texture, V2(..), circle, cubicBezierFromPath, fill, line, roundedRectangle, stroke, withClipping, withTexture, withTransformation)
import Graphics.Rasterific.Transformations (scale, translate)
enlarge :: Float
enlarge = 2
width :: Float
width = 245
height :: Float
height = 287
drawBody bodyScale torsoColor bellyColor bottomColor =
do
withTexture bottomColor
. fill
$ roundedRectangle (V2 16.163944 215.98409) 212.15131 99.693665 55 55
withScale (bodyScale, 1) (width / 2, 215)
. withTexture torsoColor
. fill
$ roundedRectangle (V2 58.40379 139.59184) 126.36129 153.8943 80 80
withTexture bellyColor
. withClipping (fill $ roundedRectangle (V2 16.163944 215.98409) 212.15131 99.693665 55 55)
. fill
$ roundedRectangle (V2 58.40379 139.59184) 126.36129 153.8943 80 80
drawHead frontColor backColor =
do
withTexture backColor
. fill
$ roundedRectangle (V2 20.827299 50.318928) 201.86699 116.59785 60 60
withTexture frontColor
. fill
$ roundedRectangle (V2 20.827299 34.955734) 201.86699 116.59785 60 60
drawEyes (eyeFraction, eyeAngle) eyeScale eyeColor pupilColor =
do
withScale eyeScale (75, 100)
$ do
withTexture eyeColor
. fill
$ circle (V2 75.04925 101.45342) 9.72327
withTexture pupilColor
. fill
$ circle (V2 (75.04925 + 6.03059 * eyeFraction * cos eyeAngle) (101.45342 + 6.03059 * eyeFraction * sin eyeAngle)) 3.64652
withScale eyeScale (170, 100)
$ do
withTexture eyeColor
. fill
$ circle (V2 (width - 75.04925) 101.45342) 9.72327
withTexture pupilColor
. fill
$ circle (V2 (width - 75.04925 + 6.03059 * eyeFraction * cos eyeAngle) (101.45342 + 6.03059 * eyeFraction * sin eyeAngle)) 3.64652
drawEars earScale frontColor backColor =
do
withScale earScale (54, 47)
$ do
withTexture backColor
. fill
$ cubicBezierFromPath
[
V2 0 0
, V2 34.875935 0.42684743
, V2 69.101494 15.066973
, V2 85.434346 34.902808
, V2 69.497156 38.440122
, V2 51.422301 45.66022
, V2 37.471204 58.134955
, V2 42.774045 32.747291
, V2 31.658189 11.934829
, V2 0 0
]
withTexture frontColor
. fill
$ cubicBezierFromPath
[
V2 0 0
, V2 50.861558 15.800834
, V2 38.191333 57.31195
, V2 37.471204 58.134955
, V2 33.553602 63.778565
, V2 30.631682 69.593209
, V2 27.302137 75.122339
, V2 14.99146 52.777337
, V2 18.687946 21.667265
, V2 0 0
]
withScale earScale (187, 47)
$ do
withTexture backColor
. fill
$ cubicBezierFromPath
[
V2 width 0
, V2 (width - 34.875935) 0.42684743
, V2 (width - 69.101494) 15.066973
, V2 (width - 85.434346) 34.902808
, V2 (width - 69.497156) 38.440122
, V2 (width - 51.422301) 45.66022
, V2 (width - 37.471204) 58.134955
, V2 (width - 42.774045) 32.747291
, V2 (width - 31.658189) 11.934829
, V2 width 0
]
withTexture frontColor
. fill
$ cubicBezierFromPath
[
V2 width 0
, V2 (width - 50.861558) 15.800834
, V2 (width - 38.191333) 57.31195
, V2 (width - 37.471204) 58.134955
, V2 (width - 33.553602) 63.778565
, V2 (width - 30.631682) 69.593209
, V2 (width - 27.302137) 75.122339
, V2 (width - 14.99146 ) 52.777337
, V2 (width - 18.687946) 21.667265
, V2 width 0
]
drawNose frontColor backColor centerColor nostrilColor =
do
withTexture backColor
. fill
$ roundedRectangle (V2 86.188965 111.72396) 71.934334 39.709103 15 15
withTexture frontColor
. fill
$ roundedRectangle (V2 86.188965 107.60213) 71.934334 39.709103 15 15
withTexture centerColor
. stroke 1 JoinRound (CapStraight 0, CapStraight 0)
$ line (V2 122.53 107.60213) (V2 122.53 (107.60213+39.709103))
withTexture nostrilColor
$ do
fill
$ roundedRectangle (V2 101.65501 117.96757) 10.00565 16.56616 3.8053 3.8053
fill
$ roundedRectangle (V2 (width - 101.65501-10.00565) 117.96757) 10.00565 16.56616 3.8053 3.8053
withAspect ratio =
withScale
(
minimum [1, ratio]
, minimum [1, 1 / ratio]
)
withScale (sx, sy) (cx, cy) =
withTransformation
$ translate (V2 cx cy )
<> scale sx sy
<> translate (V2 (- cx) (- cy))
skin h l =
let
RGB{..} = hsl h 0.7 l
q x = round $ 255 * x
in
PixelRGBA8
(q channelRed )
(q channelGreen)
(q channelBlue )
0xFF
|
cca394bedbb990048805d61dbad23b1bd21d20851705ef8289509dc25284fa5a
|
JonathanLorimer/weft
|
ServerSpec.hs
|
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE LambdaCase #
{-# LANGUAGE NoMonoLocalBinds #-}
{-# LANGUAGE NoMonomorphismRestriction #-}
{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE DerivingStrategies #-}
module ServerSpec where
import Data.Aeson
import Data.ByteString.Lazy as BL
import qualified Data.Map as M
import Test.Hspec hiding (Arg)
import TestData
import Weft.Generics.Hydrate
import Weft.Generics.JSONResponse
import Weft.Generics.Resolve
import Weft.Internal.Types
------------------------------------------------------------------------------------------
-- | Mock Resolvers
getUserResolver :: (Arg "id" ID) -> User 'Query -> IO (User 'Response)
getUserResolver a q
| (getArg a) == ID "1" = pure $ hydrate jonathan q
| (getArg a) == ID "2" = pure $ hydrate sandy q
| otherwise = pure $ hydrate jonathan q
getAllUsersResolver :: User 'Query -> IO [User 'Response]
getAllUsersResolver q = pure $ hydrateF [sandy, jonathan] q
queryResolver :: GqlQuery 'Resolver
queryResolver =
GqlQuery
{ getUser = getUserResolver
, getAllUsers = getAllUsersResolver
}
mutationResolver :: GqlMutation 'Resolver
mutationResolver =
GqlMutation
{ mutateUser = getUserResolver
, mutateAllUsers = getAllUsersResolver
}
noneResolver :: None 'Resolver
noneResolver = None (pure ())
gqlQueryResolver :: Gql GqlQuery None s 'Resolver
gqlQueryResolver =
Gql (resolve queryResolver) (resolve noneResolver)
gqlMutationResolver :: Gql None GqlMutation s 'Resolver
gqlMutationResolver =
Gql (resolve noneResolver) (resolve mutationResolver)
------------------------------------------------------------------------------------------
-- | Mock Queries
-- | getAllUsers Mocks
getAllUsersTestJsonQuery :: Gql GqlQuery None s 'Query
getAllUsersTestJsonQuery =
Gql (M.singleton "query" (ANil, gqlGetAllUsersQ)) M.empty
getAllUsersTestJsonMutation :: Gql None GqlMutation s 'Query
getAllUsersTestJsonMutation =
Gql M.empty (M.singleton "mutation" (ANil, gqlGetAllUsersM))
gqlGetAllUsersQ :: GqlQuery 'Query
gqlGetAllUsersQ =
GqlQuery
{ getUser = M.empty
, getAllUsers = M.singleton "getAllUsers" (ANil, getAllUsersQ)
}
gqlGetAllUsersM :: GqlMutation 'Query
gqlGetAllUsersM =
GqlMutation
{ mutateUser = M.empty
, mutateAllUsers = M.singleton "mutateAllUsers" (ANil, getAllUsersQ)
}
getAllUsersQ :: User 'Query
getAllUsersQ =
User
{ userId = M.singleton "userId" (Arg Nothing :@@ ANil, ())
, userName = M.singleton "userName" (ANil, ())
, userBestFriend = M.singleton "userBestFriend" ( Arg Nothing :@@ ANil
, userBestFriendQ
)
, userFriends = M.empty
, userFingers = M.empty
}
userBestFriendQ :: User 'Query
userBestFriendQ =
User
{ userId = M.singleton "userId" (Arg Nothing :@@ ANil, ())
, userName = M.singleton "userName" (ANil , ())
, userBestFriend = M.empty
, userFriends = M.empty
, userFingers = M.empty
}
getAllUsersTestJson :: BL.ByteString
getAllUsersTestJson = "{\"query\":{\"getAllUsers\":[{\"userName\":\"Sandy\",\"userId\":\"2\",\"userBestFriend\":{\"userName\":\"Jonathan\",\"userId\":\"1\"}},{\"userName\":\"Jonathan\",\"userId\":\"1\",\"userBestFriend\":{\"userName\":\"Sandy\",\"userId\":\"2\"}}]}}"
mutateAllUsersTestJson :: BL.ByteString
mutateAllUsersTestJson = "{\"mutation\":{\"mutateAllUsers\":[{\"userName\":\"Sandy\",\"userId\":\"2\",\"userBestFriend\":{\"userName\":\"Jonathan\",\"userId\":\"1\"}},{\"userName\":\"Jonathan\",\"userId\":\"1\",\"userBestFriend\":{\"userName\":\"Sandy\",\"userId\":\"2\"}}]}}"
-- | getUser Mocks
getUserTestJsonQuery :: Gql GqlQuery None s 'Query
getUserTestJsonQuery =
Gql (M.singleton "query" (ANil, gqlGetUserQ)) M.empty
getUserTestJsonMutation :: Gql None GqlMutation s 'Query
getUserTestJsonMutation =
Gql M.empty (M.singleton "mutation" (ANil, gqlGetUserM))
gqlGetUserQ :: GqlQuery 'Query
gqlGetUserQ = GqlQuery
{ getAllUsers = M.empty
, getUser = M.singleton "getUser" (Arg (ID "1") :@@ ANil, getUserQ)
}
gqlGetUserM :: GqlMutation 'Query
gqlGetUserM = GqlMutation
{ mutateAllUsers = M.empty
, mutateUser = M.singleton "mutateUser" (Arg (ID "1") :@@ ANil, getUserQ)
}
getUserQ :: User 'Query
getUserQ =
User
{ userId = M.singleton "userId" (Arg Nothing :@@ ANil, ())
, userName = M.singleton "userName" (ANil , ())
, userBestFriend = M.singleton "userBestFriend" ( Arg Nothing :@@ ANil
, bestFriendQ
)
, userFriends = M.empty
, userFingers = M.empty
}
bestFriendQ :: User 'Query
bestFriendQ =
User
{ userId = M.empty
, userName = M.singleton "userName" (ANil, ())
, userBestFriend = M.empty
, userFriends = M.empty
, userFingers = M.empty
}
getUserTestJson :: BL.ByteString
getUserTestJson =
"{\"query\":{\"getUser\":{\"userName\":\"Jonathan\",\"userId\":\"1\",\"userBestFriend\":{\"userName\":\"Sandy\"}}}}"
mutateUserTestJson :: BL.ByteString
mutateUserTestJson =
"{\"mutation\":{\"mutateUser\":{\"userName\":\"Jonathan\",\"userId\":\"1\",\"userBestFriend\":{\"userName\":\"Sandy\"}}}}"
------------------------------------------------------------------------------------------
-- | Tests
spec :: Spec
spec = describe "server" $ do
describe "Query" $ do
describe "JSON encoding responses" $ do
it "should encode a response for getUser as JSON" $ do
response <- resolve gqlQueryResolver $ getUserTestJsonQuery
(encode $ jsonResponse response) `shouldBe` getUserTestJson
it "should encode a response for getAllUsers as JSON" $ do
response <- resolve gqlQueryResolver $ getAllUsersTestJsonQuery
(encode $ jsonResponse response) `shouldBe` getAllUsersTestJson
describe "Mutation" $ do
describe "JSON encoding responses" $ do
it "should encode a response for mutateUser as JSON" $ do
response <- resolve gqlMutationResolver $ getUserTestJsonMutation
(encode $ jsonResponse response) `shouldBe` mutateUserTestJson
it "should encode a response for mutateAllUsers as JSON" $ do
response <- resolve gqlMutationResolver $ getAllUsersTestJsonMutation
(encode $ jsonResponse response) `shouldBe` mutateAllUsersTestJson
| null |
https://raw.githubusercontent.com/JonathanLorimer/weft/fc0396240905ab0202c5896019cf1e482d216f8d/test/ServerSpec.hs
|
haskell
|
# LANGUAGE NoMonoLocalBinds #
# LANGUAGE NoMonomorphismRestriction #
# LANGUAGE DeriveAnyClass #
# LANGUAGE DerivingStrategies #
----------------------------------------------------------------------------------------
| Mock Resolvers
----------------------------------------------------------------------------------------
| Mock Queries
| getAllUsers Mocks
| getUser Mocks
----------------------------------------------------------------------------------------
| Tests
|
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE LambdaCase #
module ServerSpec where
import Data.Aeson
import Data.ByteString.Lazy as BL
import qualified Data.Map as M
import Test.Hspec hiding (Arg)
import TestData
import Weft.Generics.Hydrate
import Weft.Generics.JSONResponse
import Weft.Generics.Resolve
import Weft.Internal.Types
getUserResolver :: (Arg "id" ID) -> User 'Query -> IO (User 'Response)
getUserResolver a q
| (getArg a) == ID "1" = pure $ hydrate jonathan q
| (getArg a) == ID "2" = pure $ hydrate sandy q
| otherwise = pure $ hydrate jonathan q
getAllUsersResolver :: User 'Query -> IO [User 'Response]
getAllUsersResolver q = pure $ hydrateF [sandy, jonathan] q
queryResolver :: GqlQuery 'Resolver
queryResolver =
GqlQuery
{ getUser = getUserResolver
, getAllUsers = getAllUsersResolver
}
mutationResolver :: GqlMutation 'Resolver
mutationResolver =
GqlMutation
{ mutateUser = getUserResolver
, mutateAllUsers = getAllUsersResolver
}
noneResolver :: None 'Resolver
noneResolver = None (pure ())
gqlQueryResolver :: Gql GqlQuery None s 'Resolver
gqlQueryResolver =
Gql (resolve queryResolver) (resolve noneResolver)
gqlMutationResolver :: Gql None GqlMutation s 'Resolver
gqlMutationResolver =
Gql (resolve noneResolver) (resolve mutationResolver)
getAllUsersTestJsonQuery :: Gql GqlQuery None s 'Query
getAllUsersTestJsonQuery =
Gql (M.singleton "query" (ANil, gqlGetAllUsersQ)) M.empty
getAllUsersTestJsonMutation :: Gql None GqlMutation s 'Query
getAllUsersTestJsonMutation =
Gql M.empty (M.singleton "mutation" (ANil, gqlGetAllUsersM))
gqlGetAllUsersQ :: GqlQuery 'Query
gqlGetAllUsersQ =
GqlQuery
{ getUser = M.empty
, getAllUsers = M.singleton "getAllUsers" (ANil, getAllUsersQ)
}
gqlGetAllUsersM :: GqlMutation 'Query
gqlGetAllUsersM =
GqlMutation
{ mutateUser = M.empty
, mutateAllUsers = M.singleton "mutateAllUsers" (ANil, getAllUsersQ)
}
getAllUsersQ :: User 'Query
getAllUsersQ =
User
{ userId = M.singleton "userId" (Arg Nothing :@@ ANil, ())
, userName = M.singleton "userName" (ANil, ())
, userBestFriend = M.singleton "userBestFriend" ( Arg Nothing :@@ ANil
, userBestFriendQ
)
, userFriends = M.empty
, userFingers = M.empty
}
userBestFriendQ :: User 'Query
userBestFriendQ =
User
{ userId = M.singleton "userId" (Arg Nothing :@@ ANil, ())
, userName = M.singleton "userName" (ANil , ())
, userBestFriend = M.empty
, userFriends = M.empty
, userFingers = M.empty
}
getAllUsersTestJson :: BL.ByteString
getAllUsersTestJson = "{\"query\":{\"getAllUsers\":[{\"userName\":\"Sandy\",\"userId\":\"2\",\"userBestFriend\":{\"userName\":\"Jonathan\",\"userId\":\"1\"}},{\"userName\":\"Jonathan\",\"userId\":\"1\",\"userBestFriend\":{\"userName\":\"Sandy\",\"userId\":\"2\"}}]}}"
mutateAllUsersTestJson :: BL.ByteString
mutateAllUsersTestJson = "{\"mutation\":{\"mutateAllUsers\":[{\"userName\":\"Sandy\",\"userId\":\"2\",\"userBestFriend\":{\"userName\":\"Jonathan\",\"userId\":\"1\"}},{\"userName\":\"Jonathan\",\"userId\":\"1\",\"userBestFriend\":{\"userName\":\"Sandy\",\"userId\":\"2\"}}]}}"
getUserTestJsonQuery :: Gql GqlQuery None s 'Query
getUserTestJsonQuery =
Gql (M.singleton "query" (ANil, gqlGetUserQ)) M.empty
getUserTestJsonMutation :: Gql None GqlMutation s 'Query
getUserTestJsonMutation =
Gql M.empty (M.singleton "mutation" (ANil, gqlGetUserM))
gqlGetUserQ :: GqlQuery 'Query
gqlGetUserQ = GqlQuery
{ getAllUsers = M.empty
, getUser = M.singleton "getUser" (Arg (ID "1") :@@ ANil, getUserQ)
}
gqlGetUserM :: GqlMutation 'Query
gqlGetUserM = GqlMutation
{ mutateAllUsers = M.empty
, mutateUser = M.singleton "mutateUser" (Arg (ID "1") :@@ ANil, getUserQ)
}
getUserQ :: User 'Query
getUserQ =
User
{ userId = M.singleton "userId" (Arg Nothing :@@ ANil, ())
, userName = M.singleton "userName" (ANil , ())
, userBestFriend = M.singleton "userBestFriend" ( Arg Nothing :@@ ANil
, bestFriendQ
)
, userFriends = M.empty
, userFingers = M.empty
}
bestFriendQ :: User 'Query
bestFriendQ =
User
{ userId = M.empty
, userName = M.singleton "userName" (ANil, ())
, userBestFriend = M.empty
, userFriends = M.empty
, userFingers = M.empty
}
getUserTestJson :: BL.ByteString
getUserTestJson =
"{\"query\":{\"getUser\":{\"userName\":\"Jonathan\",\"userId\":\"1\",\"userBestFriend\":{\"userName\":\"Sandy\"}}}}"
mutateUserTestJson :: BL.ByteString
mutateUserTestJson =
"{\"mutation\":{\"mutateUser\":{\"userName\":\"Jonathan\",\"userId\":\"1\",\"userBestFriend\":{\"userName\":\"Sandy\"}}}}"
spec :: Spec
spec = describe "server" $ do
describe "Query" $ do
describe "JSON encoding responses" $ do
it "should encode a response for getUser as JSON" $ do
response <- resolve gqlQueryResolver $ getUserTestJsonQuery
(encode $ jsonResponse response) `shouldBe` getUserTestJson
it "should encode a response for getAllUsers as JSON" $ do
response <- resolve gqlQueryResolver $ getAllUsersTestJsonQuery
(encode $ jsonResponse response) `shouldBe` getAllUsersTestJson
describe "Mutation" $ do
describe "JSON encoding responses" $ do
it "should encode a response for mutateUser as JSON" $ do
response <- resolve gqlMutationResolver $ getUserTestJsonMutation
(encode $ jsonResponse response) `shouldBe` mutateUserTestJson
it "should encode a response for mutateAllUsers as JSON" $ do
response <- resolve gqlMutationResolver $ getAllUsersTestJsonMutation
(encode $ jsonResponse response) `shouldBe` mutateAllUsersTestJson
|
8a276b6ec9f5eddcbf7806fc0f4763c5a0fae4bd31f2c87638b503e322f191fe
|
awslabs/s2n-bignum
|
bignum_cld.ml
|
* Copyright Amazon.com , Inc. or its affiliates . All Rights Reserved .
* SPDX - License - Identifier : Apache-2.0 OR ISC
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0 OR ISC
*)
(* ========================================================================= *)
Counting leading zero digits of a bignum .
(* ========================================================================= *)
(**** print_literal_from_elf "arm/generic/bignum_cld.o";;
****)
let bignum_cld_mc = define_assert_from_elf "bignum_cld_mc" "arm/generic/bignum_cld.o"
[
arm_CBZ X0 ( word 40 )
arm_MOV X2 XZR
arm_MOV X4 XZR
arm_LDR X3 X1 ( Shiftreg_Offset X4 3 )
arm_ADD X4 X4 ( rvalue ( word 1 ) )
arm_CMP X3 ( rvalue ( word 0 ) )
arm_CSEL X2 X4 X2 Condition_NE
arm_CMP
arm_BNE ( word 2097132 )
arm_SUB X2
arm_RET X30
];;
let BIGNUM_CLD_EXEC = ARM_MK_EXEC_RULE bignum_cld_mc;;
(* ------------------------------------------------------------------------- *)
(* Correctness proof. *)
(* ------------------------------------------------------------------------- *)
let BIGNUM_CLD_CORRECT = prove
(`!k a x pc.
ensures arm
(\s. aligned_bytes_loaded s (word pc) bignum_cld_mc /\
read PC s = word pc /\
C_ARGUMENTS [k;a] s /\
bignum_from_memory(a,val k) s = x)
(\s'. read PC s' = word (pc + 0x28) /\
C_RETURN s' = word((64 * val k - bitsize x) DIV 64))
(MAYCHANGE [PC; X0; X2; X3; X4] ,,
MAYCHANGE SOME_FLAGS)`,
W64_GEN_TAC `k:num` THEN
MAP_EVERY X_GEN_TAC [`a:int64`; `x:num`; `pc:num`] THEN
REWRITE_TAC[C_ARGUMENTS; C_RETURN; SOME_FLAGS] THEN
BIGNUM_RANGE_TAC "k" "x" THEN
ASM_CASES_TAC `k = 0` THENL
[UNDISCH_TAC `x < 2 EXP (64 * k)` THEN
ASM_REWRITE_TAC[MULT_CLAUSES; EXP; ARITH_RULE `x < 1 <=> x = 0`] THEN
DISCH_THEN(fun th -> REWRITE_TAC[th]) THEN
ENSURES_INIT_TAC "s0" THEN ARM_STEPS_TAC BIGNUM_CLD_EXEC [1] THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[BITSIZE_0] THEN
CONV_TAC NUM_REDUCE_CONV;
ALL_TAC] THEN
ENSURES_WHILE_PUP_TAC `k:num` `pc + 0xc` `pc + 0x20`
`\i s. (bignum_from_memory (a,k) s = x /\
read X0 s = word k /\
read X1 s = a /\
read X4 s = word i /\
bignum_from_memory(word_add a (word(8 * val(read X2 s))),
i - val(read X2 s)) s = 0 /\
(read X2 s = word 0 \/
~(read X2 s = word 0) /\ val(read X2 s) <= i /\
~(bigdigit x (val(word_sub (read X2 s) (word 1))) = 0))) /\
(read ZF s <=> i = k)` THEN
ASM_REWRITE_TAC[] THEN REPEAT CONJ_TAC THENL
[REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN
ENSURES_INIT_TAC "s0" THEN ARM_STEPS_TAC BIGNUM_CLD_EXEC (1--3) THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[] THEN
ASM_REWRITE_TAC[GSYM BIGNUM_FROM_MEMORY_BYTES; VAL_WORD_0; SUB_REFL] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_TRIVIAL];
ALL_TAC; (*** Main loop invariant ***)
X_GEN_TAC `j:num` THEN STRIP_TAC THEN VAL_INT64_TAC `j:num` THEN
ASM_REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN
GHOST_INTRO_TAC `r:int64` `read X2` THEN
ENSURES_INIT_TAC "s0" THEN ARM_STEPS_TAC BIGNUM_CLD_EXEC [1] THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[];
GHOST_INTRO_TAC `r:int64` `read X2` THEN
ABBREV_TAC `i = val(r:int64)` THEN
SUBGOAL_THEN `i < 2 EXP 64` ASSUME_TAC THENL
[ASM_MESON_TAC[VAL_BOUND_64]; ALL_TAC] THEN
VAL_INT64_TAC `i:num` THEN
ASM_REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN
ENSURES_INIT_TAC "s0" THEN ARM_STEPS_TAC BIGNUM_CLD_EXEC (1--2) THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[] THEN
FIRST_X_ASSUM(DISJ_CASES_THEN MP_TAC) THENL
[DISCH_THEN SUBST_ALL_TAC THEN
UNDISCH_TAC `val(word 0:int64) = i` THEN
REWRITE_TAC[VAL_WORD_0] THEN DISCH_THEN(SUBST_ALL_TAC o SYM) THEN
RULE_ASSUM_TAC(REWRITE_RULE[MULT_CLAUSES; SUB_0; WORD_ADD_0]) THEN
UNDISCH_TAC `read (memory :> bytes (a,8 * k)) s2 = x` THEN
ASM_REWRITE_TAC[] THEN DISCH_THEN(SUBST1_TAC o SYM) THEN
REWRITE_TAC[BITSIZE_0; SUB_0; WORD_SUB_0] THEN
AP_TERM_TAC THEN ARITH_TAC;
ASM_REWRITE_TAC[GSYM VAL_EQ_0] THEN STRIP_TAC] THEN
SUBGOAL_THEN `val(word_sub r (word 1):int64) = i - 1` SUBST_ALL_TAC THENL
[ASM_REWRITE_TAC[VAL_WORD_SUB_CASES; VAL_WORD_1] THEN
ASM_REWRITE_TAC[ARITH_RULE `1 <= i <=> ~(i = 0)`];
ALL_TAC] THEN
ABBREV_TAC `d = bigdigit x (i - 1)` THEN
SUBGOAL_THEN `x = 2 EXP (64 * i) * highdigits x i + lowdigits x i`
SUBST1_TAC THENL [REWRITE_TAC[HIGH_LOW_DIGITS]; ALL_TAC] THEN
SUBGOAL_THEN `highdigits x i = 0` SUBST1_TAC THENL
[EXPAND_TAC "x" THEN REWRITE_TAC[GSYM BIGNUM_FROM_MEMORY_BYTES] THEN
REWRITE_TAC[highdigits; BIGNUM_FROM_MEMORY_DIV] THEN
ASM_REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES];
REWRITE_TAC[MULT_CLAUSES; ADD_CLAUSES]] THEN
SUBGOAL_THEN `i = (i - 1) + 1` SUBST1_TAC THENL
[SIMPLE_ARITH_TAC; REWRITE_TAC[LOWDIGITS_CLAUSES]] THEN
ASM_SIMP_TAC[BITSIZE_MULT_ADD; LOWDIGITS_BOUND] THEN
TRANS_TAC EQ_TRANS `word(k - i):int64` THEN CONJ_TAC THENL
[VAL_INT64_TAC `k - i:num` THEN
ASM_REWRITE_TAC[GSYM VAL_EQ; VAL_WORD_SUB_CASES];
AP_TERM_TAC] THEN
MP_TAC(SPECL [`d:num`; `64`] BITSIZE_LE) THEN EXPAND_TAC "d" THEN
REWRITE_TAC[BIGDIGIT_BOUND] THEN
ASM_SIMP_TAC[ARITH_RULE
`~(i = 0) /\ i <= k /\ d <= 64
==> 64 * k - (64 * (i - 1) + d) = 64 * (k - i) + (64 - d)`] THEN
DISCH_THEN(K ALL_TAC) THEN
SIMP_TAC[DIV_MULT_ADD; EXP_EQ_0; ARITH_EQ; DIV_EQ_0;
ARITH_RULE `a = a + b <=> b = 0`] THEN
MP_TAC(SPEC `d:num` BITSIZE_EQ_0) THEN ASM_REWRITE_TAC[] THEN
ARITH_TAC] THEN
X_GEN_TAC `j:num` THEN STRIP_TAC THEN VAL_INT64_TAC `j:num` THEN
VAL_INT64_TAC `j + 1` THEN
GHOST_INTRO_TAC `r:int64` `read X2` THEN
ABBREV_TAC `i = val(r:int64)` THEN
SUBGOAL_THEN `i < 2 EXP 64` ASSUME_TAC THENL
[ASM_MESON_TAC[VAL_BOUND_64]; ALL_TAC] THEN
VAL_INT64_TAC `i:num` THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN
ENSURES_INIT_TAC "s0" THEN
SUBGOAL_THEN
`read(memory :> bytes64(word_add a (word(8 * j)))) s0 = word(bigdigit x j)`
ASSUME_TAC THENL
[EXPAND_TAC "x" THEN
REWRITE_TAC[GSYM BIGNUM_FROM_MEMORY_BYTES;
BIGDIGIT_BIGNUM_FROM_MEMORY] THEN
ASM_REWRITE_TAC[WORD_VAL];
ALL_TAC] THEN
ARM_STEPS_TAC BIGNUM_CLD_EXEC (1--5) THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[] THEN
CONJ_TAC THENL [CONV_TAC WORD_RULE; REWRITE_TAC[CONJ_ASSOC]] THEN
CONJ_TAC THENL
[SIMP_TAC[VAL_WORD_EQ; DIMINDEX_64; BIGDIGIT_BOUND];
REWRITE_TAC[VAL_EQ_0; WORD_SUB_EQ_0; GSYM WORD_ADD] THEN
MATCH_MP_TAC WORD_EQ_IMP THEN REWRITE_TAC[DIMINDEX_64] THEN
SIMPLE_ARITH_TAC] THEN
FIRST_X_ASSUM(MP_TAC o check (is_disj o concl)) THEN
REWRITE_TAC[WORD_SUB_0] THEN
ASM_CASES_TAC `bigdigit x j = 0` THEN ASM_REWRITE_TAC[] THEN
ASM_CASES_TAC `r:int64 = word 0` THEN
ASM_REWRITE_TAC[VAL_WORD_0; SUB_0] THENL
[UNDISCH_TAC `val(r:int64) = i` THEN ASM_REWRITE_TAC[VAL_WORD_0] THEN
DISCH_THEN(SUBST_ALL_TAC o SYM) THEN
REWRITE_TAC[MULT_CLAUSES; WORD_ADD_0; SUB_0] THEN
REWRITE_TAC[GSYM BIGNUM_FROM_MEMORY_BYTES] THEN
ASM_REWRITE_TAC[BIGNUM_FROM_MEMORY_STEP; ADD_CLAUSES; MULT_CLAUSES] THEN
RULE_ASSUM_TAC(REWRITE_RULE[WORD_ADD_0; MULT_CLAUSES; SUB_0]) THEN
ASM_REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES];
SIMP_TAC[ARITH_RULE `i <= j ==> i <= j + 1`] THEN
SIMP_TAC[ARITH_RULE `i <= j ==> (j + 1) - i = (j - i) + 1`] THEN
STRIP_TAC THEN REWRITE_TAC[GSYM BIGNUM_FROM_MEMORY_BYTES] THEN
ASM_REWRITE_TAC[BIGNUM_FROM_MEMORY_STEP] THEN
ASM_REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES; MULT_EQ_0; ADD_CLAUSES] THEN
DISJ2_TAC THEN REWRITE_TAC[GSYM WORD_ADD_ASSOC] THEN
REWRITE_TAC[GSYM WORD_ADD] THEN
ASM_SIMP_TAC[ARITH_RULE `i <= j ==> 8 * i + 8 * (j - i) = 8 * j`] THEN
REWRITE_TAC[VAL_WORD_0];
ASM_SIMP_TAC[VAL_WORD_EQ; DIMINDEX_64; BIGDIGIT_BOUND] THEN
UNDISCH_TAC `val(r:int64) = i` THEN ASM_REWRITE_TAC[VAL_WORD_0] THEN
DISCH_THEN(SUBST_ALL_TAC o SYM) THEN
REWRITE_TAC[WORD_RULE `word_sub (word_add x y) y = x`] THEN
VAL_INT64_TAC `j:num` THEN ASM_REWRITE_TAC[GSYM WORD_ADD] THEN
REWRITE_TAC[SUB_REFL; GSYM BIGNUM_FROM_MEMORY_BYTES] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_TRIVIAL] THEN DISJ2_TAC THEN
REWRITE_TAC[LE_REFL] THEN VAL_INT64_TAC `j + 1` THEN
ASM_REWRITE_TAC[GSYM VAL_EQ_0] THEN ARITH_TAC;
SIMP_TAC[VAL_WORD_EQ; DIMINDEX_64; BIGDIGIT_BOUND] THEN
FIRST_ASSUM(MP_TAC o GEN_REWRITE_RULE RAND_CONV [GSYM VAL_EQ_0]) THEN
ASM_REWRITE_TAC[VAL_WORD_SUB_CASES; VAL_WORD_1] THEN
DISCH_TAC THEN ASM_REWRITE_TAC[ARITH_RULE `1 <= i <=> ~(i = 0)`] THEN
VAL_INT64_TAC `j:num` THEN ASM_REWRITE_TAC[GSYM WORD_ADD] THEN
ASM_REWRITE_TAC[GSYM VAL_EQ_0; ADD_EQ_0; ARITH_EQ; ADD_SUB; LE_REFL] THEN
REWRITE_TAC[SUB_REFL; GSYM BIGNUM_FROM_MEMORY_BYTES] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_TRIVIAL]]);;
let BIGNUM_CLD_SUBROUTINE_CORRECT = prove
(`!k a x pc returnaddress.
ensures arm
(\s. aligned_bytes_loaded s (word pc) bignum_cld_mc /\
read PC s = word pc /\
read X30 s = returnaddress /\
C_ARGUMENTS [k;a] s /\
bignum_from_memory(a,val k) s = x)
(\s'. read PC s' = returnaddress /\
C_RETURN s' = word((64 * val k - bitsize x) DIV 64))
(MAYCHANGE [PC; X0; X2; X3; X4] ,,
MAYCHANGE SOME_FLAGS)`,
ARM_ADD_RETURN_NOSTACK_TAC BIGNUM_CLD_EXEC BIGNUM_CLD_CORRECT);;
| null |
https://raw.githubusercontent.com/awslabs/s2n-bignum/824c15f908d7a343af1b2f378cfedd36e880bdde/arm/proofs/bignum_cld.ml
|
ocaml
|
=========================================================================
=========================================================================
*** print_literal_from_elf "arm/generic/bignum_cld.o";;
***
-------------------------------------------------------------------------
Correctness proof.
-------------------------------------------------------------------------
** Main loop invariant **
|
* Copyright Amazon.com , Inc. or its affiliates . All Rights Reserved .
* SPDX - License - Identifier : Apache-2.0 OR ISC
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0 OR ISC
*)
Counting leading zero digits of a bignum .
let bignum_cld_mc = define_assert_from_elf "bignum_cld_mc" "arm/generic/bignum_cld.o"
[
arm_CBZ X0 ( word 40 )
arm_MOV X2 XZR
arm_MOV X4 XZR
arm_LDR X3 X1 ( Shiftreg_Offset X4 3 )
arm_ADD X4 X4 ( rvalue ( word 1 ) )
arm_CMP X3 ( rvalue ( word 0 ) )
arm_CSEL X2 X4 X2 Condition_NE
arm_CMP
arm_BNE ( word 2097132 )
arm_SUB X2
arm_RET X30
];;
let BIGNUM_CLD_EXEC = ARM_MK_EXEC_RULE bignum_cld_mc;;
let BIGNUM_CLD_CORRECT = prove
(`!k a x pc.
ensures arm
(\s. aligned_bytes_loaded s (word pc) bignum_cld_mc /\
read PC s = word pc /\
C_ARGUMENTS [k;a] s /\
bignum_from_memory(a,val k) s = x)
(\s'. read PC s' = word (pc + 0x28) /\
C_RETURN s' = word((64 * val k - bitsize x) DIV 64))
(MAYCHANGE [PC; X0; X2; X3; X4] ,,
MAYCHANGE SOME_FLAGS)`,
W64_GEN_TAC `k:num` THEN
MAP_EVERY X_GEN_TAC [`a:int64`; `x:num`; `pc:num`] THEN
REWRITE_TAC[C_ARGUMENTS; C_RETURN; SOME_FLAGS] THEN
BIGNUM_RANGE_TAC "k" "x" THEN
ASM_CASES_TAC `k = 0` THENL
[UNDISCH_TAC `x < 2 EXP (64 * k)` THEN
ASM_REWRITE_TAC[MULT_CLAUSES; EXP; ARITH_RULE `x < 1 <=> x = 0`] THEN
DISCH_THEN(fun th -> REWRITE_TAC[th]) THEN
ENSURES_INIT_TAC "s0" THEN ARM_STEPS_TAC BIGNUM_CLD_EXEC [1] THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[BITSIZE_0] THEN
CONV_TAC NUM_REDUCE_CONV;
ALL_TAC] THEN
ENSURES_WHILE_PUP_TAC `k:num` `pc + 0xc` `pc + 0x20`
`\i s. (bignum_from_memory (a,k) s = x /\
read X0 s = word k /\
read X1 s = a /\
read X4 s = word i /\
bignum_from_memory(word_add a (word(8 * val(read X2 s))),
i - val(read X2 s)) s = 0 /\
(read X2 s = word 0 \/
~(read X2 s = word 0) /\ val(read X2 s) <= i /\
~(bigdigit x (val(word_sub (read X2 s) (word 1))) = 0))) /\
(read ZF s <=> i = k)` THEN
ASM_REWRITE_TAC[] THEN REPEAT CONJ_TAC THENL
[REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN
ENSURES_INIT_TAC "s0" THEN ARM_STEPS_TAC BIGNUM_CLD_EXEC (1--3) THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[] THEN
ASM_REWRITE_TAC[GSYM BIGNUM_FROM_MEMORY_BYTES; VAL_WORD_0; SUB_REFL] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_TRIVIAL];
X_GEN_TAC `j:num` THEN STRIP_TAC THEN VAL_INT64_TAC `j:num` THEN
ASM_REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN
GHOST_INTRO_TAC `r:int64` `read X2` THEN
ENSURES_INIT_TAC "s0" THEN ARM_STEPS_TAC BIGNUM_CLD_EXEC [1] THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[];
GHOST_INTRO_TAC `r:int64` `read X2` THEN
ABBREV_TAC `i = val(r:int64)` THEN
SUBGOAL_THEN `i < 2 EXP 64` ASSUME_TAC THENL
[ASM_MESON_TAC[VAL_BOUND_64]; ALL_TAC] THEN
VAL_INT64_TAC `i:num` THEN
ASM_REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN
ENSURES_INIT_TAC "s0" THEN ARM_STEPS_TAC BIGNUM_CLD_EXEC (1--2) THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[] THEN
FIRST_X_ASSUM(DISJ_CASES_THEN MP_TAC) THENL
[DISCH_THEN SUBST_ALL_TAC THEN
UNDISCH_TAC `val(word 0:int64) = i` THEN
REWRITE_TAC[VAL_WORD_0] THEN DISCH_THEN(SUBST_ALL_TAC o SYM) THEN
RULE_ASSUM_TAC(REWRITE_RULE[MULT_CLAUSES; SUB_0; WORD_ADD_0]) THEN
UNDISCH_TAC `read (memory :> bytes (a,8 * k)) s2 = x` THEN
ASM_REWRITE_TAC[] THEN DISCH_THEN(SUBST1_TAC o SYM) THEN
REWRITE_TAC[BITSIZE_0; SUB_0; WORD_SUB_0] THEN
AP_TERM_TAC THEN ARITH_TAC;
ASM_REWRITE_TAC[GSYM VAL_EQ_0] THEN STRIP_TAC] THEN
SUBGOAL_THEN `val(word_sub r (word 1):int64) = i - 1` SUBST_ALL_TAC THENL
[ASM_REWRITE_TAC[VAL_WORD_SUB_CASES; VAL_WORD_1] THEN
ASM_REWRITE_TAC[ARITH_RULE `1 <= i <=> ~(i = 0)`];
ALL_TAC] THEN
ABBREV_TAC `d = bigdigit x (i - 1)` THEN
SUBGOAL_THEN `x = 2 EXP (64 * i) * highdigits x i + lowdigits x i`
SUBST1_TAC THENL [REWRITE_TAC[HIGH_LOW_DIGITS]; ALL_TAC] THEN
SUBGOAL_THEN `highdigits x i = 0` SUBST1_TAC THENL
[EXPAND_TAC "x" THEN REWRITE_TAC[GSYM BIGNUM_FROM_MEMORY_BYTES] THEN
REWRITE_TAC[highdigits; BIGNUM_FROM_MEMORY_DIV] THEN
ASM_REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES];
REWRITE_TAC[MULT_CLAUSES; ADD_CLAUSES]] THEN
SUBGOAL_THEN `i = (i - 1) + 1` SUBST1_TAC THENL
[SIMPLE_ARITH_TAC; REWRITE_TAC[LOWDIGITS_CLAUSES]] THEN
ASM_SIMP_TAC[BITSIZE_MULT_ADD; LOWDIGITS_BOUND] THEN
TRANS_TAC EQ_TRANS `word(k - i):int64` THEN CONJ_TAC THENL
[VAL_INT64_TAC `k - i:num` THEN
ASM_REWRITE_TAC[GSYM VAL_EQ; VAL_WORD_SUB_CASES];
AP_TERM_TAC] THEN
MP_TAC(SPECL [`d:num`; `64`] BITSIZE_LE) THEN EXPAND_TAC "d" THEN
REWRITE_TAC[BIGDIGIT_BOUND] THEN
ASM_SIMP_TAC[ARITH_RULE
`~(i = 0) /\ i <= k /\ d <= 64
==> 64 * k - (64 * (i - 1) + d) = 64 * (k - i) + (64 - d)`] THEN
DISCH_THEN(K ALL_TAC) THEN
SIMP_TAC[DIV_MULT_ADD; EXP_EQ_0; ARITH_EQ; DIV_EQ_0;
ARITH_RULE `a = a + b <=> b = 0`] THEN
MP_TAC(SPEC `d:num` BITSIZE_EQ_0) THEN ASM_REWRITE_TAC[] THEN
ARITH_TAC] THEN
X_GEN_TAC `j:num` THEN STRIP_TAC THEN VAL_INT64_TAC `j:num` THEN
VAL_INT64_TAC `j + 1` THEN
GHOST_INTRO_TAC `r:int64` `read X2` THEN
ABBREV_TAC `i = val(r:int64)` THEN
SUBGOAL_THEN `i < 2 EXP 64` ASSUME_TAC THENL
[ASM_MESON_TAC[VAL_BOUND_64]; ALL_TAC] THEN
VAL_INT64_TAC `i:num` THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN
ENSURES_INIT_TAC "s0" THEN
SUBGOAL_THEN
`read(memory :> bytes64(word_add a (word(8 * j)))) s0 = word(bigdigit x j)`
ASSUME_TAC THENL
[EXPAND_TAC "x" THEN
REWRITE_TAC[GSYM BIGNUM_FROM_MEMORY_BYTES;
BIGDIGIT_BIGNUM_FROM_MEMORY] THEN
ASM_REWRITE_TAC[WORD_VAL];
ALL_TAC] THEN
ARM_STEPS_TAC BIGNUM_CLD_EXEC (1--5) THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[] THEN
CONJ_TAC THENL [CONV_TAC WORD_RULE; REWRITE_TAC[CONJ_ASSOC]] THEN
CONJ_TAC THENL
[SIMP_TAC[VAL_WORD_EQ; DIMINDEX_64; BIGDIGIT_BOUND];
REWRITE_TAC[VAL_EQ_0; WORD_SUB_EQ_0; GSYM WORD_ADD] THEN
MATCH_MP_TAC WORD_EQ_IMP THEN REWRITE_TAC[DIMINDEX_64] THEN
SIMPLE_ARITH_TAC] THEN
FIRST_X_ASSUM(MP_TAC o check (is_disj o concl)) THEN
REWRITE_TAC[WORD_SUB_0] THEN
ASM_CASES_TAC `bigdigit x j = 0` THEN ASM_REWRITE_TAC[] THEN
ASM_CASES_TAC `r:int64 = word 0` THEN
ASM_REWRITE_TAC[VAL_WORD_0; SUB_0] THENL
[UNDISCH_TAC `val(r:int64) = i` THEN ASM_REWRITE_TAC[VAL_WORD_0] THEN
DISCH_THEN(SUBST_ALL_TAC o SYM) THEN
REWRITE_TAC[MULT_CLAUSES; WORD_ADD_0; SUB_0] THEN
REWRITE_TAC[GSYM BIGNUM_FROM_MEMORY_BYTES] THEN
ASM_REWRITE_TAC[BIGNUM_FROM_MEMORY_STEP; ADD_CLAUSES; MULT_CLAUSES] THEN
RULE_ASSUM_TAC(REWRITE_RULE[WORD_ADD_0; MULT_CLAUSES; SUB_0]) THEN
ASM_REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES];
SIMP_TAC[ARITH_RULE `i <= j ==> i <= j + 1`] THEN
SIMP_TAC[ARITH_RULE `i <= j ==> (j + 1) - i = (j - i) + 1`] THEN
STRIP_TAC THEN REWRITE_TAC[GSYM BIGNUM_FROM_MEMORY_BYTES] THEN
ASM_REWRITE_TAC[BIGNUM_FROM_MEMORY_STEP] THEN
ASM_REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES; MULT_EQ_0; ADD_CLAUSES] THEN
DISJ2_TAC THEN REWRITE_TAC[GSYM WORD_ADD_ASSOC] THEN
REWRITE_TAC[GSYM WORD_ADD] THEN
ASM_SIMP_TAC[ARITH_RULE `i <= j ==> 8 * i + 8 * (j - i) = 8 * j`] THEN
REWRITE_TAC[VAL_WORD_0];
ASM_SIMP_TAC[VAL_WORD_EQ; DIMINDEX_64; BIGDIGIT_BOUND] THEN
UNDISCH_TAC `val(r:int64) = i` THEN ASM_REWRITE_TAC[VAL_WORD_0] THEN
DISCH_THEN(SUBST_ALL_TAC o SYM) THEN
REWRITE_TAC[WORD_RULE `word_sub (word_add x y) y = x`] THEN
VAL_INT64_TAC `j:num` THEN ASM_REWRITE_TAC[GSYM WORD_ADD] THEN
REWRITE_TAC[SUB_REFL; GSYM BIGNUM_FROM_MEMORY_BYTES] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_TRIVIAL] THEN DISJ2_TAC THEN
REWRITE_TAC[LE_REFL] THEN VAL_INT64_TAC `j + 1` THEN
ASM_REWRITE_TAC[GSYM VAL_EQ_0] THEN ARITH_TAC;
SIMP_TAC[VAL_WORD_EQ; DIMINDEX_64; BIGDIGIT_BOUND] THEN
FIRST_ASSUM(MP_TAC o GEN_REWRITE_RULE RAND_CONV [GSYM VAL_EQ_0]) THEN
ASM_REWRITE_TAC[VAL_WORD_SUB_CASES; VAL_WORD_1] THEN
DISCH_TAC THEN ASM_REWRITE_TAC[ARITH_RULE `1 <= i <=> ~(i = 0)`] THEN
VAL_INT64_TAC `j:num` THEN ASM_REWRITE_TAC[GSYM WORD_ADD] THEN
ASM_REWRITE_TAC[GSYM VAL_EQ_0; ADD_EQ_0; ARITH_EQ; ADD_SUB; LE_REFL] THEN
REWRITE_TAC[SUB_REFL; GSYM BIGNUM_FROM_MEMORY_BYTES] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_TRIVIAL]]);;
let BIGNUM_CLD_SUBROUTINE_CORRECT = prove
(`!k a x pc returnaddress.
ensures arm
(\s. aligned_bytes_loaded s (word pc) bignum_cld_mc /\
read PC s = word pc /\
read X30 s = returnaddress /\
C_ARGUMENTS [k;a] s /\
bignum_from_memory(a,val k) s = x)
(\s'. read PC s' = returnaddress /\
C_RETURN s' = word((64 * val k - bitsize x) DIV 64))
(MAYCHANGE [PC; X0; X2; X3; X4] ,,
MAYCHANGE SOME_FLAGS)`,
ARM_ADD_RETURN_NOSTACK_TAC BIGNUM_CLD_EXEC BIGNUM_CLD_CORRECT);;
|
a9935ed1a4b5a9b840fd3b3a2ad5fcfc4050bffed2d7649540d813c9b79eeb56
|
let-def/cuite
|
mlspec.mli
|
type qclass
type cfield
type qenum
type qflags
type type_kind = [ `By_ref | `By_val ]
type type_mod =
[ `Direct
| `Pointer
| `Const
| `Const_ref
| `Ref
| `Optional
]
type qtype_def =
| QClass of qclass
| QEnum of qenum
| QFlags of qflags
| Custom of { ml_decl : string; ml_name : string; ml_negname : string;
cpp_name : string; cpp_kind : type_kind;
cpp_default_mod : type_mod;
}
type qtype = { typ_mod : type_mod; typ_def : qtype_def }
val eq_typdef : qtype_def -> qtype_def -> bool
val eq_typ : qtype -> qtype -> bool
type argument = string * qtype
val compatible_arg : argument -> argument -> bool
type cfield_desc =
| Constructor of { args: argument list; custom: bool }
| Dynamic_method of { ret: qtype option; args: argument list;
kind: [`Normal | `Custom | `Protected] }
| Static_method of { ret: qtype option; args: argument list; custom: bool }
| Signal of { args: argument list; private_: bool }
| Slot of { args: argument list }
type version = int * int * int
module Decl : sig
val typ : ?modifier:type_mod -> qtype_def -> qtype
val mlname_type : qtype_def -> string
val custom_type : ?version:version -> ?kind:type_kind -> ?modifier:type_mod ->
?ml_decl:string -> ?ml_neg:string -> ?ml_name:string ->
string -> qtype_def
val qtype_kind : qtype_def -> type_kind
val qclass : ?version:version -> ?kind:type_kind -> ?modifier:type_mod ->
string -> qtype_def
val qstruct : ?version:version -> ?modifier:type_mod ->
string -> qtype_def
val qextends : ?version:version -> string -> ?modifier:type_mod ->
qtype_def -> qtype_def
val constructor : ?version:version -> ?custom:bool ->
string -> argument list -> cl:qtype_def -> unit
val dynamic :
?version:version ->
?kind:[ `Custom | `Normal | `Protected ] ->
?ret:qtype_def -> ?ret_mod:type_mod ->
string -> argument list -> cl:qtype_def -> unit
val static :
?version:version -> ?custom:bool -> ?ret:qtype_def -> ?ret_mod:type_mod ->
string -> argument list -> cl:qtype_def -> unit
val slot :
?version:version -> ?ret:qtype_def -> ?ret_mod:type_mod ->
?protected:bool -> string -> argument list -> cl:qtype_def -> unit
? ret : qtype_def - >
val signal :
?version:version ->
?private_:bool -> string -> argument list -> cl:qtype_def -> unit
val with_class : 'a -> (cl:'a -> unit) list -> unit
val qenum : ?version:version -> string -> string -> ?versioned:(version * string list) list -> string list -> qtype_def
val qflags : ?version:version -> qtype_def -> string -> qtype_def
val arg' : type_mod -> string -> qtype_def -> argument
val arg : ?modifier:type_mod -> string -> qtype_def -> argument
val opt : string -> qtype_def -> argument
val int : qtype_def
val bool : qtype_def
val float : qtype_def
val qString : qtype_def
val string : qtype_def
val pchar : qtype_def
val nativeint : qtype_def
val double : qtype_def
val qreal : qtype_def
val qint64 : qtype_def
val qRect : qtype_def
val qRectF : qtype_def
val qPoint : qtype_def
val qPointF : qtype_def
val qSize : qtype_def
val qSizeF : qtype_def
val iter_types : (qtype_def -> unit) -> unit
end
module QClass : sig
val kind : qclass -> [`By_ref | `By_val]
val extends : qclass -> qclass option
val iter_fields : qclass -> (cfield -> unit) -> unit
val ml_module : qclass -> string
val ml_shadow_type : qclass -> string
val ml_shadow_variant : qclass -> string
val cpp_type : qclass -> string
val c_base_symbol : qclass -> string
val c_field_base_symbol : cfield -> string
val field_class : cfield -> qclass
val field_desc : cfield -> cfield_desc
val field_name : cfield -> string
val stub_arity : cfield -> int option
val need_bc_wrapper : cfield -> bool
val is_QObject : qclass -> bool
end
module QEnum : sig
val ml_type : qenum -> string
val cpp_type : qenum -> string
val c_base_symbol : qenum -> string
type member
val ml_member_constructor : member -> string
val ml_member_hash : member -> int
val members : qenum -> member list
: qenum - > string
val cpp_member : qmember - > string
val cpp_member : qmember -> string*)
val cpp_qualified_member : member -> string
end
module QFlags : sig
val enum : qflags -> qenum
val cpp_type : qflags -> string
val ml_type : qflags -> string
val ml_enum_type : qflags -> string
val c_symbol : qflags -> string
end
| null |
https://raw.githubusercontent.com/let-def/cuite/42629a91c573ecbf1b01f213f1bf35a456d2b1af/spec/mlspec.mli
|
ocaml
|
type qclass
type cfield
type qenum
type qflags
type type_kind = [ `By_ref | `By_val ]
type type_mod =
[ `Direct
| `Pointer
| `Const
| `Const_ref
| `Ref
| `Optional
]
type qtype_def =
| QClass of qclass
| QEnum of qenum
| QFlags of qflags
| Custom of { ml_decl : string; ml_name : string; ml_negname : string;
cpp_name : string; cpp_kind : type_kind;
cpp_default_mod : type_mod;
}
type qtype = { typ_mod : type_mod; typ_def : qtype_def }
val eq_typdef : qtype_def -> qtype_def -> bool
val eq_typ : qtype -> qtype -> bool
type argument = string * qtype
val compatible_arg : argument -> argument -> bool
type cfield_desc =
| Constructor of { args: argument list; custom: bool }
| Dynamic_method of { ret: qtype option; args: argument list;
kind: [`Normal | `Custom | `Protected] }
| Static_method of { ret: qtype option; args: argument list; custom: bool }
| Signal of { args: argument list; private_: bool }
| Slot of { args: argument list }
type version = int * int * int
module Decl : sig
val typ : ?modifier:type_mod -> qtype_def -> qtype
val mlname_type : qtype_def -> string
val custom_type : ?version:version -> ?kind:type_kind -> ?modifier:type_mod ->
?ml_decl:string -> ?ml_neg:string -> ?ml_name:string ->
string -> qtype_def
val qtype_kind : qtype_def -> type_kind
val qclass : ?version:version -> ?kind:type_kind -> ?modifier:type_mod ->
string -> qtype_def
val qstruct : ?version:version -> ?modifier:type_mod ->
string -> qtype_def
val qextends : ?version:version -> string -> ?modifier:type_mod ->
qtype_def -> qtype_def
val constructor : ?version:version -> ?custom:bool ->
string -> argument list -> cl:qtype_def -> unit
val dynamic :
?version:version ->
?kind:[ `Custom | `Normal | `Protected ] ->
?ret:qtype_def -> ?ret_mod:type_mod ->
string -> argument list -> cl:qtype_def -> unit
val static :
?version:version -> ?custom:bool -> ?ret:qtype_def -> ?ret_mod:type_mod ->
string -> argument list -> cl:qtype_def -> unit
val slot :
?version:version -> ?ret:qtype_def -> ?ret_mod:type_mod ->
?protected:bool -> string -> argument list -> cl:qtype_def -> unit
? ret : qtype_def - >
val signal :
?version:version ->
?private_:bool -> string -> argument list -> cl:qtype_def -> unit
val with_class : 'a -> (cl:'a -> unit) list -> unit
val qenum : ?version:version -> string -> string -> ?versioned:(version * string list) list -> string list -> qtype_def
val qflags : ?version:version -> qtype_def -> string -> qtype_def
val arg' : type_mod -> string -> qtype_def -> argument
val arg : ?modifier:type_mod -> string -> qtype_def -> argument
val opt : string -> qtype_def -> argument
val int : qtype_def
val bool : qtype_def
val float : qtype_def
val qString : qtype_def
val string : qtype_def
val pchar : qtype_def
val nativeint : qtype_def
val double : qtype_def
val qreal : qtype_def
val qint64 : qtype_def
val qRect : qtype_def
val qRectF : qtype_def
val qPoint : qtype_def
val qPointF : qtype_def
val qSize : qtype_def
val qSizeF : qtype_def
val iter_types : (qtype_def -> unit) -> unit
end
module QClass : sig
val kind : qclass -> [`By_ref | `By_val]
val extends : qclass -> qclass option
val iter_fields : qclass -> (cfield -> unit) -> unit
val ml_module : qclass -> string
val ml_shadow_type : qclass -> string
val ml_shadow_variant : qclass -> string
val cpp_type : qclass -> string
val c_base_symbol : qclass -> string
val c_field_base_symbol : cfield -> string
val field_class : cfield -> qclass
val field_desc : cfield -> cfield_desc
val field_name : cfield -> string
val stub_arity : cfield -> int option
val need_bc_wrapper : cfield -> bool
val is_QObject : qclass -> bool
end
module QEnum : sig
val ml_type : qenum -> string
val cpp_type : qenum -> string
val c_base_symbol : qenum -> string
type member
val ml_member_constructor : member -> string
val ml_member_hash : member -> int
val members : qenum -> member list
: qenum - > string
val cpp_member : qmember - > string
val cpp_member : qmember -> string*)
val cpp_qualified_member : member -> string
end
module QFlags : sig
val enum : qflags -> qenum
val cpp_type : qflags -> string
val ml_type : qflags -> string
val ml_enum_type : qflags -> string
val c_symbol : qflags -> string
end
|
|
e05d53539d333d57c2a5a6811261ffa594f71696e08171beac844768f2f132ed
|
TerrorJack/ghc-alter
|
T1548.hs
|
import Text.Printf
main = do
printf "%.*f\n" (2::Int) ((1/3) :: Double)
( expected : " 0.33 " )
printf "%.3s\n" "foobar"
-- (expected: "foo")
printf "%10.5d\n" (4::Int)
( expected : " 00004 " )
| null |
https://raw.githubusercontent.com/TerrorJack/ghc-alter/db736f34095eef416b7e077f9b26fc03aa78c311/ghc-alter/boot-lib/base/tests/Text.Printf/T1548.hs
|
haskell
|
(expected: "foo")
|
import Text.Printf
main = do
printf "%.*f\n" (2::Int) ((1/3) :: Double)
( expected : " 0.33 " )
printf "%.3s\n" "foobar"
printf "%10.5d\n" (4::Int)
( expected : " 00004 " )
|
086b5329b00edaf91bdabec8cd969c47d1c43179ccafdfaa6e4dd8d2a845d4aa
|
maximedenes/native-coq
|
omega.ml
|
(************************************************************************)
v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2010
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
(* // * This file is distributed under the terms of the *)
(* * GNU Lesser General Public License Version 2.1 *)
(************************************************************************)
(**************************************************************************)
(* *)
Omega : a solver of quantifier - free problems in Presburger Arithmetic
(* *)
( CNET , Lannion , France )
(* *)
(* 13/10/2002 : modified to cope with an external numbering of equations *)
and hypothesis . Its use for Omega is not more complex and it makes
(* things much simpler for the reflexive version where we should limit *)
(* the number of source of numbering. *)
(**************************************************************************)
open Names
module type INT = sig
type bigint
val less_than : bigint -> bigint -> bool
val add : bigint -> bigint -> bigint
val sub : bigint -> bigint -> bigint
val mult : bigint -> bigint -> bigint
val euclid : bigint -> bigint -> bigint * bigint
val neg : bigint -> bigint
val zero : bigint
val one : bigint
val to_string : bigint -> string
end
let debug = ref false
module MakeOmegaSolver (Int:INT) = struct
type bigint = Int.bigint
let (<?) = Int.less_than
let (<=?) x y = Int.less_than x y or x = y
let (>?) x y = Int.less_than y x
let (>=?) x y = Int.less_than y x or x = y
let (=?) = (=)
let (+) = Int.add
let (-) = Int.sub
let ( * ) = Int.mult
let (/) x y = fst (Int.euclid x y)
let (mod) x y = snd (Int.euclid x y)
let zero = Int.zero
let one = Int.one
let two = one + one
let negone = Int.neg one
let abs x = if Int.less_than x zero then Int.neg x else x
let string_of_bigint = Int.to_string
let neg = Int.neg
(* To ensure that polymorphic (<) is not used mistakenly on big integers *)
(* Warning: do not use (=) either on big int *)
let (<) = ((<) : int -> int -> bool)
let (>) = ((>) : int -> int -> bool)
let (<=) = ((<=) : int -> int -> bool)
let (>=) = ((>=) : int -> int -> bool)
let pp i = print_int i; print_newline (); flush stdout
let push v l = l := v :: !l
let rec pgcd x y = if y =? zero then x else pgcd y (x mod y)
let pgcd_l = function
| [] -> failwith "pgcd_l"
| x :: l -> List.fold_left pgcd x l
let floor_div a b =
match a >=? zero , b >? zero with
| true,true -> a / b
| false,false -> a / b
| true, false -> (a-one) / b - one
| false,true -> (a+one) / b - one
type coeff = {c: bigint ; v: int}
type linear = coeff list
type eqn_kind = EQUA | INEQ | DISE
type afine = {
(* a number uniquely identifying the equation *)
id: int ;
(* a boolean true for an eq, false for an ineq (Sigma a_i x_i >= 0) *)
kind: eqn_kind;
(* the variables and their coefficient *)
body: coeff list;
(* a constant *)
constant: bigint }
type state_action = {
st_new_eq : afine;
st_def : afine;
st_orig : afine;
st_coef : bigint;
st_var : int }
type action =
| DIVIDE_AND_APPROX of afine * afine * bigint * bigint
| NOT_EXACT_DIVIDE of afine * bigint
| FORGET_C of int
| EXACT_DIVIDE of afine * bigint
| SUM of int * (bigint * afine) * (bigint * afine)
| STATE of state_action
| HYP of afine
| FORGET of int * int
| FORGET_I of int * int
| CONTRADICTION of afine * afine
| NEGATE_CONTRADICT of afine * afine * bool
| MERGE_EQ of int * afine * int
| CONSTANT_NOT_NUL of int * bigint
| CONSTANT_NUL of int
| CONSTANT_NEG of int * bigint
| SPLIT_INEQ of afine * (int * action list) * (int * action list)
| WEAKEN of int * bigint
exception UNSOLVABLE
exception NO_CONTRADICTION
let display_eq print_var (l,e) =
let _ =
List.fold_left
(fun not_first f ->
print_string
(if f.c <? zero then "- " else if not_first then "+ " else "");
let c = abs f.c in
if c =? one then
Printf.printf "%s " (print_var f.v)
else
Printf.printf "%s %s " (string_of_bigint c) (print_var f.v);
true)
false l
in
if e >? zero then
Printf.printf "+ %s " (string_of_bigint e)
else if e <? zero then
Printf.printf "- %s " (string_of_bigint (abs e))
let rec trace_length l =
let action_length accu = function
| SPLIT_INEQ (_,(_,l1),(_,l2)) ->
accu + one + trace_length l1 + trace_length l2
| _ -> accu + one in
List.fold_left action_length zero l
let operator_of_eq = function
| EQUA -> "=" | DISE -> "!=" | INEQ -> ">="
let kind_of = function
| EQUA -> "equation" | DISE -> "disequation" | INEQ -> "inequation"
let display_system print_var l =
List.iter
(fun { kind=b; body=e; constant=c; id=id} ->
Printf.printf "E%d: " id;
display_eq print_var (e,c);
Printf.printf "%s 0\n" (operator_of_eq b))
l;
print_string "------------------------\n\n"
let display_inequations print_var l =
List.iter (fun e -> display_eq print_var e;print_string ">= 0\n") l;
print_string "------------------------\n\n"
let sbi = string_of_bigint
let rec display_action print_var = function
| act :: l -> begin match act with
| DIVIDE_AND_APPROX (e1,e2,k,d) ->
Printf.printf
"Inequation E%d is divided by %s and the constant coefficient is \
rounded by substracting %s.\n" e1.id (sbi k) (sbi d)
| NOT_EXACT_DIVIDE (e,k) ->
Printf.printf
"Constant in equation E%d is not divisible by the pgcd \
%s of its other coefficients.\n" e.id (sbi k)
| EXACT_DIVIDE (e,k) ->
Printf.printf
"Equation E%d is divided by the pgcd \
%s of its coefficients.\n" e.id (sbi k)
| WEAKEN (e,k) ->
Printf.printf
"To ensure a solution in the dark shadow \
the equation E%d is weakened by %s.\n" e (sbi k)
| SUM (e,(c1,e1),(c2,e2)) ->
Printf.printf
"We state %s E%d = %s %s E%d + %s %s E%d.\n"
(kind_of e1.kind) e (sbi c1) (kind_of e1.kind) e1.id (sbi c2)
(kind_of e2.kind) e2.id
| STATE { st_new_eq = e } ->
Printf.printf "We define a new equation E%d: " e.id;
display_eq print_var (e.body,e.constant);
print_string (operator_of_eq e.kind); print_string " 0"
| HYP e ->
Printf.printf "We define E%d: " e.id;
display_eq print_var (e.body,e.constant);
print_string (operator_of_eq e.kind); print_string " 0\n"
| FORGET_C e -> Printf.printf "E%d is trivially satisfiable.\n" e
| FORGET (e1,e2) -> Printf.printf "E%d subsumes E%d.\n" e1 e2
| FORGET_I (e1,e2) -> Printf.printf "E%d subsumes E%d.\n" e1 e2
| MERGE_EQ (e,e1,e2) ->
Printf.printf "E%d and E%d can be merged into E%d.\n" e1.id e2 e
| CONTRADICTION (e1,e2) ->
Printf.printf
"Equations E%d and E%d imply a contradiction on their \
constant factors.\n" e1.id e2.id
| NEGATE_CONTRADICT(e1,e2,b) ->
Printf.printf
"Equations E%d and E%d state that their body is at the same time \
equal and different\n" e1.id e2.id
| CONSTANT_NOT_NUL (e,k) ->
Printf.printf "Equation E%d states %s = 0.\n" e (sbi k)
| CONSTANT_NEG(e,k) ->
Printf.printf "Equation E%d states %s >= 0.\n" e (sbi k)
| CONSTANT_NUL e ->
Printf.printf "Inequation E%d states 0 != 0.\n" e
| SPLIT_INEQ (e,(e1,l1),(e2,l2)) ->
Printf.printf "Equation E%d is split in E%d and E%d\n\n" e.id e1 e2;
display_action print_var l1;
print_newline ();
display_action print_var l2;
print_newline ()
end; display_action print_var l
| [] ->
flush stdout
let default_print_var v = Printf.sprintf "X%d" v (* For debugging *)
(*""*)
let add_event, history, clear_history =
let accu = ref [] in
(fun (v:action) -> if !debug then display_action default_print_var [v]; push v accu),
(fun () -> !accu),
(fun () -> accu := [])
let nf_linear = Sort.list (fun x y -> x.v > y.v)
let nf ((b : bool),(e,(x : int))) = (b,(nf_linear e,x))
let map_eq_linear f =
let rec loop = function
| x :: l -> let c = f x.c in if c=?zero then loop l else {v=x.v; c=c} :: loop l
| [] -> []
in
loop
let map_eq_afine f e =
{ id = e.id; kind = e.kind; body = map_eq_linear f e.body;
constant = f e.constant }
let negate_eq = map_eq_afine (fun x -> neg x)
let rec sum p0 p1 = match (p0,p1) with
| ([], l) -> l | (l, []) -> l
| (((x1::l1) as l1'), ((x2::l2) as l2')) ->
if x1.v = x2.v then
let c = x1.c + x2.c in
if c =? zero then sum l1 l2 else {v=x1.v;c=c} :: sum l1 l2
else if x1.v > x2.v then
x1 :: sum l1 l2'
else
x2 :: sum l1' l2
let sum_afine new_eq_id eq1 eq2 =
{ kind = eq1.kind; id = new_eq_id ();
body = sum eq1.body eq2.body; constant = eq1.constant + eq2.constant }
exception FACTOR1
let rec chop_factor_1 = function
| x :: l ->
if abs x.c =? one then x,l else let (c',l') = chop_factor_1 l in (c',x::l')
| [] -> raise FACTOR1
exception CHOPVAR
let rec chop_var v = function
| f :: l -> if f.v = v then f,l else let (f',l') = chop_var v l in (f',f::l')
| [] -> raise CHOPVAR
let normalize ({id=id; kind=eq_flag; body=e; constant =x} as eq) =
if e = [] then begin
match eq_flag with
| EQUA ->
if x =? zero then [] else begin
add_event (CONSTANT_NOT_NUL(id,x)); raise UNSOLVABLE
end
| DISE ->
if x <> zero then [] else begin
add_event (CONSTANT_NUL id); raise UNSOLVABLE
end
| INEQ ->
if x >=? zero then [] else begin
add_event (CONSTANT_NEG(id,x)); raise UNSOLVABLE
end
end else
let gcd = pgcd_l (List.map (fun f -> abs f.c) e) in
if eq_flag=EQUA & x mod gcd <> zero then begin
add_event (NOT_EXACT_DIVIDE (eq,gcd)); raise UNSOLVABLE
end else if eq_flag=DISE & x mod gcd <> zero then begin
add_event (FORGET_C eq.id); []
end else if gcd <> one then begin
let c = floor_div x gcd in
let d = x - c * gcd in
let new_eq = {id=id; kind=eq_flag; constant=c;
body=map_eq_linear (fun c -> c / gcd) e} in
add_event (if eq_flag=EQUA or eq_flag = DISE then EXACT_DIVIDE(eq,gcd)
else DIVIDE_AND_APPROX(eq,new_eq,gcd,d));
[new_eq]
end else [eq]
let eliminate_with_in new_eq_id {v=v;c=c_unite} eq2
({body=e1; constant=c1} as eq1) =
try
let (f,_) = chop_var v e1 in
let coeff = if c_unite=?one then neg f.c else if c_unite=? negone then f.c
else failwith "eliminate_with_in" in
let res = sum_afine new_eq_id eq1 (map_eq_afine (fun c -> c * coeff) eq2) in
add_event (SUM (res.id,(one,eq1),(coeff,eq2))); res
with CHOPVAR -> eq1
let omega_mod a b = a - b * floor_div (two * a + b) (two * b)
let banerjee_step (new_eq_id,new_var_id,print_var) original l1 l2 =
let e = original.body in
let sigma = new_var_id () in
let smallest,var =
try
List.fold_left (fun (v,p) c -> if v >? (abs c.c) then abs c.c,c.v else (v,p))
(abs (List.hd e).c, (List.hd e).v) (List.tl e)
with Failure "tl" -> display_system print_var [original] ; failwith "TL" in
let m = smallest + one in
let new_eq =
{ constant = omega_mod original.constant m;
body = {c= neg m;v=sigma} ::
map_eq_linear (fun a -> omega_mod a m) original.body;
id = new_eq_id (); kind = EQUA } in
let definition =
{ constant = neg (floor_div (two * original.constant + m) (two * m));
body = map_eq_linear (fun a -> neg (floor_div (two * a + m) (two * m)))
original.body;
id = new_eq_id (); kind = EQUA } in
add_event (STATE {st_new_eq = new_eq; st_def = definition;
st_orig = original; st_coef = m; st_var = sigma});
let new_eq = List.hd (normalize new_eq) in
let eliminated_var, def = chop_var var new_eq.body in
let other_equations =
Util.list_map_append
(fun e ->
normalize (eliminate_with_in new_eq_id eliminated_var new_eq e)) l1 in
let inequations =
Util.list_map_append
(fun e ->
normalize (eliminate_with_in new_eq_id eliminated_var new_eq e)) l2 in
let original' = eliminate_with_in new_eq_id eliminated_var new_eq original in
let mod_original = map_eq_afine (fun c -> c / m) original' in
add_event (EXACT_DIVIDE (original',m));
List.hd (normalize mod_original),other_equations,inequations
let rec eliminate_one_equation ((new_eq_id,new_var_id,print_var) as new_ids) (e,other,ineqs) =
if !debug then display_system print_var (e::other);
try
let v,def = chop_factor_1 e.body in
(Util.list_map_append
(fun e' -> normalize (eliminate_with_in new_eq_id v e e')) other,
Util.list_map_append
(fun e' -> normalize (eliminate_with_in new_eq_id v e e')) ineqs)
with FACTOR1 ->
eliminate_one_equation new_ids (banerjee_step new_ids e other ineqs)
let rec banerjee ((_,_,print_var) as new_ids) (sys_eq,sys_ineq) =
let rec fst_eq_1 = function
(eq::l) ->
if List.exists (fun x -> abs x.c =? one) eq.body then eq,l
else let (eq',l') = fst_eq_1 l in (eq',eq::l')
| [] -> raise Not_found in
match sys_eq with
[] -> if !debug then display_system print_var sys_ineq; sys_ineq
| (e1::rest) ->
let eq,other = try fst_eq_1 sys_eq with Not_found -> (e1,rest) in
if eq.body = [] then
if eq.constant =? zero then begin
add_event (FORGET_C eq.id); banerjee new_ids (other,sys_ineq)
end else begin
add_event (CONSTANT_NOT_NUL(eq.id,eq.constant)); raise UNSOLVABLE
end
else
banerjee new_ids
(eliminate_one_equation new_ids (eq,other,sys_ineq))
type kind = INVERTED | NORMAL
let redundancy_elimination new_eq_id system =
let normal = function
({body=f::_} as e) when f.c <? zero -> negate_eq e, INVERTED
| e -> e,NORMAL in
let table = Hashtbl.create 7 in
List.iter
(fun e ->
let ({body=ne} as nx) ,kind = normal e in
if ne = [] then
if nx.constant <? zero then begin
add_event (CONSTANT_NEG(nx.id,nx.constant)); raise UNSOLVABLE
end else add_event (FORGET_C nx.id)
else
try
let (optnormal,optinvert) = Hashtbl.find table ne in
let final =
if kind = NORMAL then begin
match optnormal with
Some v ->
let kept =
if v.constant <? nx.constant
then begin add_event (FORGET (v.id,nx.id));v end
else begin add_event (FORGET (nx.id,v.id));nx end in
(Some(kept),optinvert)
| None -> Some nx,optinvert
end else begin
match optinvert with
Some v ->
let _kept =
if v.constant >? nx.constant
then begin add_event (FORGET_I (v.id,nx.id));v end
else begin add_event (FORGET_I (nx.id,v.id));nx end in
(optnormal,Some(if v.constant >? nx.constant then v else nx))
| None -> optnormal,Some nx
end in
begin match final with
(Some high, Some low) ->
if high.constant <? low.constant then begin
add_event(CONTRADICTION (high,negate_eq low));
raise UNSOLVABLE
end
| _ -> () end;
Hashtbl.remove table ne;
Hashtbl.add table ne final
with Not_found ->
Hashtbl.add table ne
(if kind = NORMAL then (Some nx,None) else (None,Some nx)))
system;
let accu_eq = ref [] in
let accu_ineq = ref [] in
Hashtbl.iter
(fun p0 p1 -> match (p0,p1) with
| (e, (Some x, Some y)) when x.constant =? y.constant ->
let id=new_eq_id () in
add_event (MERGE_EQ(id,x,y.id));
push {id=id; kind=EQUA; body=x.body; constant=x.constant} accu_eq
| (e, (optnorm,optinvert)) ->
begin match optnorm with
Some x -> push x accu_ineq | _ -> () end;
begin match optinvert with
Some x -> push (negate_eq x) accu_ineq | _ -> () end)
table;
!accu_eq,!accu_ineq
exception SOLVED_SYSTEM
let select_variable system =
let table = Hashtbl.create 7 in
let push v c=
try let r = Hashtbl.find table v in r := max !r (abs c)
with Not_found -> Hashtbl.add table v (ref (abs c)) in
List.iter (fun {body=l} -> List.iter (fun f -> push f.v f.c) l) system;
let vmin,cmin = ref (-1), ref zero in
let var_cpt = ref 0 in
Hashtbl.iter
(fun v ({contents = c}) ->
incr var_cpt;
if c <? !cmin or !vmin = (-1) then begin vmin := v; cmin := c end)
table;
if !var_cpt < 1 then raise SOLVED_SYSTEM;
!vmin
let classify v system =
List.fold_left
(fun (not_occ,below,over) eq ->
try let f,eq' = chop_var v eq.body in
if f.c >=? zero then (not_occ,((f.c,eq) :: below),over)
else (not_occ,below,((neg f.c,eq) :: over))
with CHOPVAR -> (eq::not_occ,below,over))
([],[],[]) system
let product new_eq_id dark_shadow low high =
List.fold_left
(fun accu (a,eq1) ->
List.fold_left
(fun accu (b,eq2) ->
let eq =
sum_afine new_eq_id (map_eq_afine (fun c -> c * b) eq1)
(map_eq_afine (fun c -> c * a) eq2) in
add_event(SUM(eq.id,(b,eq1),(a,eq2)));
match normalize eq with
| [eq] ->
let final_eq =
if dark_shadow then
let delta = (a - one) * (b - one) in
add_event(WEAKEN(eq.id,delta));
{id = eq.id; kind=INEQ; body = eq.body;
constant = eq.constant - delta}
else eq
in final_eq :: accu
| (e::_) -> failwith "Product dardk"
| [] -> accu)
accu high)
[] low
let fourier_motzkin (new_eq_id,_,print_var) dark_shadow system =
let v = select_variable system in
let (ineq_out, ineq_low,ineq_high) = classify v system in
let expanded = ineq_out @ product new_eq_id dark_shadow ineq_low ineq_high in
if !debug then display_system print_var expanded; expanded
let simplify ((new_eq_id,new_var_id,print_var) as new_ids) dark_shadow system =
if List.exists (fun e -> e.kind = DISE) system then
failwith "disequation in simplify";
clear_history ();
List.iter (fun e -> add_event (HYP e)) system;
let system = Util.list_map_append normalize system in
let eqs,ineqs = List.partition (fun e -> e.kind=EQUA) system in
let simp_eq,simp_ineq = redundancy_elimination new_eq_id ineqs in
let system = (eqs @ simp_eq,simp_ineq) in
let rec loop1a system =
let sys_ineq = banerjee new_ids system in
loop1b sys_ineq
and loop1b sys_ineq =
let simp_eq,simp_ineq = redundancy_elimination new_eq_id sys_ineq in
if simp_eq = [] then simp_ineq else loop1a (simp_eq,simp_ineq)
in
let rec loop2 system =
try
let expanded = fourier_motzkin new_ids dark_shadow system in
loop2 (loop1b expanded)
with SOLVED_SYSTEM ->
if !debug then display_system print_var system; system
in
loop2 (loop1a system)
let rec depend relie_on accu = function
| act :: l ->
begin match act with
| DIVIDE_AND_APPROX (e,_,_,_) ->
if List.mem e.id relie_on then depend relie_on (act::accu) l
else depend relie_on accu l
| EXACT_DIVIDE (e,_) ->
if List.mem e.id relie_on then depend relie_on (act::accu) l
else depend relie_on accu l
| WEAKEN (e,_) ->
if List.mem e relie_on then depend relie_on (act::accu) l
else depend relie_on accu l
| SUM (e,(_,e1),(_,e2)) ->
if List.mem e relie_on then
depend (e1.id::e2.id::relie_on) (act::accu) l
else
depend relie_on accu l
| STATE {st_new_eq=e;st_orig=o} ->
if List.mem e.id relie_on then depend (o.id::relie_on) (act::accu) l
else depend relie_on accu l
| HYP e ->
if List.mem e.id relie_on then depend relie_on (act::accu) l
else depend relie_on accu l
| FORGET_C _ -> depend relie_on accu l
| FORGET _ -> depend relie_on accu l
| FORGET_I _ -> depend relie_on accu l
| MERGE_EQ (e,e1,e2) ->
if List.mem e relie_on then
depend (e1.id::e2::relie_on) (act::accu) l
else
depend relie_on accu l
| NOT_EXACT_DIVIDE (e,_) -> depend (e.id::relie_on) (act::accu) l
| CONTRADICTION (e1,e2) ->
depend (e1.id::e2.id::relie_on) (act::accu) l
| CONSTANT_NOT_NUL (e,_) -> depend (e::relie_on) (act::accu) l
| CONSTANT_NEG (e,_) -> depend (e::relie_on) (act::accu) l
| CONSTANT_NUL e -> depend (e::relie_on) (act::accu) l
| NEGATE_CONTRADICT (e1,e2,_) ->
depend (e1.id::e2.id::relie_on) (act::accu) l
| SPLIT_INEQ _ -> failwith "depend"
end
| [] -> relie_on, accu
let depend relie_on accu trace =
Printf.printf " Longueur de la trace initiale : % d\n "
( trace_length trace + trace_length accu ) ;
let rel',trace ' = depend relie_on accu trace in
Printf.printf " Longueur de la trace simplifiée : % d\n " ( trace_length trace ' ) ;
rel',trace '
let depend relie_on accu trace =
Printf.printf "Longueur de la trace initiale : %d\n"
(trace_length trace + trace_length accu);
let rel',trace' = depend relie_on accu trace in
Printf.printf "Longueur de la trace simplifiée : %d\n" (trace_length trace');
rel',trace'
*)
let solve (new_eq_id,new_eq_var,print_var) system =
try let _ = simplify new_eq_id false system in failwith "no contradiction"
with UNSOLVABLE -> display_action print_var (snd (depend [] [] (history ())))
let negation (eqs,ineqs) =
let diseq,_ = List.partition (fun e -> e.kind = DISE) ineqs in
let normal = function
| ({body=f::_} as e) when f.c <? zero -> negate_eq e, INVERTED
| e -> e,NORMAL in
let table = Hashtbl.create 7 in
List.iter (fun e ->
let {body=ne;constant=c} ,kind = normal e in
Hashtbl.add table (ne,c) (kind,e)) diseq;
List.iter (fun e ->
assert (e.kind = EQUA);
let {body=ne;constant=c},kind = normal e in
try
let (kind',e') = Hashtbl.find table (ne,c) in
add_event (NEGATE_CONTRADICT (e,e',kind=kind'));
raise UNSOLVABLE
with Not_found -> ()) eqs
exception FULL_SOLUTION of action list * int list
let simplify_strong ((new_eq_id,new_var_id,print_var) as new_ids) system =
clear_history ();
List.iter (fun e -> add_event (HYP e)) system;
(* Initial simplification phase *)
let rec loop1a system =
negation system;
let sys_ineq = banerjee new_ids system in
loop1b sys_ineq
and loop1b sys_ineq =
let dise,ine = List.partition (fun e -> e.kind = DISE) sys_ineq in
let simp_eq,simp_ineq = redundancy_elimination new_eq_id ine in
if simp_eq = [] then dise @ simp_ineq
else loop1a (simp_eq,dise @ simp_ineq)
in
let rec loop2 system =
try
let expanded = fourier_motzkin new_ids false system in
loop2 (loop1b expanded)
with SOLVED_SYSTEM -> if !debug then display_system print_var system; system
in
let rec explode_diseq = function
| (de::diseq,ineqs,expl_map) ->
let id1 = new_eq_id ()
and id2 = new_eq_id () in
let e1 =
{id = id1; kind=INEQ; body = de.body; constant = de.constant -one} in
let e2 =
{id = id2; kind=INEQ; body = map_eq_linear neg de.body;
constant = neg de.constant - one} in
let new_sys =
List.map (fun (what,sys) -> ((de.id,id1,true)::what, e1::sys))
ineqs @
List.map (fun (what,sys) -> ((de.id,id2,false)::what,e2::sys))
ineqs
in
explode_diseq (diseq,new_sys,(de.id,(de,id1,id2))::expl_map)
| ([],ineqs,expl_map) -> ineqs,expl_map
in
try
let system = Util.list_map_append normalize system in
let eqs,ineqs = List.partition (fun e -> e.kind=EQUA) system in
let dise,ine = List.partition (fun e -> e.kind = DISE) ineqs in
let simp_eq,simp_ineq = redundancy_elimination new_eq_id ine in
let system = (eqs @ simp_eq,simp_ineq @ dise) in
let system' = loop1a system in
let diseq,ineq = List.partition (fun e -> e.kind = DISE) system' in
let first_segment = history () in
let sys_exploded,explode_map = explode_diseq (diseq,[[],ineq],[]) in
let all_solutions =
List.map
(fun (decomp,sys) ->
clear_history ();
try let _ = loop2 sys in raise NO_CONTRADICTION
with UNSOLVABLE ->
let relie_on,path = depend [] [] (history ()) in
let dc,_ = List.partition (fun (_,id,_) -> List.mem id relie_on) decomp in
let red = List.map (fun (x,_,_) -> x) dc in
(red,relie_on,decomp,path))
sys_exploded
in
let max_count sys =
let tbl = Hashtbl.create 7 in
let augment x =
try incr (Hashtbl.find tbl x)
with Not_found -> Hashtbl.add tbl x (ref 1) in
let eq = ref (-1) and c = ref 0 in
List.iter (function
| ([],r_on,_,path) -> raise (FULL_SOLUTION (path,r_on))
| (l,_,_,_) -> List.iter augment l) sys;
Hashtbl.iter (fun x v -> if !v > !c then begin eq := x; c := !v end) tbl;
!eq
in
let rec solve systems =
try
let id = max_count systems in
let rec sign = function
| ((id',_,b)::l) -> if id=id' then b else sign l
| [] -> failwith "solve" in
let s1,s2 =
List.partition (fun (_,_,decomp,_) -> sign decomp) systems in
let s1' =
List.map (fun (dep,ro,dc,pa) -> (Util.list_except id dep,ro,dc,pa)) s1 in
let s2' =
List.map (fun (dep,ro,dc,pa) -> (Util.list_except id dep,ro,dc,pa)) s2 in
let (r1,relie1) = solve s1'
and (r2,relie2) = solve s2' in
let (eq,id1,id2) = List.assoc id explode_map in
[SPLIT_INEQ(eq,(id1,r1),(id2, r2))], eq.id :: Util.list_union relie1 relie2
with FULL_SOLUTION (x0,x1) -> (x0,x1)
in
let act,relie_on = solve all_solutions in
snd(depend relie_on act first_segment)
with UNSOLVABLE -> snd (depend [] [] (history ()))
end
| null |
https://raw.githubusercontent.com/maximedenes/native-coq/3623a4d9fe95c165f02f7119c0e6564a83a9f4c9/plugins/omega/omega.ml
|
ocaml
|
**********************************************************************
// * This file is distributed under the terms of the
* GNU Lesser General Public License Version 2.1
**********************************************************************
************************************************************************
13/10/2002 : modified to cope with an external numbering of equations
things much simpler for the reflexive version where we should limit
the number of source of numbering.
************************************************************************
To ensure that polymorphic (<) is not used mistakenly on big integers
Warning: do not use (=) either on big int
a number uniquely identifying the equation
a boolean true for an eq, false for an ineq (Sigma a_i x_i >= 0)
the variables and their coefficient
a constant
For debugging
""
Initial simplification phase
|
v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2010
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
Omega : a solver of quantifier - free problems in Presburger Arithmetic
( CNET , Lannion , France )
and hypothesis . Its use for Omega is not more complex and it makes
open Names
module type INT = sig
type bigint
val less_than : bigint -> bigint -> bool
val add : bigint -> bigint -> bigint
val sub : bigint -> bigint -> bigint
val mult : bigint -> bigint -> bigint
val euclid : bigint -> bigint -> bigint * bigint
val neg : bigint -> bigint
val zero : bigint
val one : bigint
val to_string : bigint -> string
end
let debug = ref false
module MakeOmegaSolver (Int:INT) = struct
type bigint = Int.bigint
let (<?) = Int.less_than
let (<=?) x y = Int.less_than x y or x = y
let (>?) x y = Int.less_than y x
let (>=?) x y = Int.less_than y x or x = y
let (=?) = (=)
let (+) = Int.add
let (-) = Int.sub
let ( * ) = Int.mult
let (/) x y = fst (Int.euclid x y)
let (mod) x y = snd (Int.euclid x y)
let zero = Int.zero
let one = Int.one
let two = one + one
let negone = Int.neg one
let abs x = if Int.less_than x zero then Int.neg x else x
let string_of_bigint = Int.to_string
let neg = Int.neg
let (<) = ((<) : int -> int -> bool)
let (>) = ((>) : int -> int -> bool)
let (<=) = ((<=) : int -> int -> bool)
let (>=) = ((>=) : int -> int -> bool)
let pp i = print_int i; print_newline (); flush stdout
let push v l = l := v :: !l
let rec pgcd x y = if y =? zero then x else pgcd y (x mod y)
let pgcd_l = function
| [] -> failwith "pgcd_l"
| x :: l -> List.fold_left pgcd x l
let floor_div a b =
match a >=? zero , b >? zero with
| true,true -> a / b
| false,false -> a / b
| true, false -> (a-one) / b - one
| false,true -> (a+one) / b - one
type coeff = {c: bigint ; v: int}
type linear = coeff list
type eqn_kind = EQUA | INEQ | DISE
type afine = {
id: int ;
kind: eqn_kind;
body: coeff list;
constant: bigint }
type state_action = {
st_new_eq : afine;
st_def : afine;
st_orig : afine;
st_coef : bigint;
st_var : int }
type action =
| DIVIDE_AND_APPROX of afine * afine * bigint * bigint
| NOT_EXACT_DIVIDE of afine * bigint
| FORGET_C of int
| EXACT_DIVIDE of afine * bigint
| SUM of int * (bigint * afine) * (bigint * afine)
| STATE of state_action
| HYP of afine
| FORGET of int * int
| FORGET_I of int * int
| CONTRADICTION of afine * afine
| NEGATE_CONTRADICT of afine * afine * bool
| MERGE_EQ of int * afine * int
| CONSTANT_NOT_NUL of int * bigint
| CONSTANT_NUL of int
| CONSTANT_NEG of int * bigint
| SPLIT_INEQ of afine * (int * action list) * (int * action list)
| WEAKEN of int * bigint
exception UNSOLVABLE
exception NO_CONTRADICTION
let display_eq print_var (l,e) =
let _ =
List.fold_left
(fun not_first f ->
print_string
(if f.c <? zero then "- " else if not_first then "+ " else "");
let c = abs f.c in
if c =? one then
Printf.printf "%s " (print_var f.v)
else
Printf.printf "%s %s " (string_of_bigint c) (print_var f.v);
true)
false l
in
if e >? zero then
Printf.printf "+ %s " (string_of_bigint e)
else if e <? zero then
Printf.printf "- %s " (string_of_bigint (abs e))
let rec trace_length l =
let action_length accu = function
| SPLIT_INEQ (_,(_,l1),(_,l2)) ->
accu + one + trace_length l1 + trace_length l2
| _ -> accu + one in
List.fold_left action_length zero l
let operator_of_eq = function
| EQUA -> "=" | DISE -> "!=" | INEQ -> ">="
let kind_of = function
| EQUA -> "equation" | DISE -> "disequation" | INEQ -> "inequation"
let display_system print_var l =
List.iter
(fun { kind=b; body=e; constant=c; id=id} ->
Printf.printf "E%d: " id;
display_eq print_var (e,c);
Printf.printf "%s 0\n" (operator_of_eq b))
l;
print_string "------------------------\n\n"
let display_inequations print_var l =
List.iter (fun e -> display_eq print_var e;print_string ">= 0\n") l;
print_string "------------------------\n\n"
let sbi = string_of_bigint
let rec display_action print_var = function
| act :: l -> begin match act with
| DIVIDE_AND_APPROX (e1,e2,k,d) ->
Printf.printf
"Inequation E%d is divided by %s and the constant coefficient is \
rounded by substracting %s.\n" e1.id (sbi k) (sbi d)
| NOT_EXACT_DIVIDE (e,k) ->
Printf.printf
"Constant in equation E%d is not divisible by the pgcd \
%s of its other coefficients.\n" e.id (sbi k)
| EXACT_DIVIDE (e,k) ->
Printf.printf
"Equation E%d is divided by the pgcd \
%s of its coefficients.\n" e.id (sbi k)
| WEAKEN (e,k) ->
Printf.printf
"To ensure a solution in the dark shadow \
the equation E%d is weakened by %s.\n" e (sbi k)
| SUM (e,(c1,e1),(c2,e2)) ->
Printf.printf
"We state %s E%d = %s %s E%d + %s %s E%d.\n"
(kind_of e1.kind) e (sbi c1) (kind_of e1.kind) e1.id (sbi c2)
(kind_of e2.kind) e2.id
| STATE { st_new_eq = e } ->
Printf.printf "We define a new equation E%d: " e.id;
display_eq print_var (e.body,e.constant);
print_string (operator_of_eq e.kind); print_string " 0"
| HYP e ->
Printf.printf "We define E%d: " e.id;
display_eq print_var (e.body,e.constant);
print_string (operator_of_eq e.kind); print_string " 0\n"
| FORGET_C e -> Printf.printf "E%d is trivially satisfiable.\n" e
| FORGET (e1,e2) -> Printf.printf "E%d subsumes E%d.\n" e1 e2
| FORGET_I (e1,e2) -> Printf.printf "E%d subsumes E%d.\n" e1 e2
| MERGE_EQ (e,e1,e2) ->
Printf.printf "E%d and E%d can be merged into E%d.\n" e1.id e2 e
| CONTRADICTION (e1,e2) ->
Printf.printf
"Equations E%d and E%d imply a contradiction on their \
constant factors.\n" e1.id e2.id
| NEGATE_CONTRADICT(e1,e2,b) ->
Printf.printf
"Equations E%d and E%d state that their body is at the same time \
equal and different\n" e1.id e2.id
| CONSTANT_NOT_NUL (e,k) ->
Printf.printf "Equation E%d states %s = 0.\n" e (sbi k)
| CONSTANT_NEG(e,k) ->
Printf.printf "Equation E%d states %s >= 0.\n" e (sbi k)
| CONSTANT_NUL e ->
Printf.printf "Inequation E%d states 0 != 0.\n" e
| SPLIT_INEQ (e,(e1,l1),(e2,l2)) ->
Printf.printf "Equation E%d is split in E%d and E%d\n\n" e.id e1 e2;
display_action print_var l1;
print_newline ();
display_action print_var l2;
print_newline ()
end; display_action print_var l
| [] ->
flush stdout
let add_event, history, clear_history =
let accu = ref [] in
(fun (v:action) -> if !debug then display_action default_print_var [v]; push v accu),
(fun () -> !accu),
(fun () -> accu := [])
let nf_linear = Sort.list (fun x y -> x.v > y.v)
let nf ((b : bool),(e,(x : int))) = (b,(nf_linear e,x))
let map_eq_linear f =
let rec loop = function
| x :: l -> let c = f x.c in if c=?zero then loop l else {v=x.v; c=c} :: loop l
| [] -> []
in
loop
let map_eq_afine f e =
{ id = e.id; kind = e.kind; body = map_eq_linear f e.body;
constant = f e.constant }
let negate_eq = map_eq_afine (fun x -> neg x)
let rec sum p0 p1 = match (p0,p1) with
| ([], l) -> l | (l, []) -> l
| (((x1::l1) as l1'), ((x2::l2) as l2')) ->
if x1.v = x2.v then
let c = x1.c + x2.c in
if c =? zero then sum l1 l2 else {v=x1.v;c=c} :: sum l1 l2
else if x1.v > x2.v then
x1 :: sum l1 l2'
else
x2 :: sum l1' l2
let sum_afine new_eq_id eq1 eq2 =
{ kind = eq1.kind; id = new_eq_id ();
body = sum eq1.body eq2.body; constant = eq1.constant + eq2.constant }
exception FACTOR1
let rec chop_factor_1 = function
| x :: l ->
if abs x.c =? one then x,l else let (c',l') = chop_factor_1 l in (c',x::l')
| [] -> raise FACTOR1
exception CHOPVAR
let rec chop_var v = function
| f :: l -> if f.v = v then f,l else let (f',l') = chop_var v l in (f',f::l')
| [] -> raise CHOPVAR
let normalize ({id=id; kind=eq_flag; body=e; constant =x} as eq) =
if e = [] then begin
match eq_flag with
| EQUA ->
if x =? zero then [] else begin
add_event (CONSTANT_NOT_NUL(id,x)); raise UNSOLVABLE
end
| DISE ->
if x <> zero then [] else begin
add_event (CONSTANT_NUL id); raise UNSOLVABLE
end
| INEQ ->
if x >=? zero then [] else begin
add_event (CONSTANT_NEG(id,x)); raise UNSOLVABLE
end
end else
let gcd = pgcd_l (List.map (fun f -> abs f.c) e) in
if eq_flag=EQUA & x mod gcd <> zero then begin
add_event (NOT_EXACT_DIVIDE (eq,gcd)); raise UNSOLVABLE
end else if eq_flag=DISE & x mod gcd <> zero then begin
add_event (FORGET_C eq.id); []
end else if gcd <> one then begin
let c = floor_div x gcd in
let d = x - c * gcd in
let new_eq = {id=id; kind=eq_flag; constant=c;
body=map_eq_linear (fun c -> c / gcd) e} in
add_event (if eq_flag=EQUA or eq_flag = DISE then EXACT_DIVIDE(eq,gcd)
else DIVIDE_AND_APPROX(eq,new_eq,gcd,d));
[new_eq]
end else [eq]
let eliminate_with_in new_eq_id {v=v;c=c_unite} eq2
({body=e1; constant=c1} as eq1) =
try
let (f,_) = chop_var v e1 in
let coeff = if c_unite=?one then neg f.c else if c_unite=? negone then f.c
else failwith "eliminate_with_in" in
let res = sum_afine new_eq_id eq1 (map_eq_afine (fun c -> c * coeff) eq2) in
add_event (SUM (res.id,(one,eq1),(coeff,eq2))); res
with CHOPVAR -> eq1
let omega_mod a b = a - b * floor_div (two * a + b) (two * b)
let banerjee_step (new_eq_id,new_var_id,print_var) original l1 l2 =
let e = original.body in
let sigma = new_var_id () in
let smallest,var =
try
List.fold_left (fun (v,p) c -> if v >? (abs c.c) then abs c.c,c.v else (v,p))
(abs (List.hd e).c, (List.hd e).v) (List.tl e)
with Failure "tl" -> display_system print_var [original] ; failwith "TL" in
let m = smallest + one in
let new_eq =
{ constant = omega_mod original.constant m;
body = {c= neg m;v=sigma} ::
map_eq_linear (fun a -> omega_mod a m) original.body;
id = new_eq_id (); kind = EQUA } in
let definition =
{ constant = neg (floor_div (two * original.constant + m) (two * m));
body = map_eq_linear (fun a -> neg (floor_div (two * a + m) (two * m)))
original.body;
id = new_eq_id (); kind = EQUA } in
add_event (STATE {st_new_eq = new_eq; st_def = definition;
st_orig = original; st_coef = m; st_var = sigma});
let new_eq = List.hd (normalize new_eq) in
let eliminated_var, def = chop_var var new_eq.body in
let other_equations =
Util.list_map_append
(fun e ->
normalize (eliminate_with_in new_eq_id eliminated_var new_eq e)) l1 in
let inequations =
Util.list_map_append
(fun e ->
normalize (eliminate_with_in new_eq_id eliminated_var new_eq e)) l2 in
let original' = eliminate_with_in new_eq_id eliminated_var new_eq original in
let mod_original = map_eq_afine (fun c -> c / m) original' in
add_event (EXACT_DIVIDE (original',m));
List.hd (normalize mod_original),other_equations,inequations
let rec eliminate_one_equation ((new_eq_id,new_var_id,print_var) as new_ids) (e,other,ineqs) =
if !debug then display_system print_var (e::other);
try
let v,def = chop_factor_1 e.body in
(Util.list_map_append
(fun e' -> normalize (eliminate_with_in new_eq_id v e e')) other,
Util.list_map_append
(fun e' -> normalize (eliminate_with_in new_eq_id v e e')) ineqs)
with FACTOR1 ->
eliminate_one_equation new_ids (banerjee_step new_ids e other ineqs)
let rec banerjee ((_,_,print_var) as new_ids) (sys_eq,sys_ineq) =
let rec fst_eq_1 = function
(eq::l) ->
if List.exists (fun x -> abs x.c =? one) eq.body then eq,l
else let (eq',l') = fst_eq_1 l in (eq',eq::l')
| [] -> raise Not_found in
match sys_eq with
[] -> if !debug then display_system print_var sys_ineq; sys_ineq
| (e1::rest) ->
let eq,other = try fst_eq_1 sys_eq with Not_found -> (e1,rest) in
if eq.body = [] then
if eq.constant =? zero then begin
add_event (FORGET_C eq.id); banerjee new_ids (other,sys_ineq)
end else begin
add_event (CONSTANT_NOT_NUL(eq.id,eq.constant)); raise UNSOLVABLE
end
else
banerjee new_ids
(eliminate_one_equation new_ids (eq,other,sys_ineq))
type kind = INVERTED | NORMAL
let redundancy_elimination new_eq_id system =
let normal = function
({body=f::_} as e) when f.c <? zero -> negate_eq e, INVERTED
| e -> e,NORMAL in
let table = Hashtbl.create 7 in
List.iter
(fun e ->
let ({body=ne} as nx) ,kind = normal e in
if ne = [] then
if nx.constant <? zero then begin
add_event (CONSTANT_NEG(nx.id,nx.constant)); raise UNSOLVABLE
end else add_event (FORGET_C nx.id)
else
try
let (optnormal,optinvert) = Hashtbl.find table ne in
let final =
if kind = NORMAL then begin
match optnormal with
Some v ->
let kept =
if v.constant <? nx.constant
then begin add_event (FORGET (v.id,nx.id));v end
else begin add_event (FORGET (nx.id,v.id));nx end in
(Some(kept),optinvert)
| None -> Some nx,optinvert
end else begin
match optinvert with
Some v ->
let _kept =
if v.constant >? nx.constant
then begin add_event (FORGET_I (v.id,nx.id));v end
else begin add_event (FORGET_I (nx.id,v.id));nx end in
(optnormal,Some(if v.constant >? nx.constant then v else nx))
| None -> optnormal,Some nx
end in
begin match final with
(Some high, Some low) ->
if high.constant <? low.constant then begin
add_event(CONTRADICTION (high,negate_eq low));
raise UNSOLVABLE
end
| _ -> () end;
Hashtbl.remove table ne;
Hashtbl.add table ne final
with Not_found ->
Hashtbl.add table ne
(if kind = NORMAL then (Some nx,None) else (None,Some nx)))
system;
let accu_eq = ref [] in
let accu_ineq = ref [] in
Hashtbl.iter
(fun p0 p1 -> match (p0,p1) with
| (e, (Some x, Some y)) when x.constant =? y.constant ->
let id=new_eq_id () in
add_event (MERGE_EQ(id,x,y.id));
push {id=id; kind=EQUA; body=x.body; constant=x.constant} accu_eq
| (e, (optnorm,optinvert)) ->
begin match optnorm with
Some x -> push x accu_ineq | _ -> () end;
begin match optinvert with
Some x -> push (negate_eq x) accu_ineq | _ -> () end)
table;
!accu_eq,!accu_ineq
exception SOLVED_SYSTEM
let select_variable system =
let table = Hashtbl.create 7 in
let push v c=
try let r = Hashtbl.find table v in r := max !r (abs c)
with Not_found -> Hashtbl.add table v (ref (abs c)) in
List.iter (fun {body=l} -> List.iter (fun f -> push f.v f.c) l) system;
let vmin,cmin = ref (-1), ref zero in
let var_cpt = ref 0 in
Hashtbl.iter
(fun v ({contents = c}) ->
incr var_cpt;
if c <? !cmin or !vmin = (-1) then begin vmin := v; cmin := c end)
table;
if !var_cpt < 1 then raise SOLVED_SYSTEM;
!vmin
let classify v system =
List.fold_left
(fun (not_occ,below,over) eq ->
try let f,eq' = chop_var v eq.body in
if f.c >=? zero then (not_occ,((f.c,eq) :: below),over)
else (not_occ,below,((neg f.c,eq) :: over))
with CHOPVAR -> (eq::not_occ,below,over))
([],[],[]) system
let product new_eq_id dark_shadow low high =
List.fold_left
(fun accu (a,eq1) ->
List.fold_left
(fun accu (b,eq2) ->
let eq =
sum_afine new_eq_id (map_eq_afine (fun c -> c * b) eq1)
(map_eq_afine (fun c -> c * a) eq2) in
add_event(SUM(eq.id,(b,eq1),(a,eq2)));
match normalize eq with
| [eq] ->
let final_eq =
if dark_shadow then
let delta = (a - one) * (b - one) in
add_event(WEAKEN(eq.id,delta));
{id = eq.id; kind=INEQ; body = eq.body;
constant = eq.constant - delta}
else eq
in final_eq :: accu
| (e::_) -> failwith "Product dardk"
| [] -> accu)
accu high)
[] low
let fourier_motzkin (new_eq_id,_,print_var) dark_shadow system =
let v = select_variable system in
let (ineq_out, ineq_low,ineq_high) = classify v system in
let expanded = ineq_out @ product new_eq_id dark_shadow ineq_low ineq_high in
if !debug then display_system print_var expanded; expanded
let simplify ((new_eq_id,new_var_id,print_var) as new_ids) dark_shadow system =
if List.exists (fun e -> e.kind = DISE) system then
failwith "disequation in simplify";
clear_history ();
List.iter (fun e -> add_event (HYP e)) system;
let system = Util.list_map_append normalize system in
let eqs,ineqs = List.partition (fun e -> e.kind=EQUA) system in
let simp_eq,simp_ineq = redundancy_elimination new_eq_id ineqs in
let system = (eqs @ simp_eq,simp_ineq) in
let rec loop1a system =
let sys_ineq = banerjee new_ids system in
loop1b sys_ineq
and loop1b sys_ineq =
let simp_eq,simp_ineq = redundancy_elimination new_eq_id sys_ineq in
if simp_eq = [] then simp_ineq else loop1a (simp_eq,simp_ineq)
in
let rec loop2 system =
try
let expanded = fourier_motzkin new_ids dark_shadow system in
loop2 (loop1b expanded)
with SOLVED_SYSTEM ->
if !debug then display_system print_var system; system
in
loop2 (loop1a system)
let rec depend relie_on accu = function
| act :: l ->
begin match act with
| DIVIDE_AND_APPROX (e,_,_,_) ->
if List.mem e.id relie_on then depend relie_on (act::accu) l
else depend relie_on accu l
| EXACT_DIVIDE (e,_) ->
if List.mem e.id relie_on then depend relie_on (act::accu) l
else depend relie_on accu l
| WEAKEN (e,_) ->
if List.mem e relie_on then depend relie_on (act::accu) l
else depend relie_on accu l
| SUM (e,(_,e1),(_,e2)) ->
if List.mem e relie_on then
depend (e1.id::e2.id::relie_on) (act::accu) l
else
depend relie_on accu l
| STATE {st_new_eq=e;st_orig=o} ->
if List.mem e.id relie_on then depend (o.id::relie_on) (act::accu) l
else depend relie_on accu l
| HYP e ->
if List.mem e.id relie_on then depend relie_on (act::accu) l
else depend relie_on accu l
| FORGET_C _ -> depend relie_on accu l
| FORGET _ -> depend relie_on accu l
| FORGET_I _ -> depend relie_on accu l
| MERGE_EQ (e,e1,e2) ->
if List.mem e relie_on then
depend (e1.id::e2::relie_on) (act::accu) l
else
depend relie_on accu l
| NOT_EXACT_DIVIDE (e,_) -> depend (e.id::relie_on) (act::accu) l
| CONTRADICTION (e1,e2) ->
depend (e1.id::e2.id::relie_on) (act::accu) l
| CONSTANT_NOT_NUL (e,_) -> depend (e::relie_on) (act::accu) l
| CONSTANT_NEG (e,_) -> depend (e::relie_on) (act::accu) l
| CONSTANT_NUL e -> depend (e::relie_on) (act::accu) l
| NEGATE_CONTRADICT (e1,e2,_) ->
depend (e1.id::e2.id::relie_on) (act::accu) l
| SPLIT_INEQ _ -> failwith "depend"
end
| [] -> relie_on, accu
let depend relie_on accu trace =
Printf.printf " Longueur de la trace initiale : % d\n "
( trace_length trace + trace_length accu ) ;
let rel',trace ' = depend relie_on accu trace in
Printf.printf " Longueur de la trace simplifiée : % d\n " ( trace_length trace ' ) ;
rel',trace '
let depend relie_on accu trace =
Printf.printf "Longueur de la trace initiale : %d\n"
(trace_length trace + trace_length accu);
let rel',trace' = depend relie_on accu trace in
Printf.printf "Longueur de la trace simplifiée : %d\n" (trace_length trace');
rel',trace'
*)
let solve (new_eq_id,new_eq_var,print_var) system =
try let _ = simplify new_eq_id false system in failwith "no contradiction"
with UNSOLVABLE -> display_action print_var (snd (depend [] [] (history ())))
let negation (eqs,ineqs) =
let diseq,_ = List.partition (fun e -> e.kind = DISE) ineqs in
let normal = function
| ({body=f::_} as e) when f.c <? zero -> negate_eq e, INVERTED
| e -> e,NORMAL in
let table = Hashtbl.create 7 in
List.iter (fun e ->
let {body=ne;constant=c} ,kind = normal e in
Hashtbl.add table (ne,c) (kind,e)) diseq;
List.iter (fun e ->
assert (e.kind = EQUA);
let {body=ne;constant=c},kind = normal e in
try
let (kind',e') = Hashtbl.find table (ne,c) in
add_event (NEGATE_CONTRADICT (e,e',kind=kind'));
raise UNSOLVABLE
with Not_found -> ()) eqs
exception FULL_SOLUTION of action list * int list
let simplify_strong ((new_eq_id,new_var_id,print_var) as new_ids) system =
clear_history ();
List.iter (fun e -> add_event (HYP e)) system;
let rec loop1a system =
negation system;
let sys_ineq = banerjee new_ids system in
loop1b sys_ineq
and loop1b sys_ineq =
let dise,ine = List.partition (fun e -> e.kind = DISE) sys_ineq in
let simp_eq,simp_ineq = redundancy_elimination new_eq_id ine in
if simp_eq = [] then dise @ simp_ineq
else loop1a (simp_eq,dise @ simp_ineq)
in
let rec loop2 system =
try
let expanded = fourier_motzkin new_ids false system in
loop2 (loop1b expanded)
with SOLVED_SYSTEM -> if !debug then display_system print_var system; system
in
let rec explode_diseq = function
| (de::diseq,ineqs,expl_map) ->
let id1 = new_eq_id ()
and id2 = new_eq_id () in
let e1 =
{id = id1; kind=INEQ; body = de.body; constant = de.constant -one} in
let e2 =
{id = id2; kind=INEQ; body = map_eq_linear neg de.body;
constant = neg de.constant - one} in
let new_sys =
List.map (fun (what,sys) -> ((de.id,id1,true)::what, e1::sys))
ineqs @
List.map (fun (what,sys) -> ((de.id,id2,false)::what,e2::sys))
ineqs
in
explode_diseq (diseq,new_sys,(de.id,(de,id1,id2))::expl_map)
| ([],ineqs,expl_map) -> ineqs,expl_map
in
try
let system = Util.list_map_append normalize system in
let eqs,ineqs = List.partition (fun e -> e.kind=EQUA) system in
let dise,ine = List.partition (fun e -> e.kind = DISE) ineqs in
let simp_eq,simp_ineq = redundancy_elimination new_eq_id ine in
let system = (eqs @ simp_eq,simp_ineq @ dise) in
let system' = loop1a system in
let diseq,ineq = List.partition (fun e -> e.kind = DISE) system' in
let first_segment = history () in
let sys_exploded,explode_map = explode_diseq (diseq,[[],ineq],[]) in
let all_solutions =
List.map
(fun (decomp,sys) ->
clear_history ();
try let _ = loop2 sys in raise NO_CONTRADICTION
with UNSOLVABLE ->
let relie_on,path = depend [] [] (history ()) in
let dc,_ = List.partition (fun (_,id,_) -> List.mem id relie_on) decomp in
let red = List.map (fun (x,_,_) -> x) dc in
(red,relie_on,decomp,path))
sys_exploded
in
let max_count sys =
let tbl = Hashtbl.create 7 in
let augment x =
try incr (Hashtbl.find tbl x)
with Not_found -> Hashtbl.add tbl x (ref 1) in
let eq = ref (-1) and c = ref 0 in
List.iter (function
| ([],r_on,_,path) -> raise (FULL_SOLUTION (path,r_on))
| (l,_,_,_) -> List.iter augment l) sys;
Hashtbl.iter (fun x v -> if !v > !c then begin eq := x; c := !v end) tbl;
!eq
in
let rec solve systems =
try
let id = max_count systems in
let rec sign = function
| ((id',_,b)::l) -> if id=id' then b else sign l
| [] -> failwith "solve" in
let s1,s2 =
List.partition (fun (_,_,decomp,_) -> sign decomp) systems in
let s1' =
List.map (fun (dep,ro,dc,pa) -> (Util.list_except id dep,ro,dc,pa)) s1 in
let s2' =
List.map (fun (dep,ro,dc,pa) -> (Util.list_except id dep,ro,dc,pa)) s2 in
let (r1,relie1) = solve s1'
and (r2,relie2) = solve s2' in
let (eq,id1,id2) = List.assoc id explode_map in
[SPLIT_INEQ(eq,(id1,r1),(id2, r2))], eq.id :: Util.list_union relie1 relie2
with FULL_SOLUTION (x0,x1) -> (x0,x1)
in
let act,relie_on = solve all_solutions in
snd(depend relie_on act first_segment)
with UNSOLVABLE -> snd (depend [] [] (history ()))
end
|
d1526a7154bc24c8f53ce203940614d990040ea6f2caed0b4e882ec33c82b219
|
alavrik/piqi
|
piqi_getopt.ml
|
Copyright 2009 , 2010 , 2011 , 2012 , 2013 , 2014 , 2015 , 2017
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
you may not use this file except in compliance with the License .
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing , software
distributed under the License is distributed on an " AS IS " BASIS ,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied .
See the License for the specific language governing permissions and
limitations under the License .
Copyright 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2017 Anton Lavrik
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*)
* Interpreting command - line arguments as Piq data
* Interpreting command-line arguments as Piq data
*)
@doc
Piqi uses different option syntax than / GNU getopt , because their
syntax is way too relaxed and imprecise . These are examples of GNU getopt
options and their possible meanings :
--c - long=10 // c - long = 10
-c 10 // c , 10
-c10 // c = 10
-ac10 // a , c = 10
-ca10 // c = a10
In Piqi getopt , both short and long options are supported . Both type of
options must be seprated from a value by whitespace , e.g.
-c 10
--c - long 10
Short options start with ' - ' character followed by one or more letters . In
the latter case , each letter is treated as if it was specified separaterly .
For example ,
-abc 10
is equivalent to
-a -b -c 10
' - ' followed by a < number > is normally treated as a negative number , e.g.
-10
-0.0
-0.infinity
Words will be treated either as Piq strings or binaries or words , depending
on the expected type . Examples of words :
a
foo
Strings or binaries can be specified explicitly using Piq string syntax .
' " a " '
' " foo\u0000 " '
' " \x00\n\r " '
Lists can be specified using regular Piq syntax , but ' [ ' and ' ] ' characters
can be specified as separate arguments and not as a part of other arguments .
Examples :
[ ]
[ a b ] // this is correct
[ a b ] // this is incorrect
[ a b 10 -1 ]
[ a b [ c d ] ]
Values for the arguments that start with ' @ ' character will be loaded from a
file which names follows the ' @ ' character . For example :
@foo // string or binary value will be loaded from file " foo "
TODO : @- // string or binary value will be loaded from stdin
Piqi getopt uses different option syntax than Posix/GNU getopt, because their
syntax is way too relaxed and imprecise. These are examples of GNU getopt
options and their possible meanings:
--c-long=10 // c-long = 10
-c 10 // c, 10
-c10 // c = 10
-ac10 // a, c = 10
-ca10 // c = a10
In Piqi getopt, both short and long options are supported. Both type of
options must be seprated from a value by whitespace, e.g.
-c 10
--c-long 10
Short options start with '-' character followed by one or more letters. In
the latter case, each letter is treated as if it was specified separaterly.
For example,
-abc 10
is equivalent to
-a -b -c 10
'-' followed by a <number> is normally treated as a negative number, e.g.
-10
-0.nan
-0.0
-0.infinity
Words will be treated either as Piq strings or binaries or words, depending
on the expected type. Examples of words:
a
foo
Strings or binaries can be specified explicitly using Piq string syntax.
'"a"'
'"foo\u0000"'
'"\x00\n\r"'
Lists can be specified using regular Piq syntax, but '[' and ']' characters
can be specified as separate arguments and not as a part of other arguments.
Examples:
[]
[ a b ] // this is correct
[a b] // this is incorrect
[ a b 10 -1 ]
[ a b [ c d ] ]
Values for the arguments that start with '@' character will be loaded from a
file which names follows the '@' character. For example:
@foo // string or binary value will be loaded from file "foo"
TODO: @- // string or binary value will be loaded from stdin
*)
module C = Piqi_common
open C
* Set " alt - name " fields for Piqi options and fields based on " - name "
* fields provided by user in the Piqi spec .
*
* " alt - name " field is specific to the library implementation while
* " - name " field is a part of public Piqi specification .
* Set "alt-name" fields for Piqi options and fields based on "getopt-name"
* fields provided by user in the Piqi spec.
*
* "alt-name" field is specific to the library implementation while
* "getopt-name" field is a part of public Piqi specification.
*)
let check_getopt_letter s =
let error err =
error s ("invalid getopt-letter " ^ U.quote s ^ ": " ^ err)
in
(* NOTE: getopt-letter is a Piq word and, therefore, it can't be empty -- so
* there's no need to check for that *)
if String.length s > 1
then error "must contain exactly one letter";
match s.[0] with
| 'a'..'z' | 'A'..'Z' -> ()
| c -> error "must be lower- or upper-case alphabet letter"
let getopt_name_field x =
let open Field in
let letter = x.getopt_letter in
match letter with
| None -> ()
| Some n ->
check_getopt_letter n;
x.piq_alias <- letter
let getopt_name_option x =
let open Option in
let letter = x.getopt_letter in
match letter with
| None -> ()
| Some n ->
check_getopt_letter n;
x.piq_alias <- letter
(* name fields and options *)
let getopt_name_record x =
List.iter getopt_name_field x.R.field
let getopt_name_variant x =
List.iter getopt_name_option x.V.option
let getopt_name_enum x =
List.iter getopt_name_option x.E.option
let getopt_name_typedef = function
| `record x -> getopt_name_record x
| `variant x -> getopt_name_variant x
| `enum x -> getopt_name_enum x
| _ -> ()
let getopt_name_defs defs =
(* name fields and options *)
List.iter getopt_name_typedef defs
let getopt_name_piqi _idtable (piqi:T.piqi) =
let open P in
getopt_name_defs piqi.resolved_typedef
NOTE : this function is called only in case if a getopt - related operation is
* performed ( e.g. " " or " piqi call " . We do n't need this startup
* overhead otherwise
* performed (e.g. "piqi getopt" or "piqi call". We don't need this startup
* overhead otherwise *)
let init () =
trace "init getopt\n";
Piqi.register_processing_hook getopt_name_piqi
(**)
(* fake filename for error reporting *)
let getopt_filename = "argv"
let error s =
(* using fake location here, the actual location (i.e. the index of the
* argument) will be correctly provided by the exception handler below *)
let loc = (0,0) in
raise (Piq_lexer.Error (s, loc))
let parse_string_arg s =
let lexbuf = Piq_lexer.init_from_string s in
let token () =
try
Piq_lexer.token lexbuf
with
Piq_lexer.Error (err, _loc) -> error (err ^ ": " ^ s)
in
let res = token () in
match res with
| Piq_lexer.String _ ->
(* there must be no other literal after the string *)
if token() = Piq_lexer.EOF
then res
else
(* s is alread quoted *)
error ("trailing characters after string: " ^ s)
| _ ->
assert false (* something that starts with '"' have to be a string *)
let parse_word_arg s =
if Piq_lexer.is_valid_word s
then
Piq_lexer.Word s
else
(* Raw string -- just a sequence of bytes: may be parsed as binary or utf8
* string *)
Piq_lexer.Raw_string s
let parse_name_arg s =
(* cut the leading '-' and check if what we got is a valid Piq name *)
let n = String.sub s 1 (String.length s - 1) in
if Piqi_name.is_valid_name n ~allow:"."
then (
let s = Bytes.of_string s in
replace ' - ' with ' . ' to turn it into a Piq name
Piq_lexer.Name (Bytes.unsafe_to_string s)
)
else error ("invalid name: " ^ U.quote s)
let read_file filename =
let ch = open_in_bin filename in
let len = in_channel_length ch in
let buf = Buffer.create len in
Buffer.add_channel buf ch len;
close_in ch;
Buffer.contents buf
let read_file filename =
try read_file filename
with Sys_error s ->
error ("error reading file argument: " ^ s)
let parse_arg s =
let len = String.length s in
match s with
(* NOTE: we don't support '(' and ')' and '[]' is handeled separately below *)
| "[" -> Piq_lexer.Lbr
| "]" -> Piq_lexer.Rbr
| s when s.[0] = '"' -> parse_string_arg s
| s when s.[0] = '@' ->
let filename = String.sub s 1 (len - 1) in
let content = read_file filename in
(* Raw string -- just a sequence of bytes: may be parsed as either
* binary or utf8 string *)
Piq_lexer.Raw_string content
(* parsing long options starting with "--"
*
* NOTE: it is safe to check s.[1] because a single '-' case is eliminated
* in the calling function *)
| s when s.[0] = '-' && s.[1] = '-' ->
let name = String.sub s 1 (len - 1) in (* skip first '-' *)
parse_name_arg name
| s when s.[0] = '.' ->
parse_name_arg s (* XXX: allowing Piq -style names *)
(* XXX: support typenames and, possibly, other literals? *)
| s ->
parse_word_arg s
let parse_argv start =
let error i err =
C.error_at (getopt_filename, 0, i) err
in
let make_token i tok =
1 - based token position in the argv starting from the position after " -- "
let loc = (0, i - start + 1) in
(tok, loc)
in
let parse_make_arg i x =
let tok =
try parse_arg x
with Piq_lexer.Error (err, _loc) -> error i err
in
make_token i tok
in
let parse_letter_args i s =
let len = String.length s in
let rec aux j =
if j = len
then [] (* end of string *)
else
let c = s.[j] in
match c with
(* only letters are allowed as single-letter options *)
| 'a'..'z' | 'A'..'Z' ->
creating Piq name : ' . ' followed by the letter
let word = Bytes.create 2 in
Bytes.set word 0 '.'; Bytes.set word 1 c;
let tok = Piq_lexer.Name (Bytes.unsafe_to_string word) in
(make_token i tok) :: (aux (j+1))
| _ ->
error i ("invalid single-letter argument: " ^ Char.escaped c)
in
start at position 1 skipping the leading ' - '
in
let len = Array.length Sys.argv in
let rec aux i =
if i >= len
then [make_token i Piq_lexer.EOF]
else
let a = Sys.argv.(i) in
match a with
| "" ->
error i "empty argument"
| "-" | "--" ->
error i ("invalid argument: " ^ a)
split it into two tokens ' [ ' and ' ] '
(parse_make_arg i "[") :: (parse_make_arg i "]") :: (aux (i+1))
After skipping negative integers , and those arguments that start with
* ' -- ' , we end up having ' - ' followed by one or more characters . We
* treat those characters as single - letter arguments .
*
* NOTE : it is safe to check s.[1 ] because a single ' - ' case is
* eliminated above
* '--', we end up having '-' followed by one or more characters. We
* treat those characters as single-letter arguments.
*
* NOTE: it is safe to check s.[1] because a single '-' case is
* eliminated above *)
| s when s.[0] = '-' && s.[1] <> '-' && (s.[1] < '0' || s.[1] > '9') ->
(parse_letter_args i s) @ (aux (i+1))
| s ->
(parse_make_arg i s) :: (aux (i+1))
in
aux start
(* index of the "--" element in argv array *)
let argv_start_index = ref 0
find the position of the first argument after " -- "
let rest_fun arg =
first argument after first occurrence of " -- "
then argv_start_index := !Arg.current + 1
else ()
let arg__rest =
"--", Arg.Rest rest_fun,
"separator between piqi command-line arguments and data arguments"
let getopt_piq () :piq_ast list =
let start =
if !argv_start_index = 0 (* "--" is not present in the list of arguments *)
then Array.length Sys.argv
else !argv_start_index
in
let tokens = parse_argv start in
let piq_parser = Piq_parser.init_from_token_list getopt_filename tokens in
let piq_ast_list =
U.with_bool Config.piq_relaxed_parsing true
(fun () -> Piq_parser.read_all piq_parser)
in
piq_ast_list
let parse_args (piqtype: T.piqtype) (args: piq_ast list) :Piqobj.obj =
let ast =
match args with
| [x] when not (C.is_container_type piqtype) -> (* scalar type? *)
x
| l ->
let res = `list l in
(* set the location *)
let loc = (getopt_filename, 0, 1) in
Piqloc.addlocret loc res
in
let ast = Piq_parser.expand ast in
let piqobj = U.with_bool Config.piq_relaxed_parsing true
(fun () -> Piqobj_of_piq.parse_obj piqtype ast)
in
piqobj
| null |
https://raw.githubusercontent.com/alavrik/piqi/bcea4d44997966198dc295df0609591fa787b1d2/piqilib/piqi_getopt.ml
|
ocaml
|
NOTE: getopt-letter is a Piq word and, therefore, it can't be empty -- so
* there's no need to check for that
name fields and options
name fields and options
fake filename for error reporting
using fake location here, the actual location (i.e. the index of the
* argument) will be correctly provided by the exception handler below
there must be no other literal after the string
s is alread quoted
something that starts with '"' have to be a string
Raw string -- just a sequence of bytes: may be parsed as binary or utf8
* string
cut the leading '-' and check if what we got is a valid Piq name
NOTE: we don't support '(' and ')' and '[]' is handeled separately below
Raw string -- just a sequence of bytes: may be parsed as either
* binary or utf8 string
parsing long options starting with "--"
*
* NOTE: it is safe to check s.[1] because a single '-' case is eliminated
* in the calling function
skip first '-'
XXX: allowing Piq -style names
XXX: support typenames and, possibly, other literals?
end of string
only letters are allowed as single-letter options
index of the "--" element in argv array
"--" is not present in the list of arguments
scalar type?
set the location
|
Copyright 2009 , 2010 , 2011 , 2012 , 2013 , 2014 , 2015 , 2017
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
you may not use this file except in compliance with the License .
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing , software
distributed under the License is distributed on an " AS IS " BASIS ,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied .
See the License for the specific language governing permissions and
limitations under the License .
Copyright 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2017 Anton Lavrik
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*)
* Interpreting command - line arguments as Piq data
* Interpreting command-line arguments as Piq data
*)
@doc
Piqi uses different option syntax than / GNU getopt , because their
syntax is way too relaxed and imprecise . These are examples of GNU getopt
options and their possible meanings :
--c - long=10 // c - long = 10
-c 10 // c , 10
-c10 // c = 10
-ac10 // a , c = 10
-ca10 // c = a10
In Piqi getopt , both short and long options are supported . Both type of
options must be seprated from a value by whitespace , e.g.
-c 10
--c - long 10
Short options start with ' - ' character followed by one or more letters . In
the latter case , each letter is treated as if it was specified separaterly .
For example ,
-abc 10
is equivalent to
-a -b -c 10
' - ' followed by a < number > is normally treated as a negative number , e.g.
-10
-0.0
-0.infinity
Words will be treated either as Piq strings or binaries or words , depending
on the expected type . Examples of words :
a
foo
Strings or binaries can be specified explicitly using Piq string syntax .
' " a " '
' " foo\u0000 " '
' " \x00\n\r " '
Lists can be specified using regular Piq syntax , but ' [ ' and ' ] ' characters
can be specified as separate arguments and not as a part of other arguments .
Examples :
[ ]
[ a b ] // this is correct
[ a b ] // this is incorrect
[ a b 10 -1 ]
[ a b [ c d ] ]
Values for the arguments that start with ' @ ' character will be loaded from a
file which names follows the ' @ ' character . For example :
@foo // string or binary value will be loaded from file " foo "
TODO : @- // string or binary value will be loaded from stdin
Piqi getopt uses different option syntax than Posix/GNU getopt, because their
syntax is way too relaxed and imprecise. These are examples of GNU getopt
options and their possible meanings:
--c-long=10 // c-long = 10
-c 10 // c, 10
-c10 // c = 10
-ac10 // a, c = 10
-ca10 // c = a10
In Piqi getopt, both short and long options are supported. Both type of
options must be seprated from a value by whitespace, e.g.
-c 10
--c-long 10
Short options start with '-' character followed by one or more letters. In
the latter case, each letter is treated as if it was specified separaterly.
For example,
-abc 10
is equivalent to
-a -b -c 10
'-' followed by a <number> is normally treated as a negative number, e.g.
-10
-0.nan
-0.0
-0.infinity
Words will be treated either as Piq strings or binaries or words, depending
on the expected type. Examples of words:
a
foo
Strings or binaries can be specified explicitly using Piq string syntax.
'"a"'
'"foo\u0000"'
'"\x00\n\r"'
Lists can be specified using regular Piq syntax, but '[' and ']' characters
can be specified as separate arguments and not as a part of other arguments.
Examples:
[]
[ a b ] // this is correct
[a b] // this is incorrect
[ a b 10 -1 ]
[ a b [ c d ] ]
Values for the arguments that start with '@' character will be loaded from a
file which names follows the '@' character. For example:
@foo // string or binary value will be loaded from file "foo"
TODO: @- // string or binary value will be loaded from stdin
*)
module C = Piqi_common
open C
* Set " alt - name " fields for Piqi options and fields based on " - name "
* fields provided by user in the Piqi spec .
*
* " alt - name " field is specific to the library implementation while
* " - name " field is a part of public Piqi specification .
* Set "alt-name" fields for Piqi options and fields based on "getopt-name"
* fields provided by user in the Piqi spec.
*
* "alt-name" field is specific to the library implementation while
* "getopt-name" field is a part of public Piqi specification.
*)
let check_getopt_letter s =
let error err =
error s ("invalid getopt-letter " ^ U.quote s ^ ": " ^ err)
in
if String.length s > 1
then error "must contain exactly one letter";
match s.[0] with
| 'a'..'z' | 'A'..'Z' -> ()
| c -> error "must be lower- or upper-case alphabet letter"
let getopt_name_field x =
let open Field in
let letter = x.getopt_letter in
match letter with
| None -> ()
| Some n ->
check_getopt_letter n;
x.piq_alias <- letter
let getopt_name_option x =
let open Option in
let letter = x.getopt_letter in
match letter with
| None -> ()
| Some n ->
check_getopt_letter n;
x.piq_alias <- letter
let getopt_name_record x =
List.iter getopt_name_field x.R.field
let getopt_name_variant x =
List.iter getopt_name_option x.V.option
let getopt_name_enum x =
List.iter getopt_name_option x.E.option
let getopt_name_typedef = function
| `record x -> getopt_name_record x
| `variant x -> getopt_name_variant x
| `enum x -> getopt_name_enum x
| _ -> ()
let getopt_name_defs defs =
List.iter getopt_name_typedef defs
let getopt_name_piqi _idtable (piqi:T.piqi) =
let open P in
getopt_name_defs piqi.resolved_typedef
NOTE : this function is called only in case if a getopt - related operation is
* performed ( e.g. " " or " piqi call " . We do n't need this startup
* overhead otherwise
* performed (e.g. "piqi getopt" or "piqi call". We don't need this startup
* overhead otherwise *)
let init () =
trace "init getopt\n";
Piqi.register_processing_hook getopt_name_piqi
let getopt_filename = "argv"
let error s =
let loc = (0,0) in
raise (Piq_lexer.Error (s, loc))
let parse_string_arg s =
let lexbuf = Piq_lexer.init_from_string s in
let token () =
try
Piq_lexer.token lexbuf
with
Piq_lexer.Error (err, _loc) -> error (err ^ ": " ^ s)
in
let res = token () in
match res with
| Piq_lexer.String _ ->
if token() = Piq_lexer.EOF
then res
else
error ("trailing characters after string: " ^ s)
| _ ->
let parse_word_arg s =
if Piq_lexer.is_valid_word s
then
Piq_lexer.Word s
else
Piq_lexer.Raw_string s
let parse_name_arg s =
let n = String.sub s 1 (String.length s - 1) in
if Piqi_name.is_valid_name n ~allow:"."
then (
let s = Bytes.of_string s in
replace ' - ' with ' . ' to turn it into a Piq name
Piq_lexer.Name (Bytes.unsafe_to_string s)
)
else error ("invalid name: " ^ U.quote s)
let read_file filename =
let ch = open_in_bin filename in
let len = in_channel_length ch in
let buf = Buffer.create len in
Buffer.add_channel buf ch len;
close_in ch;
Buffer.contents buf
let read_file filename =
try read_file filename
with Sys_error s ->
error ("error reading file argument: " ^ s)
let parse_arg s =
let len = String.length s in
match s with
| "[" -> Piq_lexer.Lbr
| "]" -> Piq_lexer.Rbr
| s when s.[0] = '"' -> parse_string_arg s
| s when s.[0] = '@' ->
let filename = String.sub s 1 (len - 1) in
let content = read_file filename in
Piq_lexer.Raw_string content
| s when s.[0] = '-' && s.[1] = '-' ->
parse_name_arg name
| s when s.[0] = '.' ->
| s ->
parse_word_arg s
let parse_argv start =
let error i err =
C.error_at (getopt_filename, 0, i) err
in
let make_token i tok =
1 - based token position in the argv starting from the position after " -- "
let loc = (0, i - start + 1) in
(tok, loc)
in
let parse_make_arg i x =
let tok =
try parse_arg x
with Piq_lexer.Error (err, _loc) -> error i err
in
make_token i tok
in
let parse_letter_args i s =
let len = String.length s in
let rec aux j =
if j = len
else
let c = s.[j] in
match c with
| 'a'..'z' | 'A'..'Z' ->
creating Piq name : ' . ' followed by the letter
let word = Bytes.create 2 in
Bytes.set word 0 '.'; Bytes.set word 1 c;
let tok = Piq_lexer.Name (Bytes.unsafe_to_string word) in
(make_token i tok) :: (aux (j+1))
| _ ->
error i ("invalid single-letter argument: " ^ Char.escaped c)
in
start at position 1 skipping the leading ' - '
in
let len = Array.length Sys.argv in
let rec aux i =
if i >= len
then [make_token i Piq_lexer.EOF]
else
let a = Sys.argv.(i) in
match a with
| "" ->
error i "empty argument"
| "-" | "--" ->
error i ("invalid argument: " ^ a)
split it into two tokens ' [ ' and ' ] '
(parse_make_arg i "[") :: (parse_make_arg i "]") :: (aux (i+1))
After skipping negative integers , and those arguments that start with
* ' -- ' , we end up having ' - ' followed by one or more characters . We
* treat those characters as single - letter arguments .
*
* NOTE : it is safe to check s.[1 ] because a single ' - ' case is
* eliminated above
* '--', we end up having '-' followed by one or more characters. We
* treat those characters as single-letter arguments.
*
* NOTE: it is safe to check s.[1] because a single '-' case is
* eliminated above *)
| s when s.[0] = '-' && s.[1] <> '-' && (s.[1] < '0' || s.[1] > '9') ->
(parse_letter_args i s) @ (aux (i+1))
| s ->
(parse_make_arg i s) :: (aux (i+1))
in
aux start
let argv_start_index = ref 0
find the position of the first argument after " -- "
let rest_fun arg =
first argument after first occurrence of " -- "
then argv_start_index := !Arg.current + 1
else ()
let arg__rest =
"--", Arg.Rest rest_fun,
"separator between piqi command-line arguments and data arguments"
let getopt_piq () :piq_ast list =
let start =
then Array.length Sys.argv
else !argv_start_index
in
let tokens = parse_argv start in
let piq_parser = Piq_parser.init_from_token_list getopt_filename tokens in
let piq_ast_list =
U.with_bool Config.piq_relaxed_parsing true
(fun () -> Piq_parser.read_all piq_parser)
in
piq_ast_list
let parse_args (piqtype: T.piqtype) (args: piq_ast list) :Piqobj.obj =
let ast =
match args with
x
| l ->
let res = `list l in
let loc = (getopt_filename, 0, 1) in
Piqloc.addlocret loc res
in
let ast = Piq_parser.expand ast in
let piqobj = U.with_bool Config.piq_relaxed_parsing true
(fun () -> Piqobj_of_piq.parse_obj piqtype ast)
in
piqobj
|
897bc074c4c5df3fec1e9c3356c8552adfb9aa630e0bc6bb8dc515bc6160d185
|
madmax96/brave-clojure-solutions
|
section_9.clj
|
(ns clojure-brave.exercises.section-9)
; NOTE:
Rather than sending requests to or Google ,
;i will use simpler approach and just simulate some long running action with wait function.
Sending request to Google / Bing wo n't always work .
(defmacro wait
"Sleep `timeout` seconds before evaluating body"
[timeout & body]
`(do (Thread/sleep ~timeout) ~@body))
1 skipped , Exercise 2 is generalisation of 1 , so I implemented just exercise 2 .
2
If you are familiar with Javascript 's promises , this is basically Promise.race pattern ,
we have N concurrent processes , and we should return promise that resolves to result of process that finishes first
(defn p-race
[values]
(let [p (promise)]
(doseq [v values]
(future (wait (* v 1000) (deliver p v))))
p))
(def p (p-race [3 2 5 7]))
(println @p)
3
If you are familiar with Javascript 's promises , this is basically Promise.all pattern
; We have N concurrent processes, and we should return promise that resolves to array of data returned by all processes
(defn p-all
[values]
(let [promises (map (fn [v]
(future (wait (* v 1000) v))) values)]
(future (map deref promises))))
(def p-data (p-all [3 2 2 1]))
(println @p-data)
| null |
https://raw.githubusercontent.com/madmax96/brave-clojure-solutions/3be234bdcf3704acd2aca62d1a46fa03463e5735/section_9.clj
|
clojure
|
NOTE:
i will use simpler approach and just simulate some long running action with wait function.
We have N concurrent processes, and we should return promise that resolves to array of data returned by all processes
|
(ns clojure-brave.exercises.section-9)
Rather than sending requests to or Google ,
Sending request to Google / Bing wo n't always work .
(defmacro wait
"Sleep `timeout` seconds before evaluating body"
[timeout & body]
`(do (Thread/sleep ~timeout) ~@body))
1 skipped , Exercise 2 is generalisation of 1 , so I implemented just exercise 2 .
2
If you are familiar with Javascript 's promises , this is basically Promise.race pattern ,
we have N concurrent processes , and we should return promise that resolves to result of process that finishes first
(defn p-race
[values]
(let [p (promise)]
(doseq [v values]
(future (wait (* v 1000) (deliver p v))))
p))
(def p (p-race [3 2 5 7]))
(println @p)
3
If you are familiar with Javascript 's promises , this is basically Promise.all pattern
(defn p-all
[values]
(let [promises (map (fn [v]
(future (wait (* v 1000) v))) values)]
(future (map deref promises))))
(def p-data (p-all [3 2 2 1]))
(println @p-data)
|
8e5788f155d59e54d7db1400ead499cf90e8f161bc1e7cb6c00d93ba81f8bc3a
|
HunterYIboHu/htdp2-solution
|
ex274-prefixes-suffixes.rkt
|
The first three lines of this file were inserted by . They record metadata
;; about the language level of this file in a form that our tools can easily process.
#reader(lib "htdp-intermediate-lambda-reader.ss" "lang")((modname ex274-prefixes-suffixes) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f () #f)))
; [List-of 1String] -> [List-of [List-of 1String]]
produces the list of all prefixes , a list p is a prefix of l
if p and l are the same up through all items in p.
(check-expect (prefixes '()) '())
(check-expect (prefixes (list "A")) (list (list "A")))
(check-expect (prefixes (list "A" "B"))
(list (list "A") (list "A" "B")))
(check-expect (prefixes (list "A" "B" "C"))
(list (list "A") (list "A" "B") (list "A" "B" "C")))
(define (prefixes los)
(cond [(empty? los) '()]
[else (local ((define first-elt (first los))
; 1String [List-of [List-of 1String]] ->
; [List-of [List-of 1String]]
; add the given s to the head of all the lol's list
(define (add-first-at-head lls)
(cons first-elt lls)))
(cons `(,first-elt)
(map add-first-at-head (prefixes (rest los)))))]))
; [List-of 1String] -> [List-of [List-of 1String]]
produces the list of all suffix of l. A list s is a suffix of l if
; p and l are the same from the end, up through all items in s.
(check-expect (suffixes '()) '())
(check-expect (suffixes (list "A")) (list (list "A")))
(check-expect (suffixes (list "A" "B")) (list (list "A" "B") (list "B")))
(check-expect (suffixes (list "A" "B" "C"))
(list (list "A" "B" "C") (list "B" "C") (list "C")))
(define (suffixes los)
(cond [(empty? los) '()]
[else (cons los
(suffixes (rest los)))]))
| null |
https://raw.githubusercontent.com/HunterYIboHu/htdp2-solution/6182b4c2ef650ac7059f3c143f639d09cd708516/Chapter3-Abstraction/Section16-Using-Abstraction/ex274-prefixes-suffixes.rkt
|
racket
|
about the language level of this file in a form that our tools can easily process.
[List-of 1String] -> [List-of [List-of 1String]]
1String [List-of [List-of 1String]] ->
[List-of [List-of 1String]]
add the given s to the head of all the lol's list
[List-of 1String] -> [List-of [List-of 1String]]
p and l are the same from the end, up through all items in s.
|
The first three lines of this file were inserted by . They record metadata
#reader(lib "htdp-intermediate-lambda-reader.ss" "lang")((modname ex274-prefixes-suffixes) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f () #f)))
produces the list of all prefixes , a list p is a prefix of l
if p and l are the same up through all items in p.
(check-expect (prefixes '()) '())
(check-expect (prefixes (list "A")) (list (list "A")))
(check-expect (prefixes (list "A" "B"))
(list (list "A") (list "A" "B")))
(check-expect (prefixes (list "A" "B" "C"))
(list (list "A") (list "A" "B") (list "A" "B" "C")))
(define (prefixes los)
(cond [(empty? los) '()]
[else (local ((define first-elt (first los))
(define (add-first-at-head lls)
(cons first-elt lls)))
(cons `(,first-elt)
(map add-first-at-head (prefixes (rest los)))))]))
produces the list of all suffix of l. A list s is a suffix of l if
(check-expect (suffixes '()) '())
(check-expect (suffixes (list "A")) (list (list "A")))
(check-expect (suffixes (list "A" "B")) (list (list "A" "B") (list "B")))
(check-expect (suffixes (list "A" "B" "C"))
(list (list "A" "B" "C") (list "B" "C") (list "C")))
(define (suffixes los)
(cond [(empty? los) '()]
[else (cons los
(suffixes (rest los)))]))
|
21b12824f8bfeb296e425456c52e1714607ba4965ad40396ebf529d0a4824897
|
cloojure/yang-parser
|
calc1.clj
|
(ns tst.parse.calc1
(:use parse.core
parse.transform
tupelo.test )
(:require
[tupelo.core :as t]
[tupelo.forest :as tf]
)
(:import [java.util.concurrent TimeoutException] ))
(t/refer-tupelo)
(def ^:dynamic *rpc-timeout-ms* 200)
(def ^:dynamic *rpc-delay-simulated-ms* 30)
(defn add-impl
[msg]
(let [result-promise (promise)]
(future
(let [rpc-fn-tag (grab :tag msg)
rpc-fn (grab rpc-fn-tag rpc-fn-map)
args (grab :content msg)]
(Thread/sleep *rpc-delay-simulated-ms*)
(deliver result-promise (apply rpc-fn args))))
result-promise))
(defn add [x y]
(let [result-promise (add-impl (tf/hiccup->enlive [:add x y]))
rpc-result (deref result-promise *rpc-timeout-ms* ::timeout-failure)]
(when (= ::timeout-failure rpc-result)
(throw (TimeoutException. (format "Timeout Exceed=%s add: %s %s; " *rpc-timeout-ms* x y))))
rpc-result))
(dotest
(binding [*rpc-timeout-ms* 200
*rpc-delay-simulated-ms* 30]
(is= 5 (add 2 3)))
(binding [*rpc-timeout-ms* 20
*rpc-delay-simulated-ms* 30]
(throws? (add 2 3))))
| null |
https://raw.githubusercontent.com/cloojure/yang-parser/e9d8e1e26e8ec0956ec019f36452f53a218ce049/test/tst/parse/calc1.clj
|
clojure
|
(ns tst.parse.calc1
(:use parse.core
parse.transform
tupelo.test )
(:require
[tupelo.core :as t]
[tupelo.forest :as tf]
)
(:import [java.util.concurrent TimeoutException] ))
(t/refer-tupelo)
(def ^:dynamic *rpc-timeout-ms* 200)
(def ^:dynamic *rpc-delay-simulated-ms* 30)
(defn add-impl
[msg]
(let [result-promise (promise)]
(future
(let [rpc-fn-tag (grab :tag msg)
rpc-fn (grab rpc-fn-tag rpc-fn-map)
args (grab :content msg)]
(Thread/sleep *rpc-delay-simulated-ms*)
(deliver result-promise (apply rpc-fn args))))
result-promise))
(defn add [x y]
(let [result-promise (add-impl (tf/hiccup->enlive [:add x y]))
rpc-result (deref result-promise *rpc-timeout-ms* ::timeout-failure)]
(when (= ::timeout-failure rpc-result)
(throw (TimeoutException. (format "Timeout Exceed=%s add: %s %s; " *rpc-timeout-ms* x y))))
rpc-result))
(dotest
(binding [*rpc-timeout-ms* 200
*rpc-delay-simulated-ms* 30]
(is= 5 (add 2 3)))
(binding [*rpc-timeout-ms* 20
*rpc-delay-simulated-ms* 30]
(throws? (add 2 3))))
|
|
aa1c5040dde71f7ffe800e5e2e1ee015eab85e43d9aa7c8372926936532b9e6d
|
music-suite/music-suite
|
Time.hs
|
# OPTIONS_GHC -fno - warn - name - shadowing
-fno - warn - unused - imports
-fno - warn - redundant - constraints #
-fno-warn-unused-imports
-fno-warn-redundant-constraints #-}
-------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------
-- |
Copyright : ( c ) 2012 - 2014
--
-- License : BSD-style
--
Maintainer :
-- Stability : experimental
Portability : non - portable ( TF , )
--
-- Provides time signatures and related meta-data.
module Music.Score.Meta.Time
( -- * Time signature type
TimeSignature (..),
time,
compoundTime,
isSimpleTime,
isCompoundTime,
toSimpleTime,
-- * Adding time signature to scores
timeSignature,
timeSignatureDuring,
-- * Utility
standardTimeSignature,
)
where
import Control.Lens (view, (^.))
import Control.Monad.Plus
import Data.Bifunctor
import Data.Bits ((.&.))
import Data.Foldable (Foldable)
import qualified Data.Foldable as F
import qualified Data.List as List
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Maybe
import Data.Ratio ((%))
import Data.Semigroup
import Data.Set (Set)
import qualified Data.Set as Set
import Data.String
import Data.Traversable (Traversable)
import qualified Data.Traversable as T
import Data.Typeable
import Music.Pitch.Literal
import Music.Score.Internal.Util
import Music.Score.Meta
import Music.Score.Part
import Music.Score.Pitch
import Music.Time
-- |
-- A time signature is a sequence of beat numbers and a note value (i.e. an expression on the
-- form @(a1+a2...)/b@). For simple time signatures just one beat number is used.
--
TimeSignature is an instance of ' Fractional ' and can be used as
-- follows:
--
> timeSignature ( 4/4 )
> timeSignature ( 6/8 )
> ( ( 3 + 2)/4 )
newtype TimeSignature = TimeSignature {getTimeSignature :: ([Integer], Integer)}
deriving (Eq, Ord, Typeable)
mapNums f (TimeSignature (m, n)) = TimeSignature (f m, n)
mapDenom f (TimeSignature (m, n)) = TimeSignature (m, f n)
isSimple (TimeSignature ([_], _)) = True
isSimple _ = False
getSimple (TimeSignature ([m], n)) = m `div` n
getSimple _ = error "getSimple: Not a simple time signature"
TODO move
liftRational f = fromRational . f . toRational
liftRational2 f x y = fromRational $ toRational x `f` toRational y
instance Num TimeSignature where
x + y
| x `haveSameDenominator` y = concatFrac x y
| otherwise = liftRational2 (+) x y
where
TimeSignature (_, n1) `haveSameDenominator` TimeSignature (_, n2) = n1 == n2
TimeSignature (m1, n) `concatFrac` TimeSignature (m2, _) = TimeSignature (m1 <> m2, n)
x * y
| isSimple y = mapNums (fmap (* getSimple y)) x
| otherwise = liftRational2 (*) x y
negate = liftRational negate
abs = liftRational abs
signum = liftRational signum
fromInteger x = TimeSignature ([x], 1)
instance Fractional TimeSignature where
fromRational (unRatio -> (m, n)) = TimeSignature ([m], n)
x / y
| isSimple y = mapDenom (* getSimple y) x
| otherwise = liftRational2 (/) x y
instance Real TimeSignature where
toRational (TimeSignature (xs, x)) = sum xs % x
instance Show TimeSignature where
show (TimeSignature ([m], n)) = show m ++ "/" ++ show n
show (TimeSignature (xs, n)) = "(" ++ List.intercalate "+" (fmap show xs) ++ ")/" ++ show n
-- | Create a simple time signature.
time :: Integer -> Integer -> TimeSignature
time x y = TimeSignature ([x], y)
-- | Create a compound time signature.
compoundTime :: [Integer] -> Integer -> TimeSignature
compoundTime = curry TimeSignature
-- | Whether this is a simple time signature.
isSimpleTime :: TimeSignature -> Bool
isSimpleTime (TimeSignature ([_], _)) = True
isSimpleTime _ = False
-- | Whether this is a compound time signature.
isCompoundTime :: TimeSignature -> Bool
isCompoundTime = not . isSimpleTime
-- | Convert to a simple time signature by adding all numerators.
-- If given a simple time signature, returns it.
toSimpleTime :: TimeSignature -> TimeSignature
toSimpleTime = fromRational . toRational
-- | Set the time signature of the given score.
timeSignature :: (HasMeta a, HasPosition a, Transformable a) => TimeSignature -> a -> a
timeSignature c x = case _era x of
Nothing -> x
Just e -> timeSignatureDuring e c x
-- use (x^.onset <-> x^.offset) instead of (0 <-> x^.offset)
-- timeSignature' c x = timeSignatureDuring (era x) c x
-- | Set the time signature of the given part of a score.
timeSignatureDuring :: HasMeta a => Span -> TimeSignature -> a -> a
timeSignatureDuring s c = addMetaEvent $ view event (s, Just $ Last c)
-- | Time signature typically used for the given duration.
--
> > > standardTimeSignature 1
Just 4/4
--
> > > standardTimeSignature 0.5
Just 2/4
--
Just standardTimeSignature 0.625
Just 5/8
--
Returns Nothing if the denominator of the canonical form of given duration is not a power of two .
standardTimeSignature :: Duration -> Maybe TimeSignature
standardTimeSignature x = case unRatio (toRational x) of
( 1,2 ) - > time 1 2
(2, 2) -> pure $ time 2 2
(3, 2) -> pure $ time 3 2
(2, 1) -> pure $ time 4 2
(5, 2) -> pure $ time 5 2
(3, 1) -> pure $ time 6 2
(7, 2) -> pure $ time 7 2
(1, 4) -> pure $ time 1 4
(1, 2) -> pure $ time 2 4
(3, 4) -> pure $ time 3 4
(1, 1) -> pure $ time 4 4
(5, 4) -> pure $ time 5 4
( 3,2 ) - > pure $ time 6 4
(7, 4) -> pure $ time 7 4
(1, 8) -> pure $ time 1 8
( 1,4 ) - > pure $ time 2 8
(3, 8) -> pure $ time 3 8
( 1,2 ) - > pure $ time 4 8
(5, 8) -> pure $ time 5 8
( 3,4 ) - > pure $ time 6 8
(7, 8) -> pure $ time 7 8
TODO check divisible by 8 etc
(m, n)
| isPowerOfTwo n -> pure $ time m n
| otherwise -> Nothing
isPowerOfTwo :: Integer -> Bool
isPowerOfTwo 0 = True
isPowerOfTwo 1 = False
isPowerOfTwo n = (n .&. (n -1)) == 0
# INLINE isPowerOfTwo #
mapNums :: ([Integer] -> [Integer]) -> TimeSignature -> TimeSignature
mapDenom :: (Integer -> Integer) -> TimeSignature -> TimeSignature
isSimple :: TimeSignature -> Bool
getSimple :: TimeSignature -> Integer
liftRational :: (Fractional c, Real a) => (Rational -> Rational) -> a -> c
liftRational2 :: (Fractional a, Real a1, Real a2) => (Rational -> Rational -> Rational) -> a1 -> a2 -> a
| null |
https://raw.githubusercontent.com/music-suite/music-suite/7f01fd62334c66418043b7a2d662af127f98685d/src/Music/Score/Meta/Time.hs
|
haskell
|
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
|
License : BSD-style
Stability : experimental
Provides time signatures and related meta-data.
* Time signature type
* Adding time signature to scores
* Utility
|
A time signature is a sequence of beat numbers and a note value (i.e. an expression on the
form @(a1+a2...)/b@). For simple time signatures just one beat number is used.
follows:
| Create a simple time signature.
| Create a compound time signature.
| Whether this is a simple time signature.
| Whether this is a compound time signature.
| Convert to a simple time signature by adding all numerators.
If given a simple time signature, returns it.
| Set the time signature of the given score.
use (x^.onset <-> x^.offset) instead of (0 <-> x^.offset)
timeSignature' c x = timeSignatureDuring (era x) c x
| Set the time signature of the given part of a score.
| Time signature typically used for the given duration.
|
# OPTIONS_GHC -fno - warn - name - shadowing
-fno - warn - unused - imports
-fno - warn - redundant - constraints #
-fno-warn-unused-imports
-fno-warn-redundant-constraints #-}
Copyright : ( c ) 2012 - 2014
Maintainer :
Portability : non - portable ( TF , )
module Music.Score.Meta.Time
TimeSignature (..),
time,
compoundTime,
isSimpleTime,
isCompoundTime,
toSimpleTime,
timeSignature,
timeSignatureDuring,
standardTimeSignature,
)
where
import Control.Lens (view, (^.))
import Control.Monad.Plus
import Data.Bifunctor
import Data.Bits ((.&.))
import Data.Foldable (Foldable)
import qualified Data.Foldable as F
import qualified Data.List as List
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Maybe
import Data.Ratio ((%))
import Data.Semigroup
import Data.Set (Set)
import qualified Data.Set as Set
import Data.String
import Data.Traversable (Traversable)
import qualified Data.Traversable as T
import Data.Typeable
import Music.Pitch.Literal
import Music.Score.Internal.Util
import Music.Score.Meta
import Music.Score.Part
import Music.Score.Pitch
import Music.Time
TimeSignature is an instance of ' Fractional ' and can be used as
> timeSignature ( 4/4 )
> timeSignature ( 6/8 )
> ( ( 3 + 2)/4 )
newtype TimeSignature = TimeSignature {getTimeSignature :: ([Integer], Integer)}
deriving (Eq, Ord, Typeable)
mapNums f (TimeSignature (m, n)) = TimeSignature (f m, n)
mapDenom f (TimeSignature (m, n)) = TimeSignature (m, f n)
isSimple (TimeSignature ([_], _)) = True
isSimple _ = False
getSimple (TimeSignature ([m], n)) = m `div` n
getSimple _ = error "getSimple: Not a simple time signature"
TODO move
liftRational f = fromRational . f . toRational
liftRational2 f x y = fromRational $ toRational x `f` toRational y
instance Num TimeSignature where
x + y
| x `haveSameDenominator` y = concatFrac x y
| otherwise = liftRational2 (+) x y
where
TimeSignature (_, n1) `haveSameDenominator` TimeSignature (_, n2) = n1 == n2
TimeSignature (m1, n) `concatFrac` TimeSignature (m2, _) = TimeSignature (m1 <> m2, n)
x * y
| isSimple y = mapNums (fmap (* getSimple y)) x
| otherwise = liftRational2 (*) x y
negate = liftRational negate
abs = liftRational abs
signum = liftRational signum
fromInteger x = TimeSignature ([x], 1)
instance Fractional TimeSignature where
fromRational (unRatio -> (m, n)) = TimeSignature ([m], n)
x / y
| isSimple y = mapDenom (* getSimple y) x
| otherwise = liftRational2 (/) x y
instance Real TimeSignature where
toRational (TimeSignature (xs, x)) = sum xs % x
instance Show TimeSignature where
show (TimeSignature ([m], n)) = show m ++ "/" ++ show n
show (TimeSignature (xs, n)) = "(" ++ List.intercalate "+" (fmap show xs) ++ ")/" ++ show n
time :: Integer -> Integer -> TimeSignature
time x y = TimeSignature ([x], y)
compoundTime :: [Integer] -> Integer -> TimeSignature
compoundTime = curry TimeSignature
isSimpleTime :: TimeSignature -> Bool
isSimpleTime (TimeSignature ([_], _)) = True
isSimpleTime _ = False
isCompoundTime :: TimeSignature -> Bool
isCompoundTime = not . isSimpleTime
toSimpleTime :: TimeSignature -> TimeSignature
toSimpleTime = fromRational . toRational
timeSignature :: (HasMeta a, HasPosition a, Transformable a) => TimeSignature -> a -> a
timeSignature c x = case _era x of
Nothing -> x
Just e -> timeSignatureDuring e c x
timeSignatureDuring :: HasMeta a => Span -> TimeSignature -> a -> a
timeSignatureDuring s c = addMetaEvent $ view event (s, Just $ Last c)
> > > standardTimeSignature 1
Just 4/4
> > > standardTimeSignature 0.5
Just 2/4
Just standardTimeSignature 0.625
Just 5/8
Returns Nothing if the denominator of the canonical form of given duration is not a power of two .
standardTimeSignature :: Duration -> Maybe TimeSignature
standardTimeSignature x = case unRatio (toRational x) of
( 1,2 ) - > time 1 2
(2, 2) -> pure $ time 2 2
(3, 2) -> pure $ time 3 2
(2, 1) -> pure $ time 4 2
(5, 2) -> pure $ time 5 2
(3, 1) -> pure $ time 6 2
(7, 2) -> pure $ time 7 2
(1, 4) -> pure $ time 1 4
(1, 2) -> pure $ time 2 4
(3, 4) -> pure $ time 3 4
(1, 1) -> pure $ time 4 4
(5, 4) -> pure $ time 5 4
( 3,2 ) - > pure $ time 6 4
(7, 4) -> pure $ time 7 4
(1, 8) -> pure $ time 1 8
( 1,4 ) - > pure $ time 2 8
(3, 8) -> pure $ time 3 8
( 1,2 ) - > pure $ time 4 8
(5, 8) -> pure $ time 5 8
( 3,4 ) - > pure $ time 6 8
(7, 8) -> pure $ time 7 8
TODO check divisible by 8 etc
(m, n)
| isPowerOfTwo n -> pure $ time m n
| otherwise -> Nothing
isPowerOfTwo :: Integer -> Bool
isPowerOfTwo 0 = True
isPowerOfTwo 1 = False
isPowerOfTwo n = (n .&. (n -1)) == 0
# INLINE isPowerOfTwo #
mapNums :: ([Integer] -> [Integer]) -> TimeSignature -> TimeSignature
mapDenom :: (Integer -> Integer) -> TimeSignature -> TimeSignature
isSimple :: TimeSignature -> Bool
getSimple :: TimeSignature -> Integer
liftRational :: (Fractional c, Real a) => (Rational -> Rational) -> a -> c
liftRational2 :: (Fractional a, Real a1, Real a2) => (Rational -> Rational -> Rational) -> a1 -> a2 -> a
|
690da00d4aeea6e64a33acb4567f6f2fa310a5887413faf6bedc5997a92589ca
|
cbaggers/shipshape
|
ship.lisp
|
(in-package :shipshape)
(defun ship-it (system-name)
(let ((system-name
(or (asdf:coerce-name system-name)
(error "Could not coerce "))))
(unless (asdf:find-component system-name nil)
(error "No system named ~s was found, has it been loaded yet?"
system-name))
(let ((src (asdf:system-relative-pathname :shipshape "build-it.lisp"))
(dst (asdf:system-relative-pathname system-name "build-it.lisp")))
(cl-fad:copy-file src dst :overwrite t)
;; If we can then lets run the script for the user..
#+(and sbcl (or linux darwin))
(let ((task (format nil "sbcl --load ~s --system ~s" (namestring dst) system-name)))
(format t "will now try to run: ~a" task)
(asdf/run-program:run-program task :output *standard-output*))
;; ..Otherwise let them know how to run it
#+(or windows (not sbcl))
(format t "Please run your implementation's equivalent of the following: sbcl --load \"build-it.lisp\" --system ~s"
system-name))))
(defun set-sail (system-name &optional (profile +default-profile+))
;; force load to catch errors
(unless (asdf:component-loaded-p system-name)
(asdf:load-system system-name :force t))
;; manifest should now be available
(let ((manifest (find-manifest system-name profile)))
(unless manifest
(error "No shipping manifest found for ~s with profile ~s"
system-name profile))
;; delete any existing build
(ensure-no-directory (local-media-path manifest))
(ensure-no-directory (local-c-library-path manifest))
;; Copy all files
(copy-all-media manifest)
(copy-all-c-libs manifest)
;; disconnect all c-libraries
(disconnect-all-c-libs)
;; we have picked a profile so the other information is redundent
(transform-manifest-store-for-shipped profile)
;; and now we can save
(let ((binary-path (merge-pathnames
(binary-name manifest)
(local-path (build-path manifest)
(system manifest)))))
(setf *shipped* t)
(save-core binary-path manifest)
(format t "~%Binary written to ~a" binary-path))))
(defun dock ()
;; Only used during development of shipshape
(setf *shipped* nil)
(transform-manifest-store-for-dev))
(defun command-line-invoke ()
(labels ((argument (name)
(let* ((args sb-ext:*posix-argv*)
(index (position name args :test 'equal))
(value (when (and (numberp index)
(< index (length args)))
(nth (1+ index) args))))
value)))
(let* ((system (argument "--system"))
(profile (or (argument "--profile") +default-profile+)))
(set-sail system profile))))
| null |
https://raw.githubusercontent.com/cbaggers/shipshape/af0238a267e3f5e8dcd1ab5e41f01594f4360997/ship.lisp
|
lisp
|
If we can then lets run the script for the user..
..Otherwise let them know how to run it
force load to catch errors
manifest should now be available
delete any existing build
Copy all files
disconnect all c-libraries
we have picked a profile so the other information is redundent
and now we can save
Only used during development of shipshape
|
(in-package :shipshape)
(defun ship-it (system-name)
(let ((system-name
(or (asdf:coerce-name system-name)
(error "Could not coerce "))))
(unless (asdf:find-component system-name nil)
(error "No system named ~s was found, has it been loaded yet?"
system-name))
(let ((src (asdf:system-relative-pathname :shipshape "build-it.lisp"))
(dst (asdf:system-relative-pathname system-name "build-it.lisp")))
(cl-fad:copy-file src dst :overwrite t)
#+(and sbcl (or linux darwin))
(let ((task (format nil "sbcl --load ~s --system ~s" (namestring dst) system-name)))
(format t "will now try to run: ~a" task)
(asdf/run-program:run-program task :output *standard-output*))
#+(or windows (not sbcl))
(format t "Please run your implementation's equivalent of the following: sbcl --load \"build-it.lisp\" --system ~s"
system-name))))
(defun set-sail (system-name &optional (profile +default-profile+))
(unless (asdf:component-loaded-p system-name)
(asdf:load-system system-name :force t))
(let ((manifest (find-manifest system-name profile)))
(unless manifest
(error "No shipping manifest found for ~s with profile ~s"
system-name profile))
(ensure-no-directory (local-media-path manifest))
(ensure-no-directory (local-c-library-path manifest))
(copy-all-media manifest)
(copy-all-c-libs manifest)
(disconnect-all-c-libs)
(transform-manifest-store-for-shipped profile)
(let ((binary-path (merge-pathnames
(binary-name manifest)
(local-path (build-path manifest)
(system manifest)))))
(setf *shipped* t)
(save-core binary-path manifest)
(format t "~%Binary written to ~a" binary-path))))
(defun dock ()
(setf *shipped* nil)
(transform-manifest-store-for-dev))
(defun command-line-invoke ()
(labels ((argument (name)
(let* ((args sb-ext:*posix-argv*)
(index (position name args :test 'equal))
(value (when (and (numberp index)
(< index (length args)))
(nth (1+ index) args))))
value)))
(let* ((system (argument "--system"))
(profile (or (argument "--profile") +default-profile+)))
(set-sail system profile))))
|
c91efd60c3b7afecf384504a9e6adf2a21d54c33f22f6c56edede06ed0ce067a
|
turion/rhine
|
Event.hs
|
|
This module provides two things :
* Clocks that tick whenever events arrive on a ' Control . Concurrent . ' ,
and useful utilities .
* Primitives to emit events .
Note that _ events work across multiple clocks _ ,
i.e. it is possible ( and encouraged ) to emit events from signals
on a different clock than the event clock .
This is in line with the Rhine philosophy that _ event sources are clocks _ .
Events even work well across separate threads ,
and constitute the recommended way of communication between threads in Rhine .
A simple example using events and threads can be found in rhine - examples .
This module provides two things:
* Clocks that tick whenever events arrive on a 'Control.Concurrent.Chan',
and useful utilities.
* Primitives to emit events.
Note that _events work across multiple clocks_,
i.e. it is possible (and encouraged) to emit events from signals
on a different clock than the event clock.
This is in line with the Rhine philosophy that _event sources are clocks_.
Events even work well across separate threads,
and constitute the recommended way of communication between threads in Rhine.
A simple example using events and threads can be found in rhine-examples.
-}
# LANGUAGE DataKinds #
# LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
# LANGUAGE MultiParamTypeClasses #
{-# LANGUAGE RankNTypes #-}
# LANGUAGE TypeFamilies #
module FRP.Rhine.Clock.Realtime.Event
( module FRP.Rhine.Clock.Realtime.Event
, module Control.Monad.IO.Class
, newChan
)
where
-- base
import Control.Concurrent.Chan
import Data.Time.Clock
deepseq
import Control.DeepSeq
-- transformers
import Control.Monad.IO.Class
import Control.Monad.Trans.Reader
-- rhine
import FRP.Rhine.Clock.Proxy
import FRP.Rhine.ClSF
import FRP.Rhine.Schedule
import FRP.Rhine.Schedule.Concurrently
-- * Monads allowing for event emission and handling
-- | A monad transformer in which events can be emitted onto a 'Chan'.
type EventChanT event m = ReaderT (Chan event) m
| Escape the ' EventChanT ' layer by explicitly providing a channel
-- over which events are sent.
-- Often this is not needed, and 'runEventChanT' can be used instead.
withChan :: Chan event -> EventChanT event m a -> m a
withChan = flip runReaderT
| Create a channel across which events can be communicated ,
and subsequently execute all event effects on this channel .
Ideally , this action is run _ outside _ of ' flow ' ,
e.g. @runEventChanT $ flow myRhine@.
This way , exactly one channel is created .
Caution : Do n't use this with ' morphS ' ,
since it would create a new channel every tick .
Instead , create one @chan : : c@ , e.g. with ' newChan ' ,
and then use ' withChanS ' .
and subsequently execute all event effects on this channel.
Ideally, this action is run _outside_ of 'flow',
e.g. @runEventChanT $ flow myRhine@.
This way, exactly one channel is created.
Caution: Don't use this with 'morphS',
since it would create a new channel every tick.
Instead, create one @chan :: Chan c@, e.g. with 'newChan',
and then use 'withChanS'.
-}
runEventChanT :: MonadIO m => EventChanT event m a -> m a
runEventChanT a = do
chan <- liftIO newChan
runReaderT a chan
| Remove ( " run " ) an ' EventChanT ' layer from the monad stack
by passing it explicitly the channel over which events are sent .
This is usually only needed if you ca n't use ' runEventChanT '
to create the channel .
Typically , create a @chan : : c@ in your main program
before the main loop ( e.g. ' flow ' ) would be run ,
then , by using this function ,
pass the channel to every behaviour or ' ' that wants to emit events ,
and , by using ' eventClockOn ' , to every clock that should tick on the event .
by passing it explicitly the channel over which events are sent.
This is usually only needed if you can't use 'runEventChanT'
to create the channel.
Typically, create a @chan :: Chan c@ in your main program
before the main loop (e.g. 'flow') would be run,
then, by using this function,
pass the channel to every behaviour or 'ClSF' that wants to emit events,
and, by using 'eventClockOn', to every clock that should tick on the event.
-}
withChanS
:: Monad m
=> Chan event
-> ClSF (EventChanT event m) cl a b
-> ClSF m cl a b
withChanS = flip runReaderS_
-- * Event emission
| Emit a single event .
This causes every ' EventClock ' on the same monad to tick immediately .
Be cautious when emitting events from a signal clocked by an ' EventClock ' .
Nothing prevents you from emitting more events than are handled ,
causing the event buffer to grow indefinitely .
This causes every 'EventClock' on the same monad to tick immediately.
Be cautious when emitting events from a signal clocked by an 'EventClock'.
Nothing prevents you from emitting more events than are handled,
causing the event buffer to grow indefinitely.
-}
emit :: MonadIO m => event -> EventChanT event m ()
emit event = do
chan <- ask
liftIO $ writeChan chan event
-- | Emit an event on every tick.
emitS :: MonadIO m => ClSF (EventChanT event m) cl event ()
emitS = arrMCl emit
-- | Emit an event whenever the input value is @Just event@.
emitSMaybe :: MonadIO m => ClSF (EventChanT event m) cl (Maybe event) ()
emitSMaybe = mapMaybe emitS >>> arr (const ())
-- | Like 'emit', but completely evaluates the event before emitting it.
emit' :: (NFData event, MonadIO m) => event -> EventChanT event m ()
emit' event = event `deepseq` do
chan <- ask
liftIO $ writeChan chan event
-- | Like 'emitS', but completely evaluates the event before emitting it.
emitS' :: (NFData event, MonadIO m) => ClSF (EventChanT event m) cl event ()
emitS' = arrMCl emit'
-- | Like 'emitSMaybe', but completely evaluates the event before emitting it.
emitSMaybe'
:: (NFData event, MonadIO m)
=> ClSF (EventChanT event m) cl (Maybe event) ()
emitSMaybe' = mapMaybe emitS' >>> arr (const ())
-- * Event clocks and schedules
-- | A clock that ticks whenever an @event@ is emitted.
-- It is not yet bound to a specific channel,
-- since ideally, the correct channel is created automatically
-- by 'runEventChanT'.
-- If you want to create the channel manually and bind the clock to it,
-- use 'eventClockOn'.
data EventClock event = EventClock
instance Semigroup (EventClock event) where
(<>) _ _ = EventClock
instance MonadIO m => Clock (EventChanT event m) (EventClock event) where
type Time (EventClock event) = UTCTime
type Tag (EventClock event) = event
initClock _ = do
initialTime <- liftIO getCurrentTime
return
( constM $ do
chan <- ask
event <- liftIO $ readChan chan
time <- liftIO getCurrentTime
return (time, event)
, initialTime
)
instance GetClockProxy (EventClock event)
-- | Create an event clock that is bound to a specific event channel.
-- This is usually only useful if you can't apply 'runEventChanT'
-- to the main loop (see 'withChanS').
eventClockOn
:: MonadIO m
=> Chan event
-> HoistClock (EventChanT event m) m (EventClock event)
eventClockOn chan = HoistClock
{ unhoistedClock = EventClock
, monadMorphism = withChan chan
}
|
Given two clocks with an ' EventChanT ' layer directly atop the ' IO ' monad ,
you can schedule them using concurrent GHC threads ,
and share the event channel .
Typical use cases :
* Different subevent selection clocks
( implemented i.e. with ' FRP.Rhine . Clock . Select ' )
on top of the same main event source .
* An event clock and other event - unaware clocks in the ' IO ' monad ,
which are lifted using ' ' .
Given two clocks with an 'EventChanT' layer directly atop the 'IO' monad,
you can schedule them using concurrent GHC threads,
and share the event channel.
Typical use cases:
* Different subevent selection clocks
(implemented i.e. with 'FRP.Rhine.Clock.Select')
on top of the same main event source.
* An event clock and other event-unaware clocks in the 'IO' monad,
which are lifted using 'liftClock'.
-}
concurrentlyWithEvents
:: ( Time cl1 ~ Time cl2
, Clock (EventChanT event IO) cl1
, Clock (EventChanT event IO) cl2
)
=> Schedule (EventChanT event IO) cl1 cl2
concurrentlyWithEvents = readerSchedule concurrently
| null |
https://raw.githubusercontent.com/turion/rhine/3bae3ddfa1ee70b8487e214f09a80c75b34f7398/rhine/src/FRP/Rhine/Clock/Realtime/Event.hs
|
haskell
|
# LANGUAGE RankNTypes #
base
transformers
rhine
* Monads allowing for event emission and handling
| A monad transformer in which events can be emitted onto a 'Chan'.
over which events are sent.
Often this is not needed, and 'runEventChanT' can be used instead.
* Event emission
| Emit an event on every tick.
| Emit an event whenever the input value is @Just event@.
| Like 'emit', but completely evaluates the event before emitting it.
| Like 'emitS', but completely evaluates the event before emitting it.
| Like 'emitSMaybe', but completely evaluates the event before emitting it.
* Event clocks and schedules
| A clock that ticks whenever an @event@ is emitted.
It is not yet bound to a specific channel,
since ideally, the correct channel is created automatically
by 'runEventChanT'.
If you want to create the channel manually and bind the clock to it,
use 'eventClockOn'.
| Create an event clock that is bound to a specific event channel.
This is usually only useful if you can't apply 'runEventChanT'
to the main loop (see 'withChanS').
|
|
This module provides two things :
* Clocks that tick whenever events arrive on a ' Control . Concurrent . ' ,
and useful utilities .
* Primitives to emit events .
Note that _ events work across multiple clocks _ ,
i.e. it is possible ( and encouraged ) to emit events from signals
on a different clock than the event clock .
This is in line with the Rhine philosophy that _ event sources are clocks _ .
Events even work well across separate threads ,
and constitute the recommended way of communication between threads in Rhine .
A simple example using events and threads can be found in rhine - examples .
This module provides two things:
* Clocks that tick whenever events arrive on a 'Control.Concurrent.Chan',
and useful utilities.
* Primitives to emit events.
Note that _events work across multiple clocks_,
i.e. it is possible (and encouraged) to emit events from signals
on a different clock than the event clock.
This is in line with the Rhine philosophy that _event sources are clocks_.
Events even work well across separate threads,
and constitute the recommended way of communication between threads in Rhine.
A simple example using events and threads can be found in rhine-examples.
-}
# LANGUAGE DataKinds #
# LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE TypeFamilies #
module FRP.Rhine.Clock.Realtime.Event
( module FRP.Rhine.Clock.Realtime.Event
, module Control.Monad.IO.Class
, newChan
)
where
import Control.Concurrent.Chan
import Data.Time.Clock
deepseq
import Control.DeepSeq
import Control.Monad.IO.Class
import Control.Monad.Trans.Reader
import FRP.Rhine.Clock.Proxy
import FRP.Rhine.ClSF
import FRP.Rhine.Schedule
import FRP.Rhine.Schedule.Concurrently
type EventChanT event m = ReaderT (Chan event) m
| Escape the ' EventChanT ' layer by explicitly providing a channel
withChan :: Chan event -> EventChanT event m a -> m a
withChan = flip runReaderT
| Create a channel across which events can be communicated ,
and subsequently execute all event effects on this channel .
Ideally , this action is run _ outside _ of ' flow ' ,
e.g. @runEventChanT $ flow myRhine@.
This way , exactly one channel is created .
Caution : Do n't use this with ' morphS ' ,
since it would create a new channel every tick .
Instead , create one @chan : : c@ , e.g. with ' newChan ' ,
and then use ' withChanS ' .
and subsequently execute all event effects on this channel.
Ideally, this action is run _outside_ of 'flow',
e.g. @runEventChanT $ flow myRhine@.
This way, exactly one channel is created.
Caution: Don't use this with 'morphS',
since it would create a new channel every tick.
Instead, create one @chan :: Chan c@, e.g. with 'newChan',
and then use 'withChanS'.
-}
runEventChanT :: MonadIO m => EventChanT event m a -> m a
runEventChanT a = do
chan <- liftIO newChan
runReaderT a chan
| Remove ( " run " ) an ' EventChanT ' layer from the monad stack
by passing it explicitly the channel over which events are sent .
This is usually only needed if you ca n't use ' runEventChanT '
to create the channel .
Typically , create a @chan : : c@ in your main program
before the main loop ( e.g. ' flow ' ) would be run ,
then , by using this function ,
pass the channel to every behaviour or ' ' that wants to emit events ,
and , by using ' eventClockOn ' , to every clock that should tick on the event .
by passing it explicitly the channel over which events are sent.
This is usually only needed if you can't use 'runEventChanT'
to create the channel.
Typically, create a @chan :: Chan c@ in your main program
before the main loop (e.g. 'flow') would be run,
then, by using this function,
pass the channel to every behaviour or 'ClSF' that wants to emit events,
and, by using 'eventClockOn', to every clock that should tick on the event.
-}
withChanS
:: Monad m
=> Chan event
-> ClSF (EventChanT event m) cl a b
-> ClSF m cl a b
withChanS = flip runReaderS_
| Emit a single event .
This causes every ' EventClock ' on the same monad to tick immediately .
Be cautious when emitting events from a signal clocked by an ' EventClock ' .
Nothing prevents you from emitting more events than are handled ,
causing the event buffer to grow indefinitely .
This causes every 'EventClock' on the same monad to tick immediately.
Be cautious when emitting events from a signal clocked by an 'EventClock'.
Nothing prevents you from emitting more events than are handled,
causing the event buffer to grow indefinitely.
-}
emit :: MonadIO m => event -> EventChanT event m ()
emit event = do
chan <- ask
liftIO $ writeChan chan event
emitS :: MonadIO m => ClSF (EventChanT event m) cl event ()
emitS = arrMCl emit
emitSMaybe :: MonadIO m => ClSF (EventChanT event m) cl (Maybe event) ()
emitSMaybe = mapMaybe emitS >>> arr (const ())
emit' :: (NFData event, MonadIO m) => event -> EventChanT event m ()
emit' event = event `deepseq` do
chan <- ask
liftIO $ writeChan chan event
emitS' :: (NFData event, MonadIO m) => ClSF (EventChanT event m) cl event ()
emitS' = arrMCl emit'
emitSMaybe'
:: (NFData event, MonadIO m)
=> ClSF (EventChanT event m) cl (Maybe event) ()
emitSMaybe' = mapMaybe emitS' >>> arr (const ())
data EventClock event = EventClock
instance Semigroup (EventClock event) where
(<>) _ _ = EventClock
instance MonadIO m => Clock (EventChanT event m) (EventClock event) where
type Time (EventClock event) = UTCTime
type Tag (EventClock event) = event
initClock _ = do
initialTime <- liftIO getCurrentTime
return
( constM $ do
chan <- ask
event <- liftIO $ readChan chan
time <- liftIO getCurrentTime
return (time, event)
, initialTime
)
instance GetClockProxy (EventClock event)
eventClockOn
:: MonadIO m
=> Chan event
-> HoistClock (EventChanT event m) m (EventClock event)
eventClockOn chan = HoistClock
{ unhoistedClock = EventClock
, monadMorphism = withChan chan
}
|
Given two clocks with an ' EventChanT ' layer directly atop the ' IO ' monad ,
you can schedule them using concurrent GHC threads ,
and share the event channel .
Typical use cases :
* Different subevent selection clocks
( implemented i.e. with ' FRP.Rhine . Clock . Select ' )
on top of the same main event source .
* An event clock and other event - unaware clocks in the ' IO ' monad ,
which are lifted using ' ' .
Given two clocks with an 'EventChanT' layer directly atop the 'IO' monad,
you can schedule them using concurrent GHC threads,
and share the event channel.
Typical use cases:
* Different subevent selection clocks
(implemented i.e. with 'FRP.Rhine.Clock.Select')
on top of the same main event source.
* An event clock and other event-unaware clocks in the 'IO' monad,
which are lifted using 'liftClock'.
-}
concurrentlyWithEvents
:: ( Time cl1 ~ Time cl2
, Clock (EventChanT event IO) cl1
, Clock (EventChanT event IO) cl2
)
=> Schedule (EventChanT event IO) cl1 cl2
concurrentlyWithEvents = readerSchedule concurrently
|
9782eeae3b79272a83b0ceb128c47bb9147026d3a1c57a235c0070a321d270b0
|
fjames86/frpc2
|
rpcbind.lisp
|
Copyright ( c ) 2016 < >
This code is licensed under the MIT license .
(defpackage #:rpcbind
(:use #:cl #:frpc2)
(:export #:rpcbind
#:start-rpcbind
#:stop-rpcbind
#:register-program
#:unregister-program))
(in-package #:rpcbind)
;; ------------------- logging -------------------------
(defvar *rpcbind-tag* (babel:string-to-octets "RPCB"))
(defun rpcbind-log (lvl format-string &rest args)
(when *frpc2-log*
(pounds.log:write-message *frpc2-log* lvl
(apply #'format nil format-string args)
:tag *rpcbind-tag*)))
;; -------------- globals ------------------
(defvar *mappings* (make-list 32))
(defparameter *heartbeat-age* nil
"If non-nil, will call the nullproc periodically after this many seconds.
Typical values might be 5 minutes.")
(defparameter *purge-age* nil
"If non-nil, is the number of seconds without reply afterwhich the mapping will be purged. A typical value might be 6 minutes.")
;; --------------- RPC Handlers ----------------
;; the set and unset handlers may only be called from loopback device
(defun loopback-or-fail (server)
(let ((pfd (simple-rpc-server-rpfd server)))
(typecase pfd
(udp-pollfd
(unless (fsocket:loopback-p (udp-pollfd-addr pfd))
(error 'auth-error :stat :tooweak)))
(tcp-pollfd
(unless (fsocket:loopback-p (tcp-pollfd-addr pfd))
(error 'auth-error :stat :tooweak))))))
;; proc 0
(defun handle-rpcbind-null (server arg)
(declare (ignore server arg))
(rpcbind-log :info "START NULL")
nil)
proc 1
(defun handle-rpcbind-set (server mapping)
(rpcbind-log :info "START SET")
(loopback-or-fail server)
(let ((oldest 0))
(do ((mappings *mappings* (cdr mappings))
(i 0 (1+ i))
(age 0))
((null mappings))
(let ((m (car mappings)))
(cond
((null m)
(setf oldest i
mappings nil))
((and (= (mapping-program (car m)) (mapping-program mapping))
(eq (mapping-protocol (car m)) (mapping-protocol mapping)))
;; program already exists on this protocol, don't add
(return-from handle-rpcbind-set nil))
(t
(destructuring-bind (mp last-seen next-heartbeat) m
(declare (ignore mp next-heartbeat))
(when (or (zerop age) (< last-seen age))
(setf oldest i
age last-seen)))))))
(setf (nth oldest *mappings*)
(list mapping (get-universal-time)
(when *heartbeat-age*
(+ (get-universal-time) *heartbeat-age*))))
t))
proc 2
(defun handle-rpcbind-unset (server mapping)
(rpcbind-log :info "START UNSET")
(loopback-or-fail server)
(do ((mappings *mappings* (cdr mappings)))
((null mappings))
(when (car mappings)
(destructuring-bind (mp last-seen next-heartbeat) (car mappings)
(declare (ignore last-seen next-heartbeat))
(when (and (= (mapping-program mapping) (mapping-program mp))
(eq (mapping-protocol mapping) (mapping-protocol mp)))
;; found it. clear out entry
(setf (car mappings) nil)))))
t)
proc 3
(defun handle-rpcbind-getport (server mapping)
(declare (ignore server))
(rpcbind-log :info "START GETPORT")
(dolist (m *mappings*)
(when m
(destructuring-bind (mp last-seen next-heartbeat) m
(declare (ignore last-seen next-heartbeat))
(when (and (= (mapping-program mapping) (mapping-program mp))
(= (mapping-version mapping) (mapping-version mp))
(eq (mapping-protocol mapping) (mapping-protocol mp)))
(return-from handle-rpcbind-getport
(mapping-port mp))))))
0)
proc 4
(defun handle-rpcbind-dump (server arg)
(declare (ignore server arg))
(rpcbind-log :info "START DUMP")
(mapcan (lambda (m)
(when m
(list (car m))))
*mappings*))
-------- proc 5 ( ) requires special treatment -----------
(defun process-callit-reply (server blk arg)
(let ((msg (simple-rpc-server-msg server)))
;; we don't want to send any reply in the event that the call failed
(handler-bind ((error (lambda (e)
(rpcbind-log :info "Callit failed ~A" e)
(return-from process-callit-reply nil))))
(frpc2::rpc-reply-verf msg)))
(destructuring-bind (raddr rxid rpfd) arg
(rpcbind-log :info "Callit reply ~A" rxid)
send the reply back to the reply address
(let ((rblk (drx:xdr-block (- (drx:xdr-block-count blk)
(drx:xdr-block-offset blk)))))
(rpcbind-log :info "Callit reply ~A bytes"
(- (drx:xdr-block-count blk)
(drx:xdr-block-offset blk)))
(do ((i (drx:xdr-block-offset blk) (1+ i)))
((= i (drx:xdr-block-count blk)))
(setf (aref (drx:xdr-block-buffer rblk) (- i (drx:xdr-block-offset blk)))
(aref (drx:xdr-block-buffer blk) i)))
(let ((res (list (fsocket:sockaddr-in-port
(udp-pollfd-addr
(simple-rpc-server-rpfd server)))
(list (drx:xdr-block-buffer rblk)
0 (- (drx:xdr-block-count blk)
(drx:xdr-block-offset blk))))))
(drx:reset-xdr-block blk)
(encode-rpc-msg blk (make-rpc-reply rxid :success))
(encode-callit-res blk res)
(etypecase rpfd
(udp-pollfd
(rpcbind-log :trace "Replying to UDP client")
(fsocket:socket-sendto (fsocket:pollfd-fd rpfd)
(drx:xdr-block-buffer blk)
raddr
:start 0 :end (drx:xdr-block-offset blk)))
(tcp-pollfd
(rpcbind-log :trace "Replying to TCP client")
need to send the byte count first
(let ((cblk (drx:xdr-block 4)))
(drx:encode-uint32 cblk (logior (drx:xdr-block-offset blk) #x80000000))
(let ((cnt (fsocket:socket-send (fsocket:pollfd-fd rpfd)
(drx:xdr-block-buffer cblk))))
(unless (= cnt 4) (rpcbind-log :trace "Short write"))))
(let ((cnt (fsocket:socket-send (fsocket:pollfd-fd rpfd)
(drx:xdr-block-buffer blk)
:start 0 :end (drx:xdr-block-offset blk))))
(unless (= cnt (drx:xdr-block-offset blk)) (rpcbind-log :trace "Short write"))))))))
nil)
(defun handle-rpcbind-callit (server arg)
;; packup and send the arg to the program handler
(rpcbind-log :info "START CALLIT ~A:~A:~A~%" (callit-arg-program arg) (callit-arg-version arg) (callit-arg-proc arg))
(let ((mapping (car (find-if (lambda (m)
(let ((mp (car m)))
(when mp
(and (= (callit-arg-program arg) (mapping-program mp))
(= (callit-arg-version arg) (mapping-version mp))
(eq (mapping-protocol mp) :udp)))))
*mappings*)))
(pfd (find-if (lambda (p)
(typep p 'udp-pollfd))
(fsocket:poll-context-fds (simple-rpc-server-pc server)))))
;; if no mapping found then silently discard
(unless mapping
(rpcbind-log :info "No mapping found")
(rpc-discard-call))
(when pfd
(let ((blk (udp-pollfd-blk pfd))
(carg (destructuring-bind (buf start end) (callit-arg-args arg)
(list (subseq buf start end) 0 (- end start)))))
(drx:reset-xdr-block blk)
(let ((xid (encode-rpc-call blk
#'drx:encode-void
nil
(callit-arg-program arg)
(callit-arg-version arg)
(callit-arg-proc arg)
:xid (rpc-msg-xid (simple-rpc-server-msg server)))))
;; encode the args directly
(dotimes (i (third carg))
(setf (aref (drx:xdr-block-buffer blk)
(+ (drx:xdr-block-offset blk) i))
(aref (first carg) i)))
(incf (drx:xdr-block-offset blk) (third carg))
(fsocket:socket-sendto (fsocket:pollfd-fd pfd)
(drx:xdr-block-buffer blk)
(fsocket:make-sockaddr-in :addr #(127 0 0 1)
:port (mapping-port mapping))
:start 0 :end (drx:xdr-block-offset blk))
(rpcbind-log :info "Awaiting reply for ~A" xid)
(simple-rpc-server-await-reply server xid #'process-callit-reply
:context (list (etypecase pfd
(udp-pollfd (udp-pollfd-addr pfd))
(tcp-pollfd (tcp-pollfd-addr pfd)))
xid
(simple-rpc-server-rpfd server)))))))
;; we don't actually want to exit this function normally because otherwise
;; we'd need to block waiting for a reply.
;; Instead we exit early and send the reply later when we receive a response
;; using the simple-rpc-server waiter API.
(rpc-discard-call))
(defconstant +rpcbind-program+ 100000)
(defconstant +rpcbind-version+ 2)
(define-rpc-server rpcbind (+rpcbind-program+ +rpcbind-version+)
(null :void :void)
(set mapping :boolean)
(unset mapping :boolean)
(getport mapping :uint32)
(dump :void mapping-list-opt)
(callit callit-arg callit-res))
(defun process-heartbeat-reply (server blk arg)
(declare (ignore server blk))
(destructuring-bind (program version) arg
(rpcbind-log :info "Heartbeat reply ~A ~A" program version)
(let ((now (get-universal-time)))
;; find the mapping entry and update its timestamp
(dolist (m *mappings*)
(when m
(destructuring-bind (mp last-seen next-heartbeat) m
(declare (ignore last-seen next-heartbeat))
(when (and (= (mapping-program mp) program)
(= (mapping-version mp) version))
(setf (second m) now
(third m) (when *heartbeat-age*
(+ now *heartbeat-age*))))))))))
(defun send-heartbeat (server fd blk mapping)
(drx:reset-xdr-block blk)
;; encode a call and send it
(rpcbind-log :info "Heartbeating ~A on port ~A" (mapping-program mapping) (mapping-port mapping))
(let ((xid (encode-rpc-call blk #'drx:encode-void nil
(mapping-program mapping)
(mapping-version mapping)
0)))
(fsocket:socket-sendto fd
(drx:xdr-block-buffer blk)
(fsocket:make-sockaddr-in :addr #(127 0 0 1)
:port (frpc2:mapping-port mapping))
:start 0 :end (drx:xdr-block-offset blk))
(simple-rpc-server-await-reply server xid
#'process-heartbeat-reply
:context (list (mapping-program mapping)
(mapping-version mapping)))))
(defvar *server* nil)
(defun run-rpcbind (server)
;; main loop
(do ((now (get-universal-time) (get-universal-time)))
((simple-rpc-server-exiting server))
(simple-rpc-server-process server)
;; call the null proc on each of the registered programs
(let ((pfd (find-if (lambda (p)
(typep p 'udp-pollfd))
(fsocket:poll-context-fds (simple-rpc-server-pc server)))))
(when pfd
(let ((blk (udp-pollfd-blk pfd)))
(dolist (m *mappings*)
(when m
(destructuring-bind (mapping last-seen next-heartbeat) m
(declare (ignore last-seen))
(when (and (eq (mapping-protocol mapping) :udp)
next-heartbeat
(> now next-heartbeat))
(send-heartbeat server (fsocket:pollfd-fd pfd)
blk mapping)
add 5 seconds to the next heartbeat age so we do n't spin if no reply received
(incf (third m) 5))))))))
;; purge any mappings which are not responding to heartbeats
(do ((mappings *mappings* (cdr mappings)))
((null mappings))
(let ((m (car mappings)))
(when m
(destructuring-bind (mapping last-seen next-heartbeat) m
(declare (ignore next-heartbeat))
(when (and *purge-age* (> now (+ last-seen *purge-age*)))
(rpcbind-log :info "Purging ~A" (mapping-program mapping))
(setf (car mappings) nil))))))))
(defun start-rpcbind (&key programs udp-ports tcp-ports providers)
"Start an RPC server which serves the rpcbind service.
PROGRAMS ::= a list of programs to serve in addition to the rpcbind program.
UDP-PORTS ::= a list of integers specifying UDP ports to listen on, in addition
to port 111.
TCP-PORTS ::= a list of integers specifying TCP ports to listen on, in addition
to port 111.
PROVIDERS ::= a list of authentication providers to use.
"
(unless *server*
(setf *server* (simple-rpc-server-construct (cons (make-rpcbind-program)
programs)
:providers providers
:udp-ports (cons 111 udp-ports)
:tcp-ports (cons 111 tcp-ports)))
;; ensure we have rpcbind set in the mappings
(handle-rpcbind-set *server* (make-mapping :program 100000 :version 2 :protocol :udp :port 111))
(handle-rpcbind-set *server* (make-mapping :program 100000 :version 2 :protocol :tcp :port 111))
(simple-rpc-server-start *server*
#'run-rpcbind
"rpcbind-service-thread")))
(defun stop-rpcbind ()
"Stop the rpcbind service."
(when *server*
(simple-rpc-server-stop *server*)
(simple-rpc-server-destruct *server*)
(setf *server* nil)))
(defun register-program (program)
(unless *server* (error "RPCBIND server not running."))
(dolist (p (rpc-server-programs *server*))
(when (and (= (first p) (first program))
(= (second p) (second program)))
(setf (cddr p) (cddr program))
(return-from register-program nil)))
(push program (rpc-server-programs *server*))
(handle-rpcbind-set *server*
(make-mapping :program (first program)
:version (second program)
:port 111
:protocol :udp))
(handle-rpcbind-set *server*
(make-mapping :program (first program)
:version (second program)
:port 111
:protocol :tcp))
nil)
(defun unregister-program (program-id version-id)
(unless *server* (error "RPCBIND server not running."))
(setf (rpc-server-programs *server*)
(remove-if (lambda (p)
(and (= (first p) program-id)
(= (second p) version-id)))
(rpc-server-programs *server*)))
nil)
| null |
https://raw.githubusercontent.com/fjames86/frpc2/6b7ec2c7d57a0918ecc3755af75ff183e24d7e85/programs/rpcbind.lisp
|
lisp
|
------------------- logging -------------------------
-------------- globals ------------------
--------------- RPC Handlers ----------------
the set and unset handlers may only be called from loopback device
proc 0
program already exists on this protocol, don't add
found it. clear out entry
we don't want to send any reply in the event that the call failed
packup and send the arg to the program handler
if no mapping found then silently discard
encode the args directly
we don't actually want to exit this function normally because otherwise
we'd need to block waiting for a reply.
Instead we exit early and send the reply later when we receive a response
using the simple-rpc-server waiter API.
find the mapping entry and update its timestamp
encode a call and send it
main loop
call the null proc on each of the registered programs
purge any mappings which are not responding to heartbeats
ensure we have rpcbind set in the mappings
|
Copyright ( c ) 2016 < >
This code is licensed under the MIT license .
(defpackage #:rpcbind
(:use #:cl #:frpc2)
(:export #:rpcbind
#:start-rpcbind
#:stop-rpcbind
#:register-program
#:unregister-program))
(in-package #:rpcbind)
(defvar *rpcbind-tag* (babel:string-to-octets "RPCB"))
(defun rpcbind-log (lvl format-string &rest args)
(when *frpc2-log*
(pounds.log:write-message *frpc2-log* lvl
(apply #'format nil format-string args)
:tag *rpcbind-tag*)))
(defvar *mappings* (make-list 32))
(defparameter *heartbeat-age* nil
"If non-nil, will call the nullproc periodically after this many seconds.
Typical values might be 5 minutes.")
(defparameter *purge-age* nil
"If non-nil, is the number of seconds without reply afterwhich the mapping will be purged. A typical value might be 6 minutes.")
(defun loopback-or-fail (server)
(let ((pfd (simple-rpc-server-rpfd server)))
(typecase pfd
(udp-pollfd
(unless (fsocket:loopback-p (udp-pollfd-addr pfd))
(error 'auth-error :stat :tooweak)))
(tcp-pollfd
(unless (fsocket:loopback-p (tcp-pollfd-addr pfd))
(error 'auth-error :stat :tooweak))))))
(defun handle-rpcbind-null (server arg)
(declare (ignore server arg))
(rpcbind-log :info "START NULL")
nil)
proc 1
(defun handle-rpcbind-set (server mapping)
(rpcbind-log :info "START SET")
(loopback-or-fail server)
(let ((oldest 0))
(do ((mappings *mappings* (cdr mappings))
(i 0 (1+ i))
(age 0))
((null mappings))
(let ((m (car mappings)))
(cond
((null m)
(setf oldest i
mappings nil))
((and (= (mapping-program (car m)) (mapping-program mapping))
(eq (mapping-protocol (car m)) (mapping-protocol mapping)))
(return-from handle-rpcbind-set nil))
(t
(destructuring-bind (mp last-seen next-heartbeat) m
(declare (ignore mp next-heartbeat))
(when (or (zerop age) (< last-seen age))
(setf oldest i
age last-seen)))))))
(setf (nth oldest *mappings*)
(list mapping (get-universal-time)
(when *heartbeat-age*
(+ (get-universal-time) *heartbeat-age*))))
t))
proc 2
(defun handle-rpcbind-unset (server mapping)
(rpcbind-log :info "START UNSET")
(loopback-or-fail server)
(do ((mappings *mappings* (cdr mappings)))
((null mappings))
(when (car mappings)
(destructuring-bind (mp last-seen next-heartbeat) (car mappings)
(declare (ignore last-seen next-heartbeat))
(when (and (= (mapping-program mapping) (mapping-program mp))
(eq (mapping-protocol mapping) (mapping-protocol mp)))
(setf (car mappings) nil)))))
t)
proc 3
(defun handle-rpcbind-getport (server mapping)
(declare (ignore server))
(rpcbind-log :info "START GETPORT")
(dolist (m *mappings*)
(when m
(destructuring-bind (mp last-seen next-heartbeat) m
(declare (ignore last-seen next-heartbeat))
(when (and (= (mapping-program mapping) (mapping-program mp))
(= (mapping-version mapping) (mapping-version mp))
(eq (mapping-protocol mapping) (mapping-protocol mp)))
(return-from handle-rpcbind-getport
(mapping-port mp))))))
0)
proc 4
(defun handle-rpcbind-dump (server arg)
(declare (ignore server arg))
(rpcbind-log :info "START DUMP")
(mapcan (lambda (m)
(when m
(list (car m))))
*mappings*))
-------- proc 5 ( ) requires special treatment -----------
(defun process-callit-reply (server blk arg)
(let ((msg (simple-rpc-server-msg server)))
(handler-bind ((error (lambda (e)
(rpcbind-log :info "Callit failed ~A" e)
(return-from process-callit-reply nil))))
(frpc2::rpc-reply-verf msg)))
(destructuring-bind (raddr rxid rpfd) arg
(rpcbind-log :info "Callit reply ~A" rxid)
send the reply back to the reply address
(let ((rblk (drx:xdr-block (- (drx:xdr-block-count blk)
(drx:xdr-block-offset blk)))))
(rpcbind-log :info "Callit reply ~A bytes"
(- (drx:xdr-block-count blk)
(drx:xdr-block-offset blk)))
(do ((i (drx:xdr-block-offset blk) (1+ i)))
((= i (drx:xdr-block-count blk)))
(setf (aref (drx:xdr-block-buffer rblk) (- i (drx:xdr-block-offset blk)))
(aref (drx:xdr-block-buffer blk) i)))
(let ((res (list (fsocket:sockaddr-in-port
(udp-pollfd-addr
(simple-rpc-server-rpfd server)))
(list (drx:xdr-block-buffer rblk)
0 (- (drx:xdr-block-count blk)
(drx:xdr-block-offset blk))))))
(drx:reset-xdr-block blk)
(encode-rpc-msg blk (make-rpc-reply rxid :success))
(encode-callit-res blk res)
(etypecase rpfd
(udp-pollfd
(rpcbind-log :trace "Replying to UDP client")
(fsocket:socket-sendto (fsocket:pollfd-fd rpfd)
(drx:xdr-block-buffer blk)
raddr
:start 0 :end (drx:xdr-block-offset blk)))
(tcp-pollfd
(rpcbind-log :trace "Replying to TCP client")
need to send the byte count first
(let ((cblk (drx:xdr-block 4)))
(drx:encode-uint32 cblk (logior (drx:xdr-block-offset blk) #x80000000))
(let ((cnt (fsocket:socket-send (fsocket:pollfd-fd rpfd)
(drx:xdr-block-buffer cblk))))
(unless (= cnt 4) (rpcbind-log :trace "Short write"))))
(let ((cnt (fsocket:socket-send (fsocket:pollfd-fd rpfd)
(drx:xdr-block-buffer blk)
:start 0 :end (drx:xdr-block-offset blk))))
(unless (= cnt (drx:xdr-block-offset blk)) (rpcbind-log :trace "Short write"))))))))
nil)
(defun handle-rpcbind-callit (server arg)
(rpcbind-log :info "START CALLIT ~A:~A:~A~%" (callit-arg-program arg) (callit-arg-version arg) (callit-arg-proc arg))
(let ((mapping (car (find-if (lambda (m)
(let ((mp (car m)))
(when mp
(and (= (callit-arg-program arg) (mapping-program mp))
(= (callit-arg-version arg) (mapping-version mp))
(eq (mapping-protocol mp) :udp)))))
*mappings*)))
(pfd (find-if (lambda (p)
(typep p 'udp-pollfd))
(fsocket:poll-context-fds (simple-rpc-server-pc server)))))
(unless mapping
(rpcbind-log :info "No mapping found")
(rpc-discard-call))
(when pfd
(let ((blk (udp-pollfd-blk pfd))
(carg (destructuring-bind (buf start end) (callit-arg-args arg)
(list (subseq buf start end) 0 (- end start)))))
(drx:reset-xdr-block blk)
(let ((xid (encode-rpc-call blk
#'drx:encode-void
nil
(callit-arg-program arg)
(callit-arg-version arg)
(callit-arg-proc arg)
:xid (rpc-msg-xid (simple-rpc-server-msg server)))))
(dotimes (i (third carg))
(setf (aref (drx:xdr-block-buffer blk)
(+ (drx:xdr-block-offset blk) i))
(aref (first carg) i)))
(incf (drx:xdr-block-offset blk) (third carg))
(fsocket:socket-sendto (fsocket:pollfd-fd pfd)
(drx:xdr-block-buffer blk)
(fsocket:make-sockaddr-in :addr #(127 0 0 1)
:port (mapping-port mapping))
:start 0 :end (drx:xdr-block-offset blk))
(rpcbind-log :info "Awaiting reply for ~A" xid)
(simple-rpc-server-await-reply server xid #'process-callit-reply
:context (list (etypecase pfd
(udp-pollfd (udp-pollfd-addr pfd))
(tcp-pollfd (tcp-pollfd-addr pfd)))
xid
(simple-rpc-server-rpfd server)))))))
(rpc-discard-call))
(defconstant +rpcbind-program+ 100000)
(defconstant +rpcbind-version+ 2)
(define-rpc-server rpcbind (+rpcbind-program+ +rpcbind-version+)
(null :void :void)
(set mapping :boolean)
(unset mapping :boolean)
(getport mapping :uint32)
(dump :void mapping-list-opt)
(callit callit-arg callit-res))
(defun process-heartbeat-reply (server blk arg)
(declare (ignore server blk))
(destructuring-bind (program version) arg
(rpcbind-log :info "Heartbeat reply ~A ~A" program version)
(let ((now (get-universal-time)))
(dolist (m *mappings*)
(when m
(destructuring-bind (mp last-seen next-heartbeat) m
(declare (ignore last-seen next-heartbeat))
(when (and (= (mapping-program mp) program)
(= (mapping-version mp) version))
(setf (second m) now
(third m) (when *heartbeat-age*
(+ now *heartbeat-age*))))))))))
(defun send-heartbeat (server fd blk mapping)
(drx:reset-xdr-block blk)
(rpcbind-log :info "Heartbeating ~A on port ~A" (mapping-program mapping) (mapping-port mapping))
(let ((xid (encode-rpc-call blk #'drx:encode-void nil
(mapping-program mapping)
(mapping-version mapping)
0)))
(fsocket:socket-sendto fd
(drx:xdr-block-buffer blk)
(fsocket:make-sockaddr-in :addr #(127 0 0 1)
:port (frpc2:mapping-port mapping))
:start 0 :end (drx:xdr-block-offset blk))
(simple-rpc-server-await-reply server xid
#'process-heartbeat-reply
:context (list (mapping-program mapping)
(mapping-version mapping)))))
(defvar *server* nil)
(defun run-rpcbind (server)
(do ((now (get-universal-time) (get-universal-time)))
((simple-rpc-server-exiting server))
(simple-rpc-server-process server)
(let ((pfd (find-if (lambda (p)
(typep p 'udp-pollfd))
(fsocket:poll-context-fds (simple-rpc-server-pc server)))))
(when pfd
(let ((blk (udp-pollfd-blk pfd)))
(dolist (m *mappings*)
(when m
(destructuring-bind (mapping last-seen next-heartbeat) m
(declare (ignore last-seen))
(when (and (eq (mapping-protocol mapping) :udp)
next-heartbeat
(> now next-heartbeat))
(send-heartbeat server (fsocket:pollfd-fd pfd)
blk mapping)
add 5 seconds to the next heartbeat age so we do n't spin if no reply received
(incf (third m) 5))))))))
(do ((mappings *mappings* (cdr mappings)))
((null mappings))
(let ((m (car mappings)))
(when m
(destructuring-bind (mapping last-seen next-heartbeat) m
(declare (ignore next-heartbeat))
(when (and *purge-age* (> now (+ last-seen *purge-age*)))
(rpcbind-log :info "Purging ~A" (mapping-program mapping))
(setf (car mappings) nil))))))))
(defun start-rpcbind (&key programs udp-ports tcp-ports providers)
"Start an RPC server which serves the rpcbind service.
PROGRAMS ::= a list of programs to serve in addition to the rpcbind program.
UDP-PORTS ::= a list of integers specifying UDP ports to listen on, in addition
to port 111.
TCP-PORTS ::= a list of integers specifying TCP ports to listen on, in addition
to port 111.
PROVIDERS ::= a list of authentication providers to use.
"
(unless *server*
(setf *server* (simple-rpc-server-construct (cons (make-rpcbind-program)
programs)
:providers providers
:udp-ports (cons 111 udp-ports)
:tcp-ports (cons 111 tcp-ports)))
(handle-rpcbind-set *server* (make-mapping :program 100000 :version 2 :protocol :udp :port 111))
(handle-rpcbind-set *server* (make-mapping :program 100000 :version 2 :protocol :tcp :port 111))
(simple-rpc-server-start *server*
#'run-rpcbind
"rpcbind-service-thread")))
(defun stop-rpcbind ()
"Stop the rpcbind service."
(when *server*
(simple-rpc-server-stop *server*)
(simple-rpc-server-destruct *server*)
(setf *server* nil)))
(defun register-program (program)
(unless *server* (error "RPCBIND server not running."))
(dolist (p (rpc-server-programs *server*))
(when (and (= (first p) (first program))
(= (second p) (second program)))
(setf (cddr p) (cddr program))
(return-from register-program nil)))
(push program (rpc-server-programs *server*))
(handle-rpcbind-set *server*
(make-mapping :program (first program)
:version (second program)
:port 111
:protocol :udp))
(handle-rpcbind-set *server*
(make-mapping :program (first program)
:version (second program)
:port 111
:protocol :tcp))
nil)
(defun unregister-program (program-id version-id)
(unless *server* (error "RPCBIND server not running."))
(setf (rpc-server-programs *server*)
(remove-if (lambda (p)
(and (= (first p) program-id)
(= (second p) version-id)))
(rpc-server-programs *server*)))
nil)
|
0e7c10b9c7f474a6f05f47ad0707f3a3d80a396b0eafc244ac0c234f77d30211
|
batsh-dev-team/Batsh
|
batsh_ast.ml
|
open Core_kernel
type identifier = string
and identifiers = identifier list
and leftvalue =
| Identifier of identifier
| ListAccess of (leftvalue * expression)
and expression =
| Bool of bool
| Float of float
| Int of int
| List of expressions
| String of string
| Leftvalue of leftvalue
| ArithUnary of (string * expression)
| ArithBinary of (string * expression * expression)
| Concat of (expression * expression)
| StrCompare of (string * expression * expression)
| Call of (identifier * expressions)
and expressions = expression list
and statement =
| Comment of string
| Block of statements
| Expression of expression
| Assignment of (leftvalue * expression)
| If of (expression * statement)
| IfElse of (expression * statement * statement)
| While of (expression * statement)
| Global of identifier
| Return of expression option
| Empty
and statements = statement list
and toplevel =
| Statement of statement
| Function of (identifier * identifiers * statements)
and t = toplevel list
[@@deriving sexp]
| null |
https://raw.githubusercontent.com/batsh-dev-team/Batsh/5c8ae421e0eea5dcb3da01643152ad96af941f07/lib/batsh_ast.ml
|
ocaml
|
open Core_kernel
type identifier = string
and identifiers = identifier list
and leftvalue =
| Identifier of identifier
| ListAccess of (leftvalue * expression)
and expression =
| Bool of bool
| Float of float
| Int of int
| List of expressions
| String of string
| Leftvalue of leftvalue
| ArithUnary of (string * expression)
| ArithBinary of (string * expression * expression)
| Concat of (expression * expression)
| StrCompare of (string * expression * expression)
| Call of (identifier * expressions)
and expressions = expression list
and statement =
| Comment of string
| Block of statements
| Expression of expression
| Assignment of (leftvalue * expression)
| If of (expression * statement)
| IfElse of (expression * statement * statement)
| While of (expression * statement)
| Global of identifier
| Return of expression option
| Empty
and statements = statement list
and toplevel =
| Statement of statement
| Function of (identifier * identifiers * statements)
and t = toplevel list
[@@deriving sexp]
|
|
f4f5e8d9528f62cf2cd69e95ca4b82a241e8e79a010bc0df20cd8111843bb4ff
|
AbstractMachinesLab/caramel
|
omd.mli
|
* A markdown parser in OCaml , with no extra dependencies .
This module represents this entire Markdown library written in
OCaml only .
Its main purpose is to allow you to use the Markdown library while
keeping you away from the other modules .
If you want to extend the Markdown parser , you can do it without
accessing any module of this library but this one , and by doing
so , you are free from having to maintain a fork of this library .
This module is supposed to be reentrant ,
if it 's not then please report the bug .
This module represents this entire Markdown library written in
OCaml only.
Its main purpose is to allow you to use the Markdown library while
keeping you away from the other modules.
If you want to extend the Markdown parser, you can do it without
accessing any module of this library but this one, and by doing
so, you are free from having to maintain a fork of this library.
N.B. This module is supposed to be reentrant,
if it's not then please report the bug. *)
(************************************************************************)
* { 2 Representation of Markdown documents }
type t = element list
* Representation of a Markdown document .
and ref_container =
(< add_ref: string -> string -> string -> unit ;
get_ref : string -> (string*string) option;
get_all : (string * (string * string)) list;
>)
* A element of a Markdown document .
and element = Omd_representation.element =
* Header of level 1
* Header of level 2
* Header of level 3
* Header of level 4
* Header of level 5
* Header of level 6
| Paragraph of t
* A paragraph ( must be enabled in { ! of_string } )
| Text of string (** Text. *)
| Emph of t (** Emphasis (italic) *)
| Bold of t (** Bold *)
| Ul of t list (** Unumbered list *)
| Ol of t list (** Ordered (i.e. numbered) list *)
| Ulp of t list
| Olp of t list
| Code of name * string
* [ Code(lang , code ) ] represent [ code ] within the text ( :
` code ` ) . The language [ lang ] can not be specified from ,
it can be from { ! of_string } though or when programatically
generating documents . Beware that the [ code ] is taken
verbatim from and may contain characters that must be
escaped for HTML .
`code`). The language [lang] cannot be specified from Markdown,
it can be from {!of_string} though or when programatically
generating Markdown documents. Beware that the [code] is taken
verbatim from Markdown and may contain characters that must be
escaped for HTML. *)
| Code_block of name * string
* [ Code_block(lang , code ) ] : a code clock ( e.g. indented by 4
spaces in the text ) . The first parameter [ lang ] is the language
if specified . Beware that the [ code ] is taken verbatim from
and may contain characters that must be escaped for
HTML .
spaces in the text). The first parameter [lang] is the language
if specified. Beware that the [code] is taken verbatim from
Markdown and may contain characters that must be escaped for
HTML. *)
| Br (** (Forced) line break *)
| Hr (** Horizontal rule *)
* Newline character . Newline characters that act
like delimiters ( e.g. for paragraphs ) are removed from the AST .
like delimiters (e.g. for paragraphs) are removed from the AST. *)
| Url of href * t * title
| Ref of ref_container * name * string * fallback
| Img_ref of ref_container * name * alt * fallback
| Html of name * (string * string option) list * t
| Html_block of name * (string * string option) list * t
| Html_comment of string
(** An HTML comment, including "<!--" and "-->". *)
| Raw of string
(** Raw: something that shall never be converted *)
| Raw_block of string
(** Raw_block: a block with contents that shall never be converted *)
| Blockquote of t (** Quoted block *)
| Img of alt * src * title
| X of (< (* extension of [element]. *)
name: string;
(* N.B. [to_html] means that htmlentities will not
be applied to its output. *)
to_html: ?indent:int -> (t -> string) -> t -> string option;
to_sexpr: (t -> string) -> t -> string option;
to_t: t -> t option >)
and fallback = < to_string : string ; to_t : t >
(** Fallback for references in case they refer to non-existant references *)
and name = string
(** Markdown reference name. *)
and alt = string
(** HTML img tag attribute. *)
and src = string
(** HTML attribute. *)
and href = string
(** HTML attribute. *)
and title = string
(** HTML attribute. *)
type code_stylist = lang:string -> string -> string
(** Function that takes a language name and some code and returns
that code with style. *)
(************************************************************************)
* { 2 Input and Output }
val of_string : ?extensions:Omd_representation.extensions ->
?default_lang: name ->
string -> t
* [ of_string s ] returns the representation of the string
[ s ] .
@param lang language for blocks of code where it was not
specified . Default : [ " " ] .
If you want to use a custom lexer or parser , use { ! Omd_lexer.lex }
and { ! Omd_parser.parse } .
[s].
@param lang language for blocks of code where it was not
specified. Default: [""].
If you want to use a custom lexer or parser, use {!Omd_lexer.lex}
and {!Omd_parser.parse}. *)
val of_bigarray : ?extensions:Omd_representation.extensions ->
?default_lang: name ->
Omd_lexer.bigstring -> t
(** As {!of_string}, but read input from a bigarray rather than from a
string. *)
val set_default_lang : name -> t -> t
(** [set_default_lang lang md] return a copy of [md] where the
language of all [Code] or [Code_block] with an empty language is
set to [lang]. *)
val to_html :
?override:(Omd_representation.element -> string option) ->
?pindent:bool -> ?nl2br:bool -> ?cs:code_stylist -> t -> string
(** Translate markdown representation into raw HTML. If you need a
full HTML representation, you mainly have to figure out how to
convert [Html of string] and [Html_block of string]
into your HTML representation. *)
val to_markdown : t -> string
(** Translate markdown representation into textual markdown. *)
val to_text : t -> string
(** Translate markdown representation into raw text. *)
(************************************************************************)
* { 2 documents }
val toc : ?start:int list -> ?depth:int -> t -> t
* [ toc md ] returns [ toc ] a table of contents for [ md ] .
@param start gives the section for which the TOC must be built .
For example [ ~start:[2;3 ] ] will build the TOC for subsections of
the second [ H1 ] header , and within that section , the third [ h2 ]
header . If a number is [ 0 ] , it means to look for the first
section at that level but stop if one encounters any other
subsection . If no subsection exists , an empty TOC [ [ ] ] will be
returned . Default : [ [ ] ] i.e. list all sections , starting with the
first [ H1 ] .
@param depth the table of contents . Default : [ 2 ] .
@param start gives the section for which the TOC must be built.
For example [~start:[2;3]] will build the TOC for subsections of
the second [H1] header, and within that section, the third [h2]
header. If a number is [0], it means to look for the first
section at that level but stop if one encounters any other
subsection. If no subsection exists, an empty TOC [[]] will be
returned. Default: [[]] i.e. list all sections, starting with the
first [H1].
@param depth the table of contents. Default: [2]. *)
;;
| null |
https://raw.githubusercontent.com/AbstractMachinesLab/caramel/7d4e505d6032e22a630d2e3bd7085b77d0efbb0c/vendor/ocaml-lsp-1.4.0/ocaml-lsp-server/vendor/omd/src/omd.mli
|
ocaml
|
**********************************************************************
* Text.
* Emphasis (italic)
* Bold
* Unumbered list
* Ordered (i.e. numbered) list
* (Forced) line break
* Horizontal rule
* An HTML comment, including "<!--" and "-->".
* Raw: something that shall never be converted
* Raw_block: a block with contents that shall never be converted
* Quoted block
extension of [element].
N.B. [to_html] means that htmlentities will not
be applied to its output.
* Fallback for references in case they refer to non-existant references
* Markdown reference name.
* HTML img tag attribute.
* HTML attribute.
* HTML attribute.
* HTML attribute.
* Function that takes a language name and some code and returns
that code with style.
**********************************************************************
* As {!of_string}, but read input from a bigarray rather than from a
string.
* [set_default_lang lang md] return a copy of [md] where the
language of all [Code] or [Code_block] with an empty language is
set to [lang].
* Translate markdown representation into raw HTML. If you need a
full HTML representation, you mainly have to figure out how to
convert [Html of string] and [Html_block of string]
into your HTML representation.
* Translate markdown representation into textual markdown.
* Translate markdown representation into raw text.
**********************************************************************
|
* A markdown parser in OCaml , with no extra dependencies .
This module represents this entire Markdown library written in
OCaml only .
Its main purpose is to allow you to use the Markdown library while
keeping you away from the other modules .
If you want to extend the Markdown parser , you can do it without
accessing any module of this library but this one , and by doing
so , you are free from having to maintain a fork of this library .
This module is supposed to be reentrant ,
if it 's not then please report the bug .
This module represents this entire Markdown library written in
OCaml only.
Its main purpose is to allow you to use the Markdown library while
keeping you away from the other modules.
If you want to extend the Markdown parser, you can do it without
accessing any module of this library but this one, and by doing
so, you are free from having to maintain a fork of this library.
N.B. This module is supposed to be reentrant,
if it's not then please report the bug. *)
* { 2 Representation of Markdown documents }
type t = element list
* Representation of a Markdown document .
and ref_container =
(< add_ref: string -> string -> string -> unit ;
get_ref : string -> (string*string) option;
get_all : (string * (string * string)) list;
>)
* A element of a Markdown document .
and element = Omd_representation.element =
* Header of level 1
* Header of level 2
* Header of level 3
* Header of level 4
* Header of level 5
* Header of level 6
| Paragraph of t
* A paragraph ( must be enabled in { ! of_string } )
| Ulp of t list
| Olp of t list
| Code of name * string
* [ Code(lang , code ) ] represent [ code ] within the text ( :
` code ` ) . The language [ lang ] can not be specified from ,
it can be from { ! of_string } though or when programatically
generating documents . Beware that the [ code ] is taken
verbatim from and may contain characters that must be
escaped for HTML .
`code`). The language [lang] cannot be specified from Markdown,
it can be from {!of_string} though or when programatically
generating Markdown documents. Beware that the [code] is taken
verbatim from Markdown and may contain characters that must be
escaped for HTML. *)
| Code_block of name * string
* [ Code_block(lang , code ) ] : a code clock ( e.g. indented by 4
spaces in the text ) . The first parameter [ lang ] is the language
if specified . Beware that the [ code ] is taken verbatim from
and may contain characters that must be escaped for
HTML .
spaces in the text). The first parameter [lang] is the language
if specified. Beware that the [code] is taken verbatim from
Markdown and may contain characters that must be escaped for
HTML. *)
* Newline character . Newline characters that act
like delimiters ( e.g. for paragraphs ) are removed from the AST .
like delimiters (e.g. for paragraphs) are removed from the AST. *)
| Url of href * t * title
| Ref of ref_container * name * string * fallback
| Img_ref of ref_container * name * alt * fallback
| Html of name * (string * string option) list * t
| Html_block of name * (string * string option) list * t
| Html_comment of string
| Raw of string
| Raw_block of string
| Img of alt * src * title
name: string;
to_html: ?indent:int -> (t -> string) -> t -> string option;
to_sexpr: (t -> string) -> t -> string option;
to_t: t -> t option >)
and fallback = < to_string : string ; to_t : t >
and name = string
and alt = string
and src = string
and href = string
and title = string
type code_stylist = lang:string -> string -> string
* { 2 Input and Output }
val of_string : ?extensions:Omd_representation.extensions ->
?default_lang: name ->
string -> t
* [ of_string s ] returns the representation of the string
[ s ] .
@param lang language for blocks of code where it was not
specified . Default : [ " " ] .
If you want to use a custom lexer or parser , use { ! Omd_lexer.lex }
and { ! Omd_parser.parse } .
[s].
@param lang language for blocks of code where it was not
specified. Default: [""].
If you want to use a custom lexer or parser, use {!Omd_lexer.lex}
and {!Omd_parser.parse}. *)
val of_bigarray : ?extensions:Omd_representation.extensions ->
?default_lang: name ->
Omd_lexer.bigstring -> t
val set_default_lang : name -> t -> t
val to_html :
?override:(Omd_representation.element -> string option) ->
?pindent:bool -> ?nl2br:bool -> ?cs:code_stylist -> t -> string
val to_markdown : t -> string
val to_text : t -> string
* { 2 documents }
val toc : ?start:int list -> ?depth:int -> t -> t
* [ toc md ] returns [ toc ] a table of contents for [ md ] .
@param start gives the section for which the TOC must be built .
For example [ ~start:[2;3 ] ] will build the TOC for subsections of
the second [ H1 ] header , and within that section , the third [ h2 ]
header . If a number is [ 0 ] , it means to look for the first
section at that level but stop if one encounters any other
subsection . If no subsection exists , an empty TOC [ [ ] ] will be
returned . Default : [ [ ] ] i.e. list all sections , starting with the
first [ H1 ] .
@param depth the table of contents . Default : [ 2 ] .
@param start gives the section for which the TOC must be built.
For example [~start:[2;3]] will build the TOC for subsections of
the second [H1] header, and within that section, the third [h2]
header. If a number is [0], it means to look for the first
section at that level but stop if one encounters any other
subsection. If no subsection exists, an empty TOC [[]] will be
returned. Default: [[]] i.e. list all sections, starting with the
first [H1].
@param depth the table of contents. Default: [2]. *)
;;
|
f47c863c0091d5528c483a63b67e50b75f1656da519382e3edf0d56f0b97b130
|
spectrum-finance/cardano-dex-backend
|
Serialization.hs
|
module Spectrum.Common.Persistence.Serialization
( serialize
, deserializeM
) where
import RIO
( ByteString, MonadThrow(..) )
import qualified Data.ByteString.Lazy as LBS
import Data.Aeson
( ToJSON, encode, FromJSON, decode )
import Spectrum.Common.Persistence.Exception
( StorageDeserializationFailed(StorageDeserializationFailed) )
serialize :: ToJSON a => a -> ByteString
serialize = LBS.toStrict . encode
deserializeM :: (MonadThrow m, FromJSON a) => ByteString -> m a
deserializeM =
maybe
(throwM $ StorageDeserializationFailed "Cannot parse data from ledger storage")
pure . decode . LBS.fromStrict
| null |
https://raw.githubusercontent.com/spectrum-finance/cardano-dex-backend/47528f6a43124ab4f6849521d61dbb3fad476c19/amm-executor/src/Spectrum/Common/Persistence/Serialization.hs
|
haskell
|
module Spectrum.Common.Persistence.Serialization
( serialize
, deserializeM
) where
import RIO
( ByteString, MonadThrow(..) )
import qualified Data.ByteString.Lazy as LBS
import Data.Aeson
( ToJSON, encode, FromJSON, decode )
import Spectrum.Common.Persistence.Exception
( StorageDeserializationFailed(StorageDeserializationFailed) )
serialize :: ToJSON a => a -> ByteString
serialize = LBS.toStrict . encode
deserializeM :: (MonadThrow m, FromJSON a) => ByteString -> m a
deserializeM =
maybe
(throwM $ StorageDeserializationFailed "Cannot parse data from ledger storage")
pure . decode . LBS.fromStrict
|
|
4aff4da490074fcbb1491ff28f5911e1780e249b175a29b14b23ae912e9777e2
|
huangjs/cl
|
defpackage.lisp
|
;;; defpackage.lisp -- DEFPACKAGE forms for the cl-bench modules
;;
Time - stamp : < 2004 - 01 - 01 emarsden >
(defpackage :cl-bench
(:use :common-lisp
#+cmu :ext
#+clisp :ext
#+allegro :excl))
(defpackage :cl-bench.gabriel
(:use :common-lisp)
(:export #:boyer
#:browse
#:dderiv-run
#:deriv-run
#:run-destructive
#:run-div2-test1
#:run-div2-test2
#:div2-l
#:run-fft
#:run-frpoly/fixnum
#:run-frpoly/bignum
#:run-frpoly/float
#:run-puzzle
#:run-tak
#:run-ctak
#:run-trtak
#:run-takl
#:run-stak
#:fprint/pretty
#:fprint/ugly
#:run-traverse
#:run-triangle))
(defpackage :cl-bench.math
(:use :common-lisp)
(:export #:run-factorial
#:run-fib
#:run-fib-ratio
#:run-ackermann
#:run-mandelbrot/complex
#:run-mandelbrot/dfloat
#:run-mrg32k3a))
(defpackage :cl-bench.crc
(:use :common-lisp)
(:export #:run-crc40))
(defpackage :cl-bench.bignum
(:use :common-lisp)
(:export #:run-elem-100-1000
#:run-elem-1000-100
#:run-elem-10000-1
#:run-pari-100-10
#:run-pari-200-5
#:run-pari-1000-1
#:run-pi-decimal/small
#:run-pi-decimal/big
#:run-pi-atan))
(defpackage :cl-bench.ratios
(:use :common-lisp)
(:export #:run-pi-ratios))
(defpackage :cl-bench.hash
(:use :common-lisp)
(:export #:run-slurp-lines
#:hash-strings
#:hash-integers))
(defpackage :cl-bench.boehm-gc
(:use :common-lisp)
(:export #:gc-benchmark))
(defpackage :cl-bench.deflate
(:use :common-lisp)
(:export #:run-deflate-file))
(defpackage :cl-bench.arrays
(:use :common-lisp)
(:export #:bench-1d-arrays
#:bench-2d-arrays
#:bench-3d-arrays
#:bench-bitvectors
#:bench-strings
#:bench-strings/adjustable
#:bench-string-concat
#:bench-search-sequence))
(defpackage :cl-bench.richards
(:use :common-lisp)
(:export #:richards))
(defpackage :cl-bench.clos
(:use :common-lisp)
(:export #:run-defclass
#:run-defmethod
#:make-instances
#:make-instances/simple
#:methodcalls/simple
#:methodcalls/simple+after
#:methodcalls/complex
#:run-eql-fib))
(defpackage :cl-bench.misc
(:use :common-lisp)
(:export #:run-compiler
#:run-fasload
#:run-permutations
#:walk-list/seq
#:walk-list/mess))
(defpackage :cl-ppcre-test
(:use :common-lisp)
(:export #:test))
EOF
| null |
https://raw.githubusercontent.com/huangjs/cl/96158b3f82f82a6b7d53ef04b3b29c5c8de2dbf7/lib/other-code/cl-bench/defpackage.lisp
|
lisp
|
defpackage.lisp -- DEFPACKAGE forms for the cl-bench modules
|
Time - stamp : < 2004 - 01 - 01 emarsden >
(defpackage :cl-bench
(:use :common-lisp
#+cmu :ext
#+clisp :ext
#+allegro :excl))
(defpackage :cl-bench.gabriel
(:use :common-lisp)
(:export #:boyer
#:browse
#:dderiv-run
#:deriv-run
#:run-destructive
#:run-div2-test1
#:run-div2-test2
#:div2-l
#:run-fft
#:run-frpoly/fixnum
#:run-frpoly/bignum
#:run-frpoly/float
#:run-puzzle
#:run-tak
#:run-ctak
#:run-trtak
#:run-takl
#:run-stak
#:fprint/pretty
#:fprint/ugly
#:run-traverse
#:run-triangle))
(defpackage :cl-bench.math
(:use :common-lisp)
(:export #:run-factorial
#:run-fib
#:run-fib-ratio
#:run-ackermann
#:run-mandelbrot/complex
#:run-mandelbrot/dfloat
#:run-mrg32k3a))
(defpackage :cl-bench.crc
(:use :common-lisp)
(:export #:run-crc40))
(defpackage :cl-bench.bignum
(:use :common-lisp)
(:export #:run-elem-100-1000
#:run-elem-1000-100
#:run-elem-10000-1
#:run-pari-100-10
#:run-pari-200-5
#:run-pari-1000-1
#:run-pi-decimal/small
#:run-pi-decimal/big
#:run-pi-atan))
(defpackage :cl-bench.ratios
(:use :common-lisp)
(:export #:run-pi-ratios))
(defpackage :cl-bench.hash
(:use :common-lisp)
(:export #:run-slurp-lines
#:hash-strings
#:hash-integers))
(defpackage :cl-bench.boehm-gc
(:use :common-lisp)
(:export #:gc-benchmark))
(defpackage :cl-bench.deflate
(:use :common-lisp)
(:export #:run-deflate-file))
(defpackage :cl-bench.arrays
(:use :common-lisp)
(:export #:bench-1d-arrays
#:bench-2d-arrays
#:bench-3d-arrays
#:bench-bitvectors
#:bench-strings
#:bench-strings/adjustable
#:bench-string-concat
#:bench-search-sequence))
(defpackage :cl-bench.richards
(:use :common-lisp)
(:export #:richards))
(defpackage :cl-bench.clos
(:use :common-lisp)
(:export #:run-defclass
#:run-defmethod
#:make-instances
#:make-instances/simple
#:methodcalls/simple
#:methodcalls/simple+after
#:methodcalls/complex
#:run-eql-fib))
(defpackage :cl-bench.misc
(:use :common-lisp)
(:export #:run-compiler
#:run-fasload
#:run-permutations
#:walk-list/seq
#:walk-list/mess))
(defpackage :cl-ppcre-test
(:use :common-lisp)
(:export #:test))
EOF
|
babd49e1a76390e2fef6ad13d32b39a7dcd6d44b24c9b22bdf56bea330beee8e
|
racket/handin
|
info.rkt
|
#lang setup/infotab
(define collection 'multi)
(define deps '("base"
"compatibility-lib"
"drracket"
"drracket-plugin-lib"
"gui-lib"
"htdp-lib"
"net-lib"
"pconvert-lib"
["sandbox-lib" #:version "1.2"]
"rackunit-lib"
"web-server-lib"))
(define build-deps '("gui-doc"
"racket-doc"
"scribble-lib"))
| null |
https://raw.githubusercontent.com/racket/handin/08fdb0426b75c1200e696f851864b8b524a7c41d/info.rkt
|
racket
|
#lang setup/infotab
(define collection 'multi)
(define deps '("base"
"compatibility-lib"
"drracket"
"drracket-plugin-lib"
"gui-lib"
"htdp-lib"
"net-lib"
"pconvert-lib"
["sandbox-lib" #:version "1.2"]
"rackunit-lib"
"web-server-lib"))
(define build-deps '("gui-doc"
"racket-doc"
"scribble-lib"))
|
|
45534f99c22cb135609da0bf46744324e5e698c185efe5a1e3edd6c33ef7150e
|
scalaris-team/scalaris
|
mathlib_SUITE.erl
|
2012 Zuse Institute Berlin
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
% you may not use this file except in compliance with the License.
% You may obtain a copy of the License at
%
% -2.0
%
% Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an " AS IS " BASIS ,
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
% See the License for the specific language governing permissions and
% limitations under the License.
@author < >
@doc Test suite for the mathlib module .
%% @end
%% @version $Id$
-module(mathlib_SUITE).
-author('').
-vsn('$Id$').
-compile(export_all).
-include("unittest.hrl").
-include("scalaris.hrl").
all() -> [
euclidian_distance
, nearest_centroid
, closest_points
, agglomerative_clustering
].
suite() ->
[
{timetrap, {seconds, 30}}
].
init_per_suite(Config) ->
Config.
end_per_suite(_Config) ->
ok.
%% helper functions
-spec in(X::any(), List::[any()]) -> boolean().
in(X, List) ->
lists:foldl(fun(_, true) -> true;
(E, false) when E == X -> true;
(_, _) -> false
end, false, List)
.
% Test mathlib:euclideanDistance/2
euclidian_distance(_Config) ->
{U1, V1, V2, V3, V4} = {
[0.0,0.0],
[0, 1.0],
[1.0, 0],
[1.0, 1.0],
[-1.0,-1.0]
},
?equals(mathlib:euclideanDistance(U1, U1), 0.0),
?equals(mathlib:euclideanDistance(U1, V1), 1.0),
?equals(mathlib:euclideanDistance(U1, V2), 1.0),
?equals(mathlib:euclideanDistance(U1, V3), math:sqrt(2)),
?equals(mathlib:euclideanDistance(U1, V4), math:sqrt(2)),
ok.
% Test mathlib:nearestCentroid/2
%
% Testcases:
% - Centroids empty (problemcase)
% - Centroids non-empty and items are unique, U not contained (good case)
% - Centroids contains U again (problemcase)
- Centroids non - empty , not unique , does n't contain U ( should be ok )
% - Centroids non-empty, not unique, contains U
nearest_centroid(_Config) ->
Note : The relative size will be ignored in this unittest , so we set it to zero
U = dc_centroids:new([0.0, 0.0], 0.0),
%% ----- Good cases which should work ------
List of Centroids is not empty . U is not an element and only one
% element in the list is nearest to U
C1 = [C1Nearest1, C1Nearest2 | _] = [dc_centroids:new([float(X), float(X)], 0.0)
|| X <- lists:seq(1,5)],
?equals(mathlib:nearestCentroid(U, C1), {math:sqrt(2), C1Nearest1}),
?equals(mathlib:nearestCentroid(U, tl(C1)), {math:sqrt(8), C1Nearest2}),
List not empty , U is an element , only one nearest element
C2 = [U|C1],
?equals(mathlib:nearestCentroid(U, C2), {math:sqrt(2), C1Nearest1}),
C3 = C1 ++ [U],
?equals(mathlib:nearestCentroid(U, C3), {math:sqrt(2), C1Nearest1}),
%% List contains the same entry multiple times
C4 = C1 ++ C1 ++ C1,
?equals(mathlib:nearestCentroid(U, C4), {math:sqrt(2), C1Nearest1}),
%% Order of the list should not be important
RC4 = lists:reverse(C4),
?equals(mathlib:nearestCentroid(U, RC4), {math:sqrt(2), C1Nearest1}),
%%
%% ----- Cases that should behave well ------
% empty centroids: return 'none'
?equals(mathlib:nearestCentroid(U, []), none),
% ambiguous centroids: return a node from a set of nodes
Ambiguous1 = [dc_centroids:new([float(X), float(Y)], 0.0)
|| X <- lists:seq(1,5), Y <- lists:seq(1,5)],
{AmbiguousDistance1, Element} = mathlib:nearestCentroid(U, Ambiguous1),
?equals(AmbiguousDistance1, math:sqrt(2)),
AllowedElements1 = [dc_centroids:new([X, Y], 0.0) || {X, Y} <- [
{1.0,1.0},{1.0,-1.0},{-1.0,1.0},{-1.0,-1.0}
]],
?assert_w_note(in(Element, AllowedElements1),
"Nearest element not in list of allowed coordinates"),
% regression test
U2 = dc_centroids:new([0.0, 0.0], 1.0),
V2 = dc_centroids:new([1.0, 1.0], 1.0),
FarAway = dc_centroids:new([100.0, 100.0], 1.0),
?equals(mathlib:nearestCentroid(U2, [V2, FarAway]), {dc_centroids:distance(U2, V2),
V2}),
?equals(mathlib:nearestCentroid(U2, [FarAway, V2]), {dc_centroids:distance(U2, V2),
V2}),
ok.
% Test mathlib:closestPoints/1
%
% Testcases:
% - Return none for an empty list of centroids
- Return none for a list containing only one centroid
- Return the two elements with the smallest distance
- When ambiguous , pick any two elements with a smallest distance
closest_points(_Config) ->
%% ----- Good cases which should work ------
C1 = [C1_1, C1_2 | _] = [dc_centroids:new([float(X), float(X)], 0.0)
|| X <- lists:seq(1,5)],
Dist1 = dc_centroids:distance(C1_1, C1_2),
?equals(mathlib:closestPoints(C1), {Dist1, C1_1, C1_2}),
%% ----- Cases that should behave well ------
% empty list
?equals(mathlib:closestPoints([]), none),
list with only one element
U = dc_centroids:new([0.0, 0.0], 0.0),
?equals(mathlib:closestPoints([U]), none),
% ambiguous list
C2 = [C2_1, C2_2 | _] = [dc_centroids:new([float(X), float(Y)], 0.0)
|| X <- lists:seq(1,5),
Y <- lists:seq(1,5)],
Dist2 = dc_centroids:distance(C2_1, C2_2),
?equals(mathlib:closestPoints(C2), {Dist2, C2_1, C2_2}),
% shuffled ambiguous list
C3 = util:shuffle(C2),
{Dist3, _A, _B} = mathlib:closestPoints(C3),
?equals(Dist3, 1.0),
% regression test
U2 = dc_centroids:new([0.0, 0.0], 1.0),
V2 = dc_centroids:new([1.0, 1.0], 1.0),
FarAway = dc_centroids:new([100.0, 100.0], 1.0),
?equals(mathlib:closestPoints([U2, V2, FarAway]),
{dc_centroids:distance(U2,V2), U2, V2}),
?equals(mathlib:closestPoints([U2, FarAway, V2]),
{dc_centroids:distance(U2,V2), U2, V2}),
ok.
% Test mathlib:aggloClustering/1
%
% Testcases:
- Clustering should fail with error when Radius < 0
% - Clustering an empty list should return an empty list
- Clustering of one centroid should return the same centroid
- Clustering two centroids with a distance less / equal Radius should return a merged centroid
- Clustering two centroids with a distance > Radius should return both centroids
% - Clustering a set of centroids should return the correct set of merged centroids
% - The sum of the relative size over all centroids should remain the same
% - XXX What should it do if elements/coordinates are duplicated?
agglomerative_clustering(_Config) ->
% crash when radius < 0
?expect_exception(mathlib:aggloClustering([], -1), error, function_clause),
% empty centroid list
?equals(mathlib:aggloClustering([], 0), []),
% single node
U = dc_centroids:new([0.0, 0.0], 1.0),
?equals(mathlib:aggloClustering([U], 0), [U]),
merge two nodes
V = dc_centroids:new([1.0, 1.0], 1.0),
MergedUV = dc_centroids:new([0.5, 0.5], 2.0),
?equals(mathlib:aggloClustering([U,V], 2), [MergedUV]),
?equals(mathlib:aggloClustering([V,U], 2), [MergedUV]),
% don't merge far-away nodes
FarAway = dc_centroids:new([100.0, 100.0], 1.0),
?equals(mathlib:aggloClustering([V, FarAway], 50), [V, FarAway]),
?equals(mathlib:aggloClustering([V, U, FarAway], 99), [MergedUV, FarAway]),
?equals(mathlib:aggloClustering([V, FarAway, U], 99), [MergedUV, FarAway]),
% merge many nodes, relative size sum should remain the same
C = [dc_centroids:new([float(X), float(X)], 1/6) || X <- lists:seq(1,6)],
?equals(mathlib:aggloClustering(C, 7), [dc_centroids:new([3.5, 3.5], 1.0)]),
ok.
| null |
https://raw.githubusercontent.com/scalaris-team/scalaris/feb894d54e642bb3530e709e730156b0ecc1635f/test/mathlib_SUITE.erl
|
erlang
|
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
@end
@version $Id$
helper functions
Test mathlib:euclideanDistance/2
Test mathlib:nearestCentroid/2
Testcases:
- Centroids empty (problemcase)
- Centroids non-empty and items are unique, U not contained (good case)
- Centroids contains U again (problemcase)
- Centroids non-empty, not unique, contains U
----- Good cases which should work ------
element in the list is nearest to U
List contains the same entry multiple times
Order of the list should not be important
----- Cases that should behave well ------
empty centroids: return 'none'
ambiguous centroids: return a node from a set of nodes
regression test
Test mathlib:closestPoints/1
Testcases:
- Return none for an empty list of centroids
----- Good cases which should work ------
----- Cases that should behave well ------
empty list
ambiguous list
shuffled ambiguous list
regression test
Test mathlib:aggloClustering/1
Testcases:
- Clustering an empty list should return an empty list
- Clustering a set of centroids should return the correct set of merged centroids
- The sum of the relative size over all centroids should remain the same
- XXX What should it do if elements/coordinates are duplicated?
crash when radius < 0
empty centroid list
single node
don't merge far-away nodes
merge many nodes, relative size sum should remain the same
|
2012 Zuse Institute Berlin
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
distributed under the License is distributed on an " AS IS " BASIS ,
@author < >
@doc Test suite for the mathlib module .
-module(mathlib_SUITE).
-author('').
-vsn('$Id$').
-compile(export_all).
-include("unittest.hrl").
-include("scalaris.hrl").
all() -> [
euclidian_distance
, nearest_centroid
, closest_points
, agglomerative_clustering
].
suite() ->
[
{timetrap, {seconds, 30}}
].
init_per_suite(Config) ->
Config.
end_per_suite(_Config) ->
ok.
-spec in(X::any(), List::[any()]) -> boolean().
in(X, List) ->
lists:foldl(fun(_, true) -> true;
(E, false) when E == X -> true;
(_, _) -> false
end, false, List)
.
euclidian_distance(_Config) ->
{U1, V1, V2, V3, V4} = {
[0.0,0.0],
[0, 1.0],
[1.0, 0],
[1.0, 1.0],
[-1.0,-1.0]
},
?equals(mathlib:euclideanDistance(U1, U1), 0.0),
?equals(mathlib:euclideanDistance(U1, V1), 1.0),
?equals(mathlib:euclideanDistance(U1, V2), 1.0),
?equals(mathlib:euclideanDistance(U1, V3), math:sqrt(2)),
?equals(mathlib:euclideanDistance(U1, V4), math:sqrt(2)),
ok.
- Centroids non - empty , not unique , does n't contain U ( should be ok )
nearest_centroid(_Config) ->
Note : The relative size will be ignored in this unittest , so we set it to zero
U = dc_centroids:new([0.0, 0.0], 0.0),
List of Centroids is not empty . U is not an element and only one
C1 = [C1Nearest1, C1Nearest2 | _] = [dc_centroids:new([float(X), float(X)], 0.0)
|| X <- lists:seq(1,5)],
?equals(mathlib:nearestCentroid(U, C1), {math:sqrt(2), C1Nearest1}),
?equals(mathlib:nearestCentroid(U, tl(C1)), {math:sqrt(8), C1Nearest2}),
List not empty , U is an element , only one nearest element
C2 = [U|C1],
?equals(mathlib:nearestCentroid(U, C2), {math:sqrt(2), C1Nearest1}),
C3 = C1 ++ [U],
?equals(mathlib:nearestCentroid(U, C3), {math:sqrt(2), C1Nearest1}),
C4 = C1 ++ C1 ++ C1,
?equals(mathlib:nearestCentroid(U, C4), {math:sqrt(2), C1Nearest1}),
RC4 = lists:reverse(C4),
?equals(mathlib:nearestCentroid(U, RC4), {math:sqrt(2), C1Nearest1}),
?equals(mathlib:nearestCentroid(U, []), none),
Ambiguous1 = [dc_centroids:new([float(X), float(Y)], 0.0)
|| X <- lists:seq(1,5), Y <- lists:seq(1,5)],
{AmbiguousDistance1, Element} = mathlib:nearestCentroid(U, Ambiguous1),
?equals(AmbiguousDistance1, math:sqrt(2)),
AllowedElements1 = [dc_centroids:new([X, Y], 0.0) || {X, Y} <- [
{1.0,1.0},{1.0,-1.0},{-1.0,1.0},{-1.0,-1.0}
]],
?assert_w_note(in(Element, AllowedElements1),
"Nearest element not in list of allowed coordinates"),
U2 = dc_centroids:new([0.0, 0.0], 1.0),
V2 = dc_centroids:new([1.0, 1.0], 1.0),
FarAway = dc_centroids:new([100.0, 100.0], 1.0),
?equals(mathlib:nearestCentroid(U2, [V2, FarAway]), {dc_centroids:distance(U2, V2),
V2}),
?equals(mathlib:nearestCentroid(U2, [FarAway, V2]), {dc_centroids:distance(U2, V2),
V2}),
ok.
- Return none for a list containing only one centroid
- Return the two elements with the smallest distance
- When ambiguous , pick any two elements with a smallest distance
closest_points(_Config) ->
C1 = [C1_1, C1_2 | _] = [dc_centroids:new([float(X), float(X)], 0.0)
|| X <- lists:seq(1,5)],
Dist1 = dc_centroids:distance(C1_1, C1_2),
?equals(mathlib:closestPoints(C1), {Dist1, C1_1, C1_2}),
?equals(mathlib:closestPoints([]), none),
list with only one element
U = dc_centroids:new([0.0, 0.0], 0.0),
?equals(mathlib:closestPoints([U]), none),
C2 = [C2_1, C2_2 | _] = [dc_centroids:new([float(X), float(Y)], 0.0)
|| X <- lists:seq(1,5),
Y <- lists:seq(1,5)],
Dist2 = dc_centroids:distance(C2_1, C2_2),
?equals(mathlib:closestPoints(C2), {Dist2, C2_1, C2_2}),
C3 = util:shuffle(C2),
{Dist3, _A, _B} = mathlib:closestPoints(C3),
?equals(Dist3, 1.0),
U2 = dc_centroids:new([0.0, 0.0], 1.0),
V2 = dc_centroids:new([1.0, 1.0], 1.0),
FarAway = dc_centroids:new([100.0, 100.0], 1.0),
?equals(mathlib:closestPoints([U2, V2, FarAway]),
{dc_centroids:distance(U2,V2), U2, V2}),
?equals(mathlib:closestPoints([U2, FarAway, V2]),
{dc_centroids:distance(U2,V2), U2, V2}),
ok.
- Clustering should fail with error when Radius < 0
- Clustering of one centroid should return the same centroid
- Clustering two centroids with a distance less / equal Radius should return a merged centroid
- Clustering two centroids with a distance > Radius should return both centroids
agglomerative_clustering(_Config) ->
?expect_exception(mathlib:aggloClustering([], -1), error, function_clause),
?equals(mathlib:aggloClustering([], 0), []),
U = dc_centroids:new([0.0, 0.0], 1.0),
?equals(mathlib:aggloClustering([U], 0), [U]),
merge two nodes
V = dc_centroids:new([1.0, 1.0], 1.0),
MergedUV = dc_centroids:new([0.5, 0.5], 2.0),
?equals(mathlib:aggloClustering([U,V], 2), [MergedUV]),
?equals(mathlib:aggloClustering([V,U], 2), [MergedUV]),
FarAway = dc_centroids:new([100.0, 100.0], 1.0),
?equals(mathlib:aggloClustering([V, FarAway], 50), [V, FarAway]),
?equals(mathlib:aggloClustering([V, U, FarAway], 99), [MergedUV, FarAway]),
?equals(mathlib:aggloClustering([V, FarAway, U], 99), [MergedUV, FarAway]),
C = [dc_centroids:new([float(X), float(X)], 1/6) || X <- lists:seq(1,6)],
?equals(mathlib:aggloClustering(C, 7), [dc_centroids:new([3.5, 3.5], 1.0)]),
ok.
|
9f2df23a0b1ff65567edfe8e56caeef38b0c8e8dea7f2aee81cfaa18b30da75e
|
garrigue/labltk
|
image.ml
|
##ifdef CAMLTK
let cTKtoCAMLimage s =
let res = tkEval [|TkToken "image"; TkToken "type"; TkToken s|] in
match res with
| "bitmap" -> ImageBitmap (BitmapImage s)
| "photo" -> ImagePhoto (PhotoImage s)
| _ -> raise (TkError ("unknown image type \"" ^ res ^ "\""))
;;
let names () =
let res = tkEval [|TkToken "image"; TkToken "names"|] in
let names = splitlist res in
List.map cTKtoCAMLimage names
;;
##else
let cTKtoCAMLimage s =
let res = tkEval [|TkToken "image"; TkToken "type"; TkToken s|] in
match res with
| "bitmap" -> `Bitmap s
| "photo" -> `Photo s
| _ -> raise (TkError ("unknown image type \"" ^ res ^ "\""))
;;
let names () =
let res = tkEval [|TkToken "image"; TkToken "names"|] in
let names = splitlist res in
List.map ~f:cTKtoCAMLimage names
;;
##endif
| null |
https://raw.githubusercontent.com/garrigue/labltk/2cbb92a8c0feacdd8ee69976f3f45a7cf81f805c/builtin/image.ml
|
ocaml
|
##ifdef CAMLTK
let cTKtoCAMLimage s =
let res = tkEval [|TkToken "image"; TkToken "type"; TkToken s|] in
match res with
| "bitmap" -> ImageBitmap (BitmapImage s)
| "photo" -> ImagePhoto (PhotoImage s)
| _ -> raise (TkError ("unknown image type \"" ^ res ^ "\""))
;;
let names () =
let res = tkEval [|TkToken "image"; TkToken "names"|] in
let names = splitlist res in
List.map cTKtoCAMLimage names
;;
##else
let cTKtoCAMLimage s =
let res = tkEval [|TkToken "image"; TkToken "type"; TkToken s|] in
match res with
| "bitmap" -> `Bitmap s
| "photo" -> `Photo s
| _ -> raise (TkError ("unknown image type \"" ^ res ^ "\""))
;;
let names () =
let res = tkEval [|TkToken "image"; TkToken "names"|] in
let names = splitlist res in
List.map ~f:cTKtoCAMLimage names
;;
##endif
|
|
94c5098c8f5283cef00ddd6c26411bc7e71950f986103b80cfec21850b843f0a
|
huangjs/cl
|
parser.lisp
|
-*- Mode : LISP ; Syntax : COMMON - LISP ; Package : CL - PPCRE ; Base : 10 -*-
$ Header : /usr / local / cvsrep / cl - ppcre / parser.lisp , v 1.1.1.1 2002/12/20 10:10:44 edi Exp $
;;; The parser will - with the help of the lexer - parse a regex
;;; string and convert it into a "parse tree" (see docs for details
;;; about the syntax of these trees). Note that the lexer might return
;;; illegal parse trees. It is assumed that the conversion process
;;; later on will track them down.
Copyright ( c ) 2002 , Dr. . All rights reserved .
;;; Redistribution and use in source and binary forms, with or without
;;; modification, are permitted provided that the following conditions
;;; are met:
;;; * Redistributions of source code must retain the above copyright
;;; notice, this list of conditions and the following disclaimer.
;;; * Redistributions in binary form must reproduce the above
;;; copyright notice, this list of conditions and the following
;;; disclaimer in the documentation and/or other materials
;;; provided with the distribution.
;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED
;;; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
;;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
;;; ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL
;;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
;;; GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY ,
;;; WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
(in-package "CL-PPCRE")
(defmethod group ((lexer lexer))
(declare (optimize speed space)
(special extended-mode-p))
"Parses and consumes a <group>.
The productions are: <group> -> \"(\"<regex>\")\"
\"(?:\"<regex>\")\"
\"(?<\"<regex>\")\"
\"(?<flags>:\"<regex>\")\"
\"(?=\"<regex>\")\"
\"(?!\"<regex>\")\"
\"(?<=\"<regex>\")\"
\"(?<!\"<regex>\")\"
\"(?(\"<num>\")\"<regex>\")\"
\"(?(\"<regex>\")\"<regex>\")\"
<legal-token>
where <flags> is parsed by the lexer function MAYBE-PARSE-FLAGS.
Will return <parse-tree> or (<grouping-type> <parse-tree>) where
<grouping-type> is one of six keywords - see source for details."
;; make sure modifications of extended mode are discarded at closing
;; parenthesis
(multiple-value-bind (open-token flags)
(get-token lexer)
(cond ((eq open-token :open-paren-paren)
;; special case for conditional regular expressions; note
;; that at this point we accept a couple of illegal
;; combinations which'll be sorted out later by the
;; converter
(let* ((open-paren-pos (car (last-pos lexer)))
;; check if what follows "(?(" is a number
(number (try-number lexer :no-whitespace-p t))
;; make changes to extended-mode-p local
(extended-mode-p extended-mode-p))
(declare (special extended-mode-p))
(cond (number
;; condition is a number (i.e. refers to a
;; back-reference)
(let* ((inner-close-token (get-token lexer))
(regex (regex lexer))
(close-token (get-token lexer)))
(unless (eq inner-close-token :close-paren)
(error "Opening paren at position ~A has no matching closing paren"
(fix-pos (+ open-paren-pos 2))))
(unless (eq close-token :close-paren)
(error "Opening paren at position ~A has no matching closing paren"
(fix-pos open-paren-pos)))
(list :branch number regex)))
(t
;; condition must be a full regex (actually a
;; look-behind or look-ahead); and here comes a
;; terrible kludge: instead of being cleanly
;; separated from the lexer, the parser pushes
back the lexer by one position , thereby
;; landing in the middle of the 'token' "(?(" -
;; yuck!!
(decf (pos lexer))
(let* ((inner-regex (group lexer))
(regex (regex lexer))
(close-token (get-token lexer)))
(unless (eq close-token :close-paren)
(error "Opening paren at position ~A has no matching closing paren"
(fix-pos open-paren-pos)))
(list :branch inner-regex regex))))))
((member open-token '(:open-paren
:open-paren-colon
:open-paren-greater
:open-paren-equal
:open-paren-exclamation
:open-paren-less-equal
:open-paren-less-exclamation)
:test #'eq)
;; make changes to extended-mode-p local
(let ((extended-mode-p extended-mode-p))
(declare (special extended-mode-p))
we saw one of the six token representing opening
;; parentheses
(let* ((open-paren-pos (car (last-pos lexer)))
(regex (regex lexer))
(close-token (get-token lexer)))
(when (eq open-token :open-paren)
;; if this is the "("<regex>")" production we have to
;; increment the register counter of the lexer
(incf (reg lexer)))
(unless (eq close-token :close-paren)
;; the token following <regex> must be the closing
;; parenthesis or this is a syntax error
(error "Opening paren at position ~A has no matching closing paren"
(fix-pos open-paren-pos)))
(if flags
;; if the lexer has returned a list of flags this must
;; have been the "(?:"<regex>")" production
(cons :group (nconc flags (list regex)))
(list (case open-token
((:open-paren)
:register)
((:open-paren-colon)
:group)
((:open-paren-greater)
:standalone)
((:open-paren-equal)
:positive-lookahead)
((:open-paren-exclamation)
:negative-lookahead)
((:open-paren-less-equal)
:positive-lookbehind)
((:open-paren-less-exclamation)
:negative-lookbehind))
regex)))))
(t
;; this is the <legal-token> production; <legal-token> is
;; any token which passes START-OF-SUBEXPR-P (otherwise
parsing had already stopped in the SEQ method )
open-token))))
(defmethod greedy-quant ((lexer lexer))
(declare (optimize speed space))
"Parses and consumes a <greedy-quant>.
The productions are: <greedy-quant> -> <group> | <group><quantifier>
where <quantifier> is parsed by the lexer function GET-QUANTIFIER.
Will return <parse-tree> or (:GREEDY-REPETITION <min> <max> <parse-tree>)."
(let* ((group (group lexer))
(token (get-quantifier lexer)))
(if token
;; if GET-QUANTIFIER returned a non-NIL value it's the
two - element list ( < min > < max > )
(list :greedy-repetition (first token) (second token) group)
group)))
(defmethod quant ((lexer lexer))
(declare (optimize speed space))
"Parses and consumes a <quant>.
The productions are: <quant> -> <greedy-quant> | <greedy-quant>\"?\".
Will return the <parse-tree> returned by GREEDY-QUANT and optionally
change :GREEDY-REPETITION to :NON-GREEDY-REPETITION."
(let* ((greedy-quant (greedy-quant lexer))
(token (get-token lexer :test-only t)))
(when token
(if (eq token :question-mark)
(setf (car greedy-quant) :non-greedy-repetition)
(unget-token lexer)))
greedy-quant))
(defmethod seq ((lexer lexer))
(declare (optimize speed space))
"Parses and consumes a <seq>.
The productions are: <seq> -> <quant> | <quant><seq>.
Will return <parse-tree> or (:SEQUENCE <parse-tree> <parse-tree>)."
Note that we 're calling START - OF - SUBEXPR - P before we actually try
;; to parse a <seq> or <quant> in order to catch empty regular
;; expressions
(if (start-of-subexpr-p lexer)
(let ((quant (quant lexer)))
(if (start-of-subexpr-p lexer)
(list :sequence quant (seq lexer))
quant))
:void))
(defmethod regex ((lexer lexer))
(declare (optimize speed space))
"Parses and consumes a <regex>, a complete regular expression.
The productions are: <regex> -> <seq> | <seq>\"|\"<regex>.
Will return <parse-tree> or (:ALTERNATION <parse-tree> <parse-tree>)."
(let ((token (get-token lexer :test-only t)))
(cond ((not token)
;; if we didn't get any token we return :VOID which stands
;; for "empty regular expression"
:void)
((eq token :vertical-bar)
;; now check whether the expression started with a
;; vertical bar, i.e. <seq> - the left alternation - is
;; empty
(list :alternation :void (regex lexer)))
(t
otherwise un - read the token we just saw and parse a
;; <seq> plus the token following it
(unget-token lexer)
(let* ((seq (seq lexer))
(token (get-token lexer :test-only t)))
(cond ((not token)
;; no further token, just a <seq>
seq)
((eq token :vertical-bar)
;; if the token was a vertical bar, this is an
alternation and we have the second production
(list :alternation seq (regex lexer)))
(t
;; a token which is not a vertical bar - this is
;; either a syntax error or we're inside of a
;; group and the next token is a closing
parenthesis ; so we just un - read the token and
;; let another function take care of it
(unget-token lexer)
seq)))))))
(defun parse-string (str)
(declare (optimize speed space))
"Translate the regex string STR into a parse tree."
(let* ((lexer (make-instance 'lexer :str str))
(extended-mode-p nil)
(parse-tree (regex lexer)))
;; initialize the extended mode flag to NIL before starting the lexer
(declare (special extended-mode-p))
;; check whether we've consumed the whole regex string
(if (end-of-string-p lexer)
parse-tree
(error "Expected end of string at position ~A"
(fix-pos (pos lexer))))))
| null |
https://raw.githubusercontent.com/huangjs/cl/96158b3f82f82a6b7d53ef04b3b29c5c8de2dbf7/lib/other-code/cl-bench/files/cl-ppcre/parser.lisp
|
lisp
|
Syntax : COMMON - LISP ; Package : CL - PPCRE ; Base : 10 -*-
The parser will - with the help of the lexer - parse a regex
string and convert it into a "parse tree" (see docs for details
about the syntax of these trees). Note that the lexer might return
illegal parse trees. It is assumed that the conversion process
later on will track them down.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials
provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED
OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
make sure modifications of extended mode are discarded at closing
parenthesis
special case for conditional regular expressions; note
that at this point we accept a couple of illegal
combinations which'll be sorted out later by the
converter
check if what follows "(?(" is a number
make changes to extended-mode-p local
condition is a number (i.e. refers to a
back-reference)
condition must be a full regex (actually a
look-behind or look-ahead); and here comes a
terrible kludge: instead of being cleanly
separated from the lexer, the parser pushes
landing in the middle of the 'token' "(?(" -
yuck!!
make changes to extended-mode-p local
parentheses
if this is the "("<regex>")" production we have to
increment the register counter of the lexer
the token following <regex> must be the closing
parenthesis or this is a syntax error
if the lexer has returned a list of flags this must
have been the "(?:"<regex>")" production
this is the <legal-token> production; <legal-token> is
any token which passes START-OF-SUBEXPR-P (otherwise
if GET-QUANTIFIER returned a non-NIL value it's the
to parse a <seq> or <quant> in order to catch empty regular
expressions
if we didn't get any token we return :VOID which stands
for "empty regular expression"
now check whether the expression started with a
vertical bar, i.e. <seq> - the left alternation - is
empty
<seq> plus the token following it
no further token, just a <seq>
if the token was a vertical bar, this is an
a token which is not a vertical bar - this is
either a syntax error or we're inside of a
group and the next token is a closing
so we just un - read the token and
let another function take care of it
initialize the extended mode flag to NIL before starting the lexer
check whether we've consumed the whole regex string
|
$ Header : /usr / local / cvsrep / cl - ppcre / parser.lisp , v 1.1.1.1 2002/12/20 10:10:44 edi Exp $
Copyright ( c ) 2002 , Dr. . All rights reserved .
DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL
INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY ,
(in-package "CL-PPCRE")
(defmethod group ((lexer lexer))
(declare (optimize speed space)
(special extended-mode-p))
"Parses and consumes a <group>.
The productions are: <group> -> \"(\"<regex>\")\"
\"(?:\"<regex>\")\"
\"(?<\"<regex>\")\"
\"(?<flags>:\"<regex>\")\"
\"(?=\"<regex>\")\"
\"(?!\"<regex>\")\"
\"(?<=\"<regex>\")\"
\"(?<!\"<regex>\")\"
\"(?(\"<num>\")\"<regex>\")\"
\"(?(\"<regex>\")\"<regex>\")\"
<legal-token>
where <flags> is parsed by the lexer function MAYBE-PARSE-FLAGS.
Will return <parse-tree> or (<grouping-type> <parse-tree>) where
<grouping-type> is one of six keywords - see source for details."
(multiple-value-bind (open-token flags)
(get-token lexer)
(cond ((eq open-token :open-paren-paren)
(let* ((open-paren-pos (car (last-pos lexer)))
(number (try-number lexer :no-whitespace-p t))
(extended-mode-p extended-mode-p))
(declare (special extended-mode-p))
(cond (number
(let* ((inner-close-token (get-token lexer))
(regex (regex lexer))
(close-token (get-token lexer)))
(unless (eq inner-close-token :close-paren)
(error "Opening paren at position ~A has no matching closing paren"
(fix-pos (+ open-paren-pos 2))))
(unless (eq close-token :close-paren)
(error "Opening paren at position ~A has no matching closing paren"
(fix-pos open-paren-pos)))
(list :branch number regex)))
(t
back the lexer by one position , thereby
(decf (pos lexer))
(let* ((inner-regex (group lexer))
(regex (regex lexer))
(close-token (get-token lexer)))
(unless (eq close-token :close-paren)
(error "Opening paren at position ~A has no matching closing paren"
(fix-pos open-paren-pos)))
(list :branch inner-regex regex))))))
((member open-token '(:open-paren
:open-paren-colon
:open-paren-greater
:open-paren-equal
:open-paren-exclamation
:open-paren-less-equal
:open-paren-less-exclamation)
:test #'eq)
(let ((extended-mode-p extended-mode-p))
(declare (special extended-mode-p))
we saw one of the six token representing opening
(let* ((open-paren-pos (car (last-pos lexer)))
(regex (regex lexer))
(close-token (get-token lexer)))
(when (eq open-token :open-paren)
(incf (reg lexer)))
(unless (eq close-token :close-paren)
(error "Opening paren at position ~A has no matching closing paren"
(fix-pos open-paren-pos)))
(if flags
(cons :group (nconc flags (list regex)))
(list (case open-token
((:open-paren)
:register)
((:open-paren-colon)
:group)
((:open-paren-greater)
:standalone)
((:open-paren-equal)
:positive-lookahead)
((:open-paren-exclamation)
:negative-lookahead)
((:open-paren-less-equal)
:positive-lookbehind)
((:open-paren-less-exclamation)
:negative-lookbehind))
regex)))))
(t
parsing had already stopped in the SEQ method )
open-token))))
(defmethod greedy-quant ((lexer lexer))
(declare (optimize speed space))
"Parses and consumes a <greedy-quant>.
The productions are: <greedy-quant> -> <group> | <group><quantifier>
where <quantifier> is parsed by the lexer function GET-QUANTIFIER.
Will return <parse-tree> or (:GREEDY-REPETITION <min> <max> <parse-tree>)."
(let* ((group (group lexer))
(token (get-quantifier lexer)))
(if token
two - element list ( < min > < max > )
(list :greedy-repetition (first token) (second token) group)
group)))
(defmethod quant ((lexer lexer))
(declare (optimize speed space))
"Parses and consumes a <quant>.
The productions are: <quant> -> <greedy-quant> | <greedy-quant>\"?\".
Will return the <parse-tree> returned by GREEDY-QUANT and optionally
change :GREEDY-REPETITION to :NON-GREEDY-REPETITION."
(let* ((greedy-quant (greedy-quant lexer))
(token (get-token lexer :test-only t)))
(when token
(if (eq token :question-mark)
(setf (car greedy-quant) :non-greedy-repetition)
(unget-token lexer)))
greedy-quant))
(defmethod seq ((lexer lexer))
(declare (optimize speed space))
"Parses and consumes a <seq>.
The productions are: <seq> -> <quant> | <quant><seq>.
Will return <parse-tree> or (:SEQUENCE <parse-tree> <parse-tree>)."
Note that we 're calling START - OF - SUBEXPR - P before we actually try
(if (start-of-subexpr-p lexer)
(let ((quant (quant lexer)))
(if (start-of-subexpr-p lexer)
(list :sequence quant (seq lexer))
quant))
:void))
(defmethod regex ((lexer lexer))
(declare (optimize speed space))
"Parses and consumes a <regex>, a complete regular expression.
The productions are: <regex> -> <seq> | <seq>\"|\"<regex>.
Will return <parse-tree> or (:ALTERNATION <parse-tree> <parse-tree>)."
(let ((token (get-token lexer :test-only t)))
(cond ((not token)
:void)
((eq token :vertical-bar)
(list :alternation :void (regex lexer)))
(t
otherwise un - read the token we just saw and parse a
(unget-token lexer)
(let* ((seq (seq lexer))
(token (get-token lexer :test-only t)))
(cond ((not token)
seq)
((eq token :vertical-bar)
alternation and we have the second production
(list :alternation seq (regex lexer)))
(t
(unget-token lexer)
seq)))))))
(defun parse-string (str)
(declare (optimize speed space))
"Translate the regex string STR into a parse tree."
(let* ((lexer (make-instance 'lexer :str str))
(extended-mode-p nil)
(parse-tree (regex lexer)))
(declare (special extended-mode-p))
(if (end-of-string-p lexer)
parse-tree
(error "Expected end of string at position ~A"
(fix-pos (pos lexer))))))
|
9cb356c6ee1e8de8a16daab1a0cc2f9b600ab9925675a4efc062d2354e1008ef
|
BranchTaken/Hemlock
|
test_rev.ml
|
open! Basis.Rudiments
open! Basis
open List
let test () =
let lists = [
[];
[0L];
[0L; 1L];
[0L; 1L; 2L];
] in
iter lists ~f:(fun l ->
File.Fmt.stdout
|> Fmt.fmt "rev "
|> (pp Uns.pp) l
|> Fmt.fmt " -> "
|> (pp Uns.pp) (rev l)
|> Fmt.fmt "\n"
|> ignore
)
let _ = test ()
| null |
https://raw.githubusercontent.com/BranchTaken/Hemlock/f3604ceda4f75cf18b6ee2b1c2f3c5759ad495a5/bootstrap/test/basis/list/test_rev.ml
|
ocaml
|
open! Basis.Rudiments
open! Basis
open List
let test () =
let lists = [
[];
[0L];
[0L; 1L];
[0L; 1L; 2L];
] in
iter lists ~f:(fun l ->
File.Fmt.stdout
|> Fmt.fmt "rev "
|> (pp Uns.pp) l
|> Fmt.fmt " -> "
|> (pp Uns.pp) (rev l)
|> Fmt.fmt "\n"
|> ignore
)
let _ = test ()
|
|
aac01d961bac72b3ab3fa1a9226d530eb35baa2bb1dee380089f8db07457a850
|
GaoYusong/erlang-traffic-control
|
traffic_control_app.erl
|
-module(traffic_control_app).
-behaviour(application).
%% Application callbacks
-export([start/2, stop/1]).
%% ===================================================================
%% Application callbacks
%% ===================================================================
start(_StartType, _StartArgs) ->
traffic_control_sup:start_link().
stop(_State) ->
ok.
| null |
https://raw.githubusercontent.com/GaoYusong/erlang-traffic-control/002a1d637a368d58e65f9f81c79f4c7b6612388e/src/traffic_control_app.erl
|
erlang
|
Application callbacks
===================================================================
Application callbacks
===================================================================
|
-module(traffic_control_app).
-behaviour(application).
-export([start/2, stop/1]).
start(_StartType, _StartArgs) ->
traffic_control_sup:start_link().
stop(_State) ->
ok.
|
cec3712d7dd73b99bd30eeb4b9b5c8508a1de66f2a23d41acd886f21c861d82a
|
siriusdemon/Pearl
|
monads.rkt
|
#lang typed/racket/no-check
;#lang typed/racket
(provide (all-defined-out))
(struct (A) Just
([a : A])
#:transparent)
(struct Nothing
()
#:transparent)
(define-type (Maybe A)
(U (Just A)
Nothing))
(: bind-maybe (All (A B) (-> (Maybe A) (-> A (Maybe B)) (Maybe B))))
(define (bind-maybe ma f)
(match ma
[(Just a) (f a)]
[(Nothing) (Nothing)]))
(struct Unit
())
(struct (W A) Writer
([log : (Listof W)]
[a : A]))
(: run-writer (All (W A) (-> (Writer W A) (Pair (Listof W) A))))
(define (run-writer ma)
(match ma
[(Writer log a) (cons log a)]))
(: inj-writer (All (W A) (-> A (Writer W A))))
(define (inj-writer a)
(Writer '() a))
(: tell (All (W) (-> W (Writer W Unit))))
(define (tell msg)
(Writer (list msg) (Unit)))
(: bind-writer (All (W A B) (-> (Writer W A) (-> A (Writer W B)) (Writer W B))))
(define (bind-writer ma f)
(match ma
[(Writer la a) (match (run-writer (f a))
[(cons lb b) (Writer (append la lb) b)])]))
(: pass (All (W A) (-> (Writer W A) (-> (Listof W) (Listof W)) (Writer W A))))
(define (pass ma f)
(match ma
[(Writer la a) (Writer (f la) a)]))
(: listen (All (W A) (-> (Writer W A) (Writer W (Pair (Listof W) A)))))
(define (listen ma)
(match ma
[(Writer la a) (Writer la (cons la a))]))
(struct (Store A) State
([run-state : (-> Store (Pair Store A))]))
(: inj-state (All (S A) (-> A (State S A))))
(define (inj-state a)
(State (λ ([s : S]) (cons s a))))
(: run-state (All (S A) (-> (State S A) (-> S (Pair S A)))))
(define run-state State-run-state)
(: bind-state (All (S A B) (-> (State S A) (-> A (State S B)) (State S B))))
(define (bind-state ma f)
(State (λ ([s : S])
(match ((run-state ma) s)
[`(,s . ,a) ((run-state (f a)) s)]))))
(: get (All (S) (-> (State S S))))
(define (get)
(State (λ ([s : S])
(cons s s))))
(: put (All (S) (-> S (State S Unit))))
(define (put s)
(State (λ (_) (cons s (Unit)))))
(struct (R A) Cont
([run-k : (-> (-> A R) R)]))
(: run-k (All (R A) (-> (Cont R A) (-> (-> A R) R))))
(define run-k Cont-run-k)
(: inj-k (All (R A) (-> A (Cont R A))))
(define (inj-k a)
(Cont (λ ([k : (-> A R)]) (k a))))
(: bind-k (All (A B R) (-> (Cont R A) (-> A (Cont R B)) (Cont R B))))
(define (bind-k ma f)
(Cont (λ ([k : (-> B R)])
((run-k ma) (λ ([a : A]) ((run-k (f a)) k))))))
(: callcc (All (R A B) (-> (-> (-> A (Cont R B)) (Cont R A)) (Cont R A))))
(define (callcc f)
(Cont (λ ([k : (-> A R)])
((run-k (f (λ (a) (Cont (λ (_) (k a))))))
k))))
(: inj-list (All (A) (Listof A)))
(define (inj-list a)
`(,a))
(: empty-list (All (A) (Listof A)))
(define (empty-list)
'())
(: bind-list (All (A B) (→ (Listof A) (→ A (Listof B))
(Listof B))))
(define (bind-list ls f)
(append-map f ls))
(define bind
(λ (m f)
(cond
[(or (Just? m) (Nothing? m)) (bind-maybe m f)]
[(Writer? m) (bind-writer m f)]
[(State? m) (bind-state m f)]
[(Cont? m) (bind-k m f)]
[(list? m) (bind-list m f)]
[else (error "bind: ~a is not a monad" m)])))
#;
(define-syntax go-on
(syntax-rules (<-)
[(_ e) e]
[(_ (v₀ <- e₀) e ...)
(bind e₀ (λ (v₀) (go-on e ...)))]
[(_ e₀ e ...)
(bind e₀ (λ (_) (go-on e ...)))]))
(define-syntax go-on
(syntax-rules ()
[(_ () b) b]
[(_ ([v₀ e₀] pr ...) b)
(bind e₀ (λ (v₀) (go-on (pr ...) b)))]))
| null |
https://raw.githubusercontent.com/siriusdemon/Pearl/05f3c7a700809193b04acb795e846c58721f4872/material/monads.rkt
|
racket
|
#lang typed/racket
|
#lang typed/racket/no-check
(provide (all-defined-out))
(struct (A) Just
([a : A])
#:transparent)
(struct Nothing
()
#:transparent)
(define-type (Maybe A)
(U (Just A)
Nothing))
(: bind-maybe (All (A B) (-> (Maybe A) (-> A (Maybe B)) (Maybe B))))
(define (bind-maybe ma f)
(match ma
[(Just a) (f a)]
[(Nothing) (Nothing)]))
(struct Unit
())
(struct (W A) Writer
([log : (Listof W)]
[a : A]))
(: run-writer (All (W A) (-> (Writer W A) (Pair (Listof W) A))))
(define (run-writer ma)
(match ma
[(Writer log a) (cons log a)]))
(: inj-writer (All (W A) (-> A (Writer W A))))
(define (inj-writer a)
(Writer '() a))
(: tell (All (W) (-> W (Writer W Unit))))
(define (tell msg)
(Writer (list msg) (Unit)))
(: bind-writer (All (W A B) (-> (Writer W A) (-> A (Writer W B)) (Writer W B))))
(define (bind-writer ma f)
(match ma
[(Writer la a) (match (run-writer (f a))
[(cons lb b) (Writer (append la lb) b)])]))
(: pass (All (W A) (-> (Writer W A) (-> (Listof W) (Listof W)) (Writer W A))))
(define (pass ma f)
(match ma
[(Writer la a) (Writer (f la) a)]))
(: listen (All (W A) (-> (Writer W A) (Writer W (Pair (Listof W) A)))))
(define (listen ma)
(match ma
[(Writer la a) (Writer la (cons la a))]))
(struct (Store A) State
([run-state : (-> Store (Pair Store A))]))
(: inj-state (All (S A) (-> A (State S A))))
(define (inj-state a)
(State (λ ([s : S]) (cons s a))))
(: run-state (All (S A) (-> (State S A) (-> S (Pair S A)))))
(define run-state State-run-state)
(: bind-state (All (S A B) (-> (State S A) (-> A (State S B)) (State S B))))
(define (bind-state ma f)
(State (λ ([s : S])
(match ((run-state ma) s)
[`(,s . ,a) ((run-state (f a)) s)]))))
(: get (All (S) (-> (State S S))))
(define (get)
(State (λ ([s : S])
(cons s s))))
(: put (All (S) (-> S (State S Unit))))
(define (put s)
(State (λ (_) (cons s (Unit)))))
(struct (R A) Cont
([run-k : (-> (-> A R) R)]))
(: run-k (All (R A) (-> (Cont R A) (-> (-> A R) R))))
(define run-k Cont-run-k)
(: inj-k (All (R A) (-> A (Cont R A))))
(define (inj-k a)
(Cont (λ ([k : (-> A R)]) (k a))))
(: bind-k (All (A B R) (-> (Cont R A) (-> A (Cont R B)) (Cont R B))))
(define (bind-k ma f)
(Cont (λ ([k : (-> B R)])
((run-k ma) (λ ([a : A]) ((run-k (f a)) k))))))
(: callcc (All (R A B) (-> (-> (-> A (Cont R B)) (Cont R A)) (Cont R A))))
(define (callcc f)
(Cont (λ ([k : (-> A R)])
((run-k (f (λ (a) (Cont (λ (_) (k a))))))
k))))
(: inj-list (All (A) (Listof A)))
(define (inj-list a)
`(,a))
(: empty-list (All (A) (Listof A)))
(define (empty-list)
'())
(: bind-list (All (A B) (→ (Listof A) (→ A (Listof B))
(Listof B))))
(define (bind-list ls f)
(append-map f ls))
(define bind
(λ (m f)
(cond
[(or (Just? m) (Nothing? m)) (bind-maybe m f)]
[(Writer? m) (bind-writer m f)]
[(State? m) (bind-state m f)]
[(Cont? m) (bind-k m f)]
[(list? m) (bind-list m f)]
[else (error "bind: ~a is not a monad" m)])))
(define-syntax go-on
(syntax-rules (<-)
[(_ e) e]
[(_ (v₀ <- e₀) e ...)
(bind e₀ (λ (v₀) (go-on e ...)))]
[(_ e₀ e ...)
(bind e₀ (λ (_) (go-on e ...)))]))
(define-syntax go-on
(syntax-rules ()
[(_ () b) b]
[(_ ([v₀ e₀] pr ...) b)
(bind e₀ (λ (v₀) (go-on (pr ...) b)))]))
|
dc65cebbaa841f64702a00086f80de692c48dc28050426f0e23d099b42b7018a
|
alexandroid000/improv
|
SetPenRequest.hs
|
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE DeriveDataTypeable #-}
# LANGUAGE DeriveGeneric #
# LANGUAGE TemplateHaskell #
module Ros.Turtlesim.SetPenRequest where
import qualified Prelude as P
import Prelude ((.), (+), (*))
import qualified Data.Typeable as T
import Control.Applicative
import Ros.Internal.RosBinary
import Ros.Internal.Msg.MsgInfo
import qualified GHC.Generics as G
import qualified Data.Default.Generics as D
import Ros.Internal.Msg.SrvInfo
import qualified Data.Word as Word
import Foreign.Storable (Storable(..))
import qualified Ros.Internal.Util.StorableMonad as SM
import Lens.Family.TH (makeLenses)
import Lens.Family (view, set)
data SetPenRequest = SetPenRequest { _r :: Word.Word8
, _g :: Word.Word8
, _b :: Word.Word8
, _width :: Word.Word8
, _off :: Word.Word8
} deriving (P.Show, P.Eq, P.Ord, T.Typeable, G.Generic)
$(makeLenses ''SetPenRequest)
instance RosBinary SetPenRequest where
put obj' = put (_r obj') *> put (_g obj') *> put (_b obj') *> put (_width obj') *> put (_off obj')
get = SetPenRequest <$> get <*> get <*> get <*> get <*> get
instance Storable SetPenRequest where
sizeOf _ = sizeOf (P.undefined::Word.Word8) +
sizeOf (P.undefined::Word.Word8) +
sizeOf (P.undefined::Word.Word8) +
sizeOf (P.undefined::Word.Word8) +
sizeOf (P.undefined::Word.Word8)
alignment _ = 8
peek = SM.runStorable (SetPenRequest <$> SM.peek <*> SM.peek <*> SM.peek <*> SM.peek <*> SM.peek)
poke ptr' obj' = SM.runStorable store' ptr'
where store' = SM.poke (_r obj') *> SM.poke (_g obj') *> SM.poke (_b obj') *> SM.poke (_width obj') *> SM.poke (_off obj')
instance MsgInfo SetPenRequest where
sourceMD5 _ = "9f452acce566bf0c0954594f69a8e41b"
msgTypeName _ = "turtlesim/SetPenRequest"
instance D.Default SetPenRequest
instance SrvInfo SetPenRequest where
srvMD5 _ = "9f452acce566bf0c0954594f69a8e41b"
srvTypeName _ = "turtlesim/SetPen"
| null |
https://raw.githubusercontent.com/alexandroid000/improv/ef0f4a6a5f99a9c7ff3d25f50529417aba9f757c/roshask/msgs/Turtlesim/Ros/Turtlesim/SetPenRequest.hs
|
haskell
|
# LANGUAGE OverloadedStrings #
# LANGUAGE DeriveDataTypeable #
|
# LANGUAGE DeriveGeneric #
# LANGUAGE TemplateHaskell #
module Ros.Turtlesim.SetPenRequest where
import qualified Prelude as P
import Prelude ((.), (+), (*))
import qualified Data.Typeable as T
import Control.Applicative
import Ros.Internal.RosBinary
import Ros.Internal.Msg.MsgInfo
import qualified GHC.Generics as G
import qualified Data.Default.Generics as D
import Ros.Internal.Msg.SrvInfo
import qualified Data.Word as Word
import Foreign.Storable (Storable(..))
import qualified Ros.Internal.Util.StorableMonad as SM
import Lens.Family.TH (makeLenses)
import Lens.Family (view, set)
data SetPenRequest = SetPenRequest { _r :: Word.Word8
, _g :: Word.Word8
, _b :: Word.Word8
, _width :: Word.Word8
, _off :: Word.Word8
} deriving (P.Show, P.Eq, P.Ord, T.Typeable, G.Generic)
$(makeLenses ''SetPenRequest)
instance RosBinary SetPenRequest where
put obj' = put (_r obj') *> put (_g obj') *> put (_b obj') *> put (_width obj') *> put (_off obj')
get = SetPenRequest <$> get <*> get <*> get <*> get <*> get
instance Storable SetPenRequest where
sizeOf _ = sizeOf (P.undefined::Word.Word8) +
sizeOf (P.undefined::Word.Word8) +
sizeOf (P.undefined::Word.Word8) +
sizeOf (P.undefined::Word.Word8) +
sizeOf (P.undefined::Word.Word8)
alignment _ = 8
peek = SM.runStorable (SetPenRequest <$> SM.peek <*> SM.peek <*> SM.peek <*> SM.peek <*> SM.peek)
poke ptr' obj' = SM.runStorable store' ptr'
where store' = SM.poke (_r obj') *> SM.poke (_g obj') *> SM.poke (_b obj') *> SM.poke (_width obj') *> SM.poke (_off obj')
instance MsgInfo SetPenRequest where
sourceMD5 _ = "9f452acce566bf0c0954594f69a8e41b"
msgTypeName _ = "turtlesim/SetPenRequest"
instance D.Default SetPenRequest
instance SrvInfo SetPenRequest where
srvMD5 _ = "9f452acce566bf0c0954594f69a8e41b"
srvTypeName _ = "turtlesim/SetPen"
|
f79ff5cc1a5b08c87e475f243b49884edccc9eef9bb0fdd576d38908c00b4cdb
|
ghc/packages-base
|
Latin1.hs
|
# LANGUAGE Trustworthy #
# LANGUAGE NoImplicitPrelude
, BangPatterns
, NondecreasingIndentation
#
, BangPatterns
, NondecreasingIndentation
#-}
# OPTIONS_GHC -funbox - strict - fields #
-----------------------------------------------------------------------------
-- |
-- Module : GHC.IO.Encoding.Latin1
Copyright : ( c ) The University of Glasgow , 2009
-- License : see libraries/base/LICENSE
--
-- Maintainer :
-- Stability : internal
-- Portability : non-portable
--
UTF-32 Codecs for the IO library
--
Portions Copyright : ( c ) 2008 - 2009 ,
( c ) 2009 ,
( c ) 2009
--
-----------------------------------------------------------------------------
module GHC.IO.Encoding.Latin1 (
latin1, mkLatin1,
latin1_checked, mkLatin1_checked,
latin1_decode,
latin1_encode,
latin1_checked_encode,
) where
import GHC.Base
import GHC.Real
import GHC.Num
import GHC.IO
import GHC.IO.Buffer
import GHC.IO.Encoding.Failure
import GHC.IO.Encoding.Types
-- -----------------------------------------------------------------------------
Latin1
latin1 :: TextEncoding
latin1 = mkLatin1 ErrorOnCodingFailure
-- | /Since: 4.4.0.0/
mkLatin1 :: CodingFailureMode -> TextEncoding
mkLatin1 cfm = TextEncoding { textEncodingName = "ISO8859-1",
mkTextDecoder = latin1_DF cfm,
mkTextEncoder = latin1_EF cfm }
latin1_DF :: CodingFailureMode -> IO (TextDecoder ())
latin1_DF cfm =
return (BufferCodec {
encode = latin1_decode,
recover = recoverDecode cfm,
close = return (),
getState = return (),
setState = const $ return ()
})
latin1_EF :: CodingFailureMode -> IO (TextEncoder ())
latin1_EF cfm =
return (BufferCodec {
encode = latin1_encode,
recover = recoverEncode cfm,
close = return (),
getState = return (),
setState = const $ return ()
})
latin1_checked :: TextEncoding
latin1_checked = mkLatin1_checked ErrorOnCodingFailure
-- | /Since: 4.4.0.0/
mkLatin1_checked :: CodingFailureMode -> TextEncoding
mkLatin1_checked cfm = TextEncoding { textEncodingName = "ISO8859-1(checked)",
mkTextDecoder = latin1_DF cfm,
mkTextEncoder = latin1_checked_EF cfm }
latin1_checked_EF :: CodingFailureMode -> IO (TextEncoder ())
latin1_checked_EF cfm =
return (BufferCodec {
encode = latin1_checked_encode,
recover = recoverEncode cfm,
close = return (),
getState = return (),
setState = const $ return ()
})
latin1_decode :: DecodeBuffer
latin1_decode
input@Buffer{ bufRaw=iraw, bufL=ir0, bufR=iw, bufSize=_ }
output@Buffer{ bufRaw=oraw, bufL=_, bufR=ow0, bufSize=os }
= let
loop !ir !ow
| ow >= os = done OutputUnderflow ir ow
| ir >= iw = done InputUnderflow ir ow
| otherwise = do
c0 <- readWord8Buf iraw ir
ow' <- writeCharBuf oraw ow (unsafeChr (fromIntegral c0))
loop (ir+1) ow'
-- lambda-lifted, to avoid thunks being built in the inner-loop:
done why !ir !ow = return (why,
if ir == iw then input{ bufL=0, bufR=0 }
else input{ bufL=ir },
output{ bufR=ow })
in
loop ir0 ow0
latin1_encode :: EncodeBuffer
latin1_encode
input@Buffer{ bufRaw=iraw, bufL=ir0, bufR=iw, bufSize=_ }
output@Buffer{ bufRaw=oraw, bufL=_, bufR=ow0, bufSize=os }
= let
done why !ir !ow = return (why,
if ir == iw then input{ bufL=0, bufR=0 }
else input{ bufL=ir },
output{ bufR=ow })
loop !ir !ow
| ow >= os = done OutputUnderflow ir ow
| ir >= iw = done InputUnderflow ir ow
| otherwise = do
(c,ir') <- readCharBuf iraw ir
writeWord8Buf oraw ow (fromIntegral (ord c))
loop ir' (ow+1)
in
loop ir0 ow0
latin1_checked_encode :: EncodeBuffer
latin1_checked_encode
input@Buffer{ bufRaw=iraw, bufL=ir0, bufR=iw, bufSize=_ }
output@Buffer{ bufRaw=oraw, bufL=_, bufR=ow0, bufSize=os }
= let
done why !ir !ow = return (why,
if ir == iw then input{ bufL=0, bufR=0 }
else input{ bufL=ir },
output{ bufR=ow })
loop !ir !ow
| ow >= os = done OutputUnderflow ir ow
| ir >= iw = done InputUnderflow ir ow
| otherwise = do
(c,ir') <- readCharBuf iraw ir
if ord c > 0xff then invalid else do
writeWord8Buf oraw ow (fromIntegral (ord c))
loop ir' (ow+1)
where
invalid = done InvalidSequence ir ow
in
loop ir0 ow0
| null |
https://raw.githubusercontent.com/ghc/packages-base/52c0b09036c36f1ed928663abb2f295fd36a88bb/GHC/IO/Encoding/Latin1.hs
|
haskell
|
---------------------------------------------------------------------------
|
Module : GHC.IO.Encoding.Latin1
License : see libraries/base/LICENSE
Maintainer :
Stability : internal
Portability : non-portable
---------------------------------------------------------------------------
-----------------------------------------------------------------------------
| /Since: 4.4.0.0/
| /Since: 4.4.0.0/
lambda-lifted, to avoid thunks being built in the inner-loop:
|
# LANGUAGE Trustworthy #
# LANGUAGE NoImplicitPrelude
, BangPatterns
, NondecreasingIndentation
#
, BangPatterns
, NondecreasingIndentation
#-}
# OPTIONS_GHC -funbox - strict - fields #
Copyright : ( c ) The University of Glasgow , 2009
UTF-32 Codecs for the IO library
Portions Copyright : ( c ) 2008 - 2009 ,
( c ) 2009 ,
( c ) 2009
module GHC.IO.Encoding.Latin1 (
latin1, mkLatin1,
latin1_checked, mkLatin1_checked,
latin1_decode,
latin1_encode,
latin1_checked_encode,
) where
import GHC.Base
import GHC.Real
import GHC.Num
import GHC.IO
import GHC.IO.Buffer
import GHC.IO.Encoding.Failure
import GHC.IO.Encoding.Types
Latin1
latin1 :: TextEncoding
latin1 = mkLatin1 ErrorOnCodingFailure
mkLatin1 :: CodingFailureMode -> TextEncoding
mkLatin1 cfm = TextEncoding { textEncodingName = "ISO8859-1",
mkTextDecoder = latin1_DF cfm,
mkTextEncoder = latin1_EF cfm }
latin1_DF :: CodingFailureMode -> IO (TextDecoder ())
latin1_DF cfm =
return (BufferCodec {
encode = latin1_decode,
recover = recoverDecode cfm,
close = return (),
getState = return (),
setState = const $ return ()
})
latin1_EF :: CodingFailureMode -> IO (TextEncoder ())
latin1_EF cfm =
return (BufferCodec {
encode = latin1_encode,
recover = recoverEncode cfm,
close = return (),
getState = return (),
setState = const $ return ()
})
latin1_checked :: TextEncoding
latin1_checked = mkLatin1_checked ErrorOnCodingFailure
mkLatin1_checked :: CodingFailureMode -> TextEncoding
mkLatin1_checked cfm = TextEncoding { textEncodingName = "ISO8859-1(checked)",
mkTextDecoder = latin1_DF cfm,
mkTextEncoder = latin1_checked_EF cfm }
latin1_checked_EF :: CodingFailureMode -> IO (TextEncoder ())
latin1_checked_EF cfm =
return (BufferCodec {
encode = latin1_checked_encode,
recover = recoverEncode cfm,
close = return (),
getState = return (),
setState = const $ return ()
})
latin1_decode :: DecodeBuffer
latin1_decode
input@Buffer{ bufRaw=iraw, bufL=ir0, bufR=iw, bufSize=_ }
output@Buffer{ bufRaw=oraw, bufL=_, bufR=ow0, bufSize=os }
= let
loop !ir !ow
| ow >= os = done OutputUnderflow ir ow
| ir >= iw = done InputUnderflow ir ow
| otherwise = do
c0 <- readWord8Buf iraw ir
ow' <- writeCharBuf oraw ow (unsafeChr (fromIntegral c0))
loop (ir+1) ow'
done why !ir !ow = return (why,
if ir == iw then input{ bufL=0, bufR=0 }
else input{ bufL=ir },
output{ bufR=ow })
in
loop ir0 ow0
latin1_encode :: EncodeBuffer
latin1_encode
input@Buffer{ bufRaw=iraw, bufL=ir0, bufR=iw, bufSize=_ }
output@Buffer{ bufRaw=oraw, bufL=_, bufR=ow0, bufSize=os }
= let
done why !ir !ow = return (why,
if ir == iw then input{ bufL=0, bufR=0 }
else input{ bufL=ir },
output{ bufR=ow })
loop !ir !ow
| ow >= os = done OutputUnderflow ir ow
| ir >= iw = done InputUnderflow ir ow
| otherwise = do
(c,ir') <- readCharBuf iraw ir
writeWord8Buf oraw ow (fromIntegral (ord c))
loop ir' (ow+1)
in
loop ir0 ow0
latin1_checked_encode :: EncodeBuffer
latin1_checked_encode
input@Buffer{ bufRaw=iraw, bufL=ir0, bufR=iw, bufSize=_ }
output@Buffer{ bufRaw=oraw, bufL=_, bufR=ow0, bufSize=os }
= let
done why !ir !ow = return (why,
if ir == iw then input{ bufL=0, bufR=0 }
else input{ bufL=ir },
output{ bufR=ow })
loop !ir !ow
| ow >= os = done OutputUnderflow ir ow
| ir >= iw = done InputUnderflow ir ow
| otherwise = do
(c,ir') <- readCharBuf iraw ir
if ord c > 0xff then invalid else do
writeWord8Buf oraw ow (fromIntegral (ord c))
loop ir' (ow+1)
where
invalid = done InvalidSequence ir ow
in
loop ir0 ow0
|
f7aeaf5c8b7a2e3955e9db7afa5e4f1d32f613b62d323a3aa21793696037df50
|
ocaml/ocaml-lsp
|
ts_types.mli
|
open Import
module Literal : sig
type t =
| String of string
| Int of int
| Float of float
val to_maybe_quoted_string : t -> string
val to_dyn : t -> Dyn.t
end
module Enum : sig
type case =
| Literal of Literal.t
| Alias of string
val dyn_of_case : case -> Dyn.t
type t = (string * case) list
val to_dyn : (string * case) list -> Dyn.t
end
module type S = sig
type ident
type field_def =
| Single of
{ optional : bool
; typ : typ
}
| Pattern of
{ pat : typ
; typ : typ
}
and field = field_def Named.t
and typ =
| Literal of Literal.t
| Ident of ident
| Sum of typ list
| List of typ
| Record of field list
| Tuple of typ list
| App of typ * typ
and interface = { fields : field list }
and decl =
| Interface of interface
| Type of typ
| Enum_anon of Enum.t
and t = decl Named.t
val to_dyn : t -> Dyn.t
val dyn_of_typ : typ -> Dyn.t
val dyn_of_field : field -> Dyn.t
class map :
object
method enum_anon : Enum.t -> Enum.t
method field : field -> field
method interface : interface -> interface
method sum : typ list -> typ
method t : t -> t
method typ : typ -> typ
end
class ['a] fold :
object
method field : field -> init:'a -> 'a
method ident : ident -> init:'a -> 'a
method t : t -> init:'a -> 'a
method typ : typ -> init:'a -> 'a
end
end
module Unresolved : sig
include S with type ident := String.t
val enum : name:string -> constrs:Enum.t -> Enum.t Named.t
val interface : name:string -> fields:field list -> interface Named.t
val pattern_field : name:string -> pat:typ -> typ:typ -> field_def Named.t
val named_field : ?optional:bool -> typ -> string -> field_def Named.t
end
module Ident : sig
module Id : Id.S
type t =
{ id : Id.t
; name : string
}
val to_dyn : t -> Dyn.t
val make : string -> t
module Top_closure : sig
val top_closure :
key:('a -> t)
-> deps:('a -> 'a list)
-> 'a list
-> ('a list, 'a list) result
end
end
module Prim : sig
type t =
| Null
| String
| Bool
| Number
| Uinteger
| Any
| Object
| List
| Self
| Resolved of Ident.t
val to_dyn : t -> Dyn.t
val of_string : string -> resolve:(string -> t) -> t
end
module Resolved : S with type ident := Prim.t
val resolve_all :
Unresolved.t list -> names:Ident.t String.Map.t -> Resolved.t list
| null |
https://raw.githubusercontent.com/ocaml/ocaml-lsp/2757cdc11dd68a6b0260aa961395b5e8a995ff11/lsp/bin/typescript/ts_types.mli
|
ocaml
|
open Import
module Literal : sig
type t =
| String of string
| Int of int
| Float of float
val to_maybe_quoted_string : t -> string
val to_dyn : t -> Dyn.t
end
module Enum : sig
type case =
| Literal of Literal.t
| Alias of string
val dyn_of_case : case -> Dyn.t
type t = (string * case) list
val to_dyn : (string * case) list -> Dyn.t
end
module type S = sig
type ident
type field_def =
| Single of
{ optional : bool
; typ : typ
}
| Pattern of
{ pat : typ
; typ : typ
}
and field = field_def Named.t
and typ =
| Literal of Literal.t
| Ident of ident
| Sum of typ list
| List of typ
| Record of field list
| Tuple of typ list
| App of typ * typ
and interface = { fields : field list }
and decl =
| Interface of interface
| Type of typ
| Enum_anon of Enum.t
and t = decl Named.t
val to_dyn : t -> Dyn.t
val dyn_of_typ : typ -> Dyn.t
val dyn_of_field : field -> Dyn.t
class map :
object
method enum_anon : Enum.t -> Enum.t
method field : field -> field
method interface : interface -> interface
method sum : typ list -> typ
method t : t -> t
method typ : typ -> typ
end
class ['a] fold :
object
method field : field -> init:'a -> 'a
method ident : ident -> init:'a -> 'a
method t : t -> init:'a -> 'a
method typ : typ -> init:'a -> 'a
end
end
module Unresolved : sig
include S with type ident := String.t
val enum : name:string -> constrs:Enum.t -> Enum.t Named.t
val interface : name:string -> fields:field list -> interface Named.t
val pattern_field : name:string -> pat:typ -> typ:typ -> field_def Named.t
val named_field : ?optional:bool -> typ -> string -> field_def Named.t
end
module Ident : sig
module Id : Id.S
type t =
{ id : Id.t
; name : string
}
val to_dyn : t -> Dyn.t
val make : string -> t
module Top_closure : sig
val top_closure :
key:('a -> t)
-> deps:('a -> 'a list)
-> 'a list
-> ('a list, 'a list) result
end
end
module Prim : sig
type t =
| Null
| String
| Bool
| Number
| Uinteger
| Any
| Object
| List
| Self
| Resolved of Ident.t
val to_dyn : t -> Dyn.t
val of_string : string -> resolve:(string -> t) -> t
end
module Resolved : S with type ident := Prim.t
val resolve_all :
Unresolved.t list -> names:Ident.t String.Map.t -> Resolved.t list
|
|
94c7c39fbb3ffa785df584acac79acfd0d69ab0e6655e7ce202d6811859fe3cb
|
haskell-hvr/HsYAML
|
Writer.hs
|
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE Safe #-}
-- |
Copyright : © 2015 - 2018
SPDX - License - Identifier : GPL-2.0 - or - later
--
-- Event-stream oriented YAML writer API
--
module Data.YAML.Event.Writer
( writeEvents
, writeEventsText
) where
import Data.YAML.Event.Internal
import qualified Data.ByteString.Lazy as BS.L
import qualified Data.Char as C
import qualified Data.Map as Map
import qualified Data.Text as T
import Text.Printf (printf)
import qualified Data.Text.Lazy as T.L
import qualified Data.Text.Lazy.Builder as T.B
import qualified Data.Text.Lazy.Encoding as T.L
import Util
WARNING : the code that follows will make you cry ; a safety pig is provided below for your benefit .
_
_ . _ _ ... _ .- ' , _ .. _ ( ` ) )
' - . ` ' /-._.- ' ' , /
) \ ' .
/ _ _ | \
| a a / |
\ .- . ;
' - ( '' ) .- ' , ' ;
' - ; | . '
\ \ /
| 7 . _ _ _ .-\ \
| | | ` ` / / ` /
/,_| | /,_/ /
/,_/ ' ` - '
_
_._ _..._ .-', _.._(`))
'-. ` ' /-._.-' ',/
) \ '.
/ _ _ | \
| a a / |
\ .-. ;
'-('' ).-' ,' ;
'-; | .'
\ \ /
| 7 .__ _.-\ \
| | | ``/ /` /
/,_| | /,_/ /
/,_/ '`-'
-}
| Serialise ' Event 's using specified UTF encoding to a lazy ' BS.L.ByteString '
--
-- __NOTE__: This function is only well-defined for valid 'Event' streams
--
@since 0.2.0.0
writeEvents :: Encoding -> [Event] -> BS.L.ByteString
writeEvents UTF8 = T.L.encodeUtf8 . writeEventsText
writeEvents UTF16LE = T.L.encodeUtf16LE . T.L.cons '\xfeff' . writeEventsText
writeEvents UTF16BE = T.L.encodeUtf16BE . T.L.cons '\xfeff' . writeEventsText
writeEvents UTF32LE = T.L.encodeUtf32LE . T.L.cons '\xfeff' . writeEventsText
writeEvents UTF32BE = T.L.encodeUtf32BE . T.L.cons '\xfeff' . writeEventsText
| Serialise ' Event 's to lazy ' T.L.Text '
--
-- __NOTE__: This function is only well-defined for valid 'Event' streams
--
@since 0.2.0.0
writeEventsText :: [Event] -> T.L.Text
writeEventsText [] = mempty
writeEventsText (StreamStart:xs) = T.B.toLazyText $ goStream xs (error "writeEvents: internal error")
where
-- goStream :: [Event] -> [Event] -> T.B.Builder
goStream [StreamEnd] _ = mempty
goStream (StreamEnd : _ : _ ) _cont = error "writeEvents: events after StreamEnd"
goStream (Comment com: rest) cont = goComment (0 :: Int) True BlockIn com (goStream rest cont)
goStream (DocumentStart marker : rest) cont
= case marker of
NoDirEndMarker -> putNode False rest (\zs -> goDoc zs cont)
DirEndMarkerNoVersion -> "---" <> putNode True rest (\zs -> goDoc zs cont)
DirEndMarkerVersion mi -> "%YAML 1." <> (T.B.fromString (show mi)) <> "\n---" <> putNode True rest (\zs -> goDoc zs cont)
goStream (x:_) _cont = error ("writeEvents: unexpected " ++ show x ++ " (expected DocumentStart or StreamEnd)")
goStream [] _cont = error ("writeEvents: unexpected end of stream (expected DocumentStart or StreamEnd)")
goDoc (DocumentEnd marker : rest) cont
= (if marker then "...\n" else mempty) <> goStream rest cont
goDoc (Comment com: rest) cont = goComment (0 :: Int) True BlockIn com (goDoc rest cont)
goDoc ys _ = error (show ys)
-- unexpected s l = error ("writeEvents: unexpected " ++ show l ++ " " ++ show s)
writeEventsText (x:_) = error ("writeEvents: unexpected " ++ show x ++ " (expected StreamStart)")
| Production context -- copied from Data . YAML.Token
data Context = BlockOut -- ^ Outside block sequence.
| BlockIn -- ^ Inside block sequence.
| BlockKey -- ^ Implicit block key.
| FlowOut -- ^ Outside flow collection.
| FlowIn -- ^ Inside flow collection.
| FlowKey -- ^ Implicit flow key.
deriving (Eq,Show)
goComment :: Int -> Bool -> Context -> T.Text -> T.B.Builder -> T.B.Builder
goComment !n !sol c comment cont = doSol <> "#" <> (T.B.fromText comment) <> doEol <> doIndent <> cont
where
doEol
| not sol && n == 0 = mempty -- "--- " case
| sol && FlowIn == c = mempty
| otherwise = eol
doSol
| not sol && (BlockOut == c || FlowOut == c) = ws
| sol = mkInd n'
| otherwise = eol <> mkInd n'
n'
| BlockOut <- c = max 0 (n - 1)
| FlowOut <- c = n + 1
| otherwise = n
doIndent
| BlockOut <- c = mkInd n'
| FlowOut <- c = mkInd n'
| otherwise = mempty
putNode :: Bool -> [Event] -> ([Event] -> T.B.Builder) -> T.B.Builder
putNode = \docMarker -> go (-1 :: Int) (not docMarker) BlockIn
where
s - l+block - node(n , c )
[ 196 ] s - l+block - node(n , c ) : : = s - l+block - in - block(n , c ) | s - l+flow - in - block(n )
[ 197 ] s - l+flow - in - block(n ) : : = s - separate(n+1,flow - out ) ns - flow - node(n+1,flow - out ) s - l - comments
[ 198 ] s - l+block - in - block(n , c ) : : = s - l+block - scalar(n , c ) | s - l+block - collection(n , c )
[ 199 ] s - l+block - scalar(n , c ) : : = s - separate(n+1,c ) ( c - ns - properties(n+1,c ) s - separate(n+1,c ) ) ? ( c - l+literal(n ) | c - l+folded(n ) )
[ 200 ] s - l+block - collection(n , c ) : : = ( s - separate(n+1,c ) c - ns - properties(n+1,c ) ) ? s - l - comments
( l+block - sequence(seq - spaces(n , c ) ) | l+block - mapping(n ) )
[ 201 ] seq - spaces(n , c ) : : = c = block - out ⇒ n-1
c = block - in ⇒ n
[196] s-l+block-node(n,c) ::= s-l+block-in-block(n,c) | s-l+flow-in-block(n)
[197] s-l+flow-in-block(n) ::= s-separate(n+1,flow-out) ns-flow-node(n+1,flow-out) s-l-comments
[198] s-l+block-in-block(n,c) ::= s-l+block-scalar(n,c) | s-l+block-collection(n,c)
[199] s-l+block-scalar(n,c) ::= s-separate(n+1,c) ( c-ns-properties(n+1,c) s-separate(n+1,c) )? ( c-l+literal(n) | c-l+folded(n) )
[200] s-l+block-collection(n,c) ::= ( s-separate(n+1,c) c-ns-properties(n+1,c) )? s-l-comments
( l+block-sequence(seq-spaces(n,c)) | l+block-mapping(n) )
[201] seq-spaces(n,c) ::= c = block-out ⇒ n-1
c = block-in ⇒ n
-}
go :: Int -> Bool -> Context -> [Event] -> ([Event] -> T.B.Builder) -> T.B.Builder
go _ _ _ [] _cont = error ("putNode: expected node-start event instead of end-of-stream")
go !n !sol c (t : rest) cont = case t of
Scalar anc tag sty t' -> goStr (n+1) sol c anc tag sty t' (cont rest)
SequenceStart anc tag sty -> goSeq (n+1) sol (chn sty) anc tag sty rest cont
MappingStart anc tag sty -> goMap (n+1) sol (chn sty) anc tag sty rest cont
Alias a -> pfx <> goAlias c a (cont rest)
Comment com -> goComment (n+1) sol c com (go n sol c rest cont)
_ -> error ("putNode: expected node-start event instead of " ++ show t)
where
pfx | sol = mempty
| BlockKey <- c = mempty
| FlowKey <- c = mempty
| otherwise = T.B.singleton ' '
chn sty
| Flow <-sty, (BlockIn == c || BlockOut == c) = FlowOut
| otherwise = c
goMap _ sol _ anc tag _ (MappingEnd : rest) cont = pfx $ "{}\n" <> cont rest
where
pfx cont' = wsSol sol <> anchorTag'' (Right ws) anc tag cont'
goMap n sol c anc tag Block xs cont = case c of
BlockIn | not (not sol && n == 0) -- avoid "--- " case
-> wsSol sol <> anchorTag'' (Right (eol <> mkInd n)) anc tag
(putKey xs putValue')
_ -> anchorTag'' (Left ws) anc tag $ doEol <> g' xs
where
g' (MappingEnd : rest) = cont rest -- All comments should be part of the key
g' ys = pfx <> putKey ys putValue'
g (Comment com: rest) = goComment n True c' com (g rest) -- For trailing comments
g (MappingEnd : rest) = cont rest
g ys = pfx <> putKey ys putValue'
pfx = if c == BlockIn || c == BlockOut || c == BlockKey then mkInd n else ws
c' = if FlowIn == c then FlowKey else BlockKey
doEol = case c of
FlowKey -> mempty
FlowIn -> mempty
_ -> eol
putKey zs cont2
| isSmallKey zs = go n (n == 0) c' zs (\ys -> ":" <> cont2 ys)
| Comment com: rest <- zs = "?" <> ws <> goComment 0 True BlockIn com (f rest cont2)
| otherwise = "?" <> go n False BlockIn zs (putValue cont2)
f (Comment com: rest) cont2 = goComment (n + 1) True BlockIn com (f rest cont2) -- Comments should not change position in key
f zs cont2 = ws <> mkInd n <> go n False BlockIn zs (putValue cont2)
putValue cont2 zs
| FlowIn <- c = ws <> mkInd (n - 1) <> ":" <> cont2 zs
| otherwise = mkInd n <> ":" <> cont2 zs
putValue' (Comment com: rest) = goComment (n + 1) False BlockOut com (ws <> putValue' rest) -- Comments should not change position in value
putValue' zs = go n False (if FlowIn == c then FlowIn else BlockOut) zs g
goMap n sol c anc tag Flow xs cont =
wsSol sol <> anchorTag'' (Right ws) anc tag ("{" <> f xs)
where
f (Comment com: rest) = eol <> wsSol sol <> goComment n' True (inFlow c) com (f rest)
f (MappingEnd : rest) = eol <> wsSol sol <> mkInd (n - 1) <> "}" <> doEol <> cont rest
f ys = eol <> mkInd n' <> putKey ys putValue'
n' = n + 1
doEol = case c of
FlowKey -> mempty
FlowIn -> mempty
_ -> eol
g (Comment com: rest) = "," <> eol <> wsSol sol <> goComment n' True (inFlow c) com (f rest)
g (MappingEnd : rest) = eol <> wsSol sol <> mkInd (n - 1) <> "}" <> doEol <> cont rest
g ys = "," <> eol <> mkInd n' <> putKey ys putValue'
putKey zs cont2
| (Comment com: rest) <- zs = goComment n' True c com (eol <> mkInd n' <> putKey rest cont2)
| isSmallKey zs = go n' (n == 0) FlowKey zs (if isComEv zs then putValue cont2 else (\ys -> ":" <> cont2 ys))
| otherwise = "?" <> go n False FlowIn zs (putValue cont2)
putValue cont2 zs
| Comment com: rest <- zs = eol <> wsSol sol <> goComment n' True (inFlow c) com (putValue cont2 rest)
| otherwise = eol <> mkInd n' <> ":" <> cont2 zs
putValue' zs
| Comment com : rest <- zs = goComment n' False FlowOut com (putValue' rest)
| otherwise = go n' False FlowIn zs g
goSeq _ sol _ anc tag _ (SequenceEnd : rest) cont = pfx $ "[]\n" <> cont rest
where
pfx cont' = wsSol sol <> anchorTag'' (Right ws) anc tag cont'
goSeq n sol c anc tag Block xs cont = case c of
BlockOut -> anchorTag'' (Left ws) anc tag (eol <> if isComEv xs then "-" <> eol <> f xs else g xs)
BlockIn
| not sol && n == 0 {- "---" case -} -> goSeq n sol BlockOut anc tag Block xs cont
| Comment com: rest <- xs -> wsSol sol <> anchorTag'' (Right (eol <> mkInd n')) anc tag ("-" <> ws <> goComment 0 True BlockIn com (f rest))
| otherwise -> wsSol sol <> anchorTag'' (Right (eol <> mkInd n')) anc tag ("-" <> go n' False BlockIn xs g)
BlockKey -> error "sequence in block-key context not supported"
_ -> error "Invalid Context in Block style"
where
n' | BlockOut <- c = max 0 (n - 1)
| otherwise = n
g (Comment com: rest) = goComment n' True BlockIn com (g rest)
g (SequenceEnd : rest) = cont rest
g ys = mkInd n' <> "-" <> go n' False BlockIn ys g
f (Comment com: rest) = goComment n' True BlockIn com (f rest)
f (SequenceEnd : rest) = cont rest
f ys = ws <> mkInd n' <> go n' False BlockIn ys g
goSeq n sol c anc tag Flow xs cont =
wsSol sol <> anchorTag'' (Right ws) anc tag ("[" <> f xs)
where
f (Comment com: rest) = eol <> wsSol sol <> goComment n' True (inFlow c) com (f rest)
f (SequenceEnd : rest) = eol <> wsSol sol <> mkInd (n - 1) <> "]" <> doEol <> cont rest
f ys = eol <> mkInd n' <> go n' False (inFlow c) ys g
n' = n + 1
doEol = case c of
FlowKey -> mempty
FlowIn -> mempty
_ -> eol
g (Comment com: rest) = "," <> eol <> wsSol sol <> goComment n' True (inFlow c) com (f rest)
g (SequenceEnd : rest) = eol <> wsSol sol <> mkInd (n - 1) <> "]" <> doEol <> cont rest
g ys = "," <> eol <> mkInd n' <> go n' False (inFlow c) ys g
goAlias c a cont = T.B.singleton '*' <> T.B.fromText a <> sep <> cont
where
sep = case c of
BlockIn -> eol
BlockOut -> eol
BlockKey -> T.B.singleton ' '
FlowIn -> mempty
FlowOut -> eol
FlowKey -> T.B.singleton ' '
goStr :: Int -> Bool -> Context -> Maybe Anchor -> Tag -> ScalarStyle -> Text -> T.B.Builder -> T.B.Builder
goStr !n !sol c anc tag sty t cont = case sty of
-- flow-style
Plain -- empty scalars
| t == "" -> case () of
_ | Nothing <- anc, Tag Nothing <- tag -> contEol -- not even node properties
| sol -> anchorTag0 anc tag (if c == BlockKey || c == FlowKey then ws <> cont else contEol)
| BlockKey <- c -> anchorTag0 anc tag (ws <> cont)
| FlowKey <- c -> anchorTag0 anc tag (ws <> cont)
| otherwise -> anchorTag'' (Left ws) anc tag contEol
Plain -> pfx $
let h [] = contEol
h (x:xs) = T.B.fromText x <> f' xs
where
f' [] = contEol
f' (y:ys) = eol <> mkInd (n+1) <> T.B.fromText y <> f' ys
FIXME : unquoted plain - strings ca n't handle leading / trailing whitespace properly
FIXME : leading white - space ( i.e. SPC ) before / after LF
DoubleQuoted -> pfx $ T.B.singleton '"' <> T.B.fromText (escapeDQ t) <> T.B.singleton '"' <> contEol
-- block style
Folded chm iden -> pfx $ ">" <> goChomp chm <> goDigit iden <> g (insFoldNls' $ T.lines t) (fromEnum iden) cont
Literal chm iden -> pfx $ "|" <> goChomp chm <> goDigit iden <> g (T.lines t) (fromEnum iden) cont
where
goDigit :: IndentOfs -> T.B.Builder
goDigit iden = let ch = C.intToDigit.fromEnum $ iden
in if(ch == '0') then mempty else T.B.singleton ch
goChomp :: Chomp -> T.B.Builder
goChomp chm = case chm of
Strip -> T.B.singleton '-'
Clip -> mempty
Keep -> T.B.singleton '+'
pfx cont' = (if sol || c == BlockKey || c == FlowKey then mempty else ws) <> anchorTag'' (Right ws) anc tag cont'
doEol = case c of
BlockKey -> False
FlowKey -> False
FlowIn -> False
_ -> True
contEol
| doEol = eol <> cont
| otherwise = cont
g [] _ cont' = eol <> cont'
g (x:xs) dig cont'
| T.null x = eol <> g xs dig cont'
| dig == 0 = eol <> (if n > 0 then mkInd n else mkInd' 1) <> T.B.fromText x <> g xs dig cont'
| otherwise = eol <> mkInd (n-1) <> mkInd' dig <> T.B.fromText x <> g xs dig cont'
g' [] cont' = cont'
g' (x:xs) cont' = eol <> mkInd (n+1) <> T.B.fromText x <> g' xs cont'
f [] cont' = cont'
f (x:xs) cont' = T.B.fromText x <> g' xs cont'
isSmallKey (Alias _ : _) = True
isSmallKey (Scalar _ _ (Folded _ _) _: _) = False
isSmallKey (Scalar _ _ (Literal _ _) _: _) = False
isSmallKey (Scalar _ _ _ _ : _) = True
isSmallKey (SequenceStart _ _ _ : _) = False
isSmallKey (MappingStart _ _ _ : _) = False
isSmallKey _ = False
-- <#in-flow(c) in-flow(c)>
inFlow c = case c of
FlowIn -> FlowIn
FlowOut -> FlowIn
BlockKey -> FlowKey
FlowKey -> FlowKey
_ -> error "Invalid context in Flow style"
putTag t cont
| Just t' <- T.stripPrefix "tag:yaml.org,2002:" t = "!!" <> T.B.fromText t' <> cont
| "!" `T.isPrefixOf` t = T.B.fromText t <> cont
| otherwise = "!<" <> T.B.fromText t <> T.B.singleton '>' <> cont
anchorTag'' :: Either T.B.Builder T.B.Builder -> Maybe Anchor -> Tag -> T.B.Builder -> T.B.Builder
anchorTag'' _ Nothing (Tag Nothing) cont = cont
anchorTag'' (Right pad) Nothing (Tag (Just t)) cont = putTag t (pad <> cont)
anchorTag'' (Right pad) (Just a) (Tag Nothing) cont = T.B.singleton '&' <> T.B.fromText a <> pad <> cont
anchorTag'' (Right pad) (Just a) (Tag (Just t)) cont = T.B.singleton '&' <> T.B.fromText a <> T.B.singleton ' ' <> putTag t (pad <> cont)
anchorTag'' (Left pad) Nothing (Tag (Just t)) cont = pad <> putTag t cont
anchorTag'' (Left pad) (Just a) (Tag Nothing) cont = pad <> T.B.singleton '&' <> T.B.fromText a <> cont
anchorTag'' (Left pad) (Just a) (Tag (Just t)) cont = pad <> T.B.singleton '&' <> T.B.fromText a <> T.B.singleton ' ' <> putTag t cont
anchorTag0 = anchorTag'' (Left mempty)
anchorTag = anchorTag '' ( Right ( T.B.singleton ' ' ) )
anchorTag ' = anchorTag '' ( Left ( T.B.singleton ' ' ) )
isComEv :: [Event] -> Bool
isComEv (Comment _: _) = True
isComEv _ = False
-- indentation helper
mkInd :: Int -> T.B.Builder
mkInd (-1) = mempty
mkInd 0 = mempty
mkInd 1 = " "
mkInd 2 = " "
mkInd 3 = " "
mkInd 4 = " "
mkInd l
| l < 0 = error (show l)
| otherwise = T.B.fromText (T.replicate l " ")
mkInd' :: Int -> T.B.Builder
mkInd' 1 = " "
mkInd' 2 = " "
mkInd' 3 = " "
mkInd' 4 = " "
mkInd' 5 = " "
mkInd' 6 = " "
mkInd' 7 = " "
mkInd' 8 = " "
mkInd' 9 = " "
mkInd' l = error ("Impossible Indentation-level" ++ show l)
eol, ws:: T.B.Builder
eol = T.B.singleton '\n'
ws = T.B.singleton ' '
wsSol :: Bool -> T.B.Builder
wsSol sol = if sol then mempty else ws
escapeDQ :: Text -> Text
escapeDQ t
| T.all (\c -> C.isPrint c && c /= '\\' && c /= '"') t = t
| otherwise = T.concatMap escapeChar t
escapeChar :: Char -> Text
escapeChar c
| c == '\\' = "\\\\"
| c == '"' = "\\\""
| C.isPrint c = T.singleton c
| Just e <- Map.lookup c emap = e
| x <= 0xff = T.pack (printf "\\x%02x" x)
| x <= 0xffff = T.pack (printf "\\u%04x" x)
| otherwise = T.pack (printf "\\U%08x" x)
where
x = ord c
emap = Map.fromList [ (v,T.pack ['\\',k]) | (k,v) <- escapes ]
escapes :: [(Char,Char)]
escapes =
[ ('0', '\0')
, ('a', '\x7')
, ('b', '\x8')
, ('\x9', '\x9')
, ('t', '\x9')
, ('n', '\xa')
, ('v', '\xb')
, ('f', '\xc')
, ('r', '\xd')
, ('e', '\x1b')
, (' ', ' ')
, ('"', '"')
, ('/', '/')
, ('\\', '\\')
, ('N', '\x85')
, ('_', '\xa0')
, ('L', '\x2028')
, ('P', '\x2029')
]
-- flow style line folding
-- FIXME: check single-quoted strings with leading '\n' or trailing '\n's
insFoldNls :: [Text] -> [Text]
insFoldNls [] = []
insFoldNls z0@(z:zs)
| all T.null z0 = "" : z0 -- HACK
| otherwise = z : go zs
where
go [] = []
go (l:ls)
| T.null l = l : go' ls
| otherwise = "" : l : go ls
go' [] = [""]
go' (l:ls)
| T.null l = l : go' ls
| otherwise = "" : l : go ls
{- block style line folding
The combined effect of the block line folding rules is that each
“paragraph” is interpreted as a line, empty lines are interpreted as a
line feed, and the formatting of more-indented lines is preserved.
-}
insFoldNls' :: [Text] -> [Text]
insFoldNls' = go'
where
go [] = []
go (l:ls)
| T.null l = l : go ls
| isWhite (T.head l) = l : go' ls
| otherwise = "" : l : go ls
go' [] = []
go' (l:ls)
| T.null l = l : go' ls
| isWhite (T.head l) = l : go' ls
| otherwise = l : go ls
@s - white@
isWhite :: Char -> Bool
isWhite ' ' = True
isWhite '\t' = True
isWhite _ = False
| null |
https://raw.githubusercontent.com/haskell-hvr/HsYAML/be6040095fa7ad442c28d5c56ce9da3578807ea4/src/Data/YAML/Event/Writer.hs
|
haskell
|
# LANGUAGE BangPatterns #
# LANGUAGE OverloadedStrings #
# LANGUAGE Safe #
|
Event-stream oriented YAML writer API
__NOTE__: This function is only well-defined for valid 'Event' streams
__NOTE__: This function is only well-defined for valid 'Event' streams
goStream :: [Event] -> [Event] -> T.B.Builder
unexpected s l = error ("writeEvents: unexpected " ++ show l ++ " " ++ show s)
copied from Data . YAML.Token
^ Outside block sequence.
^ Inside block sequence.
^ Implicit block key.
^ Outside flow collection.
^ Inside flow collection.
^ Implicit flow key.
"--- " case
avoid "--- " case
All comments should be part of the key
For trailing comments
Comments should not change position in key
Comments should not change position in value
"---" case
flow-style
empty scalars
not even node properties
block style
<#in-flow(c) in-flow(c)>
indentation helper
flow style line folding
FIXME: check single-quoted strings with leading '\n' or trailing '\n's
HACK
block style line folding
The combined effect of the block line folding rules is that each
“paragraph” is interpreted as a line, empty lines are interpreted as a
line feed, and the formatting of more-indented lines is preserved.
|
Copyright : © 2015 - 2018
SPDX - License - Identifier : GPL-2.0 - or - later
module Data.YAML.Event.Writer
( writeEvents
, writeEventsText
) where
import Data.YAML.Event.Internal
import qualified Data.ByteString.Lazy as BS.L
import qualified Data.Char as C
import qualified Data.Map as Map
import qualified Data.Text as T
import Text.Printf (printf)
import qualified Data.Text.Lazy as T.L
import qualified Data.Text.Lazy.Builder as T.B
import qualified Data.Text.Lazy.Encoding as T.L
import Util
WARNING : the code that follows will make you cry ; a safety pig is provided below for your benefit .
_
_ . _ _ ... _ .- ' , _ .. _ ( ` ) )
' - . ` ' /-._.- ' ' , /
) \ ' .
/ _ _ | \
| a a / |
\ .- . ;
' - ( '' ) .- ' , ' ;
' - ; | . '
\ \ /
| 7 . _ _ _ .-\ \
| | | ` ` / / ` /
/,_| | /,_/ /
/,_/ ' ` - '
_
_._ _..._ .-', _.._(`))
'-. ` ' /-._.-' ',/
) \ '.
/ _ _ | \
| a a / |
\ .-. ;
'-('' ).-' ,' ;
'-; | .'
\ \ /
| 7 .__ _.-\ \
| | | ``/ /` /
/,_| | /,_/ /
/,_/ '`-'
-}
| Serialise ' Event 's using specified UTF encoding to a lazy ' BS.L.ByteString '
@since 0.2.0.0
writeEvents :: Encoding -> [Event] -> BS.L.ByteString
writeEvents UTF8 = T.L.encodeUtf8 . writeEventsText
writeEvents UTF16LE = T.L.encodeUtf16LE . T.L.cons '\xfeff' . writeEventsText
writeEvents UTF16BE = T.L.encodeUtf16BE . T.L.cons '\xfeff' . writeEventsText
writeEvents UTF32LE = T.L.encodeUtf32LE . T.L.cons '\xfeff' . writeEventsText
writeEvents UTF32BE = T.L.encodeUtf32BE . T.L.cons '\xfeff' . writeEventsText
| Serialise ' Event 's to lazy ' T.L.Text '
@since 0.2.0.0
writeEventsText :: [Event] -> T.L.Text
writeEventsText [] = mempty
writeEventsText (StreamStart:xs) = T.B.toLazyText $ goStream xs (error "writeEvents: internal error")
where
goStream [StreamEnd] _ = mempty
goStream (StreamEnd : _ : _ ) _cont = error "writeEvents: events after StreamEnd"
goStream (Comment com: rest) cont = goComment (0 :: Int) True BlockIn com (goStream rest cont)
goStream (DocumentStart marker : rest) cont
= case marker of
NoDirEndMarker -> putNode False rest (\zs -> goDoc zs cont)
DirEndMarkerNoVersion -> "---" <> putNode True rest (\zs -> goDoc zs cont)
DirEndMarkerVersion mi -> "%YAML 1." <> (T.B.fromString (show mi)) <> "\n---" <> putNode True rest (\zs -> goDoc zs cont)
goStream (x:_) _cont = error ("writeEvents: unexpected " ++ show x ++ " (expected DocumentStart or StreamEnd)")
goStream [] _cont = error ("writeEvents: unexpected end of stream (expected DocumentStart or StreamEnd)")
goDoc (DocumentEnd marker : rest) cont
= (if marker then "...\n" else mempty) <> goStream rest cont
goDoc (Comment com: rest) cont = goComment (0 :: Int) True BlockIn com (goDoc rest cont)
goDoc ys _ = error (show ys)
writeEventsText (x:_) = error ("writeEvents: unexpected " ++ show x ++ " (expected StreamStart)")
deriving (Eq,Show)
goComment :: Int -> Bool -> Context -> T.Text -> T.B.Builder -> T.B.Builder
goComment !n !sol c comment cont = doSol <> "#" <> (T.B.fromText comment) <> doEol <> doIndent <> cont
where
doEol
| sol && FlowIn == c = mempty
| otherwise = eol
doSol
| not sol && (BlockOut == c || FlowOut == c) = ws
| sol = mkInd n'
| otherwise = eol <> mkInd n'
n'
| BlockOut <- c = max 0 (n - 1)
| FlowOut <- c = n + 1
| otherwise = n
doIndent
| BlockOut <- c = mkInd n'
| FlowOut <- c = mkInd n'
| otherwise = mempty
putNode :: Bool -> [Event] -> ([Event] -> T.B.Builder) -> T.B.Builder
putNode = \docMarker -> go (-1 :: Int) (not docMarker) BlockIn
where
s - l+block - node(n , c )
[ 196 ] s - l+block - node(n , c ) : : = s - l+block - in - block(n , c ) | s - l+flow - in - block(n )
[ 197 ] s - l+flow - in - block(n ) : : = s - separate(n+1,flow - out ) ns - flow - node(n+1,flow - out ) s - l - comments
[ 198 ] s - l+block - in - block(n , c ) : : = s - l+block - scalar(n , c ) | s - l+block - collection(n , c )
[ 199 ] s - l+block - scalar(n , c ) : : = s - separate(n+1,c ) ( c - ns - properties(n+1,c ) s - separate(n+1,c ) ) ? ( c - l+literal(n ) | c - l+folded(n ) )
[ 200 ] s - l+block - collection(n , c ) : : = ( s - separate(n+1,c ) c - ns - properties(n+1,c ) ) ? s - l - comments
( l+block - sequence(seq - spaces(n , c ) ) | l+block - mapping(n ) )
[ 201 ] seq - spaces(n , c ) : : = c = block - out ⇒ n-1
c = block - in ⇒ n
[196] s-l+block-node(n,c) ::= s-l+block-in-block(n,c) | s-l+flow-in-block(n)
[197] s-l+flow-in-block(n) ::= s-separate(n+1,flow-out) ns-flow-node(n+1,flow-out) s-l-comments
[198] s-l+block-in-block(n,c) ::= s-l+block-scalar(n,c) | s-l+block-collection(n,c)
[199] s-l+block-scalar(n,c) ::= s-separate(n+1,c) ( c-ns-properties(n+1,c) s-separate(n+1,c) )? ( c-l+literal(n) | c-l+folded(n) )
[200] s-l+block-collection(n,c) ::= ( s-separate(n+1,c) c-ns-properties(n+1,c) )? s-l-comments
( l+block-sequence(seq-spaces(n,c)) | l+block-mapping(n) )
[201] seq-spaces(n,c) ::= c = block-out ⇒ n-1
c = block-in ⇒ n
-}
go :: Int -> Bool -> Context -> [Event] -> ([Event] -> T.B.Builder) -> T.B.Builder
go _ _ _ [] _cont = error ("putNode: expected node-start event instead of end-of-stream")
go !n !sol c (t : rest) cont = case t of
Scalar anc tag sty t' -> goStr (n+1) sol c anc tag sty t' (cont rest)
SequenceStart anc tag sty -> goSeq (n+1) sol (chn sty) anc tag sty rest cont
MappingStart anc tag sty -> goMap (n+1) sol (chn sty) anc tag sty rest cont
Alias a -> pfx <> goAlias c a (cont rest)
Comment com -> goComment (n+1) sol c com (go n sol c rest cont)
_ -> error ("putNode: expected node-start event instead of " ++ show t)
where
pfx | sol = mempty
| BlockKey <- c = mempty
| FlowKey <- c = mempty
| otherwise = T.B.singleton ' '
chn sty
| Flow <-sty, (BlockIn == c || BlockOut == c) = FlowOut
| otherwise = c
goMap _ sol _ anc tag _ (MappingEnd : rest) cont = pfx $ "{}\n" <> cont rest
where
pfx cont' = wsSol sol <> anchorTag'' (Right ws) anc tag cont'
goMap n sol c anc tag Block xs cont = case c of
-> wsSol sol <> anchorTag'' (Right (eol <> mkInd n)) anc tag
(putKey xs putValue')
_ -> anchorTag'' (Left ws) anc tag $ doEol <> g' xs
where
g' ys = pfx <> putKey ys putValue'
g (MappingEnd : rest) = cont rest
g ys = pfx <> putKey ys putValue'
pfx = if c == BlockIn || c == BlockOut || c == BlockKey then mkInd n else ws
c' = if FlowIn == c then FlowKey else BlockKey
doEol = case c of
FlowKey -> mempty
FlowIn -> mempty
_ -> eol
putKey zs cont2
| isSmallKey zs = go n (n == 0) c' zs (\ys -> ":" <> cont2 ys)
| Comment com: rest <- zs = "?" <> ws <> goComment 0 True BlockIn com (f rest cont2)
| otherwise = "?" <> go n False BlockIn zs (putValue cont2)
f zs cont2 = ws <> mkInd n <> go n False BlockIn zs (putValue cont2)
putValue cont2 zs
| FlowIn <- c = ws <> mkInd (n - 1) <> ":" <> cont2 zs
| otherwise = mkInd n <> ":" <> cont2 zs
putValue' zs = go n False (if FlowIn == c then FlowIn else BlockOut) zs g
goMap n sol c anc tag Flow xs cont =
wsSol sol <> anchorTag'' (Right ws) anc tag ("{" <> f xs)
where
f (Comment com: rest) = eol <> wsSol sol <> goComment n' True (inFlow c) com (f rest)
f (MappingEnd : rest) = eol <> wsSol sol <> mkInd (n - 1) <> "}" <> doEol <> cont rest
f ys = eol <> mkInd n' <> putKey ys putValue'
n' = n + 1
doEol = case c of
FlowKey -> mempty
FlowIn -> mempty
_ -> eol
g (Comment com: rest) = "," <> eol <> wsSol sol <> goComment n' True (inFlow c) com (f rest)
g (MappingEnd : rest) = eol <> wsSol sol <> mkInd (n - 1) <> "}" <> doEol <> cont rest
g ys = "," <> eol <> mkInd n' <> putKey ys putValue'
putKey zs cont2
| (Comment com: rest) <- zs = goComment n' True c com (eol <> mkInd n' <> putKey rest cont2)
| isSmallKey zs = go n' (n == 0) FlowKey zs (if isComEv zs then putValue cont2 else (\ys -> ":" <> cont2 ys))
| otherwise = "?" <> go n False FlowIn zs (putValue cont2)
putValue cont2 zs
| Comment com: rest <- zs = eol <> wsSol sol <> goComment n' True (inFlow c) com (putValue cont2 rest)
| otherwise = eol <> mkInd n' <> ":" <> cont2 zs
putValue' zs
| Comment com : rest <- zs = goComment n' False FlowOut com (putValue' rest)
| otherwise = go n' False FlowIn zs g
goSeq _ sol _ anc tag _ (SequenceEnd : rest) cont = pfx $ "[]\n" <> cont rest
where
pfx cont' = wsSol sol <> anchorTag'' (Right ws) anc tag cont'
goSeq n sol c anc tag Block xs cont = case c of
BlockOut -> anchorTag'' (Left ws) anc tag (eol <> if isComEv xs then "-" <> eol <> f xs else g xs)
BlockIn
| Comment com: rest <- xs -> wsSol sol <> anchorTag'' (Right (eol <> mkInd n')) anc tag ("-" <> ws <> goComment 0 True BlockIn com (f rest))
| otherwise -> wsSol sol <> anchorTag'' (Right (eol <> mkInd n')) anc tag ("-" <> go n' False BlockIn xs g)
BlockKey -> error "sequence in block-key context not supported"
_ -> error "Invalid Context in Block style"
where
n' | BlockOut <- c = max 0 (n - 1)
| otherwise = n
g (Comment com: rest) = goComment n' True BlockIn com (g rest)
g (SequenceEnd : rest) = cont rest
g ys = mkInd n' <> "-" <> go n' False BlockIn ys g
f (Comment com: rest) = goComment n' True BlockIn com (f rest)
f (SequenceEnd : rest) = cont rest
f ys = ws <> mkInd n' <> go n' False BlockIn ys g
goSeq n sol c anc tag Flow xs cont =
wsSol sol <> anchorTag'' (Right ws) anc tag ("[" <> f xs)
where
f (Comment com: rest) = eol <> wsSol sol <> goComment n' True (inFlow c) com (f rest)
f (SequenceEnd : rest) = eol <> wsSol sol <> mkInd (n - 1) <> "]" <> doEol <> cont rest
f ys = eol <> mkInd n' <> go n' False (inFlow c) ys g
n' = n + 1
doEol = case c of
FlowKey -> mempty
FlowIn -> mempty
_ -> eol
g (Comment com: rest) = "," <> eol <> wsSol sol <> goComment n' True (inFlow c) com (f rest)
g (SequenceEnd : rest) = eol <> wsSol sol <> mkInd (n - 1) <> "]" <> doEol <> cont rest
g ys = "," <> eol <> mkInd n' <> go n' False (inFlow c) ys g
goAlias c a cont = T.B.singleton '*' <> T.B.fromText a <> sep <> cont
where
sep = case c of
BlockIn -> eol
BlockOut -> eol
BlockKey -> T.B.singleton ' '
FlowIn -> mempty
FlowOut -> eol
FlowKey -> T.B.singleton ' '
goStr :: Int -> Bool -> Context -> Maybe Anchor -> Tag -> ScalarStyle -> Text -> T.B.Builder -> T.B.Builder
goStr !n !sol c anc tag sty t cont = case sty of
| t == "" -> case () of
| sol -> anchorTag0 anc tag (if c == BlockKey || c == FlowKey then ws <> cont else contEol)
| BlockKey <- c -> anchorTag0 anc tag (ws <> cont)
| FlowKey <- c -> anchorTag0 anc tag (ws <> cont)
| otherwise -> anchorTag'' (Left ws) anc tag contEol
Plain -> pfx $
let h [] = contEol
h (x:xs) = T.B.fromText x <> f' xs
where
f' [] = contEol
f' (y:ys) = eol <> mkInd (n+1) <> T.B.fromText y <> f' ys
FIXME : unquoted plain - strings ca n't handle leading / trailing whitespace properly
FIXME : leading white - space ( i.e. SPC ) before / after LF
DoubleQuoted -> pfx $ T.B.singleton '"' <> T.B.fromText (escapeDQ t) <> T.B.singleton '"' <> contEol
Folded chm iden -> pfx $ ">" <> goChomp chm <> goDigit iden <> g (insFoldNls' $ T.lines t) (fromEnum iden) cont
Literal chm iden -> pfx $ "|" <> goChomp chm <> goDigit iden <> g (T.lines t) (fromEnum iden) cont
where
goDigit :: IndentOfs -> T.B.Builder
goDigit iden = let ch = C.intToDigit.fromEnum $ iden
in if(ch == '0') then mempty else T.B.singleton ch
goChomp :: Chomp -> T.B.Builder
goChomp chm = case chm of
Strip -> T.B.singleton '-'
Clip -> mempty
Keep -> T.B.singleton '+'
pfx cont' = (if sol || c == BlockKey || c == FlowKey then mempty else ws) <> anchorTag'' (Right ws) anc tag cont'
doEol = case c of
BlockKey -> False
FlowKey -> False
FlowIn -> False
_ -> True
contEol
| doEol = eol <> cont
| otherwise = cont
g [] _ cont' = eol <> cont'
g (x:xs) dig cont'
| T.null x = eol <> g xs dig cont'
| dig == 0 = eol <> (if n > 0 then mkInd n else mkInd' 1) <> T.B.fromText x <> g xs dig cont'
| otherwise = eol <> mkInd (n-1) <> mkInd' dig <> T.B.fromText x <> g xs dig cont'
g' [] cont' = cont'
g' (x:xs) cont' = eol <> mkInd (n+1) <> T.B.fromText x <> g' xs cont'
f [] cont' = cont'
f (x:xs) cont' = T.B.fromText x <> g' xs cont'
isSmallKey (Alias _ : _) = True
isSmallKey (Scalar _ _ (Folded _ _) _: _) = False
isSmallKey (Scalar _ _ (Literal _ _) _: _) = False
isSmallKey (Scalar _ _ _ _ : _) = True
isSmallKey (SequenceStart _ _ _ : _) = False
isSmallKey (MappingStart _ _ _ : _) = False
isSmallKey _ = False
inFlow c = case c of
FlowIn -> FlowIn
FlowOut -> FlowIn
BlockKey -> FlowKey
FlowKey -> FlowKey
_ -> error "Invalid context in Flow style"
putTag t cont
| Just t' <- T.stripPrefix "tag:yaml.org,2002:" t = "!!" <> T.B.fromText t' <> cont
| "!" `T.isPrefixOf` t = T.B.fromText t <> cont
| otherwise = "!<" <> T.B.fromText t <> T.B.singleton '>' <> cont
anchorTag'' :: Either T.B.Builder T.B.Builder -> Maybe Anchor -> Tag -> T.B.Builder -> T.B.Builder
anchorTag'' _ Nothing (Tag Nothing) cont = cont
anchorTag'' (Right pad) Nothing (Tag (Just t)) cont = putTag t (pad <> cont)
anchorTag'' (Right pad) (Just a) (Tag Nothing) cont = T.B.singleton '&' <> T.B.fromText a <> pad <> cont
anchorTag'' (Right pad) (Just a) (Tag (Just t)) cont = T.B.singleton '&' <> T.B.fromText a <> T.B.singleton ' ' <> putTag t (pad <> cont)
anchorTag'' (Left pad) Nothing (Tag (Just t)) cont = pad <> putTag t cont
anchorTag'' (Left pad) (Just a) (Tag Nothing) cont = pad <> T.B.singleton '&' <> T.B.fromText a <> cont
anchorTag'' (Left pad) (Just a) (Tag (Just t)) cont = pad <> T.B.singleton '&' <> T.B.fromText a <> T.B.singleton ' ' <> putTag t cont
anchorTag0 = anchorTag'' (Left mempty)
anchorTag = anchorTag '' ( Right ( T.B.singleton ' ' ) )
anchorTag ' = anchorTag '' ( Left ( T.B.singleton ' ' ) )
isComEv :: [Event] -> Bool
isComEv (Comment _: _) = True
isComEv _ = False
mkInd :: Int -> T.B.Builder
mkInd (-1) = mempty
mkInd 0 = mempty
mkInd 1 = " "
mkInd 2 = " "
mkInd 3 = " "
mkInd 4 = " "
mkInd l
| l < 0 = error (show l)
| otherwise = T.B.fromText (T.replicate l " ")
mkInd' :: Int -> T.B.Builder
mkInd' 1 = " "
mkInd' 2 = " "
mkInd' 3 = " "
mkInd' 4 = " "
mkInd' 5 = " "
mkInd' 6 = " "
mkInd' 7 = " "
mkInd' 8 = " "
mkInd' 9 = " "
mkInd' l = error ("Impossible Indentation-level" ++ show l)
eol, ws:: T.B.Builder
eol = T.B.singleton '\n'
ws = T.B.singleton ' '
wsSol :: Bool -> T.B.Builder
wsSol sol = if sol then mempty else ws
escapeDQ :: Text -> Text
escapeDQ t
| T.all (\c -> C.isPrint c && c /= '\\' && c /= '"') t = t
| otherwise = T.concatMap escapeChar t
escapeChar :: Char -> Text
escapeChar c
| c == '\\' = "\\\\"
| c == '"' = "\\\""
| C.isPrint c = T.singleton c
| Just e <- Map.lookup c emap = e
| x <= 0xff = T.pack (printf "\\x%02x" x)
| x <= 0xffff = T.pack (printf "\\u%04x" x)
| otherwise = T.pack (printf "\\U%08x" x)
where
x = ord c
emap = Map.fromList [ (v,T.pack ['\\',k]) | (k,v) <- escapes ]
escapes :: [(Char,Char)]
escapes =
[ ('0', '\0')
, ('a', '\x7')
, ('b', '\x8')
, ('\x9', '\x9')
, ('t', '\x9')
, ('n', '\xa')
, ('v', '\xb')
, ('f', '\xc')
, ('r', '\xd')
, ('e', '\x1b')
, (' ', ' ')
, ('"', '"')
, ('/', '/')
, ('\\', '\\')
, ('N', '\x85')
, ('_', '\xa0')
, ('L', '\x2028')
, ('P', '\x2029')
]
insFoldNls :: [Text] -> [Text]
insFoldNls [] = []
insFoldNls z0@(z:zs)
| otherwise = z : go zs
where
go [] = []
go (l:ls)
| T.null l = l : go' ls
| otherwise = "" : l : go ls
go' [] = [""]
go' (l:ls)
| T.null l = l : go' ls
| otherwise = "" : l : go ls
insFoldNls' :: [Text] -> [Text]
insFoldNls' = go'
where
go [] = []
go (l:ls)
| T.null l = l : go ls
| isWhite (T.head l) = l : go' ls
| otherwise = "" : l : go ls
go' [] = []
go' (l:ls)
| T.null l = l : go' ls
| isWhite (T.head l) = l : go' ls
| otherwise = l : go ls
@s - white@
isWhite :: Char -> Bool
isWhite ' ' = True
isWhite '\t' = True
isWhite _ = False
|
e12c6fba9fd67239305aea0374a07098f364a7385291fa054e585a48896b2f25
|
kongeor/evolduo-app
|
stats.clj
|
(ns evolduo-app.controllers.stats
(:require [evolduo-app.response :as r]
[evolduo-app.views.stats :as view]))
(defn stats
[req]
(r/render-html view/stats req))
| null |
https://raw.githubusercontent.com/kongeor/evolduo-app/ecc72cb089f7b63690ba6d66c58aabca52b7620c/src/evolduo_app/controllers/stats.clj
|
clojure
|
(ns evolduo-app.controllers.stats
(:require [evolduo-app.response :as r]
[evolduo-app.views.stats :as view]))
(defn stats
[req]
(r/render-html view/stats req))
|
|
9d190c2dbbd31af53798582180ad062d1511f5c9f9dbd74ed988a42fa31e082d
|
nmattia/niv
|
Cmd.hs
|
{-# LANGUAGE Arrows #-}
# LANGUAGE LambdaCase #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE QuasiQuotes #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TupleSections #
# LANGUAGE ViewPatterns #
module Niv.Local.Cmd where
import Control.Arrow
import qualified Data.Aeson as Aeson
import qualified Data.Aeson.Key as K
import qualified Data.Aeson.KeyMap as KM
import qualified Data.Text as T
import Niv.Cmd
import Niv.Sources
import Niv.Update
import qualified Options.Applicative as Opts
import qualified Options.Applicative.Help.Pretty as Opts
localCmd :: Cmd
localCmd =
Cmd
{ description = describeLocal,
parseCmdShortcut = parseLocalShortcut,
parsePackageSpec = parseLocalPackageSpec,
updateCmd = proc () -> do
useOrSet "type" -< ("local" :: Box T.Text)
returnA -< (),
name = "local",
extraLogs = const []
}
parseLocalShortcut :: T.Text -> Maybe (PackageName, Aeson.Object)
parseLocalShortcut txt =
if (T.isPrefixOf "./" txt || T.isPrefixOf "/" txt)
then do
let n = last $ T.splitOn "/" txt
Just (PackageName n, KM.fromList [("path", Aeson.String txt)])
else Nothing
parseLocalPackageSpec :: Opts.Parser PackageSpec
parseLocalPackageSpec = PackageSpec . KM.fromList <$> parseParams
where
parseParams :: Opts.Parser [(K.Key, Aeson.Value)]
parseParams = maybe [] pure <$> Opts.optional parsePath
parsePath =
("path",) . Aeson.String
<$> Opts.strOption
( Opts.long "path"
<> Opts.metavar "PATH"
)
describeLocal :: Opts.InfoMod a
describeLocal =
mconcat
[ Opts.fullDesc,
Opts.progDesc "Add a local dependency. Experimental.",
Opts.headerDoc $
Just $
"Examples:"
Opts.<$$> ""
Opts.<$$> " niv add local ./foo/bar"
]
| null |
https://raw.githubusercontent.com/nmattia/niv/2998a663d03ef9521585f67cf8fdfa8dac348462/src/Niv/Local/Cmd.hs
|
haskell
|
# LANGUAGE Arrows #
# LANGUAGE OverloadedStrings #
|
# LANGUAGE LambdaCase #
# LANGUAGE QuasiQuotes #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TupleSections #
# LANGUAGE ViewPatterns #
module Niv.Local.Cmd where
import Control.Arrow
import qualified Data.Aeson as Aeson
import qualified Data.Aeson.Key as K
import qualified Data.Aeson.KeyMap as KM
import qualified Data.Text as T
import Niv.Cmd
import Niv.Sources
import Niv.Update
import qualified Options.Applicative as Opts
import qualified Options.Applicative.Help.Pretty as Opts
localCmd :: Cmd
localCmd =
Cmd
{ description = describeLocal,
parseCmdShortcut = parseLocalShortcut,
parsePackageSpec = parseLocalPackageSpec,
updateCmd = proc () -> do
useOrSet "type" -< ("local" :: Box T.Text)
returnA -< (),
name = "local",
extraLogs = const []
}
parseLocalShortcut :: T.Text -> Maybe (PackageName, Aeson.Object)
parseLocalShortcut txt =
if (T.isPrefixOf "./" txt || T.isPrefixOf "/" txt)
then do
let n = last $ T.splitOn "/" txt
Just (PackageName n, KM.fromList [("path", Aeson.String txt)])
else Nothing
parseLocalPackageSpec :: Opts.Parser PackageSpec
parseLocalPackageSpec = PackageSpec . KM.fromList <$> parseParams
where
parseParams :: Opts.Parser [(K.Key, Aeson.Value)]
parseParams = maybe [] pure <$> Opts.optional parsePath
parsePath =
("path",) . Aeson.String
<$> Opts.strOption
( Opts.long "path"
<> Opts.metavar "PATH"
)
describeLocal :: Opts.InfoMod a
describeLocal =
mconcat
[ Opts.fullDesc,
Opts.progDesc "Add a local dependency. Experimental.",
Opts.headerDoc $
Just $
"Examples:"
Opts.<$$> ""
Opts.<$$> " niv add local ./foo/bar"
]
|
949acc65b485e254375f65124ec92457b3f5f2a44b8830e21f78b7d9abe0ebe7
|
webyrd/miniKanren-uncourse
|
mk-chicken.scm
|
28 November 02014 WEB
;;;
;;; * Fixed missing unquote before E in 'drop-Y-b/c-dup-var'
;;;
;;; * Updated 'rem-xx-from-d' to check against other constraints after
;;; unification, in order to remove redundant disequality constraints
subsumed by absento constraints .
newer version : Sept. 18 2013 ( with eigens )
, , and
;;; E = (e* . x*)*, where e* is a list of eigens and x* is a list of variables.
;;; Each e in e* is checked for any of its eigens be in any of its x*. Then it fails.
;;; Since eigen-occurs-check is chasing variables, we might as will do a memq instead
;;; of an eq? when an eigen is found through a chain of walks. See eigen-occurs-check.
;;; All the e* must be the eigens created as part of a single eigen. The reifier just
abandons E , if it succeeds . If there is no failure by then , there were no eigen
;;; violations.
(define (list-sort x y) (sort y x))
(define (exists p l)
(if (null? l)
#f
(if (p (car l))
#t
(exists p (cdr l)))))
(define (find p l)
(if (null? l)
#f
(if (p (car l))
(car l)
(find p (cdr l)))))
(define (remp p l)
(if (null? l)
'()
(if (p (car l))
(cons (car l) (remp p (cdr l)))
(remp p (cdr l)))))
;;(define sort list-sort)
(define empty-c '(() () () () () () ()))
(define eigen-tag (vector 'eigen-tag))
(define-syntax inc
(syntax-rules ()
((_ e) (lambdaf@ () e))))
(define-syntax lambdaf@
(syntax-rules ()
((_ () e) (lambda () e))))
(define-syntax lambdag@
(syntax-rules (:)
((_ (c) e) (lambda (c) e))
((_ (c : B E S) e)
(lambda (c)
(let ((B (c->B c)) (E (c->E c)) (S (c->S c)))
e)))
((_ (c : B E S D Y N T) e)
(lambda (c)
(let ((B (c->B c)) (E (c->E c)) (S (c->S c)) (D (c->D c))
(Y (c->Y c)) (N (c->N c)) (T (c->T c)))
e)))))
(define rhs
(lambda (pr)
(cdr pr)))
(define lhs
(lambda (pr)
(car pr)))
(define eigen-var
(lambda ()
(vector eigen-tag)))
(define eigen?
(lambda (x)
(and (vector? x) (eq? (vector-ref x 0) eigen-tag))))
(define var
(lambda (dummy)
(vector dummy)))
(define var?
(lambda (x)
(and (vector? x) (not (eq? (vector-ref x 0) eigen-tag)))))
(define walk
(lambda (u S)
(cond
((and (var? u) (assq u S)) =>
(lambda (pr) (walk (rhs pr) S)))
(else u))))
(define prefix-S
(lambda (S+ S)
(cond
((eq? S+ S) '())
(else (cons (car S+)
(prefix-S (cdr S+) S))))))
(define unify
(lambda (u v s)
(let ((u (walk u s))
(v (walk v s)))
(cond
((eq? u v) s)
((var? u) (ext-s-check u v s))
((var? v) (ext-s-check v u s))
((and (pair? u) (pair? v))
(let ((s (unify (car u) (car v) s)))
(and s (unify (cdr u) (cdr v) s))))
((or (eigen? u) (eigen? v)) #f)
((equal? u v) s)
(else #f)))))
(define occurs-check
(lambda (x v s)
(let ((v (walk v s)))
(cond
((var? v) (eq? v x))
((pair? v)
(or
(occurs-check x (car v) s)
(occurs-check x (cdr v) s)))
(else #f)))))
(define eigen-occurs-check
(lambda (e* x s)
(let ((x (walk x s)))
(cond
((var? x) #f)
((eigen? x) (memq x e*))
((pair? x)
(or
(eigen-occurs-check e* (car x) s)
(eigen-occurs-check e* (cdr x) s)))
(else #f)))))
(define empty-f (lambdaf@ () (mzero)))
(define ext-s-check
(lambda (x v s)
(cond
((occurs-check x v s) #f)
(else (cons `(,x . ,v) s)))))
(define unify*
(lambda (S+ S)
(unify (map lhs S+) (map rhs S+) S)))
(define-syntax case-inf
(syntax-rules ()
((_ e (() e0) ((f^) e1) ((c^) e2) ((c f) e3))
(let ((c-inf e))
(cond
((not c-inf) e0)
((procedure? c-inf) (let ((f^ c-inf)) e1))
((not (and (pair? c-inf)
(procedure? (cdr c-inf))))
(let ((c^ c-inf)) e2))
(else (let ((c (car c-inf)) (f (cdr c-inf)))
e3)))))))
(define-syntax fresh
(syntax-rules ()
((_ (x ...) g0 g ...)
(lambdag@ (c : B E S D Y N T)
(inc
(let ((x (var 'x)) ...)
(let ((B (append `(,x ...) B)))
(bind* (g0 `(,B ,E ,S ,D ,Y ,N ,T)) g ...))))))))
(define-syntax eigen
(syntax-rules ()
((_ (x ...) g0 g ...)
(lambdag@ (c : B E S)
(let ((x (eigen-var)) ...)
((fresh () (eigen-absento `(,x ...) B) g0 g ...) c))))))
(define-syntax bind*
(syntax-rules ()
((_ e) e)
((_ e g0 g ...) (bind* (bind e g0) g ...))))
(define bind
(lambda (c-inf g)
(case-inf c-inf
(() (mzero))
((f) (inc (bind (f) g)))
((c) (g c))
((c f) (mplus (g c) (lambdaf@ () (bind (f) g)))))))
(define-syntax run
(syntax-rules ()
((_ n (q) g0 g ...)
(take n
(lambdaf@ ()
((fresh (q) g0 g ...
(lambdag@ (final-c)
(let ((z ((reify q) final-c)))
(choice z empty-f))))
empty-c))))
((_ n (q0 q1 q ...) g0 g ...)
(run n (x) (fresh (q0 q1 q ...) g0 g ... (== `(,q0 ,q1 ,q ...) x))))))
(define-syntax run*
(syntax-rules ()
((_ (q0 q ...) g0 g ...) (run #f (q0 q ...) g0 g ...))))
(define take
(lambda (n f)
(cond
((and n (zero? n)) '())
(else
(case-inf (f)
(() '())
((f) (take n f))
((c) (cons c '()))
((c f) (cons c
(take (and n (- n 1)) f))))))))
(define-syntax conde
(syntax-rules ()
((_ (g0 g ...) (g1 g^ ...) ...)
(lambdag@ (c)
(inc
(mplus*
(bind* (g0 c) g ...)
(bind* (g1 c) g^ ...) ...))))))
(define-syntax mplus*
(syntax-rules ()
((_ e) e)
((_ e0 e ...) (mplus e0
(lambdaf@ () (mplus* e ...))))))
(define mplus
(lambda (c-inf f)
(case-inf c-inf
(() (f))
((f^) (inc (mplus (f) f^)))
((c) (choice c f))
((c f^) (choice c (lambdaf@ () (mplus (f) f^)))))))
(define c->B (lambda (c) (car c)))
(define c->E (lambda (c) (cadr c)))
(define c->S (lambda (c) (caddr c)))
(define c->D (lambda (c) (cadddr c)))
(define c->Y (lambda (c) (cadddr (cdr c))))
(define c->N (lambda (c) (cadddr (cddr c))))
(define c->T (lambda (c) (cadddr (cdddr c))))
(define-syntax conda
(syntax-rules ()
((_ (g0 g ...) (g1 g^ ...) ...)
(lambdag@ (c)
(inc
(ifa ((g0 c) g ...)
((g1 c) g^ ...) ...))))))
(define-syntax ifa
(syntax-rules ()
((_) (mzero))
((_ (e g ...) b ...)
(let loop ((c-inf e))
(case-inf c-inf
(() (ifa b ...))
((f) (inc (loop (f))))
((a) (bind* c-inf g ...))
((a f) (bind* c-inf g ...)))))))
(define-syntax condu
(syntax-rules ()
((_ (g0 g ...) (g1 g^ ...) ...)
(lambdag@ (c)
(inc
(ifu ((g0 c) g ...)
((g1 c) g^ ...) ...))))))
(define-syntax ifu
(syntax-rules ()
((_) (mzero))
((_ (e g ...) b ...)
(let loop ((c-inf e))
(case-inf c-inf
(() (ifu b ...))
((f) (inc (loop (f))))
((c) (bind* c-inf g ...))
((c f) (bind* (unit c) g ...)))))))
(define mzero (lambda () #f))
(define unit (lambda (c) c))
(define choice (lambda (c f) (cons c f)))
(define tagged?
(lambda (S Y y^)
(exists (lambda (y) (eqv? (walk y S) y^)) Y)))
(define untyped-var?
(lambda (S Y N t^)
(let ((in-type? (lambda (y) (eq? (walk y S) t^))))
(and (var? t^)
(not (exists in-type? Y))
(not (exists in-type? N))))))
(define-syntax project
(syntax-rules ()
((_ (x ...) g g* ...)
(lambdag@ (c : B E S)
(let ((x (walk* x S)) ...)
((fresh () g g* ...) c))))))
(define walk*
(lambda (v S)
(let ((v (walk v S)))
(cond
((var? v) v)
((pair? v)
(cons (walk* (car v) S) (walk* (cdr v) S)))
(else v)))))
(define reify-S
(lambda (v S)
(let ((v (walk v S)))
(cond
((var? v)
(let ((n (length S)))
(let ((name (reify-name n)))
(cons `(,v . ,name) S))))
((pair? v)
(let ((S (reify-S (car v) S)))
(reify-S (cdr v) S)))
(else S)))))
(define reify-name
(lambda (n)
(string->symbol
(string-append "_" "." (number->string n)))))
(define drop-dot
(lambda (X)
(map (lambda (t)
(let ((a (lhs t))
(d (rhs t)))
`(,a ,d)))
X)))
(define sorter
(lambda (ls)
(list-sort lex<=? ls)))
(define lex<=?
(lambda (x y)
(string<=? (datum->string x) (datum->string y))))
(define datum->string
(lambda (x)
(call-with-string-output-port
(lambda (p) (display x p)))))
(define anyvar?
(lambda (u r)
(cond
((pair? u)
(or (anyvar? (car u) r)
(anyvar? (cdr u) r)))
(else (var? (walk u r))))))
(define anyeigen?
(lambda (u r)
(cond
((pair? u)
(or (anyeigen? (car u) r)
(anyeigen? (cdr u) r)))
(else (eigen? (walk u r))))))
(define member*
(lambda (u v)
(cond
((equal? u v) #t)
((pair? v)
(or (member* u (car v)) (member* u (cdr v))))
(else #f))))
;;;
(define drop-N-b/c-const
(lambdag@ (c : B E S D Y N T)
(let ((const? (lambda (n)
(not (var? (walk n S))))))
(cond
((find const? N) =>
(lambda (n) `(,B ,E ,S ,D ,Y ,(remq1 n N) ,T)))
(else c)))))
(define drop-Y-b/c-const
(lambdag@ (c : B E S D Y N T)
(let ((const? (lambda (y)
(not (var? (walk y S))))))
(cond
((find const? Y) =>
(lambda (y) `(,B ,E ,S ,D ,(remq1 y Y) ,N ,T)))
(else c)))))
(define remq1
(lambda (elem ls)
(cond
((null? ls) '())
((eq? (car ls) elem) (cdr ls))
(else (cons (car ls) (remq1 elem (cdr ls)))))))
(define same-var?
(lambda (v)
(lambda (v^)
(and (var? v) (var? v^) (eq? v v^)))))
(define find-dup
(lambda (f S)
(lambda (set)
(let loop ((set^ set))
(cond
((null? set^) #f)
(else
(let ((elem (car set^)))
(let ((elem^ (walk elem S)))
(cond
((find (lambda (elem^^)
((f elem^) (walk elem^^ S)))
(cdr set^))
elem)
(else (loop (cdr set^))))))))))))
(define drop-N-b/c-dup-var
(lambdag@ (c : B E S D Y N T)
(cond
(((find-dup same-var? S) N) =>
(lambda (n) `(,B ,E ,S ,D ,Y ,(remq1 n N) ,T)))
(else c))))
(define drop-Y-b/c-dup-var
(lambdag@ (c : B E S D Y N T)
(cond
(((find-dup same-var? S) Y) =>
(lambda (y)
`(,B ,E ,S ,D ,(remq1 y Y) ,N ,T)))
(else c))))
(define var-type-mismatch?
(lambda (S Y N t1^ t2^)
(cond
((num? S N t1^) (not (num? S N t2^)))
((sym? S Y t1^) (not (sym? S Y t2^)))
(else #f))))
(define term-ununifiable?
(lambda (S Y N t1 t2)
(let ((t1^ (walk t1 S))
(t2^ (walk t2 S)))
(cond
((or (untyped-var? S Y N t1^) (untyped-var? S Y N t2^)) #f)
((var? t1^) (var-type-mismatch? S Y N t1^ t2^))
((var? t2^) (var-type-mismatch? S Y N t2^ t1^))
((and (pair? t1^) (pair? t2^))
(or (term-ununifiable? S Y N (car t1^) (car t2^))
(term-ununifiable? S Y N (cdr t1^) (cdr t2^))))
(else (not (eqv? t1^ t2^)))))))
(define T-term-ununifiable?
(lambda (S Y N)
(lambda (t1)
(let ((t1^ (walk t1 S)))
(letrec
((t2-check
(lambda (t2)
(let ((t2^ (walk t2 S)))
(cond
((pair? t2^) (and
(term-ununifiable? S Y N t1^ t2^)
(t2-check (car t2^))
(t2-check (cdr t2^))))
(else (term-ununifiable? S Y N t1^ t2^)))))))
t2-check)))))
(define num?
(lambda (S N n)
(let ((n (walk n S)))
(cond
((var? n) (tagged? S N n))
(else (number? n))))))
(define sym?
(lambda (S Y y)
(let ((y (walk y S)))
(cond
((var? y) (tagged? S Y y))
(else (symbol? y))))))
(define drop-T-b/c-Y-and-N
(lambdag@ (c : B E S D Y N T)
(let ((drop-t? (T-term-ununifiable? S Y N)))
(cond
((find (lambda (t) ((drop-t? (lhs t)) (rhs t))) T) =>
(lambda (t) `(,B ,E ,S ,D ,Y ,N ,(remq1 t T))))
(else c)))))
(define move-T-to-D-b/c-t2-atom
(lambdag@ (c : B E S D Y N T)
(cond
((exists (lambda (t)
(let ((t2^ (walk (rhs t) S)))
(cond
((and (not (untyped-var? S Y N t2^))
(not (pair? t2^)))
(let ((T (remq1 t T)))
`(,B ,E ,S ((,t) . ,D) ,Y ,N ,T)))
(else #f))))
T))
(else c))))
(define terms-pairwise=?
(lambda (pr-a^ pr-d^ t-a^ t-d^ S)
(or
(and (term=? pr-a^ t-a^ S)
(term=? pr-d^ t-a^ S))
(and (term=? pr-a^ t-d^ S)
(term=? pr-d^ t-a^ S)))))
(define T-superfluous-pr?
(lambda (S Y N T)
(lambda (pr)
(let ((pr-a^ (walk (lhs pr) S))
(pr-d^ (walk (rhs pr) S)))
(cond
((exists
(lambda (t)
(let ((t-a^ (walk (lhs t) S))
(t-d^ (walk (rhs t) S)))
(terms-pairwise=? pr-a^ pr-d^ t-a^ t-d^ S)))
T)
(for-all
(lambda (t)
(let ((t-a^ (walk (lhs t) S))
(t-d^ (walk (rhs t) S)))
(or
(not (terms-pairwise=? pr-a^ pr-d^ t-a^ t-d^ S))
(untyped-var? S Y N t-d^)
(pair? t-d^))))
T))
(else #f))))))
(define drop-from-D-b/c-T
(lambdag@ (c : B E S D Y N T)
(cond
((find
(lambda (d)
(exists
(T-superfluous-pr? S Y N T)
d))
D) =>
(lambda (d) `(,B ,E ,S ,(remq1 d D) ,Y ,N ,T)))
(else c))))
(define drop-t-b/c-t2-occurs-t1
(lambdag@ (c : B E S D Y N T)
(cond
((find (lambda (t)
(let ((t-a^ (walk (lhs t) S))
(t-d^ (walk (rhs t) S)))
(mem-check t-d^ t-a^ S)))
T) =>
(lambda (t)
`(,B ,E ,S ,D ,Y ,N ,(remq1 t T))))
(else c))))
(define split-t-move-to-d-b/c-pair
(lambdag@ (c : B E S D Y N T)
(cond
((exists
(lambda (t)
(let ((t2^ (walk (rhs t) S)))
(cond
((pair? t2^) (let ((ta `(,(lhs t) . ,(car t2^)))
(td `(,(lhs t) . ,(cdr t2^))))
(let ((T `(,ta ,td . ,(remq1 t T))))
`(,B ,E ,S ((,t) . ,D) ,Y ,N ,T))))
(else #f))))
T))
(else c))))
(define find-d-conflict
(lambda (S Y N)
(lambda (D)
(find
(lambda (d)
(exists (lambda (pr)
(term-ununifiable? S Y N (lhs pr) (rhs pr)))
d))
D))))
(define drop-D-b/c-Y-or-N
(lambdag@ (c : B E S D Y N T)
(cond
(((find-d-conflict S Y N) D) =>
(lambda (d) `(,B ,E ,S ,(remq1 d D) ,Y ,N ,T)))
(else c))))
(define cycle
(lambdag@ (c)
(let loop ((c^ c)
(fns^ (LOF))
(n (length (LOF))))
(cond
((zero? n) c^)
((null? fns^) (loop c^ (LOF) n))
(else
(let ((c^^ ((car fns^) c^)))
(cond
((not (eq? c^^ c^))
(loop c^^ (cdr fns^) (length (LOF))))
(else (loop c^ (cdr fns^) (sub1 n))))))))))
(define absento
(lambda (u v)
(lambdag@ (c : B E S D Y N T)
(cond
[(mem-check u v S) (mzero)]
[else (unit `(,B ,E ,S ,D ,Y ,N ((,u . ,v) . ,T)))]))))
(define eigen-absento
(lambda (e* x*)
(lambdag@ (c : B E S D Y N T)
(cond
[(eigen-occurs-check e* x* S) (mzero)]
[else (unit `(,B ((,e* . ,x*) . ,E) ,S ,D ,Y ,N ,T))]))))
(define mem-check
(lambda (u t S)
(let ((t (walk t S)))
(cond
((pair? t)
(or (term=? u t S)
(mem-check u (car t) S)
(mem-check u (cdr t) S)))
(else (term=? u t S))))))
(define term=?
(lambda (u t S)
(cond
((unify u t S) =>
(lambda (S0)
(eq? S0 S)))
(else #f))))
(define ground-non-<type>?
(lambda (pred)
(lambda (u S)
(let ((u (walk u S)))
(cond
((var? u) #f)
(else (not (pred u))))))))
;; moved
(define ground-non-symbol?
(ground-non-<type>? symbol?))
(define ground-non-number?
(ground-non-<type>? number?))
(define symbolo
(lambda (u)
(lambdag@ (c : B E S D Y N T)
(cond
[(ground-non-symbol? u S) (mzero)]
[(mem-check u N S) (mzero)]
[else (unit `(,B ,E ,S ,D (,u . ,Y) ,N ,T))]))))
(define numbero
(lambda (u)
(lambdag@ (c : B E S D Y N T)
(cond
[(ground-non-number? u S) (mzero)]
[(mem-check u Y S) (mzero)]
[else (unit `(,B ,E ,S ,D ,Y (,u . ,N) ,T))]))))
;; end moved
(define =/= ;; moved
(lambda (u v)
(lambdag@ (c : B E S D Y N T)
(cond
((unify u v S) =>
(lambda (S0)
(let ((pfx (prefix-S S0 S)))
(cond
((null? pfx) (mzero))
(else (unit `(,B ,E ,S (,pfx . ,D) ,Y ,N ,T)))))))
(else c)))))
(define ==
(lambda (u v)
(lambdag@ (c : B E S D Y N T)
(cond
((unify u v S) =>
(lambda (S0)
(cond
((==fail-check B E S0 D Y N T) (mzero))
(else (unit `(,B ,E ,S0 ,D ,Y ,N ,T))))))
(else (mzero))))))
(define succeed (== #f #f))
(define fail (== #f #t))
(define ==fail-check
(lambda (B E S0 D Y N T)
(cond
((eigen-absento-fail-check E S0) #t)
((atomic-fail-check S0 Y ground-non-symbol?) #t)
((atomic-fail-check S0 N ground-non-number?) #t)
((symbolo-numbero-fail-check S0 Y N) #t)
((=/=-fail-check S0 D) #t)
((absento-fail-check S0 T) #t)
(else #f))))
(define eigen-absento-fail-check
(lambda (E S0)
(exists (lambda (e*/x*) (eigen-occurs-check (car e*/x*) (cdr e*/x*) S0)) E)))
(define atomic-fail-check
(lambda (S A pred)
(exists (lambda (a) (pred (walk a S) S)) A)))
(define symbolo-numbero-fail-check
(lambda (S A N)
(let ((N (map (lambda (n) (walk n S)) N)))
(exists (lambda (a) (exists (same-var? (walk a S)) N))
A))))
(define absento-fail-check
(lambda (S T)
(exists (lambda (t) (mem-check (lhs t) (rhs t) S)) T)))
(define =/=-fail-check
(lambda (S D)
(exists (d-fail-check S) D)))
(define d-fail-check
(lambda (S)
(lambda (d)
(cond
((unify* d S) =>
(lambda (S+) (eq? S+ S)))
(else #f)))))
(define reify
(lambda (x)
(lambda (c)
(let ((c (cycle c)))
(let* ((S (c->S c))
(D (walk* (c->D c) S))
(Y (walk* (c->Y c) S))
(N (walk* (c->N c) S))
(T (walk* (c->T c) S)))
(let ((v (walk* x S)))
(let ((R (reify-S v '())))
(reify+ v R
(let ((D (remp
(lambda (d)
(let ((dw (walk* d S)))
(or
(anyvar? dw R)
(anyeigen? dw R))))
(rem-xx-from-d c))))
(rem-subsumed D))
(remp
(lambda (y) (var? (walk y R)))
Y)
(remp
(lambda (n) (var? (walk n R)))
N)
(remp (lambda (t)
(or (anyeigen? t R) (anyvar? t R))) T)))))))))
(define reify+
(lambda (v R D Y N T)
(form (walk* v R)
(walk* D R)
(walk* Y R)
(walk* N R)
(rem-subsumed-T (walk* T R)))))
(define form
(lambda (v D Y N T)
(let ((fd (sort-D D))
(fy (sorter Y))
(fn (sorter N))
(ft (sorter T)))
(let ((fd (if (null? fd) fd
(let ((fd (drop-dot-D fd)))
`((=/= . ,fd)))))
(fy (if (null? fy) fy `((sym . ,fy))))
(fn (if (null? fn) fn `((num . ,fn))))
(ft (if (null? ft) ft
(let ((ft (drop-dot ft)))
`((absento . ,ft))))))
(cond
((and (null? fd) (null? fy)
(null? fn) (null? ft))
v)
(else (append `(,v) fd fn fy ft)))))))
(define sort-D
(lambda (D)
(sorter
(map sort-d D))))
(define sort-d
(lambda (d)
(list-sort
(lambda (x y)
(lex<=? (car x) (car y)))
(map sort-pr d))))
(define drop-dot-D
(lambda (D)
(map drop-dot D)))
(define lex<-reified-name?
(lambda (r)
(char<?
(string-ref
(datum->string r) 0)
#\_)))
(define sort-pr
(lambda (pr)
(let ((l (lhs pr))
(r (rhs pr)))
(cond
((lex<-reified-name? r) pr)
((lex<=? r l) `(,r . ,l))
(else pr)))))
(define rem-subsumed
(lambda (D)
(let rem-subsumed ((D D) (d^* '()))
(cond
((null? D) d^*)
((or (subsumed? (car D) (cdr D))
(subsumed? (car D) d^*))
(rem-subsumed (cdr D) d^*))
(else (rem-subsumed (cdr D)
(cons (car D) d^*)))))))
(define subsumed?
(lambda (d d*)
(cond
((null? d*) #f)
(else
(let ((d^ (unify* (car d*) d)))
(or
(and d^ (eq? d^ d))
(subsumed? d (cdr d*))))))))
(define rem-xx-from-d
(lambdag@ (c : B E S D Y N T)
(let ((D (walk* D S)))
(remp not
(map (lambda (d)
(cond
((unify* d S) =>
(lambda (S0)
(cond
((==fail-check B E S0 '() Y N T) #f)
(else (prefix-S S0 S)))))
(else #f)))
D)))))
(define rem-subsumed-T
(lambda (T)
(let rem-subsumed ((T T) (T^ '()))
(cond
((null? T) T^)
(else
(let ((lit (lhs (car T)))
(big (rhs (car T))))
(cond
((or (subsumed-T? lit big (cdr T))
(subsumed-T? lit big T^))
(rem-subsumed (cdr T) T^))
(else (rem-subsumed (cdr T)
(cons (car T) T^))))))))))
(define subsumed-T?
(lambda (lit big T)
(cond
((null? T) #f)
(else
(let ((lit^ (lhs (car T)))
(big^ (rhs (car T))))
(or
(and (eq? big big^) (member* lit^ lit))
(subsumed-T? lit big (cdr T))))))))
(define LOF
(lambda ()
`(,drop-N-b/c-const ,drop-Y-b/c-const ,drop-Y-b/c-dup-var
,drop-N-b/c-dup-var ,drop-D-b/c-Y-or-N ,drop-T-b/c-Y-and-N
,move-T-to-D-b/c-t2-atom ,split-t-move-to-d-b/c-pair
,drop-from-D-b/c-T ,drop-t-b/c-t2-occurs-t1)))
| null |
https://raw.githubusercontent.com/webyrd/miniKanren-uncourse/19bc2903266197d6ba6c6b818e0a196ea620377b/mk-implementations/scheme/mk-chicken.scm
|
scheme
|
* Fixed missing unquote before E in 'drop-Y-b/c-dup-var'
* Updated 'rem-xx-from-d' to check against other constraints after
unification, in order to remove redundant disequality constraints
E = (e* . x*)*, where e* is a list of eigens and x* is a list of variables.
Each e in e* is checked for any of its eigens be in any of its x*. Then it fails.
Since eigen-occurs-check is chasing variables, we might as will do a memq instead
of an eq? when an eigen is found through a chain of walks. See eigen-occurs-check.
All the e* must be the eigens created as part of a single eigen. The reifier just
violations.
(define sort list-sort)
moved
end moved
moved
|
28 November 02014 WEB
subsumed by absento constraints .
newer version : Sept. 18 2013 ( with eigens )
, , and
abandons E , if it succeeds . If there is no failure by then , there were no eigen
(define (list-sort x y) (sort y x))
(define (exists p l)
(if (null? l)
#f
(if (p (car l))
#t
(exists p (cdr l)))))
(define (find p l)
(if (null? l)
#f
(if (p (car l))
(car l)
(find p (cdr l)))))
(define (remp p l)
(if (null? l)
'()
(if (p (car l))
(cons (car l) (remp p (cdr l)))
(remp p (cdr l)))))
(define empty-c '(() () () () () () ()))
(define eigen-tag (vector 'eigen-tag))
(define-syntax inc
(syntax-rules ()
((_ e) (lambdaf@ () e))))
(define-syntax lambdaf@
(syntax-rules ()
((_ () e) (lambda () e))))
(define-syntax lambdag@
(syntax-rules (:)
((_ (c) e) (lambda (c) e))
((_ (c : B E S) e)
(lambda (c)
(let ((B (c->B c)) (E (c->E c)) (S (c->S c)))
e)))
((_ (c : B E S D Y N T) e)
(lambda (c)
(let ((B (c->B c)) (E (c->E c)) (S (c->S c)) (D (c->D c))
(Y (c->Y c)) (N (c->N c)) (T (c->T c)))
e)))))
(define rhs
(lambda (pr)
(cdr pr)))
(define lhs
(lambda (pr)
(car pr)))
(define eigen-var
(lambda ()
(vector eigen-tag)))
(define eigen?
(lambda (x)
(and (vector? x) (eq? (vector-ref x 0) eigen-tag))))
(define var
(lambda (dummy)
(vector dummy)))
(define var?
(lambda (x)
(and (vector? x) (not (eq? (vector-ref x 0) eigen-tag)))))
(define walk
(lambda (u S)
(cond
((and (var? u) (assq u S)) =>
(lambda (pr) (walk (rhs pr) S)))
(else u))))
(define prefix-S
(lambda (S+ S)
(cond
((eq? S+ S) '())
(else (cons (car S+)
(prefix-S (cdr S+) S))))))
(define unify
(lambda (u v s)
(let ((u (walk u s))
(v (walk v s)))
(cond
((eq? u v) s)
((var? u) (ext-s-check u v s))
((var? v) (ext-s-check v u s))
((and (pair? u) (pair? v))
(let ((s (unify (car u) (car v) s)))
(and s (unify (cdr u) (cdr v) s))))
((or (eigen? u) (eigen? v)) #f)
((equal? u v) s)
(else #f)))))
(define occurs-check
(lambda (x v s)
(let ((v (walk v s)))
(cond
((var? v) (eq? v x))
((pair? v)
(or
(occurs-check x (car v) s)
(occurs-check x (cdr v) s)))
(else #f)))))
(define eigen-occurs-check
(lambda (e* x s)
(let ((x (walk x s)))
(cond
((var? x) #f)
((eigen? x) (memq x e*))
((pair? x)
(or
(eigen-occurs-check e* (car x) s)
(eigen-occurs-check e* (cdr x) s)))
(else #f)))))
(define empty-f (lambdaf@ () (mzero)))
(define ext-s-check
(lambda (x v s)
(cond
((occurs-check x v s) #f)
(else (cons `(,x . ,v) s)))))
(define unify*
(lambda (S+ S)
(unify (map lhs S+) (map rhs S+) S)))
(define-syntax case-inf
(syntax-rules ()
((_ e (() e0) ((f^) e1) ((c^) e2) ((c f) e3))
(let ((c-inf e))
(cond
((not c-inf) e0)
((procedure? c-inf) (let ((f^ c-inf)) e1))
((not (and (pair? c-inf)
(procedure? (cdr c-inf))))
(let ((c^ c-inf)) e2))
(else (let ((c (car c-inf)) (f (cdr c-inf)))
e3)))))))
(define-syntax fresh
(syntax-rules ()
((_ (x ...) g0 g ...)
(lambdag@ (c : B E S D Y N T)
(inc
(let ((x (var 'x)) ...)
(let ((B (append `(,x ...) B)))
(bind* (g0 `(,B ,E ,S ,D ,Y ,N ,T)) g ...))))))))
(define-syntax eigen
(syntax-rules ()
((_ (x ...) g0 g ...)
(lambdag@ (c : B E S)
(let ((x (eigen-var)) ...)
((fresh () (eigen-absento `(,x ...) B) g0 g ...) c))))))
(define-syntax bind*
(syntax-rules ()
((_ e) e)
((_ e g0 g ...) (bind* (bind e g0) g ...))))
(define bind
(lambda (c-inf g)
(case-inf c-inf
(() (mzero))
((f) (inc (bind (f) g)))
((c) (g c))
((c f) (mplus (g c) (lambdaf@ () (bind (f) g)))))))
(define-syntax run
(syntax-rules ()
((_ n (q) g0 g ...)
(take n
(lambdaf@ ()
((fresh (q) g0 g ...
(lambdag@ (final-c)
(let ((z ((reify q) final-c)))
(choice z empty-f))))
empty-c))))
((_ n (q0 q1 q ...) g0 g ...)
(run n (x) (fresh (q0 q1 q ...) g0 g ... (== `(,q0 ,q1 ,q ...) x))))))
(define-syntax run*
(syntax-rules ()
((_ (q0 q ...) g0 g ...) (run #f (q0 q ...) g0 g ...))))
(define take
(lambda (n f)
(cond
((and n (zero? n)) '())
(else
(case-inf (f)
(() '())
((f) (take n f))
((c) (cons c '()))
((c f) (cons c
(take (and n (- n 1)) f))))))))
(define-syntax conde
(syntax-rules ()
((_ (g0 g ...) (g1 g^ ...) ...)
(lambdag@ (c)
(inc
(mplus*
(bind* (g0 c) g ...)
(bind* (g1 c) g^ ...) ...))))))
(define-syntax mplus*
(syntax-rules ()
((_ e) e)
((_ e0 e ...) (mplus e0
(lambdaf@ () (mplus* e ...))))))
(define mplus
(lambda (c-inf f)
(case-inf c-inf
(() (f))
((f^) (inc (mplus (f) f^)))
((c) (choice c f))
((c f^) (choice c (lambdaf@ () (mplus (f) f^)))))))
(define c->B (lambda (c) (car c)))
(define c->E (lambda (c) (cadr c)))
(define c->S (lambda (c) (caddr c)))
(define c->D (lambda (c) (cadddr c)))
(define c->Y (lambda (c) (cadddr (cdr c))))
(define c->N (lambda (c) (cadddr (cddr c))))
(define c->T (lambda (c) (cadddr (cdddr c))))
(define-syntax conda
(syntax-rules ()
((_ (g0 g ...) (g1 g^ ...) ...)
(lambdag@ (c)
(inc
(ifa ((g0 c) g ...)
((g1 c) g^ ...) ...))))))
(define-syntax ifa
(syntax-rules ()
((_) (mzero))
((_ (e g ...) b ...)
(let loop ((c-inf e))
(case-inf c-inf
(() (ifa b ...))
((f) (inc (loop (f))))
((a) (bind* c-inf g ...))
((a f) (bind* c-inf g ...)))))))
(define-syntax condu
(syntax-rules ()
((_ (g0 g ...) (g1 g^ ...) ...)
(lambdag@ (c)
(inc
(ifu ((g0 c) g ...)
((g1 c) g^ ...) ...))))))
(define-syntax ifu
(syntax-rules ()
((_) (mzero))
((_ (e g ...) b ...)
(let loop ((c-inf e))
(case-inf c-inf
(() (ifu b ...))
((f) (inc (loop (f))))
((c) (bind* c-inf g ...))
((c f) (bind* (unit c) g ...)))))))
(define mzero (lambda () #f))
(define unit (lambda (c) c))
(define choice (lambda (c f) (cons c f)))
(define tagged?
(lambda (S Y y^)
(exists (lambda (y) (eqv? (walk y S) y^)) Y)))
(define untyped-var?
(lambda (S Y N t^)
(let ((in-type? (lambda (y) (eq? (walk y S) t^))))
(and (var? t^)
(not (exists in-type? Y))
(not (exists in-type? N))))))
(define-syntax project
(syntax-rules ()
((_ (x ...) g g* ...)
(lambdag@ (c : B E S)
(let ((x (walk* x S)) ...)
((fresh () g g* ...) c))))))
(define walk*
(lambda (v S)
(let ((v (walk v S)))
(cond
((var? v) v)
((pair? v)
(cons (walk* (car v) S) (walk* (cdr v) S)))
(else v)))))
(define reify-S
(lambda (v S)
(let ((v (walk v S)))
(cond
((var? v)
(let ((n (length S)))
(let ((name (reify-name n)))
(cons `(,v . ,name) S))))
((pair? v)
(let ((S (reify-S (car v) S)))
(reify-S (cdr v) S)))
(else S)))))
(define reify-name
(lambda (n)
(string->symbol
(string-append "_" "." (number->string n)))))
(define drop-dot
(lambda (X)
(map (lambda (t)
(let ((a (lhs t))
(d (rhs t)))
`(,a ,d)))
X)))
(define sorter
(lambda (ls)
(list-sort lex<=? ls)))
(define lex<=?
(lambda (x y)
(string<=? (datum->string x) (datum->string y))))
(define datum->string
(lambda (x)
(call-with-string-output-port
(lambda (p) (display x p)))))
(define anyvar?
(lambda (u r)
(cond
((pair? u)
(or (anyvar? (car u) r)
(anyvar? (cdr u) r)))
(else (var? (walk u r))))))
(define anyeigen?
(lambda (u r)
(cond
((pair? u)
(or (anyeigen? (car u) r)
(anyeigen? (cdr u) r)))
(else (eigen? (walk u r))))))
(define member*
(lambda (u v)
(cond
((equal? u v) #t)
((pair? v)
(or (member* u (car v)) (member* u (cdr v))))
(else #f))))
(define drop-N-b/c-const
(lambdag@ (c : B E S D Y N T)
(let ((const? (lambda (n)
(not (var? (walk n S))))))
(cond
((find const? N) =>
(lambda (n) `(,B ,E ,S ,D ,Y ,(remq1 n N) ,T)))
(else c)))))
(define drop-Y-b/c-const
(lambdag@ (c : B E S D Y N T)
(let ((const? (lambda (y)
(not (var? (walk y S))))))
(cond
((find const? Y) =>
(lambda (y) `(,B ,E ,S ,D ,(remq1 y Y) ,N ,T)))
(else c)))))
(define remq1
(lambda (elem ls)
(cond
((null? ls) '())
((eq? (car ls) elem) (cdr ls))
(else (cons (car ls) (remq1 elem (cdr ls)))))))
(define same-var?
(lambda (v)
(lambda (v^)
(and (var? v) (var? v^) (eq? v v^)))))
(define find-dup
(lambda (f S)
(lambda (set)
(let loop ((set^ set))
(cond
((null? set^) #f)
(else
(let ((elem (car set^)))
(let ((elem^ (walk elem S)))
(cond
((find (lambda (elem^^)
((f elem^) (walk elem^^ S)))
(cdr set^))
elem)
(else (loop (cdr set^))))))))))))
(define drop-N-b/c-dup-var
(lambdag@ (c : B E S D Y N T)
(cond
(((find-dup same-var? S) N) =>
(lambda (n) `(,B ,E ,S ,D ,Y ,(remq1 n N) ,T)))
(else c))))
(define drop-Y-b/c-dup-var
(lambdag@ (c : B E S D Y N T)
(cond
(((find-dup same-var? S) Y) =>
(lambda (y)
`(,B ,E ,S ,D ,(remq1 y Y) ,N ,T)))
(else c))))
(define var-type-mismatch?
(lambda (S Y N t1^ t2^)
(cond
((num? S N t1^) (not (num? S N t2^)))
((sym? S Y t1^) (not (sym? S Y t2^)))
(else #f))))
(define term-ununifiable?
(lambda (S Y N t1 t2)
(let ((t1^ (walk t1 S))
(t2^ (walk t2 S)))
(cond
((or (untyped-var? S Y N t1^) (untyped-var? S Y N t2^)) #f)
((var? t1^) (var-type-mismatch? S Y N t1^ t2^))
((var? t2^) (var-type-mismatch? S Y N t2^ t1^))
((and (pair? t1^) (pair? t2^))
(or (term-ununifiable? S Y N (car t1^) (car t2^))
(term-ununifiable? S Y N (cdr t1^) (cdr t2^))))
(else (not (eqv? t1^ t2^)))))))
(define T-term-ununifiable?
(lambda (S Y N)
(lambda (t1)
(let ((t1^ (walk t1 S)))
(letrec
((t2-check
(lambda (t2)
(let ((t2^ (walk t2 S)))
(cond
((pair? t2^) (and
(term-ununifiable? S Y N t1^ t2^)
(t2-check (car t2^))
(t2-check (cdr t2^))))
(else (term-ununifiable? S Y N t1^ t2^)))))))
t2-check)))))
(define num?
(lambda (S N n)
(let ((n (walk n S)))
(cond
((var? n) (tagged? S N n))
(else (number? n))))))
(define sym?
(lambda (S Y y)
(let ((y (walk y S)))
(cond
((var? y) (tagged? S Y y))
(else (symbol? y))))))
(define drop-T-b/c-Y-and-N
(lambdag@ (c : B E S D Y N T)
(let ((drop-t? (T-term-ununifiable? S Y N)))
(cond
((find (lambda (t) ((drop-t? (lhs t)) (rhs t))) T) =>
(lambda (t) `(,B ,E ,S ,D ,Y ,N ,(remq1 t T))))
(else c)))))
(define move-T-to-D-b/c-t2-atom
(lambdag@ (c : B E S D Y N T)
(cond
((exists (lambda (t)
(let ((t2^ (walk (rhs t) S)))
(cond
((and (not (untyped-var? S Y N t2^))
(not (pair? t2^)))
(let ((T (remq1 t T)))
`(,B ,E ,S ((,t) . ,D) ,Y ,N ,T)))
(else #f))))
T))
(else c))))
(define terms-pairwise=?
(lambda (pr-a^ pr-d^ t-a^ t-d^ S)
(or
(and (term=? pr-a^ t-a^ S)
(term=? pr-d^ t-a^ S))
(and (term=? pr-a^ t-d^ S)
(term=? pr-d^ t-a^ S)))))
(define T-superfluous-pr?
(lambda (S Y N T)
(lambda (pr)
(let ((pr-a^ (walk (lhs pr) S))
(pr-d^ (walk (rhs pr) S)))
(cond
((exists
(lambda (t)
(let ((t-a^ (walk (lhs t) S))
(t-d^ (walk (rhs t) S)))
(terms-pairwise=? pr-a^ pr-d^ t-a^ t-d^ S)))
T)
(for-all
(lambda (t)
(let ((t-a^ (walk (lhs t) S))
(t-d^ (walk (rhs t) S)))
(or
(not (terms-pairwise=? pr-a^ pr-d^ t-a^ t-d^ S))
(untyped-var? S Y N t-d^)
(pair? t-d^))))
T))
(else #f))))))
(define drop-from-D-b/c-T
(lambdag@ (c : B E S D Y N T)
(cond
((find
(lambda (d)
(exists
(T-superfluous-pr? S Y N T)
d))
D) =>
(lambda (d) `(,B ,E ,S ,(remq1 d D) ,Y ,N ,T)))
(else c))))
(define drop-t-b/c-t2-occurs-t1
(lambdag@ (c : B E S D Y N T)
(cond
((find (lambda (t)
(let ((t-a^ (walk (lhs t) S))
(t-d^ (walk (rhs t) S)))
(mem-check t-d^ t-a^ S)))
T) =>
(lambda (t)
`(,B ,E ,S ,D ,Y ,N ,(remq1 t T))))
(else c))))
(define split-t-move-to-d-b/c-pair
(lambdag@ (c : B E S D Y N T)
(cond
((exists
(lambda (t)
(let ((t2^ (walk (rhs t) S)))
(cond
((pair? t2^) (let ((ta `(,(lhs t) . ,(car t2^)))
(td `(,(lhs t) . ,(cdr t2^))))
(let ((T `(,ta ,td . ,(remq1 t T))))
`(,B ,E ,S ((,t) . ,D) ,Y ,N ,T))))
(else #f))))
T))
(else c))))
(define find-d-conflict
(lambda (S Y N)
(lambda (D)
(find
(lambda (d)
(exists (lambda (pr)
(term-ununifiable? S Y N (lhs pr) (rhs pr)))
d))
D))))
(define drop-D-b/c-Y-or-N
(lambdag@ (c : B E S D Y N T)
(cond
(((find-d-conflict S Y N) D) =>
(lambda (d) `(,B ,E ,S ,(remq1 d D) ,Y ,N ,T)))
(else c))))
(define cycle
(lambdag@ (c)
(let loop ((c^ c)
(fns^ (LOF))
(n (length (LOF))))
(cond
((zero? n) c^)
((null? fns^) (loop c^ (LOF) n))
(else
(let ((c^^ ((car fns^) c^)))
(cond
((not (eq? c^^ c^))
(loop c^^ (cdr fns^) (length (LOF))))
(else (loop c^ (cdr fns^) (sub1 n))))))))))
(define absento
(lambda (u v)
(lambdag@ (c : B E S D Y N T)
(cond
[(mem-check u v S) (mzero)]
[else (unit `(,B ,E ,S ,D ,Y ,N ((,u . ,v) . ,T)))]))))
(define eigen-absento
(lambda (e* x*)
(lambdag@ (c : B E S D Y N T)
(cond
[(eigen-occurs-check e* x* S) (mzero)]
[else (unit `(,B ((,e* . ,x*) . ,E) ,S ,D ,Y ,N ,T))]))))
(define mem-check
(lambda (u t S)
(let ((t (walk t S)))
(cond
((pair? t)
(or (term=? u t S)
(mem-check u (car t) S)
(mem-check u (cdr t) S)))
(else (term=? u t S))))))
(define term=?
(lambda (u t S)
(cond
((unify u t S) =>
(lambda (S0)
(eq? S0 S)))
(else #f))))
(define ground-non-<type>?
(lambda (pred)
(lambda (u S)
(let ((u (walk u S)))
(cond
((var? u) #f)
(else (not (pred u))))))))
(define ground-non-symbol?
(ground-non-<type>? symbol?))
(define ground-non-number?
(ground-non-<type>? number?))
(define symbolo
(lambda (u)
(lambdag@ (c : B E S D Y N T)
(cond
[(ground-non-symbol? u S) (mzero)]
[(mem-check u N S) (mzero)]
[else (unit `(,B ,E ,S ,D (,u . ,Y) ,N ,T))]))))
(define numbero
(lambda (u)
(lambdag@ (c : B E S D Y N T)
(cond
[(ground-non-number? u S) (mzero)]
[(mem-check u Y S) (mzero)]
[else (unit `(,B ,E ,S ,D ,Y (,u . ,N) ,T))]))))
(lambda (u v)
(lambdag@ (c : B E S D Y N T)
(cond
((unify u v S) =>
(lambda (S0)
(let ((pfx (prefix-S S0 S)))
(cond
((null? pfx) (mzero))
(else (unit `(,B ,E ,S (,pfx . ,D) ,Y ,N ,T)))))))
(else c)))))
(define ==
(lambda (u v)
(lambdag@ (c : B E S D Y N T)
(cond
((unify u v S) =>
(lambda (S0)
(cond
((==fail-check B E S0 D Y N T) (mzero))
(else (unit `(,B ,E ,S0 ,D ,Y ,N ,T))))))
(else (mzero))))))
(define succeed (== #f #f))
(define fail (== #f #t))
(define ==fail-check
(lambda (B E S0 D Y N T)
(cond
((eigen-absento-fail-check E S0) #t)
((atomic-fail-check S0 Y ground-non-symbol?) #t)
((atomic-fail-check S0 N ground-non-number?) #t)
((symbolo-numbero-fail-check S0 Y N) #t)
((=/=-fail-check S0 D) #t)
((absento-fail-check S0 T) #t)
(else #f))))
(define eigen-absento-fail-check
(lambda (E S0)
(exists (lambda (e*/x*) (eigen-occurs-check (car e*/x*) (cdr e*/x*) S0)) E)))
(define atomic-fail-check
(lambda (S A pred)
(exists (lambda (a) (pred (walk a S) S)) A)))
(define symbolo-numbero-fail-check
(lambda (S A N)
(let ((N (map (lambda (n) (walk n S)) N)))
(exists (lambda (a) (exists (same-var? (walk a S)) N))
A))))
(define absento-fail-check
(lambda (S T)
(exists (lambda (t) (mem-check (lhs t) (rhs t) S)) T)))
(define =/=-fail-check
(lambda (S D)
(exists (d-fail-check S) D)))
(define d-fail-check
(lambda (S)
(lambda (d)
(cond
((unify* d S) =>
(lambda (S+) (eq? S+ S)))
(else #f)))))
(define reify
(lambda (x)
(lambda (c)
(let ((c (cycle c)))
(let* ((S (c->S c))
(D (walk* (c->D c) S))
(Y (walk* (c->Y c) S))
(N (walk* (c->N c) S))
(T (walk* (c->T c) S)))
(let ((v (walk* x S)))
(let ((R (reify-S v '())))
(reify+ v R
(let ((D (remp
(lambda (d)
(let ((dw (walk* d S)))
(or
(anyvar? dw R)
(anyeigen? dw R))))
(rem-xx-from-d c))))
(rem-subsumed D))
(remp
(lambda (y) (var? (walk y R)))
Y)
(remp
(lambda (n) (var? (walk n R)))
N)
(remp (lambda (t)
(or (anyeigen? t R) (anyvar? t R))) T)))))))))
(define reify+
(lambda (v R D Y N T)
(form (walk* v R)
(walk* D R)
(walk* Y R)
(walk* N R)
(rem-subsumed-T (walk* T R)))))
(define form
(lambda (v D Y N T)
(let ((fd (sort-D D))
(fy (sorter Y))
(fn (sorter N))
(ft (sorter T)))
(let ((fd (if (null? fd) fd
(let ((fd (drop-dot-D fd)))
`((=/= . ,fd)))))
(fy (if (null? fy) fy `((sym . ,fy))))
(fn (if (null? fn) fn `((num . ,fn))))
(ft (if (null? ft) ft
(let ((ft (drop-dot ft)))
`((absento . ,ft))))))
(cond
((and (null? fd) (null? fy)
(null? fn) (null? ft))
v)
(else (append `(,v) fd fn fy ft)))))))
(define sort-D
(lambda (D)
(sorter
(map sort-d D))))
(define sort-d
(lambda (d)
(list-sort
(lambda (x y)
(lex<=? (car x) (car y)))
(map sort-pr d))))
(define drop-dot-D
(lambda (D)
(map drop-dot D)))
(define lex<-reified-name?
(lambda (r)
(char<?
(string-ref
(datum->string r) 0)
#\_)))
(define sort-pr
(lambda (pr)
(let ((l (lhs pr))
(r (rhs pr)))
(cond
((lex<-reified-name? r) pr)
((lex<=? r l) `(,r . ,l))
(else pr)))))
(define rem-subsumed
(lambda (D)
(let rem-subsumed ((D D) (d^* '()))
(cond
((null? D) d^*)
((or (subsumed? (car D) (cdr D))
(subsumed? (car D) d^*))
(rem-subsumed (cdr D) d^*))
(else (rem-subsumed (cdr D)
(cons (car D) d^*)))))))
(define subsumed?
(lambda (d d*)
(cond
((null? d*) #f)
(else
(let ((d^ (unify* (car d*) d)))
(or
(and d^ (eq? d^ d))
(subsumed? d (cdr d*))))))))
(define rem-xx-from-d
(lambdag@ (c : B E S D Y N T)
(let ((D (walk* D S)))
(remp not
(map (lambda (d)
(cond
((unify* d S) =>
(lambda (S0)
(cond
((==fail-check B E S0 '() Y N T) #f)
(else (prefix-S S0 S)))))
(else #f)))
D)))))
(define rem-subsumed-T
(lambda (T)
(let rem-subsumed ((T T) (T^ '()))
(cond
((null? T) T^)
(else
(let ((lit (lhs (car T)))
(big (rhs (car T))))
(cond
((or (subsumed-T? lit big (cdr T))
(subsumed-T? lit big T^))
(rem-subsumed (cdr T) T^))
(else (rem-subsumed (cdr T)
(cons (car T) T^))))))))))
(define subsumed-T?
(lambda (lit big T)
(cond
((null? T) #f)
(else
(let ((lit^ (lhs (car T)))
(big^ (rhs (car T))))
(or
(and (eq? big big^) (member* lit^ lit))
(subsumed-T? lit big (cdr T))))))))
(define LOF
(lambda ()
`(,drop-N-b/c-const ,drop-Y-b/c-const ,drop-Y-b/c-dup-var
,drop-N-b/c-dup-var ,drop-D-b/c-Y-or-N ,drop-T-b/c-Y-and-N
,move-T-to-D-b/c-t2-atom ,split-t-move-to-d-b/c-pair
,drop-from-D-b/c-T ,drop-t-b/c-t2-occurs-t1)))
|
4d97ac897049a929fced623dea93870299fe64ab2241e6b79f0aa24e430cbfc6
|
metosin/malli
|
generator_ast_test.clj
|
(ns malli.generator-ast-test
(:require [clojure.test :refer [deftest is]]
[clojure.test.check.generators :as tcgen]
[malli.generator-ast :as ast]))
(deftest generator-ast-test
(is (= '{:op :recursive-gen,
:target :recur0
:rec-gen
{:op :one-of,
:generators
[{:op :boolean}
{:op :tuple,
:generators [{:op :return, :value :not} {:op :boolean}]}
{:op :tuple,
:generators
[{:op :return, :value :and}
{:op :vector, :generator {:op :recur :target :recur0}}]}
{:op :tuple,
:generators
[{:op :return, :value :or}
{:op :vector, :generator {:op :recur :target :recur0}}]}]},
:scalar-gen
{:op :one-of,
:generators
[{:op :boolean}
{:op :tuple,
:generators [{:op :return, :value :not} {:op :boolean}]}
{:op :tuple,
:generators
[{:op :return, :value :and} {:op :return, :value ()}]}
{:op :tuple,
:generators
[{:op :return, :value :or} {:op :return, :value ()}]}]}}
(ast/generator-ast
[:schema
{:registry
{::formula
[:or
:boolean
[:tuple [:enum :not] :boolean]
[:tuple [:enum :and] [:* [:ref ::formula]]]
[:tuple [:enum :or] [:* [:ref ::formula]]]]}}
[:ref ::formula]])))
(is (= '{:op :recursive-gen,
:target :recur0
:rec-gen
{:op :one-of,
:generators
[{:op :boolean}
{:op :tuple,
:generators [{:op :return, :value :not} {:op :boolean}]}
{:op :tuple,
:generators
[{:op :return, :value :and}
{:op :vector-min
:generator {:op :recur :target :recur0}
:min 1}]}
{:op :tuple,
:generators
[{:op :return, :value :or}
{:op :vector-min
:generator {:op :recur :target :recur0}
:min 1}]}]},
:scalar-gen
{:op :one-of,
:generators
[{:op :boolean}
{:op :tuple,
:generators [{:op :return, :value :not} {:op :boolean}]}]}}
(ast/generator-ast
[:schema
{:registry
{::formula
[:or
:boolean
[:tuple [:enum :not] :boolean]
[:tuple [:enum :and] [:+ [:ref ::formula]]]
[:tuple [:enum :or] [:+ [:ref ::formula]]]]}}
[:ref ::formula]])))
(is (= '{:op :recursive-gen,
:target :recur0,
:rec-gen
{:op :tuple,
:generators
[{:op :return, :value "A"}
{:op :one-of,
:generators
[{:op :return, :value nil}
{:op :one-of,
:generators
[{:op :recursive-gen,
:target :recur1,
:rec-gen
{:op :tuple,
:generators
[{:op :return, :value "B"}
{:op :one-of,
:generators
[{:op :return, :value nil}
{:op :one-of,
:generators
[{:op :tuple,
:generators
[{:op :return, :value "C"}
{:op :one-of,
:generators
[{:op :return, :value nil}
{:op :one-of,
:generators
[{:op :recur, :target :recur0}
{:op :recur, :target :recur1}]}]}]}
{:op :recur, :target :recur0}]}]}]},
:scalar-gen
{:op :tuple,
:generators
[{:op :return, :value "B"}
{:op :one-of,
:generators
[{:op :return, :value nil}
{:op :one-of,
:generators
[{:op :tuple,
:generators
[{:op :return, :value "C"}
{:op :one-of,
:generators
[{:op :return, :value nil}
{:op :recur, :target :recur0}]}]}
{:op :recur, :target :recur0}]}]}]}}
{:op :recursive-gen,
:target :recur1,
:rec-gen
{:op :tuple,
:generators
[{:op :return, :value "C"}
{:op :one-of,
:generators
[{:op :return, :value nil}
{:op :one-of,
:generators
[{:op :recur, :target :recur0}
{:op :tuple,
:generators
[{:op :return, :value "B"}
{:op :one-of,
:generators
[{:op :return, :value nil}
{:op :one-of,
:generators
[{:op :recur, :target :recur1}
{:op :recur, :target :recur0}]}]}]}]}]}]},
:scalar-gen
{:op :tuple,
:generators
[{:op :return, :value "C"}
{:op :one-of,
:generators
[{:op :return, :value nil}
{:op :one-of,
:generators
[{:op :recur, :target :recur0}
{:op :tuple,
:generators
[{:op :return, :value "B"}
{:op :one-of,
:generators
[{:op :return, :value nil}
{:op :recur, :target :recur0}]}]}]}]}]}}]}]}]},
:scalar-gen
{:op :tuple,
:generators
[{:op :return, :value "A"}
{:op :one-of,
:generators
[{:op :return, :value nil}
{:op :one-of,
:generators
[{:op :recursive-gen,
:target :recur0,
:rec-gen
{:op :tuple,
:generators
[{:op :return, :value "B"}
{:op :one-of,
:generators
[{:op :return, :value nil}
{:op :tuple,
:generators
[{:op :return, :value "C"}
{:op :one-of,
:generators
[{:op :return, :value nil}
{:op :recur, :target :recur0}]}]}]}]},
:scalar-gen
{:op :tuple,
:generators
[{:op :return, :value "B"}
{:op :one-of,
:generators
[{:op :return, :value nil}
{:op :tuple,
:generators
[{:op :return, :value "C"}
{:op :return, :value nil}]}]}]}}
{:op :recursive-gen,
:target :recur0,
:rec-gen
{:op :tuple,
:generators
[{:op :return, :value "C"}
{:op :one-of,
:generators
[{:op :return, :value nil}
{:op :tuple,
:generators
[{:op :return, :value "B"}
{:op :one-of,
:generators
[{:op :return, :value nil}
{:op :recur, :target :recur0}]}]}]}]},
:scalar-gen
{:op :tuple,
:generators
[{:op :return, :value "C"}
{:op :one-of,
:generators
[{:op :return, :value nil}
{:op :tuple,
:generators
[{:op :return, :value "B"}
{:op :return, :value nil}]}]}]}}]}]}]}}
(ast/generator-ast
[:schema
{:registry {::A [:tuple [:= "A"] [:maybe [:or [:ref ::B] [:ref ::C]]]]
::B [:tuple [:= "B"] [:maybe [:or [:ref ::C] [:ref ::A]]]]
::C [:tuple [:= "C"] [:maybe [:or [:ref ::A] [:ref ::B]]]]}}
[:ref ::A]]))))
(def this-ns *ns*)
(deftest generator-code-test
(is (= '(tcgen/recursive-gen
(fn [recur0]
(tcgen/tuple (tcgen/return "A")
(tcgen/one-of
[(tcgen/return nil)
(tcgen/one-of
[(tcgen/recursive-gen
(fn [recur1]
(tcgen/tuple (tcgen/return "B")
(tcgen/one-of
[(tcgen/return nil)
(tcgen/one-of
[(tcgen/tuple
(tcgen/return "C")
(tcgen/one-of [(tcgen/return nil)
(tcgen/one-of [recur0 recur1])]))
recur0])])))
(tcgen/tuple (tcgen/return "B")
(tcgen/one-of [(tcgen/return nil)
(tcgen/one-of
[(tcgen/tuple (tcgen/return "C")
(tcgen/one-of [(tcgen/return nil)
recur0]))
recur0])])))
(tcgen/recursive-gen
(fn [recur1]
(tcgen/tuple (tcgen/return "C")
(tcgen/one-of [(tcgen/return nil)
(tcgen/one-of
[recur0
(tcgen/tuple
(tcgen/return "B")
(tcgen/one-of [(tcgen/return nil)
(tcgen/one-of [recur1 recur0])]))])])))
(tcgen/tuple (tcgen/return "C")
(tcgen/one-of [(tcgen/return nil)
(tcgen/one-of
[recur0
(tcgen/tuple (tcgen/return "B")
(tcgen/one-of [(tcgen/return nil)
recur0]))])])))])])))
(tcgen/tuple (tcgen/return "A")
(tcgen/one-of [(tcgen/return nil)
(tcgen/one-of
[(tcgen/recursive-gen
(fn [recur0]
(tcgen/tuple (tcgen/return "B")
(tcgen/one-of [(tcgen/return nil)
(tcgen/tuple
(tcgen/return "C")
(tcgen/one-of [(tcgen/return nil)
recur0]))])))
(tcgen/tuple (tcgen/return "B")
(tcgen/one-of [(tcgen/return nil)
(tcgen/tuple (tcgen/return "C")
(tcgen/return nil))])))
(tcgen/recursive-gen
(fn [recur0]
(tcgen/tuple (tcgen/return "C")
(tcgen/one-of [(tcgen/return nil)
(tcgen/tuple (tcgen/return "B")
(tcgen/one-of [(tcgen/return nil)
recur0]))])))
(tcgen/tuple (tcgen/return "C")
(tcgen/one-of [(tcgen/return nil)
(tcgen/tuple (tcgen/return "B")
(tcgen/return nil))])))])])))
(binding [*ns* this-ns]
(ast/generator-code
[:schema
{:registry {::A [:tuple [:= "A"] [:maybe [:or [:ref ::B] [:ref ::C]]]]
::B [:tuple [:= "B"] [:maybe [:or [:ref ::C] [:ref ::A]]]]
::C [:tuple [:= "C"] [:maybe [:or [:ref ::A] [:ref ::B]]]]}}
[:ref ::A]])))))
(deftest maybe-ast-test
(is (ast/generator-ast [:maybe :boolean])))
| null |
https://raw.githubusercontent.com/metosin/malli/ae6abbe2ac0b663eaa741948a852067091289107/test/malli/generator_ast_test.clj
|
clojure
|
(ns malli.generator-ast-test
(:require [clojure.test :refer [deftest is]]
[clojure.test.check.generators :as tcgen]
[malli.generator-ast :as ast]))
(deftest generator-ast-test
(is (= '{:op :recursive-gen,
:target :recur0
:rec-gen
{:op :one-of,
:generators
[{:op :boolean}
{:op :tuple,
:generators [{:op :return, :value :not} {:op :boolean}]}
{:op :tuple,
:generators
[{:op :return, :value :and}
{:op :vector, :generator {:op :recur :target :recur0}}]}
{:op :tuple,
:generators
[{:op :return, :value :or}
{:op :vector, :generator {:op :recur :target :recur0}}]}]},
:scalar-gen
{:op :one-of,
:generators
[{:op :boolean}
{:op :tuple,
:generators [{:op :return, :value :not} {:op :boolean}]}
{:op :tuple,
:generators
[{:op :return, :value :and} {:op :return, :value ()}]}
{:op :tuple,
:generators
[{:op :return, :value :or} {:op :return, :value ()}]}]}}
(ast/generator-ast
[:schema
{:registry
{::formula
[:or
:boolean
[:tuple [:enum :not] :boolean]
[:tuple [:enum :and] [:* [:ref ::formula]]]
[:tuple [:enum :or] [:* [:ref ::formula]]]]}}
[:ref ::formula]])))
(is (= '{:op :recursive-gen,
:target :recur0
:rec-gen
{:op :one-of,
:generators
[{:op :boolean}
{:op :tuple,
:generators [{:op :return, :value :not} {:op :boolean}]}
{:op :tuple,
:generators
[{:op :return, :value :and}
{:op :vector-min
:generator {:op :recur :target :recur0}
:min 1}]}
{:op :tuple,
:generators
[{:op :return, :value :or}
{:op :vector-min
:generator {:op :recur :target :recur0}
:min 1}]}]},
:scalar-gen
{:op :one-of,
:generators
[{:op :boolean}
{:op :tuple,
:generators [{:op :return, :value :not} {:op :boolean}]}]}}
(ast/generator-ast
[:schema
{:registry
{::formula
[:or
:boolean
[:tuple [:enum :not] :boolean]
[:tuple [:enum :and] [:+ [:ref ::formula]]]
[:tuple [:enum :or] [:+ [:ref ::formula]]]]}}
[:ref ::formula]])))
(is (= '{:op :recursive-gen,
:target :recur0,
:rec-gen
{:op :tuple,
:generators
[{:op :return, :value "A"}
{:op :one-of,
:generators
[{:op :return, :value nil}
{:op :one-of,
:generators
[{:op :recursive-gen,
:target :recur1,
:rec-gen
{:op :tuple,
:generators
[{:op :return, :value "B"}
{:op :one-of,
:generators
[{:op :return, :value nil}
{:op :one-of,
:generators
[{:op :tuple,
:generators
[{:op :return, :value "C"}
{:op :one-of,
:generators
[{:op :return, :value nil}
{:op :one-of,
:generators
[{:op :recur, :target :recur0}
{:op :recur, :target :recur1}]}]}]}
{:op :recur, :target :recur0}]}]}]},
:scalar-gen
{:op :tuple,
:generators
[{:op :return, :value "B"}
{:op :one-of,
:generators
[{:op :return, :value nil}
{:op :one-of,
:generators
[{:op :tuple,
:generators
[{:op :return, :value "C"}
{:op :one-of,
:generators
[{:op :return, :value nil}
{:op :recur, :target :recur0}]}]}
{:op :recur, :target :recur0}]}]}]}}
{:op :recursive-gen,
:target :recur1,
:rec-gen
{:op :tuple,
:generators
[{:op :return, :value "C"}
{:op :one-of,
:generators
[{:op :return, :value nil}
{:op :one-of,
:generators
[{:op :recur, :target :recur0}
{:op :tuple,
:generators
[{:op :return, :value "B"}
{:op :one-of,
:generators
[{:op :return, :value nil}
{:op :one-of,
:generators
[{:op :recur, :target :recur1}
{:op :recur, :target :recur0}]}]}]}]}]}]},
:scalar-gen
{:op :tuple,
:generators
[{:op :return, :value "C"}
{:op :one-of,
:generators
[{:op :return, :value nil}
{:op :one-of,
:generators
[{:op :recur, :target :recur0}
{:op :tuple,
:generators
[{:op :return, :value "B"}
{:op :one-of,
:generators
[{:op :return, :value nil}
{:op :recur, :target :recur0}]}]}]}]}]}}]}]}]},
:scalar-gen
{:op :tuple,
:generators
[{:op :return, :value "A"}
{:op :one-of,
:generators
[{:op :return, :value nil}
{:op :one-of,
:generators
[{:op :recursive-gen,
:target :recur0,
:rec-gen
{:op :tuple,
:generators
[{:op :return, :value "B"}
{:op :one-of,
:generators
[{:op :return, :value nil}
{:op :tuple,
:generators
[{:op :return, :value "C"}
{:op :one-of,
:generators
[{:op :return, :value nil}
{:op :recur, :target :recur0}]}]}]}]},
:scalar-gen
{:op :tuple,
:generators
[{:op :return, :value "B"}
{:op :one-of,
:generators
[{:op :return, :value nil}
{:op :tuple,
:generators
[{:op :return, :value "C"}
{:op :return, :value nil}]}]}]}}
{:op :recursive-gen,
:target :recur0,
:rec-gen
{:op :tuple,
:generators
[{:op :return, :value "C"}
{:op :one-of,
:generators
[{:op :return, :value nil}
{:op :tuple,
:generators
[{:op :return, :value "B"}
{:op :one-of,
:generators
[{:op :return, :value nil}
{:op :recur, :target :recur0}]}]}]}]},
:scalar-gen
{:op :tuple,
:generators
[{:op :return, :value "C"}
{:op :one-of,
:generators
[{:op :return, :value nil}
{:op :tuple,
:generators
[{:op :return, :value "B"}
{:op :return, :value nil}]}]}]}}]}]}]}}
(ast/generator-ast
[:schema
{:registry {::A [:tuple [:= "A"] [:maybe [:or [:ref ::B] [:ref ::C]]]]
::B [:tuple [:= "B"] [:maybe [:or [:ref ::C] [:ref ::A]]]]
::C [:tuple [:= "C"] [:maybe [:or [:ref ::A] [:ref ::B]]]]}}
[:ref ::A]]))))
(def this-ns *ns*)
(deftest generator-code-test
(is (= '(tcgen/recursive-gen
(fn [recur0]
(tcgen/tuple (tcgen/return "A")
(tcgen/one-of
[(tcgen/return nil)
(tcgen/one-of
[(tcgen/recursive-gen
(fn [recur1]
(tcgen/tuple (tcgen/return "B")
(tcgen/one-of
[(tcgen/return nil)
(tcgen/one-of
[(tcgen/tuple
(tcgen/return "C")
(tcgen/one-of [(tcgen/return nil)
(tcgen/one-of [recur0 recur1])]))
recur0])])))
(tcgen/tuple (tcgen/return "B")
(tcgen/one-of [(tcgen/return nil)
(tcgen/one-of
[(tcgen/tuple (tcgen/return "C")
(tcgen/one-of [(tcgen/return nil)
recur0]))
recur0])])))
(tcgen/recursive-gen
(fn [recur1]
(tcgen/tuple (tcgen/return "C")
(tcgen/one-of [(tcgen/return nil)
(tcgen/one-of
[recur0
(tcgen/tuple
(tcgen/return "B")
(tcgen/one-of [(tcgen/return nil)
(tcgen/one-of [recur1 recur0])]))])])))
(tcgen/tuple (tcgen/return "C")
(tcgen/one-of [(tcgen/return nil)
(tcgen/one-of
[recur0
(tcgen/tuple (tcgen/return "B")
(tcgen/one-of [(tcgen/return nil)
recur0]))])])))])])))
(tcgen/tuple (tcgen/return "A")
(tcgen/one-of [(tcgen/return nil)
(tcgen/one-of
[(tcgen/recursive-gen
(fn [recur0]
(tcgen/tuple (tcgen/return "B")
(tcgen/one-of [(tcgen/return nil)
(tcgen/tuple
(tcgen/return "C")
(tcgen/one-of [(tcgen/return nil)
recur0]))])))
(tcgen/tuple (tcgen/return "B")
(tcgen/one-of [(tcgen/return nil)
(tcgen/tuple (tcgen/return "C")
(tcgen/return nil))])))
(tcgen/recursive-gen
(fn [recur0]
(tcgen/tuple (tcgen/return "C")
(tcgen/one-of [(tcgen/return nil)
(tcgen/tuple (tcgen/return "B")
(tcgen/one-of [(tcgen/return nil)
recur0]))])))
(tcgen/tuple (tcgen/return "C")
(tcgen/one-of [(tcgen/return nil)
(tcgen/tuple (tcgen/return "B")
(tcgen/return nil))])))])])))
(binding [*ns* this-ns]
(ast/generator-code
[:schema
{:registry {::A [:tuple [:= "A"] [:maybe [:or [:ref ::B] [:ref ::C]]]]
::B [:tuple [:= "B"] [:maybe [:or [:ref ::C] [:ref ::A]]]]
::C [:tuple [:= "C"] [:maybe [:or [:ref ::A] [:ref ::B]]]]}}
[:ref ::A]])))))
(deftest maybe-ast-test
(is (ast/generator-ast [:maybe :boolean])))
|
|
38f3f040623dd260f7efb5aa2ed88def3454708de3604ce7c715bd5d58aa7414
|
JonasDuregard/testing-feat
|
Class.hs
|
module Test.Feat.Class {-# DEPRECATED "Use Control.Enumerable instead" #-}
( Enumerable(..)
, nullary
, unary
, funcurry
, shared
, consts
, deriveEnumerable
) where
import Control.Enumerable
-- compatability
{-# DEPRECATED nullary "use c0 instead" #-}
-- nullary :: x -> Memoizable f x
nullary x = c0 x
{-# DEPRECATED unary "use c1 instead" #-}
-- unary :: (Enumerable a, MemoSized f) => (a -> x) -> f x
unary x = c1 x
{-# DEPRECATED shared "use access instead" #-}
shared :: (Sized f, Enumerable a, Typeable f) => Shareable f a
shared = access
funcurry = uncurry
{-# DEPRECATED consts "use datatype instead" #-}
consts : : ( a , MemoSized f ) = > [ f a ] - > Closed ( f a )
consts xs = datatype xs
| null |
https://raw.githubusercontent.com/JonasDuregard/testing-feat/a1b32842a8cc8ab467d93a9f97f2365330a02113/Test/Feat/Class.hs
|
haskell
|
# DEPRECATED "Use Control.Enumerable instead" #
compatability
# DEPRECATED nullary "use c0 instead" #
nullary :: x -> Memoizable f x
# DEPRECATED unary "use c1 instead" #
unary :: (Enumerable a, MemoSized f) => (a -> x) -> f x
# DEPRECATED shared "use access instead" #
# DEPRECATED consts "use datatype instead" #
|
( Enumerable(..)
, nullary
, unary
, funcurry
, shared
, consts
, deriveEnumerable
) where
import Control.Enumerable
nullary x = c0 x
unary x = c1 x
shared :: (Sized f, Enumerable a, Typeable f) => Shareable f a
shared = access
funcurry = uncurry
consts : : ( a , MemoSized f ) = > [ f a ] - > Closed ( f a )
consts xs = datatype xs
|
b67c9fd6f337e55bb8d2972c6f3839abd19725929f867e8ad771323f5135db9c
|
MinaProtocol/mina
|
vesta_based_plonk.ml
|
open Core_kernel
open Kimchi_backend_common
open Kimchi_pasta_basic
module Field = Fp
module Curve = Vesta
module Bigint = struct
include Field.Bigint
let of_data _ = failwith __LOC__
let to_field = Field.of_bigint
let of_field = Field.to_bigint
end
let field_size : Bigint.t = Field.size
module Verification_key = struct
type t =
( Pasta_bindings.Fp.t
, Kimchi_bindings.Protocol.SRS.Fp.t
, Pasta_bindings.Fq.t Kimchi_types.or_infinity Kimchi_types.poly_comm )
Kimchi_types.VerifierIndex.verifier_index
let to_string _ = failwith __LOC__
let of_string _ = failwith __LOC__
let shifts (t : t) = t.shifts
end
module R1CS_constraint_system =
Kimchi_pasta_constraint_system.Vesta_constraint_system
let lagrange srs domain_log2 : _ Kimchi_types.poly_comm array =
let domain_size = Int.pow 2 domain_log2 in
Array.init domain_size ~f:(fun i ->
Kimchi_bindings.Protocol.SRS.Fp.lagrange_commitment srs domain_size i )
let with_lagrange f (vk : Verification_key.t) =
f (lagrange vk.srs vk.domain.log_size_of_group) vk
let with_lagranges f (vks : Verification_key.t array) =
let lgrs =
Array.map vks ~f:(fun vk -> lagrange vk.srs vk.domain.log_size_of_group)
in
f lgrs vks
module Rounds_vector = Rounds.Step_vector
module Rounds = Rounds.Step
module Keypair = Dlog_plonk_based_keypair.Make (struct
let name = "vesta"
module Rounds = Rounds
module Urs = Kimchi_bindings.Protocol.SRS.Fp
module Index = Kimchi_bindings.Protocol.Index.Fp
module Curve = Curve
module Poly_comm = Fp_poly_comm
module Scalar_field = Field
module Verifier_index = Kimchi_bindings.Protocol.VerifierIndex.Fp
module Gate_vector = Kimchi_bindings.Protocol.Gates.Vector.Fp
module Constraint_system = R1CS_constraint_system
end)
module Proof = Plonk_dlog_proof.Make (struct
let id = "pasta_vesta"
module Scalar_field = Field
module Base_field = Fq
module Backend = struct
type t =
( Pasta_bindings.Fq.t Kimchi_types.or_infinity
, Pasta_bindings.Fp.t )
Kimchi_types.prover_proof
include Kimchi_bindings.Protocol.Proof.Fp
let batch_verify vks ts =
Promise.run_in_thread (fun () -> batch_verify vks ts)
let create_aux ~f:create (pk : Keypair.t) primary auxiliary prev_chals
prev_comms =
external values contains [ 1 , primary ... , auxiliary ]
let external_values i =
let open Field.Vector in
if i = 0 then Field.one
else if i - 1 < length primary then get primary (i - 1)
else get auxiliary (i - 1 - length primary)
in
(* compute witness *)
let computed_witness =
R1CS_constraint_system.compute_witness pk.cs external_values
in
let num_rows = Array.length computed_witness.(0) in
convert to Rust vector
let witness_cols =
Array.init Kimchi_backend_common.Constants.columns ~f:(fun col ->
let witness = Field.Vector.create () in
for row = 0 to num_rows - 1 do
Field.Vector.emplace_back witness computed_witness.(col).(row)
done ;
witness )
in
create pk.index witness_cols prev_chals prev_comms
let create_async (pk : Keypair.t) primary auxiliary prev_chals prev_comms =
create_aux pk primary auxiliary prev_chals prev_comms
~f:(fun pk auxiliary_input prev_challenges prev_sgs ->
Promise.run_in_thread (fun () ->
create pk auxiliary_input prev_challenges prev_sgs ) )
let create (pk : Keypair.t) primary auxiliary prev_chals prev_comms =
create_aux pk primary auxiliary prev_chals prev_comms ~f:create
end
module Verifier_index = Kimchi_bindings.Protocol.VerifierIndex.Fp
module Index = Keypair
module Evaluations_backend = struct
type t = Scalar_field.t Kimchi_types.proof_evaluations
end
module Opening_proof_backend = struct
type t = (Curve.Affine.Backend.t, Scalar_field.t) Kimchi_types.opening_proof
end
module Poly_comm = Fp_poly_comm
module Curve = Curve
end)
module Proving_key = struct
type t = Keypair.t
include
Core_kernel.Binable.Of_binable
(Core_kernel.Unit)
(struct
type nonrec t = t
let to_binable _ = ()
let of_binable () = failwith "TODO"
end)
let is_initialized _ = `Yes
let set_constraint_system _ _ = ()
let to_string _ = failwith "TODO"
let of_string _ = failwith "TODO"
end
module Oracles = Plonk_dlog_oracles.Make (struct
module Verifier_index = Verification_key
module Field = Field
module Proof = Proof
module Backend = struct
include Kimchi_bindings.Protocol.Oracles.Fp
let create = with_lagrange create
end
end)
| null |
https://raw.githubusercontent.com/MinaProtocol/mina/cee2e182c50d1e36f132e73a146ff0be613f2bb5/src/lib/crypto/kimchi_backend/pasta/vesta_based_plonk.ml
|
ocaml
|
compute witness
|
open Core_kernel
open Kimchi_backend_common
open Kimchi_pasta_basic
module Field = Fp
module Curve = Vesta
module Bigint = struct
include Field.Bigint
let of_data _ = failwith __LOC__
let to_field = Field.of_bigint
let of_field = Field.to_bigint
end
let field_size : Bigint.t = Field.size
module Verification_key = struct
type t =
( Pasta_bindings.Fp.t
, Kimchi_bindings.Protocol.SRS.Fp.t
, Pasta_bindings.Fq.t Kimchi_types.or_infinity Kimchi_types.poly_comm )
Kimchi_types.VerifierIndex.verifier_index
let to_string _ = failwith __LOC__
let of_string _ = failwith __LOC__
let shifts (t : t) = t.shifts
end
module R1CS_constraint_system =
Kimchi_pasta_constraint_system.Vesta_constraint_system
let lagrange srs domain_log2 : _ Kimchi_types.poly_comm array =
let domain_size = Int.pow 2 domain_log2 in
Array.init domain_size ~f:(fun i ->
Kimchi_bindings.Protocol.SRS.Fp.lagrange_commitment srs domain_size i )
let with_lagrange f (vk : Verification_key.t) =
f (lagrange vk.srs vk.domain.log_size_of_group) vk
let with_lagranges f (vks : Verification_key.t array) =
let lgrs =
Array.map vks ~f:(fun vk -> lagrange vk.srs vk.domain.log_size_of_group)
in
f lgrs vks
module Rounds_vector = Rounds.Step_vector
module Rounds = Rounds.Step
module Keypair = Dlog_plonk_based_keypair.Make (struct
let name = "vesta"
module Rounds = Rounds
module Urs = Kimchi_bindings.Protocol.SRS.Fp
module Index = Kimchi_bindings.Protocol.Index.Fp
module Curve = Curve
module Poly_comm = Fp_poly_comm
module Scalar_field = Field
module Verifier_index = Kimchi_bindings.Protocol.VerifierIndex.Fp
module Gate_vector = Kimchi_bindings.Protocol.Gates.Vector.Fp
module Constraint_system = R1CS_constraint_system
end)
module Proof = Plonk_dlog_proof.Make (struct
let id = "pasta_vesta"
module Scalar_field = Field
module Base_field = Fq
module Backend = struct
type t =
( Pasta_bindings.Fq.t Kimchi_types.or_infinity
, Pasta_bindings.Fp.t )
Kimchi_types.prover_proof
include Kimchi_bindings.Protocol.Proof.Fp
let batch_verify vks ts =
Promise.run_in_thread (fun () -> batch_verify vks ts)
let create_aux ~f:create (pk : Keypair.t) primary auxiliary prev_chals
prev_comms =
external values contains [ 1 , primary ... , auxiliary ]
let external_values i =
let open Field.Vector in
if i = 0 then Field.one
else if i - 1 < length primary then get primary (i - 1)
else get auxiliary (i - 1 - length primary)
in
let computed_witness =
R1CS_constraint_system.compute_witness pk.cs external_values
in
let num_rows = Array.length computed_witness.(0) in
convert to Rust vector
let witness_cols =
Array.init Kimchi_backend_common.Constants.columns ~f:(fun col ->
let witness = Field.Vector.create () in
for row = 0 to num_rows - 1 do
Field.Vector.emplace_back witness computed_witness.(col).(row)
done ;
witness )
in
create pk.index witness_cols prev_chals prev_comms
let create_async (pk : Keypair.t) primary auxiliary prev_chals prev_comms =
create_aux pk primary auxiliary prev_chals prev_comms
~f:(fun pk auxiliary_input prev_challenges prev_sgs ->
Promise.run_in_thread (fun () ->
create pk auxiliary_input prev_challenges prev_sgs ) )
let create (pk : Keypair.t) primary auxiliary prev_chals prev_comms =
create_aux pk primary auxiliary prev_chals prev_comms ~f:create
end
module Verifier_index = Kimchi_bindings.Protocol.VerifierIndex.Fp
module Index = Keypair
module Evaluations_backend = struct
type t = Scalar_field.t Kimchi_types.proof_evaluations
end
module Opening_proof_backend = struct
type t = (Curve.Affine.Backend.t, Scalar_field.t) Kimchi_types.opening_proof
end
module Poly_comm = Fp_poly_comm
module Curve = Curve
end)
module Proving_key = struct
type t = Keypair.t
include
Core_kernel.Binable.Of_binable
(Core_kernel.Unit)
(struct
type nonrec t = t
let to_binable _ = ()
let of_binable () = failwith "TODO"
end)
let is_initialized _ = `Yes
let set_constraint_system _ _ = ()
let to_string _ = failwith "TODO"
let of_string _ = failwith "TODO"
end
module Oracles = Plonk_dlog_oracles.Make (struct
module Verifier_index = Verification_key
module Field = Field
module Proof = Proof
module Backend = struct
include Kimchi_bindings.Protocol.Oracles.Fp
let create = with_lagrange create
end
end)
|
3cd3094265ce7a72fc72ac54dd47329e62ccd30387cd8dd3c74c2985ad391d50
|
Clojure2D/clojure2d-examples
|
hittable_list.clj
|
(ns rt4.the-next-week.ch05d.hittable-list
(:require [rt4.the-next-week.ch05d.interval :as interval]
[rt4.the-next-week.ch05d.hittable :as hittable]
[rt4.the-next-week.ch05d.aabb :as aabb]))
(defprotocol HittableListProto
(add [hittable-list object]))
(defrecord HittableList [objects bbox]
hittable/HittableProto
(hit [_ ray ray-t]
(reduce (fn [curr-hit object]
(if-let [hit-object (hittable/hit object ray (interval/interval (:mn ray-t)
(or (:t curr-hit) (:mx ray-t))))]
hit-object
curr-hit)) nil objects))
HittableListProto
(add [_ object]
(->HittableList (conj objects object) (aabb/merge-boxes bbox (:bbox object)))))
(defn hittable-list
[& objects]
(->HittableList objects (reduce aabb/merge-boxes (map :bbox objects))))
| null |
https://raw.githubusercontent.com/Clojure2D/clojure2d-examples/ead92d6f17744b91070e6308157364ad4eab8a1b/src/rt4/the_next_week/ch05d/hittable_list.clj
|
clojure
|
(ns rt4.the-next-week.ch05d.hittable-list
(:require [rt4.the-next-week.ch05d.interval :as interval]
[rt4.the-next-week.ch05d.hittable :as hittable]
[rt4.the-next-week.ch05d.aabb :as aabb]))
(defprotocol HittableListProto
(add [hittable-list object]))
(defrecord HittableList [objects bbox]
hittable/HittableProto
(hit [_ ray ray-t]
(reduce (fn [curr-hit object]
(if-let [hit-object (hittable/hit object ray (interval/interval (:mn ray-t)
(or (:t curr-hit) (:mx ray-t))))]
hit-object
curr-hit)) nil objects))
HittableListProto
(add [_ object]
(->HittableList (conj objects object) (aabb/merge-boxes bbox (:bbox object)))))
(defn hittable-list
[& objects]
(->HittableList objects (reduce aabb/merge-boxes (map :bbox objects))))
|
|
37149e3ffdf3f876edd524c541a2b991b3e190cfeedcf41d83ae4734c2ffb421
|
yetanalytics/re-oidc
|
test_runner.cljs
|
;; This test runner is intended to be run from the command line
(ns com.test-runner
(:require
;; require all the namespaces that you want to test
[com.yetanalytics.re-oidc-test]
[figwheel.main.testing :refer [run-tests-async]]))
(defn -main [& args]
(run-tests-async 5000))
| null |
https://raw.githubusercontent.com/yetanalytics/re-oidc/a33d50d999b486c4d88f7ff1314c9e8a4af955a0/src/test/com/test_runner.cljs
|
clojure
|
This test runner is intended to be run from the command line
require all the namespaces that you want to test
|
(ns com.test-runner
(:require
[com.yetanalytics.re-oidc-test]
[figwheel.main.testing :refer [run-tests-async]]))
(defn -main [& args]
(run-tests-async 5000))
|
14a65ac885ba2c12467ff17052780e77a17b2fd4b9b14ac54c817b16c21a52d1
|
plandes/cisql
|
conf.clj
|
(ns ^{:doc "Manages application level configuration using the Java Prefernces
system."
:author "Paul Landes"}
zensols.cisql.conf
(:require [clojure.string :as str]
[clojure.tools.logging :as log]
[clojure.set :refer (difference)]
[zensols.cisql.version :as ver]
[zensols.cisql.pref :as pref]))
(def ^:private var-meta
[[:loglevel "info" "logging verbosity (<error|warn|info|debug|trace>)"]
[:catalog nil "set the catalog (resets connection)"]
[:schema nil "set the schema (resets connection)"]
[:strict true "if true, do not allow setting of free variables"
"built-in-and-user-variables"]
[:linesep ";" "tell where to end a query and then send"]
[:rowcount nil "the number of rows to display (all be default)" "row-count"]
[:errorlong false "if true, provide more SQL level error information"]
[:prex false "print exception stack traces"]
[:prompt " %1$s > " "a format string for the promp"
"variables"]
[:sigintercept true "if true, intercept and break on Control-C signals"]
[:gui false "use a graphical window to display result sets"
"graphical-results"]
[:guiheight 0 "the number of pixels to add to the height of the GUI window"]
[:guiwidth 0 "the number of pixels to add to the width of the GUI window"]
[:headless true "use separate window for GUI (require restart)"
"graphical-results"]])
(def ^:private default-config
(->> var-meta
(map #(array-map (first %) (second %)))
(apply merge)))
(def ^:private help-sections
(->> var-meta
(map #(array-map (first %) (if (> (count %) 3)
(nth % 3))))
(apply merge)))
(def ^:private system-properties
{:headless "apple.awt.UIElement"})
(def ^:private set-config-hooks (atom #{}))
(def ^:private config-data-inst (atom nil))
(def ^:private parse-keys
#{:errorlong :gui})
(def ^:private help-message
"type 'help' to see a list of commands")
(def ^:private our-ns *ns*)
(defn- update-system-properties [key value]
(let [k (get system-properties key)
k (if k (name k))
value (str value)]
(when k
(log/debugf "settings prop: %s -> %s" k value)
(System/setProperty k value))))
(defn add-set-config-hook [callback-fn]
(swap! set-config-hooks #(conj % callback-fn)))
(add-set-config-hook update-system-properties)
(defn- config-data []
(swap! config-data-inst
(fn [prefs]
(if (nil? prefs)
(let [prefs (pref/environment default-config)]
(doseq [[k v] prefs]
(doseq [callback @set-config-hooks]
((eval callback) k v)))
prefs)
prefs))))
(defn config
([]
(config nil))
([key & {:keys [expect?]
:or {expect? nil}}]
(if (nil? key)
(config-data)
(let [val (get (config-data) key)]
(if (and (nil? val) expect?)
(-> (format "no such variable: %s" (name key))
(ex-info {:key key})
throw))
val))))
(defn set-config
"Set variable with name **key** to **value** and save."
[key value]
(log/tracef "%s -> %s" key value)
(config)
(if (and @config-data-inst (config :strict)
(not (contains? default-config key)))
(-> (format "no such variable: %s" (name key))
(ex-info {:key key :value value})
throw))
(let [val (if (and (contains? parse-keys key)
(string? value))
(read-string value)
value)]
(swap! config-data-inst assoc key val)
(doseq [callback @set-config-hooks]
((eval callback) key value))
(pref/set-environment @config-data-inst)
(log/tracef "vars: %s" @config-data-inst)))
(defn remove-config
"Remove variable with name **key** and save."
[key]
(if (contains? default-config key)
(-> (format "can not delete built in variable: %s" key)
(ex-info {:key key})
throw))
(if (not (contains? (config) key))
(-> (format "no such user variable: %s" key)
(ex-info {:key key})
throw))
(swap! config-data-inst dissoc key)
(pref/set-environment @config-data-inst))
(defn- user-variable-names
"Return a list of the variable keys in user space."
[]
(->> (keys default-config)
set
(difference (set (keys (config))))))
(defn print-key-values
"Print state of variable key/value pairs as markdown."
[]
(let [conf (config)]
(letfn [(pr-conf [key]
(let [val (get conf key)
val (if (nil? val)
"<none>"
val)]
(println (format " * %s: %s" (name key) val))))]
(println "# Built in variables:")
(->> (map first var-meta)
(map pr-conf)
doall)
(println "# User variables:")
(->> (user-variable-names)
(map pr-conf)
doall))))
(defn print-key-desc
"Print variable names and documentation as markdown."
[space]
(let [space (or space 0)
space (->> (map first var-meta)
(map #(-> % name count))
(reduce max)
(max 0)
inc
(max space))
fmt (str " * %-" space "s %s")]
(->> var-meta
(map (fn [[k d v]]
(println (format fmt (str (name k)) v))))
doall)))
(defn help-section
"Return help section for the variable with **key** if there is one."
[key]
(get help-sections key))
(defn reset
"Reset **all** variable data to it's initial nascent state."
[]
(pref/clear :var 'environment)
(reset! config-data-inst nil)
(config))
(defn format-version []
(format "v%s " ver/version))
(defn format-intro []
(format "Clojure Interactive SQL (cisql) %s
(C) Paul Landes 2015 - 2021"
(format-version)))
(defn print-help []
(println (format-intro))
(println help-message))
| null |
https://raw.githubusercontent.com/plandes/cisql/8001864f1596d191386a3787b49e8a640705fee2/src/clojure/zensols/cisql/conf.clj
|
clojure
|
(ns ^{:doc "Manages application level configuration using the Java Prefernces
system."
:author "Paul Landes"}
zensols.cisql.conf
(:require [clojure.string :as str]
[clojure.tools.logging :as log]
[clojure.set :refer (difference)]
[zensols.cisql.version :as ver]
[zensols.cisql.pref :as pref]))
(def ^:private var-meta
[[:loglevel "info" "logging verbosity (<error|warn|info|debug|trace>)"]
[:catalog nil "set the catalog (resets connection)"]
[:schema nil "set the schema (resets connection)"]
[:strict true "if true, do not allow setting of free variables"
"built-in-and-user-variables"]
[:linesep ";" "tell where to end a query and then send"]
[:rowcount nil "the number of rows to display (all be default)" "row-count"]
[:errorlong false "if true, provide more SQL level error information"]
[:prex false "print exception stack traces"]
[:prompt " %1$s > " "a format string for the promp"
"variables"]
[:sigintercept true "if true, intercept and break on Control-C signals"]
[:gui false "use a graphical window to display result sets"
"graphical-results"]
[:guiheight 0 "the number of pixels to add to the height of the GUI window"]
[:guiwidth 0 "the number of pixels to add to the width of the GUI window"]
[:headless true "use separate window for GUI (require restart)"
"graphical-results"]])
(def ^:private default-config
(->> var-meta
(map #(array-map (first %) (second %)))
(apply merge)))
(def ^:private help-sections
(->> var-meta
(map #(array-map (first %) (if (> (count %) 3)
(nth % 3))))
(apply merge)))
(def ^:private system-properties
{:headless "apple.awt.UIElement"})
(def ^:private set-config-hooks (atom #{}))
(def ^:private config-data-inst (atom nil))
(def ^:private parse-keys
#{:errorlong :gui})
(def ^:private help-message
"type 'help' to see a list of commands")
(def ^:private our-ns *ns*)
(defn- update-system-properties [key value]
(let [k (get system-properties key)
k (if k (name k))
value (str value)]
(when k
(log/debugf "settings prop: %s -> %s" k value)
(System/setProperty k value))))
(defn add-set-config-hook [callback-fn]
(swap! set-config-hooks #(conj % callback-fn)))
(add-set-config-hook update-system-properties)
(defn- config-data []
(swap! config-data-inst
(fn [prefs]
(if (nil? prefs)
(let [prefs (pref/environment default-config)]
(doseq [[k v] prefs]
(doseq [callback @set-config-hooks]
((eval callback) k v)))
prefs)
prefs))))
(defn config
([]
(config nil))
([key & {:keys [expect?]
:or {expect? nil}}]
(if (nil? key)
(config-data)
(let [val (get (config-data) key)]
(if (and (nil? val) expect?)
(-> (format "no such variable: %s" (name key))
(ex-info {:key key})
throw))
val))))
(defn set-config
"Set variable with name **key** to **value** and save."
[key value]
(log/tracef "%s -> %s" key value)
(config)
(if (and @config-data-inst (config :strict)
(not (contains? default-config key)))
(-> (format "no such variable: %s" (name key))
(ex-info {:key key :value value})
throw))
(let [val (if (and (contains? parse-keys key)
(string? value))
(read-string value)
value)]
(swap! config-data-inst assoc key val)
(doseq [callback @set-config-hooks]
((eval callback) key value))
(pref/set-environment @config-data-inst)
(log/tracef "vars: %s" @config-data-inst)))
(defn remove-config
"Remove variable with name **key** and save."
[key]
(if (contains? default-config key)
(-> (format "can not delete built in variable: %s" key)
(ex-info {:key key})
throw))
(if (not (contains? (config) key))
(-> (format "no such user variable: %s" key)
(ex-info {:key key})
throw))
(swap! config-data-inst dissoc key)
(pref/set-environment @config-data-inst))
(defn- user-variable-names
"Return a list of the variable keys in user space."
[]
(->> (keys default-config)
set
(difference (set (keys (config))))))
(defn print-key-values
"Print state of variable key/value pairs as markdown."
[]
(let [conf (config)]
(letfn [(pr-conf [key]
(let [val (get conf key)
val (if (nil? val)
"<none>"
val)]
(println (format " * %s: %s" (name key) val))))]
(println "# Built in variables:")
(->> (map first var-meta)
(map pr-conf)
doall)
(println "# User variables:")
(->> (user-variable-names)
(map pr-conf)
doall))))
(defn print-key-desc
"Print variable names and documentation as markdown."
[space]
(let [space (or space 0)
space (->> (map first var-meta)
(map #(-> % name count))
(reduce max)
(max 0)
inc
(max space))
fmt (str " * %-" space "s %s")]
(->> var-meta
(map (fn [[k d v]]
(println (format fmt (str (name k)) v))))
doall)))
(defn help-section
"Return help section for the variable with **key** if there is one."
[key]
(get help-sections key))
(defn reset
"Reset **all** variable data to it's initial nascent state."
[]
(pref/clear :var 'environment)
(reset! config-data-inst nil)
(config))
(defn format-version []
(format "v%s " ver/version))
(defn format-intro []
(format "Clojure Interactive SQL (cisql) %s
(C) Paul Landes 2015 - 2021"
(format-version)))
(defn print-help []
(println (format-intro))
(println help-message))
|
|
1d2855989dc679ada9f0dba9d192fb49a2553699d04f57f1fb702524ade9bf64
|
elaforge/karya
|
Warning.hs
|
Copyright 2013
-- This program is distributed under the terms of the GNU General Public
-- License 3.0, see COPYING or -3.0.txt
module Perform.Warning where
import qualified Control.DeepSeq as DeepSeq
import qualified Derive.Stack as Stack
import Types
data Warning = Warning {
warn_msg :: String
, warn_event :: Stack.Stack
-- | Range that the warning covers. It should be within the event's
-- range. It's in real time, so it needs to be converted back to
-- score time, and it's (start, end) rather than (start, dur).
TODO : convert these back to ScoreTime with the tempo map
-- then I can put them in the stack
, warn_pos :: Maybe (RealTime, RealTime)
} deriving (Eq, Show)
warning = Warning
instance DeepSeq.NFData Warning where
rnf (Warning msg stack pos) = DeepSeq.rnf msg `seq` DeepSeq.rnf stack
`seq` DeepSeq.rnf pos
| null |
https://raw.githubusercontent.com/elaforge/karya/471a2131f5a68b3b10b1a138e6f9ed1282980a18/Perform/Warning.hs
|
haskell
|
This program is distributed under the terms of the GNU General Public
License 3.0, see COPYING or -3.0.txt
| Range that the warning covers. It should be within the event's
range. It's in real time, so it needs to be converted back to
score time, and it's (start, end) rather than (start, dur).
then I can put them in the stack
|
Copyright 2013
module Perform.Warning where
import qualified Control.DeepSeq as DeepSeq
import qualified Derive.Stack as Stack
import Types
data Warning = Warning {
warn_msg :: String
, warn_event :: Stack.Stack
TODO : convert these back to ScoreTime with the tempo map
, warn_pos :: Maybe (RealTime, RealTime)
} deriving (Eq, Show)
warning = Warning
instance DeepSeq.NFData Warning where
rnf (Warning msg stack pos) = DeepSeq.rnf msg `seq` DeepSeq.rnf stack
`seq` DeepSeq.rnf pos
|
330f59413b2bc9880ad1b72b4f26c5584308388855873af21093cf583e467a18
|
lijunsong/pollen-rock
|
tags-handler.rkt
|
#lang racket
(require json)
(require web-server/http/request-structs)
(require "expose-module.rkt")
(provide tags-answer
tags-handler
do-get-tags)
(define/contract (tags-answer errno tags)
(-> integer? (listof (hash/c symbol? jsexpr?)) jsexpr?)
(hash 'errno errno
'tags tags))
(define/contract (tags-handler req url-parts tags-getter)
(-> request? (listof string?)
(-> path-string? (listof jsexpr?)) jsexpr?)
(define mod-path (apply build-path url-parts))
(tags-answer 0 (tags-getter mod-path)))
;; TODO: make extract-module-bindings take non-list and return
;; another value to indicate if extraction succeeds.
(define/contract (do-get-tags mod-path)
(-> (or/c path-string? symbol?) (listof jsexpr?))
(extract-module-bindings (list mod-path)))
(module+ test
(require rackunit)
(require "../http-util.rkt")
(define tags-request-url-parts
(list "path1" "path2" "file.html.pm"))
(define tags-request
(make-test-request "tags" tags-request-url-parts
(hash)))
;; test that handler passes the correct path into getter
(check-equal?
(tags-answer 0 (list (hash 'x 1)))
(tags-handler
tags-request tags-request-url-parts
(lambda (mod-path)
(check-equal?
mod-path
(apply build-path tags-request-url-parts))
(list (hash 'x 1)))))
)
| null |
https://raw.githubusercontent.com/lijunsong/pollen-rock/8107c7c1a1ca1e5ab125650f38002683b15b22c9/pollen-rock/handlers/tags-handler.rkt
|
racket
|
TODO: make extract-module-bindings take non-list and return
another value to indicate if extraction succeeds.
test that handler passes the correct path into getter
|
#lang racket
(require json)
(require web-server/http/request-structs)
(require "expose-module.rkt")
(provide tags-answer
tags-handler
do-get-tags)
(define/contract (tags-answer errno tags)
(-> integer? (listof (hash/c symbol? jsexpr?)) jsexpr?)
(hash 'errno errno
'tags tags))
(define/contract (tags-handler req url-parts tags-getter)
(-> request? (listof string?)
(-> path-string? (listof jsexpr?)) jsexpr?)
(define mod-path (apply build-path url-parts))
(tags-answer 0 (tags-getter mod-path)))
(define/contract (do-get-tags mod-path)
(-> (or/c path-string? symbol?) (listof jsexpr?))
(extract-module-bindings (list mod-path)))
(module+ test
(require rackunit)
(require "../http-util.rkt")
(define tags-request-url-parts
(list "path1" "path2" "file.html.pm"))
(define tags-request
(make-test-request "tags" tags-request-url-parts
(hash)))
(check-equal?
(tags-answer 0 (list (hash 'x 1)))
(tags-handler
tags-request tags-request-url-parts
(lambda (mod-path)
(check-equal?
mod-path
(apply build-path tags-request-url-parts))
(list (hash 'x 1)))))
)
|
fab673fa17d98626420b100f6d2cc2cfadbc1b2c1d97a69cf85e74acf683b7ee
|
ocaml/ocaml
|
pr10189.ml
|
(* TEST
* expect
*)
type i = <m : 'c. 'c -> 'c >
type ('a, 'b) j = <m : 'c. 'a -> 'b >
type _ t = A : i t;;
[%%expect{|
type i = < m : 'c. 'c -> 'c >
type ('a, 'b) j = < m : 'a -> 'b >
type _ t = A : i t
|}]
let f (type a b) (y : (a, b) j t) : a -> b =
let A = y in fun x -> x;;
[%%expect{|
Line 2, characters 6-7:
2 | let A = y in fun x -> x;;
^
Error: This pattern matches values of type i t
but a pattern was expected which matches values of type (a, b) j t
Type i = < m : 'c. 'c -> 'c > is not compatible with type
(a, b) j = < m : a -> b >
The method m has type 'c. 'c -> 'c, but the expected method type was
a -> b
The universal variable 'c would escape its scope
|}]
let g (type a b) (y : (a,b) j t option) =
let None = y in () ;;
[%%expect{|
val g : ('a, 'b) j t option -> unit = <fun>
|}]
module M = struct
type 'a d = D
type j = <m : 'c. 'c -> 'c d >
end ;;
let g (y : M.j t option) =
let None = y in () ;;
[%%expect{|
module M : sig type 'a d = D type j = < m : 'c. 'c -> 'c d > end
val g : M.j t option -> unit = <fun>
|}]
module M = struct
type 'a d
type j = <m : 'c. 'c -> 'c d >
end ;;
let g (y : M.j t option) =
let None = y in () ;;
[%%expect{|
module M : sig type 'a d type j = < m : 'c. 'c -> 'c d > end
Line 6, characters 2-20:
6 | let None = y in () ;;
^^^^^^^^^^^^^^^^^^
Warning 8 [partial-match]: this pattern-matching is not exhaustive.
Here is an example of a case that is not matched:
Some A
val g : M.j t option -> unit = <fun>
|}]
module M = struct
type e
type 'a d
type i = <m : 'c. 'c -> 'c d >
type j = <m : 'c. 'c -> e >
end ;;
type _ t = A : M.i t
let g (y : M.j t option) =
let None = y in () ;;
[%%expect{|
module M :
sig
type e
type 'a d
type i = < m : 'c. 'c -> 'c d >
type j = < m : 'c. 'c -> e >
end
type _ t = A : M.i t
Line 9, characters 2-20:
9 | let None = y in () ;;
^^^^^^^^^^^^^^^^^^
Warning 8 [partial-match]: this pattern-matching is not exhaustive.
Here is an example of a case that is not matched:
Some A
val g : M.j t option -> unit = <fun>
|}]
module M = struct
type 'a d
type i = <m : 'c. 'c -> 'c d >
type 'a j = <m : 'c. 'c -> 'a >
end ;;
type _ t = A : M.i t
(* Should warn *)
let g (y : 'a M.j t option) =
let None = y in () ;;
[%%expect{|
module M :
sig
type 'a d
type i = < m : 'c. 'c -> 'c d >
type 'a j = < m : 'c. 'c -> 'a >
end
type _ t = A : M.i t
Line 9, characters 2-20:
9 | let None = y in () ;;
^^^^^^^^^^^^^^^^^^
Warning 8 [partial-match]: this pattern-matching is not exhaustive.
Here is an example of a case that is not matched:
Some A
val g : 'a M.j t option -> unit = <fun>
|}]
more examples by @lpw25
module M = struct
type a
type i = C of <m : 'c. 'c -> 'c >
type j = C of <m : 'c. 'c -> a >
end
type _ t = A : M.i t;;
let f (y : M.j t) = match y with _ -> .;;
[%%expect{|
module M :
sig
type a
type i = C of < m : 'c. 'c -> 'c >
type j = C of < m : 'c. 'c -> a >
end
type _ t = A : M.i t
val f : M.j t -> 'a = <fun>
|}]
module M = struct
type a
type i = C of <m : 'c. 'c -> 'c -> 'c >
type j = C of <m : 'c. 'c -> a >
end
type _ t = A : M.i t;;
let f (y : M.j t) = match y with _ -> .;;
[%%expect{|
module M :
sig
type a
type i = C of < m : 'c. 'c -> 'c -> 'c >
type j = C of < m : 'c. 'c -> a >
end
type _ t = A : M.i t
val f : M.j t -> 'a = <fun>
|}]
module M = struct
type 'a a
type i = C of <m : 'c. 'c -> 'c -> 'c >
type j = C of <m : 'c. 'c -> 'c a >
end
type _ t = A : M.i t;;
let f (y : M.j t) = match y with _ -> .;;
[%%expect{|
module M :
sig
type 'a a
type i = C of < m : 'c. 'c -> 'c -> 'c >
type j = C of < m : 'c. 'c -> 'c a >
end
type _ t = A : M.i t
Line 7, characters 33-34:
7 | let f (y : M.j t) = match y with _ -> .;;
^
Error: This match case could not be refuted.
Here is an example of a value that would reach it: A
|}]
| null |
https://raw.githubusercontent.com/ocaml/ocaml/d71ea3d089ae3c338b8b6e2fb7beb08908076c7a/testsuite/tests/typing-gadts/pr10189.ml
|
ocaml
|
TEST
* expect
Should warn
|
type i = <m : 'c. 'c -> 'c >
type ('a, 'b) j = <m : 'c. 'a -> 'b >
type _ t = A : i t;;
[%%expect{|
type i = < m : 'c. 'c -> 'c >
type ('a, 'b) j = < m : 'a -> 'b >
type _ t = A : i t
|}]
let f (type a b) (y : (a, b) j t) : a -> b =
let A = y in fun x -> x;;
[%%expect{|
Line 2, characters 6-7:
2 | let A = y in fun x -> x;;
^
Error: This pattern matches values of type i t
but a pattern was expected which matches values of type (a, b) j t
Type i = < m : 'c. 'c -> 'c > is not compatible with type
(a, b) j = < m : a -> b >
The method m has type 'c. 'c -> 'c, but the expected method type was
a -> b
The universal variable 'c would escape its scope
|}]
let g (type a b) (y : (a,b) j t option) =
let None = y in () ;;
[%%expect{|
val g : ('a, 'b) j t option -> unit = <fun>
|}]
module M = struct
type 'a d = D
type j = <m : 'c. 'c -> 'c d >
end ;;
let g (y : M.j t option) =
let None = y in () ;;
[%%expect{|
module M : sig type 'a d = D type j = < m : 'c. 'c -> 'c d > end
val g : M.j t option -> unit = <fun>
|}]
module M = struct
type 'a d
type j = <m : 'c. 'c -> 'c d >
end ;;
let g (y : M.j t option) =
let None = y in () ;;
[%%expect{|
module M : sig type 'a d type j = < m : 'c. 'c -> 'c d > end
Line 6, characters 2-20:
6 | let None = y in () ;;
^^^^^^^^^^^^^^^^^^
Warning 8 [partial-match]: this pattern-matching is not exhaustive.
Here is an example of a case that is not matched:
Some A
val g : M.j t option -> unit = <fun>
|}]
module M = struct
type e
type 'a d
type i = <m : 'c. 'c -> 'c d >
type j = <m : 'c. 'c -> e >
end ;;
type _ t = A : M.i t
let g (y : M.j t option) =
let None = y in () ;;
[%%expect{|
module M :
sig
type e
type 'a d
type i = < m : 'c. 'c -> 'c d >
type j = < m : 'c. 'c -> e >
end
type _ t = A : M.i t
Line 9, characters 2-20:
9 | let None = y in () ;;
^^^^^^^^^^^^^^^^^^
Warning 8 [partial-match]: this pattern-matching is not exhaustive.
Here is an example of a case that is not matched:
Some A
val g : M.j t option -> unit = <fun>
|}]
module M = struct
type 'a d
type i = <m : 'c. 'c -> 'c d >
type 'a j = <m : 'c. 'c -> 'a >
end ;;
type _ t = A : M.i t
let g (y : 'a M.j t option) =
let None = y in () ;;
[%%expect{|
module M :
sig
type 'a d
type i = < m : 'c. 'c -> 'c d >
type 'a j = < m : 'c. 'c -> 'a >
end
type _ t = A : M.i t
Line 9, characters 2-20:
9 | let None = y in () ;;
^^^^^^^^^^^^^^^^^^
Warning 8 [partial-match]: this pattern-matching is not exhaustive.
Here is an example of a case that is not matched:
Some A
val g : 'a M.j t option -> unit = <fun>
|}]
more examples by @lpw25
module M = struct
type a
type i = C of <m : 'c. 'c -> 'c >
type j = C of <m : 'c. 'c -> a >
end
type _ t = A : M.i t;;
let f (y : M.j t) = match y with _ -> .;;
[%%expect{|
module M :
sig
type a
type i = C of < m : 'c. 'c -> 'c >
type j = C of < m : 'c. 'c -> a >
end
type _ t = A : M.i t
val f : M.j t -> 'a = <fun>
|}]
module M = struct
type a
type i = C of <m : 'c. 'c -> 'c -> 'c >
type j = C of <m : 'c. 'c -> a >
end
type _ t = A : M.i t;;
let f (y : M.j t) = match y with _ -> .;;
[%%expect{|
module M :
sig
type a
type i = C of < m : 'c. 'c -> 'c -> 'c >
type j = C of < m : 'c. 'c -> a >
end
type _ t = A : M.i t
val f : M.j t -> 'a = <fun>
|}]
module M = struct
type 'a a
type i = C of <m : 'c. 'c -> 'c -> 'c >
type j = C of <m : 'c. 'c -> 'c a >
end
type _ t = A : M.i t;;
let f (y : M.j t) = match y with _ -> .;;
[%%expect{|
module M :
sig
type 'a a
type i = C of < m : 'c. 'c -> 'c -> 'c >
type j = C of < m : 'c. 'c -> 'c a >
end
type _ t = A : M.i t
Line 7, characters 33-34:
7 | let f (y : M.j t) = match y with _ -> .;;
^
Error: This match case could not be refuted.
Here is an example of a value that would reach it: A
|}]
|
b77b911ca7a4bd449eb6e20cc71e83b86dbc2222653b5064eff68eeb631ed4e4
|
haskell-opengl/OpenGLRaw
|
TransformFeedback.hs
|
# LANGUAGE PatternSynonyms #
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.GL.NV.TransformFeedback
Copyright : ( c ) 2019
-- License : BSD3
--
Maintainer : < >
-- Stability : stable
-- Portability : portable
--
--------------------------------------------------------------------------------
module Graphics.GL.NV.TransformFeedback (
-- * Extension Support
glGetNVTransformFeedback,
gl_NV_transform_feedback,
-- * Enums
pattern GL_ACTIVE_VARYINGS_NV,
pattern GL_ACTIVE_VARYING_MAX_LENGTH_NV,
pattern GL_BACK_PRIMARY_COLOR_NV,
pattern GL_BACK_SECONDARY_COLOR_NV,
pattern GL_CLIP_DISTANCE_NV,
pattern GL_GENERIC_ATTRIB_NV,
pattern GL_INTERLEAVED_ATTRIBS_NV,
pattern GL_LAYER_NV,
pattern GL_MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS_NV,
pattern GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS_NV,
pattern GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS_NV,
pattern GL_NEXT_BUFFER_NV,
pattern GL_PRIMITIVES_GENERATED_NV,
pattern GL_PRIMITIVE_ID_NV,
pattern GL_RASTERIZER_DISCARD_NV,
pattern GL_SEPARATE_ATTRIBS_NV,
pattern GL_SKIP_COMPONENTS1_NV,
pattern GL_SKIP_COMPONENTS2_NV,
pattern GL_SKIP_COMPONENTS3_NV,
pattern GL_SKIP_COMPONENTS4_NV,
pattern GL_TEXTURE_COORD_NV,
pattern GL_TRANSFORM_FEEDBACK_ATTRIBS_NV,
pattern GL_TRANSFORM_FEEDBACK_BUFFER_BINDING_NV,
pattern GL_TRANSFORM_FEEDBACK_BUFFER_MODE_NV,
pattern GL_TRANSFORM_FEEDBACK_BUFFER_NV,
pattern GL_TRANSFORM_FEEDBACK_BUFFER_SIZE_NV,
pattern GL_TRANSFORM_FEEDBACK_BUFFER_START_NV,
pattern GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN_NV,
pattern GL_TRANSFORM_FEEDBACK_RECORD_NV,
pattern GL_TRANSFORM_FEEDBACK_VARYINGS_NV,
pattern GL_VERTEX_ID_NV,
-- * Functions
glActiveVaryingNV,
glBeginTransformFeedbackNV,
glBindBufferBaseNV,
glBindBufferOffsetNV,
glBindBufferRangeNV,
glEndTransformFeedbackNV,
glGetActiveVaryingNV,
glGetTransformFeedbackVaryingNV,
glGetVaryingLocationNV,
glTransformFeedbackAttribsNV,
glTransformFeedbackStreamAttribsNV,
glTransformFeedbackVaryingsNV
) where
import Graphics.GL.ExtensionPredicates
import Graphics.GL.Tokens
import Graphics.GL.Functions
| null |
https://raw.githubusercontent.com/haskell-opengl/OpenGLRaw/57e50c9d28dfa62d6a87ae9b561af28f64ce32a0/src/Graphics/GL/NV/TransformFeedback.hs
|
haskell
|
------------------------------------------------------------------------------
|
Module : Graphics.GL.NV.TransformFeedback
License : BSD3
Stability : stable
Portability : portable
------------------------------------------------------------------------------
* Extension Support
* Enums
* Functions
|
# LANGUAGE PatternSynonyms #
Copyright : ( c ) 2019
Maintainer : < >
module Graphics.GL.NV.TransformFeedback (
glGetNVTransformFeedback,
gl_NV_transform_feedback,
pattern GL_ACTIVE_VARYINGS_NV,
pattern GL_ACTIVE_VARYING_MAX_LENGTH_NV,
pattern GL_BACK_PRIMARY_COLOR_NV,
pattern GL_BACK_SECONDARY_COLOR_NV,
pattern GL_CLIP_DISTANCE_NV,
pattern GL_GENERIC_ATTRIB_NV,
pattern GL_INTERLEAVED_ATTRIBS_NV,
pattern GL_LAYER_NV,
pattern GL_MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS_NV,
pattern GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS_NV,
pattern GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS_NV,
pattern GL_NEXT_BUFFER_NV,
pattern GL_PRIMITIVES_GENERATED_NV,
pattern GL_PRIMITIVE_ID_NV,
pattern GL_RASTERIZER_DISCARD_NV,
pattern GL_SEPARATE_ATTRIBS_NV,
pattern GL_SKIP_COMPONENTS1_NV,
pattern GL_SKIP_COMPONENTS2_NV,
pattern GL_SKIP_COMPONENTS3_NV,
pattern GL_SKIP_COMPONENTS4_NV,
pattern GL_TEXTURE_COORD_NV,
pattern GL_TRANSFORM_FEEDBACK_ATTRIBS_NV,
pattern GL_TRANSFORM_FEEDBACK_BUFFER_BINDING_NV,
pattern GL_TRANSFORM_FEEDBACK_BUFFER_MODE_NV,
pattern GL_TRANSFORM_FEEDBACK_BUFFER_NV,
pattern GL_TRANSFORM_FEEDBACK_BUFFER_SIZE_NV,
pattern GL_TRANSFORM_FEEDBACK_BUFFER_START_NV,
pattern GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN_NV,
pattern GL_TRANSFORM_FEEDBACK_RECORD_NV,
pattern GL_TRANSFORM_FEEDBACK_VARYINGS_NV,
pattern GL_VERTEX_ID_NV,
glActiveVaryingNV,
glBeginTransformFeedbackNV,
glBindBufferBaseNV,
glBindBufferOffsetNV,
glBindBufferRangeNV,
glEndTransformFeedbackNV,
glGetActiveVaryingNV,
glGetTransformFeedbackVaryingNV,
glGetVaryingLocationNV,
glTransformFeedbackAttribsNV,
glTransformFeedbackStreamAttribsNV,
glTransformFeedbackVaryingsNV
) where
import Graphics.GL.ExtensionPredicates
import Graphics.GL.Tokens
import Graphics.GL.Functions
|
1460ced54bc50fcc5e4126f63e4487c3a361505bc3ede8d5a82b5ad86e51b754
|
brendanhay/amazonka
|
Choice.hs
|
# LANGUAGE DeriveGeneric #
# LANGUAGE DuplicateRecordFields #
# LANGUAGE NamedFieldPuns #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE RecordWildCards #
{-# LANGUAGE StrictData #-}
# LANGUAGE NoImplicitPrelude #
# OPTIONS_GHC -fno - warn - unused - imports #
# OPTIONS_GHC -fno - warn - unused - matches #
Derived from AWS service descriptions , licensed under Apache 2.0 .
-- |
-- Module : Amazonka.WellArchitected.Types.Choice
Copyright : ( c ) 2013 - 2023
License : Mozilla Public License , v. 2.0 .
Maintainer : < brendan.g.hay+ >
-- Stability : auto-generated
Portability : non - portable ( GHC extensions )
module Amazonka.WellArchitected.Types.Choice where
import qualified Amazonka.Core as Core
import qualified Amazonka.Core.Lens.Internal as Lens
import qualified Amazonka.Data as Data
import qualified Amazonka.Prelude as Prelude
import Amazonka.WellArchitected.Types.AdditionalResources
import Amazonka.WellArchitected.Types.ChoiceContent
-- | A choice available to answer question.
--
/See:/ ' newChoice ' smart constructor .
data Choice = Choice'
| The additional resources for a choice . A choice can have up to two
additional resources : one of type @HELPFUL_RESOURCE@ , one of type
@IMPROVEMENT_PLAN@ , or both .
additionalResources :: Prelude.Maybe [AdditionalResources],
choiceId :: Prelude.Maybe Prelude.Text,
description :: Prelude.Maybe Prelude.Text,
-- | The choice level helpful resource.
helpfulResource :: Prelude.Maybe ChoiceContent,
-- | The choice level improvement plan.
improvementPlan :: Prelude.Maybe ChoiceContent,
title :: Prelude.Maybe Prelude.Text
}
deriving (Prelude.Eq, Prelude.Read, Prelude.Show, Prelude.Generic)
-- |
-- Create a value of 'Choice' with all optional fields omitted.
--
Use < -lens generic - lens > or < optics > to modify other optional fields .
--
-- The following record fields are available, with the corresponding lenses provided
-- for backwards compatibility:
--
' additionalResources ' , ' choice_additionalResources ' - The additional resources for a choice . A choice can have up to two
additional resources : one of type @HELPFUL_RESOURCE@ , one of type
@IMPROVEMENT_PLAN@ , or both .
--
-- 'choiceId', 'choice_choiceId' - Undocumented member.
--
-- 'description', 'choice_description' - Undocumented member.
--
-- 'helpfulResource', 'choice_helpfulResource' - The choice level helpful resource.
--
-- 'improvementPlan', 'choice_improvementPlan' - The choice level improvement plan.
--
-- 'title', 'choice_title' - Undocumented member.
newChoice ::
Choice
newChoice =
Choice'
{ additionalResources = Prelude.Nothing,
choiceId = Prelude.Nothing,
description = Prelude.Nothing,
helpfulResource = Prelude.Nothing,
improvementPlan = Prelude.Nothing,
title = Prelude.Nothing
}
| The additional resources for a choice . A choice can have up to two
additional resources : one of type @HELPFUL_RESOURCE@ , one of type
@IMPROVEMENT_PLAN@ , or both .
choice_additionalResources :: Lens.Lens' Choice (Prelude.Maybe [AdditionalResources])
choice_additionalResources = Lens.lens (\Choice' {additionalResources} -> additionalResources) (\s@Choice' {} a -> s {additionalResources = a} :: Choice) Prelude.. Lens.mapping Lens.coerced
-- | Undocumented member.
choice_choiceId :: Lens.Lens' Choice (Prelude.Maybe Prelude.Text)
choice_choiceId = Lens.lens (\Choice' {choiceId} -> choiceId) (\s@Choice' {} a -> s {choiceId = a} :: Choice)
-- | Undocumented member.
choice_description :: Lens.Lens' Choice (Prelude.Maybe Prelude.Text)
choice_description = Lens.lens (\Choice' {description} -> description) (\s@Choice' {} a -> s {description = a} :: Choice)
-- | The choice level helpful resource.
choice_helpfulResource :: Lens.Lens' Choice (Prelude.Maybe ChoiceContent)
choice_helpfulResource = Lens.lens (\Choice' {helpfulResource} -> helpfulResource) (\s@Choice' {} a -> s {helpfulResource = a} :: Choice)
-- | The choice level improvement plan.
choice_improvementPlan :: Lens.Lens' Choice (Prelude.Maybe ChoiceContent)
choice_improvementPlan = Lens.lens (\Choice' {improvementPlan} -> improvementPlan) (\s@Choice' {} a -> s {improvementPlan = a} :: Choice)
-- | Undocumented member.
choice_title :: Lens.Lens' Choice (Prelude.Maybe Prelude.Text)
choice_title = Lens.lens (\Choice' {title} -> title) (\s@Choice' {} a -> s {title = a} :: Choice)
instance Data.FromJSON Choice where
parseJSON =
Data.withObject
"Choice"
( \x ->
Choice'
Prelude.<$> ( x Data..:? "AdditionalResources"
Data..!= Prelude.mempty
)
Prelude.<*> (x Data..:? "ChoiceId")
Prelude.<*> (x Data..:? "Description")
Prelude.<*> (x Data..:? "HelpfulResource")
Prelude.<*> (x Data..:? "ImprovementPlan")
Prelude.<*> (x Data..:? "Title")
)
instance Prelude.Hashable Choice where
hashWithSalt _salt Choice' {..} =
_salt `Prelude.hashWithSalt` additionalResources
`Prelude.hashWithSalt` choiceId
`Prelude.hashWithSalt` description
`Prelude.hashWithSalt` helpfulResource
`Prelude.hashWithSalt` improvementPlan
`Prelude.hashWithSalt` title
instance Prelude.NFData Choice where
rnf Choice' {..} =
Prelude.rnf additionalResources
`Prelude.seq` Prelude.rnf choiceId
`Prelude.seq` Prelude.rnf description
`Prelude.seq` Prelude.rnf helpfulResource
`Prelude.seq` Prelude.rnf improvementPlan
`Prelude.seq` Prelude.rnf title
| null |
https://raw.githubusercontent.com/brendanhay/amazonka/09f52b75d2cfdff221b439280d3279d22690d6a6/lib/services/amazonka-wellarchitected/gen/Amazonka/WellArchitected/Types/Choice.hs
|
haskell
|
# LANGUAGE OverloadedStrings #
# LANGUAGE StrictData #
|
Module : Amazonka.WellArchitected.Types.Choice
Stability : auto-generated
| A choice available to answer question.
| The choice level helpful resource.
| The choice level improvement plan.
|
Create a value of 'Choice' with all optional fields omitted.
The following record fields are available, with the corresponding lenses provided
for backwards compatibility:
'choiceId', 'choice_choiceId' - Undocumented member.
'description', 'choice_description' - Undocumented member.
'helpfulResource', 'choice_helpfulResource' - The choice level helpful resource.
'improvementPlan', 'choice_improvementPlan' - The choice level improvement plan.
'title', 'choice_title' - Undocumented member.
| Undocumented member.
| Undocumented member.
| The choice level helpful resource.
| The choice level improvement plan.
| Undocumented member.
|
# LANGUAGE DeriveGeneric #
# LANGUAGE DuplicateRecordFields #
# LANGUAGE NamedFieldPuns #
# LANGUAGE RecordWildCards #
# LANGUAGE NoImplicitPrelude #
# OPTIONS_GHC -fno - warn - unused - imports #
# OPTIONS_GHC -fno - warn - unused - matches #
Derived from AWS service descriptions , licensed under Apache 2.0 .
Copyright : ( c ) 2013 - 2023
License : Mozilla Public License , v. 2.0 .
Maintainer : < brendan.g.hay+ >
Portability : non - portable ( GHC extensions )
module Amazonka.WellArchitected.Types.Choice where
import qualified Amazonka.Core as Core
import qualified Amazonka.Core.Lens.Internal as Lens
import qualified Amazonka.Data as Data
import qualified Amazonka.Prelude as Prelude
import Amazonka.WellArchitected.Types.AdditionalResources
import Amazonka.WellArchitected.Types.ChoiceContent
/See:/ ' newChoice ' smart constructor .
data Choice = Choice'
| The additional resources for a choice . A choice can have up to two
additional resources : one of type @HELPFUL_RESOURCE@ , one of type
@IMPROVEMENT_PLAN@ , or both .
additionalResources :: Prelude.Maybe [AdditionalResources],
choiceId :: Prelude.Maybe Prelude.Text,
description :: Prelude.Maybe Prelude.Text,
helpfulResource :: Prelude.Maybe ChoiceContent,
improvementPlan :: Prelude.Maybe ChoiceContent,
title :: Prelude.Maybe Prelude.Text
}
deriving (Prelude.Eq, Prelude.Read, Prelude.Show, Prelude.Generic)
Use < -lens generic - lens > or < optics > to modify other optional fields .
' additionalResources ' , ' choice_additionalResources ' - The additional resources for a choice . A choice can have up to two
additional resources : one of type @HELPFUL_RESOURCE@ , one of type
@IMPROVEMENT_PLAN@ , or both .
newChoice ::
Choice
newChoice =
Choice'
{ additionalResources = Prelude.Nothing,
choiceId = Prelude.Nothing,
description = Prelude.Nothing,
helpfulResource = Prelude.Nothing,
improvementPlan = Prelude.Nothing,
title = Prelude.Nothing
}
| The additional resources for a choice . A choice can have up to two
additional resources : one of type @HELPFUL_RESOURCE@ , one of type
@IMPROVEMENT_PLAN@ , or both .
choice_additionalResources :: Lens.Lens' Choice (Prelude.Maybe [AdditionalResources])
choice_additionalResources = Lens.lens (\Choice' {additionalResources} -> additionalResources) (\s@Choice' {} a -> s {additionalResources = a} :: Choice) Prelude.. Lens.mapping Lens.coerced
choice_choiceId :: Lens.Lens' Choice (Prelude.Maybe Prelude.Text)
choice_choiceId = Lens.lens (\Choice' {choiceId} -> choiceId) (\s@Choice' {} a -> s {choiceId = a} :: Choice)
choice_description :: Lens.Lens' Choice (Prelude.Maybe Prelude.Text)
choice_description = Lens.lens (\Choice' {description} -> description) (\s@Choice' {} a -> s {description = a} :: Choice)
choice_helpfulResource :: Lens.Lens' Choice (Prelude.Maybe ChoiceContent)
choice_helpfulResource = Lens.lens (\Choice' {helpfulResource} -> helpfulResource) (\s@Choice' {} a -> s {helpfulResource = a} :: Choice)
choice_improvementPlan :: Lens.Lens' Choice (Prelude.Maybe ChoiceContent)
choice_improvementPlan = Lens.lens (\Choice' {improvementPlan} -> improvementPlan) (\s@Choice' {} a -> s {improvementPlan = a} :: Choice)
choice_title :: Lens.Lens' Choice (Prelude.Maybe Prelude.Text)
choice_title = Lens.lens (\Choice' {title} -> title) (\s@Choice' {} a -> s {title = a} :: Choice)
instance Data.FromJSON Choice where
parseJSON =
Data.withObject
"Choice"
( \x ->
Choice'
Prelude.<$> ( x Data..:? "AdditionalResources"
Data..!= Prelude.mempty
)
Prelude.<*> (x Data..:? "ChoiceId")
Prelude.<*> (x Data..:? "Description")
Prelude.<*> (x Data..:? "HelpfulResource")
Prelude.<*> (x Data..:? "ImprovementPlan")
Prelude.<*> (x Data..:? "Title")
)
instance Prelude.Hashable Choice where
hashWithSalt _salt Choice' {..} =
_salt `Prelude.hashWithSalt` additionalResources
`Prelude.hashWithSalt` choiceId
`Prelude.hashWithSalt` description
`Prelude.hashWithSalt` helpfulResource
`Prelude.hashWithSalt` improvementPlan
`Prelude.hashWithSalt` title
instance Prelude.NFData Choice where
rnf Choice' {..} =
Prelude.rnf additionalResources
`Prelude.seq` Prelude.rnf choiceId
`Prelude.seq` Prelude.rnf description
`Prelude.seq` Prelude.rnf helpfulResource
`Prelude.seq` Prelude.rnf improvementPlan
`Prelude.seq` Prelude.rnf title
|
347fa02774176482d9dc3328f0ed5b1f9ffee6935c3f630a9b1ad13f1e904b7d
|
BoeingX/haskell-programming-from-first-principles
|
SmallLibraryForMaybeSpec.hs
|
module SignalingAdversity.ChapterExercises.SmallLibraryForMaybeSpec where
import Test.Hspec
import SignalingAdversity.ChapterExercises.SmallLibraryForMaybe
spec :: Spec
spec = do
describe "Test isJust" $ do
it "isJust (Just 1)" $ do
isJust (Just 1) `shouldBe` True
it "isJust Nothing" $ do
isJust Nothing `shouldBe` False
describe "Test isNothing" $ do
it "isNothing (Just 1)" $ do
isNothing (Just 1) `shouldBe` False
it "isNothing Nothing" $ do
isNothing Nothing `shouldBe` True
describe "Test maybee" $ do
it "mayybee 0 (+1) Nothing" $ do
mayybee 0 (+1) Nothing `shouldBe` 0
it "mayybee 0 (+1) (Just 1)" $ do
mayybee 0 (+1) (Just 1) `shouldBe` 2
describe "Test fromMaybe" $ do
it "fromMaybe 0 Nothing" $ do
fromMaybe 0 Nothing `shouldBe` 0
it "fromMaybe 0 (Just 1)" $ do
fromMaybe 0 (Just 1) `shouldBe` 1
describe "Test listToMaybe" $ do
it "listToMaybe [1, 2, 3]" $ do
listToMaybe [1, 2, 3] `shouldBe` Just 1
it "listToMaybe []" $ do
listToMaybe ([] :: [Int]) `shouldBe` (Nothing :: Maybe Int)
describe "Test maybeToList" $ do
it "maybeToList (Just 1)" $ do
maybeToList (Just 1) `shouldBe` [1]
it "maybeToList Nothing" $ do
maybeToList (Nothing :: Maybe Int) `shouldBe` ([] :: [Int])
describe "Test catMaybes" $ do
it "catMaybes [Just 1, Nothing, Just 2]" $ do
catMaybes [Just 1, Nothing, Just 2] `shouldBe` [1, 2]
it "catMaybes [Nothing, Nothing, Nothing]" $ do
catMaybes ([Nothing, Nothing, Nothing] :: [Maybe Int]) `shouldBe` ([] :: [Int])
describe "Test flipMaybe" $ do
it "flipMaybe [Just 1, Just 2, Just 3]" $ do
flipMaybe [Just 1, Just 2, Just 3] `shouldBe` Just [1, 2, 3]
it "flipMaybe [Just 1, Nothing, Just 3]" $ do
flipMaybe [Just 1, Nothing, Just 3] `shouldBe` (Nothing :: Maybe [Int])
| null |
https://raw.githubusercontent.com/BoeingX/haskell-programming-from-first-principles/ffb637f536597f552a4e4567fee848ed27f3ba74/test/SignalingAdversity/ChapterExercises/SmallLibraryForMaybeSpec.hs
|
haskell
|
module SignalingAdversity.ChapterExercises.SmallLibraryForMaybeSpec where
import Test.Hspec
import SignalingAdversity.ChapterExercises.SmallLibraryForMaybe
spec :: Spec
spec = do
describe "Test isJust" $ do
it "isJust (Just 1)" $ do
isJust (Just 1) `shouldBe` True
it "isJust Nothing" $ do
isJust Nothing `shouldBe` False
describe "Test isNothing" $ do
it "isNothing (Just 1)" $ do
isNothing (Just 1) `shouldBe` False
it "isNothing Nothing" $ do
isNothing Nothing `shouldBe` True
describe "Test maybee" $ do
it "mayybee 0 (+1) Nothing" $ do
mayybee 0 (+1) Nothing `shouldBe` 0
it "mayybee 0 (+1) (Just 1)" $ do
mayybee 0 (+1) (Just 1) `shouldBe` 2
describe "Test fromMaybe" $ do
it "fromMaybe 0 Nothing" $ do
fromMaybe 0 Nothing `shouldBe` 0
it "fromMaybe 0 (Just 1)" $ do
fromMaybe 0 (Just 1) `shouldBe` 1
describe "Test listToMaybe" $ do
it "listToMaybe [1, 2, 3]" $ do
listToMaybe [1, 2, 3] `shouldBe` Just 1
it "listToMaybe []" $ do
listToMaybe ([] :: [Int]) `shouldBe` (Nothing :: Maybe Int)
describe "Test maybeToList" $ do
it "maybeToList (Just 1)" $ do
maybeToList (Just 1) `shouldBe` [1]
it "maybeToList Nothing" $ do
maybeToList (Nothing :: Maybe Int) `shouldBe` ([] :: [Int])
describe "Test catMaybes" $ do
it "catMaybes [Just 1, Nothing, Just 2]" $ do
catMaybes [Just 1, Nothing, Just 2] `shouldBe` [1, 2]
it "catMaybes [Nothing, Nothing, Nothing]" $ do
catMaybes ([Nothing, Nothing, Nothing] :: [Maybe Int]) `shouldBe` ([] :: [Int])
describe "Test flipMaybe" $ do
it "flipMaybe [Just 1, Just 2, Just 3]" $ do
flipMaybe [Just 1, Just 2, Just 3] `shouldBe` Just [1, 2, 3]
it "flipMaybe [Just 1, Nothing, Just 3]" $ do
flipMaybe [Just 1, Nothing, Just 3] `shouldBe` (Nothing :: Maybe [Int])
|
|
3bf1f86f58f166d1a578f6e761f0ef646d214ad9e4d650b50111851f1f7dfa19
|
MyDataFlow/ttalk-server
|
exml_stream_tests.erl
|
-module(exml_stream_tests).
-include("exml_stream.hrl").
-include_lib("eunit/include/eunit.hrl").
-compile(export_all).
parser_error_bad_stream_opt_test() ->
?assertEqual({error, {error, {invalid_parser_opt,
{infinite_stream, infinity}}}},
exml_stream:new_parser([{infinite_stream, infinity}])).
parser_error_bad_autoreset_opt_test() ->
?assertEqual({error, {error, {invalid_parser_opt,
{autoreset, kielbasa}}}},
exml_stream:new_parser([{autoreset, kielbasa}])).
basic_parse_test() ->
{ok, Parser0} = exml_stream:new_parser(),
{ok, Parser1, Empty0} =
exml_stream:parse(Parser0, <<"<stream:stream xmlns:stream='' version='1.0'">>),
?assertEqual([], Empty0),
{ok, Parser2, StreamStart} =
exml_stream:parse(Parser1, <<" to='i.am.banana.com' xml:lang='en'><auth">>),
?assertEqual(
[#xmlstreamstart{name = <<"stream:stream">>,
attrs = [{<<"xmlns:stream">>, <<"">>},
{<<"version">>, <<"1.0">>},
{<<"to">>, <<"i.am.banana.com">>},
{<<"xml:lang">>, <<"en">>}]}],
StreamStart),
{ok, Parser3, Auth} = exml_stream:parse(Parser2, <<" mechanism='DIGEST-MD5'/>">>),
?assertEqual(
[#xmlel{name = <<"auth">>, attrs = [{<<"mechanism">>, <<"DIGEST-MD5">>}]}],
Auth),
{ok, Parser4, Empty1} = exml_stream:parse(Parser3, <<"<stream:features><bind xmlns='some_ns'">>),
?assertEqual([], Empty1),
{ok, Parser5, Empty2} = exml_stream:parse(Parser4, <<"/><session xmlns='some_other'/>This is ">>),
?assertEqual([], Empty2),
{ok, Parser6, Features} = exml_stream:parse(Parser5, <<"some CData</stream:features>">>),
?assertMatch(
[#xmlel{name = <<"stream:features">>,
children = [#xmlel{name = <<"bind">>,
attrs = [{<<"xmlns">>, <<"some_ns">>}]},
#xmlel{name = <<"session">>,
attrs = [{<<"xmlns">>, <<"some_other">>}]},
_CData]}],
Features),
[#xmlel{children=[_, _, CData]}] = Features,
?assertEqual(<<"This is some CData">>, exml:unescape_cdata(CData)),
?assertEqual(ok, exml_stream:free_parser(Parser6)).
parser_errors_test() ->
?assertMatch({error, _}, exml:parse(<<"<notclosed_element>">>)),
%% it is the special case, because we are wrapping binary in the following way
%% Stream = <<"<stream>", XML/binary, "</stream>">>,
%% to make it a non-blocking call(?)
?assertMatch({error, {bad_parse, _}}, exml:parse(<<"<stream>">>)).
-define(BANANA_STREAM, <<"<stream:stream xmlns:stream='something'><foo attr='bar'>I am a banana!<baz/></foo></stream:stream>">>).
fun instead of begin / end because we bind CData in unhygenic macro
?assertMatch([#xmlstreamstart{name = <<"stream:stream">>,
attrs = [{<<"xmlns:stream">>, <<"something">>}]},
#xmlel{name = <<"foo">>,
attrs = [{<<"attr">>, <<"bar">>}],
children = [_CData, #xmlel{name = <<"baz">>}]},
#xmlstreamend{name = <<"stream:stream">>}],
Elements),
[_, #xmlel{children=[CData|_]}|_] = Elements,
?assertEqual(<<"I am a banana!">>, exml:unescape_cdata(CData)),
Elements
end)()).
conv_test() ->
AssertParses = fun(Input) ->
{ok, Parser0} = exml_stream:new_parser(),
{ok, Parser1, Elements} = exml_stream:parse(Parser0, Input),
ok = exml_stream:free_parser(Parser1),
?assertIsBanana(Elements)
end,
Elements = AssertParses(?BANANA_STREAM),
AssertParses(exml:to_binary(Elements)),
AssertParses(list_to_binary(exml:to_list(Elements))),
AssertParses(list_to_binary(exml:to_iolist(Elements))).
stream_reopen_test() ->
{ok, Parser0} = exml_stream:new_parser(),
{ok, Parser1, Elements1} = exml_stream:parse(Parser0, ?BANANA_STREAM),
?assertIsBanana(Elements1),
{ok, Parser2} = exml_stream:reset_parser(Parser1),
{ok, Parser3, Elements2} = exml_stream:parse(Parser2, ?BANANA_STREAM),
?assertIsBanana(Elements2),
ok = exml_stream:free_parser(Parser3).
infinit_framed_stream_test() ->
{ok, Parser0} = exml_stream:new_parser([{infinite_stream, true},
{autoreset, true}]),
Els = [#xmlel{name = <<"open">>,
attrs = [{<<"xmlns">>, <<"urn:ietf:params:xml:ns:xmpp-framing">>},
{<<"to">>, <<"example.com">>},
{<<"version">>, <<"1.0">>}]},
#xmlel{name = <<"foo">>},
#xmlel{name = <<"message">>,
attrs = [{<<"to">>, <<"">>}],
children = [#xmlel{name = <<"body">>,
children = [#xmlcdata{content = <<"Hi, How Are You?">>}]}]}
],
lists:foldl(fun(#xmlel{name = Name} = Elem, Parser) ->
Bin = exml:to_binary(Elem),
matches to one element list
#xmlel{ name = Name} = Element, %% checks if returned is xmlel of given name
Parser1
end, Parser0, Els).
parse_error_test() ->
{ok, Parser0} = exml_stream:new_parser(),
Input = <<"top-level non-tag">>,
?assertEqual({error, {"syntax error", Input}},
exml_stream:parse(Parser0, Input)),
ok = exml_stream:free_parser(Parser0).
assert_parses_escape_cdata(Text) ->
Escaped = exml:escape_cdata(Text),
Tag = #xmlel{name = <<"tag">>, children=[Escaped]},
Stream = [#xmlstreamstart{name = <<"s">>}, Tag, #xmlstreamend{name = <<"s">>}],
{ok, Parser0} = exml_stream:new_parser(),
{ok, Parser1, Elements} = exml_stream:parse(Parser0, exml:to_binary(Stream)),
?assertMatch([#xmlstreamstart{name = <<"s">>},
#xmlel{name = <<"tag">>, children=[_CData]},
#xmlstreamend{name = <<"s">>}],
Elements),
[_, #xmlel{children=[CData]}, _] = Elements,
?assertEqual(Text, exml:unescape_cdata(CData)),
ok = exml_stream:free_parser(Parser1).
reset_parser_error_test() ->
{ok, _P} = exml_stream:new_parser(),
BadParser = {parser, foo, bar, baz},
?assertEqual({error, {error, badarg}},
exml_stream:reset_parser(BadParser)).
cdata_is_ignored_when_first_child_of_stream_test() ->
{ok, P} = exml_stream:new_parser(),
{ok, _, Elements} =
exml_stream:parse(P, <<"<stream>hello</stream>">>),
?assertMatch([#xmlstreamstart{name = <<"stream">>},
#xmlstreamend{name = <<"stream">>}],
Elements).
multiple_cdata_are_joined_test() ->
{ok, P} = exml_stream:new_parser([{infinite_stream, false},
{autoreset, true}]),
{ok, P1, _} =
exml_stream:parse(P, <<"<s><a><![CDATA[hello]]>">>),
{ok, P2, E1} =
exml_stream:parse(P1, <<", world</a>">>),
{ok, _, _} =
exml_stream:parse(P2, <<"</s>">>),
#xmlel{children=[CData]} = hd(E1),
?assertEqual(<<"hello, world">>, exml:unescape_cdata(CData)).
cdata_test() ->
assert_parses_escape_cdata(<<"I am a banana!">>),
assert_parses_escape_cdata(<<"]:-> ]]> >">>),
assert_parses_escape_cdata(<<"><tag">>),
assert_parses_escape_cdata(<<"<!--">>),
assert_parses_escape_cdata(<<"<![CDATA[ test">>).
-define(ATTR_TEST_STREAM, <<"<stream:stream xmlns:stream='something'><quote attr=\"&<>"'
	
\"/></stream:stream>">>).
conv_attr_test() ->
AssertParses = fun(Input) ->
{ok, Parser0} = exml_stream:new_parser(),
{ok, Parser1, Elements} = exml_stream:parse(Parser0, Input),
ok = exml_stream:free_parser(Parser1),
?assertMatch([_, #xmlel{attrs = [{<<"attr">>, <<"&<>\"'\n\t\r">>}]} | _],
Elements),
Elements
end,
Elements = AssertParses(?ATTR_TEST_STREAM),
AssertParses(exml:to_binary(Elements)),
AssertParses(list_to_binary(exml:to_list(Elements))),
AssertParses(list_to_binary(exml:to_iolist(Elements))).
| null |
https://raw.githubusercontent.com/MyDataFlow/ttalk-server/07a60d5d74cd86aedd1f19c922d9d3abf2ebf28d/deps/exml/test/exml_stream_tests.erl
|
erlang
|
it is the special case, because we are wrapping binary in the following way
Stream = <<"<stream>", XML/binary, "</stream>">>,
to make it a non-blocking call(?)
checks if returned is xmlel of given name
|
-module(exml_stream_tests).
-include("exml_stream.hrl").
-include_lib("eunit/include/eunit.hrl").
-compile(export_all).
parser_error_bad_stream_opt_test() ->
?assertEqual({error, {error, {invalid_parser_opt,
{infinite_stream, infinity}}}},
exml_stream:new_parser([{infinite_stream, infinity}])).
parser_error_bad_autoreset_opt_test() ->
?assertEqual({error, {error, {invalid_parser_opt,
{autoreset, kielbasa}}}},
exml_stream:new_parser([{autoreset, kielbasa}])).
basic_parse_test() ->
{ok, Parser0} = exml_stream:new_parser(),
{ok, Parser1, Empty0} =
exml_stream:parse(Parser0, <<"<stream:stream xmlns:stream='' version='1.0'">>),
?assertEqual([], Empty0),
{ok, Parser2, StreamStart} =
exml_stream:parse(Parser1, <<" to='i.am.banana.com' xml:lang='en'><auth">>),
?assertEqual(
[#xmlstreamstart{name = <<"stream:stream">>,
attrs = [{<<"xmlns:stream">>, <<"">>},
{<<"version">>, <<"1.0">>},
{<<"to">>, <<"i.am.banana.com">>},
{<<"xml:lang">>, <<"en">>}]}],
StreamStart),
{ok, Parser3, Auth} = exml_stream:parse(Parser2, <<" mechanism='DIGEST-MD5'/>">>),
?assertEqual(
[#xmlel{name = <<"auth">>, attrs = [{<<"mechanism">>, <<"DIGEST-MD5">>}]}],
Auth),
{ok, Parser4, Empty1} = exml_stream:parse(Parser3, <<"<stream:features><bind xmlns='some_ns'">>),
?assertEqual([], Empty1),
{ok, Parser5, Empty2} = exml_stream:parse(Parser4, <<"/><session xmlns='some_other'/>This is ">>),
?assertEqual([], Empty2),
{ok, Parser6, Features} = exml_stream:parse(Parser5, <<"some CData</stream:features>">>),
?assertMatch(
[#xmlel{name = <<"stream:features">>,
children = [#xmlel{name = <<"bind">>,
attrs = [{<<"xmlns">>, <<"some_ns">>}]},
#xmlel{name = <<"session">>,
attrs = [{<<"xmlns">>, <<"some_other">>}]},
_CData]}],
Features),
[#xmlel{children=[_, _, CData]}] = Features,
?assertEqual(<<"This is some CData">>, exml:unescape_cdata(CData)),
?assertEqual(ok, exml_stream:free_parser(Parser6)).
parser_errors_test() ->
?assertMatch({error, _}, exml:parse(<<"<notclosed_element>">>)),
?assertMatch({error, {bad_parse, _}}, exml:parse(<<"<stream>">>)).
-define(BANANA_STREAM, <<"<stream:stream xmlns:stream='something'><foo attr='bar'>I am a banana!<baz/></foo></stream:stream>">>).
fun instead of begin / end because we bind CData in unhygenic macro
?assertMatch([#xmlstreamstart{name = <<"stream:stream">>,
attrs = [{<<"xmlns:stream">>, <<"something">>}]},
#xmlel{name = <<"foo">>,
attrs = [{<<"attr">>, <<"bar">>}],
children = [_CData, #xmlel{name = <<"baz">>}]},
#xmlstreamend{name = <<"stream:stream">>}],
Elements),
[_, #xmlel{children=[CData|_]}|_] = Elements,
?assertEqual(<<"I am a banana!">>, exml:unescape_cdata(CData)),
Elements
end)()).
conv_test() ->
AssertParses = fun(Input) ->
{ok, Parser0} = exml_stream:new_parser(),
{ok, Parser1, Elements} = exml_stream:parse(Parser0, Input),
ok = exml_stream:free_parser(Parser1),
?assertIsBanana(Elements)
end,
Elements = AssertParses(?BANANA_STREAM),
AssertParses(exml:to_binary(Elements)),
AssertParses(list_to_binary(exml:to_list(Elements))),
AssertParses(list_to_binary(exml:to_iolist(Elements))).
stream_reopen_test() ->
{ok, Parser0} = exml_stream:new_parser(),
{ok, Parser1, Elements1} = exml_stream:parse(Parser0, ?BANANA_STREAM),
?assertIsBanana(Elements1),
{ok, Parser2} = exml_stream:reset_parser(Parser1),
{ok, Parser3, Elements2} = exml_stream:parse(Parser2, ?BANANA_STREAM),
?assertIsBanana(Elements2),
ok = exml_stream:free_parser(Parser3).
infinit_framed_stream_test() ->
{ok, Parser0} = exml_stream:new_parser([{infinite_stream, true},
{autoreset, true}]),
Els = [#xmlel{name = <<"open">>,
attrs = [{<<"xmlns">>, <<"urn:ietf:params:xml:ns:xmpp-framing">>},
{<<"to">>, <<"example.com">>},
{<<"version">>, <<"1.0">>}]},
#xmlel{name = <<"foo">>},
#xmlel{name = <<"message">>,
attrs = [{<<"to">>, <<"">>}],
children = [#xmlel{name = <<"body">>,
children = [#xmlcdata{content = <<"Hi, How Are You?">>}]}]}
],
lists:foldl(fun(#xmlel{name = Name} = Elem, Parser) ->
Bin = exml:to_binary(Elem),
matches to one element list
Parser1
end, Parser0, Els).
parse_error_test() ->
{ok, Parser0} = exml_stream:new_parser(),
Input = <<"top-level non-tag">>,
?assertEqual({error, {"syntax error", Input}},
exml_stream:parse(Parser0, Input)),
ok = exml_stream:free_parser(Parser0).
assert_parses_escape_cdata(Text) ->
Escaped = exml:escape_cdata(Text),
Tag = #xmlel{name = <<"tag">>, children=[Escaped]},
Stream = [#xmlstreamstart{name = <<"s">>}, Tag, #xmlstreamend{name = <<"s">>}],
{ok, Parser0} = exml_stream:new_parser(),
{ok, Parser1, Elements} = exml_stream:parse(Parser0, exml:to_binary(Stream)),
?assertMatch([#xmlstreamstart{name = <<"s">>},
#xmlel{name = <<"tag">>, children=[_CData]},
#xmlstreamend{name = <<"s">>}],
Elements),
[_, #xmlel{children=[CData]}, _] = Elements,
?assertEqual(Text, exml:unescape_cdata(CData)),
ok = exml_stream:free_parser(Parser1).
reset_parser_error_test() ->
{ok, _P} = exml_stream:new_parser(),
BadParser = {parser, foo, bar, baz},
?assertEqual({error, {error, badarg}},
exml_stream:reset_parser(BadParser)).
cdata_is_ignored_when_first_child_of_stream_test() ->
{ok, P} = exml_stream:new_parser(),
{ok, _, Elements} =
exml_stream:parse(P, <<"<stream>hello</stream>">>),
?assertMatch([#xmlstreamstart{name = <<"stream">>},
#xmlstreamend{name = <<"stream">>}],
Elements).
multiple_cdata_are_joined_test() ->
{ok, P} = exml_stream:new_parser([{infinite_stream, false},
{autoreset, true}]),
{ok, P1, _} =
exml_stream:parse(P, <<"<s><a><![CDATA[hello]]>">>),
{ok, P2, E1} =
exml_stream:parse(P1, <<", world</a>">>),
{ok, _, _} =
exml_stream:parse(P2, <<"</s>">>),
#xmlel{children=[CData]} = hd(E1),
?assertEqual(<<"hello, world">>, exml:unescape_cdata(CData)).
cdata_test() ->
assert_parses_escape_cdata(<<"I am a banana!">>),
assert_parses_escape_cdata(<<"]:-> ]]> >">>),
assert_parses_escape_cdata(<<"><tag">>),
assert_parses_escape_cdata(<<"<!--">>),
assert_parses_escape_cdata(<<"<![CDATA[ test">>).
-define(ATTR_TEST_STREAM, <<"<stream:stream xmlns:stream='something'><quote attr=\"&<>"'
	
\"/></stream:stream>">>).
conv_attr_test() ->
AssertParses = fun(Input) ->
{ok, Parser0} = exml_stream:new_parser(),
{ok, Parser1, Elements} = exml_stream:parse(Parser0, Input),
ok = exml_stream:free_parser(Parser1),
?assertMatch([_, #xmlel{attrs = [{<<"attr">>, <<"&<>\"'\n\t\r">>}]} | _],
Elements),
Elements
end,
Elements = AssertParses(?ATTR_TEST_STREAM),
AssertParses(exml:to_binary(Elements)),
AssertParses(list_to_binary(exml:to_list(Elements))),
AssertParses(list_to_binary(exml:to_iolist(Elements))).
|
fa7faef60d849f7fdb1ae210e8c5a218a1f57d2033ec009f6aa6a32d90218b4e
|
swarmpit/swarmpit
|
info.cljs
|
(ns swarmpit.component.secret.info
(:require [material.icon :as icon]
[material.components :as comp]
[material.component.form :as form]
[swarmpit.component.state :as state]
[swarmpit.component.mixin :as mixin]
[swarmpit.component.dialog :as dialog]
[swarmpit.component.message :as message]
[swarmpit.component.progress :as progress]
[swarmpit.component.toolbar :as toolbar]
[swarmpit.component.common :as common]
[swarmpit.component.service.list :as services]
[swarmpit.url :refer [dispatch!]]
[swarmpit.ajax :as ajax]
[swarmpit.routes :as routes]
[sablono.core :refer-macros [html]]
[clojure.contrib.inflect :as inflect]
[rum.core :as rum]))
(enable-console-print!)
(defn- secret-services-handler
[secret-id]
(ajax/get
(routes/path-for-backend :secret-services {:id secret-id})
{:on-success (fn [{:keys [response]}]
(state/update-value [:services] response state/form-value-cursor))}))
(defn- secret-handler
[secret-id]
(ajax/get
(routes/path-for-backend :secret {:id secret-id})
{:state [:loading?]
:on-success (fn [{:keys [response]}]
(state/update-value [:secret] response state/form-value-cursor))}))
(defn- delete-secret-handler
[secret-id]
(ajax/delete
(routes/path-for-backend :secret {:id secret-id})
{:on-success (fn [_]
(dispatch!
(routes/path-for-frontend :secret-list))
(message/info
(str "Secret " secret-id " has been removed.")))
:on-error (fn [{:keys [response]}]
(message/error
(str "Secret removing failed. " (:error response))))}))
(rum/defc form-general < rum/static [secret services]
(comp/card
{:className "Swarmpit-form-card"}
(form/item-main "ID" (:id secret) false)
(form/item-main "Created" (form/item-date (:createdAt secret)))
(form/item-main "Last Update" (form/item-date (:updatedAt secret)))))
(def form-actions
[{:onClick #(state/update-value [:open] true dialog/dialog-cursor)
:icon (comp/svg icon/trash-path)
:color "default"
:variant "outlined"
:name "Delete"}])
(defn- init-form-state
[]
(state/set-value {:loading? true} state/form-state-cursor))
(def mixin-init-form
(mixin/init-form
(fn [{{:keys [id]} :params}]
(init-form-state)
(secret-handler id)
(secret-services-handler id))))
(rum/defc form-info < rum/static [{:keys [secret services]}]
(comp/mui
(html
[:div.Swarmpit-form
(dialog/confirm-dialog
#(delete-secret-handler (:id secret))
"Delete secret?"
"Delete")
(comp/container
{:maxWidth "md"
:className "Swarmpit-container"}
(comp/grid
{:container true
:spacing 2}
(comp/grid
{:item true
:xs 12}
(toolbar/toolbar "Secret" (:secretName secret) form-actions))
(comp/grid
{:item true
:xs 12}
(form-general secret services))
(comp/grid
{:item true
:xs 12}
(services/linked services))))])))
(rum/defc form < rum/reactive
mixin-init-form
mixin/subscribe-form [_]
(let [state (state/react state/form-state-cursor)
item (state/react state/form-value-cursor)]
(progress/form
(:loading? state)
(form-info item))))
| null |
https://raw.githubusercontent.com/swarmpit/swarmpit/38ffbe08e717d8620bf433c99f2e85a9e5984c32/src/cljs/swarmpit/component/secret/info.cljs
|
clojure
|
(ns swarmpit.component.secret.info
(:require [material.icon :as icon]
[material.components :as comp]
[material.component.form :as form]
[swarmpit.component.state :as state]
[swarmpit.component.mixin :as mixin]
[swarmpit.component.dialog :as dialog]
[swarmpit.component.message :as message]
[swarmpit.component.progress :as progress]
[swarmpit.component.toolbar :as toolbar]
[swarmpit.component.common :as common]
[swarmpit.component.service.list :as services]
[swarmpit.url :refer [dispatch!]]
[swarmpit.ajax :as ajax]
[swarmpit.routes :as routes]
[sablono.core :refer-macros [html]]
[clojure.contrib.inflect :as inflect]
[rum.core :as rum]))
(enable-console-print!)
(defn- secret-services-handler
[secret-id]
(ajax/get
(routes/path-for-backend :secret-services {:id secret-id})
{:on-success (fn [{:keys [response]}]
(state/update-value [:services] response state/form-value-cursor))}))
(defn- secret-handler
[secret-id]
(ajax/get
(routes/path-for-backend :secret {:id secret-id})
{:state [:loading?]
:on-success (fn [{:keys [response]}]
(state/update-value [:secret] response state/form-value-cursor))}))
(defn- delete-secret-handler
[secret-id]
(ajax/delete
(routes/path-for-backend :secret {:id secret-id})
{:on-success (fn [_]
(dispatch!
(routes/path-for-frontend :secret-list))
(message/info
(str "Secret " secret-id " has been removed.")))
:on-error (fn [{:keys [response]}]
(message/error
(str "Secret removing failed. " (:error response))))}))
(rum/defc form-general < rum/static [secret services]
(comp/card
{:className "Swarmpit-form-card"}
(form/item-main "ID" (:id secret) false)
(form/item-main "Created" (form/item-date (:createdAt secret)))
(form/item-main "Last Update" (form/item-date (:updatedAt secret)))))
(def form-actions
[{:onClick #(state/update-value [:open] true dialog/dialog-cursor)
:icon (comp/svg icon/trash-path)
:color "default"
:variant "outlined"
:name "Delete"}])
(defn- init-form-state
[]
(state/set-value {:loading? true} state/form-state-cursor))
(def mixin-init-form
(mixin/init-form
(fn [{{:keys [id]} :params}]
(init-form-state)
(secret-handler id)
(secret-services-handler id))))
(rum/defc form-info < rum/static [{:keys [secret services]}]
(comp/mui
(html
[:div.Swarmpit-form
(dialog/confirm-dialog
#(delete-secret-handler (:id secret))
"Delete secret?"
"Delete")
(comp/container
{:maxWidth "md"
:className "Swarmpit-container"}
(comp/grid
{:container true
:spacing 2}
(comp/grid
{:item true
:xs 12}
(toolbar/toolbar "Secret" (:secretName secret) form-actions))
(comp/grid
{:item true
:xs 12}
(form-general secret services))
(comp/grid
{:item true
:xs 12}
(services/linked services))))])))
(rum/defc form < rum/reactive
mixin-init-form
mixin/subscribe-form [_]
(let [state (state/react state/form-state-cursor)
item (state/react state/form-value-cursor)]
(progress/form
(:loading? state)
(form-info item))))
|
|
85b7ad6703b56e150655cb9c3b89411b9625d2131f7a93154095ceb7afa84e09
|
clojure-interop/aws-api
|
AWSResourceGroupsClientBuilder.clj
|
(ns com.amazonaws.services.resourcegroups.AWSResourceGroupsClientBuilder
"Fluent builder for AWSResourceGroups. Use of the builder is preferred
over using constructors of the client class."
(:refer-clojure :only [require comment defn ->])
(:import [com.amazonaws.services.resourcegroups AWSResourceGroupsClientBuilder]))
(defn *standard
"returns: Create new instance of builder with all defaults set. - `com.amazonaws.services.resourcegroups.AWSResourceGroupsClientBuilder`"
(^com.amazonaws.services.resourcegroups.AWSResourceGroupsClientBuilder []
(AWSResourceGroupsClientBuilder/standard )))
(defn *default-client
"returns: Default client using the DefaultAWSCredentialsProviderChain and
DefaultAwsRegionProviderChain chain - `com.amazonaws.services.resourcegroups.AWSResourceGroups`"
(^com.amazonaws.services.resourcegroups.AWSResourceGroups []
(AWSResourceGroupsClientBuilder/defaultClient )))
| null |
https://raw.githubusercontent.com/clojure-interop/aws-api/59249b43d3bfaff0a79f5f4f8b7bc22518a3bf14/com.amazonaws.services.resourcegroups/src/com/amazonaws/services/resourcegroups/AWSResourceGroupsClientBuilder.clj
|
clojure
|
(ns com.amazonaws.services.resourcegroups.AWSResourceGroupsClientBuilder
"Fluent builder for AWSResourceGroups. Use of the builder is preferred
over using constructors of the client class."
(:refer-clojure :only [require comment defn ->])
(:import [com.amazonaws.services.resourcegroups AWSResourceGroupsClientBuilder]))
(defn *standard
"returns: Create new instance of builder with all defaults set. - `com.amazonaws.services.resourcegroups.AWSResourceGroupsClientBuilder`"
(^com.amazonaws.services.resourcegroups.AWSResourceGroupsClientBuilder []
(AWSResourceGroupsClientBuilder/standard )))
(defn *default-client
"returns: Default client using the DefaultAWSCredentialsProviderChain and
DefaultAwsRegionProviderChain chain - `com.amazonaws.services.resourcegroups.AWSResourceGroups`"
(^com.amazonaws.services.resourcegroups.AWSResourceGroups []
(AWSResourceGroupsClientBuilder/defaultClient )))
|
|
606aee932de2be55d74f3ab3fa5aec7583c635a4997273148ab27d6004c2ccee
|
vseloved/prj-algo3
|
ford-fulkerson.lisp
|
(load "../utils/graph.lisp")
(load "../utils/bfs.lisp")
(defparameter *graph*
(adj-list->adj-mat
(make-graph '(0 1 16)
'(0 2 13)
'(1 3 12)
'(1 2 10)
'(2 1 4)
'(2 4 14)
'(3 5 20)
'(3 2 9)
'(4 3 7)
'(4 5 4))))
(defun ford-fulkerson (g source sink)
(let* ((size (sqrt (array-total-size g)))
(paths (make-array size :initial-element nil))
(r (make-array (array-dimensions g))))
;;; Fill in redsiduals graph.
(loop :for i :from 0 :below size :do
(loop :for j :from 0 :below size :do
(setf (aref r i j) (aref g i j))))
;;; Find maximum flow.
(loop :with max-flow = 0 :while (bfs-on-mat r source sink paths) :do
(let ((tmp-flow most-positive-fixnum))
;;; Find possible flow.
(loop :with current = sink :while (not (eql current source)) :do
(let ((next (aref paths current)))
(setf tmp-flow (min tmp-flow (aref r next current))
current next)))
;;; Decrease residual capacity.
(loop :with current = sink :while (not (eql current source)) :do
(let ((next (aref paths current)))
(decf (aref r next current) tmp-flow)
(incf (aref r current next) tmp-flow)
(setf current next)))
(incf max-flow tmp-flow))
:finally (return max-flow))))
(defun test ()
(assert 23 (ford-fulkerson *graph* 0 5)))
| null |
https://raw.githubusercontent.com/vseloved/prj-algo3/ed485ca730e42cd1bba757fd3f409b51ddb43c03/tasks/h8is2w8/18-graphs/ford-fulkerson.lisp
|
lisp
|
Fill in redsiduals graph.
Find maximum flow.
Find possible flow.
Decrease residual capacity.
|
(load "../utils/graph.lisp")
(load "../utils/bfs.lisp")
(defparameter *graph*
(adj-list->adj-mat
(make-graph '(0 1 16)
'(0 2 13)
'(1 3 12)
'(1 2 10)
'(2 1 4)
'(2 4 14)
'(3 5 20)
'(3 2 9)
'(4 3 7)
'(4 5 4))))
(defun ford-fulkerson (g source sink)
(let* ((size (sqrt (array-total-size g)))
(paths (make-array size :initial-element nil))
(r (make-array (array-dimensions g))))
(loop :for i :from 0 :below size :do
(loop :for j :from 0 :below size :do
(setf (aref r i j) (aref g i j))))
(loop :with max-flow = 0 :while (bfs-on-mat r source sink paths) :do
(let ((tmp-flow most-positive-fixnum))
(loop :with current = sink :while (not (eql current source)) :do
(let ((next (aref paths current)))
(setf tmp-flow (min tmp-flow (aref r next current))
current next)))
(loop :with current = sink :while (not (eql current source)) :do
(let ((next (aref paths current)))
(decf (aref r next current) tmp-flow)
(incf (aref r current next) tmp-flow)
(setf current next)))
(incf max-flow tmp-flow))
:finally (return max-flow))))
(defun test ()
(assert 23 (ford-fulkerson *graph* 0 5)))
|
06fcc55465acbfa683b5e191c66720d450ab2f76a2473a0225ae87e0287d8e42
|
patrikja/AFPcourse
|
Shallow.hs
|
{-|
A simple embedded language for input/output. Shallow embedding.
-}
module Program.Shallow
( Input, Output
, Program
, putC, getC
, run
) where
import Control.Applicative (Applicative(..))
import Control.Monad (liftM, ap)
type Input = String
type Output = String
-- | Shallow embedding: programs are represented by their semantics
-- In this case a program is a function from the input to the
-- result, the remaining input and the output.
type IOSem a = Input -> (a, Input, Output)
newtype Program a = P { unP :: IOSem a }
-- | Print a character.
putC :: Char -> Program ()
putC c = P $ \i -> ((), i, [c])
-- | Read a character (if there is one).
getC :: Program (Maybe Char)
getC = P $ \i -> case i of
[] -> (Nothing, [], [])
c : i' -> (Just c, i', [])
Program is a monad , which provides us with a nice interface for
-- sequencing programs.
instance Monad Program where
return = returnP
(>>=) = bindP
returnP :: a -> Program a
returnP x = P $ \i -> (x, i, [])
bindP :: Program a -> (a -> Program b) -> Program b
bindP p k = P $ \i ->
let (x, i1, o1) = unP p i
(y, i2, o2) = unP (k x) i1
in (y, i2, o1 ++ o2)
-- | Running a program is simply returning its semantics.
run :: Program a -> IOSem a
run = unP
--------
-- Preparing for the Functor-Applicative-Monad proposal:
-- -Applicative-Monad_Proposal
-- | The following instances are valid for _all_ monads:
instance Functor Program where
fmap = liftM
instance Applicative Program where
pure = return
(<*>) = ap
{-
-- Exercise: write direct implementations:
apP :: Program (a->b) -> Program a -> Program b
fmapP :: (a->b) -> Program a -> Program b
-}
| null |
https://raw.githubusercontent.com/patrikja/AFPcourse/1a079ae80ba2dbb36f3f79f0fc96a502c0f670b6/L3/src/Program/Shallow.hs
|
haskell
|
|
A simple embedded language for input/output. Shallow embedding.
| Shallow embedding: programs are represented by their semantics
In this case a program is a function from the input to the
result, the remaining input and the output.
| Print a character.
| Read a character (if there is one).
sequencing programs.
| Running a program is simply returning its semantics.
------
Preparing for the Functor-Applicative-Monad proposal:
-Applicative-Monad_Proposal
| The following instances are valid for _all_ monads:
-- Exercise: write direct implementations:
apP :: Program (a->b) -> Program a -> Program b
fmapP :: (a->b) -> Program a -> Program b
|
module Program.Shallow
( Input, Output
, Program
, putC, getC
, run
) where
import Control.Applicative (Applicative(..))
import Control.Monad (liftM, ap)
type Input = String
type Output = String
type IOSem a = Input -> (a, Input, Output)
newtype Program a = P { unP :: IOSem a }
putC :: Char -> Program ()
putC c = P $ \i -> ((), i, [c])
getC :: Program (Maybe Char)
getC = P $ \i -> case i of
[] -> (Nothing, [], [])
c : i' -> (Just c, i', [])
Program is a monad , which provides us with a nice interface for
instance Monad Program where
return = returnP
(>>=) = bindP
returnP :: a -> Program a
returnP x = P $ \i -> (x, i, [])
bindP :: Program a -> (a -> Program b) -> Program b
bindP p k = P $ \i ->
let (x, i1, o1) = unP p i
(y, i2, o2) = unP (k x) i1
in (y, i2, o1 ++ o2)
run :: Program a -> IOSem a
run = unP
instance Functor Program where
fmap = liftM
instance Applicative Program where
pure = return
(<*>) = ap
|
a28fe7d0bff9935e1f5e2654e03d7bc487633dcc6734091d2476839e5d4562bb
|
ktakashi/sagittarius-scheme
|
label.scm
|
-*- mode : scheme ; coding : utf-8 ; -*-
;;;
;;; win32/gui/label.scm - Win32 Label component
;;;
Copyright ( c ) 2021 < >
;;;
;;; Redistribution and use in source and binary forms, with or without
;;; modification, are permitted provided that the following conditions
;;; are met:
;;;
;;; 1. Redistributions of source code must retain the above copyright
;;; notice, this list of conditions and the following disclaimer.
;;;
;;; 2. Redistributions in binary form must reproduce the above copyright
;;; notice, this list of conditions and the following disclaimer in the
;;; documentation and/or other materials provided with the distribution.
;;;
;;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
" AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT
;;; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
;;; A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
;;; 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.
;;;
#!nounbound
(library (win32 gui label)
(export make-win32-label <win32-label>
win32-label?
win32-label-set-text!
)
(import (rnrs)
(sagittarius)
(sagittarius ffi)
(win32 kernel)
(win32 user)
(win32 defs)
(win32 common-control)
(win32 gui api)
(clos user)
(sagittarius control)
(sagittarius object))
(define *win32-default-label-class-name* "sagittarius-default-label-class")
(define-class <win32-label> (<win32-component>) ())
(define (win32-label? o) (is-a? o <win32-label>))
(define (make-win32-label . args) (apply make <win32-label> args))
(define-method initialize ((o <win32-label>) initargs)
(call-next-method)
(unless (slot-bound? o 'class-name)
(set! (~ o 'class-name) *win32-default-label-class-name*))
o)
(define (win32-label-set-text! l text)
(set! (~ l 'name) text)
(set-window-text (~ l 'hwnd) text))
(inherit-window-class WC_STATIC *win32-default-label-class-name* WM_NCCREATE)
)
| null |
https://raw.githubusercontent.com/ktakashi/sagittarius-scheme/6b313540c8d539d86a7de90437700ce054180a52/ext/ffi/win32/gui/label.scm
|
scheme
|
coding : utf-8 ; -*-
win32/gui/label.scm - Win32 Label component
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
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,
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
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 ) 2021 < >
" AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT
SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED
LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT ( INCLUDING
#!nounbound
(library (win32 gui label)
(export make-win32-label <win32-label>
win32-label?
win32-label-set-text!
)
(import (rnrs)
(sagittarius)
(sagittarius ffi)
(win32 kernel)
(win32 user)
(win32 defs)
(win32 common-control)
(win32 gui api)
(clos user)
(sagittarius control)
(sagittarius object))
(define *win32-default-label-class-name* "sagittarius-default-label-class")
(define-class <win32-label> (<win32-component>) ())
(define (win32-label? o) (is-a? o <win32-label>))
(define (make-win32-label . args) (apply make <win32-label> args))
(define-method initialize ((o <win32-label>) initargs)
(call-next-method)
(unless (slot-bound? o 'class-name)
(set! (~ o 'class-name) *win32-default-label-class-name*))
o)
(define (win32-label-set-text! l text)
(set! (~ l 'name) text)
(set-window-text (~ l 'hwnd) text))
(inherit-window-class WC_STATIC *win32-default-label-class-name* WM_NCCREATE)
)
|
55a9a91affaf761bdb42b6f538958eb33058805e33da2994f7ae204e689e15d0
|
jrm-code-project/LISP-Machine
|
starter-list.lisp
|
-*- Mode : Lisp ; Package : User ; : CPTFONT ; ; : CL -*-
;;;
Mailing list file MAIL ; LIST.LISP
;;;
Mailer internal addresses .
("Postman" (:file . "MAIL; POSTMAN-MAIL.TEXT"))
("Postmaster" "Postman")
| null |
https://raw.githubusercontent.com/jrm-code-project/LISP-Machine/0a448d27f40761fafabe5775ffc550637be537b2/lambda/network/mailer/starter-list.lisp
|
lisp
|
Package : User ; : CPTFONT ; ; : CL -*-
LIST.LISP
|
Mailer internal addresses .
("Postman" (:file . "MAIL; POSTMAN-MAIL.TEXT"))
("Postmaster" "Postman")
|
ede9930884f2d4c3355fc381a56f36d54056c80daac8be60d5e8283caa3fc181
|
cmeiklejohn/ensemble
|
ensemble.erl
|
%% -------------------------------------------------------------------
%%
Copyright ( c ) 2016 . All Rights Reserved .
%%
This file is provided to you under the Apache License ,
%% Version 2.0 (the "License"); you may not use this file
except in compliance with the License . You may obtain
%% a copy of the License at
%%
%% -2.0
%%
%% Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
" AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY
%% KIND, either express or implied. See the License for the
%% specific language governing permissions and limitations
%% under the License.
%%
%% -------------------------------------------------------------------
-module(ensemble).
-author("Christopher S. Meiklejohn <>").
-include("ensemble.hrl").
| null |
https://raw.githubusercontent.com/cmeiklejohn/ensemble/9471b07c0ce18d7a58fef683fceca99992579ff3/src/ensemble.erl
|
erlang
|
-------------------------------------------------------------------
Version 2.0 (the "License"); you may not use this file
a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing,
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-------------------------------------------------------------------
|
Copyright ( c ) 2016 . All Rights Reserved .
This file is provided to you under the Apache License ,
except in compliance with the License . You may obtain
software distributed under the License is distributed on an
" AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY
-module(ensemble).
-author("Christopher S. Meiklejohn <>").
-include("ensemble.hrl").
|
d54071778dea7b1a1be43b123a387c6ec7eaf494bb2e9137db32716a2f7052b8
|
eglaysher/rldev
|
variables.ml
|
Rlc : variable handling
Copyright ( C ) 2006 Haeleth
This program is free software ; you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free Software
Foundation ; either version 2 of the License , or ( at your option ) any later
version .
This program is distributed in the hope that it will be useful , but WITHOUT
ANY WARRANTY ; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE . See the GNU General Public License for more
details .
You should have received a copy of the GNU General Public License along with
this program ; if not , write to the Free Software Foundation , Inc. , 59 Temple
Place - Suite 330 , Boston , MA 02111 - 1307 , USA .
Rlc: variable handling
Copyright (C) 2006 Haeleth
This program is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free Software
Foundation; either version 2 of the License, or (at your option) any later
version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
details.
You should have received a copy of the GNU General Public License along with
this program; if not, write to the Free Software Foundation, Inc., 59 Temple
Place - Suite 330, Boston, MA 02111-1307, USA.
*)
open Printf
open ExtList
open KeTypes
open KeAst
(* Code-generation auxiliaries *)
let setrng ?init fn s t ?(first = 0) len =
Meta.call fn (`Deref (nowhere, s, t, Meta.int first)
:: `Deref (nowhere, s, t, Meta.int (len - 1))
:: (match init with None -> [] | Some e -> [e]))
(* Main functions *)
let decldir_of_ident =
let decldir_table =
[Text.ident "zero", `Zero;
Text.ident "block", `Block;
Text.ident "ext", `Ext;
Text.ident "labelled", `Label]
in
fun loc (str_id, txt_id) ->
try
List.assoc txt_id decldir_table
with Not_found ->
ksprintf (error loc) "unknown declaration directive `%s'" str_id
let get_elements (loc, str_id, _, array_length, init_value, _) =
match array_length with
| `None -> 1
| `Auto ->
(match init_value with
| `Array [] -> ksprintf (error loc) "`%s[]' must either be given an explicit length, or the initial value array must contain at least one element" str_id
| `Array l -> List.length l
| _ -> ksprintf (error loc) "array `%s[]' must be given a length, either explicitly or by providing an initial value array" str_id)
| `Some expr ->
(try
Int32.to_int (Global.expr__normalise_and_get_int expr ~abort_on_fail:false)
with Exit ->
ksprintf (error (loc_of_expr expr)) "array length for `%s[]' must evaluate to a constant integer" str_id)
let get_address loc vartype str_id block_size =
function
| None
-> let space, f, max = if vartype = `Str then Memory.temp_str_spec () else Memory.temp_int_spec () in
space, Memory.find_block loc space f block_size ~max
| Some (sp, addr)
-> try
Int32.to_int (Global.expr__normalise_and_get_int sp ~abort_on_fail:false),
Int32.to_int (Global.expr__normalise_and_get_int addr ~abort_on_fail:false)
with Exit ->
ksprintf (error (loc_of_expr sp)) "fixed address for %s must evaluate to a pair of constant integers" str_id
let get_real_address vartype space address address_is_access =
let typed_space, eltmod =
match vartype with
| `Int 1 -> space + 26, 32
| `Int 2 -> space + 52, 16
| `Int 4 -> space + 78, 8
| `Int 8 -> space + 104, 4
| _ -> space, 1
in
let access_address, alloc_address =
if address_is_access
then address, address / eltmod
else address * eltmod, address
in
typed_space, access_address, alloc_address
let allocate (loc, vartype, directives, variables) =
assert (variables != []);
let is_block = List.mem `Block directives
and is_str = vartype = `Str
in
Set ` elements ' to the number of elements required for each variable - 1 for
scalars , or the length for arrays .
scalars, or the length for arrays. *)
let elements =
List.map get_elements variables
in
(* Allocate and retrieve appropriate addresses to use. *)
let spaces_addresses_counts =
let get_block_size elt_count =
match vartype with
| `Str -> elt_count
| `Int elt_bits -> (elt_count * elt_bits - 1) / 32 + 1
in
if is_block then
(* Allocate one block and place individual variables within it. *)
let elt_total = List.fold_left (+) 0 elements in
let block_size = get_block_size elt_total
and fixed_address =
let all_addresses = List.map (fun (loc, _, _, _, _, rv) -> loc, rv) variables in
let (_, rv), tail = match all_addresses with hd :: tl -> hd, tl | _ -> assert false in
Direct address specifications are invalid other than for the first variable .
List.iter (function _, None -> () | loc, Some _ -> error loc "when the `block' directive is specified, only the first variable in a declaration may have an address specifier") tail;
rv
in
let space, base_address =
get_address loc vartype "block allocation" block_size fixed_address
in
Memory.allocate_block loc space base_address block_size;
let address =
match vartype with
| `Int 1 -> base_address * 32
| `Int 2 -> base_address * 16
| `Int 4 -> base_address * 8
| `Int 8 -> base_address * 4
| _ -> base_address
in
let total, retval =
List.fold_left
(fun (elt_accum, retval) elt_count ->
let blocks_required =
get_block_size elt_count
and typed_space, access_address, alloc_address =
get_real_address vartype space (address + elt_accum) true
in
let elt = space, typed_space, alloc_address, access_address, elt_count, blocks_required in
elt_accum + elt_count, elt :: retval)
(0, [])
elements
in
assert (total == elt_total);
List.rev retval
else
(* Allocate variables wherever they'll fit, out of order or split up if necessary. *)
TODO : For now , this is done naively - each variable uses an entire block .
Ideally we would combine multiple sub - int variables in one block where possible .
Ideally we would combine multiple sub-int variables in one block where possible. *)
List.map2
(fun (loc, str_id, _,_,_, fixed_addr) elt_count ->
let blocks_required =
get_block_size elt_count
in
let space, address =
get_address loc vartype str_id blocks_required fixed_addr
in
let typed_space, access_address, alloc_address =
get_real_address vartype space address (fixed_addr <> None)
in
Memory.allocate_block loc space alloc_address blocks_required;
space, typed_space, alloc_address, access_address, elt_count, blocks_required)
variables
elements
in
(* Define the symbols. *)
let scoped = not (List.mem `Ext directives) in
List.iter2
(fun (loc, _, txt_id, array_length, _, _)
(space, typed_space, alloc_address, access_address, elt_count, blocks_required) ->
Memory.define txt_id ~scoped
(`StaticVar
(typed_space,
Int32.of_int access_address,
(if array_length <> `None then Some elt_count else None),
Memory.varidx space,
alloc_address,
blocks_required)))
variables
spaces_addresses_counts;
(* Write to flag.ini if required *)
if !App.flag_labels && (List.mem `Label directives || Memory.check_def "__AllLabelled__" ()) then (
let fn = Filename.concat (Filename.dirname !App.gameexe) "flag.ini" in
let oc = open_out_gen [Open_wronly; Open_creat; Open_append; Open_text] 0o666 fn in
try
List.iter2
(fun (_, str_id, _, array_length, _, _) (_, typed_space, _, access_address, elt_count, _) ->
fprintf oc "%s[%d]:0:%s\n"
(variable_name typed_space ~prefix:false)
access_address
(if array_length = `None then str_id else sprintf "%s[%d]" str_id elt_count))
variables
spaces_addresses_counts;
close_out oc
with e ->
close_out oc;
raise e
);
Initialise the variables
let is_zero = List.mem `Zero directives in
if is_block && is_zero && List.length variables > 1 then begin
Handle block initialisations specially when the ` zero ' directive was passed :
in this case we can sometimes optimise the initialisation fairly easily .
in this case we can sometimes optimise the initialisation fairly easily. *)
let _, str_id, txt_id, _, _, _ = List.hd variables in
let spc, addr =
match Memory.get_as_expression txt_id ~allow_arrays:true with
| `SVar (_, s, `Int (_, idx)) -> s, idx
| `IVar (_, s, `Int (_, idx)) -> s, idx
| _ -> assert false
in
Check whether any non - zero initial values have been provided .
let elt_total, any_have_values =
let expr_non_zero e =
try
!Global.expr__normalise_and_get_const e ~abort_on_fail:false <> `Integer 0l
with Exit ->
true
in
List.fold_left2
(fun (ec, acc) (_, _, _, _, ival, _) ec' -> ec + ec', acc ||
match ival with
| `None -> false
| `Scalar e -> expr_non_zero e
| `Array es -> List.exists expr_non_zero es)
(0, false)
variables
elements
in
If they have n't , we can just zero the entire block .
if not any_have_values then
if is_str then
Meta.call "strclear"
[`SVar (nowhere, spc, `Int (nowhere, addr));
`SVar (nowhere, spc, `Int (nowhere, Int32.add addr (Int32.of_int (elt_total - 1))))]
else
Meta.call "setrng"
[`IVar (nowhere, spc, `Int (nowhere, addr));
`IVar (nowhere, spc, `Int (nowhere, Int32.add addr (Int32.of_int (elt_total - 1))))]
else
(* If they have, we must take them into account. *)
let init_values =
List.fold_right2
(fun (loc, str_id, _, _, ival, _) elt_count vallist ->
match ival with
| `None -> List.rev_append (List.make elt_count Meta.zero) vallist
| `Scalar e -> List.rev_append (List.make elt_count e) vallist
| `Array es
-> let len = List.length es in
if len > elt_count then ksprintf (error loc) "too many values supplied to initialise %s[]" str_id;
es @ if len < elt_count
then List.rev_append (List.make (elt_count - len) Meta.zero) vallist
else vallist)
variables elements
[]
in
(* String assignments become an optional clearing followed by a series of assignments. *)
if is_str then
let any_empty = List.exists (function `Int _ -> true | _ -> false) init_values in
if any_empty then
Meta.call "strclear"
[`SVar (nowhere, spc, `Int (nowhere, addr));
`SVar (nowhere, spc, `Int (nowhere, Int32.add addr (Int32.of_int (elt_total - 1))))];
List.iter
(function `Int _ -> () | expr -> Meta.assign (`VarOrFn (nowhere, str_id, txt_id)) `Set expr)
init_values
else
For ints , we just call . ( This may be a Bad Thing if init_values is very long . )
Meta.call "setarray" (`IVar (nowhere, spc, `Int (nowhere, addr)) :: init_values)
end
else
Not a block allocation , or no ` zero ' directive : initalise variables separately .
List.iter2
(fun (loc, str_id, txt_id, array_length, init_value, _) elt_count ->
let is_array = array_length <> `None in
match init_value with
| `None
No initial value supplied . If the zero directive is in effect , we
give the variable an empty initial value , otherwise leave it alone .
give the variable an empty initial value, otherwise leave it alone. *)
if is_zero then
begin match is_str, is_array with
| false, false -> Meta.assign (`VarOrFn (nowhere, str_id, txt_id)) `Set Meta.zero
| true, false -> Meta.call "strclear" [`VarOrFn (nowhere, str_id, txt_id)]
| false, true -> setrng "setrng" str_id txt_id elt_count
| true, true -> setrng "strclear" str_id txt_id elt_count
end
| `Scalar e
-> if is_array then
if is_str then
let idx = Memory.get_temp_int () in
!Global.compilerFrame__parse (Global.dynArray (
`For
(nowhere,
Global.dynArray (`Assign (nowhere, idx, `Set, Meta.zero)),
`LogOp (nowhere, idx, `Ltn, Meta.int elt_count),
Global.dynArray (`Assign (nowhere, idx, `Add, Meta.int 1)),
`Assign (nowhere, `Deref (nowhere, str_id, txt_id, idx), `Set, e))
))
else
setrng "setrng" str_id txt_id elt_count ~init:e
else
Meta.assign (`VarOrFn (nowhere, str_id, txt_id)) `Set e
| `Array es
-> let len = List.length es in
if len > elt_count then ksprintf (error loc) "too many values supplied to initialise %s[]" str_id;
if is_str then
List.iteri (fun i e -> Meta.assign (`Deref (nowhere, str_id, txt_id, Meta.int i)) `Set e) es
else
Meta.call "setarray" (`Deref (nowhere, str_id, txt_id, Meta.zero) :: es);
if len < elt_count then
if is_zero
then setrng (if is_str then "strclear" else "setrng") str_id txt_id ~first:len elt_count
else ksprintf (warning loc) "not enough values supplied for %s[]: the last %d elements will hold undefined values" str_id (elt_count - len))
variables
elements
| null |
https://raw.githubusercontent.com/eglaysher/rldev/e59103b165e1c20bd940942405b2eee767933c96/src/rlc/variables.ml
|
ocaml
|
Code-generation auxiliaries
Main functions
Allocate and retrieve appropriate addresses to use.
Allocate one block and place individual variables within it.
Allocate variables wherever they'll fit, out of order or split up if necessary.
Define the symbols.
Write to flag.ini if required
If they have, we must take them into account.
String assignments become an optional clearing followed by a series of assignments.
|
Rlc : variable handling
Copyright ( C ) 2006 Haeleth
This program is free software ; you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free Software
Foundation ; either version 2 of the License , or ( at your option ) any later
version .
This program is distributed in the hope that it will be useful , but WITHOUT
ANY WARRANTY ; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE . See the GNU General Public License for more
details .
You should have received a copy of the GNU General Public License along with
this program ; if not , write to the Free Software Foundation , Inc. , 59 Temple
Place - Suite 330 , Boston , MA 02111 - 1307 , USA .
Rlc: variable handling
Copyright (C) 2006 Haeleth
This program is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free Software
Foundation; either version 2 of the License, or (at your option) any later
version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
details.
You should have received a copy of the GNU General Public License along with
this program; if not, write to the Free Software Foundation, Inc., 59 Temple
Place - Suite 330, Boston, MA 02111-1307, USA.
*)
open Printf
open ExtList
open KeTypes
open KeAst
let setrng ?init fn s t ?(first = 0) len =
Meta.call fn (`Deref (nowhere, s, t, Meta.int first)
:: `Deref (nowhere, s, t, Meta.int (len - 1))
:: (match init with None -> [] | Some e -> [e]))
let decldir_of_ident =
let decldir_table =
[Text.ident "zero", `Zero;
Text.ident "block", `Block;
Text.ident "ext", `Ext;
Text.ident "labelled", `Label]
in
fun loc (str_id, txt_id) ->
try
List.assoc txt_id decldir_table
with Not_found ->
ksprintf (error loc) "unknown declaration directive `%s'" str_id
let get_elements (loc, str_id, _, array_length, init_value, _) =
match array_length with
| `None -> 1
| `Auto ->
(match init_value with
| `Array [] -> ksprintf (error loc) "`%s[]' must either be given an explicit length, or the initial value array must contain at least one element" str_id
| `Array l -> List.length l
| _ -> ksprintf (error loc) "array `%s[]' must be given a length, either explicitly or by providing an initial value array" str_id)
| `Some expr ->
(try
Int32.to_int (Global.expr__normalise_and_get_int expr ~abort_on_fail:false)
with Exit ->
ksprintf (error (loc_of_expr expr)) "array length for `%s[]' must evaluate to a constant integer" str_id)
let get_address loc vartype str_id block_size =
function
| None
-> let space, f, max = if vartype = `Str then Memory.temp_str_spec () else Memory.temp_int_spec () in
space, Memory.find_block loc space f block_size ~max
| Some (sp, addr)
-> try
Int32.to_int (Global.expr__normalise_and_get_int sp ~abort_on_fail:false),
Int32.to_int (Global.expr__normalise_and_get_int addr ~abort_on_fail:false)
with Exit ->
ksprintf (error (loc_of_expr sp)) "fixed address for %s must evaluate to a pair of constant integers" str_id
let get_real_address vartype space address address_is_access =
let typed_space, eltmod =
match vartype with
| `Int 1 -> space + 26, 32
| `Int 2 -> space + 52, 16
| `Int 4 -> space + 78, 8
| `Int 8 -> space + 104, 4
| _ -> space, 1
in
let access_address, alloc_address =
if address_is_access
then address, address / eltmod
else address * eltmod, address
in
typed_space, access_address, alloc_address
let allocate (loc, vartype, directives, variables) =
assert (variables != []);
let is_block = List.mem `Block directives
and is_str = vartype = `Str
in
Set ` elements ' to the number of elements required for each variable - 1 for
scalars , or the length for arrays .
scalars, or the length for arrays. *)
let elements =
List.map get_elements variables
in
let spaces_addresses_counts =
let get_block_size elt_count =
match vartype with
| `Str -> elt_count
| `Int elt_bits -> (elt_count * elt_bits - 1) / 32 + 1
in
if is_block then
let elt_total = List.fold_left (+) 0 elements in
let block_size = get_block_size elt_total
and fixed_address =
let all_addresses = List.map (fun (loc, _, _, _, _, rv) -> loc, rv) variables in
let (_, rv), tail = match all_addresses with hd :: tl -> hd, tl | _ -> assert false in
Direct address specifications are invalid other than for the first variable .
List.iter (function _, None -> () | loc, Some _ -> error loc "when the `block' directive is specified, only the first variable in a declaration may have an address specifier") tail;
rv
in
let space, base_address =
get_address loc vartype "block allocation" block_size fixed_address
in
Memory.allocate_block loc space base_address block_size;
let address =
match vartype with
| `Int 1 -> base_address * 32
| `Int 2 -> base_address * 16
| `Int 4 -> base_address * 8
| `Int 8 -> base_address * 4
| _ -> base_address
in
let total, retval =
List.fold_left
(fun (elt_accum, retval) elt_count ->
let blocks_required =
get_block_size elt_count
and typed_space, access_address, alloc_address =
get_real_address vartype space (address + elt_accum) true
in
let elt = space, typed_space, alloc_address, access_address, elt_count, blocks_required in
elt_accum + elt_count, elt :: retval)
(0, [])
elements
in
assert (total == elt_total);
List.rev retval
else
TODO : For now , this is done naively - each variable uses an entire block .
Ideally we would combine multiple sub - int variables in one block where possible .
Ideally we would combine multiple sub-int variables in one block where possible. *)
List.map2
(fun (loc, str_id, _,_,_, fixed_addr) elt_count ->
let blocks_required =
get_block_size elt_count
in
let space, address =
get_address loc vartype str_id blocks_required fixed_addr
in
let typed_space, access_address, alloc_address =
get_real_address vartype space address (fixed_addr <> None)
in
Memory.allocate_block loc space alloc_address blocks_required;
space, typed_space, alloc_address, access_address, elt_count, blocks_required)
variables
elements
in
let scoped = not (List.mem `Ext directives) in
List.iter2
(fun (loc, _, txt_id, array_length, _, _)
(space, typed_space, alloc_address, access_address, elt_count, blocks_required) ->
Memory.define txt_id ~scoped
(`StaticVar
(typed_space,
Int32.of_int access_address,
(if array_length <> `None then Some elt_count else None),
Memory.varidx space,
alloc_address,
blocks_required)))
variables
spaces_addresses_counts;
if !App.flag_labels && (List.mem `Label directives || Memory.check_def "__AllLabelled__" ()) then (
let fn = Filename.concat (Filename.dirname !App.gameexe) "flag.ini" in
let oc = open_out_gen [Open_wronly; Open_creat; Open_append; Open_text] 0o666 fn in
try
List.iter2
(fun (_, str_id, _, array_length, _, _) (_, typed_space, _, access_address, elt_count, _) ->
fprintf oc "%s[%d]:0:%s\n"
(variable_name typed_space ~prefix:false)
access_address
(if array_length = `None then str_id else sprintf "%s[%d]" str_id elt_count))
variables
spaces_addresses_counts;
close_out oc
with e ->
close_out oc;
raise e
);
Initialise the variables
let is_zero = List.mem `Zero directives in
if is_block && is_zero && List.length variables > 1 then begin
Handle block initialisations specially when the ` zero ' directive was passed :
in this case we can sometimes optimise the initialisation fairly easily .
in this case we can sometimes optimise the initialisation fairly easily. *)
let _, str_id, txt_id, _, _, _ = List.hd variables in
let spc, addr =
match Memory.get_as_expression txt_id ~allow_arrays:true with
| `SVar (_, s, `Int (_, idx)) -> s, idx
| `IVar (_, s, `Int (_, idx)) -> s, idx
| _ -> assert false
in
Check whether any non - zero initial values have been provided .
let elt_total, any_have_values =
let expr_non_zero e =
try
!Global.expr__normalise_and_get_const e ~abort_on_fail:false <> `Integer 0l
with Exit ->
true
in
List.fold_left2
(fun (ec, acc) (_, _, _, _, ival, _) ec' -> ec + ec', acc ||
match ival with
| `None -> false
| `Scalar e -> expr_non_zero e
| `Array es -> List.exists expr_non_zero es)
(0, false)
variables
elements
in
If they have n't , we can just zero the entire block .
if not any_have_values then
if is_str then
Meta.call "strclear"
[`SVar (nowhere, spc, `Int (nowhere, addr));
`SVar (nowhere, spc, `Int (nowhere, Int32.add addr (Int32.of_int (elt_total - 1))))]
else
Meta.call "setrng"
[`IVar (nowhere, spc, `Int (nowhere, addr));
`IVar (nowhere, spc, `Int (nowhere, Int32.add addr (Int32.of_int (elt_total - 1))))]
else
let init_values =
List.fold_right2
(fun (loc, str_id, _, _, ival, _) elt_count vallist ->
match ival with
| `None -> List.rev_append (List.make elt_count Meta.zero) vallist
| `Scalar e -> List.rev_append (List.make elt_count e) vallist
| `Array es
-> let len = List.length es in
if len > elt_count then ksprintf (error loc) "too many values supplied to initialise %s[]" str_id;
es @ if len < elt_count
then List.rev_append (List.make (elt_count - len) Meta.zero) vallist
else vallist)
variables elements
[]
in
if is_str then
let any_empty = List.exists (function `Int _ -> true | _ -> false) init_values in
if any_empty then
Meta.call "strclear"
[`SVar (nowhere, spc, `Int (nowhere, addr));
`SVar (nowhere, spc, `Int (nowhere, Int32.add addr (Int32.of_int (elt_total - 1))))];
List.iter
(function `Int _ -> () | expr -> Meta.assign (`VarOrFn (nowhere, str_id, txt_id)) `Set expr)
init_values
else
For ints , we just call . ( This may be a Bad Thing if init_values is very long . )
Meta.call "setarray" (`IVar (nowhere, spc, `Int (nowhere, addr)) :: init_values)
end
else
Not a block allocation , or no ` zero ' directive : initalise variables separately .
List.iter2
(fun (loc, str_id, txt_id, array_length, init_value, _) elt_count ->
let is_array = array_length <> `None in
match init_value with
| `None
No initial value supplied . If the zero directive is in effect , we
give the variable an empty initial value , otherwise leave it alone .
give the variable an empty initial value, otherwise leave it alone. *)
if is_zero then
begin match is_str, is_array with
| false, false -> Meta.assign (`VarOrFn (nowhere, str_id, txt_id)) `Set Meta.zero
| true, false -> Meta.call "strclear" [`VarOrFn (nowhere, str_id, txt_id)]
| false, true -> setrng "setrng" str_id txt_id elt_count
| true, true -> setrng "strclear" str_id txt_id elt_count
end
| `Scalar e
-> if is_array then
if is_str then
let idx = Memory.get_temp_int () in
!Global.compilerFrame__parse (Global.dynArray (
`For
(nowhere,
Global.dynArray (`Assign (nowhere, idx, `Set, Meta.zero)),
`LogOp (nowhere, idx, `Ltn, Meta.int elt_count),
Global.dynArray (`Assign (nowhere, idx, `Add, Meta.int 1)),
`Assign (nowhere, `Deref (nowhere, str_id, txt_id, idx), `Set, e))
))
else
setrng "setrng" str_id txt_id elt_count ~init:e
else
Meta.assign (`VarOrFn (nowhere, str_id, txt_id)) `Set e
| `Array es
-> let len = List.length es in
if len > elt_count then ksprintf (error loc) "too many values supplied to initialise %s[]" str_id;
if is_str then
List.iteri (fun i e -> Meta.assign (`Deref (nowhere, str_id, txt_id, Meta.int i)) `Set e) es
else
Meta.call "setarray" (`Deref (nowhere, str_id, txt_id, Meta.zero) :: es);
if len < elt_count then
if is_zero
then setrng (if is_str then "strclear" else "setrng") str_id txt_id ~first:len elt_count
else ksprintf (warning loc) "not enough values supplied for %s[]: the last %d elements will hold undefined values" str_id (elt_count - len))
variables
elements
|
417dcba43a9654276099d6ad0511b68bda2b9385284298cee68f5888fba07bdd
|
mikera/ironclad
|
gamefactory.clj
|
(ns ic.gamefactory
"Map and level generation routines"
(:use [ic protocols engine map units game])
(:use [clojure.test])
(:use [mc.util])
(:import [mikera.engine Hex])
(:import [mikera.util Rand]))
(set! *warn-on-reflection* true)
(set! *unchecked-math* true)
(def blank-map
(new-map))
(def ^:const DEFAULT_MAP_SIZE 20)
(defn find-point [g pred]
(loop [i 1000]
(let [^ic.engine.Point pt (random-point (:terrain g))]
(if (pred (.x pt) (.y pt))
pt
(if (> i 0)
(recur (dec i))
nil)))))
(defn add-unit-random-position [g side u]
(let [^ic.engine.Point pt (find-point
g
(fn [x y]
(and
(nil? (get-unit g x y))
(suitable-terrain? u (get-terrain g x y)))))
new-unit (merge u
{:side side
:player-id (:id (get-player-for-side g side))})]
(if (nil? pt)
g
(-> g
(add-unit (.x pt) (.y pt) new-unit)))))
(defn add-units [g]
(-> g
(add-unit-random-position 0 (unit "Fortress Turret"))
(add-unit-random-position 0 (unit "Assault Zeppelin"))
(add-unit-random-position 0 (unit "Patrol Boat"))
(add-unit-random-position 0 (unit "Artillery Tank"))
(add-unit-random-position 0 (unit "Paddle Cruiser"))
(add-unit-random-position 0 (unit "Construction Crawler"))
(add-unit-random-position 0 (unit "Rifles"))
(add-unit-random-position 0 (unit "Steam Tank"))
(add-unit-random-position 1 (unit "Construction Crawler"))
(add-unit-random-position 1 (unit "Battle Tank"))
(add-unit-random-position 1 (unit "Rifles"))
(add-unit-random-position 1 (unit "Rifles"))
(add-unit-random-position 1 (unit "Rifles"))))
( defn draw - terrain - line [ g terrain - function sx sy tx ty ]
; (if (and (= sx tx) (= sy ty))
; (set-terrain g tx ty (terrain-funtion (get-terrain g tx ty)))
; (let [])))
(defn regularize-map
([m]
(regularize-map m 0.5))
([m ^Double prob]
(let [tm (atom m)]
(mvisit m
(fn [x y v]
(swap! tm
(fn [om]
(let [dir (mikera.util.Rand/r 6)
dt (mget m (+ x (Hex/dx dir)) (+ y (Hex/dy dir)))]
(if (and dt (Rand/chance prob))
(mset om x y dt)
om))))))
@tm)))
(defn subdivide-map
([m]
(let [tm (atom m)]
(mvisit m
(fn [x y v]
(let [cx (dec (* 2 x))
cy (dec (* 2 y))]
(dotimes [ix 2]
(dotimes [iy 2]
(swap! tm mset
(+ cx ix)
(+ cy iy)
(if
(Rand/chance 0.5)
(if (= ix 1) (mget m (inc x) y) v)
(if (= iy 1) (mget m x (inc y)) v)))))
these two are needed to handle nil edge corners
(swap! tm mset (inc cx) (dec cy)
(if (Rand/chance 0.5) v (mget m (inc x) (dec y))))
(swap! tm mset (dec cx) (inc cy)
(if (Rand/chance 0.5) v (mget m (dec x) (inc y)))))))
@tm)))
(defn make-map-using-function
([] (make-map-using-function 13))
([size]
(make-map-using-function size (fn [x y] (rand-terrain))))
([size function-xy]
(let [m (new-map)]
(reduce
(fn [m [x y]] (mset m x y (function-xy x y)))
m
(for [
x (range 1 (inc size))
y (range 1 (inc size))] [x (- y (/ x 2))])))))
(def region-defs
[
{:desc "Pure grasslands"
:terrain-types ["Grassland"]}
{:desc "Grasslands with scattered lakes and woods"
:terrain-types ["Grassland" "Grassland" "Grassland" "Grassland" "Grassland" "Grassland" "Grassland" "Grassland" "Sea" "Wooded Grassland" "Sea"]}
{:desc "Grasslands with scattered features"
:terrain-types ["Grassland" "Grassland" "Grassland" "Grassland" "Grassland" "Grassland" "Grassland" "Grassland" "Woods" "Wooded Grassland" "Rocky Grassland"]}
{:desc "Pure open sea"
:terrain-types ["Deep Sea"]}
{:desc "Deep Sea with features"
:terrain-types ["Deep Sea" "Deep Sea" "Deep Sea" "Deep Sea" "Deep Sea" "Sea" "Sea Rocks" "Impassable Mountain"]}
{:desc "Shallow Sea"
:terrain-types ["Sea" "Sea" "Sea" "Sea" "Deep Sea" "Deep Sea" "Sea Rocks" "Grassland"]}
{:desc "Rocky coastal/lakes area"
:terrain-types ["Sea" "Sea" "Grassland" "Grassland" "Rocky Grassland" "Rocky Hills" "Mountain" "Deep Sea" "Sea Rocks"]}
{:desc "Heavily wooded area"
:terrain-types ["Woods" "Woods" "Woods" "Grassland" "Grassland" "Rocky Grassland" "Wooded Hills" "Wooded Grassland"]}
{:desc "Hilly wooded/rocky area"
:terrain-types ["Grassland" "Grassland" "Grassland" "Wooded Grassland" "Rocky Grassland" "Woods" "Rocky Hills" "Wooded Hills" "Hills" "Mountain"]}
{:desc "Mountainous area"
:terrain-types ["Grassland" "Grassland" "Grassland" "Grassland" "Rocky Grassland" "Rocky Hills" "Wooded Hills" "Wooded Grassland" "Rocky Grassland" "Hills" "Hills" "Mountain" "Mountain" "Impassable Mountain"]}
])
(defn make-regions
([size]
(applyn
subdivide-map
3
(make-map-using-function (+ 2 (/ size 8)) (fn [x y] (rand-choice region-defs))))))
(defn make-map-from-regions [region-map]
(applyn
regularize-map
2
(mmap region-map
(fn [{terrain-types :terrain-types}]
(terrain (rand-choice terrain-types))))))
(defn cut-map
([source size]
(make-map-using-function
size
(fn [x y] (mget source x y)))))
(defn make-map
([] (make-map DEFAULT_MAP_SIZE))
([size]
(let [source (make-map-from-regions (make-regions size))]
(cut-map source size)
; source
)))
(defn add-default-players [game]
(-> game
(add-player
(player
{:name "Albion"
:side 0
:is-human true
:ai-controlled false}))
(add-player
(player
{:name "Krantz"
:side 1
:ai-controlled true}))
(add-player
(player
{:name "Mekkai"
:side 2
:ai-controlled false}))
(add-player
(player
{:name "Rebels"
:side 3
:ai-controlled true}))))
(defn random-terrain-game [size]
(-> (new-game)
(assoc :terrain (make-map size))
(add-default-players)))
; random challenge game
(defn random-challenge-game []
(-> (new-game)
(assoc :terrain (make-map DEFAULT_MAP_SIZE))
(add-default-players)
(#(reduce
(fn [g i]
(-> g
(add-unit-random-position 0 (ic.units/random-unit))
(add-unit-random-position 1 (ic.units/random-unit))))
%1
(range 10)))))
; game factory function
(defn make-game
([] (make-game DEFAULT_MAP_SIZE))
([size]
(-> (new-game)
(assoc :terrain (make-map size))
(add-default-players)
(add-units))))
(def test-map
(let [m (new-map)]
(reduce
(fn [m [x y]]
(mset m x y (ic.map/terrain "Grassland")))
m
(for [x (range 0 10)
y (range 0 10)]
[x y]))))
| null |
https://raw.githubusercontent.com/mikera/ironclad/ef647bcd097eeaf45f058d43e9e5f53ce910b4b2/src/main/clojure/ic/gamefactory.clj
|
clojure
|
(if (and (= sx tx) (= sy ty))
(set-terrain g tx ty (terrain-funtion (get-terrain g tx ty)))
(let [])))
source
random challenge game
game factory function
|
(ns ic.gamefactory
"Map and level generation routines"
(:use [ic protocols engine map units game])
(:use [clojure.test])
(:use [mc.util])
(:import [mikera.engine Hex])
(:import [mikera.util Rand]))
(set! *warn-on-reflection* true)
(set! *unchecked-math* true)
(def blank-map
(new-map))
(def ^:const DEFAULT_MAP_SIZE 20)
(defn find-point [g pred]
(loop [i 1000]
(let [^ic.engine.Point pt (random-point (:terrain g))]
(if (pred (.x pt) (.y pt))
pt
(if (> i 0)
(recur (dec i))
nil)))))
(defn add-unit-random-position [g side u]
(let [^ic.engine.Point pt (find-point
g
(fn [x y]
(and
(nil? (get-unit g x y))
(suitable-terrain? u (get-terrain g x y)))))
new-unit (merge u
{:side side
:player-id (:id (get-player-for-side g side))})]
(if (nil? pt)
g
(-> g
(add-unit (.x pt) (.y pt) new-unit)))))
(defn add-units [g]
(-> g
(add-unit-random-position 0 (unit "Fortress Turret"))
(add-unit-random-position 0 (unit "Assault Zeppelin"))
(add-unit-random-position 0 (unit "Patrol Boat"))
(add-unit-random-position 0 (unit "Artillery Tank"))
(add-unit-random-position 0 (unit "Paddle Cruiser"))
(add-unit-random-position 0 (unit "Construction Crawler"))
(add-unit-random-position 0 (unit "Rifles"))
(add-unit-random-position 0 (unit "Steam Tank"))
(add-unit-random-position 1 (unit "Construction Crawler"))
(add-unit-random-position 1 (unit "Battle Tank"))
(add-unit-random-position 1 (unit "Rifles"))
(add-unit-random-position 1 (unit "Rifles"))
(add-unit-random-position 1 (unit "Rifles"))))
( defn draw - terrain - line [ g terrain - function sx sy tx ty ]
(defn regularize-map
([m]
(regularize-map m 0.5))
([m ^Double prob]
(let [tm (atom m)]
(mvisit m
(fn [x y v]
(swap! tm
(fn [om]
(let [dir (mikera.util.Rand/r 6)
dt (mget m (+ x (Hex/dx dir)) (+ y (Hex/dy dir)))]
(if (and dt (Rand/chance prob))
(mset om x y dt)
om))))))
@tm)))
(defn subdivide-map
([m]
(let [tm (atom m)]
(mvisit m
(fn [x y v]
(let [cx (dec (* 2 x))
cy (dec (* 2 y))]
(dotimes [ix 2]
(dotimes [iy 2]
(swap! tm mset
(+ cx ix)
(+ cy iy)
(if
(Rand/chance 0.5)
(if (= ix 1) (mget m (inc x) y) v)
(if (= iy 1) (mget m x (inc y)) v)))))
these two are needed to handle nil edge corners
(swap! tm mset (inc cx) (dec cy)
(if (Rand/chance 0.5) v (mget m (inc x) (dec y))))
(swap! tm mset (dec cx) (inc cy)
(if (Rand/chance 0.5) v (mget m (dec x) (inc y)))))))
@tm)))
(defn make-map-using-function
([] (make-map-using-function 13))
([size]
(make-map-using-function size (fn [x y] (rand-terrain))))
([size function-xy]
(let [m (new-map)]
(reduce
(fn [m [x y]] (mset m x y (function-xy x y)))
m
(for [
x (range 1 (inc size))
y (range 1 (inc size))] [x (- y (/ x 2))])))))
(def region-defs
[
{:desc "Pure grasslands"
:terrain-types ["Grassland"]}
{:desc "Grasslands with scattered lakes and woods"
:terrain-types ["Grassland" "Grassland" "Grassland" "Grassland" "Grassland" "Grassland" "Grassland" "Grassland" "Sea" "Wooded Grassland" "Sea"]}
{:desc "Grasslands with scattered features"
:terrain-types ["Grassland" "Grassland" "Grassland" "Grassland" "Grassland" "Grassland" "Grassland" "Grassland" "Woods" "Wooded Grassland" "Rocky Grassland"]}
{:desc "Pure open sea"
:terrain-types ["Deep Sea"]}
{:desc "Deep Sea with features"
:terrain-types ["Deep Sea" "Deep Sea" "Deep Sea" "Deep Sea" "Deep Sea" "Sea" "Sea Rocks" "Impassable Mountain"]}
{:desc "Shallow Sea"
:terrain-types ["Sea" "Sea" "Sea" "Sea" "Deep Sea" "Deep Sea" "Sea Rocks" "Grassland"]}
{:desc "Rocky coastal/lakes area"
:terrain-types ["Sea" "Sea" "Grassland" "Grassland" "Rocky Grassland" "Rocky Hills" "Mountain" "Deep Sea" "Sea Rocks"]}
{:desc "Heavily wooded area"
:terrain-types ["Woods" "Woods" "Woods" "Grassland" "Grassland" "Rocky Grassland" "Wooded Hills" "Wooded Grassland"]}
{:desc "Hilly wooded/rocky area"
:terrain-types ["Grassland" "Grassland" "Grassland" "Wooded Grassland" "Rocky Grassland" "Woods" "Rocky Hills" "Wooded Hills" "Hills" "Mountain"]}
{:desc "Mountainous area"
:terrain-types ["Grassland" "Grassland" "Grassland" "Grassland" "Rocky Grassland" "Rocky Hills" "Wooded Hills" "Wooded Grassland" "Rocky Grassland" "Hills" "Hills" "Mountain" "Mountain" "Impassable Mountain"]}
])
(defn make-regions
([size]
(applyn
subdivide-map
3
(make-map-using-function (+ 2 (/ size 8)) (fn [x y] (rand-choice region-defs))))))
(defn make-map-from-regions [region-map]
(applyn
regularize-map
2
(mmap region-map
(fn [{terrain-types :terrain-types}]
(terrain (rand-choice terrain-types))))))
(defn cut-map
([source size]
(make-map-using-function
size
(fn [x y] (mget source x y)))))
(defn make-map
([] (make-map DEFAULT_MAP_SIZE))
([size]
(let [source (make-map-from-regions (make-regions size))]
(cut-map source size)
)))
(defn add-default-players [game]
(-> game
(add-player
(player
{:name "Albion"
:side 0
:is-human true
:ai-controlled false}))
(add-player
(player
{:name "Krantz"
:side 1
:ai-controlled true}))
(add-player
(player
{:name "Mekkai"
:side 2
:ai-controlled false}))
(add-player
(player
{:name "Rebels"
:side 3
:ai-controlled true}))))
(defn random-terrain-game [size]
(-> (new-game)
(assoc :terrain (make-map size))
(add-default-players)))
(defn random-challenge-game []
(-> (new-game)
(assoc :terrain (make-map DEFAULT_MAP_SIZE))
(add-default-players)
(#(reduce
(fn [g i]
(-> g
(add-unit-random-position 0 (ic.units/random-unit))
(add-unit-random-position 1 (ic.units/random-unit))))
%1
(range 10)))))
(defn make-game
([] (make-game DEFAULT_MAP_SIZE))
([size]
(-> (new-game)
(assoc :terrain (make-map size))
(add-default-players)
(add-units))))
(def test-map
(let [m (new-map)]
(reduce
(fn [m [x y]]
(mset m x y (ic.map/terrain "Grassland")))
m
(for [x (range 0 10)
y (range 0 10)]
[x y]))))
|
d998e10957fd5a89968629d4bb4b79d9313d6ac6e1c23b487c0ab6bea853f453
|
jabber-at/ejabberd
|
configure_deps.erl
|
-module(configure_deps).
-export(['configure-deps'/2]).
'configure-deps'(Config, Vals) ->
{ok, Config}.
| null |
https://raw.githubusercontent.com/jabber-at/ejabberd/7bfec36856eaa4df21b26e879d3ba90285bad1aa/plugins/configure_deps.erl
|
erlang
|
-module(configure_deps).
-export(['configure-deps'/2]).
'configure-deps'(Config, Vals) ->
{ok, Config}.
|
|
735a4bd9d40b9c50075c0db525cf5d4054c216abb67d3893d7ff8bdfc5c262eb
|
bytekid/mkbtt
|
aCULogic.ml
|
(*** OPENS ***************************************************************)
open Util;;
(*** SUBMODULES **********************************************************)
module Var = Rewriting.Variable;;
module Fun = Rewriting.Function;;
module M = U.Monad;;
module T = U.Term;;
module Sub = U.Substitution;;
module Elogic = U.Elogic;;
module TSub = Replacement.Make(T)(T);;
module L = U.Label;;
module Sig = U.Signature;;
module A = ACLogicNoFakeAux;;
* * OPENS ( 2 ) * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
open M;;
(*** EXCEPTIONS **********************************************************)
exception Repeated_variables
(*** FUNCTIONS ***********************************************************)
let theory : Theory.t ref = ref []
let t_solve = ref 0.0
zero substitution list { { } }
let zero_list = [Sub.empty]
let is_ac_symbol = M.is_theory L.AC
let is_acu_symbol = Theory.is_acu_symbol
let is_ac_or_acu_symbol f th =
M.is_theory L.AC f >>= fun ac ->
return (ac || (Theory.is_acu_symbol f th))
;;
let unit_for = Theory.unit_for
let ac_root = function
| T.Var _ -> return None
| T.Fun(f,_) ->
is_ac_symbol f >>= fun b -> return (if b then Some f else None)
;;
let list_option = function
| [] -> None
| l -> Some l
;;
let flat_map_option f l =
let add res x =
f x >>= function
| None -> return res
| Some res' -> return (res @ res')
in foldl add [] l
;;
let acu_simplify f th t =
let z = unit_for f th in
let e = T.Fun(z,[]) in
let t' = A.feterm f z (List.filter (fun t' -> t' <> e) (T.args t)) in
t', T.compare t t' <> 0
;;
let rec acu_simplify_all th = function
| (T.Var _) as t -> t
| T.Fun(f, ts) ->
let t = T.Fun(f, List.map (acu_simplify_all th) ts) in
if is_acu_symbol f th then fst (acu_simplify f th t) else t
;;
Given terms s and t , return complete set of unifiers for s=_{AC } t.
Calls unify ' and simplifies returned set of bindings in that all
bindings x - > t are removed where x does not occur in s or t.
Calls unify' and simplifies returned set of bindings in that all
bindings x -> t are removed where x does not occur in s or t. *)
let rec unify_me th c (s, t) =
T.to_stringm s > > = fun rs - >
T.to_stringm t > > = fun ts - >
Format.printf " \nNo Fake : Unification start % s with % s ( % i)\n% ! " ts rs c ;
T.to_stringm t >>= fun ts ->
Format.printf "\nNo Fake: Unification start %s with %s (%i)\n%!" ts rs c;*)
(* restrict substitution to variables of interest *)
let vars = List.union (T.vars s) (T.vars t) in
let add x t s = if List.mem x vars then Sub.add x t s else s in
let simplify s = Sub.fold add s Sub.empty in
(lift (Option.map (List.map simplify))) (unify th (c+1) (s, t))
(* Given terms s and t, return complete set of unifiers for s=_{AC} t.
When matching, s is ground. *)
and unify th c (s,t) =
T.to_stringm s > > = fun rs - >
T.to_stringm t > > = fun ts - >
Format.printf " \nUnify % s with % s ( % i)\n% ! " ts rs c ;
T.to_stringm t >>= fun ts ->
Format.printf "\nUnify %s with %s (%i)\n%!" ts rs c;*)
match s, t with
| T.Var x, _ ->
if T.is_proper_subterm s t then return None (* fail *)
else if s = t then return (Some zero_list)
else return (Some [Sub.add x t Sub.empty])
| _, T.Var y ->
if T.is_proper_subterm t s then return None (* fail *)
else return (Some [Sub.add y s Sub.empty])
| T.Fun(a,[]),T.Fun(b,[]) -> (* both constants *)
if a = b then return (Some zero_list) else return None
| T.Fun(f, fs), T.Fun(g, gs) when f <> g ->
let f_is_acu, g_is_acu = is_acu_symbol f th, is_acu_symbol g th in
let use_f = f_is_acu (*&& (List.for_all T.is_var fs)*) in
let use_g = g_is_acu (*&& (List.for_all T.is_var gs)*) in
if use_f then
if use_g then
let cjs = A.acu_unify_fterm s t (f,unit_for f th) in
flat_map_option (unify_conjunction th c) cjs >>= fun subs ->
let cjs = A.acu_unify_fterm t s (g,unit_for g th) in
flat_map_option (unify_conjunction th c) cjs >>= fun subs' ->
return (list_option (subs @ subs'))
else
let cjs = A.acu_unify_fterm s t (f,unit_for f th) in
flat_map_option (unify_conjunction th c) cjs >>= (return <.> list_option)
else if use_g then
let cjs = A.acu_unify_fterm t s (g,unit_for g th) in
flat_map_option (unify_conjunction th c) cjs >>= (return <.> list_option)
else
if f_is_acu then
(let s', p = acu_simplify f th s in
if p then unify th c (s',t) else return None)
else if g_is_acu then
(let t', p = acu_simplify g th t in
if p then unify th c (s,t') else return None)
else return None
| T.Fun(f,ss), T.Fun(_, ts) -> ((* same root symbol *)
if not (is_acu_symbol f th) then (* assume length ss = length ts *)
unify_with_list th c (List.zip ss ts) zero_list
else (
Termx.flatten s >>= fun s' -> Termx.flatten t >>= fun t' ->
(* (1) remove common arguments *)
let ss', ts' = A.remove_common_args (T.args s') (T.args t') in
T.to_stringm (T.Fun(f,ss')) >>= fun s1 ->
T.to_stringm (T.Fun(f,ts')) >>= fun s2 ->
Format.printf "after common args removed: %s, %s\n%!" s1 s2;
if List.is_empty ss' && List.is_empty ts' then
return (Some [Sub.empty])
else if List.is_empty ss' || List.is_empty ts' then
return None
else (
( 1 ) abstract non - variable terms
Format.printf "Before abstract\n%!";
A.more_abstract (T.Fun(f,ss')) (T.Fun(f,ts')) >>= fun (cs,xs,ys,theta) ->
project A.str_vars (xs,ys) >>= fun (xss,yss) ->
Format.printf "Abstractions: %s and %s \n Constraint:%!" xss yss;
A.print_constraints cs >>= fun _ ->
( 2 ) solve diophantine equations
let b = DioMio.solve (xs,ys) in
A.str_assignments b >>= fun bs ->
Format.printf "Assignments: %s\n%!" bs;
( 3 ) find minimal solution subset
let b = DioMio.minimize b in
A.str_assignments b >>= fun bs ->
Format.printf "Minimal Assignments: %s\n%!" bs;
( 4 ) construct semigroup representation , fresh vars for rows
A.to_semigroup f b >>= fun (b',vars) ->
A.list_to_stringm (A.list_to_stringm (A.list_to_stringm T.to_stringm)) (Array.to_list (Array.map Array.to_list b')) >>= fun bs ->
Format.printf "to semigroup yields %s\n%!" bs;
( 5 ) construct semigroup unifier ( sum of all minimal ones )
(* let gamma = A.sum_up bsubsets b' (xs,ys) f in*)
let tau = A.sum b' (xs,ys) (f,unit_for f th) in
Format.printf "Tau: %i\n%!" (if Sub.is_empty tau then 0 else 1);
A.print_sub tau >>= fun _ ->
( 6 ) make substitutions idempotent
let tau = A.make_idempotent tau in
( 10 ) recursively solve subproblems
acu_unify_with ( c+1 ) e cs tau theta ( List.unique ( xs@ys ) )
Format.printf "Tau: %i\n%!" (if Sub.is_empty tau then 0 else 1);
unify_with_list th c cs [tau]
) ))
and acu_unify_with c e es tau theta vars =
let consider_var subs x =
( * match \theta x with | , t - > can not happen currently
and acu_unify_with c e es tau theta vars =
let consider_var subs x =
(* match \theta x with | T.Var x, t -> cannot happen currently *)
let app = Sub.apply_term
let rhos =
if theta x defined then
A.acu_unify_fterm e (app tau x) (app theta x) else in
let add csus rho =
let compose s = Sub.compose Sub.apply_term rho s in
let cs = A.sub_constraints rho es in
unify_conjunction c cs >>= function
| None -> return csus
| Some z -> return ((List.map compose z) @ csus)
in foldl add [] rhos
in
foldl consider_var [] vars >>= function
" ( % i ) Unify list with constraints:\n% ! " c ;
print_constraints es > > = fun _ - >
Format.printf " ( % i ) and substitutions \n% ! " c ;
print_subs subs > > = fun _ - >
Format.printf " ( % i ) yields % i results\n% ! " c ( List.length subs ) ;
print_subs subs > >
print_constraints es >>= fun _ ->
Format.printf "(%i) and substitutions \n%!" c;
print_subs subs >>= fun _ ->
Format.printf "(%i) yields %i results\n%!" c (List.length subs);
print_subs subs >>*)
[] -> return None | subs -> return (Some subs)
*)
Given list ( i.e. conjunction ) of equations es and set of substitutions
subs , take union of CSU(es\theta ) over all \theta in subs , where CSU(X )
is complete set of unifiers for X.
subs, take union of CSU(es\theta) over all \theta in subs, where CSU(X)
is complete set of unifiers for X. *)
and unify_with_list th c es subs =
let add csus theta =
let compose s = Sub.compose Sub.apply_term theta s in
let cs = A.sub_constraints theta es in
" Unify list with constraints:\n% ! " ;
cs > > = fun _ - >
A.print_constraints cs >>= fun _ ->*)
unify_conjunction th c cs >>= function
| None -> return csus
| Some z -> return ((List.map compose z) @ csus)
in
" Called unify list with initial constraints:\n% ! " ;
A.print_constraints es > > = fun _ - >
Format.printf " ( % i ) and substitutions \n% ! " c ;
A.print_subs subs > > = fun _ - >
A.print_constraints es >>= fun _ ->
Format.printf "(%i) and substitutions \n%!" c;
A.print_subs subs >>= fun _ ->*)
foldl add [] subs >>= fun subs ->
" ( % i ) Unify list with constraints:\n% ! " c ;
print_constraints es > > = fun _ - >
Format.printf " ( % i ) and substitutions \n% ! " c ;
print_subs subs > > = fun _ - >
Format.printf " ( % i ) yields % i results\n% ! " c ( List.length subs ) ;
print_subs subs > >
print_constraints es >>= fun _ ->
Format.printf "(%i) and substitutions \n%!" c;
print_subs subs >>= fun _ ->
Format.printf "(%i) yields %i results\n%!" c (List.length subs);
print_subs subs >>*)
match subs with
[] -> return None | subs -> return (Some subs)
(* Given a list (i.e. conjunction) of equations es, return complete set
of unifiers for es. *)
and unify_conjunction th c cj =
" Called unify conjunction % i elements\n " ( cj ) ;
match cj with
| [] -> return (Some zero_list) (*e.g. unify (fxy,fxy) *)
| [e1] -> unify th c e1
| e1 :: es -> unify th c e1 >>= function
| None -> return None | Some ss -> unify_with_list th c es ss
;;
let unify ts =
T.to_stringm (fst ts) >>= fun s1 ->
T.to_stringm (snd ts) >>= fun s2 ->
Format.printf "\nNo Fake: Unification start %s with %s\n%!" s1 s2;
unify_me !theory 0 ts >>= fun subs -> (
let subs = Option.map (List.map (Sub.map (acu_simplify_all !theory))) subs in
match subs with
| None -> Format.printf "No Result\n"; return None
| Some s ->
(let s = List.unique s in
Format.printf "Result: \n%!"; A.print_subs s) >>
return (Some s))
;;
(* TESTS *)
let test () =
let sigma = Sig.empty 20 in
let x,sigma = Sig.create_var "x" sigma in
let y,sigma = Sig.create_var "y" sigma in
let z,sigma = Sig.create_var "z" sigma in
let u,sigma = Sig.create_var "u" sigma in
let v,sigma = Sig.create_var "v" sigma in
let w,sigma = Sig.create_var "w" sigma in
let x,y,z,u,v,w = T.Var x, T.Var y, T.Var z, T.Var u, T.Var v, T.Var w in
let f,sigma = Sig.create_fun 2 "f" sigma in
let f,sigma = Sig.set_theory f U.Label.AC sigma in
let a,sigma = Sig.create_fun 0 "a" sigma in
let b,sigma = Sig.create_fun 0 "b" sigma in
let c,sigma = Sig.create_fun 0 "c" sigma in
let d,sigma = Sig.create_fun 0 "d" sigma in
let e,sigma = Sig.create_fun 0 "e" sigma in
let g,sigma = Sig.create_fun 1 "g" sigma in
let a_ = T.Fun(a, []) in
let b_ = T.Fun(b, []) in
let c_ = T.Fun(c, []) in
let d_ = T.Fun(d, []) in
let e_ = T.Fun(e, []) in
let faa = T.Fun(f, [a_;a_]) in
let faaa = T.Fun(f, [a_;faa]) in
let fabc = T.Fun(f, [a_;T.Fun(f, [b_;c_])]) in
let fcab = T.Fun(f, [c_;T.Fun(f, [a_;b_])]) in
let faby = T.Fun(f, [a_;T.Fun(f, [b_;y])]) in
let fxy = T.Fun(f, [x;y]) in
let fxx = T.Fun(f, [x;x]) in
let fyy = T.Fun(f, [y;y]) in
let fzz = T.Fun(f, [z;z]) in
let fax = T.Fun(f, [a_;x]) in
let gx = T.Fun(g, [x]) in
let ga = T.Fun(g, [a_]) in
let gb = T.Fun(g, [b_]) in
let gu = T.Fun(g, [u]) in
let fgax = T.Fun(f, [ga; x]) in
let fgay = T.Fun(f, [ga; y]) in
let gfaa = T.Fun(g,[faa]) in
let gfax = T.Fun(g,[fax]) in
let rec flist = function
[s; t] -> T.Fun(f, [s; t])
| s :: ts -> T.Fun(f, [s; flist ts])
| _ -> failwith "Unexpected pattern"
in
let t_lc88_1 = flist [c_;c_;gu; x] in
let t_lc88_2 = flist [b_;ga;y; z] in
(* testing unification *)
let run_unify (s,t) = Either.right (M.run sigma (
Termx.flatten s >>= fun s ->
Termx.flatten t >>= fun t ->
unify (s,t))) in
let print_subs (s,t) = let (s,n) = Either.right (M.run sigma (
Termx.flatten s >>= fun s ->
Termx.flatten t >>= fun t ->
T.to_stringm s >>= fun ss ->
T.to_stringm t >>= fun ts ->
let m = "To unify "^ss^" and "^ts^", " in
unify (s,t) >>= function
None -> return (m^"none", 0)
| Some us ->
let m' = m^(string_of_int (List.length us))^" substitutions\n" in
iter (fun f ->
project (Termx.flatten <.> (Sub.apply_term f)) (s,t) >>= fun (s,t) ->
assert (T.equal s t); return () ) us >>
foldl
(fun s u -> A.print_sub u >>= fun us -> return (s^"\n or\n"^us))
m' us >>= fun s -> return (s, List.length us)
)) in Format.printf "%s\n" s; n in
let assert_some ts =
assert(ignore (print_subs ts); Option.is_some (run_unify ts)) in
let assert_more ts n =
assert(Option.is_some (run_unify ts)); assert (print_subs ts = n) in
let assert_none ts = assert(Option.is_none (run_unify ts)) in
assert_some (x,x);
assert_some (x,y);
assert_some (x,a_);
assert_some (a_, y);
assert_some (a_,a_);
assert_none (ga,gb);
assert_some (gx,ga);
assert_some (faa, y);
assert_some (gx,gfaa);
assert_none (a_, gx);
assert_none (x, gx);
assert_some (y, gx);
assert_none (faa, faaa);
assert_some (fcab, fabc);
assert_some (faa, fax);
assert_some (gfaa, gfax);
assert_some (faaa, fax);
assert_some (fabc, fax);
assert_some (faa, fxy);
assert_some (flist[a_;b_], fxy);
assert_some (fabc, fxy);
assert_some (faby, fxy);
assert_some (T.Fun(f,[u; gfaa]), T.Fun(f, [gfax; y]));
assert_none (fgax, fax);
assert_some (fgay, fax);
assert_none (fgay, faaa);
assert_some (fgay, fgay);
assert_some (T.Fun(f, [T.Fun(g,[faa]); u]), faby);
(* examples with repeated variables *)
assert_some (fxx,fyy);
assert_some (fxy,fzz);
assert_some (flist [x;x;gx], flist[u;u;gu]);
some examples from christian / lincoln 88
assert_some (t_lc88_1,t_lc88_2);
assert_more (flist [x;a_;b_],flist [u;c_;d_;e_]) 2;
assert_more (flist [x;a_;b_],flist [u;c_;c_;d_]) 2;
assert_more (flist [x;a_;b_],flist [u;c_;c_;c_]) 2;
assert_more (flist [x;a_;b_],flist [u;y;c_;d_]) 12;
assert_more (flist [x;a_;b_],flist [u;y;c_;c_]) 12;
assert_more (flist [x;a_;b_],flist [u;y;z;c_]) 30;
assert_more (flist [x;a_;b_],flist [u;y;z;v]) 56;
assert_more (flist [x;a_;a_],flist [u;c_;d_;e_]) 2;
assert_more (flist [x;a_;a_],flist [u;c_;c_;d_]) 2;
assert_more (flist [x;a_;a_],flist [u;c_;c_;c_]) 2;
not just 8
not just 18
not just 32
assert_more (flist [x;y;a_],flist [u;c_;d_;e_]) 28;
not just 20
assert_more (flist [x;y;a_],flist [u;v;c_;d_]) 88;
assert_more (flist [x;y;a_],flist [u;v;z;c_]) 204;
assert_more (flist [x;y;z],flist [u;v;c_;d_]) 336;
assert_more (flist [x;y;z],flist [u;v;w;c_]) 870;
;;
(*test ()*)
| null |
https://raw.githubusercontent.com/bytekid/mkbtt/c2f8e0615389b52eabd12655fe48237aa0fe83fd/src/mascott/src/aCULogic.ml
|
ocaml
|
** OPENS **************************************************************
** SUBMODULES *********************************************************
** EXCEPTIONS *********************************************************
** FUNCTIONS **********************************************************
restrict substitution to variables of interest
Given terms s and t, return complete set of unifiers for s=_{AC} t.
When matching, s is ground.
fail
fail
both constants
&& (List.for_all T.is_var fs)
&& (List.for_all T.is_var gs)
same root symbol
assume length ss = length ts
(1) remove common arguments
let gamma = A.sum_up bsubsets b' (xs,ys) f in
match \theta x with | T.Var x, t -> cannot happen currently
Given a list (i.e. conjunction) of equations es, return complete set
of unifiers for es.
e.g. unify (fxy,fxy)
TESTS
testing unification
examples with repeated variables
test ()
|
open Util;;
module Var = Rewriting.Variable;;
module Fun = Rewriting.Function;;
module M = U.Monad;;
module T = U.Term;;
module Sub = U.Substitution;;
module Elogic = U.Elogic;;
module TSub = Replacement.Make(T)(T);;
module L = U.Label;;
module Sig = U.Signature;;
module A = ACLogicNoFakeAux;;
* * OPENS ( 2 ) * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
open M;;
exception Repeated_variables
let theory : Theory.t ref = ref []
let t_solve = ref 0.0
zero substitution list { { } }
let zero_list = [Sub.empty]
let is_ac_symbol = M.is_theory L.AC
let is_acu_symbol = Theory.is_acu_symbol
let is_ac_or_acu_symbol f th =
M.is_theory L.AC f >>= fun ac ->
return (ac || (Theory.is_acu_symbol f th))
;;
let unit_for = Theory.unit_for
let ac_root = function
| T.Var _ -> return None
| T.Fun(f,_) ->
is_ac_symbol f >>= fun b -> return (if b then Some f else None)
;;
let list_option = function
| [] -> None
| l -> Some l
;;
let flat_map_option f l =
let add res x =
f x >>= function
| None -> return res
| Some res' -> return (res @ res')
in foldl add [] l
;;
let acu_simplify f th t =
let z = unit_for f th in
let e = T.Fun(z,[]) in
let t' = A.feterm f z (List.filter (fun t' -> t' <> e) (T.args t)) in
t', T.compare t t' <> 0
;;
let rec acu_simplify_all th = function
| (T.Var _) as t -> t
| T.Fun(f, ts) ->
let t = T.Fun(f, List.map (acu_simplify_all th) ts) in
if is_acu_symbol f th then fst (acu_simplify f th t) else t
;;
Given terms s and t , return complete set of unifiers for s=_{AC } t.
Calls unify ' and simplifies returned set of bindings in that all
bindings x - > t are removed where x does not occur in s or t.
Calls unify' and simplifies returned set of bindings in that all
bindings x -> t are removed where x does not occur in s or t. *)
let rec unify_me th c (s, t) =
T.to_stringm s > > = fun rs - >
T.to_stringm t > > = fun ts - >
Format.printf " \nNo Fake : Unification start % s with % s ( % i)\n% ! " ts rs c ;
T.to_stringm t >>= fun ts ->
Format.printf "\nNo Fake: Unification start %s with %s (%i)\n%!" ts rs c;*)
let vars = List.union (T.vars s) (T.vars t) in
let add x t s = if List.mem x vars then Sub.add x t s else s in
let simplify s = Sub.fold add s Sub.empty in
(lift (Option.map (List.map simplify))) (unify th (c+1) (s, t))
and unify th c (s,t) =
T.to_stringm s > > = fun rs - >
T.to_stringm t > > = fun ts - >
Format.printf " \nUnify % s with % s ( % i)\n% ! " ts rs c ;
T.to_stringm t >>= fun ts ->
Format.printf "\nUnify %s with %s (%i)\n%!" ts rs c;*)
match s, t with
| T.Var x, _ ->
else if s = t then return (Some zero_list)
else return (Some [Sub.add x t Sub.empty])
| _, T.Var y ->
else return (Some [Sub.add y s Sub.empty])
if a = b then return (Some zero_list) else return None
| T.Fun(f, fs), T.Fun(g, gs) when f <> g ->
let f_is_acu, g_is_acu = is_acu_symbol f th, is_acu_symbol g th in
if use_f then
if use_g then
let cjs = A.acu_unify_fterm s t (f,unit_for f th) in
flat_map_option (unify_conjunction th c) cjs >>= fun subs ->
let cjs = A.acu_unify_fterm t s (g,unit_for g th) in
flat_map_option (unify_conjunction th c) cjs >>= fun subs' ->
return (list_option (subs @ subs'))
else
let cjs = A.acu_unify_fterm s t (f,unit_for f th) in
flat_map_option (unify_conjunction th c) cjs >>= (return <.> list_option)
else if use_g then
let cjs = A.acu_unify_fterm t s (g,unit_for g th) in
flat_map_option (unify_conjunction th c) cjs >>= (return <.> list_option)
else
if f_is_acu then
(let s', p = acu_simplify f th s in
if p then unify th c (s',t) else return None)
else if g_is_acu then
(let t', p = acu_simplify g th t in
if p then unify th c (s,t') else return None)
else return None
unify_with_list th c (List.zip ss ts) zero_list
else (
Termx.flatten s >>= fun s' -> Termx.flatten t >>= fun t' ->
let ss', ts' = A.remove_common_args (T.args s') (T.args t') in
T.to_stringm (T.Fun(f,ss')) >>= fun s1 ->
T.to_stringm (T.Fun(f,ts')) >>= fun s2 ->
Format.printf "after common args removed: %s, %s\n%!" s1 s2;
if List.is_empty ss' && List.is_empty ts' then
return (Some [Sub.empty])
else if List.is_empty ss' || List.is_empty ts' then
return None
else (
( 1 ) abstract non - variable terms
Format.printf "Before abstract\n%!";
A.more_abstract (T.Fun(f,ss')) (T.Fun(f,ts')) >>= fun (cs,xs,ys,theta) ->
project A.str_vars (xs,ys) >>= fun (xss,yss) ->
Format.printf "Abstractions: %s and %s \n Constraint:%!" xss yss;
A.print_constraints cs >>= fun _ ->
( 2 ) solve diophantine equations
let b = DioMio.solve (xs,ys) in
A.str_assignments b >>= fun bs ->
Format.printf "Assignments: %s\n%!" bs;
( 3 ) find minimal solution subset
let b = DioMio.minimize b in
A.str_assignments b >>= fun bs ->
Format.printf "Minimal Assignments: %s\n%!" bs;
( 4 ) construct semigroup representation , fresh vars for rows
A.to_semigroup f b >>= fun (b',vars) ->
A.list_to_stringm (A.list_to_stringm (A.list_to_stringm T.to_stringm)) (Array.to_list (Array.map Array.to_list b')) >>= fun bs ->
Format.printf "to semigroup yields %s\n%!" bs;
( 5 ) construct semigroup unifier ( sum of all minimal ones )
let tau = A.sum b' (xs,ys) (f,unit_for f th) in
Format.printf "Tau: %i\n%!" (if Sub.is_empty tau then 0 else 1);
A.print_sub tau >>= fun _ ->
( 6 ) make substitutions idempotent
let tau = A.make_idempotent tau in
( 10 ) recursively solve subproblems
acu_unify_with ( c+1 ) e cs tau theta ( List.unique ( xs@ys ) )
Format.printf "Tau: %i\n%!" (if Sub.is_empty tau then 0 else 1);
unify_with_list th c cs [tau]
) ))
and acu_unify_with c e es tau theta vars =
let consider_var subs x =
( * match \theta x with | , t - > can not happen currently
and acu_unify_with c e es tau theta vars =
let consider_var subs x =
let app = Sub.apply_term
let rhos =
if theta x defined then
A.acu_unify_fterm e (app tau x) (app theta x) else in
let add csus rho =
let compose s = Sub.compose Sub.apply_term rho s in
let cs = A.sub_constraints rho es in
unify_conjunction c cs >>= function
| None -> return csus
| Some z -> return ((List.map compose z) @ csus)
in foldl add [] rhos
in
foldl consider_var [] vars >>= function
" ( % i ) Unify list with constraints:\n% ! " c ;
print_constraints es > > = fun _ - >
Format.printf " ( % i ) and substitutions \n% ! " c ;
print_subs subs > > = fun _ - >
Format.printf " ( % i ) yields % i results\n% ! " c ( List.length subs ) ;
print_subs subs > >
print_constraints es >>= fun _ ->
Format.printf "(%i) and substitutions \n%!" c;
print_subs subs >>= fun _ ->
Format.printf "(%i) yields %i results\n%!" c (List.length subs);
print_subs subs >>*)
[] -> return None | subs -> return (Some subs)
*)
Given list ( i.e. conjunction ) of equations es and set of substitutions
subs , take union of CSU(es\theta ) over all \theta in subs , where CSU(X )
is complete set of unifiers for X.
subs, take union of CSU(es\theta) over all \theta in subs, where CSU(X)
is complete set of unifiers for X. *)
and unify_with_list th c es subs =
let add csus theta =
let compose s = Sub.compose Sub.apply_term theta s in
let cs = A.sub_constraints theta es in
" Unify list with constraints:\n% ! " ;
cs > > = fun _ - >
A.print_constraints cs >>= fun _ ->*)
unify_conjunction th c cs >>= function
| None -> return csus
| Some z -> return ((List.map compose z) @ csus)
in
" Called unify list with initial constraints:\n% ! " ;
A.print_constraints es > > = fun _ - >
Format.printf " ( % i ) and substitutions \n% ! " c ;
A.print_subs subs > > = fun _ - >
A.print_constraints es >>= fun _ ->
Format.printf "(%i) and substitutions \n%!" c;
A.print_subs subs >>= fun _ ->*)
foldl add [] subs >>= fun subs ->
" ( % i ) Unify list with constraints:\n% ! " c ;
print_constraints es > > = fun _ - >
Format.printf " ( % i ) and substitutions \n% ! " c ;
print_subs subs > > = fun _ - >
Format.printf " ( % i ) yields % i results\n% ! " c ( List.length subs ) ;
print_subs subs > >
print_constraints es >>= fun _ ->
Format.printf "(%i) and substitutions \n%!" c;
print_subs subs >>= fun _ ->
Format.printf "(%i) yields %i results\n%!" c (List.length subs);
print_subs subs >>*)
match subs with
[] -> return None | subs -> return (Some subs)
and unify_conjunction th c cj =
" Called unify conjunction % i elements\n " ( cj ) ;
match cj with
| [e1] -> unify th c e1
| e1 :: es -> unify th c e1 >>= function
| None -> return None | Some ss -> unify_with_list th c es ss
;;
let unify ts =
T.to_stringm (fst ts) >>= fun s1 ->
T.to_stringm (snd ts) >>= fun s2 ->
Format.printf "\nNo Fake: Unification start %s with %s\n%!" s1 s2;
unify_me !theory 0 ts >>= fun subs -> (
let subs = Option.map (List.map (Sub.map (acu_simplify_all !theory))) subs in
match subs with
| None -> Format.printf "No Result\n"; return None
| Some s ->
(let s = List.unique s in
Format.printf "Result: \n%!"; A.print_subs s) >>
return (Some s))
;;
let test () =
let sigma = Sig.empty 20 in
let x,sigma = Sig.create_var "x" sigma in
let y,sigma = Sig.create_var "y" sigma in
let z,sigma = Sig.create_var "z" sigma in
let u,sigma = Sig.create_var "u" sigma in
let v,sigma = Sig.create_var "v" sigma in
let w,sigma = Sig.create_var "w" sigma in
let x,y,z,u,v,w = T.Var x, T.Var y, T.Var z, T.Var u, T.Var v, T.Var w in
let f,sigma = Sig.create_fun 2 "f" sigma in
let f,sigma = Sig.set_theory f U.Label.AC sigma in
let a,sigma = Sig.create_fun 0 "a" sigma in
let b,sigma = Sig.create_fun 0 "b" sigma in
let c,sigma = Sig.create_fun 0 "c" sigma in
let d,sigma = Sig.create_fun 0 "d" sigma in
let e,sigma = Sig.create_fun 0 "e" sigma in
let g,sigma = Sig.create_fun 1 "g" sigma in
let a_ = T.Fun(a, []) in
let b_ = T.Fun(b, []) in
let c_ = T.Fun(c, []) in
let d_ = T.Fun(d, []) in
let e_ = T.Fun(e, []) in
let faa = T.Fun(f, [a_;a_]) in
let faaa = T.Fun(f, [a_;faa]) in
let fabc = T.Fun(f, [a_;T.Fun(f, [b_;c_])]) in
let fcab = T.Fun(f, [c_;T.Fun(f, [a_;b_])]) in
let faby = T.Fun(f, [a_;T.Fun(f, [b_;y])]) in
let fxy = T.Fun(f, [x;y]) in
let fxx = T.Fun(f, [x;x]) in
let fyy = T.Fun(f, [y;y]) in
let fzz = T.Fun(f, [z;z]) in
let fax = T.Fun(f, [a_;x]) in
let gx = T.Fun(g, [x]) in
let ga = T.Fun(g, [a_]) in
let gb = T.Fun(g, [b_]) in
let gu = T.Fun(g, [u]) in
let fgax = T.Fun(f, [ga; x]) in
let fgay = T.Fun(f, [ga; y]) in
let gfaa = T.Fun(g,[faa]) in
let gfax = T.Fun(g,[fax]) in
let rec flist = function
[s; t] -> T.Fun(f, [s; t])
| s :: ts -> T.Fun(f, [s; flist ts])
| _ -> failwith "Unexpected pattern"
in
let t_lc88_1 = flist [c_;c_;gu; x] in
let t_lc88_2 = flist [b_;ga;y; z] in
let run_unify (s,t) = Either.right (M.run sigma (
Termx.flatten s >>= fun s ->
Termx.flatten t >>= fun t ->
unify (s,t))) in
let print_subs (s,t) = let (s,n) = Either.right (M.run sigma (
Termx.flatten s >>= fun s ->
Termx.flatten t >>= fun t ->
T.to_stringm s >>= fun ss ->
T.to_stringm t >>= fun ts ->
let m = "To unify "^ss^" and "^ts^", " in
unify (s,t) >>= function
None -> return (m^"none", 0)
| Some us ->
let m' = m^(string_of_int (List.length us))^" substitutions\n" in
iter (fun f ->
project (Termx.flatten <.> (Sub.apply_term f)) (s,t) >>= fun (s,t) ->
assert (T.equal s t); return () ) us >>
foldl
(fun s u -> A.print_sub u >>= fun us -> return (s^"\n or\n"^us))
m' us >>= fun s -> return (s, List.length us)
)) in Format.printf "%s\n" s; n in
let assert_some ts =
assert(ignore (print_subs ts); Option.is_some (run_unify ts)) in
let assert_more ts n =
assert(Option.is_some (run_unify ts)); assert (print_subs ts = n) in
let assert_none ts = assert(Option.is_none (run_unify ts)) in
assert_some (x,x);
assert_some (x,y);
assert_some (x,a_);
assert_some (a_, y);
assert_some (a_,a_);
assert_none (ga,gb);
assert_some (gx,ga);
assert_some (faa, y);
assert_some (gx,gfaa);
assert_none (a_, gx);
assert_none (x, gx);
assert_some (y, gx);
assert_none (faa, faaa);
assert_some (fcab, fabc);
assert_some (faa, fax);
assert_some (gfaa, gfax);
assert_some (faaa, fax);
assert_some (fabc, fax);
assert_some (faa, fxy);
assert_some (flist[a_;b_], fxy);
assert_some (fabc, fxy);
assert_some (faby, fxy);
assert_some (T.Fun(f,[u; gfaa]), T.Fun(f, [gfax; y]));
assert_none (fgax, fax);
assert_some (fgay, fax);
assert_none (fgay, faaa);
assert_some (fgay, fgay);
assert_some (T.Fun(f, [T.Fun(g,[faa]); u]), faby);
assert_some (fxx,fyy);
assert_some (fxy,fzz);
assert_some (flist [x;x;gx], flist[u;u;gu]);
some examples from christian / lincoln 88
assert_some (t_lc88_1,t_lc88_2);
assert_more (flist [x;a_;b_],flist [u;c_;d_;e_]) 2;
assert_more (flist [x;a_;b_],flist [u;c_;c_;d_]) 2;
assert_more (flist [x;a_;b_],flist [u;c_;c_;c_]) 2;
assert_more (flist [x;a_;b_],flist [u;y;c_;d_]) 12;
assert_more (flist [x;a_;b_],flist [u;y;c_;c_]) 12;
assert_more (flist [x;a_;b_],flist [u;y;z;c_]) 30;
assert_more (flist [x;a_;b_],flist [u;y;z;v]) 56;
assert_more (flist [x;a_;a_],flist [u;c_;d_;e_]) 2;
assert_more (flist [x;a_;a_],flist [u;c_;c_;d_]) 2;
assert_more (flist [x;a_;a_],flist [u;c_;c_;c_]) 2;
not just 8
not just 18
not just 32
assert_more (flist [x;y;a_],flist [u;c_;d_;e_]) 28;
not just 20
assert_more (flist [x;y;a_],flist [u;v;c_;d_]) 88;
assert_more (flist [x;y;a_],flist [u;v;z;c_]) 204;
assert_more (flist [x;y;z],flist [u;v;c_;d_]) 336;
assert_more (flist [x;y;z],flist [u;v;w;c_]) 870;
;;
|
73af29bd1ab0cc62503cd103c39f414320986e88b8ab79473a9c4d2714bfc680
|
AlexanderMann/conj-2016
|
project.clj
|
(defproject conj-2016 "0.1.0-SNAPSHOT"
:description "Repo for work pertaining to TSNE, Conj, and English Embeddings"
:url "-2016"
:license {:name "Eclipse Public License"
:url "-v10.html"}
:resource-paths ["resources"]
:dependencies [[cheshire "5.7.0"]
[clatrix "0.5.0"]
[com.taoensso/timbre "4.8.0"]
[com.taoensso/tufte "1.1.1"]
[dali "0.7.3"]
[incanter "1.9.1"]
[net.mikera/core.matrix "0.57.0"]
[org.clojure/clojure "1.9.0-alpha14"]
[org.clojure/core.memoize "0.5.9"]
[org.clojure/data.csv "0.1.3"]
[org.clojure/test.check "0.9.0"]]
:jvm-opts ["-Xmx8g"]
:aliases {"nrepl" ["repl" ":headless" ":port" "54321"]})
| null |
https://raw.githubusercontent.com/AlexanderMann/conj-2016/00b07f654f83ca1da7af4486d58b7d0add880544/project.clj
|
clojure
|
(defproject conj-2016 "0.1.0-SNAPSHOT"
:description "Repo for work pertaining to TSNE, Conj, and English Embeddings"
:url "-2016"
:license {:name "Eclipse Public License"
:url "-v10.html"}
:resource-paths ["resources"]
:dependencies [[cheshire "5.7.0"]
[clatrix "0.5.0"]
[com.taoensso/timbre "4.8.0"]
[com.taoensso/tufte "1.1.1"]
[dali "0.7.3"]
[incanter "1.9.1"]
[net.mikera/core.matrix "0.57.0"]
[org.clojure/clojure "1.9.0-alpha14"]
[org.clojure/core.memoize "0.5.9"]
[org.clojure/data.csv "0.1.3"]
[org.clojure/test.check "0.9.0"]]
:jvm-opts ["-Xmx8g"]
:aliases {"nrepl" ["repl" ":headless" ":port" "54321"]})
|
|
41a9d991a9b02a2c5aa06117d57f0a35e80dac8420eb926dd55bf39b3f297425
|
cloudant/lager_rsyslog
|
lager_rsyslog_util.erl
|
This file is provided to you under the Apache License ,
%% Version 2.0 (the "License"); you may not use this file
except in compliance with the License . You may obtain
%% a copy of the License at
%%
%% -2.0
%%
%% Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
" AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY
%% KIND, either express or implied. See the License for the
%% specific language governing permissions and limitations
%% under the License.
-module(lager_rsyslog_util).
-export([
dest_addr/1,
dest_port/1,
identity/1,
facility/1,
mask/1,
level/1,
formatter/1,
iso8601_timestamp/0
]).
-include("lager_rsyslog.hrl").
dest_addr(Config) ->
case lists:keyfind(host, 1, Config) of
{host, Host} ->
case inet:getaddr(Host, inet) of
{ok, Address} ->
Address;
_ ->
{127, 0, 0, 1}
end;
false ->
{127, 0, 0, 1}
end.
dest_port(Config) ->
case lists:keyfind(port, 1, Config) of
{port, P} when is_integer(P), P > 0, P < 65536 ->
P;
_ ->
514
end.
identity(Config) ->
case lists:keyfind(identity, 1, Config) of
{identity, Ident} when is_atom(Ident) orelse is_list(Ident) ->
Ident;
false ->
hd(string:tokens(atom_to_list(node()), "@"))
end.
facility(Config) ->
case lists:keyfind(facility, 1, Config) of
{facility, Facility} ->
facility_int(Facility);
false ->
facility_int(local2)
end.
facility_int(kern) -> (0 bsl 3);
facility_int(user) -> (1 bsl 3);
facility_int(mail) -> (2 bsl 3);
facility_int(daemon) -> (3 bsl 3);
facility_int(auth) -> (4 bsl 3);
facility_int(syslog) -> (5 bsl 3);
facility_int(lpr) -> (6 bsl 3);
facility_int(news) -> (7 bsl 3);
facility_int(uucp) -> (8 bsl 3);
facility_int(cron) -> (9 bsl 3);
facility_int(authpriv) -> (10 bsl 3);
facility_int(ftp) -> (11 bsl 3);
facility_int(local0) -> (16 bsl 3);
facility_int(local1) -> (17 bsl 3);
facility_int(local2) -> (18 bsl 3);
facility_int(local3) -> (19 bsl 3);
facility_int(local4) -> (20 bsl 3);
facility_int(local5) -> (21 bsl 3);
facility_int(local6) -> (22 bsl 3);
facility_int(local7) -> (23 bsl 3);
facility_int(Facility) when is_list(Facility) ->
facility_int(list_to_existing_atom(Facility));
facility_int(Facility) when is_binary(Facility) ->
facility_int(list_to_existing_atom(binary_to_list(Facility))).
mask(Config) ->
case lists:keyfind(level, 1, Config) of
{level, Level} ->
try
lager_util:config_to_mask(Level)
catch _:_ ->
lager_util:config_to_mask(info)
end;
false ->
lager_util:config_to_mask(info)
end.
level(debug) -> 7;
level(info) -> 6;
level(notice) -> 5;
level(warn) -> 4;
level(warning) -> 4;
level(err) -> 3;
level(error) -> 3;
level(crit) -> 2;
level(alert) -> 1;
level(emerg) -> 0;
level(panic) -> 0;
level(I) when is_integer(I), I >= 0, I =< 7 ->
I;
level(_BadLevel) ->
3.
formatter(Config) ->
case lists:keyfind(formatter, 1, Config) of
{formatter, {Mod, FmtCfg}} when is_atom(Mod) ->
{Mod, FmtCfg};
false ->
?DEFAULT_FORMATTER
end.
iso8601_timestamp() ->
{_,_,Micro} = Now = os:timestamp(),
{{Year,Month,Date},{Hour,Minute,Second}} = calendar:now_to_datetime(Now),
Format = "~4.10.0B-~2.10.0B-~2.10.0BT~2.10.0B:~2.10.0B:~2.10.0B.~6.10.0BZ",
io_lib:format(Format, [Year, Month, Date, Hour, Minute, Second, Micro]).
| null |
https://raw.githubusercontent.com/cloudant/lager_rsyslog/f90ed8ce0f655b49d4914649f06a3d79ed64cdd6/src/lager_rsyslog_util.erl
|
erlang
|
Version 2.0 (the "License"); you may not use this file
a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing,
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
|
This file is provided to you under the Apache License ,
except in compliance with the License . You may obtain
software distributed under the License is distributed on an
" AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY
-module(lager_rsyslog_util).
-export([
dest_addr/1,
dest_port/1,
identity/1,
facility/1,
mask/1,
level/1,
formatter/1,
iso8601_timestamp/0
]).
-include("lager_rsyslog.hrl").
dest_addr(Config) ->
case lists:keyfind(host, 1, Config) of
{host, Host} ->
case inet:getaddr(Host, inet) of
{ok, Address} ->
Address;
_ ->
{127, 0, 0, 1}
end;
false ->
{127, 0, 0, 1}
end.
dest_port(Config) ->
case lists:keyfind(port, 1, Config) of
{port, P} when is_integer(P), P > 0, P < 65536 ->
P;
_ ->
514
end.
identity(Config) ->
case lists:keyfind(identity, 1, Config) of
{identity, Ident} when is_atom(Ident) orelse is_list(Ident) ->
Ident;
false ->
hd(string:tokens(atom_to_list(node()), "@"))
end.
facility(Config) ->
case lists:keyfind(facility, 1, Config) of
{facility, Facility} ->
facility_int(Facility);
false ->
facility_int(local2)
end.
facility_int(kern) -> (0 bsl 3);
facility_int(user) -> (1 bsl 3);
facility_int(mail) -> (2 bsl 3);
facility_int(daemon) -> (3 bsl 3);
facility_int(auth) -> (4 bsl 3);
facility_int(syslog) -> (5 bsl 3);
facility_int(lpr) -> (6 bsl 3);
facility_int(news) -> (7 bsl 3);
facility_int(uucp) -> (8 bsl 3);
facility_int(cron) -> (9 bsl 3);
facility_int(authpriv) -> (10 bsl 3);
facility_int(ftp) -> (11 bsl 3);
facility_int(local0) -> (16 bsl 3);
facility_int(local1) -> (17 bsl 3);
facility_int(local2) -> (18 bsl 3);
facility_int(local3) -> (19 bsl 3);
facility_int(local4) -> (20 bsl 3);
facility_int(local5) -> (21 bsl 3);
facility_int(local6) -> (22 bsl 3);
facility_int(local7) -> (23 bsl 3);
facility_int(Facility) when is_list(Facility) ->
facility_int(list_to_existing_atom(Facility));
facility_int(Facility) when is_binary(Facility) ->
facility_int(list_to_existing_atom(binary_to_list(Facility))).
mask(Config) ->
case lists:keyfind(level, 1, Config) of
{level, Level} ->
try
lager_util:config_to_mask(Level)
catch _:_ ->
lager_util:config_to_mask(info)
end;
false ->
lager_util:config_to_mask(info)
end.
level(debug) -> 7;
level(info) -> 6;
level(notice) -> 5;
level(warn) -> 4;
level(warning) -> 4;
level(err) -> 3;
level(error) -> 3;
level(crit) -> 2;
level(alert) -> 1;
level(emerg) -> 0;
level(panic) -> 0;
level(I) when is_integer(I), I >= 0, I =< 7 ->
I;
level(_BadLevel) ->
3.
formatter(Config) ->
case lists:keyfind(formatter, 1, Config) of
{formatter, {Mod, FmtCfg}} when is_atom(Mod) ->
{Mod, FmtCfg};
false ->
?DEFAULT_FORMATTER
end.
iso8601_timestamp() ->
{_,_,Micro} = Now = os:timestamp(),
{{Year,Month,Date},{Hour,Minute,Second}} = calendar:now_to_datetime(Now),
Format = "~4.10.0B-~2.10.0B-~2.10.0BT~2.10.0B:~2.10.0B:~2.10.0B.~6.10.0BZ",
io_lib:format(Format, [Year, Month, Date, Hour, Minute, Second, Micro]).
|
e9459b10939b23161ac0777a2a6ab7f5afc612ad7e1ef02e0febe2fa201ed4c6
|
grapesmoker/cl-sfml
|
keyboard.lisp
|
(in-package :sfml)
(defcenum sf-key-code
(:sf-key-unknown -1)
(:sf-key-a 0)
(:sf-key-b 1)
(:sf-key-c 2)
(:sf-key-d 3)
(:sf-key-e 4)
(:sf-key-f 5)
(:sf-key-g 6)
(:sf-key-h 7)
(:sf-key-i 8)
(:sf-key-j 9)
(:sf-key-k 10)
(:sf-key-l 11)
(:sf-key-m 12)
(:sf-key-n 13)
(:sf-key-o 14)
(:sf-key-p 15)
(:sf-key-q 16)
(:sf-key-r 17)
(:sf-key-s 18)
(:sf-key-t 19)
(:sf-key-u 20)
(:sf-key-v 21)
(:sf-key-w 22)
(:sf-key-x 23)
(:sf-key-y 24)
(:sf-key-z 25)
(:sf-key-num-0 26)
(:sf-key-num-1 27)
(:sf-key-num-2 28)
(:sf-key-num-3 29)
(:sf-key-num-4 30)
(:sf-key-num-5 31)
(:sf-key-num-6 32)
(:sf-key-num-7 33)
(:sf-key-num-8 34)
(:sf-key-num-9 35)
(:sf-key-escape 36)
(:sf-key-l-control 37)
(:sf-key-l-shift 38)
(:sf-key-l-alt 39)
(:sf-key-l-system 40)
(:sf-key-r-control 41)
(:sf-key-r-shift 42)
(:sf-key-r-alt 43)
(:sf-key-r-system 44)
(:sf-key-menu 45)
(:sf-key-l-bracket 46)
(:sf-key-r-bracket 47)
(:sf-key-semicolon 48)
(:sf-key-comma 49)
(:sf-key-period 50)
(:sf-key-quote 51)
(:sf-key-slash 52)
(:sf-key-backslash 53)
(:sf-key-tilde 54)
(:sf-key-equal 55)
(:sf-key-dash 56)
(:sf-key-space 57)
(:sf-key-return 58)
(:sf-key-back 59)
(:sf-key-tab 60)
(:sf-key-page-up 61)
(:sf-key-page-down 62)
(:sf-key-end 63)
(:sf-key-home 64)
(:sf-key-insert 65)
(:sf-key-delete 66)
(:sf-key-add 67)
(:sf-key-subtract 68)
(:sf-key-multiply 69)
(:sf-key-divide 70)
(:sf-key-left 71)
(:sf-key-right 72)
(:sf-key-up 73)
(:sf-key-down 74)
(:sf-key-numpad-0 75)
(:sf-key-numpad-1 76)
(:sf-key-numpad-2 77)
(:sf-key-numpad-3 78)
(:sf-key-numpad-4 79)
(:sf-key-numpad-5 80)
(:sf-key-numpad-6 81)
(:sf-key-numpad-7 82)
(:sf-key-numpad-8 83)
(:sf-key-numpad-9 84)
(:sf-key-f1 85)
(:sf-key-f2 86)
(:sf-key-f3 87)
(:sf-key-f4 88)
(:sf-key-f5 89)
(:sf-key-f6 90)
(:sf-key-f7 91)
(:sf-key-f8 92)
(:sf-key-f9 93)
(:sf-key-f10 94)
(:sf-key-f11 95)
(:sf-key-f12 96)
(:sf-key-f13 97)
(:sf-key-f14 98)
(:sf-key-f15 99)
(:sf-key-pause 100)
(:sf-key-count 101))
(defparameter *keypress-mapping*
'(8 :sf-key-backspace
27 :sf-key-escape
39 :sf-key-quote
42 :sf-key-multiply
43 :sf-key-add
44 :sf-key-comma
45 :sf-key-subtract
46 :sf-key-period
47 :sf-key-divide
59 :sf-key-semicolon
61 :sf-key-equal
91 :sf-key-l-bracket
92 :sf-key-backslash
93 :sf-key-r-bracket
96 :sf-key-tilde
127 :sf-key-delete))
(defcfun ("sfKeyboard_isKeyPressed" sf-keyboard-is-key-pressed) :boolean
(key sf-key-code))
(defun is-key-pressed? (key-code)
(sf-keyboard-is-key-pressed key-code))
;; (foreign-enum-keyword 'sf-key-code key-code)))
| null |
https://raw.githubusercontent.com/grapesmoker/cl-sfml/3e587b431bbdd23dde2d0031f979d859ac436bca/win/keyboard.lisp
|
lisp
|
(foreign-enum-keyword 'sf-key-code key-code)))
|
(in-package :sfml)
(defcenum sf-key-code
(:sf-key-unknown -1)
(:sf-key-a 0)
(:sf-key-b 1)
(:sf-key-c 2)
(:sf-key-d 3)
(:sf-key-e 4)
(:sf-key-f 5)
(:sf-key-g 6)
(:sf-key-h 7)
(:sf-key-i 8)
(:sf-key-j 9)
(:sf-key-k 10)
(:sf-key-l 11)
(:sf-key-m 12)
(:sf-key-n 13)
(:sf-key-o 14)
(:sf-key-p 15)
(:sf-key-q 16)
(:sf-key-r 17)
(:sf-key-s 18)
(:sf-key-t 19)
(:sf-key-u 20)
(:sf-key-v 21)
(:sf-key-w 22)
(:sf-key-x 23)
(:sf-key-y 24)
(:sf-key-z 25)
(:sf-key-num-0 26)
(:sf-key-num-1 27)
(:sf-key-num-2 28)
(:sf-key-num-3 29)
(:sf-key-num-4 30)
(:sf-key-num-5 31)
(:sf-key-num-6 32)
(:sf-key-num-7 33)
(:sf-key-num-8 34)
(:sf-key-num-9 35)
(:sf-key-escape 36)
(:sf-key-l-control 37)
(:sf-key-l-shift 38)
(:sf-key-l-alt 39)
(:sf-key-l-system 40)
(:sf-key-r-control 41)
(:sf-key-r-shift 42)
(:sf-key-r-alt 43)
(:sf-key-r-system 44)
(:sf-key-menu 45)
(:sf-key-l-bracket 46)
(:sf-key-r-bracket 47)
(:sf-key-semicolon 48)
(:sf-key-comma 49)
(:sf-key-period 50)
(:sf-key-quote 51)
(:sf-key-slash 52)
(:sf-key-backslash 53)
(:sf-key-tilde 54)
(:sf-key-equal 55)
(:sf-key-dash 56)
(:sf-key-space 57)
(:sf-key-return 58)
(:sf-key-back 59)
(:sf-key-tab 60)
(:sf-key-page-up 61)
(:sf-key-page-down 62)
(:sf-key-end 63)
(:sf-key-home 64)
(:sf-key-insert 65)
(:sf-key-delete 66)
(:sf-key-add 67)
(:sf-key-subtract 68)
(:sf-key-multiply 69)
(:sf-key-divide 70)
(:sf-key-left 71)
(:sf-key-right 72)
(:sf-key-up 73)
(:sf-key-down 74)
(:sf-key-numpad-0 75)
(:sf-key-numpad-1 76)
(:sf-key-numpad-2 77)
(:sf-key-numpad-3 78)
(:sf-key-numpad-4 79)
(:sf-key-numpad-5 80)
(:sf-key-numpad-6 81)
(:sf-key-numpad-7 82)
(:sf-key-numpad-8 83)
(:sf-key-numpad-9 84)
(:sf-key-f1 85)
(:sf-key-f2 86)
(:sf-key-f3 87)
(:sf-key-f4 88)
(:sf-key-f5 89)
(:sf-key-f6 90)
(:sf-key-f7 91)
(:sf-key-f8 92)
(:sf-key-f9 93)
(:sf-key-f10 94)
(:sf-key-f11 95)
(:sf-key-f12 96)
(:sf-key-f13 97)
(:sf-key-f14 98)
(:sf-key-f15 99)
(:sf-key-pause 100)
(:sf-key-count 101))
(defparameter *keypress-mapping*
'(8 :sf-key-backspace
27 :sf-key-escape
39 :sf-key-quote
42 :sf-key-multiply
43 :sf-key-add
44 :sf-key-comma
45 :sf-key-subtract
46 :sf-key-period
47 :sf-key-divide
59 :sf-key-semicolon
61 :sf-key-equal
91 :sf-key-l-bracket
92 :sf-key-backslash
93 :sf-key-r-bracket
96 :sf-key-tilde
127 :sf-key-delete))
(defcfun ("sfKeyboard_isKeyPressed" sf-keyboard-is-key-pressed) :boolean
(key sf-key-code))
(defun is-key-pressed? (key-code)
(sf-keyboard-is-key-pressed key-code))
|
838936ccff3213bced5b710cf1a367b708a3990ed0ae828be7124d5deb9b8157
|
dschrempf/elynx
|
Alignment.hs
|
-- |
-- Module : ELynx.Sequence.Alignment
-- Description : Multi sequence alignment related types and functions
Copyright : 2021
License : GPL-3.0 - or - later
--
-- Maintainer :
-- Stability : unstable
--
-- Portability : portable
--
Creation date : Thu Oct 4 18:40:18 2018 .
--
-- This module is to be imported qualified.
module ELynx.Sequence.Alignment
( Alignment (..),
length,
nSequences,
-- | * Input, output
fromSequences,
toSequences,
summarize,
-- | * Manipulation
join,
concat,
concatAlignments,
filterColsConstant,
filterColsConstantSoft,
filterColsOnlyStd,
filterColsStd,
filterColsNoGaps,
-- | * Analysis
FrequencyData,
distribution,
toFrequencyData,
kEffEntropy,
kEffHomoplasy,
countIUPACChars,
countGaps,
countUnknowns,
-- | * Sub sample
subSample,
randomSubSample,
)
where
import Control.Monad hiding (join)
import Control.Parallel.Strategies
import qualified Data.ByteString.Lazy.Char8 as BL
import Data.List hiding
( concat,
length,
)
import qualified Data.Matrix.Unboxed as M
import qualified Data.Vector.Unboxed as V
import qualified ELynx.Alphabet.Alphabet as A
import ELynx.Alphabet.Character
import qualified ELynx.Alphabet.DistributionDiversity as D
import ELynx.Sequence.Defaults
import qualified ELynx.Sequence.Sequence as S
import System.Random.Stateful
import Prelude hiding
( concat,
length,
)
-- | A collection of sequences.
data Alignment = Alignment
{ names :: [S.Name],
descriptions :: [S.Description],
alphabet :: A.Alphabet,
matrix :: M.Matrix Character
}
deriving (Show, Eq)
-- | Number of sites.
length :: Alignment -> Int
length = M.cols . matrix
-- | Number of sequences.
nSequences :: Alignment -> Int
nSequences = M.rows . matrix
| Create ' Alignment ' from a list of ' S.Sequence 's .
fromSequences :: [S.Sequence] -> Either String Alignment
fromSequences ss
| S.equalLength ss && allEqual (map S.alphabet ss) =
Right $
Alignment ns ds a d
| S.equalLength ss = Left "Sequences do not have equal codes."
| otherwise = Left "Sequences do not have equal lengths."
where
ns = map S.name ss
ds = map S.description ss
a = S.alphabet $ head ss
bss = map S.characters ss
d = M.fromRows bss
allEqual [] = True
allEqual xs = all (== head xs) $ tail xs
| Conversion to list of ' S.Sequence 's .
toSequences :: Alignment -> [S.Sequence]
toSequences (Alignment ns ds a da) =
zipWith3
(\n d r -> S.Sequence n d a r)
ns
ds
rows
where
rows = M.toRows da
header :: Alignment -> BL.ByteString
header a =
BL.unlines $
[ BL.pack "Multi sequence alignment.",
BL.pack $ "Code: " ++ A.alphabetDescription (alphabet a) ++ ".",
BL.pack $ "Length: " ++ show (length a) ++ "."
]
++ reportLengthSummary
++ reportNumberSummary
where
reportLengthSummary =
[ BL.pack $
"For each sequence, the "
++ show summaryLength
++ " first bases are shown."
| length a > summaryLength
]
reportNumberSummary =
[ BL.pack $
show summaryNSequences
++ " out of "
++ show (nSequences a)
++ " sequences are shown."
| nSequences a > summaryNSequences
]
-- | Similar to 'S.summarizeSequenceList' but with different Header.
summarize :: Alignment -> BL.ByteString
summarize a = header a <> S.body (toSequences a)
-- Vertical concatenation.
(===) :: V.Unbox a => M.Matrix a -> M.Matrix a -> M.Matrix a
(===) l r = M.fromRows $ lRs ++ rRs
where
lRs = M.toRows l
rRs = M.toRows r
Horizontal concatenation .
(|||) :: V.Unbox a => M.Matrix a -> M.Matrix a -> M.Matrix a
(|||) l r = M.fromColumns $ lCs ++ rCs
where
lCs = M.toColumns l
rCs = M.toColumns r
| Join two ' Alignment 's vertically . That is , add more sequences
-- to an alignment. See also 'concat'.
join :: Alignment -> Alignment -> Alignment
-- top bottom.
join t b
| length t /= length b =
error
"join: Multi sequence alignments do not have equal lengths."
| alphabet t /= alphabet b =
error
"join: Multi sequence alignments do not have equal alphabets."
| otherwise = Alignment ns ds al (tD === bD)
where
ns = names t ++ names b
ds = descriptions t ++ descriptions b
tD = matrix t
bD = matrix b
al = alphabet t
| Concatenate two ' Alignment 's horizontally . That is , add more
-- sites to an alignment. See also 'join'.
concat :: Alignment -> Alignment -> Alignment
-- left right.
concat l r
| nSequences l /= nSequences r =
error
"concat: Multi sequence alignments do not have an equal number of sequences."
| alphabet l /= alphabet r =
error "concat: Multi sequence alignments do not have an equal alphabets."
| names l /= names r =
error "concat: Multi sequence alignments do not have an equal names."
| descriptions l /= descriptions r =
error "concat: Multi sequence alignments do not have an equal descriptions."
| otherwise =
Alignment (names l) (descriptions l) (alphabet l) (lD ||| rD)
where
lD = matrix l
rD = matrix r
-- | Concatenate a list of 'Alignment's horizontally. See
-- 'concat'.
concatAlignments :: [Alignment] -> Alignment
concatAlignments [] = error "concatAlignments: Nothing to concatenate."
concatAlignments [a] = a
concatAlignments as = foldl' concat (head as) (tail as)
-- Only keep columns from alignment that satisfy given predicate.
filterColsWith :: (V.Vector Character -> Bool) -> Alignment -> Alignment
filterColsWith p a = a {matrix = m'}
where
m' = M.fromColumns . filter p . M.toColumns $ matrix a
-- | Only keep constant columns.
filterColsConstant :: Alignment -> Alignment
filterColsConstant = filterColsWith (\v -> V.all (== V.head v) v)
| Only keep constant columns , and constant columns with at least one standard
-- character as well as any number of gaps or unknowns.
filterColsConstantSoft :: Alignment -> Alignment
filterColsConstantSoft a = filterColsWith f a
where
al = alphabet a
f v = case V.find (A.isStd al) v of
Nothing -> False
Just c -> V.all (\x -> x == c || A.isGap al x || A.isUnknown al x) v
| Only keep columns with standard characters . Alignment columns with IUPAC
-- characters are removed.
filterColsOnlyStd :: Alignment -> Alignment
filterColsOnlyStd a = filterColsWith (V.all $ A.isStd (alphabet a)) a
-- | Filter columns with proportion of standard character larger than given number.
filterColsStd :: Double -> Alignment -> Alignment
filterColsStd prop a =
filterColsWith
(\col -> prop * n <= fromIntegral (V.length (V.filter (A.isStd al) col)))
a
where
al = alphabet a
n = fromIntegral $ nSequences a
-- | Only keep columns without gaps or unknown characters.
filterColsNoGaps :: Alignment -> Alignment
filterColsNoGaps a = filterColsWith (V.all $ not . A.isGap (alphabet a)) a
-- | Frequency data; do not store the actual characters, but their frequencies.
The matrix is of size @N x K@ , where @N@ is the number of sites , and @K@ is
-- the number of characters.
type FrequencyData = M.Matrix Double
Map a function on each column of a DIM2 array ; parallel version with given chunk size .
fMapColParChunk ::
(V.Unbox a, V.Unbox b) =>
Int ->
(V.Vector a -> V.Vector b) ->
M.Matrix a ->
M.Matrix b
fMapColParChunk n f m =
M.fromColumns (map f (M.toColumns m) `using` parListChunk n rseq)
-- | Calculcate frequency of characters at each site of a multi sequence alignment.
toFrequencyData :: Alignment -> FrequencyData
toFrequencyData a = fMapColParChunk 100 (D.frequencyCharacters spec) (matrix a)
where
spec = A.alphabetSpec (alphabet a)
-- | Calculate the distribution of characters.
distribution :: FrequencyData -> [Double]
distribution fd =
map (/ fromIntegral nSites) $
V.toList $
foldl1
(V.zipWith (+))
(M.toColumns fd)
where
nSites = M.cols fd
-- Parallel map with given chunk size.
parMapChunk :: Int -> (a -> b) -> [a] -> [b]
parMapChunk n f as = map f as `using` parListChunk n rseq
chunksize :: Int
chunksize = 500
-- | Diversity analysis. See 'kEffEntropy'.
kEffEntropy :: FrequencyData -> [Double]
kEffEntropy fd = parMapChunk chunksize D.kEffEntropy (M.toColumns fd)
-- | Diversity analysis. See 'kEffEntropy'.
kEffHomoplasy :: FrequencyData -> [Double]
kEffHomoplasy fd = parMapChunk chunksize D.kEffHomoplasy (M.toColumns fd)
| Count the number of standard ( i.e. , not extended IUPAC ) characters in the
-- alignment.
countIUPACChars :: Alignment -> Int
countIUPACChars a = V.length . V.filter (A.isIUPAC (alphabet a)) $ allChars
where
allChars = M.flatten $ matrix a
-- | Count the number of gaps in the alignment.
countGaps :: Alignment -> Int
countGaps a = V.length . V.filter (A.isGap (alphabet a)) $ allChars
where
allChars = M.flatten $ matrix a
-- | Count the number of unknown characters in the alignment.
countUnknowns :: Alignment -> Int
countUnknowns a = V.length . V.filter (A.isUnknown (alphabet a)) $ allChars
where
allChars = M.flatten $ matrix a
-- Sample the given sites from a matrix.
subSampleMatrix :: V.Unbox a => [Int] -> M.Matrix a -> M.Matrix a
subSampleMatrix is m =
M.fromColumns $ foldl' (\a i -> M.takeColumn m i : a) [] (reverse is)
-- | Sample the given sites from a multi sequence alignment.
subSample :: [Int] -> Alignment -> Alignment
subSample is a = a {matrix = m'} where m' = subSampleMatrix is $ matrix a
-- | Randomly sample a given number of sites of the multi sequence alignment.
randomSubSample :: StatefulGen g m => Int -> Alignment -> g -> m Alignment
randomSubSample n a g = do
let l = length a
is <- replicateM n $ uniformRM (0, l - 1) g
return $ subSample is a
| null |
https://raw.githubusercontent.com/dschrempf/elynx/bf5f0b353b5e2f74d29058fc86ea6723133cab5c/elynx-seq/src/ELynx/Sequence/Alignment.hs
|
haskell
|
|
Module : ELynx.Sequence.Alignment
Description : Multi sequence alignment related types and functions
Maintainer :
Stability : unstable
Portability : portable
This module is to be imported qualified.
| * Input, output
| * Manipulation
| * Analysis
| * Sub sample
| A collection of sequences.
| Number of sites.
| Number of sequences.
| Similar to 'S.summarizeSequenceList' but with different Header.
Vertical concatenation.
to an alignment. See also 'concat'.
top bottom.
sites to an alignment. See also 'join'.
left right.
| Concatenate a list of 'Alignment's horizontally. See
'concat'.
Only keep columns from alignment that satisfy given predicate.
| Only keep constant columns.
character as well as any number of gaps or unknowns.
characters are removed.
| Filter columns with proportion of standard character larger than given number.
| Only keep columns without gaps or unknown characters.
| Frequency data; do not store the actual characters, but their frequencies.
the number of characters.
| Calculcate frequency of characters at each site of a multi sequence alignment.
| Calculate the distribution of characters.
Parallel map with given chunk size.
| Diversity analysis. See 'kEffEntropy'.
| Diversity analysis. See 'kEffEntropy'.
alignment.
| Count the number of gaps in the alignment.
| Count the number of unknown characters in the alignment.
Sample the given sites from a matrix.
| Sample the given sites from a multi sequence alignment.
| Randomly sample a given number of sites of the multi sequence alignment.
|
Copyright : 2021
License : GPL-3.0 - or - later
Creation date : Thu Oct 4 18:40:18 2018 .
module ELynx.Sequence.Alignment
( Alignment (..),
length,
nSequences,
fromSequences,
toSequences,
summarize,
join,
concat,
concatAlignments,
filterColsConstant,
filterColsConstantSoft,
filterColsOnlyStd,
filterColsStd,
filterColsNoGaps,
FrequencyData,
distribution,
toFrequencyData,
kEffEntropy,
kEffHomoplasy,
countIUPACChars,
countGaps,
countUnknowns,
subSample,
randomSubSample,
)
where
import Control.Monad hiding (join)
import Control.Parallel.Strategies
import qualified Data.ByteString.Lazy.Char8 as BL
import Data.List hiding
( concat,
length,
)
import qualified Data.Matrix.Unboxed as M
import qualified Data.Vector.Unboxed as V
import qualified ELynx.Alphabet.Alphabet as A
import ELynx.Alphabet.Character
import qualified ELynx.Alphabet.DistributionDiversity as D
import ELynx.Sequence.Defaults
import qualified ELynx.Sequence.Sequence as S
import System.Random.Stateful
import Prelude hiding
( concat,
length,
)
data Alignment = Alignment
{ names :: [S.Name],
descriptions :: [S.Description],
alphabet :: A.Alphabet,
matrix :: M.Matrix Character
}
deriving (Show, Eq)
length :: Alignment -> Int
length = M.cols . matrix
nSequences :: Alignment -> Int
nSequences = M.rows . matrix
| Create ' Alignment ' from a list of ' S.Sequence 's .
fromSequences :: [S.Sequence] -> Either String Alignment
fromSequences ss
| S.equalLength ss && allEqual (map S.alphabet ss) =
Right $
Alignment ns ds a d
| S.equalLength ss = Left "Sequences do not have equal codes."
| otherwise = Left "Sequences do not have equal lengths."
where
ns = map S.name ss
ds = map S.description ss
a = S.alphabet $ head ss
bss = map S.characters ss
d = M.fromRows bss
allEqual [] = True
allEqual xs = all (== head xs) $ tail xs
| Conversion to list of ' S.Sequence 's .
toSequences :: Alignment -> [S.Sequence]
toSequences (Alignment ns ds a da) =
zipWith3
(\n d r -> S.Sequence n d a r)
ns
ds
rows
where
rows = M.toRows da
header :: Alignment -> BL.ByteString
header a =
BL.unlines $
[ BL.pack "Multi sequence alignment.",
BL.pack $ "Code: " ++ A.alphabetDescription (alphabet a) ++ ".",
BL.pack $ "Length: " ++ show (length a) ++ "."
]
++ reportLengthSummary
++ reportNumberSummary
where
reportLengthSummary =
[ BL.pack $
"For each sequence, the "
++ show summaryLength
++ " first bases are shown."
| length a > summaryLength
]
reportNumberSummary =
[ BL.pack $
show summaryNSequences
++ " out of "
++ show (nSequences a)
++ " sequences are shown."
| nSequences a > summaryNSequences
]
summarize :: Alignment -> BL.ByteString
summarize a = header a <> S.body (toSequences a)
(===) :: V.Unbox a => M.Matrix a -> M.Matrix a -> M.Matrix a
(===) l r = M.fromRows $ lRs ++ rRs
where
lRs = M.toRows l
rRs = M.toRows r
Horizontal concatenation .
(|||) :: V.Unbox a => M.Matrix a -> M.Matrix a -> M.Matrix a
(|||) l r = M.fromColumns $ lCs ++ rCs
where
lCs = M.toColumns l
rCs = M.toColumns r
| Join two ' Alignment 's vertically . That is , add more sequences
join :: Alignment -> Alignment -> Alignment
join t b
| length t /= length b =
error
"join: Multi sequence alignments do not have equal lengths."
| alphabet t /= alphabet b =
error
"join: Multi sequence alignments do not have equal alphabets."
| otherwise = Alignment ns ds al (tD === bD)
where
ns = names t ++ names b
ds = descriptions t ++ descriptions b
tD = matrix t
bD = matrix b
al = alphabet t
| Concatenate two ' Alignment 's horizontally . That is , add more
concat :: Alignment -> Alignment -> Alignment
concat l r
| nSequences l /= nSequences r =
error
"concat: Multi sequence alignments do not have an equal number of sequences."
| alphabet l /= alphabet r =
error "concat: Multi sequence alignments do not have an equal alphabets."
| names l /= names r =
error "concat: Multi sequence alignments do not have an equal names."
| descriptions l /= descriptions r =
error "concat: Multi sequence alignments do not have an equal descriptions."
| otherwise =
Alignment (names l) (descriptions l) (alphabet l) (lD ||| rD)
where
lD = matrix l
rD = matrix r
concatAlignments :: [Alignment] -> Alignment
concatAlignments [] = error "concatAlignments: Nothing to concatenate."
concatAlignments [a] = a
concatAlignments as = foldl' concat (head as) (tail as)
filterColsWith :: (V.Vector Character -> Bool) -> Alignment -> Alignment
filterColsWith p a = a {matrix = m'}
where
m' = M.fromColumns . filter p . M.toColumns $ matrix a
filterColsConstant :: Alignment -> Alignment
filterColsConstant = filterColsWith (\v -> V.all (== V.head v) v)
| Only keep constant columns , and constant columns with at least one standard
filterColsConstantSoft :: Alignment -> Alignment
filterColsConstantSoft a = filterColsWith f a
where
al = alphabet a
f v = case V.find (A.isStd al) v of
Nothing -> False
Just c -> V.all (\x -> x == c || A.isGap al x || A.isUnknown al x) v
| Only keep columns with standard characters . Alignment columns with IUPAC
filterColsOnlyStd :: Alignment -> Alignment
filterColsOnlyStd a = filterColsWith (V.all $ A.isStd (alphabet a)) a
filterColsStd :: Double -> Alignment -> Alignment
filterColsStd prop a =
filterColsWith
(\col -> prop * n <= fromIntegral (V.length (V.filter (A.isStd al) col)))
a
where
al = alphabet a
n = fromIntegral $ nSequences a
filterColsNoGaps :: Alignment -> Alignment
filterColsNoGaps a = filterColsWith (V.all $ not . A.isGap (alphabet a)) a
The matrix is of size @N x K@ , where @N@ is the number of sites , and @K@ is
type FrequencyData = M.Matrix Double
Map a function on each column of a DIM2 array ; parallel version with given chunk size .
fMapColParChunk ::
(V.Unbox a, V.Unbox b) =>
Int ->
(V.Vector a -> V.Vector b) ->
M.Matrix a ->
M.Matrix b
fMapColParChunk n f m =
M.fromColumns (map f (M.toColumns m) `using` parListChunk n rseq)
toFrequencyData :: Alignment -> FrequencyData
toFrequencyData a = fMapColParChunk 100 (D.frequencyCharacters spec) (matrix a)
where
spec = A.alphabetSpec (alphabet a)
distribution :: FrequencyData -> [Double]
distribution fd =
map (/ fromIntegral nSites) $
V.toList $
foldl1
(V.zipWith (+))
(M.toColumns fd)
where
nSites = M.cols fd
parMapChunk :: Int -> (a -> b) -> [a] -> [b]
parMapChunk n f as = map f as `using` parListChunk n rseq
chunksize :: Int
chunksize = 500
kEffEntropy :: FrequencyData -> [Double]
kEffEntropy fd = parMapChunk chunksize D.kEffEntropy (M.toColumns fd)
kEffHomoplasy :: FrequencyData -> [Double]
kEffHomoplasy fd = parMapChunk chunksize D.kEffHomoplasy (M.toColumns fd)
| Count the number of standard ( i.e. , not extended IUPAC ) characters in the
countIUPACChars :: Alignment -> Int
countIUPACChars a = V.length . V.filter (A.isIUPAC (alphabet a)) $ allChars
where
allChars = M.flatten $ matrix a
countGaps :: Alignment -> Int
countGaps a = V.length . V.filter (A.isGap (alphabet a)) $ allChars
where
allChars = M.flatten $ matrix a
countUnknowns :: Alignment -> Int
countUnknowns a = V.length . V.filter (A.isUnknown (alphabet a)) $ allChars
where
allChars = M.flatten $ matrix a
subSampleMatrix :: V.Unbox a => [Int] -> M.Matrix a -> M.Matrix a
subSampleMatrix is m =
M.fromColumns $ foldl' (\a i -> M.takeColumn m i : a) [] (reverse is)
subSample :: [Int] -> Alignment -> Alignment
subSample is a = a {matrix = m'} where m' = subSampleMatrix is $ matrix a
randomSubSample :: StatefulGen g m => Int -> Alignment -> g -> m Alignment
randomSubSample n a g = do
let l = length a
is <- replicateM n $ uniformRM (0, l - 1) g
return $ subSample is a
|
9a8d5e15f95e2fbb7eafd61b902aba429a5d7aef630f1df61f4ac3bc011a742a
|
okuoku/nausicaa
|
control.sps
|
Copyright ( c ) 2008
;;;
;;;This library is free software; you can redistribute it and/or modify
it under the terms of the GNU Library General Public License as
published by the Free Software Foundation ; either version 2 of the
;;;License, or (at your option) any later version.
;;;
;;;This library is distributed in the hope that it will be useful, but
;;;WITHOUT ANY WARRANTY; without even the implied warranty of
;;;MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details .
;;;
You should have received a copy of the GNU Library General Public
License along with this library ; if not , write to the Free Software
Foundation , Inc. , 51 Franklin Street , Fifth Floor , Boston , MA
02110 - 1301 USA .
#!r6rs
(import (tests r6rs control)
(tests r6rs test)
(rnrs io simple))
(display "Running tests for (rnrs control)\n")
(run-control-tests)
(report-test-results)
| null |
https://raw.githubusercontent.com/okuoku/nausicaa/50e7b4d4141ad4d81051588608677223fe9fb715/scheme/tests/r6rs/run/control.sps
|
scheme
|
This library is free software; you can redistribute it and/or modify
either version 2 of the
License, or (at your option) any later version.
This library is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
if not , write to the Free Software
|
Copyright ( c ) 2008
it under the terms of the GNU Library General Public License as
Library General Public License for more details .
You should have received a copy of the GNU Library General Public
Foundation , Inc. , 51 Franklin Street , Fifth Floor , Boston , MA
02110 - 1301 USA .
#!r6rs
(import (tests r6rs control)
(tests r6rs test)
(rnrs io simple))
(display "Running tests for (rnrs control)\n")
(run-control-tests)
(report-test-results)
|
5133241a06c990dd423b153545c41b04bda662b2e95bc5ebfbebde082e79fadd
|
tautologico/progfun
|
aula4.rkt
|
#lang racket
;; numeros naturais
;;
;; um numero natural pode ser:
;; - zero
- o um numero natural
;;
( soma n ) retorna a soma dos numeros 1 + 2 + ... + n
(define (soma n)
(if (zero? n)
0
(+ n (soma (sub1 n)))))
;; listas
;;
uma lista pode ser :
;; - a lista vazia '()
- ( cons x lst ) onde lst é uma lista
;;
exemplo : ( cons 1 ( cons 2 ( cons 3 ' ( ) ) ) )
;; '(1 2 3)
;; (list 1 2 3)
( tamanho lst ) retorna o numero na lista lst
(define (tamanho lst)
(cond [(empty? lst) 0]
[else (add1 (tamanho (rest lst)))]))
( remove - primeiro x lst ) retorna uma lista igual a lst
mas sem a do elemento x ( se houver )
(define (remove-primeiro x lst)
(cond [(empty? lst) '()]
[(equal? x (first lst)) (rest lst)]
[else (cons (first lst) (remove-primeiro x (rest lst)))]))
(define (remove-todos x lst)
(cond [(empty? lst) '()]
[(equal? x (first lst)) (remove-todos x (rest lst))]
[else (cons (first lst) (remove-todos x (rest lst)))]))
( remove - duplicatas lst ) retorna uma lista igual a lst
mas com elemento de lst
(define (remove-duplicatas lst)
(cond [(empty? lst) '()]
[(cons (first lst) (remove-todos (first lst)
(remove-duplicatas (rest lst))))]))
( combine l1 l2 ) com o primeiro do
par tirado de l1 e o segundo de l2
(define (combine l1 l2)
(cond [(empty? l1) '()]
[(empty? l2) '()]
[else (cons (list (first l1) (first l2))
(combine (rest l1) (rest l2)))]))
| null |
https://raw.githubusercontent.com/tautologico/progfun/0e8b2985e48445d289fa96f27c2485710c356709/codigo/aula4.rkt
|
racket
|
numeros naturais
um numero natural pode ser:
- zero
listas
- a lista vazia '()
'(1 2 3)
(list 1 2 3)
|
#lang racket
- o um numero natural
( soma n ) retorna a soma dos numeros 1 + 2 + ... + n
(define (soma n)
(if (zero? n)
0
(+ n (soma (sub1 n)))))
uma lista pode ser :
- ( cons x lst ) onde lst é uma lista
exemplo : ( cons 1 ( cons 2 ( cons 3 ' ( ) ) ) )
( tamanho lst ) retorna o numero na lista lst
(define (tamanho lst)
(cond [(empty? lst) 0]
[else (add1 (tamanho (rest lst)))]))
( remove - primeiro x lst ) retorna uma lista igual a lst
mas sem a do elemento x ( se houver )
(define (remove-primeiro x lst)
(cond [(empty? lst) '()]
[(equal? x (first lst)) (rest lst)]
[else (cons (first lst) (remove-primeiro x (rest lst)))]))
(define (remove-todos x lst)
(cond [(empty? lst) '()]
[(equal? x (first lst)) (remove-todos x (rest lst))]
[else (cons (first lst) (remove-todos x (rest lst)))]))
( remove - duplicatas lst ) retorna uma lista igual a lst
mas com elemento de lst
(define (remove-duplicatas lst)
(cond [(empty? lst) '()]
[(cons (first lst) (remove-todos (first lst)
(remove-duplicatas (rest lst))))]))
( combine l1 l2 ) com o primeiro do
par tirado de l1 e o segundo de l2
(define (combine l1 l2)
(cond [(empty? l1) '()]
[(empty? l2) '()]
[else (cons (list (first l1) (first l2))
(combine (rest l1) (rest l2)))]))
|
6e8d2f730b2f28ffda2b848f24047780c430e09ddb4e475865362af8b4682737
|
raptazure/experiments
|
Lib.hs
|
module Lib where
import Control.Monad.Reader
import Control.Monad.Writer
class where
-- return :: a -> m a
-- (>>=) :: m a -> (a -> m b) -> m b
( > > ) : : = > m a - > m b - > m b
-- m >> k = m >>= \_ -> k
| Maybe
instance Maybe where
-- (Just x) >>= k = k x
-- Nothing >>= k = Nothing
-- return = Just
maybeExample1 :: Maybe Int
maybeExample1 = do
a <- Just 3
b <- Just 4
return $ a + b
maybeDesugared1 :: Maybe Int
maybeDesugared1 = Just 3 >>= \a -> Just 4 >>= \b -> return $ a + b
-- | List Monad
instance [ ] where
-- m >>= f = concat (map f m)
-- return x = [x]
-- a = [f x y | x <- xs, y <- ys, x == y]
-- b = do
-- x <- xs
-- y <- ys
-- guard $ x == y
return $ f x y
listExample :: [(Int, Int, Int)]
listExample = do
a <- [1, 2]
b <- [10, 20]
c <- [100, 200]
return (a, b, c)
listDesugared :: [(Int, Int, Int)]
listDesugared =
[1, 2] >>= \a ->
[10, 20] >>= \b ->
[100, 200] >>= \c ->
return (a, b, c)
| IO Monad
namer :: IO ()
namer = do
putStrLn "What is your name?"
name <- getLine
putStrLn name
-- namer' :: IO ()
-- namer' = putStrLn "What is your name:" >>=
-- \_ -> getLine >>= \name -> putStrLn name
namer' :: IO ()
namer' =
putStrLn
"What is your name?"
>> ( getLine
>>= putStrLn
)
{- what is the point -}
sequence' :: Monad m => [m a] -> m [a]
sequence' = foldr mcons (return [])
mcons :: Monad m => m t -> m [t] -> m [t]
mcons p q = do
x <- p
y <- q
return (x : y)
test1 :: Maybe [Integer]
test1 = sequence' [Just 3, Just 4]
test2 :: [[Integer]]
test2 = sequence' [[1, 2, 3], [4, 5, 6]]
test3 :: IO [String]
test3 = sequence' [getLine, getLine, getLine]
{- Reader Monad -}
-- newtype Reader r a = Reader {runReader :: r -> a}
instance ( Reader r ) where
-- return a = Reader $ \_ -> a
-- m >>= k = Reader $ \r -> runReader (k (runReader m r)) r
-- ask :: Reader a a
-- ask = Reader id
-- asks :: (r -> a) -> Reader r a
-- asks f = Reader f
-- local :: (r -> r) -> Reader r a -> Reader r a
-- local f m = Reader $ runReader m . f
data MyContext = MyContext
{ foo :: String,
bar :: Int
}
deriving (Show)
computation :: Reader MyContext (Maybe String)
computation = do
n <- asks bar
x <- asks foo
if n > 0
then return (Just x)
else return Nothing
ex1 :: Maybe String
ex1 = runReader computation $ MyContext "hello" 0
ex2 :: Maybe String
ex2 = runReader computation $ MyContext "haskell" 1
newtype Writer w a = Writer { : : ( a , w ) }
-- instance Monoid w => Monad (Writer w) where
return a = Writer ( a , mempty )
-- m >>= k =
-- Writer $
let ( a , w ) =
( b , w ' ) = ( k a )
-- in (b, w `mappend` w')
-- execWriter :: Writer w a -> w
execWriter m = snd ( )
-- tell :: w -> Writer w ()
-- tell w = Writer ((), w)
type MyWriter = Writer [Int] String
writerExample :: MyWriter
writerExample = do
tell [1 .. 3]
tell [3 .. 5]
return "foo"
output :: (String, [Int])
output = runWriter writerExample
State Monad
newtype State s a = State { runState : : s - > ( a , s ) }
instance ( State s ) where
-- return a = State $ \s -> (a, s)
State act > > = k = State $ \s - >
-- let (a, s') = act s
in runState ( k a ) s '
-- get :: State a a
-- get = State $ \s -> (s, s)
put : : p - > State s ( )
-- put s = State $ \s -> ((), s)
modify : : ( s - > s ) - > State s ( )
-- modify f = get >>= \x -> put (f x)
-- evalState :: State b c -> b -> c
-- evalState act = fst . runState act
-- execState :: State c a -> c -> c
execState act = snd . runState act
| null |
https://raw.githubusercontent.com/raptazure/experiments/c48263980d1ce22ee9407ff8dcf0cf5091b01c70/haskell/wiwinwlh/monads/src/Lib.hs
|
haskell
|
return :: a -> m a
(>>=) :: m a -> (a -> m b) -> m b
m >> k = m >>= \_ -> k
(Just x) >>= k = k x
Nothing >>= k = Nothing
return = Just
| List Monad
m >>= f = concat (map f m)
return x = [x]
a = [f x y | x <- xs, y <- ys, x == y]
b = do
x <- xs
y <- ys
guard $ x == y
namer' :: IO ()
namer' = putStrLn "What is your name:" >>=
\_ -> getLine >>= \name -> putStrLn name
what is the point
Reader Monad
newtype Reader r a = Reader {runReader :: r -> a}
return a = Reader $ \_ -> a
m >>= k = Reader $ \r -> runReader (k (runReader m r)) r
ask :: Reader a a
ask = Reader id
asks :: (r -> a) -> Reader r a
asks f = Reader f
local :: (r -> r) -> Reader r a -> Reader r a
local f m = Reader $ runReader m . f
instance Monoid w => Monad (Writer w) where
m >>= k =
Writer $
in (b, w `mappend` w')
execWriter :: Writer w a -> w
tell :: w -> Writer w ()
tell w = Writer ((), w)
return a = State $ \s -> (a, s)
let (a, s') = act s
get :: State a a
get = State $ \s -> (s, s)
put s = State $ \s -> ((), s)
modify f = get >>= \x -> put (f x)
evalState :: State b c -> b -> c
evalState act = fst . runState act
execState :: State c a -> c -> c
|
module Lib where
import Control.Monad.Reader
import Control.Monad.Writer
class where
( > > ) : : = > m a - > m b - > m b
| Maybe
instance Maybe where
maybeExample1 :: Maybe Int
maybeExample1 = do
a <- Just 3
b <- Just 4
return $ a + b
maybeDesugared1 :: Maybe Int
maybeDesugared1 = Just 3 >>= \a -> Just 4 >>= \b -> return $ a + b
instance [ ] where
return $ f x y
listExample :: [(Int, Int, Int)]
listExample = do
a <- [1, 2]
b <- [10, 20]
c <- [100, 200]
return (a, b, c)
listDesugared :: [(Int, Int, Int)]
listDesugared =
[1, 2] >>= \a ->
[10, 20] >>= \b ->
[100, 200] >>= \c ->
return (a, b, c)
| IO Monad
namer :: IO ()
namer = do
putStrLn "What is your name?"
name <- getLine
putStrLn name
namer' :: IO ()
namer' =
putStrLn
"What is your name?"
>> ( getLine
>>= putStrLn
)
sequence' :: Monad m => [m a] -> m [a]
sequence' = foldr mcons (return [])
mcons :: Monad m => m t -> m [t] -> m [t]
mcons p q = do
x <- p
y <- q
return (x : y)
test1 :: Maybe [Integer]
test1 = sequence' [Just 3, Just 4]
test2 :: [[Integer]]
test2 = sequence' [[1, 2, 3], [4, 5, 6]]
test3 :: IO [String]
test3 = sequence' [getLine, getLine, getLine]
instance ( Reader r ) where
data MyContext = MyContext
{ foo :: String,
bar :: Int
}
deriving (Show)
computation :: Reader MyContext (Maybe String)
computation = do
n <- asks bar
x <- asks foo
if n > 0
then return (Just x)
else return Nothing
ex1 :: Maybe String
ex1 = runReader computation $ MyContext "hello" 0
ex2 :: Maybe String
ex2 = runReader computation $ MyContext "haskell" 1
newtype Writer w a = Writer { : : ( a , w ) }
return a = Writer ( a , mempty )
let ( a , w ) =
( b , w ' ) = ( k a )
execWriter m = snd ( )
type MyWriter = Writer [Int] String
writerExample :: MyWriter
writerExample = do
tell [1 .. 3]
tell [3 .. 5]
return "foo"
output :: (String, [Int])
output = runWriter writerExample
State Monad
newtype State s a = State { runState : : s - > ( a , s ) }
instance ( State s ) where
State act > > = k = State $ \s - >
in runState ( k a ) s '
put : : p - > State s ( )
modify : : ( s - > s ) - > State s ( )
execState act = snd . runState act
|
bdf9f2f5c96a4ae785adde45e8c41855b152ab52cc6908017253893ca2b0848f
|
jeluard/cljc-ethereum
|
websocket.cljc
|
(ns ethereum.transports.websocket)
;; -ws
;;
;;
| null |
https://raw.githubusercontent.com/jeluard/cljc-ethereum/41fb6e1fc5cd870eca7daa690c2a19e4db08db9c/src/ethereum/transports/websocket.cljc
|
clojure
|
-ws
|
(ns ethereum.transports.websocket)
|
9a34436084e92a30a4ecaf16dfecf44b3e7ca23634ca2a23b36285aeda6c1993
|
input-output-hk/cardano-base
|
PackedBytes.hs
|
{-# LANGUAGE BangPatterns #-}
# LANGUAGE CPP #
# LANGUAGE DataKinds #
# LANGUAGE DerivingVia #
{-# LANGUAGE GADTs #-}
# LANGUAGE MagicHash #
{-# LANGUAGE RankNTypes #-}
# LANGUAGE ScopedTypeVariables #
# LANGUAGE StandaloneDeriving #
# LANGUAGE TypeApplications #
# LANGUAGE TypeFamilyDependencies #
# LANGUAGE UnboxedTuples #
module Cardano.Crypto.PackedBytes
( PackedBytes(..)
, packBytes
, packBytesMaybe
, packPinnedBytes
, unpackBytes
, unpackPinnedBytes
, xorPackedBytes
) where
import Codec.Serialise (Serialise(..))
import Codec.Serialise.Decoding (decodeBytes)
import Codec.Serialise.Encoding (encodeBytes)
import Control.DeepSeq
import Control.Monad (guard)
import Control.Monad.Primitive
import Data.Bits
import Data.ByteString
import Data.ByteString.Internal as BS (accursedUnutterablePerformIO,
fromForeignPtr, toForeignPtr)
import Data.ByteString.Short.Internal as SBS
import Data.Primitive.ByteArray
import Data.Primitive.PrimArray (PrimArray(..), imapPrimArray, indexPrimArray)
import Data.Typeable
import Foreign.ForeignPtr
import Foreign.Ptr (castPtr)
import Foreign.Storable (peekByteOff)
import GHC.Exts
import GHC.ForeignPtr (ForeignPtr(ForeignPtr), ForeignPtrContents(PlainPtr))
#if MIN_VERSION_base(4,15,0)
import GHC.ForeignPtr (unsafeWithForeignPtr)
#endif
import GHC.ST
import GHC.TypeLits
import GHC.Word
import NoThunks.Class
#include "MachDeps.h"
data PackedBytes (n :: Nat) where
PackedBytes8 :: {-# UNPACK #-} !Word64
-> PackedBytes 8
PackedBytes28 :: {-# UNPACK #-} !Word64
-> {-# UNPACK #-} !Word64
-> {-# UNPACK #-} !Word64
-> {-# UNPACK #-} !Word32
-> PackedBytes 28
PackedBytes32 :: {-# UNPACK #-} !Word64
-> {-# UNPACK #-} !Word64
-> {-# UNPACK #-} !Word64
-> {-# UNPACK #-} !Word64
-> PackedBytes 32
PackedBytes# :: ByteArray# -> PackedBytes n
deriving via OnlyCheckWhnfNamed "PackedBytes" (PackedBytes n) instance NoThunks (PackedBytes n)
instance Eq (PackedBytes n) where
PackedBytes8 x == PackedBytes8 y = x == y
PackedBytes28 x0 x1 x2 x3 == PackedBytes28 y0 y1 y2 y3 =
x0 == y0 && x1 == y1 && x2 == y2 && x3 == y3
PackedBytes32 x0 x1 x2 x3 == PackedBytes32 y0 y1 y2 y3 =
x0 == y0 && x1 == y1 && x2 == y2 && x3 == y3
x1 == x2 = unpackBytes x1 == unpackBytes x2
# INLINE (= =) #
instance Ord (PackedBytes n) where
compare (PackedBytes8 x) (PackedBytes8 y) = compare x y
compare (PackedBytes28 x0 x1 x2 x3) (PackedBytes28 y0 y1 y2 y3) =
compare x0 y0 <> compare x1 y1 <> compare x2 y2 <> compare x3 y3
compare (PackedBytes32 x0 x1 x2 x3) (PackedBytes32 y0 y1 y2 y3) =
compare x0 y0 <> compare x1 y1 <> compare x2 y2 <> compare x3 y3
compare x1 x2 = compare (unpackBytes x1) (unpackBytes x2)
# INLINE compare #
instance NFData (PackedBytes n) where
rnf PackedBytes8 {} = ()
rnf PackedBytes28 {} = ()
rnf PackedBytes32 {} = ()
rnf PackedBytes# {} = ()
instance Serialise (PackedBytes n) where
encode = encodeBytes . unpackPinnedBytes
decode = packPinnedBytesN <$> decodeBytes
xorPackedBytes :: PackedBytes n -> PackedBytes n -> PackedBytes n
xorPackedBytes (PackedBytes8 x) (PackedBytes8 y) = PackedBytes8 (x `xor` y)
xorPackedBytes (PackedBytes28 x0 x1 x2 x3) (PackedBytes28 y0 y1 y2 y3) =
PackedBytes28 (x0 `xor` y0) (x1 `xor` y1) (x2 `xor` y2) (x3 `xor` y3)
xorPackedBytes (PackedBytes32 x0 x1 x2 x3) (PackedBytes32 y0 y1 y2 y3) =
PackedBytes32 (x0 `xor` y0) (x1 `xor` y1) (x2 `xor` y2) (x3 `xor` y3)
xorPackedBytes (PackedBytes# ba1#) (PackedBytes# ba2#) =
let pa1 = PrimArray ba1# :: PrimArray Word8
pa2 = PrimArray ba2# :: PrimArray Word8
in case imapPrimArray (xor . indexPrimArray pa1) pa2 of
PrimArray pa# -> PackedBytes# pa#
xorPackedBytes _ _ =
error "Impossible case. GHC can't figure out that pattern match is exhaustive."
{-# INLINE xorPackedBytes #-}
withMutableByteArray :: Int -> (forall s . MutableByteArray s -> ST s ()) -> ByteArray
withMutableByteArray n f = do
runST $ do
mba <- newByteArray n
f mba
unsafeFreezeByteArray mba
# INLINE withMutableByteArray #
withPinnedMutableByteArray :: Int -> (forall s . MutableByteArray s -> ST s ()) -> ByteArray
withPinnedMutableByteArray n f = do
runST $ do
mba <- newPinnedByteArray n
f mba
unsafeFreezeByteArray mba
# INLINE withPinnedMutableByteArray #
unpackBytes :: PackedBytes n -> ShortByteString
unpackBytes = byteArrayToShortByteString . unpackBytesWith withMutableByteArray
{-# INLINE unpackBytes #-}
unpackPinnedBytes :: PackedBytes n -> ByteString
unpackPinnedBytes = byteArrayToByteString . unpackBytesWith withPinnedMutableByteArray
# INLINE unpackPinnedBytes #
unpackBytesWith ::
(Int -> (forall s. MutableByteArray s -> ST s ()) -> ByteArray)
-> PackedBytes n
-> ByteArray
unpackBytesWith allocate (PackedBytes8 w) =
allocate 8 $ \mba -> writeWord64BE mba 0 w
unpackBytesWith allocate (PackedBytes28 w0 w1 w2 w3) =
allocate 28 $ \mba -> do
writeWord64BE mba 0 w0
writeWord64BE mba 8 w1
writeWord64BE mba 16 w2
writeWord32BE mba 24 w3
unpackBytesWith allocate (PackedBytes32 w0 w1 w2 w3) =
allocate 32 $ \mba -> do
writeWord64BE mba 0 w0
writeWord64BE mba 8 w1
writeWord64BE mba 16 w2
writeWord64BE mba 24 w3
unpackBytesWith _ (PackedBytes# ba#) = ByteArray ba#
# INLINE unpackBytesWith #
packBytes8 :: ShortByteString -> Int -> PackedBytes 8
packBytes8 (SBS ba#) offset =
let ba = ByteArray ba#
in PackedBytes8 (indexWord64BE ba offset)
# INLINE packBytes8 #
packBytes28 :: ShortByteString -> Int -> PackedBytes 28
packBytes28 (SBS ba#) offset =
let ba = ByteArray ba#
in PackedBytes28
(indexWord64BE ba offset)
(indexWord64BE ba (offset + 8))
(indexWord64BE ba (offset + 16))
(indexWord32BE ba (offset + 24))
{-# INLINE packBytes28 #-}
packBytes32 :: ShortByteString -> Int -> PackedBytes 32
packBytes32 (SBS ba#) offset =
let ba = ByteArray ba#
in PackedBytes32
(indexWord64BE ba offset)
(indexWord64BE ba (offset + 8))
(indexWord64BE ba (offset + 16))
(indexWord64BE ba (offset + 24))
# INLINE packBytes32 #
packBytes :: forall n . KnownNat n => ShortByteString -> Int -> PackedBytes n
packBytes sbs@(SBS ba#) offset =
let px = Proxy :: Proxy n
n = fromInteger (natVal px)
ba = ByteArray ba#
in case sameNat px (Proxy :: Proxy 8) of
Just Refl -> packBytes8 sbs offset
Nothing -> case sameNat px (Proxy :: Proxy 28) of
Just Refl -> packBytes28 sbs offset
Nothing -> case sameNat px (Proxy :: Proxy 32) of
Just Refl -> packBytes32 sbs offset
Nothing
| offset == 0
, sizeofByteArray ba == n -> PackedBytes# ba#
Nothing ->
let !(ByteArray slice#) = cloneByteArray ba offset n
in PackedBytes# slice#
{-# INLINE[1] packBytes #-}
# RULES
" packBytes8 " packBytes = packBytes8
" packBytes28 " packBytes = packBytes28
" packBytes32 " packBytes = packBytes32
#
"packBytes8" packBytes = packBytes8
"packBytes28" packBytes = packBytes28
"packBytes32" packBytes = packBytes32
#-}
-- | Construct `PackedBytes` from a `ShortByteString` and a non-negative offset
-- in number of bytes from the beginning. This function is safe.
packBytesMaybe :: forall n . KnownNat n => ShortByteString -> Int -> Maybe (PackedBytes n)
packBytesMaybe bs offset = do
let bufferSize = SBS.length bs
size = fromInteger (natVal' (proxy# @n))
guard (offset >= 0)
guard (size <= bufferSize - offset)
Just $ packBytes bs offset
packPinnedBytes8 :: ByteString -> PackedBytes 8
packPinnedBytes8 bs = unsafeWithByteStringPtr bs (fmap PackedBytes8 . (`peekWord64BE` 0))
# INLINE packPinnedBytes8 #
packPinnedBytes28 :: ByteString -> PackedBytes 28
packPinnedBytes28 bs =
unsafeWithByteStringPtr bs $ \ptr ->
PackedBytes28
<$> peekWord64BE ptr 0
<*> peekWord64BE ptr 8
<*> peekWord64BE ptr 16
<*> peekWord32BE ptr 24
{-# INLINE packPinnedBytes28 #-}
packPinnedBytes32 :: ByteString -> PackedBytes 32
packPinnedBytes32 bs =
unsafeWithByteStringPtr bs $ \ptr -> PackedBytes32 <$> peekWord64BE ptr 0
<*> peekWord64BE ptr 8
<*> peekWord64BE ptr 16
<*> peekWord64BE ptr 24
# INLINE packPinnedBytes32 #
packPinnedBytesN :: ByteString -> PackedBytes n
packPinnedBytesN bs =
case toShort bs of
SBS ba# -> PackedBytes# ba#
# INLINE packPinnedBytesN #
packPinnedBytes :: forall n . KnownNat n => ByteString -> PackedBytes n
packPinnedBytes bs =
let px = Proxy :: Proxy n
in case sameNat px (Proxy :: Proxy 8) of
Just Refl -> packPinnedBytes8 bs
Nothing -> case sameNat px (Proxy :: Proxy 28) of
Just Refl -> packPinnedBytes28 bs
Nothing -> case sameNat px (Proxy :: Proxy 32) of
Just Refl -> packPinnedBytes32 bs
Nothing -> packPinnedBytesN bs
# INLINE[1 ] packPinnedBytes #
{-# RULES
"packPinnedBytes8" packPinnedBytes = packPinnedBytes8
"packPinnedBytes28" packPinnedBytes = packPinnedBytes28
"packPinnedBytes32" packPinnedBytes = packPinnedBytes32
#-}
--- Primitive architecture agnostic helpers
#if WORD_SIZE_IN_BITS == 64
indexWord64BE :: ByteArray -> Int -> Word64
indexWord64BE (ByteArray ba#) (I# i#) =
#ifdef WORDS_BIGENDIAN
W64# (indexWord8ArrayAsWord64# ba# i#)
#else
W64# (byteSwap64# (indexWord8ArrayAsWord64# ba# i#))
#endif
# INLINE indexWord64BE #
peekWord64BE :: Ptr a -> Int -> IO Word64
peekWord64BE ptr i =
#ifndef WORDS_BIGENDIAN
byteSwap64 <$>
#endif
peekByteOff (castPtr ptr) i
# INLINE peekWord64BE #
writeWord64BE :: MutableByteArray s -> Int -> Word64 -> ST s ()
writeWord64BE (MutableByteArray mba#) (I# i#) (W64# w#) =
primitive_ (writeWord8ArrayAsWord64# mba# i# wbe#)
where
#ifdef WORDS_BIGENDIAN
!wbe# = w#
#else
!wbe# = byteSwap64# w#
#endif
{-# INLINE writeWord64BE #-}
#elif WORD_SIZE_IN_BITS == 32
indexWord64BE :: ByteArray -> Int -> Word64
indexWord64BE ba i =
(fromIntegral (indexWord32BE ba i) `shiftL` 32) .|. fromIntegral (indexWord32BE ba (i + 4))
# INLINE indexWord64BE #
peekWord64BE :: Ptr a -> Int -> IO Word64
peekWord64BE ptr i = do
u <- peekWord32BE ptr i
l <- peekWord32BE ptr (i + 4)
pure ((fromIntegral u `shiftL` 32) .|. fromIntegral l)
# INLINE peekWord64BE #
writeWord64BE :: MutableByteArray s -> Int -> Word64 -> ST s ()
writeWord64BE mba i w64 = do
writeWord32BE mba i (fromIntegral (w64 `shiftR` 32))
writeWord32BE mba (i + 4) (fromIntegral w64)
{-# INLINE writeWord64BE #-}
#else
#error "Unsupported architecture"
#endif
indexWord32BE :: ByteArray -> Int -> Word32
indexWord32BE (ByteArray ba#) (I# i#) =
#ifdef WORDS_BIGENDIAN
w32
#else
byteSwap32 w32
#endif
where
w32 = W32# (indexWord8ArrayAsWord32# ba# i#)
# INLINE indexWord32BE #
peekWord32BE :: Ptr a -> Int -> IO Word32
peekWord32BE ptr i =
#ifndef WORDS_BIGENDIAN
byteSwap32 <$>
#endif
peekByteOff (castPtr ptr) i
# INLINE peekWord32BE #
writeWord32BE :: MutableByteArray s -> Int -> Word32 -> ST s ()
writeWord32BE (MutableByteArray mba#) (I# i#) w =
primitive_ (writeWord8ArrayAsWord32# mba# i# w#)
where
#ifdef WORDS_BIGENDIAN
!(W32# w#) = w
#else
!(W32# w#) = byteSwap32 w
#endif
# INLINE writeWord32BE #
byteArrayToShortByteString :: ByteArray -> ShortByteString
byteArrayToShortByteString (ByteArray ba#) = SBS ba#
# INLINE byteArrayToShortByteString #
byteArrayToByteString :: ByteArray -> ByteString
byteArrayToByteString ba
| isByteArrayPinned ba =
BS.fromForeignPtr (pinnedByteArrayToForeignPtr ba) 0 (sizeofByteArray ba)
| otherwise = SBS.fromShort (byteArrayToShortByteString ba)
# INLINE byteArrayToByteString #
pinnedByteArrayToForeignPtr :: ByteArray -> ForeignPtr a
pinnedByteArrayToForeignPtr (ByteArray ba#) =
ForeignPtr (byteArrayContents# ba#) (PlainPtr (unsafeCoerce# ba#))
# INLINE pinnedByteArrayToForeignPtr #
-- Usage of `accursedUnutterablePerformIO` here is safe because we only use it
for indexing into an immutable ` ByteString ` , which is analogous to
-- `Data.ByteString.index`. Make sure you know what you are doing before using
-- this function.
unsafeWithByteStringPtr :: ByteString -> (Ptr b -> IO a) -> a
unsafeWithByteStringPtr bs f =
accursedUnutterablePerformIO $
case toForeignPtr bs of
(fp, offset, _) ->
unsafeWithForeignPtr (plusForeignPtr fp offset) f
# INLINE unsafeWithByteStringPtr #
#if !MIN_VERSION_base(4,15,0)
-- | A compatibility wrapper for 'GHC.ForeignPtr.unsafeWithForeignPtr' provided
by GHC 9.0.1 and later .
unsafeWithForeignPtr :: ForeignPtr a -> (Ptr a -> IO b) -> IO b
unsafeWithForeignPtr = withForeignPtr
# INLINE unsafeWithForeignPtr #
#endif
| null |
https://raw.githubusercontent.com/input-output-hk/cardano-base/7e3ddba98a61900181fe63cdd4c9ed9708d1a6a7/cardano-crypto-class/src/Cardano/Crypto/PackedBytes.hs
|
haskell
|
# LANGUAGE BangPatterns #
# LANGUAGE GADTs #
# LANGUAGE RankNTypes #
# UNPACK #
# UNPACK #
# UNPACK #
# UNPACK #
# UNPACK #
# UNPACK #
# UNPACK #
# UNPACK #
# UNPACK #
# INLINE xorPackedBytes #
# INLINE unpackBytes #
# INLINE packBytes28 #
# INLINE[1] packBytes #
| Construct `PackedBytes` from a `ShortByteString` and a non-negative offset
in number of bytes from the beginning. This function is safe.
# INLINE packPinnedBytes28 #
# RULES
"packPinnedBytes8" packPinnedBytes = packPinnedBytes8
"packPinnedBytes28" packPinnedBytes = packPinnedBytes28
"packPinnedBytes32" packPinnedBytes = packPinnedBytes32
#
- Primitive architecture agnostic helpers
# INLINE writeWord64BE #
# INLINE writeWord64BE #
Usage of `accursedUnutterablePerformIO` here is safe because we only use it
`Data.ByteString.index`. Make sure you know what you are doing before using
this function.
| A compatibility wrapper for 'GHC.ForeignPtr.unsafeWithForeignPtr' provided
|
# LANGUAGE CPP #
# LANGUAGE DataKinds #
# LANGUAGE DerivingVia #
# LANGUAGE MagicHash #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE StandaloneDeriving #
# LANGUAGE TypeApplications #
# LANGUAGE TypeFamilyDependencies #
# LANGUAGE UnboxedTuples #
module Cardano.Crypto.PackedBytes
( PackedBytes(..)
, packBytes
, packBytesMaybe
, packPinnedBytes
, unpackBytes
, unpackPinnedBytes
, xorPackedBytes
) where
import Codec.Serialise (Serialise(..))
import Codec.Serialise.Decoding (decodeBytes)
import Codec.Serialise.Encoding (encodeBytes)
import Control.DeepSeq
import Control.Monad (guard)
import Control.Monad.Primitive
import Data.Bits
import Data.ByteString
import Data.ByteString.Internal as BS (accursedUnutterablePerformIO,
fromForeignPtr, toForeignPtr)
import Data.ByteString.Short.Internal as SBS
import Data.Primitive.ByteArray
import Data.Primitive.PrimArray (PrimArray(..), imapPrimArray, indexPrimArray)
import Data.Typeable
import Foreign.ForeignPtr
import Foreign.Ptr (castPtr)
import Foreign.Storable (peekByteOff)
import GHC.Exts
import GHC.ForeignPtr (ForeignPtr(ForeignPtr), ForeignPtrContents(PlainPtr))
#if MIN_VERSION_base(4,15,0)
import GHC.ForeignPtr (unsafeWithForeignPtr)
#endif
import GHC.ST
import GHC.TypeLits
import GHC.Word
import NoThunks.Class
#include "MachDeps.h"
data PackedBytes (n :: Nat) where
-> PackedBytes 8
-> PackedBytes 28
-> PackedBytes 32
PackedBytes# :: ByteArray# -> PackedBytes n
deriving via OnlyCheckWhnfNamed "PackedBytes" (PackedBytes n) instance NoThunks (PackedBytes n)
instance Eq (PackedBytes n) where
PackedBytes8 x == PackedBytes8 y = x == y
PackedBytes28 x0 x1 x2 x3 == PackedBytes28 y0 y1 y2 y3 =
x0 == y0 && x1 == y1 && x2 == y2 && x3 == y3
PackedBytes32 x0 x1 x2 x3 == PackedBytes32 y0 y1 y2 y3 =
x0 == y0 && x1 == y1 && x2 == y2 && x3 == y3
x1 == x2 = unpackBytes x1 == unpackBytes x2
# INLINE (= =) #
instance Ord (PackedBytes n) where
compare (PackedBytes8 x) (PackedBytes8 y) = compare x y
compare (PackedBytes28 x0 x1 x2 x3) (PackedBytes28 y0 y1 y2 y3) =
compare x0 y0 <> compare x1 y1 <> compare x2 y2 <> compare x3 y3
compare (PackedBytes32 x0 x1 x2 x3) (PackedBytes32 y0 y1 y2 y3) =
compare x0 y0 <> compare x1 y1 <> compare x2 y2 <> compare x3 y3
compare x1 x2 = compare (unpackBytes x1) (unpackBytes x2)
# INLINE compare #
instance NFData (PackedBytes n) where
rnf PackedBytes8 {} = ()
rnf PackedBytes28 {} = ()
rnf PackedBytes32 {} = ()
rnf PackedBytes# {} = ()
instance Serialise (PackedBytes n) where
encode = encodeBytes . unpackPinnedBytes
decode = packPinnedBytesN <$> decodeBytes
xorPackedBytes :: PackedBytes n -> PackedBytes n -> PackedBytes n
xorPackedBytes (PackedBytes8 x) (PackedBytes8 y) = PackedBytes8 (x `xor` y)
xorPackedBytes (PackedBytes28 x0 x1 x2 x3) (PackedBytes28 y0 y1 y2 y3) =
PackedBytes28 (x0 `xor` y0) (x1 `xor` y1) (x2 `xor` y2) (x3 `xor` y3)
xorPackedBytes (PackedBytes32 x0 x1 x2 x3) (PackedBytes32 y0 y1 y2 y3) =
PackedBytes32 (x0 `xor` y0) (x1 `xor` y1) (x2 `xor` y2) (x3 `xor` y3)
xorPackedBytes (PackedBytes# ba1#) (PackedBytes# ba2#) =
let pa1 = PrimArray ba1# :: PrimArray Word8
pa2 = PrimArray ba2# :: PrimArray Word8
in case imapPrimArray (xor . indexPrimArray pa1) pa2 of
PrimArray pa# -> PackedBytes# pa#
xorPackedBytes _ _ =
error "Impossible case. GHC can't figure out that pattern match is exhaustive."
withMutableByteArray :: Int -> (forall s . MutableByteArray s -> ST s ()) -> ByteArray
withMutableByteArray n f = do
runST $ do
mba <- newByteArray n
f mba
unsafeFreezeByteArray mba
# INLINE withMutableByteArray #
withPinnedMutableByteArray :: Int -> (forall s . MutableByteArray s -> ST s ()) -> ByteArray
withPinnedMutableByteArray n f = do
runST $ do
mba <- newPinnedByteArray n
f mba
unsafeFreezeByteArray mba
# INLINE withPinnedMutableByteArray #
unpackBytes :: PackedBytes n -> ShortByteString
unpackBytes = byteArrayToShortByteString . unpackBytesWith withMutableByteArray
unpackPinnedBytes :: PackedBytes n -> ByteString
unpackPinnedBytes = byteArrayToByteString . unpackBytesWith withPinnedMutableByteArray
# INLINE unpackPinnedBytes #
unpackBytesWith ::
(Int -> (forall s. MutableByteArray s -> ST s ()) -> ByteArray)
-> PackedBytes n
-> ByteArray
unpackBytesWith allocate (PackedBytes8 w) =
allocate 8 $ \mba -> writeWord64BE mba 0 w
unpackBytesWith allocate (PackedBytes28 w0 w1 w2 w3) =
allocate 28 $ \mba -> do
writeWord64BE mba 0 w0
writeWord64BE mba 8 w1
writeWord64BE mba 16 w2
writeWord32BE mba 24 w3
unpackBytesWith allocate (PackedBytes32 w0 w1 w2 w3) =
allocate 32 $ \mba -> do
writeWord64BE mba 0 w0
writeWord64BE mba 8 w1
writeWord64BE mba 16 w2
writeWord64BE mba 24 w3
unpackBytesWith _ (PackedBytes# ba#) = ByteArray ba#
# INLINE unpackBytesWith #
packBytes8 :: ShortByteString -> Int -> PackedBytes 8
packBytes8 (SBS ba#) offset =
let ba = ByteArray ba#
in PackedBytes8 (indexWord64BE ba offset)
# INLINE packBytes8 #
packBytes28 :: ShortByteString -> Int -> PackedBytes 28
packBytes28 (SBS ba#) offset =
let ba = ByteArray ba#
in PackedBytes28
(indexWord64BE ba offset)
(indexWord64BE ba (offset + 8))
(indexWord64BE ba (offset + 16))
(indexWord32BE ba (offset + 24))
packBytes32 :: ShortByteString -> Int -> PackedBytes 32
packBytes32 (SBS ba#) offset =
let ba = ByteArray ba#
in PackedBytes32
(indexWord64BE ba offset)
(indexWord64BE ba (offset + 8))
(indexWord64BE ba (offset + 16))
(indexWord64BE ba (offset + 24))
# INLINE packBytes32 #
packBytes :: forall n . KnownNat n => ShortByteString -> Int -> PackedBytes n
packBytes sbs@(SBS ba#) offset =
let px = Proxy :: Proxy n
n = fromInteger (natVal px)
ba = ByteArray ba#
in case sameNat px (Proxy :: Proxy 8) of
Just Refl -> packBytes8 sbs offset
Nothing -> case sameNat px (Proxy :: Proxy 28) of
Just Refl -> packBytes28 sbs offset
Nothing -> case sameNat px (Proxy :: Proxy 32) of
Just Refl -> packBytes32 sbs offset
Nothing
| offset == 0
, sizeofByteArray ba == n -> PackedBytes# ba#
Nothing ->
let !(ByteArray slice#) = cloneByteArray ba offset n
in PackedBytes# slice#
# RULES
" packBytes8 " packBytes = packBytes8
" packBytes28 " packBytes = packBytes28
" packBytes32 " packBytes = packBytes32
#
"packBytes8" packBytes = packBytes8
"packBytes28" packBytes = packBytes28
"packBytes32" packBytes = packBytes32
#-}
packBytesMaybe :: forall n . KnownNat n => ShortByteString -> Int -> Maybe (PackedBytes n)
packBytesMaybe bs offset = do
let bufferSize = SBS.length bs
size = fromInteger (natVal' (proxy# @n))
guard (offset >= 0)
guard (size <= bufferSize - offset)
Just $ packBytes bs offset
packPinnedBytes8 :: ByteString -> PackedBytes 8
packPinnedBytes8 bs = unsafeWithByteStringPtr bs (fmap PackedBytes8 . (`peekWord64BE` 0))
# INLINE packPinnedBytes8 #
packPinnedBytes28 :: ByteString -> PackedBytes 28
packPinnedBytes28 bs =
unsafeWithByteStringPtr bs $ \ptr ->
PackedBytes28
<$> peekWord64BE ptr 0
<*> peekWord64BE ptr 8
<*> peekWord64BE ptr 16
<*> peekWord32BE ptr 24
packPinnedBytes32 :: ByteString -> PackedBytes 32
packPinnedBytes32 bs =
unsafeWithByteStringPtr bs $ \ptr -> PackedBytes32 <$> peekWord64BE ptr 0
<*> peekWord64BE ptr 8
<*> peekWord64BE ptr 16
<*> peekWord64BE ptr 24
# INLINE packPinnedBytes32 #
packPinnedBytesN :: ByteString -> PackedBytes n
packPinnedBytesN bs =
case toShort bs of
SBS ba# -> PackedBytes# ba#
# INLINE packPinnedBytesN #
packPinnedBytes :: forall n . KnownNat n => ByteString -> PackedBytes n
packPinnedBytes bs =
let px = Proxy :: Proxy n
in case sameNat px (Proxy :: Proxy 8) of
Just Refl -> packPinnedBytes8 bs
Nothing -> case sameNat px (Proxy :: Proxy 28) of
Just Refl -> packPinnedBytes28 bs
Nothing -> case sameNat px (Proxy :: Proxy 32) of
Just Refl -> packPinnedBytes32 bs
Nothing -> packPinnedBytesN bs
# INLINE[1 ] packPinnedBytes #
#if WORD_SIZE_IN_BITS == 64
indexWord64BE :: ByteArray -> Int -> Word64
indexWord64BE (ByteArray ba#) (I# i#) =
#ifdef WORDS_BIGENDIAN
W64# (indexWord8ArrayAsWord64# ba# i#)
#else
W64# (byteSwap64# (indexWord8ArrayAsWord64# ba# i#))
#endif
# INLINE indexWord64BE #
peekWord64BE :: Ptr a -> Int -> IO Word64
peekWord64BE ptr i =
#ifndef WORDS_BIGENDIAN
byteSwap64 <$>
#endif
peekByteOff (castPtr ptr) i
# INLINE peekWord64BE #
writeWord64BE :: MutableByteArray s -> Int -> Word64 -> ST s ()
writeWord64BE (MutableByteArray mba#) (I# i#) (W64# w#) =
primitive_ (writeWord8ArrayAsWord64# mba# i# wbe#)
where
#ifdef WORDS_BIGENDIAN
!wbe# = w#
#else
!wbe# = byteSwap64# w#
#endif
#elif WORD_SIZE_IN_BITS == 32
indexWord64BE :: ByteArray -> Int -> Word64
indexWord64BE ba i =
(fromIntegral (indexWord32BE ba i) `shiftL` 32) .|. fromIntegral (indexWord32BE ba (i + 4))
# INLINE indexWord64BE #
peekWord64BE :: Ptr a -> Int -> IO Word64
peekWord64BE ptr i = do
u <- peekWord32BE ptr i
l <- peekWord32BE ptr (i + 4)
pure ((fromIntegral u `shiftL` 32) .|. fromIntegral l)
# INLINE peekWord64BE #
writeWord64BE :: MutableByteArray s -> Int -> Word64 -> ST s ()
writeWord64BE mba i w64 = do
writeWord32BE mba i (fromIntegral (w64 `shiftR` 32))
writeWord32BE mba (i + 4) (fromIntegral w64)
#else
#error "Unsupported architecture"
#endif
indexWord32BE :: ByteArray -> Int -> Word32
indexWord32BE (ByteArray ba#) (I# i#) =
#ifdef WORDS_BIGENDIAN
w32
#else
byteSwap32 w32
#endif
where
w32 = W32# (indexWord8ArrayAsWord32# ba# i#)
# INLINE indexWord32BE #
peekWord32BE :: Ptr a -> Int -> IO Word32
peekWord32BE ptr i =
#ifndef WORDS_BIGENDIAN
byteSwap32 <$>
#endif
peekByteOff (castPtr ptr) i
# INLINE peekWord32BE #
writeWord32BE :: MutableByteArray s -> Int -> Word32 -> ST s ()
writeWord32BE (MutableByteArray mba#) (I# i#) w =
primitive_ (writeWord8ArrayAsWord32# mba# i# w#)
where
#ifdef WORDS_BIGENDIAN
!(W32# w#) = w
#else
!(W32# w#) = byteSwap32 w
#endif
# INLINE writeWord32BE #
byteArrayToShortByteString :: ByteArray -> ShortByteString
byteArrayToShortByteString (ByteArray ba#) = SBS ba#
# INLINE byteArrayToShortByteString #
byteArrayToByteString :: ByteArray -> ByteString
byteArrayToByteString ba
| isByteArrayPinned ba =
BS.fromForeignPtr (pinnedByteArrayToForeignPtr ba) 0 (sizeofByteArray ba)
| otherwise = SBS.fromShort (byteArrayToShortByteString ba)
# INLINE byteArrayToByteString #
pinnedByteArrayToForeignPtr :: ByteArray -> ForeignPtr a
pinnedByteArrayToForeignPtr (ByteArray ba#) =
ForeignPtr (byteArrayContents# ba#) (PlainPtr (unsafeCoerce# ba#))
# INLINE pinnedByteArrayToForeignPtr #
for indexing into an immutable ` ByteString ` , which is analogous to
unsafeWithByteStringPtr :: ByteString -> (Ptr b -> IO a) -> a
unsafeWithByteStringPtr bs f =
accursedUnutterablePerformIO $
case toForeignPtr bs of
(fp, offset, _) ->
unsafeWithForeignPtr (plusForeignPtr fp offset) f
# INLINE unsafeWithByteStringPtr #
#if !MIN_VERSION_base(4,15,0)
by GHC 9.0.1 and later .
unsafeWithForeignPtr :: ForeignPtr a -> (Ptr a -> IO b) -> IO b
unsafeWithForeignPtr = withForeignPtr
# INLINE unsafeWithForeignPtr #
#endif
|
db724632fc5d292fb38826bc6c036724e3412bd0a67ed9f9f535705749281684
|
brendanhay/terrafomo
|
Resources.hs
|
-- This module is auto-generated.
# LANGUAGE NoImplicitPrelude #
# LANGUAGE RecordWildCards #
# LANGUAGE StrictData #
# LANGUAGE UndecidableInstances #
# OPTIONS_GHC -fno - warn - unused - imports #
-- |
Module : . Kubernetes . Resources
Copyright : ( c ) 2017 - 2018
License : Mozilla Public License , v. 2.0 .
Maintainer : < brendan.g.hay+ >
-- Stability : auto-generated
Portability : non - portable ( GHC extensions )
--
module Terrafomo.Kubernetes.Resources
(
-- * kubernetes_config_map
newConfigMapR
, ConfigMapR (..)
, ConfigMapR_Required (..)
-- * kubernetes_horizontal_pod_autoscaler
, newHorizontalPodAutoscalerR
, HorizontalPodAutoscalerR (..)
-- * kubernetes_limit_range
, newLimitRangeR
, LimitRangeR (..)
, LimitRangeR_Required (..)
-- * kubernetes_namespace
, newNamespaceR
, NamespaceR (..)
-- * kubernetes_persistent_volume_claim
, newPersistentVolumeClaimR
, PersistentVolumeClaimR (..)
, PersistentVolumeClaimR_Required (..)
-- * kubernetes_persistent_volume
, newPersistentVolumeR
, PersistentVolumeR (..)
*
, newPodR
, PodR (..)
-- * kubernetes_replication_controller
, newReplicationControllerR
, ReplicationControllerR (..)
-- * kubernetes_resource_quota
, newResourceQuotaR
, ResourceQuotaR (..)
, ResourceQuotaR_Required (..)
*
, newSecretR
, SecretR (..)
, SecretR_Required (..)
* kubernetes_service_account
, newServiceAccountR
, ServiceAccountR (..)
, ServiceAccountR_Required (..)
-- * kubernetes_service
, newServiceR
, ServiceR (..)
* kubernetes_storage_class
, newStorageClassR
, StorageClassR (..)
, StorageClassR_Required (..)
) where
import Data.Functor ((<$>))
import Data.Semigroup ((<>))
import GHC.Base (Proxy#, proxy#, ($))
import Terrafomo.Kubernetes.Settings
import qualified Data.Functor.Const as P
import qualified Data.List.NonEmpty as P
import qualified Data.Map.Strict as P
import qualified Data.Maybe as P
import qualified Data.Text.Lazy as P
import qualified Prelude as P
import qualified Terrafomo.Encode as Encode
import qualified Terrafomo.HCL as TF
import qualified Terrafomo.HIL as TF
import qualified Terrafomo.Kubernetes.Provider as P
import qualified Terrafomo.Kubernetes.Types as P
import qualified Terrafomo.Lens as Lens
import qualified Terrafomo.Schema as TF
-- | The main @kubernetes_config_map@ resource definition.
data ConfigMapR s = ConfigMapR_Internal
{ data_ :: P.Maybe (TF.Expr s (P.Map P.Text (TF.Expr s P.Text)))
-- ^ @data@
-- - (Optional)
-- A map of the configuration data.
, metadata :: TF.Expr s (ConfigMapMetadata s)
-- ^ @metadata@
-- - (Required)
-- Standard config map's metadata. More info:
-- -conventions.md#metadata
} deriving (P.Show)
| Construct a new @kubernetes_config_map@ resource . The
available argument lenses and computed attribute getters are documented below .
See the < terraform documentation > for more information .
= = = Example Usage
You can define a minimal @kubernetes_config_map@ via :
@
Kubernetes.newConfigMapR
( Kubernetes . ConfigMapR
{ Kubernetes.metadata = metadata -- s ( ConfigMapMetadata s )
} )
@
= = = Argument Reference
The following arguments are supported :
@
# data : : Lens ' ( Resource ConfigMapR s ) ( Maybe ( s ( Map Text ( Expr s Text ) ) ) )
# metadata : : ' ( Resource ConfigMapR s ) ( s ( ConfigMapMetadata s ) )
@
= = = Attributes Reference
In addition to the arguments above , the following computed attributes are available :
@
# i d : : Getting r ( Ref ConfigMapR s ) ( s I d )
@
= = = Configuring Meta - parameters
The following additional configuration is supported :
@
# prevent_destroy : : Lens ' ( Resource ConfigMapR s ) Bool
# create_before_destroy : : ' ( Resource ConfigMapR s ) Bool
# ignore_changes : : ' ( Resource ConfigMapR s ) ( Changes s )
# depends_on : : ' ( Resource ConfigMapR s ) ( Set ( Depends s ) )
# provider : : ' ( Resource ConfigMapR s ) ( Maybe Kubernetes )
@
available argument lenses and computed attribute getters are documented below.
See the < terraform documentation> for more information.
=== Example Usage
You can define a minimal @kubernetes_config_map@ via:
@
Kubernetes.newConfigMapR
(Kubernetes.ConfigMapR
{ Kubernetes.metadata = metadata -- Expr s (ConfigMapMetadata s)
})
@
=== Argument Reference
The following arguments are supported:
@
#data :: Lens' (Resource ConfigMapR s) (Maybe (Expr s (Map Text (Expr s Text))))
#metadata :: Lens' (Resource ConfigMapR s) (Expr s (ConfigMapMetadata s))
@
=== Attributes Reference
In addition to the arguments above, the following computed attributes are available:
@
#id :: Getting r (Ref ConfigMapR s) (Expr s Id)
@
=== Configuring Meta-parameters
The following additional configuration is supported:
@
#prevent_destroy :: Lens' (Resource ConfigMapR s) Bool
#create_before_destroy :: Lens' (Resource ConfigMapR s) Bool
#ignore_changes :: Lens' (Resource ConfigMapR s) (Changes s)
#depends_on :: Lens' (Resource ConfigMapR s) (Set (Depends s))
#provider :: Lens' (Resource ConfigMapR s) (Maybe Kubernetes)
@
-}
newConfigMapR
:: ConfigMapR_Required s -- ^ The minimal/required arguments.
-> P.Resource ConfigMapR s
newConfigMapR x =
TF.unsafeResource "kubernetes_config_map" Encode.metadata
(\ConfigMapR_Internal{..} ->
P.mempty
<> P.maybe P.mempty (TF.pair "data") data_
<> TF.pair "metadata" metadata
)
(let ConfigMapR{..} = x in ConfigMapR_Internal
{ data_ = P.Nothing
, metadata = metadata
})
-- | The required arguments for 'newConfigMapR'.
data ConfigMapR_Required s = ConfigMapR
{ metadata :: TF.Expr s (ConfigMapMetadata s)
-- ^ (Required)
-- Standard config map's metadata. More info:
-- -conventions.md#metadata
} deriving (P.Show)
instance Lens.HasField "data" f (P.Resource ConfigMapR s) (P.Maybe (TF.Expr s (P.Map P.Text (TF.Expr s P.Text)))) where
field = Lens.resourceLens P.. Lens.lens'
(data_ :: ConfigMapR s -> P.Maybe (TF.Expr s (P.Map P.Text (TF.Expr s P.Text))))
(\s a -> s { data_ = a } :: ConfigMapR s)
instance Lens.HasField "metadata" f (P.Resource ConfigMapR s) (TF.Expr s (ConfigMapMetadata s)) where
field = Lens.resourceLens P.. Lens.lens'
(metadata :: ConfigMapR s -> TF.Expr s (ConfigMapMetadata s))
(\s a -> s { metadata = a } :: ConfigMapR s)
instance Lens.HasField "id" (P.Const r) (TF.Ref ConfigMapR s) (TF.Expr s TF.Id) where
field = Lens.to (TF.unsafeComputed Encode.attribute (proxy# :: Proxy# "id"))
-- | The main @kubernetes_horizontal_pod_autoscaler@ resource definition.
data HorizontalPodAutoscalerR s = HorizontalPodAutoscalerR
{ metadata :: TF.Expr s (HorizontalPodAutoscalerMetadata s)
-- ^ @metadata@
-- - (Required)
-- Standard horizontal pod autoscaler's metadata. More info:
-- -conventions.md#metadata
, spec :: TF.Expr s (HorizontalPodAutoscalerSpec s)
-- ^ @spec@
-- - (Required)
-- Behaviour of the autoscaler. More info:
-conventions.md#spec-and-status
} deriving (P.Show)
| Construct a new @kubernetes_horizontal_pod_autoscaler@ resource . The
available argument lenses and computed attribute getters are documented below .
See the < terraform documentation > for more information .
= = = Example Usage
You can define a minimal @kubernetes_horizontal_pod_autoscaler@ via :
@
( Kubernetes . HorizontalPodAutoscalerR
{ Kubernetes.metadata = metadata -- s ( HorizontalPodAutoscalerMetadata s )
, Kubernetes.spec = spec -- Expr s ( HorizontalPodAutoscalerSpec s )
} )
@
= = = Argument Reference
The following arguments are supported :
@
# metadata : : ' ( Resource HorizontalPodAutoscalerR s ) ( s ( HorizontalPodAutoscalerMetadata s ) )
# spec : : ' ( Resource HorizontalPodAutoscalerR s ) ( s ( HorizontalPodAutoscalerSpec s ) )
@
= = = Attributes Reference
In addition to the arguments above , the following computed attributes are available :
@
# i d : : Getting r ( Ref HorizontalPodAutoscalerR s ) ( s I d )
@
= = = Configuring Meta - parameters
The following additional configuration is supported :
@
# prevent_destroy : : Lens ' ( Resource HorizontalPodAutoscalerR s ) Bool
# create_before_destroy : : ' ( Resource HorizontalPodAutoscalerR s ) Bool
# ignore_changes : : ' ( Resource HorizontalPodAutoscalerR s ) ( Changes s )
# depends_on : : ' ( Resource HorizontalPodAutoscalerR s ) ( Set ( Depends s ) )
# provider : : ' ( Resource HorizontalPodAutoscalerR s ) ( Maybe Kubernetes )
@
available argument lenses and computed attribute getters are documented below.
See the < terraform documentation> for more information.
=== Example Usage
You can define a minimal @kubernetes_horizontal_pod_autoscaler@ via:
@
Kubernetes.newHorizontalPodAutoscalerR
(Kubernetes.HorizontalPodAutoscalerR
{ Kubernetes.metadata = metadata -- Expr s (HorizontalPodAutoscalerMetadata s)
, Kubernetes.spec = spec -- Expr s (HorizontalPodAutoscalerSpec s)
})
@
=== Argument Reference
The following arguments are supported:
@
#metadata :: Lens' (Resource HorizontalPodAutoscalerR s) (Expr s (HorizontalPodAutoscalerMetadata s))
#spec :: Lens' (Resource HorizontalPodAutoscalerR s) (Expr s (HorizontalPodAutoscalerSpec s))
@
=== Attributes Reference
In addition to the arguments above, the following computed attributes are available:
@
#id :: Getting r (Ref HorizontalPodAutoscalerR s) (Expr s Id)
@
=== Configuring Meta-parameters
The following additional configuration is supported:
@
#prevent_destroy :: Lens' (Resource HorizontalPodAutoscalerR s) Bool
#create_before_destroy :: Lens' (Resource HorizontalPodAutoscalerR s) Bool
#ignore_changes :: Lens' (Resource HorizontalPodAutoscalerR s) (Changes s)
#depends_on :: Lens' (Resource HorizontalPodAutoscalerR s) (Set (Depends s))
#provider :: Lens' (Resource HorizontalPodAutoscalerR s) (Maybe Kubernetes)
@
-}
newHorizontalPodAutoscalerR
:: HorizontalPodAutoscalerR s -- ^ The minimal/required arguments.
-> P.Resource HorizontalPodAutoscalerR s
newHorizontalPodAutoscalerR =
TF.unsafeResource "kubernetes_horizontal_pod_autoscaler" Encode.metadata
(\HorizontalPodAutoscalerR{..} ->
P.mempty
<> TF.pair "metadata" metadata
<> TF.pair "spec" spec
)
instance Lens.HasField "metadata" f (P.Resource HorizontalPodAutoscalerR s) (TF.Expr s (HorizontalPodAutoscalerMetadata s)) where
field = Lens.resourceLens P.. Lens.lens'
(metadata :: HorizontalPodAutoscalerR s -> TF.Expr s (HorizontalPodAutoscalerMetadata s))
(\s a -> s { metadata = a } :: HorizontalPodAutoscalerR s)
instance Lens.HasField "spec" f (P.Resource HorizontalPodAutoscalerR s) (TF.Expr s (HorizontalPodAutoscalerSpec s)) where
field = Lens.resourceLens P.. Lens.lens'
(spec :: HorizontalPodAutoscalerR s -> TF.Expr s (HorizontalPodAutoscalerSpec s))
(\s a -> s { spec = a } :: HorizontalPodAutoscalerR s)
instance Lens.HasField "id" (P.Const r) (TF.Ref HorizontalPodAutoscalerR s) (TF.Expr s TF.Id) where
field = Lens.to (TF.unsafeComputed Encode.attribute (proxy# :: Proxy# "id"))
| The main resource definition .
data LimitRangeR s = LimitRangeR_Internal
{ metadata :: TF.Expr s (LimitRangeMetadata s)
-- ^ @metadata@
-- - (Required)
-- Standard limit range's metadata. More info:
-- -conventions.md#metadata
, spec :: P.Maybe (TF.Expr s (LimitRangeSpec s))
-- ^ @spec@
-- - (Optional)
Spec defines the limits enforced . More info :
-conventions.md#spec-and-status
} deriving (P.Show)
| Construct a new resource . The
available argument lenses and computed attribute getters are documented below .
See the < terraform documentation > for more information .
= = = Example Usage
You can define a minimal via :
@
Kubernetes.newLimitRangeR
( Kubernetes . LimitRangeR
{ Kubernetes.metadata = metadata -- s ( LimitRangeMetadata s )
} )
@
= = = Argument Reference
The following arguments are supported :
@
# metadata : : ' ( Resource LimitRangeR s ) ( s ( LimitRangeMetadata s ) )
# spec : : ' ( Resource LimitRangeR s ) ( Maybe ( s ( LimitRangeSpec s ) ) )
@
= = = Attributes Reference
In addition to the arguments above , the following computed attributes are available :
@
# i d : : Getting r ( Ref LimitRangeR s ) ( s I d )
@
= = = Configuring Meta - parameters
The following additional configuration is supported :
@
# prevent_destroy : : Lens ' ( Resource LimitRangeR s ) Bool
# create_before_destroy : : ' ( Resource LimitRangeR s ) Bool
# ignore_changes : : ' ( Resource LimitRangeR s ) ( Changes s )
# depends_on : : ' ( Resource LimitRangeR s ) ( Set ( Depends s ) )
# provider : : ' ( Resource LimitRangeR s ) ( Maybe Kubernetes )
@
available argument lenses and computed attribute getters are documented below.
See the < terraform documentation> for more information.
=== Example Usage
You can define a minimal @kubernetes_limit_range@ via:
@
Kubernetes.newLimitRangeR
(Kubernetes.LimitRangeR
{ Kubernetes.metadata = metadata -- Expr s (LimitRangeMetadata s)
})
@
=== Argument Reference
The following arguments are supported:
@
#metadata :: Lens' (Resource LimitRangeR s) (Expr s (LimitRangeMetadata s))
#spec :: Lens' (Resource LimitRangeR s) (Maybe (Expr s (LimitRangeSpec s)))
@
=== Attributes Reference
In addition to the arguments above, the following computed attributes are available:
@
#id :: Getting r (Ref LimitRangeR s) (Expr s Id)
@
=== Configuring Meta-parameters
The following additional configuration is supported:
@
#prevent_destroy :: Lens' (Resource LimitRangeR s) Bool
#create_before_destroy :: Lens' (Resource LimitRangeR s) Bool
#ignore_changes :: Lens' (Resource LimitRangeR s) (Changes s)
#depends_on :: Lens' (Resource LimitRangeR s) (Set (Depends s))
#provider :: Lens' (Resource LimitRangeR s) (Maybe Kubernetes)
@
-}
newLimitRangeR
:: LimitRangeR_Required s -- ^ The minimal/required arguments.
-> P.Resource LimitRangeR s
newLimitRangeR x =
TF.unsafeResource "kubernetes_limit_range" Encode.metadata
(\LimitRangeR_Internal{..} ->
P.mempty
<> TF.pair "metadata" metadata
<> P.maybe P.mempty (TF.pair "spec") spec
)
(let LimitRangeR{..} = x in LimitRangeR_Internal
{ metadata = metadata
, spec = P.Nothing
})
| The required arguments for ' newLimitRangeR ' .
data LimitRangeR_Required s = LimitRangeR
{ metadata :: TF.Expr s (LimitRangeMetadata s)
-- ^ (Required)
-- Standard limit range's metadata. More info:
-- -conventions.md#metadata
} deriving (P.Show)
instance Lens.HasField "metadata" f (P.Resource LimitRangeR s) (TF.Expr s (LimitRangeMetadata s)) where
field = Lens.resourceLens P.. Lens.lens'
(metadata :: LimitRangeR s -> TF.Expr s (LimitRangeMetadata s))
(\s a -> s { metadata = a } :: LimitRangeR s)
instance Lens.HasField "spec" f (P.Resource LimitRangeR s) (P.Maybe (TF.Expr s (LimitRangeSpec s))) where
field = Lens.resourceLens P.. Lens.lens'
(spec :: LimitRangeR s -> P.Maybe (TF.Expr s (LimitRangeSpec s)))
(\s a -> s { spec = a } :: LimitRangeR s)
instance Lens.HasField "id" (P.Const r) (TF.Ref LimitRangeR s) (TF.Expr s TF.Id) where
field = Lens.to (TF.unsafeComputed Encode.attribute (proxy# :: Proxy# "id"))
-- | The main @kubernetes_namespace@ resource definition.
newtype NamespaceR s = NamespaceR
{ metadata :: TF.Expr s (NamespaceMetadata s)
-- ^ @metadata@
-- - (Required)
-- Standard namespace's metadata. More info:
-- -conventions.md#metadata
} deriving (P.Show)
| Construct a new @kubernetes_namespace@ resource . The
available argument lenses and computed attribute getters are documented below .
See the < terraform documentation > for more information .
= = = Example Usage
You can define a minimal @kubernetes_namespace@ via :
@
Kubernetes.newNamespaceR
( Kubernetes . NamespaceR
{ Kubernetes.metadata = metadata -- s ( NamespaceMetadata s )
} )
@
= = = Argument Reference
The following arguments are supported :
@
# metadata : : ' ( Resource NamespaceR s ) ( s ( NamespaceMetadata s ) )
@
= = = Attributes Reference
In addition to the arguments above , the following computed attributes are available :
@
# i d : : Getting r ( Ref NamespaceR s ) ( s I d )
@
= = = Configuring Meta - parameters
The following additional configuration is supported :
@
# prevent_destroy : : Lens ' ( Resource NamespaceR s ) Bool
# create_before_destroy : : ' ( Resource NamespaceR s ) Bool
# ignore_changes : : ' ( Resource NamespaceR s ) ( Changes s )
# depends_on : : ' ( Resource NamespaceR s ) ( Set ( Depends s ) )
# provider : : ' ( Resource NamespaceR s ) ( Maybe Kubernetes )
@
available argument lenses and computed attribute getters are documented below.
See the < terraform documentation> for more information.
=== Example Usage
You can define a minimal @kubernetes_namespace@ via:
@
Kubernetes.newNamespaceR
(Kubernetes.NamespaceR
{ Kubernetes.metadata = metadata -- Expr s (NamespaceMetadata s)
})
@
=== Argument Reference
The following arguments are supported:
@
#metadata :: Lens' (Resource NamespaceR s) (Expr s (NamespaceMetadata s))
@
=== Attributes Reference
In addition to the arguments above, the following computed attributes are available:
@
#id :: Getting r (Ref NamespaceR s) (Expr s Id)
@
=== Configuring Meta-parameters
The following additional configuration is supported:
@
#prevent_destroy :: Lens' (Resource NamespaceR s) Bool
#create_before_destroy :: Lens' (Resource NamespaceR s) Bool
#ignore_changes :: Lens' (Resource NamespaceR s) (Changes s)
#depends_on :: Lens' (Resource NamespaceR s) (Set (Depends s))
#provider :: Lens' (Resource NamespaceR s) (Maybe Kubernetes)
@
-}
newNamespaceR
:: NamespaceR s -- ^ The minimal/required arguments.
-> P.Resource NamespaceR s
newNamespaceR =
TF.unsafeResource "kubernetes_namespace" Encode.metadata
(\NamespaceR{..} ->
P.mempty
<> TF.pair "metadata" metadata
)
instance Lens.HasField "metadata" f (P.Resource NamespaceR s) (TF.Expr s (NamespaceMetadata s)) where
field = Lens.resourceLens P.. Lens.lens'
(metadata :: NamespaceR s -> TF.Expr s (NamespaceMetadata s))
(\s a -> s { metadata = a } :: NamespaceR s)
instance Lens.HasField "id" (P.Const r) (TF.Ref NamespaceR s) (TF.Expr s TF.Id) where
field = Lens.to (TF.unsafeComputed Encode.attribute (proxy# :: Proxy# "id"))
-- | The main @kubernetes_persistent_volume_claim@ resource definition.
data PersistentVolumeClaimR s = PersistentVolumeClaimR_Internal
{ metadata :: TF.Expr s (PersistentVolumeClaimMetadata s)
-- ^ @metadata@
-- - (Required)
-- Standard persistent volume claim's metadata. More info:
-- -conventions.md#metadata
, spec :: TF.Expr s (PersistentVolumeClaimSpec s)
-- ^ @spec@
-- - (Required, Forces New)
Spec defines the desired characteristics of a volume requested by a pod
-- author. More info:
-- -guide/persistent-volumes#persistentvolumeclaims
, wait_until_bound :: TF.Expr s P.Bool
-- ^ @wait_until_bound@
-- - (Default __@true@__)
-- Whether to wait for the claim to reach `Bound` state (to find volume in
-- which to claim the space)
} deriving (P.Show)
| Construct a new @kubernetes_persistent_volume_claim@ resource . The
available argument lenses and computed attribute getters are documented below .
See the < terraform documentation > for more information .
= = = Example Usage
You can define a minimal @kubernetes_persistent_volume_claim@ via :
@
Kubernetes.newPersistentVolumeClaimR
( Kubernetes . PersistentVolumeClaimR
{ Kubernetes.metadata = metadata -- s ( PersistentVolumeClaimMetadata s )
, Kubernetes.spec = spec -- Expr s ( PersistentVolumeClaimSpec s )
} )
@
= = = Argument Reference
The following arguments are supported :
@
# metadata : : ' ( Resource PersistentVolumeClaimR s ) ( s ( PersistentVolumeClaimMetadata s ) )
# spec : : ' ( Resource PersistentVolumeClaimR s ) ( s ( PersistentVolumeClaimSpec s ) )
# wait_until_bound : : ' ( Resource PersistentVolumeClaimR s ) ( s Bool )
@
= = = Attributes Reference
In addition to the arguments above , the following computed attributes are available :
@
# i d : : Getting r ( Ref PersistentVolumeClaimR s ) ( s I d )
@
= = = Configuring Meta - parameters
The following additional configuration is supported :
@
# prevent_destroy : : Lens ' ( Resource PersistentVolumeClaimR s ) Bool
# create_before_destroy : : ' ( Resource PersistentVolumeClaimR s ) Bool
# ignore_changes : : ' ( Resource PersistentVolumeClaimR s ) ( Changes s )
# depends_on : : ' ( Resource PersistentVolumeClaimR s ) ( Set ( Depends s ) )
# provider : : ' ( Resource PersistentVolumeClaimR s ) ( Maybe Kubernetes )
@
available argument lenses and computed attribute getters are documented below.
See the < terraform documentation> for more information.
=== Example Usage
You can define a minimal @kubernetes_persistent_volume_claim@ via:
@
Kubernetes.newPersistentVolumeClaimR
(Kubernetes.PersistentVolumeClaimR
{ Kubernetes.metadata = metadata -- Expr s (PersistentVolumeClaimMetadata s)
, Kubernetes.spec = spec -- Expr s (PersistentVolumeClaimSpec s)
})
@
=== Argument Reference
The following arguments are supported:
@
#metadata :: Lens' (Resource PersistentVolumeClaimR s) (Expr s (PersistentVolumeClaimMetadata s))
#spec :: Lens' (Resource PersistentVolumeClaimR s) (Expr s (PersistentVolumeClaimSpec s))
#wait_until_bound :: Lens' (Resource PersistentVolumeClaimR s) (Expr s Bool)
@
=== Attributes Reference
In addition to the arguments above, the following computed attributes are available:
@
#id :: Getting r (Ref PersistentVolumeClaimR s) (Expr s Id)
@
=== Configuring Meta-parameters
The following additional configuration is supported:
@
#prevent_destroy :: Lens' (Resource PersistentVolumeClaimR s) Bool
#create_before_destroy :: Lens' (Resource PersistentVolumeClaimR s) Bool
#ignore_changes :: Lens' (Resource PersistentVolumeClaimR s) (Changes s)
#depends_on :: Lens' (Resource PersistentVolumeClaimR s) (Set (Depends s))
#provider :: Lens' (Resource PersistentVolumeClaimR s) (Maybe Kubernetes)
@
-}
newPersistentVolumeClaimR
:: PersistentVolumeClaimR_Required s -- ^ The minimal/required arguments.
-> P.Resource PersistentVolumeClaimR s
newPersistentVolumeClaimR x =
TF.unsafeResource "kubernetes_persistent_volume_claim" Encode.metadata
(\PersistentVolumeClaimR_Internal{..} ->
P.mempty
<> TF.pair "metadata" metadata
<> TF.pair "spec" spec
<> TF.pair "wait_until_bound" wait_until_bound
)
(let PersistentVolumeClaimR{..} = x in PersistentVolumeClaimR_Internal
{ metadata = metadata
, spec = spec
, wait_until_bound = TF.expr P.True
})
-- | The required arguments for 'newPersistentVolumeClaimR'.
data PersistentVolumeClaimR_Required s = PersistentVolumeClaimR
{ metadata :: TF.Expr s (PersistentVolumeClaimMetadata s)
-- ^ (Required)
-- Standard persistent volume claim's metadata. More info:
-- -conventions.md#metadata
, spec :: TF.Expr s (PersistentVolumeClaimSpec s)
^ ( Required , Forces New )
Spec defines the desired characteristics of a volume requested by a pod
-- author. More info:
-- -guide/persistent-volumes#persistentvolumeclaims
} deriving (P.Show)
instance Lens.HasField "metadata" f (P.Resource PersistentVolumeClaimR s) (TF.Expr s (PersistentVolumeClaimMetadata s)) where
field = Lens.resourceLens P.. Lens.lens'
(metadata :: PersistentVolumeClaimR s -> TF.Expr s (PersistentVolumeClaimMetadata s))
(\s a -> s { metadata = a } :: PersistentVolumeClaimR s)
instance Lens.HasField "spec" f (P.Resource PersistentVolumeClaimR s) (TF.Expr s (PersistentVolumeClaimSpec s)) where
field = Lens.resourceLens P.. Lens.lens'
(spec :: PersistentVolumeClaimR s -> TF.Expr s (PersistentVolumeClaimSpec s))
(\s a -> s { spec = a } :: PersistentVolumeClaimR s)
instance Lens.HasField "wait_until_bound" f (P.Resource PersistentVolumeClaimR s) (TF.Expr s P.Bool) where
field = Lens.resourceLens P.. Lens.lens'
(wait_until_bound :: PersistentVolumeClaimR s -> TF.Expr s P.Bool)
(\s a -> s { wait_until_bound = a } :: PersistentVolumeClaimR s)
instance Lens.HasField "id" (P.Const r) (TF.Ref PersistentVolumeClaimR s) (TF.Expr s TF.Id) where
field = Lens.to (TF.unsafeComputed Encode.attribute (proxy# :: Proxy# "id"))
| The main @kubernetes_persistent_volume@ resource definition .
data PersistentVolumeR s = PersistentVolumeR
{ metadata :: TF.Expr s (PersistentVolumeMetadata s)
-- ^ @metadata@
-- - (Required)
-- Standard persistent volume's metadata. More info:
-- -conventions.md#metadata
, spec :: TF.Expr s [TF.Expr s (PersistentVolumeSpec s)]
-- ^ @spec@
-- - (Required)
Spec of the persistent volume owned by the cluster
} deriving (P.Show)
| Construct a new @kubernetes_persistent_volume@ resource . The
available argument lenses and computed attribute getters are documented below .
See the < terraform documentation > for more information .
= = = Example Usage
You can define a minimal @kubernetes_persistent_volume@ via :
@
Kubernetes.newPersistentVolumeR
( Kubernetes . PersistentVolumeR
{ Kubernetes.metadata = metadata -- s ( PersistentVolumeMetadata s )
, Kubernetes.spec = spec -- s [ s ( PersistentVolumeSpec s ) ]
} )
@
= = = Argument Reference
The following arguments are supported :
@
# metadata : : ' ( Resource PersistentVolumeR s ) ( s ( PersistentVolumeMetadata s ) )
# spec : : Lens ' ( Resource PersistentVolumeR s ) ( s [ s ( PersistentVolumeSpec s ) ] )
@
= = = Attributes Reference
In addition to the arguments above , the following computed attributes are available :
@
# i d : : Getting r ( Ref PersistentVolumeR s ) ( s I d )
@
= = = Configuring Meta - parameters
The following additional configuration is supported :
@
# prevent_destroy : : Lens ' ( Resource PersistentVolumeR s ) Bool
# create_before_destroy : : ' ( Resource PersistentVolumeR s ) Bool
# ignore_changes : : ' ( Resource PersistentVolumeR s ) ( Changes s )
# depends_on : : ' ( Resource PersistentVolumeR s ) ( Set ( Depends s ) )
# provider : : ' ( Resource PersistentVolumeR s ) ( Maybe Kubernetes )
@
available argument lenses and computed attribute getters are documented below.
See the < terraform documentation> for more information.
=== Example Usage
You can define a minimal @kubernetes_persistent_volume@ via:
@
Kubernetes.newPersistentVolumeR
(Kubernetes.PersistentVolumeR
{ Kubernetes.metadata = metadata -- Expr s (PersistentVolumeMetadata s)
, Kubernetes.spec = spec -- Expr s [Expr s (PersistentVolumeSpec s)]
})
@
=== Argument Reference
The following arguments are supported:
@
#metadata :: Lens' (Resource PersistentVolumeR s) (Expr s (PersistentVolumeMetadata s))
#spec :: Lens' (Resource PersistentVolumeR s) (Expr s [Expr s (PersistentVolumeSpec s)])
@
=== Attributes Reference
In addition to the arguments above, the following computed attributes are available:
@
#id :: Getting r (Ref PersistentVolumeR s) (Expr s Id)
@
=== Configuring Meta-parameters
The following additional configuration is supported:
@
#prevent_destroy :: Lens' (Resource PersistentVolumeR s) Bool
#create_before_destroy :: Lens' (Resource PersistentVolumeR s) Bool
#ignore_changes :: Lens' (Resource PersistentVolumeR s) (Changes s)
#depends_on :: Lens' (Resource PersistentVolumeR s) (Set (Depends s))
#provider :: Lens' (Resource PersistentVolumeR s) (Maybe Kubernetes)
@
-}
newPersistentVolumeR
:: PersistentVolumeR s -- ^ The minimal/required arguments.
-> P.Resource PersistentVolumeR s
newPersistentVolumeR =
TF.unsafeResource "kubernetes_persistent_volume" Encode.metadata
(\PersistentVolumeR{..} ->
P.mempty
<> TF.pair "metadata" metadata
<> TF.pair "spec" spec
)
instance Lens.HasField "metadata" f (P.Resource PersistentVolumeR s) (TF.Expr s (PersistentVolumeMetadata s)) where
field = Lens.resourceLens P.. Lens.lens'
(metadata :: PersistentVolumeR s -> TF.Expr s (PersistentVolumeMetadata s))
(\s a -> s { metadata = a } :: PersistentVolumeR s)
instance Lens.HasField "spec" f (P.Resource PersistentVolumeR s) (TF.Expr s [TF.Expr s (PersistentVolumeSpec s)]) where
field = Lens.resourceLens P.. Lens.lens'
(spec :: PersistentVolumeR s -> TF.Expr s [TF.Expr s (PersistentVolumeSpec s)])
(\s a -> s { spec = a } :: PersistentVolumeR s)
instance Lens.HasField "id" (P.Const r) (TF.Ref PersistentVolumeR s) (TF.Expr s TF.Id) where
field = Lens.to (TF.unsafeComputed Encode.attribute (proxy# :: Proxy# "id"))
-- | The main @kubernetes_pod@ resource definition.
data PodR s = PodR
{ metadata :: TF.Expr s (PodMetadata s)
-- ^ @metadata@
-- - (Required)
-- Standard pod's metadata. More info:
-- -conventions.md#metadata
, spec :: TF.Expr s (PodSpec s)
-- ^ @spec@
-- - (Required)
Spec of the pod owned by the cluster
} deriving (P.Show)
| Construct a new @kubernetes_pod@ resource . The
available argument lenses and computed attribute getters are documented below .
See the < terraform documentation > for more information .
= = = Example Usage
You can define a minimal @kubernetes_pod@ via :
@
Kubernetes.newPodR
( Kubernetes . PodR
{ Kubernetes.metadata = metadata -- s ( PodMetadata s )
, Kubernetes.spec = spec -- s ( PodSpec s )
} )
@
= = = Argument Reference
The following arguments are supported :
@
# metadata : : ' ( Resource PodR s ) ( s ( PodMetadata s ) )
# spec : : Lens ' ( Resource PodR s ) ( s ( PodSpec s ) )
@
= = = Attributes Reference
In addition to the arguments above , the following computed attributes are available :
@
# i d : : Getting r ( Ref PodR s ) ( s I d )
@
= = = Configuring Meta - parameters
The following additional configuration is supported :
@
# prevent_destroy : : Lens ' ( Resource PodR s ) Bool
# create_before_destroy : : ' ( Resource PodR s ) Bool
# ignore_changes : : ' ( Resource PodR s ) ( Changes s )
# depends_on : : ' ( Resource PodR s ) ( Set ( Depends s ) )
# provider : : ' ( Resource PodR s ) ( Maybe Kubernetes )
@
available argument lenses and computed attribute getters are documented below.
See the < terraform documentation> for more information.
=== Example Usage
You can define a minimal @kubernetes_pod@ via:
@
Kubernetes.newPodR
(Kubernetes.PodR
{ Kubernetes.metadata = metadata -- Expr s (PodMetadata s)
, Kubernetes.spec = spec -- Expr s (PodSpec s)
})
@
=== Argument Reference
The following arguments are supported:
@
#metadata :: Lens' (Resource PodR s) (Expr s (PodMetadata s))
#spec :: Lens' (Resource PodR s) (Expr s (PodSpec s))
@
=== Attributes Reference
In addition to the arguments above, the following computed attributes are available:
@
#id :: Getting r (Ref PodR s) (Expr s Id)
@
=== Configuring Meta-parameters
The following additional configuration is supported:
@
#prevent_destroy :: Lens' (Resource PodR s) Bool
#create_before_destroy :: Lens' (Resource PodR s) Bool
#ignore_changes :: Lens' (Resource PodR s) (Changes s)
#depends_on :: Lens' (Resource PodR s) (Set (Depends s))
#provider :: Lens' (Resource PodR s) (Maybe Kubernetes)
@
-}
newPodR
:: PodR s -- ^ The minimal/required arguments.
-> P.Resource PodR s
newPodR =
TF.unsafeResource "kubernetes_pod" Encode.metadata
(\PodR{..} ->
P.mempty
<> TF.pair "metadata" metadata
<> TF.pair "spec" spec
)
instance Lens.HasField "metadata" f (P.Resource PodR s) (TF.Expr s (PodMetadata s)) where
field = Lens.resourceLens P.. Lens.lens'
(metadata :: PodR s -> TF.Expr s (PodMetadata s))
(\s a -> s { metadata = a } :: PodR s)
instance Lens.HasField "spec" f (P.Resource PodR s) (TF.Expr s (PodSpec s)) where
field = Lens.resourceLens P.. Lens.lens'
(spec :: PodR s -> TF.Expr s (PodSpec s))
(\s a -> s { spec = a } :: PodR s)
instance Lens.HasField "id" (P.Const r) (TF.Ref PodR s) (TF.Expr s TF.Id) where
field = Lens.to (TF.unsafeComputed Encode.attribute (proxy# :: Proxy# "id"))
-- | The main @kubernetes_replication_controller@ resource definition.
data ReplicationControllerR s = ReplicationControllerR
{ metadata :: TF.Expr s (ReplicationControllerMetadata s)
-- ^ @metadata@
-- - (Required)
-- Standard replication controller's metadata. More info:
-- -conventions.md#metadata
, spec :: TF.Expr s (ReplicationControllerSpec s)
-- ^ @spec@
-- - (Required)
Spec defines the specification of the desired behavior of the replication
-- controller. More info:
-- -conventions.md#spec-and-status
} deriving (P.Show)
| Construct a new @kubernetes_replication_controller@ resource . The
available argument lenses and computed attribute getters are documented below .
See the < terraform documentation > for more information .
= = = Example Usage
You can define a minimal @kubernetes_replication_controller@ via :
@
( Kubernetes . ReplicationControllerR
{ Kubernetes.metadata = metadata -- s ( ReplicationControllerMetadata s )
, Kubernetes.spec = spec -- Expr s ( s )
} )
@
= = = Argument Reference
The following arguments are supported :
@
# metadata : : ' ( Resource ReplicationControllerR s ) ( s ( ReplicationControllerMetadata s ) )
# spec : : Lens ' ( Resource ReplicationControllerR s ) ( s ( s ) )
@
= = = Attributes Reference
In addition to the arguments above , the following computed attributes are available :
@
# i d : : Getting r ( Ref ReplicationControllerR s ) ( s I d )
@
= = = Configuring Meta - parameters
The following additional configuration is supported :
@
# prevent_destroy : : Lens ' ( Resource ReplicationControllerR s ) Bool
# create_before_destroy : : ' ( Resource ReplicationControllerR s ) Bool
# ignore_changes : : ' ( Resource ReplicationControllerR s ) ( Changes s )
# depends_on : : ' ( Resource ReplicationControllerR s ) ( Set ( Depends s ) )
# provider : : ' ( Resource ReplicationControllerR s ) ( Maybe Kubernetes )
@
available argument lenses and computed attribute getters are documented below.
See the < terraform documentation> for more information.
=== Example Usage
You can define a minimal @kubernetes_replication_controller@ via:
@
Kubernetes.newReplicationControllerR
(Kubernetes.ReplicationControllerR
{ Kubernetes.metadata = metadata -- Expr s (ReplicationControllerMetadata s)
, Kubernetes.spec = spec -- Expr s (ReplicationControllerSpec s)
})
@
=== Argument Reference
The following arguments are supported:
@
#metadata :: Lens' (Resource ReplicationControllerR s) (Expr s (ReplicationControllerMetadata s))
#spec :: Lens' (Resource ReplicationControllerR s) (Expr s (ReplicationControllerSpec s))
@
=== Attributes Reference
In addition to the arguments above, the following computed attributes are available:
@
#id :: Getting r (Ref ReplicationControllerR s) (Expr s Id)
@
=== Configuring Meta-parameters
The following additional configuration is supported:
@
#prevent_destroy :: Lens' (Resource ReplicationControllerR s) Bool
#create_before_destroy :: Lens' (Resource ReplicationControllerR s) Bool
#ignore_changes :: Lens' (Resource ReplicationControllerR s) (Changes s)
#depends_on :: Lens' (Resource ReplicationControllerR s) (Set (Depends s))
#provider :: Lens' (Resource ReplicationControllerR s) (Maybe Kubernetes)
@
-}
newReplicationControllerR
:: ReplicationControllerR s -- ^ The minimal/required arguments.
-> P.Resource ReplicationControllerR s
newReplicationControllerR =
TF.unsafeResource "kubernetes_replication_controller" Encode.metadata
(\ReplicationControllerR{..} ->
P.mempty
<> TF.pair "metadata" metadata
<> TF.pair "spec" spec
)
instance Lens.HasField "metadata" f (P.Resource ReplicationControllerR s) (TF.Expr s (ReplicationControllerMetadata s)) where
field = Lens.resourceLens P.. Lens.lens'
(metadata :: ReplicationControllerR s -> TF.Expr s (ReplicationControllerMetadata s))
(\s a -> s { metadata = a } :: ReplicationControllerR s)
instance Lens.HasField "spec" f (P.Resource ReplicationControllerR s) (TF.Expr s (ReplicationControllerSpec s)) where
field = Lens.resourceLens P.. Lens.lens'
(spec :: ReplicationControllerR s -> TF.Expr s (ReplicationControllerSpec s))
(\s a -> s { spec = a } :: ReplicationControllerR s)
instance Lens.HasField "id" (P.Const r) (TF.Ref ReplicationControllerR s) (TF.Expr s TF.Id) where
field = Lens.to (TF.unsafeComputed Encode.attribute (proxy# :: Proxy# "id"))
| The main @kubernetes_resource_quota@ resource definition .
data ResourceQuotaR s = ResourceQuotaR_Internal
{ metadata :: TF.Expr s (ResourceQuotaMetadata s)
-- ^ @metadata@
-- - (Required)
-- Standard resource quota's metadata. More info:
-- -conventions.md#metadata
, spec :: P.Maybe (TF.Expr s (ResourceQuotaSpec s))
-- ^ @spec@
-- - (Optional)
Spec defines the desired quota .
-conventions.md#spec-and-status
} deriving (P.Show)
| Construct a new @kubernetes_resource_quota@ resource . The
available argument lenses and computed attribute getters are documented below .
See the < terraform documentation > for more information .
= = = Example Usage
You can define a minimal @kubernetes_resource_quota@ via :
@
Kubernetes.newResourceQuotaR
( Kubernetes . ResourceQuotaR
{ Kubernetes.metadata = metadata -- s ( ResourceQuotaMetadata s )
} )
@
= = = Argument Reference
The following arguments are supported :
@
# metadata : : ' ( Resource ResourceQuotaR s ) ( s ( ResourceQuotaMetadata s ) )
# spec : : Lens ' ( Resource ResourceQuotaR s ) ( Maybe ( s ( ResourceQuotaSpec s ) ) )
@
= = = Attributes Reference
In addition to the arguments above , the following computed attributes are available :
@
# i d : : Getting r ( Ref ResourceQuotaR s ) ( s I d )
@
= = = Configuring Meta - parameters
The following additional configuration is supported :
@
# prevent_destroy : : Lens ' ( Resource ResourceQuotaR s ) Bool
# create_before_destroy : : ' ( Resource ResourceQuotaR s ) Bool
# ignore_changes : : ' ( Resource ResourceQuotaR s ) ( Changes s )
# depends_on : : ' ( Resource ResourceQuotaR s ) ( Set ( Depends s ) )
# provider : : ' ( Resource ResourceQuotaR s ) ( Maybe Kubernetes )
@
available argument lenses and computed attribute getters are documented below.
See the < terraform documentation> for more information.
=== Example Usage
You can define a minimal @kubernetes_resource_quota@ via:
@
Kubernetes.newResourceQuotaR
(Kubernetes.ResourceQuotaR
{ Kubernetes.metadata = metadata -- Expr s (ResourceQuotaMetadata s)
})
@
=== Argument Reference
The following arguments are supported:
@
#metadata :: Lens' (Resource ResourceQuotaR s) (Expr s (ResourceQuotaMetadata s))
#spec :: Lens' (Resource ResourceQuotaR s) (Maybe (Expr s (ResourceQuotaSpec s)))
@
=== Attributes Reference
In addition to the arguments above, the following computed attributes are available:
@
#id :: Getting r (Ref ResourceQuotaR s) (Expr s Id)
@
=== Configuring Meta-parameters
The following additional configuration is supported:
@
#prevent_destroy :: Lens' (Resource ResourceQuotaR s) Bool
#create_before_destroy :: Lens' (Resource ResourceQuotaR s) Bool
#ignore_changes :: Lens' (Resource ResourceQuotaR s) (Changes s)
#depends_on :: Lens' (Resource ResourceQuotaR s) (Set (Depends s))
#provider :: Lens' (Resource ResourceQuotaR s) (Maybe Kubernetes)
@
-}
newResourceQuotaR
:: ResourceQuotaR_Required s -- ^ The minimal/required arguments.
-> P.Resource ResourceQuotaR s
newResourceQuotaR x =
TF.unsafeResource "kubernetes_resource_quota" Encode.metadata
(\ResourceQuotaR_Internal{..} ->
P.mempty
<> TF.pair "metadata" metadata
<> P.maybe P.mempty (TF.pair "spec") spec
)
(let ResourceQuotaR{..} = x in ResourceQuotaR_Internal
{ metadata = metadata
, spec = P.Nothing
})
-- | The required arguments for 'newResourceQuotaR'.
data ResourceQuotaR_Required s = ResourceQuotaR
{ metadata :: TF.Expr s (ResourceQuotaMetadata s)
-- ^ (Required)
-- Standard resource quota's metadata. More info:
-- -conventions.md#metadata
} deriving (P.Show)
instance Lens.HasField "metadata" f (P.Resource ResourceQuotaR s) (TF.Expr s (ResourceQuotaMetadata s)) where
field = Lens.resourceLens P.. Lens.lens'
(metadata :: ResourceQuotaR s -> TF.Expr s (ResourceQuotaMetadata s))
(\s a -> s { metadata = a } :: ResourceQuotaR s)
instance Lens.HasField "spec" f (P.Resource ResourceQuotaR s) (P.Maybe (TF.Expr s (ResourceQuotaSpec s))) where
field = Lens.resourceLens P.. Lens.lens'
(spec :: ResourceQuotaR s -> P.Maybe (TF.Expr s (ResourceQuotaSpec s)))
(\s a -> s { spec = a } :: ResourceQuotaR s)
instance Lens.HasField "id" (P.Const r) (TF.Ref ResourceQuotaR s) (TF.Expr s TF.Id) where
field = Lens.to (TF.unsafeComputed Encode.attribute (proxy# :: Proxy# "id"))
-- | The main @kubernetes_secret@ resource definition.
data SecretR s = SecretR_Internal
{ data_ :: P.Maybe (TF.Expr s (P.Map P.Text (TF.Expr s P.Text)))
-- ^ @data@
-- - (Optional)
-- A map of the secret data.
, metadata :: TF.Expr s (SecretMetadata s)
-- ^ @metadata@
-- - (Required)
-- Standard secret's metadata. More info:
-- -conventions.md#metadata
, type_ :: TF.Expr s P.Text
-- ^ @type@
-- - (Default __@Opaque@__, Forces New)
-- Type of secret
} deriving (P.Show)
| Construct a new @kubernetes_secret@ resource . The
available argument lenses and computed attribute getters are documented below .
See the < terraform documentation > for more information .
= = = Example Usage
You can define a minimal @kubernetes_secret@ via :
@
Kubernetes.newSecretR
( Kubernetes . SecretR
{ Kubernetes.metadata = metadata -- s ( SecretMetadata s )
} )
@
= = = Argument Reference
The following arguments are supported :
@
# data : : ' ( Resource SecretR s ) ( Maybe ( s ( Map Text ( Expr s Text ) ) ) )
# metadata : : ' ( Resource SecretR s ) ( s ( SecretMetadata s ) )
# type : : ' ( Resource SecretR s ) ( Expr s Text )
@
= = = Attributes Reference
In addition to the arguments above , the following computed attributes are available :
@
# i d : : Getting r ( Ref SecretR s ) ( s I d )
@
= = = Configuring Meta - parameters
The following additional configuration is supported :
@
# prevent_destroy : : Lens ' ( Resource SecretR s ) Bool
# create_before_destroy : : ' ( Resource SecretR s ) Bool
# ignore_changes : : ' ( Resource SecretR s ) ( Changes s )
# depends_on : : ' ( Resource SecretR s ) ( Set ( Depends s ) )
# provider : : ' ( Resource SecretR s ) ( Maybe Kubernetes )
@
available argument lenses and computed attribute getters are documented below.
See the < terraform documentation> for more information.
=== Example Usage
You can define a minimal @kubernetes_secret@ via:
@
Kubernetes.newSecretR
(Kubernetes.SecretR
{ Kubernetes.metadata = metadata -- Expr s (SecretMetadata s)
})
@
=== Argument Reference
The following arguments are supported:
@
#data :: Lens' (Resource SecretR s) (Maybe (Expr s (Map Text (Expr s Text))))
#metadata :: Lens' (Resource SecretR s) (Expr s (SecretMetadata s))
#type :: Lens' (Resource SecretR s) (Expr s Text)
@
=== Attributes Reference
In addition to the arguments above, the following computed attributes are available:
@
#id :: Getting r (Ref SecretR s) (Expr s Id)
@
=== Configuring Meta-parameters
The following additional configuration is supported:
@
#prevent_destroy :: Lens' (Resource SecretR s) Bool
#create_before_destroy :: Lens' (Resource SecretR s) Bool
#ignore_changes :: Lens' (Resource SecretR s) (Changes s)
#depends_on :: Lens' (Resource SecretR s) (Set (Depends s))
#provider :: Lens' (Resource SecretR s) (Maybe Kubernetes)
@
-}
newSecretR
:: SecretR_Required s -- ^ The minimal/required arguments.
-> P.Resource SecretR s
newSecretR x =
TF.unsafeResource "kubernetes_secret" Encode.metadata
(\SecretR_Internal{..} ->
P.mempty
<> P.maybe P.mempty (TF.pair "data") data_
<> TF.pair "metadata" metadata
<> TF.pair "type" type_
)
(let SecretR{..} = x in SecretR_Internal
{ data_ = P.Nothing
, metadata = metadata
, type_ = TF.expr "Opaque"
})
| The required arguments for ' newSecretR ' .
data SecretR_Required s = SecretR
{ metadata :: TF.Expr s (SecretMetadata s)
-- ^ (Required)
-- Standard secret's metadata. More info:
-- -conventions.md#metadata
} deriving (P.Show)
instance Lens.HasField "data" f (P.Resource SecretR s) (P.Maybe (TF.Expr s (P.Map P.Text (TF.Expr s P.Text)))) where
field = Lens.resourceLens P.. Lens.lens'
(data_ :: SecretR s -> P.Maybe (TF.Expr s (P.Map P.Text (TF.Expr s P.Text))))
(\s a -> s { data_ = a } :: SecretR s)
instance Lens.HasField "metadata" f (P.Resource SecretR s) (TF.Expr s (SecretMetadata s)) where
field = Lens.resourceLens P.. Lens.lens'
(metadata :: SecretR s -> TF.Expr s (SecretMetadata s))
(\s a -> s { metadata = a } :: SecretR s)
instance Lens.HasField "type" f (P.Resource SecretR s) (TF.Expr s P.Text) where
field = Lens.resourceLens P.. Lens.lens'
(type_ :: SecretR s -> TF.Expr s P.Text)
(\s a -> s { type_ = a } :: SecretR s)
instance Lens.HasField "id" (P.Const r) (TF.Ref SecretR s) (TF.Expr s TF.Id) where
field = Lens.to (TF.unsafeComputed Encode.attribute (proxy# :: Proxy# "id"))
| The main @kubernetes_service_account@ resource definition .
data ServiceAccountR s = ServiceAccountR_Internal
{ image_pull_secret :: P.Maybe (TF.Expr s [TF.Expr s (ServiceAccountImagePullSecret s)])
-- ^ @image_pull_secret@
-- - (Optional)
-- A list of references to secrets in the same namespace to use for pulling any
-- images in pods that reference this Service Account. More info:
-- -guide/secrets#manually-specifying-an-imagepullsecret
, metadata :: TF.Expr s (ServiceAccountMetadata s)
-- ^ @metadata@
-- - (Required)
-- Standard service account's metadata. More info:
-- -conventions.md#metadata
, secret :: P.Maybe (TF.Expr s [TF.Expr s (ServiceAccountSecret s)])
-- ^ @secret@
-- - (Optional)
A list of secrets allowed to be used by pods running using this Service
-- Account. More info: -guide/secrets
} deriving (P.Show)
| Construct a new @kubernetes_service_account@ resource . The
available argument lenses and computed attribute getters are documented below .
See the < terraform documentation > for more information .
= = = Example Usage
You can define a minimal @kubernetes_service_account@ via :
@
( Kubernetes . ServiceAccountR
{ Kubernetes.metadata = metadata -- s ( ServiceAccountMetadata s )
} )
@
= = = Argument Reference
The following arguments are supported :
@
# image_pull_secret : : Lens ' ( Resource ServiceAccountR s ) ( Maybe ( s [ s ( ServiceAccountImagePullSecret s ) ] ) )
# metadata : : ' ( Resource ServiceAccountR s ) ( s ( ServiceAccountMetadata s ) )
# secret : : Lens ' ( Resource ServiceAccountR s ) ( Maybe ( s [ s ( ServiceAccountSecret s ) ] ) )
@
= = = Attributes Reference
In addition to the arguments above , the following computed attributes are available :
@
# i d : : Getting r ( Ref ServiceAccountR s ) ( s I d )
# default_secret_name : : Getting r ( Ref ServiceAccountR s ) ( Expr s Text )
@
= = = Configuring Meta - parameters
The following additional configuration is supported :
@
# prevent_destroy : : Lens ' ( Resource ServiceAccountR s ) Bool
# create_before_destroy : : ' ( Resource ServiceAccountR s ) Bool
# ignore_changes : : ' ( Resource ServiceAccountR s ) ( Changes s )
# depends_on : : ' ( Resource ServiceAccountR s ) ( Set ( Depends s ) )
# provider : : ' ( Resource ServiceAccountR s ) ( Maybe Kubernetes )
@
available argument lenses and computed attribute getters are documented below.
See the < terraform documentation> for more information.
=== Example Usage
You can define a minimal @kubernetes_service_account@ via:
@
Kubernetes.newServiceAccountR
(Kubernetes.ServiceAccountR
{ Kubernetes.metadata = metadata -- Expr s (ServiceAccountMetadata s)
})
@
=== Argument Reference
The following arguments are supported:
@
#image_pull_secret :: Lens' (Resource ServiceAccountR s) (Maybe (Expr s [Expr s (ServiceAccountImagePullSecret s)]))
#metadata :: Lens' (Resource ServiceAccountR s) (Expr s (ServiceAccountMetadata s))
#secret :: Lens' (Resource ServiceAccountR s) (Maybe (Expr s [Expr s (ServiceAccountSecret s)]))
@
=== Attributes Reference
In addition to the arguments above, the following computed attributes are available:
@
#id :: Getting r (Ref ServiceAccountR s) (Expr s Id)
#default_secret_name :: Getting r (Ref ServiceAccountR s) (Expr s Text)
@
=== Configuring Meta-parameters
The following additional configuration is supported:
@
#prevent_destroy :: Lens' (Resource ServiceAccountR s) Bool
#create_before_destroy :: Lens' (Resource ServiceAccountR s) Bool
#ignore_changes :: Lens' (Resource ServiceAccountR s) (Changes s)
#depends_on :: Lens' (Resource ServiceAccountR s) (Set (Depends s))
#provider :: Lens' (Resource ServiceAccountR s) (Maybe Kubernetes)
@
-}
newServiceAccountR
:: ServiceAccountR_Required s -- ^ The minimal/required arguments.
-> P.Resource ServiceAccountR s
newServiceAccountR x =
TF.unsafeResource "kubernetes_service_account" Encode.metadata
(\ServiceAccountR_Internal{..} ->
P.mempty
<> P.maybe P.mempty (TF.pair "image_pull_secret") image_pull_secret
<> TF.pair "metadata" metadata
<> P.maybe P.mempty (TF.pair "secret") secret
)
(let ServiceAccountR{..} = x in ServiceAccountR_Internal
{ image_pull_secret = P.Nothing
, metadata = metadata
, secret = P.Nothing
})
| The required arguments for ' newServiceAccountR ' .
data ServiceAccountR_Required s = ServiceAccountR
{ metadata :: TF.Expr s (ServiceAccountMetadata s)
-- ^ (Required)
-- Standard service account's metadata. More info:
-- -conventions.md#metadata
} deriving (P.Show)
instance Lens.HasField "image_pull_secret" f (P.Resource ServiceAccountR s) (P.Maybe (TF.Expr s [TF.Expr s (ServiceAccountImagePullSecret s)])) where
field = Lens.resourceLens P.. Lens.lens'
(image_pull_secret :: ServiceAccountR s -> P.Maybe (TF.Expr s [TF.Expr s (ServiceAccountImagePullSecret s)]))
(\s a -> s { image_pull_secret = a } :: ServiceAccountR s)
instance Lens.HasField "metadata" f (P.Resource ServiceAccountR s) (TF.Expr s (ServiceAccountMetadata s)) where
field = Lens.resourceLens P.. Lens.lens'
(metadata :: ServiceAccountR s -> TF.Expr s (ServiceAccountMetadata s))
(\s a -> s { metadata = a } :: ServiceAccountR s)
instance Lens.HasField "secret" f (P.Resource ServiceAccountR s) (P.Maybe (TF.Expr s [TF.Expr s (ServiceAccountSecret s)])) where
field = Lens.resourceLens P.. Lens.lens'
(secret :: ServiceAccountR s -> P.Maybe (TF.Expr s [TF.Expr s (ServiceAccountSecret s)]))
(\s a -> s { secret = a } :: ServiceAccountR s)
instance Lens.HasField "id" (P.Const r) (TF.Ref ServiceAccountR s) (TF.Expr s TF.Id) where
field = Lens.to (TF.unsafeComputed Encode.attribute (proxy# :: Proxy# "id"))
instance Lens.HasField "default_secret_name" (P.Const r) (TF.Ref ServiceAccountR s) (TF.Expr s P.Text) where
field = Lens.to (TF.unsafeComputed Encode.attribute (proxy# :: Proxy# "default_secret_name"))
| The main @kubernetes_service@ resource definition .
data ServiceR s = ServiceR
{ metadata :: TF.Expr s (ServiceMetadata s)
-- ^ @metadata@
-- - (Required)
-- Standard service's metadata. More info:
-- -conventions.md#metadata
, spec :: TF.Expr s (ServiceSpec s)
-- ^ @spec@
-- - (Required)
Spec defines the behavior of a service .
-conventions.md#spec-and-status
} deriving (P.Show)
| Construct a new @kubernetes_service@ resource . The
available argument lenses and computed attribute getters are documented below .
See the < terraform documentation > for more information .
= = = Example Usage
You can define a minimal @kubernetes_service@ via :
@
( Kubernetes . ServiceR
{ Kubernetes.metadata = metadata -- s ( ServiceMetadata s )
, Kubernetes.spec = spec -- Expr s ( ServiceSpec s )
} )
@
= = = Argument Reference
The following arguments are supported :
@
# metadata : : ' ( Resource ServiceR s ) ( s ( ServiceMetadata s ) )
# spec : : ' ( Resource ServiceR s ) ( s ( ServiceSpec s ) )
@
= = = Attributes Reference
In addition to the arguments above , the following computed attributes are available :
@
# i d : : Getting r ( Ref ServiceR s ) ( s I d )
# load_balancer_ingress : : Getting r ( Ref ServiceR s ) ( s [ s ( ServiceLoadBalancerIngress s ) ] )
@
= = = Configuring Meta - parameters
The following additional configuration is supported :
@
# prevent_destroy : : Lens ' ( Resource ServiceR s ) Bool
# create_before_destroy : : ' ( Resource ServiceR s ) Bool
# ignore_changes : : ' ( Resource ServiceR s ) ( Changes s )
# depends_on : : ' ( Resource ServiceR s ) ( Set ( Depends s ) )
# provider : : ' ( Resource ServiceR s ) ( Maybe Kubernetes )
@
available argument lenses and computed attribute getters are documented below.
See the < terraform documentation> for more information.
=== Example Usage
You can define a minimal @kubernetes_service@ via:
@
Kubernetes.newServiceR
(Kubernetes.ServiceR
{ Kubernetes.metadata = metadata -- Expr s (ServiceMetadata s)
, Kubernetes.spec = spec -- Expr s (ServiceSpec s)
})
@
=== Argument Reference
The following arguments are supported:
@
#metadata :: Lens' (Resource ServiceR s) (Expr s (ServiceMetadata s))
#spec :: Lens' (Resource ServiceR s) (Expr s (ServiceSpec s))
@
=== Attributes Reference
In addition to the arguments above, the following computed attributes are available:
@
#id :: Getting r (Ref ServiceR s) (Expr s Id)
#load_balancer_ingress :: Getting r (Ref ServiceR s) (Expr s [Expr s (ServiceLoadBalancerIngress s)])
@
=== Configuring Meta-parameters
The following additional configuration is supported:
@
#prevent_destroy :: Lens' (Resource ServiceR s) Bool
#create_before_destroy :: Lens' (Resource ServiceR s) Bool
#ignore_changes :: Lens' (Resource ServiceR s) (Changes s)
#depends_on :: Lens' (Resource ServiceR s) (Set (Depends s))
#provider :: Lens' (Resource ServiceR s) (Maybe Kubernetes)
@
-}
newServiceR
:: ServiceR s -- ^ The minimal/required arguments.
-> P.Resource ServiceR s
newServiceR =
TF.unsafeResource "kubernetes_service" Encode.metadata
(\ServiceR{..} ->
P.mempty
<> TF.pair "metadata" metadata
<> TF.pair "spec" spec
)
instance Lens.HasField "metadata" f (P.Resource ServiceR s) (TF.Expr s (ServiceMetadata s)) where
field = Lens.resourceLens P.. Lens.lens'
(metadata :: ServiceR s -> TF.Expr s (ServiceMetadata s))
(\s a -> s { metadata = a } :: ServiceR s)
instance Lens.HasField "spec" f (P.Resource ServiceR s) (TF.Expr s (ServiceSpec s)) where
field = Lens.resourceLens P.. Lens.lens'
(spec :: ServiceR s -> TF.Expr s (ServiceSpec s))
(\s a -> s { spec = a } :: ServiceR s)
instance Lens.HasField "id" (P.Const r) (TF.Ref ServiceR s) (TF.Expr s TF.Id) where
field = Lens.to (TF.unsafeComputed Encode.attribute (proxy# :: Proxy# "id"))
instance Lens.HasField "load_balancer_ingress" (P.Const r) (TF.Ref ServiceR s) (TF.Expr s [TF.Expr s (ServiceLoadBalancerIngress s)]) where
field = Lens.to (TF.unsafeComputed Encode.attribute (proxy# :: Proxy# "load_balancer_ingress"))
| The main @kubernetes_storage_class@ resource definition .
data StorageClassR s = StorageClassR_Internal
{ metadata :: TF.Expr s (StorageClassMetadata s)
-- ^ @metadata@
-- - (Required)
-- Standard storage class's metadata. More info:
-- -conventions.md#metadata
, parameters :: P.Maybe (TF.Expr s (P.Map P.Text (TF.Expr s P.Text)))
-- ^ @parameters@
-- - (Optional, Forces New)
-- The parameters for the provisioner that should create volumes of this
-- storage class
, storage_provisioner :: TF.Expr s P.Text
-- ^ @storage_provisioner@
-- - (Required, Forces New)
-- Indicates the type of the provisioner
} deriving (P.Show)
| Construct a new @kubernetes_storage_class@ resource . The
available argument lenses and computed attribute getters are documented below .
See the < terraform documentation > for more information .
= = = Example Usage
You can define a minimal @kubernetes_storage_class@ via :
@
Kubernetes.newStorageClassR
( Kubernetes .
{ Kubernetes.metadata = metadata -- s ( StorageClassMetadata s )
, Kubernetes.storage_provisioner = storage_provisioner -- Expr s Text
} )
@
= = = Argument Reference
The following arguments are supported :
@
# metadata : : ' ( Resource StorageClassR s ) ( s ( StorageClassMetadata s ) )
# parameters : : ' ( Resource StorageClassR s ) ( Maybe ( s ( Map Text ( Expr s Text ) ) ) )
# storage_provisioner : : Lens ' ( Resource StorageClassR s ) ( Expr s Text )
@
= = = Attributes Reference
In addition to the arguments above , the following computed attributes are available :
@
# i d : : Getting r ( Ref StorageClassR s ) ( s I d )
@
= = = Configuring Meta - parameters
The following additional configuration is supported :
@
# prevent_destroy : : Lens ' ( Resource StorageClassR s ) Bool
# create_before_destroy : : ' ( Resource StorageClassR s ) Bool
# ignore_changes : : ' ( Resource StorageClassR s ) ( Changes s )
# depends_on : : ' ( Resource StorageClassR s ) ( Set ( Depends s ) )
# provider : : ' ( Resource StorageClassR s ) ( Maybe Kubernetes )
@
available argument lenses and computed attribute getters are documented below.
See the < terraform documentation> for more information.
=== Example Usage
You can define a minimal @kubernetes_storage_class@ via:
@
Kubernetes.newStorageClassR
(Kubernetes.StorageClassR
{ Kubernetes.metadata = metadata -- Expr s (StorageClassMetadata s)
, Kubernetes.storage_provisioner = storage_provisioner -- Expr s Text
})
@
=== Argument Reference
The following arguments are supported:
@
#metadata :: Lens' (Resource StorageClassR s) (Expr s (StorageClassMetadata s))
#parameters :: Lens' (Resource StorageClassR s) (Maybe (Expr s (Map Text (Expr s Text))))
#storage_provisioner :: Lens' (Resource StorageClassR s) (Expr s Text)
@
=== Attributes Reference
In addition to the arguments above, the following computed attributes are available:
@
#id :: Getting r (Ref StorageClassR s) (Expr s Id)
@
=== Configuring Meta-parameters
The following additional configuration is supported:
@
#prevent_destroy :: Lens' (Resource StorageClassR s) Bool
#create_before_destroy :: Lens' (Resource StorageClassR s) Bool
#ignore_changes :: Lens' (Resource StorageClassR s) (Changes s)
#depends_on :: Lens' (Resource StorageClassR s) (Set (Depends s))
#provider :: Lens' (Resource StorageClassR s) (Maybe Kubernetes)
@
-}
newStorageClassR
:: StorageClassR_Required s -- ^ The minimal/required arguments.
-> P.Resource StorageClassR s
newStorageClassR x =
TF.unsafeResource "kubernetes_storage_class" Encode.metadata
(\StorageClassR_Internal{..} ->
P.mempty
<> TF.pair "metadata" metadata
<> P.maybe P.mempty (TF.pair "parameters") parameters
<> TF.pair "storage_provisioner" storage_provisioner
)
(let StorageClassR{..} = x in StorageClassR_Internal
{ metadata = metadata
, parameters = P.Nothing
, storage_provisioner = storage_provisioner
})
-- | The required arguments for 'newStorageClassR'.
data StorageClassR_Required s = StorageClassR
{ metadata :: TF.Expr s (StorageClassMetadata s)
-- ^ (Required)
-- Standard storage class's metadata. More info:
-- -conventions.md#metadata
, storage_provisioner :: TF.Expr s P.Text
^ ( Required , Forces New )
-- Indicates the type of the provisioner
} deriving (P.Show)
instance Lens.HasField "metadata" f (P.Resource StorageClassR s) (TF.Expr s (StorageClassMetadata s)) where
field = Lens.resourceLens P.. Lens.lens'
(metadata :: StorageClassR s -> TF.Expr s (StorageClassMetadata s))
(\s a -> s { metadata = a } :: StorageClassR s)
instance Lens.HasField "parameters" f (P.Resource StorageClassR s) (P.Maybe (TF.Expr s (P.Map P.Text (TF.Expr s P.Text)))) where
field = Lens.resourceLens P.. Lens.lens'
(parameters :: StorageClassR s -> P.Maybe (TF.Expr s (P.Map P.Text (TF.Expr s P.Text))))
(\s a -> s { parameters = a } :: StorageClassR s)
instance Lens.HasField "storage_provisioner" f (P.Resource StorageClassR s) (TF.Expr s P.Text) where
field = Lens.resourceLens P.. Lens.lens'
(storage_provisioner :: StorageClassR s -> TF.Expr s P.Text)
(\s a -> s { storage_provisioner = a } :: StorageClassR s)
instance Lens.HasField "id" (P.Const r) (TF.Ref StorageClassR s) (TF.Expr s TF.Id) where
field = Lens.to (TF.unsafeComputed Encode.attribute (proxy# :: Proxy# "id"))
| null |
https://raw.githubusercontent.com/brendanhay/terrafomo/387a0e9341fb9cd5543ef8332dea126f50f1070e/provider/terrafomo-kubernetes/gen/Terrafomo/Kubernetes/Resources.hs
|
haskell
|
This module is auto-generated.
|
Stability : auto-generated
* kubernetes_config_map
* kubernetes_horizontal_pod_autoscaler
* kubernetes_limit_range
* kubernetes_namespace
* kubernetes_persistent_volume_claim
* kubernetes_persistent_volume
* kubernetes_replication_controller
* kubernetes_resource_quota
* kubernetes_service
| The main @kubernetes_config_map@ resource definition.
^ @data@
- (Optional)
A map of the configuration data.
^ @metadata@
- (Required)
Standard config map's metadata. More info:
-conventions.md#metadata
s ( ConfigMapMetadata s )
Expr s (ConfigMapMetadata s)
^ The minimal/required arguments.
| The required arguments for 'newConfigMapR'.
^ (Required)
Standard config map's metadata. More info:
-conventions.md#metadata
| The main @kubernetes_horizontal_pod_autoscaler@ resource definition.
^ @metadata@
- (Required)
Standard horizontal pod autoscaler's metadata. More info:
-conventions.md#metadata
^ @spec@
- (Required)
Behaviour of the autoscaler. More info:
s ( HorizontalPodAutoscalerMetadata s )
Expr s ( HorizontalPodAutoscalerSpec s )
Expr s (HorizontalPodAutoscalerMetadata s)
Expr s (HorizontalPodAutoscalerSpec s)
^ The minimal/required arguments.
^ @metadata@
- (Required)
Standard limit range's metadata. More info:
-conventions.md#metadata
^ @spec@
- (Optional)
s ( LimitRangeMetadata s )
Expr s (LimitRangeMetadata s)
^ The minimal/required arguments.
^ (Required)
Standard limit range's metadata. More info:
-conventions.md#metadata
| The main @kubernetes_namespace@ resource definition.
^ @metadata@
- (Required)
Standard namespace's metadata. More info:
-conventions.md#metadata
s ( NamespaceMetadata s )
Expr s (NamespaceMetadata s)
^ The minimal/required arguments.
| The main @kubernetes_persistent_volume_claim@ resource definition.
^ @metadata@
- (Required)
Standard persistent volume claim's metadata. More info:
-conventions.md#metadata
^ @spec@
- (Required, Forces New)
author. More info:
-guide/persistent-volumes#persistentvolumeclaims
^ @wait_until_bound@
- (Default __@true@__)
Whether to wait for the claim to reach `Bound` state (to find volume in
which to claim the space)
s ( PersistentVolumeClaimMetadata s )
Expr s ( PersistentVolumeClaimSpec s )
Expr s (PersistentVolumeClaimMetadata s)
Expr s (PersistentVolumeClaimSpec s)
^ The minimal/required arguments.
| The required arguments for 'newPersistentVolumeClaimR'.
^ (Required)
Standard persistent volume claim's metadata. More info:
-conventions.md#metadata
author. More info:
-guide/persistent-volumes#persistentvolumeclaims
^ @metadata@
- (Required)
Standard persistent volume's metadata. More info:
-conventions.md#metadata
^ @spec@
- (Required)
s ( PersistentVolumeMetadata s )
s [ s ( PersistentVolumeSpec s ) ]
Expr s (PersistentVolumeMetadata s)
Expr s [Expr s (PersistentVolumeSpec s)]
^ The minimal/required arguments.
| The main @kubernetes_pod@ resource definition.
^ @metadata@
- (Required)
Standard pod's metadata. More info:
-conventions.md#metadata
^ @spec@
- (Required)
s ( PodMetadata s )
s ( PodSpec s )
Expr s (PodMetadata s)
Expr s (PodSpec s)
^ The minimal/required arguments.
| The main @kubernetes_replication_controller@ resource definition.
^ @metadata@
- (Required)
Standard replication controller's metadata. More info:
-conventions.md#metadata
^ @spec@
- (Required)
controller. More info:
-conventions.md#spec-and-status
s ( ReplicationControllerMetadata s )
Expr s ( s )
Expr s (ReplicationControllerMetadata s)
Expr s (ReplicationControllerSpec s)
^ The minimal/required arguments.
^ @metadata@
- (Required)
Standard resource quota's metadata. More info:
-conventions.md#metadata
^ @spec@
- (Optional)
s ( ResourceQuotaMetadata s )
Expr s (ResourceQuotaMetadata s)
^ The minimal/required arguments.
| The required arguments for 'newResourceQuotaR'.
^ (Required)
Standard resource quota's metadata. More info:
-conventions.md#metadata
| The main @kubernetes_secret@ resource definition.
^ @data@
- (Optional)
A map of the secret data.
^ @metadata@
- (Required)
Standard secret's metadata. More info:
-conventions.md#metadata
^ @type@
- (Default __@Opaque@__, Forces New)
Type of secret
s ( SecretMetadata s )
Expr s (SecretMetadata s)
^ The minimal/required arguments.
^ (Required)
Standard secret's metadata. More info:
-conventions.md#metadata
^ @image_pull_secret@
- (Optional)
A list of references to secrets in the same namespace to use for pulling any
images in pods that reference this Service Account. More info:
-guide/secrets#manually-specifying-an-imagepullsecret
^ @metadata@
- (Required)
Standard service account's metadata. More info:
-conventions.md#metadata
^ @secret@
- (Optional)
Account. More info: -guide/secrets
s ( ServiceAccountMetadata s )
Expr s (ServiceAccountMetadata s)
^ The minimal/required arguments.
^ (Required)
Standard service account's metadata. More info:
-conventions.md#metadata
^ @metadata@
- (Required)
Standard service's metadata. More info:
-conventions.md#metadata
^ @spec@
- (Required)
s ( ServiceMetadata s )
Expr s ( ServiceSpec s )
Expr s (ServiceMetadata s)
Expr s (ServiceSpec s)
^ The minimal/required arguments.
^ @metadata@
- (Required)
Standard storage class's metadata. More info:
-conventions.md#metadata
^ @parameters@
- (Optional, Forces New)
The parameters for the provisioner that should create volumes of this
storage class
^ @storage_provisioner@
- (Required, Forces New)
Indicates the type of the provisioner
s ( StorageClassMetadata s )
Expr s Text
Expr s (StorageClassMetadata s)
Expr s Text
^ The minimal/required arguments.
| The required arguments for 'newStorageClassR'.
^ (Required)
Standard storage class's metadata. More info:
-conventions.md#metadata
Indicates the type of the provisioner
|
# LANGUAGE NoImplicitPrelude #
# LANGUAGE RecordWildCards #
# LANGUAGE StrictData #
# LANGUAGE UndecidableInstances #
# OPTIONS_GHC -fno - warn - unused - imports #
Module : . Kubernetes . Resources
Copyright : ( c ) 2017 - 2018
License : Mozilla Public License , v. 2.0 .
Maintainer : < brendan.g.hay+ >
Portability : non - portable ( GHC extensions )
module Terrafomo.Kubernetes.Resources
(
newConfigMapR
, ConfigMapR (..)
, ConfigMapR_Required (..)
, newHorizontalPodAutoscalerR
, HorizontalPodAutoscalerR (..)
, newLimitRangeR
, LimitRangeR (..)
, LimitRangeR_Required (..)
, newNamespaceR
, NamespaceR (..)
, newPersistentVolumeClaimR
, PersistentVolumeClaimR (..)
, PersistentVolumeClaimR_Required (..)
, newPersistentVolumeR
, PersistentVolumeR (..)
*
, newPodR
, PodR (..)
, newReplicationControllerR
, ReplicationControllerR (..)
, newResourceQuotaR
, ResourceQuotaR (..)
, ResourceQuotaR_Required (..)
*
, newSecretR
, SecretR (..)
, SecretR_Required (..)
* kubernetes_service_account
, newServiceAccountR
, ServiceAccountR (..)
, ServiceAccountR_Required (..)
, newServiceR
, ServiceR (..)
* kubernetes_storage_class
, newStorageClassR
, StorageClassR (..)
, StorageClassR_Required (..)
) where
import Data.Functor ((<$>))
import Data.Semigroup ((<>))
import GHC.Base (Proxy#, proxy#, ($))
import Terrafomo.Kubernetes.Settings
import qualified Data.Functor.Const as P
import qualified Data.List.NonEmpty as P
import qualified Data.Map.Strict as P
import qualified Data.Maybe as P
import qualified Data.Text.Lazy as P
import qualified Prelude as P
import qualified Terrafomo.Encode as Encode
import qualified Terrafomo.HCL as TF
import qualified Terrafomo.HIL as TF
import qualified Terrafomo.Kubernetes.Provider as P
import qualified Terrafomo.Kubernetes.Types as P
import qualified Terrafomo.Lens as Lens
import qualified Terrafomo.Schema as TF
data ConfigMapR s = ConfigMapR_Internal
{ data_ :: P.Maybe (TF.Expr s (P.Map P.Text (TF.Expr s P.Text)))
, metadata :: TF.Expr s (ConfigMapMetadata s)
} deriving (P.Show)
| Construct a new @kubernetes_config_map@ resource . The
available argument lenses and computed attribute getters are documented below .
See the < terraform documentation > for more information .
= = = Example Usage
You can define a minimal @kubernetes_config_map@ via :
@
Kubernetes.newConfigMapR
( Kubernetes . ConfigMapR
} )
@
= = = Argument Reference
The following arguments are supported :
@
# data : : Lens ' ( Resource ConfigMapR s ) ( Maybe ( s ( Map Text ( Expr s Text ) ) ) )
# metadata : : ' ( Resource ConfigMapR s ) ( s ( ConfigMapMetadata s ) )
@
= = = Attributes Reference
In addition to the arguments above , the following computed attributes are available :
@
# i d : : Getting r ( Ref ConfigMapR s ) ( s I d )
@
= = = Configuring Meta - parameters
The following additional configuration is supported :
@
# prevent_destroy : : Lens ' ( Resource ConfigMapR s ) Bool
# create_before_destroy : : ' ( Resource ConfigMapR s ) Bool
# ignore_changes : : ' ( Resource ConfigMapR s ) ( Changes s )
# depends_on : : ' ( Resource ConfigMapR s ) ( Set ( Depends s ) )
# provider : : ' ( Resource ConfigMapR s ) ( Maybe Kubernetes )
@
available argument lenses and computed attribute getters are documented below.
See the < terraform documentation> for more information.
=== Example Usage
You can define a minimal @kubernetes_config_map@ via:
@
Kubernetes.newConfigMapR
(Kubernetes.ConfigMapR
})
@
=== Argument Reference
The following arguments are supported:
@
#data :: Lens' (Resource ConfigMapR s) (Maybe (Expr s (Map Text (Expr s Text))))
#metadata :: Lens' (Resource ConfigMapR s) (Expr s (ConfigMapMetadata s))
@
=== Attributes Reference
In addition to the arguments above, the following computed attributes are available:
@
#id :: Getting r (Ref ConfigMapR s) (Expr s Id)
@
=== Configuring Meta-parameters
The following additional configuration is supported:
@
#prevent_destroy :: Lens' (Resource ConfigMapR s) Bool
#create_before_destroy :: Lens' (Resource ConfigMapR s) Bool
#ignore_changes :: Lens' (Resource ConfigMapR s) (Changes s)
#depends_on :: Lens' (Resource ConfigMapR s) (Set (Depends s))
#provider :: Lens' (Resource ConfigMapR s) (Maybe Kubernetes)
@
-}
newConfigMapR
-> P.Resource ConfigMapR s
newConfigMapR x =
TF.unsafeResource "kubernetes_config_map" Encode.metadata
(\ConfigMapR_Internal{..} ->
P.mempty
<> P.maybe P.mempty (TF.pair "data") data_
<> TF.pair "metadata" metadata
)
(let ConfigMapR{..} = x in ConfigMapR_Internal
{ data_ = P.Nothing
, metadata = metadata
})
data ConfigMapR_Required s = ConfigMapR
{ metadata :: TF.Expr s (ConfigMapMetadata s)
} deriving (P.Show)
instance Lens.HasField "data" f (P.Resource ConfigMapR s) (P.Maybe (TF.Expr s (P.Map P.Text (TF.Expr s P.Text)))) where
field = Lens.resourceLens P.. Lens.lens'
(data_ :: ConfigMapR s -> P.Maybe (TF.Expr s (P.Map P.Text (TF.Expr s P.Text))))
(\s a -> s { data_ = a } :: ConfigMapR s)
instance Lens.HasField "metadata" f (P.Resource ConfigMapR s) (TF.Expr s (ConfigMapMetadata s)) where
field = Lens.resourceLens P.. Lens.lens'
(metadata :: ConfigMapR s -> TF.Expr s (ConfigMapMetadata s))
(\s a -> s { metadata = a } :: ConfigMapR s)
instance Lens.HasField "id" (P.Const r) (TF.Ref ConfigMapR s) (TF.Expr s TF.Id) where
field = Lens.to (TF.unsafeComputed Encode.attribute (proxy# :: Proxy# "id"))
data HorizontalPodAutoscalerR s = HorizontalPodAutoscalerR
{ metadata :: TF.Expr s (HorizontalPodAutoscalerMetadata s)
, spec :: TF.Expr s (HorizontalPodAutoscalerSpec s)
-conventions.md#spec-and-status
} deriving (P.Show)
| Construct a new @kubernetes_horizontal_pod_autoscaler@ resource . The
available argument lenses and computed attribute getters are documented below .
See the < terraform documentation > for more information .
= = = Example Usage
You can define a minimal @kubernetes_horizontal_pod_autoscaler@ via :
@
( Kubernetes . HorizontalPodAutoscalerR
} )
@
= = = Argument Reference
The following arguments are supported :
@
# metadata : : ' ( Resource HorizontalPodAutoscalerR s ) ( s ( HorizontalPodAutoscalerMetadata s ) )
# spec : : ' ( Resource HorizontalPodAutoscalerR s ) ( s ( HorizontalPodAutoscalerSpec s ) )
@
= = = Attributes Reference
In addition to the arguments above , the following computed attributes are available :
@
# i d : : Getting r ( Ref HorizontalPodAutoscalerR s ) ( s I d )
@
= = = Configuring Meta - parameters
The following additional configuration is supported :
@
# prevent_destroy : : Lens ' ( Resource HorizontalPodAutoscalerR s ) Bool
# create_before_destroy : : ' ( Resource HorizontalPodAutoscalerR s ) Bool
# ignore_changes : : ' ( Resource HorizontalPodAutoscalerR s ) ( Changes s )
# depends_on : : ' ( Resource HorizontalPodAutoscalerR s ) ( Set ( Depends s ) )
# provider : : ' ( Resource HorizontalPodAutoscalerR s ) ( Maybe Kubernetes )
@
available argument lenses and computed attribute getters are documented below.
See the < terraform documentation> for more information.
=== Example Usage
You can define a minimal @kubernetes_horizontal_pod_autoscaler@ via:
@
Kubernetes.newHorizontalPodAutoscalerR
(Kubernetes.HorizontalPodAutoscalerR
})
@
=== Argument Reference
The following arguments are supported:
@
#metadata :: Lens' (Resource HorizontalPodAutoscalerR s) (Expr s (HorizontalPodAutoscalerMetadata s))
#spec :: Lens' (Resource HorizontalPodAutoscalerR s) (Expr s (HorizontalPodAutoscalerSpec s))
@
=== Attributes Reference
In addition to the arguments above, the following computed attributes are available:
@
#id :: Getting r (Ref HorizontalPodAutoscalerR s) (Expr s Id)
@
=== Configuring Meta-parameters
The following additional configuration is supported:
@
#prevent_destroy :: Lens' (Resource HorizontalPodAutoscalerR s) Bool
#create_before_destroy :: Lens' (Resource HorizontalPodAutoscalerR s) Bool
#ignore_changes :: Lens' (Resource HorizontalPodAutoscalerR s) (Changes s)
#depends_on :: Lens' (Resource HorizontalPodAutoscalerR s) (Set (Depends s))
#provider :: Lens' (Resource HorizontalPodAutoscalerR s) (Maybe Kubernetes)
@
-}
newHorizontalPodAutoscalerR
-> P.Resource HorizontalPodAutoscalerR s
newHorizontalPodAutoscalerR =
TF.unsafeResource "kubernetes_horizontal_pod_autoscaler" Encode.metadata
(\HorizontalPodAutoscalerR{..} ->
P.mempty
<> TF.pair "metadata" metadata
<> TF.pair "spec" spec
)
instance Lens.HasField "metadata" f (P.Resource HorizontalPodAutoscalerR s) (TF.Expr s (HorizontalPodAutoscalerMetadata s)) where
field = Lens.resourceLens P.. Lens.lens'
(metadata :: HorizontalPodAutoscalerR s -> TF.Expr s (HorizontalPodAutoscalerMetadata s))
(\s a -> s { metadata = a } :: HorizontalPodAutoscalerR s)
instance Lens.HasField "spec" f (P.Resource HorizontalPodAutoscalerR s) (TF.Expr s (HorizontalPodAutoscalerSpec s)) where
field = Lens.resourceLens P.. Lens.lens'
(spec :: HorizontalPodAutoscalerR s -> TF.Expr s (HorizontalPodAutoscalerSpec s))
(\s a -> s { spec = a } :: HorizontalPodAutoscalerR s)
instance Lens.HasField "id" (P.Const r) (TF.Ref HorizontalPodAutoscalerR s) (TF.Expr s TF.Id) where
field = Lens.to (TF.unsafeComputed Encode.attribute (proxy# :: Proxy# "id"))
| The main resource definition .
data LimitRangeR s = LimitRangeR_Internal
{ metadata :: TF.Expr s (LimitRangeMetadata s)
, spec :: P.Maybe (TF.Expr s (LimitRangeSpec s))
Spec defines the limits enforced . More info :
-conventions.md#spec-and-status
} deriving (P.Show)
| Construct a new resource . The
available argument lenses and computed attribute getters are documented below .
See the < terraform documentation > for more information .
= = = Example Usage
You can define a minimal via :
@
Kubernetes.newLimitRangeR
( Kubernetes . LimitRangeR
} )
@
= = = Argument Reference
The following arguments are supported :
@
# metadata : : ' ( Resource LimitRangeR s ) ( s ( LimitRangeMetadata s ) )
# spec : : ' ( Resource LimitRangeR s ) ( Maybe ( s ( LimitRangeSpec s ) ) )
@
= = = Attributes Reference
In addition to the arguments above , the following computed attributes are available :
@
# i d : : Getting r ( Ref LimitRangeR s ) ( s I d )
@
= = = Configuring Meta - parameters
The following additional configuration is supported :
@
# prevent_destroy : : Lens ' ( Resource LimitRangeR s ) Bool
# create_before_destroy : : ' ( Resource LimitRangeR s ) Bool
# ignore_changes : : ' ( Resource LimitRangeR s ) ( Changes s )
# depends_on : : ' ( Resource LimitRangeR s ) ( Set ( Depends s ) )
# provider : : ' ( Resource LimitRangeR s ) ( Maybe Kubernetes )
@
available argument lenses and computed attribute getters are documented below.
See the < terraform documentation> for more information.
=== Example Usage
You can define a minimal @kubernetes_limit_range@ via:
@
Kubernetes.newLimitRangeR
(Kubernetes.LimitRangeR
})
@
=== Argument Reference
The following arguments are supported:
@
#metadata :: Lens' (Resource LimitRangeR s) (Expr s (LimitRangeMetadata s))
#spec :: Lens' (Resource LimitRangeR s) (Maybe (Expr s (LimitRangeSpec s)))
@
=== Attributes Reference
In addition to the arguments above, the following computed attributes are available:
@
#id :: Getting r (Ref LimitRangeR s) (Expr s Id)
@
=== Configuring Meta-parameters
The following additional configuration is supported:
@
#prevent_destroy :: Lens' (Resource LimitRangeR s) Bool
#create_before_destroy :: Lens' (Resource LimitRangeR s) Bool
#ignore_changes :: Lens' (Resource LimitRangeR s) (Changes s)
#depends_on :: Lens' (Resource LimitRangeR s) (Set (Depends s))
#provider :: Lens' (Resource LimitRangeR s) (Maybe Kubernetes)
@
-}
newLimitRangeR
-> P.Resource LimitRangeR s
newLimitRangeR x =
TF.unsafeResource "kubernetes_limit_range" Encode.metadata
(\LimitRangeR_Internal{..} ->
P.mempty
<> TF.pair "metadata" metadata
<> P.maybe P.mempty (TF.pair "spec") spec
)
(let LimitRangeR{..} = x in LimitRangeR_Internal
{ metadata = metadata
, spec = P.Nothing
})
| The required arguments for ' newLimitRangeR ' .
data LimitRangeR_Required s = LimitRangeR
{ metadata :: TF.Expr s (LimitRangeMetadata s)
} deriving (P.Show)
instance Lens.HasField "metadata" f (P.Resource LimitRangeR s) (TF.Expr s (LimitRangeMetadata s)) where
field = Lens.resourceLens P.. Lens.lens'
(metadata :: LimitRangeR s -> TF.Expr s (LimitRangeMetadata s))
(\s a -> s { metadata = a } :: LimitRangeR s)
instance Lens.HasField "spec" f (P.Resource LimitRangeR s) (P.Maybe (TF.Expr s (LimitRangeSpec s))) where
field = Lens.resourceLens P.. Lens.lens'
(spec :: LimitRangeR s -> P.Maybe (TF.Expr s (LimitRangeSpec s)))
(\s a -> s { spec = a } :: LimitRangeR s)
instance Lens.HasField "id" (P.Const r) (TF.Ref LimitRangeR s) (TF.Expr s TF.Id) where
field = Lens.to (TF.unsafeComputed Encode.attribute (proxy# :: Proxy# "id"))
newtype NamespaceR s = NamespaceR
{ metadata :: TF.Expr s (NamespaceMetadata s)
} deriving (P.Show)
| Construct a new @kubernetes_namespace@ resource . The
available argument lenses and computed attribute getters are documented below .
See the < terraform documentation > for more information .
= = = Example Usage
You can define a minimal @kubernetes_namespace@ via :
@
Kubernetes.newNamespaceR
( Kubernetes . NamespaceR
} )
@
= = = Argument Reference
The following arguments are supported :
@
# metadata : : ' ( Resource NamespaceR s ) ( s ( NamespaceMetadata s ) )
@
= = = Attributes Reference
In addition to the arguments above , the following computed attributes are available :
@
# i d : : Getting r ( Ref NamespaceR s ) ( s I d )
@
= = = Configuring Meta - parameters
The following additional configuration is supported :
@
# prevent_destroy : : Lens ' ( Resource NamespaceR s ) Bool
# create_before_destroy : : ' ( Resource NamespaceR s ) Bool
# ignore_changes : : ' ( Resource NamespaceR s ) ( Changes s )
# depends_on : : ' ( Resource NamespaceR s ) ( Set ( Depends s ) )
# provider : : ' ( Resource NamespaceR s ) ( Maybe Kubernetes )
@
available argument lenses and computed attribute getters are documented below.
See the < terraform documentation> for more information.
=== Example Usage
You can define a minimal @kubernetes_namespace@ via:
@
Kubernetes.newNamespaceR
(Kubernetes.NamespaceR
})
@
=== Argument Reference
The following arguments are supported:
@
#metadata :: Lens' (Resource NamespaceR s) (Expr s (NamespaceMetadata s))
@
=== Attributes Reference
In addition to the arguments above, the following computed attributes are available:
@
#id :: Getting r (Ref NamespaceR s) (Expr s Id)
@
=== Configuring Meta-parameters
The following additional configuration is supported:
@
#prevent_destroy :: Lens' (Resource NamespaceR s) Bool
#create_before_destroy :: Lens' (Resource NamespaceR s) Bool
#ignore_changes :: Lens' (Resource NamespaceR s) (Changes s)
#depends_on :: Lens' (Resource NamespaceR s) (Set (Depends s))
#provider :: Lens' (Resource NamespaceR s) (Maybe Kubernetes)
@
-}
newNamespaceR
-> P.Resource NamespaceR s
newNamespaceR =
TF.unsafeResource "kubernetes_namespace" Encode.metadata
(\NamespaceR{..} ->
P.mempty
<> TF.pair "metadata" metadata
)
instance Lens.HasField "metadata" f (P.Resource NamespaceR s) (TF.Expr s (NamespaceMetadata s)) where
field = Lens.resourceLens P.. Lens.lens'
(metadata :: NamespaceR s -> TF.Expr s (NamespaceMetadata s))
(\s a -> s { metadata = a } :: NamespaceR s)
instance Lens.HasField "id" (P.Const r) (TF.Ref NamespaceR s) (TF.Expr s TF.Id) where
field = Lens.to (TF.unsafeComputed Encode.attribute (proxy# :: Proxy# "id"))
data PersistentVolumeClaimR s = PersistentVolumeClaimR_Internal
{ metadata :: TF.Expr s (PersistentVolumeClaimMetadata s)
, spec :: TF.Expr s (PersistentVolumeClaimSpec s)
Spec defines the desired characteristics of a volume requested by a pod
, wait_until_bound :: TF.Expr s P.Bool
} deriving (P.Show)
| Construct a new @kubernetes_persistent_volume_claim@ resource . The
available argument lenses and computed attribute getters are documented below .
See the < terraform documentation > for more information .
= = = Example Usage
You can define a minimal @kubernetes_persistent_volume_claim@ via :
@
Kubernetes.newPersistentVolumeClaimR
( Kubernetes . PersistentVolumeClaimR
} )
@
= = = Argument Reference
The following arguments are supported :
@
# metadata : : ' ( Resource PersistentVolumeClaimR s ) ( s ( PersistentVolumeClaimMetadata s ) )
# spec : : ' ( Resource PersistentVolumeClaimR s ) ( s ( PersistentVolumeClaimSpec s ) )
# wait_until_bound : : ' ( Resource PersistentVolumeClaimR s ) ( s Bool )
@
= = = Attributes Reference
In addition to the arguments above , the following computed attributes are available :
@
# i d : : Getting r ( Ref PersistentVolumeClaimR s ) ( s I d )
@
= = = Configuring Meta - parameters
The following additional configuration is supported :
@
# prevent_destroy : : Lens ' ( Resource PersistentVolumeClaimR s ) Bool
# create_before_destroy : : ' ( Resource PersistentVolumeClaimR s ) Bool
# ignore_changes : : ' ( Resource PersistentVolumeClaimR s ) ( Changes s )
# depends_on : : ' ( Resource PersistentVolumeClaimR s ) ( Set ( Depends s ) )
# provider : : ' ( Resource PersistentVolumeClaimR s ) ( Maybe Kubernetes )
@
available argument lenses and computed attribute getters are documented below.
See the < terraform documentation> for more information.
=== Example Usage
You can define a minimal @kubernetes_persistent_volume_claim@ via:
@
Kubernetes.newPersistentVolumeClaimR
(Kubernetes.PersistentVolumeClaimR
})
@
=== Argument Reference
The following arguments are supported:
@
#metadata :: Lens' (Resource PersistentVolumeClaimR s) (Expr s (PersistentVolumeClaimMetadata s))
#spec :: Lens' (Resource PersistentVolumeClaimR s) (Expr s (PersistentVolumeClaimSpec s))
#wait_until_bound :: Lens' (Resource PersistentVolumeClaimR s) (Expr s Bool)
@
=== Attributes Reference
In addition to the arguments above, the following computed attributes are available:
@
#id :: Getting r (Ref PersistentVolumeClaimR s) (Expr s Id)
@
=== Configuring Meta-parameters
The following additional configuration is supported:
@
#prevent_destroy :: Lens' (Resource PersistentVolumeClaimR s) Bool
#create_before_destroy :: Lens' (Resource PersistentVolumeClaimR s) Bool
#ignore_changes :: Lens' (Resource PersistentVolumeClaimR s) (Changes s)
#depends_on :: Lens' (Resource PersistentVolumeClaimR s) (Set (Depends s))
#provider :: Lens' (Resource PersistentVolumeClaimR s) (Maybe Kubernetes)
@
-}
newPersistentVolumeClaimR
-> P.Resource PersistentVolumeClaimR s
newPersistentVolumeClaimR x =
TF.unsafeResource "kubernetes_persistent_volume_claim" Encode.metadata
(\PersistentVolumeClaimR_Internal{..} ->
P.mempty
<> TF.pair "metadata" metadata
<> TF.pair "spec" spec
<> TF.pair "wait_until_bound" wait_until_bound
)
(let PersistentVolumeClaimR{..} = x in PersistentVolumeClaimR_Internal
{ metadata = metadata
, spec = spec
, wait_until_bound = TF.expr P.True
})
data PersistentVolumeClaimR_Required s = PersistentVolumeClaimR
{ metadata :: TF.Expr s (PersistentVolumeClaimMetadata s)
, spec :: TF.Expr s (PersistentVolumeClaimSpec s)
^ ( Required , Forces New )
Spec defines the desired characteristics of a volume requested by a pod
} deriving (P.Show)
instance Lens.HasField "metadata" f (P.Resource PersistentVolumeClaimR s) (TF.Expr s (PersistentVolumeClaimMetadata s)) where
field = Lens.resourceLens P.. Lens.lens'
(metadata :: PersistentVolumeClaimR s -> TF.Expr s (PersistentVolumeClaimMetadata s))
(\s a -> s { metadata = a } :: PersistentVolumeClaimR s)
instance Lens.HasField "spec" f (P.Resource PersistentVolumeClaimR s) (TF.Expr s (PersistentVolumeClaimSpec s)) where
field = Lens.resourceLens P.. Lens.lens'
(spec :: PersistentVolumeClaimR s -> TF.Expr s (PersistentVolumeClaimSpec s))
(\s a -> s { spec = a } :: PersistentVolumeClaimR s)
instance Lens.HasField "wait_until_bound" f (P.Resource PersistentVolumeClaimR s) (TF.Expr s P.Bool) where
field = Lens.resourceLens P.. Lens.lens'
(wait_until_bound :: PersistentVolumeClaimR s -> TF.Expr s P.Bool)
(\s a -> s { wait_until_bound = a } :: PersistentVolumeClaimR s)
instance Lens.HasField "id" (P.Const r) (TF.Ref PersistentVolumeClaimR s) (TF.Expr s TF.Id) where
field = Lens.to (TF.unsafeComputed Encode.attribute (proxy# :: Proxy# "id"))
| The main @kubernetes_persistent_volume@ resource definition .
data PersistentVolumeR s = PersistentVolumeR
{ metadata :: TF.Expr s (PersistentVolumeMetadata s)
, spec :: TF.Expr s [TF.Expr s (PersistentVolumeSpec s)]
Spec of the persistent volume owned by the cluster
} deriving (P.Show)
| Construct a new @kubernetes_persistent_volume@ resource . The
available argument lenses and computed attribute getters are documented below .
See the < terraform documentation > for more information .
= = = Example Usage
You can define a minimal @kubernetes_persistent_volume@ via :
@
Kubernetes.newPersistentVolumeR
( Kubernetes . PersistentVolumeR
} )
@
= = = Argument Reference
The following arguments are supported :
@
# metadata : : ' ( Resource PersistentVolumeR s ) ( s ( PersistentVolumeMetadata s ) )
# spec : : Lens ' ( Resource PersistentVolumeR s ) ( s [ s ( PersistentVolumeSpec s ) ] )
@
= = = Attributes Reference
In addition to the arguments above , the following computed attributes are available :
@
# i d : : Getting r ( Ref PersistentVolumeR s ) ( s I d )
@
= = = Configuring Meta - parameters
The following additional configuration is supported :
@
# prevent_destroy : : Lens ' ( Resource PersistentVolumeR s ) Bool
# create_before_destroy : : ' ( Resource PersistentVolumeR s ) Bool
# ignore_changes : : ' ( Resource PersistentVolumeR s ) ( Changes s )
# depends_on : : ' ( Resource PersistentVolumeR s ) ( Set ( Depends s ) )
# provider : : ' ( Resource PersistentVolumeR s ) ( Maybe Kubernetes )
@
available argument lenses and computed attribute getters are documented below.
See the < terraform documentation> for more information.
=== Example Usage
You can define a minimal @kubernetes_persistent_volume@ via:
@
Kubernetes.newPersistentVolumeR
(Kubernetes.PersistentVolumeR
})
@
=== Argument Reference
The following arguments are supported:
@
#metadata :: Lens' (Resource PersistentVolumeR s) (Expr s (PersistentVolumeMetadata s))
#spec :: Lens' (Resource PersistentVolumeR s) (Expr s [Expr s (PersistentVolumeSpec s)])
@
=== Attributes Reference
In addition to the arguments above, the following computed attributes are available:
@
#id :: Getting r (Ref PersistentVolumeR s) (Expr s Id)
@
=== Configuring Meta-parameters
The following additional configuration is supported:
@
#prevent_destroy :: Lens' (Resource PersistentVolumeR s) Bool
#create_before_destroy :: Lens' (Resource PersistentVolumeR s) Bool
#ignore_changes :: Lens' (Resource PersistentVolumeR s) (Changes s)
#depends_on :: Lens' (Resource PersistentVolumeR s) (Set (Depends s))
#provider :: Lens' (Resource PersistentVolumeR s) (Maybe Kubernetes)
@
-}
newPersistentVolumeR
-> P.Resource PersistentVolumeR s
newPersistentVolumeR =
TF.unsafeResource "kubernetes_persistent_volume" Encode.metadata
(\PersistentVolumeR{..} ->
P.mempty
<> TF.pair "metadata" metadata
<> TF.pair "spec" spec
)
instance Lens.HasField "metadata" f (P.Resource PersistentVolumeR s) (TF.Expr s (PersistentVolumeMetadata s)) where
field = Lens.resourceLens P.. Lens.lens'
(metadata :: PersistentVolumeR s -> TF.Expr s (PersistentVolumeMetadata s))
(\s a -> s { metadata = a } :: PersistentVolumeR s)
instance Lens.HasField "spec" f (P.Resource PersistentVolumeR s) (TF.Expr s [TF.Expr s (PersistentVolumeSpec s)]) where
field = Lens.resourceLens P.. Lens.lens'
(spec :: PersistentVolumeR s -> TF.Expr s [TF.Expr s (PersistentVolumeSpec s)])
(\s a -> s { spec = a } :: PersistentVolumeR s)
instance Lens.HasField "id" (P.Const r) (TF.Ref PersistentVolumeR s) (TF.Expr s TF.Id) where
field = Lens.to (TF.unsafeComputed Encode.attribute (proxy# :: Proxy# "id"))
data PodR s = PodR
{ metadata :: TF.Expr s (PodMetadata s)
, spec :: TF.Expr s (PodSpec s)
Spec of the pod owned by the cluster
} deriving (P.Show)
| Construct a new @kubernetes_pod@ resource . The
available argument lenses and computed attribute getters are documented below .
See the < terraform documentation > for more information .
= = = Example Usage
You can define a minimal @kubernetes_pod@ via :
@
Kubernetes.newPodR
( Kubernetes . PodR
} )
@
= = = Argument Reference
The following arguments are supported :
@
# metadata : : ' ( Resource PodR s ) ( s ( PodMetadata s ) )
# spec : : Lens ' ( Resource PodR s ) ( s ( PodSpec s ) )
@
= = = Attributes Reference
In addition to the arguments above , the following computed attributes are available :
@
# i d : : Getting r ( Ref PodR s ) ( s I d )
@
= = = Configuring Meta - parameters
The following additional configuration is supported :
@
# prevent_destroy : : Lens ' ( Resource PodR s ) Bool
# create_before_destroy : : ' ( Resource PodR s ) Bool
# ignore_changes : : ' ( Resource PodR s ) ( Changes s )
# depends_on : : ' ( Resource PodR s ) ( Set ( Depends s ) )
# provider : : ' ( Resource PodR s ) ( Maybe Kubernetes )
@
available argument lenses and computed attribute getters are documented below.
See the < terraform documentation> for more information.
=== Example Usage
You can define a minimal @kubernetes_pod@ via:
@
Kubernetes.newPodR
(Kubernetes.PodR
})
@
=== Argument Reference
The following arguments are supported:
@
#metadata :: Lens' (Resource PodR s) (Expr s (PodMetadata s))
#spec :: Lens' (Resource PodR s) (Expr s (PodSpec s))
@
=== Attributes Reference
In addition to the arguments above, the following computed attributes are available:
@
#id :: Getting r (Ref PodR s) (Expr s Id)
@
=== Configuring Meta-parameters
The following additional configuration is supported:
@
#prevent_destroy :: Lens' (Resource PodR s) Bool
#create_before_destroy :: Lens' (Resource PodR s) Bool
#ignore_changes :: Lens' (Resource PodR s) (Changes s)
#depends_on :: Lens' (Resource PodR s) (Set (Depends s))
#provider :: Lens' (Resource PodR s) (Maybe Kubernetes)
@
-}
newPodR
-> P.Resource PodR s
newPodR =
TF.unsafeResource "kubernetes_pod" Encode.metadata
(\PodR{..} ->
P.mempty
<> TF.pair "metadata" metadata
<> TF.pair "spec" spec
)
instance Lens.HasField "metadata" f (P.Resource PodR s) (TF.Expr s (PodMetadata s)) where
field = Lens.resourceLens P.. Lens.lens'
(metadata :: PodR s -> TF.Expr s (PodMetadata s))
(\s a -> s { metadata = a } :: PodR s)
instance Lens.HasField "spec" f (P.Resource PodR s) (TF.Expr s (PodSpec s)) where
field = Lens.resourceLens P.. Lens.lens'
(spec :: PodR s -> TF.Expr s (PodSpec s))
(\s a -> s { spec = a } :: PodR s)
instance Lens.HasField "id" (P.Const r) (TF.Ref PodR s) (TF.Expr s TF.Id) where
field = Lens.to (TF.unsafeComputed Encode.attribute (proxy# :: Proxy# "id"))
data ReplicationControllerR s = ReplicationControllerR
{ metadata :: TF.Expr s (ReplicationControllerMetadata s)
, spec :: TF.Expr s (ReplicationControllerSpec s)
Spec defines the specification of the desired behavior of the replication
} deriving (P.Show)
| Construct a new @kubernetes_replication_controller@ resource . The
available argument lenses and computed attribute getters are documented below .
See the < terraform documentation > for more information .
= = = Example Usage
You can define a minimal @kubernetes_replication_controller@ via :
@
( Kubernetes . ReplicationControllerR
} )
@
= = = Argument Reference
The following arguments are supported :
@
# metadata : : ' ( Resource ReplicationControllerR s ) ( s ( ReplicationControllerMetadata s ) )
# spec : : Lens ' ( Resource ReplicationControllerR s ) ( s ( s ) )
@
= = = Attributes Reference
In addition to the arguments above , the following computed attributes are available :
@
# i d : : Getting r ( Ref ReplicationControllerR s ) ( s I d )
@
= = = Configuring Meta - parameters
The following additional configuration is supported :
@
# prevent_destroy : : Lens ' ( Resource ReplicationControllerR s ) Bool
# create_before_destroy : : ' ( Resource ReplicationControllerR s ) Bool
# ignore_changes : : ' ( Resource ReplicationControllerR s ) ( Changes s )
# depends_on : : ' ( Resource ReplicationControllerR s ) ( Set ( Depends s ) )
# provider : : ' ( Resource ReplicationControllerR s ) ( Maybe Kubernetes )
@
available argument lenses and computed attribute getters are documented below.
See the < terraform documentation> for more information.
=== Example Usage
You can define a minimal @kubernetes_replication_controller@ via:
@
Kubernetes.newReplicationControllerR
(Kubernetes.ReplicationControllerR
})
@
=== Argument Reference
The following arguments are supported:
@
#metadata :: Lens' (Resource ReplicationControllerR s) (Expr s (ReplicationControllerMetadata s))
#spec :: Lens' (Resource ReplicationControllerR s) (Expr s (ReplicationControllerSpec s))
@
=== Attributes Reference
In addition to the arguments above, the following computed attributes are available:
@
#id :: Getting r (Ref ReplicationControllerR s) (Expr s Id)
@
=== Configuring Meta-parameters
The following additional configuration is supported:
@
#prevent_destroy :: Lens' (Resource ReplicationControllerR s) Bool
#create_before_destroy :: Lens' (Resource ReplicationControllerR s) Bool
#ignore_changes :: Lens' (Resource ReplicationControllerR s) (Changes s)
#depends_on :: Lens' (Resource ReplicationControllerR s) (Set (Depends s))
#provider :: Lens' (Resource ReplicationControllerR s) (Maybe Kubernetes)
@
-}
newReplicationControllerR
-> P.Resource ReplicationControllerR s
newReplicationControllerR =
TF.unsafeResource "kubernetes_replication_controller" Encode.metadata
(\ReplicationControllerR{..} ->
P.mempty
<> TF.pair "metadata" metadata
<> TF.pair "spec" spec
)
instance Lens.HasField "metadata" f (P.Resource ReplicationControllerR s) (TF.Expr s (ReplicationControllerMetadata s)) where
field = Lens.resourceLens P.. Lens.lens'
(metadata :: ReplicationControllerR s -> TF.Expr s (ReplicationControllerMetadata s))
(\s a -> s { metadata = a } :: ReplicationControllerR s)
instance Lens.HasField "spec" f (P.Resource ReplicationControllerR s) (TF.Expr s (ReplicationControllerSpec s)) where
field = Lens.resourceLens P.. Lens.lens'
(spec :: ReplicationControllerR s -> TF.Expr s (ReplicationControllerSpec s))
(\s a -> s { spec = a } :: ReplicationControllerR s)
instance Lens.HasField "id" (P.Const r) (TF.Ref ReplicationControllerR s) (TF.Expr s TF.Id) where
field = Lens.to (TF.unsafeComputed Encode.attribute (proxy# :: Proxy# "id"))
| The main @kubernetes_resource_quota@ resource definition .
data ResourceQuotaR s = ResourceQuotaR_Internal
{ metadata :: TF.Expr s (ResourceQuotaMetadata s)
, spec :: P.Maybe (TF.Expr s (ResourceQuotaSpec s))
Spec defines the desired quota .
-conventions.md#spec-and-status
} deriving (P.Show)
| Construct a new @kubernetes_resource_quota@ resource . The
available argument lenses and computed attribute getters are documented below .
See the < terraform documentation > for more information .
= = = Example Usage
You can define a minimal @kubernetes_resource_quota@ via :
@
Kubernetes.newResourceQuotaR
( Kubernetes . ResourceQuotaR
} )
@
= = = Argument Reference
The following arguments are supported :
@
# metadata : : ' ( Resource ResourceQuotaR s ) ( s ( ResourceQuotaMetadata s ) )
# spec : : Lens ' ( Resource ResourceQuotaR s ) ( Maybe ( s ( ResourceQuotaSpec s ) ) )
@
= = = Attributes Reference
In addition to the arguments above , the following computed attributes are available :
@
# i d : : Getting r ( Ref ResourceQuotaR s ) ( s I d )
@
= = = Configuring Meta - parameters
The following additional configuration is supported :
@
# prevent_destroy : : Lens ' ( Resource ResourceQuotaR s ) Bool
# create_before_destroy : : ' ( Resource ResourceQuotaR s ) Bool
# ignore_changes : : ' ( Resource ResourceQuotaR s ) ( Changes s )
# depends_on : : ' ( Resource ResourceQuotaR s ) ( Set ( Depends s ) )
# provider : : ' ( Resource ResourceQuotaR s ) ( Maybe Kubernetes )
@
available argument lenses and computed attribute getters are documented below.
See the < terraform documentation> for more information.
=== Example Usage
You can define a minimal @kubernetes_resource_quota@ via:
@
Kubernetes.newResourceQuotaR
(Kubernetes.ResourceQuotaR
})
@
=== Argument Reference
The following arguments are supported:
@
#metadata :: Lens' (Resource ResourceQuotaR s) (Expr s (ResourceQuotaMetadata s))
#spec :: Lens' (Resource ResourceQuotaR s) (Maybe (Expr s (ResourceQuotaSpec s)))
@
=== Attributes Reference
In addition to the arguments above, the following computed attributes are available:
@
#id :: Getting r (Ref ResourceQuotaR s) (Expr s Id)
@
=== Configuring Meta-parameters
The following additional configuration is supported:
@
#prevent_destroy :: Lens' (Resource ResourceQuotaR s) Bool
#create_before_destroy :: Lens' (Resource ResourceQuotaR s) Bool
#ignore_changes :: Lens' (Resource ResourceQuotaR s) (Changes s)
#depends_on :: Lens' (Resource ResourceQuotaR s) (Set (Depends s))
#provider :: Lens' (Resource ResourceQuotaR s) (Maybe Kubernetes)
@
-}
newResourceQuotaR
-> P.Resource ResourceQuotaR s
newResourceQuotaR x =
TF.unsafeResource "kubernetes_resource_quota" Encode.metadata
(\ResourceQuotaR_Internal{..} ->
P.mempty
<> TF.pair "metadata" metadata
<> P.maybe P.mempty (TF.pair "spec") spec
)
(let ResourceQuotaR{..} = x in ResourceQuotaR_Internal
{ metadata = metadata
, spec = P.Nothing
})
data ResourceQuotaR_Required s = ResourceQuotaR
{ metadata :: TF.Expr s (ResourceQuotaMetadata s)
} deriving (P.Show)
instance Lens.HasField "metadata" f (P.Resource ResourceQuotaR s) (TF.Expr s (ResourceQuotaMetadata s)) where
field = Lens.resourceLens P.. Lens.lens'
(metadata :: ResourceQuotaR s -> TF.Expr s (ResourceQuotaMetadata s))
(\s a -> s { metadata = a } :: ResourceQuotaR s)
instance Lens.HasField "spec" f (P.Resource ResourceQuotaR s) (P.Maybe (TF.Expr s (ResourceQuotaSpec s))) where
field = Lens.resourceLens P.. Lens.lens'
(spec :: ResourceQuotaR s -> P.Maybe (TF.Expr s (ResourceQuotaSpec s)))
(\s a -> s { spec = a } :: ResourceQuotaR s)
instance Lens.HasField "id" (P.Const r) (TF.Ref ResourceQuotaR s) (TF.Expr s TF.Id) where
field = Lens.to (TF.unsafeComputed Encode.attribute (proxy# :: Proxy# "id"))
data SecretR s = SecretR_Internal
{ data_ :: P.Maybe (TF.Expr s (P.Map P.Text (TF.Expr s P.Text)))
, metadata :: TF.Expr s (SecretMetadata s)
, type_ :: TF.Expr s P.Text
} deriving (P.Show)
| Construct a new @kubernetes_secret@ resource . The
available argument lenses and computed attribute getters are documented below .
See the < terraform documentation > for more information .
= = = Example Usage
You can define a minimal @kubernetes_secret@ via :
@
Kubernetes.newSecretR
( Kubernetes . SecretR
} )
@
= = = Argument Reference
The following arguments are supported :
@
# data : : ' ( Resource SecretR s ) ( Maybe ( s ( Map Text ( Expr s Text ) ) ) )
# metadata : : ' ( Resource SecretR s ) ( s ( SecretMetadata s ) )
# type : : ' ( Resource SecretR s ) ( Expr s Text )
@
= = = Attributes Reference
In addition to the arguments above , the following computed attributes are available :
@
# i d : : Getting r ( Ref SecretR s ) ( s I d )
@
= = = Configuring Meta - parameters
The following additional configuration is supported :
@
# prevent_destroy : : Lens ' ( Resource SecretR s ) Bool
# create_before_destroy : : ' ( Resource SecretR s ) Bool
# ignore_changes : : ' ( Resource SecretR s ) ( Changes s )
# depends_on : : ' ( Resource SecretR s ) ( Set ( Depends s ) )
# provider : : ' ( Resource SecretR s ) ( Maybe Kubernetes )
@
available argument lenses and computed attribute getters are documented below.
See the < terraform documentation> for more information.
=== Example Usage
You can define a minimal @kubernetes_secret@ via:
@
Kubernetes.newSecretR
(Kubernetes.SecretR
})
@
=== Argument Reference
The following arguments are supported:
@
#data :: Lens' (Resource SecretR s) (Maybe (Expr s (Map Text (Expr s Text))))
#metadata :: Lens' (Resource SecretR s) (Expr s (SecretMetadata s))
#type :: Lens' (Resource SecretR s) (Expr s Text)
@
=== Attributes Reference
In addition to the arguments above, the following computed attributes are available:
@
#id :: Getting r (Ref SecretR s) (Expr s Id)
@
=== Configuring Meta-parameters
The following additional configuration is supported:
@
#prevent_destroy :: Lens' (Resource SecretR s) Bool
#create_before_destroy :: Lens' (Resource SecretR s) Bool
#ignore_changes :: Lens' (Resource SecretR s) (Changes s)
#depends_on :: Lens' (Resource SecretR s) (Set (Depends s))
#provider :: Lens' (Resource SecretR s) (Maybe Kubernetes)
@
-}
newSecretR
-> P.Resource SecretR s
newSecretR x =
TF.unsafeResource "kubernetes_secret" Encode.metadata
(\SecretR_Internal{..} ->
P.mempty
<> P.maybe P.mempty (TF.pair "data") data_
<> TF.pair "metadata" metadata
<> TF.pair "type" type_
)
(let SecretR{..} = x in SecretR_Internal
{ data_ = P.Nothing
, metadata = metadata
, type_ = TF.expr "Opaque"
})
| The required arguments for ' newSecretR ' .
data SecretR_Required s = SecretR
{ metadata :: TF.Expr s (SecretMetadata s)
} deriving (P.Show)
instance Lens.HasField "data" f (P.Resource SecretR s) (P.Maybe (TF.Expr s (P.Map P.Text (TF.Expr s P.Text)))) where
field = Lens.resourceLens P.. Lens.lens'
(data_ :: SecretR s -> P.Maybe (TF.Expr s (P.Map P.Text (TF.Expr s P.Text))))
(\s a -> s { data_ = a } :: SecretR s)
instance Lens.HasField "metadata" f (P.Resource SecretR s) (TF.Expr s (SecretMetadata s)) where
field = Lens.resourceLens P.. Lens.lens'
(metadata :: SecretR s -> TF.Expr s (SecretMetadata s))
(\s a -> s { metadata = a } :: SecretR s)
instance Lens.HasField "type" f (P.Resource SecretR s) (TF.Expr s P.Text) where
field = Lens.resourceLens P.. Lens.lens'
(type_ :: SecretR s -> TF.Expr s P.Text)
(\s a -> s { type_ = a } :: SecretR s)
instance Lens.HasField "id" (P.Const r) (TF.Ref SecretR s) (TF.Expr s TF.Id) where
field = Lens.to (TF.unsafeComputed Encode.attribute (proxy# :: Proxy# "id"))
| The main @kubernetes_service_account@ resource definition .
data ServiceAccountR s = ServiceAccountR_Internal
{ image_pull_secret :: P.Maybe (TF.Expr s [TF.Expr s (ServiceAccountImagePullSecret s)])
, metadata :: TF.Expr s (ServiceAccountMetadata s)
, secret :: P.Maybe (TF.Expr s [TF.Expr s (ServiceAccountSecret s)])
A list of secrets allowed to be used by pods running using this Service
} deriving (P.Show)
| Construct a new @kubernetes_service_account@ resource . The
available argument lenses and computed attribute getters are documented below .
See the < terraform documentation > for more information .
= = = Example Usage
You can define a minimal @kubernetes_service_account@ via :
@
( Kubernetes . ServiceAccountR
} )
@
= = = Argument Reference
The following arguments are supported :
@
# image_pull_secret : : Lens ' ( Resource ServiceAccountR s ) ( Maybe ( s [ s ( ServiceAccountImagePullSecret s ) ] ) )
# metadata : : ' ( Resource ServiceAccountR s ) ( s ( ServiceAccountMetadata s ) )
# secret : : Lens ' ( Resource ServiceAccountR s ) ( Maybe ( s [ s ( ServiceAccountSecret s ) ] ) )
@
= = = Attributes Reference
In addition to the arguments above , the following computed attributes are available :
@
# i d : : Getting r ( Ref ServiceAccountR s ) ( s I d )
# default_secret_name : : Getting r ( Ref ServiceAccountR s ) ( Expr s Text )
@
= = = Configuring Meta - parameters
The following additional configuration is supported :
@
# prevent_destroy : : Lens ' ( Resource ServiceAccountR s ) Bool
# create_before_destroy : : ' ( Resource ServiceAccountR s ) Bool
# ignore_changes : : ' ( Resource ServiceAccountR s ) ( Changes s )
# depends_on : : ' ( Resource ServiceAccountR s ) ( Set ( Depends s ) )
# provider : : ' ( Resource ServiceAccountR s ) ( Maybe Kubernetes )
@
available argument lenses and computed attribute getters are documented below.
See the < terraform documentation> for more information.
=== Example Usage
You can define a minimal @kubernetes_service_account@ via:
@
Kubernetes.newServiceAccountR
(Kubernetes.ServiceAccountR
})
@
=== Argument Reference
The following arguments are supported:
@
#image_pull_secret :: Lens' (Resource ServiceAccountR s) (Maybe (Expr s [Expr s (ServiceAccountImagePullSecret s)]))
#metadata :: Lens' (Resource ServiceAccountR s) (Expr s (ServiceAccountMetadata s))
#secret :: Lens' (Resource ServiceAccountR s) (Maybe (Expr s [Expr s (ServiceAccountSecret s)]))
@
=== Attributes Reference
In addition to the arguments above, the following computed attributes are available:
@
#id :: Getting r (Ref ServiceAccountR s) (Expr s Id)
#default_secret_name :: Getting r (Ref ServiceAccountR s) (Expr s Text)
@
=== Configuring Meta-parameters
The following additional configuration is supported:
@
#prevent_destroy :: Lens' (Resource ServiceAccountR s) Bool
#create_before_destroy :: Lens' (Resource ServiceAccountR s) Bool
#ignore_changes :: Lens' (Resource ServiceAccountR s) (Changes s)
#depends_on :: Lens' (Resource ServiceAccountR s) (Set (Depends s))
#provider :: Lens' (Resource ServiceAccountR s) (Maybe Kubernetes)
@
-}
newServiceAccountR
-> P.Resource ServiceAccountR s
newServiceAccountR x =
TF.unsafeResource "kubernetes_service_account" Encode.metadata
(\ServiceAccountR_Internal{..} ->
P.mempty
<> P.maybe P.mempty (TF.pair "image_pull_secret") image_pull_secret
<> TF.pair "metadata" metadata
<> P.maybe P.mempty (TF.pair "secret") secret
)
(let ServiceAccountR{..} = x in ServiceAccountR_Internal
{ image_pull_secret = P.Nothing
, metadata = metadata
, secret = P.Nothing
})
| The required arguments for ' newServiceAccountR ' .
data ServiceAccountR_Required s = ServiceAccountR
{ metadata :: TF.Expr s (ServiceAccountMetadata s)
} deriving (P.Show)
instance Lens.HasField "image_pull_secret" f (P.Resource ServiceAccountR s) (P.Maybe (TF.Expr s [TF.Expr s (ServiceAccountImagePullSecret s)])) where
field = Lens.resourceLens P.. Lens.lens'
(image_pull_secret :: ServiceAccountR s -> P.Maybe (TF.Expr s [TF.Expr s (ServiceAccountImagePullSecret s)]))
(\s a -> s { image_pull_secret = a } :: ServiceAccountR s)
instance Lens.HasField "metadata" f (P.Resource ServiceAccountR s) (TF.Expr s (ServiceAccountMetadata s)) where
field = Lens.resourceLens P.. Lens.lens'
(metadata :: ServiceAccountR s -> TF.Expr s (ServiceAccountMetadata s))
(\s a -> s { metadata = a } :: ServiceAccountR s)
instance Lens.HasField "secret" f (P.Resource ServiceAccountR s) (P.Maybe (TF.Expr s [TF.Expr s (ServiceAccountSecret s)])) where
field = Lens.resourceLens P.. Lens.lens'
(secret :: ServiceAccountR s -> P.Maybe (TF.Expr s [TF.Expr s (ServiceAccountSecret s)]))
(\s a -> s { secret = a } :: ServiceAccountR s)
instance Lens.HasField "id" (P.Const r) (TF.Ref ServiceAccountR s) (TF.Expr s TF.Id) where
field = Lens.to (TF.unsafeComputed Encode.attribute (proxy# :: Proxy# "id"))
instance Lens.HasField "default_secret_name" (P.Const r) (TF.Ref ServiceAccountR s) (TF.Expr s P.Text) where
field = Lens.to (TF.unsafeComputed Encode.attribute (proxy# :: Proxy# "default_secret_name"))
| The main @kubernetes_service@ resource definition .
data ServiceR s = ServiceR
{ metadata :: TF.Expr s (ServiceMetadata s)
, spec :: TF.Expr s (ServiceSpec s)
Spec defines the behavior of a service .
-conventions.md#spec-and-status
} deriving (P.Show)
| Construct a new @kubernetes_service@ resource . The
available argument lenses and computed attribute getters are documented below .
See the < terraform documentation > for more information .
= = = Example Usage
You can define a minimal @kubernetes_service@ via :
@
( Kubernetes . ServiceR
} )
@
= = = Argument Reference
The following arguments are supported :
@
# metadata : : ' ( Resource ServiceR s ) ( s ( ServiceMetadata s ) )
# spec : : ' ( Resource ServiceR s ) ( s ( ServiceSpec s ) )
@
= = = Attributes Reference
In addition to the arguments above , the following computed attributes are available :
@
# i d : : Getting r ( Ref ServiceR s ) ( s I d )
# load_balancer_ingress : : Getting r ( Ref ServiceR s ) ( s [ s ( ServiceLoadBalancerIngress s ) ] )
@
= = = Configuring Meta - parameters
The following additional configuration is supported :
@
# prevent_destroy : : Lens ' ( Resource ServiceR s ) Bool
# create_before_destroy : : ' ( Resource ServiceR s ) Bool
# ignore_changes : : ' ( Resource ServiceR s ) ( Changes s )
# depends_on : : ' ( Resource ServiceR s ) ( Set ( Depends s ) )
# provider : : ' ( Resource ServiceR s ) ( Maybe Kubernetes )
@
available argument lenses and computed attribute getters are documented below.
See the < terraform documentation> for more information.
=== Example Usage
You can define a minimal @kubernetes_service@ via:
@
Kubernetes.newServiceR
(Kubernetes.ServiceR
})
@
=== Argument Reference
The following arguments are supported:
@
#metadata :: Lens' (Resource ServiceR s) (Expr s (ServiceMetadata s))
#spec :: Lens' (Resource ServiceR s) (Expr s (ServiceSpec s))
@
=== Attributes Reference
In addition to the arguments above, the following computed attributes are available:
@
#id :: Getting r (Ref ServiceR s) (Expr s Id)
#load_balancer_ingress :: Getting r (Ref ServiceR s) (Expr s [Expr s (ServiceLoadBalancerIngress s)])
@
=== Configuring Meta-parameters
The following additional configuration is supported:
@
#prevent_destroy :: Lens' (Resource ServiceR s) Bool
#create_before_destroy :: Lens' (Resource ServiceR s) Bool
#ignore_changes :: Lens' (Resource ServiceR s) (Changes s)
#depends_on :: Lens' (Resource ServiceR s) (Set (Depends s))
#provider :: Lens' (Resource ServiceR s) (Maybe Kubernetes)
@
-}
newServiceR
-> P.Resource ServiceR s
newServiceR =
TF.unsafeResource "kubernetes_service" Encode.metadata
(\ServiceR{..} ->
P.mempty
<> TF.pair "metadata" metadata
<> TF.pair "spec" spec
)
instance Lens.HasField "metadata" f (P.Resource ServiceR s) (TF.Expr s (ServiceMetadata s)) where
field = Lens.resourceLens P.. Lens.lens'
(metadata :: ServiceR s -> TF.Expr s (ServiceMetadata s))
(\s a -> s { metadata = a } :: ServiceR s)
instance Lens.HasField "spec" f (P.Resource ServiceR s) (TF.Expr s (ServiceSpec s)) where
field = Lens.resourceLens P.. Lens.lens'
(spec :: ServiceR s -> TF.Expr s (ServiceSpec s))
(\s a -> s { spec = a } :: ServiceR s)
instance Lens.HasField "id" (P.Const r) (TF.Ref ServiceR s) (TF.Expr s TF.Id) where
field = Lens.to (TF.unsafeComputed Encode.attribute (proxy# :: Proxy# "id"))
instance Lens.HasField "load_balancer_ingress" (P.Const r) (TF.Ref ServiceR s) (TF.Expr s [TF.Expr s (ServiceLoadBalancerIngress s)]) where
field = Lens.to (TF.unsafeComputed Encode.attribute (proxy# :: Proxy# "load_balancer_ingress"))
| The main @kubernetes_storage_class@ resource definition .
data StorageClassR s = StorageClassR_Internal
{ metadata :: TF.Expr s (StorageClassMetadata s)
, parameters :: P.Maybe (TF.Expr s (P.Map P.Text (TF.Expr s P.Text)))
, storage_provisioner :: TF.Expr s P.Text
} deriving (P.Show)
| Construct a new @kubernetes_storage_class@ resource . The
available argument lenses and computed attribute getters are documented below .
See the < terraform documentation > for more information .
= = = Example Usage
You can define a minimal @kubernetes_storage_class@ via :
@
Kubernetes.newStorageClassR
( Kubernetes .
} )
@
= = = Argument Reference
The following arguments are supported :
@
# metadata : : ' ( Resource StorageClassR s ) ( s ( StorageClassMetadata s ) )
# parameters : : ' ( Resource StorageClassR s ) ( Maybe ( s ( Map Text ( Expr s Text ) ) ) )
# storage_provisioner : : Lens ' ( Resource StorageClassR s ) ( Expr s Text )
@
= = = Attributes Reference
In addition to the arguments above , the following computed attributes are available :
@
# i d : : Getting r ( Ref StorageClassR s ) ( s I d )
@
= = = Configuring Meta - parameters
The following additional configuration is supported :
@
# prevent_destroy : : Lens ' ( Resource StorageClassR s ) Bool
# create_before_destroy : : ' ( Resource StorageClassR s ) Bool
# ignore_changes : : ' ( Resource StorageClassR s ) ( Changes s )
# depends_on : : ' ( Resource StorageClassR s ) ( Set ( Depends s ) )
# provider : : ' ( Resource StorageClassR s ) ( Maybe Kubernetes )
@
available argument lenses and computed attribute getters are documented below.
See the < terraform documentation> for more information.
=== Example Usage
You can define a minimal @kubernetes_storage_class@ via:
@
Kubernetes.newStorageClassR
(Kubernetes.StorageClassR
})
@
=== Argument Reference
The following arguments are supported:
@
#metadata :: Lens' (Resource StorageClassR s) (Expr s (StorageClassMetadata s))
#parameters :: Lens' (Resource StorageClassR s) (Maybe (Expr s (Map Text (Expr s Text))))
#storage_provisioner :: Lens' (Resource StorageClassR s) (Expr s Text)
@
=== Attributes Reference
In addition to the arguments above, the following computed attributes are available:
@
#id :: Getting r (Ref StorageClassR s) (Expr s Id)
@
=== Configuring Meta-parameters
The following additional configuration is supported:
@
#prevent_destroy :: Lens' (Resource StorageClassR s) Bool
#create_before_destroy :: Lens' (Resource StorageClassR s) Bool
#ignore_changes :: Lens' (Resource StorageClassR s) (Changes s)
#depends_on :: Lens' (Resource StorageClassR s) (Set (Depends s))
#provider :: Lens' (Resource StorageClassR s) (Maybe Kubernetes)
@
-}
newStorageClassR
-> P.Resource StorageClassR s
newStorageClassR x =
TF.unsafeResource "kubernetes_storage_class" Encode.metadata
(\StorageClassR_Internal{..} ->
P.mempty
<> TF.pair "metadata" metadata
<> P.maybe P.mempty (TF.pair "parameters") parameters
<> TF.pair "storage_provisioner" storage_provisioner
)
(let StorageClassR{..} = x in StorageClassR_Internal
{ metadata = metadata
, parameters = P.Nothing
, storage_provisioner = storage_provisioner
})
data StorageClassR_Required s = StorageClassR
{ metadata :: TF.Expr s (StorageClassMetadata s)
, storage_provisioner :: TF.Expr s P.Text
^ ( Required , Forces New )
} deriving (P.Show)
instance Lens.HasField "metadata" f (P.Resource StorageClassR s) (TF.Expr s (StorageClassMetadata s)) where
field = Lens.resourceLens P.. Lens.lens'
(metadata :: StorageClassR s -> TF.Expr s (StorageClassMetadata s))
(\s a -> s { metadata = a } :: StorageClassR s)
instance Lens.HasField "parameters" f (P.Resource StorageClassR s) (P.Maybe (TF.Expr s (P.Map P.Text (TF.Expr s P.Text)))) where
field = Lens.resourceLens P.. Lens.lens'
(parameters :: StorageClassR s -> P.Maybe (TF.Expr s (P.Map P.Text (TF.Expr s P.Text))))
(\s a -> s { parameters = a } :: StorageClassR s)
instance Lens.HasField "storage_provisioner" f (P.Resource StorageClassR s) (TF.Expr s P.Text) where
field = Lens.resourceLens P.. Lens.lens'
(storage_provisioner :: StorageClassR s -> TF.Expr s P.Text)
(\s a -> s { storage_provisioner = a } :: StorageClassR s)
instance Lens.HasField "id" (P.Const r) (TF.Ref StorageClassR s) (TF.Expr s TF.Id) where
field = Lens.to (TF.unsafeComputed Encode.attribute (proxy# :: Proxy# "id"))
|
33b8cc2c08f71f23edfdb94de4733b7e59bb4d52d75680360adc1cdc8e0dfe9c
|
Stedi-Public-Archive/cdk-clj
|
examples_test.clj
|
(ns stedi.cdk.examples-test
(:require [clojure.java.io :as io]
[clojure.java.shell :as sh]
[clojure.string :as string]
[clojure.test :refer [deftest testing is]]))
(def cdk-bin-path "node_modules/aws-cdk/bin/cdk")
(defn example-projects
[]
(->> (file-seq (io/file "examples"))
(map #(.split (str %) "/"))
(filter #(= 2 (count %)))
(map second)))
(defn synth
[project]
(let [{:keys [exit out err]}
(sh/with-sh-dir (format "examples/%s" project)
(sh/sh (str "../../" cdk-bin-path) "synth"))]
(when-not (= 0 exit)
(println (format "===== [%s] failed to synth! =====" project))
(when-not (string/blank? out)
(println)
(println "Out:")
(println)
(println out))
(when-not (string/blank? err)
(println)
(println "Err:")
(println)
(println err))
(throw (Exception. (str "An error occured running cdk synth. "
"Check logs for more info."))))
true))
(deftest ^:integration synth-examples-test
(assert (.exists (io/file cdk-bin-path)) "Could not find cdk executable. Did you run `npm install`?")
(doseq [project (example-projects)]
(testing (str "cdk synth " project)
(is (synth project)))))
| null |
https://raw.githubusercontent.com/Stedi-Public-Archive/cdk-clj/8de0174c47ef456f0c22a6bec0ca9845844cc818/test/stedi/cdk/examples_test.clj
|
clojure
|
(ns stedi.cdk.examples-test
(:require [clojure.java.io :as io]
[clojure.java.shell :as sh]
[clojure.string :as string]
[clojure.test :refer [deftest testing is]]))
(def cdk-bin-path "node_modules/aws-cdk/bin/cdk")
(defn example-projects
[]
(->> (file-seq (io/file "examples"))
(map #(.split (str %) "/"))
(filter #(= 2 (count %)))
(map second)))
(defn synth
[project]
(let [{:keys [exit out err]}
(sh/with-sh-dir (format "examples/%s" project)
(sh/sh (str "../../" cdk-bin-path) "synth"))]
(when-not (= 0 exit)
(println (format "===== [%s] failed to synth! =====" project))
(when-not (string/blank? out)
(println)
(println "Out:")
(println)
(println out))
(when-not (string/blank? err)
(println)
(println "Err:")
(println)
(println err))
(throw (Exception. (str "An error occured running cdk synth. "
"Check logs for more info."))))
true))
(deftest ^:integration synth-examples-test
(assert (.exists (io/file cdk-bin-path)) "Could not find cdk executable. Did you run `npm install`?")
(doseq [project (example-projects)]
(testing (str "cdk synth " project)
(is (synth project)))))
|
|
3a885054fea0224e0d22f9c85abbf053c9b95c4f0dc6ad976e39f62fe511622f
|
rmloveland/scheme48-0.53
|
mutation.scm
|
Copyright ( c ) 1993 - 1999 by and . See file COPYING .
; Package mutation tests
"
,translate =scheme48/ ./
,open packages compiler built-in-structures handle condition
,open interfaces table defpackage package-mutation
"
(define (try exp env . should-return-option)
(let ((val (ignore-errors (lambda () (eval exp env)))))
(if (if (null? should-return-option)
(error? val)
(not (if (eq? (car should-return-option) 'error)
(error? val)
(eq? val (car should-return-option)))))
(begin (write `(lost: ,exp => ,val))
(newline)))))
(define p1 (make-simple-package (list scheme) eval #f 'p1))
(try 'a p1 'error)
(try '(define a 'aa) p1)
(try 'a p1 'aa)
(try '(define (foo) b) p1)
(try '(foo) p1 'error)
(try '(define b 'bb) p1)
(try 'b p1 'bb)
(try '(foo) p1 'bb)
(define s1-sig (make-simple-interface 's1-sig '(((a b c d e f) value))))
(define s1 (make-structure p1 (lambda () s1-sig) 's1))
(define p2 (make-simple-package (list s1 scheme) eval #f 'p2))
(try 'b p2 'bb)
(try 'c p2 'error)
(try 'z p2 'error)
(try '(define (bar) c) p2)
(try '(bar) p2 'error)
(try '(define c 'cc) p1)
(try 'c p2 'cc)
(try '(bar) p2 'cc)
(try '(define (baz1) d) p1)
(try '(define (baz2) d) p2)
(try '(baz1) p1 'error)
(try '(baz2) p2 'error)
(try '(define d 'dd) p1)
(try '(baz1) p1 'dd)
(try '(baz2) p2 'dd)
Shadow
(try '(define d 'shadowed) p2)
(try '(baz1) p1 'dd)
(try '(baz2) p2 'shadowed)
Shadow undefined
(try '(define (moo1) f) p1)
(try '(define (moo2) f) p2)
(try '(define f 'ff) p2)
(try '(moo1) p1 'error)
(try '(moo2) p2 'ff)
(try '(define (quux1) e) p1)
(try '(define (quux2) e) p2)
(try '(define (quux3 x) (set! e x)) p1)
(try '(define (quux4 x) (set! e x)) p2)
;
(try '(quux1) p1 'error)
(try '(quux2) p2 'error)
(try '(quux3 'q3) p1 'error)
(try '(quux4 'q4) p2 'error)
;
(try '(define e 'ee) p1)
(try '(quux1) p1 'ee)
(try '(quux2) p2 'ee)
(try '(quux3 'q3) p1)
(try '(quux1) p1 'q3)
(try '(quux2) p2 'q3)
(try '(quux4 'q4) p2 'error)
;
(try '(define e 'ee2) p2)
(try '(quux1) p1 'q3)
(try '(quux2) p2 'ee2)
(try '(quux3 'qq3) p1)
(try '(quux4 'qq4) p2)
(try '(quux1) p1 'qq3)
(try '(quux2) p2 'qq4)
; (set-verify-later! really-verify-later!)
(define-interface s3-sig (export a b x y z))
(define s3
(make-structure p1 (lambda () s3-sig) 's3))
(define p4 (make-simple-package (list s3 scheme) eval #f 'p4))
(try '(define (fuu1) a) p4)
(try '(define (fuu2) d) p4)
(try '(fuu1) p4 'aa)
(try '(fuu2) p4 'error)
; Remove a, add d
(define-interface s3-sig (export b d x y z))
;(package-system-sentinel)
(try 'a p4 'error)
(try 'd p4 'dd)
(try '(fuu2) p4 'dd)
(try '(fuu1) p4 'error) ; Foo.
(define (table->alist t)
(let ((l '()))
(table-walk (lambda (key val) (set! l (cons (cons key val) l))) t)
l))
| null |
https://raw.githubusercontent.com/rmloveland/scheme48-0.53/1ae4531fac7150bd2af42d124da9b50dd1b89ec1/scheme/debug/mutation.scm
|
scheme
|
Package mutation tests
(set-verify-later! really-verify-later!)
Remove a, add d
(package-system-sentinel)
Foo.
|
Copyright ( c ) 1993 - 1999 by and . See file COPYING .
"
,translate =scheme48/ ./
,open packages compiler built-in-structures handle condition
,open interfaces table defpackage package-mutation
"
(define (try exp env . should-return-option)
(let ((val (ignore-errors (lambda () (eval exp env)))))
(if (if (null? should-return-option)
(error? val)
(not (if (eq? (car should-return-option) 'error)
(error? val)
(eq? val (car should-return-option)))))
(begin (write `(lost: ,exp => ,val))
(newline)))))
(define p1 (make-simple-package (list scheme) eval #f 'p1))
(try 'a p1 'error)
(try '(define a 'aa) p1)
(try 'a p1 'aa)
(try '(define (foo) b) p1)
(try '(foo) p1 'error)
(try '(define b 'bb) p1)
(try 'b p1 'bb)
(try '(foo) p1 'bb)
(define s1-sig (make-simple-interface 's1-sig '(((a b c d e f) value))))
(define s1 (make-structure p1 (lambda () s1-sig) 's1))
(define p2 (make-simple-package (list s1 scheme) eval #f 'p2))
(try 'b p2 'bb)
(try 'c p2 'error)
(try 'z p2 'error)
(try '(define (bar) c) p2)
(try '(bar) p2 'error)
(try '(define c 'cc) p1)
(try 'c p2 'cc)
(try '(bar) p2 'cc)
(try '(define (baz1) d) p1)
(try '(define (baz2) d) p2)
(try '(baz1) p1 'error)
(try '(baz2) p2 'error)
(try '(define d 'dd) p1)
(try '(baz1) p1 'dd)
(try '(baz2) p2 'dd)
Shadow
(try '(define d 'shadowed) p2)
(try '(baz1) p1 'dd)
(try '(baz2) p2 'shadowed)
Shadow undefined
(try '(define (moo1) f) p1)
(try '(define (moo2) f) p2)
(try '(define f 'ff) p2)
(try '(moo1) p1 'error)
(try '(moo2) p2 'ff)
(try '(define (quux1) e) p1)
(try '(define (quux2) e) p2)
(try '(define (quux3 x) (set! e x)) p1)
(try '(define (quux4 x) (set! e x)) p2)
(try '(quux1) p1 'error)
(try '(quux2) p2 'error)
(try '(quux3 'q3) p1 'error)
(try '(quux4 'q4) p2 'error)
(try '(define e 'ee) p1)
(try '(quux1) p1 'ee)
(try '(quux2) p2 'ee)
(try '(quux3 'q3) p1)
(try '(quux1) p1 'q3)
(try '(quux2) p2 'q3)
(try '(quux4 'q4) p2 'error)
(try '(define e 'ee2) p2)
(try '(quux1) p1 'q3)
(try '(quux2) p2 'ee2)
(try '(quux3 'qq3) p1)
(try '(quux4 'qq4) p2)
(try '(quux1) p1 'qq3)
(try '(quux2) p2 'qq4)
(define-interface s3-sig (export a b x y z))
(define s3
(make-structure p1 (lambda () s3-sig) 's3))
(define p4 (make-simple-package (list s3 scheme) eval #f 'p4))
(try '(define (fuu1) a) p4)
(try '(define (fuu2) d) p4)
(try '(fuu1) p4 'aa)
(try '(fuu2) p4 'error)
(define-interface s3-sig (export b d x y z))
(try 'a p4 'error)
(try 'd p4 'dd)
(try '(fuu2) p4 'dd)
(define (table->alist t)
(let ((l '()))
(table-walk (lambda (key val) (set! l (cons (cons key val) l))) t)
l))
|
b08f1f65e97054d5697770f7d7e3ec9cac4fd45294e719c914f7bf4f7a66acae
|
imteekay/functional-programming-learning-path
|
problem06.clj
|
;;
(= [:a :b :c] (list :a :b :c) (vec '(:a :b :c)) (vector :a :b :c))
| null |
https://raw.githubusercontent.com/imteekay/functional-programming-learning-path/07dac09c9fabfa54f8b4d80b62f43b092cb87b0d/programming_challenges/4clojure/problem06.clj
|
clojure
|
(= [:a :b :c] (list :a :b :c) (vec '(:a :b :c)) (vector :a :b :c))
|
|
491fbf92e3ba74f70d4463ee5878c30fbbb1d0dc58b99843ab670f5571929e37
|
witheve/eve-experiments
|
smil.clj
|
(ns server.smil
(:refer-clojure :exclude [read])
(:require [server.db :as db]
[server.util :refer [merge-state]]
[clojure.string :as string]
[clojure.tools.reader :as reader]
[clojure.tools.reader.reader-types :as reader-types]))
(def REMOVE_FACT 5)
(defn read [str]
(reader/read (reader-types/indexing-push-back-reader str)))
(defn syntax-error
([msg expr] (syntax-error msg expr nil))
([msg expr data]
(let [{:keys [line column end-line end-column]} (meta expr)
standard-data {:expr expr :line line :column column :end-line end-line :end-column end-column}]
(ex-info msg (merge standard-data data)))))
(defn splat-map [m]
(reduce-kv conj [] m))
Flatten vecs ( multi - returns ) in the given body
(defn congeal-body [body]
(vec (reduce #(if (vector? %2)
(into %1 %2)
(conj %1 %2))
[]
body)))
(defn as-query [expr]
(if (and (seq? expr) (= (first expr) 'query))
expr
(list 'query
(list '= 'return expr))))
(defn assert-queries [body]
(doseq [expr body]
;; @NOTE: Should this allow unions/chooses as well?
(when (or (not (seq? expr)) (not (= (first expr) 'query)))
(throw (syntax-error "All union/choose members must be queries" expr))))
body)
(defn validate-sort [sexpr args]
(doseq [[var dir] (partition 2 {:sorting args})]
(when-not (symbol? var)
(syntax-error "First argument of each pair must be a variable" sexpr {:var var :dir dir}))
(when-not (or (symbol? dir) (= "ascending" dir) (= "descending" dir))
(syntax-error "Second argument of each pair must be a direction" sexpr {:var var :dir dir}))))
(defn get-fields [sexpr]
(when (and (seq? sexpr) (#{'query 'union 'choose} (first sexpr)))
(vec (second sexpr))))
;; :args - positional arguments
: kwargs - keyword arguments
;; :rest - remaining arguments
;; :optional - arguments which may not be specified
;; :validate - optional function to validate the argument map
(def schemas {
;; Special forms
'insert-fact! nil
'remove-fact! nil
'fact nil
'define! nil ; Special due to multiple aliases
'query nil ; Special due to optional parameterization
'define-ui nil
Macros
'remove-by-t! {:args [:tick]}
'if {:args [:cond :then :else]}
;; native forms
'insert-fact-btu! {:args [:entity :attribute :value :bag] :kwargs [:tick] :optional #{:bag :tick}} ; bag can be inferred in SMIR
'sort {:rest :sorting :optional #{:return} :validate validate-sort}
'union {:args [:params] :rest :members :body true}
'choose {:args [:params] :rest :members :body true}
'not {:rest :body :body true}
'fact-btu {:args [:entity :attribute :value :bag] :kwargs [:tick] :optional #{:entity :attribute :value :bag :tick}}
'full-fact-btu {:args [:entity :attribute :value :bag] :kwargs [:tick] :optional #{:entity :attribute :value :bag :tick}}
'context {:kwargs [:bag :tick] :rest :body :optional #{:bag :tick :body} :body true}})
;; These are only needed for testing -- they'll be provided dynamically by the db at runtime
(def primitives {'= {:args [:a :b]}
'+ {:args [:a :b] :kwargs [:return] :optional #{:return}}
'- {:args [:a :b] :kwargs [:return] :optional #{:return}}
'* {:args [:a :b] :kwargs [:return] :optional #{:return}}
'/ {:args [:a :b] :kwargs [:return] :optional #{:return}}
'not= {:args [:a :b] :kwargs [:return] :optional #{:return}}
'> {:args [:a :b] :kwargs [:return] :optional #{:return}}
'>= {:args [:a :b] :kwargs [:return] :optional #{:return}}
'< {:args [:a :b] :kwargs [:return] :optional #{:return}}
'<= {:args [:a :b] :kwargs [:return] :optional #{:return}}
'str {:rest :a :kwargs [:return] :optional #{:return}}
'hash {:args [:a]}
'sum {:args [:a] :kwargs [:return] :optional #{:return}}})
(defn get-schema
([op] (or (get schemas op nil) (get primitives op nil)))
([db op]
(if (or (contains? schemas op) (contains? primitives op))
(get-schema op)
(or
(when-let [implication (and db (db/implication-of db (name op)))]
(let [args (map keyword (first implication))]
{:args (vec args) :optional (set args)}))
{})))) ;; @FIXME: Hack to allow unknown implications to be used if pre-expanded for multi-form expansions.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
Parse sexprs into argument hashmaps
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn parse-schema [schema sexpr]
1 . If a keyword has been shifted into : kw
;; A. If the value is also keyword, :kw is an implicit var binding
: kw is mapped manually to the value
2 . If the value is a keyword , shift it into : kw and stop accepting positionals
3 . If we have n't exhausted our positionals , shift a positional to map to the value
4 . If the form accepts a rest parameter , shift the value onto the rest list
(let [body (rest sexpr)
state (reduce
#(merge-state %1
(if (:kw %1)
(if (keyword? %2)
;; Implicit variable; sub in a symbol of the same name, set the next :kw
{:kw %2 :args {(:kw %1) (symbol (name (:kw %1)))}}
Normal KV pair ; use the : kw
{:kw nil :args {(:kw %1) %2}})
(if (keyword? %2)
;; Manual keyword, set the next :kw and cease being positional
{:position 0 :kw %2}
(if-let [kw (get (:args schema) (- (count (:args schema)) (:position %1)) nil)]
;; Positional value; use kw from (:args schema) and decrement (position
{:position (dec (:position %1)) :args {kw %2}}
(if (:rest schema)
;; If a rest argument is specified, dump excess args into it
(if (keyword? %2)
(throw (syntax-error "Keyword arguments must come before rest arguments" sexpr))
{:args {(:rest schema) [%2]}})
;; Too many arguments without names, bail
(throw (syntax-error
(str "Too many positional arguments without a rest argument. Expected " (count (:args schema)))
sexpr)))))))
{:args {} :kw nil :position (count (:args schema))} body)
state (merge-state state (if (:kw state)
{:kw nil :args {(:kw state) (symbol (name (:kw state)))}}
nil))]
(:args state)))
(defn parse-define [sexpr]
1 . If we 've started parsing the body , everything else gets pushed into the body
2 . If there 's an existing symbol in : ( alias )
;; A. If the value is a vec, shift the pair into the :header
( Aliases must be followed by their exported variables )
3 . If the value is a symbol , shift it into :
4 . Shift the value into the body
(let [{header :header body :body}
(reduce
#(merge-state
%1
;; If we've already entered the body, no more headers can follow
(if (> (count (:body %1)) 0)
{:body [%2]}
;; If we've already snatched an alias, it must be followed by a vec of vars
(if (:sym %1)
(if (vector? %2)
{:sym nil :header [(:sym %1) %2]}
(throw (syntax-error
(str "Implication alias " (:sym %1) " must be followed by a vec of exported variables")
sexpr)))
;; If our state is clear we can begin a new header (symbol) or enter the body (anything else)
(if (symbol? %2)
{:sym %2}
If no headers are defined before we try to enter the body , that 's a paddlin '
(if (> (count (:header %1)) 0)
{:body [%2]}
(throw (syntax-error "Implications must specify at least one alias" sexpr)))))))
{:header [] :body [] :sym nil} (rest sexpr))]
(if (> (count header) 0)
{:header header :body body}
(throw (syntax-error "Implications must specify at least one alias" sexpr)))))
(defn parse-query [sexpr]
(let [body (rest sexpr)
[params body] (if (or (vector? (first body)) (nil? (first body)))
[(first body) (rest body)]
[nil body])]
{:params params :body body}))
(defn parse-fact [sexpr]
1 . Shift the first expr into : entity
2 . If there 's an existing value in : attr ( attribute )
;; A. If the value is also keyword, :attr is an implicit var binding
B. Else shift : attr and the value into an [: entity : attr value ] triple in : facts
3 . Shift the value into : attr
(let [body (rest sexpr)
state (reduce
#(merge-state
%1
(if (:attr %1)
(if (keyword? %2)
;; Implicit variable; sub in a symbol of the same name, set the next :attr
{:attr %2 :facts [[(:entity %1) (name (:attr %1)) (symbol (name (:attr %1)))]]}
Normal KV pair ; use the : attr
{:attr nil :facts [[(:entity %1) (name (:attr %1)) %2]]})
;; Shift the next value into :attr
(if (keyword? %2)
{:attr %2}
(throw (syntax-error
(str "Invalid attribute '" %2 "'. Attributes must be keyword literals. Use fact-btu for free attributes")
sexpr)))))
{:entity (first body) :facts [] :attr nil}
(rest body))
state (merge-state state (if (:attr state)
{:attr nil :facts [[(:entity state) (name (:attr state)) (symbol (name (:attr state)))]]}
nil))
state (merge-state state (if (= (count (:facts state)) 0)
{:facts [[(:entity state)]]}
nil))]
state))
(defn ui-id-alias? [[elem attr value]]
(and (= attr "id") (symbol? value)))
(defn parse-ui [sexpr root-id]
(as-> {:group-id (gensym root-id) :grouping (second sexpr) :elems (vec (drop 2 sexpr))} args
(assoc-in args [:ids]
(reduce-kv #(assoc %1 %3 (symbol (str (:group-id args) "_" %2))) {} (:elems args)))
(assoc-in args [:id-values]
(reduce-kv (fn [memo elem id]
(let [grouping (:grouping args)
row-id (interpose "__" (cons (name id) grouping))]
(assoc memo id `(~'str ~@row-id))))
{}
(:ids args)))
(assoc-in args [:attributes]
(map (fn [elem]
(let [id (get (:ids args) elem)]
[id "tag" (name (first elem))]))
(:elems args)))
(update-in args [:attributes] concat
(apply concat
(map
(fn [elem]
(let [id (get (:ids args) elem)]
(map (fn [attr]
[id (name (first attr)) (second attr)])
(parse-schema {} elem))))
(:elems args))))
(assoc-in args [:aliases]
(reduce
(fn [memo [elem attr val]]
(assoc memo val elem))
{}
(filter ui-id-alias? (:attributes args))))
(assoc-in args [:generated]
(loop [ids (:id-values args)
aliases (:aliases args)
generated [ ]]
(if (zero? (count ids))
(if-not (zero? (count aliases))
(apply conj generated aliases)
generated)
(let [id (first ids)
aliased-to-id (filter #(= (first id) (second %1)) aliases)]
(recur (dissoc ids (first id))
(apply dissoc aliases (map first aliased-to-id))
(apply conj generated id aliased-to-id))))))
(update-in args [:attributes] #(filter (complement ui-id-alias?) %1))
(assoc-in args [:join] (concat (:grouping args) (vals (:ids args)) (keys (:aliases args))))))
(defn parse-define-ui [sexpr]
(as-> {:id (nth sexpr 1) :projection [] :query [] :ui []} args
;; Split exprs into :ui (ui ...) and :query <everything else>
(reduce
(fn [args expr]
(if (= 'ui (first expr))
(update-in args [:ui] conj (parse-ui expr (:id args)))
(update-in args [:query] conj expr)))
args
(drop 2 sexpr))))
(defn parse-args
([sexpr] (parse-args nil sexpr))
([db sexpr]
(let [op (first sexpr)
body (rest sexpr)
schema (get-schema db op)]
(with-meta
(cond
schema (parse-schema schema sexpr)
(= op 'define!) (parse-define sexpr)
(= op 'query) (parse-query sexpr)
(= op 'fact) (parse-fact sexpr)
(= op 'insert-fact!) (parse-fact sexpr)
(= op 'remove-fact!) (parse-fact sexpr)
(= op 'define-ui) (parse-define-ui sexpr)
:else (throw (syntax-error (str "Unknown operator " op) sexpr)))
{:expr sexpr :schema schema}))))
(defn validate-args [args]
(let [{:keys [schema expr]} (meta args)
supplied? (set (keys args))
optional? (:optional schema)
params (into (:args schema) (:kwargs schema))
params (if (:rest schema) (conj params (:rest schema)) params)
param? (set params)
required (if optional? (into [] (filter #(not (optional? %1)) params)) params)]
(when (and schema (not= schema {}))
(or (when param? (some #(when-not (param? %1)
(syntax-error (str "Invalid keyword argument " %1 " for " (first expr)) (merge expr {:schema schema})))
(keys args)))
(some #(when-not (supplied? %1)
(syntax-error (str "Missing required argument " %1 " for " (first expr)) expr))
required)
(when (:validate schema) ((:validate schema) expr args))))))
(defn assert-valid [args]
(if-let [err (validate-args args)]
(throw err)
args))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
Expand a SMIL sexpr recursively until it 's ready for WEASL compilation
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(declare expand)
(defn expand-each [db args]
(congeal-body (map #(expand db %1) args)))
(defn expand-values [db args]
(reduce-kv (fn [memo k v]
(assoc memo k (if (vector? v) (expand-each db v) (expand db v)))) {} args))
(defn generate-ui [db args]
(let [projection (vec (distinct (apply concat (map :join (:ui args)))))
generated (apply concat (map :generated (:ui args)))
query (concat (:query args)
(map
(fn [[var val]]
`(~'= ~var ~val))
generated))]
(vec (concat [`(~'define! ~(:id args) ~projection
~@(expand-each db query))]
(map
(fn [ui-group]
`(~'define! ~'ui ~['e 'a 'v]
(~(:id args) ~@(map keyword (:join ui-group)))
(~'union ~(into ['e 'a 'v] (:join ui-group))
~@(map (fn [[elem attribute value]]
`(~'query
(~'= ~'e ~elem)
(~'= ~'a ~attribute)
(~'= ~'v ~value)))
(:attributes ui-group)))))
(:ui args))
))))
;; @FIXME: Returning multiple forms from a single expand doesn't bloody work.
(defn expand [db expr]
(cond
(seq? expr)
(let [sexpr expr
op (first sexpr)
body (rest sexpr)
args (assert-valid (parse-args db sexpr))
expanded (case op
;; Special forms
query (concat [op (:params args)] (expand-each db (:body args)))
define! (with-meta (concat [op] (:header args) (expand-each db (:body args)))
args)
fact (expand-each db (map #(cons (with-meta 'fact-btu (meta op)) %1) (:facts args)))
insert-fact! (expand-each db (map #(cons (with-meta 'insert-fact-btu! (meta op)) %1) (:facts args)))
sort (cons op (splat-map args))
define-ui (expand-each db (generate-ui db args))
Macros
remove-fact! (expand-each db (for [fact (:facts args)
:let [tick (gensym "tick")]]
[`(~(with-meta 'fact-btu (meta op)) ~@fact :tick ~tick)
`(~'remove-by-t! ~tick)]))
remove-by-t! (expand db (list (with-meta 'insert-fact-btu! (meta op)) (:tick args) REMOVE_FACT nil))
if (let [[head body] (split-at 2 (expand db (as-query (:then args))))
then (concat head (expand db (:cond args)) body)
else (expand db (as-query (:else args)))]
(seq (conj ['choose ['return]] then else)))
Native forms
insert-fact-btu! (cons op (splat-map (expand-values db args)))
union (concat [op] [(:params args)] (assert-queries (expand-each db (:members args))))
choose (concat [op] [(:params args)] (assert-queries (expand-each db (:members args))))
not (cons op (expand-each db (:body args)))
context (cons op (splat-map (expand-values db args)))
;; Default
(cons op (splat-map (expand-values db args))))]
(with-meta expanded (merge (meta expr) (meta expanded))))
(sequential? expr) (expand-each db expr)
:else expr))
(defn returnable? [sexpr]
(let [schema (get-schema (first sexpr))]
(if-not (nil? schema)
(boolean (:return (:optional schema)))
false)))
(defn get-args
"Retrieves a hash-map of args from an already parsed form, ignoring special forms + forms w/ rest params."
[sexpr]
(when-let [schema (and (seq? sexpr) (get-schema (first sexpr)))]
(when-not (:body schema)
(apply hash-map (rest sexpr)))))
(defn unpack-inline [sexpr]
(let [argmap (when (seq? sexpr) (pr-str sexpr) (get-args sexpr))]
(cond
(vector? sexpr)
(let [unpacked (reduce #(merge-with merge-state %1 (unpack-inline %2))
{:inline [] :query []}
sexpr)]
{:inline [(:inline unpacked)] :query (:query unpacked)})
(not (seq? sexpr))
{:inline [sexpr]}
(#{'query 'define! 'not 'context 'choose 'union} (first sexpr))
{:inline [(with-meta
(concat
[(first sexpr)]
(reduce
#(let [{inline :inline query :query} (unpack-inline %2)]
(into (into %1 query) inline))
[] (rest sexpr)))
(meta sexpr))]
:query []}
(= (first sexpr) '=)
(cond
(every? seq? (vals argmap))
(let [returns {:a (:return (get-args (:a argmap)))
:b (:return (get-args (:b argmap)))}
var (or (:a returns) (:b returns) (gensym "$$tmp"))]
{:inline [] :query (with-meta (apply concat (map (fn [x]
(let [sub-expr (if (x returns)
(x argmap)
(concat (x argmap) [:return var]))
{inline :inline query :query} (unpack-inline sub-expr)]
(concat query inline)))
[:a :b]))
(meta sexpr))})
(some seq? (vals argmap))
(let [[val var] (map argmap (if (seq? (:a argmap)) [:a :b] [:b :a]))
{inline :inline query :query} (unpack-inline val)]
{:inline [(with-meta (concat (first inline) [:return var])
(meta (:b argmap)))]
:query query})
:else
{:inline [sexpr]})
(returnable? sexpr)
(let [state (reduce
#(merge-state
%1
(if-not (seq? %2)
{:inline [%2]}
(let [{inline :inline query :query} (unpack-inline %2)
tmp (gensym "$$tmp")
query (conj query (concat (first inline) [:return tmp]))]
{:inline [tmp] :query query})))
{:inline [] :query []}
(rest sexpr))]
{:inline [(concat [(first sexpr)] (:inline state))] :query (:query state)})
:else
(let [state (reduce #(merge-with merge-state %1
(if (and (seq? %2) (returnable? %2))
(let [sub-argmap (get-args %2)
sub-argmap (when (not (:return sub-argmap))
(assoc sub-argmap :return (gensym "$$tmp")))
{inline :inline query :query} (unpack-inline (apply list (first %2) (splat-map sub-argmap)))]
{:inline [(:return sub-argmap)] :query (concat query inline)})
(unpack-inline %2)))
{:inline [(first sexpr)] :query []}
(rest sexpr))]
{:inline [(with-meta (seq (:inline state)) (meta sexpr))] :query (:query state)}))))
(defn unpack [db sexpr]
(let [unpacked (first (:inline (unpack-inline (expand db sexpr))))]
(if (vector? unpacked) unpacked [unpacked])))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
SMIL formatting and debugging utilities
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn print-indent
([indent] (print-indent indent 0))
([indent offset]
(print (apply str (repeat (+ (* indent 2) offset) " ")))))
(defn print-expr [& args]
(print (string/join
" "
(map #(condp (fn [x y] (= (type y) x)) %1
nil "nil"
java.lang.String (str "\"" %1 "\"")
(str %1))
args))))
(defn print-smil [sexpr & {:keys [indent] :or {indent 0}}]
(cond
(vector? sexpr)
(do
(print "[")
(doseq [expr sexpr]
(print-smil expr))
(print "]\n"))
(not (seq? sexpr))
(if (sequential? sexpr)
(map #(print-smil %1 :indent indent) sexpr)
(print-expr sexpr))
(= 'query (first sexpr))
(do
(print-indent indent)
(print "(")
(print-expr (first sexpr) (second sexpr))
(println)
(doseq [child (drop 2 sexpr)]
(print-smil child :indent (+ indent 1)))
(print-indent indent)
(println ")"))
(= 'define! (first sexpr))
(let [m (meta sexpr)
header (partition 2 (:header m))
pair (first header)
skip (count (:header m))
body (drop skip (rest sexpr))]
(print-indent indent)
(print "(")
(print-expr (first sexpr) (first pair) (second pair))
(println)
(doseq [pair (rest header)]
(print-indent indent 9)
(print-expr (first pair) (second pair))
(println))
(doseq [child body]
(print-smil child :indent (+ indent 1)))
(print-indent indent)
(println ")"))
:else
(do
(print-indent indent)
(print "(")
(print-expr (first sexpr))
(doseq [expr (rest sexpr)]
(print " ")
(print-smil expr :indent (+ indent 1)))
(println ")"))
))
(defn test-sm
([sexpr] (test-sm nil sexpr))
([db sexpr]
(println "----[" sexpr "]----")
(let [op (first sexpr)
body (rest sexpr)
schema (get-schema db op)
_ (println " - schema " schema)
args (parse-args db sexpr)
_ (println " - args " args)
invalid (validate-args args)
_ (println " - invalid " (when invalid {:message (.getMessage invalid) :data (ex-data invalid)}))
expanded (expand db sexpr)
_ (println " - expanded " expanded)
unpacked (first (:inline (unpack-inline expanded)))
_ (println " - unpacked " unpacked)
]
(print-smil unpacked))))
;; Positive test cases
;; (test-sm '(define! foo [a b] (fact bar :age a) (fact a :tag bar)))
( test - sm ' ( query ( insert - fact ! a : b c : d 2 : e ) ) )
;; (test-sm '(union [person] (query (not (fact-btu :value person)) (fact person :company "kodowa"))))
;; (test-sm '(choose [person] (query (fact person)) (query (fact other :friend person))))
;; (test-sm '(query (+ (/ 2 x) (- y 7))))
;; Negative test cases
;; (test-sm '(non-existent-foo))
( test - sm ' ( insert - fact ! foo a 1 b ) )
;; (test-sm '(insert-fact-btu! e "attr"))
;; (test-sm '(fact-btu :non-existent foo))
;; (test-sm '(not foo bar))
;; (test-sm '(fact a b c))
;; (test-sm '(define! (fact a)))
;; (test-sm '(define! foo (fact a)))
;; (test-sm '(union [result] (fact a)))
| null |
https://raw.githubusercontent.com/witheve/eve-experiments/8a1cdb353b3e728bc768b315e5b9a9f9dc785ae1/server/src/server/smil.clj
|
clojure
|
@NOTE: Should this allow unions/chooses as well?
:args - positional arguments
:rest - remaining arguments
:optional - arguments which may not be specified
:validate - optional function to validate the argument map
Special forms
Special due to multiple aliases
Special due to optional parameterization
native forms
bag can be inferred in SMIR
These are only needed for testing -- they'll be provided dynamically by the db at runtime
@FIXME: Hack to allow unknown implications to be used if pre-expanded for multi-form expansions.
A. If the value is also keyword, :kw is an implicit var binding
Implicit variable; sub in a symbol of the same name, set the next :kw
use the : kw
Manual keyword, set the next :kw and cease being positional
Positional value; use kw from (:args schema) and decrement (position
If a rest argument is specified, dump excess args into it
Too many arguments without names, bail
A. If the value is a vec, shift the pair into the :header
If we've already entered the body, no more headers can follow
If we've already snatched an alias, it must be followed by a vec of vars
If our state is clear we can begin a new header (symbol) or enter the body (anything else)
A. If the value is also keyword, :attr is an implicit var binding
Implicit variable; sub in a symbol of the same name, set the next :attr
use the : attr
Shift the next value into :attr
Split exprs into :ui (ui ...) and :query <everything else>
@FIXME: Returning multiple forms from a single expand doesn't bloody work.
Special forms
Default
Positive test cases
(test-sm '(define! foo [a b] (fact bar :age a) (fact a :tag bar)))
(test-sm '(union [person] (query (not (fact-btu :value person)) (fact person :company "kodowa"))))
(test-sm '(choose [person] (query (fact person)) (query (fact other :friend person))))
(test-sm '(query (+ (/ 2 x) (- y 7))))
Negative test cases
(test-sm '(non-existent-foo))
(test-sm '(insert-fact-btu! e "attr"))
(test-sm '(fact-btu :non-existent foo))
(test-sm '(not foo bar))
(test-sm '(fact a b c))
(test-sm '(define! (fact a)))
(test-sm '(define! foo (fact a)))
(test-sm '(union [result] (fact a)))
|
(ns server.smil
(:refer-clojure :exclude [read])
(:require [server.db :as db]
[server.util :refer [merge-state]]
[clojure.string :as string]
[clojure.tools.reader :as reader]
[clojure.tools.reader.reader-types :as reader-types]))
(def REMOVE_FACT 5)
(defn read [str]
(reader/read (reader-types/indexing-push-back-reader str)))
(defn syntax-error
([msg expr] (syntax-error msg expr nil))
([msg expr data]
(let [{:keys [line column end-line end-column]} (meta expr)
standard-data {:expr expr :line line :column column :end-line end-line :end-column end-column}]
(ex-info msg (merge standard-data data)))))
(defn splat-map [m]
(reduce-kv conj [] m))
Flatten vecs ( multi - returns ) in the given body
(defn congeal-body [body]
(vec (reduce #(if (vector? %2)
(into %1 %2)
(conj %1 %2))
[]
body)))
(defn as-query [expr]
(if (and (seq? expr) (= (first expr) 'query))
expr
(list 'query
(list '= 'return expr))))
(defn assert-queries [body]
(doseq [expr body]
(when (or (not (seq? expr)) (not (= (first expr) 'query)))
(throw (syntax-error "All union/choose members must be queries" expr))))
body)
(defn validate-sort [sexpr args]
(doseq [[var dir] (partition 2 {:sorting args})]
(when-not (symbol? var)
(syntax-error "First argument of each pair must be a variable" sexpr {:var var :dir dir}))
(when-not (or (symbol? dir) (= "ascending" dir) (= "descending" dir))
(syntax-error "Second argument of each pair must be a direction" sexpr {:var var :dir dir}))))
(defn get-fields [sexpr]
(when (and (seq? sexpr) (#{'query 'union 'choose} (first sexpr)))
(vec (second sexpr))))
: kwargs - keyword arguments
(def schemas {
'insert-fact! nil
'remove-fact! nil
'fact nil
'define-ui nil
Macros
'remove-by-t! {:args [:tick]}
'if {:args [:cond :then :else]}
'sort {:rest :sorting :optional #{:return} :validate validate-sort}
'union {:args [:params] :rest :members :body true}
'choose {:args [:params] :rest :members :body true}
'not {:rest :body :body true}
'fact-btu {:args [:entity :attribute :value :bag] :kwargs [:tick] :optional #{:entity :attribute :value :bag :tick}}
'full-fact-btu {:args [:entity :attribute :value :bag] :kwargs [:tick] :optional #{:entity :attribute :value :bag :tick}}
'context {:kwargs [:bag :tick] :rest :body :optional #{:bag :tick :body} :body true}})
(def primitives {'= {:args [:a :b]}
'+ {:args [:a :b] :kwargs [:return] :optional #{:return}}
'- {:args [:a :b] :kwargs [:return] :optional #{:return}}
'* {:args [:a :b] :kwargs [:return] :optional #{:return}}
'/ {:args [:a :b] :kwargs [:return] :optional #{:return}}
'not= {:args [:a :b] :kwargs [:return] :optional #{:return}}
'> {:args [:a :b] :kwargs [:return] :optional #{:return}}
'>= {:args [:a :b] :kwargs [:return] :optional #{:return}}
'< {:args [:a :b] :kwargs [:return] :optional #{:return}}
'<= {:args [:a :b] :kwargs [:return] :optional #{:return}}
'str {:rest :a :kwargs [:return] :optional #{:return}}
'hash {:args [:a]}
'sum {:args [:a] :kwargs [:return] :optional #{:return}}})
(defn get-schema
([op] (or (get schemas op nil) (get primitives op nil)))
([db op]
(if (or (contains? schemas op) (contains? primitives op))
(get-schema op)
(or
(when-let [implication (and db (db/implication-of db (name op)))]
(let [args (map keyword (first implication))]
{:args (vec args) :optional (set args)}))
Parse sexprs into argument hashmaps
(defn parse-schema [schema sexpr]
1 . If a keyword has been shifted into : kw
: kw is mapped manually to the value
2 . If the value is a keyword , shift it into : kw and stop accepting positionals
3 . If we have n't exhausted our positionals , shift a positional to map to the value
4 . If the form accepts a rest parameter , shift the value onto the rest list
(let [body (rest sexpr)
state (reduce
#(merge-state %1
(if (:kw %1)
(if (keyword? %2)
{:kw %2 :args {(:kw %1) (symbol (name (:kw %1)))}}
{:kw nil :args {(:kw %1) %2}})
(if (keyword? %2)
{:position 0 :kw %2}
(if-let [kw (get (:args schema) (- (count (:args schema)) (:position %1)) nil)]
{:position (dec (:position %1)) :args {kw %2}}
(if (:rest schema)
(if (keyword? %2)
(throw (syntax-error "Keyword arguments must come before rest arguments" sexpr))
{:args {(:rest schema) [%2]}})
(throw (syntax-error
(str "Too many positional arguments without a rest argument. Expected " (count (:args schema)))
sexpr)))))))
{:args {} :kw nil :position (count (:args schema))} body)
state (merge-state state (if (:kw state)
{:kw nil :args {(:kw state) (symbol (name (:kw state)))}}
nil))]
(:args state)))
(defn parse-define [sexpr]
1 . If we 've started parsing the body , everything else gets pushed into the body
2 . If there 's an existing symbol in : ( alias )
( Aliases must be followed by their exported variables )
3 . If the value is a symbol , shift it into :
4 . Shift the value into the body
(let [{header :header body :body}
(reduce
#(merge-state
%1
(if (> (count (:body %1)) 0)
{:body [%2]}
(if (:sym %1)
(if (vector? %2)
{:sym nil :header [(:sym %1) %2]}
(throw (syntax-error
(str "Implication alias " (:sym %1) " must be followed by a vec of exported variables")
sexpr)))
(if (symbol? %2)
{:sym %2}
If no headers are defined before we try to enter the body , that 's a paddlin '
(if (> (count (:header %1)) 0)
{:body [%2]}
(throw (syntax-error "Implications must specify at least one alias" sexpr)))))))
{:header [] :body [] :sym nil} (rest sexpr))]
(if (> (count header) 0)
{:header header :body body}
(throw (syntax-error "Implications must specify at least one alias" sexpr)))))
(defn parse-query [sexpr]
(let [body (rest sexpr)
[params body] (if (or (vector? (first body)) (nil? (first body)))
[(first body) (rest body)]
[nil body])]
{:params params :body body}))
(defn parse-fact [sexpr]
1 . Shift the first expr into : entity
2 . If there 's an existing value in : attr ( attribute )
B. Else shift : attr and the value into an [: entity : attr value ] triple in : facts
3 . Shift the value into : attr
(let [body (rest sexpr)
state (reduce
#(merge-state
%1
(if (:attr %1)
(if (keyword? %2)
{:attr %2 :facts [[(:entity %1) (name (:attr %1)) (symbol (name (:attr %1)))]]}
{:attr nil :facts [[(:entity %1) (name (:attr %1)) %2]]})
(if (keyword? %2)
{:attr %2}
(throw (syntax-error
(str "Invalid attribute '" %2 "'. Attributes must be keyword literals. Use fact-btu for free attributes")
sexpr)))))
{:entity (first body) :facts [] :attr nil}
(rest body))
state (merge-state state (if (:attr state)
{:attr nil :facts [[(:entity state) (name (:attr state)) (symbol (name (:attr state)))]]}
nil))
state (merge-state state (if (= (count (:facts state)) 0)
{:facts [[(:entity state)]]}
nil))]
state))
(defn ui-id-alias? [[elem attr value]]
(and (= attr "id") (symbol? value)))
(defn parse-ui [sexpr root-id]
(as-> {:group-id (gensym root-id) :grouping (second sexpr) :elems (vec (drop 2 sexpr))} args
(assoc-in args [:ids]
(reduce-kv #(assoc %1 %3 (symbol (str (:group-id args) "_" %2))) {} (:elems args)))
(assoc-in args [:id-values]
(reduce-kv (fn [memo elem id]
(let [grouping (:grouping args)
row-id (interpose "__" (cons (name id) grouping))]
(assoc memo id `(~'str ~@row-id))))
{}
(:ids args)))
(assoc-in args [:attributes]
(map (fn [elem]
(let [id (get (:ids args) elem)]
[id "tag" (name (first elem))]))
(:elems args)))
(update-in args [:attributes] concat
(apply concat
(map
(fn [elem]
(let [id (get (:ids args) elem)]
(map (fn [attr]
[id (name (first attr)) (second attr)])
(parse-schema {} elem))))
(:elems args))))
(assoc-in args [:aliases]
(reduce
(fn [memo [elem attr val]]
(assoc memo val elem))
{}
(filter ui-id-alias? (:attributes args))))
(assoc-in args [:generated]
(loop [ids (:id-values args)
aliases (:aliases args)
generated [ ]]
(if (zero? (count ids))
(if-not (zero? (count aliases))
(apply conj generated aliases)
generated)
(let [id (first ids)
aliased-to-id (filter #(= (first id) (second %1)) aliases)]
(recur (dissoc ids (first id))
(apply dissoc aliases (map first aliased-to-id))
(apply conj generated id aliased-to-id))))))
(update-in args [:attributes] #(filter (complement ui-id-alias?) %1))
(assoc-in args [:join] (concat (:grouping args) (vals (:ids args)) (keys (:aliases args))))))
(defn parse-define-ui [sexpr]
(as-> {:id (nth sexpr 1) :projection [] :query [] :ui []} args
(reduce
(fn [args expr]
(if (= 'ui (first expr))
(update-in args [:ui] conj (parse-ui expr (:id args)))
(update-in args [:query] conj expr)))
args
(drop 2 sexpr))))
(defn parse-args
([sexpr] (parse-args nil sexpr))
([db sexpr]
(let [op (first sexpr)
body (rest sexpr)
schema (get-schema db op)]
(with-meta
(cond
schema (parse-schema schema sexpr)
(= op 'define!) (parse-define sexpr)
(= op 'query) (parse-query sexpr)
(= op 'fact) (parse-fact sexpr)
(= op 'insert-fact!) (parse-fact sexpr)
(= op 'remove-fact!) (parse-fact sexpr)
(= op 'define-ui) (parse-define-ui sexpr)
:else (throw (syntax-error (str "Unknown operator " op) sexpr)))
{:expr sexpr :schema schema}))))
(defn validate-args [args]
(let [{:keys [schema expr]} (meta args)
supplied? (set (keys args))
optional? (:optional schema)
params (into (:args schema) (:kwargs schema))
params (if (:rest schema) (conj params (:rest schema)) params)
param? (set params)
required (if optional? (into [] (filter #(not (optional? %1)) params)) params)]
(when (and schema (not= schema {}))
(or (when param? (some #(when-not (param? %1)
(syntax-error (str "Invalid keyword argument " %1 " for " (first expr)) (merge expr {:schema schema})))
(keys args)))
(some #(when-not (supplied? %1)
(syntax-error (str "Missing required argument " %1 " for " (first expr)) expr))
required)
(when (:validate schema) ((:validate schema) expr args))))))
(defn assert-valid [args]
(if-let [err (validate-args args)]
(throw err)
args))
Expand a SMIL sexpr recursively until it 's ready for WEASL compilation
(declare expand)
(defn expand-each [db args]
(congeal-body (map #(expand db %1) args)))
(defn expand-values [db args]
(reduce-kv (fn [memo k v]
(assoc memo k (if (vector? v) (expand-each db v) (expand db v)))) {} args))
(defn generate-ui [db args]
(let [projection (vec (distinct (apply concat (map :join (:ui args)))))
generated (apply concat (map :generated (:ui args)))
query (concat (:query args)
(map
(fn [[var val]]
`(~'= ~var ~val))
generated))]
(vec (concat [`(~'define! ~(:id args) ~projection
~@(expand-each db query))]
(map
(fn [ui-group]
`(~'define! ~'ui ~['e 'a 'v]
(~(:id args) ~@(map keyword (:join ui-group)))
(~'union ~(into ['e 'a 'v] (:join ui-group))
~@(map (fn [[elem attribute value]]
`(~'query
(~'= ~'e ~elem)
(~'= ~'a ~attribute)
(~'= ~'v ~value)))
(:attributes ui-group)))))
(:ui args))
))))
(defn expand [db expr]
(cond
(seq? expr)
(let [sexpr expr
op (first sexpr)
body (rest sexpr)
args (assert-valid (parse-args db sexpr))
expanded (case op
query (concat [op (:params args)] (expand-each db (:body args)))
define! (with-meta (concat [op] (:header args) (expand-each db (:body args)))
args)
fact (expand-each db (map #(cons (with-meta 'fact-btu (meta op)) %1) (:facts args)))
insert-fact! (expand-each db (map #(cons (with-meta 'insert-fact-btu! (meta op)) %1) (:facts args)))
sort (cons op (splat-map args))
define-ui (expand-each db (generate-ui db args))
Macros
remove-fact! (expand-each db (for [fact (:facts args)
:let [tick (gensym "tick")]]
[`(~(with-meta 'fact-btu (meta op)) ~@fact :tick ~tick)
`(~'remove-by-t! ~tick)]))
remove-by-t! (expand db (list (with-meta 'insert-fact-btu! (meta op)) (:tick args) REMOVE_FACT nil))
if (let [[head body] (split-at 2 (expand db (as-query (:then args))))
then (concat head (expand db (:cond args)) body)
else (expand db (as-query (:else args)))]
(seq (conj ['choose ['return]] then else)))
Native forms
insert-fact-btu! (cons op (splat-map (expand-values db args)))
union (concat [op] [(:params args)] (assert-queries (expand-each db (:members args))))
choose (concat [op] [(:params args)] (assert-queries (expand-each db (:members args))))
not (cons op (expand-each db (:body args)))
context (cons op (splat-map (expand-values db args)))
(cons op (splat-map (expand-values db args))))]
(with-meta expanded (merge (meta expr) (meta expanded))))
(sequential? expr) (expand-each db expr)
:else expr))
(defn returnable? [sexpr]
(let [schema (get-schema (first sexpr))]
(if-not (nil? schema)
(boolean (:return (:optional schema)))
false)))
(defn get-args
"Retrieves a hash-map of args from an already parsed form, ignoring special forms + forms w/ rest params."
[sexpr]
(when-let [schema (and (seq? sexpr) (get-schema (first sexpr)))]
(when-not (:body schema)
(apply hash-map (rest sexpr)))))
(defn unpack-inline [sexpr]
(let [argmap (when (seq? sexpr) (pr-str sexpr) (get-args sexpr))]
(cond
(vector? sexpr)
(let [unpacked (reduce #(merge-with merge-state %1 (unpack-inline %2))
{:inline [] :query []}
sexpr)]
{:inline [(:inline unpacked)] :query (:query unpacked)})
(not (seq? sexpr))
{:inline [sexpr]}
(#{'query 'define! 'not 'context 'choose 'union} (first sexpr))
{:inline [(with-meta
(concat
[(first sexpr)]
(reduce
#(let [{inline :inline query :query} (unpack-inline %2)]
(into (into %1 query) inline))
[] (rest sexpr)))
(meta sexpr))]
:query []}
(= (first sexpr) '=)
(cond
(every? seq? (vals argmap))
(let [returns {:a (:return (get-args (:a argmap)))
:b (:return (get-args (:b argmap)))}
var (or (:a returns) (:b returns) (gensym "$$tmp"))]
{:inline [] :query (with-meta (apply concat (map (fn [x]
(let [sub-expr (if (x returns)
(x argmap)
(concat (x argmap) [:return var]))
{inline :inline query :query} (unpack-inline sub-expr)]
(concat query inline)))
[:a :b]))
(meta sexpr))})
(some seq? (vals argmap))
(let [[val var] (map argmap (if (seq? (:a argmap)) [:a :b] [:b :a]))
{inline :inline query :query} (unpack-inline val)]
{:inline [(with-meta (concat (first inline) [:return var])
(meta (:b argmap)))]
:query query})
:else
{:inline [sexpr]})
(returnable? sexpr)
(let [state (reduce
#(merge-state
%1
(if-not (seq? %2)
{:inline [%2]}
(let [{inline :inline query :query} (unpack-inline %2)
tmp (gensym "$$tmp")
query (conj query (concat (first inline) [:return tmp]))]
{:inline [tmp] :query query})))
{:inline [] :query []}
(rest sexpr))]
{:inline [(concat [(first sexpr)] (:inline state))] :query (:query state)})
:else
(let [state (reduce #(merge-with merge-state %1
(if (and (seq? %2) (returnable? %2))
(let [sub-argmap (get-args %2)
sub-argmap (when (not (:return sub-argmap))
(assoc sub-argmap :return (gensym "$$tmp")))
{inline :inline query :query} (unpack-inline (apply list (first %2) (splat-map sub-argmap)))]
{:inline [(:return sub-argmap)] :query (concat query inline)})
(unpack-inline %2)))
{:inline [(first sexpr)] :query []}
(rest sexpr))]
{:inline [(with-meta (seq (:inline state)) (meta sexpr))] :query (:query state)}))))
(defn unpack [db sexpr]
(let [unpacked (first (:inline (unpack-inline (expand db sexpr))))]
(if (vector? unpacked) unpacked [unpacked])))
SMIL formatting and debugging utilities
(defn print-indent
([indent] (print-indent indent 0))
([indent offset]
(print (apply str (repeat (+ (* indent 2) offset) " ")))))
(defn print-expr [& args]
(print (string/join
" "
(map #(condp (fn [x y] (= (type y) x)) %1
nil "nil"
java.lang.String (str "\"" %1 "\"")
(str %1))
args))))
(defn print-smil [sexpr & {:keys [indent] :or {indent 0}}]
(cond
(vector? sexpr)
(do
(print "[")
(doseq [expr sexpr]
(print-smil expr))
(print "]\n"))
(not (seq? sexpr))
(if (sequential? sexpr)
(map #(print-smil %1 :indent indent) sexpr)
(print-expr sexpr))
(= 'query (first sexpr))
(do
(print-indent indent)
(print "(")
(print-expr (first sexpr) (second sexpr))
(println)
(doseq [child (drop 2 sexpr)]
(print-smil child :indent (+ indent 1)))
(print-indent indent)
(println ")"))
(= 'define! (first sexpr))
(let [m (meta sexpr)
header (partition 2 (:header m))
pair (first header)
skip (count (:header m))
body (drop skip (rest sexpr))]
(print-indent indent)
(print "(")
(print-expr (first sexpr) (first pair) (second pair))
(println)
(doseq [pair (rest header)]
(print-indent indent 9)
(print-expr (first pair) (second pair))
(println))
(doseq [child body]
(print-smil child :indent (+ indent 1)))
(print-indent indent)
(println ")"))
:else
(do
(print-indent indent)
(print "(")
(print-expr (first sexpr))
(doseq [expr (rest sexpr)]
(print " ")
(print-smil expr :indent (+ indent 1)))
(println ")"))
))
(defn test-sm
([sexpr] (test-sm nil sexpr))
([db sexpr]
(println "----[" sexpr "]----")
(let [op (first sexpr)
body (rest sexpr)
schema (get-schema db op)
_ (println " - schema " schema)
args (parse-args db sexpr)
_ (println " - args " args)
invalid (validate-args args)
_ (println " - invalid " (when invalid {:message (.getMessage invalid) :data (ex-data invalid)}))
expanded (expand db sexpr)
_ (println " - expanded " expanded)
unpacked (first (:inline (unpack-inline expanded)))
_ (println " - unpacked " unpacked)
]
(print-smil unpacked))))
( test - sm ' ( query ( insert - fact ! a : b c : d 2 : e ) ) )
( test - sm ' ( insert - fact ! foo a 1 b ) )
|
761747f5300e4932071d2b312548b3c9490b0af588d5edf590f2cc8f74c6a3c3
|
input-output-hk/cardano-sl
|
Update.hs
|
-- | Reexport of Pos.Client.Update.* modules.
module Pos.Client.Update
( module Pos.Client.Update.Network
) where
import Pos.Client.Update.Network
| null |
https://raw.githubusercontent.com/input-output-hk/cardano-sl/1499214d93767b703b9599369a431e67d83f10a2/client/src/Pos/Client/Update.hs
|
haskell
|
| Reexport of Pos.Client.Update.* modules.
|
module Pos.Client.Update
( module Pos.Client.Update.Network
) where
import Pos.Client.Update.Network
|
7b574932b4a79d47d9e806abae60b56c686087283cf49056392e7400dba43a6d
|
imandra-ai/fix-engine
|
runtime.ml
|
let ( let* ) = Lwt.bind
type direction =
| Incoming
| Outgoing
[@@deriving show]
type msg_type =
| Application
| Admin
[@@deriving show]
type message = {
message: (string * string) list;
direction: direction;
msg_type: msg_type;
}
[@@deriving show]
type event =
| Log of string
| FIXMessage of message
| Connected of string
| Disconnected of string
| ConnectionRejected of string
[@@deriving show]
type t = {
engine_box: Engine.event Lwt_mvar.t;
fixio_box: Fix_io.message Lwt_mvar.t;
send_box: Engine.message Lwt_mvar.t;
result_box: (unit, Engine.err) result Lwt_mvar.t;
engine: Engine.t;
log_file: string option;
fixio: Fix_io.fix_io option;
recv: event -> unit Lwt.t;
}
type handle = t
let get_msg_type message =
match List.assoc_opt "35" message with
| None -> Application
| Some k ->
(match Parse_admin_tags.parse_admin_msg_tag k with
| None -> Application
| Some _ -> Admin)
let mk_event message direction =
let msg_type = get_msg_type message in
FIXMessage { message; direction; msg_type }
let receive_fix_io t message =
Lwt.join
[
Engine.process_fix_wire t.engine message;
t.recv (mk_event message Incoming);
]
let receive_engine t event =
match event, t.fixio with
| Engine.FIXFromEngine message, Some fixio ->
Lwt.join [ Fix_io.send fixio message; t.recv (mk_event message Outgoing) ]
| Engine.Log msg, _ -> t.recv (Log msg)
| _ -> Lwt.return_unit
let receive_send t message =
let* result = Engine.send_fix_message t.engine message in
Lwt_mvar.put t.result_box result
let rec loop (t : t) : unit Lwt.t =
let rec loop_box box receiver =
let* msg = Lwt_mvar.take box in
let* () = receiver t msg in
loop_box box receiver
in
let* () =
Lwt.join
[
loop_box t.engine_box receive_engine;
loop_box t.fixio_box receive_fix_io;
loop_box t.send_box receive_send;
]
in
loop t
let with_catch_disconnect recv f =
Lwt.catch f (fun e ->
let stack = Printexc.get_backtrace () in
let msg = Printexc.to_string e in
let msg = Printf.sprintf "\n%s%s\n" msg stack in
recv (Disconnected msg))
let connection_lock = Lwt_mutex.create ()
let with_locks recv f =
Lwt_mutex.with_lock connection_lock @@ fun () -> with_catch_disconnect recv f
let addr_to_string = function
| Unix.ADDR_UNIX s -> s
| ADDR_INET (h, p) -> Printf.sprintf "%s:%d" (Unix.string_of_inet_addr h) p
let server_handler (t : t) (in_addr : Unix.sockaddr) (inch, outch) =
let addr_str = addr_to_string in_addr in
if Lwt_mutex.is_locked connection_lock then
t.recv (ConnectionRejected addr_str)
else
let* () = t.recv (Connected addr_str) in
with_locks t.recv @@ fun () ->
(* FIX IO loop *)
let recv = Lwt_mvar.put t.fixio_box in
let log_file = t.log_file in
let fixio_thread, fixio = Fix_io.start ~recv ?log_file (inch, outch) in
let t = { t with fixio = Some fixio } in
Lwt.pick [ fixio_thread; loop t ]
let default_session_folder ~(config : Engine.config) =
let hostid =
match config.host_id with
| None -> "NoHostid"
| Some host_id -> host_id
in
Printf.sprintf "%s.%s.%s.session" config.comp_id config.target_id hostid
let make_state_and_thread ~(session_dir : string option)
~(log_file : string option) ~(reset : bool option) ~(config : Engine.config)
~(recv : event -> unit Lwt.t) =
let reset =
match reset with
| None -> false
| Some x -> x
in
let session_dir =
match session_dir with
| Some x -> x
| None -> default_session_folder ~config
in
let engine_box = Lwt_mvar.create_empty () in
let fixio_box = Lwt_mvar.create_empty () in
let send_box = Lwt_mvar.create_empty () in
let result_box = Lwt_mvar.create_empty () in
let engine_thread, engine =
let recv = Lwt_mvar.put engine_box in
Engine.start ~reset ~session_dir ~config ~recv
in
let state =
{
fixio = None;
engine;
engine_box;
fixio_box;
send_box;
result_box;
recv;
log_file;
}
in
state, engine_thread
let start_server ?(session_dir : string option) ?(log_file : string option)
?(reset : bool option) ~(config : Engine.config) ~(port : int)
~(recv : event -> unit Lwt.t) () =
let state, engine_thread =
make_state_and_thread ~session_dir ~log_file ~reset ~config ~recv
in
let addr = Unix.(ADDR_INET (inet_addr_any, port)) in
let server_thread =
let handler = server_handler state in
let _server = Lwt_io.establish_server_with_client_address addr handler in
let* () = Lwt_io.printlf "FIX Server established on localhost:%d" port in
Lwt.return_unit
in
let thread = Lwt.join [ engine_thread; server_thread ] in
state, thread
let client_handler addr_str (t, engine_thread, init_msg) (inch, outch) =
let* () = t.recv (Connected addr_str) in
with_catch_disconnect t.recv @@ fun () ->
let recv = Lwt_mvar.put t.fixio_box in
let log_file = t.log_file in
let fixio_thread, fixio = Fix_io.start ~recv ?log_file (inch, outch) in
let fixio_thread =
let* () = fixio_thread in
t.recv (Disconnected addr_str)
in
let t = { t with fixio = Some fixio } in
let* () = Engine.send_internal_message t.engine init_msg in
Lwt.pick [ engine_thread; fixio_thread; loop t ]
let start_client ?(session_dir : string option) ?(log_file : string option)
?(reset : bool option) ~(config : Engine.config) ~(host : string)
~(port : int) ~(recv : event -> unit Lwt.t) () =
let state, engine_thread =
make_state_and_thread ~session_dir ~log_file ~reset ~config ~recv
in
let init_msg =
Fix_engine_state.(
IncIntMsg_CreateSession
{ dest_comp_id = config.target_id; reset_seq_num = false })
in
let addr = Unix.inet_addr_of_string host in
let addr = Unix.(ADDR_INET (addr, port)) in
let addr_str = addr_to_string addr in
let handler = client_handler addr_str (state, engine_thread, init_msg) in
let thread = Lwt_io.with_connection addr handler in
state, thread
let send_message t msg =
let* () = Lwt_mvar.put t.send_box msg in
Lwt_mvar.take t.result_box
* If [ final_seqnums ] is passed , these are written to the session dir
to be read on next startup of fix - engine .
If no seqnums are present on startup , fix - engine just starts from 0
to be read on next startup of fix-engine.
If no seqnums are present on startup, fix-engine just starts from 0
*)
let terminate ?final_seqnums (t : t) =
let () =
match final_seqnums with
| None -> ()
| Some (seqin, seqout) ->
Engine.persist_final_seqnums t.engine (seqin, seqout)
in
Engine.terminate t.engine
| null |
https://raw.githubusercontent.com/imandra-ai/fix-engine/4d24f4d89a262ed7f16ff898570dbc9319730374/fix-engine/src-runtime/runtime.ml
|
ocaml
|
FIX IO loop
|
let ( let* ) = Lwt.bind
type direction =
| Incoming
| Outgoing
[@@deriving show]
type msg_type =
| Application
| Admin
[@@deriving show]
type message = {
message: (string * string) list;
direction: direction;
msg_type: msg_type;
}
[@@deriving show]
type event =
| Log of string
| FIXMessage of message
| Connected of string
| Disconnected of string
| ConnectionRejected of string
[@@deriving show]
type t = {
engine_box: Engine.event Lwt_mvar.t;
fixio_box: Fix_io.message Lwt_mvar.t;
send_box: Engine.message Lwt_mvar.t;
result_box: (unit, Engine.err) result Lwt_mvar.t;
engine: Engine.t;
log_file: string option;
fixio: Fix_io.fix_io option;
recv: event -> unit Lwt.t;
}
type handle = t
let get_msg_type message =
match List.assoc_opt "35" message with
| None -> Application
| Some k ->
(match Parse_admin_tags.parse_admin_msg_tag k with
| None -> Application
| Some _ -> Admin)
let mk_event message direction =
let msg_type = get_msg_type message in
FIXMessage { message; direction; msg_type }
let receive_fix_io t message =
Lwt.join
[
Engine.process_fix_wire t.engine message;
t.recv (mk_event message Incoming);
]
let receive_engine t event =
match event, t.fixio with
| Engine.FIXFromEngine message, Some fixio ->
Lwt.join [ Fix_io.send fixio message; t.recv (mk_event message Outgoing) ]
| Engine.Log msg, _ -> t.recv (Log msg)
| _ -> Lwt.return_unit
let receive_send t message =
let* result = Engine.send_fix_message t.engine message in
Lwt_mvar.put t.result_box result
let rec loop (t : t) : unit Lwt.t =
let rec loop_box box receiver =
let* msg = Lwt_mvar.take box in
let* () = receiver t msg in
loop_box box receiver
in
let* () =
Lwt.join
[
loop_box t.engine_box receive_engine;
loop_box t.fixio_box receive_fix_io;
loop_box t.send_box receive_send;
]
in
loop t
let with_catch_disconnect recv f =
Lwt.catch f (fun e ->
let stack = Printexc.get_backtrace () in
let msg = Printexc.to_string e in
let msg = Printf.sprintf "\n%s%s\n" msg stack in
recv (Disconnected msg))
let connection_lock = Lwt_mutex.create ()
let with_locks recv f =
Lwt_mutex.with_lock connection_lock @@ fun () -> with_catch_disconnect recv f
let addr_to_string = function
| Unix.ADDR_UNIX s -> s
| ADDR_INET (h, p) -> Printf.sprintf "%s:%d" (Unix.string_of_inet_addr h) p
let server_handler (t : t) (in_addr : Unix.sockaddr) (inch, outch) =
let addr_str = addr_to_string in_addr in
if Lwt_mutex.is_locked connection_lock then
t.recv (ConnectionRejected addr_str)
else
let* () = t.recv (Connected addr_str) in
with_locks t.recv @@ fun () ->
let recv = Lwt_mvar.put t.fixio_box in
let log_file = t.log_file in
let fixio_thread, fixio = Fix_io.start ~recv ?log_file (inch, outch) in
let t = { t with fixio = Some fixio } in
Lwt.pick [ fixio_thread; loop t ]
let default_session_folder ~(config : Engine.config) =
let hostid =
match config.host_id with
| None -> "NoHostid"
| Some host_id -> host_id
in
Printf.sprintf "%s.%s.%s.session" config.comp_id config.target_id hostid
let make_state_and_thread ~(session_dir : string option)
~(log_file : string option) ~(reset : bool option) ~(config : Engine.config)
~(recv : event -> unit Lwt.t) =
let reset =
match reset with
| None -> false
| Some x -> x
in
let session_dir =
match session_dir with
| Some x -> x
| None -> default_session_folder ~config
in
let engine_box = Lwt_mvar.create_empty () in
let fixio_box = Lwt_mvar.create_empty () in
let send_box = Lwt_mvar.create_empty () in
let result_box = Lwt_mvar.create_empty () in
let engine_thread, engine =
let recv = Lwt_mvar.put engine_box in
Engine.start ~reset ~session_dir ~config ~recv
in
let state =
{
fixio = None;
engine;
engine_box;
fixio_box;
send_box;
result_box;
recv;
log_file;
}
in
state, engine_thread
let start_server ?(session_dir : string option) ?(log_file : string option)
?(reset : bool option) ~(config : Engine.config) ~(port : int)
~(recv : event -> unit Lwt.t) () =
let state, engine_thread =
make_state_and_thread ~session_dir ~log_file ~reset ~config ~recv
in
let addr = Unix.(ADDR_INET (inet_addr_any, port)) in
let server_thread =
let handler = server_handler state in
let _server = Lwt_io.establish_server_with_client_address addr handler in
let* () = Lwt_io.printlf "FIX Server established on localhost:%d" port in
Lwt.return_unit
in
let thread = Lwt.join [ engine_thread; server_thread ] in
state, thread
let client_handler addr_str (t, engine_thread, init_msg) (inch, outch) =
let* () = t.recv (Connected addr_str) in
with_catch_disconnect t.recv @@ fun () ->
let recv = Lwt_mvar.put t.fixio_box in
let log_file = t.log_file in
let fixio_thread, fixio = Fix_io.start ~recv ?log_file (inch, outch) in
let fixio_thread =
let* () = fixio_thread in
t.recv (Disconnected addr_str)
in
let t = { t with fixio = Some fixio } in
let* () = Engine.send_internal_message t.engine init_msg in
Lwt.pick [ engine_thread; fixio_thread; loop t ]
let start_client ?(session_dir : string option) ?(log_file : string option)
?(reset : bool option) ~(config : Engine.config) ~(host : string)
~(port : int) ~(recv : event -> unit Lwt.t) () =
let state, engine_thread =
make_state_and_thread ~session_dir ~log_file ~reset ~config ~recv
in
let init_msg =
Fix_engine_state.(
IncIntMsg_CreateSession
{ dest_comp_id = config.target_id; reset_seq_num = false })
in
let addr = Unix.inet_addr_of_string host in
let addr = Unix.(ADDR_INET (addr, port)) in
let addr_str = addr_to_string addr in
let handler = client_handler addr_str (state, engine_thread, init_msg) in
let thread = Lwt_io.with_connection addr handler in
state, thread
let send_message t msg =
let* () = Lwt_mvar.put t.send_box msg in
Lwt_mvar.take t.result_box
* If [ final_seqnums ] is passed , these are written to the session dir
to be read on next startup of fix - engine .
If no seqnums are present on startup , fix - engine just starts from 0
to be read on next startup of fix-engine.
If no seqnums are present on startup, fix-engine just starts from 0
*)
let terminate ?final_seqnums (t : t) =
let () =
match final_seqnums with
| None -> ()
| Some (seqin, seqout) ->
Engine.persist_final_seqnums t.engine (seqin, seqout)
in
Engine.terminate t.engine
|
219a6fc14d242f867e4581334ee62afa2b671dea4cb8558e4240e6e7ede07a1b
|
burtonsamograd/med
|
point.lisp
|
(in-package :med)
Point motion .
(defun move-beginning-of-line (buffer)
(setf (mark-charpos (buffer-point buffer)) 0)
(values))
(defun move-end-of-line (buffer)
(let ((point (buffer-point buffer)))
(setf (mark-charpos point) (line-length (mark-line point))))
(values))
(defun move-beginning-of-buffer (buffer)
(setf (mark-line (buffer-point buffer)) (first-line buffer)
(mark-charpos (buffer-point buffer)) 0)
(values))
(defun move-end-of-buffer (buffer)
(let ((point (buffer-point buffer)))
(setf (mark-line point) (last-line buffer)
(mark-charpos point) (line-length (mark-line point))))
(values))
(defun move-mark (mark &optional (n 1))
"Move MARK forward by N character. Move backwards if N is negative.
Returns false when the mark reaches the start or end of the buffer, true otherwise."
(cond ((minusp n)
(setf n (- n))
(dotimes (i n)
(let ((current-line (mark-line mark)))
(cond ((zerop (mark-charpos mark))
(cond ((previous-line current-line)
;; At start of line.
(setf (mark-line mark) (previous-line current-line)
(mark-charpos mark) (line-length (previous-line current-line))))
(t ;; At start of buffer.
(return-from move-mark nil))))
(t ;; Moving within a line.
(decf (mark-charpos mark)))))))
(t
(dotimes (i n)
(let ((current-line (mark-line mark)))
(cond ((eql (line-length current-line) (mark-charpos mark))
(cond ((next-line current-line)
;; At end of line.
(setf (mark-line mark) (next-line current-line)
(mark-charpos mark) 0))
(t (return-from move-mark nil))))
(t ;; Moving within a line.
(incf (mark-charpos mark))))))))
t)
(defun move-char (buffer &optional (n 1))
"Move point forward by N characters. Move backwards if N is negative."
(move-mark (buffer-point buffer) n)
(values))
(defun move-line (buffer &optional (n 1))
"Move point down by N lines. N may be negative.
Tries to stay as close to the hint column as possible."
(let* ((accessor #'next-line)
(point (buffer-point buffer)))
(when (not (eql *last-command* 'next-line))
(setf (buffer-property buffer 'column-hint 0) (mark-charpos point)))
(setf *this-command* 'next-line)
(when (minusp n)
(setf n (- n)
accessor #'previous-line))
(dotimes (i n)
(let* ((current-line (mark-line point))
(new-line (funcall accessor current-line)))
(cond (new-line
(setf (mark-line point) new-line
(mark-charpos point) (min (buffer-property buffer 'column-hint)
(line-length new-line))))
(t (return))))))
(values))
(defun character-right-of (mark)
(cond ((end-of-line-p mark)
(cond
((next-line (mark-line mark))
;; At end of line.
#\Newline)
(t ;; At end of buffer.
nil)))
(t (line-character (mark-line mark) (mark-charpos mark)))))
(defun character-left-of (mark)
(cond ((start-of-line-p mark)
(cond
((previous-line (mark-line mark))
;; At start of line.
#\Newline)
(t ;; At start of buffer.
nil)))
(t (line-character (mark-line mark) (1- (mark-charpos mark))))))
(defun nth-character-left-of (mark nth)
(let ((buffer (line-buffer (mark-line mark))))
(save-excursion (buffer)
(dotimes (i (1- nth))
(move-mark mark -1))
(character-left-of mark))))
(defun scan (mark predicate jump key)
(loop
(let ((ch (funcall key mark)))
(when (not ch)
(return nil))
(when (funcall predicate ch)
(return t))
(when (not (move-mark mark jump))
(return nil)))))
(defun scan-forward (mark predicate)
(scan mark predicate 1 #'character-right-of))
(defun scan-backward (mark predicate)
(scan mark predicate -1 #'character-left-of))
(defun move-word (buffer &optional (n 1))
"Move point forward by N words. N may be negative."
(let ((point (buffer-point buffer))
(fn #'scan-forward))
(when (minusp n)
(setf n (- n)
fn #'scan-backward))
(dotimes (i n)
;; Forward past leading non-alphanumberic characters.
(funcall fn point #'alphanumericp)
;; And now past alphanumeric characters.
(funcall fn point (complement #'alphanumericp)))))
(defun scan-sexp-forward (mark)
(let ((pair-stack '())
(first-char t))
(flet ((whitespacep (ch)
(cond
((eql (sys.int::readtable-syntax-type ch nil) :whitespace) t)
((eql ch #\SEMICOLON) (scan-forward mark (lambda (c) (eql c #\Newline)))
t))))
;; Skip past any leading whitespace.
(scan-forward mark (complement #'whitespacep))
(loop
(let* ((ch (character-right-of mark))
(chl (character-left-of mark))
(chl2 (when (eql chl #\\) (nth-character-left-of mark 2))))
(when (not ch)
(return nil))
(when (and (whitespacep ch) (not pair-stack))
(return t))
(unless (and (eql chl #\\)
(eql chl2 #\#))
(cond ((eql ch (first pair-stack))
(pop pair-stack)
(when (not pair-stack)
;; Found last match, finished.
(move-mark mark 1)
(return t)))
((eql ch #\))
(if first-char
(error "Unmatched ~C." ch)
(return t)))
((eql ch #\")
(push #\" pair-stack))
((eql ch #\()
(push #\) pair-stack))))
(move-mark mark 1))
(setf first-char nil)))))
(defun scan-sexp-backward (mark)
(let ((pair-stack '())
(first-char t))
(flet ((whitespacep (ch)
(eql (sys.int::readtable-syntax-type ch nil) :whitespace)))
;; Skip past any leading whitespace.
(scan-backward mark (complement #'whitespacep))
(loop
(let ((ch (character-left-of mark)))
(when (not ch)
(return nil))
(when (and (whitespacep ch) (not pair-stack))
(return t))
(cond ((eql ch (first pair-stack))
(pop pair-stack)
(when (not pair-stack)
;; Found last match, finished.
(move-mark mark -1)
(return t)))
((eql ch #\()
(if first-char
(error "Unmatched ~C." ch)
(return t)))
((eql ch #\")
(push #\" pair-stack))
((eql ch #\))
(push #\( pair-stack)))
(move-mark mark -1))
(setf first-char nil)))))
(defun move-sexp (buffer &optional (n 1))
"Move point forward by N s-expressions. N may be negative."
(let ((point (buffer-point buffer))
(fn #'scan-sexp-forward))
(when (minusp n)
(setf n (- n)
fn #'scan-sexp-backward))
(dotimes (i n)
(funcall fn point))))
(defun test-fill (buffer)
(let ((width (1- (truncate (editor-width)
(mezzano.gui.font:glyph-advance
(mezzano.gui.font:character-to-glyph
(font *editor*) #\M))))))
(with-mark (mark point :left)
(dotimes (i (* (window-rows) 2))
(dotimes (j width)
(insert buffer (code-char (+ #x20 i))))
(insert buffer #\Newline))
(point-to-mark buffer mark))))
| null |
https://raw.githubusercontent.com/burtonsamograd/med/667c45032f60831447ad0eafd4d5c9a9748b4366/point.lisp
|
lisp
|
At start of line.
At start of buffer.
Moving within a line.
At end of line.
Moving within a line.
At end of line.
At end of buffer.
At start of line.
At start of buffer.
Forward past leading non-alphanumberic characters.
And now past alphanumeric characters.
Skip past any leading whitespace.
Found last match, finished.
Skip past any leading whitespace.
Found last match, finished.
|
(in-package :med)
Point motion .
(defun move-beginning-of-line (buffer)
(setf (mark-charpos (buffer-point buffer)) 0)
(values))
(defun move-end-of-line (buffer)
(let ((point (buffer-point buffer)))
(setf (mark-charpos point) (line-length (mark-line point))))
(values))
(defun move-beginning-of-buffer (buffer)
(setf (mark-line (buffer-point buffer)) (first-line buffer)
(mark-charpos (buffer-point buffer)) 0)
(values))
(defun move-end-of-buffer (buffer)
(let ((point (buffer-point buffer)))
(setf (mark-line point) (last-line buffer)
(mark-charpos point) (line-length (mark-line point))))
(values))
(defun move-mark (mark &optional (n 1))
"Move MARK forward by N character. Move backwards if N is negative.
Returns false when the mark reaches the start or end of the buffer, true otherwise."
(cond ((minusp n)
(setf n (- n))
(dotimes (i n)
(let ((current-line (mark-line mark)))
(cond ((zerop (mark-charpos mark))
(cond ((previous-line current-line)
(setf (mark-line mark) (previous-line current-line)
(mark-charpos mark) (line-length (previous-line current-line))))
(return-from move-mark nil))))
(decf (mark-charpos mark)))))))
(t
(dotimes (i n)
(let ((current-line (mark-line mark)))
(cond ((eql (line-length current-line) (mark-charpos mark))
(cond ((next-line current-line)
(setf (mark-line mark) (next-line current-line)
(mark-charpos mark) 0))
(t (return-from move-mark nil))))
(incf (mark-charpos mark))))))))
t)
(defun move-char (buffer &optional (n 1))
"Move point forward by N characters. Move backwards if N is negative."
(move-mark (buffer-point buffer) n)
(values))
(defun move-line (buffer &optional (n 1))
"Move point down by N lines. N may be negative.
Tries to stay as close to the hint column as possible."
(let* ((accessor #'next-line)
(point (buffer-point buffer)))
(when (not (eql *last-command* 'next-line))
(setf (buffer-property buffer 'column-hint 0) (mark-charpos point)))
(setf *this-command* 'next-line)
(when (minusp n)
(setf n (- n)
accessor #'previous-line))
(dotimes (i n)
(let* ((current-line (mark-line point))
(new-line (funcall accessor current-line)))
(cond (new-line
(setf (mark-line point) new-line
(mark-charpos point) (min (buffer-property buffer 'column-hint)
(line-length new-line))))
(t (return))))))
(values))
(defun character-right-of (mark)
(cond ((end-of-line-p mark)
(cond
((next-line (mark-line mark))
#\Newline)
nil)))
(t (line-character (mark-line mark) (mark-charpos mark)))))
(defun character-left-of (mark)
(cond ((start-of-line-p mark)
(cond
((previous-line (mark-line mark))
#\Newline)
nil)))
(t (line-character (mark-line mark) (1- (mark-charpos mark))))))
(defun nth-character-left-of (mark nth)
(let ((buffer (line-buffer (mark-line mark))))
(save-excursion (buffer)
(dotimes (i (1- nth))
(move-mark mark -1))
(character-left-of mark))))
(defun scan (mark predicate jump key)
(loop
(let ((ch (funcall key mark)))
(when (not ch)
(return nil))
(when (funcall predicate ch)
(return t))
(when (not (move-mark mark jump))
(return nil)))))
(defun scan-forward (mark predicate)
(scan mark predicate 1 #'character-right-of))
(defun scan-backward (mark predicate)
(scan mark predicate -1 #'character-left-of))
(defun move-word (buffer &optional (n 1))
"Move point forward by N words. N may be negative."
(let ((point (buffer-point buffer))
(fn #'scan-forward))
(when (minusp n)
(setf n (- n)
fn #'scan-backward))
(dotimes (i n)
(funcall fn point #'alphanumericp)
(funcall fn point (complement #'alphanumericp)))))
(defun scan-sexp-forward (mark)
(let ((pair-stack '())
(first-char t))
(flet ((whitespacep (ch)
(cond
((eql (sys.int::readtable-syntax-type ch nil) :whitespace) t)
((eql ch #\SEMICOLON) (scan-forward mark (lambda (c) (eql c #\Newline)))
t))))
(scan-forward mark (complement #'whitespacep))
(loop
(let* ((ch (character-right-of mark))
(chl (character-left-of mark))
(chl2 (when (eql chl #\\) (nth-character-left-of mark 2))))
(when (not ch)
(return nil))
(when (and (whitespacep ch) (not pair-stack))
(return t))
(unless (and (eql chl #\\)
(eql chl2 #\#))
(cond ((eql ch (first pair-stack))
(pop pair-stack)
(when (not pair-stack)
(move-mark mark 1)
(return t)))
((eql ch #\))
(if first-char
(error "Unmatched ~C." ch)
(return t)))
((eql ch #\")
(push #\" pair-stack))
((eql ch #\()
(push #\) pair-stack))))
(move-mark mark 1))
(setf first-char nil)))))
(defun scan-sexp-backward (mark)
(let ((pair-stack '())
(first-char t))
(flet ((whitespacep (ch)
(eql (sys.int::readtable-syntax-type ch nil) :whitespace)))
(scan-backward mark (complement #'whitespacep))
(loop
(let ((ch (character-left-of mark)))
(when (not ch)
(return nil))
(when (and (whitespacep ch) (not pair-stack))
(return t))
(cond ((eql ch (first pair-stack))
(pop pair-stack)
(when (not pair-stack)
(move-mark mark -1)
(return t)))
((eql ch #\()
(if first-char
(error "Unmatched ~C." ch)
(return t)))
((eql ch #\")
(push #\" pair-stack))
((eql ch #\))
(push #\( pair-stack)))
(move-mark mark -1))
(setf first-char nil)))))
(defun move-sexp (buffer &optional (n 1))
"Move point forward by N s-expressions. N may be negative."
(let ((point (buffer-point buffer))
(fn #'scan-sexp-forward))
(when (minusp n)
(setf n (- n)
fn #'scan-sexp-backward))
(dotimes (i n)
(funcall fn point))))
(defun test-fill (buffer)
(let ((width (1- (truncate (editor-width)
(mezzano.gui.font:glyph-advance
(mezzano.gui.font:character-to-glyph
(font *editor*) #\M))))))
(with-mark (mark point :left)
(dotimes (i (* (window-rows) 2))
(dotimes (j width)
(insert buffer (code-char (+ #x20 i))))
(insert buffer #\Newline))
(point-to-mark buffer mark))))
|
d4b10da70de5c985eb1dc040c1917a98dd211db5d563c14f48a62285b6df49ce
|
clojure-dus/chess
|
xboard_adapter.clj
|
(ns chess.xboard-adapter)
| null |
https://raw.githubusercontent.com/clojure-dus/chess/7eb0e5bf15290f520f31e7eb3f2b7742c7f27729/src/chess/xboard_adapter.clj
|
clojure
|
(ns chess.xboard-adapter)
|
|
1614a3f085ae7b6e0a6684db8ddedb87ff0ab442989167779a19d0e0a8616750
|
quil-lang/magicl
|
load-libs.lisp
|
;;;; load-libs.lisp
;;;;
Author :
(in-package #:magicl.foreign-libraries)
(cffi:define-foreign-library libexpokit
(:darwin (:or "libexpokit.dylib" "expokit.dylib"))
(:unix (:or "libexpokit.so" "expokit.so"))
(:windows (:or "libexpokit.dll" "expokit.dll"))
(t (:default "expokit")))
(pushnew 'libexpokit *foreign-libraries*)
(pushnew (first (asdf:output-files 'asdf:compile-op
(asdf:find-component
(asdf:find-component "magicl/ext-expokit" "expokit")
"expokit")))
cffi:*foreign-library-directories*
:test #'equal)
;; Keep above in sync with 'perform ((... compile-op) (... f->so))'
;; method in magicl.asd.
(export 'libexpokit)
(defvar *expokit-libs-loaded* nil)
(unless *expokit-libs-loaded*
(cffi:load-foreign-library 'libexpokit)
(setf *expokit-libs-loaded* t))
(magicl:define-backend :expokit
:documentation "Functions available from Expokit."
:default t)
| null |
https://raw.githubusercontent.com/quil-lang/magicl/c23abd55d245cd9f3eccf5e12631017032aa1f86/src/extensions/expokit/load-libs.lisp
|
lisp
|
load-libs.lisp
Keep above in sync with 'perform ((... compile-op) (... f->so))'
method in magicl.asd.
|
Author :
(in-package #:magicl.foreign-libraries)
(cffi:define-foreign-library libexpokit
(:darwin (:or "libexpokit.dylib" "expokit.dylib"))
(:unix (:or "libexpokit.so" "expokit.so"))
(:windows (:or "libexpokit.dll" "expokit.dll"))
(t (:default "expokit")))
(pushnew 'libexpokit *foreign-libraries*)
(pushnew (first (asdf:output-files 'asdf:compile-op
(asdf:find-component
(asdf:find-component "magicl/ext-expokit" "expokit")
"expokit")))
cffi:*foreign-library-directories*
:test #'equal)
(export 'libexpokit)
(defvar *expokit-libs-loaded* nil)
(unless *expokit-libs-loaded*
(cffi:load-foreign-library 'libexpokit)
(setf *expokit-libs-loaded* t))
(magicl:define-backend :expokit
:documentation "Functions available from Expokit."
:default t)
|
addca60a534b40bbf0feb88b67055cc7c12946a9a910d29e65ebaa6f13bd930e
|
babashka/babashka
|
bb_edn_test.clj
|
(ns babashka.bb-edn-test
(:require
[babashka.fs :as fs]
[babashka.impl.classpath :as cp]
[babashka.impl.common :as common]
[babashka.main :as main]
[babashka.test-utils :as test-utils]
[borkdude.deps]
[clojure.edn :as edn]
[clojure.string :as str]
[clojure.test :as test :refer [deftest is testing]]))
(defn bb [& args]
(let [args (map str args)
ret (apply test-utils/bb nil args)]
;; (.println System/out :args)
;; (.println System/out (vec args))
( .println System / out : ret )
( .println System / out ret )
(edn/read-string
{:readers *data-readers*
:eof nil}
ret)))
(deftest deps-test
(test-utils/with-config '{:deps {medley/medley {:mvn/version "1.3.0"}}}
(is (= '{1 {:id 1}, 2 {:id 2}}
(bb "-e" "(require 'medley.core)" "-e" "(medley.core/index-by :id [{:id 1} {:id 2}])"))))
(test-utils/with-config '{:deps {medley/medley {:mvn/version "1.3.0"}}}
(let [cp (bb "-e" "(do (require '[babashka.classpath :as cp])
(cp/split-classpath (cp/get-classpath)))")]
(is (= 1 (count cp)))
(is (str/includes? (first cp) "medley"))))
(testing "--classpath option overrides bb.edn"
(test-utils/with-config '{:deps {medley/medley {:mvn/version "1.3.0"}}}
(is (= "src"
(bb "-cp" "src" "-e" "(babashka.classpath/get-classpath)"))))))
(deftest print-deps-test
(test-utils/with-config '{:deps {medley/medley {:mvn/version "1.3.0"}}}
(testing "deps output"
(let [edn (bb "print-deps")
deps (:deps edn)]
(is deps)
(is (map? (get deps 'selmer/selmer)))
(is (string? (:mvn/version (get deps 'selmer/selmer))))
(testing "user provided lib"
(is (map? (get deps 'medley/medley))))))
(testing "classpath output"
(let [classpath (test-utils/bb nil "print-deps" "--format" "classpath")]
(is (str/includes? classpath "selmer"))
(is (str/includes? classpath (System/getProperty "path.separator")))
(is (str/includes? classpath "medley"))))))
(deftest task-test
(test-utils/with-config '{:tasks {foo (+ 1 2 3)}}
(is (= 6 (bb "run" "--prn" "foo"))))
(testing "init test"
(test-utils/with-config '{:tasks {:init (def x 1)
foo x}}
(is (= 1 (bb "run" "--prn" "foo")))))
(testing "requires test"
(test-utils/with-config '{:tasks {:requires ([babashka.fs :as fs])
foo (fs/exists? ".")}}
(is (= true (bb "run" "--prn" "foo"))))
(test-utils/with-config '{:tasks {foo {:requires ([babashka.fs :as fs])
:task (fs/exists? ".")}}}
(is (= true (bb "run" "--prn" "foo"))))
(test-utils/with-config '{:tasks {bar {:requires ([babashka.fs :as fs])}
foo {:depends [bar]
:task (fs/exists? ".")}}}
(is (= true (bb "run" "--prn" "foo")))))
(testing "map returned from task"
(test-utils/with-config '{:tasks {foo {:task {:a 1 :b 2}}}}
(is (= {:a 1 :b 2} (bb "run" "--prn" "foo")))))
(let [tmp-dir (fs/create-temp-dir)
out (str (fs/file tmp-dir "out.txt"))
echo-cmd (if main/windows? "cmd /c echo" "echo")
ls-cmd (if main/windows? "cmd /c dir" "ls")
fix-lines test-utils/normalize]
(testing "shell test"
(test-utils/with-config {:tasks {'foo (list 'shell {:out out}
echo-cmd "hello")}}
(bb "foo")
(is (= "hello\n" (fix-lines (slurp out))))))
(fs/delete out)
(testing "shell test with :continue fn"
(test-utils/with-config {:tasks {'foo (list '-> (list 'shell {:out out
:err out
:continue '(fn [proc]
(contains? proc :exit))}
ls-cmd "foobar")
:exit)}}
(is (pos? (bb "run" "--prn" "foo")))))
(testing "shell test with :error"
(test-utils/with-config
{:tasks {'foo (list '-> (list 'shell {:out out
:err out
:error-fn '(constantly 1337)}
ls-cmd "foobar"))}}
(is (= 1337 (bb "run" "--prn" "foo"))))
(test-utils/with-config
{:tasks {'foo (list '-> (list 'shell {:out out
:err out
:error-fn
'(fn [opts]
(and (:task opts)
(:proc opts)
(not (zero? (:exit (:proc opts))))))}
ls-cmd "foobar"))}}
(is (true? (bb "run" "--prn" "foo")))))
(fs/delete out)
(testing "clojure test"
(test-utils/with-config {:tasks {'foo (list 'clojure {:out out}
"-M -e" "(println :yolo)")}}
(bb "foo")
(is (= ":yolo\n" (fix-lines (slurp out))))))
(fs/delete out)
(testing "depends"
(test-utils/with-config {:tasks {'quux (list 'spit out "quux\n")
'baz (list 'spit out "baz\n" :append true)
'bar {:depends ['baz]
:task (list 'spit out "bar\n" :append true)}
'foo {:depends ['quux 'bar 'baz]
:task (list 'spit out "foo\n" :append true)}}}
(bb "foo")
(is (= "quux\nbaz\nbar\nfoo\n" (slurp out)))))
(fs/delete out)
;; This is why we don't support :when for now
#_(testing "depends with :when"
(test-utils/with-config {:tasks {'quux (list 'spit out "quux\n")
'baz (list 'spit out "baz\n" :append true)
'bar {:when false
:depends ['baz]
:task (list 'spit out "bar\n" :append true)}
'foo {:depends ['quux 'bar]
:task (list 'spit out "foo\n" :append true)}}}
(bb "foo")
(is (= "quux\nbaz\nbar\nfoo\n" (slurp out))))))
(testing "fully qualified symbol execution"
(test-utils/with-config {:paths ["test-resources/task_scripts"]
:tasks '{foo tasks/foo}}
(is (= :foo (bb "run" "--prn" "foo"))))
(test-utils/with-config {:paths ["test-resources/task_scripts"]
:tasks '{:requires ([tasks :as t])
foo t/foo}}
(is (= :foo (bb "run" "--prn" "foo"))))
(test-utils/with-config {:paths ["test-resources/task_scripts"]
:tasks '{foo {:requires ([tasks :as t])
:task t/foo}}}
(is (= :foo (bb "run" "--prn" "foo")))))
(testing "extra-paths"
(test-utils/with-config {:paths ["test-resources/task_scripts"]
:tasks '{:requires ([tasks :as t])
foo {:extra-paths ["test-resources/task_test_scripts"]
:requires ([task-test :as tt])
:task tt/task-test-fn}}}
(is (= :task-test-fn (bb "run" "--prn" "foo")))))
(testing "extra-deps"
(test-utils/with-config {:tasks '{foo {:extra-deps {medley/medley {:mvn/version "1.3.0"}}
:requires ([medley.core :as m])
:task (m/index-by :id [{:id 1} {:id 2}])}}}
(is (= {1 {:id 1}, 2 {:id 2}} (bb "run" "--prn" "foo")))))
(testing "enter / leave"
(test-utils/with-config '{:tasks {:init (do (def enter-ctx (atom []))
(def leave-ctx (atom [])))
:enter (swap! enter-ctx conj (:name (current-task)))
:leave (swap! leave-ctx conj (:name (current-task)))
foo {:depends [bar]
:task [@enter-ctx @leave-ctx]}
bar {:depends [baz]}
baz {:enter nil
:leave nil}}}
(is (= '[[bar foo] [bar]] (bb "run" "--prn" "foo")))))
(testing "run"
(test-utils/with-config '{:tasks {a (+ 1 2 3)
b (prn (run 'a))}}
(is (= 6 (bb "run" "b")))))
(testing "no such task"
(test-utils/with-config '{:tasks {a (+ 1 2 3)}}
(is (thrown-with-msg?
Exception #"No such task: b"
(bb "run" "b")))))
(testing "unresolved dependency"
(test-utils/with-config '{:tasks {a (+ 1 2 3)
b {:depends [x]
:task (+ a 4 5 6)}}}
(is (thrown-with-msg?
Exception #"No such task: x"
(bb "run" "b")))))
(testing "cyclic task"
(test-utils/with-config '{:tasks {b {:depends [b]
:task (+ a 4 5 6)}}}
(is (thrown-with-msg?
Exception #"Cyclic task: b"
(bb "run" "b"))))
(test-utils/with-config '{:tasks {c {:depends [b]}
b {:depends [c]
:task (+ a 4 5 6)}}}
(is (thrown-with-msg?
Exception #"Cyclic task: b"
(bb "run" "b")))))
(testing "friendly regex literal error handling"
(test-utils/with-config
"{:tasks {something (clojure.string/split \"1-2\" #\"-\")}}"
(is (thrown-with-msg?
Exception #"Invalid regex literal"
(bb "run" "something")))))
(testing "doc"
(test-utils/with-config '{:tasks {b {:doc "Beautiful docstring"}}}
(let [s (test-utils/bb nil "doc" "b")]
(is (= "-------------------------\nb\nTask\nBeautiful docstring\n" s)))))
(testing "system property"
(test-utils/with-config '{:tasks {b (System/getProperty "babashka.task")}}
(let [s (bb "run" "--prn" "b")]
(is (= "b" s)))))
(testing "parallel test"
(test-utils/with-config (edn/read-string (slurp "test-resources/coffee-tasks.edn"))
(let [tree [:made-coffee [[:ground-beans [:measured-beans]] [:heated-water [:poured-water]] :filter :mug]]
t0 (System/currentTimeMillis)
s (bb "run" "--prn" "coffeep")
t1 (System/currentTimeMillis)
delta-sequential (- t1 t0)]
(is (= tree s))
(test-utils/with-config (edn/read-string (slurp "test-resources/coffee-tasks.edn"))
(let [t0 (System/currentTimeMillis)
s (bb "run" "--parallel" "--prn" "coffeep")
t1 (System/currentTimeMillis)
delta-parallel (- t1 t0)]
(is (= tree s))
(when (>= (doto (-> (Runtime/getRuntime) (.availableProcessors))
(prn))
2)
(is (< delta-parallel delta-sequential)))))))
(testing "exception"
(test-utils/with-config '{:tasks {a (Thread/sleep 10000)
b (do (Thread/sleep 10)
(throw (ex-info "0 noes" {})))
c {:depends [a b]}}}
(is (thrown-with-msg? Exception #"0 noes"
(bb "run" "--parallel" "c")))))
(testing "edge case"
(test-utils/with-config '{:tasks
{a (run '-a {:parallel true})
-a {:depends [a:a a:b c]
:task (prn [a:a a:b c])}
a:a {:depends [c]
:task (+ 1 2 3)}
a:b {:depends [c]
:task (do (Thread/sleep 10)
(+ 1 2 3))}
c (do (Thread/sleep 10) :c)}}
(is (= [6 6 :c] (bb "run" "--prn" "a"))))))
(testing "dynamic vars"
(test-utils/with-config '{:tasks
{:init (def ^:dynamic *foo* true)
a (do
(def ^:dynamic *bar* false)
(binding [*foo* false
*bar* true]
[*foo* *bar*]))}}
(is (= [false true] (bb "run" "--prn" "a")))))
(testing "stable namespace name"
(test-utils/with-config '{:tasks
{:init (do (def ^:dynamic *jdk*)
(def ^:dynamic *server*))
server [*jdk* *server*]
run-all (for [jdk [8 11 15]
server [:foo :bar]]
(binding [*jdk* jdk
*server* server]
(babashka.tasks/run 'server)))}}
(is (= '([8 :foo] [8 :bar] [11 :foo] [11 :bar] [15 :foo] [15 :bar])
(bb "run" "--prn" "run-all")))))
TODO : disabled because of " Volume in drive C has no label.\r\n Volume Serial Number is 1CB8 - D4AA\r\n\r\n Directory of C:\\projects\\babashka\r\n\r\n " on Appveyor . See .
(testing "shell test with :continue"
(let [ls-cmd (if main/windows? "cmd /c dir" "ls")]
(test-utils/with-config {:tasks {'foo (list 'do
(list 'shell {:continue true}
(str ls-cmd " foobar"))
(list 'println :hello))}}
(is (str/includes? (test-utils/bb nil "foo") ":hello"))))))
(deftest ^:skip-windows unix-task-test
(testing "shell pipe test"
(test-utils/with-config '{:tasks {a (-> (shell {:out :string}
"echo hello")
(shell {:out :string} "cat")
:out)}}
(let [s (bb "run" "--prn" "a")]
(is (= "hello\n" s))))))
(deftest ^:windows-only win-task-test
(when main/windows?
(testing "shell pipe test"
this task prints the contents of deps.edn
(test-utils/with-config '{:tasks {a (->> (shell {:out :string}
"cmd /c echo deps.edn")
:out
clojure.string/trim-newline
(shell {:out :string} "cmd /c type")
:out)}}
(let [s (bb "run" "--prn" "a")]
(is (str/includes? s "paths")))))))
(deftest tasks:clojure-test
(testing "tokenization when called from tasks"
(test-utils/with-config
(pr-str '{:tasks {foo (-> (clojure {:out :string} "-J-Dfoo=\"{:port 5555 :accept clojure.core.server/repl}\" -M -e \"(clojure.edn/read-string (System/getProperty (name :foo)))\"") :out clojure.edn/read-string prn)}})
(is (= '{:port 5555, :accept clojure.core.server/repl}
(bb "run" "foo")))))
(testing "can be called without args"
(test-utils/with-config
(pr-str '{:tasks {foo (-> (clojure {:in "(+ 1 2 3)" :out :string}) :out prn)}})
(is (str/includes? (bb "run" "foo") "6")))
ca n't properly test this , but ` ( clojure ) ` should work with zero args
#_(test-utils/with-config
(pr-str '{:tasks {foo (-> (clojure) :out prn)}})
(is (str/includes? (test-utils/bb "(+ 1 2 3)" "run" "foo") "6")))))
(deftest list-tasks-test
(test-utils/with-config {}
(let [res (test-utils/bb nil "tasks")]
(is (str/includes? res "No tasks found."))))
(test-utils/with-config '{:tasks {:x 1}}
(let [res (test-utils/bb nil "tasks")]
(is (str/includes? res "No tasks found."))))
(test-utils/with-config '{:tasks {-xyz 5}}
(let [res (test-utils/bb nil "tasks")]
(is (str/includes? res "No tasks found."))))
(test-utils/with-config '{:tasks {xyz {:private true}}}
(let [res (test-utils/bb nil "tasks")]
(is (str/includes? res "No tasks found."))))
(test-utils/with-config '{:tasks {abc 1 xyz 2}}
(let [res (test-utils/bb nil "tasks")]
(is (= "The following tasks are available:\n\nabc\nxyz\n" res))))
(test-utils/with-config '{:tasks {abc 1 xyz {:doc "some text" :tasks 5}
-xyz 3 qrs {:private true}}}
(let [res (test-utils/bb nil "tasks")]
(is (= "The following tasks are available:\n\nabc\nxyz some text\n" res))))
(test-utils/with-config '{:tasks {xyz 1 abc 2}}
(let [res (test-utils/bb nil "tasks")]
(is (= "The following tasks are available:\n\nxyz\nabc\n" res))))
(test-utils/with-config "{:paths [\"test-resources/task_scripts\"]
:tasks {:requires ([tasks :as t])
task1
{:doc \"task1 doc
more stuff here
even more stuff here\"
:task (+ 1 2 3)}
task2
{:doc \"task2 doc\"
:task (+ 4 5 6)}
-task3
{:task (+ 1 2 3)}
task4
{:task (+ 1 2 3)
:private true}
foo tasks/foo
bar t/foo
baz non-existing/bar
quux {:requires ([tasks :as t2])
:task t2/foo}}}"
(let [res (test-utils/bb nil "tasks")]
(is (= "The following tasks are available:\n\ntask1 task1 doc\ntask2 task2 doc\nfoo Foo docstring\nbar Foo docstring\nbaz \nquux Foo docstring\n"
res))))
(testing ":tasks is the first node"
(test-utils/with-config "{:tasks {task1
{:doc \"task1 doc\"
:task (+ 1 2 3)}}}"
(let [res (test-utils/bb nil "tasks")]
(is (= "The following tasks are available:\n\ntask1 task1 doc\n"
res))))))
(deftest task-priority-test
(when-not test-utils/native?
(testing "FILE > TASK > SUBCOMMAND"
(is (= "foo.jar" (:uberjar (main/parse-opts ["uberjar" "foo.jar"]))))
(vreset! common/bb-edn '{:tasks {uberjar (+ 1 2 3)}})
(is (= "uberjar" (:run (main/parse-opts ["uberjar"]))))
(try
(spit "uberjar" "#!/usr/bin/env bb\n(+ 1 2 3)")
(vreset! common/bb-edn '{:tasks {uberjar (+ 1 2 3)}})
(is (= "uberjar" (:file (main/parse-opts ["uberjar"]))))
(finally (fs/delete "uberjar"))))))
(deftest min-bb-version-test
(fs/with-temp-dir [dir {}]
(let [config (str (fs/file dir "bb.edn"))]
(spit config '{:min-bb-version "300.0.0"})
(let [sw (java.io.StringWriter.)]
(binding [*err* sw]
(main/main "--config" config "-e" "nil"))
(is (str/includes? (str sw)
"WARNING: this project requires babashka 300.0.0 or newer, but you have: "))))))
(deftest classpath-other-bb-edn-test
(fs/with-temp-dir [dir {}]
(let [config (str (fs/file dir "bb.edn"))]
(spit config '{:paths ["src"]
:tasks {cp (prn (babashka.classpath/get-classpath))}})
(let [out (bb "--config" config "cp")
entries (cp/split-classpath out)
entry (first entries)]
(is (= 1 (count entries)))
(is (= (fs/parent config) (fs/parent entry)))
(is (str/ends-with? entry "src"))))))
(deftest without-deps-test
(when-not test-utils/native?
(with-redefs [borkdude.deps/-main (fn [& _]
(throw (ex-info "This ain't allowed!" {})))]
(testing "bb.edn without :deps should not require deps.clj"
(test-utils/with-config '{:tasks {a 1}}
(bb "-e" "(+ 1 2 3)"))))))
(deftest deps-race-condition-test
(test-utils/with-config
(pr-str '{:tasks {task-b (do
(Thread/sleep 10)
:task00-out)
task-c {:depends [task-b]
:task (do
(println
"task-b: "
(type task-b))
{})}
task-a {:task (do
(Thread/sleep 10)
:task0-out)}
task-e {:depends [task-e1] :task {}}
task-e2 {:depends [task-a] :task {}}
task-e3 {:depends [task-b] :task {}}
task-e1 {:depends [task-e2 task-e3]
:task {}}
task-h {:depends [task-a task-b]
:task {}}
task-d {:task (do (Thread/sleep 2) {})}
task-f {:depends [task-d task-e task-a]
:task {}}
task-g {:depends [task-f
task-d
task-a
task-c
task-h]
:task {}}}})
(time (dotimes [_ 50]
(is (str/includes? (test-utils/bb nil "run" "--parallel" "task-g")
"task-b: clojure.lang.Keyword"))))))
(deftest parallel-nil-results-test
(test-utils/with-config
(pr-str '{:tasks {a (do nil)
b (do nil)
c (do nil)
d {:depends [a b c]
:task (prn [a b c])}}})
(is (= [nil nil nil] (bb "run" "--parallel" "d")))))
(deftest current-task-result-test
(test-utils/with-config
(pr-str '{:tasks {:leave (prn [(:name (current-task)) (:result (current-task))])
a 1
b 2
c {:depends [a b]
:task [a b]}}})
(is (= ["[a 1]" "[b 2]" "[c [1 2]]"] (str/split-lines (test-utils/bb nil "run" "c"))))))
(deftest pod-from-registry-test
(when (= "amd64" (System/getProperty "os.arch")) ; TODO: Build bootleg for aarch64 too or use a different pod
(test-utils/with-config
(pr-str '{:paths ["test-resources"]
:pods {retrogradeorbit/bootleg {:version "0.1.9"}}})
(is (= "\"<div><p>Test</p></div>\"\n"
(test-utils/bb nil "--prn" "-m" "pod-tests.bootleg"))))))
(deftest ^:skip-windows local-pod-test
(test-utils/with-config
(pr-str '{:paths ["test-resources"]
:pods {pod/test-pod {:path "test-resources/pod"}}})
(is (= "42\n" (test-utils/bb nil "-m" "pod-tests.local")))))
(deftest tag-test
(test-utils/with-config
"{:deps {}
:aliases {:foo {:env-vars {:dude #env \"DUDE\"}}}}"
(is (= 6 (bb "-e" "(+ 1 2 3)")))))
(deftest merge-deps-test
(test-utils/with-config
"{:deps {}}"
(is (= {1 {:a 1}}
(bb "-Sdeps" "{:deps {medley/medley {:mvn/version \"1.4.0\"}}}" "-e" "(require 'medley.core) (medley.core/index-by :a [{:a 1}])")))))
(deftest deps-root-test
(fs/with-temp-dir [dir {}]
(let [f (fs/file dir "bb.edn")
config (str f)]
(spit config
'{:paths ["src"]
:tasks {cp (prn (babashka.classpath/get-classpath))}})
(testing "custom deps-root path"
(let [out (bb "--config" config "--deps-root" (str dir) "cp")
entries (cp/split-classpath out)]
(is (= 1 (count entries)))
(is (= (fs/file dir "src") (fs/file (first entries))))))
(testing "default deps-root path is same as bb.edn"
(let [out (bb "--config" config "cp")
entries (cp/split-classpath out)]
(is (= (fs/parent f) (fs/parent (first entries))))))
(spit config
'{:paths ["src"]
:deps {local/dep {:local/root "local-dep"}}
:tasks {cp (prn (babashka.classpath/get-classpath))}})
(testing "relative paths in deps should be relative to bb.edn"
(let [root (fs/create-dir (fs/file dir "local-dep"))
_ (spit (str (fs/file root "deps.edn")) {})
out (bb "--config" config "cp")
entries (cp/split-classpath out)]
(is (= (fs/parent f) (fs/parent (first entries)))))))))
| null |
https://raw.githubusercontent.com/babashka/babashka/42fd5d851f8c29a39826e4b57c1b9da53608cdc3/test/babashka/bb_edn_test.clj
|
clojure
|
(.println System/out :args)
(.println System/out (vec args))
This is why we don't support :when for now
TODO: Build bootleg for aarch64 too or use a different pod
|
(ns babashka.bb-edn-test
(:require
[babashka.fs :as fs]
[babashka.impl.classpath :as cp]
[babashka.impl.common :as common]
[babashka.main :as main]
[babashka.test-utils :as test-utils]
[borkdude.deps]
[clojure.edn :as edn]
[clojure.string :as str]
[clojure.test :as test :refer [deftest is testing]]))
(defn bb [& args]
(let [args (map str args)
ret (apply test-utils/bb nil args)]
( .println System / out : ret )
( .println System / out ret )
(edn/read-string
{:readers *data-readers*
:eof nil}
ret)))
(deftest deps-test
(test-utils/with-config '{:deps {medley/medley {:mvn/version "1.3.0"}}}
(is (= '{1 {:id 1}, 2 {:id 2}}
(bb "-e" "(require 'medley.core)" "-e" "(medley.core/index-by :id [{:id 1} {:id 2}])"))))
(test-utils/with-config '{:deps {medley/medley {:mvn/version "1.3.0"}}}
(let [cp (bb "-e" "(do (require '[babashka.classpath :as cp])
(cp/split-classpath (cp/get-classpath)))")]
(is (= 1 (count cp)))
(is (str/includes? (first cp) "medley"))))
(testing "--classpath option overrides bb.edn"
(test-utils/with-config '{:deps {medley/medley {:mvn/version "1.3.0"}}}
(is (= "src"
(bb "-cp" "src" "-e" "(babashka.classpath/get-classpath)"))))))
(deftest print-deps-test
(test-utils/with-config '{:deps {medley/medley {:mvn/version "1.3.0"}}}
(testing "deps output"
(let [edn (bb "print-deps")
deps (:deps edn)]
(is deps)
(is (map? (get deps 'selmer/selmer)))
(is (string? (:mvn/version (get deps 'selmer/selmer))))
(testing "user provided lib"
(is (map? (get deps 'medley/medley))))))
(testing "classpath output"
(let [classpath (test-utils/bb nil "print-deps" "--format" "classpath")]
(is (str/includes? classpath "selmer"))
(is (str/includes? classpath (System/getProperty "path.separator")))
(is (str/includes? classpath "medley"))))))
(deftest task-test
(test-utils/with-config '{:tasks {foo (+ 1 2 3)}}
(is (= 6 (bb "run" "--prn" "foo"))))
(testing "init test"
(test-utils/with-config '{:tasks {:init (def x 1)
foo x}}
(is (= 1 (bb "run" "--prn" "foo")))))
(testing "requires test"
(test-utils/with-config '{:tasks {:requires ([babashka.fs :as fs])
foo (fs/exists? ".")}}
(is (= true (bb "run" "--prn" "foo"))))
(test-utils/with-config '{:tasks {foo {:requires ([babashka.fs :as fs])
:task (fs/exists? ".")}}}
(is (= true (bb "run" "--prn" "foo"))))
(test-utils/with-config '{:tasks {bar {:requires ([babashka.fs :as fs])}
foo {:depends [bar]
:task (fs/exists? ".")}}}
(is (= true (bb "run" "--prn" "foo")))))
(testing "map returned from task"
(test-utils/with-config '{:tasks {foo {:task {:a 1 :b 2}}}}
(is (= {:a 1 :b 2} (bb "run" "--prn" "foo")))))
(let [tmp-dir (fs/create-temp-dir)
out (str (fs/file tmp-dir "out.txt"))
echo-cmd (if main/windows? "cmd /c echo" "echo")
ls-cmd (if main/windows? "cmd /c dir" "ls")
fix-lines test-utils/normalize]
(testing "shell test"
(test-utils/with-config {:tasks {'foo (list 'shell {:out out}
echo-cmd "hello")}}
(bb "foo")
(is (= "hello\n" (fix-lines (slurp out))))))
(fs/delete out)
(testing "shell test with :continue fn"
(test-utils/with-config {:tasks {'foo (list '-> (list 'shell {:out out
:err out
:continue '(fn [proc]
(contains? proc :exit))}
ls-cmd "foobar")
:exit)}}
(is (pos? (bb "run" "--prn" "foo")))))
(testing "shell test with :error"
(test-utils/with-config
{:tasks {'foo (list '-> (list 'shell {:out out
:err out
:error-fn '(constantly 1337)}
ls-cmd "foobar"))}}
(is (= 1337 (bb "run" "--prn" "foo"))))
(test-utils/with-config
{:tasks {'foo (list '-> (list 'shell {:out out
:err out
:error-fn
'(fn [opts]
(and (:task opts)
(:proc opts)
(not (zero? (:exit (:proc opts))))))}
ls-cmd "foobar"))}}
(is (true? (bb "run" "--prn" "foo")))))
(fs/delete out)
(testing "clojure test"
(test-utils/with-config {:tasks {'foo (list 'clojure {:out out}
"-M -e" "(println :yolo)")}}
(bb "foo")
(is (= ":yolo\n" (fix-lines (slurp out))))))
(fs/delete out)
(testing "depends"
(test-utils/with-config {:tasks {'quux (list 'spit out "quux\n")
'baz (list 'spit out "baz\n" :append true)
'bar {:depends ['baz]
:task (list 'spit out "bar\n" :append true)}
'foo {:depends ['quux 'bar 'baz]
:task (list 'spit out "foo\n" :append true)}}}
(bb "foo")
(is (= "quux\nbaz\nbar\nfoo\n" (slurp out)))))
(fs/delete out)
#_(testing "depends with :when"
(test-utils/with-config {:tasks {'quux (list 'spit out "quux\n")
'baz (list 'spit out "baz\n" :append true)
'bar {:when false
:depends ['baz]
:task (list 'spit out "bar\n" :append true)}
'foo {:depends ['quux 'bar]
:task (list 'spit out "foo\n" :append true)}}}
(bb "foo")
(is (= "quux\nbaz\nbar\nfoo\n" (slurp out))))))
(testing "fully qualified symbol execution"
(test-utils/with-config {:paths ["test-resources/task_scripts"]
:tasks '{foo tasks/foo}}
(is (= :foo (bb "run" "--prn" "foo"))))
(test-utils/with-config {:paths ["test-resources/task_scripts"]
:tasks '{:requires ([tasks :as t])
foo t/foo}}
(is (= :foo (bb "run" "--prn" "foo"))))
(test-utils/with-config {:paths ["test-resources/task_scripts"]
:tasks '{foo {:requires ([tasks :as t])
:task t/foo}}}
(is (= :foo (bb "run" "--prn" "foo")))))
(testing "extra-paths"
(test-utils/with-config {:paths ["test-resources/task_scripts"]
:tasks '{:requires ([tasks :as t])
foo {:extra-paths ["test-resources/task_test_scripts"]
:requires ([task-test :as tt])
:task tt/task-test-fn}}}
(is (= :task-test-fn (bb "run" "--prn" "foo")))))
(testing "extra-deps"
(test-utils/with-config {:tasks '{foo {:extra-deps {medley/medley {:mvn/version "1.3.0"}}
:requires ([medley.core :as m])
:task (m/index-by :id [{:id 1} {:id 2}])}}}
(is (= {1 {:id 1}, 2 {:id 2}} (bb "run" "--prn" "foo")))))
(testing "enter / leave"
(test-utils/with-config '{:tasks {:init (do (def enter-ctx (atom []))
(def leave-ctx (atom [])))
:enter (swap! enter-ctx conj (:name (current-task)))
:leave (swap! leave-ctx conj (:name (current-task)))
foo {:depends [bar]
:task [@enter-ctx @leave-ctx]}
bar {:depends [baz]}
baz {:enter nil
:leave nil}}}
(is (= '[[bar foo] [bar]] (bb "run" "--prn" "foo")))))
(testing "run"
(test-utils/with-config '{:tasks {a (+ 1 2 3)
b (prn (run 'a))}}
(is (= 6 (bb "run" "b")))))
(testing "no such task"
(test-utils/with-config '{:tasks {a (+ 1 2 3)}}
(is (thrown-with-msg?
Exception #"No such task: b"
(bb "run" "b")))))
(testing "unresolved dependency"
(test-utils/with-config '{:tasks {a (+ 1 2 3)
b {:depends [x]
:task (+ a 4 5 6)}}}
(is (thrown-with-msg?
Exception #"No such task: x"
(bb "run" "b")))))
(testing "cyclic task"
(test-utils/with-config '{:tasks {b {:depends [b]
:task (+ a 4 5 6)}}}
(is (thrown-with-msg?
Exception #"Cyclic task: b"
(bb "run" "b"))))
(test-utils/with-config '{:tasks {c {:depends [b]}
b {:depends [c]
:task (+ a 4 5 6)}}}
(is (thrown-with-msg?
Exception #"Cyclic task: b"
(bb "run" "b")))))
(testing "friendly regex literal error handling"
(test-utils/with-config
"{:tasks {something (clojure.string/split \"1-2\" #\"-\")}}"
(is (thrown-with-msg?
Exception #"Invalid regex literal"
(bb "run" "something")))))
(testing "doc"
(test-utils/with-config '{:tasks {b {:doc "Beautiful docstring"}}}
(let [s (test-utils/bb nil "doc" "b")]
(is (= "-------------------------\nb\nTask\nBeautiful docstring\n" s)))))
(testing "system property"
(test-utils/with-config '{:tasks {b (System/getProperty "babashka.task")}}
(let [s (bb "run" "--prn" "b")]
(is (= "b" s)))))
(testing "parallel test"
(test-utils/with-config (edn/read-string (slurp "test-resources/coffee-tasks.edn"))
(let [tree [:made-coffee [[:ground-beans [:measured-beans]] [:heated-water [:poured-water]] :filter :mug]]
t0 (System/currentTimeMillis)
s (bb "run" "--prn" "coffeep")
t1 (System/currentTimeMillis)
delta-sequential (- t1 t0)]
(is (= tree s))
(test-utils/with-config (edn/read-string (slurp "test-resources/coffee-tasks.edn"))
(let [t0 (System/currentTimeMillis)
s (bb "run" "--parallel" "--prn" "coffeep")
t1 (System/currentTimeMillis)
delta-parallel (- t1 t0)]
(is (= tree s))
(when (>= (doto (-> (Runtime/getRuntime) (.availableProcessors))
(prn))
2)
(is (< delta-parallel delta-sequential)))))))
(testing "exception"
(test-utils/with-config '{:tasks {a (Thread/sleep 10000)
b (do (Thread/sleep 10)
(throw (ex-info "0 noes" {})))
c {:depends [a b]}}}
(is (thrown-with-msg? Exception #"0 noes"
(bb "run" "--parallel" "c")))))
(testing "edge case"
(test-utils/with-config '{:tasks
{a (run '-a {:parallel true})
-a {:depends [a:a a:b c]
:task (prn [a:a a:b c])}
a:a {:depends [c]
:task (+ 1 2 3)}
a:b {:depends [c]
:task (do (Thread/sleep 10)
(+ 1 2 3))}
c (do (Thread/sleep 10) :c)}}
(is (= [6 6 :c] (bb "run" "--prn" "a"))))))
(testing "dynamic vars"
(test-utils/with-config '{:tasks
{:init (def ^:dynamic *foo* true)
a (do
(def ^:dynamic *bar* false)
(binding [*foo* false
*bar* true]
[*foo* *bar*]))}}
(is (= [false true] (bb "run" "--prn" "a")))))
(testing "stable namespace name"
(test-utils/with-config '{:tasks
{:init (do (def ^:dynamic *jdk*)
(def ^:dynamic *server*))
server [*jdk* *server*]
run-all (for [jdk [8 11 15]
server [:foo :bar]]
(binding [*jdk* jdk
*server* server]
(babashka.tasks/run 'server)))}}
(is (= '([8 :foo] [8 :bar] [11 :foo] [11 :bar] [15 :foo] [15 :bar])
(bb "run" "--prn" "run-all")))))
TODO : disabled because of " Volume in drive C has no label.\r\n Volume Serial Number is 1CB8 - D4AA\r\n\r\n Directory of C:\\projects\\babashka\r\n\r\n " on Appveyor . See .
(testing "shell test with :continue"
(let [ls-cmd (if main/windows? "cmd /c dir" "ls")]
(test-utils/with-config {:tasks {'foo (list 'do
(list 'shell {:continue true}
(str ls-cmd " foobar"))
(list 'println :hello))}}
(is (str/includes? (test-utils/bb nil "foo") ":hello"))))))
(deftest ^:skip-windows unix-task-test
(testing "shell pipe test"
(test-utils/with-config '{:tasks {a (-> (shell {:out :string}
"echo hello")
(shell {:out :string} "cat")
:out)}}
(let [s (bb "run" "--prn" "a")]
(is (= "hello\n" s))))))
(deftest ^:windows-only win-task-test
(when main/windows?
(testing "shell pipe test"
this task prints the contents of deps.edn
(test-utils/with-config '{:tasks {a (->> (shell {:out :string}
"cmd /c echo deps.edn")
:out
clojure.string/trim-newline
(shell {:out :string} "cmd /c type")
:out)}}
(let [s (bb "run" "--prn" "a")]
(is (str/includes? s "paths")))))))
(deftest tasks:clojure-test
(testing "tokenization when called from tasks"
(test-utils/with-config
(pr-str '{:tasks {foo (-> (clojure {:out :string} "-J-Dfoo=\"{:port 5555 :accept clojure.core.server/repl}\" -M -e \"(clojure.edn/read-string (System/getProperty (name :foo)))\"") :out clojure.edn/read-string prn)}})
(is (= '{:port 5555, :accept clojure.core.server/repl}
(bb "run" "foo")))))
(testing "can be called without args"
(test-utils/with-config
(pr-str '{:tasks {foo (-> (clojure {:in "(+ 1 2 3)" :out :string}) :out prn)}})
(is (str/includes? (bb "run" "foo") "6")))
ca n't properly test this , but ` ( clojure ) ` should work with zero args
#_(test-utils/with-config
(pr-str '{:tasks {foo (-> (clojure) :out prn)}})
(is (str/includes? (test-utils/bb "(+ 1 2 3)" "run" "foo") "6")))))
(deftest list-tasks-test
(test-utils/with-config {}
(let [res (test-utils/bb nil "tasks")]
(is (str/includes? res "No tasks found."))))
(test-utils/with-config '{:tasks {:x 1}}
(let [res (test-utils/bb nil "tasks")]
(is (str/includes? res "No tasks found."))))
(test-utils/with-config '{:tasks {-xyz 5}}
(let [res (test-utils/bb nil "tasks")]
(is (str/includes? res "No tasks found."))))
(test-utils/with-config '{:tasks {xyz {:private true}}}
(let [res (test-utils/bb nil "tasks")]
(is (str/includes? res "No tasks found."))))
(test-utils/with-config '{:tasks {abc 1 xyz 2}}
(let [res (test-utils/bb nil "tasks")]
(is (= "The following tasks are available:\n\nabc\nxyz\n" res))))
(test-utils/with-config '{:tasks {abc 1 xyz {:doc "some text" :tasks 5}
-xyz 3 qrs {:private true}}}
(let [res (test-utils/bb nil "tasks")]
(is (= "The following tasks are available:\n\nabc\nxyz some text\n" res))))
(test-utils/with-config '{:tasks {xyz 1 abc 2}}
(let [res (test-utils/bb nil "tasks")]
(is (= "The following tasks are available:\n\nxyz\nabc\n" res))))
(test-utils/with-config "{:paths [\"test-resources/task_scripts\"]
:tasks {:requires ([tasks :as t])
task1
{:doc \"task1 doc
more stuff here
even more stuff here\"
:task (+ 1 2 3)}
task2
{:doc \"task2 doc\"
:task (+ 4 5 6)}
-task3
{:task (+ 1 2 3)}
task4
{:task (+ 1 2 3)
:private true}
foo tasks/foo
bar t/foo
baz non-existing/bar
quux {:requires ([tasks :as t2])
:task t2/foo}}}"
(let [res (test-utils/bb nil "tasks")]
(is (= "The following tasks are available:\n\ntask1 task1 doc\ntask2 task2 doc\nfoo Foo docstring\nbar Foo docstring\nbaz \nquux Foo docstring\n"
res))))
(testing ":tasks is the first node"
(test-utils/with-config "{:tasks {task1
{:doc \"task1 doc\"
:task (+ 1 2 3)}}}"
(let [res (test-utils/bb nil "tasks")]
(is (= "The following tasks are available:\n\ntask1 task1 doc\n"
res))))))
(deftest task-priority-test
(when-not test-utils/native?
(testing "FILE > TASK > SUBCOMMAND"
(is (= "foo.jar" (:uberjar (main/parse-opts ["uberjar" "foo.jar"]))))
(vreset! common/bb-edn '{:tasks {uberjar (+ 1 2 3)}})
(is (= "uberjar" (:run (main/parse-opts ["uberjar"]))))
(try
(spit "uberjar" "#!/usr/bin/env bb\n(+ 1 2 3)")
(vreset! common/bb-edn '{:tasks {uberjar (+ 1 2 3)}})
(is (= "uberjar" (:file (main/parse-opts ["uberjar"]))))
(finally (fs/delete "uberjar"))))))
(deftest min-bb-version-test
(fs/with-temp-dir [dir {}]
(let [config (str (fs/file dir "bb.edn"))]
(spit config '{:min-bb-version "300.0.0"})
(let [sw (java.io.StringWriter.)]
(binding [*err* sw]
(main/main "--config" config "-e" "nil"))
(is (str/includes? (str sw)
"WARNING: this project requires babashka 300.0.0 or newer, but you have: "))))))
(deftest classpath-other-bb-edn-test
(fs/with-temp-dir [dir {}]
(let [config (str (fs/file dir "bb.edn"))]
(spit config '{:paths ["src"]
:tasks {cp (prn (babashka.classpath/get-classpath))}})
(let [out (bb "--config" config "cp")
entries (cp/split-classpath out)
entry (first entries)]
(is (= 1 (count entries)))
(is (= (fs/parent config) (fs/parent entry)))
(is (str/ends-with? entry "src"))))))
(deftest without-deps-test
(when-not test-utils/native?
(with-redefs [borkdude.deps/-main (fn [& _]
(throw (ex-info "This ain't allowed!" {})))]
(testing "bb.edn without :deps should not require deps.clj"
(test-utils/with-config '{:tasks {a 1}}
(bb "-e" "(+ 1 2 3)"))))))
(deftest deps-race-condition-test
(test-utils/with-config
(pr-str '{:tasks {task-b (do
(Thread/sleep 10)
:task00-out)
task-c {:depends [task-b]
:task (do
(println
"task-b: "
(type task-b))
{})}
task-a {:task (do
(Thread/sleep 10)
:task0-out)}
task-e {:depends [task-e1] :task {}}
task-e2 {:depends [task-a] :task {}}
task-e3 {:depends [task-b] :task {}}
task-e1 {:depends [task-e2 task-e3]
:task {}}
task-h {:depends [task-a task-b]
:task {}}
task-d {:task (do (Thread/sleep 2) {})}
task-f {:depends [task-d task-e task-a]
:task {}}
task-g {:depends [task-f
task-d
task-a
task-c
task-h]
:task {}}}})
(time (dotimes [_ 50]
(is (str/includes? (test-utils/bb nil "run" "--parallel" "task-g")
"task-b: clojure.lang.Keyword"))))))
(deftest parallel-nil-results-test
(test-utils/with-config
(pr-str '{:tasks {a (do nil)
b (do nil)
c (do nil)
d {:depends [a b c]
:task (prn [a b c])}}})
(is (= [nil nil nil] (bb "run" "--parallel" "d")))))
(deftest current-task-result-test
(test-utils/with-config
(pr-str '{:tasks {:leave (prn [(:name (current-task)) (:result (current-task))])
a 1
b 2
c {:depends [a b]
:task [a b]}}})
(is (= ["[a 1]" "[b 2]" "[c [1 2]]"] (str/split-lines (test-utils/bb nil "run" "c"))))))
(deftest pod-from-registry-test
(test-utils/with-config
(pr-str '{:paths ["test-resources"]
:pods {retrogradeorbit/bootleg {:version "0.1.9"}}})
(is (= "\"<div><p>Test</p></div>\"\n"
(test-utils/bb nil "--prn" "-m" "pod-tests.bootleg"))))))
(deftest ^:skip-windows local-pod-test
(test-utils/with-config
(pr-str '{:paths ["test-resources"]
:pods {pod/test-pod {:path "test-resources/pod"}}})
(is (= "42\n" (test-utils/bb nil "-m" "pod-tests.local")))))
(deftest tag-test
(test-utils/with-config
"{:deps {}
:aliases {:foo {:env-vars {:dude #env \"DUDE\"}}}}"
(is (= 6 (bb "-e" "(+ 1 2 3)")))))
(deftest merge-deps-test
(test-utils/with-config
"{:deps {}}"
(is (= {1 {:a 1}}
(bb "-Sdeps" "{:deps {medley/medley {:mvn/version \"1.4.0\"}}}" "-e" "(require 'medley.core) (medley.core/index-by :a [{:a 1}])")))))
(deftest deps-root-test
(fs/with-temp-dir [dir {}]
(let [f (fs/file dir "bb.edn")
config (str f)]
(spit config
'{:paths ["src"]
:tasks {cp (prn (babashka.classpath/get-classpath))}})
(testing "custom deps-root path"
(let [out (bb "--config" config "--deps-root" (str dir) "cp")
entries (cp/split-classpath out)]
(is (= 1 (count entries)))
(is (= (fs/file dir "src") (fs/file (first entries))))))
(testing "default deps-root path is same as bb.edn"
(let [out (bb "--config" config "cp")
entries (cp/split-classpath out)]
(is (= (fs/parent f) (fs/parent (first entries))))))
(spit config
'{:paths ["src"]
:deps {local/dep {:local/root "local-dep"}}
:tasks {cp (prn (babashka.classpath/get-classpath))}})
(testing "relative paths in deps should be relative to bb.edn"
(let [root (fs/create-dir (fs/file dir "local-dep"))
_ (spit (str (fs/file root "deps.edn")) {})
out (bb "--config" config "cp")
entries (cp/split-classpath out)]
(is (= (fs/parent f) (fs/parent (first entries)))))))))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.