_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 |
|---|---|---|---|---|---|---|---|---|
b17b9d44ed71036d88f1fe851370bb061885f6a6c259e71b1d2441f88202ff10 | cxxxr/apispec | operation.lisp | (defpackage #:apispec/tests/classes/operation
(:use #:cl
#:rove
#:apispec/classes/operation)
(:import-from #:apispec/classes/schema
#:schema
#:object)
(:import-from #:apispec/classes/parameter
#:parameter)
(:import-from #:apispec/classes/response
#:response)
(:import-from #:apispec/classes/media-type
#:media-type)
(:import-from #:lack.request
#:request-query-parameters
#:request-cookies)
(:import-from #:lack.response
#:make-response)
(:import-from #:assoc-utils
#:alist-hash))
(in-package #:apispec/tests/classes/operation)
(defun make-operation (parameters)
(make-instance 'operation
:parameters parameters
:responses
`(("204" . ,(make-instance 'response
:description "Success"
:content nil)))))
(deftest validate-request-tests
(testing "path"
(let* ((operation (make-operation
(list
(make-instance 'parameter
:name "car_id"
:in "path"
:schema (schema integer))
(make-instance 'parameter
:name "driver_id"
:in "path"
:schema (schema string)))))
(request (validate-request operation
()
:path-parameters '(("car_id" . "1")
("driver_id" . "xyz")))))
(ok (typep request 'request))
(ok (equalp (request-path-parameters request)
'(("car_id" . 1)
("driver_id" . "xyz"))))))
(testing "query"
(let* ((operation (make-operation
(list
(make-instance 'parameter
:name "role"
:in "query"
:schema (schema string))
(make-instance 'parameter
:name "debug"
:in "query"
:schema (schema boolean)))))
(request (validate-request operation
'(:query-string "role=admin&debug=0"))))
(ok (typep request 'request))
(ok (equalp (request-query-parameters request)
'(("role" . "admin")
("debug" . nil))))))
(testing "header"
(let* ((operation (make-operation
(list
(make-instance 'parameter
:name "X-App-Version"
:in "header"
:schema (schema integer)))))
(request (validate-request operation
(list
:headers (alist-hash
`(("x-app-version" . "3")))))))
(ok (typep request 'request))
(ok (equalp (request-header-parameters request)
'(("X-App-Version" . 3))))))
(testing "cookie"
(let* ((operation (make-operation
(list
(make-instance 'parameter
:name "debug"
:in "cookie"
:schema (schema boolean))
(make-instance 'parameter
:name "csrftoken"
:in "cookie"
:schema (schema string)))))
(request (validate-request operation
(list
:headers (alist-hash
`(("cookie" . "debug=0; csrftoken=BUSe35dohU3O1MZvDCU")))))))
(ok (typep request 'request))
(ok (equalp (request-cookies request)
'(("debug" . nil)
("csrftoken" . "BUSe35dohU3O1MZvDCU")))))))
(deftest validate-response-tests
(let* ((media-type (make-instance 'media-type
:schema (schema (object (("hello" string))))))
(200-response (make-instance 'response
:description "Success"
:content `(("application/json" . ,media-type)))))
(testing "200 OK (application/json)"
(let ((operation (make-instance 'operation
:parameters nil
:responses
`(("200" . ,200-response)))))
(ok (equal (validate-response operation
(make-response 200
'(:content-type "application/json; charset=utf-8")
'(("hello" . "こんにちは"))))
'(200 (:content-type "application/json; charset=utf-8") ("{\"hello\":\"こんにちは\"}"))))))
(testing "204 No Content"
(let* ((response (make-instance 'response
:description "No Content"
:content nil))
(operation (make-instance 'operation
:parameters nil
:responses `(("204" . ,response)
("2XX" . ,200-response)))))
(ok (equal (validate-response operation
(make-response 204))
'(204 () ())))))))
| null | https://raw.githubusercontent.com/cxxxr/apispec/4bdd238f6b5effed305d284e0e6b7cef214e94a2/tests/classes/operation.lisp | lisp | (defpackage #:apispec/tests/classes/operation
(:use #:cl
#:rove
#:apispec/classes/operation)
(:import-from #:apispec/classes/schema
#:schema
#:object)
(:import-from #:apispec/classes/parameter
#:parameter)
(:import-from #:apispec/classes/response
#:response)
(:import-from #:apispec/classes/media-type
#:media-type)
(:import-from #:lack.request
#:request-query-parameters
#:request-cookies)
(:import-from #:lack.response
#:make-response)
(:import-from #:assoc-utils
#:alist-hash))
(in-package #:apispec/tests/classes/operation)
(defun make-operation (parameters)
(make-instance 'operation
:parameters parameters
:responses
`(("204" . ,(make-instance 'response
:description "Success"
:content nil)))))
(deftest validate-request-tests
(testing "path"
(let* ((operation (make-operation
(list
(make-instance 'parameter
:name "car_id"
:in "path"
:schema (schema integer))
(make-instance 'parameter
:name "driver_id"
:in "path"
:schema (schema string)))))
(request (validate-request operation
()
:path-parameters '(("car_id" . "1")
("driver_id" . "xyz")))))
(ok (typep request 'request))
(ok (equalp (request-path-parameters request)
'(("car_id" . 1)
("driver_id" . "xyz"))))))
(testing "query"
(let* ((operation (make-operation
(list
(make-instance 'parameter
:name "role"
:in "query"
:schema (schema string))
(make-instance 'parameter
:name "debug"
:in "query"
:schema (schema boolean)))))
(request (validate-request operation
'(:query-string "role=admin&debug=0"))))
(ok (typep request 'request))
(ok (equalp (request-query-parameters request)
'(("role" . "admin")
("debug" . nil))))))
(testing "header"
(let* ((operation (make-operation
(list
(make-instance 'parameter
:name "X-App-Version"
:in "header"
:schema (schema integer)))))
(request (validate-request operation
(list
:headers (alist-hash
`(("x-app-version" . "3")))))))
(ok (typep request 'request))
(ok (equalp (request-header-parameters request)
'(("X-App-Version" . 3))))))
(testing "cookie"
(let* ((operation (make-operation
(list
(make-instance 'parameter
:name "debug"
:in "cookie"
:schema (schema boolean))
(make-instance 'parameter
:name "csrftoken"
:in "cookie"
:schema (schema string)))))
(request (validate-request operation
(list
:headers (alist-hash
`(("cookie" . "debug=0; csrftoken=BUSe35dohU3O1MZvDCU")))))))
(ok (typep request 'request))
(ok (equalp (request-cookies request)
'(("debug" . nil)
("csrftoken" . "BUSe35dohU3O1MZvDCU")))))))
(deftest validate-response-tests
(let* ((media-type (make-instance 'media-type
:schema (schema (object (("hello" string))))))
(200-response (make-instance 'response
:description "Success"
:content `(("application/json" . ,media-type)))))
(testing "200 OK (application/json)"
(let ((operation (make-instance 'operation
:parameters nil
:responses
`(("200" . ,200-response)))))
(ok (equal (validate-response operation
(make-response 200
'(:content-type "application/json; charset=utf-8")
'(("hello" . "こんにちは"))))
'(200 (:content-type "application/json; charset=utf-8") ("{\"hello\":\"こんにちは\"}"))))))
(testing "204 No Content"
(let* ((response (make-instance 'response
:description "No Content"
:content nil))
(operation (make-instance 'operation
:parameters nil
:responses `(("204" . ,response)
("2XX" . ,200-response)))))
(ok (equal (validate-response operation
(make-response 204))
'(204 () ())))))))
| |
81692fd1da2bc02576e00e06ba62dcbc4c9cb7894eca81fa11cbcebe4d7d2b22 | jlongster/gambit-iphone-example | srfi-2.scm | ; Checking of a LAND* special form
;
; LAND* is a generalized AND: it evaluates a sequence of forms one after another
till the first one that yields # f ; the non-#f result of a form can be bound
; to a fresh variable and used in the subsequent forms.
;
; When an ordinary AND is formed of _proper_ boolean expressions:
; (AND E1 E2 ...)
expression E2 , if it gets to be evaluated , knows that E1 has returned non-#f .
Moreover , E2 knows exactly what the result of E1 was - # t - so E2 can use
; this knowledge to its advantage. If E1 however is an _extended_
; boolean expression, E2 can no longer tell which particular non-#f
value E1 has returned . Chances are it took a lot of work to evaluate E1 ,
; and the produced result (a number, a vector, a string, etc) may be of
value to E2 . Alas , the AND form merely checks that the result is not an # f ,
; and throws it away. If E2 needs it, it has to recompute the value again.
; This proposed LAND* special form lets constituent expressions get
; hold of the results of already evaluated expressions, without re-doing
; their work.
;
; Syntax:
; LAND* (CLAWS) BODY
;
where CLAWS is a list of expressions or bindings :
CLAWS : : = ' ( ) | ( cons CLAW CLAWS )
Every element of the CLAWS list , a CLAW , must be one of the following :
; (VARIABLE EXPRESSION)
; or
; (EXPRESSION)
; or
; BOUND-VARIABLE
These CLAWS are evaluated in the strict left - to - right order . For each
CLAW , the EXPRESSION part is evaluated first ( or BOUND - VARIABLE is looked up ) .
If the result is # f , LAND * immediately returns # f , thus disregarding the rest
of the CLAWS and the BODY . If the EXPRESSION evaluates to not-#f , and
the CLAW is of the form
; (VARIABLE EXPRESSION)
the EXPRESSION 's value is bound to a freshly made VARIABLE . The VARIABLE is
available for _ the rest _ of the CLAWS , and the BODY . As usual , all
; VARIABLEs must be unique (like in let*).
;
; Thus LAND* is a sort of cross-breed between LET* and AND.
;
; Denotation semantics:
;
; Eval[ (LAND* (CLAW1 ...) BODY), Env] =
; EvalClaw[ CLAW1, Env ] andalso
Eval [ ( LAND * ( ... ) BODY ) , ExtClawEnv [ CLAW1 , Env ] ]
;
Eval [ ( LAND * ( CLAW ) ) , Env ] = EvalClaw [ CLAW , Env ]
; Eval[ (LAND* () FORM1 ...), Env] = Eval[ (BEGIN FORM1 ...), Env ]
; Eval[ (LAND* () ), Env] = #t
;
; EvalClaw[ BOUND-VARIABLE, Env ] = Eval[ BOUND-VARIABLE, Env ]
; EvalClaw[ (EXPRESSION), Env ] = Eval[ EXPRESSION, Env ]
; EvalClaw[ (VARIABLE EXPRESSION), Env ] = Eval[ EXPRESSION, Env ]
;
; ExtClawEnv[ BOUND-VARIABLE, Env ] = Env
; ExtClawEnv[ (EXPRESSION), Env ] = EnvAfterEval[ EXPRESSION, Env ]
; ExtClawEnv[ (VARIABLE EXPRESSION), Env ] =
ExtendEnv [ EnvAfterEval [ EXPRESSION , Env ] ,
; VARIABLE boundto Eval[ EXPRESSION, Env ]]
;
;
If one has a Scheme interpreter written in Prolog / ML / Haskell , he can
; implement the above semantics right away. Within Scheme, it is trivial to
code LAND * with R4RS " define - syntax " . Alas , Gambit does not have this
; facility. So this implementation uses macros instead.
;
; The following LAND* macro will convert a LAND* expression into a "tree" of
; AND and LET expressions. For example,
; (LAND* ((my-list (compute-list)) ((not (null? my-list))))
; (do-something my-list))
; is transformed into
; (and (let ((my-list (compute-list)))
; (and my-list (not (null? my-list)) (begin (do-something my-list)))))
;
; I must admit the LAND* macro is written in a pathetic anti-functional style.
; To my excuse, the macro's goal is a syntactic transformation of source
code , that is , performing a re - writing . IMHO , rewriting kind of suggests
; mutating.
;
; Sample applications:
;
; The following piece of code (from my treap package)
; (let ((new-root (node:dispatch-on-key root key ...)))
; (if new-root (set! root new-root)))
; could be elegantly re-written as
; (land* ((new-root (node:dispatch-on-key root key ...)))
; (set! root new-root))
;
; A very common application of land* is looking up a value
; associated with a given key in an assoc list, returning #f in case of a
; look-up failure:
;
; ; Standard implementation
; (define (look-up key alist)
; (let ((found-assoc (assq key alist)))
; (and found-assoc (cdr found-assoc))))
;
; ; A more elegant solution
; (define (look-up key alist)
; (cdr (or (assq key alist) '(#f . #f))))
;
; ; An implementation which is just as graceful as the latter
; ; and just as efficient as the former:
; (define (look-up key alist)
( land * ( ( x ( assq key alist ) ) ) ) ) )
;
; Generalized cond:
;
; (or
; (land* (bindings-cond1) body1)
( land * ( bindings - cond2 ) )
; (begin else-clause))
;
; Unlike => (cond's send), LAND* applies beyond cond. LAND* can also be used
; to generalize cond, as => is limited to sending of only a single value;
; LAND* allows as many bindings as necessary (which are performed in sequence)
;
; (or
; (land* ((c (read-char)) ((not (eof-object? c))))
; (string-set! some-str i c) (++! i))
; (begin (do-process-eof)))
;
; Another concept LAND* is reminiscent of is programming with guards:
; a LAND* form can be considered a sequence of _guarded_ expressions.
; In a regular program, forms may produce results, bind them to variables
; and let other forms use these results. LAND* differs in that it checks
; to make sure that every produced result "makes sense" (that is, not an #f).
The first " failure " triggers the guard and aborts the rest of the
; sequence (which presumably would not make any sense to execute anyway).
;
$ I d : vland - gambit.scm , v 1.1 1998/12/28 23:54:29 Exp $
(define-macro (and-let* claws . body)
(let* ((new-vars '()) (result (cons 'and '())) (growth-point result))
; We need a way to report a syntax error
; the following is how Gambit compiler does it...
(##define-macro (ct-error-syntax msg . args)
`(##signal '##signal.syntax-error #t ,msg ,@args))
(define (andjoin! clause)
(let ((prev-point growth-point) (clause-cell (cons clause '())))
(set-cdr! growth-point clause-cell)
(set! growth-point clause-cell)))
(if (not (list? claws))
(ct-error-syntax "bindings must be a list " bindings))
(for-each
(lambda (claw)
(cond
BOUND - VARIABLE form
(andjoin! claw))
((and (pair? claw) (null? (cdr claw))) ; (EXPRESSION) form
(andjoin! (car claw)))
; (VARIABLE EXPRESSION) form
((and (pair? claw) (symbol? (car claw))
(pair? (cdr claw)) (null? (cddr claw)))
(let* ((var (car claw)) (var-cell (cons var '())))
(if (memq var new-vars)
(ct-error-syntax "duplicate variable " var " in the bindings"))
(set! new-vars (cons var new-vars))
(set-cdr! growth-point `((let (,claw) (and . ,var-cell))))
(set! growth-point var-cell)))
(else
(ct-error-syntax "An ill-formed binding in a syntactic form land* "
claw))
))
claws)
(if (not (null? body))
(andjoin! `(begin ,@body)))
result))
| null | https://raw.githubusercontent.com/jlongster/gambit-iphone-example/e55d915180cb6c57312cbb683d81823ea455e14f/lib/util/srfi-2.scm | scheme | Checking of a LAND* special form
LAND* is a generalized AND: it evaluates a sequence of forms one after another
the non-#f result of a form can be bound
to a fresh variable and used in the subsequent forms.
When an ordinary AND is formed of _proper_ boolean expressions:
(AND E1 E2 ...)
this knowledge to its advantage. If E1 however is an _extended_
boolean expression, E2 can no longer tell which particular non-#f
and the produced result (a number, a vector, a string, etc) may be of
and throws it away. If E2 needs it, it has to recompute the value again.
This proposed LAND* special form lets constituent expressions get
hold of the results of already evaluated expressions, without re-doing
their work.
Syntax:
LAND* (CLAWS) BODY
(VARIABLE EXPRESSION)
or
(EXPRESSION)
or
BOUND-VARIABLE
(VARIABLE EXPRESSION)
VARIABLEs must be unique (like in let*).
Thus LAND* is a sort of cross-breed between LET* and AND.
Denotation semantics:
Eval[ (LAND* (CLAW1 ...) BODY), Env] =
EvalClaw[ CLAW1, Env ] andalso
Eval[ (LAND* () FORM1 ...), Env] = Eval[ (BEGIN FORM1 ...), Env ]
Eval[ (LAND* () ), Env] = #t
EvalClaw[ BOUND-VARIABLE, Env ] = Eval[ BOUND-VARIABLE, Env ]
EvalClaw[ (EXPRESSION), Env ] = Eval[ EXPRESSION, Env ]
EvalClaw[ (VARIABLE EXPRESSION), Env ] = Eval[ EXPRESSION, Env ]
ExtClawEnv[ BOUND-VARIABLE, Env ] = Env
ExtClawEnv[ (EXPRESSION), Env ] = EnvAfterEval[ EXPRESSION, Env ]
ExtClawEnv[ (VARIABLE EXPRESSION), Env ] =
VARIABLE boundto Eval[ EXPRESSION, Env ]]
implement the above semantics right away. Within Scheme, it is trivial to
facility. So this implementation uses macros instead.
The following LAND* macro will convert a LAND* expression into a "tree" of
AND and LET expressions. For example,
(LAND* ((my-list (compute-list)) ((not (null? my-list))))
(do-something my-list))
is transformed into
(and (let ((my-list (compute-list)))
(and my-list (not (null? my-list)) (begin (do-something my-list)))))
I must admit the LAND* macro is written in a pathetic anti-functional style.
To my excuse, the macro's goal is a syntactic transformation of source
mutating.
Sample applications:
The following piece of code (from my treap package)
(let ((new-root (node:dispatch-on-key root key ...)))
(if new-root (set! root new-root)))
could be elegantly re-written as
(land* ((new-root (node:dispatch-on-key root key ...)))
(set! root new-root))
A very common application of land* is looking up a value
associated with a given key in an assoc list, returning #f in case of a
look-up failure:
; Standard implementation
(define (look-up key alist)
(let ((found-assoc (assq key alist)))
(and found-assoc (cdr found-assoc))))
; A more elegant solution
(define (look-up key alist)
(cdr (or (assq key alist) '(#f . #f))))
; An implementation which is just as graceful as the latter
; and just as efficient as the former:
(define (look-up key alist)
Generalized cond:
(or
(land* (bindings-cond1) body1)
(begin else-clause))
Unlike => (cond's send), LAND* applies beyond cond. LAND* can also be used
to generalize cond, as => is limited to sending of only a single value;
LAND* allows as many bindings as necessary (which are performed in sequence)
(or
(land* ((c (read-char)) ((not (eof-object? c))))
(string-set! some-str i c) (++! i))
(begin (do-process-eof)))
Another concept LAND* is reminiscent of is programming with guards:
a LAND* form can be considered a sequence of _guarded_ expressions.
In a regular program, forms may produce results, bind them to variables
and let other forms use these results. LAND* differs in that it checks
to make sure that every produced result "makes sense" (that is, not an #f).
sequence (which presumably would not make any sense to execute anyway).
We need a way to report a syntax error
the following is how Gambit compiler does it...
(EXPRESSION) form
(VARIABLE EXPRESSION) form | expression E2 , if it gets to be evaluated , knows that E1 has returned non-#f .
Moreover , E2 knows exactly what the result of E1 was - # t - so E2 can use
value E1 has returned . Chances are it took a lot of work to evaluate E1 ,
value to E2 . Alas , the AND form merely checks that the result is not an # f ,
where CLAWS is a list of expressions or bindings :
CLAWS : : = ' ( ) | ( cons CLAW CLAWS )
Every element of the CLAWS list , a CLAW , must be one of the following :
These CLAWS are evaluated in the strict left - to - right order . For each
CLAW , the EXPRESSION part is evaluated first ( or BOUND - VARIABLE is looked up ) .
If the result is # f , LAND * immediately returns # f , thus disregarding the rest
of the CLAWS and the BODY . If the EXPRESSION evaluates to not-#f , and
the CLAW is of the form
the EXPRESSION 's value is bound to a freshly made VARIABLE . The VARIABLE is
available for _ the rest _ of the CLAWS , and the BODY . As usual , all
Eval [ ( LAND * ( ... ) BODY ) , ExtClawEnv [ CLAW1 , Env ] ]
Eval [ ( LAND * ( CLAW ) ) , Env ] = EvalClaw [ CLAW , Env ]
ExtendEnv [ EnvAfterEval [ EXPRESSION , Env ] ,
If one has a Scheme interpreter written in Prolog / ML / Haskell , he can
code LAND * with R4RS " define - syntax " . Alas , Gambit does not have this
code , that is , performing a re - writing . IMHO , rewriting kind of suggests
( land * ( ( x ( assq key alist ) ) ) ) ) )
( land * ( bindings - cond2 ) )
The first " failure " triggers the guard and aborts the rest of the
$ I d : vland - gambit.scm , v 1.1 1998/12/28 23:54:29 Exp $
(define-macro (and-let* claws . body)
(let* ((new-vars '()) (result (cons 'and '())) (growth-point result))
(##define-macro (ct-error-syntax msg . args)
`(##signal '##signal.syntax-error #t ,msg ,@args))
(define (andjoin! clause)
(let ((prev-point growth-point) (clause-cell (cons clause '())))
(set-cdr! growth-point clause-cell)
(set! growth-point clause-cell)))
(if (not (list? claws))
(ct-error-syntax "bindings must be a list " bindings))
(for-each
(lambda (claw)
(cond
BOUND - VARIABLE form
(andjoin! claw))
(andjoin! (car claw)))
((and (pair? claw) (symbol? (car claw))
(pair? (cdr claw)) (null? (cddr claw)))
(let* ((var (car claw)) (var-cell (cons var '())))
(if (memq var new-vars)
(ct-error-syntax "duplicate variable " var " in the bindings"))
(set! new-vars (cons var new-vars))
(set-cdr! growth-point `((let (,claw) (and . ,var-cell))))
(set! growth-point var-cell)))
(else
(ct-error-syntax "An ill-formed binding in a syntactic form land* "
claw))
))
claws)
(if (not (null? body))
(andjoin! `(begin ,@body)))
result))
|
b4af4094c648f937a81c4b3ffbaf9961077d041eee782e7eb23d164c301fe076 | dschrempf/elynx | SLynx.hs | -- |
Module : SLynx . SLynx
Description : SLynx module
Copyright : 2021
License : GPL-3.0 - or - later
--
-- Maintainer :
-- Stability : unstable
-- Portability : portable
--
Creation date : Thu Apr 23 16:38:55 2020 .
module SLynx.SLynx
( slynx,
rSLynx,
)
where
import ELynx.Tools.ELynx
import ELynx.Tools.Options
import SLynx.Concatenate.Concatenate
import SLynx.Examine.Examine
import SLynx.Filter.Filter
import SLynx.Options
import SLynx.Simulate.Simulate
import SLynx.SubSample.SubSample
import SLynx.Translate.Translate
-- | Run SLynx with given arguments.
slynx :: Arguments CommandArguments -> IO ()
slynx c = case local c of
Concatenate l -> eLynxWrapper g l Concatenate concatenateCmd
Examine l -> eLynxWrapper g l Examine examineCmd
FilterCols l -> eLynxWrapper g l FilterCols filterColsCmd
FilterRows l -> eLynxWrapper g l FilterRows filterRowsCmd
Simulate l -> eLynxWrapper g l Simulate simulateCmd
SubSample l -> eLynxWrapper g l SubSample subSampleCmd
Translate l -> eLynxWrapper g l Translate translateCmd
where
g = global c
-- | Run SLynx, parse arguments from command line.
rSLynx :: IO ()
rSLynx = parseArguments >>= slynx
| null | https://raw.githubusercontent.com/dschrempf/elynx/f73f4474c61c22c6a9e54c56bdc34b37eff09687/slynx/src/SLynx/SLynx.hs | haskell | |
Maintainer :
Stability : unstable
Portability : portable
| Run SLynx with given arguments.
| Run SLynx, parse arguments from command line. | Module : SLynx . SLynx
Description : SLynx module
Copyright : 2021
License : GPL-3.0 - or - later
Creation date : Thu Apr 23 16:38:55 2020 .
module SLynx.SLynx
( slynx,
rSLynx,
)
where
import ELynx.Tools.ELynx
import ELynx.Tools.Options
import SLynx.Concatenate.Concatenate
import SLynx.Examine.Examine
import SLynx.Filter.Filter
import SLynx.Options
import SLynx.Simulate.Simulate
import SLynx.SubSample.SubSample
import SLynx.Translate.Translate
slynx :: Arguments CommandArguments -> IO ()
slynx c = case local c of
Concatenate l -> eLynxWrapper g l Concatenate concatenateCmd
Examine l -> eLynxWrapper g l Examine examineCmd
FilterCols l -> eLynxWrapper g l FilterCols filterColsCmd
FilterRows l -> eLynxWrapper g l FilterRows filterRowsCmd
Simulate l -> eLynxWrapper g l Simulate simulateCmd
SubSample l -> eLynxWrapper g l SubSample subSampleCmd
Translate l -> eLynxWrapper g l Translate translateCmd
where
g = global c
rSLynx :: IO ()
rSLynx = parseArguments >>= slynx
|
de24d5f8c43e48dd1576beaeb047c6432accc25cbb5445ee09960d7110aeece2 | scalaris-team/scalaris | gset.erl | 2008 - 2018 Zuse Institute Berlin
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
% you may not use this file except in compliance with the License.
% You may obtain a copy of the License at
%
% -2.0
%
% Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an " AS IS " BASIS ,
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
% See the License for the specific language governing permissions and
% limitations under the License.
@author < >
@doc Implementation of a G - Set ( Grow - only Set ) state - based CRDT .
%% @end
%% @version $Id$
-module(gset).
-author('').
-vsn('Id$').
-include("scalaris.hrl").
-export([update_add/2]).
-export([query_lookup/2]).
GLA utility functions
-export([lt/2]).
-export([exists/2]).
-export([subtract/2]).
-export([fold/3]).
-behaviour(crdt_beh).
-define(SET, ordsets).
-opaque crdt() :: ?SET:ordset(term()).
-include("crdt_beh.hrl").
-spec new() -> crdt().
new() -> ?SET:new().
-spec merge(crdt(), crdt()) -> crdt().
merge(CRDT1, CRDT2) -> ?SET:union(CRDT1, CRDT2).
-spec eq(crdt(), crdt()) -> boolean().
eq(CRDT1, CRDT2) ->
?SET:is_subset(CRDT1, CRDT2) andalso
?SET:is_subset(CRDT2, CRDT1).
-spec lteq(crdt(), crdt()) -> boolean().
lteq(CRDT1, CRDT2) -> ?SET:is_subset(CRDT1, CRDT2).
%%%%%%%%%%%%%%% Available update and query functions
-spec update_add(term(), crdt()) -> crdt().
update_add(ToAdd, CRDT) -> ?SET:add_element(ToAdd, CRDT).
-spec query_lookup(term(), crdt()) -> boolean().
query_lookup(Element, CRDT) -> ?SET:is_element(Element, CRDT).
Utility functions used in GLA implementation
-spec lt(crdt(), crdt()) -> boolean().
lt(CRDT1, CRDT2) -> lteq(CRDT1, CRDT2) andalso not eq(CRDT1, CRDT2).
-spec exists(fun((term()) -> boolean()), crdt()) -> boolean().
exists(PredFun, CRDT) ->
?SET:fold(fun(_, true) -> true;
(E, false) ->
PredFun(E)
end, false, CRDT).
-spec fold(fun((term(), term()) -> term()), term(), crdt()) -> term().
fold(Fun, Acc0, CRDT) ->
?SET:fold(Fun, Acc0, CRDT).
-spec subtract(crdt(), crdt()) -> crdt().
subtract(CRDT1, CRDT2) -> ?SET:subtract(CRDT1, CRDT2).
| null | https://raw.githubusercontent.com/scalaris-team/scalaris/feb894d54e642bb3530e709e730156b0ecc1635f/src/crdt/types/gset.erl | erlang | you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
@end
@version $Id$
Available update and query functions | 2008 - 2018 Zuse Institute Berlin
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
distributed under the License is distributed on an " AS IS " BASIS ,
@author < >
@doc Implementation of a G - Set ( Grow - only Set ) state - based CRDT .
-module(gset).
-author('').
-vsn('Id$').
-include("scalaris.hrl").
-export([update_add/2]).
-export([query_lookup/2]).
GLA utility functions
-export([lt/2]).
-export([exists/2]).
-export([subtract/2]).
-export([fold/3]).
-behaviour(crdt_beh).
-define(SET, ordsets).
-opaque crdt() :: ?SET:ordset(term()).
-include("crdt_beh.hrl").
-spec new() -> crdt().
new() -> ?SET:new().
-spec merge(crdt(), crdt()) -> crdt().
merge(CRDT1, CRDT2) -> ?SET:union(CRDT1, CRDT2).
-spec eq(crdt(), crdt()) -> boolean().
eq(CRDT1, CRDT2) ->
?SET:is_subset(CRDT1, CRDT2) andalso
?SET:is_subset(CRDT2, CRDT1).
-spec lteq(crdt(), crdt()) -> boolean().
lteq(CRDT1, CRDT2) -> ?SET:is_subset(CRDT1, CRDT2).
-spec update_add(term(), crdt()) -> crdt().
update_add(ToAdd, CRDT) -> ?SET:add_element(ToAdd, CRDT).
-spec query_lookup(term(), crdt()) -> boolean().
query_lookup(Element, CRDT) -> ?SET:is_element(Element, CRDT).
Utility functions used in GLA implementation
-spec lt(crdt(), crdt()) -> boolean().
lt(CRDT1, CRDT2) -> lteq(CRDT1, CRDT2) andalso not eq(CRDT1, CRDT2).
-spec exists(fun((term()) -> boolean()), crdt()) -> boolean().
exists(PredFun, CRDT) ->
?SET:fold(fun(_, true) -> true;
(E, false) ->
PredFun(E)
end, false, CRDT).
-spec fold(fun((term(), term()) -> term()), term(), crdt()) -> term().
fold(Fun, Acc0, CRDT) ->
?SET:fold(Fun, Acc0, CRDT).
-spec subtract(crdt(), crdt()) -> crdt().
subtract(CRDT1, CRDT2) -> ?SET:subtract(CRDT1, CRDT2).
|
c9af9f47fa517a7acda0815a27b2132d8c361368b0195291b721019534b79606 | naoiwata/sicp | ex4.02.scm | ;;
;; @author naoiwata
SICP Chapter4
Exercise 4.02 .
;;
; ------------------------------------------------------------------------
; solution
; ------------------------------------------------------------------------
; a
; Louis code
(define (eval exp env)
(cond
((self-evalutating? exp) exp)
((variable? exp) (lookup-variable-value exp env))
((quoted? exp) (text-of-quotation exp))
((application? exp)
(apply (eval (operator exp) env)
(list-of-values (operands exp) env)))
((assignment? exp) (eval-assignment exp env))
((definition? exp) (eval-definition exp env))
((if? exp) (eval-if exp env))
((lambda? exp)
(make-procedure (lambda-rparameters exp)
(lambda-body exp)
env))
((begin? exp)
(eval-sequence (lambda-actions exp) env))
((cond? exp) (eval (cond->if exp) env))
(else
(error "Unknown expression type -- EVAL" exp))))
手続きは、assignment ? 手続きよりも application ? 。
( define x 3 ) を評価しようとすると、define 手続きに引数 x , 3 を適応するような処理が実行され、本来意図していた x に 3 を代入しない 。
; b
(define (application? exp)
(tagged-list? exp 'call))
(define (operator exp) (cadr exp))
(define (operands exp) (cddr exp))
| null | https://raw.githubusercontent.com/naoiwata/sicp/7314136c5892de402015acfe4b9148a3558b1211/chapter4/ex4.02.scm | scheme |
@author naoiwata
------------------------------------------------------------------------
solution
------------------------------------------------------------------------
a
Louis code
b | SICP Chapter4
Exercise 4.02 .
(define (eval exp env)
(cond
((self-evalutating? exp) exp)
((variable? exp) (lookup-variable-value exp env))
((quoted? exp) (text-of-quotation exp))
((application? exp)
(apply (eval (operator exp) env)
(list-of-values (operands exp) env)))
((assignment? exp) (eval-assignment exp env))
((definition? exp) (eval-definition exp env))
((if? exp) (eval-if exp env))
((lambda? exp)
(make-procedure (lambda-rparameters exp)
(lambda-body exp)
env))
((begin? exp)
(eval-sequence (lambda-actions exp) env))
((cond? exp) (eval (cond->if exp) env))
(else
(error "Unknown expression type -- EVAL" exp))))
手続きは、assignment ? 手続きよりも application ? 。
( define x 3 ) を評価しようとすると、define 手続きに引数 x , 3 を適応するような処理が実行され、本来意図していた x に 3 を代入しない 。
(define (application? exp)
(tagged-list? exp 'call))
(define (operator exp) (cadr exp))
(define (operands exp) (cddr exp))
|
7268b0127f0633ff343843a7228bcfaa6489648a7fbac005eead6a76fcc0eb53 | 3b/learnopengl | shader-uniform.lisp | ;;;; shader code
(defpackage shaders-uniform/shaders
(:use #:3bgl-glsl/cl)
;; shadow POSITION so we don't conflict with the default definition
of CL : POSITION as ( input position : vec4 : location 0 )
(:shadow position))
(in-package shaders-uniform/shaders)
(input position :vec3 :location 0)
;; if we want to use the same name for different things in different
;; stages, we need to specify which we mean. If a stage isn't
;; specified, the same definition will be included in any stage that uses
;; the variable.
(input color :vec3 :location 1 :stage :vertex)
(output our-color :vec3 :stage :vertex)
(output color :vec4 :stage :fragment)
;; uniforms allow more keywords:
;; (uniform name type &key stage location layout qualifiers default)
(uniform our-color :vec4 :stage :fragment)
(defun vertex ()
(setf gl-position (vec4 position 1)
our-color color))
(defun fragment ()
(setf color our-color))
;;;; back to normal lisp code
(in-package learning-opengl)
(defclass shader-uniforms (common2)
((uniform-location :initform nil :accessor uniform-location))
(:default-initargs
:shader-parts '(:vertex-shader shaders-uniform/shaders::vertex
:fragment-shader shaders-uniform/shaders::fragment)))
(defmethod init :after ((w shader-uniforms))
(setf (uniform-location w)
(gl:get-uniform-location (shader-program w) "ourColor")))
(defmethod draw :before ((w shader-uniforms))
(let* ((time-value (float (/ (get-internal-real-time)
internal-time-units-per-second)))
(green-value (/ (1+ (sin time-value)) 2)))
;; update the uniform
(gl:uniformf (uniform-location w) 0 green-value 0 1)))
#++
(common 'shader-uniforms)
| null | https://raw.githubusercontent.com/3b/learnopengl/30f910895ef336ac5ff0b4cc676af506413bb953/factored/shader-uniform.lisp | lisp | shader code
shadow POSITION so we don't conflict with the default definition
if we want to use the same name for different things in different
stages, we need to specify which we mean. If a stage isn't
specified, the same definition will be included in any stage that uses
the variable.
uniforms allow more keywords:
(uniform name type &key stage location layout qualifiers default)
back to normal lisp code
update the uniform |
(defpackage shaders-uniform/shaders
(:use #:3bgl-glsl/cl)
of CL : POSITION as ( input position : vec4 : location 0 )
(:shadow position))
(in-package shaders-uniform/shaders)
(input position :vec3 :location 0)
(input color :vec3 :location 1 :stage :vertex)
(output our-color :vec3 :stage :vertex)
(output color :vec4 :stage :fragment)
(uniform our-color :vec4 :stage :fragment)
(defun vertex ()
(setf gl-position (vec4 position 1)
our-color color))
(defun fragment ()
(setf color our-color))
(in-package learning-opengl)
(defclass shader-uniforms (common2)
((uniform-location :initform nil :accessor uniform-location))
(:default-initargs
:shader-parts '(:vertex-shader shaders-uniform/shaders::vertex
:fragment-shader shaders-uniform/shaders::fragment)))
(defmethod init :after ((w shader-uniforms))
(setf (uniform-location w)
(gl:get-uniform-location (shader-program w) "ourColor")))
(defmethod draw :before ((w shader-uniforms))
(let* ((time-value (float (/ (get-internal-real-time)
internal-time-units-per-second)))
(green-value (/ (1+ (sin time-value)) 2)))
(gl:uniformf (uniform-location w) 0 green-value 0 1)))
#++
(common 'shader-uniforms)
|
f8d49f80cba10875788e38c3a06625383c6ff53f47738e335ebc2c0a1bda10bf | eholk/harlan | driver.scm | (library
(harlan driver)
(export get-cflags g++-compile-stdin read-source output-filename)
(import
(rnrs)
(only (elegant-weapons helpers) join)
(elegant-weapons match)
(util system)
(util compat)
(harlan compile-opts))
(define (get-cflags)
(case (get-os)
('darwin '("-framework OpenCL"))
('linux '("-I/opt/cuda/include" "-I/usr/local/cuda/include"
"-I/opt/nvidia/cudatoolkit/default/include"
"-L/opt/cray/nvidia/default/lib64/"
Hack for delta.futuregrid.org -RRN
"-lOpenCL" "-lrt"))))
(define (get-runtime)
(if (make-shared-object)
(string-append (HARLAND) "/rt/libharlanrts.a")
(string-append (HARLAND) "/rt/libharlanrt.a")))
;; Converts foo/bar.kfc to bar
(define (output-filename input)
(let ((base (path-last (path-root input))))
(if (make-shared-object)
(string-append base (case (get-os)
('linux ".so")
('darwin ".dylib")))
base)))
(define (g++-compile-stdin src outfile . args)
(let* ((src-tmp (string-append outfile ".cpp"))
(command
(join " " (append `("g++"
,(if (generate-debug) "-g" "")
,(if (make-shared-object) "-shared -fPIC" "")
"-Wno-unused-value"
"-Wno-comment"
"-O2"
"-x c++"
,src-tmp "-x none"
,(get-runtime)
,(string-append "-I" (HARLAND) "/rt")
"-o" ,outfile
"-lm")
(get-cflags)
args))))
(if (verbose)
(begin (display command) (newline)))
(if (file-exists? src-tmp) (unlink src-tmp))
(let ((out (open-output-file src-tmp)))
(display src out)
(close-output-port out))
(system command)
(unless (generate-debug)
(unlink src-tmp))))
(define (read-source path)
(let* ((file (open-input-file path))
(source (read file)))
(match source
((%testspec ,[parse-testspec -> spec*] ...)
(values (read file) spec*))
((module ,decl* ...)
(values source '())))))
(define (parse-testspec spec)
(match spec
(xfail (error 'parse-testspec "xfail is now a tag"))
(run-fail '(run-fail))
((iterate ,iterspec* ...)
(error 'parse-testspec "iteration is no longer supported"))
((%tags ,tags ...) `(tags ,tags ...))
((compile-fail) `(compile-fail))
((compile-fail ,s) (guard (string? s))
`(compile-fail . ,s))
((run-fail) `(run-fail))
((run-fail ,s) (guard (string? s))
`(run-fail . ,s))
(,else (error 'parse-testspec "Invalid test specification" else))))
;;end library
)
| null | https://raw.githubusercontent.com/eholk/harlan/3afd95b1c3ad02a354481774585e866857a687b8/harlan/driver.scm | scheme | Converts foo/bar.kfc to bar
end library | (library
(harlan driver)
(export get-cflags g++-compile-stdin read-source output-filename)
(import
(rnrs)
(only (elegant-weapons helpers) join)
(elegant-weapons match)
(util system)
(util compat)
(harlan compile-opts))
(define (get-cflags)
(case (get-os)
('darwin '("-framework OpenCL"))
('linux '("-I/opt/cuda/include" "-I/usr/local/cuda/include"
"-I/opt/nvidia/cudatoolkit/default/include"
"-L/opt/cray/nvidia/default/lib64/"
Hack for delta.futuregrid.org -RRN
"-lOpenCL" "-lrt"))))
(define (get-runtime)
(if (make-shared-object)
(string-append (HARLAND) "/rt/libharlanrts.a")
(string-append (HARLAND) "/rt/libharlanrt.a")))
(define (output-filename input)
(let ((base (path-last (path-root input))))
(if (make-shared-object)
(string-append base (case (get-os)
('linux ".so")
('darwin ".dylib")))
base)))
(define (g++-compile-stdin src outfile . args)
(let* ((src-tmp (string-append outfile ".cpp"))
(command
(join " " (append `("g++"
,(if (generate-debug) "-g" "")
,(if (make-shared-object) "-shared -fPIC" "")
"-Wno-unused-value"
"-Wno-comment"
"-O2"
"-x c++"
,src-tmp "-x none"
,(get-runtime)
,(string-append "-I" (HARLAND) "/rt")
"-o" ,outfile
"-lm")
(get-cflags)
args))))
(if (verbose)
(begin (display command) (newline)))
(if (file-exists? src-tmp) (unlink src-tmp))
(let ((out (open-output-file src-tmp)))
(display src out)
(close-output-port out))
(system command)
(unless (generate-debug)
(unlink src-tmp))))
(define (read-source path)
(let* ((file (open-input-file path))
(source (read file)))
(match source
((%testspec ,[parse-testspec -> spec*] ...)
(values (read file) spec*))
((module ,decl* ...)
(values source '())))))
(define (parse-testspec spec)
(match spec
(xfail (error 'parse-testspec "xfail is now a tag"))
(run-fail '(run-fail))
((iterate ,iterspec* ...)
(error 'parse-testspec "iteration is no longer supported"))
((%tags ,tags ...) `(tags ,tags ...))
((compile-fail) `(compile-fail))
((compile-fail ,s) (guard (string? s))
`(compile-fail . ,s))
((run-fail) `(run-fail))
((run-fail ,s) (guard (string? s))
`(run-fail . ,s))
(,else (error 'parse-testspec "Invalid test specification" else))))
)
|
94260d9ac9750e36a71d1440b4e4d0f7046deb5fa1d1f28e61349f5d0ec8bb81 | ocaml-multicore/parafuzz | ctype.mli | (**************************************************************************)
(* *)
(* OCaml *)
(* *)
, projet Cristal , INRIA Rocquencourt
(* *)
Copyright 1996 Institut National de Recherche en Informatique et
(* en Automatique. *)
(* *)
(* All rights reserved. This file is distributed under the terms of *)
the GNU Lesser General Public License version 2.1 , with the
(* special exception on linking described in the file LICENSE. *)
(* *)
(**************************************************************************)
Operations on core types
open Asttypes
open Types
module Unification_trace: sig
(** Unification traces are used to explain unification errors
when printing error messages *)
type position = First | Second
type desc = { t: type_expr; expanded: type_expr option }
type 'a diff = { got: 'a; expected: 'a}
(** Scope escape related errors *)
type 'a escape =
| Constructor of Path.t
| Univ of type_expr
* The type_expr argument of [ Univ ] is always a [ Tunivar _ ] ,
we keep a [ type_expr ] to track renaming in { ! }
we keep a [type_expr] to track renaming in {!Printtyp} *)
| Self
| Module_type of Path.t
| Equation of 'a
(** Errors for polymorphic variants *)
type fixed_row_case =
| Cannot_be_closed
| Cannot_add_tags of string list
type variant =
| No_intersection
| No_tags of position * (Asttypes.label * row_field) list
| Incompatible_types_for of string
| Fixed_row of position * fixed_row_case * fixed_explanation
(** Fixed row types, e.g. ['a. [> `X] as 'a] *)
type obj =
| Missing_field of position * string
| Abstract_row of position
| Self_cannot_be_closed
type 'a elt =
| Diff of 'a diff
| Variant of variant
| Obj of obj
| Escape of {context: type_expr option; kind:'a escape}
| Incompatible_fields of {name:string; diff: type_expr diff }
| Rec_occur of type_expr * type_expr
type t = desc elt list
val diff: type_expr -> type_expr -> desc elt
(** [map_diff f {expected;got}] is [{expected=f expected; got=f got}] *)
val map_diff: ('a -> 'b) -> 'a diff -> 'b diff
(** [flatten f trace] flattens all elements of type {!desc} in
[trace] to either [f x.t expanded] if [x.expanded=Some expanded]
or [f x.t x.t] otherwise *)
val flatten: (type_expr -> type_expr -> 'a) -> t -> 'a elt list
(** Switch [expected] and [got] *)
val swap: t -> t
(** [explain trace f] calls [f] on trace elements starting from the end
until [f ~prev elt] is [Some _], returns that
or [None] if the end of the trace is reached. *)
val explain:
'a elt list ->
(prev:'a elt option -> 'a elt -> 'b option) ->
'b option
end
exception Unify of Unification_trace.t
exception Tags of label * label
exception Subtype of Unification_trace.t * Unification_trace.t
exception Cannot_expand
exception Cannot_apply
val init_def: int -> unit
(* Set the initial variable level *)
val begin_def: unit -> unit
(* Raise the variable level by one at the beginning of a definition. *)
val end_def: unit -> unit
Lower the variable level by one at the end of a definition
val begin_class_def: unit -> unit
val raise_nongen_level: unit -> unit
val reset_global_level: unit -> unit
(* Reset the global level before typing an expression *)
val increase_global_level: unit -> int
val restore_global_level: int -> unit
This pair of functions is only used in Typetexp
type levels =
{ current_level: int; nongen_level: int; global_level: int;
saved_level: (int * int) list; }
val save_levels: unit -> levels
val set_levels: levels -> unit
val create_scope : unit -> int
val newty: type_desc -> type_expr
val newvar: ?name:string -> unit -> type_expr
val newvar2: ?name:string -> int -> type_expr
(* Return a fresh variable *)
val new_global_var: ?name:string -> unit -> type_expr
(* Return a fresh variable, bound at toplevel
(as type variables ['a] in type constraints). *)
val newobj: type_expr -> type_expr
val newconstr: Path.t -> type_expr list -> type_expr
val none: type_expr
(* A dummy type expression *)
val repr: type_expr -> type_expr
(* Return the canonical representative of a type. *)
val object_fields: type_expr -> type_expr
val flatten_fields:
type_expr -> (string * field_kind * type_expr) list * type_expr
(* Transform a field type into a list of pairs label-type *)
(* The fields are sorted *)
val associate_fields:
(string * field_kind * type_expr) list ->
(string * field_kind * type_expr) list ->
(string * field_kind * type_expr * field_kind * type_expr) list *
(string * field_kind * type_expr) list *
(string * field_kind * type_expr) list
val opened_object: type_expr -> bool
val close_object: type_expr -> bool
val row_variable: type_expr -> type_expr
(* Return the row variable of an open object type *)
val set_object_name:
Ident.t -> type_expr -> type_expr list -> type_expr -> unit
val remove_object_name: type_expr -> unit
val hide_private_methods: type_expr -> unit
val find_cltype_for_path: Env.t -> Path.t -> type_declaration * type_expr
val sort_row_fields: (label * row_field) list -> (label * row_field) list
val merge_row_fields:
(label * row_field) list -> (label * row_field) list ->
(label * row_field) list * (label * row_field) list *
(label * row_field * row_field) list
val filter_row_fields:
bool -> (label * row_field) list -> (label * row_field) list
val generalize: type_expr -> unit
in - place the given type
val lower_contravariant: Env.t -> type_expr -> unit
(* Lower level of type variables inside contravariant branches;
to be used before generalize for expansive expressions *)
val generalize_structure: type_expr -> unit
(* Same, but variables are only lowered to !current_level *)
val generalize_spine: type_expr -> unit
(* Special function to generalize a method during inference *)
val correct_levels: type_expr -> type_expr
(* Returns a copy with decreasing levels *)
val limited_generalize: type_expr -> type_expr -> unit
(* Only generalize some part of the type
Make the remaining of the type non-generalizable *)
val check_scope_escape : Env.t -> int -> type_expr -> unit
(* [check_scope_escape env lvl ty] ensures that [ty] could be raised
to the level [lvl] without any scope escape.
Raises [Unify] otherwise *)
val instance: ?partial:bool -> type_expr -> type_expr
(* Take an instance of a type scheme *)
(* partial=None -> normal
partial=false -> newvar() for non generic subterms
partial=true -> newty2 ty.level Tvar for non generic subterms *)
val generic_instance: type_expr -> type_expr
(* Same as instance, but new nodes at generic_level *)
val instance_list: type_expr list -> type_expr list
(* Take an instance of a list of type schemes *)
val existential_name: constructor_description -> type_expr -> string
val instance_constructor:
?in_pattern:Env.t ref * int ->
constructor_description -> type_expr list * type_expr
(* Same, for a constructor *)
val instance_parameterized_type:
?keep_names:bool ->
type_expr list -> type_expr -> type_expr list * type_expr
val instance_parameterized_type_2:
type_expr list -> type_expr list -> type_expr ->
type_expr list * type_expr list * type_expr
val instance_declaration: type_declaration -> type_declaration
val generic_instance_declaration: type_declaration -> type_declaration
(* Same as instance_declaration, but new nodes at generic_level *)
val instance_class:
type_expr list -> class_type -> type_expr list * class_type
val instance_poly:
?keep_names:bool ->
bool -> type_expr list -> type_expr -> type_expr list * type_expr
(* Take an instance of a type scheme containing free univars *)
val instance_label:
bool -> label_description -> type_expr list * type_expr * type_expr
(* Same, for a label *)
val apply:
Env.t -> type_expr list -> type_expr -> type_expr list -> type_expr
(* [apply [p1...pN] t [a1...aN]] match the arguments [ai] to
the parameters [pi] and returns the corresponding instance of
[t]. Exception [Cannot_apply] is raised in case of failure. *)
val expand_head_once: Env.t -> type_expr -> type_expr
val expand_head: Env.t -> type_expr -> type_expr
val try_expand_once_opt: Env.t -> type_expr -> type_expr
val expand_head_opt: Env.t -> type_expr -> type_expr
(** The compiler's own version of [expand_head] necessary for type-based
optimisations. *)
val full_expand: Env.t -> type_expr -> type_expr
val extract_concrete_typedecl:
Env.t -> type_expr -> Path.t * Path.t * type_declaration
Return the original path of the types , and the first concrete
type declaration found expanding it .
Raise [ Not_found ] if none appears or not a type constructor .
type declaration found expanding it.
Raise [Not_found] if none appears or not a type constructor. *)
val enforce_constraints: Env.t -> type_expr -> unit
val get_new_abstract_name : string -> string
val unify: Env.t -> type_expr -> type_expr -> unit
Unify the two types given . Raise [ Unify ] if not possible .
val unify_gadt:
equations_level:int -> Env.t ref -> type_expr -> type_expr -> unit
Unify the two types given and update the environment with the
local constraints . Raise [ Unify ] if not possible .
local constraints. Raise [Unify] if not possible. *)
val unify_var: Env.t -> type_expr -> type_expr -> unit
Same as [ unify ] , but allow free univars when first type
is a variable .
is a variable. *)
val with_passive_variants: ('a -> 'b) -> ('a -> 'b)
(* Call [f] in passive_variants mode, for exhaustiveness check. *)
val filter_arrow: Env.t -> type_expr -> arg_label -> type_expr * type_expr
(* A special case of unification (with l:'a -> 'b). *)
val filter_method: Env.t -> string -> private_flag -> type_expr -> type_expr
(* A special case of unification (with {m : 'a; 'b}). *)
val check_filter_method: Env.t -> string -> private_flag -> type_expr -> unit
(* A special case of unification (with {m : 'a; 'b}), returning unit. *)
val occur_in: Env.t -> type_expr -> type_expr -> bool
val deep_occur: type_expr -> type_expr -> bool
val filter_self_method:
Env.t -> string -> private_flag -> (Ident.t * type_expr) Meths.t ref ->
type_expr -> Ident.t * type_expr
val moregeneral: Env.t -> bool -> type_expr -> type_expr -> bool
Check if the first type scheme is more general than the second .
val rigidify: type_expr -> type_expr list
" Rigidify " a type and return its type variable
val all_distinct_vars: Env.t -> type_expr list -> bool
(* Check those types are all distinct type variables *)
val matches: Env.t -> type_expr -> type_expr -> bool
Same as [ moregeneral false ] , implemented using the two above
functions and backtracking . Ignore levels
functions and backtracking. Ignore levels *)
val reify_univars : Types.type_expr -> Types.type_expr
(* Replaces all the variables of a type by a univar. *)
type class_match_failure =
CM_Virtual_class
| CM_Parameter_arity_mismatch of int * int
| CM_Type_parameter_mismatch of Env.t * Unification_trace.t
| CM_Class_type_mismatch of Env.t * class_type * class_type
| CM_Parameter_mismatch of Env.t * Unification_trace.t
| CM_Val_type_mismatch of string * Env.t * Unification_trace.t
| CM_Meth_type_mismatch of string * Env.t * Unification_trace.t
| CM_Non_mutable_value of string
| CM_Non_concrete_value of string
| CM_Missing_value of string
| CM_Missing_method of string
| CM_Hide_public of string
| CM_Hide_virtual of string * string
| CM_Public_method of string
| CM_Private_method of string
| CM_Virtual_method of string
val match_class_types:
?trace:bool -> Env.t -> class_type -> class_type -> class_match_failure list
Check if the first class type is more general than the second .
val equal: Env.t -> bool -> type_expr list -> type_expr list -> bool
(* [equal env [x1...xn] tau [y1...yn] sigma]
checks whether the parameterized types
[/\x1.../\xn.tau] and [/\y1.../\yn.sigma] are equivalent. *)
val match_class_declarations:
Env.t -> type_expr list -> class_type -> type_expr list ->
class_type -> class_match_failure list
Check if the first class type is more general than the second .
val enlarge_type: Env.t -> type_expr -> type_expr * bool
(* Make a type larger, flag is true if some pruning had to be done *)
val subtype: Env.t -> type_expr -> type_expr -> unit -> unit
(* [subtype env t1 t2] checks that [t1] is a subtype of [t2].
It accumulates the constraints the type variables must
enforce and returns a function that enforces this
constraints. *)
exception Nondep_cannot_erase of Ident.t
val nondep_type: Env.t -> Ident.t list -> type_expr -> type_expr
(* Return a type equivalent to the given type but without
references to any of the given identifiers.
Raise [Nondep_cannot_erase id] if no such type exists because [id],
in particular, could not be erased. *)
val nondep_type_decl:
Env.t -> Ident.t list -> bool -> type_declaration -> type_declaration
(* Same for type declarations. *)
val nondep_extension_constructor:
Env.t -> Ident.t list -> extension_constructor ->
extension_constructor
(* Same for extension constructor *)
val nondep_class_declaration:
Env.t -> Ident.t list -> class_declaration -> class_declaration
(* Same for class declarations. *)
val nondep_cltype_declaration:
Env.t -> Ident.t list -> class_type_declaration -> class_type_declaration
(* Same for class type declarations. *)
correct_abbrev : - > Path.t - > type_expr list - > type_expr - > unit
val cyclic_abbrev: Env.t -> Ident.t -> type_expr -> bool
val is_contractive: Env.t -> Path.t -> bool
val normalize_type: Env.t -> type_expr -> unit
val closed_schema: Env.t -> type_expr -> bool
(* Check whether the given type scheme contains no non-generic
type variables *)
val free_variables: ?env:Env.t -> type_expr -> type_expr list
(* If env present, then check for incomplete definitions too *)
val closed_type_decl: type_declaration -> type_expr option
val closed_extension_constructor: extension_constructor -> type_expr option
type closed_class_failure =
CC_Method of type_expr * bool * string * type_expr
| CC_Value of type_expr * bool * string * type_expr
val closed_class:
type_expr list -> class_signature -> closed_class_failure option
(* Check whether all type variables are bound *)
val unalias: type_expr -> type_expr
val signature_of_class_type: class_type -> class_signature
val self_type: class_type -> type_expr
val class_type_arity: class_type -> int
val arity: type_expr -> int
(* Return the arity (as for curried functions) of the given type. *)
val collapse_conj_params: Env.t -> type_expr list -> unit
(* Collapse conjunctive types in class parameters *)
val get_current_level: unit -> int
val wrap_trace_gadt_instances: Env.t -> ('a -> 'b) -> 'a -> 'b
val reset_reified_var_counter: unit -> unit
val immediacy : Env.t -> type_expr -> Type_immediacy.t
val maybe_pointer_type : Env.t -> type_expr -> bool
(* True if type is possibly pointer, false if definitely not a pointer *)
(* Stubs *)
val package_subtype :
(Env.t -> Path.t -> Longident.t list -> type_expr list ->
Path.t -> Longident.t list -> type_expr list -> bool) ref
val mcomp : Env.t -> type_expr -> type_expr -> unit
| null | https://raw.githubusercontent.com/ocaml-multicore/parafuzz/6a92906f1ba03287ffcb433063bded831a644fd5/typing/ctype.mli | ocaml | ************************************************************************
OCaml
en Automatique.
All rights reserved. This file is distributed under the terms of
special exception on linking described in the file LICENSE.
************************************************************************
* Unification traces are used to explain unification errors
when printing error messages
* Scope escape related errors
* Errors for polymorphic variants
* Fixed row types, e.g. ['a. [> `X] as 'a]
* [map_diff f {expected;got}] is [{expected=f expected; got=f got}]
* [flatten f trace] flattens all elements of type {!desc} in
[trace] to either [f x.t expanded] if [x.expanded=Some expanded]
or [f x.t x.t] otherwise
* Switch [expected] and [got]
* [explain trace f] calls [f] on trace elements starting from the end
until [f ~prev elt] is [Some _], returns that
or [None] if the end of the trace is reached.
Set the initial variable level
Raise the variable level by one at the beginning of a definition.
Reset the global level before typing an expression
Return a fresh variable
Return a fresh variable, bound at toplevel
(as type variables ['a] in type constraints).
A dummy type expression
Return the canonical representative of a type.
Transform a field type into a list of pairs label-type
The fields are sorted
Return the row variable of an open object type
Lower level of type variables inside contravariant branches;
to be used before generalize for expansive expressions
Same, but variables are only lowered to !current_level
Special function to generalize a method during inference
Returns a copy with decreasing levels
Only generalize some part of the type
Make the remaining of the type non-generalizable
[check_scope_escape env lvl ty] ensures that [ty] could be raised
to the level [lvl] without any scope escape.
Raises [Unify] otherwise
Take an instance of a type scheme
partial=None -> normal
partial=false -> newvar() for non generic subterms
partial=true -> newty2 ty.level Tvar for non generic subterms
Same as instance, but new nodes at generic_level
Take an instance of a list of type schemes
Same, for a constructor
Same as instance_declaration, but new nodes at generic_level
Take an instance of a type scheme containing free univars
Same, for a label
[apply [p1...pN] t [a1...aN]] match the arguments [ai] to
the parameters [pi] and returns the corresponding instance of
[t]. Exception [Cannot_apply] is raised in case of failure.
* The compiler's own version of [expand_head] necessary for type-based
optimisations.
Call [f] in passive_variants mode, for exhaustiveness check.
A special case of unification (with l:'a -> 'b).
A special case of unification (with {m : 'a; 'b}).
A special case of unification (with {m : 'a; 'b}), returning unit.
Check those types are all distinct type variables
Replaces all the variables of a type by a univar.
[equal env [x1...xn] tau [y1...yn] sigma]
checks whether the parameterized types
[/\x1.../\xn.tau] and [/\y1.../\yn.sigma] are equivalent.
Make a type larger, flag is true if some pruning had to be done
[subtype env t1 t2] checks that [t1] is a subtype of [t2].
It accumulates the constraints the type variables must
enforce and returns a function that enforces this
constraints.
Return a type equivalent to the given type but without
references to any of the given identifiers.
Raise [Nondep_cannot_erase id] if no such type exists because [id],
in particular, could not be erased.
Same for type declarations.
Same for extension constructor
Same for class declarations.
Same for class type declarations.
Check whether the given type scheme contains no non-generic
type variables
If env present, then check for incomplete definitions too
Check whether all type variables are bound
Return the arity (as for curried functions) of the given type.
Collapse conjunctive types in class parameters
True if type is possibly pointer, false if definitely not a pointer
Stubs | , projet Cristal , INRIA Rocquencourt
Copyright 1996 Institut National de Recherche en Informatique et
the GNU Lesser General Public License version 2.1 , with the
Operations on core types
open Asttypes
open Types
module Unification_trace: sig
type position = First | Second
type desc = { t: type_expr; expanded: type_expr option }
type 'a diff = { got: 'a; expected: 'a}
type 'a escape =
| Constructor of Path.t
| Univ of type_expr
* The type_expr argument of [ Univ ] is always a [ Tunivar _ ] ,
we keep a [ type_expr ] to track renaming in { ! }
we keep a [type_expr] to track renaming in {!Printtyp} *)
| Self
| Module_type of Path.t
| Equation of 'a
type fixed_row_case =
| Cannot_be_closed
| Cannot_add_tags of string list
type variant =
| No_intersection
| No_tags of position * (Asttypes.label * row_field) list
| Incompatible_types_for of string
| Fixed_row of position * fixed_row_case * fixed_explanation
type obj =
| Missing_field of position * string
| Abstract_row of position
| Self_cannot_be_closed
type 'a elt =
| Diff of 'a diff
| Variant of variant
| Obj of obj
| Escape of {context: type_expr option; kind:'a escape}
| Incompatible_fields of {name:string; diff: type_expr diff }
| Rec_occur of type_expr * type_expr
type t = desc elt list
val diff: type_expr -> type_expr -> desc elt
val map_diff: ('a -> 'b) -> 'a diff -> 'b diff
val flatten: (type_expr -> type_expr -> 'a) -> t -> 'a elt list
val swap: t -> t
val explain:
'a elt list ->
(prev:'a elt option -> 'a elt -> 'b option) ->
'b option
end
exception Unify of Unification_trace.t
exception Tags of label * label
exception Subtype of Unification_trace.t * Unification_trace.t
exception Cannot_expand
exception Cannot_apply
val init_def: int -> unit
val begin_def: unit -> unit
val end_def: unit -> unit
Lower the variable level by one at the end of a definition
val begin_class_def: unit -> unit
val raise_nongen_level: unit -> unit
val reset_global_level: unit -> unit
val increase_global_level: unit -> int
val restore_global_level: int -> unit
This pair of functions is only used in Typetexp
type levels =
{ current_level: int; nongen_level: int; global_level: int;
saved_level: (int * int) list; }
val save_levels: unit -> levels
val set_levels: levels -> unit
val create_scope : unit -> int
val newty: type_desc -> type_expr
val newvar: ?name:string -> unit -> type_expr
val newvar2: ?name:string -> int -> type_expr
val new_global_var: ?name:string -> unit -> type_expr
val newobj: type_expr -> type_expr
val newconstr: Path.t -> type_expr list -> type_expr
val none: type_expr
val repr: type_expr -> type_expr
val object_fields: type_expr -> type_expr
val flatten_fields:
type_expr -> (string * field_kind * type_expr) list * type_expr
val associate_fields:
(string * field_kind * type_expr) list ->
(string * field_kind * type_expr) list ->
(string * field_kind * type_expr * field_kind * type_expr) list *
(string * field_kind * type_expr) list *
(string * field_kind * type_expr) list
val opened_object: type_expr -> bool
val close_object: type_expr -> bool
val row_variable: type_expr -> type_expr
val set_object_name:
Ident.t -> type_expr -> type_expr list -> type_expr -> unit
val remove_object_name: type_expr -> unit
val hide_private_methods: type_expr -> unit
val find_cltype_for_path: Env.t -> Path.t -> type_declaration * type_expr
val sort_row_fields: (label * row_field) list -> (label * row_field) list
val merge_row_fields:
(label * row_field) list -> (label * row_field) list ->
(label * row_field) list * (label * row_field) list *
(label * row_field * row_field) list
val filter_row_fields:
bool -> (label * row_field) list -> (label * row_field) list
val generalize: type_expr -> unit
in - place the given type
val lower_contravariant: Env.t -> type_expr -> unit
val generalize_structure: type_expr -> unit
val generalize_spine: type_expr -> unit
val correct_levels: type_expr -> type_expr
val limited_generalize: type_expr -> type_expr -> unit
val check_scope_escape : Env.t -> int -> type_expr -> unit
val instance: ?partial:bool -> type_expr -> type_expr
val generic_instance: type_expr -> type_expr
val instance_list: type_expr list -> type_expr list
val existential_name: constructor_description -> type_expr -> string
val instance_constructor:
?in_pattern:Env.t ref * int ->
constructor_description -> type_expr list * type_expr
val instance_parameterized_type:
?keep_names:bool ->
type_expr list -> type_expr -> type_expr list * type_expr
val instance_parameterized_type_2:
type_expr list -> type_expr list -> type_expr ->
type_expr list * type_expr list * type_expr
val instance_declaration: type_declaration -> type_declaration
val generic_instance_declaration: type_declaration -> type_declaration
val instance_class:
type_expr list -> class_type -> type_expr list * class_type
val instance_poly:
?keep_names:bool ->
bool -> type_expr list -> type_expr -> type_expr list * type_expr
val instance_label:
bool -> label_description -> type_expr list * type_expr * type_expr
val apply:
Env.t -> type_expr list -> type_expr -> type_expr list -> type_expr
val expand_head_once: Env.t -> type_expr -> type_expr
val expand_head: Env.t -> type_expr -> type_expr
val try_expand_once_opt: Env.t -> type_expr -> type_expr
val expand_head_opt: Env.t -> type_expr -> type_expr
val full_expand: Env.t -> type_expr -> type_expr
val extract_concrete_typedecl:
Env.t -> type_expr -> Path.t * Path.t * type_declaration
Return the original path of the types , and the first concrete
type declaration found expanding it .
Raise [ Not_found ] if none appears or not a type constructor .
type declaration found expanding it.
Raise [Not_found] if none appears or not a type constructor. *)
val enforce_constraints: Env.t -> type_expr -> unit
val get_new_abstract_name : string -> string
val unify: Env.t -> type_expr -> type_expr -> unit
Unify the two types given . Raise [ Unify ] if not possible .
val unify_gadt:
equations_level:int -> Env.t ref -> type_expr -> type_expr -> unit
Unify the two types given and update the environment with the
local constraints . Raise [ Unify ] if not possible .
local constraints. Raise [Unify] if not possible. *)
val unify_var: Env.t -> type_expr -> type_expr -> unit
Same as [ unify ] , but allow free univars when first type
is a variable .
is a variable. *)
val with_passive_variants: ('a -> 'b) -> ('a -> 'b)
val filter_arrow: Env.t -> type_expr -> arg_label -> type_expr * type_expr
val filter_method: Env.t -> string -> private_flag -> type_expr -> type_expr
val check_filter_method: Env.t -> string -> private_flag -> type_expr -> unit
val occur_in: Env.t -> type_expr -> type_expr -> bool
val deep_occur: type_expr -> type_expr -> bool
val filter_self_method:
Env.t -> string -> private_flag -> (Ident.t * type_expr) Meths.t ref ->
type_expr -> Ident.t * type_expr
val moregeneral: Env.t -> bool -> type_expr -> type_expr -> bool
Check if the first type scheme is more general than the second .
val rigidify: type_expr -> type_expr list
" Rigidify " a type and return its type variable
val all_distinct_vars: Env.t -> type_expr list -> bool
val matches: Env.t -> type_expr -> type_expr -> bool
Same as [ moregeneral false ] , implemented using the two above
functions and backtracking . Ignore levels
functions and backtracking. Ignore levels *)
val reify_univars : Types.type_expr -> Types.type_expr
type class_match_failure =
CM_Virtual_class
| CM_Parameter_arity_mismatch of int * int
| CM_Type_parameter_mismatch of Env.t * Unification_trace.t
| CM_Class_type_mismatch of Env.t * class_type * class_type
| CM_Parameter_mismatch of Env.t * Unification_trace.t
| CM_Val_type_mismatch of string * Env.t * Unification_trace.t
| CM_Meth_type_mismatch of string * Env.t * Unification_trace.t
| CM_Non_mutable_value of string
| CM_Non_concrete_value of string
| CM_Missing_value of string
| CM_Missing_method of string
| CM_Hide_public of string
| CM_Hide_virtual of string * string
| CM_Public_method of string
| CM_Private_method of string
| CM_Virtual_method of string
val match_class_types:
?trace:bool -> Env.t -> class_type -> class_type -> class_match_failure list
Check if the first class type is more general than the second .
val equal: Env.t -> bool -> type_expr list -> type_expr list -> bool
val match_class_declarations:
Env.t -> type_expr list -> class_type -> type_expr list ->
class_type -> class_match_failure list
Check if the first class type is more general than the second .
val enlarge_type: Env.t -> type_expr -> type_expr * bool
val subtype: Env.t -> type_expr -> type_expr -> unit -> unit
exception Nondep_cannot_erase of Ident.t
val nondep_type: Env.t -> Ident.t list -> type_expr -> type_expr
val nondep_type_decl:
Env.t -> Ident.t list -> bool -> type_declaration -> type_declaration
val nondep_extension_constructor:
Env.t -> Ident.t list -> extension_constructor ->
extension_constructor
val nondep_class_declaration:
Env.t -> Ident.t list -> class_declaration -> class_declaration
val nondep_cltype_declaration:
Env.t -> Ident.t list -> class_type_declaration -> class_type_declaration
correct_abbrev : - > Path.t - > type_expr list - > type_expr - > unit
val cyclic_abbrev: Env.t -> Ident.t -> type_expr -> bool
val is_contractive: Env.t -> Path.t -> bool
val normalize_type: Env.t -> type_expr -> unit
val closed_schema: Env.t -> type_expr -> bool
val free_variables: ?env:Env.t -> type_expr -> type_expr list
val closed_type_decl: type_declaration -> type_expr option
val closed_extension_constructor: extension_constructor -> type_expr option
type closed_class_failure =
CC_Method of type_expr * bool * string * type_expr
| CC_Value of type_expr * bool * string * type_expr
val closed_class:
type_expr list -> class_signature -> closed_class_failure option
val unalias: type_expr -> type_expr
val signature_of_class_type: class_type -> class_signature
val self_type: class_type -> type_expr
val class_type_arity: class_type -> int
val arity: type_expr -> int
val collapse_conj_params: Env.t -> type_expr list -> unit
val get_current_level: unit -> int
val wrap_trace_gadt_instances: Env.t -> ('a -> 'b) -> 'a -> 'b
val reset_reified_var_counter: unit -> unit
val immediacy : Env.t -> type_expr -> Type_immediacy.t
val maybe_pointer_type : Env.t -> type_expr -> bool
val package_subtype :
(Env.t -> Path.t -> Longident.t list -> type_expr list ->
Path.t -> Longident.t list -> type_expr list -> bool) ref
val mcomp : Env.t -> type_expr -> type_expr -> unit
|
1aee47ae7432170f4cec2ead49b1c8d993f932f35926e98024fafa3189af790c | camllight/camllight | fnat.ml | nat : fonctions auxiliaires et d impression pour le type .
Derive de nats.ml de Caml V3.1 , .
Adapte a Caml Light par Xavier Leroy & .
Portage 64 bits : .
Derive de nats.ml de Caml V3.1, Valerie Menissier.
Adapte a Caml Light par Xavier Leroy & Pierre Weis.
Portage 64 bits: Pierre Weis. *)
#open "eq";;
#open "exc";;
#open "int";;
#open "bool";;
#open "ref";;
#open "fstring";;
#open "fvect";;
#open "fchar";;
#open "int_misc";;
(* Nat temporaries *)
let tmp_A_2 = create_nat 2
and tmp_A_1 = create_nat 1
and tmp_B_2 = create_nat 2
;;
(* Sizes of words and strings. *)
let length_of_digit = sys__word_size;;
let make_nat len =
if len <= 0 then invalid_arg "make_nat" else
let res = create_nat len in set_to_zero_nat res 0 len; res
;;
let copy_nat nat off_set length =
let res = create_nat (length) in
blit_nat res 0 nat off_set length;
res
;;
let zero_nat = make_nat 1;;
let is_zero_nat n off len =
compare_nat zero_nat 0 1 n off (num_digits_nat n off len) == 0
;;
let is_nat_int nat off len =
num_digits_nat nat off len == 1 && is_digit_int nat off
;;
let sys_int_of_nat nat off len =
if is_nat_int nat off len
then nth_digit_nat nat off
else failwith "sys_int_of_nat"
;;
let int_of_nat nat =
sys_int_of_nat nat 0 (length_nat nat)
;;
let nat_of_int i =
if i < 0 then invalid_arg "nat_of_int" else
let res = create_nat 1 in
set_digit_nat res 0 i;
res
;;
let eq_nat nat1 off1 len1 nat2 off2 len2 =
compare_nat nat1 off1 (num_digits_nat nat1 off1 len1)
nat2 off2 (num_digits_nat nat2 off2 len2) == 0
and le_nat nat1 off1 len1 nat2 off2 len2 =
compare_nat nat1 off1 (num_digits_nat nat1 off1 len1)
nat2 off2 (num_digits_nat nat2 off2 len2) <= 0
and lt_nat nat1 off1 len1 nat2 off2 len2 =
compare_nat nat1 off1 (num_digits_nat nat1 off1 len1)
nat2 off2 (num_digits_nat nat2 off2 len2) < 0
and ge_nat nat1 off1 len1 nat2 off2 len2 =
compare_nat nat1 off1 (num_digits_nat nat1 off1 len1)
nat2 off2 (num_digits_nat nat2 off2 len2) >= 0
and gt_nat nat1 off1 len1 nat2 off2 len2 =
compare_nat nat1 off1 (num_digits_nat nat1 off1 len1)
nat2 off2 (num_digits_nat nat2 off2 len2) > 0
;;
let square_nat nat1 off1 len1 nat2 off2 len2 =
mult_nat nat1 off1 len1 nat2 off2 len2 nat2 off2 len2
;;
let set_square_nat nat1 off1 len1 nat2 off2 len2 =
let _ = square_nat nat1 off1 len1 nat2 off2 len2 in ();;
let gcd_int_nat i nat off len =
if i == 0 then 1 else
if is_nat_int nat off len then begin
set_digit_nat nat off (gcd_int (nth_digit_nat nat off) i); 0
end else begin
let len_copy = succ len in
let copy = create_nat len_copy
and quotient = create_nat 1
and remainder = create_nat 1 in
blit_nat copy 0 nat off len;
set_digit_nat copy len 0;
div_digit_nat quotient 0 remainder 0 copy 0 len_copy (nat_of_int i) 0;
set_digit_nat nat off (gcd_int (nth_digit_nat remainder 0) i);
0
end
;;
let exchange r1 r2 =
let old1 = !r1 in r1 := !r2; r2 := old1
;;
let gcd_nat nat1 off1 len1 nat2 off2 len2 =
if is_zero_nat nat1 off1 len1 then begin
blit_nat nat1 off1 nat2 off2 len2; len2
end else begin
let copy1 = ref (create_nat (succ len1))
and copy2 = ref (create_nat (succ len2)) in
blit_nat !copy1 0 nat1 off1 len1;
blit_nat !copy2 0 nat2 off2 len2;
set_digit_nat !copy1 len1 0;
set_digit_nat !copy2 len2 0;
if lt_nat !copy1 0 len1 !copy2 0 len2
then exchange copy1 copy2;
let real_len1 =
ref (num_digits_nat !copy1 0 (length_nat !copy1))
and real_len2 =
ref (num_digits_nat !copy2 0 (length_nat !copy2)) in
while not (is_zero_nat !copy2 0 !real_len2) do
set_digit_nat !copy1 !real_len1 0;
div_nat !copy1 0 (succ !real_len1) !copy2 0 !real_len2;
exchange copy1 copy2;
real_len1 := !real_len2;
real_len2 := num_digits_nat !copy2 0 !real_len2
done;
blit_nat nat1 off1 !copy1 0 !real_len1;
!real_len1
end
;;
( entière par défaut ) .
Théorème : la suite xn+1 = ( xn + a / xn ) / 2 converge vers la racine
a par défaut , si on part d'une valeur x0
strictement plus grande que la racine de a , sauf quand a est un
carré - 1 , suite alterne entre la racine par défaut
et par excès . Dans tous les cas , le dernier terme de la partie
strictement est .
let sqrt_nat rad off len =
let len = num_digits_nat rad off len in
Copie de travail du radicande
let len_parity = len mod 2 in
let rad_len = len + 1 + len_parity in
let rad =
let res = create_nat rad_len in
blit_nat res 0 rad off len;
set_digit_nat res len 0;
set_digit_nat res (rad_len - 1) 0;
res in
let cand_len = (len + 1) / 2 in (* ceiling len / 2 *)
let cand_rest = rad_len - cand_len in
Racine carrée supposée cand = " |FFFF .... | "
let cand = make_nat cand_len in
Amélioration de la racine de départ :
on bits significatifs du premier digit du candidat
( la moitié du nombre de bits significatifs dans les deux premiers
digits du radicande étendu à une longueur paire ) .
shift_cand est word_size - nbb
on calcule nbb le nombre de bits significatifs du premier digit du candidat
(la moitié du nombre de bits significatifs dans les deux premiers
digits du radicande étendu à une longueur paire).
shift_cand est word_size - nbb *)
let shift_cand =
((num_leading_zero_bits_in_digit rad (len-1)) +
sys__word_size * len_parity) / 2 in
Tous les bits du radicande sont à 0 , on rend 0 .
if shift_cand == sys__word_size then cand else
begin
complement_nat cand 0 cand_len;
shift_right_nat cand 0 1 tmp_A_1 0 shift_cand;
let next_cand = create_nat rad_len in
(* Repeat until *)
let rec loop () =
(* next_cand := rad *)
blit_nat next_cand 0 rad 0 rad_len;
(* next_cand <- next_cand / cand *)
div_nat next_cand 0 rad_len cand 0 cand_len;
(* next_cand (poids fort) <- next_cand (poids fort) + cand,
i.e. next_cand <- cand + rad / cand *)
set_add_nat next_cand cand_len cand_rest cand 0 cand_len 0;
(* next_cand <- next_cand / 2 *)
shift_right_nat next_cand cand_len cand_rest tmp_A_1 0 1;
if lt_nat next_cand cand_len cand_rest cand 0 cand_len then
begin (* cand <- next_cand *)
blit_nat cand 0 next_cand cand_len cand_len; loop ()
end
else cand in
loop ()
end;;
let max_superscript_10_power_in_int =
match sys__word_size with
| 64 -> 18
| 32 -> 9
| _ -> invalid_arg "Bad word size";;
let max_power_10_power_in_int =
match sys__word_size with
| 64 -> nat_of_int 1000000000000000000
| 32 -> nat_of_int 1000000000
| _ -> invalid_arg "Bad word size";;
let sys_string_of_digit nat off =
if is_nat_int nat off 1 then string_of_int (nth_digit_nat nat off) else
begin
blit_nat tmp_B_2 0 nat off 1;
set_to_zero_nat tmp_B_2 1 1;
div_digit_nat tmp_A_2 0 tmp_A_1 0 tmp_B_2 0 2 max_power_10_power_in_int 0;
let leading_digits = nth_digit_nat tmp_A_2 0
and s1 = string_of_int (nth_digit_nat tmp_A_1 0) in
let len = string_length s1 in
if leading_digits < 10 then begin
let result = make_string (max_superscript_10_power_in_int + 1) `0` in
result.[0] <- char_of_int (48 + leading_digits);
blit_string s1 0 result (string_length result - len) len;
result
end else begin
let result = make_string (max_superscript_10_power_in_int + 2) `0` in
blit_string (string_of_int leading_digits) 0 result 0 2;
blit_string s1 0 result (string_length result - len) len;
result
end
end
;;
let string_of_digit nat =
sys_string_of_digit nat 0
;;
make_power_base affecte power_base des puissances successives de base a
partir de la puissance 1 - ieme .
A la fin de la boucle i-1 est la plus grande puissance de la base qui tient
sur un seul digit et j est la plus grande puissance de la base qui tient
sur un int .
Attention base n''est pas forcément une base valide ( utilisé en
particulier dans big_int ) .
partir de la puissance 1-ieme.
A la fin de la boucle i-1 est la plus grande puissance de la base qui tient
sur un seul digit et j est la plus grande puissance de la base qui tient
sur un int.
Attention base n''est pas forcément une base valide (utilisé en
particulier dans big_int avec un entier quelconque). *)
let make_power_base base power_base =
let i = ref 1
and j = ref 0 in
set_digit_nat power_base 0 base;
while is_digit_zero power_base !i do
set_mult_digit_nat power_base !i 2 power_base (pred !i) 1 power_base 0;
incr i
done;
decr i;
while !j <= !i && is_digit_int power_base !j do incr j done;
(!i - 1, min !i !j);;
On compte les zéros placés au début de la chaîne ,
on en déduit la
et on construit la chaîne adhoc en y ajoutant before et after .
on en déduit la longueur réelle de la chaîne
et on construit la chaîne adhoc en y ajoutant before et after. *)
let adjust_string s before after =
let len_s = string_length s
and k = ref 0 in
while !k < len_s - 1 && s.[!k] == `0`
do incr k
done;
let len_before = string_length before
and len_after = string_length after
and l1 = max (len_s - !k) 1 in
let l2 = len_before + l1 in
if l2 <= 0 then failwith "adjust_string" else
let ok_len = l2 + len_after in
let ok_s = create_string ok_len in
blit_string before 0 ok_s 0 len_before;
blit_string s !k ok_s len_before l1;
blit_string after 0 ok_s l2 len_after;
ok_s
;;
let power_base_int base i =
if i == 0 then
nat_of_int 1
else if i < 0 then
invalid_arg "power_base_int"
else begin
let power_base = make_nat (succ length_of_digit) in
let (pmax, pint) = make_power_base base power_base in
let n = i / (succ pmax)
and rem = i mod (succ pmax) in
if n > 0 then begin
let newn =
if i == biggest_int then n else (succ n) in
let res = make_nat newn
and res2 = make_nat newn
and l = num_bits_int n - 2 in
let p = ref (1 lsl l) in
blit_nat res 0 power_base pmax 1;
for i = l downto 0 do
let len = num_digits_nat res 0 newn in
let len2 = min n (2 * len) in
let succ_len2 = succ len2 in
set_square_nat res2 0 len2 res 0 len;
if n land !p > 0 then begin
set_to_zero_nat res 0 len;
set_mult_digit_nat res 0 succ_len2
res2 0 len2
power_base pmax
end else
blit_nat res 0 res2 0 len2;
set_to_zero_nat res2 0 len2;
p := !p lsr 1
done;
if rem > 0 then begin
set_mult_digit_nat res2 0 newn
res 0 n power_base (pred rem);
res2
end else res
end else
copy_nat power_base (pred rem) 1
end
;;
PW : rajoute avec 32 et 64 bits
the base - th element ( base > = 2 ) of num_digits_max_vector is :
| |
| sys__max_string_length * log ( base ) |
| ----------------------------------- | + 1
| length_of_digit * log ( 2 ) |
-- --
La base la plus grande possible pour l'impression est 16 .
| |
| sys__max_string_length * log (base) |
| ----------------------------------- | + 1
| length_of_digit * log (2) |
-- --
La base la plus grande possible pour l'impression est 16. *)
num_digits_max_vector.(base ) gives the maximum number of words that
may have the biggest big number that can be printed into a single
character string of maximum length ( the number being printed in
base [ base ] ) . ( This computation takes into account the size of the
machine word ( length_of_digit or size_word ) . )
may have the biggest big number that can be printed into a single
character string of maximum length (the number being printed in
base [base]). (This computation takes into account the size of the
machine word (length_of_digit or size_word).) *)
let num_digits_max_vector =
match sys__word_size with
| 64 ->
[| 0; 0; 262143; 415488; 524287; 608679; 677632; 735930; 786431; 830976;
870823; 906868; 939776; 970047; 998074; 1024167; 1048575; |]
| 32 ->
[| 0; 0; 524287; 830976; 1048575; 1217358; 1355264; 1471861; 1572863;
1661953; 1741646; 1813737; 1879552; 1940095; 1996149; 2048335;
2097151 |]
| _ -> invalid_arg "Bad word size";;
let zero_nat = make_nat 1;;
let power_max_map = make_vect 17 zero_nat;;
let power_max base =
let v = power_max_map.(base) in
if v != zero_nat then v else begin
let v = power_base_int base sys__max_string_length in
power_max_map.(base) <- v; v
end
;;
let sys_string_list_of_nat base nat off len =
if is_nat_int nat off len
then [sys_string_of_int base "" (nth_digit_nat nat off) ""] else begin
pmax : L'indice de la plus grande puissance de base qui soit un digit
pint : La plus grande puissance de base qui soit un int
power_base : ( length_of_digit + 1 ) digits do nt le i - ème digit
contient base^(i+1 )
pint : La plus grande puissance de base qui soit un int
power_base : nat de (length_of_digit + 1) digits dont le i-ème digit
contient base^(i+1) *)
check_base base;
let power_base = make_nat (succ length_of_digit) in
let (pmax, pint) = make_power_base base power_base in
La représentation de 2^length_of_digit en base base
a real_pmax chiffres
a real_pmax chiffres *)
let real_pmax = pmax + 2
and num_int_in_digit = pmax / pint
new_nat est une copie a à cause de
la division
la division *)
and new_nat = make_nat (succ len)
and len_copy = ref (succ (num_digits_nat nat off len)) in
let len_new_nat = ref !len_copy in
copy1 et copy2 sont en fait 2 noms pour un même contenu ,
copy1 est l'argument sur lequel se fait la division ,
quotient de la division
et on remet copy1 à la bonne valeur à la fin de la boucle
copy1 est l'argument sur lequel se fait la division,
copy2 est le quotient de la division
et on remet copy1 à la bonne valeur à la fin de la boucle *)
let copy1 = create_nat !len_copy
and copy2 = make_nat !len_copy
and rest_digit = make_nat 2
and rest_int = create_nat 1
and places = ref 0 in
On divise nat par power_max jusqu'à épuisement , on écrit les restes
successifs , la représentation de ces nombres en base base tient sur
biggest_int
successifs, la représentation de ces nombres en base base tient sur
biggest_int chiffres donc sur une chaîne de caractères *)
let length_block = num_digits_max_vector.(base) in
let l = ref ([] : string list) in
len_copy := pred !len_copy;
blit_nat new_nat 0 nat 0 len;
while not (is_zero_nat new_nat 0 !len_new_nat) do
let len_s =
if !len_new_nat <= length_block
then let cand = real_pmax * !len_new_nat in
(if cand <= 0 then sys__max_string_length else cand)
else sys__max_string_length in
(if !len_new_nat > length_block
then (let power_max_base = power_max base in
div_nat new_nat 0 !len_new_nat power_max_base 0 length_block;
blit_nat copy1 0 new_nat 0 length_block;
len_copy := num_digits_nat copy1 0 length_block;
len_new_nat := max 1 (!len_new_nat - length_block);
blit_nat new_nat 0 new_nat length_block !len_new_nat;
set_to_zero_nat new_nat !len_new_nat length_block;
new_nat a un premier digit nul pour les divisions
ultérieures éventuelles
ultérieures éventuelles *)
len_new_nat :=
(if is_zero_nat new_nat 0 !len_new_nat
then 1
else succ (
num_digits_nat new_nat 0 !len_new_nat)))
else (blit_nat copy1 0 new_nat 0 !len_new_nat;
len_copy := num_digits_nat copy1 0 !len_new_nat;
set_to_zero_nat new_nat 0 !len_new_nat;
len_new_nat := 1));
let s = make_string len_s `0`
and pos_ref = ref (pred len_s) in
while not (is_zero_nat copy1 0 !len_copy) do
On rest_digit
set_digit_nat copy1 !len_copy 0;
div_digit_nat copy2 0
rest_digit 0 copy1 0 (succ !len_copy) power_base pmax;
places := succ pmax;
for j = 0 to num_int_in_digit do
On rest_int .
La valeur significative de copy se trouve dans copy2
on utiliser copy1 pour stocker la valeur du
quotient avant de la remettre dans rest_digit .
La valeur significative de copy se trouve dans copy2
on peut donc utiliser copy1 pour stocker la valeur du
quotient avant de la remettre dans rest_digit. *)
if compare_digits_nat rest_digit 0 power_base (pred pint) == 0
then (set_digit_nat rest_digit 0 1;
set_digit_nat rest_int 0 0)
else (div_digit_nat copy1 0 rest_int 0 rest_digit 0 2
power_base (pred pint);
blit_nat rest_digit 0 copy1 0 1);
On l'écrit dans la chaîne s en lui réservant la place
nécessaire .
nécessaire. *)
int_to_string
(nth_digit_nat rest_int 0) s pos_ref base
(if is_zero_nat copy2 0 !len_copy then min !pos_ref pint else
if !places > pint then (places := !places - pint; pint)
else !places)
done;
len_copy := num_digits_nat copy2 0 !len_copy;
blit_nat copy1 0 copy2 0 !len_copy
done;
if is_zero_nat new_nat 0 !len_new_nat
then l := adjust_string s "" "" :: !l
else l := s :: !l
done; !l
end
;;
(* Power_base_max is used *)
let power_base_max = make_nat 2;;
let pmax =
match sys__word_size with
| 64 ->
set_digit_nat power_base_max 0 1000000000000000000;
set_mult_digit_nat power_base_max 0 2
power_base_max 0 1 (nat_of_int 9) 0;
19
| 32 ->
set_digit_nat power_base_max 0 1000000000;
9
| _ -> invalid_arg "Bad word size";;
let unadjusted_string_of_nat nat off len_nat =
let len = num_digits_nat nat off len_nat in
if len == 1 then sys_string_of_digit nat off else
let len_copy = ref (succ len) in
let copy1 = create_nat !len_copy
and copy2 = make_nat !len_copy
and rest_digit = make_nat 2 in
if len > biggest_int / (succ pmax)
then failwith "number too long"
else let len_s = (succ pmax) * len in
let s = make_string len_s `0`
and pos_ref = ref len_s in
len_copy := pred !len_copy;
blit_nat copy1 0 nat off len;
set_digit_nat copy1 len 0;
while not (is_zero_nat copy1 0 !len_copy) do
div_digit_nat copy2 0
rest_digit 0
copy1 0 (succ !len_copy)
power_base_max 0;
let str = sys_string_of_digit rest_digit 0 in
blit_string str 0
s (!pos_ref - string_length str)
(string_length str);
pos_ref := !pos_ref - pmax;
len_copy := num_digits_nat copy2 0 !len_copy;
blit_nat copy1 0 copy2 0 !len_copy;
set_digit_nat copy1 !len_copy 0
done;
s
;;
let string_of_nat nat =
let s = unadjusted_string_of_nat nat 0 (length_nat nat)
and index = ref 0 in
begin try
for i = 0 to string_length s - 2 do
if s.[i] != `0` then (index := i; raise Exit)
done
with Exit -> () end;
sub_string s !index (string_length s - !index)
;;
let sys_string_of_nat base before nat off len after =
if base == 10 then
if num_digits_nat nat off len == 1 &&
string_length before == 0 &&
string_length after == 0
then sys_string_of_digit nat off
else adjust_string
(unadjusted_string_of_nat nat off len) before after else
if is_nat_int nat off len
then sys_string_of_int base before (nth_digit_nat nat off) after
else let sl = sys_string_list_of_nat base nat off len in
match sl with
| [s] -> adjust_string s before after
| _ -> invalid_arg "sys_string_of_nat"
;;
Pour debugger , on écrit les digits du nombre en base 16 , des barres : |dn|dn-1 ... |d0|
des barres: |dn|dn-1 ...|d0| *)
let power_debug = nat_of_int 256;;
Nombre de caractères d'un digit écrit en base 16 ,
supplémentaire pour la barre de séparation des digits .
supplémentaire pour la barre de séparation des digits. *)
let chars_in_digit_debug = succ (length_of_digit / 4);;
let debug_string_vect_nat nat =
let len_n = length_nat nat in
let max_digits = sys__max_string_length / chars_in_digit_debug in
let blocks = len_n / max_digits
and rest = len_n mod max_digits in
let length = chars_in_digit_debug * max_digits
and vs = make_vect (succ blocks) "" in
for i = 0 to blocks do
let len_s =
if i == blocks
then 1 + chars_in_digit_debug * rest else length in
let s = make_string len_s `0`
and pos = ref (len_s - 1) in
let treat_int int end_digit =
decr pos;
s.[!pos] <- digits.[int mod 16];
let rest_int = int asr 4 in
decr pos;
s.[!pos] <- digits.[rest_int mod 16];
if end_digit then (decr pos; s.[!pos] <- `|`)
in s.[!pos] <- `|`;
for j = i * max_digits to pred (min len_n (succ i * max_digits)) do
let digit = make_nat 1
and digit1 = make_nat 2
and digit2 = make_nat 2 in
blit_nat digit1 0 nat j 1;
for k = 1 to pred (length_of_digit / 8) do
div_digit_nat digit2 0 digit 0 digit1 0 2 power_debug 0;
blit_nat digit1 0 digit2 0 1;
treat_int (nth_digit_nat digit 0) false
done;
treat_int (nth_digit_nat digit1 0) true
done;
vs.(i) <- s
done;
vs
;;
let debug_string_nat nat =
let vs = debug_string_vect_nat nat in
if vect_length vs == 1 then vs.(0) else invalid_arg "debug_string_nat"
;;
La sous - chaine ( s , off , len ) représente en base base que
on .
on détermine ici. *)
let simple_sys_nat_of_string base s off len =
(* check_base base; : inutile la base est vérifiée par base_digit_of_char *)
let power_base = make_nat (succ length_of_digit) in
let (pmax, pint) = make_power_base base power_base in
let new_len = ref (1 + len / (pmax + 1))
and current_len = ref 1 in
let possible_len = ref (min 2 !new_len) in
let nat1 = make_nat !new_len
and nat2 = make_nat !new_len
and digits_read = ref 0
and bound = off + len - 1
and int = ref 0 in
for i = off to bound do
(* On lit pint (au maximum) chiffres, on en fait un int
et on l'intègre au nombre. *)
let c = s.[i] in
begin match c with
| ` ` | `\t` | `\n` | `\r` | `\\` -> ()
| _ -> int := !int * base + base_digit_of_char base c;
incr digits_read
end;
if (!digits_read == pint || i == bound) && not (!digits_read == 0)
then
begin
set_digit_nat nat1 0 !int;
let erase_len = if !new_len = !current_len then !current_len - 1
else !current_len in
for j = 1 to erase_len do
set_digit_nat nat1 j 0
done;
set_mult_digit_nat nat1 0 !possible_len
nat2 0 !current_len
power_base (pred !digits_read);
blit_nat nat2 0 nat1 0 !possible_len;
current_len := num_digits_nat nat1 0 !possible_len;
possible_len := min !new_len (succ !current_len);
int := 0;
digits_read := 0
end
done;
On recadre le nat
let nat = create_nat !current_len in
blit_nat nat 0 nat1 0 !current_len;
nat
;;
base_power_nat base n nat compute nat*base^n
let base_power_nat base n nat =
match sign_int n with
| 0 -> nat
| -1 -> let base_nat = power_base_int base (- n) in
let len_base_nat = num_digits_nat base_nat 0 (length_nat base_nat)
and len_nat = num_digits_nat nat 0 (length_nat nat) in
if len_nat < len_base_nat then invalid_arg "base_power_nat" else
if len_nat == len_base_nat &&
compare_digits_nat nat len_nat base_nat len_base_nat == -1
then invalid_arg "base_power_nat"
else
let copy = create_nat (succ len_nat) in
blit_nat copy 0 nat 0 len_nat;
set_digit_nat copy len_nat 0;
div_nat copy 0 (succ len_nat) base_nat 0 len_base_nat;
if not (is_zero_nat copy 0 len_base_nat)
then invalid_arg "base_power_nat"
else copy_nat copy len_base_nat 1
| _ -> let base_nat = power_base_int base n in
let len_base_nat = num_digits_nat base_nat 0 (length_nat base_nat)
and len_nat = num_digits_nat nat 0 (length_nat nat) in
let new_len = len_nat + len_base_nat in
let res = make_nat new_len in
if len_nat > len_base_nat
then set_mult_nat res 0 new_len
nat 0 len_nat
base_nat 0 len_base_nat
else set_mult_nat res 0 new_len
base_nat 0 len_base_nat
nat 0 len_nat;
if is_zero_nat res 0 new_len then zero_nat
else res
;;
Tests if s has only zeros characters from index i to index
let rec only_zeros s i lim =
i >= lim || s.[i] == `0` && only_zeros s (succ i) lim;;
(* Parses a string d*.d*e[+/-]d* *)
let rec only_zeros s i lim =
i >= lim || s.[i] == `0` && only_zeros s (succ i) lim;;
(* Parses a string d*.d*e[+/-]d* *)
let decimal_of_string base s off len =
(* Skipping leading + sign if any *)
let skip_first = s.[off] == `+` in
let offset = if skip_first then off + 1 else off
and length = if skip_first then len - 1 else len in
let offset_limit = offset + length - 1 in
try
let dot_pos = index_char_from s offset `.` in
try
if dot_pos = offset_limit then raise Not_found else
let e_pos = index_char_from s (dot_pos + 1) `e` in
(* int.int e int *)
let e_arg =
if e_pos = offset_limit then 0 else
sys_int_of_string base s (succ e_pos) (offset_limit - e_pos) in
let exponant = e_arg - (e_pos - dot_pos - 1) in
let s_res = create_string (e_pos - offset - 1) in
let int_part_length = dot_pos - offset in
blit_string s offset s_res 0 int_part_length;
blit_string s (dot_pos + 1) s_res int_part_length (e_pos - dot_pos - 1);
s_res, exponant
with Not_found ->
(* `.` found, no `e` *)
if only_zeros s (dot_pos + 1) (offset_limit + 1)
then (sub_string s offset (dot_pos - offset), 0)
else
let exponant = - (offset_limit - dot_pos) in
let s_res = create_string (length - 1) in
let int_part_length = dot_pos - offset in
blit_string s offset s_res 0 int_part_length;
if dot_pos < offset_limit then
blit_string s (dot_pos + 1)
s_res int_part_length (offset_limit - dot_pos);
(s_res, exponant)
with Not_found ->
(* no `.` *)
try
(* int e int *)
let e_pos = index_char_from s offset `e` in
let e_arg =
if e_pos = offset_limit then 0 else
sys_int_of_string base s (succ e_pos) (offset_limit - e_pos) in
let exponant = e_arg in
let int_part_length = e_pos - offset in
let s_res = create_string int_part_length in
blit_string s offset s_res 0 int_part_length;
s_res, exponant
with Not_found ->
(* a bare int *)
(sub_string s offset length, 0);;
La chaîne s contient un entier en notation scientifique , de off sur
une longueur de len
une longueur de len *)
let sys_nat_of_string base s off len =
let (snat, k) = decimal_of_string base s off len in
let len_snat = string_length snat in
if k < 0 then begin
for i = len_snat + k to pred len_snat do
if snat.[i] != `0` then failwith "sys_nat_of_string"
done;
simple_sys_nat_of_string base snat 0 (len_snat + k)
end
else base_power_nat base k (simple_sys_nat_of_string base snat 0 len_snat)
;;
let nat_of_string s = sys_nat_of_string 10 s 0 (string_length s);;
let sys_float_of_nat nat off len =
float_of_string (sys_string_of_nat 10 "" nat off len ".0");;
let float_of_nat nat = sys_float_of_nat nat 0 (length_nat nat);;
let nat_of_float f = nat_of_string (string_of_float f);;
(* Nat printing *)
#open "format";;
let string_for_read_of_nat n =
sys_string_of_nat 10 "#<" n 0 (length_nat n) ">";;
let sys_print_nat base before nat off len after =
print_string before;
do_list print_string (sys_string_list_of_nat base nat off len);
print_string after
;;
let print_nat nat =
sys_print_nat 10 "" nat 0 (num_digits_nat nat 0 (length_nat nat)) ""
;;
let print_nat_for_read nat =
sys_print_nat 10 "#<" nat 0 (num_digits_nat nat 0 (length_nat nat)) ">"
;;
let debug_print_nat nat =
let vs = debug_string_vect_nat nat in
for i = pred (vect_length vs) downto 0 do
print_string vs.(i)
done
;;
| null | https://raw.githubusercontent.com/camllight/camllight/0cc537de0846393322058dbb26449427bfc76786/sources/contrib/libnum/fnat.ml | ocaml | Nat temporaries
Sizes of words and strings.
ceiling len / 2
Repeat until
next_cand := rad
next_cand <- next_cand / cand
next_cand (poids fort) <- next_cand (poids fort) + cand,
i.e. next_cand <- cand + rad / cand
next_cand <- next_cand / 2
cand <- next_cand
Power_base_max is used
check_base base; : inutile la base est vérifiée par base_digit_of_char
On lit pint (au maximum) chiffres, on en fait un int
et on l'intègre au nombre.
Parses a string d*.d*e[+/-]d*
Parses a string d*.d*e[+/-]d*
Skipping leading + sign if any
int.int e int
`.` found, no `e`
no `.`
int e int
a bare int
Nat printing | nat : fonctions auxiliaires et d impression pour le type .
Derive de nats.ml de Caml V3.1 , .
Adapte a Caml Light par Xavier Leroy & .
Portage 64 bits : .
Derive de nats.ml de Caml V3.1, Valerie Menissier.
Adapte a Caml Light par Xavier Leroy & Pierre Weis.
Portage 64 bits: Pierre Weis. *)
#open "eq";;
#open "exc";;
#open "int";;
#open "bool";;
#open "ref";;
#open "fstring";;
#open "fvect";;
#open "fchar";;
#open "int_misc";;
let tmp_A_2 = create_nat 2
and tmp_A_1 = create_nat 1
and tmp_B_2 = create_nat 2
;;
let length_of_digit = sys__word_size;;
let make_nat len =
if len <= 0 then invalid_arg "make_nat" else
let res = create_nat len in set_to_zero_nat res 0 len; res
;;
let copy_nat nat off_set length =
let res = create_nat (length) in
blit_nat res 0 nat off_set length;
res
;;
let zero_nat = make_nat 1;;
let is_zero_nat n off len =
compare_nat zero_nat 0 1 n off (num_digits_nat n off len) == 0
;;
let is_nat_int nat off len =
num_digits_nat nat off len == 1 && is_digit_int nat off
;;
let sys_int_of_nat nat off len =
if is_nat_int nat off len
then nth_digit_nat nat off
else failwith "sys_int_of_nat"
;;
let int_of_nat nat =
sys_int_of_nat nat 0 (length_nat nat)
;;
let nat_of_int i =
if i < 0 then invalid_arg "nat_of_int" else
let res = create_nat 1 in
set_digit_nat res 0 i;
res
;;
let eq_nat nat1 off1 len1 nat2 off2 len2 =
compare_nat nat1 off1 (num_digits_nat nat1 off1 len1)
nat2 off2 (num_digits_nat nat2 off2 len2) == 0
and le_nat nat1 off1 len1 nat2 off2 len2 =
compare_nat nat1 off1 (num_digits_nat nat1 off1 len1)
nat2 off2 (num_digits_nat nat2 off2 len2) <= 0
and lt_nat nat1 off1 len1 nat2 off2 len2 =
compare_nat nat1 off1 (num_digits_nat nat1 off1 len1)
nat2 off2 (num_digits_nat nat2 off2 len2) < 0
and ge_nat nat1 off1 len1 nat2 off2 len2 =
compare_nat nat1 off1 (num_digits_nat nat1 off1 len1)
nat2 off2 (num_digits_nat nat2 off2 len2) >= 0
and gt_nat nat1 off1 len1 nat2 off2 len2 =
compare_nat nat1 off1 (num_digits_nat nat1 off1 len1)
nat2 off2 (num_digits_nat nat2 off2 len2) > 0
;;
let square_nat nat1 off1 len1 nat2 off2 len2 =
mult_nat nat1 off1 len1 nat2 off2 len2 nat2 off2 len2
;;
let set_square_nat nat1 off1 len1 nat2 off2 len2 =
let _ = square_nat nat1 off1 len1 nat2 off2 len2 in ();;
let gcd_int_nat i nat off len =
if i == 0 then 1 else
if is_nat_int nat off len then begin
set_digit_nat nat off (gcd_int (nth_digit_nat nat off) i); 0
end else begin
let len_copy = succ len in
let copy = create_nat len_copy
and quotient = create_nat 1
and remainder = create_nat 1 in
blit_nat copy 0 nat off len;
set_digit_nat copy len 0;
div_digit_nat quotient 0 remainder 0 copy 0 len_copy (nat_of_int i) 0;
set_digit_nat nat off (gcd_int (nth_digit_nat remainder 0) i);
0
end
;;
let exchange r1 r2 =
let old1 = !r1 in r1 := !r2; r2 := old1
;;
let gcd_nat nat1 off1 len1 nat2 off2 len2 =
if is_zero_nat nat1 off1 len1 then begin
blit_nat nat1 off1 nat2 off2 len2; len2
end else begin
let copy1 = ref (create_nat (succ len1))
and copy2 = ref (create_nat (succ len2)) in
blit_nat !copy1 0 nat1 off1 len1;
blit_nat !copy2 0 nat2 off2 len2;
set_digit_nat !copy1 len1 0;
set_digit_nat !copy2 len2 0;
if lt_nat !copy1 0 len1 !copy2 0 len2
then exchange copy1 copy2;
let real_len1 =
ref (num_digits_nat !copy1 0 (length_nat !copy1))
and real_len2 =
ref (num_digits_nat !copy2 0 (length_nat !copy2)) in
while not (is_zero_nat !copy2 0 !real_len2) do
set_digit_nat !copy1 !real_len1 0;
div_nat !copy1 0 (succ !real_len1) !copy2 0 !real_len2;
exchange copy1 copy2;
real_len1 := !real_len2;
real_len2 := num_digits_nat !copy2 0 !real_len2
done;
blit_nat nat1 off1 !copy1 0 !real_len1;
!real_len1
end
;;
( entière par défaut ) .
Théorème : la suite xn+1 = ( xn + a / xn ) / 2 converge vers la racine
a par défaut , si on part d'une valeur x0
strictement plus grande que la racine de a , sauf quand a est un
carré - 1 , suite alterne entre la racine par défaut
et par excès . Dans tous les cas , le dernier terme de la partie
strictement est .
let sqrt_nat rad off len =
let len = num_digits_nat rad off len in
Copie de travail du radicande
let len_parity = len mod 2 in
let rad_len = len + 1 + len_parity in
let rad =
let res = create_nat rad_len in
blit_nat res 0 rad off len;
set_digit_nat res len 0;
set_digit_nat res (rad_len - 1) 0;
res in
let cand_rest = rad_len - cand_len in
Racine carrée supposée cand = " |FFFF .... | "
let cand = make_nat cand_len in
Amélioration de la racine de départ :
on bits significatifs du premier digit du candidat
( la moitié du nombre de bits significatifs dans les deux premiers
digits du radicande étendu à une longueur paire ) .
shift_cand est word_size - nbb
on calcule nbb le nombre de bits significatifs du premier digit du candidat
(la moitié du nombre de bits significatifs dans les deux premiers
digits du radicande étendu à une longueur paire).
shift_cand est word_size - nbb *)
let shift_cand =
((num_leading_zero_bits_in_digit rad (len-1)) +
sys__word_size * len_parity) / 2 in
Tous les bits du radicande sont à 0 , on rend 0 .
if shift_cand == sys__word_size then cand else
begin
complement_nat cand 0 cand_len;
shift_right_nat cand 0 1 tmp_A_1 0 shift_cand;
let next_cand = create_nat rad_len in
let rec loop () =
blit_nat next_cand 0 rad 0 rad_len;
div_nat next_cand 0 rad_len cand 0 cand_len;
set_add_nat next_cand cand_len cand_rest cand 0 cand_len 0;
shift_right_nat next_cand cand_len cand_rest tmp_A_1 0 1;
if lt_nat next_cand cand_len cand_rest cand 0 cand_len then
blit_nat cand 0 next_cand cand_len cand_len; loop ()
end
else cand in
loop ()
end;;
let max_superscript_10_power_in_int =
match sys__word_size with
| 64 -> 18
| 32 -> 9
| _ -> invalid_arg "Bad word size";;
let max_power_10_power_in_int =
match sys__word_size with
| 64 -> nat_of_int 1000000000000000000
| 32 -> nat_of_int 1000000000
| _ -> invalid_arg "Bad word size";;
let sys_string_of_digit nat off =
if is_nat_int nat off 1 then string_of_int (nth_digit_nat nat off) else
begin
blit_nat tmp_B_2 0 nat off 1;
set_to_zero_nat tmp_B_2 1 1;
div_digit_nat tmp_A_2 0 tmp_A_1 0 tmp_B_2 0 2 max_power_10_power_in_int 0;
let leading_digits = nth_digit_nat tmp_A_2 0
and s1 = string_of_int (nth_digit_nat tmp_A_1 0) in
let len = string_length s1 in
if leading_digits < 10 then begin
let result = make_string (max_superscript_10_power_in_int + 1) `0` in
result.[0] <- char_of_int (48 + leading_digits);
blit_string s1 0 result (string_length result - len) len;
result
end else begin
let result = make_string (max_superscript_10_power_in_int + 2) `0` in
blit_string (string_of_int leading_digits) 0 result 0 2;
blit_string s1 0 result (string_length result - len) len;
result
end
end
;;
let string_of_digit nat =
sys_string_of_digit nat 0
;;
make_power_base affecte power_base des puissances successives de base a
partir de la puissance 1 - ieme .
A la fin de la boucle i-1 est la plus grande puissance de la base qui tient
sur un seul digit et j est la plus grande puissance de la base qui tient
sur un int .
Attention base n''est pas forcément une base valide ( utilisé en
particulier dans big_int ) .
partir de la puissance 1-ieme.
A la fin de la boucle i-1 est la plus grande puissance de la base qui tient
sur un seul digit et j est la plus grande puissance de la base qui tient
sur un int.
Attention base n''est pas forcément une base valide (utilisé en
particulier dans big_int avec un entier quelconque). *)
let make_power_base base power_base =
let i = ref 1
and j = ref 0 in
set_digit_nat power_base 0 base;
while is_digit_zero power_base !i do
set_mult_digit_nat power_base !i 2 power_base (pred !i) 1 power_base 0;
incr i
done;
decr i;
while !j <= !i && is_digit_int power_base !j do incr j done;
(!i - 1, min !i !j);;
On compte les zéros placés au début de la chaîne ,
on en déduit la
et on construit la chaîne adhoc en y ajoutant before et after .
on en déduit la longueur réelle de la chaîne
et on construit la chaîne adhoc en y ajoutant before et after. *)
let adjust_string s before after =
let len_s = string_length s
and k = ref 0 in
while !k < len_s - 1 && s.[!k] == `0`
do incr k
done;
let len_before = string_length before
and len_after = string_length after
and l1 = max (len_s - !k) 1 in
let l2 = len_before + l1 in
if l2 <= 0 then failwith "adjust_string" else
let ok_len = l2 + len_after in
let ok_s = create_string ok_len in
blit_string before 0 ok_s 0 len_before;
blit_string s !k ok_s len_before l1;
blit_string after 0 ok_s l2 len_after;
ok_s
;;
let power_base_int base i =
if i == 0 then
nat_of_int 1
else if i < 0 then
invalid_arg "power_base_int"
else begin
let power_base = make_nat (succ length_of_digit) in
let (pmax, pint) = make_power_base base power_base in
let n = i / (succ pmax)
and rem = i mod (succ pmax) in
if n > 0 then begin
let newn =
if i == biggest_int then n else (succ n) in
let res = make_nat newn
and res2 = make_nat newn
and l = num_bits_int n - 2 in
let p = ref (1 lsl l) in
blit_nat res 0 power_base pmax 1;
for i = l downto 0 do
let len = num_digits_nat res 0 newn in
let len2 = min n (2 * len) in
let succ_len2 = succ len2 in
set_square_nat res2 0 len2 res 0 len;
if n land !p > 0 then begin
set_to_zero_nat res 0 len;
set_mult_digit_nat res 0 succ_len2
res2 0 len2
power_base pmax
end else
blit_nat res 0 res2 0 len2;
set_to_zero_nat res2 0 len2;
p := !p lsr 1
done;
if rem > 0 then begin
set_mult_digit_nat res2 0 newn
res 0 n power_base (pred rem);
res2
end else res
end else
copy_nat power_base (pred rem) 1
end
;;
PW : rajoute avec 32 et 64 bits
the base - th element ( base > = 2 ) of num_digits_max_vector is :
| |
| sys__max_string_length * log ( base ) |
| ----------------------------------- | + 1
| length_of_digit * log ( 2 ) |
-- --
La base la plus grande possible pour l'impression est 16 .
| |
| sys__max_string_length * log (base) |
| ----------------------------------- | + 1
| length_of_digit * log (2) |
-- --
La base la plus grande possible pour l'impression est 16. *)
num_digits_max_vector.(base ) gives the maximum number of words that
may have the biggest big number that can be printed into a single
character string of maximum length ( the number being printed in
base [ base ] ) . ( This computation takes into account the size of the
machine word ( length_of_digit or size_word ) . )
may have the biggest big number that can be printed into a single
character string of maximum length (the number being printed in
base [base]). (This computation takes into account the size of the
machine word (length_of_digit or size_word).) *)
let num_digits_max_vector =
match sys__word_size with
| 64 ->
[| 0; 0; 262143; 415488; 524287; 608679; 677632; 735930; 786431; 830976;
870823; 906868; 939776; 970047; 998074; 1024167; 1048575; |]
| 32 ->
[| 0; 0; 524287; 830976; 1048575; 1217358; 1355264; 1471861; 1572863;
1661953; 1741646; 1813737; 1879552; 1940095; 1996149; 2048335;
2097151 |]
| _ -> invalid_arg "Bad word size";;
let zero_nat = make_nat 1;;
let power_max_map = make_vect 17 zero_nat;;
let power_max base =
let v = power_max_map.(base) in
if v != zero_nat then v else begin
let v = power_base_int base sys__max_string_length in
power_max_map.(base) <- v; v
end
;;
let sys_string_list_of_nat base nat off len =
if is_nat_int nat off len
then [sys_string_of_int base "" (nth_digit_nat nat off) ""] else begin
pmax : L'indice de la plus grande puissance de base qui soit un digit
pint : La plus grande puissance de base qui soit un int
power_base : ( length_of_digit + 1 ) digits do nt le i - ème digit
contient base^(i+1 )
pint : La plus grande puissance de base qui soit un int
power_base : nat de (length_of_digit + 1) digits dont le i-ème digit
contient base^(i+1) *)
check_base base;
let power_base = make_nat (succ length_of_digit) in
let (pmax, pint) = make_power_base base power_base in
La représentation de 2^length_of_digit en base base
a real_pmax chiffres
a real_pmax chiffres *)
let real_pmax = pmax + 2
and num_int_in_digit = pmax / pint
new_nat est une copie a à cause de
la division
la division *)
and new_nat = make_nat (succ len)
and len_copy = ref (succ (num_digits_nat nat off len)) in
let len_new_nat = ref !len_copy in
copy1 et copy2 sont en fait 2 noms pour un même contenu ,
copy1 est l'argument sur lequel se fait la division ,
quotient de la division
et on remet copy1 à la bonne valeur à la fin de la boucle
copy1 est l'argument sur lequel se fait la division,
copy2 est le quotient de la division
et on remet copy1 à la bonne valeur à la fin de la boucle *)
let copy1 = create_nat !len_copy
and copy2 = make_nat !len_copy
and rest_digit = make_nat 2
and rest_int = create_nat 1
and places = ref 0 in
On divise nat par power_max jusqu'à épuisement , on écrit les restes
successifs , la représentation de ces nombres en base base tient sur
biggest_int
successifs, la représentation de ces nombres en base base tient sur
biggest_int chiffres donc sur une chaîne de caractères *)
let length_block = num_digits_max_vector.(base) in
let l = ref ([] : string list) in
len_copy := pred !len_copy;
blit_nat new_nat 0 nat 0 len;
while not (is_zero_nat new_nat 0 !len_new_nat) do
let len_s =
if !len_new_nat <= length_block
then let cand = real_pmax * !len_new_nat in
(if cand <= 0 then sys__max_string_length else cand)
else sys__max_string_length in
(if !len_new_nat > length_block
then (let power_max_base = power_max base in
div_nat new_nat 0 !len_new_nat power_max_base 0 length_block;
blit_nat copy1 0 new_nat 0 length_block;
len_copy := num_digits_nat copy1 0 length_block;
len_new_nat := max 1 (!len_new_nat - length_block);
blit_nat new_nat 0 new_nat length_block !len_new_nat;
set_to_zero_nat new_nat !len_new_nat length_block;
new_nat a un premier digit nul pour les divisions
ultérieures éventuelles
ultérieures éventuelles *)
len_new_nat :=
(if is_zero_nat new_nat 0 !len_new_nat
then 1
else succ (
num_digits_nat new_nat 0 !len_new_nat)))
else (blit_nat copy1 0 new_nat 0 !len_new_nat;
len_copy := num_digits_nat copy1 0 !len_new_nat;
set_to_zero_nat new_nat 0 !len_new_nat;
len_new_nat := 1));
let s = make_string len_s `0`
and pos_ref = ref (pred len_s) in
while not (is_zero_nat copy1 0 !len_copy) do
On rest_digit
set_digit_nat copy1 !len_copy 0;
div_digit_nat copy2 0
rest_digit 0 copy1 0 (succ !len_copy) power_base pmax;
places := succ pmax;
for j = 0 to num_int_in_digit do
On rest_int .
La valeur significative de copy se trouve dans copy2
on utiliser copy1 pour stocker la valeur du
quotient avant de la remettre dans rest_digit .
La valeur significative de copy se trouve dans copy2
on peut donc utiliser copy1 pour stocker la valeur du
quotient avant de la remettre dans rest_digit. *)
if compare_digits_nat rest_digit 0 power_base (pred pint) == 0
then (set_digit_nat rest_digit 0 1;
set_digit_nat rest_int 0 0)
else (div_digit_nat copy1 0 rest_int 0 rest_digit 0 2
power_base (pred pint);
blit_nat rest_digit 0 copy1 0 1);
On l'écrit dans la chaîne s en lui réservant la place
nécessaire .
nécessaire. *)
int_to_string
(nth_digit_nat rest_int 0) s pos_ref base
(if is_zero_nat copy2 0 !len_copy then min !pos_ref pint else
if !places > pint then (places := !places - pint; pint)
else !places)
done;
len_copy := num_digits_nat copy2 0 !len_copy;
blit_nat copy1 0 copy2 0 !len_copy
done;
if is_zero_nat new_nat 0 !len_new_nat
then l := adjust_string s "" "" :: !l
else l := s :: !l
done; !l
end
;;
let power_base_max = make_nat 2;;
let pmax =
match sys__word_size with
| 64 ->
set_digit_nat power_base_max 0 1000000000000000000;
set_mult_digit_nat power_base_max 0 2
power_base_max 0 1 (nat_of_int 9) 0;
19
| 32 ->
set_digit_nat power_base_max 0 1000000000;
9
| _ -> invalid_arg "Bad word size";;
let unadjusted_string_of_nat nat off len_nat =
let len = num_digits_nat nat off len_nat in
if len == 1 then sys_string_of_digit nat off else
let len_copy = ref (succ len) in
let copy1 = create_nat !len_copy
and copy2 = make_nat !len_copy
and rest_digit = make_nat 2 in
if len > biggest_int / (succ pmax)
then failwith "number too long"
else let len_s = (succ pmax) * len in
let s = make_string len_s `0`
and pos_ref = ref len_s in
len_copy := pred !len_copy;
blit_nat copy1 0 nat off len;
set_digit_nat copy1 len 0;
while not (is_zero_nat copy1 0 !len_copy) do
div_digit_nat copy2 0
rest_digit 0
copy1 0 (succ !len_copy)
power_base_max 0;
let str = sys_string_of_digit rest_digit 0 in
blit_string str 0
s (!pos_ref - string_length str)
(string_length str);
pos_ref := !pos_ref - pmax;
len_copy := num_digits_nat copy2 0 !len_copy;
blit_nat copy1 0 copy2 0 !len_copy;
set_digit_nat copy1 !len_copy 0
done;
s
;;
let string_of_nat nat =
let s = unadjusted_string_of_nat nat 0 (length_nat nat)
and index = ref 0 in
begin try
for i = 0 to string_length s - 2 do
if s.[i] != `0` then (index := i; raise Exit)
done
with Exit -> () end;
sub_string s !index (string_length s - !index)
;;
let sys_string_of_nat base before nat off len after =
if base == 10 then
if num_digits_nat nat off len == 1 &&
string_length before == 0 &&
string_length after == 0
then sys_string_of_digit nat off
else adjust_string
(unadjusted_string_of_nat nat off len) before after else
if is_nat_int nat off len
then sys_string_of_int base before (nth_digit_nat nat off) after
else let sl = sys_string_list_of_nat base nat off len in
match sl with
| [s] -> adjust_string s before after
| _ -> invalid_arg "sys_string_of_nat"
;;
Pour debugger , on écrit les digits du nombre en base 16 , des barres : |dn|dn-1 ... |d0|
des barres: |dn|dn-1 ...|d0| *)
let power_debug = nat_of_int 256;;
Nombre de caractères d'un digit écrit en base 16 ,
supplémentaire pour la barre de séparation des digits .
supplémentaire pour la barre de séparation des digits. *)
let chars_in_digit_debug = succ (length_of_digit / 4);;
let debug_string_vect_nat nat =
let len_n = length_nat nat in
let max_digits = sys__max_string_length / chars_in_digit_debug in
let blocks = len_n / max_digits
and rest = len_n mod max_digits in
let length = chars_in_digit_debug * max_digits
and vs = make_vect (succ blocks) "" in
for i = 0 to blocks do
let len_s =
if i == blocks
then 1 + chars_in_digit_debug * rest else length in
let s = make_string len_s `0`
and pos = ref (len_s - 1) in
let treat_int int end_digit =
decr pos;
s.[!pos] <- digits.[int mod 16];
let rest_int = int asr 4 in
decr pos;
s.[!pos] <- digits.[rest_int mod 16];
if end_digit then (decr pos; s.[!pos] <- `|`)
in s.[!pos] <- `|`;
for j = i * max_digits to pred (min len_n (succ i * max_digits)) do
let digit = make_nat 1
and digit1 = make_nat 2
and digit2 = make_nat 2 in
blit_nat digit1 0 nat j 1;
for k = 1 to pred (length_of_digit / 8) do
div_digit_nat digit2 0 digit 0 digit1 0 2 power_debug 0;
blit_nat digit1 0 digit2 0 1;
treat_int (nth_digit_nat digit 0) false
done;
treat_int (nth_digit_nat digit1 0) true
done;
vs.(i) <- s
done;
vs
;;
let debug_string_nat nat =
let vs = debug_string_vect_nat nat in
if vect_length vs == 1 then vs.(0) else invalid_arg "debug_string_nat"
;;
La sous - chaine ( s , off , len ) représente en base base que
on .
on détermine ici. *)
let simple_sys_nat_of_string base s off len =
let power_base = make_nat (succ length_of_digit) in
let (pmax, pint) = make_power_base base power_base in
let new_len = ref (1 + len / (pmax + 1))
and current_len = ref 1 in
let possible_len = ref (min 2 !new_len) in
let nat1 = make_nat !new_len
and nat2 = make_nat !new_len
and digits_read = ref 0
and bound = off + len - 1
and int = ref 0 in
for i = off to bound do
let c = s.[i] in
begin match c with
| ` ` | `\t` | `\n` | `\r` | `\\` -> ()
| _ -> int := !int * base + base_digit_of_char base c;
incr digits_read
end;
if (!digits_read == pint || i == bound) && not (!digits_read == 0)
then
begin
set_digit_nat nat1 0 !int;
let erase_len = if !new_len = !current_len then !current_len - 1
else !current_len in
for j = 1 to erase_len do
set_digit_nat nat1 j 0
done;
set_mult_digit_nat nat1 0 !possible_len
nat2 0 !current_len
power_base (pred !digits_read);
blit_nat nat2 0 nat1 0 !possible_len;
current_len := num_digits_nat nat1 0 !possible_len;
possible_len := min !new_len (succ !current_len);
int := 0;
digits_read := 0
end
done;
On recadre le nat
let nat = create_nat !current_len in
blit_nat nat 0 nat1 0 !current_len;
nat
;;
base_power_nat base n nat compute nat*base^n
let base_power_nat base n nat =
match sign_int n with
| 0 -> nat
| -1 -> let base_nat = power_base_int base (- n) in
let len_base_nat = num_digits_nat base_nat 0 (length_nat base_nat)
and len_nat = num_digits_nat nat 0 (length_nat nat) in
if len_nat < len_base_nat then invalid_arg "base_power_nat" else
if len_nat == len_base_nat &&
compare_digits_nat nat len_nat base_nat len_base_nat == -1
then invalid_arg "base_power_nat"
else
let copy = create_nat (succ len_nat) in
blit_nat copy 0 nat 0 len_nat;
set_digit_nat copy len_nat 0;
div_nat copy 0 (succ len_nat) base_nat 0 len_base_nat;
if not (is_zero_nat copy 0 len_base_nat)
then invalid_arg "base_power_nat"
else copy_nat copy len_base_nat 1
| _ -> let base_nat = power_base_int base n in
let len_base_nat = num_digits_nat base_nat 0 (length_nat base_nat)
and len_nat = num_digits_nat nat 0 (length_nat nat) in
let new_len = len_nat + len_base_nat in
let res = make_nat new_len in
if len_nat > len_base_nat
then set_mult_nat res 0 new_len
nat 0 len_nat
base_nat 0 len_base_nat
else set_mult_nat res 0 new_len
base_nat 0 len_base_nat
nat 0 len_nat;
if is_zero_nat res 0 new_len then zero_nat
else res
;;
Tests if s has only zeros characters from index i to index
let rec only_zeros s i lim =
i >= lim || s.[i] == `0` && only_zeros s (succ i) lim;;
let rec only_zeros s i lim =
i >= lim || s.[i] == `0` && only_zeros s (succ i) lim;;
let decimal_of_string base s off len =
let skip_first = s.[off] == `+` in
let offset = if skip_first then off + 1 else off
and length = if skip_first then len - 1 else len in
let offset_limit = offset + length - 1 in
try
let dot_pos = index_char_from s offset `.` in
try
if dot_pos = offset_limit then raise Not_found else
let e_pos = index_char_from s (dot_pos + 1) `e` in
let e_arg =
if e_pos = offset_limit then 0 else
sys_int_of_string base s (succ e_pos) (offset_limit - e_pos) in
let exponant = e_arg - (e_pos - dot_pos - 1) in
let s_res = create_string (e_pos - offset - 1) in
let int_part_length = dot_pos - offset in
blit_string s offset s_res 0 int_part_length;
blit_string s (dot_pos + 1) s_res int_part_length (e_pos - dot_pos - 1);
s_res, exponant
with Not_found ->
if only_zeros s (dot_pos + 1) (offset_limit + 1)
then (sub_string s offset (dot_pos - offset), 0)
else
let exponant = - (offset_limit - dot_pos) in
let s_res = create_string (length - 1) in
let int_part_length = dot_pos - offset in
blit_string s offset s_res 0 int_part_length;
if dot_pos < offset_limit then
blit_string s (dot_pos + 1)
s_res int_part_length (offset_limit - dot_pos);
(s_res, exponant)
with Not_found ->
try
let e_pos = index_char_from s offset `e` in
let e_arg =
if e_pos = offset_limit then 0 else
sys_int_of_string base s (succ e_pos) (offset_limit - e_pos) in
let exponant = e_arg in
let int_part_length = e_pos - offset in
let s_res = create_string int_part_length in
blit_string s offset s_res 0 int_part_length;
s_res, exponant
with Not_found ->
(sub_string s offset length, 0);;
La chaîne s contient un entier en notation scientifique , de off sur
une longueur de len
une longueur de len *)
let sys_nat_of_string base s off len =
let (snat, k) = decimal_of_string base s off len in
let len_snat = string_length snat in
if k < 0 then begin
for i = len_snat + k to pred len_snat do
if snat.[i] != `0` then failwith "sys_nat_of_string"
done;
simple_sys_nat_of_string base snat 0 (len_snat + k)
end
else base_power_nat base k (simple_sys_nat_of_string base snat 0 len_snat)
;;
let nat_of_string s = sys_nat_of_string 10 s 0 (string_length s);;
let sys_float_of_nat nat off len =
float_of_string (sys_string_of_nat 10 "" nat off len ".0");;
let float_of_nat nat = sys_float_of_nat nat 0 (length_nat nat);;
let nat_of_float f = nat_of_string (string_of_float f);;
#open "format";;
let string_for_read_of_nat n =
sys_string_of_nat 10 "#<" n 0 (length_nat n) ">";;
let sys_print_nat base before nat off len after =
print_string before;
do_list print_string (sys_string_list_of_nat base nat off len);
print_string after
;;
let print_nat nat =
sys_print_nat 10 "" nat 0 (num_digits_nat nat 0 (length_nat nat)) ""
;;
let print_nat_for_read nat =
sys_print_nat 10 "#<" nat 0 (num_digits_nat nat 0 (length_nat nat)) ">"
;;
let debug_print_nat nat =
let vs = debug_string_vect_nat nat in
for i = pred (vect_length vs) downto 0 do
print_string vs.(i)
done
;;
|
0a1ee3b4569acaa2b2d2134e93823671382ecaf3ab1680658c2cb6454b934873 | mfoemmel/erlang-otp | tv_ip.erl | %%
%% %CopyrightBegin%
%%
Copyright Ericsson AB 1997 - 2009 . All Rights Reserved .
%%
The contents of this file are subject to the Erlang Public License ,
Version 1.1 , ( the " License " ) ; you may not use this file except in
%% compliance with the License. You should have received a copy of the
%% Erlang Public License along with this software. If not, it can be
%% retrieved online at /.
%%
Software distributed under the License is distributed on an " AS IS "
%% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
%% the License for the specific language governing rights and limitations
%% under the License.
%%
%% %CopyrightEnd%
-module(tv_ip).
-export([ip/1]).
-include("tv_int_msg.hrl").
-define(NOF_LABELS, 25).
-define(DEFAULT_BG_COLOR, {217, 217, 217}).
%%%*********************************************************************
%%% EXTERNAL FUNCTIONS
%%%*********************************************************************
%%======================================================================
%% Function:
%%
%% Return Value:
%%
%% Description:
%%
%% Parameters:
%%======================================================================
ip(_Master) ->
W = gs:window(win, gs:start(), [{width, 302},
{height, 38},
{bg, ?DEFAULT_BG_COLOR},
{title, "Launching..."}
]),
C = gs:canvas(W, [{width, 40},
{height, 35},
{x, 0},
{bg, {255, 255, 255}}
]),
gs:create(image, C, [{load_gif, code:priv_dir(tv) ++ "/erlang.gif"}]),
gs:label(W, [{width, 252},
{height, 12},
{x, 47},
{y, 23},
{bg, {0, 0, 0}},
{cursor, arrow}
]),
LabelList = create_labels(?NOF_LABELS, W, 48),
L = gs:label(W, [{width, 250},
{height, 18},
{x, 47},
{y, 0},
{bg, ?DEFAULT_BG_COLOR},
{fg, {0, 0, 0}},
{align, w}
]),
gs:config(win, [{map, true}]),
loop(1, LabelList, L).
%%%*********************************************************************
%%% INTERNAL FUNCTIONS
%%%*********************************************************************
%%======================================================================
%% Function:
%%
%% Return Value:
%%
%% Description:
%%
%% Parameters:
%%======================================================================
create_labels(0, _WinId, _Xpos) ->
[];
create_labels(N, WinId, Xpos) ->
Width = 10,
Xdiff = Width,
LabelId = gs:label(WinId, [{width, Width},
{height, 10},
{x, Xpos},
{y, 24},
{bg, {235, 235, 235}},
{cursor, arrow}
]),
[LabelId | create_labels(N - 1, WinId, Xpos + Xdiff)].
%%======================================================================
%% Function:
%%
%% Return Value:
%%
%% Description:
%%
%% Parameters:
%%======================================================================
loop(N, LabelList, L) ->
receive
Msg ->
case Msg of
#ip_update{nof_elements_to_mark = X, text = Text} ->
update_window(LabelList, N, N + X, L, Text),
loop(N + X, LabelList, L);
#ip_quit{} ->
update_labels(LabelList, N, ?NOF_LABELS),
receive
after 1000 ->
done
end,
done;
_Other ->
loop(N, LabelList, L)
end
end.
%%======================================================================
%% Function:
%%
%% Return Value:
%%
%% Description:
%%
%% Parameters:
%%======================================================================
update_window(LabelList, N, Hi, LblId, Text) ->
gs:config(win, [raise]),
gs:config(LblId, [{label, {text, Text}}]),
update_labels(LabelList, N, Hi).
%%======================================================================
%% Function:
%%
%% Return Value:
%%
%% Description:
%%
%% Parameters:
%%======================================================================
update_labels(_LabelList, N, _Hi) when N > ?NOF_LABELS ->
done;
update_labels(_LabelList, N, Hi) when N >= Hi ->
done;
update_labels(LabelList, N, Hi) ->
LabelId = lists:nth(N, LabelList),
gs:config(LabelId, [{bg, {0, 0, 255}}]),
update_labels(LabelList, N + 1, Hi).
| null | https://raw.githubusercontent.com/mfoemmel/erlang-otp/9c6fdd21e4e6573ca6f567053ff3ac454d742bc2/lib/tv/src/tv_ip.erl | erlang |
%CopyrightBegin%
compliance with the License. You should have received a copy of the
Erlang Public License along with this software. If not, it can be
retrieved online at /.
basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
the License for the specific language governing rights and limitations
under the License.
%CopyrightEnd%
*********************************************************************
EXTERNAL FUNCTIONS
*********************************************************************
======================================================================
Function:
Return Value:
Description:
Parameters:
======================================================================
*********************************************************************
INTERNAL FUNCTIONS
*********************************************************************
======================================================================
Function:
Return Value:
Description:
Parameters:
======================================================================
======================================================================
Function:
Return Value:
Description:
Parameters:
======================================================================
======================================================================
Function:
Return Value:
Description:
Parameters:
======================================================================
======================================================================
Function:
Return Value:
Description:
Parameters:
====================================================================== | Copyright Ericsson AB 1997 - 2009 . All Rights Reserved .
The contents of this file are subject to the Erlang Public License ,
Version 1.1 , ( the " License " ) ; you may not use this file except in
Software distributed under the License is distributed on an " AS IS "
-module(tv_ip).
-export([ip/1]).
-include("tv_int_msg.hrl").
-define(NOF_LABELS, 25).
-define(DEFAULT_BG_COLOR, {217, 217, 217}).
ip(_Master) ->
W = gs:window(win, gs:start(), [{width, 302},
{height, 38},
{bg, ?DEFAULT_BG_COLOR},
{title, "Launching..."}
]),
C = gs:canvas(W, [{width, 40},
{height, 35},
{x, 0},
{bg, {255, 255, 255}}
]),
gs:create(image, C, [{load_gif, code:priv_dir(tv) ++ "/erlang.gif"}]),
gs:label(W, [{width, 252},
{height, 12},
{x, 47},
{y, 23},
{bg, {0, 0, 0}},
{cursor, arrow}
]),
LabelList = create_labels(?NOF_LABELS, W, 48),
L = gs:label(W, [{width, 250},
{height, 18},
{x, 47},
{y, 0},
{bg, ?DEFAULT_BG_COLOR},
{fg, {0, 0, 0}},
{align, w}
]),
gs:config(win, [{map, true}]),
loop(1, LabelList, L).
create_labels(0, _WinId, _Xpos) ->
[];
create_labels(N, WinId, Xpos) ->
Width = 10,
Xdiff = Width,
LabelId = gs:label(WinId, [{width, Width},
{height, 10},
{x, Xpos},
{y, 24},
{bg, {235, 235, 235}},
{cursor, arrow}
]),
[LabelId | create_labels(N - 1, WinId, Xpos + Xdiff)].
loop(N, LabelList, L) ->
receive
Msg ->
case Msg of
#ip_update{nof_elements_to_mark = X, text = Text} ->
update_window(LabelList, N, N + X, L, Text),
loop(N + X, LabelList, L);
#ip_quit{} ->
update_labels(LabelList, N, ?NOF_LABELS),
receive
after 1000 ->
done
end,
done;
_Other ->
loop(N, LabelList, L)
end
end.
update_window(LabelList, N, Hi, LblId, Text) ->
gs:config(win, [raise]),
gs:config(LblId, [{label, {text, Text}}]),
update_labels(LabelList, N, Hi).
update_labels(_LabelList, N, _Hi) when N > ?NOF_LABELS ->
done;
update_labels(_LabelList, N, Hi) when N >= Hi ->
done;
update_labels(LabelList, N, Hi) ->
LabelId = lists:nth(N, LabelList),
gs:config(LabelId, [{bg, {0, 0, 255}}]),
update_labels(LabelList, N + 1, Hi).
|
61af877f9252a2de569f0070f6a6441a0050940f157464decc9aa7dfd5c18de8 | static-analysis-engineering/codehawk | jCHAnalysis.ml | = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
CodeHawk Java Analyzer
Author :
------------------------------------------------------------------------------
The MIT License ( MIT )
Copyright ( c ) 2005 - 2020 Kestrel Technology LLC
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
, 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 .
= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
CodeHawk Java Analyzer
Author: Anca Browne
------------------------------------------------------------------------------
The MIT License (MIT)
Copyright (c) 2005-2020 Kestrel Technology LLC
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
============================================================================= *)
open Big_int_Z
chlib
open CHPretty
open CHPrettyUtil
open CHLanguage
open CHAtlas
open CHIntervalsDomainExtensiveArrays
open CHIterator
open CHStack
open CHNumerical
open CHUtils
(* chutil *)
open CHXmlDocument
(* jchpre *)
open JCHPreFileIO
open JCHTaintOrigin
open JCHGlobals
open JCHSystem
open JCHPrintUtils
let analysis_pass start bottom_up =
if start then
JCHFields.int_field_manager#start
else
begin
JCHIntStubs.int_stub_manager#reset_calls ;
JCHFields.int_field_manager#reset
end ;
JCHNumericAnalysis.make_numeric_analysis bottom_up
let numeric_analysis_1_2 () =
pr__debug [NL; STR "Numeric analysis - First Pass"; NL; NL] ;
analysis_pass true true ;
JCHSystemUtils.add_timing "numeric analysis - first pass" ;
pr__debug [NL; STR "Numeric analysis - Second Pass"; NL; NL] ;
analysis_pass false false ;
JCHSystemUtils.add_timing "numeric analysis - second pass"
let numeric_analysis_1 () =
analysis_pass true true ;
JCHSystemUtils.add_timing "numeric analysis"
let analyze_system
~(analysis_level:int)
~(use_intervals:bool)
~(number_joins:int)
~(max_poly_coeff:int)
~(max_nb_constraints:int)
~(use_time_limits:bool)
~(poly_analysis_time_limit:int)
~(num_analysis_time_limit:int)
~(use_overflow:bool) =
if not (Sys.file_exists "codehawk") then Unix.mkdir "codehawk" 0o750 ;
if not (Sys.file_exists "codehawk/temp") then Unix.mkdir "codehawk/temp" 0o750 ;
JCHBasicTypes.set_permissive true ;
pr__debug [STR "Start the analysis."; NL] ;
JCHSystem.jsystem#set ((JCHIFSystem.chif_system)#get_system JCHIFSystem.base_system);
pr__debug [STR "System was translated."; NL];
JCHAnalysisUtils.numeric_params#set_analysis_level analysis_level;
JCHAnalysisUtils.numeric_params#set_system_use_intervals use_intervals;
JCHAnalysisUtils.numeric_params#set_number_joins number_joins;
JCHAnalysisUtils.numeric_params#set_max_poly_coefficient max_poly_coeff;
JCHAnalysisUtils.numeric_params#set_max_number_constraints_allowed max_nb_constraints ;
JCHAnalysisUtils.numeric_params#set_use_time_limits false;
JCHAnalysisUtils.numeric_params#set_use_time_limits use_time_limits;
JCHAnalysisUtils.numeric_params#set_constraint_analysis_time_limit poly_analysis_time_limit;
JCHAnalysisUtils.numeric_params#set_numeric_analysis_time_limit num_analysis_time_limit;
JCHAnalysisUtils.numeric_params#set_use_overflow use_overflow;
numeric_analysis_1_2 () ;
JCHNumericAnalysis.set_pos_fields () ; (* needed for cost analysis *)
pr__debug [STR "Polyhedra invariants were produced."; NL];
pr__debug [STR "Loops were reported."; NL]
let analyze_taint () =
pr__debug [STR "analyze_taint "; NL] ;
JCHSystem.jsystem#set (JCHIFSystem.chif_system#get_system JCHIFSystem.base_system);
JCHTaintOrigin.set_use_one_top_target false;
JCHTGraphAnalysis.make_tgraphs true
let analyze_taint_origins taint_origin_ind local_vars_only =
pr__debug [STR "analyze_taint "; NL] ;
JCHSystem.jsystem#set (JCHIFSystem.chif_system#get_system JCHIFSystem.base_system);
JCHTaintOrigin.set_use_one_top_target true;
JCHTGraphAnalysis.make_tgraphs false ;
pr__debug [STR "Start making origin graphs "; NL] ;
let res_table =
JCHTOriginGraphs.get_taint_origin_graph local_vars_only taint_origin_ind in
pr__debug [NL; STR "result: "; NL; res_table#toPretty; NL];
JCHSystemUtils.add_timing "origin graphs" ;
JCHTNode.save_taint_trail res_table taint_origin_ind
| null | https://raw.githubusercontent.com/static-analysis-engineering/codehawk/98ced4d5e6d7989575092df232759afc2cb851f6/CodeHawk/CHJ/jchpoly/jCHAnalysis.ml | ocaml | chutil
jchpre
needed for cost analysis | = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
CodeHawk Java Analyzer
Author :
------------------------------------------------------------------------------
The MIT License ( MIT )
Copyright ( c ) 2005 - 2020 Kestrel Technology LLC
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
, 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 .
= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
CodeHawk Java Analyzer
Author: Anca Browne
------------------------------------------------------------------------------
The MIT License (MIT)
Copyright (c) 2005-2020 Kestrel Technology LLC
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
============================================================================= *)
open Big_int_Z
chlib
open CHPretty
open CHPrettyUtil
open CHLanguage
open CHAtlas
open CHIntervalsDomainExtensiveArrays
open CHIterator
open CHStack
open CHNumerical
open CHUtils
open CHXmlDocument
open JCHPreFileIO
open JCHTaintOrigin
open JCHGlobals
open JCHSystem
open JCHPrintUtils
let analysis_pass start bottom_up =
if start then
JCHFields.int_field_manager#start
else
begin
JCHIntStubs.int_stub_manager#reset_calls ;
JCHFields.int_field_manager#reset
end ;
JCHNumericAnalysis.make_numeric_analysis bottom_up
let numeric_analysis_1_2 () =
pr__debug [NL; STR "Numeric analysis - First Pass"; NL; NL] ;
analysis_pass true true ;
JCHSystemUtils.add_timing "numeric analysis - first pass" ;
pr__debug [NL; STR "Numeric analysis - Second Pass"; NL; NL] ;
analysis_pass false false ;
JCHSystemUtils.add_timing "numeric analysis - second pass"
let numeric_analysis_1 () =
analysis_pass true true ;
JCHSystemUtils.add_timing "numeric analysis"
let analyze_system
~(analysis_level:int)
~(use_intervals:bool)
~(number_joins:int)
~(max_poly_coeff:int)
~(max_nb_constraints:int)
~(use_time_limits:bool)
~(poly_analysis_time_limit:int)
~(num_analysis_time_limit:int)
~(use_overflow:bool) =
if not (Sys.file_exists "codehawk") then Unix.mkdir "codehawk" 0o750 ;
if not (Sys.file_exists "codehawk/temp") then Unix.mkdir "codehawk/temp" 0o750 ;
JCHBasicTypes.set_permissive true ;
pr__debug [STR "Start the analysis."; NL] ;
JCHSystem.jsystem#set ((JCHIFSystem.chif_system)#get_system JCHIFSystem.base_system);
pr__debug [STR "System was translated."; NL];
JCHAnalysisUtils.numeric_params#set_analysis_level analysis_level;
JCHAnalysisUtils.numeric_params#set_system_use_intervals use_intervals;
JCHAnalysisUtils.numeric_params#set_number_joins number_joins;
JCHAnalysisUtils.numeric_params#set_max_poly_coefficient max_poly_coeff;
JCHAnalysisUtils.numeric_params#set_max_number_constraints_allowed max_nb_constraints ;
JCHAnalysisUtils.numeric_params#set_use_time_limits false;
JCHAnalysisUtils.numeric_params#set_use_time_limits use_time_limits;
JCHAnalysisUtils.numeric_params#set_constraint_analysis_time_limit poly_analysis_time_limit;
JCHAnalysisUtils.numeric_params#set_numeric_analysis_time_limit num_analysis_time_limit;
JCHAnalysisUtils.numeric_params#set_use_overflow use_overflow;
numeric_analysis_1_2 () ;
pr__debug [STR "Polyhedra invariants were produced."; NL];
pr__debug [STR "Loops were reported."; NL]
let analyze_taint () =
pr__debug [STR "analyze_taint "; NL] ;
JCHSystem.jsystem#set (JCHIFSystem.chif_system#get_system JCHIFSystem.base_system);
JCHTaintOrigin.set_use_one_top_target false;
JCHTGraphAnalysis.make_tgraphs true
let analyze_taint_origins taint_origin_ind local_vars_only =
pr__debug [STR "analyze_taint "; NL] ;
JCHSystem.jsystem#set (JCHIFSystem.chif_system#get_system JCHIFSystem.base_system);
JCHTaintOrigin.set_use_one_top_target true;
JCHTGraphAnalysis.make_tgraphs false ;
pr__debug [STR "Start making origin graphs "; NL] ;
let res_table =
JCHTOriginGraphs.get_taint_origin_graph local_vars_only taint_origin_ind in
pr__debug [NL; STR "result: "; NL; res_table#toPretty; NL];
JCHSystemUtils.add_timing "origin graphs" ;
JCHTNode.save_taint_trail res_table taint_origin_ind
|
805d6b7cdc047e341f26beb641a66e02a16815bae367ead6bddb08dc39c0e92d | BinaryAnalysisPlatform/bap | bap_strings_unscrambler.mli | open Core_kernel[@@warning "-D"]
(** symbol encoding *)
module type Alphabet = sig
(** total number of symbols in the alphabet *)
val length : int
(** [index x] maps [x] to the [n]'th symbol of an alphabet, if [x]
is a representation of that symbols, returns a number that is
outside of [[0,len-1]] interval if it is not.*)
val index : char -> int
end
* ASCII Characters
Also provides , different subsets of the Ascii character set ,
e.g. , [ Ascii . Digits ] , [ AScii ]
Also provides, different subsets of the Ascii character set,
e.g., [Ascii.Digits], [AScii]
*)
module Ascii : sig
(** Letters *)
module Alpha : sig
(** Caseless Letters *)
module Caseless : Alphabet
include Alphabet
end
(** Letters and Numbers *)
module Alphanum : sig
(** Caseless Letters *)
module Caseless : Alphabet
include Alphabet
end
(** Digits *)
module Digits : Alphabet
(** All printable ASCII characters *)
module Printable : Alphabet
include Alphabet
end
(** [Make(Alphabet)] creates an unscrambler for the given alphabet.
The unscrambler will build all words from the provided sequence of
characters, essentially it is the same as playing scrabble. For
example, from characters [h,e,l,l,o] it will build words "hell",
"hello", "ell", "hoe", and so on, provided that they are known to
the unscrambler, i.e., present in its dictionary.
The unscrambler requires to know the alphabet of the language
beforehand, because it uses efficient trie-like representation of
the dictionary that enables O(1) search for words (O(1) in terms
of the dictionary size).
*)
module Make(A : Alphabet) : sig
type t [@@deriving bin_io, compare, sexp]
(** an empty unscrambler that doesn't know any words *)
val empty : t
(** [of_file name] reads the dictionary from file [name],
each word is on a separate line. (the standard linux dictionary
file format)
*)
val of_file : string -> t
(** [of_files names] reads the dictionary from all provided file
[names], each file should be a sequence of newline separated
words.*)
val of_files : string list -> t
(** [add_word d x] extends the dictionary [d] with the new word [x]. *)
val add_word : t -> string -> t
(** [build d chars] returns a sequence of all words in the
dictionary [d] that could be built from the sequence of characters [chars] *)
val build : t -> string -> string Sequence.t
(** [is_buildable d chars] returns [true] if in the dictionary [d]
exists a word that can be built from the given characters. *)
val is_buildable : t -> string -> bool
end
| null | https://raw.githubusercontent.com/BinaryAnalysisPlatform/bap/253afc171bbfd0fe1b34f6442795dbf4b1798348/lib/bap_strings/bap_strings_unscrambler.mli | ocaml | * symbol encoding
* total number of symbols in the alphabet
* [index x] maps [x] to the [n]'th symbol of an alphabet, if [x]
is a representation of that symbols, returns a number that is
outside of [[0,len-1]] interval if it is not.
* Letters
* Caseless Letters
* Letters and Numbers
* Caseless Letters
* Digits
* All printable ASCII characters
* [Make(Alphabet)] creates an unscrambler for the given alphabet.
The unscrambler will build all words from the provided sequence of
characters, essentially it is the same as playing scrabble. For
example, from characters [h,e,l,l,o] it will build words "hell",
"hello", "ell", "hoe", and so on, provided that they are known to
the unscrambler, i.e., present in its dictionary.
The unscrambler requires to know the alphabet of the language
beforehand, because it uses efficient trie-like representation of
the dictionary that enables O(1) search for words (O(1) in terms
of the dictionary size).
* an empty unscrambler that doesn't know any words
* [of_file name] reads the dictionary from file [name],
each word is on a separate line. (the standard linux dictionary
file format)
* [of_files names] reads the dictionary from all provided file
[names], each file should be a sequence of newline separated
words.
* [add_word d x] extends the dictionary [d] with the new word [x].
* [build d chars] returns a sequence of all words in the
dictionary [d] that could be built from the sequence of characters [chars]
* [is_buildable d chars] returns [true] if in the dictionary [d]
exists a word that can be built from the given characters. | open Core_kernel[@@warning "-D"]
module type Alphabet = sig
val length : int
val index : char -> int
end
* ASCII Characters
Also provides , different subsets of the Ascii character set ,
e.g. , [ Ascii . Digits ] , [ AScii ]
Also provides, different subsets of the Ascii character set,
e.g., [Ascii.Digits], [AScii]
*)
module Ascii : sig
module Alpha : sig
module Caseless : Alphabet
include Alphabet
end
module Alphanum : sig
module Caseless : Alphabet
include Alphabet
end
module Digits : Alphabet
module Printable : Alphabet
include Alphabet
end
module Make(A : Alphabet) : sig
type t [@@deriving bin_io, compare, sexp]
val empty : t
val of_file : string -> t
val of_files : string list -> t
val add_word : t -> string -> t
val build : t -> string -> string Sequence.t
val is_buildable : t -> string -> bool
end
|
f712e8121e617b2b1b5a3783ad6b79c5a73f7ff0438d9b10536a149e2909cc12 | reborg/clojure-essential-reference | 7.clj | < 1 >
( defn unchecked - inc - int ; < 2 >
" Returns a number one greater than x , an int .
;; Note - uses a primitive operator subject to overflow."
;; {:inline (fn [x] `(. clojure.lang.Numbers (unchecked_int_inc ~x)))
: added " 1.0 " }
;; [x] (. clojure.lang.Numbers (unchecked_int_inc x))) | null | https://raw.githubusercontent.com/reborg/clojure-essential-reference/c37fa19d45dd52b2995a191e3e96f0ebdc3f6d69/TheToolbox/clojure.repl/7.clj | clojure | < 2 >
Note - uses a primitive operator subject to overflow."
{:inline (fn [x] `(. clojure.lang.Numbers (unchecked_int_inc ~x)))
[x] (. clojure.lang.Numbers (unchecked_int_inc x))) | < 1 >
" Returns a number one greater than x , an int .
: added " 1.0 " } |
c17c947a036107f13c51f91ab9bbe37520cf3e3e71275724be959cca173a3093 | garrigue/lablgl | test11.ml | #!/usr/bin/env lablglut
open Printf
Copyright ( c ) 1994 .
(* This program is freely distributable without licensing fees
and is provided without guarantee or warrantee expressed or
implied. This program is -not- in the public domain. *)
ported to lablglut by Issac Trotts on August 6 , 2002
let main () =
ignore(Glut.init Sys.argv);
printf "Keyboard : %s\n" (if Glut.deviceGet(Glut.HAS_KEYBOARD) <> 0 then "YES" else "no") ;
printf "Mouse : %s\n" (if Glut.deviceGet(Glut.HAS_MOUSE) <> 0 then "YES" else "no") ;
printf "Spaceball : %s\n" (if Glut.deviceGet(Glut.HAS_SPACEBALL) <> 0 then "YES" else "no") ;
printf "Dials : %s\n" (if Glut.deviceGet(Glut.HAS_DIAL_AND_BUTTON_BOX) <> 0 then "YES" else "no") ;
printf "Tablet : %s\n\n" (if Glut.deviceGet(Glut.HAS_TABLET) <> 0 then "YES" else "no") ;
printf "Mouse buttons : %d\n" (Glut.deviceGet(Glut.NUM_MOUSE_BUTTONS)) ;
printf "Spaceball buttons : %d\n" (Glut.deviceGet(Glut.NUM_SPACEBALL_BUTTONS)) ;
printf "Button box buttons : %d\n" (Glut.deviceGet(Glut.NUM_BUTTON_BOX_BUTTONS)) ;
printf "Dials : %d\n" (Glut.deviceGet(Glut.NUM_DIALS)) ;
printf "Tablet buttons : %d\n\n" (Glut.deviceGet(Glut.NUM_TABLET_BUTTONS)) ;
printf "PASS : test11\n" ;
;;
let _ = main();;
| null | https://raw.githubusercontent.com/garrigue/lablgl/d76e4ac834b6d803e7a6c07c3b71bff0e534614f/LablGlut/examples/glut3.7/test/test11.ml | ocaml | This program is freely distributable without licensing fees
and is provided without guarantee or warrantee expressed or
implied. This program is -not- in the public domain. | #!/usr/bin/env lablglut
open Printf
Copyright ( c ) 1994 .
ported to lablglut by Issac Trotts on August 6 , 2002
let main () =
ignore(Glut.init Sys.argv);
printf "Keyboard : %s\n" (if Glut.deviceGet(Glut.HAS_KEYBOARD) <> 0 then "YES" else "no") ;
printf "Mouse : %s\n" (if Glut.deviceGet(Glut.HAS_MOUSE) <> 0 then "YES" else "no") ;
printf "Spaceball : %s\n" (if Glut.deviceGet(Glut.HAS_SPACEBALL) <> 0 then "YES" else "no") ;
printf "Dials : %s\n" (if Glut.deviceGet(Glut.HAS_DIAL_AND_BUTTON_BOX) <> 0 then "YES" else "no") ;
printf "Tablet : %s\n\n" (if Glut.deviceGet(Glut.HAS_TABLET) <> 0 then "YES" else "no") ;
printf "Mouse buttons : %d\n" (Glut.deviceGet(Glut.NUM_MOUSE_BUTTONS)) ;
printf "Spaceball buttons : %d\n" (Glut.deviceGet(Glut.NUM_SPACEBALL_BUTTONS)) ;
printf "Button box buttons : %d\n" (Glut.deviceGet(Glut.NUM_BUTTON_BOX_BUTTONS)) ;
printf "Dials : %d\n" (Glut.deviceGet(Glut.NUM_DIALS)) ;
printf "Tablet buttons : %d\n\n" (Glut.deviceGet(Glut.NUM_TABLET_BUTTONS)) ;
printf "PASS : test11\n" ;
;;
let _ = main();;
|
e25acb8d3b04b8a2e94ffd616906f3b945b3bde2278dac87eefffbb41e3661d9 | tezos/tezos-mirror | test_lambda_normalization.ml | (*****************************************************************************)
(* *)
(* Open Source License *)
Copyright ( c ) 2023 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. *)
(* *)
(*****************************************************************************)
* Testing
-------
Component : Protocol ( )
Invocation : dune exec \
/ proto_alpha / lib_protocol / test / integration / / main.exe \
-- test " ^lambda normalization "
Subject : Test that lambdas are normalized to optimized format at elaboration
-------
Component: Protocol (Michelson)
Invocation: dune exec \
src/proto_alpha/lib_protocol/test/integration/michelson/main.exe \
-- test "^lambda normalization"
Subject: Test that lambdas are normalized to optimized format at elaboration
*)
open Protocol
open Alpha_context
open Script_typed_ir
let new_ctxt () =
let open Lwt_result_wrap_syntax in
let* block, _contract = Context.init1 () in
let+ incr = Incremental.begin_construction block in
Incremental.alpha_ctxt incr
let parse_and_project (ty : ((_, _) lambda, _) ty) (node : Script.node) =
let open Lwt_result_wrap_syntax in
let* ctxt = new_ctxt () in
let elab_conf = Script_ir_translator_config.make ~legacy:false () in
let*@ lam, _ctxt =
Script_ir_translator.parse_data ~elab_conf ctxt ~allow_forged:false ty node
in
match lam with
| Lam (_kdescr, node) -> return node
| LamRec (_kdescr, node) ->
return
Micheline.(
Prim (dummy_location, Michelson_v1_primitives.D_Lambda_rec, [node], []))
let node_of_string str =
let open Lwt_result_wrap_syntax in
let*? parsed =
Micheline_parser.no_parsing_error
@@ Michelson_v1_parser.parse_expression ~check:false str
in
return @@ Micheline.root parsed.expanded
let node_to_string node =
Format.asprintf
"%a"
Micheline_printer.print_expr
((Micheline_printer.printable Michelson_v1_primitives.string_of_prim)
(Micheline.strip_locations node))
let assert_lambda_normalizes_to ~loc ty str expected =
let open Lwt_result_wrap_syntax in
let* node = node_of_string str in
let* node_normalized = parse_and_project ty node in
let str_normalized = node_to_string node_normalized in
let* expected_node = node_of_string expected in
let expected = node_to_string expected_node in
Assert.equal_string ~loc expected str_normalized
let assert_normalizes_to ~loc ty str expected =
let open Lwt_result_wrap_syntax in
let* () = assert_lambda_normalizes_to ~loc ty str expected in
let* () =
assert_lambda_normalizes_to
~loc
ty
("Lambda_rec " ^ str)
("Lambda_rec " ^ expected)
in
return_unit
let test_lambda_normalization () =
let open Lwt_result_wrap_syntax in
let*?@ ty =
Script_typed_ir.(lambda_t Micheline.dummy_location unit_t never_t)
in
let*?@ lam_unit_unit =
Script_typed_ir.(lambda_t Micheline.dummy_location unit_t unit_t)
in
let* () =
(* Empty sequence normalizes to itself. *)
assert_lambda_normalizes_to ~loc:__LOC__ lam_unit_unit "{}" "{}"
in
let* () =
(* Another example normalizing to itself. *)
assert_normalizes_to ~loc:__LOC__ ty "{FAILWITH}" "{FAILWITH}"
in
let* () =
(* Readable address normalizes to optimized. *)
assert_normalizes_to
~loc:__LOC__
ty
{|{PUSH address "tz1KqTpEZ7Yob7QbPE4Hy4Wo8fHG8LhKxZSx"; FAILWITH}|}
{|{PUSH address 0x000002298c03ed7d454a101eb7022bc95f7e5f41ac78; FAILWITH}|}
in
let* () =
(* Binary pair normalizes to itself. *)
assert_normalizes_to
~loc:__LOC__
ty
{|{PUSH (pair nat nat) (Pair 0 0); FAILWITH}|}
{|{PUSH (pair nat nat) (Pair 0 0); FAILWITH}|}
in
let* () =
Ternary pair normalizes to nested binary pairs . Type is unchanged .
assert_normalizes_to
~loc:__LOC__
ty
{|{PUSH (pair nat nat nat) (Pair 0 0 0); FAILWITH}|}
{|{PUSH (pair nat nat nat) (Pair 0 (Pair 0 0)); FAILWITH}|}
in
let* () =
(* Same with nested pairs in type. Type is still unchanged. *)
assert_normalizes_to
~loc:__LOC__
ty
{|{PUSH (pair nat (pair nat nat)) (Pair 0 0 0); FAILWITH}|}
{|{PUSH (pair nat (pair nat nat)) (Pair 0 (Pair 0 0)); FAILWITH}|}
in
let* () =
Quadrary pair normalizes to sequence . Type is unchanged .
assert_normalizes_to
~loc:__LOC__
ty
{|{PUSH (pair nat nat nat nat) (Pair 0 0 0 0); FAILWITH}|}
{|{PUSH (pair nat nat nat nat) {0; 0; 0; 0}; FAILWITH}|}
in
let* () =
(* Code inside LAMBDA is normalized too. *)
assert_normalizes_to
~loc:__LOC__
ty
{|{LAMBDA unit never
{PUSH address "tz1KqTpEZ7Yob7QbPE4Hy4Wo8fHG8LhKxZSx"; FAILWITH};
FAILWITH}|}
{|{LAMBDA unit never
{PUSH address 0x000002298c03ed7d454a101eb7022bc95f7e5f41ac78; FAILWITH};
FAILWITH}|}
in
let* () =
(* Same with LAMBDA replaced by PUSH. *)
assert_normalizes_to
~loc:__LOC__
ty
{|{PUSH (lambda unit never)
{PUSH address "tz1KqTpEZ7Yob7QbPE4Hy4Wo8fHG8LhKxZSx"; FAILWITH};
FAILWITH}|}
{|{PUSH (lambda unit never)
{PUSH address 0x000002298c03ed7d454a101eb7022bc95f7e5f41ac78; FAILWITH};
FAILWITH}|}
in
let* () =
(* Code inside LAMBDA_REC is normalized too. *)
assert_normalizes_to
~loc:__LOC__
ty
{|{LAMBDA_REC unit never
{PUSH address "tz1KqTpEZ7Yob7QbPE4Hy4Wo8fHG8LhKxZSx";
FAILWITH};
FAILWITH}|}
{|{LAMBDA_REC unit never
{PUSH address 0x000002298c03ed7d454a101eb7022bc95f7e5f41ac78;
FAILWITH};
FAILWITH}|}
in
let* () =
Same with LAMBDA_REC replaced by PUSH .
assert_normalizes_to
~loc:__LOC__
ty
{|{PUSH (lambda unit never)
(Lambda_rec
{PUSH address "tz1KqTpEZ7Yob7QbPE4Hy4Wo8fHG8LhKxZSx";
FAILWITH});
FAILWITH}|}
{|{PUSH (lambda unit never)
(Lambda_rec
{PUSH address 0x000002298c03ed7d454a101eb7022bc95f7e5f41ac78;
FAILWITH});
FAILWITH}|}
in
let* () =
(* Code inside CREATE_CONTRACT is normalized too. *)
assert_normalizes_to
~loc:__LOC__
ty
{|{PUSH mutez 0;
NONE key_hash;
CREATE_CONTRACT
{parameter unit;
storage unit;
code { PUSH address "tz1KqTpEZ7Yob7QbPE4Hy4Wo8fHG8LhKxZSx"; FAILWITH}};
DROP;
FAILWITH}|}
{|{PUSH mutez 0;
NONE key_hash;
CREATE_CONTRACT
{parameter unit;
storage unit;
code { PUSH address 0x000002298c03ed7d454a101eb7022bc95f7e5f41ac78; FAILWITH}};
DROP;
FAILWITH}|}
in
return_unit
let tests =
[
Tztest.tztest
"Test that lambdas are normalized to optimized format during elaboration"
`Quick
test_lambda_normalization;
]
| null | https://raw.githubusercontent.com/tezos/tezos-mirror/2e34c19183461d5445334143d2b8a264e5f4cef1/src/proto_alpha/lib_protocol/test/integration/michelson/test_lambda_normalization.ml | ocaml | ***************************************************************************
Open Source License
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
the rights to use, copy, modify, merge, publish, distribute, sublicense,
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
***************************************************************************
Empty sequence normalizes to itself.
Another example normalizing to itself.
Readable address normalizes to optimized.
Binary pair normalizes to itself.
Same with nested pairs in type. Type is still unchanged.
Code inside LAMBDA is normalized too.
Same with LAMBDA replaced by PUSH.
Code inside LAMBDA_REC is normalized too.
Code inside CREATE_CONTRACT is normalized too. | Copyright ( c ) 2023 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
* Testing
-------
Component : Protocol ( )
Invocation : dune exec \
/ proto_alpha / lib_protocol / test / integration / / main.exe \
-- test " ^lambda normalization "
Subject : Test that lambdas are normalized to optimized format at elaboration
-------
Component: Protocol (Michelson)
Invocation: dune exec \
src/proto_alpha/lib_protocol/test/integration/michelson/main.exe \
-- test "^lambda normalization"
Subject: Test that lambdas are normalized to optimized format at elaboration
*)
open Protocol
open Alpha_context
open Script_typed_ir
let new_ctxt () =
let open Lwt_result_wrap_syntax in
let* block, _contract = Context.init1 () in
let+ incr = Incremental.begin_construction block in
Incremental.alpha_ctxt incr
let parse_and_project (ty : ((_, _) lambda, _) ty) (node : Script.node) =
let open Lwt_result_wrap_syntax in
let* ctxt = new_ctxt () in
let elab_conf = Script_ir_translator_config.make ~legacy:false () in
let*@ lam, _ctxt =
Script_ir_translator.parse_data ~elab_conf ctxt ~allow_forged:false ty node
in
match lam with
| Lam (_kdescr, node) -> return node
| LamRec (_kdescr, node) ->
return
Micheline.(
Prim (dummy_location, Michelson_v1_primitives.D_Lambda_rec, [node], []))
let node_of_string str =
let open Lwt_result_wrap_syntax in
let*? parsed =
Micheline_parser.no_parsing_error
@@ Michelson_v1_parser.parse_expression ~check:false str
in
return @@ Micheline.root parsed.expanded
let node_to_string node =
Format.asprintf
"%a"
Micheline_printer.print_expr
((Micheline_printer.printable Michelson_v1_primitives.string_of_prim)
(Micheline.strip_locations node))
let assert_lambda_normalizes_to ~loc ty str expected =
let open Lwt_result_wrap_syntax in
let* node = node_of_string str in
let* node_normalized = parse_and_project ty node in
let str_normalized = node_to_string node_normalized in
let* expected_node = node_of_string expected in
let expected = node_to_string expected_node in
Assert.equal_string ~loc expected str_normalized
let assert_normalizes_to ~loc ty str expected =
let open Lwt_result_wrap_syntax in
let* () = assert_lambda_normalizes_to ~loc ty str expected in
let* () =
assert_lambda_normalizes_to
~loc
ty
("Lambda_rec " ^ str)
("Lambda_rec " ^ expected)
in
return_unit
let test_lambda_normalization () =
let open Lwt_result_wrap_syntax in
let*?@ ty =
Script_typed_ir.(lambda_t Micheline.dummy_location unit_t never_t)
in
let*?@ lam_unit_unit =
Script_typed_ir.(lambda_t Micheline.dummy_location unit_t unit_t)
in
let* () =
assert_lambda_normalizes_to ~loc:__LOC__ lam_unit_unit "{}" "{}"
in
let* () =
assert_normalizes_to ~loc:__LOC__ ty "{FAILWITH}" "{FAILWITH}"
in
let* () =
assert_normalizes_to
~loc:__LOC__
ty
{|{PUSH address "tz1KqTpEZ7Yob7QbPE4Hy4Wo8fHG8LhKxZSx"; FAILWITH}|}
{|{PUSH address 0x000002298c03ed7d454a101eb7022bc95f7e5f41ac78; FAILWITH}|}
in
let* () =
assert_normalizes_to
~loc:__LOC__
ty
{|{PUSH (pair nat nat) (Pair 0 0); FAILWITH}|}
{|{PUSH (pair nat nat) (Pair 0 0); FAILWITH}|}
in
let* () =
Ternary pair normalizes to nested binary pairs . Type is unchanged .
assert_normalizes_to
~loc:__LOC__
ty
{|{PUSH (pair nat nat nat) (Pair 0 0 0); FAILWITH}|}
{|{PUSH (pair nat nat nat) (Pair 0 (Pair 0 0)); FAILWITH}|}
in
let* () =
assert_normalizes_to
~loc:__LOC__
ty
{|{PUSH (pair nat (pair nat nat)) (Pair 0 0 0); FAILWITH}|}
{|{PUSH (pair nat (pair nat nat)) (Pair 0 (Pair 0 0)); FAILWITH}|}
in
let* () =
Quadrary pair normalizes to sequence . Type is unchanged .
assert_normalizes_to
~loc:__LOC__
ty
{|{PUSH (pair nat nat nat nat) (Pair 0 0 0 0); FAILWITH}|}
{|{PUSH (pair nat nat nat nat) {0; 0; 0; 0}; FAILWITH}|}
in
let* () =
assert_normalizes_to
~loc:__LOC__
ty
{|{LAMBDA unit never
{PUSH address "tz1KqTpEZ7Yob7QbPE4Hy4Wo8fHG8LhKxZSx"; FAILWITH};
FAILWITH}|}
{|{LAMBDA unit never
{PUSH address 0x000002298c03ed7d454a101eb7022bc95f7e5f41ac78; FAILWITH};
FAILWITH}|}
in
let* () =
assert_normalizes_to
~loc:__LOC__
ty
{|{PUSH (lambda unit never)
{PUSH address "tz1KqTpEZ7Yob7QbPE4Hy4Wo8fHG8LhKxZSx"; FAILWITH};
FAILWITH}|}
{|{PUSH (lambda unit never)
{PUSH address 0x000002298c03ed7d454a101eb7022bc95f7e5f41ac78; FAILWITH};
FAILWITH}|}
in
let* () =
assert_normalizes_to
~loc:__LOC__
ty
{|{LAMBDA_REC unit never
{PUSH address "tz1KqTpEZ7Yob7QbPE4Hy4Wo8fHG8LhKxZSx";
FAILWITH};
FAILWITH}|}
{|{LAMBDA_REC unit never
{PUSH address 0x000002298c03ed7d454a101eb7022bc95f7e5f41ac78;
FAILWITH};
FAILWITH}|}
in
let* () =
Same with LAMBDA_REC replaced by PUSH .
assert_normalizes_to
~loc:__LOC__
ty
{|{PUSH (lambda unit never)
(Lambda_rec
{PUSH address "tz1KqTpEZ7Yob7QbPE4Hy4Wo8fHG8LhKxZSx";
FAILWITH});
FAILWITH}|}
{|{PUSH (lambda unit never)
(Lambda_rec
{PUSH address 0x000002298c03ed7d454a101eb7022bc95f7e5f41ac78;
FAILWITH});
FAILWITH}|}
in
let* () =
assert_normalizes_to
~loc:__LOC__
ty
{|{PUSH mutez 0;
NONE key_hash;
CREATE_CONTRACT
{parameter unit;
storage unit;
code { PUSH address "tz1KqTpEZ7Yob7QbPE4Hy4Wo8fHG8LhKxZSx"; FAILWITH}};
DROP;
FAILWITH}|}
{|{PUSH mutez 0;
NONE key_hash;
CREATE_CONTRACT
{parameter unit;
storage unit;
code { PUSH address 0x000002298c03ed7d454a101eb7022bc95f7e5f41ac78; FAILWITH}};
DROP;
FAILWITH}|}
in
return_unit
let tests =
[
Tztest.tztest
"Test that lambdas are normalized to optimized format during elaboration"
`Quick
test_lambda_normalization;
]
|
1ad79058fd8dc5e4a3220817196da552f88f22691d3ba360e3f2041594c1f8d6 | xaptum/oneup_metrics | oneup_metrics_test.erl | %%%-------------------------------------------------------------------
@author iguberman
( C ) 2017 , Xaptum , Inc.
%%% @doc
%%%
%%% @end
Created : 20 . Dec 2017 2:34 PM
%%%-------------------------------------------------------------------
-module(oneup_metrics_test).
-author("iguberman").
-include_lib("eunit/include/eunit.hrl").
-define(INTERVAL, 5).
-define(SECONDS_PER_MINUTE, 60.0).
-define(INTERVAL_MILLIS, 5000).
-define(ONE_MINUTE_MILLIS, 60 * 1000).
-define(FIVE_MINUTE_MILLIS, ?ONE_MINUTE_MILLIS * 5).
-define(FIFTEEN_MINUTE_MILLIS, ?ONE_MINUTE_MILLIS * 15).
-define(HOUR_MINUTES, 60).
-define(DAY_MINUTES, ?HOUR_MINUTES * 24).
@@@@@@@@@@@@@@@@@@@@@@@@@@@ EUNIT @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
display_counters_test()->
StatsConfig = [{oneup_counter,
[
[a, b, c1, d1, ref1],
[a, b, c1, d2, ref2],
[a, b, c2, d1, ref3],
[a, b, c2, d1, ref4],
[a2, b2, c2, d2, ref5]
]}
],
application:ensure_all_started(lager),
application:set_env(oneup_metrics, metrics_config, StatsConfig),
application:ensure_all_started(oneup_metrics),
StatsMap = oneup_metrics:init_from_config(StatsConfig),
Body = oneup_metrics_handler:display_metrics(StatsMap),
ct:print("@@@@@@@@@@@@ ~nFULL METRICS MAP:~n@@@@@@@@@@@@@@@@@@@@@@@@@@@~n ~p~n@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@", [Body]),
SubMetricsMapA = oneup_metrics:get_sub_metrics(StatsMap, [a]),
SubMetricsBodyA = oneup_metrics_handler:display_metrics(SubMetricsMapA),
ct:print("@@@@@@@@@@@@ ~nMETRICS MAP a:~n@@@@@@@@@@@@@@@@@@@@@@@@@@@~n ~p~n@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@", [SubMetricsBodyA]),
SubMetricsMapABC2 = oneup_metrics:get_sub_metrics(StatsMap, [a, b, c2]),
SubMetricsBodyABC2 = oneup_metrics_handler:display_metrics(SubMetricsMapABC2),
ct:print("@@@@@@@@@@@@ ~nMETRICS MAP a:~n@@@@@@@@@@@@@@@@@@@@@@@@@@@~n ~p~n@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@", [SubMetricsBodyABC2]).
init_from_config_test() ->
StatsConfig = [
{oneup_counter,
[[a, b, c1, d1, ref1],
[a, b, c1, d2, ref2],
[a, b, c2, d1, ref3],
[a, b, c2, d1, ref4],
[a2, b2, c2, d2, ref5]]}
],
application:ensure_all_started(lager),
application:set_env(oneup_metrics, metrics_config, StatsConfig),
application:ensure_all_started(oneup_metrics),
StatsMap = oneup_metrics:init_from_config(StatsConfig),
io:format("@@@@@@@ StatsMap: ~p~n", [StatsMap]),
{oneup_counter, 'a.b.c1.d1.ref1', Ref1} = oneup_metrics:get_metric(StatsMap, [a, b, c1, d1, ref1]),
{oneup_counter, 'a.b.c1.d2.ref2',Ref2} = oneup_metrics:get_metric(StatsMap, [a, b, c1, d2, ref2]),
{oneup_counter, 'a.b.c2.d1.ref3', Ref3} = oneup_metrics:get_metric(StatsMap, [a, b, c2, d1, ref3]),
{oneup_counter, 'a.b.c2.d1.ref4', Ref4} = oneup_metrics:get_metric(StatsMap, [a, b, c2, d1, ref4]),
StatsA = oneup_metrics:get_sub_metrics(StatsMap, [a]),
StatsAExpected = #{b => #{c1 => #{d1 => #{ref1 => {oneup_counter, 'a.b.c1.d1.ref1', Ref1}},
d2 => #{ref2 => {oneup_counter, 'a.b.c1.d2.ref2', Ref2}}},
c2 => #{d1 => #{ref3 => {oneup_counter, 'a.b.c2.d1.ref3', Ref3},
ref4 => {oneup_counter, 'a.b.c2.d1.ref4', Ref4} }}}},
StatsA = StatsAExpected,
StatsB = oneup_metrics:get_sub_metrics(StatsMap, [a, b]),
StatsBExpected = #{c1 => #{d1 => #{ref1 => {oneup_counter, 'a.b.c1.d1.ref1', Ref1}},
d2 => #{ref2 => {oneup_counter, 'a.b.c1.d2.ref2', Ref2}}},
c2 => #{d1 => #{ref3 => {oneup_counter, 'a.b.c2.d1.ref3', Ref3},
ref4 => {oneup_counter, 'a.b.c2.d1.ref4', Ref4}}}},
StatsB = StatsBExpected,
StatsC1 = oneup_metrics:get_sub_metrics(StatsMap, [a, b, c1]),
StatsC1Expected = #{d1 => #{ref1 => {oneup_counter, 'a.b.c1.d1.ref1', Ref1}}, d2 => #{ref2 => {oneup_counter, 'a.b.c1.d2.ref2', Ref2}}},
StatsC1 = StatsC1Expected,
StatsC2 = oneup_metrics:get_sub_metrics(StatsMap, [a, b, c2]),
StatsC2Expected = #{d1 => #{ref3 => {oneup_counter, 'a.b.c2.d1.ref3', Ref3}, ref4 => {oneup_counter, 'a.b.c2.d1.ref4', Ref4} }},
StatsC2 = StatsC2Expected,
StatsC1D1 = oneup_metrics:get_sub_metrics(StatsMap, [a, b, c1, d1]),
StatsC1D1Expected = #{ref1 => {oneup_counter, 'a.b.c1.d1.ref1', Ref1}},
StatsC1D1 = StatsC1D1Expected,
StatsC2D1 = oneup_metrics:get_sub_metrics(StatsMap, [a, b, c2, d1]),
StatsC2D1Expected = #{ref3 => {oneup_counter, 'a.b.c2.d1.ref3', Ref3}, ref4 => {oneup_counter, 'a.b.c2.d1.ref4', Ref4}},
StatsC2D1 = StatsC2D1Expected,
Ref3Expected = oneup_metrics:get_metric(StatsMap, [a, b, c2, d1, ref3]),
{oneup_counter, 'a.b.c2.d1.ref3', Ref3} = Ref3Expected,
{oneup_counter, 'a2.b2.c2.d2.ref5', Ref5} = oneup_metrics:get_metric(StatsMap, [a2, b2, c2, d2, ref5]),
0 = oneup:get(Ref5),
StatsA2 = oneup_metrics:get_sub_metrics(StatsMap, [a2]),
StatsA2Expected = #{b2 => #{c2 => #{d2 => #{ref5 => {oneup_counter, 'a2.b2.c2.d2.ref5', Ref5}}}}},
StatsA2 = StatsA2Expected,
application:stop(oneup_metrics).
counter_test()->
ct:print("Running counter_test()"),
StatsConfig = [{oneup_counter,
[ [a,b,c1,d1,ref1],
[a,b,c1,d2,ref2],
[a,b,c2,d1, ref3],
[a, b, c2, d1, ref4]]}],
application:ensure_all_started(lager),
application:set_env(oneup_metrics, metrics_config, StatsConfig),
application:ensure_all_started(oneup_metrics),
StatsMap = oneup_metrics:initial_get_config(),
oneup_metrics:enable(StatsMap),
{oneup_counter, 'a.b.c1.d1.ref1', CounterRef1} = oneup_metrics:get_metric([a,b,c1,d1,ref1]),
ct:print("CounterRef ~p for ~p in the map ~p", [CounterRef1, [a,b,c1,d1,ref1], StatsMap]),
[oneup_metrics:update({oneup_counter, CounterRef1}, 2) || _I <- lists:seq(1,10)],
20 = oneup_metrics:get_value('a.b.c1.d1.ref1'),
[spawn(oneup_metrics, update_metric, [StatsMap, [a,b,c1,d2,ref2], 2]) || _I <- lists:seq(1,10)],
timer:sleep(100),
FinalCount = oneup_metrics:get_value([a,b,c1,d2,ref2]),
io:format("Increment 10 times by 2 result: ~p~n", [FinalCount]),
20 = FinalCount,
[spawn(oneup_metrics, update_metric, [StatsMap, [a,b,c1,d2,ref2]]) || _I <- lists:seq(1,10)],
timer:sleep(100),
30 = oneup_metrics:get_value('a.b.c1.d2.ref2'),
[oneup_metrics:update_metric(StatsMap, [a,b,c2,d1, ref3], N) || N <- lists:seq(1,10)],
55 = oneup_metrics:get_value('a.b.c2.d1.ref3'),
0 = oneup_metrics:get_value('a.b.c2.d1.ref4'),
[spawn(oneup_metrics, update_metric, [StatsMap, [a, b, c2, d1, ref4], N]) || N <- lists:seq(1,10)],
timer:sleep(100),
55 = oneup_metrics:get_value('a.b.c2.d1.ref4'),
oneup_metrics:reset('a.b.c1.d1.ref1'),
0 = oneup_metrics:get_value('a.b.c1.d1.ref1'),
30 = oneup_metrics:get_value('a.b.c1.d2.ref2'),
application:stop(oneup_metrics).
gauge_test()->
ct:print("Running gauge_test()"),
StatsConfig = [{oneup_gauge,
[ [g,b,c1,d1,ref1],
[g,b,c1,d2,ref2],
[g,b,c2,d1, ref3],
[g, b, c2, d1, ref4]]}],
application:ensure_all_started(lager),
application:set_env(oneup_metrics, metrics_config, StatsConfig),
application:ensure_all_started(oneup_metrics),
StatsMap = oneup_metrics:initial_get_config(),
oneup_metrics:enable(StatsMap),
TODO temp check to verify updated oneup lib
C = oneup:new_counter(),
0 = oneup:set(C, 123),
123 = oneup:set(C, 10),
0 = oneup_metrics:update_metric(StatsMap, [g,b,c1,d1,ref1], 123),
123 = oneup_metrics:get_value('g.b.c1.d1.ref1'),
[N = oneup_metrics:update_metric(StatsMap, [g,b,c2,d1,ref3], N) + 1 || N <- lists:seq(1,10)],
10 = oneup_metrics:get_value('g.b.c2.d1.ref3'),
[spawn(oneup_metrics, update_metric, [StatsMap, [g, b, c2, d1, ref4], N]) || N <- lists:seq(1,10)],
timer:sleep(100),
Ref4Value = oneup_metrics:get_value([g, b, c2, d1, ref4]),
case Ref4Value of
N when N < 1 -> true = false;
N when N > 10 -> true = false;
N -> ok
end,
application:stop(oneup_metrics).
meter_test() ->
ct:print("Running meter_test()"),
StatsConfig = [{oneup_meter,
[ [g,b,c1,d1,ref1],
[g,b,c1,d2,ref2]]}],
application:ensure_all_started(lager),
application:set_env(oneup_metrics, metrics_config, StatsConfig),
application:ensure_all_started(oneup_metrics),
StatsMap = oneup_metrics:initial_get_config(),
oneup_metrics:enable(StatsMap),
[0, Mean, 0, 0, 0, 0, 0, 0] = oneup_metrics:get_value([g,b,c1,d1,ref1]),
ct : print("MEAN PROBLEM ! ~p ~ n ~ n " , [ [ Counter , Mean , InstantRate , OneMinRate , FiveMinRate , FifteenMinRate , HourRate , DayRate ] ] ) ,
%0 = Counter,
?assert(0 == Mean),
0 = InstantRate ,
0 = OneMinRate ,
%0 = FifteenMinRate,
%0 = FiveMinRate,
%0 = HourRate,
0 = DayRate ,
oneup_metrics:update_metric(StatsMap, [g,b,c1,d1,ref1], 1000),
[Counter, _, InstantRate, OneMinRate, FiveMinRate, FifteenMinRate, HourRate, DayRate] = oneup_metrics:get_value([g,b,c1,d1,ref1]),
1000 = Counter ,
0 = InstantRate,
0 = OneMinRate,
0 =FiveMinRate,
0 =FifteenMinRate,
0 =HourRate,
0 =DayRate,
timer:sleep(5000),
[Counter_new, Mean_new, InstantRate_new, OneMinRate_new, FiveMinRate_new, FifteenMinRate_new, HourRate_new, DayRate_new] = oneup_metrics:get_value([g,b,c1,d1,ref1]),
0 = Counter_new,
?assert(Mean_new < 300),
200 = InstantRate_new,
OneMinRate_new = tick(1,1000,0),
FiveMinRate_new = tick(5,1000,0),
FifteenMinRate_new = tick(15,1000,0),
HourRate_new = tick(60, 1000, 0),
DayRate_new = tick(1440, 1000, 0),
[0, 0.0, 0, 0, 0, 0, 0, 0] = oneup_metrics:get_value([g,b,c1,d2,ref2]),
timer:sleep(60000),
[Counter_rst, _, InstantRate_rst, OneMinRate_rst, FiveMinRate_rst, _, _, _] = oneup_metrics:get_value([g,b,c1,d1,ref1]),
0 = Counter_rst,
0 =InstantRate_rst,
true = OneMinRate_rst < 1,
true = FiveMinRate_rst > 2.6,
true = FiveMinRate_rst < 2.8,
application:stop(oneup_metrics).
histogram_test()->
ct:print("Running histogram_test()"),
StatsConfig = [{oneup_histogram,
[ [g,b,c1,d1,ref1],
[g,b,c1,d2,ref2]]}],
application:ensure_all_started(lager),
application:set_env(oneup_metrics, metrics_config, StatsConfig),
application:ensure_all_started(oneup_metrics),
StatsMap = oneup_metrics:initial_get_config(),
oneup_metrics:enable(StatsMap),
{0, 0, 0, 0} = oneup_metrics:get_value([g,b,c1,d1,ref1]),
oneup_metrics:update(StatsMap, [g,b,c2,d1,ref3],10),
{1, 10, 10, 10} = oneup_metrics:get_value([g,b,c1,d1,ref1]),
oneup_metrics:update(StatsMap, [g,b,c2,d1,ref3],20),
{2, 15, 10, 20} = oneup_metrics:get_value([g,b,c1,d1,ref1]),
{0, 0, 0, 0} = oneup_metrics:get_value([g,b,c1,d2,ref2]),
{ oneup_histogram , ' a.b.c1.d1.ref1 ' , Val_ref , Sample_ref , Min_ref , Max_ref } = oneup_metrics : get_metric(StatsMap , [ a , b , c1 , d1 , ref1 ] ) ,
timer:sleep(60000),
oneup_metrics:update(StatsMap, [g,b,c2,d1,ref3],35),
{2, 25, 10, 35} = oneup_metrics:get_value([g,b,c1,d1,ref1]),
oneup_metrics:reset([g,b,c1,d1,ref1]),
{0, 0, 999999999999, 0} = oneup_metrics:get_value([g,b,c1,d1,ref1]),
application:stop(oneup_metrics).
direct_inc_sequential_test()->
CounterRef = oneup:new_counter(),
Samples = 1000000,
TotalTime = lists:foldl(
fun(_X, Total)->
{Time, _Result} = timer:tc(oneup, inc, [CounterRef]),
Total + Time
end, 0, lists:seq(1, Samples)),
Samples = oneup:get(CounterRef),
%% This is super fast when sequential, so perfect for the tcp receiver loop
verify_avg_time(TotalTime, Samples, 0.3),
application:stop(oneup_metrics).
direct_inc_parallel_test()->
CounterRef = oneup:new_counter(),
TotalTimeAccRef = oneup:new_counter(),
Samples = 100000,
Fun = fun() -> timer:sleep(1000), {Time, _Res} = timer:tc(oneup, inc, [CounterRef]), oneup:inc2(TotalTimeAccRef, Time) end,
[spawn(Fun) || _X <- lists:seq(1, Samples)],
timer:sleep(2000),
Samples = oneup:get(CounterRef),
TotalTime = oneup:get(TotalTimeAccRef),
%% trying to access the counter ref by multiple processes simultaneously is obviously slower than doing it sequentially
verify_avg_time(TotalTime, Samples, 2.5).
perf_depth5_test()->
StatsConfig = [
{oneup_counter, [[a,b,c1,d1,ref1],
[a,b,c1,d2,ref2],
[a,b,c2,d1, ref3],
[a, b, c2, d1, ref4],
[a2, b2, c2, d2, ref5],
[a2, b3, c3, d2, ref6],
[a2, b3, c3, d3, ref7],
[a3, b1, c1, d1, ref8],
[a3, b1, c2, d2, ref9],
[a3, b2, c3, d10, ref10]]}],
application:ensure_all_started(lager),
application:set_env(oneup_metrics, metrics_config, StatsConfig),
application:ensure_all_started(oneup_metrics),
StatsMap = oneup_metrics:init_from_config(StatsConfig),
{Total, Samples} = lists:foldl(
fun(X, {Total, Samples} = Acc)->
{Time, _Result} = timer:tc(oneup_metrics, update_metric, [StatsMap, X]),
{Total + Time, Samples + 1}
end, {0,0}, [lists:nth(I rem 5 + 1, proplists:get_value(oneup_counter, StatsConfig)) || I <- lists:seq(1, 100000)]),
verify_avg_time(Total, Samples, 5),
application:stop(oneup_metrics).
perf_depth7_test() ->
ConfigMetrics = [[a, b, c1, d1, e1, f1, ref1],
[a, b, c1, d2, e1, f1, ref2],
[a, b, c2, d1, e1, f2, ref3],
[a, b, c2, d1, e1, f2, ref4],
[a2, b2, c2, d2, e1, f2, ref5],
[a2, b3, c3, d2, e1, f2, ref6],
[a2, b3, c3, d3, e1, f2, ref7],
[a3, b1, c1, d1, e1, f2, ref8],
[a3, b1, c2, d2, e1, f2, ref9],
[a3, b2, c3, d10, e1, f2, ref10]],
StatsConfig = [{oneup_counter,
ConfigMetrics
}],
application:ensure_all_started(lager),
application:set_env(oneup_metrics, metrics_config, StatsConfig),
application:ensure_all_started(oneup_metrics),
StatsMap = oneup_metrics:init_from_config(StatsConfig),
oneup_metrics:enable(StatsMap),
{Total1, Samples1} = lists:foldl(
fun(X, {Total, Samples} = Acc)->
{Time, _Result} = timer:tc(oneup_metrics, update_metric, [StatsMap, X]),
{Total + Time, Samples + 1}
end, {0,0}, [lists:nth(I rem 7 + 1, ConfigMetrics) || I <- lists:seq(1, 100000)]),
verify_avg_time(Total1, Samples1, 6),
{Total2, Samples2} = lists:foldl(
fun(X, {Total, Samples} = Acc)->
{Time, _Result} = timer:tc(oneup_metrics, update_metric, [StatsMap, X, 999]),
{Total + Time, Samples + 1}
end, {0,0}, [lists:nth(I rem 7 + 1, ConfigMetrics) || I <- lists:seq(1, 100000)]),
verify_avg_time(Total2, Samples2, 6),
{Total3, Samples3} = lists:foldl(
fun(Element, {Total, Samples} = Acc)->
Value = rand:uniform(10000000000),
{Time, _Result} = timer:tc(oneup_metrics, update_metric, [StatsMap, Element, Value]),
{Total + Time, Samples + 1}
end, {0,0}, [lists:nth(I rem 7 + 1, ConfigMetrics) || I <- lists:seq(1, 100000)]),
verify_avg_time(Total3, Samples3, 6),
application:stop(oneup_metrics).
verify_avg_time(Total, Samples, Micros) ->
AvgTime = Total/Samples,
ct:print("AvgTime ~p", [AvgTime]),
?assert(AvgTime < Micros).
alpha(Minutes)->
1 - math:exp(-math:pow(?INTERVAL,2) / ?SECONDS_PER_MINUTE / math:pow(Minutes,2)).
tick(_Minutes, Count, undefined)->
Count / ?INTERVAL; %% just return instant rate
tick(Minutes, Count, PrevRate)->
InstantRate = Count / ?INTERVAL,
PrevRate + (alpha(Minutes) * (InstantRate - PrevRate)).
| null | https://raw.githubusercontent.com/xaptum/oneup_metrics/cfbf248a8f630596f7c3e40c3da1f32d9c1c0531/test/oneup_metrics_test.erl | erlang | -------------------------------------------------------------------
@doc
@end
-------------------------------------------------------------------
0 = Counter,
0 = FifteenMinRate,
0 = FiveMinRate,
0 = HourRate,
This is super fast when sequential, so perfect for the tcp receiver loop
trying to access the counter ref by multiple processes simultaneously is obviously slower than doing it sequentially
just return instant rate | @author iguberman
( C ) 2017 , Xaptum , Inc.
Created : 20 . Dec 2017 2:34 PM
-module(oneup_metrics_test).
-author("iguberman").
-include_lib("eunit/include/eunit.hrl").
-define(INTERVAL, 5).
-define(SECONDS_PER_MINUTE, 60.0).
-define(INTERVAL_MILLIS, 5000).
-define(ONE_MINUTE_MILLIS, 60 * 1000).
-define(FIVE_MINUTE_MILLIS, ?ONE_MINUTE_MILLIS * 5).
-define(FIFTEEN_MINUTE_MILLIS, ?ONE_MINUTE_MILLIS * 15).
-define(HOUR_MINUTES, 60).
-define(DAY_MINUTES, ?HOUR_MINUTES * 24).
@@@@@@@@@@@@@@@@@@@@@@@@@@@ EUNIT @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
display_counters_test()->
StatsConfig = [{oneup_counter,
[
[a, b, c1, d1, ref1],
[a, b, c1, d2, ref2],
[a, b, c2, d1, ref3],
[a, b, c2, d1, ref4],
[a2, b2, c2, d2, ref5]
]}
],
application:ensure_all_started(lager),
application:set_env(oneup_metrics, metrics_config, StatsConfig),
application:ensure_all_started(oneup_metrics),
StatsMap = oneup_metrics:init_from_config(StatsConfig),
Body = oneup_metrics_handler:display_metrics(StatsMap),
ct:print("@@@@@@@@@@@@ ~nFULL METRICS MAP:~n@@@@@@@@@@@@@@@@@@@@@@@@@@@~n ~p~n@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@", [Body]),
SubMetricsMapA = oneup_metrics:get_sub_metrics(StatsMap, [a]),
SubMetricsBodyA = oneup_metrics_handler:display_metrics(SubMetricsMapA),
ct:print("@@@@@@@@@@@@ ~nMETRICS MAP a:~n@@@@@@@@@@@@@@@@@@@@@@@@@@@~n ~p~n@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@", [SubMetricsBodyA]),
SubMetricsMapABC2 = oneup_metrics:get_sub_metrics(StatsMap, [a, b, c2]),
SubMetricsBodyABC2 = oneup_metrics_handler:display_metrics(SubMetricsMapABC2),
ct:print("@@@@@@@@@@@@ ~nMETRICS MAP a:~n@@@@@@@@@@@@@@@@@@@@@@@@@@@~n ~p~n@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@", [SubMetricsBodyABC2]).
init_from_config_test() ->
StatsConfig = [
{oneup_counter,
[[a, b, c1, d1, ref1],
[a, b, c1, d2, ref2],
[a, b, c2, d1, ref3],
[a, b, c2, d1, ref4],
[a2, b2, c2, d2, ref5]]}
],
application:ensure_all_started(lager),
application:set_env(oneup_metrics, metrics_config, StatsConfig),
application:ensure_all_started(oneup_metrics),
StatsMap = oneup_metrics:init_from_config(StatsConfig),
io:format("@@@@@@@ StatsMap: ~p~n", [StatsMap]),
{oneup_counter, 'a.b.c1.d1.ref1', Ref1} = oneup_metrics:get_metric(StatsMap, [a, b, c1, d1, ref1]),
{oneup_counter, 'a.b.c1.d2.ref2',Ref2} = oneup_metrics:get_metric(StatsMap, [a, b, c1, d2, ref2]),
{oneup_counter, 'a.b.c2.d1.ref3', Ref3} = oneup_metrics:get_metric(StatsMap, [a, b, c2, d1, ref3]),
{oneup_counter, 'a.b.c2.d1.ref4', Ref4} = oneup_metrics:get_metric(StatsMap, [a, b, c2, d1, ref4]),
StatsA = oneup_metrics:get_sub_metrics(StatsMap, [a]),
StatsAExpected = #{b => #{c1 => #{d1 => #{ref1 => {oneup_counter, 'a.b.c1.d1.ref1', Ref1}},
d2 => #{ref2 => {oneup_counter, 'a.b.c1.d2.ref2', Ref2}}},
c2 => #{d1 => #{ref3 => {oneup_counter, 'a.b.c2.d1.ref3', Ref3},
ref4 => {oneup_counter, 'a.b.c2.d1.ref4', Ref4} }}}},
StatsA = StatsAExpected,
StatsB = oneup_metrics:get_sub_metrics(StatsMap, [a, b]),
StatsBExpected = #{c1 => #{d1 => #{ref1 => {oneup_counter, 'a.b.c1.d1.ref1', Ref1}},
d2 => #{ref2 => {oneup_counter, 'a.b.c1.d2.ref2', Ref2}}},
c2 => #{d1 => #{ref3 => {oneup_counter, 'a.b.c2.d1.ref3', Ref3},
ref4 => {oneup_counter, 'a.b.c2.d1.ref4', Ref4}}}},
StatsB = StatsBExpected,
StatsC1 = oneup_metrics:get_sub_metrics(StatsMap, [a, b, c1]),
StatsC1Expected = #{d1 => #{ref1 => {oneup_counter, 'a.b.c1.d1.ref1', Ref1}}, d2 => #{ref2 => {oneup_counter, 'a.b.c1.d2.ref2', Ref2}}},
StatsC1 = StatsC1Expected,
StatsC2 = oneup_metrics:get_sub_metrics(StatsMap, [a, b, c2]),
StatsC2Expected = #{d1 => #{ref3 => {oneup_counter, 'a.b.c2.d1.ref3', Ref3}, ref4 => {oneup_counter, 'a.b.c2.d1.ref4', Ref4} }},
StatsC2 = StatsC2Expected,
StatsC1D1 = oneup_metrics:get_sub_metrics(StatsMap, [a, b, c1, d1]),
StatsC1D1Expected = #{ref1 => {oneup_counter, 'a.b.c1.d1.ref1', Ref1}},
StatsC1D1 = StatsC1D1Expected,
StatsC2D1 = oneup_metrics:get_sub_metrics(StatsMap, [a, b, c2, d1]),
StatsC2D1Expected = #{ref3 => {oneup_counter, 'a.b.c2.d1.ref3', Ref3}, ref4 => {oneup_counter, 'a.b.c2.d1.ref4', Ref4}},
StatsC2D1 = StatsC2D1Expected,
Ref3Expected = oneup_metrics:get_metric(StatsMap, [a, b, c2, d1, ref3]),
{oneup_counter, 'a.b.c2.d1.ref3', Ref3} = Ref3Expected,
{oneup_counter, 'a2.b2.c2.d2.ref5', Ref5} = oneup_metrics:get_metric(StatsMap, [a2, b2, c2, d2, ref5]),
0 = oneup:get(Ref5),
StatsA2 = oneup_metrics:get_sub_metrics(StatsMap, [a2]),
StatsA2Expected = #{b2 => #{c2 => #{d2 => #{ref5 => {oneup_counter, 'a2.b2.c2.d2.ref5', Ref5}}}}},
StatsA2 = StatsA2Expected,
application:stop(oneup_metrics).
counter_test()->
ct:print("Running counter_test()"),
StatsConfig = [{oneup_counter,
[ [a,b,c1,d1,ref1],
[a,b,c1,d2,ref2],
[a,b,c2,d1, ref3],
[a, b, c2, d1, ref4]]}],
application:ensure_all_started(lager),
application:set_env(oneup_metrics, metrics_config, StatsConfig),
application:ensure_all_started(oneup_metrics),
StatsMap = oneup_metrics:initial_get_config(),
oneup_metrics:enable(StatsMap),
{oneup_counter, 'a.b.c1.d1.ref1', CounterRef1} = oneup_metrics:get_metric([a,b,c1,d1,ref1]),
ct:print("CounterRef ~p for ~p in the map ~p", [CounterRef1, [a,b,c1,d1,ref1], StatsMap]),
[oneup_metrics:update({oneup_counter, CounterRef1}, 2) || _I <- lists:seq(1,10)],
20 = oneup_metrics:get_value('a.b.c1.d1.ref1'),
[spawn(oneup_metrics, update_metric, [StatsMap, [a,b,c1,d2,ref2], 2]) || _I <- lists:seq(1,10)],
timer:sleep(100),
FinalCount = oneup_metrics:get_value([a,b,c1,d2,ref2]),
io:format("Increment 10 times by 2 result: ~p~n", [FinalCount]),
20 = FinalCount,
[spawn(oneup_metrics, update_metric, [StatsMap, [a,b,c1,d2,ref2]]) || _I <- lists:seq(1,10)],
timer:sleep(100),
30 = oneup_metrics:get_value('a.b.c1.d2.ref2'),
[oneup_metrics:update_metric(StatsMap, [a,b,c2,d1, ref3], N) || N <- lists:seq(1,10)],
55 = oneup_metrics:get_value('a.b.c2.d1.ref3'),
0 = oneup_metrics:get_value('a.b.c2.d1.ref4'),
[spawn(oneup_metrics, update_metric, [StatsMap, [a, b, c2, d1, ref4], N]) || N <- lists:seq(1,10)],
timer:sleep(100),
55 = oneup_metrics:get_value('a.b.c2.d1.ref4'),
oneup_metrics:reset('a.b.c1.d1.ref1'),
0 = oneup_metrics:get_value('a.b.c1.d1.ref1'),
30 = oneup_metrics:get_value('a.b.c1.d2.ref2'),
application:stop(oneup_metrics).
gauge_test()->
ct:print("Running gauge_test()"),
StatsConfig = [{oneup_gauge,
[ [g,b,c1,d1,ref1],
[g,b,c1,d2,ref2],
[g,b,c2,d1, ref3],
[g, b, c2, d1, ref4]]}],
application:ensure_all_started(lager),
application:set_env(oneup_metrics, metrics_config, StatsConfig),
application:ensure_all_started(oneup_metrics),
StatsMap = oneup_metrics:initial_get_config(),
oneup_metrics:enable(StatsMap),
TODO temp check to verify updated oneup lib
C = oneup:new_counter(),
0 = oneup:set(C, 123),
123 = oneup:set(C, 10),
0 = oneup_metrics:update_metric(StatsMap, [g,b,c1,d1,ref1], 123),
123 = oneup_metrics:get_value('g.b.c1.d1.ref1'),
[N = oneup_metrics:update_metric(StatsMap, [g,b,c2,d1,ref3], N) + 1 || N <- lists:seq(1,10)],
10 = oneup_metrics:get_value('g.b.c2.d1.ref3'),
[spawn(oneup_metrics, update_metric, [StatsMap, [g, b, c2, d1, ref4], N]) || N <- lists:seq(1,10)],
timer:sleep(100),
Ref4Value = oneup_metrics:get_value([g, b, c2, d1, ref4]),
case Ref4Value of
N when N < 1 -> true = false;
N when N > 10 -> true = false;
N -> ok
end,
application:stop(oneup_metrics).
meter_test() ->
ct:print("Running meter_test()"),
StatsConfig = [{oneup_meter,
[ [g,b,c1,d1,ref1],
[g,b,c1,d2,ref2]]}],
application:ensure_all_started(lager),
application:set_env(oneup_metrics, metrics_config, StatsConfig),
application:ensure_all_started(oneup_metrics),
StatsMap = oneup_metrics:initial_get_config(),
oneup_metrics:enable(StatsMap),
[0, Mean, 0, 0, 0, 0, 0, 0] = oneup_metrics:get_value([g,b,c1,d1,ref1]),
ct : print("MEAN PROBLEM ! ~p ~ n ~ n " , [ [ Counter , Mean , InstantRate , OneMinRate , FiveMinRate , FifteenMinRate , HourRate , DayRate ] ] ) ,
?assert(0 == Mean),
0 = InstantRate ,
0 = OneMinRate ,
0 = DayRate ,
oneup_metrics:update_metric(StatsMap, [g,b,c1,d1,ref1], 1000),
[Counter, _, InstantRate, OneMinRate, FiveMinRate, FifteenMinRate, HourRate, DayRate] = oneup_metrics:get_value([g,b,c1,d1,ref1]),
1000 = Counter ,
0 = InstantRate,
0 = OneMinRate,
0 =FiveMinRate,
0 =FifteenMinRate,
0 =HourRate,
0 =DayRate,
timer:sleep(5000),
[Counter_new, Mean_new, InstantRate_new, OneMinRate_new, FiveMinRate_new, FifteenMinRate_new, HourRate_new, DayRate_new] = oneup_metrics:get_value([g,b,c1,d1,ref1]),
0 = Counter_new,
?assert(Mean_new < 300),
200 = InstantRate_new,
OneMinRate_new = tick(1,1000,0),
FiveMinRate_new = tick(5,1000,0),
FifteenMinRate_new = tick(15,1000,0),
HourRate_new = tick(60, 1000, 0),
DayRate_new = tick(1440, 1000, 0),
[0, 0.0, 0, 0, 0, 0, 0, 0] = oneup_metrics:get_value([g,b,c1,d2,ref2]),
timer:sleep(60000),
[Counter_rst, _, InstantRate_rst, OneMinRate_rst, FiveMinRate_rst, _, _, _] = oneup_metrics:get_value([g,b,c1,d1,ref1]),
0 = Counter_rst,
0 =InstantRate_rst,
true = OneMinRate_rst < 1,
true = FiveMinRate_rst > 2.6,
true = FiveMinRate_rst < 2.8,
application:stop(oneup_metrics).
histogram_test()->
ct:print("Running histogram_test()"),
StatsConfig = [{oneup_histogram,
[ [g,b,c1,d1,ref1],
[g,b,c1,d2,ref2]]}],
application:ensure_all_started(lager),
application:set_env(oneup_metrics, metrics_config, StatsConfig),
application:ensure_all_started(oneup_metrics),
StatsMap = oneup_metrics:initial_get_config(),
oneup_metrics:enable(StatsMap),
{0, 0, 0, 0} = oneup_metrics:get_value([g,b,c1,d1,ref1]),
oneup_metrics:update(StatsMap, [g,b,c2,d1,ref3],10),
{1, 10, 10, 10} = oneup_metrics:get_value([g,b,c1,d1,ref1]),
oneup_metrics:update(StatsMap, [g,b,c2,d1,ref3],20),
{2, 15, 10, 20} = oneup_metrics:get_value([g,b,c1,d1,ref1]),
{0, 0, 0, 0} = oneup_metrics:get_value([g,b,c1,d2,ref2]),
{ oneup_histogram , ' a.b.c1.d1.ref1 ' , Val_ref , Sample_ref , Min_ref , Max_ref } = oneup_metrics : get_metric(StatsMap , [ a , b , c1 , d1 , ref1 ] ) ,
timer:sleep(60000),
oneup_metrics:update(StatsMap, [g,b,c2,d1,ref3],35),
{2, 25, 10, 35} = oneup_metrics:get_value([g,b,c1,d1,ref1]),
oneup_metrics:reset([g,b,c1,d1,ref1]),
{0, 0, 999999999999, 0} = oneup_metrics:get_value([g,b,c1,d1,ref1]),
application:stop(oneup_metrics).
direct_inc_sequential_test()->
CounterRef = oneup:new_counter(),
Samples = 1000000,
TotalTime = lists:foldl(
fun(_X, Total)->
{Time, _Result} = timer:tc(oneup, inc, [CounterRef]),
Total + Time
end, 0, lists:seq(1, Samples)),
Samples = oneup:get(CounterRef),
verify_avg_time(TotalTime, Samples, 0.3),
application:stop(oneup_metrics).
direct_inc_parallel_test()->
CounterRef = oneup:new_counter(),
TotalTimeAccRef = oneup:new_counter(),
Samples = 100000,
Fun = fun() -> timer:sleep(1000), {Time, _Res} = timer:tc(oneup, inc, [CounterRef]), oneup:inc2(TotalTimeAccRef, Time) end,
[spawn(Fun) || _X <- lists:seq(1, Samples)],
timer:sleep(2000),
Samples = oneup:get(CounterRef),
TotalTime = oneup:get(TotalTimeAccRef),
verify_avg_time(TotalTime, Samples, 2.5).
perf_depth5_test()->
StatsConfig = [
{oneup_counter, [[a,b,c1,d1,ref1],
[a,b,c1,d2,ref2],
[a,b,c2,d1, ref3],
[a, b, c2, d1, ref4],
[a2, b2, c2, d2, ref5],
[a2, b3, c3, d2, ref6],
[a2, b3, c3, d3, ref7],
[a3, b1, c1, d1, ref8],
[a3, b1, c2, d2, ref9],
[a3, b2, c3, d10, ref10]]}],
application:ensure_all_started(lager),
application:set_env(oneup_metrics, metrics_config, StatsConfig),
application:ensure_all_started(oneup_metrics),
StatsMap = oneup_metrics:init_from_config(StatsConfig),
{Total, Samples} = lists:foldl(
fun(X, {Total, Samples} = Acc)->
{Time, _Result} = timer:tc(oneup_metrics, update_metric, [StatsMap, X]),
{Total + Time, Samples + 1}
end, {0,0}, [lists:nth(I rem 5 + 1, proplists:get_value(oneup_counter, StatsConfig)) || I <- lists:seq(1, 100000)]),
verify_avg_time(Total, Samples, 5),
application:stop(oneup_metrics).
perf_depth7_test() ->
ConfigMetrics = [[a, b, c1, d1, e1, f1, ref1],
[a, b, c1, d2, e1, f1, ref2],
[a, b, c2, d1, e1, f2, ref3],
[a, b, c2, d1, e1, f2, ref4],
[a2, b2, c2, d2, e1, f2, ref5],
[a2, b3, c3, d2, e1, f2, ref6],
[a2, b3, c3, d3, e1, f2, ref7],
[a3, b1, c1, d1, e1, f2, ref8],
[a3, b1, c2, d2, e1, f2, ref9],
[a3, b2, c3, d10, e1, f2, ref10]],
StatsConfig = [{oneup_counter,
ConfigMetrics
}],
application:ensure_all_started(lager),
application:set_env(oneup_metrics, metrics_config, StatsConfig),
application:ensure_all_started(oneup_metrics),
StatsMap = oneup_metrics:init_from_config(StatsConfig),
oneup_metrics:enable(StatsMap),
{Total1, Samples1} = lists:foldl(
fun(X, {Total, Samples} = Acc)->
{Time, _Result} = timer:tc(oneup_metrics, update_metric, [StatsMap, X]),
{Total + Time, Samples + 1}
end, {0,0}, [lists:nth(I rem 7 + 1, ConfigMetrics) || I <- lists:seq(1, 100000)]),
verify_avg_time(Total1, Samples1, 6),
{Total2, Samples2} = lists:foldl(
fun(X, {Total, Samples} = Acc)->
{Time, _Result} = timer:tc(oneup_metrics, update_metric, [StatsMap, X, 999]),
{Total + Time, Samples + 1}
end, {0,0}, [lists:nth(I rem 7 + 1, ConfigMetrics) || I <- lists:seq(1, 100000)]),
verify_avg_time(Total2, Samples2, 6),
{Total3, Samples3} = lists:foldl(
fun(Element, {Total, Samples} = Acc)->
Value = rand:uniform(10000000000),
{Time, _Result} = timer:tc(oneup_metrics, update_metric, [StatsMap, Element, Value]),
{Total + Time, Samples + 1}
end, {0,0}, [lists:nth(I rem 7 + 1, ConfigMetrics) || I <- lists:seq(1, 100000)]),
verify_avg_time(Total3, Samples3, 6),
application:stop(oneup_metrics).
verify_avg_time(Total, Samples, Micros) ->
AvgTime = Total/Samples,
ct:print("AvgTime ~p", [AvgTime]),
?assert(AvgTime < Micros).
alpha(Minutes)->
1 - math:exp(-math:pow(?INTERVAL,2) / ?SECONDS_PER_MINUTE / math:pow(Minutes,2)).
tick(_Minutes, Count, undefined)->
tick(Minutes, Count, PrevRate)->
InstantRate = Count / ?INTERVAL,
PrevRate + (alpha(Minutes) * (InstantRate - PrevRate)).
|
a3deb19e482751f3377c79d48022622400aabcf3fc8e73e617c97354877f7a44 | deadpendency/deadpendency | Main.hs | module Main
( main,
)
where
import FD.TheMain (theMain)
main :: IO ()
main = theMain
| null | https://raw.githubusercontent.com/deadpendency/deadpendency/170d6689658f81842168b90aa3d9e235d416c8bd/apps/front-door/app/Main.hs | haskell | module Main
( main,
)
where
import FD.TheMain (theMain)
main :: IO ()
main = theMain
| |
c433bf409d3e09687e5e20235137481751abfaee3a7c4598a2775ce2ca48cb6e | Mayvenn/storefront | pagination.cljs | (ns storefront.components.stylist.pagination
(:require [storefront.platform.component-utils :as utils]
[storefront.components.ui :as ui]))
(defn more-pages? [page pages]
(> (or pages 0) (or page 0)))
(defn fetch-more [event fetching? page pages]
[:.col-5.mx-auto.my3
(if fetching?
[:.h2 ui/spinner]
(when (more-pages? page pages)
[:div
(ui/button-medium-secondary
{:on-click (utils/send-event-callback event)}
"Load More")]))])
| null | https://raw.githubusercontent.com/Mayvenn/storefront/f75506230d5ea3dd150c2251e38a2e76e25d9df7/src-cljs/storefront/components/stylist/pagination.cljs | clojure | (ns storefront.components.stylist.pagination
(:require [storefront.platform.component-utils :as utils]
[storefront.components.ui :as ui]))
(defn more-pages? [page pages]
(> (or pages 0) (or page 0)))
(defn fetch-more [event fetching? page pages]
[:.col-5.mx-auto.my3
(if fetching?
[:.h2 ui/spinner]
(when (more-pages? page pages)
[:div
(ui/button-medium-secondary
{:on-click (utils/send-event-callback event)}
"Load More")]))])
| |
511c96cb173b68e45ba645e18947962616bac336e9fc9d664d6ff98ea73d536d | coccinelle/coccinelle | moreLabels.mli | module Hashtbl :
sig
type ('a, 'b) t = ('a, 'b) Hashtbl.t
val create : ?random:bool -> int -> ('a, 'b) t
val clear : ('a, 'b) t -> unit
val reset : ('a, 'b) t -> unit
val copy : ('a, 'b) t -> ('a, 'b) t
val add : ('a, 'b) t -> key:'a -> data:'b -> unit
val find : ('a, 'b) t -> 'a -> 'b
val find_opt : ('a, 'b) t -> 'a -> 'b option
val find_all : ('a, 'b) t -> 'a -> 'b list
val mem : ('a, 'b) t -> 'a -> bool
val remove : ('a, 'b) t -> 'a -> unit
val replace : ('a, 'b) t -> key:'a -> data:'b -> unit
val iter : f:(key:'a -> data:'b -> unit) -> ('a, 'b) t -> unit
val filter_map_inplace :
f:(key:'a -> data:'b -> 'b option) -> ('a, 'b) t -> unit
val fold : f:(key:'a -> data:'b -> 'c -> 'c) -> ('a, 'b) t -> init:'c -> 'c
val length : ('a, 'b) t -> int
val randomize : unit -> unit
val is_randomized : unit -> bool
type statistics = Hashtbl.statistics
val stats : ('a, 'b) t -> statistics
val to_seq : ('a, 'b) t -> ('a * 'b) Seq.t
val to_seq_keys : ('a, 'b) t -> 'a Seq.t
val to_seq_values : ('a, 'b) t -> 'b Seq.t
val add_seq : ('a, 'b) t -> ('a * 'b) Seq.t -> unit
val replace_seq : ('a, 'b) t -> ('a * 'b) Seq.t -> unit
val of_seq : ('a * 'b) Seq.t -> ('a, 'b) t
module type HashedType = Hashtbl.HashedType
module type SeededHashedType = Hashtbl.SeededHashedType
module type S =
sig
type key
and 'a t
val create : int -> 'a t
val clear : 'a t -> unit
val reset : 'a t -> unit
val copy : 'a t -> 'a t
val add : 'a t -> key:key -> data:'a -> unit
val remove : 'a t -> key -> unit
val find : 'a t -> key -> 'a
val find_opt : 'a t -> key -> 'a option
val find_all : 'a t -> key -> 'a list
val replace : 'a t -> key:key -> data:'a -> unit
val mem : 'a t -> key -> bool
val iter : f:(key:key -> data:'a -> unit) -> 'a t -> unit
val filter_map_inplace :
f:(key:key -> data:'a -> 'a option) -> 'a t -> unit
val fold : f:(key:key -> data:'a -> 'b -> 'b) -> 'a t -> init:'b -> 'b
val length : 'a t -> int
val stats : 'a t -> statistics
val to_seq : 'a t -> (key * 'a) Seq.t
val to_seq_keys : 'a t -> key Seq.t
val to_seq_values : 'a t -> 'a Seq.t
val add_seq : 'a t -> (key * 'a) Seq.t -> unit
val replace_seq : 'a t -> (key * 'a) Seq.t -> unit
val of_seq : (key * 'a) Seq.t -> 'a t
end
module type SeededS =
sig
type key
and 'a t
val create : ?random:bool -> int -> 'a t
val clear : 'a t -> unit
val reset : 'a t -> unit
val copy : 'a t -> 'a t
val add : 'a t -> key:key -> data:'a -> unit
val remove : 'a t -> key -> unit
val find : 'a t -> key -> 'a
val find_opt : 'a t -> key -> 'a option
val find_all : 'a t -> key -> 'a list
val replace : 'a t -> key:key -> data:'a -> unit
val mem : 'a t -> key -> bool
val iter : f:(key:key -> data:'a -> unit) -> 'a t -> unit
val filter_map_inplace :
f:(key:key -> data:'a -> 'a option) -> 'a t -> unit
val fold : f:(key:key -> data:'a -> 'b -> 'b) -> 'a t -> init:'b -> 'b
val length : 'a t -> int
val stats : 'a t -> statistics
val to_seq : 'a t -> (key * 'a) Seq.t
val to_seq_keys : 'a t -> key Seq.t
val to_seq_values : 'a t -> 'a Seq.t
val add_seq : 'a t -> (key * 'a) Seq.t -> unit
val replace_seq : 'a t -> (key * 'a) Seq.t -> unit
val of_seq : (key * 'a) Seq.t -> 'a t
end
module Make :
functor (H : HashedType) ->
sig
type key = H.t
and 'a t = 'a Hashtbl.Make(H).t
val create : int -> 'a t
val clear : 'a t -> unit
val reset : 'a t -> unit
val copy : 'a t -> 'a t
val add : 'a t -> key:key -> data:'a -> unit
val remove : 'a t -> key -> unit
val find : 'a t -> key -> 'a
val find_opt : 'a t -> key -> 'a option
val find_all : 'a t -> key -> 'a list
val replace : 'a t -> key:key -> data:'a -> unit
val mem : 'a t -> key -> bool
val iter : f:(key:key -> data:'a -> unit) -> 'a t -> unit
val filter_map_inplace :
f:(key:key -> data:'a -> 'a option) -> 'a t -> unit
val fold : f:(key:key -> data:'a -> 'b -> 'b) -> 'a t -> init:'b -> 'b
val length : 'a t -> int
val stats : 'a t -> statistics
val to_seq : 'a t -> (key * 'a) Seq.t
val to_seq_keys : 'a t -> key Seq.t
val to_seq_values : 'a t -> 'a Seq.t
val add_seq : 'a t -> (key * 'a) Seq.t -> unit
val replace_seq : 'a t -> (key * 'a) Seq.t -> unit
val of_seq : (key * 'a) Seq.t -> 'a t
end
module MakeSeeded :
functor (H : SeededHashedType) ->
sig
type key = H.t
and 'a t = 'a Hashtbl.MakeSeeded(H).t
val create : ?random:bool -> int -> 'a t
val clear : 'a t -> unit
val reset : 'a t -> unit
val copy : 'a t -> 'a t
val add : 'a t -> key:key -> data:'a -> unit
val remove : 'a t -> key -> unit
val find : 'a t -> key -> 'a
val find_opt : 'a t -> key -> 'a option
val find_all : 'a t -> key -> 'a list
val replace : 'a t -> key:key -> data:'a -> unit
val mem : 'a t -> key -> bool
val iter : f:(key:key -> data:'a -> unit) -> 'a t -> unit
val filter_map_inplace :
f:(key:key -> data:'a -> 'a option) -> 'a t -> unit
val fold : f:(key:key -> data:'a -> 'b -> 'b) -> 'a t -> init:'b -> 'b
val length : 'a t -> int
val stats : 'a t -> statistics
val to_seq : 'a t -> (key * 'a) Seq.t
val to_seq_keys : 'a t -> key Seq.t
val to_seq_values : 'a t -> 'a Seq.t
val add_seq : 'a t -> (key * 'a) Seq.t -> unit
val replace_seq : 'a t -> (key * 'a) Seq.t -> unit
val of_seq : (key * 'a) Seq.t -> 'a t
end
val hash : 'a -> int
val seeded_hash : int -> 'a -> int
val hash_param : int -> int -> 'a -> int
val seeded_hash_param : int -> int -> int -> 'a -> int
end
module Map :
sig
module type OrderedType = Map.OrderedType
module type S =
sig
type key
and +'a t
val empty : 'a t
val is_empty : 'a t -> bool
val mem : key -> 'a t -> bool
val add : key:key -> data:'a -> 'a t -> 'a t
val update : key:key -> f:('a option -> 'a option) -> 'a t -> 'a t
val singleton : key -> 'a -> 'a t
val remove : key -> 'a t -> 'a t
val merge :
f:(key -> 'a option -> 'b option -> 'c option) ->
'a t -> 'b t -> 'c t
val union : f:(key -> 'a -> 'a -> 'a option) -> 'a t -> 'a t -> 'a t
val compare : cmp:('a -> 'a -> int) -> 'a t -> 'a t -> int
val equal : cmp:('a -> 'a -> bool) -> 'a t -> 'a t -> bool
val iter : f:(key:key -> data:'a -> unit) -> 'a t -> unit
val fold : f:(key:key -> data:'a -> 'b -> 'b) -> 'a t -> init:'b -> 'b
val for_all : f:(key -> 'a -> bool) -> 'a t -> bool
val exists : f:(key -> 'a -> bool) -> 'a t -> bool
val filter : f:(key -> 'a -> bool) -> 'a t -> 'a t
val filter_map : f:(key -> 'a -> 'b option) -> 'a t -> 'b t
val partition : f:(key -> 'a -> bool) -> 'a t -> ('a t * 'a t)
val cardinal : 'a t -> int
val bindings : 'a t -> (key * 'a) list
val min_binding : 'a t -> (key * 'a)
val min_binding_opt : 'a t -> (key * 'a) option
val max_binding : 'a t -> (key * 'a)
val max_binding_opt : 'a t -> (key * 'a) option
val choose : 'a t -> (key * 'a)
val choose_opt : 'a t -> (key * 'a) option
val split : key -> 'a t -> ('a t * 'a option * 'a t)
val find : key -> 'a t -> 'a
val find_opt : key -> 'a t -> 'a option
val find_first : f:(key -> bool) -> 'a t -> (key * 'a)
val find_first_opt : f:(key -> bool) -> 'a t -> (key * 'a) option
val find_last : f:(key -> bool) -> 'a t -> (key * 'a)
val find_last_opt : f:(key -> bool) -> 'a t -> (key * 'a) option
val map : f:('a -> 'b) -> 'a t -> 'b t
val mapi : f:(key -> 'a -> 'b) -> 'a t -> 'b t
val to_seq : 'a t -> (key * 'a) Seq.t
val to_seq_from : key -> 'a t -> (key * 'a) Seq.t
val add_seq : (key * 'a) Seq.t -> 'a t -> 'a t
val of_seq : (key * 'a) Seq.t -> 'a t
end
module Make :
functor (Ord : OrderedType) ->
sig
type key = Ord.t
and 'a t = 'a Map.Make(Ord).t
val empty : 'a t
val is_empty : 'a t -> bool
val mem : key -> 'a t -> bool
val add : key:key -> data:'a -> 'a t -> 'a t
val update : key:key -> f:('a option -> 'a option) -> 'a t -> 'a t
val singleton : key -> 'a -> 'a t
val remove : key -> 'a t -> 'a t
val merge :
f:(key -> 'a option -> 'b option -> 'c option) ->
'a t -> 'b t -> 'c t
val union : f:(key -> 'a -> 'a -> 'a option) -> 'a t -> 'a t -> 'a t
val compare : cmp:('a -> 'a -> int) -> 'a t -> 'a t -> int
val equal : cmp:('a -> 'a -> bool) -> 'a t -> 'a t -> bool
val iter : f:(key:key -> data:'a -> unit) -> 'a t -> unit
val fold : f:(key:key -> data:'a -> 'b -> 'b) -> 'a t -> init:'b -> 'b
val for_all : f:(key -> 'a -> bool) -> 'a t -> bool
val exists : f:(key -> 'a -> bool) -> 'a t -> bool
val filter : f:(key -> 'a -> bool) -> 'a t -> 'a t
val filter_map : f:(key -> 'a -> 'b option) -> 'a t -> 'b t
val partition : f:(key -> 'a -> bool) -> 'a t -> ('a t * 'a t)
val cardinal : 'a t -> int
val bindings : 'a t -> (key * 'a) list
val min_binding : 'a t -> (key * 'a)
val min_binding_opt : 'a t -> (key * 'a) option
val max_binding : 'a t -> (key * 'a)
val max_binding_opt : 'a t -> (key * 'a) option
val choose : 'a t -> (key * 'a)
val choose_opt : 'a t -> (key * 'a) option
val split : key -> 'a t -> ('a t * 'a option * 'a t)
val find : key -> 'a t -> 'a
val find_opt : key -> 'a t -> 'a option
val find_first : f:(key -> bool) -> 'a t -> (key * 'a)
val find_first_opt : f:(key -> bool) -> 'a t -> (key * 'a) option
val find_last : f:(key -> bool) -> 'a t -> (key * 'a)
val find_last_opt : f:(key -> bool) -> 'a t -> (key * 'a) option
val map : f:('a -> 'b) -> 'a t -> 'b t
val mapi : f:(key -> 'a -> 'b) -> 'a t -> 'b t
val to_seq : 'a t -> (key * 'a) Seq.t
val to_seq_from : key -> 'a t -> (key * 'a) Seq.t
val add_seq : (key * 'a) Seq.t -> 'a t -> 'a t
val of_seq : (key * 'a) Seq.t -> 'a t
end
end
module Set :
sig
module type OrderedType = Set.OrderedType
module type S =
sig
type elt
and t
val empty : t
val is_empty : t -> bool
val mem : elt -> t -> bool
val add : elt -> t -> t
val singleton : elt -> t
val remove : elt -> t -> t
val union : t -> t -> t
val inter : t -> t -> t
val disjoint : t -> t -> bool
val diff : t -> t -> t
val compare : t -> t -> int
val equal : t -> t -> bool
val subset : t -> t -> bool
val iter : f:(elt -> unit) -> t -> unit
val map : f:(elt -> elt) -> t -> t
val fold : f:(elt -> 'a -> 'a) -> t -> init:'a -> 'a
val for_all : f:(elt -> bool) -> t -> bool
val exists : f:(elt -> bool) -> t -> bool
val filter : f:(elt -> bool) -> t -> t
val filter_map : f:(elt -> elt option) -> t -> t
val partition : f:(elt -> bool) -> t -> (t * t)
val cardinal : t -> int
val elements : t -> elt list
val min_elt : t -> elt
val min_elt_opt : t -> elt option
val max_elt : t -> elt
val max_elt_opt : t -> elt option
val choose : t -> elt
val choose_opt : t -> elt option
val split : elt -> t -> (t * bool * t)
val find : elt -> t -> elt
val find_opt : elt -> t -> elt option
val find_first : f:(elt -> bool) -> t -> elt
val find_first_opt : f:(elt -> bool) -> t -> elt option
val find_last : f:(elt -> bool) -> t -> elt
val find_last_opt : f:(elt -> bool) -> t -> elt option
val of_list : elt list -> t
val to_seq_from : elt -> t -> elt Seq.t
val to_seq : t -> elt Seq.t
val add_seq : elt Seq.t -> t -> t
val of_seq : elt Seq.t -> t
end
module Make :
functor (Ord : OrderedType) ->
sig
type elt = Ord.t
and t = Set.Make(Ord).t
val empty : t
val is_empty : t -> bool
val mem : elt -> t -> bool
val add : elt -> t -> t
val singleton : elt -> t
val remove : elt -> t -> t
val union : t -> t -> t
val inter : t -> t -> t
val disjoint : t -> t -> bool
val diff : t -> t -> t
val compare : t -> t -> int
val equal : t -> t -> bool
val subset : t -> t -> bool
val iter : f:(elt -> unit) -> t -> unit
val map : f:(elt -> elt) -> t -> t
val fold : f:(elt -> 'a -> 'a) -> t -> init:'a -> 'a
val for_all : f:(elt -> bool) -> t -> bool
val exists : f:(elt -> bool) -> t -> bool
val filter : f:(elt -> bool) -> t -> t
val filter_map : f:(elt -> elt option) -> t -> t
val partition : f:(elt -> bool) -> t -> (t * t)
val cardinal : t -> int
val elements : t -> elt list
val min_elt : t -> elt
val min_elt_opt : t -> elt option
val max_elt : t -> elt
val max_elt_opt : t -> elt option
val choose : t -> elt
val choose_opt : t -> elt option
val split : elt -> t -> (t * bool * t)
val find : elt -> t -> elt
val find_opt : elt -> t -> elt option
val find_first : f:(elt -> bool) -> t -> elt
val find_first_opt : f:(elt -> bool) -> t -> elt option
val find_last : f:(elt -> bool) -> t -> elt
val find_last_opt : f:(elt -> bool) -> t -> elt option
val of_list : elt list -> t
val to_seq_from : elt -> t -> elt Seq.t
val to_seq : t -> elt Seq.t
val add_seq : elt Seq.t -> t -> t
val of_seq : elt Seq.t -> t
end
end
| null | https://raw.githubusercontent.com/coccinelle/coccinelle/5448bb2bd03491ffec356bf7bd6ddcdbf4d36bc9/bundles/stdcompat/stdcompat-current/interfaces/4.11/moreLabels.mli | ocaml | module Hashtbl :
sig
type ('a, 'b) t = ('a, 'b) Hashtbl.t
val create : ?random:bool -> int -> ('a, 'b) t
val clear : ('a, 'b) t -> unit
val reset : ('a, 'b) t -> unit
val copy : ('a, 'b) t -> ('a, 'b) t
val add : ('a, 'b) t -> key:'a -> data:'b -> unit
val find : ('a, 'b) t -> 'a -> 'b
val find_opt : ('a, 'b) t -> 'a -> 'b option
val find_all : ('a, 'b) t -> 'a -> 'b list
val mem : ('a, 'b) t -> 'a -> bool
val remove : ('a, 'b) t -> 'a -> unit
val replace : ('a, 'b) t -> key:'a -> data:'b -> unit
val iter : f:(key:'a -> data:'b -> unit) -> ('a, 'b) t -> unit
val filter_map_inplace :
f:(key:'a -> data:'b -> 'b option) -> ('a, 'b) t -> unit
val fold : f:(key:'a -> data:'b -> 'c -> 'c) -> ('a, 'b) t -> init:'c -> 'c
val length : ('a, 'b) t -> int
val randomize : unit -> unit
val is_randomized : unit -> bool
type statistics = Hashtbl.statistics
val stats : ('a, 'b) t -> statistics
val to_seq : ('a, 'b) t -> ('a * 'b) Seq.t
val to_seq_keys : ('a, 'b) t -> 'a Seq.t
val to_seq_values : ('a, 'b) t -> 'b Seq.t
val add_seq : ('a, 'b) t -> ('a * 'b) Seq.t -> unit
val replace_seq : ('a, 'b) t -> ('a * 'b) Seq.t -> unit
val of_seq : ('a * 'b) Seq.t -> ('a, 'b) t
module type HashedType = Hashtbl.HashedType
module type SeededHashedType = Hashtbl.SeededHashedType
module type S =
sig
type key
and 'a t
val create : int -> 'a t
val clear : 'a t -> unit
val reset : 'a t -> unit
val copy : 'a t -> 'a t
val add : 'a t -> key:key -> data:'a -> unit
val remove : 'a t -> key -> unit
val find : 'a t -> key -> 'a
val find_opt : 'a t -> key -> 'a option
val find_all : 'a t -> key -> 'a list
val replace : 'a t -> key:key -> data:'a -> unit
val mem : 'a t -> key -> bool
val iter : f:(key:key -> data:'a -> unit) -> 'a t -> unit
val filter_map_inplace :
f:(key:key -> data:'a -> 'a option) -> 'a t -> unit
val fold : f:(key:key -> data:'a -> 'b -> 'b) -> 'a t -> init:'b -> 'b
val length : 'a t -> int
val stats : 'a t -> statistics
val to_seq : 'a t -> (key * 'a) Seq.t
val to_seq_keys : 'a t -> key Seq.t
val to_seq_values : 'a t -> 'a Seq.t
val add_seq : 'a t -> (key * 'a) Seq.t -> unit
val replace_seq : 'a t -> (key * 'a) Seq.t -> unit
val of_seq : (key * 'a) Seq.t -> 'a t
end
module type SeededS =
sig
type key
and 'a t
val create : ?random:bool -> int -> 'a t
val clear : 'a t -> unit
val reset : 'a t -> unit
val copy : 'a t -> 'a t
val add : 'a t -> key:key -> data:'a -> unit
val remove : 'a t -> key -> unit
val find : 'a t -> key -> 'a
val find_opt : 'a t -> key -> 'a option
val find_all : 'a t -> key -> 'a list
val replace : 'a t -> key:key -> data:'a -> unit
val mem : 'a t -> key -> bool
val iter : f:(key:key -> data:'a -> unit) -> 'a t -> unit
val filter_map_inplace :
f:(key:key -> data:'a -> 'a option) -> 'a t -> unit
val fold : f:(key:key -> data:'a -> 'b -> 'b) -> 'a t -> init:'b -> 'b
val length : 'a t -> int
val stats : 'a t -> statistics
val to_seq : 'a t -> (key * 'a) Seq.t
val to_seq_keys : 'a t -> key Seq.t
val to_seq_values : 'a t -> 'a Seq.t
val add_seq : 'a t -> (key * 'a) Seq.t -> unit
val replace_seq : 'a t -> (key * 'a) Seq.t -> unit
val of_seq : (key * 'a) Seq.t -> 'a t
end
module Make :
functor (H : HashedType) ->
sig
type key = H.t
and 'a t = 'a Hashtbl.Make(H).t
val create : int -> 'a t
val clear : 'a t -> unit
val reset : 'a t -> unit
val copy : 'a t -> 'a t
val add : 'a t -> key:key -> data:'a -> unit
val remove : 'a t -> key -> unit
val find : 'a t -> key -> 'a
val find_opt : 'a t -> key -> 'a option
val find_all : 'a t -> key -> 'a list
val replace : 'a t -> key:key -> data:'a -> unit
val mem : 'a t -> key -> bool
val iter : f:(key:key -> data:'a -> unit) -> 'a t -> unit
val filter_map_inplace :
f:(key:key -> data:'a -> 'a option) -> 'a t -> unit
val fold : f:(key:key -> data:'a -> 'b -> 'b) -> 'a t -> init:'b -> 'b
val length : 'a t -> int
val stats : 'a t -> statistics
val to_seq : 'a t -> (key * 'a) Seq.t
val to_seq_keys : 'a t -> key Seq.t
val to_seq_values : 'a t -> 'a Seq.t
val add_seq : 'a t -> (key * 'a) Seq.t -> unit
val replace_seq : 'a t -> (key * 'a) Seq.t -> unit
val of_seq : (key * 'a) Seq.t -> 'a t
end
module MakeSeeded :
functor (H : SeededHashedType) ->
sig
type key = H.t
and 'a t = 'a Hashtbl.MakeSeeded(H).t
val create : ?random:bool -> int -> 'a t
val clear : 'a t -> unit
val reset : 'a t -> unit
val copy : 'a t -> 'a t
val add : 'a t -> key:key -> data:'a -> unit
val remove : 'a t -> key -> unit
val find : 'a t -> key -> 'a
val find_opt : 'a t -> key -> 'a option
val find_all : 'a t -> key -> 'a list
val replace : 'a t -> key:key -> data:'a -> unit
val mem : 'a t -> key -> bool
val iter : f:(key:key -> data:'a -> unit) -> 'a t -> unit
val filter_map_inplace :
f:(key:key -> data:'a -> 'a option) -> 'a t -> unit
val fold : f:(key:key -> data:'a -> 'b -> 'b) -> 'a t -> init:'b -> 'b
val length : 'a t -> int
val stats : 'a t -> statistics
val to_seq : 'a t -> (key * 'a) Seq.t
val to_seq_keys : 'a t -> key Seq.t
val to_seq_values : 'a t -> 'a Seq.t
val add_seq : 'a t -> (key * 'a) Seq.t -> unit
val replace_seq : 'a t -> (key * 'a) Seq.t -> unit
val of_seq : (key * 'a) Seq.t -> 'a t
end
val hash : 'a -> int
val seeded_hash : int -> 'a -> int
val hash_param : int -> int -> 'a -> int
val seeded_hash_param : int -> int -> int -> 'a -> int
end
module Map :
sig
module type OrderedType = Map.OrderedType
module type S =
sig
type key
and +'a t
val empty : 'a t
val is_empty : 'a t -> bool
val mem : key -> 'a t -> bool
val add : key:key -> data:'a -> 'a t -> 'a t
val update : key:key -> f:('a option -> 'a option) -> 'a t -> 'a t
val singleton : key -> 'a -> 'a t
val remove : key -> 'a t -> 'a t
val merge :
f:(key -> 'a option -> 'b option -> 'c option) ->
'a t -> 'b t -> 'c t
val union : f:(key -> 'a -> 'a -> 'a option) -> 'a t -> 'a t -> 'a t
val compare : cmp:('a -> 'a -> int) -> 'a t -> 'a t -> int
val equal : cmp:('a -> 'a -> bool) -> 'a t -> 'a t -> bool
val iter : f:(key:key -> data:'a -> unit) -> 'a t -> unit
val fold : f:(key:key -> data:'a -> 'b -> 'b) -> 'a t -> init:'b -> 'b
val for_all : f:(key -> 'a -> bool) -> 'a t -> bool
val exists : f:(key -> 'a -> bool) -> 'a t -> bool
val filter : f:(key -> 'a -> bool) -> 'a t -> 'a t
val filter_map : f:(key -> 'a -> 'b option) -> 'a t -> 'b t
val partition : f:(key -> 'a -> bool) -> 'a t -> ('a t * 'a t)
val cardinal : 'a t -> int
val bindings : 'a t -> (key * 'a) list
val min_binding : 'a t -> (key * 'a)
val min_binding_opt : 'a t -> (key * 'a) option
val max_binding : 'a t -> (key * 'a)
val max_binding_opt : 'a t -> (key * 'a) option
val choose : 'a t -> (key * 'a)
val choose_opt : 'a t -> (key * 'a) option
val split : key -> 'a t -> ('a t * 'a option * 'a t)
val find : key -> 'a t -> 'a
val find_opt : key -> 'a t -> 'a option
val find_first : f:(key -> bool) -> 'a t -> (key * 'a)
val find_first_opt : f:(key -> bool) -> 'a t -> (key * 'a) option
val find_last : f:(key -> bool) -> 'a t -> (key * 'a)
val find_last_opt : f:(key -> bool) -> 'a t -> (key * 'a) option
val map : f:('a -> 'b) -> 'a t -> 'b t
val mapi : f:(key -> 'a -> 'b) -> 'a t -> 'b t
val to_seq : 'a t -> (key * 'a) Seq.t
val to_seq_from : key -> 'a t -> (key * 'a) Seq.t
val add_seq : (key * 'a) Seq.t -> 'a t -> 'a t
val of_seq : (key * 'a) Seq.t -> 'a t
end
module Make :
functor (Ord : OrderedType) ->
sig
type key = Ord.t
and 'a t = 'a Map.Make(Ord).t
val empty : 'a t
val is_empty : 'a t -> bool
val mem : key -> 'a t -> bool
val add : key:key -> data:'a -> 'a t -> 'a t
val update : key:key -> f:('a option -> 'a option) -> 'a t -> 'a t
val singleton : key -> 'a -> 'a t
val remove : key -> 'a t -> 'a t
val merge :
f:(key -> 'a option -> 'b option -> 'c option) ->
'a t -> 'b t -> 'c t
val union : f:(key -> 'a -> 'a -> 'a option) -> 'a t -> 'a t -> 'a t
val compare : cmp:('a -> 'a -> int) -> 'a t -> 'a t -> int
val equal : cmp:('a -> 'a -> bool) -> 'a t -> 'a t -> bool
val iter : f:(key:key -> data:'a -> unit) -> 'a t -> unit
val fold : f:(key:key -> data:'a -> 'b -> 'b) -> 'a t -> init:'b -> 'b
val for_all : f:(key -> 'a -> bool) -> 'a t -> bool
val exists : f:(key -> 'a -> bool) -> 'a t -> bool
val filter : f:(key -> 'a -> bool) -> 'a t -> 'a t
val filter_map : f:(key -> 'a -> 'b option) -> 'a t -> 'b t
val partition : f:(key -> 'a -> bool) -> 'a t -> ('a t * 'a t)
val cardinal : 'a t -> int
val bindings : 'a t -> (key * 'a) list
val min_binding : 'a t -> (key * 'a)
val min_binding_opt : 'a t -> (key * 'a) option
val max_binding : 'a t -> (key * 'a)
val max_binding_opt : 'a t -> (key * 'a) option
val choose : 'a t -> (key * 'a)
val choose_opt : 'a t -> (key * 'a) option
val split : key -> 'a t -> ('a t * 'a option * 'a t)
val find : key -> 'a t -> 'a
val find_opt : key -> 'a t -> 'a option
val find_first : f:(key -> bool) -> 'a t -> (key * 'a)
val find_first_opt : f:(key -> bool) -> 'a t -> (key * 'a) option
val find_last : f:(key -> bool) -> 'a t -> (key * 'a)
val find_last_opt : f:(key -> bool) -> 'a t -> (key * 'a) option
val map : f:('a -> 'b) -> 'a t -> 'b t
val mapi : f:(key -> 'a -> 'b) -> 'a t -> 'b t
val to_seq : 'a t -> (key * 'a) Seq.t
val to_seq_from : key -> 'a t -> (key * 'a) Seq.t
val add_seq : (key * 'a) Seq.t -> 'a t -> 'a t
val of_seq : (key * 'a) Seq.t -> 'a t
end
end
module Set :
sig
module type OrderedType = Set.OrderedType
module type S =
sig
type elt
and t
val empty : t
val is_empty : t -> bool
val mem : elt -> t -> bool
val add : elt -> t -> t
val singleton : elt -> t
val remove : elt -> t -> t
val union : t -> t -> t
val inter : t -> t -> t
val disjoint : t -> t -> bool
val diff : t -> t -> t
val compare : t -> t -> int
val equal : t -> t -> bool
val subset : t -> t -> bool
val iter : f:(elt -> unit) -> t -> unit
val map : f:(elt -> elt) -> t -> t
val fold : f:(elt -> 'a -> 'a) -> t -> init:'a -> 'a
val for_all : f:(elt -> bool) -> t -> bool
val exists : f:(elt -> bool) -> t -> bool
val filter : f:(elt -> bool) -> t -> t
val filter_map : f:(elt -> elt option) -> t -> t
val partition : f:(elt -> bool) -> t -> (t * t)
val cardinal : t -> int
val elements : t -> elt list
val min_elt : t -> elt
val min_elt_opt : t -> elt option
val max_elt : t -> elt
val max_elt_opt : t -> elt option
val choose : t -> elt
val choose_opt : t -> elt option
val split : elt -> t -> (t * bool * t)
val find : elt -> t -> elt
val find_opt : elt -> t -> elt option
val find_first : f:(elt -> bool) -> t -> elt
val find_first_opt : f:(elt -> bool) -> t -> elt option
val find_last : f:(elt -> bool) -> t -> elt
val find_last_opt : f:(elt -> bool) -> t -> elt option
val of_list : elt list -> t
val to_seq_from : elt -> t -> elt Seq.t
val to_seq : t -> elt Seq.t
val add_seq : elt Seq.t -> t -> t
val of_seq : elt Seq.t -> t
end
module Make :
functor (Ord : OrderedType) ->
sig
type elt = Ord.t
and t = Set.Make(Ord).t
val empty : t
val is_empty : t -> bool
val mem : elt -> t -> bool
val add : elt -> t -> t
val singleton : elt -> t
val remove : elt -> t -> t
val union : t -> t -> t
val inter : t -> t -> t
val disjoint : t -> t -> bool
val diff : t -> t -> t
val compare : t -> t -> int
val equal : t -> t -> bool
val subset : t -> t -> bool
val iter : f:(elt -> unit) -> t -> unit
val map : f:(elt -> elt) -> t -> t
val fold : f:(elt -> 'a -> 'a) -> t -> init:'a -> 'a
val for_all : f:(elt -> bool) -> t -> bool
val exists : f:(elt -> bool) -> t -> bool
val filter : f:(elt -> bool) -> t -> t
val filter_map : f:(elt -> elt option) -> t -> t
val partition : f:(elt -> bool) -> t -> (t * t)
val cardinal : t -> int
val elements : t -> elt list
val min_elt : t -> elt
val min_elt_opt : t -> elt option
val max_elt : t -> elt
val max_elt_opt : t -> elt option
val choose : t -> elt
val choose_opt : t -> elt option
val split : elt -> t -> (t * bool * t)
val find : elt -> t -> elt
val find_opt : elt -> t -> elt option
val find_first : f:(elt -> bool) -> t -> elt
val find_first_opt : f:(elt -> bool) -> t -> elt option
val find_last : f:(elt -> bool) -> t -> elt
val find_last_opt : f:(elt -> bool) -> t -> elt option
val of_list : elt list -> t
val to_seq_from : elt -> t -> elt Seq.t
val to_seq : t -> elt Seq.t
val add_seq : elt Seq.t -> t -> t
val of_seq : elt Seq.t -> t
end
end
| |
4ac681ed6e9cb19d07ce294c88238e5723925fa56d740744e409740fef1108a6 | GaloisInc/renovate | Common.hs |
Module : Renovate . BinaryFormat . ELF.Common
Description : Common operations for dealing with ELF files
Copyright : ( c ) Galois , Inc 2020
License : < >
Stability : provisional
Module : Renovate.BinaryFormat.ELF.Common
Description : Common operations for dealing with ELF files
Copyright : (c) Galois, Inc 2020
License : BSD3
Maintainer : Langston Barrett <>
Stability : provisional
-}
# LANGUAGE FlexibleContexts #
module Renovate.BinaryFormat.ELF.Common
( module Renovate.BinaryFormat.ELF.Common.Internal
, allocatedVAddrs
, allocatedVAddrsM
, findTextSections
, findTextSection
, pageAlignment
, newTextAlign
) where
import qualified Control.Monad.Catch as C
import qualified Data.ByteString.Char8 as C8
import qualified Data.Foldable as F
import qualified Data.Map as Map
import Data.Word (Word64)
import qualified Data.ElfEdit as E
import Renovate.BinaryFormat.ELF.Common.Internal
import qualified Renovate.Core.Exception as RCE
-- | Extract all the segments' virtual addresses (keys) and their sizes
-- (values). If we don't know the size of a segment yet because it is going to
-- be computed later, return that segment as an error.
allocatedVAddrs ::
E.ElfWidthConstraints w =>
E.Elf w ->
Either (E.ElfSegment w)
(Map.Map (E.ElfWordType w) (E.ElfWordType w))
allocatedVAddrs e = F.foldl' (Map.unionWith max) Map.empty <$> traverse processRegion (E._elfFileData e) where
processRegion (E.ElfDataSegment seg) = case E.elfSegmentMemSize seg of
E.ElfRelativeSize{} -> Left seg
E.ElfAbsoluteSize size -> return (Map.singleton (E.elfSegmentVirtAddr seg) size)
processRegion _ = return Map.empty
-- | Like allocatedVAddrs, but throw an error instead of returning it purely
allocatedVAddrsM
:: (C.MonadThrow m, E.ElfWidthConstraints w)
=> E.Elf w
-> m (Map.Map (E.ElfWordType w) (E.ElfWordType w))
allocatedVAddrsM e = case allocatedVAddrs e of
Left seg -> C.throwM (RCE.SegmentHasRelativeSize (toInteger (E.elfSegmentIndex seg)))
Right m -> return m
findTextSections :: E.Elf w -> [E.ElfSection (E.ElfWordType w)]
findTextSections = E.findSectionByName (C8.pack ".text")
findTextSection :: C.MonadThrow m => E.Elf w -> m (E.ElfSection (E.ElfWordType w))
findTextSection e = do
case findTextSections e of
[textSection] -> return textSection
[] -> C.throwM (RCE.MissingExpectedSection ".text")
sections -> C.throwM (RCE.MultipleSectionDefinitions ".text" (length sections))
| The system page alignment ( assuming 4k pages )
pageAlignment :: Word64
pageAlignment = 0x1000
-- | The alignment of the new text segment
--
-- We could just copy the alignment from the old one, but the alignment on x86
-- is very high, which would waste a lot of space. It seems like setting it
-- lower is safe...
newTextAlign :: Word64
newTextAlign = pageAlignment
| null | https://raw.githubusercontent.com/GaloisInc/renovate/89b82366f84be894c3437852e39c9b4e28666a37/renovate/src/Renovate/BinaryFormat/ELF/Common.hs | haskell | | Extract all the segments' virtual addresses (keys) and their sizes
(values). If we don't know the size of a segment yet because it is going to
be computed later, return that segment as an error.
| Like allocatedVAddrs, but throw an error instead of returning it purely
| The alignment of the new text segment
We could just copy the alignment from the old one, but the alignment on x86
is very high, which would waste a lot of space. It seems like setting it
lower is safe... |
Module : Renovate . BinaryFormat . ELF.Common
Description : Common operations for dealing with ELF files
Copyright : ( c ) Galois , Inc 2020
License : < >
Stability : provisional
Module : Renovate.BinaryFormat.ELF.Common
Description : Common operations for dealing with ELF files
Copyright : (c) Galois, Inc 2020
License : BSD3
Maintainer : Langston Barrett <>
Stability : provisional
-}
# LANGUAGE FlexibleContexts #
module Renovate.BinaryFormat.ELF.Common
( module Renovate.BinaryFormat.ELF.Common.Internal
, allocatedVAddrs
, allocatedVAddrsM
, findTextSections
, findTextSection
, pageAlignment
, newTextAlign
) where
import qualified Control.Monad.Catch as C
import qualified Data.ByteString.Char8 as C8
import qualified Data.Foldable as F
import qualified Data.Map as Map
import Data.Word (Word64)
import qualified Data.ElfEdit as E
import Renovate.BinaryFormat.ELF.Common.Internal
import qualified Renovate.Core.Exception as RCE
allocatedVAddrs ::
E.ElfWidthConstraints w =>
E.Elf w ->
Either (E.ElfSegment w)
(Map.Map (E.ElfWordType w) (E.ElfWordType w))
allocatedVAddrs e = F.foldl' (Map.unionWith max) Map.empty <$> traverse processRegion (E._elfFileData e) where
processRegion (E.ElfDataSegment seg) = case E.elfSegmentMemSize seg of
E.ElfRelativeSize{} -> Left seg
E.ElfAbsoluteSize size -> return (Map.singleton (E.elfSegmentVirtAddr seg) size)
processRegion _ = return Map.empty
allocatedVAddrsM
:: (C.MonadThrow m, E.ElfWidthConstraints w)
=> E.Elf w
-> m (Map.Map (E.ElfWordType w) (E.ElfWordType w))
allocatedVAddrsM e = case allocatedVAddrs e of
Left seg -> C.throwM (RCE.SegmentHasRelativeSize (toInteger (E.elfSegmentIndex seg)))
Right m -> return m
findTextSections :: E.Elf w -> [E.ElfSection (E.ElfWordType w)]
findTextSections = E.findSectionByName (C8.pack ".text")
findTextSection :: C.MonadThrow m => E.Elf w -> m (E.ElfSection (E.ElfWordType w))
findTextSection e = do
case findTextSections e of
[textSection] -> return textSection
[] -> C.throwM (RCE.MissingExpectedSection ".text")
sections -> C.throwM (RCE.MultipleSectionDefinitions ".text" (length sections))
| The system page alignment ( assuming 4k pages )
pageAlignment :: Word64
pageAlignment = 0x1000
newTextAlign :: Word64
newTextAlign = pageAlignment
|
6ac79e33c350765b2ab9dc03de7c09ea9a12ce69ffbffdcdff37a9f94713badc | postgres-haskell/postgres-wire | Misc.hs | module Misc where
import qualified Data.ByteString as B
import Data.Foldable
import Test.Tasty
import Test.Tasty.HUnit
import Database.PostgreSQL.Protocol.Types
import Database.PostgreSQL.Protocol.Parsers
testMisc :: TestTree
testMisc = testGroup "Misc"
[ testCase "Parser server version" testParseServerVersion
]
testParseServerVersion :: IO ()
testParseServerVersion = traverse_ testSingle
[ ("9.2", ServerVersion 9 2 0 "")
, ("9.2.1", ServerVersion 9 2 1 "")
, ("9.4beta1", ServerVersion 9 4 0 "beta1")
, ("10devel", ServerVersion 10 0 0 "devel")
, ("10beta2", ServerVersion 10 0 0 "beta2")
]
where
testSingle (str, result) = case parseServerVersion str of
Left _ -> assertFailure "Should be Right, got error "
Right v -> result @=? v
| null | https://raw.githubusercontent.com/postgres-haskell/postgres-wire/fda5e3b70c3cc0bab8365b4b872991d50da0348c/tests/Misc.hs | haskell | module Misc where
import qualified Data.ByteString as B
import Data.Foldable
import Test.Tasty
import Test.Tasty.HUnit
import Database.PostgreSQL.Protocol.Types
import Database.PostgreSQL.Protocol.Parsers
testMisc :: TestTree
testMisc = testGroup "Misc"
[ testCase "Parser server version" testParseServerVersion
]
testParseServerVersion :: IO ()
testParseServerVersion = traverse_ testSingle
[ ("9.2", ServerVersion 9 2 0 "")
, ("9.2.1", ServerVersion 9 2 1 "")
, ("9.4beta1", ServerVersion 9 4 0 "beta1")
, ("10devel", ServerVersion 10 0 0 "devel")
, ("10beta2", ServerVersion 10 0 0 "beta2")
]
where
testSingle (str, result) = case parseServerVersion str of
Left _ -> assertFailure "Should be Right, got error "
Right v -> result @=? v
| |
afdd560575d618bfea152932769cccce8b9bbe49eb653d28dc4517ba319079ee | mauny/the-functional-approach-to-programming | pictures.ml | #directory "../MLGRAPH.DIR";;
#open "MLgraph";;
#open "option";;
#open "graph";;
#open "prelude";;
#open "binary_trees";;
#open "binary_trees_parser";;
#open "binary_trees_drawing";;
#open "poly_tree";;
let draw_tree drn (h,d,cl,pt) =
let LS = {linewidth= h*.0.01;linecap=Buttcap;
linejoin=Miterjoin;dashpattern=[]}
in let rec draw_r (d,cl,({xc=x; yc=y} as pt)) =
function
Leaf n -> center_picture (drn n) pt
| Node(a1,a2)
-> let d=d*.(hd cl)
in let pt1 = {xc=x-.d/.2.0;yc=y-.h}
and pt2 = {xc=x+.d/.2.0;yc=y-.h}
in group_pictures
[make_draw_picture
(LS,black)
(make_sketch [Seg [pt;pt1]]);
make_draw_picture
(LS,black)
(make_sketch [Seg [pt;pt2]]);
draw_r (d,tl cl,pt1) a1;
draw_r (d,tl cl,pt2) a2]
in draw_r (d,cl,pt)
;;
let rec convert=
function Leaf _ -> Bin(Empty,1,Empty)
| Node(a1,a2) -> Bin (convert a1,1,convert a2);;
let make_tree_picture drn (height,d_min,root) t =
let t' =convert t
in let coef_list = compute_coef_list t'
in let total_coef = it_list mult_float 1.0 coef_list
in let d= d_min/.total_coef
in draw_tree drn (height,d,coef_list,root) t;;
let draw_s_node r a =
let t=make_text_picture (make_font Helvetica r) black a
in let f= make_fill_picture (Nzfill,white)
(frame_sketch (extend_frame Vertic_ext 0.5
(picture_frame t)))
in center_picture
(group_pictures [f;t])
origin;;
let draw_i_node r n = draw_s_node r (string_of_int n);;
let t= Node(Leaf 3,Node(Leaf 4,Leaf 5))
in let p= make_tree_picture (draw_i_node 8.0)
(30.0,25.0,origin) t
in eps_file p "../../PS/tree_ex";;
let FONT= make_font Courier 3.0;;
let g= assembleGraphs [] ["une";"deux"]
[ [string "arrowDir" "F"; float "arrowPos" 0.65], "une" , De, "deux";
[string "arrowDir" "F"; float "arrowPos" 0.968], "deux", Ds , "une"
];;
let make_string_node s =
let p= make_text_picture FONT black s
in let fr= extend_frame All_ext 0.2 (picture_frame p)
in group_pictures
[make_fill_picture (Nzfill,white) (frame_sketch fr);p];;
let l= map (fun s -> s, (make_string_node ("\"" ^s^"\"") ))
["une";"deux"];;
let p= scale_picture (5.0,5.0)
(graphGen [float "lineWidthCoef" 0.5] g l);;
eps_file p "../../PS/boucle";;
let t= Node(Node(Node(Leaf "a",Leaf "b"),Node(Leaf "c",Leaf "d")),Leaf "e")
in let p= make_tree_picture (draw_s_node 10.0)
(30.0,25.0,origin) t
in eps_file p "../../PS/tree_ex2";;
| null | https://raw.githubusercontent.com/mauny/the-functional-approach-to-programming/1ec8bed5d33d3a67bbd67d09afb3f5c3c8978838/cl-75/Struct/pictures.ml | ocaml | #directory "../MLGRAPH.DIR";;
#open "MLgraph";;
#open "option";;
#open "graph";;
#open "prelude";;
#open "binary_trees";;
#open "binary_trees_parser";;
#open "binary_trees_drawing";;
#open "poly_tree";;
let draw_tree drn (h,d,cl,pt) =
let LS = {linewidth= h*.0.01;linecap=Buttcap;
linejoin=Miterjoin;dashpattern=[]}
in let rec draw_r (d,cl,({xc=x; yc=y} as pt)) =
function
Leaf n -> center_picture (drn n) pt
| Node(a1,a2)
-> let d=d*.(hd cl)
in let pt1 = {xc=x-.d/.2.0;yc=y-.h}
and pt2 = {xc=x+.d/.2.0;yc=y-.h}
in group_pictures
[make_draw_picture
(LS,black)
(make_sketch [Seg [pt;pt1]]);
make_draw_picture
(LS,black)
(make_sketch [Seg [pt;pt2]]);
draw_r (d,tl cl,pt1) a1;
draw_r (d,tl cl,pt2) a2]
in draw_r (d,cl,pt)
;;
let rec convert=
function Leaf _ -> Bin(Empty,1,Empty)
| Node(a1,a2) -> Bin (convert a1,1,convert a2);;
let make_tree_picture drn (height,d_min,root) t =
let t' =convert t
in let coef_list = compute_coef_list t'
in let total_coef = it_list mult_float 1.0 coef_list
in let d= d_min/.total_coef
in draw_tree drn (height,d,coef_list,root) t;;
let draw_s_node r a =
let t=make_text_picture (make_font Helvetica r) black a
in let f= make_fill_picture (Nzfill,white)
(frame_sketch (extend_frame Vertic_ext 0.5
(picture_frame t)))
in center_picture
(group_pictures [f;t])
origin;;
let draw_i_node r n = draw_s_node r (string_of_int n);;
let t= Node(Leaf 3,Node(Leaf 4,Leaf 5))
in let p= make_tree_picture (draw_i_node 8.0)
(30.0,25.0,origin) t
in eps_file p "../../PS/tree_ex";;
let FONT= make_font Courier 3.0;;
let g= assembleGraphs [] ["une";"deux"]
[ [string "arrowDir" "F"; float "arrowPos" 0.65], "une" , De, "deux";
[string "arrowDir" "F"; float "arrowPos" 0.968], "deux", Ds , "une"
];;
let make_string_node s =
let p= make_text_picture FONT black s
in let fr= extend_frame All_ext 0.2 (picture_frame p)
in group_pictures
[make_fill_picture (Nzfill,white) (frame_sketch fr);p];;
let l= map (fun s -> s, (make_string_node ("\"" ^s^"\"") ))
["une";"deux"];;
let p= scale_picture (5.0,5.0)
(graphGen [float "lineWidthCoef" 0.5] g l);;
eps_file p "../../PS/boucle";;
let t= Node(Node(Node(Leaf "a",Leaf "b"),Node(Leaf "c",Leaf "d")),Leaf "e")
in let p= make_tree_picture (draw_s_node 10.0)
(30.0,25.0,origin) t
in eps_file p "../../PS/tree_ex2";;
| |
9e4ada12a93b93d77ba7abdab9f525bdcf8a062ff5abbb83a16fca3981afe5e3 | vyzo/gerbil | gxi-interactive.scm | -*- -*-
( C ) vyzo at hackzen.org
interactive interpreter init
(_gx#gxi-init-interactive! (command-line))
| null | https://raw.githubusercontent.com/vyzo/gerbil/17fbcb95a8302c0de3f88380be1a3eb6fe891b95/src/gerbil/boot/gxi-interactive.scm | scheme | -*- -*-
( C ) vyzo at hackzen.org
interactive interpreter init
(_gx#gxi-init-interactive! (command-line))
| |
3b51ce64564e34112c1d0475666a366e89f6ca9815cd64b67594cf1925a615d9 | callum-oakley/advent-of-code | 21.clj | (ns aoc.2022.21
(:require
[clojure.string :as str]
[clojure.test :refer [deftest is]]))
(defn parse [s]
(into {} (map (fn [line]
(let [[m & job] (map read-string (re-seq #"[^:\s]+" line))]
[m (if (= 1 (count job)) (first job) (vec job))]))
(str/split-lines s))))
(defn part-1 [monkeys]
((fn go [m]
(if (int? (monkeys m))
(monkeys m)
(let [[x op y] (monkeys m)]
(eval (list op (go x) (go y))))))
'root))
(defn part-2 [monkeys]
(let [f (fn [h] (-> monkeys (assoc-in ['root 1] '-) (assoc 'humn h) part-1))]
;; Since monkeys is a tree, f is a linear function of h, so we can find the
root by taking the value of f at two points and extrapolating .
(/ (f 0) (- (f 0) (f 1)))))
(def example
"root: pppw + sjmn\ndbpl: 5\ncczh: sllz + lgvd\nzczc: 2\nptdq: humn - dvpt
dvpt: 3\nlfqf: 4\nhumn: 5\nljgn: 2\nsjmn: drzm * dbpl\nsllz: 4
pppw: cczh / lfqf\nlgvd: ljgn * ptdq\ndrzm: hmdt - zczc\nhmdt: 32")
(deftest test-example
(is (= 152 (part-1 (parse example))))
(is (= 301 (part-2 (parse example)))))
| null | https://raw.githubusercontent.com/callum-oakley/advent-of-code/cfe623aa81cf54b542bcd3062c1edeb61473ebed/src/aoc/2022/21.clj | clojure | Since monkeys is a tree, f is a linear function of h, so we can find the | (ns aoc.2022.21
(:require
[clojure.string :as str]
[clojure.test :refer [deftest is]]))
(defn parse [s]
(into {} (map (fn [line]
(let [[m & job] (map read-string (re-seq #"[^:\s]+" line))]
[m (if (= 1 (count job)) (first job) (vec job))]))
(str/split-lines s))))
(defn part-1 [monkeys]
((fn go [m]
(if (int? (monkeys m))
(monkeys m)
(let [[x op y] (monkeys m)]
(eval (list op (go x) (go y))))))
'root))
(defn part-2 [monkeys]
(let [f (fn [h] (-> monkeys (assoc-in ['root 1] '-) (assoc 'humn h) part-1))]
root by taking the value of f at two points and extrapolating .
(/ (f 0) (- (f 0) (f 1)))))
(def example
"root: pppw + sjmn\ndbpl: 5\ncczh: sllz + lgvd\nzczc: 2\nptdq: humn - dvpt
dvpt: 3\nlfqf: 4\nhumn: 5\nljgn: 2\nsjmn: drzm * dbpl\nsllz: 4
pppw: cczh / lfqf\nlgvd: ljgn * ptdq\ndrzm: hmdt - zczc\nhmdt: 32")
(deftest test-example
(is (= 152 (part-1 (parse example))))
(is (= 301 (part-2 (parse example)))))
|
a4d72d076c4945c53ae51256459245add4895c1d6e154af7ee91da318ced0669 | sebsheep/elm2node | Extract.hs | # OPTIONS_GHC -Wall #
# LANGUAGE BangPatterns , OverloadedStrings , Rank2Types #
module Elm.Compiler.Type.Extract
( fromAnnotation
, fromType
, Types(..)
, mergeMany
, merge
, fromInterface
, fromDependencyInterface
, fromMsg
)
where
import Data.Map ((!))
import qualified Data.Map as Map
import qualified Data.Maybe as Maybe
import qualified Data.Name as Name
import qualified Data.Set as Set
import qualified AST.Canonical as Can
import qualified AST.Optimized as Opt
import qualified AST.Utils.Type as Type
import qualified Elm.Compiler.Type as T
import qualified Elm.Interface as I
import qualified Elm.ModuleName as ModuleName
-- EXTRACTION
fromAnnotation :: Can.Annotation -> T.Type
fromAnnotation (Can.Forall _ astType) =
fromType astType
fromType :: Can.Type -> T.Type
fromType astType =
snd (run (extract astType))
extract :: Can.Type -> Extractor T.Type
extract astType =
case astType of
Can.TLambda arg result ->
T.Lambda
<$> extract arg
<*> extract result
Can.TVar x ->
pure (T.Var x)
Can.TType home name args ->
addUnion (Opt.Global home name) (T.Type (toPublicName home name))
<*> traverse extract args
Can.TRecord fields ext ->
do efields <- traverse (traverse extract) (Can.fieldsToList fields)
pure (T.Record efields ext)
Can.TUnit ->
pure T.Unit
Can.TTuple a b maybeC ->
T.Tuple
<$> extract a
<*> extract b
<*> traverse extract (Maybe.maybeToList maybeC)
Can.TAlias home name args aliasType ->
do addAlias (Opt.Global home name) ()
_ <- extract (Type.dealias args aliasType)
T.Type (toPublicName home name)
<$> traverse (extract . snd) args
toPublicName :: ModuleName.Canonical -> Name.Name -> Name.Name
toPublicName (ModuleName.Canonical _ home) name =
Name.sepBy 0x2E {- . -} home name
TRANSITIVELY AVAILABLE TYPES
newtype Types =
Types (Map.Map ModuleName.Canonical Types_)
-- PERF profile Opt.Global representation
-- current representation needs less allocation
-- but maybe the lookup is much worse
data Types_ =
Types_
{ _union_info :: Map.Map Name.Name Can.Union
, _alias_info :: Map.Map Name.Name Can.Alias
}
mergeMany :: [Types] -> Types
mergeMany listOfTypes =
case listOfTypes of
[] -> Types Map.empty
t:ts -> foldr merge t ts
merge :: Types -> Types -> Types
merge (Types types1) (Types types2) =
Types (Map.union types1 types2)
fromInterface :: ModuleName.Raw -> I.Interface -> Types
fromInterface name (I.Interface pkg _ unions aliases _) =
Types $ Map.singleton (ModuleName.Canonical pkg name) $
Types_ (Map.map I.extractUnion unions) (Map.map I.extractAlias aliases)
fromDependencyInterface :: ModuleName.Canonical -> I.DependencyInterface -> Types
fromDependencyInterface home di =
Types $ Map.singleton home $
case di of
I.Public (I.Interface _ _ unions aliases _) ->
Types_ (Map.map I.extractUnion unions) (Map.map I.extractAlias aliases)
I.Private _ unions aliases ->
Types_ unions aliases
-- EXTRACT MODEL, MSG, AND ANY TRANSITIVE DEPENDENCIES
fromMsg :: Types -> Can.Type -> T.DebugMetadata
fromMsg types message =
let
(msgDeps, msgType) =
run (extract message)
(aliases, unions) =
extractTransitive types noDeps msgDeps
in
T.DebugMetadata msgType aliases unions
extractTransitive :: Types -> Deps -> Deps -> ( [T.Alias], [T.Union] )
extractTransitive types (Deps seenAliases seenUnions) (Deps nextAliases nextUnions) =
let
aliases = Set.difference nextAliases seenAliases
unions = Set.difference nextUnions seenUnions
in
if Set.null aliases && Set.null unions then
( [], [] )
else
let
(newDeps, result) =
run $
(,)
<$> traverse (extractAlias types) (Set.toList aliases)
<*> traverse (extractUnion types) (Set.toList unions)
oldDeps =
Deps (Set.union seenAliases nextAliases) (Set.union seenUnions nextUnions)
remainingResult =
extractTransitive types oldDeps newDeps
in
mappend result remainingResult
extractAlias :: Types -> Opt.Global -> Extractor T.Alias
extractAlias (Types dict) (Opt.Global home name) =
let
(Can.Alias args aliasType) = _alias_info (dict ! home) ! name
in
T.Alias (toPublicName home name) args <$> extract aliasType
extractUnion :: Types -> Opt.Global -> Extractor T.Union
extractUnion (Types dict) (Opt.Global home name) =
if name == Name.list && home == ModuleName.list
then return $ T.Union (toPublicName home name) ["a"] []
else
let
pname = toPublicName home name
(Can.Union vars ctors _ _) = _union_info (dict ! home) ! name
in
T.Union pname vars <$> traverse extractCtor ctors
extractCtor :: Can.Ctor -> Extractor (Name.Name, [T.Type])
extractCtor (Can.Ctor ctor _ _ args) =
(,) ctor <$> traverse extract args
DEPS
data Deps =
Deps
{ _aliases :: Set.Set Opt.Global
, _unions :: Set.Set Opt.Global
}
{-# NOINLINE noDeps #-}
noDeps :: Deps
noDeps =
Deps Set.empty Set.empty
-- EXTRACTOR
newtype Extractor a =
Extractor (
forall result.
Set.Set Opt.Global
-> Set.Set Opt.Global
-> (Set.Set Opt.Global -> Set.Set Opt.Global -> a -> result)
-> result
)
run :: Extractor a -> (Deps, a)
run (Extractor k) =
k Set.empty Set.empty $ \aliases unions value ->
( Deps aliases unions, value )
addAlias :: Opt.Global -> a -> Extractor a
addAlias alias value =
Extractor $ \aliases unions ok ->
ok (Set.insert alias aliases) unions value
addUnion :: Opt.Global -> a -> Extractor a
addUnion union value =
Extractor $ \aliases unions ok ->
ok aliases (Set.insert union unions) value
instance Functor Extractor where
fmap func (Extractor k) =
Extractor $ \aliases unions ok ->
let
ok1 a1 u1 value =
ok a1 u1 (func value)
in
k aliases unions ok1
instance Applicative Extractor where
pure value =
Extractor $ \aliases unions ok ->
ok aliases unions value
(<*>) (Extractor kf) (Extractor kv) =
Extractor $ \aliases unions ok ->
let
ok1 a1 u1 func =
let
ok2 a2 u2 value =
ok a2 u2 (func value)
in
kv a1 u1 ok2
in
kf aliases unions ok1
instance Monad Extractor where
return = pure
(>>=) (Extractor ka) callback =
Extractor $ \aliases unions ok ->
let
ok1 a1 u1 value =
case callback value of
Extractor kb -> kb a1 u1 ok
in
ka aliases unions ok1
| null | https://raw.githubusercontent.com/sebsheep/elm2node/602a64f48e39edcdfa6d99793cc2827b677d650d/compiler/src/Elm/Compiler/Type/Extract.hs | haskell | EXTRACTION
.
PERF profile Opt.Global representation
current representation needs less allocation
but maybe the lookup is much worse
EXTRACT MODEL, MSG, AND ANY TRANSITIVE DEPENDENCIES
# NOINLINE noDeps #
EXTRACTOR | # OPTIONS_GHC -Wall #
# LANGUAGE BangPatterns , OverloadedStrings , Rank2Types #
module Elm.Compiler.Type.Extract
( fromAnnotation
, fromType
, Types(..)
, mergeMany
, merge
, fromInterface
, fromDependencyInterface
, fromMsg
)
where
import Data.Map ((!))
import qualified Data.Map as Map
import qualified Data.Maybe as Maybe
import qualified Data.Name as Name
import qualified Data.Set as Set
import qualified AST.Canonical as Can
import qualified AST.Optimized as Opt
import qualified AST.Utils.Type as Type
import qualified Elm.Compiler.Type as T
import qualified Elm.Interface as I
import qualified Elm.ModuleName as ModuleName
fromAnnotation :: Can.Annotation -> T.Type
fromAnnotation (Can.Forall _ astType) =
fromType astType
fromType :: Can.Type -> T.Type
fromType astType =
snd (run (extract astType))
extract :: Can.Type -> Extractor T.Type
extract astType =
case astType of
Can.TLambda arg result ->
T.Lambda
<$> extract arg
<*> extract result
Can.TVar x ->
pure (T.Var x)
Can.TType home name args ->
addUnion (Opt.Global home name) (T.Type (toPublicName home name))
<*> traverse extract args
Can.TRecord fields ext ->
do efields <- traverse (traverse extract) (Can.fieldsToList fields)
pure (T.Record efields ext)
Can.TUnit ->
pure T.Unit
Can.TTuple a b maybeC ->
T.Tuple
<$> extract a
<*> extract b
<*> traverse extract (Maybe.maybeToList maybeC)
Can.TAlias home name args aliasType ->
do addAlias (Opt.Global home name) ()
_ <- extract (Type.dealias args aliasType)
T.Type (toPublicName home name)
<$> traverse (extract . snd) args
toPublicName :: ModuleName.Canonical -> Name.Name -> Name.Name
toPublicName (ModuleName.Canonical _ home) name =
TRANSITIVELY AVAILABLE TYPES
newtype Types =
Types (Map.Map ModuleName.Canonical Types_)
data Types_ =
Types_
{ _union_info :: Map.Map Name.Name Can.Union
, _alias_info :: Map.Map Name.Name Can.Alias
}
mergeMany :: [Types] -> Types
mergeMany listOfTypes =
case listOfTypes of
[] -> Types Map.empty
t:ts -> foldr merge t ts
merge :: Types -> Types -> Types
merge (Types types1) (Types types2) =
Types (Map.union types1 types2)
fromInterface :: ModuleName.Raw -> I.Interface -> Types
fromInterface name (I.Interface pkg _ unions aliases _) =
Types $ Map.singleton (ModuleName.Canonical pkg name) $
Types_ (Map.map I.extractUnion unions) (Map.map I.extractAlias aliases)
fromDependencyInterface :: ModuleName.Canonical -> I.DependencyInterface -> Types
fromDependencyInterface home di =
Types $ Map.singleton home $
case di of
I.Public (I.Interface _ _ unions aliases _) ->
Types_ (Map.map I.extractUnion unions) (Map.map I.extractAlias aliases)
I.Private _ unions aliases ->
Types_ unions aliases
fromMsg :: Types -> Can.Type -> T.DebugMetadata
fromMsg types message =
let
(msgDeps, msgType) =
run (extract message)
(aliases, unions) =
extractTransitive types noDeps msgDeps
in
T.DebugMetadata msgType aliases unions
extractTransitive :: Types -> Deps -> Deps -> ( [T.Alias], [T.Union] )
extractTransitive types (Deps seenAliases seenUnions) (Deps nextAliases nextUnions) =
let
aliases = Set.difference nextAliases seenAliases
unions = Set.difference nextUnions seenUnions
in
if Set.null aliases && Set.null unions then
( [], [] )
else
let
(newDeps, result) =
run $
(,)
<$> traverse (extractAlias types) (Set.toList aliases)
<*> traverse (extractUnion types) (Set.toList unions)
oldDeps =
Deps (Set.union seenAliases nextAliases) (Set.union seenUnions nextUnions)
remainingResult =
extractTransitive types oldDeps newDeps
in
mappend result remainingResult
extractAlias :: Types -> Opt.Global -> Extractor T.Alias
extractAlias (Types dict) (Opt.Global home name) =
let
(Can.Alias args aliasType) = _alias_info (dict ! home) ! name
in
T.Alias (toPublicName home name) args <$> extract aliasType
extractUnion :: Types -> Opt.Global -> Extractor T.Union
extractUnion (Types dict) (Opt.Global home name) =
if name == Name.list && home == ModuleName.list
then return $ T.Union (toPublicName home name) ["a"] []
else
let
pname = toPublicName home name
(Can.Union vars ctors _ _) = _union_info (dict ! home) ! name
in
T.Union pname vars <$> traverse extractCtor ctors
extractCtor :: Can.Ctor -> Extractor (Name.Name, [T.Type])
extractCtor (Can.Ctor ctor _ _ args) =
(,) ctor <$> traverse extract args
DEPS
data Deps =
Deps
{ _aliases :: Set.Set Opt.Global
, _unions :: Set.Set Opt.Global
}
noDeps :: Deps
noDeps =
Deps Set.empty Set.empty
newtype Extractor a =
Extractor (
forall result.
Set.Set Opt.Global
-> Set.Set Opt.Global
-> (Set.Set Opt.Global -> Set.Set Opt.Global -> a -> result)
-> result
)
run :: Extractor a -> (Deps, a)
run (Extractor k) =
k Set.empty Set.empty $ \aliases unions value ->
( Deps aliases unions, value )
addAlias :: Opt.Global -> a -> Extractor a
addAlias alias value =
Extractor $ \aliases unions ok ->
ok (Set.insert alias aliases) unions value
addUnion :: Opt.Global -> a -> Extractor a
addUnion union value =
Extractor $ \aliases unions ok ->
ok aliases (Set.insert union unions) value
instance Functor Extractor where
fmap func (Extractor k) =
Extractor $ \aliases unions ok ->
let
ok1 a1 u1 value =
ok a1 u1 (func value)
in
k aliases unions ok1
instance Applicative Extractor where
pure value =
Extractor $ \aliases unions ok ->
ok aliases unions value
(<*>) (Extractor kf) (Extractor kv) =
Extractor $ \aliases unions ok ->
let
ok1 a1 u1 func =
let
ok2 a2 u2 value =
ok a2 u2 (func value)
in
kv a1 u1 ok2
in
kf aliases unions ok1
instance Monad Extractor where
return = pure
(>>=) (Extractor ka) callback =
Extractor $ \aliases unions ok ->
let
ok1 a1 u1 value =
case callback value of
Extractor kb -> kb a1 u1 ok
in
ka aliases unions ok1
|
3cc1eb09f38f4a71608e2a61bb89961ad0f182760304deceeeb859728050c385 | janestreet/core_profiler | fstats.ml | * This module is basically copied straight from [ . ] , however :
- [ decay ] removed ( to avoid Option.value branch in [ update_in_place ] )
- [ update_in_place ] optimised so that it does n't allocate ( see below )
This copy can be killed when the original is available publicly .
- [decay] removed (to avoid Option.value branch in [update_in_place])
- [update_in_place] optimised so that it doesn't allocate (see below)
This copy can be killed when the original is available publicly. *)
open Core
open Poly
type t = {
(* Note: we keep samples as a float instead of an int so that all floats in the record
are kept unboxed. *)
mutable samples : float; (* sum of sample^0 *)
sum of sample^1
mutable sqsum: float; (* sum of sample^2 *)
The naive algorithm of ( sqsum - sum^2 ) exhibits catastrophic cancellation ,
so we use an alternative algorithm that keeps a running total of the variance
and gets much better numerical precision .
See " Weighted incremental algorithm " and " Parallel algorithm " at
so we use an alternative algorithm that keeps a running total of the variance
and gets much better numerical precision.
See "Weighted incremental algorithm" and "Parallel algorithm" at
*)
mutable varsum : float; (* sum of running_variance *)
mutable max : float; (* largest sample *)
mutable min : float; (* smallest sample *)
}
let create () =
{ sum = 0.
; sqsum = 0.
; varsum = 0.
; samples = 0.
; max = Float.neg_infinity
; min = Float.infinity
}
let samples t = Float.to_int t.samples
let total t = t.sum
let min t = t.min
let max t = t.max
let mean t = t.sum /. t.samples
let var t =
if t.samples <= 1.
then Float.nan
else Float.max 0. ((t.varsum /. t.samples) *. (t.samples /. (t.samples -. 1.)))
let stdev t = sqrt (var t)
we need [ update_in_place ] to be inlined in order to eliminate the float allocation at
the callsites where we have an int to hand instead of a float .
the callsites where we have an int to hand instead of a float. *)
let[@inline] update_in_place t value =
if t.samples <= 0.
then begin
(* [Rstats.safe_mean] allocates, even after it's been inlined.
It seems that in general, expressions of form
[if expr then some_float else other_float]
cause allocation, even in cases where it is unnecessary.
So, I handle the [t.samples <= 0] separately, so that [safe_mean] is
not needed. *)
t.samples <- 1.;
t.sum <- value;
t.sqsum <- value *. value;
t.max <- value;
t.min <- value;
t.varsum <- 0.
end
else begin
(* [Option.value decay ~default_decay:...] suffers the same problem. *)
let old_mean = mean t in
t.samples <- t.samples +. 1.;
t.sum <- t.sum +. value;
t.sqsum <- t.sqsum +. value *. value;
(* [Float.max] suffers the same problem as above and causes allocation even
after it's been inlined. *)
if value > t.max then t.max <- value;
if value < t.min then t.min <- value;
let new_mean = mean t in
(* Numerically stable method for computing variance. On wikipedia page:
# Alternatively, "M2 = M2 + weight * delta * (x−mean)" *)
t.varsum <- t.varsum +. (value -. old_mean) *. (value -. new_mean)
end
let copy t = { t with sum = t.sum }
let%test_module "Fstats" = (module struct
let data =
[|198215.02492520443; 28715.0284862834887; 434619.094190333097; 800678.330169520807
; 200186.54372400351; 137503.258498826239; 566498.60534151; 549219.475914424169
; 780230.679805230233; 712168.552241884521; 512045.175157501479
; 606136.851468109642; 368469.614224194782; 213372.100528741139
; 487759.722525204881; 545327.353652161313; 565759.781024767901
; 227130.713477647136; 14526.9831253076572; 87168.3680568782729
; 317822.864412072755; 328746.783061697963; 446049.964182617899
; 451270.307992378599; 822506.373272555647; 947812.349198815064
; 563960.680863914196; 73057.735605084; 475515.868111219897; 79103.4644861585693
; 61060.2804668050376; 821842.058883985155; 162383.377334053017
; 151034.116153264389; 357173.747924180352; 417551.514353964303
; 758440.286012416356; 480593.8769512953; 109763.567296876703
; 154961.955787061859; 50902.5130336880611; 273048.455977052858
; 673477.375928052119; 790059.438551203464; 817997.314074333408
; 280563.866073483776; 858501.471649471; 908670.036968784756; 843433.873243822
; 717604.357264731894; 257166.21131005112; 587352.255237122881; 679376.01970596856
; 93196.2210949568544; 343319.788271304453; 757660.644341278588
; 403271.576879935688; 974099.221967302146; 964390.741413959884
; 807222.013931629714; 670868.156459537; 656612.853921575472; 545398.269980843412|]
let stats = create ()
let () =
Array.iter data ~f:(update_in_place stats)
let%test "samples" = samples stats = 63
let%test "min" = min stats = 14526.9831253076572
let%test "max" = max stats = 974099.221967302146
let%test "total" = total stats = 29970575.106168244
let%test "mean" = mean stats = 475723.414383622934
let%test "var" = var stats = 78826737609.7966156
let%test "stdev" = stdev stats = 280760.997308736958
let%test_unit "copy" =
let stats2 = copy stats in
update_in_place stats2 0.;
[%test_eq: int] (samples stats) 63;
[%test_eq: int] (samples stats2) 64
end)
let%bench_module "Fstats" = (module struct
let stats = create ()
let%bench "update_in_place" = update_in_place stats 5.
end)
| null | https://raw.githubusercontent.com/janestreet/core_profiler/3d1c0e61df848f5f25f78d64beea92b619b6d5d9/src/fstats.ml | ocaml | Note: we keep samples as a float instead of an int so that all floats in the record
are kept unboxed.
sum of sample^0
sum of sample^2
sum of running_variance
largest sample
smallest sample
[Rstats.safe_mean] allocates, even after it's been inlined.
It seems that in general, expressions of form
[if expr then some_float else other_float]
cause allocation, even in cases where it is unnecessary.
So, I handle the [t.samples <= 0] separately, so that [safe_mean] is
not needed.
[Option.value decay ~default_decay:...] suffers the same problem.
[Float.max] suffers the same problem as above and causes allocation even
after it's been inlined.
Numerically stable method for computing variance. On wikipedia page:
# Alternatively, "M2 = M2 + weight * delta * (x−mean)" | * This module is basically copied straight from [ . ] , however :
- [ decay ] removed ( to avoid Option.value branch in [ update_in_place ] )
- [ update_in_place ] optimised so that it does n't allocate ( see below )
This copy can be killed when the original is available publicly .
- [decay] removed (to avoid Option.value branch in [update_in_place])
- [update_in_place] optimised so that it doesn't allocate (see below)
This copy can be killed when the original is available publicly. *)
open Core
open Poly
type t = {
sum of sample^1
The naive algorithm of ( sqsum - sum^2 ) exhibits catastrophic cancellation ,
so we use an alternative algorithm that keeps a running total of the variance
and gets much better numerical precision .
See " Weighted incremental algorithm " and " Parallel algorithm " at
so we use an alternative algorithm that keeps a running total of the variance
and gets much better numerical precision.
See "Weighted incremental algorithm" and "Parallel algorithm" at
*)
}
let create () =
{ sum = 0.
; sqsum = 0.
; varsum = 0.
; samples = 0.
; max = Float.neg_infinity
; min = Float.infinity
}
let samples t = Float.to_int t.samples
let total t = t.sum
let min t = t.min
let max t = t.max
let mean t = t.sum /. t.samples
let var t =
if t.samples <= 1.
then Float.nan
else Float.max 0. ((t.varsum /. t.samples) *. (t.samples /. (t.samples -. 1.)))
let stdev t = sqrt (var t)
we need [ update_in_place ] to be inlined in order to eliminate the float allocation at
the callsites where we have an int to hand instead of a float .
the callsites where we have an int to hand instead of a float. *)
let[@inline] update_in_place t value =
if t.samples <= 0.
then begin
t.samples <- 1.;
t.sum <- value;
t.sqsum <- value *. value;
t.max <- value;
t.min <- value;
t.varsum <- 0.
end
else begin
let old_mean = mean t in
t.samples <- t.samples +. 1.;
t.sum <- t.sum +. value;
t.sqsum <- t.sqsum +. value *. value;
if value > t.max then t.max <- value;
if value < t.min then t.min <- value;
let new_mean = mean t in
t.varsum <- t.varsum +. (value -. old_mean) *. (value -. new_mean)
end
let copy t = { t with sum = t.sum }
let%test_module "Fstats" = (module struct
let data =
[|198215.02492520443; 28715.0284862834887; 434619.094190333097; 800678.330169520807
; 200186.54372400351; 137503.258498826239; 566498.60534151; 549219.475914424169
; 780230.679805230233; 712168.552241884521; 512045.175157501479
; 606136.851468109642; 368469.614224194782; 213372.100528741139
; 487759.722525204881; 545327.353652161313; 565759.781024767901
; 227130.713477647136; 14526.9831253076572; 87168.3680568782729
; 317822.864412072755; 328746.783061697963; 446049.964182617899
; 451270.307992378599; 822506.373272555647; 947812.349198815064
; 563960.680863914196; 73057.735605084; 475515.868111219897; 79103.4644861585693
; 61060.2804668050376; 821842.058883985155; 162383.377334053017
; 151034.116153264389; 357173.747924180352; 417551.514353964303
; 758440.286012416356; 480593.8769512953; 109763.567296876703
; 154961.955787061859; 50902.5130336880611; 273048.455977052858
; 673477.375928052119; 790059.438551203464; 817997.314074333408
; 280563.866073483776; 858501.471649471; 908670.036968784756; 843433.873243822
; 717604.357264731894; 257166.21131005112; 587352.255237122881; 679376.01970596856
; 93196.2210949568544; 343319.788271304453; 757660.644341278588
; 403271.576879935688; 974099.221967302146; 964390.741413959884
; 807222.013931629714; 670868.156459537; 656612.853921575472; 545398.269980843412|]
let stats = create ()
let () =
Array.iter data ~f:(update_in_place stats)
let%test "samples" = samples stats = 63
let%test "min" = min stats = 14526.9831253076572
let%test "max" = max stats = 974099.221967302146
let%test "total" = total stats = 29970575.106168244
let%test "mean" = mean stats = 475723.414383622934
let%test "var" = var stats = 78826737609.7966156
let%test "stdev" = stdev stats = 280760.997308736958
let%test_unit "copy" =
let stats2 = copy stats in
update_in_place stats2 0.;
[%test_eq: int] (samples stats) 63;
[%test_eq: int] (samples stats2) 64
end)
let%bench_module "Fstats" = (module struct
let stats = create ()
let%bench "update_in_place" = update_in_place stats 5.
end)
|
ec1622b9e64b43a40b1e0c40781f628b59c4b8b4f4ae044649d626d4ff4d2fd4 | kblake/erlang-chat-demo | PAGE.erl | -module (PAGE).
-include_lib ("nitrogen/include/wf.inc").
-compile(export_all).
main() ->
#template { file="./wwwroot/template.html"}.
title() ->
"PAGE".
body() ->
#label{text="PAGE body."}.
event(_) -> ok. | null | https://raw.githubusercontent.com/kblake/erlang-chat-demo/6fd2fce12f2e059e25a24c9a84169b088710edaf/apps/nitrogen/priv/skel/PAGE.erl | erlang | -module (PAGE).
-include_lib ("nitrogen/include/wf.inc").
-compile(export_all).
main() ->
#template { file="./wwwroot/template.html"}.
title() ->
"PAGE".
body() ->
#label{text="PAGE body."}.
event(_) -> ok. | |
fcd90fbc338670e1f0dbbe20016a4260b4b954ae6403e30c1e64554f59594f41 | lingnand/VIMonad | ThreeColumns.hs | # LANGUAGE FlexibleInstances , MultiParamTypeClasses #
-----------------------------------------------------------------------------
-- |
-- Module : XMonad.Layout.ThreeColumns
Copyright : ( c ) < >
-- License : BSD3-style (see LICENSE)
--
-- Maintainer : ?
-- Stability : unstable
-- Portability : unportable
--
A layout similar to tall but with three columns . With 2560x1600 pixels this
layout can be used for a huge main window and up to six reasonable sized
-- slave windows.
-----------------------------------------------------------------------------
module XMonad.Layout.ThreeColumns (
-- * Usage
-- $usage
-- * Screenshots
-- $screenshot
ThreeCol(..)
) where
import XMonad
import qualified XMonad.StackSet as W
import Data.Ratio
import Control.Monad
-- $usage
-- You can use this module with the following in your @~\/.xmonad\/xmonad.hs@:
--
> import XMonad . Layout . ThreeColumns
--
-- Then edit your @layoutHook@ by adding the ThreeCol layout:
--
> myLayout = ThreeCol 1 ( 3/100 ) ( 1/2 ) ||| ThreeColMid 1 ( 3/100 ) ( 1/2 ) ||| etc ..
-- > main = xmonad def { layoutHook = myLayout }
--
The first argument specifies how many windows initially appear in the main
window . The second argument argument specifies the amount to resize while
resizing and the third argument specifies the initial size of the columns .
-- A positive size designates the fraction of the screen that the main window
-- should occupy, but if the size is negative the absolute value designates the
-- fraction a slave column should occupy. If both slave columns are visible,
-- they always occupy the same amount of space.
--
-- The ThreeColMid variant places the main window between the slave columns.
--
-- For more detailed instructions on editing the layoutHook see:
--
-- "XMonad.Doc.Extending#Editing_the_layout_hook"
-- $screenshot
-- <<-otto.de/xmonad/ThreeColumnsMiddle.png>>
-- | Arguments are nmaster, delta, fraction
data ThreeCol a = ThreeColMid { threeColNMaster :: !Int, threeColDelta :: !Rational, threeColFrac :: !Rational}
| ThreeCol { threeColNMaster :: !Int, threeColDelta :: !Rational, threeColFrac :: !Rational}
deriving (Show,Read)
instance LayoutClass ThreeCol a where
pureLayout (ThreeCol n _ f) r = doL False n f r
pureLayout (ThreeColMid n _ f) r = doL True n f r
handleMessage l m =
return $ msum [fmap resize (fromMessage m)
,fmap incmastern (fromMessage m)]
where resize Shrink = l { threeColFrac = max (-0.5) $ f-d }
resize Expand = l { threeColFrac = min 1 $ f+d }
incmastern (IncMasterN x) = l { threeColNMaster = max 0 (n+x) }
n = threeColNMaster l
d = threeColDelta l
f = threeColFrac l
description _ = "ThreeCol"
doL :: Bool-> Int-> Rational-> Rectangle-> W.Stack a-> [(a, Rectangle)]
doL m n f r = ap zip (tile3 m f r n . length) . W.integrate
| . Compute window positions using 3 panes
tile3 :: Bool -> Rational -> Rectangle -> Int -> Int -> [Rectangle]
tile3 middle f r nmaster n
| n <= nmaster || nmaster == 0 = splitVertically n r
| n <= nmaster+1 = splitVertically nmaster s1 ++ splitVertically (n-nmaster) s2
| otherwise = splitVertically nmaster r1 ++ splitVertically nslave1 r2 ++ splitVertically nslave2 r3
where (r1, r2, r3) = split3HorizontallyBy middle (if f<0 then 1+2*f else f) r
(s1, s2) = splitHorizontallyBy (if f<0 then 1+f else f) r
nslave = (n - nmaster)
nslave1 = ceiling (nslave % 2)
nslave2 = (n - nmaster - nslave1)
split3HorizontallyBy :: Bool -> Rational -> Rectangle -> (Rectangle, Rectangle, Rectangle)
split3HorizontallyBy middle f (Rectangle sx sy sw sh) =
if middle
then ( Rectangle (sx + fromIntegral r3w) sy r1w sh
, Rectangle (sx + fromIntegral r3w + fromIntegral r1w) sy r2w sh
, Rectangle sx sy r3w sh )
else ( Rectangle sx sy r1w sh
, Rectangle (sx + fromIntegral r1w) sy r2w sh
, Rectangle (sx + fromIntegral r1w + fromIntegral r2w) sy r3w sh )
where r1w = ceiling $ fromIntegral sw * f
r2w = ceiling ( (sw - r1w) % 2 )
r3w = sw - r1w - r2w
| null | https://raw.githubusercontent.com/lingnand/VIMonad/048e419fc4ef57a5235dbaeef8890faf6956b574/XMonadContrib/XMonad/Layout/ThreeColumns.hs | haskell | ---------------------------------------------------------------------------
|
Module : XMonad.Layout.ThreeColumns
License : BSD3-style (see LICENSE)
Maintainer : ?
Stability : unstable
Portability : unportable
slave windows.
---------------------------------------------------------------------------
* Usage
$usage
* Screenshots
$screenshot
$usage
You can use this module with the following in your @~\/.xmonad\/xmonad.hs@:
Then edit your @layoutHook@ by adding the ThreeCol layout:
> main = xmonad def { layoutHook = myLayout }
A positive size designates the fraction of the screen that the main window
should occupy, but if the size is negative the absolute value designates the
fraction a slave column should occupy. If both slave columns are visible,
they always occupy the same amount of space.
The ThreeColMid variant places the main window between the slave columns.
For more detailed instructions on editing the layoutHook see:
"XMonad.Doc.Extending#Editing_the_layout_hook"
$screenshot
<<-otto.de/xmonad/ThreeColumnsMiddle.png>>
| Arguments are nmaster, delta, fraction | # LANGUAGE FlexibleInstances , MultiParamTypeClasses #
Copyright : ( c ) < >
A layout similar to tall but with three columns . With 2560x1600 pixels this
layout can be used for a huge main window and up to six reasonable sized
module XMonad.Layout.ThreeColumns (
ThreeCol(..)
) where
import XMonad
import qualified XMonad.StackSet as W
import Data.Ratio
import Control.Monad
> import XMonad . Layout . ThreeColumns
> myLayout = ThreeCol 1 ( 3/100 ) ( 1/2 ) ||| ThreeColMid 1 ( 3/100 ) ( 1/2 ) ||| etc ..
The first argument specifies how many windows initially appear in the main
window . The second argument argument specifies the amount to resize while
resizing and the third argument specifies the initial size of the columns .
data ThreeCol a = ThreeColMid { threeColNMaster :: !Int, threeColDelta :: !Rational, threeColFrac :: !Rational}
| ThreeCol { threeColNMaster :: !Int, threeColDelta :: !Rational, threeColFrac :: !Rational}
deriving (Show,Read)
instance LayoutClass ThreeCol a where
pureLayout (ThreeCol n _ f) r = doL False n f r
pureLayout (ThreeColMid n _ f) r = doL True n f r
handleMessage l m =
return $ msum [fmap resize (fromMessage m)
,fmap incmastern (fromMessage m)]
where resize Shrink = l { threeColFrac = max (-0.5) $ f-d }
resize Expand = l { threeColFrac = min 1 $ f+d }
incmastern (IncMasterN x) = l { threeColNMaster = max 0 (n+x) }
n = threeColNMaster l
d = threeColDelta l
f = threeColFrac l
description _ = "ThreeCol"
doL :: Bool-> Int-> Rational-> Rectangle-> W.Stack a-> [(a, Rectangle)]
doL m n f r = ap zip (tile3 m f r n . length) . W.integrate
| . Compute window positions using 3 panes
tile3 :: Bool -> Rational -> Rectangle -> Int -> Int -> [Rectangle]
tile3 middle f r nmaster n
| n <= nmaster || nmaster == 0 = splitVertically n r
| n <= nmaster+1 = splitVertically nmaster s1 ++ splitVertically (n-nmaster) s2
| otherwise = splitVertically nmaster r1 ++ splitVertically nslave1 r2 ++ splitVertically nslave2 r3
where (r1, r2, r3) = split3HorizontallyBy middle (if f<0 then 1+2*f else f) r
(s1, s2) = splitHorizontallyBy (if f<0 then 1+f else f) r
nslave = (n - nmaster)
nslave1 = ceiling (nslave % 2)
nslave2 = (n - nmaster - nslave1)
split3HorizontallyBy :: Bool -> Rational -> Rectangle -> (Rectangle, Rectangle, Rectangle)
split3HorizontallyBy middle f (Rectangle sx sy sw sh) =
if middle
then ( Rectangle (sx + fromIntegral r3w) sy r1w sh
, Rectangle (sx + fromIntegral r3w + fromIntegral r1w) sy r2w sh
, Rectangle sx sy r3w sh )
else ( Rectangle sx sy r1w sh
, Rectangle (sx + fromIntegral r1w) sy r2w sh
, Rectangle (sx + fromIntegral r1w + fromIntegral r2w) sy r3w sh )
where r1w = ceiling $ fromIntegral sw * f
r2w = ceiling ( (sw - r1w) % 2 )
r3w = sw - r1w - r2w
|
f745bf051c36f866be0c2d868815fe2d1cecc6db705b8d13aced5073256feaba | GaloisInc/pate | BlockPairDetail.hs | {-# LANGUAGE RankNTypes #-}
module Pate.Interactive.Render.BlockPairDetail (
renderBlockPairDetail
) where
import Control.Lens ( (^.) )
import qualified Control.Lens as L
import qualified Data.Foldable as F
import Data.Maybe ( fromMaybe )
import qualified Data.String.UTF8 as UTF8
import Graphics.UI.Threepenny ( (#), (#+), (#.) )
import qualified Graphics.UI.Threepenny as TP
import qualified Language.C as LC
import qualified Data.Macaw.BinaryLoader as MBL
import qualified Data.Macaw.CFG as MC
import qualified Pate.Arch as PAr
import qualified Pate.Block as PB
import qualified Pate.Binary as PB
import qualified Pate.Event as PE
import qualified Pate.Loader.ELF as PLE
import qualified Pate.Proof.Instances as PFI
import qualified Pate.Proof as PPr
import qualified Pate.Interactive.Render.SliceGraph as IRS
import qualified Pate.Interactive.State as IS
renderCounterexample :: PE.EquivalenceResult arch -> [TP.UI TP.Element]
renderCounterexample er =
case er of
PE.Equivalent -> []
PE.Inconclusive -> []
PE.Inequivalent ir' -> PPr.withIneqResult ir' $ \ir ->
[TP.ul #+ [ TP.li #+ [ TP.string ("Reason: " ++ show (PPr.ineqReason ir))
, TP.pre #+ [TP.string (PFI.ppInequivalencePreRegs ir')]
]
]
]
-- | Note that we always look up the original address because we key the
-- function name off of that... we could do better
renderSource :: (PAr.ValidArch arch)
=> IS.State arch
-> (IS.SourcePair LC.CTranslUnit -> LC.CTranslUnit)
-> L.Getter (IS.State arch) (Maybe (PLE.LoadedELF arch))
-> MC.MemAddr (MC.ArchAddrWidth arch)
-> [TP.UI TP.Element]
renderSource st getSource binL addr = fromMaybe [] $ do
lelf <- st ^. binL
bname <- MBL.symbolFor (PLE.loadedBinary lelf) addr
let sname = UTF8.toString (UTF8.fromRep bname)
LC.CTranslUnit decls _ <- getSource <$> st ^. IS.sources
fundef <- F.find (matchingFunctionName sname) decls
return [ TP.code #+ [ TP.pre # TP.set TP.text (show (LC.pretty fundef)) #. "source-listing" ] ]
-- | Find the declaration matching the given function name
matchingFunctionName :: String -> LC.CExternalDeclaration LC.NodeInfo -> Bool
matchingFunctionName sname def =
case def of
LC.CDeclExt {} -> False
LC.CAsmExt {} -> False
LC.CFDefExt (LC.CFunDef _declspecs declr _decls _stmts _annot) ->
case declr of
LC.CDeclr (Just ident) _ _ _ _ -> LC.identToString ident == sname
LC.CDeclr Nothing _ _ _ _ -> False
renderFunctionName :: (PAr.ValidArch arch)
=> IS.State arch
-> MC.MemAddr (MC.ArchAddrWidth arch)
-> [TP.UI TP.Element]
renderFunctionName st origAddr = fromMaybe [] $ do
lelf <- st ^. IS.originalBinary
bname <- MBL.symbolFor (PLE.loadedBinary lelf) origAddr
let sname = UTF8.toString (UTF8.fromRep bname)
return [TP.string ("(Function: " ++ sname ++ ")")]
renderAddr :: (Show a) => String -> a -> TP.UI TP.Element
renderAddr label addr = TP.string (label ++ " (" ++ show addr ++ ")")
renderBlockPairDetail
:: (PAr.ValidArch arch)
=> IS.State arch
-> PE.Blocks arch PB.Original
-> PE.Blocks arch PB.Patched
-> Maybe (PE.EquivalenceResult arch)
-> TP.UI (TP.Element, TP.UI (), TP.UI ())
renderBlockPairDetail st o@(PE.Blocks _ blkO _opbs) p@(PE.Blocks _ blkP _ppbs) res = do
g <- TP.grid [ maybe [] renderCounterexample res
, concat [[renderAddr "Original Code" origAddr, renderAddr "Patched Code" patchedAddr], renderFunctionName st origAddr]
, concat [ renderSource st IS.originalSource IS.originalBinary origAddr
, renderSource st IS.patchedSource IS.patchedBinary patchedAddr
]
, [origGraphDiv, patchedGraphDiv]
]
return (g, origGraphSetup, patchedGraphSetup)
where
origAddr = PB.blockMemAddr blkO
patchedAddr = PB.blockMemAddr blkP
(origGraphDiv, origGraphSetup) = IRS.renderSliceGraph "original-slice-graph" o
(patchedGraphDiv, patchedGraphSetup) = IRS.renderSliceGraph "patched-slice-graph" p
| null | https://raw.githubusercontent.com/GaloisInc/pate/af72348c2c70b0ce5c28d10afa154ee33a9c3e08/src/Pate/Interactive/Render/BlockPairDetail.hs | haskell | # LANGUAGE RankNTypes #
| Note that we always look up the original address because we key the
function name off of that... we could do better
| Find the declaration matching the given function name | module Pate.Interactive.Render.BlockPairDetail (
renderBlockPairDetail
) where
import Control.Lens ( (^.) )
import qualified Control.Lens as L
import qualified Data.Foldable as F
import Data.Maybe ( fromMaybe )
import qualified Data.String.UTF8 as UTF8
import Graphics.UI.Threepenny ( (#), (#+), (#.) )
import qualified Graphics.UI.Threepenny as TP
import qualified Language.C as LC
import qualified Data.Macaw.BinaryLoader as MBL
import qualified Data.Macaw.CFG as MC
import qualified Pate.Arch as PAr
import qualified Pate.Block as PB
import qualified Pate.Binary as PB
import qualified Pate.Event as PE
import qualified Pate.Loader.ELF as PLE
import qualified Pate.Proof.Instances as PFI
import qualified Pate.Proof as PPr
import qualified Pate.Interactive.Render.SliceGraph as IRS
import qualified Pate.Interactive.State as IS
renderCounterexample :: PE.EquivalenceResult arch -> [TP.UI TP.Element]
renderCounterexample er =
case er of
PE.Equivalent -> []
PE.Inconclusive -> []
PE.Inequivalent ir' -> PPr.withIneqResult ir' $ \ir ->
[TP.ul #+ [ TP.li #+ [ TP.string ("Reason: " ++ show (PPr.ineqReason ir))
, TP.pre #+ [TP.string (PFI.ppInequivalencePreRegs ir')]
]
]
]
renderSource :: (PAr.ValidArch arch)
=> IS.State arch
-> (IS.SourcePair LC.CTranslUnit -> LC.CTranslUnit)
-> L.Getter (IS.State arch) (Maybe (PLE.LoadedELF arch))
-> MC.MemAddr (MC.ArchAddrWidth arch)
-> [TP.UI TP.Element]
renderSource st getSource binL addr = fromMaybe [] $ do
lelf <- st ^. binL
bname <- MBL.symbolFor (PLE.loadedBinary lelf) addr
let sname = UTF8.toString (UTF8.fromRep bname)
LC.CTranslUnit decls _ <- getSource <$> st ^. IS.sources
fundef <- F.find (matchingFunctionName sname) decls
return [ TP.code #+ [ TP.pre # TP.set TP.text (show (LC.pretty fundef)) #. "source-listing" ] ]
matchingFunctionName :: String -> LC.CExternalDeclaration LC.NodeInfo -> Bool
matchingFunctionName sname def =
case def of
LC.CDeclExt {} -> False
LC.CAsmExt {} -> False
LC.CFDefExt (LC.CFunDef _declspecs declr _decls _stmts _annot) ->
case declr of
LC.CDeclr (Just ident) _ _ _ _ -> LC.identToString ident == sname
LC.CDeclr Nothing _ _ _ _ -> False
renderFunctionName :: (PAr.ValidArch arch)
=> IS.State arch
-> MC.MemAddr (MC.ArchAddrWidth arch)
-> [TP.UI TP.Element]
renderFunctionName st origAddr = fromMaybe [] $ do
lelf <- st ^. IS.originalBinary
bname <- MBL.symbolFor (PLE.loadedBinary lelf) origAddr
let sname = UTF8.toString (UTF8.fromRep bname)
return [TP.string ("(Function: " ++ sname ++ ")")]
renderAddr :: (Show a) => String -> a -> TP.UI TP.Element
renderAddr label addr = TP.string (label ++ " (" ++ show addr ++ ")")
renderBlockPairDetail
:: (PAr.ValidArch arch)
=> IS.State arch
-> PE.Blocks arch PB.Original
-> PE.Blocks arch PB.Patched
-> Maybe (PE.EquivalenceResult arch)
-> TP.UI (TP.Element, TP.UI (), TP.UI ())
renderBlockPairDetail st o@(PE.Blocks _ blkO _opbs) p@(PE.Blocks _ blkP _ppbs) res = do
g <- TP.grid [ maybe [] renderCounterexample res
, concat [[renderAddr "Original Code" origAddr, renderAddr "Patched Code" patchedAddr], renderFunctionName st origAddr]
, concat [ renderSource st IS.originalSource IS.originalBinary origAddr
, renderSource st IS.patchedSource IS.patchedBinary patchedAddr
]
, [origGraphDiv, patchedGraphDiv]
]
return (g, origGraphSetup, patchedGraphSetup)
where
origAddr = PB.blockMemAddr blkO
patchedAddr = PB.blockMemAddr blkP
(origGraphDiv, origGraphSetup) = IRS.renderSliceGraph "original-slice-graph" o
(patchedGraphDiv, patchedGraphSetup) = IRS.renderSliceGraph "patched-slice-graph" p
|
5bf5f8c02577f688ad81563af455767e68ecf344dd0e2975597de12d7921d9c8 | logseq/logseq | select.cljs | (ns frontend.components.select
"Generic component for fuzzy searching items to select an item. See
select-config to add a new use or select-type for this component. To use the
new select-type, set :ui/open-select to the select-type. See
:graph/open command for an example."
(:require [frontend.modules.shortcut.core :as shortcut]
[frontend.context.i18n :refer [t]]
[frontend.search :as search]
[frontend.state :as state]
[frontend.ui :as ui]
[frontend.util :as util]
[frontend.util.text :as text-util]
[frontend.db :as db]
[rum.core :as rum]
[frontend.config :as config]
[frontend.handler.repo :as repo-handler]
[reitit.frontend.easy :as rfe]))
(rum/defc render-item
[result chosen?]
(if (map? result)
(let [{:keys [id value]} result]
[:div.inline-grid.grid-cols-4.gap-x-4.w-full
{:class (when chosen? "chosen")}
[:span.col-span-3 value]
[:div.col-span-1.justify-end.tip.flex
(when id
[:code.opacity-20.bg-transparent id])]])
[:div.inline-grid.grid-cols-4.gap-x-4.w-full
{:class (when chosen? "chosen")}
[:span.col-span-3 result]]))
(rum/defcs select <
(shortcut/disable-all-shortcuts)
(rum/local "" ::input)
{:will-unmount (fn [state]
(state/set-state! [:ui/open-select] nil)
state)}
[state {:keys [items limit on-chosen empty-placeholder
prompt-key input-default-placeholder close-modal?
extract-fn host-opts on-input input-opts
item-cp transform-fn tap-*input-val]
:or {limit 100
prompt-key :select/default-prompt
empty-placeholder (fn [_t] [:div])
close-modal? true
extract-fn :value}}]
(let [input (::input state)]
(when (fn? tap-*input-val)
(tap-*input-val input))
[:div.cp__select
(merge {:class "cp__select-main"} host-opts)
[:div.input-wrap
[:input.cp__select-input.w-full
(merge {:type "text"
:placeholder (or input-default-placeholder (t prompt-key))
:auto-focus true
:value @input
:on-change (fn [e]
(let [v (util/evalue e)]
(reset! input v)
(and (fn? on-input) (on-input v))))}
input-opts)]]
[:div.item-results-wrap
(ui/auto-complete
(cond-> (search/fuzzy-search items @input :limit limit :extract-fn extract-fn)
(fn? transform-fn)
(transform-fn @input))
{:item-render (or item-cp render-item)
:class "cp__select-results"
:on-chosen (fn [x]
(when close-modal? (state/close-modal!))
(on-chosen x))
:empty-placeholder (empty-placeholder t)})]]))
(defn select-config
"Config that supports multiple types (uses) of this component. To add a new
type, add a key with the value being a map with the following keys:
* :items-fn - fn that returns items with a :value key that are used for the
fuzzy search and selection. Items can have an optional :id and are displayed
lightly for a given item.
* :on-chosen - fn that is given item when it is chosen.
* :empty-placeholder (optional) - fn that returns hiccup html to render if no
matched graphs found.
* :prompt-key (optional) - dictionary keyword that prompts when components is
first open. Defaults to :select/default-prompt."
[]
{:graph-open
{:items-fn (fn []
(->>
(state/get-repos)
(remove (fn [{:keys [url]}]
(or (config/demo-graph? url)
(= url (state/get-current-repo)))))
(map (fn [{:keys [url]}]
{:value (text-util/get-graph-name-from-path
;; TODO: Use helper when a common one is refactored
;; from components.repo
(if (config/local-db? url)
(config/get-local-dir url)
(db/get-repo-path url)))
:id (config/get-repo-dir url)
:graph url}))))
:prompt-key :select.graph/prompt
:on-chosen #(state/pub-event! [:graph/switch (:graph %)])
:empty-placeholder (fn [t]
[:div.px-4.py-2
[:div.mb-2 (t :select.graph/empty-placeholder-description)]
(ui/button
(t :select.graph/add-graph)
:href (rfe/href :repo-add)
:on-click state/close-modal!)])}
:graph-remove
{:items-fn (fn []
(->> (state/get-repos)
(remove (fn [{:keys [url]}]
(config/demo-graph? url)))
(map (fn [{:keys [url] :as original-graph}]
{:value (text-util/get-graph-name-from-path
;; TODO: Use helper when a common one is refactored
;; from components.repo
(if (config/local-db? url)
(config/get-local-dir url)
(db/get-repo-path url)))
:id (config/get-repo-dir url)
:graph url
:original-graph original-graph}))))
:on-chosen #(repo-handler/remove-repo! (:original-graph %))}})
(rum/defc select-modal < rum/reactive
[]
(when-let [select-type (state/sub [:ui/open-select])]
(let [select-type-config (get (select-config) select-type)]
(state/set-modal!
#(select (-> select-type-config
(select-keys [:on-chosen :empty-placeholder :prompt-key])
(assoc :items ((:items-fn select-type-config)))))
{:fullscreen? false
:close-btn? false}))
nil))
| null | https://raw.githubusercontent.com/logseq/logseq/d53ac94bfc019926f85690224deb5f3517b8bb3c/src/main/frontend/components/select.cljs | clojure | TODO: Use helper when a common one is refactored
from components.repo
TODO: Use helper when a common one is refactored
from components.repo | (ns frontend.components.select
"Generic component for fuzzy searching items to select an item. See
select-config to add a new use or select-type for this component. To use the
new select-type, set :ui/open-select to the select-type. See
:graph/open command for an example."
(:require [frontend.modules.shortcut.core :as shortcut]
[frontend.context.i18n :refer [t]]
[frontend.search :as search]
[frontend.state :as state]
[frontend.ui :as ui]
[frontend.util :as util]
[frontend.util.text :as text-util]
[frontend.db :as db]
[rum.core :as rum]
[frontend.config :as config]
[frontend.handler.repo :as repo-handler]
[reitit.frontend.easy :as rfe]))
(rum/defc render-item
[result chosen?]
(if (map? result)
(let [{:keys [id value]} result]
[:div.inline-grid.grid-cols-4.gap-x-4.w-full
{:class (when chosen? "chosen")}
[:span.col-span-3 value]
[:div.col-span-1.justify-end.tip.flex
(when id
[:code.opacity-20.bg-transparent id])]])
[:div.inline-grid.grid-cols-4.gap-x-4.w-full
{:class (when chosen? "chosen")}
[:span.col-span-3 result]]))
(rum/defcs select <
(shortcut/disable-all-shortcuts)
(rum/local "" ::input)
{:will-unmount (fn [state]
(state/set-state! [:ui/open-select] nil)
state)}
[state {:keys [items limit on-chosen empty-placeholder
prompt-key input-default-placeholder close-modal?
extract-fn host-opts on-input input-opts
item-cp transform-fn tap-*input-val]
:or {limit 100
prompt-key :select/default-prompt
empty-placeholder (fn [_t] [:div])
close-modal? true
extract-fn :value}}]
(let [input (::input state)]
(when (fn? tap-*input-val)
(tap-*input-val input))
[:div.cp__select
(merge {:class "cp__select-main"} host-opts)
[:div.input-wrap
[:input.cp__select-input.w-full
(merge {:type "text"
:placeholder (or input-default-placeholder (t prompt-key))
:auto-focus true
:value @input
:on-change (fn [e]
(let [v (util/evalue e)]
(reset! input v)
(and (fn? on-input) (on-input v))))}
input-opts)]]
[:div.item-results-wrap
(ui/auto-complete
(cond-> (search/fuzzy-search items @input :limit limit :extract-fn extract-fn)
(fn? transform-fn)
(transform-fn @input))
{:item-render (or item-cp render-item)
:class "cp__select-results"
:on-chosen (fn [x]
(when close-modal? (state/close-modal!))
(on-chosen x))
:empty-placeholder (empty-placeholder t)})]]))
(defn select-config
"Config that supports multiple types (uses) of this component. To add a new
type, add a key with the value being a map with the following keys:
* :items-fn - fn that returns items with a :value key that are used for the
fuzzy search and selection. Items can have an optional :id and are displayed
lightly for a given item.
* :on-chosen - fn that is given item when it is chosen.
* :empty-placeholder (optional) - fn that returns hiccup html to render if no
matched graphs found.
* :prompt-key (optional) - dictionary keyword that prompts when components is
first open. Defaults to :select/default-prompt."
[]
{:graph-open
{:items-fn (fn []
(->>
(state/get-repos)
(remove (fn [{:keys [url]}]
(or (config/demo-graph? url)
(= url (state/get-current-repo)))))
(map (fn [{:keys [url]}]
{:value (text-util/get-graph-name-from-path
(if (config/local-db? url)
(config/get-local-dir url)
(db/get-repo-path url)))
:id (config/get-repo-dir url)
:graph url}))))
:prompt-key :select.graph/prompt
:on-chosen #(state/pub-event! [:graph/switch (:graph %)])
:empty-placeholder (fn [t]
[:div.px-4.py-2
[:div.mb-2 (t :select.graph/empty-placeholder-description)]
(ui/button
(t :select.graph/add-graph)
:href (rfe/href :repo-add)
:on-click state/close-modal!)])}
:graph-remove
{:items-fn (fn []
(->> (state/get-repos)
(remove (fn [{:keys [url]}]
(config/demo-graph? url)))
(map (fn [{:keys [url] :as original-graph}]
{:value (text-util/get-graph-name-from-path
(if (config/local-db? url)
(config/get-local-dir url)
(db/get-repo-path url)))
:id (config/get-repo-dir url)
:graph url
:original-graph original-graph}))))
:on-chosen #(repo-handler/remove-repo! (:original-graph %))}})
(rum/defc select-modal < rum/reactive
[]
(when-let [select-type (state/sub [:ui/open-select])]
(let [select-type-config (get (select-config) select-type)]
(state/set-modal!
#(select (-> select-type-config
(select-keys [:on-chosen :empty-placeholder :prompt-key])
(assoc :items ((:items-fn select-type-config)))))
{:fullscreen? false
:close-btn? false}))
nil))
|
24ff2d0e8c04faa05448911cd0614c979d010bcf5d20718a97e15ffacdc664aa | S8A/htdp-exercises | ex428.rkt | The first three lines of this file were inserted by . They record metadata
;; about the language level of this file in a form that our tools can easily process.
#reader(lib "htdp-intermediate-lambda-reader.ss" "lang")((modname ex428) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f () #f)))
; [List-of Number] -> [List-of Number]
; produces a sorted version of alon
(define (quick-sort< alon)
(cond
[(empty? alon) '()]
[(= (length alon) 1) alon]
[else (local ((define pivot (first alon))
(define others (rest alon)))
(append (quick-sort< (smallers others pivot))
(list pivot)
(quick-sort< (largers others pivot))))]))
(check-expect (quick-sort< '(11 8 14 7)) '(7 8 11 14))
(check-expect (quick-sort< '(11 9 3 2 18 3 6 12 3 4 14 2 7 4 1))
'(1 2 2 3 3 3 4 4 6 7 9 11 12 14 18))
; [List-of Number] Number -> [List-of Number]
; produces a list of those numbers from the given list that
; are larger than n
(define (largers alon n)
(cond
[(empty? alon) '()]
[else (if (>= (first alon) n)
(cons (first alon) (largers (rest alon) n))
(largers (rest alon) n))]))
; [List-of Number] Number -> [List-of Number]
; produces a list of those numbers from the given list that
; are smaller than n
(define (smallers alon n)
(cond
[(empty? alon) '()]
[else (if (< (first alon) n)
(cons (first alon) (smallers (rest alon) n))
(smallers (rest alon) n))]))
| null | https://raw.githubusercontent.com/S8A/htdp-exercises/578e49834a9513f29ef81b7589b28081c5e0b69f/ex428.rkt | racket | about the language level of this file in a form that our tools can easily process.
[List-of Number] -> [List-of Number]
produces a sorted version of alon
[List-of Number] Number -> [List-of Number]
produces a list of those numbers from the given list that
are larger than n
[List-of Number] Number -> [List-of Number]
produces a list of those numbers from the given list that
are smaller than n | The first three lines of this file were inserted by . They record metadata
#reader(lib "htdp-intermediate-lambda-reader.ss" "lang")((modname ex428) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f () #f)))
(define (quick-sort< alon)
(cond
[(empty? alon) '()]
[(= (length alon) 1) alon]
[else (local ((define pivot (first alon))
(define others (rest alon)))
(append (quick-sort< (smallers others pivot))
(list pivot)
(quick-sort< (largers others pivot))))]))
(check-expect (quick-sort< '(11 8 14 7)) '(7 8 11 14))
(check-expect (quick-sort< '(11 9 3 2 18 3 6 12 3 4 14 2 7 4 1))
'(1 2 2 3 3 3 4 4 6 7 9 11 12 14 18))
(define (largers alon n)
(cond
[(empty? alon) '()]
[else (if (>= (first alon) n)
(cons (first alon) (largers (rest alon) n))
(largers (rest alon) n))]))
(define (smallers alon n)
(cond
[(empty? alon) '()]
[else (if (< (first alon) n)
(cons (first alon) (smallers (rest alon) n))
(smallers (rest alon) n))]))
|
fecde74bb19802bb2e2d5c272e51a641ec8e1433d393695866c75bfd9d90814b | lexml/lexml-linker | Parser.hs | # LANGUAGE FlexibleContexts #
module LexML.Linker.Parser (
LinkerParseError (..), parseReferencias2
) where
import Data.Char
import Control.Monad
import Control.Monad.Trans
import Control.Monad.Except
import Control.Monad.Identity
import Control.Monad.State
import Control.Monad.Writer
import LexML.Linker.Decorator (DecorationMap, addURN)
import Data.Typeable
import LexML.Linker.LexerPrim (Token, TokenData(..), tokenDataLength)
import qualified Data.Map as M
import Text.Parsec
import Text.Parsec.Prim
import Text.Parsec.Pos (newPos)
import LexML.URN.Types
import LexML.URN.Show
import qualified LexML.URN.Atalhos as U
import LexML.Linker.ParserBase
import LexML.Linker .
import qualified LexML.Linker.Regras2 as R2
import LexML.Linker.RegrasSTF
parseReferencias : : ( BaseM m , MonadError LinkerParseError m ) = > [ Token ] - > m
parseReferencias l = execStateT ( runPT ( many ) ( ) " source " l ) iniState > > = return .
iniState = LPS {
lpsDecorationMap = M.empty,
lpsResolverURL = "",
lpsContexto = Nothing,
lpsLogTokens = False,
lpsLogRegras = False,
lpsLogOther = False,
lpsLogMessages = [],
lpsConstituicaoSimples = False,
lpsPrevTokens = []
}
doParse : : BaseM m = > LinkerParserMonad m ( )
= choice ( ( map ( try . parseCase ) parseCases + + [ skip ] ) )
doParse = choice ((map (try . parseCase) parseCases ++ [skip])) -}
parseReferencias2 :: [LinkerComponent] -> Maybe String -> URNLexML -> [Token] -> Bool -> (DecorationMap,[String])
parseReferencias2 logComps murlresolver ctx l constituicaoSimples = (lpsDecorationMap res, reverse $ lpsLogMessages res)
where
res = execState (fmap join $ runExceptT $ fmap (either (Left . LPE_ParseError) Right) $ runPT (many doParse) () "" l) iniState'''
iniState''' = iniState'' { lpsConstituicaoSimples = constituicaoSimples }
iniState'' = foldr enable iniState' logComps
iniState' = case murlresolver of
Nothing -> iniState { lpsContexto = Just ctx }
Just u -> iniState { lpsResolverURL = u, lpsContexto = Just ctx }
doParse = choice (ignored : (map (try . parseCase2 ctx) (pSTF : R2.parseCases) ++ [skip]))
| null | https://raw.githubusercontent.com/lexml/lexml-linker/b102332b9e4dce4e2dab533c94bbabd76f43bcc9/src/main/haskell/LexML/Linker/Parser.hs | haskell | # LANGUAGE FlexibleContexts #
module LexML.Linker.Parser (
LinkerParseError (..), parseReferencias2
) where
import Data.Char
import Control.Monad
import Control.Monad.Trans
import Control.Monad.Except
import Control.Monad.Identity
import Control.Monad.State
import Control.Monad.Writer
import LexML.Linker.Decorator (DecorationMap, addURN)
import Data.Typeable
import LexML.Linker.LexerPrim (Token, TokenData(..), tokenDataLength)
import qualified Data.Map as M
import Text.Parsec
import Text.Parsec.Prim
import Text.Parsec.Pos (newPos)
import LexML.URN.Types
import LexML.URN.Show
import qualified LexML.URN.Atalhos as U
import LexML.Linker.ParserBase
import LexML.Linker .
import qualified LexML.Linker.Regras2 as R2
import LexML.Linker.RegrasSTF
parseReferencias : : ( BaseM m , MonadError LinkerParseError m ) = > [ Token ] - > m
parseReferencias l = execStateT ( runPT ( many ) ( ) " source " l ) iniState > > = return .
iniState = LPS {
lpsDecorationMap = M.empty,
lpsResolverURL = "",
lpsContexto = Nothing,
lpsLogTokens = False,
lpsLogRegras = False,
lpsLogOther = False,
lpsLogMessages = [],
lpsConstituicaoSimples = False,
lpsPrevTokens = []
}
doParse : : BaseM m = > LinkerParserMonad m ( )
= choice ( ( map ( try . parseCase ) parseCases + + [ skip ] ) )
doParse = choice ((map (try . parseCase) parseCases ++ [skip])) -}
parseReferencias2 :: [LinkerComponent] -> Maybe String -> URNLexML -> [Token] -> Bool -> (DecorationMap,[String])
parseReferencias2 logComps murlresolver ctx l constituicaoSimples = (lpsDecorationMap res, reverse $ lpsLogMessages res)
where
res = execState (fmap join $ runExceptT $ fmap (either (Left . LPE_ParseError) Right) $ runPT (many doParse) () "" l) iniState'''
iniState''' = iniState'' { lpsConstituicaoSimples = constituicaoSimples }
iniState'' = foldr enable iniState' logComps
iniState' = case murlresolver of
Nothing -> iniState { lpsContexto = Just ctx }
Just u -> iniState { lpsResolverURL = u, lpsContexto = Just ctx }
doParse = choice (ignored : (map (try . parseCase2 ctx) (pSTF : R2.parseCases) ++ [skip]))
| |
e75e625d56b386afbb7e99bbeba61e0ceda405667a4291fd953de98852987cb4 | scarvalhojr/haskellbook | section17.8.hs |
import Data.Monoid ((<>))
data List a = Nil | Cons a (List a)
deriving (Eq, Show)
instance Functor List where
fmap _ Nil = Nil
fmap f (Cons x t) = Cons (f x) (fmap f t)
instance Monoid (List a) where
mempty = Nil
mappend Nil ys = ys
mappend (Cons x xs) ys = Cons x (xs <> ys)
instance Applicative List where
pure x = Cons x Nil
(<*>) Nil _ = Nil
(<*>) _ Nil = Nil
(<*>) fs xs = flatMap (flip fmap xs) fs
toList :: Foldable t => t a -> List a
toList = foldr Cons Nil
fromList :: List a -> [a]
fromList Nil = []
fromList (Cons h t) = h : fromList t
fold :: (a -> b -> b) -> b -> List a -> b
fold _ z Nil = z
fold f z (Cons h t) = f h (fold f z t)
concat' :: List (List a) -> List a
concat' = fold (<>) Nil
flatMap :: (a -> List b) -> List a -> List b
flatMap f l = concat' (fmap f l)
---
f1 = toList [(+1), (*2)]
v1 = toList [1, 2]
test1 = (f1 <*> v1) == toList [2, 3, 2, 4]
f2 = toList [negate, (+10), (*10), (`mod` 10)]
v2 = toList [50..55]
test2 = fromList (f2 <*> v2) == [-50, -51, -52, -53, -54, -55
, 60, 61, 62, 63, 64, 65
,500, 510, 520, 530, 540, 550
, 0, 1, 2, 3, 4, 5]
---
newtype ZipList a = ZipList (List a)
deriving (Eq, Show)
instance Functor ZipList where
fmap f (ZipList xs) = ZipList (fmap f xs)
instance Monoid (ZipList a) where
mempty = ZipList Nil
mappend (ZipList xs) (ZipList ys) = ZipList (xs <> ys)
instance Applicative ZipList where
pure x = ZipList (Cons x Nil)
(<*>) (ZipList Nil) _ = ZipList Nil
(<*>) _ (ZipList Nil) = ZipList Nil
(<*>) (ZipList (Cons f fs)) (ZipList (Cons x xs))
= ZipList (Cons (f x) Nil) <> (ZipList fs <*> ZipList xs)
---
f3 = ZipList (toList [(+9), (*2), (+8)])
v3 = ZipList (toList [1..3])
test3 = (f3 <*> v3) == ZipList (toList [10, 4, 11])
f4 = f3
v4 = ZipList (toList (repeat 1))
test4 = (f4 <*> v4) == ZipList (toList [10, 2, 9])
f5 = ZipList (toList [negate, (+10), (*10), (`mod` 10)])
v5 = ZipList (toList [50..])
test5 = (f5 <*> v5) == ZipList (toList [-50, 61, 520, 3])
---
data Validation e a = Failure e | Success a
deriving (Eq, Show)
instance Functor (Validation e) where
fmap _ (Failure e) = Failure e
fmap f (Success a) = Success (f a)
instance Monoid e => Applicative (Validation e) where
pure x = Success x
(Failure e1) <*> (Failure e2) = Failure (e1 <> e2)
(Failure e) <*> (Success _) = Failure e
(Success _) <*> (Failure e) = Failure e
(Success f) <*> (Success x) = Success (f x)
| null | https://raw.githubusercontent.com/scarvalhojr/haskellbook/6016a5a78da3fc4a29f5ea68b239563895c448d5/chapter17/section17.8.hs | haskell | -
-
-
- |
import Data.Monoid ((<>))
data List a = Nil | Cons a (List a)
deriving (Eq, Show)
instance Functor List where
fmap _ Nil = Nil
fmap f (Cons x t) = Cons (f x) (fmap f t)
instance Monoid (List a) where
mempty = Nil
mappend Nil ys = ys
mappend (Cons x xs) ys = Cons x (xs <> ys)
instance Applicative List where
pure x = Cons x Nil
(<*>) Nil _ = Nil
(<*>) _ Nil = Nil
(<*>) fs xs = flatMap (flip fmap xs) fs
toList :: Foldable t => t a -> List a
toList = foldr Cons Nil
fromList :: List a -> [a]
fromList Nil = []
fromList (Cons h t) = h : fromList t
fold :: (a -> b -> b) -> b -> List a -> b
fold _ z Nil = z
fold f z (Cons h t) = f h (fold f z t)
concat' :: List (List a) -> List a
concat' = fold (<>) Nil
flatMap :: (a -> List b) -> List a -> List b
flatMap f l = concat' (fmap f l)
f1 = toList [(+1), (*2)]
v1 = toList [1, 2]
test1 = (f1 <*> v1) == toList [2, 3, 2, 4]
f2 = toList [negate, (+10), (*10), (`mod` 10)]
v2 = toList [50..55]
test2 = fromList (f2 <*> v2) == [-50, -51, -52, -53, -54, -55
, 60, 61, 62, 63, 64, 65
,500, 510, 520, 530, 540, 550
, 0, 1, 2, 3, 4, 5]
newtype ZipList a = ZipList (List a)
deriving (Eq, Show)
instance Functor ZipList where
fmap f (ZipList xs) = ZipList (fmap f xs)
instance Monoid (ZipList a) where
mempty = ZipList Nil
mappend (ZipList xs) (ZipList ys) = ZipList (xs <> ys)
instance Applicative ZipList where
pure x = ZipList (Cons x Nil)
(<*>) (ZipList Nil) _ = ZipList Nil
(<*>) _ (ZipList Nil) = ZipList Nil
(<*>) (ZipList (Cons f fs)) (ZipList (Cons x xs))
= ZipList (Cons (f x) Nil) <> (ZipList fs <*> ZipList xs)
f3 = ZipList (toList [(+9), (*2), (+8)])
v3 = ZipList (toList [1..3])
test3 = (f3 <*> v3) == ZipList (toList [10, 4, 11])
f4 = f3
v4 = ZipList (toList (repeat 1))
test4 = (f4 <*> v4) == ZipList (toList [10, 2, 9])
f5 = ZipList (toList [negate, (+10), (*10), (`mod` 10)])
v5 = ZipList (toList [50..])
test5 = (f5 <*> v5) == ZipList (toList [-50, 61, 520, 3])
data Validation e a = Failure e | Success a
deriving (Eq, Show)
instance Functor (Validation e) where
fmap _ (Failure e) = Failure e
fmap f (Success a) = Success (f a)
instance Monoid e => Applicative (Validation e) where
pure x = Success x
(Failure e1) <*> (Failure e2) = Failure (e1 <> e2)
(Failure e) <*> (Success _) = Failure e
(Success _) <*> (Failure e) = Failure e
(Success f) <*> (Success x) = Success (f x)
|
19ba8b77ef2c854c88aaa33d523efc84093b5f0bf48dfa8d32327a715a13eb73 | slyrus/abcl | typep.lisp | ;;; typep.lisp
;;;
Copyright ( C ) 2003 - 2005
$ Id$
;;;
;;; This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation ; either version 2
of the License , or ( at your option ) any later version .
;;;
;;; This program is distributed in the hope that it will be useful,
;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;;; GNU General Public License for more details.
;;;
You should have received a copy of the GNU General Public License
;;; along with this program; if not, write to the Free Software
Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA .
;;;
;;; As a special exception, the copyright holders of this library give you
;;; permission to link this library with independent modules to produce an
;;; executable, regardless of the license terms of these independent
;;; modules, and to copy and distribute the resulting executable under
;;; terms of your choice, provided that you also meet, for each linked
;;; independent module, the terms and conditions of the license of that
;;; module. An independent module is a module which is not derived from
;;; or based on this library. If you modify this library, you may extend
;;; this exception to your version of the library, but you are not
;;; obligated to do so. If you do not wish to do so, delete this
;;; exception statement from your version.
(in-package #:system)
(defun simple-array-p (object)
(and (arrayp object)
(not (array-has-fill-pointer-p object))
(multiple-value-bind (displaced-to offset) (array-displacement object)
(and (null displaced-to) (zerop offset)))))
(defun in-interval-p (x interval)
(if (endp interval)
t
(let ((low (%car interval))
(high (if (endp (%cdr interval)) '* (%cadr interval))))
(cond ((eq low '*))
((consp low)
(when (<= x (%car low))
(return-from in-interval-p nil)))
((when (< x low)
(return-from in-interval-p nil))))
(cond ((eq high '*))
((consp high)
(when (>= x (%car high))
(return-from in-interval-p nil)))
((when (> x high)
(return-from in-interval-p nil))))
t)))
(defun match-dimensions (dim pat)
(if (null dim)
(null pat)
(and (or (eq (car pat) '*)
(eql (car dim) (car pat)))
(match-dimensions (cdr dim) (cdr pat)))))
(defun %typep (object type)
(when (atom type)
(when (eq type 'values)
(error 'simple-error
:format-control "The symbol ~S is not valid as a type specifier."
:format-arguments (list type)))
(unless (and (symbolp type) (get type 'deftype-definition))
(return-from %typep (simple-typep object type))))
(setf type (normalize-type type))
(when (atom type)
(return-from %typep (simple-typep object type)))
(let ((tp (%car type))
(i (%cdr type)))
(case tp
(INTEGER
(and (integerp object) (in-interval-p object i)))
(RATIONAL
(and (rationalp object) (in-interval-p object i)))
((FLOAT SINGLE-FLOAT DOUBLE-FLOAT SHORT-FLOAT LONG-FLOAT)
(and (floatp object) (in-interval-p object i)))
(REAL
(and (realp object) (in-interval-p object i)))
(COMPLEX
(and (complexp object)
(or (null i)
(and (typep (realpart object) i)
(typep (imagpart object) i)))))
(CONS
(and (consp object)
(or (null (car i)) (eq (car i) '*) (%typep (%car object) (car i)))
(or (null (cadr i)) (eq (cadr i) '*) (%typep (%cdr object) (cadr i)))))
(SIMPLE-BIT-VECTOR
(and (simple-bit-vector-p object)
(or (endp i)
(eq (%car i) '*)
(eql (%car i) (array-dimension object 0)))))
(BIT-VECTOR
(and (bit-vector-p object)
(or (endp i)
(eq (%car i) '*)
(eql (%car i) (array-dimension object 0)))))
(SIMPLE-STRING
(and (simple-string-p object)
(or (endp i)
(eq (%car i) '*)
(eql (%car i) (array-dimension object 0)))))
(STRING
(and (stringp object)
(or (endp i)
(eq (%car i) '*)
(eql (%car i) (array-dimension object 0)))))
(SIMPLE-VECTOR
(and (simple-vector-p object)
(or (endp i)
(eq (%car i) '*)
(eql (%car i) (array-dimension object 0)))))
(VECTOR
(and (vectorp object)
(or (endp i)
(eq (%car i) '*)
(and (eq (%car i) t) (not (stringp object)) (not (bit-vector-p object)))
(and (stringp object) (%subtypep (%car i) 'character))
(equal (array-element-type object) (%car i)))
(or (endp (cdr i))
(eq (%cadr i) '*)
(eql (%cadr i) (array-dimension object 0)))))
(SIMPLE-ARRAY
(and (simple-array-p object)
(or (endp i)
(eq (%car i) '*)
(equal (array-element-type object) (upgraded-array-element-type (%car i))))
(or (endp (cdr i))
(eq (%cadr i) '*)
(if (listp (%cadr i))
(match-dimensions (array-dimensions object) (%cadr i))
(eql (array-rank object) (%cadr i))))))
(ARRAY
(and (arrayp object)
(or (endp i)
(eq (%car i) '*)
(equal (array-element-type object) (upgraded-array-element-type (%car i))))
(or (endp (cdr i))
(eq (%cadr i) '*)
(if (listp (%cadr i))
(match-dimensions (array-dimensions object) (%cadr i))
(eql (array-rank object) (%cadr i))))))
(AND
(dolist (type i)
(unless (%typep object type)
(return-from %typep nil)))
t)
(OR
(dolist (type i)
(when (%typep object type)
(return-from %typep t)))
nil)
(NOT
(not (%typep object (car i))))
(MEMBER
(member object i))
(EQL
(eql object (car i)))
(SATISFIES
(unless (symbolp (car i))
(error 'simple-type-error
:datum (car i)
:expected-type 'symbol
:format-control "The SATISFIES predicate name is not a symbol: ~S"
:format-arguments (list (car i))))
(funcall (car i) object))
(NIL-VECTOR
(and (simple-typep object 'nil-vector)
(or (endp i)
(eql (%car i) (length object)))))
(MOD
(and (integerp object)
(or (zerop object)
(and (plusp object)
(< object (second type))))))
((FUNCTION VALUES)
(error 'simple-error
:format-control "~S types are not a legal argument to TYPEP: ~S"
:format-arguments (list tp type)))
(t
nil))))
(defun typep (object type &optional environment)
(declare (ignore environment))
(%typep object type))
| null | https://raw.githubusercontent.com/slyrus/abcl/881f733fdbf4b722865318a7d2abe2ff8fdad96e/src/org/armedbear/lisp/typep.lisp | lisp | typep.lisp
This program is free software; you can redistribute it and/or
either version 2
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
along with this program; if not, write to the Free Software
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. | Copyright ( C ) 2003 - 2005
$ Id$
modify it under the terms of the GNU General Public License
of the License , or ( at your option ) any later version .
You should have received a copy of the GNU General Public License
Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA .
(in-package #:system)
(defun simple-array-p (object)
(and (arrayp object)
(not (array-has-fill-pointer-p object))
(multiple-value-bind (displaced-to offset) (array-displacement object)
(and (null displaced-to) (zerop offset)))))
(defun in-interval-p (x interval)
(if (endp interval)
t
(let ((low (%car interval))
(high (if (endp (%cdr interval)) '* (%cadr interval))))
(cond ((eq low '*))
((consp low)
(when (<= x (%car low))
(return-from in-interval-p nil)))
((when (< x low)
(return-from in-interval-p nil))))
(cond ((eq high '*))
((consp high)
(when (>= x (%car high))
(return-from in-interval-p nil)))
((when (> x high)
(return-from in-interval-p nil))))
t)))
(defun match-dimensions (dim pat)
(if (null dim)
(null pat)
(and (or (eq (car pat) '*)
(eql (car dim) (car pat)))
(match-dimensions (cdr dim) (cdr pat)))))
(defun %typep (object type)
(when (atom type)
(when (eq type 'values)
(error 'simple-error
:format-control "The symbol ~S is not valid as a type specifier."
:format-arguments (list type)))
(unless (and (symbolp type) (get type 'deftype-definition))
(return-from %typep (simple-typep object type))))
(setf type (normalize-type type))
(when (atom type)
(return-from %typep (simple-typep object type)))
(let ((tp (%car type))
(i (%cdr type)))
(case tp
(INTEGER
(and (integerp object) (in-interval-p object i)))
(RATIONAL
(and (rationalp object) (in-interval-p object i)))
((FLOAT SINGLE-FLOAT DOUBLE-FLOAT SHORT-FLOAT LONG-FLOAT)
(and (floatp object) (in-interval-p object i)))
(REAL
(and (realp object) (in-interval-p object i)))
(COMPLEX
(and (complexp object)
(or (null i)
(and (typep (realpart object) i)
(typep (imagpart object) i)))))
(CONS
(and (consp object)
(or (null (car i)) (eq (car i) '*) (%typep (%car object) (car i)))
(or (null (cadr i)) (eq (cadr i) '*) (%typep (%cdr object) (cadr i)))))
(SIMPLE-BIT-VECTOR
(and (simple-bit-vector-p object)
(or (endp i)
(eq (%car i) '*)
(eql (%car i) (array-dimension object 0)))))
(BIT-VECTOR
(and (bit-vector-p object)
(or (endp i)
(eq (%car i) '*)
(eql (%car i) (array-dimension object 0)))))
(SIMPLE-STRING
(and (simple-string-p object)
(or (endp i)
(eq (%car i) '*)
(eql (%car i) (array-dimension object 0)))))
(STRING
(and (stringp object)
(or (endp i)
(eq (%car i) '*)
(eql (%car i) (array-dimension object 0)))))
(SIMPLE-VECTOR
(and (simple-vector-p object)
(or (endp i)
(eq (%car i) '*)
(eql (%car i) (array-dimension object 0)))))
(VECTOR
(and (vectorp object)
(or (endp i)
(eq (%car i) '*)
(and (eq (%car i) t) (not (stringp object)) (not (bit-vector-p object)))
(and (stringp object) (%subtypep (%car i) 'character))
(equal (array-element-type object) (%car i)))
(or (endp (cdr i))
(eq (%cadr i) '*)
(eql (%cadr i) (array-dimension object 0)))))
(SIMPLE-ARRAY
(and (simple-array-p object)
(or (endp i)
(eq (%car i) '*)
(equal (array-element-type object) (upgraded-array-element-type (%car i))))
(or (endp (cdr i))
(eq (%cadr i) '*)
(if (listp (%cadr i))
(match-dimensions (array-dimensions object) (%cadr i))
(eql (array-rank object) (%cadr i))))))
(ARRAY
(and (arrayp object)
(or (endp i)
(eq (%car i) '*)
(equal (array-element-type object) (upgraded-array-element-type (%car i))))
(or (endp (cdr i))
(eq (%cadr i) '*)
(if (listp (%cadr i))
(match-dimensions (array-dimensions object) (%cadr i))
(eql (array-rank object) (%cadr i))))))
(AND
(dolist (type i)
(unless (%typep object type)
(return-from %typep nil)))
t)
(OR
(dolist (type i)
(when (%typep object type)
(return-from %typep t)))
nil)
(NOT
(not (%typep object (car i))))
(MEMBER
(member object i))
(EQL
(eql object (car i)))
(SATISFIES
(unless (symbolp (car i))
(error 'simple-type-error
:datum (car i)
:expected-type 'symbol
:format-control "The SATISFIES predicate name is not a symbol: ~S"
:format-arguments (list (car i))))
(funcall (car i) object))
(NIL-VECTOR
(and (simple-typep object 'nil-vector)
(or (endp i)
(eql (%car i) (length object)))))
(MOD
(and (integerp object)
(or (zerop object)
(and (plusp object)
(< object (second type))))))
((FUNCTION VALUES)
(error 'simple-error
:format-control "~S types are not a legal argument to TYPEP: ~S"
:format-arguments (list tp type)))
(t
nil))))
(defun typep (object type &optional environment)
(declare (ignore environment))
(%typep object type))
|
3c6dbe9e15550b26128ebd59ada6df7550672a5eb28c29e9b40a61cfed6246fb | armstnp/advent-of-code-2019 | day5_sketch.clj | (ns advent-of-code-2019.day5-sketch
(:require [advent-of-code-2019.day5 :as soln]
[quil.core :as q :include-macros true]
[quil.middleware :as m]))
;; Pause and unpause the simulation by clicking or pressing any key
(def cells (count soln/input))
(def memory-cell-width 15)
(def memory-cell-height (q/ceil (/ cells memory-cell-width)))
(def cell-width 80)
(def cell-height 20)
(def mid-cell (/ cell-height 2))
(def memory-width (* cell-width memory-cell-width))
(def memory-height (* cell-height memory-cell-height))
(def diagnostic-height 20)
(def canvas-width memory-width)
(def canvas-height (+ diagnostic-height memory-height))
(def diagnostic-line (+ memory-height (/ diagnostic-height 2)))
(def diagnostic-offset (quot canvas-width 3))
(defn setup
[]
(q/frame-rate 1)
(q/color-mode :rgb)
(q/background 0)
(q/text-size 12)
(q/text-align :left :center)
(q/no-stroke)
{:memory soln/input
:ip 0
:in-stack '(5)
:out-queue []
:paused true})
(defn addr-by-mode
[mode value-addr value]
(case mode
0 value
1 value-addr))
(def op-display
{1 "+"
2 "*"
3 "in"
4 "out"
5 "j:t"
6 "j:f"
7 "<"
8 "="
99 "HALT"})
(defn draw-ip
[ip touched?]
(when touched?
(q/fill 0 0 100)
(q/rect 0 memory-height diagnostic-offset canvas-height))
(q/fill 255 255 255)
(q/text (str "IP: " ip) 0 diagnostic-line))
(defn draw-in-stack
[[next-input] takes-input?]
(when takes-input?
(q/fill 0 50 0)
(q/rect diagnostic-offset memory-height diagnostic-offset canvas-height))
(q/fill 255 255 255)
(q/text (str "NEXT IN: " next-input) diagnostic-offset diagnostic-line))
(defn draw-out-queue
[out-queue emits-output?]
(when emits-output?
(q/fill 50 0 0)
(q/rect (* 2 diagnostic-offset) memory-height (- canvas-width (* 2 diagnostic-offset)) canvas-height))
(q/fill 255 255 255)
(q/text (str "LAST OUT: " (first out-queue)) (* 2 diagnostic-offset) diagnostic-line))
(defn draw-state
[{:keys [memory ip in-stack out-queue halt]}]
(q/clear)
(q/background (if halt 100 0) 0 0)
(let [[opcode modes] (soln/parse-code (memory ip))
inputs (case opcode
(1 2 5 6 7 8) (->> memory
(drop (inc ip))
(take 2)
(map addr-by-mode modes (range (inc ip) (+ 3 ip)))
set)
4 (->> ip
inc
(nth memory)
(addr-by-mode (first modes) (inc ip))
hash-set)
(3 99) #{}
#{})
output (case opcode
(1 2 7 8) (memory (+ ip 3))
3 (memory (inc ip))
(4 5 6 99) nil
nil)
instr-range? (case opcode
(1 2 7 8) (set (range (inc ip) (+ ip 4)))
(5 6) (set (range (inc ip) (+ ip 3)))
(3 4) (hash-set (inc ip))
99 #{}
#{})
takes-input? (= opcode 3)
emits-output? (= opcode 4)
touches-ip? (#{5 6} opcode)]
(doall
(map-indexed
(fn [addr value]
(let [x (* cell-width (mod addr memory-cell-width))
y (* cell-height (quot addr memory-cell-width))
op? (= addr ip)
input? (inputs addr)
output? (= output addr)
red (if op? 50 0)
green (if input? 50 0)
blue (if output? 100 0)
color (map +
(if halt [100 0 0] [red green blue])
(if (instr-range? addr) [100 100 100] [0 0 0]))
value-str (if op?
(str value " (" (op-display opcode) ")")
(str value))]
(apply q/fill color)
(q/rect x y cell-width cell-height)
(q/fill 255 255 255)
(q/text value-str (+ x 2) (+ y mid-cell))))
memory))
(draw-ip ip touches-ip?)
(draw-in-stack in-stack takes-input?)
(draw-out-queue out-queue emits-output?)))
(defn pause-unpause
[state _event]
(update state :paused not))
(q/defsketch day5-sketch
:title "AoC 2019-5: Sunny with a Chance of Asteroids"
:size [canvas-width canvas-height]
:setup setup
:update #(if (:paused %) % (soln/run-instr %))
:draw draw-state
:mouse-clicked pause-unpause
:key-typed pause-unpause
:middleware [m/fun-mode])
Hosted at
| null | https://raw.githubusercontent.com/armstnp/advent-of-code-2019/68e21174394d8b0e14433f9f249e995c10ac6d67/src/advent_of_code_2019/day5_sketch.clj | clojure | Pause and unpause the simulation by clicking or pressing any key | (ns advent-of-code-2019.day5-sketch
(:require [advent-of-code-2019.day5 :as soln]
[quil.core :as q :include-macros true]
[quil.middleware :as m]))
(def cells (count soln/input))
(def memory-cell-width 15)
(def memory-cell-height (q/ceil (/ cells memory-cell-width)))
(def cell-width 80)
(def cell-height 20)
(def mid-cell (/ cell-height 2))
(def memory-width (* cell-width memory-cell-width))
(def memory-height (* cell-height memory-cell-height))
(def diagnostic-height 20)
(def canvas-width memory-width)
(def canvas-height (+ diagnostic-height memory-height))
(def diagnostic-line (+ memory-height (/ diagnostic-height 2)))
(def diagnostic-offset (quot canvas-width 3))
(defn setup
[]
(q/frame-rate 1)
(q/color-mode :rgb)
(q/background 0)
(q/text-size 12)
(q/text-align :left :center)
(q/no-stroke)
{:memory soln/input
:ip 0
:in-stack '(5)
:out-queue []
:paused true})
(defn addr-by-mode
[mode value-addr value]
(case mode
0 value
1 value-addr))
(def op-display
{1 "+"
2 "*"
3 "in"
4 "out"
5 "j:t"
6 "j:f"
7 "<"
8 "="
99 "HALT"})
(defn draw-ip
[ip touched?]
(when touched?
(q/fill 0 0 100)
(q/rect 0 memory-height diagnostic-offset canvas-height))
(q/fill 255 255 255)
(q/text (str "IP: " ip) 0 diagnostic-line))
(defn draw-in-stack
[[next-input] takes-input?]
(when takes-input?
(q/fill 0 50 0)
(q/rect diagnostic-offset memory-height diagnostic-offset canvas-height))
(q/fill 255 255 255)
(q/text (str "NEXT IN: " next-input) diagnostic-offset diagnostic-line))
(defn draw-out-queue
[out-queue emits-output?]
(when emits-output?
(q/fill 50 0 0)
(q/rect (* 2 diagnostic-offset) memory-height (- canvas-width (* 2 diagnostic-offset)) canvas-height))
(q/fill 255 255 255)
(q/text (str "LAST OUT: " (first out-queue)) (* 2 diagnostic-offset) diagnostic-line))
(defn draw-state
[{:keys [memory ip in-stack out-queue halt]}]
(q/clear)
(q/background (if halt 100 0) 0 0)
(let [[opcode modes] (soln/parse-code (memory ip))
inputs (case opcode
(1 2 5 6 7 8) (->> memory
(drop (inc ip))
(take 2)
(map addr-by-mode modes (range (inc ip) (+ 3 ip)))
set)
4 (->> ip
inc
(nth memory)
(addr-by-mode (first modes) (inc ip))
hash-set)
(3 99) #{}
#{})
output (case opcode
(1 2 7 8) (memory (+ ip 3))
3 (memory (inc ip))
(4 5 6 99) nil
nil)
instr-range? (case opcode
(1 2 7 8) (set (range (inc ip) (+ ip 4)))
(5 6) (set (range (inc ip) (+ ip 3)))
(3 4) (hash-set (inc ip))
99 #{}
#{})
takes-input? (= opcode 3)
emits-output? (= opcode 4)
touches-ip? (#{5 6} opcode)]
(doall
(map-indexed
(fn [addr value]
(let [x (* cell-width (mod addr memory-cell-width))
y (* cell-height (quot addr memory-cell-width))
op? (= addr ip)
input? (inputs addr)
output? (= output addr)
red (if op? 50 0)
green (if input? 50 0)
blue (if output? 100 0)
color (map +
(if halt [100 0 0] [red green blue])
(if (instr-range? addr) [100 100 100] [0 0 0]))
value-str (if op?
(str value " (" (op-display opcode) ")")
(str value))]
(apply q/fill color)
(q/rect x y cell-width cell-height)
(q/fill 255 255 255)
(q/text value-str (+ x 2) (+ y mid-cell))))
memory))
(draw-ip ip touches-ip?)
(draw-in-stack in-stack takes-input?)
(draw-out-queue out-queue emits-output?)))
(defn pause-unpause
[state _event]
(update state :paused not))
(q/defsketch day5-sketch
:title "AoC 2019-5: Sunny with a Chance of Asteroids"
:size [canvas-width canvas-height]
:setup setup
:update #(if (:paused %) % (soln/run-instr %))
:draw draw-state
:mouse-clicked pause-unpause
:key-typed pause-unpause
:middleware [m/fun-mode])
Hosted at
|
2c1e088e27b68ce7c4f39d0ae4c9e46214ca835ac63628baaee458c2288ddc84 | bobzhang/fan | a_exn.ml | TYPE_CONV_PATH "B_exn"
exception V of int with sexp
. Exn_magic.register1 ( fun v1 - > V v1 ) " a_exn.ml . V " sexp_of_int
let () = Sexplib.Exn_magic.register1 (fun v1 -> V v1) "B_exn.V" sexp_of_int
(* let () = Sexplib.Exn_magic.register1 (fun v1 -> V v1) "A_exn.V" sexp_of_int *)
(* let () = *)
. Exn_magic.register1 ( fun v1 - > V v1 ) " a_exn.ml . V " sexp_of_int
| null | https://raw.githubusercontent.com/bobzhang/fan/7ed527d96c5a006da43d3813f32ad8a5baa31b7f/src/migration/a_exn.ml | ocaml | let () = Sexplib.Exn_magic.register1 (fun v1 -> V v1) "A_exn.V" sexp_of_int
let () = | TYPE_CONV_PATH "B_exn"
exception V of int with sexp
. Exn_magic.register1 ( fun v1 - > V v1 ) " a_exn.ml . V " sexp_of_int
let () = Sexplib.Exn_magic.register1 (fun v1 -> V v1) "B_exn.V" sexp_of_int
. Exn_magic.register1 ( fun v1 - > V v1 ) " a_exn.ml . V " sexp_of_int
|
469606287e0b021020a29d812e10b375f142856f24824a3dd08eae01f1f19c6d | na4zagin3/satyrographos | setup.mli | (** Default location of target of install subcommand *)
val default_target_dir : string
(** Read current runtime-dependent information.
This command SHOULD NOT affect the environment. *)
val read_environment : unit -> Satyrographos.Environment.t
| null | https://raw.githubusercontent.com/na4zagin3/satyrographos/c6a430bb641166c8a23240f4a827f53405f746e1/bin/setup.mli | ocaml | * Default location of target of install subcommand
* Read current runtime-dependent information.
This command SHOULD NOT affect the environment. | val default_target_dir : string
val read_environment : unit -> Satyrographos.Environment.t
|
9be90551239b8bcb1f895b01c4c03df2af7e93107e56d9e5e3d41990875b02d4 | c4-project/c4f | my_quickcheck.ml | This file is part of c4f .
Copyright ( c ) 2018 - 2022 C4 Project
c4 t itself is licensed under the MIT License . See the LICENSE file in the
project root for more information .
Parts of c4 t are based on code from the Herdtools7 project
( ) : see the LICENSE.herd file in the
project root for more information .
Copyright (c) 2018-2022 C4 Project
c4t itself is licensed under the MIT License. See the LICENSE file in the
project root for more information.
Parts of c4t are based on code from the Herdtools7 project
() : see the LICENSE.herd file in the
project root for more information. *)
open Base
module type S_with_sexp = sig
type t [@@deriving sexp_of, quickcheck]
end
module type S_sample = sig
type t [@@deriving sexp, compare, quickcheck]
end
let gen_string_initial ~(initial : char Base_quickcheck.Generator.t)
~(rest : char Base_quickcheck.Generator.t) :
string Base_quickcheck.Generator.t =
Base_quickcheck.Generator.Let_syntax.(
let%map x = initial and y = Base_quickcheck.Generator.string_of rest in
String.of_char x ^ y)
module Small_non_negative_int : sig
include module type of Int
include S_with_sexp with type t := int
end = struct
include Int
let quickcheck_generator =
Base_quickcheck.Generator.small_positive_or_zero_int
let quickcheck_shrinker = Base_quickcheck.Shrinker.int
let quickcheck_observer = Base_quickcheck.Observer.int
end
let print_sample (type a) ?(test_count : int = 20)
?(printer : (a -> unit) option) (module M : S_sample with type t = a) :
unit =
let print =
Option.value printer ~default:(fun x -> Stdio.print_s [%sexp (x : M.t)])
in
Base_quickcheck.Test.with_sample_exn [%quickcheck.generator: M.t]
~config:{Base_quickcheck.Test.default_config with test_count}
~f:(fun sequence ->
sequence |> Sequence.to_list
|> List.dedup_and_sort ~compare:M.compare
|> List.iter ~f:print )
| null | https://raw.githubusercontent.com/c4-project/c4f/8939477732861789abc807c8c1532a302b2848a5/lib/utils/src/my_quickcheck.ml | ocaml | This file is part of c4f .
Copyright ( c ) 2018 - 2022 C4 Project
c4 t itself is licensed under the MIT License . See the LICENSE file in the
project root for more information .
Parts of c4 t are based on code from the Herdtools7 project
( ) : see the LICENSE.herd file in the
project root for more information .
Copyright (c) 2018-2022 C4 Project
c4t itself is licensed under the MIT License. See the LICENSE file in the
project root for more information.
Parts of c4t are based on code from the Herdtools7 project
() : see the LICENSE.herd file in the
project root for more information. *)
open Base
module type S_with_sexp = sig
type t [@@deriving sexp_of, quickcheck]
end
module type S_sample = sig
type t [@@deriving sexp, compare, quickcheck]
end
let gen_string_initial ~(initial : char Base_quickcheck.Generator.t)
~(rest : char Base_quickcheck.Generator.t) :
string Base_quickcheck.Generator.t =
Base_quickcheck.Generator.Let_syntax.(
let%map x = initial and y = Base_quickcheck.Generator.string_of rest in
String.of_char x ^ y)
module Small_non_negative_int : sig
include module type of Int
include S_with_sexp with type t := int
end = struct
include Int
let quickcheck_generator =
Base_quickcheck.Generator.small_positive_or_zero_int
let quickcheck_shrinker = Base_quickcheck.Shrinker.int
let quickcheck_observer = Base_quickcheck.Observer.int
end
let print_sample (type a) ?(test_count : int = 20)
?(printer : (a -> unit) option) (module M : S_sample with type t = a) :
unit =
let print =
Option.value printer ~default:(fun x -> Stdio.print_s [%sexp (x : M.t)])
in
Base_quickcheck.Test.with_sample_exn [%quickcheck.generator: M.t]
~config:{Base_quickcheck.Test.default_config with test_count}
~f:(fun sequence ->
sequence |> Sequence.to_list
|> List.dedup_and_sort ~compare:M.compare
|> List.iter ~f:print )
| |
8408408b53cc1cddeb3601af0e8da2018d9edd7f746ee98a65816cf641dace80 | jarvinet/scheme | myeval.scm | Structure and Interpretation of Computer Programs , 2nd edition
; My evaluator
; See myeval.txt for accompanying notes.
;-----------------------------------
; Misc
(define (tagged-list? exp tag)
(if (pair? exp)
(eq? (car exp) tag)
false))
(define (list-of-values operands env)
(if (null? operands)
'()
(cons (eval (car operands) env)
(list-of-values (cdr operands) env))))
(define (true? x) (not (eq? x false)))
(define (false? x) (eq? x false))
; I think it is better not to rename this apply
; and use name "myapply" for the apply defined in this evaluator
; so multiple loadings of this file does not lose the original apply
; (define apply-in-underlying-scheme apply)
(define (last-exp? seq) (null? (cdr seq)))
(define (first-exp seq) (car seq))
(define (rest-exps seq) (cdr seq))
(define (filter predicate stream)
(cond ((null? stream)
'())
((predicate (car stream))
(cons (car stream) (filter predicate (cdr stream))))
(else (filter predicate (cdr stream)))))
;-----------------------------------
Table operations from section 3.3.3
; to support operation/type table for data-directed dispatch
(define (assoc key records)
(cond ((null? records) false)
((equal? key (caar records)) (car records))
(else (assoc key (cdr records)))))
(define (make-table)
(let ((local-table (list '*table*)))
(define (lookup key-1 key-2)
(let ((subtable (assoc key-1 (cdr local-table))))
(if subtable
(let ((record (assoc key-2 (cdr subtable))))
(if record
(cdr record)
false))
false)))
(define (insert! key-1 key-2 value)
(let ((subtable (assoc key-1 (cdr local-table))))
(if subtable
(let ((record (assoc key-2 (cdr subtable))))
(if record
(set-cdr! record value)
(set-cdr! subtable
(cons (cons key-2 value)
(cdr subtable)))))
(set-cdr! local-table
(cons (list key-1
(cons key-2 value))
(cdr local-table)))))
'ok)
(define (dispatch m)
(cond ((eq? m 'lookup-proc) lookup)
((eq? m 'insert-proc!) insert!)
(else (error "Unknown operation -- TABLE" m))))
dispatch))
(define operation-table (make-table))
(define get (operation-table 'lookup-proc))
(define put (operation-table 'insert-proc!))
;-----------------------------------
; Binding is a name-value pair:
;
; +-+-+
; | | |
; +-+-+
; | |
; V V
; name value
(define (binding-make name value) (cons name value))
(define (binding-name binding) (car binding))
(define (binding-value binding) (cdr binding))
(define (binding-set-value! binding new-value)
(set-cdr! binding new-value))
;-----------------------------------
; Frame is a list of bindings, with a "head node" whose car is *frame*:
;
; +-+-+ +-+-+ +-+-+
; | | +------>| | |------>| |/|
; +-+-+ +-+-+ +-+-+
; | | |
; V V V
; *frame* +-+-+ +-+-+
; | | | | | |
; +-+-+ +-+-+
; | | | |
; V V V V
; name value name value
(define (frame-make)
(cons '*frame* '()))
(define (frame-add-binding! binding frame)
(let ((pair (cons binding (cdr frame))))
(set-cdr! frame pair)))
(define (frame-lookup-binding frame name)
(define (iter bindings)
(if (null? bindings)
'()
(let ((binding (car bindings)))
(if (eq? (binding-name binding) name)
binding
(iter (cdr bindings))))))
(iter (cdr frame)))
;-----------------------------------
; Environment is a list of frames
(define (first-frame env) (car env))
(define (env-enclosing-environment env) (cdr env))
(define (env-lookup-binding env name)
(define (env-loop env)
(if (eq? env the-empty-environment)
'()
(let ((frame (first-frame env)))
(let ((binding (frame-lookup-binding frame name)))
(if (null? binding)
(env-loop (env-enclosing-environment env))
binding)))))
(env-loop env))
(define (env-extend vars vals base-env)
(if (= (length vars) (length vals))
(let ((frame (frame-make)))
(define (loop frame vars vals)
(if (null? vars)
frame
(begin (frame-add-binding!
(binding-make (car vars) (car vals))
frame)
(loop frame (cdr vars) (cdr vals)))))
(loop frame vars vals)
(cons frame base-env))
(if (< (length vars) (length vals))
(error "Too many arguments supplied" vars vals)
(error "Too few arguments supplied" vars vals))))
(define (env-lookup-variable-value var env)
(let ((binding (env-lookup-binding env var)))
(if (null? binding)
(error "Unbound variable" var)
(let ((value (binding-value binding)))
(if (eq? value '*unassigned*)
(error "Unassigned variable" var)
value)))))
(define (env-set-variable-value! var val env)
(let ((binding (env-lookup-binding env var)))
(if (null? binding)
(error "Unbound variable -- SET!" var)
(binding-set-value! binding val))))
(define (env-define-variable! var val env)
(let ((frame (first-frame env)))
(let ((binding (frame-lookup-binding frame var)))
(if (null? binding)
(frame-add-binding! (binding-make var val) frame)
(binding-set-value! binding val)))))
;-----------------------------------
; Procedure application
( foo 1 2 )
(define (application? exp) (pair? exp))
(define (operator exp) (car exp))
(define (operands exp) (cdr exp))
; A compound procedure is applied as follows:
1 ) Create a new frame ( extend environment ) where the operands
; of the application are bound to the parameters of the procedure.
; The enclosing environment of the new frame is the environment
; packaged with the procedure to be applied.
2 ) The body of the procedure is evaluated in the new environment .
(define (myapply procedure arguments)
(cond ((primitive-procedure? procedure)
(apply-primitive-procedure procedure arguments))
((compound-procedure? procedure)
(sequence-eval (procedure-body procedure)
(env-extend
(procedure-parameters procedure)
arguments
(procedure-env procedure))))
(else
(error "Unknown procedure type - myapply"
procedure))))
;-----------------------------------
; Self-evaluating expressions
(define (self-evaluating? exp)
(cond ((number? exp) true)
((string? exp) true)
(else false)))
;-----------------------------------
; Variables
(define (variable? exp) (symbol? exp))
;-----------------------------------
; Quotation
; Special form
; 'foo
(define (quoted? exp) (tagged-list? exp 'quote))
(define (quote-text exp) (cadr exp))
;-----------------------------------
; Assignment
; Special form
( set ! foo 1 )
(define (assignment? exp) (tagged-list? exp 'set!))
(define (assignment-variable exp) (cadr exp))
(define (assignment-value exp) (caddr exp))
(define (assignment-make variable value)
(list 'set! variable value))
(define (assignment-eval exp env)
(let ((var (assignment-variable exp))
(value (eval (assignment-value exp) env)))
(env-set-variable-value! var value env)
var))
;-----------------------------------
; Definition
( define foo 1 ) ; case 1 ( Special form )
( define ( foo bar ) body ) ; case 2 ( Derived expression )
case 2 can be converted to an equivalent case 1 form :
; (define foo (lambda (bar) body))
(define (definition? exp)
(tagged-list? exp 'define))
(define (definition-variable exp)
(if (symbol? (cadr exp))
case 1
case 2
(define (definition-value exp)
(if (symbol? (cadr exp))
case 1
case 2
(cdadr exp)
(cddr exp))))
(define (definition-eval exp env)
(let ((var (definition-variable exp))
(val (eval (definition-value exp) env)))
(env-define-variable! var val env)
var))
;-----------------------------------
; If
; Special form
; (if condition consequent alternative)
(define (if? exp) (tagged-list? exp 'if))
(define (if-predicate exp) (cadr exp))
(define (if-consequent exp) (caddr exp))
; return false if there is no alternative
(define (if-alternative exp)
(if (null? (cdddr exp))
'false
(cadddr exp)))
(define (if-make predicate consequent alternative)
(list 'if predicate consequent alternative))
(define (if-eval exp env)
(if (true? (eval (if-predicate exp) env))
(eval (if-consequent exp) env)
(eval (if-alternative exp) env)))
;-----------------------------------
; lambda expression
; Special form
; (lambda (par1 par2) body-foo)
(define (lambda-make parameters body)
(cons 'lambda (cons parameters body)))
(define (lambda? exp) (tagged-list? exp 'lambda))
(define (lambda-parameters exp) (cadr exp))
(define (lambda-body exp) (cddr exp))
;-----------------------------------
; Procedures
(define (compound-procedure? procedure)
(tagged-list? procedure 'procedure))
(define (procedure-make parameters body env)
(list 'procedure parameters (scan-out-defines body) env))
(define (procedure-parameters procedure) (cadr procedure))
(define (procedure-body procedure) (caddr procedure))
(define (procedure-env procedure) (cadddr procedure))
Exercise 4.16
(define (scan-out-defines body)
(let ((defines (filter definition? body)))
(if (null? defines)
body
(let* ((body-without-defines
(filter (lambda (exp) (not (definition? exp)))
body))
(variables
(map (lambda (exp) (definition-variable exp))
defines))
(values
(map (lambda (exp) (definition-value exp))
defines))
(bindings
(map (lambda (var) (list var ''*unassigned*))
variables))
(assignments
(map (lambda (var val) (assignment-make var val))
variables values)))
(list (let-make bindings
(append assignments body-without-defines)))))))
;-----------------------------------
; Primitives from the underlying implementation
; (primitive impl)
(define primitive-procedures
(list (list 'car car)
(list 'cdr cdr)
(list 'cons cons)
(list 'null? null?)
(list 'display display)
(list '+ +)
(list '- -)
(list '* *)
(list '= =)
(list '< <)
(list '> >)
;; list more primitives here
))
(define (primitive-procedure? procedure)
(tagged-list? procedure 'primitive))
(define (primitive-implementation primitive)
(cadr primitive))
(define (primitive-procedure-names)
(map car
primitive-procedures))
(define (primitive-procedure-objects)
(map (lambda (proc) (list 'primitive (primitive-implementation proc)))
primitive-procedures))
(define (apply-primitive-procedure proc args)
(apply (primitive-implementation proc) args))
;-----------------------------------
; A sequence of expressions
; Special form
( begin expr1 expr2 ... )
(define (sequence? exp) (tagged-list? exp 'begin))
(define (sequence-actions exp) (cdr exp))
(define (sequence-make seq) (cons 'begin seq))
(define (sequence->exp seq)
(cond ((null? seq) seq)
((last-exp? seq) (first-exp seq))
(else (sequence-make seq))))
(define (sequence-eval exps env)
(cond ((last-exp? exps) (eval (first-exp exps) env))
(else (eval (first-exp exps) env)
(sequence-eval (rest-exps exps) env))))
;-----------------------------------
; A conditional expression
; special form derived expression
;
( cond ( )
( )
; (else alternative))
;
; is equivalent to
;
; (if (predicate1)
; consequent1
; (if (predicate2)
; alternative))
(define (cond? exp) (tagged-list? exp 'cond))
(define (cond-clauses exp) (cdr exp))
(define (cond-else-clause? clause)
(eq? (cond-predicate clause) 'else))
(define (cond-predicate clause) (car clause))
(define (cond-actions clause) (cdr clause))
(define (cond->if exp)
(expand-clauses (cond-clauses exp)))
(define (expand-clauses clauses)
(if (null? clauses)
'false
(let ((first (car clauses))
(rest (cdr clauses)))
(if (cond-else-clause? first)
(if (null? rest)
(sequence->exp (cond-actions first))
(error "else not last clause -- cond->if" clauses))
(if-make (cond-predicate first)
(sequence->exp (cond-actions first))
(expand-clauses rest))))))
;-----------------------------------
; Let special form
;
; let is of the form
; (let
( ( var1 exp1 ) ( var2 exp2 ) )
; body)
; which is equivalent to
( ( lambda ( var1 var2 ) body ) exp1 exp2 )
(define (let? exp) (tagged-list? exp 'let))
(define (named-let? exp) (not (pair? (cadr exp))))
(define (let-name exp)
(cond ((named-let? exp) (cadr exp))
(else '())))
(define (let-bindings exp)
(cond ((named-let? exp) (caddr exp))
(else (cadr exp))))
(define (let-body exp)
(cond ((named-let? exp) (cdddr exp))
(else (cddr exp))))
; Extract a list of variables from a let
(define (let-variables exp)
(let ((bindings (let-bindings exp)))
(map (lambda (binding) (car binding))
bindings)))
; Extract a list of expressions from a let
(define (let-expressions exp)
(let ((bindings (let-bindings exp)))
(map (lambda (binding) (cadr binding))
bindings)))
(define (let-make bindings body)
(cons 'let (cons bindings body)))
Exercise 4.6
Exercise 4.8
(define (let->combination exp)
(let ((variables (let-variables exp))
(expressions (let-expressions exp))
(body (let-body exp))
(name (let-name exp)))
(cond ((named-let? exp)
(let-make (list (list name ''*unassigned*))
(list (assignment-make name (lambda-make variables body))
(cons name expressions))))
(else
(cons (lambda-make variables body) expressions)))))
Exercise 4.7
(define (let*->nested-lets exp)
(car (expand-bindings (let-bindings exp) (let-body exp))))
(define (expand-bindings bindings body)
(if (null? bindings)
body
(list (let-make (list (first-exp bindings))
(expand-bindings (rest-exps bindings) body)))))
Exercise 4.20
(define (letrec->let exp)
(let* ((variables (let-variables exp))
(values (let-expressions exp))
(bindings (map (lambda (var) (list var ''*unassigned*)) variables))
(assignments (map (lambda (var val) (assignment-make var val))
variables values)))
(let-make bindings
(append assignments (let-body exp)))))
;-----------------------------------
; And, Or special forms
Exercise 4.4
(define (and? exp) (tagged-list? exp 'and))
(define (or? exp) (tagged-list? exp 'or))
(define (eval-and exps env)
(cond ((null? exps) true)
((last-exp? exps) (eval (first-exp exps) env))
((eval (first-exp exps) env) (eval-and (rest-exps exps) env))
(else false)))
(define (eval-or exps env)
(cond ((null? exps) false)
(else
(let ((first (eval (first-exp exps) env)))
(if first
first
(eval-or (rest-exps exps) env))))))
(define (and-expressions exp) (cdr exp))
(define (or-expressions exp) (cdr exp))
;-----------------------------------
; Eval
; evaluate an expression in the given environment
The old - style ( prior exercise 4.3 ) eval - procedure
; (define (eval exp env)
; (cond ((self-evaluating? exp) exp)
; ((variable? exp) (env-lookup-variable-value exp env))
; ((quoted? exp) (quote-text exp))
; ((assignment? exp) (assignment-eval exp env))
; ((definition? exp) (definition-eval exp env))
; ((if? exp) (if-eval exp env))
; ((lambda? exp)
; (procedure-make (lambda-parameters exp)
; (lambda-body exp)
; env))
; ((sequence? exp)
; (sequence-eval (sequence-actions exp) env))
; ((and? exp) (eval-and (and-expressions exp) env))
; ((or? exp) (eval-or (or-expressions exp) env))
; ((cond? exp) (eval (cond->if exp) env))
; ((let? exp) (eval (let->combination exp) env))
; ((application? exp)
; (myapply (eval (operator exp) env)
; (list-of-values (operands exp) env)))
; (else
; (error "Unknown expression type -- eval" exp))))
; Special forms
(put 'eval 'quote (lambda (exp env) (quote-text exp)))
(put 'eval 'set! (lambda (exp env) (assignment-eval exp env)))
(put 'eval 'define (lambda (exp env) (definition-eval exp env)))
(put 'eval 'if (lambda (exp env) (if-eval exp env)))
(put 'eval 'lambda (lambda (exp env) (procedure-make (lambda-parameters exp) (lambda-body exp) env)))
(put 'eval 'begin (lambda (exp env) (sequence-eval (sequence-actions exp) env)))
(put 'eval 'and (lambda (exp env) (eval-and (and-expressions exp) env)))
(put 'eval 'or (lambda (exp env) (eval-or (or-expressions exp) env)))
; Derived expressions
(put 'eval 'cond (lambda (exp env) (eval (cond->if exp) env)))
(put 'eval 'let (lambda (exp env) (eval (let->combination exp) env)))
(put 'eval 'let* (lambda (exp env) (eval (let*->nested-lets exp) env)))
(put 'eval 'letrec (lambda (exp env) (eval (letrec->let exp) env)))
Exercise 4.3 myeval.txt
(define (eval exp env)
(cond ((self-evaluating? exp) exp)
((variable? exp) (env-lookup-variable-value exp env))
(else
(let ((proc (get 'eval (car exp))))
(cond ((not (null? proc))
(proc exp env))
((application? exp)
(myapply (eval (operator exp) env)
(list-of-values (operands exp) env)))
(else
error "Unknown expression type -- EVAL" exp))))))
;-----------------------------------
; Driver
(define the-empty-environment (frame-make))
(define input-prompt ";;; MyEval input:")
(define output-prompt ";;; MyEval value:")
(define (driver-loop)
(prompt-for-input input-prompt)
(let ((input (read)))
(let ((output (eval input the-global-environment)))
(announce-output output-prompt)
(user-print output)))
(driver-loop))
(define (prompt-for-input string)
(newline) (newline) (display string) (newline))
(define (announce-output string)
(newline) (display string) (newline))
(define (user-print object)
(if (compound-procedure? object)
(display (list 'compound-procedure
(procedure-parameters object)
(procedure-body object)
'<procedure-env>))
(display object)))
(define (setup-environment)
(let ((initial-env
(env-extend (primitive-procedure-names)
(primitive-procedure-objects)
the-empty-environment)))
(env-define-variable! 'true true initial-env)
(env-define-variable! 'false false initial-env)
initial-env))
;;;Following are commented out so as not to be evaluated when
;;; the file is loaded.
; (define the-global-environment (setup-environment))
; (driver-loop)
| null | https://raw.githubusercontent.com/jarvinet/scheme/47633d7fc4d82d739a62ceec75c111f6549b1650/bin/test/myeval.scm | scheme | My evaluator
See myeval.txt for accompanying notes.
-----------------------------------
Misc
I think it is better not to rename this apply
and use name "myapply" for the apply defined in this evaluator
so multiple loadings of this file does not lose the original apply
(define apply-in-underlying-scheme apply)
-----------------------------------
to support operation/type table for data-directed dispatch
-----------------------------------
Binding is a name-value pair:
+-+-+
| | |
+-+-+
| |
V V
name value
-----------------------------------
Frame is a list of bindings, with a "head node" whose car is *frame*:
+-+-+ +-+-+ +-+-+
| | +------>| | |------>| |/|
+-+-+ +-+-+ +-+-+
| | |
V V V
*frame* +-+-+ +-+-+
| | | | | |
+-+-+ +-+-+
| | | |
V V V V
name value name value
-----------------------------------
Environment is a list of frames
-----------------------------------
Procedure application
A compound procedure is applied as follows:
of the application are bound to the parameters of the procedure.
The enclosing environment of the new frame is the environment
packaged with the procedure to be applied.
-----------------------------------
Self-evaluating expressions
-----------------------------------
Variables
-----------------------------------
Quotation
Special form
'foo
-----------------------------------
Assignment
Special form
-----------------------------------
Definition
case 1 ( Special form )
case 2 ( Derived expression )
(define foo (lambda (bar) body))
-----------------------------------
If
Special form
(if condition consequent alternative)
return false if there is no alternative
-----------------------------------
lambda expression
Special form
(lambda (par1 par2) body-foo)
-----------------------------------
Procedures
-----------------------------------
Primitives from the underlying implementation
(primitive impl)
list more primitives here
-----------------------------------
A sequence of expressions
Special form
-----------------------------------
A conditional expression
special form derived expression
(else alternative))
is equivalent to
(if (predicate1)
consequent1
(if (predicate2)
alternative))
-----------------------------------
Let special form
let is of the form
(let
body)
which is equivalent to
Extract a list of variables from a let
Extract a list of expressions from a let
-----------------------------------
And, Or special forms
-----------------------------------
Eval
evaluate an expression in the given environment
(define (eval exp env)
(cond ((self-evaluating? exp) exp)
((variable? exp) (env-lookup-variable-value exp env))
((quoted? exp) (quote-text exp))
((assignment? exp) (assignment-eval exp env))
((definition? exp) (definition-eval exp env))
((if? exp) (if-eval exp env))
((lambda? exp)
(procedure-make (lambda-parameters exp)
(lambda-body exp)
env))
((sequence? exp)
(sequence-eval (sequence-actions exp) env))
((and? exp) (eval-and (and-expressions exp) env))
((or? exp) (eval-or (or-expressions exp) env))
((cond? exp) (eval (cond->if exp) env))
((let? exp) (eval (let->combination exp) env))
((application? exp)
(myapply (eval (operator exp) env)
(list-of-values (operands exp) env)))
(else
(error "Unknown expression type -- eval" exp))))
Special forms
Derived expressions
-----------------------------------
Driver
Following are commented out so as not to be evaluated when
the file is loaded.
(define the-global-environment (setup-environment))
(driver-loop) | Structure and Interpretation of Computer Programs , 2nd edition
(define (tagged-list? exp tag)
(if (pair? exp)
(eq? (car exp) tag)
false))
(define (list-of-values operands env)
(if (null? operands)
'()
(cons (eval (car operands) env)
(list-of-values (cdr operands) env))))
(define (true? x) (not (eq? x false)))
(define (false? x) (eq? x false))
(define (last-exp? seq) (null? (cdr seq)))
(define (first-exp seq) (car seq))
(define (rest-exps seq) (cdr seq))
(define (filter predicate stream)
(cond ((null? stream)
'())
((predicate (car stream))
(cons (car stream) (filter predicate (cdr stream))))
(else (filter predicate (cdr stream)))))
Table operations from section 3.3.3
(define (assoc key records)
(cond ((null? records) false)
((equal? key (caar records)) (car records))
(else (assoc key (cdr records)))))
(define (make-table)
(let ((local-table (list '*table*)))
(define (lookup key-1 key-2)
(let ((subtable (assoc key-1 (cdr local-table))))
(if subtable
(let ((record (assoc key-2 (cdr subtable))))
(if record
(cdr record)
false))
false)))
(define (insert! key-1 key-2 value)
(let ((subtable (assoc key-1 (cdr local-table))))
(if subtable
(let ((record (assoc key-2 (cdr subtable))))
(if record
(set-cdr! record value)
(set-cdr! subtable
(cons (cons key-2 value)
(cdr subtable)))))
(set-cdr! local-table
(cons (list key-1
(cons key-2 value))
(cdr local-table)))))
'ok)
(define (dispatch m)
(cond ((eq? m 'lookup-proc) lookup)
((eq? m 'insert-proc!) insert!)
(else (error "Unknown operation -- TABLE" m))))
dispatch))
(define operation-table (make-table))
(define get (operation-table 'lookup-proc))
(define put (operation-table 'insert-proc!))
(define (binding-make name value) (cons name value))
(define (binding-name binding) (car binding))
(define (binding-value binding) (cdr binding))
(define (binding-set-value! binding new-value)
(set-cdr! binding new-value))
(define (frame-make)
(cons '*frame* '()))
(define (frame-add-binding! binding frame)
(let ((pair (cons binding (cdr frame))))
(set-cdr! frame pair)))
(define (frame-lookup-binding frame name)
(define (iter bindings)
(if (null? bindings)
'()
(let ((binding (car bindings)))
(if (eq? (binding-name binding) name)
binding
(iter (cdr bindings))))))
(iter (cdr frame)))
(define (first-frame env) (car env))
(define (env-enclosing-environment env) (cdr env))
(define (env-lookup-binding env name)
(define (env-loop env)
(if (eq? env the-empty-environment)
'()
(let ((frame (first-frame env)))
(let ((binding (frame-lookup-binding frame name)))
(if (null? binding)
(env-loop (env-enclosing-environment env))
binding)))))
(env-loop env))
(define (env-extend vars vals base-env)
(if (= (length vars) (length vals))
(let ((frame (frame-make)))
(define (loop frame vars vals)
(if (null? vars)
frame
(begin (frame-add-binding!
(binding-make (car vars) (car vals))
frame)
(loop frame (cdr vars) (cdr vals)))))
(loop frame vars vals)
(cons frame base-env))
(if (< (length vars) (length vals))
(error "Too many arguments supplied" vars vals)
(error "Too few arguments supplied" vars vals))))
(define (env-lookup-variable-value var env)
(let ((binding (env-lookup-binding env var)))
(if (null? binding)
(error "Unbound variable" var)
(let ((value (binding-value binding)))
(if (eq? value '*unassigned*)
(error "Unassigned variable" var)
value)))))
(define (env-set-variable-value! var val env)
(let ((binding (env-lookup-binding env var)))
(if (null? binding)
(error "Unbound variable -- SET!" var)
(binding-set-value! binding val))))
(define (env-define-variable! var val env)
(let ((frame (first-frame env)))
(let ((binding (frame-lookup-binding frame var)))
(if (null? binding)
(frame-add-binding! (binding-make var val) frame)
(binding-set-value! binding val)))))
( foo 1 2 )
(define (application? exp) (pair? exp))
(define (operator exp) (car exp))
(define (operands exp) (cdr exp))
1 ) Create a new frame ( extend environment ) where the operands
2 ) The body of the procedure is evaluated in the new environment .
(define (myapply procedure arguments)
(cond ((primitive-procedure? procedure)
(apply-primitive-procedure procedure arguments))
((compound-procedure? procedure)
(sequence-eval (procedure-body procedure)
(env-extend
(procedure-parameters procedure)
arguments
(procedure-env procedure))))
(else
(error "Unknown procedure type - myapply"
procedure))))
(define (self-evaluating? exp)
(cond ((number? exp) true)
((string? exp) true)
(else false)))
(define (variable? exp) (symbol? exp))
(define (quoted? exp) (tagged-list? exp 'quote))
(define (quote-text exp) (cadr exp))
( set ! foo 1 )
(define (assignment? exp) (tagged-list? exp 'set!))
(define (assignment-variable exp) (cadr exp))
(define (assignment-value exp) (caddr exp))
(define (assignment-make variable value)
(list 'set! variable value))
(define (assignment-eval exp env)
(let ((var (assignment-variable exp))
(value (eval (assignment-value exp) env)))
(env-set-variable-value! var value env)
var))
case 2 can be converted to an equivalent case 1 form :
(define (definition? exp)
(tagged-list? exp 'define))
(define (definition-variable exp)
(if (symbol? (cadr exp))
case 1
case 2
(define (definition-value exp)
(if (symbol? (cadr exp))
case 1
case 2
(cdadr exp)
(cddr exp))))
(define (definition-eval exp env)
(let ((var (definition-variable exp))
(val (eval (definition-value exp) env)))
(env-define-variable! var val env)
var))
(define (if? exp) (tagged-list? exp 'if))
(define (if-predicate exp) (cadr exp))
(define (if-consequent exp) (caddr exp))
(define (if-alternative exp)
(if (null? (cdddr exp))
'false
(cadddr exp)))
(define (if-make predicate consequent alternative)
(list 'if predicate consequent alternative))
(define (if-eval exp env)
(if (true? (eval (if-predicate exp) env))
(eval (if-consequent exp) env)
(eval (if-alternative exp) env)))
(define (lambda-make parameters body)
(cons 'lambda (cons parameters body)))
(define (lambda? exp) (tagged-list? exp 'lambda))
(define (lambda-parameters exp) (cadr exp))
(define (lambda-body exp) (cddr exp))
(define (compound-procedure? procedure)
(tagged-list? procedure 'procedure))
(define (procedure-make parameters body env)
(list 'procedure parameters (scan-out-defines body) env))
(define (procedure-parameters procedure) (cadr procedure))
(define (procedure-body procedure) (caddr procedure))
(define (procedure-env procedure) (cadddr procedure))
Exercise 4.16
(define (scan-out-defines body)
(let ((defines (filter definition? body)))
(if (null? defines)
body
(let* ((body-without-defines
(filter (lambda (exp) (not (definition? exp)))
body))
(variables
(map (lambda (exp) (definition-variable exp))
defines))
(values
(map (lambda (exp) (definition-value exp))
defines))
(bindings
(map (lambda (var) (list var ''*unassigned*))
variables))
(assignments
(map (lambda (var val) (assignment-make var val))
variables values)))
(list (let-make bindings
(append assignments body-without-defines)))))))
(define primitive-procedures
(list (list 'car car)
(list 'cdr cdr)
(list 'cons cons)
(list 'null? null?)
(list 'display display)
(list '+ +)
(list '- -)
(list '* *)
(list '= =)
(list '< <)
(list '> >)
))
(define (primitive-procedure? procedure)
(tagged-list? procedure 'primitive))
(define (primitive-implementation primitive)
(cadr primitive))
(define (primitive-procedure-names)
(map car
primitive-procedures))
(define (primitive-procedure-objects)
(map (lambda (proc) (list 'primitive (primitive-implementation proc)))
primitive-procedures))
(define (apply-primitive-procedure proc args)
(apply (primitive-implementation proc) args))
( begin expr1 expr2 ... )
(define (sequence? exp) (tagged-list? exp 'begin))
(define (sequence-actions exp) (cdr exp))
(define (sequence-make seq) (cons 'begin seq))
(define (sequence->exp seq)
(cond ((null? seq) seq)
((last-exp? seq) (first-exp seq))
(else (sequence-make seq))))
(define (sequence-eval exps env)
(cond ((last-exp? exps) (eval (first-exp exps) env))
(else (eval (first-exp exps) env)
(sequence-eval (rest-exps exps) env))))
( cond ( )
( )
(define (cond? exp) (tagged-list? exp 'cond))
(define (cond-clauses exp) (cdr exp))
(define (cond-else-clause? clause)
(eq? (cond-predicate clause) 'else))
(define (cond-predicate clause) (car clause))
(define (cond-actions clause) (cdr clause))
(define (cond->if exp)
(expand-clauses (cond-clauses exp)))
(define (expand-clauses clauses)
(if (null? clauses)
'false
(let ((first (car clauses))
(rest (cdr clauses)))
(if (cond-else-clause? first)
(if (null? rest)
(sequence->exp (cond-actions first))
(error "else not last clause -- cond->if" clauses))
(if-make (cond-predicate first)
(sequence->exp (cond-actions first))
(expand-clauses rest))))))
( ( var1 exp1 ) ( var2 exp2 ) )
( ( lambda ( var1 var2 ) body ) exp1 exp2 )
(define (let? exp) (tagged-list? exp 'let))
(define (named-let? exp) (not (pair? (cadr exp))))
(define (let-name exp)
(cond ((named-let? exp) (cadr exp))
(else '())))
(define (let-bindings exp)
(cond ((named-let? exp) (caddr exp))
(else (cadr exp))))
(define (let-body exp)
(cond ((named-let? exp) (cdddr exp))
(else (cddr exp))))
(define (let-variables exp)
(let ((bindings (let-bindings exp)))
(map (lambda (binding) (car binding))
bindings)))
(define (let-expressions exp)
(let ((bindings (let-bindings exp)))
(map (lambda (binding) (cadr binding))
bindings)))
(define (let-make bindings body)
(cons 'let (cons bindings body)))
Exercise 4.6
Exercise 4.8
(define (let->combination exp)
(let ((variables (let-variables exp))
(expressions (let-expressions exp))
(body (let-body exp))
(name (let-name exp)))
(cond ((named-let? exp)
(let-make (list (list name ''*unassigned*))
(list (assignment-make name (lambda-make variables body))
(cons name expressions))))
(else
(cons (lambda-make variables body) expressions)))))
Exercise 4.7
(define (let*->nested-lets exp)
(car (expand-bindings (let-bindings exp) (let-body exp))))
(define (expand-bindings bindings body)
(if (null? bindings)
body
(list (let-make (list (first-exp bindings))
(expand-bindings (rest-exps bindings) body)))))
Exercise 4.20
(define (letrec->let exp)
(let* ((variables (let-variables exp))
(values (let-expressions exp))
(bindings (map (lambda (var) (list var ''*unassigned*)) variables))
(assignments (map (lambda (var val) (assignment-make var val))
variables values)))
(let-make bindings
(append assignments (let-body exp)))))
Exercise 4.4
(define (and? exp) (tagged-list? exp 'and))
(define (or? exp) (tagged-list? exp 'or))
(define (eval-and exps env)
(cond ((null? exps) true)
((last-exp? exps) (eval (first-exp exps) env))
((eval (first-exp exps) env) (eval-and (rest-exps exps) env))
(else false)))
(define (eval-or exps env)
(cond ((null? exps) false)
(else
(let ((first (eval (first-exp exps) env)))
(if first
first
(eval-or (rest-exps exps) env))))))
(define (and-expressions exp) (cdr exp))
(define (or-expressions exp) (cdr exp))
The old - style ( prior exercise 4.3 ) eval - procedure
(put 'eval 'quote (lambda (exp env) (quote-text exp)))
(put 'eval 'set! (lambda (exp env) (assignment-eval exp env)))
(put 'eval 'define (lambda (exp env) (definition-eval exp env)))
(put 'eval 'if (lambda (exp env) (if-eval exp env)))
(put 'eval 'lambda (lambda (exp env) (procedure-make (lambda-parameters exp) (lambda-body exp) env)))
(put 'eval 'begin (lambda (exp env) (sequence-eval (sequence-actions exp) env)))
(put 'eval 'and (lambda (exp env) (eval-and (and-expressions exp) env)))
(put 'eval 'or (lambda (exp env) (eval-or (or-expressions exp) env)))
(put 'eval 'cond (lambda (exp env) (eval (cond->if exp) env)))
(put 'eval 'let (lambda (exp env) (eval (let->combination exp) env)))
(put 'eval 'let* (lambda (exp env) (eval (let*->nested-lets exp) env)))
(put 'eval 'letrec (lambda (exp env) (eval (letrec->let exp) env)))
Exercise 4.3 myeval.txt
(define (eval exp env)
(cond ((self-evaluating? exp) exp)
((variable? exp) (env-lookup-variable-value exp env))
(else
(let ((proc (get 'eval (car exp))))
(cond ((not (null? proc))
(proc exp env))
((application? exp)
(myapply (eval (operator exp) env)
(list-of-values (operands exp) env)))
(else
error "Unknown expression type -- EVAL" exp))))))
(define the-empty-environment (frame-make))
(define input-prompt ";;; MyEval input:")
(define output-prompt ";;; MyEval value:")
(define (driver-loop)
(prompt-for-input input-prompt)
(let ((input (read)))
(let ((output (eval input the-global-environment)))
(announce-output output-prompt)
(user-print output)))
(driver-loop))
(define (prompt-for-input string)
(newline) (newline) (display string) (newline))
(define (announce-output string)
(newline) (display string) (newline))
(define (user-print object)
(if (compound-procedure? object)
(display (list 'compound-procedure
(procedure-parameters object)
(procedure-body object)
'<procedure-env>))
(display object)))
(define (setup-environment)
(let ((initial-env
(env-extend (primitive-procedure-names)
(primitive-procedure-objects)
the-empty-environment)))
(env-define-variable! 'true true initial-env)
(env-define-variable! 'false false initial-env)
initial-env))
|
e830586686d5ffd8d34982229aa5e1f15720f137bc5a4fe8e31b59dae93f76cc | simonmar/parconc-examples | Substitution.hs | --
-- Adapted from the program "infer", believed to have been originally
authored by , and used in the nofib benchmark suite
since at least the late 90s .
--
module Substitution (Sub, applySub, lookupSub, emptySub, extendSub,
makeSub, thenSub, domSub, unifySub)
where
import Type
import FiniteMap
import MaybeM
data Sub = MkSub (FM TVarId MonoType)
rep :: Sub -> FM TVarId MonoType
rep (MkSub f) = f
applySub :: Sub -> MonoType -> MonoType
applySub s (TVar x) = lookupSub s x
applySub s (TCon k ts) = TCon k (map (applySub s) ts)
lookupSub :: Sub -> TVarId -> MonoType
lookupSub s x = lookupElseFM (TVar x) (rep s) x
unitSub :: TVarId -> MonoType -> Sub
unitSub x t = MkSub (makeFM [(x,t)])
emptySub :: Sub
emptySub = MkSub emptyFM
makeSub :: [(TVarId, MonoType)] -> Sub
makeSub xts = MkSub (makeFM xts)
extendSub :: Sub -> TVarId -> MonoType -> Sub
extendSub s x t = s `thenSub` unitSub x (applySub s t)
thenSub :: Sub -> Sub -> Sub
r `thenSub` s = MkSub (mapFM (applySub s) (rep r) `thenFM` rep s)
domSub :: Sub -> [TVarId]
domSub s = domFM (rep s)
unifySub = unify
unify :: MonoType -> MonoType -> Sub -> Maybe Sub
unify (TVar x) u s = unifyTVar x u s
unify t (TVar y) s = unifyTVar y t s
unify (TCon j ts) (TCon k us) s = (j == k) `guardM` unifies ts us s
unifies :: [MonoType] -> [MonoType] -> Sub -> Maybe Sub
unifies [] [] s = returnM s
unifies (t:ts) (u:us) s = unify t u s `thenM` (\s' -> unifies ts us s')
unifyTVar :: TVarId -> MonoType -> Sub -> Maybe Sub
unifyTVar x t s | x `elem` domSub s = unify (lookupSub s x) t s
| TVar x == t = returnM s
| x `elem` freeVars t = failM
| otherwise = returnM (extendSub s x t)
freeVars = freeTVarMono
| null | https://raw.githubusercontent.com/simonmar/parconc-examples/840a3f508f9bb6e03961e1b90311a1edd945adba/parinfer/Substitution.hs | haskell |
Adapted from the program "infer", believed to have been originally
| authored by , and used in the nofib benchmark suite
since at least the late 90s .
module Substitution (Sub, applySub, lookupSub, emptySub, extendSub,
makeSub, thenSub, domSub, unifySub)
where
import Type
import FiniteMap
import MaybeM
data Sub = MkSub (FM TVarId MonoType)
rep :: Sub -> FM TVarId MonoType
rep (MkSub f) = f
applySub :: Sub -> MonoType -> MonoType
applySub s (TVar x) = lookupSub s x
applySub s (TCon k ts) = TCon k (map (applySub s) ts)
lookupSub :: Sub -> TVarId -> MonoType
lookupSub s x = lookupElseFM (TVar x) (rep s) x
unitSub :: TVarId -> MonoType -> Sub
unitSub x t = MkSub (makeFM [(x,t)])
emptySub :: Sub
emptySub = MkSub emptyFM
makeSub :: [(TVarId, MonoType)] -> Sub
makeSub xts = MkSub (makeFM xts)
extendSub :: Sub -> TVarId -> MonoType -> Sub
extendSub s x t = s `thenSub` unitSub x (applySub s t)
thenSub :: Sub -> Sub -> Sub
r `thenSub` s = MkSub (mapFM (applySub s) (rep r) `thenFM` rep s)
domSub :: Sub -> [TVarId]
domSub s = domFM (rep s)
unifySub = unify
unify :: MonoType -> MonoType -> Sub -> Maybe Sub
unify (TVar x) u s = unifyTVar x u s
unify t (TVar y) s = unifyTVar y t s
unify (TCon j ts) (TCon k us) s = (j == k) `guardM` unifies ts us s
unifies :: [MonoType] -> [MonoType] -> Sub -> Maybe Sub
unifies [] [] s = returnM s
unifies (t:ts) (u:us) s = unify t u s `thenM` (\s' -> unifies ts us s')
unifyTVar :: TVarId -> MonoType -> Sub -> Maybe Sub
unifyTVar x t s | x `elem` domSub s = unify (lookupSub s x) t s
| TVar x == t = returnM s
| x `elem` freeVars t = failM
| otherwise = returnM (extendSub s x t)
freeVars = freeTVarMono
|
c9ec85385941237621f176b9565cad380daa8632cb4fe9ab9d7e559a9e85f6a8 | kevinchevalier/kemulator | Main.hs | module Main where
import System.Environment
import NES
import Cartridge
import DataTypes
import CPU6502
import Data.Word
import Control.Monad.State
import Util
import Control.Monad.IO.Class
import OpCodes
import Timing
import System.IO
import Disassembler
startup :: Operation ()
startup = do
interrupt Reset
runLoop :: Handle -> Operation ()
runLoop handle = do
-- Get the next command.
outputCommand handle
nesTick
runLoop handle
-- Run the command.
push2Test :: Operation ()
push2Test = do
push2 0xFFCC
a <- pop2
liftIO $ printHex16 "Popped" a
main :: IO ()
main = do
args <- getArgs
c <- loadNESFile (head args)
file <- openFile "trace.trace" WriteMode
case c of
Just cart -> do
let nes = initNES cart
putStrLn "Cartridge"
putStrLn . show . cpu $ nes
(val', status') <- runStateT startup nes
(val'', status'') <- runStateT (runLoop file) status'
return ()
Nothing -> putStrLn "Nothing"
| null | https://raw.githubusercontent.com/kevinchevalier/kemulator/f8bbaad5105f89006fbed8fe58a193fb5bfced8d/Main.hs | haskell | Get the next command.
Run the command. | module Main where
import System.Environment
import NES
import Cartridge
import DataTypes
import CPU6502
import Data.Word
import Control.Monad.State
import Util
import Control.Monad.IO.Class
import OpCodes
import Timing
import System.IO
import Disassembler
startup :: Operation ()
startup = do
interrupt Reset
runLoop :: Handle -> Operation ()
runLoop handle = do
outputCommand handle
nesTick
runLoop handle
push2Test :: Operation ()
push2Test = do
push2 0xFFCC
a <- pop2
liftIO $ printHex16 "Popped" a
main :: IO ()
main = do
args <- getArgs
c <- loadNESFile (head args)
file <- openFile "trace.trace" WriteMode
case c of
Just cart -> do
let nes = initNES cart
putStrLn "Cartridge"
putStrLn . show . cpu $ nes
(val', status') <- runStateT startup nes
(val'', status'') <- runStateT (runLoop file) status'
return ()
Nothing -> putStrLn "Nothing"
|
86ef9ac97bb88ae63d9a2e70a5fc6e1cbc9b8cba8260651a9e000a5e978fd558 | no-defun-allowed/concurrent-hash-tables | phony-redis-serial-hash-table.lisp | (defpackage :phony-redis
(:use :cl)
(:export #:make-server #:connect-to-server
#:find-value #:close-connection))
(in-package :phony-redis)
(defun make-server ()
(list
(bt:make-lock)
(make-hash-table :test #'equal)))
(defun connect-to-server (server)
server)
(defun find-value (connection name)
(bt:with-lock-held ((first connection))
(gethash name (second connection))))
(defun (setf find-value) (value connection name)
(bt:with-lock-held ((first connection))
(setf (gethash name (second connection))
value)))
(defun close-connection (connection)
(declare (ignore connection))
(values))
| null | https://raw.githubusercontent.com/no-defun-allowed/concurrent-hash-tables/1b9f0b5da54fece4f42296e1bdacfcec0c370a5a/Examples/phony-redis-serial-hash-table.lisp | lisp | (defpackage :phony-redis
(:use :cl)
(:export #:make-server #:connect-to-server
#:find-value #:close-connection))
(in-package :phony-redis)
(defun make-server ()
(list
(bt:make-lock)
(make-hash-table :test #'equal)))
(defun connect-to-server (server)
server)
(defun find-value (connection name)
(bt:with-lock-held ((first connection))
(gethash name (second connection))))
(defun (setf find-value) (value connection name)
(bt:with-lock-held ((first connection))
(setf (gethash name (second connection))
value)))
(defun close-connection (connection)
(declare (ignore connection))
(values))
| |
2bffad1a547ccad0355af07d0b9e47cc40a5cae230018d07c902a4c924a943da | mhwombat/grid | Grid.hs | -----------------------------------------------------------------------------
-- |
-- Module : Math.Geometry.Grid
Copyright : ( c ) 2012 - 2022
-- License : BSD-style
-- Maintainer :
-- Stability : experimental
-- Portability : portable
--
-- A regular arrangement of tiles. Grids have a variety of uses,
-- including games and self-organising maps.
-- The userguide is available at
-- <>.
--
In this package , tiles are called " , \"square\ " , etc . ,
-- based on the number of /neighbours/ they have.
For example , a square tile has four neighbours , and a hexagonal
tile has six .
There are only three regular polygons that can tile a plane :
-- triangles, squares, and hexagons.
-- Of course, other plane tilings are possible if you use irregular
-- polygons, or curved shapes, or if you combine tiles of different
-- shapes.
--
-- When you tile other surfaces, things get very interesting.
Octagons will tile a /hyperbolic/ plane .
-- (Alternatively, you can think of these as squares on a board game
-- where diagonal moves are allowed.)
--
-- For a board game, you probably want to choose the grid type based
-- on the number of /directions/ a player can move, rather than the
-- number of sides the tile will have when you display it.
-- For example, for a game that uses square tiles and allows the user
-- to move diagonally as well as horizontally and vertically,
consider using one of the grids with /octagonal/ tiles to model the
-- board.
-- You can still /display/ the tiles as squares, but for internal
-- calculations they are octagons.
--
NOTE : Version 6.0 moved the various grid flavours to sub - modules .
--
NOTE : Version 4.0 uses associated ( type ) synonyms instead of
-- multi-parameter type classes.
--
NOTE : Version 3.0 changed the order of parameters for many functions .
-- This makes it easier for the user to write mapping and folding
-- operations.
--
-----------------------------------------------------------------------------
# LANGUAGE FlexibleInstances #
# LANGUAGE MultiParamTypeClasses #
module Math.Geometry.Grid
(
-- * Example
-- $Example
-- * Grids
Grid(indices, distance, minDistance, neighbours, neighbour,
contains, tileCount, null, nonNull, edges, viewpoint,
isAdjacent, adjacentTilesToward, minimalPaths, directionTo),
Index,
Direction,
-- * Finite grids
FiniteGrid(..),
-- * Bounded grids
BoundedGrid(..)
) where
import Math.Geometry.GridInternal (BoundedGrid (..), FiniteGrid (..), Grid (..))
$ Example
Create a grid .
> ghci > let g =
> ghci > indices g
> [ ( -2,0),(-2,1),(-2,2),(-1,-1),(-1,0),(-1,1),(-1,2),(0,-2),(0,-1),(0,0),(0,1),(0,2),(1,-2),(1,-1),(1,0),(1,1),(2,-2),(2,-1),(2,0 ) ]
Find out if the specified index is contained within the grid .
> ghci > g ` contains ` ( 0,-2 )
> True
> ghci > g ` contains ` ( 99,99 )
> False
Find out the minimum number of moves to go from one tile in a grid to
another tile , moving between adjacent tiles at each step .
> ghci > distance g ( 0,-2 ) ( 0,2 )
> 4
Find out the minimum number of moves to go from one tile in a grid to
any other tile , moving between adjacent tiles at each step .
> ghci > viewpoint ( 1,-2 )
> [ ( ( ) ]
Find out which tiles are adjacent to a particular tile .
> ghci > neighbours ( -1,1 )
> [ ( -2,1),(-2,2),(-1,2),(0,1),(0,0),(-1,0 ) ]
Find how many tiles are adjacent to a particular tile .
( Note that the result is consistent with the result from the previous
step . )
> ghci ( -1,1 )
> 6
Find out if an index is valid for the grid .
> ghci > g ` contains ` ( 0,0 )
> True
> ghci > g ` contains ` ( 0,12 )
> False
Find out the physical dimensions of the grid .
> ghci > size g
> 3
Get the list of boundary tiles for a grid .
> ghci > boundary g
> [ ( ) ]
Find out the number of tiles in the grid .
> ghci > tileCount g
> 19
Check if a grid is null ( contains no tiles ) .
> ghci > null g
> False
> ghci >
> True
Find the central tile(s ) ( the tile(s ) furthest from the boundary ) .
> ghci > centre g
> [ ( 0,0 ) ]
Find all of the minimal paths between two points .
> ghci > let g =
> ghci > ( 0,0 ) ( 2,-1 )
> [ [ ( 0,0),(1,0),(2,-1)],[(0,0),(1,-1),(2,-1 ) ] ]
Find all of the pairs of tiles that are adjacent .
> ghci > edges g
> [ ( ( -2,0),(-2,1)),((-2,0),(-1,0)),((-2,0),(-1,-1)),((-2,1),(-2,2)),((-2,1),(-1,1)),((-2,1),(-1,0)),((-2,2),(-1,2)),((-2,2),(-1,1)),((-1,-1),(-1,0)),((-1,-1),(0,-1)),((-1,-1),(0,-2)),((-1,0),(-1,1)),((-1,0),(0,0)),((-1,0),(0,-1)),((-1,1),(-1,2)),((-1,1),(0,1)),((-1,1),(0,0)),((-1,2),(0,2)),((-1,2),(0,1)),((0,-2),(0,-1)),((0,-2),(1,-2)),((0,-1),(0,0)),((0,-1),(1,-1)),((0,-1),(1,-2)),((0,0),(0,1)),((0,0),(1,0)),((0,0),(1,-1)),((0,1),(0,2)),((0,1),(1,1)),((0,1),(1,0)),((0,2),(1,1)),((1,-2),(1,-1)),((1,-2),(2,-2)),((1,-1),(1,0)),((1,-1),(2,-1)),((1,-1),(2,-2)),((1,0),(1,1)),((1,0),(2,0)),((1,0),(2,-1)),((1,1),(2,0)),((2,-2),(2,-1)),((2,-1),(2,0 ) ) ]
Find out if two tiles are adjacent .
> ghci > isAdjacent g ( -2,0 ) ( -2,1 )
> True
> ghci > isAdjacent g ( -2,0 ) ( 0,1 )
> False
Create a grid.
>ghci> let g = hexHexGrid 3
>ghci> indices g
>[(-2,0),(-2,1),(-2,2),(-1,-1),(-1,0),(-1,1),(-1,2),(0,-2),(0,-1),(0,0),(0,1),(0,2),(1,-2),(1,-1),(1,0),(1,1),(2,-2),(2,-1),(2,0)]
Find out if the specified index is contained within the grid.
>ghci> g `contains` (0,-2)
>True
>ghci> g `contains` (99,99)
>False
Find out the minimum number of moves to go from one tile in a grid to
another tile, moving between adjacent tiles at each step.
>ghci> distance g (0,-2) (0,2)
>4
Find out the minimum number of moves to go from one tile in a grid to
any other tile, moving between adjacent tiles at each step.
>ghci> viewpoint g (1,-2)
>[((-2,0),3),((-2,1),3),((-2,2),4),((-1,-1),2),((-1,0),2),((-1,1),3),((-1,2),4),((0,-2),1),((0,-1),1),((0,0),2),((0,1),3),((0,2),4),((1,-2),0),((1,-1),1),((1,0),2),((1,1),3),((2,-2),1),((2,-1),2),((2,0),3)]
Find out which tiles are adjacent to a particular tile.
>ghci> neighbours g (-1,1)
>[(-2,1),(-2,2),(-1,2),(0,1),(0,0),(-1,0)]
Find how many tiles are adjacent to a particular tile.
(Note that the result is consistent with the result from the previous
step.)
>ghci> numNeighbours g (-1,1)
>6
Find out if an index is valid for the grid.
>ghci> g `contains` (0,0)
>True
>ghci> g `contains` (0,12)
>False
Find out the physical dimensions of the grid.
>ghci> size g
>3
Get the list of boundary tiles for a grid.
>ghci> boundary g
>[(-2,2),(-1,2),(0,2),(1,1),(2,0),(2,-1),(2,-2),(1,-2),(0,-2),(-1,-1),(-2,0),(-2,1)]
Find out the number of tiles in the grid.
>ghci> tileCount g
>19
Check if a grid is null (contains no tiles).
>ghci> null g
>False
>ghci> nonNull g
>True
Find the central tile(s) (the tile(s) furthest from the boundary).
>ghci> centre g
>[(0,0)]
Find all of the minimal paths between two points.
>ghci> let g = hexHexGrid 3
>ghci> minimalPaths g (0,0) (2,-1)
>[[(0,0),(1,0),(2,-1)],[(0,0),(1,-1),(2,-1)]]
Find all of the pairs of tiles that are adjacent.
>ghci> edges g
>[((-2,0),(-2,1)),((-2,0),(-1,0)),((-2,0),(-1,-1)),((-2,1),(-2,2)),((-2,1),(-1,1)),((-2,1),(-1,0)),((-2,2),(-1,2)),((-2,2),(-1,1)),((-1,-1),(-1,0)),((-1,-1),(0,-1)),((-1,-1),(0,-2)),((-1,0),(-1,1)),((-1,0),(0,0)),((-1,0),(0,-1)),((-1,1),(-1,2)),((-1,1),(0,1)),((-1,1),(0,0)),((-1,2),(0,2)),((-1,2),(0,1)),((0,-2),(0,-1)),((0,-2),(1,-2)),((0,-1),(0,0)),((0,-1),(1,-1)),((0,-1),(1,-2)),((0,0),(0,1)),((0,0),(1,0)),((0,0),(1,-1)),((0,1),(0,2)),((0,1),(1,1)),((0,1),(1,0)),((0,2),(1,1)),((1,-2),(1,-1)),((1,-2),(2,-2)),((1,-1),(1,0)),((1,-1),(2,-1)),((1,-1),(2,-2)),((1,0),(1,1)),((1,0),(2,0)),((1,0),(2,-1)),((1,1),(2,0)),((2,-2),(2,-1)),((2,-1),(2,0))]
Find out if two tiles are adjacent.
>ghci> isAdjacent g (-2,0) (-2,1)
>True
>ghci> isAdjacent g (-2,0) (0,1)
>False
-}
| null | https://raw.githubusercontent.com/mhwombat/grid/b8c4a928733494f4a410127d6ae007857de921f9/src/Math/Geometry/Grid.hs | haskell | ---------------------------------------------------------------------------
|
Module : Math.Geometry.Grid
License : BSD-style
Maintainer :
Stability : experimental
Portability : portable
A regular arrangement of tiles. Grids have a variety of uses,
including games and self-organising maps.
The userguide is available at
<>.
based on the number of /neighbours/ they have.
triangles, squares, and hexagons.
Of course, other plane tilings are possible if you use irregular
polygons, or curved shapes, or if you combine tiles of different
shapes.
When you tile other surfaces, things get very interesting.
(Alternatively, you can think of these as squares on a board game
where diagonal moves are allowed.)
For a board game, you probably want to choose the grid type based
on the number of /directions/ a player can move, rather than the
number of sides the tile will have when you display it.
For example, for a game that uses square tiles and allows the user
to move diagonally as well as horizontally and vertically,
board.
You can still /display/ the tiles as squares, but for internal
calculations they are octagons.
multi-parameter type classes.
This makes it easier for the user to write mapping and folding
operations.
---------------------------------------------------------------------------
* Example
$Example
* Grids
* Finite grids
* Bounded grids | Copyright : ( c ) 2012 - 2022
In this package , tiles are called " , \"square\ " , etc . ,
For example , a square tile has four neighbours , and a hexagonal
tile has six .
There are only three regular polygons that can tile a plane :
Octagons will tile a /hyperbolic/ plane .
consider using one of the grids with /octagonal/ tiles to model the
NOTE : Version 6.0 moved the various grid flavours to sub - modules .
NOTE : Version 4.0 uses associated ( type ) synonyms instead of
NOTE : Version 3.0 changed the order of parameters for many functions .
# LANGUAGE FlexibleInstances #
# LANGUAGE MultiParamTypeClasses #
module Math.Geometry.Grid
(
Grid(indices, distance, minDistance, neighbours, neighbour,
contains, tileCount, null, nonNull, edges, viewpoint,
isAdjacent, adjacentTilesToward, minimalPaths, directionTo),
Index,
Direction,
FiniteGrid(..),
BoundedGrid(..)
) where
import Math.Geometry.GridInternal (BoundedGrid (..), FiniteGrid (..), Grid (..))
$ Example
Create a grid .
> ghci > let g =
> ghci > indices g
> [ ( -2,0),(-2,1),(-2,2),(-1,-1),(-1,0),(-1,1),(-1,2),(0,-2),(0,-1),(0,0),(0,1),(0,2),(1,-2),(1,-1),(1,0),(1,1),(2,-2),(2,-1),(2,0 ) ]
Find out if the specified index is contained within the grid .
> ghci > g ` contains ` ( 0,-2 )
> True
> ghci > g ` contains ` ( 99,99 )
> False
Find out the minimum number of moves to go from one tile in a grid to
another tile , moving between adjacent tiles at each step .
> ghci > distance g ( 0,-2 ) ( 0,2 )
> 4
Find out the minimum number of moves to go from one tile in a grid to
any other tile , moving between adjacent tiles at each step .
> ghci > viewpoint ( 1,-2 )
> [ ( ( ) ]
Find out which tiles are adjacent to a particular tile .
> ghci > neighbours ( -1,1 )
> [ ( -2,1),(-2,2),(-1,2),(0,1),(0,0),(-1,0 ) ]
Find how many tiles are adjacent to a particular tile .
( Note that the result is consistent with the result from the previous
step . )
> ghci ( -1,1 )
> 6
Find out if an index is valid for the grid .
> ghci > g ` contains ` ( 0,0 )
> True
> ghci > g ` contains ` ( 0,12 )
> False
Find out the physical dimensions of the grid .
> ghci > size g
> 3
Get the list of boundary tiles for a grid .
> ghci > boundary g
> [ ( ) ]
Find out the number of tiles in the grid .
> ghci > tileCount g
> 19
Check if a grid is null ( contains no tiles ) .
> ghci > null g
> False
> ghci >
> True
Find the central tile(s ) ( the tile(s ) furthest from the boundary ) .
> ghci > centre g
> [ ( 0,0 ) ]
Find all of the minimal paths between two points .
> ghci > let g =
> ghci > ( 0,0 ) ( 2,-1 )
> [ [ ( 0,0),(1,0),(2,-1)],[(0,0),(1,-1),(2,-1 ) ] ]
Find all of the pairs of tiles that are adjacent .
> ghci > edges g
> [ ( ( -2,0),(-2,1)),((-2,0),(-1,0)),((-2,0),(-1,-1)),((-2,1),(-2,2)),((-2,1),(-1,1)),((-2,1),(-1,0)),((-2,2),(-1,2)),((-2,2),(-1,1)),((-1,-1),(-1,0)),((-1,-1),(0,-1)),((-1,-1),(0,-2)),((-1,0),(-1,1)),((-1,0),(0,0)),((-1,0),(0,-1)),((-1,1),(-1,2)),((-1,1),(0,1)),((-1,1),(0,0)),((-1,2),(0,2)),((-1,2),(0,1)),((0,-2),(0,-1)),((0,-2),(1,-2)),((0,-1),(0,0)),((0,-1),(1,-1)),((0,-1),(1,-2)),((0,0),(0,1)),((0,0),(1,0)),((0,0),(1,-1)),((0,1),(0,2)),((0,1),(1,1)),((0,1),(1,0)),((0,2),(1,1)),((1,-2),(1,-1)),((1,-2),(2,-2)),((1,-1),(1,0)),((1,-1),(2,-1)),((1,-1),(2,-2)),((1,0),(1,1)),((1,0),(2,0)),((1,0),(2,-1)),((1,1),(2,0)),((2,-2),(2,-1)),((2,-1),(2,0 ) ) ]
Find out if two tiles are adjacent .
> ghci > isAdjacent g ( -2,0 ) ( -2,1 )
> True
> ghci > isAdjacent g ( -2,0 ) ( 0,1 )
> False
Create a grid.
>ghci> let g = hexHexGrid 3
>ghci> indices g
>[(-2,0),(-2,1),(-2,2),(-1,-1),(-1,0),(-1,1),(-1,2),(0,-2),(0,-1),(0,0),(0,1),(0,2),(1,-2),(1,-1),(1,0),(1,1),(2,-2),(2,-1),(2,0)]
Find out if the specified index is contained within the grid.
>ghci> g `contains` (0,-2)
>True
>ghci> g `contains` (99,99)
>False
Find out the minimum number of moves to go from one tile in a grid to
another tile, moving between adjacent tiles at each step.
>ghci> distance g (0,-2) (0,2)
>4
Find out the minimum number of moves to go from one tile in a grid to
any other tile, moving between adjacent tiles at each step.
>ghci> viewpoint g (1,-2)
>[((-2,0),3),((-2,1),3),((-2,2),4),((-1,-1),2),((-1,0),2),((-1,1),3),((-1,2),4),((0,-2),1),((0,-1),1),((0,0),2),((0,1),3),((0,2),4),((1,-2),0),((1,-1),1),((1,0),2),((1,1),3),((2,-2),1),((2,-1),2),((2,0),3)]
Find out which tiles are adjacent to a particular tile.
>ghci> neighbours g (-1,1)
>[(-2,1),(-2,2),(-1,2),(0,1),(0,0),(-1,0)]
Find how many tiles are adjacent to a particular tile.
(Note that the result is consistent with the result from the previous
step.)
>ghci> numNeighbours g (-1,1)
>6
Find out if an index is valid for the grid.
>ghci> g `contains` (0,0)
>True
>ghci> g `contains` (0,12)
>False
Find out the physical dimensions of the grid.
>ghci> size g
>3
Get the list of boundary tiles for a grid.
>ghci> boundary g
>[(-2,2),(-1,2),(0,2),(1,1),(2,0),(2,-1),(2,-2),(1,-2),(0,-2),(-1,-1),(-2,0),(-2,1)]
Find out the number of tiles in the grid.
>ghci> tileCount g
>19
Check if a grid is null (contains no tiles).
>ghci> null g
>False
>ghci> nonNull g
>True
Find the central tile(s) (the tile(s) furthest from the boundary).
>ghci> centre g
>[(0,0)]
Find all of the minimal paths between two points.
>ghci> let g = hexHexGrid 3
>ghci> minimalPaths g (0,0) (2,-1)
>[[(0,0),(1,0),(2,-1)],[(0,0),(1,-1),(2,-1)]]
Find all of the pairs of tiles that are adjacent.
>ghci> edges g
>[((-2,0),(-2,1)),((-2,0),(-1,0)),((-2,0),(-1,-1)),((-2,1),(-2,2)),((-2,1),(-1,1)),((-2,1),(-1,0)),((-2,2),(-1,2)),((-2,2),(-1,1)),((-1,-1),(-1,0)),((-1,-1),(0,-1)),((-1,-1),(0,-2)),((-1,0),(-1,1)),((-1,0),(0,0)),((-1,0),(0,-1)),((-1,1),(-1,2)),((-1,1),(0,1)),((-1,1),(0,0)),((-1,2),(0,2)),((-1,2),(0,1)),((0,-2),(0,-1)),((0,-2),(1,-2)),((0,-1),(0,0)),((0,-1),(1,-1)),((0,-1),(1,-2)),((0,0),(0,1)),((0,0),(1,0)),((0,0),(1,-1)),((0,1),(0,2)),((0,1),(1,1)),((0,1),(1,0)),((0,2),(1,1)),((1,-2),(1,-1)),((1,-2),(2,-2)),((1,-1),(1,0)),((1,-1),(2,-1)),((1,-1),(2,-2)),((1,0),(1,1)),((1,0),(2,0)),((1,0),(2,-1)),((1,1),(2,0)),((2,-2),(2,-1)),((2,-1),(2,0))]
Find out if two tiles are adjacent.
>ghci> isAdjacent g (-2,0) (-2,1)
>True
>ghci> isAdjacent g (-2,0) (0,1)
>False
-}
|
02342851350bdb0a1da13b0fd34fc436a63fd210af069864423dd85bf54ab7cc | pflanze/chj-schemelib | simple-match-1.scm | Copyright 2010 , 2011 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 cj-source
define-macro-star
cj-phasing
(fixnum dec)
;; improper-length is included by cj-source-util.scm is
included by define-macro-star.scm
)
(export (macro warn*)
(macro match*)
(macro match-list*)
(macro assert-desourcified*)
(macro assert*)
(macro assert**))
; (define (warn* message . args)
; (continuation-capture
; (lambda (cont)
; )))
;or, 'simpler':
(define-macro* (warn* message . args)
(let ((loc (source-location stx)))
`(location-warn ',loc
,message
,@args)))
(define-macro* (match* input* . clauses*)
;; only supports flat list matching for now
;; although including improper lists
;; not even anything other than just binding variables.
;; also doesn't check for errors in clauses syntax very well.
(let ((V* (gensym 'v*))
(V (gensym 'v))
(LEN (gensym 'len)))
`(let* ((,V* ,input*)
(,V (source-code ,V*))
(,LEN (improper-length ,V)))
(if (negative? ,LEN)
(raise-source-error ,V* "not a proper list")
,(let rec ((clauses clauses*))
(cond ((null? clauses)
`(raise-source-error
,V*
,(let ((str (scm:objects->string
(map car (map cj-desourcify clauses*))
separator: " | ")))
(string-append
"no match, expecting "
(if (> (length clauses*) 1)
(string-append "any of " str)
str)))))
((pair? clauses)
(let* ((clause* (car clauses))
(clause (source-code clause*))
(pro* (car clause))
(body (cdr clause)) ;;(XX require body to be non-null?)
(pro (source-code pro*))
(len (improper-length pro))
)
(if (not (negative? len))
`(if (= ,LEN ,len)
;; XX just *assume* that clause contents are just symbols for now
,(let rec2 ((pro pro))
(cond ((null? pro)
(cons 'begin body))
((pair? pro)
`(let* ((,(car pro) (car ,V))
;; reuse var name (shadowing):
(,V (cdr ,V)))
,(rec2 (cdr pro))))))
,(rec (cdr clauses)))
;; otherwise var arg match:
;; (could optimize: if len is -1, the clause matches everything, no test needed and stop recursing, ignore remaining clauses (XXX croak about it when there *are* further clauses))
`(if (>= ,LEN ,(dec (- len)))
;; XX ditto above
,(let rec2 ((pro pro))
(cond ((pair? pro)
`(let* ((,(car pro) (car ,V))
;; reuse var name (shadowing):
(,V (cdr ,V)))
,(rec2 (cdr pro))))
(else
`(let ((,pro ,V))
,@body))))
,(rec (cdr clauses))))))
(else
;; can't use raise-source-error here yet (because
;; it has not been defined in this phase)
(error "invalid match syntax: expecting list of clauses, got:" clauses))))))))
;; require input to be a proper list (complain otherwise):
;; currently just an alias for match*, but I might change match* some time.
(define-macro* (match-list* input* . clauses)
`(match* ,input* ,@clauses))
;; TESTs see simple-match.scm
(both-times
(define (assert*-expand desourcify
gen-full-desourcify/1
pred
val
yes-cont
no-cont)
(define V* (gensym 'v*))
(define V (gensym 'v))
`(let* ((,V* ,val)
(,V (,desourcify ,V*)))
(if (,pred ,V)
,(if yes-cont `(,yes-cont ,V) `(void))
,(if (source-code no-cont)
no-cont
`(raise-source-error
,V*
,(string-append "does not match "
(scm:object->string
(cj-desourcify pred))
" predicate")
,(gen-full-desourcify/1 V* V)))))))
(define-macro* (assert-desourcified* pred val #!optional yes-cont no-cont)
(assert*-expand 'cj-desourcify
(lambda (V* V)
V)
pred val yes-cont no-cont))
only remove location information 1 level ( uh , better names ? )
(define-macro* (assert* pred val #!optional yes-cont no-cont)
(assert*-expand 'source-code
(lambda (V* V)
`(cj-desourcify ,V*))
pred val yes-cont no-cont))
different from assert - desourcified * in two ways ( 1 ) pass the unwrapped result in
' the same variable as ' v instead of expecting a function , ( 2 ) evals
the input first .
(define-macro* (assert** pred var #!optional yes-expr no-expr)
(assert-desourcified* symbol? var
(lambda (_)
`(assert-desourcified* ,pred (eval ,var)
(lambda (,var)
,yes-expr)
,@(if (source-code no-expr)
(list no-expr)
(list))))))
| null | https://raw.githubusercontent.com/pflanze/chj-schemelib/59ff8476e39f207c2f1d807cfc9670581c8cedd3/simple-match-1.scm | scheme | This file is free software; you can redistribute it and/or modify
(at your option) any later version.
improper-length is included by cj-source-util.scm is
(define (warn* message . args)
(continuation-capture
(lambda (cont)
)))
or, 'simpler':
only supports flat list matching for now
although including improper lists
not even anything other than just binding variables.
also doesn't check for errors in clauses syntax very well.
(XX require body to be non-null?)
XX just *assume* that clause contents are just symbols for now
reuse var name (shadowing):
otherwise var arg match:
(could optimize: if len is -1, the clause matches everything, no test needed and stop recursing, ignore remaining clauses (XXX croak about it when there *are* further clauses))
XX ditto above
reuse var name (shadowing):
can't use raise-source-error here yet (because
it has not been defined in this phase)
require input to be a proper list (complain otherwise):
currently just an alias for match*, but I might change match* some time.
TESTs see simple-match.scm | Copyright 2010 , 2011 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 cj-source
define-macro-star
cj-phasing
(fixnum dec)
included by define-macro-star.scm
)
(export (macro warn*)
(macro match*)
(macro match-list*)
(macro assert-desourcified*)
(macro assert*)
(macro assert**))
(define-macro* (warn* message . args)
(let ((loc (source-location stx)))
`(location-warn ',loc
,message
,@args)))
(define-macro* (match* input* . clauses*)
(let ((V* (gensym 'v*))
(V (gensym 'v))
(LEN (gensym 'len)))
`(let* ((,V* ,input*)
(,V (source-code ,V*))
(,LEN (improper-length ,V)))
(if (negative? ,LEN)
(raise-source-error ,V* "not a proper list")
,(let rec ((clauses clauses*))
(cond ((null? clauses)
`(raise-source-error
,V*
,(let ((str (scm:objects->string
(map car (map cj-desourcify clauses*))
separator: " | ")))
(string-append
"no match, expecting "
(if (> (length clauses*) 1)
(string-append "any of " str)
str)))))
((pair? clauses)
(let* ((clause* (car clauses))
(clause (source-code clause*))
(pro* (car clause))
(pro (source-code pro*))
(len (improper-length pro))
)
(if (not (negative? len))
`(if (= ,LEN ,len)
,(let rec2 ((pro pro))
(cond ((null? pro)
(cons 'begin body))
((pair? pro)
`(let* ((,(car pro) (car ,V))
(,V (cdr ,V)))
,(rec2 (cdr pro))))))
,(rec (cdr clauses)))
`(if (>= ,LEN ,(dec (- len)))
,(let rec2 ((pro pro))
(cond ((pair? pro)
`(let* ((,(car pro) (car ,V))
(,V (cdr ,V)))
,(rec2 (cdr pro))))
(else
`(let ((,pro ,V))
,@body))))
,(rec (cdr clauses))))))
(else
(error "invalid match syntax: expecting list of clauses, got:" clauses))))))))
(define-macro* (match-list* input* . clauses)
`(match* ,input* ,@clauses))
(both-times
(define (assert*-expand desourcify
gen-full-desourcify/1
pred
val
yes-cont
no-cont)
(define V* (gensym 'v*))
(define V (gensym 'v))
`(let* ((,V* ,val)
(,V (,desourcify ,V*)))
(if (,pred ,V)
,(if yes-cont `(,yes-cont ,V) `(void))
,(if (source-code no-cont)
no-cont
`(raise-source-error
,V*
,(string-append "does not match "
(scm:object->string
(cj-desourcify pred))
" predicate")
,(gen-full-desourcify/1 V* V)))))))
(define-macro* (assert-desourcified* pred val #!optional yes-cont no-cont)
(assert*-expand 'cj-desourcify
(lambda (V* V)
V)
pred val yes-cont no-cont))
only remove location information 1 level ( uh , better names ? )
(define-macro* (assert* pred val #!optional yes-cont no-cont)
(assert*-expand 'source-code
(lambda (V* V)
`(cj-desourcify ,V*))
pred val yes-cont no-cont))
different from assert - desourcified * in two ways ( 1 ) pass the unwrapped result in
' the same variable as ' v instead of expecting a function , ( 2 ) evals
the input first .
(define-macro* (assert** pred var #!optional yes-expr no-expr)
(assert-desourcified* symbol? var
(lambda (_)
`(assert-desourcified* ,pred (eval ,var)
(lambda (,var)
,yes-expr)
,@(if (source-code no-expr)
(list no-expr)
(list))))))
|
8c22ddab319235ea95d20577e09a1432fc410a14e6195080d6c55201c2137203 | wesen/ruinwesen | soundfile.lisp | (in-package :ruinwesen)
| null | https://raw.githubusercontent.com/wesen/ruinwesen/9f3ccea85425cf46b57e76144b3114ca342bad0f/ruinwesen/src/soundfile.lisp | lisp | (in-package :ruinwesen)
| |
ffbdd509c1f55f7796b395d92dd6c9a43dd49102eadf6ff2b80783fbe1a032c4 | russmatney/ralphie | fzf.clj | (ns ralphie.fzf
(:require
[defthing.defcom :refer [defcom] :as defcom]
[babashka.process :refer [process]]
[clojure.string :as string]))
(defn fzf [xs]
(let [labels (->> xs (map :fzf/label))
proc (process ["fzf"]
{:in (string/join "\n" labels)
:err :inherit
:out :string})
selected-label (-> @proc :out string/trim)]
(when (seq selected-label)
(some->> xs
(filter (comp #{selected-label} :fzf/label))
first))))
(defcom fzf-cmd
(fn [_cmd args]
(when-let [cmd (->> (defcom/list-commands)
(filter (comp seq :name))
(map (fn [cmd] (assoc cmd :fzf/label (:name cmd))))
fzf)]
(defcom/exec cmd (rest args)))))
| null | https://raw.githubusercontent.com/russmatney/ralphie/3b7af4a9ec2dc2b9e59036d67a66f365691f171d/src/ralphie/fzf.clj | clojure | (ns ralphie.fzf
(:require
[defthing.defcom :refer [defcom] :as defcom]
[babashka.process :refer [process]]
[clojure.string :as string]))
(defn fzf [xs]
(let [labels (->> xs (map :fzf/label))
proc (process ["fzf"]
{:in (string/join "\n" labels)
:err :inherit
:out :string})
selected-label (-> @proc :out string/trim)]
(when (seq selected-label)
(some->> xs
(filter (comp #{selected-label} :fzf/label))
first))))
(defcom fzf-cmd
(fn [_cmd args]
(when-let [cmd (->> (defcom/list-commands)
(filter (comp seq :name))
(map (fn [cmd] (assoc cmd :fzf/label (:name cmd))))
fzf)]
(defcom/exec cmd (rest args)))))
| |
e549a7dafec69c8ee2672568df0e6026c51a80afe88df1a0f779e219461d1943 | Fytex/ExciteBike-LI1 | Tarefa3_2019li1g068.hs | |
Module : Tarefa3_2019li1g068
Description : Módulo Haskell contendo as , relativas à Tarefa 3 do Projeto da Unidade Curricular de LI1
Copyright : Fytex ;
Arkimedez
Um módulo contendo definições com sucesso a Tarefa 3 :
A Tarefa 3 consiste no ato de desconstruir um mapa . que nos bulldozers ( um por pista ) que partida , e usarão o conjunto o mapa em questão .
Module: Tarefa3_2019li1g068
Description: Módulo Haskell contendo as funções necessárias, relativas à Tarefa 3 do Projeto da Unidade Curricular de LI1
Copyright: Fytex;
Arkimedez
Um módulo contendo definições Haskell para executar com sucesso a Tarefa 3:
A Tarefa 3 consiste no ato de desconstruir um mapa num conjunto de instruções. Para tal temos de definir funções que nos possam ajudar nessa tarefa.
Os bulldozers (um por pista) que avançarão desde da partida, e usarão o conjunto de instruções para construir o mapa em questão.
-}
|
= Introdução
Na Tarefa 3 tivemos de arranjar uma forma de desconstruir mapas , de forma a que dado um mapa cujo pista é maior que 1 ,
este fosse convertido numa . Estas instruções eram dadas a um grupo de bulldozers ( um por pista ) que avançavam da partida para construir
o mapa em questão .
= Objetivos
A questão chave desta era a de identificar padrões , que /horizontais/,/verticais/ ou /verticais desfasados/.
O nosso a nossa função ' desconstroi ' fazia o básico , algo que pelas funções auxiliares ' convertePeca ' e
' converteMapa ' .
Seguidamente , tentamos tratar os , oficio que não nos pareceu . Sucedemos , com a função ' ' , várias
permutações de ' Repete 's .Porém Tarefa já tinhamos em mente os /verticais/ e , portanto , optámos a opção um padrão
quando só se repete 2 vezes . Deixamos em forma de /Nota/ :
É preferivel [ Anda Terra 0 , 0 ] a [ Repete 2 Terra 0 ] pois podemos agrupar com a linha de baixo caso seja possivel !
Depois , era a vez de tentar os padrões /verticais/ , que já bastante complexa . Conseguimos .
Há que deixar anotado que o nosso objetivo principal , principalmente depois de termos , todos os restantes objetivos desta e as totalmente
, tratar os padrões /verticais desfasados/. Tentamos , com bastante esforço , implementar a /Teleporta/ no nosso projeto . e a função até era funcional , mas tinha alguns /bugs/ e , como o site não esteve funcional durante um período de tempo considerável , o que aliado a uma
grande depois as , resolver os bugs da /Teleporta/.
= Discussão e Conclusão
Em suma , acreditamos que fizemos um bom trabalho e ficamos , grosso modo , satisfeitos com o resultado . Acabamos por ficar em 3º. lugar sem o tratamento dos padrões
/verticais desfasados/ , como era o nosso objetivo . Além disso , /bugs/ referidos ,
4º.lugar .
No final optamos por
=Introdução
Na Tarefa 3 tivemos de arranjar uma forma de desconstruir mapas, de forma a que dado um mapa cujo comprimento de cada pista é maior que 1,
este fosse convertido numa sequência de instruções. Estas instruções eram dadas a um grupo de bulldozers (um por pista) que avançavam da partida para construir
o mapa em questão.
= Objetivos
A questão chave desta Tarefa era a de identificar padrões, que podiam ser /horizontais/,/verticais/ ou /verticais desfasados/.
O nosso primeiro objetivo foi o de garantir que a nossa função 'desconstroi' fazia o básico, algo que foi garantido pelas funções auxiliares 'convertePeca' e
'converteMapa'.
Seguidamente, tentamos tratar os padrões /horizontais/, oficio que não nos pareceu muito complexo. Sucedemos, com a função 'loopPistas', que gerou as várias
permutações de 'Repete's .Porém nesta fase da Tarefa já tinhamos em mente os padrões /verticais/ e, portanto, optámos por não usar nunca a opção de criar um padrão
quando só se repete 2 vezes. Deixamos essa decisão em forma de /Nota/:
É preferivel [Anda Terra 0, Anda Terra 0] a [Repete 2 Anda Terra 0] pois podemos agrupar com a linha de baixo caso seja possivel!
Depois, era a vez de tentar os padrões /verticais/, que já constituiam uma fase bastante complexa da Tarefa. Conseguimos.
Há que deixar anotado que o nosso objetivo principal, principalmente depois de termos, todos os restantes objetivos desta Tarefa e as Tarefas 1 e 2 totalmente
otimizadas, foi tentar tratar os padrões /verticais desfasados/. Tentamos, com bastante esforço, implementar a /Teleporta/ no nosso projeto. Conseguimos criar os
padrões e a função até era funcional, mas tinha alguns /bugs/ e, como o site não esteve funcional durante um período de tempo considerável, o que aliado a uma
grande quantidade de grupos que depois tiveram de testar as suas Tarefas, não conseguimos resolver os bugs da /Teleporta/.
= Discussão e Conclusão
Em suma, acreditamos que fizemos um bom trabalho e ficamos, grosso modo, satisfeitos com o resultado. Acabamos por ficar em 3º. lugar sem o tratamento dos padrões
/verticais desfasados/ , como era o nosso objetivo. Além disso, não deixa de ser caricato constatar que mesmo com os /bugs/ referidos em cima, conseguimos ficar em
4º.lugar.
No final optamos por deixar a versão sem os /bugs/.
-}
Este módulo define do trabalho prático .
module Tarefa3_2019li1g068 where
import LI11920
import Tarefa1_2019li1g068
-- * Testes
-- | Testes unitários da Tarefa 3.
--
Cada teste é um ' ' .
testesT3 :: [Mapa]
testesT3 = [[[Recta Terra 0, Recta Terra 0, Recta Terra 0]],[[Recta Terra 0, Recta Lama 0], [Recta Terra 0, Recta Boost 0], [Recta Terra 0, Recta Lama 0]], [[Recta Terra 0, Recta Terra 0, Recta Terra 0, Recta Terra 0, Recta Lama 0, Recta Lama 0, Recta Lama 0], [Recta Terra 0, Recta Terra 0, Recta Lama 0, Recta Terra 0, Recta Lama 0, Recta Terra 0, Recta Lama 0]], [[Recta Terra 0, Recta Terra 0, Recta Cola 0, Recta Lama 0, Recta Terra 0, Recta Cola 0, Recta Lama 0], [Recta Terra 0, Recta Terra 0, Recta Lama 0, Recta Terra 0, Recta Lama 0, Recta Boost 0, Recta Lama 0]],gera 5 5 5, gera 7 5 2, gera 2 4 5, gera 1 2 5, gera 9 10 3, gera 2 3 5, gera 12 2 3, gera 4 5 7, gera 4 8 1, gera 9 8 4,gera 4 19 9, gera 50 20 9]
* Funções principais da Tarefa 3 .
| Desconstrói um ' ' numa Instrucoes ' .
--
_ _ NB : _ _ retornar uma Instrucoes ' tal que , para qualquer mapa válido ( /m/ ) , executar as instruções ' ( desconstroi m ) ' produza o ( /m/ ) .
--
_ _ NB : _ _ Uma boa solução deve representar o ' Mapa ' dado no mínimo número de ' Instrucoes ' , de acordo com a função ' tamanhoInstrucoes ' .
desconstroi :: Mapa -> Instrucoes
desconstroi m = verticalInstrucoes (loopPistas (converteMapa m 0))
: : [ [ a ] ] - > [ [ a ] ]
[ ] = [ ]
l = ( map head l):transpostaMatriz ( map tail l )
-- * Funções auxiliares da Tarefa 3.
| Função que dada uma Peca e um inteiro(relativo à pista ) , dá uma Instrucao , que será utilizada bulldozer
convertePeca :: Int -> Peca -> Instrucao
convertePeca n (Recta piso _) = (Anda [n] piso)
convertePeca n (Rampa piso y y') | y' > y = (Sobe [n] piso diff)
| otherwise = (Desce [n] piso diff)
where diff = abs (y-y')
| Função que converte o Mapa numa lista de ' Instrucoes ' . Esta função é a mais simples , uma vez que não tem em conta os , verticais e verticais desfasados .
converteMapa :: Mapa -> Int -> [Instrucoes]
converteMapa [] _ = []
converteMapa (h:t) n = (map (convertePeca n) (tail h)):(converteMapa t (n+1))
| Função que será usada as várias permutações de ' Repete 's
loopPistas :: [Instrucoes] -> [Instrucoes]
loopPistas [] = []
loopPistas (h:t) = (loopRepeteInstrucoes h (1, (div (length h) 2))):loopPistas t
| Função que será usada ' loopPistas ' para o /looping/ das várias permutações
loopRepeteInstrucoes :: Instrucoes -> (Int,Int) -> Instrucoes
loopRepeteInstrucoes l (start, end) | start > end = l
| otherwise = loopRepeteInstrucoes (repeteInstrucoes l start) ((start + 1), end)
|
Função que recebe uma permutação de cada vez e tenta gerar ' Instrucoes ' , lista com os ' Repete 's
= = NOTA :
É preferivel [ Anda Terra 0 , 0 ] a [ Repete 2 Terra 0 ] pois podemos agrupar com a linha de baixo caso seja possivel !
Função que recebe uma permutação de cada vez e tenta gerar 'Instrucoes', otimizando essa lista com os 'Repete's
==NOTA:
É preferivel [Anda Terra 0, Anda Terra 0] a [Repete 2 Anda Terra 0] pois podemos agrupar com a linha de baixo caso seja possivel!
-}
preferivel [ Anda Terra 0 , 0 ] a [ Repete 2 Terra 0 ] pois podemos agrupar com a linha de baixo caso seja possivel !
repeteInstrucoes :: Instrucoes -> Int -> Instrucoes
repeteInstrucoes [] _ = []
repeteInstrucoes l@(h:t) step | n > 0 && (n /= 1 || step /= 1) = (Repete (n+1) l1):repeteInstrucoes (drop (n*step) l2) step
| otherwise = h:repeteInstrucoes t step
where
(l1, l2) = splitAt step l
l' = chunksOf step l2
n = length (takeWhile (==l1) l')
| Função que vê as ' Instrucoes ' de duas pistas e cria um , se ele fôr possível .
verticalInstrucoes :: [Instrucoes] -> Instrucoes
verticalInstrucoes (h:h':t) = verticalInstrucoes ((introduzirInstrucoes h' h):t)
verticalInstrucoes l = concat l
| Função que permite o vertical , ' que resultam de introduzir ' Instrucoes ' às ' Instrucoes ' iniciais
introduzirInstrucoes :: Instrucoes -> Instrucoes -> Instrucoes
introduzirInstrucoes (instrucao:resto) l@(_:_) | null l2 = instrucao:introduzirInstrucoes resto l
| otherwise = l1 ++ (somaPistas instrucao ins):introduzirInstrucoes resto t
where
(l1, l2) = span (instrucoesDiff instrucao) l
(ins:t) = l2
introduzirInstrucoes l [] = l
introduzirInstrucoes _ l = l
| menos um dos casos , então dá /True/
funcao or recebe uma lista e se menos um for verdadeiro
instrucoesDiff :: Instrucao -> Instrucao -> Bool
instrucoesDiff (Anda _ piso) (Anda _ piso') = piso /= piso'
instrucoesDiff (Sobe _ piso h) (Sobe _ piso' h') = piso /= piso' || h/=h'
instrucoesDiff (Desce _ piso h) (Desce _ piso' h') = piso /= piso' || h/=h'
instrucoesDiff (Repete i ins) (Repete i' ins') = i/=i' ||( not (primeiraDentroSegundaLista ins ins') && not (primeiraDentroSegundaLista ins' ins))
instrucoesDiff _ _ = True
| Verifica se uma lista lista , independentemente da lista de pistas .
primeiraDentroSegundaLista :: Instrucoes -> Instrucoes -> Bool
primeiraDentroSegundaLista l@(h:t) (h':t') | not (instrucoesDiff h h') = primeiraDentroSegundaLista t t'
| otherwise = primeiraDentroSegundaLista l t'
primeiraDentroSegundaLista [] _ = True
primeiraDentroSegundaLista _ _ = False
| Converge 2 listas .
juntaPrimeiraASegundaLista :: Instrucoes -> Instrucoes -> Instrucoes
juntaPrimeiraASegundaLista l@(h:t) (h':t') | not (instrucoesDiff h h') = (somaPistas h h'):juntaPrimeiraASegundaLista t t'
| otherwise = h':juntaPrimeiraASegundaLista l t'
juntaPrimeiraASegundaLista _ l = l
| Função que que recebe ' Instrucao ' e ' Instrucao ' e junta os indíces das ' Pista 's com a mesma ' Instrucao '
no caso dos repetes se forem iguais entao a soma de cada x pertencente a um dos repetes com y pertencente a ao outro tem de dar [ x ] e nao [ x , y ]
somaPistas :: Instrucao -> Instrucao -> Instrucao
somaPistas (Anda l piso) (Anda l' _) = Anda (l++l') piso
somaPistas (Sobe l piso h) (Sobe l' _ _) = Sobe (l++l') piso h
somaPistas (Desce l piso h) (Desce l' _ _) = Desce (l++l') piso h
somaPistas (Repete i ins) (Repete _ ins') | length ins > length ins' = Repete i (juntaPrimeiraASegundaLista ins' ins)
| otherwise = Repete i (juntaPrimeiraASegundaLista ins ins')
| null | https://raw.githubusercontent.com/Fytex/ExciteBike-LI1/ac544dc4a818181ff4bdf23f9164e14e8d26ab0c/Tarefa3_2019li1g068.hs | haskell | * Testes
| Testes unitários da Tarefa 3.
* Funções auxiliares da Tarefa 3. | |
Module : Tarefa3_2019li1g068
Description : Módulo Haskell contendo as , relativas à Tarefa 3 do Projeto da Unidade Curricular de LI1
Copyright : Fytex ;
Arkimedez
Um módulo contendo definições com sucesso a Tarefa 3 :
A Tarefa 3 consiste no ato de desconstruir um mapa . que nos bulldozers ( um por pista ) que partida , e usarão o conjunto o mapa em questão .
Module: Tarefa3_2019li1g068
Description: Módulo Haskell contendo as funções necessárias, relativas à Tarefa 3 do Projeto da Unidade Curricular de LI1
Copyright: Fytex;
Arkimedez
Um módulo contendo definições Haskell para executar com sucesso a Tarefa 3:
A Tarefa 3 consiste no ato de desconstruir um mapa num conjunto de instruções. Para tal temos de definir funções que nos possam ajudar nessa tarefa.
Os bulldozers (um por pista) que avançarão desde da partida, e usarão o conjunto de instruções para construir o mapa em questão.
-}
|
= Introdução
Na Tarefa 3 tivemos de arranjar uma forma de desconstruir mapas , de forma a que dado um mapa cujo pista é maior que 1 ,
este fosse convertido numa . Estas instruções eram dadas a um grupo de bulldozers ( um por pista ) que avançavam da partida para construir
o mapa em questão .
= Objetivos
A questão chave desta era a de identificar padrões , que /horizontais/,/verticais/ ou /verticais desfasados/.
O nosso a nossa função ' desconstroi ' fazia o básico , algo que pelas funções auxiliares ' convertePeca ' e
' converteMapa ' .
Seguidamente , tentamos tratar os , oficio que não nos pareceu . Sucedemos , com a função ' ' , várias
permutações de ' Repete 's .Porém Tarefa já tinhamos em mente os /verticais/ e , portanto , optámos a opção um padrão
quando só se repete 2 vezes . Deixamos em forma de /Nota/ :
É preferivel [ Anda Terra 0 , 0 ] a [ Repete 2 Terra 0 ] pois podemos agrupar com a linha de baixo caso seja possivel !
Depois , era a vez de tentar os padrões /verticais/ , que já bastante complexa . Conseguimos .
Há que deixar anotado que o nosso objetivo principal , principalmente depois de termos , todos os restantes objetivos desta e as totalmente
, tratar os padrões /verticais desfasados/. Tentamos , com bastante esforço , implementar a /Teleporta/ no nosso projeto . e a função até era funcional , mas tinha alguns /bugs/ e , como o site não esteve funcional durante um período de tempo considerável , o que aliado a uma
grande depois as , resolver os bugs da /Teleporta/.
= Discussão e Conclusão
Em suma , acreditamos que fizemos um bom trabalho e ficamos , grosso modo , satisfeitos com o resultado . Acabamos por ficar em 3º. lugar sem o tratamento dos padrões
/verticais desfasados/ , como era o nosso objetivo . Além disso , /bugs/ referidos ,
4º.lugar .
No final optamos por
=Introdução
Na Tarefa 3 tivemos de arranjar uma forma de desconstruir mapas, de forma a que dado um mapa cujo comprimento de cada pista é maior que 1,
este fosse convertido numa sequência de instruções. Estas instruções eram dadas a um grupo de bulldozers (um por pista) que avançavam da partida para construir
o mapa em questão.
= Objetivos
A questão chave desta Tarefa era a de identificar padrões, que podiam ser /horizontais/,/verticais/ ou /verticais desfasados/.
O nosso primeiro objetivo foi o de garantir que a nossa função 'desconstroi' fazia o básico, algo que foi garantido pelas funções auxiliares 'convertePeca' e
'converteMapa'.
Seguidamente, tentamos tratar os padrões /horizontais/, oficio que não nos pareceu muito complexo. Sucedemos, com a função 'loopPistas', que gerou as várias
permutações de 'Repete's .Porém nesta fase da Tarefa já tinhamos em mente os padrões /verticais/ e, portanto, optámos por não usar nunca a opção de criar um padrão
quando só se repete 2 vezes. Deixamos essa decisão em forma de /Nota/:
É preferivel [Anda Terra 0, Anda Terra 0] a [Repete 2 Anda Terra 0] pois podemos agrupar com a linha de baixo caso seja possivel!
Depois, era a vez de tentar os padrões /verticais/, que já constituiam uma fase bastante complexa da Tarefa. Conseguimos.
Há que deixar anotado que o nosso objetivo principal, principalmente depois de termos, todos os restantes objetivos desta Tarefa e as Tarefas 1 e 2 totalmente
otimizadas, foi tentar tratar os padrões /verticais desfasados/. Tentamos, com bastante esforço, implementar a /Teleporta/ no nosso projeto. Conseguimos criar os
padrões e a função até era funcional, mas tinha alguns /bugs/ e, como o site não esteve funcional durante um período de tempo considerável, o que aliado a uma
grande quantidade de grupos que depois tiveram de testar as suas Tarefas, não conseguimos resolver os bugs da /Teleporta/.
= Discussão e Conclusão
Em suma, acreditamos que fizemos um bom trabalho e ficamos, grosso modo, satisfeitos com o resultado. Acabamos por ficar em 3º. lugar sem o tratamento dos padrões
/verticais desfasados/ , como era o nosso objetivo. Além disso, não deixa de ser caricato constatar que mesmo com os /bugs/ referidos em cima, conseguimos ficar em
4º.lugar.
No final optamos por deixar a versão sem os /bugs/.
-}
Este módulo define do trabalho prático .
module Tarefa3_2019li1g068 where
import LI11920
import Tarefa1_2019li1g068
Cada teste é um ' ' .
testesT3 :: [Mapa]
testesT3 = [[[Recta Terra 0, Recta Terra 0, Recta Terra 0]],[[Recta Terra 0, Recta Lama 0], [Recta Terra 0, Recta Boost 0], [Recta Terra 0, Recta Lama 0]], [[Recta Terra 0, Recta Terra 0, Recta Terra 0, Recta Terra 0, Recta Lama 0, Recta Lama 0, Recta Lama 0], [Recta Terra 0, Recta Terra 0, Recta Lama 0, Recta Terra 0, Recta Lama 0, Recta Terra 0, Recta Lama 0]], [[Recta Terra 0, Recta Terra 0, Recta Cola 0, Recta Lama 0, Recta Terra 0, Recta Cola 0, Recta Lama 0], [Recta Terra 0, Recta Terra 0, Recta Lama 0, Recta Terra 0, Recta Lama 0, Recta Boost 0, Recta Lama 0]],gera 5 5 5, gera 7 5 2, gera 2 4 5, gera 1 2 5, gera 9 10 3, gera 2 3 5, gera 12 2 3, gera 4 5 7, gera 4 8 1, gera 9 8 4,gera 4 19 9, gera 50 20 9]
* Funções principais da Tarefa 3 .
| Desconstrói um ' ' numa Instrucoes ' .
_ _ NB : _ _ retornar uma Instrucoes ' tal que , para qualquer mapa válido ( /m/ ) , executar as instruções ' ( desconstroi m ) ' produza o ( /m/ ) .
_ _ NB : _ _ Uma boa solução deve representar o ' Mapa ' dado no mínimo número de ' Instrucoes ' , de acordo com a função ' tamanhoInstrucoes ' .
desconstroi :: Mapa -> Instrucoes
desconstroi m = verticalInstrucoes (loopPistas (converteMapa m 0))
: : [ [ a ] ] - > [ [ a ] ]
[ ] = [ ]
l = ( map head l):transpostaMatriz ( map tail l )
| Função que dada uma Peca e um inteiro(relativo à pista ) , dá uma Instrucao , que será utilizada bulldozer
convertePeca :: Int -> Peca -> Instrucao
convertePeca n (Recta piso _) = (Anda [n] piso)
convertePeca n (Rampa piso y y') | y' > y = (Sobe [n] piso diff)
| otherwise = (Desce [n] piso diff)
where diff = abs (y-y')
| Função que converte o Mapa numa lista de ' Instrucoes ' . Esta função é a mais simples , uma vez que não tem em conta os , verticais e verticais desfasados .
converteMapa :: Mapa -> Int -> [Instrucoes]
converteMapa [] _ = []
converteMapa (h:t) n = (map (convertePeca n) (tail h)):(converteMapa t (n+1))
| Função que será usada as várias permutações de ' Repete 's
loopPistas :: [Instrucoes] -> [Instrucoes]
loopPistas [] = []
loopPistas (h:t) = (loopRepeteInstrucoes h (1, (div (length h) 2))):loopPistas t
| Função que será usada ' loopPistas ' para o /looping/ das várias permutações
loopRepeteInstrucoes :: Instrucoes -> (Int,Int) -> Instrucoes
loopRepeteInstrucoes l (start, end) | start > end = l
| otherwise = loopRepeteInstrucoes (repeteInstrucoes l start) ((start + 1), end)
|
Função que recebe uma permutação de cada vez e tenta gerar ' Instrucoes ' , lista com os ' Repete 's
= = NOTA :
É preferivel [ Anda Terra 0 , 0 ] a [ Repete 2 Terra 0 ] pois podemos agrupar com a linha de baixo caso seja possivel !
Função que recebe uma permutação de cada vez e tenta gerar 'Instrucoes', otimizando essa lista com os 'Repete's
==NOTA:
É preferivel [Anda Terra 0, Anda Terra 0] a [Repete 2 Anda Terra 0] pois podemos agrupar com a linha de baixo caso seja possivel!
-}
preferivel [ Anda Terra 0 , 0 ] a [ Repete 2 Terra 0 ] pois podemos agrupar com a linha de baixo caso seja possivel !
repeteInstrucoes :: Instrucoes -> Int -> Instrucoes
repeteInstrucoes [] _ = []
repeteInstrucoes l@(h:t) step | n > 0 && (n /= 1 || step /= 1) = (Repete (n+1) l1):repeteInstrucoes (drop (n*step) l2) step
| otherwise = h:repeteInstrucoes t step
where
(l1, l2) = splitAt step l
l' = chunksOf step l2
n = length (takeWhile (==l1) l')
| Função que vê as ' Instrucoes ' de duas pistas e cria um , se ele fôr possível .
verticalInstrucoes :: [Instrucoes] -> Instrucoes
verticalInstrucoes (h:h':t) = verticalInstrucoes ((introduzirInstrucoes h' h):t)
verticalInstrucoes l = concat l
| Função que permite o vertical , ' que resultam de introduzir ' Instrucoes ' às ' Instrucoes ' iniciais
introduzirInstrucoes :: Instrucoes -> Instrucoes -> Instrucoes
introduzirInstrucoes (instrucao:resto) l@(_:_) | null l2 = instrucao:introduzirInstrucoes resto l
| otherwise = l1 ++ (somaPistas instrucao ins):introduzirInstrucoes resto t
where
(l1, l2) = span (instrucoesDiff instrucao) l
(ins:t) = l2
introduzirInstrucoes l [] = l
introduzirInstrucoes _ l = l
| menos um dos casos , então dá /True/
funcao or recebe uma lista e se menos um for verdadeiro
instrucoesDiff :: Instrucao -> Instrucao -> Bool
instrucoesDiff (Anda _ piso) (Anda _ piso') = piso /= piso'
instrucoesDiff (Sobe _ piso h) (Sobe _ piso' h') = piso /= piso' || h/=h'
instrucoesDiff (Desce _ piso h) (Desce _ piso' h') = piso /= piso' || h/=h'
instrucoesDiff (Repete i ins) (Repete i' ins') = i/=i' ||( not (primeiraDentroSegundaLista ins ins') && not (primeiraDentroSegundaLista ins' ins))
instrucoesDiff _ _ = True
| Verifica se uma lista lista , independentemente da lista de pistas .
primeiraDentroSegundaLista :: Instrucoes -> Instrucoes -> Bool
primeiraDentroSegundaLista l@(h:t) (h':t') | not (instrucoesDiff h h') = primeiraDentroSegundaLista t t'
| otherwise = primeiraDentroSegundaLista l t'
primeiraDentroSegundaLista [] _ = True
primeiraDentroSegundaLista _ _ = False
| Converge 2 listas .
juntaPrimeiraASegundaLista :: Instrucoes -> Instrucoes -> Instrucoes
juntaPrimeiraASegundaLista l@(h:t) (h':t') | not (instrucoesDiff h h') = (somaPistas h h'):juntaPrimeiraASegundaLista t t'
| otherwise = h':juntaPrimeiraASegundaLista l t'
juntaPrimeiraASegundaLista _ l = l
| Função que que recebe ' Instrucao ' e ' Instrucao ' e junta os indíces das ' Pista 's com a mesma ' Instrucao '
no caso dos repetes se forem iguais entao a soma de cada x pertencente a um dos repetes com y pertencente a ao outro tem de dar [ x ] e nao [ x , y ]
somaPistas :: Instrucao -> Instrucao -> Instrucao
somaPistas (Anda l piso) (Anda l' _) = Anda (l++l') piso
somaPistas (Sobe l piso h) (Sobe l' _ _) = Sobe (l++l') piso h
somaPistas (Desce l piso h) (Desce l' _ _) = Desce (l++l') piso h
somaPistas (Repete i ins) (Repete _ ins') | length ins > length ins' = Repete i (juntaPrimeiraASegundaLista ins' ins)
| otherwise = Repete i (juntaPrimeiraASegundaLista ins ins')
|
0b8c1bde4256c27cfda00c22e8b0a393853c797980758c23cca430b369c5e741 | dyzsr/ocaml-selectml | t253-offsetclosure2.ml | TEST
include tool - ocaml - lib
flags = " -w -a "
ocaml_script_as_argument = " true "
* setup - ocaml - build - env
* *
include tool-ocaml-lib
flags = "-w -a"
ocaml_script_as_argument = "true"
* setup-ocaml-build-env
** ocaml
*)
open Lib;;
let rec f _ = g
and g _ = 10
in
if f 3 4 <> 10 then raise Not_found
;;
*
0 CONSTINT 42
2 PUSHACC0
3 MAKEBLOCK1 0
5 POP 1
7
9 BRANCH 18
11 OFFSETCLOSURE2
12 RETURN 1
14 CONSTINT 10
16 RETURN 1
18 CLOSUREREC 0 , 11 , 14
23 CONSTINT 10
25 PUSHCONSTINT 4
27 PUSHCONST3
28 PUSHACC4
29 APPLY2
30 NEQ
31 BRANCHIFNOT 38
33 GETGLOBAL Not_found
35 MAKEBLOCK1 0
37 RAISE
38 POP 2
40 ATOM0
41 SETGLOBAL T253 - offsetclosure2
43 STOP
*
0 CONSTINT 42
2 PUSHACC0
3 MAKEBLOCK1 0
5 POP 1
7 SETGLOBAL Lib
9 BRANCH 18
11 OFFSETCLOSURE2
12 RETURN 1
14 CONSTINT 10
16 RETURN 1
18 CLOSUREREC 0, 11, 14
23 CONSTINT 10
25 PUSHCONSTINT 4
27 PUSHCONST3
28 PUSHACC4
29 APPLY2
30 NEQ
31 BRANCHIFNOT 38
33 GETGLOBAL Not_found
35 MAKEBLOCK1 0
37 RAISE
38 POP 2
40 ATOM0
41 SETGLOBAL T253-offsetclosure2
43 STOP
**)
| null | https://raw.githubusercontent.com/dyzsr/ocaml-selectml/875544110abb3350e9fb5ec9bbadffa332c270d2/testsuite/tests/tool-ocaml/t253-offsetclosure2.ml | ocaml | TEST
include tool - ocaml - lib
flags = " -w -a "
ocaml_script_as_argument = " true "
* setup - ocaml - build - env
* *
include tool-ocaml-lib
flags = "-w -a"
ocaml_script_as_argument = "true"
* setup-ocaml-build-env
** ocaml
*)
open Lib;;
let rec f _ = g
and g _ = 10
in
if f 3 4 <> 10 then raise Not_found
;;
*
0 CONSTINT 42
2 PUSHACC0
3 MAKEBLOCK1 0
5 POP 1
7
9 BRANCH 18
11 OFFSETCLOSURE2
12 RETURN 1
14 CONSTINT 10
16 RETURN 1
18 CLOSUREREC 0 , 11 , 14
23 CONSTINT 10
25 PUSHCONSTINT 4
27 PUSHCONST3
28 PUSHACC4
29 APPLY2
30 NEQ
31 BRANCHIFNOT 38
33 GETGLOBAL Not_found
35 MAKEBLOCK1 0
37 RAISE
38 POP 2
40 ATOM0
41 SETGLOBAL T253 - offsetclosure2
43 STOP
*
0 CONSTINT 42
2 PUSHACC0
3 MAKEBLOCK1 0
5 POP 1
7 SETGLOBAL Lib
9 BRANCH 18
11 OFFSETCLOSURE2
12 RETURN 1
14 CONSTINT 10
16 RETURN 1
18 CLOSUREREC 0, 11, 14
23 CONSTINT 10
25 PUSHCONSTINT 4
27 PUSHCONST3
28 PUSHACC4
29 APPLY2
30 NEQ
31 BRANCHIFNOT 38
33 GETGLOBAL Not_found
35 MAKEBLOCK1 0
37 RAISE
38 POP 2
40 ATOM0
41 SETGLOBAL T253-offsetclosure2
43 STOP
**)
| |
36d2e510347c97b4dcbb74c3033f51a2bd721e511a7166eccc6a5b010414ed36 | racket/gui | tab-panel.rkt | #lang racket/base
(require racket/class
ffi/unsafe
"../../syntax.rkt"
"window.rkt"
"client-window.rkt"
"utils.rkt"
"panel.rkt"
"types.rkt"
"widget.rkt"
"message.rkt"
"../../lock.rkt"
"../common/event.rkt")
(provide
(protect-out tab-panel%))
(define-gtk gtk_notebook_new (_fun -> _GtkWidget))
(define-gtk gtk_notebook_append_page (_fun _GtkWidget _GtkWidget (_or-null _GtkWidget) -> _void))
(define-gtk gtk_notebook_remove_page (_fun _GtkWidget _int -> _void))
(define-gtk gtk_notebook_set_scrollable (_fun _GtkWidget _gboolean -> _void))
(define-gtk gtk_notebook_get_current_page (_fun _GtkWidget -> _int))
(define-gtk gtk_notebook_set_current_page (_fun _GtkWidget _int -> _void))
(define-gtk gtk_notebook_get_tab_label (_fun _GtkWidget _GtkWidget -> _GtkWidget))
(define-gtk gtk_notebook_set_tab_reorderable (_fun _GtkWidget _GtkWidget _gboolean -> _void))
(define-gtk gtk_container_remove (_fun _GtkWidget _GtkWidget -> _void))
(define text-close-label? #t)
;; Used for test close label:
(define-gtk gtk_label_new (_fun _string -> _GtkWidget))
(define-gtk gtk_label_set_use_markup (_fun _GtkWidget _gboolean -> _void))
(define-gtk gtk_label_set_use_underline (_fun _GtkWidget _gboolean -> _void))
;; Used for icon close label:
(define-gtk gtk_button_new (_fun -> _GtkWidget))
(define-gtk gtk_button_set_relief (_fun _GtkWidget _int -> _void))
(define-gtk gtk_button_set_image (_fun _GtkWidget _GtkWidget -> _void))
(define-gtk gtk_image_new_from_stock (_fun _string _int -> _GtkWidget))
(define GTK_STOCK_CLOSE "gtk-close")
(define GTK_ICON_SIZE_MENU 1)
(define GTK_RELIEF_NONE 2)
(define-gtk gtk_widget_get_parent (_fun _GtkWidget -> _GtkWidget))
(define-gtk gtk_widget_set_focus_on_click (_fun _GtkWidget _gboolean -> _void)
#:fail (lambda () (lambda (w focus?) (void))))
(define-gtk gtk_widget_ref (_fun _GtkWidget -> _void)
#:fail (lambda () g_object_ref))
(define-gtk gtk_widget_unref (_fun _GtkWidget -> _void)
#:fail (lambda () g_object_unref))
(define-struct page (bin-gtk label-gtk close-gtk))
(define-signal-handler connect-changed "switch-page"
(_fun _GtkWidget _pointer _int -> _void)
(lambda (gtk ignored i)
(let ([wx (gtk->wx gtk)])
(when wx
(send wx page-changed i)))))
(define-signal-handler connect-reordered "page-reordered"
(_fun _GtkWidget _pointer _int -> _void)
(lambda (gtk child i)
(let ([wx (gtk->wx gtk)])
(when wx
(send wx page-reordered child i)))))
(define-signal-handler connect-clicked "clicked"
(_fun _GtkWidget _GtkWidget -> _void)
(lambda (button-gtk gtk)
(let ([wx (gtk->wx gtk)])
(when wx
(send wx queue-close-clicked (gtk_widget_get_parent button-gtk))))))
(define tab-panel%
(class (client-size-mixin (panel-container-mixin (panel-mixin window%)))
(init parent
x y w h
style
labels)
(inherit set-size set-auto-size infer-client-delta get-gtk
reset-child-freezes reset-child-dcs get-height)
(define notebook-gtk (if gtk3?
(gtk_notebook_new)
(as-gtk-allocation (gtk_notebook_new))))
(define gtk (if gtk3?
;; For some reason, tabs in a hidden eventbox
;; don't work right. Add a layer.
(let ([gtk (as-gtk-allocation (gtk_event_box_new))])
(gtk_container_add gtk notebook-gtk)
(gtk_widget_show notebook-gtk)
gtk)
notebook-gtk))
Reparented so that it 's always in the current page 's :
(define client-gtk (gtk_fixed_new))
(gtk_notebook_set_scrollable notebook-gtk #t)
(define can-reorder? (and (memq 'can-reorder style) #t))
(define can-close? (and (memq 'can-close style) #t))
(super-new [parent parent]
[gtk gtk]
[client-gtk client-gtk]
[extra-gtks (append
(if (eq? gtk notebook-gtk)
null
(list notebook-gtk))
(list client-gtk))]
[no-show? (memq 'deleted style)])
; Once without tabs to set client-width delta:
(infer-client-delta #t #f)
(define empty-bin-gtk (gtk_hbox_new #f 0))
(define current-bin-gtk #f)
(define/private (select-bin bin-gtk)
(set! current-bin-gtk bin-gtk)
;; re-parenting can change the underlying window, so
;; make sure no freeze in places:
(reset-child-freezes)
(gtk_box_pack_start bin-gtk client-gtk #t #t 0)
;; re-parenting can change the underlying window dc:
(reset-child-dcs))
(define/private (maybe-add-close label-gtk)
(cond
[can-close?
(let ([hbox-gtk (gtk_hbox_new #f 0)]
[close-gtk (gtk_button_new)])
(cond
[text-close-label?
;; abuse of multiply symbol?
(define close-label-gtk (gtk_label_new "\xD7"))
(gtk_label_set_use_markup close-label-gtk #f)
(gtk_label_set_use_underline close-label-gtk #f)
(gtk_container_add close-gtk close-label-gtk)
(gtk_widget_show close-label-gtk)]
[else
;; looks heavy for most purposes:
(define close-icon (gtk_image_new_from_stock GTK_STOCK_CLOSE
GTK_ICON_SIZE_MENU))
(gtk_button_set_image close-gtk close-icon)])
(gtk_widget_set_focus_on_click close-gtk #f)
(gtk_button_set_relief close-gtk GTK_RELIEF_NONE)
(gtk_container_add hbox-gtk label-gtk)
(gtk_container_add hbox-gtk close-gtk)
(gtk_widget_show close-gtk)
(gtk_widget_show label-gtk)
(connect-clicked close-gtk gtk)
hbox-gtk)]
[else label-gtk]))
(define pages
(for/list ([lbl labels])
(let* ([bin-gtk (gtk_hbox_new #f 0)]
[label-gtk (gtk_label_new_with_mnemonic lbl)]
[close-gtk (maybe-add-close label-gtk)])
(gtk_notebook_append_page notebook-gtk bin-gtk close-gtk)
(when can-reorder?
(gtk_notebook_set_tab_reorderable notebook-gtk bin-gtk #t))
(gtk_widget_show bin-gtk)
(make-page bin-gtk label-gtk close-gtk))))
(define/private (install-empty-page)
(gtk_notebook_append_page notebook-gtk empty-bin-gtk #f)
(gtk_widget_show empty-bin-gtk))
(if (null? pages)
(begin
(select-bin empty-bin-gtk)
(install-empty-page))
(begin
(select-bin (page-bin-gtk (car pages)))))
(gtk_widget_show client-gtk)
(connect-key-and-mouse notebook-gtk)
(connect-focus notebook-gtk)
; With tabs to set client-width delta:
(infer-client-delta #f #t)
(set-auto-size)
(define callback void)
(define/public (set-callback cb) (set! callback cb))
(define/private (do-callback)
(callback this (new control-event%
[event-type 'tab-panel]
[time-stamp (current-milliseconds)])))
(define/public (swap-in bin-gtk)
(gtk_widget_ref client-gtk)
(gtk_container_remove current-bin-gtk client-gtk)
(select-bin bin-gtk)
(gtk_widget_unref client-gtk))
(define callback-ok? #t)
(define/public (page-changed i)
; range check works around spurious callbacks:
(when (< -1 i (length pages))
(swap-in (page-bin-gtk (list-ref pages i)))
(when callback-ok?
(queue-window-event this (lambda () (do-callback))))))
(connect-changed notebook-gtk)
(define/public (page-reordered child new-pos)
(unless (equal? child (list-ref pages new-pos))
(define old-pages (for/hash ([page (in-list pages)]
[i (in-naturals)])
(values (page-bin-gtk page) (cons i page))))
(define move-page (cdr (hash-ref old-pages child)))
(define new-pages (let loop ([l pages] [i 0])
(cond
[(= i new-pos) (cons move-page (remove move-page l))]
[(equal? (car l) move-page)
(loop (cdr l) i)]
[else
(cons (car l) (loop (cdr l) (add1 i)))])))
(set! pages new-pages)
(on-choice-reorder (for/list ([page (in-list new-pages)])
(car (hash-ref old-pages (page-bin-gtk page)))))))
(define/public (on-choice-reorder moved-mapping) (void))
(when can-reorder?
(connect-reordered notebook-gtk))
(define/public (queue-close-clicked close-gtk)
(for ([page (in-list pages)]
[i (in-naturals)])
(when (equal? close-gtk (page-close-gtk page))
(queue-window-event this (lambda () (on-choice-close i))))))
(define/public (on-choice-close pos) (void))
(define/override (get-client-gtk) client-gtk)
(public [append* append])
(define (append* lbl)
(atomically
(set! callback-ok? #f)
(do-append lbl)
(set! callback-ok? #t)))
(define/private (do-append lbl)
(let ([page
(let* ([bin-gtk (gtk_hbox_new #f 0)]
[label-gtk (gtk_label_new_with_mnemonic lbl)]
[close-gtk (maybe-add-close label-gtk)])
(gtk_notebook_append_page notebook-gtk bin-gtk close-gtk)
(when can-reorder?
(gtk_notebook_set_tab_reorderable notebook-gtk bin-gtk #t))
(gtk_widget_show bin-gtk)
(make-page bin-gtk label-gtk close-gtk))])
(set! pages (append pages (list page)))
(when (null? (cdr pages))
(swap-in (page-bin-gtk (car pages)))
(g_object_ref empty-bin-gtk)
(gtk_notebook_remove_page notebook-gtk 0))))
(define/private (do-delete i)
(let ([page (list-ref pages i)])
(when (ptr-equal? current-bin-gtk (page-bin-gtk page))
(let ([cnt (length pages)])
(if (= i (sub1 cnt))
(if (null? (cdr pages))
(begin
(install-empty-page)
(set! pages null)
(gtk_notebook_set_current_page notebook-gtk 1)
(swap-in empty-bin-gtk))
(gtk_notebook_set_current_page notebook-gtk (sub1 i)))
(gtk_notebook_set_current_page notebook-gtk (add1 i)))))
(gtk_notebook_remove_page notebook-gtk i)
(set! pages (remq page pages))))
(define/public (delete i)
(atomically
(set! callback-ok? #f)
(do-delete i)
(set! callback-ok? #t)))
(define/public (set choices)
(atomically
(set! callback-ok? #f)
(for ([page (in-list pages)])
(do-delete 0))
(for ([lbl (in-list choices)])
(append* lbl))
(set! callback-ok? #t)))
(define/public (set-label i str)
(gtk_label_set_text_with_mnemonic (page-label-gtk (list-ref pages i))
(mnemonic-string str)))
(define/public (number) (length pages))
(define/public (button-focus n)
(if (= n -1)
(get-selection)
(direct-set-selection n)))
(define/override (gets-focus?) #t)
(define/override (set-focus)
(gtk_widget_grab_focus notebook-gtk))
(define/private (direct-set-selection i)
(gtk_notebook_set_current_page notebook-gtk i))
(define/public (set-selection i)
(atomically
(set! callback-ok? #f)
(direct-set-selection i)
(set! callback-ok? #t)))
(define/public (get-selection)
(gtk_notebook_get_current_page notebook-gtk))))
| null | https://raw.githubusercontent.com/racket/gui/d1fef7a43a482c0fdd5672be9a6e713f16d8be5c/gui-lib/mred/private/wx/gtk/tab-panel.rkt | racket | Used for test close label:
Used for icon close label:
For some reason, tabs in a hidden eventbox
don't work right. Add a layer.
Once without tabs to set client-width delta:
re-parenting can change the underlying window, so
make sure no freeze in places:
re-parenting can change the underlying window dc:
abuse of multiply symbol?
looks heavy for most purposes:
With tabs to set client-width delta:
range check works around spurious callbacks: | #lang racket/base
(require racket/class
ffi/unsafe
"../../syntax.rkt"
"window.rkt"
"client-window.rkt"
"utils.rkt"
"panel.rkt"
"types.rkt"
"widget.rkt"
"message.rkt"
"../../lock.rkt"
"../common/event.rkt")
(provide
(protect-out tab-panel%))
(define-gtk gtk_notebook_new (_fun -> _GtkWidget))
(define-gtk gtk_notebook_append_page (_fun _GtkWidget _GtkWidget (_or-null _GtkWidget) -> _void))
(define-gtk gtk_notebook_remove_page (_fun _GtkWidget _int -> _void))
(define-gtk gtk_notebook_set_scrollable (_fun _GtkWidget _gboolean -> _void))
(define-gtk gtk_notebook_get_current_page (_fun _GtkWidget -> _int))
(define-gtk gtk_notebook_set_current_page (_fun _GtkWidget _int -> _void))
(define-gtk gtk_notebook_get_tab_label (_fun _GtkWidget _GtkWidget -> _GtkWidget))
(define-gtk gtk_notebook_set_tab_reorderable (_fun _GtkWidget _GtkWidget _gboolean -> _void))
(define-gtk gtk_container_remove (_fun _GtkWidget _GtkWidget -> _void))
(define text-close-label? #t)
(define-gtk gtk_label_new (_fun _string -> _GtkWidget))
(define-gtk gtk_label_set_use_markup (_fun _GtkWidget _gboolean -> _void))
(define-gtk gtk_label_set_use_underline (_fun _GtkWidget _gboolean -> _void))
(define-gtk gtk_button_new (_fun -> _GtkWidget))
(define-gtk gtk_button_set_relief (_fun _GtkWidget _int -> _void))
(define-gtk gtk_button_set_image (_fun _GtkWidget _GtkWidget -> _void))
(define-gtk gtk_image_new_from_stock (_fun _string _int -> _GtkWidget))
(define GTK_STOCK_CLOSE "gtk-close")
(define GTK_ICON_SIZE_MENU 1)
(define GTK_RELIEF_NONE 2)
(define-gtk gtk_widget_get_parent (_fun _GtkWidget -> _GtkWidget))
(define-gtk gtk_widget_set_focus_on_click (_fun _GtkWidget _gboolean -> _void)
#:fail (lambda () (lambda (w focus?) (void))))
(define-gtk gtk_widget_ref (_fun _GtkWidget -> _void)
#:fail (lambda () g_object_ref))
(define-gtk gtk_widget_unref (_fun _GtkWidget -> _void)
#:fail (lambda () g_object_unref))
(define-struct page (bin-gtk label-gtk close-gtk))
(define-signal-handler connect-changed "switch-page"
(_fun _GtkWidget _pointer _int -> _void)
(lambda (gtk ignored i)
(let ([wx (gtk->wx gtk)])
(when wx
(send wx page-changed i)))))
(define-signal-handler connect-reordered "page-reordered"
(_fun _GtkWidget _pointer _int -> _void)
(lambda (gtk child i)
(let ([wx (gtk->wx gtk)])
(when wx
(send wx page-reordered child i)))))
(define-signal-handler connect-clicked "clicked"
(_fun _GtkWidget _GtkWidget -> _void)
(lambda (button-gtk gtk)
(let ([wx (gtk->wx gtk)])
(when wx
(send wx queue-close-clicked (gtk_widget_get_parent button-gtk))))))
(define tab-panel%
(class (client-size-mixin (panel-container-mixin (panel-mixin window%)))
(init parent
x y w h
style
labels)
(inherit set-size set-auto-size infer-client-delta get-gtk
reset-child-freezes reset-child-dcs get-height)
(define notebook-gtk (if gtk3?
(gtk_notebook_new)
(as-gtk-allocation (gtk_notebook_new))))
(define gtk (if gtk3?
(let ([gtk (as-gtk-allocation (gtk_event_box_new))])
(gtk_container_add gtk notebook-gtk)
(gtk_widget_show notebook-gtk)
gtk)
notebook-gtk))
Reparented so that it 's always in the current page 's :
(define client-gtk (gtk_fixed_new))
(gtk_notebook_set_scrollable notebook-gtk #t)
(define can-reorder? (and (memq 'can-reorder style) #t))
(define can-close? (and (memq 'can-close style) #t))
(super-new [parent parent]
[gtk gtk]
[client-gtk client-gtk]
[extra-gtks (append
(if (eq? gtk notebook-gtk)
null
(list notebook-gtk))
(list client-gtk))]
[no-show? (memq 'deleted style)])
(infer-client-delta #t #f)
(define empty-bin-gtk (gtk_hbox_new #f 0))
(define current-bin-gtk #f)
(define/private (select-bin bin-gtk)
(set! current-bin-gtk bin-gtk)
(reset-child-freezes)
(gtk_box_pack_start bin-gtk client-gtk #t #t 0)
(reset-child-dcs))
(define/private (maybe-add-close label-gtk)
(cond
[can-close?
(let ([hbox-gtk (gtk_hbox_new #f 0)]
[close-gtk (gtk_button_new)])
(cond
[text-close-label?
(define close-label-gtk (gtk_label_new "\xD7"))
(gtk_label_set_use_markup close-label-gtk #f)
(gtk_label_set_use_underline close-label-gtk #f)
(gtk_container_add close-gtk close-label-gtk)
(gtk_widget_show close-label-gtk)]
[else
(define close-icon (gtk_image_new_from_stock GTK_STOCK_CLOSE
GTK_ICON_SIZE_MENU))
(gtk_button_set_image close-gtk close-icon)])
(gtk_widget_set_focus_on_click close-gtk #f)
(gtk_button_set_relief close-gtk GTK_RELIEF_NONE)
(gtk_container_add hbox-gtk label-gtk)
(gtk_container_add hbox-gtk close-gtk)
(gtk_widget_show close-gtk)
(gtk_widget_show label-gtk)
(connect-clicked close-gtk gtk)
hbox-gtk)]
[else label-gtk]))
(define pages
(for/list ([lbl labels])
(let* ([bin-gtk (gtk_hbox_new #f 0)]
[label-gtk (gtk_label_new_with_mnemonic lbl)]
[close-gtk (maybe-add-close label-gtk)])
(gtk_notebook_append_page notebook-gtk bin-gtk close-gtk)
(when can-reorder?
(gtk_notebook_set_tab_reorderable notebook-gtk bin-gtk #t))
(gtk_widget_show bin-gtk)
(make-page bin-gtk label-gtk close-gtk))))
(define/private (install-empty-page)
(gtk_notebook_append_page notebook-gtk empty-bin-gtk #f)
(gtk_widget_show empty-bin-gtk))
(if (null? pages)
(begin
(select-bin empty-bin-gtk)
(install-empty-page))
(begin
(select-bin (page-bin-gtk (car pages)))))
(gtk_widget_show client-gtk)
(connect-key-and-mouse notebook-gtk)
(connect-focus notebook-gtk)
(infer-client-delta #f #t)
(set-auto-size)
(define callback void)
(define/public (set-callback cb) (set! callback cb))
(define/private (do-callback)
(callback this (new control-event%
[event-type 'tab-panel]
[time-stamp (current-milliseconds)])))
(define/public (swap-in bin-gtk)
(gtk_widget_ref client-gtk)
(gtk_container_remove current-bin-gtk client-gtk)
(select-bin bin-gtk)
(gtk_widget_unref client-gtk))
(define callback-ok? #t)
(define/public (page-changed i)
(when (< -1 i (length pages))
(swap-in (page-bin-gtk (list-ref pages i)))
(when callback-ok?
(queue-window-event this (lambda () (do-callback))))))
(connect-changed notebook-gtk)
(define/public (page-reordered child new-pos)
(unless (equal? child (list-ref pages new-pos))
(define old-pages (for/hash ([page (in-list pages)]
[i (in-naturals)])
(values (page-bin-gtk page) (cons i page))))
(define move-page (cdr (hash-ref old-pages child)))
(define new-pages (let loop ([l pages] [i 0])
(cond
[(= i new-pos) (cons move-page (remove move-page l))]
[(equal? (car l) move-page)
(loop (cdr l) i)]
[else
(cons (car l) (loop (cdr l) (add1 i)))])))
(set! pages new-pages)
(on-choice-reorder (for/list ([page (in-list new-pages)])
(car (hash-ref old-pages (page-bin-gtk page)))))))
(define/public (on-choice-reorder moved-mapping) (void))
(when can-reorder?
(connect-reordered notebook-gtk))
(define/public (queue-close-clicked close-gtk)
(for ([page (in-list pages)]
[i (in-naturals)])
(when (equal? close-gtk (page-close-gtk page))
(queue-window-event this (lambda () (on-choice-close i))))))
(define/public (on-choice-close pos) (void))
(define/override (get-client-gtk) client-gtk)
(public [append* append])
(define (append* lbl)
(atomically
(set! callback-ok? #f)
(do-append lbl)
(set! callback-ok? #t)))
(define/private (do-append lbl)
(let ([page
(let* ([bin-gtk (gtk_hbox_new #f 0)]
[label-gtk (gtk_label_new_with_mnemonic lbl)]
[close-gtk (maybe-add-close label-gtk)])
(gtk_notebook_append_page notebook-gtk bin-gtk close-gtk)
(when can-reorder?
(gtk_notebook_set_tab_reorderable notebook-gtk bin-gtk #t))
(gtk_widget_show bin-gtk)
(make-page bin-gtk label-gtk close-gtk))])
(set! pages (append pages (list page)))
(when (null? (cdr pages))
(swap-in (page-bin-gtk (car pages)))
(g_object_ref empty-bin-gtk)
(gtk_notebook_remove_page notebook-gtk 0))))
(define/private (do-delete i)
(let ([page (list-ref pages i)])
(when (ptr-equal? current-bin-gtk (page-bin-gtk page))
(let ([cnt (length pages)])
(if (= i (sub1 cnt))
(if (null? (cdr pages))
(begin
(install-empty-page)
(set! pages null)
(gtk_notebook_set_current_page notebook-gtk 1)
(swap-in empty-bin-gtk))
(gtk_notebook_set_current_page notebook-gtk (sub1 i)))
(gtk_notebook_set_current_page notebook-gtk (add1 i)))))
(gtk_notebook_remove_page notebook-gtk i)
(set! pages (remq page pages))))
(define/public (delete i)
(atomically
(set! callback-ok? #f)
(do-delete i)
(set! callback-ok? #t)))
(define/public (set choices)
(atomically
(set! callback-ok? #f)
(for ([page (in-list pages)])
(do-delete 0))
(for ([lbl (in-list choices)])
(append* lbl))
(set! callback-ok? #t)))
(define/public (set-label i str)
(gtk_label_set_text_with_mnemonic (page-label-gtk (list-ref pages i))
(mnemonic-string str)))
(define/public (number) (length pages))
(define/public (button-focus n)
(if (= n -1)
(get-selection)
(direct-set-selection n)))
(define/override (gets-focus?) #t)
(define/override (set-focus)
(gtk_widget_grab_focus notebook-gtk))
(define/private (direct-set-selection i)
(gtk_notebook_set_current_page notebook-gtk i))
(define/public (set-selection i)
(atomically
(set! callback-ok? #f)
(direct-set-selection i)
(set! callback-ok? #t)))
(define/public (get-selection)
(gtk_notebook_get_current_page notebook-gtk))))
|
4999986a78498a937b63f184c49af5d607922ff00e75485e38b41e1a252c34ba | janestreet/base | sign_or_nan.ml | open! Import
module T = struct
type t =
| Neg
| Zero
| Pos
| Nan
[@@deriving_inline sexp, sexp_grammar, compare, hash, enumerate]
let t_of_sexp =
(let error_source__003_ = "sign_or_nan.ml.T.t" in
function
| Sexplib0.Sexp.Atom ("neg" | "Neg") -> Neg
| Sexplib0.Sexp.Atom ("zero" | "Zero") -> Zero
| Sexplib0.Sexp.Atom ("pos" | "Pos") -> Pos
| Sexplib0.Sexp.Atom ("nan" | "Nan") -> Nan
| Sexplib0.Sexp.List (Sexplib0.Sexp.Atom ("neg" | "Neg") :: _) as sexp__004_ ->
Sexplib0.Sexp_conv_error.stag_no_args error_source__003_ sexp__004_
| Sexplib0.Sexp.List (Sexplib0.Sexp.Atom ("zero" | "Zero") :: _) as sexp__004_ ->
Sexplib0.Sexp_conv_error.stag_no_args error_source__003_ sexp__004_
| Sexplib0.Sexp.List (Sexplib0.Sexp.Atom ("pos" | "Pos") :: _) as sexp__004_ ->
Sexplib0.Sexp_conv_error.stag_no_args error_source__003_ sexp__004_
| Sexplib0.Sexp.List (Sexplib0.Sexp.Atom ("nan" | "Nan") :: _) as sexp__004_ ->
Sexplib0.Sexp_conv_error.stag_no_args error_source__003_ sexp__004_
| Sexplib0.Sexp.List (Sexplib0.Sexp.List _ :: _) as sexp__002_ ->
Sexplib0.Sexp_conv_error.nested_list_invalid_sum error_source__003_ sexp__002_
| Sexplib0.Sexp.List [] as sexp__002_ ->
Sexplib0.Sexp_conv_error.empty_list_invalid_sum error_source__003_ sexp__002_
| sexp__002_ ->
Sexplib0.Sexp_conv_error.unexpected_stag error_source__003_ sexp__002_
: Sexplib0.Sexp.t -> t)
;;
let sexp_of_t =
(function
| Neg -> Sexplib0.Sexp.Atom "Neg"
| Zero -> Sexplib0.Sexp.Atom "Zero"
| Pos -> Sexplib0.Sexp.Atom "Pos"
| Nan -> Sexplib0.Sexp.Atom "Nan"
: t -> Sexplib0.Sexp.t)
;;
let (t_sexp_grammar : t Sexplib0.Sexp_grammar.t) =
{ untyped =
Variant
{ case_sensitivity = Case_sensitive_except_first_character
; clauses =
[ No_tag { name = "Neg"; clause_kind = Atom_clause }
; No_tag { name = "Zero"; clause_kind = Atom_clause }
; No_tag { name = "Pos"; clause_kind = Atom_clause }
; No_tag { name = "Nan"; clause_kind = Atom_clause }
]
}
}
;;
let compare = (Stdlib.compare : t -> t -> int)
let (hash_fold_t : Ppx_hash_lib.Std.Hash.state -> t -> Ppx_hash_lib.Std.Hash.state) =
(fun hsv arg ->
match arg with
| Neg -> Ppx_hash_lib.Std.Hash.fold_int hsv 0
| Zero -> Ppx_hash_lib.Std.Hash.fold_int hsv 1
| Pos -> Ppx_hash_lib.Std.Hash.fold_int hsv 2
| Nan -> Ppx_hash_lib.Std.Hash.fold_int hsv 3
: Ppx_hash_lib.Std.Hash.state -> t -> Ppx_hash_lib.Std.Hash.state)
;;
let (hash : t -> Ppx_hash_lib.Std.Hash.hash_value) =
let func arg =
Ppx_hash_lib.Std.Hash.get_hash_value
(let hsv = Ppx_hash_lib.Std.Hash.create () in
hash_fold_t hsv arg)
in
fun x -> func x
;;
let all = ([ Neg; Zero; Pos; Nan ] : t list)
[@@@end]
let of_string s = t_of_sexp (sexp_of_string s)
let to_string t = string_of_sexp (sexp_of_t t)
let module_name = "Base.Sign_or_nan"
end
module Replace_polymorphic_compare = struct
let ( < ) (x : T.t) y = Poly.( < ) x y
let ( <= ) (x : T.t) y = Poly.( <= ) x y
let ( <> ) (x : T.t) y = Poly.( <> ) x y
let ( = ) (x : T.t) y = Poly.( = ) x y
let ( > ) (x : T.t) y = Poly.( > ) x y
let ( >= ) (x : T.t) y = Poly.( >= ) x y
let ascending (x : T.t) y = Poly.ascending x y
let descending (x : T.t) y = Poly.descending x y
let compare (x : T.t) y = Poly.compare x y
let equal (x : T.t) y = Poly.equal x y
let max (x : T.t) y = if x >= y then x else y
let min (x : T.t) y = if x <= y then x else y
end
include T
include Identifiable.Make (T)
(* Open [Replace_polymorphic_compare] after including functor applications so they do not
shadow its definitions. This is here so that efficient versions of the comparison
functions are available within this module. *)
open! Replace_polymorphic_compare
let of_sign = function
| Sign.Neg -> Neg
| Sign.Zero -> Zero
| Sign.Pos -> Pos
;;
let to_sign_exn = function
| Neg -> Sign.Neg
| Zero -> Sign.Zero
| Pos -> Sign.Pos
| Nan -> invalid_arg "Base.Sign_or_nan.to_sign_exn: Nan"
;;
let of_int n = of_sign (Sign.of_int n)
let to_int_exn t = Sign.to_int (to_sign_exn t)
let flip = function
| Neg -> Pos
| Zero -> Zero
| Pos -> Neg
| Nan -> Nan
;;
let ( * ) t t' =
match t, t' with
| Nan, _ | _, Nan -> Nan
| _ -> of_sign (Sign.( * ) (to_sign_exn t) (to_sign_exn t'))
;;
let to_string_hum = function
| Neg -> "negative"
| Zero -> "zero"
| Pos -> "positive"
| Nan -> "not-a-number"
;;
(* Include [Replace_polymorphic_compare] at the end, after any functor applications that
could shadow its definitions. This is here so that efficient versions of the comparison
functions are exported by this module. *)
include Replace_polymorphic_compare
| null | https://raw.githubusercontent.com/janestreet/base/1462b7d5458e96569275a1c673df968ecbf3342f/src/sign_or_nan.ml | ocaml | Open [Replace_polymorphic_compare] after including functor applications so they do not
shadow its definitions. This is here so that efficient versions of the comparison
functions are available within this module.
Include [Replace_polymorphic_compare] at the end, after any functor applications that
could shadow its definitions. This is here so that efficient versions of the comparison
functions are exported by this module. | open! Import
module T = struct
type t =
| Neg
| Zero
| Pos
| Nan
[@@deriving_inline sexp, sexp_grammar, compare, hash, enumerate]
let t_of_sexp =
(let error_source__003_ = "sign_or_nan.ml.T.t" in
function
| Sexplib0.Sexp.Atom ("neg" | "Neg") -> Neg
| Sexplib0.Sexp.Atom ("zero" | "Zero") -> Zero
| Sexplib0.Sexp.Atom ("pos" | "Pos") -> Pos
| Sexplib0.Sexp.Atom ("nan" | "Nan") -> Nan
| Sexplib0.Sexp.List (Sexplib0.Sexp.Atom ("neg" | "Neg") :: _) as sexp__004_ ->
Sexplib0.Sexp_conv_error.stag_no_args error_source__003_ sexp__004_
| Sexplib0.Sexp.List (Sexplib0.Sexp.Atom ("zero" | "Zero") :: _) as sexp__004_ ->
Sexplib0.Sexp_conv_error.stag_no_args error_source__003_ sexp__004_
| Sexplib0.Sexp.List (Sexplib0.Sexp.Atom ("pos" | "Pos") :: _) as sexp__004_ ->
Sexplib0.Sexp_conv_error.stag_no_args error_source__003_ sexp__004_
| Sexplib0.Sexp.List (Sexplib0.Sexp.Atom ("nan" | "Nan") :: _) as sexp__004_ ->
Sexplib0.Sexp_conv_error.stag_no_args error_source__003_ sexp__004_
| Sexplib0.Sexp.List (Sexplib0.Sexp.List _ :: _) as sexp__002_ ->
Sexplib0.Sexp_conv_error.nested_list_invalid_sum error_source__003_ sexp__002_
| Sexplib0.Sexp.List [] as sexp__002_ ->
Sexplib0.Sexp_conv_error.empty_list_invalid_sum error_source__003_ sexp__002_
| sexp__002_ ->
Sexplib0.Sexp_conv_error.unexpected_stag error_source__003_ sexp__002_
: Sexplib0.Sexp.t -> t)
;;
let sexp_of_t =
(function
| Neg -> Sexplib0.Sexp.Atom "Neg"
| Zero -> Sexplib0.Sexp.Atom "Zero"
| Pos -> Sexplib0.Sexp.Atom "Pos"
| Nan -> Sexplib0.Sexp.Atom "Nan"
: t -> Sexplib0.Sexp.t)
;;
let (t_sexp_grammar : t Sexplib0.Sexp_grammar.t) =
{ untyped =
Variant
{ case_sensitivity = Case_sensitive_except_first_character
; clauses =
[ No_tag { name = "Neg"; clause_kind = Atom_clause }
; No_tag { name = "Zero"; clause_kind = Atom_clause }
; No_tag { name = "Pos"; clause_kind = Atom_clause }
; No_tag { name = "Nan"; clause_kind = Atom_clause }
]
}
}
;;
let compare = (Stdlib.compare : t -> t -> int)
let (hash_fold_t : Ppx_hash_lib.Std.Hash.state -> t -> Ppx_hash_lib.Std.Hash.state) =
(fun hsv arg ->
match arg with
| Neg -> Ppx_hash_lib.Std.Hash.fold_int hsv 0
| Zero -> Ppx_hash_lib.Std.Hash.fold_int hsv 1
| Pos -> Ppx_hash_lib.Std.Hash.fold_int hsv 2
| Nan -> Ppx_hash_lib.Std.Hash.fold_int hsv 3
: Ppx_hash_lib.Std.Hash.state -> t -> Ppx_hash_lib.Std.Hash.state)
;;
let (hash : t -> Ppx_hash_lib.Std.Hash.hash_value) =
let func arg =
Ppx_hash_lib.Std.Hash.get_hash_value
(let hsv = Ppx_hash_lib.Std.Hash.create () in
hash_fold_t hsv arg)
in
fun x -> func x
;;
let all = ([ Neg; Zero; Pos; Nan ] : t list)
[@@@end]
let of_string s = t_of_sexp (sexp_of_string s)
let to_string t = string_of_sexp (sexp_of_t t)
let module_name = "Base.Sign_or_nan"
end
module Replace_polymorphic_compare = struct
let ( < ) (x : T.t) y = Poly.( < ) x y
let ( <= ) (x : T.t) y = Poly.( <= ) x y
let ( <> ) (x : T.t) y = Poly.( <> ) x y
let ( = ) (x : T.t) y = Poly.( = ) x y
let ( > ) (x : T.t) y = Poly.( > ) x y
let ( >= ) (x : T.t) y = Poly.( >= ) x y
let ascending (x : T.t) y = Poly.ascending x y
let descending (x : T.t) y = Poly.descending x y
let compare (x : T.t) y = Poly.compare x y
let equal (x : T.t) y = Poly.equal x y
let max (x : T.t) y = if x >= y then x else y
let min (x : T.t) y = if x <= y then x else y
end
include T
include Identifiable.Make (T)
open! Replace_polymorphic_compare
let of_sign = function
| Sign.Neg -> Neg
| Sign.Zero -> Zero
| Sign.Pos -> Pos
;;
let to_sign_exn = function
| Neg -> Sign.Neg
| Zero -> Sign.Zero
| Pos -> Sign.Pos
| Nan -> invalid_arg "Base.Sign_or_nan.to_sign_exn: Nan"
;;
let of_int n = of_sign (Sign.of_int n)
let to_int_exn t = Sign.to_int (to_sign_exn t)
let flip = function
| Neg -> Pos
| Zero -> Zero
| Pos -> Neg
| Nan -> Nan
;;
let ( * ) t t' =
match t, t' with
| Nan, _ | _, Nan -> Nan
| _ -> of_sign (Sign.( * ) (to_sign_exn t) (to_sign_exn t'))
;;
let to_string_hum = function
| Neg -> "negative"
| Zero -> "zero"
| Pos -> "positive"
| Nan -> "not-a-number"
;;
include Replace_polymorphic_compare
|
28302876f7f8cb48560e89e913fb9413f7d7da2f7be78aa70ca25e34f710a026 | michalkonecny/aern2 | aern2-real-cdar-simpleOp.hs | |
Module : Main ( file aern2 - real - benchOp )
Description : execute a simple CR expression
Copyright : ( c ) : :
Stability : experimental
Portability : portable
Module : Main (file aern2-real-benchOp)
Description : execute a simple CR expression
Copyright : (c) Michal Konecny
License : BSD3
Maintainer :
Stability : experimental
Portability : portable
-}
module Main where
import MixedTypesNumPrelude
import Prelude
import Text.Printf
import System.Environment
import Data.CDAR
main :: IO ()
main =
do
args <- getArgs
(computationDescription, result) <- processArgs args
putStrLn $ computationDescription
putStrLn $ "result = " ++ showA result
processArgs ::
[String] ->
IO (String, Approx)
processArgs [op, accuracyS] =
return (computationDescription, result)
where
computationDescription =
printf "computing %s using accuracy %d" op ac
ac :: Int
ac = read accuracyS
result =
case op of
-- "exp" ->
map ( ( ? ( ac ) ) . exp ) $
unsafePerformIO $ pickValues valuesSmall count
-- "log" ->
map ( ( ~ ! ) . ( ? ( ) ) . log ) $
unsafePerformIO $ count
"sqrt2" ->
require ac $ sqrt 2
-- "cos" ->
map ( ( ? ( ac ) ) . cos ) $
-- unsafePerformIO $ pickValues values count
-- "add" ->
map ( ( ? ( ac ) ) . ( uncurry ( + ) ) ) $
-- unsafePerformIO $ pickValues2 values values count
-- "mul" ->
map ( ( ? ( ac ) ) . ( uncurry ( * ) ) ) $
-- unsafePerformIO $ pickValues2 values values count
-- "div" ->
map ( ( ~ ! ) . ( ? ( ) ) . ( uncurry ( / ) ) ) $
unsafePerformIO $ pickValues2 values valuesPositive count
-- "logistic" ->
map ( ( ? ( ac ) ) . ( logistic 3.82 count ) ) $
[ real 0.125 ]
_ -> error $ "unknown op " ++ op
processArgs _ =
error "expecting arguments: <operation> <precision>"
-- logistic :: Rational -> Integer -> CauchyReal -> CauchyReal
-- logistic c n x
-- | n == 0 = x
| otherwise = logistic c ( n-1 ) $ c * x * ( 1 - x )
| null | https://raw.githubusercontent.com/michalkonecny/aern2/7ab41113ca8f73dca70d887d190ddab3b43ef084/aern2-net/bench/aern2-real-cdar-simpleOp.hs | haskell | "exp" ->
"log" ->
"cos" ->
unsafePerformIO $ pickValues values count
"add" ->
unsafePerformIO $ pickValues2 values values count
"mul" ->
unsafePerformIO $ pickValues2 values values count
"div" ->
"logistic" ->
logistic :: Rational -> Integer -> CauchyReal -> CauchyReal
logistic c n x
| n == 0 = x | |
Module : Main ( file aern2 - real - benchOp )
Description : execute a simple CR expression
Copyright : ( c ) : :
Stability : experimental
Portability : portable
Module : Main (file aern2-real-benchOp)
Description : execute a simple CR expression
Copyright : (c) Michal Konecny
License : BSD3
Maintainer :
Stability : experimental
Portability : portable
-}
module Main where
import MixedTypesNumPrelude
import Prelude
import Text.Printf
import System.Environment
import Data.CDAR
main :: IO ()
main =
do
args <- getArgs
(computationDescription, result) <- processArgs args
putStrLn $ computationDescription
putStrLn $ "result = " ++ showA result
processArgs ::
[String] ->
IO (String, Approx)
processArgs [op, accuracyS] =
return (computationDescription, result)
where
computationDescription =
printf "computing %s using accuracy %d" op ac
ac :: Int
ac = read accuracyS
result =
case op of
map ( ( ? ( ac ) ) . exp ) $
unsafePerformIO $ pickValues valuesSmall count
map ( ( ~ ! ) . ( ? ( ) ) . log ) $
unsafePerformIO $ count
"sqrt2" ->
require ac $ sqrt 2
map ( ( ? ( ac ) ) . cos ) $
map ( ( ? ( ac ) ) . ( uncurry ( + ) ) ) $
map ( ( ? ( ac ) ) . ( uncurry ( * ) ) ) $
map ( ( ~ ! ) . ( ? ( ) ) . ( uncurry ( / ) ) ) $
unsafePerformIO $ pickValues2 values valuesPositive count
map ( ( ? ( ac ) ) . ( logistic 3.82 count ) ) $
[ real 0.125 ]
_ -> error $ "unknown op " ++ op
processArgs _ =
error "expecting arguments: <operation> <precision>"
| otherwise = logistic c ( n-1 ) $ c * x * ( 1 - x )
|
6fe65e13b18b75ae39dd743ac7b8fe2f248447b2ddb3df0ef90d328853e44428 | ultralisp/ultralisp | package-variance-fix.lisp | (defpackage #:ultralisp/package-variance-fix
(:use #:cl)
(:import-from #:log4cl))
(in-package #:ultralisp/package-variance-fix)
;; For some reasons, some libraries start to raise ASDF compile errors
;; because of package variance. This is the only hack I could imagine
to suppress warnings from SBCL during compilation .
#+sbcl
(defmethod asdf/component:around-compile-hook :around ((component t))
(let ((previous-hook (call-next-method)))
(lambda (compile-function)
(handler-bind ((sb-int:package-at-variance-error
(lambda (c)
(log:warn "Suppressing package-at-varience-error: ~S"
(apply #'format nil
(simple-condition-format-control c)
(simple-condition-format-arguments c)))
(invoke-restart 'sb-impl::drop-them))))
We need this binding to make sbcl signal a restartable error
(let ((sb-ext:*on-package-variance* '(:error t)))
(if previous-hook
(funcall previous-hook compile-function)
(funcall compile-function)))))))
| null | https://raw.githubusercontent.com/ultralisp/ultralisp/37bd5d92b2cf751cd03ced69bac785bf4bcb6c15/src/package-variance-fix.lisp | lisp | For some reasons, some libraries start to raise ASDF compile errors
because of package variance. This is the only hack I could imagine | (defpackage #:ultralisp/package-variance-fix
(:use #:cl)
(:import-from #:log4cl))
(in-package #:ultralisp/package-variance-fix)
to suppress warnings from SBCL during compilation .
#+sbcl
(defmethod asdf/component:around-compile-hook :around ((component t))
(let ((previous-hook (call-next-method)))
(lambda (compile-function)
(handler-bind ((sb-int:package-at-variance-error
(lambda (c)
(log:warn "Suppressing package-at-varience-error: ~S"
(apply #'format nil
(simple-condition-format-control c)
(simple-condition-format-arguments c)))
(invoke-restart 'sb-impl::drop-them))))
We need this binding to make sbcl signal a restartable error
(let ((sb-ext:*on-package-variance* '(:error t)))
(if previous-hook
(funcall previous-hook compile-function)
(funcall compile-function)))))))
|
d1484f620537388b03161d0d47dc027b191d8998f5f3eaab27cc2bbf1e88ef68 | PacktPublishing/Data-Analysis-with-IBM-SPSS-Statistics | Create GSS2016 small28 40317.sps | * Encoding: UTF-8.
* create GSS2016small with 28 fields.
* Modified 4/3/17 to use INCOM06 rather than INCOME - better set of values.
SAVE OUTFILE='C:\GSS Data\GSS2016sm28 40317.sav'
/keep = happy marital hapmar age
VOTE12 PRES12 educ speduc natpark natroad NATENRGY
cappun natmass natchld natsci
partyid degree incom16 satfin size spdeg polviews
rincom16 res16 childs wrkstat sex region /COMPRESSED.
| null | https://raw.githubusercontent.com/PacktPublishing/Data-Analysis-with-IBM-SPSS-Statistics/1edd4c1dce8dc0a3ebce093bbac37c94ebbb63e9/Chapter03/Create%20GSS2016%20small28%2040317.sps | scheme | * Encoding: UTF-8.
* create GSS2016small with 28 fields.
* Modified 4/3/17 to use INCOM06 rather than INCOME - better set of values.
SAVE OUTFILE='C:\GSS Data\GSS2016sm28 40317.sav'
/keep = happy marital hapmar age
VOTE12 PRES12 educ speduc natpark natroad NATENRGY
cappun natmass natchld natsci
partyid degree incom16 satfin size spdeg polviews
rincom16 res16 childs wrkstat sex region /COMPRESSED.
| |
aecf90a2b12e2cbc419e10028e441d85dc011b346ffd9c0fb824a44426d0ae38 | Martoon-00/toy-compiler | Parsable.hs | # OPTIONS_GHC -fno - warn - orphans #
module Toy.Base.Parsable
( OutputValues (..)
) where
import Control.Applicative (many, (<|>))
import Text.Megaparsec (char, eof, label, space, spaceChar)
import Text.Megaparsec.Lexer (integer, signed)
import Universum
import Toy.Base.Data (Value)
import Toy.Util (Parsable (..))
instance Parsable Value where
parserName _ = "Value"
mkParser = label "Value" $ fmap fromIntegral $ space *> signed pass integer
instance Parsable [Value] where
parserName _ = "Values list"
mkParser = many (mkParser <* space) <* eof
newtype OutputValues = OutputValues
{ getOutputValues :: [Value]
} deriving (Show, Eq)
instance Parsable OutputValues where
parserName _ = "Output values"
mkParser = do
let spaces = many (void spaceChar <|> char '>' $> ())
OutputValues <$> (spaces *> many (mkParser <* spaces)) <* eof
| null | https://raw.githubusercontent.com/Martoon-00/toy-compiler/a325d56c367bbb673608d283197fcd51cf5960fa/src/Toy/Base/Parsable.hs | haskell | # OPTIONS_GHC -fno - warn - orphans #
module Toy.Base.Parsable
( OutputValues (..)
) where
import Control.Applicative (many, (<|>))
import Text.Megaparsec (char, eof, label, space, spaceChar)
import Text.Megaparsec.Lexer (integer, signed)
import Universum
import Toy.Base.Data (Value)
import Toy.Util (Parsable (..))
instance Parsable Value where
parserName _ = "Value"
mkParser = label "Value" $ fmap fromIntegral $ space *> signed pass integer
instance Parsable [Value] where
parserName _ = "Values list"
mkParser = many (mkParser <* space) <* eof
newtype OutputValues = OutputValues
{ getOutputValues :: [Value]
} deriving (Show, Eq)
instance Parsable OutputValues where
parserName _ = "Output values"
mkParser = do
let spaces = many (void spaceChar <|> char '>' $> ())
OutputValues <$> (spaces *> many (mkParser <* spaces)) <* eof
| |
7b6a8d3cfa333cc22ff5e83fcd2c21226db2459602dd9e31aedd79cf9a133c34 | haskell/haskell-language-server | DestructInt.expected.hs | import Data.Int
data Test = Test Int32
test :: Test -> Int32
test (Test in') = _w0
| null | https://raw.githubusercontent.com/haskell/haskell-language-server/f3ad27ba1634871b2240b8cd7de9f31b91a2e502/plugins/hls-tactics-plugin/new/test/golden/DestructInt.expected.hs | haskell | import Data.Int
data Test = Test Int32
test :: Test -> Int32
test (Test in') = _w0
| |
dd7138685ae76888da165894bff48ae56f805f4ffb272efdd5395379fc778a71 | graninas/Hydra | Class.hs | {-# LANGUAGE GADTs #-}
# LANGUAGE TemplateHaskell #
module Hydra.Core.Random.Class where
import Hydra.Prelude
class Monad m => Random m where
getRandomInt :: (Int, Int) -> m Int
| null | https://raw.githubusercontent.com/graninas/Hydra/60d591b1300528f5ffd93efa205012eebdd0286c/lib/hydra-base/src/Hydra/Core/Random/Class.hs | haskell | # LANGUAGE GADTs # | # LANGUAGE TemplateHaskell #
module Hydra.Core.Random.Class where
import Hydra.Prelude
class Monad m => Random m where
getRandomInt :: (Int, Int) -> m Int
|
55293155c17c1ee6ba4e18c8e1a90d1f38afcb8e53bf3d8beeb23d570361c1d6 | kitnil/dotfiles | guixsd.scm | (use-modules (gnu home)
(gnu home services)
( gnu home services files )
(gnu home services mcron)
(gnu home services shells)
(gnu home services ssh)
(gnu packages admin)
(gnu packages bash)
(gnu packages guile)
(gnu packages pulseaudio)
(gnu packages virtualization)
(gnu packages terminals)
(gnu packages xdisorg)
(gnu packages xorg)
(gnu services)
(gnu services configuration)
(guix gexp)
(guix modules)
(guix profiles)
(ice-9 rdelim)
(json)
(gnu packages base)
(gnu packages haskell-apps)
(gnu packages wm)
(home config)
(home config openssh)
(home services ansible)
(home services cisco)
(home services desktop)
(home services gdb)
(home services emacs)
(home services juniper)
(home services h3c)
(home services mail)
(home services monitoring)
(home services nix)
(home services package-management)
(home services shell)
(home services version-control)
(home services terminals)
(home services tmux)
(home services linux)
(home services haskell-apps)
(home services gtk)
(home services stumpwm)
(home services rust-apps)
(home services lisp)
(home services python)
(home services nano)
(home services dns)
(home services web)
(home services gnupg)
(home services groovy)
(home services guile)
(home services kodi)
(home services databases)
(home services mime)
(home services video)
(home services networking)
(home services kubernetes)
(home services majordomo billing2)
(gnu packages mail)
(gnu packages dhall)
(guile pass)
;; (dwl-guile home-service)
;; (dwl-guile configuration)
)
(define %home
(and=> (getenv "HOME")
(lambda (home)
home)))
(add-to-load-path (string-append %home "/.local/bin"))
(use-modules (mjru-github-projects))
(define .bash_profile
(string-append %home "/.local/share/chezmoi/dot_bash_profile"))
(define .bashrc
(string-append %home "/.local/share/chezmoi/dot_bashrc"))
(define xmodmap-script
(program-file
"xmodmap"
#~(begin
(use-modules (srfi srfi-1)
(ice-9 popen)
(ice-9 rdelim))
(define %home
(and=> (getenv "HOME")
(lambda (home)
home)))
(define xmodmap
#$(file-append xmodmap "/bin/xmodmap"))
(define count (make-parameter 0))
(let loop ()
(let* ((port (open-pipe* OPEN_READ xmodmap "-pke"))
(output (read-string port)))
(close-pipe port)
(if (or (< 2 (count))
(any (lambda (str)
(string= str "keycode 134 = Control_L NoSymbol Control_L"))
(string-split (string-trim-right output #\newline) #\newline)))
#t
(begin
(count (1+ (count)))
(system* xmodmap (string-append %home "/.Xmodmap"))
(sleep 3)
(loop))))))))
(define* (majordomo-mbsync-goimapnotify-services name #:key (max-messages 0))
(define (pass-private-or-public name)
(if (file-exists? (string-append %home "/.password-store/majordomo/private/router.majordomo.ru/" name "@majordomo.ru.gpg"))
(string-append "majordomo/private/router.majordomo.ru/"
name "@majordomo.ru")
(string-append "majordomo/public/router.majordomo.ru/"
name "@majordomo.ru")))
(define majordomo-mbsync-imap-account-configuration
(mbsync-imap-account-configuration
(host "router.majordomo.ru")
(auth-mechs '("LOGIN"))
(ssl-type "None")
(certificate-file "/etc/ssl/certs/ca-certificates.crt")
(pipeline-depth 50)))
(define majordomo-mbsync-imap-store-configuration
(mbsync-imap-store-configuration
(imap-store "majordomo-remote")
(account "majordomo")))
(define majordomo-mbsync-maildir-store-configuration
(mbsync-maildir-store-configuration
(path "~/Maildir/")
(sub-folders "Verbatim")))
(define majordomo-mbsync-channel-configuration
(mbsync-channel-configuration
(patterns '("INBOX"))
(sync '("Pull"))
(max-messages max-messages)
(expunge "near")
(expire-unread "yes")))
(list
(simple-service (symbol-append 'home-mbsync-majordomo-
(string->symbol name))
home-mbsync-service-type
(mbsync-configuration
(imap-accounts
(list
(mbsync-imap-account-configuration
(inherit majordomo-mbsync-imap-account-configuration)
(imap-account (string-append "majordomo-" name))
(user (string-append name "@majordomo.ru"))
(ssl-type "IMAPS")
(pass-cmd
(string-join
(list "pass" "show"
(pass-private-or-public name)))))))
(imap-stores
(list
(mbsync-imap-store-configuration
(imap-store (string-append "majordomo-" name "-remote"))
(account (string-append "majordomo-" name)))))
(maildir-stores
(list
(mbsync-maildir-store-configuration
(inherit majordomo-mbsync-maildir-store-configuration)
(maildir-store (string-append "majordomo-" name "-local"))
(inbox (string-append "~/Maildir/majordomo-" name)))))
(channels
(list
(mbsync-channel-configuration
(inherit majordomo-mbsync-channel-configuration)
(channel (string-append "majordomo-" name))
(far (string-append ":majordomo-" name "-remote:"))
(near (string-append ":majordomo-" name "-local:")))))))
(service home-goimapnotify-service-type
(goimapnotify-configuration
(config-file
(computed-file
(string-append "isync-majordomo-" name "-config")
(with-extensions (list guile-json-4)
(with-imported-modules (source-module-closure '((json builder)))
#~(begin
(use-modules (json builder)
(ice-9 format))
(define isync
#$(file-append isync "/bin/mbsync"))
(define timeout
#$(file-append coreutils "/bin/timeout"))
(define password
#$(pass "show" (pass-private-or-public name)))
(define username #$name)
(with-output-to-file #$output
(lambda ()
(scm->json
`(("boxes" . #("INBOX"))
("onNewMail" . ,(string-join (list timeout (number->string 60) isync
(string-append "majordomo-" username))))
("xoauth2" . #f)
("password" . ,password)
("username" . ,(string-append username "@majordomo.ru"))
("tlsOptions" ("rejectUnauthorized" . #t))
("tls" . #t)
("port" . 993)
("host" . "imap.majordomo.ru"))))))))))))))
(define xsession-config-file
(let* ((stumpwp-load-file
(plain-file
"stumpwp-load-file"
(with-output-to-string
(lambda ()
(display '(require :asdf))
(newline)
(display '(require :stumpwm))
(newline)
(display '(stumpwm:stumpwm))
(newline)))))
(xsession-file
(program-file
"xsession"
#~(begin
(use-modules (srfi srfi-1)
(ice-9 popen)
(ice-9 rdelim)
(ice-9 format))
(define %display
(and=> (getenv "DISPLAY")
(lambda (display)
display)))
(define %home
(and=> (getenv "HOME")
(lambda (home)
home)))
(display "Set background\n")
(system* #$(file-append xsetroot "/bin/xsetroot")
"-solid" "black")
(display "Set cursor theme\n")
(system* #$(file-append xsetroot "/bin/xsetroot")
"-cursor_name" "left_ptr")
(display "Disable speaker\n")
(system* #$(file-append xset "/bin/xset") "-b")
(display "Configure keymap\n")
(system* #$xmodmap-script)
(system* #$(file-append setxkbmap "/bin/setxkbmap")
"-layout" "us,ru" "-option" "grp:win_space_toggle")
;; Prepare environment for VNC sessions
(display "Start window manager\n")
(if (string= %display ":0.0")
(execl "/run/current-system/profile/bin/sbcl" "sbcl" "--load" #$stumpwp-load-file)
(begin
(unsetenv "SESSION_MANAGER")
(unsetenv "DBUS_SESSION_BUS_ADDRESS")
(system* #$(file-append xhost "/bin/xhost") "+local:")
(let* ((pw (getpw (getuid)))
(shell (passwd:shell pw)))
The ' --login ' option is supported at least by Bash and .
(execl shell "sbcl" "--login" "-c"
(format #f ". /home/oleg/.bash_profile; /run/current-system/profile/bin/sbcl --load ~a"
#$stumpwp-load-file)))))))))
#~(begin
(let ((file #$(string-append %home "/.xsession")))
(copy-file #$xsession-file file)
(chmod file #o700)))))
(home-environment
(services
(append
(majordomo-mbsync-goimapnotify-services "pyhalov")
(majordomo-mbsync-goimapnotify-services "sidorov")
(majordomo-mbsync-goimapnotify-services "alertmanager"
#:max-messages 1000)
(majordomo-mbsync-goimapnotify-services "git-commits")
(majordomo-mbsync-goimapnotify-services "grafana")
(majordomo-mbsync-goimapnotify-services "healthchecks")
(majordomo-mbsync-goimapnotify-services "issues")
(majordomo-mbsync-goimapnotify-services "jenkins")
(majordomo-mbsync-goimapnotify-services "prometheus")
(majordomo-mbsync-goimapnotify-services "security")
(majordomo-mbsync-goimapnotify-services "smartmontools")
(majordomo-mbsync-goimapnotify-services "tracker")
(majordomo-mbsync-goimapnotify-services "ihc-zabbix")
(list
(simple-service 'home-mbsync-wugi-oleg
home-mbsync-service-type
(mbsync-configuration
(imap-accounts
(list
(mbsync-imap-account-configuration
(imap-account "wugi-oleg")
(host "imap.wugi.info")
(user "")
(pass-cmd "gpg -q --for-your-eyes-only --no-tty -d ~/.password-store/localhost/imap/oleg.gpg")
(auth-mechs '("LOGIN"))
(ssl-type "IMAPS")
(certificate-file "/etc/ssl/certs/ca-certificates.crt")
(pipeline-depth 50))))
(imap-stores
(list
(mbsync-imap-store-configuration
(imap-store "wugi-oleg-remote")
(account "wugi-oleg"))))
(maildir-stores
(list
(mbsync-maildir-store-configuration
(maildir-store "wugi-oleg-local")
(path "~/Maildir/")
(inbox "~/Maildir/wugi.info")
(sub-folders "Verbatim"))))
(channels
(list
(mbsync-channel-configuration
(channel "wugi-oleg")
(far ":wugi-oleg-remote:")
(near ":wugi-oleg-local:")
(patterns '("INBOX"))
(sync '("Pull")))))))
(simple-service 'home-mbsync-gmail-wigust
home-mbsync-service-type
(mbsync-configuration
(imap-accounts
(list
(mbsync-imap-account-configuration
(imap-account "gmail")
(host "imap.gmail.com")
(user "")
(pass-cmd "gpg -q --for-your-eyes-only --no-tty -d ~/.password-store/myaccount.google.com/apppasswords/go.wigust.gpg")
(auth-mechs '("LOGIN"))
(ssl-type "IMAPS")
(certificate-file "/etc/ssl/certs/ca-certificates.crt")
(pipeline-depth 50))))
(imap-stores
(list
(mbsync-imap-store-configuration
(imap-store "gmail-remote")
(account "gmail"))))
(maildir-stores
(list
(mbsync-maildir-store-configuration
(maildir-store "gmail-local")
(path "~/Maildir/")
(inbox "~/Maildir/INBOX")
(sub-folders "Verbatim"))))
(channels
(list
(mbsync-channel-configuration
(channel "gmail")
(far ":gmail-remote:")
(near ":gmail-local:")
(patterns '("INBOX"))
(sync '("Pull"))
(max-messages 2000)
(expunge "near"))))))
(service home-goimapnotify-service-type
(goimapnotify-configuration
(config-file
(computed-file
"isync-gmail-config"
(with-extensions (list guile-json-4)
(with-imported-modules (source-module-closure '((json builder)))
#~(begin
(use-modules (json builder)
(ice-9 format))
(define timeout
#$(file-append coreutils "/bin/timeout"))
(define isync
#$(file-append isync "/bin/mbsync"))
(define password
#$(pass "show" "myaccount.google.com/apppasswords/go.wigust"))
(with-output-to-file #$output
(lambda ()
(scm->json
`(("boxes" . #("INBOX"))
("onNewMail" . ,(string-join (list timeout (number->string 60) isync "gmail")))
("xoauth2" . #f)
("password" . ,password)
("username" . "")
("tlsOptions" ("rejectUnauthorized" . #t))
("tls" . #t)
("port" . 993)
("host" . "imap.gmail.com"))
#:pretty #t))))))))))
(service home-goimapnotify-service-type
(goimapnotify-configuration
(config-file
(computed-file
"isync-wugi-config"
(with-extensions (list guile-json-4)
(with-imported-modules (source-module-closure '((json builder)))
#~(begin
(use-modules (json builder)
(ice-9 format))
(define timeout
#$(file-append coreutils "/bin/timeout"))
(define isync
#$(file-append isync "/bin/mbsync"))
(define password
#$(pass "show" "localhost/imap/oleg"))
(with-output-to-file #$output
(lambda ()
(scm->json
`(("boxes" . #("INBOX"))
("onNewMail" . ,(string-join (list timeout (number->string 60) isync "wugi-oleg")))
("xoauth2" . #f)
("password" . ,password)
("username" . "")
("tlsOptions" ("rejectUnauthorized" . #t))
("tls" . #t)
("port" . 993)
("host" . "imap.wugi.info"))
#:pretty #t))))))))))
(simple-service 'amtool-config
home-files-service-type
(list `(".config/amtool/config.yml"
,(computed-file
"amtool-config.json"
(with-extensions (list guile-json-4)
(with-imported-modules (source-module-closure '((json builder)))
#~(begin
(use-modules (json builder))
(with-output-to-file #$output
(lambda ()
(scm->json
'(("output" . "extended")
;; ("receiver" . "team-X-pager")
;; ("comment_required" . #t)
;; ("author" . "")
("alertmanager.url" . ":9093"))
#:pretty #t))))))))))
home-chromium-service
home-bin-service
home-networking-service
(simple-service 'looking-glass-wrapper
home-files-service-type
(list `(".local/bin/looking-glass-client-wrapper"
,(local-file (string-append %project-directory "/dot_local/bin/executable_looking-glass-client-wrapper")
#:recursive? #t))))
(simple-service 'idea-ultimate-wrapper
home-files-service-type
(list `(".local/bin/idea-ultimate"
,(computed-file
"idea-ultimate-wrapper"
#~(begin
(with-output-to-file #$output
(lambda ()
(format #t "\
#!/bin/sh
PYTHONPATH='' exec -a \"$0\" ~a/bin/idea-ultimate \"$@\"\n"
#$(string-append %home "/.nix-profile"))))
(chmod #$output #o555))))))
;; home-shellcheck-service
(service stumpwm-service-type
(let ((config-files
'("utils.lisp"
"keys.lisp"
"nav.lisp"
"theme.lisp"
"xorg.lisp"
"term.lisp"
"text-editors.lisp"
"repl.lisp"
"notify.lisp"
"hardware.lisp"
"admin.lisp"
"clipboard.lisp"
"screenshoot.lisp"
"password.lisp"
"trans.lisp"
"backup.lisp"
"documentation.lisp"
"emacs.lisp"
"chat.lisp"
"mail.lisp"
"docker.lisp"
"vnc.lisp"
"rofi.lisp"
"audio.lisp"
"mpv.lisp"
"streamlink.lisp"
"youtube-dl.lisp"
"android.lisp"
"kodi.lisp"
"web.lisp"
"time.lisp"
"mjru.lisp"
"virtualization.lisp"
"bittorrent.lisp"
"kubernetes.lisp"
"disk.lisp"
"rest.lisp"
"cpu.lisp"
"mem.lisp"
"imap.lisp"
"covid19.lisp"
"gpg.lisp"
"vpn.lisp"
"mode-line.lisp"
"display-0.lisp"
"display.lisp"
"autostart.lisp"
"swank.lisp"
"gaps.lisp")))
(stumpwm-configuration
(init-config
`((in-package :stumpwm)
(require "asdf")
;; -in-nix-installed-packages-on-a-non-nixos-system/5871/9
(defvar *fontconfig-file*
"FONTCONFIG_FILE=/run/current-system/profile/etc/fonts/fonts.conf")
(redirect-all-output
(concat
(getenv "HOME") "/.local/var/log/stumpwm/" (getenv "DISPLAY") ".log"))
( defcommand quassel ( ) ( )
;; (run-shell-command (join (list *fontconfig-file* "/home/oleg/.nix-profile/bin/quassel"))))
Tuesday January 3 2005 23:05:25
(setq *time-format-string-default* "%A %B %e %Y %k:%M:%S")
(setf *startup-message* nil)
(setf *message-window-gravity* :center)
(setf *input-window-gravity* :center)
,@(map (lambda (config-file)
`(load ,(string-append "/home/oleg/.stumpwm.d/" config-file)))
config-files)
( restore - from - file , ( local - file " /home / oleg/.local / share / chezmoi / dot_stumpwm.d / group-1.lisp " ) )
))
(config-files config-files))))
home-bash-service
home-mime-service
home-bind-utils-service
home-direnv-service
home-gdb-service
home-ghci-service
home-git-service
home-gita-service
home-emacs-state-service
home-emacs-service
home-groovy-service
home-gnupg-service
home-inputrc-service
home-guile-service
(simple-service 'keynav-config
home-files-service-type
(list `(".keynavrc" ,(local-file (string-append %project-directory "/dot_keynavrc")))))
home-kodi-service
home-mailcap-service
home-mongo-service
home-postgresql-service
home-mycli-service
home-nano-service
home-python-service
home-sbcl-service
home-screen-service
home-tmux-service
tmuxifier-service
home-top-service
(simple-service 'xmodmap-config
home-files-service-type
(list `(".Xmodmap" ,(local-file (string-append %project-directory "/dot_Xmodmap")))))
(simple-service 'xresources-config
home-files-service-type
(list `(".Xresources" ,(local-file (string-append %project-directory "/dot_Xresources")))))
home-qterminal-service
(simple-service 'zathura-config
home-files-service-type
(list `(".config/zathura/zathurarc" ,(local-file (string-append %project-directory "/dot_config/zathura/zathurarc")))))
home-ripgrep-service
home-gtk-service
home-gtkrc-service
home-greenclip-service
home-alacritty-service
home-kitty-service
(simple-service 'feh-config
home-files-service-type
(list `(".config/feh/buttons" ,(local-file (string-append %project-directory "/dot_config/feh/buttons")))))
(simple-service 'sway-config
home-files-service-type
(list `(".config/sway/config" ,(local-file (string-append %project-directory "/dot_config/sway/config")))))
(simple-service 'polybar-config
home-files-service-type
(list `(".config/polybar/config" ,(local-file (string-append %project-directory "/dot_config/polybar/config")))))
home-youtube-dl-service
(simple-service 'cava-config
home-files-service-type
(list `(".config/cava/config" ,(local-file (string-append %project-directory "/dot_config/cava/config")))))
(simple-service 'termonad-config
home-files-service-type
(list `(".config/termonad/termonad.hs" ,(local-file (string-append %project-directory "/dot_config/termonad/termonad.hs")))))
home-nix-service
home-mpv-service
(simple-service 'cagebreak-config
home-files-service-type
(list `(".config/cagebreak/config" ,(local-file (string-append %project-directory "/dot_config/cagebreak/config")))))
(simple-service 'vis-config
home-files-service-type
(list `(".config/vis/config" ,(local-file (string-append %project-directory "/dot_config/vis/config")))))
(simple-service 'dunst-config
home-files-service-type
(list `(".config/dunst/dunstrc" ,(local-file (string-append %project-directory "/dot_config/dunst/dunstrc")))))
;; TODO: Add those
;; dot_config/guile/mariadb.scm
;; dot_config/mjru/encrypted_config.scm
;; dot_config/mjru/encrypted_firefox.scm
;; Symlinking to store breaks espanso, so use files instead.
(simple-service 'espanso-config
home-activation-service-type
#~(invoke
#$(program-file
"espanso-config"
(with-imported-modules '((ice-9 match))
#~(begin
(use-modules (ice-9 match))
(for-each (match-lambda ((destination source)
(let ((destination-full-path (string-append #$%home "/." destination)))
(when (file-exists? destination-full-path)
(chmod destination-full-path #o644))
(copy-file source destination-full-path))))
(list `("config/espanso/default.yml" ,#$(local-file (string-append %project-directory "/dot_config/espanso/default.yml")))
;; TODO: Add `("config/espanso/user/home.yml.tmpl" ,(local-file (string-append %project-directory "/dot_config/espanso/user/home.yml.tmpl")))
`("config/espanso/user/systemd.yml" ,#$(local-file (string-append %project-directory "/dot_config/espanso/user/systemd.yml")))
`("config/espanso/user/juniper.yml" ,#$(local-file (string-append %project-directory "/dot_config/espanso/user/juniper.yml")))
`("config/espanso/user/mysql.yml" ,#$(local-file (string-append %project-directory "/dot_config/espanso/user/mysql.yml")))
`("config/espanso/user/nix.yml" ,#$(local-file (string-append %project-directory "/dot_config/espanso/user/nix.yml")))
`("config/espanso/user/mjru.yml" ,#$(local-file (string-append %project-directory "/dot_config/espanso/user/mjru.yml"))))))))))
(simple-service 'sshrc-config
home-files-service-type
(list `(".sshrc" ,(local-file (string-append %project-directory "/dot_sshrc")))
`(".sshrc.d/.bashrc" ,(local-file (string-append %project-directory "/dot_sshrc.d/dot_bashrc")))
`(".sshrc.d/.tmux.conf" ,(local-file (string-append %project-directory "/dot_sshrc.d/dot_tmux.conf")))))
(simple-service 'vnc-config
home-files-service-type
(list `(".vnc/default.tigervnc" ,(local-file (string-append %project-directory "/private_dot_vnc/default.tigervnc")))
`(".vnc/xstartup" ,(local-file (string-append %project-directory "/private_dot_vnc/executable_xstartup") #:recursive? #t))
`(".vnc/xstartup-firefox" ,(local-file (string-append %project-directory "/private_dot_vnc/executable_xstartup-firefox") #:recursive? #t))
`(".vnc/xstartup-quassel" ,(local-file (string-append %project-directory "/private_dot_vnc/executable_xstartup-quassel") #:recursive? #t))
`(".vnc/xstartup-ratpoison" ,(local-file (string-append %project-directory "/private_dot_vnc/executable_xstartup-ratpoison") #:recursive? #t))
`(".vnc/xstartup-stumpwm" ,(local-file (string-append %project-directory "/private_dot_vnc/executable_xstartup-stumpwm") #:recursive? #t))
`(".vnc/xstartup-twm" ,(local-file (string-append %project-directory "/private_dot_vnc/executable_xstartup-twm") #:recursive? #t))))
(simple-service 'xsession-config
home-activation-service-type
xsession-config-file)
home-parallel-service
(simple-service 'msmtp-config
home-activation-service-type
#~(begin
(define %home
(and=> (getenv "HOME")
(lambda (home)
home)))
(add-to-load-path (string-append %home "/.local/share/chezmoi/dotfiles"))
(use-modules (ice-9 format)
(guile pass))
(define msmtp-config
(string-append %home "/.msmtprc"))
(call-with-output-file msmtp-config
(lambda (port)
(format port "\
# Set default values for all following accounts.
defaults
auth on
tls on
tls_trust_file /etc/ssl/certs/ca-certificates.crt
logfile ~a/.msmtp.log
# Gmail
account gmail
host smtp.gmail.com
port 587
from
user go.wigust
password ~a
# Majordomo
account majordomo-pyhalov
host smtp.majordomo.ru
port 587
from
user
password ~a
# Set a default account
account default : gmail
"
%home
(pass "myaccount.google.com/apppasswords/go.wigust")
(pass "majordomo/private/newmail.majordomo.ru/"))))
(chmod msmtp-config #o600)))
(simple-service 'netrc-config
home-activation-service-type
(let ((file
(scheme-file
"netrc.scm"
#~(begin
(let ((%home
(and=> (getenv "HOME")
(lambda (home)
home))))
(add-to-load-path (string-append %home "/.local/share/chezmoi/dotfiles"))
(use-modules (ice-9 format)
(ice-9 match)
(guile pass))
(call-with-output-file (string-append %home "/.netrc")
(lambda (port)
(for-each
(match-lambda
((net (machine m)
(login l)
(password p))
(format port "~%machine ~a~%" m)
(format port "login ~a~%" l)
(format port "password ~a~%" (pass p))))
'((net
(machine "api.github.com")
(login "wigust")
(password "github/tokens/api/wigust"))
(net
(machine "uploads.github.com")
(login "wigust")
(password "github/tokens/api/wigust"))
(net
(machine "imap.yandex.ru")
(login "houdinihar")
(password "email/yandex.ru/houdinihar"))
(net
(machine "imap.rambler.ru")
(login "houdinihar")
(password "email/rambler/houdinihar"))
(net
(machine "imap.majordomo.ru")
(login "pyhalov")
(password "majordomo/private/newmail.majordomo.ru/"))
(net
(machine "localhost")
(login "oleg")
(password "localhost/imap/oleg"))
(net
(machine "bareos.intr")
(login "netcfg")
(password "majordomo/public/172.16.103.111/netcfg"))
(net
(machine "pop3.hoster24.ru")
(login "pop3")
(password "majordomo/public/hoster24.ru/pop3"))
(net
(machine "172.16.103.111")
(login "netcfg")
(password "majordomo/public/172.16.103.111/netcfg")))))))))))
#~(begin (primitive-load #$file))))
(service home-mcron-service-type)
(service nix-delete-generations-service-type
(nix-delete-generations-configuration
(schedule '(next-hour '(21)))))
(service guix-delete-generations-service-type
(guix-delete-generations-configuration
(schedule '(next-hour '(21)))
(period "1m")))
(service ansible-playbook-service-type)
(service juniper-service-type)
(service h3c-service-type)
(service cisco-service-type)
(service kubernetes-service-type)
(service billing2-service-type)
(simple-service 'ansible-config
home-files-service-type
(append (list `(,".ansible.cfg" ,(local-file (string-append %project-directory "/dot_ansible.cfg"))))
(map (lambda (file-name)
`(,(string-append ".ansible/plugins/modules/" file-name)
,(local-file (string-append %project-directory
"/dot_ansible/plugins/modules/"
file-name))))
'("guix_package.py"
"guix_pull.py"))))
(simple-service 'ansible-hosts-config
home-activation-service-type
(with-extensions (list guile-json-4)
(with-imported-modules (source-module-closure '((json builder)))
#~(begin
(add-to-load-path (string-append #$%home "/.local/share/chezmoi/dotfiles"))
(use-modules (ice-9 rdelim)
(ice-9 popen)
(guile pass)
(json builder)
(ice-9 match)
(srfi srfi-41))
(define password-router
(pass "majordomo/public/router4/root"))
(define majordomo-office
( " Admin-1 " " 172.16.107.21 " " 18 : c0:4d : f9 : c0 : b6 " " Home segment " " Wired " " 100 Mbit / s " " Port 1 " )
( " Admin-2 " " 172.16.107.22 " " 18 : c0:4d : f9 : c1:9a " " Offline " )
( " Admin-3 " " 172.16.107.23 " " 18 : c0:4d : f9 : c0 : bb " " Home segment " " Wired " " 100 Mbit / s " " Port 1 " )
( " dev-1 " " 172.16.107.11 " " 18 : c0:4d : f9 : c1:99 " " Home segment " " Wired " " 100 Mbit / s " " Port 1 " )
( " dev-2 " " 172.16.107.12 " " 18 : c0:4d : f9 : c1:9b " " Home segment " " Wired " " 100 Mbit / s " " Port 1 " )
( " Info-1 " " 172.16.107.31 " " 18 : c0:4d : f9 : " " Home segment " " Wired " " 100 Mbit / s " " Port 1 " )
( " Info-2 " " 172.16.107.32 " " 18 : c0:4d : f9 : c0 : fe " " Home segment " " Wired " " 100 Mbit / s " " Port 1 " )
( " iPhone - Gennadiy via Keenetic Air ( KN-1611 ) " " 172.16.107.143 " " ce:97:72 : a9:1f : d6 " " Home segment " " 5 GHz Wi - Fi " " 130 Mbit / s WPA2 " " ac / k / v 2x2 20 MHz " )
( " SPA122 " " 172.16.107.8 " " 88:75:56:07:73:92 " " Home segment " " Wired " " 0 Mbit / s " " Port 1 " )
("sup1" "172.16.107.41" "18:c0:4d:f9:c0:b8" "Home segment" "Wired" "100 Mbit/s" "Port 1")
("sup2" "172.16.107.42" "18:c0:4d:f9:c0:bc" "Home segment" "Wired" "100 Mbit/s" "Port 1")
("sup3" "172.16.107.43" "18:c0:4d:f9:c0:f9" "Home segment" "Wired" "100 Mbit/s" "Port 1")
("sup4" "172.16.107.44" "18:c0:4d:f9:c0:83" "Home segment" "Wired" "100 Mbit/s" "Port 1")))
(call-with-output-file #$(string-append %home "/.ansible-hosts")
(lambda (port)
(scm->json
`(("vps"
("vars"
("ansible_ssh_user" . "opc")
("ansible_ssh_private_key_file"
.
"~/.ssh/id_rsa_oracle"))
("hosts" ("oracle" . null)))
("vm"
("vars"
("ansible_ssh_user" . "root")
("ansible_python_interpreter"
.
"/usr/bin/python3"))
("children"
("majordomo_office"
("hosts"
,@(map ((@@ (ice-9 match) match-lambda)
((name ip mac etc ...)
(cons ip 'null)))
majordomo-office))
("vars"
("ansible_ssh_user" . "root")
("ansible_python_interpreter" . "/run/current-system/sw/bin/python3")))
("mjru"
("hosts"
("78.108.87.99" . null)
("78.108.87.50" . null)
("78.108.86.20" . null)
("78.108.86.111" . null)
("78.108.82.130" . null)
("178.250.247.88" . null)
("178.250.247.60" . null)
("178.250.246.69" . null)
("178.250.246.123" . null)
("178.250.245.80" . null)
("178.250.244.239" . null)))
("ihc"
("vars"
("ansible_ssh_user" . "pyhalov")
("ansible_ssh_private_key_file" . "~/.ssh/id_rsa_ihc_pyhalov"))
("hosts"
("kvm-nvme1.majordomo.ru" . null)
("kvm-nvme101.majordomo.ru" . null)
("kvm-nvme102.majordomo.ru" . null)
("kvm-nvme201.majordomo.ru" . null)
("kvm-nvme202.majordomo.ru" . null)
("kvm-nvme203.majordomo.ru" . null)))
("kubernetes"
("hosts"
,@(map (lambda (number)
`(,(string-append "kube" (number->string number) ".intr") . null))
(stream->list (stream-range 1 9))))
("vars"
("ansible_ssh_user" . "root")
("ansible_python_interpreter" . "/run/current-system/sw/bin/python3")))
("glpi" ("hosts" ("178.250.244.239" . null)))
("docker"
("hosts"
("78.108.87.99" . null)
("78.108.86.20" . null)
("178.250.246.123" . null))))
)
("majordomo"
("hosts"
("zabbix.intr" . null)
("ci.intr" . null)
("bareos.intr" . null)
("archive.intr" . null)
("backup.intr" . null))
("children"
("web"
("hosts"
("web37.intr" . null)
("web36.intr" . null)
("web35.intr" . null)
("web34.intr" . null)
("web33.intr" . null)
("web32.intr" . null)
("web31.intr" . null)
("web30.intr" . null)
("web29.intr" . null)
("web28.intr" . null)
("web27.intr" . null)
("web26.intr" . null)
("web25.intr" . null)
;; ("web24.intr" . null)
("web23.intr" . null)
("web22.intr" . null)
("web21.intr" . null)
("web20.intr" . null)
("web19.intr" . null)
("web18.intr" . null)
("web17.intr" . null)
("web16.intr" . null)
("web15.intr" . null)))
("deprecated_web"
("hosts"
#$@%ansible-majordomo-deprecated-webs))
("vpn"
("hosts"
("router4.intr" . null)
("ns1-dh.intr" . null)
("galera-backup.intr" . null)))
("swarm"
("hosts"
("dh5-mr.intr" . null)
("dh4-mr.intr" . null)
("dh3-mr.intr" . null)
("dh2-mr.intr" . null)
("dh1-mr.intr" . null)))
("router"
("children"
("routers"
("vars" ("ansible_ssh_pass" . ,password-router))
("hosts" ("router4.intr" . null)))
("office"
("hosts"
("router2.intr" . null)
("router1.intr" . null)))
("freebsd"
("vars"
("ansible_python_interpreter"
.
"/usr/local/bin/python2"))
("hosts" ("router-miran1.intr" . null)))))
("redis"
("hosts"
("hms02-mr.intr" . null)
("hms01-mr.intr" . null)))
("ns"
("hosts"
("ns2-mr.intr" . null)
("ns2-dh.intr" . null)
("ns1-mr.intr" . null)
("ns1-dh.intr" . null)))
("nginx"
("hosts"
("nginx3.intr" . null)
("nginx2.intr" . null)
("nginx1.intr" . null)))
("mongo"
("hosts"
("hms03-mr.intr" . null)
("hms02-mr.intr" . null)
("hms01-mr.intr" . null)))
("miran"
("children"
("rack4"
("hosts"
("zabbix.intr" . null)
("web18.intr" . null)
("web15.intr" . null)
("staff.intr" . null)
("router-miran1.intr" . null)
("mail-checker2.intr" . null)
("kvm14.intr" . null)
("galera3.intr" . null)
("galera2.intr" . null)
("galera1.intr" . null)
("dh2.intr" . null)
("bareos.intr" . null)))
("rack3"
("hosts"
("web37.intr" . null)
("web34.intr" . null)
("web33.intr" . null)
("web32.intr" . null)
("web31.intr" . null)
("web30.intr" . null)
("web29.intr" . null)
("web28.intr" . null)
("web27.intr" . null)
("web26.intr" . null)
("web25.intr" . null)
;; ("web24.intr" . null)
("web23.intr" . null)
("web22.intr" . null)
("web20.intr" . null)
("web19.intr" . null)
("web17.intr" . null)
("web16.intr" . null)
("ns2-mr.intr" . null)
("kvm2.intr" . null)
("kvm15.intr" . null)
("jenkins.intr" . null)))
("rack2"
("hosts"
("webmail2.intr" . null)
("webmail1.intr" . null)
("web36.intr" . null)
("web35.intr" . null)
("web21.intr" . null)
("smtp-staff.intr" . null)
("ns1-mr.intr" . null)
("nginx2.intr" . null)
("nginx1.intr" . null)
("kvm37.intr" . null)
("hms02-mr.intr" . null)
("galera-backup.intr" . null)
("dh4.intr" . null)
("dh1.intr" . null)
("chef-server.intr" . null)
("buka2-new.intr" . null)
("archive.intr" . null)))
("rack1"
("hosts"
("pop5.intr" . null)
("mx1.intr" . null)
("hms01-mr.intr" . null)
("fluentd.intr" . null)
("dh3.intr" . null)))))
("mail"
("children"
("spam"
("hosts"
("mail-checker2.intr" . null)
("mail-checker1.intr" . null)))
("smtp"
("hosts"
("webmail2.intr" . null)
("webmail1.intr" . null)))
("pop"
("hosts"
("pop5.intr" . null)
("pop1.intr" . null)))
("mx"
("hosts"
("nginx2.intr" . null)
("nginx1.intr" . null)))))
("kvm"
("hosts"
("kvm9.intr" . null)
("kvm6.intr" . null)
("kvm5.intr" . null)
("kvm37.intr" . null)
("kvm35.intr" . null)
("kvm34.intr" . null)
("kvm33.intr" . null)
("kvm32.intr" . null)
("kvm31.intr" . null)
("kvm30.intr" . null)
("kvm29.intr" . null)
("kvm28.intr" . null)
("kvm27.intr" . null)
("kvm26.intr" . null)
("kvm25.intr" . null)
("kvm24.intr" . null)
("kvm23.intr" . null)
("kvm22.intr" . null)
("kvm21.intr" . null)
("kvm20.intr" . null)
("kvm2.intr" . null)
("kvm19.intr" . null)
("kvm17.intr" . null)
("kvm16.intr" . null)
("kvm15.intr" . null)
("kvm14.intr" . null)
("kvm13.intr" . null)
("kvm12.intr" . null)
("kvm10.intr" . null)
("kvm1.intr" . null)
("c-11122.intr" . null)))
("jenkins" ("hosts" ("jenkins.intr" . null)))
("galera"
("hosts"
("galera1.intr" . null)
("galera2.intr" . null)
("galera3.intr" . null)))
("elk"
("hosts"
("pop5.intr" . null)
("fluentd.intr" . null)
("chef-server.intr" . null)))
("datahouse"
("hosts"
("kvm1.intr" . null)
("kvm2.intr" . null)
("kvm5.intr" . null)
("kvm6.intr" . null)
("kvm7.intr" . null)
("kvm9.intr" . null)
("kvm10.intr" . null)
("kvm11.intr" . null)
("kvm12.intr" . null)
("kvm13.intr" . null)
("kvm14.intr" . null)
("kvm15.intr" . null)
("kvm16.intr" . null)
("kvm17.intr" . null)
("kvm18.intr" . null)
("kvm19.intr" . null)
("kvm20.intr" . null)
("kvm21.intr" . null)
("kvm22.intr" . null)
("kvm23.intr" . null)
("kvm24.intr" . null)
("kvm25.intr" . null)
("kvm26.intr" . null)
("kvm27.intr" . null)
("kvm28.intr" . null)
("kvm29.intr" . null)
("kvm34.intr" . null)
("kvm33.intr" . null)
("kvm32.intr" . null)
("kvm31.intr" . null)
("kvm30.intr" . null)
("kvm35.intr" . null)
("kvm37.intr" . null)))))
("guix"
("vars"
("ansible_python_interpreter"
.
"/home/oleg/.guix-profile/bin/python3"))
("children"
("local"
("vars" ("ansible_connection" . "local"))
("hosts" ("localhost" . null)))
( " guix_work " ( " hosts " ( " ws1.wugi.info " . null ) ) )
("guix_vm"
("hosts"
("vm1.wugi.info" . null))))))
port
#:pretty #t)))))))
(service home-openssh-service-type %home-openssh-configuration)
;; XXX: missing home-ssh-configuration
;; (service home-ssh-service-type
;; (home-ssh-configuration
;; (extra-config
;; (list
;; (ssh-host "savannah"
;; '((compression . #f)))))))
(service home-greenclip-service-type)
(service nix-build-service-type
(nix-build-configurations
(configurations
(append
(map
(lambda (hostname)
(nix-build-configuration
(name hostname)
(git-project git-project-nixos-pop)))
'("pop1" "pop5"))
(map
(lambda (hostname)
(nix-build-configuration
(name hostname)
(git-project git-project-nixos-monitoring)))
'("staff"))
(map
(lambda (hostname)
(nix-build-configuration
(name hostname)
(git-project git-project-nixos-ns)))
'("ns1-mr" "ns2-mr" "ns1-dh" "ns2-dh"))
(map
(lambda (hostname)
(nix-build-configuration
(name hostname)
(git-project git-project-nixos-web)))
'("web30"))
(map
(lambda (hostname)
(nix-build-configuration
(name hostname)
(git-project git-project-nixos-jenkins)))
'("jenkins"))))))
XXX : Make sure ~/.ssh / known_hosts provides ssh - rsa host key algorithm ,
;; so ssh-exporter works properly.
(service home-prometheus-ssh-exporter-service-type
(prometheus-ssh-exporter-configuration
(config-file
(computed-file
"ssh-exporter.json"
(with-extensions (list guile-json-4)
(with-imported-modules (source-module-closure '((json builder)))
#~(begin
(use-modules (json builder)
(ice-9 rdelim))
(define %home #$%home)
(with-output-to-file #$output
(lambda ()
(scm->json
`(("modules"
("default"
("user" . "oleg")
("timeout" . 5)
("private_key" . ,(string-append %home "/.ssh/id"))
("known_hosts" . ,(string-append %home "/.ssh/known_hosts"))
("host_key_algorithms" . #("ssh-ed25519"))
("command" . "uptime"))
("id_rsa"
("user" . "oleg")
("timeout" . 5)
("private_key" . ,(string-append %home "/.ssh/id_rsa"))
("known_hosts" . ,(string-append %home "/.ssh/known_hosts"))
("command" . "uptime"))
("majordomo-eng"
("user" . "eng")
("timeout" . 5)
("private_key" . ,(string-append %home "/.ssh/id_rsa_majordomo_eng"))
("known_hosts" . ,(string-append %home "/.ssh/known_hosts"))
("command" . "uptime"))
("majordomo-net"
("user" . "root")
("timeout" . 5)
("private_key" . ,(string-append %home "/.ssh/id_rsa_majordomo_eng"))
("known_hosts" . ,(string-append %home "/.ssh/known_hosts"))
("command" . "uptime"))))))))))))))
oleg@guixsd ~/.local / share / chezmoi$ command home -L dotfiles / guixsd / modules -L ~/src / engstrand - config - home - service - dwl - guile reconfigure dotfiles / guixsd / home.scm
;; (service home-dwl-guile-service-type
;; (home-dwl-guile-configuration
;; (package-transform? #f)
;; (auto-start? #f)))
;; (simple-service 'add-dwl-guile-keybinding home-dwl-guile-service-type
;; (modify-dwl-guile-config
;; (config =>
;; (dwl-config
;; (inherit config)
;; (keys
;; (append
( let ( ( ( file - append ponymix " /bin / ponymix " ) ) )
;; (list
;; (dwl-key
;; (key "s-w")
;; (action `(dwl:spawn "firefox")))
;; (dwl-key
;; (key "<XF86AudioMute>")
;; (action `(dwl:spawn ,ponymix "toggle")))
;; (dwl-key
;; (key "<XF86AudioLowerVolume>")
( action ` ( dwl : spawn , ponymix " decrease " " 5 " ) ) )
;; (dwl-key
;; (key "<XF86AudioRaiseVolume>")
( action ` ( dwl : spawn , ponymix " increase " " 5 " ) ) )
;; (dwl-key
;; (key "S-s-=")
;; (action `(dwl:spawn ,(file-append pavucontrol "/bin/pavucontrol"))))
;; (dwl-key
;; (key "s-e")
;; (action `(dwl:spawn "emacs")))))
;; (dwl-config-keys config)))
;; (terminal `(,(file-append alacritty "/bin/alacritty")))
;; (menu `(,(file-append bemenu "/bin/bemenu-run")))))))
(simple-service
'auto-shutdown-cron-jobs
home-mcron-service-type
(list
#~(job
'(next-hour)
#$(program-file
"schedule-power"
#~(begin
(system*
#$(local-file (string-append %project-directory "/dot_local/bin/executable_schedule-power")
#:recursive? #t)))))))))))
| null | https://raw.githubusercontent.com/kitnil/dotfiles/fd5bd0e01e429c887e9f3952e0f5320cc47fb017/dotfiles/guixsd/home/guixsd.scm | scheme | (dwl-guile home-service)
(dwl-guile configuration)
Prepare environment for VNC sessions
("receiver" . "team-X-pager")
("comment_required" . #t)
("author" . "")
home-shellcheck-service
-in-nix-installed-packages-on-a-non-nixos-system/5871/9
(run-shell-command (join (list *fontconfig-file* "/home/oleg/.nix-profile/bin/quassel"))))
TODO: Add those
dot_config/guile/mariadb.scm
dot_config/mjru/encrypted_config.scm
dot_config/mjru/encrypted_firefox.scm
Symlinking to store breaks espanso, so use files instead.
TODO: Add `("config/espanso/user/home.yml.tmpl" ,(local-file (string-append %project-directory "/dot_config/espanso/user/home.yml.tmpl")))
("web24.intr" . null)
("web24.intr" . null)
XXX: missing home-ssh-configuration
(service home-ssh-service-type
(home-ssh-configuration
(extra-config
(list
(ssh-host "savannah"
'((compression . #f)))))))
so ssh-exporter works properly.
(service home-dwl-guile-service-type
(home-dwl-guile-configuration
(package-transform? #f)
(auto-start? #f)))
(simple-service 'add-dwl-guile-keybinding home-dwl-guile-service-type
(modify-dwl-guile-config
(config =>
(dwl-config
(inherit config)
(keys
(append
(list
(dwl-key
(key "s-w")
(action `(dwl:spawn "firefox")))
(dwl-key
(key "<XF86AudioMute>")
(action `(dwl:spawn ,ponymix "toggle")))
(dwl-key
(key "<XF86AudioLowerVolume>")
(dwl-key
(key "<XF86AudioRaiseVolume>")
(dwl-key
(key "S-s-=")
(action `(dwl:spawn ,(file-append pavucontrol "/bin/pavucontrol"))))
(dwl-key
(key "s-e")
(action `(dwl:spawn "emacs")))))
(dwl-config-keys config)))
(terminal `(,(file-append alacritty "/bin/alacritty")))
(menu `(,(file-append bemenu "/bin/bemenu-run"))))))) | (use-modules (gnu home)
(gnu home services)
( gnu home services files )
(gnu home services mcron)
(gnu home services shells)
(gnu home services ssh)
(gnu packages admin)
(gnu packages bash)
(gnu packages guile)
(gnu packages pulseaudio)
(gnu packages virtualization)
(gnu packages terminals)
(gnu packages xdisorg)
(gnu packages xorg)
(gnu services)
(gnu services configuration)
(guix gexp)
(guix modules)
(guix profiles)
(ice-9 rdelim)
(json)
(gnu packages base)
(gnu packages haskell-apps)
(gnu packages wm)
(home config)
(home config openssh)
(home services ansible)
(home services cisco)
(home services desktop)
(home services gdb)
(home services emacs)
(home services juniper)
(home services h3c)
(home services mail)
(home services monitoring)
(home services nix)
(home services package-management)
(home services shell)
(home services version-control)
(home services terminals)
(home services tmux)
(home services linux)
(home services haskell-apps)
(home services gtk)
(home services stumpwm)
(home services rust-apps)
(home services lisp)
(home services python)
(home services nano)
(home services dns)
(home services web)
(home services gnupg)
(home services groovy)
(home services guile)
(home services kodi)
(home services databases)
(home services mime)
(home services video)
(home services networking)
(home services kubernetes)
(home services majordomo billing2)
(gnu packages mail)
(gnu packages dhall)
(guile pass)
)
(define %home
(and=> (getenv "HOME")
(lambda (home)
home)))
(add-to-load-path (string-append %home "/.local/bin"))
(use-modules (mjru-github-projects))
(define .bash_profile
(string-append %home "/.local/share/chezmoi/dot_bash_profile"))
(define .bashrc
(string-append %home "/.local/share/chezmoi/dot_bashrc"))
(define xmodmap-script
(program-file
"xmodmap"
#~(begin
(use-modules (srfi srfi-1)
(ice-9 popen)
(ice-9 rdelim))
(define %home
(and=> (getenv "HOME")
(lambda (home)
home)))
(define xmodmap
#$(file-append xmodmap "/bin/xmodmap"))
(define count (make-parameter 0))
(let loop ()
(let* ((port (open-pipe* OPEN_READ xmodmap "-pke"))
(output (read-string port)))
(close-pipe port)
(if (or (< 2 (count))
(any (lambda (str)
(string= str "keycode 134 = Control_L NoSymbol Control_L"))
(string-split (string-trim-right output #\newline) #\newline)))
#t
(begin
(count (1+ (count)))
(system* xmodmap (string-append %home "/.Xmodmap"))
(sleep 3)
(loop))))))))
(define* (majordomo-mbsync-goimapnotify-services name #:key (max-messages 0))
(define (pass-private-or-public name)
(if (file-exists? (string-append %home "/.password-store/majordomo/private/router.majordomo.ru/" name "@majordomo.ru.gpg"))
(string-append "majordomo/private/router.majordomo.ru/"
name "@majordomo.ru")
(string-append "majordomo/public/router.majordomo.ru/"
name "@majordomo.ru")))
(define majordomo-mbsync-imap-account-configuration
(mbsync-imap-account-configuration
(host "router.majordomo.ru")
(auth-mechs '("LOGIN"))
(ssl-type "None")
(certificate-file "/etc/ssl/certs/ca-certificates.crt")
(pipeline-depth 50)))
(define majordomo-mbsync-imap-store-configuration
(mbsync-imap-store-configuration
(imap-store "majordomo-remote")
(account "majordomo")))
(define majordomo-mbsync-maildir-store-configuration
(mbsync-maildir-store-configuration
(path "~/Maildir/")
(sub-folders "Verbatim")))
(define majordomo-mbsync-channel-configuration
(mbsync-channel-configuration
(patterns '("INBOX"))
(sync '("Pull"))
(max-messages max-messages)
(expunge "near")
(expire-unread "yes")))
(list
(simple-service (symbol-append 'home-mbsync-majordomo-
(string->symbol name))
home-mbsync-service-type
(mbsync-configuration
(imap-accounts
(list
(mbsync-imap-account-configuration
(inherit majordomo-mbsync-imap-account-configuration)
(imap-account (string-append "majordomo-" name))
(user (string-append name "@majordomo.ru"))
(ssl-type "IMAPS")
(pass-cmd
(string-join
(list "pass" "show"
(pass-private-or-public name)))))))
(imap-stores
(list
(mbsync-imap-store-configuration
(imap-store (string-append "majordomo-" name "-remote"))
(account (string-append "majordomo-" name)))))
(maildir-stores
(list
(mbsync-maildir-store-configuration
(inherit majordomo-mbsync-maildir-store-configuration)
(maildir-store (string-append "majordomo-" name "-local"))
(inbox (string-append "~/Maildir/majordomo-" name)))))
(channels
(list
(mbsync-channel-configuration
(inherit majordomo-mbsync-channel-configuration)
(channel (string-append "majordomo-" name))
(far (string-append ":majordomo-" name "-remote:"))
(near (string-append ":majordomo-" name "-local:")))))))
(service home-goimapnotify-service-type
(goimapnotify-configuration
(config-file
(computed-file
(string-append "isync-majordomo-" name "-config")
(with-extensions (list guile-json-4)
(with-imported-modules (source-module-closure '((json builder)))
#~(begin
(use-modules (json builder)
(ice-9 format))
(define isync
#$(file-append isync "/bin/mbsync"))
(define timeout
#$(file-append coreutils "/bin/timeout"))
(define password
#$(pass "show" (pass-private-or-public name)))
(define username #$name)
(with-output-to-file #$output
(lambda ()
(scm->json
`(("boxes" . #("INBOX"))
("onNewMail" . ,(string-join (list timeout (number->string 60) isync
(string-append "majordomo-" username))))
("xoauth2" . #f)
("password" . ,password)
("username" . ,(string-append username "@majordomo.ru"))
("tlsOptions" ("rejectUnauthorized" . #t))
("tls" . #t)
("port" . 993)
("host" . "imap.majordomo.ru"))))))))))))))
(define xsession-config-file
(let* ((stumpwp-load-file
(plain-file
"stumpwp-load-file"
(with-output-to-string
(lambda ()
(display '(require :asdf))
(newline)
(display '(require :stumpwm))
(newline)
(display '(stumpwm:stumpwm))
(newline)))))
(xsession-file
(program-file
"xsession"
#~(begin
(use-modules (srfi srfi-1)
(ice-9 popen)
(ice-9 rdelim)
(ice-9 format))
(define %display
(and=> (getenv "DISPLAY")
(lambda (display)
display)))
(define %home
(and=> (getenv "HOME")
(lambda (home)
home)))
(display "Set background\n")
(system* #$(file-append xsetroot "/bin/xsetroot")
"-solid" "black")
(display "Set cursor theme\n")
(system* #$(file-append xsetroot "/bin/xsetroot")
"-cursor_name" "left_ptr")
(display "Disable speaker\n")
(system* #$(file-append xset "/bin/xset") "-b")
(display "Configure keymap\n")
(system* #$xmodmap-script)
(system* #$(file-append setxkbmap "/bin/setxkbmap")
"-layout" "us,ru" "-option" "grp:win_space_toggle")
(display "Start window manager\n")
(if (string= %display ":0.0")
(execl "/run/current-system/profile/bin/sbcl" "sbcl" "--load" #$stumpwp-load-file)
(begin
(unsetenv "SESSION_MANAGER")
(unsetenv "DBUS_SESSION_BUS_ADDRESS")
(system* #$(file-append xhost "/bin/xhost") "+local:")
(let* ((pw (getpw (getuid)))
(shell (passwd:shell pw)))
The ' --login ' option is supported at least by Bash and .
(execl shell "sbcl" "--login" "-c"
(format #f ". /home/oleg/.bash_profile; /run/current-system/profile/bin/sbcl --load ~a"
#$stumpwp-load-file)))))))))
#~(begin
(let ((file #$(string-append %home "/.xsession")))
(copy-file #$xsession-file file)
(chmod file #o700)))))
(home-environment
(services
(append
(majordomo-mbsync-goimapnotify-services "pyhalov")
(majordomo-mbsync-goimapnotify-services "sidorov")
(majordomo-mbsync-goimapnotify-services "alertmanager"
#:max-messages 1000)
(majordomo-mbsync-goimapnotify-services "git-commits")
(majordomo-mbsync-goimapnotify-services "grafana")
(majordomo-mbsync-goimapnotify-services "healthchecks")
(majordomo-mbsync-goimapnotify-services "issues")
(majordomo-mbsync-goimapnotify-services "jenkins")
(majordomo-mbsync-goimapnotify-services "prometheus")
(majordomo-mbsync-goimapnotify-services "security")
(majordomo-mbsync-goimapnotify-services "smartmontools")
(majordomo-mbsync-goimapnotify-services "tracker")
(majordomo-mbsync-goimapnotify-services "ihc-zabbix")
(list
(simple-service 'home-mbsync-wugi-oleg
home-mbsync-service-type
(mbsync-configuration
(imap-accounts
(list
(mbsync-imap-account-configuration
(imap-account "wugi-oleg")
(host "imap.wugi.info")
(user "")
(pass-cmd "gpg -q --for-your-eyes-only --no-tty -d ~/.password-store/localhost/imap/oleg.gpg")
(auth-mechs '("LOGIN"))
(ssl-type "IMAPS")
(certificate-file "/etc/ssl/certs/ca-certificates.crt")
(pipeline-depth 50))))
(imap-stores
(list
(mbsync-imap-store-configuration
(imap-store "wugi-oleg-remote")
(account "wugi-oleg"))))
(maildir-stores
(list
(mbsync-maildir-store-configuration
(maildir-store "wugi-oleg-local")
(path "~/Maildir/")
(inbox "~/Maildir/wugi.info")
(sub-folders "Verbatim"))))
(channels
(list
(mbsync-channel-configuration
(channel "wugi-oleg")
(far ":wugi-oleg-remote:")
(near ":wugi-oleg-local:")
(patterns '("INBOX"))
(sync '("Pull")))))))
(simple-service 'home-mbsync-gmail-wigust
home-mbsync-service-type
(mbsync-configuration
(imap-accounts
(list
(mbsync-imap-account-configuration
(imap-account "gmail")
(host "imap.gmail.com")
(user "")
(pass-cmd "gpg -q --for-your-eyes-only --no-tty -d ~/.password-store/myaccount.google.com/apppasswords/go.wigust.gpg")
(auth-mechs '("LOGIN"))
(ssl-type "IMAPS")
(certificate-file "/etc/ssl/certs/ca-certificates.crt")
(pipeline-depth 50))))
(imap-stores
(list
(mbsync-imap-store-configuration
(imap-store "gmail-remote")
(account "gmail"))))
(maildir-stores
(list
(mbsync-maildir-store-configuration
(maildir-store "gmail-local")
(path "~/Maildir/")
(inbox "~/Maildir/INBOX")
(sub-folders "Verbatim"))))
(channels
(list
(mbsync-channel-configuration
(channel "gmail")
(far ":gmail-remote:")
(near ":gmail-local:")
(patterns '("INBOX"))
(sync '("Pull"))
(max-messages 2000)
(expunge "near"))))))
(service home-goimapnotify-service-type
(goimapnotify-configuration
(config-file
(computed-file
"isync-gmail-config"
(with-extensions (list guile-json-4)
(with-imported-modules (source-module-closure '((json builder)))
#~(begin
(use-modules (json builder)
(ice-9 format))
(define timeout
#$(file-append coreutils "/bin/timeout"))
(define isync
#$(file-append isync "/bin/mbsync"))
(define password
#$(pass "show" "myaccount.google.com/apppasswords/go.wigust"))
(with-output-to-file #$output
(lambda ()
(scm->json
`(("boxes" . #("INBOX"))
("onNewMail" . ,(string-join (list timeout (number->string 60) isync "gmail")))
("xoauth2" . #f)
("password" . ,password)
("username" . "")
("tlsOptions" ("rejectUnauthorized" . #t))
("tls" . #t)
("port" . 993)
("host" . "imap.gmail.com"))
#:pretty #t))))))))))
(service home-goimapnotify-service-type
(goimapnotify-configuration
(config-file
(computed-file
"isync-wugi-config"
(with-extensions (list guile-json-4)
(with-imported-modules (source-module-closure '((json builder)))
#~(begin
(use-modules (json builder)
(ice-9 format))
(define timeout
#$(file-append coreutils "/bin/timeout"))
(define isync
#$(file-append isync "/bin/mbsync"))
(define password
#$(pass "show" "localhost/imap/oleg"))
(with-output-to-file #$output
(lambda ()
(scm->json
`(("boxes" . #("INBOX"))
("onNewMail" . ,(string-join (list timeout (number->string 60) isync "wugi-oleg")))
("xoauth2" . #f)
("password" . ,password)
("username" . "")
("tlsOptions" ("rejectUnauthorized" . #t))
("tls" . #t)
("port" . 993)
("host" . "imap.wugi.info"))
#:pretty #t))))))))))
(simple-service 'amtool-config
home-files-service-type
(list `(".config/amtool/config.yml"
,(computed-file
"amtool-config.json"
(with-extensions (list guile-json-4)
(with-imported-modules (source-module-closure '((json builder)))
#~(begin
(use-modules (json builder))
(with-output-to-file #$output
(lambda ()
(scm->json
'(("output" . "extended")
("alertmanager.url" . ":9093"))
#:pretty #t))))))))))
home-chromium-service
home-bin-service
home-networking-service
(simple-service 'looking-glass-wrapper
home-files-service-type
(list `(".local/bin/looking-glass-client-wrapper"
,(local-file (string-append %project-directory "/dot_local/bin/executable_looking-glass-client-wrapper")
#:recursive? #t))))
(simple-service 'idea-ultimate-wrapper
home-files-service-type
(list `(".local/bin/idea-ultimate"
,(computed-file
"idea-ultimate-wrapper"
#~(begin
(with-output-to-file #$output
(lambda ()
(format #t "\
#!/bin/sh
PYTHONPATH='' exec -a \"$0\" ~a/bin/idea-ultimate \"$@\"\n"
#$(string-append %home "/.nix-profile"))))
(chmod #$output #o555))))))
(service stumpwm-service-type
(let ((config-files
'("utils.lisp"
"keys.lisp"
"nav.lisp"
"theme.lisp"
"xorg.lisp"
"term.lisp"
"text-editors.lisp"
"repl.lisp"
"notify.lisp"
"hardware.lisp"
"admin.lisp"
"clipboard.lisp"
"screenshoot.lisp"
"password.lisp"
"trans.lisp"
"backup.lisp"
"documentation.lisp"
"emacs.lisp"
"chat.lisp"
"mail.lisp"
"docker.lisp"
"vnc.lisp"
"rofi.lisp"
"audio.lisp"
"mpv.lisp"
"streamlink.lisp"
"youtube-dl.lisp"
"android.lisp"
"kodi.lisp"
"web.lisp"
"time.lisp"
"mjru.lisp"
"virtualization.lisp"
"bittorrent.lisp"
"kubernetes.lisp"
"disk.lisp"
"rest.lisp"
"cpu.lisp"
"mem.lisp"
"imap.lisp"
"covid19.lisp"
"gpg.lisp"
"vpn.lisp"
"mode-line.lisp"
"display-0.lisp"
"display.lisp"
"autostart.lisp"
"swank.lisp"
"gaps.lisp")))
(stumpwm-configuration
(init-config
`((in-package :stumpwm)
(require "asdf")
(defvar *fontconfig-file*
"FONTCONFIG_FILE=/run/current-system/profile/etc/fonts/fonts.conf")
(redirect-all-output
(concat
(getenv "HOME") "/.local/var/log/stumpwm/" (getenv "DISPLAY") ".log"))
( defcommand quassel ( ) ( )
Tuesday January 3 2005 23:05:25
(setq *time-format-string-default* "%A %B %e %Y %k:%M:%S")
(setf *startup-message* nil)
(setf *message-window-gravity* :center)
(setf *input-window-gravity* :center)
,@(map (lambda (config-file)
`(load ,(string-append "/home/oleg/.stumpwm.d/" config-file)))
config-files)
( restore - from - file , ( local - file " /home / oleg/.local / share / chezmoi / dot_stumpwm.d / group-1.lisp " ) )
))
(config-files config-files))))
home-bash-service
home-mime-service
home-bind-utils-service
home-direnv-service
home-gdb-service
home-ghci-service
home-git-service
home-gita-service
home-emacs-state-service
home-emacs-service
home-groovy-service
home-gnupg-service
home-inputrc-service
home-guile-service
(simple-service 'keynav-config
home-files-service-type
(list `(".keynavrc" ,(local-file (string-append %project-directory "/dot_keynavrc")))))
home-kodi-service
home-mailcap-service
home-mongo-service
home-postgresql-service
home-mycli-service
home-nano-service
home-python-service
home-sbcl-service
home-screen-service
home-tmux-service
tmuxifier-service
home-top-service
(simple-service 'xmodmap-config
home-files-service-type
(list `(".Xmodmap" ,(local-file (string-append %project-directory "/dot_Xmodmap")))))
(simple-service 'xresources-config
home-files-service-type
(list `(".Xresources" ,(local-file (string-append %project-directory "/dot_Xresources")))))
home-qterminal-service
(simple-service 'zathura-config
home-files-service-type
(list `(".config/zathura/zathurarc" ,(local-file (string-append %project-directory "/dot_config/zathura/zathurarc")))))
home-ripgrep-service
home-gtk-service
home-gtkrc-service
home-greenclip-service
home-alacritty-service
home-kitty-service
(simple-service 'feh-config
home-files-service-type
(list `(".config/feh/buttons" ,(local-file (string-append %project-directory "/dot_config/feh/buttons")))))
(simple-service 'sway-config
home-files-service-type
(list `(".config/sway/config" ,(local-file (string-append %project-directory "/dot_config/sway/config")))))
(simple-service 'polybar-config
home-files-service-type
(list `(".config/polybar/config" ,(local-file (string-append %project-directory "/dot_config/polybar/config")))))
home-youtube-dl-service
(simple-service 'cava-config
home-files-service-type
(list `(".config/cava/config" ,(local-file (string-append %project-directory "/dot_config/cava/config")))))
(simple-service 'termonad-config
home-files-service-type
(list `(".config/termonad/termonad.hs" ,(local-file (string-append %project-directory "/dot_config/termonad/termonad.hs")))))
home-nix-service
home-mpv-service
(simple-service 'cagebreak-config
home-files-service-type
(list `(".config/cagebreak/config" ,(local-file (string-append %project-directory "/dot_config/cagebreak/config")))))
(simple-service 'vis-config
home-files-service-type
(list `(".config/vis/config" ,(local-file (string-append %project-directory "/dot_config/vis/config")))))
(simple-service 'dunst-config
home-files-service-type
(list `(".config/dunst/dunstrc" ,(local-file (string-append %project-directory "/dot_config/dunst/dunstrc")))))
(simple-service 'espanso-config
home-activation-service-type
#~(invoke
#$(program-file
"espanso-config"
(with-imported-modules '((ice-9 match))
#~(begin
(use-modules (ice-9 match))
(for-each (match-lambda ((destination source)
(let ((destination-full-path (string-append #$%home "/." destination)))
(when (file-exists? destination-full-path)
(chmod destination-full-path #o644))
(copy-file source destination-full-path))))
(list `("config/espanso/default.yml" ,#$(local-file (string-append %project-directory "/dot_config/espanso/default.yml")))
`("config/espanso/user/systemd.yml" ,#$(local-file (string-append %project-directory "/dot_config/espanso/user/systemd.yml")))
`("config/espanso/user/juniper.yml" ,#$(local-file (string-append %project-directory "/dot_config/espanso/user/juniper.yml")))
`("config/espanso/user/mysql.yml" ,#$(local-file (string-append %project-directory "/dot_config/espanso/user/mysql.yml")))
`("config/espanso/user/nix.yml" ,#$(local-file (string-append %project-directory "/dot_config/espanso/user/nix.yml")))
`("config/espanso/user/mjru.yml" ,#$(local-file (string-append %project-directory "/dot_config/espanso/user/mjru.yml"))))))))))
(simple-service 'sshrc-config
home-files-service-type
(list `(".sshrc" ,(local-file (string-append %project-directory "/dot_sshrc")))
`(".sshrc.d/.bashrc" ,(local-file (string-append %project-directory "/dot_sshrc.d/dot_bashrc")))
`(".sshrc.d/.tmux.conf" ,(local-file (string-append %project-directory "/dot_sshrc.d/dot_tmux.conf")))))
(simple-service 'vnc-config
home-files-service-type
(list `(".vnc/default.tigervnc" ,(local-file (string-append %project-directory "/private_dot_vnc/default.tigervnc")))
`(".vnc/xstartup" ,(local-file (string-append %project-directory "/private_dot_vnc/executable_xstartup") #:recursive? #t))
`(".vnc/xstartup-firefox" ,(local-file (string-append %project-directory "/private_dot_vnc/executable_xstartup-firefox") #:recursive? #t))
`(".vnc/xstartup-quassel" ,(local-file (string-append %project-directory "/private_dot_vnc/executable_xstartup-quassel") #:recursive? #t))
`(".vnc/xstartup-ratpoison" ,(local-file (string-append %project-directory "/private_dot_vnc/executable_xstartup-ratpoison") #:recursive? #t))
`(".vnc/xstartup-stumpwm" ,(local-file (string-append %project-directory "/private_dot_vnc/executable_xstartup-stumpwm") #:recursive? #t))
`(".vnc/xstartup-twm" ,(local-file (string-append %project-directory "/private_dot_vnc/executable_xstartup-twm") #:recursive? #t))))
(simple-service 'xsession-config
home-activation-service-type
xsession-config-file)
home-parallel-service
(simple-service 'msmtp-config
home-activation-service-type
#~(begin
(define %home
(and=> (getenv "HOME")
(lambda (home)
home)))
(add-to-load-path (string-append %home "/.local/share/chezmoi/dotfiles"))
(use-modules (ice-9 format)
(guile pass))
(define msmtp-config
(string-append %home "/.msmtprc"))
(call-with-output-file msmtp-config
(lambda (port)
(format port "\
# Set default values for all following accounts.
defaults
auth on
tls on
tls_trust_file /etc/ssl/certs/ca-certificates.crt
logfile ~a/.msmtp.log
# Gmail
account gmail
host smtp.gmail.com
port 587
from
user go.wigust
password ~a
# Majordomo
account majordomo-pyhalov
host smtp.majordomo.ru
port 587
from
user
password ~a
# Set a default account
account default : gmail
"
%home
(pass "myaccount.google.com/apppasswords/go.wigust")
(pass "majordomo/private/newmail.majordomo.ru/"))))
(chmod msmtp-config #o600)))
(simple-service 'netrc-config
home-activation-service-type
(let ((file
(scheme-file
"netrc.scm"
#~(begin
(let ((%home
(and=> (getenv "HOME")
(lambda (home)
home))))
(add-to-load-path (string-append %home "/.local/share/chezmoi/dotfiles"))
(use-modules (ice-9 format)
(ice-9 match)
(guile pass))
(call-with-output-file (string-append %home "/.netrc")
(lambda (port)
(for-each
(match-lambda
((net (machine m)
(login l)
(password p))
(format port "~%machine ~a~%" m)
(format port "login ~a~%" l)
(format port "password ~a~%" (pass p))))
'((net
(machine "api.github.com")
(login "wigust")
(password "github/tokens/api/wigust"))
(net
(machine "uploads.github.com")
(login "wigust")
(password "github/tokens/api/wigust"))
(net
(machine "imap.yandex.ru")
(login "houdinihar")
(password "email/yandex.ru/houdinihar"))
(net
(machine "imap.rambler.ru")
(login "houdinihar")
(password "email/rambler/houdinihar"))
(net
(machine "imap.majordomo.ru")
(login "pyhalov")
(password "majordomo/private/newmail.majordomo.ru/"))
(net
(machine "localhost")
(login "oleg")
(password "localhost/imap/oleg"))
(net
(machine "bareos.intr")
(login "netcfg")
(password "majordomo/public/172.16.103.111/netcfg"))
(net
(machine "pop3.hoster24.ru")
(login "pop3")
(password "majordomo/public/hoster24.ru/pop3"))
(net
(machine "172.16.103.111")
(login "netcfg")
(password "majordomo/public/172.16.103.111/netcfg")))))))))))
#~(begin (primitive-load #$file))))
(service home-mcron-service-type)
(service nix-delete-generations-service-type
(nix-delete-generations-configuration
(schedule '(next-hour '(21)))))
(service guix-delete-generations-service-type
(guix-delete-generations-configuration
(schedule '(next-hour '(21)))
(period "1m")))
(service ansible-playbook-service-type)
(service juniper-service-type)
(service h3c-service-type)
(service cisco-service-type)
(service kubernetes-service-type)
(service billing2-service-type)
(simple-service 'ansible-config
home-files-service-type
(append (list `(,".ansible.cfg" ,(local-file (string-append %project-directory "/dot_ansible.cfg"))))
(map (lambda (file-name)
`(,(string-append ".ansible/plugins/modules/" file-name)
,(local-file (string-append %project-directory
"/dot_ansible/plugins/modules/"
file-name))))
'("guix_package.py"
"guix_pull.py"))))
(simple-service 'ansible-hosts-config
home-activation-service-type
(with-extensions (list guile-json-4)
(with-imported-modules (source-module-closure '((json builder)))
#~(begin
(add-to-load-path (string-append #$%home "/.local/share/chezmoi/dotfiles"))
(use-modules (ice-9 rdelim)
(ice-9 popen)
(guile pass)
(json builder)
(ice-9 match)
(srfi srfi-41))
(define password-router
(pass "majordomo/public/router4/root"))
(define majordomo-office
( " Admin-1 " " 172.16.107.21 " " 18 : c0:4d : f9 : c0 : b6 " " Home segment " " Wired " " 100 Mbit / s " " Port 1 " )
( " Admin-2 " " 172.16.107.22 " " 18 : c0:4d : f9 : c1:9a " " Offline " )
( " Admin-3 " " 172.16.107.23 " " 18 : c0:4d : f9 : c0 : bb " " Home segment " " Wired " " 100 Mbit / s " " Port 1 " )
( " dev-1 " " 172.16.107.11 " " 18 : c0:4d : f9 : c1:99 " " Home segment " " Wired " " 100 Mbit / s " " Port 1 " )
( " dev-2 " " 172.16.107.12 " " 18 : c0:4d : f9 : c1:9b " " Home segment " " Wired " " 100 Mbit / s " " Port 1 " )
( " Info-1 " " 172.16.107.31 " " 18 : c0:4d : f9 : " " Home segment " " Wired " " 100 Mbit / s " " Port 1 " )
( " Info-2 " " 172.16.107.32 " " 18 : c0:4d : f9 : c0 : fe " " Home segment " " Wired " " 100 Mbit / s " " Port 1 " )
( " iPhone - Gennadiy via Keenetic Air ( KN-1611 ) " " 172.16.107.143 " " ce:97:72 : a9:1f : d6 " " Home segment " " 5 GHz Wi - Fi " " 130 Mbit / s WPA2 " " ac / k / v 2x2 20 MHz " )
( " SPA122 " " 172.16.107.8 " " 88:75:56:07:73:92 " " Home segment " " Wired " " 0 Mbit / s " " Port 1 " )
("sup1" "172.16.107.41" "18:c0:4d:f9:c0:b8" "Home segment" "Wired" "100 Mbit/s" "Port 1")
("sup2" "172.16.107.42" "18:c0:4d:f9:c0:bc" "Home segment" "Wired" "100 Mbit/s" "Port 1")
("sup3" "172.16.107.43" "18:c0:4d:f9:c0:f9" "Home segment" "Wired" "100 Mbit/s" "Port 1")
("sup4" "172.16.107.44" "18:c0:4d:f9:c0:83" "Home segment" "Wired" "100 Mbit/s" "Port 1")))
(call-with-output-file #$(string-append %home "/.ansible-hosts")
(lambda (port)
(scm->json
`(("vps"
("vars"
("ansible_ssh_user" . "opc")
("ansible_ssh_private_key_file"
.
"~/.ssh/id_rsa_oracle"))
("hosts" ("oracle" . null)))
("vm"
("vars"
("ansible_ssh_user" . "root")
("ansible_python_interpreter"
.
"/usr/bin/python3"))
("children"
("majordomo_office"
("hosts"
,@(map ((@@ (ice-9 match) match-lambda)
((name ip mac etc ...)
(cons ip 'null)))
majordomo-office))
("vars"
("ansible_ssh_user" . "root")
("ansible_python_interpreter" . "/run/current-system/sw/bin/python3")))
("mjru"
("hosts"
("78.108.87.99" . null)
("78.108.87.50" . null)
("78.108.86.20" . null)
("78.108.86.111" . null)
("78.108.82.130" . null)
("178.250.247.88" . null)
("178.250.247.60" . null)
("178.250.246.69" . null)
("178.250.246.123" . null)
("178.250.245.80" . null)
("178.250.244.239" . null)))
("ihc"
("vars"
("ansible_ssh_user" . "pyhalov")
("ansible_ssh_private_key_file" . "~/.ssh/id_rsa_ihc_pyhalov"))
("hosts"
("kvm-nvme1.majordomo.ru" . null)
("kvm-nvme101.majordomo.ru" . null)
("kvm-nvme102.majordomo.ru" . null)
("kvm-nvme201.majordomo.ru" . null)
("kvm-nvme202.majordomo.ru" . null)
("kvm-nvme203.majordomo.ru" . null)))
("kubernetes"
("hosts"
,@(map (lambda (number)
`(,(string-append "kube" (number->string number) ".intr") . null))
(stream->list (stream-range 1 9))))
("vars"
("ansible_ssh_user" . "root")
("ansible_python_interpreter" . "/run/current-system/sw/bin/python3")))
("glpi" ("hosts" ("178.250.244.239" . null)))
("docker"
("hosts"
("78.108.87.99" . null)
("78.108.86.20" . null)
("178.250.246.123" . null))))
)
("majordomo"
("hosts"
("zabbix.intr" . null)
("ci.intr" . null)
("bareos.intr" . null)
("archive.intr" . null)
("backup.intr" . null))
("children"
("web"
("hosts"
("web37.intr" . null)
("web36.intr" . null)
("web35.intr" . null)
("web34.intr" . null)
("web33.intr" . null)
("web32.intr" . null)
("web31.intr" . null)
("web30.intr" . null)
("web29.intr" . null)
("web28.intr" . null)
("web27.intr" . null)
("web26.intr" . null)
("web25.intr" . null)
("web23.intr" . null)
("web22.intr" . null)
("web21.intr" . null)
("web20.intr" . null)
("web19.intr" . null)
("web18.intr" . null)
("web17.intr" . null)
("web16.intr" . null)
("web15.intr" . null)))
("deprecated_web"
("hosts"
#$@%ansible-majordomo-deprecated-webs))
("vpn"
("hosts"
("router4.intr" . null)
("ns1-dh.intr" . null)
("galera-backup.intr" . null)))
("swarm"
("hosts"
("dh5-mr.intr" . null)
("dh4-mr.intr" . null)
("dh3-mr.intr" . null)
("dh2-mr.intr" . null)
("dh1-mr.intr" . null)))
("router"
("children"
("routers"
("vars" ("ansible_ssh_pass" . ,password-router))
("hosts" ("router4.intr" . null)))
("office"
("hosts"
("router2.intr" . null)
("router1.intr" . null)))
("freebsd"
("vars"
("ansible_python_interpreter"
.
"/usr/local/bin/python2"))
("hosts" ("router-miran1.intr" . null)))))
("redis"
("hosts"
("hms02-mr.intr" . null)
("hms01-mr.intr" . null)))
("ns"
("hosts"
("ns2-mr.intr" . null)
("ns2-dh.intr" . null)
("ns1-mr.intr" . null)
("ns1-dh.intr" . null)))
("nginx"
("hosts"
("nginx3.intr" . null)
("nginx2.intr" . null)
("nginx1.intr" . null)))
("mongo"
("hosts"
("hms03-mr.intr" . null)
("hms02-mr.intr" . null)
("hms01-mr.intr" . null)))
("miran"
("children"
("rack4"
("hosts"
("zabbix.intr" . null)
("web18.intr" . null)
("web15.intr" . null)
("staff.intr" . null)
("router-miran1.intr" . null)
("mail-checker2.intr" . null)
("kvm14.intr" . null)
("galera3.intr" . null)
("galera2.intr" . null)
("galera1.intr" . null)
("dh2.intr" . null)
("bareos.intr" . null)))
("rack3"
("hosts"
("web37.intr" . null)
("web34.intr" . null)
("web33.intr" . null)
("web32.intr" . null)
("web31.intr" . null)
("web30.intr" . null)
("web29.intr" . null)
("web28.intr" . null)
("web27.intr" . null)
("web26.intr" . null)
("web25.intr" . null)
("web23.intr" . null)
("web22.intr" . null)
("web20.intr" . null)
("web19.intr" . null)
("web17.intr" . null)
("web16.intr" . null)
("ns2-mr.intr" . null)
("kvm2.intr" . null)
("kvm15.intr" . null)
("jenkins.intr" . null)))
("rack2"
("hosts"
("webmail2.intr" . null)
("webmail1.intr" . null)
("web36.intr" . null)
("web35.intr" . null)
("web21.intr" . null)
("smtp-staff.intr" . null)
("ns1-mr.intr" . null)
("nginx2.intr" . null)
("nginx1.intr" . null)
("kvm37.intr" . null)
("hms02-mr.intr" . null)
("galera-backup.intr" . null)
("dh4.intr" . null)
("dh1.intr" . null)
("chef-server.intr" . null)
("buka2-new.intr" . null)
("archive.intr" . null)))
("rack1"
("hosts"
("pop5.intr" . null)
("mx1.intr" . null)
("hms01-mr.intr" . null)
("fluentd.intr" . null)
("dh3.intr" . null)))))
("mail"
("children"
("spam"
("hosts"
("mail-checker2.intr" . null)
("mail-checker1.intr" . null)))
("smtp"
("hosts"
("webmail2.intr" . null)
("webmail1.intr" . null)))
("pop"
("hosts"
("pop5.intr" . null)
("pop1.intr" . null)))
("mx"
("hosts"
("nginx2.intr" . null)
("nginx1.intr" . null)))))
("kvm"
("hosts"
("kvm9.intr" . null)
("kvm6.intr" . null)
("kvm5.intr" . null)
("kvm37.intr" . null)
("kvm35.intr" . null)
("kvm34.intr" . null)
("kvm33.intr" . null)
("kvm32.intr" . null)
("kvm31.intr" . null)
("kvm30.intr" . null)
("kvm29.intr" . null)
("kvm28.intr" . null)
("kvm27.intr" . null)
("kvm26.intr" . null)
("kvm25.intr" . null)
("kvm24.intr" . null)
("kvm23.intr" . null)
("kvm22.intr" . null)
("kvm21.intr" . null)
("kvm20.intr" . null)
("kvm2.intr" . null)
("kvm19.intr" . null)
("kvm17.intr" . null)
("kvm16.intr" . null)
("kvm15.intr" . null)
("kvm14.intr" . null)
("kvm13.intr" . null)
("kvm12.intr" . null)
("kvm10.intr" . null)
("kvm1.intr" . null)
("c-11122.intr" . null)))
("jenkins" ("hosts" ("jenkins.intr" . null)))
("galera"
("hosts"
("galera1.intr" . null)
("galera2.intr" . null)
("galera3.intr" . null)))
("elk"
("hosts"
("pop5.intr" . null)
("fluentd.intr" . null)
("chef-server.intr" . null)))
("datahouse"
("hosts"
("kvm1.intr" . null)
("kvm2.intr" . null)
("kvm5.intr" . null)
("kvm6.intr" . null)
("kvm7.intr" . null)
("kvm9.intr" . null)
("kvm10.intr" . null)
("kvm11.intr" . null)
("kvm12.intr" . null)
("kvm13.intr" . null)
("kvm14.intr" . null)
("kvm15.intr" . null)
("kvm16.intr" . null)
("kvm17.intr" . null)
("kvm18.intr" . null)
("kvm19.intr" . null)
("kvm20.intr" . null)
("kvm21.intr" . null)
("kvm22.intr" . null)
("kvm23.intr" . null)
("kvm24.intr" . null)
("kvm25.intr" . null)
("kvm26.intr" . null)
("kvm27.intr" . null)
("kvm28.intr" . null)
("kvm29.intr" . null)
("kvm34.intr" . null)
("kvm33.intr" . null)
("kvm32.intr" . null)
("kvm31.intr" . null)
("kvm30.intr" . null)
("kvm35.intr" . null)
("kvm37.intr" . null)))))
("guix"
("vars"
("ansible_python_interpreter"
.
"/home/oleg/.guix-profile/bin/python3"))
("children"
("local"
("vars" ("ansible_connection" . "local"))
("hosts" ("localhost" . null)))
( " guix_work " ( " hosts " ( " ws1.wugi.info " . null ) ) )
("guix_vm"
("hosts"
("vm1.wugi.info" . null))))))
port
#:pretty #t)))))))
(service home-openssh-service-type %home-openssh-configuration)
(service home-greenclip-service-type)
(service nix-build-service-type
(nix-build-configurations
(configurations
(append
(map
(lambda (hostname)
(nix-build-configuration
(name hostname)
(git-project git-project-nixos-pop)))
'("pop1" "pop5"))
(map
(lambda (hostname)
(nix-build-configuration
(name hostname)
(git-project git-project-nixos-monitoring)))
'("staff"))
(map
(lambda (hostname)
(nix-build-configuration
(name hostname)
(git-project git-project-nixos-ns)))
'("ns1-mr" "ns2-mr" "ns1-dh" "ns2-dh"))
(map
(lambda (hostname)
(nix-build-configuration
(name hostname)
(git-project git-project-nixos-web)))
'("web30"))
(map
(lambda (hostname)
(nix-build-configuration
(name hostname)
(git-project git-project-nixos-jenkins)))
'("jenkins"))))))
XXX : Make sure ~/.ssh / known_hosts provides ssh - rsa host key algorithm ,
(service home-prometheus-ssh-exporter-service-type
(prometheus-ssh-exporter-configuration
(config-file
(computed-file
"ssh-exporter.json"
(with-extensions (list guile-json-4)
(with-imported-modules (source-module-closure '((json builder)))
#~(begin
(use-modules (json builder)
(ice-9 rdelim))
(define %home #$%home)
(with-output-to-file #$output
(lambda ()
(scm->json
`(("modules"
("default"
("user" . "oleg")
("timeout" . 5)
("private_key" . ,(string-append %home "/.ssh/id"))
("known_hosts" . ,(string-append %home "/.ssh/known_hosts"))
("host_key_algorithms" . #("ssh-ed25519"))
("command" . "uptime"))
("id_rsa"
("user" . "oleg")
("timeout" . 5)
("private_key" . ,(string-append %home "/.ssh/id_rsa"))
("known_hosts" . ,(string-append %home "/.ssh/known_hosts"))
("command" . "uptime"))
("majordomo-eng"
("user" . "eng")
("timeout" . 5)
("private_key" . ,(string-append %home "/.ssh/id_rsa_majordomo_eng"))
("known_hosts" . ,(string-append %home "/.ssh/known_hosts"))
("command" . "uptime"))
("majordomo-net"
("user" . "root")
("timeout" . 5)
("private_key" . ,(string-append %home "/.ssh/id_rsa_majordomo_eng"))
("known_hosts" . ,(string-append %home "/.ssh/known_hosts"))
("command" . "uptime"))))))))))))))
oleg@guixsd ~/.local / share / chezmoi$ command home -L dotfiles / guixsd / modules -L ~/src / engstrand - config - home - service - dwl - guile reconfigure dotfiles / guixsd / home.scm
( let ( ( ( file - append ponymix " /bin / ponymix " ) ) )
( action ` ( dwl : spawn , ponymix " decrease " " 5 " ) ) )
( action ` ( dwl : spawn , ponymix " increase " " 5 " ) ) )
(simple-service
'auto-shutdown-cron-jobs
home-mcron-service-type
(list
#~(job
'(next-hour)
#$(program-file
"schedule-power"
#~(begin
(system*
#$(local-file (string-append %project-directory "/dot_local/bin/executable_schedule-power")
#:recursive? #t)))))))))))
|
8c9de98bd5bd116bc1a078a5c0fe4752f451b0df45bd84ce01b8423c3d82e4b8 | jyh/metaprl | itt_union.ml | doc <:doc<
@spelling{handedness}
@module[Itt_union]
The union type $T_1 + T_2$ defines a union space containing the
elements of both $T_1$ and $T_2$. The union is @emph{disjoint}: the
elements are @emph{tagged} with the @hrefterm[inl] and @hrefterm[inr]
tags as belonging to the ``left'' type $T_1$ or the ``right'' type
$T_2$.
The union type is the first primitive type that can have more than one
element. The tag makes the handedness of membership decidable, and
the union type $@unit + @unit$ contains two elements: <<inl{it}>> and
<<inr{it}>>. The @hrefmodule[Itt_bool] module uses this definition to
define the Boolean values, where @emph{false} is <<inl{it}>> and
@emph{true} is <<inr{it}>>.
@docoff
----------------------------------------------------------------
@begin[license]
This file is part of MetaPRL, a modular, higher order
logical framework that provides a logical programming
environment for OCaml and other languages.
See the file doc/htmlman/default.html or visit /
for more information.
Copyright (C) 1997-2006 MetaPRL Group, Cornell University and
California Institute of Technology
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
Author: Jason Hickey @email{}
Modified by: Aleksey Nogin @email{}
@end[license]
>>
doc <:doc< @parents >>
extends Itt_void
extends Itt_equal
extends Itt_struct
extends Itt_subtype
doc docoff
open Unify_mm
open Basic_tactics
open Itt_equal
open Itt_subtype
(************************************************************************
* TERMS *
************************************************************************)
doc <:doc<
@terms
The @tt{union} type is the binary union of two types $A$ and $B$.
The elements are $@inl{a}$ for $a @in A$ and $@inr{b}$ for $b @in B$.
The @tt{decide} term @emph{decides} the handedness of the term $x @in A + B$.
>>
declare \union{'A; 'B}
declare inl{'x}
declare inr{'x}
declare decide{'x; y. 'a['y]; z. 'b['z]}
declare undefined
define unfold_outl: outl{'x} <--> decide{'x; y. 'y; z. undefined}
define unfold_outr: outr{'x} <--> decide{'x; y. undefined; z. 'z}
define unfold_out: out{'x} <--> decide{'x; y. 'y; z. 'z}
(************************************************************************
* REWRITES *
************************************************************************)
doc <:doc<
@rewrites
The following two rules define the computational behavior of the
@hrefterm[decide] term. There are two reductions, the @tt{reduceDecideInl}
rewrite describes reduction of @tt{decide} on the @hrefterm[inl] term,
and @tt{reduceDecideInr} describes reduction on the @hrefterm[inr] term.
The rewrites are added to the @hrefconv[reduceC] resource.
>>
prim_rw reduceDecideInl {| reduce |} : decide{inl{'x}; u. 'l['u]; v. 'r['v]} <--> 'l['x]
prim_rw reduceDecideInr {| reduce |} : decide{inr{'x}; u. 'l['u]; v. 'r['v]} <--> 'r['x]
interactive_rw reduce_outl_inl {| reduce |} : outl{inl{'x}} <--> 'x
interactive_rw reduce_outr_inr {| reduce |} : outr{inr{'x}} <--> 'x
interactive_rw reduce_out_inl {| reduce |} : out{inl{'x}} <--> 'x
interactive_rw reduce_out_inr {| reduce |} : out{inr{'x}} <--> 'x
doc docoff
(************************************************************************
* DISPLAY FORMS *
************************************************************************)
prec prec_inl
prec prec_union
dform union_df : except_mode[src] :: parens :: "prec"[prec_union] :: \union{'A; 'B} =
slot{'A} " " `"+" " " slot{'B}
dform inl_df : except_mode[src] :: parens :: "prec"[prec_inl] :: inl{'a} =
`"inl" " " slot{'a}
dform inr_df : except_mode[src] :: parens :: "prec"[prec_inl] :: inr{'a} =
`"inr" " " slot{'a}
dform decide_df : except_mode[src] :: decide{'x; y. 'a; z. 'b} =
pushm[1] szone pushm[3] keyword["match"] " " slot{'x} " " keyword["with"] hspace
pushm[3] `"inl " 'y `" -> " slot{'a} popm popm hspace
`"| " pushm[3] `"inr " 'z `" -> " slot{'b} popm ezone popm
(************************************************************************
* RULES *
************************************************************************)
doc <:doc<
@rules
@modsubsection{Typehood and equality}
The equality of the @hrefterm[union] type is intensional; the
union $A + B$ is a type if both $A$ and $B$ are types.
>>
prim unionEquality {| intro [] |} :
[wf] sequent { <H> >- 'A1 = 'A2 in univ[i:l] } -->
[wf] sequent { <H> >- 'B1 = 'B2 in univ[i:l] } -->
sequent { <H> >- 'A1 + 'B1 = 'A2 + 'B2 in univ[i:l] } =
it
(*
* Typehood.
*)
prim unionType {| intro [] |} :
[wf] sequent { <H> >- "type"{'A} } -->
[wf] sequent { <H> >- "type"{'B} } -->
sequent { <H> >- "type"{'A + 'B} } =
it
doc <:doc<
@modsubsection{Membership}
The following two rules define membership, $@inl{a} @in A + B$
if $a @in A$ and $@inr{b} @in A + B$ if $b @in B$. Both
$A$ and $B$ must be types.
>>
prim inlEquality {| intro [] |} :
[wf] sequent { <H> >- 'a1 = 'a2 in 'A } -->
[wf] sequent { <H> >- "type"{'B} } -->
sequent { <H> >- inl{'a1} = inl{'a2} in 'A + 'B } =
it
* H > - inr b1 = inr b2 in A + B
* by H > - b1 = b2 in B
* H > - A = A in Ui
* H >- inr b1 = inr b2 in A + B
* by inrEquality
* H >- b1 = b2 in B
* H >- A = A in Ui
*)
prim inrEquality {| intro [] |} :
[wf] sequent { <H> >- 'b1 = 'b2 in 'B } -->
[wf] sequent { <H> >- "type"{'A} } -->
sequent { <H> >- inr{'b1} = inr{'b2} in 'A + 'B } =
it
doc <:doc<
@modsubsection{Introduction}
The union type $A + B$ is true if both $A$ and $B$ are types,
and either 1) $A$ is provable, or 2) $B$ is provable. The following
two rules are added to the @hreftactic[dT] tactic. The application
uses the @hreftactic[selT] tactic to choose the handedness; the
@tt{inlFormation} rule is applied with the tactic @tt{selT 1 (dT 0)}
and the @tt{inrFormation} is applied with @tt{selT 2 (dT 0)}.
>>
interactive inlFormation {| intro [SelectOption 1] |} :
[main] sequent { <H> >- 'A } -->
[wf] sequent { <H> >- "type"{'B} } -->
sequent { <H> >- 'A + 'B }
* H > - A + B ext inl a
* by inrFormation
* H > - B
* H > - A = A in Ui
* H >- A + B ext inl a
* by inrFormation
* H >- B
* H >- A = A in Ui
*)
interactive inrFormation {| intro [SelectOption 2] |} :
[main] ('b : sequent { <H> >- 'B }) -->
[wf] sequent { <H> >- "type"{'A} } -->
sequent { <H> >- 'A + 'B }
doc <:doc<
@modsubsection{Elimination}
The handedness of the union membership is @emph{decidable}. The
elimination rule performs a case analysis in the assumption $x@colon A + B$;
the first for the @tt{inl} case, and the second for the @tt{inr}. The proof
extract term is the @tt{decide} combinator (which performs a decision
on element membership).
>>
prim unionElimination {| elim |} 'H :
[left] ('left['u] : sequent { <H>; u: 'A; <J[inl{'u}]> >- 'T[inl{'u}] }) -->
[right] ('right['v] : sequent { <H>; v: 'B; <J[inr{'v}]> >- 'T[inr{'v}] }) -->
sequent { <H>; x: 'A + 'B; <J['x]> >- 'T['x] } =
decide{'x; u. 'left['u]; v. 'right['v]}
doc <:doc<
@modsubsection{Combinator equality}
The @tt{decide} term equality is true if there is @emph{some} type
$A + B$ for which all the subterms are equal.
>>
prim decideEquality {| intro [] |} bind{z. 'T['z]} ('A + 'B) :
[wf] sequent { <H> >- 'e1 = 'e2 in 'A + 'B } -->
[wf] sequent { <H>; u: 'A; 'e1 = inl{'u} in 'A + 'B >- 'l1['u] = 'l2['u] in 'T[inl{'u}] } -->
[wf] sequent { <H>; v: 'B; 'e1 = inr{'v} in 'A + 'B >- 'r1['v] = 'r2['v] in 'T[inr{'v}] } -->
sequent { <H> >- decide{'e1; u1. 'l1['u1]; v1. 'r1['v1]} =
decide{'e2; u2. 'l2['u2]; v2. 'r2['v2]} in
'T['e1] } =
it
doc <:doc<
@modsubsection{Subtyping}
The union type $A_1 + A_2$ is a subtype of type $A_2 + B_2$ if
$A_1 @subseteq A_2$ and $B_1 @subseteq B_2$. This rule is added
to the @hrefresource[subtype_resource].
>>
interactive unionSubtype {| intro [] |} :
["subtype"] sequent { <H> >- 'A1 subtype 'A2 } -->
["subtype"] sequent { <H> >- 'B1 subtype 'B2 } -->
sequent { <H> >- 'A1 + 'B1 subtype 'A2 + 'B2 }
doc <:doc<
@modsubsection{Contradiction lemmas}
An @tt[inl] can not be equal to @tt[inr].
>>
interactive unionContradiction1 {| elim []; nth_hyp |} 'H :
sequent { <H>; x: inl{'y} = inr{'z} in 'A+'B; <J['x]> >- 'C['x] }
interactive unionContradiction2 {| elim []; nth_hyp |} 'H :
sequent { <H>; x: inr{'y} = inl{'z} in 'A+'B; <J['x]> >- 'C['x] }
doc docoff
(*
* H >- Ui ext A + B
* by unionFormation
* H >- Ui ext A
* H >- Ui ext B
*)
interactive unionFormation :
sequent { <H> >- univ[i:l] } -->
sequent { <H> >- univ[i:l] } -->
sequent { <H> >- univ[i:l] }
(************************************************************************
* PRIMITIVES *
************************************************************************)
let union_term = << 'A + 'B >>
let union_opname = opname_of_term union_term
let is_union_term = is_dep0_dep0_term union_opname
let dest_union = dest_dep0_dep0_term union_opname
let mk_union_term = mk_dep0_dep0_term union_opname
let inl_term = << inl{'x} >>
let inl_opname = opname_of_term inl_term
let is_inl_term = is_dep0_term inl_opname
let dest_inl = dest_dep0_term inl_opname
let mk_inl_term = mk_dep0_term inl_opname
let inr_term = << inr{'x} >>
let inr_opname = opname_of_term inr_term
let is_inr_term = is_dep0_term inr_opname
let dest_inr = dest_dep0_term inr_opname
let mk_inr_term = mk_dep0_term inr_opname
let decide_term = << decide{'x; y. 'a['y]; z. 'b['z]} >>
let decide_opname = opname_of_term decide_term
let is_decide_term = is_dep0_dep1_dep1_term decide_opname
let dest_decide = dest_dep0_dep1_dep1_term decide_opname
let mk_decide_term = mk_dep0_dep1_dep1_term decide_opname
(************************************************************************
* TYPE INFERENCE *
************************************************************************)
let resource typeinf += (union_term, infer_univ_dep0_dep0 dest_union)
let tr_var = Lm_symbol.add "T-r"
let tl_var = Lm_symbol.add "T-l"
* Type of inl .
* Type of inl.
*)
let inf_inl inf consts decls eqs opt_eqs defs t =
let a = dest_inl t in
let eqs', opt_eqs', defs', a' = inf consts decls eqs opt_eqs defs a in
let b = Typeinf.vnewname consts defs' tr_var in
eqs', opt_eqs', ((b,<<void>>)::defs') , mk_union_term a' (mk_var_term b)
let resource typeinf += (inl_term, inf_inl)
* Type of inr .
* Type of inr.
*)
let inf_inr inf consts decls eqs opt_eqs defs t =
let a = dest_inl t in
let eqs', opt_eqs', defs', a' = inf consts decls eqs opt_eqs defs a in
let b = Typeinf.vnewname consts defs' tl_var in
eqs', opt_eqs', ((b,<<void>>)::defs') , mk_union_term (mk_var_term b) a'
let resource typeinf += (inr_term, inf_inr)
(*
* Type of decide.
*)
let inf_decide inf consts decls eqs opt_eqs defs t =
let e, x, a, y, b = dest_decide t in
let eqs', opt_eqs', defs', e' = inf consts decls eqs opt_eqs defs e in
let consts = SymbolSet.add (SymbolSet.add consts x) y in
let l = Typeinf.vnewname consts defs' tl_var in
let l' = mk_var_term l in
let r = Typeinf.vnewname consts defs' tr_var in
let r' = mk_var_term r in
let eqs'', opt_eqs'', defs'', a' =
inf consts ((x, l')::decls)
(eqnlist_append_eqn eqs' e' (mk_union_term l' r')) opt_eqs'
((l,Itt_void.top_term)::(r,Itt_void.top_term)::defs') a
in
let eqs''', opt_eqs''', defs''', b' =
inf consts ((y, r')::decls) eqs'' opt_eqs'' defs'' b
in eqs''', ((a',b')::opt_eqs'''), defs''', a'
let resource typeinf += (decide_term, inf_decide)
(************************************************************************
* SUBTYPING *
************************************************************************)
* Subtyping of two union types .
* Subtyping of two union types.
*)
let resource sub +=
(DSubtype ([<< 'A1 + 'B1 >>, << 'A2 + 'B2 >>;
<< 'A1 >>, << 'A2 >>;
<< 'B1 >>, << 'B2 >>],
unionSubtype))
(*
* -*-
* Local Variables:
* End:
* -*-
*)
| null | https://raw.githubusercontent.com/jyh/metaprl/51ba0bbbf409ecb7f96f5abbeb91902fdec47a19/theories/itt/core/itt_union.ml | ocaml | ***********************************************************************
* TERMS *
***********************************************************************
***********************************************************************
* REWRITES *
***********************************************************************
***********************************************************************
* DISPLAY FORMS *
***********************************************************************
***********************************************************************
* RULES *
***********************************************************************
* Typehood.
* H >- Ui ext A + B
* by unionFormation
* H >- Ui ext A
* H >- Ui ext B
***********************************************************************
* PRIMITIVES *
***********************************************************************
***********************************************************************
* TYPE INFERENCE *
***********************************************************************
* Type of decide.
***********************************************************************
* SUBTYPING *
***********************************************************************
* -*-
* Local Variables:
* End:
* -*-
| doc <:doc<
@spelling{handedness}
@module[Itt_union]
The union type $T_1 + T_2$ defines a union space containing the
elements of both $T_1$ and $T_2$. The union is @emph{disjoint}: the
elements are @emph{tagged} with the @hrefterm[inl] and @hrefterm[inr]
tags as belonging to the ``left'' type $T_1$ or the ``right'' type
$T_2$.
The union type is the first primitive type that can have more than one
element. The tag makes the handedness of membership decidable, and
the union type $@unit + @unit$ contains two elements: <<inl{it}>> and
<<inr{it}>>. The @hrefmodule[Itt_bool] module uses this definition to
define the Boolean values, where @emph{false} is <<inl{it}>> and
@emph{true} is <<inr{it}>>.
@docoff
----------------------------------------------------------------
@begin[license]
This file is part of MetaPRL, a modular, higher order
logical framework that provides a logical programming
environment for OCaml and other languages.
See the file doc/htmlman/default.html or visit /
for more information.
Copyright (C) 1997-2006 MetaPRL Group, Cornell University and
California Institute of Technology
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
Author: Jason Hickey @email{}
Modified by: Aleksey Nogin @email{}
@end[license]
>>
doc <:doc< @parents >>
extends Itt_void
extends Itt_equal
extends Itt_struct
extends Itt_subtype
doc docoff
open Unify_mm
open Basic_tactics
open Itt_equal
open Itt_subtype
doc <:doc<
@terms
The @tt{union} type is the binary union of two types $A$ and $B$.
The elements are $@inl{a}$ for $a @in A$ and $@inr{b}$ for $b @in B$.
The @tt{decide} term @emph{decides} the handedness of the term $x @in A + B$.
>>
declare \union{'A; 'B}
declare inl{'x}
declare inr{'x}
declare decide{'x; y. 'a['y]; z. 'b['z]}
declare undefined
define unfold_outl: outl{'x} <--> decide{'x; y. 'y; z. undefined}
define unfold_outr: outr{'x} <--> decide{'x; y. undefined; z. 'z}
define unfold_out: out{'x} <--> decide{'x; y. 'y; z. 'z}
doc <:doc<
@rewrites
The following two rules define the computational behavior of the
@hrefterm[decide] term. There are two reductions, the @tt{reduceDecideInl}
rewrite describes reduction of @tt{decide} on the @hrefterm[inl] term,
and @tt{reduceDecideInr} describes reduction on the @hrefterm[inr] term.
The rewrites are added to the @hrefconv[reduceC] resource.
>>
prim_rw reduceDecideInl {| reduce |} : decide{inl{'x}; u. 'l['u]; v. 'r['v]} <--> 'l['x]
prim_rw reduceDecideInr {| reduce |} : decide{inr{'x}; u. 'l['u]; v. 'r['v]} <--> 'r['x]
interactive_rw reduce_outl_inl {| reduce |} : outl{inl{'x}} <--> 'x
interactive_rw reduce_outr_inr {| reduce |} : outr{inr{'x}} <--> 'x
interactive_rw reduce_out_inl {| reduce |} : out{inl{'x}} <--> 'x
interactive_rw reduce_out_inr {| reduce |} : out{inr{'x}} <--> 'x
doc docoff
prec prec_inl
prec prec_union
dform union_df : except_mode[src] :: parens :: "prec"[prec_union] :: \union{'A; 'B} =
slot{'A} " " `"+" " " slot{'B}
dform inl_df : except_mode[src] :: parens :: "prec"[prec_inl] :: inl{'a} =
`"inl" " " slot{'a}
dform inr_df : except_mode[src] :: parens :: "prec"[prec_inl] :: inr{'a} =
`"inr" " " slot{'a}
dform decide_df : except_mode[src] :: decide{'x; y. 'a; z. 'b} =
pushm[1] szone pushm[3] keyword["match"] " " slot{'x} " " keyword["with"] hspace
pushm[3] `"inl " 'y `" -> " slot{'a} popm popm hspace
`"| " pushm[3] `"inr " 'z `" -> " slot{'b} popm ezone popm
doc <:doc<
@rules
@modsubsection{Typehood and equality}
The equality of the @hrefterm[union] type is intensional; the
union $A + B$ is a type if both $A$ and $B$ are types.
>>
prim unionEquality {| intro [] |} :
[wf] sequent { <H> >- 'A1 = 'A2 in univ[i:l] } -->
[wf] sequent { <H> >- 'B1 = 'B2 in univ[i:l] } -->
sequent { <H> >- 'A1 + 'B1 = 'A2 + 'B2 in univ[i:l] } =
it
prim unionType {| intro [] |} :
[wf] sequent { <H> >- "type"{'A} } -->
[wf] sequent { <H> >- "type"{'B} } -->
sequent { <H> >- "type"{'A + 'B} } =
it
doc <:doc<
@modsubsection{Membership}
The following two rules define membership, $@inl{a} @in A + B$
if $a @in A$ and $@inr{b} @in A + B$ if $b @in B$. Both
$A$ and $B$ must be types.
>>
prim inlEquality {| intro [] |} :
[wf] sequent { <H> >- 'a1 = 'a2 in 'A } -->
[wf] sequent { <H> >- "type"{'B} } -->
sequent { <H> >- inl{'a1} = inl{'a2} in 'A + 'B } =
it
* H > - inr b1 = inr b2 in A + B
* by H > - b1 = b2 in B
* H > - A = A in Ui
* H >- inr b1 = inr b2 in A + B
* by inrEquality
* H >- b1 = b2 in B
* H >- A = A in Ui
*)
prim inrEquality {| intro [] |} :
[wf] sequent { <H> >- 'b1 = 'b2 in 'B } -->
[wf] sequent { <H> >- "type"{'A} } -->
sequent { <H> >- inr{'b1} = inr{'b2} in 'A + 'B } =
it
doc <:doc<
@modsubsection{Introduction}
The union type $A + B$ is true if both $A$ and $B$ are types,
and either 1) $A$ is provable, or 2) $B$ is provable. The following
two rules are added to the @hreftactic[dT] tactic. The application
uses the @hreftactic[selT] tactic to choose the handedness; the
@tt{inlFormation} rule is applied with the tactic @tt{selT 1 (dT 0)}
and the @tt{inrFormation} is applied with @tt{selT 2 (dT 0)}.
>>
interactive inlFormation {| intro [SelectOption 1] |} :
[main] sequent { <H> >- 'A } -->
[wf] sequent { <H> >- "type"{'B} } -->
sequent { <H> >- 'A + 'B }
* H > - A + B ext inl a
* by inrFormation
* H > - B
* H > - A = A in Ui
* H >- A + B ext inl a
* by inrFormation
* H >- B
* H >- A = A in Ui
*)
interactive inrFormation {| intro [SelectOption 2] |} :
[main] ('b : sequent { <H> >- 'B }) -->
[wf] sequent { <H> >- "type"{'A} } -->
sequent { <H> >- 'A + 'B }
doc <:doc<
@modsubsection{Elimination}
The handedness of the union membership is @emph{decidable}. The
elimination rule performs a case analysis in the assumption $x@colon A + B$;
the first for the @tt{inl} case, and the second for the @tt{inr}. The proof
extract term is the @tt{decide} combinator (which performs a decision
on element membership).
>>
prim unionElimination {| elim |} 'H :
[left] ('left['u] : sequent { <H>; u: 'A; <J[inl{'u}]> >- 'T[inl{'u}] }) -->
[right] ('right['v] : sequent { <H>; v: 'B; <J[inr{'v}]> >- 'T[inr{'v}] }) -->
sequent { <H>; x: 'A + 'B; <J['x]> >- 'T['x] } =
decide{'x; u. 'left['u]; v. 'right['v]}
doc <:doc<
@modsubsection{Combinator equality}
The @tt{decide} term equality is true if there is @emph{some} type
$A + B$ for which all the subterms are equal.
>>
prim decideEquality {| intro [] |} bind{z. 'T['z]} ('A + 'B) :
[wf] sequent { <H> >- 'e1 = 'e2 in 'A + 'B } -->
[wf] sequent { <H>; u: 'A; 'e1 = inl{'u} in 'A + 'B >- 'l1['u] = 'l2['u] in 'T[inl{'u}] } -->
[wf] sequent { <H>; v: 'B; 'e1 = inr{'v} in 'A + 'B >- 'r1['v] = 'r2['v] in 'T[inr{'v}] } -->
sequent { <H> >- decide{'e1; u1. 'l1['u1]; v1. 'r1['v1]} =
decide{'e2; u2. 'l2['u2]; v2. 'r2['v2]} in
'T['e1] } =
it
doc <:doc<
@modsubsection{Subtyping}
The union type $A_1 + A_2$ is a subtype of type $A_2 + B_2$ if
$A_1 @subseteq A_2$ and $B_1 @subseteq B_2$. This rule is added
to the @hrefresource[subtype_resource].
>>
interactive unionSubtype {| intro [] |} :
["subtype"] sequent { <H> >- 'A1 subtype 'A2 } -->
["subtype"] sequent { <H> >- 'B1 subtype 'B2 } -->
sequent { <H> >- 'A1 + 'B1 subtype 'A2 + 'B2 }
doc <:doc<
@modsubsection{Contradiction lemmas}
An @tt[inl] can not be equal to @tt[inr].
>>
interactive unionContradiction1 {| elim []; nth_hyp |} 'H :
sequent { <H>; x: inl{'y} = inr{'z} in 'A+'B; <J['x]> >- 'C['x] }
interactive unionContradiction2 {| elim []; nth_hyp |} 'H :
sequent { <H>; x: inr{'y} = inl{'z} in 'A+'B; <J['x]> >- 'C['x] }
doc docoff
interactive unionFormation :
sequent { <H> >- univ[i:l] } -->
sequent { <H> >- univ[i:l] } -->
sequent { <H> >- univ[i:l] }
let union_term = << 'A + 'B >>
let union_opname = opname_of_term union_term
let is_union_term = is_dep0_dep0_term union_opname
let dest_union = dest_dep0_dep0_term union_opname
let mk_union_term = mk_dep0_dep0_term union_opname
let inl_term = << inl{'x} >>
let inl_opname = opname_of_term inl_term
let is_inl_term = is_dep0_term inl_opname
let dest_inl = dest_dep0_term inl_opname
let mk_inl_term = mk_dep0_term inl_opname
let inr_term = << inr{'x} >>
let inr_opname = opname_of_term inr_term
let is_inr_term = is_dep0_term inr_opname
let dest_inr = dest_dep0_term inr_opname
let mk_inr_term = mk_dep0_term inr_opname
let decide_term = << decide{'x; y. 'a['y]; z. 'b['z]} >>
let decide_opname = opname_of_term decide_term
let is_decide_term = is_dep0_dep1_dep1_term decide_opname
let dest_decide = dest_dep0_dep1_dep1_term decide_opname
let mk_decide_term = mk_dep0_dep1_dep1_term decide_opname
let resource typeinf += (union_term, infer_univ_dep0_dep0 dest_union)
let tr_var = Lm_symbol.add "T-r"
let tl_var = Lm_symbol.add "T-l"
* Type of inl .
* Type of inl.
*)
let inf_inl inf consts decls eqs opt_eqs defs t =
let a = dest_inl t in
let eqs', opt_eqs', defs', a' = inf consts decls eqs opt_eqs defs a in
let b = Typeinf.vnewname consts defs' tr_var in
eqs', opt_eqs', ((b,<<void>>)::defs') , mk_union_term a' (mk_var_term b)
let resource typeinf += (inl_term, inf_inl)
* Type of inr .
* Type of inr.
*)
let inf_inr inf consts decls eqs opt_eqs defs t =
let a = dest_inl t in
let eqs', opt_eqs', defs', a' = inf consts decls eqs opt_eqs defs a in
let b = Typeinf.vnewname consts defs' tl_var in
eqs', opt_eqs', ((b,<<void>>)::defs') , mk_union_term (mk_var_term b) a'
let resource typeinf += (inr_term, inf_inr)
let inf_decide inf consts decls eqs opt_eqs defs t =
let e, x, a, y, b = dest_decide t in
let eqs', opt_eqs', defs', e' = inf consts decls eqs opt_eqs defs e in
let consts = SymbolSet.add (SymbolSet.add consts x) y in
let l = Typeinf.vnewname consts defs' tl_var in
let l' = mk_var_term l in
let r = Typeinf.vnewname consts defs' tr_var in
let r' = mk_var_term r in
let eqs'', opt_eqs'', defs'', a' =
inf consts ((x, l')::decls)
(eqnlist_append_eqn eqs' e' (mk_union_term l' r')) opt_eqs'
((l,Itt_void.top_term)::(r,Itt_void.top_term)::defs') a
in
let eqs''', opt_eqs''', defs''', b' =
inf consts ((y, r')::decls) eqs'' opt_eqs'' defs'' b
in eqs''', ((a',b')::opt_eqs'''), defs''', a'
let resource typeinf += (decide_term, inf_decide)
* Subtyping of two union types .
* Subtyping of two union types.
*)
let resource sub +=
(DSubtype ([<< 'A1 + 'B1 >>, << 'A2 + 'B2 >>;
<< 'A1 >>, << 'A2 >>;
<< 'B1 >>, << 'B2 >>],
unionSubtype))
|
557e3345dd3dca549ee305e614964aa7d55d7abfa9d71ea861e69edcdc6d8654 | s-expressionists/ctype | fpzero.lisp | (in-package #:ctype)
;;;; Floating point negative zeroes lead to an unfortunate special case in the
CL type system .
To review , if distinct negative zeroes exist , (= -0.0 0.0 ) is true , but
( eql -0.0 0.0 ) is false . This means that ( or ( eql 0.0 ) ( float ( 0.0 ) ) )
;;;; cannot be reduced into a range type (or disjunction of them, whatever),
because ( typep -0.0 ' ( or ( eql 0.0 ) ( float ( 0.0 ) ) ) ) is false whereas
( typep -0.0 ' ( float 0.0 ) ) is true .
To deal with this , we have an entirely separate ctype class , fpzero .
;;;; An fpzero ctype represents an (eql floating-point-zero) type specifier.
;;;; Since the problem is mostly in relating to ranges, the important methods
for these are in pairwise.lisp , except we do sometimes form ranges here
for ( or ( eql -0.0 ) ( eql 0.0 ) ) .
(defmethod ctypep (object (ctype fpzero))
(eql object (fpzero-zero object)))
(defmethod subctypep ((ct1 fpzero) (ct2 fpzero))
(values (eql (fpzero-zero ct1) (fpzero-zero ct2)) t))
(defmethod ctype= ((ct1 fpzero) (ct2 fpzero))
(values (eql (fpzero-zero ct1) (fpzero-zero ct2)) t))
(defmethod disjointp ((ct1 fpzero) (ct2 fpzero))
(values (not (eql (fpzero-zero ct1) (fpzero-zero ct2))) t))
(defmethod conjointp ((ct1 fpzero) (ct2 fpzero)) (values nil t))
(defmethod cofinitep ((ct fpzero)) (values nil t))
(defmethod conjoin/2 ((ct1 fpzero) (ct2 fpzero))
(if (eql (fpzero-zero ct1) (fpzero-zero ct2))
ct1
(bot)))
(defmethod disjoin/2 ((ct1 fpzero) (ct2 fpzero))
(let ((k1 (fpzero-kind ct1))
(z1 (fpzero-zero ct1)) (z2 (fpzero-zero ct2)))
(cond ((eql z1 z2) ct1)
( member -0.0 0.0 ): make a range
((eql z1 (- z2)) (range k1 z1 nil z1 nil))
(t nil))))
(defmethod subtract ((ct1 fpzero) (ct2 fpzero))
(if (eql (fpzero-zero ct1) (fpzero-zero ct2))
(bot)
ct1))
(defmethod unparse ((ct fpzero)) `(eql ,(fpzero-zero ct)))
| null | https://raw.githubusercontent.com/s-expressionists/ctype/2b13bc5a17fad0117b4a5860bade678ed6bf7c3c/fpzero.lisp | lisp | Floating point negative zeroes lead to an unfortunate special case in the
cannot be reduced into a range type (or disjunction of them, whatever),
An fpzero ctype represents an (eql floating-point-zero) type specifier.
Since the problem is mostly in relating to ranges, the important methods | (in-package #:ctype)
CL type system .
To review , if distinct negative zeroes exist , (= -0.0 0.0 ) is true , but
( eql -0.0 0.0 ) is false . This means that ( or ( eql 0.0 ) ( float ( 0.0 ) ) )
because ( typep -0.0 ' ( or ( eql 0.0 ) ( float ( 0.0 ) ) ) ) is false whereas
( typep -0.0 ' ( float 0.0 ) ) is true .
To deal with this , we have an entirely separate ctype class , fpzero .
for these are in pairwise.lisp , except we do sometimes form ranges here
for ( or ( eql -0.0 ) ( eql 0.0 ) ) .
(defmethod ctypep (object (ctype fpzero))
(eql object (fpzero-zero object)))
(defmethod subctypep ((ct1 fpzero) (ct2 fpzero))
(values (eql (fpzero-zero ct1) (fpzero-zero ct2)) t))
(defmethod ctype= ((ct1 fpzero) (ct2 fpzero))
(values (eql (fpzero-zero ct1) (fpzero-zero ct2)) t))
(defmethod disjointp ((ct1 fpzero) (ct2 fpzero))
(values (not (eql (fpzero-zero ct1) (fpzero-zero ct2))) t))
(defmethod conjointp ((ct1 fpzero) (ct2 fpzero)) (values nil t))
(defmethod cofinitep ((ct fpzero)) (values nil t))
(defmethod conjoin/2 ((ct1 fpzero) (ct2 fpzero))
(if (eql (fpzero-zero ct1) (fpzero-zero ct2))
ct1
(bot)))
(defmethod disjoin/2 ((ct1 fpzero) (ct2 fpzero))
(let ((k1 (fpzero-kind ct1))
(z1 (fpzero-zero ct1)) (z2 (fpzero-zero ct2)))
(cond ((eql z1 z2) ct1)
( member -0.0 0.0 ): make a range
((eql z1 (- z2)) (range k1 z1 nil z1 nil))
(t nil))))
(defmethod subtract ((ct1 fpzero) (ct2 fpzero))
(if (eql (fpzero-zero ct1) (fpzero-zero ct2))
(bot)
ct1))
(defmethod unparse ((ct fpzero)) `(eql ,(fpzero-zero ct)))
|
d41f40a5c3c6ace1265d28111624314fd0140392ecec683513d5b9336d60d4fe | haskell-servant/servant-elm | GenerateSpec.hs | # LANGUAGE DataKinds #
# LANGUAGE DeriveGeneric #
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TypeOperators #-}
module Main where
import Control.Monad (zipWithM_)
import qualified Data.Algorithm.Diff as Diff
import qualified Data.Algorithm.DiffOutput as Diff
import Data.Monoid ((<>))
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.IO as T
import Servant.API ((:>), Get, JSON)
import Servant.Elm
import Test.Hspec (Spec, describe, hspec, it)
import Test.HUnit (Assertion, assertEqual)
import Common (testApi)
import PolymorphicData (SomeRecord(..), PolymorphicData(..))
main :: IO ()
main = hspec spec
spec :: Test.Hspec.Spec
spec =
describe "encoding a simple api" $
do it "does it" $
do expected <-
mapM
(\(fpath,header) -> do
source <- T.readFile fpath
return (fpath, header, source))
[ ( "test/elm-sources/getOneSource.elm"
, "module GetOneSource exposing (..)\n\n" <>
"import Http\n" <>
"import Json.Decode exposing (..)\n" <>
"import Url.Builder\n\n\n"
)
, ( "test/elm-sources/postTwoSource.elm"
, "module PostTwoSource exposing (..)\n\n" <>
"import Http\n" <>
"import Json.Decode exposing (..)\n" <>
"import Json.Encode\n" <>
"import Url.Builder\n\n\n"
)
, ( "test/elm-sources/getBooksByIdSource.elm"
, "module GetBooksByIdSource exposing (..)\n\n" <>
"import Http\n" <>
"import Url.Builder\n" <>
"import Json.Decode\n" <>
"\n" <>
"type Book = Book\n" <>
"jsonDecBook : Json.Decode.Decoder Book\n" <>
"jsonDecBook = Debug.todo \"\"\n\n"
)
, ( "test/elm-sources/getBooksByTitleSource.elm"
, "module GetBooksByTitleSource exposing (..)\n\n" <>
"import Http\n" <>
"import Url.Builder\n" <>
"import Json.Decode as J\n\n" <>
"type alias Book = {}\n" <>
"jsonDecBook = J.succeed {}\n\n"
)
, ( "test/elm-sources/getBooksSource.elm"
, "module GetBooksSource exposing (..)\n\n" <>
"import Http\n" <>
"import Json.Decode exposing (..)\n" <>
"import Url.Builder\n" <>
"import Json.Decode as J\n\n" <>
"type alias Book = {}\n\n" <>
"jsonDecBook = J.succeed {}\n\n"
)
, ( "test/elm-sources/postBooksSource.elm"
, "module PostBooksSource exposing (..)\n\n" <>
"import Http\n" <>
"import Url.Builder\n" <>
"import Json.Encode as Enc\n\n" <>
"type alias Book = {}\n" <>
"jsonEncBook = \\b -> Enc.object []\n\n"
)
, ( "test/elm-sources/getNothingSource.elm"
, "module GetNothingSource exposing (..)\n\n" <>
"import Http\n" <>
"import Url.Builder\n\n\n"
)
, ( "test/elm-sources/putNothingSource.elm"
, "module PutNothingSource exposing (..)\n\n" <>
"import Http\n" <>
"import Url.Builder\n\n\n"
)
, ( "test/elm-sources/getWithaheaderSource.elm"
, "module GetWithAHeaderSource exposing (..)\n\n" <>
"import Http\n" <>
"import Url.Builder\n" <>
"import Json.Decode exposing (..)\n\n\n")
, ( "test/elm-sources/getWitharesponseheaderSource.elm"
, "module GetWithAResponseHeaderSource exposing (..)\n\n" <>
"import Http\n" <>
"import Url.Builder\n" <>
"import Json.Decode exposing (..)\n\n\n")]
let generated = filter (not . T.null) (generateElmForAPI testApi)
generated `itemsShouldBe` expected
it "with dynamic URLs" $
do expected <-
mapM
(\(fpath,header) -> do
source <- T.readFile fpath
return (fpath, header, source))
[ ( "test/elm-sources/getOneWithDynamicUrlSource.elm"
, "module GetOneWithDynamicUrlSource exposing (..)\n\n" <>
"import Http\n" <>
"import Url.Builder\n" <>
"import Json.Decode exposing (..)\n\n\n")]
let generated =
map
(<> "\n")
(generateElmForAPIWith
(defElmOptions
{ urlPrefix = Dynamic
})
(Proxy :: Proxy ("one" :> Get '[JSON] Int)))
generated `itemsShouldBe` expected
it "works with polymorphic data" $
do expected <-
mapM
(\(fpath, header) -> do
source <- T.readFile fpath
return (fpath, header, source))
[ ( "test/elm-sources/getPolymorphicData.elm"
, "module GetPolymorphicData exposing (..)\n\n" <>
"import Http\n" <>
"import Json.Decode exposing (..)\n" <>
"import Url.Builder\n\n" <>
"type PolymorphicData a b = PolymorphicData a b\n" <>
"type SomeRecord = SomeRecord { recordId : Int, recordname : String }\n\n" <>
"jsonDecPolymorphicData : Json.Decode.Decoder a -> Json.Decode.Decoder b -> Json.Decode.Decoder (PolymorphicData a b)\n"<>
"jsonDecPolymorphicData _ _ = Debug.todo \"finish\"\n\n" <>
"jsonDecSomeRecord : Json.Decode.Decoder SomeRecord\n"<>
"jsonDecSomeRecord = Debug.todo \"finish\"\n\n\n")]
let generated =
map
(<> "\n")
(generateElmForAPIWith
defElmOptions
(Proxy :: Proxy ( "polymorphicData" :> Get '[JSON] (PolymorphicData [String] SomeRecord))))
generated `itemsShouldBe` expected
itemsShouldBe :: [Text] -> [(String, Text, Text)] -> IO ()
itemsShouldBe actual expected =
zipWithM_
shouldBeDiff
(actual ++ replicate (length expected - length actual) mempty)
(expected ++ replicate (length actual - length expected) mempty)
shouldBeDiff :: Text -> (String, Text, Text) -> Assertion
shouldBeDiff a (fpath,header,b) =
assertEqual
("< generated\n" <> "> " <> fpath <> "\n" <>
Diff.ppDiff
(Diff.getGroupedDiff
(lines (T.unpack actual))
(lines (T.unpack expected))))
expected actual
where
actual = T.strip $ header <> a
expected = T.strip b
| null | https://raw.githubusercontent.com/haskell-servant/servant-elm/95c49abe536d8e468efb5a8a0cd750cf817295f4/test/GenerateSpec.hs | haskell | # LANGUAGE OverloadedStrings #
# LANGUAGE TypeOperators # | # LANGUAGE DataKinds #
# LANGUAGE DeriveGeneric #
module Main where
import Control.Monad (zipWithM_)
import qualified Data.Algorithm.Diff as Diff
import qualified Data.Algorithm.DiffOutput as Diff
import Data.Monoid ((<>))
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.IO as T
import Servant.API ((:>), Get, JSON)
import Servant.Elm
import Test.Hspec (Spec, describe, hspec, it)
import Test.HUnit (Assertion, assertEqual)
import Common (testApi)
import PolymorphicData (SomeRecord(..), PolymorphicData(..))
main :: IO ()
main = hspec spec
spec :: Test.Hspec.Spec
spec =
describe "encoding a simple api" $
do it "does it" $
do expected <-
mapM
(\(fpath,header) -> do
source <- T.readFile fpath
return (fpath, header, source))
[ ( "test/elm-sources/getOneSource.elm"
, "module GetOneSource exposing (..)\n\n" <>
"import Http\n" <>
"import Json.Decode exposing (..)\n" <>
"import Url.Builder\n\n\n"
)
, ( "test/elm-sources/postTwoSource.elm"
, "module PostTwoSource exposing (..)\n\n" <>
"import Http\n" <>
"import Json.Decode exposing (..)\n" <>
"import Json.Encode\n" <>
"import Url.Builder\n\n\n"
)
, ( "test/elm-sources/getBooksByIdSource.elm"
, "module GetBooksByIdSource exposing (..)\n\n" <>
"import Http\n" <>
"import Url.Builder\n" <>
"import Json.Decode\n" <>
"\n" <>
"type Book = Book\n" <>
"jsonDecBook : Json.Decode.Decoder Book\n" <>
"jsonDecBook = Debug.todo \"\"\n\n"
)
, ( "test/elm-sources/getBooksByTitleSource.elm"
, "module GetBooksByTitleSource exposing (..)\n\n" <>
"import Http\n" <>
"import Url.Builder\n" <>
"import Json.Decode as J\n\n" <>
"type alias Book = {}\n" <>
"jsonDecBook = J.succeed {}\n\n"
)
, ( "test/elm-sources/getBooksSource.elm"
, "module GetBooksSource exposing (..)\n\n" <>
"import Http\n" <>
"import Json.Decode exposing (..)\n" <>
"import Url.Builder\n" <>
"import Json.Decode as J\n\n" <>
"type alias Book = {}\n\n" <>
"jsonDecBook = J.succeed {}\n\n"
)
, ( "test/elm-sources/postBooksSource.elm"
, "module PostBooksSource exposing (..)\n\n" <>
"import Http\n" <>
"import Url.Builder\n" <>
"import Json.Encode as Enc\n\n" <>
"type alias Book = {}\n" <>
"jsonEncBook = \\b -> Enc.object []\n\n"
)
, ( "test/elm-sources/getNothingSource.elm"
, "module GetNothingSource exposing (..)\n\n" <>
"import Http\n" <>
"import Url.Builder\n\n\n"
)
, ( "test/elm-sources/putNothingSource.elm"
, "module PutNothingSource exposing (..)\n\n" <>
"import Http\n" <>
"import Url.Builder\n\n\n"
)
, ( "test/elm-sources/getWithaheaderSource.elm"
, "module GetWithAHeaderSource exposing (..)\n\n" <>
"import Http\n" <>
"import Url.Builder\n" <>
"import Json.Decode exposing (..)\n\n\n")
, ( "test/elm-sources/getWitharesponseheaderSource.elm"
, "module GetWithAResponseHeaderSource exposing (..)\n\n" <>
"import Http\n" <>
"import Url.Builder\n" <>
"import Json.Decode exposing (..)\n\n\n")]
let generated = filter (not . T.null) (generateElmForAPI testApi)
generated `itemsShouldBe` expected
it "with dynamic URLs" $
do expected <-
mapM
(\(fpath,header) -> do
source <- T.readFile fpath
return (fpath, header, source))
[ ( "test/elm-sources/getOneWithDynamicUrlSource.elm"
, "module GetOneWithDynamicUrlSource exposing (..)\n\n" <>
"import Http\n" <>
"import Url.Builder\n" <>
"import Json.Decode exposing (..)\n\n\n")]
let generated =
map
(<> "\n")
(generateElmForAPIWith
(defElmOptions
{ urlPrefix = Dynamic
})
(Proxy :: Proxy ("one" :> Get '[JSON] Int)))
generated `itemsShouldBe` expected
it "works with polymorphic data" $
do expected <-
mapM
(\(fpath, header) -> do
source <- T.readFile fpath
return (fpath, header, source))
[ ( "test/elm-sources/getPolymorphicData.elm"
, "module GetPolymorphicData exposing (..)\n\n" <>
"import Http\n" <>
"import Json.Decode exposing (..)\n" <>
"import Url.Builder\n\n" <>
"type PolymorphicData a b = PolymorphicData a b\n" <>
"type SomeRecord = SomeRecord { recordId : Int, recordname : String }\n\n" <>
"jsonDecPolymorphicData : Json.Decode.Decoder a -> Json.Decode.Decoder b -> Json.Decode.Decoder (PolymorphicData a b)\n"<>
"jsonDecPolymorphicData _ _ = Debug.todo \"finish\"\n\n" <>
"jsonDecSomeRecord : Json.Decode.Decoder SomeRecord\n"<>
"jsonDecSomeRecord = Debug.todo \"finish\"\n\n\n")]
let generated =
map
(<> "\n")
(generateElmForAPIWith
defElmOptions
(Proxy :: Proxy ( "polymorphicData" :> Get '[JSON] (PolymorphicData [String] SomeRecord))))
generated `itemsShouldBe` expected
itemsShouldBe :: [Text] -> [(String, Text, Text)] -> IO ()
itemsShouldBe actual expected =
zipWithM_
shouldBeDiff
(actual ++ replicate (length expected - length actual) mempty)
(expected ++ replicate (length actual - length expected) mempty)
shouldBeDiff :: Text -> (String, Text, Text) -> Assertion
shouldBeDiff a (fpath,header,b) =
assertEqual
("< generated\n" <> "> " <> fpath <> "\n" <>
Diff.ppDiff
(Diff.getGroupedDiff
(lines (T.unpack actual))
(lines (T.unpack expected))))
expected actual
where
actual = T.strip $ header <> a
expected = T.strip b
|
118a9fb844f1ef133034662669f8b1346c943057c542ced411ccd0b94f36a625 | ds-wizard/engine-backend | Detail_PUT.hs | module Wizard.Specs.API.Questionnaire.Detail_PUT (
detail_put,
) where
import Data.Aeson (encode)
import qualified Data.ByteString.Char8 as BS
import qualified Data.Map.Strict as M
import qualified Data.UUID as U
import Network.HTTP.Types
import Network.Wai (Application)
import Test.Hspec
import Test.Hspec.Wai hiding (shouldRespondWith)
import Test.Hspec.Wai.Matcher
import Shared.Api.Resource.Error.ErrorJM ()
import Shared.Database.Migration.Development.DocumentTemplate.Data.DocumentTemplateFormats
import Shared.Database.Migration.Development.DocumentTemplate.Data.DocumentTemplates
import Shared.Database.Migration.Development.KnowledgeModel.Data.KnowledgeModels
import Shared.Database.Migration.Development.Package.Data.Packages
import Shared.Localization.Messages.Public
import Shared.Model.Error.Error
import qualified Shared.Service.Package.PackageMapper as SPM
import Wizard.Api.Resource.Questionnaire.QuestionnaireChangeDTO
import Wizard.Api.Resource.Questionnaire.QuestionnaireDetailDTO
import Wizard.Database.DAO.Questionnaire.QuestionnaireDAO
import qualified Wizard.Database.Migration.Development.DocumentTemplate.DocumentTemplateMigration as TML
import Wizard.Database.Migration.Development.Questionnaire.Data.QuestionnaireComments
import Wizard.Database.Migration.Development.Questionnaire.Data.QuestionnaireReplies
import Wizard.Database.Migration.Development.Questionnaire.Data.QuestionnaireVersions
import Wizard.Database.Migration.Development.Questionnaire.Data.Questionnaires
import qualified Wizard.Database.Migration.Development.Questionnaire.QuestionnaireMigration as QTN
import qualified Wizard.Database.Migration.Development.User.UserMigration as U
import Wizard.Model.Context.AppContext
import Wizard.Model.Questionnaire.Questionnaire
import Wizard.Model.Questionnaire.QuestionnaireState
import Wizard.Service.Questionnaire.QuestionnaireMapper
import SharedTest.Specs.API.Common
import Wizard.Specs.API.Common
import Wizard.Specs.API.Questionnaire.Common
import Wizard.Specs.Common
-- ------------------------------------------------------------------------
-- PUT /questionnaires/{qtnUuid}
-- ------------------------------------------------------------------------
detail_put :: AppContext -> SpecWith ((), Application)
detail_put appContext =
describe "PUT /questionnaires/{qtnUuid}" $ do
test_200 appContext
test_400 appContext
test_401 appContext
test_403 appContext
test_404 appContext
-- ----------------------------------------------------
-- ----------------------------------------------------
-- ----------------------------------------------------
reqMethod = methodPut
reqUrlT qtnUuid = BS.pack $ "/questionnaires/" ++ U.toString qtnUuid
reqHeadersT authHeader = authHeader ++ [reqCtHeader]
reqDtoT qtn =
QuestionnaireChangeDTO
{ name = qtn.name
, description = qtn.description
, visibility = qtn.visibility
, sharing = qtn.sharing
, projectTags = qtn.projectTags
, permissions = qtn.permissions
, documentTemplateId = qtn.documentTemplateId
, formatUuid = qtn.formatUuid
, isTemplate = qtn.isTemplate
}
reqBodyT qtn = encode $ reqDtoT qtn
-- ----------------------------------------------------
-- ----------------------------------------------------
-- ----------------------------------------------------
test_200 appContext = do
create_test_200
"HTTP 200 OK (Owner, Private)"
appContext
questionnaire1
questionnaire1Edited
questionnaire1Ctn
[]
True
[reqAuthHeader]
False
create_test_200
"HTTP 200 OK (Owner, VisibleView)"
appContext
questionnaire2
questionnaire2Edited
questionnaire2Ctn
[]
False
[reqAuthHeader]
False
create_test_200
"HTTP 200 OK (Non-Owner, Private, Sharing, Anonymous Enabled)"
appContext
questionnaire10
questionnaire10Edited
questionnaire10Ctn
[qtn10NikolaEditPermRecordDto]
False
[reqNonAdminAuthHeader]
True
create_test_200 title appContext qtn qtnEdited qtnCtn permissions showComments authHeader anonymousEnabled =
it title $
-- GIVEN: Prepare request
do
let reqUrl = reqUrlT $ qtn.uuid
let reqHeaders = reqHeadersT authHeader
let reqBody = reqBodyT qtnEdited
-- AND: Prepare expectation
let expStatus = 200
let expHeaders = resCtHeaderPlain : resCorsHeadersPlain
let expDto =
toDetailWithPackageWithEventsDTO
qtnEdited
qtnCtn
(SPM.toPackage germanyPackage)
["1.0.0"]
km1WithQ4
QSDefault
(Just wizardDocumentTemplate)
(Just formatJson)
fReplies
( if showComments
then qtnThreadsDto
else M.empty
)
permissions
qVersionsDto
Nothing
let expType (a :: QuestionnaireDetailDTO) = a
-- AND: Run migrations
runInContextIO U.runMigration appContext
runInContextIO TML.runMigration appContext
runInContextIO QTN.runMigration appContext
runInContextIO (insertQuestionnaire questionnaire10) appContext
-- AND: Enabled anonymous sharing
updateAnonymousQuestionnaireSharing appContext anonymousEnabled
-- WHEN: Call API
response <- request reqMethod reqUrl reqHeaders reqBody
-- THEN: Compare response with expectation
assertResponseWithoutFields expStatus expHeaders expDto expType response ["updatedAt"]
-- AND: Find a result in DB
assertExistenceOfQuestionnaireInDB appContext qtnEdited
-- ----------------------------------------------------
-- ----------------------------------------------------
-- ----------------------------------------------------
test_400 appContext = createInvalidJsonTest reqMethod (reqUrlT questionnaire3.uuid) "visibility"
-- ----------------------------------------------------
-- ----------------------------------------------------
-- ----------------------------------------------------
test_401 appContext =
createAuthTest reqMethod (reqUrlT questionnaire3.uuid) [reqCtHeader] (reqBodyT questionnaire1)
-- ----------------------------------------------------
-- ----------------------------------------------------
-- ----------------------------------------------------
test_403 appContext = do
createNoPermissionTest
appContext
reqMethod
(reqUrlT questionnaire3.uuid)
[reqCtHeader]
(reqBodyT questionnaire1)
"QTN_PERM"
create_test_403
"HTTP 403 FORBIDDEN (Non-Owner, Private)"
appContext
questionnaire1
questionnaire1Edited
"View Questionnaire"
create_test_403
"HTTP 403 FORBIDDEN (Non-Owner, VisibleView)"
appContext
questionnaire2
questionnaire2Edited
"Administrate Questionnaire"
create_test_403
"HTTP 403 FORBIDDEN (Non-Owner, Private, Sharing, Anonymous Disabled)"
appContext
questionnaire10
questionnaire10Edited
"Administrate Questionnaire"
create_test_403 title appContext qtn qtnEdited reason =
it title $
-- GIVEN: Prepare request
do
let reqUrl = reqUrlT $ qtn.uuid
let reqHeaders = reqHeadersT [reqNonAdminAuthHeader]
let reqBody = reqBodyT qtnEdited
-- AND: Prepare expectation
let expStatus = 403
let expHeaders = resCtHeader : resCorsHeaders
let expDto = ForbiddenError $ _ERROR_VALIDATION__FORBIDDEN reason
let expBody = encode expDto
-- AND: Run migrations
runInContextIO U.runMigration appContext
runInContextIO TML.runMigration appContext
runInContextIO QTN.runMigration appContext
runInContextIO (insertQuestionnaire questionnaire10) appContext
-- WHEN: Call API
response <- request reqMethod reqUrl reqHeaders reqBody
-- THEN: Compare response with expectation
let responseMatcher =
ResponseMatcher {matchHeaders = expHeaders, matchStatus = expStatus, matchBody = bodyEquals expBody}
response `shouldRespondWith` responseMatcher
-- ----------------------------------------------------
-- ----------------------------------------------------
-- ----------------------------------------------------
test_404 appContext =
createNotFoundTest'
reqMethod
"/questionnaires/f08ead5f-746d-411b-aee6-77ea3d24016a"
(reqHeadersT [reqAuthHeader])
(reqBodyT questionnaire1)
"questionnaire"
[("uuid", "f08ead5f-746d-411b-aee6-77ea3d24016a")]
| null | https://raw.githubusercontent.com/ds-wizard/engine-backend/bcd95eef9e96d5d9d7c737671aa29119692e694c/engine-wizard/test/Wizard/Specs/API/Questionnaire/Detail_PUT.hs | haskell | ------------------------------------------------------------------------
PUT /questionnaires/{qtnUuid}
------------------------------------------------------------------------
----------------------------------------------------
----------------------------------------------------
----------------------------------------------------
----------------------------------------------------
----------------------------------------------------
----------------------------------------------------
GIVEN: Prepare request
AND: Prepare expectation
AND: Run migrations
AND: Enabled anonymous sharing
WHEN: Call API
THEN: Compare response with expectation
AND: Find a result in DB
----------------------------------------------------
----------------------------------------------------
----------------------------------------------------
----------------------------------------------------
----------------------------------------------------
----------------------------------------------------
----------------------------------------------------
----------------------------------------------------
----------------------------------------------------
GIVEN: Prepare request
AND: Prepare expectation
AND: Run migrations
WHEN: Call API
THEN: Compare response with expectation
----------------------------------------------------
----------------------------------------------------
---------------------------------------------------- | module Wizard.Specs.API.Questionnaire.Detail_PUT (
detail_put,
) where
import Data.Aeson (encode)
import qualified Data.ByteString.Char8 as BS
import qualified Data.Map.Strict as M
import qualified Data.UUID as U
import Network.HTTP.Types
import Network.Wai (Application)
import Test.Hspec
import Test.Hspec.Wai hiding (shouldRespondWith)
import Test.Hspec.Wai.Matcher
import Shared.Api.Resource.Error.ErrorJM ()
import Shared.Database.Migration.Development.DocumentTemplate.Data.DocumentTemplateFormats
import Shared.Database.Migration.Development.DocumentTemplate.Data.DocumentTemplates
import Shared.Database.Migration.Development.KnowledgeModel.Data.KnowledgeModels
import Shared.Database.Migration.Development.Package.Data.Packages
import Shared.Localization.Messages.Public
import Shared.Model.Error.Error
import qualified Shared.Service.Package.PackageMapper as SPM
import Wizard.Api.Resource.Questionnaire.QuestionnaireChangeDTO
import Wizard.Api.Resource.Questionnaire.QuestionnaireDetailDTO
import Wizard.Database.DAO.Questionnaire.QuestionnaireDAO
import qualified Wizard.Database.Migration.Development.DocumentTemplate.DocumentTemplateMigration as TML
import Wizard.Database.Migration.Development.Questionnaire.Data.QuestionnaireComments
import Wizard.Database.Migration.Development.Questionnaire.Data.QuestionnaireReplies
import Wizard.Database.Migration.Development.Questionnaire.Data.QuestionnaireVersions
import Wizard.Database.Migration.Development.Questionnaire.Data.Questionnaires
import qualified Wizard.Database.Migration.Development.Questionnaire.QuestionnaireMigration as QTN
import qualified Wizard.Database.Migration.Development.User.UserMigration as U
import Wizard.Model.Context.AppContext
import Wizard.Model.Questionnaire.Questionnaire
import Wizard.Model.Questionnaire.QuestionnaireState
import Wizard.Service.Questionnaire.QuestionnaireMapper
import SharedTest.Specs.API.Common
import Wizard.Specs.API.Common
import Wizard.Specs.API.Questionnaire.Common
import Wizard.Specs.Common
detail_put :: AppContext -> SpecWith ((), Application)
detail_put appContext =
describe "PUT /questionnaires/{qtnUuid}" $ do
test_200 appContext
test_400 appContext
test_401 appContext
test_403 appContext
test_404 appContext
reqMethod = methodPut
reqUrlT qtnUuid = BS.pack $ "/questionnaires/" ++ U.toString qtnUuid
reqHeadersT authHeader = authHeader ++ [reqCtHeader]
reqDtoT qtn =
QuestionnaireChangeDTO
{ name = qtn.name
, description = qtn.description
, visibility = qtn.visibility
, sharing = qtn.sharing
, projectTags = qtn.projectTags
, permissions = qtn.permissions
, documentTemplateId = qtn.documentTemplateId
, formatUuid = qtn.formatUuid
, isTemplate = qtn.isTemplate
}
reqBodyT qtn = encode $ reqDtoT qtn
test_200 appContext = do
create_test_200
"HTTP 200 OK (Owner, Private)"
appContext
questionnaire1
questionnaire1Edited
questionnaire1Ctn
[]
True
[reqAuthHeader]
False
create_test_200
"HTTP 200 OK (Owner, VisibleView)"
appContext
questionnaire2
questionnaire2Edited
questionnaire2Ctn
[]
False
[reqAuthHeader]
False
create_test_200
"HTTP 200 OK (Non-Owner, Private, Sharing, Anonymous Enabled)"
appContext
questionnaire10
questionnaire10Edited
questionnaire10Ctn
[qtn10NikolaEditPermRecordDto]
False
[reqNonAdminAuthHeader]
True
create_test_200 title appContext qtn qtnEdited qtnCtn permissions showComments authHeader anonymousEnabled =
it title $
do
let reqUrl = reqUrlT $ qtn.uuid
let reqHeaders = reqHeadersT authHeader
let reqBody = reqBodyT qtnEdited
let expStatus = 200
let expHeaders = resCtHeaderPlain : resCorsHeadersPlain
let expDto =
toDetailWithPackageWithEventsDTO
qtnEdited
qtnCtn
(SPM.toPackage germanyPackage)
["1.0.0"]
km1WithQ4
QSDefault
(Just wizardDocumentTemplate)
(Just formatJson)
fReplies
( if showComments
then qtnThreadsDto
else M.empty
)
permissions
qVersionsDto
Nothing
let expType (a :: QuestionnaireDetailDTO) = a
runInContextIO U.runMigration appContext
runInContextIO TML.runMigration appContext
runInContextIO QTN.runMigration appContext
runInContextIO (insertQuestionnaire questionnaire10) appContext
updateAnonymousQuestionnaireSharing appContext anonymousEnabled
response <- request reqMethod reqUrl reqHeaders reqBody
assertResponseWithoutFields expStatus expHeaders expDto expType response ["updatedAt"]
assertExistenceOfQuestionnaireInDB appContext qtnEdited
test_400 appContext = createInvalidJsonTest reqMethod (reqUrlT questionnaire3.uuid) "visibility"
test_401 appContext =
createAuthTest reqMethod (reqUrlT questionnaire3.uuid) [reqCtHeader] (reqBodyT questionnaire1)
test_403 appContext = do
createNoPermissionTest
appContext
reqMethod
(reqUrlT questionnaire3.uuid)
[reqCtHeader]
(reqBodyT questionnaire1)
"QTN_PERM"
create_test_403
"HTTP 403 FORBIDDEN (Non-Owner, Private)"
appContext
questionnaire1
questionnaire1Edited
"View Questionnaire"
create_test_403
"HTTP 403 FORBIDDEN (Non-Owner, VisibleView)"
appContext
questionnaire2
questionnaire2Edited
"Administrate Questionnaire"
create_test_403
"HTTP 403 FORBIDDEN (Non-Owner, Private, Sharing, Anonymous Disabled)"
appContext
questionnaire10
questionnaire10Edited
"Administrate Questionnaire"
create_test_403 title appContext qtn qtnEdited reason =
it title $
do
let reqUrl = reqUrlT $ qtn.uuid
let reqHeaders = reqHeadersT [reqNonAdminAuthHeader]
let reqBody = reqBodyT qtnEdited
let expStatus = 403
let expHeaders = resCtHeader : resCorsHeaders
let expDto = ForbiddenError $ _ERROR_VALIDATION__FORBIDDEN reason
let expBody = encode expDto
runInContextIO U.runMigration appContext
runInContextIO TML.runMigration appContext
runInContextIO QTN.runMigration appContext
runInContextIO (insertQuestionnaire questionnaire10) appContext
response <- request reqMethod reqUrl reqHeaders reqBody
let responseMatcher =
ResponseMatcher {matchHeaders = expHeaders, matchStatus = expStatus, matchBody = bodyEquals expBody}
response `shouldRespondWith` responseMatcher
test_404 appContext =
createNotFoundTest'
reqMethod
"/questionnaires/f08ead5f-746d-411b-aee6-77ea3d24016a"
(reqHeadersT [reqAuthHeader])
(reqBodyT questionnaire1)
"questionnaire"
[("uuid", "f08ead5f-746d-411b-aee6-77ea3d24016a")]
|
4efb619ab5edb13cc78393ed282a7344df426210065530d403686ef68fae7dd3 | brick-lang/kekka | id.ml | open Core
(* Types *)
(** Identifiers are unique compiler generated identities *)
type t = int
[@@deriving show, sexp]
let equal = Int.equal
let compare = Int.compare
(** A list of identifiers *)
type ids = t list
(** show quotes around the id *)
let rec pp fmt id =
Format.pp_print_string fmt @@ "\"" ^ (Int.to_string id) ^ "\""
(** create a fresh identifier *)
let create (i:int) : t = i
let create_from_id (id:t) : t = id + 1
(** Generate an 'Id' with a certain base name (which is ignored) :) *)
let generate base_name (id:t) = create id
(* dummy identifier *)
let nil : t = 0
let number (i:t) : int = i
module Map = Int.Map
module Set = Int.Set
| null | https://raw.githubusercontent.com/brick-lang/kekka/7ede659ffb49959b140e6ab0a72d38ff6c63311b/common/id.ml | ocaml | Types
* Identifiers are unique compiler generated identities
* A list of identifiers
* show quotes around the id
* create a fresh identifier
* Generate an 'Id' with a certain base name (which is ignored) :)
dummy identifier | open Core
type t = int
[@@deriving show, sexp]
let equal = Int.equal
let compare = Int.compare
type ids = t list
let rec pp fmt id =
Format.pp_print_string fmt @@ "\"" ^ (Int.to_string id) ^ "\""
let create (i:int) : t = i
let create_from_id (id:t) : t = id + 1
let generate base_name (id:t) = create id
let nil : t = 0
let number (i:t) : int = i
module Map = Int.Map
module Set = Int.Set
|
440fc2cf7bc41aa6d5679a9c3d966a81cabc7f1bd7f18b5505cbee2c27884a84 | cuplv/dai | loc_map.ml | open Dai.Import
open Tree_sitter_java
open Syntax
open Cfg
type loc_ctx = { entry : Loc.t; exit : Loc.t; ret : Loc.t; exc : Loc.t }
let pp_loc_ctx fs { entry; exit; ret; exc } =
Format.fprintf fs "{%a -> %a; ret=%a; exc=%a}" Loc.pp entry Loc.pp exit Loc.pp ret Loc.pp exc
type t = loc_ctx Int.Map.t Method_id.Map.t
let empty = Map.empty (module Method_id)
type 'a or_collision = [ `Ok of 'a | `Collision ]
let add method_id stmt loc_ctx lmap =
let stmt_hash = CST.sexp_of_statement stmt |> Sexp.hash in
match Method_id.Map.find lmap method_id with
| None ->
`Ok (Method_id.Map.add_exn lmap ~key:method_id ~data:(Int.Map.singleton stmt_hash loc_ctx))
| Some stmt_hash_map -> (
match Int.Map.add stmt_hash_map ~key:stmt_hash ~data:loc_ctx with
| `Duplicate -> `Collision
| `Ok data -> `Ok (Method_id.Map.set lmap ~key:method_id ~data))
let remove method_id stmt lmap =
let stmt_hash = CST.sexp_of_statement stmt |> Sexp.hash in
let method_lmap = Method_id.Map.find_exn lmap method_id |> flip Int.Map.remove stmt_hash in
Method_id.Map.set lmap ~key:method_id ~data:method_lmap
let remove_fn = Method_id.Map.remove
let remove_region method_id (region : Loc.Set.t) lmap =
let new_method_lmap =
Int.Map.filter (Method_id.Map.find_exn lmap method_id)
~f:(fun { entry; exit; ret = _; exc = _ } -> Loc.Set.(mem region entry && mem region exit))
in
Method_id.Map.set lmap ~key:method_id ~data:new_method_lmap
let get method_id stmt lmap =
let stmt_hash = CST.sexp_of_statement stmt |> Sexp.hash in
Method_id.Map.find_exn lmap method_id |> flip Int.Map.find_exn stmt_hash
let union l r =
Method_id.Map.merge l r ~f:(fun ~key:_ -> function
| `Both (x, y) ->
Int.Map.merge x y ~f:(fun ~key:_ -> function
| `Both _ -> failwith "collision" | `Left x | `Right x -> Some x)
|> Option.return
| `Left x -> Some x
| `Right y -> Some y)
let rebase_edges method_id ~old_src ~new_src loc_map =
let new_method_locs =
Int.Map.map (Method_id.Map.find_exn loc_map method_id) ~f:(fun { entry; exit; ret; exc } ->
if Loc.equal entry old_src then { entry = new_src; exit; ret; exc }
else { entry; exit; ret; exc })
in
Method_id.Map.set loc_map ~key:method_id ~data:new_method_locs
let pp =
let pp_inner = Map.pp Int.pp pp_loc_ctx in
Map.pp Method_id.pp pp_inner
| null | https://raw.githubusercontent.com/cuplv/dai/45d50ba49940c56b5a7337e759fc3070b0377132/src/frontend/loc_map.ml | ocaml | open Dai.Import
open Tree_sitter_java
open Syntax
open Cfg
type loc_ctx = { entry : Loc.t; exit : Loc.t; ret : Loc.t; exc : Loc.t }
let pp_loc_ctx fs { entry; exit; ret; exc } =
Format.fprintf fs "{%a -> %a; ret=%a; exc=%a}" Loc.pp entry Loc.pp exit Loc.pp ret Loc.pp exc
type t = loc_ctx Int.Map.t Method_id.Map.t
let empty = Map.empty (module Method_id)
type 'a or_collision = [ `Ok of 'a | `Collision ]
let add method_id stmt loc_ctx lmap =
let stmt_hash = CST.sexp_of_statement stmt |> Sexp.hash in
match Method_id.Map.find lmap method_id with
| None ->
`Ok (Method_id.Map.add_exn lmap ~key:method_id ~data:(Int.Map.singleton stmt_hash loc_ctx))
| Some stmt_hash_map -> (
match Int.Map.add stmt_hash_map ~key:stmt_hash ~data:loc_ctx with
| `Duplicate -> `Collision
| `Ok data -> `Ok (Method_id.Map.set lmap ~key:method_id ~data))
let remove method_id stmt lmap =
let stmt_hash = CST.sexp_of_statement stmt |> Sexp.hash in
let method_lmap = Method_id.Map.find_exn lmap method_id |> flip Int.Map.remove stmt_hash in
Method_id.Map.set lmap ~key:method_id ~data:method_lmap
let remove_fn = Method_id.Map.remove
let remove_region method_id (region : Loc.Set.t) lmap =
let new_method_lmap =
Int.Map.filter (Method_id.Map.find_exn lmap method_id)
~f:(fun { entry; exit; ret = _; exc = _ } -> Loc.Set.(mem region entry && mem region exit))
in
Method_id.Map.set lmap ~key:method_id ~data:new_method_lmap
let get method_id stmt lmap =
let stmt_hash = CST.sexp_of_statement stmt |> Sexp.hash in
Method_id.Map.find_exn lmap method_id |> flip Int.Map.find_exn stmt_hash
let union l r =
Method_id.Map.merge l r ~f:(fun ~key:_ -> function
| `Both (x, y) ->
Int.Map.merge x y ~f:(fun ~key:_ -> function
| `Both _ -> failwith "collision" | `Left x | `Right x -> Some x)
|> Option.return
| `Left x -> Some x
| `Right y -> Some y)
let rebase_edges method_id ~old_src ~new_src loc_map =
let new_method_locs =
Int.Map.map (Method_id.Map.find_exn loc_map method_id) ~f:(fun { entry; exit; ret; exc } ->
if Loc.equal entry old_src then { entry = new_src; exit; ret; exc }
else { entry; exit; ret; exc })
in
Method_id.Map.set loc_map ~key:method_id ~data:new_method_locs
let pp =
let pp_inner = Map.pp Int.pp pp_loc_ctx in
Map.pp Method_id.pp pp_inner
| |
87cf85b50c10cdaf9878f82c46f8d9c4f6960c1c05149bef928568107ce1ae71 | 8thlight/hyperion | types_spec.clj | (ns hyperion.sqlite.types-spec
(:require [speclj.core :refer :all]
[hyperion.api :refer [unpack pack]]
[hyperion.sqlite]))
(describe "sqlite types"
(context "boolean"
(it "unpacks true"
(should= true (unpack Boolean 1)))
(it "unpacks false"
(should= false (unpack Boolean 0)))
(it "unpacks nil"
(should-be-nil (unpack Boolean nil)))
(it "packs true"
(should= true (pack Boolean 1)))
(it "packs false"
(should= false (pack Boolean 0)))
(it "packs nil"
(should-be-nil (pack Boolean nil)))
)
(context "longs"
(it "packs to a long"
(should= (long 1) (pack Long (int 1)))
(should (instance? Long (pack Long (int 1)))))
(it "packs nil"
(should-be-nil (pack Long nil)))
(it "unpacks to a long"
(should= (long 1) (unpack Long (int 1)))
(should (instance? Long (unpack Long (int 1)))))
(it "unpacks nil"
(should-be-nil (unpack Long nil)))
)
)
| null | https://raw.githubusercontent.com/8thlight/hyperion/b1b8f60a5ef013da854e98319220b97920727865/sqlite/spec/hyperion/sqlite/types_spec.clj | clojure | (ns hyperion.sqlite.types-spec
(:require [speclj.core :refer :all]
[hyperion.api :refer [unpack pack]]
[hyperion.sqlite]))
(describe "sqlite types"
(context "boolean"
(it "unpacks true"
(should= true (unpack Boolean 1)))
(it "unpacks false"
(should= false (unpack Boolean 0)))
(it "unpacks nil"
(should-be-nil (unpack Boolean nil)))
(it "packs true"
(should= true (pack Boolean 1)))
(it "packs false"
(should= false (pack Boolean 0)))
(it "packs nil"
(should-be-nil (pack Boolean nil)))
)
(context "longs"
(it "packs to a long"
(should= (long 1) (pack Long (int 1)))
(should (instance? Long (pack Long (int 1)))))
(it "packs nil"
(should-be-nil (pack Long nil)))
(it "unpacks to a long"
(should= (long 1) (unpack Long (int 1)))
(should (instance? Long (unpack Long (int 1)))))
(it "unpacks nil"
(should-be-nil (unpack Long nil)))
)
)
| |
8e258781c4ff492de0e58715710e086db6bd7e3579da429e68476f7e0dd8e4bd | patrikja/AFPcourse | ParserFromStdLib.hs | # LANGUAGE GeneralizedNewtypeDeriving #
module ParserFromStdLib where
import Control.Monad
import qualified Control.Monad.State as CMS
newtype P s a = P {unP :: CMS.StateT [s] [] a}
deriving (Monad, MonadPlus, CMS.MonadState [s])
type ParseResult s a = [(a, [s])]
parse :: P s a -> [s] -> ParseResult s a
parse = CMS.runStateT . unP
symbol :: P s s
symbol = do (s:rest) <- CMS.get -- ^ Note that this will use fail in case of empty input
CMS.put rest
return s
When we are into using the standard monad combinators , we can just
as well admit that pfail and ( + + + ) are the standard methods mzero and
mplus from the MonadPlus class .
as well admit that pfail and (+++) are the standard methods mzero and
mplus from the MonadPlus class.
-}
pfail :: P s a
pfail = mzero
= fail " This string is ignored in the list monad "
(+++) :: P s a -> P s a -> P s a
(+++) = mplus
----------------
symbol : : P s s
symbol = do inp < - CMS.get
case inp of
[ ] - > pfail
( s : ss ) - > do CMS.put ss
return s
symbol :: P s s
symbol = do inp <- CMS.get
case inp of
[] -> pfail
(s:ss) -> do CMS.put ss
return s
-}
| null | https://raw.githubusercontent.com/patrikja/AFPcourse/1a079ae80ba2dbb36f3f79f0fc96a502c0f670b6/L4/src/ParserFromStdLib.hs | haskell | ^ Note that this will use fail in case of empty input
-------------- | # LANGUAGE GeneralizedNewtypeDeriving #
module ParserFromStdLib where
import Control.Monad
import qualified Control.Monad.State as CMS
newtype P s a = P {unP :: CMS.StateT [s] [] a}
deriving (Monad, MonadPlus, CMS.MonadState [s])
type ParseResult s a = [(a, [s])]
parse :: P s a -> [s] -> ParseResult s a
parse = CMS.runStateT . unP
symbol :: P s s
CMS.put rest
return s
When we are into using the standard monad combinators , we can just
as well admit that pfail and ( + + + ) are the standard methods mzero and
mplus from the MonadPlus class .
as well admit that pfail and (+++) are the standard methods mzero and
mplus from the MonadPlus class.
-}
pfail :: P s a
pfail = mzero
= fail " This string is ignored in the list monad "
(+++) :: P s a -> P s a -> P s a
(+++) = mplus
symbol : : P s s
symbol = do inp < - CMS.get
case inp of
[ ] - > pfail
( s : ss ) - > do CMS.put ss
return s
symbol :: P s s
symbol = do inp <- CMS.get
case inp of
[] -> pfail
(s:ss) -> do CMS.put ss
return s
-}
|
d825464cb0ab82cfc8797f7467614825bbde47cd117a53dd82f6a12209c70571 | egison/sweet-egison | perm2.hs | import Control.Egison
import Criterion.Main
perm2 :: Int -> [(Int, Int)]
perm2 n =
matchAll dfs [1 .. n] (Multiset Something) [[mc| $x : $y : _ -> (x, y) |]]
perm2Native :: Int -> [(Int, Int)]
perm2Native n = go [1 .. n] [] []
where
go [] _ acc = acc
go (x : xs) rest acc =
[ (x, y) | y <- rest ++ xs ] ++ go xs (rest ++ [x]) acc
main :: IO ()
main = defaultMain
[ bgroup
"perm2"
[ bgroup
"1600"
[ bench "native" $ nf perm2Native 1600
, bench "sweet-egison" $ nf perm2 1600
]
, bgroup
"3200"
[ bench "native" $ nf perm2Native 3200
, bench "sweet-egison" $ nf perm2 3200
]
, bgroup
"6400"
[ bench "native" $ nf perm2Native 6400
, bench "sweet-egison" $ nf perm2 6400
]
]
]
| null | https://raw.githubusercontent.com/egison/sweet-egison/fd3b392f9a2993bbc59d541b61f6641c7d193d6e/benchmark/perm2.hs | haskell | import Control.Egison
import Criterion.Main
perm2 :: Int -> [(Int, Int)]
perm2 n =
matchAll dfs [1 .. n] (Multiset Something) [[mc| $x : $y : _ -> (x, y) |]]
perm2Native :: Int -> [(Int, Int)]
perm2Native n = go [1 .. n] [] []
where
go [] _ acc = acc
go (x : xs) rest acc =
[ (x, y) | y <- rest ++ xs ] ++ go xs (rest ++ [x]) acc
main :: IO ()
main = defaultMain
[ bgroup
"perm2"
[ bgroup
"1600"
[ bench "native" $ nf perm2Native 1600
, bench "sweet-egison" $ nf perm2 1600
]
, bgroup
"3200"
[ bench "native" $ nf perm2Native 3200
, bench "sweet-egison" $ nf perm2 3200
]
, bgroup
"6400"
[ bench "native" $ nf perm2Native 6400
, bench "sweet-egison" $ nf perm2 6400
]
]
]
| |
7e7420a627f6a11159dda5e661665740b1275d7f6f1fc7c5c471ac752ede6e51 | johnmn3/perc | data_readers.cljc | {% perc.core/%
%1 perc.core/%1
%> perc.core/%>
%% perc.core/%%
%%1 perc.core/%%1
%%> perc.core/%%>
%%% perc.core/%%%
%%%1 perc.core/%%%1
%%%> perc.core/%%%>}
| null | https://raw.githubusercontent.com/johnmn3/perc/5f60211132fc40ea9c6a4ebe1bdd4e67d58b390a/src/data_readers.cljc | clojure | {% perc.core/%
%1 perc.core/%1
%> perc.core/%>
%% perc.core/%%
%%1 perc.core/%%1
%%> perc.core/%%>
%%% perc.core/%%%
%%%1 perc.core/%%%1
%%%> perc.core/%%%>}
| |
cee92a948c422fea8073fa2a1e58d9702fbb49ca00c0f21cef507f19bf7cb3be | fyquah/hardcaml_zprize | approx_msb_multiplier.ml | open Base
open Hardcaml
open Signal
open Reg_with_enable
module Config = struct
module Level = struct
type t =
{ k : int -> int
; for_karatsuba : Karatsuba_ofman_mult.Config.Level.t
}
end
type t =
{ levels : Level.t list
; ground_multiplier : Ground_multiplier.Config.t
}
let latency { levels; ground_multiplier } =
match levels with
| [] -> Ground_multiplier.Config.latency ground_multiplier
| { for_karatsuba =
{ radix = _; pre_adder_stages = _; middle_adder_stages = _; post_adder_stages }
; k = _
}
:: tl ->
let slowest_multiplier =
List.map tl ~f:(fun x -> x.for_karatsuba)
|> Karatsuba_ofman_mult.Config.generate ~ground_multiplier
|> Karatsuba_ofman_mult.Config.latency
in
slowest_multiplier + post_adder_stages
;;
end
module Input = Multiplier_input
let split2 ~k x = drop_bottom x k, sel_bottom x k
let split3 ~k x = drop_bottom x (2 * k), sel_bottom (drop_bottom x k) k, sel_bottom x k
let rec create_recursive
~scope
~clock
~enable
~ground_multiplier
~(levels : Config.Level.t list)
(input : Input.t)
=
match levels with
| [] ->
let a, b =
match input with
| Multiply_by_constant _ -> assert false
| Multiply (a, b) -> a, b
| Square a -> a, a
in
With_shift.no_shift
(Ground_multiplier.create ~clock ~enable ~config:ground_multiplier a b)
| level :: remaining_levels ->
create_level
~scope
~clock
~enable
~ground_multiplier
~remaining_levels
~level
(input : Input.t)
and create_level
~scope
~clock
~enable
~ground_multiplier
~remaining_levels
~level:
{ Config.Level.for_karatsuba =
{ radix; middle_adder_stages = _; pre_adder_stages = _; post_adder_stages }
; k = calc_k
}
(input : Input.t)
=
let spec = Reg_spec.create ~clock () in
let pipeline ~n x = if is_const x then x else pipeline ~enable spec x ~n in
let child_karatsuba_config =
Karatsuba_ofman_mult.Config.generate
~ground_multiplier
(List.map remaining_levels ~f:(fun l -> l.for_karatsuba))
in
let create_recursive input =
let n =
Karatsuba_ofman_mult.Config.latency child_karatsuba_config
- Config.latency { levels = remaining_levels; ground_multiplier }
in
create_recursive
~scope
~clock
~enable
~levels:remaining_levels
~ground_multiplier
input
|> With_shift.map ~f:(pipeline ~n)
in
let create_full_multiplier a b =
assert (Signal.width a = Signal.width b);
match child_karatsuba_config with
| Ground_multiplier config -> Ground_multiplier.create ~clock ~enable ~config a b
| Karatsubsa_ofman_stage _ ->
Karatsuba_ofman_mult.hierarchical
~scope
~config:child_karatsuba_config
~enable
~clock
a
(match b with
| Const { signal_id = _; constant } ->
`Constant (Bits.to_z ~signedness:Unsigned constant)
| _ -> `Signal b)
in
let w = Multiplier_input.width input in
let w2 = w * 2 in
let k = calc_k w in
let pipe_add ~stages items = With_shift.pipe_add ~scope ~enable ~clock ~stages items in
match radix with
| Radix.Radix_2 ->
( ( ta * 2^hw ) + ba ) * ( ( tb * 2^hw ) + bb )
* = ( ( ua * ub ) * 2^(2 * hw ) ) + ( ( ( ua * lb ) + ( ub * la ) ) * 2^hw ) + ( la * lb )
*
* The upper - halve is zero in a part - width hader , reduces to the following
* approximation
*
* ( ( ua * ub ) * 2^(2 * hw ) ) + ( ( ( ua * lb ) + ( ub * la ) ) * 2^hw )
*
* See approx_msb_multiplier_model.ml for information about what the
* maximum error this can produce .
* = ((ua * ub) * 2^(2 * hw)) + (((ua * lb) + (ub * la)) * 2^hw) + (la * lb)
*
* The upper-halve is zero in a part-width hader, reduces to the following
* approximation
*
* ((ua * ub) * 2^(2 * hw)) + (((ua * lb) + (ub * la)) * 2^hw)
*
* See approx_msb_multiplier_model.ml for information about what the
* maximum error this can produce.
*)
(match input with
| Multiply_by_constant _ -> assert false
| Multiply (a, b) ->
let ua, la = split2 ~k a in
let ub, lb = split2 ~k b in
let wu = width ua in
let ua_mult_lb = create_recursive (Multiply (ua, uresize lb wu)) in
let ub_mult_la = create_recursive (Multiply (ub, uresize la wu)) in
let ua_mult_ub = create_full_multiplier ua ub in
let result =
pipe_add
~stages:post_adder_stages
[ With_shift.uresize ua_mult_lb (w2 - k)
; With_shift.uresize ub_mult_la (w2 - k)
; With_shift.uresize (With_shift.create ~shift:k ua_mult_ub) (w2 - k)
]
|> With_shift.sll ~by:k
in
assert (With_shift.width result = w * 2);
result
| Square _ -> raise_s [%message "Approx MSB squaring specialization not implemented"])
| Radix_3 ->
(match input with
| Multiply_by_constant _ -> assert false
| Multiply (x, y) ->
See comments in approx_msb_multiplier_model.ml for why this works . It 's
* similar to the idea in half_width_multiplier.ml
* similar to the idea in half_width_multiplier.ml
*)
let k2 = k * 2 in
let k3 = k * 3 in
let k4 = k * 4 in
let x2, x1, x0 = split3 ~k x in
let y2, y1, y0 = split3 ~k y in
let wx2 = width x2 in
assert (width x1 = k);
assert (width x0 = k);
assert (width y2 = wx2);
assert (width y1 = k);
assert (width y0 = k);
assert (wx2 >= k);
assert (wx2 + k + k = w);
let x2y2 = create_full_multiplier (uresize x2 wx2) (uresize y2 wx2) in
let x2y1 = create_full_multiplier (uresize x2 wx2) (uresize y1 wx2) in
let x1y2 = create_full_multiplier (uresize x1 wx2) (uresize y2 wx2) in
let x2y0 = create_recursive (Multiply (uresize x2 wx2, uresize y0 wx2)) in
let x1y1 =
CR - someday : The upcast to wx2 is strictly not necessary .
* But we 're keeping it for now due to empirical better DSP usage ( at
* the cost of some LUTs ) . This is likely due to vivado offloading some
* multiplications to LUTs when there are more zeros ( due to the
* uresize ) . Revisit this when we implement custom logic to implement
* constant multiplication specially .
* But we're keeping it for now due to empirical better DSP usage (at
* the cost of some LUTs). This is likely due to vivado offloading some
* multiplications to LUTs when there are more zeros (due to the
* uresize). Revisit this when we implement custom logic to implement
* constant multiplication specially.
*)
create_recursive (Multiply (uresize x1 wx2, uresize y1 wx2))
in
let x0y2 = create_recursive (Multiply (uresize x0 wx2, uresize y2 wx2)) in
let result =
pipe_add
~stages:post_adder_stages
[ With_shift.create x2y2 ~shift:(k4 - k2)
; With_shift.uresize (With_shift.create x2y1 ~shift:(k3 - k2)) (w2 - k2)
; With_shift.uresize (With_shift.create x1y2 ~shift:(k3 - k2)) (w2 - k2)
; With_shift.uresize x2y0 ((w * 2) - k2)
; With_shift.uresize x1y1 ((w * 2) - k2)
; With_shift.uresize x0y2 ((w * 2) - k2)
]
in
With_shift.sll result ~by:k2
| Square _ ->
raise_s [%message "Radix-3 not implemented in approx msb multiplication."])
;;
let create_with_config
~config:{ Config.levels; ground_multiplier }
~scope
~clock
~enable
input
=
create_recursive ~levels ~ground_multiplier ~scope ~clock ~enable input
;;
module type Width = sig
val bits : int
end
module With_interface_multiply (M : Width) = struct
include M
module I = struct
type 'a t =
{ clock : 'a
; enable : 'a
; x : 'a [@bits bits]
; y : 'a [@bits bits]
; in_valid : 'a
}
[@@deriving sexp_of, hardcaml]
end
module O = struct
type 'a t =
{ z : 'a [@bits 2 * bits]
; out_valid : 'a
}
[@@deriving sexp_of, hardcaml]
end
let create ~config scope { I.clock; enable; x; y; in_valid } =
let spec = Reg_spec.create ~clock () in
let z =
create_with_config ~config ~scope ~clock ~enable (Multiply (x, y))
|> With_shift.to_signal
in
let out_valid = pipeline spec ~enable ~n:(Config.latency config) in_valid in
assert (width z = bits);
{ O.z; out_valid }
;;
let hierarchical ~name ~config scope i =
let module H = Hierarchy.In_scope (I) (O) in
let { O.z; out_valid = _ } = H.hierarchical ~scope ~name (create ~config) i in
z
;;
end
module Interface_1arg (M : Width) = struct
include M
module I = struct
type 'a t =
{ clock : 'a
; enable : 'a
; x : 'a [@bits bits]
; in_valid : 'a
}
[@@deriving sexp_of, hardcaml]
end
module O = struct
type 'a t =
{ y : 'a [@bits 2 * bits]
; out_valid : 'a
}
[@@deriving sexp_of, hardcaml]
end
end
module With_interface_multiply_by_constant (M : Width) = struct
include Interface_1arg (M)
let create ~config ~multiply_by scope { I.clock; enable; x; in_valid } =
let spec = Reg_spec.create ~clock () in
let y =
Multiply (x, Signal.of_constant (Bits.to_constant multiply_by))
|> create_with_config ~scope ~clock ~enable ~config
|> With_shift.to_signal
in
let out_valid = pipeline spec ~enable ~n:(Config.latency config) in_valid in
assert (width y = bits * 2);
{ O.y; out_valid }
;;
let hierarchical ~name ~config ~multiply_by scope i =
let module H = Hierarchy.In_scope (I) (O) in
let { O.y; out_valid = _ } =
H.hierarchical ~scope ~name (create ~multiply_by ~config) i
in
y
;;
end
module With_interface_square (M : Width) = struct
include Interface_1arg (M)
let create
~config:{ Config.levels; ground_multiplier }
scope
{ I.clock; enable; x; in_valid }
=
let spec = Reg_spec.create ~clock () in
let y =
create_recursive ~scope ~clock ~enable ~levels ~ground_multiplier (Square x)
|> With_shift.to_signal
in
let out_valid =
pipeline spec ~enable ~n:(Config.latency { levels; ground_multiplier }) in_valid
in
assert (width y = 2 * bits);
{ O.y; out_valid }
;;
let hierarchical ~name ~config scope i =
let module H = Hierarchy.In_scope (I) (O) in
let { O.y; out_valid = _ } = H.hierarchical ~scope ~name (create ~config) i in
y
;;
end
let hierarchical ?name ~config ~clock ~enable ~scope (input : Multiplier_input.t) =
let bits = Multiplier_input.width input in
let module Width = struct
let bits = bits
end
in
match input with
| Multiply (x, y) ->
let module M = With_interface_multiply (Width) in
let name =
Option.value ~default:(Printf.sprintf "approx_msb_multiply_%d" bits) name
in
M.hierarchical ~name ~config scope { clock; enable; x; y; in_valid = vdd }
| Multiply_by_constant (x, multiply_by) ->
let module M = With_interface_multiply_by_constant (Width) in
let name =
Option.value ~default:(Printf.sprintf "approx_msb_multiply_by_cst_%d" bits) name
in
M.hierarchical ~name ~config ~multiply_by scope { clock; enable; x; in_valid = vdd }
| Square x ->
let module M = With_interface_square (Width) in
let name =
Option.value ~default:(Printf.sprintf "approx_msb_width_square_%d" bits) name
in
M.hierarchical ~name ~config scope { clock; enable; x; in_valid = vdd }
;;
| null | https://raw.githubusercontent.com/fyquah/hardcaml_zprize/553b1be10ae9b977decbca850df6ee2d0595e7ff/libs/field_ops/src/approx_msb_multiplier.ml | ocaml | open Base
open Hardcaml
open Signal
open Reg_with_enable
module Config = struct
module Level = struct
type t =
{ k : int -> int
; for_karatsuba : Karatsuba_ofman_mult.Config.Level.t
}
end
type t =
{ levels : Level.t list
; ground_multiplier : Ground_multiplier.Config.t
}
let latency { levels; ground_multiplier } =
match levels with
| [] -> Ground_multiplier.Config.latency ground_multiplier
| { for_karatsuba =
{ radix = _; pre_adder_stages = _; middle_adder_stages = _; post_adder_stages }
; k = _
}
:: tl ->
let slowest_multiplier =
List.map tl ~f:(fun x -> x.for_karatsuba)
|> Karatsuba_ofman_mult.Config.generate ~ground_multiplier
|> Karatsuba_ofman_mult.Config.latency
in
slowest_multiplier + post_adder_stages
;;
end
module Input = Multiplier_input
let split2 ~k x = drop_bottom x k, sel_bottom x k
let split3 ~k x = drop_bottom x (2 * k), sel_bottom (drop_bottom x k) k, sel_bottom x k
let rec create_recursive
~scope
~clock
~enable
~ground_multiplier
~(levels : Config.Level.t list)
(input : Input.t)
=
match levels with
| [] ->
let a, b =
match input with
| Multiply_by_constant _ -> assert false
| Multiply (a, b) -> a, b
| Square a -> a, a
in
With_shift.no_shift
(Ground_multiplier.create ~clock ~enable ~config:ground_multiplier a b)
| level :: remaining_levels ->
create_level
~scope
~clock
~enable
~ground_multiplier
~remaining_levels
~level
(input : Input.t)
and create_level
~scope
~clock
~enable
~ground_multiplier
~remaining_levels
~level:
{ Config.Level.for_karatsuba =
{ radix; middle_adder_stages = _; pre_adder_stages = _; post_adder_stages }
; k = calc_k
}
(input : Input.t)
=
let spec = Reg_spec.create ~clock () in
let pipeline ~n x = if is_const x then x else pipeline ~enable spec x ~n in
let child_karatsuba_config =
Karatsuba_ofman_mult.Config.generate
~ground_multiplier
(List.map remaining_levels ~f:(fun l -> l.for_karatsuba))
in
let create_recursive input =
let n =
Karatsuba_ofman_mult.Config.latency child_karatsuba_config
- Config.latency { levels = remaining_levels; ground_multiplier }
in
create_recursive
~scope
~clock
~enable
~levels:remaining_levels
~ground_multiplier
input
|> With_shift.map ~f:(pipeline ~n)
in
let create_full_multiplier a b =
assert (Signal.width a = Signal.width b);
match child_karatsuba_config with
| Ground_multiplier config -> Ground_multiplier.create ~clock ~enable ~config a b
| Karatsubsa_ofman_stage _ ->
Karatsuba_ofman_mult.hierarchical
~scope
~config:child_karatsuba_config
~enable
~clock
a
(match b with
| Const { signal_id = _; constant } ->
`Constant (Bits.to_z ~signedness:Unsigned constant)
| _ -> `Signal b)
in
let w = Multiplier_input.width input in
let w2 = w * 2 in
let k = calc_k w in
let pipe_add ~stages items = With_shift.pipe_add ~scope ~enable ~clock ~stages items in
match radix with
| Radix.Radix_2 ->
( ( ta * 2^hw ) + ba ) * ( ( tb * 2^hw ) + bb )
* = ( ( ua * ub ) * 2^(2 * hw ) ) + ( ( ( ua * lb ) + ( ub * la ) ) * 2^hw ) + ( la * lb )
*
* The upper - halve is zero in a part - width hader , reduces to the following
* approximation
*
* ( ( ua * ub ) * 2^(2 * hw ) ) + ( ( ( ua * lb ) + ( ub * la ) ) * 2^hw )
*
* See approx_msb_multiplier_model.ml for information about what the
* maximum error this can produce .
* = ((ua * ub) * 2^(2 * hw)) + (((ua * lb) + (ub * la)) * 2^hw) + (la * lb)
*
* The upper-halve is zero in a part-width hader, reduces to the following
* approximation
*
* ((ua * ub) * 2^(2 * hw)) + (((ua * lb) + (ub * la)) * 2^hw)
*
* See approx_msb_multiplier_model.ml for information about what the
* maximum error this can produce.
*)
(match input with
| Multiply_by_constant _ -> assert false
| Multiply (a, b) ->
let ua, la = split2 ~k a in
let ub, lb = split2 ~k b in
let wu = width ua in
let ua_mult_lb = create_recursive (Multiply (ua, uresize lb wu)) in
let ub_mult_la = create_recursive (Multiply (ub, uresize la wu)) in
let ua_mult_ub = create_full_multiplier ua ub in
let result =
pipe_add
~stages:post_adder_stages
[ With_shift.uresize ua_mult_lb (w2 - k)
; With_shift.uresize ub_mult_la (w2 - k)
; With_shift.uresize (With_shift.create ~shift:k ua_mult_ub) (w2 - k)
]
|> With_shift.sll ~by:k
in
assert (With_shift.width result = w * 2);
result
| Square _ -> raise_s [%message "Approx MSB squaring specialization not implemented"])
| Radix_3 ->
(match input with
| Multiply_by_constant _ -> assert false
| Multiply (x, y) ->
See comments in approx_msb_multiplier_model.ml for why this works . It 's
* similar to the idea in half_width_multiplier.ml
* similar to the idea in half_width_multiplier.ml
*)
let k2 = k * 2 in
let k3 = k * 3 in
let k4 = k * 4 in
let x2, x1, x0 = split3 ~k x in
let y2, y1, y0 = split3 ~k y in
let wx2 = width x2 in
assert (width x1 = k);
assert (width x0 = k);
assert (width y2 = wx2);
assert (width y1 = k);
assert (width y0 = k);
assert (wx2 >= k);
assert (wx2 + k + k = w);
let x2y2 = create_full_multiplier (uresize x2 wx2) (uresize y2 wx2) in
let x2y1 = create_full_multiplier (uresize x2 wx2) (uresize y1 wx2) in
let x1y2 = create_full_multiplier (uresize x1 wx2) (uresize y2 wx2) in
let x2y0 = create_recursive (Multiply (uresize x2 wx2, uresize y0 wx2)) in
let x1y1 =
CR - someday : The upcast to wx2 is strictly not necessary .
* But we 're keeping it for now due to empirical better DSP usage ( at
* the cost of some LUTs ) . This is likely due to vivado offloading some
* multiplications to LUTs when there are more zeros ( due to the
* uresize ) . Revisit this when we implement custom logic to implement
* constant multiplication specially .
* But we're keeping it for now due to empirical better DSP usage (at
* the cost of some LUTs). This is likely due to vivado offloading some
* multiplications to LUTs when there are more zeros (due to the
* uresize). Revisit this when we implement custom logic to implement
* constant multiplication specially.
*)
create_recursive (Multiply (uresize x1 wx2, uresize y1 wx2))
in
let x0y2 = create_recursive (Multiply (uresize x0 wx2, uresize y2 wx2)) in
let result =
pipe_add
~stages:post_adder_stages
[ With_shift.create x2y2 ~shift:(k4 - k2)
; With_shift.uresize (With_shift.create x2y1 ~shift:(k3 - k2)) (w2 - k2)
; With_shift.uresize (With_shift.create x1y2 ~shift:(k3 - k2)) (w2 - k2)
; With_shift.uresize x2y0 ((w * 2) - k2)
; With_shift.uresize x1y1 ((w * 2) - k2)
; With_shift.uresize x0y2 ((w * 2) - k2)
]
in
With_shift.sll result ~by:k2
| Square _ ->
raise_s [%message "Radix-3 not implemented in approx msb multiplication."])
;;
let create_with_config
~config:{ Config.levels; ground_multiplier }
~scope
~clock
~enable
input
=
create_recursive ~levels ~ground_multiplier ~scope ~clock ~enable input
;;
module type Width = sig
val bits : int
end
module With_interface_multiply (M : Width) = struct
include M
module I = struct
type 'a t =
{ clock : 'a
; enable : 'a
; x : 'a [@bits bits]
; y : 'a [@bits bits]
; in_valid : 'a
}
[@@deriving sexp_of, hardcaml]
end
module O = struct
type 'a t =
{ z : 'a [@bits 2 * bits]
; out_valid : 'a
}
[@@deriving sexp_of, hardcaml]
end
let create ~config scope { I.clock; enable; x; y; in_valid } =
let spec = Reg_spec.create ~clock () in
let z =
create_with_config ~config ~scope ~clock ~enable (Multiply (x, y))
|> With_shift.to_signal
in
let out_valid = pipeline spec ~enable ~n:(Config.latency config) in_valid in
assert (width z = bits);
{ O.z; out_valid }
;;
let hierarchical ~name ~config scope i =
let module H = Hierarchy.In_scope (I) (O) in
let { O.z; out_valid = _ } = H.hierarchical ~scope ~name (create ~config) i in
z
;;
end
module Interface_1arg (M : Width) = struct
include M
module I = struct
type 'a t =
{ clock : 'a
; enable : 'a
; x : 'a [@bits bits]
; in_valid : 'a
}
[@@deriving sexp_of, hardcaml]
end
module O = struct
type 'a t =
{ y : 'a [@bits 2 * bits]
; out_valid : 'a
}
[@@deriving sexp_of, hardcaml]
end
end
module With_interface_multiply_by_constant (M : Width) = struct
include Interface_1arg (M)
let create ~config ~multiply_by scope { I.clock; enable; x; in_valid } =
let spec = Reg_spec.create ~clock () in
let y =
Multiply (x, Signal.of_constant (Bits.to_constant multiply_by))
|> create_with_config ~scope ~clock ~enable ~config
|> With_shift.to_signal
in
let out_valid = pipeline spec ~enable ~n:(Config.latency config) in_valid in
assert (width y = bits * 2);
{ O.y; out_valid }
;;
let hierarchical ~name ~config ~multiply_by scope i =
let module H = Hierarchy.In_scope (I) (O) in
let { O.y; out_valid = _ } =
H.hierarchical ~scope ~name (create ~multiply_by ~config) i
in
y
;;
end
module With_interface_square (M : Width) = struct
include Interface_1arg (M)
let create
~config:{ Config.levels; ground_multiplier }
scope
{ I.clock; enable; x; in_valid }
=
let spec = Reg_spec.create ~clock () in
let y =
create_recursive ~scope ~clock ~enable ~levels ~ground_multiplier (Square x)
|> With_shift.to_signal
in
let out_valid =
pipeline spec ~enable ~n:(Config.latency { levels; ground_multiplier }) in_valid
in
assert (width y = 2 * bits);
{ O.y; out_valid }
;;
let hierarchical ~name ~config scope i =
let module H = Hierarchy.In_scope (I) (O) in
let { O.y; out_valid = _ } = H.hierarchical ~scope ~name (create ~config) i in
y
;;
end
let hierarchical ?name ~config ~clock ~enable ~scope (input : Multiplier_input.t) =
let bits = Multiplier_input.width input in
let module Width = struct
let bits = bits
end
in
match input with
| Multiply (x, y) ->
let module M = With_interface_multiply (Width) in
let name =
Option.value ~default:(Printf.sprintf "approx_msb_multiply_%d" bits) name
in
M.hierarchical ~name ~config scope { clock; enable; x; y; in_valid = vdd }
| Multiply_by_constant (x, multiply_by) ->
let module M = With_interface_multiply_by_constant (Width) in
let name =
Option.value ~default:(Printf.sprintf "approx_msb_multiply_by_cst_%d" bits) name
in
M.hierarchical ~name ~config ~multiply_by scope { clock; enable; x; in_valid = vdd }
| Square x ->
let module M = With_interface_square (Width) in
let name =
Option.value ~default:(Printf.sprintf "approx_msb_width_square_%d" bits) name
in
M.hierarchical ~name ~config scope { clock; enable; x; in_valid = vdd }
;;
| |
9a0bcca98d912a8f8f30d060ee358e7d74ca6c5dd97f37f8770c2069a602195d | goblint/analyzer | regionDomain.ml | open GoblintCil
open GobConfig
module GU = Goblintutil
module V = Basetype.Variables
module B = Printable.UnitConf (struct let name = "•" end)
module F = Lval.Fields
module VF =
struct
include Printable.ProdSimple (V) (F)
let show (v,fd) =
let v_str = V.show v in
let fd_str = F.show fd in
v_str ^ fd_str
let pretty () x = Pretty.text (show x)
let printXml f (v,fi) =
BatPrintf.fprintf f "<value>\n<data>\n%s%a\n</data>\n</value>\n" (XmlUtil.escape (V.show v)) F.printInnerXml fi
Indicates if the two var * offset pairs should collapse or not .
let collapse (v1,f1) (v2,f2) = V.equal v1 v2 && F.collapse f1 f2
let leq (v1,f1) (v2,f2) = V.equal v1 v2 && F.leq f1 f2
(* Joins the fields, assuming the vars are equal. *)
let join (v1,f1) (v2,f2) = (v1,F.join f1 f2)
let kill x (v,f) = v, F.kill x f
let replace x exp (v,fd) = v, F.replace x exp fd
end
module VFB =
struct
include Printable.Either (VF) (B)
let printXml f = function
| `Right () ->
BatPrintf.fprintf f "<value>\n<data>\n•\n</data>\n</value>\n"
| `Left x ->
BatPrintf.fprintf f "<value>\n<data>\n%a\n</data>\n</value>\n" VF.printXml x
let collapse (x:t) (y:t): bool =
match x,y with
| `Right (), `Right () -> true
| `Right (), _ | _, `Right () -> false
| `Left x, `Left y -> VF.collapse x y
let leq x y =
match x,y with
| `Right (), `Right () -> true
| `Right (), _ | _, `Right () -> false
| `Left x, `Left y -> VF.leq x y
let join (x:t) (y:t) :t =
match x,y with
| `Right (), _ -> `Right ()
| _, `Right () -> `Right ()
| `Left x, `Left y -> `Left (VF.join x y)
let lift f y = match y with
| `Left y -> `Left (f y)
| `Right () -> `Right ()
let kill x (y:t): t = lift (VF.kill x) y
let replace x exp y = lift (VF.replace x exp) y
let is_bullet x = x = `Right ()
let bullet = `Right ()
let of_vf vf = `Left vf
let real_region (x:t): bool = match x with
| `Left (v,fd) -> F.real_region fd (v.vtype)
| `Right () -> false
end
module RS = struct
include PartitionDomain.Set (VFB)
let single_vf vf = singleton (VFB.of_vf vf)
let single_bullet = singleton (VFB.bullet)
let remove_bullet x = remove VFB.bullet x
let has_bullet x = exists VFB.is_bullet x
let is_single_bullet rs =
not (is_top rs) &&
cardinal rs = 1 &&
has_bullet rs
let to_vf_list s =
let lst = elements s in
let f x acc = match x with
| `Left vf -> vf :: acc
| `Right () -> acc
in
List.fold_right f lst []
let kill x s = map (VFB.kill x) s
let replace x exp s = map (VFB.replace x exp) s
end
module RegPart = struct
include PartitionDomain.Make (RS)
let real_region r =
RS.cardinal r > 1 || try VFB.real_region (RS.choose r)
with Not_found -> false
let add r p = if real_region r then add r p else p
end
module RegMap =
struct
include MapDomain.MapBot (VF) (RS)
let name () = "regmap"
end
module Reg =
struct
include Lattice.Prod (RegPart) (RegMap)
type set = RS.t
type elt = VF.t
let closure p m = RegMap.map (RegPart.closure p) m
let is_global (v,fd) = v.vglob
let remove v (p,m) = p, RegMap.remove (v,[]) m
let remove_vars (vs: varinfo list) (cp:t): t =
List.fold_right remove vs cp
let kill x (p,m:t): t =
p, RegMap.map (RS.kill x) m
let kill_vars vars st = List.fold_right kill vars st
let replace x exp (p,m:t): t =
RegPart.map (RS.replace x exp) p, RegMap.map (RS.replace x exp) m
let update x rval st =
match rval with
| Lval (Var y, NoOffset) when V.equal x y -> st
| BinOp (PlusA, Lval (Var y, NoOffset), (Const _ as c), typ) when V.equal x y ->
replace x (BinOp (MinusA, Lval (Var y, NoOffset), c, typ)) st
| BinOp (MinusA, Lval (Var y, NoOffset), (Const _ as c), typ) when V.equal x y ->
replace x (BinOp (PlusA, Lval (Var y, NoOffset), c, typ)) st
| _ -> kill x st
type eval_t = (bool * elt * F.t) option
let eval_exp exp: eval_t =
let offsornot offs = if (get_bool "exp.region-offsets") then F.listify offs else [] in
let rec do_offs deref def = function
| Field (fd, offs) -> begin
match Goblintutil.is_blessed (TComp (fd.fcomp, [])) with
| Some v -> do_offs deref (Some (deref, (v, offsornot (Field (fd, offs))), [])) offs
| None -> do_offs deref def offs
end
| Index (_, offs) -> do_offs deref def offs
| NoOffset -> def
in
The intuition for the offset computations is that we keep the static _ suffix _ of an
* access path . These can be used to partition accesses when fields do not overlap .
* This means that for pointer dereferences and when obtaining the value from an lval
* ( but not under ) , we drop the offsets because we land somewhere
* unknown in the region .
* access path. These can be used to partition accesses when fields do not overlap.
* This means that for pointer dereferences and when obtaining the value from an lval
* (but not under AddrOf), we drop the offsets because we land somewhere
* unknown in the region. *)
let rec eval_rval deref rval =
match rval with
| Lval lval -> BatOption.map (fun (deref, v, offs) -> (deref, v, [])) (eval_lval deref lval)
| AddrOf lval -> eval_lval deref lval
| CastE (typ, exp) -> eval_rval deref exp
| BinOp (MinusPI, p, i, typ)
| BinOp (PlusPI, p, i, typ)
| BinOp (IndexPI, p, i, typ) -> eval_rval deref p
| _ -> None
and eval_lval deref lval =
match lval with
| (Var x, NoOffset) when Goblintutil.is_blessed x.vtype <> None ->
begin match Goblintutil.is_blessed x.vtype with
| Some v -> Some (deref, (v,[]), [])
| _ when x.vglob -> Some (deref, (x, []), [])
| _ -> None
end
| (Var x, offs) -> do_offs deref (Some (deref, (x, offsornot offs), [])) offs
| (Mem exp,offs) ->
match eval_rval true exp with
| Some (deref, v, _) -> do_offs deref (Some (deref, v, offsornot offs)) offs
| x -> do_offs deref x offs
in
eval_rval false exp
(* This is the main logic for dealing with the bullet and finding it an
* owner... *)
let add_set (s:set) llist (p,m:t): t =
if RS.has_bullet s then
let f key value (ys, x) =
if RS.has_bullet value then key::ys, RS.join value x else ys,x in
let ys,x = RegMap.fold f m (llist, RS.remove_bullet s) in
let x = RS.remove_bullet x in
if RS.is_empty x then
p, RegMap.add_list_set llist RS.single_bullet m
else
RegPart.add x p, RegMap.add_list_set ys x m
else
let p = RegPart.add s p in
p, closure p m
let assign (lval: lval) (rval: exp) (st: t): t =
(* let _ = printf "%a = %a\n" (printLval plainCilPrinter) lval (printExp plainCilPrinter) rval in *)
let t = Cilfacade.typeOf rval in
TODO : this currently allows function pointers , e.g. in iowarrior , but should it ?
match eval_exp (Lval lval), eval_exp rval with
(* TODO: should offs_x matter? *)
| Some (deref_x, x,offs_x), Some (deref_y,y,offs_y) ->
if VF.equal x y then st else
let (p,m) = st in begin
let append_offs_y = RS.map (function
| `Left (v, offs) -> `Left (v, offs @ offs_y)
| `Right () -> `Right ()
)
in
match is_global x, deref_x, is_global y with
| false, false, true ->
p, RegMap.add x (append_offs_y (RegPart.closure p (RS.single_vf y))) m
| false, false, false ->
p, RegMap.add x (append_offs_y (RegMap.find y m)) m
(* TODO: use append_offs_y also in the following cases? *)
| false, true , true ->
add_set (RS.join (RegMap.find x m) (RS.single_vf y)) [x] st
| false, true , false ->
add_set (RS.join (RegMap.find x m) (RegMap.find y m)) [x;y] st
| true , _ , true ->
add_set (RS.join (RS.single_vf x) (RS.single_vf y)) [] st
| true , _ , false ->
add_set (RS.join (RS.single_vf x) (RegMap.find y m)) [y] st
end
| _ -> st
end else if isIntegralType t then begin
match lval with
| Var x, NoOffset -> update x rval st
| _ -> st
end else
match eval_exp (Lval lval) with
| Some (false, (x,_),_) -> remove x st
| _ -> st
let assign_bullet lval (p,m:t):t =
match eval_exp (Lval lval) with
| Some (_,x,_) -> p, RegMap.add x RS.single_bullet m
| _ -> p,m
let related_globals (deref_vfd: eval_t) (p,m: t): elt list =
let add_o o2 (v,o) = (v,o@o2) in
match deref_vfd with
| Some (true, vfd, os) ->
let vfd_class =
if is_global vfd then
RegPart.find_class (VFB.of_vf vfd) p
else
RegMap.find vfd m
in
Messages.warn ~msg:("ok ? " ^sprint 80 ( V.pretty ( ) ( fst vfd)++F.pretty ( ) ( snd vfd ) ) ) ( ) ;
List.map (add_o os) (RS.to_vf_list vfd_class)
| Some (false, vfd, os) ->
if is_global vfd then [vfd] else []
| None -> Messages.info ~category:Unsound "Access to unknown address could be global"; []
end
(* TODO: remove Lift *)
module RegionDom = Lattice.Lift (RegMap) (struct let top_name = "Unknown" let bot_name = "Error" end)
| null | https://raw.githubusercontent.com/goblint/analyzer/78e8ce83e70585e89623ec84af355deb2b3b854d/src/cdomains/regionDomain.ml | ocaml | Joins the fields, assuming the vars are equal.
This is the main logic for dealing with the bullet and finding it an
* owner...
let _ = printf "%a = %a\n" (printLval plainCilPrinter) lval (printExp plainCilPrinter) rval in
TODO: should offs_x matter?
TODO: use append_offs_y also in the following cases?
TODO: remove Lift | open GoblintCil
open GobConfig
module GU = Goblintutil
module V = Basetype.Variables
module B = Printable.UnitConf (struct let name = "•" end)
module F = Lval.Fields
module VF =
struct
include Printable.ProdSimple (V) (F)
let show (v,fd) =
let v_str = V.show v in
let fd_str = F.show fd in
v_str ^ fd_str
let pretty () x = Pretty.text (show x)
let printXml f (v,fi) =
BatPrintf.fprintf f "<value>\n<data>\n%s%a\n</data>\n</value>\n" (XmlUtil.escape (V.show v)) F.printInnerXml fi
Indicates if the two var * offset pairs should collapse or not .
let collapse (v1,f1) (v2,f2) = V.equal v1 v2 && F.collapse f1 f2
let leq (v1,f1) (v2,f2) = V.equal v1 v2 && F.leq f1 f2
let join (v1,f1) (v2,f2) = (v1,F.join f1 f2)
let kill x (v,f) = v, F.kill x f
let replace x exp (v,fd) = v, F.replace x exp fd
end
module VFB =
struct
include Printable.Either (VF) (B)
let printXml f = function
| `Right () ->
BatPrintf.fprintf f "<value>\n<data>\n•\n</data>\n</value>\n"
| `Left x ->
BatPrintf.fprintf f "<value>\n<data>\n%a\n</data>\n</value>\n" VF.printXml x
let collapse (x:t) (y:t): bool =
match x,y with
| `Right (), `Right () -> true
| `Right (), _ | _, `Right () -> false
| `Left x, `Left y -> VF.collapse x y
let leq x y =
match x,y with
| `Right (), `Right () -> true
| `Right (), _ | _, `Right () -> false
| `Left x, `Left y -> VF.leq x y
let join (x:t) (y:t) :t =
match x,y with
| `Right (), _ -> `Right ()
| _, `Right () -> `Right ()
| `Left x, `Left y -> `Left (VF.join x y)
let lift f y = match y with
| `Left y -> `Left (f y)
| `Right () -> `Right ()
let kill x (y:t): t = lift (VF.kill x) y
let replace x exp y = lift (VF.replace x exp) y
let is_bullet x = x = `Right ()
let bullet = `Right ()
let of_vf vf = `Left vf
let real_region (x:t): bool = match x with
| `Left (v,fd) -> F.real_region fd (v.vtype)
| `Right () -> false
end
module RS = struct
include PartitionDomain.Set (VFB)
let single_vf vf = singleton (VFB.of_vf vf)
let single_bullet = singleton (VFB.bullet)
let remove_bullet x = remove VFB.bullet x
let has_bullet x = exists VFB.is_bullet x
let is_single_bullet rs =
not (is_top rs) &&
cardinal rs = 1 &&
has_bullet rs
let to_vf_list s =
let lst = elements s in
let f x acc = match x with
| `Left vf -> vf :: acc
| `Right () -> acc
in
List.fold_right f lst []
let kill x s = map (VFB.kill x) s
let replace x exp s = map (VFB.replace x exp) s
end
module RegPart = struct
include PartitionDomain.Make (RS)
let real_region r =
RS.cardinal r > 1 || try VFB.real_region (RS.choose r)
with Not_found -> false
let add r p = if real_region r then add r p else p
end
module RegMap =
struct
include MapDomain.MapBot (VF) (RS)
let name () = "regmap"
end
module Reg =
struct
include Lattice.Prod (RegPart) (RegMap)
type set = RS.t
type elt = VF.t
let closure p m = RegMap.map (RegPart.closure p) m
let is_global (v,fd) = v.vglob
let remove v (p,m) = p, RegMap.remove (v,[]) m
let remove_vars (vs: varinfo list) (cp:t): t =
List.fold_right remove vs cp
let kill x (p,m:t): t =
p, RegMap.map (RS.kill x) m
let kill_vars vars st = List.fold_right kill vars st
let replace x exp (p,m:t): t =
RegPart.map (RS.replace x exp) p, RegMap.map (RS.replace x exp) m
let update x rval st =
match rval with
| Lval (Var y, NoOffset) when V.equal x y -> st
| BinOp (PlusA, Lval (Var y, NoOffset), (Const _ as c), typ) when V.equal x y ->
replace x (BinOp (MinusA, Lval (Var y, NoOffset), c, typ)) st
| BinOp (MinusA, Lval (Var y, NoOffset), (Const _ as c), typ) when V.equal x y ->
replace x (BinOp (PlusA, Lval (Var y, NoOffset), c, typ)) st
| _ -> kill x st
type eval_t = (bool * elt * F.t) option
let eval_exp exp: eval_t =
let offsornot offs = if (get_bool "exp.region-offsets") then F.listify offs else [] in
let rec do_offs deref def = function
| Field (fd, offs) -> begin
match Goblintutil.is_blessed (TComp (fd.fcomp, [])) with
| Some v -> do_offs deref (Some (deref, (v, offsornot (Field (fd, offs))), [])) offs
| None -> do_offs deref def offs
end
| Index (_, offs) -> do_offs deref def offs
| NoOffset -> def
in
The intuition for the offset computations is that we keep the static _ suffix _ of an
* access path . These can be used to partition accesses when fields do not overlap .
* This means that for pointer dereferences and when obtaining the value from an lval
* ( but not under ) , we drop the offsets because we land somewhere
* unknown in the region .
* access path. These can be used to partition accesses when fields do not overlap.
* This means that for pointer dereferences and when obtaining the value from an lval
* (but not under AddrOf), we drop the offsets because we land somewhere
* unknown in the region. *)
let rec eval_rval deref rval =
match rval with
| Lval lval -> BatOption.map (fun (deref, v, offs) -> (deref, v, [])) (eval_lval deref lval)
| AddrOf lval -> eval_lval deref lval
| CastE (typ, exp) -> eval_rval deref exp
| BinOp (MinusPI, p, i, typ)
| BinOp (PlusPI, p, i, typ)
| BinOp (IndexPI, p, i, typ) -> eval_rval deref p
| _ -> None
and eval_lval deref lval =
match lval with
| (Var x, NoOffset) when Goblintutil.is_blessed x.vtype <> None ->
begin match Goblintutil.is_blessed x.vtype with
| Some v -> Some (deref, (v,[]), [])
| _ when x.vglob -> Some (deref, (x, []), [])
| _ -> None
end
| (Var x, offs) -> do_offs deref (Some (deref, (x, offsornot offs), [])) offs
| (Mem exp,offs) ->
match eval_rval true exp with
| Some (deref, v, _) -> do_offs deref (Some (deref, v, offsornot offs)) offs
| x -> do_offs deref x offs
in
eval_rval false exp
let add_set (s:set) llist (p,m:t): t =
if RS.has_bullet s then
let f key value (ys, x) =
if RS.has_bullet value then key::ys, RS.join value x else ys,x in
let ys,x = RegMap.fold f m (llist, RS.remove_bullet s) in
let x = RS.remove_bullet x in
if RS.is_empty x then
p, RegMap.add_list_set llist RS.single_bullet m
else
RegPart.add x p, RegMap.add_list_set ys x m
else
let p = RegPart.add s p in
p, closure p m
let assign (lval: lval) (rval: exp) (st: t): t =
let t = Cilfacade.typeOf rval in
TODO : this currently allows function pointers , e.g. in iowarrior , but should it ?
match eval_exp (Lval lval), eval_exp rval with
| Some (deref_x, x,offs_x), Some (deref_y,y,offs_y) ->
if VF.equal x y then st else
let (p,m) = st in begin
let append_offs_y = RS.map (function
| `Left (v, offs) -> `Left (v, offs @ offs_y)
| `Right () -> `Right ()
)
in
match is_global x, deref_x, is_global y with
| false, false, true ->
p, RegMap.add x (append_offs_y (RegPart.closure p (RS.single_vf y))) m
| false, false, false ->
p, RegMap.add x (append_offs_y (RegMap.find y m)) m
| false, true , true ->
add_set (RS.join (RegMap.find x m) (RS.single_vf y)) [x] st
| false, true , false ->
add_set (RS.join (RegMap.find x m) (RegMap.find y m)) [x;y] st
| true , _ , true ->
add_set (RS.join (RS.single_vf x) (RS.single_vf y)) [] st
| true , _ , false ->
add_set (RS.join (RS.single_vf x) (RegMap.find y m)) [y] st
end
| _ -> st
end else if isIntegralType t then begin
match lval with
| Var x, NoOffset -> update x rval st
| _ -> st
end else
match eval_exp (Lval lval) with
| Some (false, (x,_),_) -> remove x st
| _ -> st
let assign_bullet lval (p,m:t):t =
match eval_exp (Lval lval) with
| Some (_,x,_) -> p, RegMap.add x RS.single_bullet m
| _ -> p,m
let related_globals (deref_vfd: eval_t) (p,m: t): elt list =
let add_o o2 (v,o) = (v,o@o2) in
match deref_vfd with
| Some (true, vfd, os) ->
let vfd_class =
if is_global vfd then
RegPart.find_class (VFB.of_vf vfd) p
else
RegMap.find vfd m
in
Messages.warn ~msg:("ok ? " ^sprint 80 ( V.pretty ( ) ( fst vfd)++F.pretty ( ) ( snd vfd ) ) ) ( ) ;
List.map (add_o os) (RS.to_vf_list vfd_class)
| Some (false, vfd, os) ->
if is_global vfd then [vfd] else []
| None -> Messages.info ~category:Unsound "Access to unknown address could be global"; []
end
module RegionDom = Lattice.Lift (RegMap) (struct let top_name = "Unknown" let bot_name = "Error" end)
|
3ae482ef6d62496e9e43b476d4092d599e55d04c23a5fc4a9c9bf1d61d687259 | lmj/lparallel | central-scheduler.lisp | Copyright ( c ) 2011 - 2012 , . All rights reserved .
;;;
;;; Redistribution and use in source and binary forms, with or without
;;; modification, are permitted provided that the following conditions
;;; are met:
;;;
;;; * Redistributions of source code must retain the above copyright
;;; notice, this list of conditions and the following disclaimer.
;;;
;;; * Redistributions in binary form must reproduce the above
;;; copyright notice, this list of conditions and the following
;;; disclaimer in the documentation and/or other materials provided
;;; with the distribution.
;;;
;;; * Neither the name of the project nor the names of its
;;; contributors may be used to endorse or promote products derived
;;; from this software without specific prior written permission.
;;;
;;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
" AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT
;;; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
;;; A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR FOR ANY DIRECT , INDIRECT , INCIDENTAL ,
SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT
LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ; LOSS OF USE ,
;;; DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT
;;; (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
;;; OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
(in-package #:lparallel.kernel)
(defun make-scheduler (workers spin-count)
(declare (ignore workers spin-count))
(make-biased-queue))
(defun/type schedule-task (scheduler task priority)
(scheduler (or task null) t) (values)
(declare #.*normal-optimize*)
(ccase priority
(:default (push-biased-queue task scheduler))
(:low (push-biased-queue/low task scheduler)))
(values))
(defun/inline next-task (scheduler worker)
(declare (ignore worker))
(pop-biased-queue scheduler))
(defun/type steal-task (scheduler) (scheduler) (or task null)
(declare #.*normal-optimize*)
(with-lock-predicate/wait
(lparallel.biased-queue::lock scheduler)
(not (biased-queue-empty-p/no-lock scheduler))
;; don't steal nil, the end condition flag
(when (peek-biased-queue/no-lock scheduler)
(pop-biased-queue/no-lock scheduler))))
| null | https://raw.githubusercontent.com/lmj/lparallel/9c11f40018155a472c540b63684049acc9b36e15/src/kernel/central-scheduler.lisp | lisp |
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.
* Neither the name of the project nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
LOSS OF USE ,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
don't steal nil, the end condition flag | Copyright ( c ) 2011 - 2012 , . All rights reserved .
" AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT
HOLDER OR FOR ANY DIRECT , INDIRECT , INCIDENTAL ,
SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT
THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT
(in-package #:lparallel.kernel)
(defun make-scheduler (workers spin-count)
(declare (ignore workers spin-count))
(make-biased-queue))
(defun/type schedule-task (scheduler task priority)
(scheduler (or task null) t) (values)
(declare #.*normal-optimize*)
(ccase priority
(:default (push-biased-queue task scheduler))
(:low (push-biased-queue/low task scheduler)))
(values))
(defun/inline next-task (scheduler worker)
(declare (ignore worker))
(pop-biased-queue scheduler))
(defun/type steal-task (scheduler) (scheduler) (or task null)
(declare #.*normal-optimize*)
(with-lock-predicate/wait
(lparallel.biased-queue::lock scheduler)
(not (biased-queue-empty-p/no-lock scheduler))
(when (peek-biased-queue/no-lock scheduler)
(pop-biased-queue/no-lock scheduler))))
|
f03f6fc07feb7a8474ca3d3eda5ad71c86f359242dc93ec552bd46d6690962eb | dschrempf/elynx | Options.hs | # LANGUAGE DeriveGeneric #
-- |
-- Module : TLynx.Shuffle.Options
-- Description : Options for the connect subcommand
Copyright : 2021
License : GPL-3.0 - or - later
--
-- Maintainer :
-- Stability : unstable
-- Portability : portable
--
Creation date : Thu Sep 19 15:02:21 2019 .
module TLynx.Shuffle.Options
( ShuffleArguments (..),
shuffleArguments,
)
where
import Data.Aeson
import ELynx.Tools.Options
import ELynx.Tools.Reproduction
import GHC.Generics
import Options.Applicative
import TLynx.Parsers
-- | Arguments of shuffle command.
data ShuffleArguments = ShuffleArguments
{ nwFormat :: NewickFormat,
nReplicates :: Int,
inFile :: FilePath,
argsSeed :: SeedOpt
}
deriving (Eq, Show, Generic)
instance Reproducible ShuffleArguments where
inFiles = pure . inFile
outSuffixes _ = [".tree"]
getSeed = Just . argsSeed
setSeed a s = a {argsSeed = s}
parser = shuffleArguments
cmdName = "shuffle"
cmdDsc =
[ "Shuffle a phylogenetic tree (keep coalescent times, but shuffle topology and leaves)."
]
instance FromJSON ShuffleArguments
instance ToJSON ShuffleArguments
| Parse arguments of shuffle command .
shuffleArguments :: Parser ShuffleArguments
shuffleArguments = ShuffleArguments <$> newickFormat <*> n <*> file <*> seedOpt
n :: Parser Int
n =
option auto $
long "replicates"
<> short 'n'
<> metavar "N"
<> value 1
<> help
"Number of trees to generate"
file :: Parser FilePath
file =
strArgument $ metavar "TREE-FILE" <> help "File containing a Newick tree"
| null | https://raw.githubusercontent.com/dschrempf/elynx/bf5f0b353b5e2f74d29058fc86ea6723133cab5c/tlynx/src/TLynx/Shuffle/Options.hs | haskell | |
Module : TLynx.Shuffle.Options
Description : Options for the connect subcommand
Maintainer :
Stability : unstable
Portability : portable
| Arguments of shuffle command. | # LANGUAGE DeriveGeneric #
Copyright : 2021
License : GPL-3.0 - or - later
Creation date : Thu Sep 19 15:02:21 2019 .
module TLynx.Shuffle.Options
( ShuffleArguments (..),
shuffleArguments,
)
where
import Data.Aeson
import ELynx.Tools.Options
import ELynx.Tools.Reproduction
import GHC.Generics
import Options.Applicative
import TLynx.Parsers
data ShuffleArguments = ShuffleArguments
{ nwFormat :: NewickFormat,
nReplicates :: Int,
inFile :: FilePath,
argsSeed :: SeedOpt
}
deriving (Eq, Show, Generic)
instance Reproducible ShuffleArguments where
inFiles = pure . inFile
outSuffixes _ = [".tree"]
getSeed = Just . argsSeed
setSeed a s = a {argsSeed = s}
parser = shuffleArguments
cmdName = "shuffle"
cmdDsc =
[ "Shuffle a phylogenetic tree (keep coalescent times, but shuffle topology and leaves)."
]
instance FromJSON ShuffleArguments
instance ToJSON ShuffleArguments
| Parse arguments of shuffle command .
shuffleArguments :: Parser ShuffleArguments
shuffleArguments = ShuffleArguments <$> newickFormat <*> n <*> file <*> seedOpt
n :: Parser Int
n =
option auto $
long "replicates"
<> short 'n'
<> metavar "N"
<> value 1
<> help
"Number of trees to generate"
file :: Parser FilePath
file =
strArgument $ metavar "TREE-FILE" <> help "File containing a Newick tree"
|
4538d1ceb8783ccf09f07a4a5d8fc5c739554703a3eeb22cad6077d53688fda0 | masatoi/cl-zerodl | adagrad.lisp | (defpackage #:cl-zerodl/core/optimizer/adagrad
(:use #:cl
#:mgl-mat
#:cl-zerodl/core/layer/base
#:cl-zerodl/core/optimizer/base
#:cl-zerodl/core/network)
(:nicknames :zerodl.optimizer.adagrad)
(:import-from #:cl-zerodl/core/utils
#:define-class)
(:import-from #:cl-zerodl/core/optimizer/sgd
#:sgd
#:learning-rate)
(:export #:adagrad
#:make-adagrad))
(in-package #:cl-zerodl/core/optimizer/adagrad)
;; Adagrad
(define-class adagrad (sgd)
velocities tmps
Tiny number to add to the denominator to avoid division by zero
(epsilon :initform 1.0e-6 :type single-float))
(defun make-adagrad (learning-rate network &key (epsilon 1.0e-6))
(let ((opt (make-instance 'adagrad
:learning-rate learning-rate
:velocities (make-hash-table :test 'eq)
:tmps (make-hash-table :test 'eq)
:epsilon epsilon)))
(do-updatable-layer (layer network)
(dolist (param (updatable-parameters layer))
(setf (gethash param (velocities opt))
(make-mat (mat-dimensions param) :initial-element 0.0)
(gethash param (tmps opt))
(make-mat (mat-dimensions param) :initial-element 0.0))))
opt))
(defmethod update! ((optimizer adagrad) parameter gradient)
(let ((velocity (gethash parameter (velocities optimizer)))
(tmp (gethash parameter (tmps optimizer))))
(geem! 1.0 gradient gradient 1.0 velocity)
(copy! velocity tmp)
(.+! (epsilon optimizer) tmp)
(.sqrt! tmp)
(.inv! tmp)
(.*! gradient tmp)
(axpy! (- (learning-rate optimizer)) tmp parameter)))
| null | https://raw.githubusercontent.com/masatoi/cl-zerodl/5c453321b41f07610cdee248792499b5b742f550/core/optimizer/adagrad.lisp | lisp | Adagrad | (defpackage #:cl-zerodl/core/optimizer/adagrad
(:use #:cl
#:mgl-mat
#:cl-zerodl/core/layer/base
#:cl-zerodl/core/optimizer/base
#:cl-zerodl/core/network)
(:nicknames :zerodl.optimizer.adagrad)
(:import-from #:cl-zerodl/core/utils
#:define-class)
(:import-from #:cl-zerodl/core/optimizer/sgd
#:sgd
#:learning-rate)
(:export #:adagrad
#:make-adagrad))
(in-package #:cl-zerodl/core/optimizer/adagrad)
(define-class adagrad (sgd)
velocities tmps
Tiny number to add to the denominator to avoid division by zero
(epsilon :initform 1.0e-6 :type single-float))
(defun make-adagrad (learning-rate network &key (epsilon 1.0e-6))
(let ((opt (make-instance 'adagrad
:learning-rate learning-rate
:velocities (make-hash-table :test 'eq)
:tmps (make-hash-table :test 'eq)
:epsilon epsilon)))
(do-updatable-layer (layer network)
(dolist (param (updatable-parameters layer))
(setf (gethash param (velocities opt))
(make-mat (mat-dimensions param) :initial-element 0.0)
(gethash param (tmps opt))
(make-mat (mat-dimensions param) :initial-element 0.0))))
opt))
(defmethod update! ((optimizer adagrad) parameter gradient)
(let ((velocity (gethash parameter (velocities optimizer)))
(tmp (gethash parameter (tmps optimizer))))
(geem! 1.0 gradient gradient 1.0 velocity)
(copy! velocity tmp)
(.+! (epsilon optimizer) tmp)
(.sqrt! tmp)
(.inv! tmp)
(.*! gradient tmp)
(axpy! (- (learning-rate optimizer)) tmp parameter)))
|
1749329cf0e40e971eec4a252ec938e7fc1b7e2a6e10ff534986c34b431fa426 | informatimago/lisp | run-program-test.lisp | -*- mode : lisp;coding : utf-8 -*-
;;;;**************************************************************************
FILE :
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: Common-Lisp
USER - INTERFACE :
;;;;DESCRIPTION
;;;;
;;;; Tests the run-program function.
;;;;
< PJB > < >
MODIFICATIONS
2012 - 03 - 25 < PJB > Created .
;;;;LEGAL
AGPL3
;;;;
Copyright 2012 - 2016
;;;;
;;;; This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation , either version 3 of the License , or
;;;; (at your option) any later version.
;;;;
;;;; This program is distributed in the hope that it will be useful,
;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details .
;;;;
You should have received a copy of the GNU Affero General Public License
;;;; along with this program. If not, see </>.
;;;;**************************************************************************
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf *readtable* (copy-readtable nil)))
(defpackage "COM.INFORMATIMAGO.CLEXT.RUN-PROGRAM.TEST"
(:use "COMMON-LISP"
"COM.INFORMATIMAGO.COMMON-LISP.CESARUM.SIMPLE-TEST"
"COM.INFORMATIMAGO.CLEXT.RUN-PROGRAM")
(:export "TEST/RUN-PROGRAM")
(:documentation "
"))
(in-package "COM.INFORMATIMAGO.CLEXT.RUN-PROGRAM.TEST")
(defun dump-stream (stream)
(loop :for line = (read-line stream nil nil) :while line :do (write-line line)))
(defun dump-file (path)
(with-open-file (inp path) (dump-stream inp)))
(defun text-file-contents (path)
(with-open-file (inp path)
(loop
:for line = (read-line inp nil nil)
:while line :collect line)))
(defun text-stream-contents (inp)
(loop
:for line = (read-line inp nil nil)
:while line :collect line))
(defun create-test-input-file ()
(with-open-file (testinp "TESTINP.TXT"
:direction :output
:if-exists :supersede
:if-does-not-exist :create)
(write-string "Hao
Wang
logicien
americain
algorithme
en
question
a
ete
publie
en
1960
dans
IBM
Journal
"
testinp)))
(defun check-sorted-output-stream (stream)
(let ((stream-contents (text-stream-contents stream))
(sorted-list (sort (copy-seq '("Hao" "Wang" "logicien" "americain"
"algorithme" "en" "question" "a" "ete" "publie"
"en" "1960" "dans" "IBM" "Journal"))
(function string<))))
(check equal sorted-list stream-contents
() "~%~20A=~S~%~20A=~S~%"
"sorted-list" sorted-list
"stream-contents" stream-contents)))
(defun check-sorted-output-file ()
(with-open-file (stream "TESTOUT.TXT")
(check-sorted-output-stream stream)))
(defvar *verbose* nil)
(define-test test/run-program (&key ((:verbose *verbose*) *verbose*))
(create-test-input-file)
(assert-true (zerop (process-status (run-program "true" '() :wait t))))
(assert-true (zerop (process-status (prog1 (run-program "true" '() :wait nil)
(sleep 1)))))
(assert-true (plusp (process-status (run-program "false" '() :wait t))))
(assert-true (plusp (process-status (prog1 (run-program "false" '() :wait nil)
(sleep 1)))))
(run-program "true" '() :wait nil :error "TESTERR.TXT")
(sleep 1)
(check equal '() (text-file-contents "TESTERR.TXT"))
(run-program "true" '() :wait t :error "TESTERR.TXT")
(check equal '() (text-file-contents "TESTERR.TXT"))
(let ((process (run-program "sh" '("-c" "echo error 1>&2")
:wait nil :input nil :output nil :error :stream)))
(check equal '("error")
(unwind-protect
(text-stream-contents (process-error process))
(close (process-error process)))))
(ignore-errors (delete-file "TESTERR.TXT"))
(run-program "sh" '("-c" "echo error 1>&2")
:wait t :input nil :output nil :error "TESTERR.TXT")
(check equal '("error") (text-file-contents "TESTERR.TXT"))
(with-open-file (err "TESTERR.TXT"
:direction :output :if-does-not-exist :create :if-exists :supersede
#+ccl :sharing #+ccl :lock
)
(run-program "sh" '("-c" "echo error 1>&2")
:wait t :input nil :output nil :error err))
(check equal '("error") (text-file-contents "TESTERR.TXT"))
(run-program "printf" '("Hello\\nWorld\\n") :wait t)
(run-program "printf" '("Hello\\nWorld\\n") :wait nil)
(let ((process (run-program "printf" '("Hello\\nWorld\\n") :wait nil :output :stream)))
(check equal '("Hello" "World")
(unwind-protect
(loop
:for line = (read-line (process-output process) nil nil)
:while line :collect line)
(close (process-output process)))))
(with-open-file (out "TESTOUT.TXT"
:direction :output :if-does-not-exist :create :if-exists :supersede
#+ccl :sharing #+ccl :lock)
(run-program "printf" '("Hello\\nWorld\\n") :wait nil :output out)
(sleep 1))
(check equal '("Hello" "World") (text-file-contents "TESTOUT.TXT"))
(with-open-file (out "TESTOUT.TXT"
:direction :output :if-does-not-exist :create :if-exists :supersede
#+ccl :sharing #+ccl :lock)
(run-program "printf" '("Hello\\nWorld\\n") :wait t :output out))
(check equal '("Hello" "World") (text-file-contents "TESTOUT.TXT"))
(run-program "sort" '() :environment '(("LC_CTYPE" . "C") ("LC_COLLATE" . "C"))
:wait nil :input "TESTINP.TXT" :output "TESTOUT.TXT")
(sleep 1)
(check-sorted-output-file)
(with-open-file (out "TESTOUT.TXT"
:direction :output :if-does-not-exist :create :if-exists :supersede
#+ccl :sharing #+ccl :lock)
(run-program "sort" '() :environment '(("LC_CTYPE" . "C") ("LC_COLLATE" . "C"))
:wait t :input "TESTINP.TXT" :output out))
(check-sorted-output-file)
(with-open-file (inp "TESTINP.TXT"
#+ccl :sharing #+ccl :lock)
(run-program "sort" '() :environment '(("LC_CTYPE" . "C") ("LC_COLLATE" . "C"))
:wait t :input inp :output "TESTOUT.TXT"))
(check-sorted-output-file)
(with-open-file (out "TESTOUT.TXT"
:direction :output :if-does-not-exist :create :if-exists :supersede
#+ccl :sharing #+ccl :lock)
(with-open-file (inp "TESTINP.TXT"
#+ccl :sharing #+ccl :lock)
(run-program "sort" '() :environment '(("LC_CTYPE" . "C") ("LC_COLLATE" . "C"))
:wait t :input inp :output out)))
(check-sorted-output-file)
(let ((process (run-program "sort" '() :environment '(("LC_CTYPE" . "C") ("LC_COLLATE" . "C"))
:wait nil :input :stream :output :stream :error nil)))
(with-open-file (testinp "TESTINP.TXT"
#+ccl :sharing #+ccl :lock)
(loop :for line = (read-line testinp nil nil)
:while line :do (write-line line (process-input process))))
(close (process-input process))
(check-sorted-output-stream (process-output process))
(close (process-output process)))
(mapc (lambda (file) (ignore-errors (delete-file file)))
'("TESTINP.TXT" "TESTOUT.TXT" "TESTERR.TXT")))
(defun test/all ()
(test/run-program :verbose nil))
;;;; THE END ;;;;
| null | https://raw.githubusercontent.com/informatimago/lisp/571af24c06ba466e01b4c9483f8bb7690bc46d03/clext/run-program/run-program-test.lisp | lisp | coding : utf-8 -*-
**************************************************************************
LANGUAGE: Common-Lisp
SYSTEM: Common-Lisp
DESCRIPTION
Tests the run-program function.
LEGAL
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see </>.
**************************************************************************
THE END ;;;; | FILE :
USER - INTERFACE :
< PJB > < >
MODIFICATIONS
2012 - 03 - 25 < PJB > Created .
AGPL3
Copyright 2012 - 2016
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation , either version 3 of the License , or
GNU Affero General Public License for more details .
You should have received a copy of the GNU Affero General Public License
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf *readtable* (copy-readtable nil)))
(defpackage "COM.INFORMATIMAGO.CLEXT.RUN-PROGRAM.TEST"
(:use "COMMON-LISP"
"COM.INFORMATIMAGO.COMMON-LISP.CESARUM.SIMPLE-TEST"
"COM.INFORMATIMAGO.CLEXT.RUN-PROGRAM")
(:export "TEST/RUN-PROGRAM")
(:documentation "
"))
(in-package "COM.INFORMATIMAGO.CLEXT.RUN-PROGRAM.TEST")
(defun dump-stream (stream)
(loop :for line = (read-line stream nil nil) :while line :do (write-line line)))
(defun dump-file (path)
(with-open-file (inp path) (dump-stream inp)))
(defun text-file-contents (path)
(with-open-file (inp path)
(loop
:for line = (read-line inp nil nil)
:while line :collect line)))
(defun text-stream-contents (inp)
(loop
:for line = (read-line inp nil nil)
:while line :collect line))
(defun create-test-input-file ()
(with-open-file (testinp "TESTINP.TXT"
:direction :output
:if-exists :supersede
:if-does-not-exist :create)
(write-string "Hao
Wang
logicien
americain
algorithme
en
question
a
ete
publie
en
1960
dans
IBM
Journal
"
testinp)))
(defun check-sorted-output-stream (stream)
(let ((stream-contents (text-stream-contents stream))
(sorted-list (sort (copy-seq '("Hao" "Wang" "logicien" "americain"
"algorithme" "en" "question" "a" "ete" "publie"
"en" "1960" "dans" "IBM" "Journal"))
(function string<))))
(check equal sorted-list stream-contents
() "~%~20A=~S~%~20A=~S~%"
"sorted-list" sorted-list
"stream-contents" stream-contents)))
(defun check-sorted-output-file ()
(with-open-file (stream "TESTOUT.TXT")
(check-sorted-output-stream stream)))
(defvar *verbose* nil)
(define-test test/run-program (&key ((:verbose *verbose*) *verbose*))
(create-test-input-file)
(assert-true (zerop (process-status (run-program "true" '() :wait t))))
(assert-true (zerop (process-status (prog1 (run-program "true" '() :wait nil)
(sleep 1)))))
(assert-true (plusp (process-status (run-program "false" '() :wait t))))
(assert-true (plusp (process-status (prog1 (run-program "false" '() :wait nil)
(sleep 1)))))
(run-program "true" '() :wait nil :error "TESTERR.TXT")
(sleep 1)
(check equal '() (text-file-contents "TESTERR.TXT"))
(run-program "true" '() :wait t :error "TESTERR.TXT")
(check equal '() (text-file-contents "TESTERR.TXT"))
(let ((process (run-program "sh" '("-c" "echo error 1>&2")
:wait nil :input nil :output nil :error :stream)))
(check equal '("error")
(unwind-protect
(text-stream-contents (process-error process))
(close (process-error process)))))
(ignore-errors (delete-file "TESTERR.TXT"))
(run-program "sh" '("-c" "echo error 1>&2")
:wait t :input nil :output nil :error "TESTERR.TXT")
(check equal '("error") (text-file-contents "TESTERR.TXT"))
(with-open-file (err "TESTERR.TXT"
:direction :output :if-does-not-exist :create :if-exists :supersede
#+ccl :sharing #+ccl :lock
)
(run-program "sh" '("-c" "echo error 1>&2")
:wait t :input nil :output nil :error err))
(check equal '("error") (text-file-contents "TESTERR.TXT"))
(run-program "printf" '("Hello\\nWorld\\n") :wait t)
(run-program "printf" '("Hello\\nWorld\\n") :wait nil)
(let ((process (run-program "printf" '("Hello\\nWorld\\n") :wait nil :output :stream)))
(check equal '("Hello" "World")
(unwind-protect
(loop
:for line = (read-line (process-output process) nil nil)
:while line :collect line)
(close (process-output process)))))
(with-open-file (out "TESTOUT.TXT"
:direction :output :if-does-not-exist :create :if-exists :supersede
#+ccl :sharing #+ccl :lock)
(run-program "printf" '("Hello\\nWorld\\n") :wait nil :output out)
(sleep 1))
(check equal '("Hello" "World") (text-file-contents "TESTOUT.TXT"))
(with-open-file (out "TESTOUT.TXT"
:direction :output :if-does-not-exist :create :if-exists :supersede
#+ccl :sharing #+ccl :lock)
(run-program "printf" '("Hello\\nWorld\\n") :wait t :output out))
(check equal '("Hello" "World") (text-file-contents "TESTOUT.TXT"))
(run-program "sort" '() :environment '(("LC_CTYPE" . "C") ("LC_COLLATE" . "C"))
:wait nil :input "TESTINP.TXT" :output "TESTOUT.TXT")
(sleep 1)
(check-sorted-output-file)
(with-open-file (out "TESTOUT.TXT"
:direction :output :if-does-not-exist :create :if-exists :supersede
#+ccl :sharing #+ccl :lock)
(run-program "sort" '() :environment '(("LC_CTYPE" . "C") ("LC_COLLATE" . "C"))
:wait t :input "TESTINP.TXT" :output out))
(check-sorted-output-file)
(with-open-file (inp "TESTINP.TXT"
#+ccl :sharing #+ccl :lock)
(run-program "sort" '() :environment '(("LC_CTYPE" . "C") ("LC_COLLATE" . "C"))
:wait t :input inp :output "TESTOUT.TXT"))
(check-sorted-output-file)
(with-open-file (out "TESTOUT.TXT"
:direction :output :if-does-not-exist :create :if-exists :supersede
#+ccl :sharing #+ccl :lock)
(with-open-file (inp "TESTINP.TXT"
#+ccl :sharing #+ccl :lock)
(run-program "sort" '() :environment '(("LC_CTYPE" . "C") ("LC_COLLATE" . "C"))
:wait t :input inp :output out)))
(check-sorted-output-file)
(let ((process (run-program "sort" '() :environment '(("LC_CTYPE" . "C") ("LC_COLLATE" . "C"))
:wait nil :input :stream :output :stream :error nil)))
(with-open-file (testinp "TESTINP.TXT"
#+ccl :sharing #+ccl :lock)
(loop :for line = (read-line testinp nil nil)
:while line :do (write-line line (process-input process))))
(close (process-input process))
(check-sorted-output-stream (process-output process))
(close (process-output process)))
(mapc (lambda (file) (ignore-errors (delete-file file)))
'("TESTINP.TXT" "TESTOUT.TXT" "TESTERR.TXT")))
(defun test/all ()
(test/run-program :verbose nil))
|
eac55e15b930fc10708d7a5447e241cc28fac4b22a8672c864e81a70da8e4906 | nubank/midje-nrepl | core.clj | (ns octocat.core)
(* 7 8)
| null | https://raw.githubusercontent.com/nubank/midje-nrepl/b4d505f346114db88ad5b5c6b3c8f0af4e0136fc/dev-resources/octocat/src/octocat/core.clj | clojure | (ns octocat.core)
(* 7 8)
| |
1bbb8a04401f1e05aa3dca6726de5937497d0fc978fc19b4fe8bfb5bb6584ae5 | robert-strandh/SICL | use-package-defun.lisp | (cl:in-package #:sicl-package)
(defun use-package
(designators-of-packages-to-use &optional package-designator)
(when (atom designators-of-packages-to-use)
(setf designators-of-packages-to-use
(list designators-of-packages-to-use)))
(unless (proper-list-p designators-of-packages-to-use)
(error 'use-list-must-be-proper-list
:datum designators-of-packages-to-use))
(let ((packages-to-use
(mapcar #'package-designator-to-package
designators-of-packages-to-use))
(package (package-designator-to-package package-designator))
(conflicts (make-hash-table :test #'equal)))
(flet ((maybe-add-symbol (name symbol)
(unless (nth-value 1 (gethash name (shadowing-symbols package)))
(pushnew symbol (gethash name conflicts '()) :test #'eq))))
(loop for package-to-use in packages-to-use
do (do-external-symbols (symbol package-to-use)
(maybe-add-symbol (symbol-name symbol) symbol)))
(loop for used-package in (use-list package)
do (do-external-symbols (symbol used-package)
(maybe-add-symbol (symbol-name symbol) symbol)))
(maphash (lambda (name symbol)
(maybe-add-symbol name symbol))
(external-symbols package))
(maphash (lambda (name symbol)
(maybe-add-symbol name symbol))
(internal-symbols package)))
(loop for shadowing-symbol in (shadowing-symbols package)
do (remhash (symbol-name shadowing-symbol) conflicts))
(loop for symbols being each hash-value of conflicts
when (> (length symbols) 1)
do (let ((choice (resolve-conflict symbols package)))
(if (symbol-is-present-p choice package)
;; The choice was a symbol that is already
;; present in PACKAGE, and we had a conflict
;; involving that symbol, so it can not have been
;; a shadowing symbol. Make it one.
(push choice (shadowing-symbols package))
;; The choice was a symbol in one of the packages
;; to use. The chosen symbol must be turned into
;; a shadowing symbol in PACKAGE.
(let ((name (symbol-name choice)))
(remhash name (internal-symbols package))
(remhash name (external-symbols package))
(setf (shadowing-symbols package)
(remove name (shadowing-symbols package)
:key #'symbol-name
:test #'equal))
(setf (gethash name (internal-symbols package))
choice)
(push choice (shadowing-symbols package))))))
(loop for package-to-use in packages-to-use
do (pushnew package-to-use (use-list package) :test #'eq)
(pushnew package (used-by-list package-to-use) :test #'eq))))
| null | https://raw.githubusercontent.com/robert-strandh/SICL/65d7009247b856b2c0f3d9bb41ca7febd3cd641b/Code/Package/use-package-defun.lisp | lisp | The choice was a symbol that is already
present in PACKAGE, and we had a conflict
involving that symbol, so it can not have been
a shadowing symbol. Make it one.
The choice was a symbol in one of the packages
to use. The chosen symbol must be turned into
a shadowing symbol in PACKAGE. | (cl:in-package #:sicl-package)
(defun use-package
(designators-of-packages-to-use &optional package-designator)
(when (atom designators-of-packages-to-use)
(setf designators-of-packages-to-use
(list designators-of-packages-to-use)))
(unless (proper-list-p designators-of-packages-to-use)
(error 'use-list-must-be-proper-list
:datum designators-of-packages-to-use))
(let ((packages-to-use
(mapcar #'package-designator-to-package
designators-of-packages-to-use))
(package (package-designator-to-package package-designator))
(conflicts (make-hash-table :test #'equal)))
(flet ((maybe-add-symbol (name symbol)
(unless (nth-value 1 (gethash name (shadowing-symbols package)))
(pushnew symbol (gethash name conflicts '()) :test #'eq))))
(loop for package-to-use in packages-to-use
do (do-external-symbols (symbol package-to-use)
(maybe-add-symbol (symbol-name symbol) symbol)))
(loop for used-package in (use-list package)
do (do-external-symbols (symbol used-package)
(maybe-add-symbol (symbol-name symbol) symbol)))
(maphash (lambda (name symbol)
(maybe-add-symbol name symbol))
(external-symbols package))
(maphash (lambda (name symbol)
(maybe-add-symbol name symbol))
(internal-symbols package)))
(loop for shadowing-symbol in (shadowing-symbols package)
do (remhash (symbol-name shadowing-symbol) conflicts))
(loop for symbols being each hash-value of conflicts
when (> (length symbols) 1)
do (let ((choice (resolve-conflict symbols package)))
(if (symbol-is-present-p choice package)
(push choice (shadowing-symbols package))
(let ((name (symbol-name choice)))
(remhash name (internal-symbols package))
(remhash name (external-symbols package))
(setf (shadowing-symbols package)
(remove name (shadowing-symbols package)
:key #'symbol-name
:test #'equal))
(setf (gethash name (internal-symbols package))
choice)
(push choice (shadowing-symbols package))))))
(loop for package-to-use in packages-to-use
do (pushnew package-to-use (use-list package) :test #'eq)
(pushnew package (used-by-list package-to-use) :test #'eq))))
|
3cf9d1b85bd6c0d7e258362a357c704c6414cca544a3e3e9cc9dd67aa7250cce | ucsd-progsys/liquidhaskell | Slice.hs | # LANGUAGE FlexibleInstances #
# LANGUAGE FlexibleContexts #
{-# LANGUAGE DerivingVia #-}
| This module has a function that computes the " slice " i.e. subset of the ` Ms. ` that
we actually need to verify a given target module , so that LH does n't choke trying to resolve
-- names that are not actually relevant and hence, not in the GHC Environment.
See LH issue 1773 for more details .
--
-- Specifically, this module has datatypes and code for building a Specification Dependency Graph
-- whose vertices are 'names' that need to be resolve, and edges are 'dependencies'.
module Language.Haskell.Liquid.Bare.Slice (sliceSpecs) where
import qualified Language . . Types as F
import qualified Data . . Strict as M
import Language.Haskell.Liquid.Types
import Data . Hashable
import qualified Language.Haskell.Liquid.Measure as Ms
-- import qualified Data.HashSet as S
-------------------------------------------------------------------------------
-- | Top-level "slicing" function
-------------------------------------------------------------------------------
sliceSpecs :: GhcSrc -> Ms.BareSpec -> [(ModName, Ms.BareSpec)] ->
[(ModName, Ms.BareSpec)]
sliceSpecs _tgtSrc _tgtSpec specs = specs
-------------------------------------------------------------------------------
-- | The different kinds of names we have to resolve
-------------------------------------------------------------------------------
data Label
= Sign -- ^ identifier signature
| Func -- ^ measure or reflect
| DCon -- ^ data constructor
| TCon -- ^ type constructor
deriving ( Eq , Ord , , Show )
-------------------------------------------------------------------------------
-- | A dependency ' Node ' is a pair of a name @LocSymbol@ and @Label@
-------------------------------------------------------------------------------
data Node = MkNode
{ nodeName : : F.Symbol
, nodeLabel : : Label
}
deriving ( Eq , Ord )
instance Hashable Label where
hashWithSalt s = hashWithSalt s . fromEnum
instance where
hashWithSalt s MkNode { .. } = hashWithSalt s ( nodeName , nodeLabel )
newtype = MkDepGraph
{ : : M.HashMap [ Node ]
}
-------------------------------------------------------------------------------
-- | A way to combine graphs of multiple modules
-------------------------------------------------------------------------------
instance Semigroup where
x < > y = MkDepGraph { = M.unionWith ( + + ) ( ) ( y ) }
instance where
mempty = MkDepGraph mempty
-------------------------------------------------------------------------------
-- | A function to build the dependencies for each module
-------------------------------------------------------------------------------
mkRoots : : GhcSrc - > S.HashSet Node
mkRoots = undefined
-------------------------------------------------------------------------------
-- | A function to build the dependencies for each module
-------------------------------------------------------------------------------
class a where
mkGraph : : a - > DepGraph
instance [ Ms. ] where
mkGraph specs sp < - specs ]
instance Ms. where
mkGraph sp = mconcat
[ undefined -- FIXME -- mkGraph ( expSigs sp )
]
-------------------------------------------------------------------------------
-- | ' reachable roots g ' returns the list of Node transitively reachable from roots
-------------------------------------------------------------------------------
reachable : : S.HashSet Node - > DepGraph - > S.HashSet Node
reachable roots g = undefined -- _ TODO
-------------------------------------------------------------------------------
-- | Extract the dependencies
-------------------------------------------------------------------------------
class a where
deps : : a - > [ Node ]
instance where
deps = error " TBD : : bareType "
instance where
deps = error " TBD : : "
instance where
deps = error " TBD : : datactor "
-------------------------------------------------------------------------------
-- | The different kinds of names we have to resolve
-------------------------------------------------------------------------------
data Label
= Sign -- ^ identifier signature
| Func -- ^ measure or reflect
| DCon -- ^ data constructor
| TCon -- ^ type constructor
deriving (Eq, Ord, Enum, Show)
-------------------------------------------------------------------------------
-- | A dependency 'Node' is a pair of a name @LocSymbol@ and @Label@
-------------------------------------------------------------------------------
data Node = MkNode
{ nodeName :: F.Symbol
, nodeLabel :: Label
}
deriving (Eq, Ord)
instance Hashable Label where
hashWithSalt s = hashWithSalt s . fromEnum
instance Hashable Node where
hashWithSalt s MkNode {..} = hashWithSalt s (nodeName, nodeLabel)
newtype DepGraph = MkDepGraph
{ dGraph :: M.HashMap Node [Node]
}
-------------------------------------------------------------------------------
-- | A way to combine graphs of multiple modules
-------------------------------------------------------------------------------
instance Semigroup DepGraph where
x <> y = MkDepGraph { dGraph = M.unionWith (++) (dGraph x) (dGraph y) }
instance Monoid DepGraph where
mempty = MkDepGraph mempty
-------------------------------------------------------------------------------
-- | A function to build the dependencies for each module
-------------------------------------------------------------------------------
mkRoots :: GhcSrc -> S.HashSet Node
mkRoots = undefined
-------------------------------------------------------------------------------
-- | A function to build the dependencies for each module
-------------------------------------------------------------------------------
class Graph a where
mkGraph :: a -> DepGraph
instance Graph [Ms.BareSpec] where
mkGraph specs = mconcat [ mkGraph sp | sp <- specs]
instance Graph Ms.BareSpec where
mkGraph sp = mconcat
[ undefined -- FIXME -- mkGraph (expSigs sp)
]
-------------------------------------------------------------------------------
-- | 'reachable roots g' returns the list of Node transitively reachable from roots
-------------------------------------------------------------------------------
reachable :: S.HashSet Node -> DepGraph -> S.HashSet Node
reachable roots g = undefined -- _TODO
-------------------------------------------------------------------------------
-- | Extract the dependencies
-------------------------------------------------------------------------------
class Deps a where
deps :: a -> [Node]
instance Deps BareType where
deps = error "TBD:deps:bareType"
instance Deps DataDecl where
deps = error "TBD:deps:datadecl"
instance Deps DataCtor where
deps = error "TBD:deps:datactor"
-}
-- = [ ( n , slice nodes sp ) | ( n , sp ) < - specs ]
-- where
-- tgtGraph = mkGraph tgtSpec
-- impGraph = mkGraph ( snd < $ > specs )
-- roots = mkRoots tgtSrc -- S.fromList . M.keys . $ tgtGraph
-- nodes = reachable roots ( tgtGraph < > impGraph )
class Sliceable a where
slice : : S.HashSet Node - > a - > a
instance Sliceable Ms. where
slice nodes sp = sp
-- = [ (n, slice nodes sp) | (n, sp) <- specs ]
-- where
-- tgtGraph = mkGraph tgtSpec
-- impGraph = mkGraph (snd <$> specs)
-- roots = mkRoots tgtSrc -- S.fromList . M.keys . dGraph $ tgtGraph
-- nodes = reachable roots (tgtGraph <> impGraph)
class Sliceable a where
slice :: S.HashSet Node -> a -> a
instance Sliceable Ms.BareSpec where
slice nodes sp = sp
-}
----
These are the fields we have to worry about
unsafeFromLiftedSpec : : LiftedSpec - > Spec LocBareType F.LocSymbol
unsafeFromLiftedSpec a = Spec
{
--- > > > , asmSigs = S.toList . liftedAsmSigs $ a
--- > > > , = S.toList . liftedSigs $ a
--- > > > , invariants = S.toList . $ a
--- > > > , dataDecls = S.toList . liftedDataDecls $ a
--- > > > , newtyDecls = S.toList . liftedNewtyDecls $ a
, measures = S.toList . liftedMeasures $ a
, S.toList . liftedImpSigs $ a
, expSigs = S.toList . liftedExpSigs $ a
, ialiases = S.toList . liftedIaliases $ a
, imports = S.toList . liftedImports $ a
, aliases = S.toList . liftedAliases $ a
, ealiases = S.toList . liftedEaliases $ a
, embeds = liftedEmbeds a
, qualifiers = S.toList . liftedQualifiers $ a
, = S.toList . liftedDecr $ a
, lvars = liftedLvars a
, autois = liftedAutois a
, autosize = liftedAutosize a
, cmeasures = S.toList . $ a
, imeasures = S.toList . liftedImeasures $ a
, classes = S.toList . liftedClasses $ a
, claws = S.toList . liftedClaws $ a
, rinstance = S.toList . liftedRinstance $ a
, ilaws = S.toList . liftedIlaws $ a
, dvariance = S.toList . $ a
, bounds = liftedBounds a
, = liftedDefs a
, = S.toList . liftedAxeqs $ a
}
These are the fields we have to worry about
unsafeFromLiftedSpec :: LiftedSpec -> Spec LocBareType F.LocSymbol
unsafeFromLiftedSpec a = Spec
{
--->>> , asmSigs = S.toList . liftedAsmSigs $ a
--->>> , sigs = S.toList . liftedSigs $ a
--->>> , invariants = S.toList . liftedInvariants $ a
--->>> , dataDecls = S.toList . liftedDataDecls $ a
--->>> , newtyDecls = S.toList . liftedNewtyDecls $ a
, measures = S.toList . liftedMeasures $ a
, impSigs = S.toList . liftedImpSigs $ a
, expSigs = S.toList . liftedExpSigs $ a
, ialiases = S.toList . liftedIaliases $ a
, imports = S.toList . liftedImports $ a
, aliases = S.toList . liftedAliases $ a
, ealiases = S.toList . liftedEaliases $ a
, embeds = liftedEmbeds a
, qualifiers = S.toList . liftedQualifiers $ a
, decr = S.toList . liftedDecr $ a
, lvars = liftedLvars a
, autois = liftedAutois a
, autosize = liftedAutosize a
, cmeasures = S.toList . liftedCmeasures $ a
, imeasures = S.toList . liftedImeasures $ a
, classes = S.toList . liftedClasses $ a
, claws = S.toList . liftedClaws $ a
, rinstance = S.toList . liftedRinstance $ a
, ilaws = S.toList . liftedIlaws $ a
, dvariance = S.toList . liftedDvariance $ a
, bounds = liftedBounds a
, defs = liftedDefs a
, axeqs = S.toList . liftedAxeqs $ a
}
-}
| null | https://raw.githubusercontent.com/ucsd-progsys/liquidhaskell/c37ca0017f20070483ad0787e7f88f0223ac169a/src/Language/Haskell/Liquid/Bare/Slice.hs | haskell | # LANGUAGE DerivingVia #
names that are not actually relevant and hence, not in the GHC Environment.
Specifically, this module has datatypes and code for building a Specification Dependency Graph
whose vertices are 'names' that need to be resolve, and edges are 'dependencies'.
import qualified Data.HashSet as S
-----------------------------------------------------------------------------
| Top-level "slicing" function
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
| The different kinds of names we have to resolve
-----------------------------------------------------------------------------
^ identifier signature
^ measure or reflect
^ data constructor
^ type constructor
-----------------------------------------------------------------------------
| A dependency ' Node ' is a pair of a name @LocSymbol@ and @Label@
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
| A way to combine graphs of multiple modules
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
| A function to build the dependencies for each module
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
| A function to build the dependencies for each module
-----------------------------------------------------------------------------
FIXME -- mkGraph ( expSigs sp )
-----------------------------------------------------------------------------
| ' reachable roots g ' returns the list of Node transitively reachable from roots
-----------------------------------------------------------------------------
_ TODO
-----------------------------------------------------------------------------
| Extract the dependencies
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
| The different kinds of names we have to resolve
-----------------------------------------------------------------------------
^ identifier signature
^ measure or reflect
^ data constructor
^ type constructor
-----------------------------------------------------------------------------
| A dependency 'Node' is a pair of a name @LocSymbol@ and @Label@
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
| A way to combine graphs of multiple modules
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
| A function to build the dependencies for each module
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
| A function to build the dependencies for each module
-----------------------------------------------------------------------------
FIXME -- mkGraph (expSigs sp)
-----------------------------------------------------------------------------
| 'reachable roots g' returns the list of Node transitively reachable from roots
-----------------------------------------------------------------------------
_TODO
-----------------------------------------------------------------------------
| Extract the dependencies
-----------------------------------------------------------------------------
= [ ( n , slice nodes sp ) | ( n , sp ) < - specs ]
where
tgtGraph = mkGraph tgtSpec
impGraph = mkGraph ( snd < $ > specs )
roots = mkRoots tgtSrc -- S.fromList . M.keys . $ tgtGraph
nodes = reachable roots ( tgtGraph < > impGraph )
= [ (n, slice nodes sp) | (n, sp) <- specs ]
where
tgtGraph = mkGraph tgtSpec
impGraph = mkGraph (snd <$> specs)
roots = mkRoots tgtSrc -- S.fromList . M.keys . dGraph $ tgtGraph
nodes = reachable roots (tgtGraph <> impGraph)
--
- > > > , asmSigs = S.toList . liftedAsmSigs $ a
- > > > , = S.toList . liftedSigs $ a
- > > > , invariants = S.toList . $ a
- > > > , dataDecls = S.toList . liftedDataDecls $ a
- > > > , newtyDecls = S.toList . liftedNewtyDecls $ a
->>> , asmSigs = S.toList . liftedAsmSigs $ a
->>> , sigs = S.toList . liftedSigs $ a
->>> , invariants = S.toList . liftedInvariants $ a
->>> , dataDecls = S.toList . liftedDataDecls $ a
->>> , newtyDecls = S.toList . liftedNewtyDecls $ a | # LANGUAGE FlexibleInstances #
# LANGUAGE FlexibleContexts #
| This module has a function that computes the " slice " i.e. subset of the ` Ms. ` that
we actually need to verify a given target module , so that LH does n't choke trying to resolve
See LH issue 1773 for more details .
module Language.Haskell.Liquid.Bare.Slice (sliceSpecs) where
import qualified Language . . Types as F
import qualified Data . . Strict as M
import Language.Haskell.Liquid.Types
import Data . Hashable
import qualified Language.Haskell.Liquid.Measure as Ms
sliceSpecs :: GhcSrc -> Ms.BareSpec -> [(ModName, Ms.BareSpec)] ->
[(ModName, Ms.BareSpec)]
sliceSpecs _tgtSrc _tgtSpec specs = specs
data Label
deriving ( Eq , Ord , , Show )
data Node = MkNode
{ nodeName : : F.Symbol
, nodeLabel : : Label
}
deriving ( Eq , Ord )
instance Hashable Label where
hashWithSalt s = hashWithSalt s . fromEnum
instance where
hashWithSalt s MkNode { .. } = hashWithSalt s ( nodeName , nodeLabel )
newtype = MkDepGraph
{ : : M.HashMap [ Node ]
}
instance Semigroup where
x < > y = MkDepGraph { = M.unionWith ( + + ) ( ) ( y ) }
instance where
mempty = MkDepGraph mempty
mkRoots : : GhcSrc - > S.HashSet Node
mkRoots = undefined
class a where
mkGraph : : a - > DepGraph
instance [ Ms. ] where
mkGraph specs sp < - specs ]
instance Ms. where
mkGraph sp = mconcat
]
reachable : : S.HashSet Node - > DepGraph - > S.HashSet Node
class a where
deps : : a - > [ Node ]
instance where
deps = error " TBD : : bareType "
instance where
deps = error " TBD : : "
instance where
deps = error " TBD : : datactor "
data Label
deriving (Eq, Ord, Enum, Show)
data Node = MkNode
{ nodeName :: F.Symbol
, nodeLabel :: Label
}
deriving (Eq, Ord)
instance Hashable Label where
hashWithSalt s = hashWithSalt s . fromEnum
instance Hashable Node where
hashWithSalt s MkNode {..} = hashWithSalt s (nodeName, nodeLabel)
newtype DepGraph = MkDepGraph
{ dGraph :: M.HashMap Node [Node]
}
instance Semigroup DepGraph where
x <> y = MkDepGraph { dGraph = M.unionWith (++) (dGraph x) (dGraph y) }
instance Monoid DepGraph where
mempty = MkDepGraph mempty
mkRoots :: GhcSrc -> S.HashSet Node
mkRoots = undefined
class Graph a where
mkGraph :: a -> DepGraph
instance Graph [Ms.BareSpec] where
mkGraph specs = mconcat [ mkGraph sp | sp <- specs]
instance Graph Ms.BareSpec where
mkGraph sp = mconcat
]
reachable :: S.HashSet Node -> DepGraph -> S.HashSet Node
class Deps a where
deps :: a -> [Node]
instance Deps BareType where
deps = error "TBD:deps:bareType"
instance Deps DataDecl where
deps = error "TBD:deps:datadecl"
instance Deps DataCtor where
deps = error "TBD:deps:datactor"
-}
class Sliceable a where
slice : : S.HashSet Node - > a - > a
instance Sliceable Ms. where
slice nodes sp = sp
class Sliceable a where
slice :: S.HashSet Node -> a -> a
instance Sliceable Ms.BareSpec where
slice nodes sp = sp
-}
These are the fields we have to worry about
unsafeFromLiftedSpec : : LiftedSpec - > Spec LocBareType F.LocSymbol
unsafeFromLiftedSpec a = Spec
{
, measures = S.toList . liftedMeasures $ a
, S.toList . liftedImpSigs $ a
, expSigs = S.toList . liftedExpSigs $ a
, ialiases = S.toList . liftedIaliases $ a
, imports = S.toList . liftedImports $ a
, aliases = S.toList . liftedAliases $ a
, ealiases = S.toList . liftedEaliases $ a
, embeds = liftedEmbeds a
, qualifiers = S.toList . liftedQualifiers $ a
, = S.toList . liftedDecr $ a
, lvars = liftedLvars a
, autois = liftedAutois a
, autosize = liftedAutosize a
, cmeasures = S.toList . $ a
, imeasures = S.toList . liftedImeasures $ a
, classes = S.toList . liftedClasses $ a
, claws = S.toList . liftedClaws $ a
, rinstance = S.toList . liftedRinstance $ a
, ilaws = S.toList . liftedIlaws $ a
, dvariance = S.toList . $ a
, bounds = liftedBounds a
, = liftedDefs a
, = S.toList . liftedAxeqs $ a
}
These are the fields we have to worry about
unsafeFromLiftedSpec :: LiftedSpec -> Spec LocBareType F.LocSymbol
unsafeFromLiftedSpec a = Spec
{
, measures = S.toList . liftedMeasures $ a
, impSigs = S.toList . liftedImpSigs $ a
, expSigs = S.toList . liftedExpSigs $ a
, ialiases = S.toList . liftedIaliases $ a
, imports = S.toList . liftedImports $ a
, aliases = S.toList . liftedAliases $ a
, ealiases = S.toList . liftedEaliases $ a
, embeds = liftedEmbeds a
, qualifiers = S.toList . liftedQualifiers $ a
, decr = S.toList . liftedDecr $ a
, lvars = liftedLvars a
, autois = liftedAutois a
, autosize = liftedAutosize a
, cmeasures = S.toList . liftedCmeasures $ a
, imeasures = S.toList . liftedImeasures $ a
, classes = S.toList . liftedClasses $ a
, claws = S.toList . liftedClaws $ a
, rinstance = S.toList . liftedRinstance $ a
, ilaws = S.toList . liftedIlaws $ a
, dvariance = S.toList . liftedDvariance $ a
, bounds = liftedBounds a
, defs = liftedDefs a
, axeqs = S.toList . liftedAxeqs $ a
}
-}
|
5275433c82b0646129db12f2490425953a4d9ba2a80ce89ad3f1aacacc595924 | ninjudd/cake | test_fixtures.clj | ; NOTE: this test is from
Copyright ( c ) . All rights reserved .
; The use and distribution terms for this software are covered by the
; Eclipse Public License 1.0 (-1.0.php)
; which can be found in the file epl-v10.html at the root of this distribution.
; By using this software in any fashion, you are agreeing to be bound by
; the terms of this license.
; You must not remove this notice, or any other, from this software.
;
;;; test_fixtures.clj: unit tests for fixtures in test.clj
by
March 28 , 2009
(ns cake.tasks.test-fixtures
(:use clojure.test))
(declare *a* *b* *c* *d*)
(def *n* 0)
(defn fixture-a [f]
(binding [*a* 3] (f)))
(defn fixture-b [f]
(binding [*b* 5] (f)))
(defn fixture-c [f]
(binding [*c* 7] (f)))
(defn fixture-d [f]
(binding [*d* 11] (f)))
(defn inc-n-fixture [f]
(binding [*n* (inc *n*)] (f)))
(use-fixtures :once fixture-a fixture-b)
(use-fixtures :each fixture-c fixture-d inc-n-fixture)
(use-fixtures :each fixture-c fixture-d inc-n-fixture)
(deftest can-use-once-fixtures
(is (= 3 *a*))
(is (= 5 *b*)))
(deftest can-use-each-fixtures
(is (= 7 *c*))
(is (= 11 *d*)))
(deftest use-fixtures-replaces
(is (= *n* 1))) | null | https://raw.githubusercontent.com/ninjudd/cake/3a1627120b74e425ab21aa4d1b263be09e945cfd/test/old/cake/tasks/test_fixtures.clj | clojure | NOTE: this test is from
The use and distribution terms for this software are covered by the
Eclipse Public License 1.0 (-1.0.php)
which can be found in the file epl-v10.html at the root of this distribution.
By using this software in any fashion, you are agreeing to be bound by
the terms of this license.
You must not remove this notice, or any other, from this software.
test_fixtures.clj: unit tests for fixtures in test.clj | Copyright ( c ) . All rights reserved .
by
March 28 , 2009
(ns cake.tasks.test-fixtures
(:use clojure.test))
(declare *a* *b* *c* *d*)
(def *n* 0)
(defn fixture-a [f]
(binding [*a* 3] (f)))
(defn fixture-b [f]
(binding [*b* 5] (f)))
(defn fixture-c [f]
(binding [*c* 7] (f)))
(defn fixture-d [f]
(binding [*d* 11] (f)))
(defn inc-n-fixture [f]
(binding [*n* (inc *n*)] (f)))
(use-fixtures :once fixture-a fixture-b)
(use-fixtures :each fixture-c fixture-d inc-n-fixture)
(use-fixtures :each fixture-c fixture-d inc-n-fixture)
(deftest can-use-once-fixtures
(is (= 3 *a*))
(is (= 5 *b*)))
(deftest can-use-each-fixtures
(is (= 7 *c*))
(is (= 11 *d*)))
(deftest use-fixtures-replaces
(is (= *n* 1))) |
184ef9771cf5ccbc3546b3711760abb120b83b5c7828fe7a05a3a4d9d6b23111 | ferd/calcalc | calcalc_day_of_week.erl | -module(calcalc_day_of_week).
-compile(export_all).
-import(calcalc_math, [mod/2]).
sunday() -> 0.
monday() -> 1.
tuesday() -> 2.
wednesday() -> 3.
thursday() -> 4.
friday() -> 5.
saturday() -> 6.
from_fixed(Date) ->
mod(Date - calcalc:fixed(0) - sunday(), 7).
first_kday(K, Date) -> nth_kday(1, K, Date).
last_kday(K, Date) -> nth_kday(-1, K, Date).
%% N=0 is undefined
-spec nth_kday(pos_integer()|neg_integer(), integer(), calcalc:fixed()) -> calcalc:fixed().
nth_kday(N, K, Date) when N > 0 ->
7*N + kday_before(K, Date);
nth_kday(N, K, Date) when N < 0 ->
7*N + kday_after(K, Date).
Kth day of the week on or before fixed date ` Date '
-spec kday_on_or_before(integer(), calcalc:fixed()) -> calcalc:fixed().
kday_on_or_before(K, Date) ->
Date - from_fixed(Date-K).
-spec kday_on_or_after(integer(), calcalc:fixed()) -> calcalc:fixed().
kday_on_or_after(K, Date) ->
kday_on_or_before(K, Date+6).
-spec kday_nearest(integer(), calcalc:fixed()) -> calcalc:fixed().
kday_nearest(K, Date) ->
kday_on_or_before(K, Date+3).
-spec kday_before(integer(), calcalc:fixed()) -> calcalc:fixed().
kday_before(K, Date) ->
kday_on_or_before(K, Date-1).
-spec kday_after(integer(), calcalc:fixed()) -> calcalc:fixed().
kday_after(K, Date) ->
kday_on_or_before(K, Date+7).
| null | https://raw.githubusercontent.com/ferd/calcalc/d16eec3512d7b4402b1ddde82128f2483e955e98/src/calcalc_day_of_week.erl | erlang | N=0 is undefined | -module(calcalc_day_of_week).
-compile(export_all).
-import(calcalc_math, [mod/2]).
sunday() -> 0.
monday() -> 1.
tuesday() -> 2.
wednesday() -> 3.
thursday() -> 4.
friday() -> 5.
saturday() -> 6.
from_fixed(Date) ->
mod(Date - calcalc:fixed(0) - sunday(), 7).
first_kday(K, Date) -> nth_kday(1, K, Date).
last_kday(K, Date) -> nth_kday(-1, K, Date).
-spec nth_kday(pos_integer()|neg_integer(), integer(), calcalc:fixed()) -> calcalc:fixed().
nth_kday(N, K, Date) when N > 0 ->
7*N + kday_before(K, Date);
nth_kday(N, K, Date) when N < 0 ->
7*N + kday_after(K, Date).
Kth day of the week on or before fixed date ` Date '
-spec kday_on_or_before(integer(), calcalc:fixed()) -> calcalc:fixed().
kday_on_or_before(K, Date) ->
Date - from_fixed(Date-K).
-spec kday_on_or_after(integer(), calcalc:fixed()) -> calcalc:fixed().
kday_on_or_after(K, Date) ->
kday_on_or_before(K, Date+6).
-spec kday_nearest(integer(), calcalc:fixed()) -> calcalc:fixed().
kday_nearest(K, Date) ->
kday_on_or_before(K, Date+3).
-spec kday_before(integer(), calcalc:fixed()) -> calcalc:fixed().
kday_before(K, Date) ->
kday_on_or_before(K, Date-1).
-spec kday_after(integer(), calcalc:fixed()) -> calcalc:fixed().
kday_after(K, Date) ->
kday_on_or_before(K, Date+7).
|
4800d2d164de94228bdc7168317be719d4498399f5a65c4d5550c9195918bdf6 | xu-hao/QueryArrow | Config.hs | # LANGUAGE DeriveGeneric , TemplateHaskell #
module QueryArrow.RPC.Config where
import Data.Aeson
import GHC.Generics
data TCPServerConfig = TCPServerConfig {
tcp_server_addr :: String,
tcp_server_port :: Int
} deriving (Show, Generic)
data HTTPServerConfig = HTTPServerConfig {
http_server_port :: Int
} deriving (Show, Generic)
data FileSystemServerConfig = FileSystemServerConfig {
fs_server_addr :: String,
fs_server_port :: Int,
fs_server_root :: String
} deriving (Show, Generic)
data UDSServerConfig = UDSServerConfig {
uds_server_addr :: String
} deriving (Show, Generic)
instance FromJSON TCPServerConfig
instance ToJSON TCPServerConfig
instance FromJSON HTTPServerConfig
instance ToJSON HTTPServerConfig
instance FromJSON FileSystemServerConfig
instance ToJSON FileSystemServerConfig
instance FromJSON UDSServerConfig
instance ToJSON UDSServerConfig
| null | https://raw.githubusercontent.com/xu-hao/QueryArrow/4dd5b8a22c8ed2d24818de5b8bcaa9abc456ef0d/QueryArrow-rpc-common/src/QueryArrow/RPC/Config.hs | haskell | # LANGUAGE DeriveGeneric , TemplateHaskell #
module QueryArrow.RPC.Config where
import Data.Aeson
import GHC.Generics
data TCPServerConfig = TCPServerConfig {
tcp_server_addr :: String,
tcp_server_port :: Int
} deriving (Show, Generic)
data HTTPServerConfig = HTTPServerConfig {
http_server_port :: Int
} deriving (Show, Generic)
data FileSystemServerConfig = FileSystemServerConfig {
fs_server_addr :: String,
fs_server_port :: Int,
fs_server_root :: String
} deriving (Show, Generic)
data UDSServerConfig = UDSServerConfig {
uds_server_addr :: String
} deriving (Show, Generic)
instance FromJSON TCPServerConfig
instance ToJSON TCPServerConfig
instance FromJSON HTTPServerConfig
instance ToJSON HTTPServerConfig
instance FromJSON FileSystemServerConfig
instance ToJSON FileSystemServerConfig
instance FromJSON UDSServerConfig
instance ToJSON UDSServerConfig
| |
80c278adbcc7663d4d0c5dd2efd3106211323fc6add11d80071dccfc2a574053 | asmyczek/simple-avro | schema_tests.clj | (ns simple-avro.schema-tests
(:use (simple-avro schema core)
(clojure test)))
(deftest test-prim-types
(is (= avro-null {:type "null"}))
(is (= avro-boolean {:type "boolean"}))
(is (= avro-int {:type "int"}))
(is (= avro-long {:type "long"}))
(is (= avro-float {:type "float"}))
(is (= avro-double {:type "double"}))
(is (= avro-bytes {:type "bytes"}))
(is (= avro-string {:type "string"})))
(deftest test-complex-types
(is (= (avro-array avro-int) {:type "array" :items {:type "int"}}))
(is (= (avro-map avro-string) {:type "map" :values {:type "string"}}))
(is (= (avro-union avro-string avro-int avro-null)
[{:type "string"} {:type "int"} {:type "null"}])))
(deftest test-named-types
(is (= (avro-fixed "MyFixed" 16)
{:type "fixed" :size 16 :name "MyFixed"}))
(is (= (avro-enum "MyEnum" "A" "B" "C")
{:type "enum" :symbols ["A" "B" "C"] :name "MyEnum"}))
(is (= (avro-record "MyRecord"
"f1" avro-int
"f2" avro-string)
{:type "record"
:name "MyRecord"
:fields [{:name "f1" :type {:type "int"}}
{:name "f2" :type {:type "string"}}]})))
(defavro-fixed MyDefFixed 16)
(defavro-enum MyDefEnum "A" "B" "C")
(defavro-record MyDefRecord
"f1" avro-int
"f2" avro-string)
(deftest test-defavro
(is (= MyDefFixed {:type "fixed" :size 16 :name "MyDefFixed"}))
(is (= MyDefEnum {:type "enum" :symbols ["A" "B" "C"] :name "MyDefEnum"}))
(is (= MyDefRecord
{:type "record"
:name "MyDefRecord"
:fields [{:name "f1" :type {:type "int"}}
{:name "f2" :type {:type "string"}}]})))
(deftest test-opts
(is (= (avro-fixed "MyFixed" 16 {:namespace "test-namespace"})
{:type "fixed" :size 16 :name "MyFixed" :namespace "test-namespace"}))
(is (= (avro-enum "MyEnum" {:namespace "test-namespace"} "A" "B" "C")
{:type "enum" :symbols ["A" "B" "C"] :name "MyEnum" :namespace "test-namespace"}))
(is (= (avro-record "MyRecord" {:namespace "test-namespace"}
"f1" avro-int
"f2" avro-string)
{:type "record"
:name "MyRecord"
:namespace "test-namespace"
:fields [{:name "f1" :type {:type "int"}}
{:name "f2" :type {:type "string"}}]})))
| null | https://raw.githubusercontent.com/asmyczek/simple-avro/25825319e008316e20e9d4d867e2d88fcd389c7c/test/simple_avro/schema_tests.clj | clojure | (ns simple-avro.schema-tests
(:use (simple-avro schema core)
(clojure test)))
(deftest test-prim-types
(is (= avro-null {:type "null"}))
(is (= avro-boolean {:type "boolean"}))
(is (= avro-int {:type "int"}))
(is (= avro-long {:type "long"}))
(is (= avro-float {:type "float"}))
(is (= avro-double {:type "double"}))
(is (= avro-bytes {:type "bytes"}))
(is (= avro-string {:type "string"})))
(deftest test-complex-types
(is (= (avro-array avro-int) {:type "array" :items {:type "int"}}))
(is (= (avro-map avro-string) {:type "map" :values {:type "string"}}))
(is (= (avro-union avro-string avro-int avro-null)
[{:type "string"} {:type "int"} {:type "null"}])))
(deftest test-named-types
(is (= (avro-fixed "MyFixed" 16)
{:type "fixed" :size 16 :name "MyFixed"}))
(is (= (avro-enum "MyEnum" "A" "B" "C")
{:type "enum" :symbols ["A" "B" "C"] :name "MyEnum"}))
(is (= (avro-record "MyRecord"
"f1" avro-int
"f2" avro-string)
{:type "record"
:name "MyRecord"
:fields [{:name "f1" :type {:type "int"}}
{:name "f2" :type {:type "string"}}]})))
(defavro-fixed MyDefFixed 16)
(defavro-enum MyDefEnum "A" "B" "C")
(defavro-record MyDefRecord
"f1" avro-int
"f2" avro-string)
(deftest test-defavro
(is (= MyDefFixed {:type "fixed" :size 16 :name "MyDefFixed"}))
(is (= MyDefEnum {:type "enum" :symbols ["A" "B" "C"] :name "MyDefEnum"}))
(is (= MyDefRecord
{:type "record"
:name "MyDefRecord"
:fields [{:name "f1" :type {:type "int"}}
{:name "f2" :type {:type "string"}}]})))
(deftest test-opts
(is (= (avro-fixed "MyFixed" 16 {:namespace "test-namespace"})
{:type "fixed" :size 16 :name "MyFixed" :namespace "test-namespace"}))
(is (= (avro-enum "MyEnum" {:namespace "test-namespace"} "A" "B" "C")
{:type "enum" :symbols ["A" "B" "C"] :name "MyEnum" :namespace "test-namespace"}))
(is (= (avro-record "MyRecord" {:namespace "test-namespace"}
"f1" avro-int
"f2" avro-string)
{:type "record"
:name "MyRecord"
:namespace "test-namespace"
:fields [{:name "f1" :type {:type "int"}}
{:name "f2" :type {:type "string"}}]})))
| |
161cc837c2fc058b81acfde531eeb42b17ee9482ff489e84e60d9546c7fb0d39 | szynwelski/nlambda | MetaPlugin.hs | module MetaPlugin where
import Avail
import qualified BooleanFormula as BF
import Class
import CoAxiom hiding (toUnbranchedList)
import Control.Applicative ((<|>))
import Control.Monad (liftM)
import Data.Char (isLetter, isLower)
import Data.Foldable (foldlM)
import Data.List ((\\), delete, find, findIndex, intersect, isInfixOf, isPrefixOf, nub, partition)
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Maybe (catMaybes, fromJust, fromMaybe, isJust, isNothing, listToMaybe, mapMaybe)
import Data.String.Utils (replace)
import GhcPlugins hiding (mkApps, mkLocalVar, substTy)
import InstEnv (ClsInst, instanceDFunId, instanceHead, instanceRoughTcs, is_cls_nm, is_flag, is_orphan, mkImportedInstance)
import Kind (defaultKind, isOpenTypeKind)
import Meta
import MkId (mkDataConWorkId, mkDictSelRhs)
import Pair (pFst, pSnd)
import TypeRep
import TcType (tcSplitSigmaTy, tcSplitPhiTy)
import Unify (tcUnifyTy)
plugin :: Plugin
plugin = defaultPlugin {
installCoreToDos = install
}
install :: [CommandLineOption] -> [CoreToDo] -> CoreM [CoreToDo]
install _ todo = do
reinitializeGlobals
env <- getHscEnv
let metaPlug = CoreDoPluginPass "MetaPlugin" $ pass env False
let showPlug = CoreDoPluginPass "ShowPlugin" $ pass env True
-- return $ showPlug:todo
return $ metaPlug:todo
return $ metaPlug : todo + + [ showPlug ]
modInfo :: Outputable a => String -> (ModGuts -> a) -> ModGuts -> CoreM ()
modInfo label fun guts = putMsg $ text label <> text ": " <> (ppr $ fun guts)
headPanic :: String -> SDoc -> [a] -> a
headPanic msg doc [] = pprPanic ("headPanic - " ++ msg) doc
headPanic _ _ l = head l
tailPanic :: String -> SDoc -> [a] -> [a]
tailPanic msg doc [] = pprPanic ("tailPanic - " ++ msg) doc
tailPanic _ _ l = tail l
pprE :: String -> CoreExpr -> SDoc
pprE n e = text (n ++ " =") <+> ppr e <+> text "::" <+> ppr (exprType e)
pprV :: String -> CoreBndr -> SDoc
pprV n v = text (n ++ " =") <+> ppr v <+> text "::" <+> ppr (varType v)
pass :: HscEnv -> Bool -> ModGuts -> CoreM ModGuts
pass env onlyShow guts =
if withMetaAnnotation guts
then do putMsg $ text "Ignore module: " <+> (ppr $ mg_module guts)
return guts
else do putMsg $ text ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> start:"
<+> (ppr $ mg_module guts)
<+> if onlyShow then text "[only show]" else text ""
mod info - all info in one place
let metaMods = getMetaModules env
let mod = modInfoEmptyMaps env guts metaMods
-- imported maps
let (impNameMap, impVarMap, impTcMap) = getImportedMaps mod
-- names
let metaNameMap = getMetaPreludeNameMap mod
nameMap <- mkNamesMap guts $ Map.union impNameMap metaNameMap
let mod' = mod {nameMap = nameMap}
-- classes and vars
let tcMap = mkTyConMap mod' {varMap = unionVarMaps varMap impVarMap} (mg_tcs guts)
varMap = mkVarMap mod' {tcMap = unionTcMaps tcMap impTcMap}
let mod'' = mod' {tcMap = unionTcMaps tcMap impTcMap, varMap = unionVarMaps varMap impVarMap}
guts' <- if onlyShow then return guts else newGuts mod'' guts
-- show info
-- putMsg $ text "binds:\n" <+> (foldr (<+>) (text "") $ map showBind $ mg_binds guts' ++ getImplicitBinds guts')
putMsg $ text " classes:\n " < + > ( vcat $ fmap showClass $ getClasses guts ' )
-- modInfo "module" mg_module guts'
modInfo " binds " ( . mg_binds ) guts '
-- modInfo "dependencies" (dep_mods . mg_deps) guts'
-- modInfo "imported" getImportedModules guts'
-- modInfo "exports" mg_exports guts'
-- modInfo "type constructors" mg_tcs guts'
-- modInfo "used names" mg_used_names guts'
-- modInfo "global rdr env" mg_rdr_env guts'
-- modInfo "fixities" mg_fix_env guts'
modInfo " class instances " mg_insts guts '
modInfo " family instances " mg_fam_insts guts '
-- modInfo "pattern synonyms" mg_patsyns guts'
-- modInfo "core rules" mg_rules guts'
-- modInfo "vect decls" mg_vect_decls guts'
-- modInfo "vect info" mg_vect_info guts'
-- modInfo "files" mg_dependent_files guts'
modInfo " classes " getClasses guts '
-- modInfo "implicit binds" getImplicitBinds guts'
-- modInfo "annotations" mg_anns guts'
putMsg $ text ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> end:" <+> (ppr $ mg_module guts')
return guts'
----------------------------------------------------------------------------------------
-- Mod info
----------------------------------------------------------------------------------------
data ModInfo = ModInfo {env :: HscEnv, guts :: ModGuts, metaModules :: [MetaModule], nameMap :: NameMap, tcMap :: TyConMap, varMap :: VarMap}
modInfoEmptyMaps :: HscEnv -> ModGuts -> [MetaModule] -> ModInfo
modInfoEmptyMaps env guts metaMods = ModInfo env guts metaMods Map.empty emptyTcMap emptyVarMap
instance Outputable ModInfo where
ppr mod = text "\n======== ModInfo =========================================================="
<+> showMap "\nNames" (nameMap mod) showName
<+> showMap "\nTyCons" (tcsWithPairs mod) showTyCon
<+> showMap "\nVars" (varsWithPairs mod) showVar
<+> text "\nAll type cons:" <+> vcat (fmap showTyCon $ allTcs mod)
<+> text "\nAll vars:" <+> vcat (fmap showVar $ allVars mod)
<+> text "\n==========================================================================="
showMap :: String -> Map a a -> (a -> SDoc) -> SDoc
showMap header map showElem = text (header ++ ":\n")
<+> (vcat (concatMap (\(x,y) -> [showElem x <+> text "->" <+> showElem y]) $ Map.toList map))
----------------------------------------------------------------------------------------
-- Guts
----------------------------------------------------------------------------------------
newGuts :: ModInfo -> ModGuts -> CoreM ModGuts
newGuts mod guts = do binds <- newBinds mod (getDataCons guts) (mg_binds guts)
binds' <- replaceMocksByInstancesInProgram mod (checkCoreProgram binds)
let exps = newExports mod (mg_exports guts)
let usedNames = newUsedNames mod (mg_used_names guts)
let clsInsts = newClassInstances mod (mg_insts guts)
let tcs = filter (inCurrentModule mod) $ Map.elems (tcsWithPairs mod)
return $ guts {mg_tcs = mg_tcs guts ++ tcs,
mg_binds = mg_binds guts ++ checkCoreProgram binds',
mg_exports = mg_exports guts ++ exps,
mg_insts = mg_insts guts ++ clsInsts,
mg_used_names = usedNames}
----------------------------------------------------------------------------------------
-- Annotation
----------------------------------------------------------------------------------------
withMetaAnnotation :: ModGuts -> Bool
withMetaAnnotation guts = isJust $ find isMetaAnn $ mg_anns guts
where isMetaAnn a = case fromSerialized deserializeWithData $ ann_value a of
Just "WithMeta" -> True
_ -> False
----------------------------------------------------------------------------------------
-- Implicit Binds - copy from compiler/main/TidyPgm.hs
----------------------------------------------------------------------------------------
getImplicitBinds :: ModGuts -> [CoreBind]
getImplicitBinds guts = (concatMap getClassImplicitBinds $ getClasses guts) ++ (concatMap getTyConImplicitBinds $ mg_tcs guts)
getClassImplicitBinds :: Class -> [CoreBind]
getClassImplicitBinds cls
= [ NonRec op (mkDictSelRhs cls val_index)
| (op, val_index) <- classAllSelIds cls `zip` [0..] ]
getTyConImplicitBinds :: TyCon -> [CoreBind]
getTyConImplicitBinds tc = map get_defn (mapMaybe dataConWrapId_maybe (tyConDataCons tc))
get_defn :: Id -> CoreBind
get_defn id = NonRec id (unfoldingTemplate (realIdUnfolding id))
----------------------------------------------------------------------------------------
-- Names
----------------------------------------------------------------------------------------
type NameMap = Map Name Name
nameMember :: ModInfo -> Name -> Bool
nameMember mod name = Map.member name $ nameMap mod
newName :: ModInfo -> Name -> Name
newName mod name = Map.findWithDefault (pprPanic "unknown name: " (showName name <+> vcat (showName <$> Map.keys map))) name map
where map = nameMap mod
mkNamesMap :: ModGuts -> NameMap -> CoreM NameMap
mkNamesMap guts impNameMap = do nameMap <- mkSuffixNamesMap (getDataConsNames guts ++ getBindsNames guts ++ getClassesNames guts)
return $ Map.union nameMap impNameMap
nameSuffix :: String -> String
nameSuffix name = if any isLetter name then name_suffix else op_suffix
nlambdaName :: String -> String
nlambdaName name = name ++ nameSuffix name
mkSuffixNamesMap :: [Name] -> CoreM NameMap
mkSuffixNamesMap names = do names' <- mapM (createNewName nameSuffix) names
return $ Map.fromList $ zip names names'
createNewName :: (String -> String) -> Name -> CoreM Name
createNewName suffix name = let occName = nameOccName name
nameStr = occNameString occName
newOccName = mkOccName (occNameSpace occName) (nameStr ++ suffix nameStr)
in newUniqueName $ tidyNameOcc name newOccName
newUniqueName :: Name -> CoreM Name
newUniqueName name = do uniq <- getUniqueM
return $ setNameLoc (setNameUnique name uniq) noSrcSpan
getNameStr :: NamedThing a => a -> String
getNameStr = occNameString . nameOccName . getName
getModuleStr :: NamedThing a => a -> String
getModuleStr = maybe "" getModuleNameStr . nameModule_maybe . getName
getModuleNameStr :: Module -> String
getModuleNameStr = moduleNameString . moduleName
newUsedNames :: ModInfo -> NameSet -> NameSet
newUsedNames mod ns = mkNameSet (nms ++ nms')
where nms = nameSetElems ns
nms' = fmap (newName mod) $ filter (nameMember mod) nms
isPreludeThing :: NamedThing a => a -> Bool
isPreludeThing = (`elem` preludeModules) . getModuleStr
inCurrentModule :: NamedThing a => ModInfo -> a -> Bool
inCurrentModule mod x = mg_module (guts mod) == nameModule (getName x)
----------------------------------------------------------------------------------------
-- Data constructors
----------------------------------------------------------------------------------------
getDataCons :: ModGuts -> [DataCon]
getDataCons = concatMap tyConDataCons . filter (not . isClassTyCon) .filter isAlgTyCon . mg_tcs
getDataConsVars :: ModGuts -> [Var]
getDataConsVars = concatMap dataConImplicitIds . getDataCons
getDataConsNames :: ModGuts -> [Name]
getDataConsNames = concatMap (\dc -> dataConName dc : (idName <$> dataConImplicitIds dc)) . getDataCons
----------------------------------------------------------------------------------------
-- Variables
----------------------------------------------------------------------------------------
type VarMap = (Map Var Var, [Var])
emptyVarMap :: VarMap
emptyVarMap = (Map.empty, [])
varsWithPairs :: ModInfo -> Map Var Var
varsWithPairs = fst . varMap
allVars :: ModInfo -> [Var]
allVars mod = snd vm ++ Map.keys (fst vm) ++ Map.elems (fst vm)
where vm = varMap mod
unionVarMaps :: VarMap -> VarMap -> VarMap
unionVarMaps (m1,l1) (m2,l2) = (Map.union m1 m2, nub $ l1 ++ l2)
newVar :: ModInfo -> Var -> Var
newVar mod v = Map.findWithDefault (pprPanic "unknown variable: " (ppr v <+> ppr (Map.assocs map))) v map
where map = varsWithPairs mod
varMapMember :: ModInfo -> Var -> Bool
varMapMember mod v = Map.member v $ varsWithPairs mod
mkVarMap :: ModInfo -> VarMap
mkVarMap mod = let g = guts mod in mkMapWithVars mod (getBindsVars g ++ getClassesVars g ++ getDataConsVars g)
mkMapWithVars :: ModInfo -> [Var] -> VarMap
mkMapWithVars mod vars = (Map.fromList $ zip varsWithPairs $ fmap newVar varsWithPairs, nub (varsWithoutPairs ++ varsFromExprs))
where (varsWithPairs, varsWithoutPairs) = partition (not . isIgnoreImportType mod . varType) vars
varsFromExprs = getAllVarsFromBinds mod \\ varsWithPairs
newVar v = let t = changeType mod $ varType v
v' = mkExportedLocalVar
(newIdDetails $ idDetails v)
(newName mod $ varName v)
(maybe t (\c -> addVarContextForHigherOrderClass mod c t) (userClassOpId mod v))
vanillaIdInfo
in if isExportedId v then setIdExported v' else setIdNotExported v'
newIdDetails (RecSelId tc naughty) = RecSelId (newTyCon mod tc) naughty
newIdDetails (ClassOpId cls) = ClassOpId $ newClass mod cls
newIdDetails (PrimOpId op) = PrimOpId op
newIdDetails (FCallId call) = FCallId call
newIdDetails (DFunId n b) = DFunId n b
newIdDetails _ = VanillaId
getAllVarsFromBinds :: ModInfo -> [Var]
getAllVarsFromBinds = nub . concatMap getAllNotLocalVarsFromExpr . concatMap rhssOfBind . mg_binds . guts
mkVarUnique :: Var -> CoreM Var
mkVarUnique v = do uniq <- getUniqueM
return $ setVarUnique v uniq
mkLocalVar :: String -> Type -> CoreM Var
mkLocalVar varName ty = do uniq <- getUniqueM
let nm = mkInternalName uniq (mkVarOcc varName) noSrcSpan
return $ mkLocalId nm ty
mkPredVar :: (Class, [Type]) -> CoreM DictId
mkPredVar (cls, tys) = do uniq <- getUniqueM
let name = mkSystemName uniq (mkDictOcc (getOccName cls))
return $ mkLocalId name $ mkClassPred cls tys
isVar :: CoreExpr -> Bool
isVar (Var _) = True
isVar _ = False
----------------------------------------------------------------------------------------
-- Imports
----------------------------------------------------------------------------------------
importsToIgnore :: [Meta.ModuleName]
importsToIgnore = [metaModuleName, "GHC.Generics"]
isIgnoreImport :: Module -> Bool
isIgnoreImport = (`elem` importsToIgnore) . moduleNameString . moduleName
getImportedModules :: ModGuts -> [Module]
getImportedModules = filter (not . isIgnoreImport) . moduleEnvKeys . mg_dir_imps
getImportedMaps :: ModInfo -> (NameMap, VarMap, TyConMap)
getImportedMaps mod = (Map.fromList namePairs, (Map.fromList varPairs, varWithoutPair), (Map.fromList tcPairs, tcWithoutPair))
where mods = catMaybes $ fmap (lookupUFM $ hsc_HPT $ env mod) $ fmap moduleName $ getImportedModules (guts mod)
things = eltsUFM $ getModulesTyThings mods
(tcThings, varThings) = fmap (filter isTyThingId) $ partition isTyThingTyCon things
tcPairs = fmap (\(tt1, tt2) -> (tyThingTyCon tt1, tyThingTyCon tt2)) $ catMaybes $ findPair things TyThingTyCon <$> getName <$> tcThings
varPairs = fmap (\(tt1, tt2) -> (tyThingId tt1, tyThingId tt2)) $ catMaybes $ findPair things TyThingId <$> getName <$> varThings
tcWithoutPair = (tyThingTyCon <$> tcThings) \\ (uncurry (++) $ unzip $ tcPairs)
varWithoutPair = (tyThingId <$> varThings) \\ (uncurry (++) $ unzip $ varPairs)
getNamePair (x, y) = (getName x, getName y)
namePairs = (getNamePair <$> tcPairs) ++ (getNamePair <$> varPairs)
-- FIXME check if isAbstractTyCon should be used here
isIgnoreImportType :: ModInfo -> Type -> Bool
isIgnoreImportType mod = anyNameEnv (\tc -> (isIgnoreImport $ nameModule $ getName tc) || isAbstractTyCon tc || varC mod == tc) . tyConsOfType
----------------------------------------------------------------------------------------
-- Exports
----------------------------------------------------------------------------------------
newExports :: ModInfo -> Avails -> Avails
newExports mod avls = concatMap go avls
where go (Avail n) = [Avail $ newName mod n]
go (AvailTC nm nms) | nameMember mod nm = [AvailTC (newName mod nm) (newName mod <$> nms)]
go (AvailTC _ nms) = (Avail . newName mod) <$> (drop 1 nms)
----------------------------------------------------------------------------------------
-- Classes
----------------------------------------------------------------------------------------
getClasses :: ModGuts -> [Class]
getClasses = catMaybes . fmap tyConClass_maybe . mg_tcs
getClassDataCons :: Class -> [DataCon]
getClassDataCons = tyConDataCons . classTyCon
getClassesVars :: ModGuts -> [Var]
getClassesVars = concatMap (\c -> classAllSelIds c ++ (concatMap dataConImplicitIds $ getClassDataCons c)) . getClasses
getClassesNames :: ModGuts -> [Name]
getClassesNames = concatMap classNames . getClasses
where classNames c = className c : (fmap idName $ classAllSelIds c) ++ dataConNames c
dataConNames c = concatMap (\dc -> dataConName dc : (idName <$> dataConImplicitIds dc)) $ getClassDataCons c
type TyConMap = (Map TyCon TyCon, [TyCon])
emptyTcMap :: TyConMap
emptyTcMap = (Map.empty, [])
tcsWithPairs :: ModInfo -> Map TyCon TyCon
tcsWithPairs = fst . tcMap
allTcs :: ModInfo -> [TyCon]
allTcs mod = snd tcm ++ Map.keys (fst tcm) ++ Map.elems (fst tcm)
where tcm = tcMap mod
allClasses :: ModInfo -> [Class]
allClasses mod = [c | Just c <- tyConClass_maybe <$> allTcs mod]
unionTcMaps :: TyConMap -> TyConMap -> TyConMap
unionTcMaps (m1, l1) (m2, l2) = (Map.union m1 m2, nub $ l1 ++ l2)
newTyCon :: ModInfo -> TyCon -> TyCon
newTyCon mod tc = Map.findWithDefault metaPrelude tc $ fst $ tcMap mod
where metaPrelude = fromMaybe
(pprPgmError "Unknown type constructor:"
(ppr tc <+> text ("\nProbably module " ++ getModuleStr tc ++ " is not compiled with NLambda Plugin.")))
(getMetaPreludeTyCon mod tc)
newClass :: ModInfo -> Class -> Class
newClass mod = fromJust . tyConClass_maybe . newTyCon mod . classTyCon
mkTyConMap :: ModInfo -> [TyCon] -> TyConMap
mkTyConMap mod tcs = let ctcs = filter isClassTyCon tcs
ctcs' = fmap (newTyConClass mod {tcMap = tcMap}) ctcs
tcMap = (Map.fromList $ zip ctcs ctcs', filter isAlgTyCon tcs)
in tcMap
newTyConClass :: ModInfo -> TyCon -> TyCon
newTyConClass mod tc = let tc' = createTyConClass mod cls rhs tc
rhs = createAlgTyConRhs mod cls $ algTyConRhs tc
cls = createClass mod tc' $ fromJust $ tyConClass_maybe tc
in tc'
createTyConClass :: ModInfo -> Class -> AlgTyConRhs -> TyCon -> TyCon
createTyConClass mod cls rhs tc = mkClassTyCon
(newName mod $ tyConName tc)
(tyConKind tc)
FIXME new unique ty vars ?
(tyConRoles tc)
rhs
cls
(if isRecursiveTyCon tc then Recursive else NonRecursive)
createAlgTyConRhs :: ModInfo -> Class -> AlgTyConRhs -> AlgTyConRhs
createAlgTyConRhs mod cls rhs = create rhs
where create (AbstractTyCon b) = AbstractTyCon b
create DataFamilyTyCon = DataFamilyTyCon
create (DataTyCon dcs isEnum) = DataTyCon (createDataCon mod <$> dcs) isEnum
create (NewTyCon dc ntRhs ntEtadRhs ntCo) = NewTyCon (createDataCon mod dc)
(changeType mod ntRhs)
(changeType mod <$> ntEtadRhs)
(changeUnbranchedCoAxiom mod cls ntCo)
createDataCon :: ModInfo -> DataCon -> DataCon
createDataCon mod dc =
let name = newName mod $ dataConName dc
workerName = newName mod $ idName $ dataConWorkId dc
workerId = mkDataConWorkId workerName dc'
(univ_tvs, ex_tvs, eq_spec, theta, arg_tys, res_ty) = dataConFullSig dc
dc' = mkDataCon
name
(dataConIsInfix dc)
[]
[]
univ_tvs
ex_tvs
((\(tv, t) -> (tv, changeType mod t)) <$> eq_spec)
(changePredType mod <$> theta)
(changeType mod <$> arg_tys)
(changeType mod res_ty)
(newTyCon mod $ dataConTyCon dc)
(changePredType mod <$> dataConStupidTheta dc)
workerId
FIXME use mkDataConRep
in dc'
createClass :: ModInfo -> TyCon -> Class -> Class
createClass mod tc cls =
let (tyVars, funDeps, scTheta, scSels, ats, opStuff) = classExtraBigSig cls
scSels' = fmap (newVar mod) scSels
opStuff' = fmap (\(v, dm) -> (newVar mod v, updateDefMeth dm)) opStuff
in mkClass
tyVars
funDeps
FIXME new predType ?
scSels'
FIXME new associated types ?
opStuff'
(updateMinDef $ classMinimalDef cls)
tc
where updateDefMeth NoDefMeth = NoDefMeth
updateDefMeth (DefMeth n) = DefMeth $ newName mod n
updateDefMeth (GenDefMeth n) = GenDefMeth $ newName mod n
updateMinDef (BF.Var n) = BF.Var $ newName mod n
updateMinDef (BF.And fs) = BF.And $ updateMinDef <$> fs
updateMinDef (BF.Or fs) = BF.Or $ updateMinDef <$> fs
getClassInstance :: ModInfo -> Class -> Type -> CoreExpr
getClassInstance mod cl t
for instances in Meta module
| Just v <- listToMaybe $ filter ((== name) . getNameStr) (allVars mod) = Var v -- for instances in user modules
| otherwise = pgmError ("NLambda plugin requires " ++ className ++ " instance for type: " ++ tcName ++ " (from " ++ getModuleStr tc ++ ")")
where Just tc = tyConAppTyCon_maybe t
tcName = getNameStr tc
className = getNameStr cl
name = "$f" ++ className ++ tcName
findSuperClass :: Type -> [CoreExpr] -> Maybe CoreExpr
findSuperClass t (e:es)
| Just (cl, ts) <- getClassPredTys_maybe (exprType e)
= let (_, _, ids, _) = classBigSig cl
es' = fmap (\i -> mkApps (Var i) (fmap Type ts ++ [e])) ids
in find (eqType t . exprType) es' <|> findSuperClass t (es ++ es')
| otherwise = findSuperClass t es
findSuperClass t [] = Nothing
newClassInstances :: ModInfo -> [ClsInst] -> [ClsInst]
newClassInstances mod is = catMaybes $ fmap new is
where new i = let dFunId = instanceDFunId i
nm = is_cls_nm i
in if varMapMember mod dFunId && nameMember mod nm
then Just $ mkImportedInstance
(newName mod nm)
(instanceRoughTcs i)
(newVar mod dFunId)
(is_flag i)
(is_orphan i)
else Nothing
userClassOpId :: ModInfo -> Id -> Maybe Class
userClassOpId mod v
| Just cls <- isClassOpId_maybe v, inCurrentModule mod cls = Just cls
| isPrefixOf classOpPrefix (getNameStr v) = lookup (getNameStr v) userClassMethods
| otherwise = Nothing
where classOpPrefix = "$c"
modClasses = filter (inCurrentModule mod) $ allClasses mod
userClassMethods = concatMap (\c -> fmap (\m -> (classOpPrefix ++ getNameStr m, c)) (classMethods c)) modClasses
----------------------------------------------------------------------------------------
-- Binds
----------------------------------------------------------------------------------------
sortBinds :: CoreProgram -> CoreProgram
sortBinds = fmap (uncurry NonRec) . sortWith (getNameStr . fst) . flattenBinds
getBindsVars :: ModGuts -> [Var]
getBindsVars = bindersOfBinds . mg_binds
getBindsNames :: ModGuts -> [Name]
getBindsNames = fmap varName . getBindsVars
newBinds :: ModInfo -> [DataCon] -> CoreProgram -> CoreM CoreProgram
newBinds mod dcs bs = do bs' <- mapM (changeBind mod) $ filter isInVarMap bs
bs'' <- mapM (dataBind mod) dcs
return $ bs' ++ bs''
where isInVarMap (NonRec b e) = varMapMember mod b
isInVarMap (Rec bs) = all (varMapMember mod) $ fst <$> bs
changeBind :: ModInfo -> CoreBind -> CoreM CoreBind
changeBind mod (NonRec b e) = do (b',e') <- changeBindExpr mod (b, e)
return (NonRec b' e')
changeBind mod (Rec bs) = do bs' <- mapM (changeBindExpr mod) bs
return (Rec bs')
changeBindExpr :: ModInfo -> (CoreBndr, CoreExpr) -> CoreM (CoreBndr, CoreExpr)
changeBindExpr mod (b, e) = do e' <- changeExpr mod e
let b' = newVar mod b
e'' <- convertMetaType mod e' $ varType b'
return (b', simpleOptExpr e'')
dataBind :: ModInfo -> DataCon -> CoreM CoreBind
dataBind mod dc
| noAtomsType $ dataConOrigResTy dc = return $ NonRec b' (Var b)
| otherwise = do e <- dataConExpr mod dc
e' <- convertMetaType mod e $ varType b'
return $ NonRec b' $ simpleOptExpr e'
where b = dataConWrapId dc
b' = newVar mod b
----------------------------------------------------------------------------------------
-- Type
----------------------------------------------------------------------------------------
changeBindTypeAndUniq :: ModInfo -> CoreBndr -> CoreM CoreBndr
changeBindTypeAndUniq mod x = mkVarUnique $ setVarType x $ changeType mod $ varType x
changeBindTypeUnderWithMetaAndUniq :: ModInfo -> CoreBndr -> CoreM CoreBndr
changeBindTypeUnderWithMetaAndUniq mod x = mkVarUnique $ setVarType x $ changeTypeUnderWithMeta mod False $ varType x
changeType :: ModInfo -> Type -> Type
changeType mod t = (changeTypeOrSkip mod True) t
changeTypeOrSkip :: ModInfo -> Bool -> Type -> Type
changeTypeOrSkip mod skipNoAtoms t = change t
where change t | skipNoAtoms, noAtomsType t = t
change t | isVoidTy t = t
change t | isPrimitiveType t = t
change t | isPredTy t = changePredType mod t
change t | (Just (tv, t')) <- splitForAllTy_maybe t = mkForAllTy tv (change t')
change t | (Just (t1, t2)) <- splitFunTy_maybe t = mkFunTy (change t1) (change t2)
change t | (Just (t1, t2)) <- splitAppTy_maybe t
= withMetaType mod $ mkAppTy t1 (changeTypeUnderWithMeta mod skipNoAtoms t2)
change t | (Just (tc, ts)) <- splitTyConApp_maybe t
= withMetaType mod $ mkTyConApp tc (changeTypeUnderWithMeta mod skipNoAtoms <$> ts)
change t = withMetaType mod t
changeTypeUnderWithMeta :: ModInfo -> Bool -> Type -> Type
changeTypeUnderWithMeta mod skipNoAtoms t = change t
where change t | skipNoAtoms, noAtomsType t = t
change t | (Just (tv, t')) <- splitForAllTy_maybe t = mkForAllTy tv (change t')
change t | (Just (t1, t2)) <- splitFunTy_maybe t
= mkFunTy (changeTypeOrSkip mod skipNoAtoms t1) (changeTypeOrSkip mod skipNoAtoms t2)
change t | (Just (t1, t2)) <- splitAppTy_maybe t = mkAppTy (change t1) (change t2)
change t | (Just (tc, ts)) <- splitTyConApp_maybe t = mkTyConApp tc (change <$> ts)
change t = t
changePredType :: ModInfo -> PredType -> PredType
changePredType mod t | (Just (tc, ts)) <- splitTyConApp_maybe t, isClassTyCon tc = mkTyConApp (newTyCon mod tc) ts
changePredType mod t = t
changeTypeAndApply :: ModInfo -> CoreExpr -> Type -> CoreExpr
changeTypeAndApply mod e t
| otherwise = (mkApp e . Type . change) t
where (tyVars, eTy) = splitForAllTys $ exprType e
tyVar = headPanic "changeTypeAndApply" (pprE "e" e) tyVars
change t = if isFunTy t && isMonoType t then changeTypeOrSkip mod (not $ isTyVarNested tyVar eTy) t else t
addVarContextForHigherOrderClass :: ModInfo -> Class -> Type -> Type
addVarContextForHigherOrderClass mod cls t
| all isMonoType $ mkTyVarTys $ classTyVars cls = t
| null tvs = t
| otherwise = mkForAllTys tvs $ mkFunTys (nub $ preds ++ preds') (addVarContextForHigherOrderClass mod cls t')
where (tvs, preds, t') = tcSplitSigmaTy t
preds' = fmap (varPredType mod) $ filter isMonoType $ mkTyVarTys $ filter (isTyVarWrappedByWithMeta mod t) tvs
getMainType :: Type -> Type
getMainType t = if t == t' then t else getMainType t'
where (tvs, ps, t') = tcSplitSigmaTy t
getFunTypeParts :: Type -> [Type]
getFunTypeParts t
| t /= getMainType t = getFunTypeParts $ getMainType t
| not $ isFunTy t = [t]
| otherwise = argTys ++ [resTy]
where (argTys, resTy) = splitFunTys t
isTyVarWrappedByWithMeta :: ModInfo -> Type -> TyVar -> Bool
isTyVarWrappedByWithMeta mod t tv = all wrappedByWithMeta $ getFunTypeParts t
where wrappedByWithMeta t | isWithMetaType mod t = True
wrappedByWithMeta (TyVarTy tv') = tv /= tv'
wrappedByWithMeta (AppTy t1 t2) = wrappedByWithMeta t1 && wrappedByWithMeta t2
wrappedByWithMeta (TyConApp tc ts) = isMetaPreludeTyCon mod tc || all wrappedByWithMeta ts
wrappedByWithMeta (FunTy t1 t2) = wrappedByWithMeta t1 && wrappedByWithMeta t2
wrappedByWithMeta (ForAllTy _ t') = wrappedByWithMeta t'
wrappedByWithMeta (LitTy _) = True
-- is ty var under app type
isTyVarNested :: TyVar -> Type -> Bool
isTyVarNested tv t = isNested False t
where isNested nested (TyVarTy tv') = nested && (tv == tv')
isNested nested (AppTy t1 t2) = isNested nested t1 || isNested True t2
isNested nested (TyConApp tc ts) = any (isNested True) ts
isNested nested (FunTy t1 t2) = isNested nested t1 || isNested nested t2
isNested nested (ForAllTy _ t) = isNested nested t
isNested nested (LitTy _) = False
isWithMetaType :: ModInfo -> Type -> Bool
isWithMetaType mod t
| Just (tc, _) <- splitTyConApp_maybe (getMainType t) = tc == withMetaC mod
| otherwise = False
getWithoutWithMetaType :: ModInfo -> Type -> Maybe Type
getWithoutWithMetaType mod t
| isWithMetaType mod t, Just ts <- tyConAppArgs_maybe t = Just $ headPanic "getWithoutWithMetaType" (ppr t) ts
| otherwise = Nothing
getAllPreds :: Type -> ThetaType
getAllPreds t
| null preds = []
| otherwise = preds ++ getAllPreds t'
where (preds, t') = tcSplitPhiTy $ dropForAlls t
isInternalType :: Type -> Bool
isInternalType t = let t' = getMainType t in isVoidTy t' || isPredTy t' || isPrimitiveType t' || isUnLiftedType t'
isMonoType :: Type -> Bool
isMonoType = not . isFunTy . typeKind
----------------------------------------------------------------------------------------
-- Checking type contains atoms
----------------------------------------------------------------------------------------
noAtomsType :: Type -> Bool
noAtomsType t | hasNestedFunType t = False
noAtomsType t = noAtomsTypeVars [] [] t
where noAtomsTypeVars :: [TyCon] -> [TyVar] -> Type -> Bool
noAtomsTypeVars tcs vs t | Just t' <- coreView t = noAtomsTypeVars tcs vs t'
noAtomsTypeVars tcs vs (TyVarTy v) = elem v vs
noAtomsTypeVars tcs vs (AppTy t1 t2) = noAtomsTypeVars tcs vs t1 && noAtomsTypeVars tcs vs t2
noAtomsTypeVars tcs vs (TyConApp tc ts) = noAtomsTypeCon tcs tc (length ts) && (all (noAtomsTypeVars tcs vs) ts)
noAtomsTypeVars tcs vs (FunTy t1 t2) = noAtomsTypeVars tcs vs t1 && noAtomsTypeVars tcs vs t2
noAtomsTypeVars tcs vs (ForAllTy v _) = elem v vs
noAtomsTypeVars tcs vs (LitTy _ ) = True
-- tcs - for recursive definitions, n - number of applied args to tc
noAtomsTypeCon :: [TyCon] -> TyCon -> Int -> Bool
noAtomsTypeCon tcs tc _ | elem tc tcs = True
noAtomsTypeCon _ tc _ | isAtomsTypeName tc = False
noAtomsTypeCon _ tc _ | isClassTyCon tc = False -- classes should be replaced by meta equivalent
noAtomsTypeCon _ tc _ | isPrimTyCon tc = True
noAtomsTypeCon tcs tc n | isDataTyCon tc = all (noAtomsTypeVars (nub $ tc : tcs) $ take n $ tyConTyVars tc)
(concatMap dataConOrigArgTys $ tyConDataCons tc)
noAtomsTypeCon _ _ _ = True
isAtomsTypeName :: TyCon -> Bool
isAtomsTypeName tc = let nm = tyConName tc in getNameStr nm == "Variable" && moduleNameString (moduleName $ nameModule nm) == "Var"
hasNestedFunType :: Type -> Bool
hasNestedFunType (TyVarTy v) = False
hasNestedFunType (AppTy _ t) = isFunTy t || hasNestedFunType t
hasNestedFunType (TyConApp _ ts) = any (\t -> isFunTy t || hasNestedFunType t) ts
hasNestedFunType (FunTy t1 t2) = hasNestedFunType t1 || hasNestedFunType t2
hasNestedFunType (ForAllTy _ t) = hasNestedFunType t
hasNestedFunType (LitTy _ ) = False
----------------------------------------------------------------------------------------
-- Type thing
----------------------------------------------------------------------------------------
data TyThingType = TyThingId | TyThingTyCon | TyThingConLike | TyThingCoAxiom deriving (Show, Eq)
tyThingType :: TyThing -> TyThingType
tyThingType (AnId _) = TyThingId
tyThingType (ATyCon _) = TyThingTyCon
tyThingType (AConLike _) = TyThingConLike
tyThingType (ACoAxiom _) = TyThingCoAxiom
isTyThingId :: TyThing -> Bool
isTyThingId = (== TyThingId) . tyThingType
isTyThingTyCon :: TyThing -> Bool
isTyThingTyCon = (== TyThingTyCon) . tyThingType
getModulesTyThings :: [HomeModInfo] -> TypeEnv
getModulesTyThings = mconcat . fmap md_types . fmap hm_details
getTyThingMaybe :: [HomeModInfo] -> String -> (TyThing -> Bool) -> (TyThing -> a) -> (a -> Name) -> Maybe a
getTyThingMaybe mods nm cond fromThing getName =
fmap fromThing $ listToMaybe $ nameEnvElts $ filterNameEnv (\t -> cond t && hasName nm (getName $ fromThing t)) (getModulesTyThings mods)
where hasName nmStr nm = occNameString (nameOccName nm) == nmStr
getTyThing :: [HomeModInfo] -> String -> (TyThing -> Bool) -> (TyThing -> a) -> (a -> Name) -> a
getTyThing mods nm cond fromThing getName = fromMaybe (pprPanic "getTyThing - name not found in module Meta:" $ text nm)
(getTyThingMaybe mods nm cond fromThing getName)
findThingByConds :: (Name -> Name -> Bool) -> (Module -> Module -> Bool) -> [TyThing] -> TyThingType -> Name -> Maybe TyThing
findThingByConds nameCond moduleCond things ty name = find cond things
where sameType = (== ty) . tyThingType
cond t = sameType t && nameCond name (getName t) && moduleCond (nameModule name) (nameModule $ getName t)
findThing :: [TyThing] -> TyThingType -> Name -> Maybe TyThing
findThing = findThingByConds (==) (==)
findPairThing :: [TyThing] -> TyThingType -> Name -> Maybe TyThing
findPairThing things ty name = findThingByConds pairName equivalentModule things ty name
where pairName name nameWithSuffix = let nameStr = getNameStr name
nameWithSuffixStr = getNameStr nameWithSuffix
in nameWithSuffixStr == nlambdaName nameStr
|| (isInfixOf name_suffix nameWithSuffixStr && replace name_suffix "" nameWithSuffixStr == nameStr)
equivalentModule m1 m2 = m1 == m2 || (elem (getModuleNameStr m1) preludeModules && getModuleNameStr m2 == metaModuleName)
findPair :: [TyThing] -> TyThingType -> Name -> Maybe (TyThing, TyThing)
findPair things ty name = (,) <$> findThing things ty name <*> findPairThing things ty name
----------------------------------------------------------------------------------------
-- Expressions map
----------------------------------------------------------------------------------------
type ExprMap = Map Var CoreExpr
mkExprMap :: ModInfo -> ExprMap
mkExprMap = Map.map Var . varsWithPairs
getExpr :: ExprMap -> Var -> CoreExpr
getExpr map v = Map.findWithDefault (pprPanic "no expression for variable: " (ppr v <+> ppr (Map.assocs map))) v map
insertVarExpr :: Var -> Var -> ExprMap -> ExprMap
insertVarExpr v v' = Map.insert v (Var v')
insertExpr :: Var -> CoreExpr -> ExprMap -> ExprMap
insertExpr = Map.insert
----------------------------------------------------------------------------------------
-- Expressions
----------------------------------------------------------------------------------------
changeExpr :: ModInfo -> CoreExpr -> CoreM CoreExpr
changeExpr mod e = newExpr (mkExprMap mod) e
where newExpr :: ExprMap -> CoreExpr -> CoreM CoreExpr
newExpr eMap e | noAtomsSubExpr e = replaceVars mod eMap e
newExpr eMap (Var v) | Map.member v eMap = addMockedInstances mod False $ getExpr eMap v
newExpr eMap (Var v) | isMetaEquivalent mod v = getMetaEquivalent mod v
newExpr eMap (Var v) = pprPgmError "Unknown variable:"
(showVar v <+> text "::" <+> ppr (varType v) <+> text ("\nProbably module " ++ getModuleStr v ++ " is not compiled with NLambda Plugin."))
newExpr eMap (Lit l) = noMetaExpr mod (Lit l)
newExpr eMap (App f (Type t)) = do f' <- newExpr eMap f
return $ changeTypeAndApply mod f' t
newExpr eMap (App f e) = do f' <- newExpr eMap f
f'' <- if isWithMetaType mod $ exprType f' then valueExpr mod f' else return f'
e' <- newExpr eMap e
e'' <- convertMetaType mod e' $ funArgTy $ exprType f''
return $ mkApp f'' e''
newExpr eMap (Lam x e) | isTKVar x = do e' <- newExpr eMap e
FIXME new uniq for x ( and then replace all occurrences ) ?
newExpr eMap (Lam x e) = do x' <- changeBindTypeAndUniq mod x
e' <- newExpr (insertVarExpr x x' eMap) e
return $ Lam x' e'
newExpr eMap (Let b e) = do (b', eMap) <- newLetBind b eMap
e' <- newExpr eMap e
return $ Let b' e'
newExpr eMap (Case e b t as) = do e' <- newExpr eMap e
e'' <- if isWithMetaType mod $ exprType e'
then valueExpr mod e'
else return e'
m <- if isWithMetaType mod $ exprType e'
then metaExpr mod e'
else return $ emptyMetaV mod
b' <- changeBindTypeUnderWithMetaAndUniq mod b
be <- createExpr mod (Var b') m
let t' = changeType mod t
as' <- mapM (newAlternative (insertExpr b be eMap) m t') as
return $ Case e'' b' t' as'
newExpr eMap (Cast e c) = do e' <- newExpr eMap e
let c' = changeCoercion mod c
e'' <- convertMetaType mod e' $ pFst $ coercionKind c'
return $ Cast e'' c'
newExpr eMap (Tick t e) = do e' <- newExpr eMap e
return $ Tick t e'
newExpr eMap (Type t) = undefined -- type should be served in (App f (Type t)) case
newExpr eMap (Coercion c) = undefined
newLetBind (NonRec b e) eMap = do b' <- changeBindTypeAndUniq mod b
let eMap' = insertVarExpr b b' eMap
e' <- newExpr eMap' e
return (NonRec b' e', eMap')
newLetBind (Rec bs) eMap = do (bs', eMap') <- newRecBinds bs eMap
return (Rec bs', eMap')
newRecBinds ((b, e):bs) eMap = do (bs', eMap') <- newRecBinds bs eMap
b' <- changeBindTypeAndUniq mod b
let eMap'' = insertVarExpr b b' eMap'
e' <- newExpr eMap'' e
return ((b',e'):bs', eMap'')
newRecBinds [] eMap = return ([], eMap)
newAlternative eMap m t (DataAlt con, xs, e) = do xs' <- mapM (changeBindTypeUnderWithMetaAndUniq mod) xs
es <- mapM (\x -> if (isFunTy $ varType x) then return $ Var x else createExpr mod (Var x) m) xs'
e' <- newExpr (Map.union (Map.fromList $ zip xs es) eMap) e
e'' <- convertMetaType mod e' t
return (DataAlt con, xs', e'')
newAlternative eMap m t (alt, [], e) = do e' <- newExpr eMap e
return (alt, [], e')
-- the type of expression is not open for atoms and there are no free variables open for atoms
noAtomsSubExpr :: CoreExpr -> Bool
noAtomsSubExpr e = (noAtomsType $ exprType e) && noAtomFreeVars
where noAtomFreeVars = isEmptyUniqSet $ filterUniqSet (not . noAtomsType . varType) $ exprFreeIds e
replaceVars :: ModInfo -> ExprMap -> CoreExpr -> CoreM CoreExpr
replaceVars mod eMap e = replace e
where replace (Var x) | isLocalId x, Just e <- Map.lookup x eMap = convertMetaType mod e $ varType x
replace (App f e) = do f' <- replace f
e' <- replace e
return $ mkApp f' e'
replace (Lam x e) = do e' <- replace e
return $ Lam x e'
replace (Let b e) = do b' <- replaceInBind b
e' <- replace e
return $ Let b' e'
replace (Case e x t as) = do e' <- replace e
as' <- mapM replaceInAlt as
return $ Case e' x t as'
replace (Cast e c) = do e' <- replace e
return $ Cast e' c
replace (Tick t e) = do e' <- replace e
return $ Tick t e'
replace e = return e
replaceInBind (NonRec x e) = do e' <- replace e
return $ NonRec x e'
replaceInBind (Rec bs) = do bs' <- mapM replaceInRecBind bs
return $ Rec bs'
replaceInRecBind (b, e) = do e' <- replace e
return (b, e')
replaceInAlt (con, bs, e) = do e' <- replace e
return (con, bs, e')
getAllNotLocalVarsFromExpr :: CoreExpr -> [Var]
getAllNotLocalVarsFromExpr = nub . get
where get (Var x) = [x]
get (Lit l) = []
get (App f e) = get f ++ get e
get (Lam x e) = delete x $ get e
get (Let b e) = filter (`notElem` (bindersOf b)) (get e ++ concatMap getAllNotLocalVarsFromExpr (rhssOfBind b))
get (Case e x t as) = delete x (get e ++ concatMap getFromAlt as)
get (Cast e c) = get e
get (Tick t e) = get e
get (Type t) = []
getFromAlt (con, bs, e) = filter (`notElem` bs) (get e)
dataConExpr :: ModInfo -> DataCon -> CoreM CoreExpr
dataConExpr mod dc
| arity == 0 = noMetaExpr mod dcv
| arity == 1 = idOpExpr mod dcv
| otherwise = do (vars, ty, subst) <- splitTypeToExprVarsWithSubst $ exprType dcv
xs <- mkArgs subst arity
let (vvs, evs) = (exprVarsToVars vars, exprVarsToExprs vars)
ra <- renameAndApplyExpr mod arity
ra' <- applyExpr ra (mkApps dcv evs)
return $ mkCoreLams (vvs ++ xs) $ mkApps ra' (Var <$> xs)
where arity = dataConSourceArity dc
dcv = Var $ dataConWrapId dc
mkArgs subst 0 = return []
mkArgs subst n = do let ty = substTy subst $ withMetaType mod $ dataConOrigArgTys dc !! (arity - n)
x <- mkLocalVar ("x" ++ show (arity - n)) ty
args <- mkArgs subst $ pred n
return $ x : args
----------------------------------------------------------------------------------------
-- Coercion
----------------------------------------------------------------------------------------
changeCoercion :: ModInfo -> Coercion -> Coercion
changeCoercion mod c = change True c
where change topLevel (Refl r t) = Refl r $ changeTy topLevel t
change topLevel (TyConAppCo r tc cs) = TyConAppCo r (newTyCon mod tc) (change False <$> cs)
change topLevel (AppCo c1 c2) = AppCo (change False c1) (change False c2)
change topLevel (ForAllCo tv c) = ForAllCo tv (change topLevel c)
change topLevel (CoVarCo cv) = let (t1,t2) = coVarKind cv in CoVarCo $ mkCoVar (coVarName cv) (mkCoercionType (coVarRole cv) t1 t2)
change topLevel (AxiomInstCo a i cs) = AxiomInstCo (changeBranchedCoAxiom mod a) i (change False <$> cs)
change topLevel (UnivCo n r t1 t2) = UnivCo n r (changeTy topLevel t1) (changeTy topLevel t2)
change topLevel (SymCo c) = SymCo $ change topLevel c
change topLevel (TransCo c1 c2) = TransCo (change topLevel c1) (change topLevel c2)
change topLevel (AxiomRuleCo a ts cs) = AxiomRuleCo a (changeTy topLevel <$> ts) (change topLevel <$> cs)
change topLevel (NthCo i c) = NthCo i $ change topLevel c
change topLevel (LRCo lr c) = LRCo lr $ change topLevel c
change topLevel (InstCo c t) = InstCo (change topLevel c) (changeTy topLevel t)
change topLevel (SubCo c) = SubCo $ change topLevel c
changeTy topLevel = if topLevel then changeType mod else changeTypeUnderWithMeta mod False
changeBranchedCoAxiom :: ModInfo -> CoAxiom Branched -> CoAxiom Branched
changeBranchedCoAxiom mod = changeCoAxiom mod toBranchList Nothing
changeUnbranchedCoAxiom :: ModInfo -> Class -> CoAxiom Unbranched -> CoAxiom Unbranched
changeUnbranchedCoAxiom mod cls = changeCoAxiom mod toUnbranchedList $ Just cls
changeCoAxiom :: ModInfo -> ([CoAxBranch] -> BranchList CoAxBranch a) -> Maybe Class -> CoAxiom a -> CoAxiom a
changeCoAxiom mod toList cls (CoAxiom u n r tc bs imp)
= CoAxiom u n r (newTyCon mod tc) (changeBranchList mod toList cls bs) imp
changeBranchList :: ModInfo -> ([CoAxBranch] -> BranchList CoAxBranch a) -> Maybe Class -> BranchList CoAxBranch a -> BranchList CoAxBranch a
changeBranchList mod toList cls = toList . fmap (changeCoAxBranch mod cls) . fromBranchList
changeCoAxBranch :: ModInfo -> Maybe Class -> CoAxBranch -> CoAxBranch
changeCoAxBranch mod cls (CoAxBranch loc tvs roles lhs rhs incpoms)
= CoAxBranch
loc
tvs
roles
(changeTypeUnderWithMeta mod False <$> lhs)
(newRhs cls)
(changeCoAxBranch mod cls <$> incpoms)
where rhs' = changeTypeUnderWithMeta mod False rhs
newRhs (Just c) = addVarContextForHigherOrderClass mod c rhs'
newRhs _ = rhs'
toUnbranchedList :: [CoAxBranch] -> BranchList CoAxBranch Unbranched
toUnbranchedList [b] = FirstBranch b
toUnbranchedList _ = pprPanic "toUnbranchedList" empty
updateCoercionType :: Type -> Coercion -> Coercion
updateCoercionType = update True
where update left t c | t == (if left then pFst else pSnd) (coercionKind c) = c
update left t (Refl r t') = Refl r t
update left t (SymCo c) = SymCo $ update (not left) t c
TODO update cs after try unify
update left t (AxiomInstCo a i cs) = AxiomInstCo (updateCoAxiomType left t i a) i cs
-- TODO other cases
update left t c = c
updateCoAxiomType :: Bool -> Type -> BranchIndex -> CoAxiom Branched -> CoAxiom Branched
updateCoAxiomType left t i a@(CoAxiom u n r tc bs imp)
| left, Just (tc', ts) <- splitTyConApp_maybe t, tc == tc' = axiom $ updateCoAxBranchesType left ts i bs
| left = pprPanic "updateCoAxiomType" (text "inconsistent type:" <+> ppr t <+> text "with co axiom:" <+> ppr a)
| otherwise = axiom $ updateCoAxBranchesType left [t] i bs
where axiom bs = CoAxiom u n r tc bs imp
updateCoAxBranchesType :: Bool -> [Type] -> BranchIndex -> BranchList CoAxBranch Branched -> BranchList CoAxBranch Branched
updateCoAxBranchesType left ts i bs = toBranchList $ fmap update $ zip (fromBranchList bs) [0..]
where update (b, bi) = if bi == i then updateCoAxBranchType left ts b else b
updateCoAxBranchType :: Bool -> [Type] -> CoAxBranch -> CoAxBranch
updateCoAxBranchType True ts (CoAxBranch loc tvs roles lhs rhs incpoms) = CoAxBranch loc tvs roles ts rhs incpoms
updateCoAxBranchType False [t] (CoAxBranch loc tvs roles lhs rhs incpoms) = CoAxBranch loc tvs roles lhs t incpoms
----------------------------------------------------------------------------------------
Core program validation
----------------------------------------------------------------------------------------
checkCoreProgram :: CoreProgram -> CoreProgram
checkCoreProgram bs = if all checkBinds bs then bs else pprPanic "checkCoreProgram failed" (ppr bs)
where checkBinds (NonRec b e) = checkBind (b,e)
checkBinds (Rec bs) = all checkBind bs
checkBind (b,e) | varType b /= exprType e
= pprPanic "\n================= INCONSISTENT TYPES IN BIND ==========================="
(vcat [text "bind: " <+> showVar b,
text "bind type:" <+> ppr (varType b),
text "expr:" <+> ppr e,
text "expr type:" <+> ppr (exprType e),
text "\n=======================================================================|"])
checkBind (b,e) = checkExpr b e
checkExpr b (Var v) = True
checkExpr b (Lit l) = True
checkExpr b (App f (Type t)) | not $ isForAllTy $ exprType f
= pprPanic "\n================= NOT FUNCTION IN APPLICATION ========================="
(vcat [text "fun expr: " <+> ppr f,
text "fun type: " <+> ppr (exprType f),
text "arg: " <+> ppr t,
text "for bind: " <+> ppr b <+> text "::" <+> ppr (varType b),
text "\n=======================================================================|"])
checkExpr b (App f (Type t)) = checkExpr b f
checkExpr b (App f x) | not $ isFunTy $ exprType f
= pprPanic "\n================= NOT FUNCTION IN APPLICATION ========================="
(vcat [text "fun expr: " <+> ppr f,
text "fun type: " <+> ppr (exprType f),
text "arg: " <+> ppr x,
text "arg type: " <+> ppr (exprType x),
text "for bind: " <+> ppr b <+> text "::" <+> ppr (varType b),
text "\n=======================================================================|"])
checkExpr b (App f x) | funArgTy (exprType f) /= exprType x
= pprPanic "\n================= INCONSISTENT TYPES IN APPLICATION ===================="
(vcat [text "fun: " <+> ppr f,
text "fun type: " <+> ppr (exprType f),
text "fun arg type: " <+> ppr (funArgTy $ exprType f),
text "arg: " <+> ppr x,
text "arg type: " <+> ppr (exprType x),
text "for bind: " <+> ppr b <+> text "::" <+> ppr (varType b),
text "\n=======================================================================|"])
checkExpr b (App f x) = checkExpr b f && checkExpr b x
checkExpr b (Lam x e) = checkExpr b e
checkExpr b (Let x e) = checkBinds x && checkExpr b e
checkExpr b (Case e x t as) = checkBind (x,e) && all (checkAlternative b t) as && all (checkAltConType b $ exprType e) as
checkExpr b (Cast e c) | exprType e /= pFst (coercionKind c)
= pprPanic "\n================= INCONSISTENT TYPES IN CAST ==========================="
(vcat [text "expr: " <+> ppr e,
text "expr type: " <+> ppr (exprType e),
text "coercion: " <+> ppr c,
text "coercion: " <+> showCoercion c,
text "coercion type: " <+> ppr (coercionType c),
text "for bind: " <+> ppr b <+> text "::" <+> ppr (varType b),
text "\n=======================================================================|"])
checkExpr b (Cast e c) = checkExpr b e
checkExpr b (Tick t e) = checkExpr b e
checkExpr b (Type t) = undefined -- type should be handled in (App f (Type t)) case
checkExpr b (Coercion c) = True
checkAlternative b t (ac, xs, e) | t /= exprType e
= pprPanic "\n================= INCONSISTENT TYPES IN CASE ALTERNATIVE ==============="
(vcat [text "type in case: " <+> ppr t,
text "case alternative expression: " <+> ppr e,
text "case alternative expression type: " <+> ppr (exprType e),
text "for bind: " <+> ppr b <+> text "::" <+> ppr (varType b),
text "\n=======================================================================|"])
checkAlternative b t (ac, xs, e) = checkExpr b e
checkAltConType b t (DataAlt dc, xs, e) = checkAltConTypes b (ppr dc) (dataConOrigResTy dc) t xs -- FIXME better evaluation of pattern type
checkAltConType b t (LitAlt l, xs, e) = checkAltConTypes b (ppr l) (literalType l) t xs
checkAltConType b _ _ = True
checkAltConTypes b conDoc pt vt xs | not $ canUnifyTypes pt vt
= pprPanic "\n========== INCONSISTENT TYPES IN CASE ALTERNATIVE PATTERN =============="
(vcat [text "type of value: " <+> ppr vt,
text "case alternative constructor: " <+> conDoc,
text "case alternative arguments: " <+> hcat ((\x -> ppr x <+> text "::" <+> ppr (varType x)) <$> xs),
text "case alternative pattern type: " <+> ppr pt,
text "for bind: " <+> ppr b <+> text "::" <+> ppr (varType b),
text "\n=======================================================================|"])
checkAltConTypes b conDoc pt vt xs = True
----------------------------------------------------------------------------------------
-- Apply expression
----------------------------------------------------------------------------------------
data ExprVar = TV TyVar | DI DictId
instance Outputable ExprVar where
ppr (TV v) = ppr v
ppr (DI i) = ppr i
isTV :: ExprVar -> Bool
isTV (TV _) = True
isTV (DI _) = False
substTy :: TvSubst -> Type -> Type
substTy subst t = head $ substTys subst [t]
substFromLists :: [TyVar] -> [TyVar] -> TvSubst
substFromLists tvs = mkTopTvSubst . zip tvs . mkTyVarTys
substDictId :: TvSubst -> DictId -> DictId
substDictId subst id = setVarType id ty
where (cl, ts) = getClassPredTys $ varType id
ts' = substTys subst ts
ty = mkClassPred cl ts'
exprVarsToVarsWithSubst :: TvSubst -> [ExprVar] -> [CoreBndr]
exprVarsToVarsWithSubst subst = catMaybes . fmap toCoreBndr
where toCoreBndr (TV v) | isNothing (lookupTyVar subst v) = Just v
toCoreBndr (TV v) = Nothing
toCoreBndr (DI i) = Just $ substDictId subst i
exprVarsToVars :: [ExprVar] -> [CoreBndr]
exprVarsToVars = exprVarsToVarsWithSubst emptyTvSubst
exprVarsToExprsWithSubst :: TvSubst -> [ExprVar] -> [CoreExpr]
exprVarsToExprsWithSubst subst = fmap toExpr
where toExpr (TV v) = Type $ substTyVar subst v
toExpr (DI i) = Var $ substDictId subst i
exprVarsToExprs :: [ExprVar] -> [CoreExpr]
exprVarsToExprs = exprVarsToExprsWithSubst emptyTvSubst
splitTypeToExprVarsWithSubst :: Type -> CoreM ([ExprVar], Type, TvSubst)
splitTypeToExprVarsWithSubst ty
| ty == ty' = return ([], ty, emptyTvSubst)
| otherwise = do tyVars' <- mapM mkTyVarUnique tyVars
let subst = substFromLists tyVars tyVars'
let preds' = filter isClassPred preds
let classTys = fmap getClassPredTys preds'
predVars <- mapM mkPredVar ((\(c,tys) -> (c, substTys subst tys)) <$> classTys)
(resTyVars, resTy, resSubst) <- splitTypeToExprVarsWithSubst $ substTy subst ty'
return ((TV <$> tyVars') ++ (DI <$> predVars) ++ resTyVars, resTy, unionTvSubst subst resSubst)
where (tyVars, preds, ty') = tcSplitSigmaTy ty
mkTyVarUnique v = do uniq <- getUniqueM
return $ mkTyVar (setNameUnique (tyVarName v) uniq) (tyVarKind v)
splitTypeToExprVars :: Type -> CoreM ([ExprVar], Type)
splitTypeToExprVars t = liftM (\(vars, ty, _) -> (vars, ty)) (splitTypeToExprVarsWithSubst t)
unifyTypes :: Type -> Type -> Maybe TvSubst
unifyTypes t1 t2 = maybe unifyWithOpenKinds Just (tcUnifyTy t1 t2)
where unifyWithOpenKinds = tcUnifyTy (replaceOpenKinds t1) (replaceOpenKinds t2)
replaceOpenKinds (TyVarTy v) | isOpenTypeKind (tyVarKind v) = TyVarTy $ setTyVarKind v (defaultKind $ tyVarKind v)
replaceOpenKinds (TyVarTy v) = TyVarTy v
replaceOpenKinds (AppTy t1 t2) = AppTy (replaceOpenKinds t1) (replaceOpenKinds t2)
replaceOpenKinds (TyConApp tc ts) = TyConApp tc (fmap replaceOpenKinds ts)
replaceOpenKinds (FunTy t1 t2) = FunTy (replaceOpenKinds t1) (replaceOpenKinds t2)
replaceOpenKinds (ForAllTy v t) = ForAllTy v (replaceOpenKinds t)
replaceOpenKinds (LitTy tl) = LitTy tl
canUnifyTypes :: Type -> Type -> Bool
canUnifyTypes t1 t2 = isJust $ unifyTypes (dropForAlls t1) (dropForAlls t2)
applyExpr :: CoreExpr -> CoreExpr -> CoreM CoreExpr
applyExpr fun e =
do (eVars, eTy) <- splitTypeToExprVars $ exprType e
(fVars, fTy) <- if isPredTy eTy
then return $ (\(tvs, t) -> (TV <$> tvs, t)) (splitForAllTys $ exprType fun)
else splitTypeToExprVars $ exprType fun
let subst = fromMaybe
(pprPanic "applyExpr - can't unify:" (ppr (funArgTy fTy) <+> text "and" <+> ppr eTy <+> text "for apply:" <+> ppr fun <+> text "with" <+> ppr e))
(unifyTypes (funArgTy fTy) eTy)
let fVars' = exprVarsToVarsWithSubst subst fVars
let fVarExprs = exprVarsToExprsWithSubst subst fVars
let eVars' = exprVarsToVarsWithSubst subst eVars
let eVarExprs = exprVarsToExprsWithSubst subst eVars
return $ mkCoreLams (sortVars [] $ reverse $ nub $ fVars' ++ eVars')
(mkApp
(mkApps fun fVarExprs)
(mkApps e eVarExprs))
where sortVars res (v:vs)
| not $ isTyVar v, Just i <- findIndex (\x -> isTyVar x && elemVarSet x (tyVarsOfType $ varType v)) res
= let (vs1, vs2) = splitAt i res in sortVars (vs1 ++ [v] ++ vs2) vs
| otherwise = sortVars (v:res) vs
sortVars res [] = res
applyExprs :: CoreExpr -> [CoreExpr] -> CoreM CoreExpr
applyExprs = foldlM applyExpr
mkAppOr :: CoreExpr -> CoreExpr -> CoreExpr -> CoreExpr
mkAppOr f x ifNotMatch
| not (isTypeArg x), funArgTy (exprType f) /= exprType x = ifNotMatch
| otherwise = mkCoreApp f x
mkApp :: CoreExpr -> CoreExpr -> CoreExpr
mkApp f x = mkAppOr f x $ pprPanic "mkApp - inconsistent types:" (pprE "f" f <+> text "," <+> pprE "x" x)
mkAppIfMatch :: CoreExpr -> CoreExpr -> CoreExpr
mkAppIfMatch f x = mkAppOr f x f
mkApps :: CoreExpr -> [CoreExpr] -> CoreExpr
mkApps = foldl mkApp
mkAppsIfMatch :: CoreExpr -> [CoreExpr] -> CoreExpr
mkAppsIfMatch = foldl mkAppIfMatch
----------------------------------------------------------------------------------------
Meta
----------------------------------------------------------------------------------------
varModuleName :: Meta.ModuleName
varModuleName = "Var"
metaModuleName :: Meta.ModuleName
metaModuleName = "Meta"
type MetaModule = HomeModInfo
getMetaModules :: HscEnv -> [MetaModule]
getMetaModules = filter ((`elem` [varModuleName, metaModuleName]) . moduleNameString . moduleName . mi_module . hm_iface) . eltsUFM . hsc_HPT
getVar :: ModInfo -> String -> Var
getVar mod nm = getTyThing (metaModules mod) nm isTyThingId tyThingId varName
getVarMaybe :: ModInfo -> String -> Maybe Var
getVarMaybe mod nm = getTyThingMaybe (metaModules mod) nm isTyThingId tyThingId varName
metaTyThings :: ModInfo -> [TyThing]
metaTyThings = nameEnvElts . getModulesTyThings . metaModules
getTyCon :: ModInfo -> String -> TyCon
getTyCon mod nm = getTyThing (metaModules mod) nm isTyThingTyCon tyThingTyCon tyConName
getMetaVar :: ModInfo -> String -> CoreExpr
getMetaVar mod = Var . getVar mod
getMetaVarMaybe :: ModInfo -> String -> Maybe CoreExpr
getMetaVarMaybe mod = fmap Var . getVarMaybe mod
noMetaV mod = getMetaVar mod "noMeta"
metaV mod = getMetaVar mod "meta"
valueV mod = getMetaVar mod "value"
createV mod = getMetaVar mod "create"
emptyMetaV mod = getMetaVar mod "emptyMeta"
idOpV mod = getMetaVar mod "idOp"
renameAndApplyV mod n = getMetaVar mod ("renameAndApply" ++ show n)
withMetaC mod = getTyCon mod "WithMeta"
metaLevelC mod = getTyCon mod "MetaLevel"
varC mod = getTyCon mod "Var"
withMetaType :: ModInfo -> Type -> Type
withMetaType mod t = mkTyConApp (withMetaC mod) [t]
varPredType :: ModInfo -> Type -> Type
varPredType mod t = mkTyConApp (varC mod) [t]
noMetaExpr :: ModInfo -> CoreExpr -> CoreM CoreExpr
noMetaExpr mod e | isInternalType $ exprType e = return e
noMetaExpr mod e = applyExpr (noMetaV mod) e
valueExpr :: ModInfo -> CoreExpr -> CoreM CoreExpr
valueExpr mod e | not $ isWithMetaType mod $ exprType e = return e
valueExpr mod e = applyExpr (valueV mod) e
metaExpr :: ModInfo -> CoreExpr -> CoreM CoreExpr
metaExpr mod e = applyExpr (metaV mod) e
createExpr :: ModInfo -> CoreExpr -> CoreExpr -> CoreM CoreExpr
createExpr mod e _ | isInternalType $ exprType e = return e
createExpr mod e1 e2 = applyExprs (createV mod) [e1, e2]
idOpExpr :: ModInfo -> CoreExpr -> CoreM CoreExpr
idOpExpr mod e = applyExpr (idOpV mod) e
renameAndApplyExpr :: ModInfo -> Int -> CoreM CoreExpr
renameAndApplyExpr mod n = addMockedInstances mod False (renameAndApplyV mod n)
----------------------------------------------------------------------------------------
-- Convert meta types
----------------------------------------------------------------------------------------
convertMetaType :: ModInfo -> CoreExpr -> Type -> CoreM CoreExpr
convertMetaType mod e t
| et == t = return e
| isClassPred t, Just e' <- findSuperClass t [e] = return e'
| Just t' <- getWithoutWithMetaType mod t, t' == et = do e' <- convertMetaType mod e t'
noMetaExpr mod e'
| Just et' <- getWithoutWithMetaType mod et, t == et' = do e' <- valueExpr mod e
convertMetaType mod e' t
| length etvs == length tvs, isFunTy et' && isFunTy t', subst <- substFromLists etvs tvs
= convertMetaFun (funArgTy $ substTy subst $ getMainType et') (splitFunTy $ getMainType t')
| otherwise = pprPanic "convertMetaType" (text "can't convert (" <+> ppr e <+> text "::" <+> ppr (exprType e) <+> text ") to type:" <+> ppr t)
where et = exprType e
(etvs, et') = splitForAllTys et
(tvs, t') = splitForAllTys t
convertMetaFun earg (arg, res) = do (vs, _, subst) <- splitTypeToExprVarsWithSubst t
let (vvs, evs) = (exprVarsToVars vs, exprVarsToExprs vs)
x <- mkLocalVar "x" (substTy subst arg)
ex <- convertMetaType mod (Var x) (substTy subst earg)
let e' = mkApp (mkAppsIfMatch e evs) ex
e'' <- convertMetaType mod e' (substTy subst res)
return $ mkCoreLams (vvs ++ [x]) e''
----------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------
getMetaPreludeNameMap :: ModInfo -> NameMap
getMetaPreludeNameMap mod = Map.fromList $ catMaybes metaPairs
where fromPrelude e | Imported ss <- gre_prov e = not $ null $ intersect preludeModules (moduleNameString <$> is_mod <$> is_decl <$> ss)
fromPrelude e = False
preludeNames = fmap gre_name $ filter fromPrelude $ concat $ occEnvElts $ mg_rdr_env $ guts mod
preludeNamesWithTypes = fmap (\n -> if isLower $ head $ getNameStr n then (TyThingId, n) else (TyThingTyCon, n)) preludeNames
metaPairs = fmap (\(ty, n) -> (\t -> (n, getName t)) <$> findPairThing (metaTyThings mod) ty n) preludeNamesWithTypes
isMetaPreludeTyCon :: ModInfo -> TyCon -> Bool
isMetaPreludeTyCon mod tc = any (\t -> getName t == getName tc && isTyThingTyCon t) $ metaTyThings mod
getMetaPreludeTyCon :: ModInfo -> TyCon -> Maybe TyCon
getMetaPreludeTyCon mod tc = (getTyCon mod . getNameStr) <$> findPairThing (metaTyThings mod) TyThingTyCon (getName tc)
getDefinedMetaEquivalentVar :: ModInfo -> Var -> Maybe Var
getDefinedMetaEquivalentVar mod v
| not $ isPreludeThing v = Nothing
super class selectors should be shift by one because of additional dependency for meta classes
FIXME count no nlambda dependencies and shift by this number
| isPrefixOf "$p" $ getNameStr v, isJust metaVar = Just $ getVar mod $ nlambdaName ("$p" ++ (show $ succ superClassNr) ++ drop 3 (getNameStr v))
| otherwise = metaVar
where metaVar = getVar mod . getNameStr <$> findPairThing (metaTyThings mod) TyThingId (getName v)
superClassNr = read [getNameStr v !! 2] :: Int
isMetaEquivalent :: ModInfo -> Var -> Bool
isMetaEquivalent mod v = case metaEquivalent (getModuleStr v) (getNameStr v) of
NoEquivalent -> isJust $ getDefinedMetaEquivalentVar mod v
_ -> True
getMetaEquivalent :: ModInfo -> Var -> CoreM CoreExpr
getMetaEquivalent mod v
= case metaEquivalent (getModuleStr v) (getNameStr v) of
OrigFun -> addWithMetaTypes mod $ Var v
MetaFun name -> addMockedInstances mod False $ getMetaVar mod name
MetaConvertFun name -> do convertFun <- addMockedInstances mod False $ getMetaVar mod name
applyExpr convertFun (Var v)
NoEquivalent -> addMockedInstances mod True $ Var $ fromMaybe
(pprPgmError "No meta equivalent for:" (showVar v <+> text "from module:" <+> text (getModuleStr v)))
(getDefinedMetaEquivalentVar mod v)
where addWithMetaTypes mod e = do (vars, _) <- splitTypeToExprVars $ exprType e
let tvs = filter isTV vars
let args = exprVarsToVars tvs
let eArgs = fmap (Type . withMetaType mod . mkTyVarTy) args
return $ mkCoreLams args $ mkApps e eArgs
----------------------------------------------------------------------------------------
-- Mock class instances
----------------------------------------------------------------------------------------
isPredicateWith :: ModInfo -> (TyCon -> Bool) -> Type -> Bool
isPredicateWith mod cond t
| Just tc <- tyConAppTyCon_maybe t, isClassTyCon tc = cond tc
| otherwise = False
isPredicate :: ModInfo -> Type -> Bool
isPredicate mod = isPredicateWith mod $ const True
isVarPredicate :: ModInfo -> Type -> Bool
isVarPredicate mod = isPredicateWith mod (== varC mod)
isPredicateForMock :: ModInfo -> Bool -> Type -> Bool
isPredicateForMock mod mockPrelude = isPredicateWith mod (\tc -> varC mod == tc || metaLevelC mod == tc || (mockPrelude && isPreludeThing tc))
varPredicatesFromType :: ModInfo -> Type -> [PredType]
varPredicatesFromType mod = filter (isVarPredicate mod) . getAllPreds
mockInstance :: Type -> CoreExpr
mockInstance t = (mkApp (Var uNDEFINED_ID) . Type) t
isMockInstance :: ModInfo -> CoreExpr -> Bool
isMockInstance mod (App (Var x) (Type t)) = uNDEFINED_ID == x && isPredicateForMock mod True t
isMockInstance _ _ = False
addMockedInstances :: ModInfo -> Bool -> CoreExpr -> CoreM CoreExpr
addMockedInstances mod mockPrelude = addMockedInstancesExcept mod mockPrelude []
addMockedInstancesExcept :: ModInfo -> Bool -> [PredType] -> CoreExpr -> CoreM CoreExpr
addMockedInstancesExcept mod mockPrelude exceptTys e
= do (vs, ty, subst) <- splitTypeToExprVarsWithSubst $ exprType e
let exceptTys' = substTy subst <$> exceptTys
let (vvs, evs) = (exprVarsToVars vs, exprVarsToExprs vs)
let vvs' = filter (\v -> isTypeVar v || not (forMock exceptTys' $ varType v)) vvs
let evs' = mockPredOrDict exceptTys' <$> evs
let e' = mkApps e evs'
let argTys = init $ getFunTypeParts $ exprType e'
args <- mkMockedArgs (length argTys) argTys
let (xs, es) = unzip args
return $ simpleOptExpr $ if all isVar es
then mkCoreLams vvs' e'
else mkCoreLams (vvs' ++ xs) $ mkApps e' es
where -- isTypeArg checked before call exprType on e
forMock exceptTys t = isPredicateForMock mod mockPrelude t && notElem t exceptTys
mockPredOrDict exceptTys e = if not (isTypeArg e) && forMock exceptTys (exprType e) then mockInstance (exprType e) else e
mkMockedArgs n (t:ts) = do x <- mkLocalVar ("x" ++ show (n - length ts)) (typeWithoutVarPreds t)
(vs, t') <- splitTypeToExprVars t
let (vvs, evs) = (exprVarsToVars vs, exprVarsToExprs vs)
let evs' = filter (\ev -> isTypeArg ev || not (isVarPredicate mod $ exprType ev)) evs
let e = if length evs == length evs' then Var x else mkCoreLams vvs $ mkApps (Var x) evs'
args <- mkMockedArgs n ts
return ((x, e) : args)
mkMockedArgs _ [] = return []
typeWithoutVarPreds t
| Just (tv, t') <- splitForAllTy_maybe t = mkForAllTy tv $ typeWithoutVarPreds t'
| Just (t1,t2) <- splitFunTy_maybe t = if isVarPredicate mod t1
then typeWithoutVarPreds t2
else mkFunTy t1 $ typeWithoutVarPreds t2
| otherwise = t
----------------------------------------------------------------------------------------
-- Replace mocked class instances with real ones
----------------------------------------------------------------------------------------
type DictInstances = [(Type, DictId)]
type ReplaceVars = [(CoreBndr, CoreBndr)]
data ReplaceInfo = ReplaceInfo {varInstances :: DictInstances, replaceBinds :: ReplaceVars, nextReplaceBinds :: ReplaceVars, noMocks :: Bool}
instance Outputable ReplaceInfo where
ppr (ReplaceInfo dis rb nrb nm) = text "ReplaceInfo{" <+> ppr dis <+> text ","
<+> vcat (fmap (\(x,y) -> ppr x <+> ppr (varType x) <+> text "~>" <+> ppr (varType y)) rb) <+> text ","
<+> vcat (fmap (\(x,y) -> ppr x <+> ppr (varType x) <+> text "~>" <+> ppr (varType y)) nrb) <+> text ","
<+> ppr nm <+> text "}"
emptyReplaceInfo :: ReplaceInfo
emptyReplaceInfo = ReplaceInfo [] [] [] True
noMoreReplaceBinds :: ReplaceInfo -> Bool
noMoreReplaceBinds = null . nextReplaceBinds
noVarInstances :: ReplaceInfo -> Bool
noVarInstances = null . varInstances
findVarInstance :: Type -> ReplaceInfo -> Maybe DictId
findVarInstance t = lookup t . varInstances
addVarInstance :: (Type, DictId) -> ReplaceInfo -> ReplaceInfo
addVarInstance (t, v) ri = ri {varInstances = (t, v) : (varInstances ri)}
addBindToReplace :: (CoreBndr, CoreBndr) -> ReplaceInfo -> ReplaceInfo
addBindToReplace (b, b') ri = ri {nextReplaceBinds = (b, b') : (nextReplaceBinds ri)}
findReplaceBind :: ModInfo -> Var -> ReplaceInfo -> Maybe Var
findReplaceBind mod x = fmap snd . find (\(x',_) -> x == x' && varType x == varType x') . replaceBinds
nextReplaceInfo :: ReplaceInfo -> ReplaceInfo
nextReplaceInfo ri = ReplaceInfo [] (nextReplaceBinds ri) [] True
withMocks :: ReplaceInfo -> ReplaceInfo
withMocks ri = ri {noMocks = False}
replaceMocksByInstancesInProgram :: ModInfo -> CoreProgram -> CoreM CoreProgram
replaceMocksByInstancesInProgram mod bs = go bs emptyReplaceInfo
where go bs ri = do (bs', ri') <- replace ri bs
if noMoreReplaceBinds ri' && noMocks ri' then return bs' else go bs' $ nextReplaceInfo ri'
replace ri (b:bs) = do (bs', ri') <- replace ri bs
(b', ri'') <- replaceMocksByInstancesInBind mod (b, [], ri')
if noVarInstances ri''
then return (b':bs', ri'')
else pprPanic "replaceMocksByInstancesInProgram - not empty var instances to insert:" (ppr ri'' <+> ppr b')
replace ri [] = return ([], ri)
-- args: mod info, (bind, dict instances from surrounding expression, replace info)
replaceMocksByInstancesInBind :: ModInfo -> (CoreBind, DictInstances, ReplaceInfo) -> CoreM (CoreBind, ReplaceInfo)
replaceMocksByInstancesInBind mod (b, dis, ri) = replace b dis ri
where replace (NonRec b e) dis ri = do ((b', e'), ri') <- replaceBind (b, e) dis ri
return (NonRec b' e', ri')
replace (Rec bs) dis ri = do (bs', ri') <- replaceBinds bs dis ri
return (Rec bs', ri')
replaceBinds (b:bs) dis ri = do (bs', ri') <- replaceBinds bs dis ri
(b', ri'') <- replaceBind b dis ri'
return (b':bs', ri'')
replaceBinds [] dis ri = return ([], ri)
replaceBind (b, e) dis ri = do (e', ri') <- replaceMocksByInstancesInExpr mod (e, dis, ri)
if varType b == exprType e'
then return ((b, e'), ri')
else let b' = setVarType b $ exprType e'
in return ((b', e'), addBindToReplace (b, b') ri')
-- args: mod info, (expression, dict instances from surrounding expression, replace info)
replaceMocksByInstancesInExpr :: ModInfo -> (CoreExpr, DictInstances, ReplaceInfo) -> CoreM (CoreExpr, ReplaceInfo)
replaceMocksByInstancesInExpr mod (e, dis, ri) = do (e', ri') <- replace e dis ri
return (simpleOptExpr e', ri')
where replace e dis ri | isMockInstance mod e = replaceMock (exprType e) dis ri
replace e dis ri | (tvs, e') <- collectTyBinders e, not (null tvs)
= do (e'', ri') <- replace e' dis ri
let (vis1, vis2) = partition (\(t,vi) -> any (`elemVarSet` (tyVarsOfType t)) tvs) (varInstances ri')
return (mkCoreLams (tvs ++ fmap snd vis1) e'', ri' {varInstances = vis2})
replace (Var x) dis ri | Just x' <- findReplaceBind mod x ri
= do x'' <- addMockedInstancesExcept mod False (varPredicatesFromType mod $ varType x) (Var x')
return (x'', withMocks ri)
replace (App f e) dis ri = do (f', ri') <- replace f dis ri
(e', ri'') <- replace e dis ri'
let argTy = funArgTy $ exprType f'
let f'' = if not (isTypeArg e') && isVarPredicate mod argTy && not (isVarPredicate mod $ exprType e')
then mkApp f' (mockInstance argTy)
else f'
return (mkApp f'' e', ri'')
replace (Lam x e) dis ri = do let dis' = if isPredicate mod $ varType x then (varType x, x) : dis else dis
(e', ri') <- replace e dis' ri
return (Lam x e', ri')
replace (Let b e) dis ri = do (b', ri') <- replaceMocksByInstancesInBind mod (b, dis, ri)
(e', ri'') <- replace e dis ri'
return (Let b' e', ri'')
replace (Case e x t as) dis ri = do (e', ri') <- replace e dis ri
(as', ri'') <- replaceAlts as dis ri'
return (Case e' x t as', ri'')
replace (Cast e c) dis ri = do (e', ri') <- replace e dis ri
let c' = updateCoercionType (exprType e') c
return (Cast e' c', ri')
replace (Tick t e) dis ri = do (e', ri') <- replace e dis ri
return (Tick t e', ri')
replace e dis ri = return (e, ri)
replaceAlts (a:as) dis ri = do (as', ri') <- replaceAlts as dis ri
(a', ri'') <- replaceAlt a dis ri'
return (a':as', ri'')
replaceAlts [] dis ri = return ([], ri)
replaceAlt (con, xs, e) dis ri = do (e', ri') <- replace e dis ri
return ((con, xs, e'), ri')
replaceMock t dis ri
| Just v <- lookup t dis = return (Var v, ri)
| isVarPredicate mod t, Just v <- findVarInstance t ri = return (Var v, ri)
| Just di <- dictInstance mod t = do di' <- addMockedInstances mod True di
return (di', withMocks ri)
| isVarPredicate mod t = do v <- mkPredVar $ getClassPredTys t
return (Var v, addVarInstance (t, v) ri)
| Just sc <- findSuperClass t (Var <$> snd <$> dis) = return (sc, ri)
| otherwise = pprPanic "replaceMock - can't create class instance for " (ppr t)
dictInstance :: ModInfo -> Type -> Maybe CoreExpr
dictInstance mod t
| Just (tc, ts) <- splitTyConApp_maybe t' = Just $ mkApps inst (Type <$> ts)
| isJust (isNumLitTy t') || isJust (isStrLitTy t') = Just inst
| isFunTy t' = Just inst
| otherwise = Nothing
where Just (cl, [t']) = getClassPredTys_maybe t
inst = getClassInstance mod cl t'
----------------------------------------------------------------------------------------
-- Show
----------------------------------------------------------------------------------------
when c v = if c then text " " <> ppr v else text ""
whenT c v = if c then text " " <> text v else text ""
showBind :: CoreBind -> SDoc
showBind (NonRec b e) = showBindExpr (b, e)
showBind (Rec bs) = hcat $ map showBindExpr bs
showBindExpr :: (CoreBndr, CoreExpr) -> SDoc
showBindExpr (b,e) = text "===> "
<+> showVar b
<+> text "::"
<+> showType (varType b)
<+> (if noAtomsType $ varType b then text "[no atoms]" else text "[atoms]")
<> text "\n"
<+> showExpr e
<> text "\n"
showType :: Type -> SDoc
showType = ppr
showType (TyVarTy v) = text "TyVarTy(" <> showVar v <> text ")"
showType (AppTy t1 t2) = text "AppTy(" <> showType t1 <+> showType t2 <> text ")"
showType (TyConApp tc ts) = text "TyConApp(" <> showTyCon tc <+> hsep (fmap showType ts) <> text ")"
showType (FunTy t1 t2) = text "FunTy(" <> showType t1 <+> showType t2 <> text ")"
showType (ForAllTy v t) = text "ForAllTy(" <> showVar v <+> showType t <> text ")"
showType (LitTy tl) = text "LitTy(" <> ppr tl <> text ")"
showTyCon :: TyCon -> SDoc
showTyCon = ppr
--showTyCon tc = text "'" <> text (occNameString $ nameOccName $ tyConName tc) <> text "'"
-- <> text "{"
< > ppr ( nameUnique $ tyConName tc )
-- <> (whenT (isAlgTyCon tc) ",Alg")
-- <> (whenT (isClassTyCon tc) ",Class")
-- <> (whenT (isFamInstTyCon tc) ",FamInst")
< > ( whenT ( ) " , Fun " )
< > ( whenT ( isPrimTyCon tc ) " , " )
-- <> (whenT (isTupleTyCon tc) ",Tuple")
< > ( whenT ( isUnboxedTupleTyCon tc ) " , UnboxedTuple " )
< > ( whenT ( isBoxedTupleTyCon tc ) " , BoxedTuple " )
< > ( whenT ( ) " , TypeSynonym " )
< > ( whenT ( isDecomposableTyCon tc ) " , Decomposable " )
-- <> (whenT (isPromotedDataCon tc) ",PromotedDataCon")
< > ( whenT ( isPromotedTyCon tc ) " , Promoted " )
< > ( whenT ( isDataTyCon tc ) " , DataTyCon " )
-- <> (whenT (isProductTyCon tc) ",ProductTyCon")
-- <> (whenT (isEnumerationTyCon tc) ",EnumerationTyCon")
-- <> (whenT (isNewTyCon tc) ",NewTyCon")
< > ( whenT ( ) " , AbstractTyCon " )
-- <> (whenT (isFamilyTyCon tc) ",FamilyTyCon")
< > ( whenT ( isOpenFamilyTyCon tc ) " , OpenFamilyTyCon " )
< > ( whenT ( isTypeFamilyTyCon tc ) " , " )
-- <> (whenT (isDataFamilyTyCon tc) ",DataFamilyTyCon")
-- <> (whenT (isOpenTypeFamilyTyCon tc) ",OpenTypeFamilyTyCon")
-- <> (whenT (isUnLiftedTyCon tc) ",UnLiftedTyCon")
< > ( whenT ( isGadtSyntaxTyCon tc ) " , " )
-- <> (whenT (isDistinctTyCon tc) ",DistinctTyCon")
-- < > ( whenT ( ) " , DistinctAlgRhs " )
-- < > ( whenT ( isInjectiveTyCon tc ) " , " )
---- <> (whenT (isGenerativeTyCon tc) ",GenerativeTyCon")
---- <> (whenT (isGenInjAlgRhs tc) ",GenInjAlgRhs")
< > ( whenT ( ) " , TyConAssoc " )
-- <> (whenT (isRecursiveTyCon tc) ",RecursiveTyCon")
-- <> (whenT (isImplicitTyCon tc) ",ImplicitTyCon")
< > ( text " , dataConNames : " < + > ( vcat $ fmap showName $ fmap dataConName $ tyConDataCons tc ) )
-- <> text "}"
showName :: Name -> SDoc
showName = ppr
--showName n = text "<"
< > ppr ( nameOccName n )
< + > ppr ( nameUnique n )
-- <+> text "("
-- <> ppr (nameModule_maybe n)
-- <> text ")"
-- <+> ppr (nameSrcLoc n)
< + > ppr ( nameSrcSpan n )
-- <+> whenT (isInternalName n) "internal"
-- <+> whenT (isExternalName n) "external"
-- <+> whenT (isSystemName n) "system"
-- <+> whenT (isWiredInName n) "wired in"
-- <> text ">"
showOccName :: OccName -> SDoc
showOccName n = text "<"
<> ppr n
<+> pprNameSpace (occNameSpace n)
<> whenT (isVarOcc n) " VarOcc"
<> whenT (isTvOcc n) " TvOcc"
<> whenT (isTcOcc n) " TcOcc"
<> whenT (isDataOcc n) " DataOcc"
<> whenT (isDataSymOcc n) " DataSymOcc"
<> whenT (isSymOcc n) " SymOcc"
<> whenT (isValOcc n) " ValOcc"
<> text ">"
showVar :: Var -> SDoc
showVar = ppr
v = text " [ "
-- <> showName (varName v)
< + > ppr ( varUnique v )
-- <+> showType (varType v)
---- <+> showOccName (nameOccName $ varName v)
-- <> (when (isId v) (idDetails v))
< > ( when ( isId v ) ( arityInfo $ idInfo v ) )
< > ( when ( isId v ) ( unfoldingInfo $ idInfo v ) )
< > ( when ( isId v ) ( cafInfo $ idInfo v ) )
-- <> (when (isId v) (oneShotInfo $ idInfo v))
-- <> (when (isId v) (inlinePragInfo $ idInfo v))
< > ( when ( isId v ) ( occInfo $ idInfo v ) )
< > ( when ( isId v ) ( strictnessInfo $ idInfo v ) )
< > ( when ( isId v ) ( demandInfo $ idInfo v ) )
< > ( when ( isId v ) ( callArityInfo $ idInfo v ) )
-- <> (whenT (isId v) "Id")
< > ( whenT ( isDictId v ) " DictId " )
< > ( whenT ( isTKVar v ) " TKVar " )
< > ( whenT ( isTyVar v ) " TyVar " )
< > ( whenT ( v ) " TcTyVar " )
< > ( whenT ( isLocalVar v ) " LocalVar " )
< > ( whenT ( isLocalId v ) " LocalId " )
< > ( whenT ( isGlobalId v ) " GlobalId " )
< > ( whenT ( v ) " ExportedId " )
< > ( whenT ( isEvVar v ) " EvVar " )
-- <> (whenT (isId v && isDataConWorkId v) "DataConWorkId")
< > ( whenT ( isId v & & isRecordSelector v ) " RecordSelector " )
< > ( whenT ( isId v & & ( isJust $ isClassOpId_maybe v ) ) " ClassOpId " )
< > ( whenT ( isId v & & isDFunId v ) " DFunId " )
< > ( whenT ( isId v & & isPrimOpId v ) " PrimOpId " )
< > ( whenT ( isId v & & isConLikeId v ) " ConLikeId " )
< > ( whenT ( isId v & & isRecordSelector v ) " RecordSelector " )
-- <> (whenT (isId v && isFCallId v) "FCallId")
< > ( whenT ( isId v & & hasNoBinding v ) " NoBinding " )
-- <> text "]"
showExpr :: CoreExpr -> SDoc
showExpr (Var i) = text "<" <> showVar i <> text ">"
showExpr (Lit l) = text "Lit" <+> pprLiteral id l
showExpr (App e (Type t)) = showExpr e <+> text "@{" <+> showType t <> text "}"
showExpr (App e a) = text "(" <> showExpr e <> text " $ " <> showExpr a <> text ")"
showExpr (Lam b e) = text "(" <> showVar b <> text " -> " <> showExpr e <> text ")"
showExpr (Let b e) = text "Let" <+> showLetBind b <+> text "in" <+> showExpr e
showExpr (Case e b t as) = text "Case" <+> showExpr e <+> showVar b <+> text "::{" <+> showType t <> text "}" <+> hcat (showAlt <$> as)
showExpr (Cast e c) = text "Cast" <+> showExpr e <+> showCoercion c
showExpr (Tick t e) = text "Tick" <+> ppr t <+> showExpr e
showExpr (Type t) = text "Type" <+> showType t
showExpr (Coercion c) = text "Coercion" <+> text "`" <> showCoercion c <> text "`"
showLetBind (NonRec b e) = showVar b <+> text "=" <+> showExpr e
showLetBind (Rec bs) = hcat $ fmap (\(b,e) -> showVar b <+> text "=" <+> showExpr e) bs
showCoercion :: Coercion -> SDoc
showCoercion c = text "`" <> show c <> text "`"
where show (Refl role typ) = text "Refl" <+> ppr role <+> showType typ
show (TyConAppCo role tyCon cs) = text "TyConAppCo"
show (AppCo c1 c2) = text "AppCo"
show (ForAllCo tyVar c) = text "ForAllCo"
show (CoVarCo coVar) = text "CoVarCo"
show (AxiomInstCo coAxiom branchIndex cs) = text "AxiomInstCo" <+> ppr coAxiom <+> ppr branchIndex <+> vcat (fmap showCoercion cs)
show (UnivCo fastString role type1 type2) = text "UnivCo"
show (SymCo c) = text "SymCo" <+> showCoercion c
show (TransCo c1 c2) = text "TransCo"
show (AxiomRuleCo coAxiomRule types cs) = text "AxiomRuleCo"
show (NthCo int c) = text "NthCo"
show (LRCo leftOrRight c) = text "LRCo"
show (InstCo c typ) = text "InstCo"
show (SubCo c) = text "SubCo"
showAlt (con, bs, e) = text "|" <> ppr con <+> hcat (fmap showVar bs) <+> showExpr e <> text "|"
showClass :: Class -> SDoc
showClass = ppr
showClass cls =
let (tyVars, funDeps, scTheta, scSels, ats, opStuff) = classExtraBigSig cls
in text "Class{"
<+> showName (className cls)
<+> ppr (classKey cls)
<+> ppr tyVars
<+> brackets (fsep (punctuate comma (map (\(m,c) -> parens (sep [showVar m <> comma, ppr c])) opStuff)))
<+> ppr (classMinimalDef cls)
<+> ppr funDeps
<+> ppr scTheta
<+> ppr scSels
<+> text "}"
showDataCon :: DataCon -> SDoc
showDataCon dc =
text "DataCon{"
<+> showName (dataConName dc)
<+> ppr (dataConFullSig dc)
<+> ppr (dataConFieldLabels dc)
<+> ppr (dataConTyCon dc)
<+> ppr (dataConTheta dc)
<+> ppr (dataConStupidTheta dc)
<+> ppr (dataConWorkId dc)
<+> ppr (dataConWrapId dc)
<+> text "}"
| null | https://raw.githubusercontent.com/szynwelski/nlambda/b9acb98af29fc240552b9bb2b991f83306888484/src/meta/MetaPlugin.hs | haskell | return $ showPlug:todo
imported maps
names
classes and vars
show info
putMsg $ text "binds:\n" <+> (foldr (<+>) (text "") $ map showBind $ mg_binds guts' ++ getImplicitBinds guts')
modInfo "module" mg_module guts'
modInfo "dependencies" (dep_mods . mg_deps) guts'
modInfo "imported" getImportedModules guts'
modInfo "exports" mg_exports guts'
modInfo "type constructors" mg_tcs guts'
modInfo "used names" mg_used_names guts'
modInfo "global rdr env" mg_rdr_env guts'
modInfo "fixities" mg_fix_env guts'
modInfo "pattern synonyms" mg_patsyns guts'
modInfo "core rules" mg_rules guts'
modInfo "vect decls" mg_vect_decls guts'
modInfo "vect info" mg_vect_info guts'
modInfo "files" mg_dependent_files guts'
modInfo "implicit binds" getImplicitBinds guts'
modInfo "annotations" mg_anns guts'
--------------------------------------------------------------------------------------
Mod info
--------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------
Guts
--------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------
Annotation
--------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------
Implicit Binds - copy from compiler/main/TidyPgm.hs
--------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------
Names
--------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------
Data constructors
--------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------
Variables
--------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------
Imports
--------------------------------------------------------------------------------------
FIXME check if isAbstractTyCon should be used here
--------------------------------------------------------------------------------------
Exports
--------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------
Classes
--------------------------------------------------------------------------------------
for instances in user modules
--------------------------------------------------------------------------------------
Binds
--------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------
Type
--------------------------------------------------------------------------------------
is ty var under app type
--------------------------------------------------------------------------------------
Checking type contains atoms
--------------------------------------------------------------------------------------
tcs - for recursive definitions, n - number of applied args to tc
classes should be replaced by meta equivalent
--------------------------------------------------------------------------------------
Type thing
--------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------
Expressions map
--------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------
Expressions
--------------------------------------------------------------------------------------
type should be served in (App f (Type t)) case
the type of expression is not open for atoms and there are no free variables open for atoms
--------------------------------------------------------------------------------------
Coercion
--------------------------------------------------------------------------------------
TODO other cases
--------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------
type should be handled in (App f (Type t)) case
FIXME better evaluation of pattern type
--------------------------------------------------------------------------------------
Apply expression
--------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------
Convert meta types
--------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------
Mock class instances
--------------------------------------------------------------------------------------
isTypeArg checked before call exprType on e
--------------------------------------------------------------------------------------
Replace mocked class instances with real ones
--------------------------------------------------------------------------------------
args: mod info, (bind, dict instances from surrounding expression, replace info)
args: mod info, (expression, dict instances from surrounding expression, replace info)
--------------------------------------------------------------------------------------
Show
--------------------------------------------------------------------------------------
showTyCon tc = text "'" <> text (occNameString $ nameOccName $ tyConName tc) <> text "'"
<> text "{"
<> (whenT (isAlgTyCon tc) ",Alg")
<> (whenT (isClassTyCon tc) ",Class")
<> (whenT (isFamInstTyCon tc) ",FamInst")
<> (whenT (isTupleTyCon tc) ",Tuple")
<> (whenT (isPromotedDataCon tc) ",PromotedDataCon")
<> (whenT (isProductTyCon tc) ",ProductTyCon")
<> (whenT (isEnumerationTyCon tc) ",EnumerationTyCon")
<> (whenT (isNewTyCon tc) ",NewTyCon")
<> (whenT (isFamilyTyCon tc) ",FamilyTyCon")
<> (whenT (isDataFamilyTyCon tc) ",DataFamilyTyCon")
<> (whenT (isOpenTypeFamilyTyCon tc) ",OpenTypeFamilyTyCon")
<> (whenT (isUnLiftedTyCon tc) ",UnLiftedTyCon")
<> (whenT (isDistinctTyCon tc) ",DistinctTyCon")
< > ( whenT ( ) " , DistinctAlgRhs " )
< > ( whenT ( isInjectiveTyCon tc ) " , " )
-- <> (whenT (isGenerativeTyCon tc) ",GenerativeTyCon")
-- <> (whenT (isGenInjAlgRhs tc) ",GenInjAlgRhs")
<> (whenT (isRecursiveTyCon tc) ",RecursiveTyCon")
<> (whenT (isImplicitTyCon tc) ",ImplicitTyCon")
<> text "}"
showName n = text "<"
<+> text "("
<> ppr (nameModule_maybe n)
<> text ")"
<+> ppr (nameSrcLoc n)
<+> whenT (isInternalName n) "internal"
<+> whenT (isExternalName n) "external"
<+> whenT (isSystemName n) "system"
<+> whenT (isWiredInName n) "wired in"
<> text ">"
<> showName (varName v)
<+> showType (varType v)
-- <+> showOccName (nameOccName $ varName v)
<> (when (isId v) (idDetails v))
<> (when (isId v) (oneShotInfo $ idInfo v))
<> (when (isId v) (inlinePragInfo $ idInfo v))
<> (whenT (isId v) "Id")
<> (whenT (isId v && isDataConWorkId v) "DataConWorkId")
<> (whenT (isId v && isFCallId v) "FCallId")
<> text "]" | module MetaPlugin where
import Avail
import qualified BooleanFormula as BF
import Class
import CoAxiom hiding (toUnbranchedList)
import Control.Applicative ((<|>))
import Control.Monad (liftM)
import Data.Char (isLetter, isLower)
import Data.Foldable (foldlM)
import Data.List ((\\), delete, find, findIndex, intersect, isInfixOf, isPrefixOf, nub, partition)
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Maybe (catMaybes, fromJust, fromMaybe, isJust, isNothing, listToMaybe, mapMaybe)
import Data.String.Utils (replace)
import GhcPlugins hiding (mkApps, mkLocalVar, substTy)
import InstEnv (ClsInst, instanceDFunId, instanceHead, instanceRoughTcs, is_cls_nm, is_flag, is_orphan, mkImportedInstance)
import Kind (defaultKind, isOpenTypeKind)
import Meta
import MkId (mkDataConWorkId, mkDictSelRhs)
import Pair (pFst, pSnd)
import TypeRep
import TcType (tcSplitSigmaTy, tcSplitPhiTy)
import Unify (tcUnifyTy)
plugin :: Plugin
plugin = defaultPlugin {
installCoreToDos = install
}
install :: [CommandLineOption] -> [CoreToDo] -> CoreM [CoreToDo]
install _ todo = do
reinitializeGlobals
env <- getHscEnv
let metaPlug = CoreDoPluginPass "MetaPlugin" $ pass env False
let showPlug = CoreDoPluginPass "ShowPlugin" $ pass env True
return $ metaPlug:todo
return $ metaPlug : todo + + [ showPlug ]
modInfo :: Outputable a => String -> (ModGuts -> a) -> ModGuts -> CoreM ()
modInfo label fun guts = putMsg $ text label <> text ": " <> (ppr $ fun guts)
headPanic :: String -> SDoc -> [a] -> a
headPanic msg doc [] = pprPanic ("headPanic - " ++ msg) doc
headPanic _ _ l = head l
tailPanic :: String -> SDoc -> [a] -> [a]
tailPanic msg doc [] = pprPanic ("tailPanic - " ++ msg) doc
tailPanic _ _ l = tail l
pprE :: String -> CoreExpr -> SDoc
pprE n e = text (n ++ " =") <+> ppr e <+> text "::" <+> ppr (exprType e)
pprV :: String -> CoreBndr -> SDoc
pprV n v = text (n ++ " =") <+> ppr v <+> text "::" <+> ppr (varType v)
pass :: HscEnv -> Bool -> ModGuts -> CoreM ModGuts
pass env onlyShow guts =
if withMetaAnnotation guts
then do putMsg $ text "Ignore module: " <+> (ppr $ mg_module guts)
return guts
else do putMsg $ text ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> start:"
<+> (ppr $ mg_module guts)
<+> if onlyShow then text "[only show]" else text ""
mod info - all info in one place
let metaMods = getMetaModules env
let mod = modInfoEmptyMaps env guts metaMods
let (impNameMap, impVarMap, impTcMap) = getImportedMaps mod
let metaNameMap = getMetaPreludeNameMap mod
nameMap <- mkNamesMap guts $ Map.union impNameMap metaNameMap
let mod' = mod {nameMap = nameMap}
let tcMap = mkTyConMap mod' {varMap = unionVarMaps varMap impVarMap} (mg_tcs guts)
varMap = mkVarMap mod' {tcMap = unionTcMaps tcMap impTcMap}
let mod'' = mod' {tcMap = unionTcMaps tcMap impTcMap, varMap = unionVarMaps varMap impVarMap}
guts' <- if onlyShow then return guts else newGuts mod'' guts
putMsg $ text " classes:\n " < + > ( vcat $ fmap showClass $ getClasses guts ' )
modInfo " binds " ( . mg_binds ) guts '
modInfo " class instances " mg_insts guts '
modInfo " family instances " mg_fam_insts guts '
modInfo " classes " getClasses guts '
putMsg $ text ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> end:" <+> (ppr $ mg_module guts')
return guts'
data ModInfo = ModInfo {env :: HscEnv, guts :: ModGuts, metaModules :: [MetaModule], nameMap :: NameMap, tcMap :: TyConMap, varMap :: VarMap}
modInfoEmptyMaps :: HscEnv -> ModGuts -> [MetaModule] -> ModInfo
modInfoEmptyMaps env guts metaMods = ModInfo env guts metaMods Map.empty emptyTcMap emptyVarMap
instance Outputable ModInfo where
ppr mod = text "\n======== ModInfo =========================================================="
<+> showMap "\nNames" (nameMap mod) showName
<+> showMap "\nTyCons" (tcsWithPairs mod) showTyCon
<+> showMap "\nVars" (varsWithPairs mod) showVar
<+> text "\nAll type cons:" <+> vcat (fmap showTyCon $ allTcs mod)
<+> text "\nAll vars:" <+> vcat (fmap showVar $ allVars mod)
<+> text "\n==========================================================================="
showMap :: String -> Map a a -> (a -> SDoc) -> SDoc
showMap header map showElem = text (header ++ ":\n")
<+> (vcat (concatMap (\(x,y) -> [showElem x <+> text "->" <+> showElem y]) $ Map.toList map))
newGuts :: ModInfo -> ModGuts -> CoreM ModGuts
newGuts mod guts = do binds <- newBinds mod (getDataCons guts) (mg_binds guts)
binds' <- replaceMocksByInstancesInProgram mod (checkCoreProgram binds)
let exps = newExports mod (mg_exports guts)
let usedNames = newUsedNames mod (mg_used_names guts)
let clsInsts = newClassInstances mod (mg_insts guts)
let tcs = filter (inCurrentModule mod) $ Map.elems (tcsWithPairs mod)
return $ guts {mg_tcs = mg_tcs guts ++ tcs,
mg_binds = mg_binds guts ++ checkCoreProgram binds',
mg_exports = mg_exports guts ++ exps,
mg_insts = mg_insts guts ++ clsInsts,
mg_used_names = usedNames}
withMetaAnnotation :: ModGuts -> Bool
withMetaAnnotation guts = isJust $ find isMetaAnn $ mg_anns guts
where isMetaAnn a = case fromSerialized deserializeWithData $ ann_value a of
Just "WithMeta" -> True
_ -> False
getImplicitBinds :: ModGuts -> [CoreBind]
getImplicitBinds guts = (concatMap getClassImplicitBinds $ getClasses guts) ++ (concatMap getTyConImplicitBinds $ mg_tcs guts)
getClassImplicitBinds :: Class -> [CoreBind]
getClassImplicitBinds cls
= [ NonRec op (mkDictSelRhs cls val_index)
| (op, val_index) <- classAllSelIds cls `zip` [0..] ]
getTyConImplicitBinds :: TyCon -> [CoreBind]
getTyConImplicitBinds tc = map get_defn (mapMaybe dataConWrapId_maybe (tyConDataCons tc))
get_defn :: Id -> CoreBind
get_defn id = NonRec id (unfoldingTemplate (realIdUnfolding id))
type NameMap = Map Name Name
nameMember :: ModInfo -> Name -> Bool
nameMember mod name = Map.member name $ nameMap mod
newName :: ModInfo -> Name -> Name
newName mod name = Map.findWithDefault (pprPanic "unknown name: " (showName name <+> vcat (showName <$> Map.keys map))) name map
where map = nameMap mod
mkNamesMap :: ModGuts -> NameMap -> CoreM NameMap
mkNamesMap guts impNameMap = do nameMap <- mkSuffixNamesMap (getDataConsNames guts ++ getBindsNames guts ++ getClassesNames guts)
return $ Map.union nameMap impNameMap
nameSuffix :: String -> String
nameSuffix name = if any isLetter name then name_suffix else op_suffix
nlambdaName :: String -> String
nlambdaName name = name ++ nameSuffix name
mkSuffixNamesMap :: [Name] -> CoreM NameMap
mkSuffixNamesMap names = do names' <- mapM (createNewName nameSuffix) names
return $ Map.fromList $ zip names names'
createNewName :: (String -> String) -> Name -> CoreM Name
createNewName suffix name = let occName = nameOccName name
nameStr = occNameString occName
newOccName = mkOccName (occNameSpace occName) (nameStr ++ suffix nameStr)
in newUniqueName $ tidyNameOcc name newOccName
newUniqueName :: Name -> CoreM Name
newUniqueName name = do uniq <- getUniqueM
return $ setNameLoc (setNameUnique name uniq) noSrcSpan
getNameStr :: NamedThing a => a -> String
getNameStr = occNameString . nameOccName . getName
getModuleStr :: NamedThing a => a -> String
getModuleStr = maybe "" getModuleNameStr . nameModule_maybe . getName
getModuleNameStr :: Module -> String
getModuleNameStr = moduleNameString . moduleName
newUsedNames :: ModInfo -> NameSet -> NameSet
newUsedNames mod ns = mkNameSet (nms ++ nms')
where nms = nameSetElems ns
nms' = fmap (newName mod) $ filter (nameMember mod) nms
isPreludeThing :: NamedThing a => a -> Bool
isPreludeThing = (`elem` preludeModules) . getModuleStr
inCurrentModule :: NamedThing a => ModInfo -> a -> Bool
inCurrentModule mod x = mg_module (guts mod) == nameModule (getName x)
getDataCons :: ModGuts -> [DataCon]
getDataCons = concatMap tyConDataCons . filter (not . isClassTyCon) .filter isAlgTyCon . mg_tcs
getDataConsVars :: ModGuts -> [Var]
getDataConsVars = concatMap dataConImplicitIds . getDataCons
getDataConsNames :: ModGuts -> [Name]
getDataConsNames = concatMap (\dc -> dataConName dc : (idName <$> dataConImplicitIds dc)) . getDataCons
type VarMap = (Map Var Var, [Var])
emptyVarMap :: VarMap
emptyVarMap = (Map.empty, [])
varsWithPairs :: ModInfo -> Map Var Var
varsWithPairs = fst . varMap
allVars :: ModInfo -> [Var]
allVars mod = snd vm ++ Map.keys (fst vm) ++ Map.elems (fst vm)
where vm = varMap mod
unionVarMaps :: VarMap -> VarMap -> VarMap
unionVarMaps (m1,l1) (m2,l2) = (Map.union m1 m2, nub $ l1 ++ l2)
newVar :: ModInfo -> Var -> Var
newVar mod v = Map.findWithDefault (pprPanic "unknown variable: " (ppr v <+> ppr (Map.assocs map))) v map
where map = varsWithPairs mod
varMapMember :: ModInfo -> Var -> Bool
varMapMember mod v = Map.member v $ varsWithPairs mod
mkVarMap :: ModInfo -> VarMap
mkVarMap mod = let g = guts mod in mkMapWithVars mod (getBindsVars g ++ getClassesVars g ++ getDataConsVars g)
mkMapWithVars :: ModInfo -> [Var] -> VarMap
mkMapWithVars mod vars = (Map.fromList $ zip varsWithPairs $ fmap newVar varsWithPairs, nub (varsWithoutPairs ++ varsFromExprs))
where (varsWithPairs, varsWithoutPairs) = partition (not . isIgnoreImportType mod . varType) vars
varsFromExprs = getAllVarsFromBinds mod \\ varsWithPairs
newVar v = let t = changeType mod $ varType v
v' = mkExportedLocalVar
(newIdDetails $ idDetails v)
(newName mod $ varName v)
(maybe t (\c -> addVarContextForHigherOrderClass mod c t) (userClassOpId mod v))
vanillaIdInfo
in if isExportedId v then setIdExported v' else setIdNotExported v'
newIdDetails (RecSelId tc naughty) = RecSelId (newTyCon mod tc) naughty
newIdDetails (ClassOpId cls) = ClassOpId $ newClass mod cls
newIdDetails (PrimOpId op) = PrimOpId op
newIdDetails (FCallId call) = FCallId call
newIdDetails (DFunId n b) = DFunId n b
newIdDetails _ = VanillaId
getAllVarsFromBinds :: ModInfo -> [Var]
getAllVarsFromBinds = nub . concatMap getAllNotLocalVarsFromExpr . concatMap rhssOfBind . mg_binds . guts
mkVarUnique :: Var -> CoreM Var
mkVarUnique v = do uniq <- getUniqueM
return $ setVarUnique v uniq
mkLocalVar :: String -> Type -> CoreM Var
mkLocalVar varName ty = do uniq <- getUniqueM
let nm = mkInternalName uniq (mkVarOcc varName) noSrcSpan
return $ mkLocalId nm ty
mkPredVar :: (Class, [Type]) -> CoreM DictId
mkPredVar (cls, tys) = do uniq <- getUniqueM
let name = mkSystemName uniq (mkDictOcc (getOccName cls))
return $ mkLocalId name $ mkClassPred cls tys
isVar :: CoreExpr -> Bool
isVar (Var _) = True
isVar _ = False
importsToIgnore :: [Meta.ModuleName]
importsToIgnore = [metaModuleName, "GHC.Generics"]
isIgnoreImport :: Module -> Bool
isIgnoreImport = (`elem` importsToIgnore) . moduleNameString . moduleName
getImportedModules :: ModGuts -> [Module]
getImportedModules = filter (not . isIgnoreImport) . moduleEnvKeys . mg_dir_imps
getImportedMaps :: ModInfo -> (NameMap, VarMap, TyConMap)
getImportedMaps mod = (Map.fromList namePairs, (Map.fromList varPairs, varWithoutPair), (Map.fromList tcPairs, tcWithoutPair))
where mods = catMaybes $ fmap (lookupUFM $ hsc_HPT $ env mod) $ fmap moduleName $ getImportedModules (guts mod)
things = eltsUFM $ getModulesTyThings mods
(tcThings, varThings) = fmap (filter isTyThingId) $ partition isTyThingTyCon things
tcPairs = fmap (\(tt1, tt2) -> (tyThingTyCon tt1, tyThingTyCon tt2)) $ catMaybes $ findPair things TyThingTyCon <$> getName <$> tcThings
varPairs = fmap (\(tt1, tt2) -> (tyThingId tt1, tyThingId tt2)) $ catMaybes $ findPair things TyThingId <$> getName <$> varThings
tcWithoutPair = (tyThingTyCon <$> tcThings) \\ (uncurry (++) $ unzip $ tcPairs)
varWithoutPair = (tyThingId <$> varThings) \\ (uncurry (++) $ unzip $ varPairs)
getNamePair (x, y) = (getName x, getName y)
namePairs = (getNamePair <$> tcPairs) ++ (getNamePair <$> varPairs)
isIgnoreImportType :: ModInfo -> Type -> Bool
isIgnoreImportType mod = anyNameEnv (\tc -> (isIgnoreImport $ nameModule $ getName tc) || isAbstractTyCon tc || varC mod == tc) . tyConsOfType
newExports :: ModInfo -> Avails -> Avails
newExports mod avls = concatMap go avls
where go (Avail n) = [Avail $ newName mod n]
go (AvailTC nm nms) | nameMember mod nm = [AvailTC (newName mod nm) (newName mod <$> nms)]
go (AvailTC _ nms) = (Avail . newName mod) <$> (drop 1 nms)
getClasses :: ModGuts -> [Class]
getClasses = catMaybes . fmap tyConClass_maybe . mg_tcs
getClassDataCons :: Class -> [DataCon]
getClassDataCons = tyConDataCons . classTyCon
getClassesVars :: ModGuts -> [Var]
getClassesVars = concatMap (\c -> classAllSelIds c ++ (concatMap dataConImplicitIds $ getClassDataCons c)) . getClasses
getClassesNames :: ModGuts -> [Name]
getClassesNames = concatMap classNames . getClasses
where classNames c = className c : (fmap idName $ classAllSelIds c) ++ dataConNames c
dataConNames c = concatMap (\dc -> dataConName dc : (idName <$> dataConImplicitIds dc)) $ getClassDataCons c
type TyConMap = (Map TyCon TyCon, [TyCon])
emptyTcMap :: TyConMap
emptyTcMap = (Map.empty, [])
tcsWithPairs :: ModInfo -> Map TyCon TyCon
tcsWithPairs = fst . tcMap
allTcs :: ModInfo -> [TyCon]
allTcs mod = snd tcm ++ Map.keys (fst tcm) ++ Map.elems (fst tcm)
where tcm = tcMap mod
allClasses :: ModInfo -> [Class]
allClasses mod = [c | Just c <- tyConClass_maybe <$> allTcs mod]
unionTcMaps :: TyConMap -> TyConMap -> TyConMap
unionTcMaps (m1, l1) (m2, l2) = (Map.union m1 m2, nub $ l1 ++ l2)
newTyCon :: ModInfo -> TyCon -> TyCon
newTyCon mod tc = Map.findWithDefault metaPrelude tc $ fst $ tcMap mod
where metaPrelude = fromMaybe
(pprPgmError "Unknown type constructor:"
(ppr tc <+> text ("\nProbably module " ++ getModuleStr tc ++ " is not compiled with NLambda Plugin.")))
(getMetaPreludeTyCon mod tc)
newClass :: ModInfo -> Class -> Class
newClass mod = fromJust . tyConClass_maybe . newTyCon mod . classTyCon
mkTyConMap :: ModInfo -> [TyCon] -> TyConMap
mkTyConMap mod tcs = let ctcs = filter isClassTyCon tcs
ctcs' = fmap (newTyConClass mod {tcMap = tcMap}) ctcs
tcMap = (Map.fromList $ zip ctcs ctcs', filter isAlgTyCon tcs)
in tcMap
newTyConClass :: ModInfo -> TyCon -> TyCon
newTyConClass mod tc = let tc' = createTyConClass mod cls rhs tc
rhs = createAlgTyConRhs mod cls $ algTyConRhs tc
cls = createClass mod tc' $ fromJust $ tyConClass_maybe tc
in tc'
createTyConClass :: ModInfo -> Class -> AlgTyConRhs -> TyCon -> TyCon
createTyConClass mod cls rhs tc = mkClassTyCon
(newName mod $ tyConName tc)
(tyConKind tc)
FIXME new unique ty vars ?
(tyConRoles tc)
rhs
cls
(if isRecursiveTyCon tc then Recursive else NonRecursive)
createAlgTyConRhs :: ModInfo -> Class -> AlgTyConRhs -> AlgTyConRhs
createAlgTyConRhs mod cls rhs = create rhs
where create (AbstractTyCon b) = AbstractTyCon b
create DataFamilyTyCon = DataFamilyTyCon
create (DataTyCon dcs isEnum) = DataTyCon (createDataCon mod <$> dcs) isEnum
create (NewTyCon dc ntRhs ntEtadRhs ntCo) = NewTyCon (createDataCon mod dc)
(changeType mod ntRhs)
(changeType mod <$> ntEtadRhs)
(changeUnbranchedCoAxiom mod cls ntCo)
createDataCon :: ModInfo -> DataCon -> DataCon
createDataCon mod dc =
let name = newName mod $ dataConName dc
workerName = newName mod $ idName $ dataConWorkId dc
workerId = mkDataConWorkId workerName dc'
(univ_tvs, ex_tvs, eq_spec, theta, arg_tys, res_ty) = dataConFullSig dc
dc' = mkDataCon
name
(dataConIsInfix dc)
[]
[]
univ_tvs
ex_tvs
((\(tv, t) -> (tv, changeType mod t)) <$> eq_spec)
(changePredType mod <$> theta)
(changeType mod <$> arg_tys)
(changeType mod res_ty)
(newTyCon mod $ dataConTyCon dc)
(changePredType mod <$> dataConStupidTheta dc)
workerId
FIXME use mkDataConRep
in dc'
createClass :: ModInfo -> TyCon -> Class -> Class
createClass mod tc cls =
let (tyVars, funDeps, scTheta, scSels, ats, opStuff) = classExtraBigSig cls
scSels' = fmap (newVar mod) scSels
opStuff' = fmap (\(v, dm) -> (newVar mod v, updateDefMeth dm)) opStuff
in mkClass
tyVars
funDeps
FIXME new predType ?
scSels'
FIXME new associated types ?
opStuff'
(updateMinDef $ classMinimalDef cls)
tc
where updateDefMeth NoDefMeth = NoDefMeth
updateDefMeth (DefMeth n) = DefMeth $ newName mod n
updateDefMeth (GenDefMeth n) = GenDefMeth $ newName mod n
updateMinDef (BF.Var n) = BF.Var $ newName mod n
updateMinDef (BF.And fs) = BF.And $ updateMinDef <$> fs
updateMinDef (BF.Or fs) = BF.Or $ updateMinDef <$> fs
getClassInstance :: ModInfo -> Class -> Type -> CoreExpr
getClassInstance mod cl t
for instances in Meta module
| otherwise = pgmError ("NLambda plugin requires " ++ className ++ " instance for type: " ++ tcName ++ " (from " ++ getModuleStr tc ++ ")")
where Just tc = tyConAppTyCon_maybe t
tcName = getNameStr tc
className = getNameStr cl
name = "$f" ++ className ++ tcName
findSuperClass :: Type -> [CoreExpr] -> Maybe CoreExpr
findSuperClass t (e:es)
| Just (cl, ts) <- getClassPredTys_maybe (exprType e)
= let (_, _, ids, _) = classBigSig cl
es' = fmap (\i -> mkApps (Var i) (fmap Type ts ++ [e])) ids
in find (eqType t . exprType) es' <|> findSuperClass t (es ++ es')
| otherwise = findSuperClass t es
findSuperClass t [] = Nothing
newClassInstances :: ModInfo -> [ClsInst] -> [ClsInst]
newClassInstances mod is = catMaybes $ fmap new is
where new i = let dFunId = instanceDFunId i
nm = is_cls_nm i
in if varMapMember mod dFunId && nameMember mod nm
then Just $ mkImportedInstance
(newName mod nm)
(instanceRoughTcs i)
(newVar mod dFunId)
(is_flag i)
(is_orphan i)
else Nothing
userClassOpId :: ModInfo -> Id -> Maybe Class
userClassOpId mod v
| Just cls <- isClassOpId_maybe v, inCurrentModule mod cls = Just cls
| isPrefixOf classOpPrefix (getNameStr v) = lookup (getNameStr v) userClassMethods
| otherwise = Nothing
where classOpPrefix = "$c"
modClasses = filter (inCurrentModule mod) $ allClasses mod
userClassMethods = concatMap (\c -> fmap (\m -> (classOpPrefix ++ getNameStr m, c)) (classMethods c)) modClasses
sortBinds :: CoreProgram -> CoreProgram
sortBinds = fmap (uncurry NonRec) . sortWith (getNameStr . fst) . flattenBinds
getBindsVars :: ModGuts -> [Var]
getBindsVars = bindersOfBinds . mg_binds
getBindsNames :: ModGuts -> [Name]
getBindsNames = fmap varName . getBindsVars
newBinds :: ModInfo -> [DataCon] -> CoreProgram -> CoreM CoreProgram
newBinds mod dcs bs = do bs' <- mapM (changeBind mod) $ filter isInVarMap bs
bs'' <- mapM (dataBind mod) dcs
return $ bs' ++ bs''
where isInVarMap (NonRec b e) = varMapMember mod b
isInVarMap (Rec bs) = all (varMapMember mod) $ fst <$> bs
changeBind :: ModInfo -> CoreBind -> CoreM CoreBind
changeBind mod (NonRec b e) = do (b',e') <- changeBindExpr mod (b, e)
return (NonRec b' e')
changeBind mod (Rec bs) = do bs' <- mapM (changeBindExpr mod) bs
return (Rec bs')
changeBindExpr :: ModInfo -> (CoreBndr, CoreExpr) -> CoreM (CoreBndr, CoreExpr)
changeBindExpr mod (b, e) = do e' <- changeExpr mod e
let b' = newVar mod b
e'' <- convertMetaType mod e' $ varType b'
return (b', simpleOptExpr e'')
dataBind :: ModInfo -> DataCon -> CoreM CoreBind
dataBind mod dc
| noAtomsType $ dataConOrigResTy dc = return $ NonRec b' (Var b)
| otherwise = do e <- dataConExpr mod dc
e' <- convertMetaType mod e $ varType b'
return $ NonRec b' $ simpleOptExpr e'
where b = dataConWrapId dc
b' = newVar mod b
changeBindTypeAndUniq :: ModInfo -> CoreBndr -> CoreM CoreBndr
changeBindTypeAndUniq mod x = mkVarUnique $ setVarType x $ changeType mod $ varType x
changeBindTypeUnderWithMetaAndUniq :: ModInfo -> CoreBndr -> CoreM CoreBndr
changeBindTypeUnderWithMetaAndUniq mod x = mkVarUnique $ setVarType x $ changeTypeUnderWithMeta mod False $ varType x
changeType :: ModInfo -> Type -> Type
changeType mod t = (changeTypeOrSkip mod True) t
changeTypeOrSkip :: ModInfo -> Bool -> Type -> Type
changeTypeOrSkip mod skipNoAtoms t = change t
where change t | skipNoAtoms, noAtomsType t = t
change t | isVoidTy t = t
change t | isPrimitiveType t = t
change t | isPredTy t = changePredType mod t
change t | (Just (tv, t')) <- splitForAllTy_maybe t = mkForAllTy tv (change t')
change t | (Just (t1, t2)) <- splitFunTy_maybe t = mkFunTy (change t1) (change t2)
change t | (Just (t1, t2)) <- splitAppTy_maybe t
= withMetaType mod $ mkAppTy t1 (changeTypeUnderWithMeta mod skipNoAtoms t2)
change t | (Just (tc, ts)) <- splitTyConApp_maybe t
= withMetaType mod $ mkTyConApp tc (changeTypeUnderWithMeta mod skipNoAtoms <$> ts)
change t = withMetaType mod t
changeTypeUnderWithMeta :: ModInfo -> Bool -> Type -> Type
changeTypeUnderWithMeta mod skipNoAtoms t = change t
where change t | skipNoAtoms, noAtomsType t = t
change t | (Just (tv, t')) <- splitForAllTy_maybe t = mkForAllTy tv (change t')
change t | (Just (t1, t2)) <- splitFunTy_maybe t
= mkFunTy (changeTypeOrSkip mod skipNoAtoms t1) (changeTypeOrSkip mod skipNoAtoms t2)
change t | (Just (t1, t2)) <- splitAppTy_maybe t = mkAppTy (change t1) (change t2)
change t | (Just (tc, ts)) <- splitTyConApp_maybe t = mkTyConApp tc (change <$> ts)
change t = t
changePredType :: ModInfo -> PredType -> PredType
changePredType mod t | (Just (tc, ts)) <- splitTyConApp_maybe t, isClassTyCon tc = mkTyConApp (newTyCon mod tc) ts
changePredType mod t = t
changeTypeAndApply :: ModInfo -> CoreExpr -> Type -> CoreExpr
changeTypeAndApply mod e t
| otherwise = (mkApp e . Type . change) t
where (tyVars, eTy) = splitForAllTys $ exprType e
tyVar = headPanic "changeTypeAndApply" (pprE "e" e) tyVars
change t = if isFunTy t && isMonoType t then changeTypeOrSkip mod (not $ isTyVarNested tyVar eTy) t else t
addVarContextForHigherOrderClass :: ModInfo -> Class -> Type -> Type
addVarContextForHigherOrderClass mod cls t
| all isMonoType $ mkTyVarTys $ classTyVars cls = t
| null tvs = t
| otherwise = mkForAllTys tvs $ mkFunTys (nub $ preds ++ preds') (addVarContextForHigherOrderClass mod cls t')
where (tvs, preds, t') = tcSplitSigmaTy t
preds' = fmap (varPredType mod) $ filter isMonoType $ mkTyVarTys $ filter (isTyVarWrappedByWithMeta mod t) tvs
getMainType :: Type -> Type
getMainType t = if t == t' then t else getMainType t'
where (tvs, ps, t') = tcSplitSigmaTy t
getFunTypeParts :: Type -> [Type]
getFunTypeParts t
| t /= getMainType t = getFunTypeParts $ getMainType t
| not $ isFunTy t = [t]
| otherwise = argTys ++ [resTy]
where (argTys, resTy) = splitFunTys t
isTyVarWrappedByWithMeta :: ModInfo -> Type -> TyVar -> Bool
isTyVarWrappedByWithMeta mod t tv = all wrappedByWithMeta $ getFunTypeParts t
where wrappedByWithMeta t | isWithMetaType mod t = True
wrappedByWithMeta (TyVarTy tv') = tv /= tv'
wrappedByWithMeta (AppTy t1 t2) = wrappedByWithMeta t1 && wrappedByWithMeta t2
wrappedByWithMeta (TyConApp tc ts) = isMetaPreludeTyCon mod tc || all wrappedByWithMeta ts
wrappedByWithMeta (FunTy t1 t2) = wrappedByWithMeta t1 && wrappedByWithMeta t2
wrappedByWithMeta (ForAllTy _ t') = wrappedByWithMeta t'
wrappedByWithMeta (LitTy _) = True
isTyVarNested :: TyVar -> Type -> Bool
isTyVarNested tv t = isNested False t
where isNested nested (TyVarTy tv') = nested && (tv == tv')
isNested nested (AppTy t1 t2) = isNested nested t1 || isNested True t2
isNested nested (TyConApp tc ts) = any (isNested True) ts
isNested nested (FunTy t1 t2) = isNested nested t1 || isNested nested t2
isNested nested (ForAllTy _ t) = isNested nested t
isNested nested (LitTy _) = False
isWithMetaType :: ModInfo -> Type -> Bool
isWithMetaType mod t
| Just (tc, _) <- splitTyConApp_maybe (getMainType t) = tc == withMetaC mod
| otherwise = False
getWithoutWithMetaType :: ModInfo -> Type -> Maybe Type
getWithoutWithMetaType mod t
| isWithMetaType mod t, Just ts <- tyConAppArgs_maybe t = Just $ headPanic "getWithoutWithMetaType" (ppr t) ts
| otherwise = Nothing
getAllPreds :: Type -> ThetaType
getAllPreds t
| null preds = []
| otherwise = preds ++ getAllPreds t'
where (preds, t') = tcSplitPhiTy $ dropForAlls t
isInternalType :: Type -> Bool
isInternalType t = let t' = getMainType t in isVoidTy t' || isPredTy t' || isPrimitiveType t' || isUnLiftedType t'
isMonoType :: Type -> Bool
isMonoType = not . isFunTy . typeKind
noAtomsType :: Type -> Bool
noAtomsType t | hasNestedFunType t = False
noAtomsType t = noAtomsTypeVars [] [] t
where noAtomsTypeVars :: [TyCon] -> [TyVar] -> Type -> Bool
noAtomsTypeVars tcs vs t | Just t' <- coreView t = noAtomsTypeVars tcs vs t'
noAtomsTypeVars tcs vs (TyVarTy v) = elem v vs
noAtomsTypeVars tcs vs (AppTy t1 t2) = noAtomsTypeVars tcs vs t1 && noAtomsTypeVars tcs vs t2
noAtomsTypeVars tcs vs (TyConApp tc ts) = noAtomsTypeCon tcs tc (length ts) && (all (noAtomsTypeVars tcs vs) ts)
noAtomsTypeVars tcs vs (FunTy t1 t2) = noAtomsTypeVars tcs vs t1 && noAtomsTypeVars tcs vs t2
noAtomsTypeVars tcs vs (ForAllTy v _) = elem v vs
noAtomsTypeVars tcs vs (LitTy _ ) = True
noAtomsTypeCon :: [TyCon] -> TyCon -> Int -> Bool
noAtomsTypeCon tcs tc _ | elem tc tcs = True
noAtomsTypeCon _ tc _ | isAtomsTypeName tc = False
noAtomsTypeCon _ tc _ | isPrimTyCon tc = True
noAtomsTypeCon tcs tc n | isDataTyCon tc = all (noAtomsTypeVars (nub $ tc : tcs) $ take n $ tyConTyVars tc)
(concatMap dataConOrigArgTys $ tyConDataCons tc)
noAtomsTypeCon _ _ _ = True
isAtomsTypeName :: TyCon -> Bool
isAtomsTypeName tc = let nm = tyConName tc in getNameStr nm == "Variable" && moduleNameString (moduleName $ nameModule nm) == "Var"
hasNestedFunType :: Type -> Bool
hasNestedFunType (TyVarTy v) = False
hasNestedFunType (AppTy _ t) = isFunTy t || hasNestedFunType t
hasNestedFunType (TyConApp _ ts) = any (\t -> isFunTy t || hasNestedFunType t) ts
hasNestedFunType (FunTy t1 t2) = hasNestedFunType t1 || hasNestedFunType t2
hasNestedFunType (ForAllTy _ t) = hasNestedFunType t
hasNestedFunType (LitTy _ ) = False
data TyThingType = TyThingId | TyThingTyCon | TyThingConLike | TyThingCoAxiom deriving (Show, Eq)
tyThingType :: TyThing -> TyThingType
tyThingType (AnId _) = TyThingId
tyThingType (ATyCon _) = TyThingTyCon
tyThingType (AConLike _) = TyThingConLike
tyThingType (ACoAxiom _) = TyThingCoAxiom
isTyThingId :: TyThing -> Bool
isTyThingId = (== TyThingId) . tyThingType
isTyThingTyCon :: TyThing -> Bool
isTyThingTyCon = (== TyThingTyCon) . tyThingType
getModulesTyThings :: [HomeModInfo] -> TypeEnv
getModulesTyThings = mconcat . fmap md_types . fmap hm_details
getTyThingMaybe :: [HomeModInfo] -> String -> (TyThing -> Bool) -> (TyThing -> a) -> (a -> Name) -> Maybe a
getTyThingMaybe mods nm cond fromThing getName =
fmap fromThing $ listToMaybe $ nameEnvElts $ filterNameEnv (\t -> cond t && hasName nm (getName $ fromThing t)) (getModulesTyThings mods)
where hasName nmStr nm = occNameString (nameOccName nm) == nmStr
getTyThing :: [HomeModInfo] -> String -> (TyThing -> Bool) -> (TyThing -> a) -> (a -> Name) -> a
getTyThing mods nm cond fromThing getName = fromMaybe (pprPanic "getTyThing - name not found in module Meta:" $ text nm)
(getTyThingMaybe mods nm cond fromThing getName)
findThingByConds :: (Name -> Name -> Bool) -> (Module -> Module -> Bool) -> [TyThing] -> TyThingType -> Name -> Maybe TyThing
findThingByConds nameCond moduleCond things ty name = find cond things
where sameType = (== ty) . tyThingType
cond t = sameType t && nameCond name (getName t) && moduleCond (nameModule name) (nameModule $ getName t)
findThing :: [TyThing] -> TyThingType -> Name -> Maybe TyThing
findThing = findThingByConds (==) (==)
findPairThing :: [TyThing] -> TyThingType -> Name -> Maybe TyThing
findPairThing things ty name = findThingByConds pairName equivalentModule things ty name
where pairName name nameWithSuffix = let nameStr = getNameStr name
nameWithSuffixStr = getNameStr nameWithSuffix
in nameWithSuffixStr == nlambdaName nameStr
|| (isInfixOf name_suffix nameWithSuffixStr && replace name_suffix "" nameWithSuffixStr == nameStr)
equivalentModule m1 m2 = m1 == m2 || (elem (getModuleNameStr m1) preludeModules && getModuleNameStr m2 == metaModuleName)
findPair :: [TyThing] -> TyThingType -> Name -> Maybe (TyThing, TyThing)
findPair things ty name = (,) <$> findThing things ty name <*> findPairThing things ty name
type ExprMap = Map Var CoreExpr
mkExprMap :: ModInfo -> ExprMap
mkExprMap = Map.map Var . varsWithPairs
getExpr :: ExprMap -> Var -> CoreExpr
getExpr map v = Map.findWithDefault (pprPanic "no expression for variable: " (ppr v <+> ppr (Map.assocs map))) v map
insertVarExpr :: Var -> Var -> ExprMap -> ExprMap
insertVarExpr v v' = Map.insert v (Var v')
insertExpr :: Var -> CoreExpr -> ExprMap -> ExprMap
insertExpr = Map.insert
changeExpr :: ModInfo -> CoreExpr -> CoreM CoreExpr
changeExpr mod e = newExpr (mkExprMap mod) e
where newExpr :: ExprMap -> CoreExpr -> CoreM CoreExpr
newExpr eMap e | noAtomsSubExpr e = replaceVars mod eMap e
newExpr eMap (Var v) | Map.member v eMap = addMockedInstances mod False $ getExpr eMap v
newExpr eMap (Var v) | isMetaEquivalent mod v = getMetaEquivalent mod v
newExpr eMap (Var v) = pprPgmError "Unknown variable:"
(showVar v <+> text "::" <+> ppr (varType v) <+> text ("\nProbably module " ++ getModuleStr v ++ " is not compiled with NLambda Plugin."))
newExpr eMap (Lit l) = noMetaExpr mod (Lit l)
newExpr eMap (App f (Type t)) = do f' <- newExpr eMap f
return $ changeTypeAndApply mod f' t
newExpr eMap (App f e) = do f' <- newExpr eMap f
f'' <- if isWithMetaType mod $ exprType f' then valueExpr mod f' else return f'
e' <- newExpr eMap e
e'' <- convertMetaType mod e' $ funArgTy $ exprType f''
return $ mkApp f'' e''
newExpr eMap (Lam x e) | isTKVar x = do e' <- newExpr eMap e
FIXME new uniq for x ( and then replace all occurrences ) ?
newExpr eMap (Lam x e) = do x' <- changeBindTypeAndUniq mod x
e' <- newExpr (insertVarExpr x x' eMap) e
return $ Lam x' e'
newExpr eMap (Let b e) = do (b', eMap) <- newLetBind b eMap
e' <- newExpr eMap e
return $ Let b' e'
newExpr eMap (Case e b t as) = do e' <- newExpr eMap e
e'' <- if isWithMetaType mod $ exprType e'
then valueExpr mod e'
else return e'
m <- if isWithMetaType mod $ exprType e'
then metaExpr mod e'
else return $ emptyMetaV mod
b' <- changeBindTypeUnderWithMetaAndUniq mod b
be <- createExpr mod (Var b') m
let t' = changeType mod t
as' <- mapM (newAlternative (insertExpr b be eMap) m t') as
return $ Case e'' b' t' as'
newExpr eMap (Cast e c) = do e' <- newExpr eMap e
let c' = changeCoercion mod c
e'' <- convertMetaType mod e' $ pFst $ coercionKind c'
return $ Cast e'' c'
newExpr eMap (Tick t e) = do e' <- newExpr eMap e
return $ Tick t e'
newExpr eMap (Coercion c) = undefined
newLetBind (NonRec b e) eMap = do b' <- changeBindTypeAndUniq mod b
let eMap' = insertVarExpr b b' eMap
e' <- newExpr eMap' e
return (NonRec b' e', eMap')
newLetBind (Rec bs) eMap = do (bs', eMap') <- newRecBinds bs eMap
return (Rec bs', eMap')
newRecBinds ((b, e):bs) eMap = do (bs', eMap') <- newRecBinds bs eMap
b' <- changeBindTypeAndUniq mod b
let eMap'' = insertVarExpr b b' eMap'
e' <- newExpr eMap'' e
return ((b',e'):bs', eMap'')
newRecBinds [] eMap = return ([], eMap)
newAlternative eMap m t (DataAlt con, xs, e) = do xs' <- mapM (changeBindTypeUnderWithMetaAndUniq mod) xs
es <- mapM (\x -> if (isFunTy $ varType x) then return $ Var x else createExpr mod (Var x) m) xs'
e' <- newExpr (Map.union (Map.fromList $ zip xs es) eMap) e
e'' <- convertMetaType mod e' t
return (DataAlt con, xs', e'')
newAlternative eMap m t (alt, [], e) = do e' <- newExpr eMap e
return (alt, [], e')
noAtomsSubExpr :: CoreExpr -> Bool
noAtomsSubExpr e = (noAtomsType $ exprType e) && noAtomFreeVars
where noAtomFreeVars = isEmptyUniqSet $ filterUniqSet (not . noAtomsType . varType) $ exprFreeIds e
replaceVars :: ModInfo -> ExprMap -> CoreExpr -> CoreM CoreExpr
replaceVars mod eMap e = replace e
where replace (Var x) | isLocalId x, Just e <- Map.lookup x eMap = convertMetaType mod e $ varType x
replace (App f e) = do f' <- replace f
e' <- replace e
return $ mkApp f' e'
replace (Lam x e) = do e' <- replace e
return $ Lam x e'
replace (Let b e) = do b' <- replaceInBind b
e' <- replace e
return $ Let b' e'
replace (Case e x t as) = do e' <- replace e
as' <- mapM replaceInAlt as
return $ Case e' x t as'
replace (Cast e c) = do e' <- replace e
return $ Cast e' c
replace (Tick t e) = do e' <- replace e
return $ Tick t e'
replace e = return e
replaceInBind (NonRec x e) = do e' <- replace e
return $ NonRec x e'
replaceInBind (Rec bs) = do bs' <- mapM replaceInRecBind bs
return $ Rec bs'
replaceInRecBind (b, e) = do e' <- replace e
return (b, e')
replaceInAlt (con, bs, e) = do e' <- replace e
return (con, bs, e')
getAllNotLocalVarsFromExpr :: CoreExpr -> [Var]
getAllNotLocalVarsFromExpr = nub . get
where get (Var x) = [x]
get (Lit l) = []
get (App f e) = get f ++ get e
get (Lam x e) = delete x $ get e
get (Let b e) = filter (`notElem` (bindersOf b)) (get e ++ concatMap getAllNotLocalVarsFromExpr (rhssOfBind b))
get (Case e x t as) = delete x (get e ++ concatMap getFromAlt as)
get (Cast e c) = get e
get (Tick t e) = get e
get (Type t) = []
getFromAlt (con, bs, e) = filter (`notElem` bs) (get e)
dataConExpr :: ModInfo -> DataCon -> CoreM CoreExpr
dataConExpr mod dc
| arity == 0 = noMetaExpr mod dcv
| arity == 1 = idOpExpr mod dcv
| otherwise = do (vars, ty, subst) <- splitTypeToExprVarsWithSubst $ exprType dcv
xs <- mkArgs subst arity
let (vvs, evs) = (exprVarsToVars vars, exprVarsToExprs vars)
ra <- renameAndApplyExpr mod arity
ra' <- applyExpr ra (mkApps dcv evs)
return $ mkCoreLams (vvs ++ xs) $ mkApps ra' (Var <$> xs)
where arity = dataConSourceArity dc
dcv = Var $ dataConWrapId dc
mkArgs subst 0 = return []
mkArgs subst n = do let ty = substTy subst $ withMetaType mod $ dataConOrigArgTys dc !! (arity - n)
x <- mkLocalVar ("x" ++ show (arity - n)) ty
args <- mkArgs subst $ pred n
return $ x : args
changeCoercion :: ModInfo -> Coercion -> Coercion
changeCoercion mod c = change True c
where change topLevel (Refl r t) = Refl r $ changeTy topLevel t
change topLevel (TyConAppCo r tc cs) = TyConAppCo r (newTyCon mod tc) (change False <$> cs)
change topLevel (AppCo c1 c2) = AppCo (change False c1) (change False c2)
change topLevel (ForAllCo tv c) = ForAllCo tv (change topLevel c)
change topLevel (CoVarCo cv) = let (t1,t2) = coVarKind cv in CoVarCo $ mkCoVar (coVarName cv) (mkCoercionType (coVarRole cv) t1 t2)
change topLevel (AxiomInstCo a i cs) = AxiomInstCo (changeBranchedCoAxiom mod a) i (change False <$> cs)
change topLevel (UnivCo n r t1 t2) = UnivCo n r (changeTy topLevel t1) (changeTy topLevel t2)
change topLevel (SymCo c) = SymCo $ change topLevel c
change topLevel (TransCo c1 c2) = TransCo (change topLevel c1) (change topLevel c2)
change topLevel (AxiomRuleCo a ts cs) = AxiomRuleCo a (changeTy topLevel <$> ts) (change topLevel <$> cs)
change topLevel (NthCo i c) = NthCo i $ change topLevel c
change topLevel (LRCo lr c) = LRCo lr $ change topLevel c
change topLevel (InstCo c t) = InstCo (change topLevel c) (changeTy topLevel t)
change topLevel (SubCo c) = SubCo $ change topLevel c
changeTy topLevel = if topLevel then changeType mod else changeTypeUnderWithMeta mod False
changeBranchedCoAxiom :: ModInfo -> CoAxiom Branched -> CoAxiom Branched
changeBranchedCoAxiom mod = changeCoAxiom mod toBranchList Nothing
changeUnbranchedCoAxiom :: ModInfo -> Class -> CoAxiom Unbranched -> CoAxiom Unbranched
changeUnbranchedCoAxiom mod cls = changeCoAxiom mod toUnbranchedList $ Just cls
changeCoAxiom :: ModInfo -> ([CoAxBranch] -> BranchList CoAxBranch a) -> Maybe Class -> CoAxiom a -> CoAxiom a
changeCoAxiom mod toList cls (CoAxiom u n r tc bs imp)
= CoAxiom u n r (newTyCon mod tc) (changeBranchList mod toList cls bs) imp
changeBranchList :: ModInfo -> ([CoAxBranch] -> BranchList CoAxBranch a) -> Maybe Class -> BranchList CoAxBranch a -> BranchList CoAxBranch a
changeBranchList mod toList cls = toList . fmap (changeCoAxBranch mod cls) . fromBranchList
changeCoAxBranch :: ModInfo -> Maybe Class -> CoAxBranch -> CoAxBranch
changeCoAxBranch mod cls (CoAxBranch loc tvs roles lhs rhs incpoms)
= CoAxBranch
loc
tvs
roles
(changeTypeUnderWithMeta mod False <$> lhs)
(newRhs cls)
(changeCoAxBranch mod cls <$> incpoms)
where rhs' = changeTypeUnderWithMeta mod False rhs
newRhs (Just c) = addVarContextForHigherOrderClass mod c rhs'
newRhs _ = rhs'
toUnbranchedList :: [CoAxBranch] -> BranchList CoAxBranch Unbranched
toUnbranchedList [b] = FirstBranch b
toUnbranchedList _ = pprPanic "toUnbranchedList" empty
updateCoercionType :: Type -> Coercion -> Coercion
updateCoercionType = update True
where update left t c | t == (if left then pFst else pSnd) (coercionKind c) = c
update left t (Refl r t') = Refl r t
update left t (SymCo c) = SymCo $ update (not left) t c
TODO update cs after try unify
update left t (AxiomInstCo a i cs) = AxiomInstCo (updateCoAxiomType left t i a) i cs
update left t c = c
updateCoAxiomType :: Bool -> Type -> BranchIndex -> CoAxiom Branched -> CoAxiom Branched
updateCoAxiomType left t i a@(CoAxiom u n r tc bs imp)
| left, Just (tc', ts) <- splitTyConApp_maybe t, tc == tc' = axiom $ updateCoAxBranchesType left ts i bs
| left = pprPanic "updateCoAxiomType" (text "inconsistent type:" <+> ppr t <+> text "with co axiom:" <+> ppr a)
| otherwise = axiom $ updateCoAxBranchesType left [t] i bs
where axiom bs = CoAxiom u n r tc bs imp
updateCoAxBranchesType :: Bool -> [Type] -> BranchIndex -> BranchList CoAxBranch Branched -> BranchList CoAxBranch Branched
updateCoAxBranchesType left ts i bs = toBranchList $ fmap update $ zip (fromBranchList bs) [0..]
where update (b, bi) = if bi == i then updateCoAxBranchType left ts b else b
updateCoAxBranchType :: Bool -> [Type] -> CoAxBranch -> CoAxBranch
updateCoAxBranchType True ts (CoAxBranch loc tvs roles lhs rhs incpoms) = CoAxBranch loc tvs roles ts rhs incpoms
updateCoAxBranchType False [t] (CoAxBranch loc tvs roles lhs rhs incpoms) = CoAxBranch loc tvs roles lhs t incpoms
Core program validation
checkCoreProgram :: CoreProgram -> CoreProgram
checkCoreProgram bs = if all checkBinds bs then bs else pprPanic "checkCoreProgram failed" (ppr bs)
where checkBinds (NonRec b e) = checkBind (b,e)
checkBinds (Rec bs) = all checkBind bs
checkBind (b,e) | varType b /= exprType e
= pprPanic "\n================= INCONSISTENT TYPES IN BIND ==========================="
(vcat [text "bind: " <+> showVar b,
text "bind type:" <+> ppr (varType b),
text "expr:" <+> ppr e,
text "expr type:" <+> ppr (exprType e),
text "\n=======================================================================|"])
checkBind (b,e) = checkExpr b e
checkExpr b (Var v) = True
checkExpr b (Lit l) = True
checkExpr b (App f (Type t)) | not $ isForAllTy $ exprType f
= pprPanic "\n================= NOT FUNCTION IN APPLICATION ========================="
(vcat [text "fun expr: " <+> ppr f,
text "fun type: " <+> ppr (exprType f),
text "arg: " <+> ppr t,
text "for bind: " <+> ppr b <+> text "::" <+> ppr (varType b),
text "\n=======================================================================|"])
checkExpr b (App f (Type t)) = checkExpr b f
checkExpr b (App f x) | not $ isFunTy $ exprType f
= pprPanic "\n================= NOT FUNCTION IN APPLICATION ========================="
(vcat [text "fun expr: " <+> ppr f,
text "fun type: " <+> ppr (exprType f),
text "arg: " <+> ppr x,
text "arg type: " <+> ppr (exprType x),
text "for bind: " <+> ppr b <+> text "::" <+> ppr (varType b),
text "\n=======================================================================|"])
checkExpr b (App f x) | funArgTy (exprType f) /= exprType x
= pprPanic "\n================= INCONSISTENT TYPES IN APPLICATION ===================="
(vcat [text "fun: " <+> ppr f,
text "fun type: " <+> ppr (exprType f),
text "fun arg type: " <+> ppr (funArgTy $ exprType f),
text "arg: " <+> ppr x,
text "arg type: " <+> ppr (exprType x),
text "for bind: " <+> ppr b <+> text "::" <+> ppr (varType b),
text "\n=======================================================================|"])
checkExpr b (App f x) = checkExpr b f && checkExpr b x
checkExpr b (Lam x e) = checkExpr b e
checkExpr b (Let x e) = checkBinds x && checkExpr b e
checkExpr b (Case e x t as) = checkBind (x,e) && all (checkAlternative b t) as && all (checkAltConType b $ exprType e) as
checkExpr b (Cast e c) | exprType e /= pFst (coercionKind c)
= pprPanic "\n================= INCONSISTENT TYPES IN CAST ==========================="
(vcat [text "expr: " <+> ppr e,
text "expr type: " <+> ppr (exprType e),
text "coercion: " <+> ppr c,
text "coercion: " <+> showCoercion c,
text "coercion type: " <+> ppr (coercionType c),
text "for bind: " <+> ppr b <+> text "::" <+> ppr (varType b),
text "\n=======================================================================|"])
checkExpr b (Cast e c) = checkExpr b e
checkExpr b (Tick t e) = checkExpr b e
checkExpr b (Coercion c) = True
checkAlternative b t (ac, xs, e) | t /= exprType e
= pprPanic "\n================= INCONSISTENT TYPES IN CASE ALTERNATIVE ==============="
(vcat [text "type in case: " <+> ppr t,
text "case alternative expression: " <+> ppr e,
text "case alternative expression type: " <+> ppr (exprType e),
text "for bind: " <+> ppr b <+> text "::" <+> ppr (varType b),
text "\n=======================================================================|"])
checkAlternative b t (ac, xs, e) = checkExpr b e
checkAltConType b t (LitAlt l, xs, e) = checkAltConTypes b (ppr l) (literalType l) t xs
checkAltConType b _ _ = True
checkAltConTypes b conDoc pt vt xs | not $ canUnifyTypes pt vt
= pprPanic "\n========== INCONSISTENT TYPES IN CASE ALTERNATIVE PATTERN =============="
(vcat [text "type of value: " <+> ppr vt,
text "case alternative constructor: " <+> conDoc,
text "case alternative arguments: " <+> hcat ((\x -> ppr x <+> text "::" <+> ppr (varType x)) <$> xs),
text "case alternative pattern type: " <+> ppr pt,
text "for bind: " <+> ppr b <+> text "::" <+> ppr (varType b),
text "\n=======================================================================|"])
checkAltConTypes b conDoc pt vt xs = True
data ExprVar = TV TyVar | DI DictId
instance Outputable ExprVar where
ppr (TV v) = ppr v
ppr (DI i) = ppr i
isTV :: ExprVar -> Bool
isTV (TV _) = True
isTV (DI _) = False
substTy :: TvSubst -> Type -> Type
substTy subst t = head $ substTys subst [t]
substFromLists :: [TyVar] -> [TyVar] -> TvSubst
substFromLists tvs = mkTopTvSubst . zip tvs . mkTyVarTys
substDictId :: TvSubst -> DictId -> DictId
substDictId subst id = setVarType id ty
where (cl, ts) = getClassPredTys $ varType id
ts' = substTys subst ts
ty = mkClassPred cl ts'
exprVarsToVarsWithSubst :: TvSubst -> [ExprVar] -> [CoreBndr]
exprVarsToVarsWithSubst subst = catMaybes . fmap toCoreBndr
where toCoreBndr (TV v) | isNothing (lookupTyVar subst v) = Just v
toCoreBndr (TV v) = Nothing
toCoreBndr (DI i) = Just $ substDictId subst i
exprVarsToVars :: [ExprVar] -> [CoreBndr]
exprVarsToVars = exprVarsToVarsWithSubst emptyTvSubst
exprVarsToExprsWithSubst :: TvSubst -> [ExprVar] -> [CoreExpr]
exprVarsToExprsWithSubst subst = fmap toExpr
where toExpr (TV v) = Type $ substTyVar subst v
toExpr (DI i) = Var $ substDictId subst i
exprVarsToExprs :: [ExprVar] -> [CoreExpr]
exprVarsToExprs = exprVarsToExprsWithSubst emptyTvSubst
splitTypeToExprVarsWithSubst :: Type -> CoreM ([ExprVar], Type, TvSubst)
splitTypeToExprVarsWithSubst ty
| ty == ty' = return ([], ty, emptyTvSubst)
| otherwise = do tyVars' <- mapM mkTyVarUnique tyVars
let subst = substFromLists tyVars tyVars'
let preds' = filter isClassPred preds
let classTys = fmap getClassPredTys preds'
predVars <- mapM mkPredVar ((\(c,tys) -> (c, substTys subst tys)) <$> classTys)
(resTyVars, resTy, resSubst) <- splitTypeToExprVarsWithSubst $ substTy subst ty'
return ((TV <$> tyVars') ++ (DI <$> predVars) ++ resTyVars, resTy, unionTvSubst subst resSubst)
where (tyVars, preds, ty') = tcSplitSigmaTy ty
mkTyVarUnique v = do uniq <- getUniqueM
return $ mkTyVar (setNameUnique (tyVarName v) uniq) (tyVarKind v)
splitTypeToExprVars :: Type -> CoreM ([ExprVar], Type)
splitTypeToExprVars t = liftM (\(vars, ty, _) -> (vars, ty)) (splitTypeToExprVarsWithSubst t)
unifyTypes :: Type -> Type -> Maybe TvSubst
unifyTypes t1 t2 = maybe unifyWithOpenKinds Just (tcUnifyTy t1 t2)
where unifyWithOpenKinds = tcUnifyTy (replaceOpenKinds t1) (replaceOpenKinds t2)
replaceOpenKinds (TyVarTy v) | isOpenTypeKind (tyVarKind v) = TyVarTy $ setTyVarKind v (defaultKind $ tyVarKind v)
replaceOpenKinds (TyVarTy v) = TyVarTy v
replaceOpenKinds (AppTy t1 t2) = AppTy (replaceOpenKinds t1) (replaceOpenKinds t2)
replaceOpenKinds (TyConApp tc ts) = TyConApp tc (fmap replaceOpenKinds ts)
replaceOpenKinds (FunTy t1 t2) = FunTy (replaceOpenKinds t1) (replaceOpenKinds t2)
replaceOpenKinds (ForAllTy v t) = ForAllTy v (replaceOpenKinds t)
replaceOpenKinds (LitTy tl) = LitTy tl
canUnifyTypes :: Type -> Type -> Bool
canUnifyTypes t1 t2 = isJust $ unifyTypes (dropForAlls t1) (dropForAlls t2)
applyExpr :: CoreExpr -> CoreExpr -> CoreM CoreExpr
applyExpr fun e =
do (eVars, eTy) <- splitTypeToExprVars $ exprType e
(fVars, fTy) <- if isPredTy eTy
then return $ (\(tvs, t) -> (TV <$> tvs, t)) (splitForAllTys $ exprType fun)
else splitTypeToExprVars $ exprType fun
let subst = fromMaybe
(pprPanic "applyExpr - can't unify:" (ppr (funArgTy fTy) <+> text "and" <+> ppr eTy <+> text "for apply:" <+> ppr fun <+> text "with" <+> ppr e))
(unifyTypes (funArgTy fTy) eTy)
let fVars' = exprVarsToVarsWithSubst subst fVars
let fVarExprs = exprVarsToExprsWithSubst subst fVars
let eVars' = exprVarsToVarsWithSubst subst eVars
let eVarExprs = exprVarsToExprsWithSubst subst eVars
return $ mkCoreLams (sortVars [] $ reverse $ nub $ fVars' ++ eVars')
(mkApp
(mkApps fun fVarExprs)
(mkApps e eVarExprs))
where sortVars res (v:vs)
| not $ isTyVar v, Just i <- findIndex (\x -> isTyVar x && elemVarSet x (tyVarsOfType $ varType v)) res
= let (vs1, vs2) = splitAt i res in sortVars (vs1 ++ [v] ++ vs2) vs
| otherwise = sortVars (v:res) vs
sortVars res [] = res
applyExprs :: CoreExpr -> [CoreExpr] -> CoreM CoreExpr
applyExprs = foldlM applyExpr
mkAppOr :: CoreExpr -> CoreExpr -> CoreExpr -> CoreExpr
mkAppOr f x ifNotMatch
| not (isTypeArg x), funArgTy (exprType f) /= exprType x = ifNotMatch
| otherwise = mkCoreApp f x
mkApp :: CoreExpr -> CoreExpr -> CoreExpr
mkApp f x = mkAppOr f x $ pprPanic "mkApp - inconsistent types:" (pprE "f" f <+> text "," <+> pprE "x" x)
mkAppIfMatch :: CoreExpr -> CoreExpr -> CoreExpr
mkAppIfMatch f x = mkAppOr f x f
mkApps :: CoreExpr -> [CoreExpr] -> CoreExpr
mkApps = foldl mkApp
mkAppsIfMatch :: CoreExpr -> [CoreExpr] -> CoreExpr
mkAppsIfMatch = foldl mkAppIfMatch
Meta
varModuleName :: Meta.ModuleName
varModuleName = "Var"
metaModuleName :: Meta.ModuleName
metaModuleName = "Meta"
type MetaModule = HomeModInfo
getMetaModules :: HscEnv -> [MetaModule]
getMetaModules = filter ((`elem` [varModuleName, metaModuleName]) . moduleNameString . moduleName . mi_module . hm_iface) . eltsUFM . hsc_HPT
getVar :: ModInfo -> String -> Var
getVar mod nm = getTyThing (metaModules mod) nm isTyThingId tyThingId varName
getVarMaybe :: ModInfo -> String -> Maybe Var
getVarMaybe mod nm = getTyThingMaybe (metaModules mod) nm isTyThingId tyThingId varName
metaTyThings :: ModInfo -> [TyThing]
metaTyThings = nameEnvElts . getModulesTyThings . metaModules
getTyCon :: ModInfo -> String -> TyCon
getTyCon mod nm = getTyThing (metaModules mod) nm isTyThingTyCon tyThingTyCon tyConName
getMetaVar :: ModInfo -> String -> CoreExpr
getMetaVar mod = Var . getVar mod
getMetaVarMaybe :: ModInfo -> String -> Maybe CoreExpr
getMetaVarMaybe mod = fmap Var . getVarMaybe mod
noMetaV mod = getMetaVar mod "noMeta"
metaV mod = getMetaVar mod "meta"
valueV mod = getMetaVar mod "value"
createV mod = getMetaVar mod "create"
emptyMetaV mod = getMetaVar mod "emptyMeta"
idOpV mod = getMetaVar mod "idOp"
renameAndApplyV mod n = getMetaVar mod ("renameAndApply" ++ show n)
withMetaC mod = getTyCon mod "WithMeta"
metaLevelC mod = getTyCon mod "MetaLevel"
varC mod = getTyCon mod "Var"
withMetaType :: ModInfo -> Type -> Type
withMetaType mod t = mkTyConApp (withMetaC mod) [t]
varPredType :: ModInfo -> Type -> Type
varPredType mod t = mkTyConApp (varC mod) [t]
noMetaExpr :: ModInfo -> CoreExpr -> CoreM CoreExpr
noMetaExpr mod e | isInternalType $ exprType e = return e
noMetaExpr mod e = applyExpr (noMetaV mod) e
valueExpr :: ModInfo -> CoreExpr -> CoreM CoreExpr
valueExpr mod e | not $ isWithMetaType mod $ exprType e = return e
valueExpr mod e = applyExpr (valueV mod) e
metaExpr :: ModInfo -> CoreExpr -> CoreM CoreExpr
metaExpr mod e = applyExpr (metaV mod) e
createExpr :: ModInfo -> CoreExpr -> CoreExpr -> CoreM CoreExpr
createExpr mod e _ | isInternalType $ exprType e = return e
createExpr mod e1 e2 = applyExprs (createV mod) [e1, e2]
idOpExpr :: ModInfo -> CoreExpr -> CoreM CoreExpr
idOpExpr mod e = applyExpr (idOpV mod) e
renameAndApplyExpr :: ModInfo -> Int -> CoreM CoreExpr
renameAndApplyExpr mod n = addMockedInstances mod False (renameAndApplyV mod n)
convertMetaType :: ModInfo -> CoreExpr -> Type -> CoreM CoreExpr
convertMetaType mod e t
| et == t = return e
| isClassPred t, Just e' <- findSuperClass t [e] = return e'
| Just t' <- getWithoutWithMetaType mod t, t' == et = do e' <- convertMetaType mod e t'
noMetaExpr mod e'
| Just et' <- getWithoutWithMetaType mod et, t == et' = do e' <- valueExpr mod e
convertMetaType mod e' t
| length etvs == length tvs, isFunTy et' && isFunTy t', subst <- substFromLists etvs tvs
= convertMetaFun (funArgTy $ substTy subst $ getMainType et') (splitFunTy $ getMainType t')
| otherwise = pprPanic "convertMetaType" (text "can't convert (" <+> ppr e <+> text "::" <+> ppr (exprType e) <+> text ") to type:" <+> ppr t)
where et = exprType e
(etvs, et') = splitForAllTys et
(tvs, t') = splitForAllTys t
convertMetaFun earg (arg, res) = do (vs, _, subst) <- splitTypeToExprVarsWithSubst t
let (vvs, evs) = (exprVarsToVars vs, exprVarsToExprs vs)
x <- mkLocalVar "x" (substTy subst arg)
ex <- convertMetaType mod (Var x) (substTy subst earg)
let e' = mkApp (mkAppsIfMatch e evs) ex
e'' <- convertMetaType mod e' (substTy subst res)
return $ mkCoreLams (vvs ++ [x]) e''
getMetaPreludeNameMap :: ModInfo -> NameMap
getMetaPreludeNameMap mod = Map.fromList $ catMaybes metaPairs
where fromPrelude e | Imported ss <- gre_prov e = not $ null $ intersect preludeModules (moduleNameString <$> is_mod <$> is_decl <$> ss)
fromPrelude e = False
preludeNames = fmap gre_name $ filter fromPrelude $ concat $ occEnvElts $ mg_rdr_env $ guts mod
preludeNamesWithTypes = fmap (\n -> if isLower $ head $ getNameStr n then (TyThingId, n) else (TyThingTyCon, n)) preludeNames
metaPairs = fmap (\(ty, n) -> (\t -> (n, getName t)) <$> findPairThing (metaTyThings mod) ty n) preludeNamesWithTypes
isMetaPreludeTyCon :: ModInfo -> TyCon -> Bool
isMetaPreludeTyCon mod tc = any (\t -> getName t == getName tc && isTyThingTyCon t) $ metaTyThings mod
getMetaPreludeTyCon :: ModInfo -> TyCon -> Maybe TyCon
getMetaPreludeTyCon mod tc = (getTyCon mod . getNameStr) <$> findPairThing (metaTyThings mod) TyThingTyCon (getName tc)
getDefinedMetaEquivalentVar :: ModInfo -> Var -> Maybe Var
getDefinedMetaEquivalentVar mod v
| not $ isPreludeThing v = Nothing
super class selectors should be shift by one because of additional dependency for meta classes
FIXME count no nlambda dependencies and shift by this number
| isPrefixOf "$p" $ getNameStr v, isJust metaVar = Just $ getVar mod $ nlambdaName ("$p" ++ (show $ succ superClassNr) ++ drop 3 (getNameStr v))
| otherwise = metaVar
where metaVar = getVar mod . getNameStr <$> findPairThing (metaTyThings mod) TyThingId (getName v)
superClassNr = read [getNameStr v !! 2] :: Int
isMetaEquivalent :: ModInfo -> Var -> Bool
isMetaEquivalent mod v = case metaEquivalent (getModuleStr v) (getNameStr v) of
NoEquivalent -> isJust $ getDefinedMetaEquivalentVar mod v
_ -> True
getMetaEquivalent :: ModInfo -> Var -> CoreM CoreExpr
getMetaEquivalent mod v
= case metaEquivalent (getModuleStr v) (getNameStr v) of
OrigFun -> addWithMetaTypes mod $ Var v
MetaFun name -> addMockedInstances mod False $ getMetaVar mod name
MetaConvertFun name -> do convertFun <- addMockedInstances mod False $ getMetaVar mod name
applyExpr convertFun (Var v)
NoEquivalent -> addMockedInstances mod True $ Var $ fromMaybe
(pprPgmError "No meta equivalent for:" (showVar v <+> text "from module:" <+> text (getModuleStr v)))
(getDefinedMetaEquivalentVar mod v)
where addWithMetaTypes mod e = do (vars, _) <- splitTypeToExprVars $ exprType e
let tvs = filter isTV vars
let args = exprVarsToVars tvs
let eArgs = fmap (Type . withMetaType mod . mkTyVarTy) args
return $ mkCoreLams args $ mkApps e eArgs
isPredicateWith :: ModInfo -> (TyCon -> Bool) -> Type -> Bool
isPredicateWith mod cond t
| Just tc <- tyConAppTyCon_maybe t, isClassTyCon tc = cond tc
| otherwise = False
isPredicate :: ModInfo -> Type -> Bool
isPredicate mod = isPredicateWith mod $ const True
isVarPredicate :: ModInfo -> Type -> Bool
isVarPredicate mod = isPredicateWith mod (== varC mod)
isPredicateForMock :: ModInfo -> Bool -> Type -> Bool
isPredicateForMock mod mockPrelude = isPredicateWith mod (\tc -> varC mod == tc || metaLevelC mod == tc || (mockPrelude && isPreludeThing tc))
varPredicatesFromType :: ModInfo -> Type -> [PredType]
varPredicatesFromType mod = filter (isVarPredicate mod) . getAllPreds
mockInstance :: Type -> CoreExpr
mockInstance t = (mkApp (Var uNDEFINED_ID) . Type) t
isMockInstance :: ModInfo -> CoreExpr -> Bool
isMockInstance mod (App (Var x) (Type t)) = uNDEFINED_ID == x && isPredicateForMock mod True t
isMockInstance _ _ = False
addMockedInstances :: ModInfo -> Bool -> CoreExpr -> CoreM CoreExpr
addMockedInstances mod mockPrelude = addMockedInstancesExcept mod mockPrelude []
addMockedInstancesExcept :: ModInfo -> Bool -> [PredType] -> CoreExpr -> CoreM CoreExpr
addMockedInstancesExcept mod mockPrelude exceptTys e
= do (vs, ty, subst) <- splitTypeToExprVarsWithSubst $ exprType e
let exceptTys' = substTy subst <$> exceptTys
let (vvs, evs) = (exprVarsToVars vs, exprVarsToExprs vs)
let vvs' = filter (\v -> isTypeVar v || not (forMock exceptTys' $ varType v)) vvs
let evs' = mockPredOrDict exceptTys' <$> evs
let e' = mkApps e evs'
let argTys = init $ getFunTypeParts $ exprType e'
args <- mkMockedArgs (length argTys) argTys
let (xs, es) = unzip args
return $ simpleOptExpr $ if all isVar es
then mkCoreLams vvs' e'
else mkCoreLams (vvs' ++ xs) $ mkApps e' es
forMock exceptTys t = isPredicateForMock mod mockPrelude t && notElem t exceptTys
mockPredOrDict exceptTys e = if not (isTypeArg e) && forMock exceptTys (exprType e) then mockInstance (exprType e) else e
mkMockedArgs n (t:ts) = do x <- mkLocalVar ("x" ++ show (n - length ts)) (typeWithoutVarPreds t)
(vs, t') <- splitTypeToExprVars t
let (vvs, evs) = (exprVarsToVars vs, exprVarsToExprs vs)
let evs' = filter (\ev -> isTypeArg ev || not (isVarPredicate mod $ exprType ev)) evs
let e = if length evs == length evs' then Var x else mkCoreLams vvs $ mkApps (Var x) evs'
args <- mkMockedArgs n ts
return ((x, e) : args)
mkMockedArgs _ [] = return []
typeWithoutVarPreds t
| Just (tv, t') <- splitForAllTy_maybe t = mkForAllTy tv $ typeWithoutVarPreds t'
| Just (t1,t2) <- splitFunTy_maybe t = if isVarPredicate mod t1
then typeWithoutVarPreds t2
else mkFunTy t1 $ typeWithoutVarPreds t2
| otherwise = t
type DictInstances = [(Type, DictId)]
type ReplaceVars = [(CoreBndr, CoreBndr)]
data ReplaceInfo = ReplaceInfo {varInstances :: DictInstances, replaceBinds :: ReplaceVars, nextReplaceBinds :: ReplaceVars, noMocks :: Bool}
instance Outputable ReplaceInfo where
ppr (ReplaceInfo dis rb nrb nm) = text "ReplaceInfo{" <+> ppr dis <+> text ","
<+> vcat (fmap (\(x,y) -> ppr x <+> ppr (varType x) <+> text "~>" <+> ppr (varType y)) rb) <+> text ","
<+> vcat (fmap (\(x,y) -> ppr x <+> ppr (varType x) <+> text "~>" <+> ppr (varType y)) nrb) <+> text ","
<+> ppr nm <+> text "}"
emptyReplaceInfo :: ReplaceInfo
emptyReplaceInfo = ReplaceInfo [] [] [] True
noMoreReplaceBinds :: ReplaceInfo -> Bool
noMoreReplaceBinds = null . nextReplaceBinds
noVarInstances :: ReplaceInfo -> Bool
noVarInstances = null . varInstances
findVarInstance :: Type -> ReplaceInfo -> Maybe DictId
findVarInstance t = lookup t . varInstances
addVarInstance :: (Type, DictId) -> ReplaceInfo -> ReplaceInfo
addVarInstance (t, v) ri = ri {varInstances = (t, v) : (varInstances ri)}
addBindToReplace :: (CoreBndr, CoreBndr) -> ReplaceInfo -> ReplaceInfo
addBindToReplace (b, b') ri = ri {nextReplaceBinds = (b, b') : (nextReplaceBinds ri)}
findReplaceBind :: ModInfo -> Var -> ReplaceInfo -> Maybe Var
findReplaceBind mod x = fmap snd . find (\(x',_) -> x == x' && varType x == varType x') . replaceBinds
nextReplaceInfo :: ReplaceInfo -> ReplaceInfo
nextReplaceInfo ri = ReplaceInfo [] (nextReplaceBinds ri) [] True
withMocks :: ReplaceInfo -> ReplaceInfo
withMocks ri = ri {noMocks = False}
replaceMocksByInstancesInProgram :: ModInfo -> CoreProgram -> CoreM CoreProgram
replaceMocksByInstancesInProgram mod bs = go bs emptyReplaceInfo
where go bs ri = do (bs', ri') <- replace ri bs
if noMoreReplaceBinds ri' && noMocks ri' then return bs' else go bs' $ nextReplaceInfo ri'
replace ri (b:bs) = do (bs', ri') <- replace ri bs
(b', ri'') <- replaceMocksByInstancesInBind mod (b, [], ri')
if noVarInstances ri''
then return (b':bs', ri'')
else pprPanic "replaceMocksByInstancesInProgram - not empty var instances to insert:" (ppr ri'' <+> ppr b')
replace ri [] = return ([], ri)
replaceMocksByInstancesInBind :: ModInfo -> (CoreBind, DictInstances, ReplaceInfo) -> CoreM (CoreBind, ReplaceInfo)
replaceMocksByInstancesInBind mod (b, dis, ri) = replace b dis ri
where replace (NonRec b e) dis ri = do ((b', e'), ri') <- replaceBind (b, e) dis ri
return (NonRec b' e', ri')
replace (Rec bs) dis ri = do (bs', ri') <- replaceBinds bs dis ri
return (Rec bs', ri')
replaceBinds (b:bs) dis ri = do (bs', ri') <- replaceBinds bs dis ri
(b', ri'') <- replaceBind b dis ri'
return (b':bs', ri'')
replaceBinds [] dis ri = return ([], ri)
replaceBind (b, e) dis ri = do (e', ri') <- replaceMocksByInstancesInExpr mod (e, dis, ri)
if varType b == exprType e'
then return ((b, e'), ri')
else let b' = setVarType b $ exprType e'
in return ((b', e'), addBindToReplace (b, b') ri')
replaceMocksByInstancesInExpr :: ModInfo -> (CoreExpr, DictInstances, ReplaceInfo) -> CoreM (CoreExpr, ReplaceInfo)
replaceMocksByInstancesInExpr mod (e, dis, ri) = do (e', ri') <- replace e dis ri
return (simpleOptExpr e', ri')
where replace e dis ri | isMockInstance mod e = replaceMock (exprType e) dis ri
replace e dis ri | (tvs, e') <- collectTyBinders e, not (null tvs)
= do (e'', ri') <- replace e' dis ri
let (vis1, vis2) = partition (\(t,vi) -> any (`elemVarSet` (tyVarsOfType t)) tvs) (varInstances ri')
return (mkCoreLams (tvs ++ fmap snd vis1) e'', ri' {varInstances = vis2})
replace (Var x) dis ri | Just x' <- findReplaceBind mod x ri
= do x'' <- addMockedInstancesExcept mod False (varPredicatesFromType mod $ varType x) (Var x')
return (x'', withMocks ri)
replace (App f e) dis ri = do (f', ri') <- replace f dis ri
(e', ri'') <- replace e dis ri'
let argTy = funArgTy $ exprType f'
let f'' = if not (isTypeArg e') && isVarPredicate mod argTy && not (isVarPredicate mod $ exprType e')
then mkApp f' (mockInstance argTy)
else f'
return (mkApp f'' e', ri'')
replace (Lam x e) dis ri = do let dis' = if isPredicate mod $ varType x then (varType x, x) : dis else dis
(e', ri') <- replace e dis' ri
return (Lam x e', ri')
replace (Let b e) dis ri = do (b', ri') <- replaceMocksByInstancesInBind mod (b, dis, ri)
(e', ri'') <- replace e dis ri'
return (Let b' e', ri'')
replace (Case e x t as) dis ri = do (e', ri') <- replace e dis ri
(as', ri'') <- replaceAlts as dis ri'
return (Case e' x t as', ri'')
replace (Cast e c) dis ri = do (e', ri') <- replace e dis ri
let c' = updateCoercionType (exprType e') c
return (Cast e' c', ri')
replace (Tick t e) dis ri = do (e', ri') <- replace e dis ri
return (Tick t e', ri')
replace e dis ri = return (e, ri)
replaceAlts (a:as) dis ri = do (as', ri') <- replaceAlts as dis ri
(a', ri'') <- replaceAlt a dis ri'
return (a':as', ri'')
replaceAlts [] dis ri = return ([], ri)
replaceAlt (con, xs, e) dis ri = do (e', ri') <- replace e dis ri
return ((con, xs, e'), ri')
replaceMock t dis ri
| Just v <- lookup t dis = return (Var v, ri)
| isVarPredicate mod t, Just v <- findVarInstance t ri = return (Var v, ri)
| Just di <- dictInstance mod t = do di' <- addMockedInstances mod True di
return (di', withMocks ri)
| isVarPredicate mod t = do v <- mkPredVar $ getClassPredTys t
return (Var v, addVarInstance (t, v) ri)
| Just sc <- findSuperClass t (Var <$> snd <$> dis) = return (sc, ri)
| otherwise = pprPanic "replaceMock - can't create class instance for " (ppr t)
dictInstance :: ModInfo -> Type -> Maybe CoreExpr
dictInstance mod t
| Just (tc, ts) <- splitTyConApp_maybe t' = Just $ mkApps inst (Type <$> ts)
| isJust (isNumLitTy t') || isJust (isStrLitTy t') = Just inst
| isFunTy t' = Just inst
| otherwise = Nothing
where Just (cl, [t']) = getClassPredTys_maybe t
inst = getClassInstance mod cl t'
when c v = if c then text " " <> ppr v else text ""
whenT c v = if c then text " " <> text v else text ""
showBind :: CoreBind -> SDoc
showBind (NonRec b e) = showBindExpr (b, e)
showBind (Rec bs) = hcat $ map showBindExpr bs
showBindExpr :: (CoreBndr, CoreExpr) -> SDoc
showBindExpr (b,e) = text "===> "
<+> showVar b
<+> text "::"
<+> showType (varType b)
<+> (if noAtomsType $ varType b then text "[no atoms]" else text "[atoms]")
<> text "\n"
<+> showExpr e
<> text "\n"
showType :: Type -> SDoc
showType = ppr
showType (TyVarTy v) = text "TyVarTy(" <> showVar v <> text ")"
showType (AppTy t1 t2) = text "AppTy(" <> showType t1 <+> showType t2 <> text ")"
showType (TyConApp tc ts) = text "TyConApp(" <> showTyCon tc <+> hsep (fmap showType ts) <> text ")"
showType (FunTy t1 t2) = text "FunTy(" <> showType t1 <+> showType t2 <> text ")"
showType (ForAllTy v t) = text "ForAllTy(" <> showVar v <+> showType t <> text ")"
showType (LitTy tl) = text "LitTy(" <> ppr tl <> text ")"
showTyCon :: TyCon -> SDoc
showTyCon = ppr
< > ppr ( nameUnique $ tyConName tc )
< > ( whenT ( ) " , Fun " )
< > ( whenT ( isPrimTyCon tc ) " , " )
< > ( whenT ( isUnboxedTupleTyCon tc ) " , UnboxedTuple " )
< > ( whenT ( isBoxedTupleTyCon tc ) " , BoxedTuple " )
< > ( whenT ( ) " , TypeSynonym " )
< > ( whenT ( isDecomposableTyCon tc ) " , Decomposable " )
< > ( whenT ( isPromotedTyCon tc ) " , Promoted " )
< > ( whenT ( isDataTyCon tc ) " , DataTyCon " )
< > ( whenT ( ) " , AbstractTyCon " )
< > ( whenT ( isOpenFamilyTyCon tc ) " , OpenFamilyTyCon " )
< > ( whenT ( isTypeFamilyTyCon tc ) " , " )
< > ( whenT ( isGadtSyntaxTyCon tc ) " , " )
< > ( whenT ( ) " , TyConAssoc " )
< > ( text " , dataConNames : " < + > ( vcat $ fmap showName $ fmap dataConName $ tyConDataCons tc ) )
showName :: Name -> SDoc
showName = ppr
< > ppr ( nameOccName n )
< + > ppr ( nameUnique n )
< + > ppr ( nameSrcSpan n )
showOccName :: OccName -> SDoc
showOccName n = text "<"
<> ppr n
<+> pprNameSpace (occNameSpace n)
<> whenT (isVarOcc n) " VarOcc"
<> whenT (isTvOcc n) " TvOcc"
<> whenT (isTcOcc n) " TcOcc"
<> whenT (isDataOcc n) " DataOcc"
<> whenT (isDataSymOcc n) " DataSymOcc"
<> whenT (isSymOcc n) " SymOcc"
<> whenT (isValOcc n) " ValOcc"
<> text ">"
showVar :: Var -> SDoc
showVar = ppr
v = text " [ "
< + > ppr ( varUnique v )
< > ( when ( isId v ) ( arityInfo $ idInfo v ) )
< > ( when ( isId v ) ( unfoldingInfo $ idInfo v ) )
< > ( when ( isId v ) ( cafInfo $ idInfo v ) )
< > ( when ( isId v ) ( occInfo $ idInfo v ) )
< > ( when ( isId v ) ( strictnessInfo $ idInfo v ) )
< > ( when ( isId v ) ( demandInfo $ idInfo v ) )
< > ( when ( isId v ) ( callArityInfo $ idInfo v ) )
< > ( whenT ( isDictId v ) " DictId " )
< > ( whenT ( isTKVar v ) " TKVar " )
< > ( whenT ( isTyVar v ) " TyVar " )
< > ( whenT ( v ) " TcTyVar " )
< > ( whenT ( isLocalVar v ) " LocalVar " )
< > ( whenT ( isLocalId v ) " LocalId " )
< > ( whenT ( isGlobalId v ) " GlobalId " )
< > ( whenT ( v ) " ExportedId " )
< > ( whenT ( isEvVar v ) " EvVar " )
< > ( whenT ( isId v & & isRecordSelector v ) " RecordSelector " )
< > ( whenT ( isId v & & ( isJust $ isClassOpId_maybe v ) ) " ClassOpId " )
< > ( whenT ( isId v & & isDFunId v ) " DFunId " )
< > ( whenT ( isId v & & isPrimOpId v ) " PrimOpId " )
< > ( whenT ( isId v & & isConLikeId v ) " ConLikeId " )
< > ( whenT ( isId v & & isRecordSelector v ) " RecordSelector " )
< > ( whenT ( isId v & & hasNoBinding v ) " NoBinding " )
showExpr :: CoreExpr -> SDoc
showExpr (Var i) = text "<" <> showVar i <> text ">"
showExpr (Lit l) = text "Lit" <+> pprLiteral id l
showExpr (App e (Type t)) = showExpr e <+> text "@{" <+> showType t <> text "}"
showExpr (App e a) = text "(" <> showExpr e <> text " $ " <> showExpr a <> text ")"
showExpr (Lam b e) = text "(" <> showVar b <> text " -> " <> showExpr e <> text ")"
showExpr (Let b e) = text "Let" <+> showLetBind b <+> text "in" <+> showExpr e
showExpr (Case e b t as) = text "Case" <+> showExpr e <+> showVar b <+> text "::{" <+> showType t <> text "}" <+> hcat (showAlt <$> as)
showExpr (Cast e c) = text "Cast" <+> showExpr e <+> showCoercion c
showExpr (Tick t e) = text "Tick" <+> ppr t <+> showExpr e
showExpr (Type t) = text "Type" <+> showType t
showExpr (Coercion c) = text "Coercion" <+> text "`" <> showCoercion c <> text "`"
showLetBind (NonRec b e) = showVar b <+> text "=" <+> showExpr e
showLetBind (Rec bs) = hcat $ fmap (\(b,e) -> showVar b <+> text "=" <+> showExpr e) bs
showCoercion :: Coercion -> SDoc
showCoercion c = text "`" <> show c <> text "`"
where show (Refl role typ) = text "Refl" <+> ppr role <+> showType typ
show (TyConAppCo role tyCon cs) = text "TyConAppCo"
show (AppCo c1 c2) = text "AppCo"
show (ForAllCo tyVar c) = text "ForAllCo"
show (CoVarCo coVar) = text "CoVarCo"
show (AxiomInstCo coAxiom branchIndex cs) = text "AxiomInstCo" <+> ppr coAxiom <+> ppr branchIndex <+> vcat (fmap showCoercion cs)
show (UnivCo fastString role type1 type2) = text "UnivCo"
show (SymCo c) = text "SymCo" <+> showCoercion c
show (TransCo c1 c2) = text "TransCo"
show (AxiomRuleCo coAxiomRule types cs) = text "AxiomRuleCo"
show (NthCo int c) = text "NthCo"
show (LRCo leftOrRight c) = text "LRCo"
show (InstCo c typ) = text "InstCo"
show (SubCo c) = text "SubCo"
showAlt (con, bs, e) = text "|" <> ppr con <+> hcat (fmap showVar bs) <+> showExpr e <> text "|"
showClass :: Class -> SDoc
showClass = ppr
showClass cls =
let (tyVars, funDeps, scTheta, scSels, ats, opStuff) = classExtraBigSig cls
in text "Class{"
<+> showName (className cls)
<+> ppr (classKey cls)
<+> ppr tyVars
<+> brackets (fsep (punctuate comma (map (\(m,c) -> parens (sep [showVar m <> comma, ppr c])) opStuff)))
<+> ppr (classMinimalDef cls)
<+> ppr funDeps
<+> ppr scTheta
<+> ppr scSels
<+> text "}"
showDataCon :: DataCon -> SDoc
showDataCon dc =
text "DataCon{"
<+> showName (dataConName dc)
<+> ppr (dataConFullSig dc)
<+> ppr (dataConFieldLabels dc)
<+> ppr (dataConTyCon dc)
<+> ppr (dataConTheta dc)
<+> ppr (dataConStupidTheta dc)
<+> ppr (dataConWorkId dc)
<+> ppr (dataConWrapId dc)
<+> text "}"
|
392717fc7f05c48f4b0963d8ed465d7ac8f7fd0b3a355bb07fa4f8b52d641ae3 | zack-bitcoin/amoveo-exchange | message_limit.erl | -module(message_limit).
-behaviour(gen_server).
-export([start_link/0,code_change/3,handle_call/3,handle_cast/2,handle_info/2,init/1,terminate/2,
doit/1]).
-record(freq, {time, many}).
init(ok) -> {ok, dict:new()}.
start_link() -> gen_server:start_link({local, ?MODULE}, ?MODULE, ok, []).
code_change(_OldVsn, State, _Extra) -> {ok, State}.
terminate(_, _) -> io:format("died!"), ok.
handle_info(_, X) -> {noreply, X}.
handle_cast(_, X) -> {noreply, X}.
handle_call(IP, _From, X) ->
Limit0 = config:message_frequency(),
requests per 2 seconds
case dict:find(IP, X) of
error ->
NF = #freq{time = erlang:timestamp(),
many = 0},
X2 = dict:store(IP, NF, X),
{reply, ok, X2};
{ok, Val} ->
TimeNow = erlang:timestamp(),
T = timer:now_diff(TimeNow,
Val#freq.time),
S = T / 1000000,%seconds
every second , divide how many have been used up by 1/2 .
Many = Many0 + 1,
V2 = #freq{time = TimeNow,
many = Many},
X2 = dict:store(IP, V2, X),
R = if
Many > Limit ->
bad;
true -> ok
end,
{reply, R, X2}
end.
doit(IP) ->
gen_server:call(?MODULE, IP).
| null | https://raw.githubusercontent.com/zack-bitcoin/amoveo-exchange/df6b59c139b710faf79e851bdf7e861983511cbe/apps/amoveo_exchange/src/networking/message_limit.erl | erlang | seconds | -module(message_limit).
-behaviour(gen_server).
-export([start_link/0,code_change/3,handle_call/3,handle_cast/2,handle_info/2,init/1,terminate/2,
doit/1]).
-record(freq, {time, many}).
init(ok) -> {ok, dict:new()}.
start_link() -> gen_server:start_link({local, ?MODULE}, ?MODULE, ok, []).
code_change(_OldVsn, State, _Extra) -> {ok, State}.
terminate(_, _) -> io:format("died!"), ok.
handle_info(_, X) -> {noreply, X}.
handle_cast(_, X) -> {noreply, X}.
handle_call(IP, _From, X) ->
Limit0 = config:message_frequency(),
requests per 2 seconds
case dict:find(IP, X) of
error ->
NF = #freq{time = erlang:timestamp(),
many = 0},
X2 = dict:store(IP, NF, X),
{reply, ok, X2};
{ok, Val} ->
TimeNow = erlang:timestamp(),
T = timer:now_diff(TimeNow,
Val#freq.time),
every second , divide how many have been used up by 1/2 .
Many = Many0 + 1,
V2 = #freq{time = TimeNow,
many = Many},
X2 = dict:store(IP, V2, X),
R = if
Many > Limit ->
bad;
true -> ok
end,
{reply, R, X2}
end.
doit(IP) ->
gen_server:call(?MODULE, IP).
|
d764cb53d0379c5f831c1496af67c33a03a2f2294ff23917575d4f37ed0e52cd | chaoxu/fancy-walks | B.hs | {-# OPTIONS_GHC -O2 #-}
import Data.List
import Data.Maybe
import Data.Char
import Data.Array
import Data.Int
import Data.Ratio
import Data.Bits
import Data.Function
import Data.Ord
import Control.Monad.State
import Control.Monad
import Control.Applicative
import Data.ByteString.Char8 (ByteString)
import qualified Data.ByteString.Char8 as BS
import Data.Set (Set)
import qualified Data.Set as Set
import Data.Map (Map)
import qualified Data.Map as Map
import Data.IntMap (IntMap)
import qualified Data.IntMap as IntMap
import Data.Sequence (Seq)
import qualified Data.Sequence as Seq
import qualified Data.Foldable as F
import Data.Graph
import Control.Monad.ST
import Data.Array.ST
import Debug.Trace
parseInput = do
cas <- readInt
replicateM cas $ do
len <- readInteger
n <- readInt
b <- replicateM n readInt
return (len, b)
where
readInt = state $ fromJust . BS.readInt . BS.dropWhile isSpace
readInteger = state $ fromJust . BS.readInteger . BS.dropWhile isSpace
readString = state $ BS.span (not . isSpace) . BS.dropWhile isSpace
readLine = state $ BS.span (not . isEoln) . BS.dropWhile isEoln
isEoln ch = ch == '\r' || ch == '\n'
main = do
input <- evalState parseInput <$> BS.getContents
forM_ (zip [1..] input) $ \(cas, params) -> do
putStrLn $ "Case #" ++ show cas ++ ": " ++ (solve params)
solve (len, b) = solve' len (last b') (init b')
where
b' = sort b
solve' tlen n len
| res == maxBound = "IMPOSSIBLE"
| otherwise = show $ tdiv + fromIntegral res
where
(tdiv, tmod) = tlen `divMod` fromIntegral n
bnds = (0, n-1)
graph = buildGraph bnds [] :: DGraph Int Int
myExpand graph i di = [ (y, di + 1 - x :: Int)
| j <- len
, let (x, y) = if i + j >= n then (1, i + j - n) else (0, i + j)
]
distance = shortestPath graph myExpand bnds 0 0
res = distance ! fromIntegral tmod
data Ord k => PairingHeap k v = Empty | Heap k v [PairingHeap k v]
empty :: Ord k => PairingHeap k v
empty = Empty
isEmpty :: Ord k => PairingHeap k v -> Bool
isEmpty Empty = True
isEmpty _ = False
unit :: Ord k => k -> v -> PairingHeap k v
unit k v = Heap k v []
insert :: Ord k => k -> v -> PairingHeap k v -> PairingHeap k v
insert k v heap = merge (unit k v) heap
merge :: Ord k => PairingHeap k v -> PairingHeap k v -> PairingHeap k v
merge Empty a = a
merge a Empty = a
merge h1@(Heap k1 v1 hs1) h2@(Heap k2 v2 hs2) =
if k1 < k2 then
Heap k1 v1 (h2:hs1)
else
Heap k2 v2 (h1:hs2)
mergeAll :: Ord k => [PairingHeap k v] -> PairingHeap k v
mergeAll [] = Empty
mergeAll [h] = h
mergeAll (x:y:zs) = merge (merge x y) (mergeAll zs)
findMin :: Ord k => PairingHeap k v -> (k, v)
findMin Empty = error "findMin: empty heap"
findMin (Heap k v _) = (k, v)
deleteMin :: Ord k => PairingHeap k v -> PairingHeap k v
deleteMin Empty = Empty
deleteMin (Heap _ _ hs) = mergeAll hs
hToList Empty = []
hToList (Heap k v hs) = (k, v) : hToList (mergeAll hs)
type DGraph k v = Array k [(k,v)]
type Expand gk gv k v = DGraph gk gv -> k -> v -> [(k, v)]
buildGraph :: Ix k => (k, k) -> [(k, (k, v))] -> DGraph k v
buildGraph bnds edges = accumArray (flip (:)) [] bnds edges
shortestPath :: (Ix gk, Ix k, Ord v, Bounded v) => DGraph gk gv -> Expand gk gv k v -> (k,k) -> k -> v -> Array k v
shortestPath graph expand bnds src sdis = runSTArray $ do
dis <- newArray bnds maxBound
writeArray dis src sdis
dijkstra dis (unit sdis src)
return dis
where
dijkstra dis heap | isEmpty heap = return ()
dijkstra dis heap = do
heapExpand <- filterM checkDis $ expand graph labelA disA
dijkstra dis $ mergeAll (heap':map (\(k, v) -> unit v k) heapExpand)
where
(disA, labelA) = findMin heap
heap' = deleteMin heap
checkDis (k, v) = do
v' <- readArray dis k
when (v < v') $ writeArray dis k v
return $ v < v'
defaultExpand :: (Ix k, Num v) => Expand k v k v
defaultExpand graph src sdis = map (\(k,v) -> (k, sdis + v)) (graph ! src)
| null | https://raw.githubusercontent.com/chaoxu/fancy-walks/952fcc345883181144131f839aa61e36f488998d/code.google.com/codejam/Google%20Code%20Jam%202010/Round%203/B.hs | haskell | # OPTIONS_GHC -O2 # |
import Data.List
import Data.Maybe
import Data.Char
import Data.Array
import Data.Int
import Data.Ratio
import Data.Bits
import Data.Function
import Data.Ord
import Control.Monad.State
import Control.Monad
import Control.Applicative
import Data.ByteString.Char8 (ByteString)
import qualified Data.ByteString.Char8 as BS
import Data.Set (Set)
import qualified Data.Set as Set
import Data.Map (Map)
import qualified Data.Map as Map
import Data.IntMap (IntMap)
import qualified Data.IntMap as IntMap
import Data.Sequence (Seq)
import qualified Data.Sequence as Seq
import qualified Data.Foldable as F
import Data.Graph
import Control.Monad.ST
import Data.Array.ST
import Debug.Trace
parseInput = do
cas <- readInt
replicateM cas $ do
len <- readInteger
n <- readInt
b <- replicateM n readInt
return (len, b)
where
readInt = state $ fromJust . BS.readInt . BS.dropWhile isSpace
readInteger = state $ fromJust . BS.readInteger . BS.dropWhile isSpace
readString = state $ BS.span (not . isSpace) . BS.dropWhile isSpace
readLine = state $ BS.span (not . isEoln) . BS.dropWhile isEoln
isEoln ch = ch == '\r' || ch == '\n'
main = do
input <- evalState parseInput <$> BS.getContents
forM_ (zip [1..] input) $ \(cas, params) -> do
putStrLn $ "Case #" ++ show cas ++ ": " ++ (solve params)
solve (len, b) = solve' len (last b') (init b')
where
b' = sort b
solve' tlen n len
| res == maxBound = "IMPOSSIBLE"
| otherwise = show $ tdiv + fromIntegral res
where
(tdiv, tmod) = tlen `divMod` fromIntegral n
bnds = (0, n-1)
graph = buildGraph bnds [] :: DGraph Int Int
myExpand graph i di = [ (y, di + 1 - x :: Int)
| j <- len
, let (x, y) = if i + j >= n then (1, i + j - n) else (0, i + j)
]
distance = shortestPath graph myExpand bnds 0 0
res = distance ! fromIntegral tmod
data Ord k => PairingHeap k v = Empty | Heap k v [PairingHeap k v]
empty :: Ord k => PairingHeap k v
empty = Empty
isEmpty :: Ord k => PairingHeap k v -> Bool
isEmpty Empty = True
isEmpty _ = False
unit :: Ord k => k -> v -> PairingHeap k v
unit k v = Heap k v []
insert :: Ord k => k -> v -> PairingHeap k v -> PairingHeap k v
insert k v heap = merge (unit k v) heap
merge :: Ord k => PairingHeap k v -> PairingHeap k v -> PairingHeap k v
merge Empty a = a
merge a Empty = a
merge h1@(Heap k1 v1 hs1) h2@(Heap k2 v2 hs2) =
if k1 < k2 then
Heap k1 v1 (h2:hs1)
else
Heap k2 v2 (h1:hs2)
mergeAll :: Ord k => [PairingHeap k v] -> PairingHeap k v
mergeAll [] = Empty
mergeAll [h] = h
mergeAll (x:y:zs) = merge (merge x y) (mergeAll zs)
findMin :: Ord k => PairingHeap k v -> (k, v)
findMin Empty = error "findMin: empty heap"
findMin (Heap k v _) = (k, v)
deleteMin :: Ord k => PairingHeap k v -> PairingHeap k v
deleteMin Empty = Empty
deleteMin (Heap _ _ hs) = mergeAll hs
hToList Empty = []
hToList (Heap k v hs) = (k, v) : hToList (mergeAll hs)
type DGraph k v = Array k [(k,v)]
type Expand gk gv k v = DGraph gk gv -> k -> v -> [(k, v)]
buildGraph :: Ix k => (k, k) -> [(k, (k, v))] -> DGraph k v
buildGraph bnds edges = accumArray (flip (:)) [] bnds edges
shortestPath :: (Ix gk, Ix k, Ord v, Bounded v) => DGraph gk gv -> Expand gk gv k v -> (k,k) -> k -> v -> Array k v
shortestPath graph expand bnds src sdis = runSTArray $ do
dis <- newArray bnds maxBound
writeArray dis src sdis
dijkstra dis (unit sdis src)
return dis
where
dijkstra dis heap | isEmpty heap = return ()
dijkstra dis heap = do
heapExpand <- filterM checkDis $ expand graph labelA disA
dijkstra dis $ mergeAll (heap':map (\(k, v) -> unit v k) heapExpand)
where
(disA, labelA) = findMin heap
heap' = deleteMin heap
checkDis (k, v) = do
v' <- readArray dis k
when (v < v') $ writeArray dis k v
return $ v < v'
defaultExpand :: (Ix k, Num v) => Expand k v k v
defaultExpand graph src sdis = map (\(k,v) -> (k, sdis + v)) (graph ! src)
|
bcd1c7dd3d4984270885ec1b98e2e6a9b1960ffe0e352053eabd44c99d0cce0e | ubf/ubf | test_sup.erl | %%% The MIT License
%%%
Copyright ( C ) 2011 - 2016 by < >
Copyright ( C ) 2002 by
%%%
%%% Permission is hereby granted, free of charge, to any person obtaining a copy
%%% of this software and associated documentation files (the "Software"), to deal
in the Software without restriction , including without limitation the rights
%%% to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software , and to permit persons to whom the Software is
%%% furnished to do so, subject to the following conditions:
%%%
%%% The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software .
%%%
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
%%% IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
%%% FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
%%% AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING FROM ,
%%% OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
%%% THE SOFTWARE.
%%%----------------------------------------------------------------------
%%% File : test_sup.erl
Purpose : test UBF top - level supervisor
%%%----------------------------------------------------------------------
-module(test_sup).
-behaviour(supervisor).
%% External exports
-export([start_link/1]).
%% supervisor callbacks
-export([init/1]).
-define(SERVER, ?MODULE).
%%%----------------------------------------------------------------------
%%% API
%%%----------------------------------------------------------------------
start_link(_Args) ->
supervisor:start_link({local, ?SERVER}, ?MODULE, []).
%%%----------------------------------------------------------------------
%%% Callback functions from supervisor
%%%----------------------------------------------------------------------
%%----------------------------------------------------------------------
%% Func: init/1
Returns : { ok , { SupFlags , [ ChildSpec ] } } |
%% ignore |
%% {error, Reason}
%%----------------------------------------------------------------------
@spec(Args::term ( ) ) - > { ok , ( ) , child_spec_list ( ) } }
@doc The main TEST UBF supervisor .
init(Args) ->
%% seq_trace:set_token(send, true), seq_trace:set_token('receive', true),
%% Child_spec = [Name, {M, F, A},
%% Restart, Shutdown_time, Type, Modules_used]
DefaultMaxConn = 10000,
DefaultTimeout = 60000,
DefaultPlugins = proplists:get_value(plugins, Args, [file_plugin, irc_plugin, irc_plugin, test_plugin]),
CUBF = case proplists:get_value(test_ubf_tcp_port, Args, 0) of
undefined ->
[];
UBFPort ->
UBFMaxConn = proplists:get_value(test_ubf_maxconn, Args, DefaultMaxConn),
UBFIdleTimer = proplists:get_value(test_ubf_timeout, Args, DefaultTimeout),
UBFOptions = [{serverhello, "test_meta_server"}
, {statelessrpc,false}
, {proto,ubf}
, {maxconn,UBFMaxConn}
, {idletimer,UBFIdleTimer}
, {registeredname,test_ubf_tcp_port}
],
UBFServer =
{ubf_server, {ubf_server, start_link, [undefined, DefaultPlugins, UBFPort, UBFOptions]},
permanent, 2000, worker, [ubf_server]},
[UBFServer]
end,
CEBF = case proplists:get_value(test_ebf_tcp_port, Args, 0) of
undefined ->
[];
EBFPort ->
EBFMaxConn = proplists:get_value(test_ebf_maxconn, Args, DefaultMaxConn),
EBFIdleTimer = proplists:get_value(test_ebf_timeout, Args, DefaultTimeout),
EBFOptions = [{serverhello, "test_meta_server"}
, {statelessrpc,false}
, {proto,ebf}
, {maxconn,EBFMaxConn}
, {idletimer,EBFIdleTimer}
, {registeredname,test_ebf_tcp_port}
],
EBFServer =
{ebf_server, {ubf_server, start_link, [undefined, DefaultPlugins, EBFPort, EBFOptions]},
permanent, 2000, worker, [ebf_server]},
[EBFServer]
end,
{ok, {{one_for_one, 2, 60}, CUBF ++ CEBF}}.
%%%----------------------------------------------------------------------
Internal functions
%%%----------------------------------------------------------------------
| null | https://raw.githubusercontent.com/ubf/ubf/c876f684fbd4959548ace1eb1cfc91941f93d377/test/unit/test_sup.erl | erlang | The MIT License
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
----------------------------------------------------------------------
File : test_sup.erl
----------------------------------------------------------------------
External exports
supervisor callbacks
----------------------------------------------------------------------
API
----------------------------------------------------------------------
----------------------------------------------------------------------
Callback functions from supervisor
----------------------------------------------------------------------
----------------------------------------------------------------------
Func: init/1
ignore |
{error, Reason}
----------------------------------------------------------------------
seq_trace:set_token(send, true), seq_trace:set_token('receive', true),
Child_spec = [Name, {M, F, A},
Restart, Shutdown_time, Type, Modules_used]
----------------------------------------------------------------------
---------------------------------------------------------------------- | Copyright ( C ) 2011 - 2016 by < >
Copyright ( C ) 2002 by
in the Software without restriction , including without limitation the rights
copies of the Software , and to permit persons to whom the Software is
all copies or substantial portions of the Software .
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING FROM ,
Purpose : test UBF top - level supervisor
-module(test_sup).
-behaviour(supervisor).
-export([start_link/1]).
-export([init/1]).
-define(SERVER, ?MODULE).
start_link(_Args) ->
supervisor:start_link({local, ?SERVER}, ?MODULE, []).
Returns : { ok , { SupFlags , [ ChildSpec ] } } |
@spec(Args::term ( ) ) - > { ok , ( ) , child_spec_list ( ) } }
@doc The main TEST UBF supervisor .
init(Args) ->
DefaultMaxConn = 10000,
DefaultTimeout = 60000,
DefaultPlugins = proplists:get_value(plugins, Args, [file_plugin, irc_plugin, irc_plugin, test_plugin]),
CUBF = case proplists:get_value(test_ubf_tcp_port, Args, 0) of
undefined ->
[];
UBFPort ->
UBFMaxConn = proplists:get_value(test_ubf_maxconn, Args, DefaultMaxConn),
UBFIdleTimer = proplists:get_value(test_ubf_timeout, Args, DefaultTimeout),
UBFOptions = [{serverhello, "test_meta_server"}
, {statelessrpc,false}
, {proto,ubf}
, {maxconn,UBFMaxConn}
, {idletimer,UBFIdleTimer}
, {registeredname,test_ubf_tcp_port}
],
UBFServer =
{ubf_server, {ubf_server, start_link, [undefined, DefaultPlugins, UBFPort, UBFOptions]},
permanent, 2000, worker, [ubf_server]},
[UBFServer]
end,
CEBF = case proplists:get_value(test_ebf_tcp_port, Args, 0) of
undefined ->
[];
EBFPort ->
EBFMaxConn = proplists:get_value(test_ebf_maxconn, Args, DefaultMaxConn),
EBFIdleTimer = proplists:get_value(test_ebf_timeout, Args, DefaultTimeout),
EBFOptions = [{serverhello, "test_meta_server"}
, {statelessrpc,false}
, {proto,ebf}
, {maxconn,EBFMaxConn}
, {idletimer,EBFIdleTimer}
, {registeredname,test_ebf_tcp_port}
],
EBFServer =
{ebf_server, {ubf_server, start_link, [undefined, DefaultPlugins, EBFPort, EBFOptions]},
permanent, 2000, worker, [ebf_server]},
[EBFServer]
end,
{ok, {{one_for_one, 2, 60}, CUBF ++ CEBF}}.
Internal functions
|
682a91315a9b5ee3f95ad7e85878db317fdf894e228704b9dc4cca092b28ef13 | aconchillo/guile-redis | redis.scm | ( redis ) --- Redis module for .
Copyright ( C ) 2013 - 2020 Aleix Conchillo Flaque < >
;;
;; This file is part of guile-redis.
;;
;; guile-redis is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation ; either version 3 of the License , or
;; (at your option) any later version.
;;
;; guile-redis is distributed in the hope that it will be useful, but
;; WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
;; General Public License for more details.
;;
You should have received a copy of the GNU General Public License
;; along with guile-redis. If not, see /.
;;; Commentary:
Redis module for
;;; Code:
(define-module (redis)
#:use-module (redis main)
#:use-module (redis commands)
#:use-module (redis pubsub))
(define-syntax re-export-modules
(syntax-rules ()
((_ (mod ...) ...)
(begin
(module-use! (module-public-interface (current-module))
(resolve-interface '(mod ...)))
...))))
(re-export-modules (redis main)
(redis commands)
(redis pubsub))
;;; (redis) ends here
| null | https://raw.githubusercontent.com/aconchillo/guile-redis/379a939eb49c209e2df33cbe85c764b971b8fa99/redis.scm | scheme |
This file is part of guile-redis.
guile-redis is free software: you can redistribute it and/or modify
either version 3 of the License , or
(at your option) any later version.
guile-redis is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
along with guile-redis. If not, see /.
Commentary:
Code:
(redis) ends here | ( redis ) --- Redis module for .
Copyright ( C ) 2013 - 2020 Aleix Conchillo Flaque < >
it under the terms of the GNU General Public License as published by
You should have received a copy of the GNU General Public License
Redis module for
(define-module (redis)
#:use-module (redis main)
#:use-module (redis commands)
#:use-module (redis pubsub))
(define-syntax re-export-modules
(syntax-rules ()
((_ (mod ...) ...)
(begin
(module-use! (module-public-interface (current-module))
(resolve-interface '(mod ...)))
...))))
(re-export-modules (redis main)
(redis commands)
(redis pubsub))
|
72171a8ac9ea9ecbe8b53472f8246380283ec251692b9cd5713ec5b00f185460 | McCLIM/McCLIM | core-tests.lisp | ;;; ---------------------------------------------------------------------------
;;; License: LGPL-2.1+ (See file 'Copyright' for details).
;;; ---------------------------------------------------------------------------
;;;
( c ) copyright 2005 < >
( c ) copyright 2006 - 2008 < >
;;;
;;; ---------------------------------------------------------------------------
;;;
Tests for the core functionality .
(cl:in-package #:drei-tests)
(def-suite core-tests :description "The test suite for
DREI-CORE related tests." :in drei-tests)
(in-suite core-tests)
(test possibly-fill-line
(with-drei-environment ()
(possibly-fill-line)
(is (string= (buffer-contents) "")))
(with-drei-environment
(:initial-contents "Very long line, this should be filled, if auto-fill is on.")
(setf (auto-fill-column (current-view)) 200
(auto-fill-mode (current-view)) nil
(offset (point)) (size (current-buffer)))
(possibly-fill-line)
(is (string= (buffer-contents)
"Very long line, this should be filled, if auto-fill is on."))
(setf (auto-fill-mode (current-view)) t)
(possibly-fill-line)
(is (string= (buffer-contents)
"Very long line, this should be filled, if auto-fill is on."))
(setf (auto-fill-column (current-view)) 20)
(possibly-fill-line)
(is (string= (buffer-contents)
"Very long line,
this should be
filled, if auto-fill
is on."))))
(test back-to-indentation
(with-drei-environment
(:initial-contents #.(format nil " ~A Foobar!" #\Tab))
(end-of-buffer (point))
(back-to-indentation (point) (current-syntax))
(is (= (offset (point)) 4))))
(test insert-character
;; Test:
;; - Overwriting
;; - Auto-filling
;; - Standard insertion
(with-drei-environment ()
(setf (auto-fill-mode (current-view)) nil
(overwrite-mode (current-view)) nil)
(insert-character #\a)
(is (string= (buffer-contents) "a"))
(insert-character #\b)
(is (string= (buffer-contents) "ab"))
(backward-object (point) 2)
(insert-character #\t)
(is (string= (buffer-contents) "tab"))
(setf (overwrite-mode (current-view)) t)
(insert-character #\i)
(insert-character #\p)
(is (string= (buffer-contents) "tip"))
;; TODO: Also test dynamic abbreviations?
))
(test delete-horizontal-space
(with-drei-environment (:initial-contents " foo")
(setf (offset (point)) 3)
(delete-horizontal-space (point) (current-syntax))
(is (string= (buffer-contents) "foo"))
(insert-sequence (point) " ")
(setf (offset (point)) 3)
(delete-horizontal-space (point) (current-syntax) t)
(is (string= (buffer-contents) " foo"))
(delete-horizontal-space (point) (current-syntax))
(is (string= (buffer-contents) "foo"))
(delete-horizontal-space (point) (current-syntax))
(is (string= (buffer-contents) "foo"))))
(test indent-current-line
(with-drei-environment (:initial-contents "Foo bar baz
Quux")
(indent-current-line (current-view) (point))
(is (string= (buffer-contents)
"Foo bar baz
Quux"))
(setf (offset (point)) 12)
(indent-current-line (current-view) (point))
(is (string= (buffer-contents)
"Foo bar baz
Quux"))))
(test insert-pair
(with-drei-environment ()
(insert-pair (mark) (current-syntax))
(buffer-is "()")
(beginning-of-buffer (point))
(insert-pair (point) (current-syntax) 0 #\[ #\])
(buffer-is "[] ()")))
(test goto-position
(with-drei-environment (:initial-contents "foobarbaz")
(goto-position (point) 5)
(is (= (offset (point)) 5))))
(test goto-line
(with-drei-environment (:initial-contents "First line
Second line
Third line")
(goto-line (point) 1)
(is (= (line-number (point)) 0))
(is (= (offset (point)) 0))
(goto-line (point) 2)
(is (= (line-number (point)) 1))
(is (= (offset (point)) 11))
(goto-line (point) 3)
(is (= (line-number (point)) 2))
(is (= (offset (point)) 23))
(goto-line (point) 4)
(is (= (line-number (point)) 2))
(is (= (offset (point)) 23))))
(test replace-one-string
(with-drei-environment (:initial-contents "Drei Climacs Drei")
(replace-one-string (point) 17 "foo bar" nil)
(buffer-is "foo bar"))
(with-drei-environment (:initial-contents "drei climacs drei")
(replace-one-string (point) 17 "foo bar" t)
(buffer-is "foo bar"))
(with-drei-environment (:initial-contents "Drei Climacs Drei")
(replace-one-string (point) 17 "foo bar" t)
(buffer-is "Foo Bar"))
(with-drei-environment (:initial-contents "DREI CLIMACS DREI")
(replace-one-string (point) 17 "foo bar" t)
(buffer-is "FOO BAR")))
(test downcase-word
(with-drei-environment ()
(downcase-word (point) (current-syntax) 1)
(is (string= (buffer-contents) "")))
(with-drei-environment (:initial-contents "Drei Climacs Drei")
(downcase-word (point) (current-syntax) 1)
(buffer-is "drei Climacs Drei")
(downcase-word (point) (current-syntax) 1)
(buffer-is "drei climacs Drei")
(downcase-word (point) (current-syntax) 1)
(buffer-is "drei climacs drei"))
(with-drei-environment (:initial-contents "Drei Climacs Drei")
(downcase-word (point) (current-syntax) 0)
(buffer-is "Drei Climacs Drei"))
(with-drei-environment (:initial-contents "Drei Climacs Drei")
(downcase-word (point) (current-syntax) 2)
(buffer-is "drei climacs Drei"))
(with-drei-environment (:initial-contents "Drei Climacs Drei")
(downcase-word (point) (current-syntax) 3)
(buffer-is "drei climacs drei"))
(with-drei-environment (:initial-contents "CLI MA CS CLIMACS")
(downcase-word (point) (current-syntax) 3)
(is (buffer-is "cli ma cs CLIMACS"))
(is (= 9 (offset (point))))))
(test upcase-word
(with-drei-environment ()
(upcase-word (point) (current-syntax) 1)
(is (string= (buffer-contents) "")))
(with-drei-environment (:initial-contents "Drei Climacs Drei")
(upcase-word (point) (current-syntax) 1)
(buffer-is "DREI Climacs Drei")
(upcase-word (point) (current-syntax) 1)
(buffer-is "DREI CLIMACS Drei")
(upcase-word (point) (current-syntax) 1)
(buffer-is "DREI CLIMACS DREI"))
(with-drei-environment (:initial-contents "Drei Climacs Drei")
(upcase-word (point) (current-syntax) 0)
(buffer-is "Drei Climacs Drei"))
(with-drei-environment (:initial-contents "Drei Climacs Drei")
(upcase-word (point) (current-syntax) 2)
(buffer-is "DREI CLIMACS Drei"))
(with-drei-environment (:initial-contents "Drei Climacs Drei")
(upcase-word (point) (current-syntax) 3)
(buffer-is "DREI CLIMACS DREI"))
(with-drei-environment (:initial-contents "cli ma cs climacs")
(let ((m (clone-mark (point) :right)))
(setf (offset m) 0)
(upcase-word m (current-syntax) 3)
(is (string= (buffer-contents)
"CLI MA CS climacs"))
(is (= (offset m) 9)))))
(test capitalize-word
(with-drei-environment ()
(capitalize-word (point) (current-syntax) 1)
(is (string= (buffer-contents) "")))
(with-drei-environment (:initial-contents "drei climacs drei")
(capitalize-word (point) (current-syntax) 1)
(buffer-is "Drei climacs drei")
(capitalize-word (point) (current-syntax) 1)
(buffer-is "Drei Climacs drei")
(capitalize-word (point) (current-syntax) 1)
(buffer-is "Drei Climacs Drei"))
(with-drei-environment (:initial-contents "drei climacs drei")
(capitalize-word (point) (current-syntax) 0)
(buffer-is "drei climacs drei"))
(with-drei-environment (:initial-contents "drei climacs drei")
(capitalize-word (point) (current-syntax) 2)
(buffer-is "Drei Climacs drei"))
(with-drei-environment (:initial-contents "drei climacs drei")
(capitalize-word (point) (current-syntax) 3)
(buffer-is "Drei Climacs Drei"))
(with-drei-environment ( :initial-contents "cli ma cs climacs")
(let ((m (clone-mark (point) :right)))
(setf (offset m) 0)
(capitalize-word m (current-syntax) 3)
(is (string= (buffer-contents)
"Cli Ma Cs climacs"))
(is (= (offset m) 9)))))
(test indent-region
;; FIXME: Sadly, we can't test this function, because it requires a
CLIM pane .
)
(test fill-line
(flet ((fill-it (fill-column)
(fill-line (point)
(lambda (mark)
(proper-line-indentation (current-view) mark))
fill-column
(tab-space-count (current-view))
(current-syntax))))
(with-drei-environment (:initial-contents "climacs climacs climacs climacs")
(let ((m (clone-mark (point) :right)))
(setf (offset m) 25)
(fill-line m #'(lambda (m) (declare (ignore m)) 8) 10 8 (current-syntax))
(is (= (offset m) 25))
(buffer-is "climacs
climacs
climacs climacs")))
(with-drei-environment (:initial-contents "climacs climacs climacs climacs")
(let ((m (clone-mark (point) :right)))
(setf (offset m) 25)
(fill-line m #'(lambda (m) (declare (ignore m)) 8) 10 8 (current-syntax) nil)
(is (= (offset m) 27))
(buffer-is "climacs
climacs
climacs climacs")))
(with-drei-environment (:initial-contents #.(format nil "climacs~Aclimacs~Aclimacs~Aclimacs"
#\Tab #\Tab #\Tab))
(let ((m (clone-mark (point) :left)))
(setf (offset m) 25)
(fill-line m #'(lambda (m) (declare (ignore m)) 8) 10 8 (current-syntax))
(is (= (offset m) 27))
(buffer-is "climacs
climacs
climacs climacs")))
(with-drei-environment (:initial-contents #.(format nil "climacs~Aclimacs~Aclimacs~Aclimacs"
#\Tab #\Tab #\Tab))
(let ((m (clone-mark (point) :left)))
(setf (offset m) 25)
(fill-line m #'(lambda (m) (declare (ignore m)) 8) 10 8 (current-syntax))
(is (= (offset m) 27))
(buffer-is "climacs
climacs
climacs climacs")))
(with-drei-environment (:initial-contents "c l i m a c s")
(let ((m (clone-mark (point) :right)))
(setf (offset m) 1)
(fill-line m #'(lambda (m) (declare (ignore m)) 8) 0 8 (current-syntax))
(is (= (offset m) 1))
(buffer-is "c l i m a c s")))
(with-drei-environment (:initial-contents "c l i m a c s")
(let ((m (clone-mark (point) :right)))
(setf (offset m) 1)
(fill-line m #'(lambda (m) (declare (ignore m)) 8) 0 8 (current-syntax) nil)
(is (= (offset m) 1))
(buffer-is "c l i m a c s")))
(with-drei-environment ()
(fill-it 80)
(buffer-is ""))
(with-drei-environment
(:initial-contents "Very long line, this should certainly be filled, if everything works")
(end-of-buffer (point))
(fill-it 200)
(buffer-is "Very long line, this should certainly be filled, if everything works")
(fill-it 20)
(buffer-is "Very long line,
this should
certainly be filled,
if everything works"))))
(test fill-region
(flet ((fill-it (fill-column)
(fill-region (point) (mark)
(lambda (mark)
(proper-line-indentation (current-view) mark))
fill-column
(tab-space-count (current-view))
(current-syntax))))
(with-drei-environment
(:initial-contents "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
What, you thought I would write something this long myself? Not a chance. Though this line is growing by a fair bit too, I better test it as well.")
(end-of-line (mark))
(fill-it 80)
(buffer-is "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor
incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis
nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu
fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in
culpa qui officia deserunt mollit anim id est laborum.
What, you thought I would write something this long myself? Not a chance. Though this line is growing by a fair bit too, I better test it as well.")
(end-of-buffer (mark))
(forward-paragraph (point) (current-syntax) 2 nil)
(backward-paragraph (point) (current-syntax) 1)
(fill-it 80)
(buffer-is "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor
incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis
nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu
fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in
culpa qui officia deserunt mollit anim id est laborum.
What, you thought I would write something this long myself? Not a chance.
Though this line is growing by a fair bit too, I better test it as well."))))
(test indent-line
(dolist (stick-to '(:left :right))
(with-drei-environment ()
(buffer-is ""))
(with-drei-environment (:initial-contents "I am to be indented")
(indent-line (clone-mark (point) stick-to) 11 nil)
(buffer-is " I am to be indented"))
(with-drei-environment (:initial-contents "I am to be indented")
(indent-line (clone-mark (point) stick-to) 11 2)
(buffer-is #. (format nil "~A~A~A~A~A I am to be indented"
#\Tab #\Tab #\Tab #\Tab #\Tab)))))
(test delete-indentation
(with-drei-environment (:initial-contents "")
(delete-indentation (current-syntax) (point))
(buffer-is ""))
(with-drei-environment (:initial-contents "Foo")
(delete-indentation (current-syntax) (point))
(buffer-is "Foo"))
(with-drei-environment (:initial-contents " Foo")
(delete-indentation (current-syntax) (point))
(buffer-is "Foo"))
(with-drei-environment (:initial-contents " Foo ")
(delete-indentation (current-syntax) (point))
(buffer-is "Foo "))
(with-drei-environment (:initial-contents " Foo
Bar
Baz")
(forward-line (point) (current-syntax))
(delete-indentation (current-syntax) (point))
(buffer-is " Foo
Bar
Baz"))
(with-drei-environment (:initial-contents "
foo bar")
(let ((start (clone-mark (point (current-view))))
(end (clone-mark (point (current-view))))
(orig-contents (buffer-contents)))
(beginning-of-buffer start)
(end-of-buffer end)
(do-buffer-region-lines (line start end)
(delete-indentation (current-syntax) line))
(buffer-is orig-contents))))
(test join-line
(with-drei-environment (:initial-contents "
climacs ")
(let ((m (clone-mark (point) :left)))
(setf (offset m) 3)
(join-line (current-syntax) m)
(is (= (offset m) 0))
(buffer-is "climacs ")))
(with-drei-environment (:initial-contents "
climacs ")
(let ((m (clone-mark (point) :right)))
(setf (offset m) 7)
(join-line (current-syntax) m)
(is (= (offset m) 0))
(buffer-is "climacs ")))
(with-drei-environment (:initial-contents " climacs ")
(let ((m (clone-mark (point) :left)))
(setf (offset m) 7)
(join-line (current-syntax) m)
(is (= (offset m) 0))
(buffer-is " climacs ")))
(with-drei-environment (:initial-contents "climacs
climacs ")
(let ((m (clone-mark (point) :right)))
(setf (offset m) 12)
(join-line (current-syntax) m)
(is (= (offset m) 8))
(buffer-is "climacs climacs ")))
(with-drei-environment (:initial-contents "
climacs ")
(let ((m (clone-mark (point) :right)))
(setf (offset m) 12)
(join-line (current-syntax) m)
(is (= (offset m) 0))
(buffer-is "climacs "))))
(test set-syntax
(dolist (syntax-designator `("Lisp" drei-lisp-syntax::lisp-syntax
,(find-class 'drei-lisp-syntax::lisp-syntax)))
(with-drei-environment ()
(let ((old-syntax (current-syntax)))
(set-syntax (current-view) syntax-designator)
(is (not (eq old-syntax (current-syntax))))
(is (typep (current-syntax) 'drei-lisp-syntax::lisp-syntax))))))
(test with-narrowed-buffer
(with-drei-environment (:initial-contents "foo bar baz quux")
(setf (offset (point)) 1
(offset (mark)) (1- (size (current-buffer))))
(let ((mark1 (clone-mark (point) :left))
(mark2 (clone-mark (mark) :right)))
(forward-object mark1)
(backward-object mark2)
(dolist (low (list 2 mark1))
(dolist (high (list (- (size (current-buffer)) 2) mark2))
(with-narrowed-buffer ((drei-instance) low high t)
(is (= (offset (point)) 2))
(is (= (offset (mark)) (- (size (current-buffer)) 2)))))))))
| null | https://raw.githubusercontent.com/McCLIM/McCLIM/7c890f1ac79f0c6f36866c47af89398e2f05b343/Libraries/Drei/Tests/core-tests.lisp | lisp | ---------------------------------------------------------------------------
License: LGPL-2.1+ (See file 'Copyright' for details).
---------------------------------------------------------------------------
---------------------------------------------------------------------------
Test:
- Overwriting
- Auto-filling
- Standard insertion
TODO: Also test dynamic abbreviations?
FIXME: Sadly, we can't test this function, because it requires a | ( c ) copyright 2005 < >
( c ) copyright 2006 - 2008 < >
Tests for the core functionality .
(cl:in-package #:drei-tests)
(def-suite core-tests :description "The test suite for
DREI-CORE related tests." :in drei-tests)
(in-suite core-tests)
(test possibly-fill-line
(with-drei-environment ()
(possibly-fill-line)
(is (string= (buffer-contents) "")))
(with-drei-environment
(:initial-contents "Very long line, this should be filled, if auto-fill is on.")
(setf (auto-fill-column (current-view)) 200
(auto-fill-mode (current-view)) nil
(offset (point)) (size (current-buffer)))
(possibly-fill-line)
(is (string= (buffer-contents)
"Very long line, this should be filled, if auto-fill is on."))
(setf (auto-fill-mode (current-view)) t)
(possibly-fill-line)
(is (string= (buffer-contents)
"Very long line, this should be filled, if auto-fill is on."))
(setf (auto-fill-column (current-view)) 20)
(possibly-fill-line)
(is (string= (buffer-contents)
"Very long line,
this should be
filled, if auto-fill
is on."))))
(test back-to-indentation
(with-drei-environment
(:initial-contents #.(format nil " ~A Foobar!" #\Tab))
(end-of-buffer (point))
(back-to-indentation (point) (current-syntax))
(is (= (offset (point)) 4))))
(test insert-character
(with-drei-environment ()
(setf (auto-fill-mode (current-view)) nil
(overwrite-mode (current-view)) nil)
(insert-character #\a)
(is (string= (buffer-contents) "a"))
(insert-character #\b)
(is (string= (buffer-contents) "ab"))
(backward-object (point) 2)
(insert-character #\t)
(is (string= (buffer-contents) "tab"))
(setf (overwrite-mode (current-view)) t)
(insert-character #\i)
(insert-character #\p)
(is (string= (buffer-contents) "tip"))
))
(test delete-horizontal-space
(with-drei-environment (:initial-contents " foo")
(setf (offset (point)) 3)
(delete-horizontal-space (point) (current-syntax))
(is (string= (buffer-contents) "foo"))
(insert-sequence (point) " ")
(setf (offset (point)) 3)
(delete-horizontal-space (point) (current-syntax) t)
(is (string= (buffer-contents) " foo"))
(delete-horizontal-space (point) (current-syntax))
(is (string= (buffer-contents) "foo"))
(delete-horizontal-space (point) (current-syntax))
(is (string= (buffer-contents) "foo"))))
(test indent-current-line
(with-drei-environment (:initial-contents "Foo bar baz
Quux")
(indent-current-line (current-view) (point))
(is (string= (buffer-contents)
"Foo bar baz
Quux"))
(setf (offset (point)) 12)
(indent-current-line (current-view) (point))
(is (string= (buffer-contents)
"Foo bar baz
Quux"))))
(test insert-pair
(with-drei-environment ()
(insert-pair (mark) (current-syntax))
(buffer-is "()")
(beginning-of-buffer (point))
(insert-pair (point) (current-syntax) 0 #\[ #\])
(buffer-is "[] ()")))
(test goto-position
(with-drei-environment (:initial-contents "foobarbaz")
(goto-position (point) 5)
(is (= (offset (point)) 5))))
(test goto-line
(with-drei-environment (:initial-contents "First line
Second line
Third line")
(goto-line (point) 1)
(is (= (line-number (point)) 0))
(is (= (offset (point)) 0))
(goto-line (point) 2)
(is (= (line-number (point)) 1))
(is (= (offset (point)) 11))
(goto-line (point) 3)
(is (= (line-number (point)) 2))
(is (= (offset (point)) 23))
(goto-line (point) 4)
(is (= (line-number (point)) 2))
(is (= (offset (point)) 23))))
(test replace-one-string
(with-drei-environment (:initial-contents "Drei Climacs Drei")
(replace-one-string (point) 17 "foo bar" nil)
(buffer-is "foo bar"))
(with-drei-environment (:initial-contents "drei climacs drei")
(replace-one-string (point) 17 "foo bar" t)
(buffer-is "foo bar"))
(with-drei-environment (:initial-contents "Drei Climacs Drei")
(replace-one-string (point) 17 "foo bar" t)
(buffer-is "Foo Bar"))
(with-drei-environment (:initial-contents "DREI CLIMACS DREI")
(replace-one-string (point) 17 "foo bar" t)
(buffer-is "FOO BAR")))
(test downcase-word
(with-drei-environment ()
(downcase-word (point) (current-syntax) 1)
(is (string= (buffer-contents) "")))
(with-drei-environment (:initial-contents "Drei Climacs Drei")
(downcase-word (point) (current-syntax) 1)
(buffer-is "drei Climacs Drei")
(downcase-word (point) (current-syntax) 1)
(buffer-is "drei climacs Drei")
(downcase-word (point) (current-syntax) 1)
(buffer-is "drei climacs drei"))
(with-drei-environment (:initial-contents "Drei Climacs Drei")
(downcase-word (point) (current-syntax) 0)
(buffer-is "Drei Climacs Drei"))
(with-drei-environment (:initial-contents "Drei Climacs Drei")
(downcase-word (point) (current-syntax) 2)
(buffer-is "drei climacs Drei"))
(with-drei-environment (:initial-contents "Drei Climacs Drei")
(downcase-word (point) (current-syntax) 3)
(buffer-is "drei climacs drei"))
(with-drei-environment (:initial-contents "CLI MA CS CLIMACS")
(downcase-word (point) (current-syntax) 3)
(is (buffer-is "cli ma cs CLIMACS"))
(is (= 9 (offset (point))))))
(test upcase-word
(with-drei-environment ()
(upcase-word (point) (current-syntax) 1)
(is (string= (buffer-contents) "")))
(with-drei-environment (:initial-contents "Drei Climacs Drei")
(upcase-word (point) (current-syntax) 1)
(buffer-is "DREI Climacs Drei")
(upcase-word (point) (current-syntax) 1)
(buffer-is "DREI CLIMACS Drei")
(upcase-word (point) (current-syntax) 1)
(buffer-is "DREI CLIMACS DREI"))
(with-drei-environment (:initial-contents "Drei Climacs Drei")
(upcase-word (point) (current-syntax) 0)
(buffer-is "Drei Climacs Drei"))
(with-drei-environment (:initial-contents "Drei Climacs Drei")
(upcase-word (point) (current-syntax) 2)
(buffer-is "DREI CLIMACS Drei"))
(with-drei-environment (:initial-contents "Drei Climacs Drei")
(upcase-word (point) (current-syntax) 3)
(buffer-is "DREI CLIMACS DREI"))
(with-drei-environment (:initial-contents "cli ma cs climacs")
(let ((m (clone-mark (point) :right)))
(setf (offset m) 0)
(upcase-word m (current-syntax) 3)
(is (string= (buffer-contents)
"CLI MA CS climacs"))
(is (= (offset m) 9)))))
(test capitalize-word
(with-drei-environment ()
(capitalize-word (point) (current-syntax) 1)
(is (string= (buffer-contents) "")))
(with-drei-environment (:initial-contents "drei climacs drei")
(capitalize-word (point) (current-syntax) 1)
(buffer-is "Drei climacs drei")
(capitalize-word (point) (current-syntax) 1)
(buffer-is "Drei Climacs drei")
(capitalize-word (point) (current-syntax) 1)
(buffer-is "Drei Climacs Drei"))
(with-drei-environment (:initial-contents "drei climacs drei")
(capitalize-word (point) (current-syntax) 0)
(buffer-is "drei climacs drei"))
(with-drei-environment (:initial-contents "drei climacs drei")
(capitalize-word (point) (current-syntax) 2)
(buffer-is "Drei Climacs drei"))
(with-drei-environment (:initial-contents "drei climacs drei")
(capitalize-word (point) (current-syntax) 3)
(buffer-is "Drei Climacs Drei"))
(with-drei-environment ( :initial-contents "cli ma cs climacs")
(let ((m (clone-mark (point) :right)))
(setf (offset m) 0)
(capitalize-word m (current-syntax) 3)
(is (string= (buffer-contents)
"Cli Ma Cs climacs"))
(is (= (offset m) 9)))))
(test indent-region
CLIM pane .
)
(test fill-line
(flet ((fill-it (fill-column)
(fill-line (point)
(lambda (mark)
(proper-line-indentation (current-view) mark))
fill-column
(tab-space-count (current-view))
(current-syntax))))
(with-drei-environment (:initial-contents "climacs climacs climacs climacs")
(let ((m (clone-mark (point) :right)))
(setf (offset m) 25)
(fill-line m #'(lambda (m) (declare (ignore m)) 8) 10 8 (current-syntax))
(is (= (offset m) 25))
(buffer-is "climacs
climacs
climacs climacs")))
(with-drei-environment (:initial-contents "climacs climacs climacs climacs")
(let ((m (clone-mark (point) :right)))
(setf (offset m) 25)
(fill-line m #'(lambda (m) (declare (ignore m)) 8) 10 8 (current-syntax) nil)
(is (= (offset m) 27))
(buffer-is "climacs
climacs
climacs climacs")))
(with-drei-environment (:initial-contents #.(format nil "climacs~Aclimacs~Aclimacs~Aclimacs"
#\Tab #\Tab #\Tab))
(let ((m (clone-mark (point) :left)))
(setf (offset m) 25)
(fill-line m #'(lambda (m) (declare (ignore m)) 8) 10 8 (current-syntax))
(is (= (offset m) 27))
(buffer-is "climacs
climacs
climacs climacs")))
(with-drei-environment (:initial-contents #.(format nil "climacs~Aclimacs~Aclimacs~Aclimacs"
#\Tab #\Tab #\Tab))
(let ((m (clone-mark (point) :left)))
(setf (offset m) 25)
(fill-line m #'(lambda (m) (declare (ignore m)) 8) 10 8 (current-syntax))
(is (= (offset m) 27))
(buffer-is "climacs
climacs
climacs climacs")))
(with-drei-environment (:initial-contents "c l i m a c s")
(let ((m (clone-mark (point) :right)))
(setf (offset m) 1)
(fill-line m #'(lambda (m) (declare (ignore m)) 8) 0 8 (current-syntax))
(is (= (offset m) 1))
(buffer-is "c l i m a c s")))
(with-drei-environment (:initial-contents "c l i m a c s")
(let ((m (clone-mark (point) :right)))
(setf (offset m) 1)
(fill-line m #'(lambda (m) (declare (ignore m)) 8) 0 8 (current-syntax) nil)
(is (= (offset m) 1))
(buffer-is "c l i m a c s")))
(with-drei-environment ()
(fill-it 80)
(buffer-is ""))
(with-drei-environment
(:initial-contents "Very long line, this should certainly be filled, if everything works")
(end-of-buffer (point))
(fill-it 200)
(buffer-is "Very long line, this should certainly be filled, if everything works")
(fill-it 20)
(buffer-is "Very long line,
this should
certainly be filled,
if everything works"))))
(test fill-region
(flet ((fill-it (fill-column)
(fill-region (point) (mark)
(lambda (mark)
(proper-line-indentation (current-view) mark))
fill-column
(tab-space-count (current-view))
(current-syntax))))
(with-drei-environment
(:initial-contents "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
What, you thought I would write something this long myself? Not a chance. Though this line is growing by a fair bit too, I better test it as well.")
(end-of-line (mark))
(fill-it 80)
(buffer-is "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor
incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis
nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu
fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in
culpa qui officia deserunt mollit anim id est laborum.
What, you thought I would write something this long myself? Not a chance. Though this line is growing by a fair bit too, I better test it as well.")
(end-of-buffer (mark))
(forward-paragraph (point) (current-syntax) 2 nil)
(backward-paragraph (point) (current-syntax) 1)
(fill-it 80)
(buffer-is "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor
incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis
nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu
fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in
culpa qui officia deserunt mollit anim id est laborum.
What, you thought I would write something this long myself? Not a chance.
Though this line is growing by a fair bit too, I better test it as well."))))
(test indent-line
(dolist (stick-to '(:left :right))
(with-drei-environment ()
(buffer-is ""))
(with-drei-environment (:initial-contents "I am to be indented")
(indent-line (clone-mark (point) stick-to) 11 nil)
(buffer-is " I am to be indented"))
(with-drei-environment (:initial-contents "I am to be indented")
(indent-line (clone-mark (point) stick-to) 11 2)
(buffer-is #. (format nil "~A~A~A~A~A I am to be indented"
#\Tab #\Tab #\Tab #\Tab #\Tab)))))
(test delete-indentation
(with-drei-environment (:initial-contents "")
(delete-indentation (current-syntax) (point))
(buffer-is ""))
(with-drei-environment (:initial-contents "Foo")
(delete-indentation (current-syntax) (point))
(buffer-is "Foo"))
(with-drei-environment (:initial-contents " Foo")
(delete-indentation (current-syntax) (point))
(buffer-is "Foo"))
(with-drei-environment (:initial-contents " Foo ")
(delete-indentation (current-syntax) (point))
(buffer-is "Foo "))
(with-drei-environment (:initial-contents " Foo
Bar
Baz")
(forward-line (point) (current-syntax))
(delete-indentation (current-syntax) (point))
(buffer-is " Foo
Bar
Baz"))
(with-drei-environment (:initial-contents "
foo bar")
(let ((start (clone-mark (point (current-view))))
(end (clone-mark (point (current-view))))
(orig-contents (buffer-contents)))
(beginning-of-buffer start)
(end-of-buffer end)
(do-buffer-region-lines (line start end)
(delete-indentation (current-syntax) line))
(buffer-is orig-contents))))
(test join-line
(with-drei-environment (:initial-contents "
climacs ")
(let ((m (clone-mark (point) :left)))
(setf (offset m) 3)
(join-line (current-syntax) m)
(is (= (offset m) 0))
(buffer-is "climacs ")))
(with-drei-environment (:initial-contents "
climacs ")
(let ((m (clone-mark (point) :right)))
(setf (offset m) 7)
(join-line (current-syntax) m)
(is (= (offset m) 0))
(buffer-is "climacs ")))
(with-drei-environment (:initial-contents " climacs ")
(let ((m (clone-mark (point) :left)))
(setf (offset m) 7)
(join-line (current-syntax) m)
(is (= (offset m) 0))
(buffer-is " climacs ")))
(with-drei-environment (:initial-contents "climacs
climacs ")
(let ((m (clone-mark (point) :right)))
(setf (offset m) 12)
(join-line (current-syntax) m)
(is (= (offset m) 8))
(buffer-is "climacs climacs ")))
(with-drei-environment (:initial-contents "
climacs ")
(let ((m (clone-mark (point) :right)))
(setf (offset m) 12)
(join-line (current-syntax) m)
(is (= (offset m) 0))
(buffer-is "climacs "))))
(test set-syntax
(dolist (syntax-designator `("Lisp" drei-lisp-syntax::lisp-syntax
,(find-class 'drei-lisp-syntax::lisp-syntax)))
(with-drei-environment ()
(let ((old-syntax (current-syntax)))
(set-syntax (current-view) syntax-designator)
(is (not (eq old-syntax (current-syntax))))
(is (typep (current-syntax) 'drei-lisp-syntax::lisp-syntax))))))
(test with-narrowed-buffer
(with-drei-environment (:initial-contents "foo bar baz quux")
(setf (offset (point)) 1
(offset (mark)) (1- (size (current-buffer))))
(let ((mark1 (clone-mark (point) :left))
(mark2 (clone-mark (mark) :right)))
(forward-object mark1)
(backward-object mark2)
(dolist (low (list 2 mark1))
(dolist (high (list (- (size (current-buffer)) 2) mark2))
(with-narrowed-buffer ((drei-instance) low high t)
(is (= (offset (point)) 2))
(is (= (offset (mark)) (- (size (current-buffer)) 2)))))))))
|
3fd287c43075ecb4f6918f5183876ad6e667aebc96b22ec1f669da7bc26fcf7e | 2600hz/community-scripts | three_byte_utf8.erl | {[
{<<"matzue">>, <<230, 157, 190, 230, 177, 159>>},
{<<"asakusa">>, <<230, 181, 133, 232, 141, 137>>}
]}. | null | https://raw.githubusercontent.com/2600hz/community-scripts/b0b81342bf02300fcdbda99e4cecc1ee93823c70/CloneTools/lib/ejson-0.1.0/t/cases/three_byte_utf8.erl | erlang | {[
{<<"matzue">>, <<230, 157, 190, 230, 177, 159>>},
{<<"asakusa">>, <<230, 181, 133, 232, 141, 137>>}
]}. | |
6100c40801ffc33edbd52a67537cb23728103b7ac77e11dd3ae200a22eb442b8 | input-output-hk/Alonzo-testnet | DeadlineRedeemer.hs | # LANGUAGE DataKinds #
# LANGUAGE FlexibleContexts #
# LANGUAGE NoImplicitPrelude #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TemplateHaskell #
# LANGUAGE TypeApplications #
# LANGUAGE TypeFamilies #
# LANGUAGE TypeOperators #
module Cardano.PlutusExample.DeadlineRedeemer
( deadlineScript
, deadlineScriptShortBs
) where
import Prelude hiding (($))
import Cardano.Api.Shelley (PlutusScript (..), PlutusScriptV1)
import Codec.Serialise
import qualified Data.ByteString.Lazy as LBS
import qualified Data.ByteString.Short as SBS
import Ledger hiding (singleton)
import Ledger.Constraints as Constraints
import qualified Ledger.Typed.Scripts as Scripts
import qualified Plutus.V1.Ledger.Scripts as Plutus
import qualified PlutusTx
import PlutusTx.Prelude hiding (Semigroup (..), unless)
{-# INLINABLE mkPolicy #-}
mkPolicy :: POSIXTime -> ScriptContext -> Bool
mkPolicy dl ctx = (to dl) `contains` range
where
info :: TxInfo
info = scriptContextTxInfo ctx
range :: POSIXTimeRange
range = txInfoValidRange info
inst :: Scripts.MintingPolicy
inst = mkMintingPolicyScript
$$(PlutusTx.compile [|| Scripts.wrapMintingPolicy mkPolicy ||])
plutusScript :: Script
plutusScript =
unMintingPolicyScript inst
deadlineValidator :: Validator
deadlineValidator =
Validator $ unMintingPolicyScript inst
script :: Plutus.Script
script = Plutus.unValidatorScript deadlineValidator
deadlineScriptShortBs :: SBS.ShortByteString
deadlineScriptShortBs = SBS.toShort . LBS.toStrict $ serialise script
deadlineScript :: PlutusScript PlutusScriptV1
deadlineScript = PlutusScriptSerialised deadlineScriptShortBs
| null | https://raw.githubusercontent.com/input-output-hk/Alonzo-testnet/1fd8da32d44ba48164931eb3e30f1a34e45955af/resources/plutus-sources/plutus-deadline/src/Cardano/PlutusDeadline/DeadlineRedeemer.hs | haskell | # INLINABLE mkPolicy # | # LANGUAGE DataKinds #
# LANGUAGE FlexibleContexts #
# LANGUAGE NoImplicitPrelude #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TemplateHaskell #
# LANGUAGE TypeApplications #
# LANGUAGE TypeFamilies #
# LANGUAGE TypeOperators #
module Cardano.PlutusExample.DeadlineRedeemer
( deadlineScript
, deadlineScriptShortBs
) where
import Prelude hiding (($))
import Cardano.Api.Shelley (PlutusScript (..), PlutusScriptV1)
import Codec.Serialise
import qualified Data.ByteString.Lazy as LBS
import qualified Data.ByteString.Short as SBS
import Ledger hiding (singleton)
import Ledger.Constraints as Constraints
import qualified Ledger.Typed.Scripts as Scripts
import qualified Plutus.V1.Ledger.Scripts as Plutus
import qualified PlutusTx
import PlutusTx.Prelude hiding (Semigroup (..), unless)
mkPolicy :: POSIXTime -> ScriptContext -> Bool
mkPolicy dl ctx = (to dl) `contains` range
where
info :: TxInfo
info = scriptContextTxInfo ctx
range :: POSIXTimeRange
range = txInfoValidRange info
inst :: Scripts.MintingPolicy
inst = mkMintingPolicyScript
$$(PlutusTx.compile [|| Scripts.wrapMintingPolicy mkPolicy ||])
plutusScript :: Script
plutusScript =
unMintingPolicyScript inst
deadlineValidator :: Validator
deadlineValidator =
Validator $ unMintingPolicyScript inst
script :: Plutus.Script
script = Plutus.unValidatorScript deadlineValidator
deadlineScriptShortBs :: SBS.ShortByteString
deadlineScriptShortBs = SBS.toShort . LBS.toStrict $ serialise script
deadlineScript :: PlutusScript PlutusScriptV1
deadlineScript = PlutusScriptSerialised deadlineScriptShortBs
|
e4563c690735a297751b68ce7b4f1d4d9abb2cea3ca9bba8fc874dbae2ae79cb | contentjon/mocha-latte | core.cljs | (ns latte.test.core
(:require-macros [latte.core :as l]))
(def assert (js/require "assert"))
(l/describe "Test Suites"
(l/it "can contain test cases" []
(assert (= true true)))
(l/it "can contain empty (pending) test cases" [])
(l/it "can skip test cases" [] :skip true
(assert (= true false)))
(l/it "can contain asynchronous test cases" [done]
(js/setTimeout done 0))
(l/it "can contain asynchronous test cases with a timeout" [done] :timeout 500
(js/setTimeout done 100))
(l/describe "Nested Suites"
(l/it "can contain test cases in nested test suites" []
(assert (= true true)))))
(def test-value (atom nil))
(l/describe "Test fixtures"
(l/describe "before"
(l/before []
(reset! test-value true))
(l/it "before is called at the beginning of the suite" []
(assert (= @test-value true))))
(l/describe "after"
(l/before []
(reset! test-value true))
(l/after []
(reset! test-value false))
(l/it "after is called at the end of the suite" []
(assert (= @test-value true))))
(l/describe "after (second pass)"
(l/it "after is called at the end of the suite" []
(assert (= @test-value false))))
(l/describe "beforeEach"
(l/before []
(reset! test-value 0))
(l/beforeEach []
(swap! test-value inc))
(l/it "beforeEach is called at the before first test case" []
(assert (= @test-value 1)))
(l/it "beforeEach is called at the before second test case" []
(assert (= @test-value 2)))
(l/it "beforeEach is called at the before third test case" []
(assert (= @test-value 3))))
(l/describe "afterEach"
(l/before []
(reset! test-value 0))
(l/afterEach []
(swap! test-value inc))
(l/it "afterEach is called at the after first test case" []
(assert (= @test-value 0)))
(l/it "afterEach is called at the after second test case" []
(assert (= @test-value 1)))
(l/it "afterEach is called at the after third test case" []
(assert (= @test-value 2))))
(l/describe "that are asynchonous"
(l/before [done]
(js/setTimeout
(fn []
(reset! test-value :foo)
(done))
0))
(l/it "test case is run after asynchronous begin finishes" []
(assert (= @test-value :foo)))))
| null | https://raw.githubusercontent.com/contentjon/mocha-latte/27251ca349086e17e82906f48014b945c848c04d/test/latte/core.cljs | clojure | (ns latte.test.core
(:require-macros [latte.core :as l]))
(def assert (js/require "assert"))
(l/describe "Test Suites"
(l/it "can contain test cases" []
(assert (= true true)))
(l/it "can contain empty (pending) test cases" [])
(l/it "can skip test cases" [] :skip true
(assert (= true false)))
(l/it "can contain asynchronous test cases" [done]
(js/setTimeout done 0))
(l/it "can contain asynchronous test cases with a timeout" [done] :timeout 500
(js/setTimeout done 100))
(l/describe "Nested Suites"
(l/it "can contain test cases in nested test suites" []
(assert (= true true)))))
(def test-value (atom nil))
(l/describe "Test fixtures"
(l/describe "before"
(l/before []
(reset! test-value true))
(l/it "before is called at the beginning of the suite" []
(assert (= @test-value true))))
(l/describe "after"
(l/before []
(reset! test-value true))
(l/after []
(reset! test-value false))
(l/it "after is called at the end of the suite" []
(assert (= @test-value true))))
(l/describe "after (second pass)"
(l/it "after is called at the end of the suite" []
(assert (= @test-value false))))
(l/describe "beforeEach"
(l/before []
(reset! test-value 0))
(l/beforeEach []
(swap! test-value inc))
(l/it "beforeEach is called at the before first test case" []
(assert (= @test-value 1)))
(l/it "beforeEach is called at the before second test case" []
(assert (= @test-value 2)))
(l/it "beforeEach is called at the before third test case" []
(assert (= @test-value 3))))
(l/describe "afterEach"
(l/before []
(reset! test-value 0))
(l/afterEach []
(swap! test-value inc))
(l/it "afterEach is called at the after first test case" []
(assert (= @test-value 0)))
(l/it "afterEach is called at the after second test case" []
(assert (= @test-value 1)))
(l/it "afterEach is called at the after third test case" []
(assert (= @test-value 2))))
(l/describe "that are asynchonous"
(l/before [done]
(js/setTimeout
(fn []
(reset! test-value :foo)
(done))
0))
(l/it "test case is run after asynchronous begin finishes" []
(assert (= @test-value :foo)))))
| |
6b7862d200b48a7f63975bf4cddde7d4b6b6d61bc1f541ed16f9df839a748ddb | pfdietz/ansi-test | svref.lsp | ;-*- Mode: Lisp -*-
Author :
Created : We d Jan 22 21:39:30 2003
Contains : Tests of
(deftest svref.1
(let ((a (vector 1 2 3 4)))
(loop for i below 4 collect (svref a i)))
(1 2 3 4))
(deftest svref.2
(let ((a (vector 1 2 3 4)))
(values
(loop for i below 4
collect (setf (svref a i) (+ i 10)))
a))
(10 11 12 13)
#(10 11 12 13))
(deftest svref.order.1
(let ((v (vector 'a 'b 'c 'd))
(i 0) a b)
(values
(svref (progn (setf a (incf i)) v)
(progn (setf b (incf i)) 2))
i a b))
c 2 1 2)
(deftest svref.order.2
(let ((v (vector 'a 'b 'c 'd))
(i 0) a b c)
(values
(setf
(svref (progn (setf a (incf i)) v)
(progn (setf b (incf i)) 2))
(progn (setf c (incf i)) 'w))
v i a b c))
w #(a b w d) 3 1 2 3)
;;; Error tests
(deftest svref.error.1
(signals-error (svref) program-error)
t)
(deftest svref.error.2
(signals-error (svref (vector 1)) program-error)
t)
(deftest svref.error.3
(signals-error (svref (vector 1) 0 0) program-error)
t)
(deftest svref.error.4
(signals-error (svref (vector 1) 0 nil) program-error)
t)
| null | https://raw.githubusercontent.com/pfdietz/ansi-test/3f4b9d31c3408114f0467eaeca4fd13b28e2ce31/arrays/svref.lsp | lisp | -*- Mode: Lisp -*-
Error tests | Author :
Created : We d Jan 22 21:39:30 2003
Contains : Tests of
(deftest svref.1
(let ((a (vector 1 2 3 4)))
(loop for i below 4 collect (svref a i)))
(1 2 3 4))
(deftest svref.2
(let ((a (vector 1 2 3 4)))
(values
(loop for i below 4
collect (setf (svref a i) (+ i 10)))
a))
(10 11 12 13)
#(10 11 12 13))
(deftest svref.order.1
(let ((v (vector 'a 'b 'c 'd))
(i 0) a b)
(values
(svref (progn (setf a (incf i)) v)
(progn (setf b (incf i)) 2))
i a b))
c 2 1 2)
(deftest svref.order.2
(let ((v (vector 'a 'b 'c 'd))
(i 0) a b c)
(values
(setf
(svref (progn (setf a (incf i)) v)
(progn (setf b (incf i)) 2))
(progn (setf c (incf i)) 'w))
v i a b c))
w #(a b w d) 3 1 2 3)
(deftest svref.error.1
(signals-error (svref) program-error)
t)
(deftest svref.error.2
(signals-error (svref (vector 1)) program-error)
t)
(deftest svref.error.3
(signals-error (svref (vector 1) 0 0) program-error)
t)
(deftest svref.error.4
(signals-error (svref (vector 1) 0 nil) program-error)
t)
|
283d8846aaef11130673639a28364f9f9cebc38d781e2b0c4c525e470dc06345 | haskellfoundation/error-message-index | DependencyOrder.hs | # LANGUAGE DataKinds , PolyKinds , ExplicitForAll #
module DependencyOrder where
import Data.Kind
data SameKind :: k -> k -> *
foo :: forall k a (b :: k). SameKind a b
foo = undefined
| null | https://raw.githubusercontent.com/haskellfoundation/error-message-index/6b80c2fe6d8d2941190bda587bcea6f775ded0a4/message-index/messages/GHC-97739/example/after/DependencyOrder.hs | haskell | # LANGUAGE DataKinds , PolyKinds , ExplicitForAll #
module DependencyOrder where
import Data.Kind
data SameKind :: k -> k -> *
foo :: forall k a (b :: k). SameKind a b
foo = undefined
| |
df9b3decac29e23626fd238bd3ac547f87bf741a5f561421f3d621cb4247c12b | basho/riak_core | vclock_qc.erl | -module(vclock_qc).
-ifdef(EQC).
-include_lib("eqc/include/eqc.hrl").
-include_lib("eqc/include/eqc_statem.hrl").
-include_lib("eunit/include/eunit.hrl").
-compile([export_all, nowarn_export_all]).
-define(ACTOR_IDS, [a,b,c,d,e]).
-define(QC_OUT(P),
eqc:on_output(fun(Str, Args) -> io:format(user, Str, Args) end, P)).
-record(state, {vclocks = []}).
-define(TEST_TIME, 20).
eqc_test_() ->
{timeout,
60,
?_assert(quickcheck(eqc:testing_time(?TEST_TIME, more_commands(10,?QC_OUT(prop_vclock())))))}.
test() ->
quickcheck(eqc:testing_time(?TEST_TIME, more_commands(10, prop_vclock()))).
test(Time) ->
quickcheck(eqc:testing_time(Time, more_commands(10, prop_vclock()))).
Initialize the state
initial_state() ->
#state{}.
%% Command generator, S is the state
command(#state{vclocks=Vs}) ->
oneof([{call, ?MODULE, fresh, []}] ++
[{call, ?MODULE, timestamp, []}] ++
[{call, ?MODULE, increment, [gen_actor_id(), elements(Vs)]} || length(Vs) > 0] ++
[{call, ?MODULE, get_counter, [gen_actor_id(), elements(Vs)]} || length(Vs) > 0] ++
[{call, ?MODULE, get_timestamp, [gen_actor_id(), elements(Vs)]} || length(Vs) > 0] ++
[{call, ?MODULE, get_dot, [gen_actor_id(), elements(Vs)]} || length(Vs) > 0] ++
[{call, ?MODULE, merge, [list(elements(Vs))]} || length(Vs) > 0] ++
[{call, ?MODULE, descends, [elements(Vs), elements(Vs)]} || length(Vs) > 0] ++
[{call, ?MODULE, descends_dot, [elements(Vs), elements(Vs), gen_actor_id()]} || length(Vs) > 0] ++
[{call, ?MODULE, dominates, [elements(Vs), elements(Vs)]} || length(Vs) > 0]
).
Next state transformation , S is the current state
next_state(S,_V,{call,_,get_counter,[_, _]}) ->
S;
next_state(S,_V,{call,_,get_timestamp,[_, _]}) ->
S;
next_state(S,_V,{call,_,get_dot,[_, _]}) ->
S;
next_state(S,_V,{call,_,descends,[_, _]}) ->
S;
next_state(S,_V,{call,_,descends_dot,[_, _, _]}) ->
S;
next_state(S,_V,{call,_,dominates,[_, _]}) ->
S;
next_state(S, _V, {call,_,timestamp,_}) ->
S;
next_state(#state{vclocks=Vs}=S,V,{call,_,_,_}) ->
S#state{vclocks=Vs ++ [V]}.
Precondition , checked before command is added to the command sequence
precondition(_S,{call,_,_,_}) ->
true.
%% Postcondition, checked after command has been evaluated
OBS : S is the state before next_state(S,_,<command > )
postcondition(_S, {call, _, get_counter, _}, {MRes, Res}) ->
MRes == Res;
postcondition(_S, {call, _, get_timestamp, _}, {MRes, Res}) ->
timestamp_values_equal(MRes, Res);
postcondition(_S, {call, _, get_dot, _}, {{_Actor, 0, 0}, undefined}) ->
true;
postcondition(_S, {call, _, get_dot, _}, {{Actor, Cnt, TS}, {ok, {Actor, {Cnt, TS}}}}) ->
true;
postcondition(_S, {call, _, get_dot, _}, {_, _}) ->
false;
postcondition(_S, {call, _, descends, _}, {MRes, Res}) ->
MRes == Res;
postcondition(_S, {call, _, descends_dot, _}, {MRes, Res}) ->
MRes == Res;
postcondition(_S, {call, _, dominates, _}, {MRes, Res}) ->
MRes == Res;
postcondition(_S, {call, _, merge, [Items]}, {MRes, Res}) ->
model_compare(MRes, Res) andalso
lists:all(fun({_, V}) ->
vclock:descends(Res, V)
end, Items);
postcondition(_S, _C, {MRes, Res}) ->
model_compare(MRes, Res);
postcondition(_S, _C, _Res) ->
true.
prop_vclock() ->
?FORALL(Cmds,commands(?MODULE),
begin
put(timestamp, 1),
{H,S,Res} = run_commands(?MODULE,Cmds),
aggregate([ length(V) || {_,V} <- S#state.vclocks ],
aggregate(command_names(Cmds),
collect({num_vclocks_div_10, length(S#state.vclocks) div 10},
pretty_commands(?MODULE,Cmds, {H,S,Res}, Res == ok))))
end).
gen_actor_id() ->
elements(?ACTOR_IDS).
gen_entry(Actor, S) ->
?LET({_M, V}, elements(S), vclock:get_dot(Actor, V)).
fresh() ->
{new_model(), vclock:fresh()}.
dominates({AM, AV}, {BM, BV}) ->
{model_descends(AM, BM) andalso not model_descends(BM, AM),
vclock:dominates(AV, BV)}.
descends({AM, AV}, {BM, BV}) ->
{model_descends(AM, BM),
vclock:descends(AV, BV)}.
descends_dot(A, {BM, BV}, Actor) ->
{AMDot, AVDot} = get_dot(Actor, A),
ModelDescends = model_descends_dot(BM, AMDot),
case AVDot of
undefined ->
{ModelDescends, true};
{ok, Dot} ->
{ModelDescends, vclock:descends_dot(BV, Dot)}
end.
get_counter(A, {M, V}) ->
{model_counter(A, M), vclock:get_counter(A, V)}.
get_dot(A, {M, V}) ->
{model_entry(A, M), vclock:get_dot(A, V)}.
increment(A, {M, V}) ->
TS = timestamp(),
MCount = model_counter(A, M),
{lists:keyreplace(A, 1, M, {A, MCount + 1, TS}), vclock:increment(A, TS, V)}.
merge(List) ->
{Models, VClocks} = lists:unzip(List),
{lists:foldl(fun model_merge/2, new_model(), Models),
vclock:merge(VClocks)}.
model_merge(M,OM) ->
[ if C1 > C2 -> {A, C1, T1};
C1 == C2 -> {A, C1, erlang:max(T1, T2)};
true -> {A, C2, T2}
end
|| {{A, C1, T1}, {A, C2, T2}} <- lists:zip(M, OM) ].
new_model() ->
[{ID, 0, 0} || ID <- ?ACTOR_IDS].
model_compare(M, V) ->
lists:all(fun(A) ->
model_counter(A,M) == vclock:get_counter(A,V) andalso
timestamps_equal(A, M, V)
end,
?ACTOR_IDS).
model_descends(AM, BM) ->
lists:all(fun({{Actor, Count1, _TS1}, {Actor, Count2, _TS2}}) ->
Count1 >= Count2
end,
lists:zip(AM, BM)).
model_descends_dot(M, {A, C, _TS}) ->
{A, MC, _MTS} = lists:keyfind(A, 1, M),
MC >= C.
get_timestamp(A, {M, V}) ->
{model_timestamp(A,M), vclock:get_timestamp(A, V)}.
timestamp() ->
put(timestamp, get(timestamp) + 1).
model_counter(A, M) ->
element(2, lists:keyfind(A, 1, M)).
model_timestamp(A, M) ->
element(3, lists:keyfind(A, 1, M)).
model_entry(A, M) ->
lists:keyfind(A, 1, M).
timestamps_equal(A, M, V) ->
VT = vclock:get_timestamp(A,V),
MT = model_timestamp(A,M),
timestamp_values_equal(MT, VT).
timestamp_values_equal(0, undefined) ->
true;
timestamp_values_equal(T, T) ->
true;
timestamp_values_equal(_, _) ->
false.
-endif.
| null | https://raw.githubusercontent.com/basho/riak_core/762ec81ae9af9a278e853f1feca418b9dcf748a3/eqc/vclock_qc.erl | erlang | Command generator, S is the state
Postcondition, checked after command has been evaluated | -module(vclock_qc).
-ifdef(EQC).
-include_lib("eqc/include/eqc.hrl").
-include_lib("eqc/include/eqc_statem.hrl").
-include_lib("eunit/include/eunit.hrl").
-compile([export_all, nowarn_export_all]).
-define(ACTOR_IDS, [a,b,c,d,e]).
-define(QC_OUT(P),
eqc:on_output(fun(Str, Args) -> io:format(user, Str, Args) end, P)).
-record(state, {vclocks = []}).
-define(TEST_TIME, 20).
eqc_test_() ->
{timeout,
60,
?_assert(quickcheck(eqc:testing_time(?TEST_TIME, more_commands(10,?QC_OUT(prop_vclock())))))}.
test() ->
quickcheck(eqc:testing_time(?TEST_TIME, more_commands(10, prop_vclock()))).
test(Time) ->
quickcheck(eqc:testing_time(Time, more_commands(10, prop_vclock()))).
Initialize the state
initial_state() ->
#state{}.
command(#state{vclocks=Vs}) ->
oneof([{call, ?MODULE, fresh, []}] ++
[{call, ?MODULE, timestamp, []}] ++
[{call, ?MODULE, increment, [gen_actor_id(), elements(Vs)]} || length(Vs) > 0] ++
[{call, ?MODULE, get_counter, [gen_actor_id(), elements(Vs)]} || length(Vs) > 0] ++
[{call, ?MODULE, get_timestamp, [gen_actor_id(), elements(Vs)]} || length(Vs) > 0] ++
[{call, ?MODULE, get_dot, [gen_actor_id(), elements(Vs)]} || length(Vs) > 0] ++
[{call, ?MODULE, merge, [list(elements(Vs))]} || length(Vs) > 0] ++
[{call, ?MODULE, descends, [elements(Vs), elements(Vs)]} || length(Vs) > 0] ++
[{call, ?MODULE, descends_dot, [elements(Vs), elements(Vs), gen_actor_id()]} || length(Vs) > 0] ++
[{call, ?MODULE, dominates, [elements(Vs), elements(Vs)]} || length(Vs) > 0]
).
Next state transformation , S is the current state
next_state(S,_V,{call,_,get_counter,[_, _]}) ->
S;
next_state(S,_V,{call,_,get_timestamp,[_, _]}) ->
S;
next_state(S,_V,{call,_,get_dot,[_, _]}) ->
S;
next_state(S,_V,{call,_,descends,[_, _]}) ->
S;
next_state(S,_V,{call,_,descends_dot,[_, _, _]}) ->
S;
next_state(S,_V,{call,_,dominates,[_, _]}) ->
S;
next_state(S, _V, {call,_,timestamp,_}) ->
S;
next_state(#state{vclocks=Vs}=S,V,{call,_,_,_}) ->
S#state{vclocks=Vs ++ [V]}.
Precondition , checked before command is added to the command sequence
precondition(_S,{call,_,_,_}) ->
true.
OBS : S is the state before next_state(S,_,<command > )
postcondition(_S, {call, _, get_counter, _}, {MRes, Res}) ->
MRes == Res;
postcondition(_S, {call, _, get_timestamp, _}, {MRes, Res}) ->
timestamp_values_equal(MRes, Res);
postcondition(_S, {call, _, get_dot, _}, {{_Actor, 0, 0}, undefined}) ->
true;
postcondition(_S, {call, _, get_dot, _}, {{Actor, Cnt, TS}, {ok, {Actor, {Cnt, TS}}}}) ->
true;
postcondition(_S, {call, _, get_dot, _}, {_, _}) ->
false;
postcondition(_S, {call, _, descends, _}, {MRes, Res}) ->
MRes == Res;
postcondition(_S, {call, _, descends_dot, _}, {MRes, Res}) ->
MRes == Res;
postcondition(_S, {call, _, dominates, _}, {MRes, Res}) ->
MRes == Res;
postcondition(_S, {call, _, merge, [Items]}, {MRes, Res}) ->
model_compare(MRes, Res) andalso
lists:all(fun({_, V}) ->
vclock:descends(Res, V)
end, Items);
postcondition(_S, _C, {MRes, Res}) ->
model_compare(MRes, Res);
postcondition(_S, _C, _Res) ->
true.
prop_vclock() ->
?FORALL(Cmds,commands(?MODULE),
begin
put(timestamp, 1),
{H,S,Res} = run_commands(?MODULE,Cmds),
aggregate([ length(V) || {_,V} <- S#state.vclocks ],
aggregate(command_names(Cmds),
collect({num_vclocks_div_10, length(S#state.vclocks) div 10},
pretty_commands(?MODULE,Cmds, {H,S,Res}, Res == ok))))
end).
gen_actor_id() ->
elements(?ACTOR_IDS).
gen_entry(Actor, S) ->
?LET({_M, V}, elements(S), vclock:get_dot(Actor, V)).
fresh() ->
{new_model(), vclock:fresh()}.
dominates({AM, AV}, {BM, BV}) ->
{model_descends(AM, BM) andalso not model_descends(BM, AM),
vclock:dominates(AV, BV)}.
descends({AM, AV}, {BM, BV}) ->
{model_descends(AM, BM),
vclock:descends(AV, BV)}.
descends_dot(A, {BM, BV}, Actor) ->
{AMDot, AVDot} = get_dot(Actor, A),
ModelDescends = model_descends_dot(BM, AMDot),
case AVDot of
undefined ->
{ModelDescends, true};
{ok, Dot} ->
{ModelDescends, vclock:descends_dot(BV, Dot)}
end.
get_counter(A, {M, V}) ->
{model_counter(A, M), vclock:get_counter(A, V)}.
get_dot(A, {M, V}) ->
{model_entry(A, M), vclock:get_dot(A, V)}.
increment(A, {M, V}) ->
TS = timestamp(),
MCount = model_counter(A, M),
{lists:keyreplace(A, 1, M, {A, MCount + 1, TS}), vclock:increment(A, TS, V)}.
merge(List) ->
{Models, VClocks} = lists:unzip(List),
{lists:foldl(fun model_merge/2, new_model(), Models),
vclock:merge(VClocks)}.
model_merge(M,OM) ->
[ if C1 > C2 -> {A, C1, T1};
C1 == C2 -> {A, C1, erlang:max(T1, T2)};
true -> {A, C2, T2}
end
|| {{A, C1, T1}, {A, C2, T2}} <- lists:zip(M, OM) ].
new_model() ->
[{ID, 0, 0} || ID <- ?ACTOR_IDS].
model_compare(M, V) ->
lists:all(fun(A) ->
model_counter(A,M) == vclock:get_counter(A,V) andalso
timestamps_equal(A, M, V)
end,
?ACTOR_IDS).
model_descends(AM, BM) ->
lists:all(fun({{Actor, Count1, _TS1}, {Actor, Count2, _TS2}}) ->
Count1 >= Count2
end,
lists:zip(AM, BM)).
model_descends_dot(M, {A, C, _TS}) ->
{A, MC, _MTS} = lists:keyfind(A, 1, M),
MC >= C.
get_timestamp(A, {M, V}) ->
{model_timestamp(A,M), vclock:get_timestamp(A, V)}.
timestamp() ->
put(timestamp, get(timestamp) + 1).
model_counter(A, M) ->
element(2, lists:keyfind(A, 1, M)).
model_timestamp(A, M) ->
element(3, lists:keyfind(A, 1, M)).
model_entry(A, M) ->
lists:keyfind(A, 1, M).
timestamps_equal(A, M, V) ->
VT = vclock:get_timestamp(A,V),
MT = model_timestamp(A,M),
timestamp_values_equal(MT, VT).
timestamp_values_equal(0, undefined) ->
true;
timestamp_values_equal(T, T) ->
true;
timestamp_values_equal(_, _) ->
false.
-endif.
|
592cfc2872356bc2588f8244a89634d2d05ed9c813d7d591322f69efb18e5d54 | oliyh/re-learn | todo_input.cljs | (ns todomvc.components.todo-input
(:require [reagent.core :as reagent]
[todomvc.actions :as actions]
[todomvc.helpers :as helpers]
[reagent.dom :as dom]
[re-learn.core :as re-learn]))
(defn on-key-down [k title default]
(let [key-pressed (.-which k)]
(condp = key-pressed
helpers/enter-key (actions/add-todo title default)
nil)))
(def component
(re-learn/with-lesson
{:id :todo-input-lesson
:description "Add new todo items by typing here, pressing Enter to save. Try it out now!"
:position :bottom
:continue {:event :keydown
:event-filter (fn [e] (= helpers/enter-key (.-which e)))}}
(with-meta
(fn []
(let [default ""
title (reagent/atom default)]
(fn []
[:input#new-todo {:type "text"
:value @title
:placeholder "What needs to be done?"
:on-change #(reset! title (-> % .-target .-value))
:on-key-down #(on-key-down % title default)}])))
{:component-did-mount #(.focus (dom/dom-node %))})))
| null | https://raw.githubusercontent.com/oliyh/re-learn/c8edc38df46910ca2a4401afab7eb3ceac7d2311/example/todomvc/todomvc/components/todo_input.cljs | clojure | (ns todomvc.components.todo-input
(:require [reagent.core :as reagent]
[todomvc.actions :as actions]
[todomvc.helpers :as helpers]
[reagent.dom :as dom]
[re-learn.core :as re-learn]))
(defn on-key-down [k title default]
(let [key-pressed (.-which k)]
(condp = key-pressed
helpers/enter-key (actions/add-todo title default)
nil)))
(def component
(re-learn/with-lesson
{:id :todo-input-lesson
:description "Add new todo items by typing here, pressing Enter to save. Try it out now!"
:position :bottom
:continue {:event :keydown
:event-filter (fn [e] (= helpers/enter-key (.-which e)))}}
(with-meta
(fn []
(let [default ""
title (reagent/atom default)]
(fn []
[:input#new-todo {:type "text"
:value @title
:placeholder "What needs to be done?"
:on-change #(reset! title (-> % .-target .-value))
:on-key-down #(on-key-down % title default)}])))
{:component-did-mount #(.focus (dom/dom-node %))})))
| |
92a12e169e60e589dd26cc3c4e5a349c703826296ef3fe31f7f55e26f4c89b1f | luminus-framework/luminus-template | handler.clj | (ns <<project-ns>>.handler
(:require
[<<project-ns>>.middleware :as middleware]<% if not service %>
[<<project-ns>>.layout :refer [error-page]]
[<<project-ns>>.routes.home :refer [home-routes]]<% endif %><% if service-required %>
<<service-required>><% endif %><% if oauth-required %>
<<oauth-required>><% endif %><% if any service swagger %>
[reitit.swagger-ui :as swagger-ui]<% endif %>
[reitit.ring :as ring]
[ring.middleware.content-type :refer [wrap-content-type]]<% if expanded %>
[ring.middleware.webjars :refer [wrap-webjars]]<% endif %>
[<<project-ns>>.env :refer [defaults]]
[mount.core :as mount]<% if war %>
[clojure.tools.logging :as log]
[<<project-ns>>.config :refer [env]]<% endif %>))
(mount/defstate init-app
:start ((or (:init defaults) (fn [])))
:stop ((or (:stop defaults) (fn []))))
<% if war %>
(defn init
"init will be called once when
app is deployed as a servlet on
an app server such as Tomcat
put any initialization code here"
[]
(doseq [component (:started (mount/start))]
(log/info component "started")))
(defn destroy
"destroy will be called when your application
shuts down, put any clean up code here"
[]
(doseq [component (:stopped (mount/stop))]
(log/info component "stopped"))
(shutdown-agents)
(log/info "<<name>> has shut down!"))
<% endif %>
<% include reitit/src/handler-fragment.clj %>
| null | https://raw.githubusercontent.com/luminus-framework/luminus-template/3278aa727cef0a173ed3ca722dfd6afa6b4bbc8f/resources/leiningen/new/luminus/core/src/handler.clj | clojure | (ns <<project-ns>>.handler
(:require
[<<project-ns>>.middleware :as middleware]<% if not service %>
[<<project-ns>>.layout :refer [error-page]]
[<<project-ns>>.routes.home :refer [home-routes]]<% endif %><% if service-required %>
<<service-required>><% endif %><% if oauth-required %>
<<oauth-required>><% endif %><% if any service swagger %>
[reitit.swagger-ui :as swagger-ui]<% endif %>
[reitit.ring :as ring]
[ring.middleware.content-type :refer [wrap-content-type]]<% if expanded %>
[ring.middleware.webjars :refer [wrap-webjars]]<% endif %>
[<<project-ns>>.env :refer [defaults]]
[mount.core :as mount]<% if war %>
[clojure.tools.logging :as log]
[<<project-ns>>.config :refer [env]]<% endif %>))
(mount/defstate init-app
:start ((or (:init defaults) (fn [])))
:stop ((or (:stop defaults) (fn []))))
<% if war %>
(defn init
"init will be called once when
app is deployed as a servlet on
an app server such as Tomcat
put any initialization code here"
[]
(doseq [component (:started (mount/start))]
(log/info component "started")))
(defn destroy
"destroy will be called when your application
shuts down, put any clean up code here"
[]
(doseq [component (:stopped (mount/stop))]
(log/info component "stopped"))
(shutdown-agents)
(log/info "<<name>> has shut down!"))
<% endif %>
<% include reitit/src/handler-fragment.clj %>
| |
99c9d08edd9c7c432b4cd3f6a97e39d0ecce3d15c4ce382bdbd69d24ce7ac215 | ragkousism/Guix-on-Hurd | elpa.scm | ;;; GNU Guix --- Functional package management for GNU
Copyright © 2015 < >
;;;
;;; This file is part of GNU Guix.
;;;
GNU is free software ; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation ; either version 3 of the License , or ( at
;;; your option) any later version.
;;;
;;; GNU Guix is distributed in the hope that it will be useful, but
;;; WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;;; GNU General Public License for more details.
;;;
You should have received a copy of the GNU General Public License
along with GNU . If not , see < / > .
(define-module (test-elpa)
#:use-module (guix import elpa)
#:use-module (guix tests)
#:use-module (srfi srfi-1)
#:use-module (srfi srfi-64)
#:use-module (ice-9 match))
(define elpa-mock-archive
'(1
(ace-window .
[(0 9 0)
((avy
(0 2 0)))
"Quickly switch windows." single
((:url . "-abo/ace-window")
(:keywords "window" "location"))])
(auctex .
[(11 88 6)
nil "Integrated environment for *TeX*" tar
((:url . "/"))])))
(define auctex-readme-mock "This is the AUCTeX description.")
(define* (elpa-package-info-mock name #:optional (repo "gnu"))
"Simulate retrieval of 'archive-contents' file from REPO and extraction of
information about package NAME. (Function 'elpa-package-info'.)"
(let* ((archive elpa-mock-archive)
(info (filter (lambda (p) (eq? (first p) (string->symbol name)))
(cdr archive))))
(if (pair? info) (first info) #f)))
(define elpa-version->string
(@@ (guix import elpa) elpa-version->string))
(define package-source-url
(@@ (guix import elpa) package-source-url))
(define ensure-list
(@@ (guix import elpa) ensure-list))
(define package-home-page
(@@ (guix import elpa) package-home-page))
(define make-elpa-package
(@@ (guix import elpa) make-elpa-package))
(test-begin "elpa")
(define (eval-test-with-elpa pkg)
(mock
replace the two fetching functions
((guix import elpa) fetch-elpa-package
(lambda* (name #:optional (repo "gnu"))
(let ((pkg (elpa-package-info-mock name repo)))
(match pkg
((name version reqs synopsis kind . rest)
(let* ((name (symbol->string name))
(ver (elpa-version->string version))
(url (package-source-url kind name ver repo)))
(make-elpa-package name ver
(ensure-list reqs) synopsis kind
(package-home-page (first rest))
auctex-readme-mock
url)))
(_ #f)))))
(match (elpa->guix-package pkg)
(('package
('name "emacs-auctex")
('version "11.88.6")
('source
('origin
('method 'url-fetch)
('uri ('string-append
"-" 'version ".tar"))
('sha256 ('base32 (? string? hash)))))
('build-system 'emacs-build-system)
('home-page "/")
('synopsis "Integrated environment for *TeX*")
('description (? string?))
('license 'license:gpl3+))
#t)
(x
(pk 'fail x #f)))))
(test-assert "elpa->guix-package test 1"
(eval-test-with-elpa "auctex"))
(test-end "elpa")
| null | https://raw.githubusercontent.com/ragkousism/Guix-on-Hurd/e951bb2c0c4961dc6ac2bda8f331b9c4cee0da95/tests/elpa.scm | scheme | GNU Guix --- Functional package management for GNU
This file is part of GNU Guix.
you can redistribute it and/or modify it
either version 3 of the License , or ( at
your option) any later version.
GNU Guix is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
| Copyright © 2015 < >
under the terms of the GNU General Public License as published by
You should have received a copy of the GNU General Public License
along with GNU . If not , see < / > .
(define-module (test-elpa)
#:use-module (guix import elpa)
#:use-module (guix tests)
#:use-module (srfi srfi-1)
#:use-module (srfi srfi-64)
#:use-module (ice-9 match))
(define elpa-mock-archive
'(1
(ace-window .
[(0 9 0)
((avy
(0 2 0)))
"Quickly switch windows." single
((:url . "-abo/ace-window")
(:keywords "window" "location"))])
(auctex .
[(11 88 6)
nil "Integrated environment for *TeX*" tar
((:url . "/"))])))
(define auctex-readme-mock "This is the AUCTeX description.")
(define* (elpa-package-info-mock name #:optional (repo "gnu"))
"Simulate retrieval of 'archive-contents' file from REPO and extraction of
information about package NAME. (Function 'elpa-package-info'.)"
(let* ((archive elpa-mock-archive)
(info (filter (lambda (p) (eq? (first p) (string->symbol name)))
(cdr archive))))
(if (pair? info) (first info) #f)))
(define elpa-version->string
(@@ (guix import elpa) elpa-version->string))
(define package-source-url
(@@ (guix import elpa) package-source-url))
(define ensure-list
(@@ (guix import elpa) ensure-list))
(define package-home-page
(@@ (guix import elpa) package-home-page))
(define make-elpa-package
(@@ (guix import elpa) make-elpa-package))
(test-begin "elpa")
(define (eval-test-with-elpa pkg)
(mock
replace the two fetching functions
((guix import elpa) fetch-elpa-package
(lambda* (name #:optional (repo "gnu"))
(let ((pkg (elpa-package-info-mock name repo)))
(match pkg
((name version reqs synopsis kind . rest)
(let* ((name (symbol->string name))
(ver (elpa-version->string version))
(url (package-source-url kind name ver repo)))
(make-elpa-package name ver
(ensure-list reqs) synopsis kind
(package-home-page (first rest))
auctex-readme-mock
url)))
(_ #f)))))
(match (elpa->guix-package pkg)
(('package
('name "emacs-auctex")
('version "11.88.6")
('source
('origin
('method 'url-fetch)
('uri ('string-append
"-" 'version ".tar"))
('sha256 ('base32 (? string? hash)))))
('build-system 'emacs-build-system)
('home-page "/")
('synopsis "Integrated environment for *TeX*")
('description (? string?))
('license 'license:gpl3+))
#t)
(x
(pk 'fail x #f)))))
(test-assert "elpa->guix-package test 1"
(eval-test-with-elpa "auctex"))
(test-end "elpa")
|
09e1ebd09f08a561cef8525dc2d76bccd578196c193df976f03ff817d4e07506 | vikram/lisplibraries | mcl.lisp | (in-package #:bordeaux-threads)
;;; Thread Creation
(defmethod make-thread (function &key name)
(ccl:process-run-function name function))
(defmethod current-thread ()
ccl:*current-thread*)
(defmethod threadp (object)
(ccl:processp object))
(defmethod thread-name (thread)
(ccl:process-name thread))
;;; Resource contention: locks and recursive locks
(defmethod make-lock (&optional name)
(ccl:make-lock name))
(defmacro with-lock-held ((place) &body body)
`(ccl:with-lock-grabbed (,place) ,@body))
(defmethod thread-yield ()
(ccl:process-allow-schedule))
;;; Introspection/debugging
(defmethod all-threadss ()
ccl:*all-processes*)
(defmethod interrupt-thread (thread function)
(ccl:process-interrupt thread function))
(defmethod destroy-thread (thread)
(ccl:process-kill thread))
(mark-supported)
| null | https://raw.githubusercontent.com/vikram/lisplibraries/105e3ef2d165275eb78f36f5090c9e2cdd0754dd/site/ucw-boxset/dependencies/bordeaux-threads/src/mcl.lisp | lisp | Thread Creation
Resource contention: locks and recursive locks
Introspection/debugging | (in-package #:bordeaux-threads)
(defmethod make-thread (function &key name)
(ccl:process-run-function name function))
(defmethod current-thread ()
ccl:*current-thread*)
(defmethod threadp (object)
(ccl:processp object))
(defmethod thread-name (thread)
(ccl:process-name thread))
(defmethod make-lock (&optional name)
(ccl:make-lock name))
(defmacro with-lock-held ((place) &body body)
`(ccl:with-lock-grabbed (,place) ,@body))
(defmethod thread-yield ()
(ccl:process-allow-schedule))
(defmethod all-threadss ()
ccl:*all-processes*)
(defmethod interrupt-thread (thread function)
(ccl:process-interrupt thread function))
(defmethod destroy-thread (thread)
(ccl:process-kill thread))
(mark-supported)
|
e3038e6de3a4913725793f7baf00166fed32c3c3b1a54534c5d9edcea589bfe3 | andorp/bead | Main.hs | module Main (main) where
import qualified SnapMain
main :: IO ()
main = SnapMain.main
| null | https://raw.githubusercontent.com/andorp/bead/280dc9c3d5cfe1b9aac0f2f802c705ae65f02ac2/main/Main.hs | haskell | module Main (main) where
import qualified SnapMain
main :: IO ()
main = SnapMain.main
| |
820e9365864eaa7eba278c80fdd472c50284b165a2f8a85031e589abf7fa7f4e | Abhiroop/okasaki | BinaryHeap.hs | module BinaryHeap(empty, insert, minimum, extractMin) where
import Prelude hiding (minimum)
data BinHeap a = Empty
| Node Bool (BinHeap a) a (BinHeap a)
deriving (Show)
empty :: BinHeap a
empty = Empty
insert :: (Ord a) => a -> BinHeap a -> BinHeap a
insert x Empty = Node True Empty x Empty
insert x (Node True h1 y h2) = Node False (insert (max x y) h1) (min x y) h2
insert x (Node False h1 y h2) = Node True h1 (min x y) (insert (max x y) h2)
minimum :: BinHeap a -> a
minimum (Node _ _ x _) = x
extractMin :: Ord a => BinHeap a -> (a, BinHeap a)
extractMin Empty = error "Cannot extract minimum from an empty heap"
extractMin (Node _ Empty x Empty) = (x, Empty)
extractMin (Node True h1 x h2) =
let (y,h2') = extractMin h2
(z,h1') = siftDown y h1
in (x, Node False h1' z h2')
extractMin (Node False h1 x h2) =
let (y,h1') = extractMin h1
(z,h2') = siftDown y h2
in (x, Node True h1' z h2')
siftDown :: Ord a => a -> BinHeap a -> (a, BinHeap a)
siftDown x Empty = (x, Empty)
siftDown x h@(Node b h1 y h2)
| x > y = (y, downHeap $ Node b h1 x h2)
| otherwise = (x, h)
downHeap :: Ord a => BinHeap a -> BinHeap a
downHeap (Node b h1 x h2) =
if minRoot h1 h2
then let (x',h1') = siftDown x h1
in (Node b h1' x' h2)
else let (x',h2') = siftDown x h2
in (Node b h1 x' h2')
downHeap h = h
minRoot :: Ord a => BinHeap a -> BinHeap a -> Bool
minRoot (Node _ _ x _) (Node _ _ y _) = x <= y
minRoot _ Empty = True
minRoot _ _ = False
| null | https://raw.githubusercontent.com/Abhiroop/okasaki/b4e8b6261cf9c44b7b273116be3da6efde76232d/src/BinaryHeap.hs | haskell | module BinaryHeap(empty, insert, minimum, extractMin) where
import Prelude hiding (minimum)
data BinHeap a = Empty
| Node Bool (BinHeap a) a (BinHeap a)
deriving (Show)
empty :: BinHeap a
empty = Empty
insert :: (Ord a) => a -> BinHeap a -> BinHeap a
insert x Empty = Node True Empty x Empty
insert x (Node True h1 y h2) = Node False (insert (max x y) h1) (min x y) h2
insert x (Node False h1 y h2) = Node True h1 (min x y) (insert (max x y) h2)
minimum :: BinHeap a -> a
minimum (Node _ _ x _) = x
extractMin :: Ord a => BinHeap a -> (a, BinHeap a)
extractMin Empty = error "Cannot extract minimum from an empty heap"
extractMin (Node _ Empty x Empty) = (x, Empty)
extractMin (Node True h1 x h2) =
let (y,h2') = extractMin h2
(z,h1') = siftDown y h1
in (x, Node False h1' z h2')
extractMin (Node False h1 x h2) =
let (y,h1') = extractMin h1
(z,h2') = siftDown y h2
in (x, Node True h1' z h2')
siftDown :: Ord a => a -> BinHeap a -> (a, BinHeap a)
siftDown x Empty = (x, Empty)
siftDown x h@(Node b h1 y h2)
| x > y = (y, downHeap $ Node b h1 x h2)
| otherwise = (x, h)
downHeap :: Ord a => BinHeap a -> BinHeap a
downHeap (Node b h1 x h2) =
if minRoot h1 h2
then let (x',h1') = siftDown x h1
in (Node b h1' x' h2)
else let (x',h2') = siftDown x h2
in (Node b h1 x' h2')
downHeap h = h
minRoot :: Ord a => BinHeap a -> BinHeap a -> Bool
minRoot (Node _ _ x _) (Node _ _ y _) = x <= y
minRoot _ Empty = True
minRoot _ _ = False
| |
fffb83323a0cf4a0922171dc6ecb32b8ab3328d5dfd481ea35927ba9d62bb65d | joneshf/open-source | QuickCheck.hs | # OPTIONS_GHC -fno - warn - orphans #
# LANGUAGE DataKinds #
# LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TypeOperators #
module Rollbar.QuickCheck where
import Data.Bifunctor (bimap)
import Data.CaseInsensitive (mk)
import Data.Proxy (Proxy(Proxy))
import GHC.TypeLits (KnownSymbol, symbolVal)
import Prelude hiding (error)
import Rollbar.Item
import Test.QuickCheck
import Test.QuickCheck.Modifiers (getASCIIString)
import qualified Data.ByteString.Char8 as BSC8
import qualified Data.Text as T
instance Arbitrary a => Arbitrary (Item a '["Authorization"]) where
arbitrary = Item <$> arbitrary <*> arbitrary
instance Arbitrary AccessToken where
arbitrary = AccessToken . T.pack . getASCIIString <$> arbitrary
instance Arbitrary a => Arbitrary (Data a '["Authorization"]) where
arbitrary = do
env <- Environment . T.pack . getASCIIString <$> arbitrary
message <- fmap (MessageBody . T.pack . getASCIIString) <$> arbitrary
payload <- arbitrary
elements $ (\f -> f env message payload) <$> datas
datas :: [Environment -> Maybe MessageBody -> a -> Data a '["Authorization"]]
datas = [debug, info, warning, error, critical]
instance Arbitrary (MissingHeaders '[]) where
arbitrary = do
xs <- arbitrary
let hs = bimap (mk . BSC8.pack) BSC8.pack <$> xs
pure . MissingHeaders $ hs
instance (KnownSymbol header, Arbitrary (MissingHeaders headers))
=> Arbitrary (MissingHeaders (header ': headers)) where
arbitrary = do
MissingHeaders hs <- arbitrary :: Gen (MissingHeaders headers)
let name = mk . BSC8.pack $ symbolVal (Proxy :: Proxy header)
value <- BSC8.pack <$> arbitrary
pure . MissingHeaders $ (name, value) : hs
| null | https://raw.githubusercontent.com/joneshf/open-source/e3412fc68c654d89a8d3af4e12ac19c70e3055ec/packages/rollbar-hs/test/Rollbar/QuickCheck.hs | haskell | # OPTIONS_GHC -fno - warn - orphans #
# LANGUAGE DataKinds #
# LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TypeOperators #
module Rollbar.QuickCheck where
import Data.Bifunctor (bimap)
import Data.CaseInsensitive (mk)
import Data.Proxy (Proxy(Proxy))
import GHC.TypeLits (KnownSymbol, symbolVal)
import Prelude hiding (error)
import Rollbar.Item
import Test.QuickCheck
import Test.QuickCheck.Modifiers (getASCIIString)
import qualified Data.ByteString.Char8 as BSC8
import qualified Data.Text as T
instance Arbitrary a => Arbitrary (Item a '["Authorization"]) where
arbitrary = Item <$> arbitrary <*> arbitrary
instance Arbitrary AccessToken where
arbitrary = AccessToken . T.pack . getASCIIString <$> arbitrary
instance Arbitrary a => Arbitrary (Data a '["Authorization"]) where
arbitrary = do
env <- Environment . T.pack . getASCIIString <$> arbitrary
message <- fmap (MessageBody . T.pack . getASCIIString) <$> arbitrary
payload <- arbitrary
elements $ (\f -> f env message payload) <$> datas
datas :: [Environment -> Maybe MessageBody -> a -> Data a '["Authorization"]]
datas = [debug, info, warning, error, critical]
instance Arbitrary (MissingHeaders '[]) where
arbitrary = do
xs <- arbitrary
let hs = bimap (mk . BSC8.pack) BSC8.pack <$> xs
pure . MissingHeaders $ hs
instance (KnownSymbol header, Arbitrary (MissingHeaders headers))
=> Arbitrary (MissingHeaders (header ': headers)) where
arbitrary = do
MissingHeaders hs <- arbitrary :: Gen (MissingHeaders headers)
let name = mk . BSC8.pack $ symbolVal (Proxy :: Proxy header)
value <- BSC8.pack <$> arbitrary
pure . MissingHeaders $ (name, value) : hs
| |
c36b04f7e4f840b92a11622fdb3d7280b665e044aefc1494fe4de461062dd91f | soren-n/bidi-higher-rank-poly | Main.ml | open Typeset
open Util
open Extra
open Back
open Front
let print layout =
Typeset.compile layout @@ fun doc ->
Typeset.render doc 2 80 @@ fun msg ->
print_endline msg
let error msg =
print (seq (~$"🔥 Error:" <+> grp msg) </> null)
let success value poly =
let ctx = Naming.make_ctx () in
Check.generalize poly @@ fun poly1 ->
Value.print_value value @@ fun value1 ->
Print.layout_poly ctx poly1 @@ fun poly2 ->
print (~$value1 <+> ~$":" <+> poly2 </> null)
let report_context tctx =
let ctx = Naming.make_ctx () in
Context.get_venv tctx @@ fun venv ->
Env.fold
(fun return -> return ~$"")
(fun name poly visit_env return ->
Print.layout_poly ctx poly @@ fun poly1 ->
visit_env @@ fun binds ->
return (~$name <+> ~$":" <+> poly1 </> binds))
venv print
let parse parser tokens =
try
let result = parser Lexer.token tokens in
Result.make_value result
with
| Lexer.Error msg ->
Result.make_error (~$"Lexing error:" <+> ~$msg)
| Parser.Error ->
Result.make_error ~$"Parsing error"
let parse_file path =
try
let file_in = open_in path in
let tokens = Lexing.from_channel file_in in
let result = parse Parser.file tokens in
close_in file_in;
result
with Sys_error msg ->
Result.make_error ~$msg
let parse_input input =
parse Parser.input (Lexing.from_string input)
let options = []
let files = ref []
let anonymous path =
files := path :: !files
let interp_input tctx env input =
match parse_input input with
| Result.Error msg -> error msg
| Result.Value stmt ->
Valid.check_stmt stmt tctx error @@ fun () ->
Check.synth_stmt stmt tctx error @@ fun result_t ->
Interp.eval_stmt stmt env @@ fun result_v ->
success result_v result_t
let interp_file tctx env path =
match parse_file path with
| Result.Error msg -> error msg; exit 1
| Result.Value prog ->
Valid.check_prog prog tctx error @@ fun () ->
Check.check_prog prog tctx error @@ fun tctx1 ->
Interp.eval_prog prog env @@ fun () ->
report_context tctx1
let interp_files tctx env paths =
List.iter (interp_file tctx env) paths;
exit 0
let read_input () =
let _complete input =
let length = String.length input in
if length < 2 then false else
if input.[length - 1] <> ';' then false else
if input.[length - 2] <> ';' then false else
true
in
let prompt = "▶ " in
let prompt_more = "⋮ " in
print_string prompt;
let input = ref (read_line ()) in
while not (_complete !input) do
print_string prompt_more;
input := !input ^ (read_line ())
done;
let result = !input in
String.sub result 0 (String.length result - 2)
let repl tctx env =
while true do
let input = read_input () in
if input = "exit" then exit 0 else
if input = "context" then report_context tctx else
interp_input tctx env input
done
let usage =
"Usage: BHRP [file] ..."
let () =
Sys.catch_break true;
Arg.parse options anonymous usage;
let _files = !files in
if (List.length _files) <> 0
then interp_files Native.tenv Native.venv !files
else repl Native.tenv Native.venv
| null | https://raw.githubusercontent.com/soren-n/bidi-higher-rank-poly/ef5625c4c4b2d5aea83c0a89cfca336e517d74e4/repl/bin/Main.ml | ocaml | open Typeset
open Util
open Extra
open Back
open Front
let print layout =
Typeset.compile layout @@ fun doc ->
Typeset.render doc 2 80 @@ fun msg ->
print_endline msg
let error msg =
print (seq (~$"🔥 Error:" <+> grp msg) </> null)
let success value poly =
let ctx = Naming.make_ctx () in
Check.generalize poly @@ fun poly1 ->
Value.print_value value @@ fun value1 ->
Print.layout_poly ctx poly1 @@ fun poly2 ->
print (~$value1 <+> ~$":" <+> poly2 </> null)
let report_context tctx =
let ctx = Naming.make_ctx () in
Context.get_venv tctx @@ fun venv ->
Env.fold
(fun return -> return ~$"")
(fun name poly visit_env return ->
Print.layout_poly ctx poly @@ fun poly1 ->
visit_env @@ fun binds ->
return (~$name <+> ~$":" <+> poly1 </> binds))
venv print
let parse parser tokens =
try
let result = parser Lexer.token tokens in
Result.make_value result
with
| Lexer.Error msg ->
Result.make_error (~$"Lexing error:" <+> ~$msg)
| Parser.Error ->
Result.make_error ~$"Parsing error"
let parse_file path =
try
let file_in = open_in path in
let tokens = Lexing.from_channel file_in in
let result = parse Parser.file tokens in
close_in file_in;
result
with Sys_error msg ->
Result.make_error ~$msg
let parse_input input =
parse Parser.input (Lexing.from_string input)
let options = []
let files = ref []
let anonymous path =
files := path :: !files
let interp_input tctx env input =
match parse_input input with
| Result.Error msg -> error msg
| Result.Value stmt ->
Valid.check_stmt stmt tctx error @@ fun () ->
Check.synth_stmt stmt tctx error @@ fun result_t ->
Interp.eval_stmt stmt env @@ fun result_v ->
success result_v result_t
let interp_file tctx env path =
match parse_file path with
| Result.Error msg -> error msg; exit 1
| Result.Value prog ->
Valid.check_prog prog tctx error @@ fun () ->
Check.check_prog prog tctx error @@ fun tctx1 ->
Interp.eval_prog prog env @@ fun () ->
report_context tctx1
let interp_files tctx env paths =
List.iter (interp_file tctx env) paths;
exit 0
let read_input () =
let _complete input =
let length = String.length input in
if length < 2 then false else
if input.[length - 1] <> ';' then false else
if input.[length - 2] <> ';' then false else
true
in
let prompt = "▶ " in
let prompt_more = "⋮ " in
print_string prompt;
let input = ref (read_line ()) in
while not (_complete !input) do
print_string prompt_more;
input := !input ^ (read_line ())
done;
let result = !input in
String.sub result 0 (String.length result - 2)
let repl tctx env =
while true do
let input = read_input () in
if input = "exit" then exit 0 else
if input = "context" then report_context tctx else
interp_input tctx env input
done
let usage =
"Usage: BHRP [file] ..."
let () =
Sys.catch_break true;
Arg.parse options anonymous usage;
let _files = !files in
if (List.length _files) <> 0
then interp_files Native.tenv Native.venv !files
else repl Native.tenv Native.venv
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.