_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
|
---|---|---|---|---|---|---|---|---|
e41ad5bfc5f882e472f9babd57ad66c6133a2a82922748c7d607d6a0d086dea5
|
TouchType/conf-er
|
conf_er.clj
|
Copyright ( c ) 2013 TouchType Ltd. All Rights Reserved .
(ns conf-er
"Global configuration utilities. This is intended to be very simple,
for top-level projects which only have one configuration file. Any
library projects using this should be good citizens and namespace
their keywords with ::keyword, so as to peacefully coexist in the
single configuration file as there is no way to specify multiple
files"
(:require [clojure.java.io :as io]
[clojure.edn :as edn])
(:import [java.io File PushbackReader]))
(defn config-file
"Handle to active config file as defined in the -Dconfig= java
property. This can be set with leiningen in the :jvm-opts vector"
[]
(if-let [filename (System/getProperty "config")]
(or (io/file filename)
(throw (Exception. (str "Can't find requested configuration file: " filename))))
(throw (Exception. "You must set the jvm property -Dconfig=<config file> to use conf-er"))))
(defn reload-config-file
"Next time a config is requested, the configuration will be re-read
from disk. Obviously this could mean that other parts of your program
have old values and haven't re-read the configuration - it is up to
you to ensure your program doesn't get into an inconsistent state and
to re-read the config when necessary"
[]
(def config-map
"Global settings map. Delayed evaluation to prevent io during
compilation. Use `config` to access this without deref."
(delay (let [file (config-file)]
(with-open [conf (PushbackReader. (io/reader file))]
(edn/read conf))))))
;;; Ensure that the config map has been requested at least once on load
(reload-config-file)
(defn configured?
"Return whether the given (possibly nested) key is provided in the
configuration"
[& ks]
(let [parent (get-in @config-map (butlast ks))]
(and (map? parent) (contains? parent (last ks)))))
(defn config
"Return the requested section of the config map. Provide any number
of nested keys, or no keys at all for the whole map.
Throws an exception if the requested key is not found"
([] @config-map)
([& ks]
(if (apply configured? ks)
(get-in @config-map ks)
(throw (Exception. (str "Could not find " ks " in configuration file"))))))
(defn opt-config
"Return the requested section of the config map. Provide any number
of nested keys, or no keys at all for the whole map.
Does NOT throw exceptions for missing keys"
[& ks]
(get-in @config-map ks))
| null |
https://raw.githubusercontent.com/TouchType/conf-er/21874eeec4c542b3bea96e8116fd6c24ab6dc767/src/conf_er.clj
|
clojure
|
Ensure that the config map has been requested at least once on load
|
Copyright ( c ) 2013 TouchType Ltd. All Rights Reserved .
(ns conf-er
"Global configuration utilities. This is intended to be very simple,
for top-level projects which only have one configuration file. Any
library projects using this should be good citizens and namespace
their keywords with ::keyword, so as to peacefully coexist in the
single configuration file as there is no way to specify multiple
files"
(:require [clojure.java.io :as io]
[clojure.edn :as edn])
(:import [java.io File PushbackReader]))
(defn config-file
"Handle to active config file as defined in the -Dconfig= java
property. This can be set with leiningen in the :jvm-opts vector"
[]
(if-let [filename (System/getProperty "config")]
(or (io/file filename)
(throw (Exception. (str "Can't find requested configuration file: " filename))))
(throw (Exception. "You must set the jvm property -Dconfig=<config file> to use conf-er"))))
(defn reload-config-file
"Next time a config is requested, the configuration will be re-read
from disk. Obviously this could mean that other parts of your program
have old values and haven't re-read the configuration - it is up to
you to ensure your program doesn't get into an inconsistent state and
to re-read the config when necessary"
[]
(def config-map
"Global settings map. Delayed evaluation to prevent io during
compilation. Use `config` to access this without deref."
(delay (let [file (config-file)]
(with-open [conf (PushbackReader. (io/reader file))]
(edn/read conf))))))
(reload-config-file)
(defn configured?
"Return whether the given (possibly nested) key is provided in the
configuration"
[& ks]
(let [parent (get-in @config-map (butlast ks))]
(and (map? parent) (contains? parent (last ks)))))
(defn config
"Return the requested section of the config map. Provide any number
of nested keys, or no keys at all for the whole map.
Throws an exception if the requested key is not found"
([] @config-map)
([& ks]
(if (apply configured? ks)
(get-in @config-map ks)
(throw (Exception. (str "Could not find " ks " in configuration file"))))))
(defn opt-config
"Return the requested section of the config map. Provide any number
of nested keys, or no keys at all for the whole map.
Does NOT throw exceptions for missing keys"
[& ks]
(get-in @config-map ks))
|
901b1d8425d5ada2668b50860e9c2e449e4fb3db3927f58934832d420e23b6b6
|
pflanze/chj-schemelib
|
fixnum-more.scm
|
Copyright 2018 - 2020 by < >
;;; This file is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License ( GPL ) as published
by the Free Software Foundation , either version 2 of the License , or
;;; (at your option) any later version.
(require define-macro-star
(cj-gambit-sys max-fixnum min-fixnum)
cj-symbol
test)
(export (macros fixnum-natural?
fixnum-natural0?
incrementable-fixnum?
decrementable-fixnum?))
(define-macro* (fixnum-natural? e)
(with-gensym x
`(##let ((,x ,e))
(##declare (fixnum) (not safe) (standard-bindings)
(extended-bindings) (block))
(##namespace ("" and fixnum? <= <))
(and (fixnum? ,x)
(< 0 ,x)))))
(define-macro* (fixnum-natural0? e)
(with-gensym x
`(##let ((,x ,e))
(##declare (fixnum) (not safe) (standard-bindings)
(extended-bindings) (block))
(##namespace ("" and fixnum? <= <))
(and (fixnum? ,x)
(<= 0 ,x)))))
(define-macro* (incrementable-fixnum? e)
(with-gensym x
`(##let ((,x ,e))
(##declare (fixnum) (not safe) (standard-bindings)
(extended-bindings) (block))
(##namespace ("" and fixnum? <= <))
(and (fixnum? ,x)
(< ,x max-fixnum)))))
(define-macro* (decrementable-fixnum? e)
(with-gensym x
`(##let ((,x ,e))
(##declare (fixnum) (not safe) (standard-bindings)
(extended-bindings) (block))
(##namespace ("" and fixnum? <= <))
(and (fixnum? ,x)
(> ,x min-fixnum)))))
(TEST
> (incrementable-fixnum? 0)
#t
> (incrementable-fixnum? 0.)
#f
> (incrementable-fixnum? -1000000)
#t
> (incrementable-fixnum? min-fixnum)
#t
> (incrementable-fixnum? max-fixnum)
#f
> (incrementable-fixnum? (dec max-fixnum))
#t
> (decrementable-fixnum? max-fixnum)
#t
> (decrementable-fixnum? min-fixnum)
#f
> (decrementable-fixnum? (inc min-fixnum))
#t)
| null |
https://raw.githubusercontent.com/pflanze/chj-schemelib/59ff8476e39f207c2f1d807cfc9670581c8cedd3/fixnum-more.scm
|
scheme
|
This file is free software; you can redistribute it and/or modify
(at your option) any later version.
|
Copyright 2018 - 2020 by < >
it under the terms of the GNU General Public License ( GPL ) as published
by the Free Software Foundation , either version 2 of the License , or
(require define-macro-star
(cj-gambit-sys max-fixnum min-fixnum)
cj-symbol
test)
(export (macros fixnum-natural?
fixnum-natural0?
incrementable-fixnum?
decrementable-fixnum?))
(define-macro* (fixnum-natural? e)
(with-gensym x
`(##let ((,x ,e))
(##declare (fixnum) (not safe) (standard-bindings)
(extended-bindings) (block))
(##namespace ("" and fixnum? <= <))
(and (fixnum? ,x)
(< 0 ,x)))))
(define-macro* (fixnum-natural0? e)
(with-gensym x
`(##let ((,x ,e))
(##declare (fixnum) (not safe) (standard-bindings)
(extended-bindings) (block))
(##namespace ("" and fixnum? <= <))
(and (fixnum? ,x)
(<= 0 ,x)))))
(define-macro* (incrementable-fixnum? e)
(with-gensym x
`(##let ((,x ,e))
(##declare (fixnum) (not safe) (standard-bindings)
(extended-bindings) (block))
(##namespace ("" and fixnum? <= <))
(and (fixnum? ,x)
(< ,x max-fixnum)))))
(define-macro* (decrementable-fixnum? e)
(with-gensym x
`(##let ((,x ,e))
(##declare (fixnum) (not safe) (standard-bindings)
(extended-bindings) (block))
(##namespace ("" and fixnum? <= <))
(and (fixnum? ,x)
(> ,x min-fixnum)))))
(TEST
> (incrementable-fixnum? 0)
#t
> (incrementable-fixnum? 0.)
#f
> (incrementable-fixnum? -1000000)
#t
> (incrementable-fixnum? min-fixnum)
#t
> (incrementable-fixnum? max-fixnum)
#f
> (incrementable-fixnum? (dec max-fixnum))
#t
> (decrementable-fixnum? max-fixnum)
#t
> (decrementable-fixnum? min-fixnum)
#f
> (decrementable-fixnum? (inc min-fixnum))
#t)
|
ec52f29b243165cce46094a1ebc19ac21abe3ec1bed2e9caab4947380693c664
|
ont-app/vocabulary
|
wikidata.cljc
|
(ns ont-app.vocabulary.wikidata
{:doc "Wikidata-related vocabulary. Requiring this file should bring in all ns assocated with wikidata."
}
(:require
[ont-app.vocabulary.core :as voc]
))
(def sparql-endpoint
"The public SPARQL endpoint provided by WMF."
"")
(voc/put-ns-meta!
'ont-app.vocabulary.wikidata.wd
{
:dc/title "Wikibase/EntityData"
:foaf/homepage ""
:vann/preferredNamespaceUri "/"
:vann/preferredNamespacePrefix "wd"
}
)
(voc/put-ns-meta!
'ont-app.vocabulary.wikidata.wdt
{
:dc/description "Direct properties in wikibase"
:vann/preferredNamespaceUri "/"
:vann/preferredNamespacePrefix "wdt"
:rdfs/seeAlso :wikibase/directClaim
}
)
(voc/put-ns-meta!
'ont-app.vocabulary.wikidata.wikibase
{
:rdfs/label "Wikibase system ontology"
:vann/preferredNamespaceUri "#"
:vann/preferredNamespacePrefix "wikibase"
:rdfs/isDefinedBy "-1.0.owl"
}
)
(voc/put-ns-meta!
'ont-app.vocabulary.wikidata.p
{
:rdfs/comment "Reifies wikibase properties"
:vann/preferredNamespaceUri "/"
:vann/preferredNamespacePrefix "p"
:foaf/homepage ":Properties"
}
)
(voc/put-ns-meta!
'ont-app.vocabulary.wikidata.ps
{
:vann/preferredNamespaceUri "/"
:vann/preferredNamespacePrefix #{"v" "ps"}
:foaf/homepage ":Statements"
}
)
(voc/put-ns-meta!
'ont-app.vocabulary.wikidata.q
{
:vann/preferredNamespaceUri ""
:vann/preferredNamespacePrefix "q"
:foaf/homepage ":Qualifiers"
}
)
;; THESE NAMESPACES ARE RELATIVELY RARE
;; BUT SHOW UP IN #Full_list_of_prefixes
;; PREFIX wdtn: <-normalized/>
(voc/put-ns-meta!
'ont-app.vocabulary.wikidata.wdtn
{
:vann/preferredNamespaceUri "-normalized/"
:vann/preferredNamespacePrefix "wdtn"
}
)
;; PREFIX wds: </>
(voc/put-ns-meta!
'ont-app.vocabulary.wikidata.wds
{
:vann/preferredNamespaceUri "/"
:vann/preferredNamespacePrefix "wds"
}
)
;; PREFIX wdref: </>
(voc/put-ns-meta!
'ont-app.vocabulary.wikidata.wdref
{
:vann/preferredNamespaceUri "/"
:vann/preferredNamespacePrefix "wdref"
}
)
PREFIX wdv : < / >
(voc/put-ns-meta!
'ont-app.vocabulary.wikidata.wdv
{
:vann/preferredNamespaceUri "/"
:vann/preferredNamespacePrefix "wdv"
}
)
;; PREFIX psv: </>
(voc/put-ns-meta!
'ont-app.vocabulary.wikidata.psv
{
:vann/preferredNamespaceUri "/"
:vann/preferredNamespacePrefix "psv"
}
)
;; PREFIX psn: <-normalized/>
(voc/put-ns-meta!
'iri.org.wikidata.www.prop.statement.value-normalized
{
:vann/preferredNamespaceUri "-normalized/"
:vann/preferredNamespacePrefix "psn"
}
)
;; PREFIX pq: </>
(voc/put-ns-meta!
'ont-app.vocabulary.wikidata.pq
{
:vann/preferredNamespaceUri "/"
:vann/preferredNamespacePrefix "pq"
}
)
;; PREFIX pqv: </>
(voc/put-ns-meta!
'ont-app.vocabulary.wikidata.pqv
{
:vann/preferredNamespaceUri "/"
:vann/preferredNamespacePrefix "pqv"
}
)
;; PREFIX pqn: <-normalized/>
(voc/put-ns-meta!
'ont-app.vocabulary.wikidata.pqn
{
:vann/preferredNamespaceUri "-normalized/"
:vann/preferredNamespacePrefix "pqn"
}
)
;; PREFIX pr: </>
(voc/put-ns-meta!
'ont-app.vocabulary.wikidata.pr
{
:vann/preferredNamespaceUri "/"
:vann/preferredNamespacePrefix "pr"
}
)
;; PREFIX prv: </>
(voc/put-ns-meta!
'ont-app.vocabulary.wikidata.prv
{
:vann/preferredNamespaceUri "/"
:vann/preferredNamespacePrefix "prv"
}
)
;; PREFIX prn: <-normalized/>
(voc/put-ns-meta!
'ont-app.vocabulary.wikidata.prn
{
:vann/preferredNamespaceUri "-normalized/"
:vann/preferredNamespacePrefix "prn"
}
)
;; PREFIX wdno: </>
(voc/put-ns-meta!
'ont-app.vocabulary.wikidata.wdno
{
:vann/preferredNamespaceUri "/"
:vann/preferredNamespacePrefix "wdno"
}
)
| null |
https://raw.githubusercontent.com/ont-app/vocabulary/cc5ae55ab2ba19e86ed68be8f6b508782489d4b1/src/ont_app/vocabulary/wikidata.cljc
|
clojure
|
THESE NAMESPACES ARE RELATIVELY RARE
BUT SHOW UP IN #Full_list_of_prefixes
PREFIX wdtn: <-normalized/>
PREFIX wds: </>
PREFIX wdref: </>
PREFIX psv: </>
PREFIX psn: <-normalized/>
PREFIX pq: </>
PREFIX pqv: </>
PREFIX pqn: <-normalized/>
PREFIX pr: </>
PREFIX prv: </>
PREFIX prn: <-normalized/>
PREFIX wdno: </>
|
(ns ont-app.vocabulary.wikidata
{:doc "Wikidata-related vocabulary. Requiring this file should bring in all ns assocated with wikidata."
}
(:require
[ont-app.vocabulary.core :as voc]
))
(def sparql-endpoint
"The public SPARQL endpoint provided by WMF."
"")
(voc/put-ns-meta!
'ont-app.vocabulary.wikidata.wd
{
:dc/title "Wikibase/EntityData"
:foaf/homepage ""
:vann/preferredNamespaceUri "/"
:vann/preferredNamespacePrefix "wd"
}
)
(voc/put-ns-meta!
'ont-app.vocabulary.wikidata.wdt
{
:dc/description "Direct properties in wikibase"
:vann/preferredNamespaceUri "/"
:vann/preferredNamespacePrefix "wdt"
:rdfs/seeAlso :wikibase/directClaim
}
)
(voc/put-ns-meta!
'ont-app.vocabulary.wikidata.wikibase
{
:rdfs/label "Wikibase system ontology"
:vann/preferredNamespaceUri "#"
:vann/preferredNamespacePrefix "wikibase"
:rdfs/isDefinedBy "-1.0.owl"
}
)
(voc/put-ns-meta!
'ont-app.vocabulary.wikidata.p
{
:rdfs/comment "Reifies wikibase properties"
:vann/preferredNamespaceUri "/"
:vann/preferredNamespacePrefix "p"
:foaf/homepage ":Properties"
}
)
(voc/put-ns-meta!
'ont-app.vocabulary.wikidata.ps
{
:vann/preferredNamespaceUri "/"
:vann/preferredNamespacePrefix #{"v" "ps"}
:foaf/homepage ":Statements"
}
)
(voc/put-ns-meta!
'ont-app.vocabulary.wikidata.q
{
:vann/preferredNamespaceUri ""
:vann/preferredNamespacePrefix "q"
:foaf/homepage ":Qualifiers"
}
)
(voc/put-ns-meta!
'ont-app.vocabulary.wikidata.wdtn
{
:vann/preferredNamespaceUri "-normalized/"
:vann/preferredNamespacePrefix "wdtn"
}
)
(voc/put-ns-meta!
'ont-app.vocabulary.wikidata.wds
{
:vann/preferredNamespaceUri "/"
:vann/preferredNamespacePrefix "wds"
}
)
(voc/put-ns-meta!
'ont-app.vocabulary.wikidata.wdref
{
:vann/preferredNamespaceUri "/"
:vann/preferredNamespacePrefix "wdref"
}
)
PREFIX wdv : < / >
(voc/put-ns-meta!
'ont-app.vocabulary.wikidata.wdv
{
:vann/preferredNamespaceUri "/"
:vann/preferredNamespacePrefix "wdv"
}
)
(voc/put-ns-meta!
'ont-app.vocabulary.wikidata.psv
{
:vann/preferredNamespaceUri "/"
:vann/preferredNamespacePrefix "psv"
}
)
(voc/put-ns-meta!
'iri.org.wikidata.www.prop.statement.value-normalized
{
:vann/preferredNamespaceUri "-normalized/"
:vann/preferredNamespacePrefix "psn"
}
)
(voc/put-ns-meta!
'ont-app.vocabulary.wikidata.pq
{
:vann/preferredNamespaceUri "/"
:vann/preferredNamespacePrefix "pq"
}
)
(voc/put-ns-meta!
'ont-app.vocabulary.wikidata.pqv
{
:vann/preferredNamespaceUri "/"
:vann/preferredNamespacePrefix "pqv"
}
)
(voc/put-ns-meta!
'ont-app.vocabulary.wikidata.pqn
{
:vann/preferredNamespaceUri "-normalized/"
:vann/preferredNamespacePrefix "pqn"
}
)
(voc/put-ns-meta!
'ont-app.vocabulary.wikidata.pr
{
:vann/preferredNamespaceUri "/"
:vann/preferredNamespacePrefix "pr"
}
)
(voc/put-ns-meta!
'ont-app.vocabulary.wikidata.prv
{
:vann/preferredNamespaceUri "/"
:vann/preferredNamespacePrefix "prv"
}
)
(voc/put-ns-meta!
'ont-app.vocabulary.wikidata.prn
{
:vann/preferredNamespaceUri "-normalized/"
:vann/preferredNamespacePrefix "prn"
}
)
(voc/put-ns-meta!
'ont-app.vocabulary.wikidata.wdno
{
:vann/preferredNamespaceUri "/"
:vann/preferredNamespacePrefix "wdno"
}
)
|
855bfb7bd3ee684485620b36f3742c538c2d281fb29b07e8a9266f4beff96256
|
donaldsonjw/bigloo
|
evaluate_fsize.scm
|
;*=====================================================================*/
* serrano / prgm / project / bigloo / runtime / Eval / evaluate_fsize.scm * /
;* ------------------------------------------------------------- */
* Author : * /
* Creation : Tue Feb 8 16:42:27 2011 * /
* Last change : Fri Nov 30 09:32:13 2012 ( serrano ) * /
* Copyright : 2011 - 12 * /
;* ------------------------------------------------------------- */
;* Compute the size of stack needed for an abstraction */
;* of the space for free variables is not included. */
;*=====================================================================*/
;*---------------------------------------------------------------------*/
;* The module */
;*---------------------------------------------------------------------*/
(module __evaluate_fsize
(import __type
__error
__bigloo
__tvector
__structure
__tvector
__bexit
__bignum
__os
__dsssl
__bit
__param
__bexit
__object
__thread
__r4_numbers_6_5
__r4_numbers_6_5_fixnum
__r4_numbers_6_5_flonum
__r4_numbers_6_5_flonum_dtoa
__r4_characters_6_6
__r4_equivalence_6_2
__r4_booleans_6_1
__r4_symbols_6_4
__r4_strings_6_7
__r4_pairs_and_lists_6_3
__r4_control_features_6_9
__r5_control_features_6_4
__r4_vectors_6_8
__r4_ports_6_10_1
__r4_output_6_10_3
__pp
__reader
__progn
__expand
__evenv
__evcompile
__everror
__evmodule
__evaluate_uncomp
__evaluate_types)
(export (frame-size::int ::ev_expr)
(extract-loops::ev_expr ::ev_expr)))
(define (frame-size::int e::ev_expr);
(fsize e 0) )
(define-generic (fsize::int e::ev_expr n::int);
(error "eval" "internal error: not defined for" e) )
(define-method (fsize::int e::ev_var n::int);
n )
(define-method (fsize::int var::ev_global n::int);
n )
(define-method (fsize::int e::ev_litt n::int);
n )
(define-method (fsize::int e::ev_if n::int);
(with-access::ev_if e (p t e)
(max (fsize p n) (fsize t n) (fsize e n)) ))
(define-method (fsize::int e::ev_list n::int);
(with-access::ev_list e (args)
(let rec ( (l args) (r n) )
(if (null? l)
r
(rec (cdr l) (max r (fsize (car l) n))) ))))
(define-method (fsize::int e::ev_prog2 n::int);
(with-access::ev_prog2 e (e1 e2)
(max (fsize e1 n) (fsize e2 n)) ))
(define-method (fsize::int e::ev_hook n::int);
(with-access::ev_hook e (e)
(fsize e n) ))
(define-method (fsize::int e::ev_bind-exit n::int);
(with-access::ev_bind-exit e (body)
(fsize body (+fx n 1)) ))
(define-method (fsize::int e::ev_unwind-protect n::int);
(with-access::ev_unwind-protect e (e body)
(max (fsize e n) (fsize body n)) ))
(define-method (fsize::int e::ev_with-handler n::int);
(with-access::ev_with-handler e (handler body)
(max (fsize handler n) (fsize body n)) ))
(define-method (fsize::int e::ev_synchronize n::int);
(with-access::ev_synchronize e (mutex prelock body)
(max (fsize mutex n) (fsize prelock n) (fsize body n)) ))
(define-method (fsize::int e::ev_let n::int);
(with-access::ev_let e (vals body)
(let rec ( (l vals) (n n) (r n) )
(if (null? l)
(max (fsize body n) r)
(rec (cdr l) (+fx n 1) (max (fsize (car l) n) r)) ))))
(define-method (fsize::int e::ev_let* n::int);
(with-access::ev_let* e (vals body)
(let rec ( (l vals) (n n) (r n) )
(if (null? l)
(max (fsize body n) r)
(rec (cdr l) (+fx n 1) (max (fsize (car l) n) r)) ))))
(define-method (fsize::int e::ev_letrec n::int);
(with-access::ev_letrec e (vals body)
(let ( (n (+fx n (length vals))) )
(let rec ( (l vals) (r n) )
(if (null? l)
(max (fsize body n) r)
(rec (cdr l) (max (fsize (car l) n) r)) )))))
(define-method (fsize::int e::ev_labels n);
(with-access::ev_labels e (vars vals body)
(let rec ( (l vals) (r n) )
(if (null? l)
(max (fsize body n) r)
(rec (cdr l) (max (fsize (cdar l) (+fx n (length (caar l)))) r)) ))))
(define-method (fsize::int e::ev_goto n);
(with-access::ev_goto e (args)
(let rec ( (l args) (n n) (r n) )
(if (null? l)
(max n r)
(rec (cdr l) (+fx n 1) (max (fsize (car l) n) r)) ))))
(define-method (fsize::int e::ev_app n::int);
(with-access::ev_app e (fun args)
(let rec ( (l args) (n n) (r (fsize fun n)) )
(if (null? l)
(max n r)
(rec (cdr l) (+fx n 1) (max (fsize (car l) n) r)) ))))
(define-method (fsize::int e::ev_abs n::int);
(with-access::ev_abs e (arity vars body size)
(let ( (nn (fsize body (length vars))) )
(set! size nn)
n )))
;;;
(define (extract-loops::ev_expr e::ev_expr)
(if #t
(search-letrec e)
e ))
(define (search-letrec* l)
(let rec ( (l l) )
(unless (null? l)
(set-car! l (search-letrec (car l)))
(rec (cdr l)) )))
(define-generic (search-letrec e::ev_expr)
(error 'search-letrec "not defined for" e) )
(define-method (search-letrec e::ev_var);
e )
(define-method (search-letrec e::ev_global);
e )
(define-method (search-letrec e::ev_litt);
e )
(define-method (search-letrec expr::ev_if);
(with-access::ev_if expr (p t e)
(set! p (search-letrec p))
(set! t (search-letrec t))
(set! e (search-letrec e))
expr ))
(define-method (search-letrec e::ev_list);
(with-access::ev_list e (args)
(search-letrec* args)
e ))
(define-method (search-letrec e::ev_prog2);
(with-access::ev_prog2 e (e1 e2)
(set! e1 (search-letrec e1))
(set! e2 (search-letrec e2))
e ))
(define-method (search-letrec expr::ev_hook);
(with-access::ev_hook expr (e)
(set! e (search-letrec e))
expr ))
(define-method (search-letrec e::ev_bind-exit);
(with-access::ev_bind-exit e (var body)
(set! body (search-letrec body))
e ))
(define-method (search-letrec expr::ev_unwind-protect);
(with-access::ev_unwind-protect expr (e body)
(set! e (search-letrec e))
(set! body (search-letrec body))
expr ))
(define-method (search-letrec e::ev_with-handler);
(with-access::ev_with-handler e (handler body)
(set! handler (search-letrec handler))
(set! body (search-letrec body))
e ))
(define-method (search-letrec e::ev_synchronize);
(with-access::ev_synchronize e (mutex prelock body)
(set! mutex (search-letrec mutex))
(set! prelock (search-letrec prelock))
(set! body (search-letrec body))
e ))
(define-method (search-letrec e::ev_binder);
(with-access::ev_binder e (vars vals body)
(search-letrec* vals)
(set! body (search-letrec body))
e ))
(define-method (search-letrec e::ev_letrec);
(with-access::ev_letrec e (vars vals body)
(search-letrec* vals)
(set! body (search-letrec body))
(let ( (ok? (letrectail? vars vals body)) )
;;(tprint "FOUND LETREC " ok?)
;(pp (uncompile e))
(if ok?
(modify-letrec vars vals body)
e ))))
(define-method (search-letrec e::ev_app);
(with-access::ev_app e (fun args)
(set! fun (search-letrec fun))
(search-letrec* args)
e ))
(define-method (search-letrec e::ev_abs);
(with-access::ev_abs e (arity vars body)
(set! body (search-letrec body))
e ))
;;;
(define (modify-letrec vars vals body)
(let ( (r (instantiate::ev_labels (vars vars) (vals '())
(body (instantiate::ev_litt (value 0))) )) )
(with-access::ev_labels r ((nbody body) (nvals vals))
(set! nbody (subst_goto body vars r))
(set! nvals (map (lambda (val)
(with-access::ev_abs val ((vvars vars) (vbody body))
(cons vvars (subst_goto vbody vars r)) ))
vals ))
r )))
(define (letrectail? vars vals body)
(every (lambda (v)
(and (tailpos body v)
(every (lambda (e)
(when (isa? e ev_abs)
(with-access::ev_abs e (arity body)
(and (>=fx arity 0)
(tailpos body v) ))))
vals )))
vars ))
;;
(define (subst_goto* l vars lbls)
(let rec ( (l l) )
(unless (null? l)
(set-car! l (subst_goto (car l) vars lbls))
(rec (cdr l)) )))
(define-generic (subst_goto e::ev_expr vars lbls)
(error 'subst_goto "not defined for" e) )
(define-method (subst_goto e::ev_var vars lbls);
e )
(define-method (subst_goto e::ev_global vars lbls);
e )
(define-method (subst_goto e::ev_litt vars lbls);
e )
(define-method (subst_goto expr::ev_if vars lbls);
(with-access::ev_if expr (p t e)
(set! p (subst_goto p vars lbls))
(set! t (subst_goto t vars lbls))
(set! e (subst_goto e vars lbls))
expr ))
(define-method (subst_goto e::ev_list vars lbls);
(with-access::ev_list e (args)
(subst_goto* args vars lbls)
e ))
(define-method (subst_goto e::ev_prog2 vars lbls);
(with-access::ev_prog2 e (e1 e2)
(set! e1 (subst_goto e1 vars lbls))
(set! e2 (subst_goto e2 vars lbls))
e ))
(define-method (subst_goto expr::ev_hook vars lbls);
(with-access::ev_hook expr (e)
(set! e (subst_goto e vars lbls))
expr ))
(define-method (subst_goto e::ev_bind-exit vars lbls);
(with-access::ev_bind-exit e (var body)
(set! body (subst_goto body vars lbls))
e ))
(define-method (subst_goto expr::ev_unwind-protect vars lbls);
(with-access::ev_unwind-protect expr (e body)
(set! e (subst_goto e vars lbls))
(set! body (subst_goto body vars lbls))
expr ))
(define-method (subst_goto e::ev_with-handler vars lbls);
(with-access::ev_with-handler e (handler body)
(set! handler (subst_goto handler vars lbls))
(set! body (subst_goto body vars lbls))
e ))
(define-method (subst_goto e::ev_synchronize vars lbls);
(with-access::ev_synchronize e (mutex prelock body)
(set! mutex (subst_goto mutex vars lbls))
(set! prelock (subst_goto prelock vars lbls))
(set! body (subst_goto body vars lbls))
e ))
(define-method (subst_goto e::ev_binder vars lbls);
(with-access::ev_binder e (vals body)
(subst_goto* vals vars lbls)
(set! body (subst_goto body vars lbls))
e ))
(define-method (subst_goto e::ev_labels vars lbls);
(with-access::ev_labels e (vals body)
(let rec ( (l vals) )
(unless (null? l)
(set-cdr! (car l) (subst_goto (cdar l) vars lbls))
(rec (cdr l)) ))
(set! body (subst_goto body vars lbls))
e ))
(define-method (subst_goto e::ev_goto vars lbls);
(with-access::ev_goto e (args)
(subst_goto* args vars lbls)
e ))
(define-method (subst_goto e::ev_app vars lbls);
(with-access::ev_app e (fun args loc)
(subst_goto* args vars lbls)
(if (memq fun vars)
(instantiate::ev_goto (label fun) (args args) (labels lbls) (loc loc))
(begin (set! fun (subst_goto fun vars lbls))
e ))))
(define-method (subst_goto e::ev_abs vars lbls);
(with-access::ev_abs e (arity body)
(set! body (subst_goto body vars lbls))
e ))
;;; (TAILPOS e x) x must appear only in functional position (x ...) in
;; a direct tail position (not closed under a lambda)
(define-generic (tailpos e::ev_expr v::ev_var)
(error 'tailpos "not defined for" e) )
(define-method (tailpos e::ev_var v::ev_var);
(not (eq? e v)) )
(define-method (tailpos e::ev_global v::ev_var);
#t )
(define-method (tailpos e::ev_litt v::ev_var);
#t )
(define-method (tailpos e::ev_if v::ev_var);
(with-access::ev_if e (p t e)
(and (not (hasvar? p v)) (tailpos t v) (tailpos e v)) ))
(define-method (tailpos e::ev_list v::ev_var);
(with-access::ev_list e (args)
(let rec ( (l args) )
(if (null? (cdr l))
(tailpos (car l) v)
(and (not (hasvar? (car l) v))
(rec (cdr l)) )))))
(define-method (tailpos e::ev_prog2 v::ev_var);
(with-access::ev_prog2 e (e1 e2)
(and (not (hasvar? e1 v)) (tailpos e2 v)) ))
(define-method (tailpos e::ev_hook v::ev_var);
(with-access::ev_hook e (e)
(not (hasvar? e v)) ))
(define-method (tailpos e::ev_setlocal var::ev_var);
(with-access::ev_setlocal e (v e)
(and (not (eq? v var)) (not (hasvar? e var))) ))
(define-method (tailpos e::ev_bind-exit v::ev_var);
(with-access::ev_bind-exit e (var body)
(not (hasvar? body v)) ))
(define-method (tailpos e::ev_unwind-protect v::ev_var);
(with-access::ev_unwind-protect e (e body)
(and (not (hasvar? e v)) (not (hasvar? body v))) ))
(define-method (tailpos e::ev_with-handler v::ev_var);
(with-access::ev_with-handler e (handler body)
(and (not (hasvar? handler v)) (not (hasvar? body v))) ))
(define-method (tailpos e::ev_synchronize v::ev_var);
(with-access::ev_synchronize e (mutex prelock body)
(and (not (hasvar? mutex v)) (not (hasvar? prelock v)) (not (hasvar? body v))) ))
(define-method (tailpos e::ev_let v::ev_var);
(with-access::ev_let e (vars vals body)
(and (every (lambda (e) (not (hasvar? e v))) vals)
(tailpos body v) )))
(define-method (tailpos e::ev_let* v::ev_var);
(with-access::ev_let* e (vars vals body)
(and (every (lambda (e) (not (hasvar? e v))) vals)
(tailpos body v) )))
(define-method (tailpos e::ev_letrec v::ev_var);
(with-access::ev_letrec e (vars vals body)
(and (every (lambda (e) (not (hasvar? e v))) vals)
(tailpos body v) )))
(define-method (tailpos e::ev_labels v::ev_var);
(with-access::ev_labels e (vals body)
(and (every (lambda (e) (tailpos (cdr e) v)) vals)
(tailpos body v) )))
(define-method (tailpos e::ev_goto v::ev_var);
(with-access::ev_goto e (args)
(every (lambda (e) (not (hasvar? e v))) args) ))
(define-method (tailpos e::ev_app v::ev_var);
(with-access::ev_app e (fun args)
(and (every (lambda (e) (not (hasvar? e v))) args)
(or (eq? fun v)
(not (hasvar? fun v)) ))))
(define-method (tailpos e::ev_abs v::ev_var);
(with-access::ev_abs e (arity vars body)
(not (hasvar? body v)) ))
( hasvar ? e x ) return true iff x appear as a subexpression of e
(define-generic (hasvar? e::ev_expr v::ev_var))
(define-method (hasvar? e::ev_var v::ev_var);
(eq? e v) )
(define-method (hasvar? e::ev_global v::ev_var);
#f )
(define-method (hasvar? e::ev_litt v::ev_var);
#f )
(define-method (hasvar? e::ev_if v::ev_var);
(with-access::ev_if e (p t e)
(or (hasvar? p v) (hasvar? t v) (hasvar? e v)) ))
(define-method (hasvar? e::ev_list v::ev_var);
(with-access::ev_list e (args)
(any (lambda (a) (hasvar? a v)) args) ))
(define-method (hasvar? e::ev_prog2 v::ev_var);
(with-access::ev_prog2 e (e1 e2)
(or (hasvar? e1 v) (hasvar? e2 v)) ))
(define-method (hasvar? e::ev_hook v::ev_var);
(with-access::ev_hook e (e)
(hasvar? e v) ))
(define-method (hasvar? e::ev_setlocal var::ev_var);
(with-access::ev_setlocal e (v e)
(or (eq? v var) (hasvar? e var)) ))
(define-method (hasvar? e::ev_bind-exit v::ev_var);
(with-access::ev_bind-exit e (var body)
(hasvar? body v) ))
(define-method (hasvar? e::ev_unwind-protect v::ev_var);
(with-access::ev_unwind-protect e (e body)
(or (hasvar? e v) (hasvar? body v)) ))
(define-method (hasvar? e::ev_with-handler v::ev_var);
(with-access::ev_with-handler e (handler body)
(or (hasvar? handler v) (hasvar? body v)) ))
(define-method (hasvar? e::ev_synchronize v::ev_var);
(with-access::ev_synchronize e (mutex prelock body)
(or (hasvar? mutex v) (hasvar? prelock v) (hasvar? body v)) ))
(define-method (hasvar? e::ev_binder v::ev_var);
(with-access::ev_binder e (vals body)
(or (any (lambda (e) (hasvar? e v)) vals)
(hasvar? body v) )))
(define-method (hasvar? e::ev_labels v::ev_var);
(with-access::ev_labels e (vals body)
(or (any (lambda (e) (hasvar? (cdr e) v)) vals)
(hasvar? body v) )))
(define-method (hasvar? e::ev_goto v::ev_var);
(with-access::ev_goto e (args)
(any (lambda (e) (hasvar? e v)) args) ))
(define-method (hasvar? e::ev_app v::ev_var);
(with-access::ev_app e (fun args)
(or (hasvar? fun v) (any (lambda (e) (hasvar? e v)) args)) ))
(define-method (hasvar? e::ev_abs v::ev_var);
(with-access::ev_abs e (vars body)
(hasvar? body v) ))
;;;
| null |
https://raw.githubusercontent.com/donaldsonjw/bigloo/a4d06e409d0004e159ce92b9908719510a18aed5/runtime/Eval/evaluate_fsize.scm
|
scheme
|
*=====================================================================*/
* ------------------------------------------------------------- */
* ------------------------------------------------------------- */
* Compute the size of stack needed for an abstraction */
* of the space for free variables is not included. */
*=====================================================================*/
*---------------------------------------------------------------------*/
* The module */
*---------------------------------------------------------------------*/
(tprint "FOUND LETREC " ok?)
(pp (uncompile e))
(TAILPOS e x) x must appear only in functional position (x ...) in
a direct tail position (not closed under a lambda)
|
* serrano / prgm / project / bigloo / runtime / Eval / evaluate_fsize.scm * /
* Author : * /
* Creation : Tue Feb 8 16:42:27 2011 * /
* Last change : Fri Nov 30 09:32:13 2012 ( serrano ) * /
* Copyright : 2011 - 12 * /
(module __evaluate_fsize
(import __type
__error
__bigloo
__tvector
__structure
__tvector
__bexit
__bignum
__os
__dsssl
__bit
__param
__bexit
__object
__thread
__r4_numbers_6_5
__r4_numbers_6_5_fixnum
__r4_numbers_6_5_flonum
__r4_numbers_6_5_flonum_dtoa
__r4_characters_6_6
__r4_equivalence_6_2
__r4_booleans_6_1
__r4_symbols_6_4
__r4_strings_6_7
__r4_pairs_and_lists_6_3
__r4_control_features_6_9
__r5_control_features_6_4
__r4_vectors_6_8
__r4_ports_6_10_1
__r4_output_6_10_3
__pp
__reader
__progn
__expand
__evenv
__evcompile
__everror
__evmodule
__evaluate_uncomp
__evaluate_types)
(export (frame-size::int ::ev_expr)
(extract-loops::ev_expr ::ev_expr)))
(fsize e 0) )
(error "eval" "internal error: not defined for" e) )
n )
n )
n )
(with-access::ev_if e (p t e)
(max (fsize p n) (fsize t n) (fsize e n)) ))
(with-access::ev_list e (args)
(let rec ( (l args) (r n) )
(if (null? l)
r
(rec (cdr l) (max r (fsize (car l) n))) ))))
(with-access::ev_prog2 e (e1 e2)
(max (fsize e1 n) (fsize e2 n)) ))
(with-access::ev_hook e (e)
(fsize e n) ))
(with-access::ev_bind-exit e (body)
(fsize body (+fx n 1)) ))
(with-access::ev_unwind-protect e (e body)
(max (fsize e n) (fsize body n)) ))
(with-access::ev_with-handler e (handler body)
(max (fsize handler n) (fsize body n)) ))
(with-access::ev_synchronize e (mutex prelock body)
(max (fsize mutex n) (fsize prelock n) (fsize body n)) ))
(with-access::ev_let e (vals body)
(let rec ( (l vals) (n n) (r n) )
(if (null? l)
(max (fsize body n) r)
(rec (cdr l) (+fx n 1) (max (fsize (car l) n) r)) ))))
(with-access::ev_let* e (vals body)
(let rec ( (l vals) (n n) (r n) )
(if (null? l)
(max (fsize body n) r)
(rec (cdr l) (+fx n 1) (max (fsize (car l) n) r)) ))))
(with-access::ev_letrec e (vals body)
(let ( (n (+fx n (length vals))) )
(let rec ( (l vals) (r n) )
(if (null? l)
(max (fsize body n) r)
(rec (cdr l) (max (fsize (car l) n) r)) )))))
(with-access::ev_labels e (vars vals body)
(let rec ( (l vals) (r n) )
(if (null? l)
(max (fsize body n) r)
(rec (cdr l) (max (fsize (cdar l) (+fx n (length (caar l)))) r)) ))))
(with-access::ev_goto e (args)
(let rec ( (l args) (n n) (r n) )
(if (null? l)
(max n r)
(rec (cdr l) (+fx n 1) (max (fsize (car l) n) r)) ))))
(with-access::ev_app e (fun args)
(let rec ( (l args) (n n) (r (fsize fun n)) )
(if (null? l)
(max n r)
(rec (cdr l) (+fx n 1) (max (fsize (car l) n) r)) ))))
(with-access::ev_abs e (arity vars body size)
(let ( (nn (fsize body (length vars))) )
(set! size nn)
n )))
(define (extract-loops::ev_expr e::ev_expr)
(if #t
(search-letrec e)
e ))
(define (search-letrec* l)
(let rec ( (l l) )
(unless (null? l)
(set-car! l (search-letrec (car l)))
(rec (cdr l)) )))
(define-generic (search-letrec e::ev_expr)
(error 'search-letrec "not defined for" e) )
e )
e )
e )
(with-access::ev_if expr (p t e)
(set! p (search-letrec p))
(set! t (search-letrec t))
(set! e (search-letrec e))
expr ))
(with-access::ev_list e (args)
(search-letrec* args)
e ))
(with-access::ev_prog2 e (e1 e2)
(set! e1 (search-letrec e1))
(set! e2 (search-letrec e2))
e ))
(with-access::ev_hook expr (e)
(set! e (search-letrec e))
expr ))
(with-access::ev_bind-exit e (var body)
(set! body (search-letrec body))
e ))
(with-access::ev_unwind-protect expr (e body)
(set! e (search-letrec e))
(set! body (search-letrec body))
expr ))
(with-access::ev_with-handler e (handler body)
(set! handler (search-letrec handler))
(set! body (search-letrec body))
e ))
(with-access::ev_synchronize e (mutex prelock body)
(set! mutex (search-letrec mutex))
(set! prelock (search-letrec prelock))
(set! body (search-letrec body))
e ))
(with-access::ev_binder e (vars vals body)
(search-letrec* vals)
(set! body (search-letrec body))
e ))
(with-access::ev_letrec e (vars vals body)
(search-letrec* vals)
(set! body (search-letrec body))
(let ( (ok? (letrectail? vars vals body)) )
(if ok?
(modify-letrec vars vals body)
e ))))
(with-access::ev_app e (fun args)
(set! fun (search-letrec fun))
(search-letrec* args)
e ))
(with-access::ev_abs e (arity vars body)
(set! body (search-letrec body))
e ))
(define (modify-letrec vars vals body)
(let ( (r (instantiate::ev_labels (vars vars) (vals '())
(body (instantiate::ev_litt (value 0))) )) )
(with-access::ev_labels r ((nbody body) (nvals vals))
(set! nbody (subst_goto body vars r))
(set! nvals (map (lambda (val)
(with-access::ev_abs val ((vvars vars) (vbody body))
(cons vvars (subst_goto vbody vars r)) ))
vals ))
r )))
(define (letrectail? vars vals body)
(every (lambda (v)
(and (tailpos body v)
(every (lambda (e)
(when (isa? e ev_abs)
(with-access::ev_abs e (arity body)
(and (>=fx arity 0)
(tailpos body v) ))))
vals )))
vars ))
(define (subst_goto* l vars lbls)
(let rec ( (l l) )
(unless (null? l)
(set-car! l (subst_goto (car l) vars lbls))
(rec (cdr l)) )))
(define-generic (subst_goto e::ev_expr vars lbls)
(error 'subst_goto "not defined for" e) )
e )
e )
e )
(with-access::ev_if expr (p t e)
(set! p (subst_goto p vars lbls))
(set! t (subst_goto t vars lbls))
(set! e (subst_goto e vars lbls))
expr ))
(with-access::ev_list e (args)
(subst_goto* args vars lbls)
e ))
(with-access::ev_prog2 e (e1 e2)
(set! e1 (subst_goto e1 vars lbls))
(set! e2 (subst_goto e2 vars lbls))
e ))
(with-access::ev_hook expr (e)
(set! e (subst_goto e vars lbls))
expr ))
(with-access::ev_bind-exit e (var body)
(set! body (subst_goto body vars lbls))
e ))
(with-access::ev_unwind-protect expr (e body)
(set! e (subst_goto e vars lbls))
(set! body (subst_goto body vars lbls))
expr ))
(with-access::ev_with-handler e (handler body)
(set! handler (subst_goto handler vars lbls))
(set! body (subst_goto body vars lbls))
e ))
(with-access::ev_synchronize e (mutex prelock body)
(set! mutex (subst_goto mutex vars lbls))
(set! prelock (subst_goto prelock vars lbls))
(set! body (subst_goto body vars lbls))
e ))
(with-access::ev_binder e (vals body)
(subst_goto* vals vars lbls)
(set! body (subst_goto body vars lbls))
e ))
(with-access::ev_labels e (vals body)
(let rec ( (l vals) )
(unless (null? l)
(set-cdr! (car l) (subst_goto (cdar l) vars lbls))
(rec (cdr l)) ))
(set! body (subst_goto body vars lbls))
e ))
(with-access::ev_goto e (args)
(subst_goto* args vars lbls)
e ))
(with-access::ev_app e (fun args loc)
(subst_goto* args vars lbls)
(if (memq fun vars)
(instantiate::ev_goto (label fun) (args args) (labels lbls) (loc loc))
(begin (set! fun (subst_goto fun vars lbls))
e ))))
(with-access::ev_abs e (arity body)
(set! body (subst_goto body vars lbls))
e ))
(define-generic (tailpos e::ev_expr v::ev_var)
(error 'tailpos "not defined for" e) )
(not (eq? e v)) )
#t )
#t )
(with-access::ev_if e (p t e)
(and (not (hasvar? p v)) (tailpos t v) (tailpos e v)) ))
(with-access::ev_list e (args)
(let rec ( (l args) )
(if (null? (cdr l))
(tailpos (car l) v)
(and (not (hasvar? (car l) v))
(rec (cdr l)) )))))
(with-access::ev_prog2 e (e1 e2)
(and (not (hasvar? e1 v)) (tailpos e2 v)) ))
(with-access::ev_hook e (e)
(not (hasvar? e v)) ))
(with-access::ev_setlocal e (v e)
(and (not (eq? v var)) (not (hasvar? e var))) ))
(with-access::ev_bind-exit e (var body)
(not (hasvar? body v)) ))
(with-access::ev_unwind-protect e (e body)
(and (not (hasvar? e v)) (not (hasvar? body v))) ))
(with-access::ev_with-handler e (handler body)
(and (not (hasvar? handler v)) (not (hasvar? body v))) ))
(with-access::ev_synchronize e (mutex prelock body)
(and (not (hasvar? mutex v)) (not (hasvar? prelock v)) (not (hasvar? body v))) ))
(with-access::ev_let e (vars vals body)
(and (every (lambda (e) (not (hasvar? e v))) vals)
(tailpos body v) )))
(with-access::ev_let* e (vars vals body)
(and (every (lambda (e) (not (hasvar? e v))) vals)
(tailpos body v) )))
(with-access::ev_letrec e (vars vals body)
(and (every (lambda (e) (not (hasvar? e v))) vals)
(tailpos body v) )))
(with-access::ev_labels e (vals body)
(and (every (lambda (e) (tailpos (cdr e) v)) vals)
(tailpos body v) )))
(with-access::ev_goto e (args)
(every (lambda (e) (not (hasvar? e v))) args) ))
(with-access::ev_app e (fun args)
(and (every (lambda (e) (not (hasvar? e v))) args)
(or (eq? fun v)
(not (hasvar? fun v)) ))))
(with-access::ev_abs e (arity vars body)
(not (hasvar? body v)) ))
( hasvar ? e x ) return true iff x appear as a subexpression of e
(define-generic (hasvar? e::ev_expr v::ev_var))
(eq? e v) )
#f )
#f )
(with-access::ev_if e (p t e)
(or (hasvar? p v) (hasvar? t v) (hasvar? e v)) ))
(with-access::ev_list e (args)
(any (lambda (a) (hasvar? a v)) args) ))
(with-access::ev_prog2 e (e1 e2)
(or (hasvar? e1 v) (hasvar? e2 v)) ))
(with-access::ev_hook e (e)
(hasvar? e v) ))
(with-access::ev_setlocal e (v e)
(or (eq? v var) (hasvar? e var)) ))
(with-access::ev_bind-exit e (var body)
(hasvar? body v) ))
(with-access::ev_unwind-protect e (e body)
(or (hasvar? e v) (hasvar? body v)) ))
(with-access::ev_with-handler e (handler body)
(or (hasvar? handler v) (hasvar? body v)) ))
(with-access::ev_synchronize e (mutex prelock body)
(or (hasvar? mutex v) (hasvar? prelock v) (hasvar? body v)) ))
(with-access::ev_binder e (vals body)
(or (any (lambda (e) (hasvar? e v)) vals)
(hasvar? body v) )))
(with-access::ev_labels e (vals body)
(or (any (lambda (e) (hasvar? (cdr e) v)) vals)
(hasvar? body v) )))
(with-access::ev_goto e (args)
(any (lambda (e) (hasvar? e v)) args) ))
(with-access::ev_app e (fun args)
(or (hasvar? fun v) (any (lambda (e) (hasvar? e v)) args)) ))
(with-access::ev_abs e (vars body)
(hasvar? body v) ))
|
0288f9cab69134fd23f65dfed25503d8e23fbc3b95599db19ef943385550d6e2
|
borkdude/tools
|
ls_jar.clj
|
#!/usr/bin/env bb
(ns ls-jar
(:require
[babashka.cli :as cli]
[clojure.java.io :as io]
[clojure.string :as str]))
(def spec [[:lib {:desc "Library as fully qualified symbol. Must be accompanied with --version."}]
[:version {:desc "Version"}]
[:jar {:desc "Jar file"}]])
(defn print-help []
(println "Enumerate files from jar files")
(println "Usage: ls_jar <options>")
(println)
(println "Options:")
(println (cli/format-opts {:spec spec}))
(println)
(println "Examples:")
(println "ls_jar --lib babashka/fs --version 0.1.6")
(println "ls_jar --jar ~/.m2/repository/babashka/fs/0.1.6/fs-0.1.6.jar"))
(if (empty? *command-line-args*)
(print-help)
(let [{:keys [jar lib version help]} (cli/parse-opts *command-line-args* {:spec spec})]
(if help (print-help)
(let [file (if jar
(io/file jar)
(if (and lib version)
(let [[_org lib-name] (str/split lib #"/")]
(io/file (System/getProperty "user.home")
(format ".m2/repository/%s/%s/%s-%s.jar"
(str/replace lib "." (System/getProperty "file.separator"))
version
lib-name version)))
(do (println "Provide either --file or: --lib and --version")
(System/exit 1))))]
(doseq [e (enumeration-seq
(.entries (java.util.jar.JarFile. file)))]
(println (.getName e)))))))
| null |
https://raw.githubusercontent.com/borkdude/tools/4d37374e786058548f70d2f451927526a7342e17/ls_jar.clj
|
clojure
|
#!/usr/bin/env bb
(ns ls-jar
(:require
[babashka.cli :as cli]
[clojure.java.io :as io]
[clojure.string :as str]))
(def spec [[:lib {:desc "Library as fully qualified symbol. Must be accompanied with --version."}]
[:version {:desc "Version"}]
[:jar {:desc "Jar file"}]])
(defn print-help []
(println "Enumerate files from jar files")
(println "Usage: ls_jar <options>")
(println)
(println "Options:")
(println (cli/format-opts {:spec spec}))
(println)
(println "Examples:")
(println "ls_jar --lib babashka/fs --version 0.1.6")
(println "ls_jar --jar ~/.m2/repository/babashka/fs/0.1.6/fs-0.1.6.jar"))
(if (empty? *command-line-args*)
(print-help)
(let [{:keys [jar lib version help]} (cli/parse-opts *command-line-args* {:spec spec})]
(if help (print-help)
(let [file (if jar
(io/file jar)
(if (and lib version)
(let [[_org lib-name] (str/split lib #"/")]
(io/file (System/getProperty "user.home")
(format ".m2/repository/%s/%s/%s-%s.jar"
(str/replace lib "." (System/getProperty "file.separator"))
version
lib-name version)))
(do (println "Provide either --file or: --lib and --version")
(System/exit 1))))]
(doseq [e (enumeration-seq
(.entries (java.util.jar.JarFile. file)))]
(println (.getName e)))))))
|
|
0b561b5e92f31e9df4111dd5de7369606c1ca133e6d042333c89b4bd931da678
|
haskell/haskell-language-server
|
DestructDataFam.expected.hs
|
# LANGUAGE TypeFamilies #
data family Yo
data instance Yo = Heya Int
test :: Yo -> Int
test (Heya n) = _w0
| null |
https://raw.githubusercontent.com/haskell/haskell-language-server/f3ad27ba1634871b2240b8cd7de9f31b91a2e502/plugins/hls-tactics-plugin/new/test/golden/DestructDataFam.expected.hs
|
haskell
|
# LANGUAGE TypeFamilies #
data family Yo
data instance Yo = Heya Int
test :: Yo -> Int
test (Heya n) = _w0
|
|
9229d5e1abfc00bb64890d8e423204fe4ed14daddcacf6caf2b1f0eae033c074
|
nikita-volkov/text-builder
|
Main.hs
|
module Main where
import qualified Data.ByteString as ByteString
import qualified Data.Text as A
import qualified Data.Text.Encoding as Text
import Test.QuickCheck.Instances
import Test.Tasty
import Test.Tasty.HUnit
import Test.Tasty.QuickCheck
import qualified Text.Builder as B
import Prelude hiding (choose)
main =
defaultMain $
testGroup "All tests" $
[ testProperty "ASCII ByteString" $
let gen = listOf $ do
list <- listOf (choose (0, 127))
return (ByteString.pack list)
in forAll gen $ \chunks ->
mconcat chunks
=== Text.encodeUtf8 (B.run (foldMap B.asciiByteString chunks)),
testProperty "Intercalation has the same effect as in Text" $
\separator texts ->
A.intercalate separator texts
=== B.run (B.intercalate (B.text separator) (fmap B.text texts)),
testProperty "Packing a list of chars is isomorphic to appending a list of builders" $
\chars ->
A.pack chars
=== B.run (foldMap B.char chars),
testProperty "Concatting a list of texts is isomorphic to fold-mapping with builders" $
\texts ->
mconcat texts
=== B.run (foldMap B.text texts),
testProperty "Concatting a list of texts is isomorphic to concatting a list of builders" $
\texts ->
mconcat texts
=== B.run (mconcat (map B.text texts)),
testProperty "Concatting a list of trimmed texts is isomorphic to concatting a list of builders" $
\texts ->
let trimmedTexts = fmap (A.drop 3) texts
in mconcat trimmedTexts
=== B.run (mconcat (map B.text trimmedTexts)),
testProperty "Decimal" $ \(x :: Integer) ->
(fromString . show) x === (B.run (B.decimal x)),
testProperty "Hexadecimal vs std show" $ \(x :: Integer) ->
x >= 0
==> (fromString . showHex x) "" === (B.run . B.hexadecimal) x,
testCase "Separated thousands" $ do
assertEqual "" "0" (B.run (B.thousandSeparatedUnsignedDecimal ',' 0))
assertEqual "" "123" (B.run (B.thousandSeparatedUnsignedDecimal ',' 123))
assertEqual "" "1,234" (B.run (B.thousandSeparatedUnsignedDecimal ',' 1234))
assertEqual "" "1,234,567" (B.run (B.thousandSeparatedUnsignedDecimal ',' 1234567)),
testCase "Pad from left" $ do
assertEqual "" "00" (B.run (B.padFromLeft 2 '0' ""))
assertEqual "" "00" (B.run (B.padFromLeft 2 '0' "0"))
assertEqual "" "01" (B.run (B.padFromLeft 2 '0' "1"))
assertEqual "" "12" (B.run (B.padFromLeft 2 '0' "12"))
assertEqual "" "123" (B.run (B.padFromLeft 2 '0' "123")),
testCase "Pad from right" $ do
assertEqual "" "00" (B.run (B.padFromRight 2 '0' ""))
assertEqual "" "00" (B.run (B.padFromRight 2 '0' "0"))
assertEqual "" "10" (B.run (B.padFromRight 2 '0' "1"))
assertEqual "" "12" (B.run (B.padFromRight 2 '0' "12"))
assertEqual "" "123" (B.run (B.padFromRight 2 '0' "123"))
assertEqual "" "1 " (B.run (B.padFromRight 3 ' ' "1")),
testCase "Hexadecimal" $
assertEqual "" "1f23" (B.run (B.hexadecimal 0x01f23)),
testCase "Negative Hexadecimal" $
assertEqual "" "-1f23" (B.run (B.hexadecimal (-0x01f23))),
testGroup "Time interval" $
[ testCase "59s" $ assertEqual "" "00:00:00:59" $ B.run $ B.intervalInSeconds 59,
testCase "minute" $ assertEqual "" "00:00:01:00" $ B.run $ B.intervalInSeconds 60,
testCase "90s" $ assertEqual "" "00:00:01:30" $ B.run $ B.intervalInSeconds 90,
testCase "hour" $ assertEqual "" "00:01:00:00" $ B.run $ B.intervalInSeconds 3600,
testCase "day" $ assertEqual "" "01:00:00:00" $ B.run $ B.intervalInSeconds 86400
],
testCase "dataSizeInBytesInDecimal" $ do
assertEqual "" "999B" (B.run (B.dataSizeInBytesInDecimal ',' 999))
assertEqual "" "1kB" (B.run (B.dataSizeInBytesInDecimal ',' 1000))
assertEqual "" "1.1kB" (B.run (B.dataSizeInBytesInDecimal ',' 1100))
assertEqual "" "1.1MB" (B.run (B.dataSizeInBytesInDecimal ',' 1150000))
assertEqual "" "9.9MB" (B.run (B.dataSizeInBytesInDecimal ',' 9990000))
assertEqual "" "10MB" (B.run (B.dataSizeInBytesInDecimal ',' 10100000))
assertEqual "" "1,000YB" (B.run (B.dataSizeInBytesInDecimal ',' 1000000000000000000000000000))
]
| null |
https://raw.githubusercontent.com/nikita-volkov/text-builder/cb33836f27ed1d27eae70b094ddea5f15f7877a3/test/Main.hs
|
haskell
|
module Main where
import qualified Data.ByteString as ByteString
import qualified Data.Text as A
import qualified Data.Text.Encoding as Text
import Test.QuickCheck.Instances
import Test.Tasty
import Test.Tasty.HUnit
import Test.Tasty.QuickCheck
import qualified Text.Builder as B
import Prelude hiding (choose)
main =
defaultMain $
testGroup "All tests" $
[ testProperty "ASCII ByteString" $
let gen = listOf $ do
list <- listOf (choose (0, 127))
return (ByteString.pack list)
in forAll gen $ \chunks ->
mconcat chunks
=== Text.encodeUtf8 (B.run (foldMap B.asciiByteString chunks)),
testProperty "Intercalation has the same effect as in Text" $
\separator texts ->
A.intercalate separator texts
=== B.run (B.intercalate (B.text separator) (fmap B.text texts)),
testProperty "Packing a list of chars is isomorphic to appending a list of builders" $
\chars ->
A.pack chars
=== B.run (foldMap B.char chars),
testProperty "Concatting a list of texts is isomorphic to fold-mapping with builders" $
\texts ->
mconcat texts
=== B.run (foldMap B.text texts),
testProperty "Concatting a list of texts is isomorphic to concatting a list of builders" $
\texts ->
mconcat texts
=== B.run (mconcat (map B.text texts)),
testProperty "Concatting a list of trimmed texts is isomorphic to concatting a list of builders" $
\texts ->
let trimmedTexts = fmap (A.drop 3) texts
in mconcat trimmedTexts
=== B.run (mconcat (map B.text trimmedTexts)),
testProperty "Decimal" $ \(x :: Integer) ->
(fromString . show) x === (B.run (B.decimal x)),
testProperty "Hexadecimal vs std show" $ \(x :: Integer) ->
x >= 0
==> (fromString . showHex x) "" === (B.run . B.hexadecimal) x,
testCase "Separated thousands" $ do
assertEqual "" "0" (B.run (B.thousandSeparatedUnsignedDecimal ',' 0))
assertEqual "" "123" (B.run (B.thousandSeparatedUnsignedDecimal ',' 123))
assertEqual "" "1,234" (B.run (B.thousandSeparatedUnsignedDecimal ',' 1234))
assertEqual "" "1,234,567" (B.run (B.thousandSeparatedUnsignedDecimal ',' 1234567)),
testCase "Pad from left" $ do
assertEqual "" "00" (B.run (B.padFromLeft 2 '0' ""))
assertEqual "" "00" (B.run (B.padFromLeft 2 '0' "0"))
assertEqual "" "01" (B.run (B.padFromLeft 2 '0' "1"))
assertEqual "" "12" (B.run (B.padFromLeft 2 '0' "12"))
assertEqual "" "123" (B.run (B.padFromLeft 2 '0' "123")),
testCase "Pad from right" $ do
assertEqual "" "00" (B.run (B.padFromRight 2 '0' ""))
assertEqual "" "00" (B.run (B.padFromRight 2 '0' "0"))
assertEqual "" "10" (B.run (B.padFromRight 2 '0' "1"))
assertEqual "" "12" (B.run (B.padFromRight 2 '0' "12"))
assertEqual "" "123" (B.run (B.padFromRight 2 '0' "123"))
assertEqual "" "1 " (B.run (B.padFromRight 3 ' ' "1")),
testCase "Hexadecimal" $
assertEqual "" "1f23" (B.run (B.hexadecimal 0x01f23)),
testCase "Negative Hexadecimal" $
assertEqual "" "-1f23" (B.run (B.hexadecimal (-0x01f23))),
testGroup "Time interval" $
[ testCase "59s" $ assertEqual "" "00:00:00:59" $ B.run $ B.intervalInSeconds 59,
testCase "minute" $ assertEqual "" "00:00:01:00" $ B.run $ B.intervalInSeconds 60,
testCase "90s" $ assertEqual "" "00:00:01:30" $ B.run $ B.intervalInSeconds 90,
testCase "hour" $ assertEqual "" "00:01:00:00" $ B.run $ B.intervalInSeconds 3600,
testCase "day" $ assertEqual "" "01:00:00:00" $ B.run $ B.intervalInSeconds 86400
],
testCase "dataSizeInBytesInDecimal" $ do
assertEqual "" "999B" (B.run (B.dataSizeInBytesInDecimal ',' 999))
assertEqual "" "1kB" (B.run (B.dataSizeInBytesInDecimal ',' 1000))
assertEqual "" "1.1kB" (B.run (B.dataSizeInBytesInDecimal ',' 1100))
assertEqual "" "1.1MB" (B.run (B.dataSizeInBytesInDecimal ',' 1150000))
assertEqual "" "9.9MB" (B.run (B.dataSizeInBytesInDecimal ',' 9990000))
assertEqual "" "10MB" (B.run (B.dataSizeInBytesInDecimal ',' 10100000))
assertEqual "" "1,000YB" (B.run (B.dataSizeInBytesInDecimal ',' 1000000000000000000000000000))
]
|
|
e44dd93af3fcecc9a25cecd6d2701fb603a7944f48d14ae0f648c55134d68c0b
|
tezos/tezos-mirror
|
p2p_test_utils.mli
|
(*****************************************************************************)
(* *)
(* Open Source License *)
Copyright ( c ) 2020 Nomadic Labs , < >
(* *)
(* Permission is hereby granted, free of charge, to any person obtaining a *)
(* copy of this software and associated documentation files (the "Software"),*)
to deal in the Software without restriction , including without limitation
(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)
and/or sell copies of the Software , and to permit persons to whom the
(* Software is furnished to do so, subject to the following conditions: *)
(* *)
(* The above copyright notice and this permission notice shall be included *)
(* in all copies or substantial portions of the Software. *)
(* *)
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)
(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)
(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING
(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)
(* DEALINGS IN THE SOFTWARE. *)
(* *)
(*****************************************************************************)
(** This module provides functions used for tests. *)
(** Is a timeout used with [wait_pred] function. *)
type 'a timeout_t = {
time : float; (** Duration of the timeout. *)
msg : 'a -> string; (** Create the error message. *)
}
(** [wait_pred] wait until [pred arg] is true. If [pred] is not satisfy after
[timeout.time] seconds a [Timeout (timeout.msg arg)] error is raised. *)
val wait_pred :
?timeout:'a timeout_t ->
pred:('a -> bool) ->
arg:'a ->
unit ->
unit tzresult Lwt.t
(** Same as [wait_pred]. *)
val wait_pred_s :
?timeout:'a timeout_t ->
pred:('a -> bool Lwt.t) ->
arg:'a ->
unit ->
unit tzresult Lwt.t
(** Based on [wait_pred]. [wait_conns ~pool n] waits until at least [n]
connections are actives in [~pool]. *)
val wait_conns :
?timeout:float ->
pool:('a, 'b, 'c) Tezos_p2p.P2p_pool.t ->
int ->
unit tzresult Lwt.t
* [ connect_all connect_handler points ] establishes the connections to
[ points ] using [ connect_handler ] and returns them . If one connection need
more than [ ? timeout ] seconds to be established , the function fails with
[ Timeout ] error .
[points] using [connect_handler] and returns them. If one connection need
more than [?timeout] seconds to be established, the function fails with
[Timeout] error. *)
val connect_all :
?timeout:Time.System.Span.t ->
('a, 'b, 'c) P2p_connect_handler.t ->
P2p_point.Id.t list ->
('a, 'b, 'c) P2p_conn.t list tzresult Lwt.t
(** [close_active_conns pool@] closes all actives connections of the pool. This
function waits until the connections are effectively closed. *)
val close_active_conns : ('a, 'b, 'c) Tezos_p2p.P2p_pool.t -> unit Lwt.t
val addr : Ipaddr.V6.t ref
val canceler : Lwt_canceler.t
val proof_of_work_target : Tezos_crypto.Crypto_box.pow_target
val id1 : P2p_identity.t Lwt.t
val id2 : P2p_identity.t Lwt.t
val run_nodes :
?port:int ->
((unit, unit) Process.Channel.t ->
P2p_io_scheduler.t ->
Ipaddr.V6.t ->
int ->
(unit, error trace) result Lwt.t) ->
((unit, unit) Process.Channel.t ->
P2p_io_scheduler.t ->
Lwt_unix.file_descr ->
(unit, error trace) result Lwt.t) ->
(unit, error trace) result Lwt.t
val raw_accept :
P2p_io_scheduler.t ->
Lwt_unix.file_descr ->
( P2p_io_scheduler.connection * (P2p_addr.t * int),
[`Socket_error of exn | `System_error of exn | `Unexpected_error of exn] )
result
Lwt.t
val accept :
?id:P2p_identity.t Lwt.t ->
?proof_of_work_target:Tezos_crypto.Crypto_box.pow_target ->
P2p_io_scheduler.t ->
Lwt_unix.file_descr ->
( unit P2p_connection.Info.t * unit P2p_socket.authenticated_connection,
error trace )
result
Lwt.t
val raw_connect :
P2p_io_scheduler.t ->
P2p_addr.t ->
int ->
( P2p_io_scheduler.connection,
[`Connection_refused | `Unexpected_error of exn] )
result
Lwt.t
val connect :
?proof_of_work_target:Tezos_crypto.Crypto_box.pow_target ->
P2p_io_scheduler.t ->
P2p_addr.t ->
int ->
P2p_identity.t ->
( unit P2p_connection.Info.t * unit P2p_socket.authenticated_connection,
error trace )
result
Lwt.t
val sync : (unit, unit) Process.Channel.t -> (unit, error trace) result Lwt.t
| null |
https://raw.githubusercontent.com/tezos/tezos-mirror/5cc73af9f7c6029c4db68fe58fba2fb3922eb6d6/src/lib_p2p/test/common/p2p_test_utils.mli
|
ocaml
|
***************************************************************************
Open Source License
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
the rights to use, copy, modify, merge, publish, distribute, sublicense,
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
***************************************************************************
* This module provides functions used for tests.
* Is a timeout used with [wait_pred] function.
* Duration of the timeout.
* Create the error message.
* [wait_pred] wait until [pred arg] is true. If [pred] is not satisfy after
[timeout.time] seconds a [Timeout (timeout.msg arg)] error is raised.
* Same as [wait_pred].
* Based on [wait_pred]. [wait_conns ~pool n] waits until at least [n]
connections are actives in [~pool].
* [close_active_conns pool@] closes all actives connections of the pool. This
function waits until the connections are effectively closed.
|
Copyright ( c ) 2020 Nomadic Labs , < >
to deal in the Software without restriction , including without limitation
and/or sell copies of the Software , and to permit persons to whom the
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING
type 'a timeout_t = {
}
val wait_pred :
?timeout:'a timeout_t ->
pred:('a -> bool) ->
arg:'a ->
unit ->
unit tzresult Lwt.t
val wait_pred_s :
?timeout:'a timeout_t ->
pred:('a -> bool Lwt.t) ->
arg:'a ->
unit ->
unit tzresult Lwt.t
val wait_conns :
?timeout:float ->
pool:('a, 'b, 'c) Tezos_p2p.P2p_pool.t ->
int ->
unit tzresult Lwt.t
* [ connect_all connect_handler points ] establishes the connections to
[ points ] using [ connect_handler ] and returns them . If one connection need
more than [ ? timeout ] seconds to be established , the function fails with
[ Timeout ] error .
[points] using [connect_handler] and returns them. If one connection need
more than [?timeout] seconds to be established, the function fails with
[Timeout] error. *)
val connect_all :
?timeout:Time.System.Span.t ->
('a, 'b, 'c) P2p_connect_handler.t ->
P2p_point.Id.t list ->
('a, 'b, 'c) P2p_conn.t list tzresult Lwt.t
val close_active_conns : ('a, 'b, 'c) Tezos_p2p.P2p_pool.t -> unit Lwt.t
val addr : Ipaddr.V6.t ref
val canceler : Lwt_canceler.t
val proof_of_work_target : Tezos_crypto.Crypto_box.pow_target
val id1 : P2p_identity.t Lwt.t
val id2 : P2p_identity.t Lwt.t
val run_nodes :
?port:int ->
((unit, unit) Process.Channel.t ->
P2p_io_scheduler.t ->
Ipaddr.V6.t ->
int ->
(unit, error trace) result Lwt.t) ->
((unit, unit) Process.Channel.t ->
P2p_io_scheduler.t ->
Lwt_unix.file_descr ->
(unit, error trace) result Lwt.t) ->
(unit, error trace) result Lwt.t
val raw_accept :
P2p_io_scheduler.t ->
Lwt_unix.file_descr ->
( P2p_io_scheduler.connection * (P2p_addr.t * int),
[`Socket_error of exn | `System_error of exn | `Unexpected_error of exn] )
result
Lwt.t
val accept :
?id:P2p_identity.t Lwt.t ->
?proof_of_work_target:Tezos_crypto.Crypto_box.pow_target ->
P2p_io_scheduler.t ->
Lwt_unix.file_descr ->
( unit P2p_connection.Info.t * unit P2p_socket.authenticated_connection,
error trace )
result
Lwt.t
val raw_connect :
P2p_io_scheduler.t ->
P2p_addr.t ->
int ->
( P2p_io_scheduler.connection,
[`Connection_refused | `Unexpected_error of exn] )
result
Lwt.t
val connect :
?proof_of_work_target:Tezos_crypto.Crypto_box.pow_target ->
P2p_io_scheduler.t ->
P2p_addr.t ->
int ->
P2p_identity.t ->
( unit P2p_connection.Info.t * unit P2p_socket.authenticated_connection,
error trace )
result
Lwt.t
val sync : (unit, unit) Process.Channel.t -> (unit, error trace) result Lwt.t
|
08ac3c49b7f540b4b1b3993b5c39b0cdf80db2abeda1a64cdf2fca92e704aed6
|
jeannekamikaze/Spear
|
Utils.hs
|
module Spear.Math.Utils
(
Side(..)
, Face(..)
, orientation2d
, viewToWorld2d
)
where
import Spear.Math.Matrix4 as M4
import Spear.Math.Vector as V
data Side = L | R deriving (Eq, Show)
data Face = F | B deriving (Eq, Show)
-- | Return the signed area of the triangle defined by the given points.
orientation2d :: Vector2 -> Vector2 -> Vector2 -> Float
orientation2d p q r = (x q - x p) * (y r - y p) - (y q - y p) * (x r - x p)
| Project the given point in view space onto the XZ plane in world space .
viewToWorld2d :: Vector2 -- ^ Point in view space
-> Matrix4 -- ^ Inverse view matrix
-> Vector2 -- ^ Projection of the given point
viewToWorld2d p viewI =
let
p1' = vec3 (x p) (y p) 0
p1 = viewI `mulp` p1'
p2 = p1 - M4.forward viewI
lambda = (y p1 / (y p1 - y p2))
p' = p1 + V.scale lambda (p2 - p1)
in
vec2 (x p') (-z p')
| null |
https://raw.githubusercontent.com/jeannekamikaze/Spear/4ce19dca3441d1e079a66e2f3dc55b77a7f0898f/Spear/Math/Utils.hs
|
haskell
|
| Return the signed area of the triangle defined by the given points.
^ Point in view space
^ Inverse view matrix
^ Projection of the given point
|
module Spear.Math.Utils
(
Side(..)
, Face(..)
, orientation2d
, viewToWorld2d
)
where
import Spear.Math.Matrix4 as M4
import Spear.Math.Vector as V
data Side = L | R deriving (Eq, Show)
data Face = F | B deriving (Eq, Show)
orientation2d :: Vector2 -> Vector2 -> Vector2 -> Float
orientation2d p q r = (x q - x p) * (y r - y p) - (y q - y p) * (x r - x p)
| Project the given point in view space onto the XZ plane in world space .
viewToWorld2d p viewI =
let
p1' = vec3 (x p) (y p) 0
p1 = viewI `mulp` p1'
p2 = p1 - M4.forward viewI
lambda = (y p1 / (y p1 - y p2))
p' = p1 + V.scale lambda (p2 - p1)
in
vec2 (x p') (-z p')
|
e3100e33d5a1b5ce198302c07353f48c2f266a5e8706172c1808620ead5c8950
|
luminus-framework/luminus-template
|
reitit.clj
|
(ns leiningen.new.reitit
(:require [leiningen.new.common :refer :all]))
(def reitit-assets
[["{{resource-path}}/docs/docs.md" "reitit/resources/docs.md"]
["{{backend-path}}/{{sanitized}}/routes/home.clj" "reitit/src/home.clj"]])
(defn reitit-features [[assets options :as state]]
(if (some #{"+reitit"} (:features options))
[(into (remove-conflicting-assets assets "home.clj" "docs.md") reitit-assets)
(-> options
(append-options :dependencies [['metosin/reitit "0.5.18"]])
(assoc :reitit true))]
state))
| null |
https://raw.githubusercontent.com/luminus-framework/luminus-template/e23c79868553ae18ff692e89f9491d3731cf1b06/src/leiningen/new/reitit.clj
|
clojure
|
(ns leiningen.new.reitit
(:require [leiningen.new.common :refer :all]))
(def reitit-assets
[["{{resource-path}}/docs/docs.md" "reitit/resources/docs.md"]
["{{backend-path}}/{{sanitized}}/routes/home.clj" "reitit/src/home.clj"]])
(defn reitit-features [[assets options :as state]]
(if (some #{"+reitit"} (:features options))
[(into (remove-conflicting-assets assets "home.clj" "docs.md") reitit-assets)
(-> options
(append-options :dependencies [['metosin/reitit "0.5.18"]])
(assoc :reitit true))]
state))
|
|
57cb400cada56dfb0cbdd009a88339f3e6be0084ce19e9246ed8395ea98677fb
|
igrishaev/book-sessions
|
web2.clj
|
(ns book.web
(:require
[ring.middleware.params :refer [wrap-params]]
[ring.middleware.keyword-params :refer [wrap-keyword-params]]
[ring.adapter.jetty :refer [run-jetty]]))
(def wrap-params+ (comp wrap-params wrap-keyword-params))
(defn app-naked [request]
{:status 200
:body (pr-str (:params request))})
(def app (-> app-naked
wrap-params+))
#_
(def server (run-jetty app {:port 8080 :join? false}))
| null |
https://raw.githubusercontent.com/igrishaev/book-sessions/c62af1230e91b8ab9e4e456798e894d1b4145dfc/src/book/web2.clj
|
clojure
|
(ns book.web
(:require
[ring.middleware.params :refer [wrap-params]]
[ring.middleware.keyword-params :refer [wrap-keyword-params]]
[ring.adapter.jetty :refer [run-jetty]]))
(def wrap-params+ (comp wrap-params wrap-keyword-params))
(defn app-naked [request]
{:status 200
:body (pr-str (:params request))})
(def app (-> app-naked
wrap-params+))
#_
(def server (run-jetty app {:port 8080 :join? false}))
|
|
acc212a8b1cdd4ae0430081eb70f4afea94d80572156d5b585979bfa62d600c7
|
Xylios13/archigd
|
for-evaluation.rkt
|
#lang racket
(require "main.rkt")
(define (floors points levels)
(for ([lvl levels])
(slab points #:bottom-level lvl)))
(define (walls points levels)
(let* ((p1 (car points))
(p2 (car (cdr points)))
(wall-length (sqrt (+ (* (- (cx p2) (cx p1))
(- (cx p2) (cx p1)))
(* (- (cy p2) (cy p1))
(- (cy p2) (cy p1)))))))
(for ([lvl levels])
(for ([wall-index (wall (cons (last points) points) #:bottom-level lvl)])
(window wall-index (/ wall-length 2))))))
(define (tower points n-floors)
(let ((levels (for/list ([i n-floors])
(level (* i (default-level-to-level-height))))))
levels
(floors points levels)
(walls points levels)
(roof points #:bottom-level (upper-level #:level (last levels)))))
(define (wall1 beginPoint endPoint thickness height)
(let* ((dx (- (cx endPoint)(cx beginPoint)))
(dy (- (cy endPoint)(cy beginPoint)))
(hip (sqrt (+ (* dx dx)(* dy dy))))
(cosalpha (/ dx hip))
(sinalpha (/ dy hip)))
(box-2points beginPoint
(+xyz endPoint (* sinalpha thickness) (* cosalpha thickness) height))))
( define ( slab beginPoint length width height )
(box beginPoint length width height))
(define (wall2 p0 p1 thickness height)
(let* ((v (p-p p1 p0))
(new-p1 (+xyz (+pol p0
(pol-rho v)
(pol-phi v))
(* (sin (pol-phi v)) thickness)
(* (cos (pol-phi v)) thickness)
height)))
(box-2points p0 new-p1)))
#;(stairs "Stair Spiral 18"
(u0)
#:use-xy-fix-size #t
#:x-ratio 37
#:additional-parameters (list (list "zzyzx" 15)
(list "nRisers" (* 36 6))
(list "angle" 2pi)
(list "swelldia" 35)
(list "rightRailType_m" 0)
(list "leftRailType_m" 0)
(list "stairBaseType_m" 0)))
#;(stairs "Stair Spiral 18"
(u0)
#:use-xy-fix-size #t
#:x-ratio 37
#:height 15
#:properties (list "nRisers" (* 36 6)
"angle" 2pi
"swelldia" 35
"rightRailType_m" 0
"leftRailType_m" 0
"stairBaseType_m" 0))
(object "Rail Solid 18"
(+x (u0) -0.75))
(object "Rail Solid 18"
(+x (u0) -0.75)
#:angle pi/2)
(disconnect)
| null |
https://raw.githubusercontent.com/Xylios13/archigd/2276679ae60858f80efdf286fdd9fb38663e2269/archicad/testing%20examples/for-evaluation.rkt
|
racket
|
(stairs "Stair Spiral 18"
(stairs "Stair Spiral 18"
|
#lang racket
(require "main.rkt")
(define (floors points levels)
(for ([lvl levels])
(slab points #:bottom-level lvl)))
(define (walls points levels)
(let* ((p1 (car points))
(p2 (car (cdr points)))
(wall-length (sqrt (+ (* (- (cx p2) (cx p1))
(- (cx p2) (cx p1)))
(* (- (cy p2) (cy p1))
(- (cy p2) (cy p1)))))))
(for ([lvl levels])
(for ([wall-index (wall (cons (last points) points) #:bottom-level lvl)])
(window wall-index (/ wall-length 2))))))
(define (tower points n-floors)
(let ((levels (for/list ([i n-floors])
(level (* i (default-level-to-level-height))))))
levels
(floors points levels)
(walls points levels)
(roof points #:bottom-level (upper-level #:level (last levels)))))
(define (wall1 beginPoint endPoint thickness height)
(let* ((dx (- (cx endPoint)(cx beginPoint)))
(dy (- (cy endPoint)(cy beginPoint)))
(hip (sqrt (+ (* dx dx)(* dy dy))))
(cosalpha (/ dx hip))
(sinalpha (/ dy hip)))
(box-2points beginPoint
(+xyz endPoint (* sinalpha thickness) (* cosalpha thickness) height))))
( define ( slab beginPoint length width height )
(box beginPoint length width height))
(define (wall2 p0 p1 thickness height)
(let* ((v (p-p p1 p0))
(new-p1 (+xyz (+pol p0
(pol-rho v)
(pol-phi v))
(* (sin (pol-phi v)) thickness)
(* (cos (pol-phi v)) thickness)
height)))
(box-2points p0 new-p1)))
(u0)
#:use-xy-fix-size #t
#:x-ratio 37
#:additional-parameters (list (list "zzyzx" 15)
(list "nRisers" (* 36 6))
(list "angle" 2pi)
(list "swelldia" 35)
(list "rightRailType_m" 0)
(list "leftRailType_m" 0)
(list "stairBaseType_m" 0)))
(u0)
#:use-xy-fix-size #t
#:x-ratio 37
#:height 15
#:properties (list "nRisers" (* 36 6)
"angle" 2pi
"swelldia" 35
"rightRailType_m" 0
"leftRailType_m" 0
"stairBaseType_m" 0))
(object "Rail Solid 18"
(+x (u0) -0.75))
(object "Rail Solid 18"
(+x (u0) -0.75)
#:angle pi/2)
(disconnect)
|
5ffe476d9ff212277566d70f4cdd956024daccacb56cd9c49ed20a081848be37
|
c-cube/frog-utils
|
Html.ml
|
(* This file is free software, part of frog-utils. See file "license" for more details. *)
* { 1 Simple wrapper for HTML }
include Tyxml.Html
type t = Html_types.div_content_fun elt
type html = t
* { 2 Encoding Records in HTML }
let to_string h =
Misc.Fmt.to_string (pp_elt()) h
module Record = struct
type t = (string * html) list
let start = []
let add s f l = (s, f) :: l
let add_with_ fun_ ?(raw=false) s f l =
let body = txt (fun_ f) in
add s (div [if raw then pre [body] else body]) l
let add_int = add_with_ string_of_int
let add_float = add_with_ string_of_float
let add_string = add_with_ (fun x->x)
let add_string_option = add_with_ (function None -> "" | Some s -> s)
let add_bool = add_with_ string_of_bool
let add_record = (@)
let close l =
table
(List.rev_map
(fun (s,f) -> tr [td [txt s]; td [f]])
l)
end
(* TODO: same as record, but for full tables? *)
| null |
https://raw.githubusercontent.com/c-cube/frog-utils/3f68c606a7abe702f9e22a0606080191a2952b18/src/lib/Html.ml
|
ocaml
|
This file is free software, part of frog-utils. See file "license" for more details.
TODO: same as record, but for full tables?
|
* { 1 Simple wrapper for HTML }
include Tyxml.Html
type t = Html_types.div_content_fun elt
type html = t
* { 2 Encoding Records in HTML }
let to_string h =
Misc.Fmt.to_string (pp_elt()) h
module Record = struct
type t = (string * html) list
let start = []
let add s f l = (s, f) :: l
let add_with_ fun_ ?(raw=false) s f l =
let body = txt (fun_ f) in
add s (div [if raw then pre [body] else body]) l
let add_int = add_with_ string_of_int
let add_float = add_with_ string_of_float
let add_string = add_with_ (fun x->x)
let add_string_option = add_with_ (function None -> "" | Some s -> s)
let add_bool = add_with_ string_of_bool
let add_record = (@)
let close l =
table
(List.rev_map
(fun (s,f) -> tr [td [txt s]; td [f]])
l)
end
|
e6ba5c7f4369d09eab6023b2e80159fa5c97afcf4562708701ae00446bb6c98f
|
rtoy/ansi-cl-tests
|
compile.lsp
|
;-*- Mode: Lisp -*-
Author :
Created : Thu Oct 10 20:54:20 2002
;;;; Contains: Tests for COMPILE, COMPILED-FUNCTION-P, COMPILED-FUNCTION
(in-package :cl-test)
(deftest compile.1
(progn
(fmakunbound 'compile.1-fn)
(values
(eval '(defun compile.1-fn (x) x))
(compiled-function-p 'compile.1-fn)
(let ((x (compile 'compile.1-fn)))
(or (eqt x 'compile.1-fn)
(notnot (compiled-function-p x))))
(compiled-function-p 'compile.1-fn)
(not (compiled-function-p #'compile.1-fn))
(fmakunbound 'compile.1-fn)))
compile.1-fn
nil
t
nil
nil
compile.1-fn)
COMPILE returns three values ( function , warnings - p , failure - p )
(deftest compile.2
(let* ((results (multiple-value-list
(compile nil '(lambda (x y) (cons y x)))))
(fn (car results)))
(values (length results)
(funcall fn 'a 'b)
(second results)
(third results)))
3
(b . a)
nil
nil)
;;; Compile does not coalesce literal constants
(deftest compile.3
(let ((x (list 'a 'b))
(y (list 'a 'b)))
(and (not (eqt x y))
(funcall (compile nil `(lambda () (eqt ',x ',y))))))
nil)
(deftest compile.4
(let ((x (copy-seq "abc"))
(y (copy-seq "abc")))
(and (not (eqt x y))
(funcall (compile nil `(lambda () (eqt ,x ,y))))))
nil)
(deftest compile.5
(let ((x (copy-seq "abc")))
(funcall (compile nil `(lambda () (eqt ,x ,x)))))
t)
(deftest compile.6
(let ((x (copy-seq "abc")))
(funcall (compile nil `(lambda () (eqt ',x ',x)))))
t)
(deftest compile.7
(let ((x (copy-seq "abc")))
(eqt x (funcall (compile nil `(lambda () ,x)))))
t)
(deftest compile.8
(let ((x (list 'a 'b)))
(eqt x (funcall (compile nil `(lambda () ',x)))))
t)
(deftest compile.9
(let ((i 0) a b)
(values
(funcall (compile (progn (setf a (incf i)) nil)
(progn (setf b (incf i)) '(lambda () 'z))))
i a b))
z 2 1 2)
;;; Error tests
(deftest compile.error.1
(signals-error (compile) program-error)
t)
(deftest compile.error.2
(signals-error (compile nil '(lambda () nil) 'garbage)
program-error)
t)
| null |
https://raw.githubusercontent.com/rtoy/ansi-cl-tests/9708f3977220c46def29f43bb237e97d62033c1d/compile.lsp
|
lisp
|
-*- Mode: Lisp -*-
Contains: Tests for COMPILE, COMPILED-FUNCTION-P, COMPILED-FUNCTION
Compile does not coalesce literal constants
Error tests
|
Author :
Created : Thu Oct 10 20:54:20 2002
(in-package :cl-test)
(deftest compile.1
(progn
(fmakunbound 'compile.1-fn)
(values
(eval '(defun compile.1-fn (x) x))
(compiled-function-p 'compile.1-fn)
(let ((x (compile 'compile.1-fn)))
(or (eqt x 'compile.1-fn)
(notnot (compiled-function-p x))))
(compiled-function-p 'compile.1-fn)
(not (compiled-function-p #'compile.1-fn))
(fmakunbound 'compile.1-fn)))
compile.1-fn
nil
t
nil
nil
compile.1-fn)
COMPILE returns three values ( function , warnings - p , failure - p )
(deftest compile.2
(let* ((results (multiple-value-list
(compile nil '(lambda (x y) (cons y x)))))
(fn (car results)))
(values (length results)
(funcall fn 'a 'b)
(second results)
(third results)))
3
(b . a)
nil
nil)
(deftest compile.3
(let ((x (list 'a 'b))
(y (list 'a 'b)))
(and (not (eqt x y))
(funcall (compile nil `(lambda () (eqt ',x ',y))))))
nil)
(deftest compile.4
(let ((x (copy-seq "abc"))
(y (copy-seq "abc")))
(and (not (eqt x y))
(funcall (compile nil `(lambda () (eqt ,x ,y))))))
nil)
(deftest compile.5
(let ((x (copy-seq "abc")))
(funcall (compile nil `(lambda () (eqt ,x ,x)))))
t)
(deftest compile.6
(let ((x (copy-seq "abc")))
(funcall (compile nil `(lambda () (eqt ',x ',x)))))
t)
(deftest compile.7
(let ((x (copy-seq "abc")))
(eqt x (funcall (compile nil `(lambda () ,x)))))
t)
(deftest compile.8
(let ((x (list 'a 'b)))
(eqt x (funcall (compile nil `(lambda () ',x)))))
t)
(deftest compile.9
(let ((i 0) a b)
(values
(funcall (compile (progn (setf a (incf i)) nil)
(progn (setf b (incf i)) '(lambda () 'z))))
i a b))
z 2 1 2)
(deftest compile.error.1
(signals-error (compile) program-error)
t)
(deftest compile.error.2
(signals-error (compile nil '(lambda () nil) 'garbage)
program-error)
t)
|
f15502c17e2758ef61051b0339673d2e792dab7e7b51dc33b8370f506d233983
|
BitGameEN/bitgamex
|
cowboy_loop.erl
|
Copyright ( c ) 2011 - 2017 , < >
%%
%% Permission to use, copy, modify, and/or distribute this software for any
%% purpose with or without fee is hereby granted, provided that the above
%% copyright notice and this permission notice appear in all copies.
%%
THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES
%% WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
%% MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN
%% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
%% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
-module(cowboy_loop).
-behaviour(cowboy_sub_protocol).
-ifdef(OTP_RELEASE).
-compile({nowarn_deprecated_function, [{erlang, get_stacktrace, 0}]}).
-endif.
-export([upgrade/4]).
-export([upgrade/5]).
-export([loop/4]).
-export([system_continue/3]).
-export([system_terminate/4]).
-export([system_code_change/4]).
-callback init(Req, any())
-> {ok | module(), Req, any()}
| {module(), Req, any(), any()}
when Req::cowboy_req:req().
-callback info(any(), Req, State)
-> {ok, Req, State}
| {ok, Req, State, hibernate}
| {stop, Req, State}
when Req::cowboy_req:req(), State::any().
-callback terminate(any(), cowboy_req:req(), any()) -> ok.
-optional_callbacks([terminate/3]).
-spec upgrade(Req, Env, module(), any())
-> {ok, Req, Env} | {suspend, ?MODULE, loop, [any()]}
when Req::cowboy_req:req(), Env::cowboy_middleware:env().
upgrade(Req, Env, Handler, HandlerState) ->
loop(Req, Env, Handler, HandlerState).
-spec upgrade(Req, Env, module(), any(), hibernate)
-> {suspend, ?MODULE, loop, [any()]}
when Req::cowboy_req:req(), Env::cowboy_middleware:env().
upgrade(Req, Env, Handler, HandlerState, hibernate) ->
suspend(Req, Env, Handler, HandlerState).
-spec loop(Req, Env, module(), any())
-> {ok, Req, Env} | {suspend, ?MODULE, loop, [any()]}
when Req::cowboy_req:req(), Env::cowboy_middleware:env().
%% @todo Handle system messages.
loop(Req=#{pid := Parent}, Env, Handler, HandlerState) ->
receive
%% System messages.
{'EXIT', Parent, Reason} ->
terminate(Req, Env, Handler, HandlerState, Reason);
{system, From, Request} ->
sys:handle_system_msg(Request, From, Parent, ?MODULE, [],
{Req, Env, Handler, HandlerState});
%% Calls from supervisor module.
{'$gen_call', From, Call} ->
cowboy_children:handle_supervisor_call(Call, From, [], ?MODULE),
loop(Req, Env, Handler, HandlerState);
Message ->
call(Req, Env, Handler, HandlerState, Message)
end.
call(Req0, Env, Handler, HandlerState0, Message) ->
try Handler:info(Message, Req0, HandlerState0) of
{ok, Req, HandlerState} ->
loop(Req, Env, Handler, HandlerState);
{ok, Req, HandlerState, hibernate} ->
suspend(Req, Env, Handler, HandlerState);
{stop, Req, HandlerState} ->
terminate(Req, Env, Handler, HandlerState, stop)
catch Class:Reason ->
cowboy_handler:terminate({crash, Class, Reason}, Req0, HandlerState0, Handler),
erlang:raise(Class, Reason, erlang:get_stacktrace())
end.
suspend(Req, Env, Handler, HandlerState) ->
{suspend, ?MODULE, loop, [Req, Env, Handler, HandlerState]}.
terminate(Req, Env, Handler, HandlerState, Reason) ->
Result = cowboy_handler:terminate(Reason, Req, HandlerState, Handler),
{ok, Req, Env#{result => Result}}.
%% System callbacks.
-spec system_continue(_, _, {Req, Env, module(), any()})
-> {ok, Req, Env} | {suspend, ?MODULE, loop, [any()]}
when Req::cowboy_req:req(), Env::cowboy_middleware:env().
system_continue(_, _, {Req, Env, Handler, HandlerState}) ->
loop(Req, Env, Handler, HandlerState).
-spec system_terminate(any(), _, _, {Req, Env, module(), any()})
-> {ok, Req, Env} when Req::cowboy_req:req(), Env::cowboy_middleware:env().
system_terminate(Reason, _, _, {Req, Env, Handler, HandlerState}) ->
terminate(Req, Env, Handler, HandlerState, Reason).
-spec system_code_change(Misc, _, _, _) -> {ok, Misc}
when Misc::{cowboy_req:req(), cowboy_middleware:env(), module(), any()}.
system_code_change(Misc, _, _, _) ->
{ok, Misc}.
| null |
https://raw.githubusercontent.com/BitGameEN/bitgamex/151ba70a481615379f9648581a5d459b503abe19/src/deps/cowboy/src/cowboy_loop.erl
|
erlang
|
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
@todo Handle system messages.
System messages.
Calls from supervisor module.
System callbacks.
|
Copyright ( c ) 2011 - 2017 , < >
THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES
ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN
-module(cowboy_loop).
-behaviour(cowboy_sub_protocol).
-ifdef(OTP_RELEASE).
-compile({nowarn_deprecated_function, [{erlang, get_stacktrace, 0}]}).
-endif.
-export([upgrade/4]).
-export([upgrade/5]).
-export([loop/4]).
-export([system_continue/3]).
-export([system_terminate/4]).
-export([system_code_change/4]).
-callback init(Req, any())
-> {ok | module(), Req, any()}
| {module(), Req, any(), any()}
when Req::cowboy_req:req().
-callback info(any(), Req, State)
-> {ok, Req, State}
| {ok, Req, State, hibernate}
| {stop, Req, State}
when Req::cowboy_req:req(), State::any().
-callback terminate(any(), cowboy_req:req(), any()) -> ok.
-optional_callbacks([terminate/3]).
-spec upgrade(Req, Env, module(), any())
-> {ok, Req, Env} | {suspend, ?MODULE, loop, [any()]}
when Req::cowboy_req:req(), Env::cowboy_middleware:env().
upgrade(Req, Env, Handler, HandlerState) ->
loop(Req, Env, Handler, HandlerState).
-spec upgrade(Req, Env, module(), any(), hibernate)
-> {suspend, ?MODULE, loop, [any()]}
when Req::cowboy_req:req(), Env::cowboy_middleware:env().
upgrade(Req, Env, Handler, HandlerState, hibernate) ->
suspend(Req, Env, Handler, HandlerState).
-spec loop(Req, Env, module(), any())
-> {ok, Req, Env} | {suspend, ?MODULE, loop, [any()]}
when Req::cowboy_req:req(), Env::cowboy_middleware:env().
loop(Req=#{pid := Parent}, Env, Handler, HandlerState) ->
receive
{'EXIT', Parent, Reason} ->
terminate(Req, Env, Handler, HandlerState, Reason);
{system, From, Request} ->
sys:handle_system_msg(Request, From, Parent, ?MODULE, [],
{Req, Env, Handler, HandlerState});
{'$gen_call', From, Call} ->
cowboy_children:handle_supervisor_call(Call, From, [], ?MODULE),
loop(Req, Env, Handler, HandlerState);
Message ->
call(Req, Env, Handler, HandlerState, Message)
end.
call(Req0, Env, Handler, HandlerState0, Message) ->
try Handler:info(Message, Req0, HandlerState0) of
{ok, Req, HandlerState} ->
loop(Req, Env, Handler, HandlerState);
{ok, Req, HandlerState, hibernate} ->
suspend(Req, Env, Handler, HandlerState);
{stop, Req, HandlerState} ->
terminate(Req, Env, Handler, HandlerState, stop)
catch Class:Reason ->
cowboy_handler:terminate({crash, Class, Reason}, Req0, HandlerState0, Handler),
erlang:raise(Class, Reason, erlang:get_stacktrace())
end.
suspend(Req, Env, Handler, HandlerState) ->
{suspend, ?MODULE, loop, [Req, Env, Handler, HandlerState]}.
terminate(Req, Env, Handler, HandlerState, Reason) ->
Result = cowboy_handler:terminate(Reason, Req, HandlerState, Handler),
{ok, Req, Env#{result => Result}}.
-spec system_continue(_, _, {Req, Env, module(), any()})
-> {ok, Req, Env} | {suspend, ?MODULE, loop, [any()]}
when Req::cowboy_req:req(), Env::cowboy_middleware:env().
system_continue(_, _, {Req, Env, Handler, HandlerState}) ->
loop(Req, Env, Handler, HandlerState).
-spec system_terminate(any(), _, _, {Req, Env, module(), any()})
-> {ok, Req, Env} when Req::cowboy_req:req(), Env::cowboy_middleware:env().
system_terminate(Reason, _, _, {Req, Env, Handler, HandlerState}) ->
terminate(Req, Env, Handler, HandlerState, Reason).
-spec system_code_change(Misc, _, _, _) -> {ok, Misc}
when Misc::{cowboy_req:req(), cowboy_middleware:env(), module(), any()}.
system_code_change(Misc, _, _, _) ->
{ok, Misc}.
|
c1838b962dfe775370c802f5f78bf106bc9ea7e212c3575f09559c65116b824f
|
input-output-hk/project-icarus-importer
|
Report.hs
|
module Statistics.Report
( reportTxFate
) where
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as M
import qualified Data.Set as S
import qualified Data.Text as T
import System.IO (hPutStrLn)
import Statistics.Block (TxFate (..))
import Types
import Universum
reportTxFate :: FilePath -> Map TxHash TxFate -> IO ([TxHash], [TxHash], [TxHash])
reportTxFate f m = withFile f WriteMode $ \h -> do
let total = M.size m
m' = M.filter isFork m
fork = M.size m'
m'' = M.filter isChain m
chain = M.size m''
m''' = M.filter isLost m
lost = M.size m'''
chains = fst <$> M.toList m''
forks = fst <$> M.toList m'
losts = fst <$> M.toList m'''
hPutStrLn h $ "total transactions: " ++ show total
hPutStrLn h $ "in blockchain: " ++ show chain
hPutStrLn h $ "in fork: " ++ show fork
hPutStrLn h $ "lost: " ++ show lost
hPutStrLn h ""
hPutStrLn h "transactions in blockchain:"
for_ (M.toList m'') $ \(tx, InBlockChain _ hash _) ->
hPutStrLn h $ toString tx ++ ": " ++ toString (T.take 6 hash)
hPutStrLn h ""
hPutStrLn h "transactions in fork:"
for_ (M.toList m') $ \(tx, InFork s) ->
hPutStrLn h $ toString tx ++ ": " ++ toString (unwords $ map (T.take 6 . snd) $ S.toList s)
hPutStrLn h ""
hPutStrLn h "lost transactions:"
for_ (M.toList m''') $ \(tx, InNoBlock) ->
hPutStrLn h (toString tx)
return (chains, forks, losts)
isFork :: TxFate -> Bool
isFork (InFork _) = True
isFork _ = False
isLost :: TxFate -> Bool
isLost InNoBlock = True
isLost _ = False
isChain :: TxFate -> Bool
isChain (InBlockChain{}) = True
isChain _ = False
| null |
https://raw.githubusercontent.com/input-output-hk/project-icarus-importer/36342f277bcb7f1902e677a02d1ce93e4cf224f0/tools/src/post-mortem/Statistics/Report.hs
|
haskell
|
module Statistics.Report
( reportTxFate
) where
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as M
import qualified Data.Set as S
import qualified Data.Text as T
import System.IO (hPutStrLn)
import Statistics.Block (TxFate (..))
import Types
import Universum
reportTxFate :: FilePath -> Map TxHash TxFate -> IO ([TxHash], [TxHash], [TxHash])
reportTxFate f m = withFile f WriteMode $ \h -> do
let total = M.size m
m' = M.filter isFork m
fork = M.size m'
m'' = M.filter isChain m
chain = M.size m''
m''' = M.filter isLost m
lost = M.size m'''
chains = fst <$> M.toList m''
forks = fst <$> M.toList m'
losts = fst <$> M.toList m'''
hPutStrLn h $ "total transactions: " ++ show total
hPutStrLn h $ "in blockchain: " ++ show chain
hPutStrLn h $ "in fork: " ++ show fork
hPutStrLn h $ "lost: " ++ show lost
hPutStrLn h ""
hPutStrLn h "transactions in blockchain:"
for_ (M.toList m'') $ \(tx, InBlockChain _ hash _) ->
hPutStrLn h $ toString tx ++ ": " ++ toString (T.take 6 hash)
hPutStrLn h ""
hPutStrLn h "transactions in fork:"
for_ (M.toList m') $ \(tx, InFork s) ->
hPutStrLn h $ toString tx ++ ": " ++ toString (unwords $ map (T.take 6 . snd) $ S.toList s)
hPutStrLn h ""
hPutStrLn h "lost transactions:"
for_ (M.toList m''') $ \(tx, InNoBlock) ->
hPutStrLn h (toString tx)
return (chains, forks, losts)
isFork :: TxFate -> Bool
isFork (InFork _) = True
isFork _ = False
isLost :: TxFate -> Bool
isLost InNoBlock = True
isLost _ = False
isChain :: TxFate -> Bool
isChain (InBlockChain{}) = True
isChain _ = False
|
|
9ed0a77f963b3219b53c5732a3f73c00d990f68f77ff8fb2c58cb3dc9414d185
|
dparis/gen-phzr
|
bounds.cljs
|
(ns phzr.component.bounds
(:require [phzr.impl.utils.core :refer [clj->phaser phaser->clj]]
[phzr.impl.extend :as ex]
[cljsjs.phaser]))
(defn ->Bounds
"The Bounds component contains properties related to the bounds of the Game Object."
([]
(js/Phaser.Component.Bounds.)))
| null |
https://raw.githubusercontent.com/dparis/gen-phzr/e4c7b272e225ac343718dc15fc84f5f0dce68023/out/component/bounds.cljs
|
clojure
|
(ns phzr.component.bounds
(:require [phzr.impl.utils.core :refer [clj->phaser phaser->clj]]
[phzr.impl.extend :as ex]
[cljsjs.phaser]))
(defn ->Bounds
"The Bounds component contains properties related to the bounds of the Game Object."
([]
(js/Phaser.Component.Bounds.)))
|
|
1a4f59512cdcd7028f53bb131549a913194029c1ea8b167a201e7d2a3285d56a
|
learningclojurescript/code-examples
|
project.clj
|
(defproject schema-demo "0.1.0-SNAPSHOT"
:description "FIXME: write this!"
:url ""
:license {:name "Eclipse Public License"
:url "-v10.html"}
:min-lein-version "2.5.3"
:dependencies [[org.clojure/clojure "1.7.0"]
[org.clojure/clojurescript "1.7.170"]
[prismatic/schema "1.0.4"]
[org.clojure/core.async "0.2.374"
:exclusions [org.clojure/tools.reader]]]
:plugins [[lein-figwheel "0.5.0-6"]
[lein-cljsbuild "1.1.2" :exclusions [[org.clojure/clojure]]]]
:source-paths ["src"]
:clean-targets ^{:protect false} ["resources/public/js/compiled" "target"]
:cljsbuild {:builds
[{:id "dev"
:source-paths ["src"]
;; If no code is to be run, set :figwheel true for continued automagical reloading
:figwheel {:on-jsload "schema-demo.core/on-js-reload"}
:compiler {:main schema-demo.core
:asset-path "js/compiled/out"
:output-to "resources/public/js/compiled/schema_demo.js"
:output-dir "resources/public/js/compiled/out"
:source-map-timestamp true}}
;; This next build is an compressed minified build for
;; production. You can build this with:
once min
{:id "min"
:source-paths ["src"]
:compiler {:output-to "resources/public/js/compiled/schema_demo.js"
:main schema-demo.core
:optimizations :advanced
:pretty-print false}}]}
:figwheel {;; :http-server-root "public" ;; default and assumes "resources"
: server - port 3449 ; ; default
: server - ip " 127.0.0.1 "
:css-dirs ["resources/public/css"] ;; watch and update CSS
Start an nREPL server into the running figwheel process
: nrepl - port 7888
Server Ring Handler ( optional )
;; if you want to embed a ring handler into the figwheel http-kit
;; server, this is for simple ring servers, if this
;; doesn't work for you just run your own server :)
;; :ring-handler hello_world.server/handler
;; To be able to open files in your editor from the heads up display
;; you will need to put a script on your path.
;; that script will have to take a file path and a line number
;; ie. in ~/bin/myfile-opener
;; #! /bin/sh
emacsclient -n + $ 2 $ 1
;;
;; :open-file-command "myfile-opener"
;; if you want to disable the REPL
;; :repl false
;; to configure a different figwheel logfile path
;; :server-logfile "tmp/logs/figwheel-logfile.log"
})
| null |
https://raw.githubusercontent.com/learningclojurescript/code-examples/fdbd0e35ae5a16d53f1f784a52c25bcd4e5a8097/chapter-7/schema-demo/project.clj
|
clojure
|
If no code is to be run, set :figwheel true for continued automagical reloading
This next build is an compressed minified build for
production. You can build this with:
:http-server-root "public" ;; default and assumes "resources"
; default
watch and update CSS
if you want to embed a ring handler into the figwheel http-kit
server, this is for simple ring servers, if this
doesn't work for you just run your own server :)
:ring-handler hello_world.server/handler
To be able to open files in your editor from the heads up display
you will need to put a script on your path.
that script will have to take a file path and a line number
ie. in ~/bin/myfile-opener
#! /bin/sh
:open-file-command "myfile-opener"
if you want to disable the REPL
:repl false
to configure a different figwheel logfile path
:server-logfile "tmp/logs/figwheel-logfile.log"
|
(defproject schema-demo "0.1.0-SNAPSHOT"
:description "FIXME: write this!"
:url ""
:license {:name "Eclipse Public License"
:url "-v10.html"}
:min-lein-version "2.5.3"
:dependencies [[org.clojure/clojure "1.7.0"]
[org.clojure/clojurescript "1.7.170"]
[prismatic/schema "1.0.4"]
[org.clojure/core.async "0.2.374"
:exclusions [org.clojure/tools.reader]]]
:plugins [[lein-figwheel "0.5.0-6"]
[lein-cljsbuild "1.1.2" :exclusions [[org.clojure/clojure]]]]
:source-paths ["src"]
:clean-targets ^{:protect false} ["resources/public/js/compiled" "target"]
:cljsbuild {:builds
[{:id "dev"
:source-paths ["src"]
:figwheel {:on-jsload "schema-demo.core/on-js-reload"}
:compiler {:main schema-demo.core
:asset-path "js/compiled/out"
:output-to "resources/public/js/compiled/schema_demo.js"
:output-dir "resources/public/js/compiled/out"
:source-map-timestamp true}}
once min
{:id "min"
:source-paths ["src"]
:compiler {:output-to "resources/public/js/compiled/schema_demo.js"
:main schema-demo.core
:optimizations :advanced
:pretty-print false}}]}
: server - ip " 127.0.0.1 "
Start an nREPL server into the running figwheel process
: nrepl - port 7888
Server Ring Handler ( optional )
emacsclient -n + $ 2 $ 1
})
|
41fe655ab96f5e1532cea01f80fe344af65a8c729bc234e3ef8ee7304bf9b39a
|
hiroshi-unno/coar
|
z3interface.ml
|
open Core
open Z3
open Common
open Common.Ext
open Ast
open Ast.LogicOld
let verbose = false
module Debug = Debug.Make (val Debug.Config.(if verbose then enable else disable))
let validate = false
let validate_cfg = [ ("model_validate", "true"); ("well_sorted_check", "true") ]
(* let _ = Z3.set_global_param "smt.macro_finder" "true" *)
let mutex = Caml_threads.Mutex.create ()
let enable_mutex = false
let lock () = if enable_mutex then Caml_threads.Mutex.lock mutex
let unlock () = if enable_mutex then Caml_threads.Mutex.unlock mutex
let full_major () = if enable_mutex then Gc.full_major ()
let enable_solver_pool = true
type dtenv = (LogicOld.Datatype.t * Z3.Sort.sort) Set.Poly.t
type fenv = (Ident.tvar, Z3.FuncDecl.func_decl) Map.Poly.t
type instance = {
ctx : context;
solver : Z3.Solver.solver;
goal : Goal.goal;
cfg : (string * string) list;
mutable dtenv : dtenv;
mutable fenv : fenv;
}
let instance_pool = Hashtbl.Poly.create ()
let cache_divide_str = "__separator__"
let cache_id = Atomic.make 0
let term_cache: (context * ((Ident.tvar, Sort.t) List.Assoc.t), int * (Term.t, Expr.expr) Hashtbl.Poly.t) Hashtbl.Poly.t = Hashtbl.Poly.create ()
let bound_var_cache : (Expr.expr list) Atomic.t = Atomic.make []
let add_to_bound_var_cache e =
lock ();
Atomic.set bound_var_cache @@ e::(Atomic.get bound_var_cache);
unlock ()
let find_in_cache ~f ctx env t =
let cid, cache =
Hashtbl.Poly.find_or_add term_cache (ctx, env) ~default:(fun _ ->
Atomic.incr cache_id; Atomic.get cache_id, Hashtbl.Poly.create ())
in
Hashtbl.Poly.find_or_add cache t ~default:(fun _ ->
Debug.print @@ lazy ("not found: " ^ Term.str_of t);
lock ( ) ; ( fun ret - > unlock ( ) ; ret ) @@
f cid)
let clean () =
(* Hashtbl.Poly.clear cache; *)
Hashtbl.Poly.clear instance_pool
let z3_solver_reset solver =
lock ( ) ; ( fun ret - > unlock ( ) ; ret ) @@
Z3.Solver.reset solver
let z3_solver_add solver exprs =
lock ( ) ; ( fun ret - > unlock ( ) ; ret ) @@
Z3.Solver.add solver exprs
let z3_goal_add goal exprs =
lock ( ) ; ( fun ret - > unlock ( ) ; ret ) @@
Z3.Goal.add goal exprs
let z3_solver_get_model solver =
lock ( ) ; ( fun ret - > unlock ( ) ; ret )
Z3.Solver.get_model solver
let z3_solver_get_unsat_core solver =
lock ( ) ; ( fun ret - > unlock ( ) ; ret )
Z3.Solver.get_unsat_core solver
let z3_solver_assert_and_track solver e1 e2=
lock ( ) ; ( fun ret - > unlock ( ) ; ret )
Z3.Solver.assert_and_track solver e1 e2
let debug_print_z3_input phis =
Debug.print @@ lazy "Z3 input formulas :";
List.iter phis ~f:(fun phi -> Debug.print @@ lazy (Formula.str_of phi))
let debug_print_z3_model model =
Debug.print @@ lazy ("Z3 output model :" ^ LogicOld.str_of_model model)
(** decoding *)
let unint_svar_prefix = "#svar_"
let unint_is_cons_prefix = "#is_"
let unint_tuple_prefix = "#tuple"
let unint_tuple_sel_prefix = "#t_sel."
let unint_string_prefix = "#string_"
let unint_epsilon = "#epsilon"
let unint_symbol_prefix = "#symbol_"
let unint_concat_fin = "#concat_fin"
let unint_concat_inf = "#concat_inf"
let unint_is_prefix_of_fin = "#is_prefix_of_fin"
let unint_is_prefix_of_inf = "#is_prefix_of_inf"
let unint_is_in_reg_exp_fin_prefix = "#is_in_reg_exp_fin"
let unint_is_in_reg_exp_inf_prefix = "#is_in_reg_exp_inf"
let unint_string = "#string"
let unint_finseq = "#fin_seq"
let unint_infseq = "#inf_seq"
let unescape_z3 = String.substr_replace_all ~pattern:"|" ~with_:""
let rec sort_of env s =
match Z3.Sort.get_sort_kind s with
| Z3enums.BOOL_SORT -> T_bool.SBool
| Z3enums.INT_SORT -> T_int.SInt
| Z3enums.REAL_SORT -> T_real.SReal
| Z3enums.DATATYPE_SORT -> begin
match Set.Poly.find env ~f:(fun (_, sort) -> Stdlib.(s = sort)) with
| Some (dt, _) -> LogicOld.T_dt.SDT dt
| _ ->
if String.is_prefix ~prefix:unint_tuple_prefix @@ unescape_z3 @@ Z3.Sort.to_string s then
let sorts = List.map ~f:(fun sel -> sort_of env @@ FuncDecl.get_range sel) @@ Tuple.get_field_decls s in
T_tuple.STuple sorts
else failwith @@ "[Z3interface.sort_of] unknown dt type:" ^ Z3.Sort.to_string s
end
| Z3enums.ARRAY_SORT ->
T_array.SArray (sort_of env @@ Z3Array.get_domain s, sort_of env @@ Z3Array.get_range s)
| Z3enums.UNINTERPRETED_SORT ->
let name = Symbol.get_string @@ Z3.Sort.get_name s in
if String.is_prefix ~prefix:unint_svar_prefix name then
let svar = String.sub name ~pos:(String.length unint_svar_prefix) ~len:(String.length name - String.length unint_svar_prefix) in
Sort.SVar (Ident.Svar svar)
else if String.(name = unint_string) then T_string.SString
else if String.(name = unint_finseq) then T_sequence.SFinSequence
else if String.(name = unint_infseq) then T_sequence.SInfSequence
else T_dt.SUS (name, [])
ToDo : implement other cases
failwith @@ "[Z3interface.sort_of] unknown type:" ^ Z3.Sort.to_string s
let look_up_func_of_dt dt sort func =
(* Debug.print @@ lazy (sprintf "look_up_func:%d :%s" (Z3.FuncDecl.get_id func) (Z3.FuncDecl.to_string func)); *)
let id = Z3.FuncDecl.get_id func in
let conses = Datatype.conses_of dt in
let z3_conses = Z3.Datatype.get_constructors sort in
let z3_testers = Z3.Datatype.get_recognizers sort in
let z3_selss = Z3.Datatype.get_accessors sort in
let z3_funcs = List.zip3_exn z3_conses z3_testers z3_selss in
List.fold2_exn conses z3_funcs ~init:`Unkonwn ~f:(fun ret cons (z3_cons, z3_tester, z3_sels) ->
match ret with
|`Unkonwn ->
if id = FuncDecl.get_id z3_cons then `Cons cons
else if id = FuncDecl.get_id z3_tester then `IsCons cons
else
List.fold2_exn (LogicOld.Datatype.sels_of_cons cons) z3_sels ~init:ret ~f:(fun ret sel z3_sel ->
(* Debug.print @@ lazy (sprintf "search_sel %d =? %d :%s" id (Z3.FuncDecl.get_id z3_sel) (Z3.FuncDecl.to_string z3_sel)); *)
match ret with
| `Unkonwn -> if id = FuncDecl.get_id z3_sel then `Sel sel else ret
| _ -> ret)
| _ -> ret)
let look_up_func dtenv func =
Set.Poly.find_map dtenv ~f:(fun (dt, sort) ->
match look_up_func_of_dt dt sort func with
| `Unkonwn -> None
| ret -> Some (dt, ret))
let rec parse_term = function
| Sexp.Atom "x" ->
Term.mk_var (Ident.Tvar "x") T_real.SReal
| Sexp.Atom ident -> begin
try T_int.mk_int (Z.of_string ident) with _ ->
try T_real.mk_real (Q.of_string ident) with _ ->
failwith "[Z3interface.parse_term]"
end
| Sexp.List [Sexp.Atom "-"; t] ->
ToDo
| Sexp.List (Sexp.Atom "+" :: arg :: args) ->
ToDo
| Sexp.List (Sexp.Atom "*" :: arg :: args) ->
ToDo
| Sexp.List [Sexp.Atom "^"; t1; t2] ->
ToDo
| _ -> failwith "[Z3interface.parse_term]"
let parse_root_obj = function
| Sexp.List [Sexp.Atom "root-obj"; t; n] ->
let t = parse_term t in t, (int_of_string @@ Sexp.to_string n)
| e -> failwith @@ "[Z3interface.parse_root_obj]" ^ Sexp.to_string e ^ " is not root-obj"
let var_of s =
Scanf.unescaped @@ (try Scanf.sscanf s "|%s@|" Fn.id with _ -> s)
|> Str.split (Str.regexp cache_divide_str)
|> List.hd_exn
let rec apply senv penv dtenv op expr =
match List.map ~f:(term_of senv penv dtenv) @@ Expr.get_args expr with
| e :: es -> List.fold ~init:e es ~f:op
| _ -> assert false
and apply_bop senv penv dtenv op expr =
match Expr.get_args expr with
| [e1; e2] -> op (term_of senv penv dtenv e1) (term_of senv penv dtenv e2)
| _ -> assert false
and apply_brel senv penv dtenv op expr =
match Expr.get_args expr with
| [e1; e2] -> op (term_of senv penv dtenv e1) (term_of senv penv dtenv e2)
| _ -> assert false
from Z3 expr to our term
(* term_of: (Ident.tvar, Sort.t) List.Assoc.t -> (Ident.pvar, FuncDecl.func_decl) List.Assoc.t -> Z3.Expr.expr -> info Logic.term *)
and term_of (senv: (Ident.tvar, Sort.t) List.Assoc.t) (penv: (Ident.pvar, FuncDecl.func_decl) List.Assoc.t) (dtenv:dtenv) expr = (*try*)
Debug.print @@ lazy ("[Z3interface.term_of] " ^ Z3.Expr.to_string expr);
if Boolean.is_true expr then
T_bool.of_atom @@ Atom.mk_true ()
else if Boolean.is_false expr then
T_bool.of_atom @@ Atom.mk_false ()
else if Boolean.is_ite expr then
match Expr.get_args expr with
| [e1; e2; e3] ->
T_bool.ifte (formula_of senv penv dtenv e1) (term_of senv penv dtenv e2) (term_of senv penv dtenv e3)
| _ -> assert false
else if Arithmetic.is_int_numeral expr then
T_int.mk_int (Arithmetic.Integer.get_big_int expr)
else if Arithmetic.is_rat_numeral expr then
T_real.mk_real (Arithmetic.Real.get_ratio expr)
else if Arithmetic.is_algebraic_number expr then
let expr = Sexp.of_string @@ Expr.to_string expr in
let t, n = parse_root_obj expr in
T_real.mk_alge t n
else if Arithmetic.is_add expr then
match sort_of dtenv @@ Expr.get_sort expr with
| T_int.SInt -> apply senv penv dtenv T_int.mk_add expr
| T_real.SReal -> apply senv penv dtenv T_real.mk_radd expr
| _ -> failwith @@ "[Z3interface.term_of]" ^ Z3.Sort.to_string @@ Expr.get_sort expr
else if Arithmetic.is_sub expr then
match sort_of dtenv @@ Expr.get_sort expr with
| T_int.SInt -> apply senv penv dtenv T_int.mk_sub expr
| T_real.SReal -> apply senv penv dtenv T_real.mk_rsub expr
| _ -> failwith @@ "[Z3interface.term_of]" ^ Z3.Sort.to_string @@ Expr.get_sort expr
else if Arithmetic.is_mul expr then
match sort_of dtenv @@ Expr.get_sort expr with
| T_int.SInt -> apply senv penv dtenv T_int.mk_mult expr
| T_real.SReal -> apply senv penv dtenv T_real.mk_rmult expr
| _ -> failwith @@ "[Z3interface.term_of]" ^ Z3.Sort.to_string @@ Expr.get_sort expr
else if Arithmetic.is_idiv expr then
apply_bop senv penv dtenv T_int.mk_div expr
else if Arithmetic.is_div expr then
apply_bop senv penv dtenv T_real.mk_rdiv expr
else if Arithmetic.is_modulus expr then
apply_bop senv penv dtenv T_int.mk_mod expr
else if Arithmetic.is_remainder expr then
apply_bop senv penv dtenv T_int.mk_rem expr
else if AST.is_var @@ Expr.ast_of_expr expr then (* bound variables *)
let _ = Debug.print @@ lazy ("z3 bound var: " ^ Expr.to_string expr) in
try
let tvar, sort =
List.nth_exn senv @@
List.length senv - Scanf.sscanf (Expr.to_string expr) "(:var %d)" Fn.id - 1
in
Term.mk_var tvar sort
with _ -> failwith @@ "[Z3interface.term_of] " ^ Expr.to_string expr ^ " not found"
else if Z3Array.is_store expr then
let sa = sort_of dtenv @@ Expr.get_sort expr in
match List.map ~f:(term_of senv penv dtenv) @@ Expr.get_args expr, sa with
| [t1; t2; t3], T_array.SArray (s1, s2) -> T_array.mk_store s1 s2 t1 t2 t3
| _ -> failwith "[Z3interface.term_of]"
else if Z3Array.is_constant_array expr then
let sa = sort_of dtenv @@ Expr.get_sort expr in
match List.map ~f:(term_of senv penv dtenv) @@ Expr.get_args expr, sa with
| [t1], T_array.SArray (s1, s2) -> T_array.mk_const_array s1 s2 t1
| _ -> failwith "[Z3interface.term_of]"
else if Z3Array.is_select expr then
let args = Expr.get_args expr in
match args, List.map ~f:(term_of senv penv dtenv) args with
| [e1; _e2], [t1; t2] -> begin
match T_array.eval_select t1 t2, sort_of dtenv @@ Expr.get_sort e1 with
| Some te, _ -> te
| _, T_array.SArray (s1, s2) -> T_array.mk_select s1 s2 t1 t2
| _ -> failwith "[Z3interface.term_of]"
end
| _ -> failwith "[Z3interface.term_of]"
else (* applications (and constants) *)
try
let func = Z3.Expr.get_func_decl expr in
let name =
FuncDecl.get_name func
|> Symbol.get_string
|> unescape_z3
|> Str.split (Str.regexp cache_divide_str)
|> List.hd_exn
in
let ts = List.map ~f:(term_of senv penv dtenv) @@ Z3.Expr.get_args expr in
let sorts = List.map ~f:Term.sort_of ts in
the following causes an exception if [ expr ] contains a bound variable :
let sorts = List.map ~f:(fun e - > sort_of dtenv @@ Expr.get_sort e ) @@ Z3.Expr.get_args expr in
let sorts = List.map ~f:(fun e -> sort_of dtenv @@ Expr.get_sort e) @@ Z3.Expr.get_args expr in *)
let sort = sort_of dtenv @@ FuncDecl.get_range func in
try (* algebraic data types *)
Debug.print @@ lazy (sprintf "[Z3interface.term_of] %s" @@ Z3.Expr.to_string expr);
match look_up_func dtenv func with
| Some (dt, `Cons cons) ->
T_dt.mk_cons dt (Datatype.name_of_cons cons) ts
| Some (dt, `IsCons cons) ->
T_bool.of_atom @@ T_dt.mk_is_cons dt (Datatype.name_of_cons cons) @@ List.hd_exn ts
| Some (dt, `Sel sel) ->
T_dt.mk_sel dt (Datatype.name_of_sel sel) @@ List.hd_exn ts
| None when T_dt.is_sdt sort && List.is_empty ts ->
Term.mk_var (Ident.Tvar name) sort
| _ -> failwith "[Z3interface.term_of] not an ADT term"
with _ ->
try (* tuples *)
if String.is_prefix ~prefix:unint_tuple_prefix name then
T_tuple.mk_tuple_cons sorts ts
else if String.is_prefix ~prefix:unint_tuple_sel_prefix name && List.length ts = 1 then
let pre_length = String.length unint_tuple_sel_prefix in
let i = Int.of_string @@ String.sub name ~pos:pre_length ~len:(String.length name - pre_length) in
match ts, sorts with
| [t], [T_tuple.STuple sorts] -> T_tuple.mk_tuple_sel sorts t i
| _ -> failwith "[Z3interface.term_of] not a valid tuple/string/sequence term"
else if String.(name = "is"(*ToDo: Z3 automatically generates a tester of the name*)) && List.length ts = 1 then
match ts, sorts with
| [_t], [T_tuple.STuple _sorts] ->
T_bool.of_atom @@ T_tuple.mk_is_tuple sorts t
| _ -> failwith "[Z3interface.term_of] not a valid tuple/string/sequence term"
else if String.is_prefix ~prefix:unint_string_prefix name && List.is_empty ts then
let pre_length = String.length unint_string_prefix in
let str = String.sub name ~pos:pre_length ~len:(String.length name - pre_length) in
T_string.mk_string_const str
else if String.(name = unint_epsilon) && List.is_empty ts then
T_sequence.mk_eps ()
else if String.is_prefix ~prefix:unint_symbol_prefix name && List.is_empty ts then
let pre_length = String.length unint_symbol_prefix in
let symbol = String.sub name ~pos:pre_length ~len:(String.length name - pre_length) in
T_sequence.mk_symbol symbol
else if String.(name = unint_concat_fin) then
match ts with
| [t1; t2] -> T_sequence.concat ~fin:true t1 t2
| _ -> failwith "[Z3interface.term_of] not a valid tuple/string/sequence term"
else if String.(name = unint_concat_inf) && List.length ts = 2 then
match ts with
| [t1; t2] -> T_sequence.concat ~fin:false t1 t2
| _ -> failwith "[Z3interface.term_of] not a valid tuple/string/sequence term"
else if String.is_prefix ~prefix:unint_is_prefix_of_fin name then
match ts with
| [t1; t2] -> T_bool.of_atom @@ T_sequence.mk_is_prefix true t1 t2
| _ -> failwith "[Z3interface.term_of] not a valid tuple/string/sequence term"
else if String.is_prefix ~prefix:unint_is_prefix_of_inf name && List.length ts = 2 then
match ts with
| [t1; t2] -> T_bool.of_atom @@ T_sequence.mk_is_prefix false t1 t2
| _ -> failwith "[Z3interface.term_of] not a valid tuple/string/sequence term"
else if String.is_prefix ~prefix:unint_is_in_reg_exp_fin_prefix name then
let regexp = failwith "not supported" in
match ts with
| [t] -> T_bool.of_atom @@ T_sequence.mk_is_in_regexp true regexp t
| _ -> failwith "[Z3interface.term_of] not a valid tuple/string/sequence term"
else if String.is_prefix ~prefix:unint_is_in_reg_exp_inf_prefix name then
let regexp = failwith "not supported" in
match ts with
| [t] -> T_bool.of_atom @@ T_sequence.mk_is_in_regexp false regexp t
| _ -> failwith "[Z3interface.term_of] not a valid tuple/string/sequence term"
else failwith "[Z3interface.term_of] not a tuple/string/sequence term"
with _ ->
match Map.Poly.find (Atomic.get ref_fenv) (Ident.Tvar name) with
| Some (params, ret_sort, _, _, _) ->
Term.mk_fvar_app (Ident.Tvar name) (List.map params ~f:snd @ [ret_sort](*sorts @ [sort]*)) ts
| _ ->
ToDo
match sort_of dtenv @@ Expr.get_sort expr with
| T_bool.SBool -> T_bool.of_formula @@ formula_of senv penv dtenv expr
| _ -> failwith "[Z3interface.term_of] not a formula"
with _ ->
if List.is_empty ts then Term.mk_var (Ident.Tvar name) sort
else LogicOld.Term.mk_fvar_app (Ident.Tvar name) (sorts @ [sort]) ts
with Failure err ->
match sort_of dtenv @@ Expr.get_sort expr with
| T_bool.SBool -> T_bool.of_formula @@ formula_of senv penv dtenv expr
| _ -> failwith @@ sprintf "[Z3interface.term_of] %s : %s" err @@ Z3.Expr.to_string expr
and
from Z3 expr to our atom
atom_of : ( Ident.tvar , Sort.t ) List . Assoc.t - > ( Ident.pvar , FuncDecl.func_decl ) List . Assoc.t - > Z3.Expr.expr - > info Logic . Atom.t
atom_of
(senv : (Ident.tvar, Sort.t) List.Assoc.t)
(penv : (Ident.pvar, FuncDecl.func_decl) List.Assoc.t)
(dtenv : dtenv)
expr =
Debug.print @@ lazy ( " [ z3 : atom_of ] " ^ Z3.Expr.to_string expr ) ;
if Boolean.is_true expr then
Atom.mk_true ()
else if Boolean.is_false expr then
Atom.mk_false ()
else if Boolean.is_eq expr then
apply_brel senv penv dtenv T_bool.mk_eq expr
else if Arithmetic.is_le expr then
Typeinf.typeinf_atom @@ apply_brel senv penv dtenv T_num.mk_nleq expr
else if Arithmetic.is_ge expr then
Typeinf.typeinf_atom @@ apply_brel senv penv dtenv T_num.mk_ngeq expr
else if Arithmetic.is_lt expr then
Typeinf.typeinf_atom @@ apply_brel senv penv dtenv T_num.mk_nlt expr
else if Arithmetic.is_gt expr then
Typeinf.typeinf_atom @@ apply_brel senv penv dtenv T_num.mk_ngt expr
else if AST.is_var @@ Expr.ast_of_expr expr then (* bound variables *)
let tvar, _sort(* assume bool*) =
List.nth_exn senv @@
List.length senv - Scanf.sscanf (Expr.to_string expr) "(:var %d)" Fn.id - 1
in
match List.Assoc.find ~equal:Stdlib.(=) penv (Ident.tvar_to_pvar tvar) with
| Some _ -> Atom.mk_pvar_app (Ident.tvar_to_pvar tvar) [] []
| _ -> Atom.of_bool_term @@ Term.mk_var tvar T_bool.SBool
else
let func = Z3.Expr.get_func_decl expr in
let name =
FuncDecl.get_name func
|> Symbol.get_string
|> unescape_z3
|> Str.split (Str.regexp cache_divide_str)
|> List.hd_exn
in
let pvar = Ident.Pvar name in
let ts = List.map ~f:(term_of senv penv dtenv) @@ Z3.Expr.get_args expr in
match List.Assoc.find ~equal:Stdlib.(=) penv pvar with
| Some _ -> Atom.mk_pvar_app pvar (List.map ts ~f:Term.sort_of) ts
| None ->
try Atom.of_bool_term @@ term_of senv penv dtenv expr with _ ->
failwith @@ "[Z3interface.atom_of] " ^ Z3.Expr.to_string expr
and
from Z3 expr to our formula
formula_of : ( Ident.tvar , Sort.t ) List . Assoc.t - > ( Ident.pvar , FuncDecl.func_decl ) List . Assoc.t - > Z3.Expr.expr - > info Logic . Formula.t
formula_of
(senv : (Ident.tvar, Sort.t) List.Assoc.t)
(penv : (Ident.pvar, FuncDecl.func_decl) List.Assoc.t)
(dtenv : dtenv)
expr =
(* Debug.print @@ lazy ("[Z3interface.formula_of] " ^ Z3.Expr.to_string expr); *)
if Boolean.is_not expr then
match Expr.get_args expr with
| [body] -> Formula.negate (formula_of senv penv dtenv body)
| _ -> failwith "[Z3interface.formula_of]"
else if Boolean.is_and expr then
Formula.and_of @@ List.map ~f:(formula_of senv penv dtenv) @@ Expr.get_args expr
else if Boolean.is_or expr then
Formula.or_of @@ List.map ~f:(formula_of senv penv dtenv) @@ Expr.get_args expr
else if Boolean.is_iff expr then
Expr.get_args expr
|> List.map ~f:(formula_of senv penv dtenv)
|> function [phi1; phi2] -> Formula.mk_iff phi1 phi2
| _ -> failwith "[Z3interface.formula_of]"
else if Boolean.is_implies expr then
Expr.get_args expr
|> List.map ~f:(formula_of senv penv dtenv)
|> function [phi1; phi2] -> Formula.mk_imply phi1 phi2
| _ -> failwith "[Z3interface.formula_of]"
else if Boolean.is_ite expr then
match Expr.get_args expr with
| [e1; e2; e3] ->
Formula.of_bool_term @@
T_bool.ifte (formula_of senv penv dtenv e1) (term_of senv penv dtenv e2) (term_of senv penv dtenv e3)
| _ -> failwith "[Z3interface.formula_of]"
else if AST.is_quantifier @@ Expr.ast_of_expr expr then
let q = Quantifier.quantifier_of_expr expr in
let binder = if Quantifier.is_universal q then Formula.Forall else Formula.Exists in
let bounds =
List.zip_exn
(List.map ~f:(fun x -> Ident.Tvar (Symbol.get_string x)) @@
Quantifier.get_bound_variable_names q)
(List.map ~f:(sort_of dtenv) @@ Quantifier.get_bound_variable_sorts q)
in
let senv = bounds @ senv in
Formula.mk_bind binder bounds @@
formula_of senv penv dtenv @@ Quantifier.get_body q
else Formula.mk_atom @@ atom_of senv penv dtenv expr
let dummy_term_map_of terms =
Map.of_set_exn @@ Set.Poly.filter_map terms ~f:(function (tvar, (T_dt.SUS _ as sort)) ->
Some (tvar, mk_fresh_dummy_term sort) | _ -> None)
let add_dummy_term model =
List.filter_map model ~f:(function _, Some t -> Some t | _ -> None)
|> List.fold_left ~init:Set.Poly.empty ~f:(fun ret term ->
Set.Poly.filter ~f:(function (_, T_dt.SUS _) -> true | _ -> false) @@
Set.Poly.union ret @@ Term.term_sort_env_of term)
|> Set.Poly.iter ~f:(fun (tvar, sort) -> add_dummy_term tvar sort)
let model_of dtenv model =
let model =
List.map (Model.get_decls model) ~f:(fun decl ->
let x =
FuncDecl.get_name decl
|> Symbol.get_string
|> Str.split (Str.regexp cache_divide_str)
|> List.hd_exn
in
let s =
Sort.mk_fun @@
List.map ~f:(sort_of dtenv) @@
FuncDecl.get_domain decl @ [FuncDecl.get_range decl]
in
(Ident.Tvar x, s),
if FuncDecl.get_arity decl = 0 then
match Model.get_const_interp model decl with
| Some expr -> Some (term_of [] [] dtenv expr)
| None -> None
else
match Model.get_func_interp model decl with
ToDo
| None -> None)
in
Debug.print @@ lazy ("model is :" ^ LogicOld.str_of_model model);
model
(** encoding *)
let of_var ctx (Ident.Tvar var) = var |> String.escaped |> Symbol.mk_string ctx
let list_type s ctx = Z3List.mk_sort ctx (Symbol.mk_string ctx "list") s
let array_type t1 t2 ctx = Z3Array.mk_sort ctx t1 t2
let sorts_of_tuple sort = sort |> Tuple.get_mk_decl |> FuncDecl.get_domain
(* from our sort to Z3 sort *)
let str_of_z3_env env =
Set.Poly.fold env ~init:"z3_env:" ~f:(fun ret (dt, sort) ->
ret ^ "\nLogicOld:\n" ^
LogicOld.Datatype.str_of dt ^ "Z3:\n" ^ Z3.Sort.to_string sort ^
List.fold2_exn
(Z3.Datatype.get_constructors sort)
(Z3.Datatype.get_accessors sort)
~init:"" ~f:(fun ret cons sels ->
ret ^ sprintf "\n|%d: %s" (Z3.FuncDecl.get_id cons) (Z3.FuncDecl.to_string cons) ^
List.fold_left sels ~init:"" ~f:(fun ret sel ->
ret ^ "\n>>> " ^ sprintf "%d: %s" (Z3.FuncDecl.get_id sel) (Z3.FuncDecl.to_string sel))) ^
List.fold_left
(Z3.Datatype.get_recognizers sort)
~init:"\ntesters:" ~f:(fun ret iscons ->
ret ^ "\n ?" ^ sprintf "%d: %s" (Z3.FuncDecl.get_id iscons) (Z3.FuncDecl.to_string iscons)))
let rec of_sort ctx dtenv = function
| Sort.SVar (Ident.Svar svar) ->
Z3.Sort.mk_uninterpreted_s ctx @@ unint_svar_prefix ^ svar
| Sort . SArrow ( s1 , ( s2 , Sort . Pure ) ) - >
Z3Array.mk_sort ctx ( of_sort ) ( of_sort s2 )
Z3Array.mk_sort ctx (of_sort ctx dtenv s1) (of_sort ctx dtenv s2)*)
| Sort.SArrow (_, (_, _, _)) as s ->
Z3.Sort.mk_uninterpreted_s ctx (Term.str_of_sort s)
| T_bool.SBool ->
Boolean.mk_sort ctx
| T_int.SInt ->
Arithmetic.Integer.mk_sort ctx
| T_real.SReal ->
Arithmetic.Real.mk_sort ctx
| T_tuple.STuple sorts ->
tuple_sort_of ctx dtenv sorts
| T_dt.SUS (name, []) ->
Z3.Sort.mk_uninterpreted_s ctx name
ToDo
Z3.Sort.mk_uninterpreted_s ctx "unsupported"
Z3.Sort.mk_uninterpreted_s ctx ( name ^ " _ with_args " )
( " ( " ^ ( String.concat_map_list ~sep : " , " params ~f : Term.str_of_sort ) ^ " ) " ^ name )
| T_dt.SDT dt -> begin
match Set.Poly.find dtenv ~f:(fun (dt1, _) ->
Stdlib.(LogicOld.Datatype.full_name_of dt1 = LogicOld.Datatype.full_name_of dt)) with
| Some (_, sort) -> sort
| None ->
Debug.print @@ lazy
(sprintf "[Z3interface.of_sort] %s to %s"
(Term.str_of_sort @@ T_dt.SDT dt) (str_of_z3_env dtenv));
of_sort ctx (update_z3env ctx dtenv dt) (T_dt.SDT dt)
end
| T_array.SArray (si, se) ->
Z3Array.mk_sort ctx (of_sort ctx dtenv si) (of_sort ctx dtenv se)
| T_string.SString -> Z3.Sort.mk_uninterpreted_s ctx unint_string
| T_sequence.SFinSequence -> Z3.Sort.mk_uninterpreted_s ctx unint_finseq
| T_sequence.SInfSequence -> Z3.Sort.mk_uninterpreted_s ctx unint_infseq
| sort ->
failwith @@ sprintf "[Z3interface.of_sort] %s is unknown" @@ LogicOld.Term.str_of_sort sort
and tuple_sort_of ctx dtenv sorts =
let tuple_num = List.length sorts in
Tuple.mk_sort ctx
(Symbol.mk_string ctx @@ sprintf "%s(%s)" unint_tuple_prefix (*tuple_num*) @@
String.concat_map_list ~sep:"," ~f:Term.short_name_of_sort sorts)
(* (tuple_prefix ^ string_of_int tuple_num |> Idnt.make |> sym_of_var) *)
(List.init tuple_num ~f:(fun i -> Symbol.mk_string ctx @@ unint_tuple_sel_prefix ^ string_of_int i))
(List.map sorts ~f:(of_sort ctx dtenv))
and update_z3env ctx dtenv t =
let dts = LogicOld.Datatype.full_dts_of t in
let dt_names, dt_conses =
List.unzip @@
List.map dts ~f:(fun dt ->
LogicOld.Datatype.full_name_of_dt dt,
List.map (LogicOld.Datatype.conses_of_dt dt) ~f:(fun cons ->
let name = LogicOld.Datatype.name_of_cons cons in
Debug.print @@ lazy (sprintf "mk cons:[%s]" name);
let is_cons_name = Z3.Symbol.mk_string ctx @@ unint_is_cons_prefix ^ name in
Debug.print @@ lazy (sprintf "mk is_cons:[%s]" @@ Z3.Symbol.get_string is_cons_name);
let sels_names, ret_sorts, ref_sorts =
List.fold_left (LogicOld.Datatype.sels_of_cons cons) ~init:([], [], [])
~f:(fun (sels_names, ret_sorts, ref_sorts) -> function
| LogicOld.Datatype.Sel (name, ret_sort) ->
Debug.print @@ lazy (sprintf "mk sel:[%s]" name);
Z3.Symbol.mk_string ctx name :: sels_names,
(Some (of_sort ctx dtenv ret_sort)) :: ret_sorts,
0 :: ref_sorts
| LogicOld.Datatype.InSel (name, ret_name, args) ->
Debug.print @@ lazy (sprintf "mk insel:[%s]" name);
let full_name =
List.fold_left args ~init:ret_name
~f:(fun ret arg -> ret ^ LogicOld.Term.str_of_sort arg)
in
match Set.Poly.find dtenv ~f:(fun (dt, _) ->
Stdlib.(full_name = LogicOld.Datatype.full_name_of dt)) with
| Some (_, sort) ->
Z3.Symbol.mk_string ctx name :: sels_names,
(Some sort) :: ret_sorts,
0 :: ref_sorts
| None ->
match List.findi dts ~f:(fun _ dt ->
Stdlib.(LogicOld.Datatype.name_of_dt dt = ret_name)) with
| Some (i, _) ->
(* Debug.print @@ lazy (sprintf "ref id:%d" i); *)
Z3.Symbol.mk_string ctx name :: sels_names,
None :: ret_sorts,
i :: ref_sorts
| _ -> assert false)
in
let z3cons =
Z3.Datatype.mk_constructor ctx
(Z3.Symbol.mk_string ctx name)
is_cons_name
(List.rev sels_names)
(List.rev ret_sorts)
(List.rev ref_sorts)
in
Debug.print @@ lazy ( " z3 tester : " ^ Z3.Datatype . Constructor.get_tester_decl z3cons | > Z3.FuncDecl.to_string ) ;
List.iter ( Z3.Datatype . Constructor.get_accessor_decls z3cons ) ~f:(fun sel - >
Debug.print @@ lazy ( " z3 sel : " ^ ) ) ;
Debug.print @@ lazy ("z3 sel:" ^ Z3.FuncDecl.to_string sel)); *)
z3cons))
in
Z3.Datatype.mk_sorts_s ctx dt_names dt_conses
|> List.fold2_exn dts ~init:dtenv ~f:(fun dtenv dt sort ->
Set.Poly.add dtenv (LogicOld.Datatype.update_name (LogicOld.Datatype.update_dts t dts) @@ LogicOld.Datatype.name_of_dt dt, sort))
and z3_dtenv_of_dtenv ?(init=Set.Poly.empty) ctx dtenv =
Debug.print @@ lazy ( " mk z3 dtenv from:\n " ^ LogicOld . ) ;
let z3_dtenv =
Map.Poly.fold dtenv ~init ~f:(fun ~key:_ ~data env ->
Debug.print @@ lazy ( sprintf " mk sort:%s \n%s " key ( LogicOld . Datatype.str_of data ) ) ;
if Set.Poly.exists env ~f:(fun (dt, _) ->
Stdlib.(LogicOld.Datatype.full_name_of data = LogicOld.Datatype.full_name_of dt))
then env
else update_z3env ctx env data)
in
(* Debug.print @@ lazy (str_of_z3_env z3_dtenv); *)
z3_dtenv
let z3_dtenv_of ?(init=Set.Poly.empty) ctx phi =
LogicOld.update_ref_dtenv @@ LogicOld.DTEnv.of_formula phi;
let dtenv = Atomic.get LogicOld.ref_dtenv in
Debug.print @@ lazy ("[Z3interface.z3_dtenv_of] from:\n" ^ LogicOld.DTEnv.str_of dtenv);
z3_dtenv_of_dtenv ~init ctx dtenv
let z3_dt_of (dtenv:dtenv) dt =
try
snd @@ Set.Poly.find_exn dtenv ~f:(fun (dt1, _) ->
" % s " ( LogicOld . Datatype.full_name_of dt1 ) ;
Stdlib.(LogicOld.Datatype.full_name_of dt = LogicOld.Datatype.full_name_of dt1))
with _ ->
failwith @@ sprintf "[Z3interface.z3_dt_of] %s not found" (LogicOld.Datatype.full_name_of dt)
let z3_cons_of (dtenv:dtenv) dt name =
let z3_conses = Z3.Datatype.get_constructors @@ z3_dt_of dtenv dt in
let conses = Datatype.conses_of dt in
List.find_map_exn (List.zip_exn conses z3_conses) ~f:(fun (cons, z3_cons) ->
if Stdlib.(Datatype.name_of_cons cons = name) then Some z3_cons else None)
let z3_sel_of (dtenv:dtenv) dt name =
let z3_selss = Z3.Datatype.get_accessors @@ z3_dt_of dtenv dt in
let conses = Datatype.conses_of dt in
List.find_map_exn (List.zip_exn conses z3_selss) ~f:(fun (cons, z3_sels) ->
let sels = Datatype.sels_of_cons cons in
List.find_map (List.zip_exn sels z3_sels) ~f:(fun (sel, z3_sel) ->
if Stdlib.(name = Datatype.name_of_sel sel) then Some z3_sel else None))
let z3_iscons_of (dtenv:dtenv) dt name =
let z3_testers = Z3.Datatype.get_recognizers @@ z3_dt_of dtenv dt in
let conses = Datatype.conses_of dt in
List.find_map_exn (List.zip_exn conses z3_testers) ~f:(fun (cons, z3_tester) ->
if Stdlib.(Datatype.name_of_cons cons = name) then Some z3_tester else None)
let z3_string_of ctx str =
FuncDecl.mk_func_decl_s ctx (unint_string_prefix ^ str(*ToDo: need to avoid escaping by z3?*)) [] @@
Z3.Sort.mk_uninterpreted_s ctx unint_string
let z3_epsilon ctx =
FuncDecl.mk_func_decl_s ctx unint_epsilon [] @@
Z3.Sort.mk_uninterpreted_s ctx unint_finseq
let z3_symbol_of ctx str =
FuncDecl.mk_func_decl_s ctx (unint_symbol_prefix ^ str(*ToDo: need to avoid escaping by z3?*)) [] @@
Z3.Sort.mk_uninterpreted_s ctx unint_finseq
let z3_concat ctx fin =
let sort =
if fin then Z3.Sort.mk_uninterpreted_s ctx unint_finseq
else Z3.Sort.mk_uninterpreted_s ctx unint_infseq
in
FuncDecl.mk_func_decl_s ctx (if fin then unint_concat_fin else unint_concat_inf)
[Z3.Sort.mk_uninterpreted_s ctx unint_finseq; sort] sort
let z3_is_prefix_of ctx fin =
FuncDecl.mk_func_decl_s ctx
(if fin then unint_is_prefix_of_fin else unint_is_prefix_of_inf)
[Z3.Sort.mk_uninterpreted_s ctx unint_finseq;
if fin then Z3.Sort.mk_uninterpreted_s ctx unint_finseq
else Z3.Sort.mk_uninterpreted_s ctx unint_infseq]
(Boolean.mk_sort ctx)
let z3_is_in_reg_exp ctx fin regexp =
FuncDecl.mk_func_decl_s ctx
(if fin then unint_is_in_reg_exp_fin_prefix ^ "(" ^ Grammar.RegWordExp.str_of Fn.id regexp ^ ")"
else unint_is_in_reg_exp_inf_prefix ^ "(" ^ Grammar.RegWordExp.str_of Fn.id regexp ^ ")")
[if fin then Z3.Sort.mk_uninterpreted_s ctx unint_finseq
else Z3.Sort.mk_uninterpreted_s ctx unint_infseq]
(Boolean.mk_sort ctx)
let penv_of phi ctx dtenv =
Formula.pred_sort_env_of phi
|> Set.Poly.to_list
|> List.map ~f:(fun (pvar, sorts) ->
pvar,
FuncDecl.mk_func_decl_s ctx
(Ident.name_of_pvar pvar)
(List.map sorts ~f:(of_sort ctx dtenv))
(Boolean.mk_sort ctx))
from our formula to Z3 expr
of_formula : Z3.context - > ( Ident.tvar , Sort.t ) List . Assoc.t - > info Logic . Formula.t
let rec of_formula ctx
(env : sort_env_list)
(penv : (Ident.pvar, FuncDecl.func_decl) List.Assoc.t)
(fenv : fenv)
(dtenv : (LogicOld.Datatype.t *Z3.Sort.sort) Set.Poly.t)
phi =
(* Debug.print @@ lazy ("[Z3interface.of_formula] " ^ Formula.str_of phi); *)
if Formula.is_atom phi then
let atom, _ = Formula.let_atom phi in
if Atom.is_pvar_app atom then
let pvar, sorts, _, _ = Atom.let_pvar_app atom in
(* Debug.print @@ lazy ("is_pvar_app: " ^ Formula.str_of phi); *)
let func =
FuncDecl.mk_func_decl_s ctx
(Ident.name_of_pvar pvar)
(List.map sorts ~f:(of_sort ctx dtenv))
(Boolean.mk_sort ctx)
in
let penv = if not @@ List.Assoc.mem ~equal:Stdlib.(=) penv pvar then (pvar, func) :: penv else penv in
of_atom ctx env penv fenv dtenv atom
else of_atom ctx env penv fenv dtenv atom
else if Formula.is_neg phi then
Boolean.mk_not ctx @@ of_formula ctx env penv fenv dtenv @@ fst (Formula.let_neg phi)
else if Formula.is_and phi then
let phi1, phi2, _ = Formula.let_and phi in
Boolean.mk_and ctx
[of_formula ctx env penv fenv dtenv phi1;
of_formula ctx env penv fenv dtenv phi2]
else if Formula.is_or phi then
let phi1, phi2, _ = Formula.let_or phi in
Boolean.mk_or ctx
[of_formula ctx env penv fenv dtenv phi1;
of_formula ctx env penv fenv dtenv phi2]
else if Formula.is_iff phi then
let phi1, phi2, _ = Formula.let_iff phi in
Boolean.mk_iff ctx
(of_formula ctx env penv fenv dtenv phi1)
(of_formula ctx env penv fenv dtenv phi2)
else if Formula.is_imply phi then
let phi1, phi2, _ = Formula.let_imply phi in
Boolean.mk_implies ctx
(of_formula ctx env penv fenv dtenv phi1)
(of_formula ctx env penv fenv dtenv phi2)
else if Formula.is_bind phi then
let binder, bounds, body, _ = Formula.let_bind phi in
let bounds = List.rev bounds in
let env = bounds @ env in
let sorts = List.map bounds ~f:(fun (_, sort) -> of_sort ctx dtenv sort) in
let vars = List.map bounds ~f:(fun (var, _) -> of_var ctx var) in
let body = of_formula ctx env penv fenv dtenv body in
(match binder with
| Formula.Forall -> Quantifier.mk_forall ctx sorts vars body None [] [] None None
| Formula.Exists -> Quantifier.mk_exists ctx sorts vars body None [] [] None None
| _ -> assert false)
|> Quantifier.expr_of_quantifier
|> (fun e -> add_to_bound_var_cache e; e)
else if Formula.is_letrec phi then
match Formula.let_letrec phi with
| [], phi, _ -> of_formula ctx env penv fenv dtenv phi
| _, _, _ ->
failwith @@ "[Z3interface.of_formula] underlying solver cannot deal with fixpoint predicates: " ^ Formula.str_of phi;
else failwith @@ sprintf "[Z3interface.of_formula] %s not supported: " @@ Formula.str_of phi
and of_var_term ctx env dtenv t =
let (var, sort), _ = Term.let_var t in
Debug.print @@ lazy
( sprintf " z3_of_var_term:%s % s "
( Ident.name_of_tvar var ) ( Term.str_of_sort @@ Term.sort_of t ) ) ;
(sprintf "z3_of_var_term:%s %s"
(Ident.name_of_tvar var) (Term.str_of_sort @@ Term.sort_of t)); *)
match List.findi env ~f:(fun _ (key, _) -> Stdlib.(key = var)) with
| Some (i, (_, sort')) ->
assert Stdlib.(sort = sort');
(* Debug.print @@ lazy ("mk quantifier"); *)
let sort = of_sort ctx dtenv sort in
lock ( ) ; ( fun ret - > unlock ( ) ; ret ) @@
Quantifier.mk_bound ctx i sort
| None ->
find_in_cache ctx env t ~f:(fun cid ->
let name = Ident.name_of_tvar var in
let symbol =
of_var ctx @@
Ident.Tvar (sprintf "%s%s%d%s" name cache_divide_str cid (Term.short_name_of_sort sort))
in
let sort = of_sort ctx dtenv sort in
(* print_endline @@ ("mk const var" ^ (Ident.name_of_tvar var)); *)
Expr.mk_const ctx symbol sort)
from our term to Z3 expr
and of_term ctx
(env : (Ident.tvar, Sort.t) List.Assoc.t)
(penv : (Ident.pvar, FuncDecl.func_decl) List.Assoc.t)
(fenv : fenv)
(dtenv : (LogicOld.Datatype.t * Z3.Sort.sort) Set.Poly.t) t =
Debug.print @@ lazy (sprintf "[Z3interface.of_term] %s" @@ Term.str_of t);
if Term.is_var t then
of_var_term ctx env dtenv t
else if Term.is_app t then
match Term.let_app t with
| T_bool.Formula phi, [], _ ->
of_formula ctx env penv fenv dtenv phi
| T_bool.IfThenElse, [cond; then_; else_], _ ->
Boolean.mk_ite ctx
(of_term ctx env penv fenv dtenv cond)
(of_term ctx env penv fenv dtenv then_)
(of_term ctx env penv fenv dtenv else_)
| T_int.Int n, [], _ ->
find_in_cache ctx env t ~f:(fun _ ->
Arithmetic.Integer.mk_numeral_s ctx (Z.to_string n))
| T_real.Real r, [], _ ->
find_in_cache ctx env t ~f:(fun _ ->
Arithmetic.Real.mk_numeral_s ctx (Q.to_string r))
| (T_int.Add | T_real.RAdd), [t1; t2], _ ->
Arithmetic.mk_add ctx
[of_term ctx env penv fenv dtenv t1;
of_term ctx env penv fenv dtenv t2]
| (T_int.Sub | T_real.RSub), [t1; t2], _ ->
Arithmetic.mk_sub ctx
[of_term ctx env penv fenv dtenv t1;
of_term ctx env penv fenv dtenv t2]
| (T_int.Mult | T_real.RMult), [t1; t2], _ ->
Arithmetic.mk_mul ctx
[of_term ctx env penv fenv dtenv t1;
of_term ctx env penv fenv dtenv t2]
| T_int.Div, [t1; t2], _ ->
Arithmetic.mk_div ctx
(of_term ctx env penv fenv dtenv t1)
(of_term ctx env penv fenv dtenv t2)
| T_int.Mod, [t1; t2], _ ->
Arithmetic.Integer.mk_mod ctx
(of_term ctx env penv fenv dtenv t1)
(of_term ctx env penv fenv dtenv t2)
| T_int.Rem, [t1; t2], _ ->
Arithmetic.Integer.mk_rem ctx
(of_term ctx env penv fenv dtenv t1)
(of_term ctx env penv fenv dtenv t2)
| T_real.RDiv, [t1; t2], _ ->
Arithmetic.mk_div ctx
(Arithmetic.Integer.mk_int2real(*ToDo: remove*) ctx @@
of_term ctx env penv fenv dtenv t1)
(Arithmetic.Integer.mk_int2real(*ToDo: remove*) ctx @@
of_term ctx env penv fenv dtenv t2)
| (T_int.Neg | T_real.RNeg), [t1], _ when Term.is_var t1 || T_int.is_int t1 ->
let n = of_term ctx env penv fenv dtenv t1 in
if T_int.is_int t1 || Expr.is_const n then
find_in_cache ctx env t ~f:(fun _ -> Arithmetic.mk_unary_minus ctx n)
else Arithmetic.mk_unary_minus ctx n
| (T_int.Neg | T_real.RNeg), [t], _ ->
Arithmetic.mk_unary_minus ctx (of_term ctx env penv fenv dtenv t)
| (T_int.Abs | T_real.RAbs) as op, [t], _ ->
let n = of_term ctx env penv fenv dtenv t in
let minus_n = of_term ctx env penv fenv dtenv (T_int.mk_neg t) in
let is_minus =
Arithmetic.mk_lt ctx n
(match op with
| T_int.Abs ->
find_in_cache ctx env (T_int.zero ())
~f:(fun _ -> Arithmetic.Integer.mk_numeral_i ctx 0)
| T_real.RAbs ->
find_in_cache ctx env (T_real.rzero ())
~f:(fun _ -> Arithmetic.Real.mk_numeral_i ctx 0)
| _ -> assert false)
in
Boolean.mk_ite ctx is_minus minus_n n
| (T_int.Power | T_real.RPower), [t1; t2], _ ->
Arithmetic.mk_power ctx
(of_term ctx env penv fenv dtenv t1)
(of_term ctx env penv fenv dtenv t2)
| FVar (var, _), ts, _ when Map.Poly.mem fenv var->
Z3.FuncDecl.apply (Map.Poly.find_exn fenv var) @@
List.map ts ~f:(of_term ctx env penv fenv dtenv)
| FVar (var, sorts), ts, _ ->
let sorts = List.map ~f:(of_sort ctx dtenv) sorts in
let sargs, sret = List.take sorts (List.length sorts - 1), List.last_exn sorts in
Expr.mk_app ctx (FuncDecl.mk_func_decl ctx (of_var ctx var) sargs sret) @@
List.map ~f:(of_term ctx env penv fenv dtenv) ts
| T_real_int.ToReal, [t], _ ->
Arithmetic.Integer.mk_int2real ctx (of_term ctx env penv fenv dtenv t)
| T_real_int.ToInt, [t], _ ->
Arithmetic.Real.mk_real2int ctx (of_term ctx env penv fenv dtenv t)
| T_tuple.TupleSel (sorts, i), [t], _ ->
let sort = of_sort ctx dtenv @@ T_tuple.STuple sorts in
Z3.FuncDecl.apply (List.nth_exn (Tuple.get_field_decls sort) i) @@
[of_term ctx env penv fenv dtenv t]
| T_tuple.TupleCons sorts, ts, _ ->
let sort = of_sort ctx dtenv @@ T_tuple.STuple sorts in
Z3.FuncDecl.apply (Tuple.get_mk_decl sort) @@
List.map ts ~f:(of_term ctx env penv fenv dtenv)
| T_dt.DTCons (name, _tys, dt), ts, _ ->
(*let dt = Datatype.update_args dt tys in*)
Z3.FuncDecl.apply (z3_cons_of dtenv dt name) @@
List.map ts ~f:(of_term ctx env penv fenv dtenv)
| T_dt.DTSel (name, dt, _), ts, _ ->
Z3.FuncDecl.apply (z3_sel_of dtenv dt name) @@
List.map ts ~f:(of_term ctx env penv fenv dtenv)
| T_array.AStore (_si, _se), [t1; t2; t3], _ ->
Z3Array.mk_store ctx
(of_term ctx env penv fenv dtenv t1)
(of_term ctx env penv fenv dtenv t2)
(of_term ctx env penv fenv dtenv t3)
| T_array.ASelect (_si, _se), [t1; t2], _ ->
Z3Array.mk_select ctx
(of_term ctx env penv fenv dtenv t1)
(of_term ctx env penv fenv dtenv t2)
| T_array.AConst (si, _se), [t1], _ ->
Z3Array.mk_const_array ctx
(of_sort ctx dtenv si)
(of_term ctx env penv fenv dtenv t1)
| T_string.StringConst str, [], _ ->
Z3.FuncDecl.apply (z3_string_of ctx str) []
| T_sequence.Epsilon, [], _ ->
Z3.FuncDecl.apply (z3_epsilon ctx) []
| T_sequence.Symbol str, [], _ ->
Z3.FuncDecl.apply (z3_symbol_of ctx str) []
| T_sequence.Concat fin, [t1; t2], _ ->
Z3.FuncDecl.apply (z3_concat ctx fin)
[of_term ctx env penv fenv dtenv t1;
of_term ctx env penv fenv dtenv t2]
| _ -> failwith @@ "[Z3interface.of_term] not supported: " ^ Term.str_of t
else failwith @@ "[Z3interface.of_term] not supported: " ^ Term.str_of t
and
from our atom to Z3 expr
of_atom ctx
(env : (Ident.tvar, Sort.t) List.Assoc.t)
(penv : (Ident.pvar, FuncDecl.func_decl) List.Assoc.t)
(fenv : fenv)
(dtenv : (LogicOld.Datatype.t *Z3.Sort.sort) Set.Poly.t) atom =
Debug.print @@ lazy (sprintf "[Z3interface.of_atom] %s" @@ Atom.str_of atom);
if Atom.is_true atom then
find_in_cache ctx env (T_bool.mk_true ()) ~f:(fun _ -> Boolean.mk_true ctx)
else if Atom.is_false atom then
find_in_cache ctx env (T_bool.mk_false ()) ~f:(fun _ -> Boolean.mk_false ctx)
else if Atom.is_psym_app atom then
let sym, args, _ = Atom.let_psym_app atom in
match sym, List.map ~f:(of_term ctx env penv fenv dtenv) args with
| T_bool.Eq, [t1; t2] ->
Boolean.mk_eq ctx t1 t2
| T_bool.Neq, [t1; t2] ->
Boolean.mk_not ctx @@ Boolean.mk_eq ctx t1 t2
| (T_int.Leq | T_real.RLeq), [t1; t2] ->
Arithmetic.mk_le ctx t1 t2
| (T_int.Geq | T_real.RGeq), [t1; t2] ->
Arithmetic.mk_ge ctx t1 t2
| (T_int.Lt | T_real.RLt), [t1; t2] ->
Arithmetic.mk_lt ctx t1 t2
| (T_int.Gt | T_real.RGt), [t1; t2] ->
Arithmetic.mk_gt ctx t1 t2
| T_int.PDiv, [t1; t2] ->
Boolean.mk_eq ctx
(Arithmetic.Integer.mk_mod ctx t2 t1)
(Arithmetic.Integer.mk_numeral_i ctx 0)
| T_int.NPDiv, [t1; t2] ->
Boolean.mk_not ctx @@
Boolean.mk_eq ctx
(Arithmetic.Integer.mk_mod ctx t2 t1)
(Arithmetic.Integer.mk_numeral_i ctx 0)
| (T_num.NLeq _ | T_num.NGeq _ | T_num.NLt _ | T_num.NGt _), [_t1; _t2] ->
failwith @@ sprintf "[Z3interface.of_atom] polymorphic inequalities not supported: %s" @@
Atom.str_of atom
| T_real_int.IsInt, [t] ->
Arithmetic.Real.mk_is_integer ctx t
| T_tuple.IsTuple _sorts, _ts ->
ToDo
let _ s = tuple_sort_of sorts in
let istuple = failwith " [ Z3interface.of_atom ] is_tuple not supported " in
let istuple = failwith "[Z3interface.of_atom] is_tuple not supported" in
Z3.FuncDecl.apply istuple ts*)
| T_tuple.NotIsTuple _sorts, _ts ->
ToDo
let _ s = tuple_sort_of sorts in
let istuple = failwith " [ Z3interface.of_atom ] is_tuple not supported " in
Boolean.mk_not ctx @@ Z3.FuncDecl.apply istuple ts
let istuple = failwith "[Z3interface.of_atom] is_tuple not supported" in
Boolean.mk_not ctx @@ Z3.FuncDecl.apply istuple ts*)
| T_dt.IsCons (name, dt), ts ->
Z3.FuncDecl.apply (z3_iscons_of dtenv dt name) ts
| T_dt.NotIsCons (name, dt), ts ->
Boolean.mk_not ctx @@
Z3.FuncDecl.apply (z3_iscons_of dtenv dt name) ts
| T_sequence.IsPrefix fin, [t1; t2] ->
Z3.FuncDecl.apply (z3_is_prefix_of ctx fin) [t1; t2]
| T_sequence.NotIsPrefix fin, [t1; t2] ->
Boolean.mk_not ctx @@ Z3.FuncDecl.apply (z3_is_prefix_of ctx fin) [t1; t2]
| T_sequence.InRegExp (fin, regexp), [t1] ->
Z3.FuncDecl.apply (z3_is_in_reg_exp ctx fin regexp) [t1]
| T_sequence.NotInRegExp (fin, regexp), [t1] ->
Boolean.mk_not ctx @@ Z3.FuncDecl.apply (z3_is_in_reg_exp ctx fin regexp) [t1]
| _ -> failwith @@ sprintf "[Z3interface.of_atom] %s not supported: " @@ Atom.str_of atom
else if Atom.is_pvar_app atom then
let pvar, _sargs, args, _ = Atom.let_pvar_app atom in
if List.is_empty args && not @@ List.Assoc.mem ~equal:Stdlib.(=) penv pvar then
of_var_term ctx env dtenv @@
Term.mk_var (Ident.pvar_to_tvar pvar) T_bool.SBool
else
let pred =
match List.Assoc.find ~equal:Stdlib.(=) penv pvar with
| None ->
failwith @@ sprintf "[Z3interface.of_atom] %s not supported: " @@
Ident.name_of_pvar pvar
| Some pred -> pred
in
Expr.mk_app ctx pred @@ List.map args ~f:(of_term ctx env penv fenv dtenv)
else failwith @@ sprintf "[Z3interface.of_atom] %s not supported: " @@ Atom.str_of atom
let z3_fenv_of ?(init=Map.Poly.empty) ctx
(env : (Ident.tvar, Sort.t) List.Assoc.t)
(penv : (Ident.pvar, FuncDecl.func_decl) List.Assoc.t)
(fenv : LogicOld.FunEnv.t)
(dtenv : (LogicOld.Datatype.t * Z3.Sort.sort) Set.Poly.t)
=
let z3_fenv =
Map.Poly.fold fenv ~init ~f:(fun ~key:var ~data:(params, sret, _, _, _) acc ->
if Map.Poly.mem acc var then acc
else
let func =
Z3.FuncDecl.mk_rec_func_decl_s
ctx
(Ident.name_of_tvar var)
(List.map params ~f:(fun (_, s) -> of_sort ctx dtenv s))
(of_sort ctx dtenv sret)
in
Map.Poly.add_exn acc ~key:var ~data:func)
in
Map.Poly.iteri fenv ~f:(fun ~key:var ~data:(params, _, def, _, _) ->
if Map.Poly.mem init var then ()
else
Z3.FuncDecl.add_rec_def
ctx
(Map.Poly.find_exn z3_fenv var)
(List.map params ~f:(fun (v, s) ->
of_term ctx env penv z3_fenv dtenv (Term.mk_var v s)))
(of_term ctx env penv z3_fenv dtenv def));
z3_fenv
let of_formula ctx
(env : (Ident.tvar, Sort.t) List.Assoc.t)
(penv : (Ident.pvar, FuncDecl.func_decl) List.Assoc.t)
(fenv : fenv)
(dtenv : (LogicOld.Datatype.t * Z3.Sort.sort) Set.Poly.t)
phi =
phi
|> Normalizer.normalize_let
(* |> Formula.elim_let *)
|> (fun phi' ->
Debug.print @@ lazy
(sprintf "[z3:of_formula]\n %s\n %s" (Formula.str_of phi) (Formula.str_of phi'));
phi')
|> Formula.equivalent_sat
|> (of_formula ctx env penv fenv dtenv)
let check_sat_z3 solver dtenv phis =
z3_solver_add solver phis;
match Z3.Solver.check solver [] with
| SATISFIABLE ->
(match z3_solver_get_model solver with
| Some model ->
let model = model_of dtenv model in
debug_print_z3_model model ;
`Sat model
| None -> `Unknown "model production is not enabled?")
| UNSATISFIABLE -> `Unsat
| UNKNOWN ->
(match Z3.Solver.get_reason_unknown solver with
| "timeout" | "canceled" -> `Timeout
| reason -> `Unknown reason)
let max_smt_z3 context dtenv hard soft =
let optimizer = Optimize.mk_opt context in
Optimize.add optimizer hard;
Map.Poly.iteri soft ~f:(fun ~key ~data ->
List.iter data ~f:(fun (expr, weight) ->
ignore @@ Optimize.add_soft optimizer expr (string_of_int weight) (Z3.Symbol.mk_string context key)));
match Optimize.check optimizer with
| SATISFIABLE ->
let open Option.Monad_infix in
Optimize.get_model optimizer >>= fun model ->
let num_sat =
Map.Poly.fold soft ~init:0 ~f:(fun ~key:_ ~data sum ->
List.fold data ~init:sum ~f:(fun sum (expr, weight) ->
sum + (match Model.eval model expr true with
| None -> 0 | Some e -> if Boolean.is_true e then weight else 0)))
in
Some (num_sat, model_of dtenv model)
| _ -> None
let check_opt_maximize_z3 context dtenv phis obj =
let optimizer = Optimize.mk_opt context in
Optimize.add optimizer phis;
let handle = Optimize.maximize optimizer obj in
match Optimize.check optimizer with
| SATISFIABLE ->
let open Option.Monad_infix in
Optimize.get_model optimizer >>= fun model ->
let lower = Optimize.get_lower handle |> term_of [] [] dtenv in
let upper = Optimize.get_upper handle |> term_of [] [] dtenv in
Some (lower, upper, model_of dtenv model)
| _ -> None
let get_instance =
let new_instance cfg =
Caml_threads.Mutex.lock mutex;
Gc.full_major ();
let ctx = mk_context cfg in
let solver = Z3.Solver.mk_solver ctx None in
let goal = Z3.Goal.mk_goal ctx false false false in
let dtenv = Set.Poly.empty in
let fenv = Map.Poly.empty in
Caml_threads.Mutex.unlock mutex;
{ ctx; solver; goal; dtenv; fenv; cfg }
in
fun (id:int option) cfg instance_pool ->
if not enable_solver_pool then new_instance cfg
else
match Hashtbl.Poly.find instance_pool (id, cfg) with
| None -> new_instance cfg
| Some instance -> instance
let back_instance ~reset instance_pool id instance =
if enable_solver_pool then begin
reset instance;
Hashtbl.Poly.set instance_pool ~key:(id, instance.cfg) ~data:instance;
end
let check_sat =
let cfg = [ ("model", "true"); ] in
let cfg = if validate then cfg @ validate_cfg else cfg in
fun ?(timeout=None) ~id fenv phis ->
let instance = get_instance id cfg instance_pool in
let ctx, solver = instance.ctx, instance.solver in
instance.dtenv <- (z3_dtenv_of ~init:instance.dtenv ctx @@ Formula.and_of phis);
instance.fenv <- (z3_fenv_of ~init:instance.fenv ctx [] [] fenv instance.dtenv);
debug_print_z3_input phis;
let phis = List.map phis ~f:(FunEnv.defined_formula_of fenv) in
debug_print_z3_input phis;
let phis' = List.map phis ~f:(of_formula ctx [] [] (instance.fenv) (instance.dtenv)) in
(match timeout with
| None -> ()
| Some timeout ->
let params = Z3.Params.mk_params ctx in
Z3.Params.add_int params (Z3.Symbol.mk_string ctx "timeout") timeout;
Z3.Solver.set_parameters solver params);
check_sat_z3 solver (instance.dtenv) phis'
|> (fun ret -> back_instance ~reset:(fun instance -> z3_solver_reset instance.solver) instance_pool id instance; ret)
(** [untrack_phis] will be poped from solver when solving finished *)
let check_sat_unsat_core_main ?(timeout=None) ?(untrack_phis=[]) solver ctx fenv dtenv pvar_clause_map =
(match timeout with
| None ->
let params = Z3.Params.mk_params ctx in
Z3.Params.add_bool params (Z3.Symbol.mk_string ctx "model") true;
Z3.Params.add_bool params (Z3.Symbol.mk_string ctx "unsat_core") true;
Z3.Solver.set_parameters solver params
| Some timeout ->
let params = Z3.Params.mk_params ctx in
Z3.Params.add_bool params (Z3.Symbol.mk_string ctx "model") true;
Z3.Params.add_bool params (Z3.Symbol.mk_string ctx "unsat_core") true;
Z3.Params.add_int params (Z3.Symbol.mk_string ctx "timeout") timeout;
Z3.Solver.set_parameters solver params);
Map.Poly.iteri pvar_clause_map ~f:(fun ~key:name ~data:phi ->
if Formula.is_true phi then ()
else begin
Debug.print @@ lazy (sprintf "assert and track: [%s] %s" name (Formula.str_of phi));
let phi_expr = of_formula ctx [] [] fenv dtenv phi in
let lable =
find_in_cache
~f:(fun _ -> Boolean.mk_const_s ctx name)
ctx []
(Term.mk_var (Tvar name) T_bool.SBool)
in
z3_solver_assert_and_track solver phi_expr lable
end);
Z3.Solver.push solver;
Z3.Solver.add solver (List.map untrack_phis ~f:(of_formula ctx [] [] fenv dtenv));
(fun ret -> Z3.Solver.pop solver 1; ret) @@
match Z3.Solver.check solver [] with
| Z3.Solver.SATISFIABLE ->
(match z3_solver_get_model solver with
| Some model -> `Sat (model_of dtenv model)
| None -> `Unknown "model production is not enabled?")
| UNSATISFIABLE ->
Debug.print @@ lazy "unsat reason:";
let unsat_keys = List.map ~f:Z3.Expr.to_string @@ z3_solver_get_unsat_core solver in
List.iter unsat_keys ~f:(fun unsat_key -> Debug.print @@ lazy (unsat_key));
`Unsat unsat_keys
| UNKNOWN ->
(match Z3.Solver.get_reason_unknown solver with
| "timeout" | "canceled" -> `Timeout
| reason -> `Unknown reason)
(** [untrack_phis] will be poped from solver when solving finished *)
let check_sat_unsat_core_main ?(timeout=None) ?(untrack_phis=[]) solver ctx fenv dtenv pvar_clause_map =
match timeout with
| None ->
check_sat_unsat_core_main ~timeout ~untrack_phis solver ctx fenv dtenv pvar_clause_map
| Some tm ->
if tm = 0 then `Timeout(* times out immediately *) else
Timer.enable_timeout (tm / 1000) Fn.id ignore
(fun () -> check_sat_unsat_core_main ~timeout ~untrack_phis solver ctx fenv dtenv pvar_clause_map)
(fun _ res -> res)
(fun _ -> function Timer.Timeout -> `Timeout | e -> raise e)
let check_sat_unsat_core ?(timeout=None) fenv pvar_clause_map =
let ctx =
let cfg = [ ("model", "true"); ("unsat_core", "true") ] in
let cfg = if validate then cfg @ validate_cfg else cfg in
let cfg =
match timeout with
| None -> cfg
| Some timeout -> cfg @ [("timeout", string_of_int timeout)]
in
mk_context cfg
in
let dtenv = z3_dtenv_of ctx @@ Formula.and_of @@ snd @@ List.unzip @@ Map.Poly.to_alist pvar_clause_map in
let solver = Z3.Solver.mk_solver ctx None in
let fenv = z3_fenv_of ctx [] [] fenv dtenv in
(match timeout with
| None -> ()
| Some timeout ->
let params = Z3.Params.mk_params ctx in
Z3.Params.add_int params (Z3.Symbol.mk_string ctx "timeout") timeout;
Z3.Solver.set_parameters solver params);
check_sat_unsat_core_main ~timeout solver ctx fenv dtenv pvar_clause_map
let max_smt fenv hard soft =
let cfg = [
("MODEL", "true");
(* ("well_sorted_check", "true"); *)
] in
let ctx = mk_context cfg in
let soft_phi = Map.Poly.to_alist soft |> List.unzip |> snd |> List.join |> List.unzip |> fst |> Formula.and_of in
let dtenv = z3_dtenv_of ctx @@ Formula.and_of (soft_phi::hard) in
let hard = List.map hard ~f:(of_formula ctx [] [] fenv dtenv) in
let soft = Map.Poly.map soft ~f:(List.map ~f:(fun (phi, weight) -> of_formula ctx [] [] fenv dtenv phi , weight)) in
max_smt_z3 ctx dtenv hard soft
* ToDo : use instead
let max_smt_of ~id fenv num_ex phis =
let cfg = [("unsat_core", "true")] in
let instance = get_instance id cfg instance_pool in
let ctx = instance.ctx in
instance.dtenv <- z3_dtenv_of ~init:instance.dtenv ctx @@ Formula.and_of phis;
instance.fenv <- (z3_fenv_of ~init:(instance.fenv) ctx [] [] fenv instance.dtenv);
let dtenv = instance.dtenv in
let fenv = instance.fenv in
let solver = instance.solver in
let name_map0 =
List.map phis ~f:(of_formula ctx [] [] fenv dtenv)
|> List.foldi ~init:Map.Poly.empty ~f:(fun i map phi ->
let name = "#S_" ^ (string_of_int i) in
let lable =
find_in_cache
~f:(fun _ -> Boolean.mk_const_s ctx name)
ctx []
(Term.mk_var (Tvar name) T_bool.SBool)
in
Map.Poly.update map lable ~f:(function None -> phi | Some x -> x)) in
let rec inner num_ex models ignored name_map =
if num_ex <= 0 then models
else begin
Map.Poly.iteri name_map ~f:(fun ~key ~data -> z3_solver_assert_and_track solver data key);
z3_solver_reset solver;
match Z3.Solver.check solver [] with
| Z3.Solver.SATISFIABLE ->
(match z3_solver_get_model solver with
| None -> assert false
| Some model ->
let models' = Set.Poly.add models (model_of dtenv model) in
let name_map' = Map.Poly.filter_keys ~f:(Set.Poly.mem ignored) name_map0 in
inner (num_ex - 1) models' Set.Poly.empty name_map')
| UNSATISFIABLE ->
let ucore = List.hd_exn @@ z3_solver_get_unsat_core solver in
inner num_ex models (Set.Poly.add ignored ucore) (Map.Poly.remove name_map ucore)
| UNKNOWN -> assert false
end
in
inner num_ex Set.Poly.empty Set.Poly.empty name_map0
|> (fun ret ->
back_instance ~reset:(fun ins -> z3_solver_reset ins.solver) instance_pool id instance;
ret)
let check_opt_maximize fenv phis obj =
let cfg = [ ("model", "true") ] in
let cfg = if validate then cfg @ validate_cfg else cfg in
let ctx = mk_context cfg in
let dtenv = z3_dtenv_of ctx @@ Formula.and_of phis in
let z3fenv = z3_fenv_of ctx [] [] fenv dtenv in
debug_print_z3_input phis;
let phis = List.map phis ~f:(of_formula ctx [] [] z3fenv dtenv) in
let obj = of_term ctx [] [] (z3_fenv_of ctx [] [] fenv dtenv) dtenv obj in
check_opt_maximize_z3 ctx dtenv phis obj
let check_valid ~id fenv phi =
match check_sat ~id fenv [Formula.negate phi] with
| `Unsat -> `Valid
| `Sat model -> `Invalid model
| res -> res
let is_valid ~id fenv phi = match check_valid ~id fenv phi with `Valid -> true | _ -> false
exception Unknown
let is_valid_exn ~id fenv phi = match check_valid ~id fenv phi with `Valid -> true | `Invalid _ -> false | _ -> raise Unknown
let is_sat ~id fenv phi = match check_sat ~id fenv [phi] with `Sat _ -> true | _ -> false
(** assume that [phi] is alpha-renamed *)
let z3_simplify ~id fenv phi =
let cfg = [("model", "true");] in
let instance = get_instance id cfg instance_pool in
let ctx = instance.ctx in
instance.dtenv <- (z3_dtenv_of ~init:(instance.dtenv) ctx phi);
instance.fenv <- (z3_fenv_of ~init:(instance.fenv) ctx [] [] fenv instance.dtenv);
let dtenv = instance.dtenv in
let fenv = instance.fenv in
let symplify_params = Z3.Params.mk_params @@ ctx in
let penv = penv_of phi ctx dtenv in
let lenv = Map.Poly.to_alist @@ Formula.let_sort_env_of phi in
let tenv = lenv @ (Formula.term_sort_env_of phi |> Set.Poly.to_list) in
Z3.Params.add_bool symplify_params (Z3.Symbol.mk_string ctx "elim_ite") true;
Z3.Params.add_bool symplify_params (Z3.Symbol.mk_string ctx "push_ite_arith") true;
let rec inner = function
| Formula.LetFormula (v, sort, def, body, info) ->
let def' =
if Stdlib.(sort = T_bool.SBool) then
T_bool.of_formula @@ inner @@ Formula.of_bool_term def
else def
in
Formula.LetFormula (v, sort, def', inner body, info)
| phi ->
phi
| > ( fun phi - > print_endline @@ Formula.str_of phi ^ " \n " ; )
|> of_formula ctx tenv penv fenv dtenv
|> (fun phi -> Z3.Expr.simplify phi @@ Some symplify_params)
|> formula_of (List.rev tenv) penv dtenv
|> Evaluator.simplify
| > ( fun phi - > print_endline @@ Formula.str_of phi ^ " \n " ; )
in
let ret = inner phi in
back_instance ~reset:ignore instance_pool id instance;
ret
let qelim ~id fenv phi =
if Formula.is_bind phi then
let _ = Debug.print @@ lazy (sprintf "[Z3interface.qelim] %s" (Formula.str_of phi)) in
let cfg = [ ("model", "true"); ] in
let instance = get_instance id cfg instance_pool in
let ctx = instance.ctx in
let goal = instance.goal in
instance.dtenv <- z3_dtenv_of ~init:instance.dtenv ctx phi;
instance.fenv <- z3_fenv_of ~init:instance.fenv ctx [] [] fenv instance.dtenv;
let symplify_params = Z3.Params.mk_params ctx in
let penv = penv_of phi ctx instance.dtenv in
Z3.Params.add_bool symplify_params (Z3.Symbol.mk_string ctx "elim_ite") true;
let qe_params = Z3.Params.mk_params ctx in
Z3.Params.add_bool qe_params (Z3.Symbol.mk_string ctx "eliminate_variables_as_block") true;
z3_goal_add goal [of_formula ctx [] penv instance.fenv instance.dtenv phi];
let g =
Goal.as_expr @@
Z3.Tactic.ApplyResult.get_subgoal (Z3.Tactic.apply (Z3.Tactic.mk_tactic ctx "qe") goal (Some qe_params)) 0
in
let expr = Z3.Expr.simplify g (Some symplify_params) in
let _ = Debug.print @@ lazy ("quantifier eliminated: " ^ Z3.Expr.to_string expr) in
let phi =
Evaluator.simplify @@ Formula.nnf_of @@
formula_of [] penv instance.dtenv expr
in
back_instance ~reset:(fun ins -> Goal.reset ins.goal) instance_pool id instance;
print_endline @@ " qelim ret : " ^ Formula.str_of phi ;
phi
else phi
let smtlib2_str_of_formula ctx fenv dtenv phi =
Expr.to_string @@
of_formula ctx
(Set.Poly.to_list @@ Formula.term_sort_env_of phi)
(penv_of phi ctx dtenv) fenv dtenv
phi
let expr_cache:(context, (Formula.t, Z3.Expr.expr) Hashtbl.Poly.t) Hashtbl.Poly.t = Hashtbl.Poly.create ()
let find_in_expr_cache ctx phi ~f =
let cache = Hashtbl.Poly.find_or_add expr_cache ctx ~default:(fun _ -> Hashtbl.Poly.create ()) in
Hashtbl.Poly.find_or_add cache phi ~default:(fun _ -> f ())
let expr_of ctx fenv dtenv phi =
find_in_expr_cache ctx phi ~f:(fun _ ->
try of_formula ctx [] [] fenv dtenv @@ Evaluator.simplify phi
with _ -> of_formula ctx [] [] fenv dtenv @@ Formula.mk_true ())
let str_of_asserts_of_solver solver =
"Asserts of solver:" ^
String.concat_map_list ~sep:"\n\t" ~f:Expr.to_string @@ Z3.Solver.get_assertions solver
let check_valid_inc solver phis =
match Z3.Solver.check solver phis with
| SATISFIABLE ->
Debug.print @@ lazy ( sprintf " % s \n check valid - > ( " ( str_of_asserts_of_solver solver ) ) ;
false
| _ ->
Debug.print @@ lazy ( sprintf " % s valid - > ( unsat)valid " ( str_of_asserts_of_solver solver ) ) ;
true
let star and_flag = function
| Formula.Atom (a, _) when Atom.is_pvar_app a -> None
| Formula.UnaryOp (Formula.Not, Formula.Atom (a, _), _) when Atom.is_pvar_app a -> None
| phi -> Some (Evaluator.simplify @@ if and_flag then phi else Formula.negate phi)
let rec simplify_term solver ctx fenv dtenv = function
| Term.FunApp (T_bool.Formula phi, [], info) ->
let phi, has_changed = simplify_formula solver ctx fenv dtenv phi in
T_bool.of_formula ~info phi, has_changed
| Term.FunApp (T_bool.IfThenElse, [t1; t2; t3], info) ->
let t1, has_changed1 = simplify_term solver ctx fenv dtenv t1 in
let t2, has_changed2 = (*ToDo: add t1 to the context*)simplify_term solver ctx fenv dtenv t2 in
let t3, has_changed3 = (*ToDo: add not t1 to the context*)simplify_term solver ctx fenv dtenv t3 in
T_bool.mk_if_then_else ~info t1 t2 t3, has_changed1 || has_changed2 || has_changed3
| t -> t, false
and simplify_atom solver ctx fenv (dtenv:dtenv) atom =
if Atom.is_pvar_app atom then
let pvar, sorts, args, info = Atom.let_pvar_app atom in
let args', _has_changed_list =
List.unzip @@ List.map ~f:(simplify_term solver ctx fenv dtenv) args
in
Atom.mk_pvar_app pvar sorts args' ~info,
List.exists ~f : ident has_changed_list
else
let phi = Formula.mk_atom atom in
(* Debug.print @@ lazy (sprintf "simplify atom: %s" (Formula.str_of phi)); *)
if check_valid_inc solver [expr_of ctx fenv dtenv @@ Formula.negate phi] then
Atom.mk_true (), true
else if check_valid_inc solver [expr_of ctx fenv dtenv @@ phi] then
Atom.mk_false (), true
else atom, false
and check_sub_formulas solver ctx fenv (dtenv:dtenv) and_flag phi =
let cs = Set.Poly.to_list @@ if and_flag then Formula.conjuncts_of phi else Formula.disjuncts_of phi in
Debug.print @@ lazy ( sprintf " Cs : % s " ( String.concat_map_list ~sep:"\n\t " cs ~f : Formula.str_of ) ) ;
Debug.print @@ lazy ( str_of_asserts_of_solver solver ) ;
Z3.Solver.push solver;
let cs', _ , has_changed =
List.fold_left cs ~init:([], List.tl_exn cs, false)
~f:(fun (cs', cs, has_changed) c ->
(* Debug.print @@ lazy (sprintf "c: %s" (Formula.str_of c)); *)
Z3.Solver.push solver;
let exprs =
List.map ~f:(expr_of ctx fenv dtenv) @@
List.filter_map cs ~f:(star and_flag)
in
z3_solver_add solver exprs;
Debug.print @@ lazy ( str_of_asserts_of_solver solver ) ;
let c', has_changed' = simplify_formula solver ctx fenv dtenv c in
Z3.Solver.pop solver 1;
(* Debug.print @@ lazy (sprintf "c': %s" (Formula.str_of c')); *)
(match star and_flag c' with
| Some phi -> z3_solver_add solver [expr_of ctx fenv dtenv phi] | None -> ());
(c' :: cs'), (match cs with | _::tl -> tl | _ -> []),
has_changed || has_changed') in
Z3.Solver.pop solver 1;
let cs' = List.rev cs' in
Debug.print @@ lazy ( sprintf " compare Cs to Cs':\nCs : % s " ( String.concat_map_list ~sep:"\n\t " cs ~f : Formula.str_of ) ) ;
Debug.print @@ lazy ( sprintf " Cs ' : % s " ( String.concat_map_list ~sep:"\n\t " cs ' ~f : Formula.str_of ) ) ;
let ret = Evaluator.simplify @@ if and_flag then Formula.and_of cs' else Formula.or_of cs' in
if has_changed then begin
(* Debug.print @@ lazy ("has changed."); *)
fst @@ check_sub_formulas solver ctx fenv dtenv and_flag ret, true
end else ret, false
and simplify_formula solver ctx fenv (dtenv:dtenv) phi =
(* Debug.print @@ lazy (sprintf "[Z3interface.simplify_formula] %s" (Formula.str_of phi) ); *)
Debug.print @@ lazy ( str_of_asserts_of_solver solver ) ;
match phi with
| Formula.Atom (atom, _) when not (Atom.is_true atom || Atom.is_false atom) ->
let atom, has_changed = simplify_atom solver ctx fenv dtenv atom in
Formula.mk_atom atom, has_changed
| Formula.UnaryOp (Not, Atom (atom, _), _)
when not (Atom.is_true atom || Atom.is_false atom) ->
let atom, has_changed = simplify_atom solver ctx fenv dtenv atom in
Formula.negate (Formula.mk_atom atom), has_changed
| Formula.BinaryOp (And, _, _, _) -> check_sub_formulas solver ctx fenv dtenv true phi
| Formula.BinaryOp (Or, _, _, _) -> check_sub_formulas solver ctx fenv dtenv false phi
| Formula.LetFormula (var, sort, def, body, info) ->
let def, _ = simplify_term solver ctx fenv dtenv def in
let body, has_changed = simplify_formula solver ctx fenv dtenv body in
Formula.LetFormula (var, sort, def, body, info), has_changed
| _ -> phi, false
and simplify ?(timeout=None) ~id fenv phi =
Debug.print @@ lazy ("===========simplify start=============");
Debug.print @@ lazy (sprintf "the formula:\n %s" @@ Formula.str_of phi);
let cfg = ["model", "true"] in
let instance = get_instance id cfg instance_pool in
let ctx, solver = instance.ctx, instance.solver in
instance.dtenv <- (z3_dtenv_of ~init:(instance.dtenv) ctx phi);
instance.fenv <- (z3_fenv_of ~init:(instance.fenv) ctx [] [] fenv instance.dtenv);
Debug.print @@ lazy ( sprintf " the smtlib2 formua:\n\t%s " @@ ) ;
(* let solver = Z3.Solver.mk_solver ctx None in *)
(match timeout with
| None -> ()
| Some timeout ->
let params = Z3.Params.mk_params ctx in
Z3.Params.add_int params (Z3.Symbol.mk_string ctx "timeout") timeout;
Z3.Solver.set_parameters solver params);
let phi = Normalizer.normalize_let phi in
let ret =
z3_simplify ~id fenv @@
fst @@ simplify_formula solver ctx instance.fenv instance.dtenv @@
z3_simplify ~id fenv @@
Formula.nnf_of phi
in
Debug.print @@ lazy (sprintf "result:\n %s\n===========simplify end=============" @@ Formula.str_of ret);
back_instance ~reset:(fun instance -> z3_solver_reset instance.solver) instance_pool id instance;
ret
let of_formula_with_z3fenv = of_formula
let of_formula ctx env penv fenv dtenv phi = (** For external calls *)
of_formula ctx env penv (z3_fenv_of ctx env penv fenv dtenv) dtenv phi
| null |
https://raw.githubusercontent.com/hiroshi-unno/coar/90a23a09332c68f380efd4115b3f6fdc825f413d/lib/Z3Smt/z3interface.ml
|
ocaml
|
let _ = Z3.set_global_param "smt.macro_finder" "true"
Hashtbl.Poly.clear cache;
* decoding
Debug.print @@ lazy (sprintf "look_up_func:%d :%s" (Z3.FuncDecl.get_id func) (Z3.FuncDecl.to_string func));
Debug.print @@ lazy (sprintf "search_sel %d =? %d :%s" id (Z3.FuncDecl.get_id z3_sel) (Z3.FuncDecl.to_string z3_sel));
term_of: (Ident.tvar, Sort.t) List.Assoc.t -> (Ident.pvar, FuncDecl.func_decl) List.Assoc.t -> Z3.Expr.expr -> info Logic.term
try
bound variables
applications (and constants)
algebraic data types
tuples
ToDo: Z3 automatically generates a tester of the name
sorts @ [sort]
bound variables
assume bool
Debug.print @@ lazy ("[Z3interface.formula_of] " ^ Z3.Expr.to_string expr);
* encoding
from our sort to Z3 sort
tuple_num
(tuple_prefix ^ string_of_int tuple_num |> Idnt.make |> sym_of_var)
Debug.print @@ lazy (sprintf "ref id:%d" i);
Debug.print @@ lazy (str_of_z3_env z3_dtenv);
ToDo: need to avoid escaping by z3?
ToDo: need to avoid escaping by z3?
Debug.print @@ lazy ("[Z3interface.of_formula] " ^ Formula.str_of phi);
Debug.print @@ lazy ("is_pvar_app: " ^ Formula.str_of phi);
Debug.print @@ lazy ("mk quantifier");
print_endline @@ ("mk const var" ^ (Ident.name_of_tvar var));
ToDo: remove
ToDo: remove
let dt = Datatype.update_args dt tys in
|> Formula.elim_let
* [untrack_phis] will be poped from solver when solving finished
* [untrack_phis] will be poped from solver when solving finished
times out immediately
("well_sorted_check", "true");
* assume that [phi] is alpha-renamed
ToDo: add t1 to the context
ToDo: add not t1 to the context
Debug.print @@ lazy (sprintf "simplify atom: %s" (Formula.str_of phi));
Debug.print @@ lazy (sprintf "c: %s" (Formula.str_of c));
Debug.print @@ lazy (sprintf "c': %s" (Formula.str_of c'));
Debug.print @@ lazy ("has changed.");
Debug.print @@ lazy (sprintf "[Z3interface.simplify_formula] %s" (Formula.str_of phi) );
let solver = Z3.Solver.mk_solver ctx None in
* For external calls
|
open Core
open Z3
open Common
open Common.Ext
open Ast
open Ast.LogicOld
let verbose = false
module Debug = Debug.Make (val Debug.Config.(if verbose then enable else disable))
let validate = false
let validate_cfg = [ ("model_validate", "true"); ("well_sorted_check", "true") ]
let mutex = Caml_threads.Mutex.create ()
let enable_mutex = false
let lock () = if enable_mutex then Caml_threads.Mutex.lock mutex
let unlock () = if enable_mutex then Caml_threads.Mutex.unlock mutex
let full_major () = if enable_mutex then Gc.full_major ()
let enable_solver_pool = true
type dtenv = (LogicOld.Datatype.t * Z3.Sort.sort) Set.Poly.t
type fenv = (Ident.tvar, Z3.FuncDecl.func_decl) Map.Poly.t
type instance = {
ctx : context;
solver : Z3.Solver.solver;
goal : Goal.goal;
cfg : (string * string) list;
mutable dtenv : dtenv;
mutable fenv : fenv;
}
let instance_pool = Hashtbl.Poly.create ()
let cache_divide_str = "__separator__"
let cache_id = Atomic.make 0
let term_cache: (context * ((Ident.tvar, Sort.t) List.Assoc.t), int * (Term.t, Expr.expr) Hashtbl.Poly.t) Hashtbl.Poly.t = Hashtbl.Poly.create ()
let bound_var_cache : (Expr.expr list) Atomic.t = Atomic.make []
let add_to_bound_var_cache e =
lock ();
Atomic.set bound_var_cache @@ e::(Atomic.get bound_var_cache);
unlock ()
let find_in_cache ~f ctx env t =
let cid, cache =
Hashtbl.Poly.find_or_add term_cache (ctx, env) ~default:(fun _ ->
Atomic.incr cache_id; Atomic.get cache_id, Hashtbl.Poly.create ())
in
Hashtbl.Poly.find_or_add cache t ~default:(fun _ ->
Debug.print @@ lazy ("not found: " ^ Term.str_of t);
lock ( ) ; ( fun ret - > unlock ( ) ; ret ) @@
f cid)
let clean () =
Hashtbl.Poly.clear instance_pool
let z3_solver_reset solver =
lock ( ) ; ( fun ret - > unlock ( ) ; ret ) @@
Z3.Solver.reset solver
let z3_solver_add solver exprs =
lock ( ) ; ( fun ret - > unlock ( ) ; ret ) @@
Z3.Solver.add solver exprs
let z3_goal_add goal exprs =
lock ( ) ; ( fun ret - > unlock ( ) ; ret ) @@
Z3.Goal.add goal exprs
let z3_solver_get_model solver =
lock ( ) ; ( fun ret - > unlock ( ) ; ret )
Z3.Solver.get_model solver
let z3_solver_get_unsat_core solver =
lock ( ) ; ( fun ret - > unlock ( ) ; ret )
Z3.Solver.get_unsat_core solver
let z3_solver_assert_and_track solver e1 e2=
lock ( ) ; ( fun ret - > unlock ( ) ; ret )
Z3.Solver.assert_and_track solver e1 e2
let debug_print_z3_input phis =
Debug.print @@ lazy "Z3 input formulas :";
List.iter phis ~f:(fun phi -> Debug.print @@ lazy (Formula.str_of phi))
let debug_print_z3_model model =
Debug.print @@ lazy ("Z3 output model :" ^ LogicOld.str_of_model model)
let unint_svar_prefix = "#svar_"
let unint_is_cons_prefix = "#is_"
let unint_tuple_prefix = "#tuple"
let unint_tuple_sel_prefix = "#t_sel."
let unint_string_prefix = "#string_"
let unint_epsilon = "#epsilon"
let unint_symbol_prefix = "#symbol_"
let unint_concat_fin = "#concat_fin"
let unint_concat_inf = "#concat_inf"
let unint_is_prefix_of_fin = "#is_prefix_of_fin"
let unint_is_prefix_of_inf = "#is_prefix_of_inf"
let unint_is_in_reg_exp_fin_prefix = "#is_in_reg_exp_fin"
let unint_is_in_reg_exp_inf_prefix = "#is_in_reg_exp_inf"
let unint_string = "#string"
let unint_finseq = "#fin_seq"
let unint_infseq = "#inf_seq"
let unescape_z3 = String.substr_replace_all ~pattern:"|" ~with_:""
let rec sort_of env s =
match Z3.Sort.get_sort_kind s with
| Z3enums.BOOL_SORT -> T_bool.SBool
| Z3enums.INT_SORT -> T_int.SInt
| Z3enums.REAL_SORT -> T_real.SReal
| Z3enums.DATATYPE_SORT -> begin
match Set.Poly.find env ~f:(fun (_, sort) -> Stdlib.(s = sort)) with
| Some (dt, _) -> LogicOld.T_dt.SDT dt
| _ ->
if String.is_prefix ~prefix:unint_tuple_prefix @@ unescape_z3 @@ Z3.Sort.to_string s then
let sorts = List.map ~f:(fun sel -> sort_of env @@ FuncDecl.get_range sel) @@ Tuple.get_field_decls s in
T_tuple.STuple sorts
else failwith @@ "[Z3interface.sort_of] unknown dt type:" ^ Z3.Sort.to_string s
end
| Z3enums.ARRAY_SORT ->
T_array.SArray (sort_of env @@ Z3Array.get_domain s, sort_of env @@ Z3Array.get_range s)
| Z3enums.UNINTERPRETED_SORT ->
let name = Symbol.get_string @@ Z3.Sort.get_name s in
if String.is_prefix ~prefix:unint_svar_prefix name then
let svar = String.sub name ~pos:(String.length unint_svar_prefix) ~len:(String.length name - String.length unint_svar_prefix) in
Sort.SVar (Ident.Svar svar)
else if String.(name = unint_string) then T_string.SString
else if String.(name = unint_finseq) then T_sequence.SFinSequence
else if String.(name = unint_infseq) then T_sequence.SInfSequence
else T_dt.SUS (name, [])
ToDo : implement other cases
failwith @@ "[Z3interface.sort_of] unknown type:" ^ Z3.Sort.to_string s
let look_up_func_of_dt dt sort func =
let id = Z3.FuncDecl.get_id func in
let conses = Datatype.conses_of dt in
let z3_conses = Z3.Datatype.get_constructors sort in
let z3_testers = Z3.Datatype.get_recognizers sort in
let z3_selss = Z3.Datatype.get_accessors sort in
let z3_funcs = List.zip3_exn z3_conses z3_testers z3_selss in
List.fold2_exn conses z3_funcs ~init:`Unkonwn ~f:(fun ret cons (z3_cons, z3_tester, z3_sels) ->
match ret with
|`Unkonwn ->
if id = FuncDecl.get_id z3_cons then `Cons cons
else if id = FuncDecl.get_id z3_tester then `IsCons cons
else
List.fold2_exn (LogicOld.Datatype.sels_of_cons cons) z3_sels ~init:ret ~f:(fun ret sel z3_sel ->
match ret with
| `Unkonwn -> if id = FuncDecl.get_id z3_sel then `Sel sel else ret
| _ -> ret)
| _ -> ret)
let look_up_func dtenv func =
Set.Poly.find_map dtenv ~f:(fun (dt, sort) ->
match look_up_func_of_dt dt sort func with
| `Unkonwn -> None
| ret -> Some (dt, ret))
let rec parse_term = function
| Sexp.Atom "x" ->
Term.mk_var (Ident.Tvar "x") T_real.SReal
| Sexp.Atom ident -> begin
try T_int.mk_int (Z.of_string ident) with _ ->
try T_real.mk_real (Q.of_string ident) with _ ->
failwith "[Z3interface.parse_term]"
end
| Sexp.List [Sexp.Atom "-"; t] ->
ToDo
| Sexp.List (Sexp.Atom "+" :: arg :: args) ->
ToDo
| Sexp.List (Sexp.Atom "*" :: arg :: args) ->
ToDo
| Sexp.List [Sexp.Atom "^"; t1; t2] ->
ToDo
| _ -> failwith "[Z3interface.parse_term]"
let parse_root_obj = function
| Sexp.List [Sexp.Atom "root-obj"; t; n] ->
let t = parse_term t in t, (int_of_string @@ Sexp.to_string n)
| e -> failwith @@ "[Z3interface.parse_root_obj]" ^ Sexp.to_string e ^ " is not root-obj"
let var_of s =
Scanf.unescaped @@ (try Scanf.sscanf s "|%s@|" Fn.id with _ -> s)
|> Str.split (Str.regexp cache_divide_str)
|> List.hd_exn
let rec apply senv penv dtenv op expr =
match List.map ~f:(term_of senv penv dtenv) @@ Expr.get_args expr with
| e :: es -> List.fold ~init:e es ~f:op
| _ -> assert false
and apply_bop senv penv dtenv op expr =
match Expr.get_args expr with
| [e1; e2] -> op (term_of senv penv dtenv e1) (term_of senv penv dtenv e2)
| _ -> assert false
and apply_brel senv penv dtenv op expr =
match Expr.get_args expr with
| [e1; e2] -> op (term_of senv penv dtenv e1) (term_of senv penv dtenv e2)
| _ -> assert false
from Z3 expr to our term
Debug.print @@ lazy ("[Z3interface.term_of] " ^ Z3.Expr.to_string expr);
if Boolean.is_true expr then
T_bool.of_atom @@ Atom.mk_true ()
else if Boolean.is_false expr then
T_bool.of_atom @@ Atom.mk_false ()
else if Boolean.is_ite expr then
match Expr.get_args expr with
| [e1; e2; e3] ->
T_bool.ifte (formula_of senv penv dtenv e1) (term_of senv penv dtenv e2) (term_of senv penv dtenv e3)
| _ -> assert false
else if Arithmetic.is_int_numeral expr then
T_int.mk_int (Arithmetic.Integer.get_big_int expr)
else if Arithmetic.is_rat_numeral expr then
T_real.mk_real (Arithmetic.Real.get_ratio expr)
else if Arithmetic.is_algebraic_number expr then
let expr = Sexp.of_string @@ Expr.to_string expr in
let t, n = parse_root_obj expr in
T_real.mk_alge t n
else if Arithmetic.is_add expr then
match sort_of dtenv @@ Expr.get_sort expr with
| T_int.SInt -> apply senv penv dtenv T_int.mk_add expr
| T_real.SReal -> apply senv penv dtenv T_real.mk_radd expr
| _ -> failwith @@ "[Z3interface.term_of]" ^ Z3.Sort.to_string @@ Expr.get_sort expr
else if Arithmetic.is_sub expr then
match sort_of dtenv @@ Expr.get_sort expr with
| T_int.SInt -> apply senv penv dtenv T_int.mk_sub expr
| T_real.SReal -> apply senv penv dtenv T_real.mk_rsub expr
| _ -> failwith @@ "[Z3interface.term_of]" ^ Z3.Sort.to_string @@ Expr.get_sort expr
else if Arithmetic.is_mul expr then
match sort_of dtenv @@ Expr.get_sort expr with
| T_int.SInt -> apply senv penv dtenv T_int.mk_mult expr
| T_real.SReal -> apply senv penv dtenv T_real.mk_rmult expr
| _ -> failwith @@ "[Z3interface.term_of]" ^ Z3.Sort.to_string @@ Expr.get_sort expr
else if Arithmetic.is_idiv expr then
apply_bop senv penv dtenv T_int.mk_div expr
else if Arithmetic.is_div expr then
apply_bop senv penv dtenv T_real.mk_rdiv expr
else if Arithmetic.is_modulus expr then
apply_bop senv penv dtenv T_int.mk_mod expr
else if Arithmetic.is_remainder expr then
apply_bop senv penv dtenv T_int.mk_rem expr
let _ = Debug.print @@ lazy ("z3 bound var: " ^ Expr.to_string expr) in
try
let tvar, sort =
List.nth_exn senv @@
List.length senv - Scanf.sscanf (Expr.to_string expr) "(:var %d)" Fn.id - 1
in
Term.mk_var tvar sort
with _ -> failwith @@ "[Z3interface.term_of] " ^ Expr.to_string expr ^ " not found"
else if Z3Array.is_store expr then
let sa = sort_of dtenv @@ Expr.get_sort expr in
match List.map ~f:(term_of senv penv dtenv) @@ Expr.get_args expr, sa with
| [t1; t2; t3], T_array.SArray (s1, s2) -> T_array.mk_store s1 s2 t1 t2 t3
| _ -> failwith "[Z3interface.term_of]"
else if Z3Array.is_constant_array expr then
let sa = sort_of dtenv @@ Expr.get_sort expr in
match List.map ~f:(term_of senv penv dtenv) @@ Expr.get_args expr, sa with
| [t1], T_array.SArray (s1, s2) -> T_array.mk_const_array s1 s2 t1
| _ -> failwith "[Z3interface.term_of]"
else if Z3Array.is_select expr then
let args = Expr.get_args expr in
match args, List.map ~f:(term_of senv penv dtenv) args with
| [e1; _e2], [t1; t2] -> begin
match T_array.eval_select t1 t2, sort_of dtenv @@ Expr.get_sort e1 with
| Some te, _ -> te
| _, T_array.SArray (s1, s2) -> T_array.mk_select s1 s2 t1 t2
| _ -> failwith "[Z3interface.term_of]"
end
| _ -> failwith "[Z3interface.term_of]"
try
let func = Z3.Expr.get_func_decl expr in
let name =
FuncDecl.get_name func
|> Symbol.get_string
|> unescape_z3
|> Str.split (Str.regexp cache_divide_str)
|> List.hd_exn
in
let ts = List.map ~f:(term_of senv penv dtenv) @@ Z3.Expr.get_args expr in
let sorts = List.map ~f:Term.sort_of ts in
the following causes an exception if [ expr ] contains a bound variable :
let sorts = List.map ~f:(fun e - > sort_of dtenv @@ Expr.get_sort e ) @@ Z3.Expr.get_args expr in
let sorts = List.map ~f:(fun e -> sort_of dtenv @@ Expr.get_sort e) @@ Z3.Expr.get_args expr in *)
let sort = sort_of dtenv @@ FuncDecl.get_range func in
Debug.print @@ lazy (sprintf "[Z3interface.term_of] %s" @@ Z3.Expr.to_string expr);
match look_up_func dtenv func with
| Some (dt, `Cons cons) ->
T_dt.mk_cons dt (Datatype.name_of_cons cons) ts
| Some (dt, `IsCons cons) ->
T_bool.of_atom @@ T_dt.mk_is_cons dt (Datatype.name_of_cons cons) @@ List.hd_exn ts
| Some (dt, `Sel sel) ->
T_dt.mk_sel dt (Datatype.name_of_sel sel) @@ List.hd_exn ts
| None when T_dt.is_sdt sort && List.is_empty ts ->
Term.mk_var (Ident.Tvar name) sort
| _ -> failwith "[Z3interface.term_of] not an ADT term"
with _ ->
if String.is_prefix ~prefix:unint_tuple_prefix name then
T_tuple.mk_tuple_cons sorts ts
else if String.is_prefix ~prefix:unint_tuple_sel_prefix name && List.length ts = 1 then
let pre_length = String.length unint_tuple_sel_prefix in
let i = Int.of_string @@ String.sub name ~pos:pre_length ~len:(String.length name - pre_length) in
match ts, sorts with
| [t], [T_tuple.STuple sorts] -> T_tuple.mk_tuple_sel sorts t i
| _ -> failwith "[Z3interface.term_of] not a valid tuple/string/sequence term"
match ts, sorts with
| [_t], [T_tuple.STuple _sorts] ->
T_bool.of_atom @@ T_tuple.mk_is_tuple sorts t
| _ -> failwith "[Z3interface.term_of] not a valid tuple/string/sequence term"
else if String.is_prefix ~prefix:unint_string_prefix name && List.is_empty ts then
let pre_length = String.length unint_string_prefix in
let str = String.sub name ~pos:pre_length ~len:(String.length name - pre_length) in
T_string.mk_string_const str
else if String.(name = unint_epsilon) && List.is_empty ts then
T_sequence.mk_eps ()
else if String.is_prefix ~prefix:unint_symbol_prefix name && List.is_empty ts then
let pre_length = String.length unint_symbol_prefix in
let symbol = String.sub name ~pos:pre_length ~len:(String.length name - pre_length) in
T_sequence.mk_symbol symbol
else if String.(name = unint_concat_fin) then
match ts with
| [t1; t2] -> T_sequence.concat ~fin:true t1 t2
| _ -> failwith "[Z3interface.term_of] not a valid tuple/string/sequence term"
else if String.(name = unint_concat_inf) && List.length ts = 2 then
match ts with
| [t1; t2] -> T_sequence.concat ~fin:false t1 t2
| _ -> failwith "[Z3interface.term_of] not a valid tuple/string/sequence term"
else if String.is_prefix ~prefix:unint_is_prefix_of_fin name then
match ts with
| [t1; t2] -> T_bool.of_atom @@ T_sequence.mk_is_prefix true t1 t2
| _ -> failwith "[Z3interface.term_of] not a valid tuple/string/sequence term"
else if String.is_prefix ~prefix:unint_is_prefix_of_inf name && List.length ts = 2 then
match ts with
| [t1; t2] -> T_bool.of_atom @@ T_sequence.mk_is_prefix false t1 t2
| _ -> failwith "[Z3interface.term_of] not a valid tuple/string/sequence term"
else if String.is_prefix ~prefix:unint_is_in_reg_exp_fin_prefix name then
let regexp = failwith "not supported" in
match ts with
| [t] -> T_bool.of_atom @@ T_sequence.mk_is_in_regexp true regexp t
| _ -> failwith "[Z3interface.term_of] not a valid tuple/string/sequence term"
else if String.is_prefix ~prefix:unint_is_in_reg_exp_inf_prefix name then
let regexp = failwith "not supported" in
match ts with
| [t] -> T_bool.of_atom @@ T_sequence.mk_is_in_regexp false regexp t
| _ -> failwith "[Z3interface.term_of] not a valid tuple/string/sequence term"
else failwith "[Z3interface.term_of] not a tuple/string/sequence term"
with _ ->
match Map.Poly.find (Atomic.get ref_fenv) (Ident.Tvar name) with
| Some (params, ret_sort, _, _, _) ->
| _ ->
ToDo
match sort_of dtenv @@ Expr.get_sort expr with
| T_bool.SBool -> T_bool.of_formula @@ formula_of senv penv dtenv expr
| _ -> failwith "[Z3interface.term_of] not a formula"
with _ ->
if List.is_empty ts then Term.mk_var (Ident.Tvar name) sort
else LogicOld.Term.mk_fvar_app (Ident.Tvar name) (sorts @ [sort]) ts
with Failure err ->
match sort_of dtenv @@ Expr.get_sort expr with
| T_bool.SBool -> T_bool.of_formula @@ formula_of senv penv dtenv expr
| _ -> failwith @@ sprintf "[Z3interface.term_of] %s : %s" err @@ Z3.Expr.to_string expr
and
from Z3 expr to our atom
atom_of : ( Ident.tvar , Sort.t ) List . Assoc.t - > ( Ident.pvar , FuncDecl.func_decl ) List . Assoc.t - > Z3.Expr.expr - > info Logic . Atom.t
atom_of
(senv : (Ident.tvar, Sort.t) List.Assoc.t)
(penv : (Ident.pvar, FuncDecl.func_decl) List.Assoc.t)
(dtenv : dtenv)
expr =
Debug.print @@ lazy ( " [ z3 : atom_of ] " ^ Z3.Expr.to_string expr ) ;
if Boolean.is_true expr then
Atom.mk_true ()
else if Boolean.is_false expr then
Atom.mk_false ()
else if Boolean.is_eq expr then
apply_brel senv penv dtenv T_bool.mk_eq expr
else if Arithmetic.is_le expr then
Typeinf.typeinf_atom @@ apply_brel senv penv dtenv T_num.mk_nleq expr
else if Arithmetic.is_ge expr then
Typeinf.typeinf_atom @@ apply_brel senv penv dtenv T_num.mk_ngeq expr
else if Arithmetic.is_lt expr then
Typeinf.typeinf_atom @@ apply_brel senv penv dtenv T_num.mk_nlt expr
else if Arithmetic.is_gt expr then
Typeinf.typeinf_atom @@ apply_brel senv penv dtenv T_num.mk_ngt expr
List.nth_exn senv @@
List.length senv - Scanf.sscanf (Expr.to_string expr) "(:var %d)" Fn.id - 1
in
match List.Assoc.find ~equal:Stdlib.(=) penv (Ident.tvar_to_pvar tvar) with
| Some _ -> Atom.mk_pvar_app (Ident.tvar_to_pvar tvar) [] []
| _ -> Atom.of_bool_term @@ Term.mk_var tvar T_bool.SBool
else
let func = Z3.Expr.get_func_decl expr in
let name =
FuncDecl.get_name func
|> Symbol.get_string
|> unescape_z3
|> Str.split (Str.regexp cache_divide_str)
|> List.hd_exn
in
let pvar = Ident.Pvar name in
let ts = List.map ~f:(term_of senv penv dtenv) @@ Z3.Expr.get_args expr in
match List.Assoc.find ~equal:Stdlib.(=) penv pvar with
| Some _ -> Atom.mk_pvar_app pvar (List.map ts ~f:Term.sort_of) ts
| None ->
try Atom.of_bool_term @@ term_of senv penv dtenv expr with _ ->
failwith @@ "[Z3interface.atom_of] " ^ Z3.Expr.to_string expr
and
from Z3 expr to our formula
formula_of : ( Ident.tvar , Sort.t ) List . Assoc.t - > ( Ident.pvar , FuncDecl.func_decl ) List . Assoc.t - > Z3.Expr.expr - > info Logic . Formula.t
formula_of
(senv : (Ident.tvar, Sort.t) List.Assoc.t)
(penv : (Ident.pvar, FuncDecl.func_decl) List.Assoc.t)
(dtenv : dtenv)
expr =
if Boolean.is_not expr then
match Expr.get_args expr with
| [body] -> Formula.negate (formula_of senv penv dtenv body)
| _ -> failwith "[Z3interface.formula_of]"
else if Boolean.is_and expr then
Formula.and_of @@ List.map ~f:(formula_of senv penv dtenv) @@ Expr.get_args expr
else if Boolean.is_or expr then
Formula.or_of @@ List.map ~f:(formula_of senv penv dtenv) @@ Expr.get_args expr
else if Boolean.is_iff expr then
Expr.get_args expr
|> List.map ~f:(formula_of senv penv dtenv)
|> function [phi1; phi2] -> Formula.mk_iff phi1 phi2
| _ -> failwith "[Z3interface.formula_of]"
else if Boolean.is_implies expr then
Expr.get_args expr
|> List.map ~f:(formula_of senv penv dtenv)
|> function [phi1; phi2] -> Formula.mk_imply phi1 phi2
| _ -> failwith "[Z3interface.formula_of]"
else if Boolean.is_ite expr then
match Expr.get_args expr with
| [e1; e2; e3] ->
Formula.of_bool_term @@
T_bool.ifte (formula_of senv penv dtenv e1) (term_of senv penv dtenv e2) (term_of senv penv dtenv e3)
| _ -> failwith "[Z3interface.formula_of]"
else if AST.is_quantifier @@ Expr.ast_of_expr expr then
let q = Quantifier.quantifier_of_expr expr in
let binder = if Quantifier.is_universal q then Formula.Forall else Formula.Exists in
let bounds =
List.zip_exn
(List.map ~f:(fun x -> Ident.Tvar (Symbol.get_string x)) @@
Quantifier.get_bound_variable_names q)
(List.map ~f:(sort_of dtenv) @@ Quantifier.get_bound_variable_sorts q)
in
let senv = bounds @ senv in
Formula.mk_bind binder bounds @@
formula_of senv penv dtenv @@ Quantifier.get_body q
else Formula.mk_atom @@ atom_of senv penv dtenv expr
let dummy_term_map_of terms =
Map.of_set_exn @@ Set.Poly.filter_map terms ~f:(function (tvar, (T_dt.SUS _ as sort)) ->
Some (tvar, mk_fresh_dummy_term sort) | _ -> None)
let add_dummy_term model =
List.filter_map model ~f:(function _, Some t -> Some t | _ -> None)
|> List.fold_left ~init:Set.Poly.empty ~f:(fun ret term ->
Set.Poly.filter ~f:(function (_, T_dt.SUS _) -> true | _ -> false) @@
Set.Poly.union ret @@ Term.term_sort_env_of term)
|> Set.Poly.iter ~f:(fun (tvar, sort) -> add_dummy_term tvar sort)
let model_of dtenv model =
let model =
List.map (Model.get_decls model) ~f:(fun decl ->
let x =
FuncDecl.get_name decl
|> Symbol.get_string
|> Str.split (Str.regexp cache_divide_str)
|> List.hd_exn
in
let s =
Sort.mk_fun @@
List.map ~f:(sort_of dtenv) @@
FuncDecl.get_domain decl @ [FuncDecl.get_range decl]
in
(Ident.Tvar x, s),
if FuncDecl.get_arity decl = 0 then
match Model.get_const_interp model decl with
| Some expr -> Some (term_of [] [] dtenv expr)
| None -> None
else
match Model.get_func_interp model decl with
ToDo
| None -> None)
in
Debug.print @@ lazy ("model is :" ^ LogicOld.str_of_model model);
model
let of_var ctx (Ident.Tvar var) = var |> String.escaped |> Symbol.mk_string ctx
let list_type s ctx = Z3List.mk_sort ctx (Symbol.mk_string ctx "list") s
let array_type t1 t2 ctx = Z3Array.mk_sort ctx t1 t2
let sorts_of_tuple sort = sort |> Tuple.get_mk_decl |> FuncDecl.get_domain
let str_of_z3_env env =
Set.Poly.fold env ~init:"z3_env:" ~f:(fun ret (dt, sort) ->
ret ^ "\nLogicOld:\n" ^
LogicOld.Datatype.str_of dt ^ "Z3:\n" ^ Z3.Sort.to_string sort ^
List.fold2_exn
(Z3.Datatype.get_constructors sort)
(Z3.Datatype.get_accessors sort)
~init:"" ~f:(fun ret cons sels ->
ret ^ sprintf "\n|%d: %s" (Z3.FuncDecl.get_id cons) (Z3.FuncDecl.to_string cons) ^
List.fold_left sels ~init:"" ~f:(fun ret sel ->
ret ^ "\n>>> " ^ sprintf "%d: %s" (Z3.FuncDecl.get_id sel) (Z3.FuncDecl.to_string sel))) ^
List.fold_left
(Z3.Datatype.get_recognizers sort)
~init:"\ntesters:" ~f:(fun ret iscons ->
ret ^ "\n ?" ^ sprintf "%d: %s" (Z3.FuncDecl.get_id iscons) (Z3.FuncDecl.to_string iscons)))
let rec of_sort ctx dtenv = function
| Sort.SVar (Ident.Svar svar) ->
Z3.Sort.mk_uninterpreted_s ctx @@ unint_svar_prefix ^ svar
| Sort . SArrow ( s1 , ( s2 , Sort . Pure ) ) - >
Z3Array.mk_sort ctx ( of_sort ) ( of_sort s2 )
Z3Array.mk_sort ctx (of_sort ctx dtenv s1) (of_sort ctx dtenv s2)*)
| Sort.SArrow (_, (_, _, _)) as s ->
Z3.Sort.mk_uninterpreted_s ctx (Term.str_of_sort s)
| T_bool.SBool ->
Boolean.mk_sort ctx
| T_int.SInt ->
Arithmetic.Integer.mk_sort ctx
| T_real.SReal ->
Arithmetic.Real.mk_sort ctx
| T_tuple.STuple sorts ->
tuple_sort_of ctx dtenv sorts
| T_dt.SUS (name, []) ->
Z3.Sort.mk_uninterpreted_s ctx name
ToDo
Z3.Sort.mk_uninterpreted_s ctx "unsupported"
Z3.Sort.mk_uninterpreted_s ctx ( name ^ " _ with_args " )
( " ( " ^ ( String.concat_map_list ~sep : " , " params ~f : Term.str_of_sort ) ^ " ) " ^ name )
| T_dt.SDT dt -> begin
match Set.Poly.find dtenv ~f:(fun (dt1, _) ->
Stdlib.(LogicOld.Datatype.full_name_of dt1 = LogicOld.Datatype.full_name_of dt)) with
| Some (_, sort) -> sort
| None ->
Debug.print @@ lazy
(sprintf "[Z3interface.of_sort] %s to %s"
(Term.str_of_sort @@ T_dt.SDT dt) (str_of_z3_env dtenv));
of_sort ctx (update_z3env ctx dtenv dt) (T_dt.SDT dt)
end
| T_array.SArray (si, se) ->
Z3Array.mk_sort ctx (of_sort ctx dtenv si) (of_sort ctx dtenv se)
| T_string.SString -> Z3.Sort.mk_uninterpreted_s ctx unint_string
| T_sequence.SFinSequence -> Z3.Sort.mk_uninterpreted_s ctx unint_finseq
| T_sequence.SInfSequence -> Z3.Sort.mk_uninterpreted_s ctx unint_infseq
| sort ->
failwith @@ sprintf "[Z3interface.of_sort] %s is unknown" @@ LogicOld.Term.str_of_sort sort
and tuple_sort_of ctx dtenv sorts =
let tuple_num = List.length sorts in
Tuple.mk_sort ctx
String.concat_map_list ~sep:"," ~f:Term.short_name_of_sort sorts)
(List.init tuple_num ~f:(fun i -> Symbol.mk_string ctx @@ unint_tuple_sel_prefix ^ string_of_int i))
(List.map sorts ~f:(of_sort ctx dtenv))
and update_z3env ctx dtenv t =
let dts = LogicOld.Datatype.full_dts_of t in
let dt_names, dt_conses =
List.unzip @@
List.map dts ~f:(fun dt ->
LogicOld.Datatype.full_name_of_dt dt,
List.map (LogicOld.Datatype.conses_of_dt dt) ~f:(fun cons ->
let name = LogicOld.Datatype.name_of_cons cons in
Debug.print @@ lazy (sprintf "mk cons:[%s]" name);
let is_cons_name = Z3.Symbol.mk_string ctx @@ unint_is_cons_prefix ^ name in
Debug.print @@ lazy (sprintf "mk is_cons:[%s]" @@ Z3.Symbol.get_string is_cons_name);
let sels_names, ret_sorts, ref_sorts =
List.fold_left (LogicOld.Datatype.sels_of_cons cons) ~init:([], [], [])
~f:(fun (sels_names, ret_sorts, ref_sorts) -> function
| LogicOld.Datatype.Sel (name, ret_sort) ->
Debug.print @@ lazy (sprintf "mk sel:[%s]" name);
Z3.Symbol.mk_string ctx name :: sels_names,
(Some (of_sort ctx dtenv ret_sort)) :: ret_sorts,
0 :: ref_sorts
| LogicOld.Datatype.InSel (name, ret_name, args) ->
Debug.print @@ lazy (sprintf "mk insel:[%s]" name);
let full_name =
List.fold_left args ~init:ret_name
~f:(fun ret arg -> ret ^ LogicOld.Term.str_of_sort arg)
in
match Set.Poly.find dtenv ~f:(fun (dt, _) ->
Stdlib.(full_name = LogicOld.Datatype.full_name_of dt)) with
| Some (_, sort) ->
Z3.Symbol.mk_string ctx name :: sels_names,
(Some sort) :: ret_sorts,
0 :: ref_sorts
| None ->
match List.findi dts ~f:(fun _ dt ->
Stdlib.(LogicOld.Datatype.name_of_dt dt = ret_name)) with
| Some (i, _) ->
Z3.Symbol.mk_string ctx name :: sels_names,
None :: ret_sorts,
i :: ref_sorts
| _ -> assert false)
in
let z3cons =
Z3.Datatype.mk_constructor ctx
(Z3.Symbol.mk_string ctx name)
is_cons_name
(List.rev sels_names)
(List.rev ret_sorts)
(List.rev ref_sorts)
in
Debug.print @@ lazy ( " z3 tester : " ^ Z3.Datatype . Constructor.get_tester_decl z3cons | > Z3.FuncDecl.to_string ) ;
List.iter ( Z3.Datatype . Constructor.get_accessor_decls z3cons ) ~f:(fun sel - >
Debug.print @@ lazy ( " z3 sel : " ^ ) ) ;
Debug.print @@ lazy ("z3 sel:" ^ Z3.FuncDecl.to_string sel)); *)
z3cons))
in
Z3.Datatype.mk_sorts_s ctx dt_names dt_conses
|> List.fold2_exn dts ~init:dtenv ~f:(fun dtenv dt sort ->
Set.Poly.add dtenv (LogicOld.Datatype.update_name (LogicOld.Datatype.update_dts t dts) @@ LogicOld.Datatype.name_of_dt dt, sort))
and z3_dtenv_of_dtenv ?(init=Set.Poly.empty) ctx dtenv =
Debug.print @@ lazy ( " mk z3 dtenv from:\n " ^ LogicOld . ) ;
let z3_dtenv =
Map.Poly.fold dtenv ~init ~f:(fun ~key:_ ~data env ->
Debug.print @@ lazy ( sprintf " mk sort:%s \n%s " key ( LogicOld . Datatype.str_of data ) ) ;
if Set.Poly.exists env ~f:(fun (dt, _) ->
Stdlib.(LogicOld.Datatype.full_name_of data = LogicOld.Datatype.full_name_of dt))
then env
else update_z3env ctx env data)
in
z3_dtenv
let z3_dtenv_of ?(init=Set.Poly.empty) ctx phi =
LogicOld.update_ref_dtenv @@ LogicOld.DTEnv.of_formula phi;
let dtenv = Atomic.get LogicOld.ref_dtenv in
Debug.print @@ lazy ("[Z3interface.z3_dtenv_of] from:\n" ^ LogicOld.DTEnv.str_of dtenv);
z3_dtenv_of_dtenv ~init ctx dtenv
let z3_dt_of (dtenv:dtenv) dt =
try
snd @@ Set.Poly.find_exn dtenv ~f:(fun (dt1, _) ->
" % s " ( LogicOld . Datatype.full_name_of dt1 ) ;
Stdlib.(LogicOld.Datatype.full_name_of dt = LogicOld.Datatype.full_name_of dt1))
with _ ->
failwith @@ sprintf "[Z3interface.z3_dt_of] %s not found" (LogicOld.Datatype.full_name_of dt)
let z3_cons_of (dtenv:dtenv) dt name =
let z3_conses = Z3.Datatype.get_constructors @@ z3_dt_of dtenv dt in
let conses = Datatype.conses_of dt in
List.find_map_exn (List.zip_exn conses z3_conses) ~f:(fun (cons, z3_cons) ->
if Stdlib.(Datatype.name_of_cons cons = name) then Some z3_cons else None)
let z3_sel_of (dtenv:dtenv) dt name =
let z3_selss = Z3.Datatype.get_accessors @@ z3_dt_of dtenv dt in
let conses = Datatype.conses_of dt in
List.find_map_exn (List.zip_exn conses z3_selss) ~f:(fun (cons, z3_sels) ->
let sels = Datatype.sels_of_cons cons in
List.find_map (List.zip_exn sels z3_sels) ~f:(fun (sel, z3_sel) ->
if Stdlib.(name = Datatype.name_of_sel sel) then Some z3_sel else None))
let z3_iscons_of (dtenv:dtenv) dt name =
let z3_testers = Z3.Datatype.get_recognizers @@ z3_dt_of dtenv dt in
let conses = Datatype.conses_of dt in
List.find_map_exn (List.zip_exn conses z3_testers) ~f:(fun (cons, z3_tester) ->
if Stdlib.(Datatype.name_of_cons cons = name) then Some z3_tester else None)
let z3_string_of ctx str =
Z3.Sort.mk_uninterpreted_s ctx unint_string
let z3_epsilon ctx =
FuncDecl.mk_func_decl_s ctx unint_epsilon [] @@
Z3.Sort.mk_uninterpreted_s ctx unint_finseq
let z3_symbol_of ctx str =
Z3.Sort.mk_uninterpreted_s ctx unint_finseq
let z3_concat ctx fin =
let sort =
if fin then Z3.Sort.mk_uninterpreted_s ctx unint_finseq
else Z3.Sort.mk_uninterpreted_s ctx unint_infseq
in
FuncDecl.mk_func_decl_s ctx (if fin then unint_concat_fin else unint_concat_inf)
[Z3.Sort.mk_uninterpreted_s ctx unint_finseq; sort] sort
let z3_is_prefix_of ctx fin =
FuncDecl.mk_func_decl_s ctx
(if fin then unint_is_prefix_of_fin else unint_is_prefix_of_inf)
[Z3.Sort.mk_uninterpreted_s ctx unint_finseq;
if fin then Z3.Sort.mk_uninterpreted_s ctx unint_finseq
else Z3.Sort.mk_uninterpreted_s ctx unint_infseq]
(Boolean.mk_sort ctx)
let z3_is_in_reg_exp ctx fin regexp =
FuncDecl.mk_func_decl_s ctx
(if fin then unint_is_in_reg_exp_fin_prefix ^ "(" ^ Grammar.RegWordExp.str_of Fn.id regexp ^ ")"
else unint_is_in_reg_exp_inf_prefix ^ "(" ^ Grammar.RegWordExp.str_of Fn.id regexp ^ ")")
[if fin then Z3.Sort.mk_uninterpreted_s ctx unint_finseq
else Z3.Sort.mk_uninterpreted_s ctx unint_infseq]
(Boolean.mk_sort ctx)
let penv_of phi ctx dtenv =
Formula.pred_sort_env_of phi
|> Set.Poly.to_list
|> List.map ~f:(fun (pvar, sorts) ->
pvar,
FuncDecl.mk_func_decl_s ctx
(Ident.name_of_pvar pvar)
(List.map sorts ~f:(of_sort ctx dtenv))
(Boolean.mk_sort ctx))
from our formula to Z3 expr
of_formula : Z3.context - > ( Ident.tvar , Sort.t ) List . Assoc.t - > info Logic . Formula.t
let rec of_formula ctx
(env : sort_env_list)
(penv : (Ident.pvar, FuncDecl.func_decl) List.Assoc.t)
(fenv : fenv)
(dtenv : (LogicOld.Datatype.t *Z3.Sort.sort) Set.Poly.t)
phi =
if Formula.is_atom phi then
let atom, _ = Formula.let_atom phi in
if Atom.is_pvar_app atom then
let pvar, sorts, _, _ = Atom.let_pvar_app atom in
let func =
FuncDecl.mk_func_decl_s ctx
(Ident.name_of_pvar pvar)
(List.map sorts ~f:(of_sort ctx dtenv))
(Boolean.mk_sort ctx)
in
let penv = if not @@ List.Assoc.mem ~equal:Stdlib.(=) penv pvar then (pvar, func) :: penv else penv in
of_atom ctx env penv fenv dtenv atom
else of_atom ctx env penv fenv dtenv atom
else if Formula.is_neg phi then
Boolean.mk_not ctx @@ of_formula ctx env penv fenv dtenv @@ fst (Formula.let_neg phi)
else if Formula.is_and phi then
let phi1, phi2, _ = Formula.let_and phi in
Boolean.mk_and ctx
[of_formula ctx env penv fenv dtenv phi1;
of_formula ctx env penv fenv dtenv phi2]
else if Formula.is_or phi then
let phi1, phi2, _ = Formula.let_or phi in
Boolean.mk_or ctx
[of_formula ctx env penv fenv dtenv phi1;
of_formula ctx env penv fenv dtenv phi2]
else if Formula.is_iff phi then
let phi1, phi2, _ = Formula.let_iff phi in
Boolean.mk_iff ctx
(of_formula ctx env penv fenv dtenv phi1)
(of_formula ctx env penv fenv dtenv phi2)
else if Formula.is_imply phi then
let phi1, phi2, _ = Formula.let_imply phi in
Boolean.mk_implies ctx
(of_formula ctx env penv fenv dtenv phi1)
(of_formula ctx env penv fenv dtenv phi2)
else if Formula.is_bind phi then
let binder, bounds, body, _ = Formula.let_bind phi in
let bounds = List.rev bounds in
let env = bounds @ env in
let sorts = List.map bounds ~f:(fun (_, sort) -> of_sort ctx dtenv sort) in
let vars = List.map bounds ~f:(fun (var, _) -> of_var ctx var) in
let body = of_formula ctx env penv fenv dtenv body in
(match binder with
| Formula.Forall -> Quantifier.mk_forall ctx sorts vars body None [] [] None None
| Formula.Exists -> Quantifier.mk_exists ctx sorts vars body None [] [] None None
| _ -> assert false)
|> Quantifier.expr_of_quantifier
|> (fun e -> add_to_bound_var_cache e; e)
else if Formula.is_letrec phi then
match Formula.let_letrec phi with
| [], phi, _ -> of_formula ctx env penv fenv dtenv phi
| _, _, _ ->
failwith @@ "[Z3interface.of_formula] underlying solver cannot deal with fixpoint predicates: " ^ Formula.str_of phi;
else failwith @@ sprintf "[Z3interface.of_formula] %s not supported: " @@ Formula.str_of phi
and of_var_term ctx env dtenv t =
let (var, sort), _ = Term.let_var t in
Debug.print @@ lazy
( sprintf " z3_of_var_term:%s % s "
( Ident.name_of_tvar var ) ( Term.str_of_sort @@ Term.sort_of t ) ) ;
(sprintf "z3_of_var_term:%s %s"
(Ident.name_of_tvar var) (Term.str_of_sort @@ Term.sort_of t)); *)
match List.findi env ~f:(fun _ (key, _) -> Stdlib.(key = var)) with
| Some (i, (_, sort')) ->
assert Stdlib.(sort = sort');
let sort = of_sort ctx dtenv sort in
lock ( ) ; ( fun ret - > unlock ( ) ; ret ) @@
Quantifier.mk_bound ctx i sort
| None ->
find_in_cache ctx env t ~f:(fun cid ->
let name = Ident.name_of_tvar var in
let symbol =
of_var ctx @@
Ident.Tvar (sprintf "%s%s%d%s" name cache_divide_str cid (Term.short_name_of_sort sort))
in
let sort = of_sort ctx dtenv sort in
Expr.mk_const ctx symbol sort)
from our term to Z3 expr
and of_term ctx
(env : (Ident.tvar, Sort.t) List.Assoc.t)
(penv : (Ident.pvar, FuncDecl.func_decl) List.Assoc.t)
(fenv : fenv)
(dtenv : (LogicOld.Datatype.t * Z3.Sort.sort) Set.Poly.t) t =
Debug.print @@ lazy (sprintf "[Z3interface.of_term] %s" @@ Term.str_of t);
if Term.is_var t then
of_var_term ctx env dtenv t
else if Term.is_app t then
match Term.let_app t with
| T_bool.Formula phi, [], _ ->
of_formula ctx env penv fenv dtenv phi
| T_bool.IfThenElse, [cond; then_; else_], _ ->
Boolean.mk_ite ctx
(of_term ctx env penv fenv dtenv cond)
(of_term ctx env penv fenv dtenv then_)
(of_term ctx env penv fenv dtenv else_)
| T_int.Int n, [], _ ->
find_in_cache ctx env t ~f:(fun _ ->
Arithmetic.Integer.mk_numeral_s ctx (Z.to_string n))
| T_real.Real r, [], _ ->
find_in_cache ctx env t ~f:(fun _ ->
Arithmetic.Real.mk_numeral_s ctx (Q.to_string r))
| (T_int.Add | T_real.RAdd), [t1; t2], _ ->
Arithmetic.mk_add ctx
[of_term ctx env penv fenv dtenv t1;
of_term ctx env penv fenv dtenv t2]
| (T_int.Sub | T_real.RSub), [t1; t2], _ ->
Arithmetic.mk_sub ctx
[of_term ctx env penv fenv dtenv t1;
of_term ctx env penv fenv dtenv t2]
| (T_int.Mult | T_real.RMult), [t1; t2], _ ->
Arithmetic.mk_mul ctx
[of_term ctx env penv fenv dtenv t1;
of_term ctx env penv fenv dtenv t2]
| T_int.Div, [t1; t2], _ ->
Arithmetic.mk_div ctx
(of_term ctx env penv fenv dtenv t1)
(of_term ctx env penv fenv dtenv t2)
| T_int.Mod, [t1; t2], _ ->
Arithmetic.Integer.mk_mod ctx
(of_term ctx env penv fenv dtenv t1)
(of_term ctx env penv fenv dtenv t2)
| T_int.Rem, [t1; t2], _ ->
Arithmetic.Integer.mk_rem ctx
(of_term ctx env penv fenv dtenv t1)
(of_term ctx env penv fenv dtenv t2)
| T_real.RDiv, [t1; t2], _ ->
Arithmetic.mk_div ctx
of_term ctx env penv fenv dtenv t1)
of_term ctx env penv fenv dtenv t2)
| (T_int.Neg | T_real.RNeg), [t1], _ when Term.is_var t1 || T_int.is_int t1 ->
let n = of_term ctx env penv fenv dtenv t1 in
if T_int.is_int t1 || Expr.is_const n then
find_in_cache ctx env t ~f:(fun _ -> Arithmetic.mk_unary_minus ctx n)
else Arithmetic.mk_unary_minus ctx n
| (T_int.Neg | T_real.RNeg), [t], _ ->
Arithmetic.mk_unary_minus ctx (of_term ctx env penv fenv dtenv t)
| (T_int.Abs | T_real.RAbs) as op, [t], _ ->
let n = of_term ctx env penv fenv dtenv t in
let minus_n = of_term ctx env penv fenv dtenv (T_int.mk_neg t) in
let is_minus =
Arithmetic.mk_lt ctx n
(match op with
| T_int.Abs ->
find_in_cache ctx env (T_int.zero ())
~f:(fun _ -> Arithmetic.Integer.mk_numeral_i ctx 0)
| T_real.RAbs ->
find_in_cache ctx env (T_real.rzero ())
~f:(fun _ -> Arithmetic.Real.mk_numeral_i ctx 0)
| _ -> assert false)
in
Boolean.mk_ite ctx is_minus minus_n n
| (T_int.Power | T_real.RPower), [t1; t2], _ ->
Arithmetic.mk_power ctx
(of_term ctx env penv fenv dtenv t1)
(of_term ctx env penv fenv dtenv t2)
| FVar (var, _), ts, _ when Map.Poly.mem fenv var->
Z3.FuncDecl.apply (Map.Poly.find_exn fenv var) @@
List.map ts ~f:(of_term ctx env penv fenv dtenv)
| FVar (var, sorts), ts, _ ->
let sorts = List.map ~f:(of_sort ctx dtenv) sorts in
let sargs, sret = List.take sorts (List.length sorts - 1), List.last_exn sorts in
Expr.mk_app ctx (FuncDecl.mk_func_decl ctx (of_var ctx var) sargs sret) @@
List.map ~f:(of_term ctx env penv fenv dtenv) ts
| T_real_int.ToReal, [t], _ ->
Arithmetic.Integer.mk_int2real ctx (of_term ctx env penv fenv dtenv t)
| T_real_int.ToInt, [t], _ ->
Arithmetic.Real.mk_real2int ctx (of_term ctx env penv fenv dtenv t)
| T_tuple.TupleSel (sorts, i), [t], _ ->
let sort = of_sort ctx dtenv @@ T_tuple.STuple sorts in
Z3.FuncDecl.apply (List.nth_exn (Tuple.get_field_decls sort) i) @@
[of_term ctx env penv fenv dtenv t]
| T_tuple.TupleCons sorts, ts, _ ->
let sort = of_sort ctx dtenv @@ T_tuple.STuple sorts in
Z3.FuncDecl.apply (Tuple.get_mk_decl sort) @@
List.map ts ~f:(of_term ctx env penv fenv dtenv)
| T_dt.DTCons (name, _tys, dt), ts, _ ->
Z3.FuncDecl.apply (z3_cons_of dtenv dt name) @@
List.map ts ~f:(of_term ctx env penv fenv dtenv)
| T_dt.DTSel (name, dt, _), ts, _ ->
Z3.FuncDecl.apply (z3_sel_of dtenv dt name) @@
List.map ts ~f:(of_term ctx env penv fenv dtenv)
| T_array.AStore (_si, _se), [t1; t2; t3], _ ->
Z3Array.mk_store ctx
(of_term ctx env penv fenv dtenv t1)
(of_term ctx env penv fenv dtenv t2)
(of_term ctx env penv fenv dtenv t3)
| T_array.ASelect (_si, _se), [t1; t2], _ ->
Z3Array.mk_select ctx
(of_term ctx env penv fenv dtenv t1)
(of_term ctx env penv fenv dtenv t2)
| T_array.AConst (si, _se), [t1], _ ->
Z3Array.mk_const_array ctx
(of_sort ctx dtenv si)
(of_term ctx env penv fenv dtenv t1)
| T_string.StringConst str, [], _ ->
Z3.FuncDecl.apply (z3_string_of ctx str) []
| T_sequence.Epsilon, [], _ ->
Z3.FuncDecl.apply (z3_epsilon ctx) []
| T_sequence.Symbol str, [], _ ->
Z3.FuncDecl.apply (z3_symbol_of ctx str) []
| T_sequence.Concat fin, [t1; t2], _ ->
Z3.FuncDecl.apply (z3_concat ctx fin)
[of_term ctx env penv fenv dtenv t1;
of_term ctx env penv fenv dtenv t2]
| _ -> failwith @@ "[Z3interface.of_term] not supported: " ^ Term.str_of t
else failwith @@ "[Z3interface.of_term] not supported: " ^ Term.str_of t
and
from our atom to Z3 expr
of_atom ctx
(env : (Ident.tvar, Sort.t) List.Assoc.t)
(penv : (Ident.pvar, FuncDecl.func_decl) List.Assoc.t)
(fenv : fenv)
(dtenv : (LogicOld.Datatype.t *Z3.Sort.sort) Set.Poly.t) atom =
Debug.print @@ lazy (sprintf "[Z3interface.of_atom] %s" @@ Atom.str_of atom);
if Atom.is_true atom then
find_in_cache ctx env (T_bool.mk_true ()) ~f:(fun _ -> Boolean.mk_true ctx)
else if Atom.is_false atom then
find_in_cache ctx env (T_bool.mk_false ()) ~f:(fun _ -> Boolean.mk_false ctx)
else if Atom.is_psym_app atom then
let sym, args, _ = Atom.let_psym_app atom in
match sym, List.map ~f:(of_term ctx env penv fenv dtenv) args with
| T_bool.Eq, [t1; t2] ->
Boolean.mk_eq ctx t1 t2
| T_bool.Neq, [t1; t2] ->
Boolean.mk_not ctx @@ Boolean.mk_eq ctx t1 t2
| (T_int.Leq | T_real.RLeq), [t1; t2] ->
Arithmetic.mk_le ctx t1 t2
| (T_int.Geq | T_real.RGeq), [t1; t2] ->
Arithmetic.mk_ge ctx t1 t2
| (T_int.Lt | T_real.RLt), [t1; t2] ->
Arithmetic.mk_lt ctx t1 t2
| (T_int.Gt | T_real.RGt), [t1; t2] ->
Arithmetic.mk_gt ctx t1 t2
| T_int.PDiv, [t1; t2] ->
Boolean.mk_eq ctx
(Arithmetic.Integer.mk_mod ctx t2 t1)
(Arithmetic.Integer.mk_numeral_i ctx 0)
| T_int.NPDiv, [t1; t2] ->
Boolean.mk_not ctx @@
Boolean.mk_eq ctx
(Arithmetic.Integer.mk_mod ctx t2 t1)
(Arithmetic.Integer.mk_numeral_i ctx 0)
| (T_num.NLeq _ | T_num.NGeq _ | T_num.NLt _ | T_num.NGt _), [_t1; _t2] ->
failwith @@ sprintf "[Z3interface.of_atom] polymorphic inequalities not supported: %s" @@
Atom.str_of atom
| T_real_int.IsInt, [t] ->
Arithmetic.Real.mk_is_integer ctx t
| T_tuple.IsTuple _sorts, _ts ->
ToDo
let _ s = tuple_sort_of sorts in
let istuple = failwith " [ Z3interface.of_atom ] is_tuple not supported " in
let istuple = failwith "[Z3interface.of_atom] is_tuple not supported" in
Z3.FuncDecl.apply istuple ts*)
| T_tuple.NotIsTuple _sorts, _ts ->
ToDo
let _ s = tuple_sort_of sorts in
let istuple = failwith " [ Z3interface.of_atom ] is_tuple not supported " in
Boolean.mk_not ctx @@ Z3.FuncDecl.apply istuple ts
let istuple = failwith "[Z3interface.of_atom] is_tuple not supported" in
Boolean.mk_not ctx @@ Z3.FuncDecl.apply istuple ts*)
| T_dt.IsCons (name, dt), ts ->
Z3.FuncDecl.apply (z3_iscons_of dtenv dt name) ts
| T_dt.NotIsCons (name, dt), ts ->
Boolean.mk_not ctx @@
Z3.FuncDecl.apply (z3_iscons_of dtenv dt name) ts
| T_sequence.IsPrefix fin, [t1; t2] ->
Z3.FuncDecl.apply (z3_is_prefix_of ctx fin) [t1; t2]
| T_sequence.NotIsPrefix fin, [t1; t2] ->
Boolean.mk_not ctx @@ Z3.FuncDecl.apply (z3_is_prefix_of ctx fin) [t1; t2]
| T_sequence.InRegExp (fin, regexp), [t1] ->
Z3.FuncDecl.apply (z3_is_in_reg_exp ctx fin regexp) [t1]
| T_sequence.NotInRegExp (fin, regexp), [t1] ->
Boolean.mk_not ctx @@ Z3.FuncDecl.apply (z3_is_in_reg_exp ctx fin regexp) [t1]
| _ -> failwith @@ sprintf "[Z3interface.of_atom] %s not supported: " @@ Atom.str_of atom
else if Atom.is_pvar_app atom then
let pvar, _sargs, args, _ = Atom.let_pvar_app atom in
if List.is_empty args && not @@ List.Assoc.mem ~equal:Stdlib.(=) penv pvar then
of_var_term ctx env dtenv @@
Term.mk_var (Ident.pvar_to_tvar pvar) T_bool.SBool
else
let pred =
match List.Assoc.find ~equal:Stdlib.(=) penv pvar with
| None ->
failwith @@ sprintf "[Z3interface.of_atom] %s not supported: " @@
Ident.name_of_pvar pvar
| Some pred -> pred
in
Expr.mk_app ctx pred @@ List.map args ~f:(of_term ctx env penv fenv dtenv)
else failwith @@ sprintf "[Z3interface.of_atom] %s not supported: " @@ Atom.str_of atom
let z3_fenv_of ?(init=Map.Poly.empty) ctx
(env : (Ident.tvar, Sort.t) List.Assoc.t)
(penv : (Ident.pvar, FuncDecl.func_decl) List.Assoc.t)
(fenv : LogicOld.FunEnv.t)
(dtenv : (LogicOld.Datatype.t * Z3.Sort.sort) Set.Poly.t)
=
let z3_fenv =
Map.Poly.fold fenv ~init ~f:(fun ~key:var ~data:(params, sret, _, _, _) acc ->
if Map.Poly.mem acc var then acc
else
let func =
Z3.FuncDecl.mk_rec_func_decl_s
ctx
(Ident.name_of_tvar var)
(List.map params ~f:(fun (_, s) -> of_sort ctx dtenv s))
(of_sort ctx dtenv sret)
in
Map.Poly.add_exn acc ~key:var ~data:func)
in
Map.Poly.iteri fenv ~f:(fun ~key:var ~data:(params, _, def, _, _) ->
if Map.Poly.mem init var then ()
else
Z3.FuncDecl.add_rec_def
ctx
(Map.Poly.find_exn z3_fenv var)
(List.map params ~f:(fun (v, s) ->
of_term ctx env penv z3_fenv dtenv (Term.mk_var v s)))
(of_term ctx env penv z3_fenv dtenv def));
z3_fenv
let of_formula ctx
(env : (Ident.tvar, Sort.t) List.Assoc.t)
(penv : (Ident.pvar, FuncDecl.func_decl) List.Assoc.t)
(fenv : fenv)
(dtenv : (LogicOld.Datatype.t * Z3.Sort.sort) Set.Poly.t)
phi =
phi
|> Normalizer.normalize_let
|> (fun phi' ->
Debug.print @@ lazy
(sprintf "[z3:of_formula]\n %s\n %s" (Formula.str_of phi) (Formula.str_of phi'));
phi')
|> Formula.equivalent_sat
|> (of_formula ctx env penv fenv dtenv)
let check_sat_z3 solver dtenv phis =
z3_solver_add solver phis;
match Z3.Solver.check solver [] with
| SATISFIABLE ->
(match z3_solver_get_model solver with
| Some model ->
let model = model_of dtenv model in
debug_print_z3_model model ;
`Sat model
| None -> `Unknown "model production is not enabled?")
| UNSATISFIABLE -> `Unsat
| UNKNOWN ->
(match Z3.Solver.get_reason_unknown solver with
| "timeout" | "canceled" -> `Timeout
| reason -> `Unknown reason)
let max_smt_z3 context dtenv hard soft =
let optimizer = Optimize.mk_opt context in
Optimize.add optimizer hard;
Map.Poly.iteri soft ~f:(fun ~key ~data ->
List.iter data ~f:(fun (expr, weight) ->
ignore @@ Optimize.add_soft optimizer expr (string_of_int weight) (Z3.Symbol.mk_string context key)));
match Optimize.check optimizer with
| SATISFIABLE ->
let open Option.Monad_infix in
Optimize.get_model optimizer >>= fun model ->
let num_sat =
Map.Poly.fold soft ~init:0 ~f:(fun ~key:_ ~data sum ->
List.fold data ~init:sum ~f:(fun sum (expr, weight) ->
sum + (match Model.eval model expr true with
| None -> 0 | Some e -> if Boolean.is_true e then weight else 0)))
in
Some (num_sat, model_of dtenv model)
| _ -> None
let check_opt_maximize_z3 context dtenv phis obj =
let optimizer = Optimize.mk_opt context in
Optimize.add optimizer phis;
let handle = Optimize.maximize optimizer obj in
match Optimize.check optimizer with
| SATISFIABLE ->
let open Option.Monad_infix in
Optimize.get_model optimizer >>= fun model ->
let lower = Optimize.get_lower handle |> term_of [] [] dtenv in
let upper = Optimize.get_upper handle |> term_of [] [] dtenv in
Some (lower, upper, model_of dtenv model)
| _ -> None
let get_instance =
let new_instance cfg =
Caml_threads.Mutex.lock mutex;
Gc.full_major ();
let ctx = mk_context cfg in
let solver = Z3.Solver.mk_solver ctx None in
let goal = Z3.Goal.mk_goal ctx false false false in
let dtenv = Set.Poly.empty in
let fenv = Map.Poly.empty in
Caml_threads.Mutex.unlock mutex;
{ ctx; solver; goal; dtenv; fenv; cfg }
in
fun (id:int option) cfg instance_pool ->
if not enable_solver_pool then new_instance cfg
else
match Hashtbl.Poly.find instance_pool (id, cfg) with
| None -> new_instance cfg
| Some instance -> instance
let back_instance ~reset instance_pool id instance =
if enable_solver_pool then begin
reset instance;
Hashtbl.Poly.set instance_pool ~key:(id, instance.cfg) ~data:instance;
end
let check_sat =
let cfg = [ ("model", "true"); ] in
let cfg = if validate then cfg @ validate_cfg else cfg in
fun ?(timeout=None) ~id fenv phis ->
let instance = get_instance id cfg instance_pool in
let ctx, solver = instance.ctx, instance.solver in
instance.dtenv <- (z3_dtenv_of ~init:instance.dtenv ctx @@ Formula.and_of phis);
instance.fenv <- (z3_fenv_of ~init:instance.fenv ctx [] [] fenv instance.dtenv);
debug_print_z3_input phis;
let phis = List.map phis ~f:(FunEnv.defined_formula_of fenv) in
debug_print_z3_input phis;
let phis' = List.map phis ~f:(of_formula ctx [] [] (instance.fenv) (instance.dtenv)) in
(match timeout with
| None -> ()
| Some timeout ->
let params = Z3.Params.mk_params ctx in
Z3.Params.add_int params (Z3.Symbol.mk_string ctx "timeout") timeout;
Z3.Solver.set_parameters solver params);
check_sat_z3 solver (instance.dtenv) phis'
|> (fun ret -> back_instance ~reset:(fun instance -> z3_solver_reset instance.solver) instance_pool id instance; ret)
let check_sat_unsat_core_main ?(timeout=None) ?(untrack_phis=[]) solver ctx fenv dtenv pvar_clause_map =
(match timeout with
| None ->
let params = Z3.Params.mk_params ctx in
Z3.Params.add_bool params (Z3.Symbol.mk_string ctx "model") true;
Z3.Params.add_bool params (Z3.Symbol.mk_string ctx "unsat_core") true;
Z3.Solver.set_parameters solver params
| Some timeout ->
let params = Z3.Params.mk_params ctx in
Z3.Params.add_bool params (Z3.Symbol.mk_string ctx "model") true;
Z3.Params.add_bool params (Z3.Symbol.mk_string ctx "unsat_core") true;
Z3.Params.add_int params (Z3.Symbol.mk_string ctx "timeout") timeout;
Z3.Solver.set_parameters solver params);
Map.Poly.iteri pvar_clause_map ~f:(fun ~key:name ~data:phi ->
if Formula.is_true phi then ()
else begin
Debug.print @@ lazy (sprintf "assert and track: [%s] %s" name (Formula.str_of phi));
let phi_expr = of_formula ctx [] [] fenv dtenv phi in
let lable =
find_in_cache
~f:(fun _ -> Boolean.mk_const_s ctx name)
ctx []
(Term.mk_var (Tvar name) T_bool.SBool)
in
z3_solver_assert_and_track solver phi_expr lable
end);
Z3.Solver.push solver;
Z3.Solver.add solver (List.map untrack_phis ~f:(of_formula ctx [] [] fenv dtenv));
(fun ret -> Z3.Solver.pop solver 1; ret) @@
match Z3.Solver.check solver [] with
| Z3.Solver.SATISFIABLE ->
(match z3_solver_get_model solver with
| Some model -> `Sat (model_of dtenv model)
| None -> `Unknown "model production is not enabled?")
| UNSATISFIABLE ->
Debug.print @@ lazy "unsat reason:";
let unsat_keys = List.map ~f:Z3.Expr.to_string @@ z3_solver_get_unsat_core solver in
List.iter unsat_keys ~f:(fun unsat_key -> Debug.print @@ lazy (unsat_key));
`Unsat unsat_keys
| UNKNOWN ->
(match Z3.Solver.get_reason_unknown solver with
| "timeout" | "canceled" -> `Timeout
| reason -> `Unknown reason)
let check_sat_unsat_core_main ?(timeout=None) ?(untrack_phis=[]) solver ctx fenv dtenv pvar_clause_map =
match timeout with
| None ->
check_sat_unsat_core_main ~timeout ~untrack_phis solver ctx fenv dtenv pvar_clause_map
| Some tm ->
Timer.enable_timeout (tm / 1000) Fn.id ignore
(fun () -> check_sat_unsat_core_main ~timeout ~untrack_phis solver ctx fenv dtenv pvar_clause_map)
(fun _ res -> res)
(fun _ -> function Timer.Timeout -> `Timeout | e -> raise e)
let check_sat_unsat_core ?(timeout=None) fenv pvar_clause_map =
let ctx =
let cfg = [ ("model", "true"); ("unsat_core", "true") ] in
let cfg = if validate then cfg @ validate_cfg else cfg in
let cfg =
match timeout with
| None -> cfg
| Some timeout -> cfg @ [("timeout", string_of_int timeout)]
in
mk_context cfg
in
let dtenv = z3_dtenv_of ctx @@ Formula.and_of @@ snd @@ List.unzip @@ Map.Poly.to_alist pvar_clause_map in
let solver = Z3.Solver.mk_solver ctx None in
let fenv = z3_fenv_of ctx [] [] fenv dtenv in
(match timeout with
| None -> ()
| Some timeout ->
let params = Z3.Params.mk_params ctx in
Z3.Params.add_int params (Z3.Symbol.mk_string ctx "timeout") timeout;
Z3.Solver.set_parameters solver params);
check_sat_unsat_core_main ~timeout solver ctx fenv dtenv pvar_clause_map
let max_smt fenv hard soft =
let cfg = [
("MODEL", "true");
] in
let ctx = mk_context cfg in
let soft_phi = Map.Poly.to_alist soft |> List.unzip |> snd |> List.join |> List.unzip |> fst |> Formula.and_of in
let dtenv = z3_dtenv_of ctx @@ Formula.and_of (soft_phi::hard) in
let hard = List.map hard ~f:(of_formula ctx [] [] fenv dtenv) in
let soft = Map.Poly.map soft ~f:(List.map ~f:(fun (phi, weight) -> of_formula ctx [] [] fenv dtenv phi , weight)) in
max_smt_z3 ctx dtenv hard soft
* ToDo : use instead
let max_smt_of ~id fenv num_ex phis =
let cfg = [("unsat_core", "true")] in
let instance = get_instance id cfg instance_pool in
let ctx = instance.ctx in
instance.dtenv <- z3_dtenv_of ~init:instance.dtenv ctx @@ Formula.and_of phis;
instance.fenv <- (z3_fenv_of ~init:(instance.fenv) ctx [] [] fenv instance.dtenv);
let dtenv = instance.dtenv in
let fenv = instance.fenv in
let solver = instance.solver in
let name_map0 =
List.map phis ~f:(of_formula ctx [] [] fenv dtenv)
|> List.foldi ~init:Map.Poly.empty ~f:(fun i map phi ->
let name = "#S_" ^ (string_of_int i) in
let lable =
find_in_cache
~f:(fun _ -> Boolean.mk_const_s ctx name)
ctx []
(Term.mk_var (Tvar name) T_bool.SBool)
in
Map.Poly.update map lable ~f:(function None -> phi | Some x -> x)) in
let rec inner num_ex models ignored name_map =
if num_ex <= 0 then models
else begin
Map.Poly.iteri name_map ~f:(fun ~key ~data -> z3_solver_assert_and_track solver data key);
z3_solver_reset solver;
match Z3.Solver.check solver [] with
| Z3.Solver.SATISFIABLE ->
(match z3_solver_get_model solver with
| None -> assert false
| Some model ->
let models' = Set.Poly.add models (model_of dtenv model) in
let name_map' = Map.Poly.filter_keys ~f:(Set.Poly.mem ignored) name_map0 in
inner (num_ex - 1) models' Set.Poly.empty name_map')
| UNSATISFIABLE ->
let ucore = List.hd_exn @@ z3_solver_get_unsat_core solver in
inner num_ex models (Set.Poly.add ignored ucore) (Map.Poly.remove name_map ucore)
| UNKNOWN -> assert false
end
in
inner num_ex Set.Poly.empty Set.Poly.empty name_map0
|> (fun ret ->
back_instance ~reset:(fun ins -> z3_solver_reset ins.solver) instance_pool id instance;
ret)
let check_opt_maximize fenv phis obj =
let cfg = [ ("model", "true") ] in
let cfg = if validate then cfg @ validate_cfg else cfg in
let ctx = mk_context cfg in
let dtenv = z3_dtenv_of ctx @@ Formula.and_of phis in
let z3fenv = z3_fenv_of ctx [] [] fenv dtenv in
debug_print_z3_input phis;
let phis = List.map phis ~f:(of_formula ctx [] [] z3fenv dtenv) in
let obj = of_term ctx [] [] (z3_fenv_of ctx [] [] fenv dtenv) dtenv obj in
check_opt_maximize_z3 ctx dtenv phis obj
let check_valid ~id fenv phi =
match check_sat ~id fenv [Formula.negate phi] with
| `Unsat -> `Valid
| `Sat model -> `Invalid model
| res -> res
let is_valid ~id fenv phi = match check_valid ~id fenv phi with `Valid -> true | _ -> false
exception Unknown
let is_valid_exn ~id fenv phi = match check_valid ~id fenv phi with `Valid -> true | `Invalid _ -> false | _ -> raise Unknown
let is_sat ~id fenv phi = match check_sat ~id fenv [phi] with `Sat _ -> true | _ -> false
let z3_simplify ~id fenv phi =
let cfg = [("model", "true");] in
let instance = get_instance id cfg instance_pool in
let ctx = instance.ctx in
instance.dtenv <- (z3_dtenv_of ~init:(instance.dtenv) ctx phi);
instance.fenv <- (z3_fenv_of ~init:(instance.fenv) ctx [] [] fenv instance.dtenv);
let dtenv = instance.dtenv in
let fenv = instance.fenv in
let symplify_params = Z3.Params.mk_params @@ ctx in
let penv = penv_of phi ctx dtenv in
let lenv = Map.Poly.to_alist @@ Formula.let_sort_env_of phi in
let tenv = lenv @ (Formula.term_sort_env_of phi |> Set.Poly.to_list) in
Z3.Params.add_bool symplify_params (Z3.Symbol.mk_string ctx "elim_ite") true;
Z3.Params.add_bool symplify_params (Z3.Symbol.mk_string ctx "push_ite_arith") true;
let rec inner = function
| Formula.LetFormula (v, sort, def, body, info) ->
let def' =
if Stdlib.(sort = T_bool.SBool) then
T_bool.of_formula @@ inner @@ Formula.of_bool_term def
else def
in
Formula.LetFormula (v, sort, def', inner body, info)
| phi ->
phi
| > ( fun phi - > print_endline @@ Formula.str_of phi ^ " \n " ; )
|> of_formula ctx tenv penv fenv dtenv
|> (fun phi -> Z3.Expr.simplify phi @@ Some symplify_params)
|> formula_of (List.rev tenv) penv dtenv
|> Evaluator.simplify
| > ( fun phi - > print_endline @@ Formula.str_of phi ^ " \n " ; )
in
let ret = inner phi in
back_instance ~reset:ignore instance_pool id instance;
ret
let qelim ~id fenv phi =
if Formula.is_bind phi then
let _ = Debug.print @@ lazy (sprintf "[Z3interface.qelim] %s" (Formula.str_of phi)) in
let cfg = [ ("model", "true"); ] in
let instance = get_instance id cfg instance_pool in
let ctx = instance.ctx in
let goal = instance.goal in
instance.dtenv <- z3_dtenv_of ~init:instance.dtenv ctx phi;
instance.fenv <- z3_fenv_of ~init:instance.fenv ctx [] [] fenv instance.dtenv;
let symplify_params = Z3.Params.mk_params ctx in
let penv = penv_of phi ctx instance.dtenv in
Z3.Params.add_bool symplify_params (Z3.Symbol.mk_string ctx "elim_ite") true;
let qe_params = Z3.Params.mk_params ctx in
Z3.Params.add_bool qe_params (Z3.Symbol.mk_string ctx "eliminate_variables_as_block") true;
z3_goal_add goal [of_formula ctx [] penv instance.fenv instance.dtenv phi];
let g =
Goal.as_expr @@
Z3.Tactic.ApplyResult.get_subgoal (Z3.Tactic.apply (Z3.Tactic.mk_tactic ctx "qe") goal (Some qe_params)) 0
in
let expr = Z3.Expr.simplify g (Some symplify_params) in
let _ = Debug.print @@ lazy ("quantifier eliminated: " ^ Z3.Expr.to_string expr) in
let phi =
Evaluator.simplify @@ Formula.nnf_of @@
formula_of [] penv instance.dtenv expr
in
back_instance ~reset:(fun ins -> Goal.reset ins.goal) instance_pool id instance;
print_endline @@ " qelim ret : " ^ Formula.str_of phi ;
phi
else phi
let smtlib2_str_of_formula ctx fenv dtenv phi =
Expr.to_string @@
of_formula ctx
(Set.Poly.to_list @@ Formula.term_sort_env_of phi)
(penv_of phi ctx dtenv) fenv dtenv
phi
let expr_cache:(context, (Formula.t, Z3.Expr.expr) Hashtbl.Poly.t) Hashtbl.Poly.t = Hashtbl.Poly.create ()
let find_in_expr_cache ctx phi ~f =
let cache = Hashtbl.Poly.find_or_add expr_cache ctx ~default:(fun _ -> Hashtbl.Poly.create ()) in
Hashtbl.Poly.find_or_add cache phi ~default:(fun _ -> f ())
let expr_of ctx fenv dtenv phi =
find_in_expr_cache ctx phi ~f:(fun _ ->
try of_formula ctx [] [] fenv dtenv @@ Evaluator.simplify phi
with _ -> of_formula ctx [] [] fenv dtenv @@ Formula.mk_true ())
let str_of_asserts_of_solver solver =
"Asserts of solver:" ^
String.concat_map_list ~sep:"\n\t" ~f:Expr.to_string @@ Z3.Solver.get_assertions solver
let check_valid_inc solver phis =
match Z3.Solver.check solver phis with
| SATISFIABLE ->
Debug.print @@ lazy ( sprintf " % s \n check valid - > ( " ( str_of_asserts_of_solver solver ) ) ;
false
| _ ->
Debug.print @@ lazy ( sprintf " % s valid - > ( unsat)valid " ( str_of_asserts_of_solver solver ) ) ;
true
let star and_flag = function
| Formula.Atom (a, _) when Atom.is_pvar_app a -> None
| Formula.UnaryOp (Formula.Not, Formula.Atom (a, _), _) when Atom.is_pvar_app a -> None
| phi -> Some (Evaluator.simplify @@ if and_flag then phi else Formula.negate phi)
let rec simplify_term solver ctx fenv dtenv = function
| Term.FunApp (T_bool.Formula phi, [], info) ->
let phi, has_changed = simplify_formula solver ctx fenv dtenv phi in
T_bool.of_formula ~info phi, has_changed
| Term.FunApp (T_bool.IfThenElse, [t1; t2; t3], info) ->
let t1, has_changed1 = simplify_term solver ctx fenv dtenv t1 in
T_bool.mk_if_then_else ~info t1 t2 t3, has_changed1 || has_changed2 || has_changed3
| t -> t, false
and simplify_atom solver ctx fenv (dtenv:dtenv) atom =
if Atom.is_pvar_app atom then
let pvar, sorts, args, info = Atom.let_pvar_app atom in
let args', _has_changed_list =
List.unzip @@ List.map ~f:(simplify_term solver ctx fenv dtenv) args
in
Atom.mk_pvar_app pvar sorts args' ~info,
List.exists ~f : ident has_changed_list
else
let phi = Formula.mk_atom atom in
if check_valid_inc solver [expr_of ctx fenv dtenv @@ Formula.negate phi] then
Atom.mk_true (), true
else if check_valid_inc solver [expr_of ctx fenv dtenv @@ phi] then
Atom.mk_false (), true
else atom, false
and check_sub_formulas solver ctx fenv (dtenv:dtenv) and_flag phi =
let cs = Set.Poly.to_list @@ if and_flag then Formula.conjuncts_of phi else Formula.disjuncts_of phi in
Debug.print @@ lazy ( sprintf " Cs : % s " ( String.concat_map_list ~sep:"\n\t " cs ~f : Formula.str_of ) ) ;
Debug.print @@ lazy ( str_of_asserts_of_solver solver ) ;
Z3.Solver.push solver;
let cs', _ , has_changed =
List.fold_left cs ~init:([], List.tl_exn cs, false)
~f:(fun (cs', cs, has_changed) c ->
Z3.Solver.push solver;
let exprs =
List.map ~f:(expr_of ctx fenv dtenv) @@
List.filter_map cs ~f:(star and_flag)
in
z3_solver_add solver exprs;
Debug.print @@ lazy ( str_of_asserts_of_solver solver ) ;
let c', has_changed' = simplify_formula solver ctx fenv dtenv c in
Z3.Solver.pop solver 1;
(match star and_flag c' with
| Some phi -> z3_solver_add solver [expr_of ctx fenv dtenv phi] | None -> ());
(c' :: cs'), (match cs with | _::tl -> tl | _ -> []),
has_changed || has_changed') in
Z3.Solver.pop solver 1;
let cs' = List.rev cs' in
Debug.print @@ lazy ( sprintf " compare Cs to Cs':\nCs : % s " ( String.concat_map_list ~sep:"\n\t " cs ~f : Formula.str_of ) ) ;
Debug.print @@ lazy ( sprintf " Cs ' : % s " ( String.concat_map_list ~sep:"\n\t " cs ' ~f : Formula.str_of ) ) ;
let ret = Evaluator.simplify @@ if and_flag then Formula.and_of cs' else Formula.or_of cs' in
if has_changed then begin
fst @@ check_sub_formulas solver ctx fenv dtenv and_flag ret, true
end else ret, false
and simplify_formula solver ctx fenv (dtenv:dtenv) phi =
Debug.print @@ lazy ( str_of_asserts_of_solver solver ) ;
match phi with
| Formula.Atom (atom, _) when not (Atom.is_true atom || Atom.is_false atom) ->
let atom, has_changed = simplify_atom solver ctx fenv dtenv atom in
Formula.mk_atom atom, has_changed
| Formula.UnaryOp (Not, Atom (atom, _), _)
when not (Atom.is_true atom || Atom.is_false atom) ->
let atom, has_changed = simplify_atom solver ctx fenv dtenv atom in
Formula.negate (Formula.mk_atom atom), has_changed
| Formula.BinaryOp (And, _, _, _) -> check_sub_formulas solver ctx fenv dtenv true phi
| Formula.BinaryOp (Or, _, _, _) -> check_sub_formulas solver ctx fenv dtenv false phi
| Formula.LetFormula (var, sort, def, body, info) ->
let def, _ = simplify_term solver ctx fenv dtenv def in
let body, has_changed = simplify_formula solver ctx fenv dtenv body in
Formula.LetFormula (var, sort, def, body, info), has_changed
| _ -> phi, false
and simplify ?(timeout=None) ~id fenv phi =
Debug.print @@ lazy ("===========simplify start=============");
Debug.print @@ lazy (sprintf "the formula:\n %s" @@ Formula.str_of phi);
let cfg = ["model", "true"] in
let instance = get_instance id cfg instance_pool in
let ctx, solver = instance.ctx, instance.solver in
instance.dtenv <- (z3_dtenv_of ~init:(instance.dtenv) ctx phi);
instance.fenv <- (z3_fenv_of ~init:(instance.fenv) ctx [] [] fenv instance.dtenv);
Debug.print @@ lazy ( sprintf " the smtlib2 formua:\n\t%s " @@ ) ;
(match timeout with
| None -> ()
| Some timeout ->
let params = Z3.Params.mk_params ctx in
Z3.Params.add_int params (Z3.Symbol.mk_string ctx "timeout") timeout;
Z3.Solver.set_parameters solver params);
let phi = Normalizer.normalize_let phi in
let ret =
z3_simplify ~id fenv @@
fst @@ simplify_formula solver ctx instance.fenv instance.dtenv @@
z3_simplify ~id fenv @@
Formula.nnf_of phi
in
Debug.print @@ lazy (sprintf "result:\n %s\n===========simplify end=============" @@ Formula.str_of ret);
back_instance ~reset:(fun instance -> z3_solver_reset instance.solver) instance_pool id instance;
ret
let of_formula_with_z3fenv = of_formula
of_formula ctx env penv (z3_fenv_of ctx env penv fenv dtenv) dtenv phi
|
c6a5e49c080de1d0289f58ab826b5557f3e3ef59bf4bb1dede49c7ddfcb6f6f4
|
ocamllabs/ocaml-modular-implicits
|
ast_helper.mli
|
(***********************************************************************)
(* *)
(* OCaml *)
(* *)
, LexiFi
(* *)
Copyright 2012 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the Q Public License version 1.0 .
(* *)
(***********************************************************************)
* Helpers to produce Parsetree fragments
open Parsetree
open Asttypes
type lid = Longident.t loc
type str = string loc
type loc = Location.t
type attrs = attribute list
* { 2 Default locations }
val default_loc: loc ref
(** Default value for all optional location arguments. *)
val with_default_loc: loc -> (unit -> 'a) -> 'a
(** Set the [default_loc] within the scope of the execution
of the provided function. *)
* { 2 Core language }
(** Type expressions *)
module Typ :
sig
val mk: ?loc:loc -> ?attrs:attrs -> core_type_desc -> core_type
val attr: core_type -> attribute -> core_type
val any: ?loc:loc -> ?attrs:attrs -> unit -> core_type
val var: ?loc:loc -> ?attrs:attrs -> string -> core_type
val arrow: ?loc:loc -> ?attrs:attrs -> arrow_flag -> core_type -> core_type
-> core_type
val tuple: ?loc:loc -> ?attrs:attrs -> core_type list -> core_type
val constr: ?loc:loc -> ?attrs:attrs -> lid -> core_type list -> core_type
val object_: ?loc:loc -> ?attrs:attrs ->
(string * attributes * core_type) list -> closed_flag ->
core_type
val class_: ?loc:loc -> ?attrs:attrs -> lid -> core_type list -> core_type
val alias: ?loc:loc -> ?attrs:attrs -> core_type -> string -> core_type
val variant: ?loc:loc -> ?attrs:attrs -> row_field list -> closed_flag
-> label list option -> core_type
val poly: ?loc:loc -> ?attrs:attrs -> string list -> core_type -> core_type
val package: ?loc:loc -> ?attrs:attrs -> lid -> (lid * core_type) list
-> core_type
val extension: ?loc:loc -> ?attrs:attrs -> extension -> core_type
val force_poly: core_type -> core_type
end
(** Patterns *)
module Pat:
sig
val mk: ?loc:loc -> ?attrs:attrs -> pattern_desc -> pattern
val attr:pattern -> attribute -> pattern
val any: ?loc:loc -> ?attrs:attrs -> unit -> pattern
val var: ?loc:loc -> ?attrs:attrs -> str -> pattern
val alias: ?loc:loc -> ?attrs:attrs -> pattern -> str -> pattern
val constant: ?loc:loc -> ?attrs:attrs -> constant -> pattern
val interval: ?loc:loc -> ?attrs:attrs -> constant -> constant -> pattern
val tuple: ?loc:loc -> ?attrs:attrs -> pattern list -> pattern
val construct: ?loc:loc -> ?attrs:attrs -> lid -> pattern option -> pattern
val variant: ?loc:loc -> ?attrs:attrs -> label -> pattern option -> pattern
val record: ?loc:loc -> ?attrs:attrs -> (lid * pattern) list -> closed_flag
-> pattern
val array: ?loc:loc -> ?attrs:attrs -> pattern list -> pattern
val or_: ?loc:loc -> ?attrs:attrs -> pattern -> pattern -> pattern
val constraint_: ?loc:loc -> ?attrs:attrs -> pattern -> core_type -> pattern
val type_: ?loc:loc -> ?attrs:attrs -> lid -> pattern
val lazy_: ?loc:loc -> ?attrs:attrs -> pattern -> pattern
val unpack: ?loc:loc -> ?attrs:attrs -> str -> pattern
val exception_: ?loc:loc -> ?attrs:attrs -> pattern -> pattern
val extension: ?loc:loc -> ?attrs:attrs -> extension -> pattern
end
(** Expressions *)
module Exp:
sig
val mk: ?loc:loc -> ?attrs:attrs -> expression_desc -> expression
val attr: expression -> attribute -> expression
val ident: ?loc:loc -> ?attrs:attrs -> lid -> expression
val constant: ?loc:loc -> ?attrs:attrs -> constant -> expression
val let_: ?loc:loc -> ?attrs:attrs -> rec_flag -> value_binding list
-> expression -> expression
val fun_: ?loc:loc -> ?attrs:attrs -> arrow_flag -> expression option
-> pattern -> expression -> expression
val function_: ?loc:loc -> ?attrs:attrs -> case list -> expression
val apply: ?loc:loc -> ?attrs:attrs -> expression
-> (apply_flag * expression) list -> expression
val match_: ?loc:loc -> ?attrs:attrs -> expression -> case list
-> expression
val try_: ?loc:loc -> ?attrs:attrs -> expression -> case list -> expression
val tuple: ?loc:loc -> ?attrs:attrs -> expression list -> expression
val construct: ?loc:loc -> ?attrs:attrs -> lid -> expression option
-> expression
val variant: ?loc:loc -> ?attrs:attrs -> label -> expression option
-> expression
val record: ?loc:loc -> ?attrs:attrs -> (lid * expression) list
-> expression option -> expression
val field: ?loc:loc -> ?attrs:attrs -> expression -> lid -> expression
val setfield: ?loc:loc -> ?attrs:attrs -> expression -> lid -> expression
-> expression
val array: ?loc:loc -> ?attrs:attrs -> expression list -> expression
val ifthenelse: ?loc:loc -> ?attrs:attrs -> expression -> expression
-> expression option -> expression
val sequence: ?loc:loc -> ?attrs:attrs -> expression -> expression
-> expression
val while_: ?loc:loc -> ?attrs:attrs -> expression -> expression
-> expression
val for_: ?loc:loc -> ?attrs:attrs -> pattern -> expression -> expression
-> direction_flag -> expression -> expression
val coerce: ?loc:loc -> ?attrs:attrs -> expression -> core_type option
-> core_type -> expression
val constraint_: ?loc:loc -> ?attrs:attrs -> expression -> core_type
-> expression
val send: ?loc:loc -> ?attrs:attrs -> expression -> string -> expression
val new_: ?loc:loc -> ?attrs:attrs -> lid -> expression
val setinstvar: ?loc:loc -> ?attrs:attrs -> str -> expression -> expression
val override: ?loc:loc -> ?attrs:attrs -> (str * expression) list
-> expression
val letmodule: ?loc:loc -> ?attrs:attrs -> module_binding -> expression
-> expression
val assert_: ?loc:loc -> ?attrs:attrs -> expression -> expression
val lazy_: ?loc:loc -> ?attrs:attrs -> expression -> expression
val poly: ?loc:loc -> ?attrs:attrs -> expression -> core_type option -> expression
val object_: ?loc:loc -> ?attrs:attrs -> class_structure -> expression
val newtype: ?loc:loc -> ?attrs:attrs -> string -> expression -> expression
val pack: ?loc:loc -> ?attrs:attrs -> module_expr -> expression
val open_: ?loc:loc -> ?attrs:attrs -> open_flag -> lid -> expression -> expression
val extension: ?loc:loc -> ?attrs:attrs -> extension -> expression
val case: pattern -> ?guard:expression -> expression -> case
end
(** Value declarations *)
module Val:
sig
val mk: ?loc:loc -> ?attrs:attrs -> ?prim:string list -> str -> core_type -> value_description
end
(** Type declarations *)
module Type:
sig
val mk: ?loc:loc -> ?attrs:attrs -> ?params:(core_type * variance) list -> ?cstrs:(core_type * core_type * loc) list -> ?kind:type_kind -> ?priv:private_flag -> ?manifest:core_type -> str -> type_declaration
val constructor: ?loc:loc -> ?attrs:attrs -> ?args:core_type list -> ?res:core_type -> str -> constructor_declaration
val field: ?loc:loc -> ?attrs:attrs -> ?mut:mutable_flag -> str -> core_type -> label_declaration
end
(** Type extensions *)
module Te:
sig
val mk: ?attrs:attrs -> ?params:(core_type * variance) list -> ?priv:private_flag -> lid -> extension_constructor list -> type_extension
val constructor: ?loc:loc -> ?attrs:attrs -> str -> extension_constructor_kind -> extension_constructor
val decl: ?loc:loc -> ?attrs:attrs -> ?args:core_type list -> ?res:core_type -> str -> extension_constructor
val rebind: ?loc:loc -> ?attrs:attrs -> str -> lid -> extension_constructor
end
* { 2 Module language }
(** Module type expressions *)
module Mty:
sig
val mk: ?loc:loc -> ?attrs:attrs -> module_type_desc -> module_type
val attr: module_type -> attribute -> module_type
val ident: ?loc:loc -> ?attrs:attrs -> lid -> module_type
val alias: ?loc:loc -> ?attrs:attrs -> lid -> module_type
val signature: ?loc:loc -> ?attrs:attrs -> signature -> module_type
val functor_: ?loc:loc -> ?attrs:attrs ->
module_parameter -> module_type -> module_type
val with_: ?loc:loc -> ?attrs:attrs -> module_type -> with_constraint list -> module_type
val typeof_: ?loc:loc -> ?attrs:attrs -> module_expr -> module_type
val extension: ?loc:loc -> ?attrs:attrs -> extension -> module_type
end
(** Module expressions *)
module Mod:
sig
val mk: ?loc:loc -> ?attrs:attrs -> module_expr_desc -> module_expr
val attr: module_expr -> attribute -> module_expr
val ident: ?loc:loc -> ?attrs:attrs -> lid -> module_expr
val structure: ?loc:loc -> ?attrs:attrs -> structure -> module_expr
val functor_: ?loc:loc -> ?attrs:attrs ->
module_parameter -> module_expr -> module_expr
val apply: ?loc:loc -> ?attrs:attrs -> module_expr ->
module_argument -> module_expr
val constraint_: ?loc:loc -> ?attrs:attrs -> module_expr -> module_type -> module_expr
val unpack: ?loc:loc -> ?attrs:attrs -> expression -> module_expr
val extension: ?loc:loc -> ?attrs:attrs -> extension -> module_expr
end
(** Signature items *)
module Sig:
sig
val mk: ?loc:loc -> signature_item_desc -> signature_item
val value: ?loc:loc -> value_description -> signature_item
val type_: ?loc:loc -> type_declaration list -> signature_item
val type_extension: ?loc:loc -> type_extension -> signature_item
val exception_: ?loc:loc -> extension_constructor -> signature_item
val module_: ?loc:loc -> module_declaration -> signature_item
val rec_module: ?loc:loc -> module_declaration list -> signature_item
val modtype: ?loc:loc -> module_type_declaration -> signature_item
val open_: ?loc:loc -> open_description -> signature_item
val include_: ?loc:loc -> include_description -> signature_item
val class_: ?loc:loc -> class_description list -> signature_item
val class_type: ?loc:loc -> class_type_declaration list -> signature_item
val extension: ?loc:loc -> ?attrs:attrs -> extension -> signature_item
val attribute: ?loc:loc -> attribute -> signature_item
end
(** Structure items *)
module Str:
sig
val mk: ?loc:loc -> structure_item_desc -> structure_item
val eval: ?loc:loc -> ?attrs:attributes -> expression -> structure_item
val value: ?loc:loc -> rec_flag -> value_binding list -> structure_item
val primitive: ?loc:loc -> value_description -> structure_item
val type_: ?loc:loc -> type_declaration list -> structure_item
val type_extension: ?loc:loc -> type_extension -> structure_item
val exception_: ?loc:loc -> extension_constructor -> structure_item
val module_: ?loc:loc -> module_binding -> structure_item
val rec_module: ?loc:loc -> module_binding list -> structure_item
val modtype: ?loc:loc -> module_type_declaration -> structure_item
val open_: ?loc:loc -> open_description -> structure_item
val class_: ?loc:loc -> class_declaration list -> structure_item
val class_type: ?loc:loc -> class_type_declaration list -> structure_item
val include_: ?loc:loc -> include_declaration -> structure_item
val extension: ?loc:loc -> ?attrs:attrs -> extension -> structure_item
val attribute: ?loc:loc -> attribute -> structure_item
end
(** Module declarations *)
module Md:
sig
val mk: ?loc:loc -> ?attrs:attrs -> ?implicit_:implicit_flag -> str -> module_type -> module_declaration
end
(** Module type declarations *)
module Mtd:
sig
val mk: ?loc:loc -> ?attrs:attrs -> ?typ:module_type -> str -> module_type_declaration
end
(** Module bindings *)
module Mb:
sig
val mk: ?loc:loc -> ?attrs:attrs -> ?implicit_:implicit_flag -> str -> module_expr -> module_binding
end
Opens
module Opn:
sig
val mk: ?loc: loc -> ?attrs:attrs -> ?flag:open_flag -> lid -> open_description
end
(* Includes *)
module Incl:
sig
val mk: ?loc: loc -> ?attrs:attrs -> 'a -> 'a include_infos
end
(** Value bindings *)
module Vb:
sig
val mk: ?loc: loc -> ?attrs:attrs -> pattern -> expression -> value_binding
end
* { 2 Class language }
(** Class type expressions *)
module Cty:
sig
val mk: ?loc:loc -> ?attrs:attrs -> class_type_desc -> class_type
val attr: class_type -> attribute -> class_type
val constr: ?loc:loc -> ?attrs:attrs -> lid -> core_type list -> class_type
val signature: ?loc:loc -> ?attrs:attrs -> class_signature -> class_type
val arrow: ?loc:loc -> ?attrs:attrs -> arrow_flag -> core_type -> class_type -> class_type
val extension: ?loc:loc -> ?attrs:attrs -> extension -> class_type
end
(** Class type fields *)
module Ctf:
sig
val mk: ?loc:loc -> ?attrs:attrs -> class_type_field_desc -> class_type_field
val attr: class_type_field -> attribute -> class_type_field
val inherit_: ?loc:loc -> ?attrs:attrs -> class_type -> class_type_field
val val_: ?loc:loc -> ?attrs:attrs -> string -> mutable_flag -> virtual_flag -> core_type -> class_type_field
val method_: ?loc:loc -> ?attrs:attrs -> string -> private_flag -> virtual_flag -> core_type -> class_type_field
val constraint_: ?loc:loc -> ?attrs:attrs -> core_type -> core_type -> class_type_field
val extension: ?loc:loc -> ?attrs:attrs -> extension -> class_type_field
val attribute: ?loc:loc -> attribute -> class_type_field
end
(** Class expressions *)
module Cl:
sig
val mk: ?loc:loc -> ?attrs:attrs -> class_expr_desc -> class_expr
val attr: class_expr -> attribute -> class_expr
val constr: ?loc:loc -> ?attrs:attrs -> lid -> core_type list -> class_expr
val structure: ?loc:loc -> ?attrs:attrs -> class_structure -> class_expr
val fun_: ?loc:loc -> ?attrs:attrs -> arrow_flag -> expression option -> pattern -> class_expr -> class_expr
val apply: ?loc:loc -> ?attrs:attrs -> class_expr -> (apply_flag * expression) list -> class_expr
val let_: ?loc:loc -> ?attrs:attrs -> rec_flag -> value_binding list -> class_expr -> class_expr
val constraint_: ?loc:loc -> ?attrs:attrs -> class_expr -> class_type -> class_expr
val extension: ?loc:loc -> ?attrs:attrs -> extension -> class_expr
end
(** Class fields *)
module Cf:
sig
val mk: ?loc:loc -> ?attrs:attrs -> class_field_desc -> class_field
val attr: class_field -> attribute -> class_field
val inherit_: ?loc:loc -> ?attrs:attrs -> override_flag -> class_expr -> string option -> class_field
val val_: ?loc:loc -> ?attrs:attrs -> str -> mutable_flag -> class_field_kind -> class_field
val method_: ?loc:loc -> ?attrs:attrs -> str -> private_flag -> class_field_kind -> class_field
val constraint_: ?loc:loc -> ?attrs:attrs -> core_type -> core_type -> class_field
val initializer_: ?loc:loc -> ?attrs:attrs -> expression -> class_field
val extension: ?loc:loc -> ?attrs:attrs -> extension -> class_field
val attribute: ?loc:loc -> attribute -> class_field
val virtual_: core_type -> class_field_kind
val concrete: override_flag -> expression -> class_field_kind
end
(** Classes *)
module Ci:
sig
val mk: ?loc:loc -> ?attrs:attrs -> ?virt:virtual_flag -> ?params:(core_type * variance) list -> str -> 'a -> 'a class_infos
end
(** Class signatures *)
module Csig:
sig
val mk: core_type -> class_type_field list -> class_signature
end
(** Class structures *)
module Cstr:
sig
val mk: pattern -> class_field list -> class_structure
end
| null |
https://raw.githubusercontent.com/ocamllabs/ocaml-modular-implicits/92e45da5c8a4c2db8b2cd5be28a5bec2ac2181f1/parsing/ast_helper.mli
|
ocaml
|
*********************************************************************
OCaml
*********************************************************************
* Default value for all optional location arguments.
* Set the [default_loc] within the scope of the execution
of the provided function.
* Type expressions
* Patterns
* Expressions
* Value declarations
* Type declarations
* Type extensions
* Module type expressions
* Module expressions
* Signature items
* Structure items
* Module declarations
* Module type declarations
* Module bindings
Includes
* Value bindings
* Class type expressions
* Class type fields
* Class expressions
* Class fields
* Classes
* Class signatures
* Class structures
|
, LexiFi
Copyright 2012 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the Q Public License version 1.0 .
* Helpers to produce Parsetree fragments
open Parsetree
open Asttypes
type lid = Longident.t loc
type str = string loc
type loc = Location.t
type attrs = attribute list
* { 2 Default locations }
val default_loc: loc ref
val with_default_loc: loc -> (unit -> 'a) -> 'a
* { 2 Core language }
module Typ :
sig
val mk: ?loc:loc -> ?attrs:attrs -> core_type_desc -> core_type
val attr: core_type -> attribute -> core_type
val any: ?loc:loc -> ?attrs:attrs -> unit -> core_type
val var: ?loc:loc -> ?attrs:attrs -> string -> core_type
val arrow: ?loc:loc -> ?attrs:attrs -> arrow_flag -> core_type -> core_type
-> core_type
val tuple: ?loc:loc -> ?attrs:attrs -> core_type list -> core_type
val constr: ?loc:loc -> ?attrs:attrs -> lid -> core_type list -> core_type
val object_: ?loc:loc -> ?attrs:attrs ->
(string * attributes * core_type) list -> closed_flag ->
core_type
val class_: ?loc:loc -> ?attrs:attrs -> lid -> core_type list -> core_type
val alias: ?loc:loc -> ?attrs:attrs -> core_type -> string -> core_type
val variant: ?loc:loc -> ?attrs:attrs -> row_field list -> closed_flag
-> label list option -> core_type
val poly: ?loc:loc -> ?attrs:attrs -> string list -> core_type -> core_type
val package: ?loc:loc -> ?attrs:attrs -> lid -> (lid * core_type) list
-> core_type
val extension: ?loc:loc -> ?attrs:attrs -> extension -> core_type
val force_poly: core_type -> core_type
end
module Pat:
sig
val mk: ?loc:loc -> ?attrs:attrs -> pattern_desc -> pattern
val attr:pattern -> attribute -> pattern
val any: ?loc:loc -> ?attrs:attrs -> unit -> pattern
val var: ?loc:loc -> ?attrs:attrs -> str -> pattern
val alias: ?loc:loc -> ?attrs:attrs -> pattern -> str -> pattern
val constant: ?loc:loc -> ?attrs:attrs -> constant -> pattern
val interval: ?loc:loc -> ?attrs:attrs -> constant -> constant -> pattern
val tuple: ?loc:loc -> ?attrs:attrs -> pattern list -> pattern
val construct: ?loc:loc -> ?attrs:attrs -> lid -> pattern option -> pattern
val variant: ?loc:loc -> ?attrs:attrs -> label -> pattern option -> pattern
val record: ?loc:loc -> ?attrs:attrs -> (lid * pattern) list -> closed_flag
-> pattern
val array: ?loc:loc -> ?attrs:attrs -> pattern list -> pattern
val or_: ?loc:loc -> ?attrs:attrs -> pattern -> pattern -> pattern
val constraint_: ?loc:loc -> ?attrs:attrs -> pattern -> core_type -> pattern
val type_: ?loc:loc -> ?attrs:attrs -> lid -> pattern
val lazy_: ?loc:loc -> ?attrs:attrs -> pattern -> pattern
val unpack: ?loc:loc -> ?attrs:attrs -> str -> pattern
val exception_: ?loc:loc -> ?attrs:attrs -> pattern -> pattern
val extension: ?loc:loc -> ?attrs:attrs -> extension -> pattern
end
module Exp:
sig
val mk: ?loc:loc -> ?attrs:attrs -> expression_desc -> expression
val attr: expression -> attribute -> expression
val ident: ?loc:loc -> ?attrs:attrs -> lid -> expression
val constant: ?loc:loc -> ?attrs:attrs -> constant -> expression
val let_: ?loc:loc -> ?attrs:attrs -> rec_flag -> value_binding list
-> expression -> expression
val fun_: ?loc:loc -> ?attrs:attrs -> arrow_flag -> expression option
-> pattern -> expression -> expression
val function_: ?loc:loc -> ?attrs:attrs -> case list -> expression
val apply: ?loc:loc -> ?attrs:attrs -> expression
-> (apply_flag * expression) list -> expression
val match_: ?loc:loc -> ?attrs:attrs -> expression -> case list
-> expression
val try_: ?loc:loc -> ?attrs:attrs -> expression -> case list -> expression
val tuple: ?loc:loc -> ?attrs:attrs -> expression list -> expression
val construct: ?loc:loc -> ?attrs:attrs -> lid -> expression option
-> expression
val variant: ?loc:loc -> ?attrs:attrs -> label -> expression option
-> expression
val record: ?loc:loc -> ?attrs:attrs -> (lid * expression) list
-> expression option -> expression
val field: ?loc:loc -> ?attrs:attrs -> expression -> lid -> expression
val setfield: ?loc:loc -> ?attrs:attrs -> expression -> lid -> expression
-> expression
val array: ?loc:loc -> ?attrs:attrs -> expression list -> expression
val ifthenelse: ?loc:loc -> ?attrs:attrs -> expression -> expression
-> expression option -> expression
val sequence: ?loc:loc -> ?attrs:attrs -> expression -> expression
-> expression
val while_: ?loc:loc -> ?attrs:attrs -> expression -> expression
-> expression
val for_: ?loc:loc -> ?attrs:attrs -> pattern -> expression -> expression
-> direction_flag -> expression -> expression
val coerce: ?loc:loc -> ?attrs:attrs -> expression -> core_type option
-> core_type -> expression
val constraint_: ?loc:loc -> ?attrs:attrs -> expression -> core_type
-> expression
val send: ?loc:loc -> ?attrs:attrs -> expression -> string -> expression
val new_: ?loc:loc -> ?attrs:attrs -> lid -> expression
val setinstvar: ?loc:loc -> ?attrs:attrs -> str -> expression -> expression
val override: ?loc:loc -> ?attrs:attrs -> (str * expression) list
-> expression
val letmodule: ?loc:loc -> ?attrs:attrs -> module_binding -> expression
-> expression
val assert_: ?loc:loc -> ?attrs:attrs -> expression -> expression
val lazy_: ?loc:loc -> ?attrs:attrs -> expression -> expression
val poly: ?loc:loc -> ?attrs:attrs -> expression -> core_type option -> expression
val object_: ?loc:loc -> ?attrs:attrs -> class_structure -> expression
val newtype: ?loc:loc -> ?attrs:attrs -> string -> expression -> expression
val pack: ?loc:loc -> ?attrs:attrs -> module_expr -> expression
val open_: ?loc:loc -> ?attrs:attrs -> open_flag -> lid -> expression -> expression
val extension: ?loc:loc -> ?attrs:attrs -> extension -> expression
val case: pattern -> ?guard:expression -> expression -> case
end
module Val:
sig
val mk: ?loc:loc -> ?attrs:attrs -> ?prim:string list -> str -> core_type -> value_description
end
module Type:
sig
val mk: ?loc:loc -> ?attrs:attrs -> ?params:(core_type * variance) list -> ?cstrs:(core_type * core_type * loc) list -> ?kind:type_kind -> ?priv:private_flag -> ?manifest:core_type -> str -> type_declaration
val constructor: ?loc:loc -> ?attrs:attrs -> ?args:core_type list -> ?res:core_type -> str -> constructor_declaration
val field: ?loc:loc -> ?attrs:attrs -> ?mut:mutable_flag -> str -> core_type -> label_declaration
end
module Te:
sig
val mk: ?attrs:attrs -> ?params:(core_type * variance) list -> ?priv:private_flag -> lid -> extension_constructor list -> type_extension
val constructor: ?loc:loc -> ?attrs:attrs -> str -> extension_constructor_kind -> extension_constructor
val decl: ?loc:loc -> ?attrs:attrs -> ?args:core_type list -> ?res:core_type -> str -> extension_constructor
val rebind: ?loc:loc -> ?attrs:attrs -> str -> lid -> extension_constructor
end
* { 2 Module language }
module Mty:
sig
val mk: ?loc:loc -> ?attrs:attrs -> module_type_desc -> module_type
val attr: module_type -> attribute -> module_type
val ident: ?loc:loc -> ?attrs:attrs -> lid -> module_type
val alias: ?loc:loc -> ?attrs:attrs -> lid -> module_type
val signature: ?loc:loc -> ?attrs:attrs -> signature -> module_type
val functor_: ?loc:loc -> ?attrs:attrs ->
module_parameter -> module_type -> module_type
val with_: ?loc:loc -> ?attrs:attrs -> module_type -> with_constraint list -> module_type
val typeof_: ?loc:loc -> ?attrs:attrs -> module_expr -> module_type
val extension: ?loc:loc -> ?attrs:attrs -> extension -> module_type
end
module Mod:
sig
val mk: ?loc:loc -> ?attrs:attrs -> module_expr_desc -> module_expr
val attr: module_expr -> attribute -> module_expr
val ident: ?loc:loc -> ?attrs:attrs -> lid -> module_expr
val structure: ?loc:loc -> ?attrs:attrs -> structure -> module_expr
val functor_: ?loc:loc -> ?attrs:attrs ->
module_parameter -> module_expr -> module_expr
val apply: ?loc:loc -> ?attrs:attrs -> module_expr ->
module_argument -> module_expr
val constraint_: ?loc:loc -> ?attrs:attrs -> module_expr -> module_type -> module_expr
val unpack: ?loc:loc -> ?attrs:attrs -> expression -> module_expr
val extension: ?loc:loc -> ?attrs:attrs -> extension -> module_expr
end
module Sig:
sig
val mk: ?loc:loc -> signature_item_desc -> signature_item
val value: ?loc:loc -> value_description -> signature_item
val type_: ?loc:loc -> type_declaration list -> signature_item
val type_extension: ?loc:loc -> type_extension -> signature_item
val exception_: ?loc:loc -> extension_constructor -> signature_item
val module_: ?loc:loc -> module_declaration -> signature_item
val rec_module: ?loc:loc -> module_declaration list -> signature_item
val modtype: ?loc:loc -> module_type_declaration -> signature_item
val open_: ?loc:loc -> open_description -> signature_item
val include_: ?loc:loc -> include_description -> signature_item
val class_: ?loc:loc -> class_description list -> signature_item
val class_type: ?loc:loc -> class_type_declaration list -> signature_item
val extension: ?loc:loc -> ?attrs:attrs -> extension -> signature_item
val attribute: ?loc:loc -> attribute -> signature_item
end
module Str:
sig
val mk: ?loc:loc -> structure_item_desc -> structure_item
val eval: ?loc:loc -> ?attrs:attributes -> expression -> structure_item
val value: ?loc:loc -> rec_flag -> value_binding list -> structure_item
val primitive: ?loc:loc -> value_description -> structure_item
val type_: ?loc:loc -> type_declaration list -> structure_item
val type_extension: ?loc:loc -> type_extension -> structure_item
val exception_: ?loc:loc -> extension_constructor -> structure_item
val module_: ?loc:loc -> module_binding -> structure_item
val rec_module: ?loc:loc -> module_binding list -> structure_item
val modtype: ?loc:loc -> module_type_declaration -> structure_item
val open_: ?loc:loc -> open_description -> structure_item
val class_: ?loc:loc -> class_declaration list -> structure_item
val class_type: ?loc:loc -> class_type_declaration list -> structure_item
val include_: ?loc:loc -> include_declaration -> structure_item
val extension: ?loc:loc -> ?attrs:attrs -> extension -> structure_item
val attribute: ?loc:loc -> attribute -> structure_item
end
module Md:
sig
val mk: ?loc:loc -> ?attrs:attrs -> ?implicit_:implicit_flag -> str -> module_type -> module_declaration
end
module Mtd:
sig
val mk: ?loc:loc -> ?attrs:attrs -> ?typ:module_type -> str -> module_type_declaration
end
module Mb:
sig
val mk: ?loc:loc -> ?attrs:attrs -> ?implicit_:implicit_flag -> str -> module_expr -> module_binding
end
Opens
module Opn:
sig
val mk: ?loc: loc -> ?attrs:attrs -> ?flag:open_flag -> lid -> open_description
end
module Incl:
sig
val mk: ?loc: loc -> ?attrs:attrs -> 'a -> 'a include_infos
end
module Vb:
sig
val mk: ?loc: loc -> ?attrs:attrs -> pattern -> expression -> value_binding
end
* { 2 Class language }
module Cty:
sig
val mk: ?loc:loc -> ?attrs:attrs -> class_type_desc -> class_type
val attr: class_type -> attribute -> class_type
val constr: ?loc:loc -> ?attrs:attrs -> lid -> core_type list -> class_type
val signature: ?loc:loc -> ?attrs:attrs -> class_signature -> class_type
val arrow: ?loc:loc -> ?attrs:attrs -> arrow_flag -> core_type -> class_type -> class_type
val extension: ?loc:loc -> ?attrs:attrs -> extension -> class_type
end
module Ctf:
sig
val mk: ?loc:loc -> ?attrs:attrs -> class_type_field_desc -> class_type_field
val attr: class_type_field -> attribute -> class_type_field
val inherit_: ?loc:loc -> ?attrs:attrs -> class_type -> class_type_field
val val_: ?loc:loc -> ?attrs:attrs -> string -> mutable_flag -> virtual_flag -> core_type -> class_type_field
val method_: ?loc:loc -> ?attrs:attrs -> string -> private_flag -> virtual_flag -> core_type -> class_type_field
val constraint_: ?loc:loc -> ?attrs:attrs -> core_type -> core_type -> class_type_field
val extension: ?loc:loc -> ?attrs:attrs -> extension -> class_type_field
val attribute: ?loc:loc -> attribute -> class_type_field
end
module Cl:
sig
val mk: ?loc:loc -> ?attrs:attrs -> class_expr_desc -> class_expr
val attr: class_expr -> attribute -> class_expr
val constr: ?loc:loc -> ?attrs:attrs -> lid -> core_type list -> class_expr
val structure: ?loc:loc -> ?attrs:attrs -> class_structure -> class_expr
val fun_: ?loc:loc -> ?attrs:attrs -> arrow_flag -> expression option -> pattern -> class_expr -> class_expr
val apply: ?loc:loc -> ?attrs:attrs -> class_expr -> (apply_flag * expression) list -> class_expr
val let_: ?loc:loc -> ?attrs:attrs -> rec_flag -> value_binding list -> class_expr -> class_expr
val constraint_: ?loc:loc -> ?attrs:attrs -> class_expr -> class_type -> class_expr
val extension: ?loc:loc -> ?attrs:attrs -> extension -> class_expr
end
module Cf:
sig
val mk: ?loc:loc -> ?attrs:attrs -> class_field_desc -> class_field
val attr: class_field -> attribute -> class_field
val inherit_: ?loc:loc -> ?attrs:attrs -> override_flag -> class_expr -> string option -> class_field
val val_: ?loc:loc -> ?attrs:attrs -> str -> mutable_flag -> class_field_kind -> class_field
val method_: ?loc:loc -> ?attrs:attrs -> str -> private_flag -> class_field_kind -> class_field
val constraint_: ?loc:loc -> ?attrs:attrs -> core_type -> core_type -> class_field
val initializer_: ?loc:loc -> ?attrs:attrs -> expression -> class_field
val extension: ?loc:loc -> ?attrs:attrs -> extension -> class_field
val attribute: ?loc:loc -> attribute -> class_field
val virtual_: core_type -> class_field_kind
val concrete: override_flag -> expression -> class_field_kind
end
module Ci:
sig
val mk: ?loc:loc -> ?attrs:attrs -> ?virt:virtual_flag -> ?params:(core_type * variance) list -> str -> 'a -> 'a class_infos
end
module Csig:
sig
val mk: core_type -> class_type_field list -> class_signature
end
module Cstr:
sig
val mk: pattern -> class_field list -> class_structure
end
|
698e71bce6dba64eba2071663995865448a1386381b7c654e5011f16bb9a049a
|
essdotteedot/distributed
|
distributed.mli
|
(** This module provides modules to create distribtued computations.
Distributed comutations are described using the {!module-type:Process}.
{!module-type:Process} provides a monadic interface to describe distributed computations.
@author essdotteedot <essdotteedot_at_gmail_dot_com>
@version 0.6.0
*)
* Some nomenclature :
- Node : A node corresponds to a operating system process . There can be many nodes on a
single machine .
- Process : A process corresponds to a light weight thread ( i.e. , user space cooperative threads ) .
There can be many processes on a single Node .
- Node : A node corresponds to a operating system process. There can be many nodes on a
single machine.
- Process : A process corresponds to a light weight thread (i.e., user space cooperative threads).
There can be many processes on a single Node.
*)
(** This module provides a type representing a node id. *)
module Node_id : sig
type t
(** The abstract type representing a node id. *)
val get_name : t -> string
* [ node ] returns the name of the node .
end
(** This module provides a type representing a process id. *)
module Process_id : sig
type t
(** The abstract type representing a process id. *)
end
* Abstract type which can perform monadic concurrent IO .
module type Nonblock_io = sig
type 'a t
(** The monadic light weight thread type returning value ['a]. *)
type 'a stream
(** An unbounded stream holding values of ['a]. *)
type input_channel
(** A type to represent a non-blocking input channel *)
type output_channel
(** A type to represent a non-blocking output channel *)
type server
(** A type to represent a server *)
exception Timeout
* Exception raised by { ! : timeout } operation
type level = Debug
| Info
| Warning
| Error
(** Type to represent levels of a log message. *)
val lib_name : string
(** The name of the implementation, for logging purposes. *)
val lib_version : string
(** The version implementation, for logging purposes. *)
val lib_description : string
(** A description of the implementation (e.g., the url of the code repository ), for logging purposes. *)
val return : 'a -> 'a t
(** [return v] creates a light weight thread returning [v]. *)
val (>>=) : 'a t -> ('a -> 'b t) -> 'b t
* [ bind t f ] is a thread which first waits for the thread [ t ] to terminate and then , if the thread succeeds ,
behaves as the application of function [ f ] to the return value of [ t ] . If the thread [ t ] fails , [ bind t f ] also fails ,
with the same exception .
behaves as the application of function [f] to the return value of [t]. If the thread [t] fails, [bind t f] also fails,
with the same exception.
*)
val fail : exn -> 'a t
(** [fail e] is a thread that fails with the exception [e]. *)
val catch : (unit -> 'a t) -> (exn -> 'a t) -> 'a t
(** [catch t f] is a thread that behaves as the thread [t ()] if this thread succeeds.
If the thread [t ()] fails with some exception, [catch t f] behaves as the application of [f] to this exception.
*)
val async : (unit -> unit t) -> unit
(** [async f starts] a thread without waiting for the result. *)
val create_stream : unit -> 'a stream * ('a option -> unit)
(** [create ()] returns a new stream and a push function. *)
val get : 'a stream -> 'a option t
* [ get st ] removes and returns the first element of the stream , if any . Will block if the stream is empty .
val stream_append : 'a stream -> 'a stream -> 'a stream
(** [stream_append s1 s2] returns a [stream] which returns all elements of [s1], then all elements of [s2]. *)
val close_input : input_channel -> unit t
(** [close ch] closes the given channel immediately. *)
val close_output : output_channel -> unit t
(** [close ch] closes the given channel. It performs all pending actions, flushes it and closes it. *)
val read_value : input_channel -> 'a t
(** [read_value ic] reads a marshalled value from [ic]. *)
val write_value : output_channel -> ?flags:Marshal.extern_flags list -> 'a -> unit t
(** [write_value oc ?flags x] marshals the value [x] to [oc]. *)
val open_connection : Unix.sockaddr -> (input_channel * output_channel) t
* [ open_connection addr ] opens a connection to the given address and returns two channels for using it .
val establish_server : ?backlog:int -> Unix.sockaddr -> (Unix.sockaddr -> input_channel * output_channel -> unit t) -> server t
(** [establish_server ?backlog sockaddr f] creates a server which will listen for incoming connections.
New connections are passed to [f]. Note that [f] must not raise any exception. Backlog is the argument passed to Lwt_unix.listen.
*)
val shutdown_server : server -> unit t
(** [shutdown_server server] will shutdown [server]. *)
val log : level -> (unit -> string) -> unit t
(** [log level message_formatter] logs a message at the specified level using the formatter provided. *)
val sleep : float -> unit t
(** [sleep d] is a thread that remains suspended for [d] seconds and then terminates. *)
val timeout : float -> 'a t
(** [timeout d] is a thread that remains suspended for [d] seconds and then fails with {!exception:Distributed.Nonblock_io.Timeout}. *)
val pick : 'a t list -> 'a t
* [ pick l ] behaves as the first thread in l to terminate . If several threads are already terminated , one is chosen at random . Cancels all sleeping threads when one terminates .
val at_exit : (unit -> unit t) -> unit
(** [at_exit fn] will call fn on program exit. *)
end
(** The abstract type representing the messages that will be sent between processes. *)
module type Message_type = sig
type t
(** Abstract type representing the messages that will be sent between processes. *)
val string_of_message : t -> string
(** [string_of_message msg] returns the [string] representation of [msg]. *)
end
(** A unit of computation which can be executed on a local or remote host, is monadic. *)
module type Process = sig
exception Init_more_than_once
* Exception that is raised if { ! : run_node } is called more than once .
exception InvalidNode of Node_id.t
* Exception that is raised when { ! : spawn } , { ! : broadcast } , { ! : monitor } are called with an invalid node or if { ! : send }
is called with a process which resides on an unknown node .
is called with a process which resides on an unknown node.
*)
exception Local_only_mode
* Exception that is raised when { ! : add_remote_node } or { ! : remove_remote_node } is called on a node that is operating in local only mode .
type 'a t
(** The abstract monadic type representing a computation returning ['a]. *)
type 'a io
* Abstract type for monadic concurrent IO returning [ ' a ] .
type message_type
(** The abstract type representing the messages that will be sent between processes. *)
type 'a matcher_list
* The abstract type representing a non - empty list of matchers to be used with { ! : receive } function .
type monitor_ref
(** The abstract type representing a monitor_ref that is returned when a processes is monitored and can be used to unmonitor it. *)
type monitor_reason = Normal of Process_id.t (** Process terminated normally. *)
| Exception of Process_id.t * exn (** Process terminated with exception. *)
| UnkownNodeId of Process_id.t * Node_id.t (** An operation failed because the remote node id is unknown. *)
| NoProcess of Process_id.t (** Attempted to monitor a process that does not exist. *)
(** Reason for process termination. *)
(** The configuration of a node to be run as a remote node i.e., one that can both send an receive messages with other nodes. *)
module Remote_config : sig
type t = { remote_nodes : (string * int * string) list ; (** The initial list of remote nodes which this node can send messages to. A list of external ip address/port/node name triplets.*)
local_port : int ; (** The port that this node should run on. *)
connection_backlog : int ; (** The the argument used when listening on a socket. *)
node_name : string ; (** The name of this node. *)
node_ip : string ; (** The external ip address of this node. *)
}
end
(** The configuration of a node to be run as a local node i.e., one that can not send or receive messages with other nodes. *)
module Local_config : sig
type t = { node_name : string ; (** The name of this node. *)
}
end
(** The configuration of a node. Can be one of {!node_config.Local} or {!node_config.Remote}. *)
type node_config = Local of Local_config.t
| Remote of Remote_config.t
val return : 'a -> 'a t
(** [return v] creates a computation returning [v]. *)
val (>>=) : 'a t -> ('a -> 'b t) -> 'b t
* [ c > > = f ] is a computation which first waits for the computation [ c ] to terminate and then , if the computation succeeds ,
behaves as the application of function [ f ] to the return value of [ c ] . If the computation [ c ] fails , [ c > > = f ] also fails ,
with the same exception .
behaves as the application of function [f] to the return value of [c]. If the computation [c] fails, [c >>= f] also fails,
with the same exception.
*)
val fail : exn -> 'a t
(** [fail e] is a process that fails with the exception [e]. *)
val catch : (unit -> 'a t) -> (exn -> 'a t) -> 'a t
(** [catch p f] is a process that behaves as the process [p ()] if this process succeeds.
If the process [p ()] fails with some exception, [catch p f] behaves as the application of [f] to this exception.
*)
val spawn : ?monitor:bool -> Node_id.t -> (unit -> unit t) -> (Process_id.t * monitor_ref option) t
* [ spawn monitor name node_id process ] will spawn [ process ] on [ node_id ] returning the { ! type : Process_id.t } associated with the newly spawned process .
If [ monitor ] is true ( default value is false ) then the spawned process will also be monitored and the associated { ! type : monitor_ref } will be
returned .
If [ node_id ] is an unknown node then { ! exception : InvalidNode } exception is raised .
If [monitor] is true (default value is false) then the spawned process will also be monitored and the associated {!type:monitor_ref} will be
returned.
If [node_id] is an unknown node then {!exception:InvalidNode} exception is raised.
*)
val case : (message_type -> (unit -> 'a t) option) -> 'a matcher_list
* [ case will create a { ! type : matcher_list } which will use [ match_fn ] to match on potential messages .
[ match_fn ] should return [ None ] to indicate no match or [ Some handler ] where [ handler ] is the function
that should be called to handle the matching message .
[match_fn] should return [None] to indicate no match or [Some handler] where [handler] is the function
that should be called to handle the matching message.
*)
val termination_case : (monitor_reason -> 'a t) -> 'a matcher_list
* [ termination_case handler ] will create a { ! type : matcher_list } which can use used to match against [ termination_reason ] for a
process that is being monitored . If this process is monitoring another process then providing this matcher in the list
of matchers to { ! : receive } will allow this process to act on the termination of the monitored process .
NOTE : when a remote process ( i.e. , one running on another node ) raises an exception you will not be able
to pattern match on the exception . This is a limitation of the Marshal OCaml module :
" Values of extensible variant types , for example exceptions ( of extensible type exn ) , returned by the unmarshaller
should not be pattern - matched over through [ match ... with ] or [ try ... with ] , because unmarshalling does not preserve the
information required for matching their constructors . Structural equalities with other extensible variant values does not work either .
Most other uses such as Printexc.to_string , will still work as expected . "
See -ocaml/libref/Marshal.html .
process that is being monitored. If this process is monitoring another process then providing this matcher in the list
of matchers to {!val:receive} will allow this process to act on the termination of the monitored process.
NOTE : when a remote process (i.e., one running on another node) raises an exception you will not be able
to pattern match on the exception . This is a limitation of the Marshal OCaml module :
" Values of extensible variant types, for example exceptions (of extensible type exn), returned by the unmarshaller
should not be pattern-matched over through [match ... with] or [try ... with], because unmarshalling does not preserve the
information required for matching their constructors. Structural equalities with other extensible variant values does not work either.
Most other uses such as Printexc.to_string, will still work as expected. "
See -ocaml/libref/Marshal.html.
*)
val (|.) : 'a matcher_list -> 'a matcher_list -> 'a matcher_list
(** [a_matcher |. b_matcher] is a {!type:matcher_list} consiting of the matchers in [a_matcher] followed by the matchers
in [b_matcher].
*)
val receive : ?timeout_duration:float -> 'a matcher_list -> 'a option t
* [ receive timeout matchers ] will wait for a message to be sent to this process which matches one of matchers provided in
[ matchers ] . The first matching matcher in [ matchers ] will used process the matching message returning [ Some result ] where
[ result ] is result of the matcher processing the matched message . All the other non - matching messages are left in the same
order they came in .
If a time out is provided and no matching messages has arrived in the time out period then None will be returned .
If the [ matchers ] is empty then an { ! exception : Empty_matchers } exception is raised .
[matchers]. The first matching matcher in [matchers] will used process the matching message returning [Some result] where
[result] is result of the matcher processing the matched message. All the other non-matching messages are left in the same
order they came in.
If a time out is provided and no matching messages has arrived in the time out period then None will be returned.
If the [matchers] is empty then an {!exception:Empty_matchers} exception is raised.
*)
val receive_loop : ?timeout_duration:float -> bool matcher_list -> unit t
(** [receive_loop timeout matchers] is a convenience function which will loop until a matcher in [matchers] returns false. *)
val send : Process_id.t -> message_type -> unit t
* [ send process_id msg ] will send , asynchronously , message [ msg ] to the process with i d [ process_id ] ( possibly running on a remote node ) .
If [ process_id ] is resides on an unknown node then { ! exception : InvalidNode } exception is raised .
If [ process_id ] is an unknown process but the node on which it resides is known then send will still succeed ( i.e. , will not raise any exceptions ) .
If [process_id] is resides on an unknown node then {!exception:InvalidNode} exception is raised.
If [process_id] is an unknown process but the node on which it resides is known then send will still succeed (i.e., will not raise any exceptions).
*)
val (>!) : Process_id.t -> message_type -> unit t
(** [pid >! msg] is equivalent to [send pid msg]. [>!] is an infix alias for [send]. *)
val broadcast : Node_id.t -> message_type -> unit t
* [ broadcast node_id msg ] will send , asynchronously , message [ msg ] to all the processes on [ node_id ] .
If [ node_id ] is an unknown node then { ! exception : InvalidNode } exception is raised .
If [node_id] is an unknown node then {!exception:InvalidNode} exception is raised.
*)
val monitor : Process_id.t -> monitor_ref t
* [ monitor pid ] will allows the calling process to monitor [ pid ] . When [ pid ] terminates ( normally or abnormally ) this monitoring
process will receive a [ termination_reason ] message , which can be matched in [ receive ] using [ termination_matcher ] . A single
process can be monitored my multiple processes .
If [ process_id ] is resides on an unknown node then { ! exception : InvalidNode } exception is raised .
process will receive a [termination_reason] message, which can be matched in [receive] using [termination_matcher]. A single
process can be monitored my multiple processes.
If [process_id] is resides on an unknown node then {!exception:InvalidNode} exception is raised.
*)
val unmonitor : monitor_ref -> unit t
* [ unmonitor ] will cause this process to stop monitoring the process which is referenced by [ ] .
If the current process is not monitoring the process referenced by [ ] then [ unmonitor ] is a no - op .
If process being unmonitored as indicated by [ monitor_ref ] is resides on an unknown node then { ! exception : InvalidNode } exception is raised .
If the current process is not monitoring the process referenced by [mref] then [unmonitor] is a no-op.
If process being unmonitored as indicated by [monitor_ref] is resides on an unknown node then {!exception:InvalidNode} exception is raised.
*)
val get_self_pid : Process_id.t t
(** [get_self_pid process] will return the process id associated with [process]. *)
val get_self_node : Node_id.t t
(** [get_self_node process] will return the node id associated with [process]. *)
val get_remote_node : string -> Node_id.t option t
(** [get_remote_node node_name] will return the node id associated with [name], if there is no record of a node with [name] at
this time then [None] is returned.
*)
val get_remote_nodes : Node_id.t list t
(** The list of all nodes currently active and inactive. *)
val add_remote_node : string -> int -> string -> Node_id.t t
(** [add_remote_node ip port name] will connect to the remote node at [ip]:[port] with name [name] and add it to the current nodes list of connected remote nodes.
The newly added node id is returned as the result. Adding a remote node that already exists is a no-op.
If the node is operating in local only mode then {!exception:Local_only_mode} is raised.
*)
val remove_remote_node : Node_id.t -> unit t
(** [remove_remote_node node_id] will remove [node_id] from the list of connected remote nodes.
If the node is operating in local only mode then {!exception:Local_only_mode} is raised.
*)
val lift_io : 'a io -> 'a t
(** [lift_io io] lifts the [io] computation into the process. *)
val run_node : ?process:(unit -> unit t) -> node_config -> unit io
(** [run_node process node_monitor_fn node_config] performs the necessary bootstrapping to start this
node according to [node_config]. If provided, runs the initial [process] returning the resulting [io].
If it's called more than once then an exception of {!exception:Init_more_than_once} is raised.
*)
end
module Make (I : Nonblock_io) (M : Message_type) : (Process with type message_type = M.t and type 'a io = 'a I.t)
(** Functor to create a module of type {!module-type:Process} given a message module [M] of type {!module-type:Message_type}. *)
| null |
https://raw.githubusercontent.com/essdotteedot/distributed/bce5906d87b28afa3d7fca4b069753667045b749/src/distributed.mli
|
ocaml
|
* This module provides modules to create distribtued computations.
Distributed comutations are described using the {!module-type:Process}.
{!module-type:Process} provides a monadic interface to describe distributed computations.
@author essdotteedot <essdotteedot_at_gmail_dot_com>
@version 0.6.0
* This module provides a type representing a node id.
* The abstract type representing a node id.
* This module provides a type representing a process id.
* The abstract type representing a process id.
* The monadic light weight thread type returning value ['a].
* An unbounded stream holding values of ['a].
* A type to represent a non-blocking input channel
* A type to represent a non-blocking output channel
* A type to represent a server
* Type to represent levels of a log message.
* The name of the implementation, for logging purposes.
* The version implementation, for logging purposes.
* A description of the implementation (e.g., the url of the code repository ), for logging purposes.
* [return v] creates a light weight thread returning [v].
* [fail e] is a thread that fails with the exception [e].
* [catch t f] is a thread that behaves as the thread [t ()] if this thread succeeds.
If the thread [t ()] fails with some exception, [catch t f] behaves as the application of [f] to this exception.
* [async f starts] a thread without waiting for the result.
* [create ()] returns a new stream and a push function.
* [stream_append s1 s2] returns a [stream] which returns all elements of [s1], then all elements of [s2].
* [close ch] closes the given channel immediately.
* [close ch] closes the given channel. It performs all pending actions, flushes it and closes it.
* [read_value ic] reads a marshalled value from [ic].
* [write_value oc ?flags x] marshals the value [x] to [oc].
* [establish_server ?backlog sockaddr f] creates a server which will listen for incoming connections.
New connections are passed to [f]. Note that [f] must not raise any exception. Backlog is the argument passed to Lwt_unix.listen.
* [shutdown_server server] will shutdown [server].
* [log level message_formatter] logs a message at the specified level using the formatter provided.
* [sleep d] is a thread that remains suspended for [d] seconds and then terminates.
* [timeout d] is a thread that remains suspended for [d] seconds and then fails with {!exception:Distributed.Nonblock_io.Timeout}.
* [at_exit fn] will call fn on program exit.
* The abstract type representing the messages that will be sent between processes.
* Abstract type representing the messages that will be sent between processes.
* [string_of_message msg] returns the [string] representation of [msg].
* A unit of computation which can be executed on a local or remote host, is monadic.
* The abstract monadic type representing a computation returning ['a].
* The abstract type representing the messages that will be sent between processes.
* The abstract type representing a monitor_ref that is returned when a processes is monitored and can be used to unmonitor it.
* Process terminated normally.
* Process terminated with exception.
* An operation failed because the remote node id is unknown.
* Attempted to monitor a process that does not exist.
* Reason for process termination.
* The configuration of a node to be run as a remote node i.e., one that can both send an receive messages with other nodes.
* The initial list of remote nodes which this node can send messages to. A list of external ip address/port/node name triplets.
* The port that this node should run on.
* The the argument used when listening on a socket.
* The name of this node.
* The external ip address of this node.
* The configuration of a node to be run as a local node i.e., one that can not send or receive messages with other nodes.
* The name of this node.
* The configuration of a node. Can be one of {!node_config.Local} or {!node_config.Remote}.
* [return v] creates a computation returning [v].
* [fail e] is a process that fails with the exception [e].
* [catch p f] is a process that behaves as the process [p ()] if this process succeeds.
If the process [p ()] fails with some exception, [catch p f] behaves as the application of [f] to this exception.
* [a_matcher |. b_matcher] is a {!type:matcher_list} consiting of the matchers in [a_matcher] followed by the matchers
in [b_matcher].
* [receive_loop timeout matchers] is a convenience function which will loop until a matcher in [matchers] returns false.
* [pid >! msg] is equivalent to [send pid msg]. [>!] is an infix alias for [send].
* [get_self_pid process] will return the process id associated with [process].
* [get_self_node process] will return the node id associated with [process].
* [get_remote_node node_name] will return the node id associated with [name], if there is no record of a node with [name] at
this time then [None] is returned.
* The list of all nodes currently active and inactive.
* [add_remote_node ip port name] will connect to the remote node at [ip]:[port] with name [name] and add it to the current nodes list of connected remote nodes.
The newly added node id is returned as the result. Adding a remote node that already exists is a no-op.
If the node is operating in local only mode then {!exception:Local_only_mode} is raised.
* [remove_remote_node node_id] will remove [node_id] from the list of connected remote nodes.
If the node is operating in local only mode then {!exception:Local_only_mode} is raised.
* [lift_io io] lifts the [io] computation into the process.
* [run_node process node_monitor_fn node_config] performs the necessary bootstrapping to start this
node according to [node_config]. If provided, runs the initial [process] returning the resulting [io].
If it's called more than once then an exception of {!exception:Init_more_than_once} is raised.
* Functor to create a module of type {!module-type:Process} given a message module [M] of type {!module-type:Message_type}.
|
* Some nomenclature :
- Node : A node corresponds to a operating system process . There can be many nodes on a
single machine .
- Process : A process corresponds to a light weight thread ( i.e. , user space cooperative threads ) .
There can be many processes on a single Node .
- Node : A node corresponds to a operating system process. There can be many nodes on a
single machine.
- Process : A process corresponds to a light weight thread (i.e., user space cooperative threads).
There can be many processes on a single Node.
*)
module Node_id : sig
type t
val get_name : t -> string
* [ node ] returns the name of the node .
end
module Process_id : sig
type t
end
* Abstract type which can perform monadic concurrent IO .
module type Nonblock_io = sig
type 'a t
type 'a stream
type input_channel
type output_channel
type server
exception Timeout
* Exception raised by { ! : timeout } operation
type level = Debug
| Info
| Warning
| Error
val lib_name : string
val lib_version : string
val lib_description : string
val return : 'a -> 'a t
val (>>=) : 'a t -> ('a -> 'b t) -> 'b t
* [ bind t f ] is a thread which first waits for the thread [ t ] to terminate and then , if the thread succeeds ,
behaves as the application of function [ f ] to the return value of [ t ] . If the thread [ t ] fails , [ bind t f ] also fails ,
with the same exception .
behaves as the application of function [f] to the return value of [t]. If the thread [t] fails, [bind t f] also fails,
with the same exception.
*)
val fail : exn -> 'a t
val catch : (unit -> 'a t) -> (exn -> 'a t) -> 'a t
val async : (unit -> unit t) -> unit
val create_stream : unit -> 'a stream * ('a option -> unit)
val get : 'a stream -> 'a option t
* [ get st ] removes and returns the first element of the stream , if any . Will block if the stream is empty .
val stream_append : 'a stream -> 'a stream -> 'a stream
val close_input : input_channel -> unit t
val close_output : output_channel -> unit t
val read_value : input_channel -> 'a t
val write_value : output_channel -> ?flags:Marshal.extern_flags list -> 'a -> unit t
val open_connection : Unix.sockaddr -> (input_channel * output_channel) t
* [ open_connection addr ] opens a connection to the given address and returns two channels for using it .
val establish_server : ?backlog:int -> Unix.sockaddr -> (Unix.sockaddr -> input_channel * output_channel -> unit t) -> server t
val shutdown_server : server -> unit t
val log : level -> (unit -> string) -> unit t
val sleep : float -> unit t
val timeout : float -> 'a t
val pick : 'a t list -> 'a t
* [ pick l ] behaves as the first thread in l to terminate . If several threads are already terminated , one is chosen at random . Cancels all sleeping threads when one terminates .
val at_exit : (unit -> unit t) -> unit
end
module type Message_type = sig
type t
val string_of_message : t -> string
end
module type Process = sig
exception Init_more_than_once
* Exception that is raised if { ! : run_node } is called more than once .
exception InvalidNode of Node_id.t
* Exception that is raised when { ! : spawn } , { ! : broadcast } , { ! : monitor } are called with an invalid node or if { ! : send }
is called with a process which resides on an unknown node .
is called with a process which resides on an unknown node.
*)
exception Local_only_mode
* Exception that is raised when { ! : add_remote_node } or { ! : remove_remote_node } is called on a node that is operating in local only mode .
type 'a t
type 'a io
* Abstract type for monadic concurrent IO returning [ ' a ] .
type message_type
type 'a matcher_list
* The abstract type representing a non - empty list of matchers to be used with { ! : receive } function .
type monitor_ref
module Remote_config : sig
}
end
module Local_config : sig
}
end
type node_config = Local of Local_config.t
| Remote of Remote_config.t
val return : 'a -> 'a t
val (>>=) : 'a t -> ('a -> 'b t) -> 'b t
* [ c > > = f ] is a computation which first waits for the computation [ c ] to terminate and then , if the computation succeeds ,
behaves as the application of function [ f ] to the return value of [ c ] . If the computation [ c ] fails , [ c > > = f ] also fails ,
with the same exception .
behaves as the application of function [f] to the return value of [c]. If the computation [c] fails, [c >>= f] also fails,
with the same exception.
*)
val fail : exn -> 'a t
val catch : (unit -> 'a t) -> (exn -> 'a t) -> 'a t
val spawn : ?monitor:bool -> Node_id.t -> (unit -> unit t) -> (Process_id.t * monitor_ref option) t
* [ spawn monitor name node_id process ] will spawn [ process ] on [ node_id ] returning the { ! type : Process_id.t } associated with the newly spawned process .
If [ monitor ] is true ( default value is false ) then the spawned process will also be monitored and the associated { ! type : monitor_ref } will be
returned .
If [ node_id ] is an unknown node then { ! exception : InvalidNode } exception is raised .
If [monitor] is true (default value is false) then the spawned process will also be monitored and the associated {!type:monitor_ref} will be
returned.
If [node_id] is an unknown node then {!exception:InvalidNode} exception is raised.
*)
val case : (message_type -> (unit -> 'a t) option) -> 'a matcher_list
* [ case will create a { ! type : matcher_list } which will use [ match_fn ] to match on potential messages .
[ match_fn ] should return [ None ] to indicate no match or [ Some handler ] where [ handler ] is the function
that should be called to handle the matching message .
[match_fn] should return [None] to indicate no match or [Some handler] where [handler] is the function
that should be called to handle the matching message.
*)
val termination_case : (monitor_reason -> 'a t) -> 'a matcher_list
* [ termination_case handler ] will create a { ! type : matcher_list } which can use used to match against [ termination_reason ] for a
process that is being monitored . If this process is monitoring another process then providing this matcher in the list
of matchers to { ! : receive } will allow this process to act on the termination of the monitored process .
NOTE : when a remote process ( i.e. , one running on another node ) raises an exception you will not be able
to pattern match on the exception . This is a limitation of the Marshal OCaml module :
" Values of extensible variant types , for example exceptions ( of extensible type exn ) , returned by the unmarshaller
should not be pattern - matched over through [ match ... with ] or [ try ... with ] , because unmarshalling does not preserve the
information required for matching their constructors . Structural equalities with other extensible variant values does not work either .
Most other uses such as Printexc.to_string , will still work as expected . "
See -ocaml/libref/Marshal.html .
process that is being monitored. If this process is monitoring another process then providing this matcher in the list
of matchers to {!val:receive} will allow this process to act on the termination of the monitored process.
NOTE : when a remote process (i.e., one running on another node) raises an exception you will not be able
to pattern match on the exception . This is a limitation of the Marshal OCaml module :
" Values of extensible variant types, for example exceptions (of extensible type exn), returned by the unmarshaller
should not be pattern-matched over through [match ... with] or [try ... with], because unmarshalling does not preserve the
information required for matching their constructors. Structural equalities with other extensible variant values does not work either.
Most other uses such as Printexc.to_string, will still work as expected. "
See -ocaml/libref/Marshal.html.
*)
val (|.) : 'a matcher_list -> 'a matcher_list -> 'a matcher_list
val receive : ?timeout_duration:float -> 'a matcher_list -> 'a option t
* [ receive timeout matchers ] will wait for a message to be sent to this process which matches one of matchers provided in
[ matchers ] . The first matching matcher in [ matchers ] will used process the matching message returning [ Some result ] where
[ result ] is result of the matcher processing the matched message . All the other non - matching messages are left in the same
order they came in .
If a time out is provided and no matching messages has arrived in the time out period then None will be returned .
If the [ matchers ] is empty then an { ! exception : Empty_matchers } exception is raised .
[matchers]. The first matching matcher in [matchers] will used process the matching message returning [Some result] where
[result] is result of the matcher processing the matched message. All the other non-matching messages are left in the same
order they came in.
If a time out is provided and no matching messages has arrived in the time out period then None will be returned.
If the [matchers] is empty then an {!exception:Empty_matchers} exception is raised.
*)
val receive_loop : ?timeout_duration:float -> bool matcher_list -> unit t
val send : Process_id.t -> message_type -> unit t
* [ send process_id msg ] will send , asynchronously , message [ msg ] to the process with i d [ process_id ] ( possibly running on a remote node ) .
If [ process_id ] is resides on an unknown node then { ! exception : InvalidNode } exception is raised .
If [ process_id ] is an unknown process but the node on which it resides is known then send will still succeed ( i.e. , will not raise any exceptions ) .
If [process_id] is resides on an unknown node then {!exception:InvalidNode} exception is raised.
If [process_id] is an unknown process but the node on which it resides is known then send will still succeed (i.e., will not raise any exceptions).
*)
val (>!) : Process_id.t -> message_type -> unit t
val broadcast : Node_id.t -> message_type -> unit t
* [ broadcast node_id msg ] will send , asynchronously , message [ msg ] to all the processes on [ node_id ] .
If [ node_id ] is an unknown node then { ! exception : InvalidNode } exception is raised .
If [node_id] is an unknown node then {!exception:InvalidNode} exception is raised.
*)
val monitor : Process_id.t -> monitor_ref t
* [ monitor pid ] will allows the calling process to monitor [ pid ] . When [ pid ] terminates ( normally or abnormally ) this monitoring
process will receive a [ termination_reason ] message , which can be matched in [ receive ] using [ termination_matcher ] . A single
process can be monitored my multiple processes .
If [ process_id ] is resides on an unknown node then { ! exception : InvalidNode } exception is raised .
process will receive a [termination_reason] message, which can be matched in [receive] using [termination_matcher]. A single
process can be monitored my multiple processes.
If [process_id] is resides on an unknown node then {!exception:InvalidNode} exception is raised.
*)
val unmonitor : monitor_ref -> unit t
* [ unmonitor ] will cause this process to stop monitoring the process which is referenced by [ ] .
If the current process is not monitoring the process referenced by [ ] then [ unmonitor ] is a no - op .
If process being unmonitored as indicated by [ monitor_ref ] is resides on an unknown node then { ! exception : InvalidNode } exception is raised .
If the current process is not monitoring the process referenced by [mref] then [unmonitor] is a no-op.
If process being unmonitored as indicated by [monitor_ref] is resides on an unknown node then {!exception:InvalidNode} exception is raised.
*)
val get_self_pid : Process_id.t t
val get_self_node : Node_id.t t
val get_remote_node : string -> Node_id.t option t
val get_remote_nodes : Node_id.t list t
val add_remote_node : string -> int -> string -> Node_id.t t
val remove_remote_node : Node_id.t -> unit t
val lift_io : 'a io -> 'a t
val run_node : ?process:(unit -> unit t) -> node_config -> unit io
end
module Make (I : Nonblock_io) (M : Message_type) : (Process with type message_type = M.t and type 'a io = 'a I.t)
|
6a02032db9fe56799236533266ce084f7876d6534e49ab25f605db9b5b2b6379
|
racket/gui
|
platform.rkt
|
#lang racket/base
(require "init.rkt"
"button.rkt"
"canvas.rkt"
"check-box.rkt"
"choice.rkt"
"clipboard.rkt"
"cursor.rkt"
"dialog.rkt"
"frame.rkt"
"gauge.rkt"
"group-panel.rkt"
"item.rkt"
"list-box.rkt"
"menu.rkt"
"menu-bar.rkt"
"menu-item.rkt"
"message.rkt"
"panel.rkt"
"printer-dc.rkt"
"radio-box.rkt"
"slider.rkt"
"tab-panel.rkt"
"window.rkt"
"procs.rkt")
(provide
(protect-out platform-values))
(define (platform-values)
(values
button%
canvas%
canvas-panel%
check-box%
choice%
clipboard-driver%
cursor-driver%
dialog%
frame%
gauge%
group-panel%
item%
list-box%
menu%
menu-bar%
menu-item%
message%
panel%
printer-dc%
radio-box%
slider%
tab-panel%
window%
can-show-print-setup?
show-print-setup
id-to-menu-item
file-selector
is-color-display?
get-display-depth
has-x-selection?
hide-cursor
bell
display-size
display-origin
display-count
display-bitmap-resolution
flush-display
get-current-mouse-state
fill-private-color
cancel-quit
get-control-font-face
get-control-font-size
get-control-font-size-in-pixels?
get-double-click-time
file-creator-and-type
location->window
shortcut-visible-in-label?
unregister-collecting-blit
register-collecting-blit
find-graphical-system-path
play-sound
get-panel-background
font-from-user-platform-mode
get-font-from-user
color-from-user-platform-mode
get-color-from-user
special-option-key
special-control-key
any-control+alt-is-altgr
get-highlight-background-color
get-highlight-text-color
get-label-foreground-color
get-label-background-color
make-screen-bitmap
make-gl-bitmap
check-for-break
key-symbol-to-menu-key
needs-grow-box-spacer?
graphical-system-type
white-on-black-panel-scheme?))
| null |
https://raw.githubusercontent.com/racket/gui/1386c815512906250443e50212e0816717cc493b/gui-lib/mred/private/wx/gtk/platform.rkt
|
racket
|
#lang racket/base
(require "init.rkt"
"button.rkt"
"canvas.rkt"
"check-box.rkt"
"choice.rkt"
"clipboard.rkt"
"cursor.rkt"
"dialog.rkt"
"frame.rkt"
"gauge.rkt"
"group-panel.rkt"
"item.rkt"
"list-box.rkt"
"menu.rkt"
"menu-bar.rkt"
"menu-item.rkt"
"message.rkt"
"panel.rkt"
"printer-dc.rkt"
"radio-box.rkt"
"slider.rkt"
"tab-panel.rkt"
"window.rkt"
"procs.rkt")
(provide
(protect-out platform-values))
(define (platform-values)
(values
button%
canvas%
canvas-panel%
check-box%
choice%
clipboard-driver%
cursor-driver%
dialog%
frame%
gauge%
group-panel%
item%
list-box%
menu%
menu-bar%
menu-item%
message%
panel%
printer-dc%
radio-box%
slider%
tab-panel%
window%
can-show-print-setup?
show-print-setup
id-to-menu-item
file-selector
is-color-display?
get-display-depth
has-x-selection?
hide-cursor
bell
display-size
display-origin
display-count
display-bitmap-resolution
flush-display
get-current-mouse-state
fill-private-color
cancel-quit
get-control-font-face
get-control-font-size
get-control-font-size-in-pixels?
get-double-click-time
file-creator-and-type
location->window
shortcut-visible-in-label?
unregister-collecting-blit
register-collecting-blit
find-graphical-system-path
play-sound
get-panel-background
font-from-user-platform-mode
get-font-from-user
color-from-user-platform-mode
get-color-from-user
special-option-key
special-control-key
any-control+alt-is-altgr
get-highlight-background-color
get-highlight-text-color
get-label-foreground-color
get-label-background-color
make-screen-bitmap
make-gl-bitmap
check-for-break
key-symbol-to-menu-key
needs-grow-box-spacer?
graphical-system-type
white-on-black-panel-scheme?))
|
|
99ce700d328bd07c3959fa27d43e62b18873997a6c8ffdafae33fcefd7b2003a
|
bzg/covid19-faq
|
test.clj
|
Copyright ( c ) 2020 DINUM , < >
SPDX - License - Identifier : EPL-2.0
;; License-Filename: LICENSES/EPL-2.0.txt
(ns covid19faq.test
(:require [clojure.test :refer :all]))
| null |
https://raw.githubusercontent.com/bzg/covid19-faq/89a3a74c000cbb14624d5e1bdc0569fccd0b9e67/test/covid19faq/test.clj
|
clojure
|
License-Filename: LICENSES/EPL-2.0.txt
|
Copyright ( c ) 2020 DINUM , < >
SPDX - License - Identifier : EPL-2.0
(ns covid19faq.test
(:require [clojure.test :refer :all]))
|
07e01a2fceaea023d22a0a0facc4ad40fa9fb23b33e10281dd2ba948ef14025a
|
damn/cdq
|
body_render.clj
|
(ns game.components.body-render
(:require [game.debug-settings :as debug]
[game.utils.geom :as geom]
[engine.render :as color])
(:use utils.core
[game.utils.tilemap :only (screenpos-of-tilepos)]
(engine core input render)
(game settings mouseoverbody)
(game.components core body destructible render ingame-loop)
(game.components.skills core melee)
game.utils.lightning)
(:import (org.newdawn.slick Color Image)))
(defn- melee-debug-info [g p body]
(when-let [meleecomp (get-skill body :melee)]
(let [target-body (get-entity (:target-body-id meleecomp))
start-attack-puffer (in-pixel (+ start-melee-puffer (get-half-width body)))
hit-puffer (in-pixel (+ melee-puffer (get-half-width body)))]
(when target-body
(set-color g (if (body-in-melee-range? body target-body false) color/red color/green))
(draw-shape g (geom/circle p start-attack-puffer))
(draw-shape g (geom/circle p hit-puffer))))))
(defn- render-body-debug-info [g [x y] body]
(when (and @debug-mode debug/show-body-debug-info)
;(render-readable-text g x y :shift false (str (get-id body)))
;(melee-debug-info g [x y] body)
; (when-let [c (get-skill body :melee)]
( render - readable - text g x y : shift false ( str (: state c ) ) ) )
(when-let [rangedcomp (get-skill body :ranged)]
(render-readable-text g x y :shift false (str (:state rangedcomp))))))
(defn- render-body-bounds [g body [x y] color]
(let [h-width (get-half-pxw body)
h-height (get-half-pxh body)
x (- x h-width)
y (- y h-height)]
(draw-rect g x y (* 2 h-width) (* 2 h-height) color)))
(def- hpbar-colors
{:green (rgbcolor :g 1 :darker 0.2)
:darkgreen (rgbcolor :g 1 :darker 0.5)
:yellow (rgbcolor :r 1 :g 1 :darker 0.5)
:red (rgbcolor :r 1 :darker 0.5)})
(defn- get-color-for-ratio [ratio]
(let [ratio (float ratio)
color (cond
(> ratio 0.75) :green
(> ratio 0.5) :darkgreen
(> ratio 0.25) :yellow
:else :red)]
(color hpbar-colors)))
(defn render-bar
([g x y w h ratio color]
(fill-rect g x y w h color/black)
(fill-rect g (inc x) (inc y) (* ratio (- w 2)) (- h 2) color))
([g x y w h current-val max-val color]
(render-bar g x y w h (get-ratio current-val max-val) color)))
(def- body-info-bars-h 3)
(defn- render-body-info-bar [g body [x y] ratio color ybuffer]
(let [half-w (int (get-half-pxw body))
half-h (int (get-half-pxh body))
h body-info-bars-h]
(render-bar g (- x half-w) (- y half-h ybuffer) (* 2 half-w) h ratio color)))
(defn- render-hp-bar [g body render-position]
(let [hp (get-hp body)
ratio (get-ratio hp)
color (get-color-for-ratio ratio)
color (if @active-lightning
(.darker ^Color color
(let [image (or
(:image (get-component body :image-render))
(get-frame (current-animation body)))
intensity (let [color (.getCornerColor ^Image image Image/TOP_LEFT)]
(/ (+ (.r color) (.g color) (.b color)) 3))]
(- 1 intensity)))
color)]
(render-body-info-bar g body render-position ratio color body-info-bars-h)))
(defn- render-attacking-bar [g body skill render-position]
(render-body-info-bar g body render-position (ratio (:attack-counter skill)) color/blue (* 2 body-info-bars-h)))
(defn body-renderfn [g body component {x 0 y 1 :as render-position}]
(let [tile-posi (get-position body)]
(when @debug-mode
(when debug/show-body-bounds
(render-body-bounds g body render-position color/white))
(render-body-debug-info g render-position body))
(when (not (is-player? body))
(when (destructible? body)
(render-hp-bar g body render-position))
(let [skillmanager (get-component body :skillmanager)
active-type (:active-type skillmanager)]
(when (and skillmanager
(#{:healing :monster-nova} active-type)
(is-attacking? skillmanager))
(render-attacking-bar g body (get-active-skill skillmanager) render-position)))
(when-let [component (find-first #(and (:show-cast-bar %) (is-attacking? %)) (get-components body))]
(render-attacking-bar g body component render-position)))))
(intern 'game.components.body 'body-info-renderfn body-renderfn)
;;;
(defpreload ^:private outlines {:green {:topleft (create-image "outline/tl.png" :scale 0.5)
:topright (create-image "outline/tr.png" :scale 0.5)
:bottomleft (create-image "outline/bl.png" :scale 0.5)
:bottomright (create-image "outline/br.png" :scale 0.5)}
:red {:topleft (create-image "outline/tl_r.png" :scale 0.5)
:topright (create-image "outline/tr_r.png" :scale 0.5)
:bottomleft (create-image "outline/bl_r.png" :scale 0.5)
:bottomright (create-image "outline/br_r.png" :scale 0.5)}})
(def body-outline-height 2)
; The corner is at pixel x4 y4 where the body outline corner is
(defn- draw-outline-shape [image x y]
(draw-image image (- x 2) (- y 2)))
(defn- render-body-outline [g body [x y] color]
(let [h-width (get-half-pxw body)
h-height (get-half-pxh body)
leftx (- x h-width)
rightx (+ x h-width)
topy (- y h-height)
bottomy (+ y h-height)]
(draw-outline-shape (:topleft (color outlines)) leftx topy)
(draw-outline-shape (:topright (color outlines)) rightx topy)
(draw-outline-shape (:bottomleft (color outlines)) leftx bottomy)
(draw-outline-shape (:bottomright (color outlines)) rightx bottomy)))
(ingame-loop-comp :body-outline
(rendering :below-gui [g c]
(when-let [body (get-mouseover-body)]
(when (:mouseover-outline (get-component body :body))
(let [p (screenpos-of-tilepos (get-position body))]
(render-body-outline g body p
(if (and (not (is-player? body))
(destructible? body))
:red
:green)))))))
; OR: current rendered image of body
= > make outline image = > draw over it ! ? .. costs 20 - 30 ms to make that would to cache it .. ! !
| null |
https://raw.githubusercontent.com/damn/cdq/5093dbdba91c445e403f53ce96ead05d5ed8262b/src/game/components/body_render.clj
|
clojure
|
(render-readable-text g x y :shift false (str (get-id body)))
(melee-debug-info g [x y] body)
(when-let [c (get-skill body :melee)]
The corner is at pixel x4 y4 where the body outline corner is
OR: current rendered image of body
|
(ns game.components.body-render
(:require [game.debug-settings :as debug]
[game.utils.geom :as geom]
[engine.render :as color])
(:use utils.core
[game.utils.tilemap :only (screenpos-of-tilepos)]
(engine core input render)
(game settings mouseoverbody)
(game.components core body destructible render ingame-loop)
(game.components.skills core melee)
game.utils.lightning)
(:import (org.newdawn.slick Color Image)))
(defn- melee-debug-info [g p body]
(when-let [meleecomp (get-skill body :melee)]
(let [target-body (get-entity (:target-body-id meleecomp))
start-attack-puffer (in-pixel (+ start-melee-puffer (get-half-width body)))
hit-puffer (in-pixel (+ melee-puffer (get-half-width body)))]
(when target-body
(set-color g (if (body-in-melee-range? body target-body false) color/red color/green))
(draw-shape g (geom/circle p start-attack-puffer))
(draw-shape g (geom/circle p hit-puffer))))))
(defn- render-body-debug-info [g [x y] body]
(when (and @debug-mode debug/show-body-debug-info)
( render - readable - text g x y : shift false ( str (: state c ) ) ) )
(when-let [rangedcomp (get-skill body :ranged)]
(render-readable-text g x y :shift false (str (:state rangedcomp))))))
(defn- render-body-bounds [g body [x y] color]
(let [h-width (get-half-pxw body)
h-height (get-half-pxh body)
x (- x h-width)
y (- y h-height)]
(draw-rect g x y (* 2 h-width) (* 2 h-height) color)))
(def- hpbar-colors
{:green (rgbcolor :g 1 :darker 0.2)
:darkgreen (rgbcolor :g 1 :darker 0.5)
:yellow (rgbcolor :r 1 :g 1 :darker 0.5)
:red (rgbcolor :r 1 :darker 0.5)})
(defn- get-color-for-ratio [ratio]
(let [ratio (float ratio)
color (cond
(> ratio 0.75) :green
(> ratio 0.5) :darkgreen
(> ratio 0.25) :yellow
:else :red)]
(color hpbar-colors)))
(defn render-bar
([g x y w h ratio color]
(fill-rect g x y w h color/black)
(fill-rect g (inc x) (inc y) (* ratio (- w 2)) (- h 2) color))
([g x y w h current-val max-val color]
(render-bar g x y w h (get-ratio current-val max-val) color)))
(def- body-info-bars-h 3)
(defn- render-body-info-bar [g body [x y] ratio color ybuffer]
(let [half-w (int (get-half-pxw body))
half-h (int (get-half-pxh body))
h body-info-bars-h]
(render-bar g (- x half-w) (- y half-h ybuffer) (* 2 half-w) h ratio color)))
(defn- render-hp-bar [g body render-position]
(let [hp (get-hp body)
ratio (get-ratio hp)
color (get-color-for-ratio ratio)
color (if @active-lightning
(.darker ^Color color
(let [image (or
(:image (get-component body :image-render))
(get-frame (current-animation body)))
intensity (let [color (.getCornerColor ^Image image Image/TOP_LEFT)]
(/ (+ (.r color) (.g color) (.b color)) 3))]
(- 1 intensity)))
color)]
(render-body-info-bar g body render-position ratio color body-info-bars-h)))
(defn- render-attacking-bar [g body skill render-position]
(render-body-info-bar g body render-position (ratio (:attack-counter skill)) color/blue (* 2 body-info-bars-h)))
(defn body-renderfn [g body component {x 0 y 1 :as render-position}]
(let [tile-posi (get-position body)]
(when @debug-mode
(when debug/show-body-bounds
(render-body-bounds g body render-position color/white))
(render-body-debug-info g render-position body))
(when (not (is-player? body))
(when (destructible? body)
(render-hp-bar g body render-position))
(let [skillmanager (get-component body :skillmanager)
active-type (:active-type skillmanager)]
(when (and skillmanager
(#{:healing :monster-nova} active-type)
(is-attacking? skillmanager))
(render-attacking-bar g body (get-active-skill skillmanager) render-position)))
(when-let [component (find-first #(and (:show-cast-bar %) (is-attacking? %)) (get-components body))]
(render-attacking-bar g body component render-position)))))
(intern 'game.components.body 'body-info-renderfn body-renderfn)
(defpreload ^:private outlines {:green {:topleft (create-image "outline/tl.png" :scale 0.5)
:topright (create-image "outline/tr.png" :scale 0.5)
:bottomleft (create-image "outline/bl.png" :scale 0.5)
:bottomright (create-image "outline/br.png" :scale 0.5)}
:red {:topleft (create-image "outline/tl_r.png" :scale 0.5)
:topright (create-image "outline/tr_r.png" :scale 0.5)
:bottomleft (create-image "outline/bl_r.png" :scale 0.5)
:bottomright (create-image "outline/br_r.png" :scale 0.5)}})
(def body-outline-height 2)
(defn- draw-outline-shape [image x y]
(draw-image image (- x 2) (- y 2)))
(defn- render-body-outline [g body [x y] color]
(let [h-width (get-half-pxw body)
h-height (get-half-pxh body)
leftx (- x h-width)
rightx (+ x h-width)
topy (- y h-height)
bottomy (+ y h-height)]
(draw-outline-shape (:topleft (color outlines)) leftx topy)
(draw-outline-shape (:topright (color outlines)) rightx topy)
(draw-outline-shape (:bottomleft (color outlines)) leftx bottomy)
(draw-outline-shape (:bottomright (color outlines)) rightx bottomy)))
(ingame-loop-comp :body-outline
(rendering :below-gui [g c]
(when-let [body (get-mouseover-body)]
(when (:mouseover-outline (get-component body :body))
(let [p (screenpos-of-tilepos (get-position body))]
(render-body-outline g body p
(if (and (not (is-player? body))
(destructible? body))
:red
:green)))))))
= > make outline image = > draw over it ! ? .. costs 20 - 30 ms to make that would to cache it .. ! !
|
16ed09cc71cb80f397c37b311dda862b37637c9e0d10570d7e1674c2d3bb3d48
|
jlouis/etorrent_core
|
etorrent_peer_send.erl
|
@author < >
%% @doc Handle outgoing messages to a peer
%% <p>This module handles all outgoing messaging for a peer. It
%% supports various API calls to facilitate this</p>
< p > Note that this module has two modes , < em > fast</em > and
< em > > . The fast mode outsources the packet encoding to the
%% C-layer, whereas the slow mode doesn't. The price to pay is that we
%% have a worse granularity on the rate calculations, so we only shift
%% into the fast gear when we have a certain amount of traffic going on.</p>
%% <p>The shift fast to slow, or slow to fast, is synchronized with
%% the process {@link etorrent_peer_recv}, so if altering the code,
%% beware of that</p>
%% @end
-module(etorrent_peer_send).
-behaviour(gen_server).
-include("etorrent_rate.hrl").
%% Apart from standard gen_server things, the main idea of this module is
%% to serve as a mediator for the peer in the send direction. Precisely,
%% we have a message we can send to the process, for each of the possible
%% messages one can send to a peer.
%% other functions
-export([start_link/3]).
%% message functions
-export([request/2,
piece/5,
cancel/4,
reject/4,
choke/1,
unchoke/1,
have/2,
not_interested/1,
interested/1,
ext_msg/2,
ext_setup/3,
bitfield/2,
port/2]).
%% gproc registry entries
-export([register_server/1,
lookup_server/1,
await_server/1]).
%% gen_server callbacks
-export([init/1,
handle_call/3,
handle_cast/2,
handle_info/2,
terminate/2,
code_change/3]).
-record(state, {
socket :: inet:socket(),
buffer :: queue(),
control :: pid(),
limiter :: none | pid(),
rate :: etorrent_rate:rate(),
torrent_id :: integer()}).
-define(DEFAULT_KEEP_ALIVE_INTERVAL, 120*1000). % From proto. spec.
Maximal number of requests a peer may make .
%% @doc Start the encoder process.
%% @end
-spec start_link(port(), integer(), boolean()) ->
ignore | {ok, pid()} | {error, any()}.
start_link(Socket, TorrentId, FastExtension) ->
gen_server:start_link(?MODULE,
[Socket, TorrentId, FastExtension], []).
%% @doc Register the local process as the encoder for a socket
-spec register_server(inet:socket()) -> true.
register_server(Socket) ->
etorrent_utils:register(server_name(Socket)).
%% @doc Lookup the encoder process for a socket
-spec lookup_server(inet:socket()) -> pid().
lookup_server(Socket) ->
etorrent_utils:lookup(server_name(Socket)).
%% @doc Wait for the encoder process for a socket to register
-spec await_server(inet:socket()) -> pid().
await_server(Socket) ->
etorrent_utils:await(server_name(Socket)).
@private Server name for encoder process .
server_name(Socket) ->
{etorrent, Socket, encoder}.
%% @doc send a REQUEST message to the remote peer.
%% @end
-spec request(pid(), {integer(), integer(), integer()}) -> ok.
request(Pid, {Index, Offset, Size}) ->
forward_message(Pid, {request, Index, Offset, Size}).
@doc send a PIECE message to the remote peer .
%% @end
-spec piece(pid(), integer(), integer(), integer(), binary()) -> ok.
piece(Pid, Index, Offset, Length, Data) when Length =:= byte_size(Data) ->
forward_message(Pid, {piece, Index, Offset, Data}).
%% @doc Send a CANCEL message to the remote peer.
%% @end
-spec cancel(pid(), integer(), integer(), integer()) -> ok.
cancel(Pid, Index, Offset, Len) ->
forward_message(Pid, {cancel, Index, Offset, Len}).
@doc Send a REJECT message to the remote peer .
%% @end
-spec reject(pid(), integer(), integer(), integer()) -> ok.
reject(Pid, Index, Offset, Length) ->
forward_message(Pid, {reject_request, Index, Offset, Length}).
%% @doc CHOKE the peer.
%% @end
-spec choke(pid()) -> ok.
choke(Pid) ->
forward_message(Pid, choke).
%% @doc UNCHOKE the peer.
%% end
-spec unchoke(pid()) -> ok.
unchoke(Pid) ->
forward_message(Pid, unchoke).
%% @doc send a NOT_INTERESTED message
%% @end
-spec not_interested(pid()) -> ok.
not_interested(Pid) ->
forward_message(Pid, not_interested).
%% @doc send an INTERESTED message
%% @end
-spec interested(pid()) -> ok.
interested(Pid) ->
forward_message(Pid, interested).
%% @doc send a HAVE message
%% @end
-spec have(pid(), integer()) -> ok.
have(Pid, Piece) ->
forward_message(Pid, {have, Piece}).
@doc Send a BITFIELD message to the peer
%% @end
-spec bitfield(pid(), binary()) -> ok. %% This should be checked
bitfield(Pid, BitField) ->
forward_message(Pid, {bitfield, BitField}).
%% @doc Send off the initial parameters for extended protocol to the peer
%% <p>This is part of BEP-10</p>
%% @end
-spec ext_setup(pid(), list(), list()) -> ok.
ext_setup(Pid, Exts, Extra) ->
forward_message(Pid, {extended, 0, etorrent_proto_wire:
extended_msg_contents(Exts, Extra)}).
%% @doc Send off an EXT_MSG to the peer
%% <p>This is part of BEP-10</p>
%% @end
ext_msg(Pid, {extended, _Id, _Body}=ExtMsg) ->
forward_message(Pid, ExtMsg).
port(Pid, PortNum) ->
forward_message(Pid, {port, PortNum}).
@private Send a message to the encoder process .
%% The encoder process is expected to forward the message to the remote peer.
forward_message(Pid, Message) ->
gen_server:cast(Pid, {forward, Message}).
@private
init([Socket, TorrentId, _FastExtension]) ->
register_server(Socket),
erlang:send_after(?DEFAULT_KEEP_ALIVE_INTERVAL, self(), tick),
erlang:send_after(?RATE_UPDATE, self(), rate_update),
CPid = etorrent_peer_control:await_server(Socket),
State = #state{
socket = Socket,
buffer = queue:new(),
rate = etorrent_rate:init(),
control = CPid,
limiter = none,
torrent_id = TorrentId},
{ok, State}.
@private
handle_call(Msg, _From, State) ->
{stop, Msg, State}.
@private Bittorrent messages . Push them into the buffer .
handle_cast({forward, Message}, State) ->
#state{buffer=Buffer, limiter=Limiter} = State,
case Limiter of
none ->
NewLimiter = etorrent_rlimit:send(1),
NewBuffer = queue:in(Message, Buffer),
NewState = State#state{buffer=NewBuffer, limiter=NewLimiter},
{noreply, NewState};
_ when is_pid(Limiter) ->
NewBuffer = queue:in(Message, Buffer),
NewState = State#state{buffer=NewBuffer},
{noreply, NewState}
end;
handle_cast(Msg, State) ->
{stop, Msg, State}.
@private
%% Whenever a tick is hit, we send out a keep alive message on the line.
handle_info(tick, State) ->
#state{torrent_id=TorrentID, rate=Rate, socket=Socket} = State,
erlang:send_after(?DEFAULT_KEEP_ALIVE_INTERVAL, self(), tick),
case send_message(TorrentID, keep_alive, Rate, Socket) of
{ok, NewRate, _Size} ->
NewState = State#state{rate=NewRate},
{noreply, NewState};
{stop, Reason} ->
{stop, Reason, State}
end;
%% When we are requested to update our rate, we do it here.
handle_info(rate_update, State) ->
#state{torrent_id=TorrentID, rate=Rate, control=Control} = State,
erlang:send_after(?RATE_UPDATE, self(), rate_update),
NewRate = etorrent_rate:update(Rate, 0),
ok = etorrent_peer_states:set_send_rate(TorrentID, Control, NewRate#peer_rate.rate),
NewState = State#state{rate=NewRate},
{noreply, NewState};
handle_info({rlimit, continue}, State) ->
#state{torrent_id=TorrentID, rate=Rate, socket=Socket, buffer=Buffer} = State,
case queue:is_empty(Buffer) of
true ->
NewState = State#state{limiter=none},
{noreply, NewState};
false ->
Message = queue:head(Buffer),
case send_message(TorrentID, Message, Rate, Socket) of
{ok, NewRate, Size} ->
Limiter = etorrent_rlimit:send(Size),
NewBuffer = queue:tail(Buffer),
NewState = State#state{
rate=NewRate,
buffer=NewBuffer,
limiter=Limiter},
{noreply, NewState};
{stop, Reason} ->
{stop, Reason, State}
end
end;
handle_info(stop, State) ->
{stop, normal, State};
handle_info(Msg, State) ->
{stop, Msg, State}.
@private
terminate(_Reason, _S) ->
ok.
@private
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
%% @todo: Think about the stop messages here. They are definitely wrong.
send_message(TorrentID, Message, Rate, Socket) ->
case etorrent_proto_wire:send_msg(Socket, Message) of
{ok, Size} ->
ok = etorrent_torrent:statechange(TorrentID, [{add_upload, Size}]),
{ok, etorrent_rate:update(Rate, Size), Size};
{{error, closed}, _} ->
{stop, normal};
{{error, ebadf}, _} ->
{stop, normal}
end.
| null |
https://raw.githubusercontent.com/jlouis/etorrent_core/7db7f4ef36c1d055812504f00df92c6a67c2e4af/src/etorrent_peer_send.erl
|
erlang
|
@doc Handle outgoing messages to a peer
<p>This module handles all outgoing messaging for a peer. It
supports various API calls to facilitate this</p>
C-layer, whereas the slow mode doesn't. The price to pay is that we
have a worse granularity on the rate calculations, so we only shift
into the fast gear when we have a certain amount of traffic going on.</p>
<p>The shift fast to slow, or slow to fast, is synchronized with
the process {@link etorrent_peer_recv}, so if altering the code,
beware of that</p>
@end
Apart from standard gen_server things, the main idea of this module is
to serve as a mediator for the peer in the send direction. Precisely,
we have a message we can send to the process, for each of the possible
messages one can send to a peer.
other functions
message functions
gproc registry entries
gen_server callbacks
From proto. spec.
@doc Start the encoder process.
@end
@doc Register the local process as the encoder for a socket
@doc Lookup the encoder process for a socket
@doc Wait for the encoder process for a socket to register
@doc send a REQUEST message to the remote peer.
@end
@end
@doc Send a CANCEL message to the remote peer.
@end
@end
@doc CHOKE the peer.
@end
@doc UNCHOKE the peer.
end
@doc send a NOT_INTERESTED message
@end
@doc send an INTERESTED message
@end
@doc send a HAVE message
@end
@end
This should be checked
@doc Send off the initial parameters for extended protocol to the peer
<p>This is part of BEP-10</p>
@end
@doc Send off an EXT_MSG to the peer
<p>This is part of BEP-10</p>
@end
The encoder process is expected to forward the message to the remote peer.
Whenever a tick is hit, we send out a keep alive message on the line.
When we are requested to update our rate, we do it here.
@todo: Think about the stop messages here. They are definitely wrong.
|
@author < >
< p > Note that this module has two modes , < em > fast</em > and
< em > > . The fast mode outsources the packet encoding to the
-module(etorrent_peer_send).
-behaviour(gen_server).
-include("etorrent_rate.hrl").
-export([start_link/3]).
-export([request/2,
piece/5,
cancel/4,
reject/4,
choke/1,
unchoke/1,
have/2,
not_interested/1,
interested/1,
ext_msg/2,
ext_setup/3,
bitfield/2,
port/2]).
-export([register_server/1,
lookup_server/1,
await_server/1]).
-export([init/1,
handle_call/3,
handle_cast/2,
handle_info/2,
terminate/2,
code_change/3]).
-record(state, {
socket :: inet:socket(),
buffer :: queue(),
control :: pid(),
limiter :: none | pid(),
rate :: etorrent_rate:rate(),
torrent_id :: integer()}).
Maximal number of requests a peer may make .
-spec start_link(port(), integer(), boolean()) ->
ignore | {ok, pid()} | {error, any()}.
start_link(Socket, TorrentId, FastExtension) ->
gen_server:start_link(?MODULE,
[Socket, TorrentId, FastExtension], []).
-spec register_server(inet:socket()) -> true.
register_server(Socket) ->
etorrent_utils:register(server_name(Socket)).
-spec lookup_server(inet:socket()) -> pid().
lookup_server(Socket) ->
etorrent_utils:lookup(server_name(Socket)).
-spec await_server(inet:socket()) -> pid().
await_server(Socket) ->
etorrent_utils:await(server_name(Socket)).
@private Server name for encoder process .
server_name(Socket) ->
{etorrent, Socket, encoder}.
-spec request(pid(), {integer(), integer(), integer()}) -> ok.
request(Pid, {Index, Offset, Size}) ->
forward_message(Pid, {request, Index, Offset, Size}).
@doc send a PIECE message to the remote peer .
-spec piece(pid(), integer(), integer(), integer(), binary()) -> ok.
piece(Pid, Index, Offset, Length, Data) when Length =:= byte_size(Data) ->
forward_message(Pid, {piece, Index, Offset, Data}).
-spec cancel(pid(), integer(), integer(), integer()) -> ok.
cancel(Pid, Index, Offset, Len) ->
forward_message(Pid, {cancel, Index, Offset, Len}).
@doc Send a REJECT message to the remote peer .
-spec reject(pid(), integer(), integer(), integer()) -> ok.
reject(Pid, Index, Offset, Length) ->
forward_message(Pid, {reject_request, Index, Offset, Length}).
-spec choke(pid()) -> ok.
choke(Pid) ->
forward_message(Pid, choke).
-spec unchoke(pid()) -> ok.
unchoke(Pid) ->
forward_message(Pid, unchoke).
-spec not_interested(pid()) -> ok.
not_interested(Pid) ->
forward_message(Pid, not_interested).
-spec interested(pid()) -> ok.
interested(Pid) ->
forward_message(Pid, interested).
-spec have(pid(), integer()) -> ok.
have(Pid, Piece) ->
forward_message(Pid, {have, Piece}).
@doc Send a BITFIELD message to the peer
bitfield(Pid, BitField) ->
forward_message(Pid, {bitfield, BitField}).
-spec ext_setup(pid(), list(), list()) -> ok.
ext_setup(Pid, Exts, Extra) ->
forward_message(Pid, {extended, 0, etorrent_proto_wire:
extended_msg_contents(Exts, Extra)}).
ext_msg(Pid, {extended, _Id, _Body}=ExtMsg) ->
forward_message(Pid, ExtMsg).
port(Pid, PortNum) ->
forward_message(Pid, {port, PortNum}).
@private Send a message to the encoder process .
forward_message(Pid, Message) ->
gen_server:cast(Pid, {forward, Message}).
@private
init([Socket, TorrentId, _FastExtension]) ->
register_server(Socket),
erlang:send_after(?DEFAULT_KEEP_ALIVE_INTERVAL, self(), tick),
erlang:send_after(?RATE_UPDATE, self(), rate_update),
CPid = etorrent_peer_control:await_server(Socket),
State = #state{
socket = Socket,
buffer = queue:new(),
rate = etorrent_rate:init(),
control = CPid,
limiter = none,
torrent_id = TorrentId},
{ok, State}.
@private
handle_call(Msg, _From, State) ->
{stop, Msg, State}.
@private Bittorrent messages . Push them into the buffer .
handle_cast({forward, Message}, State) ->
#state{buffer=Buffer, limiter=Limiter} = State,
case Limiter of
none ->
NewLimiter = etorrent_rlimit:send(1),
NewBuffer = queue:in(Message, Buffer),
NewState = State#state{buffer=NewBuffer, limiter=NewLimiter},
{noreply, NewState};
_ when is_pid(Limiter) ->
NewBuffer = queue:in(Message, Buffer),
NewState = State#state{buffer=NewBuffer},
{noreply, NewState}
end;
handle_cast(Msg, State) ->
{stop, Msg, State}.
@private
handle_info(tick, State) ->
#state{torrent_id=TorrentID, rate=Rate, socket=Socket} = State,
erlang:send_after(?DEFAULT_KEEP_ALIVE_INTERVAL, self(), tick),
case send_message(TorrentID, keep_alive, Rate, Socket) of
{ok, NewRate, _Size} ->
NewState = State#state{rate=NewRate},
{noreply, NewState};
{stop, Reason} ->
{stop, Reason, State}
end;
handle_info(rate_update, State) ->
#state{torrent_id=TorrentID, rate=Rate, control=Control} = State,
erlang:send_after(?RATE_UPDATE, self(), rate_update),
NewRate = etorrent_rate:update(Rate, 0),
ok = etorrent_peer_states:set_send_rate(TorrentID, Control, NewRate#peer_rate.rate),
NewState = State#state{rate=NewRate},
{noreply, NewState};
handle_info({rlimit, continue}, State) ->
#state{torrent_id=TorrentID, rate=Rate, socket=Socket, buffer=Buffer} = State,
case queue:is_empty(Buffer) of
true ->
NewState = State#state{limiter=none},
{noreply, NewState};
false ->
Message = queue:head(Buffer),
case send_message(TorrentID, Message, Rate, Socket) of
{ok, NewRate, Size} ->
Limiter = etorrent_rlimit:send(Size),
NewBuffer = queue:tail(Buffer),
NewState = State#state{
rate=NewRate,
buffer=NewBuffer,
limiter=Limiter},
{noreply, NewState};
{stop, Reason} ->
{stop, Reason, State}
end
end;
handle_info(stop, State) ->
{stop, normal, State};
handle_info(Msg, State) ->
{stop, Msg, State}.
@private
terminate(_Reason, _S) ->
ok.
@private
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
send_message(TorrentID, Message, Rate, Socket) ->
case etorrent_proto_wire:send_msg(Socket, Message) of
{ok, Size} ->
ok = etorrent_torrent:statechange(TorrentID, [{add_upload, Size}]),
{ok, etorrent_rate:update(Rate, Size), Size};
{{error, closed}, _} ->
{stop, normal};
{{error, ebadf}, _} ->
{stop, normal}
end.
|
655ea70b70d307a57f9d1cfe721ffc4718a8bff910dd85977d8b5f424c8a051a
|
tmfg/mmtis-national-access-point
|
company_test.clj
|
(ns ote.tasks.company-test
(:require [clojure.test :refer [deftest is testing use-fixtures]]
[ote.tasks.company :refer [update-one-csv! store-daily-company-stats]]
[ote.test :refer [system-fixture with-http-resource http-post sql-query sql-execute! *ote*]]
[ote.services.transport :as transport-service]
[com.stuartsierra.component :as component]
[ote.services.external :as external]
[clojure.string :as str]
[clojure.test.check.generators :as gen]
[ote.db.service-generators :as s-generators]
[ote.db.transport-service :as t-service]))
(use-fixtures :each
(system-fixture
:transport (component/using
(transport-service/->TransportService
(:nap nil))
[:http :db])))
(defn company-csv [companies]
(str "business id,name\n"
(str/join "\n"
(map #(str (:business-id %) "," (:name %)) companies))))
(def test-companies #{{:business-id "1234567-8" :name "company 1"}
{:business-id "2345678-9" :name "company 2"}})
(defn fetch-companies [id]
(set
(sql-query
"SELECT (x.c).\"business-id\", (x.c).name"
" FROM ("
"SELECT unnest(companies) c"
" FROM service_company "
" WHERE \"transport-service-id\" = " id
") x")))
(deftest csv-is-updated-test
(with-http-resource
"companies" ".csv"
(fn [file url]
(spit file (company-csv test-companies))
(let [ts (-> (s-generators/service-type-generator :passenger-transportation)
gen/generate
(dissoc ::t-service/companies)
(assoc ::t-service/companies-csv-url url
::t-service/company-source :csv-url))
response (http-post (:user-id-admin @ote.test/user-db-ids-atom)
"transport-service"
ts)
id (get-in response [:transit ::t-service/id])]
(is (= 200 (:status response)))
;; check that companies are stored
(is (= test-companies (fetch-companies id)))
;; write new CSV data
(spit file (company-csv test-companies))
(sql-execute! "UPDATE service_company"
" SET updated = updated - '2 days'::interval"
" WHERE \"transport-service-id\" = " id)
(update-one-csv! (:db *ote*))
(is (= test-companies (fetch-companies id)))))))
| null |
https://raw.githubusercontent.com/tmfg/mmtis-national-access-point/a86cc890ffa1fe4f773083be5d2556e87a93d975/ote/test/clj/ote/tasks/company_test.clj
|
clojure
|
check that companies are stored
write new CSV data
|
(ns ote.tasks.company-test
(:require [clojure.test :refer [deftest is testing use-fixtures]]
[ote.tasks.company :refer [update-one-csv! store-daily-company-stats]]
[ote.test :refer [system-fixture with-http-resource http-post sql-query sql-execute! *ote*]]
[ote.services.transport :as transport-service]
[com.stuartsierra.component :as component]
[ote.services.external :as external]
[clojure.string :as str]
[clojure.test.check.generators :as gen]
[ote.db.service-generators :as s-generators]
[ote.db.transport-service :as t-service]))
(use-fixtures :each
(system-fixture
:transport (component/using
(transport-service/->TransportService
(:nap nil))
[:http :db])))
(defn company-csv [companies]
(str "business id,name\n"
(str/join "\n"
(map #(str (:business-id %) "," (:name %)) companies))))
(def test-companies #{{:business-id "1234567-8" :name "company 1"}
{:business-id "2345678-9" :name "company 2"}})
(defn fetch-companies [id]
(set
(sql-query
"SELECT (x.c).\"business-id\", (x.c).name"
" FROM ("
"SELECT unnest(companies) c"
" FROM service_company "
" WHERE \"transport-service-id\" = " id
") x")))
(deftest csv-is-updated-test
(with-http-resource
"companies" ".csv"
(fn [file url]
(spit file (company-csv test-companies))
(let [ts (-> (s-generators/service-type-generator :passenger-transportation)
gen/generate
(dissoc ::t-service/companies)
(assoc ::t-service/companies-csv-url url
::t-service/company-source :csv-url))
response (http-post (:user-id-admin @ote.test/user-db-ids-atom)
"transport-service"
ts)
id (get-in response [:transit ::t-service/id])]
(is (= 200 (:status response)))
(is (= test-companies (fetch-companies id)))
(spit file (company-csv test-companies))
(sql-execute! "UPDATE service_company"
" SET updated = updated - '2 days'::interval"
" WHERE \"transport-service-id\" = " id)
(update-one-csv! (:db *ote*))
(is (= test-companies (fetch-companies id)))))))
|
a795cac8cb2384303481957e7efe3ec69be641fb3d72df462f65435e2a45ad89
|
anuragsoni/http_async
|
server_bench.ml
|
open! Core
open! Async
open Http_async
let text =
Bigstring.of_string
"CHAPTER I. Down the Rabbit-Hole Alice was beginning to get very tired of sitting \
by her sister on the bank, and of having nothing to do: once or twice she had \
peeped into the book her sister was reading, but it had no pictures or \
conversations in it, <and what is the use of a book,> thought Alice <without \
pictures or conversations?> So she was considering in her own mind (as well as she \
could, for the hot day made her feel very sleepy and stupid), whether the pleasure \
of making a daisy-chain would be worth the trouble of getting up and picking the \
daisies, when suddenly a White Rabbit with pink eyes ran close by her. There was \
nothing so very remarkable in that; nor did Alice think it so very much out of the \
way to hear the Rabbit say to itself, <Oh dear! Oh dear! I shall be late!> (when \
she thought it over afterwards, it occurred to her that she ought to have wondered \
at this, but at the time it all seemed quite natural); but when the Rabbit actually \
took a watch out of its waistcoat-pocket, and looked at it, and then hurried on, \
Alice started to her feet, for it flashed across her mind that she had never before \
seen a rabbit with either a waistcoat-pocket, or a watch to take out of it, and \
burning with curiosity, she ran across the field after it, and fortunately was just \
in time to see it pop down a large rabbit-hole under the hedge. In another moment \
down went Alice after it, never once considering how in the world she was to get \
out again. The rabbit-hole went straight on like a tunnel for some way, and then \
dipped suddenly down, so suddenly that Alice had not a moment to think about \
stopping herself before she found herself falling down a very deep well. Either the \
well was very deep, or she fell very slowly, for she had plenty of time as she went \
down to look about her and to wonder what was going to happen next. First, she \
tried to look down and make out what she was coming to, but it was too dark to see \
anything; then she looked at the sides of the well, and noticed that they were \
filled with cupboards......"
;;
let command =
Command.async
~summary:"Start a hello world Async server"
Command.Let_syntax.(
let%map_open port =
flag "-p" ~doc:"int Source port to listen on" (optional_with_default 8080 int)
in
fun () ->
let%bind.Deferred server =
Server.run
~backlog:11_000
~max_accepts_per_batch:64
~buffer_config:(Buffer_config.create ~initial_size:0x4000 ())
~where_to_listen:(Tcp.Where_to_listen.of_port port)
(fun _addr (_request, _body) ->
Deferred.return (Response.create `Ok, Body.Writer.bigstring text))
in
Deferred.forever () (fun () ->
let%map.Deferred () = after Time.Span.(of_sec 0.5) in
Log.Global.printf "Active connections: %d" (Tcp.Server.num_connections server));
Tcp.Server.close_finished_and_handlers_determined server)
;;
let () =
Memtrace.trace_if_requested ();
Command_unix.run command
;;
| null |
https://raw.githubusercontent.com/anuragsoni/http_async/602889e33b92a842ce7a64dcc259270f529231e3/bench/server_bench.ml
|
ocaml
|
open! Core
open! Async
open Http_async
let text =
Bigstring.of_string
"CHAPTER I. Down the Rabbit-Hole Alice was beginning to get very tired of sitting \
by her sister on the bank, and of having nothing to do: once or twice she had \
peeped into the book her sister was reading, but it had no pictures or \
conversations in it, <and what is the use of a book,> thought Alice <without \
pictures or conversations?> So she was considering in her own mind (as well as she \
could, for the hot day made her feel very sleepy and stupid), whether the pleasure \
of making a daisy-chain would be worth the trouble of getting up and picking the \
daisies, when suddenly a White Rabbit with pink eyes ran close by her. There was \
nothing so very remarkable in that; nor did Alice think it so very much out of the \
way to hear the Rabbit say to itself, <Oh dear! Oh dear! I shall be late!> (when \
she thought it over afterwards, it occurred to her that she ought to have wondered \
at this, but at the time it all seemed quite natural); but when the Rabbit actually \
took a watch out of its waistcoat-pocket, and looked at it, and then hurried on, \
Alice started to her feet, for it flashed across her mind that she had never before \
seen a rabbit with either a waistcoat-pocket, or a watch to take out of it, and \
burning with curiosity, she ran across the field after it, and fortunately was just \
in time to see it pop down a large rabbit-hole under the hedge. In another moment \
down went Alice after it, never once considering how in the world she was to get \
out again. The rabbit-hole went straight on like a tunnel for some way, and then \
dipped suddenly down, so suddenly that Alice had not a moment to think about \
stopping herself before she found herself falling down a very deep well. Either the \
well was very deep, or she fell very slowly, for she had plenty of time as she went \
down to look about her and to wonder what was going to happen next. First, she \
tried to look down and make out what she was coming to, but it was too dark to see \
anything; then she looked at the sides of the well, and noticed that they were \
filled with cupboards......"
;;
let command =
Command.async
~summary:"Start a hello world Async server"
Command.Let_syntax.(
let%map_open port =
flag "-p" ~doc:"int Source port to listen on" (optional_with_default 8080 int)
in
fun () ->
let%bind.Deferred server =
Server.run
~backlog:11_000
~max_accepts_per_batch:64
~buffer_config:(Buffer_config.create ~initial_size:0x4000 ())
~where_to_listen:(Tcp.Where_to_listen.of_port port)
(fun _addr (_request, _body) ->
Deferred.return (Response.create `Ok, Body.Writer.bigstring text))
in
Deferred.forever () (fun () ->
let%map.Deferred () = after Time.Span.(of_sec 0.5) in
Log.Global.printf "Active connections: %d" (Tcp.Server.num_connections server));
Tcp.Server.close_finished_and_handlers_determined server)
;;
let () =
Memtrace.trace_if_requested ();
Command_unix.run command
;;
|
|
1b7b33e799d2d0fd31502efbe8ae253cd1f8f3e871cf18d04eac2da657bcdbf2
|
Risto-Stevcev/bs-declaredom
|
Jsdom.ml
|
*
* Initializes mock window and document objects from JSDOM .
* Useful for reusing DOM code on the backend
* Initializes mock window and document objects from JSDOM.
* Useful for reusing DOM code on the backend
*)
let init: unit -> unit = [%raw fun () ->
"if (!global.document) {
var JSDOM = require('jsdom').JSDOM;
var dom = new JSDOM('');
global.window = dom.window;
global.document = dom.window.document;
}"]
| null |
https://raw.githubusercontent.com/Risto-Stevcev/bs-declaredom/6e2eb1f0daa32a7253caadbdd6392f3371807c88/src/Jsdom.ml
|
ocaml
|
*
* Initializes mock window and document objects from JSDOM .
* Useful for reusing DOM code on the backend
* Initializes mock window and document objects from JSDOM.
* Useful for reusing DOM code on the backend
*)
let init: unit -> unit = [%raw fun () ->
"if (!global.document) {
var JSDOM = require('jsdom').JSDOM;
var dom = new JSDOM('');
global.window = dom.window;
global.document = dom.window.document;
}"]
|
|
b7f643b813f6220f9f41fa3ebdc70ee0bd915552c96f529b1cc8ab400b65d6b3
|
lexi-lambda/blackboard
|
unicode.rkt
|
#lang racket/base
(require racket/contract
racket/match)
(provide (contract-out
[char:minus char?]
[math-char-style/c flat-contract?]
[math-char (->* [char?]
[#:bold? any/c
#:italic? any/c
#:style math-char-style/c]
char?)]
[superscript-char (-> char? char?)]
[subscript-char (-> char? char?)]
[integer->superscript-string (-> exact-integer? string?)]
[integer->subscript-string (-> exact-integer? string?)]))
;; -----------------------------------------------------------------------------
(define char:minus #\u2212)
(define (char+ c . ns)
(integer->char (apply + (char->integer c) ns)))
(define (char-diff c1 c2)
(- (char->integer c1) (char->integer c2)))
(define math-char-style/c
(or/c 'serif 'sans-serif 'script 'fraktur 'monospace 'double-struck))
(define (math-char c
#:bold? [bold? #f]
#:italic? [italic? #f]
#:style [style 'serif])
(define (bad-combo)
(raise-arguments-error 'math-char "no character for style"
"character" c
"bold?" bold?
"italic?" italic?
"style" style))
(define (regular stride c)
(match* {bold? italic?}
[{#f #f} c]
[{#t #f} (char+ c stride)]
[{#f #t} (char+ c (* stride 2))]
[{#t #t} (char+ c (* stride 3))]))
(define (latin c c-offset)
(match* {style bold? italic? c}
[{'serif #f #t #\h} #\U210E]
[{'serif _ _ _ } (regular 52 (char+ #\U1D3CC c-offset))]
[{'sans-serif _ _ _ } (regular 52 (char+ #\U1D5A0 c-offset))]
[{'script #f #f #\B} #\U212C]
[{'script #f #f #\E} #\U2130]
[{'script #f #f #\F} #\U2131]
[{'script #f #f #\H} #\U210B]
[{'script #f #f #\I} #\U2110]
[{'script #f #f #\L} #\U2112]
[{'script #f #f #\M} #\U2133]
[{'script #f #f #\R} #\U211B]
[{'script #f #f #\e} #\U212F]
[{'script #f #f #\g} #\U210A]
[{'script #f #f #\o} #\U2134]
[{'script _ #f _ } (regular 52 (char+ #\U1D49C c-offset))]
[{'fraktur #f #f #\C} #\U212D]
[{'fraktur #f #f #\H} #\U210C]
[{'fraktur #f #f #\I} #\U2111]
[{'fraktur #f #f #\R} #\U211C]
[{'fraktur #f #f #\Z} #\U2128]
[{'fraktur _ #f _ } (regular 104 (char+ #\U1D504 c-offset))]
[{'monospace #f #f _ } (char+ #\U1D670 c-offset)]
[{'double-struck #f #f #\C} #\U2102]
[{'double-struck #f #f #\H} #\U210D]
[{'double-struck #f #f #\N} #\U2115]
[{'double-struck #f #f #\P} #\U2119]
[{'double-struck #f #f #\Q} #\U211A]
[{'double-struck #f #f #\R} #\U211D]
[{'double-struck #f #f #\Z} #\U2124]
[{'double-struck #f #f _ } (char+ #\U1D538 c-offset)]
[{_ _ _ _ } (bad-combo)]))
(define (greek c-offset)
(match* {style bold? italic?}
[{'serif _ _ } (regular 58 (char+ #\U1D66E c-offset))]
[{'sans-serif #t #f} (char+ #\U1D756 c-offset)]
[{'sans-serif #t #t} (char+ #\U1D790 c-offset)]
[{_ _ _ } (bad-combo)]))
(define (digit c-offset)
(match* {style bold? italic?}
[{'serif #t #f} (char+ #\U1D7CE c-offset)]
[{'sans-serif #f #f} (char+ #\U1D7E2 c-offset)]
[{'sans-serif #t #f} (char+ #\U1D7EC c-offset)]
[{'monospace #f #f} (char+ #\U1D7F6 c-offset)]
[{'double-struck #f #f} (char+ #\U1D7D8 c-offset)]
[{_ _ _ } (bad-combo)]))
(cond
[(and (not bold?) (not italic?) (eq? style 'serif)) c]
[(char<=? #\A c #\Z) (latin c (char-diff c #\A))]
[(char<=? #\a c #\z) (latin c (+ (char-diff c #\a) 26))]
[(or (char<=? #\U391 c #\U3A1)
(char<=? #\Σ c #\Ω)
(char<=? #\α c #\ω))
(greek (char-diff c #\U391))]
[(char=? c #\Θ) (greek 11)]
[(char=? c #\∇) (greek 19)]
[(char=? c #\U2202) (greek 39)]
[(char=? c #\U03F5) (greek 40)]
[(char=? c #\U03D1) (greek 41)]
[(char=? c #\U03F0) (greek 42)]
[(char=? c #\U03D5) (greek 43)]
[(char=? c #\U03F1) (greek 44)]
[(char=? c #\U03D6) (greek 45)]
[(char<=? #\0 c #\9) (digit (char-diff c #\0))]
[else (bad-combo)]))
(define (superscript-char c)
(match c
[#\1 #\u00B9]
[#\2 #\u00B2]
[#\3 #\u00B3]
[#\+ #\u207A]
[(== char:minus) #\u207B]
[#\= #\u207C]
[#\( #\u207D]
[#\) #\u207E]
[#\n #\u207F]
[_
(if (char<=? #\0 c #\9)
(char+ #\u2070 (char-diff c #\0))
(raise-arguments-error 'superscript-char "no superscript variant for character"
"character" c))]))
(define (subscript-char c)
(cond
[(char<=? #\0 c #\9)
(char+ #\u2080 (char-diff c #\0))]
[else
(match c
[#\+ #\u208A]
[(== char:minus) #\u208B]
[#\= #\u208C]
[#\( #\u208D]
[#\) #\u208E]
[#\a #\u2090]
[#\e #\u2091]
[#\o #\u2092]
[#\x #\u2093]
[#\ə #\u2094]
[#\h #\u2095]
[#\k #\u2096]
[#\l #\u2097]
[#\m #\u2098]
[#\n #\u2099]
[#\p #\u209A]
[#\s #\u209B]
[#\t #\u209C]
[_
(raise-arguments-error 'subscript-char "no subscript variant for character"
"character" c)])]))
(define (integer->script-string n convert-char)
(define num-str (number->string n))
(define len (string-length num-str))
(define str (if (immutable? num-str) (make-string len) num-str))
(for ([i (in-range len)])
(define c (string-ref num-str i))
(string-set! str i (convert-char (if (char=? c #\-) char:minus c))))
str)
(define (integer->superscript-string n)
(integer->script-string n superscript-char))
(define (integer->subscript-string n)
(integer->script-string n subscript-char))
| null |
https://raw.githubusercontent.com/lexi-lambda/blackboard/cfc987e9bb3a357a10d23a44419bbe16215ea656/blackboard-lib/blackboard/private/unicode.rkt
|
racket
|
-----------------------------------------------------------------------------
|
#lang racket/base
(require racket/contract
racket/match)
(provide (contract-out
[char:minus char?]
[math-char-style/c flat-contract?]
[math-char (->* [char?]
[#:bold? any/c
#:italic? any/c
#:style math-char-style/c]
char?)]
[superscript-char (-> char? char?)]
[subscript-char (-> char? char?)]
[integer->superscript-string (-> exact-integer? string?)]
[integer->subscript-string (-> exact-integer? string?)]))
(define char:minus #\u2212)
(define (char+ c . ns)
(integer->char (apply + (char->integer c) ns)))
(define (char-diff c1 c2)
(- (char->integer c1) (char->integer c2)))
(define math-char-style/c
(or/c 'serif 'sans-serif 'script 'fraktur 'monospace 'double-struck))
(define (math-char c
#:bold? [bold? #f]
#:italic? [italic? #f]
#:style [style 'serif])
(define (bad-combo)
(raise-arguments-error 'math-char "no character for style"
"character" c
"bold?" bold?
"italic?" italic?
"style" style))
(define (regular stride c)
(match* {bold? italic?}
[{#f #f} c]
[{#t #f} (char+ c stride)]
[{#f #t} (char+ c (* stride 2))]
[{#t #t} (char+ c (* stride 3))]))
(define (latin c c-offset)
(match* {style bold? italic? c}
[{'serif #f #t #\h} #\U210E]
[{'serif _ _ _ } (regular 52 (char+ #\U1D3CC c-offset))]
[{'sans-serif _ _ _ } (regular 52 (char+ #\U1D5A0 c-offset))]
[{'script #f #f #\B} #\U212C]
[{'script #f #f #\E} #\U2130]
[{'script #f #f #\F} #\U2131]
[{'script #f #f #\H} #\U210B]
[{'script #f #f #\I} #\U2110]
[{'script #f #f #\L} #\U2112]
[{'script #f #f #\M} #\U2133]
[{'script #f #f #\R} #\U211B]
[{'script #f #f #\e} #\U212F]
[{'script #f #f #\g} #\U210A]
[{'script #f #f #\o} #\U2134]
[{'script _ #f _ } (regular 52 (char+ #\U1D49C c-offset))]
[{'fraktur #f #f #\C} #\U212D]
[{'fraktur #f #f #\H} #\U210C]
[{'fraktur #f #f #\I} #\U2111]
[{'fraktur #f #f #\R} #\U211C]
[{'fraktur #f #f #\Z} #\U2128]
[{'fraktur _ #f _ } (regular 104 (char+ #\U1D504 c-offset))]
[{'monospace #f #f _ } (char+ #\U1D670 c-offset)]
[{'double-struck #f #f #\C} #\U2102]
[{'double-struck #f #f #\H} #\U210D]
[{'double-struck #f #f #\N} #\U2115]
[{'double-struck #f #f #\P} #\U2119]
[{'double-struck #f #f #\Q} #\U211A]
[{'double-struck #f #f #\R} #\U211D]
[{'double-struck #f #f #\Z} #\U2124]
[{'double-struck #f #f _ } (char+ #\U1D538 c-offset)]
[{_ _ _ _ } (bad-combo)]))
(define (greek c-offset)
(match* {style bold? italic?}
[{'serif _ _ } (regular 58 (char+ #\U1D66E c-offset))]
[{'sans-serif #t #f} (char+ #\U1D756 c-offset)]
[{'sans-serif #t #t} (char+ #\U1D790 c-offset)]
[{_ _ _ } (bad-combo)]))
(define (digit c-offset)
(match* {style bold? italic?}
[{'serif #t #f} (char+ #\U1D7CE c-offset)]
[{'sans-serif #f #f} (char+ #\U1D7E2 c-offset)]
[{'sans-serif #t #f} (char+ #\U1D7EC c-offset)]
[{'monospace #f #f} (char+ #\U1D7F6 c-offset)]
[{'double-struck #f #f} (char+ #\U1D7D8 c-offset)]
[{_ _ _ } (bad-combo)]))
(cond
[(and (not bold?) (not italic?) (eq? style 'serif)) c]
[(char<=? #\A c #\Z) (latin c (char-diff c #\A))]
[(char<=? #\a c #\z) (latin c (+ (char-diff c #\a) 26))]
[(or (char<=? #\U391 c #\U3A1)
(char<=? #\Σ c #\Ω)
(char<=? #\α c #\ω))
(greek (char-diff c #\U391))]
[(char=? c #\Θ) (greek 11)]
[(char=? c #\∇) (greek 19)]
[(char=? c #\U2202) (greek 39)]
[(char=? c #\U03F5) (greek 40)]
[(char=? c #\U03D1) (greek 41)]
[(char=? c #\U03F0) (greek 42)]
[(char=? c #\U03D5) (greek 43)]
[(char=? c #\U03F1) (greek 44)]
[(char=? c #\U03D6) (greek 45)]
[(char<=? #\0 c #\9) (digit (char-diff c #\0))]
[else (bad-combo)]))
(define (superscript-char c)
(match c
[#\1 #\u00B9]
[#\2 #\u00B2]
[#\3 #\u00B3]
[#\+ #\u207A]
[(== char:minus) #\u207B]
[#\= #\u207C]
[#\( #\u207D]
[#\) #\u207E]
[#\n #\u207F]
[_
(if (char<=? #\0 c #\9)
(char+ #\u2070 (char-diff c #\0))
(raise-arguments-error 'superscript-char "no superscript variant for character"
"character" c))]))
(define (subscript-char c)
(cond
[(char<=? #\0 c #\9)
(char+ #\u2080 (char-diff c #\0))]
[else
(match c
[#\+ #\u208A]
[(== char:minus) #\u208B]
[#\= #\u208C]
[#\( #\u208D]
[#\) #\u208E]
[#\a #\u2090]
[#\e #\u2091]
[#\o #\u2092]
[#\x #\u2093]
[#\ə #\u2094]
[#\h #\u2095]
[#\k #\u2096]
[#\l #\u2097]
[#\m #\u2098]
[#\n #\u2099]
[#\p #\u209A]
[#\s #\u209B]
[#\t #\u209C]
[_
(raise-arguments-error 'subscript-char "no subscript variant for character"
"character" c)])]))
(define (integer->script-string n convert-char)
(define num-str (number->string n))
(define len (string-length num-str))
(define str (if (immutable? num-str) (make-string len) num-str))
(for ([i (in-range len)])
(define c (string-ref num-str i))
(string-set! str i (convert-char (if (char=? c #\-) char:minus c))))
str)
(define (integer->superscript-string n)
(integer->script-string n superscript-char))
(define (integer->subscript-string n)
(integer->script-string n subscript-char))
|
28f5a375d38468d560630ab1cff1f329691b2396036f07d893dc98c20877930e
|
uwplse/synapse
|
hd-sgn-test.rkt
|
#lang s-exp rosette
(require
"../opsyn/engine/metasketch.rkt" "../opsyn/engine/eval.rkt" "../opsyn/engine/util.rkt"
"../opsyn/bv/lang.rkt" "../benchmarks/hd/wcet.rkt" "../opsyn/engine/solver+.rkt"
"../opsyn/metasketches/iterator.rkt" "../opsyn/engine/search.rkt"
rackunit "test-runner.rkt")
(current-subprocess-custodian-mode 'kill)
(current-bitwidth 32)
(define (synth M S)
(parameterize ([current-custodian (make-custodian)])
(with-handlers ([exn? (lambda (e) (custodian-shutdown-all (current-custodian)) (raise e))])
(∃∀solver #:forall (inputs M)
#:pre (pre S)
#:post (append (post S (programs S)) (structure M S)))
(begin0
(second (thread-receive))
(custodian-shutdown-all (current-custodian))))))
(define (test-sgn M dynamic?)
(test-case (format "hd-sgn ~a" dynamic?)
(unsafe-clear-terms!)
(define-values (prog sol)
(let loop ([sketches (sequence->stream (sketches M))])
(define S (stream-first sketches))
(printf "~a: " S)
(define sol (synth M S))
(cond [(sat? sol) (printf "~s\n" (programs S sol)) (values (programs S sol) sol)]
[else
(printf "unsat\n")
(loop (stream-rest sketches))])))
(check-true (sat? sol))))
(define (test-search [threads 1] [dynamic? #t])
(test-case (format "hd-sgn search ~a" dynamic?)
(define M `(hd-sgn #:dynamic-cost? ,dynamic?))
(check-not-false
(search #:metasketch M
#:threads threads
#:timeout 30
#:bitwidth (current-bitwidth)))))
(define/provide-test-suite hd-sgn-tests
(test-sgn (hd-sgn #:dynamic-cost? #f) #f)
(test-sgn (hd-sgn #:dynamic-cost? #t) #t))
(run-tests-quiet hd-sgn-tests)
| null |
https://raw.githubusercontent.com/uwplse/synapse/10f605f8f1fff6dade90607f516550b961a10169/test/hd-sgn-test.rkt
|
racket
|
#lang s-exp rosette
(require
"../opsyn/engine/metasketch.rkt" "../opsyn/engine/eval.rkt" "../opsyn/engine/util.rkt"
"../opsyn/bv/lang.rkt" "../benchmarks/hd/wcet.rkt" "../opsyn/engine/solver+.rkt"
"../opsyn/metasketches/iterator.rkt" "../opsyn/engine/search.rkt"
rackunit "test-runner.rkt")
(current-subprocess-custodian-mode 'kill)
(current-bitwidth 32)
(define (synth M S)
(parameterize ([current-custodian (make-custodian)])
(with-handlers ([exn? (lambda (e) (custodian-shutdown-all (current-custodian)) (raise e))])
(∃∀solver #:forall (inputs M)
#:pre (pre S)
#:post (append (post S (programs S)) (structure M S)))
(begin0
(second (thread-receive))
(custodian-shutdown-all (current-custodian))))))
(define (test-sgn M dynamic?)
(test-case (format "hd-sgn ~a" dynamic?)
(unsafe-clear-terms!)
(define-values (prog sol)
(let loop ([sketches (sequence->stream (sketches M))])
(define S (stream-first sketches))
(printf "~a: " S)
(define sol (synth M S))
(cond [(sat? sol) (printf "~s\n" (programs S sol)) (values (programs S sol) sol)]
[else
(printf "unsat\n")
(loop (stream-rest sketches))])))
(check-true (sat? sol))))
(define (test-search [threads 1] [dynamic? #t])
(test-case (format "hd-sgn search ~a" dynamic?)
(define M `(hd-sgn #:dynamic-cost? ,dynamic?))
(check-not-false
(search #:metasketch M
#:threads threads
#:timeout 30
#:bitwidth (current-bitwidth)))))
(define/provide-test-suite hd-sgn-tests
(test-sgn (hd-sgn #:dynamic-cost? #f) #f)
(test-sgn (hd-sgn #:dynamic-cost? #t) #t))
(run-tests-quiet hd-sgn-tests)
|
|
f14333f64284601ad6f65e92d7832cef73dee7c14702a3109fafa1b9f0383613
|
singleheart/programming-in-haskell
|
ex3.hs
|
instance Foldable Maybe where
-- fold :: Monoid a => Maybe a -> a
fold Nothing = mempty
fold (Just a) = a
-- foldMap :: Monoid b => (a -> b) -> Maybe a -> b
foldMap _ Nothing = mempty
foldMap f (Just a) = f a
-- foldr :: (a -> b -> b) -> b -> Maybe a -> b
foldr _ _ Nothing = mempty
foldr f v (Just a) = f a v
-- foldl :: (a -> b -> a) -> a -> Maybe b -> a
foldl _ _ Nothing = mempty
foldl f v (Just b) = f v b
instance Traversable Maybe where
-- traverse :: Applicative f => (a -> f b) -> Maybe a -> f (Maybe b)
traverse g Nothing = pure Nothing
traverse g (Just a) = Just <$> g a
| null |
https://raw.githubusercontent.com/singleheart/programming-in-haskell/80c7efc0425babea3cd982e47e121f19bec0aba9/ch14/ex3.hs
|
haskell
|
fold :: Monoid a => Maybe a -> a
foldMap :: Monoid b => (a -> b) -> Maybe a -> b
foldr :: (a -> b -> b) -> b -> Maybe a -> b
foldl :: (a -> b -> a) -> a -> Maybe b -> a
traverse :: Applicative f => (a -> f b) -> Maybe a -> f (Maybe b)
|
instance Foldable Maybe where
fold Nothing = mempty
fold (Just a) = a
foldMap _ Nothing = mempty
foldMap f (Just a) = f a
foldr _ _ Nothing = mempty
foldr f v (Just a) = f a v
foldl _ _ Nothing = mempty
foldl f v (Just b) = f v b
instance Traversable Maybe where
traverse g Nothing = pure Nothing
traverse g (Just a) = Just <$> g a
|
28d4d424e7f3a22a20b13b5ad9bacbd0dcffa464ad30f74f80eda9dc6b48bf73
|
music-suite/music-suite
|
Quality.hs
|
-- | Common interval quality.
module Music.Pitch.Common.Quality
( -- * Quality
Quality (..),
qualityTypes,
isStandardQuality,
isSimpleQuality,
HasQuality (..),
invertQuality,
isPerfect,
isMajor,
isMinor,
isAugmented,
isDiminished,
-- ** Quality type
QualityType (..),
expectedQualityType,
isValidQualityNumber,
-- ** Quality to alteration
Direction (..),
qualityToAlteration,
)
where
import Music.Pitch.Common.Internal
| null |
https://raw.githubusercontent.com/music-suite/music-suite/7f01fd62334c66418043b7a2d662af127f98685d/src/Music/Pitch/Common/Quality.hs
|
haskell
|
| Common interval quality.
* Quality
** Quality type
** Quality to alteration
|
module Music.Pitch.Common.Quality
Quality (..),
qualityTypes,
isStandardQuality,
isSimpleQuality,
HasQuality (..),
invertQuality,
isPerfect,
isMajor,
isMinor,
isAugmented,
isDiminished,
QualityType (..),
expectedQualityType,
isValidQualityNumber,
Direction (..),
qualityToAlteration,
)
where
import Music.Pitch.Common.Internal
|
e96b0b9e274cd734814939e6a323358d14b43102f974e9950b055b7257f3567f
|
hammerlab/biokepi
|
vcfannotatepolyphen.ml
|
open Biokepi_run_environment
open Common
let run ~(run_with: Machine.t) ~reference_build ~vcf ~output_vcf =
let open KEDSL in
let vap_tool =
Machine.get_tool run_with Machine.Tool.Default.vcfannotatepolyphen
in
let whessdb = Machine.(get_reference_genome run_with reference_build)
|> Reference_genome.whess_exn
in
let whessdb_path = whessdb#product#path in
let vcf_path = vcf#product#path in
let name = sprintf "vcf-annotate-polyphen_%s" (Filename.basename vcf_path) in
workflow_node
(transform_vcf vcf#product ~path:output_vcf)
~name
~edges:[
depends_on Machine.Tool.(ensure vap_tool);
depends_on whessdb;
depends_on vcf;
]
~make:(
Machine.run_program run_with ~name
Program.(
Machine.Tool.(init vap_tool)
&& shf "vcf-annotate-polyphen %s %s %s" whessdb_path vcf_path output_vcf
)
)
| null |
https://raw.githubusercontent.com/hammerlab/biokepi/d64eb2c891b41bda3444445cd2adf4e3251725d4/src/bfx_tools/vcfannotatepolyphen.ml
|
ocaml
|
open Biokepi_run_environment
open Common
let run ~(run_with: Machine.t) ~reference_build ~vcf ~output_vcf =
let open KEDSL in
let vap_tool =
Machine.get_tool run_with Machine.Tool.Default.vcfannotatepolyphen
in
let whessdb = Machine.(get_reference_genome run_with reference_build)
|> Reference_genome.whess_exn
in
let whessdb_path = whessdb#product#path in
let vcf_path = vcf#product#path in
let name = sprintf "vcf-annotate-polyphen_%s" (Filename.basename vcf_path) in
workflow_node
(transform_vcf vcf#product ~path:output_vcf)
~name
~edges:[
depends_on Machine.Tool.(ensure vap_tool);
depends_on whessdb;
depends_on vcf;
]
~make:(
Machine.run_program run_with ~name
Program.(
Machine.Tool.(init vap_tool)
&& shf "vcf-annotate-polyphen %s %s %s" whessdb_path vcf_path output_vcf
)
)
|
|
e3fecee26a2701a5449b2c459ac220dfa3bb8fa0ddb2cf4737f8d8f73be9bf09
|
facebook/flow
|
default_resolve.mli
|
* Copyright ( c ) Meta Platforms , Inc. and affiliates .
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree .
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
val default_resolve_touts : flow:(Type.t * Type.t -> unit) -> 'a -> ALoc.t -> Type.use_t -> unit
| null |
https://raw.githubusercontent.com/facebook/flow/8adaf30c6254e4a2a433ede255c16fa108296022/src/typing/default_resolve.mli
|
ocaml
|
* Copyright ( c ) Meta Platforms , Inc. and affiliates .
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree .
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
val default_resolve_touts : flow:(Type.t * Type.t -> unit) -> 'a -> ALoc.t -> Type.use_t -> unit
|
|
8ef8c4c9e92cc68540f121f52ae7e1bdd842a4a0bb23304062282a93c268d26e
|
B-Lang-org/bsc
|
Intervals.hs
|
# LANGUAGE CPP #
module Intervals(VSetInteger, vEmpty, vSing, vFromTo, vGetSing,
vCompRange, vUnion, vIntersect, vNull) where
#if defined(__GLASGOW_HASKELL__) && (__GLASGOW_HASKELL__ >= 804)
import Prelude hiding ((<>))
#endif
import PPrint
data IVal = IVal Integer Integer
deriving (Show, Eq)
instance PPrint IVal where
pPrint d _ (IVal l h) =
if l == h then
text "[" <> pPrint d 0 l <> text "]"
else
text "[" <> pPrint d 0 l <> text ".." <> pPrint d 0 h <> text "]"
-- A set of values is represented as a list of ordered, non-overlapping intervals
newtype VSetInteger = VSet [IVal]
deriving (Show, Eq)
instance PPrint VSetInteger where
pPrint d p (VSet is) = pPrint d p is
vNull :: VSetInteger -> Bool
vNull (VSet xs) = null xs -- only if no empty or [h,l] intervals
vEmpty :: VSetInteger
vEmpty = VSet []
-- Complement within a range
vCompRange :: Integer -> Integer -> VSetInteger -> VSetInteger
vCompRange lo hi (VSet []) = VSet [IVal lo hi]
vCompRange lo hi (VSet is) = foldr1 vIntersect (map (vCompRangeI lo hi) is)
vCompRangeI :: Integer -> Integer -> IVal -> VSetInteger
vCompRangeI lo hi (IVal l h) = VSet [IVal lo (l-1), IVal (h+1) hi]
vSing :: Integer -> VSetInteger
vSing i = VSet [IVal i i]
vGetSing :: VSetInteger -> Maybe Integer
vGetSing (VSet [IVal i i']) | i == i' = Just i
vGetSing _ = Nothing
vFromTo :: Integer -> Integer -> VSetInteger
vFromTo i j = VSet [IVal i j]
vUnionI :: IVal -> VSetInteger -> VSetInteger
vUnionI (IVal l h) (VSet is) = VSet (add l h is)
where add l h [] = [IVal l h]
add l h (i@(IVal vl vh) : is) =
if vl <= l then
if vh < l then
coal (i : add l h is) -- (l,h) above i
else if vh < h then
add vl h is -- (l,h) overlaps i
else
i : is -- (l,h) contained in i
else if vl > h then
coal (IVal l h : i : is)-- (l,h) below i
else
if vh <= h then
add l h is -- (l,h) contains i
else
add l vh is -- (l,h) overlaps i
coal (IVal l1 h1 : IVal l2 h2 : is) | h1+1 == l2 = IVal l1 h2 : is
coal is = is
vUnion :: VSetInteger -> VSetInteger -> VSetInteger
vUnion (VSet is) vs = foldr vUnionI vs is
vIntersectI :: IVal -> VSetInteger -> VSetInteger
vIntersectI (IVal l h) (VSet is) = VSet (sub l h is)
where sub l h [] = []
sub l h (i@(IVal vl vh) : is) =
if vl <= l then
if vh < l then
sub l h is -- (l,h) above i
else if vh < h then
IVal l vh : sub l h is -- (l,h) overlaps i
else
[IVal l h] -- (l,h) contained in i
else if vl > h then
[]
else
if vh <= h then
i : sub l h is -- (l,h) contains i
else
[IVal vl h] -- (l,h) overlaps i
vIntersect :: VSetInteger -> VSetInteger -> VSetInteger
vIntersect (VSet is) vs = foldr (\ i -> vUnion (vIntersectI i vs)) vEmpty is
| null |
https://raw.githubusercontent.com/B-Lang-org/bsc/bd141b505394edc5a4bdd3db442a9b0a8c101f0f/src/comp/Intervals.hs
|
haskell
|
A set of values is represented as a list of ordered, non-overlapping intervals
only if no empty or [h,l] intervals
Complement within a range
(l,h) above i
(l,h) overlaps i
(l,h) contained in i
(l,h) below i
(l,h) contains i
(l,h) overlaps i
(l,h) above i
(l,h) overlaps i
(l,h) contained in i
(l,h) contains i
(l,h) overlaps i
|
# LANGUAGE CPP #
module Intervals(VSetInteger, vEmpty, vSing, vFromTo, vGetSing,
vCompRange, vUnion, vIntersect, vNull) where
#if defined(__GLASGOW_HASKELL__) && (__GLASGOW_HASKELL__ >= 804)
import Prelude hiding ((<>))
#endif
import PPrint
data IVal = IVal Integer Integer
deriving (Show, Eq)
instance PPrint IVal where
pPrint d _ (IVal l h) =
if l == h then
text "[" <> pPrint d 0 l <> text "]"
else
text "[" <> pPrint d 0 l <> text ".." <> pPrint d 0 h <> text "]"
newtype VSetInteger = VSet [IVal]
deriving (Show, Eq)
instance PPrint VSetInteger where
pPrint d p (VSet is) = pPrint d p is
vNull :: VSetInteger -> Bool
vEmpty :: VSetInteger
vEmpty = VSet []
vCompRange :: Integer -> Integer -> VSetInteger -> VSetInteger
vCompRange lo hi (VSet []) = VSet [IVal lo hi]
vCompRange lo hi (VSet is) = foldr1 vIntersect (map (vCompRangeI lo hi) is)
vCompRangeI :: Integer -> Integer -> IVal -> VSetInteger
vCompRangeI lo hi (IVal l h) = VSet [IVal lo (l-1), IVal (h+1) hi]
vSing :: Integer -> VSetInteger
vSing i = VSet [IVal i i]
vGetSing :: VSetInteger -> Maybe Integer
vGetSing (VSet [IVal i i']) | i == i' = Just i
vGetSing _ = Nothing
vFromTo :: Integer -> Integer -> VSetInteger
vFromTo i j = VSet [IVal i j]
vUnionI :: IVal -> VSetInteger -> VSetInteger
vUnionI (IVal l h) (VSet is) = VSet (add l h is)
where add l h [] = [IVal l h]
add l h (i@(IVal vl vh) : is) =
if vl <= l then
if vh < l then
else if vh < h then
else
else if vl > h then
else
if vh <= h then
else
coal (IVal l1 h1 : IVal l2 h2 : is) | h1+1 == l2 = IVal l1 h2 : is
coal is = is
vUnion :: VSetInteger -> VSetInteger -> VSetInteger
vUnion (VSet is) vs = foldr vUnionI vs is
vIntersectI :: IVal -> VSetInteger -> VSetInteger
vIntersectI (IVal l h) (VSet is) = VSet (sub l h is)
where sub l h [] = []
sub l h (i@(IVal vl vh) : is) =
if vl <= l then
if vh < l then
else if vh < h then
else
else if vl > h then
[]
else
if vh <= h then
else
vIntersect :: VSetInteger -> VSetInteger -> VSetInteger
vIntersect (VSet is) vs = foldr (\ i -> vUnion (vIntersectI i vs)) vEmpty is
|
51132389bb214667d95f52682a73d16069c80d31703d148dce6ada41907ff74e
|
sethfowler/pygmalion
|
ForwardDeclarations.hs
|
# LANGUAGE QuasiQuotes #
module ForwardDeclarations (testForwardDeclarations) where
import Pygmalion.Test
import Pygmalion.Test.TH
testForwardDeclarations = runPygmalionTestWithFiles $
[ ("forward-declarations-before.cpp", [pygTest|
class is_forward_declared_not_defined_before { };
|]),
("forward-declarations.cpp", [pygTest|
class @is_forward_declared; ~[Def "forward-declarations.cpp:5:7: Definition"]~
class is_backward_declared { };
class is_forward_declared { };
class @is_backward_declared; ~[Def "forward-declarations.cpp:3:7: Definition"]~
class @is_forward_declared_not_defined_before; ~~
~[Def "forward-declarations-before.cpp:1:7: Definition"]~
class @is_forward_declared_not_defined_after; ~~
~[Def "forward-declarations-after.cpp:1:7: Definition"]~
int main(int argc, char** argv)
{
@is_backward_declared a; ~[Def "forward-declarations.cpp:3:7: Definition"]~
@is_forward_declared b; ~[Def "forward-declarations.cpp:5:7: Definition"]~
@is_forward_declared_not_defined_before* c; ~~
~[Def "forward-declarations-before.cpp:1:7: Definition"]~
@is_forward_declared_not_defined_after* d; ~~
~[Def "forward-declarations-after.cpp:1:7: Definition"]~
return 0;
}
|]),
("forward-declarations-after.cpp", [pygTest|
class is_forward_declared_not_defined_after { };
|])
]
| null |
https://raw.githubusercontent.com/sethfowler/pygmalion/d58cc3411d6a17cd05c3b0263824cd6a2f862409/tests/ForwardDeclarations.hs
|
haskell
|
# LANGUAGE QuasiQuotes #
module ForwardDeclarations (testForwardDeclarations) where
import Pygmalion.Test
import Pygmalion.Test.TH
testForwardDeclarations = runPygmalionTestWithFiles $
[ ("forward-declarations-before.cpp", [pygTest|
class is_forward_declared_not_defined_before { };
|]),
("forward-declarations.cpp", [pygTest|
class @is_forward_declared; ~[Def "forward-declarations.cpp:5:7: Definition"]~
class is_backward_declared { };
class is_forward_declared { };
class @is_backward_declared; ~[Def "forward-declarations.cpp:3:7: Definition"]~
class @is_forward_declared_not_defined_before; ~~
~[Def "forward-declarations-before.cpp:1:7: Definition"]~
class @is_forward_declared_not_defined_after; ~~
~[Def "forward-declarations-after.cpp:1:7: Definition"]~
int main(int argc, char** argv)
{
@is_backward_declared a; ~[Def "forward-declarations.cpp:3:7: Definition"]~
@is_forward_declared b; ~[Def "forward-declarations.cpp:5:7: Definition"]~
@is_forward_declared_not_defined_before* c; ~~
~[Def "forward-declarations-before.cpp:1:7: Definition"]~
@is_forward_declared_not_defined_after* d; ~~
~[Def "forward-declarations-after.cpp:1:7: Definition"]~
return 0;
}
|]),
("forward-declarations-after.cpp", [pygTest|
class is_forward_declared_not_defined_after { };
|])
]
|
|
1c1f914a5acafae98cc33fa71f48952488de2cbd483e86e230c8eebf510f15ae
|
mhuebert/yawn
|
root.cljs
|
(ns yawn.root
(:require ["react-dom/client" :as react:dom]
[applied-science.js-interop :as j]))
(defn find-or-create-element [id]
(if (or (string? id) (keyword? id))
(or
(js/document.getElementById (name id))
(-> (js/document.createElement "div")
(j/!set :id (name id))
(doto (->> js/document.body.append))))
id))
(defn render [^js root react-el] (.render root react-el))
(defn create
([el] (react:dom/createRoot (find-or-create-element el)))
([el content]
(doto (create el)
(render content))))
(defn unmount [^js root] (.unmount root))
(defn unmount-soon [^js root] (js/setTimeout #(.unmount root) 0))
| null |
https://raw.githubusercontent.com/mhuebert/yawn/ac5059c7428300136e125104edd6a05b3c18382c/src/main/yawn/root.cljs
|
clojure
|
(ns yawn.root
(:require ["react-dom/client" :as react:dom]
[applied-science.js-interop :as j]))
(defn find-or-create-element [id]
(if (or (string? id) (keyword? id))
(or
(js/document.getElementById (name id))
(-> (js/document.createElement "div")
(j/!set :id (name id))
(doto (->> js/document.body.append))))
id))
(defn render [^js root react-el] (.render root react-el))
(defn create
([el] (react:dom/createRoot (find-or-create-element el)))
([el content]
(doto (create el)
(render content))))
(defn unmount [^js root] (.unmount root))
(defn unmount-soon [^js root] (js/setTimeout #(.unmount root) 0))
|
|
a7edc18ad8cf4d829c5163e9601cdb2b47ed9430883840b1dddb4191d26a9352
|
input-output-hk/ouroboros-network
|
Lift.hs
|
-- | Lifting functions for the various types used in 'HardForkState'
--
NOTE : These are internal and not exported in the toplevel @.State@ module .
module Ouroboros.Consensus.HardFork.Combinator.State.Lift (
* Lifting functions on @f@ to @Current @f@
lift
, liftM
) where
import Data.Functor.Identity
import Ouroboros.Consensus.HardFork.Combinator.State.Types
------------------------------------------------------------------------------
Lifting functions on @f@ to
------------------------------------------------------------------------------
Lifting functions on @f@ to @Current @f@
-------------------------------------------------------------------------------}
lift :: (f blk -> f' blk) -> Current f blk -> Current f' blk
lift f = runIdentity . liftM (Identity . f)
liftM :: Functor m
=> (f blk -> m (f' blk)) -> Current f blk -> m (Current f' blk)
liftM f (Current start cur) = Current start <$> f cur
| null |
https://raw.githubusercontent.com/input-output-hk/ouroboros-network/c82309f403e99d916a76bb4d96d6812fb0a9db81/ouroboros-consensus/src/Ouroboros/Consensus/HardFork/Combinator/State/Lift.hs
|
haskell
|
| Lifting functions for the various types used in 'HardForkState'
----------------------------------------------------------------------------
----------------------------------------------------------------------------
-----------------------------------------------------------------------------}
|
NOTE : These are internal and not exported in the toplevel @.State@ module .
module Ouroboros.Consensus.HardFork.Combinator.State.Lift (
* Lifting functions on @f@ to @Current @f@
lift
, liftM
) where
import Data.Functor.Identity
import Ouroboros.Consensus.HardFork.Combinator.State.Types
Lifting functions on @f@ to
Lifting functions on @f@ to @Current @f@
lift :: (f blk -> f' blk) -> Current f blk -> Current f' blk
lift f = runIdentity . liftM (Identity . f)
liftM :: Functor m
=> (f blk -> m (f' blk)) -> Current f blk -> m (Current f' blk)
liftM f (Current start cur) = Current start <$> f cur
|
3b6a7533f2dcb588ad346948144cb19428866def929cc62e2a4276bdd4263d76
|
rurban/clisp
|
koch.lisp
|
Draw snowflake
;;;
Copyright ( C ) 2005 , 2007 , 2008 by
This is Free Software , covered by the GNU GPL v2 +
;;; See
;;;
(in-package :clx-demos)
(defun koch-point (cx width/2 height/2 scale)
(list (round (+ width/2 (* scale width/2 (realpart cx))))
(round (+ height/2 (* scale height/2 (imagpart cx))))))
this assumes clockwize traversal
(defun koch-new-points (x1 y1 x5 y5)
(let* ((vx (round (- x5 x1) 3)) (vy (round (- y5 y1) 3))
(x2 (+ x1 vx)) (y2 (+ y1 vy))
(x4 (- x5 vx)) (y4 (- y5 vy))
(cx (* (complex vx vy) #.(cis (/ pi -3))))
(x3 (round (+ x2 (realpart cx))))
(y3 (round (+ y2 (imagpart cx)))))
(and (or (/= x1 x2) (/= y1 y2))
(or (/= x2 x3) (/= y2 y3))
(or (/= x3 x4) (/= y3 y4))
(or (/= x4 x5) (/= y4 y5))
(list x2 y2 x3 y3 x4 y4))))
(defun koch-update (list)
"Update the list of points.
Returns the new list and an indicator of whether we are done or not."
(let ((len (length list)))
(when (= len 3) ; init
(return-from koch-update
(values (let ((width/2 (/ (first list) 2))
(height/2 (/ (second list) 2))
(scale (third list)))
(nconc (koch-point #C(0 -1) width/2 height/2 scale)
(koch-point #.(cis (* pi 1/6)) width/2 height/2 scale)
(koch-point #.(cis (* pi 5/6)) width/2 height/2 scale)
(koch-point #C(0 -1) width/2 height/2 scale)))
nil)))
(do* ((tail list) x1 y1 (x5 (first list)) (y5 (second list))
(ret (list y5 x5)))
((endp (cddr tail)) (values (nreverse ret) nil))
(setq x1 x5 y1 y5 tail (cddr tail) x5 (first tail) y5 (second tail))
(let ((new (koch-new-points x1 y1 x5 y5)))
(unless new (return-from koch-update (values ret t))) ; done
(setq ret (list* y5 x5 (nreconc new ret)))))))
(defun koch-usage ()
(format t "~&Usage:~% q - quit~% h - help~%"))
(defun koch-show (name value)
(format t "~&;; ~A=~S~%" name value))
(defun koch-events (dpy)
(xlib:event-case (dpy)
(:button-press (code window x y)
(format t "~&;; ~S (~S ~S ~S ~S)~%" :button-press code window x y))
(:key-press (code window)
(let ((sym (xlib:keycode->keysym dpy code 0)))
(format t "~&;; ~S (~S ~S ~:D ~:O ~:X)"
:key-press code window sym sym sym)
(case sym
(#o161 #|q|# (return-from koch-events t))
(#o150 #|h|# (koch-usage)))))
(:exposure (x y width height count)
(format t "~&;; ~S: (~S ~S ~S ~S ~S)~%"
:exposure x y width height count))))
(defun koch (&key (width 1000) (height 1000) (delay 1) (x 10) (y 10)
(scale 0.8) (font "fixed") (event-loop t))
"Koch snowflake."
(xlib:with-open-display (dpy)
(let* ((screen (xlib:display-default-screen dpy))
(root (xlib:screen-root screen))
(white-pixel (xlib:screen-white-pixel screen))
(black-pixel (xlib:screen-black-pixel screen))
(win (xlib:create-window
:parent root :x x :y y :width width :height height
:event-mask '(:exposure :button-press :button-release
:key-press :key-release)
:background white-pixel))
(fnt (xlib:open-font dpy font))
(gc (xlib:create-gcontext
:drawable win :font fnt
:foreground black-pixel :background white-pixel)))
(koch-show "dpy" dpy)
(koch-show "screen" screen)
(koch-show "root" root)
(koch-show "white-pixel" white-pixel)
(koch-show "black-pixel" black-pixel)
(koch-show "win" win)
(koch-show "font" fnt)
(koch-show "gc" gc)
(setf (xlib:wm-icon-name win) "Koch Snowflake"
(xlib:wm-name win) "Koch Snowflake")
(xlib:map-window win)
(loop :with done-p :and points = (list width height scale)
:and s1 :and s2 :with previous :for iteration :upfrom 0 :do
(setf (values points done-p) (koch-update points))
(when done-p (loop-finish))
(when previous ; remove old junk
(setf (xlib:gcontext-foreground gc) white-pixel)
(xlib:draw-glyphs win gc 30 30 s1)
(xlib:draw-glyphs win gc 30 50 s2)
(xlib:draw-lines win gc previous) ; remove old lines
(setf (xlib:gcontext-foreground gc) black-pixel))
(setq previous points
s1 (format nil "iteration: ~:D" iteration)
s2 (format nil "vertexes: ~:D" (1- (/ (length points) 2))))
(format t "~&;; ~A; ~A~%" s1 s2)
(xlib:draw-glyphs win gc 30 30 s1)
(xlib:draw-glyphs win gc 30 50 s2)
(xlib:draw-lines win gc points)
(xlib:display-finish-output dpy)
(sleep delay))
(when event-loop (koch-events dpy))
(xlib:free-gcontext gc)
(xlib:close-font fnt)
(xlib:unmap-window win)
(xlib:display-finish-output dpy))))
(provide "koch")
| null |
https://raw.githubusercontent.com/rurban/clisp/75ed2995ff8f5364bcc18727cde9438cca4e7c2c/modules/clx/new-clx/demos/koch.lisp
|
lisp
|
See
init
done
q
h
remove old junk
remove old lines
|
Draw snowflake
Copyright ( C ) 2005 , 2007 , 2008 by
This is Free Software , covered by the GNU GPL v2 +
(in-package :clx-demos)
(defun koch-point (cx width/2 height/2 scale)
(list (round (+ width/2 (* scale width/2 (realpart cx))))
(round (+ height/2 (* scale height/2 (imagpart cx))))))
this assumes clockwize traversal
(defun koch-new-points (x1 y1 x5 y5)
(let* ((vx (round (- x5 x1) 3)) (vy (round (- y5 y1) 3))
(x2 (+ x1 vx)) (y2 (+ y1 vy))
(x4 (- x5 vx)) (y4 (- y5 vy))
(cx (* (complex vx vy) #.(cis (/ pi -3))))
(x3 (round (+ x2 (realpart cx))))
(y3 (round (+ y2 (imagpart cx)))))
(and (or (/= x1 x2) (/= y1 y2))
(or (/= x2 x3) (/= y2 y3))
(or (/= x3 x4) (/= y3 y4))
(or (/= x4 x5) (/= y4 y5))
(list x2 y2 x3 y3 x4 y4))))
(defun koch-update (list)
"Update the list of points.
Returns the new list and an indicator of whether we are done or not."
(let ((len (length list)))
(return-from koch-update
(values (let ((width/2 (/ (first list) 2))
(height/2 (/ (second list) 2))
(scale (third list)))
(nconc (koch-point #C(0 -1) width/2 height/2 scale)
(koch-point #.(cis (* pi 1/6)) width/2 height/2 scale)
(koch-point #.(cis (* pi 5/6)) width/2 height/2 scale)
(koch-point #C(0 -1) width/2 height/2 scale)))
nil)))
(do* ((tail list) x1 y1 (x5 (first list)) (y5 (second list))
(ret (list y5 x5)))
((endp (cddr tail)) (values (nreverse ret) nil))
(setq x1 x5 y1 y5 tail (cddr tail) x5 (first tail) y5 (second tail))
(let ((new (koch-new-points x1 y1 x5 y5)))
(setq ret (list* y5 x5 (nreconc new ret)))))))
(defun koch-usage ()
(format t "~&Usage:~% q - quit~% h - help~%"))
(defun koch-show (name value)
(format t "~&;; ~A=~S~%" name value))
(defun koch-events (dpy)
(xlib:event-case (dpy)
(:button-press (code window x y)
(format t "~&;; ~S (~S ~S ~S ~S)~%" :button-press code window x y))
(:key-press (code window)
(let ((sym (xlib:keycode->keysym dpy code 0)))
(format t "~&;; ~S (~S ~S ~:D ~:O ~:X)"
:key-press code window sym sym sym)
(case sym
(:exposure (x y width height count)
(format t "~&;; ~S: (~S ~S ~S ~S ~S)~%"
:exposure x y width height count))))
(defun koch (&key (width 1000) (height 1000) (delay 1) (x 10) (y 10)
(scale 0.8) (font "fixed") (event-loop t))
"Koch snowflake."
(xlib:with-open-display (dpy)
(let* ((screen (xlib:display-default-screen dpy))
(root (xlib:screen-root screen))
(white-pixel (xlib:screen-white-pixel screen))
(black-pixel (xlib:screen-black-pixel screen))
(win (xlib:create-window
:parent root :x x :y y :width width :height height
:event-mask '(:exposure :button-press :button-release
:key-press :key-release)
:background white-pixel))
(fnt (xlib:open-font dpy font))
(gc (xlib:create-gcontext
:drawable win :font fnt
:foreground black-pixel :background white-pixel)))
(koch-show "dpy" dpy)
(koch-show "screen" screen)
(koch-show "root" root)
(koch-show "white-pixel" white-pixel)
(koch-show "black-pixel" black-pixel)
(koch-show "win" win)
(koch-show "font" fnt)
(koch-show "gc" gc)
(setf (xlib:wm-icon-name win) "Koch Snowflake"
(xlib:wm-name win) "Koch Snowflake")
(xlib:map-window win)
(loop :with done-p :and points = (list width height scale)
:and s1 :and s2 :with previous :for iteration :upfrom 0 :do
(setf (values points done-p) (koch-update points))
(when done-p (loop-finish))
(setf (xlib:gcontext-foreground gc) white-pixel)
(xlib:draw-glyphs win gc 30 30 s1)
(xlib:draw-glyphs win gc 30 50 s2)
(setf (xlib:gcontext-foreground gc) black-pixel))
(setq previous points
s1 (format nil "iteration: ~:D" iteration)
s2 (format nil "vertexes: ~:D" (1- (/ (length points) 2))))
(format t "~&;; ~A; ~A~%" s1 s2)
(xlib:draw-glyphs win gc 30 30 s1)
(xlib:draw-glyphs win gc 30 50 s2)
(xlib:draw-lines win gc points)
(xlib:display-finish-output dpy)
(sleep delay))
(when event-loop (koch-events dpy))
(xlib:free-gcontext gc)
(xlib:close-font fnt)
(xlib:unmap-window win)
(xlib:display-finish-output dpy))))
(provide "koch")
|
0f47f04fefa416cb6593c9e61f1cb07ce594ce11caaea724436ad920d3ad2abe
|
cognitect-labs/vase
|
spec_test.clj
|
(ns com.cognitect.vase.spec-test
(:require [com.cognitect.vase.spec :as vase.spec]
[com.cognitect.vase :as vase]
[com.cognitect.vase.service-route-table :as srt]
[clojure.spec.alpha :as s]
[clojure.spec.test.alpha :as stest]
[clojure.test :refer :all]
[io.pedestal.interceptor :as interceptor]))
(deftest route-table-spec-tests
(let [handler-fn (fn [req] {:status 200 :body "foo"})]
(is (s/valid? ::vase.spec/route-table
[["/a" :get handler-fn]
["/b" :get [(interceptor/interceptor {:enter handler-fn})]]
["/c" :get handler-fn :route-name :c]
["/d/:id" :get handler-fn :route-name :d :constraints {:id #"[0-9]+"}]]))
(testing "invalid routes"
(are [v] (not (s/valid? ::vase.spec/route-table-route v))
[]
["/a"]
["/a" :get]
["/a" :get handler-fn :route-name]
["/a" :get handler-fn :not-route-name-k :bar]
["/a" :get handler-fn :route-name :bar :constraints]
["/a" :get handler-fn :route-name :bar :constraints 1]))))
(def test-spec (srt/test-spec))
(def sample-spec (vase/load-edn-resource "sample_payload.edn"))
(deftest vase-spec-tests
(testing "full vase spec"
(doseq [vspec [test-spec sample-spec]]
(is (s/valid? ::vase.spec/spec vspec))))
(testing "descriptors"
(doseq [d ["sample_descriptor.edn"
"small_descriptor.edn"]]
(is (s/valid? ::vase.spec/descriptor (vase/load-edn-resource d))
(format "%s is not valid!" d)))))
(use-fixtures :once (fn [f]
(stest/instrument `vase/routes)
(f)
(stest/unstrument `vase/routes)))
(deftest vase-routes-fn-tests
(is (vase/routes "/api" test-spec))
(is (vase/routes "/api" []))
(is (vase/routes "/api" [test-spec]))
(is (vase/routes "/api" [test-spec sample-spec]))
(is (thrown-with-msg? clojure.lang.ExceptionInfo #"did not conform" (vase/routes "" test-spec)))
(is (thrown-with-msg? clojure.lang.ExceptionInfo #"did not conform" (vase/routes :not-a-path test-spec)))
(is (thrown-with-msg? clojure.lang.ExceptionInfo #"did not conform" (vase/routes "/api" (:descriptor test-spec)))))
| null |
https://raw.githubusercontent.com/cognitect-labs/vase/d882bc8f28e8af2077b55c80e069aa2238f646b7/test/com/cognitect/vase/spec_test.clj
|
clojure
|
(ns com.cognitect.vase.spec-test
(:require [com.cognitect.vase.spec :as vase.spec]
[com.cognitect.vase :as vase]
[com.cognitect.vase.service-route-table :as srt]
[clojure.spec.alpha :as s]
[clojure.spec.test.alpha :as stest]
[clojure.test :refer :all]
[io.pedestal.interceptor :as interceptor]))
(deftest route-table-spec-tests
(let [handler-fn (fn [req] {:status 200 :body "foo"})]
(is (s/valid? ::vase.spec/route-table
[["/a" :get handler-fn]
["/b" :get [(interceptor/interceptor {:enter handler-fn})]]
["/c" :get handler-fn :route-name :c]
["/d/:id" :get handler-fn :route-name :d :constraints {:id #"[0-9]+"}]]))
(testing "invalid routes"
(are [v] (not (s/valid? ::vase.spec/route-table-route v))
[]
["/a"]
["/a" :get]
["/a" :get handler-fn :route-name]
["/a" :get handler-fn :not-route-name-k :bar]
["/a" :get handler-fn :route-name :bar :constraints]
["/a" :get handler-fn :route-name :bar :constraints 1]))))
(def test-spec (srt/test-spec))
(def sample-spec (vase/load-edn-resource "sample_payload.edn"))
(deftest vase-spec-tests
(testing "full vase spec"
(doseq [vspec [test-spec sample-spec]]
(is (s/valid? ::vase.spec/spec vspec))))
(testing "descriptors"
(doseq [d ["sample_descriptor.edn"
"small_descriptor.edn"]]
(is (s/valid? ::vase.spec/descriptor (vase/load-edn-resource d))
(format "%s is not valid!" d)))))
(use-fixtures :once (fn [f]
(stest/instrument `vase/routes)
(f)
(stest/unstrument `vase/routes)))
(deftest vase-routes-fn-tests
(is (vase/routes "/api" test-spec))
(is (vase/routes "/api" []))
(is (vase/routes "/api" [test-spec]))
(is (vase/routes "/api" [test-spec sample-spec]))
(is (thrown-with-msg? clojure.lang.ExceptionInfo #"did not conform" (vase/routes "" test-spec)))
(is (thrown-with-msg? clojure.lang.ExceptionInfo #"did not conform" (vase/routes :not-a-path test-spec)))
(is (thrown-with-msg? clojure.lang.ExceptionInfo #"did not conform" (vase/routes "/api" (:descriptor test-spec)))))
|
|
df93cb7c368544bd0e480b0d655a25adf186ab5710db1098084b81c4bce39636
|
project-oak/hafnium-verification
|
cPredicates.ml
|
* Copyright ( c ) Facebook , Inc. and its affiliates .
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree .
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
open! IStd
open Types_lexer
module L = Logging
let parsed_type_map : Ctl_parser_types.abs_ctype String.Map.t ref = ref String.Map.empty
let rec objc_class_of_pointer_type type_ptr =
match CAst_utils.get_type type_ptr with
| Some (ObjCInterfaceType (_, decl_ptr)) ->
CAst_utils.get_decl decl_ptr
| Some (ObjCObjectPointerType (_, inner_qual_type)) ->
objc_class_of_pointer_type inner_qual_type.qt_type_ptr
| Some (AttributedType (type_info, _)) -> (
match type_info.ti_desugared_type with
| Some type_ptr ->
objc_class_of_pointer_type type_ptr
| None ->
None )
| _ ->
None
let receiver_class_method_call an =
match an with
| Ctl_parser_types.Stmt (ObjCMessageExpr (_, _, _, obj_c_message_expr_info)) -> (
match obj_c_message_expr_info.omei_receiver_kind with
| `Class qt ->
CAst_utils.get_decl_from_typ_ptr qt.qt_type_ptr
| _ ->
None )
| _ ->
None
let receiver_instance_method_call an =
match an with
| Ctl_parser_types.Stmt (ObjCMessageExpr (_, args, _, obj_c_message_expr_info)) -> (
match obj_c_message_expr_info.omei_receiver_kind with
| `Instance -> (
match args with
| receiver :: _ -> (
match Clang_ast_proj.get_expr_tuple receiver with
| Some (_, _, expr_info) ->
objc_class_of_pointer_type expr_info.ei_qual_type.qt_type_ptr
| None ->
None )
| [] ->
None )
| _ ->
None )
| _ ->
None
let receiver_method_call an =
match receiver_class_method_call an with
| Some decl ->
Some decl
| None ->
receiver_instance_method_call an
let declaration_name decl =
match Clang_ast_proj.get_named_decl_tuple decl with
| Some (_, ndi) ->
Some ndi.ni_name
| None ->
None
let get_available_attr_ios_sdk an =
match an with
| Ctl_parser_types.Decl decl ->
let decl_info = Clang_ast_proj.get_decl_tuple decl in
List.find_map decl_info.di_attributes ~f:(function
| `AvailabilityAttr (_attr_info, {Clang_ast_t.aai_platform= Some "ios"; aai_introduced}) ->
let get_opt_number = Option.value ~default:0 in
Some
(Printf.sprintf "%d.%d" aai_introduced.vt_major
(get_opt_number aai_introduced.vt_minor))
| _ ->
None )
| _ ->
None
let get_ivar_attributes ivar_decl =
let open Clang_ast_t in
match ivar_decl with
| ObjCIvarDecl (ivar_decl_info, _, _, _, _) -> (
match CAst_utils.get_property_of_ivar ivar_decl_info.Clang_ast_t.di_pointer with
| Some (ObjCPropertyDecl (_, _, obj_c_property_decl_info)) ->
obj_c_property_decl_info.Clang_ast_t.opdi_property_attributes
| _ ->
[] )
| _ ->
[]
list of cxx references captured by
let captured_variables_cxx_ref an =
let open Clang_ast_t in
let capture_var_is_cxx_ref reference_captured_vars captured_var =
let decl_ref_opt = captured_var.Clang_ast_t.bcv_variable in
match CAst_utils.get_decl_opt_with_decl_ref_opt decl_ref_opt with
| Some (VarDecl (_, named_decl_info, qual_type, _))
| Some (ParmVarDecl (_, named_decl_info, qual_type, _))
| Some (ImplicitParamDecl (_, named_decl_info, qual_type, _)) -> (
match CAst_utils.get_desugared_type qual_type.Clang_ast_t.qt_type_ptr with
| Some (RValueReferenceType _) | Some (LValueReferenceType _) ->
named_decl_info :: reference_captured_vars
| _ ->
reference_captured_vars )
| _ ->
reference_captured_vars
in
match an with
| Ctl_parser_types.Decl (BlockDecl (_, bdi)) ->
List.fold ~f:capture_var_is_cxx_ref ~init:[] bdi.bdi_captured_variables
| _ ->
[]
let objc_block_is_capturing_values an =
match an with
| Ctl_parser_types.Decl (Clang_ast_t.BlockDecl (_, bdi)) ->
not (List.is_empty bdi.bdi_captured_variables)
| _ ->
false
type t = ALVar.formula_id * (* (name, [param1,...,paramK]) *) ALVar.alexp list [@@deriving compare]
let pp_predicate fmt (name_, arglist_) =
let name = ALVar.formula_id_to_string name_ in
let arglist = List.map ~f:ALVar.alexp_to_string arglist_ in
Format.fprintf fmt "%s(%a)" name (Pp.comma_seq Format.pp_print_string) arglist
(* an is a declaration whose name contains a regexp defined by re *)
let declaration_has_name an name =
match an with
| Ctl_parser_types.Decl d -> (
match declaration_name d with
| Some decl_name ->
ALVar.compare_str_with_alexp decl_name name
| _ ->
false )
| _ ->
false
let rec is_subclass_of decl name =
match CAst_utils.get_superclass_curr_class_objc_from_decl decl with
| Some super_ref -> (
let ndi = match super_ref.Clang_ast_t.dr_name with Some ni -> ni | _ -> assert false in
if ALVar.compare_str_with_alexp ndi.ni_name name then true
else
match CAst_utils.get_decl_opt_with_decl_ref_opt (Some super_ref) with
| Some decl ->
is_subclass_of decl name
| None ->
false )
| None ->
false
(* is an objc interface with name expected_name *)
let is_objc_interface_named an expected_name =
match an with
| Ctl_parser_types.Decl (Clang_ast_t.ObjCInterfaceDecl _) ->
declaration_has_name an expected_name
| _ ->
false
(* is an objc implementation with name expected_name *)
let is_objc_implementation_named an expected_name =
match an with
| Ctl_parser_types.Decl (Clang_ast_t.ObjCImplementationDecl _) ->
declaration_has_name an expected_name
| _ ->
false
let is_objc_class_named an re = is_objc_interface_named an re || is_objc_implementation_named an re
(* is an objc category interface with class name expected_name *)
let is_objc_category_interface_on_class_named an expected_name =
match an with
| Ctl_parser_types.Decl (Clang_ast_t.ObjCCategoryDecl (_, _, _, _, ocdi)) -> (
match CAst_utils.get_decl_opt_with_decl_ref_opt ocdi.odi_class_interface with
| Some decl_ref ->
is_objc_interface_named (Decl decl_ref) expected_name
| _ ->
false )
| _ ->
false
(* is an objc category implementation with class name expected_name *)
let is_objc_category_implementation_on_class_named an expected_name =
match an with
| Ctl_parser_types.Decl (Clang_ast_t.ObjCCategoryImplDecl (_, _, _, _, ocidi)) -> (
match CAst_utils.get_decl_opt_with_decl_ref_opt ocidi.ocidi_class_interface with
| Some decl_ref ->
is_objc_interface_named (Decl decl_ref) expected_name
| _ ->
false )
| _ ->
false
let is_objc_category_on_class_named an re =
is_objc_category_interface_on_class_named an re
|| is_objc_category_implementation_on_class_named an re
(* is an objc category interface with superclass name expected_name *)
let is_objc_category_interface_on_subclass_of an expected_name =
match an with
| Ctl_parser_types.Decl (Clang_ast_t.ObjCCategoryDecl (_, _, _, _, ocdi)) -> (
match CAst_utils.get_decl_opt_with_decl_ref_opt ocdi.odi_class_interface with
| Some decl_ref ->
is_subclass_of decl_ref expected_name
| _ ->
false )
| _ ->
false
(* is an objc category implementation with superclass name expected_name *)
let is_objc_category_implementation_on_subclass_of an expected_name =
match an with
| Ctl_parser_types.Decl (Clang_ast_t.ObjCCategoryImplDecl (_, _, _, _, ocidi)) -> (
match CAst_utils.get_decl_opt_with_decl_ref_opt ocidi.ocidi_class_interface with
| Some decl_ref ->
is_subclass_of decl_ref expected_name
| _ ->
false )
| _ ->
false
let is_objc_category_on_subclass_of an expected_name =
is_objc_category_interface_on_subclass_of an expected_name
|| is_objc_category_implementation_on_subclass_of an expected_name
(* is an objc category interface with name expected_name *)
let is_objc_category_interface_named an expected_name =
match an with
| Ctl_parser_types.Decl (Clang_ast_t.ObjCCategoryDecl _) ->
declaration_has_name an expected_name
| _ ->
false
(* is an objc category implementation with name expected_name *)
let is_objc_category_implementation_named an expected_name =
match an with
| Ctl_parser_types.Decl (Clang_ast_t.ObjCCategoryImplDecl _) ->
declaration_has_name an expected_name
| _ ->
false
let is_objc_category_named an re =
is_objc_category_interface_named an re || is_objc_category_implementation_named an re
let is_objc_protocol_named an re =
match an with
| Ctl_parser_types.Decl (Clang_ast_t.ObjCProtocolDecl _) ->
declaration_has_name an re
| _ ->
false
let is_objc_class_method_named an name =
match an with
| Ctl_parser_types.Decl (Clang_ast_t.ObjCMethodDecl (_, _, omdi)) ->
declaration_has_name an name && not omdi.omdi_is_instance_method
| _ ->
false
let is_objc_instance_method_named an name =
match an with
| Ctl_parser_types.Decl (Clang_ast_t.ObjCMethodDecl (_, _, omdi)) ->
declaration_has_name an name && omdi.omdi_is_instance_method
| _ ->
false
let is_objc_method_named an name =
match an with
| Ctl_parser_types.Decl (Clang_ast_t.ObjCMethodDecl _) ->
declaration_has_name an name
| _ ->
false
let is_objc_method_overriding an =
match an with
| Ctl_parser_types.Decl (Clang_ast_t.ObjCMethodDecl (_, _, mdi)) ->
mdi.omdi_is_overriding
| _ ->
false
let decl_list_has_objc_method decl_list method_name is_instance_method =
List.exists
~f:(fun decl ->
match decl with
| Clang_ast_t.ObjCMethodDecl (_, ni, omdi) ->
Bool.equal omdi.omdi_is_instance_method is_instance_method
&& String.equal ni.ni_name method_name
| _ ->
false )
decl_list
let current_objc_container context =
let open CLintersContext in
let current_objc_class = context.current_objc_class in
let current_objc_category = context.current_objc_category in
let current_objc_protocol = context.current_objc_protocol in
if not (Option.is_none current_objc_class) then current_objc_class
else if not (Option.is_none current_objc_category) then current_objc_category
else if not (Option.is_none current_objc_protocol) then current_objc_protocol
else None
let is_objc_method_exposed context an =
let open Clang_ast_t in
if is_objc_method_overriding an then true
else
match an with
| Ctl_parser_types.Decl (ObjCMethodDecl (_, ndi, mdi)) -> (
let method_name = ndi.ni_name in
let is_instance_method = mdi.omdi_is_instance_method in
match current_objc_container context with
| Some (ObjCImplementationDecl (_, _, _, _, oidi)) -> (
match CAst_utils.get_decl_opt_with_decl_ref_opt oidi.oidi_class_interface with
| Some (ObjCInterfaceDecl (_, _, decl_list, _, otdi)) ->
decl_list_has_objc_method decl_list method_name is_instance_method
|| List.exists
~f:(fun decl_ref ->
match CAst_utils.get_decl decl_ref.dr_decl_pointer with
| Some (ObjCCategoryDecl (_, ni, decl_list, _, _)) ->
String.equal ni.ni_name ""
&& decl_list_has_objc_method decl_list method_name is_instance_method
| _ ->
false )
otdi.otdi_known_categories
| _ ->
false )
| Some (ObjCCategoryImplDecl (_, _, _, _, ocidi)) -> (
match CAst_utils.get_decl_opt_with_decl_ref_opt ocidi.ocidi_category_decl with
| Some (ObjCCategoryDecl (_, _, decl_list, _, _)) ->
decl_list_has_objc_method decl_list method_name is_instance_method
| _ ->
false )
| _ ->
false )
| _ ->
false
let get_selector an =
match an with
| Ctl_parser_types.Stmt (Clang_ast_t.ObjCMessageExpr (_, _, _, omei)) ->
Some omei.omei_selector
| _ ->
None
let receiver_objc_type_name an =
match an with
| Ctl_parser_types.Stmt (ObjCMessageExpr (_, receiver :: _, _, {omei_receiver_kind= `Instance}))
->
Clang_ast_proj.get_expr_tuple receiver
|> Option.bind ~f:(fun (_, _, expr_info) ->
CAst_utils.name_opt_of_typedef_qual_type expr_info.Clang_ast_t.ei_qual_type )
|> Option.map ~f:QualifiedCppName.to_qual_string
| _ ->
None
let is_receiver_objc_class_type an =
match receiver_objc_type_name an with
| Some type_name ->
String.equal type_name "Class"
| None ->
false
let is_receiver_objc_id_type an =
match receiver_objc_type_name an with
| Some type_name ->
String.equal type_name "id"
| None ->
false
let objc_message_receiver context an =
match an with
| Ctl_parser_types.Stmt (ObjCMessageExpr (_, args, _, omei)) -> (
match omei.omei_receiver_kind with
| `SuperClass | `SuperInstance -> (
match current_objc_container context with
| Some container ->
let decl_ref_opt = CAst_utils.get_superclass_curr_class_objc_from_decl container in
CAst_utils.get_decl_opt_with_decl_ref_opt decl_ref_opt
| _ ->
None )
| `Class qt ->
CAst_utils.get_decl_from_typ_ptr qt.qt_type_ptr
| `Instance -> (
match args with
| receiver :: _ -> (
match receiver with
| ObjCMessageExpr (_, _, _, sub_omei) -> (
match CAst_utils.get_decl_opt sub_omei.omei_decl_pointer with
| Some (ObjCMethodDecl (_, _, omdi)) ->
CAst_utils.qual_type_to_objc_interface omdi.omdi_result_type
| _ ->
None )
| PseudoObjectExpr (_, _, ei) | ImplicitCastExpr (_, _, ei, _) | ParenExpr (_, _, ei) ->
CAst_utils.qual_type_to_objc_interface ei.ei_qual_type
| _ ->
None )
| [] ->
None ) )
| _ ->
None
(* an |= call_method(m) where the name must be exactly m *)
let call_method an m =
match get_selector an with Some selector -> ALVar.compare_str_with_alexp selector m | _ -> false
let call_class_method an mname =
match an with
| Ctl_parser_types.Stmt (Clang_ast_t.ObjCMessageExpr (_, _, _, omei)) -> (
match omei.omei_receiver_kind with
| `SuperClass | `Class _ ->
ALVar.compare_str_with_alexp omei.omei_selector mname
| `Instance ->
(* The ObjC class type, 'Class', is treated as an instance receiver kind.
We need to check if the receiver is the class type to catch cases like
[[self class] myClassMethod] *)
ALVar.compare_str_with_alexp omei.omei_selector mname && is_receiver_objc_class_type an
| _ ->
false )
| _ ->
false
(* an is a node calling method whose name contains mname of a class. *)
let call_instance_method an mname =
match an with
| Ctl_parser_types.Stmt (Clang_ast_t.ObjCMessageExpr (_, _, _, omei)) -> (
match omei.omei_receiver_kind with
| `SuperInstance ->
ALVar.compare_str_with_alexp omei.omei_selector mname
| `Instance ->
(* The ObjC class type, 'Class', is treated as an instance receiver kind.
We need to verify the receiver is not the class type to avoid cases like
[[self class] myClassMethod] *)
ALVar.compare_str_with_alexp omei.omei_selector mname
&& not (is_receiver_objc_class_type an)
| _ ->
false )
| _ ->
false
let adhere_to_protocol an =
match an with
| Ctl_parser_types.Decl (Clang_ast_t.ObjCInterfaceDecl (_, _, _, _, idi)) ->
not (List.is_empty idi.otdi_protocols)
| _ ->
false
let is_objc_extension lcxt =
CGeneral_utils.is_objc_extension lcxt.CLintersContext.translation_unit_context
let is_global_var an =
match an with Ctl_parser_types.Decl d -> CAst_utils.is_syntactically_global_var d | _ -> false
let is_static_local_var an =
match an with Ctl_parser_types.Decl d -> CAst_utils.is_static_local_var d | _ -> false
let is_static_var an =
match an with Ctl_parser_types.Decl (VarDecl (_, _, _, vdi)) -> vdi.vdi_is_static | _ -> false
let is_extern_var an =
match an with Ctl_parser_types.Decl (VarDecl (_, _, _, vdi)) -> vdi.vdi_is_extern | _ -> false
let is_const_expr_var an =
match an with Ctl_parser_types.Decl d -> CAst_utils.is_const_expr_var d | _ -> false
let is_init_integral_constant_expr an =
match an with
| Ctl_parser_types.Decl d -> (
match d with Clang_ast_t.VarDecl (_, _, _, vdi) -> vdi.vdi_is_init_ice | _ -> false )
| _ ->
false
let is_qual_type_const an =
match an with
| Ctl_parser_types.Stmt s -> (
match Clang_ast_proj.get_expr_tuple s with
| Some (_, _, ei) ->
ei.Clang_ast_t.ei_qual_type.qt_is_const
| _ ->
false )
| Ctl_parser_types.Decl (Clang_ast_t.VarDecl (_, _, qt, _)) ->
qt.qt_is_const
| _ ->
false
let objc_class_has_only_one_constructor_method_named an re =
let open Clang_ast_t in
let is_class_method d =
match d with
| Clang_ast_t.ObjCMethodDecl (_, _, omdi) ->
not omdi.omdi_is_instance_method
| _ ->
false
in
match an with
| Ctl_parser_types.Decl (ObjCImplementationDecl (_, _, decls, _, _)) -> (
match List.filter decls ~f:(fun d -> is_class_method d) with
| [n] ->
is_objc_class_method_named (Ctl_parser_types.Decl n) re
| _ ->
false )
| _ ->
false
let has_init_list_const_expr an =
let rec fold lexp = List.fold ~f:(fun acc e -> is_const_expr' e && acc) ~init:true lexp
and is_const_expr' exp =
let open Clang_ast_t in
let res =
match exp with
| IntegerLiteral _ | StringLiteral _ ->
true
| DeclRefExpr (_, _, _, drei) -> (
match drei.drti_decl_ref with
| Some dr -> (
match dr.dr_kind with `EnumConstant -> true | _ -> false )
| _ ->
false )
| CallExpr (_, _ :: params, _) ->
fold params
| _ -> (
match Clang_ast_proj.get_expr_tuple exp with
| Some (_, sub_exps, _) ->
fold sub_exps
| _ ->
false )
in
L.(debug Analysis Verbose)
"@\n\n[has_init_list_const_expr] EVALUATE EXP '%a' result = '%b'@\n"
(Pp.of_string ~f:Clang_ast_proj.get_stmt_kind_string)
exp res ;
res
in
match an with
| Ctl_parser_types.Stmt (Clang_ast_t.InitListExpr (_, sub_exps, _)) ->
fold sub_exps
| _ ->
false
let decl_ref_name qualified ?kind name st =
match st with
| Clang_ast_t.DeclRefExpr (_, _, _, drti) -> (
match drti.drti_decl_ref with
| Some dr -> (
let ndi, _, _ = CAst_utils.get_info_from_decl_ref dr in
let qname =
if qualified then String.concat ~sep:"::" (List.rev ndi.ni_qual_name) else ndi.ni_name
in
let has_right_name = ALVar.compare_str_with_alexp qname name in
match kind with
| Some decl_kind ->
has_right_name && PolyVariantEqual.( = ) dr.Clang_ast_t.dr_kind decl_kind
| None ->
has_right_name )
| _ ->
false )
| _ ->
false
let declaration_ref_name ?kind an name =
match an with Ctl_parser_types.Stmt st -> decl_ref_name false ?kind name st | _ -> false
let call_function an name =
match an with
| Ctl_parser_types.Stmt st ->
CAst_utils.exists_eventually_st (decl_ref_name false ~kind:`Function) name st
| _ ->
false
let call_qualified_function an name =
match an with
| Ctl_parser_types.Stmt st ->
CAst_utils.exists_eventually_st (decl_ref_name true ~kind:`Function) name st
| _ ->
false
let is_enum_constant an name =
match an with
| Ctl_parser_types.Stmt st ->
decl_ref_name false ~kind:`EnumConstant name st
| _ ->
false
let is_enum_constant_of_enum an name =
match an with
| Ctl_parser_types.Stmt (Clang_ast_t.DeclRefExpr (_, _, _, drti)) -> (
match drti.drti_decl_ref with
| Some dr -> (
let ndi, _, _ = CAst_utils.get_info_from_decl_ref dr in
let qual_name = CAst_utils.get_qualified_name ndi in
match QualifiedCppName.extract_last qual_name with
| Some (_, stripped_qual_name) -> (
match QualifiedCppName.extract_last stripped_qual_name with
| Some (enum_name, _) ->
PolyVariantEqual.( = ) dr.Clang_ast_t.dr_kind `EnumConstant
&& ALVar.compare_str_with_alexp enum_name name
| _ ->
false )
| _ ->
false )
| _ ->
false )
| _ ->
false
let is_strong_property an =
match an with
| Ctl_parser_types.Decl (Clang_ast_t.ObjCPropertyDecl (_, _, pdi)) ->
ObjcProperty_decl.is_strong_property pdi
| _ ->
false
let is_weak_property an =
match an with
| Ctl_parser_types.Decl (Clang_ast_t.ObjCPropertyDecl (_, _, pdi)) ->
ObjcProperty_decl.is_weak_property pdi
| _ ->
false
let is_assign_property an =
match an with
| Ctl_parser_types.Decl (Clang_ast_t.ObjCPropertyDecl (_, _, pdi)) ->
ObjcProperty_decl.is_assign_property pdi
| _ ->
false
let is_property_pointer_type an =
let open Clang_ast_t in
match an with
| Ctl_parser_types.Decl (ObjCPropertyDecl (_, _, pdi)) -> (
match CAst_utils.get_desugared_type pdi.opdi_qual_type.Clang_ast_t.qt_type_ptr with
| Some (MemberPointerType _) | Some (ObjCObjectPointerType _) | Some (BlockPointerType _) ->
true
| Some (TypedefType (_, tti)) ->
let typedef_str =
CAst_utils.name_of_typedef_type_info tti |> QualifiedCppName.to_qual_string
in
String.equal typedef_str CFrontend_config.id_cl
| exception Caml.Not_found ->
false
| _ ->
false )
| _ ->
false
let context_in_synchronized_block context = context.CLintersContext.in_synchronized_block
(* checks if ivar is defined among a set of fields and if it is atomic *)
let is_ivar_atomic an =
match an with
| Ctl_parser_types.Stmt (Clang_ast_t.ObjCIvarRefExpr (_, _, _, irei)) -> (
let dr_ref = irei.Clang_ast_t.ovrei_decl_ref in
let ivar_pointer = dr_ref.Clang_ast_t.dr_decl_pointer in
match CAst_utils.get_decl ivar_pointer with
| Some d ->
let attributes = get_ivar_attributes d in
List.exists ~f:(PolyVariantEqual.( = ) `Atomic) attributes
| _ ->
false )
| _ ->
false
let is_method_property_accessor_of_ivar an context =
let open Clang_ast_t in
match an with
| Ctl_parser_types.Stmt (ObjCIvarRefExpr (_, _, _, irei)) -> (
let dr_ref = irei.Clang_ast_t.ovrei_decl_ref in
let ivar_pointer = dr_ref.Clang_ast_t.dr_decl_pointer in
match context.CLintersContext.current_method with
| Some (ObjCMethodDecl (_, _, mdi)) ->
if mdi.omdi_is_property_accessor then
let property_opt = mdi.omdi_property_decl in
match CAst_utils.get_decl_opt_with_decl_ref_opt property_opt with
| Some (ObjCPropertyDecl (_, _, pdi)) -> (
match pdi.opdi_ivar_decl with
| Some decl_ref ->
Int.equal decl_ref.dr_decl_pointer ivar_pointer
| None ->
false )
| _ ->
false
else false
| _ ->
false )
| _ ->
false
let get_method_name_from_context context =
match context.CLintersContext.current_method with
| Some method_decl -> (
match Clang_ast_proj.get_named_decl_tuple method_decl with
| Some (_, mnd) ->
mnd.Clang_ast_t.ni_name
| _ ->
"" )
| _ ->
""
let is_objc_constructor context =
Procname.ObjC_Cpp.is_objc_constructor (get_method_name_from_context context)
let is_objc_dealloc context =
Procname.ObjC_Cpp.is_objc_dealloc (get_method_name_from_context context)
let is_in_method context name =
let current_method_name = get_method_name_from_context context in
ALVar.compare_str_with_alexp current_method_name name
let is_in_objc_class_method context name =
match context.CLintersContext.current_method with
| Some (ObjCMethodDecl (_, _, omdi) as objc_method) ->
declaration_has_name (Decl objc_method) name && not omdi.omdi_is_instance_method
| _ ->
false
let is_in_objc_instance_method context name =
match context.CLintersContext.current_method with
| Some (ObjCMethodDecl (_, _, omdi) as objc_method) ->
declaration_has_name (Decl objc_method) name && omdi.omdi_is_instance_method
| _ ->
false
let is_in_objc_method context name =
is_in_objc_class_method context name || is_in_objc_instance_method context name
let is_in_function context name =
match context.CLintersContext.current_method with
| Some (FunctionDecl _) ->
is_in_method context name
| _ ->
false
let is_in_cxx_method context name =
match context.CLintersContext.current_method with
| Some (CXXMethodDecl _) ->
is_in_method context name
| _ ->
false
let is_in_cxx_constructor context name =
match context.CLintersContext.current_method with
| Some (CXXConstructorDecl _) ->
is_in_method context name
| _ ->
false
let is_in_cxx_destructor context name =
match context.CLintersContext.current_method with
| Some (CXXDestructorDecl _) ->
is_in_method context name
| _ ->
false
let cxx_construct_expr_has_no_parameters an =
match an with
| Ctl_parser_types.Stmt (Clang_ast_t.CXXConstructExpr (_, [], _, _)) ->
true
| _ ->
false
let cxx_construct_expr_has_name an name =
match an with
| Ctl_parser_types.Stmt (Clang_ast_t.CXXConstructExpr (_, _, _, xcei)) -> (
match xcei.xcei_decl_ref.dr_name with
| Some ni ->
ALVar.compare_str_with_alexp ni.ni_name name
| _ ->
false )
| _ ->
false
let is_optional_objc_method an =
match an with
| Ctl_parser_types.Decl (Clang_ast_t.ObjCMethodDecl (_, _, omdi)) ->
omdi.omdi_is_optional
| _ ->
false
let is_call_to_optional_objc_method an =
let open Clang_ast_t in
match an with
| Ctl_parser_types.Stmt (ObjCMessageExpr (_, _, _, omei)) -> (
match CAst_utils.get_decl_opt omei.omei_decl_pointer with
| Some d ->
is_optional_objc_method (Ctl_parser_types.Decl d)
| _ ->
false )
| _ ->
false
let is_in_block context =
match context.CLintersContext.current_method with Some (BlockDecl _) -> true | _ -> false
let is_in_objc_subclass_of context name =
match context.CLintersContext.current_objc_class with
| Some cls ->
is_subclass_of cls name
| None ->
false
let is_in_objc_interface_named context name =
match context.CLintersContext.current_objc_class with
| Some cls ->
is_objc_interface_named (Decl cls) name
| None ->
false
let is_in_objc_implementation_named context name =
match context.CLintersContext.current_objc_class with
| Some cls ->
is_objc_implementation_named (Decl cls) name
| None ->
false
let is_in_objc_class_named context name =
match context.CLintersContext.current_objc_class with
| Some cls ->
is_objc_class_named (Decl cls) name
| None ->
false
let is_in_objc_category_interface_on_class_named context name =
match context.CLintersContext.current_objc_category with
| Some cat ->
is_objc_category_interface_on_class_named (Decl cat) name
| None ->
false
let is_in_objc_category_implementation_on_class_named context name =
match context.CLintersContext.current_objc_category with
| Some cat ->
is_objc_category_implementation_on_class_named (Decl cat) name
| None ->
false
let is_in_objc_category_on_class_named context name =
match context.CLintersContext.current_objc_category with
| Some cat ->
is_objc_category_on_class_named (Decl cat) name
| None ->
false
let is_in_objc_category_interface_on_subclass_of context name =
match context.CLintersContext.current_objc_category with
| Some cat ->
is_objc_category_interface_on_subclass_of (Decl cat) name
| None ->
false
let is_in_objc_category_implementation_on_subclass_of context name =
match context.CLintersContext.current_objc_category with
| Some cat ->
is_objc_category_implementation_on_subclass_of (Decl cat) name
| None ->
false
let is_in_objc_category_on_subclass_of context name =
match context.CLintersContext.current_objc_category with
| Some cat ->
is_objc_category_on_subclass_of (Decl cat) name
| None ->
false
let is_in_objc_category_interface_named context name =
match context.CLintersContext.current_objc_category with
| Some cat ->
is_objc_category_interface_named (Decl cat) name
| None ->
false
let is_in_objc_category_implementation_named context name =
match context.CLintersContext.current_objc_category with
| Some cat ->
is_objc_category_implementation_named (Decl cat) name
| None ->
false
let is_in_objc_category_named context name =
match context.CLintersContext.current_objc_category with
| Some cat ->
is_objc_category_named (Decl cat) name
| None ->
false
let is_in_objc_protocol_named context name =
match context.CLintersContext.current_objc_protocol with
| Some protocol ->
is_objc_protocol_named (Decl protocol) name
| None ->
false
let is_receiver_subclass_of context an cname =
match objc_message_receiver context an with
| Some receiver ->
is_subclass_of receiver cname
| _ ->
false
let is_receiver_class_named context an cname =
match objc_message_receiver context an with
| Some receiver ->
declaration_has_name (Decl receiver) cname
| _ ->
false
let is_receiver_super an =
match an with
| Ctl_parser_types.Stmt
(ObjCMessageExpr (_, _, _, {omei_receiver_kind= `SuperClass | `SuperInstance})) ->
true
| _ ->
false
let is_receiver_self an =
match an with
| Ctl_parser_types.Stmt (Clang_ast_t.ObjCMessageExpr (_, fst_param :: _, _, _)) ->
CAst_utils.exists_eventually_st
(decl_ref_name false ~kind:`ImplicitParam)
(ALVar.Const CFrontend_config.self) fst_param
| _ ->
false
let captures_cxx_references an = List.length (captured_variables_cxx_ref an) > 0
let is_binop_with_kind an alexp_kind =
let str_kind = ALVar.alexp_to_string alexp_kind in
if not (Clang_ast_proj.is_valid_binop_kind_name str_kind) then
L.(die ExternalError) "Binary operator kind '%s' is not valid" str_kind ;
match an with
| Ctl_parser_types.Stmt (Clang_ast_t.BinaryOperator (_, _, _, boi)) ->
ALVar.compare_str_with_alexp (Clang_ast_proj.string_of_binop_kind boi.boi_kind) alexp_kind
| _ ->
false
let is_unop_with_kind an alexp_kind =
let str_kind = ALVar.alexp_to_string alexp_kind in
if not (Clang_ast_proj.is_valid_unop_kind_name str_kind) then
L.(die ExternalError) "Unary operator kind '%s' is not valid" str_kind ;
match an with
| Ctl_parser_types.Stmt (Clang_ast_t.UnaryOperator (_, _, _, uoi)) ->
ALVar.compare_str_with_alexp (Clang_ast_proj.string_of_unop_kind uoi.uoi_kind) alexp_kind
| _ ->
false
let has_cast_kind an alexp_kind =
match an with
| Ctl_parser_types.Decl _ ->
false
| Ctl_parser_types.Stmt stmt -> (
let str_kind = ALVar.alexp_to_string alexp_kind in
match Clang_ast_proj.get_cast_kind stmt with
| Some cast_kind ->
let cast_kind_str = Clang_ast_proj.string_of_cast_kind cast_kind in
String.equal cast_kind_str str_kind
| None ->
false )
let is_node an nodename =
let nodename_str = ALVar.alexp_to_string nodename in
if not (Clang_ast_proj.is_valid_astnode_kind nodename_str) then
L.(die ExternalError) "Node '%s' is not a valid AST node" nodename_str ;
let an_str =
match an with
| Ctl_parser_types.Stmt s ->
Clang_ast_proj.get_stmt_kind_string s
| Ctl_parser_types.Decl d ->
Clang_ast_proj.get_decl_kind_string d
in
ALVar.compare_str_with_alexp an_str nodename
let is_ptr_to_objc_class typ class_name =
match typ with
| Some (Clang_ast_t.ObjCObjectPointerType (_, {Clang_ast_t.qt_type_ptr})) -> (
match CAst_utils.get_desugared_type qt_type_ptr with
| Some (ObjCInterfaceType (_, ptr)) -> (
match CAst_utils.get_decl ptr with
| Some (ObjCInterfaceDecl (_, ndi, _, _, _)) ->
ALVar.compare_str_with_alexp ndi.ni_name class_name
| _ ->
false )
| _ ->
false )
| _ ->
false
(* node an is of class classname *)
let isa an classname =
match an with
| Ctl_parser_types.Stmt stmt -> (
match Clang_ast_proj.get_expr_tuple stmt with
| Some (_, _, expr_info) ->
let typ = CAst_utils.get_desugared_type expr_info.ei_qual_type.qt_type_ptr in
is_ptr_to_objc_class typ classname
| _ ->
false )
| _ ->
false
let is_class an re = is_objc_class_named an re
(* an is an expression @selector with whose name in the language of re *)
let is_at_selector_with_name an re =
match an with
| Ctl_parser_types.Stmt (ObjCSelectorExpr (_, _, _, s)) ->
ALVar.compare_str_with_alexp s re
| _ ->
false
let iphoneos_target_sdk_version_by_path (cxt : CLintersContext.context) =
let source_file = cxt.translation_unit_context.source_file in
let regex_version_opt =
List.find Config.iphoneos_target_sdk_version_path_regex
~f:(fun (version_path_regex : Config.iphoneos_target_sdk_version_path_regex) ->
ALVar.str_match_forward (SourceFile.to_rel_path source_file) version_path_regex.path )
in
match regex_version_opt with
| Some version_by_regex ->
Some version_by_regex.version
| None (* no version by path specified, use default version *) ->
Config.iphoneos_target_sdk_version
let iphoneos_target_sdk_version_greater_or_equal (cxt : CLintersContext.context) version =
match iphoneos_target_sdk_version_by_path cxt with
| Some target_version ->
Utils.compare_versions target_version version >= 0
| None ->
false
let decl_unavailable_in_supported_ios_sdk (cxt : CLintersContext.context) an =
let config_iphoneos_target_sdk_version = iphoneos_target_sdk_version_by_path cxt in
let available_attr_ios_sdk_current_method =
match cxt.current_method with
| Some decl ->
get_available_attr_ios_sdk (Decl decl)
| None ->
None
in
let ios_version_guard =
match cxt.if_context with Some if_context -> if_context.ios_version_guard | None -> []
in
let allowed_os_versions =
Option.to_list config_iphoneos_target_sdk_version
@ ios_version_guard
@ Option.to_list available_attr_ios_sdk_current_method
in
let max_allowed_version = List.max_elt allowed_os_versions ~compare:Utils.compare_versions in
let available_attr_ios_sdk = get_available_attr_ios_sdk an in
match (available_attr_ios_sdk, max_allowed_version) with
| Some available_attr_ios_sdk, Some max_allowed_version ->
Utils.compare_versions available_attr_ios_sdk max_allowed_version > 0
| _ ->
false
let class_unavailable_in_supported_ios_sdk (cxt : CLintersContext.context) an =
match receiver_method_call an with
| Some decl ->
decl_unavailable_in_supported_ios_sdk cxt (Ctl_parser_types.Decl decl)
| None ->
false
(* Check whether a type_ptr and a string denote the same type *)
let type_ptr_equal_type type_ptr type_str =
let parse_type_string str =
L.(debug Linters Medium) "Starting parsing type string '%s'@\n" str ;
let lexbuf = Lexing.from_string str in
try Types_parser.abs_ctype token lexbuf with
| CTLExceptions.ALParserInvariantViolationException s ->
raise
CTLExceptions.(
ALFileException (create_exc_info ("Syntax Error when defining type " ^ s) lexbuf))
| SyntaxError _ | Types_parser.Error ->
raise CTLExceptions.(ALFileException (create_exc_info "SYNTAX ERROR" lexbuf))
in
let abs_ctype =
match String.Map.find !parsed_type_map type_str with
| Some abs_ctype' ->
abs_ctype'
| None ->
let abs_ctype' = parse_type_string type_str in
parsed_type_map := String.Map.set !parsed_type_map ~key:type_str ~data:abs_ctype' ;
abs_ctype'
in
match CAst_utils.get_type type_ptr with
| Some c_type' ->
Ctl_parser_types.c_type_equal c_type' abs_ctype
| _ ->
L.(debug Linters Medium) "Couldn't find type....@\n" ;
false
let get_ast_node_type_ptr an =
match an with
| Ctl_parser_types.Stmt stmt -> (
match Clang_ast_proj.get_expr_tuple stmt with
| Some (_, _, expr_info) ->
Some expr_info.ei_qual_type.qt_type_ptr
| _ ->
None )
| Ctl_parser_types.Decl decl ->
CAst_utils.type_of_decl decl
let has_type an typ_ =
match (get_ast_node_type_ptr an, typ_) with
| Some pt, ALVar.Const typ ->
type_ptr_equal_type pt typ
| _ ->
false
let has_type_const_ptr_to_objc_class node =
let open Clang_ast_t in
match get_ast_node_type_ptr node with
| Some type_ptr -> (
match CAst_utils.get_desugared_type type_ptr with
| Some (ObjCObjectPointerType (_, qt)) ->
qt.qt_is_const
| _ ->
false )
| None ->
false
Return the lifetime of the pointer of an expression if it is of type AttributedType
(* This is useful to check the lifetime of ivars *)
(* @returns objc_lifetime_attr *)
let get_ivar_lifetime an =
match get_ast_node_type_ptr an with
| Some pt -> (
match CAst_utils.get_type pt with
| Some c_type -> (
L.(debug Linters Medium) "@\nChecking type: `%s`\n" (Clang_ast_j.string_of_c_type c_type) ;
let open Clang_ast_t in
match c_type with
| AttributedType (_, attr_info) ->
Some attr_info.Clang_ast_t.ati_lifetime
| ObjCObjectPointerType _ ->
Some `OCL_Strong
| _ ->
L.(debug Linters Medium) "Pointer is not of type AttributedType...@\n" ;
None )
| _ ->
L.(debug Linters Medium) "Couldn't find type....\n" ;
None )
| _ ->
L.(debug Linters Medium) "Couldn't find pointer...@\n" ;
None
let is_strong_ivar an =
match get_ivar_lifetime an with
| Some lifetime -> (
match lifetime with `OCL_Strong | `OCL_Autoreleasing | `OCL_None -> true | _ -> false )
| _ ->
false
let is_decl node =
match node with Ctl_parser_types.Decl _ -> true | Ctl_parser_types.Stmt _ -> false
let method_return_type an typ_ =
L.(debug Linters Verbose) "@\n Executing method_return_type..." ;
match (an, typ_) with
| Ctl_parser_types.Decl (Clang_ast_t.ObjCMethodDecl (_, _, mdi)), ALVar.Const typ ->
L.(debug Linters Verbose) "@\n with parameter `%s`...." typ ;
let qual_type = mdi.Clang_ast_t.omdi_result_type in
type_ptr_equal_type qual_type.Clang_ast_t.qt_type_ptr typ
| _ ->
false
let rec check_protocol_hiearachy decls_ptr prot_name_ =
let open Clang_ast_t in
let is_this_protocol di_opt =
match di_opt with Some di -> ALVar.compare_str_with_alexp di.ni_name prot_name_ | _ -> false
in
match decls_ptr with
| [] ->
false
| pt :: decls' ->
let di, protocols =
match CAst_utils.get_decl pt with
| Some (ObjCProtocolDecl (_, di, _, _, opcdi)) ->
(Some di, opcdi.opcdi_protocols)
| _ ->
(None, [])
in
if is_this_protocol di || List.exists ~f:(fun dr -> is_this_protocol dr.dr_name) protocols
then true
else
let super_prot = List.map ~f:(fun dr -> dr.dr_decl_pointer) protocols in
check_protocol_hiearachy (super_prot @ decls') prot_name_
let has_type_subprotocol_of an prot_name_ =
let open Clang_ast_t in
let rec check_subprotocol t =
match t with
| Some (ObjCObjectPointerType (_, qt)) ->
check_subprotocol (CAst_utils.get_type qt.qt_type_ptr)
| Some (ObjCObjectType (_, ooti)) ->
if List.length ooti.ooti_protocol_decls_ptr > 0 then
check_protocol_hiearachy ooti.ooti_protocol_decls_ptr prot_name_
else
List.exists
~f:(fun qt -> check_subprotocol (CAst_utils.get_type qt.qt_type_ptr))
ooti.ooti_type_args
| Some (ObjCInterfaceType (_, pt)) ->
check_protocol_hiearachy [pt] prot_name_
| _ ->
false
in
match get_ast_node_type_ptr an with
| Some tp ->
check_subprotocol (CAst_utils.get_type tp)
| _ ->
false
let within_responds_to_selector_block (cxt : CLintersContext.context) an =
let open Clang_ast_t in
match an with
| Ctl_parser_types.Decl (ObjCMethodDecl (_, named_decl_info, _)) -> (
match cxt.if_context with
| Some if_context ->
let in_selector_block = if_context.within_responds_to_selector_block in
List.mem ~equal:String.equal in_selector_block named_decl_info.ni_name
| None ->
false )
| _ ->
false
let objc_method_call_within_responds_to_selector_block (cxt : CLintersContext.context) an =
let open Clang_ast_t in
match an with
| Ctl_parser_types.Stmt (ObjCMessageExpr (_, _, _, mdi)) -> (
match cxt.if_context with
| Some if_context ->
let in_selector_block = if_context.within_responds_to_selector_block in
List.mem ~equal:String.equal in_selector_block mdi.omei_selector
| None ->
false )
| _ ->
false
let within_available_class_block (cxt : CLintersContext.context) an =
match (receiver_method_call an, cxt.if_context) with
| Some receiver, Some if_context -> (
let in_available_class_block = if_context.within_available_class_block in
match declaration_name receiver with
| Some receiver_name ->
List.mem ~equal:String.equal in_available_class_block receiver_name
| None ->
false )
| _ ->
false
let using_namespace an namespace =
let open Clang_ast_t in
match an with
| Ctl_parser_types.Decl (UsingDirectiveDecl (_, _, uddi)) -> (
match uddi.uddi_nominated_namespace with
| Some dr -> (
match (dr.dr_kind, dr.dr_name) with
| `Namespace, Some ni ->
ALVar.compare_str_with_alexp ni.ni_name namespace
| _ ->
false )
| None ->
false )
| _ ->
false
let rec get_decl_attributes an =
let open Clang_ast_t in
let open Ctl_parser_types in
match an with
| Stmt (CallExpr (_, func :: _, _)) ->
get_decl_attributes (Stmt func)
| Stmt (ImplicitCastExpr (_, [stmt], _, _)) ->
get_decl_attributes (Stmt stmt)
| Stmt (DeclRefExpr (_, _, _, drti)) -> (
match CAst_utils.get_decl_opt_with_decl_ref_opt drti.drti_decl_ref with
| Some decl ->
get_decl_attributes (Decl decl)
| None ->
[] )
| Decl decl ->
let decl_info = Clang_ast_proj.get_decl_tuple decl in
decl_info.di_attributes
| _ ->
[]
let rec get_decl_attributes_for_callexpr_param an =
let open Clang_ast_t in
let open Ctl_parser_types in
let get_attr_param p = match p with ParmVarDecl (di, _, _, _) -> di.di_attributes | _ -> [] in
match an with
| Stmt (CallExpr (_, func :: _, _)) ->
get_decl_attributes_for_callexpr_param (Stmt func)
| Stmt (ImplicitCastExpr (_, [stmt], _, _)) ->
get_decl_attributes_for_callexpr_param (Stmt stmt)
| Stmt (DeclRefExpr (si, _, _, drti)) -> (
L.debug Linters Verbose "#####POINTER LOOP UP: '%i'@\n" si.si_pointer ;
match CAst_utils.get_decl_opt_with_decl_ref_opt drti.drti_decl_ref with
| Some (FunctionDecl (_, _, _, fdi)) ->
List.fold fdi.fdi_parameters ~f:(fun acc p -> List.append (get_attr_param p) acc) ~init:[]
| Some (ParmVarDecl _ as d) ->
get_attr_param d
| _ ->
[] )
| _ ->
[]
let visibility_matches vis_str (visibility : Clang_ast_t.visibility_attr) =
match (visibility, vis_str) with
| DefaultVisibility, "Default" ->
true
| HiddenVisibility, "Hidden" ->
true
| ProtectedVisibility, "Protected" ->
true
| _ ->
false
let has_visibility_attribute an visibility =
let has_visibility_attr attrs param =
List.exists attrs ~f:(function
| `VisibilityAttr (_attr_info, visibility) ->
visibility_matches param visibility
| _ ->
false )
in
let attributes = get_decl_attributes an in
match visibility with ALVar.Const vis -> has_visibility_attr attributes vis | _ -> false
let has_no_escape_attribute an =
let attributes = get_decl_attributes_for_callexpr_param an in
List.exists ~f:(fun attr -> match attr with `NoEscapeAttr _ -> true | _ -> false) attributes
let has_used_attribute an =
let attributes = get_decl_attributes an in
List.exists ~f:(fun attr -> match attr with `UsedAttr _ -> true | _ -> false) attributes
true is a declaration has an Unavailable attribute
let has_unavailable_attribute an =
let is_unavailable_attr attr = match attr with `UnavailableAttr _ -> true | _ -> false in
match an with
| Ctl_parser_types.Decl d ->
let attrs = (Clang_ast_proj.get_decl_tuple d).di_attributes in
List.exists attrs ~f:is_unavailable_attr
| _ ->
false
let has_value an al_exp =
let open Clang_ast_t in
let open Ctl_parser_types in
match an with
| Stmt (IntegerLiteral (_, _, _, integer_literal_info)) ->
let value = integer_literal_info.Clang_ast_t.ili_value in
ALVar.compare_str_with_alexp value al_exp
| Stmt (StringLiteral (_, _, _, l)) ->
ALVar.compare_str_with_alexp (String.concat ~sep:"" l) al_exp
| _ ->
false
(* check if method is called on superclass *)
let is_method_called_by_superclass an =
let open Clang_ast_t in
let open Ctl_parser_types in
match an with
| Stmt (ObjCMessageExpr (_, _, _, obj_c_message_expr_info)) -> (
match obj_c_message_expr_info.omei_receiver_kind with `SuperInstance -> true | _ -> false )
| _ ->
false
let is_cxx_copy_constructor an =
let open Clang_ast_t in
match an with
| Ctl_parser_types.Stmt (CXXConstructExpr (_, _, _, xcei)) ->
xcei.xcei_is_copy_constructor
| _ ->
false
let has_cxx_fully_qualified_name an qual_name_re =
match Ctl_parser_types.ast_node_cxx_fully_qualified_name an with
| "" ->
false
| fully_qualified_name ->
ALVar.compare_str_with_alexp fully_qualified_name qual_name_re
let has_cxx_fully_qualified_name_in_custom_symbols an list_name =
match Ctl_parser_types.ast_node_cxx_fully_qualified_name an with
| "" ->
false
| fully_qualified_name ->
Config.is_in_custom_symbols list_name fully_qualified_name
let is_cxx_method_overriding an qual_name_re =
let rec overrides_named (decl_refs : Clang_ast_t.decl_ref list) (qnre : ALVar.alexp) =
List.exists
~f:(fun (decl_ref : Clang_ast_t.decl_ref) ->
match CAst_utils.get_decl decl_ref.dr_decl_pointer with
| None ->
false
| Some decl -> (
match decl with
| Clang_ast_t.CXXMethodDecl (_, ndi, _, _, mdi) ->
ALVar.compare_str_with_alexp
(String.concat ~sep:"::" (List.rev ndi.ni_qual_name))
qnre
|| overrides_named mdi.xmdi_overriden_methods qnre
| _ ->
false ) )
decl_refs
in
match an with
| Ctl_parser_types.Decl (Clang_ast_t.CXXMethodDecl (_, _, _, _, mdi)) -> (
match qual_name_re with
| None ->
not (List.is_empty mdi.xmdi_overriden_methods)
| Some qnre ->
overrides_named mdi.xmdi_overriden_methods qnre )
| _ ->
false
let is_init_expr_cxx11_constant an =
let open Clang_ast_t in
match an with
| Ctl_parser_types.Decl (VarDecl (_, _, _, vdi)) ->
vdi.vdi_is_init_expr_cxx11_constant
| _ ->
false
let call_cxx_method an name =
let open Clang_ast_t in
match an with
| Ctl_parser_types.Stmt (CXXMemberCallExpr (_, member :: _, _)) -> (
match member with
| MemberExpr (_, _, _, memberExprInfo) ->
ALVar.compare_str_with_alexp memberExprInfo.mei_name.ni_name name
| _ ->
false )
| _ ->
false
let source_file_matches src_file path_re =
Option.value_map
~f:(fun sf ->
ALVar.compare_str_with_alexp (SourceFile.to_rel_path (SourceFile.create sf)) path_re )
~default:false src_file
let is_in_source_file an path_re = source_file_matches (Ctl_parser_types.get_source_file an) path_re
let is_referencing_decl_from_source_file an path_re =
source_file_matches (Ctl_parser_types.get_referenced_decl_source_file an) path_re
let captured_var_of_type typ captured_var =
match captured_var.Clang_ast_t.bcv_variable with
| Some dr ->
let _, _, qt = CAst_utils.get_info_from_decl_ref dr in
type_ptr_equal_type qt.Clang_ast_t.qt_type_ptr (ALVar.alexp_to_string typ)
| _ ->
false
let objc_block_is_capturing_var_of_type an typ =
match an with
| Ctl_parser_types.Decl (Clang_ast_t.BlockDecl (_, bdi)) ->
List.exists ~f:(captured_var_of_type typ) bdi.bdi_captured_variables
| _ ->
false
| null |
https://raw.githubusercontent.com/project-oak/hafnium-verification/6071eff162148e4d25a0fedaea003addac242ace/experiments/ownership-inference/infer/infer/src/al/cPredicates.ml
|
ocaml
|
(name, [param1,...,paramK])
an is a declaration whose name contains a regexp defined by re
is an objc interface with name expected_name
is an objc implementation with name expected_name
is an objc category interface with class name expected_name
is an objc category implementation with class name expected_name
is an objc category interface with superclass name expected_name
is an objc category implementation with superclass name expected_name
is an objc category interface with name expected_name
is an objc category implementation with name expected_name
an |= call_method(m) where the name must be exactly m
The ObjC class type, 'Class', is treated as an instance receiver kind.
We need to check if the receiver is the class type to catch cases like
[[self class] myClassMethod]
an is a node calling method whose name contains mname of a class.
The ObjC class type, 'Class', is treated as an instance receiver kind.
We need to verify the receiver is not the class type to avoid cases like
[[self class] myClassMethod]
checks if ivar is defined among a set of fields and if it is atomic
node an is of class classname
an is an expression @selector with whose name in the language of re
no version by path specified, use default version
Check whether a type_ptr and a string denote the same type
This is useful to check the lifetime of ivars
@returns objc_lifetime_attr
check if method is called on superclass
|
* Copyright ( c ) Facebook , Inc. and its affiliates .
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree .
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
open! IStd
open Types_lexer
module L = Logging
let parsed_type_map : Ctl_parser_types.abs_ctype String.Map.t ref = ref String.Map.empty
let rec objc_class_of_pointer_type type_ptr =
match CAst_utils.get_type type_ptr with
| Some (ObjCInterfaceType (_, decl_ptr)) ->
CAst_utils.get_decl decl_ptr
| Some (ObjCObjectPointerType (_, inner_qual_type)) ->
objc_class_of_pointer_type inner_qual_type.qt_type_ptr
| Some (AttributedType (type_info, _)) -> (
match type_info.ti_desugared_type with
| Some type_ptr ->
objc_class_of_pointer_type type_ptr
| None ->
None )
| _ ->
None
let receiver_class_method_call an =
match an with
| Ctl_parser_types.Stmt (ObjCMessageExpr (_, _, _, obj_c_message_expr_info)) -> (
match obj_c_message_expr_info.omei_receiver_kind with
| `Class qt ->
CAst_utils.get_decl_from_typ_ptr qt.qt_type_ptr
| _ ->
None )
| _ ->
None
let receiver_instance_method_call an =
match an with
| Ctl_parser_types.Stmt (ObjCMessageExpr (_, args, _, obj_c_message_expr_info)) -> (
match obj_c_message_expr_info.omei_receiver_kind with
| `Instance -> (
match args with
| receiver :: _ -> (
match Clang_ast_proj.get_expr_tuple receiver with
| Some (_, _, expr_info) ->
objc_class_of_pointer_type expr_info.ei_qual_type.qt_type_ptr
| None ->
None )
| [] ->
None )
| _ ->
None )
| _ ->
None
let receiver_method_call an =
match receiver_class_method_call an with
| Some decl ->
Some decl
| None ->
receiver_instance_method_call an
let declaration_name decl =
match Clang_ast_proj.get_named_decl_tuple decl with
| Some (_, ndi) ->
Some ndi.ni_name
| None ->
None
let get_available_attr_ios_sdk an =
match an with
| Ctl_parser_types.Decl decl ->
let decl_info = Clang_ast_proj.get_decl_tuple decl in
List.find_map decl_info.di_attributes ~f:(function
| `AvailabilityAttr (_attr_info, {Clang_ast_t.aai_platform= Some "ios"; aai_introduced}) ->
let get_opt_number = Option.value ~default:0 in
Some
(Printf.sprintf "%d.%d" aai_introduced.vt_major
(get_opt_number aai_introduced.vt_minor))
| _ ->
None )
| _ ->
None
let get_ivar_attributes ivar_decl =
let open Clang_ast_t in
match ivar_decl with
| ObjCIvarDecl (ivar_decl_info, _, _, _, _) -> (
match CAst_utils.get_property_of_ivar ivar_decl_info.Clang_ast_t.di_pointer with
| Some (ObjCPropertyDecl (_, _, obj_c_property_decl_info)) ->
obj_c_property_decl_info.Clang_ast_t.opdi_property_attributes
| _ ->
[] )
| _ ->
[]
list of cxx references captured by
let captured_variables_cxx_ref an =
let open Clang_ast_t in
let capture_var_is_cxx_ref reference_captured_vars captured_var =
let decl_ref_opt = captured_var.Clang_ast_t.bcv_variable in
match CAst_utils.get_decl_opt_with_decl_ref_opt decl_ref_opt with
| Some (VarDecl (_, named_decl_info, qual_type, _))
| Some (ParmVarDecl (_, named_decl_info, qual_type, _))
| Some (ImplicitParamDecl (_, named_decl_info, qual_type, _)) -> (
match CAst_utils.get_desugared_type qual_type.Clang_ast_t.qt_type_ptr with
| Some (RValueReferenceType _) | Some (LValueReferenceType _) ->
named_decl_info :: reference_captured_vars
| _ ->
reference_captured_vars )
| _ ->
reference_captured_vars
in
match an with
| Ctl_parser_types.Decl (BlockDecl (_, bdi)) ->
List.fold ~f:capture_var_is_cxx_ref ~init:[] bdi.bdi_captured_variables
| _ ->
[]
let objc_block_is_capturing_values an =
match an with
| Ctl_parser_types.Decl (Clang_ast_t.BlockDecl (_, bdi)) ->
not (List.is_empty bdi.bdi_captured_variables)
| _ ->
false
let pp_predicate fmt (name_, arglist_) =
let name = ALVar.formula_id_to_string name_ in
let arglist = List.map ~f:ALVar.alexp_to_string arglist_ in
Format.fprintf fmt "%s(%a)" name (Pp.comma_seq Format.pp_print_string) arglist
let declaration_has_name an name =
match an with
| Ctl_parser_types.Decl d -> (
match declaration_name d with
| Some decl_name ->
ALVar.compare_str_with_alexp decl_name name
| _ ->
false )
| _ ->
false
let rec is_subclass_of decl name =
match CAst_utils.get_superclass_curr_class_objc_from_decl decl with
| Some super_ref -> (
let ndi = match super_ref.Clang_ast_t.dr_name with Some ni -> ni | _ -> assert false in
if ALVar.compare_str_with_alexp ndi.ni_name name then true
else
match CAst_utils.get_decl_opt_with_decl_ref_opt (Some super_ref) with
| Some decl ->
is_subclass_of decl name
| None ->
false )
| None ->
false
let is_objc_interface_named an expected_name =
match an with
| Ctl_parser_types.Decl (Clang_ast_t.ObjCInterfaceDecl _) ->
declaration_has_name an expected_name
| _ ->
false
let is_objc_implementation_named an expected_name =
match an with
| Ctl_parser_types.Decl (Clang_ast_t.ObjCImplementationDecl _) ->
declaration_has_name an expected_name
| _ ->
false
let is_objc_class_named an re = is_objc_interface_named an re || is_objc_implementation_named an re
let is_objc_category_interface_on_class_named an expected_name =
match an with
| Ctl_parser_types.Decl (Clang_ast_t.ObjCCategoryDecl (_, _, _, _, ocdi)) -> (
match CAst_utils.get_decl_opt_with_decl_ref_opt ocdi.odi_class_interface with
| Some decl_ref ->
is_objc_interface_named (Decl decl_ref) expected_name
| _ ->
false )
| _ ->
false
let is_objc_category_implementation_on_class_named an expected_name =
match an with
| Ctl_parser_types.Decl (Clang_ast_t.ObjCCategoryImplDecl (_, _, _, _, ocidi)) -> (
match CAst_utils.get_decl_opt_with_decl_ref_opt ocidi.ocidi_class_interface with
| Some decl_ref ->
is_objc_interface_named (Decl decl_ref) expected_name
| _ ->
false )
| _ ->
false
let is_objc_category_on_class_named an re =
is_objc_category_interface_on_class_named an re
|| is_objc_category_implementation_on_class_named an re
let is_objc_category_interface_on_subclass_of an expected_name =
match an with
| Ctl_parser_types.Decl (Clang_ast_t.ObjCCategoryDecl (_, _, _, _, ocdi)) -> (
match CAst_utils.get_decl_opt_with_decl_ref_opt ocdi.odi_class_interface with
| Some decl_ref ->
is_subclass_of decl_ref expected_name
| _ ->
false )
| _ ->
false
let is_objc_category_implementation_on_subclass_of an expected_name =
match an with
| Ctl_parser_types.Decl (Clang_ast_t.ObjCCategoryImplDecl (_, _, _, _, ocidi)) -> (
match CAst_utils.get_decl_opt_with_decl_ref_opt ocidi.ocidi_class_interface with
| Some decl_ref ->
is_subclass_of decl_ref expected_name
| _ ->
false )
| _ ->
false
let is_objc_category_on_subclass_of an expected_name =
is_objc_category_interface_on_subclass_of an expected_name
|| is_objc_category_implementation_on_subclass_of an expected_name
let is_objc_category_interface_named an expected_name =
match an with
| Ctl_parser_types.Decl (Clang_ast_t.ObjCCategoryDecl _) ->
declaration_has_name an expected_name
| _ ->
false
let is_objc_category_implementation_named an expected_name =
match an with
| Ctl_parser_types.Decl (Clang_ast_t.ObjCCategoryImplDecl _) ->
declaration_has_name an expected_name
| _ ->
false
let is_objc_category_named an re =
is_objc_category_interface_named an re || is_objc_category_implementation_named an re
let is_objc_protocol_named an re =
match an with
| Ctl_parser_types.Decl (Clang_ast_t.ObjCProtocolDecl _) ->
declaration_has_name an re
| _ ->
false
let is_objc_class_method_named an name =
match an with
| Ctl_parser_types.Decl (Clang_ast_t.ObjCMethodDecl (_, _, omdi)) ->
declaration_has_name an name && not omdi.omdi_is_instance_method
| _ ->
false
let is_objc_instance_method_named an name =
match an with
| Ctl_parser_types.Decl (Clang_ast_t.ObjCMethodDecl (_, _, omdi)) ->
declaration_has_name an name && omdi.omdi_is_instance_method
| _ ->
false
let is_objc_method_named an name =
match an with
| Ctl_parser_types.Decl (Clang_ast_t.ObjCMethodDecl _) ->
declaration_has_name an name
| _ ->
false
let is_objc_method_overriding an =
match an with
| Ctl_parser_types.Decl (Clang_ast_t.ObjCMethodDecl (_, _, mdi)) ->
mdi.omdi_is_overriding
| _ ->
false
let decl_list_has_objc_method decl_list method_name is_instance_method =
List.exists
~f:(fun decl ->
match decl with
| Clang_ast_t.ObjCMethodDecl (_, ni, omdi) ->
Bool.equal omdi.omdi_is_instance_method is_instance_method
&& String.equal ni.ni_name method_name
| _ ->
false )
decl_list
let current_objc_container context =
let open CLintersContext in
let current_objc_class = context.current_objc_class in
let current_objc_category = context.current_objc_category in
let current_objc_protocol = context.current_objc_protocol in
if not (Option.is_none current_objc_class) then current_objc_class
else if not (Option.is_none current_objc_category) then current_objc_category
else if not (Option.is_none current_objc_protocol) then current_objc_protocol
else None
let is_objc_method_exposed context an =
let open Clang_ast_t in
if is_objc_method_overriding an then true
else
match an with
| Ctl_parser_types.Decl (ObjCMethodDecl (_, ndi, mdi)) -> (
let method_name = ndi.ni_name in
let is_instance_method = mdi.omdi_is_instance_method in
match current_objc_container context with
| Some (ObjCImplementationDecl (_, _, _, _, oidi)) -> (
match CAst_utils.get_decl_opt_with_decl_ref_opt oidi.oidi_class_interface with
| Some (ObjCInterfaceDecl (_, _, decl_list, _, otdi)) ->
decl_list_has_objc_method decl_list method_name is_instance_method
|| List.exists
~f:(fun decl_ref ->
match CAst_utils.get_decl decl_ref.dr_decl_pointer with
| Some (ObjCCategoryDecl (_, ni, decl_list, _, _)) ->
String.equal ni.ni_name ""
&& decl_list_has_objc_method decl_list method_name is_instance_method
| _ ->
false )
otdi.otdi_known_categories
| _ ->
false )
| Some (ObjCCategoryImplDecl (_, _, _, _, ocidi)) -> (
match CAst_utils.get_decl_opt_with_decl_ref_opt ocidi.ocidi_category_decl with
| Some (ObjCCategoryDecl (_, _, decl_list, _, _)) ->
decl_list_has_objc_method decl_list method_name is_instance_method
| _ ->
false )
| _ ->
false )
| _ ->
false
let get_selector an =
match an with
| Ctl_parser_types.Stmt (Clang_ast_t.ObjCMessageExpr (_, _, _, omei)) ->
Some omei.omei_selector
| _ ->
None
let receiver_objc_type_name an =
match an with
| Ctl_parser_types.Stmt (ObjCMessageExpr (_, receiver :: _, _, {omei_receiver_kind= `Instance}))
->
Clang_ast_proj.get_expr_tuple receiver
|> Option.bind ~f:(fun (_, _, expr_info) ->
CAst_utils.name_opt_of_typedef_qual_type expr_info.Clang_ast_t.ei_qual_type )
|> Option.map ~f:QualifiedCppName.to_qual_string
| _ ->
None
let is_receiver_objc_class_type an =
match receiver_objc_type_name an with
| Some type_name ->
String.equal type_name "Class"
| None ->
false
let is_receiver_objc_id_type an =
match receiver_objc_type_name an with
| Some type_name ->
String.equal type_name "id"
| None ->
false
let objc_message_receiver context an =
match an with
| Ctl_parser_types.Stmt (ObjCMessageExpr (_, args, _, omei)) -> (
match omei.omei_receiver_kind with
| `SuperClass | `SuperInstance -> (
match current_objc_container context with
| Some container ->
let decl_ref_opt = CAst_utils.get_superclass_curr_class_objc_from_decl container in
CAst_utils.get_decl_opt_with_decl_ref_opt decl_ref_opt
| _ ->
None )
| `Class qt ->
CAst_utils.get_decl_from_typ_ptr qt.qt_type_ptr
| `Instance -> (
match args with
| receiver :: _ -> (
match receiver with
| ObjCMessageExpr (_, _, _, sub_omei) -> (
match CAst_utils.get_decl_opt sub_omei.omei_decl_pointer with
| Some (ObjCMethodDecl (_, _, omdi)) ->
CAst_utils.qual_type_to_objc_interface omdi.omdi_result_type
| _ ->
None )
| PseudoObjectExpr (_, _, ei) | ImplicitCastExpr (_, _, ei, _) | ParenExpr (_, _, ei) ->
CAst_utils.qual_type_to_objc_interface ei.ei_qual_type
| _ ->
None )
| [] ->
None ) )
| _ ->
None
let call_method an m =
match get_selector an with Some selector -> ALVar.compare_str_with_alexp selector m | _ -> false
let call_class_method an mname =
match an with
| Ctl_parser_types.Stmt (Clang_ast_t.ObjCMessageExpr (_, _, _, omei)) -> (
match omei.omei_receiver_kind with
| `SuperClass | `Class _ ->
ALVar.compare_str_with_alexp omei.omei_selector mname
| `Instance ->
ALVar.compare_str_with_alexp omei.omei_selector mname && is_receiver_objc_class_type an
| _ ->
false )
| _ ->
false
let call_instance_method an mname =
match an with
| Ctl_parser_types.Stmt (Clang_ast_t.ObjCMessageExpr (_, _, _, omei)) -> (
match omei.omei_receiver_kind with
| `SuperInstance ->
ALVar.compare_str_with_alexp omei.omei_selector mname
| `Instance ->
ALVar.compare_str_with_alexp omei.omei_selector mname
&& not (is_receiver_objc_class_type an)
| _ ->
false )
| _ ->
false
let adhere_to_protocol an =
match an with
| Ctl_parser_types.Decl (Clang_ast_t.ObjCInterfaceDecl (_, _, _, _, idi)) ->
not (List.is_empty idi.otdi_protocols)
| _ ->
false
let is_objc_extension lcxt =
CGeneral_utils.is_objc_extension lcxt.CLintersContext.translation_unit_context
let is_global_var an =
match an with Ctl_parser_types.Decl d -> CAst_utils.is_syntactically_global_var d | _ -> false
let is_static_local_var an =
match an with Ctl_parser_types.Decl d -> CAst_utils.is_static_local_var d | _ -> false
let is_static_var an =
match an with Ctl_parser_types.Decl (VarDecl (_, _, _, vdi)) -> vdi.vdi_is_static | _ -> false
let is_extern_var an =
match an with Ctl_parser_types.Decl (VarDecl (_, _, _, vdi)) -> vdi.vdi_is_extern | _ -> false
let is_const_expr_var an =
match an with Ctl_parser_types.Decl d -> CAst_utils.is_const_expr_var d | _ -> false
let is_init_integral_constant_expr an =
match an with
| Ctl_parser_types.Decl d -> (
match d with Clang_ast_t.VarDecl (_, _, _, vdi) -> vdi.vdi_is_init_ice | _ -> false )
| _ ->
false
let is_qual_type_const an =
match an with
| Ctl_parser_types.Stmt s -> (
match Clang_ast_proj.get_expr_tuple s with
| Some (_, _, ei) ->
ei.Clang_ast_t.ei_qual_type.qt_is_const
| _ ->
false )
| Ctl_parser_types.Decl (Clang_ast_t.VarDecl (_, _, qt, _)) ->
qt.qt_is_const
| _ ->
false
let objc_class_has_only_one_constructor_method_named an re =
let open Clang_ast_t in
let is_class_method d =
match d with
| Clang_ast_t.ObjCMethodDecl (_, _, omdi) ->
not omdi.omdi_is_instance_method
| _ ->
false
in
match an with
| Ctl_parser_types.Decl (ObjCImplementationDecl (_, _, decls, _, _)) -> (
match List.filter decls ~f:(fun d -> is_class_method d) with
| [n] ->
is_objc_class_method_named (Ctl_parser_types.Decl n) re
| _ ->
false )
| _ ->
false
let has_init_list_const_expr an =
let rec fold lexp = List.fold ~f:(fun acc e -> is_const_expr' e && acc) ~init:true lexp
and is_const_expr' exp =
let open Clang_ast_t in
let res =
match exp with
| IntegerLiteral _ | StringLiteral _ ->
true
| DeclRefExpr (_, _, _, drei) -> (
match drei.drti_decl_ref with
| Some dr -> (
match dr.dr_kind with `EnumConstant -> true | _ -> false )
| _ ->
false )
| CallExpr (_, _ :: params, _) ->
fold params
| _ -> (
match Clang_ast_proj.get_expr_tuple exp with
| Some (_, sub_exps, _) ->
fold sub_exps
| _ ->
false )
in
L.(debug Analysis Verbose)
"@\n\n[has_init_list_const_expr] EVALUATE EXP '%a' result = '%b'@\n"
(Pp.of_string ~f:Clang_ast_proj.get_stmt_kind_string)
exp res ;
res
in
match an with
| Ctl_parser_types.Stmt (Clang_ast_t.InitListExpr (_, sub_exps, _)) ->
fold sub_exps
| _ ->
false
let decl_ref_name qualified ?kind name st =
match st with
| Clang_ast_t.DeclRefExpr (_, _, _, drti) -> (
match drti.drti_decl_ref with
| Some dr -> (
let ndi, _, _ = CAst_utils.get_info_from_decl_ref dr in
let qname =
if qualified then String.concat ~sep:"::" (List.rev ndi.ni_qual_name) else ndi.ni_name
in
let has_right_name = ALVar.compare_str_with_alexp qname name in
match kind with
| Some decl_kind ->
has_right_name && PolyVariantEqual.( = ) dr.Clang_ast_t.dr_kind decl_kind
| None ->
has_right_name )
| _ ->
false )
| _ ->
false
let declaration_ref_name ?kind an name =
match an with Ctl_parser_types.Stmt st -> decl_ref_name false ?kind name st | _ -> false
let call_function an name =
match an with
| Ctl_parser_types.Stmt st ->
CAst_utils.exists_eventually_st (decl_ref_name false ~kind:`Function) name st
| _ ->
false
let call_qualified_function an name =
match an with
| Ctl_parser_types.Stmt st ->
CAst_utils.exists_eventually_st (decl_ref_name true ~kind:`Function) name st
| _ ->
false
let is_enum_constant an name =
match an with
| Ctl_parser_types.Stmt st ->
decl_ref_name false ~kind:`EnumConstant name st
| _ ->
false
let is_enum_constant_of_enum an name =
match an with
| Ctl_parser_types.Stmt (Clang_ast_t.DeclRefExpr (_, _, _, drti)) -> (
match drti.drti_decl_ref with
| Some dr -> (
let ndi, _, _ = CAst_utils.get_info_from_decl_ref dr in
let qual_name = CAst_utils.get_qualified_name ndi in
match QualifiedCppName.extract_last qual_name with
| Some (_, stripped_qual_name) -> (
match QualifiedCppName.extract_last stripped_qual_name with
| Some (enum_name, _) ->
PolyVariantEqual.( = ) dr.Clang_ast_t.dr_kind `EnumConstant
&& ALVar.compare_str_with_alexp enum_name name
| _ ->
false )
| _ ->
false )
| _ ->
false )
| _ ->
false
let is_strong_property an =
match an with
| Ctl_parser_types.Decl (Clang_ast_t.ObjCPropertyDecl (_, _, pdi)) ->
ObjcProperty_decl.is_strong_property pdi
| _ ->
false
let is_weak_property an =
match an with
| Ctl_parser_types.Decl (Clang_ast_t.ObjCPropertyDecl (_, _, pdi)) ->
ObjcProperty_decl.is_weak_property pdi
| _ ->
false
let is_assign_property an =
match an with
| Ctl_parser_types.Decl (Clang_ast_t.ObjCPropertyDecl (_, _, pdi)) ->
ObjcProperty_decl.is_assign_property pdi
| _ ->
false
let is_property_pointer_type an =
let open Clang_ast_t in
match an with
| Ctl_parser_types.Decl (ObjCPropertyDecl (_, _, pdi)) -> (
match CAst_utils.get_desugared_type pdi.opdi_qual_type.Clang_ast_t.qt_type_ptr with
| Some (MemberPointerType _) | Some (ObjCObjectPointerType _) | Some (BlockPointerType _) ->
true
| Some (TypedefType (_, tti)) ->
let typedef_str =
CAst_utils.name_of_typedef_type_info tti |> QualifiedCppName.to_qual_string
in
String.equal typedef_str CFrontend_config.id_cl
| exception Caml.Not_found ->
false
| _ ->
false )
| _ ->
false
let context_in_synchronized_block context = context.CLintersContext.in_synchronized_block
let is_ivar_atomic an =
match an with
| Ctl_parser_types.Stmt (Clang_ast_t.ObjCIvarRefExpr (_, _, _, irei)) -> (
let dr_ref = irei.Clang_ast_t.ovrei_decl_ref in
let ivar_pointer = dr_ref.Clang_ast_t.dr_decl_pointer in
match CAst_utils.get_decl ivar_pointer with
| Some d ->
let attributes = get_ivar_attributes d in
List.exists ~f:(PolyVariantEqual.( = ) `Atomic) attributes
| _ ->
false )
| _ ->
false
let is_method_property_accessor_of_ivar an context =
let open Clang_ast_t in
match an with
| Ctl_parser_types.Stmt (ObjCIvarRefExpr (_, _, _, irei)) -> (
let dr_ref = irei.Clang_ast_t.ovrei_decl_ref in
let ivar_pointer = dr_ref.Clang_ast_t.dr_decl_pointer in
match context.CLintersContext.current_method with
| Some (ObjCMethodDecl (_, _, mdi)) ->
if mdi.omdi_is_property_accessor then
let property_opt = mdi.omdi_property_decl in
match CAst_utils.get_decl_opt_with_decl_ref_opt property_opt with
| Some (ObjCPropertyDecl (_, _, pdi)) -> (
match pdi.opdi_ivar_decl with
| Some decl_ref ->
Int.equal decl_ref.dr_decl_pointer ivar_pointer
| None ->
false )
| _ ->
false
else false
| _ ->
false )
| _ ->
false
let get_method_name_from_context context =
match context.CLintersContext.current_method with
| Some method_decl -> (
match Clang_ast_proj.get_named_decl_tuple method_decl with
| Some (_, mnd) ->
mnd.Clang_ast_t.ni_name
| _ ->
"" )
| _ ->
""
let is_objc_constructor context =
Procname.ObjC_Cpp.is_objc_constructor (get_method_name_from_context context)
let is_objc_dealloc context =
Procname.ObjC_Cpp.is_objc_dealloc (get_method_name_from_context context)
let is_in_method context name =
let current_method_name = get_method_name_from_context context in
ALVar.compare_str_with_alexp current_method_name name
let is_in_objc_class_method context name =
match context.CLintersContext.current_method with
| Some (ObjCMethodDecl (_, _, omdi) as objc_method) ->
declaration_has_name (Decl objc_method) name && not omdi.omdi_is_instance_method
| _ ->
false
let is_in_objc_instance_method context name =
match context.CLintersContext.current_method with
| Some (ObjCMethodDecl (_, _, omdi) as objc_method) ->
declaration_has_name (Decl objc_method) name && omdi.omdi_is_instance_method
| _ ->
false
let is_in_objc_method context name =
is_in_objc_class_method context name || is_in_objc_instance_method context name
let is_in_function context name =
match context.CLintersContext.current_method with
| Some (FunctionDecl _) ->
is_in_method context name
| _ ->
false
let is_in_cxx_method context name =
match context.CLintersContext.current_method with
| Some (CXXMethodDecl _) ->
is_in_method context name
| _ ->
false
let is_in_cxx_constructor context name =
match context.CLintersContext.current_method with
| Some (CXXConstructorDecl _) ->
is_in_method context name
| _ ->
false
let is_in_cxx_destructor context name =
match context.CLintersContext.current_method with
| Some (CXXDestructorDecl _) ->
is_in_method context name
| _ ->
false
let cxx_construct_expr_has_no_parameters an =
match an with
| Ctl_parser_types.Stmt (Clang_ast_t.CXXConstructExpr (_, [], _, _)) ->
true
| _ ->
false
let cxx_construct_expr_has_name an name =
match an with
| Ctl_parser_types.Stmt (Clang_ast_t.CXXConstructExpr (_, _, _, xcei)) -> (
match xcei.xcei_decl_ref.dr_name with
| Some ni ->
ALVar.compare_str_with_alexp ni.ni_name name
| _ ->
false )
| _ ->
false
let is_optional_objc_method an =
match an with
| Ctl_parser_types.Decl (Clang_ast_t.ObjCMethodDecl (_, _, omdi)) ->
omdi.omdi_is_optional
| _ ->
false
let is_call_to_optional_objc_method an =
let open Clang_ast_t in
match an with
| Ctl_parser_types.Stmt (ObjCMessageExpr (_, _, _, omei)) -> (
match CAst_utils.get_decl_opt omei.omei_decl_pointer with
| Some d ->
is_optional_objc_method (Ctl_parser_types.Decl d)
| _ ->
false )
| _ ->
false
let is_in_block context =
match context.CLintersContext.current_method with Some (BlockDecl _) -> true | _ -> false
let is_in_objc_subclass_of context name =
match context.CLintersContext.current_objc_class with
| Some cls ->
is_subclass_of cls name
| None ->
false
let is_in_objc_interface_named context name =
match context.CLintersContext.current_objc_class with
| Some cls ->
is_objc_interface_named (Decl cls) name
| None ->
false
let is_in_objc_implementation_named context name =
match context.CLintersContext.current_objc_class with
| Some cls ->
is_objc_implementation_named (Decl cls) name
| None ->
false
let is_in_objc_class_named context name =
match context.CLintersContext.current_objc_class with
| Some cls ->
is_objc_class_named (Decl cls) name
| None ->
false
let is_in_objc_category_interface_on_class_named context name =
match context.CLintersContext.current_objc_category with
| Some cat ->
is_objc_category_interface_on_class_named (Decl cat) name
| None ->
false
let is_in_objc_category_implementation_on_class_named context name =
match context.CLintersContext.current_objc_category with
| Some cat ->
is_objc_category_implementation_on_class_named (Decl cat) name
| None ->
false
let is_in_objc_category_on_class_named context name =
match context.CLintersContext.current_objc_category with
| Some cat ->
is_objc_category_on_class_named (Decl cat) name
| None ->
false
let is_in_objc_category_interface_on_subclass_of context name =
match context.CLintersContext.current_objc_category with
| Some cat ->
is_objc_category_interface_on_subclass_of (Decl cat) name
| None ->
false
let is_in_objc_category_implementation_on_subclass_of context name =
match context.CLintersContext.current_objc_category with
| Some cat ->
is_objc_category_implementation_on_subclass_of (Decl cat) name
| None ->
false
let is_in_objc_category_on_subclass_of context name =
match context.CLintersContext.current_objc_category with
| Some cat ->
is_objc_category_on_subclass_of (Decl cat) name
| None ->
false
let is_in_objc_category_interface_named context name =
match context.CLintersContext.current_objc_category with
| Some cat ->
is_objc_category_interface_named (Decl cat) name
| None ->
false
let is_in_objc_category_implementation_named context name =
match context.CLintersContext.current_objc_category with
| Some cat ->
is_objc_category_implementation_named (Decl cat) name
| None ->
false
let is_in_objc_category_named context name =
match context.CLintersContext.current_objc_category with
| Some cat ->
is_objc_category_named (Decl cat) name
| None ->
false
let is_in_objc_protocol_named context name =
match context.CLintersContext.current_objc_protocol with
| Some protocol ->
is_objc_protocol_named (Decl protocol) name
| None ->
false
let is_receiver_subclass_of context an cname =
match objc_message_receiver context an with
| Some receiver ->
is_subclass_of receiver cname
| _ ->
false
let is_receiver_class_named context an cname =
match objc_message_receiver context an with
| Some receiver ->
declaration_has_name (Decl receiver) cname
| _ ->
false
let is_receiver_super an =
match an with
| Ctl_parser_types.Stmt
(ObjCMessageExpr (_, _, _, {omei_receiver_kind= `SuperClass | `SuperInstance})) ->
true
| _ ->
false
let is_receiver_self an =
match an with
| Ctl_parser_types.Stmt (Clang_ast_t.ObjCMessageExpr (_, fst_param :: _, _, _)) ->
CAst_utils.exists_eventually_st
(decl_ref_name false ~kind:`ImplicitParam)
(ALVar.Const CFrontend_config.self) fst_param
| _ ->
false
let captures_cxx_references an = List.length (captured_variables_cxx_ref an) > 0
let is_binop_with_kind an alexp_kind =
let str_kind = ALVar.alexp_to_string alexp_kind in
if not (Clang_ast_proj.is_valid_binop_kind_name str_kind) then
L.(die ExternalError) "Binary operator kind '%s' is not valid" str_kind ;
match an with
| Ctl_parser_types.Stmt (Clang_ast_t.BinaryOperator (_, _, _, boi)) ->
ALVar.compare_str_with_alexp (Clang_ast_proj.string_of_binop_kind boi.boi_kind) alexp_kind
| _ ->
false
let is_unop_with_kind an alexp_kind =
let str_kind = ALVar.alexp_to_string alexp_kind in
if not (Clang_ast_proj.is_valid_unop_kind_name str_kind) then
L.(die ExternalError) "Unary operator kind '%s' is not valid" str_kind ;
match an with
| Ctl_parser_types.Stmt (Clang_ast_t.UnaryOperator (_, _, _, uoi)) ->
ALVar.compare_str_with_alexp (Clang_ast_proj.string_of_unop_kind uoi.uoi_kind) alexp_kind
| _ ->
false
let has_cast_kind an alexp_kind =
match an with
| Ctl_parser_types.Decl _ ->
false
| Ctl_parser_types.Stmt stmt -> (
let str_kind = ALVar.alexp_to_string alexp_kind in
match Clang_ast_proj.get_cast_kind stmt with
| Some cast_kind ->
let cast_kind_str = Clang_ast_proj.string_of_cast_kind cast_kind in
String.equal cast_kind_str str_kind
| None ->
false )
let is_node an nodename =
let nodename_str = ALVar.alexp_to_string nodename in
if not (Clang_ast_proj.is_valid_astnode_kind nodename_str) then
L.(die ExternalError) "Node '%s' is not a valid AST node" nodename_str ;
let an_str =
match an with
| Ctl_parser_types.Stmt s ->
Clang_ast_proj.get_stmt_kind_string s
| Ctl_parser_types.Decl d ->
Clang_ast_proj.get_decl_kind_string d
in
ALVar.compare_str_with_alexp an_str nodename
let is_ptr_to_objc_class typ class_name =
match typ with
| Some (Clang_ast_t.ObjCObjectPointerType (_, {Clang_ast_t.qt_type_ptr})) -> (
match CAst_utils.get_desugared_type qt_type_ptr with
| Some (ObjCInterfaceType (_, ptr)) -> (
match CAst_utils.get_decl ptr with
| Some (ObjCInterfaceDecl (_, ndi, _, _, _)) ->
ALVar.compare_str_with_alexp ndi.ni_name class_name
| _ ->
false )
| _ ->
false )
| _ ->
false
let isa an classname =
match an with
| Ctl_parser_types.Stmt stmt -> (
match Clang_ast_proj.get_expr_tuple stmt with
| Some (_, _, expr_info) ->
let typ = CAst_utils.get_desugared_type expr_info.ei_qual_type.qt_type_ptr in
is_ptr_to_objc_class typ classname
| _ ->
false )
| _ ->
false
let is_class an re = is_objc_class_named an re
let is_at_selector_with_name an re =
match an with
| Ctl_parser_types.Stmt (ObjCSelectorExpr (_, _, _, s)) ->
ALVar.compare_str_with_alexp s re
| _ ->
false
let iphoneos_target_sdk_version_by_path (cxt : CLintersContext.context) =
let source_file = cxt.translation_unit_context.source_file in
let regex_version_opt =
List.find Config.iphoneos_target_sdk_version_path_regex
~f:(fun (version_path_regex : Config.iphoneos_target_sdk_version_path_regex) ->
ALVar.str_match_forward (SourceFile.to_rel_path source_file) version_path_regex.path )
in
match regex_version_opt with
| Some version_by_regex ->
Some version_by_regex.version
Config.iphoneos_target_sdk_version
let iphoneos_target_sdk_version_greater_or_equal (cxt : CLintersContext.context) version =
match iphoneos_target_sdk_version_by_path cxt with
| Some target_version ->
Utils.compare_versions target_version version >= 0
| None ->
false
let decl_unavailable_in_supported_ios_sdk (cxt : CLintersContext.context) an =
let config_iphoneos_target_sdk_version = iphoneos_target_sdk_version_by_path cxt in
let available_attr_ios_sdk_current_method =
match cxt.current_method with
| Some decl ->
get_available_attr_ios_sdk (Decl decl)
| None ->
None
in
let ios_version_guard =
match cxt.if_context with Some if_context -> if_context.ios_version_guard | None -> []
in
let allowed_os_versions =
Option.to_list config_iphoneos_target_sdk_version
@ ios_version_guard
@ Option.to_list available_attr_ios_sdk_current_method
in
let max_allowed_version = List.max_elt allowed_os_versions ~compare:Utils.compare_versions in
let available_attr_ios_sdk = get_available_attr_ios_sdk an in
match (available_attr_ios_sdk, max_allowed_version) with
| Some available_attr_ios_sdk, Some max_allowed_version ->
Utils.compare_versions available_attr_ios_sdk max_allowed_version > 0
| _ ->
false
let class_unavailable_in_supported_ios_sdk (cxt : CLintersContext.context) an =
match receiver_method_call an with
| Some decl ->
decl_unavailable_in_supported_ios_sdk cxt (Ctl_parser_types.Decl decl)
| None ->
false
let type_ptr_equal_type type_ptr type_str =
let parse_type_string str =
L.(debug Linters Medium) "Starting parsing type string '%s'@\n" str ;
let lexbuf = Lexing.from_string str in
try Types_parser.abs_ctype token lexbuf with
| CTLExceptions.ALParserInvariantViolationException s ->
raise
CTLExceptions.(
ALFileException (create_exc_info ("Syntax Error when defining type " ^ s) lexbuf))
| SyntaxError _ | Types_parser.Error ->
raise CTLExceptions.(ALFileException (create_exc_info "SYNTAX ERROR" lexbuf))
in
let abs_ctype =
match String.Map.find !parsed_type_map type_str with
| Some abs_ctype' ->
abs_ctype'
| None ->
let abs_ctype' = parse_type_string type_str in
parsed_type_map := String.Map.set !parsed_type_map ~key:type_str ~data:abs_ctype' ;
abs_ctype'
in
match CAst_utils.get_type type_ptr with
| Some c_type' ->
Ctl_parser_types.c_type_equal c_type' abs_ctype
| _ ->
L.(debug Linters Medium) "Couldn't find type....@\n" ;
false
let get_ast_node_type_ptr an =
match an with
| Ctl_parser_types.Stmt stmt -> (
match Clang_ast_proj.get_expr_tuple stmt with
| Some (_, _, expr_info) ->
Some expr_info.ei_qual_type.qt_type_ptr
| _ ->
None )
| Ctl_parser_types.Decl decl ->
CAst_utils.type_of_decl decl
let has_type an typ_ =
match (get_ast_node_type_ptr an, typ_) with
| Some pt, ALVar.Const typ ->
type_ptr_equal_type pt typ
| _ ->
false
let has_type_const_ptr_to_objc_class node =
let open Clang_ast_t in
match get_ast_node_type_ptr node with
| Some type_ptr -> (
match CAst_utils.get_desugared_type type_ptr with
| Some (ObjCObjectPointerType (_, qt)) ->
qt.qt_is_const
| _ ->
false )
| None ->
false
Return the lifetime of the pointer of an expression if it is of type AttributedType
let get_ivar_lifetime an =
match get_ast_node_type_ptr an with
| Some pt -> (
match CAst_utils.get_type pt with
| Some c_type -> (
L.(debug Linters Medium) "@\nChecking type: `%s`\n" (Clang_ast_j.string_of_c_type c_type) ;
let open Clang_ast_t in
match c_type with
| AttributedType (_, attr_info) ->
Some attr_info.Clang_ast_t.ati_lifetime
| ObjCObjectPointerType _ ->
Some `OCL_Strong
| _ ->
L.(debug Linters Medium) "Pointer is not of type AttributedType...@\n" ;
None )
| _ ->
L.(debug Linters Medium) "Couldn't find type....\n" ;
None )
| _ ->
L.(debug Linters Medium) "Couldn't find pointer...@\n" ;
None
let is_strong_ivar an =
match get_ivar_lifetime an with
| Some lifetime -> (
match lifetime with `OCL_Strong | `OCL_Autoreleasing | `OCL_None -> true | _ -> false )
| _ ->
false
let is_decl node =
match node with Ctl_parser_types.Decl _ -> true | Ctl_parser_types.Stmt _ -> false
let method_return_type an typ_ =
L.(debug Linters Verbose) "@\n Executing method_return_type..." ;
match (an, typ_) with
| Ctl_parser_types.Decl (Clang_ast_t.ObjCMethodDecl (_, _, mdi)), ALVar.Const typ ->
L.(debug Linters Verbose) "@\n with parameter `%s`...." typ ;
let qual_type = mdi.Clang_ast_t.omdi_result_type in
type_ptr_equal_type qual_type.Clang_ast_t.qt_type_ptr typ
| _ ->
false
let rec check_protocol_hiearachy decls_ptr prot_name_ =
let open Clang_ast_t in
let is_this_protocol di_opt =
match di_opt with Some di -> ALVar.compare_str_with_alexp di.ni_name prot_name_ | _ -> false
in
match decls_ptr with
| [] ->
false
| pt :: decls' ->
let di, protocols =
match CAst_utils.get_decl pt with
| Some (ObjCProtocolDecl (_, di, _, _, opcdi)) ->
(Some di, opcdi.opcdi_protocols)
| _ ->
(None, [])
in
if is_this_protocol di || List.exists ~f:(fun dr -> is_this_protocol dr.dr_name) protocols
then true
else
let super_prot = List.map ~f:(fun dr -> dr.dr_decl_pointer) protocols in
check_protocol_hiearachy (super_prot @ decls') prot_name_
let has_type_subprotocol_of an prot_name_ =
let open Clang_ast_t in
let rec check_subprotocol t =
match t with
| Some (ObjCObjectPointerType (_, qt)) ->
check_subprotocol (CAst_utils.get_type qt.qt_type_ptr)
| Some (ObjCObjectType (_, ooti)) ->
if List.length ooti.ooti_protocol_decls_ptr > 0 then
check_protocol_hiearachy ooti.ooti_protocol_decls_ptr prot_name_
else
List.exists
~f:(fun qt -> check_subprotocol (CAst_utils.get_type qt.qt_type_ptr))
ooti.ooti_type_args
| Some (ObjCInterfaceType (_, pt)) ->
check_protocol_hiearachy [pt] prot_name_
| _ ->
false
in
match get_ast_node_type_ptr an with
| Some tp ->
check_subprotocol (CAst_utils.get_type tp)
| _ ->
false
let within_responds_to_selector_block (cxt : CLintersContext.context) an =
let open Clang_ast_t in
match an with
| Ctl_parser_types.Decl (ObjCMethodDecl (_, named_decl_info, _)) -> (
match cxt.if_context with
| Some if_context ->
let in_selector_block = if_context.within_responds_to_selector_block in
List.mem ~equal:String.equal in_selector_block named_decl_info.ni_name
| None ->
false )
| _ ->
false
let objc_method_call_within_responds_to_selector_block (cxt : CLintersContext.context) an =
let open Clang_ast_t in
match an with
| Ctl_parser_types.Stmt (ObjCMessageExpr (_, _, _, mdi)) -> (
match cxt.if_context with
| Some if_context ->
let in_selector_block = if_context.within_responds_to_selector_block in
List.mem ~equal:String.equal in_selector_block mdi.omei_selector
| None ->
false )
| _ ->
false
let within_available_class_block (cxt : CLintersContext.context) an =
match (receiver_method_call an, cxt.if_context) with
| Some receiver, Some if_context -> (
let in_available_class_block = if_context.within_available_class_block in
match declaration_name receiver with
| Some receiver_name ->
List.mem ~equal:String.equal in_available_class_block receiver_name
| None ->
false )
| _ ->
false
let using_namespace an namespace =
let open Clang_ast_t in
match an with
| Ctl_parser_types.Decl (UsingDirectiveDecl (_, _, uddi)) -> (
match uddi.uddi_nominated_namespace with
| Some dr -> (
match (dr.dr_kind, dr.dr_name) with
| `Namespace, Some ni ->
ALVar.compare_str_with_alexp ni.ni_name namespace
| _ ->
false )
| None ->
false )
| _ ->
false
let rec get_decl_attributes an =
let open Clang_ast_t in
let open Ctl_parser_types in
match an with
| Stmt (CallExpr (_, func :: _, _)) ->
get_decl_attributes (Stmt func)
| Stmt (ImplicitCastExpr (_, [stmt], _, _)) ->
get_decl_attributes (Stmt stmt)
| Stmt (DeclRefExpr (_, _, _, drti)) -> (
match CAst_utils.get_decl_opt_with_decl_ref_opt drti.drti_decl_ref with
| Some decl ->
get_decl_attributes (Decl decl)
| None ->
[] )
| Decl decl ->
let decl_info = Clang_ast_proj.get_decl_tuple decl in
decl_info.di_attributes
| _ ->
[]
let rec get_decl_attributes_for_callexpr_param an =
let open Clang_ast_t in
let open Ctl_parser_types in
let get_attr_param p = match p with ParmVarDecl (di, _, _, _) -> di.di_attributes | _ -> [] in
match an with
| Stmt (CallExpr (_, func :: _, _)) ->
get_decl_attributes_for_callexpr_param (Stmt func)
| Stmt (ImplicitCastExpr (_, [stmt], _, _)) ->
get_decl_attributes_for_callexpr_param (Stmt stmt)
| Stmt (DeclRefExpr (si, _, _, drti)) -> (
L.debug Linters Verbose "#####POINTER LOOP UP: '%i'@\n" si.si_pointer ;
match CAst_utils.get_decl_opt_with_decl_ref_opt drti.drti_decl_ref with
| Some (FunctionDecl (_, _, _, fdi)) ->
List.fold fdi.fdi_parameters ~f:(fun acc p -> List.append (get_attr_param p) acc) ~init:[]
| Some (ParmVarDecl _ as d) ->
get_attr_param d
| _ ->
[] )
| _ ->
[]
let visibility_matches vis_str (visibility : Clang_ast_t.visibility_attr) =
match (visibility, vis_str) with
| DefaultVisibility, "Default" ->
true
| HiddenVisibility, "Hidden" ->
true
| ProtectedVisibility, "Protected" ->
true
| _ ->
false
let has_visibility_attribute an visibility =
let has_visibility_attr attrs param =
List.exists attrs ~f:(function
| `VisibilityAttr (_attr_info, visibility) ->
visibility_matches param visibility
| _ ->
false )
in
let attributes = get_decl_attributes an in
match visibility with ALVar.Const vis -> has_visibility_attr attributes vis | _ -> false
let has_no_escape_attribute an =
let attributes = get_decl_attributes_for_callexpr_param an in
List.exists ~f:(fun attr -> match attr with `NoEscapeAttr _ -> true | _ -> false) attributes
let has_used_attribute an =
let attributes = get_decl_attributes an in
List.exists ~f:(fun attr -> match attr with `UsedAttr _ -> true | _ -> false) attributes
true is a declaration has an Unavailable attribute
let has_unavailable_attribute an =
let is_unavailable_attr attr = match attr with `UnavailableAttr _ -> true | _ -> false in
match an with
| Ctl_parser_types.Decl d ->
let attrs = (Clang_ast_proj.get_decl_tuple d).di_attributes in
List.exists attrs ~f:is_unavailable_attr
| _ ->
false
let has_value an al_exp =
let open Clang_ast_t in
let open Ctl_parser_types in
match an with
| Stmt (IntegerLiteral (_, _, _, integer_literal_info)) ->
let value = integer_literal_info.Clang_ast_t.ili_value in
ALVar.compare_str_with_alexp value al_exp
| Stmt (StringLiteral (_, _, _, l)) ->
ALVar.compare_str_with_alexp (String.concat ~sep:"" l) al_exp
| _ ->
false
let is_method_called_by_superclass an =
let open Clang_ast_t in
let open Ctl_parser_types in
match an with
| Stmt (ObjCMessageExpr (_, _, _, obj_c_message_expr_info)) -> (
match obj_c_message_expr_info.omei_receiver_kind with `SuperInstance -> true | _ -> false )
| _ ->
false
let is_cxx_copy_constructor an =
let open Clang_ast_t in
match an with
| Ctl_parser_types.Stmt (CXXConstructExpr (_, _, _, xcei)) ->
xcei.xcei_is_copy_constructor
| _ ->
false
let has_cxx_fully_qualified_name an qual_name_re =
match Ctl_parser_types.ast_node_cxx_fully_qualified_name an with
| "" ->
false
| fully_qualified_name ->
ALVar.compare_str_with_alexp fully_qualified_name qual_name_re
let has_cxx_fully_qualified_name_in_custom_symbols an list_name =
match Ctl_parser_types.ast_node_cxx_fully_qualified_name an with
| "" ->
false
| fully_qualified_name ->
Config.is_in_custom_symbols list_name fully_qualified_name
let is_cxx_method_overriding an qual_name_re =
let rec overrides_named (decl_refs : Clang_ast_t.decl_ref list) (qnre : ALVar.alexp) =
List.exists
~f:(fun (decl_ref : Clang_ast_t.decl_ref) ->
match CAst_utils.get_decl decl_ref.dr_decl_pointer with
| None ->
false
| Some decl -> (
match decl with
| Clang_ast_t.CXXMethodDecl (_, ndi, _, _, mdi) ->
ALVar.compare_str_with_alexp
(String.concat ~sep:"::" (List.rev ndi.ni_qual_name))
qnre
|| overrides_named mdi.xmdi_overriden_methods qnre
| _ ->
false ) )
decl_refs
in
match an with
| Ctl_parser_types.Decl (Clang_ast_t.CXXMethodDecl (_, _, _, _, mdi)) -> (
match qual_name_re with
| None ->
not (List.is_empty mdi.xmdi_overriden_methods)
| Some qnre ->
overrides_named mdi.xmdi_overriden_methods qnre )
| _ ->
false
let is_init_expr_cxx11_constant an =
let open Clang_ast_t in
match an with
| Ctl_parser_types.Decl (VarDecl (_, _, _, vdi)) ->
vdi.vdi_is_init_expr_cxx11_constant
| _ ->
false
let call_cxx_method an name =
let open Clang_ast_t in
match an with
| Ctl_parser_types.Stmt (CXXMemberCallExpr (_, member :: _, _)) -> (
match member with
| MemberExpr (_, _, _, memberExprInfo) ->
ALVar.compare_str_with_alexp memberExprInfo.mei_name.ni_name name
| _ ->
false )
| _ ->
false
let source_file_matches src_file path_re =
Option.value_map
~f:(fun sf ->
ALVar.compare_str_with_alexp (SourceFile.to_rel_path (SourceFile.create sf)) path_re )
~default:false src_file
let is_in_source_file an path_re = source_file_matches (Ctl_parser_types.get_source_file an) path_re
let is_referencing_decl_from_source_file an path_re =
source_file_matches (Ctl_parser_types.get_referenced_decl_source_file an) path_re
let captured_var_of_type typ captured_var =
match captured_var.Clang_ast_t.bcv_variable with
| Some dr ->
let _, _, qt = CAst_utils.get_info_from_decl_ref dr in
type_ptr_equal_type qt.Clang_ast_t.qt_type_ptr (ALVar.alexp_to_string typ)
| _ ->
false
let objc_block_is_capturing_var_of_type an typ =
match an with
| Ctl_parser_types.Decl (Clang_ast_t.BlockDecl (_, bdi)) ->
List.exists ~f:(captured_var_of_type typ) bdi.bdi_captured_variables
| _ ->
false
|
dd1e49eaba8936103ea27737b49c5f1de66b4122baa74ea430e63b8616a46021
|
AshleyYakeley/Truth
|
Editor.hs
|
module Changes.Core.UI.Editor where
import Changes.Core.Edit
import Changes.Core.Import
import Changes.Core.Lens
import Changes.Core.Model
import Changes.Core.UI.View.View
type Editing :: Type -> Type -> Type
data Editing update r = MkEditing
{ editingUpdate :: NonEmpty update -> EditContext -> View ()
, editingTask :: Task IO ()
, editingDo :: Task IO () -> View r
}
instance Functor (Editing update) where
fmap ab (MkEditing eu et ed) = MkEditing eu et $ \ut -> fmap ab $ ed ut
instance Applicative (Editing update) where
pure a = let
editingUpdate _ _ = return ()
editingTask = mempty
editingDo _ = return a
in MkEditing {..}
(MkEditing eu1 et1 ed1) <*> (MkEditing eu2 et2 ed2) = let
editingUpdate :: NonEmpty update -> EditContext -> View ()
editingUpdate edits ec = do
eu1 edits ec
eu2 edits ec
editingTask = et1 <> et2
editingDo utask = do
ab <- ed1 utask
a <- ed2 utask
return $ ab a
in MkEditing {..}
type Editor :: Type -> Type -> Type
newtype Editor update r =
MkEditor (Reference (UpdateEdit update) -> View (Editing update r))
instance Functor (Editor update) where
fmap ab (MkEditor ed) = MkEditor $ fmap (fmap (fmap ab)) ed
instance Applicative (Editor update) where
pure a = MkEditor $ pure $ pure $ pure a
(MkEditor ed1) <*> (MkEditor ed2) = MkEditor $ liftA2 (liftA2 (<*>)) ed1 ed2
runEditor :: Model update -> Editor update r -> View r
runEditor model (MkEditor ed) = do
e <- viewBindModelUpdates model (\_ -> True) (ed $ modelReference model) editingTask editingUpdate
editingDo e $ modelUpdatesTask model
execEditor :: View (Editor update r) -> Editor update r
execEditor cv =
MkEditor $ \ref -> do
MkEditor ed <- cv
ed ref
mapEditor :: forall updateA updateB r. ChangeLens updateA updateB -> Editor updateB r -> Editor updateA r
mapEditor l (MkEditor editor) =
MkEditor $ \refA -> do
MkEditing euB et ed <- editor $ mapReference l refA
let
euA :: NonEmpty updateA -> EditContext -> View ()
euA updatesA ec =
viewRunResourceContext refA $ \unlift arefA -> do
updatessB <-
for (toList updatesA) $ \updateA ->
clUpdate l updateA $ \rd -> liftIO $ unlift $ refRead arefA rd
case nonEmpty $ mconcat updatessB of
Nothing -> return ()
Just updatesB -> euB updatesB ec
return $ MkEditing euA et ed
floatingMapEditor ::
forall updateA updateB r. FloatingChangeLens updateA updateB -> Editor updateB r -> Editor updateA r
floatingMapEditor (MkFloatingChangeLens (NoFloatInit r) rlens) editorB = mapEditor (rlens r) editorB
floatingMapEditor (MkFloatingChangeLens (ReadFloatInit finit) rlens) editorB =
MkEditor $ \refA -> do
r <- viewRunResource refA $ \arefA -> finit $ refRead arefA
let MkEditor editorA = mapEditor (rlens r) editorB
editorA refA
| null |
https://raw.githubusercontent.com/AshleyYakeley/Truth/b1db68e38496a88268fa9b9d02059c597b21af05/Changes/changes-core/lib/Changes/Core/UI/Editor.hs
|
haskell
|
module Changes.Core.UI.Editor where
import Changes.Core.Edit
import Changes.Core.Import
import Changes.Core.Lens
import Changes.Core.Model
import Changes.Core.UI.View.View
type Editing :: Type -> Type -> Type
data Editing update r = MkEditing
{ editingUpdate :: NonEmpty update -> EditContext -> View ()
, editingTask :: Task IO ()
, editingDo :: Task IO () -> View r
}
instance Functor (Editing update) where
fmap ab (MkEditing eu et ed) = MkEditing eu et $ \ut -> fmap ab $ ed ut
instance Applicative (Editing update) where
pure a = let
editingUpdate _ _ = return ()
editingTask = mempty
editingDo _ = return a
in MkEditing {..}
(MkEditing eu1 et1 ed1) <*> (MkEditing eu2 et2 ed2) = let
editingUpdate :: NonEmpty update -> EditContext -> View ()
editingUpdate edits ec = do
eu1 edits ec
eu2 edits ec
editingTask = et1 <> et2
editingDo utask = do
ab <- ed1 utask
a <- ed2 utask
return $ ab a
in MkEditing {..}
type Editor :: Type -> Type -> Type
newtype Editor update r =
MkEditor (Reference (UpdateEdit update) -> View (Editing update r))
instance Functor (Editor update) where
fmap ab (MkEditor ed) = MkEditor $ fmap (fmap (fmap ab)) ed
instance Applicative (Editor update) where
pure a = MkEditor $ pure $ pure $ pure a
(MkEditor ed1) <*> (MkEditor ed2) = MkEditor $ liftA2 (liftA2 (<*>)) ed1 ed2
runEditor :: Model update -> Editor update r -> View r
runEditor model (MkEditor ed) = do
e <- viewBindModelUpdates model (\_ -> True) (ed $ modelReference model) editingTask editingUpdate
editingDo e $ modelUpdatesTask model
execEditor :: View (Editor update r) -> Editor update r
execEditor cv =
MkEditor $ \ref -> do
MkEditor ed <- cv
ed ref
mapEditor :: forall updateA updateB r. ChangeLens updateA updateB -> Editor updateB r -> Editor updateA r
mapEditor l (MkEditor editor) =
MkEditor $ \refA -> do
MkEditing euB et ed <- editor $ mapReference l refA
let
euA :: NonEmpty updateA -> EditContext -> View ()
euA updatesA ec =
viewRunResourceContext refA $ \unlift arefA -> do
updatessB <-
for (toList updatesA) $ \updateA ->
clUpdate l updateA $ \rd -> liftIO $ unlift $ refRead arefA rd
case nonEmpty $ mconcat updatessB of
Nothing -> return ()
Just updatesB -> euB updatesB ec
return $ MkEditing euA et ed
floatingMapEditor ::
forall updateA updateB r. FloatingChangeLens updateA updateB -> Editor updateB r -> Editor updateA r
floatingMapEditor (MkFloatingChangeLens (NoFloatInit r) rlens) editorB = mapEditor (rlens r) editorB
floatingMapEditor (MkFloatingChangeLens (ReadFloatInit finit) rlens) editorB =
MkEditor $ \refA -> do
r <- viewRunResource refA $ \arefA -> finit $ refRead arefA
let MkEditor editorA = mapEditor (rlens r) editorB
editorA refA
|
|
358c0c06d1736db6a13b8795dde3c44f9fe77e46816451cac6e896922c4c8063
|
xmonad/xmonad-contrib
|
SwapWorkspaces.hs
|
# LANGUAGE ScopedTypeVariables #
# OPTIONS_GHC -fno - warn - missing - signatures #
module SwapWorkspaces where
import Instances
import Test.QuickCheck
import XMonad.StackSet
import XMonad.Actions.SwapWorkspaces
-- Ensures that no "loss of information" can happen from a swap.
prop_double_swap (ss :: T) = do
t1 <- arbitraryTag ss
t2 <- arbitraryTag ss
let swap = swapWorkspaces t1 t2
return $ ss == swap (swap ss)
-- Degrade nicely when given invalid data.
prop_invalid_swap (ss :: T) = do
t1 <- arbitrary `suchThat` (not . (`tagMember` ss))
t2 <- arbitrary `suchThat` (not . (`tagMember` ss))
return $ ss == swapWorkspaces t1 t2 ss
-- This doesn't pass yet. Probably should.
prop_half_invalid_swap ( ss : : T ) ( NonNegative t1 ) ( NonNegative t2 ) =
-- t1 `tagMember` ss && not (t2 `tagMember` ss) ==>
-- ss == swapWorkspaces t1 t2 ss
zipWorkspacesWith :: (Workspace i l a -> Workspace i l a -> n) -> StackSet i l a s sd ->
StackSet i l a s sd -> [n]
zipWorkspacesWith f s t = f (workspace $ current s) (workspace $ current t) :
zipWith f (map workspace $ visible s) (map workspace $ visible t) ++
zipWith f (hidden s) (hidden t)
-- Swap only modifies the workspaces tagged t1 and t2 -- leaves all others alone.
prop_swap_only_two (ss :: T) = do
t1 <- arbitraryTag ss
t2 <- arbitraryTag ss
let mostlyEqual w1 w2 = map tag [w1, w2] `elem` [[t1, t2], [t2, t1]] || w1 == w2
return $ and $ zipWorkspacesWith mostlyEqual ss (swapWorkspaces t1 t2 ss)
-- swapWithCurrent stays on current
prop_swap_with_current (ss :: T) = do
t <- arbitraryTag ss
let before = workspace $ current ss
let after = workspace $ current $ swapWithCurrent t ss
return $ layout before == layout after && stack before == stack after
| null |
https://raw.githubusercontent.com/xmonad/xmonad-contrib/1d7abb102f7668369586e5da13ef4842982fb8e5/tests/SwapWorkspaces.hs
|
haskell
|
Ensures that no "loss of information" can happen from a swap.
Degrade nicely when given invalid data.
This doesn't pass yet. Probably should.
t1 `tagMember` ss && not (t2 `tagMember` ss) ==>
ss == swapWorkspaces t1 t2 ss
Swap only modifies the workspaces tagged t1 and t2 -- leaves all others alone.
swapWithCurrent stays on current
|
# LANGUAGE ScopedTypeVariables #
# OPTIONS_GHC -fno - warn - missing - signatures #
module SwapWorkspaces where
import Instances
import Test.QuickCheck
import XMonad.StackSet
import XMonad.Actions.SwapWorkspaces
prop_double_swap (ss :: T) = do
t1 <- arbitraryTag ss
t2 <- arbitraryTag ss
let swap = swapWorkspaces t1 t2
return $ ss == swap (swap ss)
prop_invalid_swap (ss :: T) = do
t1 <- arbitrary `suchThat` (not . (`tagMember` ss))
t2 <- arbitrary `suchThat` (not . (`tagMember` ss))
return $ ss == swapWorkspaces t1 t2 ss
prop_half_invalid_swap ( ss : : T ) ( NonNegative t1 ) ( NonNegative t2 ) =
zipWorkspacesWith :: (Workspace i l a -> Workspace i l a -> n) -> StackSet i l a s sd ->
StackSet i l a s sd -> [n]
zipWorkspacesWith f s t = f (workspace $ current s) (workspace $ current t) :
zipWith f (map workspace $ visible s) (map workspace $ visible t) ++
zipWith f (hidden s) (hidden t)
prop_swap_only_two (ss :: T) = do
t1 <- arbitraryTag ss
t2 <- arbitraryTag ss
let mostlyEqual w1 w2 = map tag [w1, w2] `elem` [[t1, t2], [t2, t1]] || w1 == w2
return $ and $ zipWorkspacesWith mostlyEqual ss (swapWorkspaces t1 t2 ss)
prop_swap_with_current (ss :: T) = do
t <- arbitraryTag ss
let before = workspace $ current ss
let after = workspace $ current $ swapWithCurrent t ss
return $ layout before == layout after && stack before == stack after
|
85d76dcb358082eba02026055bfd13e070c1108624c16c4fda9190599d44cc29
|
conscell/hugs-android
|
GHCPackageConfig.hs
|
# OPTIONS_GHC -cpp #
-----------------------------------------------------------------------------
-- |
-- Module : Distribution.GHCPackageConfig
Copyright : ( c ) The University of Glasgow 2004
--
-- Maintainer :
-- Stability : alpha
-- Portability : portable
--
Explanation : Performs registration for GHC . Specific to
ghc - pkg . Creates a GHC package config file .
module Distribution.Simple.GHCPackageConfig (
GHCPackageConfig(..),
mkGHCPackageConfig,
defaultGHCPackageConfig,
showGHCPackageConfig,
localPackageConfig, maybeCreateLocalPackageConfig,
canWriteLocalPackageConfig, canReadLocalPackageConfig
) where
import Distribution.PackageDescription (PackageDescription(..), BuildInfo(..), Library(..))
import Distribution.Package (PackageIdentifier(..), showPackageId)
import Distribution.Simple.LocalBuildInfo (LocalBuildInfo(..),mkLibDir)
import Distribution.Setup (CopyDest(..))
import Control.Exception (try)
import Control.Monad(unless)
import Text.PrettyPrint.HughesPJ
import System.Directory (doesFileExist, getPermissions, Permissions (..))
import Distribution.Compat.FilePath (joinFileName)
import Distribution.Compat.Directory (getHomeDirectory)
|Where ghc keeps the --user files .
-- |return the file, whether it exists, and whether it's readable
localPackageConfig :: IO FilePath
localPackageConfig = do u <- getHomeDirectory
return $ (u `joinFileName` ".ghc-packages")
-- |If the package file doesn't exist, we should try to create it. If
-- it already exists, do nothing and return true. This does not take
-- into account whether it is readable or writeable.
maybeCreateLocalPackageConfig :: IO Bool -- ^success?
maybeCreateLocalPackageConfig
= do f <- localPackageConfig
exists <- doesFileExist f
unless exists $ (try (writeFile f "[]\n") >> return ())
doesFileExist f
-- |Helper function for canReadPackageConfig and canWritePackageConfig
checkPermission :: (Permissions -> Bool) -> IO Bool
checkPermission perm
= do f <- localPackageConfig
exists <- doesFileExist f
if exists
then getPermissions f >>= (return . perm)
else return False
for read permission on the localPackageConfig
canReadLocalPackageConfig :: IO Bool
canReadLocalPackageConfig = checkPermission readable
for write permission on the localPackageConfig
canWriteLocalPackageConfig :: IO Bool
canWriteLocalPackageConfig = checkPermission writable
-- -----------------------------------------------------------------------------
GHC 6.2 PackageConfig type
Until GHC supports the InstalledPackageInfo type above , we use its
existing PackagConfig type .
mkGHCPackageConfig :: PackageDescription -> LocalBuildInfo -> GHCPackageConfig
mkGHCPackageConfig pkg_descr lbi
= defaultGHCPackageConfig {
name = pkg_name,
auto = True,
import_dirs = [mkLibDir pkg_descr lbi NoCopyDest],
library_dirs = (mkLibDir pkg_descr lbi NoCopyDest:
maybe [] (extraLibDirs . libBuildInfo) (library pkg_descr)),
hs_libraries = ["HS"++(showPackageId (package pkg_descr))],
extra_libraries = maybe [] (extraLibs . libBuildInfo) (library pkg_descr),
include_dirs = maybe [] (includeDirs . libBuildInfo) (library pkg_descr),
c_includes = maybe [] (includes . libBuildInfo) (library pkg_descr),
package_deps = map pkgName (packageDeps lbi)
}
where
pkg_name = pkgName (package pkg_descr)
data GHCPackageConfig
= GHCPackage {
name :: String,
auto :: Bool,
import_dirs :: [String],
source_dirs :: [String],
library_dirs :: [String],
hs_libraries :: [String],
extra_libraries :: [String],
include_dirs :: [String],
c_includes :: [String],
package_deps :: [String],
extra_ghc_opts :: [String],
extra_cc_opts :: [String],
extra_ld_opts :: [String],
ignored everywhere but on / MacOS X
ignored everywhere but on / MacOS X
}
defaultGHCPackageConfig :: GHCPackageConfig
defaultGHCPackageConfig
= GHCPackage {
name = error "defaultPackage",
auto = False,
import_dirs = [],
source_dirs = [],
library_dirs = [],
hs_libraries = [],
extra_libraries = [],
include_dirs = [],
c_includes = [],
package_deps = [],
extra_ghc_opts = [],
extra_cc_opts = [],
extra_ld_opts = [],
framework_dirs = [],
extra_frameworks= []
}
-- ---------------------------------------------------------------------------
-- Pretty printing package info
showGHCPackageConfig :: GHCPackageConfig -> String
showGHCPackageConfig pkg = render $
text "Package" $$ nest 3 (braces (
sep (punctuate comma [
text "name = " <> text (show (name pkg)),
text "auto = " <> text (show (auto pkg)),
dumpField "import_dirs" (import_dirs pkg),
dumpField "source_dirs" (source_dirs pkg),
dumpField "library_dirs" (library_dirs pkg),
dumpField "hs_libraries" (hs_libraries pkg),
dumpField "extra_libraries" (extra_libraries pkg),
dumpField "include_dirs" (include_dirs pkg),
dumpField "c_includes" (c_includes pkg),
dumpField "package_deps" (package_deps pkg),
dumpField "extra_ghc_opts" (extra_ghc_opts pkg),
dumpField "extra_cc_opts" (extra_cc_opts pkg),
dumpField "extra_ld_opts" (extra_ld_opts pkg),
dumpField "framework_dirs" (framework_dirs pkg),
dumpField "extra_frameworks"(extra_frameworks pkg)
])))
dumpField :: String -> [String] -> Doc
dumpField name' val = hang (text name' <+> equals) 2 (dumpFieldContents val)
dumpFieldContents :: [String] -> Doc
dumpFieldContents val = brackets (sep (punctuate comma (map (text . show) val)))
| null |
https://raw.githubusercontent.com/conscell/hugs-android/31e5861bc1a1dd9931e6b2471a9f45c14e3c6c7e/hugs/lib/hugs/packages/Cabal/Distribution/Simple/GHCPackageConfig.hs
|
haskell
|
---------------------------------------------------------------------------
|
Module : Distribution.GHCPackageConfig
Maintainer :
Stability : alpha
Portability : portable
user files .
|return the file, whether it exists, and whether it's readable
|If the package file doesn't exist, we should try to create it. If
it already exists, do nothing and return true. This does not take
into account whether it is readable or writeable.
^success?
|Helper function for canReadPackageConfig and canWritePackageConfig
-----------------------------------------------------------------------------
---------------------------------------------------------------------------
Pretty printing package info
|
# OPTIONS_GHC -cpp #
Copyright : ( c ) The University of Glasgow 2004
Explanation : Performs registration for GHC . Specific to
ghc - pkg . Creates a GHC package config file .
module Distribution.Simple.GHCPackageConfig (
GHCPackageConfig(..),
mkGHCPackageConfig,
defaultGHCPackageConfig,
showGHCPackageConfig,
localPackageConfig, maybeCreateLocalPackageConfig,
canWriteLocalPackageConfig, canReadLocalPackageConfig
) where
import Distribution.PackageDescription (PackageDescription(..), BuildInfo(..), Library(..))
import Distribution.Package (PackageIdentifier(..), showPackageId)
import Distribution.Simple.LocalBuildInfo (LocalBuildInfo(..),mkLibDir)
import Distribution.Setup (CopyDest(..))
import Control.Exception (try)
import Control.Monad(unless)
import Text.PrettyPrint.HughesPJ
import System.Directory (doesFileExist, getPermissions, Permissions (..))
import Distribution.Compat.FilePath (joinFileName)
import Distribution.Compat.Directory (getHomeDirectory)
localPackageConfig :: IO FilePath
localPackageConfig = do u <- getHomeDirectory
return $ (u `joinFileName` ".ghc-packages")
maybeCreateLocalPackageConfig
= do f <- localPackageConfig
exists <- doesFileExist f
unless exists $ (try (writeFile f "[]\n") >> return ())
doesFileExist f
checkPermission :: (Permissions -> Bool) -> IO Bool
checkPermission perm
= do f <- localPackageConfig
exists <- doesFileExist f
if exists
then getPermissions f >>= (return . perm)
else return False
for read permission on the localPackageConfig
canReadLocalPackageConfig :: IO Bool
canReadLocalPackageConfig = checkPermission readable
for write permission on the localPackageConfig
canWriteLocalPackageConfig :: IO Bool
canWriteLocalPackageConfig = checkPermission writable
GHC 6.2 PackageConfig type
Until GHC supports the InstalledPackageInfo type above , we use its
existing PackagConfig type .
mkGHCPackageConfig :: PackageDescription -> LocalBuildInfo -> GHCPackageConfig
mkGHCPackageConfig pkg_descr lbi
= defaultGHCPackageConfig {
name = pkg_name,
auto = True,
import_dirs = [mkLibDir pkg_descr lbi NoCopyDest],
library_dirs = (mkLibDir pkg_descr lbi NoCopyDest:
maybe [] (extraLibDirs . libBuildInfo) (library pkg_descr)),
hs_libraries = ["HS"++(showPackageId (package pkg_descr))],
extra_libraries = maybe [] (extraLibs . libBuildInfo) (library pkg_descr),
include_dirs = maybe [] (includeDirs . libBuildInfo) (library pkg_descr),
c_includes = maybe [] (includes . libBuildInfo) (library pkg_descr),
package_deps = map pkgName (packageDeps lbi)
}
where
pkg_name = pkgName (package pkg_descr)
data GHCPackageConfig
= GHCPackage {
name :: String,
auto :: Bool,
import_dirs :: [String],
source_dirs :: [String],
library_dirs :: [String],
hs_libraries :: [String],
extra_libraries :: [String],
include_dirs :: [String],
c_includes :: [String],
package_deps :: [String],
extra_ghc_opts :: [String],
extra_cc_opts :: [String],
extra_ld_opts :: [String],
ignored everywhere but on / MacOS X
ignored everywhere but on / MacOS X
}
defaultGHCPackageConfig :: GHCPackageConfig
defaultGHCPackageConfig
= GHCPackage {
name = error "defaultPackage",
auto = False,
import_dirs = [],
source_dirs = [],
library_dirs = [],
hs_libraries = [],
extra_libraries = [],
include_dirs = [],
c_includes = [],
package_deps = [],
extra_ghc_opts = [],
extra_cc_opts = [],
extra_ld_opts = [],
framework_dirs = [],
extra_frameworks= []
}
showGHCPackageConfig :: GHCPackageConfig -> String
showGHCPackageConfig pkg = render $
text "Package" $$ nest 3 (braces (
sep (punctuate comma [
text "name = " <> text (show (name pkg)),
text "auto = " <> text (show (auto pkg)),
dumpField "import_dirs" (import_dirs pkg),
dumpField "source_dirs" (source_dirs pkg),
dumpField "library_dirs" (library_dirs pkg),
dumpField "hs_libraries" (hs_libraries pkg),
dumpField "extra_libraries" (extra_libraries pkg),
dumpField "include_dirs" (include_dirs pkg),
dumpField "c_includes" (c_includes pkg),
dumpField "package_deps" (package_deps pkg),
dumpField "extra_ghc_opts" (extra_ghc_opts pkg),
dumpField "extra_cc_opts" (extra_cc_opts pkg),
dumpField "extra_ld_opts" (extra_ld_opts pkg),
dumpField "framework_dirs" (framework_dirs pkg),
dumpField "extra_frameworks"(extra_frameworks pkg)
])))
dumpField :: String -> [String] -> Doc
dumpField name' val = hang (text name' <+> equals) 2 (dumpFieldContents val)
dumpFieldContents :: [String] -> Doc
dumpFieldContents val = brackets (sep (punctuate comma (map (text . show) val)))
|
b07ac40e76f0f11fa01764aaffb4e467d0a49df89d922609c1c40d00d9ba5f6f
|
kmi/irs
|
french-cities-kb.lisp
|
Mode : Lisp ; Package :
File created in WebOnto
(in-package "OCML")
(in-ontology french-cities-kb)
(def-class french-city (city)
((located-in-country :value france)))
(def-instance Bordeaux french-city)
(def-instance Brest french-city)
(def-instance Cherbourg french-city)
(def-instance Dijon french-city)
(def-instance Dunkerque french-city)
(def-instance Grenoble french-city)
(def-instance Hendaye french-city)
(def-instance Lille french-city)
(def-instance Limoges french-city)
(def-instance Lyon french-city)
(def-instance Marseille french-city)
(def-instance Nancy french-city)
(def-instance Nantes french-city)
(def-instance Nice french-city)
(def-instance Orleans french-city)
(def-instance Paris french-city)
(def-instance Perpignan french-city)
(def-instance Rouen french-city)
(def-instance Strasbourg french-city)
(def-instance Toulon french-city)
(def-instance Toulouse french-city)
(def-instance Valence french-city)
| null |
https://raw.githubusercontent.com/kmi/irs/e1b8d696f61c6b6878c0e92d993ed549fee6e7dd/ontologies/applications/french-cities-kb/french-cities-kb.lisp
|
lisp
|
Package :
|
File created in WebOnto
(in-package "OCML")
(in-ontology french-cities-kb)
(def-class french-city (city)
((located-in-country :value france)))
(def-instance Bordeaux french-city)
(def-instance Brest french-city)
(def-instance Cherbourg french-city)
(def-instance Dijon french-city)
(def-instance Dunkerque french-city)
(def-instance Grenoble french-city)
(def-instance Hendaye french-city)
(def-instance Lille french-city)
(def-instance Limoges french-city)
(def-instance Lyon french-city)
(def-instance Marseille french-city)
(def-instance Nancy french-city)
(def-instance Nantes french-city)
(def-instance Nice french-city)
(def-instance Orleans french-city)
(def-instance Paris french-city)
(def-instance Perpignan french-city)
(def-instance Rouen french-city)
(def-instance Strasbourg french-city)
(def-instance Toulon french-city)
(def-instance Toulouse french-city)
(def-instance Valence french-city)
|
9ac3daeda36e56c69d7610c88d1e058eb6fe99a69d4131c4b73cfdab1b079771
|
gfngfn/SATySFi
|
myYojsonUtil.ml
|
type json = Yojson.SafePos.json
module YS = Yojson.SafePos
exception MultipleDesignation of Range.t * string
exception MissingRequiredKey of Range.t * string
exception SyntaxError of string * string
module YojsonMap = Map.Make(String)
type assoc = Yojson.position * json YojsonMap.t
let syntax_error srcpath msg =
raise (SyntaxError(srcpath, msg))
let make_range (pos : Yojson.position) =
let open Yojson in
let fname = BatOption.default "(none)" pos.file_name in
Range.make_large fname pos.start_line pos.start_column pos.end_line pos.end_column
let make_assoc ((pos, _) as json : json) : assoc =
let keyvals = json |> YS.Util.to_assoc in
let assoc =
keyvals |> List.fold_left (fun accmap (k, v) ->
if accmap |> YojsonMap.mem k then
let rng = make_range pos in
raise (MultipleDesignation(rng, k))
else
accmap |> YojsonMap.add k v
) YojsonMap.empty
in
(pos, assoc)
let find_opt (key : string) ((pos, assoc) : assoc) : json option =
assoc |> YojsonMap.find_opt key
let find (key : string) ((pos, assoc) : assoc) : json =
match assoc |> YojsonMap.find_opt key with
| None ->
let rng = make_range pos in
raise (MissingRequiredKey(rng, key))
| Some(json) ->
json
let fold (type a) (f : string -> json -> a -> a) (init : a) ((_, assoc) : assoc) : a =
YojsonMap.fold f assoc init
type 'a variant_arg =
| NoArg of (unit -> 'a)
| Arg of (json -> 'a)
let err_variant json branches =
let s =
branches |> List.map (function
| (label, NoArg(_)) -> "<" ^ label ^ ">"
| (label, Arg(_)) -> "<" ^ label ^ ": _ >"
) |> String.concat ", "
in
raise (YS.Util.Type_error("Expects one of the following form(s): " ^ s, json))
let decode_variant (type a) (branches : (string * a variant_arg) list) (json : json) : a =
match json with
| (_, `Variant(label, jsonopt)) ->
begin
match List.assoc_opt label branches with
| None ->
err_variant json branches
| Some(fopt) ->
begin
match (fopt, jsonopt) with
| (Arg(f), Some(arg)) -> f arg
| (NoArg(hook), None) -> hook ()
| _ -> err_variant json branches
end
end
| _ ->
err_variant json branches
| null |
https://raw.githubusercontent.com/gfngfn/SATySFi/9dbd61df0ab05943b3394830c371e927df45251a/src/myYojsonUtil.ml
|
ocaml
|
type json = Yojson.SafePos.json
module YS = Yojson.SafePos
exception MultipleDesignation of Range.t * string
exception MissingRequiredKey of Range.t * string
exception SyntaxError of string * string
module YojsonMap = Map.Make(String)
type assoc = Yojson.position * json YojsonMap.t
let syntax_error srcpath msg =
raise (SyntaxError(srcpath, msg))
let make_range (pos : Yojson.position) =
let open Yojson in
let fname = BatOption.default "(none)" pos.file_name in
Range.make_large fname pos.start_line pos.start_column pos.end_line pos.end_column
let make_assoc ((pos, _) as json : json) : assoc =
let keyvals = json |> YS.Util.to_assoc in
let assoc =
keyvals |> List.fold_left (fun accmap (k, v) ->
if accmap |> YojsonMap.mem k then
let rng = make_range pos in
raise (MultipleDesignation(rng, k))
else
accmap |> YojsonMap.add k v
) YojsonMap.empty
in
(pos, assoc)
let find_opt (key : string) ((pos, assoc) : assoc) : json option =
assoc |> YojsonMap.find_opt key
let find (key : string) ((pos, assoc) : assoc) : json =
match assoc |> YojsonMap.find_opt key with
| None ->
let rng = make_range pos in
raise (MissingRequiredKey(rng, key))
| Some(json) ->
json
let fold (type a) (f : string -> json -> a -> a) (init : a) ((_, assoc) : assoc) : a =
YojsonMap.fold f assoc init
type 'a variant_arg =
| NoArg of (unit -> 'a)
| Arg of (json -> 'a)
let err_variant json branches =
let s =
branches |> List.map (function
| (label, NoArg(_)) -> "<" ^ label ^ ">"
| (label, Arg(_)) -> "<" ^ label ^ ": _ >"
) |> String.concat ", "
in
raise (YS.Util.Type_error("Expects one of the following form(s): " ^ s, json))
let decode_variant (type a) (branches : (string * a variant_arg) list) (json : json) : a =
match json with
| (_, `Variant(label, jsonopt)) ->
begin
match List.assoc_opt label branches with
| None ->
err_variant json branches
| Some(fopt) ->
begin
match (fopt, jsonopt) with
| (Arg(f), Some(arg)) -> f arg
| (NoArg(hook), None) -> hook ()
| _ -> err_variant json branches
end
end
| _ ->
err_variant json branches
|
|
ac7e080b2a0cff52d6d9c72426e959ad285f8a098025625141c8bf5aa056b138
|
NorfairKing/smos
|
GitHub.hs
|
module Smos.GitHub
( smosGitHub,
)
where
import Smos.GitHub.Command
import Smos.GitHub.OptParse
smosGitHub :: IO ()
smosGitHub = do
Instructions d sets <- getInstructions
case d of
DispatchList -> githubList sets
DispatchImport importSets -> githubImport sets importSets
| null |
https://raw.githubusercontent.com/NorfairKing/smos/3b7021c22915ae16ae721c7da60d715e24f4e6bb/smos-github/src/Smos/GitHub.hs
|
haskell
|
module Smos.GitHub
( smosGitHub,
)
where
import Smos.GitHub.Command
import Smos.GitHub.OptParse
smosGitHub :: IO ()
smosGitHub = do
Instructions d sets <- getInstructions
case d of
DispatchList -> githubList sets
DispatchImport importSets -> githubImport sets importSets
|
|
7d8d949c02dda2f492df12ac8e297d4122fa8d1773d5ddcae058f88622323448
|
xapi-project/message-switch
|
updates.ml
|
(******************************************************************************)
(* Object update tracking *)
open Xapi_stdext_pervasives.Pervasiveext
module type INTERFACE = sig
val service_name : string
module Dynamic : sig
type id
val rpc_of_id : id -> Rpc.t
end
end
module Updates =
functor
(Interface : INTERFACE)
->
struct
module UpdateRecorder =
functor
(Ord : Map.OrderedType)
->
struct
(* Map of thing -> last update counter *)
module M = Map.Make (struct
type t = Ord.t
let compare = compare
end)
type id = int
(* Type for inner snapshot that we create when injecting a barrier *)
type barrier = {
bar_id: int (** This int is a token from outside. *)
; map_s: int M.t (** Snapshot of main map *)
; event_id: id
(** Snapshot of "next" from when barrier was injected *)
}
type t = {
map: int M.t (** Events with incrementing ids from "next" *)
; barriers: barrier list
; next: id
}
let initial = 0
let empty = {map= M.empty; barriers= []; next= initial + 1}
let add x t =
( {map= M.add x t.next t.map; barriers= t.barriers; next= t.next + 1}
, t.next + 1 )
let remove x t =
( {map= M.remove x t.map; barriers= t.barriers; next= t.next + 1}
, t.next + 1 )
let filter f t =
( {map= M.filter f t.map; barriers= t.barriers; next= t.next + 1}
, t.next + 1 )
let inject_barrier id filterfn t =
( {
map= t.map
; barriers=
{bar_id= id; map_s= M.filter filterfn t.map; event_id= t.next}
:: t.barriers
; next= t.next + 1
}
, t.next + 1 )
let remove_barrier id t =
( {
map= t.map
; barriers= List.filter (fun br -> br.bar_id <> id) t.barriers
; next= t.next + 1
}
, t.next + 1 )
let get from t =
(* [from] is the id of the most recent event already seen *)
let get_from_map map =
let _before, after = M.partition (fun _ time -> time <= from) map in
let xs, last =
M.fold
(fun key v (acc, m) -> ((key, v) :: acc, max m v))
after ([], from)
in
let xs =
List.sort (fun (_, v1) (_, v2) -> compare v1 v2) xs
|> List.map fst
in
(xs, last)
in
let rec filter_barriers bl acc =
match bl with
Stops at first too - old one , unlike List.filter
| x :: xs when x.event_id > from ->
filter_barriers xs (x :: acc)
| _ ->
List.rev acc
in
let recent_b = filter_barriers t.barriers [] in
let barriers =
List.map
(fun br -> (br.bar_id, get_from_map br.map_s |> fst))
recent_b
in
let rest, last_event = get_from_map t.map in
let last =
match recent_b with
assumes recent_b is sorted newest - first
| [] ->
last_event
| x :: _ ->
max last_event x.event_id
in
(* Barriers are stored newest-first, reverse to return them in order *)
(List.rev barriers, rest, last)
let last_id t = t.next - 1
let fold f t init = M.fold f t.map init
end
open Xapi_stdext_threads.Threadext
module U = UpdateRecorder (struct
type t = Interface.Dynamic.id
let compare = compare
end)
type id = U.id
type t = {mutable u: U.t; c: Condition.t; s: Scheduler.t; m: Mutex.t}
let empty scheduler =
{u= U.empty; c= Condition.create (); s= scheduler; m= Mutex.create ()}
type get_result =
(int * Interface.Dynamic.id list) list * Interface.Dynamic.id list * id
let get dbg ?(with_cancel = fun _ f -> f ()) from timeout t =
let from = Option.value ~default:U.initial from in
let cancel = ref false in
let cancel_fn () =
Mutex.execute t.m (fun () ->
cancel := true ;
Condition.broadcast t.c)
in
let id =
Option.map
(fun timeout ->
Scheduler.one_shot t.s (Scheduler.Delta timeout) dbg cancel_fn)
timeout
in
with_cancel cancel_fn (fun () ->
finally
(fun () ->
Mutex.execute t.m (fun () ->
let is_empty (x, y, _) = x = [] && y = [] in
let rec wait () =
let result = U.get from t.u in
if is_empty result && not !cancel then (
Condition.wait t.c t.m ; wait ()
) else
result
in
wait ()))
(fun () -> Option.iter (Scheduler.cancel t.s) id))
let last_id _dbg t = Mutex.execute t.m (fun () -> U.last_id t.u)
let add x t =
Mutex.execute t.m (fun () ->
let result, _id = U.add x t.u in
t.u <- result ;
Condition.broadcast t.c)
let remove x t =
Mutex.execute t.m (fun () ->
let result, _id = U.remove x t.u in
t.u <- result ;
Condition.broadcast t.c)
let filter f t =
Mutex.execute t.m (fun () ->
let result, _id = U.filter (fun x _y -> f x) t.u in
t.u <- result ;
Condition.broadcast t.c)
let inject_barrier id filter t =
Mutex.execute t.m (fun () ->
let result, _id = U.inject_barrier id filter t.u in
t.u <- result ;
Condition.broadcast t.c)
let remove_barrier id t =
Mutex.execute t.m (fun () ->
let result, _id = U.remove_barrier id t.u in
t.u <- result ;
Condition.broadcast t.c)
module Dump = struct
type u = {id: int; v: string} [@@deriving rpc]
type dump = {
updates: u list
; barriers: (int * int * u list) list
In barriers , first int is token i d of barrier ; second int is
event i d of snapshot ( from " next " )
event id of snapshot (from "next") *)
}
[@@deriving rpc]
let make_list updates =
U.M.fold
(fun key v acc ->
{id= v; v= key |> Interface.Dynamic.rpc_of_id |> Jsonrpc.to_string}
:: acc)
updates []
let make_raw u =
{
updates= make_list u.U.map
; barriers=
List.map
(fun br -> (br.U.bar_id, br.U.event_id, make_list br.U.map_s))
u.U.barriers
}
let make t = Mutex.execute t.m (fun () -> make_raw t.u)
end
end
| null |
https://raw.githubusercontent.com/xapi-project/message-switch/1d0d1aa45c01eba144ac2826d0d88bb663e33101/xapi-idl/lib/updates.ml
|
ocaml
|
****************************************************************************
Object update tracking
Map of thing -> last update counter
Type for inner snapshot that we create when injecting a barrier
* This int is a token from outside.
* Snapshot of main map
* Snapshot of "next" from when barrier was injected
* Events with incrementing ids from "next"
[from] is the id of the most recent event already seen
Barriers are stored newest-first, reverse to return them in order
|
open Xapi_stdext_pervasives.Pervasiveext
module type INTERFACE = sig
val service_name : string
module Dynamic : sig
type id
val rpc_of_id : id -> Rpc.t
end
end
module Updates =
functor
(Interface : INTERFACE)
->
struct
module UpdateRecorder =
functor
(Ord : Map.OrderedType)
->
struct
module M = Map.Make (struct
type t = Ord.t
let compare = compare
end)
type id = int
type barrier = {
; event_id: id
}
type t = {
; barriers: barrier list
; next: id
}
let initial = 0
let empty = {map= M.empty; barriers= []; next= initial + 1}
let add x t =
( {map= M.add x t.next t.map; barriers= t.barriers; next= t.next + 1}
, t.next + 1 )
let remove x t =
( {map= M.remove x t.map; barriers= t.barriers; next= t.next + 1}
, t.next + 1 )
let filter f t =
( {map= M.filter f t.map; barriers= t.barriers; next= t.next + 1}
, t.next + 1 )
let inject_barrier id filterfn t =
( {
map= t.map
; barriers=
{bar_id= id; map_s= M.filter filterfn t.map; event_id= t.next}
:: t.barriers
; next= t.next + 1
}
, t.next + 1 )
let remove_barrier id t =
( {
map= t.map
; barriers= List.filter (fun br -> br.bar_id <> id) t.barriers
; next= t.next + 1
}
, t.next + 1 )
let get from t =
let get_from_map map =
let _before, after = M.partition (fun _ time -> time <= from) map in
let xs, last =
M.fold
(fun key v (acc, m) -> ((key, v) :: acc, max m v))
after ([], from)
in
let xs =
List.sort (fun (_, v1) (_, v2) -> compare v1 v2) xs
|> List.map fst
in
(xs, last)
in
let rec filter_barriers bl acc =
match bl with
Stops at first too - old one , unlike List.filter
| x :: xs when x.event_id > from ->
filter_barriers xs (x :: acc)
| _ ->
List.rev acc
in
let recent_b = filter_barriers t.barriers [] in
let barriers =
List.map
(fun br -> (br.bar_id, get_from_map br.map_s |> fst))
recent_b
in
let rest, last_event = get_from_map t.map in
let last =
match recent_b with
assumes recent_b is sorted newest - first
| [] ->
last_event
| x :: _ ->
max last_event x.event_id
in
(List.rev barriers, rest, last)
let last_id t = t.next - 1
let fold f t init = M.fold f t.map init
end
open Xapi_stdext_threads.Threadext
module U = UpdateRecorder (struct
type t = Interface.Dynamic.id
let compare = compare
end)
type id = U.id
type t = {mutable u: U.t; c: Condition.t; s: Scheduler.t; m: Mutex.t}
let empty scheduler =
{u= U.empty; c= Condition.create (); s= scheduler; m= Mutex.create ()}
type get_result =
(int * Interface.Dynamic.id list) list * Interface.Dynamic.id list * id
let get dbg ?(with_cancel = fun _ f -> f ()) from timeout t =
let from = Option.value ~default:U.initial from in
let cancel = ref false in
let cancel_fn () =
Mutex.execute t.m (fun () ->
cancel := true ;
Condition.broadcast t.c)
in
let id =
Option.map
(fun timeout ->
Scheduler.one_shot t.s (Scheduler.Delta timeout) dbg cancel_fn)
timeout
in
with_cancel cancel_fn (fun () ->
finally
(fun () ->
Mutex.execute t.m (fun () ->
let is_empty (x, y, _) = x = [] && y = [] in
let rec wait () =
let result = U.get from t.u in
if is_empty result && not !cancel then (
Condition.wait t.c t.m ; wait ()
) else
result
in
wait ()))
(fun () -> Option.iter (Scheduler.cancel t.s) id))
let last_id _dbg t = Mutex.execute t.m (fun () -> U.last_id t.u)
let add x t =
Mutex.execute t.m (fun () ->
let result, _id = U.add x t.u in
t.u <- result ;
Condition.broadcast t.c)
let remove x t =
Mutex.execute t.m (fun () ->
let result, _id = U.remove x t.u in
t.u <- result ;
Condition.broadcast t.c)
let filter f t =
Mutex.execute t.m (fun () ->
let result, _id = U.filter (fun x _y -> f x) t.u in
t.u <- result ;
Condition.broadcast t.c)
let inject_barrier id filter t =
Mutex.execute t.m (fun () ->
let result, _id = U.inject_barrier id filter t.u in
t.u <- result ;
Condition.broadcast t.c)
let remove_barrier id t =
Mutex.execute t.m (fun () ->
let result, _id = U.remove_barrier id t.u in
t.u <- result ;
Condition.broadcast t.c)
module Dump = struct
type u = {id: int; v: string} [@@deriving rpc]
type dump = {
updates: u list
; barriers: (int * int * u list) list
In barriers , first int is token i d of barrier ; second int is
event i d of snapshot ( from " next " )
event id of snapshot (from "next") *)
}
[@@deriving rpc]
let make_list updates =
U.M.fold
(fun key v acc ->
{id= v; v= key |> Interface.Dynamic.rpc_of_id |> Jsonrpc.to_string}
:: acc)
updates []
let make_raw u =
{
updates= make_list u.U.map
; barriers=
List.map
(fun br -> (br.U.bar_id, br.U.event_id, make_list br.U.map_s))
u.U.barriers
}
let make t = Mutex.execute t.m (fun () -> make_raw t.u)
end
end
|
93bc286da4596dc308fe0203843f030170bfee196b903881d669483258818838
|
fakedata-haskell/fakedata
|
DrivingLicense.hs
|
# LANGUAGE TemplateHaskell #
{-# LANGUAGE OverloadedStrings #-}
module Faker.DrivingLicense where
import Data.Text (Text)
import Faker (Fake(..))
import Faker.Provider.DrivingLicense
import Faker.TH
$(generateFakeFieldUnresolveds "drivingLicense" ["usa","alabama"])
$(generateFakeFieldUnresolveds "drivingLicense" ["usa","alaska"])
$(generateFakeFieldUnresolveds "drivingLicense" ["usa","arizona"])
$(generateFakeFieldUnresolveds "drivingLicense" ["usa","arkansas"])
$(generateFakeFieldUnresolveds "drivingLicense" ["usa","california"])
$(generateFakeFieldUnresolveds "drivingLicense" ["usa","colorado"])
$(generateFakeFieldUnresolveds "drivingLicense" ["usa","connecticut"])
$(generateFakeFieldUnresolveds "drivingLicense" ["usa","delaware"])
$(generateFakeFieldUnresolveds "drivingLicense" ["usa","district_of_columbia"])
$(generateFakeFieldUnresolveds "drivingLicense" ["usa","florida"])
$(generateFakeFieldUnresolveds "drivingLicense" ["usa","georgia"])
$(generateFakeFieldUnresolveds "drivingLicense" ["usa","hawaii"])
$(generateFakeFieldUnresolveds "drivingLicense" ["usa","idaho"])
$(generateFakeFieldUnresolveds "drivingLicense" ["usa","illinois"])
$(generateFakeFieldUnresolveds "drivingLicense" ["usa","indiana"])
$(generateFakeFieldUnresolveds "drivingLicense" ["usa","iowa"])
$(generateFakeFieldUnresolveds "drivingLicense" ["usa","kansas"])
$(generateFakeFieldUnresolveds "drivingLicense" ["usa","kentucky"])
$(generateFakeFieldUnresolveds "drivingLicense" ["usa","louisiana"])
$(generateFakeFieldUnresolveds "drivingLicense" ["usa","maine"])
$(generateFakeFieldUnresolveds "drivingLicense" ["usa","maryland"])
$(generateFakeFieldUnresolveds "drivingLicense" ["usa","massachusetts"])
$(generateFakeFieldUnresolveds "drivingLicense" ["usa","michigan"])
$(generateFakeFieldUnresolveds "drivingLicense" ["usa","minnesota"])
$(generateFakeFieldUnresolveds "drivingLicense" ["usa","mississippi"])
$(generateFakeFieldUnresolveds "drivingLicense" ["usa","missouri"])
$(generateFakeFieldUnresolveds "drivingLicense" ["usa","montana"])
$(generateFakeFieldUnresolveds "drivingLicense" ["usa","nebraska"])
$(generateFakeFieldUnresolveds "drivingLicense" ["usa","nevada"])
$(generateFakeFieldUnresolveds "drivingLicense" ["usa","new_hampshire"])
$(generateFakeFieldUnresolveds "drivingLicense" ["usa","new_jersey"])
$(generateFakeFieldUnresolveds "drivingLicense" ["usa","new_mexico"])
$(generateFakeFieldUnresolveds "drivingLicense" ["usa","new_york"])
$(generateFakeFieldUnresolveds "drivingLicense" ["usa","north_carolina"])
| @since 1.0
$(generateFakeFieldUnresolveds "drivingLicense" ["usa","north_dakota"])
$(generateFakeFieldUnresolveds "drivingLicense" ["usa","ohio"])
$(generateFakeFieldUnresolveds "drivingLicense" ["usa","oklahoma"])
$(generateFakeFieldUnresolveds "drivingLicense" ["usa","oregon"])
$(generateFakeFieldUnresolveds "drivingLicense" ["usa","pennsylvania"])
$(generateFakeFieldUnresolveds "drivingLicense" ["usa","rhode_island"])
$(generateFakeFieldUnresolveds "drivingLicense" ["usa","south_carolina"])
$(generateFakeFieldUnresolveds "drivingLicense" ["usa","south_dakota"])
$(generateFakeFieldUnresolveds "drivingLicense" ["usa","tennessee"])
$(generateFakeFieldUnresolveds "drivingLicense" ["usa","texas"])
$(generateFakeFieldUnresolveds "drivingLicense" ["usa","utah"])
$(generateFakeFieldUnresolveds "drivingLicense" ["usa","vermont"])
$(generateFakeFieldUnresolveds "drivingLicense" ["usa","virginia"])
$(generateFakeFieldUnresolveds "drivingLicense" ["usa","washington"])
$(generateFakeFieldUnresolveds "drivingLicense" ["usa","west_virginia"])
$(generateFakeFieldUnresolveds "drivingLicense" ["usa","wisconsin"])
$(generateFakeFieldUnresolveds "drivingLicense" ["usa","wyoming"])
| null |
https://raw.githubusercontent.com/fakedata-haskell/fakedata/ea938c38845b274e28abe7f4e8e342f491e83c89/src/Faker/DrivingLicense.hs
|
haskell
|
# LANGUAGE OverloadedStrings #
|
# LANGUAGE TemplateHaskell #
module Faker.DrivingLicense where
import Data.Text (Text)
import Faker (Fake(..))
import Faker.Provider.DrivingLicense
import Faker.TH
$(generateFakeFieldUnresolveds "drivingLicense" ["usa","alabama"])
$(generateFakeFieldUnresolveds "drivingLicense" ["usa","alaska"])
$(generateFakeFieldUnresolveds "drivingLicense" ["usa","arizona"])
$(generateFakeFieldUnresolveds "drivingLicense" ["usa","arkansas"])
$(generateFakeFieldUnresolveds "drivingLicense" ["usa","california"])
$(generateFakeFieldUnresolveds "drivingLicense" ["usa","colorado"])
$(generateFakeFieldUnresolveds "drivingLicense" ["usa","connecticut"])
$(generateFakeFieldUnresolveds "drivingLicense" ["usa","delaware"])
$(generateFakeFieldUnresolveds "drivingLicense" ["usa","district_of_columbia"])
$(generateFakeFieldUnresolveds "drivingLicense" ["usa","florida"])
$(generateFakeFieldUnresolveds "drivingLicense" ["usa","georgia"])
$(generateFakeFieldUnresolveds "drivingLicense" ["usa","hawaii"])
$(generateFakeFieldUnresolveds "drivingLicense" ["usa","idaho"])
$(generateFakeFieldUnresolveds "drivingLicense" ["usa","illinois"])
$(generateFakeFieldUnresolveds "drivingLicense" ["usa","indiana"])
$(generateFakeFieldUnresolveds "drivingLicense" ["usa","iowa"])
$(generateFakeFieldUnresolveds "drivingLicense" ["usa","kansas"])
$(generateFakeFieldUnresolveds "drivingLicense" ["usa","kentucky"])
$(generateFakeFieldUnresolveds "drivingLicense" ["usa","louisiana"])
$(generateFakeFieldUnresolveds "drivingLicense" ["usa","maine"])
$(generateFakeFieldUnresolveds "drivingLicense" ["usa","maryland"])
$(generateFakeFieldUnresolveds "drivingLicense" ["usa","massachusetts"])
$(generateFakeFieldUnresolveds "drivingLicense" ["usa","michigan"])
$(generateFakeFieldUnresolveds "drivingLicense" ["usa","minnesota"])
$(generateFakeFieldUnresolveds "drivingLicense" ["usa","mississippi"])
$(generateFakeFieldUnresolveds "drivingLicense" ["usa","missouri"])
$(generateFakeFieldUnresolveds "drivingLicense" ["usa","montana"])
$(generateFakeFieldUnresolveds "drivingLicense" ["usa","nebraska"])
$(generateFakeFieldUnresolveds "drivingLicense" ["usa","nevada"])
$(generateFakeFieldUnresolveds "drivingLicense" ["usa","new_hampshire"])
$(generateFakeFieldUnresolveds "drivingLicense" ["usa","new_jersey"])
$(generateFakeFieldUnresolveds "drivingLicense" ["usa","new_mexico"])
$(generateFakeFieldUnresolveds "drivingLicense" ["usa","new_york"])
$(generateFakeFieldUnresolveds "drivingLicense" ["usa","north_carolina"])
| @since 1.0
$(generateFakeFieldUnresolveds "drivingLicense" ["usa","north_dakota"])
$(generateFakeFieldUnresolveds "drivingLicense" ["usa","ohio"])
$(generateFakeFieldUnresolveds "drivingLicense" ["usa","oklahoma"])
$(generateFakeFieldUnresolveds "drivingLicense" ["usa","oregon"])
$(generateFakeFieldUnresolveds "drivingLicense" ["usa","pennsylvania"])
$(generateFakeFieldUnresolveds "drivingLicense" ["usa","rhode_island"])
$(generateFakeFieldUnresolveds "drivingLicense" ["usa","south_carolina"])
$(generateFakeFieldUnresolveds "drivingLicense" ["usa","south_dakota"])
$(generateFakeFieldUnresolveds "drivingLicense" ["usa","tennessee"])
$(generateFakeFieldUnresolveds "drivingLicense" ["usa","texas"])
$(generateFakeFieldUnresolveds "drivingLicense" ["usa","utah"])
$(generateFakeFieldUnresolveds "drivingLicense" ["usa","vermont"])
$(generateFakeFieldUnresolveds "drivingLicense" ["usa","virginia"])
$(generateFakeFieldUnresolveds "drivingLicense" ["usa","washington"])
$(generateFakeFieldUnresolveds "drivingLicense" ["usa","west_virginia"])
$(generateFakeFieldUnresolveds "drivingLicense" ["usa","wisconsin"])
$(generateFakeFieldUnresolveds "drivingLicense" ["usa","wyoming"])
|
4924e5c6a87919531f05a7eab531c240ce94839f797b6bcd7d8c605ec6f7f9f7
|
egao1980/tesseract-capi
|
capi3.lisp
|
This file was automatically generated by SWIG ( ) .
;;; Version 4.0.2
;;;
;;; Do not make changes to this file unless you know what you are doing--modify
the SWIG interface file instead .
(defpackage #:tesseract-capi/v3
(:use #:cl #:cffi))
(in-package :tesseract-capi/v3)
SWIG wrapper code starts here
(cl:defmacro defanonenum (cl:&body enums)
"Converts anonymous enums to defconstants."
`(cl:progn ,@(cl:loop for value in enums
for index = 0 then (cl:1+ index)
when (cl:listp value) do (cl:setf index (cl:second value)
value (cl:first value))
collect `(cl:defconstant ,value ,index))))
(cl:eval-when (:compile-toplevel :load-toplevel)
(cl:unless (cl:fboundp 'swig-lispify)
(cl:defun swig-lispify (name flag cl:&optional (package cl:*package*))
(cl:labels ((helper (lst last rest cl:&aux (c (cl:car lst)))
(cl:cond
((cl:null lst)
rest)
((cl:upper-case-p c)
(helper (cl:cdr lst) 'upper
(cl:case last
((lower digit) (cl:list* c #\- rest))
(cl:t (cl:cons c rest)))))
((cl:lower-case-p c)
(helper (cl:cdr lst) 'lower (cl:cons (cl:char-upcase c) rest)))
((cl:digit-char-p c)
(helper (cl:cdr lst) 'digit
(cl:case last
((upper lower) (cl:list* c #\- rest))
(cl:t (cl:cons c rest)))))
((cl:char-equal c #\_)
(helper (cl:cdr lst) '_ (cl:cons #\- rest)))
(cl:t
(cl:error "Invalid character: ~A" c)))))
(cl:let ((fix (cl:case flag
((constant enumvalue) "+")
(variable "*")
(cl:t ""))))
(cl:intern
(cl:concatenate
'cl:string
fix
(cl:nreverse (helper (cl:concatenate 'cl:list name) cl:nil cl:nil))
fix)
package))))))
SWIG wrapper code ends here
(cl:defconstant MAX_PATH 4096)
(cl:defconstant TRUE 1)
(cl:defconstant FALSE 0)
(cffi:defcenum TessOcrEngineMode
:OEM_TESSERACT_ONLY
:OEM_CUBE_ONLY
:OEM_TESSERACT_CUBE_COMBINED
:OEM_DEFAULT)
(cffi:defcenum TessPageSegMode
:PSM_OSD_ONLY
:PSM_AUTO_OSD
:PSM_AUTO_ONLY
:PSM_AUTO
:PSM_SINGLE_COLUMN
:PSM_SINGLE_BLOCK_VERT_TEXT
:PSM_SINGLE_BLOCK
:PSM_SINGLE_LINE
:PSM_SINGLE_WORD
:PSM_CIRCLE_WORD
:PSM_SINGLE_CHAR
:PSM_SPARSE_TEXT
:PSM_SPARSE_TEXT_OSD
:PSM_COUNT)
(cffi:defcenum TessPageIteratorLevel
:RIL_BLOCK
:RIL_PARA
:RIL_TEXTLINE
:RIL_WORD
:RIL_SYMBOL)
(cffi:defcenum TessPolyBlockType
:PT_UNKNOWN
:PT_FLOWING_TEXT
:PT_HEADING_TEXT
:PT_PULLOUT_TEXT
:PT_EQUATION
:PT_INLINE_EQUATION
:PT_TABLE
:PT_VERTICAL_TEXT
:PT_CAPTION_TEXT
:PT_FLOWING_IMAGE
:PT_HEADING_IMAGE
:PT_PULLOUT_IMAGE
:PT_HORZ_LINE
:PT_VERT_LINE
:PT_NOISE
:PT_COUNT)
(cffi:defcenum TessOrientation
:ORIENTATION_PAGE_UP
:ORIENTATION_PAGE_RIGHT
:ORIENTATION_PAGE_DOWN
:ORIENTATION_PAGE_LEFT)
(cffi:defcenum TessParagraphJustification
:JUSTIFICATION_UNKNOWN
:JUSTIFICATION_LEFT
:JUSTIFICATION_CENTER
:JUSTIFICATION_RIGHT)
(cffi:defcenum TessWritingDirection
:WRITING_DIRECTION_LEFT_TO_RIGHT
:WRITING_DIRECTION_RIGHT_TO_LEFT
:WRITING_DIRECTION_TOP_TO_BOTTOM)
(cffi:defcenum TessTextlineOrder
:TEXTLINE_ORDER_LEFT_TO_RIGHT
:TEXTLINE_ORDER_RIGHT_TO_LEFT
:TEXTLINE_ORDER_TOP_TO_BOTTOM)
(cffi:defcfun ("TessVersion" TessVersion) :string)
(cffi:defcfun ("TessDeleteText" TessDeleteText) :void
(text :string))
(cffi:defcfun ("TessDeleteTextArray" TessDeleteTextArray) :void
(arr :pointer))
(cffi:defcfun ("TessDeleteIntArray" TessDeleteIntArray) :void
(arr :pointer))
(cffi:defcfun ("TessTextRendererCreate" TessTextRendererCreate) :pointer
(outputbase :string))
(cffi:defcfun ("TessHOcrRendererCreate" TessHOcrRendererCreate) :pointer
(outputbase :string))
(cffi:defcfun ("TessHOcrRendererCreate2" TessHOcrRendererCreate2) :pointer
(outputbase :string)
(font_info :int))
(cffi:defcfun ("TessPDFRendererCreate" TessPDFRendererCreate) :pointer
(outputbase :string)
(datadir :string))
(cffi:defcfun ("TessPDFRendererCreateTextonly" TessPDFRendererCreateTextonly) :pointer
(outputbase :string)
(datadir :string)
(textonly :int))
(cffi:defcfun ("TessUnlvRendererCreate" TessUnlvRendererCreate) :pointer
(outputbase :string))
(cffi:defcfun ("TessBoxTextRendererCreate" TessBoxTextRendererCreate) :pointer
(outputbase :string))
(cffi:defcfun ("TessDeleteResultRenderer" TessDeleteResultRenderer) :void
(renderer :pointer))
(cffi:defcfun ("TessResultRendererInsert" TessResultRendererInsert) :void
(renderer :pointer)
(next :pointer))
(cffi:defcfun ("TessResultRendererNext" TessResultRendererNext) :pointer
(renderer :pointer))
(cffi:defcfun ("TessResultRendererBeginDocument" TessResultRendererBeginDocument) :int
(renderer :pointer)
(title :string))
(cffi:defcfun ("TessResultRendererAddImage" TessResultRendererAddImage) :int
(renderer :pointer)
(api :pointer))
(cffi:defcfun ("TessResultRendererEndDocument" TessResultRendererEndDocument) :int
(renderer :pointer))
(cffi:defcfun ("TessResultRendererExtention" TessResultRendererExtention) :string
(renderer :pointer))
(cffi:defcfun ("TessResultRendererTitle" TessResultRendererTitle) :string
(renderer :pointer))
(cffi:defcfun ("TessResultRendererImageNum" TessResultRendererImageNum) :int
(renderer :pointer))
(cffi:defcfun ("TessBaseAPICreate" TessBaseAPICreate) :pointer)
(cffi:defcfun ("TessBaseAPIDelete" TessBaseAPIDelete) :void
(handle :pointer))
(cffi:defcfun ("TessBaseAPIGetOpenCLDevice" TessBaseAPIGetOpenCLDevice) :pointer
(handle :pointer)
(device :pointer))
(cffi:defcfun ("TessBaseAPISetInputName" TessBaseAPISetInputName) :void
(handle :pointer)
(name :string))
(cffi:defcfun ("TessBaseAPIGetInputName" TessBaseAPIGetInputName) :string
(handle :pointer))
(cffi:defcfun ("TessBaseAPISetInputImage" TessBaseAPISetInputImage) :void
(handle :pointer)
(pix :pointer))
(cffi:defcfun ("TessBaseAPIGetInputImage" TessBaseAPIGetInputImage) :pointer
(handle :pointer))
(cffi:defcfun ("TessBaseAPIGetSourceYResolution" TessBaseAPIGetSourceYResolution) :int
(handle :pointer))
(cffi:defcfun ("TessBaseAPIGetDatapath" TessBaseAPIGetDatapath) :string
(handle :pointer))
(cffi:defcfun ("TessBaseAPISetOutputName" TessBaseAPISetOutputName) :void
(handle :pointer)
(name :string))
(cffi:defcfun ("TessBaseAPISetVariable" TessBaseAPISetVariable) :int
(handle :pointer)
(name :string)
(value :string))
(cffi:defcfun ("TessBaseAPISetDebugVariable" TessBaseAPISetDebugVariable) :int
(handle :pointer)
(name :string)
(value :string))
(cffi:defcfun ("TessBaseAPIGetIntVariable" TessBaseAPIGetIntVariable) :int
(handle :pointer)
(name :string)
(value :pointer))
(cffi:defcfun ("TessBaseAPIGetBoolVariable" TessBaseAPIGetBoolVariable) :int
(handle :pointer)
(name :string)
(value :pointer))
(cffi:defcfun ("TessBaseAPIGetDoubleVariable" TessBaseAPIGetDoubleVariable) :int
(handle :pointer)
(name :string)
(value :pointer))
(cffi:defcfun ("TessBaseAPIGetStringVariable" TessBaseAPIGetStringVariable) :string
(handle :pointer)
(name :string))
(cffi:defcfun ("TessBaseAPIPrintVariables" TessBaseAPIPrintVariables) :void
(handle :pointer)
(fp :pointer))
(cffi:defcfun ("TessBaseAPIPrintVariablesToFile" TessBaseAPIPrintVariablesToFile) :int
(handle :pointer)
(filename :string))
(cffi:defcfun ("TessBaseAPIInit1" TessBaseAPIInit1) :int
(handle :pointer)
(datapath :string)
(language :string)
(oem TessOcrEngineMode)
(configs :pointer)
(configs_size :int))
(cffi:defcfun ("TessBaseAPIInit2" TessBaseAPIInit2) :int
(handle :pointer)
(datapath :string)
(language :string)
(oem TessOcrEngineMode))
(cffi:defcfun ("TessBaseAPIInit3" TessBaseAPIInit3) :int
(handle :pointer)
(datapath :string)
(language :string))
(cffi:defcfun ("TessBaseAPIInit4" TessBaseAPIInit4) :int
(handle :pointer)
(datapath :string)
(language :string)
(mode TessOcrEngineMode)
(configs :pointer)
(configs_size :int)
(vars_vec :pointer)
(vars_values :pointer)
(vars_vec_size :pointer)
(set_only_non_debug_params :int))
(cffi:defcfun ("TessBaseAPIGetInitLanguagesAsString" TessBaseAPIGetInitLanguagesAsString) :string
(handle :pointer))
(cffi:defcfun ("TessBaseAPIGetLoadedLanguagesAsVector" TessBaseAPIGetLoadedLanguagesAsVector) :pointer
(handle :pointer))
(cffi:defcfun ("TessBaseAPIGetAvailableLanguagesAsVector" TessBaseAPIGetAvailableLanguagesAsVector) :pointer
(handle :pointer))
(cffi:defcfun ("TessBaseAPIInitLangMod" TessBaseAPIInitLangMod) :int
(handle :pointer)
(datapath :string)
(language :string))
(cffi:defcfun ("TessBaseAPIInitForAnalysePage" TessBaseAPIInitForAnalysePage) :void
(handle :pointer))
(cffi:defcfun ("TessBaseAPIReadConfigFile" TessBaseAPIReadConfigFile) :void
(handle :pointer)
(filename :string))
(cffi:defcfun ("TessBaseAPIReadDebugConfigFile" TessBaseAPIReadDebugConfigFile) :void
(handle :pointer)
(filename :string))
(cffi:defcfun ("TessBaseAPISetPageSegMode" TessBaseAPISetPageSegMode) :void
(handle :pointer)
(mode TessPageSegMode))
(cffi:defcfun ("TessBaseAPIGetPageSegMode" TessBaseAPIGetPageSegMode) TessPageSegMode
(handle :pointer))
(cffi:defcfun ("TessBaseAPIRect" TessBaseAPIRect) :string
(handle :pointer)
(imagedata :pointer)
(bytes_per_pixel :int)
(bytes_per_line :int)
(left :int)
(top :int)
(width :int)
(height :int))
(cffi:defcfun ("TessBaseAPIClearAdaptiveClassifier" TessBaseAPIClearAdaptiveClassifier) :void
(handle :pointer))
(cffi:defcfun ("TessBaseAPISetImage" TessBaseAPISetImage) :void
(handle :pointer)
(imagedata :pointer)
(width :int)
(height :int)
(bytes_per_pixel :int)
(bytes_per_line :int))
(cffi:defcfun ("TessBaseAPISetImage2" TessBaseAPISetImage2) :void
(handle :pointer)
(pix :pointer))
(cffi:defcfun ("TessBaseAPISetSourceResolution" TessBaseAPISetSourceResolution) :void
(handle :pointer)
(ppi :int))
(cffi:defcfun ("TessBaseAPISetRectangle" TessBaseAPISetRectangle) :void
(handle :pointer)
(left :int)
(top :int)
(width :int)
(height :int))
(cffi:defcfun ("TessBaseAPIGetThresholdedImage" TessBaseAPIGetThresholdedImage) :pointer
(handle :pointer))
(cffi:defcfun ("TessBaseAPIGetRegions" TessBaseAPIGetRegions) :pointer
(handle :pointer)
(pixa :pointer))
(cffi:defcfun ("TessBaseAPIGetTextlines" TessBaseAPIGetTextlines) :pointer
(handle :pointer)
(pixa :pointer)
(blockids :pointer))
(cffi:defcfun ("TessBaseAPIGetTextlines1" TessBaseAPIGetTextlines1) :pointer
(handle :pointer)
(raw_image :int)
(raw_padding :int)
(pixa :pointer)
(blockids :pointer)
(paraids :pointer))
(cffi:defcfun ("TessBaseAPIGetStrips" TessBaseAPIGetStrips) :pointer
(handle :pointer)
(pixa :pointer)
(blockids :pointer))
(cffi:defcfun ("TessBaseAPIGetWords" TessBaseAPIGetWords) :pointer
(handle :pointer)
(pixa :pointer))
(cffi:defcfun ("TessBaseAPIGetConnectedComponents" TessBaseAPIGetConnectedComponents) :pointer
(handle :pointer)
(cc :pointer))
(cffi:defcfun ("TessBaseAPIGetComponentImages" TessBaseAPIGetComponentImages) :pointer
(handle :pointer)
(level TessPageIteratorLevel)
(text_only :int)
(pixa :pointer)
(blockids :pointer))
(cffi:defcfun ("TessBaseAPIGetComponentImages1" TessBaseAPIGetComponentImages1) :pointer
(handle :pointer)
(level TessPageIteratorLevel)
(text_only :int)
(raw_image :int)
(raw_padding :int)
(pixa :pointer)
(blockids :pointer)
(paraids :pointer))
(cffi:defcfun ("TessBaseAPIGetThresholdedImageScaleFactor" TessBaseAPIGetThresholdedImageScaleFactor) :int
(handle :pointer))
(cffi:defcfun ("TessBaseAPIDumpPGM" TessBaseAPIDumpPGM) :void
(handle :pointer)
(filename :string))
(cffi:defcfun ("TessBaseAPIAnalyseLayout" TessBaseAPIAnalyseLayout) :pointer
(handle :pointer))
(cffi:defcfun ("TessBaseAPIRecognize" TessBaseAPIRecognize) :int
(handle :pointer)
(monitor :pointer))
(cffi:defcfun ("TessBaseAPIRecognizeForChopTest" TessBaseAPIRecognizeForChopTest) :int
(handle :pointer)
(monitor :pointer))
(cffi:defcfun ("TessBaseAPIProcessPages" TessBaseAPIProcessPages) :int
(handle :pointer)
(filename :string)
(retry_config :string)
(timeout_millisec :int)
(renderer :pointer))
(cffi:defcfun ("TessBaseAPIProcessPage" TessBaseAPIProcessPage) :int
(handle :pointer)
(pix :pointer)
(page_index :int)
(filename :string)
(retry_config :string)
(timeout_millisec :int)
(renderer :pointer))
(cffi:defcfun ("TessBaseAPIGetIterator" TessBaseAPIGetIterator) :pointer
(handle :pointer))
(cffi:defcfun ("TessBaseAPIGetMutableIterator" TessBaseAPIGetMutableIterator) :pointer
(handle :pointer))
(cffi:defcfun ("TessBaseAPIGetUTF8Text" TessBaseAPIGetUTF8Text) :string
(handle :pointer))
(cffi:defcfun ("TessBaseAPIGetHOCRText" TessBaseAPIGetHOCRText) :string
(handle :pointer)
(page_number :int))
(cffi:defcfun ("TessBaseAPIGetBoxText" TessBaseAPIGetBoxText) :string
(handle :pointer)
(page_number :int))
(cffi:defcfun ("TessBaseAPIGetUNLVText" TessBaseAPIGetUNLVText) :string
(handle :pointer))
(cffi:defcfun ("TessBaseAPIMeanTextConf" TessBaseAPIMeanTextConf) :int
(handle :pointer))
(cffi:defcfun ("TessBaseAPIAllWordConfidences" TessBaseAPIAllWordConfidences) :pointer
(handle :pointer))
(cffi:defcfun ("TessBaseAPIAdaptToWordStr" TessBaseAPIAdaptToWordStr) :int
(handle :pointer)
(mode TessPageSegMode)
(wordstr :string))
(cffi:defcfun ("TessBaseAPIClear" TessBaseAPIClear) :void
(handle :pointer))
(cffi:defcfun ("TessBaseAPIEnd" TessBaseAPIEnd) :void
(handle :pointer))
(cffi:defcfun ("TessBaseAPIIsValidWord" TessBaseAPIIsValidWord) :int
(handle :pointer)
(word :string))
(cffi:defcfun ("TessBaseAPIGetTextDirection" TessBaseAPIGetTextDirection) :int
(handle :pointer)
(out_offset :pointer)
(out_slope :pointer))
(cffi:defcfun ("TessBaseAPIGetUnichar" TessBaseAPIGetUnichar) :string
(handle :pointer)
(unichar_id :int))
(cffi:defcfun ("TessBaseAPISetMinOrientationMargin" TessBaseAPISetMinOrientationMargin) :void
(handle :pointer)
(margin :double))
(cffi:defcfun ("TessPageIteratorDelete" TessPageIteratorDelete) :void
(handle :pointer))
(cffi:defcfun ("TessPageIteratorCopy" TessPageIteratorCopy) :pointer
(handle :pointer))
(cffi:defcfun ("TessPageIteratorBegin" TessPageIteratorBegin) :void
(handle :pointer))
(cffi:defcfun ("TessPageIteratorNext" TessPageIteratorNext) :int
(handle :pointer)
(level TessPageIteratorLevel))
(cffi:defcfun ("TessPageIteratorIsAtBeginningOf" TessPageIteratorIsAtBeginningOf) :int
(handle :pointer)
(level TessPageIteratorLevel))
(cffi:defcfun ("TessPageIteratorIsAtFinalElement" TessPageIteratorIsAtFinalElement) :int
(handle :pointer)
(level TessPageIteratorLevel)
(element TessPageIteratorLevel))
(cffi:defcfun ("TessPageIteratorBoundingBox" TessPageIteratorBoundingBox) :int
(handle :pointer)
(level TessPageIteratorLevel)
(left :pointer)
(top :pointer)
(right :pointer)
(bottom :pointer))
(cffi:defcfun ("TessPageIteratorBlockType" TessPageIteratorBlockType) TessPolyBlockType
(handle :pointer))
(cffi:defcfun ("TessPageIteratorGetBinaryImage" TessPageIteratorGetBinaryImage) :pointer
(handle :pointer)
(level TessPageIteratorLevel))
(cffi:defcfun ("TessPageIteratorGetImage" TessPageIteratorGetImage) :pointer
(handle :pointer)
(level TessPageIteratorLevel)
(padding :int)
(original_image :pointer)
(left :pointer)
(top :pointer))
(cffi:defcfun ("TessPageIteratorBaseline" TessPageIteratorBaseline) :int
(handle :pointer)
(level TessPageIteratorLevel)
(x1 :pointer)
(y1 :pointer)
(x2 :pointer)
(y2 :pointer))
(cffi:defcfun ("TessPageIteratorOrientation" TessPageIteratorOrientation) :void
(handle :pointer)
(orientation :pointer)
(writing_direction :pointer)
(textline_order :pointer)
(deskew_angle :pointer))
(cffi:defcfun ("TessPageIteratorParagraphInfo" TessPageIteratorParagraphInfo) :void
(handle :pointer)
(justification :pointer)
(is_list_item :pointer)
(is_crown :pointer)
(first_line_indent :pointer))
(cffi:defcfun ("TessResultIteratorDelete" TessResultIteratorDelete) :void
(handle :pointer))
(cffi:defcfun ("TessResultIteratorCopy" TessResultIteratorCopy) :pointer
(handle :pointer))
(cffi:defcfun ("TessResultIteratorGetPageIterator" TessResultIteratorGetPageIterator) :pointer
(handle :pointer))
(cffi:defcfun ("TessResultIteratorGetPageIteratorConst" TessResultIteratorGetPageIteratorConst) :pointer
(handle :pointer))
(cffi:defcfun ("TessResultIteratorGetChoiceIterator" TessResultIteratorGetChoiceIterator) :pointer
(handle :pointer))
(cffi:defcfun ("TessResultIteratorNext" TessResultIteratorNext) :int
(handle :pointer)
(level TessPageIteratorLevel))
(cffi:defcfun ("TessResultIteratorGetUTF8Text" TessResultIteratorGetUTF8Text) :string
(handle :pointer)
(level TessPageIteratorLevel))
(cffi:defcfun ("TessResultIteratorConfidence" TessResultIteratorConfidence) :float
(handle :pointer)
(level TessPageIteratorLevel))
(cffi:defcfun ("TessResultIteratorWordRecognitionLanguage" TessResultIteratorWordRecognitionLanguage) :string
(handle :pointer))
(cffi:defcfun ("TessResultIteratorWordFontAttributes" TessResultIteratorWordFontAttributes) :string
(handle :pointer)
(is_bold :pointer)
(is_italic :pointer)
(is_underlined :pointer)
(is_monospace :pointer)
(is_serif :pointer)
(is_smallcaps :pointer)
(pointsize :pointer)
(font_id :pointer))
(cffi:defcfun ("TessResultIteratorWordIsFromDictionary" TessResultIteratorWordIsFromDictionary) :int
(handle :pointer))
(cffi:defcfun ("TessResultIteratorWordIsNumeric" TessResultIteratorWordIsNumeric) :int
(handle :pointer))
(cffi:defcfun ("TessResultIteratorSymbolIsSuperscript" TessResultIteratorSymbolIsSuperscript) :int
(handle :pointer))
(cffi:defcfun ("TessResultIteratorSymbolIsSubscript" TessResultIteratorSymbolIsSubscript) :int
(handle :pointer))
(cffi:defcfun ("TessResultIteratorSymbolIsDropcap" TessResultIteratorSymbolIsDropcap) :int
(handle :pointer))
(cffi:defcfun ("TessChoiceIteratorDelete" TessChoiceIteratorDelete) :void
(handle :pointer))
(cffi:defcfun ("TessChoiceIteratorNext" TessChoiceIteratorNext) :int
(handle :pointer))
(cffi:defcfun ("TessChoiceIteratorGetUTF8Text" TessChoiceIteratorGetUTF8Text) :string
(handle :pointer))
(cffi:defcfun ("TessChoiceIteratorConfidence" TessChoiceIteratorConfidence) :float
(handle :pointer))
(let ((pack (find-package :tesseract-capi/v3)))
(do-all-symbols (sym pack) (when (eql (symbol-package sym) pack) (export sym))))
| null |
https://raw.githubusercontent.com/egao1980/tesseract-capi/36ee8ae3aa1170c78ddc75af7368514a86b43f4f/src/capi3.lisp
|
lisp
|
Version 4.0.2
Do not make changes to this file unless you know what you are doing--modify
|
This file was automatically generated by SWIG ( ) .
the SWIG interface file instead .
(defpackage #:tesseract-capi/v3
(:use #:cl #:cffi))
(in-package :tesseract-capi/v3)
SWIG wrapper code starts here
(cl:defmacro defanonenum (cl:&body enums)
"Converts anonymous enums to defconstants."
`(cl:progn ,@(cl:loop for value in enums
for index = 0 then (cl:1+ index)
when (cl:listp value) do (cl:setf index (cl:second value)
value (cl:first value))
collect `(cl:defconstant ,value ,index))))
(cl:eval-when (:compile-toplevel :load-toplevel)
(cl:unless (cl:fboundp 'swig-lispify)
(cl:defun swig-lispify (name flag cl:&optional (package cl:*package*))
(cl:labels ((helper (lst last rest cl:&aux (c (cl:car lst)))
(cl:cond
((cl:null lst)
rest)
((cl:upper-case-p c)
(helper (cl:cdr lst) 'upper
(cl:case last
((lower digit) (cl:list* c #\- rest))
(cl:t (cl:cons c rest)))))
((cl:lower-case-p c)
(helper (cl:cdr lst) 'lower (cl:cons (cl:char-upcase c) rest)))
((cl:digit-char-p c)
(helper (cl:cdr lst) 'digit
(cl:case last
((upper lower) (cl:list* c #\- rest))
(cl:t (cl:cons c rest)))))
((cl:char-equal c #\_)
(helper (cl:cdr lst) '_ (cl:cons #\- rest)))
(cl:t
(cl:error "Invalid character: ~A" c)))))
(cl:let ((fix (cl:case flag
((constant enumvalue) "+")
(variable "*")
(cl:t ""))))
(cl:intern
(cl:concatenate
'cl:string
fix
(cl:nreverse (helper (cl:concatenate 'cl:list name) cl:nil cl:nil))
fix)
package))))))
SWIG wrapper code ends here
(cl:defconstant MAX_PATH 4096)
(cl:defconstant TRUE 1)
(cl:defconstant FALSE 0)
(cffi:defcenum TessOcrEngineMode
:OEM_TESSERACT_ONLY
:OEM_CUBE_ONLY
:OEM_TESSERACT_CUBE_COMBINED
:OEM_DEFAULT)
(cffi:defcenum TessPageSegMode
:PSM_OSD_ONLY
:PSM_AUTO_OSD
:PSM_AUTO_ONLY
:PSM_AUTO
:PSM_SINGLE_COLUMN
:PSM_SINGLE_BLOCK_VERT_TEXT
:PSM_SINGLE_BLOCK
:PSM_SINGLE_LINE
:PSM_SINGLE_WORD
:PSM_CIRCLE_WORD
:PSM_SINGLE_CHAR
:PSM_SPARSE_TEXT
:PSM_SPARSE_TEXT_OSD
:PSM_COUNT)
(cffi:defcenum TessPageIteratorLevel
:RIL_BLOCK
:RIL_PARA
:RIL_TEXTLINE
:RIL_WORD
:RIL_SYMBOL)
(cffi:defcenum TessPolyBlockType
:PT_UNKNOWN
:PT_FLOWING_TEXT
:PT_HEADING_TEXT
:PT_PULLOUT_TEXT
:PT_EQUATION
:PT_INLINE_EQUATION
:PT_TABLE
:PT_VERTICAL_TEXT
:PT_CAPTION_TEXT
:PT_FLOWING_IMAGE
:PT_HEADING_IMAGE
:PT_PULLOUT_IMAGE
:PT_HORZ_LINE
:PT_VERT_LINE
:PT_NOISE
:PT_COUNT)
(cffi:defcenum TessOrientation
:ORIENTATION_PAGE_UP
:ORIENTATION_PAGE_RIGHT
:ORIENTATION_PAGE_DOWN
:ORIENTATION_PAGE_LEFT)
(cffi:defcenum TessParagraphJustification
:JUSTIFICATION_UNKNOWN
:JUSTIFICATION_LEFT
:JUSTIFICATION_CENTER
:JUSTIFICATION_RIGHT)
(cffi:defcenum TessWritingDirection
:WRITING_DIRECTION_LEFT_TO_RIGHT
:WRITING_DIRECTION_RIGHT_TO_LEFT
:WRITING_DIRECTION_TOP_TO_BOTTOM)
(cffi:defcenum TessTextlineOrder
:TEXTLINE_ORDER_LEFT_TO_RIGHT
:TEXTLINE_ORDER_RIGHT_TO_LEFT
:TEXTLINE_ORDER_TOP_TO_BOTTOM)
(cffi:defcfun ("TessVersion" TessVersion) :string)
(cffi:defcfun ("TessDeleteText" TessDeleteText) :void
(text :string))
(cffi:defcfun ("TessDeleteTextArray" TessDeleteTextArray) :void
(arr :pointer))
(cffi:defcfun ("TessDeleteIntArray" TessDeleteIntArray) :void
(arr :pointer))
(cffi:defcfun ("TessTextRendererCreate" TessTextRendererCreate) :pointer
(outputbase :string))
(cffi:defcfun ("TessHOcrRendererCreate" TessHOcrRendererCreate) :pointer
(outputbase :string))
(cffi:defcfun ("TessHOcrRendererCreate2" TessHOcrRendererCreate2) :pointer
(outputbase :string)
(font_info :int))
(cffi:defcfun ("TessPDFRendererCreate" TessPDFRendererCreate) :pointer
(outputbase :string)
(datadir :string))
(cffi:defcfun ("TessPDFRendererCreateTextonly" TessPDFRendererCreateTextonly) :pointer
(outputbase :string)
(datadir :string)
(textonly :int))
(cffi:defcfun ("TessUnlvRendererCreate" TessUnlvRendererCreate) :pointer
(outputbase :string))
(cffi:defcfun ("TessBoxTextRendererCreate" TessBoxTextRendererCreate) :pointer
(outputbase :string))
(cffi:defcfun ("TessDeleteResultRenderer" TessDeleteResultRenderer) :void
(renderer :pointer))
(cffi:defcfun ("TessResultRendererInsert" TessResultRendererInsert) :void
(renderer :pointer)
(next :pointer))
(cffi:defcfun ("TessResultRendererNext" TessResultRendererNext) :pointer
(renderer :pointer))
(cffi:defcfun ("TessResultRendererBeginDocument" TessResultRendererBeginDocument) :int
(renderer :pointer)
(title :string))
(cffi:defcfun ("TessResultRendererAddImage" TessResultRendererAddImage) :int
(renderer :pointer)
(api :pointer))
(cffi:defcfun ("TessResultRendererEndDocument" TessResultRendererEndDocument) :int
(renderer :pointer))
(cffi:defcfun ("TessResultRendererExtention" TessResultRendererExtention) :string
(renderer :pointer))
(cffi:defcfun ("TessResultRendererTitle" TessResultRendererTitle) :string
(renderer :pointer))
(cffi:defcfun ("TessResultRendererImageNum" TessResultRendererImageNum) :int
(renderer :pointer))
(cffi:defcfun ("TessBaseAPICreate" TessBaseAPICreate) :pointer)
(cffi:defcfun ("TessBaseAPIDelete" TessBaseAPIDelete) :void
(handle :pointer))
(cffi:defcfun ("TessBaseAPIGetOpenCLDevice" TessBaseAPIGetOpenCLDevice) :pointer
(handle :pointer)
(device :pointer))
(cffi:defcfun ("TessBaseAPISetInputName" TessBaseAPISetInputName) :void
(handle :pointer)
(name :string))
(cffi:defcfun ("TessBaseAPIGetInputName" TessBaseAPIGetInputName) :string
(handle :pointer))
(cffi:defcfun ("TessBaseAPISetInputImage" TessBaseAPISetInputImage) :void
(handle :pointer)
(pix :pointer))
(cffi:defcfun ("TessBaseAPIGetInputImage" TessBaseAPIGetInputImage) :pointer
(handle :pointer))
(cffi:defcfun ("TessBaseAPIGetSourceYResolution" TessBaseAPIGetSourceYResolution) :int
(handle :pointer))
(cffi:defcfun ("TessBaseAPIGetDatapath" TessBaseAPIGetDatapath) :string
(handle :pointer))
(cffi:defcfun ("TessBaseAPISetOutputName" TessBaseAPISetOutputName) :void
(handle :pointer)
(name :string))
(cffi:defcfun ("TessBaseAPISetVariable" TessBaseAPISetVariable) :int
(handle :pointer)
(name :string)
(value :string))
(cffi:defcfun ("TessBaseAPISetDebugVariable" TessBaseAPISetDebugVariable) :int
(handle :pointer)
(name :string)
(value :string))
(cffi:defcfun ("TessBaseAPIGetIntVariable" TessBaseAPIGetIntVariable) :int
(handle :pointer)
(name :string)
(value :pointer))
(cffi:defcfun ("TessBaseAPIGetBoolVariable" TessBaseAPIGetBoolVariable) :int
(handle :pointer)
(name :string)
(value :pointer))
(cffi:defcfun ("TessBaseAPIGetDoubleVariable" TessBaseAPIGetDoubleVariable) :int
(handle :pointer)
(name :string)
(value :pointer))
(cffi:defcfun ("TessBaseAPIGetStringVariable" TessBaseAPIGetStringVariable) :string
(handle :pointer)
(name :string))
(cffi:defcfun ("TessBaseAPIPrintVariables" TessBaseAPIPrintVariables) :void
(handle :pointer)
(fp :pointer))
(cffi:defcfun ("TessBaseAPIPrintVariablesToFile" TessBaseAPIPrintVariablesToFile) :int
(handle :pointer)
(filename :string))
(cffi:defcfun ("TessBaseAPIInit1" TessBaseAPIInit1) :int
(handle :pointer)
(datapath :string)
(language :string)
(oem TessOcrEngineMode)
(configs :pointer)
(configs_size :int))
(cffi:defcfun ("TessBaseAPIInit2" TessBaseAPIInit2) :int
(handle :pointer)
(datapath :string)
(language :string)
(oem TessOcrEngineMode))
(cffi:defcfun ("TessBaseAPIInit3" TessBaseAPIInit3) :int
(handle :pointer)
(datapath :string)
(language :string))
(cffi:defcfun ("TessBaseAPIInit4" TessBaseAPIInit4) :int
(handle :pointer)
(datapath :string)
(language :string)
(mode TessOcrEngineMode)
(configs :pointer)
(configs_size :int)
(vars_vec :pointer)
(vars_values :pointer)
(vars_vec_size :pointer)
(set_only_non_debug_params :int))
(cffi:defcfun ("TessBaseAPIGetInitLanguagesAsString" TessBaseAPIGetInitLanguagesAsString) :string
(handle :pointer))
(cffi:defcfun ("TessBaseAPIGetLoadedLanguagesAsVector" TessBaseAPIGetLoadedLanguagesAsVector) :pointer
(handle :pointer))
(cffi:defcfun ("TessBaseAPIGetAvailableLanguagesAsVector" TessBaseAPIGetAvailableLanguagesAsVector) :pointer
(handle :pointer))
(cffi:defcfun ("TessBaseAPIInitLangMod" TessBaseAPIInitLangMod) :int
(handle :pointer)
(datapath :string)
(language :string))
(cffi:defcfun ("TessBaseAPIInitForAnalysePage" TessBaseAPIInitForAnalysePage) :void
(handle :pointer))
(cffi:defcfun ("TessBaseAPIReadConfigFile" TessBaseAPIReadConfigFile) :void
(handle :pointer)
(filename :string))
(cffi:defcfun ("TessBaseAPIReadDebugConfigFile" TessBaseAPIReadDebugConfigFile) :void
(handle :pointer)
(filename :string))
(cffi:defcfun ("TessBaseAPISetPageSegMode" TessBaseAPISetPageSegMode) :void
(handle :pointer)
(mode TessPageSegMode))
(cffi:defcfun ("TessBaseAPIGetPageSegMode" TessBaseAPIGetPageSegMode) TessPageSegMode
(handle :pointer))
(cffi:defcfun ("TessBaseAPIRect" TessBaseAPIRect) :string
(handle :pointer)
(imagedata :pointer)
(bytes_per_pixel :int)
(bytes_per_line :int)
(left :int)
(top :int)
(width :int)
(height :int))
(cffi:defcfun ("TessBaseAPIClearAdaptiveClassifier" TessBaseAPIClearAdaptiveClassifier) :void
(handle :pointer))
(cffi:defcfun ("TessBaseAPISetImage" TessBaseAPISetImage) :void
(handle :pointer)
(imagedata :pointer)
(width :int)
(height :int)
(bytes_per_pixel :int)
(bytes_per_line :int))
(cffi:defcfun ("TessBaseAPISetImage2" TessBaseAPISetImage2) :void
(handle :pointer)
(pix :pointer))
(cffi:defcfun ("TessBaseAPISetSourceResolution" TessBaseAPISetSourceResolution) :void
(handle :pointer)
(ppi :int))
(cffi:defcfun ("TessBaseAPISetRectangle" TessBaseAPISetRectangle) :void
(handle :pointer)
(left :int)
(top :int)
(width :int)
(height :int))
(cffi:defcfun ("TessBaseAPIGetThresholdedImage" TessBaseAPIGetThresholdedImage) :pointer
(handle :pointer))
(cffi:defcfun ("TessBaseAPIGetRegions" TessBaseAPIGetRegions) :pointer
(handle :pointer)
(pixa :pointer))
(cffi:defcfun ("TessBaseAPIGetTextlines" TessBaseAPIGetTextlines) :pointer
(handle :pointer)
(pixa :pointer)
(blockids :pointer))
(cffi:defcfun ("TessBaseAPIGetTextlines1" TessBaseAPIGetTextlines1) :pointer
(handle :pointer)
(raw_image :int)
(raw_padding :int)
(pixa :pointer)
(blockids :pointer)
(paraids :pointer))
(cffi:defcfun ("TessBaseAPIGetStrips" TessBaseAPIGetStrips) :pointer
(handle :pointer)
(pixa :pointer)
(blockids :pointer))
(cffi:defcfun ("TessBaseAPIGetWords" TessBaseAPIGetWords) :pointer
(handle :pointer)
(pixa :pointer))
(cffi:defcfun ("TessBaseAPIGetConnectedComponents" TessBaseAPIGetConnectedComponents) :pointer
(handle :pointer)
(cc :pointer))
(cffi:defcfun ("TessBaseAPIGetComponentImages" TessBaseAPIGetComponentImages) :pointer
(handle :pointer)
(level TessPageIteratorLevel)
(text_only :int)
(pixa :pointer)
(blockids :pointer))
(cffi:defcfun ("TessBaseAPIGetComponentImages1" TessBaseAPIGetComponentImages1) :pointer
(handle :pointer)
(level TessPageIteratorLevel)
(text_only :int)
(raw_image :int)
(raw_padding :int)
(pixa :pointer)
(blockids :pointer)
(paraids :pointer))
(cffi:defcfun ("TessBaseAPIGetThresholdedImageScaleFactor" TessBaseAPIGetThresholdedImageScaleFactor) :int
(handle :pointer))
(cffi:defcfun ("TessBaseAPIDumpPGM" TessBaseAPIDumpPGM) :void
(handle :pointer)
(filename :string))
(cffi:defcfun ("TessBaseAPIAnalyseLayout" TessBaseAPIAnalyseLayout) :pointer
(handle :pointer))
(cffi:defcfun ("TessBaseAPIRecognize" TessBaseAPIRecognize) :int
(handle :pointer)
(monitor :pointer))
(cffi:defcfun ("TessBaseAPIRecognizeForChopTest" TessBaseAPIRecognizeForChopTest) :int
(handle :pointer)
(monitor :pointer))
(cffi:defcfun ("TessBaseAPIProcessPages" TessBaseAPIProcessPages) :int
(handle :pointer)
(filename :string)
(retry_config :string)
(timeout_millisec :int)
(renderer :pointer))
(cffi:defcfun ("TessBaseAPIProcessPage" TessBaseAPIProcessPage) :int
(handle :pointer)
(pix :pointer)
(page_index :int)
(filename :string)
(retry_config :string)
(timeout_millisec :int)
(renderer :pointer))
(cffi:defcfun ("TessBaseAPIGetIterator" TessBaseAPIGetIterator) :pointer
(handle :pointer))
(cffi:defcfun ("TessBaseAPIGetMutableIterator" TessBaseAPIGetMutableIterator) :pointer
(handle :pointer))
(cffi:defcfun ("TessBaseAPIGetUTF8Text" TessBaseAPIGetUTF8Text) :string
(handle :pointer))
(cffi:defcfun ("TessBaseAPIGetHOCRText" TessBaseAPIGetHOCRText) :string
(handle :pointer)
(page_number :int))
(cffi:defcfun ("TessBaseAPIGetBoxText" TessBaseAPIGetBoxText) :string
(handle :pointer)
(page_number :int))
(cffi:defcfun ("TessBaseAPIGetUNLVText" TessBaseAPIGetUNLVText) :string
(handle :pointer))
(cffi:defcfun ("TessBaseAPIMeanTextConf" TessBaseAPIMeanTextConf) :int
(handle :pointer))
(cffi:defcfun ("TessBaseAPIAllWordConfidences" TessBaseAPIAllWordConfidences) :pointer
(handle :pointer))
(cffi:defcfun ("TessBaseAPIAdaptToWordStr" TessBaseAPIAdaptToWordStr) :int
(handle :pointer)
(mode TessPageSegMode)
(wordstr :string))
(cffi:defcfun ("TessBaseAPIClear" TessBaseAPIClear) :void
(handle :pointer))
(cffi:defcfun ("TessBaseAPIEnd" TessBaseAPIEnd) :void
(handle :pointer))
(cffi:defcfun ("TessBaseAPIIsValidWord" TessBaseAPIIsValidWord) :int
(handle :pointer)
(word :string))
(cffi:defcfun ("TessBaseAPIGetTextDirection" TessBaseAPIGetTextDirection) :int
(handle :pointer)
(out_offset :pointer)
(out_slope :pointer))
(cffi:defcfun ("TessBaseAPIGetUnichar" TessBaseAPIGetUnichar) :string
(handle :pointer)
(unichar_id :int))
(cffi:defcfun ("TessBaseAPISetMinOrientationMargin" TessBaseAPISetMinOrientationMargin) :void
(handle :pointer)
(margin :double))
(cffi:defcfun ("TessPageIteratorDelete" TessPageIteratorDelete) :void
(handle :pointer))
(cffi:defcfun ("TessPageIteratorCopy" TessPageIteratorCopy) :pointer
(handle :pointer))
(cffi:defcfun ("TessPageIteratorBegin" TessPageIteratorBegin) :void
(handle :pointer))
(cffi:defcfun ("TessPageIteratorNext" TessPageIteratorNext) :int
(handle :pointer)
(level TessPageIteratorLevel))
(cffi:defcfun ("TessPageIteratorIsAtBeginningOf" TessPageIteratorIsAtBeginningOf) :int
(handle :pointer)
(level TessPageIteratorLevel))
(cffi:defcfun ("TessPageIteratorIsAtFinalElement" TessPageIteratorIsAtFinalElement) :int
(handle :pointer)
(level TessPageIteratorLevel)
(element TessPageIteratorLevel))
(cffi:defcfun ("TessPageIteratorBoundingBox" TessPageIteratorBoundingBox) :int
(handle :pointer)
(level TessPageIteratorLevel)
(left :pointer)
(top :pointer)
(right :pointer)
(bottom :pointer))
(cffi:defcfun ("TessPageIteratorBlockType" TessPageIteratorBlockType) TessPolyBlockType
(handle :pointer))
(cffi:defcfun ("TessPageIteratorGetBinaryImage" TessPageIteratorGetBinaryImage) :pointer
(handle :pointer)
(level TessPageIteratorLevel))
(cffi:defcfun ("TessPageIteratorGetImage" TessPageIteratorGetImage) :pointer
(handle :pointer)
(level TessPageIteratorLevel)
(padding :int)
(original_image :pointer)
(left :pointer)
(top :pointer))
(cffi:defcfun ("TessPageIteratorBaseline" TessPageIteratorBaseline) :int
(handle :pointer)
(level TessPageIteratorLevel)
(x1 :pointer)
(y1 :pointer)
(x2 :pointer)
(y2 :pointer))
(cffi:defcfun ("TessPageIteratorOrientation" TessPageIteratorOrientation) :void
(handle :pointer)
(orientation :pointer)
(writing_direction :pointer)
(textline_order :pointer)
(deskew_angle :pointer))
(cffi:defcfun ("TessPageIteratorParagraphInfo" TessPageIteratorParagraphInfo) :void
(handle :pointer)
(justification :pointer)
(is_list_item :pointer)
(is_crown :pointer)
(first_line_indent :pointer))
(cffi:defcfun ("TessResultIteratorDelete" TessResultIteratorDelete) :void
(handle :pointer))
(cffi:defcfun ("TessResultIteratorCopy" TessResultIteratorCopy) :pointer
(handle :pointer))
(cffi:defcfun ("TessResultIteratorGetPageIterator" TessResultIteratorGetPageIterator) :pointer
(handle :pointer))
(cffi:defcfun ("TessResultIteratorGetPageIteratorConst" TessResultIteratorGetPageIteratorConst) :pointer
(handle :pointer))
(cffi:defcfun ("TessResultIteratorGetChoiceIterator" TessResultIteratorGetChoiceIterator) :pointer
(handle :pointer))
(cffi:defcfun ("TessResultIteratorNext" TessResultIteratorNext) :int
(handle :pointer)
(level TessPageIteratorLevel))
(cffi:defcfun ("TessResultIteratorGetUTF8Text" TessResultIteratorGetUTF8Text) :string
(handle :pointer)
(level TessPageIteratorLevel))
(cffi:defcfun ("TessResultIteratorConfidence" TessResultIteratorConfidence) :float
(handle :pointer)
(level TessPageIteratorLevel))
(cffi:defcfun ("TessResultIteratorWordRecognitionLanguage" TessResultIteratorWordRecognitionLanguage) :string
(handle :pointer))
(cffi:defcfun ("TessResultIteratorWordFontAttributes" TessResultIteratorWordFontAttributes) :string
(handle :pointer)
(is_bold :pointer)
(is_italic :pointer)
(is_underlined :pointer)
(is_monospace :pointer)
(is_serif :pointer)
(is_smallcaps :pointer)
(pointsize :pointer)
(font_id :pointer))
(cffi:defcfun ("TessResultIteratorWordIsFromDictionary" TessResultIteratorWordIsFromDictionary) :int
(handle :pointer))
(cffi:defcfun ("TessResultIteratorWordIsNumeric" TessResultIteratorWordIsNumeric) :int
(handle :pointer))
(cffi:defcfun ("TessResultIteratorSymbolIsSuperscript" TessResultIteratorSymbolIsSuperscript) :int
(handle :pointer))
(cffi:defcfun ("TessResultIteratorSymbolIsSubscript" TessResultIteratorSymbolIsSubscript) :int
(handle :pointer))
(cffi:defcfun ("TessResultIteratorSymbolIsDropcap" TessResultIteratorSymbolIsDropcap) :int
(handle :pointer))
(cffi:defcfun ("TessChoiceIteratorDelete" TessChoiceIteratorDelete) :void
(handle :pointer))
(cffi:defcfun ("TessChoiceIteratorNext" TessChoiceIteratorNext) :int
(handle :pointer))
(cffi:defcfun ("TessChoiceIteratorGetUTF8Text" TessChoiceIteratorGetUTF8Text) :string
(handle :pointer))
(cffi:defcfun ("TessChoiceIteratorConfidence" TessChoiceIteratorConfidence) :float
(handle :pointer))
(let ((pack (find-package :tesseract-capi/v3)))
(do-all-symbols (sym pack) (when (eql (symbol-package sym) pack) (export sym))))
|
4064ad1f201e8249f952ea0a821cf3656a2a9c1701003795bb02df59d86819c7
|
ygmpkk/house
|
Int.hs
|
{-# OPTIONS -fno-implicit-prelude #-}
-----------------------------------------------------------------------------
-- |
-- Module : GHC.Int
Copyright : ( c ) The University of Glasgow 1997 - 2002
-- License : see libraries/base/LICENSE
--
-- Maintainer :
-- Stability : internal
Portability : non - portable ( GHC Extensions )
--
The sized integral datatypes , ' Int8 ' , ' Int16 ' , ' Int32 ' , and ' Int64 ' .
--
-----------------------------------------------------------------------------
#include "MachDeps.h"
module GHC.Int (
Int8(..), Int16(..), Int32(..), Int64(..))
where
import Data.Bits
import {-# SOURCE #-} GHC.Err
import GHC.Base
import GHC.Enum
import GHC.Num
import GHC.Real
import GHC.Read
import GHC.Arr
import GHC.Word
import GHC.Show
------------------------------------------------------------------------
-- type Int8
------------------------------------------------------------------------
Int8 is represented in the same way as Int . Operations may assume
-- and must ensure that it holds only values from its logical range.
data Int8 = I8# Int# deriving (Eq, Ord)
^ 8 - bit signed integer type
instance Show Int8 where
showsPrec p x = showsPrec p (fromIntegral x :: Int)
instance Num Int8 where
(I8# x#) + (I8# y#) = I8# (narrow8Int# (x# +# y#))
(I8# x#) - (I8# y#) = I8# (narrow8Int# (x# -# y#))
(I8# x#) * (I8# y#) = I8# (narrow8Int# (x# *# y#))
negate (I8# x#) = I8# (narrow8Int# (negateInt# x#))
abs x | x >= 0 = x
| otherwise = negate x
signum x | x > 0 = 1
signum 0 = 0
signum _ = -1
fromInteger (S# i#) = I8# (narrow8Int# i#)
fromInteger (J# s# d#) = I8# (narrow8Int# (integer2Int# s# d#))
instance Real Int8 where
toRational x = toInteger x % 1
instance Enum Int8 where
succ x
| x /= maxBound = x + 1
| otherwise = succError "Int8"
pred x
| x /= minBound = x - 1
| otherwise = predError "Int8"
toEnum i@(I# i#)
| i >= fromIntegral (minBound::Int8) && i <= fromIntegral (maxBound::Int8)
= I8# i#
| otherwise = toEnumError "Int8" i (minBound::Int8, maxBound::Int8)
fromEnum (I8# x#) = I# x#
enumFrom = boundedEnumFrom
enumFromThen = boundedEnumFromThen
instance Integral Int8 where
quot x@(I8# x#) y@(I8# y#)
| y /= 0 = I8# (narrow8Int# (x# `quotInt#` y#))
| otherwise = divZeroError
rem x@(I8# x#) y@(I8# y#)
| y /= 0 = I8# (narrow8Int# (x# `remInt#` y#))
| otherwise = divZeroError
div x@(I8# x#) y@(I8# y#)
| y /= 0 = I8# (narrow8Int# (x# `divInt#` y#))
| otherwise = divZeroError
mod x@(I8# x#) y@(I8# y#)
| y /= 0 = I8# (narrow8Int# (x# `modInt#` y#))
| otherwise = divZeroError
quotRem x@(I8# x#) y@(I8# y#)
| y /= 0 = (I8# (narrow8Int# (x# `quotInt#` y#)),
I8# (narrow8Int# (x# `remInt#` y#)))
| otherwise = divZeroError
divMod x@(I8# x#) y@(I8# y#)
| y /= 0 = (I8# (narrow8Int# (x# `divInt#` y#)),
I8# (narrow8Int# (x# `modInt#` y#)))
| otherwise = divZeroError
toInteger (I8# x#) = S# x#
instance Bounded Int8 where
minBound = -0x80
maxBound = 0x7F
instance Ix Int8 where
range (m,n) = [m..n]
unsafeIndex b@(m,_) i = fromIntegral (i - m)
inRange (m,n) i = m <= i && i <= n
unsafeRangeSize b@(_l,h) = unsafeIndex b h + 1
instance Read Int8 where
readsPrec p s = [(fromIntegral (x::Int), r) | (x, r) <- readsPrec p s]
instance Bits Int8 where
(I8# x#) .&. (I8# y#) = I8# (word2Int# (int2Word# x# `and#` int2Word# y#))
(I8# x#) .|. (I8# y#) = I8# (word2Int# (int2Word# x# `or#` int2Word# y#))
(I8# x#) `xor` (I8# y#) = I8# (word2Int# (int2Word# x# `xor#` int2Word# y#))
complement (I8# x#) = I8# (word2Int# (int2Word# x# `xor#` int2Word# (-1#)))
(I8# x#) `shift` (I# i#)
| i# >=# 0# = I8# (narrow8Int# (x# `iShiftL#` i#))
| otherwise = I8# (x# `iShiftRA#` negateInt# i#)
(I8# x#) `rotate` (I# i#)
| i'# ==# 0#
= I8# x#
| otherwise
= I8# (narrow8Int# (word2Int# ((x'# `shiftL#` i'#) `or#`
(x'# `shiftRL#` (8# -# i'#)))))
where
x'# = narrow8Word# (int2Word# x#)
i'# = word2Int# (int2Word# i# `and#` int2Word# 7#)
bitSize _ = 8
isSigned _ = True
# RULES
" fromIntegral / Int8->Int8 " fromIntegral = i d : : Int8 - > Int8
" fromIntegral / a->Int8 " fromIntegral = \x - > case fromIntegral x of I # x # - > I8 # ( narrow8Int # x # )
" fromIntegral / Int8->a " fromIntegral = \(I8 # x # ) - > fromIntegral ( I # x # )
#
"fromIntegral/Int8->Int8" fromIntegral = id :: Int8 -> Int8
"fromIntegral/a->Int8" fromIntegral = \x -> case fromIntegral x of I# x# -> I8# (narrow8Int# x#)
"fromIntegral/Int8->a" fromIntegral = \(I8# x#) -> fromIntegral (I# x#)
#-}
------------------------------------------------------------------------
-- type Int16
------------------------------------------------------------------------
Int16 is represented in the same way as Int . Operations may assume
-- and must ensure that it holds only values from its logical range.
data Int16 = I16# Int# deriving (Eq, Ord)
^ 16 - bit signed integer type
instance Show Int16 where
showsPrec p x = showsPrec p (fromIntegral x :: Int)
instance Num Int16 where
(I16# x#) + (I16# y#) = I16# (narrow16Int# (x# +# y#))
(I16# x#) - (I16# y#) = I16# (narrow16Int# (x# -# y#))
(I16# x#) * (I16# y#) = I16# (narrow16Int# (x# *# y#))
negate (I16# x#) = I16# (narrow16Int# (negateInt# x#))
abs x | x >= 0 = x
| otherwise = negate x
signum x | x > 0 = 1
signum 0 = 0
signum _ = -1
fromInteger (S# i#) = I16# (narrow16Int# i#)
fromInteger (J# s# d#) = I16# (narrow16Int# (integer2Int# s# d#))
instance Real Int16 where
toRational x = toInteger x % 1
instance Enum Int16 where
succ x
| x /= maxBound = x + 1
| otherwise = succError "Int16"
pred x
| x /= minBound = x - 1
| otherwise = predError "Int16"
toEnum i@(I# i#)
| i >= fromIntegral (minBound::Int16) && i <= fromIntegral (maxBound::Int16)
= I16# i#
| otherwise = toEnumError "Int16" i (minBound::Int16, maxBound::Int16)
fromEnum (I16# x#) = I# x#
enumFrom = boundedEnumFrom
enumFromThen = boundedEnumFromThen
instance Integral Int16 where
quot x@(I16# x#) y@(I16# y#)
| y /= 0 = I16# (narrow16Int# (x# `quotInt#` y#))
| otherwise = divZeroError
rem x@(I16# x#) y@(I16# y#)
| y /= 0 = I16# (narrow16Int# (x# `remInt#` y#))
| otherwise = divZeroError
div x@(I16# x#) y@(I16# y#)
| y /= 0 = I16# (narrow16Int# (x# `divInt#` y#))
| otherwise = divZeroError
mod x@(I16# x#) y@(I16# y#)
| y /= 0 = I16# (narrow16Int# (x# `modInt#` y#))
| otherwise = divZeroError
quotRem x@(I16# x#) y@(I16# y#)
| y /= 0 = (I16# (narrow16Int# (x# `quotInt#` y#)),
I16# (narrow16Int# (x# `remInt#` y#)))
| otherwise = divZeroError
divMod x@(I16# x#) y@(I16# y#)
| y /= 0 = (I16# (narrow16Int# (x# `divInt#` y#)),
I16# (narrow16Int# (x# `modInt#` y#)))
| otherwise = divZeroError
toInteger (I16# x#) = S# x#
instance Bounded Int16 where
minBound = -0x8000
maxBound = 0x7FFF
instance Ix Int16 where
range (m,n) = [m..n]
unsafeIndex b@(m,_) i = fromIntegral (i - m)
inRange (m,n) i = m <= i && i <= n
unsafeRangeSize b@(_l,h) = unsafeIndex b h + 1
instance Read Int16 where
readsPrec p s = [(fromIntegral (x::Int), r) | (x, r) <- readsPrec p s]
instance Bits Int16 where
(I16# x#) .&. (I16# y#) = I16# (word2Int# (int2Word# x# `and#` int2Word# y#))
(I16# x#) .|. (I16# y#) = I16# (word2Int# (int2Word# x# `or#` int2Word# y#))
(I16# x#) `xor` (I16# y#) = I16# (word2Int# (int2Word# x# `xor#` int2Word# y#))
complement (I16# x#) = I16# (word2Int# (int2Word# x# `xor#` int2Word# (-1#)))
(I16# x#) `shift` (I# i#)
| i# >=# 0# = I16# (narrow16Int# (x# `iShiftL#` i#))
| otherwise = I16# (x# `iShiftRA#` negateInt# i#)
(I16# x#) `rotate` (I# i#)
| i'# ==# 0#
= I16# x#
| otherwise
= I16# (narrow16Int# (word2Int# ((x'# `shiftL#` i'#) `or#`
(x'# `shiftRL#` (16# -# i'#)))))
where
x'# = narrow16Word# (int2Word# x#)
i'# = word2Int# (int2Word# i# `and#` int2Word# 15#)
bitSize _ = 16
isSigned _ = True
# RULES
" fromIntegral / Word8->Int16 " fromIntegral = \(W8 # x # ) - > I16 # ( word2Int # x # )
" fromIntegral / Int8->Int16 " fromIntegral = \(I8 # x # ) - > I16 # x #
" fromIntegral / Int16->Int16 " fromIntegral = i d : : Int16 - > Int16
" fromIntegral / a->Int16 " fromIntegral = \x - > case fromIntegral x of I # x # - > I16 # ( narrow16Int # x # )
" fromIntegral / Int16->a " fromIntegral = \(I16 # x # ) - > fromIntegral ( I # x # )
#
"fromIntegral/Word8->Int16" fromIntegral = \(W8# x#) -> I16# (word2Int# x#)
"fromIntegral/Int8->Int16" fromIntegral = \(I8# x#) -> I16# x#
"fromIntegral/Int16->Int16" fromIntegral = id :: Int16 -> Int16
"fromIntegral/a->Int16" fromIntegral = \x -> case fromIntegral x of I# x# -> I16# (narrow16Int# x#)
"fromIntegral/Int16->a" fromIntegral = \(I16# x#) -> fromIntegral (I# x#)
#-}
------------------------------------------------------------------------
type Int32
------------------------------------------------------------------------
#if WORD_SIZE_IN_BITS < 32
data Int32 = I32# Int32#
^ 32 - bit signed integer type
instance Eq Int32 where
(I32# x#) == (I32# y#) = x# `eqInt32#` y#
(I32# x#) /= (I32# y#) = x# `neInt32#` y#
instance Ord Int32 where
(I32# x#) < (I32# y#) = x# `ltInt32#` y#
(I32# x#) <= (I32# y#) = x# `leInt32#` y#
(I32# x#) > (I32# y#) = x# `gtInt32#` y#
(I32# x#) >= (I32# y#) = x# `geInt32#` y#
instance Show Int32 where
showsPrec p x = showsPrec p (toInteger x)
instance Num Int32 where
(I32# x#) + (I32# y#) = I32# (x# `plusInt32#` y#)
(I32# x#) - (I32# y#) = I32# (x# `minusInt32#` y#)
(I32# x#) * (I32# y#) = I32# (x# `timesInt32#` y#)
negate (I32# x#) = I32# (negateInt32# x#)
abs x | x >= 0 = x
| otherwise = negate x
signum x | x > 0 = 1
signum 0 = 0
signum _ = -1
fromInteger (S# i#) = I32# (intToInt32# i#)
fromInteger (J# s# d#) = I32# (integerToInt32# s# d#)
instance Enum Int32 where
succ x
| x /= maxBound = x + 1
| otherwise = succError "Int32"
pred x
| x /= minBound = x - 1
| otherwise = predError "Int32"
toEnum (I# i#) = I32# (intToInt32# i#)
fromEnum x@(I32# x#)
| x >= fromIntegral (minBound::Int) && x <= fromIntegral (maxBound::Int)
= I# (int32ToInt# x#)
| otherwise = fromEnumError "Int32" x
enumFrom = integralEnumFrom
enumFromThen = integralEnumFromThen
enumFromTo = integralEnumFromTo
enumFromThenTo = integralEnumFromThenTo
instance Integral Int32 where
quot x@(I32# x#) y@(I32# y#)
| y /= 0 = I32# (x# `quotInt32#` y#)
| otherwise = divZeroError
rem x@(I32# x#) y@(I32# y#)
| y /= 0 = I32# (x# `remInt32#` y#)
| otherwise = divZeroError
div x@(I32# x#) y@(I32# y#)
| y /= 0 = I32# (x# `divInt32#` y#)
| otherwise = divZeroError
mod x@(I32# x#) y@(I32# y#)
| y /= 0 = I32# (x# `modInt32#` y#)
| otherwise = divZeroError
quotRem x@(I32# x#) y@(I32# y#)
| y /= 0 = (I32# (x# `quotInt32#` y#), I32# (x# `remInt32#` y#))
| otherwise = divZeroError
divMod x@(I32# x#) y@(I32# y#)
| y /= 0 = (I32# (x# `divInt32#` y#), I32# (x# `modInt32#` y#))
| otherwise = divZeroError
toInteger x@(I32# x#)
| x >= fromIntegral (minBound::Int) && x <= fromIntegral (maxBound::Int)
= S# (int32ToInt# x#)
| otherwise = case int32ToInteger# x# of (# s, d #) -> J# s d
divInt32#, modInt32# :: Int32# -> Int32# -> Int32#
x# `divInt32#` y#
| (x# `gtInt32#` intToInt32# 0#) && (y# `ltInt32#` intToInt32# 0#)
= ((x# `minusInt32#` y#) `minusInt32#` intToInt32# 1#) `quotInt32#` y#
| (x# `ltInt32#` intToInt32# 0#) && (y# `gtInt32#` intToInt32# 0#)
= ((x# `minusInt32#` y#) `plusInt32#` intToInt32# 1#) `quotInt32#` y#
| otherwise = x# `quotInt32#` y#
x# `modInt32#` y#
| (x# `gtInt32#` intToInt32# 0#) && (y# `ltInt32#` intToInt32# 0#) ||
(x# `ltInt32#` intToInt32# 0#) && (y# `gtInt32#` intToInt32# 0#)
= if r# `neInt32#` intToInt32# 0# then r# `plusInt32#` y# else intToInt32# 0#
| otherwise = r#
where
r# = x# `remInt32#` y#
instance Read Int32 where
readsPrec p s = [(fromInteger x, r) | (x, r) <- readsPrec p s]
instance Bits Int32 where
(I32# x#) .&. (I32# y#) = I32# (word32ToInt32# (int32ToWord32# x# `and32#` int32ToWord32# y#))
(I32# x#) .|. (I32# y#) = I32# (word32ToInt32# (int32ToWord32# x# `or32#` int32ToWord32# y#))
(I32# x#) `xor` (I32# y#) = I32# (word32ToInt32# (int32ToWord32# x# `xor32#` int32ToWord32# y#))
complement (I32# x#) = I32# (word32ToInt32# (not32# (int32ToWord32# x#)))
(I32# x#) `shift` (I# i#)
| i# >=# 0# = I32# (x# `iShiftL32#` i#)
| otherwise = I32# (x# `iShiftRA32#` negateInt# i#)
(I32# x#) `rotate` (I# i#)
| i'# ==# 0#
= I32# x#
| otherwise
= I32# (word32ToInt32# ((x'# `shiftL32#` i'#) `or32#`
(x'# `shiftRL32#` (32# -# i'#))))
where
x'# = int32ToWord32# x#
i'# = word2Int# (int2Word# i# `and#` int2Word# 31#)
bitSize _ = 32
isSigned _ = True
foreign import "stg_eqInt32" unsafe eqInt32# :: Int32# -> Int32# -> Bool
foreign import "stg_neInt32" unsafe neInt32# :: Int32# -> Int32# -> Bool
foreign import "stg_ltInt32" unsafe ltInt32# :: Int32# -> Int32# -> Bool
foreign import "stg_leInt32" unsafe leInt32# :: Int32# -> Int32# -> Bool
foreign import "stg_gtInt32" unsafe gtInt32# :: Int32# -> Int32# -> Bool
foreign import "stg_geInt32" unsafe geInt32# :: Int32# -> Int32# -> Bool
foreign import "stg_plusInt32" unsafe plusInt32# :: Int32# -> Int32# -> Int32#
foreign import "stg_minusInt32" unsafe minusInt32# :: Int32# -> Int32# -> Int32#
foreign import "stg_timesInt32" unsafe timesInt32# :: Int32# -> Int32# -> Int32#
foreign import "stg_negateInt32" unsafe negateInt32# :: Int32# -> Int32#
foreign import "stg_quotInt32" unsafe quotInt32# :: Int32# -> Int32# -> Int32#
foreign import "stg_remInt32" unsafe remInt32# :: Int32# -> Int32# -> Int32#
foreign import "stg_intToInt32" unsafe intToInt32# :: Int# -> Int32#
foreign import "stg_int32ToInt" unsafe int32ToInt# :: Int32# -> Int#
foreign import "stg_wordToWord32" unsafe wordToWord32# :: Word# -> Word32#
foreign import "stg_int32ToWord32" unsafe int32ToWord32# :: Int32# -> Word32#
foreign import "stg_word32ToInt32" unsafe word32ToInt32# :: Word32# -> Int32#
foreign import "stg_and32" unsafe and32# :: Word32# -> Word32# -> Word32#
foreign import "stg_or32" unsafe or32# :: Word32# -> Word32# -> Word32#
foreign import "stg_xor32" unsafe xor32# :: Word32# -> Word32# -> Word32#
foreign import "stg_not32" unsafe not32# :: Word32# -> Word32#
foreign import "stg_iShiftL32" unsafe iShiftL32# :: Int32# -> Int# -> Int32#
foreign import "stg_iShiftRA32" unsafe iShiftRA32# :: Int32# -> Int# -> Int32#
foreign import "stg_shiftL32" unsafe shiftL32# :: Word32# -> Int# -> Word32#
foreign import "stg_shiftRL32" unsafe shiftRL32# :: Word32# -> Int# -> Word32#
# RULES
" fromIntegral / Int->Int32 " fromIntegral = \(I # x # ) - > I32 # ( intToInt32 # x # )
" fromIntegral / " fromIntegral = \(W # x # ) - > I32 # ( word32ToInt32 # ( wordToWord32 # x # ) )
" fromIntegral / Word32->Int32 " fromIntegral = \(W32 # x # ) - > I32 # ( word32ToInt32 # x # )
" fromIntegral / Int32->Int " fromIntegral = \(I32 # x # ) - > I # ( int32ToInt # x # )
" fromIntegral / Int32->Word " fromIntegral = \(I32 # x # ) - > W # ( int2Word # ( int32ToInt # x # ) )
" fromIntegral / Int32->Word32 " fromIntegral = \(I32 # x # ) - > W32 # ( int32ToWord32 # x # )
" fromIntegral / Int32->Int32 " fromIntegral = i d : : Int32 - > Int32
#
"fromIntegral/Int->Int32" fromIntegral = \(I# x#) -> I32# (intToInt32# x#)
"fromIntegral/Word->Int32" fromIntegral = \(W# x#) -> I32# (word32ToInt32# (wordToWord32# x#))
"fromIntegral/Word32->Int32" fromIntegral = \(W32# x#) -> I32# (word32ToInt32# x#)
"fromIntegral/Int32->Int" fromIntegral = \(I32# x#) -> I# (int32ToInt# x#)
"fromIntegral/Int32->Word" fromIntegral = \(I32# x#) -> W# (int2Word# (int32ToInt# x#))
"fromIntegral/Int32->Word32" fromIntegral = \(I32# x#) -> W32# (int32ToWord32# x#)
"fromIntegral/Int32->Int32" fromIntegral = id :: Int32 -> Int32
#-}
#else
Int32 is represented in the same way as Int .
#if WORD_SIZE_IN_BITS > 32
Operations may assume and must ensure that it holds only values
-- from its logical range.
#endif
data Int32 = I32# Int# deriving (Eq, Ord)
^ 32 - bit signed integer type
instance Show Int32 where
showsPrec p x = showsPrec p (fromIntegral x :: Int)
instance Num Int32 where
(I32# x#) + (I32# y#) = I32# (narrow32Int# (x# +# y#))
(I32# x#) - (I32# y#) = I32# (narrow32Int# (x# -# y#))
(I32# x#) * (I32# y#) = I32# (narrow32Int# (x# *# y#))
negate (I32# x#) = I32# (narrow32Int# (negateInt# x#))
abs x | x >= 0 = x
| otherwise = negate x
signum x | x > 0 = 1
signum 0 = 0
signum _ = -1
fromInteger (S# i#) = I32# (narrow32Int# i#)
fromInteger (J# s# d#) = I32# (narrow32Int# (integer2Int# s# d#))
instance Enum Int32 where
succ x
| x /= maxBound = x + 1
| otherwise = succError "Int32"
pred x
| x /= minBound = x - 1
| otherwise = predError "Int32"
#if WORD_SIZE_IN_BITS == 32
toEnum (I# i#) = I32# i#
#else
toEnum i@(I# i#)
| i >= fromIntegral (minBound::Int32) && i <= fromIntegral (maxBound::Int32)
= I32# i#
| otherwise = toEnumError "Int32" i (minBound::Int32, maxBound::Int32)
#endif
fromEnum (I32# x#) = I# x#
enumFrom = boundedEnumFrom
enumFromThen = boundedEnumFromThen
instance Integral Int32 where
quot x@(I32# x#) y@(I32# y#)
| y /= 0 = I32# (narrow32Int# (x# `quotInt#` y#))
| otherwise = divZeroError
rem x@(I32# x#) y@(I32# y#)
| y /= 0 = I32# (narrow32Int# (x# `remInt#` y#))
| otherwise = divZeroError
div x@(I32# x#) y@(I32# y#)
| y /= 0 = I32# (narrow32Int# (x# `divInt#` y#))
| otherwise = divZeroError
mod x@(I32# x#) y@(I32# y#)
| y /= 0 = I32# (narrow32Int# (x# `modInt#` y#))
| otherwise = divZeroError
quotRem x@(I32# x#) y@(I32# y#)
| y /= 0 = (I32# (narrow32Int# (x# `quotInt#` y#)),
I32# (narrow32Int# (x# `remInt#` y#)))
| otherwise = divZeroError
divMod x@(I32# x#) y@(I32# y#)
| y /= 0 = (I32# (narrow32Int# (x# `divInt#` y#)),
I32# (narrow32Int# (x# `modInt#` y#)))
| otherwise = divZeroError
toInteger (I32# x#) = S# x#
instance Read Int32 where
readsPrec p s = [(fromIntegral (x::Int), r) | (x, r) <- readsPrec p s]
instance Bits Int32 where
(I32# x#) .&. (I32# y#) = I32# (word2Int# (int2Word# x# `and#` int2Word# y#))
(I32# x#) .|. (I32# y#) = I32# (word2Int# (int2Word# x# `or#` int2Word# y#))
(I32# x#) `xor` (I32# y#) = I32# (word2Int# (int2Word# x# `xor#` int2Word# y#))
complement (I32# x#) = I32# (word2Int# (int2Word# x# `xor#` int2Word# (-1#)))
(I32# x#) `shift` (I# i#)
| i# >=# 0# = I32# (narrow32Int# (x# `iShiftL#` i#))
| otherwise = I32# (x# `iShiftRA#` negateInt# i#)
(I32# x#) `rotate` (I# i#)
| i'# ==# 0#
= I32# x#
| otherwise
= I32# (narrow32Int# (word2Int# ((x'# `shiftL#` i'#) `or#`
(x'# `shiftRL#` (32# -# i'#)))))
where
x'# = narrow32Word# (int2Word# x#)
i'# = word2Int# (int2Word# i# `and#` int2Word# 31#)
bitSize _ = 32
isSigned _ = True
# RULES
" fromIntegral / Word8->Int32 " fromIntegral = \(W8 # x # ) - > I32 # ( word2Int # x # )
" fromIntegral / Word16->Int32 " fromIntegral = \(W16 # x # ) - > I32 # ( word2Int # x # )
" fromIntegral / Int8->Int32 " fromIntegral = \(I8 # x # ) - > I32 # x #
" fromIntegral / Int16->Int32 " fromIntegral = \(I16 # x # ) - > I32 # x #
" fromIntegral / Int32->Int32 " fromIntegral = i d : : Int32 - > Int32
" fromIntegral / a->Int32 " fromIntegral = \x - > case fromIntegral x of I # x # - > I32 # ( narrow32Int # x # )
" fromIntegral / Int32->a " fromIntegral = \(I32 # x # ) - > fromIntegral ( I # x # )
#
"fromIntegral/Word8->Int32" fromIntegral = \(W8# x#) -> I32# (word2Int# x#)
"fromIntegral/Word16->Int32" fromIntegral = \(W16# x#) -> I32# (word2Int# x#)
"fromIntegral/Int8->Int32" fromIntegral = \(I8# x#) -> I32# x#
"fromIntegral/Int16->Int32" fromIntegral = \(I16# x#) -> I32# x#
"fromIntegral/Int32->Int32" fromIntegral = id :: Int32 -> Int32
"fromIntegral/a->Int32" fromIntegral = \x -> case fromIntegral x of I# x# -> I32# (narrow32Int# x#)
"fromIntegral/Int32->a" fromIntegral = \(I32# x#) -> fromIntegral (I# x#)
#-}
#endif
instance Real Int32 where
toRational x = toInteger x % 1
instance Bounded Int32 where
minBound = -0x80000000
maxBound = 0x7FFFFFFF
instance Ix Int32 where
range (m,n) = [m..n]
unsafeIndex b@(m,_) i = fromIntegral (i - m)
inRange (m,n) i = m <= i && i <= n
unsafeRangeSize b@(_l,h) = unsafeIndex b h + 1
------------------------------------------------------------------------
type Int64
------------------------------------------------------------------------
#if WORD_SIZE_IN_BITS < 64
data Int64 = I64# Int64#
^ 64 - bit signed integer type
instance Eq Int64 where
(I64# x#) == (I64# y#) = x# `eqInt64#` y#
(I64# x#) /= (I64# y#) = x# `neInt64#` y#
instance Ord Int64 where
(I64# x#) < (I64# y#) = x# `ltInt64#` y#
(I64# x#) <= (I64# y#) = x# `leInt64#` y#
(I64# x#) > (I64# y#) = x# `gtInt64#` y#
(I64# x#) >= (I64# y#) = x# `geInt64#` y#
instance Show Int64 where
showsPrec p x = showsPrec p (toInteger x)
instance Num Int64 where
(I64# x#) + (I64# y#) = I64# (x# `plusInt64#` y#)
(I64# x#) - (I64# y#) = I64# (x# `minusInt64#` y#)
(I64# x#) * (I64# y#) = I64# (x# `timesInt64#` y#)
negate (I64# x#) = I64# (negateInt64# x#)
abs x | x >= 0 = x
| otherwise = negate x
signum x | x > 0 = 1
signum 0 = 0
signum _ = -1
fromInteger (S# i#) = I64# (intToInt64# i#)
fromInteger (J# s# d#) = I64# (integerToInt64# s# d#)
instance Enum Int64 where
succ x
| x /= maxBound = x + 1
| otherwise = succError "Int64"
pred x
| x /= minBound = x - 1
| otherwise = predError "Int64"
toEnum (I# i#) = I64# (intToInt64# i#)
fromEnum x@(I64# x#)
| x >= fromIntegral (minBound::Int) && x <= fromIntegral (maxBound::Int)
= I# (int64ToInt# x#)
| otherwise = fromEnumError "Int64" x
enumFrom = integralEnumFrom
enumFromThen = integralEnumFromThen
enumFromTo = integralEnumFromTo
enumFromThenTo = integralEnumFromThenTo
instance Integral Int64 where
quot x@(I64# x#) y@(I64# y#)
| y /= 0 = I64# (x# `quotInt64#` y#)
| otherwise = divZeroError
rem x@(I64# x#) y@(I64# y#)
| y /= 0 = I64# (x# `remInt64#` y#)
| otherwise = divZeroError
div x@(I64# x#) y@(I64# y#)
| y /= 0 = I64# (x# `divInt64#` y#)
| otherwise = divZeroError
mod x@(I64# x#) y@(I64# y#)
| y /= 0 = I64# (x# `modInt64#` y#)
| otherwise = divZeroError
quotRem x@(I64# x#) y@(I64# y#)
| y /= 0 = (I64# (x# `quotInt64#` y#), I64# (x# `remInt64#` y#))
| otherwise = divZeroError
divMod x@(I64# x#) y@(I64# y#)
| y /= 0 = (I64# (x# `divInt64#` y#), I64# (x# `modInt64#` y#))
| otherwise = divZeroError
toInteger x@(I64# x#)
| x >= fromIntegral (minBound::Int) && x <= fromIntegral (maxBound::Int)
= S# (int64ToInt# x#)
| otherwise = case int64ToInteger# x# of (# s, d #) -> J# s d
divInt64#, modInt64# :: Int64# -> Int64# -> Int64#
x# `divInt64#` y#
| (x# `gtInt64#` intToInt64# 0#) && (y# `ltInt64#` intToInt64# 0#)
= ((x# `minusInt64#` y#) `minusInt64#` intToInt64# 1#) `quotInt64#` y#
| (x# `ltInt64#` intToInt64# 0#) && (y# `gtInt64#` intToInt64# 0#)
= ((x# `minusInt64#` y#) `plusInt64#` intToInt64# 1#) `quotInt64#` y#
| otherwise = x# `quotInt64#` y#
x# `modInt64#` y#
| (x# `gtInt64#` intToInt64# 0#) && (y# `ltInt64#` intToInt64# 0#) ||
(x# `ltInt64#` intToInt64# 0#) && (y# `gtInt64#` intToInt64# 0#)
= if r# `neInt64#` intToInt64# 0# then r# `plusInt64#` y# else intToInt64# 0#
| otherwise = r#
where
r# = x# `remInt64#` y#
instance Read Int64 where
readsPrec p s = [(fromInteger x, r) | (x, r) <- readsPrec p s]
instance Bits Int64 where
(I64# x#) .&. (I64# y#) = I64# (word64ToInt64# (int64ToWord64# x# `and64#` int64ToWord64# y#))
(I64# x#) .|. (I64# y#) = I64# (word64ToInt64# (int64ToWord64# x# `or64#` int64ToWord64# y#))
(I64# x#) `xor` (I64# y#) = I64# (word64ToInt64# (int64ToWord64# x# `xor64#` int64ToWord64# y#))
complement (I64# x#) = I64# (word64ToInt64# (not64# (int64ToWord64# x#)))
(I64# x#) `shift` (I# i#)
| i# >=# 0# = I64# (x# `iShiftL64#` i#)
| otherwise = I64# (x# `iShiftRA64#` negateInt# i#)
(I64# x#) `rotate` (I# i#)
| i'# ==# 0#
= I64# x#
| otherwise
= I64# (word64ToInt64# ((x'# `uncheckedShiftL64#` i'#) `or64#`
(x'# `uncheckedShiftRL64#` (64# -# i'#))))
where
x'# = int64ToWord64# x#
i'# = word2Int# (int2Word# i# `and#` int2Word# 63#)
bitSize _ = 64
isSigned _ = True
give the 64 - bit shift operations the same treatment as the 32 - bit
ones ( see ) , namely we wrap them in tests to catch the
cases when we 're shifting more than 64 bits to avoid unspecified
-- behaviour in the C shift operations.
iShiftL64#, iShiftRA64# :: Int64# -> Int# -> Int64#
a `iShiftL64#` b | b >=# 64# = intToInt64# 0#
| otherwise = a `uncheckedIShiftL64#` b
a `iShiftRA64#` b | b >=# 64# = if a `ltInt64#` (intToInt64# 0#)
then intToInt64# (-1#)
else intToInt64# 0#
| otherwise = a `uncheckedIShiftRA64#` b
foreign import ccall unsafe "stg_eqInt64" eqInt64# :: Int64# -> Int64# -> Bool
foreign import ccall unsafe "stg_neInt64" neInt64# :: Int64# -> Int64# -> Bool
foreign import ccall unsafe "stg_ltInt64" ltInt64# :: Int64# -> Int64# -> Bool
foreign import ccall unsafe "stg_leInt64" leInt64# :: Int64# -> Int64# -> Bool
foreign import ccall unsafe "stg_gtInt64" gtInt64# :: Int64# -> Int64# -> Bool
foreign import ccall unsafe "stg_geInt64" geInt64# :: Int64# -> Int64# -> Bool
foreign import ccall unsafe "stg_plusInt64" plusInt64# :: Int64# -> Int64# -> Int64#
foreign import ccall unsafe "stg_minusInt64" minusInt64# :: Int64# -> Int64# -> Int64#
foreign import ccall unsafe "stg_timesInt64" timesInt64# :: Int64# -> Int64# -> Int64#
foreign import ccall unsafe "stg_negateInt64" negateInt64# :: Int64# -> Int64#
foreign import ccall unsafe "stg_quotInt64" quotInt64# :: Int64# -> Int64# -> Int64#
foreign import ccall unsafe "stg_remInt64" remInt64# :: Int64# -> Int64# -> Int64#
foreign import ccall unsafe "stg_intToInt64" intToInt64# :: Int# -> Int64#
foreign import ccall unsafe "stg_int64ToInt" int64ToInt# :: Int64# -> Int#
foreign import ccall unsafe "stg_wordToWord64" wordToWord64# :: Word# -> Word64#
foreign import ccall unsafe "stg_int64ToWord64" int64ToWord64# :: Int64# -> Word64#
foreign import ccall unsafe "stg_word64ToInt64" word64ToInt64# :: Word64# -> Int64#
foreign import ccall unsafe "stg_and64" and64# :: Word64# -> Word64# -> Word64#
foreign import ccall unsafe "stg_or64" or64# :: Word64# -> Word64# -> Word64#
foreign import ccall unsafe "stg_xor64" xor64# :: Word64# -> Word64# -> Word64#
foreign import ccall unsafe "stg_not64" not64# :: Word64# -> Word64#
foreign import ccall unsafe "stg_uncheckedShiftL64" uncheckedShiftL64# :: Word64# -> Int# -> Word64#
foreign import ccall unsafe "stg_uncheckedShiftRL64" uncheckedShiftRL64# :: Word64# -> Int# -> Word64#
foreign import ccall unsafe "stg_uncheckedIShiftL64" uncheckedIShiftL64# :: Int64# -> Int# -> Int64#
foreign import ccall unsafe "stg_uncheckedIShiftRA64" uncheckedIShiftRA64# :: Int64# -> Int# -> Int64#
foreign import ccall unsafe "stg_integerToInt64" integerToInt64# :: Int# -> ByteArray# -> Int64#
# RULES
" fromIntegral / Int->Int64 " fromIntegral = \(I # x # ) - > I64 # ( intToInt64 # x # )
" fromIntegral / Word->Int64 " fromIntegral = \(W # x # ) - > I64 # ( word64ToInt64 # ( wordToWord64 # x # ) )
" fromIntegral / Word64->Int64 " fromIntegral = \(W64 # x # ) - > I64 # ( word64ToInt64 # x # )
" fromIntegral / Int64->Int " fromIntegral = \(I64 # x # ) - > I # ( int64ToInt # x # )
" fromIntegral / Int64->Word " fromIntegral = \(I64 # x # ) - > W # ( int2Word # ( int64ToInt # x # ) )
" fromIntegral / Int64->Word64 " fromIntegral = \(I64 # x # ) - > W64 # ( int64ToWord64 # x # )
" fromIntegral / Int64->Int64 " fromIntegral = i d : : Int64 - > Int64
#
"fromIntegral/Int->Int64" fromIntegral = \(I# x#) -> I64# (intToInt64# x#)
"fromIntegral/Word->Int64" fromIntegral = \(W# x#) -> I64# (word64ToInt64# (wordToWord64# x#))
"fromIntegral/Word64->Int64" fromIntegral = \(W64# x#) -> I64# (word64ToInt64# x#)
"fromIntegral/Int64->Int" fromIntegral = \(I64# x#) -> I# (int64ToInt# x#)
"fromIntegral/Int64->Word" fromIntegral = \(I64# x#) -> W# (int2Word# (int64ToInt# x#))
"fromIntegral/Int64->Word64" fromIntegral = \(I64# x#) -> W64# (int64ToWord64# x#)
"fromIntegral/Int64->Int64" fromIntegral = id :: Int64 -> Int64
#-}
#else
Int64 is represented in the same way as Int .
Operations may assume and must ensure that it holds only values
-- from its logical range.
data Int64 = I64# Int# deriving (Eq, Ord)
^ 64 - bit signed integer type
instance Show Int64 where
showsPrec p x = showsPrec p (fromIntegral x :: Int)
instance Num Int64 where
(I64# x#) + (I64# y#) = I64# (x# +# y#)
(I64# x#) - (I64# y#) = I64# (x# -# y#)
(I64# x#) * (I64# y#) = I64# (x# *# y#)
negate (I64# x#) = I64# (negateInt# x#)
abs x | x >= 0 = x
| otherwise = negate x
signum x | x > 0 = 1
signum 0 = 0
signum _ = -1
fromInteger (S# i#) = I64# i#
fromInteger (J# s# d#) = I64# (integer2Int# s# d#)
instance Enum Int64 where
succ x
| x /= maxBound = x + 1
| otherwise = succError "Int64"
pred x
| x /= minBound = x - 1
| otherwise = predError "Int64"
toEnum (I# i#) = I64# i#
fromEnum (I64# x#) = I# x#
enumFrom = boundedEnumFrom
enumFromThen = boundedEnumFromThen
instance Integral Int64 where
quot x@(I64# x#) y@(I64# y#)
| y /= 0 = I64# (x# `quotInt#` y#)
| otherwise = divZeroError
rem x@(I64# x#) y@(I64# y#)
| y /= 0 = I64# (x# `remInt#` y#)
| otherwise = divZeroError
div x@(I64# x#) y@(I64# y#)
| y /= 0 = I64# (x# `divInt#` y#)
| otherwise = divZeroError
mod x@(I64# x#) y@(I64# y#)
| y /= 0 = I64# (x# `modInt#` y#)
| otherwise = divZeroError
quotRem x@(I64# x#) y@(I64# y#)
| y /= 0 = (I64# (x# `quotInt#` y#), I64# (x# `remInt#` y#))
| otherwise = divZeroError
divMod x@(I64# x#) y@(I64# y#)
| y /= 0 = (I64# (x# `divInt#` y#), I64# (x# `modInt#` y#))
| otherwise = divZeroError
toInteger (I64# x#) = S# x#
instance Read Int64 where
readsPrec p s = [(fromIntegral (x::Int), r) | (x, r) <- readsPrec p s]
instance Bits Int64 where
(I64# x#) .&. (I64# y#) = I64# (word2Int# (int2Word# x# `and#` int2Word# y#))
(I64# x#) .|. (I64# y#) = I64# (word2Int# (int2Word# x# `or#` int2Word# y#))
(I64# x#) `xor` (I64# y#) = I64# (word2Int# (int2Word# x# `xor#` int2Word# y#))
complement (I64# x#) = I64# (word2Int# (int2Word# x# `xor#` int2Word# (-1#)))
(I64# x#) `shift` (I# i#)
| i# >=# 0# = I64# (x# `iShiftL#` i#)
| otherwise = I64# (x# `iShiftRA#` negateInt# i#)
(I64# x#) `rotate` (I# i#)
| i'# ==# 0#
= I64# x#
| otherwise
= I64# (word2Int# ((x'# `shiftL#` i'#) `or#`
(x'# `shiftRL#` (64# -# i'#))))
where
x'# = int2Word# x#
i'# = word2Int# (int2Word# i# `and#` int2Word# 63#)
bitSize _ = 64
isSigned _ = True
# RULES
" fromIntegral / a->Int64 " fromIntegral = \x - > case fromIntegral x of I # x # - > I64 # x #
" fromIntegral / Int64->a " fromIntegral = \(I64 # x # ) - > fromIntegral ( I # x # )
#
"fromIntegral/a->Int64" fromIntegral = \x -> case fromIntegral x of I# x# -> I64# x#
"fromIntegral/Int64->a" fromIntegral = \(I64# x#) -> fromIntegral (I# x#)
#-}
#endif
instance Real Int64 where
toRational x = toInteger x % 1
instance Bounded Int64 where
minBound = -0x8000000000000000
maxBound = 0x7FFFFFFFFFFFFFFF
instance Ix Int64 where
range (m,n) = [m..n]
unsafeIndex b@(m,_) i = fromIntegral (i - m)
inRange (m,n) i = m <= i && i <= n
unsafeRangeSize b@(_l,h) = unsafeIndex b h + 1
| null |
https://raw.githubusercontent.com/ygmpkk/house/1ed0eed82139869e85e3c5532f2b579cf2566fa2/ghc-6.2/libraries/base/GHC/Int.hs
|
haskell
|
# OPTIONS -fno-implicit-prelude #
---------------------------------------------------------------------------
|
Module : GHC.Int
License : see libraries/base/LICENSE
Maintainer :
Stability : internal
---------------------------------------------------------------------------
# SOURCE #
----------------------------------------------------------------------
type Int8
----------------------------------------------------------------------
and must ensure that it holds only values from its logical range.
----------------------------------------------------------------------
type Int16
----------------------------------------------------------------------
and must ensure that it holds only values from its logical range.
----------------------------------------------------------------------
----------------------------------------------------------------------
from its logical range.
----------------------------------------------------------------------
----------------------------------------------------------------------
behaviour in the C shift operations.
from its logical range.
|
Copyright : ( c ) The University of Glasgow 1997 - 2002
Portability : non - portable ( GHC Extensions )
The sized integral datatypes , ' Int8 ' , ' Int16 ' , ' Int32 ' , and ' Int64 ' .
#include "MachDeps.h"
module GHC.Int (
Int8(..), Int16(..), Int32(..), Int64(..))
where
import Data.Bits
import GHC.Base
import GHC.Enum
import GHC.Num
import GHC.Real
import GHC.Read
import GHC.Arr
import GHC.Word
import GHC.Show
Int8 is represented in the same way as Int . Operations may assume
data Int8 = I8# Int# deriving (Eq, Ord)
^ 8 - bit signed integer type
instance Show Int8 where
showsPrec p x = showsPrec p (fromIntegral x :: Int)
instance Num Int8 where
(I8# x#) + (I8# y#) = I8# (narrow8Int# (x# +# y#))
(I8# x#) - (I8# y#) = I8# (narrow8Int# (x# -# y#))
(I8# x#) * (I8# y#) = I8# (narrow8Int# (x# *# y#))
negate (I8# x#) = I8# (narrow8Int# (negateInt# x#))
abs x | x >= 0 = x
| otherwise = negate x
signum x | x > 0 = 1
signum 0 = 0
signum _ = -1
fromInteger (S# i#) = I8# (narrow8Int# i#)
fromInteger (J# s# d#) = I8# (narrow8Int# (integer2Int# s# d#))
instance Real Int8 where
toRational x = toInteger x % 1
instance Enum Int8 where
succ x
| x /= maxBound = x + 1
| otherwise = succError "Int8"
pred x
| x /= minBound = x - 1
| otherwise = predError "Int8"
toEnum i@(I# i#)
| i >= fromIntegral (minBound::Int8) && i <= fromIntegral (maxBound::Int8)
= I8# i#
| otherwise = toEnumError "Int8" i (minBound::Int8, maxBound::Int8)
fromEnum (I8# x#) = I# x#
enumFrom = boundedEnumFrom
enumFromThen = boundedEnumFromThen
instance Integral Int8 where
quot x@(I8# x#) y@(I8# y#)
| y /= 0 = I8# (narrow8Int# (x# `quotInt#` y#))
| otherwise = divZeroError
rem x@(I8# x#) y@(I8# y#)
| y /= 0 = I8# (narrow8Int# (x# `remInt#` y#))
| otherwise = divZeroError
div x@(I8# x#) y@(I8# y#)
| y /= 0 = I8# (narrow8Int# (x# `divInt#` y#))
| otherwise = divZeroError
mod x@(I8# x#) y@(I8# y#)
| y /= 0 = I8# (narrow8Int# (x# `modInt#` y#))
| otherwise = divZeroError
quotRem x@(I8# x#) y@(I8# y#)
| y /= 0 = (I8# (narrow8Int# (x# `quotInt#` y#)),
I8# (narrow8Int# (x# `remInt#` y#)))
| otherwise = divZeroError
divMod x@(I8# x#) y@(I8# y#)
| y /= 0 = (I8# (narrow8Int# (x# `divInt#` y#)),
I8# (narrow8Int# (x# `modInt#` y#)))
| otherwise = divZeroError
toInteger (I8# x#) = S# x#
instance Bounded Int8 where
minBound = -0x80
maxBound = 0x7F
instance Ix Int8 where
range (m,n) = [m..n]
unsafeIndex b@(m,_) i = fromIntegral (i - m)
inRange (m,n) i = m <= i && i <= n
unsafeRangeSize b@(_l,h) = unsafeIndex b h + 1
instance Read Int8 where
readsPrec p s = [(fromIntegral (x::Int), r) | (x, r) <- readsPrec p s]
instance Bits Int8 where
(I8# x#) .&. (I8# y#) = I8# (word2Int# (int2Word# x# `and#` int2Word# y#))
(I8# x#) .|. (I8# y#) = I8# (word2Int# (int2Word# x# `or#` int2Word# y#))
(I8# x#) `xor` (I8# y#) = I8# (word2Int# (int2Word# x# `xor#` int2Word# y#))
complement (I8# x#) = I8# (word2Int# (int2Word# x# `xor#` int2Word# (-1#)))
(I8# x#) `shift` (I# i#)
| i# >=# 0# = I8# (narrow8Int# (x# `iShiftL#` i#))
| otherwise = I8# (x# `iShiftRA#` negateInt# i#)
(I8# x#) `rotate` (I# i#)
| i'# ==# 0#
= I8# x#
| otherwise
= I8# (narrow8Int# (word2Int# ((x'# `shiftL#` i'#) `or#`
(x'# `shiftRL#` (8# -# i'#)))))
where
x'# = narrow8Word# (int2Word# x#)
i'# = word2Int# (int2Word# i# `and#` int2Word# 7#)
bitSize _ = 8
isSigned _ = True
# RULES
" fromIntegral / Int8->Int8 " fromIntegral = i d : : Int8 - > Int8
" fromIntegral / a->Int8 " fromIntegral = \x - > case fromIntegral x of I # x # - > I8 # ( narrow8Int # x # )
" fromIntegral / Int8->a " fromIntegral = \(I8 # x # ) - > fromIntegral ( I # x # )
#
"fromIntegral/Int8->Int8" fromIntegral = id :: Int8 -> Int8
"fromIntegral/a->Int8" fromIntegral = \x -> case fromIntegral x of I# x# -> I8# (narrow8Int# x#)
"fromIntegral/Int8->a" fromIntegral = \(I8# x#) -> fromIntegral (I# x#)
#-}
Int16 is represented in the same way as Int . Operations may assume
data Int16 = I16# Int# deriving (Eq, Ord)
^ 16 - bit signed integer type
instance Show Int16 where
showsPrec p x = showsPrec p (fromIntegral x :: Int)
instance Num Int16 where
(I16# x#) + (I16# y#) = I16# (narrow16Int# (x# +# y#))
(I16# x#) - (I16# y#) = I16# (narrow16Int# (x# -# y#))
(I16# x#) * (I16# y#) = I16# (narrow16Int# (x# *# y#))
negate (I16# x#) = I16# (narrow16Int# (negateInt# x#))
abs x | x >= 0 = x
| otherwise = negate x
signum x | x > 0 = 1
signum 0 = 0
signum _ = -1
fromInteger (S# i#) = I16# (narrow16Int# i#)
fromInteger (J# s# d#) = I16# (narrow16Int# (integer2Int# s# d#))
instance Real Int16 where
toRational x = toInteger x % 1
instance Enum Int16 where
succ x
| x /= maxBound = x + 1
| otherwise = succError "Int16"
pred x
| x /= minBound = x - 1
| otherwise = predError "Int16"
toEnum i@(I# i#)
| i >= fromIntegral (minBound::Int16) && i <= fromIntegral (maxBound::Int16)
= I16# i#
| otherwise = toEnumError "Int16" i (minBound::Int16, maxBound::Int16)
fromEnum (I16# x#) = I# x#
enumFrom = boundedEnumFrom
enumFromThen = boundedEnumFromThen
instance Integral Int16 where
quot x@(I16# x#) y@(I16# y#)
| y /= 0 = I16# (narrow16Int# (x# `quotInt#` y#))
| otherwise = divZeroError
rem x@(I16# x#) y@(I16# y#)
| y /= 0 = I16# (narrow16Int# (x# `remInt#` y#))
| otherwise = divZeroError
div x@(I16# x#) y@(I16# y#)
| y /= 0 = I16# (narrow16Int# (x# `divInt#` y#))
| otherwise = divZeroError
mod x@(I16# x#) y@(I16# y#)
| y /= 0 = I16# (narrow16Int# (x# `modInt#` y#))
| otherwise = divZeroError
quotRem x@(I16# x#) y@(I16# y#)
| y /= 0 = (I16# (narrow16Int# (x# `quotInt#` y#)),
I16# (narrow16Int# (x# `remInt#` y#)))
| otherwise = divZeroError
divMod x@(I16# x#) y@(I16# y#)
| y /= 0 = (I16# (narrow16Int# (x# `divInt#` y#)),
I16# (narrow16Int# (x# `modInt#` y#)))
| otherwise = divZeroError
toInteger (I16# x#) = S# x#
instance Bounded Int16 where
minBound = -0x8000
maxBound = 0x7FFF
instance Ix Int16 where
range (m,n) = [m..n]
unsafeIndex b@(m,_) i = fromIntegral (i - m)
inRange (m,n) i = m <= i && i <= n
unsafeRangeSize b@(_l,h) = unsafeIndex b h + 1
instance Read Int16 where
readsPrec p s = [(fromIntegral (x::Int), r) | (x, r) <- readsPrec p s]
instance Bits Int16 where
(I16# x#) .&. (I16# y#) = I16# (word2Int# (int2Word# x# `and#` int2Word# y#))
(I16# x#) .|. (I16# y#) = I16# (word2Int# (int2Word# x# `or#` int2Word# y#))
(I16# x#) `xor` (I16# y#) = I16# (word2Int# (int2Word# x# `xor#` int2Word# y#))
complement (I16# x#) = I16# (word2Int# (int2Word# x# `xor#` int2Word# (-1#)))
(I16# x#) `shift` (I# i#)
| i# >=# 0# = I16# (narrow16Int# (x# `iShiftL#` i#))
| otherwise = I16# (x# `iShiftRA#` negateInt# i#)
(I16# x#) `rotate` (I# i#)
| i'# ==# 0#
= I16# x#
| otherwise
= I16# (narrow16Int# (word2Int# ((x'# `shiftL#` i'#) `or#`
(x'# `shiftRL#` (16# -# i'#)))))
where
x'# = narrow16Word# (int2Word# x#)
i'# = word2Int# (int2Word# i# `and#` int2Word# 15#)
bitSize _ = 16
isSigned _ = True
# RULES
" fromIntegral / Word8->Int16 " fromIntegral = \(W8 # x # ) - > I16 # ( word2Int # x # )
" fromIntegral / Int8->Int16 " fromIntegral = \(I8 # x # ) - > I16 # x #
" fromIntegral / Int16->Int16 " fromIntegral = i d : : Int16 - > Int16
" fromIntegral / a->Int16 " fromIntegral = \x - > case fromIntegral x of I # x # - > I16 # ( narrow16Int # x # )
" fromIntegral / Int16->a " fromIntegral = \(I16 # x # ) - > fromIntegral ( I # x # )
#
"fromIntegral/Word8->Int16" fromIntegral = \(W8# x#) -> I16# (word2Int# x#)
"fromIntegral/Int8->Int16" fromIntegral = \(I8# x#) -> I16# x#
"fromIntegral/Int16->Int16" fromIntegral = id :: Int16 -> Int16
"fromIntegral/a->Int16" fromIntegral = \x -> case fromIntegral x of I# x# -> I16# (narrow16Int# x#)
"fromIntegral/Int16->a" fromIntegral = \(I16# x#) -> fromIntegral (I# x#)
#-}
type Int32
#if WORD_SIZE_IN_BITS < 32
data Int32 = I32# Int32#
^ 32 - bit signed integer type
instance Eq Int32 where
(I32# x#) == (I32# y#) = x# `eqInt32#` y#
(I32# x#) /= (I32# y#) = x# `neInt32#` y#
instance Ord Int32 where
(I32# x#) < (I32# y#) = x# `ltInt32#` y#
(I32# x#) <= (I32# y#) = x# `leInt32#` y#
(I32# x#) > (I32# y#) = x# `gtInt32#` y#
(I32# x#) >= (I32# y#) = x# `geInt32#` y#
instance Show Int32 where
showsPrec p x = showsPrec p (toInteger x)
instance Num Int32 where
(I32# x#) + (I32# y#) = I32# (x# `plusInt32#` y#)
(I32# x#) - (I32# y#) = I32# (x# `minusInt32#` y#)
(I32# x#) * (I32# y#) = I32# (x# `timesInt32#` y#)
negate (I32# x#) = I32# (negateInt32# x#)
abs x | x >= 0 = x
| otherwise = negate x
signum x | x > 0 = 1
signum 0 = 0
signum _ = -1
fromInteger (S# i#) = I32# (intToInt32# i#)
fromInteger (J# s# d#) = I32# (integerToInt32# s# d#)
instance Enum Int32 where
succ x
| x /= maxBound = x + 1
| otherwise = succError "Int32"
pred x
| x /= minBound = x - 1
| otherwise = predError "Int32"
toEnum (I# i#) = I32# (intToInt32# i#)
fromEnum x@(I32# x#)
| x >= fromIntegral (minBound::Int) && x <= fromIntegral (maxBound::Int)
= I# (int32ToInt# x#)
| otherwise = fromEnumError "Int32" x
enumFrom = integralEnumFrom
enumFromThen = integralEnumFromThen
enumFromTo = integralEnumFromTo
enumFromThenTo = integralEnumFromThenTo
instance Integral Int32 where
quot x@(I32# x#) y@(I32# y#)
| y /= 0 = I32# (x# `quotInt32#` y#)
| otherwise = divZeroError
rem x@(I32# x#) y@(I32# y#)
| y /= 0 = I32# (x# `remInt32#` y#)
| otherwise = divZeroError
div x@(I32# x#) y@(I32# y#)
| y /= 0 = I32# (x# `divInt32#` y#)
| otherwise = divZeroError
mod x@(I32# x#) y@(I32# y#)
| y /= 0 = I32# (x# `modInt32#` y#)
| otherwise = divZeroError
quotRem x@(I32# x#) y@(I32# y#)
| y /= 0 = (I32# (x# `quotInt32#` y#), I32# (x# `remInt32#` y#))
| otherwise = divZeroError
divMod x@(I32# x#) y@(I32# y#)
| y /= 0 = (I32# (x# `divInt32#` y#), I32# (x# `modInt32#` y#))
| otherwise = divZeroError
toInteger x@(I32# x#)
| x >= fromIntegral (minBound::Int) && x <= fromIntegral (maxBound::Int)
= S# (int32ToInt# x#)
| otherwise = case int32ToInteger# x# of (# s, d #) -> J# s d
divInt32#, modInt32# :: Int32# -> Int32# -> Int32#
x# `divInt32#` y#
| (x# `gtInt32#` intToInt32# 0#) && (y# `ltInt32#` intToInt32# 0#)
= ((x# `minusInt32#` y#) `minusInt32#` intToInt32# 1#) `quotInt32#` y#
| (x# `ltInt32#` intToInt32# 0#) && (y# `gtInt32#` intToInt32# 0#)
= ((x# `minusInt32#` y#) `plusInt32#` intToInt32# 1#) `quotInt32#` y#
| otherwise = x# `quotInt32#` y#
x# `modInt32#` y#
| (x# `gtInt32#` intToInt32# 0#) && (y# `ltInt32#` intToInt32# 0#) ||
(x# `ltInt32#` intToInt32# 0#) && (y# `gtInt32#` intToInt32# 0#)
= if r# `neInt32#` intToInt32# 0# then r# `plusInt32#` y# else intToInt32# 0#
| otherwise = r#
where
r# = x# `remInt32#` y#
instance Read Int32 where
readsPrec p s = [(fromInteger x, r) | (x, r) <- readsPrec p s]
instance Bits Int32 where
(I32# x#) .&. (I32# y#) = I32# (word32ToInt32# (int32ToWord32# x# `and32#` int32ToWord32# y#))
(I32# x#) .|. (I32# y#) = I32# (word32ToInt32# (int32ToWord32# x# `or32#` int32ToWord32# y#))
(I32# x#) `xor` (I32# y#) = I32# (word32ToInt32# (int32ToWord32# x# `xor32#` int32ToWord32# y#))
complement (I32# x#) = I32# (word32ToInt32# (not32# (int32ToWord32# x#)))
(I32# x#) `shift` (I# i#)
| i# >=# 0# = I32# (x# `iShiftL32#` i#)
| otherwise = I32# (x# `iShiftRA32#` negateInt# i#)
(I32# x#) `rotate` (I# i#)
| i'# ==# 0#
= I32# x#
| otherwise
= I32# (word32ToInt32# ((x'# `shiftL32#` i'#) `or32#`
(x'# `shiftRL32#` (32# -# i'#))))
where
x'# = int32ToWord32# x#
i'# = word2Int# (int2Word# i# `and#` int2Word# 31#)
bitSize _ = 32
isSigned _ = True
foreign import "stg_eqInt32" unsafe eqInt32# :: Int32# -> Int32# -> Bool
foreign import "stg_neInt32" unsafe neInt32# :: Int32# -> Int32# -> Bool
foreign import "stg_ltInt32" unsafe ltInt32# :: Int32# -> Int32# -> Bool
foreign import "stg_leInt32" unsafe leInt32# :: Int32# -> Int32# -> Bool
foreign import "stg_gtInt32" unsafe gtInt32# :: Int32# -> Int32# -> Bool
foreign import "stg_geInt32" unsafe geInt32# :: Int32# -> Int32# -> Bool
foreign import "stg_plusInt32" unsafe plusInt32# :: Int32# -> Int32# -> Int32#
foreign import "stg_minusInt32" unsafe minusInt32# :: Int32# -> Int32# -> Int32#
foreign import "stg_timesInt32" unsafe timesInt32# :: Int32# -> Int32# -> Int32#
foreign import "stg_negateInt32" unsafe negateInt32# :: Int32# -> Int32#
foreign import "stg_quotInt32" unsafe quotInt32# :: Int32# -> Int32# -> Int32#
foreign import "stg_remInt32" unsafe remInt32# :: Int32# -> Int32# -> Int32#
foreign import "stg_intToInt32" unsafe intToInt32# :: Int# -> Int32#
foreign import "stg_int32ToInt" unsafe int32ToInt# :: Int32# -> Int#
foreign import "stg_wordToWord32" unsafe wordToWord32# :: Word# -> Word32#
foreign import "stg_int32ToWord32" unsafe int32ToWord32# :: Int32# -> Word32#
foreign import "stg_word32ToInt32" unsafe word32ToInt32# :: Word32# -> Int32#
foreign import "stg_and32" unsafe and32# :: Word32# -> Word32# -> Word32#
foreign import "stg_or32" unsafe or32# :: Word32# -> Word32# -> Word32#
foreign import "stg_xor32" unsafe xor32# :: Word32# -> Word32# -> Word32#
foreign import "stg_not32" unsafe not32# :: Word32# -> Word32#
foreign import "stg_iShiftL32" unsafe iShiftL32# :: Int32# -> Int# -> Int32#
foreign import "stg_iShiftRA32" unsafe iShiftRA32# :: Int32# -> Int# -> Int32#
foreign import "stg_shiftL32" unsafe shiftL32# :: Word32# -> Int# -> Word32#
foreign import "stg_shiftRL32" unsafe shiftRL32# :: Word32# -> Int# -> Word32#
# RULES
" fromIntegral / Int->Int32 " fromIntegral = \(I # x # ) - > I32 # ( intToInt32 # x # )
" fromIntegral / " fromIntegral = \(W # x # ) - > I32 # ( word32ToInt32 # ( wordToWord32 # x # ) )
" fromIntegral / Word32->Int32 " fromIntegral = \(W32 # x # ) - > I32 # ( word32ToInt32 # x # )
" fromIntegral / Int32->Int " fromIntegral = \(I32 # x # ) - > I # ( int32ToInt # x # )
" fromIntegral / Int32->Word " fromIntegral = \(I32 # x # ) - > W # ( int2Word # ( int32ToInt # x # ) )
" fromIntegral / Int32->Word32 " fromIntegral = \(I32 # x # ) - > W32 # ( int32ToWord32 # x # )
" fromIntegral / Int32->Int32 " fromIntegral = i d : : Int32 - > Int32
#
"fromIntegral/Int->Int32" fromIntegral = \(I# x#) -> I32# (intToInt32# x#)
"fromIntegral/Word->Int32" fromIntegral = \(W# x#) -> I32# (word32ToInt32# (wordToWord32# x#))
"fromIntegral/Word32->Int32" fromIntegral = \(W32# x#) -> I32# (word32ToInt32# x#)
"fromIntegral/Int32->Int" fromIntegral = \(I32# x#) -> I# (int32ToInt# x#)
"fromIntegral/Int32->Word" fromIntegral = \(I32# x#) -> W# (int2Word# (int32ToInt# x#))
"fromIntegral/Int32->Word32" fromIntegral = \(I32# x#) -> W32# (int32ToWord32# x#)
"fromIntegral/Int32->Int32" fromIntegral = id :: Int32 -> Int32
#-}
#else
Int32 is represented in the same way as Int .
#if WORD_SIZE_IN_BITS > 32
Operations may assume and must ensure that it holds only values
#endif
data Int32 = I32# Int# deriving (Eq, Ord)
^ 32 - bit signed integer type
instance Show Int32 where
showsPrec p x = showsPrec p (fromIntegral x :: Int)
instance Num Int32 where
(I32# x#) + (I32# y#) = I32# (narrow32Int# (x# +# y#))
(I32# x#) - (I32# y#) = I32# (narrow32Int# (x# -# y#))
(I32# x#) * (I32# y#) = I32# (narrow32Int# (x# *# y#))
negate (I32# x#) = I32# (narrow32Int# (negateInt# x#))
abs x | x >= 0 = x
| otherwise = negate x
signum x | x > 0 = 1
signum 0 = 0
signum _ = -1
fromInteger (S# i#) = I32# (narrow32Int# i#)
fromInteger (J# s# d#) = I32# (narrow32Int# (integer2Int# s# d#))
instance Enum Int32 where
succ x
| x /= maxBound = x + 1
| otherwise = succError "Int32"
pred x
| x /= minBound = x - 1
| otherwise = predError "Int32"
#if WORD_SIZE_IN_BITS == 32
toEnum (I# i#) = I32# i#
#else
toEnum i@(I# i#)
| i >= fromIntegral (minBound::Int32) && i <= fromIntegral (maxBound::Int32)
= I32# i#
| otherwise = toEnumError "Int32" i (minBound::Int32, maxBound::Int32)
#endif
fromEnum (I32# x#) = I# x#
enumFrom = boundedEnumFrom
enumFromThen = boundedEnumFromThen
instance Integral Int32 where
quot x@(I32# x#) y@(I32# y#)
| y /= 0 = I32# (narrow32Int# (x# `quotInt#` y#))
| otherwise = divZeroError
rem x@(I32# x#) y@(I32# y#)
| y /= 0 = I32# (narrow32Int# (x# `remInt#` y#))
| otherwise = divZeroError
div x@(I32# x#) y@(I32# y#)
| y /= 0 = I32# (narrow32Int# (x# `divInt#` y#))
| otherwise = divZeroError
mod x@(I32# x#) y@(I32# y#)
| y /= 0 = I32# (narrow32Int# (x# `modInt#` y#))
| otherwise = divZeroError
quotRem x@(I32# x#) y@(I32# y#)
| y /= 0 = (I32# (narrow32Int# (x# `quotInt#` y#)),
I32# (narrow32Int# (x# `remInt#` y#)))
| otherwise = divZeroError
divMod x@(I32# x#) y@(I32# y#)
| y /= 0 = (I32# (narrow32Int# (x# `divInt#` y#)),
I32# (narrow32Int# (x# `modInt#` y#)))
| otherwise = divZeroError
toInteger (I32# x#) = S# x#
instance Read Int32 where
readsPrec p s = [(fromIntegral (x::Int), r) | (x, r) <- readsPrec p s]
instance Bits Int32 where
(I32# x#) .&. (I32# y#) = I32# (word2Int# (int2Word# x# `and#` int2Word# y#))
(I32# x#) .|. (I32# y#) = I32# (word2Int# (int2Word# x# `or#` int2Word# y#))
(I32# x#) `xor` (I32# y#) = I32# (word2Int# (int2Word# x# `xor#` int2Word# y#))
complement (I32# x#) = I32# (word2Int# (int2Word# x# `xor#` int2Word# (-1#)))
(I32# x#) `shift` (I# i#)
| i# >=# 0# = I32# (narrow32Int# (x# `iShiftL#` i#))
| otherwise = I32# (x# `iShiftRA#` negateInt# i#)
(I32# x#) `rotate` (I# i#)
| i'# ==# 0#
= I32# x#
| otherwise
= I32# (narrow32Int# (word2Int# ((x'# `shiftL#` i'#) `or#`
(x'# `shiftRL#` (32# -# i'#)))))
where
x'# = narrow32Word# (int2Word# x#)
i'# = word2Int# (int2Word# i# `and#` int2Word# 31#)
bitSize _ = 32
isSigned _ = True
# RULES
" fromIntegral / Word8->Int32 " fromIntegral = \(W8 # x # ) - > I32 # ( word2Int # x # )
" fromIntegral / Word16->Int32 " fromIntegral = \(W16 # x # ) - > I32 # ( word2Int # x # )
" fromIntegral / Int8->Int32 " fromIntegral = \(I8 # x # ) - > I32 # x #
" fromIntegral / Int16->Int32 " fromIntegral = \(I16 # x # ) - > I32 # x #
" fromIntegral / Int32->Int32 " fromIntegral = i d : : Int32 - > Int32
" fromIntegral / a->Int32 " fromIntegral = \x - > case fromIntegral x of I # x # - > I32 # ( narrow32Int # x # )
" fromIntegral / Int32->a " fromIntegral = \(I32 # x # ) - > fromIntegral ( I # x # )
#
"fromIntegral/Word8->Int32" fromIntegral = \(W8# x#) -> I32# (word2Int# x#)
"fromIntegral/Word16->Int32" fromIntegral = \(W16# x#) -> I32# (word2Int# x#)
"fromIntegral/Int8->Int32" fromIntegral = \(I8# x#) -> I32# x#
"fromIntegral/Int16->Int32" fromIntegral = \(I16# x#) -> I32# x#
"fromIntegral/Int32->Int32" fromIntegral = id :: Int32 -> Int32
"fromIntegral/a->Int32" fromIntegral = \x -> case fromIntegral x of I# x# -> I32# (narrow32Int# x#)
"fromIntegral/Int32->a" fromIntegral = \(I32# x#) -> fromIntegral (I# x#)
#-}
#endif
instance Real Int32 where
toRational x = toInteger x % 1
instance Bounded Int32 where
minBound = -0x80000000
maxBound = 0x7FFFFFFF
instance Ix Int32 where
range (m,n) = [m..n]
unsafeIndex b@(m,_) i = fromIntegral (i - m)
inRange (m,n) i = m <= i && i <= n
unsafeRangeSize b@(_l,h) = unsafeIndex b h + 1
type Int64
#if WORD_SIZE_IN_BITS < 64
data Int64 = I64# Int64#
^ 64 - bit signed integer type
instance Eq Int64 where
(I64# x#) == (I64# y#) = x# `eqInt64#` y#
(I64# x#) /= (I64# y#) = x# `neInt64#` y#
instance Ord Int64 where
(I64# x#) < (I64# y#) = x# `ltInt64#` y#
(I64# x#) <= (I64# y#) = x# `leInt64#` y#
(I64# x#) > (I64# y#) = x# `gtInt64#` y#
(I64# x#) >= (I64# y#) = x# `geInt64#` y#
instance Show Int64 where
showsPrec p x = showsPrec p (toInteger x)
instance Num Int64 where
(I64# x#) + (I64# y#) = I64# (x# `plusInt64#` y#)
(I64# x#) - (I64# y#) = I64# (x# `minusInt64#` y#)
(I64# x#) * (I64# y#) = I64# (x# `timesInt64#` y#)
negate (I64# x#) = I64# (negateInt64# x#)
abs x | x >= 0 = x
| otherwise = negate x
signum x | x > 0 = 1
signum 0 = 0
signum _ = -1
fromInteger (S# i#) = I64# (intToInt64# i#)
fromInteger (J# s# d#) = I64# (integerToInt64# s# d#)
instance Enum Int64 where
succ x
| x /= maxBound = x + 1
| otherwise = succError "Int64"
pred x
| x /= minBound = x - 1
| otherwise = predError "Int64"
toEnum (I# i#) = I64# (intToInt64# i#)
fromEnum x@(I64# x#)
| x >= fromIntegral (minBound::Int) && x <= fromIntegral (maxBound::Int)
= I# (int64ToInt# x#)
| otherwise = fromEnumError "Int64" x
enumFrom = integralEnumFrom
enumFromThen = integralEnumFromThen
enumFromTo = integralEnumFromTo
enumFromThenTo = integralEnumFromThenTo
instance Integral Int64 where
quot x@(I64# x#) y@(I64# y#)
| y /= 0 = I64# (x# `quotInt64#` y#)
| otherwise = divZeroError
rem x@(I64# x#) y@(I64# y#)
| y /= 0 = I64# (x# `remInt64#` y#)
| otherwise = divZeroError
div x@(I64# x#) y@(I64# y#)
| y /= 0 = I64# (x# `divInt64#` y#)
| otherwise = divZeroError
mod x@(I64# x#) y@(I64# y#)
| y /= 0 = I64# (x# `modInt64#` y#)
| otherwise = divZeroError
quotRem x@(I64# x#) y@(I64# y#)
| y /= 0 = (I64# (x# `quotInt64#` y#), I64# (x# `remInt64#` y#))
| otherwise = divZeroError
divMod x@(I64# x#) y@(I64# y#)
| y /= 0 = (I64# (x# `divInt64#` y#), I64# (x# `modInt64#` y#))
| otherwise = divZeroError
toInteger x@(I64# x#)
| x >= fromIntegral (minBound::Int) && x <= fromIntegral (maxBound::Int)
= S# (int64ToInt# x#)
| otherwise = case int64ToInteger# x# of (# s, d #) -> J# s d
divInt64#, modInt64# :: Int64# -> Int64# -> Int64#
x# `divInt64#` y#
| (x# `gtInt64#` intToInt64# 0#) && (y# `ltInt64#` intToInt64# 0#)
= ((x# `minusInt64#` y#) `minusInt64#` intToInt64# 1#) `quotInt64#` y#
| (x# `ltInt64#` intToInt64# 0#) && (y# `gtInt64#` intToInt64# 0#)
= ((x# `minusInt64#` y#) `plusInt64#` intToInt64# 1#) `quotInt64#` y#
| otherwise = x# `quotInt64#` y#
x# `modInt64#` y#
| (x# `gtInt64#` intToInt64# 0#) && (y# `ltInt64#` intToInt64# 0#) ||
(x# `ltInt64#` intToInt64# 0#) && (y# `gtInt64#` intToInt64# 0#)
= if r# `neInt64#` intToInt64# 0# then r# `plusInt64#` y# else intToInt64# 0#
| otherwise = r#
where
r# = x# `remInt64#` y#
instance Read Int64 where
readsPrec p s = [(fromInteger x, r) | (x, r) <- readsPrec p s]
instance Bits Int64 where
(I64# x#) .&. (I64# y#) = I64# (word64ToInt64# (int64ToWord64# x# `and64#` int64ToWord64# y#))
(I64# x#) .|. (I64# y#) = I64# (word64ToInt64# (int64ToWord64# x# `or64#` int64ToWord64# y#))
(I64# x#) `xor` (I64# y#) = I64# (word64ToInt64# (int64ToWord64# x# `xor64#` int64ToWord64# y#))
complement (I64# x#) = I64# (word64ToInt64# (not64# (int64ToWord64# x#)))
(I64# x#) `shift` (I# i#)
| i# >=# 0# = I64# (x# `iShiftL64#` i#)
| otherwise = I64# (x# `iShiftRA64#` negateInt# i#)
(I64# x#) `rotate` (I# i#)
| i'# ==# 0#
= I64# x#
| otherwise
= I64# (word64ToInt64# ((x'# `uncheckedShiftL64#` i'#) `or64#`
(x'# `uncheckedShiftRL64#` (64# -# i'#))))
where
x'# = int64ToWord64# x#
i'# = word2Int# (int2Word# i# `and#` int2Word# 63#)
bitSize _ = 64
isSigned _ = True
give the 64 - bit shift operations the same treatment as the 32 - bit
ones ( see ) , namely we wrap them in tests to catch the
cases when we 're shifting more than 64 bits to avoid unspecified
iShiftL64#, iShiftRA64# :: Int64# -> Int# -> Int64#
a `iShiftL64#` b | b >=# 64# = intToInt64# 0#
| otherwise = a `uncheckedIShiftL64#` b
a `iShiftRA64#` b | b >=# 64# = if a `ltInt64#` (intToInt64# 0#)
then intToInt64# (-1#)
else intToInt64# 0#
| otherwise = a `uncheckedIShiftRA64#` b
foreign import ccall unsafe "stg_eqInt64" eqInt64# :: Int64# -> Int64# -> Bool
foreign import ccall unsafe "stg_neInt64" neInt64# :: Int64# -> Int64# -> Bool
foreign import ccall unsafe "stg_ltInt64" ltInt64# :: Int64# -> Int64# -> Bool
foreign import ccall unsafe "stg_leInt64" leInt64# :: Int64# -> Int64# -> Bool
foreign import ccall unsafe "stg_gtInt64" gtInt64# :: Int64# -> Int64# -> Bool
foreign import ccall unsafe "stg_geInt64" geInt64# :: Int64# -> Int64# -> Bool
foreign import ccall unsafe "stg_plusInt64" plusInt64# :: Int64# -> Int64# -> Int64#
foreign import ccall unsafe "stg_minusInt64" minusInt64# :: Int64# -> Int64# -> Int64#
foreign import ccall unsafe "stg_timesInt64" timesInt64# :: Int64# -> Int64# -> Int64#
foreign import ccall unsafe "stg_negateInt64" negateInt64# :: Int64# -> Int64#
foreign import ccall unsafe "stg_quotInt64" quotInt64# :: Int64# -> Int64# -> Int64#
foreign import ccall unsafe "stg_remInt64" remInt64# :: Int64# -> Int64# -> Int64#
foreign import ccall unsafe "stg_intToInt64" intToInt64# :: Int# -> Int64#
foreign import ccall unsafe "stg_int64ToInt" int64ToInt# :: Int64# -> Int#
foreign import ccall unsafe "stg_wordToWord64" wordToWord64# :: Word# -> Word64#
foreign import ccall unsafe "stg_int64ToWord64" int64ToWord64# :: Int64# -> Word64#
foreign import ccall unsafe "stg_word64ToInt64" word64ToInt64# :: Word64# -> Int64#
foreign import ccall unsafe "stg_and64" and64# :: Word64# -> Word64# -> Word64#
foreign import ccall unsafe "stg_or64" or64# :: Word64# -> Word64# -> Word64#
foreign import ccall unsafe "stg_xor64" xor64# :: Word64# -> Word64# -> Word64#
foreign import ccall unsafe "stg_not64" not64# :: Word64# -> Word64#
foreign import ccall unsafe "stg_uncheckedShiftL64" uncheckedShiftL64# :: Word64# -> Int# -> Word64#
foreign import ccall unsafe "stg_uncheckedShiftRL64" uncheckedShiftRL64# :: Word64# -> Int# -> Word64#
foreign import ccall unsafe "stg_uncheckedIShiftL64" uncheckedIShiftL64# :: Int64# -> Int# -> Int64#
foreign import ccall unsafe "stg_uncheckedIShiftRA64" uncheckedIShiftRA64# :: Int64# -> Int# -> Int64#
foreign import ccall unsafe "stg_integerToInt64" integerToInt64# :: Int# -> ByteArray# -> Int64#
# RULES
" fromIntegral / Int->Int64 " fromIntegral = \(I # x # ) - > I64 # ( intToInt64 # x # )
" fromIntegral / Word->Int64 " fromIntegral = \(W # x # ) - > I64 # ( word64ToInt64 # ( wordToWord64 # x # ) )
" fromIntegral / Word64->Int64 " fromIntegral = \(W64 # x # ) - > I64 # ( word64ToInt64 # x # )
" fromIntegral / Int64->Int " fromIntegral = \(I64 # x # ) - > I # ( int64ToInt # x # )
" fromIntegral / Int64->Word " fromIntegral = \(I64 # x # ) - > W # ( int2Word # ( int64ToInt # x # ) )
" fromIntegral / Int64->Word64 " fromIntegral = \(I64 # x # ) - > W64 # ( int64ToWord64 # x # )
" fromIntegral / Int64->Int64 " fromIntegral = i d : : Int64 - > Int64
#
"fromIntegral/Int->Int64" fromIntegral = \(I# x#) -> I64# (intToInt64# x#)
"fromIntegral/Word->Int64" fromIntegral = \(W# x#) -> I64# (word64ToInt64# (wordToWord64# x#))
"fromIntegral/Word64->Int64" fromIntegral = \(W64# x#) -> I64# (word64ToInt64# x#)
"fromIntegral/Int64->Int" fromIntegral = \(I64# x#) -> I# (int64ToInt# x#)
"fromIntegral/Int64->Word" fromIntegral = \(I64# x#) -> W# (int2Word# (int64ToInt# x#))
"fromIntegral/Int64->Word64" fromIntegral = \(I64# x#) -> W64# (int64ToWord64# x#)
"fromIntegral/Int64->Int64" fromIntegral = id :: Int64 -> Int64
#-}
#else
Int64 is represented in the same way as Int .
Operations may assume and must ensure that it holds only values
data Int64 = I64# Int# deriving (Eq, Ord)
^ 64 - bit signed integer type
instance Show Int64 where
showsPrec p x = showsPrec p (fromIntegral x :: Int)
instance Num Int64 where
(I64# x#) + (I64# y#) = I64# (x# +# y#)
(I64# x#) - (I64# y#) = I64# (x# -# y#)
(I64# x#) * (I64# y#) = I64# (x# *# y#)
negate (I64# x#) = I64# (negateInt# x#)
abs x | x >= 0 = x
| otherwise = negate x
signum x | x > 0 = 1
signum 0 = 0
signum _ = -1
fromInteger (S# i#) = I64# i#
fromInteger (J# s# d#) = I64# (integer2Int# s# d#)
instance Enum Int64 where
succ x
| x /= maxBound = x + 1
| otherwise = succError "Int64"
pred x
| x /= minBound = x - 1
| otherwise = predError "Int64"
toEnum (I# i#) = I64# i#
fromEnum (I64# x#) = I# x#
enumFrom = boundedEnumFrom
enumFromThen = boundedEnumFromThen
instance Integral Int64 where
quot x@(I64# x#) y@(I64# y#)
| y /= 0 = I64# (x# `quotInt#` y#)
| otherwise = divZeroError
rem x@(I64# x#) y@(I64# y#)
| y /= 0 = I64# (x# `remInt#` y#)
| otherwise = divZeroError
div x@(I64# x#) y@(I64# y#)
| y /= 0 = I64# (x# `divInt#` y#)
| otherwise = divZeroError
mod x@(I64# x#) y@(I64# y#)
| y /= 0 = I64# (x# `modInt#` y#)
| otherwise = divZeroError
quotRem x@(I64# x#) y@(I64# y#)
| y /= 0 = (I64# (x# `quotInt#` y#), I64# (x# `remInt#` y#))
| otherwise = divZeroError
divMod x@(I64# x#) y@(I64# y#)
| y /= 0 = (I64# (x# `divInt#` y#), I64# (x# `modInt#` y#))
| otherwise = divZeroError
toInteger (I64# x#) = S# x#
instance Read Int64 where
readsPrec p s = [(fromIntegral (x::Int), r) | (x, r) <- readsPrec p s]
instance Bits Int64 where
(I64# x#) .&. (I64# y#) = I64# (word2Int# (int2Word# x# `and#` int2Word# y#))
(I64# x#) .|. (I64# y#) = I64# (word2Int# (int2Word# x# `or#` int2Word# y#))
(I64# x#) `xor` (I64# y#) = I64# (word2Int# (int2Word# x# `xor#` int2Word# y#))
complement (I64# x#) = I64# (word2Int# (int2Word# x# `xor#` int2Word# (-1#)))
(I64# x#) `shift` (I# i#)
| i# >=# 0# = I64# (x# `iShiftL#` i#)
| otherwise = I64# (x# `iShiftRA#` negateInt# i#)
(I64# x#) `rotate` (I# i#)
| i'# ==# 0#
= I64# x#
| otherwise
= I64# (word2Int# ((x'# `shiftL#` i'#) `or#`
(x'# `shiftRL#` (64# -# i'#))))
where
x'# = int2Word# x#
i'# = word2Int# (int2Word# i# `and#` int2Word# 63#)
bitSize _ = 64
isSigned _ = True
# RULES
" fromIntegral / a->Int64 " fromIntegral = \x - > case fromIntegral x of I # x # - > I64 # x #
" fromIntegral / Int64->a " fromIntegral = \(I64 # x # ) - > fromIntegral ( I # x # )
#
"fromIntegral/a->Int64" fromIntegral = \x -> case fromIntegral x of I# x# -> I64# x#
"fromIntegral/Int64->a" fromIntegral = \(I64# x#) -> fromIntegral (I# x#)
#-}
#endif
instance Real Int64 where
toRational x = toInteger x % 1
instance Bounded Int64 where
minBound = -0x8000000000000000
maxBound = 0x7FFFFFFFFFFFFFFF
instance Ix Int64 where
range (m,n) = [m..n]
unsafeIndex b@(m,_) i = fromIntegral (i - m)
inRange (m,n) i = m <= i && i <= n
unsafeRangeSize b@(_l,h) = unsafeIndex b h + 1
|
b53e0cb2cf4dfc436f12fb9ff356f3656513e8296dc4ace8a572aa4413eaf8ca
|
scrintal/heroicons-reagent
|
cursor_arrow_rays.cljs
|
(ns com.scrintal.heroicons.solid.cursor-arrow-rays)
(defn render []
[:svg {:xmlns ""
:viewBox "0 0 24 24"
:fill "currentColor"
:aria-hidden "true"}
[:path {:fillRule "evenodd"
:d "M12 1.5a.75.75 0 01.75.75V4.5a.75.75 0 01-1.5 0V2.25A.75.75 0 0112 1.5zM5.636 4.136a.75.75 0 011.06 0l1.592 1.591a.75.75 0 01-1.061 1.06l-1.591-1.59a.75.75 0 010-1.061zm12.728 0a.75.75 0 010 1.06l-1.591 1.592a.75.75 0 01-1.06-1.061l1.59-1.591a.75.75 0 011.061 0zm-6.816 4.496a.75.75 0 01.82.311l5.228 7.917a.75.75 0 01-.777 1.148l-2.097-.43 1.045 3.9a.75.75 0 01-1.45.388l-1.044-3.899-1.601 1.42a.75.75 0 01-1.247-.606l.569-9.47a.75.75 0 01.554-.68zM3 10.5a.75.75 0 01.75-.75H6a.75.75 0 010 1.5H3.75A.75.75 0 013 10.5zm14.25 0a.75.75 0 01.75-.75h2.25a.75.75 0 010 1.5H18a.75.75 0 01-.75-.75zm-8.962 3.712a.75.75 0 010 1.061l-1.591 1.591a.75.75 0 11-1.061-1.06l1.591-1.592a.75.75 0 011.06 0z"
:clipRule "evenodd"}]])
| null |
https://raw.githubusercontent.com/scrintal/heroicons-reagent/572f51d2466697ec4d38813663ee2588960365b6/src/com/scrintal/heroicons/solid/cursor_arrow_rays.cljs
|
clojure
|
(ns com.scrintal.heroicons.solid.cursor-arrow-rays)
(defn render []
[:svg {:xmlns ""
:viewBox "0 0 24 24"
:fill "currentColor"
:aria-hidden "true"}
[:path {:fillRule "evenodd"
:d "M12 1.5a.75.75 0 01.75.75V4.5a.75.75 0 01-1.5 0V2.25A.75.75 0 0112 1.5zM5.636 4.136a.75.75 0 011.06 0l1.592 1.591a.75.75 0 01-1.061 1.06l-1.591-1.59a.75.75 0 010-1.061zm12.728 0a.75.75 0 010 1.06l-1.591 1.592a.75.75 0 01-1.06-1.061l1.59-1.591a.75.75 0 011.061 0zm-6.816 4.496a.75.75 0 01.82.311l5.228 7.917a.75.75 0 01-.777 1.148l-2.097-.43 1.045 3.9a.75.75 0 01-1.45.388l-1.044-3.899-1.601 1.42a.75.75 0 01-1.247-.606l.569-9.47a.75.75 0 01.554-.68zM3 10.5a.75.75 0 01.75-.75H6a.75.75 0 010 1.5H3.75A.75.75 0 013 10.5zm14.25 0a.75.75 0 01.75-.75h2.25a.75.75 0 010 1.5H18a.75.75 0 01-.75-.75zm-8.962 3.712a.75.75 0 010 1.061l-1.591 1.591a.75.75 0 11-1.061-1.06l1.591-1.592a.75.75 0 011.06 0z"
:clipRule "evenodd"}]])
|
|
c596e8b6fab5d5bec3b123e66b13995ec171b22d85885f803ad66fc13441b6b6
|
jameysharp/corrode
|
test.hs
|
import Control.Monad
import Control.Monad.Trans.Class
import Control.Monad.Trans.State.Lazy
import Data.Either
import Data.Foldable
import Data.Functor.Identity
import qualified Data.IntMap as IntMap
import qualified Data.Map as Map
import Data.List
import Language.Rust.Corrode.CFG
import Test.Tasty
import qualified Test.Tasty.QuickCheck as QC
import Text.PrettyPrint.HughesPJClass hiding (empty)
main :: IO ()
main = defaultMain tests
tests :: TestTree
tests = testGroup "Tests"
[ QC.testProperty "structuring CFGs conserves code" cfgStructureConservesCode
, QC.testProperty "CFG structuring round-trips" cfgRoundTrip
]
data Stmt
= Stmt Int
| Return
| Loop Label [Stmt]
| Break (Maybe Label)
| Continue (Maybe Label)
| If Cond [Stmt] [Stmt]
| Goto Int
deriving (Show, Eq)
data Cond
= Cond Int
| Match Int
deriving (Show, Eq)
instance Pretty Stmt where
pPrint (Loop l b) = vcat
[ text ("Loop " ++ show l ++ " {")
, nest 4 (prettyStmts b)
, text "}"
]
pPrint (If c t f) = vcat
[ text ("If " ++ show c ++ " {")
, nest 4 (prettyStmts t)
, text "} else {"
, nest 4 (prettyStmts f)
, text "}"
]
pPrint s = text (show s)
prettyStmts :: [Stmt] -> Doc
prettyStmts = vcat . map pPrint
stmtToCFG :: [Stmt] -> CFG DepthFirst [Stmt] Cond
stmtToCFG = depthFirstOrder . staticCFG . runIdentity . buildCFG . convert [] ([], Unreachable)
where
makeBlock ([], Branch to) = return to
makeBlock (after, term) = do
b <- newLabel
addBlock b after term
return b
convert loops term stmts = convert' loops term stmts >>= makeBlock
convert' loops = foldrM go
where
getLoop Nothing = case loops of
(_, labels) : _ -> labels
[] -> error "stmtToCFG: loop exit without an enclosing loop"
getLoop (Just l) = case lookup l loops of
Just labels -> labels
Nothing -> error ("stmtToCFG: loop " ++ show l ++ " not in " ++ show loops)
go Return _ = return ([Return], Unreachable)
go (Loop l stmts) (after, term) = do
brk <- makeBlock (after, term)
cont <- newLabel
(after', term') <- convert' ((l, (brk, cont)) : loops) ([], Branch cont) stmts
addBlock cont after' term'
return ([], Branch cont)
go (Break l) _ = return ([], Branch (fst (getLoop l)))
go (Continue l) _ = return ([], Branch (snd (getLoop l)))
go (If c t f) term = do
term' <- (,) [] <$> Branch <$> makeBlock term
t' <- convert loops term' t
f' <- convert loops term' f
return ([], CondBranch c t' f')
go s (after, term) = return (s : after, term)
staticCFG :: CFG k [Stmt] Cond -> CFG Unordered [Stmt] Cond
staticCFG (CFG start blocks) = removeEmptyBlocks $ evalState (buildCFG $ foo initialState start) Map.empty
where
initialState = -1
getGoto (Goto l) = Right l
getGoto s = Left s
extractGoto current stmts = case partitionEithers $ map getGoto stmts of
(stmts', gotos) -> (last (current : gotos), stmts')
foo current b = do
let key = (current, b)
seen <- lift get
case key `Map.lookup` seen of
Just b' -> return b'
Nothing -> case IntMap.lookup b blocks of
Nothing -> fail ("staticCFG: block " ++ show b ++ " missing")
Just (BasicBlock stmts term) -> do
b' <- newLabel
lift $ put $ Map.insert key b' seen
let (current', stmts') = extractGoto current stmts
term' <- case term of
CondBranch (Match n) t f
| current' == n -> Branch <$> foo current' t
| otherwise -> Branch <$> foo current' f
_ -> mapM (foo current') term
addBlock b' stmts' term'
return b'
data BigramFst = FstStmt Int | FstCond Int Bool
deriving (Eq, Ord, Show)
data BigramSnd = SndStmt Int | SndCond Int | SndReturn
deriving (Eq, Ord, Show)
bigrams :: CFG DepthFirst [Stmt] Cond -> Map.Map BigramFst BigramSnd
bigrams (CFG start blocks) = snd $ IntMap.findWithDefault undefined start $ allBlocks $ allBlocks IntMap.empty
where
allBlocks seen = IntMap.foldrWithKey perBlock seen blocks
perBlock l (BasicBlock stmts term) seen = IntMap.insert l (foldr perStmt (perTerm go term) stmts) seen
where
go to = IntMap.findWithDefault (Nothing, Map.empty) to seen
newBigram _ (Nothing, seen) = seen
newBigram bigramFst (Just bigramSnd, seen) = Map.insert bigramFst bigramSnd seen
perStmt (Stmt s) next = (Just (SndStmt s), newBigram (FstStmt s) next)
perStmt Return _ = (Just SndReturn, Map.empty)
perStmt s _ = error ("bigrams: unsupported statment " ++ show s)
perTerm go term = case term of
Unreachable -> (Nothing, Map.empty)
Branch to -> go to
CondBranch (Cond c) t f -> (Just (SndCond c), bar True t `Map.union` bar False f)
where
bar matched to = newBigram (FstCond c matched) (go to)
CondBranch c _ _ -> error ("bigrams: unsupported condition " ++ show c)
fingerprintStmt :: [Stmt] -> (IntMap.IntMap Int, IntMap.IntMap Int)
fingerprintStmt = foldr go (IntMap.empty, IntMap.empty)
where
go (Stmt l) (stmts, conds) = (IntMap.insertWith (+) l 1 stmts, conds)
go Return rest = rest
go (Loop _ stmts) rest = foldr go rest stmts
go (Break _) rest = rest
go (Continue _) rest = rest
go (If c t f) rest = case c of
Cond l -> (stmts, IntMap.insertWith (+) l 1 conds)
Match _ -> (stmts, conds)
where (stmts, conds) = foldr go (foldr go rest t) f
go (Goto _) rest = rest
fingerprintCFG :: CFG k [Stmt] Cond -> (IntMap.IntMap Int, IntMap.IntMap Int)
fingerprintCFG (CFG _ blocks) = mconcat $ map go $ IntMap.elems blocks
where
go (BasicBlock stmt term) =
let (stmts, conds) = fingerprintStmt stmt in case term of
CondBranch (Cond c) _ _ -> (stmts, IntMap.insertWith (+) c 1 conds)
_ -> (stmts, conds)
genStmts :: CFG DepthFirst s c -> CFG DepthFirst [Stmt] c
genStmts (CFG start blocks) = CFG start (IntMap.mapWithKey go blocks)
where
go _ (BasicBlock _ Unreachable) = BasicBlock [Return] Unreachable
go l (BasicBlock _ term) = BasicBlock [Stmt l] term
genCFG :: QC.Gen (CFG DepthFirst [Stmt] Cond)
genCFG = QC.sized $ \ n -> fmap (genStmts . depthFirstOrder) $ buildCFG $ do
labels <- replicateM (1 + n) newLabel
let chooseLabel = QC.elements labels
forM_ labels $ \ label -> do
term <- lift $ QC.oneof
[ return Unreachable
, Branch <$> chooseLabel
, CondBranch (Cond label) <$> chooseLabel <*> chooseLabel
]
addBlock label () term
return (head labels)
shrinkCFG :: CFG DepthFirst [Stmt] Cond -> [CFG DepthFirst [Stmt] Cond]
shrinkCFG (CFG entry blocks) = map (genStmts . depthFirstOrder) (removeEdges ++ skipBlocks)
where
removeEdges = map (CFG entry . IntMap.fromList) $ go $ IntMap.toList blocks
where
go [] = []
go ((l, BasicBlock b term) : xs) =
[ (l, BasicBlock b term') : xs | term' <- removeEdge term ] ++
[ (l, BasicBlock b term) : xs' | xs' <- go xs ]
removeEdge (CondBranch _ t f) = Unreachable : map Branch (nub [t, f])
removeEdge (Branch _) = [Unreachable]
removeEdge Unreachable = []
skipBlocks = [ skipBlock from to | (from, BasicBlock _ (Branch to)) <- IntMap.toList blocks ]
skipBlock from to = CFG (rewrite entry) (IntMap.map (\ (BasicBlock b term) -> BasicBlock b (fmap rewrite term)) blocks)
where rewrite label = if label == from then to else label
structureStmtCFG :: CFG DepthFirst [Stmt] Cond -> [Stmt]
structureStmtCFG = snd . structureCFG
(return . Break)
(return . Continue)
(\ l b -> [Loop l b])
(\ c t f -> [If c t f])
(return . Goto)
(flip (foldr (\ (l, t) f -> [If (Match l) t f])))
subtractMap :: IntMap.IntMap Int -> IntMap.IntMap Int -> IntMap.IntMap Int
subtractMap = IntMap.mergeWithKey (\ _ a b -> Just (a - b)) id (IntMap.map negate)
cfgStructureConservesCode :: QC.Property
cfgStructureConservesCode = QC.forAllShrink genCFG shrinkCFG $ \ cfg ->
let (cfgStmts, cfgConds) = fingerprintCFG cfg
structured = structureStmtCFG cfg
(structuredStmts, structuredConds) = fingerprintStmt structured
in QC.counterexample (render (prettyStructure (relooperRoot cfg) $+$ prettyStmts structured))
(conserved "statements" structuredStmts cfgStmts QC..&&. conserved "conditions" structuredConds cfgConds)
where
conserved kind structured cfg = case IntMap.toList $ IntMap.filter (/= 0) $ subtractMap structured cfg of
[] -> QC.property True
miss -> QC.counterexample (kind ++ " not conserved: " ++ show miss) False
cfgRoundTrip :: QC.Property
cfgRoundTrip = QC.forAllShrink genCFG shrinkCFG $ \ cfg ->
let bi = bigrams cfg
stmts = structureStmtCFG cfg
cfg' = stmtToCFG stmts
bi' = bigrams cfg'
in foldr QC.counterexample (QC.property (bi == bi')) $
map (++ "\n")
[ render (prettyStructure (relooperRoot cfg))
, render (prettyStmts stmts)
, show bi
, show bi'
, show cfg'
]
| null |
https://raw.githubusercontent.com/jameysharp/corrode/34053342c2f1ca04f23ad94d67057f14e74d9fb9/tests/test.hs
|
haskell
|
import Control.Monad
import Control.Monad.Trans.Class
import Control.Monad.Trans.State.Lazy
import Data.Either
import Data.Foldable
import Data.Functor.Identity
import qualified Data.IntMap as IntMap
import qualified Data.Map as Map
import Data.List
import Language.Rust.Corrode.CFG
import Test.Tasty
import qualified Test.Tasty.QuickCheck as QC
import Text.PrettyPrint.HughesPJClass hiding (empty)
main :: IO ()
main = defaultMain tests
tests :: TestTree
tests = testGroup "Tests"
[ QC.testProperty "structuring CFGs conserves code" cfgStructureConservesCode
, QC.testProperty "CFG structuring round-trips" cfgRoundTrip
]
data Stmt
= Stmt Int
| Return
| Loop Label [Stmt]
| Break (Maybe Label)
| Continue (Maybe Label)
| If Cond [Stmt] [Stmt]
| Goto Int
deriving (Show, Eq)
data Cond
= Cond Int
| Match Int
deriving (Show, Eq)
instance Pretty Stmt where
pPrint (Loop l b) = vcat
[ text ("Loop " ++ show l ++ " {")
, nest 4 (prettyStmts b)
, text "}"
]
pPrint (If c t f) = vcat
[ text ("If " ++ show c ++ " {")
, nest 4 (prettyStmts t)
, text "} else {"
, nest 4 (prettyStmts f)
, text "}"
]
pPrint s = text (show s)
prettyStmts :: [Stmt] -> Doc
prettyStmts = vcat . map pPrint
stmtToCFG :: [Stmt] -> CFG DepthFirst [Stmt] Cond
stmtToCFG = depthFirstOrder . staticCFG . runIdentity . buildCFG . convert [] ([], Unreachable)
where
makeBlock ([], Branch to) = return to
makeBlock (after, term) = do
b <- newLabel
addBlock b after term
return b
convert loops term stmts = convert' loops term stmts >>= makeBlock
convert' loops = foldrM go
where
getLoop Nothing = case loops of
(_, labels) : _ -> labels
[] -> error "stmtToCFG: loop exit without an enclosing loop"
getLoop (Just l) = case lookup l loops of
Just labels -> labels
Nothing -> error ("stmtToCFG: loop " ++ show l ++ " not in " ++ show loops)
go Return _ = return ([Return], Unreachable)
go (Loop l stmts) (after, term) = do
brk <- makeBlock (after, term)
cont <- newLabel
(after', term') <- convert' ((l, (brk, cont)) : loops) ([], Branch cont) stmts
addBlock cont after' term'
return ([], Branch cont)
go (Break l) _ = return ([], Branch (fst (getLoop l)))
go (Continue l) _ = return ([], Branch (snd (getLoop l)))
go (If c t f) term = do
term' <- (,) [] <$> Branch <$> makeBlock term
t' <- convert loops term' t
f' <- convert loops term' f
return ([], CondBranch c t' f')
go s (after, term) = return (s : after, term)
staticCFG :: CFG k [Stmt] Cond -> CFG Unordered [Stmt] Cond
staticCFG (CFG start blocks) = removeEmptyBlocks $ evalState (buildCFG $ foo initialState start) Map.empty
where
initialState = -1
getGoto (Goto l) = Right l
getGoto s = Left s
extractGoto current stmts = case partitionEithers $ map getGoto stmts of
(stmts', gotos) -> (last (current : gotos), stmts')
foo current b = do
let key = (current, b)
seen <- lift get
case key `Map.lookup` seen of
Just b' -> return b'
Nothing -> case IntMap.lookup b blocks of
Nothing -> fail ("staticCFG: block " ++ show b ++ " missing")
Just (BasicBlock stmts term) -> do
b' <- newLabel
lift $ put $ Map.insert key b' seen
let (current', stmts') = extractGoto current stmts
term' <- case term of
CondBranch (Match n) t f
| current' == n -> Branch <$> foo current' t
| otherwise -> Branch <$> foo current' f
_ -> mapM (foo current') term
addBlock b' stmts' term'
return b'
data BigramFst = FstStmt Int | FstCond Int Bool
deriving (Eq, Ord, Show)
data BigramSnd = SndStmt Int | SndCond Int | SndReturn
deriving (Eq, Ord, Show)
bigrams :: CFG DepthFirst [Stmt] Cond -> Map.Map BigramFst BigramSnd
bigrams (CFG start blocks) = snd $ IntMap.findWithDefault undefined start $ allBlocks $ allBlocks IntMap.empty
where
allBlocks seen = IntMap.foldrWithKey perBlock seen blocks
perBlock l (BasicBlock stmts term) seen = IntMap.insert l (foldr perStmt (perTerm go term) stmts) seen
where
go to = IntMap.findWithDefault (Nothing, Map.empty) to seen
newBigram _ (Nothing, seen) = seen
newBigram bigramFst (Just bigramSnd, seen) = Map.insert bigramFst bigramSnd seen
perStmt (Stmt s) next = (Just (SndStmt s), newBigram (FstStmt s) next)
perStmt Return _ = (Just SndReturn, Map.empty)
perStmt s _ = error ("bigrams: unsupported statment " ++ show s)
perTerm go term = case term of
Unreachable -> (Nothing, Map.empty)
Branch to -> go to
CondBranch (Cond c) t f -> (Just (SndCond c), bar True t `Map.union` bar False f)
where
bar matched to = newBigram (FstCond c matched) (go to)
CondBranch c _ _ -> error ("bigrams: unsupported condition " ++ show c)
fingerprintStmt :: [Stmt] -> (IntMap.IntMap Int, IntMap.IntMap Int)
fingerprintStmt = foldr go (IntMap.empty, IntMap.empty)
where
go (Stmt l) (stmts, conds) = (IntMap.insertWith (+) l 1 stmts, conds)
go Return rest = rest
go (Loop _ stmts) rest = foldr go rest stmts
go (Break _) rest = rest
go (Continue _) rest = rest
go (If c t f) rest = case c of
Cond l -> (stmts, IntMap.insertWith (+) l 1 conds)
Match _ -> (stmts, conds)
where (stmts, conds) = foldr go (foldr go rest t) f
go (Goto _) rest = rest
fingerprintCFG :: CFG k [Stmt] Cond -> (IntMap.IntMap Int, IntMap.IntMap Int)
fingerprintCFG (CFG _ blocks) = mconcat $ map go $ IntMap.elems blocks
where
go (BasicBlock stmt term) =
let (stmts, conds) = fingerprintStmt stmt in case term of
CondBranch (Cond c) _ _ -> (stmts, IntMap.insertWith (+) c 1 conds)
_ -> (stmts, conds)
genStmts :: CFG DepthFirst s c -> CFG DepthFirst [Stmt] c
genStmts (CFG start blocks) = CFG start (IntMap.mapWithKey go blocks)
where
go _ (BasicBlock _ Unreachable) = BasicBlock [Return] Unreachable
go l (BasicBlock _ term) = BasicBlock [Stmt l] term
genCFG :: QC.Gen (CFG DepthFirst [Stmt] Cond)
genCFG = QC.sized $ \ n -> fmap (genStmts . depthFirstOrder) $ buildCFG $ do
labels <- replicateM (1 + n) newLabel
let chooseLabel = QC.elements labels
forM_ labels $ \ label -> do
term <- lift $ QC.oneof
[ return Unreachable
, Branch <$> chooseLabel
, CondBranch (Cond label) <$> chooseLabel <*> chooseLabel
]
addBlock label () term
return (head labels)
shrinkCFG :: CFG DepthFirst [Stmt] Cond -> [CFG DepthFirst [Stmt] Cond]
shrinkCFG (CFG entry blocks) = map (genStmts . depthFirstOrder) (removeEdges ++ skipBlocks)
where
removeEdges = map (CFG entry . IntMap.fromList) $ go $ IntMap.toList blocks
where
go [] = []
go ((l, BasicBlock b term) : xs) =
[ (l, BasicBlock b term') : xs | term' <- removeEdge term ] ++
[ (l, BasicBlock b term) : xs' | xs' <- go xs ]
removeEdge (CondBranch _ t f) = Unreachable : map Branch (nub [t, f])
removeEdge (Branch _) = [Unreachable]
removeEdge Unreachable = []
skipBlocks = [ skipBlock from to | (from, BasicBlock _ (Branch to)) <- IntMap.toList blocks ]
skipBlock from to = CFG (rewrite entry) (IntMap.map (\ (BasicBlock b term) -> BasicBlock b (fmap rewrite term)) blocks)
where rewrite label = if label == from then to else label
structureStmtCFG :: CFG DepthFirst [Stmt] Cond -> [Stmt]
structureStmtCFG = snd . structureCFG
(return . Break)
(return . Continue)
(\ l b -> [Loop l b])
(\ c t f -> [If c t f])
(return . Goto)
(flip (foldr (\ (l, t) f -> [If (Match l) t f])))
subtractMap :: IntMap.IntMap Int -> IntMap.IntMap Int -> IntMap.IntMap Int
subtractMap = IntMap.mergeWithKey (\ _ a b -> Just (a - b)) id (IntMap.map negate)
cfgStructureConservesCode :: QC.Property
cfgStructureConservesCode = QC.forAllShrink genCFG shrinkCFG $ \ cfg ->
let (cfgStmts, cfgConds) = fingerprintCFG cfg
structured = structureStmtCFG cfg
(structuredStmts, structuredConds) = fingerprintStmt structured
in QC.counterexample (render (prettyStructure (relooperRoot cfg) $+$ prettyStmts structured))
(conserved "statements" structuredStmts cfgStmts QC..&&. conserved "conditions" structuredConds cfgConds)
where
conserved kind structured cfg = case IntMap.toList $ IntMap.filter (/= 0) $ subtractMap structured cfg of
[] -> QC.property True
miss -> QC.counterexample (kind ++ " not conserved: " ++ show miss) False
cfgRoundTrip :: QC.Property
cfgRoundTrip = QC.forAllShrink genCFG shrinkCFG $ \ cfg ->
let bi = bigrams cfg
stmts = structureStmtCFG cfg
cfg' = stmtToCFG stmts
bi' = bigrams cfg'
in foldr QC.counterexample (QC.property (bi == bi')) $
map (++ "\n")
[ render (prettyStructure (relooperRoot cfg))
, render (prettyStmts stmts)
, show bi
, show bi'
, show cfg'
]
|
|
3c729ba16be30b8fd818bfe4b18dcb3446ebac5d9f9a31eb38c9ae7eb5a86671
|
erlyaws/yaws
|
binary_header.erl
|
-module(binary_header).
-export([out/1]).
out(_Arg) ->
Regression test for github issue 367 , where returning a binary
%% header with deflate on would cause a crash.
%%
[{status, 200},
{header, {content_type, <<"application/octet">>}},
{ehtml, {pre,[],<<"ABCDEFGHIJKLMNOPQRSTUVWXYZ\n">>}}].
| null |
https://raw.githubusercontent.com/erlyaws/yaws/da198c828e9d95ca2137da7884cddadd73941d13/testsuite/deflate_SUITE_data/binary_header.erl
|
erlang
|
header with deflate on would cause a crash.
|
-module(binary_header).
-export([out/1]).
out(_Arg) ->
Regression test for github issue 367 , where returning a binary
[{status, 200},
{header, {content_type, <<"application/octet">>}},
{ehtml, {pre,[],<<"ABCDEFGHIJKLMNOPQRSTUVWXYZ\n">>}}].
|
a72977d7a0a172215bd8973134f9bed59c5d85c6ebf8cf76a134becec00d1c6c
|
facebook/flow
|
checkContentsCommand.ml
|
* Copyright ( c ) Meta Platforms , Inc. and affiliates .
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree .
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
(***********************************************************************)
(* flow check-contents command *)
(***********************************************************************)
open CommandUtils
let spec =
{
CommandSpec.name = "check-contents";
doc = "Run typechecker on contents from stdin";
usage =
Printf.sprintf
"Usage: %s check-contents [OPTION]... [FILE]\n\nRuns a flow check on the contents of stdin. If FILE is provided, then\ncheck-contents pretends that the contents of stdin come from FILE\n\ne.g. %s check-contents < foo.js\nor %s check-contents foo.js < foo.js\n"
CommandUtils.exe_name
CommandUtils.exe_name
CommandUtils.exe_name;
args =
CommandSpec.ArgSpec.(
empty
|> base_flags
|> connect_and_json_flags
|> json_version_flag
|> offset_style_flag
|> root_flag
|> error_flags
|> strip_root_flag
|> verbose_flags
|> from_flag
|> wait_for_recheck_flag
|> flag "--all" truthy ~doc:"Ignore absence of an @flow pragma"
|> anon "filename" (optional string)
);
}
let main
base_flags
option_values
json
pretty
json_version
offset_style
root
error_flags
strip_root
verbose
wait_for_recheck
all
file
() =
let file = get_file_from_filename_or_stdin file ~cmd:CommandSpec.(spec.name) None in
let flowconfig_name = base_flags.Base_flags.flowconfig_name in
let root =
guess_root
flowconfig_name
(match root with
| Some root -> Some root
| None -> File_input.path_of_file_input file)
in
(* pretty implies json *)
let json = json || Base.Option.is_some json_version || pretty in
let offset_kind = CommandUtils.offset_kind_of_offset_style offset_style in
if (not option_values.quiet) && verbose <> None then
prerr_endline "NOTE: --verbose writes to the server log file";
let include_warnings = error_flags.Errors.Cli_output.include_warnings in
let request =
ServerProt.Request.CHECK_FILE
{ input = file; verbose; force = all; include_warnings; wait_for_recheck }
in
let response =
match connect_and_make_request flowconfig_name option_values root request with
| ServerProt.Response.CHECK_FILE response -> response
| response -> failwith_bad_response ~request ~response
in
let stdin_file =
match file with
| File_input.FileContent (None, contents) -> Some (Path.make_unsafe "-", contents)
| File_input.FileContent (Some path, contents) -> Some (Path.make path, contents)
| _ -> None
in
let strip_root =
if strip_root then
Some root
else
None
in
let print_json =
Errors.Json_output.print_errors
~out_channel:stdout
~strip_root
~pretty
?version:json_version
~offset_kind
~stdin_file
in
match response with
| ServerProt.Response.ERRORS { errors; warnings; suppressed_errors } ->
if json then
print_json ~errors ~warnings ~suppressed_errors ()
else (
Errors.Cli_output.print_errors
~out_channel:stdout
~flags:error_flags
~stdin_file
~strip_root
~errors
~warnings
~lazy_msg:None
();
(* Return a successful exit code if there were only warnings. *)
Exit.(
exit
(get_check_or_status_exit_code errors warnings error_flags.Errors.Cli_output.max_warnings)
)
)
| ServerProt.Response.NO_ERRORS ->
if json then
print_json
~errors:Errors.ConcreteLocPrintableErrorSet.empty
~warnings:Errors.ConcreteLocPrintableErrorSet.empty
~suppressed_errors:[]
()
else
Printf.printf "No errors!\n%!";
Exit.(exit No_error)
| ServerProt.Response.NOT_COVERED ->
if json then
print_json
~errors:Errors.ConcreteLocPrintableErrorSet.empty
~warnings:Errors.ConcreteLocPrintableErrorSet.empty
~suppressed_errors:[]
()
else
Printf.printf "File is not @flow!\n%!";
Exit.(exit No_error)
let command = CommandSpec.command spec main
| null |
https://raw.githubusercontent.com/facebook/flow/b918b06104ac1489b516988707431d98833ce99f/src/commands/checkContentsCommand.ml
|
ocaml
|
*********************************************************************
flow check-contents command
*********************************************************************
pretty implies json
Return a successful exit code if there were only warnings.
|
* Copyright ( c ) Meta Platforms , Inc. and affiliates .
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree .
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
open CommandUtils
let spec =
{
CommandSpec.name = "check-contents";
doc = "Run typechecker on contents from stdin";
usage =
Printf.sprintf
"Usage: %s check-contents [OPTION]... [FILE]\n\nRuns a flow check on the contents of stdin. If FILE is provided, then\ncheck-contents pretends that the contents of stdin come from FILE\n\ne.g. %s check-contents < foo.js\nor %s check-contents foo.js < foo.js\n"
CommandUtils.exe_name
CommandUtils.exe_name
CommandUtils.exe_name;
args =
CommandSpec.ArgSpec.(
empty
|> base_flags
|> connect_and_json_flags
|> json_version_flag
|> offset_style_flag
|> root_flag
|> error_flags
|> strip_root_flag
|> verbose_flags
|> from_flag
|> wait_for_recheck_flag
|> flag "--all" truthy ~doc:"Ignore absence of an @flow pragma"
|> anon "filename" (optional string)
);
}
let main
base_flags
option_values
json
pretty
json_version
offset_style
root
error_flags
strip_root
verbose
wait_for_recheck
all
file
() =
let file = get_file_from_filename_or_stdin file ~cmd:CommandSpec.(spec.name) None in
let flowconfig_name = base_flags.Base_flags.flowconfig_name in
let root =
guess_root
flowconfig_name
(match root with
| Some root -> Some root
| None -> File_input.path_of_file_input file)
in
let json = json || Base.Option.is_some json_version || pretty in
let offset_kind = CommandUtils.offset_kind_of_offset_style offset_style in
if (not option_values.quiet) && verbose <> None then
prerr_endline "NOTE: --verbose writes to the server log file";
let include_warnings = error_flags.Errors.Cli_output.include_warnings in
let request =
ServerProt.Request.CHECK_FILE
{ input = file; verbose; force = all; include_warnings; wait_for_recheck }
in
let response =
match connect_and_make_request flowconfig_name option_values root request with
| ServerProt.Response.CHECK_FILE response -> response
| response -> failwith_bad_response ~request ~response
in
let stdin_file =
match file with
| File_input.FileContent (None, contents) -> Some (Path.make_unsafe "-", contents)
| File_input.FileContent (Some path, contents) -> Some (Path.make path, contents)
| _ -> None
in
let strip_root =
if strip_root then
Some root
else
None
in
let print_json =
Errors.Json_output.print_errors
~out_channel:stdout
~strip_root
~pretty
?version:json_version
~offset_kind
~stdin_file
in
match response with
| ServerProt.Response.ERRORS { errors; warnings; suppressed_errors } ->
if json then
print_json ~errors ~warnings ~suppressed_errors ()
else (
Errors.Cli_output.print_errors
~out_channel:stdout
~flags:error_flags
~stdin_file
~strip_root
~errors
~warnings
~lazy_msg:None
();
Exit.(
exit
(get_check_or_status_exit_code errors warnings error_flags.Errors.Cli_output.max_warnings)
)
)
| ServerProt.Response.NO_ERRORS ->
if json then
print_json
~errors:Errors.ConcreteLocPrintableErrorSet.empty
~warnings:Errors.ConcreteLocPrintableErrorSet.empty
~suppressed_errors:[]
()
else
Printf.printf "No errors!\n%!";
Exit.(exit No_error)
| ServerProt.Response.NOT_COVERED ->
if json then
print_json
~errors:Errors.ConcreteLocPrintableErrorSet.empty
~warnings:Errors.ConcreteLocPrintableErrorSet.empty
~suppressed_errors:[]
()
else
Printf.printf "File is not @flow!\n%!";
Exit.(exit No_error)
let command = CommandSpec.command spec main
|
7b73a63d0331f3e8d0b2f8e34f3db193e93c3a4025869b2850927de369db5667
|
gstew5/snarkl
|
Keccak.hs
|
# LANGUAGE RebindableSyntax , DataKinds #
module Keccak where
import qualified Data.Map.Strict as Map
import Data.Bits hiding (xor)
import Prelude hiding
( (>>)
, (>>=)
, (+)
, (-)
, (*)
, (/)
, (&&)
, not
, return
, fromRational
, negate
)
import qualified Prelude as P
import SyntaxMonad
import Syntax
import TExpr
import Toplevel
num_lanes :: Int
num_lanes = (P.*) 5 5
ln_width :: Int
ln_width = 32
| ' i'th bit of round constant
-> TExp ('TArr ('TArr ('TArr 'TBool))) Rational -- | Array 'a'
-> Comp 'TUnit
round1 rc a
= do { -- Allocate local array variables [b], [c], [d].
b <- arr3 5 5 ln_width
; c <- arr2 5 ln_width
; d <- arr2 5 ln_width
Initialize arrays .
; forall3 ([0..4],[0..4],[0..dec ln_width])
(\i j k -> set3 (b,i,j,k) false)
; forall2 ([0..4],[0..dec ln_width]) (\i j -> set2 (c,i,j) false)
; forall2 ([0..4],[0..dec ln_width]) (\i j -> set2 (d,i,j) false)
-- \theta step
; forall2 ([0..4],[0..dec ln_width]) (\x i ->
do q <- get3 (a,x,0,i)
u <- get3 (a,x,1,i)
v <- get3 (a,x,2,i)
w <- get3 (a,x,3,i)
z <- get3 (a,x,4,i)
set2 (c,x,i) $ q `xor` u `xor` v `xor` w `xor` z)
; forall2 ([0..4],[0..dec ln_width]) (\x i ->
do q <- get2 (c,dec x `mod` 5,i)
u <- get2 (c,inc x `mod` 5,rot_index i 1)
set2 (d,x,i) $ q `xor` u)
; forall3 ([0..4],[0..4],[0..dec ln_width]) (\x y i ->
do q <- get3 (a,x,y,i)
u <- get2 (d,x,i)
set3 (a,x,y,i) $ q `xor` u)
\rho and \pi steps
; forall3 ([0..4],[0..4],[0..dec ln_width]) (\x y i ->
do q <- get3 (a,x,y,rot_index i (rot_tbl x y))
set3 (b,y,((P.+) ((P.*) 2 x) ((P.*) 3 y)) `mod` 5,i) q)
\chi step
; forall3 ([0..4],[0..4],[0..dec ln_width]) (\x y i ->
do q <- get3 (b,x,y,i)
u <- get3 (b,inc x `mod` 5,y,i)
v <- get3 (b,(inc . inc) x `mod` 5,y,i)
set3 (a,x,y,i) $ q `xor` (not u && v))
-- \iota step
; forall [0..dec ln_width] (\i ->
do q <- get3 (a,0,0,i)
set3 (a,0,0,i) (q `xor` rc i))
}
-- round constants
round_consts :: [Integer]
round_consts
= [ 0x00000001
, 0x00008082
, 0x0000808a
, 0x80008000
, 0x0000808b
, 0x80000001
, 0x80008081
, 0x00008009
, 0x0000008a
, 0x00000088
, 0x80008009
, 0x8000000a
, 0x8000808b
, 0x800000000000008b
, 0x8000000000008089
, 0x8000000000008003
, 0x8000000000008002
, 0x8000000000000080
, 0x800000000000800a
, 0x800000008000000a
, 0x8000000080008081
, 0x8000000080008080
, 0x0000000080000001
, 0x8000000080008008
]
rot_index :: Int -- rotate index 'i'
-> Int -- by 'n' (mod lane width)
-> Int
rot_index i n = ((P.-) i n) `mod` ln_width
rot_tbl x y
= let m = Map.fromList $
[ ((3,2), 25), ((4,2), 39), ((0,2), 3), ((1,2), 10), ((2,2), 43)
, ((3,1), 55), ((4,1), 20), ((0,1), 36), ((1,1), 44), ((2,1), 6)
, ((3,0), 28), ((4,0), 27), ((0,0), 0), ((1,0), 1), ((2,0), 62)
, ((3,4), 56), ((4,4), 14), ((0,4), 18), ((1,4), 2), ((2,4), 61)
, ((3,3), 21), ((4,3), 8), ((0,3), 41), ((1,3), 45), ((2,3), 15) ]
in case Map.lookup (x,y) m of
Nothing -> error $ show (x,y) ++ " not a valid rotation key"
Just r -> r
trunc :: Integer -> Int
trunc rc
= fromIntegral rc
.&. dec (truncate (2**fromIntegral ln_width :: Double) :: Int)
get_round_bit :: Int -> Int -> TExp 'TBool Rational
get_round_bit round_i bit_i
= let the_bit = round_consts !! round_i
.&. truncate (2**fromIntegral bit_i :: Double)
in case the_bit > 0 of
False -> false
True -> true
keccak_f1 num_rounds a
= forall [0..dec num_rounds] (\round_i ->
round1 (\bit_i -> get_round_bit round_i bit_i) a)
num_rounds = 12 + 2l , where 2^l = ln_width
keccak1 num_rounds
= do { a <- input_arr3 5 5 ln_width
; keccak_f1 num_rounds a
; b <- arr 1
; set (b, 0) false
; forall3 ([0..4], [0..4], [0..dec ln_width]) (\i j k -> do
a_val <- get3 (a, i, j, k)
b_val <- get (b, 0)
set (b, 0) (a_val `xor` b_val))
; get (b, 0)
}
input_vals = go ((P.*) num_lanes ln_width)
where go :: Int -> [Int]
go 0 = []
go n | odd n = 0 : go (dec n)
go n | otherwise = 1 : go (dec n)
-- test_full n
= Top.test ( keccak1 n , input_vals , ( 1::Integer ) )
-- test_interp n
= Top.texp_interp ( keccak1 n ) ( map fromIntegral input_vals )
-- test_r1cs n
= let ( nv , in_vars , e ) = Top.texp_of_comp ( keccak1 n )
r1cs =
in putStrLn
-- $ show
-- $ last (r1cs_clauses r1cs)
-- First compile to R1CS , then generate witness .
-- test_wit n
= let ( nv , in_vars , e ) = Top.texp_of_comp ( keccak1 n )
r1cs =
-- wit = Top.wit_of_r1cs (map fromIntegral input_vals) r1cs
in case IntMap.lookup 1000000 wit of
-- Nothing -> putStr $ show $ last (r1cs_clauses r1cs)
-- Just v -> putStr $ show v ++ (show $ last (r1cs_clauses r1cs))
| null |
https://raw.githubusercontent.com/gstew5/snarkl/d6ce72b13e370d2965bb226f28a1135269e7c198/src/examples/Keccak.hs
|
haskell
|
| Array 'a'
Allocate local array variables [b], [c], [d].
\theta step
\iota step
round constants
rotate index 'i'
by 'n' (mod lane width)
test_full n
test_interp n
test_r1cs n
$ show
$ last (r1cs_clauses r1cs)
First compile to R1CS , then generate witness .
test_wit n
wit = Top.wit_of_r1cs (map fromIntegral input_vals) r1cs
Nothing -> putStr $ show $ last (r1cs_clauses r1cs)
Just v -> putStr $ show v ++ (show $ last (r1cs_clauses r1cs))
|
# LANGUAGE RebindableSyntax , DataKinds #
module Keccak where
import qualified Data.Map.Strict as Map
import Data.Bits hiding (xor)
import Prelude hiding
( (>>)
, (>>=)
, (+)
, (-)
, (*)
, (/)
, (&&)
, not
, return
, fromRational
, negate
)
import qualified Prelude as P
import SyntaxMonad
import Syntax
import TExpr
import Toplevel
num_lanes :: Int
num_lanes = (P.*) 5 5
ln_width :: Int
ln_width = 32
| ' i'th bit of round constant
-> Comp 'TUnit
round1 rc a
b <- arr3 5 5 ln_width
; c <- arr2 5 ln_width
; d <- arr2 5 ln_width
Initialize arrays .
; forall3 ([0..4],[0..4],[0..dec ln_width])
(\i j k -> set3 (b,i,j,k) false)
; forall2 ([0..4],[0..dec ln_width]) (\i j -> set2 (c,i,j) false)
; forall2 ([0..4],[0..dec ln_width]) (\i j -> set2 (d,i,j) false)
; forall2 ([0..4],[0..dec ln_width]) (\x i ->
do q <- get3 (a,x,0,i)
u <- get3 (a,x,1,i)
v <- get3 (a,x,2,i)
w <- get3 (a,x,3,i)
z <- get3 (a,x,4,i)
set2 (c,x,i) $ q `xor` u `xor` v `xor` w `xor` z)
; forall2 ([0..4],[0..dec ln_width]) (\x i ->
do q <- get2 (c,dec x `mod` 5,i)
u <- get2 (c,inc x `mod` 5,rot_index i 1)
set2 (d,x,i) $ q `xor` u)
; forall3 ([0..4],[0..4],[0..dec ln_width]) (\x y i ->
do q <- get3 (a,x,y,i)
u <- get2 (d,x,i)
set3 (a,x,y,i) $ q `xor` u)
\rho and \pi steps
; forall3 ([0..4],[0..4],[0..dec ln_width]) (\x y i ->
do q <- get3 (a,x,y,rot_index i (rot_tbl x y))
set3 (b,y,((P.+) ((P.*) 2 x) ((P.*) 3 y)) `mod` 5,i) q)
\chi step
; forall3 ([0..4],[0..4],[0..dec ln_width]) (\x y i ->
do q <- get3 (b,x,y,i)
u <- get3 (b,inc x `mod` 5,y,i)
v <- get3 (b,(inc . inc) x `mod` 5,y,i)
set3 (a,x,y,i) $ q `xor` (not u && v))
; forall [0..dec ln_width] (\i ->
do q <- get3 (a,0,0,i)
set3 (a,0,0,i) (q `xor` rc i))
}
round_consts :: [Integer]
round_consts
= [ 0x00000001
, 0x00008082
, 0x0000808a
, 0x80008000
, 0x0000808b
, 0x80000001
, 0x80008081
, 0x00008009
, 0x0000008a
, 0x00000088
, 0x80008009
, 0x8000000a
, 0x8000808b
, 0x800000000000008b
, 0x8000000000008089
, 0x8000000000008003
, 0x8000000000008002
, 0x8000000000000080
, 0x800000000000800a
, 0x800000008000000a
, 0x8000000080008081
, 0x8000000080008080
, 0x0000000080000001
, 0x8000000080008008
]
-> Int
rot_index i n = ((P.-) i n) `mod` ln_width
rot_tbl x y
= let m = Map.fromList $
[ ((3,2), 25), ((4,2), 39), ((0,2), 3), ((1,2), 10), ((2,2), 43)
, ((3,1), 55), ((4,1), 20), ((0,1), 36), ((1,1), 44), ((2,1), 6)
, ((3,0), 28), ((4,0), 27), ((0,0), 0), ((1,0), 1), ((2,0), 62)
, ((3,4), 56), ((4,4), 14), ((0,4), 18), ((1,4), 2), ((2,4), 61)
, ((3,3), 21), ((4,3), 8), ((0,3), 41), ((1,3), 45), ((2,3), 15) ]
in case Map.lookup (x,y) m of
Nothing -> error $ show (x,y) ++ " not a valid rotation key"
Just r -> r
trunc :: Integer -> Int
trunc rc
= fromIntegral rc
.&. dec (truncate (2**fromIntegral ln_width :: Double) :: Int)
get_round_bit :: Int -> Int -> TExp 'TBool Rational
get_round_bit round_i bit_i
= let the_bit = round_consts !! round_i
.&. truncate (2**fromIntegral bit_i :: Double)
in case the_bit > 0 of
False -> false
True -> true
keccak_f1 num_rounds a
= forall [0..dec num_rounds] (\round_i ->
round1 (\bit_i -> get_round_bit round_i bit_i) a)
num_rounds = 12 + 2l , where 2^l = ln_width
keccak1 num_rounds
= do { a <- input_arr3 5 5 ln_width
; keccak_f1 num_rounds a
; b <- arr 1
; set (b, 0) false
; forall3 ([0..4], [0..4], [0..dec ln_width]) (\i j k -> do
a_val <- get3 (a, i, j, k)
b_val <- get (b, 0)
set (b, 0) (a_val `xor` b_val))
; get (b, 0)
}
input_vals = go ((P.*) num_lanes ln_width)
where go :: Int -> [Int]
go 0 = []
go n | odd n = 0 : go (dec n)
go n | otherwise = 1 : go (dec n)
= Top.test ( keccak1 n , input_vals , ( 1::Integer ) )
= Top.texp_interp ( keccak1 n ) ( map fromIntegral input_vals )
= let ( nv , in_vars , e ) = Top.texp_of_comp ( keccak1 n )
r1cs =
in putStrLn
= let ( nv , in_vars , e ) = Top.texp_of_comp ( keccak1 n )
r1cs =
in case IntMap.lookup 1000000 wit of
|
98300d09d5512e3a047bf08cc23d68bc767431e65c280518bb007ba680de2f31
|
haskell-tls/hs-tls
|
State.hs
|
{-# LANGUAGE Rank2Types #-}
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE GeneralizedNewtypeDeriving #
-- |
Module : Network . TLS.State
-- License : BSD-style
Maintainer : < >
-- Stability : experimental
-- Portability : unknown
--
the State module contains calls related to state initialization / manipulation
-- which is use by the Receiving module and the Sending module.
--
module Network.TLS.State
( TLSState(..)
, TLSSt
, runTLSState
, newTLSState
, withTLSRNG
, updateVerifiedData
, finishHandshakeTypeMaterial
, finishHandshakeMaterial
, certVerifyHandshakeTypeMaterial
, certVerifyHandshakeMaterial
, setVersion
, setVersionIfUnset
, getVersion
, getVersionWithDefault
, setSecureRenegotiation
, getSecureRenegotiation
, setExtensionALPN
, getExtensionALPN
, setNegotiatedProtocol
, getNegotiatedProtocol
, setClientALPNSuggest
, getClientALPNSuggest
, setClientEcPointFormatSuggest
, getClientEcPointFormatSuggest
, getClientCertificateChain
, setClientCertificateChain
, setClientSNI
, getClientSNI
, getVerifiedData
, setSession
, getSession
, isSessionResuming
, isClientContext
, setExporterMasterSecret
, getExporterMasterSecret
, setTLS13KeyShare
, getTLS13KeyShare
, setTLS13PreSharedKey
, getTLS13PreSharedKey
, setTLS13HRR
, getTLS13HRR
, setTLS13Cookie
, getTLS13Cookie
, setClientSupportsPHA
, getClientSupportsPHA
-- * random
, genRandom
, withRNG
) where
import Network.TLS.Imports
import Network.TLS.Struct
import Network.TLS.Struct13
import Network.TLS.RNG
import Network.TLS.Types (Role(..), HostName)
import Network.TLS.Wire (GetContinuation)
import Network.TLS.Extension
import qualified Data.ByteString as B
import Control.Monad.State.Strict
import Network.TLS.ErrT
import Crypto.Random
import Data.X509 (CertificateChain)
data TLSState = TLSState
{ stSession :: Session
, stSessionResuming :: Bool
, stSecureRenegotiation :: Bool -- RFC 5746
, stClientVerifiedData :: ByteString -- RFC 5746
, stServerVerifiedData :: ByteString -- RFC 5746
, stExtensionALPN :: Bool -- RFC 7301
, stHandshakeRecordCont :: Maybe (GetContinuation (HandshakeType, ByteString))
ALPN protocol
, stHandshakeRecordCont13 :: Maybe (GetContinuation (HandshakeType13, ByteString))
, stClientALPNSuggest :: Maybe [B.ByteString]
, stClientGroupSuggest :: Maybe [Group]
, stClientEcPointFormatSuggest :: Maybe [EcPointFormat]
, stClientCertificateChain :: Maybe CertificateChain
, stClientSNI :: Maybe HostName
, stRandomGen :: StateRNG
, stVersion :: Maybe Version
, stClientContext :: Role
, stTLS13KeyShare :: Maybe KeyShare
, stTLS13PreSharedKey :: Maybe PreSharedKey
, stTLS13HRR :: !Bool
, stTLS13Cookie :: Maybe Cookie
, stExporterMasterSecret :: Maybe ByteString -- TLS 1.3
Post - Handshake Authentication ( TLS 1.3 )
}
newtype TLSSt a = TLSSt { runTLSSt :: ErrT TLSError (State TLSState) a }
deriving (Monad, MonadError TLSError, Functor, Applicative)
instance MonadState TLSState TLSSt where
put x = TLSSt (lift $ put x)
get = TLSSt (lift get)
state f = TLSSt (lift $ state f)
runTLSState :: TLSSt a -> TLSState -> (Either TLSError a, TLSState)
runTLSState f st = runState (runErrT (runTLSSt f)) st
newTLSState :: StateRNG -> Role -> TLSState
newTLSState rng clientContext = TLSState
{ stSession = Session Nothing
, stSessionResuming = False
, stSecureRenegotiation = False
, stClientVerifiedData = B.empty
, stServerVerifiedData = B.empty
, stExtensionALPN = False
, stHandshakeRecordCont = Nothing
, stHandshakeRecordCont13 = Nothing
, stNegotiatedProtocol = Nothing
, stClientALPNSuggest = Nothing
, stClientGroupSuggest = Nothing
, stClientEcPointFormatSuggest = Nothing
, stClientCertificateChain = Nothing
, stClientSNI = Nothing
, stRandomGen = rng
, stVersion = Nothing
, stClientContext = clientContext
, stTLS13KeyShare = Nothing
, stTLS13PreSharedKey = Nothing
, stTLS13HRR = False
, stTLS13Cookie = Nothing
, stExporterMasterSecret = Nothing
, stClientSupportsPHA = False
}
updateVerifiedData :: Role -> ByteString -> TLSSt ()
updateVerifiedData sending bs = do
cc <- isClientContext
if cc /= sending
then modify (\st -> st { stServerVerifiedData = bs })
else modify (\st -> st { stClientVerifiedData = bs })
finishHandshakeTypeMaterial :: HandshakeType -> Bool
finishHandshakeTypeMaterial HandshakeType_ClientHello = True
finishHandshakeTypeMaterial HandshakeType_ServerHello = True
finishHandshakeTypeMaterial HandshakeType_Certificate = True
finishHandshakeTypeMaterial HandshakeType_HelloRequest = False
finishHandshakeTypeMaterial HandshakeType_ServerHelloDone = True
finishHandshakeTypeMaterial HandshakeType_ClientKeyXchg = True
finishHandshakeTypeMaterial HandshakeType_ServerKeyXchg = True
finishHandshakeTypeMaterial HandshakeType_CertRequest = True
finishHandshakeTypeMaterial HandshakeType_CertVerify = True
finishHandshakeTypeMaterial HandshakeType_Finished = True
finishHandshakeMaterial :: Handshake -> Bool
finishHandshakeMaterial = finishHandshakeTypeMaterial . typeOfHandshake
certVerifyHandshakeTypeMaterial :: HandshakeType -> Bool
certVerifyHandshakeTypeMaterial HandshakeType_ClientHello = True
certVerifyHandshakeTypeMaterial HandshakeType_ServerHello = True
certVerifyHandshakeTypeMaterial HandshakeType_Certificate = True
certVerifyHandshakeTypeMaterial HandshakeType_HelloRequest = False
certVerifyHandshakeTypeMaterial HandshakeType_ServerHelloDone = True
certVerifyHandshakeTypeMaterial HandshakeType_ClientKeyXchg = True
certVerifyHandshakeTypeMaterial HandshakeType_ServerKeyXchg = True
certVerifyHandshakeTypeMaterial HandshakeType_CertRequest = True
certVerifyHandshakeTypeMaterial HandshakeType_CertVerify = False
certVerifyHandshakeTypeMaterial HandshakeType_Finished = False
certVerifyHandshakeMaterial :: Handshake -> Bool
certVerifyHandshakeMaterial = certVerifyHandshakeTypeMaterial . typeOfHandshake
setSession :: Session -> Bool -> TLSSt ()
setSession session resuming = modify (\st -> st { stSession = session, stSessionResuming = resuming })
getSession :: TLSSt Session
getSession = gets stSession
isSessionResuming :: TLSSt Bool
isSessionResuming = gets stSessionResuming
setVersion :: Version -> TLSSt ()
setVersion ver = modify (\st -> st { stVersion = Just ver })
setVersionIfUnset :: Version -> TLSSt ()
setVersionIfUnset ver = modify maybeSet
where maybeSet st = case stVersion st of
Nothing -> st { stVersion = Just ver }
Just _ -> st
getVersion :: TLSSt Version
getVersion = fromMaybe (error "internal error: version hasn't been set yet") <$> gets stVersion
getVersionWithDefault :: Version -> TLSSt Version
getVersionWithDefault defaultVer = fromMaybe defaultVer <$> gets stVersion
setSecureRenegotiation :: Bool -> TLSSt ()
setSecureRenegotiation b = modify (\st -> st { stSecureRenegotiation = b })
getSecureRenegotiation :: TLSSt Bool
getSecureRenegotiation = gets stSecureRenegotiation
setExtensionALPN :: Bool -> TLSSt ()
setExtensionALPN b = modify (\st -> st { stExtensionALPN = b })
getExtensionALPN :: TLSSt Bool
getExtensionALPN = gets stExtensionALPN
setNegotiatedProtocol :: B.ByteString -> TLSSt ()
setNegotiatedProtocol s = modify (\st -> st { stNegotiatedProtocol = Just s })
getNegotiatedProtocol :: TLSSt (Maybe B.ByteString)
getNegotiatedProtocol = gets stNegotiatedProtocol
setClientALPNSuggest :: [B.ByteString] -> TLSSt ()
setClientALPNSuggest ps = modify (\st -> st { stClientALPNSuggest = Just ps})
getClientALPNSuggest :: TLSSt (Maybe [B.ByteString])
getClientALPNSuggest = gets stClientALPNSuggest
setClientEcPointFormatSuggest :: [EcPointFormat] -> TLSSt ()
setClientEcPointFormatSuggest epf = modify (\st -> st { stClientEcPointFormatSuggest = Just epf})
getClientEcPointFormatSuggest :: TLSSt (Maybe [EcPointFormat])
getClientEcPointFormatSuggest = gets stClientEcPointFormatSuggest
setClientCertificateChain :: CertificateChain -> TLSSt ()
setClientCertificateChain s = modify (\st -> st { stClientCertificateChain = Just s })
getClientCertificateChain :: TLSSt (Maybe CertificateChain)
getClientCertificateChain = gets stClientCertificateChain
setClientSNI :: HostName -> TLSSt ()
setClientSNI hn = modify (\st -> st { stClientSNI = Just hn })
getClientSNI :: TLSSt (Maybe HostName)
getClientSNI = gets stClientSNI
getVerifiedData :: Role -> TLSSt ByteString
getVerifiedData client = gets (if client == ClientRole then stClientVerifiedData else stServerVerifiedData)
isClientContext :: TLSSt Role
isClientContext = gets stClientContext
genRandom :: Int -> TLSSt ByteString
genRandom n = do
withRNG (getRandomBytes n)
withRNG :: MonadPseudoRandom StateRNG a -> TLSSt a
withRNG f = do
st <- get
let (a,rng') = withTLSRNG (stRandomGen st) f
put (st { stRandomGen = rng' })
return a
setExporterMasterSecret :: ByteString -> TLSSt ()
setExporterMasterSecret key = modify (\st -> st { stExporterMasterSecret = Just key })
getExporterMasterSecret :: TLSSt (Maybe ByteString)
getExporterMasterSecret = gets stExporterMasterSecret
setTLS13KeyShare :: Maybe KeyShare -> TLSSt ()
setTLS13KeyShare mks = modify (\st -> st { stTLS13KeyShare = mks })
getTLS13KeyShare :: TLSSt (Maybe KeyShare)
getTLS13KeyShare = gets stTLS13KeyShare
setTLS13PreSharedKey :: Maybe PreSharedKey -> TLSSt ()
setTLS13PreSharedKey mpsk = modify (\st -> st { stTLS13PreSharedKey = mpsk })
getTLS13PreSharedKey :: TLSSt (Maybe PreSharedKey)
getTLS13PreSharedKey = gets stTLS13PreSharedKey
setTLS13HRR :: Bool -> TLSSt ()
setTLS13HRR b = modify (\st -> st { stTLS13HRR = b })
getTLS13HRR :: TLSSt Bool
getTLS13HRR = gets stTLS13HRR
setTLS13Cookie :: Maybe Cookie -> TLSSt ()
setTLS13Cookie mcookie = modify (\st -> st { stTLS13Cookie = mcookie })
getTLS13Cookie :: TLSSt (Maybe Cookie)
getTLS13Cookie = gets stTLS13Cookie
setClientSupportsPHA :: Bool -> TLSSt ()
setClientSupportsPHA b = modify (\st -> st { stClientSupportsPHA = b })
getClientSupportsPHA :: TLSSt Bool
getClientSupportsPHA = gets stClientSupportsPHA
| null |
https://raw.githubusercontent.com/haskell-tls/hs-tls/c2fc6f308bb7144d99dfe8b5431144ab5bd49ceb/core/Network/TLS/State.hs
|
haskell
|
# LANGUAGE Rank2Types #
|
License : BSD-style
Stability : experimental
Portability : unknown
which is use by the Receiving module and the Sending module.
* random
RFC 5746
RFC 5746
RFC 5746
RFC 7301
TLS 1.3
|
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE GeneralizedNewtypeDeriving #
Module : Network . TLS.State
Maintainer : < >
the State module contains calls related to state initialization / manipulation
module Network.TLS.State
( TLSState(..)
, TLSSt
, runTLSState
, newTLSState
, withTLSRNG
, updateVerifiedData
, finishHandshakeTypeMaterial
, finishHandshakeMaterial
, certVerifyHandshakeTypeMaterial
, certVerifyHandshakeMaterial
, setVersion
, setVersionIfUnset
, getVersion
, getVersionWithDefault
, setSecureRenegotiation
, getSecureRenegotiation
, setExtensionALPN
, getExtensionALPN
, setNegotiatedProtocol
, getNegotiatedProtocol
, setClientALPNSuggest
, getClientALPNSuggest
, setClientEcPointFormatSuggest
, getClientEcPointFormatSuggest
, getClientCertificateChain
, setClientCertificateChain
, setClientSNI
, getClientSNI
, getVerifiedData
, setSession
, getSession
, isSessionResuming
, isClientContext
, setExporterMasterSecret
, getExporterMasterSecret
, setTLS13KeyShare
, getTLS13KeyShare
, setTLS13PreSharedKey
, getTLS13PreSharedKey
, setTLS13HRR
, getTLS13HRR
, setTLS13Cookie
, getTLS13Cookie
, setClientSupportsPHA
, getClientSupportsPHA
, genRandom
, withRNG
) where
import Network.TLS.Imports
import Network.TLS.Struct
import Network.TLS.Struct13
import Network.TLS.RNG
import Network.TLS.Types (Role(..), HostName)
import Network.TLS.Wire (GetContinuation)
import Network.TLS.Extension
import qualified Data.ByteString as B
import Control.Monad.State.Strict
import Network.TLS.ErrT
import Crypto.Random
import Data.X509 (CertificateChain)
data TLSState = TLSState
{ stSession :: Session
, stSessionResuming :: Bool
, stHandshakeRecordCont :: Maybe (GetContinuation (HandshakeType, ByteString))
ALPN protocol
, stHandshakeRecordCont13 :: Maybe (GetContinuation (HandshakeType13, ByteString))
, stClientALPNSuggest :: Maybe [B.ByteString]
, stClientGroupSuggest :: Maybe [Group]
, stClientEcPointFormatSuggest :: Maybe [EcPointFormat]
, stClientCertificateChain :: Maybe CertificateChain
, stClientSNI :: Maybe HostName
, stRandomGen :: StateRNG
, stVersion :: Maybe Version
, stClientContext :: Role
, stTLS13KeyShare :: Maybe KeyShare
, stTLS13PreSharedKey :: Maybe PreSharedKey
, stTLS13HRR :: !Bool
, stTLS13Cookie :: Maybe Cookie
Post - Handshake Authentication ( TLS 1.3 )
}
newtype TLSSt a = TLSSt { runTLSSt :: ErrT TLSError (State TLSState) a }
deriving (Monad, MonadError TLSError, Functor, Applicative)
instance MonadState TLSState TLSSt where
put x = TLSSt (lift $ put x)
get = TLSSt (lift get)
state f = TLSSt (lift $ state f)
runTLSState :: TLSSt a -> TLSState -> (Either TLSError a, TLSState)
runTLSState f st = runState (runErrT (runTLSSt f)) st
newTLSState :: StateRNG -> Role -> TLSState
newTLSState rng clientContext = TLSState
{ stSession = Session Nothing
, stSessionResuming = False
, stSecureRenegotiation = False
, stClientVerifiedData = B.empty
, stServerVerifiedData = B.empty
, stExtensionALPN = False
, stHandshakeRecordCont = Nothing
, stHandshakeRecordCont13 = Nothing
, stNegotiatedProtocol = Nothing
, stClientALPNSuggest = Nothing
, stClientGroupSuggest = Nothing
, stClientEcPointFormatSuggest = Nothing
, stClientCertificateChain = Nothing
, stClientSNI = Nothing
, stRandomGen = rng
, stVersion = Nothing
, stClientContext = clientContext
, stTLS13KeyShare = Nothing
, stTLS13PreSharedKey = Nothing
, stTLS13HRR = False
, stTLS13Cookie = Nothing
, stExporterMasterSecret = Nothing
, stClientSupportsPHA = False
}
updateVerifiedData :: Role -> ByteString -> TLSSt ()
updateVerifiedData sending bs = do
cc <- isClientContext
if cc /= sending
then modify (\st -> st { stServerVerifiedData = bs })
else modify (\st -> st { stClientVerifiedData = bs })
finishHandshakeTypeMaterial :: HandshakeType -> Bool
finishHandshakeTypeMaterial HandshakeType_ClientHello = True
finishHandshakeTypeMaterial HandshakeType_ServerHello = True
finishHandshakeTypeMaterial HandshakeType_Certificate = True
finishHandshakeTypeMaterial HandshakeType_HelloRequest = False
finishHandshakeTypeMaterial HandshakeType_ServerHelloDone = True
finishHandshakeTypeMaterial HandshakeType_ClientKeyXchg = True
finishHandshakeTypeMaterial HandshakeType_ServerKeyXchg = True
finishHandshakeTypeMaterial HandshakeType_CertRequest = True
finishHandshakeTypeMaterial HandshakeType_CertVerify = True
finishHandshakeTypeMaterial HandshakeType_Finished = True
finishHandshakeMaterial :: Handshake -> Bool
finishHandshakeMaterial = finishHandshakeTypeMaterial . typeOfHandshake
certVerifyHandshakeTypeMaterial :: HandshakeType -> Bool
certVerifyHandshakeTypeMaterial HandshakeType_ClientHello = True
certVerifyHandshakeTypeMaterial HandshakeType_ServerHello = True
certVerifyHandshakeTypeMaterial HandshakeType_Certificate = True
certVerifyHandshakeTypeMaterial HandshakeType_HelloRequest = False
certVerifyHandshakeTypeMaterial HandshakeType_ServerHelloDone = True
certVerifyHandshakeTypeMaterial HandshakeType_ClientKeyXchg = True
certVerifyHandshakeTypeMaterial HandshakeType_ServerKeyXchg = True
certVerifyHandshakeTypeMaterial HandshakeType_CertRequest = True
certVerifyHandshakeTypeMaterial HandshakeType_CertVerify = False
certVerifyHandshakeTypeMaterial HandshakeType_Finished = False
certVerifyHandshakeMaterial :: Handshake -> Bool
certVerifyHandshakeMaterial = certVerifyHandshakeTypeMaterial . typeOfHandshake
setSession :: Session -> Bool -> TLSSt ()
setSession session resuming = modify (\st -> st { stSession = session, stSessionResuming = resuming })
getSession :: TLSSt Session
getSession = gets stSession
isSessionResuming :: TLSSt Bool
isSessionResuming = gets stSessionResuming
setVersion :: Version -> TLSSt ()
setVersion ver = modify (\st -> st { stVersion = Just ver })
setVersionIfUnset :: Version -> TLSSt ()
setVersionIfUnset ver = modify maybeSet
where maybeSet st = case stVersion st of
Nothing -> st { stVersion = Just ver }
Just _ -> st
getVersion :: TLSSt Version
getVersion = fromMaybe (error "internal error: version hasn't been set yet") <$> gets stVersion
getVersionWithDefault :: Version -> TLSSt Version
getVersionWithDefault defaultVer = fromMaybe defaultVer <$> gets stVersion
setSecureRenegotiation :: Bool -> TLSSt ()
setSecureRenegotiation b = modify (\st -> st { stSecureRenegotiation = b })
getSecureRenegotiation :: TLSSt Bool
getSecureRenegotiation = gets stSecureRenegotiation
setExtensionALPN :: Bool -> TLSSt ()
setExtensionALPN b = modify (\st -> st { stExtensionALPN = b })
getExtensionALPN :: TLSSt Bool
getExtensionALPN = gets stExtensionALPN
setNegotiatedProtocol :: B.ByteString -> TLSSt ()
setNegotiatedProtocol s = modify (\st -> st { stNegotiatedProtocol = Just s })
getNegotiatedProtocol :: TLSSt (Maybe B.ByteString)
getNegotiatedProtocol = gets stNegotiatedProtocol
setClientALPNSuggest :: [B.ByteString] -> TLSSt ()
setClientALPNSuggest ps = modify (\st -> st { stClientALPNSuggest = Just ps})
getClientALPNSuggest :: TLSSt (Maybe [B.ByteString])
getClientALPNSuggest = gets stClientALPNSuggest
setClientEcPointFormatSuggest :: [EcPointFormat] -> TLSSt ()
setClientEcPointFormatSuggest epf = modify (\st -> st { stClientEcPointFormatSuggest = Just epf})
getClientEcPointFormatSuggest :: TLSSt (Maybe [EcPointFormat])
getClientEcPointFormatSuggest = gets stClientEcPointFormatSuggest
setClientCertificateChain :: CertificateChain -> TLSSt ()
setClientCertificateChain s = modify (\st -> st { stClientCertificateChain = Just s })
getClientCertificateChain :: TLSSt (Maybe CertificateChain)
getClientCertificateChain = gets stClientCertificateChain
setClientSNI :: HostName -> TLSSt ()
setClientSNI hn = modify (\st -> st { stClientSNI = Just hn })
getClientSNI :: TLSSt (Maybe HostName)
getClientSNI = gets stClientSNI
getVerifiedData :: Role -> TLSSt ByteString
getVerifiedData client = gets (if client == ClientRole then stClientVerifiedData else stServerVerifiedData)
isClientContext :: TLSSt Role
isClientContext = gets stClientContext
genRandom :: Int -> TLSSt ByteString
genRandom n = do
withRNG (getRandomBytes n)
withRNG :: MonadPseudoRandom StateRNG a -> TLSSt a
withRNG f = do
st <- get
let (a,rng') = withTLSRNG (stRandomGen st) f
put (st { stRandomGen = rng' })
return a
setExporterMasterSecret :: ByteString -> TLSSt ()
setExporterMasterSecret key = modify (\st -> st { stExporterMasterSecret = Just key })
getExporterMasterSecret :: TLSSt (Maybe ByteString)
getExporterMasterSecret = gets stExporterMasterSecret
setTLS13KeyShare :: Maybe KeyShare -> TLSSt ()
setTLS13KeyShare mks = modify (\st -> st { stTLS13KeyShare = mks })
getTLS13KeyShare :: TLSSt (Maybe KeyShare)
getTLS13KeyShare = gets stTLS13KeyShare
setTLS13PreSharedKey :: Maybe PreSharedKey -> TLSSt ()
setTLS13PreSharedKey mpsk = modify (\st -> st { stTLS13PreSharedKey = mpsk })
getTLS13PreSharedKey :: TLSSt (Maybe PreSharedKey)
getTLS13PreSharedKey = gets stTLS13PreSharedKey
setTLS13HRR :: Bool -> TLSSt ()
setTLS13HRR b = modify (\st -> st { stTLS13HRR = b })
getTLS13HRR :: TLSSt Bool
getTLS13HRR = gets stTLS13HRR
setTLS13Cookie :: Maybe Cookie -> TLSSt ()
setTLS13Cookie mcookie = modify (\st -> st { stTLS13Cookie = mcookie })
getTLS13Cookie :: TLSSt (Maybe Cookie)
getTLS13Cookie = gets stTLS13Cookie
setClientSupportsPHA :: Bool -> TLSSt ()
setClientSupportsPHA b = modify (\st -> st { stClientSupportsPHA = b })
getClientSupportsPHA :: TLSSt Bool
getClientSupportsPHA = gets stClientSupportsPHA
|
a9c3d0b9830dba68c10a4779659c31bd92c3f7da46cfe424e6336840b536105f
|
clojurewerkz/money
|
json.clj
|
This source code is dual - licensed under the Apache License , version
2.0 , and the Eclipse Public License , version 1.0 .
;;
;; The APL v2.0:
;;
;; ----------------------------------------------------------------------------------
Copyright ( c ) 2012 - 2014 , , and the ClojureWerkz Team
;;
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.
;; ----------------------------------------------------------------------------------
;;
The EPL v1.0 :
;;
;; ----------------------------------------------------------------------------------
Copyright ( c ) 2012 - 2014 , , and the ClojureWerkz Team .
;; All rights reserved.
;;
;; This program and the accompanying materials are made available under the terms of
the Eclipse Public License Version 1.0 ,
;; which accompanies this distribution and is available at
-v10.html .
;; ----------------------------------------------------------------------------------
(ns clojurewerkz.money.json
"Provides Cheshire integration.
org.joda.money.Money instances are serialized to strings with human-readable
amounts following ISO-4217 currency codes.
Currency units are serialized to strings by taking their ISO-4217 codes."
(:require cheshire.generate
[clojurewerkz.money.amounts :as ma])
(:import [org.joda.money Money CurrencyUnit]
[com.fasterxml.jackson.core.json WriterBasedJsonGenerator]))
(defn- encode-money
"Encodes an instance of org.joda.money.Money as a string with an ISO-4217
currency code followed by a human-readable amount."
^String
[^Money m]
(format "%s %s" (.getCode (ma/currency-of m)) (.getAmount m)))
(cheshire.generate/add-encoder CurrencyUnit
(fn [^CurrencyUnit cu ^WriterBasedJsonGenerator generator]
(.writeString generator (.getCode cu))))
(cheshire.generate/add-encoder Money
(fn [^Money m ^WriterBasedJsonGenerator generator]
(.writeString generator (encode-money m))))
| null |
https://raw.githubusercontent.com/clojurewerkz/money/734b99e2c8d4617e69b20a68d1a1760262d7786f/src/clojure/clojurewerkz/money/json.clj
|
clojure
|
The APL v2.0:
----------------------------------------------------------------------------------
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.
----------------------------------------------------------------------------------
----------------------------------------------------------------------------------
All rights reserved.
This program and the accompanying materials are made available under the terms of
which accompanies this distribution and is available at
----------------------------------------------------------------------------------
|
This source code is dual - licensed under the Apache License , version
2.0 , and the Eclipse Public License , version 1.0 .
Copyright ( c ) 2012 - 2014 , , and the ClojureWerkz Team
distributed under the License is distributed on an " AS IS " BASIS ,
The EPL v1.0 :
Copyright ( c ) 2012 - 2014 , , and the ClojureWerkz Team .
the Eclipse Public License Version 1.0 ,
-v10.html .
(ns clojurewerkz.money.json
"Provides Cheshire integration.
org.joda.money.Money instances are serialized to strings with human-readable
amounts following ISO-4217 currency codes.
Currency units are serialized to strings by taking their ISO-4217 codes."
(:require cheshire.generate
[clojurewerkz.money.amounts :as ma])
(:import [org.joda.money Money CurrencyUnit]
[com.fasterxml.jackson.core.json WriterBasedJsonGenerator]))
(defn- encode-money
"Encodes an instance of org.joda.money.Money as a string with an ISO-4217
currency code followed by a human-readable amount."
^String
[^Money m]
(format "%s %s" (.getCode (ma/currency-of m)) (.getAmount m)))
(cheshire.generate/add-encoder CurrencyUnit
(fn [^CurrencyUnit cu ^WriterBasedJsonGenerator generator]
(.writeString generator (.getCode cu))))
(cheshire.generate/add-encoder Money
(fn [^Money m ^WriterBasedJsonGenerator generator]
(.writeString generator (encode-money m))))
|
dd00db943f308633aa1b44e83c57796cee08ffb5dfed1677fbd98fda6a7cf29f
|
inria-parkas/sundialsml
|
nvector_parallel_top.ml
|
(* Automatically generated file - don't edit! See the Makefile. *)
Sundials_top.install_printers [
"Nvector_parallel.pp";
];;
| null |
https://raw.githubusercontent.com/inria-parkas/sundialsml/0c46b0c6c067677af6ef8006260b9e697cc0562b/src/nvectors/nvector_parallel_top.ml
|
ocaml
|
Automatically generated file - don't edit! See the Makefile.
|
Sundials_top.install_printers [
"Nvector_parallel.pp";
];;
|
7cd5dab67b107d2029ed4c54b9fbfa07aac1c533324b4071a22d76681f4a9903
|
yuriy-chumak/ol
|
math-extra.scm
|
;;;
;;; Owl math module, things after basic arithmetic
;;;
; todo - /~carlp/PDF/complexity12.pdf
(define-library (owl math-extra)
(export
isqrt iroot iexpt
ilog ;; integer log a b
expt expt-mod
ncr npr
!
dlog dlog-simple
fib
histogram
bisect
; inv-mod mod-solve
; r7rs
exact-integer-sqrt ;; n → m r, m^2 + r = n
rationalize
)
(import
(scheme core)
(scheme list)
(owl math)
(owl iff)
(owl list-extra)
(owl sort)
(only (otus async) por por*)
(owl ff))
(begin
(define ncar car)
(define ncdr cdr)
(define-syntax lets (syntax-rules () ((lets . stuff) (let* . stuff)))) ; TEMP
;;;
;;; SQUARE ROOTS (stub)
;;;
; fixme, did not find a good integer sqrt algorithm which would
; work with these numerals, so i rolled my own as a quick substitute
; bench later
Величина положительного числа в битах ( f - сколько , " перенос " )
(define (nbits n f)
(cond
((eq? n 0) f)
((eq? (type n) type-enum+)
(lets ((hi lo (vm:shr n 1)))
(nbits hi (nat+1 f))))
(else
(let ((tl (cdr n)))
(if (null? tl)
(nbits (car n) f)
(nbits tl (add f (vm:vsize))))))))
; приблизительное значение корня "для затравки"
(define (isqrt-init n)
(lets
((nb (nbits n 0))
(val (<< 1 (sub (>> nb 1) 1))))
(if (eq? (band nb 1) 0)
val
(lets ((val2 (<< val 1)) (sq (mul val2 val2)))
(if (<= sq n) val2 val)))))
(define (isqrt-fix hi bit n)
(if (eq? bit 0)
hi
(lets ((this (bor hi bit)) (mid (mul this this)))
(if (> mid n)
(isqrt-fix hi (>> bit 1) n)
(isqrt-fix this (>> bit 1) n)))))
; largest m where m^2 <= n
(define (isqrt n)
(cond
((eq? (type n) type-enum-) (sub 0 (isqrt (sub 0 n))))
((eq? (type n) type-int-) (sub 0 (isqrt (sub 0 n))))
((eq? n 0) 0)
((eq? n 1) 1)
(else
(let ((hi (isqrt-init n)))
(isqrt-fix hi (>> hi 1) n)))))
(define (exact-integer-sqrt n)
(let ((sq (isqrt n)))
(values sq (sub n (mul sq sq)))))
(assert (let*((x y (exact-integer-sqrt 17))) (list x y)) ===> '(4 1))
;; ------------------------------------
Bisect
(define (bisect-fini op lo hi pos last)
(cond
((= pos hi) last)
((op pos)
(let ((next (+ pos 1)))
(cond
((= next hi) pos)
((op next)
(bisect-fini op lo hi (+ next 1) pos))
(else
pos))))
((= pos lo)
#false)
(else
(bisect-fini op lo hi (- pos 1) last))))
; find the match or it's close neighbour by halving jump to correct direction
(define (bisect-seek op lo hi pos step last)
(cond
((eq? step 1)
(bisect-fini op lo hi pos last))
((op pos)
(bisect-seek op lo hi (+ pos step) (>> step 1) pos))
(else
(bisect-seek op lo hi (- pos step) (>> step 1) last))))
; search the last position in [lo ... hi-1] where op(x) is true
(define (bisect op lo hi)
(when (< lo hi)
(let*((range (- hi lo))
(step (max 1 (>> range 1))))
(bisect-seek op lo hi
(+ lo step) ;; move to middle of range
(max 1 (>> step 1)) ;; quarter step
#false))))
;;; exponentiation
; the usual O(lg n) exponentiation
(define (expt-loop ap p out)
(cond
((eq? p 0) out)
((eq? (band p 1) 0)
(expt-loop (* ap ap) (>> p 1) out))
(else
(expt-loop (* ap ap) (>> p 1) (* out ap)))))
(define (iexpt a p)
(cond
((eq? p 0) 1)
((eq? a 1) 1)
(else
(expt-loop a (- p 1) a))))
(define (iroot i n)
(cond
((eq? i 0) 0)
((eq? i 1) 1)
((eq? n 1) i)
((negative? i)
(complex 0 (iroot (* i -1) n)))
(else
(or
(bisect
(lambda (q) (<= (iexpt q n) i))
1 i)
1))))
(define (expt a b)
(cond
((eq? b 0) 1)
((eq? b 1) a)
((eq? b 2) (* a a))
((eq? (type b) type-enum+) (expt-loop a (sub b 1) a))
((eq? (type b) type-int+) (expt-loop a (sub b 1) a))
((eq? (type b) type-enum-) (/ 1 (expt a (negate b))))
((eq? (type b) type-int-) (/ 1 (expt a (negate b))))
((eq? (type b) type-rational)
;; inexact if cannot be solved exactly
(expt (iroot a (ref b 2)) (ref b 1)))
(else (big-bad-args 'expt a b))))
; (mod (expt a b) m) = (expt-mod a b m)
(define (expt-mod-loop ap p out m)
(cond
((eq? p 0) (mod out m))
((eq? (band p 1) 0)
(expt-mod-loop (rem (mul ap ap) m) (>> p 1) out m))
(else
(expt-mod-loop (rem (mul ap ap) m) (>> p 1)
(rem (mul out ap) m) m))))
(define (expt-mod a b m)
(cond
((eq? b 0) (mod 1 m))
((eq? b 1) (mod a m))
(else
(expt-mod-loop (rem a m) (sub b 1) a m))))
;;;
UNSORTED
;;;
; naive factorial
(define (fact-iter n o)
(if (eq? n 1)
o
(fact-iter (- n 1) (* o n))))
(define (! n)
(if (eq? n 0)
1
(fact-iter n 1)))
npr , number of permutations , naively n!/(n - m ) !
(define (npr-loop n m o)
(if (eq? m 0)
o
(npr-loop (- n 1) (- m 1) (* o n))))
(define (npr n m)
(if (eq? m 0)
0
(npr-loop (- n 1) (- m 1) n)))
ncr , number of combinations , n choose m , simply n!/(m!(n - m ) ! )
(define (ncr n m)
(if (< n m)
0
(let ((mp (- n m)))
(cond
((eq? m 0) 1)
((eq? mp 0) 1)
((> m mp) (ncr n mp))
(else (/ (npr n m) (! m)))))))
;;;
;;; Discrete Logarithm
;;;
;; find ? such that (expt-mod a ? n) = y
(define (dlp-naive y a n)
(let loop ((x 0) (seen empty))
(let ((this (expt-mod a x n)))
(cond
((= y this) x)
((iget seen this #false) #false) ; looped, not solvable
(else (loop (+ x 1) (iput seen this #true)))))))
;; like naive, but avoids useless multiplications and remainders
(define (dlp-simple y a n)
(let loop ((x 0) (v 1) (seen empty))
(cond
((>= v n) (loop x (rem v n) seen)) ; overflow
((= v y) x) ; solved
((iget seen v #false) #false) ; looped -> not solvable
(else ; try next
(loop (+ x 1) (* v a) (iput seen v v))))))
like simple , but has O(1 ) space at the cost of ~1.5x time
(define (dlp-th-step v a n)
(let ((v (* a v)))
(if (>= v n) (rem v n) v)))
(define (dlp-th y a n)
(if (= y 1)
0
(let loop ((x1 0) (v1 1) (x2 1) (v2 a) (step? #false))
(cond
((= v2 y) x2) ; hare finds carot \o/
((= v1 v2) #false) ; hare finds tortoise o_O
(step? ; fast hare is fast
(loop x1 v1 (+ x2 1) (dlp-th-step v2 a n) #false))
(else ; enhance
(loop
(+ x1 1) (dlp-th-step v1 a n)
(+ x2 1) (dlp-th-step v2 a n) #true))))))
' baby - step giant - step algorithm ( still not quite working properly )
(define (carless a b) (< (car a) (car b)))
(define (find-match b g pred)
(cond
((null? b) #false)
((null? g) #false)
((= (caar b) (caar g))
(let ((x (- (cdar g) (cdar b))))
(if (pred x)
x
(find-match (cdr b) (cdr g) pred))))
((< (caar b) (caar g)) (find-match (cdr b) g pred))
(else (find-match b (cdr g) pred))))
;; a silly mod to avoid some remainders
(define (bound x n)
(if (< x n) x (mod x n)))
;; this can be done much more efficiently incrementally, but just testing for correctness now
;; todo: use incremental construction and an iff to check for matches
(define (sqrt-ceil n)
(let ((s (isqrt n)))
(if (< (* s s) n)
(+ s 1)
s)))
;; y a n → x, such that y = a^x (mod n)
(define (dlog-shanks y a n)
(lets
((s (sqrt-ceil n))
(baby
(sort carless
( ya^r . r )
(lrange 5 1 s)))
;(sort carless
; (let loop ((ya (bound y n)) (r 0))
; (if (= r s)
; null
; (cons (cons ya r) (loop (bound (* ya a) n) (+ r 1))))))
)
(giant
(sort carless
(map (λ (t) (cons (expt-mod a (* s t) n) (bound (* t s) n)))
(lrange 1 1 (+ s 1))))))
;; i thought the match would be unique, but there seem to be many and some aren't solutions. not sure yet why.
(find-match baby giant (λ (x) (= y (expt-mod a x n))))))
(define dlog-simple dlp-th) ;; a simple reference implementation
(define dlog dlog-shanks)
;;; Fibonacci numbers
;; n → f_n, f_n+1
(define (fibs n)
(cond
((eq? n 0) (values 1 1))
((eq? n 1) (values 1 2))
(else
(lets
((a b (fibs (- (>> n 1) 1)))
(c (+ a b))
(aa (* a a)) (bb (* b b)) (cc (* c c)))
(if (eq? 0 (band n 1))
(values (+ aa bb) (- cc aa))
(values (- cc aa) (+ bb cc)))))))
one of the the relatively fast ways to compute fibonacci numbers
(define (fib n)
(if (< n 2)
n
(lets ((n sn (fibs (- n 1)))) n)))
( num ... ) [ n - bins ] - > ( ( n - in - bin . ) ... )
(define (histogram data . bins)
(if (null? data)
null
(lets
((l (length data))
(bins
(if (null? bins)
(min l (+ 1 (ilog2 l)))
(car bins)))
(data (sort < data))
(low (car data))
(high (fold (λ (last next) next) low data))
(bin (/ (- high low) bins)))
(let loop ((data data) (count 0) (limit (+ low bin)))
(cond
((null? data)
(list (cons count limit)))
((> (car data) limit)
(cons (cons count limit)
(loop data 0 (+ limit bin))))
(else
(loop (cdr data) (+ count 1) limit)))))))
(define rationalize
algorithm
(letrec
((rat1 ; x < y
(lambda (x y)
(cond
((> x 0) (rat2 x y))
((< y 0) (- (rat2 (- y) (- x))))
(else (if (and (exact? x) (exact? y)) 0 0.0)))))
(rat2 ; 0 < x < y
(lambda (x y)
(let ((fx (floor x)) (fy (floor y)))
(cond
((= fx x) fx)
((= fx fy) (+ fx (/ (rat2 (/ (- y fy)) (/ (- x fx))))))
(else (+ fx 1)))))))
(lambda (x e)
(unless (real? x) (runtime-error 'rationalize x))
(unless (real? e) (runtime-error 'rationalize e))
(let ((x (- x e)) (y (+ x e)))
(cond
((< x y) (rat1 x y))
((< y x) (rat1 y x))
(else x))))))
))
| null |
https://raw.githubusercontent.com/yuriy-chumak/ol/fa8fe7decb3c8995f391dd82c09190d665026b77/libraries/owl/math-extra.scm
|
scheme
|
Owl math module, things after basic arithmetic
todo - /~carlp/PDF/complexity12.pdf
integer log a b
inv-mod mod-solve
r7rs
n → m r, m^2 + r = n
TEMP
SQUARE ROOTS (stub)
fixme, did not find a good integer sqrt algorithm which would
work with these numerals, so i rolled my own as a quick substitute
bench later
приблизительное значение корня "для затравки"
largest m where m^2 <= n
------------------------------------
find the match or it's close neighbour by halving jump to correct direction
search the last position in [lo ... hi-1] where op(x) is true
move to middle of range
quarter step
exponentiation
the usual O(lg n) exponentiation
inexact if cannot be solved exactly
(mod (expt a b) m) = (expt-mod a b m)
naive factorial
Discrete Logarithm
find ? such that (expt-mod a ? n) = y
looped, not solvable
like naive, but avoids useless multiplications and remainders
overflow
solved
looped -> not solvable
try next
hare finds carot \o/
hare finds tortoise o_O
fast hare is fast
enhance
a silly mod to avoid some remainders
this can be done much more efficiently incrementally, but just testing for correctness now
todo: use incremental construction and an iff to check for matches
y a n → x, such that y = a^x (mod n)
(sort carless
(let loop ((ya (bound y n)) (r 0))
(if (= r s)
null
(cons (cons ya r) (loop (bound (* ya a) n) (+ r 1))))))
i thought the match would be unique, but there seem to be many and some aren't solutions. not sure yet why.
a simple reference implementation
Fibonacci numbers
n → f_n, f_n+1
x < y
0 < x < y
|
(define-library (owl math-extra)
(export
isqrt iroot iexpt
expt expt-mod
ncr npr
!
dlog dlog-simple
fib
histogram
bisect
rationalize
)
(import
(scheme core)
(scheme list)
(owl math)
(owl iff)
(owl list-extra)
(owl sort)
(only (otus async) por por*)
(owl ff))
(begin
(define ncar car)
(define ncdr cdr)
Величина положительного числа в битах ( f - сколько , " перенос " )
(define (nbits n f)
(cond
((eq? n 0) f)
((eq? (type n) type-enum+)
(lets ((hi lo (vm:shr n 1)))
(nbits hi (nat+1 f))))
(else
(let ((tl (cdr n)))
(if (null? tl)
(nbits (car n) f)
(nbits tl (add f (vm:vsize))))))))
(define (isqrt-init n)
(lets
((nb (nbits n 0))
(val (<< 1 (sub (>> nb 1) 1))))
(if (eq? (band nb 1) 0)
val
(lets ((val2 (<< val 1)) (sq (mul val2 val2)))
(if (<= sq n) val2 val)))))
(define (isqrt-fix hi bit n)
(if (eq? bit 0)
hi
(lets ((this (bor hi bit)) (mid (mul this this)))
(if (> mid n)
(isqrt-fix hi (>> bit 1) n)
(isqrt-fix this (>> bit 1) n)))))
(define (isqrt n)
(cond
((eq? (type n) type-enum-) (sub 0 (isqrt (sub 0 n))))
((eq? (type n) type-int-) (sub 0 (isqrt (sub 0 n))))
((eq? n 0) 0)
((eq? n 1) 1)
(else
(let ((hi (isqrt-init n)))
(isqrt-fix hi (>> hi 1) n)))))
(define (exact-integer-sqrt n)
(let ((sq (isqrt n)))
(values sq (sub n (mul sq sq)))))
(assert (let*((x y (exact-integer-sqrt 17))) (list x y)) ===> '(4 1))
Bisect
(define (bisect-fini op lo hi pos last)
(cond
((= pos hi) last)
((op pos)
(let ((next (+ pos 1)))
(cond
((= next hi) pos)
((op next)
(bisect-fini op lo hi (+ next 1) pos))
(else
pos))))
((= pos lo)
#false)
(else
(bisect-fini op lo hi (- pos 1) last))))
(define (bisect-seek op lo hi pos step last)
(cond
((eq? step 1)
(bisect-fini op lo hi pos last))
((op pos)
(bisect-seek op lo hi (+ pos step) (>> step 1) pos))
(else
(bisect-seek op lo hi (- pos step) (>> step 1) last))))
(define (bisect op lo hi)
(when (< lo hi)
(let*((range (- hi lo))
(step (max 1 (>> range 1))))
(bisect-seek op lo hi
#false))))
(define (expt-loop ap p out)
(cond
((eq? p 0) out)
((eq? (band p 1) 0)
(expt-loop (* ap ap) (>> p 1) out))
(else
(expt-loop (* ap ap) (>> p 1) (* out ap)))))
(define (iexpt a p)
(cond
((eq? p 0) 1)
((eq? a 1) 1)
(else
(expt-loop a (- p 1) a))))
(define (iroot i n)
(cond
((eq? i 0) 0)
((eq? i 1) 1)
((eq? n 1) i)
((negative? i)
(complex 0 (iroot (* i -1) n)))
(else
(or
(bisect
(lambda (q) (<= (iexpt q n) i))
1 i)
1))))
(define (expt a b)
(cond
((eq? b 0) 1)
((eq? b 1) a)
((eq? b 2) (* a a))
((eq? (type b) type-enum+) (expt-loop a (sub b 1) a))
((eq? (type b) type-int+) (expt-loop a (sub b 1) a))
((eq? (type b) type-enum-) (/ 1 (expt a (negate b))))
((eq? (type b) type-int-) (/ 1 (expt a (negate b))))
((eq? (type b) type-rational)
(expt (iroot a (ref b 2)) (ref b 1)))
(else (big-bad-args 'expt a b))))
(define (expt-mod-loop ap p out m)
(cond
((eq? p 0) (mod out m))
((eq? (band p 1) 0)
(expt-mod-loop (rem (mul ap ap) m) (>> p 1) out m))
(else
(expt-mod-loop (rem (mul ap ap) m) (>> p 1)
(rem (mul out ap) m) m))))
(define (expt-mod a b m)
(cond
((eq? b 0) (mod 1 m))
((eq? b 1) (mod a m))
(else
(expt-mod-loop (rem a m) (sub b 1) a m))))
UNSORTED
(define (fact-iter n o)
(if (eq? n 1)
o
(fact-iter (- n 1) (* o n))))
(define (! n)
(if (eq? n 0)
1
(fact-iter n 1)))
npr , number of permutations , naively n!/(n - m ) !
(define (npr-loop n m o)
(if (eq? m 0)
o
(npr-loop (- n 1) (- m 1) (* o n))))
(define (npr n m)
(if (eq? m 0)
0
(npr-loop (- n 1) (- m 1) n)))
ncr , number of combinations , n choose m , simply n!/(m!(n - m ) ! )
(define (ncr n m)
(if (< n m)
0
(let ((mp (- n m)))
(cond
((eq? m 0) 1)
((eq? mp 0) 1)
((> m mp) (ncr n mp))
(else (/ (npr n m) (! m)))))))
(define (dlp-naive y a n)
(let loop ((x 0) (seen empty))
(let ((this (expt-mod a x n)))
(cond
((= y this) x)
(else (loop (+ x 1) (iput seen this #true)))))))
(define (dlp-simple y a n)
(let loop ((x 0) (v 1) (seen empty))
(cond
(loop (+ x 1) (* v a) (iput seen v v))))))
like simple , but has O(1 ) space at the cost of ~1.5x time
(define (dlp-th-step v a n)
(let ((v (* a v)))
(if (>= v n) (rem v n) v)))
(define (dlp-th y a n)
(if (= y 1)
0
(let loop ((x1 0) (v1 1) (x2 1) (v2 a) (step? #false))
(cond
(loop x1 v1 (+ x2 1) (dlp-th-step v2 a n) #false))
(loop
(+ x1 1) (dlp-th-step v1 a n)
(+ x2 1) (dlp-th-step v2 a n) #true))))))
' baby - step giant - step algorithm ( still not quite working properly )
(define (carless a b) (< (car a) (car b)))
(define (find-match b g pred)
(cond
((null? b) #false)
((null? g) #false)
((= (caar b) (caar g))
(let ((x (- (cdar g) (cdar b))))
(if (pred x)
x
(find-match (cdr b) (cdr g) pred))))
((< (caar b) (caar g)) (find-match (cdr b) g pred))
(else (find-match b (cdr g) pred))))
(define (bound x n)
(if (< x n) x (mod x n)))
(define (sqrt-ceil n)
(let ((s (isqrt n)))
(if (< (* s s) n)
(+ s 1)
s)))
(define (dlog-shanks y a n)
(lets
((s (sqrt-ceil n))
(baby
(sort carless
( ya^r . r )
(lrange 5 1 s)))
)
(giant
(sort carless
(map (λ (t) (cons (expt-mod a (* s t) n) (bound (* t s) n)))
(lrange 1 1 (+ s 1))))))
(find-match baby giant (λ (x) (= y (expt-mod a x n))))))
(define dlog dlog-shanks)
(define (fibs n)
(cond
((eq? n 0) (values 1 1))
((eq? n 1) (values 1 2))
(else
(lets
((a b (fibs (- (>> n 1) 1)))
(c (+ a b))
(aa (* a a)) (bb (* b b)) (cc (* c c)))
(if (eq? 0 (band n 1))
(values (+ aa bb) (- cc aa))
(values (- cc aa) (+ bb cc)))))))
one of the the relatively fast ways to compute fibonacci numbers
(define (fib n)
(if (< n 2)
n
(lets ((n sn (fibs (- n 1)))) n)))
( num ... ) [ n - bins ] - > ( ( n - in - bin . ) ... )
(define (histogram data . bins)
(if (null? data)
null
(lets
((l (length data))
(bins
(if (null? bins)
(min l (+ 1 (ilog2 l)))
(car bins)))
(data (sort < data))
(low (car data))
(high (fold (λ (last next) next) low data))
(bin (/ (- high low) bins)))
(let loop ((data data) (count 0) (limit (+ low bin)))
(cond
((null? data)
(list (cons count limit)))
((> (car data) limit)
(cons (cons count limit)
(loop data 0 (+ limit bin))))
(else
(loop (cdr data) (+ count 1) limit)))))))
(define rationalize
algorithm
(letrec
(lambda (x y)
(cond
((> x 0) (rat2 x y))
((< y 0) (- (rat2 (- y) (- x))))
(else (if (and (exact? x) (exact? y)) 0 0.0)))))
(lambda (x y)
(let ((fx (floor x)) (fy (floor y)))
(cond
((= fx x) fx)
((= fx fy) (+ fx (/ (rat2 (/ (- y fy)) (/ (- x fx))))))
(else (+ fx 1)))))))
(lambda (x e)
(unless (real? x) (runtime-error 'rationalize x))
(unless (real? e) (runtime-error 'rationalize e))
(let ((x (- x e)) (y (+ x e)))
(cond
((< x y) (rat1 x y))
((< y x) (rat1 y x))
(else x))))))
))
|
dfc0a3a43a1d4646d8f5d011d7aa432ef1ca2af51e6afb20e54d60943b5b8657
|
district0x/district-registry
|
runner.cljs
|
(ns district-registry.tests.runner
(:require
[cljs.nodejs :as nodejs]
[cljs.test :refer [run-tests]]
[district-registry.shared.smart-contracts-dev :refer [smart-contracts]]
[district-registry.tests.smart-contracts.deployment-tests]
[district-registry.tests.smart-contracts.district-tests]
[district-registry.tests.smart-contracts.kit-district-tests]
[district-registry.tests.smart-contracts.param-change-tests]
[district-registry.tests.smart-contracts.registry-entry-tests]
[district-registry.tests.smart-contracts.registry-tests]
[district.server.logging]
[district.server.web3]
[district.server.smart-contracts]
[district.shared.async-helpers :as async-helpers]
[mount.core :as mount]
[doo.runner :refer-macros [doo-tests]]
[taoensso.timbre :as log]))
(nodejs/enable-util-print!)
(async-helpers/extend-promises-as-channels!)
(defn start-and-run-tests []
(-> (mount/with-args {:web3 {:url "ws:8545"}
:smart-contracts {:contracts-var #'smart-contracts}
:logging {:level :info
:console? false}})
(mount/only [#'district.server.logging/logging
#'district.server.web3/web3
#'district.server.smart-contracts/smart-contracts])
(mount/start)
(as-> $ (log/warn "Started" $)))
(run-tests
'district-registry.tests.smart-contracts.deployment-tests
'district-registry.tests.smart-contracts.registry-entry-tests
'district-registry.tests.smart-contracts.district-tests
'district-registry.tests.smart-contracts.registry-tests
'district-registry.tests.smart-contracts.kit-district-tests
'district-registry.tests.smart-contracts.param-change-tests))
(start-and-run-tests)
| null |
https://raw.githubusercontent.com/district0x/district-registry/c2dcf7978d2243a773165b18e7a76632d8ad724e/test/district_registry/tests/runner.cljs
|
clojure
|
(ns district-registry.tests.runner
(:require
[cljs.nodejs :as nodejs]
[cljs.test :refer [run-tests]]
[district-registry.shared.smart-contracts-dev :refer [smart-contracts]]
[district-registry.tests.smart-contracts.deployment-tests]
[district-registry.tests.smart-contracts.district-tests]
[district-registry.tests.smart-contracts.kit-district-tests]
[district-registry.tests.smart-contracts.param-change-tests]
[district-registry.tests.smart-contracts.registry-entry-tests]
[district-registry.tests.smart-contracts.registry-tests]
[district.server.logging]
[district.server.web3]
[district.server.smart-contracts]
[district.shared.async-helpers :as async-helpers]
[mount.core :as mount]
[doo.runner :refer-macros [doo-tests]]
[taoensso.timbre :as log]))
(nodejs/enable-util-print!)
(async-helpers/extend-promises-as-channels!)
(defn start-and-run-tests []
(-> (mount/with-args {:web3 {:url "ws:8545"}
:smart-contracts {:contracts-var #'smart-contracts}
:logging {:level :info
:console? false}})
(mount/only [#'district.server.logging/logging
#'district.server.web3/web3
#'district.server.smart-contracts/smart-contracts])
(mount/start)
(as-> $ (log/warn "Started" $)))
(run-tests
'district-registry.tests.smart-contracts.deployment-tests
'district-registry.tests.smart-contracts.registry-entry-tests
'district-registry.tests.smart-contracts.district-tests
'district-registry.tests.smart-contracts.registry-tests
'district-registry.tests.smart-contracts.kit-district-tests
'district-registry.tests.smart-contracts.param-change-tests))
(start-and-run-tests)
|
|
635472e6b8c7da5e87779b3196271b8d753b51cebae516c608e5b3b01ed59512
|
haroldcarr/learn-haskell-coq-ml-etc
|
HW11_AParser.hs
|
module HW11_AParser (Parser, runParser, satisfy, char, posInt) where
import Control.Applicative
import Data.Char
newtype Parser a = Parser { runParser :: String -> Maybe (a, String) }
satisfy :: (Char -> Bool) -> Parser Char
satisfy p = Parser f
where
f [] = Nothing
f (x:xs)
| p x = Just (x, xs)
| otherwise = Nothing
char :: Char -> Parser Char
char c = satisfy (== c)
posInt :: Parser Integer
posInt = Parser f
where
f xs
| null ns = Nothing
| otherwise = Just (read ns, rest)
where (ns, rest) = span isDigit xs
inParser :: ((String -> Maybe (a, String)) -> String -> Maybe (b, String))
-> Parser a -> Parser b
inParser f = Parser . f . runParser
first :: (a -> b) -> (a,c) -> (b,c)
first f (x,y) = (f x, y)
instance Functor Parser where
fmap = inParser . fmap . fmap . first
instance Applicative Parser where
pure a = Parser (\s -> Just (a, s))
(Parser fp) <*> xp = Parser $ \s ->
case fp s of
Nothing -> Nothing
Just (f,s') -> runParser (f <$> xp) s'
instance Alternative Parser where
empty = Parser (const Nothing)
Parser p1 <|> Parser p2 = Parser $ liftA2 (<|>) p1 p2
| null |
https://raw.githubusercontent.com/haroldcarr/learn-haskell-coq-ml-etc/b4e83ec7c7af730de688b7376497b9f49dc24a0e/haskell/course/2014-06-upenn/cis194/src/HW11_AParser.hs
|
haskell
|
module HW11_AParser (Parser, runParser, satisfy, char, posInt) where
import Control.Applicative
import Data.Char
newtype Parser a = Parser { runParser :: String -> Maybe (a, String) }
satisfy :: (Char -> Bool) -> Parser Char
satisfy p = Parser f
where
f [] = Nothing
f (x:xs)
| p x = Just (x, xs)
| otherwise = Nothing
char :: Char -> Parser Char
char c = satisfy (== c)
posInt :: Parser Integer
posInt = Parser f
where
f xs
| null ns = Nothing
| otherwise = Just (read ns, rest)
where (ns, rest) = span isDigit xs
inParser :: ((String -> Maybe (a, String)) -> String -> Maybe (b, String))
-> Parser a -> Parser b
inParser f = Parser . f . runParser
first :: (a -> b) -> (a,c) -> (b,c)
first f (x,y) = (f x, y)
instance Functor Parser where
fmap = inParser . fmap . fmap . first
instance Applicative Parser where
pure a = Parser (\s -> Just (a, s))
(Parser fp) <*> xp = Parser $ \s ->
case fp s of
Nothing -> Nothing
Just (f,s') -> runParser (f <$> xp) s'
instance Alternative Parser where
empty = Parser (const Nothing)
Parser p1 <|> Parser p2 = Parser $ liftA2 (<|>) p1 p2
|
|
68dd7caee42e3054d3a39325b908e51a704c104664f92974a8a30634e4c918b4
|
unclechu/xlib-keys-hack
|
Types.hs
|
Author :
License : -keys-hack/master/LICENSE
# LANGUAGE DeriveGeneric , DeriveAnyClass #
module Types
( type AlternativeModeState
, type AlternativeModeLevel (..)
, numberToAlternativeModeLevel
) where
import "base" GHC.Generics (type Generic)
import "data-default" Data.Default (type Default (def))
import "deepseq" Control.DeepSeq (type NFData)
| @Bool@ indicates whether alternative mode is turned on permanently ( @True@ )
-- or temporarily (@False@) by holding a modifier.
type AlternativeModeState = Maybe (AlternativeModeLevel, Bool)
data AlternativeModeLevel
= FirstAlternativeModeLevel
| SecondAlternativeModeLevel
deriving (Show, Eq, Ord, Bounded, Enum, Generic, NFData)
instance Default AlternativeModeLevel where
def = FirstAlternativeModeLevel
numberToAlternativeModeLevel :: Integral a => a -> Maybe AlternativeModeLevel
numberToAlternativeModeLevel 1 = Just FirstAlternativeModeLevel
numberToAlternativeModeLevel 2 = Just SecondAlternativeModeLevel
numberToAlternativeModeLevel _ = Nothing
| null |
https://raw.githubusercontent.com/unclechu/xlib-keys-hack/33b49a9b1fc4bc87bdb95e2bb632a312ec2ebad0/src/Types.hs
|
haskell
|
or temporarily (@False@) by holding a modifier.
|
Author :
License : -keys-hack/master/LICENSE
# LANGUAGE DeriveGeneric , DeriveAnyClass #
module Types
( type AlternativeModeState
, type AlternativeModeLevel (..)
, numberToAlternativeModeLevel
) where
import "base" GHC.Generics (type Generic)
import "data-default" Data.Default (type Default (def))
import "deepseq" Control.DeepSeq (type NFData)
| @Bool@ indicates whether alternative mode is turned on permanently ( @True@ )
type AlternativeModeState = Maybe (AlternativeModeLevel, Bool)
data AlternativeModeLevel
= FirstAlternativeModeLevel
| SecondAlternativeModeLevel
deriving (Show, Eq, Ord, Bounded, Enum, Generic, NFData)
instance Default AlternativeModeLevel where
def = FirstAlternativeModeLevel
numberToAlternativeModeLevel :: Integral a => a -> Maybe AlternativeModeLevel
numberToAlternativeModeLevel 1 = Just FirstAlternativeModeLevel
numberToAlternativeModeLevel 2 = Just SecondAlternativeModeLevel
numberToAlternativeModeLevel _ = Nothing
|
eb1272936ef3bb2601223efd307e1094abb55230103e286a49276517e6791cc0
|
dreixel/regular
|
GArbitrary2.hs
|
{-# OPTIONS -fglasgow-exts #-}
module GArbitrary2 where
import Prelude hiding (sum)
import qualified Prelude
import Control.Monad
import Control.Applicative
import System.Random
import Test.QuickCheck
import Debug.Trace
import Generics.Regular
Just x `combM` Just y = Just (x+y)
Just x `combM` _ = Just x
_ `combM` Just y = Just y
Nothing `combM` Nothing = Nothing
instance Applicative (PFAnalysis e) where
pure x = PFAnalysis [(Nothing,const (return x))]
(PFAnalysis xs) <*> (PFAnalysis ys)
= PFAnalysis [(mx `combM` my,\e -> (x e) `ap` (y e))| (mx,x) <- xs, (my,y) <- ys]
instance Alternative (PFAnalysis e) where
empty = PFAnalysis []
(PFAnalysis xs) <|> (PFAnalysis ys) = PFAnalysis (xs ++ ys)
data PFAnalysis a b = PFAnalysis [(Maybe Int,Gen a -> Gen b)]
instance Functor (PFAnalysis a) where
fmap f (PFAnalysis xs) = PFAnalysis [(mx,fmap f . x)|(mx,x)<-xs]
class GArbitrary f where
garbitraryf :: PFAnalysis a (f a)
instance GArbitrary U where
garbitraryf = pure U
instance GArbitrary I where
garbitraryf = PFAnalysis [(Just 1,\e -> liftM I e)]
instance Arbitrary a => GArbitrary (K a) where
garbitraryf = PFAnalysis [(Nothing,const $ liftM K arbitrary)]
instance (GArbitrary f,GArbitrary g) => GArbitrary (f :*: g) where
garbitraryf = (:*:) <$> garbitraryf <*> garbitraryf
instance (GArbitrary f,GArbitrary g) => GArbitrary (f :+: g) where
garbitraryf = L <$> garbitraryf <|> R <$> garbitraryf
garbitrary :: (Regular a, GArbitrary (PF a)) => Int -> Gen a
garbitrary = go
where
go 0 = frequency nonRec
go sz = frequency (all sz)
PFAnalysis cons = fmap to garbitraryf
nonRec = [(1,f undefined) | (Nothing,f) <- cons]
all sz = nonRec ++
[(fixps+1,f $ go $ sz `div` fixps) | (Just fixps,f) <- cons]
| null |
https://raw.githubusercontent.com/dreixel/regular/c8460ee827f1eb04dd31b873380ff9626a4a4220/examples/framework/GArbitrary2.hs
|
haskell
|
# OPTIONS -fglasgow-exts #
|
module GArbitrary2 where
import Prelude hiding (sum)
import qualified Prelude
import Control.Monad
import Control.Applicative
import System.Random
import Test.QuickCheck
import Debug.Trace
import Generics.Regular
Just x `combM` Just y = Just (x+y)
Just x `combM` _ = Just x
_ `combM` Just y = Just y
Nothing `combM` Nothing = Nothing
instance Applicative (PFAnalysis e) where
pure x = PFAnalysis [(Nothing,const (return x))]
(PFAnalysis xs) <*> (PFAnalysis ys)
= PFAnalysis [(mx `combM` my,\e -> (x e) `ap` (y e))| (mx,x) <- xs, (my,y) <- ys]
instance Alternative (PFAnalysis e) where
empty = PFAnalysis []
(PFAnalysis xs) <|> (PFAnalysis ys) = PFAnalysis (xs ++ ys)
data PFAnalysis a b = PFAnalysis [(Maybe Int,Gen a -> Gen b)]
instance Functor (PFAnalysis a) where
fmap f (PFAnalysis xs) = PFAnalysis [(mx,fmap f . x)|(mx,x)<-xs]
class GArbitrary f where
garbitraryf :: PFAnalysis a (f a)
instance GArbitrary U where
garbitraryf = pure U
instance GArbitrary I where
garbitraryf = PFAnalysis [(Just 1,\e -> liftM I e)]
instance Arbitrary a => GArbitrary (K a) where
garbitraryf = PFAnalysis [(Nothing,const $ liftM K arbitrary)]
instance (GArbitrary f,GArbitrary g) => GArbitrary (f :*: g) where
garbitraryf = (:*:) <$> garbitraryf <*> garbitraryf
instance (GArbitrary f,GArbitrary g) => GArbitrary (f :+: g) where
garbitraryf = L <$> garbitraryf <|> R <$> garbitraryf
garbitrary :: (Regular a, GArbitrary (PF a)) => Int -> Gen a
garbitrary = go
where
go 0 = frequency nonRec
go sz = frequency (all sz)
PFAnalysis cons = fmap to garbitraryf
nonRec = [(1,f undefined) | (Nothing,f) <- cons]
all sz = nonRec ++
[(fixps+1,f $ go $ sz `div` fixps) | (Just fixps,f) <- cons]
|
259599f3688e9ef2df818df4412de3935d4cb7ce524ed82b93dc16186d54f36a
|
spawnfest/eep49ers
|
fixtable_SUITE.erl
|
%%
%% %CopyrightBegin%
%%
Copyright Ericsson AB 1999 - 2016 . All Rights Reserved .
%%
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
%% you may not use this file except in compliance with the License.
%% You may obtain a copy of the License at
%%
%% -2.0
%%
%% Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an " AS IS " BASIS ,
%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
%% See the License for the specific language governing permissions and
%% limitations under the License.
%%
%% %CopyrightEnd%
%%
%%%----------------------------------------------------------------------
%%% Purpose : Tests the safe_fixtable functions in both ets and dets.
%%%----------------------------------------------------------------------
-module(fixtable_SUITE).
-export([all/0, suite/0,groups/0,init_per_suite/1, end_per_suite/1,
init_per_group/2,end_per_group/2]).
%%% Test cases
-export([multiple_fixes/1, multiple_processes/1,
other_process_deletes/1, owner_dies/1,
other_process_closes/1,insert_same_key/1]).
-export([fixbag/1]).
-export([init_per_testcase/2, end_per_testcase/2]).
%%% Internal exports
-export([command_loop/0,start_commander/0]).
suite() ->
[{ct_hooks,[ts_install_cth]},
{timetrap,{minutes,1}}].
all() ->
[multiple_fixes, multiple_processes,
other_process_deletes, owner_dies, other_process_closes,
insert_same_key, fixbag].
groups() ->
[].
init_per_suite(Config) ->
Config.
end_per_suite(_Config) ->
ok.
init_per_group(_GroupName, Config) ->
Config.
end_per_group(_GroupName, Config) ->
Config.
-include_lib("common_test/include/ct.hrl").
I wrote this thinking I would use more than one temporary at a time , but
%%% I wasn't... Well, maybe in the future...
-define(DETS_TEMPORARIES, [tmp1]).
-define(ETS_TEMPORARIES, [gurksmetsmedaljong]).
-define(DETS_TMP1,hd(?DETS_TEMPORARIES)).
-define(ETS_TMP1,hd(?ETS_TEMPORARIES)).
-define(HELPER_NODE, (atom_to_list(?MODULE) ++ "_helper1")).
init_per_testcase(_Func, Config) ->
PrivDir = proplists:get_value(priv_dir,Config),
file:make_dir(PrivDir),
Config.
end_per_testcase(_Func, Config) ->
lists:foreach(fun(X) ->
(catch dets:close(X)),
(catch file:delete(dets_filename(X,Config)))
end,
?DETS_TEMPORARIES),
lists:foreach(fun(X) ->
(catch ets:delete(X))
end,
?ETS_TEMPORARIES).
-ifdef(DEBUG).
-define(LOG(X), show(X,?LINE)).
show(Term, Line) ->
io:format("~p: ~p~n", [Line,Term]),
Term.
-else.
-define(LOG(X),X).
-endif.
%% Check for bug OTP-5087; safe_fixtable for bags could give incorrect
%% lookups.
fixbag(Config) when is_list(Config) ->
T = ets:new(x,[bag]),
ets:insert(T,{a,1}),
ets:insert(T,{a,2}),
ets:safe_fixtable(T,true),
ets:match_delete(T,{a,2}),
ets:insert(T,{a,3}),
Res = ets:lookup(T,a),
ets:safe_fixtable(T,false),
Res = ets:lookup(T,a),
ok.
%% Check correct behaviour if a key is deleted and reinserted during
%% fixation.
insert_same_key(Config) when is_list(Config) ->
{ok,Dets1} = dets:open_file(?DETS_TMP1,
[{file, dets_filename(?DETS_TMP1,Config)}]),
Ets1 = ets:new(ets,[]),
insert_same_key(Dets1,dets,Config),
insert_same_key(Ets1,ets,Config),
ets:insert(Ets1,{1,2}),
1 = ets:info(Ets1,size),
dets:insert(Dets1,{1,2}),
1 = dets:info(Dets1,size),
dets:close(Dets1),
(catch file:delete(dets_filename(Dets1,Config))),
ets:delete(Ets1),
{ok,Dets2} = dets:open_file(?DETS_TMP1,
[{type,bag},{file, dets_filename(?DETS_TMP1,Config)}]),
Ets2 = ets:new(ets,[bag]),
insert_same_key(Dets2,dets,Config),
insert_same_key(Ets2,ets,Config),
ets:insert(Ets2,{1,2}),
2 = ets:info(Ets2,size),
ets:insert(Ets2,{1,2}),
2 = ets:info(Ets2,size),
dets:insert(Dets2,{1,2}),
2 = dets:info(Dets2,size),
dets:insert(Dets2,{1,2}),
2 = dets:info(Dets2,size),
dets:close(Dets2),
(catch file:delete(dets_filename(Dets2,Config))),
ets:delete(Ets2),
{ok,Dets3} = dets:open_file(?DETS_TMP1,
[{type,duplicate_bag},
{file, dets_filename(?DETS_TMP1,Config)}]),
Ets3 = ets:new(ets,[duplicate_bag]),
insert_same_key(Dets3,dets,Config),
insert_same_key(Ets3,ets,Config),
ets:insert(Ets3,{1,2}),
2 = ets:info(Ets3,size),
ets:insert(Ets3,{1,2}),
3 = ets:info(Ets3,size),
dets:insert(Dets3,{1,2}),
2 = dets:info(Dets3,size),
dets:insert(Dets3,{1,2}),
3 = dets:info(Dets3,size),
dets:close(Dets3),
(catch file:delete(dets_filename(Dets3,Config))),
ets:delete(Ets3),
ok.
insert_same_key(Tab,Mod,_Config) ->
Mod:insert(Tab,{1,1}),
Mod:insert(Tab,{1,2}),
Mod:insert(Tab,{2,2}),
Mod:insert(Tab,{2,2}),
Mod:safe_fixtable(Tab,true),
Mod:delete(Tab,1),
Mod:insert(Tab,{1,1}),
Expect = case Mod:info(Tab,type) of
bag ->
Mod:insert(Tab,{1,2}),
2;
_ ->
1
end,
Mod:delete(Tab,2),
Mod:safe_fixtable(Tab,false),
case Mod:info(Tab,size) of
Expect ->
ok;
_ ->
exit({size_field_wrong,{Mod,Mod:info(Tab)}})
end.
%% Check correct behaviour if the table owner dies.
owner_dies(Config) when is_list(Config) ->
P1 = start_commander(),
Ets1 = command(P1,{ets,new,[ets,[]]}),
command(P1,{ets,safe_fixtable,[Ets1,true]}),
{_,[{P1,1}]} = ets:info(Ets1, safe_fixed),
stop_commander(P1),
undefined = ets:info(Ets1, safe_fixed),
P2 = start_commander(),
Ets2 = command(P2,{ets,new,[ets,[public]]}),
command(P2,{ets,safe_fixtable,[Ets2,true]}),
ets:safe_fixtable(Ets2,true),
true = ets:info(Ets2, fixed),
{_,[{_,1},{_,1}]} = ets:info(Ets2, safe_fixed),
stop_commander(P2),
undefined = ets:info(Ets2, safe_fixed),
undefined = ets:info(Ets2, fixed),
P3 = start_commander(),
{ok,Dets} = ?LOG(command(P3, {dets, open_file,
[?DETS_TMP1,
[{file,
dets_filename(?DETS_TMP1,
Config)}]]})),
command(P3, {dets, safe_fixtable, [Dets, true]}),
{_,[{P3,1}]} = dets:info(Dets, safe_fixed),
true = dets:info(Dets, fixed),
stop_commander(P3),
undefined = dets:info(Dets, safe_fixed),
undefined = dets:info(Dets, fixed),
P4 = start_commander(),
{ok,Dets} = command(P4, {dets, open_file,
[?DETS_TMP1,
[{file, dets_filename(?DETS_TMP1,Config)}]]}),
{ok,Dets} = dets:open_file(?DETS_TMP1,
[{file, dets_filename(?DETS_TMP1,Config)}]),
false = dets:info(Dets, safe_fixed),
command(P4, {dets, safe_fixtable, [Dets, true]}),
dets:safe_fixtable(Dets, true),
{_,[{_,1},{_,1}]} = dets:info(Dets, safe_fixed),
dets:safe_fixtable(Dets, true),
stop_commander(P4),
S = self(),
{_,[{S,2}]} = dets:info(Dets, safe_fixed),
true = dets:info(Dets, fixed),
dets:close(Dets),
undefined = dets:info(Dets, fixed),
undefined = dets:info(Dets, safe_fixed),
ok.
%% When another process closes an dets table, different things should
%% happen depending on if it has opened it before.
other_process_closes(Config) when is_list(Config) ->
{ok,Dets} = dets:open_file(?DETS_TMP1,
[{file, dets_filename(tmp1,Config)}]),
P2 = start_commander(),
dets:safe_fixtable(Dets,true),
S = self(),
{_,[{S,1}]} = dets:info(Dets, safe_fixed),
command(P2,{dets, safe_fixtable, [Dets, true]}),
{_,[_,_]} = dets:info(Dets, safe_fixed),
{error, not_owner} = command(P2,{dets, close, [Dets]}),
{_,[_,_]} = dets:info(Dets, safe_fixed),
command(P2,{dets, open_file,[?DETS_TMP1,
[{file,
dets_filename(?DETS_TMP1, Config)}]]}),
{_,[_,_]} = dets:info(Dets, safe_fixed),
command(P2,{dets, close, [Dets]}),
stop_commander(P2),
{_,[{S,1}]} = dets:info(Dets, safe_fixed),
true = dets:info(Dets,fixed),
dets:close(Dets),
undefined = dets:info(Dets,fixed),
undefined = dets:info(Dets, safe_fixed),
ok.
%% Check that fixtable structures are cleaned up if another process
%% deletes an ets table.
other_process_deletes(Config) when is_list(Config) ->
Ets = ets:new(ets,[public]),
P = start_commander(),
ets:safe_fixtable(Ets,true),
ets:safe_fixtable(Ets,true),
true = ets:info(Ets, fixed),
{_,_} = ets:info(Ets, safe_fixed),
command(P,{ets,delete,[Ets]}),
stop_commander(P),
undefined = ets:info(Ets, fixed),
undefined = ets:info(Ets, safe_fixed),
ok.
%% Check that multiple safe_fixtable keeps the reference counter.
multiple_fixes(Config) when is_list(Config) ->
{ok,Dets} = dets:open_file(?DETS_TMP1,
[{file, dets_filename(?DETS_TMP1,Config)}]),
Ets = ets:new(ets,[]),
multiple_fixes(Dets,dets),
multiple_fixes(Ets,ets),
dets:close(Dets),
ok.
multiple_fixes(Tab, Mod) ->
false = Mod:info(Tab,fixed),
false = Mod:info(Tab, safe_fixed),
Mod:safe_fixtable(Tab, true),
true = Mod:info(Tab,fixed),
S = self(),
{_,[{S,1}]} = Mod:info(Tab, safe_fixed),
Mod:safe_fixtable(Tab, true),
Mod:safe_fixtable(Tab, true),
{_,[{S,3}]} = Mod:info(Tab, safe_fixed),
true = Mod:info(Tab,fixed),
Mod:safe_fixtable(Tab, false),
{_,[{S,2}]} = Mod:info(Tab, safe_fixed),
true = Mod:info(Tab,fixed),
Mod:safe_fixtable(Tab, false),
{_,[{S,1}]} = Mod:info(Tab, safe_fixed),
true = Mod:info(Tab,fixed),
Mod:safe_fixtable(Tab, false),
false = Mod:info(Tab, safe_fixed),
false = Mod:info(Tab,fixed).
%% Check that multiple safe_fixtable across processes are reference
%% counted OK.
multiple_processes(Config) when is_list(Config) ->
{ok,Dets} = dets:open_file(?DETS_TMP1,[{file,
dets_filename(?DETS_TMP1,
Config)}]),
Ets = ets:new(ets,[public]),
multiple_processes(Dets,dets),
multiple_processes(Ets,ets),
ok.
multiple_processes(Tab, Mod) ->
io:format("Mod = ~p\n", [Mod]),
P1 = start_commander(),
P2 = start_commander(),
false = Mod:info(Tab,fixed),
false = Mod:info(Tab, safe_fixed),
command(P1, {Mod, safe_fixtable, [Tab,true]}),
true = Mod:info(Tab,fixed),
{_,[{P1,1}]} = Mod:info(Tab, safe_fixed),
command(P2, {Mod, safe_fixtable, [Tab,true]}),
true = Mod:info(Tab,fixed),
{_,L} = Mod:info(Tab,safe_fixed),
true = (lists:sort(L) == lists:sort([{P1,1},{P2,1}])),
command(P2, {Mod, safe_fixtable, [Tab,true]}),
{_,L2} = Mod:info(Tab,safe_fixed),
true = (lists:sort(L2) == lists:sort([{P1,1},{P2,2}])),
command(P2, {Mod, safe_fixtable, [Tab,false]}),
true = Mod:info(Tab,fixed),
{_,L3} = Mod:info(Tab,safe_fixed),
true = (lists:sort(L3) == lists:sort([{P1,1},{P2,1}])),
command(P2, {Mod, safe_fixtable, [Tab,false]}),
true = Mod:info(Tab,fixed),
{_,[{P1,1}]} = Mod:info(Tab, safe_fixed),
stop_commander(P1),
receive after 1000 -> ok end,
false = Mod:info(Tab,fixed),
false = Mod:info(Tab, safe_fixed),
command(P2, {Mod, safe_fixtable, [Tab,true]}),
true = Mod:info(Tab,fixed),
{_,[{P2,1}]} = Mod:info(Tab, safe_fixed),
case Mod of
dets ->
dets:close(Tab);
ets ->
ets:delete(Tab)
end,
stop_commander(P2),
receive after 1000 -> ok end,
undefined = Mod:info(Tab, safe_fixed),
ok.
%%% Helpers
dets_filename(Base, Config) when is_atom(Base) ->
dets_filename(atom_to_list(Base) ++ ".dat", Config);
dets_filename(Basename, Config) ->
PrivDir = proplists:get_value(priv_dir,Config),
filename:join(PrivDir, Basename).
command_loop() ->
receive
{From, command, {M,F,A}} ->
Res = (catch apply(M, F, A)),
From ! {self(), Res},
command_loop();
die ->
ok
end.
start_commander() ->
spawn(?MODULE, command_loop, []).
stop_commander(Pid) ->
process_flag(trap_exit, true),
link(Pid),
Pid ! die,
receive
{'EXIT',Pid,_} ->
timer:sleep(1), % let other processes handle the signal as well
true
after 5000 ->
exit(stop_timeout)
end.
command(Pid,MFA) ->
Pid ! {self(), command, MFA},
receive
{Pid, Res} ->
Res
after 20000 ->
exit(command_timeout)
end.
| null |
https://raw.githubusercontent.com/spawnfest/eep49ers/d1020fd625a0bbda8ab01caf0e1738eb1cf74886/lib/stdlib/test/fixtable_SUITE.erl
|
erlang
|
%CopyrightBegin%
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.
%CopyrightEnd%
----------------------------------------------------------------------
Purpose : Tests the safe_fixtable functions in both ets and dets.
----------------------------------------------------------------------
Test cases
Internal exports
I wasn't... Well, maybe in the future...
Check for bug OTP-5087; safe_fixtable for bags could give incorrect
lookups.
Check correct behaviour if a key is deleted and reinserted during
fixation.
Check correct behaviour if the table owner dies.
When another process closes an dets table, different things should
happen depending on if it has opened it before.
Check that fixtable structures are cleaned up if another process
deletes an ets table.
Check that multiple safe_fixtable keeps the reference counter.
Check that multiple safe_fixtable across processes are reference
counted OK.
Helpers
let other processes handle the signal as well
|
Copyright Ericsson AB 1999 - 2016 . All Rights Reserved .
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
distributed under the License is distributed on an " AS IS " BASIS ,
-module(fixtable_SUITE).
-export([all/0, suite/0,groups/0,init_per_suite/1, end_per_suite/1,
init_per_group/2,end_per_group/2]).
-export([multiple_fixes/1, multiple_processes/1,
other_process_deletes/1, owner_dies/1,
other_process_closes/1,insert_same_key/1]).
-export([fixbag/1]).
-export([init_per_testcase/2, end_per_testcase/2]).
-export([command_loop/0,start_commander/0]).
suite() ->
[{ct_hooks,[ts_install_cth]},
{timetrap,{minutes,1}}].
all() ->
[multiple_fixes, multiple_processes,
other_process_deletes, owner_dies, other_process_closes,
insert_same_key, fixbag].
groups() ->
[].
init_per_suite(Config) ->
Config.
end_per_suite(_Config) ->
ok.
init_per_group(_GroupName, Config) ->
Config.
end_per_group(_GroupName, Config) ->
Config.
-include_lib("common_test/include/ct.hrl").
I wrote this thinking I would use more than one temporary at a time , but
-define(DETS_TEMPORARIES, [tmp1]).
-define(ETS_TEMPORARIES, [gurksmetsmedaljong]).
-define(DETS_TMP1,hd(?DETS_TEMPORARIES)).
-define(ETS_TMP1,hd(?ETS_TEMPORARIES)).
-define(HELPER_NODE, (atom_to_list(?MODULE) ++ "_helper1")).
init_per_testcase(_Func, Config) ->
PrivDir = proplists:get_value(priv_dir,Config),
file:make_dir(PrivDir),
Config.
end_per_testcase(_Func, Config) ->
lists:foreach(fun(X) ->
(catch dets:close(X)),
(catch file:delete(dets_filename(X,Config)))
end,
?DETS_TEMPORARIES),
lists:foreach(fun(X) ->
(catch ets:delete(X))
end,
?ETS_TEMPORARIES).
-ifdef(DEBUG).
-define(LOG(X), show(X,?LINE)).
show(Term, Line) ->
io:format("~p: ~p~n", [Line,Term]),
Term.
-else.
-define(LOG(X),X).
-endif.
fixbag(Config) when is_list(Config) ->
T = ets:new(x,[bag]),
ets:insert(T,{a,1}),
ets:insert(T,{a,2}),
ets:safe_fixtable(T,true),
ets:match_delete(T,{a,2}),
ets:insert(T,{a,3}),
Res = ets:lookup(T,a),
ets:safe_fixtable(T,false),
Res = ets:lookup(T,a),
ok.
insert_same_key(Config) when is_list(Config) ->
{ok,Dets1} = dets:open_file(?DETS_TMP1,
[{file, dets_filename(?DETS_TMP1,Config)}]),
Ets1 = ets:new(ets,[]),
insert_same_key(Dets1,dets,Config),
insert_same_key(Ets1,ets,Config),
ets:insert(Ets1,{1,2}),
1 = ets:info(Ets1,size),
dets:insert(Dets1,{1,2}),
1 = dets:info(Dets1,size),
dets:close(Dets1),
(catch file:delete(dets_filename(Dets1,Config))),
ets:delete(Ets1),
{ok,Dets2} = dets:open_file(?DETS_TMP1,
[{type,bag},{file, dets_filename(?DETS_TMP1,Config)}]),
Ets2 = ets:new(ets,[bag]),
insert_same_key(Dets2,dets,Config),
insert_same_key(Ets2,ets,Config),
ets:insert(Ets2,{1,2}),
2 = ets:info(Ets2,size),
ets:insert(Ets2,{1,2}),
2 = ets:info(Ets2,size),
dets:insert(Dets2,{1,2}),
2 = dets:info(Dets2,size),
dets:insert(Dets2,{1,2}),
2 = dets:info(Dets2,size),
dets:close(Dets2),
(catch file:delete(dets_filename(Dets2,Config))),
ets:delete(Ets2),
{ok,Dets3} = dets:open_file(?DETS_TMP1,
[{type,duplicate_bag},
{file, dets_filename(?DETS_TMP1,Config)}]),
Ets3 = ets:new(ets,[duplicate_bag]),
insert_same_key(Dets3,dets,Config),
insert_same_key(Ets3,ets,Config),
ets:insert(Ets3,{1,2}),
2 = ets:info(Ets3,size),
ets:insert(Ets3,{1,2}),
3 = ets:info(Ets3,size),
dets:insert(Dets3,{1,2}),
2 = dets:info(Dets3,size),
dets:insert(Dets3,{1,2}),
3 = dets:info(Dets3,size),
dets:close(Dets3),
(catch file:delete(dets_filename(Dets3,Config))),
ets:delete(Ets3),
ok.
insert_same_key(Tab,Mod,_Config) ->
Mod:insert(Tab,{1,1}),
Mod:insert(Tab,{1,2}),
Mod:insert(Tab,{2,2}),
Mod:insert(Tab,{2,2}),
Mod:safe_fixtable(Tab,true),
Mod:delete(Tab,1),
Mod:insert(Tab,{1,1}),
Expect = case Mod:info(Tab,type) of
bag ->
Mod:insert(Tab,{1,2}),
2;
_ ->
1
end,
Mod:delete(Tab,2),
Mod:safe_fixtable(Tab,false),
case Mod:info(Tab,size) of
Expect ->
ok;
_ ->
exit({size_field_wrong,{Mod,Mod:info(Tab)}})
end.
owner_dies(Config) when is_list(Config) ->
P1 = start_commander(),
Ets1 = command(P1,{ets,new,[ets,[]]}),
command(P1,{ets,safe_fixtable,[Ets1,true]}),
{_,[{P1,1}]} = ets:info(Ets1, safe_fixed),
stop_commander(P1),
undefined = ets:info(Ets1, safe_fixed),
P2 = start_commander(),
Ets2 = command(P2,{ets,new,[ets,[public]]}),
command(P2,{ets,safe_fixtable,[Ets2,true]}),
ets:safe_fixtable(Ets2,true),
true = ets:info(Ets2, fixed),
{_,[{_,1},{_,1}]} = ets:info(Ets2, safe_fixed),
stop_commander(P2),
undefined = ets:info(Ets2, safe_fixed),
undefined = ets:info(Ets2, fixed),
P3 = start_commander(),
{ok,Dets} = ?LOG(command(P3, {dets, open_file,
[?DETS_TMP1,
[{file,
dets_filename(?DETS_TMP1,
Config)}]]})),
command(P3, {dets, safe_fixtable, [Dets, true]}),
{_,[{P3,1}]} = dets:info(Dets, safe_fixed),
true = dets:info(Dets, fixed),
stop_commander(P3),
undefined = dets:info(Dets, safe_fixed),
undefined = dets:info(Dets, fixed),
P4 = start_commander(),
{ok,Dets} = command(P4, {dets, open_file,
[?DETS_TMP1,
[{file, dets_filename(?DETS_TMP1,Config)}]]}),
{ok,Dets} = dets:open_file(?DETS_TMP1,
[{file, dets_filename(?DETS_TMP1,Config)}]),
false = dets:info(Dets, safe_fixed),
command(P4, {dets, safe_fixtable, [Dets, true]}),
dets:safe_fixtable(Dets, true),
{_,[{_,1},{_,1}]} = dets:info(Dets, safe_fixed),
dets:safe_fixtable(Dets, true),
stop_commander(P4),
S = self(),
{_,[{S,2}]} = dets:info(Dets, safe_fixed),
true = dets:info(Dets, fixed),
dets:close(Dets),
undefined = dets:info(Dets, fixed),
undefined = dets:info(Dets, safe_fixed),
ok.
other_process_closes(Config) when is_list(Config) ->
{ok,Dets} = dets:open_file(?DETS_TMP1,
[{file, dets_filename(tmp1,Config)}]),
P2 = start_commander(),
dets:safe_fixtable(Dets,true),
S = self(),
{_,[{S,1}]} = dets:info(Dets, safe_fixed),
command(P2,{dets, safe_fixtable, [Dets, true]}),
{_,[_,_]} = dets:info(Dets, safe_fixed),
{error, not_owner} = command(P2,{dets, close, [Dets]}),
{_,[_,_]} = dets:info(Dets, safe_fixed),
command(P2,{dets, open_file,[?DETS_TMP1,
[{file,
dets_filename(?DETS_TMP1, Config)}]]}),
{_,[_,_]} = dets:info(Dets, safe_fixed),
command(P2,{dets, close, [Dets]}),
stop_commander(P2),
{_,[{S,1}]} = dets:info(Dets, safe_fixed),
true = dets:info(Dets,fixed),
dets:close(Dets),
undefined = dets:info(Dets,fixed),
undefined = dets:info(Dets, safe_fixed),
ok.
other_process_deletes(Config) when is_list(Config) ->
Ets = ets:new(ets,[public]),
P = start_commander(),
ets:safe_fixtable(Ets,true),
ets:safe_fixtable(Ets,true),
true = ets:info(Ets, fixed),
{_,_} = ets:info(Ets, safe_fixed),
command(P,{ets,delete,[Ets]}),
stop_commander(P),
undefined = ets:info(Ets, fixed),
undefined = ets:info(Ets, safe_fixed),
ok.
multiple_fixes(Config) when is_list(Config) ->
{ok,Dets} = dets:open_file(?DETS_TMP1,
[{file, dets_filename(?DETS_TMP1,Config)}]),
Ets = ets:new(ets,[]),
multiple_fixes(Dets,dets),
multiple_fixes(Ets,ets),
dets:close(Dets),
ok.
multiple_fixes(Tab, Mod) ->
false = Mod:info(Tab,fixed),
false = Mod:info(Tab, safe_fixed),
Mod:safe_fixtable(Tab, true),
true = Mod:info(Tab,fixed),
S = self(),
{_,[{S,1}]} = Mod:info(Tab, safe_fixed),
Mod:safe_fixtable(Tab, true),
Mod:safe_fixtable(Tab, true),
{_,[{S,3}]} = Mod:info(Tab, safe_fixed),
true = Mod:info(Tab,fixed),
Mod:safe_fixtable(Tab, false),
{_,[{S,2}]} = Mod:info(Tab, safe_fixed),
true = Mod:info(Tab,fixed),
Mod:safe_fixtable(Tab, false),
{_,[{S,1}]} = Mod:info(Tab, safe_fixed),
true = Mod:info(Tab,fixed),
Mod:safe_fixtable(Tab, false),
false = Mod:info(Tab, safe_fixed),
false = Mod:info(Tab,fixed).
multiple_processes(Config) when is_list(Config) ->
{ok,Dets} = dets:open_file(?DETS_TMP1,[{file,
dets_filename(?DETS_TMP1,
Config)}]),
Ets = ets:new(ets,[public]),
multiple_processes(Dets,dets),
multiple_processes(Ets,ets),
ok.
multiple_processes(Tab, Mod) ->
io:format("Mod = ~p\n", [Mod]),
P1 = start_commander(),
P2 = start_commander(),
false = Mod:info(Tab,fixed),
false = Mod:info(Tab, safe_fixed),
command(P1, {Mod, safe_fixtable, [Tab,true]}),
true = Mod:info(Tab,fixed),
{_,[{P1,1}]} = Mod:info(Tab, safe_fixed),
command(P2, {Mod, safe_fixtable, [Tab,true]}),
true = Mod:info(Tab,fixed),
{_,L} = Mod:info(Tab,safe_fixed),
true = (lists:sort(L) == lists:sort([{P1,1},{P2,1}])),
command(P2, {Mod, safe_fixtable, [Tab,true]}),
{_,L2} = Mod:info(Tab,safe_fixed),
true = (lists:sort(L2) == lists:sort([{P1,1},{P2,2}])),
command(P2, {Mod, safe_fixtable, [Tab,false]}),
true = Mod:info(Tab,fixed),
{_,L3} = Mod:info(Tab,safe_fixed),
true = (lists:sort(L3) == lists:sort([{P1,1},{P2,1}])),
command(P2, {Mod, safe_fixtable, [Tab,false]}),
true = Mod:info(Tab,fixed),
{_,[{P1,1}]} = Mod:info(Tab, safe_fixed),
stop_commander(P1),
receive after 1000 -> ok end,
false = Mod:info(Tab,fixed),
false = Mod:info(Tab, safe_fixed),
command(P2, {Mod, safe_fixtable, [Tab,true]}),
true = Mod:info(Tab,fixed),
{_,[{P2,1}]} = Mod:info(Tab, safe_fixed),
case Mod of
dets ->
dets:close(Tab);
ets ->
ets:delete(Tab)
end,
stop_commander(P2),
receive after 1000 -> ok end,
undefined = Mod:info(Tab, safe_fixed),
ok.
dets_filename(Base, Config) when is_atom(Base) ->
dets_filename(atom_to_list(Base) ++ ".dat", Config);
dets_filename(Basename, Config) ->
PrivDir = proplists:get_value(priv_dir,Config),
filename:join(PrivDir, Basename).
command_loop() ->
receive
{From, command, {M,F,A}} ->
Res = (catch apply(M, F, A)),
From ! {self(), Res},
command_loop();
die ->
ok
end.
start_commander() ->
spawn(?MODULE, command_loop, []).
stop_commander(Pid) ->
process_flag(trap_exit, true),
link(Pid),
Pid ! die,
receive
{'EXIT',Pid,_} ->
true
after 5000 ->
exit(stop_timeout)
end.
command(Pid,MFA) ->
Pid ! {self(), command, MFA},
receive
{Pid, Res} ->
Res
after 20000 ->
exit(command_timeout)
end.
|
484caed8cc60eb2d2a719f8d926b7cd79ef2e9f94346be8a650b8f55be849cb5
|
mbutterick/beautiful-racket
|
main.rkt
|
#lang br/quicklang
(module+ reader
(provide read-syntax))
(define (tokenize ip)
(for/list ([tok (in-port read ip)])
tok))
(define (parse tok)
(if (list? tok)
(map parse tok)
'taco))
(define (read-syntax src ip)
(define toks (tokenize ip))
(define parse-tree (parse toks))
(with-syntax ([(PT ...) parse-tree])
#'(module tacofied racket
'PT ...)))
| null |
https://raw.githubusercontent.com/mbutterick/beautiful-racket/f0e2cb5b325733b3f9cbd554cc7d2bb236af9ee9/beautiful-racket-demo/quantum-taco-demo/main.rkt
|
racket
|
#lang br/quicklang
(module+ reader
(provide read-syntax))
(define (tokenize ip)
(for/list ([tok (in-port read ip)])
tok))
(define (parse tok)
(if (list? tok)
(map parse tok)
'taco))
(define (read-syntax src ip)
(define toks (tokenize ip))
(define parse-tree (parse toks))
(with-syntax ([(PT ...) parse-tree])
#'(module tacofied racket
'PT ...)))
|
|
85e14d10501af9a527475bbacc745f005758facb2999f5d9acfeba788276f99d
|
bollu/koans
|
recursion-schemes.hs
|
Implementation of Bananas , Lenses and Barbed Wire
data Star a = Nil | Cons a (Star a) deriving (Show, Eq)
cata :: b -> (a -> b -> b) -> Star a -> b
cata b combine =
let h = \x -> case x of
Nil -> b
Cons a as -> combine a (h as)
in h
ana :: (b -> Bool) -> (b -> (a, b)) -> b -> Star a
ana p g =
let h = \b -> if p b
then Nil
else
let (a, b') = g b in Cons a (h b')
in h
zip as
zip xs ys = ana (\(xs, ys) -> (null xs) || (null ys)) (\((x:xs), (y:ys)) -> ((x, y), (xs, ys))) (xs, ys)
iterate as
iterate :: (a -> a) -> a -> Star a
iterate f x = ana (const False) (\x -> (x, f x)) x
TODO : map as both cata and
hylo :: c -> (b -> c -> c) -> (a -> (b, a)) -> (a -> Bool) -> a -> c
hylo c combine g p =
let
h = \a -> if p a
then c
else
let (b, a') = g a
in combine b (h a')
in h
fact n = hylo 1 (*) (\x -> (x, x - 1)) (== 0) n
class Bifunctor f where
bimap :: (a -> b, c -> d) -> (f a c -> f b d)
| null |
https://raw.githubusercontent.com/bollu/koans/0204e9bb5ef9c541fe161523acac3cacae5d07fe/recursion-schemes.hs
|
haskell
|
Implementation of Bananas , Lenses and Barbed Wire
data Star a = Nil | Cons a (Star a) deriving (Show, Eq)
cata :: b -> (a -> b -> b) -> Star a -> b
cata b combine =
let h = \x -> case x of
Nil -> b
Cons a as -> combine a (h as)
in h
ana :: (b -> Bool) -> (b -> (a, b)) -> b -> Star a
ana p g =
let h = \b -> if p b
then Nil
else
let (a, b') = g b in Cons a (h b')
in h
zip as
zip xs ys = ana (\(xs, ys) -> (null xs) || (null ys)) (\((x:xs), (y:ys)) -> ((x, y), (xs, ys))) (xs, ys)
iterate as
iterate :: (a -> a) -> a -> Star a
iterate f x = ana (const False) (\x -> (x, f x)) x
TODO : map as both cata and
hylo :: c -> (b -> c -> c) -> (a -> (b, a)) -> (a -> Bool) -> a -> c
hylo c combine g p =
let
h = \a -> if p a
then c
else
let (b, a') = g a
in combine b (h a')
in h
fact n = hylo 1 (*) (\x -> (x, x - 1)) (== 0) n
class Bifunctor f where
bimap :: (a -> b, c -> d) -> (f a c -> f b d)
|
|
e0c641f49c03bdabfe4d08262db6bc494c6b347d576c2b1c119e365cb43e9152
|
stchang/parsack
|
main.rkt
|
#lang racket
(require "parsack.rkt")
(provide (all-from-out "parsack.rkt"))
| null |
https://raw.githubusercontent.com/stchang/parsack/57b21873e8e3eb7ffbdfa253251c3c27a66723b1/parsack-lib/parsack/main.rkt
|
racket
|
#lang racket
(require "parsack.rkt")
(provide (all-from-out "parsack.rkt"))
|
|
446b5b34c22b55a88c56c69634d1bec603c9bbd1281a01256fd51aef44ed3cfb
|
jafingerhut/clojure-benchmarks
|
revcomp.clj-10.clj
|
The Computer Language Benchmarks Game
;; /
contributed by
(ns revcomp
(:gen-class))
(set! *warn-on-reflection* true)
(def complement-dna-char-map
{\w \W, \W \W,
\s \S, \S \S,
\a \T, \A \T,
\t \A, \T \A,
\u \A, \U \A,
\g \C, \G \C,
\c \G, \C \G,
\y \R, \Y \R,
\r \Y, \R \Y,
\k \M, \K \M,
\m \K, \M \K,
\b \V, \B \V,
\d \H, \D \H,
\h \D, \H \D,
\v \B, \V \B,
\n \N, \N \N })
(defn make-array-char-mapper [cmap]
(int-array 256 (map (fn [i]
(if (contains? cmap (char i))
(int (cmap (char i)))
i))
(range 256))))
(defn revcomp-buf-and-write [#^java.lang.StringBuilder buf
#^java.io.BufferedWriter wrtr
#^ints comp]
(let [len (.length buf)
nl (int \newline)]
(when (> len 0)
(loop [begin (int 0)
end (int (dec len))]
(when (<= begin end)
then reverse and complement two more characters , working
;; from beginning and end towards the middle
(let [b (int (if (= (int (.charAt buf begin)) nl)
(inc begin)
begin))
e (int (if (= (int (.charAt buf end)) nl)
(dec end)
end))]
(when (<= b e)
(let [cb (char (aget comp (int (.charAt buf b))))
ce (char (aget comp (int (.charAt buf e))))]
(.setCharAt buf b ce)
(.setCharAt buf e cb)
(recur (inc b) (dec e)))))))
(.write wrtr (.toString buf) 0 len))))
(defn -main [& args]
(let [rdr (java.io.BufferedReader. *in*)
wrtr (java.io.BufferedWriter. *out*)
complement-dna-char-array (make-array-char-mapper
complement-dna-char-map)]
(loop [line (.readLine rdr)
buf (new java.lang.StringBuilder)]
(if line
(if (= (get line 0) \>)
then print out revcomp of any string in buf , and after
;; that, the line just read
(do
(revcomp-buf-and-write buf wrtr complement-dna-char-array)
(.write wrtr line 0 (count line))
(.newLine wrtr)
(recur (.readLine rdr) (new java.lang.StringBuilder)))
else add the line to buf
(do
(.append buf line)
(.append buf \newline)
(recur (.readLine rdr) buf)))
else print out revcomp of any string in buf
(revcomp-buf-and-write buf wrtr complement-dna-char-array)))
(.flush wrtr)))
| null |
https://raw.githubusercontent.com/jafingerhut/clojure-benchmarks/474a8a4823727dd371f1baa9809517f9e0b508d4/revcomp/revcomp.clj-10.clj
|
clojure
|
/
from beginning and end towards the middle
that, the line just read
|
The Computer Language Benchmarks Game
contributed by
(ns revcomp
(:gen-class))
(set! *warn-on-reflection* true)
(def complement-dna-char-map
{\w \W, \W \W,
\s \S, \S \S,
\a \T, \A \T,
\t \A, \T \A,
\u \A, \U \A,
\g \C, \G \C,
\c \G, \C \G,
\y \R, \Y \R,
\r \Y, \R \Y,
\k \M, \K \M,
\m \K, \M \K,
\b \V, \B \V,
\d \H, \D \H,
\h \D, \H \D,
\v \B, \V \B,
\n \N, \N \N })
(defn make-array-char-mapper [cmap]
(int-array 256 (map (fn [i]
(if (contains? cmap (char i))
(int (cmap (char i)))
i))
(range 256))))
(defn revcomp-buf-and-write [#^java.lang.StringBuilder buf
#^java.io.BufferedWriter wrtr
#^ints comp]
(let [len (.length buf)
nl (int \newline)]
(when (> len 0)
(loop [begin (int 0)
end (int (dec len))]
(when (<= begin end)
then reverse and complement two more characters , working
(let [b (int (if (= (int (.charAt buf begin)) nl)
(inc begin)
begin))
e (int (if (= (int (.charAt buf end)) nl)
(dec end)
end))]
(when (<= b e)
(let [cb (char (aget comp (int (.charAt buf b))))
ce (char (aget comp (int (.charAt buf e))))]
(.setCharAt buf b ce)
(.setCharAt buf e cb)
(recur (inc b) (dec e)))))))
(.write wrtr (.toString buf) 0 len))))
(defn -main [& args]
(let [rdr (java.io.BufferedReader. *in*)
wrtr (java.io.BufferedWriter. *out*)
complement-dna-char-array (make-array-char-mapper
complement-dna-char-map)]
(loop [line (.readLine rdr)
buf (new java.lang.StringBuilder)]
(if line
(if (= (get line 0) \>)
then print out revcomp of any string in buf , and after
(do
(revcomp-buf-and-write buf wrtr complement-dna-char-array)
(.write wrtr line 0 (count line))
(.newLine wrtr)
(recur (.readLine rdr) (new java.lang.StringBuilder)))
else add the line to buf
(do
(.append buf line)
(.append buf \newline)
(recur (.readLine rdr) buf)))
else print out revcomp of any string in buf
(revcomp-buf-and-write buf wrtr complement-dna-char-array)))
(.flush wrtr)))
|
3922041919475589236a1c7e05ffaf5bb00b48ad7c0db6b8797f630b76cc8037
|
lexi-lambda/hackett
|
info.rkt
|
#lang info
(define collection 'multi)
(define deps
'("base"
"hackett-lib"
["scribble-lib" #:version "1.16"]))
(define build-deps
'("at-exp-lib"
"racket-doc"))
| null |
https://raw.githubusercontent.com/lexi-lambda/hackett/e90ace9e4a056ec0a2a267f220cb29b756cbefce/hackett-doc/info.rkt
|
racket
|
#lang info
(define collection 'multi)
(define deps
'("base"
"hackett-lib"
["scribble-lib" #:version "1.16"]))
(define build-deps
'("at-exp-lib"
"racket-doc"))
|
|
aaa0a113f54413e6037f26e55f5aff581dbd05d5c8b0bfa7285dd642a15b5048
|
BillHallahan/G2
|
Reducer.hs
|
# LANGUAGE DeriveGeneric #
# LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
# LANGUAGE FunctionalDependencies #
{-# LANGUAGE GADTs #-}
# LANGUAGE MultiParamTypeClasses #
{-# LANGUAGE RankNTypes #-}
# LANGUAGE UndecidableInstances #
module G2.Execution.Reducer ( Reducer (..)
, Halter (..)
, Orderer (..)
, Processed (..)
, mapProcessed
, ReducerRes (..)
, HaltC (..)
, SomeReducer (..)
, SomeHalter (..)
, SomeOrderer (..)
-- Reducers
, InitReducer
, RedRules
, mkSimpleReducer
, stdRed
, nonRedPCRed
, nonRedPCRedConst
, taggerRed
, getLogger
, simpleLogger
, prettyLogger
, limLogger
, LimLogger (..)
, (<~)
, (<~?)
, (<~|)
, (.|.)
, (.<~)
, (.<~?)
, (.<~|)
Halters
, mkSimpleHalter
, swhnfHalter
, acceptIfViolatedHalter
, (<~>)
, zeroHalter
, discardIfAcceptedTagHalter
, maxOutputsHalter
, switchEveryNHalter
, varLookupLimitHalter
, stdTimerHalter
, timerHalter
-- Orderers
, mkSimpleOrderer
, (<->)
, ordComb
, nextOrderer
, pickLeastUsedOrderer
, bucketSizeOrderer
, adtHeightOrderer
, adtSizeOrderer
, pcSizeOrderer
, incrAfterN
, quotTrueAssert
, runReducer ) where
import G2.Config
import qualified G2.Language.ExprEnv as E
import G2.Execution.Rules
import G2.Language
import qualified G2.Language.Monad as MD
import qualified G2.Language.PathConds as PC
import qualified G2.Language.Stack as Stck
import G2.Solver
import G2.Lib.Printers
import Control.Monad.IO.Class
import qualified Control.Monad.State as SM
import Data.Foldable
import qualified Data.HashSet as HS
import qualified Data.HashMap.Strict as HM
import qualified Data.Map as M
import Data.Maybe
import Data.Monoid ((<>))
import qualified Data.List as L
import Data.Tuple
import Data.Time.Clock
import System.Directory
-- | Used when applying execution rules
-- Allows tracking extra information to control halting of rule application,
-- and to reorder states
see also , the Reducer , Halter ,
-- cases is used for logging states
data ExState rv hv sov t = ExState { state :: State t
, reducer_val :: rv
, halter_val :: hv
, order_val :: sov
}
-- | Keeps track of type a's that have either been accepted or dropped
data Processed a = Processed { accepted :: [a]
, discarded :: [a] }
mapProcessed :: (a -> b) -> Processed a -> Processed b
mapProcessed f pr = Processed { accepted = map f (accepted pr)
, discarded = map f (discarded pr)}
-- | Used by Reducers to indicate their progress reducing.
data ReducerRes = NoProgress | InProgress | Finished deriving (Eq, Ord, Show, Read)
progPrioritizer :: ReducerRes -> ReducerRes -> ReducerRes
progPrioritizer InProgress _ = InProgress
progPrioritizer _ InProgress = InProgress
progPrioritizer Finished _ = Finished
progPrioritizer _ Finished = Finished
progPrioritizer _ _ = NoProgress
-- | Used by members of the Halter typeclass to control whether to continue
evaluating the current State , or switch to evaluating a new state .
data HaltC = Discard -- ^ Switch to evaluating a new state, and reject the current state
| Accept -- ^ Switch to evaluating a new state, and accept the current state
| Switch -- ^ Switch to evaluating a new state, but continue evaluating the current state later
^ Continue evaluating the current State
deriving (Eq, Ord, Show, Read)
type InitReducer rv t = State t -> rv
type RedRules m rv t = rv -> State t -> Bindings -> m (ReducerRes, [(State t, rv)], Bindings)
| A Reducer is used to describe a set of Reduction Rules .
Reduction Rules take a State , and output new states .
-- The type parameter r is used to disambiguate between different producers.
To create a new reducer , define some new type , and use it as r.
-- The reducer value, rv, can be used to track special, per Reducer, information.
data Reducer m rv t = Reducer {
-- | Initialized the reducer value
initReducer :: InitReducer rv t
| Takes a State , and performs the appropriate Reduction Rule
, redRules :: RedRules m rv t
-- | After a reducer returns multiple states,
gives an opportunity to update with all States and ,
output by all 's , visible
-- Errors if the returned list is too short.
If only one state is returned by all reducers , updateWithAll does not run .
, updateWithAll :: [(State t, rv)] -> [rv]
, onAccept :: State t -> rv -> m ()
}
# INLINE mkSimpleReducer #
mkSimpleReducer :: Monad m => InitReducer rv t -> RedRules m rv t -> Reducer m rv t
mkSimpleReducer init_red red_rules =
Reducer {
initReducer = init_red
, redRules = red_rules
, updateWithAll = map snd
, onAccept = \_ _ -> return ()
}
type InitHalter hv t = State t -> hv
type UpdatePerStateHalt hv t = hv -> Processed (State t) -> State t -> hv
type StopRed m hv t = hv -> Processed (State t) -> State t -> m HaltC
type StepHalter hv t = hv -> Processed (State t) -> [State t] -> State t -> hv
-- | Determines when to stop evaluating a state
-- The type parameter h is used to disambiguate between different producers.
-- To create a new Halter, define some new type, and use it as h.
data Halter m hv t = Halter {
-- | Initializes each state halter value
initHalt :: InitHalter hv t
-- | Runs whenever we switch to evaluating a different state,
-- to update the halter value of that new state
, updatePerStateHalt :: UpdatePerStateHalt hv t
-- | Runs when we start execution on a state, immediately after
` updatePerStateHalt ` . Allows a State to be discarded right
-- before execution is about to (re-)begin.
-- Return True if execution should proceed, False to discard
, discardOnStart :: hv -> Processed (State t) -> State t -> Bool
-- | Determines whether to continue reduction on the current state
, stopRed :: StopRed m hv t
-- | Takes a state, and updates its halter record field
, stepHalter :: StepHalter hv t
-- | After multiple states, are returned
gives an opportunity to update halters with all States and halter values visible .
-- Errors if the returned list is too short.
If only one state is returned , updateHalterWithAll does not run .
, updateHalterWithAll :: [(State t, hv)] -> [hv]
}
# INLINE mkSimpleHalter #
mkSimpleHalter :: Monad m => InitHalter hv t -> UpdatePerStateHalt hv t -> StopRed m hv t -> StepHalter hv t -> Halter m hv t
mkSimpleHalter initial update stop step = Halter { initHalt = initial
, updatePerStateHalt = update
, discardOnStart = \_ _ _ -> False
, stopRed = stop
, stepHalter = step
, updateHalterWithAll = map snd }
# INLINE mkStoppingHalter #
mkStoppingHalter :: Monad m => StopRed m () t -> Halter m () t
mkStoppingHalter stop =
mkSimpleHalter
(const ())
(\_ _ _ -> ())
stop
(\_ _ _ _ -> ())
type InitOrderer sov t = State t -> sov
type OrderStates sov b t = sov -> Processed (State t) -> State t -> b
type UpdateSelected sov t = sov -> Processed (State t) -> State t -> sov
-- | Picks an order to evaluate the states, to allow prioritizing some over others
-- The type parameter or is used to disambiguate between different producers.
-- To create a new reducer, define some new type, and use it as or.
data Orderer sov b t = Orderer {
-- | Initializing the per state ordering value
initPerStateOrder :: InitOrderer sov t
-- | Assigns each state some value of an ordered type, and then proceeds with execution on the
-- state assigned the minimal value
, orderStates :: OrderStates sov b t
-- | Run on the selected state, to update it's sov field
, updateSelected :: UpdateSelected sov t
-- | Run on the state at each step, to update it's sov field
, stepOrderer :: sov -> Processed (State t) -> [State t] -> State t -> sov
}
mkSimpleOrderer :: InitOrderer sov t -> OrderStates sov b t -> UpdateSelected sov t -> Orderer sov b t
mkSimpleOrderer initial order update = Orderer { initPerStateOrder = initial
, orderStates = order
, updateSelected = update
, stepOrderer = \sov _ _ _ -> sov}
getState :: M.Map b [s] -> Maybe (b, [s])
getState = M.lookupMin
data SomeReducer m t where
SomeReducer :: forall m rv t . Reducer m rv t -> SomeReducer m t
data SomeHalter m t where
SomeHalter :: forall m hv t . Halter m hv t -> SomeHalter m t
data SomeOrderer t where
SomeOrderer :: forall sov b t . Ord b => Orderer sov b t -> SomeOrderer t
----------------------------------------------------
-- Combines reducers in various ways
We use RC to combine the reducer values for RCombiner
We should never define any other instance of Reducer with RC , or export it
-- because this could lead to undecidable instances
data RC a b = RC a b
{-# INLINE (<~) #-}
(<~) :: Monad m => Reducer m rv1 t -> Reducer m rv2 t -> Reducer m (RC rv1 rv2) t
r1 <~ r2 =
Reducer { initReducer = \s -> RC (initReducer r1 s) (initReducer r2 s)
, redRules = \(RC rv1 rv2) s b -> do
(rr2, srv2, b') <- redRules r2 rv2 s b
(rr1, srv1, b'') <- redRulesToStates r1 rv1 srv2 b'
return (progPrioritizer rr1 rr2, srv1, b'')
, updateWithAll = updateWithAllPair (updateWithAll r1) (updateWithAll r2)
, onAccept = \s (RC rv1 rv2) -> do
onAccept r1 s rv1
onAccept r2 s rv2
}
{-# INLINE (<~?) #-}
(<~?) :: Monad m => Reducer m rv1 t -> Reducer m rv2 t -> Reducer m (RC rv1 rv2) t
r1 <~? r2 =
Reducer { initReducer = \s -> RC (initReducer r1 s) (initReducer r2 s)
, redRules = \(RC rv1 rv2) s b -> do
(rr2, srv2, b') <- redRules r2 rv2 s b
let (s', rv2') = unzip srv2
case rr2 of
NoProgress -> do
(rr1, ss, b'') <- redRulesToStates r1 rv1 srv2 b'
return (rr1, ss, b'')
_ -> return (rr2, zip s' (map (RC rv1) rv2'), b')
, updateWithAll = updateWithAllPair (updateWithAll r1) (updateWithAll r2)
, onAccept = \s (RC rv1 rv2) -> do
onAccept r1 s rv1
onAccept r2 s rv2
}
{-# INLINE (<~|) #-}
(<~|) :: Monad m => Reducer m rv1 t -> Reducer m rv2 t -> Reducer m (RC rv1 rv2) t
r1 <~| r2 =
Reducer { initReducer = \s -> RC (initReducer r1 s) (initReducer r2 s)
, redRules = \(RC rv1 rv2) s b -> do
(rr2, srv2, b') <- redRules r2 rv2 s b
let (s', rv2') = unzip srv2
case rr2 of
Finished -> do
(rr1, ss, b'') <- redRulesToStates r1 rv1 srv2 b'
return (rr1, ss, b'')
_ -> return (rr2, zip s' (map (RC rv1) rv2'), b')
, updateWithAll = updateWithAllPair (updateWithAll r1) (updateWithAll r2)
, onAccept = \s (RC rv1 rv2) -> do
onAccept r1 s rv1
onAccept r2 s rv2
}
# INLINE ( .| . ) #
(.|.) :: Monad m => Reducer m rv1 t -> Reducer m rv2 t -> Reducer m (RC rv1 rv2) t
r1 .|. r2 =
Reducer { initReducer = \s -> RC (initReducer r1 s) (initReducer r2 s)
, redRules = \(RC rv1 rv2) s b -> do
(rr2, srv2, b') <- redRules r2 rv2 s b
(rr1, srv1, b'') <- redRules r1 rv1 s b'
let srv2' = map (\(s_, rv2_) -> (s_, RC rv1 rv2_) ) srv2
srv1' = map (\(s_, rv1_) -> (s_, RC rv1_ rv2) ) srv1
return (progPrioritizer rr1 rr2, srv2' ++ srv1', b'')
, updateWithAll = updateWithAllPair (updateWithAll r1) (updateWithAll r2)
, onAccept = \s (RC rv1 rv2) -> do
onAccept r1 s rv1
onAccept r2 s rv2
}
{-# INLINE (.<~) #-}
(.<~) :: Monad m => SomeReducer m t -> SomeReducer m t -> SomeReducer m t
SomeReducer r1 .<~ SomeReducer r2 = SomeReducer (r1 <~ r2)
{-# INLINE (.<~?) #-}
(.<~?) :: Monad m => SomeReducer m t -> SomeReducer m t -> SomeReducer m t
SomeReducer r1 .<~? SomeReducer r2 = SomeReducer (r1 <~? r2)
{-# INLINE (.<~|) #-}
(.<~|) :: Monad m => SomeReducer m t -> SomeReducer m t -> SomeReducer m t
SomeReducer r1 .<~| SomeReducer r2 = SomeReducer (r1 <~| r2)
updateWithAllPair :: ([(State t, rv1)] -> [rv1]) -> ([(State t, rv2)] -> [rv2]) -> [(State t, RC rv1 rv2)] -> [RC rv1 rv2]
updateWithAllPair update1 update2 srv =
let
srv1 = map (\(s, RC rv1 _) -> (s, rv1)) srv
srv2 = map (\(s, RC _ rv2) -> (s, rv2)) srv
rv1' = update1 srv1
rv2' = update2 srv2
in
map (uncurry RC) $ zip rv1' rv2'
redRulesToStatesAux :: Monad m => Reducer m rv t -> rv -> Bindings -> (State t, rv2) -> m (Bindings, (ReducerRes, [(State t, RC rv rv2)]))
redRulesToStatesAux r rv1 b (is, rv2) = do
(rr_, is', b') <- redRules r rv1 is b
return (b', (rr_, map (\(is'', rv1') -> (is'', RC rv1' rv2) ) is'))
redRulesToStates :: Monad m => Reducer m rv t -> rv -> [(State t, rv2)] -> Bindings -> m (ReducerRes, [(State t, RC rv rv2)], Bindings)
redRulesToStates r rv1 s b = do
let redRulesToStatesAux' = redRulesToStatesAux r rv1
(b', rs) <- MD.mapMAccumB redRulesToStatesAux' b s
let (rr, s') = L.unzip rs
let rf = foldr progPrioritizer NoProgress rr
return $ (rf, concat s', b')
# INLINE stdRed #
stdRed :: (MonadIO m, Solver solver, Simplifier simplifier) => Sharing -> solver -> simplifier -> Reducer m () t
stdRed share solver simplifier =
mkSimpleReducer (\_ -> ())
(\_ s b -> do
(r, s', b') <- liftIO $ stdReduce share solver simplifier s b
return (if r == RuleIdentity then Finished else InProgress, s', b')
)
| Removes and reduces the values in a State 's non_red_path_conds field .
# INLINE nonRedPCRed #
nonRedPCRed :: Monad m => Reducer m () t
nonRedPCRed = mkSimpleReducer (\_ -> ())
nonRedPCRedFunc
nonRedPCRedFunc :: Monad m => RedRules m () t
nonRedPCRedFunc _
s@(State { expr_env = eenv
, curr_expr = cexpr
, exec_stack = stck
, non_red_path_conds = nr:nrs
, model = m })
b@(Bindings { higher_order_inst = inst }) = do
let stck' = Stck.push (CurrExprFrame AddPC cexpr) stck
let cexpr' = CurrExpr Evaluate nr
let eenv_si_ces = substHigherOrder eenv m inst cexpr'
let s' = s { exec_stack = stck'
, non_red_path_conds = nrs
}
xs = map (\(eenv', m', ce) -> (s' { expr_env = eenv'
, model = m'
, curr_expr = ce }, ())) eenv_si_ces
return (InProgress, xs, b)
nonRedPCRedFunc _ s b = return (Finished, [(s, ())], b)
-- [Higher-Order Model]
-- Substitutes all possible higher order functions for symbolic higher order functions.
-- We insert the substituted higher order function directly into the model, because, due
-- to the VAR-RED rule, the function name will (if the function is called) be lost during execution.
substHigherOrder :: ExprEnv -> Model -> HS.HashSet Name -> CurrExpr -> [(ExprEnv, Model, CurrExpr)]
substHigherOrder eenv m ns ce =
let
is = mapMaybe (\n -> case E.lookup n eenv of
Just e -> Just $ Id n (typeOf e)
Nothing -> Nothing) $ HS.toList ns
higherOrd = filter (isTyFun . typeOf) . symbVars eenv $ ce
higherOrdSub = map (\v -> (v, mapMaybe (genSubstitutable v) is)) higherOrd
in
substHigherOrder' [(eenv, m, ce)] higherOrdSub
where
genSubstitutable v i
| Just bm <- specializes (typeOf v) (typeOf i) =
let
bnds = map idName $ leadingTyForAllBindings i
tys = mapMaybe (\b -> fmap Type $ M.lookup b bm) bnds
in
Just . mkApp $ Var i:tys
| otherwise = Nothing
substHigherOrder' :: [(ExprEnv, Model, CurrExpr)] -> [(Id, [Expr])] -> [(ExprEnv, Model, CurrExpr)]
substHigherOrder' eenvsice [] = eenvsice
substHigherOrder' eenvsice ((i, es):iss) =
substHigherOrder'
(concatMap (\e_rep ->
map (\(eenv, m, ce) -> ( E.insert (idName i) e_rep eenv
, HM.insert (idName i) e_rep m
, replaceASTs (Var i) e_rep ce)
) eenvsice)
es) iss
| Removes and reduces the values in a State 's non_red_path_conds field by instantiating higher order functions to be constant
nonRedPCRedConst :: Monad m => Reducer m () t
nonRedPCRedConst = mkSimpleReducer (\_ -> ())
nonRedPCRedConstFunc
nonRedPCRedConstFunc :: Monad m => RedRules m () t
nonRedPCRedConstFunc _
s@(State { expr_env = eenv
, curr_expr = cexpr
, exec_stack = stck
, non_red_path_conds = nr:nrs
, model = m })
b@(Bindings { name_gen = ng }) = do
let stck' = Stck.push (CurrExprFrame AddPC cexpr) stck
let cexpr' = CurrExpr Evaluate nr
let higher_ord = L.filter (isTyFun . typeOf) $ E.symbolicIds eenv
(ng', new_lam_is) = L.mapAccumL (\ng_ ts -> swap $ freshIds ts ng_) ng (map anonArgumentTypes higher_ord)
(new_sym_gen, ng'') = freshIds (map returnType higher_ord) ng'
es = map (\(f_id, lam_i, sg_i) -> (f_id, mkLams (zip (repeat TermL) lam_i) (Var sg_i)) )
$ zip3 higher_ord new_lam_is new_sym_gen
eenv' = foldr (uncurry E.insert) eenv (map (\(i, e) -> (idName i, e)) es)
eenv'' = foldr E.insertSymbolic eenv' new_sym_gen
m' = foldr (\(i, e) -> HM.insert (idName i) e) m es
let s' = s { expr_env = eenv''
, curr_expr = cexpr'
, model = m'
, exec_stack = stck'
, non_red_path_conds = nrs
}
return (InProgress, [(s', ())], b { name_gen = ng'' })
nonRedPCRedConstFunc _ s b = return (Finished, [(s, ())], b)
# INLINE taggerRed #
taggerRed :: Monad m => Name -> Reducer m () t
taggerRed n = mkSimpleReducer (const ()) (taggerRedStep n)
taggerRedStep :: Monad m => Name -> RedRules m () t
taggerRedStep n _ s@(State {tags = ts}) b@(Bindings { name_gen = ng }) =
let
(n'@(Name n_ m_ _ _), ng') = freshSeededName n ng
in
if null $ HS.filter (\(Name n__ m__ _ _) -> n_ == n__ && m_ == m__) ts then
return (Finished, [(s {tags = HS.insert n' ts}, ())], b { name_gen = ng' })
else
return (Finished, [(s, ())], b)
getLogger :: (MonadIO m, Show t) => Config -> Maybe (Reducer (SM.StateT PrettyGuide m) [Int] t)
getLogger config = case logStates config of
Log Raw fp -> Just (simpleLogger fp)
Log Pretty fp -> Just (prettyLogger fp)
NoLog -> Nothing
-- | A Reducer to producer logging output
simpleLogger :: (MonadIO m, Show t) => FilePath -> Reducer m [Int] t
simpleLogger fn =
(mkSimpleReducer (const [])
(\li s b -> do
liftIO $ outputState fn li s b pprExecStateStr
return (NoProgress, [(s, li)], b) ))
{ updateWithAll = \s -> map (\(l, i) -> l ++ [i]) $ zip (map snd s) [1..] }
-- | A Reducer to producer logging output
prettyLogger :: (MonadIO m, Show t) => FilePath -> Reducer (SM.StateT PrettyGuide m) [Int] t
prettyLogger fp =
(mkSimpleReducer
(const [])
(\li s b -> do
pg <- SM.get
let pg' = updatePrettyGuide (s { track = () }) pg
SM.put pg'
liftIO $ outputState fp li s b (\s_ _ -> prettyState pg' s_)
return (NoProgress, [(s, li)], b)
)
) { updateWithAll = \s -> map (\(l, i) -> l ++ [i]) $ zip (map snd s) [1..]
, onAccept = \_ ll -> liftIO . putStrLn $ "Accepted on path " ++ show ll }
-- | A Reducer to producer limited logging output.
data LimLogger =
LimLogger { every_n :: Int -- Output a state every n steps
, after_n :: Int -- Only begin outputting after passing a certain n
, before_n :: Maybe Int -- Only output before a certain n
, down_path :: [Int] -- Output states that have gone down or are going down the given path prefix
, lim_output_path :: String
}
data LLTracker = LLTracker { ll_count :: Int, ll_offset :: [Int]}
limLogger :: (MonadIO m, Show t) => LimLogger -> Reducer m LLTracker t
limLogger ll@(LimLogger { after_n = aft, before_n = bfr, down_path = down }) =
(mkSimpleReducer (const $ LLTracker { ll_count = every_n ll, ll_offset = []}) rr)
{ updateWithAll = updateWithAllLL
, onAccept = \_ llt -> liftIO . putStrLn $ "Accepted on path " ++ show (ll_offset llt)}
where
rr llt@(LLTracker { ll_count = 0, ll_offset = off }) s b
| down `L.isPrefixOf` off || off `L.isPrefixOf` down
, aft <= length_rules && maybe True (length_rules <=) bfr = do
liftIO $ outputState (lim_output_path ll) off s b pprExecStateStr
return (NoProgress, [(s, llt { ll_count = every_n ll })], b)
| otherwise =
return (NoProgress, [(s, llt { ll_count = every_n ll })], b)
where
length_rules = length (rules s)
rr llt@(LLTracker {ll_count = n}) s b =
return (NoProgress, [(s, llt { ll_count = n - 1 })], b)
updateWithAllLL [(_, l)] = [l]
updateWithAllLL ss =
map (\(llt, i) -> llt { ll_offset = ll_offset llt ++ [i] }) $ zip (map snd ss) [1..]
outputState :: FilePath -> [Int] -> State t -> Bindings -> (State t -> Bindings -> String) -> IO ()
outputState dn is s b printer = do
fn <- getFile dn is "state" s
-- Don't re-output states that already exist
exists <- doesPathExist fn
if not exists
then do
let write = printer s b
writeFile fn write
putStrLn fn
else return ()
getFile :: String -> [Int] -> String -> State t -> IO String
getFile dn is n s = do
let dir = dn ++ "/" ++ foldl' (\str i -> str ++ show i ++ "/") "" is
createDirectoryIfMissing True dir
let fn = dir ++ n ++ show (length $ rules s) ++ ".txt"
return fn
-- We use C to combine the halter values for HCombiner
-- We should never define any other instance of Halter with C, or export it
-- because this could lead to undecidable instances
data C a b = C a b deriving Eq
instance (ASTContainer a Expr, ASTContainer b Expr) => ASTContainer (C a b) Expr where
containedASTs (C a b) = containedASTs a ++ containedASTs b
modifyContainedASTs f (C a b) = C (modifyContainedASTs f a) (modifyContainedASTs f b)
instance (ASTContainer a Type, ASTContainer b Type) => ASTContainer (C a b) Type where
containedASTs (C a b) = containedASTs a ++ containedASTs b
modifyContainedASTs f (C a b) = C (modifyContainedASTs f a) (modifyContainedASTs f b)
instance (Named a, Named b) => Named (C a b) where
names (C a b) = names a <> names b
rename old new (C a b) = C (rename old new a) (rename old new b)
renames hm (C a b) = C (renames hm a) (renames hm b)
-- | Allows executing multiple halters.
-- If the halters disagree, prioritizes the order:
Discard , Accept , Switch , Continue
(<~>) :: Monad m => Halter m hv1 t -> Halter m hv2 t -> Halter m (C hv1 hv2) t
h1 <~> h2 =
Halter {
initHalt = \s ->
let
hv1 = initHalt h1 s
hv2 = initHalt h2 s
in
C hv1 hv2
, updatePerStateHalt = \(C hv1 hv2) proc s ->
let
hv1' = updatePerStateHalt h1 hv1 proc s
hv2' = updatePerStateHalt h2 hv2 proc s
in
C hv1' hv2'
, discardOnStart = \(C hv1 hv2) proc s ->
let
b1 = discardOnStart h1 hv1 proc s
b2 = discardOnStart h2 hv2 proc s
in
b1 || b2
, stopRed = \(C hv1 hv2) proc s -> do
hc1 <- stopRed h1 hv1 proc s
hc2 <- stopRed h2 hv2 proc s
return $ min hc1 hc2
, stepHalter = \(C hv1 hv2) proc xs s ->
let
hv1' = stepHalter h1 hv1 proc xs s
hv2' = stepHalter h2 hv2 proc xs s
in
C hv1' hv2'
, updateHalterWithAll = \shv ->
let
shv1 = map (\(s, C hv1 _) -> (s, hv1)) shv
shv2 = map (\(s, C _ hv2) -> (s, hv2)) shv
shv1' = updateHalterWithAll h1 shv1
shv2' = updateHalterWithAll h2 shv2
in
map (uncurry C) $ zip shv1' shv2'
}
{-# INLINE (<~>) #-}
# INLINE swhnfHalter #
swhnfHalter :: Monad m => Halter m () t
swhnfHalter = mkStoppingHalter stop
where
stop _ _ s =
case isExecValueForm s of
True -> return Accept
False -> return Continue
| Accepts a state when it is in SWHNF and is true
Discards it if in SWHNF and true_assert is false
acceptIfViolatedHalter :: Monad m => Halter m () t
acceptIfViolatedHalter = mkStoppingHalter stop
where
stop _ _ s =
case isExecValueForm s of
True
| true_assert s -> return Accept
| otherwise -> return Discard
False -> return Continue
-- | Allows execution to continue until the step counter hits 0, then discards the state
zeroHalter :: Monad m => Int -> Halter m Int t
zeroHalter n = mkSimpleHalter
(const n)
(\h _ _ -> h)
(\h _ _ -> if h == 0 then return Discard else return Continue)
(\h _ _ _ -> h - 1)
maxOutputsHalter :: Monad m => Maybe Int -> Halter m (Maybe Int) t
maxOutputsHalter m = mkSimpleHalter
(const m)
(\hv _ _ -> hv)
(\_ (Processed {accepted = acc}) _ ->
case m of
Just m' -> return $ if length acc >= m' then Discard else Continue
_ -> return Continue)
(\hv _ _ _ -> hv)
-- | Switch execution every n steps
# INLINE switchEveryNHalter #
switchEveryNHalter :: Monad m => Int -> Halter m Int t
switchEveryNHalter sw = (mkSimpleHalter
(const sw)
(\_ _ _ -> sw)
(\i _ _ -> return $ if i <= 0 then Switch else Continue)
(\i _ _ _ -> i - 1))
{ updateHalterWithAll = updateAll }
where
updateAll [] = []
updateAll xs@((_, c):_) =
let
len = length xs
c' = c `quot` len
in
replicate len c'
| If the Name , disregarding the Unique , in the DiscardIfAcceptedTag
-- matches a Tag in the Accepted State list,
and in the State being evaluated , discard the State
discardIfAcceptedTagHalter :: Monad m => Name -> Halter m (HS.HashSet Name) t
discardIfAcceptedTagHalter (Name n m _ _) =
mkSimpleHalter
(const HS.empty)
ups
(\ns _ _ -> return $ if not (HS.null ns) then Discard else Continue)
(\hv _ _ _ -> hv)
where
ups _
(Processed {accepted = acc})
(State {tags = ts}) =
let
allAccTags = HS.unions $ map tags acc
matchCurrState = HS.intersection ts allAccTags
in
HS.filter (\(Name n' m' _ _) -> n == n' && m == m') matchCurrState
-- | Counts the number of variable lookups are made, and switches the state
-- whenever we've hit a threshold
varLookupLimitHalter :: Monad m => Int -> Halter m Int t
varLookupLimitHalter lim = mkSimpleHalter
(const lim)
(\_ _ _ -> lim)
(\l _ _ -> return $ if l <= 0 then Switch else Continue)
step
where
step l _ _ (State { curr_expr = CurrExpr Evaluate (Var _) }) = l - 1
step l _ _ _ = l
# INLINE stdTimerHalter #
stdTimerHalter :: (MonadIO m, MonadIO m_run) => NominalDiffTime -> m (Halter m_run Int t)
stdTimerHalter ms = timerHalter ms Discard 10
# INLINE timerHalter #
timerHalter :: (MonadIO m, MonadIO m_run) => NominalDiffTime -> HaltC -> Int -> m (Halter m_run Int t)
timerHalter ms def ce = do
curr <- liftIO $ getCurrentTime
return $ mkSimpleHalter
(const 0)
(\_ _ _ -> 0)
(stop curr)
step
where
stop it v (Processed { accepted = acc }) _
| v == 0
, not (null acc) = do
curr <- liftIO $ getCurrentTime
let diff = diffUTCTime curr it
if diff > ms
then return def
else return Continue
| otherwise = return Continue
step v _ _ _
| v >= ce = 0
| otherwise = v + 1
-- Orderer things
(<->) :: Orderer sov1 b1 t -> Orderer sov2 b2 t -> Orderer (C sov1 sov2) (b1, b2) t
or1 <-> or2 = Orderer {
initPerStateOrder = \s ->
let
sov1 = initPerStateOrder or1 s
sov2 = initPerStateOrder or2 s
in
C sov1 sov2
, orderStates = \(C sov1 sov2) pr s ->
let
sov1' = orderStates or1 sov1 pr s
sov2' = orderStates or2 sov2 pr s
in
(sov1', sov2')
, updateSelected = \(C sov1 sov2) proc s ->
let
sov1' = updateSelected or1 sov1 proc s
sov2' = updateSelected or2 sov2 proc s
in
C sov1' sov2'
, stepOrderer = \(C sov1 sov2) proc xs s ->
let
sov1' = stepOrderer or1 sov1 proc xs s
sov2' = stepOrderer or2 sov2 proc xs s
in
C sov1' sov2'
}
ordComb :: (v1 -> v2 -> v3) -> Orderer sov1 v1 t -> Orderer sov2 v2 t -> Orderer(C sov1 sov2) v3 t
ordComb f or1 or2 = Orderer {
initPerStateOrder = \s ->
let
sov1 = initPerStateOrder or1 s
sov2 = initPerStateOrder or2 s
in
C sov1 sov2
, orderStates = \(C sov1 sov2) pr s ->
let
sov1' = orderStates or1 sov1 pr s
sov2' = orderStates or2 sov2 pr s
in
f sov1' sov2'
, updateSelected = \(C sov1 sov2) proc s ->
let
sov1' = updateSelected or1 sov1 proc s
sov2' = updateSelected or2 sov2 proc s
in
C sov1' sov2'
, stepOrderer = \(C sov1 sov2) proc xs s ->
let
sov1' = stepOrderer or1 sov1 proc xs s
sov2' = stepOrderer or2 sov2 proc xs s
in
C sov1' sov2'
}
nextOrderer :: Orderer () Int t
nextOrderer = mkSimpleOrderer (const ()) (\_ _ _ -> 0) (\v _ _ -> v)
-- | Continue execution on the state that has been picked the least in the past.
pickLeastUsedOrderer :: Orderer Int Int t
pickLeastUsedOrderer = mkSimpleOrderer (const 0) (\v _ _ -> v) (\v _ _ -> v + 1)
-- | Floors and does bucket size
bucketSizeOrderer :: Int -> Orderer Int Int t
bucketSizeOrderer b =
mkSimpleOrderer (const 0)
(\v _ _ -> floor (fromIntegral v / fromIntegral b :: Float))
(\v _ _ -> v + 1)
| Orders by the size ( in terms of height ) of ( previously ) symbolic ADT .
In particular , aims to first execute those states with a height closest to
-- the specified height.
adtHeightOrderer :: Int -> Maybe Name -> Orderer (HS.HashSet Name, Bool) Int t
adtHeightOrderer pref_height mn =
(mkSimpleOrderer initial
order
(\v _ _ -> v))
{ stepOrderer = step }
where
-- Normally, each state tracks the names of currently symbolic variables,
-- but here we want all variables that were ever symbolic.
To track this , we use a HashSet .
-- The tracked bool is to speed up adjusting this hashset- if it is set to false,
-- we do not update the hashset. If it is set to true,
-- after the next step the hashset will be updated, and the bool will be set
-- back to false.
-- This avoids repeated operations on the hashset after rules that we know
-- will not add symbolic variables.
initial s = (HS.fromList . map idName . E.symbolicIds . expr_env $ s, False)
order (v, _) _ s =
let
m = maximum $ (-1):(HS.toList $ HS.map (flip adtHeight s) v)
h = abs (pref_height - m)
in
h
step (v, _) _ _
(State { curr_expr = CurrExpr _ (SymGen _) }) = (v, True)
step(v, True) _ _ s =
(v `HS.union` (HS.fromList . map idName . E.symbolicIds . expr_env $ s), False)
step (v, _) _ _
(State { curr_expr = CurrExpr _ (Tick (NamedLoc n') (Var (Id vn _))) })
| Just n <- mn, n == n' =
(HS.insert vn v, False)
step v _ _ _ = v
adtHeight :: Name -> State t -> Int
adtHeight n s@(State { expr_env = eenv })
| Just (E.Sym _) <- v = 0
| Just (E.Conc e) <- v =
1 + adtHeight' e s
| otherwise = 0
where
v = E.lookupConcOrSym n eenv
adtHeight' :: Expr -> State t -> Int
adtHeight' e s =
let
_:es = unApp e
in
maximum $ 0:map (\e' -> case e' of
Var (Id n _) -> adtHeight n s
_ -> 0) es
| Orders by the combined size of ( previously ) symbolic ADT .
In particular , aims to first execute those states with a combined ADT size closest to
-- the specified zize.
adtSizeOrderer :: Int -> Maybe Name -> Orderer (HS.HashSet Name, Bool) Int t
adtSizeOrderer pref_height mn =
(mkSimpleOrderer initial
order
(\v _ _ -> v))
{ stepOrderer = step }
where
-- Normally, each state tracks the names of currently symbolic variables,
-- but here we want all variables that were ever symbolic.
To track this , we use a HashSet .
-- The tracked bool is to speed up adjusting this hashset- if it is set to false,
-- we do not update the hashset. If it is set to true,
-- after the next step the hashset will be updated, and the bool will be set
-- back to false.
-- This avoids repeated operations on the hashset after rules that we know
-- will not add symbolic variables.
initial s = (HS.fromList . map idName . E.symbolicIds . expr_env $ s, False)
order (v, _) _ s =
let
m = sum (HS.toList $ HS.map (flip adtSize s) v)
h = abs (pref_height - m)
in
h
step (v, _) _ _
(State { curr_expr = CurrExpr _ (SymGen _) }) = (v, True)
step (v, True) _ _ s =
(v `HS.union` (HS.fromList . map idName . E.symbolicIds . expr_env $ s), False)
step (v, _) _ _
(State { curr_expr = CurrExpr _ (Tick (NamedLoc n') (Var (Id vn _))) })
| Just n <- mn, n == n' = (HS.insert vn v, False)
step v _ _ _ = v
adtSize :: Name -> State t -> Int
adtSize n s@(State { expr_env = eenv })
| Just (E.Sym _) <- v = 0
| Just (E.Conc e) <- v =
1 + adtSize' e s
| otherwise = 0
where
v = E.lookupConcOrSym n eenv
adtSize' :: Expr -> State t -> Int
adtSize' e s =
let
_:es = unApp e
in
sum $ 0:map (\e' -> case e' of
Var (Id n _) -> adtSize n s
_ -> 0) es
| Orders by the number of Path Constraints
pcSizeOrderer :: Int -- ^ What size should we prioritize?
-> Orderer () Int t
pcSizeOrderer pref_height = mkSimpleOrderer (const ())
order
(\v _ _ -> v)
where
order _ _ s =
let
m = PC.number (path_conds s)
h = abs (pref_height - m)
in
h
data IncrAfterNTr sov = IncrAfterNTr { steps_since_change :: Int
, incr_by :: Int
, underlying :: sov }
| Wraps an existing , and increases it 's value by 1 , every time
-- it doesn't change after N steps
incrAfterN :: (Eq sov, Enum b) => Int -> Orderer sov b t -> Orderer (IncrAfterNTr sov) b t
incrAfterN n ord = (mkSimpleOrderer initial order update) { stepOrderer = step }
where
initial s =
IncrAfterNTr { steps_since_change = 0
, incr_by = 0
, underlying = initPerStateOrder ord s }
order sov pr s =
let
b = orderStates ord (underlying sov) pr s
in
succNTimes (incr_by sov) b
update sov pr s =
sov { underlying = updateSelected ord (underlying sov) pr s }
step sov pr xs s
| steps_since_change sov >= n =
sov' { incr_by = incr_by sov' + 1
, steps_since_change = 0 }
| under /= under' =
sov' { steps_since_change = 0 }
| otherwise =
sov' { steps_since_change = steps_since_change sov' + 1}
where
under = underlying sov
under' = stepOrderer ord under pr xs s
sov' = sov { underlying = under' }
succNTimes :: Enum b => Int -> b -> b
succNTimes x b
| x <= 0 = b
| otherwise = succNTimes (x - 1) (succ b)
| Wraps an existing orderer , and divides its value by 2 if true_assert is true
quotTrueAssert :: Integral b => Orderer sov b t -> Orderer sov b t
quotTrueAssert ord = (mkSimpleOrderer (initPerStateOrder ord)
order
(updateSelected ord))
{ stepOrderer = stepOrderer ord}
where
order sov pr s =
let
b = orderStates ord sov pr s
in
if true_assert s then b `quot` 2 else b
--------
--------
| Uses a passed , and to execute the reduce on the State , and generated States
runReducer :: (MonadIO m, Ord b) =>
Reducer m rv t
-> Halter m hv t
-> Orderer sov b t
-> State t
-> Bindings
-> m (Processed (State t), Bindings)
runReducer red hal ord s b = do
let pr = Processed {accepted = [], discarded = []}
let s' = ExState { state = s
, reducer_val = initReducer red s
, halter_val = initHalt hal s
, order_val = initPerStateOrder ord s }
(states, b') <- runReducer' red hal ord pr s' b M.empty
return (states, b')
runReducer' :: (MonadIO m, Ord b)
=> Reducer m rv t
-> Halter m hv t
-> Orderer sov b t
-> Processed (State t)
-> ExState rv hv sov t
-> Bindings
-> M.Map b [ExState rv hv sov t]
-> m (Processed (State t), Bindings)
runReducer' red hal ord pr rs@(ExState { state = s, reducer_val = r_val, halter_val = h_val, order_val = o_val }) b xs = do
hc <- stopRed hal h_val pr s
case () of
()
| hc == Accept ->
let
pr' = pr {accepted = state rs:accepted pr}
jrs = minState ord pr' xs
in
case jrs of
Just (rs', xs') -> do
onAccept red s r_val
switchState red hal ord pr' rs' b xs'
Nothing -> return (pr', b)
| hc == Discard ->
let
pr' = pr {discarded = state rs:discarded pr}
jrs = minState ord pr' xs
in
case jrs of
Just (rs', xs') ->
switchState red hal ord pr' rs' b xs'
Nothing -> return (pr', b)
| hc == Switch ->
let
k = orderStates ord (order_val rs') pr (state rs)
rs' = rs { order_val = updateSelected ord (order_val rs) pr (state rs) }
Just (rs'', xs') = minState ord pr (M.insertWith (++) k [rs'] xs)
in
switchState red hal ord pr rs'' b xs'
| otherwise -> do
(_, reduceds, b') <- redRules red r_val s b
let reduceds' = map (\(r, rv) -> (r {num_steps = num_steps r + 1}, rv)) reduceds
r_vals = if length reduceds' > 1
then updateWithAll red reduceds' ++ error "List returned by updateWithAll is too short."
else map snd reduceds
reduceds_h_vals = map (\(r, _) -> (r, h_val)) reduceds'
h_vals = if length reduceds' > 1
then updateHalterWithAll hal reduceds_h_vals ++ error "List returned by updateWithAll is too short."
else repeat h_val
new_states = map fst reduceds'
mod_info = map (\(s', r_val', h_val') ->
rs { state = s'
, reducer_val = r_val'
, halter_val = stepHalter hal h_val' pr new_states s'
, order_val = stepOrderer ord o_val pr new_states s'}) $ zip3 new_states r_vals h_vals
case mod_info of
(s_h:ss_tail) -> do
let
b_ss_tail =
L.map (\s' ->
let
n_b = orderStates ord (order_val s') pr (state s')
in
(n_b, s')) ss_tail
xs' = foldr (\(or_b, s') -> M.insertWith (++) or_b [s']) xs b_ss_tail
runReducer' red hal ord pr s_h b' xs'
[] -> runReducerList red hal ord pr xs b'
switchState :: (MonadIO m, Ord b)
=> Reducer m rv t
-> Halter m hv t
-> Orderer sov b t
-> Processed (State t)
-> ExState rv hv sov t
-> Bindings
-> M.Map b [ExState rv hv sov t]
-> m (Processed (State t), Bindings)
switchState red hal ord pr rs b xs
| not $ discardOnStart hal (halter_val rs') pr (state rs') =
runReducer' red hal ord pr rs' b xs
| otherwise =
runReducerListSwitching red hal ord (pr {discarded = state rs':discarded pr}) xs b
where
rs' = rs { halter_val = updatePerStateHalt hal (halter_val rs) pr (state rs) }
-- To be used when we we need to select a state without switching
runReducerList :: (MonadIO m, Ord b)
=> Reducer m rv t
-> Halter m hv t
-> Orderer sov b t
-> Processed (State t)
-> M.Map b [ExState rv hv sov t]
-> Bindings
-> m (Processed (State t), Bindings)
runReducerList red hal ord pr m binds =
case minState ord pr m of
Just (rs, m') ->
let
rs' = rs { halter_val = updatePerStateHalt hal (halter_val rs) pr (state rs) }
in
runReducer' red hal ord pr rs' binds m'
Nothing -> return (pr, binds)
-- To be used when we are possibly switching states
runReducerListSwitching :: (MonadIO m, Ord b)
=> Reducer m rv t
-> Halter m hv t
-> Orderer sov b t
-> Processed (State t)
-> M.Map b [ExState rv hv sov t]
-> Bindings
-> m (Processed (State t), Bindings)
runReducerListSwitching red hal ord pr m binds =
case minState ord pr m of
Just (x, m') -> switchState red hal ord pr x binds m'
Nothing -> return (pr, binds)
-- Uses the Orderer to determine which state to continue execution on.
Returns that State , and a list of the rest of the states
minState :: Ord b
=> Orderer sov b t
-> Processed (State t)
-> M.Map b [ExState rv hv sov t]
-> Maybe ((ExState rv hv sov t), M.Map b [ExState rv hv sov t])
minState ord pr m =
case getState m of
Just (k, x:[]) -> Just (x, M.delete k m)
Just (k, x:xs) -> Just (x, M.insert k xs m)
Just (k, []) -> minState ord pr $ M.delete k m
Nothing -> Nothing
| null |
https://raw.githubusercontent.com/BillHallahan/G2/cb302723b504c3d275d8503c3a8beae4ffc6f4b9/src/G2/Execution/Reducer.hs
|
haskell
|
# LANGUAGE GADTs #
# LANGUAGE RankNTypes #
Reducers
Orderers
| Used when applying execution rules
Allows tracking extra information to control halting of rule application,
and to reorder states
cases is used for logging states
| Keeps track of type a's that have either been accepted or dropped
| Used by Reducers to indicate their progress reducing.
| Used by members of the Halter typeclass to control whether to continue
^ Switch to evaluating a new state, and reject the current state
^ Switch to evaluating a new state, and accept the current state
^ Switch to evaluating a new state, but continue evaluating the current state later
The type parameter r is used to disambiguate between different producers.
The reducer value, rv, can be used to track special, per Reducer, information.
| Initialized the reducer value
| After a reducer returns multiple states,
Errors if the returned list is too short.
| Determines when to stop evaluating a state
The type parameter h is used to disambiguate between different producers.
To create a new Halter, define some new type, and use it as h.
| Initializes each state halter value
| Runs whenever we switch to evaluating a different state,
to update the halter value of that new state
| Runs when we start execution on a state, immediately after
before execution is about to (re-)begin.
Return True if execution should proceed, False to discard
| Determines whether to continue reduction on the current state
| Takes a state, and updates its halter record field
| After multiple states, are returned
Errors if the returned list is too short.
| Picks an order to evaluate the states, to allow prioritizing some over others
The type parameter or is used to disambiguate between different producers.
To create a new reducer, define some new type, and use it as or.
| Initializing the per state ordering value
| Assigns each state some value of an ordered type, and then proceeds with execution on the
state assigned the minimal value
| Run on the selected state, to update it's sov field
| Run on the state at each step, to update it's sov field
--------------------------------------------------
Combines reducers in various ways
because this could lead to undecidable instances
# INLINE (<~) #
# INLINE (<~?) #
# INLINE (<~|) #
# INLINE (.<~) #
# INLINE (.<~?) #
# INLINE (.<~|) #
[Higher-Order Model]
Substitutes all possible higher order functions for symbolic higher order functions.
We insert the substituted higher order function directly into the model, because, due
to the VAR-RED rule, the function name will (if the function is called) be lost during execution.
| A Reducer to producer logging output
| A Reducer to producer logging output
| A Reducer to producer limited logging output.
Output a state every n steps
Only begin outputting after passing a certain n
Only output before a certain n
Output states that have gone down or are going down the given path prefix
Don't re-output states that already exist
We use C to combine the halter values for HCombiner
We should never define any other instance of Halter with C, or export it
because this could lead to undecidable instances
| Allows executing multiple halters.
If the halters disagree, prioritizes the order:
# INLINE (<~>) #
| Allows execution to continue until the step counter hits 0, then discards the state
| Switch execution every n steps
matches a Tag in the Accepted State list,
| Counts the number of variable lookups are made, and switches the state
whenever we've hit a threshold
Orderer things
| Continue execution on the state that has been picked the least in the past.
| Floors and does bucket size
the specified height.
Normally, each state tracks the names of currently symbolic variables,
but here we want all variables that were ever symbolic.
The tracked bool is to speed up adjusting this hashset- if it is set to false,
we do not update the hashset. If it is set to true,
after the next step the hashset will be updated, and the bool will be set
back to false.
This avoids repeated operations on the hashset after rules that we know
will not add symbolic variables.
the specified zize.
Normally, each state tracks the names of currently symbolic variables,
but here we want all variables that were ever symbolic.
The tracked bool is to speed up adjusting this hashset- if it is set to false,
we do not update the hashset. If it is set to true,
after the next step the hashset will be updated, and the bool will be set
back to false.
This avoids repeated operations on the hashset after rules that we know
will not add symbolic variables.
^ What size should we prioritize?
it doesn't change after N steps
------
------
To be used when we we need to select a state without switching
To be used when we are possibly switching states
Uses the Orderer to determine which state to continue execution on.
|
# LANGUAGE DeriveGeneric #
# LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
# LANGUAGE FunctionalDependencies #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE UndecidableInstances #
module G2.Execution.Reducer ( Reducer (..)
, Halter (..)
, Orderer (..)
, Processed (..)
, mapProcessed
, ReducerRes (..)
, HaltC (..)
, SomeReducer (..)
, SomeHalter (..)
, SomeOrderer (..)
, InitReducer
, RedRules
, mkSimpleReducer
, stdRed
, nonRedPCRed
, nonRedPCRedConst
, taggerRed
, getLogger
, simpleLogger
, prettyLogger
, limLogger
, LimLogger (..)
, (<~)
, (<~?)
, (<~|)
, (.|.)
, (.<~)
, (.<~?)
, (.<~|)
Halters
, mkSimpleHalter
, swhnfHalter
, acceptIfViolatedHalter
, (<~>)
, zeroHalter
, discardIfAcceptedTagHalter
, maxOutputsHalter
, switchEveryNHalter
, varLookupLimitHalter
, stdTimerHalter
, timerHalter
, mkSimpleOrderer
, (<->)
, ordComb
, nextOrderer
, pickLeastUsedOrderer
, bucketSizeOrderer
, adtHeightOrderer
, adtSizeOrderer
, pcSizeOrderer
, incrAfterN
, quotTrueAssert
, runReducer ) where
import G2.Config
import qualified G2.Language.ExprEnv as E
import G2.Execution.Rules
import G2.Language
import qualified G2.Language.Monad as MD
import qualified G2.Language.PathConds as PC
import qualified G2.Language.Stack as Stck
import G2.Solver
import G2.Lib.Printers
import Control.Monad.IO.Class
import qualified Control.Monad.State as SM
import Data.Foldable
import qualified Data.HashSet as HS
import qualified Data.HashMap.Strict as HM
import qualified Data.Map as M
import Data.Maybe
import Data.Monoid ((<>))
import qualified Data.List as L
import Data.Tuple
import Data.Time.Clock
import System.Directory
see also , the Reducer , Halter ,
data ExState rv hv sov t = ExState { state :: State t
, reducer_val :: rv
, halter_val :: hv
, order_val :: sov
}
data Processed a = Processed { accepted :: [a]
, discarded :: [a] }
mapProcessed :: (a -> b) -> Processed a -> Processed b
mapProcessed f pr = Processed { accepted = map f (accepted pr)
, discarded = map f (discarded pr)}
data ReducerRes = NoProgress | InProgress | Finished deriving (Eq, Ord, Show, Read)
progPrioritizer :: ReducerRes -> ReducerRes -> ReducerRes
progPrioritizer InProgress _ = InProgress
progPrioritizer _ InProgress = InProgress
progPrioritizer Finished _ = Finished
progPrioritizer _ Finished = Finished
progPrioritizer _ _ = NoProgress
evaluating the current State , or switch to evaluating a new state .
^ Continue evaluating the current State
deriving (Eq, Ord, Show, Read)
type InitReducer rv t = State t -> rv
type RedRules m rv t = rv -> State t -> Bindings -> m (ReducerRes, [(State t, rv)], Bindings)
| A Reducer is used to describe a set of Reduction Rules .
Reduction Rules take a State , and output new states .
To create a new reducer , define some new type , and use it as r.
data Reducer m rv t = Reducer {
initReducer :: InitReducer rv t
| Takes a State , and performs the appropriate Reduction Rule
, redRules :: RedRules m rv t
gives an opportunity to update with all States and ,
output by all 's , visible
If only one state is returned by all reducers , updateWithAll does not run .
, updateWithAll :: [(State t, rv)] -> [rv]
, onAccept :: State t -> rv -> m ()
}
# INLINE mkSimpleReducer #
mkSimpleReducer :: Monad m => InitReducer rv t -> RedRules m rv t -> Reducer m rv t
mkSimpleReducer init_red red_rules =
Reducer {
initReducer = init_red
, redRules = red_rules
, updateWithAll = map snd
, onAccept = \_ _ -> return ()
}
type InitHalter hv t = State t -> hv
type UpdatePerStateHalt hv t = hv -> Processed (State t) -> State t -> hv
type StopRed m hv t = hv -> Processed (State t) -> State t -> m HaltC
type StepHalter hv t = hv -> Processed (State t) -> [State t] -> State t -> hv
data Halter m hv t = Halter {
initHalt :: InitHalter hv t
, updatePerStateHalt :: UpdatePerStateHalt hv t
` updatePerStateHalt ` . Allows a State to be discarded right
, discardOnStart :: hv -> Processed (State t) -> State t -> Bool
, stopRed :: StopRed m hv t
, stepHalter :: StepHalter hv t
gives an opportunity to update halters with all States and halter values visible .
If only one state is returned , updateHalterWithAll does not run .
, updateHalterWithAll :: [(State t, hv)] -> [hv]
}
# INLINE mkSimpleHalter #
mkSimpleHalter :: Monad m => InitHalter hv t -> UpdatePerStateHalt hv t -> StopRed m hv t -> StepHalter hv t -> Halter m hv t
mkSimpleHalter initial update stop step = Halter { initHalt = initial
, updatePerStateHalt = update
, discardOnStart = \_ _ _ -> False
, stopRed = stop
, stepHalter = step
, updateHalterWithAll = map snd }
# INLINE mkStoppingHalter #
mkStoppingHalter :: Monad m => StopRed m () t -> Halter m () t
mkStoppingHalter stop =
mkSimpleHalter
(const ())
(\_ _ _ -> ())
stop
(\_ _ _ _ -> ())
type InitOrderer sov t = State t -> sov
type OrderStates sov b t = sov -> Processed (State t) -> State t -> b
type UpdateSelected sov t = sov -> Processed (State t) -> State t -> sov
data Orderer sov b t = Orderer {
initPerStateOrder :: InitOrderer sov t
, orderStates :: OrderStates sov b t
, updateSelected :: UpdateSelected sov t
, stepOrderer :: sov -> Processed (State t) -> [State t] -> State t -> sov
}
mkSimpleOrderer :: InitOrderer sov t -> OrderStates sov b t -> UpdateSelected sov t -> Orderer sov b t
mkSimpleOrderer initial order update = Orderer { initPerStateOrder = initial
, orderStates = order
, updateSelected = update
, stepOrderer = \sov _ _ _ -> sov}
getState :: M.Map b [s] -> Maybe (b, [s])
getState = M.lookupMin
data SomeReducer m t where
SomeReducer :: forall m rv t . Reducer m rv t -> SomeReducer m t
data SomeHalter m t where
SomeHalter :: forall m hv t . Halter m hv t -> SomeHalter m t
data SomeOrderer t where
SomeOrderer :: forall sov b t . Ord b => Orderer sov b t -> SomeOrderer t
We use RC to combine the reducer values for RCombiner
We should never define any other instance of Reducer with RC , or export it
data RC a b = RC a b
(<~) :: Monad m => Reducer m rv1 t -> Reducer m rv2 t -> Reducer m (RC rv1 rv2) t
r1 <~ r2 =
Reducer { initReducer = \s -> RC (initReducer r1 s) (initReducer r2 s)
, redRules = \(RC rv1 rv2) s b -> do
(rr2, srv2, b') <- redRules r2 rv2 s b
(rr1, srv1, b'') <- redRulesToStates r1 rv1 srv2 b'
return (progPrioritizer rr1 rr2, srv1, b'')
, updateWithAll = updateWithAllPair (updateWithAll r1) (updateWithAll r2)
, onAccept = \s (RC rv1 rv2) -> do
onAccept r1 s rv1
onAccept r2 s rv2
}
(<~?) :: Monad m => Reducer m rv1 t -> Reducer m rv2 t -> Reducer m (RC rv1 rv2) t
r1 <~? r2 =
Reducer { initReducer = \s -> RC (initReducer r1 s) (initReducer r2 s)
, redRules = \(RC rv1 rv2) s b -> do
(rr2, srv2, b') <- redRules r2 rv2 s b
let (s', rv2') = unzip srv2
case rr2 of
NoProgress -> do
(rr1, ss, b'') <- redRulesToStates r1 rv1 srv2 b'
return (rr1, ss, b'')
_ -> return (rr2, zip s' (map (RC rv1) rv2'), b')
, updateWithAll = updateWithAllPair (updateWithAll r1) (updateWithAll r2)
, onAccept = \s (RC rv1 rv2) -> do
onAccept r1 s rv1
onAccept r2 s rv2
}
(<~|) :: Monad m => Reducer m rv1 t -> Reducer m rv2 t -> Reducer m (RC rv1 rv2) t
r1 <~| r2 =
Reducer { initReducer = \s -> RC (initReducer r1 s) (initReducer r2 s)
, redRules = \(RC rv1 rv2) s b -> do
(rr2, srv2, b') <- redRules r2 rv2 s b
let (s', rv2') = unzip srv2
case rr2 of
Finished -> do
(rr1, ss, b'') <- redRulesToStates r1 rv1 srv2 b'
return (rr1, ss, b'')
_ -> return (rr2, zip s' (map (RC rv1) rv2'), b')
, updateWithAll = updateWithAllPair (updateWithAll r1) (updateWithAll r2)
, onAccept = \s (RC rv1 rv2) -> do
onAccept r1 s rv1
onAccept r2 s rv2
}
# INLINE ( .| . ) #
(.|.) :: Monad m => Reducer m rv1 t -> Reducer m rv2 t -> Reducer m (RC rv1 rv2) t
r1 .|. r2 =
Reducer { initReducer = \s -> RC (initReducer r1 s) (initReducer r2 s)
, redRules = \(RC rv1 rv2) s b -> do
(rr2, srv2, b') <- redRules r2 rv2 s b
(rr1, srv1, b'') <- redRules r1 rv1 s b'
let srv2' = map (\(s_, rv2_) -> (s_, RC rv1 rv2_) ) srv2
srv1' = map (\(s_, rv1_) -> (s_, RC rv1_ rv2) ) srv1
return (progPrioritizer rr1 rr2, srv2' ++ srv1', b'')
, updateWithAll = updateWithAllPair (updateWithAll r1) (updateWithAll r2)
, onAccept = \s (RC rv1 rv2) -> do
onAccept r1 s rv1
onAccept r2 s rv2
}
(.<~) :: Monad m => SomeReducer m t -> SomeReducer m t -> SomeReducer m t
SomeReducer r1 .<~ SomeReducer r2 = SomeReducer (r1 <~ r2)
(.<~?) :: Monad m => SomeReducer m t -> SomeReducer m t -> SomeReducer m t
SomeReducer r1 .<~? SomeReducer r2 = SomeReducer (r1 <~? r2)
(.<~|) :: Monad m => SomeReducer m t -> SomeReducer m t -> SomeReducer m t
SomeReducer r1 .<~| SomeReducer r2 = SomeReducer (r1 <~| r2)
updateWithAllPair :: ([(State t, rv1)] -> [rv1]) -> ([(State t, rv2)] -> [rv2]) -> [(State t, RC rv1 rv2)] -> [RC rv1 rv2]
updateWithAllPair update1 update2 srv =
let
srv1 = map (\(s, RC rv1 _) -> (s, rv1)) srv
srv2 = map (\(s, RC _ rv2) -> (s, rv2)) srv
rv1' = update1 srv1
rv2' = update2 srv2
in
map (uncurry RC) $ zip rv1' rv2'
redRulesToStatesAux :: Monad m => Reducer m rv t -> rv -> Bindings -> (State t, rv2) -> m (Bindings, (ReducerRes, [(State t, RC rv rv2)]))
redRulesToStatesAux r rv1 b (is, rv2) = do
(rr_, is', b') <- redRules r rv1 is b
return (b', (rr_, map (\(is'', rv1') -> (is'', RC rv1' rv2) ) is'))
redRulesToStates :: Monad m => Reducer m rv t -> rv -> [(State t, rv2)] -> Bindings -> m (ReducerRes, [(State t, RC rv rv2)], Bindings)
redRulesToStates r rv1 s b = do
let redRulesToStatesAux' = redRulesToStatesAux r rv1
(b', rs) <- MD.mapMAccumB redRulesToStatesAux' b s
let (rr, s') = L.unzip rs
let rf = foldr progPrioritizer NoProgress rr
return $ (rf, concat s', b')
# INLINE stdRed #
stdRed :: (MonadIO m, Solver solver, Simplifier simplifier) => Sharing -> solver -> simplifier -> Reducer m () t
stdRed share solver simplifier =
mkSimpleReducer (\_ -> ())
(\_ s b -> do
(r, s', b') <- liftIO $ stdReduce share solver simplifier s b
return (if r == RuleIdentity then Finished else InProgress, s', b')
)
| Removes and reduces the values in a State 's non_red_path_conds field .
# INLINE nonRedPCRed #
nonRedPCRed :: Monad m => Reducer m () t
nonRedPCRed = mkSimpleReducer (\_ -> ())
nonRedPCRedFunc
nonRedPCRedFunc :: Monad m => RedRules m () t
nonRedPCRedFunc _
s@(State { expr_env = eenv
, curr_expr = cexpr
, exec_stack = stck
, non_red_path_conds = nr:nrs
, model = m })
b@(Bindings { higher_order_inst = inst }) = do
let stck' = Stck.push (CurrExprFrame AddPC cexpr) stck
let cexpr' = CurrExpr Evaluate nr
let eenv_si_ces = substHigherOrder eenv m inst cexpr'
let s' = s { exec_stack = stck'
, non_red_path_conds = nrs
}
xs = map (\(eenv', m', ce) -> (s' { expr_env = eenv'
, model = m'
, curr_expr = ce }, ())) eenv_si_ces
return (InProgress, xs, b)
nonRedPCRedFunc _ s b = return (Finished, [(s, ())], b)
substHigherOrder :: ExprEnv -> Model -> HS.HashSet Name -> CurrExpr -> [(ExprEnv, Model, CurrExpr)]
substHigherOrder eenv m ns ce =
let
is = mapMaybe (\n -> case E.lookup n eenv of
Just e -> Just $ Id n (typeOf e)
Nothing -> Nothing) $ HS.toList ns
higherOrd = filter (isTyFun . typeOf) . symbVars eenv $ ce
higherOrdSub = map (\v -> (v, mapMaybe (genSubstitutable v) is)) higherOrd
in
substHigherOrder' [(eenv, m, ce)] higherOrdSub
where
genSubstitutable v i
| Just bm <- specializes (typeOf v) (typeOf i) =
let
bnds = map idName $ leadingTyForAllBindings i
tys = mapMaybe (\b -> fmap Type $ M.lookup b bm) bnds
in
Just . mkApp $ Var i:tys
| otherwise = Nothing
substHigherOrder' :: [(ExprEnv, Model, CurrExpr)] -> [(Id, [Expr])] -> [(ExprEnv, Model, CurrExpr)]
substHigherOrder' eenvsice [] = eenvsice
substHigherOrder' eenvsice ((i, es):iss) =
substHigherOrder'
(concatMap (\e_rep ->
map (\(eenv, m, ce) -> ( E.insert (idName i) e_rep eenv
, HM.insert (idName i) e_rep m
, replaceASTs (Var i) e_rep ce)
) eenvsice)
es) iss
| Removes and reduces the values in a State 's non_red_path_conds field by instantiating higher order functions to be constant
nonRedPCRedConst :: Monad m => Reducer m () t
nonRedPCRedConst = mkSimpleReducer (\_ -> ())
nonRedPCRedConstFunc
nonRedPCRedConstFunc :: Monad m => RedRules m () t
nonRedPCRedConstFunc _
s@(State { expr_env = eenv
, curr_expr = cexpr
, exec_stack = stck
, non_red_path_conds = nr:nrs
, model = m })
b@(Bindings { name_gen = ng }) = do
let stck' = Stck.push (CurrExprFrame AddPC cexpr) stck
let cexpr' = CurrExpr Evaluate nr
let higher_ord = L.filter (isTyFun . typeOf) $ E.symbolicIds eenv
(ng', new_lam_is) = L.mapAccumL (\ng_ ts -> swap $ freshIds ts ng_) ng (map anonArgumentTypes higher_ord)
(new_sym_gen, ng'') = freshIds (map returnType higher_ord) ng'
es = map (\(f_id, lam_i, sg_i) -> (f_id, mkLams (zip (repeat TermL) lam_i) (Var sg_i)) )
$ zip3 higher_ord new_lam_is new_sym_gen
eenv' = foldr (uncurry E.insert) eenv (map (\(i, e) -> (idName i, e)) es)
eenv'' = foldr E.insertSymbolic eenv' new_sym_gen
m' = foldr (\(i, e) -> HM.insert (idName i) e) m es
let s' = s { expr_env = eenv''
, curr_expr = cexpr'
, model = m'
, exec_stack = stck'
, non_red_path_conds = nrs
}
return (InProgress, [(s', ())], b { name_gen = ng'' })
nonRedPCRedConstFunc _ s b = return (Finished, [(s, ())], b)
# INLINE taggerRed #
taggerRed :: Monad m => Name -> Reducer m () t
taggerRed n = mkSimpleReducer (const ()) (taggerRedStep n)
taggerRedStep :: Monad m => Name -> RedRules m () t
taggerRedStep n _ s@(State {tags = ts}) b@(Bindings { name_gen = ng }) =
let
(n'@(Name n_ m_ _ _), ng') = freshSeededName n ng
in
if null $ HS.filter (\(Name n__ m__ _ _) -> n_ == n__ && m_ == m__) ts then
return (Finished, [(s {tags = HS.insert n' ts}, ())], b { name_gen = ng' })
else
return (Finished, [(s, ())], b)
getLogger :: (MonadIO m, Show t) => Config -> Maybe (Reducer (SM.StateT PrettyGuide m) [Int] t)
getLogger config = case logStates config of
Log Raw fp -> Just (simpleLogger fp)
Log Pretty fp -> Just (prettyLogger fp)
NoLog -> Nothing
simpleLogger :: (MonadIO m, Show t) => FilePath -> Reducer m [Int] t
simpleLogger fn =
(mkSimpleReducer (const [])
(\li s b -> do
liftIO $ outputState fn li s b pprExecStateStr
return (NoProgress, [(s, li)], b) ))
{ updateWithAll = \s -> map (\(l, i) -> l ++ [i]) $ zip (map snd s) [1..] }
prettyLogger :: (MonadIO m, Show t) => FilePath -> Reducer (SM.StateT PrettyGuide m) [Int] t
prettyLogger fp =
(mkSimpleReducer
(const [])
(\li s b -> do
pg <- SM.get
let pg' = updatePrettyGuide (s { track = () }) pg
SM.put pg'
liftIO $ outputState fp li s b (\s_ _ -> prettyState pg' s_)
return (NoProgress, [(s, li)], b)
)
) { updateWithAll = \s -> map (\(l, i) -> l ++ [i]) $ zip (map snd s) [1..]
, onAccept = \_ ll -> liftIO . putStrLn $ "Accepted on path " ++ show ll }
data LimLogger =
, lim_output_path :: String
}
data LLTracker = LLTracker { ll_count :: Int, ll_offset :: [Int]}
limLogger :: (MonadIO m, Show t) => LimLogger -> Reducer m LLTracker t
limLogger ll@(LimLogger { after_n = aft, before_n = bfr, down_path = down }) =
(mkSimpleReducer (const $ LLTracker { ll_count = every_n ll, ll_offset = []}) rr)
{ updateWithAll = updateWithAllLL
, onAccept = \_ llt -> liftIO . putStrLn $ "Accepted on path " ++ show (ll_offset llt)}
where
rr llt@(LLTracker { ll_count = 0, ll_offset = off }) s b
| down `L.isPrefixOf` off || off `L.isPrefixOf` down
, aft <= length_rules && maybe True (length_rules <=) bfr = do
liftIO $ outputState (lim_output_path ll) off s b pprExecStateStr
return (NoProgress, [(s, llt { ll_count = every_n ll })], b)
| otherwise =
return (NoProgress, [(s, llt { ll_count = every_n ll })], b)
where
length_rules = length (rules s)
rr llt@(LLTracker {ll_count = n}) s b =
return (NoProgress, [(s, llt { ll_count = n - 1 })], b)
updateWithAllLL [(_, l)] = [l]
updateWithAllLL ss =
map (\(llt, i) -> llt { ll_offset = ll_offset llt ++ [i] }) $ zip (map snd ss) [1..]
outputState :: FilePath -> [Int] -> State t -> Bindings -> (State t -> Bindings -> String) -> IO ()
outputState dn is s b printer = do
fn <- getFile dn is "state" s
exists <- doesPathExist fn
if not exists
then do
let write = printer s b
writeFile fn write
putStrLn fn
else return ()
getFile :: String -> [Int] -> String -> State t -> IO String
getFile dn is n s = do
let dir = dn ++ "/" ++ foldl' (\str i -> str ++ show i ++ "/") "" is
createDirectoryIfMissing True dir
let fn = dir ++ n ++ show (length $ rules s) ++ ".txt"
return fn
data C a b = C a b deriving Eq
instance (ASTContainer a Expr, ASTContainer b Expr) => ASTContainer (C a b) Expr where
containedASTs (C a b) = containedASTs a ++ containedASTs b
modifyContainedASTs f (C a b) = C (modifyContainedASTs f a) (modifyContainedASTs f b)
instance (ASTContainer a Type, ASTContainer b Type) => ASTContainer (C a b) Type where
containedASTs (C a b) = containedASTs a ++ containedASTs b
modifyContainedASTs f (C a b) = C (modifyContainedASTs f a) (modifyContainedASTs f b)
instance (Named a, Named b) => Named (C a b) where
names (C a b) = names a <> names b
rename old new (C a b) = C (rename old new a) (rename old new b)
renames hm (C a b) = C (renames hm a) (renames hm b)
Discard , Accept , Switch , Continue
(<~>) :: Monad m => Halter m hv1 t -> Halter m hv2 t -> Halter m (C hv1 hv2) t
h1 <~> h2 =
Halter {
initHalt = \s ->
let
hv1 = initHalt h1 s
hv2 = initHalt h2 s
in
C hv1 hv2
, updatePerStateHalt = \(C hv1 hv2) proc s ->
let
hv1' = updatePerStateHalt h1 hv1 proc s
hv2' = updatePerStateHalt h2 hv2 proc s
in
C hv1' hv2'
, discardOnStart = \(C hv1 hv2) proc s ->
let
b1 = discardOnStart h1 hv1 proc s
b2 = discardOnStart h2 hv2 proc s
in
b1 || b2
, stopRed = \(C hv1 hv2) proc s -> do
hc1 <- stopRed h1 hv1 proc s
hc2 <- stopRed h2 hv2 proc s
return $ min hc1 hc2
, stepHalter = \(C hv1 hv2) proc xs s ->
let
hv1' = stepHalter h1 hv1 proc xs s
hv2' = stepHalter h2 hv2 proc xs s
in
C hv1' hv2'
, updateHalterWithAll = \shv ->
let
shv1 = map (\(s, C hv1 _) -> (s, hv1)) shv
shv2 = map (\(s, C _ hv2) -> (s, hv2)) shv
shv1' = updateHalterWithAll h1 shv1
shv2' = updateHalterWithAll h2 shv2
in
map (uncurry C) $ zip shv1' shv2'
}
# INLINE swhnfHalter #
swhnfHalter :: Monad m => Halter m () t
swhnfHalter = mkStoppingHalter stop
where
stop _ _ s =
case isExecValueForm s of
True -> return Accept
False -> return Continue
| Accepts a state when it is in SWHNF and is true
Discards it if in SWHNF and true_assert is false
acceptIfViolatedHalter :: Monad m => Halter m () t
acceptIfViolatedHalter = mkStoppingHalter stop
where
stop _ _ s =
case isExecValueForm s of
True
| true_assert s -> return Accept
| otherwise -> return Discard
False -> return Continue
zeroHalter :: Monad m => Int -> Halter m Int t
zeroHalter n = mkSimpleHalter
(const n)
(\h _ _ -> h)
(\h _ _ -> if h == 0 then return Discard else return Continue)
(\h _ _ _ -> h - 1)
maxOutputsHalter :: Monad m => Maybe Int -> Halter m (Maybe Int) t
maxOutputsHalter m = mkSimpleHalter
(const m)
(\hv _ _ -> hv)
(\_ (Processed {accepted = acc}) _ ->
case m of
Just m' -> return $ if length acc >= m' then Discard else Continue
_ -> return Continue)
(\hv _ _ _ -> hv)
# INLINE switchEveryNHalter #
switchEveryNHalter :: Monad m => Int -> Halter m Int t
switchEveryNHalter sw = (mkSimpleHalter
(const sw)
(\_ _ _ -> sw)
(\i _ _ -> return $ if i <= 0 then Switch else Continue)
(\i _ _ _ -> i - 1))
{ updateHalterWithAll = updateAll }
where
updateAll [] = []
updateAll xs@((_, c):_) =
let
len = length xs
c' = c `quot` len
in
replicate len c'
| If the Name , disregarding the Unique , in the DiscardIfAcceptedTag
and in the State being evaluated , discard the State
discardIfAcceptedTagHalter :: Monad m => Name -> Halter m (HS.HashSet Name) t
discardIfAcceptedTagHalter (Name n m _ _) =
mkSimpleHalter
(const HS.empty)
ups
(\ns _ _ -> return $ if not (HS.null ns) then Discard else Continue)
(\hv _ _ _ -> hv)
where
ups _
(Processed {accepted = acc})
(State {tags = ts}) =
let
allAccTags = HS.unions $ map tags acc
matchCurrState = HS.intersection ts allAccTags
in
HS.filter (\(Name n' m' _ _) -> n == n' && m == m') matchCurrState
varLookupLimitHalter :: Monad m => Int -> Halter m Int t
varLookupLimitHalter lim = mkSimpleHalter
(const lim)
(\_ _ _ -> lim)
(\l _ _ -> return $ if l <= 0 then Switch else Continue)
step
where
step l _ _ (State { curr_expr = CurrExpr Evaluate (Var _) }) = l - 1
step l _ _ _ = l
# INLINE stdTimerHalter #
stdTimerHalter :: (MonadIO m, MonadIO m_run) => NominalDiffTime -> m (Halter m_run Int t)
stdTimerHalter ms = timerHalter ms Discard 10
# INLINE timerHalter #
timerHalter :: (MonadIO m, MonadIO m_run) => NominalDiffTime -> HaltC -> Int -> m (Halter m_run Int t)
timerHalter ms def ce = do
curr <- liftIO $ getCurrentTime
return $ mkSimpleHalter
(const 0)
(\_ _ _ -> 0)
(stop curr)
step
where
stop it v (Processed { accepted = acc }) _
| v == 0
, not (null acc) = do
curr <- liftIO $ getCurrentTime
let diff = diffUTCTime curr it
if diff > ms
then return def
else return Continue
| otherwise = return Continue
step v _ _ _
| v >= ce = 0
| otherwise = v + 1
(<->) :: Orderer sov1 b1 t -> Orderer sov2 b2 t -> Orderer (C sov1 sov2) (b1, b2) t
or1 <-> or2 = Orderer {
initPerStateOrder = \s ->
let
sov1 = initPerStateOrder or1 s
sov2 = initPerStateOrder or2 s
in
C sov1 sov2
, orderStates = \(C sov1 sov2) pr s ->
let
sov1' = orderStates or1 sov1 pr s
sov2' = orderStates or2 sov2 pr s
in
(sov1', sov2')
, updateSelected = \(C sov1 sov2) proc s ->
let
sov1' = updateSelected or1 sov1 proc s
sov2' = updateSelected or2 sov2 proc s
in
C sov1' sov2'
, stepOrderer = \(C sov1 sov2) proc xs s ->
let
sov1' = stepOrderer or1 sov1 proc xs s
sov2' = stepOrderer or2 sov2 proc xs s
in
C sov1' sov2'
}
ordComb :: (v1 -> v2 -> v3) -> Orderer sov1 v1 t -> Orderer sov2 v2 t -> Orderer(C sov1 sov2) v3 t
ordComb f or1 or2 = Orderer {
initPerStateOrder = \s ->
let
sov1 = initPerStateOrder or1 s
sov2 = initPerStateOrder or2 s
in
C sov1 sov2
, orderStates = \(C sov1 sov2) pr s ->
let
sov1' = orderStates or1 sov1 pr s
sov2' = orderStates or2 sov2 pr s
in
f sov1' sov2'
, updateSelected = \(C sov1 sov2) proc s ->
let
sov1' = updateSelected or1 sov1 proc s
sov2' = updateSelected or2 sov2 proc s
in
C sov1' sov2'
, stepOrderer = \(C sov1 sov2) proc xs s ->
let
sov1' = stepOrderer or1 sov1 proc xs s
sov2' = stepOrderer or2 sov2 proc xs s
in
C sov1' sov2'
}
nextOrderer :: Orderer () Int t
nextOrderer = mkSimpleOrderer (const ()) (\_ _ _ -> 0) (\v _ _ -> v)
pickLeastUsedOrderer :: Orderer Int Int t
pickLeastUsedOrderer = mkSimpleOrderer (const 0) (\v _ _ -> v) (\v _ _ -> v + 1)
bucketSizeOrderer :: Int -> Orderer Int Int t
bucketSizeOrderer b =
mkSimpleOrderer (const 0)
(\v _ _ -> floor (fromIntegral v / fromIntegral b :: Float))
(\v _ _ -> v + 1)
| Orders by the size ( in terms of height ) of ( previously ) symbolic ADT .
In particular , aims to first execute those states with a height closest to
adtHeightOrderer :: Int -> Maybe Name -> Orderer (HS.HashSet Name, Bool) Int t
adtHeightOrderer pref_height mn =
(mkSimpleOrderer initial
order
(\v _ _ -> v))
{ stepOrderer = step }
where
To track this , we use a HashSet .
initial s = (HS.fromList . map idName . E.symbolicIds . expr_env $ s, False)
order (v, _) _ s =
let
m = maximum $ (-1):(HS.toList $ HS.map (flip adtHeight s) v)
h = abs (pref_height - m)
in
h
step (v, _) _ _
(State { curr_expr = CurrExpr _ (SymGen _) }) = (v, True)
step(v, True) _ _ s =
(v `HS.union` (HS.fromList . map idName . E.symbolicIds . expr_env $ s), False)
step (v, _) _ _
(State { curr_expr = CurrExpr _ (Tick (NamedLoc n') (Var (Id vn _))) })
| Just n <- mn, n == n' =
(HS.insert vn v, False)
step v _ _ _ = v
adtHeight :: Name -> State t -> Int
adtHeight n s@(State { expr_env = eenv })
| Just (E.Sym _) <- v = 0
| Just (E.Conc e) <- v =
1 + adtHeight' e s
| otherwise = 0
where
v = E.lookupConcOrSym n eenv
adtHeight' :: Expr -> State t -> Int
adtHeight' e s =
let
_:es = unApp e
in
maximum $ 0:map (\e' -> case e' of
Var (Id n _) -> adtHeight n s
_ -> 0) es
| Orders by the combined size of ( previously ) symbolic ADT .
In particular , aims to first execute those states with a combined ADT size closest to
adtSizeOrderer :: Int -> Maybe Name -> Orderer (HS.HashSet Name, Bool) Int t
adtSizeOrderer pref_height mn =
(mkSimpleOrderer initial
order
(\v _ _ -> v))
{ stepOrderer = step }
where
To track this , we use a HashSet .
initial s = (HS.fromList . map idName . E.symbolicIds . expr_env $ s, False)
order (v, _) _ s =
let
m = sum (HS.toList $ HS.map (flip adtSize s) v)
h = abs (pref_height - m)
in
h
step (v, _) _ _
(State { curr_expr = CurrExpr _ (SymGen _) }) = (v, True)
step (v, True) _ _ s =
(v `HS.union` (HS.fromList . map idName . E.symbolicIds . expr_env $ s), False)
step (v, _) _ _
(State { curr_expr = CurrExpr _ (Tick (NamedLoc n') (Var (Id vn _))) })
| Just n <- mn, n == n' = (HS.insert vn v, False)
step v _ _ _ = v
adtSize :: Name -> State t -> Int
adtSize n s@(State { expr_env = eenv })
| Just (E.Sym _) <- v = 0
| Just (E.Conc e) <- v =
1 + adtSize' e s
| otherwise = 0
where
v = E.lookupConcOrSym n eenv
adtSize' :: Expr -> State t -> Int
adtSize' e s =
let
_:es = unApp e
in
sum $ 0:map (\e' -> case e' of
Var (Id n _) -> adtSize n s
_ -> 0) es
| Orders by the number of Path Constraints
-> Orderer () Int t
pcSizeOrderer pref_height = mkSimpleOrderer (const ())
order
(\v _ _ -> v)
where
order _ _ s =
let
m = PC.number (path_conds s)
h = abs (pref_height - m)
in
h
data IncrAfterNTr sov = IncrAfterNTr { steps_since_change :: Int
, incr_by :: Int
, underlying :: sov }
| Wraps an existing , and increases it 's value by 1 , every time
incrAfterN :: (Eq sov, Enum b) => Int -> Orderer sov b t -> Orderer (IncrAfterNTr sov) b t
incrAfterN n ord = (mkSimpleOrderer initial order update) { stepOrderer = step }
where
initial s =
IncrAfterNTr { steps_since_change = 0
, incr_by = 0
, underlying = initPerStateOrder ord s }
order sov pr s =
let
b = orderStates ord (underlying sov) pr s
in
succNTimes (incr_by sov) b
update sov pr s =
sov { underlying = updateSelected ord (underlying sov) pr s }
step sov pr xs s
| steps_since_change sov >= n =
sov' { incr_by = incr_by sov' + 1
, steps_since_change = 0 }
| under /= under' =
sov' { steps_since_change = 0 }
| otherwise =
sov' { steps_since_change = steps_since_change sov' + 1}
where
under = underlying sov
under' = stepOrderer ord under pr xs s
sov' = sov { underlying = under' }
succNTimes :: Enum b => Int -> b -> b
succNTimes x b
| x <= 0 = b
| otherwise = succNTimes (x - 1) (succ b)
| Wraps an existing orderer , and divides its value by 2 if true_assert is true
quotTrueAssert :: Integral b => Orderer sov b t -> Orderer sov b t
quotTrueAssert ord = (mkSimpleOrderer (initPerStateOrder ord)
order
(updateSelected ord))
{ stepOrderer = stepOrderer ord}
where
order sov pr s =
let
b = orderStates ord sov pr s
in
if true_assert s then b `quot` 2 else b
| Uses a passed , and to execute the reduce on the State , and generated States
runReducer :: (MonadIO m, Ord b) =>
Reducer m rv t
-> Halter m hv t
-> Orderer sov b t
-> State t
-> Bindings
-> m (Processed (State t), Bindings)
runReducer red hal ord s b = do
let pr = Processed {accepted = [], discarded = []}
let s' = ExState { state = s
, reducer_val = initReducer red s
, halter_val = initHalt hal s
, order_val = initPerStateOrder ord s }
(states, b') <- runReducer' red hal ord pr s' b M.empty
return (states, b')
runReducer' :: (MonadIO m, Ord b)
=> Reducer m rv t
-> Halter m hv t
-> Orderer sov b t
-> Processed (State t)
-> ExState rv hv sov t
-> Bindings
-> M.Map b [ExState rv hv sov t]
-> m (Processed (State t), Bindings)
runReducer' red hal ord pr rs@(ExState { state = s, reducer_val = r_val, halter_val = h_val, order_val = o_val }) b xs = do
hc <- stopRed hal h_val pr s
case () of
()
| hc == Accept ->
let
pr' = pr {accepted = state rs:accepted pr}
jrs = minState ord pr' xs
in
case jrs of
Just (rs', xs') -> do
onAccept red s r_val
switchState red hal ord pr' rs' b xs'
Nothing -> return (pr', b)
| hc == Discard ->
let
pr' = pr {discarded = state rs:discarded pr}
jrs = minState ord pr' xs
in
case jrs of
Just (rs', xs') ->
switchState red hal ord pr' rs' b xs'
Nothing -> return (pr', b)
| hc == Switch ->
let
k = orderStates ord (order_val rs') pr (state rs)
rs' = rs { order_val = updateSelected ord (order_val rs) pr (state rs) }
Just (rs'', xs') = minState ord pr (M.insertWith (++) k [rs'] xs)
in
switchState red hal ord pr rs'' b xs'
| otherwise -> do
(_, reduceds, b') <- redRules red r_val s b
let reduceds' = map (\(r, rv) -> (r {num_steps = num_steps r + 1}, rv)) reduceds
r_vals = if length reduceds' > 1
then updateWithAll red reduceds' ++ error "List returned by updateWithAll is too short."
else map snd reduceds
reduceds_h_vals = map (\(r, _) -> (r, h_val)) reduceds'
h_vals = if length reduceds' > 1
then updateHalterWithAll hal reduceds_h_vals ++ error "List returned by updateWithAll is too short."
else repeat h_val
new_states = map fst reduceds'
mod_info = map (\(s', r_val', h_val') ->
rs { state = s'
, reducer_val = r_val'
, halter_val = stepHalter hal h_val' pr new_states s'
, order_val = stepOrderer ord o_val pr new_states s'}) $ zip3 new_states r_vals h_vals
case mod_info of
(s_h:ss_tail) -> do
let
b_ss_tail =
L.map (\s' ->
let
n_b = orderStates ord (order_val s') pr (state s')
in
(n_b, s')) ss_tail
xs' = foldr (\(or_b, s') -> M.insertWith (++) or_b [s']) xs b_ss_tail
runReducer' red hal ord pr s_h b' xs'
[] -> runReducerList red hal ord pr xs b'
switchState :: (MonadIO m, Ord b)
=> Reducer m rv t
-> Halter m hv t
-> Orderer sov b t
-> Processed (State t)
-> ExState rv hv sov t
-> Bindings
-> M.Map b [ExState rv hv sov t]
-> m (Processed (State t), Bindings)
switchState red hal ord pr rs b xs
| not $ discardOnStart hal (halter_val rs') pr (state rs') =
runReducer' red hal ord pr rs' b xs
| otherwise =
runReducerListSwitching red hal ord (pr {discarded = state rs':discarded pr}) xs b
where
rs' = rs { halter_val = updatePerStateHalt hal (halter_val rs) pr (state rs) }
runReducerList :: (MonadIO m, Ord b)
=> Reducer m rv t
-> Halter m hv t
-> Orderer sov b t
-> Processed (State t)
-> M.Map b [ExState rv hv sov t]
-> Bindings
-> m (Processed (State t), Bindings)
runReducerList red hal ord pr m binds =
case minState ord pr m of
Just (rs, m') ->
let
rs' = rs { halter_val = updatePerStateHalt hal (halter_val rs) pr (state rs) }
in
runReducer' red hal ord pr rs' binds m'
Nothing -> return (pr, binds)
runReducerListSwitching :: (MonadIO m, Ord b)
=> Reducer m rv t
-> Halter m hv t
-> Orderer sov b t
-> Processed (State t)
-> M.Map b [ExState rv hv sov t]
-> Bindings
-> m (Processed (State t), Bindings)
runReducerListSwitching red hal ord pr m binds =
case minState ord pr m of
Just (x, m') -> switchState red hal ord pr x binds m'
Nothing -> return (pr, binds)
Returns that State , and a list of the rest of the states
minState :: Ord b
=> Orderer sov b t
-> Processed (State t)
-> M.Map b [ExState rv hv sov t]
-> Maybe ((ExState rv hv sov t), M.Map b [ExState rv hv sov t])
minState ord pr m =
case getState m of
Just (k, x:[]) -> Just (x, M.delete k m)
Just (k, x:xs) -> Just (x, M.insert k xs m)
Just (k, []) -> minState ord pr $ M.delete k m
Nothing -> Nothing
|
9a5ac5bcc7dbb901d0908722411fd0d04f3bffdac4d1bb4da7613977ea26c19e
|
input-output-hk/cardano-ledger
|
EraMapping.hs
|
# LANGUAGE DataKinds #
# LANGUAGE TypeFamilies #
module Test.Cardano.Ledger.Alonzo.EraMapping where
import Cardano.Ledger.Alonzo (AlonzoEra)
import Cardano.Ledger.Core (EraRule)
import Cardano.Protocol.TPraos.Rules.Tickn (TICKN)
import Test.Cardano.Ledger.EraBuffet (TestCrypto)
type instance EraRule "TICKN" (AlonzoEra TestCrypto) = TICKN
| null |
https://raw.githubusercontent.com/input-output-hk/cardano-ledger/e02891020a990f5700797493b30aaa3c6d8330ee/eras/alonzo/test-suite/src/Test/Cardano/Ledger/Alonzo/EraMapping.hs
|
haskell
|
# LANGUAGE DataKinds #
# LANGUAGE TypeFamilies #
module Test.Cardano.Ledger.Alonzo.EraMapping where
import Cardano.Ledger.Alonzo (AlonzoEra)
import Cardano.Ledger.Core (EraRule)
import Cardano.Protocol.TPraos.Rules.Tickn (TICKN)
import Test.Cardano.Ledger.EraBuffet (TestCrypto)
type instance EraRule "TICKN" (AlonzoEra TestCrypto) = TICKN
|
|
b511d6f757d1a41403e21044bcdf2cc4db34df45e4f201299e124f374ab4953d
|
xldenis/MGC
|
PrimSpec.hs
|
module MGC.Parser.PrimSpec (spec) where
import MGC.Expectation
import Test.Hspec
import MGC.Parser.Prim
import Text.Parsec
import MGC.Syntax
import Control.Applicative ((<*))
spec :: Spec
spec = do
describe "literal" $ do
describe "int" $ do
it "parses octal 0" $ do
intLit `parses` "00" ~> (Integer 0)
it "parses octal 17" $ do
intLit `parses` "021" ~> (Integer 17)
it "parses hex 0x0" $ do
intLit `parses` "0x0" ~> (Integer 0)
it "parses hex 0X0" $ do
intLit `parses` "0X0" ~> (Integer 0)
it "parses hex 0X15" $ do
intLit `parses` "0X15" ~> (Integer 21)
it "parses decimal 0" $ do
intLit `parses` "0" ~> (Integer 0)
it "eats whitespace" $ do
(intLit <* eof) `parses` "0 " ~> (Integer 0)
describe "string" $ do
it "parses interpreted strings" $ do
pending
it "parses literal strings" $ do
stringLit `parses` "`test`" ~> (RawString "test")
it "parses unicode literals" $ do
stringLit `parses` "\"\\u0000\"" ~> (IntString "\\u0000")
it "parses escape sequences" $ do
stringLit `parses` "\" \\n \\r \\t \\a \\' \\\" \"" ~> (IntString " \\n \\r \\t \\a \\' \\\" ")
describe "runes" $ do
it "recognizes normal chars" $ do
runeLit `parses` "'a'" ~> (Rune "a")
it "recognizes octal bytes" $ do
runeLit `parses` "'\\000'" ~> (Rune "\\000")
it "recognizes hex bytes" $ do
runeLit `parses` "'\\x00'" ~> (Rune "\\x00")
describe "identifier" $ do
it "recognizes strings" $ do
identifier `parses` "akadjfkadjfkl" ~> ("akadjfkadjfkl")
it "accepts _ as a leading char" $ do
identifier `parses` "_test" ~> ("_test")
it "doesnt allow reserved words" $ do
identifier `wontParse` "var"
| null |
https://raw.githubusercontent.com/xldenis/MGC/caeb2d72d16fbbefeb5104d7133c537fea66ba21/test/MGC/Parser/PrimSpec.hs
|
haskell
|
module MGC.Parser.PrimSpec (spec) where
import MGC.Expectation
import Test.Hspec
import MGC.Parser.Prim
import Text.Parsec
import MGC.Syntax
import Control.Applicative ((<*))
spec :: Spec
spec = do
describe "literal" $ do
describe "int" $ do
it "parses octal 0" $ do
intLit `parses` "00" ~> (Integer 0)
it "parses octal 17" $ do
intLit `parses` "021" ~> (Integer 17)
it "parses hex 0x0" $ do
intLit `parses` "0x0" ~> (Integer 0)
it "parses hex 0X0" $ do
intLit `parses` "0X0" ~> (Integer 0)
it "parses hex 0X15" $ do
intLit `parses` "0X15" ~> (Integer 21)
it "parses decimal 0" $ do
intLit `parses` "0" ~> (Integer 0)
it "eats whitespace" $ do
(intLit <* eof) `parses` "0 " ~> (Integer 0)
describe "string" $ do
it "parses interpreted strings" $ do
pending
it "parses literal strings" $ do
stringLit `parses` "`test`" ~> (RawString "test")
it "parses unicode literals" $ do
stringLit `parses` "\"\\u0000\"" ~> (IntString "\\u0000")
it "parses escape sequences" $ do
stringLit `parses` "\" \\n \\r \\t \\a \\' \\\" \"" ~> (IntString " \\n \\r \\t \\a \\' \\\" ")
describe "runes" $ do
it "recognizes normal chars" $ do
runeLit `parses` "'a'" ~> (Rune "a")
it "recognizes octal bytes" $ do
runeLit `parses` "'\\000'" ~> (Rune "\\000")
it "recognizes hex bytes" $ do
runeLit `parses` "'\\x00'" ~> (Rune "\\x00")
describe "identifier" $ do
it "recognizes strings" $ do
identifier `parses` "akadjfkadjfkl" ~> ("akadjfkadjfkl")
it "accepts _ as a leading char" $ do
identifier `parses` "_test" ~> ("_test")
it "doesnt allow reserved words" $ do
identifier `wontParse` "var"
|
|
12d20614dfd83ef9586309b89b10413bed5c3b1adccd6e0a3a8db3205e13bedf
|
fbellomi/crossclj
|
gzip.clj
|
(ns crossclj.gzip
"Ring gzip compression."
(:require [clojure.java.io :as io])
(:import (java.io InputStream
Closeable
File
ByteArrayOutputStream)
(java.util.zip GZIPOutputStream)))
(defn- accepts-gzip?
[req]
(if-let [accepts (get-in req [:headers "accept-encoding"])]
;; Be aggressive in supporting clients with mangled headers (due to
proxies , av software , buggy browsers , etc ... )
(re-seq
#"(gzip\s*,?\s*(gzip|deflate)?|X{4,13}|~{4,13}|\-{4,13})"
accepts)))
;; Set Vary to make sure proxies don't deliver the wrong content.
(defn- set-response-headers
[headers]
(if-let [vary (get headers "vary")]
(-> headers
(assoc "Vary" (str vary ", Accept-Encoding"))
(assoc "Content-Encoding" "gzip")
(dissoc "Content-Length")
(dissoc "vary"))
(-> headers
(assoc "Vary" "Accept-Encoding")
(assoc "Content-Encoding" "gzip")
(dissoc "Content-Length"))))
(def ^:private supported-status? #{200, 201, 202, 203, 204, 205 403, 404})
(defn- unencoded-type?
[headers]
(if (headers "content-encoding")
false
true))
(defn- supported-type?
[resp]
(let [{:keys [body]} resp]
(or (string? body)
(seq? body)
(instance? InputStream body)
(and (instance? File body)
(re-seq #"(?i)\.(htm|html|css|js|json|xml)" (pr-str body))))))
(def ^:private min-length 859)
(defn- supported-size?
[resp]
(let [{body :body} resp]
(cond
(string? body) (> (count body) min-length)
(seq? body) (> (count body) min-length)
(instance? File body) (> (.length body) min-length)
:else true)))
(defn- supported-response?
[resp]
(let [{:keys [status headers]} resp]
(and (supported-status? status)
(unencoded-type? headers)
(supported-type? resp)
(supported-size? resp))))
(defn- compress-body [body]
(let [bas (ByteArrayOutputStream.)]
(with-open [out (GZIPOutputStream. bas)]
(if (seq? body)
(doseq [string body] (io/copy (str string) out))
(io/copy body out)))
(when (instance? Closeable body)
(.close body))
(.close bas)
(.toByteArray bas)))
(defn- gzip-response
[resp]
(-> resp
(update-in [:headers] set-response-headers)
(update-in [:body] compress-body)))
(defn test-gzip [handler]
(fn [request]
(handler (if (accepts-gzip? request)
(assoc request :gzip true)
request))))
(defn wrap-gzip
"Middleware that compresses responses with gzip for supported user-agents."
[handler]
(fn [req]
(if (:gzip req)
(let [resp (handler req)]
(if (supported-response? resp)
(gzip-response resp)
resp))
(handler req))))
| null |
https://raw.githubusercontent.com/fbellomi/crossclj/7630270ebe9ea3df89fe3d877b2571e6eae1062b/src/crossclj/gzip.clj
|
clojure
|
Be aggressive in supporting clients with mangled headers (due to
Set Vary to make sure proxies don't deliver the wrong content.
|
(ns crossclj.gzip
"Ring gzip compression."
(:require [clojure.java.io :as io])
(:import (java.io InputStream
Closeable
File
ByteArrayOutputStream)
(java.util.zip GZIPOutputStream)))
(defn- accepts-gzip?
[req]
(if-let [accepts (get-in req [:headers "accept-encoding"])]
proxies , av software , buggy browsers , etc ... )
(re-seq
#"(gzip\s*,?\s*(gzip|deflate)?|X{4,13}|~{4,13}|\-{4,13})"
accepts)))
(defn- set-response-headers
[headers]
(if-let [vary (get headers "vary")]
(-> headers
(assoc "Vary" (str vary ", Accept-Encoding"))
(assoc "Content-Encoding" "gzip")
(dissoc "Content-Length")
(dissoc "vary"))
(-> headers
(assoc "Vary" "Accept-Encoding")
(assoc "Content-Encoding" "gzip")
(dissoc "Content-Length"))))
(def ^:private supported-status? #{200, 201, 202, 203, 204, 205 403, 404})
(defn- unencoded-type?
[headers]
(if (headers "content-encoding")
false
true))
(defn- supported-type?
[resp]
(let [{:keys [body]} resp]
(or (string? body)
(seq? body)
(instance? InputStream body)
(and (instance? File body)
(re-seq #"(?i)\.(htm|html|css|js|json|xml)" (pr-str body))))))
(def ^:private min-length 859)
(defn- supported-size?
[resp]
(let [{body :body} resp]
(cond
(string? body) (> (count body) min-length)
(seq? body) (> (count body) min-length)
(instance? File body) (> (.length body) min-length)
:else true)))
(defn- supported-response?
[resp]
(let [{:keys [status headers]} resp]
(and (supported-status? status)
(unencoded-type? headers)
(supported-type? resp)
(supported-size? resp))))
(defn- compress-body [body]
(let [bas (ByteArrayOutputStream.)]
(with-open [out (GZIPOutputStream. bas)]
(if (seq? body)
(doseq [string body] (io/copy (str string) out))
(io/copy body out)))
(when (instance? Closeable body)
(.close body))
(.close bas)
(.toByteArray bas)))
(defn- gzip-response
[resp]
(-> resp
(update-in [:headers] set-response-headers)
(update-in [:body] compress-body)))
(defn test-gzip [handler]
(fn [request]
(handler (if (accepts-gzip? request)
(assoc request :gzip true)
request))))
(defn wrap-gzip
"Middleware that compresses responses with gzip for supported user-agents."
[handler]
(fn [req]
(if (:gzip req)
(let [resp (handler req)]
(if (supported-response? resp)
(gzip-response resp)
resp))
(handler req))))
|
98bf05fde1a3810f8ec0ddac57bf4211be8a143d7b7c88314bc0bd01cdad6cd4
|
Hans-Halverson/myte
|
io.ml
|
let chan_read_contents chan =
let rec read_line lines =
try
let line = input_line chan in
line :: read_line lines
with
| End_of_file -> List.rev lines
in
let lines = read_line [] in
let contents = String.concat "\n" lines in
contents
let file_read_lines file =
let file_in = open_in file in
let rec read_lines lines =
try
let line = input_line file_in in
line :: read_lines lines
with
| End_of_file -> List.rev lines
in
read_lines []
let file_read_lines_between file start _end =
let file_in = open_in file in
let rec read_lines i lines =
try
let line = input_line file_in in
if start <= i && i <= _end then
line :: read_lines (i + 1) lines
else
read_lines (i + 1) lines
with
| End_of_file -> List.rev lines
in
read_lines 1 []
| null |
https://raw.githubusercontent.com/Hans-Halverson/myte/04c91ff8b0d44e7f65acaf6c223401741a4c0143/src/common/io.ml
|
ocaml
|
let chan_read_contents chan =
let rec read_line lines =
try
let line = input_line chan in
line :: read_line lines
with
| End_of_file -> List.rev lines
in
let lines = read_line [] in
let contents = String.concat "\n" lines in
contents
let file_read_lines file =
let file_in = open_in file in
let rec read_lines lines =
try
let line = input_line file_in in
line :: read_lines lines
with
| End_of_file -> List.rev lines
in
read_lines []
let file_read_lines_between file start _end =
let file_in = open_in file in
let rec read_lines i lines =
try
let line = input_line file_in in
if start <= i && i <= _end then
line :: read_lines (i + 1) lines
else
read_lines (i + 1) lines
with
| End_of_file -> List.rev lines
in
read_lines 1 []
|
|
f16cec2df14d515f05e6df0dd5112dc2a03f5c12dd02704829249d72b5db369d
|
clj-commons/aleph
|
client_middleware_test.clj
|
(ns aleph.http.client-middleware-test
(:require
[aleph.http.client-middleware :as middleware]
[clojure.test :as t :refer [deftest is]])
(:import
(java.net URLDecoder)))
(deftest test-empty-query-string
(is (= "" (middleware/generate-query-string {})))
(is (= "" (middleware/generate-query-string {} "text/plain; charset=utf-8")))
(is (= "" (middleware/generate-query-string {} "text/html;charset=ISO-8859-1"))))
(deftest test-basic-auth-value-encoding
;; see #page-5
(is (= "Basic Og==" (middleware/basic-auth-value nil)))
(is (= "Basic Og==" (middleware/basic-auth-value [])))
(is (= "Basic " (middleware/basic-auth-value "")))
(is (= "Basic dXNlcm5hbWU6cGFzc3dvcmQ=" (middleware/basic-auth-value "username:password")))
(is (= "Basic dXNlcm5hbWU6cGFzc3dvcmQ=" (middleware/basic-auth-value ["username" "password"])))
(is (= "Basic dXNlcm5hbWU6" (middleware/basic-auth-value ["username"])))
(is (= "Basic dXNlcm5hbWU=" (middleware/basic-auth-value "username"))))
(deftest test-coerce-form-params
(is (= "{\"foo\":\"bar\"}" (middleware/coerce-form-params {:content-type :json
:form-params {:foo :bar}})))
(is (= "[\"^ \",\"~:foo\",\"~:bar\"]"
(slurp (middleware/coerce-form-params {:content-type :transit+json
:form-params {:foo :bar}}))))
(is (= "{:foo :bar}" (middleware/coerce-form-params {:content-type :edn
:form-params {:foo :bar}})))
(is (= "foo=%3Abar" (middleware/coerce-form-params {:content-type :default
:form-params {:foo :bar}})))
(is (= "foo=%3Abar&foo=%3Abaz"
(middleware/coerce-form-params {:content-type :default
:form-params {:foo [:bar :baz]}})))
(is (= "foo[]=%3Abar&foo[]=%3Abaz"
(middleware/coerce-form-params {:content-type :default
:multi-param-style :array
:form-params {:foo [:bar :baz]}})))
(is (= "foo[0]=%3Abar&foo[1]=%3Abaz"
(middleware/coerce-form-params {:content-type :default
:multi-param-style :indexed
:form-params {:foo [:bar :baz]}})))
(is (= (middleware/coerce-form-params {:content-type :default
:form-params {:foo :bar}})
(middleware/coerce-form-params {:form-params {:foo :bar}}))))
(deftest test-nested-query-params
(let [req {:query-params {:foo {:bar "baz"}}}
{:keys [query-string]} (reduce #(%2 %1) req middleware/default-middleware)]
(is (= "foo[bar]=baz" (URLDecoder/decode query-string)))))
(deftest test-cookie-store
(let [c1 {:name "id"
:value "42"
:domain "domain.com"
:path "/"
:max-age nil
:http-only? true
:secure? false}
c2 {:name "track"
:value "off"
:domain "domain.com"
:path "/"
:max-age nil
:http-only? true
:secure? true}
c3 {:name "track"
:value "on"
:domain "domain.com"
:path "/blog"
:max-age nil
:http-only? true
:secure? true}
c4 {:name "subdomain"
:value "detect"
:domain "subdomain.com"}
c5 (middleware/decode-set-cookie-header "outdated=val; Domain=outdomain.com; Expires=Wed, 21 Oct 2015 07:28:00 GMT")
cs (middleware/in-memory-cookie-store [c1 c2 c3 c4 c5])
spec middleware/default-cookie-spec
dc (middleware/decode-set-cookie-header "id=42; Domain=domain.com; Path=/; HttpOnly")]
(is (= c1 dc))
(is (= "id=42; track=off" (-> (middleware/add-cookie-header cs spec {:url "/"})
(get-in [:headers "cookie"])))
"emit cookie for /blog path")
(is (= "id=42" (-> (middleware/add-cookie-header cs spec {:url "/"})
(get-in [:headers "cookie"])))
"http request should not set secure cookies")
(is (= "id=42; track=on" (-> (middleware/add-cookie-header cs spec {:url ""})
(get-in [:headers "cookie"])))
"the most specific path")
(is (= "subdomain=detect" (-> (middleware/add-cookie-header cs spec {:url ""})
(get-in [:headers "cookie"])))
"subdomain should match w/o leading dot under latest specifications")
(is (nil? (-> (middleware/add-cookie-header cs spec {:url "/"})
(get-in [:headers "cookie"])))
"domain mistmatch")
(is (nil? (-> (middleware/add-cookie-header cs spec {:url "/"})
(get-in [:headers "cookie"])))
"should not set expired")
(is (= "no_override"
(-> (middleware/wrap-cookies {:cookie-store cs
:cookie-spec spec
:url "/"
:headers {"cookie" "no_override"}})
(get-in [:headers "cookie"])))
"no attempts to override when header is already set")
(is (= "id=44" (-> (middleware/wrap-cookies {:url "/"
:cookies [{:name "id"
:value "44"
:domain "domain.com"}]})
(get-in [:headers "cookie"])))
"accept cookies from req directly")
(is (= "name=John" (-> (middleware/wrap-cookies {:url "/"
:cookies [{:name "name" :value "John"}]
:cookie-store cs})
(get-in [:headers "cookie"])))
"explicitly set cookies override cookie-store even when specified")
(is (nil? (middleware/decode-set-cookie-header ""))
"empty set-cookie header doesn't crash")))
(defn req->query-string [req]
(-> (reduce #(%2 %1) req middleware/default-middleware)
:query-string
URLDecoder/decode))
(defn req->body-raw [req]
(:body (reduce #(%2 %1) req middleware/default-middleware)))
(defn req->body-decoded [req]
(URLDecoder/decode (req->body-raw req)))
(deftest test-nested-params
(is (= "foo[bar]=baz" (req->query-string {:query-params {:foo {:bar "baz"}}})))
(is (= "foo[bar]=baz" (req->query-string {:query-params {:foo {:bar "baz"}}
:content-type :json})))
(is (= "foo[bar]=baz" (req->query-string {:query-params {:foo {:bar "baz"}}
:ignore-nested-query-string false})))
(is (= "foo={:bar \"baz\"}" (req->query-string {:query-params {:foo {:bar "baz"}}
:ignore-nested-query-string true})))
(is (= "foo[bar]=baz" (req->body-decoded {:method :post
:form-params {:foo {:bar "baz"}}})))
(is (= "foo[bar]=baz" (req->body-decoded {:method :post
:flatten-nested-form-params true
:form-params {:foo {:bar "baz"}}})))
(is (= "foo={:bar \"baz\"}" (req->body-decoded {:method :post
:flatten-nested-form-params false
:form-params {:foo {:bar "baz"}}})))
(is (= "foo={:bar \"baz\"}" (req->body-decoded {:method :post
:flatten-nested-keys []
:form-params {:foo {:bar "baz"}}})))
(is (= "foo={:bar \"baz\"}" (req->body-decoded {:method :post
:flatten-nested-keys [:query-params]
:form-params {:foo {:bar "baz"}}})))
(is (= "foo[bar]=baz" (req->body-decoded {:method :post
:flatten-nested-keys [:form-params]
:form-params {:foo {:bar "baz"}}})))
(is (= "{\"foo\":{\"bar\":\"baz\"}}"
(req->body-raw {:method :post
:content-type :json
:form-params {:foo {:bar "baz"}}}))))
(deftest test-query-string-multi-param
(is (= "name=John" (middleware/generate-query-string {:name "John"})))
(is (= "name=John&name=Mark" (middleware/generate-query-string {:name ["John" "Mark"]})))
(is (= "name=John&name=Mark"
(middleware/generate-query-string {:name ["John" "Mark"]} nil :default)))
(is (= "name[]=John&name[]=Mark"
(middleware/generate-query-string {:name ["John" "Mark"]} nil :array)))
(is (= "name[0]=John&name[1]=Mark"
(middleware/generate-query-string {:name ["John" "Mark"]} nil :indexed))))
| null |
https://raw.githubusercontent.com/clj-commons/aleph/b5ca4d1b16b701c9465101be937a8ccce5d95d0b/test/aleph/http/client_middleware_test.clj
|
clojure
|
see #page-5
|
(ns aleph.http.client-middleware-test
(:require
[aleph.http.client-middleware :as middleware]
[clojure.test :as t :refer [deftest is]])
(:import
(java.net URLDecoder)))
(deftest test-empty-query-string
(is (= "" (middleware/generate-query-string {})))
(is (= "" (middleware/generate-query-string {} "text/plain; charset=utf-8")))
(is (= "" (middleware/generate-query-string {} "text/html;charset=ISO-8859-1"))))
(deftest test-basic-auth-value-encoding
(is (= "Basic Og==" (middleware/basic-auth-value nil)))
(is (= "Basic Og==" (middleware/basic-auth-value [])))
(is (= "Basic " (middleware/basic-auth-value "")))
(is (= "Basic dXNlcm5hbWU6cGFzc3dvcmQ=" (middleware/basic-auth-value "username:password")))
(is (= "Basic dXNlcm5hbWU6cGFzc3dvcmQ=" (middleware/basic-auth-value ["username" "password"])))
(is (= "Basic dXNlcm5hbWU6" (middleware/basic-auth-value ["username"])))
(is (= "Basic dXNlcm5hbWU=" (middleware/basic-auth-value "username"))))
(deftest test-coerce-form-params
(is (= "{\"foo\":\"bar\"}" (middleware/coerce-form-params {:content-type :json
:form-params {:foo :bar}})))
(is (= "[\"^ \",\"~:foo\",\"~:bar\"]"
(slurp (middleware/coerce-form-params {:content-type :transit+json
:form-params {:foo :bar}}))))
(is (= "{:foo :bar}" (middleware/coerce-form-params {:content-type :edn
:form-params {:foo :bar}})))
(is (= "foo=%3Abar" (middleware/coerce-form-params {:content-type :default
:form-params {:foo :bar}})))
(is (= "foo=%3Abar&foo=%3Abaz"
(middleware/coerce-form-params {:content-type :default
:form-params {:foo [:bar :baz]}})))
(is (= "foo[]=%3Abar&foo[]=%3Abaz"
(middleware/coerce-form-params {:content-type :default
:multi-param-style :array
:form-params {:foo [:bar :baz]}})))
(is (= "foo[0]=%3Abar&foo[1]=%3Abaz"
(middleware/coerce-form-params {:content-type :default
:multi-param-style :indexed
:form-params {:foo [:bar :baz]}})))
(is (= (middleware/coerce-form-params {:content-type :default
:form-params {:foo :bar}})
(middleware/coerce-form-params {:form-params {:foo :bar}}))))
(deftest test-nested-query-params
(let [req {:query-params {:foo {:bar "baz"}}}
{:keys [query-string]} (reduce #(%2 %1) req middleware/default-middleware)]
(is (= "foo[bar]=baz" (URLDecoder/decode query-string)))))
(deftest test-cookie-store
(let [c1 {:name "id"
:value "42"
:domain "domain.com"
:path "/"
:max-age nil
:http-only? true
:secure? false}
c2 {:name "track"
:value "off"
:domain "domain.com"
:path "/"
:max-age nil
:http-only? true
:secure? true}
c3 {:name "track"
:value "on"
:domain "domain.com"
:path "/blog"
:max-age nil
:http-only? true
:secure? true}
c4 {:name "subdomain"
:value "detect"
:domain "subdomain.com"}
c5 (middleware/decode-set-cookie-header "outdated=val; Domain=outdomain.com; Expires=Wed, 21 Oct 2015 07:28:00 GMT")
cs (middleware/in-memory-cookie-store [c1 c2 c3 c4 c5])
spec middleware/default-cookie-spec
dc (middleware/decode-set-cookie-header "id=42; Domain=domain.com; Path=/; HttpOnly")]
(is (= c1 dc))
(is (= "id=42; track=off" (-> (middleware/add-cookie-header cs spec {:url "/"})
(get-in [:headers "cookie"])))
"emit cookie for /blog path")
(is (= "id=42" (-> (middleware/add-cookie-header cs spec {:url "/"})
(get-in [:headers "cookie"])))
"http request should not set secure cookies")
(is (= "id=42; track=on" (-> (middleware/add-cookie-header cs spec {:url ""})
(get-in [:headers "cookie"])))
"the most specific path")
(is (= "subdomain=detect" (-> (middleware/add-cookie-header cs spec {:url ""})
(get-in [:headers "cookie"])))
"subdomain should match w/o leading dot under latest specifications")
(is (nil? (-> (middleware/add-cookie-header cs spec {:url "/"})
(get-in [:headers "cookie"])))
"domain mistmatch")
(is (nil? (-> (middleware/add-cookie-header cs spec {:url "/"})
(get-in [:headers "cookie"])))
"should not set expired")
(is (= "no_override"
(-> (middleware/wrap-cookies {:cookie-store cs
:cookie-spec spec
:url "/"
:headers {"cookie" "no_override"}})
(get-in [:headers "cookie"])))
"no attempts to override when header is already set")
(is (= "id=44" (-> (middleware/wrap-cookies {:url "/"
:cookies [{:name "id"
:value "44"
:domain "domain.com"}]})
(get-in [:headers "cookie"])))
"accept cookies from req directly")
(is (= "name=John" (-> (middleware/wrap-cookies {:url "/"
:cookies [{:name "name" :value "John"}]
:cookie-store cs})
(get-in [:headers "cookie"])))
"explicitly set cookies override cookie-store even when specified")
(is (nil? (middleware/decode-set-cookie-header ""))
"empty set-cookie header doesn't crash")))
(defn req->query-string [req]
(-> (reduce #(%2 %1) req middleware/default-middleware)
:query-string
URLDecoder/decode))
(defn req->body-raw [req]
(:body (reduce #(%2 %1) req middleware/default-middleware)))
(defn req->body-decoded [req]
(URLDecoder/decode (req->body-raw req)))
(deftest test-nested-params
(is (= "foo[bar]=baz" (req->query-string {:query-params {:foo {:bar "baz"}}})))
(is (= "foo[bar]=baz" (req->query-string {:query-params {:foo {:bar "baz"}}
:content-type :json})))
(is (= "foo[bar]=baz" (req->query-string {:query-params {:foo {:bar "baz"}}
:ignore-nested-query-string false})))
(is (= "foo={:bar \"baz\"}" (req->query-string {:query-params {:foo {:bar "baz"}}
:ignore-nested-query-string true})))
(is (= "foo[bar]=baz" (req->body-decoded {:method :post
:form-params {:foo {:bar "baz"}}})))
(is (= "foo[bar]=baz" (req->body-decoded {:method :post
:flatten-nested-form-params true
:form-params {:foo {:bar "baz"}}})))
(is (= "foo={:bar \"baz\"}" (req->body-decoded {:method :post
:flatten-nested-form-params false
:form-params {:foo {:bar "baz"}}})))
(is (= "foo={:bar \"baz\"}" (req->body-decoded {:method :post
:flatten-nested-keys []
:form-params {:foo {:bar "baz"}}})))
(is (= "foo={:bar \"baz\"}" (req->body-decoded {:method :post
:flatten-nested-keys [:query-params]
:form-params {:foo {:bar "baz"}}})))
(is (= "foo[bar]=baz" (req->body-decoded {:method :post
:flatten-nested-keys [:form-params]
:form-params {:foo {:bar "baz"}}})))
(is (= "{\"foo\":{\"bar\":\"baz\"}}"
(req->body-raw {:method :post
:content-type :json
:form-params {:foo {:bar "baz"}}}))))
(deftest test-query-string-multi-param
(is (= "name=John" (middleware/generate-query-string {:name "John"})))
(is (= "name=John&name=Mark" (middleware/generate-query-string {:name ["John" "Mark"]})))
(is (= "name=John&name=Mark"
(middleware/generate-query-string {:name ["John" "Mark"]} nil :default)))
(is (= "name[]=John&name[]=Mark"
(middleware/generate-query-string {:name ["John" "Mark"]} nil :array)))
(is (= "name[0]=John&name[1]=Mark"
(middleware/generate-query-string {:name ["John" "Mark"]} nil :indexed))))
|
9e0e383ab8f061fdadd78a9a4943177e3b44caa1a885b5e943bc1e1fc55a32c9
|
wildarch/jepsen.rqlite
|
sequential.clj
|
(ns jepsen.rqlite.sequential
"A sequential consistency test.
Verify that client order is consistent with DB order by performing queries
(in four distinct transactions) like
A: insert x
A: insert y
B: read y
B: read x
A's process order enforces that x must be visible before y, so we should
always read both or neither."
(:refer-clojure :exclude [test])
(:require [clojure.tools.logging :refer :all]
[jepsen.checker :as checker]
[jepsen.generator :as gen]
[jepsen.nemesis :as nemesis]
[clojure.core.reducers :as r]
[knossos.op :as op]
[jepsen.rqlite.common :as rqlite]
[jepsen.rqlite.nemesis :as nem]
[jepsen.cli :as cli])
(:import com.rqlite.Rqlite)
(:import com.rqlite.RqliteFactory
(com.rqlite.dto QueryResults)
(com.rqlite Rqlite$ReadConsistencyLevel)
(jepsen.generator Generator)
(clojure.lang PersistentQueue)))
Code adapted from the sequential test for CockroachDB from :
; -io/jepsen/blob/main/cockroachdb/src/jepsen/cockroach/sequential.clj
(def table-prefix "String prepended to all table names." "seq_")
(defn table-names
"Names of all tables"
[table-count]
(map (partial str table-prefix) (range table-count)))
(defn key->table
"Turns a key into a table id"
[table-count k]
(str table-prefix (mod (hash k) table-count)))
(defn subkeys
"The subkeys used for a given key, in order."
[key-count k]
(mapv (partial str k "_") (range key-count)))
(defn query-results-value
"Returns the only value returned from the query"
[results]
(do (assert (instance? QueryResults results))
(->> (.-results results)
first
.-values
first
first)))
(defrecord Client [table-count table-created? conn]
jepsen.client/Client
(open! [this test node]
(Thread/sleep 3000)
(assoc this :conn (RqliteFactory/connect "http" node (int 4001))))
(setup! [this test]
(locking table-created?
(when (compare-and-set! table-created? false true)
(info "Creating tables")
(doseq [t (table-names table-count)]
(.Execute conn (str "DROP TABLE IF EXISTS " t))
(.Execute conn (str "CREATE TABLE " t " (key varchar(255) primary key)"))))))
(invoke! [this test op]
(let [ks (subkeys (:key-count test) (:value op))]
(try
(case (:f op)
:write (do (doseq [k ks]
(let [table (key->table table-count k)]
(.Execute conn (str "INSERT INTO " table " VALUES ('" k "')"))))
(assoc op :type :ok))
:read (->> ks
reverse
(mapv (fn [k]
(query-results-value
(.Query conn
(str "SELECT key FROM "
(key->table table-count k)
" WHERE key = '" k "'")
(case (:read-consistency test)
:none com.rqlite.Rqlite$ReadConsistencyLevel/NONE
:weak com.rqlite.Rqlite$ReadConsistencyLevel/WEAK
:strong com.rqlite.Rqlite$ReadConsistencyLevel/STRONG)))))
(vector (:value op))
(assoc op :type :ok, :value)))
(catch com.rqlite.NodeUnavailableException e
(error "Node unavailable")
(assoc op :type :fail , :error :not-found))
(catch java.lang.NullPointerException e
(error "Connection error")
(assoc op
:type (if (= :read (:f op)) :fail :info)
:error :connection-lost)))))
(teardown! [this test])
(close! [_ test]))
(defn writes
"We emit sequential integer keys for writes, logging the most recent n keys
in the given atom, wrapping a PersistentQueue."
[last-written]
(let [k (atom -1)]
(fn []
(let [k (swap! k inc)]
(swap! last-written #(-> % pop (conj k)))
{:type :invoke, :f :write, :value k}))))
(defn reads
"We use the last-written atom to perform a read of a randomly selected
recently written value."
[last-written]
(gen/filter (comp complement nil? :value)
(fn [] {:type :invoke, :f :read, :value (rand-nth @last-written)})))
(defn gen
"Basic generator with n writers, and a buffer of 2n"
[n]
(let [last-written (atom
(reduce conj PersistentQueue/EMPTY
(repeat (* 2 n) nil)))]
(gen/reserve n (writes last-written)
(reads last-written))))
(defn trailing-nil?
"Does the given sequence contain a nil anywhere after a non-nil element?"
[coll]
(some nil? (drop-while nil? coll)))
(defn checker
[]
(reify checker/Checker
(check [this test history opts]
(assert (integer? (:key-count test)))
(let [reads (->> history
(r/filter op/ok?)
(r/filter #(= :read (:f %)))
(r/map :value)
(into []))
none (filter (comp (partial every? nil?) second) reads)
some (filter (comp (partial some nil?) second) reads)
bad (filter (comp trailing-nil? second) reads)
all (filter (fn [[k ks]]
(= (subkeys (:key-count test) k)
(reverse ks)))
reads)]
{:valid? (not (seq bad))
:all-count (count all)
:some-count (count some)
:none-count (count none)
:bad-count (count bad)
:bad bad}))))
(defn test
[opts]
(let [gen (gen 4)
keyrange (atom {})]
(merge rqlite/basic-test
{:name "sequential"
:key-count 5
:keyrange keyrange
:client (Client. 10 (atom false) nil)
:nemesis (case (:nemesis-type opts)
:partition (nemesis/partition-random-halves)
:hammer (nemesis/hammer-time "rqlited")
:flaky (nem/flaky)
:slow (nem/slow 1.0)
:noop nemesis/noop)
:generator (->>
(gen/stagger 1/100 gen)
(gen/nemesis
(cycle [(gen/sleep 5)
{:type :info, :f :start}
(gen/sleep 5)
{:type :info, :f :stop}]))
(gen/time-limit (:time-limit opts)))
:checker (checker)
:read-consistency (:read-consistency opts)}
opts)))
| null |
https://raw.githubusercontent.com/wildarch/jepsen.rqlite/f3430b4edc1aa0583d19e350b8cdd115fa187fb6/src/jepsen/rqlite/sequential.clj
|
clojure
|
-io/jepsen/blob/main/cockroachdb/src/jepsen/cockroach/sequential.clj
|
(ns jepsen.rqlite.sequential
"A sequential consistency test.
Verify that client order is consistent with DB order by performing queries
(in four distinct transactions) like
A: insert x
A: insert y
B: read y
B: read x
A's process order enforces that x must be visible before y, so we should
always read both or neither."
(:refer-clojure :exclude [test])
(:require [clojure.tools.logging :refer :all]
[jepsen.checker :as checker]
[jepsen.generator :as gen]
[jepsen.nemesis :as nemesis]
[clojure.core.reducers :as r]
[knossos.op :as op]
[jepsen.rqlite.common :as rqlite]
[jepsen.rqlite.nemesis :as nem]
[jepsen.cli :as cli])
(:import com.rqlite.Rqlite)
(:import com.rqlite.RqliteFactory
(com.rqlite.dto QueryResults)
(com.rqlite Rqlite$ReadConsistencyLevel)
(jepsen.generator Generator)
(clojure.lang PersistentQueue)))
Code adapted from the sequential test for CockroachDB from :
(def table-prefix "String prepended to all table names." "seq_")
(defn table-names
"Names of all tables"
[table-count]
(map (partial str table-prefix) (range table-count)))
(defn key->table
"Turns a key into a table id"
[table-count k]
(str table-prefix (mod (hash k) table-count)))
(defn subkeys
"The subkeys used for a given key, in order."
[key-count k]
(mapv (partial str k "_") (range key-count)))
(defn query-results-value
"Returns the only value returned from the query"
[results]
(do (assert (instance? QueryResults results))
(->> (.-results results)
first
.-values
first
first)))
(defrecord Client [table-count table-created? conn]
jepsen.client/Client
(open! [this test node]
(Thread/sleep 3000)
(assoc this :conn (RqliteFactory/connect "http" node (int 4001))))
(setup! [this test]
(locking table-created?
(when (compare-and-set! table-created? false true)
(info "Creating tables")
(doseq [t (table-names table-count)]
(.Execute conn (str "DROP TABLE IF EXISTS " t))
(.Execute conn (str "CREATE TABLE " t " (key varchar(255) primary key)"))))))
(invoke! [this test op]
(let [ks (subkeys (:key-count test) (:value op))]
(try
(case (:f op)
:write (do (doseq [k ks]
(let [table (key->table table-count k)]
(.Execute conn (str "INSERT INTO " table " VALUES ('" k "')"))))
(assoc op :type :ok))
:read (->> ks
reverse
(mapv (fn [k]
(query-results-value
(.Query conn
(str "SELECT key FROM "
(key->table table-count k)
" WHERE key = '" k "'")
(case (:read-consistency test)
:none com.rqlite.Rqlite$ReadConsistencyLevel/NONE
:weak com.rqlite.Rqlite$ReadConsistencyLevel/WEAK
:strong com.rqlite.Rqlite$ReadConsistencyLevel/STRONG)))))
(vector (:value op))
(assoc op :type :ok, :value)))
(catch com.rqlite.NodeUnavailableException e
(error "Node unavailable")
(assoc op :type :fail , :error :not-found))
(catch java.lang.NullPointerException e
(error "Connection error")
(assoc op
:type (if (= :read (:f op)) :fail :info)
:error :connection-lost)))))
(teardown! [this test])
(close! [_ test]))
(defn writes
"We emit sequential integer keys for writes, logging the most recent n keys
in the given atom, wrapping a PersistentQueue."
[last-written]
(let [k (atom -1)]
(fn []
(let [k (swap! k inc)]
(swap! last-written #(-> % pop (conj k)))
{:type :invoke, :f :write, :value k}))))
(defn reads
"We use the last-written atom to perform a read of a randomly selected
recently written value."
[last-written]
(gen/filter (comp complement nil? :value)
(fn [] {:type :invoke, :f :read, :value (rand-nth @last-written)})))
(defn gen
"Basic generator with n writers, and a buffer of 2n"
[n]
(let [last-written (atom
(reduce conj PersistentQueue/EMPTY
(repeat (* 2 n) nil)))]
(gen/reserve n (writes last-written)
(reads last-written))))
(defn trailing-nil?
"Does the given sequence contain a nil anywhere after a non-nil element?"
[coll]
(some nil? (drop-while nil? coll)))
(defn checker
[]
(reify checker/Checker
(check [this test history opts]
(assert (integer? (:key-count test)))
(let [reads (->> history
(r/filter op/ok?)
(r/filter #(= :read (:f %)))
(r/map :value)
(into []))
none (filter (comp (partial every? nil?) second) reads)
some (filter (comp (partial some nil?) second) reads)
bad (filter (comp trailing-nil? second) reads)
all (filter (fn [[k ks]]
(= (subkeys (:key-count test) k)
(reverse ks)))
reads)]
{:valid? (not (seq bad))
:all-count (count all)
:some-count (count some)
:none-count (count none)
:bad-count (count bad)
:bad bad}))))
(defn test
[opts]
(let [gen (gen 4)
keyrange (atom {})]
(merge rqlite/basic-test
{:name "sequential"
:key-count 5
:keyrange keyrange
:client (Client. 10 (atom false) nil)
:nemesis (case (:nemesis-type opts)
:partition (nemesis/partition-random-halves)
:hammer (nemesis/hammer-time "rqlited")
:flaky (nem/flaky)
:slow (nem/slow 1.0)
:noop nemesis/noop)
:generator (->>
(gen/stagger 1/100 gen)
(gen/nemesis
(cycle [(gen/sleep 5)
{:type :info, :f :start}
(gen/sleep 5)
{:type :info, :f :stop}]))
(gen/time-limit (:time-limit opts)))
:checker (checker)
:read-consistency (:read-consistency opts)}
opts)))
|
1074662355b6ef37cb1cef97ddcbefaf3ac73649c6e544a107f04a0572844d2d
|
chaitanyagupta/chronicity
|
utils.lisp
|
-*- Mode : LISP ; Syntax : COMMON - LISP ; Package : CL - USER ; Base : 10 -*-
;;; utils.lisp
;;; See the LICENSE file for licensing information.
(cl:in-package #:chronicity-test)
(defmacro assert-datetime= (expected form)
(let ((value (gensym "RESULT-")))
`(let ((,value ,form))
(assert-true (and ,value (datetime= ,expected ,value)) ,value))))
| null |
https://raw.githubusercontent.com/chaitanyagupta/chronicity/5841d1548cad0ca6917d8e68933124a5af68f5ec/test/utils.lisp
|
lisp
|
Syntax : COMMON - LISP ; Package : CL - USER ; Base : 10 -*-
utils.lisp
See the LICENSE file for licensing information.
|
(cl:in-package #:chronicity-test)
(defmacro assert-datetime= (expected form)
(let ((value (gensym "RESULT-")))
`(let ((,value ,form))
(assert-true (and ,value (datetime= ,expected ,value)) ,value))))
|
83357d34fdb0bb0e3633976a93ea44d21f10ea2c3ad0fccbba41238a1c13bfb6
|
haskell-tools/haskell-tools
|
Exprs.hs
|
-- | Representation of Haskell expressions
module Language.Haskell.Tools.AST.Representation.Exprs where
import Language.Haskell.Tools.AST.Ann (Ann, AnnListG, AnnMaybeG)
import {-# SOURCE #-} Language.Haskell.Tools.AST.Representation.Binds (ULocalBind, ULocalBinds, URhsGuard)
import Language.Haskell.Tools.AST.Representation.Literals (ULiteral)
import Language.Haskell.Tools.AST.Representation.Names (UStringNode, UName, UOperator)
import Language.Haskell.Tools.AST.Representation.Patterns (UPattern)
import Language.Haskell.Tools.AST.Representation.Stmts
import {-# SOURCE #-} Language.Haskell.Tools.AST.Representation.TH (UBracket, UQuasiQuote, USplice)
import Language.Haskell.Tools.AST.Representation.Types (UType)
-- | Haskell expressions
data UExpr dom stage
= UVar { _exprName :: Ann UName dom stage
} -- ^ A variable or a data constructor (@ a @)
| ULit { _exprLit :: Ann ULiteral dom stage
^ Literal expression ( @ 42 @ )
| UInfixApp { _exprLhs :: Ann UExpr dom stage
, _exprOperator :: Ann UOperator dom stage
, _exprRhs :: Ann UExpr dom stage
} -- ^ An infix operator application (@ a + b @)
| UPrefixApp { _exprOperator :: Ann UOperator dom stage
, _exprRhs :: Ann UExpr dom stage
} -- ^ Prefix operator application (@ -x @)
| UApp { _exprFun :: Ann UExpr dom stage
, _exprArg :: Ann UExpr dom stage
^ Function application ( @ f 4 @ )
^ at least one
, _exprInner :: Ann UExpr dom stage
} -- ^ Lambda expression (@ \a b -> a + b @)
| ULet { _exprFunBind :: AnnListG ULocalBind dom stage -- ^ nonempty
, _exprInner :: Ann UExpr dom stage
^ Local binding ( @ let x = 2 ; y = 3 in e x y @ )
| UIf { _exprCond :: Ann UExpr dom stage
, _exprThen :: Ann UExpr dom stage
, _exprElse :: Ann UExpr dom stage
} -- ^ If expression (@ if a then b else c @)
| UMultiIf { _exprIfAlts :: AnnListG UGuardedCaseRhs dom stage
^ Multi way if expressions with @MultiWayIf@ extension ( @ if | guard1 - > expr1 ; guard2 - > expr2 @ )
| UCase { _exprCase :: Ann UExpr dom stage
, _exprAlts :: AnnListG UAlt dom stage
^ Pattern matching expression ( @ case expr of pat1 - > expr1 ; pat2 - > expr2 @ )
| UDo { _doKind :: Ann UDoKind dom stage
, _exprStmts :: AnnListG UStmt dom stage
} -- ^ Do-notation expressions (@ do x <- act1; act2 @)
| UTuple { _tupleElems :: AnnListG UExpr dom stage
} -- ^ Tuple expression (@ (e1, e2, e3) @)
| UUnboxedTuple { _tupleElems :: AnnListG UExpr dom stage
^ tuple expression ( @ ( # e1 , e2 , e3 # ) @ )
| UTupleSection { _tupleSectionElems :: AnnListG UTupSecElem dom stage
^ Tuple section , enabled with @TupleSections@ ( @ ( a,,b ) @ ) . One of the elements must be missing .
| UUnboxedTupSec { _tupleSectionElems :: AnnListG UTupSecElem dom stage
^ Unboxed tuple section enabled with @TupleSections@ ( @ ( # a,,b # ) @ ) . One of the elements must be missing .
| UList { _listElems :: AnnListG UExpr dom stage
} -- ^ List expression: @[1,2,3]@
| UParArray { _listElems :: AnnListG UExpr dom stage
} -- ^ Parallel array expression: @[: 1,2,3 :]@
| UParen { _exprInner :: Ann UExpr dom stage
} -- ^ Parenthesized expression: @( a + b )@
| ULeftSection { _exprLhs :: Ann UExpr dom stage
, _exprOperator :: Ann UOperator dom stage
} -- ^ Left operator section: @(1+)@
| URightSection { _exprOperator :: Ann UOperator dom stage
, _exprRhs :: Ann UExpr dom stage
} -- ^ Right operator section: @(+1)@
| URecCon { _exprRecName :: Ann UName dom stage
, _exprRecFields :: AnnListG UFieldUpdate dom stage
^ Record value construction : @Point { x = 3 , y = -2 } @
| URecUpdate { _exprInner :: Ann UExpr dom stage
, _exprRecFields :: AnnListG UFieldUpdate dom stage
^ Record value update : @p1 { x = 3 , y = -2 } @
| UEnum { _enumFrom :: Ann UExpr dom stage
, _enumThen :: AnnMaybeG UExpr dom stage
, _enumTo :: AnnMaybeG UExpr dom stage
^ Enumeration expression ( @ [ 1,3 .. 10 ] @ )
| UParArrayEnum { _enumFrom :: Ann UExpr dom stage
, _enumThen :: AnnMaybeG UExpr dom stage
, _enumToFix :: Ann UExpr dom stage
^ Parallel array enumeration ( @ [: 1,3 .. 10 :] @ )
| UListComp { _compExpr :: Ann UExpr dom stage
^ Can only have 1 element without @ParallelListComp@
} -- ^ List comprehension (@ [ (x, y) | x <- xs | y <- ys ] @)
| UParArrayComp { _compExpr :: Ann UExpr dom stage
, _compBody :: AnnListG UListCompBody dom stage
} -- ^ Parallel array comprehensions @ [: (x, y) | x <- xs , y <- ys :] @ enabled by @ParallelArrays@
| UTypeSig { _exprInner :: Ann UExpr dom stage
, _exprSig :: Ann UType dom stage
} -- ^ Explicit type signature (@ x :: Int @)
| UExplTypeApp { _exprInner :: Ann UExpr dom stage
, _exprType :: Ann UType dom stage
} -- ^ Explicit type application (@ show \@Integer (read "5") @)
| UVarQuote { _quotedName :: Ann UName dom stage
} -- ^ @'x@ for template haskell reifying of expressions
| UTypeQuote { _quotedName :: Ann UName dom stage
} -- ^ @''T@ for template haskell reifying of types
| UBracketExpr { _exprBracket :: Ann UBracket dom stage
} -- ^ Template haskell bracket expression
| USplice { _exprSplice :: Ann USplice dom stage
^ Template haskell splice expression , for example : @$(gen a)@ or @$x@
| UQuasiQuoteExpr { _exprQQ :: Ann UQuasiQuote dom stage
} -- ^ Template haskell quasi-quotation: @[$quoter|str]@
| UExprPragma { _exprPragma :: Ann UExprPragma dom stage
, _innerExpr :: Ann UExpr dom stage
}
Arrows
| UProc { _procPattern :: Ann UPattern dom stage
, _procExpr :: Ann UCmd dom stage
} -- ^ Arrow definition: @proc a -> f -< a+1@
| UArrowApp { _exprLhs :: Ann UExpr dom stage
, _arrowAppl :: Ann UArrowAppl dom stage
, _exprRhs :: Ann UExpr dom stage
} -- ^ Arrow application: @f -< a+1@
| ULamCase { _exprAlts :: AnnListG UAlt dom stage
^ Lambda case ( @\case 0 - > 1 ; 1 - > 2@ )
| UStaticPtr { _exprInner :: Ann UExpr dom stage
} -- ^ Static pointer expression (@ static e @). The inner expression must be closed (cannot have variables bound outside)
| UUnboxedSum { _exprSumPlaceholdersBefore :: AnnListG UUnboxedSumPlaceHolder dom stage
, _exprInner :: Ann UExpr dom stage
, _exprSumPlaceholdersAfter :: AnnListG UUnboxedSumPlaceHolder dom stage
^ sum expression ( @ ( # | True # ) @ ) .
| UHole -- ^ A hole in the program @_@, similar to undefined but gives type information.
-- XML expressions omitted
-- | Field update expressions
data UFieldUpdate dom stage
= UNormalFieldUpdate { _fieldName :: Ann UName dom stage
, _fieldValue :: Ann UExpr dom stage
^ Update of a field ( @ x = 1 @ )
| UFieldPun { _fieldUpdateName :: Ann UName dom stage
} -- ^ Update the field to the value of the same name (@ x @)
| UFieldWildcard { _fieldWildcard :: Ann UFieldWildcard dom stage
} -- ^ Update the fields of the bounded names to their values (@ .. @). Must be the last initializer. Cannot be used in a record update expression.
-- | Marker for a field wildcard. Only needed to attach semantic information in a type-safe way.
data UFieldWildcard dom stage = FldWildcard
-- | An element of a tuple section that can be an expression or missing (indicating a value from a parameter)
data UTupSecElem dom stage
= Present { _tupSecExpr :: Ann UExpr dom stage
} -- ^ An existing element in a tuple section
| Missing -- ^ A missing element in a tuple section
-- | Clause of case expression (@ Just x -> x + 1 @)
data UAlt' expr dom stage
= UAlt { _altPattern :: Ann UPattern dom stage
, _altRhs :: Ann (UCaseRhs' expr) dom stage
, _altBinds :: AnnMaybeG ULocalBinds dom stage
}
type UAlt = UAlt' UExpr
type UCmdAlt = UAlt' UCmd
| Right hand side of a match ( possible with guards ): ( @ - > 3 @ or @ | x = = 1 - > 3 ; | otherwise - > 4 @ )
data UCaseRhs' expr dom stage
= UUnguardedCaseRhs { _rhsCaseExpr :: Ann expr dom stage
^ Unguarded right - hand side a pattern match ( @ - > 3 @ )
| UGuardedCaseRhss { _rhsCaseGuards :: AnnListG (UGuardedCaseRhs' expr) dom stage
^ Guarded right - hand sides of a pattern match ( @ | x = = 1 - > 3 ; | otherwise - > 4 @ )
type UCaseRhs = UCaseRhs' UExpr
type UCmdCaseRhs = UCaseRhs' UCmd
| A guarded right - hand side of pattern matches binding ( @ | x > 3 - > 2 @ )
data UGuardedCaseRhs' expr dom stage
= UGuardedCaseRhs { _caseGuardStmts :: AnnListG URhsGuard dom stage -- ^ Cannot be empty.
, _caseGuardExpr :: Ann expr dom stage
}
type UGuardedCaseRhs = UGuardedCaseRhs' UExpr
type UCmdGuardedCaseRhs = UGuardedCaseRhs' UCmd
-- | Pragmas that can be applied to expressions
data UExprPragma dom stage
= UCorePragma { _pragmaStr :: Ann UStringNode dom stage
} -- ^ A @CORE@ pragma for adding notes to expressions.
| USccPragma { _pragmaStr :: Ann UStringNode dom stage
} -- ^ An @SCC@ pragma for defining cost centers for profiling
| UGeneratedPragma { _pragmaSrcRange :: Ann USourceRange dom stage
} -- ^ A pragma that describes if an expression was generated from a code fragment by an external tool (@ {-# GENERATED "Happy.y" 1:15-1:25 #-} @)
-- | In-AST source ranges (for generated pragmas)
data USourceRange dom stage
= USourceRange { _srFileName :: Ann UStringNode dom stage
, _srFromLine :: Ann Number dom stage
, _srFromCol :: Ann Number dom stage
, _srToLine :: Ann Number dom stage
, _srToCol :: Ann Number dom stage
}
data Number dom stage
= Number { _numberInteger :: Integer
}
-- * Arrows
data UCmd dom stage
= UArrowAppCmd { _cmdLhs :: Ann UExpr dom stage
, _cmdArrowOp :: Ann UArrowAppl dom stage
, _cmdRhs :: Ann UExpr dom stage
} -- ^ An arrow application command (@ f -< x + 1 @)
| UArrowFormCmd { _cmdExpr :: Ann UExpr dom stage
, _cmdInnerCmds :: AnnListG UCmd dom stage
^ A form command ( @ ( |untilA ( increment - < x+y ) ( within 0.5 - < x)| ) @ )
| UAppCmd { _cmdInnerCmd :: Ann UCmd dom stage
, _cmdApplied :: Ann UExpr dom stage
} -- ^ A function application command
| UInfixCmd { _cmdLeftCmd :: Ann UCmd dom stage
, _cmdOperator :: Ann UName dom stage
, _cmdRightCmd :: Ann UCmd dom stage
} -- ^ An infix command application
^ at least one
, _cmdInner :: Ann UCmd dom stage
} -- ^ A lambda command
| UParenCmd { _cmdInner :: Ann UCmd dom stage
} -- ^ A parenthesized command
| UCaseCmd { _cmdExpr :: Ann UExpr dom stage
, _cmdAlts :: AnnListG UCmdAlt dom stage
} -- ^ A pattern match command
| UIfCmd { _cmdExpr :: Ann UExpr dom stage
, _cmdThen :: Ann UCmd dom stage
, _cmdElse :: Ann UCmd dom stage
} -- ^ An if command (@ if f x y then g -< x+1 else h -< y+2 @)
| ULetCmd { _cmdBinds :: AnnListG ULocalBind dom stage -- ^ nonempty
, _cmdInner :: Ann UCmd dom stage
} -- ^ A local binding command (@ let z = x+y @)
| UDoCmd { _cmdStmts :: AnnListG UCmdStmt dom stage
} -- ^ A do-notation in a command
data UArrowAppl dom stage
= ULeftAppl -- ^ Left arrow application: @-<@
^ Right arrow application :
| ULeftHighApp -- ^ Left arrow high application: @-<<@
| URightHighApp -- ^ Right arrow high application: @>>-@
data UUnboxedSumPlaceHolder dom stage = UUnboxedSumPlaceHolder
| null |
https://raw.githubusercontent.com/haskell-tools/haskell-tools/b1189ab4f63b29bbf1aa14af4557850064931e32/src/ast/Language/Haskell/Tools/AST/Representation/Exprs.hs
|
haskell
|
| Representation of Haskell expressions
# SOURCE #
# SOURCE #
| Haskell expressions
^ A variable or a data constructor (@ a @)
^ An infix operator application (@ a + b @)
^ Prefix operator application (@ -x @)
^ Lambda expression (@ \a b -> a + b @)
^ nonempty
^ If expression (@ if a then b else c @)
^ Do-notation expressions (@ do x <- act1; act2 @)
^ Tuple expression (@ (e1, e2, e3) @)
^ List expression: @[1,2,3]@
^ Parallel array expression: @[: 1,2,3 :]@
^ Parenthesized expression: @( a + b )@
^ Left operator section: @(1+)@
^ Right operator section: @(+1)@
^ List comprehension (@ [ (x, y) | x <- xs | y <- ys ] @)
^ Parallel array comprehensions @ [: (x, y) | x <- xs , y <- ys :] @ enabled by @ParallelArrays@
^ Explicit type signature (@ x :: Int @)
^ Explicit type application (@ show \@Integer (read "5") @)
^ @'x@ for template haskell reifying of expressions
^ @''T@ for template haskell reifying of types
^ Template haskell bracket expression
^ Template haskell quasi-quotation: @[$quoter|str]@
^ Arrow definition: @proc a -> f -< a+1@
^ Arrow application: @f -< a+1@
^ Static pointer expression (@ static e @). The inner expression must be closed (cannot have variables bound outside)
^ A hole in the program @_@, similar to undefined but gives type information.
XML expressions omitted
| Field update expressions
^ Update the field to the value of the same name (@ x @)
^ Update the fields of the bounded names to their values (@ .. @). Must be the last initializer. Cannot be used in a record update expression.
| Marker for a field wildcard. Only needed to attach semantic information in a type-safe way.
| An element of a tuple section that can be an expression or missing (indicating a value from a parameter)
^ An existing element in a tuple section
^ A missing element in a tuple section
| Clause of case expression (@ Just x -> x + 1 @)
^ Cannot be empty.
| Pragmas that can be applied to expressions
^ A @CORE@ pragma for adding notes to expressions.
^ An @SCC@ pragma for defining cost centers for profiling
^ A pragma that describes if an expression was generated from a code fragment by an external tool (@ {-# GENERATED "Happy.y" 1:15-1:25 #-} @)
| In-AST source ranges (for generated pragmas)
* Arrows
^ An arrow application command (@ f -< x + 1 @)
^ A function application command
^ An infix command application
^ A lambda command
^ A parenthesized command
^ A pattern match command
^ An if command (@ if f x y then g -< x+1 else h -< y+2 @)
^ nonempty
^ A local binding command (@ let z = x+y @)
^ A do-notation in a command
^ Left arrow application: @-<@
^ Left arrow high application: @-<<@
^ Right arrow high application: @>>-@
|
module Language.Haskell.Tools.AST.Representation.Exprs where
import Language.Haskell.Tools.AST.Ann (Ann, AnnListG, AnnMaybeG)
import Language.Haskell.Tools.AST.Representation.Literals (ULiteral)
import Language.Haskell.Tools.AST.Representation.Names (UStringNode, UName, UOperator)
import Language.Haskell.Tools.AST.Representation.Patterns (UPattern)
import Language.Haskell.Tools.AST.Representation.Stmts
import Language.Haskell.Tools.AST.Representation.Types (UType)
data UExpr dom stage
= UVar { _exprName :: Ann UName dom stage
| ULit { _exprLit :: Ann ULiteral dom stage
^ Literal expression ( @ 42 @ )
| UInfixApp { _exprLhs :: Ann UExpr dom stage
, _exprOperator :: Ann UOperator dom stage
, _exprRhs :: Ann UExpr dom stage
| UPrefixApp { _exprOperator :: Ann UOperator dom stage
, _exprRhs :: Ann UExpr dom stage
| UApp { _exprFun :: Ann UExpr dom stage
, _exprArg :: Ann UExpr dom stage
^ Function application ( @ f 4 @ )
^ at least one
, _exprInner :: Ann UExpr dom stage
, _exprInner :: Ann UExpr dom stage
^ Local binding ( @ let x = 2 ; y = 3 in e x y @ )
| UIf { _exprCond :: Ann UExpr dom stage
, _exprThen :: Ann UExpr dom stage
, _exprElse :: Ann UExpr dom stage
| UMultiIf { _exprIfAlts :: AnnListG UGuardedCaseRhs dom stage
^ Multi way if expressions with @MultiWayIf@ extension ( @ if | guard1 - > expr1 ; guard2 - > expr2 @ )
| UCase { _exprCase :: Ann UExpr dom stage
, _exprAlts :: AnnListG UAlt dom stage
^ Pattern matching expression ( @ case expr of pat1 - > expr1 ; pat2 - > expr2 @ )
| UDo { _doKind :: Ann UDoKind dom stage
, _exprStmts :: AnnListG UStmt dom stage
| UTuple { _tupleElems :: AnnListG UExpr dom stage
| UUnboxedTuple { _tupleElems :: AnnListG UExpr dom stage
^ tuple expression ( @ ( # e1 , e2 , e3 # ) @ )
| UTupleSection { _tupleSectionElems :: AnnListG UTupSecElem dom stage
^ Tuple section , enabled with @TupleSections@ ( @ ( a,,b ) @ ) . One of the elements must be missing .
| UUnboxedTupSec { _tupleSectionElems :: AnnListG UTupSecElem dom stage
^ Unboxed tuple section enabled with @TupleSections@ ( @ ( # a,,b # ) @ ) . One of the elements must be missing .
| UList { _listElems :: AnnListG UExpr dom stage
| UParArray { _listElems :: AnnListG UExpr dom stage
| UParen { _exprInner :: Ann UExpr dom stage
| ULeftSection { _exprLhs :: Ann UExpr dom stage
, _exprOperator :: Ann UOperator dom stage
| URightSection { _exprOperator :: Ann UOperator dom stage
, _exprRhs :: Ann UExpr dom stage
| URecCon { _exprRecName :: Ann UName dom stage
, _exprRecFields :: AnnListG UFieldUpdate dom stage
^ Record value construction : @Point { x = 3 , y = -2 } @
| URecUpdate { _exprInner :: Ann UExpr dom stage
, _exprRecFields :: AnnListG UFieldUpdate dom stage
^ Record value update : @p1 { x = 3 , y = -2 } @
| UEnum { _enumFrom :: Ann UExpr dom stage
, _enumThen :: AnnMaybeG UExpr dom stage
, _enumTo :: AnnMaybeG UExpr dom stage
^ Enumeration expression ( @ [ 1,3 .. 10 ] @ )
| UParArrayEnum { _enumFrom :: Ann UExpr dom stage
, _enumThen :: AnnMaybeG UExpr dom stage
, _enumToFix :: Ann UExpr dom stage
^ Parallel array enumeration ( @ [: 1,3 .. 10 :] @ )
| UListComp { _compExpr :: Ann UExpr dom stage
^ Can only have 1 element without @ParallelListComp@
| UParArrayComp { _compExpr :: Ann UExpr dom stage
, _compBody :: AnnListG UListCompBody dom stage
| UTypeSig { _exprInner :: Ann UExpr dom stage
, _exprSig :: Ann UType dom stage
| UExplTypeApp { _exprInner :: Ann UExpr dom stage
, _exprType :: Ann UType dom stage
| UVarQuote { _quotedName :: Ann UName dom stage
| UTypeQuote { _quotedName :: Ann UName dom stage
| UBracketExpr { _exprBracket :: Ann UBracket dom stage
| USplice { _exprSplice :: Ann USplice dom stage
^ Template haskell splice expression , for example : @$(gen a)@ or @$x@
| UQuasiQuoteExpr { _exprQQ :: Ann UQuasiQuote dom stage
| UExprPragma { _exprPragma :: Ann UExprPragma dom stage
, _innerExpr :: Ann UExpr dom stage
}
Arrows
| UProc { _procPattern :: Ann UPattern dom stage
, _procExpr :: Ann UCmd dom stage
| UArrowApp { _exprLhs :: Ann UExpr dom stage
, _arrowAppl :: Ann UArrowAppl dom stage
, _exprRhs :: Ann UExpr dom stage
| ULamCase { _exprAlts :: AnnListG UAlt dom stage
^ Lambda case ( @\case 0 - > 1 ; 1 - > 2@ )
| UStaticPtr { _exprInner :: Ann UExpr dom stage
| UUnboxedSum { _exprSumPlaceholdersBefore :: AnnListG UUnboxedSumPlaceHolder dom stage
, _exprInner :: Ann UExpr dom stage
, _exprSumPlaceholdersAfter :: AnnListG UUnboxedSumPlaceHolder dom stage
^ sum expression ( @ ( # | True # ) @ ) .
data UFieldUpdate dom stage
= UNormalFieldUpdate { _fieldName :: Ann UName dom stage
, _fieldValue :: Ann UExpr dom stage
^ Update of a field ( @ x = 1 @ )
| UFieldPun { _fieldUpdateName :: Ann UName dom stage
| UFieldWildcard { _fieldWildcard :: Ann UFieldWildcard dom stage
data UFieldWildcard dom stage = FldWildcard
data UTupSecElem dom stage
= Present { _tupSecExpr :: Ann UExpr dom stage
data UAlt' expr dom stage
= UAlt { _altPattern :: Ann UPattern dom stage
, _altRhs :: Ann (UCaseRhs' expr) dom stage
, _altBinds :: AnnMaybeG ULocalBinds dom stage
}
type UAlt = UAlt' UExpr
type UCmdAlt = UAlt' UCmd
| Right hand side of a match ( possible with guards ): ( @ - > 3 @ or @ | x = = 1 - > 3 ; | otherwise - > 4 @ )
data UCaseRhs' expr dom stage
= UUnguardedCaseRhs { _rhsCaseExpr :: Ann expr dom stage
^ Unguarded right - hand side a pattern match ( @ - > 3 @ )
| UGuardedCaseRhss { _rhsCaseGuards :: AnnListG (UGuardedCaseRhs' expr) dom stage
^ Guarded right - hand sides of a pattern match ( @ | x = = 1 - > 3 ; | otherwise - > 4 @ )
type UCaseRhs = UCaseRhs' UExpr
type UCmdCaseRhs = UCaseRhs' UCmd
| A guarded right - hand side of pattern matches binding ( @ | x > 3 - > 2 @ )
data UGuardedCaseRhs' expr dom stage
, _caseGuardExpr :: Ann expr dom stage
}
type UGuardedCaseRhs = UGuardedCaseRhs' UExpr
type UCmdGuardedCaseRhs = UGuardedCaseRhs' UCmd
data UExprPragma dom stage
= UCorePragma { _pragmaStr :: Ann UStringNode dom stage
| USccPragma { _pragmaStr :: Ann UStringNode dom stage
| UGeneratedPragma { _pragmaSrcRange :: Ann USourceRange dom stage
data USourceRange dom stage
= USourceRange { _srFileName :: Ann UStringNode dom stage
, _srFromLine :: Ann Number dom stage
, _srFromCol :: Ann Number dom stage
, _srToLine :: Ann Number dom stage
, _srToCol :: Ann Number dom stage
}
data Number dom stage
= Number { _numberInteger :: Integer
}
data UCmd dom stage
= UArrowAppCmd { _cmdLhs :: Ann UExpr dom stage
, _cmdArrowOp :: Ann UArrowAppl dom stage
, _cmdRhs :: Ann UExpr dom stage
| UArrowFormCmd { _cmdExpr :: Ann UExpr dom stage
, _cmdInnerCmds :: AnnListG UCmd dom stage
^ A form command ( @ ( |untilA ( increment - < x+y ) ( within 0.5 - < x)| ) @ )
| UAppCmd { _cmdInnerCmd :: Ann UCmd dom stage
, _cmdApplied :: Ann UExpr dom stage
| UInfixCmd { _cmdLeftCmd :: Ann UCmd dom stage
, _cmdOperator :: Ann UName dom stage
, _cmdRightCmd :: Ann UCmd dom stage
^ at least one
, _cmdInner :: Ann UCmd dom stage
| UParenCmd { _cmdInner :: Ann UCmd dom stage
| UCaseCmd { _cmdExpr :: Ann UExpr dom stage
, _cmdAlts :: AnnListG UCmdAlt dom stage
| UIfCmd { _cmdExpr :: Ann UExpr dom stage
, _cmdThen :: Ann UCmd dom stage
, _cmdElse :: Ann UCmd dom stage
, _cmdInner :: Ann UCmd dom stage
| UDoCmd { _cmdStmts :: AnnListG UCmdStmt dom stage
data UArrowAppl dom stage
^ Right arrow application :
data UUnboxedSumPlaceHolder dom stage = UUnboxedSumPlaceHolder
|
76f991b1d9740d0a008fe1a1fec98286d3dab0304c7c8c4c4c649d2469b86b12
|
callum-oakley/advent-of-code
|
23.clj
|
(ns aoc.2020.23
(:require
[clojure.string :as str]
[clojure.test :refer [deftest is]]))
(defn parse [s]
(map #(- (int %) (int \0)) s))
(defn initial-state [cups]
{:next-cup (->> (partition 2 1 cups)
(concat [[0 nil] [(last cups) (first cups)]])
(sort-by first)
(mapv second)
transient)
:current (first cups)
:maxcup (apply max cups)})
(defn move [{:keys [next-cup current maxcup] :as state}]
;; ... current a b c d ... destination e ...
(let [a (next-cup current) b (next-cup a) c (next-cup b) d (next-cup c)
destination (->> (iterate #(if (= % 1) maxcup (dec %)) current)
rest
(some #(when-not (#{a b c} %) %)))
e (next-cup destination)]
(assoc state
:next-cup (assoc! next-cup current d destination a c e)
:current d)))
(defn game [n cups]
(:next-cup (first (drop n (iterate move (initial-state cups))))))
(defn part-1 [cups]
(let [next-cup (game 100 cups)]
(str/join (take (dec (count cups)) (rest (iterate next-cup 1))))))
(defn part-2 [cups]
(let [next-cup (game 10000000 (concat cups (range 10 1000001)))
a (next-cup 1) b (next-cup a)]
(* a b)))
(deftest test-examples
(is (= (part-1 [3 8 9 1 2 5 4 6 7]) "67384529"))
(is (= (part-2 [3 8 9 1 2 5 4 6 7]) 149245887792)))
| null |
https://raw.githubusercontent.com/callum-oakley/advent-of-code/da5233fc0fd3d3773d35ee747fd837c59c2b1c04/src/aoc/2020/23.clj
|
clojure
|
... current a b c d ... destination e ...
|
(ns aoc.2020.23
(:require
[clojure.string :as str]
[clojure.test :refer [deftest is]]))
(defn parse [s]
(map #(- (int %) (int \0)) s))
(defn initial-state [cups]
{:next-cup (->> (partition 2 1 cups)
(concat [[0 nil] [(last cups) (first cups)]])
(sort-by first)
(mapv second)
transient)
:current (first cups)
:maxcup (apply max cups)})
(defn move [{:keys [next-cup current maxcup] :as state}]
(let [a (next-cup current) b (next-cup a) c (next-cup b) d (next-cup c)
destination (->> (iterate #(if (= % 1) maxcup (dec %)) current)
rest
(some #(when-not (#{a b c} %) %)))
e (next-cup destination)]
(assoc state
:next-cup (assoc! next-cup current d destination a c e)
:current d)))
(defn game [n cups]
(:next-cup (first (drop n (iterate move (initial-state cups))))))
(defn part-1 [cups]
(let [next-cup (game 100 cups)]
(str/join (take (dec (count cups)) (rest (iterate next-cup 1))))))
(defn part-2 [cups]
(let [next-cup (game 10000000 (concat cups (range 10 1000001)))
a (next-cup 1) b (next-cup a)]
(* a b)))
(deftest test-examples
(is (= (part-1 [3 8 9 1 2 5 4 6 7]) "67384529"))
(is (= (part-2 [3 8 9 1 2 5 4 6 7]) 149245887792)))
|
763da135d126c47529a6ef0b51a765e8dd2a5a649314361ca91051b71219fa53
|
mbj/stratosphere
|
NotificationConfigurationProperty.hs
|
module Stratosphere.S3.Bucket.NotificationConfigurationProperty (
module Exports, NotificationConfigurationProperty(..),
mkNotificationConfigurationProperty
) where
import qualified Data.Aeson as JSON
import qualified Stratosphere.Prelude as Prelude
import Stratosphere.Property
import {-# SOURCE #-} Stratosphere.S3.Bucket.EventBridgeConfigurationProperty as Exports
import {-# SOURCE #-} Stratosphere.S3.Bucket.LambdaConfigurationProperty as Exports
import {-# SOURCE #-} Stratosphere.S3.Bucket.QueueConfigurationProperty as Exports
import {-# SOURCE #-} Stratosphere.S3.Bucket.TopicConfigurationProperty as Exports
import Stratosphere.ResourceProperties
data NotificationConfigurationProperty
= NotificationConfigurationProperty {eventBridgeConfiguration :: (Prelude.Maybe EventBridgeConfigurationProperty),
lambdaConfigurations :: (Prelude.Maybe [LambdaConfigurationProperty]),
queueConfigurations :: (Prelude.Maybe [QueueConfigurationProperty]),
topicConfigurations :: (Prelude.Maybe [TopicConfigurationProperty])}
mkNotificationConfigurationProperty ::
NotificationConfigurationProperty
mkNotificationConfigurationProperty
= NotificationConfigurationProperty
{eventBridgeConfiguration = Prelude.Nothing,
lambdaConfigurations = Prelude.Nothing,
queueConfigurations = Prelude.Nothing,
topicConfigurations = Prelude.Nothing}
instance ToResourceProperties NotificationConfigurationProperty where
toResourceProperties NotificationConfigurationProperty {..}
= ResourceProperties
{awsType = "AWS::S3::Bucket.NotificationConfiguration",
supportsTags = Prelude.False,
properties = Prelude.fromList
(Prelude.catMaybes
[(JSON..=) "EventBridgeConfiguration"
Prelude.<$> eventBridgeConfiguration,
(JSON..=) "LambdaConfigurations" Prelude.<$> lambdaConfigurations,
(JSON..=) "QueueConfigurations" Prelude.<$> queueConfigurations,
(JSON..=) "TopicConfigurations" Prelude.<$> topicConfigurations])}
instance JSON.ToJSON NotificationConfigurationProperty where
toJSON NotificationConfigurationProperty {..}
= JSON.object
(Prelude.fromList
(Prelude.catMaybes
[(JSON..=) "EventBridgeConfiguration"
Prelude.<$> eventBridgeConfiguration,
(JSON..=) "LambdaConfigurations" Prelude.<$> lambdaConfigurations,
(JSON..=) "QueueConfigurations" Prelude.<$> queueConfigurations,
(JSON..=) "TopicConfigurations" Prelude.<$> topicConfigurations]))
instance Property "EventBridgeConfiguration" NotificationConfigurationProperty where
type PropertyType "EventBridgeConfiguration" NotificationConfigurationProperty = EventBridgeConfigurationProperty
set newValue NotificationConfigurationProperty {..}
= NotificationConfigurationProperty
{eventBridgeConfiguration = Prelude.pure newValue, ..}
instance Property "LambdaConfigurations" NotificationConfigurationProperty where
type PropertyType "LambdaConfigurations" NotificationConfigurationProperty = [LambdaConfigurationProperty]
set newValue NotificationConfigurationProperty {..}
= NotificationConfigurationProperty
{lambdaConfigurations = Prelude.pure newValue, ..}
instance Property "QueueConfigurations" NotificationConfigurationProperty where
type PropertyType "QueueConfigurations" NotificationConfigurationProperty = [QueueConfigurationProperty]
set newValue NotificationConfigurationProperty {..}
= NotificationConfigurationProperty
{queueConfigurations = Prelude.pure newValue, ..}
instance Property "TopicConfigurations" NotificationConfigurationProperty where
type PropertyType "TopicConfigurations" NotificationConfigurationProperty = [TopicConfigurationProperty]
set newValue NotificationConfigurationProperty {..}
= NotificationConfigurationProperty
{topicConfigurations = Prelude.pure newValue, ..}
| null |
https://raw.githubusercontent.com/mbj/stratosphere/c70f301715425247efcda29af4f3fcf7ec04aa2f/services/s3/gen/Stratosphere/S3/Bucket/NotificationConfigurationProperty.hs
|
haskell
|
# SOURCE #
# SOURCE #
# SOURCE #
# SOURCE #
|
module Stratosphere.S3.Bucket.NotificationConfigurationProperty (
module Exports, NotificationConfigurationProperty(..),
mkNotificationConfigurationProperty
) where
import qualified Data.Aeson as JSON
import qualified Stratosphere.Prelude as Prelude
import Stratosphere.Property
import Stratosphere.ResourceProperties
data NotificationConfigurationProperty
= NotificationConfigurationProperty {eventBridgeConfiguration :: (Prelude.Maybe EventBridgeConfigurationProperty),
lambdaConfigurations :: (Prelude.Maybe [LambdaConfigurationProperty]),
queueConfigurations :: (Prelude.Maybe [QueueConfigurationProperty]),
topicConfigurations :: (Prelude.Maybe [TopicConfigurationProperty])}
mkNotificationConfigurationProperty ::
NotificationConfigurationProperty
mkNotificationConfigurationProperty
= NotificationConfigurationProperty
{eventBridgeConfiguration = Prelude.Nothing,
lambdaConfigurations = Prelude.Nothing,
queueConfigurations = Prelude.Nothing,
topicConfigurations = Prelude.Nothing}
instance ToResourceProperties NotificationConfigurationProperty where
toResourceProperties NotificationConfigurationProperty {..}
= ResourceProperties
{awsType = "AWS::S3::Bucket.NotificationConfiguration",
supportsTags = Prelude.False,
properties = Prelude.fromList
(Prelude.catMaybes
[(JSON..=) "EventBridgeConfiguration"
Prelude.<$> eventBridgeConfiguration,
(JSON..=) "LambdaConfigurations" Prelude.<$> lambdaConfigurations,
(JSON..=) "QueueConfigurations" Prelude.<$> queueConfigurations,
(JSON..=) "TopicConfigurations" Prelude.<$> topicConfigurations])}
instance JSON.ToJSON NotificationConfigurationProperty where
toJSON NotificationConfigurationProperty {..}
= JSON.object
(Prelude.fromList
(Prelude.catMaybes
[(JSON..=) "EventBridgeConfiguration"
Prelude.<$> eventBridgeConfiguration,
(JSON..=) "LambdaConfigurations" Prelude.<$> lambdaConfigurations,
(JSON..=) "QueueConfigurations" Prelude.<$> queueConfigurations,
(JSON..=) "TopicConfigurations" Prelude.<$> topicConfigurations]))
instance Property "EventBridgeConfiguration" NotificationConfigurationProperty where
type PropertyType "EventBridgeConfiguration" NotificationConfigurationProperty = EventBridgeConfigurationProperty
set newValue NotificationConfigurationProperty {..}
= NotificationConfigurationProperty
{eventBridgeConfiguration = Prelude.pure newValue, ..}
instance Property "LambdaConfigurations" NotificationConfigurationProperty where
type PropertyType "LambdaConfigurations" NotificationConfigurationProperty = [LambdaConfigurationProperty]
set newValue NotificationConfigurationProperty {..}
= NotificationConfigurationProperty
{lambdaConfigurations = Prelude.pure newValue, ..}
instance Property "QueueConfigurations" NotificationConfigurationProperty where
type PropertyType "QueueConfigurations" NotificationConfigurationProperty = [QueueConfigurationProperty]
set newValue NotificationConfigurationProperty {..}
= NotificationConfigurationProperty
{queueConfigurations = Prelude.pure newValue, ..}
instance Property "TopicConfigurations" NotificationConfigurationProperty where
type PropertyType "TopicConfigurations" NotificationConfigurationProperty = [TopicConfigurationProperty]
set newValue NotificationConfigurationProperty {..}
= NotificationConfigurationProperty
{topicConfigurations = Prelude.pure newValue, ..}
|
ef3c5d4a860cfa7f43cd3b819fe4f790474bb8085a2825afec8df5a5dd3c16f9
|
ijvcms/chuanqi_dev
|
word_map_config.erl
|
%%%-------------------------------------------------------------------
@author zhengsiying
%%% @doc
%%% 自动生成文件,不要手动修改
%%% @end
Created : 2016/10/12
%%%-------------------------------------------------------------------
-module(word_map_config).
-include("common.hrl").
-include("config.hrl").
-compile([export_all]).
get_list_conf() ->
[ word_map_config:get(X) || X <- get_list() ].
get_list() ->
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16].
get(1) ->
#word_map_conf{
id = 1,
scene_id = 20100
};
get(2) ->
#word_map_conf{
id = 2,
scene_id = 20101
};
get(3) ->
#word_map_conf{
id = 3,
scene_id = 20102
};
get(4) ->
#word_map_conf{
id = 4,
scene_id = 20103
};
get(5) ->
#word_map_conf{
id = 5,
scene_id = 20015
};
get(6) ->
#word_map_conf{
id = 6,
scene_id = 20105
};
get(7) ->
#word_map_conf{
id = 7,
scene_id = 20201
};
get(8) ->
#word_map_conf{
id = 8,
scene_id = 20204
};
get(9) ->
#word_map_conf{
id = 9,
scene_id = 20207
};
get(10) ->
#word_map_conf{
id = 10,
scene_id = 20210
};
get(11) ->
#word_map_conf{
id = 11,
scene_id = 20213
};
get(12) ->
#word_map_conf{
id = 12,
scene_id = 20216
};
get(13) ->
#word_map_conf{
id = 13,
scene_id = 20234
};
get(14) ->
#word_map_conf{
id = 14,
scene_id = 20237
};
get(15) ->
#word_map_conf{
id = 15,
scene_id = 20243
};
get(16) ->
#word_map_conf{
id = 16,
scene_id = 32118
};
get(_Key) ->
?ERR("undefined key from word_map_config ~p", [_Key]).
| null |
https://raw.githubusercontent.com/ijvcms/chuanqi_dev/7742184bded15f25be761c4f2d78834249d78097/server/trunk/server/src/config/word_map_config.erl
|
erlang
|
-------------------------------------------------------------------
@doc
自动生成文件,不要手动修改
@end
-------------------------------------------------------------------
|
@author zhengsiying
Created : 2016/10/12
-module(word_map_config).
-include("common.hrl").
-include("config.hrl").
-compile([export_all]).
get_list_conf() ->
[ word_map_config:get(X) || X <- get_list() ].
get_list() ->
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16].
get(1) ->
#word_map_conf{
id = 1,
scene_id = 20100
};
get(2) ->
#word_map_conf{
id = 2,
scene_id = 20101
};
get(3) ->
#word_map_conf{
id = 3,
scene_id = 20102
};
get(4) ->
#word_map_conf{
id = 4,
scene_id = 20103
};
get(5) ->
#word_map_conf{
id = 5,
scene_id = 20015
};
get(6) ->
#word_map_conf{
id = 6,
scene_id = 20105
};
get(7) ->
#word_map_conf{
id = 7,
scene_id = 20201
};
get(8) ->
#word_map_conf{
id = 8,
scene_id = 20204
};
get(9) ->
#word_map_conf{
id = 9,
scene_id = 20207
};
get(10) ->
#word_map_conf{
id = 10,
scene_id = 20210
};
get(11) ->
#word_map_conf{
id = 11,
scene_id = 20213
};
get(12) ->
#word_map_conf{
id = 12,
scene_id = 20216
};
get(13) ->
#word_map_conf{
id = 13,
scene_id = 20234
};
get(14) ->
#word_map_conf{
id = 14,
scene_id = 20237
};
get(15) ->
#word_map_conf{
id = 15,
scene_id = 20243
};
get(16) ->
#word_map_conf{
id = 16,
scene_id = 32118
};
get(_Key) ->
?ERR("undefined key from word_map_config ~p", [_Key]).
|
9c26a29d9747cd113b10e328e1f4b7645e6161f90d483062323eb43c18174506
|
DavidAlphaFox/RabbitMQ
|
rabbit_mgmt_wm_parameter.erl
|
The contents of this file are subject to the Mozilla Public License
Version 1.1 ( the " License " ) ; you may not use this file except in
%% compliance with the License. You may obtain a copy of the License at
%% /
%%
Software distributed under the License is distributed on an " AS IS "
%% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
%% License for the specific language governing rights and limitations
%% under the License.
%%
The Original Code is RabbitMQ Management Plugin .
%%
The Initial Developer of the Original Code is GoPivotal , Inc.
Copyright ( c ) 2010 - 2014 GoPivotal , Inc. All rights reserved .
%%
-module(rabbit_mgmt_wm_parameter).
-export([init/1, resource_exists/2, to_json/2,
content_types_provided/2, content_types_accepted/2,
is_authorized/2, allowed_methods/2, accept_content/2,
delete_resource/2]).
-import(rabbit_misc, [pget/2]).
-include("rabbit_mgmt.hrl").
-include_lib("webmachine/include/webmachine.hrl").
-include_lib("rabbit_common/include/rabbit.hrl").
%%--------------------------------------------------------------------
init(_Config) -> {ok, #context{}}.
content_types_provided(ReqData, Context) ->
{[{"application/json", to_json}], ReqData, Context}.
content_types_accepted(ReqData, Context) ->
{[{"application/json", accept_content}], ReqData, Context}.
allowed_methods(ReqData, Context) ->
{['HEAD', 'GET', 'PUT', 'DELETE'], ReqData, Context}.
resource_exists(ReqData, Context) ->
{case parameter(ReqData) of
not_found -> false;
_ -> true
end, ReqData, Context}.
to_json(ReqData, Context) ->
rabbit_mgmt_util:reply(rabbit_mgmt_format:parameter(parameter(ReqData)),
ReqData, Context).
accept_content(ReqData, Context = #context{user = User}) ->
case rabbit_mgmt_util:vhost(ReqData) of
not_found ->
rabbit_mgmt_util:not_found(vhost_not_found, ReqData, Context);
VHost ->
rabbit_mgmt_util:with_decode(
[value], ReqData, Context,
fun([Value], _) ->
case rabbit_runtime_parameters:set(
VHost, component(ReqData), name(ReqData),
rabbit_misc:json_to_term(Value), User) of
ok ->
{true, ReqData, Context};
{error_string, Reason} ->
rabbit_mgmt_util:bad_request(
list_to_binary(Reason), ReqData, Context)
end
end)
end.
delete_resource(ReqData, Context) ->
ok = rabbit_runtime_parameters:clear(
rabbit_mgmt_util:vhost(ReqData), component(ReqData), name(ReqData)),
{true, ReqData, Context}.
is_authorized(ReqData, Context) ->
rabbit_mgmt_util:is_authorized_policies(ReqData, Context).
%%--------------------------------------------------------------------
parameter(ReqData) ->
rabbit_runtime_parameters:lookup(
rabbit_mgmt_util:vhost(ReqData), component(ReqData), name(ReqData)).
component(ReqData) -> rabbit_mgmt_util:id(component, ReqData).
name(ReqData) -> rabbit_mgmt_util:id(name, ReqData).
| null |
https://raw.githubusercontent.com/DavidAlphaFox/RabbitMQ/0a64e6f0464a9a4ce85c6baa52fb1c584689f49a/plugins-src/rabbitmq-management/src/rabbit_mgmt_wm_parameter.erl
|
erlang
|
compliance with the License. You may obtain a copy of the License at
/
basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
License for the specific language governing rights and limitations
under the License.
--------------------------------------------------------------------
--------------------------------------------------------------------
|
The contents of this file are subject to the Mozilla Public License
Version 1.1 ( the " License " ) ; you may not use this file except in
Software distributed under the License is distributed on an " AS IS "
The Original Code is RabbitMQ Management Plugin .
The Initial Developer of the Original Code is GoPivotal , Inc.
Copyright ( c ) 2010 - 2014 GoPivotal , Inc. All rights reserved .
-module(rabbit_mgmt_wm_parameter).
-export([init/1, resource_exists/2, to_json/2,
content_types_provided/2, content_types_accepted/2,
is_authorized/2, allowed_methods/2, accept_content/2,
delete_resource/2]).
-import(rabbit_misc, [pget/2]).
-include("rabbit_mgmt.hrl").
-include_lib("webmachine/include/webmachine.hrl").
-include_lib("rabbit_common/include/rabbit.hrl").
init(_Config) -> {ok, #context{}}.
content_types_provided(ReqData, Context) ->
{[{"application/json", to_json}], ReqData, Context}.
content_types_accepted(ReqData, Context) ->
{[{"application/json", accept_content}], ReqData, Context}.
allowed_methods(ReqData, Context) ->
{['HEAD', 'GET', 'PUT', 'DELETE'], ReqData, Context}.
resource_exists(ReqData, Context) ->
{case parameter(ReqData) of
not_found -> false;
_ -> true
end, ReqData, Context}.
to_json(ReqData, Context) ->
rabbit_mgmt_util:reply(rabbit_mgmt_format:parameter(parameter(ReqData)),
ReqData, Context).
accept_content(ReqData, Context = #context{user = User}) ->
case rabbit_mgmt_util:vhost(ReqData) of
not_found ->
rabbit_mgmt_util:not_found(vhost_not_found, ReqData, Context);
VHost ->
rabbit_mgmt_util:with_decode(
[value], ReqData, Context,
fun([Value], _) ->
case rabbit_runtime_parameters:set(
VHost, component(ReqData), name(ReqData),
rabbit_misc:json_to_term(Value), User) of
ok ->
{true, ReqData, Context};
{error_string, Reason} ->
rabbit_mgmt_util:bad_request(
list_to_binary(Reason), ReqData, Context)
end
end)
end.
delete_resource(ReqData, Context) ->
ok = rabbit_runtime_parameters:clear(
rabbit_mgmt_util:vhost(ReqData), component(ReqData), name(ReqData)),
{true, ReqData, Context}.
is_authorized(ReqData, Context) ->
rabbit_mgmt_util:is_authorized_policies(ReqData, Context).
parameter(ReqData) ->
rabbit_runtime_parameters:lookup(
rabbit_mgmt_util:vhost(ReqData), component(ReqData), name(ReqData)).
component(ReqData) -> rabbit_mgmt_util:id(component, ReqData).
name(ReqData) -> rabbit_mgmt_util:id(name, ReqData).
|
63496a7256b7437f35138c0a77ccbec943aa4c291f02c8af6932685dc4c6e76f
|
CryptoKami/cryptokami-core
|
Addresses.hs
|
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TypeOperators #-}
module Cryptokami.Wallet.API.V1.Handlers.Addresses where
import Universum
import Pos.Crypto (emptyPassphrase)
import qualified Pos.Wallet.Web.Account as V0
import qualified Pos.Wallet.Web.Methods as V0
import Cryptokami.Wallet.API.Request
import Cryptokami.Wallet.API.Response
import qualified Cryptokami.Wallet.API.V1.Addresses as Addresses
import Cryptokami.Wallet.API.V1.Migration
import Cryptokami.Wallet.API.V1.Types
import Pos.Core (decodeTextAddress)
import Servant
import Test.QuickCheck (arbitrary, generate, vectorOf)
handlers
:: (MonadThrow m, V0.MonadWalletLogic ctx m)
=> ServerT Addresses.API m
handlers = listAddresses
:<|> newAddress
:<|> verifyAddress
listAddresses
:: MonadIO m
=> RequestParams -> m (WalletResponse [Address])
listAddresses RequestParams {..} = do
addresses <- liftIO $ generate (vectorOf 2 arbitrary)
return WalletResponse {
wrData = addresses
, wrStatus = SuccessStatus
, wrMeta = Metadata $ PaginationMetadata {
metaTotalPages = 1
, metaPage = 1
, metaPerPage = 20
, metaTotalEntries = 2
}
}
newAddress
:: (MonadThrow m, V0.MonadWalletLogic ctx m)
=> NewAddress -> m (WalletResponse WalletAddress)
newAddress NewAddress {..} = do
let password = fromMaybe emptyPassphrase newaddrSpendingPassword
accountId <- migrate (newaddrWalletId, newaddrAccountId)
fmap single $ V0.newAddress V0.RandomSeed password accountId
>>= migrate
-- | Verifies that an address is base58 decodable.
verifyAddress :: Monad m => Text -> m (WalletResponse AddressValidity)
verifyAddress address =
case decodeTextAddress address of
Right _ ->
return $ single $ AddressValidity True
Left _ ->
return $ single $ AddressValidity False
| null |
https://raw.githubusercontent.com/CryptoKami/cryptokami-core/12ca60a9ad167b6327397b3b2f928c19436ae114/wallet-new/server/Cryptokami/Wallet/API/V1/Handlers/Addresses.hs
|
haskell
|
# LANGUAGE OverloadedStrings #
# LANGUAGE TypeOperators #
| Verifies that an address is base58 decodable.
|
module Cryptokami.Wallet.API.V1.Handlers.Addresses where
import Universum
import Pos.Crypto (emptyPassphrase)
import qualified Pos.Wallet.Web.Account as V0
import qualified Pos.Wallet.Web.Methods as V0
import Cryptokami.Wallet.API.Request
import Cryptokami.Wallet.API.Response
import qualified Cryptokami.Wallet.API.V1.Addresses as Addresses
import Cryptokami.Wallet.API.V1.Migration
import Cryptokami.Wallet.API.V1.Types
import Pos.Core (decodeTextAddress)
import Servant
import Test.QuickCheck (arbitrary, generate, vectorOf)
handlers
:: (MonadThrow m, V0.MonadWalletLogic ctx m)
=> ServerT Addresses.API m
handlers = listAddresses
:<|> newAddress
:<|> verifyAddress
listAddresses
:: MonadIO m
=> RequestParams -> m (WalletResponse [Address])
listAddresses RequestParams {..} = do
addresses <- liftIO $ generate (vectorOf 2 arbitrary)
return WalletResponse {
wrData = addresses
, wrStatus = SuccessStatus
, wrMeta = Metadata $ PaginationMetadata {
metaTotalPages = 1
, metaPage = 1
, metaPerPage = 20
, metaTotalEntries = 2
}
}
newAddress
:: (MonadThrow m, V0.MonadWalletLogic ctx m)
=> NewAddress -> m (WalletResponse WalletAddress)
newAddress NewAddress {..} = do
let password = fromMaybe emptyPassphrase newaddrSpendingPassword
accountId <- migrate (newaddrWalletId, newaddrAccountId)
fmap single $ V0.newAddress V0.RandomSeed password accountId
>>= migrate
verifyAddress :: Monad m => Text -> m (WalletResponse AddressValidity)
verifyAddress address =
case decodeTextAddress address of
Right _ ->
return $ single $ AddressValidity True
Left _ ->
return $ single $ AddressValidity False
|
19de4d317a1133af2ea5f99272fb68414e28375dd75d8d5f59998c450757a76a
|
noinia/hgeometry
|
DivideAndConquer.hs
|
# LANGUAGE ScopedTypeVariables #
--------------------------------------------------------------------------------
-- |
Module : Algorithms . Geometry . ClosestPair . DivideAndConquer
Copyright : ( C )
-- License : see the LICENSE file
Maintainer :
--
Classical \(O(n\log n)\ ) time divide and conquer algorithm to compute the
-- closest pair among a set of \(n\) points in \(\mathbb{R}^2\).
--
--------------------------------------------------------------------------------
module Algorithms.Geometry.ClosestPair.DivideAndConquer( closestPair
, CP
, CCP(..)
, mergePairs
)
where
import Algorithms.DivideAndConquer
import Control.Lens
import Data.Ext
import Geometry.Point
import Data.LSeq (LSeq)
import qualified Data.LSeq as LSeq
import qualified Data.List as List
import Data.List.NonEmpty (NonEmpty(..))
import qualified Data.List.NonEmpty as NonEmpty
import Data.Ord (comparing)
import Data.Semigroup.Foldable (toNonEmpty)
import Data.UnBounded
import Data.Util
--------------------------------------------------------------------------------
-- | Classical divide and conquer algorithm to compute the closest pair among
-- \(n\) points.
--
-- running time: \(O(n \log n)\)
closestPair :: (Ord r, Num r) => LSeq 2 (Point 2 r :+ p) -> Two (Point 2 r :+ p)
closestPair = f . divideAndConquer1 mkCCP . toNonEmpty
. LSeq.unstableSortBy (comparing (^.core))
where
mkCCP p = CCP (p :| []) Top
f = \case
CCP _ (ValT (SP cp _)) -> cp
CCP _ Top -> error "closestPair: absurd."
-- | the closest pair and its (squared) distance
type CP q r = Top (SP (Two q) r)
-- | Type used in the closest pair computation. The fields represent the points
-- ordered on increasing y-order and the closest pair (if we know it)
data CCP p r = CCP (NonEmpty (Point 2 r :+ p))
!(CP (Point 2 r :+ p) r)
deriving (Show,Eq)
instance (Num r, Ord r) => Semigroup (CCP p r) where
(CCP ptsl cpl) <> (CCP ptsr cpr) = CCP (mergeSortedBy cmp ptsl ptsr)
(mergePairs (minBy getDist cpl cpr) ptsl ptsr)
where
compare on y first then on x
cmp :: Point 2 r :+ p -> Point 2 r :+ p -> Ordering
cmp p q = comparing (^.core.yCoord) p q <> comparing (^.core.xCoord) p q
-- | Function that does the actual merging work
mergePairs :: forall p r. (Ord r, Num r)
=> CP (Point 2 r :+ p) r -- ^ current closest pair and its dist
-> NonEmpty (Point 2 r :+ p) -- ^ pts on the left
-> NonEmpty (Point 2 r :+ p) -- ^ pts on the right
-> CP (Point 2 r :+ p) r
mergePairs cp' ls' rs' = go cp' (NonEmpty.toList ls') (NonEmpty.toList rs')
where
-- scan through the points on the right in increasing order.
go :: CP (Point 2 r :+ p) r -> [Point 2 r :+ p] -> [Point 2 r :+ p]
-> CP (Point 2 r :+ p) r
go cp _ [] = cp
go cp ls (r:rs) = let ls'' = trim (getDist cp) ls r
try to find a new closer pair with r.
in go cp'' ls'' rs -- and then process the remaining points
-- | ditch the points on the left that are too low anyway
trim :: (Ord r, Num r)
=> Top r -> [Point 2 r :+ q] -> Point 2 r :+ a
-> [Point 2 r :+ q]
trim (ValT d) ls r = List.dropWhile (\l -> sqVertDist l r > d) ls
trim _ ls _ = ls
-- | the squared vertical distance (in case r lies above l) or 0 otherwise
sqVertDist :: (Ord r, Num r) => Point 2 r :+ p -> Point 2 r :+ q -> r
sqVertDist l r = let d = 0 `max` (r^.core.yCoord - l^.core.yCoord) in d*d
| try and find a new closest pair with r. If we get to points that are too
-- far above r we stop (since none of those points will be closer to r anyway)
run :: (Ord r, Num r)
=> CP (Point 2 r :+ p) r -> Point 2 r :+ p -> [Point 2 r :+ p]
-> CP (Point 2 r :+ p) r
run cp'' r ls =
runWhile cp'' ls
(\cp l -> ValT (sqVertDist r l) < getDist cp) -- r and l inverted
-- by design
(\cp l -> minBy getDist cp (ValT $ SP (Two l r) (dist l r)))
where
dist (p :+ _) (q :+ _) = squaredEuclideanDist p q
-- | Given some function that decides when to keep things while maintaining some state.
runWhile :: s -> [a] -> (s -> a -> Bool) -> (s -> a -> s) -> s
runWhile s' ys p f = go s' ys
where
go s [] = s
go s (x:xs) | p s x = go (f s x) xs -- continue with new state
| otherwise = s -- stop, return the current state
-- | returns the minimum element according to some function.
minBy :: Ord b => (a -> b) -> a -> a -> a
minBy f a b | f a < f b = a
| otherwise = b
-- | Get the distance of a (candidate) closest pair
getDist :: CP a r -> Top r
getDist = fmap (view _2)
test4 = [ Point2 ( 479109173120836 % 8353334321025 ) ( 5100576283797 % 96072829279 ) : + ( )
, Point2 ( 58405408826671 % 1010204299645 ) ( 416491493323834 % 7859181827347 ) : + ( )
, Point2 ( 497723773632392 % 8797511756605 ) ( 484251118551575 % 9452820868018 ) : + ( )
, Point2 ( 71823625388220 % 1256943286753 ) ( 211467894699900 % 3952412568913 ) : + ( )
-- ]
myTree = asBalancedBinLeafTree . LSeq.toNonEmpty . LSeq.promise . ( comparing ( ^.core ) ) . LSeq.fromList $ test4
myTree2 = let mkCCP ( Elem p ) = CCP ( p :| [ ] ) Top in mkCCP < $ > myTree
ans2p = Point2 ( 479109173120836 % 8353334321025 ) ( 5100576283797 % 96072829279 )
ans2q = Point2 ( 71823625388220 % 1256943286753 ) ( 211467894699900 % 3952412568913 )
temp = Two ( test4 ! ! 1 ) ( test4 ! ! 0 )
-- tempX = ValT (SP temp $ squaredEuclideanDist (temp^._1.core) (temp^._2.core))
| null |
https://raw.githubusercontent.com/noinia/hgeometry/89cd3d3109ec68f877bf8e34dc34b6df337a4ec1/hgeometry/src/Algorithms/Geometry/ClosestPair/DivideAndConquer.hs
|
haskell
|
------------------------------------------------------------------------------
|
License : see the LICENSE file
closest pair among a set of \(n\) points in \(\mathbb{R}^2\).
------------------------------------------------------------------------------
------------------------------------------------------------------------------
| Classical divide and conquer algorithm to compute the closest pair among
\(n\) points.
running time: \(O(n \log n)\)
| the closest pair and its (squared) distance
| Type used in the closest pair computation. The fields represent the points
ordered on increasing y-order and the closest pair (if we know it)
| Function that does the actual merging work
^ current closest pair and its dist
^ pts on the left
^ pts on the right
scan through the points on the right in increasing order.
and then process the remaining points
| ditch the points on the left that are too low anyway
| the squared vertical distance (in case r lies above l) or 0 otherwise
far above r we stop (since none of those points will be closer to r anyway)
r and l inverted
by design
| Given some function that decides when to keep things while maintaining some state.
continue with new state
stop, return the current state
| returns the minimum element according to some function.
| Get the distance of a (candidate) closest pair
]
tempX = ValT (SP temp $ squaredEuclideanDist (temp^._1.core) (temp^._2.core))
|
# LANGUAGE ScopedTypeVariables #
Module : Algorithms . Geometry . ClosestPair . DivideAndConquer
Copyright : ( C )
Maintainer :
Classical \(O(n\log n)\ ) time divide and conquer algorithm to compute the
module Algorithms.Geometry.ClosestPair.DivideAndConquer( closestPair
, CP
, CCP(..)
, mergePairs
)
where
import Algorithms.DivideAndConquer
import Control.Lens
import Data.Ext
import Geometry.Point
import Data.LSeq (LSeq)
import qualified Data.LSeq as LSeq
import qualified Data.List as List
import Data.List.NonEmpty (NonEmpty(..))
import qualified Data.List.NonEmpty as NonEmpty
import Data.Ord (comparing)
import Data.Semigroup.Foldable (toNonEmpty)
import Data.UnBounded
import Data.Util
closestPair :: (Ord r, Num r) => LSeq 2 (Point 2 r :+ p) -> Two (Point 2 r :+ p)
closestPair = f . divideAndConquer1 mkCCP . toNonEmpty
. LSeq.unstableSortBy (comparing (^.core))
where
mkCCP p = CCP (p :| []) Top
f = \case
CCP _ (ValT (SP cp _)) -> cp
CCP _ Top -> error "closestPair: absurd."
type CP q r = Top (SP (Two q) r)
data CCP p r = CCP (NonEmpty (Point 2 r :+ p))
!(CP (Point 2 r :+ p) r)
deriving (Show,Eq)
instance (Num r, Ord r) => Semigroup (CCP p r) where
(CCP ptsl cpl) <> (CCP ptsr cpr) = CCP (mergeSortedBy cmp ptsl ptsr)
(mergePairs (minBy getDist cpl cpr) ptsl ptsr)
where
compare on y first then on x
cmp :: Point 2 r :+ p -> Point 2 r :+ p -> Ordering
cmp p q = comparing (^.core.yCoord) p q <> comparing (^.core.xCoord) p q
mergePairs :: forall p r. (Ord r, Num r)
-> CP (Point 2 r :+ p) r
mergePairs cp' ls' rs' = go cp' (NonEmpty.toList ls') (NonEmpty.toList rs')
where
go :: CP (Point 2 r :+ p) r -> [Point 2 r :+ p] -> [Point 2 r :+ p]
-> CP (Point 2 r :+ p) r
go cp _ [] = cp
go cp ls (r:rs) = let ls'' = trim (getDist cp) ls r
try to find a new closer pair with r.
trim :: (Ord r, Num r)
=> Top r -> [Point 2 r :+ q] -> Point 2 r :+ a
-> [Point 2 r :+ q]
trim (ValT d) ls r = List.dropWhile (\l -> sqVertDist l r > d) ls
trim _ ls _ = ls
sqVertDist :: (Ord r, Num r) => Point 2 r :+ p -> Point 2 r :+ q -> r
sqVertDist l r = let d = 0 `max` (r^.core.yCoord - l^.core.yCoord) in d*d
| try and find a new closest pair with r. If we get to points that are too
run :: (Ord r, Num r)
=> CP (Point 2 r :+ p) r -> Point 2 r :+ p -> [Point 2 r :+ p]
-> CP (Point 2 r :+ p) r
run cp'' r ls =
runWhile cp'' ls
(\cp l -> minBy getDist cp (ValT $ SP (Two l r) (dist l r)))
where
dist (p :+ _) (q :+ _) = squaredEuclideanDist p q
runWhile :: s -> [a] -> (s -> a -> Bool) -> (s -> a -> s) -> s
runWhile s' ys p f = go s' ys
where
go s [] = s
minBy :: Ord b => (a -> b) -> a -> a -> a
minBy f a b | f a < f b = a
| otherwise = b
getDist :: CP a r -> Top r
getDist = fmap (view _2)
test4 = [ Point2 ( 479109173120836 % 8353334321025 ) ( 5100576283797 % 96072829279 ) : + ( )
, Point2 ( 58405408826671 % 1010204299645 ) ( 416491493323834 % 7859181827347 ) : + ( )
, Point2 ( 497723773632392 % 8797511756605 ) ( 484251118551575 % 9452820868018 ) : + ( )
, Point2 ( 71823625388220 % 1256943286753 ) ( 211467894699900 % 3952412568913 ) : + ( )
myTree = asBalancedBinLeafTree . LSeq.toNonEmpty . LSeq.promise . ( comparing ( ^.core ) ) . LSeq.fromList $ test4
myTree2 = let mkCCP ( Elem p ) = CCP ( p :| [ ] ) Top in mkCCP < $ > myTree
ans2p = Point2 ( 479109173120836 % 8353334321025 ) ( 5100576283797 % 96072829279 )
ans2q = Point2 ( 71823625388220 % 1256943286753 ) ( 211467894699900 % 3952412568913 )
temp = Two ( test4 ! ! 1 ) ( test4 ! ! 0 )
|
c5641e7efb52ad008e66c89170a698b2df41ff42833dd8371533d15257603863
|
mixphix/toolbox
|
Toolbox.hs
|
# LANGUAGE TypeApplications #
-- |
Module : Control . . Toolbox
Copyright : ( c ) 2021
-- License : BSD3 (see the file LICENSE)
-- Maintainer :
--
Utility functions on top of ' Control . Applicative ' and ' Control . ' .
--
This module re - exports the above modules , so modules need only import ' Control . . Toolbox ' .
module Control.Monad.Toolbox (
-- * Functorial operators
(<<$>>),
-- * Applicative operators
guarded,
* * Booleans
ifA,
(<&&>),
(<||>),
-- ** Lifted eliminators
maybeA,
fromMaybeA,
eitherA,
-- * Monad operators
* * Booleans
ifM,
(&^&),
(|^|),
-- ** Lifted eliminators
maybeM,
fromMaybeM,
eitherM,
* * Monad utilities
whenM,
unlessM,
whenJust,
whenJustM,
-- ** Looping
whileM,
loop,
loopM,
-- * Re-exports
module Control.Monad,
module Control.Applicative,
module Data.Functor,
) where
import Control.Applicative
import Control.Monad
import Data.Bool (bool)
import Data.Function (fix)
import Data.Functor
import Data.Functor.Identity (Identity (..))
import Data.Maybe (fromMaybe)
| Apply a pure function through two functors instead of one .
(<<$>>) :: (Functor g, Functor f) => (a -> b) -> g (f a) -> g (f b)
f <<$>> gfa = fmap (fmap f) gfa
| A version of @if ... then ... else@ over an ' Applicative ' functor . Does not short - circuit !
--
If you need short - circuiting and have a ' Monad ' constraint , use ' ifM ' .
--
-- > ifA (Just False) (Just 1) Nothing == Nothing
> ifA ( Just True ) ( Just 1 ) Nothing = = Just 1
-- > ifA (Just True) (Just 1) (Just undefined) == undefined
ifA :: (Applicative f) => f Bool -> f a -> f a -> f a
ifA test t f = bool <$> f <*> t <*> test
infixr 3 <&&>
-- | A version of '(&&)' over an @Applicative functor. Does not short-circuit!
--
If you need short - circuiting and have a ' Monad ' constraint , use ' ( & ^ & ) ' .
--
> Just True < & & > Just False = = Just False
> Just False < & & > Just undefined = = undefined
(<&&>) :: (Applicative f) => f Bool -> f Bool -> f Bool
(<&&>) = liftA2 (&&)
infixr 2 <||>
-- | A version of '(||)' over an @Applicative functor. Does not short-circuit!
--
If you need short - circuiting and have a ' Monad ' constraint , use ' ( |^| ) ' .
--
-- > Just True <||> Just False == Just True
-- > Just True <||> Just undefined == undefined
(<||>) :: (Applicative f) => f Bool -> f Bool -> f Bool
(<||>) = liftA2 (||)
| A version of @if ... then ... else@ over a ' Monad ' . Short - circuits if the ' Bool ' is true .
--
-- > ifM (Just False) (Just 1) (Just 0) == Just 0
> ifM ( Just True ) ( Just 1 ) ( Just 0 ) = = Just 1
> ifM ( Just True ) ( Just 1 ) ( Just undefined ) = = Just 1
ifM :: (Monad m) => m Bool -> m a -> m a -> m a
ifM test t f = bool f t =<< test
infixr 3 &^&
| A version of ' ( & & ) ' over a ' Monad ' . Short - circuits if the first argument is ' False ' .
--
-- > Just True &^& Just False == Just False
-- > Just False &^& Just undefined == Just False
(&^&) :: (Monad m) => m Bool -> m Bool -> m Bool
ma &^& mb = ifM ma mb (pure False)
infixr 2 |^|
| A version of ' ( & & ) ' over a ' Monad ' . Short - circuits if the first argument is ' True ' .
--
-- > Just True |^| Just False == Just True
-- > Just True |^| Just undefined == Just True
(|^|) :: (Monad m) => m Bool -> m Bool -> m Bool
ma |^| mb = ifM ma (pure True) mb
-- | A version of 'when' where the test can be inside the 'Monad'.
--
-- > whenM [True] [(), (), ()] == [(), (), ()]
-- > whenM [False] [(), (), ()] == [()]
whenM :: (Monad m) => m Bool -> m () -> m ()
whenM test act = ifM test act (pure ())
-- | A version of 'unless' where the test can be inside the 'Monad'.
--
-- > unlessM [True] [(), (), ()] == [()]
-- > unlessM [False] [(), (), ()] == [(), (), ()]
unlessM :: (Monad m) => m Bool -> m () -> m ()
unlessM test act = ifM (not <$> test) act (pure ())
-- | A version of 'when' that does nothing when given 'Nothing', and provides access
-- to the wrapped value otherwise.
--
> whenJust ( Just 5 ) ( \ _ - > [ ( ) , ( ) , ( ) ] ) = = [ ( ) , ( ) , ( ) ]
-- > whenJust Nothing (\_ -> [(), (), ()]) == [()]
whenJust :: (Monad m) => Maybe a -> (a -> m ()) -> m ()
whenJust = flip $ maybe (pure ())
-- | A combination of 'whenM' and 'whenJust'.
whenJustM :: (Monad m) => m (Maybe a) -> (a -> m ()) -> m ()
whenJustM = flip $ maybeM (pure ())
-- | A version of 'guard' that provides a value if the condition is met, or 'empty' otherwise.
--
-- > guarded @Maybe False 1 == Nothing
> guarded @Maybe True 1 = = Just 1
guarded :: (Alternative f) => Bool -> a -> f a
guarded b = if b then pure else const empty
-- | A version of 'maybe' that works over an 'Applicative' functor.
Note the type of the " just " parameter is the same as the first parameter of ' ( < * > ) ' .
--
> maybeA [ 0 ] [ \x - > x + 1 , \x - > x + 2 ] [ Just 2 ] = = [ 3 , 4 ]
> maybeA [ 0 ] [ \x - > x + 1 , \x - > x + 2 ] [ Nothing ] = = [ 0 ]
maybeA :: (Applicative f) => f b -> f (a -> b) -> f (Maybe a) -> f b
maybeA noth just may = maybe <$> noth <*> just <*> may
-- | A version of 'fromMaybe' that works over an 'Applicative' functor.
--
> fromMaybeA [ 0 ] [ Just 5 ] = = [ 5 ]
-- > fromMaybeA [0] [Nothing] == [0]
fromMaybeA :: (Applicative f) => f a -> f (Maybe a) -> f a
fromMaybeA = liftA2 fromMaybe
-- | A version of 'maybe' that works over a 'Monad'.
--
> maybeM [ 0 ] ( \x - > [ x + 1 , x + 2 ] ) [ Just 2 ] = = [ 3 , 4 ]
> maybeM [ 0 ] ( \x - > [ x + 1 , x + 2 ] ) [ Nothing ] = = [ 0 ]
maybeM :: (Monad m) => m b -> (a -> m b) -> m (Maybe a) -> m b
maybeM noth just may = maybe noth just =<< may
-- | A restriction of 'fromMaybeA' to a 'Monad'.
fromMaybeM :: (Monad m) => m a -> m (Maybe a) -> m a
fromMaybeM = fromMaybeA
-- | A version of 'either' that works over an 'Applicative' functor.
--
> eitherA ( ZipList [ pred , ( +3 ) ] ) ( ZipList [ succ , ( * 2 ) ] ) ( ZipList [ Left 5 , Right 10 ] ) = = ZipList { getZipList = [ 4,20 ] }
> eitherA [ pred , ( +3 ) ] [ succ , ( * 2 ) ] [ Left 5 , Right 10 ] = = [ 4,11,4,20,8,11,8,20 ] -- FOIL
> eitherA [ pred , ( +3 ) ] [ ] [ Left 5 , Right 10 ] = = [ ]
> eitherA ( Just pred ) ( Just succ ) ( Just ( Left 6 ) ) = = Just 5
> eitherA ( Just pred ) ( Just succ ) ( Just ( Right 6 ) ) = = Just 7
-- > eitherA (Just pred) (Just succ) (Nothing :: Maybe (Either Int Int)) == Nothing
> eitherA ( Just pred ) Nothing ( Just ( Left 6 ) ) = = Nothing
-- > eitherA Nothing (Just succ) (Just (Right 6)) == Nothing
eitherA :: (Applicative f) => f (a -> c) -> f (b -> c) -> f (Either a b) -> f c
eitherA = liftA3 either
-- | A version of 'either' that works over a 'Monad'.
--
> eitherM ( \a - > [ pred a , a + 3 ] ) ( \b - > [ succ b , b * 2 ] ) [ Left 5 , Right 10 ] = = [ 4,8,11,20 ]
> eitherM ( \ _ - > Nothing ) ( \b - > Just ( b + 2 ) ) Nothing = = Nothing
> eitherM ( \ _ - > Nothing ) ( \b - > Just ( b + 2 ) ) ( Just ( Left 5 ) ) = = Nothing
> eitherM ( \ _ - > Nothing ) ( \b - > Just ( b + 2 ) ) ( Just ( Right 5 ) ) = = Just 7
eitherM :: (Monad m) => (a -> m c) -> (b -> m c) -> m (Either a b) -> m c
eitherM lft rgt eab = either lft rgt =<< eab
-- | Run a monadic computation until its value becomes 'False'.
--
> execState ( while ( do { n < - get ; if n < 10 then True < $ put ( n + 1 ) else pure False } : : State Int Bool ) ) 0 = = 10
whileM :: (Monad m) => m Bool -> m ()
whileM = fix (whenM <*>)
-- | Run a monadic computation until its value becomes 'Right'.
--
> loopM @Identity ( \a - > if a < 0 then pure ( Right a ) else pure ( Left $ pred a ) ) 20 = = -1
loopM :: (Monad m) => (a -> m (Either a b)) -> a -> m b
loopM comp = eitherM (loopM comp) pure . comp
-- | Loop a computation using 'Left' values as seeds for the next iteration.
--
> loop ( \a - > if a < 0 then Right a else Left ( pred a ) ) 20 = = -1
loop :: (a -> Either a b) -> a -> b
loop f = runIdentity . loopM (Identity . f)
| null |
https://raw.githubusercontent.com/mixphix/toolbox/4136a8e4e2799679825a05aee49e2f21a4715c26/src/Control/Monad/Toolbox.hs
|
haskell
|
|
License : BSD3 (see the file LICENSE)
Maintainer :
* Functorial operators
* Applicative operators
** Lifted eliminators
* Monad operators
** Lifted eliminators
** Looping
* Re-exports
> ifA (Just False) (Just 1) Nothing == Nothing
> ifA (Just True) (Just 1) (Just undefined) == undefined
| A version of '(&&)' over an @Applicative functor. Does not short-circuit!
| A version of '(||)' over an @Applicative functor. Does not short-circuit!
> Just True <||> Just False == Just True
> Just True <||> Just undefined == undefined
> ifM (Just False) (Just 1) (Just 0) == Just 0
> Just True &^& Just False == Just False
> Just False &^& Just undefined == Just False
> Just True |^| Just False == Just True
> Just True |^| Just undefined == Just True
| A version of 'when' where the test can be inside the 'Monad'.
> whenM [True] [(), (), ()] == [(), (), ()]
> whenM [False] [(), (), ()] == [()]
| A version of 'unless' where the test can be inside the 'Monad'.
> unlessM [True] [(), (), ()] == [()]
> unlessM [False] [(), (), ()] == [(), (), ()]
| A version of 'when' that does nothing when given 'Nothing', and provides access
to the wrapped value otherwise.
> whenJust Nothing (\_ -> [(), (), ()]) == [()]
| A combination of 'whenM' and 'whenJust'.
| A version of 'guard' that provides a value if the condition is met, or 'empty' otherwise.
> guarded @Maybe False 1 == Nothing
| A version of 'maybe' that works over an 'Applicative' functor.
| A version of 'fromMaybe' that works over an 'Applicative' functor.
> fromMaybeA [0] [Nothing] == [0]
| A version of 'maybe' that works over a 'Monad'.
| A restriction of 'fromMaybeA' to a 'Monad'.
| A version of 'either' that works over an 'Applicative' functor.
FOIL
> eitherA (Just pred) (Just succ) (Nothing :: Maybe (Either Int Int)) == Nothing
> eitherA Nothing (Just succ) (Just (Right 6)) == Nothing
| A version of 'either' that works over a 'Monad'.
| Run a monadic computation until its value becomes 'False'.
| Run a monadic computation until its value becomes 'Right'.
| Loop a computation using 'Left' values as seeds for the next iteration.
|
# LANGUAGE TypeApplications #
Module : Control . . Toolbox
Copyright : ( c ) 2021
Utility functions on top of ' Control . Applicative ' and ' Control . ' .
This module re - exports the above modules , so modules need only import ' Control . . Toolbox ' .
module Control.Monad.Toolbox (
(<<$>>),
guarded,
* * Booleans
ifA,
(<&&>),
(<||>),
maybeA,
fromMaybeA,
eitherA,
* * Booleans
ifM,
(&^&),
(|^|),
maybeM,
fromMaybeM,
eitherM,
* * Monad utilities
whenM,
unlessM,
whenJust,
whenJustM,
whileM,
loop,
loopM,
module Control.Monad,
module Control.Applicative,
module Data.Functor,
) where
import Control.Applicative
import Control.Monad
import Data.Bool (bool)
import Data.Function (fix)
import Data.Functor
import Data.Functor.Identity (Identity (..))
import Data.Maybe (fromMaybe)
| Apply a pure function through two functors instead of one .
(<<$>>) :: (Functor g, Functor f) => (a -> b) -> g (f a) -> g (f b)
f <<$>> gfa = fmap (fmap f) gfa
| A version of @if ... then ... else@ over an ' Applicative ' functor . Does not short - circuit !
If you need short - circuiting and have a ' Monad ' constraint , use ' ifM ' .
> ifA ( Just True ) ( Just 1 ) Nothing = = Just 1
ifA :: (Applicative f) => f Bool -> f a -> f a -> f a
ifA test t f = bool <$> f <*> t <*> test
infixr 3 <&&>
If you need short - circuiting and have a ' Monad ' constraint , use ' ( & ^ & ) ' .
> Just True < & & > Just False = = Just False
> Just False < & & > Just undefined = = undefined
(<&&>) :: (Applicative f) => f Bool -> f Bool -> f Bool
(<&&>) = liftA2 (&&)
infixr 2 <||>
If you need short - circuiting and have a ' Monad ' constraint , use ' ( |^| ) ' .
(<||>) :: (Applicative f) => f Bool -> f Bool -> f Bool
(<||>) = liftA2 (||)
| A version of @if ... then ... else@ over a ' Monad ' . Short - circuits if the ' Bool ' is true .
> ifM ( Just True ) ( Just 1 ) ( Just 0 ) = = Just 1
> ifM ( Just True ) ( Just 1 ) ( Just undefined ) = = Just 1
ifM :: (Monad m) => m Bool -> m a -> m a -> m a
ifM test t f = bool f t =<< test
infixr 3 &^&
| A version of ' ( & & ) ' over a ' Monad ' . Short - circuits if the first argument is ' False ' .
(&^&) :: (Monad m) => m Bool -> m Bool -> m Bool
ma &^& mb = ifM ma mb (pure False)
infixr 2 |^|
| A version of ' ( & & ) ' over a ' Monad ' . Short - circuits if the first argument is ' True ' .
(|^|) :: (Monad m) => m Bool -> m Bool -> m Bool
ma |^| mb = ifM ma (pure True) mb
whenM :: (Monad m) => m Bool -> m () -> m ()
whenM test act = ifM test act (pure ())
unlessM :: (Monad m) => m Bool -> m () -> m ()
unlessM test act = ifM (not <$> test) act (pure ())
> whenJust ( Just 5 ) ( \ _ - > [ ( ) , ( ) , ( ) ] ) = = [ ( ) , ( ) , ( ) ]
whenJust :: (Monad m) => Maybe a -> (a -> m ()) -> m ()
whenJust = flip $ maybe (pure ())
whenJustM :: (Monad m) => m (Maybe a) -> (a -> m ()) -> m ()
whenJustM = flip $ maybeM (pure ())
> guarded @Maybe True 1 = = Just 1
guarded :: (Alternative f) => Bool -> a -> f a
guarded b = if b then pure else const empty
Note the type of the " just " parameter is the same as the first parameter of ' ( < * > ) ' .
> maybeA [ 0 ] [ \x - > x + 1 , \x - > x + 2 ] [ Just 2 ] = = [ 3 , 4 ]
> maybeA [ 0 ] [ \x - > x + 1 , \x - > x + 2 ] [ Nothing ] = = [ 0 ]
maybeA :: (Applicative f) => f b -> f (a -> b) -> f (Maybe a) -> f b
maybeA noth just may = maybe <$> noth <*> just <*> may
> fromMaybeA [ 0 ] [ Just 5 ] = = [ 5 ]
fromMaybeA :: (Applicative f) => f a -> f (Maybe a) -> f a
fromMaybeA = liftA2 fromMaybe
> maybeM [ 0 ] ( \x - > [ x + 1 , x + 2 ] ) [ Just 2 ] = = [ 3 , 4 ]
> maybeM [ 0 ] ( \x - > [ x + 1 , x + 2 ] ) [ Nothing ] = = [ 0 ]
maybeM :: (Monad m) => m b -> (a -> m b) -> m (Maybe a) -> m b
maybeM noth just may = maybe noth just =<< may
fromMaybeM :: (Monad m) => m a -> m (Maybe a) -> m a
fromMaybeM = fromMaybeA
> eitherA ( ZipList [ pred , ( +3 ) ] ) ( ZipList [ succ , ( * 2 ) ] ) ( ZipList [ Left 5 , Right 10 ] ) = = ZipList { getZipList = [ 4,20 ] }
> eitherA [ pred , ( +3 ) ] [ ] [ Left 5 , Right 10 ] = = [ ]
> eitherA ( Just pred ) ( Just succ ) ( Just ( Left 6 ) ) = = Just 5
> eitherA ( Just pred ) ( Just succ ) ( Just ( Right 6 ) ) = = Just 7
> eitherA ( Just pred ) Nothing ( Just ( Left 6 ) ) = = Nothing
eitherA :: (Applicative f) => f (a -> c) -> f (b -> c) -> f (Either a b) -> f c
eitherA = liftA3 either
> eitherM ( \a - > [ pred a , a + 3 ] ) ( \b - > [ succ b , b * 2 ] ) [ Left 5 , Right 10 ] = = [ 4,8,11,20 ]
> eitherM ( \ _ - > Nothing ) ( \b - > Just ( b + 2 ) ) Nothing = = Nothing
> eitherM ( \ _ - > Nothing ) ( \b - > Just ( b + 2 ) ) ( Just ( Left 5 ) ) = = Nothing
> eitherM ( \ _ - > Nothing ) ( \b - > Just ( b + 2 ) ) ( Just ( Right 5 ) ) = = Just 7
eitherM :: (Monad m) => (a -> m c) -> (b -> m c) -> m (Either a b) -> m c
eitherM lft rgt eab = either lft rgt =<< eab
> execState ( while ( do { n < - get ; if n < 10 then True < $ put ( n + 1 ) else pure False } : : State Int Bool ) ) 0 = = 10
whileM :: (Monad m) => m Bool -> m ()
whileM = fix (whenM <*>)
> loopM @Identity ( \a - > if a < 0 then pure ( Right a ) else pure ( Left $ pred a ) ) 20 = = -1
loopM :: (Monad m) => (a -> m (Either a b)) -> a -> m b
loopM comp = eitherM (loopM comp) pure . comp
> loop ( \a - > if a < 0 then Right a else Left ( pred a ) ) 20 = = -1
loop :: (a -> Either a b) -> a -> b
loop f = runIdentity . loopM (Identity . f)
|
80c321c979b3a8066b7d06fe4184f74154045223bba2a2199a59385af381d679
|
logicmoo/logicmoo_nlu
|
patrgram.lsp
|
;;; % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % %
% Example code from the book " Natural Language Processing in LISP " %
% published by %
% Copyright ( c ) 1989 , . %
;;; % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % %
;;;
;;; patrgram.lsp [Chapter 7] simple PATR grammar
(setq rules
'((Rule (S -> NP VP)
(S cat) = S
(NP cat) = NP
(VP cat) = VP
(S slash) = (VP slash)
(NP slash) = 0)
(Rule (VP -> V X)
(VP cat) = VP
(V cat) = V
(V arg1) = (X cat)
(V slash) = 0
(VP slash) = (X slash))
(Rule (PP -> P X)
(PP cat) = PP
(P cat) = P
(P arg1) = (X cat)
(P slash) = 0
(PP slash) = (X slash))
( Rule ( > X1 C X2 )
( ) = ( X1 cat )
( ) = ( X2 cat )
;;; (C cat) = C
( C slash ) = 0
( slash ) = ( X1 slash )
( slash ) = ( X2 slash )
( ) = ( X1 arg1 )
( ) = ( X2 arg1 ) )
(Rule (S -> X1 X2)
(S cat) = S
(S slash) = 0
(X1 slash) = 0
(X1 empty) = no
(X2 cat) = S
(X2 slash) = (X1 cat)
(X2 empty) = no)
(Rule (X0 -> )
(X0 cat) = (X0 slash)
(X0 empty) = yes)
))
(setq lexical_rules
'((Word (approved)
(cat) = V
(slash) = 0
(arg1) = PP)
(Word (disapproved)
(cat) = V
(slash) = 0
(arg1) = PP)
(Word (appeared)
(cat) = V
(slash) = 0
(arg1) = AP)
(Word (seemed)
(cat) = V
(slash) = 0
(arg1) = AP)
(Word (had)
(cat) = V
(slash) = 0
(arg1) = VP)
(Word (believed)
(cat) = V
(slash) = 0
(arg1) = S)
(Word (thought)
(cat) = V
(slash) = 0
(arg1) = S)
(Word (of)
(cat) = P
(slash) = 0
(arg1) = NP)
(Word (fit)
(slash) = 0
(cat) = AP)
(Word (competent)
(slash) = 0
(cat) = AP)
(Word (well - qualified)
(slash) = 0
(cat) = AP)
(Word (Dr Chan)
(slash) = 0
(cat) = NP)
(Word (nurses)
(slash) = 0
(cat) = NP)
(Word (MediCenter)
(slash) = 0
(cat) = NP)
(Word (patients)
(slash) = 0
(cat) = NP)
(Word (died)
(arg1) = 0
(slash) = 0
(cat) = V)
(Word (employed)
(arg1) = NP
(slash) = 0
(cat) = V)))
(defun category (d subst)
(let (
(cat (find_feature_value 'cat d subst))
(slash (find_feature_value 'slash d subst)))
(if (equal slash 0)
cat
(list cat '/ slash))))
(defun tree (cat subtrees)
(cons cat subtrees))
| null |
https://raw.githubusercontent.com/logicmoo/logicmoo_nlu/c066897f55b3ff45aa9155ebcf799fda9741bf74/ext/nlp_book/lisp/patrgram.lsp
|
lisp
|
% % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % %
% % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % %
patrgram.lsp [Chapter 7] simple PATR grammar
(C cat) = C
|
% Example code from the book " Natural Language Processing in LISP " %
% published by %
% Copyright ( c ) 1989 , . %
(setq rules
'((Rule (S -> NP VP)
(S cat) = S
(NP cat) = NP
(VP cat) = VP
(S slash) = (VP slash)
(NP slash) = 0)
(Rule (VP -> V X)
(VP cat) = VP
(V cat) = V
(V arg1) = (X cat)
(V slash) = 0
(VP slash) = (X slash))
(Rule (PP -> P X)
(PP cat) = PP
(P cat) = P
(P arg1) = (X cat)
(P slash) = 0
(PP slash) = (X slash))
( Rule ( > X1 C X2 )
( ) = ( X1 cat )
( ) = ( X2 cat )
( C slash ) = 0
( slash ) = ( X1 slash )
( slash ) = ( X2 slash )
( ) = ( X1 arg1 )
( ) = ( X2 arg1 ) )
(Rule (S -> X1 X2)
(S cat) = S
(S slash) = 0
(X1 slash) = 0
(X1 empty) = no
(X2 cat) = S
(X2 slash) = (X1 cat)
(X2 empty) = no)
(Rule (X0 -> )
(X0 cat) = (X0 slash)
(X0 empty) = yes)
))
(setq lexical_rules
'((Word (approved)
(cat) = V
(slash) = 0
(arg1) = PP)
(Word (disapproved)
(cat) = V
(slash) = 0
(arg1) = PP)
(Word (appeared)
(cat) = V
(slash) = 0
(arg1) = AP)
(Word (seemed)
(cat) = V
(slash) = 0
(arg1) = AP)
(Word (had)
(cat) = V
(slash) = 0
(arg1) = VP)
(Word (believed)
(cat) = V
(slash) = 0
(arg1) = S)
(Word (thought)
(cat) = V
(slash) = 0
(arg1) = S)
(Word (of)
(cat) = P
(slash) = 0
(arg1) = NP)
(Word (fit)
(slash) = 0
(cat) = AP)
(Word (competent)
(slash) = 0
(cat) = AP)
(Word (well - qualified)
(slash) = 0
(cat) = AP)
(Word (Dr Chan)
(slash) = 0
(cat) = NP)
(Word (nurses)
(slash) = 0
(cat) = NP)
(Word (MediCenter)
(slash) = 0
(cat) = NP)
(Word (patients)
(slash) = 0
(cat) = NP)
(Word (died)
(arg1) = 0
(slash) = 0
(cat) = V)
(Word (employed)
(arg1) = NP
(slash) = 0
(cat) = V)))
(defun category (d subst)
(let (
(cat (find_feature_value 'cat d subst))
(slash (find_feature_value 'slash d subst)))
(if (equal slash 0)
cat
(list cat '/ slash))))
(defun tree (cat subtrees)
(cons cat subtrees))
|
ccb059de45eadeecff8b2f5ec0162317a321d3463b66cfbe859d64ef5a033a66
|
gelisam/frp-zoo
|
Main.hs
|
{-# LANGUAGE Arrows #-}
module
Main
where
import Prelude hiding (id, (.))
import Control.Category
import Control.Arrow
import Control.Monad
import Data.Functor ((<$))
import qualified Control.Arrow.Machine as P
import Graphics.Gloss
import qualified Graphics.Gloss.Interface.IO.Game as G
import Buttons
import GlossInterface
mainArrow :: P.ProcessA (Kleisli IO) (Float, P.Event G.Event) Picture
mainArrow = proc (_, e) ->
do
let
click0 = P.filterEvent (Just Click ==) $ filter0 <$> e
click5 = P.filterEvent (Just Click ==) $ filter5 <$> e
click10 = P.filterEvent (Just Click ==) $ filter10 <$> e
toggle0 = P.filterEvent (Just Toggle ==) $ filter0 <$> e
toggle5 = P.filterEvent (Just Toggle ==) $ filter5 <$> e
toggle10 = P.filterEvent (Just Toggle ==) $ filter10 <$> e
mode0 <- P.accum True -< not <$ toggle0
mode5 <- P.accum True -< not <$ toggle5
mode10 <- P.accum True -< not <$ toggle10
-- ---------------------------
First order implementation
-- ---------------------------
count0 <- P.accum 0 <<< P.gather -< [(+1) <$ click0, const 0 <$ toggle0]
count5 <- P.accum 0 -< (if mode5 then (+1) else id) <$ click5
count10 <- P.accum 0 -< (+1) <$ click10
let
show0 = if mode0 then count0 else -1
show5 = if mode5 then count5 else -1
show10 = if mode10 then count10 else -1
-- ---------------------------
-- Higher order implementation
-- ---------------------------
-- Every toggle event causes switch of counters, with every counter is newly created.
show0D <-
(let
active _ =
P.switch (counter *** dropE 1) inactive
inactive _ =
P.switch (pure (-1) *** dropE 1) active
in
P.switch (counter *** id) inactive)
-< (click0, () <$ toggle0)
Every toggle event causes switch of a counter , with one counter reused .
show5D <-
(let
test = proc ((_, toggle), _) ->
returnA -< toggle
active pa _ =
P.kSwitch pa (test >>> dropE 1) inactive
inactive pa _ =
P.switch (pure (-1) *** dropE 1) (active pa)
in
P.kSwitch (arr fst >>> counter) test inactive)
-< (click5, () <$ toggle5)
returnA -<
renderButtons show0 (Just show0D) show5 (Just show5D) show10 Nothing
where
counter = proc e ->
P.accum 0 -< (+1) <$ e
dropE n = P.construct $
do
replicateM_ n P.await
forever (P.await >>= P.yield)
main :: IO ()
main =
playMachinecell
(InWindow "Machinecell Example" (320, 240) (800, 200))
white
300
mainArrow
| null |
https://raw.githubusercontent.com/gelisam/frp-zoo/1a1704e4294b17a1c6e4b417a73e61216bad2321/machinecell-example/Main.hs
|
haskell
|
# LANGUAGE Arrows #
---------------------------
---------------------------
---------------------------
Higher order implementation
---------------------------
Every toggle event causes switch of counters, with every counter is newly created.
|
module
Main
where
import Prelude hiding (id, (.))
import Control.Category
import Control.Arrow
import Control.Monad
import Data.Functor ((<$))
import qualified Control.Arrow.Machine as P
import Graphics.Gloss
import qualified Graphics.Gloss.Interface.IO.Game as G
import Buttons
import GlossInterface
mainArrow :: P.ProcessA (Kleisli IO) (Float, P.Event G.Event) Picture
mainArrow = proc (_, e) ->
do
let
click0 = P.filterEvent (Just Click ==) $ filter0 <$> e
click5 = P.filterEvent (Just Click ==) $ filter5 <$> e
click10 = P.filterEvent (Just Click ==) $ filter10 <$> e
toggle0 = P.filterEvent (Just Toggle ==) $ filter0 <$> e
toggle5 = P.filterEvent (Just Toggle ==) $ filter5 <$> e
toggle10 = P.filterEvent (Just Toggle ==) $ filter10 <$> e
mode0 <- P.accum True -< not <$ toggle0
mode5 <- P.accum True -< not <$ toggle5
mode10 <- P.accum True -< not <$ toggle10
First order implementation
count0 <- P.accum 0 <<< P.gather -< [(+1) <$ click0, const 0 <$ toggle0]
count5 <- P.accum 0 -< (if mode5 then (+1) else id) <$ click5
count10 <- P.accum 0 -< (+1) <$ click10
let
show0 = if mode0 then count0 else -1
show5 = if mode5 then count5 else -1
show10 = if mode10 then count10 else -1
show0D <-
(let
active _ =
P.switch (counter *** dropE 1) inactive
inactive _ =
P.switch (pure (-1) *** dropE 1) active
in
P.switch (counter *** id) inactive)
-< (click0, () <$ toggle0)
Every toggle event causes switch of a counter , with one counter reused .
show5D <-
(let
test = proc ((_, toggle), _) ->
returnA -< toggle
active pa _ =
P.kSwitch pa (test >>> dropE 1) inactive
inactive pa _ =
P.switch (pure (-1) *** dropE 1) (active pa)
in
P.kSwitch (arr fst >>> counter) test inactive)
-< (click5, () <$ toggle5)
returnA -<
renderButtons show0 (Just show0D) show5 (Just show5D) show10 Nothing
where
counter = proc e ->
P.accum 0 -< (+1) <$ e
dropE n = P.construct $
do
replicateM_ n P.await
forever (P.await >>= P.yield)
main :: IO ()
main =
playMachinecell
(InWindow "Machinecell Example" (320, 240) (800, 200))
white
300
mainArrow
|
4c7675329333eba6d1aa920ce6ceedd380caf949ef2d8cf516943aedea0e6368
|
gtk2hs/gtk2hs
|
Binary.hs
|
# LANGUAGE CPP , ScopedTypeVariables #
--
( c ) The University of Glasgow 2002
--
Binary I / O library , with special tweaks for GHC
--
-- Based on the nhc98 Binary library, which is copyright
( c ) and , University of York , 1998 .
-- Under the terms of the license for that software, we must tell you
-- where you can obtain the original version of the Binary library, namely
/
module Binary
( {-type-} Bin,
{-class-} Binary(..),
{-type-} BinHandle,
openBinIO, openBinIO_,
openBinMem,
-- closeBin,
seekBin,
tellBin,
castBin,
writeBinMem,
readBinMem,
isEOFBin,
-- for writing instances:
putByte,
getByte,
putSharedString,
getSharedString,
lazy I / O
lazyGet,
lazyPut,
#if __GLASGOW_HASKELL__<610
GHC only :
ByteArray(..),
getByteArray,
putByteArray,
#endif
getBinFileWithDict, -- :: Binary a => FilePath -> IO a
putBinFileWithDict, -- :: Binary a => FilePath -> ModuleName -> a -> IO ()
) where
#if __GLASGOW_HASKELL__>=604
#include "ghcconfig.h"
#else
#include "config.h"
#endif
import FastMutInt
import Map (Map)
import qualified Map as Map
#if __GLASGOW_HASKELL__>=602
# if __GLASGOW_HASKELL__>=707
import Data.HashTable.Class as HashTable
(HashTable)
import Data.HashTable.IO as HashTable
(BasicHashTable, toList, new, insert, lookup)
# else
import Data.HashTable as HashTable
# endif
#endif
import Data.Array.IO
import Data.Array
import Data.Bits
import Data.Int
import Data.Word
import Data.IORef
import Data.Char ( ord, chr )
import Data.Array.Base ( unsafeRead, unsafeWrite )
import Control.Monad ( when, liftM )
import System.IO as IO
import System.IO.Unsafe ( unsafeInterleaveIO )
import System.IO.Error ( mkIOError, eofErrorType )
import GHC.Real ( Ratio(..) )
import GHC.Exts
# if __GLASGOW_HASKELL__>=612
import GHC.IO (IO(IO))
#else
import GHC.IOBase (IO(IO))
#endif
import GHC.Word ( Word8(..) )
# if __GLASGOW_HASKELL__<602
import GHC.Handle ( hSetBinaryMode )
# endif
-- for debug
import System.CPUTime (getCPUTime)
import Numeric (showFFloat)
#define SIZEOF_HSINT SIZEOF_VOID_P
type BinArray = IOUArray Int Word8
---------------------------------------------------------------
-- BinHandle
---------------------------------------------------------------
data BinHandle
= BinMem { -- binary data stored in an unboxed array
bh_usr :: UserData, -- sigh, need parameterized modules :-)
off_r :: !FastMutInt, -- the current offset
sz_r :: !FastMutInt, -- size of the array (cached)
arr_r :: !(IORef BinArray) -- the array (bounds: (0,size-1))
}
-- XXX: should really store a "high water mark" for dumping out
-- the binary data to a file.
| BinIO { -- binary data stored in a file
bh_usr :: UserData,
off_r :: !FastMutInt, -- the current offset (cached)
hdl :: !IO.Handle -- the file handle (must be seekable)
}
cache the file ptr in BinIO ; using hTell is too expensive
-- to call repeatedly. If anyone else is modifying this Handle
-- at the same time, we'll be screwed.
getUserData :: BinHandle -> UserData
getUserData bh = bh_usr bh
setUserData :: BinHandle -> UserData -> BinHandle
setUserData bh us = bh { bh_usr = us }
---------------------------------------------------------------
---------------------------------------------------------------
newtype Bin a = BinPtr Int
deriving (Eq, Ord, Show, Bounded)
castBin :: Bin a -> Bin b
castBin (BinPtr i) = BinPtr i
---------------------------------------------------------------
-- class Binary
---------------------------------------------------------------
class Binary a where
put_ :: BinHandle -> a -> IO ()
put :: BinHandle -> a -> IO (Bin a)
get :: BinHandle -> IO a
define one of put _ , put . Use of put _ is recommended because it
-- is more likely that tail-calls can kick in, and we rarely need the
-- position return value.
put_ bh a = do put bh a; return ()
put bh a = do p <- tellBin bh; put_ bh a; return p
putAt :: Binary a => BinHandle -> Bin a -> a -> IO ()
putAt bh p x = do seekBin bh p; put bh x; return ()
getAt :: Binary a => BinHandle -> Bin a -> IO a
getAt bh p = do seekBin bh p; get bh
openBinIO_ :: IO.Handle -> IO BinHandle
openBinIO_ h = openBinIO h
openBinIO :: IO.Handle -> IO BinHandle
openBinIO h = do
r <- newFastMutInt
writeFastMutInt r 0
return (BinIO noUserData r h)
openBinMem :: Int -> IO BinHandle
openBinMem size
| size <= 0 = error "Data.Binary.openBinMem: size must be >= 0"
| otherwise = do
arr <- newArray_ (0,size-1)
arr_r <- newIORef arr
ix_r <- newFastMutInt
writeFastMutInt ix_r 0
sz_r <- newFastMutInt
writeFastMutInt sz_r size
return (BinMem noUserData ix_r sz_r arr_r)
tellBin :: BinHandle -> IO (Bin a)
tellBin (BinIO _ r _) = do ix <- readFastMutInt r; return (BinPtr ix)
tellBin (BinMem _ r _ _) = do ix <- readFastMutInt r; return (BinPtr ix)
seekBin :: BinHandle -> Bin a -> IO ()
seekBin (BinIO _ ix_r h) (BinPtr p) = do
writeFastMutInt ix_r p
hSeek h AbsoluteSeek (fromIntegral p)
seekBin h@(BinMem _ ix_r sz_r a) (BinPtr p) = do
sz <- readFastMutInt sz_r
if (p >= sz)
then do expandBin h p; writeFastMutInt ix_r p
else writeFastMutInt ix_r p
isEOFBin :: BinHandle -> IO Bool
isEOFBin (BinMem _ ix_r sz_r a) = do
ix <- readFastMutInt ix_r
sz <- readFastMutInt sz_r
return (ix >= sz)
isEOFBin (BinIO _ ix_r h) = hIsEOF h
writeBinMem :: BinHandle -> FilePath -> IO ()
writeBinMem (BinIO _ _ _) _ = error "Data.Binary.writeBinMem: not a memory handle"
writeBinMem (BinMem _ ix_r sz_r arr_r) fn = do
h <- openFile fn WriteMode
hSetBinaryMode h True
arr <- readIORef arr_r
ix <- readFastMutInt ix_r
hPutArray h arr ix
hClose h
readBinMem :: FilePath -> IO BinHandle
Return a BinHandle with a totally undefined State
readBinMem filename = do
h <- openFile filename ReadMode
hSetBinaryMode h True
filesize' <- hFileSize h
let filesize = fromIntegral filesize'
arr <- newArray_ (0,filesize-1)
count <- hGetArray h arr filesize
when (count /= filesize)
(error ("Binary.readBinMem: only read " ++ show count ++ " bytes"))
hClose h
arr_r <- newIORef arr
ix_r <- newFastMutInt
writeFastMutInt ix_r 0
sz_r <- newFastMutInt
writeFastMutInt sz_r filesize
return (BinMem noUserData ix_r sz_r arr_r)
-- expand the size of the array to include a specified offset
expandBin :: BinHandle -> Int -> IO ()
expandBin (BinMem _ ix_r sz_r arr_r) off = do
sz <- readFastMutInt sz_r
let sz' = head (dropWhile (<= off) (iterate (* 2) sz))
arr <- readIORef arr_r
arr' <- newArray_ (0,sz'-1)
sequence_ [ unsafeRead arr i >>= unsafeWrite arr' i
| i <- [ 0 .. sz-1 ] ]
writeFastMutInt sz_r sz'
writeIORef arr_r arr'
#ifdef DEBUG
hPutStrLn stderr ("Binary: expanding to size: " ++ show sz')
#endif
return ()
expandBin (BinIO _ _ _) _ = return ()
-- no need to expand a file, we'll assume they expand by themselves.
# INLINE expandBin #
-- -----------------------------------------------------------------------------
-- Low-level reading/writing of bytes
putWord8 :: BinHandle -> Word8 -> IO ()
putWord8 h@(BinMem _ ix_r sz_r arr_r) w = do
ix <- readFastMutInt ix_r
sz <- readFastMutInt sz_r
-- double the size of the array if it overflows
if (ix >= sz)
then do expandBin h ix
putWord8 h w
else do arr <- readIORef arr_r
unsafeWrite arr ix w
writeFastMutInt ix_r (ix+1)
return ()
putWord8 (BinIO _ ix_r h) w = do
ix <- readFastMutInt ix_r
hPutChar h (chr (fromIntegral w)) -- XXX not really correct
writeFastMutInt ix_r (ix+1)
return ()
getWord8 :: BinHandle -> IO Word8
getWord8 (BinMem _ ix_r sz_r arr_r) = do
ix <- readFastMutInt ix_r
sz <- readFastMutInt sz_r
when (ix >= sz) $
ioError (mkIOError eofErrorType "Data.Binary.getWord8" Nothing Nothing)
arr <- readIORef arr_r
w <- unsafeRead arr ix
writeFastMutInt ix_r (ix+1)
return w
getWord8 (BinIO _ ix_r h) = do
ix <- readFastMutInt ix_r
c <- hGetChar h
writeFastMutInt ix_r (ix+1)
return $! (fromIntegral (ord c)) -- XXX not really correct
putByte :: BinHandle -> Word8 -> IO ()
putByte bh w = put_ bh w
getByte :: BinHandle -> IO Word8
getByte = getWord8
-- -----------------------------------------------------------------------------
Primitve Word writes
instance Binary Word8 where
put_ = putWord8
get = getWord8
instance Binary Word16 where
put_ h w = do -- XXX too slow.. inline putWord8?
putByte h (fromIntegral (w `shiftR` 8))
putByte h (fromIntegral (w .&. 0xff))
get h = do
w1 <- getWord8 h
w2 <- getWord8 h
return $! ((fromIntegral w1 `shiftL` 8) .|. fromIntegral w2)
instance Binary Word32 where
put_ h w = do
putByte h (fromIntegral (w `shiftR` 24))
putByte h (fromIntegral ((w `shiftR` 16) .&. 0xff))
putByte h (fromIntegral ((w `shiftR` 8) .&. 0xff))
putByte h (fromIntegral (w .&. 0xff))
get h = do
w1 <- getWord8 h
w2 <- getWord8 h
w3 <- getWord8 h
w4 <- getWord8 h
return $! ((fromIntegral w1 `shiftL` 24) .|.
(fromIntegral w2 `shiftL` 16) .|.
(fromIntegral w3 `shiftL` 8) .|.
(fromIntegral w4))
instance Binary Word64 where
put_ h w = do
putByte h (fromIntegral (w `shiftR` 56))
putByte h (fromIntegral ((w `shiftR` 48) .&. 0xff))
putByte h (fromIntegral ((w `shiftR` 40) .&. 0xff))
putByte h (fromIntegral ((w `shiftR` 32) .&. 0xff))
putByte h (fromIntegral ((w `shiftR` 24) .&. 0xff))
putByte h (fromIntegral ((w `shiftR` 16) .&. 0xff))
putByte h (fromIntegral ((w `shiftR` 8) .&. 0xff))
putByte h (fromIntegral (w .&. 0xff))
get h = do
w1 <- getWord8 h
w2 <- getWord8 h
w3 <- getWord8 h
w4 <- getWord8 h
w5 <- getWord8 h
w6 <- getWord8 h
w7 <- getWord8 h
w8 <- getWord8 h
return $! ((fromIntegral w1 `shiftL` 56) .|.
(fromIntegral w2 `shiftL` 48) .|.
(fromIntegral w3 `shiftL` 40) .|.
(fromIntegral w4 `shiftL` 32) .|.
(fromIntegral w5 `shiftL` 24) .|.
(fromIntegral w6 `shiftL` 16) .|.
(fromIntegral w7 `shiftL` 8) .|.
(fromIntegral w8))
-- -----------------------------------------------------------------------------
-- Primitve Int writes
instance Binary Int8 where
put_ h w = put_ h (fromIntegral w :: Word8)
get h = do w <- get h; return $! (fromIntegral (w::Word8))
instance Binary Int16 where
put_ h w = put_ h (fromIntegral w :: Word16)
get h = do w <- get h; return $! (fromIntegral (w::Word16))
instance Binary Int32 where
put_ h w = put_ h (fromIntegral w :: Word32)
get h = do w <- get h; return $! (fromIntegral (w::Word32))
instance Binary Int64 where
put_ h w = put_ h (fromIntegral w :: Word64)
get h = do w <- get h; return $! (fromIntegral (w::Word64))
-- -----------------------------------------------------------------------------
-- Instances for standard types
instance Binary () where
put_ bh () = return ()
get _ = return ()
-- getF bh p = case getBitsF bh 0 p of (_,b) -> ((),b)
instance Binary Bool where
put_ bh b = putByte bh (fromIntegral (fromEnum b))
get bh = do x <- getWord8 bh; return $! (toEnum (fromIntegral x))
-- getF bh p = case getBitsF bh 1 p of (x,b) -> (toEnum x,b)
instance Binary Char where
put_ bh c = put_ bh (fromIntegral (ord c) :: Word8)
get bh = do x <- get bh; return $! (chr (fromIntegral (x :: Word8)))
-- getF bh p = case getBitsF bh 8 p of (x,b) -> (toEnum x,b)
instance Binary Int where
#if SIZEOF_HSINT == 4
put_ bh i = put_ bh (fromIntegral i :: Int32)
get bh = do
x <- get bh
return $! (fromIntegral (x :: Int32))
#elif SIZEOF_HSINT == 8
put_ bh i = put_ bh (fromIntegral i :: Int64)
get bh = do
x <- get bh
return $! (fromIntegral (x :: Int64))
#else
#error "unsupported sizeof(HsInt)"
#endif
getF bh = getBitsF bh 32
instance Binary a => Binary [a] where
put_ bh list = do put_ bh (length list)
mapM_ (put_ bh) list
get bh = do len <- get bh
let getMany :: Int -> IO [a]
getMany 0 = return []
getMany n = do x <- get bh
xs <- getMany (n-1)
return (x:xs)
getMany len
instance (Binary a, Binary b) => Binary (a,b) where
put_ bh (a,b) = do put_ bh a; put_ bh b
get bh = do a <- get bh
b <- get bh
return (a,b)
instance (Binary a, Binary b, Binary c) => Binary (a,b,c) where
put_ bh (a,b,c) = do put_ bh a; put_ bh b; put_ bh c
get bh = do a <- get bh
b <- get bh
c <- get bh
return (a,b,c)
instance (Binary a, Binary b, Binary c, Binary d) => Binary (a,b,c,d) where
put_ bh (a,b,c,d) = do put_ bh a; put_ bh b; put_ bh c; put_ bh d
get bh = do a <- get bh
b <- get bh
c <- get bh
d <- get bh
return (a,b,c,d)
instance Binary a => Binary (Maybe a) where
put_ bh Nothing = putByte bh 0
put_ bh (Just a) = do putByte bh 1; put_ bh a
get bh = do h <- getWord8 bh
case h of
0 -> return Nothing
_ -> do x <- get bh; return (Just x)
instance (Binary a, Binary b) => Binary (Either a b) where
put_ bh (Left a) = do putByte bh 0; put_ bh a
put_ bh (Right b) = do putByte bh 1; put_ bh b
get bh = do h <- getWord8 bh
case h of
0 -> do a <- get bh ; return (Left a)
_ -> do b <- get bh ; return (Right b)
instance (Binary a, Binary i, Ix i) => Binary (Array i a) where
put_ bh arr = do put_ bh (Data.Array.bounds arr)
put_ bh (Data.Array.elems arr)
get bh = do bounds <- get bh
elems <- get bh
return $ listArray bounds elems
instance (Binary key, Ord key, Binary elem) => Binary (Map key elem) where
put _ bh fm = put _ bh ( Map.toList fm )
-- get bh = do list <- get bh
return ( Map.fromList list )
put_ bh fm = do let list = Map.toList fm
put_ bh (length list)
mapM_ (\(key, val) -> do put_ bh key
lazyPut bh val) list
get bh = do len <- get bh
let getMany :: Int -> IO [(key,elem)]
getMany 0 = return []
getMany n = do key <- get bh
val <- lazyGet bh
xs <- getMany (n-1)
return ((key,val):xs)
-- printElapsedTime "before get Map"
list <- getMany len
-- printElapsedTime "after get Map"
return (Map.fromList list)
#ifdef __GLASGOW_HASKELL__
#if __GLASGOW_HASKELL__<610
instance Binary Integer where
put_ bh (S# i#) = do putByte bh 0; put_ bh (I# i#)
put_ bh (J# s# a#) = do
p <- putByte bh 1;
put_ bh (I# s#)
let sz# = sizeofByteArray# a# -- in *bytes*
put_ bh (I# sz#) -- in *bytes*
putByteArray bh a# sz#
get bh = do
b <- getByte bh
case b of
0 -> do (I# i#) <- get bh
return (S# i#)
_ -> do (I# s#) <- get bh
sz <- get bh
(BA a#) <- getByteArray bh sz
return (J# s# a#)
putByteArray :: BinHandle -> ByteArray# -> Int# -> IO ()
putByteArray bh a s# = loop 0#
where loop n#
| n# ==# s# = return ()
| otherwise = do
putByte bh (indexByteArray a n#)
loop (n# +# 1#)
getByteArray :: BinHandle -> Int -> IO ByteArray
getByteArray bh (I# sz) = do
(MBA arr) <- newByteArray sz
let loop n
| n ==# sz = return ()
| otherwise = do
w <- getByte bh
writeByteArray arr n w
loop (n +# 1#)
loop 0#
freezeByteArray arr
data ByteArray = BA ByteArray#
data MBA = MBA (MutableByteArray# RealWorld)
newByteArray :: Int# -> IO MBA
newByteArray sz = IO $ \s ->
case newByteArray# sz s of { (# s, arr #) ->
(# s, MBA arr #) }
freezeByteArray :: MutableByteArray# RealWorld -> IO ByteArray
freezeByteArray arr = IO $ \s ->
case unsafeFreezeByteArray# arr s of { (# s, arr #) ->
(# s, BA arr #) }
writeByteArray :: MutableByteArray# RealWorld -> Int# -> Word8 -> IO ()
#if __GLASGOW_HASKELL__ < 503
writeByteArray arr i w8 = IO $ \s ->
case word8ToWord w8 of { W# w# ->
case writeCharArray# arr i (chr# (word2Int# w#)) s of { s ->
(# s , () #) }}
#else
writeByteArray arr i (W8# w) = IO $ \s ->
case writeWord8Array# arr i w s of { s ->
(# s, () #) }
#endif
#if __GLASGOW_HASKELL__ < 503
indexByteArray a# n# = fromIntegral (I# (ord# (indexCharArray# a# n#)))
#else
indexByteArray a# n# = W8# (indexWord8Array# a# n#)
#endif
instance (Integral a, Binary a) => Binary (Ratio a) where
put_ bh (a :% b) = do put_ bh a; put_ bh b
get bh = do a <- get bh; b <- get bh; return (a :% b)
#else
instance Binary Integer where
put_ h n = do
put h ((fromIntegral $ signum n) :: Int8)
when (n /= 0) $ do
let n' = abs n
nBytes = byteSize n'
put h (fromIntegral nBytes :: Word64)
mapM_ (putByte h) [ fromIntegral ((n' `shiftR` (b * 8)) .&. 0xff)
| b <- [ nBytes-1, nBytes-2 .. 0 ] ]
where byteSize n =
let f b = if (1 `shiftL` (b * 8)) > n
then b
else f (b + 1)
in f 0
get h = do
sign :: Int8 <- get h
if sign == 0
then return 0
else do
nBytes :: Word64 <- get h
n <- accumBytes nBytes 0
return $ fromIntegral sign * n
where accumBytes nBytes acc | nBytes == 0 = return acc
| otherwise = do
b <- getByte h
accumBytes (nBytes - 1) ((acc `shiftL` 8) .|. fromIntegral b)
#endif
#endif
instance Binary (Bin a) where
put_ bh (BinPtr i) = put_ bh i
get bh = do i <- get bh; return (BinPtr i)
-- -----------------------------------------------------------------------------
-- Lazy reading/writing
lazyPut :: Binary a => BinHandle -> a -> IO ()
lazyPut bh a = do
-- output the obj with a ptr to skip over it:
pre_a <- tellBin bh
save a slot for the ptr
put_ bh a -- dump the object
q <- tellBin bh -- q = ptr to after object
fill in slot before a with ptr to q
seekBin bh q -- finally carry on writing at q
lazyGet :: Binary a => BinHandle -> IO a
lazyGet bh = do
a BinPtr
p_a <- tellBin bh
a <- unsafeInterleaveIO (getAt bh p_a)
seekBin bh p -- skip over the object for now
return a
-- --------------------------------------------------------------
-- Main wrappers: getBinFileWithDict, putBinFileWithDict
--
-- This layer is built on top of the stuff above,
and should not know anything about BinHandles
-- --------------------------------------------------------------
initBinMemSize = (1024*1024) :: Int
binaryInterfaceMagic = 0x1face :: Word32
getBinFileWithDict :: Binary a => FilePath -> IO a
getBinFileWithDict file_path = do
bh <- Binary.readBinMem file_path
Read the magic number to check that this really is a GHC .hi file
-- (This magic number does not change when we change
GHC interface file format )
magic <- get bh
when (magic /= binaryInterfaceMagic) $
error "magic number mismatch: old/corrupt interface file?"
-- Read the dictionary
-- The next word in the file is a pointer to where the dictionary is
-- (probably at the end of the file)
dict_p <- Binary.get bh -- Get the dictionary ptr
data_p <- tellBin bh -- Remember where we are now
seekBin bh dict_p
dict <- getDictionary bh
seekBin bh data_p -- Back to where we were before
Initialise the user - data field of bh
let bh' = setUserData bh (initReadState dict)
-- At last, get the thing
get bh'
putBinFileWithDict :: Binary a => FilePath -> a -> IO ()
putBinFileWithDict file_path the_thing = do
hnd < - openBinaryFile file_path WriteMode
-- bh <- openBinIO hnd
bh <- openBinMem initBinMemSize
put_ bh binaryInterfaceMagic
-- Remember where the dictionary pointer will go
dict_p_p <- tellBin bh
put_ bh dict_p_p -- Placeholder for ptr to dictionary
-- Make some intial state
usr_state <- newWriteState
-- Put the main thing,
put_ (setUserData bh usr_state) the_thing
-- Get the final-state
j <- readIORef (ud_next usr_state)
#if __GLASGOW_HASKELL__>=602
fm <- HashTable.toList (ud_map usr_state)
#else
fm <- liftM Map.toList $ readIORef (ud_map usr_state)
#endif
dict_p <- tellBin bh -- This is where the dictionary will start
-- Write the dictionary pointer at the fornt of the file
putAt bh dict_p_p dict_p -- Fill in the placeholder
seekBin bh dict_p -- Seek back to the end of the file
-- Write the dictionary itself
putDictionary bh j (constructDictionary j fm)
-- And send the result to the file
writeBinMem bh file_path
hClose hnd
-- -----------------------------------------------------------------------------
UserData
-- -----------------------------------------------------------------------------
data UserData =
UserData { -- This field is used only when reading
ud_dict :: Dictionary,
The next two fields are only used when writing
ud_next :: IORef Int, -- The next index to use
#if __GLASGOW_HASKELL__>=602
# if __GLASGOW_HASKELL__>=707
ud_map :: BasicHashTable String Int -- The index of each string
# else
ud_map :: HashTable String Int -- The index of each string
# endif
#else
ud_map :: IORef (Map String Int)
#endif
}
noUserData = error "Binary.UserData: no user data"
initReadState :: Dictionary -> UserData
initReadState dict = UserData{ ud_dict = dict,
ud_next = undef "next",
ud_map = undef "map" }
newWriteState :: IO UserData
newWriteState = do
j_r <- newIORef 0
#if __GLASGOW_HASKELL__>=602
# if __GLASGOW_HASKELL__>=707
out_r <- HashTable.new
# else
out_r <- HashTable.new (==) HashTable.hashString
# endif
#else
out_r <- newIORef Map.empty
#endif
return (UserData { ud_dict = error "dict",
ud_next = j_r,
ud_map = out_r })
undef s = error ("Binary.UserData: no " ++ s)
---------------------------------------------------------
-- The Dictionary
---------------------------------------------------------
type Dictionary = Array Int String -- The dictionary
-- Should be 0-indexed
putDictionary :: BinHandle -> Int -> Dictionary -> IO ()
putDictionary bh sz dict = do
put_ bh sz
mapM_ (put_ bh) (elems dict)
getDictionary :: BinHandle -> IO Dictionary
getDictionary bh = do
sz <- get bh
elems <- sequence (take sz (repeat (get bh)))
return (listArray (0,sz-1) elems)
constructDictionary :: Int -> [(String,Int)] -> Dictionary
constructDictionary j fm = array (0,j-1) (map (\(x,y) -> (y,x)) fm)
---------------------------------------------------------
Reading and writing memoised
---------------------------------------------------------
putSharedString :: BinHandle -> String -> IO ()
putSharedString bh str =
case getUserData bh of
UserData { ud_next = j_r, ud_map = out_r, ud_dict = dict} -> do
#if __GLASGOW_HASKELL__>=602
entry <- HashTable.lookup out_r str
#else
fm <- readIORef out_r
let entry = Map.lookup str fm
#endif
case entry of
Just j -> put_ bh j
Nothing -> do
j <- readIORef j_r
put_ bh j
writeIORef j_r (j+1)
#if __GLASGOW_HASKELL__>=602
HashTable.insert out_r str j
#else
modifyIORef out_r (\fm -> Map.insert str j fm)
#endif
getSharedString :: BinHandle -> IO String
getSharedString bh = do
j <- get bh
return $! (ud_dict (getUserData bh) ! j)
---------------------------------------------------------
-- Reading and writing FastStrings
---------------------------------------------------------
putFS bh ( FastString i d l ba ) = do
put _ bh ( I # l )
putByteArray bh ba l
putFS bh s = error ( " Binary.put_(FastString ): " + + unpackFS s )
-- Note : the length of the FastString is * not * the same as
-- the size of the : the latter is rounded up to a
-- multiple of the word size .
{ - -- possible faster version , not quite there yet :
getFS bh@BinMem { } = do
( I # l ) < - get bh
arr < - readIORef ( arr_r bh )
off < - readFastMutInt ( off_r bh )
return $ ! ( mkFastSubStringBA # arr off l )
---------------------------------------------------------
-- Reading and writing FastStrings
---------------------------------------------------------
putFS bh (FastString id l ba) = do
put_ bh (I# l)
putByteArray bh ba l
putFS bh s = error ("Binary.put_(FastString): " ++ unpackFS s)
-- Note: the length of the FastString is *not* the same as
-- the size of the ByteArray: the latter is rounded up to a
-- multiple of the word size.
{- -- possible faster version, not quite there yet:
getFS bh@BinMem{} = do
(I# l) <- get bh
arr <- readIORef (arr_r bh)
off <- readFastMutInt (off_r bh)
return $! (mkFastSubStringBA# arr off l)
-}
getFS bh = do
(I# l) <- get bh
(BA ba) <- getByteArray bh (I# l)
return $! (mkFastSubStringBA# ba 0# l)
instance Binary FastString where
put_ bh f@(FastString id l ba) =
case getUserData bh of {
UserData { ud_next = j_r, ud_map = out_r, ud_dict = dict} -> do
out <- readIORef out_r
let uniq = getUnique f
case lookupUFM out uniq of
Just (j,f) -> put_ bh j
Nothing -> do
j <- readIORef j_r
put_ bh j
writeIORef j_r (j+1)
writeIORef out_r (addToUFM out uniq (j,f))
}
put_ bh s = error ("Binary.put_(FastString): " ++ show (unpackFS s))
get bh = do
j <- get bh
return $! (ud_dict (getUserData bh) ! j)
-}
printElapsedTime :: String -> IO ()
printElapsedTime msg = do
time <- getCPUTime
hPutStr stderr $ "elapsed time: " ++ Numeric.showFFloat (Just 2) ((fromIntegral time) / 10^12) " (" ++ msg ++ ")\n"
| null |
https://raw.githubusercontent.com/gtk2hs/gtk2hs/ce06bb7f79fc2fe8b259486032e602b1816bebcd/tools/c2hs/base/general/Binary.hs
|
haskell
|
Based on the nhc98 Binary library, which is copyright
Under the terms of the license for that software, we must tell you
where you can obtain the original version of the Binary library, namely
type
class
type
closeBin,
for writing instances:
:: Binary a => FilePath -> IO a
:: Binary a => FilePath -> ModuleName -> a -> IO ()
for debug
-------------------------------------------------------------
BinHandle
-------------------------------------------------------------
binary data stored in an unboxed array
sigh, need parameterized modules :-)
the current offset
size of the array (cached)
the array (bounds: (0,size-1))
XXX: should really store a "high water mark" for dumping out
the binary data to a file.
binary data stored in a file
the current offset (cached)
the file handle (must be seekable)
to call repeatedly. If anyone else is modifying this Handle
at the same time, we'll be screwed.
-------------------------------------------------------------
-------------------------------------------------------------
-------------------------------------------------------------
class Binary
-------------------------------------------------------------
is more likely that tail-calls can kick in, and we rarely need the
position return value.
expand the size of the array to include a specified offset
no need to expand a file, we'll assume they expand by themselves.
-----------------------------------------------------------------------------
Low-level reading/writing of bytes
double the size of the array if it overflows
XXX not really correct
XXX not really correct
-----------------------------------------------------------------------------
XXX too slow.. inline putWord8?
-----------------------------------------------------------------------------
Primitve Int writes
-----------------------------------------------------------------------------
Instances for standard types
getF bh p = case getBitsF bh 0 p of (_,b) -> ((),b)
getF bh p = case getBitsF bh 1 p of (x,b) -> (toEnum x,b)
getF bh p = case getBitsF bh 8 p of (x,b) -> (toEnum x,b)
get bh = do list <- get bh
printElapsedTime "before get Map"
printElapsedTime "after get Map"
in *bytes*
in *bytes*
-----------------------------------------------------------------------------
Lazy reading/writing
output the obj with a ptr to skip over it:
dump the object
q = ptr to after object
finally carry on writing at q
skip over the object for now
--------------------------------------------------------------
Main wrappers: getBinFileWithDict, putBinFileWithDict
This layer is built on top of the stuff above,
--------------------------------------------------------------
(This magic number does not change when we change
Read the dictionary
The next word in the file is a pointer to where the dictionary is
(probably at the end of the file)
Get the dictionary ptr
Remember where we are now
Back to where we were before
At last, get the thing
bh <- openBinIO hnd
Remember where the dictionary pointer will go
Placeholder for ptr to dictionary
Make some intial state
Put the main thing,
Get the final-state
This is where the dictionary will start
Write the dictionary pointer at the fornt of the file
Fill in the placeholder
Seek back to the end of the file
Write the dictionary itself
And send the result to the file
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
This field is used only when reading
The next index to use
The index of each string
The index of each string
-------------------------------------------------------
The Dictionary
-------------------------------------------------------
The dictionary
Should be 0-indexed
-------------------------------------------------------
-------------------------------------------------------
-------------------------------------------------------
Reading and writing FastStrings
-------------------------------------------------------
Note : the length of the FastString is * not * the same as
the size of the : the latter is rounded up to a
multiple of the word size .
possible faster version , not quite there yet :
-------------------------------------------------------
Reading and writing FastStrings
-------------------------------------------------------
Note: the length of the FastString is *not* the same as
the size of the ByteArray: the latter is rounded up to a
multiple of the word size.
-- possible faster version, not quite there yet:
getFS bh@BinMem{} = do
(I# l) <- get bh
arr <- readIORef (arr_r bh)
off <- readFastMutInt (off_r bh)
return $! (mkFastSubStringBA# arr off l)
|
# LANGUAGE CPP , ScopedTypeVariables #
( c ) The University of Glasgow 2002
Binary I / O library , with special tweaks for GHC
( c ) and , University of York , 1998 .
/
module Binary
openBinIO, openBinIO_,
openBinMem,
seekBin,
tellBin,
castBin,
writeBinMem,
readBinMem,
isEOFBin,
putByte,
getByte,
putSharedString,
getSharedString,
lazy I / O
lazyGet,
lazyPut,
#if __GLASGOW_HASKELL__<610
GHC only :
ByteArray(..),
getByteArray,
putByteArray,
#endif
) where
#if __GLASGOW_HASKELL__>=604
#include "ghcconfig.h"
#else
#include "config.h"
#endif
import FastMutInt
import Map (Map)
import qualified Map as Map
#if __GLASGOW_HASKELL__>=602
# if __GLASGOW_HASKELL__>=707
import Data.HashTable.Class as HashTable
(HashTable)
import Data.HashTable.IO as HashTable
(BasicHashTable, toList, new, insert, lookup)
# else
import Data.HashTable as HashTable
# endif
#endif
import Data.Array.IO
import Data.Array
import Data.Bits
import Data.Int
import Data.Word
import Data.IORef
import Data.Char ( ord, chr )
import Data.Array.Base ( unsafeRead, unsafeWrite )
import Control.Monad ( when, liftM )
import System.IO as IO
import System.IO.Unsafe ( unsafeInterleaveIO )
import System.IO.Error ( mkIOError, eofErrorType )
import GHC.Real ( Ratio(..) )
import GHC.Exts
# if __GLASGOW_HASKELL__>=612
import GHC.IO (IO(IO))
#else
import GHC.IOBase (IO(IO))
#endif
import GHC.Word ( Word8(..) )
# if __GLASGOW_HASKELL__<602
import GHC.Handle ( hSetBinaryMode )
# endif
import System.CPUTime (getCPUTime)
import Numeric (showFFloat)
#define SIZEOF_HSINT SIZEOF_VOID_P
type BinArray = IOUArray Int Word8
data BinHandle
}
bh_usr :: UserData,
}
cache the file ptr in BinIO ; using hTell is too expensive
getUserData :: BinHandle -> UserData
getUserData bh = bh_usr bh
setUserData :: BinHandle -> UserData -> BinHandle
setUserData bh us = bh { bh_usr = us }
newtype Bin a = BinPtr Int
deriving (Eq, Ord, Show, Bounded)
castBin :: Bin a -> Bin b
castBin (BinPtr i) = BinPtr i
class Binary a where
put_ :: BinHandle -> a -> IO ()
put :: BinHandle -> a -> IO (Bin a)
get :: BinHandle -> IO a
define one of put _ , put . Use of put _ is recommended because it
put_ bh a = do put bh a; return ()
put bh a = do p <- tellBin bh; put_ bh a; return p
putAt :: Binary a => BinHandle -> Bin a -> a -> IO ()
putAt bh p x = do seekBin bh p; put bh x; return ()
getAt :: Binary a => BinHandle -> Bin a -> IO a
getAt bh p = do seekBin bh p; get bh
openBinIO_ :: IO.Handle -> IO BinHandle
openBinIO_ h = openBinIO h
openBinIO :: IO.Handle -> IO BinHandle
openBinIO h = do
r <- newFastMutInt
writeFastMutInt r 0
return (BinIO noUserData r h)
openBinMem :: Int -> IO BinHandle
openBinMem size
| size <= 0 = error "Data.Binary.openBinMem: size must be >= 0"
| otherwise = do
arr <- newArray_ (0,size-1)
arr_r <- newIORef arr
ix_r <- newFastMutInt
writeFastMutInt ix_r 0
sz_r <- newFastMutInt
writeFastMutInt sz_r size
return (BinMem noUserData ix_r sz_r arr_r)
tellBin :: BinHandle -> IO (Bin a)
tellBin (BinIO _ r _) = do ix <- readFastMutInt r; return (BinPtr ix)
tellBin (BinMem _ r _ _) = do ix <- readFastMutInt r; return (BinPtr ix)
seekBin :: BinHandle -> Bin a -> IO ()
seekBin (BinIO _ ix_r h) (BinPtr p) = do
writeFastMutInt ix_r p
hSeek h AbsoluteSeek (fromIntegral p)
seekBin h@(BinMem _ ix_r sz_r a) (BinPtr p) = do
sz <- readFastMutInt sz_r
if (p >= sz)
then do expandBin h p; writeFastMutInt ix_r p
else writeFastMutInt ix_r p
isEOFBin :: BinHandle -> IO Bool
isEOFBin (BinMem _ ix_r sz_r a) = do
ix <- readFastMutInt ix_r
sz <- readFastMutInt sz_r
return (ix >= sz)
isEOFBin (BinIO _ ix_r h) = hIsEOF h
writeBinMem :: BinHandle -> FilePath -> IO ()
writeBinMem (BinIO _ _ _) _ = error "Data.Binary.writeBinMem: not a memory handle"
writeBinMem (BinMem _ ix_r sz_r arr_r) fn = do
h <- openFile fn WriteMode
hSetBinaryMode h True
arr <- readIORef arr_r
ix <- readFastMutInt ix_r
hPutArray h arr ix
hClose h
readBinMem :: FilePath -> IO BinHandle
Return a BinHandle with a totally undefined State
readBinMem filename = do
h <- openFile filename ReadMode
hSetBinaryMode h True
filesize' <- hFileSize h
let filesize = fromIntegral filesize'
arr <- newArray_ (0,filesize-1)
count <- hGetArray h arr filesize
when (count /= filesize)
(error ("Binary.readBinMem: only read " ++ show count ++ " bytes"))
hClose h
arr_r <- newIORef arr
ix_r <- newFastMutInt
writeFastMutInt ix_r 0
sz_r <- newFastMutInt
writeFastMutInt sz_r filesize
return (BinMem noUserData ix_r sz_r arr_r)
expandBin :: BinHandle -> Int -> IO ()
expandBin (BinMem _ ix_r sz_r arr_r) off = do
sz <- readFastMutInt sz_r
let sz' = head (dropWhile (<= off) (iterate (* 2) sz))
arr <- readIORef arr_r
arr' <- newArray_ (0,sz'-1)
sequence_ [ unsafeRead arr i >>= unsafeWrite arr' i
| i <- [ 0 .. sz-1 ] ]
writeFastMutInt sz_r sz'
writeIORef arr_r arr'
#ifdef DEBUG
hPutStrLn stderr ("Binary: expanding to size: " ++ show sz')
#endif
return ()
expandBin (BinIO _ _ _) _ = return ()
# INLINE expandBin #
putWord8 :: BinHandle -> Word8 -> IO ()
putWord8 h@(BinMem _ ix_r sz_r arr_r) w = do
ix <- readFastMutInt ix_r
sz <- readFastMutInt sz_r
if (ix >= sz)
then do expandBin h ix
putWord8 h w
else do arr <- readIORef arr_r
unsafeWrite arr ix w
writeFastMutInt ix_r (ix+1)
return ()
putWord8 (BinIO _ ix_r h) w = do
ix <- readFastMutInt ix_r
writeFastMutInt ix_r (ix+1)
return ()
getWord8 :: BinHandle -> IO Word8
getWord8 (BinMem _ ix_r sz_r arr_r) = do
ix <- readFastMutInt ix_r
sz <- readFastMutInt sz_r
when (ix >= sz) $
ioError (mkIOError eofErrorType "Data.Binary.getWord8" Nothing Nothing)
arr <- readIORef arr_r
w <- unsafeRead arr ix
writeFastMutInt ix_r (ix+1)
return w
getWord8 (BinIO _ ix_r h) = do
ix <- readFastMutInt ix_r
c <- hGetChar h
writeFastMutInt ix_r (ix+1)
putByte :: BinHandle -> Word8 -> IO ()
putByte bh w = put_ bh w
getByte :: BinHandle -> IO Word8
getByte = getWord8
Primitve Word writes
instance Binary Word8 where
put_ = putWord8
get = getWord8
instance Binary Word16 where
putByte h (fromIntegral (w `shiftR` 8))
putByte h (fromIntegral (w .&. 0xff))
get h = do
w1 <- getWord8 h
w2 <- getWord8 h
return $! ((fromIntegral w1 `shiftL` 8) .|. fromIntegral w2)
instance Binary Word32 where
put_ h w = do
putByte h (fromIntegral (w `shiftR` 24))
putByte h (fromIntegral ((w `shiftR` 16) .&. 0xff))
putByte h (fromIntegral ((w `shiftR` 8) .&. 0xff))
putByte h (fromIntegral (w .&. 0xff))
get h = do
w1 <- getWord8 h
w2 <- getWord8 h
w3 <- getWord8 h
w4 <- getWord8 h
return $! ((fromIntegral w1 `shiftL` 24) .|.
(fromIntegral w2 `shiftL` 16) .|.
(fromIntegral w3 `shiftL` 8) .|.
(fromIntegral w4))
instance Binary Word64 where
put_ h w = do
putByte h (fromIntegral (w `shiftR` 56))
putByte h (fromIntegral ((w `shiftR` 48) .&. 0xff))
putByte h (fromIntegral ((w `shiftR` 40) .&. 0xff))
putByte h (fromIntegral ((w `shiftR` 32) .&. 0xff))
putByte h (fromIntegral ((w `shiftR` 24) .&. 0xff))
putByte h (fromIntegral ((w `shiftR` 16) .&. 0xff))
putByte h (fromIntegral ((w `shiftR` 8) .&. 0xff))
putByte h (fromIntegral (w .&. 0xff))
get h = do
w1 <- getWord8 h
w2 <- getWord8 h
w3 <- getWord8 h
w4 <- getWord8 h
w5 <- getWord8 h
w6 <- getWord8 h
w7 <- getWord8 h
w8 <- getWord8 h
return $! ((fromIntegral w1 `shiftL` 56) .|.
(fromIntegral w2 `shiftL` 48) .|.
(fromIntegral w3 `shiftL` 40) .|.
(fromIntegral w4 `shiftL` 32) .|.
(fromIntegral w5 `shiftL` 24) .|.
(fromIntegral w6 `shiftL` 16) .|.
(fromIntegral w7 `shiftL` 8) .|.
(fromIntegral w8))
instance Binary Int8 where
put_ h w = put_ h (fromIntegral w :: Word8)
get h = do w <- get h; return $! (fromIntegral (w::Word8))
instance Binary Int16 where
put_ h w = put_ h (fromIntegral w :: Word16)
get h = do w <- get h; return $! (fromIntegral (w::Word16))
instance Binary Int32 where
put_ h w = put_ h (fromIntegral w :: Word32)
get h = do w <- get h; return $! (fromIntegral (w::Word32))
instance Binary Int64 where
put_ h w = put_ h (fromIntegral w :: Word64)
get h = do w <- get h; return $! (fromIntegral (w::Word64))
instance Binary () where
put_ bh () = return ()
get _ = return ()
instance Binary Bool where
put_ bh b = putByte bh (fromIntegral (fromEnum b))
get bh = do x <- getWord8 bh; return $! (toEnum (fromIntegral x))
instance Binary Char where
put_ bh c = put_ bh (fromIntegral (ord c) :: Word8)
get bh = do x <- get bh; return $! (chr (fromIntegral (x :: Word8)))
instance Binary Int where
#if SIZEOF_HSINT == 4
put_ bh i = put_ bh (fromIntegral i :: Int32)
get bh = do
x <- get bh
return $! (fromIntegral (x :: Int32))
#elif SIZEOF_HSINT == 8
put_ bh i = put_ bh (fromIntegral i :: Int64)
get bh = do
x <- get bh
return $! (fromIntegral (x :: Int64))
#else
#error "unsupported sizeof(HsInt)"
#endif
getF bh = getBitsF bh 32
instance Binary a => Binary [a] where
put_ bh list = do put_ bh (length list)
mapM_ (put_ bh) list
get bh = do len <- get bh
let getMany :: Int -> IO [a]
getMany 0 = return []
getMany n = do x <- get bh
xs <- getMany (n-1)
return (x:xs)
getMany len
instance (Binary a, Binary b) => Binary (a,b) where
put_ bh (a,b) = do put_ bh a; put_ bh b
get bh = do a <- get bh
b <- get bh
return (a,b)
instance (Binary a, Binary b, Binary c) => Binary (a,b,c) where
put_ bh (a,b,c) = do put_ bh a; put_ bh b; put_ bh c
get bh = do a <- get bh
b <- get bh
c <- get bh
return (a,b,c)
instance (Binary a, Binary b, Binary c, Binary d) => Binary (a,b,c,d) where
put_ bh (a,b,c,d) = do put_ bh a; put_ bh b; put_ bh c; put_ bh d
get bh = do a <- get bh
b <- get bh
c <- get bh
d <- get bh
return (a,b,c,d)
instance Binary a => Binary (Maybe a) where
put_ bh Nothing = putByte bh 0
put_ bh (Just a) = do putByte bh 1; put_ bh a
get bh = do h <- getWord8 bh
case h of
0 -> return Nothing
_ -> do x <- get bh; return (Just x)
instance (Binary a, Binary b) => Binary (Either a b) where
put_ bh (Left a) = do putByte bh 0; put_ bh a
put_ bh (Right b) = do putByte bh 1; put_ bh b
get bh = do h <- getWord8 bh
case h of
0 -> do a <- get bh ; return (Left a)
_ -> do b <- get bh ; return (Right b)
instance (Binary a, Binary i, Ix i) => Binary (Array i a) where
put_ bh arr = do put_ bh (Data.Array.bounds arr)
put_ bh (Data.Array.elems arr)
get bh = do bounds <- get bh
elems <- get bh
return $ listArray bounds elems
instance (Binary key, Ord key, Binary elem) => Binary (Map key elem) where
put _ bh fm = put _ bh ( Map.toList fm )
return ( Map.fromList list )
put_ bh fm = do let list = Map.toList fm
put_ bh (length list)
mapM_ (\(key, val) -> do put_ bh key
lazyPut bh val) list
get bh = do len <- get bh
let getMany :: Int -> IO [(key,elem)]
getMany 0 = return []
getMany n = do key <- get bh
val <- lazyGet bh
xs <- getMany (n-1)
return ((key,val):xs)
list <- getMany len
return (Map.fromList list)
#ifdef __GLASGOW_HASKELL__
#if __GLASGOW_HASKELL__<610
instance Binary Integer where
put_ bh (S# i#) = do putByte bh 0; put_ bh (I# i#)
put_ bh (J# s# a#) = do
p <- putByte bh 1;
put_ bh (I# s#)
putByteArray bh a# sz#
get bh = do
b <- getByte bh
case b of
0 -> do (I# i#) <- get bh
return (S# i#)
_ -> do (I# s#) <- get bh
sz <- get bh
(BA a#) <- getByteArray bh sz
return (J# s# a#)
putByteArray :: BinHandle -> ByteArray# -> Int# -> IO ()
putByteArray bh a s# = loop 0#
where loop n#
| n# ==# s# = return ()
| otherwise = do
putByte bh (indexByteArray a n#)
loop (n# +# 1#)
getByteArray :: BinHandle -> Int -> IO ByteArray
getByteArray bh (I# sz) = do
(MBA arr) <- newByteArray sz
let loop n
| n ==# sz = return ()
| otherwise = do
w <- getByte bh
writeByteArray arr n w
loop (n +# 1#)
loop 0#
freezeByteArray arr
data ByteArray = BA ByteArray#
data MBA = MBA (MutableByteArray# RealWorld)
newByteArray :: Int# -> IO MBA
newByteArray sz = IO $ \s ->
case newByteArray# sz s of { (# s, arr #) ->
(# s, MBA arr #) }
freezeByteArray :: MutableByteArray# RealWorld -> IO ByteArray
freezeByteArray arr = IO $ \s ->
case unsafeFreezeByteArray# arr s of { (# s, arr #) ->
(# s, BA arr #) }
writeByteArray :: MutableByteArray# RealWorld -> Int# -> Word8 -> IO ()
#if __GLASGOW_HASKELL__ < 503
writeByteArray arr i w8 = IO $ \s ->
case word8ToWord w8 of { W# w# ->
case writeCharArray# arr i (chr# (word2Int# w#)) s of { s ->
(# s , () #) }}
#else
writeByteArray arr i (W8# w) = IO $ \s ->
case writeWord8Array# arr i w s of { s ->
(# s, () #) }
#endif
#if __GLASGOW_HASKELL__ < 503
indexByteArray a# n# = fromIntegral (I# (ord# (indexCharArray# a# n#)))
#else
indexByteArray a# n# = W8# (indexWord8Array# a# n#)
#endif
instance (Integral a, Binary a) => Binary (Ratio a) where
put_ bh (a :% b) = do put_ bh a; put_ bh b
get bh = do a <- get bh; b <- get bh; return (a :% b)
#else
instance Binary Integer where
put_ h n = do
put h ((fromIntegral $ signum n) :: Int8)
when (n /= 0) $ do
let n' = abs n
nBytes = byteSize n'
put h (fromIntegral nBytes :: Word64)
mapM_ (putByte h) [ fromIntegral ((n' `shiftR` (b * 8)) .&. 0xff)
| b <- [ nBytes-1, nBytes-2 .. 0 ] ]
where byteSize n =
let f b = if (1 `shiftL` (b * 8)) > n
then b
else f (b + 1)
in f 0
get h = do
sign :: Int8 <- get h
if sign == 0
then return 0
else do
nBytes :: Word64 <- get h
n <- accumBytes nBytes 0
return $ fromIntegral sign * n
where accumBytes nBytes acc | nBytes == 0 = return acc
| otherwise = do
b <- getByte h
accumBytes (nBytes - 1) ((acc `shiftL` 8) .|. fromIntegral b)
#endif
#endif
instance Binary (Bin a) where
put_ bh (BinPtr i) = put_ bh i
get bh = do i <- get bh; return (BinPtr i)
lazyPut :: Binary a => BinHandle -> a -> IO ()
lazyPut bh a = do
pre_a <- tellBin bh
save a slot for the ptr
fill in slot before a with ptr to q
lazyGet :: Binary a => BinHandle -> IO a
lazyGet bh = do
a BinPtr
p_a <- tellBin bh
a <- unsafeInterleaveIO (getAt bh p_a)
return a
and should not know anything about BinHandles
initBinMemSize = (1024*1024) :: Int
binaryInterfaceMagic = 0x1face :: Word32
getBinFileWithDict :: Binary a => FilePath -> IO a
getBinFileWithDict file_path = do
bh <- Binary.readBinMem file_path
Read the magic number to check that this really is a GHC .hi file
GHC interface file format )
magic <- get bh
when (magic /= binaryInterfaceMagic) $
error "magic number mismatch: old/corrupt interface file?"
seekBin bh dict_p
dict <- getDictionary bh
Initialise the user - data field of bh
let bh' = setUserData bh (initReadState dict)
get bh'
putBinFileWithDict :: Binary a => FilePath -> a -> IO ()
putBinFileWithDict file_path the_thing = do
hnd < - openBinaryFile file_path WriteMode
bh <- openBinMem initBinMemSize
put_ bh binaryInterfaceMagic
dict_p_p <- tellBin bh
usr_state <- newWriteState
put_ (setUserData bh usr_state) the_thing
j <- readIORef (ud_next usr_state)
#if __GLASGOW_HASKELL__>=602
fm <- HashTable.toList (ud_map usr_state)
#else
fm <- liftM Map.toList $ readIORef (ud_map usr_state)
#endif
putDictionary bh j (constructDictionary j fm)
writeBinMem bh file_path
hClose hnd
UserData
data UserData =
ud_dict :: Dictionary,
The next two fields are only used when writing
#if __GLASGOW_HASKELL__>=602
# if __GLASGOW_HASKELL__>=707
# else
# endif
#else
ud_map :: IORef (Map String Int)
#endif
}
noUserData = error "Binary.UserData: no user data"
initReadState :: Dictionary -> UserData
initReadState dict = UserData{ ud_dict = dict,
ud_next = undef "next",
ud_map = undef "map" }
newWriteState :: IO UserData
newWriteState = do
j_r <- newIORef 0
#if __GLASGOW_HASKELL__>=602
# if __GLASGOW_HASKELL__>=707
out_r <- HashTable.new
# else
out_r <- HashTable.new (==) HashTable.hashString
# endif
#else
out_r <- newIORef Map.empty
#endif
return (UserData { ud_dict = error "dict",
ud_next = j_r,
ud_map = out_r })
undef s = error ("Binary.UserData: no " ++ s)
putDictionary :: BinHandle -> Int -> Dictionary -> IO ()
putDictionary bh sz dict = do
put_ bh sz
mapM_ (put_ bh) (elems dict)
getDictionary :: BinHandle -> IO Dictionary
getDictionary bh = do
sz <- get bh
elems <- sequence (take sz (repeat (get bh)))
return (listArray (0,sz-1) elems)
constructDictionary :: Int -> [(String,Int)] -> Dictionary
constructDictionary j fm = array (0,j-1) (map (\(x,y) -> (y,x)) fm)
Reading and writing memoised
putSharedString :: BinHandle -> String -> IO ()
putSharedString bh str =
case getUserData bh of
UserData { ud_next = j_r, ud_map = out_r, ud_dict = dict} -> do
#if __GLASGOW_HASKELL__>=602
entry <- HashTable.lookup out_r str
#else
fm <- readIORef out_r
let entry = Map.lookup str fm
#endif
case entry of
Just j -> put_ bh j
Nothing -> do
j <- readIORef j_r
put_ bh j
writeIORef j_r (j+1)
#if __GLASGOW_HASKELL__>=602
HashTable.insert out_r str j
#else
modifyIORef out_r (\fm -> Map.insert str j fm)
#endif
getSharedString :: BinHandle -> IO String
getSharedString bh = do
j <- get bh
return $! (ud_dict (getUserData bh) ! j)
putFS bh ( FastString i d l ba ) = do
put _ bh ( I # l )
putByteArray bh ba l
putFS bh s = error ( " Binary.put_(FastString ): " + + unpackFS s )
getFS bh@BinMem { } = do
( I # l ) < - get bh
arr < - readIORef ( arr_r bh )
off < - readFastMutInt ( off_r bh )
return $ ! ( mkFastSubStringBA # arr off l )
putFS bh (FastString id l ba) = do
put_ bh (I# l)
putByteArray bh ba l
putFS bh s = error ("Binary.put_(FastString): " ++ unpackFS s)
getFS bh = do
(I# l) <- get bh
(BA ba) <- getByteArray bh (I# l)
return $! (mkFastSubStringBA# ba 0# l)
instance Binary FastString where
put_ bh f@(FastString id l ba) =
case getUserData bh of {
UserData { ud_next = j_r, ud_map = out_r, ud_dict = dict} -> do
out <- readIORef out_r
let uniq = getUnique f
case lookupUFM out uniq of
Just (j,f) -> put_ bh j
Nothing -> do
j <- readIORef j_r
put_ bh j
writeIORef j_r (j+1)
writeIORef out_r (addToUFM out uniq (j,f))
}
put_ bh s = error ("Binary.put_(FastString): " ++ show (unpackFS s))
get bh = do
j <- get bh
return $! (ud_dict (getUserData bh) ! j)
-}
printElapsedTime :: String -> IO ()
printElapsedTime msg = do
time <- getCPUTime
hPutStr stderr $ "elapsed time: " ++ Numeric.showFFloat (Just 2) ((fromIntegral time) / 10^12) " (" ++ msg ++ ")\n"
|
14b600fe9eec451f2347c44ebf479bb853c1bff151970e43265b005fed580b36
|
haskell-suite/haskell-src-exts
|
IndentedWhereBlock.hs
|
module Graph where
countryLookUp :: String -> Graph -> Maybe Int
countryLookUp country graph = indexOf country graph where
indexOf :: String -> Graph -> Maybe Int
indexOf _ Empty = Nothing
| null |
https://raw.githubusercontent.com/haskell-suite/haskell-src-exts/84a4930e0e5c051b7d9efd20ef7c822d5fc1c33b/tests/examples/IndentedWhereBlock.hs
|
haskell
|
module Graph where
countryLookUp :: String -> Graph -> Maybe Int
countryLookUp country graph = indexOf country graph where
indexOf :: String -> Graph -> Maybe Int
indexOf _ Empty = Nothing
|
|
6c71c5610e704538f3083a43b40637b5748c83366f1a34071ec0b62841d69ee3
|
sacerdot/CovidMonitoring
|
luoghi.erl
|
-module(luoghi).
-export([start/0, luogo/0, init_luogo/1, visit_place/2]).
-import(utils, [sleep/1, set_subtract/2, make_probability/1, check_service/1]).
%%%%%%%%%%%%%%%%%%%%%%%%%%% PROTOCOLLO DI INIZIALIZZAZIONE %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
init_luogo(Prob) ->
PidServer = check_service(server),
PidServer ! {ciao, da, luogo, self()},
link(PidServer),
process_flag(trap_exit, true),
PidServer ! {new_place, self()},
visit_place([], Prob).
PROTOCOLLO DI VISITA DEI LUOGHI % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % %
visit_place(L, Probs) ->
receive
{begin_visit, PID, Ref} ->
MRef = monitor(process, PID),
% PidOldUser can die
[contact(PID, PidOldUser, Probs(contact_tracing)) || {PidOldUser, _, _} <- L],
check_for_closing(Probs(check_for_closing)),
visit_place([{PID, Ref, MRef} | L], Probs);
{end_visit, PID, Ref} ->
case [MR || {Pid, _, MR} <- L, Pid =:= PID] of
[MRef] ->
demonitor(MRef),
visit_place(set_subtract(L, [{PID, Ref, MRef}]), Probs);
_ -> visit_place(L, Probs)
end;
{'DOWN', MRef, process, PidExit, Reason} ->
case [{R, MR} || {Pid, R, MR} <- L, Pid =:= PidExit] of
[{Ref, MRef}] ->
io:format("[Luogo] ~p Utente ~p con Ref ~p morto per ~p ~n", [self(), PidExit, Ref, Reason]),
visit_place(set_subtract(L, [{PidExit, Ref, MRef}]), Probs);
_ ->
io:format("[Luogo] ~p Utente ~p non presente in lista~n", [self(), PidExit]),
visit_place(L, Probs)
end
end.
PROTOCOLLO DI RILEVAMENTO DEI CONTATTI % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % %
contact(NewUser, PidOldUser, Prob) ->
case Prob() of
true ->
NewUser ! {contact, PidOldUser},
io:format("[Luogo] ~p Contatto da ~p a ~p~n", [self(), NewUser, PidOldUser]);
false -> ok
end.
CICLO DI VITA % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % %
check_for_closing(Prob) ->
case Prob() of
true -> exit(normal);
false -> ok
end.
get_probs() ->
Probs = #{contact_tracing => make_probability(25), check_for_closing => make_probability(10)},
fun(X) ->
maps:get(X, Probs)
end.
luogo() ->
io:format("Io sono il luogo ~p~n", [self()]),
init_luogo(get_probs()).
start() ->
[spawn(fun luogo/0) || _ <- lists:seq(1, 1000)].
| null |
https://raw.githubusercontent.com/sacerdot/CovidMonitoring/fe969cd51869bbe6479da509c9a6ab21d43e6d11/BartoliniFapohundaGuerra/src/luoghi.erl
|
erlang
|
PROTOCOLLO DI INIZIALIZZAZIONE %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % %
PidOldUser can die
% % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % %
% % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % %
|
-module(luoghi).
-export([start/0, luogo/0, init_luogo/1, visit_place/2]).
-import(utils, [sleep/1, set_subtract/2, make_probability/1, check_service/1]).
init_luogo(Prob) ->
PidServer = check_service(server),
PidServer ! {ciao, da, luogo, self()},
link(PidServer),
process_flag(trap_exit, true),
PidServer ! {new_place, self()},
visit_place([], Prob).
visit_place(L, Probs) ->
receive
{begin_visit, PID, Ref} ->
MRef = monitor(process, PID),
[contact(PID, PidOldUser, Probs(contact_tracing)) || {PidOldUser, _, _} <- L],
check_for_closing(Probs(check_for_closing)),
visit_place([{PID, Ref, MRef} | L], Probs);
{end_visit, PID, Ref} ->
case [MR || {Pid, _, MR} <- L, Pid =:= PID] of
[MRef] ->
demonitor(MRef),
visit_place(set_subtract(L, [{PID, Ref, MRef}]), Probs);
_ -> visit_place(L, Probs)
end;
{'DOWN', MRef, process, PidExit, Reason} ->
case [{R, MR} || {Pid, R, MR} <- L, Pid =:= PidExit] of
[{Ref, MRef}] ->
io:format("[Luogo] ~p Utente ~p con Ref ~p morto per ~p ~n", [self(), PidExit, Ref, Reason]),
visit_place(set_subtract(L, [{PidExit, Ref, MRef}]), Probs);
_ ->
io:format("[Luogo] ~p Utente ~p non presente in lista~n", [self(), PidExit]),
visit_place(L, Probs)
end
end.
contact(NewUser, PidOldUser, Prob) ->
case Prob() of
true ->
NewUser ! {contact, PidOldUser},
io:format("[Luogo] ~p Contatto da ~p a ~p~n", [self(), NewUser, PidOldUser]);
false -> ok
end.
check_for_closing(Prob) ->
case Prob() of
true -> exit(normal);
false -> ok
end.
get_probs() ->
Probs = #{contact_tracing => make_probability(25), check_for_closing => make_probability(10)},
fun(X) ->
maps:get(X, Probs)
end.
luogo() ->
io:format("Io sono il luogo ~p~n", [self()]),
init_luogo(get_probs()).
start() ->
[spawn(fun luogo/0) || _ <- lists:seq(1, 1000)].
|
c1ba1e99c9988211d0131c004729095b3719a7c14eb2ae98ef6a91c902578c89
|
luisgabriel/erl-chat-server
|
chat_server.erl
|
-module(chat_server).
-export([start/1, pre_loop/1]).
start(Port) ->
controller:start(),
tcp_server:start(?MODULE, Port, {?MODULE, pre_loop}).
pre_loop(Socket) ->
case gen_tcp:recv(Socket, 0) of
{ok, Data} ->
io:format("Data: ~p~n", [binary_to_list(Data)]),
Message = binary_to_list(Data),
{Command, [_|Nick]} = lists:splitwith(fun(T) -> [T] =/= ":" end, Message),
io:format("Nick: ~p~n", [Nick]),
case Command of
"CONNECT" ->
try_connection(clean(Nick), Socket);
_ ->
gen_tcp:send(Socket, "Unknown command!\n"),
ok
end;
{error, closed} ->
ok
end.
try_connection(Nick, Socket) ->
Response = gen_server:call(controller, {connect, Nick, Socket}),
case Response of
{ok, List} ->
gen_tcp:send(Socket, "CONNECT:OK:" ++ List ++ "\n"),
gen_server:cast(controller, {join, Nick}),
loop(Nick, Socket);
nick_in_use ->
gen_tcp:send(Socket, "CONNECT:ERROR:Nick in use.\n"),
ok
end.
loop(Nick, Socket) ->
case gen_tcp:recv(Socket, 0) of
{ok, Data} ->
io:format("Data: ~p~n", [binary_to_list(Data)]),
Message = binary_to_list(Data),
{Command, [_|Content]} = lists:splitwith(fun(T) -> [T] =/= ":" end, Message),
case Command of
"SAY" ->
say(Nick, Socket, clean(Content));
"PVT" ->
{ReceiverNick, [_|Msg]} = lists:splitwith(fun(T) -> [T] =/= ":" end, Content),
private_message(Nick, Socket, ReceiverNick, clean(Msg));
"QUIT" ->
quit(Nick, Socket)
end;
{error, closed} ->
ok
end.
say(Nick, Socket, Content) ->
gen_server:cast(controller, {say, Nick, Content}),
loop(Nick, Socket).
private_message(Nick, Socket, ReceiverNick, Msg) ->
gen_server:cast(controller, {private_message, Nick, ReceiverNick, Msg}),
loop(Nick, Socket).
quit(Nick, Socket) ->
Response = gen_server:call(controller, {disconnect, Nick}),
case Response of
ok ->
gen_tcp:send(Socket, "Bye.\n"),
gen_server:cast(controller, {left, Nick}),
ok;
user_not_found ->
gen_tcp:send(Socket, "Bye with errors.\n"),
ok
end.
clean(Data) ->
string:strip(Data, both, $\n).
| null |
https://raw.githubusercontent.com/luisgabriel/erl-chat-server/fcc972fec727e7a9f1bb9a82a99a34262860f59a/src/chat_server.erl
|
erlang
|
-module(chat_server).
-export([start/1, pre_loop/1]).
start(Port) ->
controller:start(),
tcp_server:start(?MODULE, Port, {?MODULE, pre_loop}).
pre_loop(Socket) ->
case gen_tcp:recv(Socket, 0) of
{ok, Data} ->
io:format("Data: ~p~n", [binary_to_list(Data)]),
Message = binary_to_list(Data),
{Command, [_|Nick]} = lists:splitwith(fun(T) -> [T] =/= ":" end, Message),
io:format("Nick: ~p~n", [Nick]),
case Command of
"CONNECT" ->
try_connection(clean(Nick), Socket);
_ ->
gen_tcp:send(Socket, "Unknown command!\n"),
ok
end;
{error, closed} ->
ok
end.
try_connection(Nick, Socket) ->
Response = gen_server:call(controller, {connect, Nick, Socket}),
case Response of
{ok, List} ->
gen_tcp:send(Socket, "CONNECT:OK:" ++ List ++ "\n"),
gen_server:cast(controller, {join, Nick}),
loop(Nick, Socket);
nick_in_use ->
gen_tcp:send(Socket, "CONNECT:ERROR:Nick in use.\n"),
ok
end.
loop(Nick, Socket) ->
case gen_tcp:recv(Socket, 0) of
{ok, Data} ->
io:format("Data: ~p~n", [binary_to_list(Data)]),
Message = binary_to_list(Data),
{Command, [_|Content]} = lists:splitwith(fun(T) -> [T] =/= ":" end, Message),
case Command of
"SAY" ->
say(Nick, Socket, clean(Content));
"PVT" ->
{ReceiverNick, [_|Msg]} = lists:splitwith(fun(T) -> [T] =/= ":" end, Content),
private_message(Nick, Socket, ReceiverNick, clean(Msg));
"QUIT" ->
quit(Nick, Socket)
end;
{error, closed} ->
ok
end.
say(Nick, Socket, Content) ->
gen_server:cast(controller, {say, Nick, Content}),
loop(Nick, Socket).
private_message(Nick, Socket, ReceiverNick, Msg) ->
gen_server:cast(controller, {private_message, Nick, ReceiverNick, Msg}),
loop(Nick, Socket).
quit(Nick, Socket) ->
Response = gen_server:call(controller, {disconnect, Nick}),
case Response of
ok ->
gen_tcp:send(Socket, "Bye.\n"),
gen_server:cast(controller, {left, Nick}),
ok;
user_not_found ->
gen_tcp:send(Socket, "Bye with errors.\n"),
ok
end.
clean(Data) ->
string:strip(Data, both, $\n).
|
|
203c8ba44083a5396f9154b85283b25d03338a4406b2f817d76991633c075b56
|
symbiont-io/detsys-testkit
|
Random.hs
|
module Lec05.Random where
import Data.IORef
import System.Random (StdGen, setStdGen, getStdGen, mkStdGen, randomR, randomIO)
import qualified System.Random
------------------------------------------------------------------------
data Random = Random
{ rGetStdGen :: IO StdGen
, rSetStdGen :: StdGen -> IO ()
}
newtype Seed = Seed { unSeed :: Int }
realRandom :: IO Random
realRandom =
return Random
{ rGetStdGen = getStdGen
, rSetStdGen = setStdGen
}
fakeRandom :: Seed -> IO Random
fakeRandom (Seed seed) = do
let g = mkStdGen seed
r <- newIORef g
return Random
{ rGetStdGen = readIORef r
, rSetStdGen = writeIORef r
}
randomInterval :: System.Random.Random a => Random -> (a, a) -> IO a
randomInterval random range = do
g <- rGetStdGen random
let (x, g') = randomR range g
rSetStdGen random g'
return x
generateSeeds :: Int -> IO [Seed]
generateSeeds nr = mapM (\_ -> fmap Seed randomIO) [1..nr]
data RandomDist
= Uniform Double Double
| Exponential Double
defaultRandomDist :: RandomDist
defaultRandomDist = Exponential 0.5
randomFromDist :: Random -> RandomDist -> IO Double
randomFromDist random (Uniform minV maxV) = do
randomInterval random (minV, maxV)
randomFromDist random (Exponential lambda) = do
-- #Examples
y <- randomInterval random (0.0, 1.0 :: Double)
return $ -1/lambda*log (1 - y)
| null |
https://raw.githubusercontent.com/symbiont-io/detsys-testkit/96a66b307a2481f85a9c75977b23f35d9b1054db/doc/advanced-testing-mini-course/src/Lec05/Random.hs
|
haskell
|
----------------------------------------------------------------------
#Examples
|
module Lec05.Random where
import Data.IORef
import System.Random (StdGen, setStdGen, getStdGen, mkStdGen, randomR, randomIO)
import qualified System.Random
data Random = Random
{ rGetStdGen :: IO StdGen
, rSetStdGen :: StdGen -> IO ()
}
newtype Seed = Seed { unSeed :: Int }
realRandom :: IO Random
realRandom =
return Random
{ rGetStdGen = getStdGen
, rSetStdGen = setStdGen
}
fakeRandom :: Seed -> IO Random
fakeRandom (Seed seed) = do
let g = mkStdGen seed
r <- newIORef g
return Random
{ rGetStdGen = readIORef r
, rSetStdGen = writeIORef r
}
randomInterval :: System.Random.Random a => Random -> (a, a) -> IO a
randomInterval random range = do
g <- rGetStdGen random
let (x, g') = randomR range g
rSetStdGen random g'
return x
generateSeeds :: Int -> IO [Seed]
generateSeeds nr = mapM (\_ -> fmap Seed randomIO) [1..nr]
data RandomDist
= Uniform Double Double
| Exponential Double
defaultRandomDist :: RandomDist
defaultRandomDist = Exponential 0.5
randomFromDist :: Random -> RandomDist -> IO Double
randomFromDist random (Uniform minV maxV) = do
randomInterval random (minV, maxV)
randomFromDist random (Exponential lambda) = do
y <- randomInterval random (0.0, 1.0 :: Double)
return $ -1/lambda*log (1 - y)
|
548fdd456aeb9f36a766c7d9f73cc734cd5435160cf911c5de626a0672c32fcb
|
jordwalke/rehp
|
annot_parser.mli
|
(* The type of tokens. *)
type token =
| TWeakdef
| TVersion
| TVNum of (string)
| TSemi
| TRequires
| TProvides
| TOTHER of (string)
| TIdent of (string)
| TComma
| TA_Shallow
| TA_Pure
| TA_Object_literal
| TA_Mutator
| TA_Mutable
| TA_Const
| RPARENT
| LT
| LPARENT
| LE
| GT
| GE
| EQ
| EOL
| EOF
(* This exception is raised by the monolithic API functions. *)
exception Error
(* The monolithic API. *)
val annot: (Lexing.lexbuf -> token) -> Lexing.lexbuf -> (Primitive.t)
| null |
https://raw.githubusercontent.com/jordwalke/rehp/f122b94f0a3f06410ddba59e3c9c603b33aadabf/compiler/lib/annot_parser.mli
|
ocaml
|
The type of tokens.
This exception is raised by the monolithic API functions.
The monolithic API.
|
type token =
| TWeakdef
| TVersion
| TVNum of (string)
| TSemi
| TRequires
| TProvides
| TOTHER of (string)
| TIdent of (string)
| TComma
| TA_Shallow
| TA_Pure
| TA_Object_literal
| TA_Mutator
| TA_Mutable
| TA_Const
| RPARENT
| LT
| LPARENT
| LE
| GT
| GE
| EQ
| EOL
| EOF
exception Error
val annot: (Lexing.lexbuf -> token) -> Lexing.lexbuf -> (Primitive.t)
|
b757e0cbb982ff044af2b567ddfaf300b42b5428e1a6bbdccfa2107d7b31dbd7
|
frex-project/metaocaml-frex
|
monoids.mli
|
module S : Aux.Sig with module Ops := Algebra.Monoid_ops
module Coproduct_monoid (A : S.Algebra) (B : S.Algebra) :
S.COPRODUCT with module A.T = A.T with module B.T = B.T
module Free_monoid (A : Algebra.TYPE) :
Algebra.MONOID with type t = A.t list
module PS_monoid (A : Algebra.MONOID)
(C : Algebra.MONOID with type t = A.t code) : S.PS with type A.T.t = A.t
| null |
https://raw.githubusercontent.com/frex-project/metaocaml-frex/e249551a41bd6a8af1a95d77bf9946822a19e3b0/lib/monoids.mli
|
ocaml
|
module S : Aux.Sig with module Ops := Algebra.Monoid_ops
module Coproduct_monoid (A : S.Algebra) (B : S.Algebra) :
S.COPRODUCT with module A.T = A.T with module B.T = B.T
module Free_monoid (A : Algebra.TYPE) :
Algebra.MONOID with type t = A.t list
module PS_monoid (A : Algebra.MONOID)
(C : Algebra.MONOID with type t = A.t code) : S.PS with type A.T.t = A.t
|
|
cc539ae019bed589f1f39e1e56e8ef018683351c86e24e67021271f472503798
|
joedevivo/chatterbox
|
h2_connection.erl
|
-module(h2_connection).
-include("http2.hrl").
-behaviour(gen_statem).
Start / Stop API
-export([
start_client/2,
start_client/5,
start_client_link/2,
start_client_link/5,
start_ssl_upgrade_link/5,
start_server_link/3,
become/1,
become/2,
become/3,
stop/1
]).
%% HTTP Operations
-export([
send_headers/3,
send_headers/4,
send_trailers/3,
send_trailers/4,
send_body/3,
send_body/4,
send_request/3,
send_ping/1,
is_push/1,
new_stream/1,
new_stream/2,
send_promise/4,
get_response/2,
get_peer/1,
get_peercert/1,
get_streams/1,
send_window_update/2,
update_settings/2,
send_frame/2
]).
%% gen_statem callbacks
-export(
[
init/1,
callback_mode/0,
code_change/4,
terminate/3
]).
%% gen_statem states
-export([
listen/3,
handshake/3,
connected/3,
continuation/3,
closing/3
]).
-export([
go_away/2
]).
-record(h2_listening_state, {
ssl_options :: [ssl:ssl_option()],
listen_socket :: ssl:sslsocket() | inet:socket(),
transport :: gen_tcp | ssl,
listen_ref :: non_neg_integer(),
acceptor_callback = fun chatterbox_sup:start_socket/0 :: fun(),
server_settings = #settings{} :: settings()
}).
-record(continuation_state, {
stream_id :: stream_id(),
promised_id = undefined :: undefined | stream_id(),
frames = queue:new() :: queue:queue(h2_frame:frame()),
type :: headers | push_promise | trailers,
end_stream = false :: boolean(),
end_headers = false :: boolean()
}).
-record(connection, {
type = undefined :: client | server | undefined,
ssl_options = [],
listen_ref :: non_neg_integer() | undefined,
socket = undefined :: sock:socket(),
peer_settings = #settings{} :: settings(),
self_settings = #settings{} :: settings(),
send_window_size = ?DEFAULT_INITIAL_WINDOW_SIZE :: integer(),
recv_window_size = ?DEFAULT_INITIAL_WINDOW_SIZE :: integer(),
decode_context = hpack:new_context() :: hpack:context(),
encode_context = hpack:new_context() :: hpack:context(),
settings_sent = queue:new() :: queue:queue(),
next_available_stream_id = 2 :: stream_id(),
streams :: h2_stream_set:stream_set(),
stream_callback_mod = application:get_env(chatterbox, stream_callback_mod, chatterbox_static_stream) :: module(),
stream_callback_opts = application:get_env(chatterbox, stream_callback_opts, []) :: list(),
buffer = empty :: empty | {binary, binary()} | {frame, h2_frame:header(), binary()},
continuation = undefined :: undefined | #continuation_state{},
flow_control = auto :: auto | manual,
pings = #{} :: #{binary() => {pid(), non_neg_integer()}}
}).
-type connection() :: #connection{}.
-type send_option() :: {send_end_stream, boolean()}.
-type send_opts() :: [send_option()].
-export_type([send_option/0, send_opts/0]).
-ifdef(OTP_RELEASE).
-define(ssl_accept(ClientSocket, SSLOptions), ssl:handshake(ClientSocket, SSLOptions)).
-else.
-define(ssl_accept(ClientSocket, SSLOptions), ssl:ssl_accept(ClientSocket, SSLOptions)).
-endif.
-spec start_client_link(gen_tcp | ssl,
inet:ip_address() | inet:hostname(),
inet:port_number(),
[ssl:ssl_option()],
settings()
) ->
{ok, pid()} | ignore | {error, term()}.
start_client_link(Transport, Host, Port, SSLOptions, Http2Settings) ->
gen_statem:start_link(?MODULE, {client, Transport, Host, Port, SSLOptions, Http2Settings}, []).
-spec start_client(gen_tcp | ssl,
inet:ip_address() | inet:hostname(),
inet:port_number(),
[ssl:ssl_option()],
settings()
) ->
{ok, pid()} | ignore | {error, term()}.
start_client(Transport, Host, Port, SSLOptions, Http2Settings) ->
gen_statem:start(?MODULE, {client, Transport, Host, Port, SSLOptions, Http2Settings}, []).
-spec start_client_link(socket(),
settings()
) ->
{ok, pid()} | ignore | {error, term()}.
start_client_link({Transport, Socket}, Http2Settings) ->
gen_statem:start_link(?MODULE, {client, {Transport, Socket}, Http2Settings}, []).
-spec start_client(socket(),
settings()
) ->
{ok, pid()} | ignore | {error, term()}.
start_client({Transport, Socket}, Http2Settings) ->
gen_statem:start(?MODULE, {client, {Transport, Socket}, Http2Settings}, []).
-spec start_ssl_upgrade_link(inet:ip_address() | inet:hostname(),
inet:port_number(),
binary(),
[ssl:ssl_option()],
settings()
) ->
{ok, pid()} | ignore | {error, term()}.
start_ssl_upgrade_link(Host, Port, InitialMessage, SSLOptions, Http2Settings) ->
gen_statem:start_link(?MODULE, {client_ssl_upgrade, Host, Port, InitialMessage, SSLOptions, Http2Settings}, []).
-spec start_server_link(socket(),
[ssl:ssl_option()],
settings()) ->
{ok, pid()} | ignore | {error, term()}.
start_server_link({Transport, ListenSocket}, SSLOptions, Http2Settings) ->
gen_statem:start_link(?MODULE, {server, {Transport, ListenSocket}, SSLOptions, Http2Settings}, []).
-spec become(socket()) -> no_return().
become(Socket) ->
become(Socket, chatterbox:settings(server)).
-spec become(socket(), settings()) -> no_return().
become(Socket, Http2Settings) ->
become(Socket, Http2Settings, #{}).
-spec become(socket(), settings(), maps:map()) -> no_return().
become({Transport, Socket}, Http2Settings, ConnectionSettings) ->
ok = sock:setopts({Transport, Socket}, [{packet, raw}, binary]),
case start_http2_server(Http2Settings,
#connection{
stream_callback_mod =
maps:get(stream_callback_mod, ConnectionSettings,
application:get_env(chatterbox, stream_callback_mod, chatterbox_static_stream)),
stream_callback_opts =
maps:get(stream_callback_opts, ConnectionSettings,
application:get_env(chatterbox, stream_callback_opts, [])),
streams = h2_stream_set:new(server),
socket = {Transport, Socket}
}) of
{_, handshake, NewState} ->
gen_statem:enter_loop(?MODULE,
[],
handshake,
NewState);
{_, closing, _NewState} ->
sock:close({Transport, Socket}),
exit(invalid_preface)
end.
Init callback
init({client, Transport, Host, Port, SSLOptions, Http2Settings}) ->
case Transport:connect(Host, Port, client_options(Transport, SSLOptions)) of
{ok, Socket} ->
init({client, {Transport, Socket}, Http2Settings});
{error, Reason} ->
{stop, Reason}
end;
init({client, {Transport, Socket}, Http2Settings}) ->
ok = sock:setopts({Transport, Socket}, [{packet, raw}, binary, {active, once}]),
Transport:send(Socket, <<?PREFACE>>),
InitialState =
#connection{
type = client,
streams = h2_stream_set:new(client),
socket = {Transport, Socket},
next_available_stream_id=1,
flow_control=application:get_env(chatterbox, client_flow_control, auto)
},
{ok,
handshake,
send_settings(Http2Settings, InitialState),
4500};
init({client_ssl_upgrade, Host, Port, InitialMessage, SSLOptions, Http2Settings}) ->
case gen_tcp:connect(Host, Port, [{active, false}]) of
{ok, TCP} ->
gen_tcp:send(TCP, InitialMessage),
case ssl:connect(TCP, client_options(ssl, SSLOptions)) of
{ok, Socket} ->
init({client, {ssl, Socket}, Http2Settings});
{error, Reason} ->
{stop, Reason}
end;
{error, Reason} ->
{stop, Reason}
end;
init({server, {Transport, ListenSocket}, SSLOptions, Http2Settings}) ->
%% prim_inet:async_accept is dope. It says just hang out here and
%% wait for a message that a client has connected. That message
%% looks like:
{ inet_async , ListenSocket , Ref , { ok , ClientSocket } }
case prim_inet:async_accept(ListenSocket, -1) of
{ok, Ref} ->
{ok,
listen,
#h2_listening_state{
ssl_options = SSLOptions,
listen_socket = ListenSocket,
listen_ref = Ref,
transport = Transport,
server_settings = Http2Settings
}}; %% No timeout here, it's just a listener
{error, Reason} ->
{stop, Reason}
end.
callback_mode() ->
state_functions.
send_frame(Pid, Bin)
when is_binary(Bin); is_list(Bin) ->
gen_statem:cast(Pid, {send_bin, Bin});
send_frame(Pid, Frame) ->
gen_statem:cast(Pid, {send_frame, Frame}).
-spec send_headers(pid(), stream_id(), hpack:headers()) -> ok.
send_headers(Pid, StreamId, Headers) ->
gen_statem:cast(Pid, {send_headers, StreamId, Headers, []}),
ok.
-spec send_headers(pid(), stream_id(), hpack:headers(), send_opts()) -> ok.
send_headers(Pid, StreamId, Headers, Opts) ->
gen_statem:cast(Pid, {send_headers, StreamId, Headers, Opts}),
ok.
-spec send_trailers(pid(), stream_id(), hpack:headers()) -> ok.
send_trailers(Pid, StreamId, Trailers) ->
gen_statem:cast(Pid, {send_trailers, StreamId, Trailers, []}),
ok.
-spec send_trailers(pid(), stream_id(), hpack:headers(), send_opts()) -> ok.
send_trailers(Pid, StreamId, Trailers, Opts) ->
gen_statem:cast(Pid, {send_trailers, StreamId, Trailers, Opts}),
ok.
-spec send_body(pid(), stream_id(), binary()) -> ok.
send_body(Pid, StreamId, Body) ->
gen_statem:cast(Pid, {send_body, StreamId, Body, []}),
ok.
-spec send_body(pid(), stream_id(), binary(), send_opts()) -> ok.
send_body(Pid, StreamId, Body, Opts) ->
gen_statem:cast(Pid, {send_body, StreamId, Body, Opts}),
ok.
-spec send_request(pid(), hpack:headers(), binary()) -> ok.
send_request(Pid, Headers, Body) ->
gen_statem:call(Pid, {send_request, self(), Headers, Body}, infinity),
ok.
-spec send_ping(pid()) -> ok.
send_ping(Pid) ->
gen_statem:call(Pid, {send_ping, self()}, infinity),
ok.
-spec get_peer(pid()) ->
{ok, {inet:ip_address(), inet:port_number()}} | {error, term()}.
get_peer(Pid) ->
gen_statem:call(Pid, get_peer).
-spec get_peercert(pid()) ->
{ok, binary()} | {error, term()}.
get_peercert(Pid) ->
gen_statem:call(Pid, get_peercert).
-spec is_push(pid()) -> boolean().
is_push(Pid) ->
gen_statem:call(Pid, is_push).
-spec new_stream(pid()) -> stream_id() | {error, error_code()}.
new_stream(Pid) ->
new_stream(Pid, self()).
-spec new_stream(pid(), pid()) ->
stream_id()
| {error, error_code()}.
new_stream(Pid, NotifyPid) ->
gen_statem:call(Pid, {new_stream, NotifyPid}).
-spec send_promise(pid(), stream_id(), stream_id(), hpack:headers()) -> ok.
send_promise(Pid, StreamId, NewStreamId, Headers) ->
gen_statem:cast(Pid, {send_promise, StreamId, NewStreamId, Headers}),
ok.
-spec get_response(pid(), stream_id()) ->
{ok, {hpack:headers(), iodata()}}
| not_ready.
get_response(Pid, StreamId) ->
gen_statem:call(Pid, {get_response, StreamId}).
-spec get_streams(pid()) -> h2_stream_set:stream_set().
get_streams(Pid) ->
gen_statem:call(Pid, streams).
-spec send_window_update(pid(), non_neg_integer()) -> ok.
send_window_update(Pid, Size) ->
gen_statem:cast(Pid, {send_window_update, Size}).
-spec update_settings(pid(), h2_frame_settings:payload()) -> ok.
update_settings(Pid, Payload) ->
gen_statem:cast(Pid, {update_settings, Payload}).
-spec stop(pid()) -> ok.
stop(Pid) ->
gen_statem:cast(Pid, stop).
%% The listen state only exists to wait around for new prim_inet
%% connections
listen(info, {inet_async, ListenSocket, Ref, {ok, ClientSocket}},
#h2_listening_state{
listen_socket = ListenSocket,
listen_ref = Ref,
transport = Transport,
ssl_options = SSLOptions,
acceptor_callback = AcceptorCallback,
server_settings = Http2Settings
}) ->
%If anything crashes in here, at least there's another acceptor ready
AcceptorCallback(),
inet_db:register_socket(ClientSocket, inet_tcp),
Socket = case Transport of
gen_tcp ->
ClientSocket;
ssl ->
{ok, AcceptSocket} = ?ssl_accept(ClientSocket, SSLOptions),
{ok, <<"h2">>} = ssl:negotiated_protocol(AcceptSocket),
AcceptSocket
end,
start_http2_server(
Http2Settings,
#connection{
streams = h2_stream_set:new(server),
socket={Transport, Socket}
});
listen(timeout, _, State) ->
go_away(?PROTOCOL_ERROR, State);
listen(Type, Msg, State) ->
handle_event(Type, Msg, State).
-spec handshake(gen_statem:event_type(), {frame, h2_frame:frame()} | term(), connection()) ->
{next_state,
handshake|connected|closing,
connection()}.
handshake(timeout, _, State) ->
go_away(?PROTOCOL_ERROR, State);
handshake(_, {frame, {FH, _Payload}=Frame}, State) ->
The first frame should be the client settings as per
case FH#frame_header.type of
?SETTINGS ->
route_frame(Frame, State);
_ ->
go_away(?PROTOCOL_ERROR, State)
end;
handshake(Type, Msg, State) ->
handle_event(Type, Msg, State).
connected(_, {frame, Frame},
#connection{}=Conn
) ->
route_frame(Frame, Conn);
connected(Type, Msg, State) ->
handle_event(Type, Msg, State).
%% The continuation state in entered after receiving a HEADERS frame
%% with no ?END_HEADERS flag set, we're locked waiting for contiunation
%% frames on the same stream to preserve the decoding context state
continuation(_, {frame,
{#frame_header{
stream_id=StreamId,
type=?CONTINUATION
}, _}=Frame},
#connection{
continuation = #continuation_state{
stream_id = StreamId
}
}=Conn) ->
route_frame(Frame, Conn);
continuation(Type, Msg, State) ->
handle_event(Type, Msg, State).
%% The closing state should deal with frames on the wire still, I
%% think. But we should just close it up now.
closing(_, _Message,
#connection{
socket=Socket
}=Conn) ->
sock:close(Socket),
{stop, normal, Conn};
closing(Type, Msg, State) ->
handle_event(Type, Msg, State).
route_frame 's job needs to be " now that we 've read a frame off the
%% wire, do connection based things to it and/or forward it to the
http2 stream processor ( h2_stream : recv_frame )
-spec route_frame(
h2_frame:frame() | {error, term()},
connection()) ->
{next_state,
connected | continuation | closing ,
connection()}.
%% Bad Length of frame, exceedes maximum allowed size
route_frame({#frame_header{length=L}, _},
#connection{
self_settings=#settings{max_frame_size=MFS}
}=Conn)
when L > MFS ->
go_away(?FRAME_SIZE_ERROR, Conn);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Connection Level Frames
%%
%% Here we'll handle anything that belongs on stream 0.
%% SETTINGS, finally something that's ok on stream 0
%% This is the non-ACK case, where settings have actually arrived
route_frame({H, Payload},
#connection{
peer_settings=PS=#settings{
initial_window_size=OldIWS,
header_table_size=HTS
},
streams=Streams,
encode_context=EncodeContext
}=Conn)
when H#frame_header.type == ?SETTINGS,
?NOT_FLAG((H#frame_header.flags), ?FLAG_ACK) ->
%% Need a way of processing settings so I know which ones came in
on this one payload .
case h2_frame_settings:validate(Payload) of
ok ->
{settings, PList} = Payload,
Delta =
case proplists:get_value(?SETTINGS_INITIAL_WINDOW_SIZE, PList) of
undefined ->
0;
NewIWS ->
NewIWS - OldIWS
end,
NewPeerSettings = h2_frame_settings:overlay(PS, Payload),
%% We've just got connection settings from a peer. He have a
%% couple of jobs to do here w.r.t. flow control
If Delta ! = 0 , we need to change every stream 's
%% send_window_size in the state open or
half_closed_remote . We 'll just send the message
%% everywhere. It's up to them if they need to do
%% anything.
UpdatedStreams1 =
h2_stream_set:update_all_send_windows(Delta, Streams),
UpdatedStreams2 =
case proplists:get_value(?SETTINGS_MAX_CONCURRENT_STREAMS, PList) of
undefined ->
UpdatedStreams1;
NewMax ->
h2_stream_set:update_my_max_active(NewMax, UpdatedStreams1)
end,
NewEncodeContext = hpack:new_max_table_size(HTS, EncodeContext),
socksend(Conn, h2_frame_settings:ack()),
{next_state, connected, Conn#connection{
peer_settings=NewPeerSettings,
Why are n't we updating send_window_size here ? Section 6.9.2 of
%% the spec says: "The connection flow-control window can only be
%% changed using WINDOW_UPDATE frames.",
encode_context=NewEncodeContext,
streams=UpdatedStreams2
}};
{error, Code} ->
go_away(Code, Conn)
end;
%% This is the case where we got an ACK, so dequeue settings we're
%% waiting to apply
route_frame({H, _Payload},
#connection{
settings_sent=SS,
streams=Streams,
self_settings=#settings{
initial_window_size=OldIWS
}
}=Conn)
when H#frame_header.type == ?SETTINGS,
?IS_FLAG((H#frame_header.flags), ?FLAG_ACK) ->
case queue:out(SS) of
{{value, {_Ref, NewSettings}}, NewSS} ->
UpdatedStreams1 =
case NewSettings#settings.initial_window_size of
undefined ->
ok;
NewIWS ->
Delta = OldIWS - NewIWS,
h2_stream_set:update_all_recv_windows(Delta, Streams)
end,
UpdatedStreams2 =
case NewSettings#settings.max_concurrent_streams of
undefined ->
UpdatedStreams1;
NewMax ->
h2_stream_set:update_their_max_active(NewMax, UpdatedStreams1)
end,
{next_state,
connected,
Conn#connection{
streams=UpdatedStreams2,
settings_sent=NewSS,
self_settings=NewSettings
Same thing here , section 6.9.2
}};
_X ->
{next_state, closing, Conn}
end;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Stream level frames
%%
%% receive data frame bigger than connection recv window
route_frame({H,_Payload}, Conn)
when H#frame_header.type == ?DATA,
H#frame_header.length > Conn#connection.recv_window_size ->
go_away(?FLOW_CONTROL_ERROR, Conn);
route_frame(F={H=#frame_header{
length=L,
stream_id=StreamId}, _Payload},
#connection{
recv_window_size=CRWS,
streams=Streams
}=Conn)
when H#frame_header.type == ?DATA ->
Stream = h2_stream_set:get(StreamId, Streams),
case h2_stream_set:type(Stream) of
active ->
case {
h2_stream_set:recv_window_size(Stream) < L,
Conn#connection.flow_control,
L > 0
} of
{true, _, _} ->
rst_stream(Stream,
?FLOW_CONTROL_ERROR,
Conn);
%% If flow control is set to auto, and L > 0, send
%% window updates back to the peer. If L == 0, we're
%% not allowed to send window_updates of size 0, so we
%% hit the next clause
{false, auto, true} ->
%% Make window size great again
h2_frame_window_update:send(Conn#connection.socket,
L, StreamId),
send_window_update(self(), L),
recv_data(Stream, F),
{next_state,
connected,
Conn};
%% Either
%% {false, auto, true} or
{ false , manual , _ }
_Tried ->
recv_data(Stream, F),
{next_state,
connected,
Conn#connection{
recv_window_size=CRWS-L,
streams=h2_stream_set:upsert(
h2_stream_set:decrement_recv_window(L, Stream),
Streams)
}}
end;
_ ->
go_away(?PROTOCOL_ERROR, Conn)
end;
route_frame({#frame_header{type=?HEADERS}=FH, _Payload},
#connection{}=Conn)
when Conn#connection.type == server,
FH#frame_header.stream_id rem 2 == 0 ->
go_away(?PROTOCOL_ERROR, Conn);
route_frame({#frame_header{type=?HEADERS}=FH, _Payload}=Frame,
#connection{}=Conn) ->
StreamId = FH#frame_header.stream_id,
Streams = Conn#connection.streams,
Four things could be happening here .
%% If we're a server, these are either request headers or request
%% trailers
%% If we're a client, these are either headers in response to a
%% client request, or headers in response to a push promise
Stream = h2_stream_set:get(StreamId, Streams),
{ContinuationType, NewConn} =
case {h2_stream_set:type(Stream), Conn#connection.type} of
{idle, server} ->
case
h2_stream_set:new_stream(
StreamId,
self(),
Conn#connection.stream_callback_mod,
Conn#connection.stream_callback_opts,
Conn#connection.socket,
(Conn#connection.peer_settings)#settings.initial_window_size,
(Conn#connection.self_settings)#settings.initial_window_size,
Streams) of
{error, ErrorCode, NewStream} ->
rst_stream(NewStream, ErrorCode, Conn),
{none, Conn};
NewStreams ->
{headers, Conn#connection{streams=NewStreams}}
end;
{active, server} ->
{trailers, Conn};
_ ->
{headers, Conn}
end,
case ContinuationType of
none ->
{next_state,
connected,
NewConn};
_ ->
ContinuationState =
#continuation_state{
type = ContinuationType,
frames = queue:from_list([Frame]),
end_stream = ?IS_FLAG((FH#frame_header.flags), ?FLAG_END_STREAM),
end_headers = ?IS_FLAG((FH#frame_header.flags), ?FLAG_END_HEADERS),
stream_id = StreamId
},
%% maybe_hpack/2 uses this #continuation_state to figure
%% out what to do, which might include hpack
maybe_hpack(ContinuationState, NewConn)
end;
route_frame(F={H=#frame_header{
stream_id=_StreamId,
type=?CONTINUATION
}, _Payload},
#connection{
continuation = #continuation_state{
frames = CFQ
} = Cont
}=Conn) ->
maybe_hpack(Cont#continuation_state{
frames=queue:in(F, CFQ),
end_headers=?IS_FLAG((H#frame_header.flags), ?FLAG_END_HEADERS)
},
Conn);
route_frame({H, _Payload},
#connection{}=Conn)
when H#frame_header.type == ?PRIORITY,
H#frame_header.stream_id == 0 ->
go_away(?PROTOCOL_ERROR, Conn);
route_frame({H, _Payload},
#connection{} = Conn)
when H#frame_header.type == ?PRIORITY ->
{next_state, connected, Conn};
route_frame(
{#frame_header{
stream_id=StreamId,
type=?RST_STREAM
},
_Payload},
#connection{} = Conn) ->
%% TODO: anything with this?
EC = h2_frame_rst_stream : error_code(Payload ) ,
Streams = Conn#connection.streams,
Stream = h2_stream_set:get(StreamId, Streams),
case h2_stream_set:type(Stream) of
idle ->
go_away(?PROTOCOL_ERROR, Conn);
_Stream ->
%% TODO: RST_STREAM support
{next_state, connected, Conn}
end;
route_frame({H=#frame_header{}, _P},
#connection{} =Conn)
when H#frame_header.type == ?PUSH_PROMISE,
Conn#connection.type == server ->
go_away(?PROTOCOL_ERROR, Conn);
route_frame({H=#frame_header{
stream_id=StreamId
},
Payload}=Frame,
#connection{}=Conn)
when H#frame_header.type == ?PUSH_PROMISE,
Conn#connection.type == client ->
PSID = h2_frame_push_promise:promised_stream_id(Payload),
Streams = Conn#connection.streams,
Old = h2_stream_set:get(StreamId, Streams),
NotifyPid = h2_stream_set:notify_pid(Old),
%% TODO: Case statement here about execeding the number of
%% pushed. Honestly I think it's a bigger problem with the
%% h2_stream_set, but we can punt it for now. The idea is that
%% reserved(local) and reserved(remote) aren't technically
%% 'active', but they're being counted that way right now. Again,
%% that only matters if Server Push is enabled.
NewStreams =
h2_stream_set:new_stream(
PSID,
NotifyPid,
Conn#connection.stream_callback_mod,
Conn#connection.stream_callback_opts,
Conn#connection.socket,
(Conn#connection.peer_settings)#settings.initial_window_size,
(Conn#connection.self_settings)#settings.initial_window_size,
Streams),
Continuation = #continuation_state{
stream_id=StreamId,
type=push_promise,
frames = queue:in(Frame, queue:new()),
end_headers=?IS_FLAG((H#frame_header.flags), ?FLAG_END_HEADERS),
promised_id=PSID
},
maybe_hpack(Continuation,
Conn#connection{
streams = NewStreams
});
%% PING
%% If not stream 0, then connection error
route_frame({H, _Payload},
#connection{} = Conn)
when H#frame_header.type == ?PING,
H#frame_header.stream_id =/= 0 ->
go_away(?PROTOCOL_ERROR, Conn);
If length ! = 8 , FRAME_SIZE_ERROR
TODO : I think this case is already covered in h2_frame now
route_frame({H, _Payload},
#connection{}=Conn)
when H#frame_header.type == ?PING,
H#frame_header.length =/= 8 ->
go_away(?FRAME_SIZE_ERROR, Conn);
If PING & & ! ACK , must ACK
route_frame({H, Ping},
#connection{}=Conn)
when H#frame_header.type == ?PING,
?NOT_FLAG((H#frame_header.flags), ?FLAG_ACK) ->
Ack = h2_frame_ping:ack(Ping),
socksend(Conn, h2_frame:to_binary(Ack)),
{next_state, connected, Conn};
route_frame({H, Payload},
#connection{pings = Pings}=Conn)
when H#frame_header.type == ?PING,
?IS_FLAG((H#frame_header.flags), ?FLAG_ACK) ->
case maps:get(h2_frame_ping:to_binary(Payload), Pings, undefined) of
undefined ->
ok;
{NotifyPid, _} ->
NotifyPid ! {'PONG', self()}
end,
NextPings = maps:remove(Payload, Pings),
{next_state, connected, Conn#connection{pings = NextPings}};
route_frame({H=#frame_header{stream_id=0}, _Payload},
#connection{}=Conn)
when H#frame_header.type == ?GOAWAY ->
go_away(?NO_ERROR, Conn);
%% Window Update
route_frame(
{#frame_header{
stream_id=0,
type=?WINDOW_UPDATE
},
Payload},
#connection{
send_window_size=SWS
}=Conn) ->
WSI = h2_frame_window_update:size_increment(Payload),
NewSendWindow = SWS+WSI,
case NewSendWindow > 2147483647 of
true ->
go_away(?FLOW_CONTROL_ERROR, Conn);
false ->
%% TODO: Priority Sort! Right now, it's just sorting on
lowest stream_id first
Streams = h2_stream_set:sort(Conn#connection.streams),
{RemainingSendWindow, UpdatedStreams} =
h2_stream_set:send_what_we_can(
all,
NewSendWindow,
(Conn#connection.peer_settings)#settings.max_frame_size,
Streams
),
{next_state, connected,
Conn#connection{
send_window_size=RemainingSendWindow,
streams=UpdatedStreams
}}
end;
route_frame(
{#frame_header{type=?WINDOW_UPDATE}=FH,
Payload},
#connection{}=Conn
) ->
StreamId = FH#frame_header.stream_id,
Streams = Conn#connection.streams,
WSI = h2_frame_window_update:size_increment(Payload),
Stream = h2_stream_set:get(StreamId, Streams),
case h2_stream_set:type(Stream) of
idle ->
go_away(?PROTOCOL_ERROR, Conn);
closed ->
rst_stream(Stream, ?STREAM_CLOSED, Conn);
active ->
SWS = Conn#connection.send_window_size,
NewSSWS = h2_stream_set:send_window_size(Stream)+WSI,
case NewSSWS > 2147483647 of
true ->
rst_stream(Stream, ?FLOW_CONTROL_ERROR, Conn);
false ->
{RemainingSendWindow, NewStreams}
= h2_stream_set:send_what_we_can(
StreamId,
SWS,
(Conn#connection.peer_settings)#settings.max_frame_size,
h2_stream_set:upsert(
h2_stream_set:increment_send_window_size(WSI, Stream),
Streams)
),
{next_state, connected,
Conn#connection{
send_window_size=RemainingSendWindow,
streams=NewStreams
}}
end
end;
route_frame({#frame_header{type=T}, _}, Conn)
when T > ?CONTINUATION ->
{next_state, connected, Conn};
route_frame(Frame, #connection{}=Conn) ->
error_logger:error_msg("Frame condition not covered by pattern match."
"Please open a github issue with this output: ~s",
[h2_frame:format(Frame)]),
go_away(?PROTOCOL_ERROR, Conn).
handle_event(_, {stream_finished,
StreamId,
Headers,
Body},
Conn) ->
Stream = h2_stream_set:get(StreamId, Conn#connection.streams),
case h2_stream_set:type(Stream) of
active ->
NotifyPid = h2_stream_set:notify_pid(Stream),
Response =
case Conn#connection.type of
server -> garbage;
client -> {Headers, Body}
end,
{_NewStream, NewStreams} =
h2_stream_set:close(
Stream,
Response,
Conn#connection.streams),
NewConn =
Conn#connection{
streams = NewStreams
},
case {Conn#connection.type, is_pid(NotifyPid)} of
{client, true} ->
NotifyPid ! {'END_STREAM', StreamId};
_ ->
ok
end,
{keep_state, NewConn};
_ ->
%% stream finished multiple times
{keep_state, Conn}
end;
handle_event(_, {send_window_update, 0}, Conn) ->
{keep_state, Conn};
handle_event(_, {send_window_update, Size},
#connection{
recv_window_size=CRWS,
socket=Socket
}=Conn) ->
ok = h2_frame_window_update:send(Socket, Size, 0),
{keep_state,
Conn#connection{
recv_window_size=CRWS+Size
}};
handle_event(_, {update_settings, Http2Settings},
#connection{}=Conn) ->
{keep_state,
send_settings(Http2Settings, Conn)};
handle_event(_, {send_headers, StreamId, Headers, Opts},
#connection{
encode_context=EncodeContext,
streams = Streams,
socket = Socket
}=Conn
) ->
StreamComplete = proplists:get_value(send_end_stream, Opts, false),
Stream = h2_stream_set:get(StreamId, Streams),
case h2_stream_set:type(Stream) of
active ->
{FramesToSend, NewContext} =
h2_frame_headers:to_frames(h2_stream_set:stream_id(Stream),
Headers,
EncodeContext,
(Conn#connection.peer_settings)#settings.max_frame_size,
StreamComplete
),
[sock:send(Socket, h2_frame:to_binary(Frame)) || Frame <- FramesToSend],
send_h(Stream, Headers),
{keep_state,
Conn#connection{
encode_context=NewContext
}};
idle ->
%% In theory this is a client maybe activating a stream,
%% but in practice, we've already activated the stream in
%% new_stream/1
{keep_state, Conn};
closed ->
{keep_state, Conn}
end;
handle_event(_, {send_trailers, StreamId, Headers, Opts},
#connection{
encode_context=EncodeContext,
streams = Streams,
socket = _Socket
}=Conn
) ->
BodyComplete = proplists:get_value(send_end_stream, Opts, true),
Stream = h2_stream_set:get(StreamId, Streams),
case h2_stream_set:type(Stream) of
active ->
{FramesToSend, NewContext} =
h2_frame_headers:to_frames(h2_stream_set:stream_id(Stream),
Headers,
EncodeContext,
(Conn#connection.peer_settings)#settings.max_frame_size,
true
),
NewS = h2_stream_set:update_trailers(FramesToSend, Stream),
{NewSWS, NewStreams} =
h2_stream_set:send_what_we_can(
StreamId,
Conn#connection.send_window_size,
(Conn#connection.peer_settings)#settings.max_frame_size,
h2_stream_set:upsert(
h2_stream_set:update_data_queue(h2_stream_set:queued_data(Stream), BodyComplete, NewS),
Conn#connection.streams)),
send_t(Stream, Headers),
{keep_state,
Conn#connection{
encode_context=NewContext,
send_window_size=NewSWS,
streams=NewStreams
}};
idle ->
%% In theory this is a client maybe activating a stream,
%% but in practice, we've already activated the stream in
%% new_stream/1
{keep_state, Conn};
closed ->
{keep_state, Conn}
end;
handle_event(_, {send_body, StreamId, Body, Opts},
#connection{}=Conn) ->
BodyComplete = proplists:get_value(send_end_stream, Opts, true),
Stream = h2_stream_set:get(StreamId, Conn#connection.streams),
case h2_stream_set:type(Stream) of
active ->
OldBody = h2_stream_set:queued_data(Stream),
NewBody = case is_binary(OldBody) of
true -> <<OldBody/binary, Body/binary>>;
false -> Body
end,
{NewSWS, NewStreams} =
h2_stream_set:send_what_we_can(
StreamId,
Conn#connection.send_window_size,
(Conn#connection.peer_settings)#settings.max_frame_size,
h2_stream_set:upsert(
h2_stream_set:update_data_queue(NewBody, BodyComplete, Stream),
Conn#connection.streams)),
{keep_state,
Conn#connection{
send_window_size=NewSWS,
streams=NewStreams
}};
idle ->
%% Sending DATA frames on an idle stream? It's a
%% Connection level protocol error on receipt, but If we
%% have no active stream what can we even do?
{keep_state, Conn};
closed ->
{keep_state, Conn}
end;
handle_event(_, {send_request, NotifyPid, Headers, Body},
#connection{
streams=Streams,
next_available_stream_id=NextId
}=Conn) ->
case send_request(NextId, NotifyPid, Conn, Streams, Headers, Body) of
{ok, GoodStreamSet} ->
{keep_state, Conn#connection{
next_available_stream_id=NextId+2,
streams=GoodStreamSet
}};
{error, _Code} ->
{keep_state, Conn}
end;
handle_event(_, {send_promise, StreamId, NewStreamId, Headers},
#connection{
streams=Streams,
encode_context=OldContext
}=Conn
) ->
NewStream = h2_stream_set:get(NewStreamId, Streams),
case h2_stream_set:type(NewStream) of
active ->
%% TODO: This could be a series of frames, not just one
{PromiseFrame, NewContext} =
h2_frame_push_promise:to_frame(
StreamId,
NewStreamId,
Headers,
OldContext
),
%% Send the PP Frame
Binary = h2_frame:to_binary(PromiseFrame),
socksend(Conn, Binary),
%% Get the promised stream rolling
h2_stream:send_pp(h2_stream_set:stream_pid(NewStream), Headers),
{keep_state,
Conn#connection{
encode_context=NewContext
}};
_ ->
{keep_state, Conn}
end;
handle_event(_, {check_settings_ack, {Ref, NewSettings}},
#connection{
settings_sent=SS
}=Conn) ->
case queue:out(SS) of
{{value, {Ref, NewSettings}}, _} ->
%% This is still here!
go_away(?SETTINGS_TIMEOUT, Conn);
_ ->
!
{keep_state, Conn}
end;
handle_event(_, {send_bin, Binary},
#connection{} = Conn) ->
socksend(Conn, Binary),
{keep_state, Conn};
handle_event(_, {send_frame, Frame},
#connection{} =Conn) ->
Binary = h2_frame:to_binary(Frame),
socksend(Conn, Binary),
{keep_state, Conn};
handle_event(stop, _StateName,
#connection{}=Conn) ->
go_away(0, Conn);
handle_event({call, From}, streams,
#connection{
streams=Streams
}=Conn) ->
{keep_state, Conn, [{reply, From, Streams}]};
handle_event({call, From}, {get_response, StreamId},
#connection{}=Conn) ->
Stream = h2_stream_set:get(StreamId, Conn#connection.streams),
{Reply, NewStreams} =
case h2_stream_set:type(Stream) of
closed ->
{_, NewStreams0} =
h2_stream_set:close(
Stream,
garbage,
Conn#connection.streams),
{{ok, h2_stream_set:response(Stream)}, NewStreams0};
active ->
{not_ready, Conn#connection.streams}
end,
{keep_state, Conn#connection{streams=NewStreams}, [{reply, From, Reply}]};
handle_event({call, From}, {new_stream, NotifyPid},
#connection{
streams=Streams,
next_available_stream_id=NextId
}=Conn) ->
{Reply, NewStreams} =
case
h2_stream_set:new_stream(
NextId,
NotifyPid,
Conn#connection.stream_callback_mod,
Conn#connection.stream_callback_opts,
Conn#connection.socket,
Conn#connection.peer_settings#settings.initial_window_size,
Conn#connection.self_settings#settings.initial_window_size,
Streams)
of
{error, Code, _NewStream} ->
%% TODO: probably want to have events like this available for metrics
%% tried to create new_stream but there are too many
{{error, Code}, Streams};
GoodStreamSet ->
{NextId, GoodStreamSet}
end,
{keep_state, Conn#connection{
next_available_stream_id=NextId+2,
streams=NewStreams
}, [{reply, From, Reply}]};
handle_event({call, From}, is_push,
#connection{
peer_settings=#settings{enable_push=Push}
}=Conn) ->
IsPush = case Push of
1 -> true;
_ -> false
end,
{keep_state, Conn, [{reply, From, IsPush}]};
handle_event({call, From}, get_peer,
#connection{
socket=Socket
}=Conn) ->
case sock:peername(Socket) of
{error, _}=Error ->
{keep_state, Conn, [{reply, From, Error}]};
{ok, _AddrPort}=OK ->
{keep_state, Conn, [{reply, From, OK}]}
end;
handle_event({call, From}, get_peercert,
#connection{
socket=Socket
}=Conn) ->
case sock:peercert(Socket) of
{error, _}=Error ->
{keep_state, Conn, [{reply, From, Error}]};
{ok, _Cert}=OK ->
{keep_state, Conn, [{reply, From, OK}]}
end;
handle_event({call, From}, {send_request, NotifyPid, Headers, Body},
#connection{
streams=Streams,
next_available_stream_id=NextId
}=Conn) ->
case send_request(NextId, NotifyPid, Conn, Streams, Headers, Body) of
{ok, GoodStreamSet} ->
{keep_state, Conn#connection{
next_available_stream_id=NextId+2,
streams=GoodStreamSet
}, [{reply, From, ok}]};
{error, Code} ->
{keep_state, Conn, [{reply, From, {error, Code}}]}
end;
handle_event({call, From}, {send_ping, NotifyPid},
#connection{pings = Pings} = Conn) ->
PingValue = crypto:strong_rand_bytes(8),
Frame = h2_frame_ping:new(PingValue),
Headers = #frame_header{stream_id = 0, flags = 16#0},
Binary = h2_frame:to_binary({Headers, Frame}),
case socksend(Conn, Binary) of
ok ->
NextPings = maps:put(PingValue, {NotifyPid, erlang:monotonic_time(milli_seconds)}, Pings),
NextConn = Conn#connection{pings = NextPings},
{keep_state, NextConn, [{reply, From, ok}]};
{error, _Reason} = Err ->
{keep_state, Conn, [{reply, From, Err}]}
end;
%% Socket Messages
{ tcp , Socket , Data }
handle_event(info, {tcp, Socket, Data},
#connection{
socket={gen_tcp,Socket}
}=Conn) ->
handle_socket_data(Data, Conn);
%% {ssl, Socket, Data}
handle_event(info, {ssl, Socket, Data},
#connection{
socket={ssl,Socket}
}=Conn) ->
handle_socket_data(Data, Conn);
%% {tcp_passive, Socket}
handle_event(info, {tcp_passive, Socket},
#connection{
socket={gen_tcp, Socket}
}=Conn) ->
handle_socket_passive(Conn);
%% {tcp_closed, Socket}
handle_event(info, {tcp_closed, Socket},
#connection{
socket={gen_tcp, Socket}
}=Conn) ->
handle_socket_closed(Conn);
%% {ssl_closed, Socket}
handle_event(info, {ssl_closed, Socket},
#connection{
socket={ssl, Socket}
}=Conn) ->
handle_socket_closed(Conn);
%% {tcp_error, Socket, Reason}
handle_event(info, {tcp_error, Socket, Reason},
#connection{
socket={gen_tcp,Socket}
}=Conn) ->
handle_socket_error(Reason, Conn);
%% {ssl_error, Socket, Reason}
handle_event(info, {ssl_error, Socket, Reason},
#connection{
socket={ssl,Socket}
}=Conn) ->
handle_socket_error(Reason, Conn);
handle_event(info, {_,R},
#connection{}=Conn) ->
handle_socket_error(R, Conn);
handle_event(_, _, Conn) ->
go_away(?PROTOCOL_ERROR, Conn).
code_change(_OldVsn, StateName, Conn, _Extra) ->
{ok, StateName, Conn}.
terminate(normal, _StateName, _Conn) ->
ok;
terminate(_Reason, _StateName, _Conn=#connection{}) ->
ok;
terminate(_Reason, _StateName, _State) ->
ok.
-spec go_away(error_code(), connection()) -> {next_state, closing, connection()}.
go_away(ErrorCode,
#connection{
next_available_stream_id=NAS
}=Conn) ->
GoAway = h2_frame_goaway:new(NAS, ErrorCode),
GoAwayBin = h2_frame:to_binary({#frame_header{
stream_id=0
}, GoAway}),
socksend(Conn, GoAwayBin),
%% TODO: why is this sending a string?
gen_statem:cast(self(), io_lib:format("GO_AWAY: ErrorCode ~p", [ErrorCode])),
{next_state, closing, Conn}.
%% rst_stream/3 looks for a running process for the stream. If it
%% finds one, it delegates sending the rst_stream frame to it, but if
%% it doesn't, it seems like a waste to spawn one just to kill it
%% after sending that frame, so we send it from here.
-spec rst_stream(
h2_stream_set:stream(),
error_code(),
connection()
) ->
{next_state, connected, connection()}.
rst_stream(Stream, ErrorCode, Conn) ->
case h2_stream_set:type(Stream) of
active ->
%% Can this ever be undefined?
Pid = h2_stream_set:stream_pid(Stream),
%% h2_stream's rst_stream will take care of letting us know
%% this stream is closed and will send us a message to close the
%% stream somewhere else
h2_stream:rst_stream(Pid, ErrorCode),
{next_state, connected, Conn};
_ ->
StreamId = h2_stream_set:stream_id(Stream),
RstStream = h2_frame_rst_stream:new(ErrorCode),
RstStreamBin = h2_frame:to_binary(
{#frame_header{
stream_id=StreamId
},
RstStream}),
sock:send(Conn#connection.socket, RstStreamBin),
{next_state, connected, Conn}
end.
-spec send_settings(settings(), connection()) -> connection().
send_settings(SettingsToSend,
#connection{
self_settings=CurrentSettings,
settings_sent=SS
}=Conn) ->
Ref = make_ref(),
Bin = h2_frame_settings:send(CurrentSettings, SettingsToSend),
socksend(Conn, Bin),
send_ack_timeout({Ref,SettingsToSend}),
Conn#connection{
settings_sent=queue:in({Ref, SettingsToSend}, SS)
}.
-spec send_ack_timeout({reference(), settings()}) -> pid().
send_ack_timeout(SS) ->
Self = self(),
SendAck = fun() ->
timer:sleep(5000),
gen_statem:cast(Self, {check_settings_ack,SS})
end,
spawn_link(SendAck).
%% private socket handling
active_once(Socket) ->
sock:setopts(Socket, [{active, once}]).
client_options(Transport, SSLOptions) ->
ClientSocketOptions = [
binary,
{packet, raw},
{active, false}
],
case Transport of
ssl ->
[{alpn_advertised_protocols, [<<"h2">>]}|ClientSocketOptions ++ SSLOptions];
gen_tcp ->
ClientSocketOptions
end.
start_http2_server(
Http2Settings,
#connection{
socket=Socket
}=Conn) ->
case accept_preface(Socket) of
ok ->
ok = active_once(Socket),
NewState =
Conn#connection{
type=server,
next_available_stream_id=2,
flow_control=application:get_env(chatterbox, server_flow_control, auto)
},
{next_state,
handshake,
send_settings(Http2Settings, NewState)
};
{error, invalid_preface} ->
{next_state, closing, Conn}
end.
%% We're going to iterate through the preface string until we're done
%% or hit a mismatch
accept_preface(Socket) ->
accept_preface(Socket, <<?PREFACE>>).
accept_preface(_Socket, <<>>) ->
ok;
accept_preface(Socket, <<Char:8,Rem/binary>>) ->
case sock:recv(Socket, 1, 5000) of
{ok, <<Char>>} ->
accept_preface(Socket, Rem);
_E ->
sock:close(Socket),
{error, invalid_preface}
end.
%% Incoming data is a series of frames. With a passive socket we can just:
1 . read(9 )
2 . turn that 9 into an http2 frame header
3 . use that header 's length field L
4 . ) , now we have a frame
5 . do something with it
6 . 1
%% Things will be different with an {active, true} socket, and also
%% different again with an {active, once} socket
%% with {active, true}, we'd have to maintain some kind of input queue
because it will be very likely that Data is not neatly just a frame
%% with {active, once}, we'd probably be in a situation where Data
%% starts with a frame header. But it's possible that we're here with
%% a partial frame left over from the last active stream
%% We're going to go with the {active, once} approach, because it
wo n't block the gen_server on Transport : ) , but it will wake
up and do something every time Data comes in .
handle_socket_data(<<>>,
#connection{
socket=Socket
}=Conn) ->
active_once(Socket),
{keep_state, Conn};
handle_socket_data(Data,
#connection{
socket=Socket,
buffer=Buffer
}=Conn) ->
More =
case sock:recv(Socket, 0, 1) of %% fail fast
{ok, Rest} ->
Rest;
%% It's not really an error, it's what we want
{error, timeout} ->
<<>>;
_ ->
<<>>
end,
%% What is buffer?
%% empty - nothing, yay
{ frame , : header ( ) , binary ( ) } - Frame Header processed , Payload not big enough
{ binary , binary ( ) } - If we 're here , it must mean that was too small to even be a header
ToParse = case Buffer of
empty ->
<<Data/binary,More/binary>>;
{frame, FHeader, BufferBin} ->
{FHeader, <<BufferBin/binary,Data/binary,More/binary>>};
{binary, BufferBin} ->
<<BufferBin/binary,Data/binary,More/binary>>
end,
%% Now that the buffer has been merged, it's best to make sure any
further state references do n't have one
NewConn = Conn#connection{buffer=empty},
case h2_frame:recv(ToParse) of
We got a full frame , ship it off to the FSM
{ok, Frame, Rem} ->
gen_statem:cast(self(), {frame, Frame}),
handle_socket_data(Rem, NewConn);
%% Not enough bytes left to make a header :(
{not_enough_header, Bin} ->
%% This is a situation where more bytes should come soon,
%% so let's switch back to active, once
active_once(Socket),
{keep_state, NewConn#connection{buffer={binary, Bin}}};
%% Not enough bytes to make a payload
{not_enough_payload, Header, Bin} ->
%% This too
active_once(Socket),
{keep_state, NewConn#connection{buffer={frame, Header, Bin}}};
{error, 0, Code, _Rem} ->
%% Remaining Bytes don't matter, we're closing up shop.
go_away(Code, NewConn);
{error, StreamId, Code, Rem} ->
Stream = h2_stream_set:get(StreamId, Conn#connection.streams),
rst_stream(Stream, Code, NewConn),
handle_socket_data(Rem, NewConn)
end.
handle_socket_passive(Conn) ->
{keep_state, Conn}.
handle_socket_closed(Conn) ->
{stop, normal, Conn}.
handle_socket_error(Reason, Conn) ->
{stop, Reason, Conn}.
socksend(#connection{
socket=Socket
}, Data) ->
case sock:send(Socket, Data) of
ok ->
ok;
{error, Reason} ->
{error, Reason}
end.
%% maybe_hpack will decode headers if it can, or tell the connection
to wait for frames if it ca n't .
-spec maybe_hpack(#continuation_state{}, connection()) ->
{next_state, atom(), connection()}.
%% If there's an END_HEADERS flag, we have a complete headers binary
%% to decode, let's do this!
maybe_hpack(Continuation, Conn)
when Continuation#continuation_state.end_headers ->
Stream = h2_stream_set:get(
Continuation#continuation_state.stream_id,
Conn#connection.streams
),
HeadersBin = h2_frame_headers:from_frames(
queue:to_list(Continuation#continuation_state.frames)
),
case hpack:decode(HeadersBin, Conn#connection.decode_context) of
{error, compression_error} ->
go_away(?COMPRESSION_ERROR, Conn);
{ok, {Headers, NewDecodeContext}} ->
case {Continuation#continuation_state.type,
Continuation#continuation_state.end_stream} of
{push_promise, _} ->
Promised =
h2_stream_set:get(
Continuation#continuation_state.promised_id,
Conn#connection.streams
),
recv_pp(Promised, Headers);
{trailers, false} ->
rst_stream(Stream, ?PROTOCOL_ERROR, Conn);
_ -> %% headers or trailers!
recv_h(Stream, Conn, Headers)
end,
case Continuation#continuation_state.end_stream of
true ->
recv_es(Stream, Conn);
false ->
ok
end,
{next_state, connected,
Conn#connection{
decode_context=NewDecodeContext,
continuation=undefined
}}
end;
If not , we have to wait for all the CONTINUATIONS to roll in .
maybe_hpack(Continuation, Conn) ->
{next_state, continuation,
Conn#connection{
continuation = Continuation
}}.
%% Stream API: These will be moved
-spec recv_h(
Stream :: h2_stream_set:stream(),
Conn :: connection(),
Headers :: hpack:headers()) ->
ok.
recv_h(Stream,
Conn,
Headers) ->
case h2_stream_set:type(Stream) of
active ->
%% If the stream is active, let the process deal with it.
Pid = h2_stream_set:pid(Stream),
h2_stream:send_event(Pid, {recv_h, Headers});
closed ->
If the stream is closed , there 's no running FSM
rst_stream(Stream, ?STREAM_CLOSED, Conn);
idle ->
%% If we're calling this function, we've already activated
a stream FSM ( probably ) . On the off chance we did n't ,
%% we'll throw this
rst_stream(Stream, ?STREAM_CLOSED, Conn)
end.
-spec send_h(
h2_stream_set:stream(),
hpack:headers()) ->
ok.
send_h(Stream, Headers) ->
case h2_stream_set:pid(Stream) of
undefined ->
%% TODO: Should this be some kind of error?
ok;
Pid ->
h2_stream:send_event(Pid, {send_h, Headers})
end.
-spec send_t(
h2_stream_set:stream(),
hpack:headers()) ->
ok.
send_t(Stream, Trailers) ->
case h2_stream_set:pid(Stream) of
undefined ->
%% TODO: Should this be some kind of error?
ok;
Pid ->
h2_stream:send_event(Pid, {send_t, Trailers})
end.
-spec recv_es(Stream :: h2_stream_set:stream(),
Conn :: connection()) ->
ok | {rst_stream, error_code()}.
recv_es(Stream, Conn) ->
case h2_stream_set:type(Stream) of
active ->
Pid = h2_stream_set:pid(Stream),
h2_stream:send_event(Pid, recv_es);
closed ->
rst_stream(Stream, ?STREAM_CLOSED, Conn);
idle ->
rst_stream(Stream, ?STREAM_CLOSED, Conn)
end.
-spec recv_pp(h2_stream_set:stream(),
hpack:headers()) ->
ok.
recv_pp(Stream, Headers) ->
case h2_stream_set:pid(Stream) of
undefined ->
%% Should this be an error?
ok;
Pid ->
h2_stream:send_event(Pid, {recv_pp, Headers})
end.
-spec recv_data(h2_stream_set:stream(),
h2_frame:frame()) ->
ok.
recv_data(Stream, Frame) ->
case h2_stream_set:pid(Stream) of
undefined ->
%% Again, error? These aren't errors now because the code
%% isn't set up to handle errors when these are called
%% anyway.
ok;
Pid ->
h2_stream:send_event(Pid, {recv_data, Frame})
end.
send_request(NextId, NotifyPid, Conn, Streams, Headers, Body) ->
case
h2_stream_set:new_stream(
NextId,
NotifyPid,
Conn#connection.stream_callback_mod,
Conn#connection.stream_callback_opts,
Conn#connection.socket,
Conn#connection.peer_settings#settings.initial_window_size,
Conn#connection.self_settings#settings.initial_window_size,
Streams)
of
{error, Code, _NewStream} ->
%% error creating new stream
{error, Code};
GoodStreamSet ->
send_headers(self(), NextId, Headers),
send_body(self(), NextId, Body),
{ok, GoodStreamSet}
end.
| null |
https://raw.githubusercontent.com/joedevivo/chatterbox/c0506c707bd10d2d2071647f53e188b9740041f2/src/h2_connection.erl
|
erlang
|
HTTP Operations
gen_statem callbacks
gen_statem states
prim_inet:async_accept is dope. It says just hang out here and
wait for a message that a client has connected. That message
looks like:
No timeout here, it's just a listener
The listen state only exists to wait around for new prim_inet
connections
If anything crashes in here, at least there's another acceptor ready
The continuation state in entered after receiving a HEADERS frame
with no ?END_HEADERS flag set, we're locked waiting for contiunation
frames on the same stream to preserve the decoding context state
The closing state should deal with frames on the wire still, I
think. But we should just close it up now.
wire, do connection based things to it and/or forward it to the
Bad Length of frame, exceedes maximum allowed size
Here we'll handle anything that belongs on stream 0.
SETTINGS, finally something that's ok on stream 0
This is the non-ACK case, where settings have actually arrived
Need a way of processing settings so I know which ones came in
We've just got connection settings from a peer. He have a
couple of jobs to do here w.r.t. flow control
send_window_size in the state open or
everywhere. It's up to them if they need to do
anything.
the spec says: "The connection flow-control window can only be
changed using WINDOW_UPDATE frames.",
This is the case where we got an ACK, so dequeue settings we're
waiting to apply
Stream level frames
receive data frame bigger than connection recv window
If flow control is set to auto, and L > 0, send
window updates back to the peer. If L == 0, we're
not allowed to send window_updates of size 0, so we
hit the next clause
Make window size great again
Either
{false, auto, true} or
If we're a server, these are either request headers or request
trailers
If we're a client, these are either headers in response to a
client request, or headers in response to a push promise
maybe_hpack/2 uses this #continuation_state to figure
out what to do, which might include hpack
TODO: anything with this?
TODO: RST_STREAM support
TODO: Case statement here about execeding the number of
pushed. Honestly I think it's a bigger problem with the
h2_stream_set, but we can punt it for now. The idea is that
reserved(local) and reserved(remote) aren't technically
'active', but they're being counted that way right now. Again,
that only matters if Server Push is enabled.
PING
If not stream 0, then connection error
Window Update
TODO: Priority Sort! Right now, it's just sorting on
stream finished multiple times
In theory this is a client maybe activating a stream,
but in practice, we've already activated the stream in
new_stream/1
In theory this is a client maybe activating a stream,
but in practice, we've already activated the stream in
new_stream/1
Sending DATA frames on an idle stream? It's a
Connection level protocol error on receipt, but If we
have no active stream what can we even do?
TODO: This could be a series of frames, not just one
Send the PP Frame
Get the promised stream rolling
This is still here!
TODO: probably want to have events like this available for metrics
tried to create new_stream but there are too many
Socket Messages
{ssl, Socket, Data}
{tcp_passive, Socket}
{tcp_closed, Socket}
{ssl_closed, Socket}
{tcp_error, Socket, Reason}
{ssl_error, Socket, Reason}
TODO: why is this sending a string?
rst_stream/3 looks for a running process for the stream. If it
finds one, it delegates sending the rst_stream frame to it, but if
it doesn't, it seems like a waste to spawn one just to kill it
after sending that frame, so we send it from here.
Can this ever be undefined?
h2_stream's rst_stream will take care of letting us know
this stream is closed and will send us a message to close the
stream somewhere else
private socket handling
We're going to iterate through the preface string until we're done
or hit a mismatch
Incoming data is a series of frames. With a passive socket we can just:
Things will be different with an {active, true} socket, and also
different again with an {active, once} socket
with {active, true}, we'd have to maintain some kind of input queue
with {active, once}, we'd probably be in a situation where Data
starts with a frame header. But it's possible that we're here with
a partial frame left over from the last active stream
We're going to go with the {active, once} approach, because it
fail fast
It's not really an error, it's what we want
What is buffer?
empty - nothing, yay
Now that the buffer has been merged, it's best to make sure any
Not enough bytes left to make a header :(
This is a situation where more bytes should come soon,
so let's switch back to active, once
Not enough bytes to make a payload
This too
Remaining Bytes don't matter, we're closing up shop.
maybe_hpack will decode headers if it can, or tell the connection
If there's an END_HEADERS flag, we have a complete headers binary
to decode, let's do this!
headers or trailers!
Stream API: These will be moved
If the stream is active, let the process deal with it.
If we're calling this function, we've already activated
we'll throw this
TODO: Should this be some kind of error?
TODO: Should this be some kind of error?
Should this be an error?
Again, error? These aren't errors now because the code
isn't set up to handle errors when these are called
anyway.
error creating new stream
|
-module(h2_connection).
-include("http2.hrl").
-behaviour(gen_statem).
Start / Stop API
-export([
start_client/2,
start_client/5,
start_client_link/2,
start_client_link/5,
start_ssl_upgrade_link/5,
start_server_link/3,
become/1,
become/2,
become/3,
stop/1
]).
-export([
send_headers/3,
send_headers/4,
send_trailers/3,
send_trailers/4,
send_body/3,
send_body/4,
send_request/3,
send_ping/1,
is_push/1,
new_stream/1,
new_stream/2,
send_promise/4,
get_response/2,
get_peer/1,
get_peercert/1,
get_streams/1,
send_window_update/2,
update_settings/2,
send_frame/2
]).
-export(
[
init/1,
callback_mode/0,
code_change/4,
terminate/3
]).
-export([
listen/3,
handshake/3,
connected/3,
continuation/3,
closing/3
]).
-export([
go_away/2
]).
-record(h2_listening_state, {
ssl_options :: [ssl:ssl_option()],
listen_socket :: ssl:sslsocket() | inet:socket(),
transport :: gen_tcp | ssl,
listen_ref :: non_neg_integer(),
acceptor_callback = fun chatterbox_sup:start_socket/0 :: fun(),
server_settings = #settings{} :: settings()
}).
-record(continuation_state, {
stream_id :: stream_id(),
promised_id = undefined :: undefined | stream_id(),
frames = queue:new() :: queue:queue(h2_frame:frame()),
type :: headers | push_promise | trailers,
end_stream = false :: boolean(),
end_headers = false :: boolean()
}).
-record(connection, {
type = undefined :: client | server | undefined,
ssl_options = [],
listen_ref :: non_neg_integer() | undefined,
socket = undefined :: sock:socket(),
peer_settings = #settings{} :: settings(),
self_settings = #settings{} :: settings(),
send_window_size = ?DEFAULT_INITIAL_WINDOW_SIZE :: integer(),
recv_window_size = ?DEFAULT_INITIAL_WINDOW_SIZE :: integer(),
decode_context = hpack:new_context() :: hpack:context(),
encode_context = hpack:new_context() :: hpack:context(),
settings_sent = queue:new() :: queue:queue(),
next_available_stream_id = 2 :: stream_id(),
streams :: h2_stream_set:stream_set(),
stream_callback_mod = application:get_env(chatterbox, stream_callback_mod, chatterbox_static_stream) :: module(),
stream_callback_opts = application:get_env(chatterbox, stream_callback_opts, []) :: list(),
buffer = empty :: empty | {binary, binary()} | {frame, h2_frame:header(), binary()},
continuation = undefined :: undefined | #continuation_state{},
flow_control = auto :: auto | manual,
pings = #{} :: #{binary() => {pid(), non_neg_integer()}}
}).
-type connection() :: #connection{}.
-type send_option() :: {send_end_stream, boolean()}.
-type send_opts() :: [send_option()].
-export_type([send_option/0, send_opts/0]).
-ifdef(OTP_RELEASE).
-define(ssl_accept(ClientSocket, SSLOptions), ssl:handshake(ClientSocket, SSLOptions)).
-else.
-define(ssl_accept(ClientSocket, SSLOptions), ssl:ssl_accept(ClientSocket, SSLOptions)).
-endif.
-spec start_client_link(gen_tcp | ssl,
inet:ip_address() | inet:hostname(),
inet:port_number(),
[ssl:ssl_option()],
settings()
) ->
{ok, pid()} | ignore | {error, term()}.
start_client_link(Transport, Host, Port, SSLOptions, Http2Settings) ->
gen_statem:start_link(?MODULE, {client, Transport, Host, Port, SSLOptions, Http2Settings}, []).
-spec start_client(gen_tcp | ssl,
inet:ip_address() | inet:hostname(),
inet:port_number(),
[ssl:ssl_option()],
settings()
) ->
{ok, pid()} | ignore | {error, term()}.
start_client(Transport, Host, Port, SSLOptions, Http2Settings) ->
gen_statem:start(?MODULE, {client, Transport, Host, Port, SSLOptions, Http2Settings}, []).
-spec start_client_link(socket(),
settings()
) ->
{ok, pid()} | ignore | {error, term()}.
start_client_link({Transport, Socket}, Http2Settings) ->
gen_statem:start_link(?MODULE, {client, {Transport, Socket}, Http2Settings}, []).
-spec start_client(socket(),
settings()
) ->
{ok, pid()} | ignore | {error, term()}.
start_client({Transport, Socket}, Http2Settings) ->
gen_statem:start(?MODULE, {client, {Transport, Socket}, Http2Settings}, []).
-spec start_ssl_upgrade_link(inet:ip_address() | inet:hostname(),
inet:port_number(),
binary(),
[ssl:ssl_option()],
settings()
) ->
{ok, pid()} | ignore | {error, term()}.
start_ssl_upgrade_link(Host, Port, InitialMessage, SSLOptions, Http2Settings) ->
gen_statem:start_link(?MODULE, {client_ssl_upgrade, Host, Port, InitialMessage, SSLOptions, Http2Settings}, []).
-spec start_server_link(socket(),
[ssl:ssl_option()],
settings()) ->
{ok, pid()} | ignore | {error, term()}.
start_server_link({Transport, ListenSocket}, SSLOptions, Http2Settings) ->
gen_statem:start_link(?MODULE, {server, {Transport, ListenSocket}, SSLOptions, Http2Settings}, []).
-spec become(socket()) -> no_return().
become(Socket) ->
become(Socket, chatterbox:settings(server)).
-spec become(socket(), settings()) -> no_return().
become(Socket, Http2Settings) ->
become(Socket, Http2Settings, #{}).
-spec become(socket(), settings(), maps:map()) -> no_return().
become({Transport, Socket}, Http2Settings, ConnectionSettings) ->
ok = sock:setopts({Transport, Socket}, [{packet, raw}, binary]),
case start_http2_server(Http2Settings,
#connection{
stream_callback_mod =
maps:get(stream_callback_mod, ConnectionSettings,
application:get_env(chatterbox, stream_callback_mod, chatterbox_static_stream)),
stream_callback_opts =
maps:get(stream_callback_opts, ConnectionSettings,
application:get_env(chatterbox, stream_callback_opts, [])),
streams = h2_stream_set:new(server),
socket = {Transport, Socket}
}) of
{_, handshake, NewState} ->
gen_statem:enter_loop(?MODULE,
[],
handshake,
NewState);
{_, closing, _NewState} ->
sock:close({Transport, Socket}),
exit(invalid_preface)
end.
Init callback
init({client, Transport, Host, Port, SSLOptions, Http2Settings}) ->
case Transport:connect(Host, Port, client_options(Transport, SSLOptions)) of
{ok, Socket} ->
init({client, {Transport, Socket}, Http2Settings});
{error, Reason} ->
{stop, Reason}
end;
init({client, {Transport, Socket}, Http2Settings}) ->
ok = sock:setopts({Transport, Socket}, [{packet, raw}, binary, {active, once}]),
Transport:send(Socket, <<?PREFACE>>),
InitialState =
#connection{
type = client,
streams = h2_stream_set:new(client),
socket = {Transport, Socket},
next_available_stream_id=1,
flow_control=application:get_env(chatterbox, client_flow_control, auto)
},
{ok,
handshake,
send_settings(Http2Settings, InitialState),
4500};
init({client_ssl_upgrade, Host, Port, InitialMessage, SSLOptions, Http2Settings}) ->
case gen_tcp:connect(Host, Port, [{active, false}]) of
{ok, TCP} ->
gen_tcp:send(TCP, InitialMessage),
case ssl:connect(TCP, client_options(ssl, SSLOptions)) of
{ok, Socket} ->
init({client, {ssl, Socket}, Http2Settings});
{error, Reason} ->
{stop, Reason}
end;
{error, Reason} ->
{stop, Reason}
end;
init({server, {Transport, ListenSocket}, SSLOptions, Http2Settings}) ->
{ inet_async , ListenSocket , Ref , { ok , ClientSocket } }
case prim_inet:async_accept(ListenSocket, -1) of
{ok, Ref} ->
{ok,
listen,
#h2_listening_state{
ssl_options = SSLOptions,
listen_socket = ListenSocket,
listen_ref = Ref,
transport = Transport,
server_settings = Http2Settings
{error, Reason} ->
{stop, Reason}
end.
callback_mode() ->
state_functions.
send_frame(Pid, Bin)
when is_binary(Bin); is_list(Bin) ->
gen_statem:cast(Pid, {send_bin, Bin});
send_frame(Pid, Frame) ->
gen_statem:cast(Pid, {send_frame, Frame}).
-spec send_headers(pid(), stream_id(), hpack:headers()) -> ok.
send_headers(Pid, StreamId, Headers) ->
gen_statem:cast(Pid, {send_headers, StreamId, Headers, []}),
ok.
-spec send_headers(pid(), stream_id(), hpack:headers(), send_opts()) -> ok.
send_headers(Pid, StreamId, Headers, Opts) ->
gen_statem:cast(Pid, {send_headers, StreamId, Headers, Opts}),
ok.
-spec send_trailers(pid(), stream_id(), hpack:headers()) -> ok.
send_trailers(Pid, StreamId, Trailers) ->
gen_statem:cast(Pid, {send_trailers, StreamId, Trailers, []}),
ok.
-spec send_trailers(pid(), stream_id(), hpack:headers(), send_opts()) -> ok.
send_trailers(Pid, StreamId, Trailers, Opts) ->
gen_statem:cast(Pid, {send_trailers, StreamId, Trailers, Opts}),
ok.
-spec send_body(pid(), stream_id(), binary()) -> ok.
send_body(Pid, StreamId, Body) ->
gen_statem:cast(Pid, {send_body, StreamId, Body, []}),
ok.
-spec send_body(pid(), stream_id(), binary(), send_opts()) -> ok.
send_body(Pid, StreamId, Body, Opts) ->
gen_statem:cast(Pid, {send_body, StreamId, Body, Opts}),
ok.
-spec send_request(pid(), hpack:headers(), binary()) -> ok.
send_request(Pid, Headers, Body) ->
gen_statem:call(Pid, {send_request, self(), Headers, Body}, infinity),
ok.
-spec send_ping(pid()) -> ok.
send_ping(Pid) ->
gen_statem:call(Pid, {send_ping, self()}, infinity),
ok.
-spec get_peer(pid()) ->
{ok, {inet:ip_address(), inet:port_number()}} | {error, term()}.
get_peer(Pid) ->
gen_statem:call(Pid, get_peer).
-spec get_peercert(pid()) ->
{ok, binary()} | {error, term()}.
get_peercert(Pid) ->
gen_statem:call(Pid, get_peercert).
-spec is_push(pid()) -> boolean().
is_push(Pid) ->
gen_statem:call(Pid, is_push).
-spec new_stream(pid()) -> stream_id() | {error, error_code()}.
new_stream(Pid) ->
new_stream(Pid, self()).
-spec new_stream(pid(), pid()) ->
stream_id()
| {error, error_code()}.
new_stream(Pid, NotifyPid) ->
gen_statem:call(Pid, {new_stream, NotifyPid}).
-spec send_promise(pid(), stream_id(), stream_id(), hpack:headers()) -> ok.
send_promise(Pid, StreamId, NewStreamId, Headers) ->
gen_statem:cast(Pid, {send_promise, StreamId, NewStreamId, Headers}),
ok.
-spec get_response(pid(), stream_id()) ->
{ok, {hpack:headers(), iodata()}}
| not_ready.
get_response(Pid, StreamId) ->
gen_statem:call(Pid, {get_response, StreamId}).
-spec get_streams(pid()) -> h2_stream_set:stream_set().
get_streams(Pid) ->
gen_statem:call(Pid, streams).
-spec send_window_update(pid(), non_neg_integer()) -> ok.
send_window_update(Pid, Size) ->
gen_statem:cast(Pid, {send_window_update, Size}).
-spec update_settings(pid(), h2_frame_settings:payload()) -> ok.
update_settings(Pid, Payload) ->
gen_statem:cast(Pid, {update_settings, Payload}).
-spec stop(pid()) -> ok.
stop(Pid) ->
gen_statem:cast(Pid, stop).
listen(info, {inet_async, ListenSocket, Ref, {ok, ClientSocket}},
#h2_listening_state{
listen_socket = ListenSocket,
listen_ref = Ref,
transport = Transport,
ssl_options = SSLOptions,
acceptor_callback = AcceptorCallback,
server_settings = Http2Settings
}) ->
AcceptorCallback(),
inet_db:register_socket(ClientSocket, inet_tcp),
Socket = case Transport of
gen_tcp ->
ClientSocket;
ssl ->
{ok, AcceptSocket} = ?ssl_accept(ClientSocket, SSLOptions),
{ok, <<"h2">>} = ssl:negotiated_protocol(AcceptSocket),
AcceptSocket
end,
start_http2_server(
Http2Settings,
#connection{
streams = h2_stream_set:new(server),
socket={Transport, Socket}
});
listen(timeout, _, State) ->
go_away(?PROTOCOL_ERROR, State);
listen(Type, Msg, State) ->
handle_event(Type, Msg, State).
-spec handshake(gen_statem:event_type(), {frame, h2_frame:frame()} | term(), connection()) ->
{next_state,
handshake|connected|closing,
connection()}.
handshake(timeout, _, State) ->
go_away(?PROTOCOL_ERROR, State);
handshake(_, {frame, {FH, _Payload}=Frame}, State) ->
The first frame should be the client settings as per
case FH#frame_header.type of
?SETTINGS ->
route_frame(Frame, State);
_ ->
go_away(?PROTOCOL_ERROR, State)
end;
handshake(Type, Msg, State) ->
handle_event(Type, Msg, State).
connected(_, {frame, Frame},
#connection{}=Conn
) ->
route_frame(Frame, Conn);
connected(Type, Msg, State) ->
handle_event(Type, Msg, State).
continuation(_, {frame,
{#frame_header{
stream_id=StreamId,
type=?CONTINUATION
}, _}=Frame},
#connection{
continuation = #continuation_state{
stream_id = StreamId
}
}=Conn) ->
route_frame(Frame, Conn);
continuation(Type, Msg, State) ->
handle_event(Type, Msg, State).
closing(_, _Message,
#connection{
socket=Socket
}=Conn) ->
sock:close(Socket),
{stop, normal, Conn};
closing(Type, Msg, State) ->
handle_event(Type, Msg, State).
route_frame 's job needs to be " now that we 've read a frame off the
http2 stream processor ( h2_stream : recv_frame )
-spec route_frame(
h2_frame:frame() | {error, term()},
connection()) ->
{next_state,
connected | continuation | closing ,
connection()}.
route_frame({#frame_header{length=L}, _},
#connection{
self_settings=#settings{max_frame_size=MFS}
}=Conn)
when L > MFS ->
go_away(?FRAME_SIZE_ERROR, Conn);
Connection Level Frames
route_frame({H, Payload},
#connection{
peer_settings=PS=#settings{
initial_window_size=OldIWS,
header_table_size=HTS
},
streams=Streams,
encode_context=EncodeContext
}=Conn)
when H#frame_header.type == ?SETTINGS,
?NOT_FLAG((H#frame_header.flags), ?FLAG_ACK) ->
on this one payload .
case h2_frame_settings:validate(Payload) of
ok ->
{settings, PList} = Payload,
Delta =
case proplists:get_value(?SETTINGS_INITIAL_WINDOW_SIZE, PList) of
undefined ->
0;
NewIWS ->
NewIWS - OldIWS
end,
NewPeerSettings = h2_frame_settings:overlay(PS, Payload),
If Delta ! = 0 , we need to change every stream 's
half_closed_remote . We 'll just send the message
UpdatedStreams1 =
h2_stream_set:update_all_send_windows(Delta, Streams),
UpdatedStreams2 =
case proplists:get_value(?SETTINGS_MAX_CONCURRENT_STREAMS, PList) of
undefined ->
UpdatedStreams1;
NewMax ->
h2_stream_set:update_my_max_active(NewMax, UpdatedStreams1)
end,
NewEncodeContext = hpack:new_max_table_size(HTS, EncodeContext),
socksend(Conn, h2_frame_settings:ack()),
{next_state, connected, Conn#connection{
peer_settings=NewPeerSettings,
Why are n't we updating send_window_size here ? Section 6.9.2 of
encode_context=NewEncodeContext,
streams=UpdatedStreams2
}};
{error, Code} ->
go_away(Code, Conn)
end;
route_frame({H, _Payload},
#connection{
settings_sent=SS,
streams=Streams,
self_settings=#settings{
initial_window_size=OldIWS
}
}=Conn)
when H#frame_header.type == ?SETTINGS,
?IS_FLAG((H#frame_header.flags), ?FLAG_ACK) ->
case queue:out(SS) of
{{value, {_Ref, NewSettings}}, NewSS} ->
UpdatedStreams1 =
case NewSettings#settings.initial_window_size of
undefined ->
ok;
NewIWS ->
Delta = OldIWS - NewIWS,
h2_stream_set:update_all_recv_windows(Delta, Streams)
end,
UpdatedStreams2 =
case NewSettings#settings.max_concurrent_streams of
undefined ->
UpdatedStreams1;
NewMax ->
h2_stream_set:update_their_max_active(NewMax, UpdatedStreams1)
end,
{next_state,
connected,
Conn#connection{
streams=UpdatedStreams2,
settings_sent=NewSS,
self_settings=NewSettings
Same thing here , section 6.9.2
}};
_X ->
{next_state, closing, Conn}
end;
route_frame({H,_Payload}, Conn)
when H#frame_header.type == ?DATA,
H#frame_header.length > Conn#connection.recv_window_size ->
go_away(?FLOW_CONTROL_ERROR, Conn);
route_frame(F={H=#frame_header{
length=L,
stream_id=StreamId}, _Payload},
#connection{
recv_window_size=CRWS,
streams=Streams
}=Conn)
when H#frame_header.type == ?DATA ->
Stream = h2_stream_set:get(StreamId, Streams),
case h2_stream_set:type(Stream) of
active ->
case {
h2_stream_set:recv_window_size(Stream) < L,
Conn#connection.flow_control,
L > 0
} of
{true, _, _} ->
rst_stream(Stream,
?FLOW_CONTROL_ERROR,
Conn);
{false, auto, true} ->
h2_frame_window_update:send(Conn#connection.socket,
L, StreamId),
send_window_update(self(), L),
recv_data(Stream, F),
{next_state,
connected,
Conn};
{ false , manual , _ }
_Tried ->
recv_data(Stream, F),
{next_state,
connected,
Conn#connection{
recv_window_size=CRWS-L,
streams=h2_stream_set:upsert(
h2_stream_set:decrement_recv_window(L, Stream),
Streams)
}}
end;
_ ->
go_away(?PROTOCOL_ERROR, Conn)
end;
route_frame({#frame_header{type=?HEADERS}=FH, _Payload},
#connection{}=Conn)
when Conn#connection.type == server,
FH#frame_header.stream_id rem 2 == 0 ->
go_away(?PROTOCOL_ERROR, Conn);
route_frame({#frame_header{type=?HEADERS}=FH, _Payload}=Frame,
#connection{}=Conn) ->
StreamId = FH#frame_header.stream_id,
Streams = Conn#connection.streams,
Four things could be happening here .
Stream = h2_stream_set:get(StreamId, Streams),
{ContinuationType, NewConn} =
case {h2_stream_set:type(Stream), Conn#connection.type} of
{idle, server} ->
case
h2_stream_set:new_stream(
StreamId,
self(),
Conn#connection.stream_callback_mod,
Conn#connection.stream_callback_opts,
Conn#connection.socket,
(Conn#connection.peer_settings)#settings.initial_window_size,
(Conn#connection.self_settings)#settings.initial_window_size,
Streams) of
{error, ErrorCode, NewStream} ->
rst_stream(NewStream, ErrorCode, Conn),
{none, Conn};
NewStreams ->
{headers, Conn#connection{streams=NewStreams}}
end;
{active, server} ->
{trailers, Conn};
_ ->
{headers, Conn}
end,
case ContinuationType of
none ->
{next_state,
connected,
NewConn};
_ ->
ContinuationState =
#continuation_state{
type = ContinuationType,
frames = queue:from_list([Frame]),
end_stream = ?IS_FLAG((FH#frame_header.flags), ?FLAG_END_STREAM),
end_headers = ?IS_FLAG((FH#frame_header.flags), ?FLAG_END_HEADERS),
stream_id = StreamId
},
maybe_hpack(ContinuationState, NewConn)
end;
route_frame(F={H=#frame_header{
stream_id=_StreamId,
type=?CONTINUATION
}, _Payload},
#connection{
continuation = #continuation_state{
frames = CFQ
} = Cont
}=Conn) ->
maybe_hpack(Cont#continuation_state{
frames=queue:in(F, CFQ),
end_headers=?IS_FLAG((H#frame_header.flags), ?FLAG_END_HEADERS)
},
Conn);
route_frame({H, _Payload},
#connection{}=Conn)
when H#frame_header.type == ?PRIORITY,
H#frame_header.stream_id == 0 ->
go_away(?PROTOCOL_ERROR, Conn);
route_frame({H, _Payload},
#connection{} = Conn)
when H#frame_header.type == ?PRIORITY ->
{next_state, connected, Conn};
route_frame(
{#frame_header{
stream_id=StreamId,
type=?RST_STREAM
},
_Payload},
#connection{} = Conn) ->
EC = h2_frame_rst_stream : error_code(Payload ) ,
Streams = Conn#connection.streams,
Stream = h2_stream_set:get(StreamId, Streams),
case h2_stream_set:type(Stream) of
idle ->
go_away(?PROTOCOL_ERROR, Conn);
_Stream ->
{next_state, connected, Conn}
end;
route_frame({H=#frame_header{}, _P},
#connection{} =Conn)
when H#frame_header.type == ?PUSH_PROMISE,
Conn#connection.type == server ->
go_away(?PROTOCOL_ERROR, Conn);
route_frame({H=#frame_header{
stream_id=StreamId
},
Payload}=Frame,
#connection{}=Conn)
when H#frame_header.type == ?PUSH_PROMISE,
Conn#connection.type == client ->
PSID = h2_frame_push_promise:promised_stream_id(Payload),
Streams = Conn#connection.streams,
Old = h2_stream_set:get(StreamId, Streams),
NotifyPid = h2_stream_set:notify_pid(Old),
NewStreams =
h2_stream_set:new_stream(
PSID,
NotifyPid,
Conn#connection.stream_callback_mod,
Conn#connection.stream_callback_opts,
Conn#connection.socket,
(Conn#connection.peer_settings)#settings.initial_window_size,
(Conn#connection.self_settings)#settings.initial_window_size,
Streams),
Continuation = #continuation_state{
stream_id=StreamId,
type=push_promise,
frames = queue:in(Frame, queue:new()),
end_headers=?IS_FLAG((H#frame_header.flags), ?FLAG_END_HEADERS),
promised_id=PSID
},
maybe_hpack(Continuation,
Conn#connection{
streams = NewStreams
});
route_frame({H, _Payload},
#connection{} = Conn)
when H#frame_header.type == ?PING,
H#frame_header.stream_id =/= 0 ->
go_away(?PROTOCOL_ERROR, Conn);
If length ! = 8 , FRAME_SIZE_ERROR
TODO : I think this case is already covered in h2_frame now
route_frame({H, _Payload},
#connection{}=Conn)
when H#frame_header.type == ?PING,
H#frame_header.length =/= 8 ->
go_away(?FRAME_SIZE_ERROR, Conn);
If PING & & ! ACK , must ACK
route_frame({H, Ping},
#connection{}=Conn)
when H#frame_header.type == ?PING,
?NOT_FLAG((H#frame_header.flags), ?FLAG_ACK) ->
Ack = h2_frame_ping:ack(Ping),
socksend(Conn, h2_frame:to_binary(Ack)),
{next_state, connected, Conn};
route_frame({H, Payload},
#connection{pings = Pings}=Conn)
when H#frame_header.type == ?PING,
?IS_FLAG((H#frame_header.flags), ?FLAG_ACK) ->
case maps:get(h2_frame_ping:to_binary(Payload), Pings, undefined) of
undefined ->
ok;
{NotifyPid, _} ->
NotifyPid ! {'PONG', self()}
end,
NextPings = maps:remove(Payload, Pings),
{next_state, connected, Conn#connection{pings = NextPings}};
route_frame({H=#frame_header{stream_id=0}, _Payload},
#connection{}=Conn)
when H#frame_header.type == ?GOAWAY ->
go_away(?NO_ERROR, Conn);
route_frame(
{#frame_header{
stream_id=0,
type=?WINDOW_UPDATE
},
Payload},
#connection{
send_window_size=SWS
}=Conn) ->
WSI = h2_frame_window_update:size_increment(Payload),
NewSendWindow = SWS+WSI,
case NewSendWindow > 2147483647 of
true ->
go_away(?FLOW_CONTROL_ERROR, Conn);
false ->
lowest stream_id first
Streams = h2_stream_set:sort(Conn#connection.streams),
{RemainingSendWindow, UpdatedStreams} =
h2_stream_set:send_what_we_can(
all,
NewSendWindow,
(Conn#connection.peer_settings)#settings.max_frame_size,
Streams
),
{next_state, connected,
Conn#connection{
send_window_size=RemainingSendWindow,
streams=UpdatedStreams
}}
end;
route_frame(
{#frame_header{type=?WINDOW_UPDATE}=FH,
Payload},
#connection{}=Conn
) ->
StreamId = FH#frame_header.stream_id,
Streams = Conn#connection.streams,
WSI = h2_frame_window_update:size_increment(Payload),
Stream = h2_stream_set:get(StreamId, Streams),
case h2_stream_set:type(Stream) of
idle ->
go_away(?PROTOCOL_ERROR, Conn);
closed ->
rst_stream(Stream, ?STREAM_CLOSED, Conn);
active ->
SWS = Conn#connection.send_window_size,
NewSSWS = h2_stream_set:send_window_size(Stream)+WSI,
case NewSSWS > 2147483647 of
true ->
rst_stream(Stream, ?FLOW_CONTROL_ERROR, Conn);
false ->
{RemainingSendWindow, NewStreams}
= h2_stream_set:send_what_we_can(
StreamId,
SWS,
(Conn#connection.peer_settings)#settings.max_frame_size,
h2_stream_set:upsert(
h2_stream_set:increment_send_window_size(WSI, Stream),
Streams)
),
{next_state, connected,
Conn#connection{
send_window_size=RemainingSendWindow,
streams=NewStreams
}}
end
end;
route_frame({#frame_header{type=T}, _}, Conn)
when T > ?CONTINUATION ->
{next_state, connected, Conn};
route_frame(Frame, #connection{}=Conn) ->
error_logger:error_msg("Frame condition not covered by pattern match."
"Please open a github issue with this output: ~s",
[h2_frame:format(Frame)]),
go_away(?PROTOCOL_ERROR, Conn).
handle_event(_, {stream_finished,
StreamId,
Headers,
Body},
Conn) ->
Stream = h2_stream_set:get(StreamId, Conn#connection.streams),
case h2_stream_set:type(Stream) of
active ->
NotifyPid = h2_stream_set:notify_pid(Stream),
Response =
case Conn#connection.type of
server -> garbage;
client -> {Headers, Body}
end,
{_NewStream, NewStreams} =
h2_stream_set:close(
Stream,
Response,
Conn#connection.streams),
NewConn =
Conn#connection{
streams = NewStreams
},
case {Conn#connection.type, is_pid(NotifyPid)} of
{client, true} ->
NotifyPid ! {'END_STREAM', StreamId};
_ ->
ok
end,
{keep_state, NewConn};
_ ->
{keep_state, Conn}
end;
handle_event(_, {send_window_update, 0}, Conn) ->
{keep_state, Conn};
handle_event(_, {send_window_update, Size},
#connection{
recv_window_size=CRWS,
socket=Socket
}=Conn) ->
ok = h2_frame_window_update:send(Socket, Size, 0),
{keep_state,
Conn#connection{
recv_window_size=CRWS+Size
}};
handle_event(_, {update_settings, Http2Settings},
#connection{}=Conn) ->
{keep_state,
send_settings(Http2Settings, Conn)};
handle_event(_, {send_headers, StreamId, Headers, Opts},
#connection{
encode_context=EncodeContext,
streams = Streams,
socket = Socket
}=Conn
) ->
StreamComplete = proplists:get_value(send_end_stream, Opts, false),
Stream = h2_stream_set:get(StreamId, Streams),
case h2_stream_set:type(Stream) of
active ->
{FramesToSend, NewContext} =
h2_frame_headers:to_frames(h2_stream_set:stream_id(Stream),
Headers,
EncodeContext,
(Conn#connection.peer_settings)#settings.max_frame_size,
StreamComplete
),
[sock:send(Socket, h2_frame:to_binary(Frame)) || Frame <- FramesToSend],
send_h(Stream, Headers),
{keep_state,
Conn#connection{
encode_context=NewContext
}};
idle ->
{keep_state, Conn};
closed ->
{keep_state, Conn}
end;
handle_event(_, {send_trailers, StreamId, Headers, Opts},
#connection{
encode_context=EncodeContext,
streams = Streams,
socket = _Socket
}=Conn
) ->
BodyComplete = proplists:get_value(send_end_stream, Opts, true),
Stream = h2_stream_set:get(StreamId, Streams),
case h2_stream_set:type(Stream) of
active ->
{FramesToSend, NewContext} =
h2_frame_headers:to_frames(h2_stream_set:stream_id(Stream),
Headers,
EncodeContext,
(Conn#connection.peer_settings)#settings.max_frame_size,
true
),
NewS = h2_stream_set:update_trailers(FramesToSend, Stream),
{NewSWS, NewStreams} =
h2_stream_set:send_what_we_can(
StreamId,
Conn#connection.send_window_size,
(Conn#connection.peer_settings)#settings.max_frame_size,
h2_stream_set:upsert(
h2_stream_set:update_data_queue(h2_stream_set:queued_data(Stream), BodyComplete, NewS),
Conn#connection.streams)),
send_t(Stream, Headers),
{keep_state,
Conn#connection{
encode_context=NewContext,
send_window_size=NewSWS,
streams=NewStreams
}};
idle ->
{keep_state, Conn};
closed ->
{keep_state, Conn}
end;
handle_event(_, {send_body, StreamId, Body, Opts},
#connection{}=Conn) ->
BodyComplete = proplists:get_value(send_end_stream, Opts, true),
Stream = h2_stream_set:get(StreamId, Conn#connection.streams),
case h2_stream_set:type(Stream) of
active ->
OldBody = h2_stream_set:queued_data(Stream),
NewBody = case is_binary(OldBody) of
true -> <<OldBody/binary, Body/binary>>;
false -> Body
end,
{NewSWS, NewStreams} =
h2_stream_set:send_what_we_can(
StreamId,
Conn#connection.send_window_size,
(Conn#connection.peer_settings)#settings.max_frame_size,
h2_stream_set:upsert(
h2_stream_set:update_data_queue(NewBody, BodyComplete, Stream),
Conn#connection.streams)),
{keep_state,
Conn#connection{
send_window_size=NewSWS,
streams=NewStreams
}};
idle ->
{keep_state, Conn};
closed ->
{keep_state, Conn}
end;
handle_event(_, {send_request, NotifyPid, Headers, Body},
#connection{
streams=Streams,
next_available_stream_id=NextId
}=Conn) ->
case send_request(NextId, NotifyPid, Conn, Streams, Headers, Body) of
{ok, GoodStreamSet} ->
{keep_state, Conn#connection{
next_available_stream_id=NextId+2,
streams=GoodStreamSet
}};
{error, _Code} ->
{keep_state, Conn}
end;
handle_event(_, {send_promise, StreamId, NewStreamId, Headers},
#connection{
streams=Streams,
encode_context=OldContext
}=Conn
) ->
NewStream = h2_stream_set:get(NewStreamId, Streams),
case h2_stream_set:type(NewStream) of
active ->
{PromiseFrame, NewContext} =
h2_frame_push_promise:to_frame(
StreamId,
NewStreamId,
Headers,
OldContext
),
Binary = h2_frame:to_binary(PromiseFrame),
socksend(Conn, Binary),
h2_stream:send_pp(h2_stream_set:stream_pid(NewStream), Headers),
{keep_state,
Conn#connection{
encode_context=NewContext
}};
_ ->
{keep_state, Conn}
end;
handle_event(_, {check_settings_ack, {Ref, NewSettings}},
#connection{
settings_sent=SS
}=Conn) ->
case queue:out(SS) of
{{value, {Ref, NewSettings}}, _} ->
go_away(?SETTINGS_TIMEOUT, Conn);
_ ->
!
{keep_state, Conn}
end;
handle_event(_, {send_bin, Binary},
#connection{} = Conn) ->
socksend(Conn, Binary),
{keep_state, Conn};
handle_event(_, {send_frame, Frame},
#connection{} =Conn) ->
Binary = h2_frame:to_binary(Frame),
socksend(Conn, Binary),
{keep_state, Conn};
handle_event(stop, _StateName,
#connection{}=Conn) ->
go_away(0, Conn);
handle_event({call, From}, streams,
#connection{
streams=Streams
}=Conn) ->
{keep_state, Conn, [{reply, From, Streams}]};
handle_event({call, From}, {get_response, StreamId},
#connection{}=Conn) ->
Stream = h2_stream_set:get(StreamId, Conn#connection.streams),
{Reply, NewStreams} =
case h2_stream_set:type(Stream) of
closed ->
{_, NewStreams0} =
h2_stream_set:close(
Stream,
garbage,
Conn#connection.streams),
{{ok, h2_stream_set:response(Stream)}, NewStreams0};
active ->
{not_ready, Conn#connection.streams}
end,
{keep_state, Conn#connection{streams=NewStreams}, [{reply, From, Reply}]};
handle_event({call, From}, {new_stream, NotifyPid},
#connection{
streams=Streams,
next_available_stream_id=NextId
}=Conn) ->
{Reply, NewStreams} =
case
h2_stream_set:new_stream(
NextId,
NotifyPid,
Conn#connection.stream_callback_mod,
Conn#connection.stream_callback_opts,
Conn#connection.socket,
Conn#connection.peer_settings#settings.initial_window_size,
Conn#connection.self_settings#settings.initial_window_size,
Streams)
of
{error, Code, _NewStream} ->
{{error, Code}, Streams};
GoodStreamSet ->
{NextId, GoodStreamSet}
end,
{keep_state, Conn#connection{
next_available_stream_id=NextId+2,
streams=NewStreams
}, [{reply, From, Reply}]};
handle_event({call, From}, is_push,
#connection{
peer_settings=#settings{enable_push=Push}
}=Conn) ->
IsPush = case Push of
1 -> true;
_ -> false
end,
{keep_state, Conn, [{reply, From, IsPush}]};
handle_event({call, From}, get_peer,
#connection{
socket=Socket
}=Conn) ->
case sock:peername(Socket) of
{error, _}=Error ->
{keep_state, Conn, [{reply, From, Error}]};
{ok, _AddrPort}=OK ->
{keep_state, Conn, [{reply, From, OK}]}
end;
handle_event({call, From}, get_peercert,
#connection{
socket=Socket
}=Conn) ->
case sock:peercert(Socket) of
{error, _}=Error ->
{keep_state, Conn, [{reply, From, Error}]};
{ok, _Cert}=OK ->
{keep_state, Conn, [{reply, From, OK}]}
end;
handle_event({call, From}, {send_request, NotifyPid, Headers, Body},
#connection{
streams=Streams,
next_available_stream_id=NextId
}=Conn) ->
case send_request(NextId, NotifyPid, Conn, Streams, Headers, Body) of
{ok, GoodStreamSet} ->
{keep_state, Conn#connection{
next_available_stream_id=NextId+2,
streams=GoodStreamSet
}, [{reply, From, ok}]};
{error, Code} ->
{keep_state, Conn, [{reply, From, {error, Code}}]}
end;
handle_event({call, From}, {send_ping, NotifyPid},
#connection{pings = Pings} = Conn) ->
PingValue = crypto:strong_rand_bytes(8),
Frame = h2_frame_ping:new(PingValue),
Headers = #frame_header{stream_id = 0, flags = 16#0},
Binary = h2_frame:to_binary({Headers, Frame}),
case socksend(Conn, Binary) of
ok ->
NextPings = maps:put(PingValue, {NotifyPid, erlang:monotonic_time(milli_seconds)}, Pings),
NextConn = Conn#connection{pings = NextPings},
{keep_state, NextConn, [{reply, From, ok}]};
{error, _Reason} = Err ->
{keep_state, Conn, [{reply, From, Err}]}
end;
{ tcp , Socket , Data }
handle_event(info, {tcp, Socket, Data},
#connection{
socket={gen_tcp,Socket}
}=Conn) ->
handle_socket_data(Data, Conn);
handle_event(info, {ssl, Socket, Data},
#connection{
socket={ssl,Socket}
}=Conn) ->
handle_socket_data(Data, Conn);
handle_event(info, {tcp_passive, Socket},
#connection{
socket={gen_tcp, Socket}
}=Conn) ->
handle_socket_passive(Conn);
handle_event(info, {tcp_closed, Socket},
#connection{
socket={gen_tcp, Socket}
}=Conn) ->
handle_socket_closed(Conn);
handle_event(info, {ssl_closed, Socket},
#connection{
socket={ssl, Socket}
}=Conn) ->
handle_socket_closed(Conn);
handle_event(info, {tcp_error, Socket, Reason},
#connection{
socket={gen_tcp,Socket}
}=Conn) ->
handle_socket_error(Reason, Conn);
handle_event(info, {ssl_error, Socket, Reason},
#connection{
socket={ssl,Socket}
}=Conn) ->
handle_socket_error(Reason, Conn);
handle_event(info, {_,R},
#connection{}=Conn) ->
handle_socket_error(R, Conn);
handle_event(_, _, Conn) ->
go_away(?PROTOCOL_ERROR, Conn).
code_change(_OldVsn, StateName, Conn, _Extra) ->
{ok, StateName, Conn}.
terminate(normal, _StateName, _Conn) ->
ok;
terminate(_Reason, _StateName, _Conn=#connection{}) ->
ok;
terminate(_Reason, _StateName, _State) ->
ok.
-spec go_away(error_code(), connection()) -> {next_state, closing, connection()}.
go_away(ErrorCode,
#connection{
next_available_stream_id=NAS
}=Conn) ->
GoAway = h2_frame_goaway:new(NAS, ErrorCode),
GoAwayBin = h2_frame:to_binary({#frame_header{
stream_id=0
}, GoAway}),
socksend(Conn, GoAwayBin),
gen_statem:cast(self(), io_lib:format("GO_AWAY: ErrorCode ~p", [ErrorCode])),
{next_state, closing, Conn}.
-spec rst_stream(
h2_stream_set:stream(),
error_code(),
connection()
) ->
{next_state, connected, connection()}.
rst_stream(Stream, ErrorCode, Conn) ->
case h2_stream_set:type(Stream) of
active ->
Pid = h2_stream_set:stream_pid(Stream),
h2_stream:rst_stream(Pid, ErrorCode),
{next_state, connected, Conn};
_ ->
StreamId = h2_stream_set:stream_id(Stream),
RstStream = h2_frame_rst_stream:new(ErrorCode),
RstStreamBin = h2_frame:to_binary(
{#frame_header{
stream_id=StreamId
},
RstStream}),
sock:send(Conn#connection.socket, RstStreamBin),
{next_state, connected, Conn}
end.
-spec send_settings(settings(), connection()) -> connection().
send_settings(SettingsToSend,
#connection{
self_settings=CurrentSettings,
settings_sent=SS
}=Conn) ->
Ref = make_ref(),
Bin = h2_frame_settings:send(CurrentSettings, SettingsToSend),
socksend(Conn, Bin),
send_ack_timeout({Ref,SettingsToSend}),
Conn#connection{
settings_sent=queue:in({Ref, SettingsToSend}, SS)
}.
-spec send_ack_timeout({reference(), settings()}) -> pid().
send_ack_timeout(SS) ->
Self = self(),
SendAck = fun() ->
timer:sleep(5000),
gen_statem:cast(Self, {check_settings_ack,SS})
end,
spawn_link(SendAck).
active_once(Socket) ->
sock:setopts(Socket, [{active, once}]).
client_options(Transport, SSLOptions) ->
ClientSocketOptions = [
binary,
{packet, raw},
{active, false}
],
case Transport of
ssl ->
[{alpn_advertised_protocols, [<<"h2">>]}|ClientSocketOptions ++ SSLOptions];
gen_tcp ->
ClientSocketOptions
end.
start_http2_server(
Http2Settings,
#connection{
socket=Socket
}=Conn) ->
case accept_preface(Socket) of
ok ->
ok = active_once(Socket),
NewState =
Conn#connection{
type=server,
next_available_stream_id=2,
flow_control=application:get_env(chatterbox, server_flow_control, auto)
},
{next_state,
handshake,
send_settings(Http2Settings, NewState)
};
{error, invalid_preface} ->
{next_state, closing, Conn}
end.
accept_preface(Socket) ->
accept_preface(Socket, <<?PREFACE>>).
accept_preface(_Socket, <<>>) ->
ok;
accept_preface(Socket, <<Char:8,Rem/binary>>) ->
case sock:recv(Socket, 1, 5000) of
{ok, <<Char>>} ->
accept_preface(Socket, Rem);
_E ->
sock:close(Socket),
{error, invalid_preface}
end.
1 . read(9 )
2 . turn that 9 into an http2 frame header
3 . use that header 's length field L
4 . ) , now we have a frame
5 . do something with it
6 . 1
because it will be very likely that Data is not neatly just a frame
wo n't block the gen_server on Transport : ) , but it will wake
up and do something every time Data comes in .
handle_socket_data(<<>>,
#connection{
socket=Socket
}=Conn) ->
active_once(Socket),
{keep_state, Conn};
handle_socket_data(Data,
#connection{
socket=Socket,
buffer=Buffer
}=Conn) ->
More =
{ok, Rest} ->
Rest;
{error, timeout} ->
<<>>;
_ ->
<<>>
end,
{ frame , : header ( ) , binary ( ) } - Frame Header processed , Payload not big enough
{ binary , binary ( ) } - If we 're here , it must mean that was too small to even be a header
ToParse = case Buffer of
empty ->
<<Data/binary,More/binary>>;
{frame, FHeader, BufferBin} ->
{FHeader, <<BufferBin/binary,Data/binary,More/binary>>};
{binary, BufferBin} ->
<<BufferBin/binary,Data/binary,More/binary>>
end,
further state references do n't have one
NewConn = Conn#connection{buffer=empty},
case h2_frame:recv(ToParse) of
We got a full frame , ship it off to the FSM
{ok, Frame, Rem} ->
gen_statem:cast(self(), {frame, Frame}),
handle_socket_data(Rem, NewConn);
{not_enough_header, Bin} ->
active_once(Socket),
{keep_state, NewConn#connection{buffer={binary, Bin}}};
{not_enough_payload, Header, Bin} ->
active_once(Socket),
{keep_state, NewConn#connection{buffer={frame, Header, Bin}}};
{error, 0, Code, _Rem} ->
go_away(Code, NewConn);
{error, StreamId, Code, Rem} ->
Stream = h2_stream_set:get(StreamId, Conn#connection.streams),
rst_stream(Stream, Code, NewConn),
handle_socket_data(Rem, NewConn)
end.
handle_socket_passive(Conn) ->
{keep_state, Conn}.
handle_socket_closed(Conn) ->
{stop, normal, Conn}.
handle_socket_error(Reason, Conn) ->
{stop, Reason, Conn}.
socksend(#connection{
socket=Socket
}, Data) ->
case sock:send(Socket, Data) of
ok ->
ok;
{error, Reason} ->
{error, Reason}
end.
to wait for frames if it ca n't .
-spec maybe_hpack(#continuation_state{}, connection()) ->
{next_state, atom(), connection()}.
maybe_hpack(Continuation, Conn)
when Continuation#continuation_state.end_headers ->
Stream = h2_stream_set:get(
Continuation#continuation_state.stream_id,
Conn#connection.streams
),
HeadersBin = h2_frame_headers:from_frames(
queue:to_list(Continuation#continuation_state.frames)
),
case hpack:decode(HeadersBin, Conn#connection.decode_context) of
{error, compression_error} ->
go_away(?COMPRESSION_ERROR, Conn);
{ok, {Headers, NewDecodeContext}} ->
case {Continuation#continuation_state.type,
Continuation#continuation_state.end_stream} of
{push_promise, _} ->
Promised =
h2_stream_set:get(
Continuation#continuation_state.promised_id,
Conn#connection.streams
),
recv_pp(Promised, Headers);
{trailers, false} ->
rst_stream(Stream, ?PROTOCOL_ERROR, Conn);
recv_h(Stream, Conn, Headers)
end,
case Continuation#continuation_state.end_stream of
true ->
recv_es(Stream, Conn);
false ->
ok
end,
{next_state, connected,
Conn#connection{
decode_context=NewDecodeContext,
continuation=undefined
}}
end;
If not , we have to wait for all the CONTINUATIONS to roll in .
maybe_hpack(Continuation, Conn) ->
{next_state, continuation,
Conn#connection{
continuation = Continuation
}}.
-spec recv_h(
Stream :: h2_stream_set:stream(),
Conn :: connection(),
Headers :: hpack:headers()) ->
ok.
recv_h(Stream,
Conn,
Headers) ->
case h2_stream_set:type(Stream) of
active ->
Pid = h2_stream_set:pid(Stream),
h2_stream:send_event(Pid, {recv_h, Headers});
closed ->
If the stream is closed , there 's no running FSM
rst_stream(Stream, ?STREAM_CLOSED, Conn);
idle ->
a stream FSM ( probably ) . On the off chance we did n't ,
rst_stream(Stream, ?STREAM_CLOSED, Conn)
end.
-spec send_h(
h2_stream_set:stream(),
hpack:headers()) ->
ok.
send_h(Stream, Headers) ->
case h2_stream_set:pid(Stream) of
undefined ->
ok;
Pid ->
h2_stream:send_event(Pid, {send_h, Headers})
end.
-spec send_t(
h2_stream_set:stream(),
hpack:headers()) ->
ok.
send_t(Stream, Trailers) ->
case h2_stream_set:pid(Stream) of
undefined ->
ok;
Pid ->
h2_stream:send_event(Pid, {send_t, Trailers})
end.
-spec recv_es(Stream :: h2_stream_set:stream(),
Conn :: connection()) ->
ok | {rst_stream, error_code()}.
recv_es(Stream, Conn) ->
case h2_stream_set:type(Stream) of
active ->
Pid = h2_stream_set:pid(Stream),
h2_stream:send_event(Pid, recv_es);
closed ->
rst_stream(Stream, ?STREAM_CLOSED, Conn);
idle ->
rst_stream(Stream, ?STREAM_CLOSED, Conn)
end.
-spec recv_pp(h2_stream_set:stream(),
hpack:headers()) ->
ok.
recv_pp(Stream, Headers) ->
case h2_stream_set:pid(Stream) of
undefined ->
ok;
Pid ->
h2_stream:send_event(Pid, {recv_pp, Headers})
end.
-spec recv_data(h2_stream_set:stream(),
h2_frame:frame()) ->
ok.
recv_data(Stream, Frame) ->
case h2_stream_set:pid(Stream) of
undefined ->
ok;
Pid ->
h2_stream:send_event(Pid, {recv_data, Frame})
end.
send_request(NextId, NotifyPid, Conn, Streams, Headers, Body) ->
case
h2_stream_set:new_stream(
NextId,
NotifyPid,
Conn#connection.stream_callback_mod,
Conn#connection.stream_callback_opts,
Conn#connection.socket,
Conn#connection.peer_settings#settings.initial_window_size,
Conn#connection.self_settings#settings.initial_window_size,
Streams)
of
{error, Code, _NewStream} ->
{error, Code};
GoodStreamSet ->
send_headers(self(), NextId, Headers),
send_body(self(), NextId, Body),
{ok, GoodStreamSet}
end.
|
42c34acbc44c2d7434d6dce55aac1fef2de8952e467fd02d2d70a68be7d94040
|
geoffder/olm-ml
|
session.ml
|
open Core
open Helpers
open Helpers.ResultInfix
module Message : sig
type t = private PreKey of string | Message of string
val ciphertext : t -> string
val is_pre_key : t -> bool
val to_size : t -> Unsigned.size_t
val to_string : t -> string
val create : string -> int -> (t, [> `ValueError of string ]) result
end = struct
type t = PreKey of string | Message of string
let message_type_pre_key = size_of_int 0
let message_type_message = size_of_int 1
let ciphertext = function
| PreKey c -> c
| Message c -> c
let is_pre_key = function
| PreKey _ -> true
| _ -> false
let to_size = function
| PreKey _ -> message_type_pre_key
| Message _ -> message_type_message
let to_string = function
| PreKey c -> sprintf "PreKey ( %s )" c
| Message c -> sprintf "Message ( %s )" c
let create txt message_type_int =
if String.length txt > 0 then
match message_type_int with
| 0 -> Result.return (PreKey txt)
| 1 -> Result.return (Message txt)
| _ -> Result.fail (`ValueError "Invalid message type (not 0 or 1).")
else Result.fail (`ValueError "Ciphertext can't be empty.")
end
type t = { buf : char Ctypes.ptr
; ses : C.Types.Session.t Ctypes_static.ptr
}
let size = C.Funcs.session_size () |> size_to_int
let clear ses = C.Funcs.clear_session ses |> size_to_result
let check_error t ret =
size_to_result ret
|> Result.map_error ~f:begin fun _ ->
C.Funcs.session_last_error t.ses
|> OlmError.of_last_error
end
let alloc () =
let finalise = finaliser C.Types.Session.t clear in
let buf = allocate_buf ~finalise size in
{ buf; ses = C.Funcs.session (Ctypes.to_voidp buf) }
let create_inbound ?identity_key (acc : Account.t) = function
| Message.Message _ -> Result.fail (`ValueError "PreKey message is required.")
| PreKey ciphertext ->
let cipher_buf = string_to_ptr Ctypes.void ciphertext in
let cipher_len = String.length ciphertext |> size_of_int in
let t = alloc () in
begin
match identity_key with
| Some key when String.length key > 0 ->
let key_buf = string_to_ptr Ctypes.void key in
let key_len = String.length key |> size_of_int in
C.Funcs.create_inbound_session_from
t.ses acc.acc
key_buf key_len
cipher_buf cipher_len
| _ -> C.Funcs.create_inbound_session t.ses acc.acc cipher_buf cipher_len
end |> check_error t >>| fun _ ->
t
let create_outbound (acc: Account.t) identity_key one_time_key =
non_empty_string ~label:"Identity key" identity_key >>|
string_to_sized_buff Ctypes.void >>= fun (id_buf, id_len) ->
non_empty_string ~label:"One time key" one_time_key >>|
string_to_sized_buff Ctypes.void >>= fun (one_buf, one_len) ->
let t = alloc () in
let random_len = C.Funcs.create_outbound_session_random_length t.ses in
let random_buf = Rng.void_buf (size_to_int random_len) in
C.Funcs.create_outbound_session
t.ses acc.acc
id_buf id_len
one_buf one_len
random_buf random_len
|> check_error t >>| fun _ ->
t
let pickle ?(pass="") t =
let key_buf, key_len = string_to_sized_buff Ctypes.void pass in
let pickle_len = C.Funcs.pickle_session_length t.ses in
let pickle_buf = allocate_bytes_void (size_to_int pickle_len) in
let ret = C.Funcs.pickle_session t.ses key_buf key_len pickle_buf pickle_len in
let () = zero_bytes Ctypes.void ~length:(size_to_int key_len) key_buf in
check_error t ret >>| fun _ ->
string_of_ptr_clr Ctypes.void ~length:(size_to_int pickle_len) pickle_buf
let from_pickle ?(pass="") pickle =
non_empty_string ~label:"Pickle" pickle >>|
string_to_sized_buff Ctypes.void >>= fun (pickle_buf, pickle_len) ->
let key_buf, key_len = string_to_sized_buff Ctypes.void pass in
let t = alloc () in
let ret = C.Funcs.unpickle_session t.ses key_buf key_len pickle_buf pickle_len in
let () = zero_bytes Ctypes.void ~length:(size_to_int key_len) key_buf in
check_error t ret >>| fun _ ->
t
let encrypt t plaintext =
C.Funcs.encrypt_message_type t.ses |> check_error t >>= fun msg_type ->
let txt_buf, txt_len = string_to_sized_buff Ctypes.void plaintext in
let random_len = C.Funcs.encrypt_random_length t.ses in
let random_buf = Rng.void_buf (size_to_int random_len) in
let cipher_len = C.Funcs.encrypt_message_length t.ses txt_len in
let cipher_buf = allocate_bytes_void (size_to_int cipher_len) in
let ret = C.Funcs.encrypt t.ses txt_buf txt_len random_buf random_len cipher_buf cipher_len in
let () = zero_bytes Ctypes.void ~length:(size_to_int txt_len) txt_buf in
check_error t ret >>= fun _ ->
let ciphertext = string_of_ptr Ctypes.void ~length:(size_to_int cipher_len) cipher_buf in
Message.create ciphertext msg_type
let decrypt ?ignore_unicode_errors t msg =
let ciphertext = Message.ciphertext msg in
let msg_type = Message.to_size msg in
let cipher_buf () = string_to_ptr Ctypes.void ciphertext in (* max len fun destroys *)
let cipher_len = String.length ciphertext |> size_of_int in
C.Funcs.decrypt_max_plaintext_length t.ses msg_type (cipher_buf ()) cipher_len
|> check_error t >>= fun max_txt_len ->
let txt_buf = allocate_bytes_void max_txt_len in
C.Funcs.decrypt t.ses msg_type (cipher_buf ()) cipher_len txt_buf (size_of_int max_txt_len)
|> check_error t >>= fun txt_len ->
string_of_ptr_clr Ctypes.void ~length:txt_len txt_buf
|> UTF8.recode ?ignore_unicode_errors
let id t =
let id_len = C.Funcs.session_id_length t.ses in
let id_buf = allocate_bytes_void (size_to_int id_len) in
C.Funcs.session_id t.ses id_buf id_len
|> check_error t >>| fun _ ->
string_of_ptr_clr Ctypes.void ~length:(size_to_int id_len) id_buf
let matches ?identity_key t = function
| Message.Message _ -> Result.fail (`ValueError "PreKey message is required.")
| PreKey ciphertext ->
let cipher_buf () = string_to_ptr Ctypes.void ciphertext in
let cipher_len = String.length ciphertext |> size_of_int in
begin
match identity_key with
| Some key when String.length key > 0 ->
let key_buf, key_len = string_to_sized_buff Ctypes.void key in
C.Funcs.matches_inbound_session_from t.ses key_buf key_len (cipher_buf ()) cipher_len
| _ -> C.Funcs.matches_inbound_session t.ses (cipher_buf ()) cipher_len
end |> check_error t >>| fun matched ->
matched > 0
(* This lives in Account in the official API example, but that would be a cyclic
* dependency, so I have moved it here. *)
let remove_one_time_keys t (acc : Account.t) =
C.Funcs.remove_one_time_keys acc.acc t.ses
|> Account.check_error acc
| null |
https://raw.githubusercontent.com/geoffder/olm-ml/6ab791c5f4cacb54cf8939d78bd2a6820ec136b3/olm/lib/session.ml
|
ocaml
|
max len fun destroys
This lives in Account in the official API example, but that would be a cyclic
* dependency, so I have moved it here.
|
open Core
open Helpers
open Helpers.ResultInfix
module Message : sig
type t = private PreKey of string | Message of string
val ciphertext : t -> string
val is_pre_key : t -> bool
val to_size : t -> Unsigned.size_t
val to_string : t -> string
val create : string -> int -> (t, [> `ValueError of string ]) result
end = struct
type t = PreKey of string | Message of string
let message_type_pre_key = size_of_int 0
let message_type_message = size_of_int 1
let ciphertext = function
| PreKey c -> c
| Message c -> c
let is_pre_key = function
| PreKey _ -> true
| _ -> false
let to_size = function
| PreKey _ -> message_type_pre_key
| Message _ -> message_type_message
let to_string = function
| PreKey c -> sprintf "PreKey ( %s )" c
| Message c -> sprintf "Message ( %s )" c
let create txt message_type_int =
if String.length txt > 0 then
match message_type_int with
| 0 -> Result.return (PreKey txt)
| 1 -> Result.return (Message txt)
| _ -> Result.fail (`ValueError "Invalid message type (not 0 or 1).")
else Result.fail (`ValueError "Ciphertext can't be empty.")
end
type t = { buf : char Ctypes.ptr
; ses : C.Types.Session.t Ctypes_static.ptr
}
let size = C.Funcs.session_size () |> size_to_int
let clear ses = C.Funcs.clear_session ses |> size_to_result
let check_error t ret =
size_to_result ret
|> Result.map_error ~f:begin fun _ ->
C.Funcs.session_last_error t.ses
|> OlmError.of_last_error
end
let alloc () =
let finalise = finaliser C.Types.Session.t clear in
let buf = allocate_buf ~finalise size in
{ buf; ses = C.Funcs.session (Ctypes.to_voidp buf) }
let create_inbound ?identity_key (acc : Account.t) = function
| Message.Message _ -> Result.fail (`ValueError "PreKey message is required.")
| PreKey ciphertext ->
let cipher_buf = string_to_ptr Ctypes.void ciphertext in
let cipher_len = String.length ciphertext |> size_of_int in
let t = alloc () in
begin
match identity_key with
| Some key when String.length key > 0 ->
let key_buf = string_to_ptr Ctypes.void key in
let key_len = String.length key |> size_of_int in
C.Funcs.create_inbound_session_from
t.ses acc.acc
key_buf key_len
cipher_buf cipher_len
| _ -> C.Funcs.create_inbound_session t.ses acc.acc cipher_buf cipher_len
end |> check_error t >>| fun _ ->
t
let create_outbound (acc: Account.t) identity_key one_time_key =
non_empty_string ~label:"Identity key" identity_key >>|
string_to_sized_buff Ctypes.void >>= fun (id_buf, id_len) ->
non_empty_string ~label:"One time key" one_time_key >>|
string_to_sized_buff Ctypes.void >>= fun (one_buf, one_len) ->
let t = alloc () in
let random_len = C.Funcs.create_outbound_session_random_length t.ses in
let random_buf = Rng.void_buf (size_to_int random_len) in
C.Funcs.create_outbound_session
t.ses acc.acc
id_buf id_len
one_buf one_len
random_buf random_len
|> check_error t >>| fun _ ->
t
let pickle ?(pass="") t =
let key_buf, key_len = string_to_sized_buff Ctypes.void pass in
let pickle_len = C.Funcs.pickle_session_length t.ses in
let pickle_buf = allocate_bytes_void (size_to_int pickle_len) in
let ret = C.Funcs.pickle_session t.ses key_buf key_len pickle_buf pickle_len in
let () = zero_bytes Ctypes.void ~length:(size_to_int key_len) key_buf in
check_error t ret >>| fun _ ->
string_of_ptr_clr Ctypes.void ~length:(size_to_int pickle_len) pickle_buf
let from_pickle ?(pass="") pickle =
non_empty_string ~label:"Pickle" pickle >>|
string_to_sized_buff Ctypes.void >>= fun (pickle_buf, pickle_len) ->
let key_buf, key_len = string_to_sized_buff Ctypes.void pass in
let t = alloc () in
let ret = C.Funcs.unpickle_session t.ses key_buf key_len pickle_buf pickle_len in
let () = zero_bytes Ctypes.void ~length:(size_to_int key_len) key_buf in
check_error t ret >>| fun _ ->
t
let encrypt t plaintext =
C.Funcs.encrypt_message_type t.ses |> check_error t >>= fun msg_type ->
let txt_buf, txt_len = string_to_sized_buff Ctypes.void plaintext in
let random_len = C.Funcs.encrypt_random_length t.ses in
let random_buf = Rng.void_buf (size_to_int random_len) in
let cipher_len = C.Funcs.encrypt_message_length t.ses txt_len in
let cipher_buf = allocate_bytes_void (size_to_int cipher_len) in
let ret = C.Funcs.encrypt t.ses txt_buf txt_len random_buf random_len cipher_buf cipher_len in
let () = zero_bytes Ctypes.void ~length:(size_to_int txt_len) txt_buf in
check_error t ret >>= fun _ ->
let ciphertext = string_of_ptr Ctypes.void ~length:(size_to_int cipher_len) cipher_buf in
Message.create ciphertext msg_type
let decrypt ?ignore_unicode_errors t msg =
let ciphertext = Message.ciphertext msg in
let msg_type = Message.to_size msg in
let cipher_len = String.length ciphertext |> size_of_int in
C.Funcs.decrypt_max_plaintext_length t.ses msg_type (cipher_buf ()) cipher_len
|> check_error t >>= fun max_txt_len ->
let txt_buf = allocate_bytes_void max_txt_len in
C.Funcs.decrypt t.ses msg_type (cipher_buf ()) cipher_len txt_buf (size_of_int max_txt_len)
|> check_error t >>= fun txt_len ->
string_of_ptr_clr Ctypes.void ~length:txt_len txt_buf
|> UTF8.recode ?ignore_unicode_errors
let id t =
let id_len = C.Funcs.session_id_length t.ses in
let id_buf = allocate_bytes_void (size_to_int id_len) in
C.Funcs.session_id t.ses id_buf id_len
|> check_error t >>| fun _ ->
string_of_ptr_clr Ctypes.void ~length:(size_to_int id_len) id_buf
let matches ?identity_key t = function
| Message.Message _ -> Result.fail (`ValueError "PreKey message is required.")
| PreKey ciphertext ->
let cipher_buf () = string_to_ptr Ctypes.void ciphertext in
let cipher_len = String.length ciphertext |> size_of_int in
begin
match identity_key with
| Some key when String.length key > 0 ->
let key_buf, key_len = string_to_sized_buff Ctypes.void key in
C.Funcs.matches_inbound_session_from t.ses key_buf key_len (cipher_buf ()) cipher_len
| _ -> C.Funcs.matches_inbound_session t.ses (cipher_buf ()) cipher_len
end |> check_error t >>| fun matched ->
matched > 0
let remove_one_time_keys t (acc : Account.t) =
C.Funcs.remove_one_time_keys acc.acc t.ses
|> Account.check_error acc
|
ee0a61f9e8745bde830356fcc4ca43e8ba7e8f6196e575b426afc35bc5687f3f
|
dedbox/racket-template
|
lang.rkt
|
Copyright 2020 < >
;;
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.
#lang racket/base
(require racket/base template)
(provide (except-out (all-from-out racket/base) #%module-begin)
(all-from-out template)
(rename-out [template-module-begin #%module-begin]))
| null |
https://raw.githubusercontent.com/dedbox/racket-template/7e8cd438cdc168b74b1a23721d3410be330de209/lang.rkt
|
racket
|
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.
|
Copyright 2020 < >
distributed under the License is distributed on an " AS IS " BASIS ,
#lang racket/base
(require racket/base template)
(provide (except-out (all-from-out racket/base) #%module-begin)
(all-from-out template)
(rename-out [template-module-begin #%module-begin]))
|
d7333f9f247a49b77e40487602e5b5a03cafdf148fcf13537297c7811b4ce3e0
|
elastic/eui-cljs
|
sorting.cljs
|
(ns eui.services.sorting
(:require ["@elastic/eui/lib/services/breakpoint/_sorting.js" :as eui]))
(def sortMapByLargeToSmallValues eui/sortMapByLargeToSmallValues)
(def sortMapBySmallToLargeValues eui/sortMapBySmallToLargeValues)
| null |
https://raw.githubusercontent.com/elastic/eui-cljs/88737a49699cdd2fd578acff3ad32e97b2b2e798/src/eui/services/sorting.cljs
|
clojure
|
(ns eui.services.sorting
(:require ["@elastic/eui/lib/services/breakpoint/_sorting.js" :as eui]))
(def sortMapByLargeToSmallValues eui/sortMapByLargeToSmallValues)
(def sortMapBySmallToLargeValues eui/sortMapBySmallToLargeValues)
|
|
86034d57115468714181fc455b94eac6caa708473b3b3e2ea6e02bd9d716afb5
|
egri-nagy/kigen
|
T8conjreps.clj
|
;; Finding all conjugacy class representative transformations of the full
transformation semigroup Tn .
;; Exploiting the fact that the maximal conjrep is of the form
[ 1 2 3 .. n-1 0 ]
;; (for the cyclic permutation of n points) we enumerate all transformations
;; lexicographically, odometer style.
recreating integer sequence
(require '[kigen.transf :as t])
m is the maximal available digit , e.g. 1 for binary , 9 for decimal
(defn nxt
"Returns the next vector in lexicographic ordering.
Leftmost is the most significant digit.
Replacing the the first maximal digits with 0s, increase the 1st of
the remaining digits, then copy leftover."
[v m]
(let [[ms others] (split-with (partial = m) v)]
(vec (concat (repeat (count ms) 0)
(when-not (empty? others)
(concat [(inc (first others))]
(rest others)))))))
(defn zerovec
"A vector containing m+1 zeroes."
[m]
(vec (repeat (inc m) 0)))
(defn maxcnj
"Maximal conjugacy class representative for the full transformation semigroup
of degree m+1."
[m]
(vec (concat (range 1 (inc m)) [0])))
(defn full-Tm+1-conjreps
[m]
(let [reps (reduce
(fn [coll v]
(conj coll ((comp t/conjrep reverse) v)))
#{}
(take-while #(not= (vec (reverse %)) (maxcnj m))
(iterate #(nxt % m) (zerovec m))))]
(conj reps (maxcnj m)))) ; not to forget the maximal conjrep
;; checking:
(println (map (comp count full-Tm+1-conjreps) [0 1 2 3 4 5]))
;; should produce
( 1 3 7 19 47 130 )
in a couple of seconds
THE REAL CALCULATION - about an hour
( spit " experiments / DIAGSGPS / T8conjreps " ( vec ( sort ( full - Tm+1 - conjreps 7 ) ) ) )
;; this can be slurped back by
;; (def T8conjreps (clojure.edn/read-string
( slurp " experiments / DIAGSGPS / T8conjreps " ) ) )
;; checked against data from
;; -groups.mcs.st-andrews.ac.uk/~jamesm/data.php
2017.03.22 .
| null |
https://raw.githubusercontent.com/egri-nagy/kigen/5248499fab9d8af05d7d0b07626d0676dfe580c9/experiments/DIAGSGPS/T8conjreps.clj
|
clojure
|
Finding all conjugacy class representative transformations of the full
Exploiting the fact that the maximal conjrep is of the form
(for the cyclic permutation of n points) we enumerate all transformations
lexicographically, odometer style.
not to forget the maximal conjrep
checking:
should produce
this can be slurped back by
(def T8conjreps (clojure.edn/read-string
checked against data from
-groups.mcs.st-andrews.ac.uk/~jamesm/data.php
|
transformation semigroup Tn .
[ 1 2 3 .. n-1 0 ]
recreating integer sequence
(require '[kigen.transf :as t])
m is the maximal available digit , e.g. 1 for binary , 9 for decimal
(defn nxt
"Returns the next vector in lexicographic ordering.
Leftmost is the most significant digit.
Replacing the the first maximal digits with 0s, increase the 1st of
the remaining digits, then copy leftover."
[v m]
(let [[ms others] (split-with (partial = m) v)]
(vec (concat (repeat (count ms) 0)
(when-not (empty? others)
(concat [(inc (first others))]
(rest others)))))))
(defn zerovec
"A vector containing m+1 zeroes."
[m]
(vec (repeat (inc m) 0)))
(defn maxcnj
"Maximal conjugacy class representative for the full transformation semigroup
of degree m+1."
[m]
(vec (concat (range 1 (inc m)) [0])))
(defn full-Tm+1-conjreps
[m]
(let [reps (reduce
(fn [coll v]
(conj coll ((comp t/conjrep reverse) v)))
#{}
(take-while #(not= (vec (reverse %)) (maxcnj m))
(iterate #(nxt % m) (zerovec m))))]
(println (map (comp count full-Tm+1-conjreps) [0 1 2 3 4 5]))
( 1 3 7 19 47 130 )
in a couple of seconds
THE REAL CALCULATION - about an hour
( spit " experiments / DIAGSGPS / T8conjreps " ( vec ( sort ( full - Tm+1 - conjreps 7 ) ) ) )
( slurp " experiments / DIAGSGPS / T8conjreps " ) ) )
2017.03.22 .
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.