_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 |
|---|---|---|---|---|---|---|---|---|
c7ff6850884240c2a06a9c533a4cc837e6eb5b2f883950b3c9bcd3e0b16c1906 | aliter/aliter | packets.erl | -module(packets, [PacketVer]).
-export([packet_size/1]).
mod_for(Version) ->
list_to_atom(lists:concat(["packets_", Version])).
packet_size(Header) ->
(mod_for(PacketVer)):packet_size(Header).
| null | https://raw.githubusercontent.com/aliter/aliter/03c7d395d5812887aecdca20b16369f8a8abd278/src/packets.erl | erlang | -module(packets, [PacketVer]).
-export([packet_size/1]).
mod_for(Version) ->
list_to_atom(lists:concat(["packets_", Version])).
packet_size(Header) ->
(mod_for(PacketVer)):packet_size(Header).
| |
87890a18ff0c657a598967c6df8b024988583232a2bdd0bbc147dd8f304f2948 | haskell-suite/haskell-names | Rec3.hs | module Rec3 (rec1_1, rec1_2, rec3) where
import Rec2
import Rec1 (rec1_2)
rec3 = rec3
| null | https://raw.githubusercontent.com/haskell-suite/haskell-names/795d717541484dbe456342a510ac8e712e1f16e4/tests/exports/Rec3.hs | haskell | module Rec3 (rec1_1, rec1_2, rec3) where
import Rec2
import Rec1 (rec1_2)
rec3 = rec3
| |
0d4c56bd05a649198393a37529aa6cd4c7ab65ce597e7c425926e11a079c1e63 | sbcl/sbcl | target-insts.lisp | This file is for stuff which was in CMU CL 's insts.lisp
file , but which in the SBCL build process ca n't be compiled
;;;; into code for the cross-compilation host.
This software is part of the SBCL system . See the README file for
;;;; more information.
;;;;
This software is derived from the CMU CL system , which was
written at Carnegie Mellon University and released into the
;;;; public domain. The software is in the public domain and is
;;;; provided with absolutely no warranty. See the COPYING and CREDITS
;;;; files for more information.
(in-package "SB-SPARC-ASM")
(defun sethi-arg-printer (value stream dstate)
(format stream "%hi(#x~8,'0x)" (ash value 10))
;; Save the immediate value and the destination register from this
;; sethi instruction. This is used later to print some possible
;; notes about the value loaded by sethi.
(let* ((word (sap-ref-int (dstate-segment-sap dstate)
(dstate-cur-offs dstate) n-word-bytes
(dstate-byte-order dstate)))
(imm22 (ldb (byte 22 0) word))
(rd (ldb (byte 5 25) word)))
(push (cons rd imm22) *note-sethi-inst*)))
;; Look at the current instruction and see if we can't add some notes
;; about what's happening.
(defun maybe-add-notes (reg dstate)
;; FIXME: these accessors should all be defined using the :READER option
;; of DEFINE-INSTRUCTION-FORMAT.
(let* ((word (sap-ref-int (dstate-segment-sap dstate)
(dstate-cur-offs dstate) n-word-bytes
(dstate-byte-order dstate)))
(format (ldb (byte 2 30) word))
(op3 (ldb (byte 6 19) word))
(rs1 (ldb (byte 5 14) word))
(rd (ldb (byte 5 25) word))
(immed-p (not (zerop (ldb (byte 1 13) word))))
(immed-val (sign-extend-immed-value (ldb (byte 13 0) word))))
(declare (ignore immed-p))
;; Only the value of format and rd are guaranteed to be correct
;; because the disassembler is trying to print out the value of a
;; register. The other values may not be right.
(case format
(2
(case op3
(#b000000
(when (= reg rs1)
(handle-add-inst rs1 immed-val rd dstate)))
(#b111000
(when (= reg rs1)
(handle-jmpl-inst rs1 immed-val rd dstate)))
(#b010001
(when (= reg rs1)
(handle-andcc-inst rs1 immed-val rd dstate)))))
(3
(case op3
((#b000000 #b000100)
(when (= reg rs1)
(handle-ld/st-inst rs1 immed-val rd dstate))))))
If this is not a SETHI instruction , and RD is the same as some
register used by SETHI , we delete the entry . ( In case we have
a SETHI without any additional instruction because the low bits
were zero . )
(unless (and (zerop format) (= #b100 (ldb (byte 3 22) word)))
(let ((sethi (assoc rd *note-sethi-inst*)))
(when sethi
(setf *note-sethi-inst* (delete sethi *note-sethi-inst*)))))))
(defun handle-add-inst (rs1 immed-val rd dstate)
(let* ((sethi (assoc rs1 *note-sethi-inst*)))
(cond
(sethi
RS1 was used in a SETHI instruction . Assume that
this is the offset part of the SETHI instruction for
a full 32 - bit address of something . Make a note
;; about this usage as a Lisp assembly routine or
;; foreign routine, if possible. If not, just note the
;; final value.
(let ((addr (+ immed-val (ash (cdr sethi) 10))))
(or (note-code-constant addr dstate :absolute)
(maybe-note-assembler-routine addr t dstate)
(note (format nil "~A = #x~8,'0X" (get-reg-name rd) addr) dstate)))
(setf *note-sethi-inst* (delete sethi *note-sethi-inst*)))
((= rs1 null-offset)
We have an ADD % NULL , < n > , RD instruction . This is a
;; reference to a static symbol.
(maybe-note-nil-indexed-object immed-val dstate))
#+nil ((and (= rs1 zero-offset) *pseudo-atomic-set*)
" ADD % ZERO , num , RD " inside a pseudo - atomic is very
;; likely loading up a header word. Make a note to that
;; effect.
(let ((type (second (assoc (logand immed-val #xff) header-word-type-alist)))
(size (ldb (byte 24 8) immed-val)))
(when type
(note (format nil "Header word ~A, size ~D?" type size) dstate)))))))
(defun handle-jmpl-inst (rs1 immed-val rd dstate)
(declare (ignore rd))
(let* ((sethi (assoc rs1 *note-sethi-inst*)))
(when sethi
RS1 was used in a SETHI instruction . Assume that
this is the offset part of the SETHI instruction for
a full 32 - bit address of something . Make a note
;; about this usage as a Lisp assembly routine or
;; foreign routine, if possible. If not, just note the
;; final value.
(let ((addr (+ immed-val (ash (cdr sethi) 10))))
(maybe-note-assembler-routine addr t dstate)
(setf *note-sethi-inst* (delete sethi *note-sethi-inst*))))))
(defun handle-ld/st-inst (rs1 immed-val rd dstate)
(declare (ignore rd))
Got an LDUW / LD or STW instruction , with immediate offset .
(case rs1
(29
;; A reference to a code constant (reg = %CODE)
(note-code-constant immed-val dstate))
(2
;; A reference to a static symbol or static function (reg =
;; %NULL)
(or (maybe-note-nil-indexed-symbol-slot-ref immed-val dstate)
#+nil (sb-disassem::maybe-note-static-function immed-val dstate)))
(t
(let ((sethi (assoc rs1 *note-sethi-inst*)))
(when sethi
(let ((addr (+ immed-val (ash (cdr sethi) 10))))
(maybe-note-assembler-routine addr nil dstate)
(setf *note-sethi-inst* (delete sethi *note-sethi-inst*))))))))
(defun handle-andcc-inst (rs1 immed-val rd dstate)
(declare (ignorable rs1 immed-val rd dstate))
ANDCC % ALLOC , 3 , % ZERO instruction
(when nil
(note "pseudo-atomic interrupted?" dstate)))
(defun unimp-control (chunk inst stream dstate)
(declare (ignore inst))
(flet ((nt (x) (if stream (note x dstate))))
(let ((trap (format-2-unimp-data chunk dstate)))
(case trap
(#.breakpoint-trap
(nt "Breakpoint trap"))
(#.pending-interrupt-trap
(nt "Pending interrupt trap"))
(#.halt-trap
(nt "Halt trap"))
(#.fun-end-breakpoint-trap
(nt "Function end breakpoint trap"))
(t
(when (or (and (= trap cerror-trap) (progn (nt "cerror trap") t))
(>= trap error-trap))
(handle-break-args #'snarf-error-junk trap stream dstate)))))))
| null | https://raw.githubusercontent.com/sbcl/sbcl/1a983ef5865d083a32ee3f67b02bbcf15d041b48/src/compiler/sparc/target-insts.lisp | lisp | into code for the cross-compilation host.
more information.
public domain. The software is in the public domain and is
provided with absolutely no warranty. See the COPYING and CREDITS
files for more information.
Save the immediate value and the destination register from this
sethi instruction. This is used later to print some possible
notes about the value loaded by sethi.
Look at the current instruction and see if we can't add some notes
about what's happening.
FIXME: these accessors should all be defined using the :READER option
of DEFINE-INSTRUCTION-FORMAT.
Only the value of format and rd are guaranteed to be correct
because the disassembler is trying to print out the value of a
register. The other values may not be right.
about this usage as a Lisp assembly routine or
foreign routine, if possible. If not, just note the
final value.
reference to a static symbol.
likely loading up a header word. Make a note to that
effect.
about this usage as a Lisp assembly routine or
foreign routine, if possible. If not, just note the
final value.
A reference to a code constant (reg = %CODE)
A reference to a static symbol or static function (reg =
%NULL) | This file is for stuff which was in CMU CL 's insts.lisp
file , but which in the SBCL build process ca n't be compiled
This software is part of the SBCL system . See the README file for
This software is derived from the CMU CL system , which was
written at Carnegie Mellon University and released into the
(in-package "SB-SPARC-ASM")
(defun sethi-arg-printer (value stream dstate)
(format stream "%hi(#x~8,'0x)" (ash value 10))
(let* ((word (sap-ref-int (dstate-segment-sap dstate)
(dstate-cur-offs dstate) n-word-bytes
(dstate-byte-order dstate)))
(imm22 (ldb (byte 22 0) word))
(rd (ldb (byte 5 25) word)))
(push (cons rd imm22) *note-sethi-inst*)))
(defun maybe-add-notes (reg dstate)
(let* ((word (sap-ref-int (dstate-segment-sap dstate)
(dstate-cur-offs dstate) n-word-bytes
(dstate-byte-order dstate)))
(format (ldb (byte 2 30) word))
(op3 (ldb (byte 6 19) word))
(rs1 (ldb (byte 5 14) word))
(rd (ldb (byte 5 25) word))
(immed-p (not (zerop (ldb (byte 1 13) word))))
(immed-val (sign-extend-immed-value (ldb (byte 13 0) word))))
(declare (ignore immed-p))
(case format
(2
(case op3
(#b000000
(when (= reg rs1)
(handle-add-inst rs1 immed-val rd dstate)))
(#b111000
(when (= reg rs1)
(handle-jmpl-inst rs1 immed-val rd dstate)))
(#b010001
(when (= reg rs1)
(handle-andcc-inst rs1 immed-val rd dstate)))))
(3
(case op3
((#b000000 #b000100)
(when (= reg rs1)
(handle-ld/st-inst rs1 immed-val rd dstate))))))
If this is not a SETHI instruction , and RD is the same as some
register used by SETHI , we delete the entry . ( In case we have
a SETHI without any additional instruction because the low bits
were zero . )
(unless (and (zerop format) (= #b100 (ldb (byte 3 22) word)))
(let ((sethi (assoc rd *note-sethi-inst*)))
(when sethi
(setf *note-sethi-inst* (delete sethi *note-sethi-inst*)))))))
(defun handle-add-inst (rs1 immed-val rd dstate)
(let* ((sethi (assoc rs1 *note-sethi-inst*)))
(cond
(sethi
RS1 was used in a SETHI instruction . Assume that
this is the offset part of the SETHI instruction for
a full 32 - bit address of something . Make a note
(let ((addr (+ immed-val (ash (cdr sethi) 10))))
(or (note-code-constant addr dstate :absolute)
(maybe-note-assembler-routine addr t dstate)
(note (format nil "~A = #x~8,'0X" (get-reg-name rd) addr) dstate)))
(setf *note-sethi-inst* (delete sethi *note-sethi-inst*)))
((= rs1 null-offset)
We have an ADD % NULL , < n > , RD instruction . This is a
(maybe-note-nil-indexed-object immed-val dstate))
#+nil ((and (= rs1 zero-offset) *pseudo-atomic-set*)
" ADD % ZERO , num , RD " inside a pseudo - atomic is very
(let ((type (second (assoc (logand immed-val #xff) header-word-type-alist)))
(size (ldb (byte 24 8) immed-val)))
(when type
(note (format nil "Header word ~A, size ~D?" type size) dstate)))))))
(defun handle-jmpl-inst (rs1 immed-val rd dstate)
(declare (ignore rd))
(let* ((sethi (assoc rs1 *note-sethi-inst*)))
(when sethi
RS1 was used in a SETHI instruction . Assume that
this is the offset part of the SETHI instruction for
a full 32 - bit address of something . Make a note
(let ((addr (+ immed-val (ash (cdr sethi) 10))))
(maybe-note-assembler-routine addr t dstate)
(setf *note-sethi-inst* (delete sethi *note-sethi-inst*))))))
(defun handle-ld/st-inst (rs1 immed-val rd dstate)
(declare (ignore rd))
Got an LDUW / LD or STW instruction , with immediate offset .
(case rs1
(29
(note-code-constant immed-val dstate))
(2
(or (maybe-note-nil-indexed-symbol-slot-ref immed-val dstate)
#+nil (sb-disassem::maybe-note-static-function immed-val dstate)))
(t
(let ((sethi (assoc rs1 *note-sethi-inst*)))
(when sethi
(let ((addr (+ immed-val (ash (cdr sethi) 10))))
(maybe-note-assembler-routine addr nil dstate)
(setf *note-sethi-inst* (delete sethi *note-sethi-inst*))))))))
(defun handle-andcc-inst (rs1 immed-val rd dstate)
(declare (ignorable rs1 immed-val rd dstate))
ANDCC % ALLOC , 3 , % ZERO instruction
(when nil
(note "pseudo-atomic interrupted?" dstate)))
(defun unimp-control (chunk inst stream dstate)
(declare (ignore inst))
(flet ((nt (x) (if stream (note x dstate))))
(let ((trap (format-2-unimp-data chunk dstate)))
(case trap
(#.breakpoint-trap
(nt "Breakpoint trap"))
(#.pending-interrupt-trap
(nt "Pending interrupt trap"))
(#.halt-trap
(nt "Halt trap"))
(#.fun-end-breakpoint-trap
(nt "Function end breakpoint trap"))
(t
(when (or (and (= trap cerror-trap) (progn (nt "cerror trap") t))
(>= trap error-trap))
(handle-break-args #'snarf-error-junk trap stream dstate)))))))
|
53a2d9f609d3d759be3fea51a386f14eccc3d13c8752e61e9c08baf0b3cdcd79 | elastic/eui-cljs | sort_direction.cljs | (ns eui.services.sort-direction
(:require ["@elastic/eui/lib/services/sort/sort_direction.js" :as eui]))
(def SortDirection eui/SortDirection)
(def SortDirectionType eui/SortDirectionType)
| null | https://raw.githubusercontent.com/elastic/eui-cljs/ad60b57470a2eb8db9bca050e02f52dd964d9f8e/src/eui/services/sort_direction.cljs | clojure | (ns eui.services.sort-direction
(:require ["@elastic/eui/lib/services/sort/sort_direction.js" :as eui]))
(def SortDirection eui/SortDirection)
(def SortDirectionType eui/SortDirectionType)
| |
1e282b0addc4bd04ffe2ea1e8e324d9a68824621ae6bd4c8dc60aba388bb5b2f | rcherrueau/APE | let_4.rkt | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
Writing Hygienic Macros in Scheme with Syntax - case
Technical Report # 356
;;
page 10
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
#lang racket
(require "print-test.rkt")
; `all-ids' fender reject input expression that do not have
; identifiers where they are expected.
(define-syntax (let_4 x)
(define (all-ids? lst)
(define (id? an-id previous-id-res)
(and (identifier? an-id) previous-id-res))
(foldl id? #t (syntax->list lst)))
(syntax-case x ()
[(_ ([i v] ...) e1 e2 ...)
(all-ids? #'(i ...))
#'((lambda (i ...) e1 e2 ...) v ...)]
[(_ name ([i v] ...) e1 e2 ...)
(all-ids? #'(i ...))
#'((letrec ((name (lambda (i ...) e1 e2 ...))) name)
v ...)]))
(print-test (let_4 ([v1 '1]
[v2 '3]
[v3 '3]
[v4 '7])
(format "~s~s~s~s" v1 v2 v3 v4))
(let_4 fac ([n 10])
(if (zero? n)
1
(* n (fac (sub1 n)))))
; "v1" as identifier will report a bad syntax error.
(let_4 (["v1" '1])
(format "~s" v1)))
| null | https://raw.githubusercontent.com/rcherrueau/APE/8b5302709000bd043b64d46d55642acb34ce5ba7/racket/hygienic_macros/let_4.rkt | racket |
`all-ids' fender reject input expression that do not have
identifiers where they are expected.
"v1" as identifier will report a bad syntax error. | Writing Hygienic Macros in Scheme with Syntax - case
Technical Report # 356
page 10
#lang racket
(require "print-test.rkt")
(define-syntax (let_4 x)
(define (all-ids? lst)
(define (id? an-id previous-id-res)
(and (identifier? an-id) previous-id-res))
(foldl id? #t (syntax->list lst)))
(syntax-case x ()
[(_ ([i v] ...) e1 e2 ...)
(all-ids? #'(i ...))
#'((lambda (i ...) e1 e2 ...) v ...)]
[(_ name ([i v] ...) e1 e2 ...)
(all-ids? #'(i ...))
#'((letrec ((name (lambda (i ...) e1 e2 ...))) name)
v ...)]))
(print-test (let_4 ([v1 '1]
[v2 '3]
[v3 '3]
[v4 '7])
(format "~s~s~s~s" v1 v2 v3 v4))
(let_4 fac ([n 10])
(if (zero? n)
1
(* n (fac (sub1 n)))))
(let_4 (["v1" '1])
(format "~s" v1)))
|
0545f9fd722a2b400ee007aea1cdf9f08490c8e35f8066fb51667316e3bd4e2a | portkey-cloud/aws-clj-sdk | secretsmanager.clj | (ns portkey.aws.secretsmanager (:require [portkey.aws]))
(def
endpoints
'{"ap-northeast-1"
{:credential-scope
{:service "secretsmanager", :region "ap-northeast-1"},
:ssl-common-name "secretsmanager.ap-northeast-1.amazonaws.com",
:endpoint "-northeast-1.amazonaws.com",
:signature-version :v4},
"eu-west-1"
{:credential-scope {:service "secretsmanager", :region "eu-west-1"},
:ssl-common-name "secretsmanager.eu-west-1.amazonaws.com",
:endpoint "-west-1.amazonaws.com",
:signature-version :v4},
"us-east-2"
{:credential-scope {:service "secretsmanager", :region "us-east-2"},
:ssl-common-name "secretsmanager.us-east-2.amazonaws.com",
:endpoint "-east-2.amazonaws.com",
:signature-version :v4},
"ap-southeast-2"
{:credential-scope
{:service "secretsmanager", :region "ap-southeast-2"},
:ssl-common-name "secretsmanager.ap-southeast-2.amazonaws.com",
:endpoint "-southeast-2.amazonaws.com",
:signature-version :v4},
"sa-east-1"
{:credential-scope {:service "secretsmanager", :region "sa-east-1"},
:ssl-common-name "secretsmanager.sa-east-1.amazonaws.com",
:endpoint "-east-1.amazonaws.com",
:signature-version :v4},
"ap-southeast-1"
{:credential-scope
{:service "secretsmanager", :region "ap-southeast-1"},
:ssl-common-name "secretsmanager.ap-southeast-1.amazonaws.com",
:endpoint "-southeast-1.amazonaws.com",
:signature-version :v4},
"ap-northeast-2"
{:credential-scope
{:service "secretsmanager", :region "ap-northeast-2"},
:ssl-common-name "secretsmanager.ap-northeast-2.amazonaws.com",
:endpoint "-northeast-2.amazonaws.com",
:signature-version :v4},
"ca-central-1"
{:credential-scope
{:service "secretsmanager", :region "ca-central-1"},
:ssl-common-name "secretsmanager.ca-central-1.amazonaws.com",
:endpoint "-central-1.amazonaws.com",
:signature-version :v4},
"eu-central-1"
{:credential-scope
{:service "secretsmanager", :region "eu-central-1"},
:ssl-common-name "secretsmanager.eu-central-1.amazonaws.com",
:endpoint "-central-1.amazonaws.com",
:signature-version :v4},
"eu-west-2"
{:credential-scope {:service "secretsmanager", :region "eu-west-2"},
:ssl-common-name "secretsmanager.eu-west-2.amazonaws.com",
:endpoint "-west-2.amazonaws.com",
:signature-version :v4},
"us-west-2"
{:credential-scope {:service "secretsmanager", :region "us-west-2"},
:ssl-common-name "secretsmanager.us-west-2.amazonaws.com",
:endpoint "-west-2.amazonaws.com",
:signature-version :v4},
"us-east-1"
{:credential-scope {:service "secretsmanager", :region "us-east-1"},
:ssl-common-name "secretsmanager.us-east-1.amazonaws.com",
:endpoint "-east-1.amazonaws.com",
:signature-version :v4},
"us-west-1"
{:credential-scope {:service "secretsmanager", :region "us-west-1"},
:ssl-common-name "secretsmanager.us-west-1.amazonaws.com",
:endpoint "-west-1.amazonaws.com",
:signature-version :v4},
"ap-south-1"
{:credential-scope
{:service "secretsmanager", :region "ap-south-1"},
:ssl-common-name "secretsmanager.ap-south-1.amazonaws.com",
:endpoint "-south-1.amazonaws.com",
:signature-version :v4}})
(comment TODO support "json")
| null | https://raw.githubusercontent.com/portkey-cloud/aws-clj-sdk/10623a5c86bd56c8b312f56b76ae5ff52c26a945/src/portkey/aws/secretsmanager.clj | clojure | (ns portkey.aws.secretsmanager (:require [portkey.aws]))
(def
endpoints
'{"ap-northeast-1"
{:credential-scope
{:service "secretsmanager", :region "ap-northeast-1"},
:ssl-common-name "secretsmanager.ap-northeast-1.amazonaws.com",
:endpoint "-northeast-1.amazonaws.com",
:signature-version :v4},
"eu-west-1"
{:credential-scope {:service "secretsmanager", :region "eu-west-1"},
:ssl-common-name "secretsmanager.eu-west-1.amazonaws.com",
:endpoint "-west-1.amazonaws.com",
:signature-version :v4},
"us-east-2"
{:credential-scope {:service "secretsmanager", :region "us-east-2"},
:ssl-common-name "secretsmanager.us-east-2.amazonaws.com",
:endpoint "-east-2.amazonaws.com",
:signature-version :v4},
"ap-southeast-2"
{:credential-scope
{:service "secretsmanager", :region "ap-southeast-2"},
:ssl-common-name "secretsmanager.ap-southeast-2.amazonaws.com",
:endpoint "-southeast-2.amazonaws.com",
:signature-version :v4},
"sa-east-1"
{:credential-scope {:service "secretsmanager", :region "sa-east-1"},
:ssl-common-name "secretsmanager.sa-east-1.amazonaws.com",
:endpoint "-east-1.amazonaws.com",
:signature-version :v4},
"ap-southeast-1"
{:credential-scope
{:service "secretsmanager", :region "ap-southeast-1"},
:ssl-common-name "secretsmanager.ap-southeast-1.amazonaws.com",
:endpoint "-southeast-1.amazonaws.com",
:signature-version :v4},
"ap-northeast-2"
{:credential-scope
{:service "secretsmanager", :region "ap-northeast-2"},
:ssl-common-name "secretsmanager.ap-northeast-2.amazonaws.com",
:endpoint "-northeast-2.amazonaws.com",
:signature-version :v4},
"ca-central-1"
{:credential-scope
{:service "secretsmanager", :region "ca-central-1"},
:ssl-common-name "secretsmanager.ca-central-1.amazonaws.com",
:endpoint "-central-1.amazonaws.com",
:signature-version :v4},
"eu-central-1"
{:credential-scope
{:service "secretsmanager", :region "eu-central-1"},
:ssl-common-name "secretsmanager.eu-central-1.amazonaws.com",
:endpoint "-central-1.amazonaws.com",
:signature-version :v4},
"eu-west-2"
{:credential-scope {:service "secretsmanager", :region "eu-west-2"},
:ssl-common-name "secretsmanager.eu-west-2.amazonaws.com",
:endpoint "-west-2.amazonaws.com",
:signature-version :v4},
"us-west-2"
{:credential-scope {:service "secretsmanager", :region "us-west-2"},
:ssl-common-name "secretsmanager.us-west-2.amazonaws.com",
:endpoint "-west-2.amazonaws.com",
:signature-version :v4},
"us-east-1"
{:credential-scope {:service "secretsmanager", :region "us-east-1"},
:ssl-common-name "secretsmanager.us-east-1.amazonaws.com",
:endpoint "-east-1.amazonaws.com",
:signature-version :v4},
"us-west-1"
{:credential-scope {:service "secretsmanager", :region "us-west-1"},
:ssl-common-name "secretsmanager.us-west-1.amazonaws.com",
:endpoint "-west-1.amazonaws.com",
:signature-version :v4},
"ap-south-1"
{:credential-scope
{:service "secretsmanager", :region "ap-south-1"},
:ssl-common-name "secretsmanager.ap-south-1.amazonaws.com",
:endpoint "-south-1.amazonaws.com",
:signature-version :v4}})
(comment TODO support "json")
| |
a9a9e93c9318b77717cabffb119fa58f2a86661ca8a4da610549ca5ee72d114a | rukor/cljs-ssr-node | state.cljs | (ns com.firstlinq.ssr.state
(:require [cognitect.transit :as t]))
(defmulti get-state (fn [state route-id route-params opts] route-id))
(defprotocol Serialiser
(->string [_ state])
(->state [_ string]))
(defn transit-serialiser []
(reify Serialiser
(->string [_ state]
(let [w (t/writer :json)]
(t/write w state)))
(->state [_ string]
(let [r (t/reader :json)]
(t/read r string)))))
(defn hydrate [serialiser state-atom el]
(when (empty? @state-atom)
(->> (.-textContent el)
(->state serialiser)
(reset! state-atom)))) | null | https://raw.githubusercontent.com/rukor/cljs-ssr-node/6115f18ca66b9595a87c0e880ebdfce25042c612/src/com/firstlinq/ssr/state.cljs | clojure | (ns com.firstlinq.ssr.state
(:require [cognitect.transit :as t]))
(defmulti get-state (fn [state route-id route-params opts] route-id))
(defprotocol Serialiser
(->string [_ state])
(->state [_ string]))
(defn transit-serialiser []
(reify Serialiser
(->string [_ state]
(let [w (t/writer :json)]
(t/write w state)))
(->state [_ string]
(let [r (t/reader :json)]
(t/read r string)))))
(defn hydrate [serialiser state-atom el]
(when (empty? @state-atom)
(->> (.-textContent el)
(->state serialiser)
(reset! state-atom)))) | |
640048e475e47ae73fc3d3ee7ef5e1c0a11308c4486abf32ee1b16f465bd206d | IFCA/opencl | Setup.hs | Copyright ( c ) 2011 ,
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 nor the names of other
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
OWNER OR 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 .
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 nor the names of other
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
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-}
import Distribution.Simple
main = defaultMain
| null | https://raw.githubusercontent.com/IFCA/opencl/80d0cb9d235819cd53e6a36d7a9258bc19d564ab/Setup.hs | haskell | Copyright ( c ) 2011 ,
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 nor the names of other
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
OWNER OR 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 .
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 nor the names of other
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
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-}
import Distribution.Simple
main = defaultMain
| |
9137d9d504e3761dbb15e77b510026eb484b41e3b9dd9ac1b0e80b7ddc1efc5e | oasis-open/openc2-lycan-beam | a_simple_post_SUITE.erl | @author
( C ) 2018 , sFractal Consulting LLC
%%%
-module(a_simple_post_SUITE).
-author("Duncan Sparrell").
-license("MIT").
-copyright("2018, Duncan Sparrell sFractal Consulting LLC").
%%%-------------------------------------------------------------------
Copyright ( c ) 2018 , , sFractal Consulting
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 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.
%%%-------------------------------------------------------------------
%% for test export all functions
-export( [ all/0
, suite/0
, init_per_suite/1
, end_per_suite/1
, test_bad_method/1
, test_post_missing_body/1
, test_unsupported_media_type/1
, test_bad_json/1
, test_bad_action/1
, test_missing_action/1
, test_missing_target/1
, test_post/1
]).
%% required for common_test to work
-include_lib("common_test/include/ct.hrl").
%% tests to run
all() ->
[ test_bad_method
, test_post_missing_body
, test_unsupported_media_type
, test_bad_json
, test_missing_action
, test_post
, test_bad_action
, test_missing_target
].
timeout if no reply in a minute
suite() ->
[{timetrap, {minutes, 2}}].
%% setup config parameters
init_per_suite(Config) ->
{ok, _AppList} = application:ensure_all_started(lager),
%%lager:info("AppList: ~p~n", [AppList]),
{ok, _AppList2} = application:ensure_all_started(gun),
%%lager:info("AppList2: ~p~n", [AppList2]),
%% since ct doesn't read sys.config, set configs here
application:set_env(slpfhw, port, 8080),
application:set_env(slpfhw, listener_count, 5),
%% start application
{ok, _AppList3} = application:ensure_all_started(slpfhw),
%%lager:info("AppList3: ~p~n", [AppList3]),
lager_common_test_backend:bounce(debug),
Config.
end_per_suite(Config) ->
Config.
test_post(Config) ->
test json file with query profile
JsonSendFileName = "query.helloworld.json",
%% expect results files
JsonResponseFileName = "query.helloworld.reply.json",
expect status = OK ie 200
StatusCode = 200,
%% send command and check results
ok = helper:post_oc2_body( JsonSendFileName
, StatusCode
, JsonResponseFileName
, Config
),
ok.
test_bad_method(_Config) ->
%% test if send get when expecting post
MyPort = application:get_env(slpfhw, port, 8080),
lager:info("test_bad_method"),
{ok, Conn} = gun:open("localhost", MyPort),
send get to which only allows posts
StreamRef = gun:get(Conn, "/openc2"),
%% check reply
Response = gun:await(Conn,StreamRef),
lager:info("test_bad_method:Response= ~p", [Response]),
%% Check contents of reply
response = element(1,Response),
fin = element(2, Response),
Status = element(3,Response),
ExpectedStatus = 405,
ExpectedStatus = Status,
RespHeaders = element(4,Response),
true = lists:member({<<"allow">>,<<"POST">>},RespHeaders),
true = lists:member({<<"content-length">>,<<"0">>},RespHeaders),
true = lists:member({<<"server">>,<<"Cowboy">>},RespHeaders),
ok.
test_post_missing_body(_Config) ->
%% test proper reponse to bad input (no body to html request)
MyPort = application:get_env(slpfhw, port, 8080),
lager:info("test_post_missing_body"),
{ok, ConnPid} = gun:open("localhost", MyPort),
%% send json post with no body
Headers = [ {<<"content-type">>, <<"application/json">>} ],
Body = "",
StreamRef = gun:post(ConnPid, "/openc2", Headers, Body),
%% check reply
Response = gun:await(ConnPid,StreamRef),
lager:info("test_post_missing_body:Response= ~p", [Response]),
%% Check contents of reply
response = element(1,Response),
nofin = element(2, Response),
Status = element(3,Response),
ExpectedStatus = 400,
ExpectedStatus = Status,
RespHeaders = element(4,Response),
true = lists:member({<<"content-length">>,<<"19">>},RespHeaders),
true = lists:member({<<"server">>,<<"Cowboy">>},RespHeaders),
%% get the body of the reply (which has error msg)
{ok, RespBody} = gun:await_body(ConnPid, StreamRef),
lager:info("test_post_missing_body:RespBody= ~p", [RespBody]),
%% test body is what was expected
<<"\"Missing http body\"">> = RespBody,
ok.
test_unsupported_media_type(_Config) ->
%% test proper reponse to bad input
%% (html request has media type other than json)
MyPort = application:get_env(slpfhw, port, 8080),
lager:info("test_unsupported_media_type"),
{ok, ConnPid} = gun:open("localhost", MyPort),
Headers = [ {<<"content-type">>, <<"text/plain">>} ],
Body = "scan",
send json command to
lager : info("about to send json to " ) ,
StreamRef = gun:post(ConnPid, "/openc2", Headers, Body),
%% check reply
Response = gun:await(ConnPid,StreamRef),
lager:info("test_unsupported_media_type:Response= ~p", [Response]),
%% Check contents of reply
response = element(1,Response),
fin = element(2, Response),
Status = element(3,Response),
ExpectedStatus = 415,
ExpectedStatus = Status,
RespHeaders = element(4,Response),
true = lists:member({<<"content-length">>,<<"0">>},RespHeaders),
true = lists:member({<<"server">>,<<"Cowboy">>},RespHeaders),
ok.
test_bad_json(_Config) ->
test proper reponse to bad input ( )
MyPort = application:get_env(slpfhw, port, 8080),
lager : info("test_bad_json : port= ~p " , [ MyPort ] ) ,
{ok, ConnPid} = gun:open("localhost", MyPort),
Headers = [ {<<"content-type">>, <<"application/json">>} ],
BadJson = "{]}",
send json command to
StreamRef = gun:post(ConnPid, "/openc2", Headers, BadJson),
%% check reply
Response = gun:await(ConnPid,StreamRef),
lager:info("test_bad_json:Response= ~p", [Response]),
%% Check contents of reply
response = element(1,Response),
nofin = element(2, Response),
Status = element(3,Response),
ExpectedStatus = 400,
ExpectedStatus = Status,
RespHeaders = element(4,Response),
%% forcefail = Response, %% use for debuggingh
true = lists:member({<<"content-length">>,<<"20">>},RespHeaders),
true = lists:member({<<"server">>,<<"Cowboy">>},RespHeaders),
%% get the body of the reply (which has error msg)
{ok, RespBody} = gun:await_body(ConnPid, StreamRef),
lager:info("test_bad_json:RespBody= ~p", [RespBody]),
%% test body is what was expected
<<"\"Can not parse JSON\"">> = RespBody,
ok.
test_bad_action(Config) ->
test json file with query profile
JsonSendFileName = "badaction.json",
%% expect results files
JsonResponseFileName = "badaction.reply.json",
%% expect status=400
StatusCode = 400,
%% send command and check results
ok = helper:post_oc2_body( JsonSendFileName
, StatusCode
, JsonResponseFileName
, Config
),
ok.
test_missing_action(_Config) ->
%% test proper reponse to bad input (missing action)
MyPort = application:get_env(slpfhw, port, 8080),
{ok, ConnPid} = gun:open("localhost", MyPort),
Headers = [ {<<"content-type">>, <<"application/json">>} ],
%% test JSON is missing action
Body = <<"{\"id\":\"0b4153de-03e1-4008-a071-0b2b23e20723\",\"target\":\"Hello World\"}">>,
send json command to
StreamRef = gun:post(ConnPid, "/openc2", Headers, Body),
%% check reply
Response = gun:await(ConnPid,StreamRef),
lager:info("test_missing_action:Response= ~p", [Response]),
%% Check contents of reply
response = element(1,Response),
nofin = element(2, Response),
Status = element(3,Response),
ExpectedStatus = 400,
ExpectedStatus = Status,
RespHeaders = element(4,Response),
true = lists:member({<<"content-length">>,<<"24">>},RespHeaders),
true= lists:member({<<"server">>,<<"Cowboy">>},RespHeaders),
%% get the body of the reply (which has error msg)
{ok, RespBody} = gun:await_body(ConnPid, StreamRef),
lager:info("test_bad_json:RespBody= ~p", [RespBody]),
%% test body is what was expected
<<"\"missing command action\"">> = RespBody,
ok.
test_missing_target(_Config) ->
%% test proper reponse to bad input (missing target)
MyPort = application:get_env(slpfhw, port, 8080),
{ok, ConnPid} = gun:open("localhost", MyPort),
Headers = [ {<<"content-type">>, <<"application/json">>} ],
%% JSON is missing target
Body = <<"{\"id\":\"0b4153de-03e1-4008-a071-0b2b23e20723\",\"action\":\"query\"}">>,
send json command to
StreamRef = gun:post(ConnPid, "/openc2", Headers, Body),
%% check reply
Response = gun:await(ConnPid,StreamRef),
lager:info("test_missing_target:Response= ~p", [Response]),
%% Check contents of reply
response = element(1,Response),
nofin = element(2, Response),
Status = element(3,Response),
ExpectedStatus = 400,
ExpectedStatus = Status,
RespHeaders = element(4,Response),
%%true = Response, %% for debugging
true = lists:member({<<"content-length">>,<<"24">>},RespHeaders),
true= lists:member({<<"server">>,<<"Cowboy">>},RespHeaders),
%% get the body of the reply (which has error msg)
{ok, RespBody} = gun:await_body(ConnPid, StreamRef),
lager:info("test_missing_target:RespBody= ~p", [RespBody]),
%% test body is what was expected
<<"\"missing command target\"">> = RespBody,
ok.
| null | https://raw.githubusercontent.com/oasis-open/openc2-lycan-beam/c8a580eb79a46cb3fa7db0d6576bfa23eb78c943/slpfhw/erlang/slpfhw/apps/slpfhw/test/a_simple_post_SUITE.erl | erlang |
-------------------------------------------------------------------
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation files
including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
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.
-------------------------------------------------------------------
for test export all functions
required for common_test to work
tests to run
setup config parameters
lager:info("AppList: ~p~n", [AppList]),
lager:info("AppList2: ~p~n", [AppList2]),
since ct doesn't read sys.config, set configs here
start application
lager:info("AppList3: ~p~n", [AppList3]),
expect results files
send command and check results
test if send get when expecting post
check reply
Check contents of reply
test proper reponse to bad input (no body to html request)
send json post with no body
check reply
Check contents of reply
get the body of the reply (which has error msg)
test body is what was expected
test proper reponse to bad input
(html request has media type other than json)
check reply
Check contents of reply
check reply
Check contents of reply
forcefail = Response, %% use for debuggingh
get the body of the reply (which has error msg)
test body is what was expected
expect results files
expect status=400
send command and check results
test proper reponse to bad input (missing action)
test JSON is missing action
check reply
Check contents of reply
get the body of the reply (which has error msg)
test body is what was expected
test proper reponse to bad input (missing target)
JSON is missing target
check reply
Check contents of reply
true = Response, %% for debugging
get the body of the reply (which has error msg)
test body is what was expected | @author
( C ) 2018 , sFractal Consulting LLC
-module(a_simple_post_SUITE).
-author("Duncan Sparrell").
-license("MIT").
-copyright("2018, Duncan Sparrell sFractal Consulting LLC").
Copyright ( c ) 2018 , , sFractal Consulting
MIT License
( the " Software " ) , to deal in the Software without restriction ,
sell copies of the Software , and to permit persons to whom the
shall be included in all copies or substantial portions of the Software .
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND ,
AND NONINFRINGEMENT . IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
-export( [ all/0
, suite/0
, init_per_suite/1
, end_per_suite/1
, test_bad_method/1
, test_post_missing_body/1
, test_unsupported_media_type/1
, test_bad_json/1
, test_bad_action/1
, test_missing_action/1
, test_missing_target/1
, test_post/1
]).
-include_lib("common_test/include/ct.hrl").
all() ->
[ test_bad_method
, test_post_missing_body
, test_unsupported_media_type
, test_bad_json
, test_missing_action
, test_post
, test_bad_action
, test_missing_target
].
timeout if no reply in a minute
suite() ->
[{timetrap, {minutes, 2}}].
init_per_suite(Config) ->
{ok, _AppList} = application:ensure_all_started(lager),
{ok, _AppList2} = application:ensure_all_started(gun),
application:set_env(slpfhw, port, 8080),
application:set_env(slpfhw, listener_count, 5),
{ok, _AppList3} = application:ensure_all_started(slpfhw),
lager_common_test_backend:bounce(debug),
Config.
end_per_suite(Config) ->
Config.
test_post(Config) ->
test json file with query profile
JsonSendFileName = "query.helloworld.json",
JsonResponseFileName = "query.helloworld.reply.json",
expect status = OK ie 200
StatusCode = 200,
ok = helper:post_oc2_body( JsonSendFileName
, StatusCode
, JsonResponseFileName
, Config
),
ok.
test_bad_method(_Config) ->
MyPort = application:get_env(slpfhw, port, 8080),
lager:info("test_bad_method"),
{ok, Conn} = gun:open("localhost", MyPort),
send get to which only allows posts
StreamRef = gun:get(Conn, "/openc2"),
Response = gun:await(Conn,StreamRef),
lager:info("test_bad_method:Response= ~p", [Response]),
response = element(1,Response),
fin = element(2, Response),
Status = element(3,Response),
ExpectedStatus = 405,
ExpectedStatus = Status,
RespHeaders = element(4,Response),
true = lists:member({<<"allow">>,<<"POST">>},RespHeaders),
true = lists:member({<<"content-length">>,<<"0">>},RespHeaders),
true = lists:member({<<"server">>,<<"Cowboy">>},RespHeaders),
ok.
test_post_missing_body(_Config) ->
MyPort = application:get_env(slpfhw, port, 8080),
lager:info("test_post_missing_body"),
{ok, ConnPid} = gun:open("localhost", MyPort),
Headers = [ {<<"content-type">>, <<"application/json">>} ],
Body = "",
StreamRef = gun:post(ConnPid, "/openc2", Headers, Body),
Response = gun:await(ConnPid,StreamRef),
lager:info("test_post_missing_body:Response= ~p", [Response]),
response = element(1,Response),
nofin = element(2, Response),
Status = element(3,Response),
ExpectedStatus = 400,
ExpectedStatus = Status,
RespHeaders = element(4,Response),
true = lists:member({<<"content-length">>,<<"19">>},RespHeaders),
true = lists:member({<<"server">>,<<"Cowboy">>},RespHeaders),
{ok, RespBody} = gun:await_body(ConnPid, StreamRef),
lager:info("test_post_missing_body:RespBody= ~p", [RespBody]),
<<"\"Missing http body\"">> = RespBody,
ok.
test_unsupported_media_type(_Config) ->
MyPort = application:get_env(slpfhw, port, 8080),
lager:info("test_unsupported_media_type"),
{ok, ConnPid} = gun:open("localhost", MyPort),
Headers = [ {<<"content-type">>, <<"text/plain">>} ],
Body = "scan",
send json command to
lager : info("about to send json to " ) ,
StreamRef = gun:post(ConnPid, "/openc2", Headers, Body),
Response = gun:await(ConnPid,StreamRef),
lager:info("test_unsupported_media_type:Response= ~p", [Response]),
response = element(1,Response),
fin = element(2, Response),
Status = element(3,Response),
ExpectedStatus = 415,
ExpectedStatus = Status,
RespHeaders = element(4,Response),
true = lists:member({<<"content-length">>,<<"0">>},RespHeaders),
true = lists:member({<<"server">>,<<"Cowboy">>},RespHeaders),
ok.
test_bad_json(_Config) ->
test proper reponse to bad input ( )
MyPort = application:get_env(slpfhw, port, 8080),
lager : info("test_bad_json : port= ~p " , [ MyPort ] ) ,
{ok, ConnPid} = gun:open("localhost", MyPort),
Headers = [ {<<"content-type">>, <<"application/json">>} ],
BadJson = "{]}",
send json command to
StreamRef = gun:post(ConnPid, "/openc2", Headers, BadJson),
Response = gun:await(ConnPid,StreamRef),
lager:info("test_bad_json:Response= ~p", [Response]),
response = element(1,Response),
nofin = element(2, Response),
Status = element(3,Response),
ExpectedStatus = 400,
ExpectedStatus = Status,
RespHeaders = element(4,Response),
true = lists:member({<<"content-length">>,<<"20">>},RespHeaders),
true = lists:member({<<"server">>,<<"Cowboy">>},RespHeaders),
{ok, RespBody} = gun:await_body(ConnPid, StreamRef),
lager:info("test_bad_json:RespBody= ~p", [RespBody]),
<<"\"Can not parse JSON\"">> = RespBody,
ok.
test_bad_action(Config) ->
test json file with query profile
JsonSendFileName = "badaction.json",
JsonResponseFileName = "badaction.reply.json",
StatusCode = 400,
ok = helper:post_oc2_body( JsonSendFileName
, StatusCode
, JsonResponseFileName
, Config
),
ok.
test_missing_action(_Config) ->
MyPort = application:get_env(slpfhw, port, 8080),
{ok, ConnPid} = gun:open("localhost", MyPort),
Headers = [ {<<"content-type">>, <<"application/json">>} ],
Body = <<"{\"id\":\"0b4153de-03e1-4008-a071-0b2b23e20723\",\"target\":\"Hello World\"}">>,
send json command to
StreamRef = gun:post(ConnPid, "/openc2", Headers, Body),
Response = gun:await(ConnPid,StreamRef),
lager:info("test_missing_action:Response= ~p", [Response]),
response = element(1,Response),
nofin = element(2, Response),
Status = element(3,Response),
ExpectedStatus = 400,
ExpectedStatus = Status,
RespHeaders = element(4,Response),
true = lists:member({<<"content-length">>,<<"24">>},RespHeaders),
true= lists:member({<<"server">>,<<"Cowboy">>},RespHeaders),
{ok, RespBody} = gun:await_body(ConnPid, StreamRef),
lager:info("test_bad_json:RespBody= ~p", [RespBody]),
<<"\"missing command action\"">> = RespBody,
ok.
test_missing_target(_Config) ->
MyPort = application:get_env(slpfhw, port, 8080),
{ok, ConnPid} = gun:open("localhost", MyPort),
Headers = [ {<<"content-type">>, <<"application/json">>} ],
Body = <<"{\"id\":\"0b4153de-03e1-4008-a071-0b2b23e20723\",\"action\":\"query\"}">>,
send json command to
StreamRef = gun:post(ConnPid, "/openc2", Headers, Body),
Response = gun:await(ConnPid,StreamRef),
lager:info("test_missing_target:Response= ~p", [Response]),
response = element(1,Response),
nofin = element(2, Response),
Status = element(3,Response),
ExpectedStatus = 400,
ExpectedStatus = Status,
RespHeaders = element(4,Response),
true = lists:member({<<"content-length">>,<<"24">>},RespHeaders),
true= lists:member({<<"server">>,<<"Cowboy">>},RespHeaders),
{ok, RespBody} = gun:await_body(ConnPid, StreamRef),
lager:info("test_missing_target:RespBody= ~p", [RespBody]),
<<"\"missing command target\"">> = RespBody,
ok.
|
3a5fbd17c5e1ae59c7d9ed54b324017d1937095ffb695ef3b6ba85b2871f91ce | acieroid/scala-am | omega.scm | ((lambda (x) (x x))
(lambda (x) (x x)))
| null | https://raw.githubusercontent.com/acieroid/scala-am/13ef3befbfc664b77f31f56847c30d60f4ee7dfe/test/R5RS/WeiChenRompf2019/omega.scm | scheme | ((lambda (x) (x x))
(lambda (x) (x x)))
| |
1edddeb7dacbacabdadebfd5577c34f446619c031404319a8fdc688836868b66 | openmusic-project/RQ | tempo-smoothing.lisp |
;;;============================
;;; ALGORITHM FOR TEMPO SMOOTHING
;;;
;;; Dynamic-programming segmentation algorithm
Inspired by the segmentation algorithm described in : , , : " A Dynamic Programming Approach to for Rhythm Transcription " ( see also )
;;; Also includes a new-tempo penalty (tempo jump penalty)
The " ERR " function is replaced by a - like best - path algorithm
;;; The "ERR" function finds the series of tempo that minimizes the variations between successive tempi, and the weights of the corresponding transcriptions.
;;; The balance between tempo variations and weights is made by the alpha parameter
(defpackage "TempSmooth"
(:nicknames :ts)
(:use "COMMON-LISP" "CL-USER" "OM-API" "LISPWORKS" "OM-LISP")
(:import-from "CL-USER")
(:export #:tempo-smooth)
)
(in-package :ts)
;------- Functions to calculate the best sequence of tempi in a sublist ------;
(defun dist (tempo1 tempo2 &optional (type :rse))
"Computes the distance between two tempi"
(let ((diff (- tempo2 tempo1)))
(case type
(:rse (* diff diff))
(:abs (abs diff))
(:alg diff)
)))
(defun dists (tempo ltempo &optional (type :rse))
"Returns a list holding the distances between TEMPO and each tempo in LTEMPO"
(loop for tempo2 in ltempo
collect (dist tempo tempo2 type)))
(defun min-argmin (list &optional (min most-positive-fixnum) (min-index 0) (cur-index 0))
"Returns the min (in absolute value) and the argmin of a list"
(if list
(if (< (abs (car list)) (abs min))
(min-argmin (rest list) (car list) cur-index (1+ cur-index))
(min-argmin (rest list) min min-index (1+ cur-index)))
(values min min-index))
)
(defun viterbi-backtrace (T1 &optional indexes tempi)
(let* ((new (nth (car indexes) (car T1)))
(new-index (second new))
(new-tempo (third new)))
(if new-index
(viterbi-backtrace (rest T1) (append (list new-index) indexes) (append (list new-tempo) tempi))
(values indexes (append (list new-tempo) tempi))))
)
(defun tempo-viterbi (ltempi lweights alpha &optional (type :rse))
"Computes the sequence of tempi that minimises the weight (compromise between the weight of the solution and the tempi difference among segments)"
(let ((T1 (make-list (length ltempi))))
T1 holds the cumulated values . It has the same length as ltempi .
;Its i-th element is a list of same length as (nth i ltempi)
;Each element of this list is a triplet (min argmin tempo)
;initialization
(setf (first T1) (loop for weight in (first lweights)
for tempo in (first ltempi)
collect (list (* (- 1 alpha) weight) nil tempo)))
;iteration
(loop for tempi in (rest ltempi)
for weights in (rest lweights)
for i = 1 then (1+ i)
do
(setf (nth i T1)
(let* ((prev (nth (1- i) T1))
(prev-vals (mapcar #'first prev))
(prev-tempi (mapcar #'third prev)))
(loop for tempo in tempi
for weight in weights
collect
(multiple-value-bind (val index) (min-argmin (om::om+ prev-vals
;(om::om* (dists tempo prev-tempi type) weight)))
(om::om+ (om::om* alpha (dists tempo prev-tempi type)) (* 2 (- 1 alpha) weight))))
(list val index tempo))))))
;backtrace
(let* ((last-vals (mapcar #'first (car (last T1))))
(min-val (reduce #'min (mapcar #'abs last-vals)))
(last-index (position min-val last-vals)))
(multiple-value-bind (indexes tempi)
(viterbi-backtrace (reverse T1) (list last-index))
(values min-val indexes tempi)
))
))
;-------- General algorithm --------;
(defun opt (ltempi lweights optlist k alpha type)
"Returns the weight and the index of the previous segmentation mark that gives the best weight"
(let* ((errorlist (make-list k))
(Tlist (make-list k))
(minimum)
(index))
(loop for i from 0 to (1- k) do
(multiple-value-bind (error index-list) (tempo-viterbi (subseq ltempi i) (subseq lweights i) alpha type)
(setf (nth i errorlist) (+ (nth i optlist) error)
(nth i Tlist) index-list)
))
(setq minimum (reduce #'min errorlist))
(setq index (position minimum errorlist))
(values minimum index (nth index Tlist))
))
(defun backtrace (Slist Tlist &optional Sbuff Tbuff)
(if Slist
(let ((S (car (last Slist))))
(backtrace (subseq Slist 0 S) (subseq Tlist 0 S) (append (list S) Sbuff) (append (last Tlist) Tbuff))
)
(values Sbuff Tbuff)))
(defun tempo-smooth (ltempi lweights &key (alpha 0.5) (type :abs) (penalty 5))
"Returns a list of indexes that optimises the variations of tempo between each measure"
(let* ((N (length ltempi))
(optlist (make-list (1+ N) :initial-element 0 ))
(Slist (make-list N :initial-element 0))
(Tlist (make-list N :initial-element 0)))
(loop for k from 1 to N do
(multiple-value-bind (OPT S index-list) (opt (subseq ltempi 0 k) (subseq lweights 0 k) optlist k alpha type)
(setf (nth k optlist) (+ OPT penalty))
(setf (nth (1- k) Slist) S)
(setf (nth (1- k) Tlist) index-list)
))
(multiple-value-bind (Ss Ts) (backtrace Slist Tlist) ;we discard the segmentation points list, as we do not use it further (we return the indexes of the solution to keep for each segment)
(let ((ks (reduce #'append Ts)))
(values ks
(loop for k in ks
for tempi in ltempi
collect (nth k tempi))))
)))
| null | https://raw.githubusercontent.com/openmusic-project/RQ/d6b1274a4462c1500dfc2edab81a4425a6dfcda7/src/algorithm/tempo-smoothing.lisp | lisp | ============================
ALGORITHM FOR TEMPO SMOOTHING
Dynamic-programming segmentation algorithm
Also includes a new-tempo penalty (tempo jump penalty)
The "ERR" function finds the series of tempo that minimizes the variations between successive tempi, and the weights of the corresponding transcriptions.
The balance between tempo variations and weights is made by the alpha parameter
------- Functions to calculate the best sequence of tempi in a sublist ------;
Its i-th element is a list of same length as (nth i ltempi)
Each element of this list is a triplet (min argmin tempo)
initialization
iteration
(om::om* (dists tempo prev-tempi type) weight)))
backtrace
-------- General algorithm --------;
we discard the segmentation points list, as we do not use it further (we return the indexes of the solution to keep for each segment) |
Inspired by the segmentation algorithm described in : , , : " A Dynamic Programming Approach to for Rhythm Transcription " ( see also )
The " ERR " function is replaced by a - like best - path algorithm
(defpackage "TempSmooth"
(:nicknames :ts)
(:use "COMMON-LISP" "CL-USER" "OM-API" "LISPWORKS" "OM-LISP")
(:import-from "CL-USER")
(:export #:tempo-smooth)
)
(in-package :ts)
(defun dist (tempo1 tempo2 &optional (type :rse))
"Computes the distance between two tempi"
(let ((diff (- tempo2 tempo1)))
(case type
(:rse (* diff diff))
(:abs (abs diff))
(:alg diff)
)))
(defun dists (tempo ltempo &optional (type :rse))
"Returns a list holding the distances between TEMPO and each tempo in LTEMPO"
(loop for tempo2 in ltempo
collect (dist tempo tempo2 type)))
(defun min-argmin (list &optional (min most-positive-fixnum) (min-index 0) (cur-index 0))
"Returns the min (in absolute value) and the argmin of a list"
(if list
(if (< (abs (car list)) (abs min))
(min-argmin (rest list) (car list) cur-index (1+ cur-index))
(min-argmin (rest list) min min-index (1+ cur-index)))
(values min min-index))
)
(defun viterbi-backtrace (T1 &optional indexes tempi)
(let* ((new (nth (car indexes) (car T1)))
(new-index (second new))
(new-tempo (third new)))
(if new-index
(viterbi-backtrace (rest T1) (append (list new-index) indexes) (append (list new-tempo) tempi))
(values indexes (append (list new-tempo) tempi))))
)
(defun tempo-viterbi (ltempi lweights alpha &optional (type :rse))
"Computes the sequence of tempi that minimises the weight (compromise between the weight of the solution and the tempi difference among segments)"
(let ((T1 (make-list (length ltempi))))
T1 holds the cumulated values . It has the same length as ltempi .
(setf (first T1) (loop for weight in (first lweights)
for tempo in (first ltempi)
collect (list (* (- 1 alpha) weight) nil tempo)))
(loop for tempi in (rest ltempi)
for weights in (rest lweights)
for i = 1 then (1+ i)
do
(setf (nth i T1)
(let* ((prev (nth (1- i) T1))
(prev-vals (mapcar #'first prev))
(prev-tempi (mapcar #'third prev)))
(loop for tempo in tempi
for weight in weights
collect
(multiple-value-bind (val index) (min-argmin (om::om+ prev-vals
(om::om+ (om::om* alpha (dists tempo prev-tempi type)) (* 2 (- 1 alpha) weight))))
(list val index tempo))))))
(let* ((last-vals (mapcar #'first (car (last T1))))
(min-val (reduce #'min (mapcar #'abs last-vals)))
(last-index (position min-val last-vals)))
(multiple-value-bind (indexes tempi)
(viterbi-backtrace (reverse T1) (list last-index))
(values min-val indexes tempi)
))
))
(defun opt (ltempi lweights optlist k alpha type)
"Returns the weight and the index of the previous segmentation mark that gives the best weight"
(let* ((errorlist (make-list k))
(Tlist (make-list k))
(minimum)
(index))
(loop for i from 0 to (1- k) do
(multiple-value-bind (error index-list) (tempo-viterbi (subseq ltempi i) (subseq lweights i) alpha type)
(setf (nth i errorlist) (+ (nth i optlist) error)
(nth i Tlist) index-list)
))
(setq minimum (reduce #'min errorlist))
(setq index (position minimum errorlist))
(values minimum index (nth index Tlist))
))
(defun backtrace (Slist Tlist &optional Sbuff Tbuff)
(if Slist
(let ((S (car (last Slist))))
(backtrace (subseq Slist 0 S) (subseq Tlist 0 S) (append (list S) Sbuff) (append (last Tlist) Tbuff))
)
(values Sbuff Tbuff)))
(defun tempo-smooth (ltempi lweights &key (alpha 0.5) (type :abs) (penalty 5))
"Returns a list of indexes that optimises the variations of tempo between each measure"
(let* ((N (length ltempi))
(optlist (make-list (1+ N) :initial-element 0 ))
(Slist (make-list N :initial-element 0))
(Tlist (make-list N :initial-element 0)))
(loop for k from 1 to N do
(multiple-value-bind (OPT S index-list) (opt (subseq ltempi 0 k) (subseq lweights 0 k) optlist k alpha type)
(setf (nth k optlist) (+ OPT penalty))
(setf (nth (1- k) Slist) S)
(setf (nth (1- k) Tlist) index-list)
))
(let ((ks (reduce #'append Ts)))
(values ks
(loop for k in ks
for tempi in ltempi
collect (nth k tempi))))
)))
|
75d62a0311504041021fa4be3ca0a8aae19f5475d678339b00c3dc01f4b3a69f | fujita-y/ypsilon | arithmetic.scm | #!core
Copyright ( c ) 2004 - 2022 Yoshikatsu Fujita / LittleWing Company Limited .
;;; See LICENSE file for terms and conditions of use.
(library (core arithmetic)
(export fixnum?
fixnum-width
least-fixnum
greatest-fixnum
fx=?
fx<?
fx>?
fx<=?
fx>=?
fxzero?
fxpositive?
fxnegative?
fxodd?
fxeven?
fxmax
fxmin
fx+
fx*
fx-
fxdiv
fxmod
fxdiv-and-mod
fxdiv0
fxmod0
fxdiv0-and-mod0
fx+/carry
fx-/carry
fx*/carry
fxnot
fxand
fxior
fxxor
fxif
fxbit-count
fxlength
fxfirst-bit-set
fxbit-set?
fxcopy-bit
fxbit-field
fxcopy-bit-field
fxarithmetic-shift
fxarithmetic-shift-left
fxarithmetic-shift-right
fxrotate-bit-field
fxreverse-bit-field
flonum?
real->flonum
fl=?
fl<?
fl>?
fl<=?
fl>=?
flinteger?
flzero?
flpositive?
flnegative?
flodd?
fleven?
flfinite?
flinfinite?
flnan?
flmax
flmin
fl+
fl*
fl-
fl/
fldiv-and-mod
fldiv
flmod
fldiv0-and-mod0
fldiv0
flmod0
flnumerator
fldenominator
flfloor
flceiling
fltruncate
flround
flexp
flexpt
fllog
flsin
flcos
fltan
flasin
flacos
flatan
flabs
flsqrt
fixnum->flonum
bitwise-not
bitwise-and
bitwise-ior
bitwise-xor
bitwise-if
bitwise-bit-count
bitwise-length
bitwise-first-bit-set
bitwise-bit-set?
bitwise-copy-bit
bitwise-bit-field
bitwise-copy-bit-field
bitwise-arithmetic-shift
bitwise-arithmetic-shift-left
bitwise-arithmetic-shift-right
bitwise-rotate-bit-field
bitwise-reverse-bit-field
&no-infinities make-no-infinities-violation no-infinities-violation?
&no-nans make-no-nans-violation no-nans-violation?)
(import (core primitives))
(define flmod
(lambda (x y)
(fl- x (fl* (fldiv x y) y))))
(define fldiv-and-mod
(lambda (x y)
(let ((d (fldiv x y)))
(values d (fl- x (fl* d y))))))
(define flmod0
(lambda (x y)
(fl- x (fl* (fldiv0 x y) y))))
(define fldiv0-and-mod0
(lambda (x y)
(let ((d0 (fldiv0 x y)))
(values d0 (fl- x (fl* d0 y))))))
(define 2^fixnum-width (expt 2 (fixnum-width)))
(define fxmod
(lambda (x y)
(fx- x (fx* (fxdiv x y) y))))
(define fxdiv-and-mod
(lambda (x y)
(let ((d (fxdiv x y)))
(values d (fx- x (fx* d y))))))
(define fxmod0
(lambda (x y)
(fx- x (fx* (fxdiv0 x y) y))))
(define fxdiv0-and-mod0
(lambda (x y)
(let ((d0 (fxdiv0 x y)))
(values d0 (fx- x (fx* d0 y))))))
(define fx+/carry
(lambda (fx1 fx2 fx3)
(let* ((s (+ fx1 fx2 fx3))
(s0 (mod0 s 2^fixnum-width))
(s1 (div0 s 2^fixnum-width)))
(values s0 s1))))
(define fx-/carry
(lambda (fx1 fx2 fx3)
(let* ((d (- fx1 fx2 fx3))
(d0 (mod0 d 2^fixnum-width))
(d1 (div0 d 2^fixnum-width)))
(values d0 d1))))
(define fx*/carry
(lambda (fx1 fx2 fx3)
(let* ((s (+ (* fx1 fx2) fx3))
(s0 (mod0 s 2^fixnum-width))
(s1 (div0 s 2^fixnum-width)))
(values s0 s1))))
(define fxrotate-bit-field
(lambda (ei1 ei2 ei3 ei4)
(let* ((n ei1)
(start ei2)
(end ei3)
(count ei4)
(width (fx- end start)))
(if (fxpositive? width)
(fxcopy-bit-field n start end
(fxior
(fxarithmetic-shift-left
(fxbit-field n start (fx- end count)) count)
(fxarithmetic-shift-right
(fxbit-field n start end) (fx- width count))))
n))))
(define fxreverse-bit-field
(lambda (ei1 ei2 ei3)
(let* ((n ei1)
(start ei2)
(end ei3)
(width (fx- end start)))
(if (fxpositive? width)
(let loop ((reversed 0) (field (fxbit-field n start end)) (width width))
(if (fxzero? width)
(fxcopy-bit-field n start end reversed)
(if (fxzero? (fxand field 1))
(loop (fxarithmetic-shift-left reversed 1)
(fxarithmetic-shift-right field 1)
(fx- width 1))
(loop (fxior (fxarithmetic-shift-left reversed 1) 1)
(fxarithmetic-shift-right field 1)
(fx- width 1)))))
n))))
(define bitwise-arithmetic-shift-left bitwise-arithmetic-shift)
(define bitwise-if
(lambda (ei1 ei2 ei3)
(bitwise-ior (bitwise-and ei1 ei2)
(bitwise-and (bitwise-not ei1) ei3))))
(define bitwise-bit-set?
(lambda (ei1 ei2)
(not (zero? (bitwise-and (bitwise-arithmetic-shift 1 ei2) ei1)))))
(define bitwise-copy-bit
(lambda (ei1 ei2 ei3)
(let* ((mask (bitwise-arithmetic-shift 1 ei2)))
(bitwise-if mask (bitwise-arithmetic-shift ei3 ei2) ei1))))
(define bitwise-bit-field
(lambda (ei1 ei2 ei3)
(let ((mask (bitwise-not (bitwise-arithmetic-shift -1 ei3))))
(bitwise-arithmetic-shift-right (bitwise-and ei1 mask) ei2))))
(define bitwise-copy-bit-field
(lambda (ei1 ei2 ei3 ei4)
(let* ((to ei1)
(start ei2)
(end ei3)
(from ei4)
(mask1 (bitwise-arithmetic-shift -1 start))
(mask2 (bitwise-not (bitwise-arithmetic-shift -1 end)))
(mask (bitwise-and mask1 mask2)))
(bitwise-if mask (bitwise-arithmetic-shift from start) to))))
(define bitwise-arithmetic-shift-right
(lambda (ei1 ei2)
(bitwise-arithmetic-shift ei1 (- ei2))))
(define bitwise-rotate-bit-field
(lambda (ei1 ei2 ei3 ei4)
(let* ((n ei1)
(start ei2)
(end ei3)
(count ei4)
(width (- end start)))
(if (positive? width)
(let* ((count (mod count width))
(field0 (bitwise-bit-field n start end))
(field1 (bitwise-arithmetic-shift field0 count))
(field2 (bitwise-arithmetic-shift-right field0 (- width count)))
(field (bitwise-ior field1 field2)))
(bitwise-copy-bit-field n start end field))
n))))
(define bitwise-reverse-bit-field
(lambda (ei1 ei2 ei3)
(let* ((n ei1)
(start ei2)
(end ei3)
(width (- end start)))
(if (positive? width)
(let loop ((reversed 0) (field (bitwise-bit-field n start end)) (width width))
(if (zero? width)
(bitwise-copy-bit-field n start end reversed)
(if (zero? (bitwise-and field 1))
(loop (bitwise-arithmetic-shift reversed 1)
(bitwise-arithmetic-shift-right field 1)
(- width 1))
(loop (bitwise-ior (bitwise-arithmetic-shift reversed 1) 1)
(bitwise-arithmetic-shift-right field 1)
(- width 1)))))
n))))
) ;[end]
| null | https://raw.githubusercontent.com/fujita-y/ypsilon/44260d99e24000f9847e79c94826c3d9b76872c2/stdlib/core/arithmetic.scm | scheme | See LICENSE file for terms and conditions of use.
[end] | #!core
Copyright ( c ) 2004 - 2022 Yoshikatsu Fujita / LittleWing Company Limited .
(library (core arithmetic)
(export fixnum?
fixnum-width
least-fixnum
greatest-fixnum
fx=?
fx<?
fx>?
fx<=?
fx>=?
fxzero?
fxpositive?
fxnegative?
fxodd?
fxeven?
fxmax
fxmin
fx+
fx*
fx-
fxdiv
fxmod
fxdiv-and-mod
fxdiv0
fxmod0
fxdiv0-and-mod0
fx+/carry
fx-/carry
fx*/carry
fxnot
fxand
fxior
fxxor
fxif
fxbit-count
fxlength
fxfirst-bit-set
fxbit-set?
fxcopy-bit
fxbit-field
fxcopy-bit-field
fxarithmetic-shift
fxarithmetic-shift-left
fxarithmetic-shift-right
fxrotate-bit-field
fxreverse-bit-field
flonum?
real->flonum
fl=?
fl<?
fl>?
fl<=?
fl>=?
flinteger?
flzero?
flpositive?
flnegative?
flodd?
fleven?
flfinite?
flinfinite?
flnan?
flmax
flmin
fl+
fl*
fl-
fl/
fldiv-and-mod
fldiv
flmod
fldiv0-and-mod0
fldiv0
flmod0
flnumerator
fldenominator
flfloor
flceiling
fltruncate
flround
flexp
flexpt
fllog
flsin
flcos
fltan
flasin
flacos
flatan
flabs
flsqrt
fixnum->flonum
bitwise-not
bitwise-and
bitwise-ior
bitwise-xor
bitwise-if
bitwise-bit-count
bitwise-length
bitwise-first-bit-set
bitwise-bit-set?
bitwise-copy-bit
bitwise-bit-field
bitwise-copy-bit-field
bitwise-arithmetic-shift
bitwise-arithmetic-shift-left
bitwise-arithmetic-shift-right
bitwise-rotate-bit-field
bitwise-reverse-bit-field
&no-infinities make-no-infinities-violation no-infinities-violation?
&no-nans make-no-nans-violation no-nans-violation?)
(import (core primitives))
(define flmod
(lambda (x y)
(fl- x (fl* (fldiv x y) y))))
(define fldiv-and-mod
(lambda (x y)
(let ((d (fldiv x y)))
(values d (fl- x (fl* d y))))))
(define flmod0
(lambda (x y)
(fl- x (fl* (fldiv0 x y) y))))
(define fldiv0-and-mod0
(lambda (x y)
(let ((d0 (fldiv0 x y)))
(values d0 (fl- x (fl* d0 y))))))
(define 2^fixnum-width (expt 2 (fixnum-width)))
(define fxmod
(lambda (x y)
(fx- x (fx* (fxdiv x y) y))))
(define fxdiv-and-mod
(lambda (x y)
(let ((d (fxdiv x y)))
(values d (fx- x (fx* d y))))))
(define fxmod0
(lambda (x y)
(fx- x (fx* (fxdiv0 x y) y))))
(define fxdiv0-and-mod0
(lambda (x y)
(let ((d0 (fxdiv0 x y)))
(values d0 (fx- x (fx* d0 y))))))
(define fx+/carry
(lambda (fx1 fx2 fx3)
(let* ((s (+ fx1 fx2 fx3))
(s0 (mod0 s 2^fixnum-width))
(s1 (div0 s 2^fixnum-width)))
(values s0 s1))))
(define fx-/carry
(lambda (fx1 fx2 fx3)
(let* ((d (- fx1 fx2 fx3))
(d0 (mod0 d 2^fixnum-width))
(d1 (div0 d 2^fixnum-width)))
(values d0 d1))))
(define fx*/carry
(lambda (fx1 fx2 fx3)
(let* ((s (+ (* fx1 fx2) fx3))
(s0 (mod0 s 2^fixnum-width))
(s1 (div0 s 2^fixnum-width)))
(values s0 s1))))
(define fxrotate-bit-field
(lambda (ei1 ei2 ei3 ei4)
(let* ((n ei1)
(start ei2)
(end ei3)
(count ei4)
(width (fx- end start)))
(if (fxpositive? width)
(fxcopy-bit-field n start end
(fxior
(fxarithmetic-shift-left
(fxbit-field n start (fx- end count)) count)
(fxarithmetic-shift-right
(fxbit-field n start end) (fx- width count))))
n))))
(define fxreverse-bit-field
(lambda (ei1 ei2 ei3)
(let* ((n ei1)
(start ei2)
(end ei3)
(width (fx- end start)))
(if (fxpositive? width)
(let loop ((reversed 0) (field (fxbit-field n start end)) (width width))
(if (fxzero? width)
(fxcopy-bit-field n start end reversed)
(if (fxzero? (fxand field 1))
(loop (fxarithmetic-shift-left reversed 1)
(fxarithmetic-shift-right field 1)
(fx- width 1))
(loop (fxior (fxarithmetic-shift-left reversed 1) 1)
(fxarithmetic-shift-right field 1)
(fx- width 1)))))
n))))
(define bitwise-arithmetic-shift-left bitwise-arithmetic-shift)
(define bitwise-if
(lambda (ei1 ei2 ei3)
(bitwise-ior (bitwise-and ei1 ei2)
(bitwise-and (bitwise-not ei1) ei3))))
(define bitwise-bit-set?
(lambda (ei1 ei2)
(not (zero? (bitwise-and (bitwise-arithmetic-shift 1 ei2) ei1)))))
(define bitwise-copy-bit
(lambda (ei1 ei2 ei3)
(let* ((mask (bitwise-arithmetic-shift 1 ei2)))
(bitwise-if mask (bitwise-arithmetic-shift ei3 ei2) ei1))))
(define bitwise-bit-field
(lambda (ei1 ei2 ei3)
(let ((mask (bitwise-not (bitwise-arithmetic-shift -1 ei3))))
(bitwise-arithmetic-shift-right (bitwise-and ei1 mask) ei2))))
(define bitwise-copy-bit-field
(lambda (ei1 ei2 ei3 ei4)
(let* ((to ei1)
(start ei2)
(end ei3)
(from ei4)
(mask1 (bitwise-arithmetic-shift -1 start))
(mask2 (bitwise-not (bitwise-arithmetic-shift -1 end)))
(mask (bitwise-and mask1 mask2)))
(bitwise-if mask (bitwise-arithmetic-shift from start) to))))
(define bitwise-arithmetic-shift-right
(lambda (ei1 ei2)
(bitwise-arithmetic-shift ei1 (- ei2))))
(define bitwise-rotate-bit-field
(lambda (ei1 ei2 ei3 ei4)
(let* ((n ei1)
(start ei2)
(end ei3)
(count ei4)
(width (- end start)))
(if (positive? width)
(let* ((count (mod count width))
(field0 (bitwise-bit-field n start end))
(field1 (bitwise-arithmetic-shift field0 count))
(field2 (bitwise-arithmetic-shift-right field0 (- width count)))
(field (bitwise-ior field1 field2)))
(bitwise-copy-bit-field n start end field))
n))))
(define bitwise-reverse-bit-field
(lambda (ei1 ei2 ei3)
(let* ((n ei1)
(start ei2)
(end ei3)
(width (- end start)))
(if (positive? width)
(let loop ((reversed 0) (field (bitwise-bit-field n start end)) (width width))
(if (zero? width)
(bitwise-copy-bit-field n start end reversed)
(if (zero? (bitwise-and field 1))
(loop (bitwise-arithmetic-shift reversed 1)
(bitwise-arithmetic-shift-right field 1)
(- width 1))
(loop (bitwise-ior (bitwise-arithmetic-shift reversed 1) 1)
(bitwise-arithmetic-shift-right field 1)
(- width 1)))))
n))))
|
94ea92417f675d008a54b44d6371fc790472070050282330fbc656db217d24ef | awslabs/s2n-bignum | bignum_montredc.ml |
* Copyright Amazon.com , Inc. or its affiliates . All Rights Reserved .
* SPDX - License - Identifier : Apache-2.0 OR ISC
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0 OR ISC
*)
(* ========================================================================= *)
Montgomery reduction of arbitrary bignum .
(* ========================================================================= *)
(**** print_literal_from_elf "x86/generic/bignum_montredc.o";;
****)
let bignum_montredc_mc =
define_assert_from_elf "bignum_montredc_mc" "x86/generic/bignum_montredc.o"
[
0x53; (* PUSH (% rbx) *)
0x55; (* PUSH (% rbp) *)
0x41; 0x54; (* PUSH (% r12) *)
0x41; 0x55; (* PUSH (% r13) *)
0x41; 0x56; (* PUSH (% r14) *)
0x41; 0x57; (* PUSH (% r15) *)
SUB ( % rsp ) ( Imm8 ( word 8) )
0x48; 0x85; 0xff; (* TEST (% rdi) (% rdi) *)
0x0f; 0x84; 0x57; 0x01; 0x00; 0x00;
JE ( Imm32 ( word 343 ) )
MOV ( % r10 ) ( % rdx )
MOV ( % rax ) ( ( % % ( r8,0 ) ) )
MOV ( % r14 ) ( % rax )
MOV ( % rbx ) ( % rax )
SHL ( % r14 ) ( Imm8 ( word 2 ) )
0x4c; 0x29; 0xf3; (* SUB (% rbx) (% r14) *)
XOR ( % rbx ) ( Imm8 ( word 2 ) )
MOV ( % r14 ) ( % rbx )
IMUL ( % r14 ) ( % rax )
0xb8; 0x02; 0x00; 0x00; 0x00;
MOV ( % eax ) ( Imm32 ( word 2 ) )
0x4c; 0x01; 0xf0; (* ADD (% rax) (% r14) *)
ADD ( % r14 ) ( Imm8 ( word 1 ) )
IMUL ( % rbx ) ( % rax )
IMUL ( % r14 ) ( % r14 )
0xb8; 0x01; 0x00; 0x00; 0x00;
MOV ( % eax ) ( Imm32 ( word 1 ) )
0x4c; 0x01; 0xf0; (* ADD (% rax) (% r14) *)
IMUL ( % rbx ) ( % rax )
IMUL ( % r14 ) ( % r14 )
0xb8; 0x01; 0x00; 0x00; 0x00;
MOV ( % eax ) ( Imm32 ( word 1 ) )
0x4c; 0x01; 0xf0; (* ADD (% rax) (% r14) *)
IMUL ( % rbx ) ( % rax )
IMUL ( % r14 ) ( % r14 )
0xb8; 0x01; 0x00; 0x00; 0x00;
MOV ( % eax ) ( Imm32 ( word 1 ) )
0x4c; 0x01; 0xf0; (* ADD (% rax) (% r14) *)
IMUL ( % rbx ) ( % rax )
MOV ( ( % % ( rsp,0 ) ) ) ( % rbx )
MOV ( % rbx ) ( % rdi )
CMP ( % r10 ) ( % rdi )
CMOVB ( % rbx ) ( % r10 )
0x4d; 0x31; 0xf6; (* XOR (% r14) (% r14) *)
0x48; 0x85; 0xdb; (* TEST (% rbx) (% rbx) *)
JE ( Imm8 ( word 24 ) )
MOV ( % rax ) ( ( % % % ( rcx,3,r14 ) ) )
MOV ( ( % % % ( rsi,3,r14 ) ) ) ( % rax )
0x49; 0xff; 0xc6; (* INC (% r14) *)
CMP ( % r14 ) ( % rbx )
JB ( Imm8 ( word 240 ) )
CMP ( % r14 ) ( % rdi )
JAE ( Imm8 ( word 15 ) )
0x48; 0x31; 0xdb; (* XOR (% rbx) (% rbx) *)
MOV ( ( % % % ( rsi,3,r14 ) ) ) ( % rbx )
0x49; 0xff; 0xc6; (* INC (% r14) *)
CMP ( % r14 ) ( % rdi )
JB ( Imm8 ( word 244 ) )
0x4d; 0x31; 0xff; (* XOR (% r15) (% r15) *)
0x4d; 0x85; 0xc9; (* TEST (% r9) (% r9) *)
JE ( Imm8 ( word 120 ) )
0x4d; 0x31; 0xf6; (* XOR (% r14) (% r14) *)
MOV ( % r12 ) ( ( % % ( rsi,0 ) ) )
MOV ( % rbp ) ( ( % % ( rsp,0 ) ) )
IMUL ( % rbp ) ( % r12 )
MOV ( % rax ) ( ( % % ( r8,0 ) ) )
MUL2 ( % rdx,% rax ) ( % rbp )
0x4c; 0x01; 0xe0; (* ADD (% rax) (% r12) *)
MOV ( % r11 ) ( % rdx )
0xbb; 0x01; 0x00; 0x00; 0x00;
MOV ( % ebx ) ( Imm32 ( word 1 ) )
MOV ( % r13 ) ( % rdi )
DEC ( % r13 )
JE ( Imm8 ( word 36 ) )
ADC ( % r11 ) ( ( % % % ( ) ) )
SBB ( % r12 ) ( % r12 )
MOV ( % rax ) ( ( % % % ( r8,3,rbx ) ) )
MUL2 ( % rdx,% rax ) ( % rbp )
SUB ( % rdx ) ( % r12 )
0x4c; 0x01; 0xd8; (* ADD (% rax) (% r11) *)
0x48; 0x89; 0x44; 0xde; 0xf8;
MOV ( ( % % % % ( rsi,3,rbx,-- & 8) ) ) ( % rax )
MOV ( % r11 ) ( % rdx )
0x48; 0xff; 0xc3; (* INC (% rbx) *)
DEC ( % r13 )
JNE ( Imm8 ( word 220 ) )
0x4d; 0x11; 0xfb; (* ADC (% r11) (% r15) *)
0x41; 0xbf; 0x00; 0x00; 0x00; 0x00;
MOV ( % r15d ) ( Imm32 ( word 0 ) )
0x49; 0x83; 0xd7; 0x00; (* ADC (% r15) (Imm8 (word 0)) *)
0x4c; 0x01; 0xf3; (* ADD (% rbx) (% r14) *)
CMP ( % rbx ) ( % r10 )
JAE ( Imm8 ( word 11 ) )
MOV ( % rax ) ( ( % % % ( rcx,3,rbx ) ) )
0x49; 0x01; 0xc3; (* ADD (% r11) (% rax) *)
0x49; 0x83; 0xd7; 0x00; (* ADC (% r15) (Imm8 (word 0)) *)
0x4c; 0x89; 0x5c; 0xfe; 0xf8;
MOV ( ( % % % % ( rsi,3,rdi,-- & 8) ) ) ( % r11 )
0x49; 0xff; 0xc6; (* INC (% r14) *)
CMP ( % r14 ) ( % r9 )
JB ( Imm8 ( word 139 ) )
0x48; 0x31; 0xdb; (* XOR (% rbx) (% rbx) *)
MOV ( % r10 ) ( % rdi )
MOV ( % rax ) ( ( % % % ( ) ) )
SBB ( % rax ) ( ( % % % ( r8,3,rbx ) ) )
0x48; 0xff; 0xc3; (* INC (% rbx) *)
DEC ( % r10 )
JNE ( Imm8 ( word 240 ) )
SBB ( % r15 ) ( Imm8 ( word 0 ) )
SBB ( % rbp ) ( % rbp )
0x48; 0xf7; 0xd5; (* NOT (% rbp) *)
0x4d; 0x31; 0xe4; (* XOR (% r12) (% r12) *)
0x48; 0x31; 0xdb; (* XOR (% rbx) (% rbx) *)
MOV ( % rax ) ( ( % % % ( r8,3,rbx ) ) )
0x48; 0x21; 0xe8; (* AND (% rax) (% rbp) *)
0x49; 0xf7; 0xdc; (* NEG (% r12) *)
SBB ( ( % % % ( ) ) ) ( % rax )
SBB ( % r12 ) ( % r12 )
0x48; 0xff; 0xc3; (* INC (% rbx) *)
CMP ( % rbx ) ( % rdi )
JB ( Imm8 ( word 231 ) )
0x48; 0x83; 0xc4; 0x08; (* ADD (% rsp) (Imm8 (word 8)) *)
0x41; 0x5f; (* POP (% r15) *)
0x41; 0x5e; (* POP (% r14) *)
0x41; 0x5d; (* POP (% r13) *)
0x41; 0x5c; (* POP (% r12) *)
0x5d; (* POP (% rbp) *)
0x5b; (* POP (% rbx) *)
RET
];;
let BIGNUM_MONTREDC_EXEC = X86_MK_CORE_EXEC_RULE bignum_montredc_mc;;
(* ------------------------------------------------------------------------- *)
(* Proof. *)
(* ------------------------------------------------------------------------- *)
* * This actually works mod 32 but if anything this is more convenient * *
let WORD_NEGMODINV_SEED_LEMMA_16 = prove
(`!a x:int64.
ODD a /\
word_xor (word_sub (word a) (word_shl (word a) 2)) (word 2) = x
==> (a * val x + 1 == 0) (mod 16)`,
REPEAT STRIP_TAC THEN REWRITE_TAC[CONG; MOD_0] THEN
TRANS_TAC EQ_TRANS
`(val(word a:int64) MOD 16 * val(x:int64) MOD 16 + 1) MOD 16` THEN
REWRITE_TAC[ARITH_RULE `16 = 2 EXP 4`] THEN CONJ_TAC THENL
[REWRITE_TAC[VAL_WORD; DIMINDEX_64; MOD_MOD_EXP_MIN] THEN
CONV_TAC NUM_REDUCE_CONV THEN CONV_TAC MOD_DOWN_CONV THEN REFL_TAC;
REWRITE_TAC[VAL_MOD; NUMSEG_LT; ARITH_EQ; ARITH]] THEN
SUBGOAL_THEN `bit 0 (word a:int64)` MP_TAC THENL
[ASM_REWRITE_TAC[BIT_LSB_WORD];
EXPAND_TAC "x" THEN POP_ASSUM_LIST(K ALL_TAC) THEN DISCH_TAC] THEN
CONV_TAC(ONCE_DEPTH_CONV EXPAND_NSUM_CONV) THEN
CONV_TAC(TOP_DEPTH_CONV BIT_WORD_CONV) THEN
MAP_EVERY ASM_CASES_TAC
[`bit 1 (word a:int64)`;`bit 2 (word a:int64)`;`bit 3 (word a:int64)`] THEN
ASM_REWRITE_TAC[BITVAL_CLAUSES] THEN CONV_TAC NUM_REDUCE_CONV);;
let BIGNUM_MONTREDC_CORRECT = time prove
(`!k z r x m p a n pc stackpointer.
ALL (nonoverlapping (stackpointer,8))
[(word pc,0x17d); (x,8 * val r); (m,8 * val k); (z,8 * val k)] /\
ALL (nonoverlapping (z,8 * val k)) [(word pc,0x17d); (m,8 * val k)] /\
(x = z \/ nonoverlapping (x,8 * val r) (z,8 * val k)) /\
val p < 2 EXP 61 /\ val r < 2 EXP 61
==> ensures x86
(\s. bytes_loaded s (word pc) (BUTLAST bignum_montredc_mc) /\
read RIP s = word(pc + 0xe) /\
read RSP s = stackpointer /\
C_ARGUMENTS [k; z; r; x; m; p] s /\
bignum_from_memory (x,val r) s = a /\
bignum_from_memory (m,val k) s = n)
(\s. read RIP s = word(pc + 0x16e) /\
(ODD n /\
lowdigits a (val k + val p) <= 2 EXP (64 * val p) * n
==> bignum_from_memory (z,val k) s =
(inverse_mod n (2 EXP (64 * val p)) *
lowdigits a (val k + val p)) MOD n))
(MAYCHANGE [RIP; RAX; RBX; RBP; RDX;
R10; R11; R12; R13; R14; R15] ,,
MAYCHANGE [memory :> bytes(z,8 * val k);
memory :> bytes(stackpointer,8)] ,,
MAYCHANGE SOME_FLAGS)`,
W64_GEN_TAC `k:num` THEN X_GEN_TAC `z:int64` THEN
W64_GEN_TAC `nx:num` THEN X_GEN_TAC `x:int64` THEN
X_GEN_TAC `m:int64` THEN W64_GEN_TAC `p:num` THEN
MAP_EVERY X_GEN_TAC [`a:num`; `n:num`; `pc:num`] THEN
X_GEN_TAC `stackpointer:int64` THEN
REWRITE_TAC[ALL; NONOVERLAPPING_CLAUSES] THEN
REWRITE_TAC[C_ARGUMENTS; C_RETURN; SOME_FLAGS] THEN
DISCH_THEN(REPEAT_TCL CONJUNCTS_THEN ASSUME_TAC) THEN
BIGNUM_TERMRANGE_TAC `k:num` `n:num` THEN
BIGNUM_TERMRANGE_TAC `nx:num` `a:num` THEN
(*** Degenerate k = 0 case ***)
ASM_CASES_TAC `k = 0` THENL
[UNDISCH_THEN `k = 0` SUBST_ALL_TAC THEN
REPEAT(FIRST_X_ASSUM(SUBST_ALL_TAC o MATCH_MP (ARITH_RULE
`a < 2 EXP (64 * 0) ==> a = 0`))) THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN
ENSURES_INIT_TAC "s0" THEN X86_STEPS_TAC BIGNUM_MONTREDC_EXEC (1--2) THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[ODD];
ALL_TAC] THEN
(*** Initial word-level modular inverse ***)
ENSURES_SEQUENCE_TAC `pc + 0x75`
`\s. read RSP s = stackpointer /\
read RDI s = word k /\
read RSI s = z /\
read R10 s = word nx /\
read RCX s = x /\
read R8 s = m /\
read R9 s = word p /\
bignum_from_memory (x,nx) s = a /\
bignum_from_memory (m,k) s = n /\
(ODD n ==> (n * val(read RBX s) + 1 == 0) (mod (2 EXP 64)))` THEN
CONJ_TAC THENL
[REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN ENSURES_INIT_TAC "s0" THEN
SUBGOAL_THEN `bignum_from_memory(m,k) s0 = highdigits n 0` MP_TAC THENL
[ASM_REWRITE_TAC[HIGHDIGITS_0; BIGNUM_FROM_MEMORY_BYTES];
GEN_REWRITE_TAC LAND_CONV[BIGNUM_FROM_MEMORY_EQ_HIGHDIGITS] THEN
ASM_REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES; ADD_CLAUSES] THEN
REWRITE_TAC[GSYM LOWDIGITS_1; lowdigits; MULT_CLAUSES] THEN
REWRITE_TAC[GSYM DIMINDEX_64; WORD_MOD_SIZE] THEN
REWRITE_TAC[DIMINDEX_64] THEN STRIP_TAC] THEN
X86_STEPS_TAC BIGNUM_MONTREDC_EXEC (1--9) THEN
SUBGOAL_THEN `ODD n ==> (n * val (read RBX s9) + 1 == 0) (mod 16)`
MP_TAC THENL [ASM_SIMP_TAC[WORD_NEGMODINV_SEED_LEMMA_16]; ALL_TAC] THEN
REABBREV_TAC `x0 = read RBX s9` THEN DISCH_TAC THEN
X86_STEPS_TAC BIGNUM_MONTREDC_EXEC (10--27) THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[] THEN
REWRITE_TAC[VAL_WORD_MUL; VAL_WORD_ADD; VAL_WORD; DIMINDEX_64; CONG] THEN
CONV_TAC MOD_DOWN_CONV THEN REWRITE_TAC[GSYM CONG] THEN
SUBST1_TAC(ARITH_RULE `2 EXP 64 = 16 EXP (2 EXP 4)`) THEN
DISCH_THEN(fun th -> FIRST_X_ASSUM(MP_TAC o C MATCH_MP th)) THEN
SPEC_TAC(`16`,`e:num`) THEN CONV_TAC NUM_REDUCE_CONV THEN
CONV_TAC NUMBER_RULE;
GHOST_INTRO_TAC `w:num` `\s. val(read RBX s)` THEN
REWRITE_TAC[VAL_WORD_GALOIS; DIMINDEX_64]] THEN
GLOBALIZE_PRECONDITION_TAC THEN ASM_REWRITE_TAC[] THEN
VAL_INT64_TAC `w:num` THEN
(*** Get a basic bound on k from the nonoverlapping assumptions ***)
FIRST_ASSUM(MP_TAC o MATCH_MP (ONCE_REWRITE_RULE[IMP_CONJ]
NONOVERLAPPING_IMP_SMALL_1)) THEN
ANTS_TAC THENL [CONV_TAC NUM_REDUCE_CONV; DISCH_TAC] THEN
(*** Initialization of the output buffer ***)
ENSURES_SEQUENCE_TAC `pc + 0xb2`
`\s. read RSP s = stackpointer /\
read RDI s = word k /\
read RSI s = z /\
read R10 s = word nx /\
read RCX s = x /\
read R8 s = m /\
read R9 s = word p /\
bignum_from_memory (word_add x (word (8 * k)),nx - k) s =
highdigits a k /\
bignum_from_memory (m,k) s = n /\
read (memory :> bytes64 stackpointer) s = word w /\
bignum_from_memory (z,k) s = lowdigits a k /\
read R15 s = word 0` THEN
CONJ_TAC THENL
[ASM_CASES_TAC `nx = 0` THENL
[UNDISCH_THEN `nx = 0` SUBST_ALL_TAC THEN
REPEAT(FIRST_X_ASSUM(SUBST_ALL_TAC o MATCH_MP (ARITH_RULE
`a < 2 EXP (64 * 0) ==> a = 0`))) THEN
ENSURES_WHILE_UP_TAC `k:num` `pc + 0xa3` `pc + 0xaa`
`\i s. read RSP s = stackpointer /\
read RDI s = word k /\
read RSI s = z /\
read R10 s = word 0 /\
read RCX s = x /\
read R8 s = m /\
read R9 s = word p /\
bignum_from_memory (m,k) s = n /\
read (memory :> bytes64 stackpointer) s = word w /\
read R14 s = word i /\
read RBX s = word 0 /\
bignum_from_memory (z,i) s = 0` THEN
ASM_REWRITE_TAC[] THEN REPEAT CONJ_TAC THENL
[X86_SIM_TAC BIGNUM_MONTREDC_EXEC (1--7) THEN
ASM_SIMP_TAC[LE_1; GSYM BIGNUM_FROM_MEMORY_BYTES] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_TRIVIAL];
X_GEN_TAC `i:num` THEN STRIP_TAC THEN VAL_INT64_TAC `i:num` THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_STEP] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN ENSURES_INIT_TAC "s0" THEN
X86_STEPS_TAC BIGNUM_MONTREDC_EXEC (1--2) THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[GSYM WORD_ADD] THEN
ARITH_TAC;
X_GEN_TAC `i:num` THEN STRIP_TAC THEN VAL_INT64_TAC `i:num` THEN
X86_SIM_TAC BIGNUM_MONTREDC_EXEC (1--2);
REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN ENSURES_INIT_TAC "s0" THEN
X86_STEPS_TAC BIGNUM_MONTREDC_EXEC (1--3) THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[LOWDIGITS_TRIVIAL] THEN
REWRITE_TAC[LE; GSYM BIGNUM_FROM_MEMORY_BYTES] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_TRIVIAL; SUB_0] THEN
REWRITE_TAC[HIGHDIGITS_TRIVIAL]];
ALL_TAC] THEN
(*** Copyloop ***)
ENSURES_WHILE_UP_TAC `MIN k nx` `pc + 0x8b` `pc + 0x96`
`\i s. read RSP s = stackpointer /\
read RDI s = word k /\
read RSI s = z /\
read R10 s = word nx /\
read RCX s = x /\
read R8 s = m /\
read R9 s = word p /\
bignum_from_memory (m,k) s = n /\
read (memory :> bytes64 stackpointer) s = word w /\
read R14 s = word i /\
read RBX s = word(MIN k nx) /\
bignum_from_memory(word_add x (word(8 * i)),nx - i) s =
highdigits a i /\
bignum_from_memory (z,i) s = lowdigits a i` THEN
ASM_REWRITE_TAC[] THEN REPEAT CONJ_TAC THENL
[ASM_REWRITE_TAC[ARITH_RULE `MIN a b = 0 <=> a = 0 \/ b = 0`];
X86_SIM_TAC BIGNUM_MONTREDC_EXEC (1--7) THEN
MATCH_MP_TAC(TAUT `q /\ (q ==> p) /\ r ==> p /\ q /\ r`) THEN
CONJ_TAC THENL [REWRITE_TAC[MIN] THEN MESON_TAC[NOT_LT]; ALL_TAC] THEN
REWRITE_TAC[GSYM BIGNUM_FROM_MEMORY_BYTES; LOWDIGITS_0] THEN
REWRITE_TAC[MULT_CLAUSES; WORD_ADD_0; SUB_0; HIGHDIGITS_0] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_TRIVIAL] THEN
ASM_REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN
DISCH_THEN SUBST1_TAC THEN VAL_INT64_TAC `MIN k nx` THEN
ASM_REWRITE_TAC[ARITH_RULE `MIN a b = 0 <=> a = 0 \/ b = 0`];
X_GEN_TAC `i:num` THEN STRIP_TAC THEN VAL_INT64_TAC `i:num` THEN
SUBGOAL_THEN `i:num < nx /\ i < k` STRIP_ASSUME_TAC THENL
[SIMPLE_ARITH_TAC; ALL_TAC] THEN
GEN_REWRITE_TAC (RATOR_CONV o LAND_CONV o ONCE_DEPTH_CONV)
[BIGNUM_FROM_MEMORY_OFFSET_EQ_HIGHDIGITS] THEN
ASM_REWRITE_TAC[SUB_EQ_0; GSYM NOT_LT] THEN
REWRITE_TAC[ARITH_RULE `k - i - 1 = k - (i + 1)`] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_STEP] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN
ENSURES_INIT_TAC "s0" THEN
X86_STEPS_TAC BIGNUM_MONTREDC_EXEC (1--3) THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[GSYM WORD_ADD] THEN
SIMP_TAC[VAL_WORD_EQ; DIMINDEX_64; BIGDIGIT_BOUND] THEN
REWRITE_TAC[LOWDIGITS_CLAUSES] THEN ARITH_TAC;
X_GEN_TAC `i:num` THEN STRIP_TAC THEN VAL_INT64_TAC `i:num` THEN
X86_SIM_TAC BIGNUM_MONTREDC_EXEC (1--2) THEN
VAL_INT64_TAC `MIN k nx` THEN ASM_REWRITE_TAC[];
ALL_TAC] THEN
(*** Now consider the cases again ***)
ASM_CASES_TAC `k:num <= nx` THENL
[ASM_SIMP_TAC[ARITH_RULE `k <= nx ==> MIN k nx = k`] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN
ENSURES_INIT_TAC "s0" THEN
X86_STEPS_TAC BIGNUM_MONTREDC_EXEC (1--5) THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[];
RULE_ASSUM_TAC(REWRITE_RULE[NOT_LE]) THEN
ASM_SIMP_TAC[ARITH_RULE `nx < k ==> MIN k nx = nx`]] THEN
(*** Padloop following copyloop ***)
ENSURES_WHILE_AUP_TAC `nx:num` `k:num` `pc + 0xa3` `pc + 0xaa`
`\i s. read RSP s = stackpointer /\
read RDI s = word k /\
read RSI s = z /\
read R10 s = word nx /\
read RCX s = x /\
read R8 s = m /\
read R9 s = word p /\
bignum_from_memory (m,k) s = n /\
read (memory :> bytes64 stackpointer) s = word w /\
read R14 s = word i /\
read RBX s = word 0 /\
bignum_from_memory (z,i) s = lowdigits a i` THEN
ASM_REWRITE_TAC[] THEN REPEAT CONJ_TAC THENL
[X86_SIM_TAC BIGNUM_MONTREDC_EXEC (1--5);
X_GEN_TAC `i:num` THEN STRIP_TAC THEN VAL_INT64_TAC `i:num` THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_STEP] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN ENSURES_INIT_TAC "s0" THEN
X86_STEPS_TAC BIGNUM_MONTREDC_EXEC (1--2) THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[GSYM WORD_ADD] THEN
SIMP_TAC[VAL_WORD_0; LOWDIGITS_CLAUSES; MULT_CLAUSES; ADD_CLAUSES] THEN
MATCH_MP_TAC(NUM_RING `d = 0 ==> a = e * d + a`) THEN
MATCH_MP_TAC BIGDIGIT_ZERO THEN
TRANS_TAC LTE_TRANS `2 EXP (64 * nx)` THEN
ASM_REWRITE_TAC[LE_EXP] THEN UNDISCH_TAC `nx:num <= i` THEN ARITH_TAC;
X_GEN_TAC `i:num` THEN STRIP_TAC THEN VAL_INT64_TAC `i:num` THEN
X86_SIM_TAC BIGNUM_MONTREDC_EXEC (1--2);
X86_SIM_TAC BIGNUM_MONTREDC_EXEC (1--3) THEN
REWRITE_TAC[GSYM BIGNUM_FROM_MEMORY_BYTES] THEN
ASM_SIMP_TAC[ARITH_RULE `nx < k ==> nx - k = 0`] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_TRIVIAL] THEN
CONV_TAC SYM_CONV THEN MATCH_MP_TAC HIGHDIGITS_ZERO THEN
TRANS_TAC LTE_TRANS `2 EXP (64 * nx)` THEN
ASM_REWRITE_TAC[LE_EXP] THEN UNDISCH_TAC `nx:num < k` THEN ARITH_TAC];
ALL_TAC] THEN
(*** Break at "corrective" to share degenerate cases, corrective ending ***)
ENSURES_SEQUENCE_TAC `pc + 0x12f`
`\s. read RSP s = stackpointer /\
read RDI s = word k /\
read RSI s = z /\
read R8 s = m /\
bignum_from_memory (m,k) s = n /\
?q r.
q < 2 EXP (64 * p) /\
r < 2 EXP (64 * p) /\
2 EXP (64 * p) *
(2 EXP (64 * k) * val(read R15 s) + bignum_from_memory(z,k) s) + r =
q * n + lowdigits a (k + p) /\
(ODD n ==> r = 0)` THEN
CONJ_TAC THENL
[ALL_TAC;
GHOST_INTRO_TAC `cout:num` `\s. val(read R15 s)` THEN
GHOST_INTRO_TAC `mm:num` `bignum_from_memory(z,k)` THEN
BIGNUM_TERMRANGE_TAC `k:num` `mm:num` THEN
ASM_SIMP_TAC[LOWDIGITS_SELF] THEN
GLOBALIZE_PRECONDITION_TAC THEN ASM_REWRITE_TAC[] THEN
FIRST_X_ASSUM(X_CHOOSE_THEN `q:num` (X_CHOOSE_THEN `r:num`
STRIP_ASSUME_TAC)) THEN
SUBGOAL_THEN `cout < 2` MP_TAC THENL
[SUBGOAL_THEN `q * n + lowdigits a (k + p) < 2 EXP (64 * (k + p)) * 2`
MP_TAC THENL
[MATCH_MP_TAC(ARITH_RULE `x < e /\ y < e ==> x + y < e * 2`) THEN
REWRITE_TAC[LOWDIGITS_BOUND] THEN
REWRITE_TAC[ARITH_RULE `64 * (k + p) = 64 * p + 64 * k`] THEN
ASM_SIMP_TAC[LT_MULT2; EXP_ADD];
FIRST_X_ASSUM(fun th ->
GEN_REWRITE_TAC (LAND_CONV o LAND_CONV) [SYM th]) THEN
REWRITE_TAC[LEFT_ADD_DISTRIB; MULT_ASSOC; GSYM ADD_ASSOC] THEN
REWRITE_TAC[ARITH_RULE `64 * k + 64 * p = 64 * (p + k)`] THEN
DISCH_THEN(MP_TAC o MATCH_MP (ARITH_RULE
`a + b:num < c ==> a < c`)) THEN
REWRITE_TAC[GSYM EXP_ADD; GSYM LEFT_ADD_DISTRIB] THEN
REWRITE_TAC[LT_MULT_LCANCEL; EXP_EQ_0; ARITH_EQ]];
GEN_REWRITE_TAC LAND_CONV [NUM_AS_BITVAL_ALT]] THEN
DISCH_THEN(X_CHOOSE_THEN `c0:bool` SUBST_ALL_TAC) THEN
REWRITE_TAC[VAL_EQ_BITVAL] THEN
(*** Comparison operation "cmploop" ***)
ENSURES_WHILE_PUP_TAC `k:num` `pc + 0x135` `pc + 0x143`
`\i s. (read RDI s = word k /\
read RSI s = z /\
read R8 s = m /\
bignum_from_memory (z,k) s = mm /\
bignum_from_memory (m,k) s = n /\
read RBX s = word i /\
read R10 s = word(k - i) /\
read R15 s = word(bitval c0) /\
bignum_from_memory (word_add z (word(8 * i)),k - i) s =
highdigits mm i /\
bignum_from_memory (word_add m (word(8 * i)),k - i) s =
highdigits n i /\
(read CF s <=> lowdigits mm i < lowdigits n i)) /\
(read ZF s <=> i = k)` THEN
ASM_REWRITE_TAC[] THEN REPEAT CONJ_TAC THENL
[REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES; SUB_0] THEN
ENSURES_INIT_TAC "s0" THEN X86_STEPS_TAC BIGNUM_MONTREDC_EXEC (1--2) THEN
ENSURES_FINAL_STATE_TAC THEN
ASM_REWRITE_TAC[LOWDIGITS_0; HIGHDIGITS_0; LT_REFL] THEN
ASM_REWRITE_TAC[MULT_CLAUSES; ADD_CLAUSES; WORD_ADD_0];
X_GEN_TAC `i:num` THEN STRIP_TAC THEN VAL_INT64_TAC `i:num` THEN
GHOST_INTRO_TAC `cin:bool` `read CF` THEN
GEN_REWRITE_TAC (RATOR_CONV o LAND_CONV o ONCE_DEPTH_CONV)
[BIGNUM_FROM_MEMORY_OFFSET_EQ_HIGHDIGITS] THEN
ASM_REWRITE_TAC[SUB_EQ_0; GSYM NOT_LT] THEN
REWRITE_TAC[ARITH_RULE `k - i - 1 = k - (i + 1)`] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_STEP] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN
ENSURES_INIT_TAC "s0" THEN
X86_STEPS_TAC BIGNUM_MONTREDC_EXEC (1--4) THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[] THEN
REWRITE_TAC[WORD_ADD] THEN REPEAT CONJ_TAC THENL
[REWRITE_TAC[ARITH_RULE `p - (n + 1) = p - n - 1`] THEN
GEN_REWRITE_TAC RAND_CONV [WORD_SUB] THEN
ASM_REWRITE_TAC[ARITH_RULE `1 <= p - n <=> n < p`];
REWRITE_TAC[LOWDIGITS_CLAUSES];
REWRITE_TAC[VAL_EQ_0; WORD_SUB_EQ_0] THEN
VAL_INT64_TAC `k - i:num` THEN
ASM_REWRITE_TAC[GSYM VAL_EQ; VAL_WORD_1] THEN ARITH_TAC] THEN
SIMP_TAC[LEXICOGRAPHIC_LT; LOWDIGITS_BOUND] THEN
SIMP_TAC[VAL_WORD_EQ; DIMINDEX_64; BIGDIGIT_BOUND] THEN
POP_ASSUM_LIST(K ALL_TAC) THEN REWRITE_TAC[bitval] THEN ARITH_TAC;
X_GEN_TAC `i:num` THEN STRIP_TAC THEN VAL_INT64_TAC `i:num` THEN
ASM_REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN
ENSURES_INIT_TAC "s0" THEN X86_STEPS_TAC BIGNUM_MONTREDC_EXEC [1] THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[];
ASM_SIMP_TAC[LOWDIGITS_SELF; HIGHDIGITS_ZERO; SUB_REFL] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_TRIVIAL]] THEN
(*** Corrective subtraction "corrloop" ***)
ABBREV_TAC `c <=> n <= 2 EXP (64 * k) * bitval c0 + mm` THEN
ENSURES_WHILE_UP_TAC `k:num` `pc + 0x155` `pc + 0x169`
`\i s. read RDI s = word k /\
read RSI s = z /\
read R8 s = m /\
read RBP s = word_neg(word(bitval c)) /\
read RBX s = word i /\
val(word_neg(read R12 s)) <= 1 /\
bignum_from_memory (word_add z (word(8 * i)),k - i) s =
highdigits mm i /\
bignum_from_memory (word_add m (word(8 * i)),k - i) s =
highdigits n i /\
&(bignum_from_memory(z,i) s):real =
&2 pow (64 * i) * &(val(word_neg(read R12 s))) +
&(lowdigits mm i) - &(bitval c) * &(lowdigits n i)` THEN
ASM_REWRITE_TAC[] THEN REPEAT CONJ_TAC THENL
[REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN
ENSURES_INIT_TAC "s0" THEN X86_STEPS_TAC BIGNUM_MONTREDC_EXEC (1--6) THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[] THEN
REWRITE_TAC[WORD_SUB_LZERO; SUB_0; GSYM BIGNUM_FROM_MEMORY_BYTES] THEN
REWRITE_TAC[WORD_ADD_0; MULT_CLAUSES; BITVAL_CLAUSES; WORD_NEG_0] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_TRIVIAL; LOWDIGITS_0; VAL_WORD_0] THEN
ASM_REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES; HIGHDIGITS_0; LE_0] THEN
REWRITE_TAC[REAL_MUL_RZERO; REAL_ADD_LID; REAL_SUB_REFL] THEN
REWRITE_TAC[WORD_NOT_MASK] THEN EXPAND_TAC "c" THEN
REPLICATE_TAC 3 AP_TERM_TAC THEN REWRITE_TAC[NOT_LT; ADD_CLAUSES] THEN
REWRITE_TAC[VAL_WORD_BITVAL] THEN BOOL_CASES_TAC `c0:bool` THEN
REWRITE_TAC[BITVAL_CLAUSES; ADD_CLAUSES; MULT_CLAUSES] THEN
ASM_SIMP_TAC[ARITH_RULE `n:num < e ==> n <= e + m`; BITVAL_BOUND] THEN
REWRITE_TAC[CONJUNCT1 LE; BITVAL_EQ_0; NOT_LT];
X_GEN_TAC `i:num` THEN STRIP_TAC THEN VAL_INT64_TAC `i:num` THEN
GHOST_INTRO_TAC `cval:num` `\s. val(word_neg(read R12 s))` THEN
GLOBALIZE_PRECONDITION_TAC THEN
FIRST_X_ASSUM(X_CHOOSE_THEN `cin:bool` SUBST_ALL_TAC o
GEN_REWRITE_RULE I [NUM_AS_BITVAL]) THEN
REWRITE_TAC[VAL_EQ_BITVAL] THEN
REWRITE_TAC[WORD_RULE `word_neg x:int64 = y <=> x = word_neg y`] THEN
GEN_REWRITE_TAC (RATOR_CONV o LAND_CONV o ONCE_DEPTH_CONV)
[BIGNUM_FROM_MEMORY_OFFSET_EQ_HIGHDIGITS] THEN
ASM_REWRITE_TAC[SUB_EQ_0; GSYM NOT_LT] THEN
REWRITE_TAC[ARITH_RULE `k - i - 1 = k - (i + 1)`] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_STEP] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN
ENSURES_INIT_TAC "s0" THEN
X86_ACCSTEPS_TAC BIGNUM_MONTREDC_EXEC [4] (1--6) THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[GSYM WORD_ADD] THEN
REWRITE_TAC[WORD_NEG_NEG; VAL_WORD_BITVAL; BITVAL_BOUND] THEN
ACCUMULATOR_POP_ASSUM_LIST(MP_TAC o end_itlist CONJ) THEN
SIMP_TAC[VAL_WORD_EQ; DIMINDEX_64; BIGDIGIT_BOUND] THEN
REWRITE_TAC[WORD_ADD; WORD_NEG_NEG; VAL_WORD_BITVAL; WORD_BITVAL_EQ_0;
LOWDIGITS_CLAUSES; WORD_NEG_EQ_0; BITVAL_BOUND; NOT_LT] THEN
REWRITE_TAC[WORD_AND_MASK] THEN COND_CASES_TAC THEN
REWRITE_TAC[GSYM REAL_OF_NUM_CLAUSES] THEN ASM_REWRITE_TAC[NOT_LT] THEN
SIMP_TAC[VAL_WORD_EQ; DIMINDEX_64; BIGDIGIT_BOUND; VAL_WORD_0;
BITVAL_CLAUSES; ARITH_RULE `64 * (i + 1) = 64 * i + 64`] THEN
REWRITE_TAC[REAL_POW_ADD] THEN CONV_TAC REAL_RING;
X_GEN_TAC `i:num` THEN STRIP_TAC THEN VAL_INT64_TAC `i:num` THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN
ENSURES_INIT_TAC "s0" THEN X86_STEPS_TAC BIGNUM_MONTREDC_EXEC (1--2) THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[];
ASM_SIMP_TAC[BIGNUM_FROM_MEMORY_BYTES; LOWDIGITS_SELF] THEN
ENSURES_INIT_TAC "s0" THEN X86_STEPS_TAC BIGNUM_MONTREDC_EXEC (1--2) THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[VAL_WORD_SUB_EQ_0] THEN
STRIP_TAC THEN UNDISCH_TAC `ODD n ==> r = 0` THEN
ASM_REWRITE_TAC[] THEN DISCH_THEN SUBST_ALL_TAC THEN
RULE_ASSUM_TAC(REWRITE_RULE[ADD_CLAUSES])] THEN
FIRST_ASSUM(ASSUME_TAC o MATCH_MP (MESON[ODD] `ODD n ==> ~(n = 0)`)) THEN
TRANS_TAC EQ_TRANS `(2 EXP (64 * k) * bitval c0 + mm) MOD n` THEN
CONJ_TAC THENL
[REWRITE_TAC[GSYM REAL_OF_NUM_CLAUSES] THEN
MATCH_MP_TAC EQUAL_FROM_CONGRUENT_REAL THEN
MAP_EVERY EXISTS_TAC [`64 * k`; `&0:real`] THEN CONJ_TAC THENL
[REWRITE_TAC[REAL_OF_NUM_CLAUSES; GSYM BIGNUM_FROM_MEMORY_BYTES] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_BOUND; LE_0];
REWRITE_TAC[INTEGER_CLOSED; REAL_POS]] THEN
CONJ_TAC THENL
[REWRITE_TAC[REAL_OF_NUM_CLAUSES] THEN TRANS_TAC LT_TRANS `n:num` THEN
ASM_REWRITE_TAC[MOD_LT_EQ];
ALL_TAC] THEN
MP_TAC(SPECL [`2 EXP (64 * k) * bitval c0 + mm`; `n:num`]
MOD_CASES) THEN
ANTS_TAC THENL
[MATCH_MP_TAC(MESON[LT_MULT_LCANCEL]
`!e. ~(e = 0) /\ e * a < e * b ==> a < b`) THEN
EXISTS_TAC `2 EXP (64 * p)` THEN
ASM_REWRITE_TAC[EXP_EQ_0; ARITH_EQ] THEN
MATCH_MP_TAC(ARITH_RULE
`q * n < e * n /\ aa <= e * n ==> q * n + aa < e * 2 * n`) THEN
ASM_REWRITE_TAC[LT_MULT_RCANCEL];
DISCH_THEN SUBST1_TAC] THEN
REWRITE_TAC[GSYM NOT_LE; COND_SWAP] THEN ONCE_REWRITE_TAC[COND_RAND] THEN
SIMP_TAC[GSYM REAL_OF_NUM_SUB] THEN
ASM_REWRITE_TAC[GSYM REAL_OF_NUM_CLAUSES] THEN
ASM_CASES_TAC `c:bool` THEN ASM_REWRITE_TAC[BITVAL_CLAUSES] THEN
REWRITE_TAC[ONCE_REWRITE_RULE[REAL_MUL_SYM] real_div] THEN
REWRITE_TAC[REAL_ADD_LDISTRIB; REAL_SUB_LDISTRIB; REAL_MUL_ASSOC] THEN
SIMP_TAC[REAL_MUL_LINV; REAL_POW_EQ_0; REAL_OF_NUM_EQ; ARITH_EQ] THEN
REAL_INTEGER_TAC;
REWRITE_TAC[GSYM CONG] THEN
FIRST_ASSUM(MATCH_MP_TAC o MATCH_MP (NUMBER_RULE
`e * x:num = q * n + ab
==> (i * e == 1) (mod n)
==> (x == i * ab) (mod n)`)) THEN
ASM_REWRITE_TAC[INVERSE_MOD_LMUL_EQ; COPRIME_REXP; COPRIME_2]]] THEN
(*** Another semi-degenerate case p = 0 ***)
ASM_CASES_TAC `p = 0` THENL
[UNDISCH_THEN `p = 0` SUBST_ALL_TAC THEN
REPEAT(FIRST_X_ASSUM(SUBST_ALL_TAC o MATCH_MP (ARITH_RULE
`a < 2 EXP (64 * 0) ==> a = 0`))) THEN
X86_SIM_TAC BIGNUM_MONTREDC_EXEC (1--2) THEN
REPEAT(EXISTS_TAC `0`) THEN
REWRITE_TAC[MULT_CLAUSES; EXP; ADD_CLAUSES] THEN ARITH_TAC;
ALL_TAC] THEN
(*** Setup of the main loop ***)
ENSURES_WHILE_UP_TAC `p:num` `pc + 0xba` `pc + 0x12a`
`\i s. read RSP s = stackpointer /\
read RDI s = word k /\
read RSI s = z /\
read R10 s = word nx /\
read RCX s = x /\
read R8 s = m /\
read R9 s = word p /\
read (memory :> bytes64 stackpointer) s = word w /\
read R14 s = word i /\
bignum_from_memory (m,k) s = n /\
bignum_from_memory(word_add x (word(8 * (k + i))),nx - (k + i)) s =
highdigits a (k + i) /\
?q r. q < 2 EXP (64 * i) /\ r < 2 EXP (64 * i) /\
2 EXP (64 * i) *
(2 EXP (64 * k) * val(read R15 s) +
bignum_from_memory(z,k) s) +
r =
q * n + lowdigits a (k + i) /\
(ODD n ==> r = 0)` THEN
ASM_REWRITE_TAC[] THEN REPEAT CONJ_TAC THENL
[X86_SIM_TAC BIGNUM_MONTREDC_EXEC (1--3) THEN
ASM_REWRITE_TAC[ADD_CLAUSES; VAL_WORD_0] THEN
REPEAT(EXISTS_TAC `0`) THEN ARITH_TAC;
ALL_TAC; (*** This is the main loop invariant: save for later ***)
X_GEN_TAC `i:num` THEN STRIP_TAC THEN VAL_INT64_TAC `i:num` THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN
ENSURES_INIT_TAC "s0" THEN X86_STEPS_TAC BIGNUM_MONTREDC_EXEC (1--2) THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[];
X86_SIM_TAC BIGNUM_MONTREDC_EXEC (1--2)] THEN
(*** Start on the main outer loop invariant ***)
X_GEN_TAC `i:num` THEN STRIP_TAC THEN VAL_INT64_TAC `i:num` THEN
GHOST_INTRO_TAC `cout:num` `\s. val(read R15 s)` THEN
GHOST_INTRO_TAC `z1:num` `bignum_from_memory(z,k)` THEN
BIGNUM_TERMRANGE_TAC `k:num` `z1:num` THEN
GLOBALIZE_PRECONDITION_TAC THEN ASM_REWRITE_TAC[] THEN
FIRST_X_ASSUM(X_CHOOSE_THEN `q:num` (X_CHOOSE_THEN `r:num`
STRIP_ASSUME_TAC)) THEN
REWRITE_TAC[VAL_WORD_GALOIS; DIMINDEX_64] THEN
GLOBALIZE_PRECONDITION_TAC THEN
* * The initial prelude of the reduction * *
ABBREV_TAC `q0 = (w * z1) MOD 2 EXP 64` THEN
SUBGOAL_THEN `q0 < 2 EXP 64 /\ val(word q0:int64) = q0`
STRIP_ASSUME_TAC THENL
[EXPAND_TAC "q0" THEN CONJ_TAC THENL [ARITH_TAC; ALL_TAC] THEN
REWRITE_TAC[VAL_WORD; DIMINDEX_64; MOD_MOD_REFL];
ALL_TAC] THEN
ENSURES_SEQUENCE_TAC `pc + 0xd9`
`\s. read RSP s = stackpointer /\
read RDI s = word k /\
read RSI s = z /\
read R10 s = word nx /\
read RCX s = x /\
read R8 s = m /\
read R9 s = word p /\
read (memory :> bytes64 stackpointer) s = word w /\
read R14 s = word i /\
bignum_from_memory (m,k) s = n /\
bignum_from_memory (word_add x (word (8 * (k + i))),nx - (k + i)) s =
highdigits a (k + i) /\
read R15 s = word cout /\
bignum_from_memory (z,k) s = z1 /\
read RBP s = word q0 /\
read RBX s = word 1 /\
read R13 s = word k /\
2 EXP 64 * (bitval(read CF s) + val(read R11 s)) + val(read RAX s) =
q0 * bigdigit n 0 + bigdigit z1 0` THEN
CONJ_TAC THENL
[REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN ENSURES_INIT_TAC "s0" THEN
SUBGOAL_THEN
`bignum_from_memory(m,k) s0 = highdigits n 0 /\
bignum_from_memory(z,k) s0 = highdigits z1 0`
MP_TAC THENL
[ASM_REWRITE_TAC[HIGHDIGITS_0; BIGNUM_FROM_MEMORY_BYTES];
GEN_REWRITE_TAC (LAND_CONV o BINOP_CONV)
[BIGNUM_FROM_MEMORY_EQ_HIGHDIGITS] THEN
ASM_REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES; ADD_CLAUSES] THEN
STRIP_TAC] THEN
X86_ACCSTEPS_TAC BIGNUM_MONTREDC_EXEC [5;6] (1--9) THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[] THEN
MATCH_MP_TAC(TAUT `p /\ (p ==> q) ==> p /\ q`) THEN CONJ_TAC THENL
[UNDISCH_THEN `(w * z1) MOD 2 EXP 64 = q0` (SUBST1_TAC o SYM) THEN
REWRITE_TAC[GSYM WORD_MUL] THEN ONCE_REWRITE_TAC[GSYM WORD_MOD_SIZE] THEN
REWRITE_TAC[GSYM LOWDIGITS_1; lowdigits; MULT_CLAUSES] THEN
REWRITE_TAC[ADD_CLAUSES; DIMINDEX_64; VAL_WORD] THEN
CONV_TAC MOD_DOWN_CONV THEN REWRITE_TAC[MULT_SYM];
DISCH_THEN SUBST_ALL_TAC] THEN
ASM_REWRITE_TAC[WORD_SUB; ARITH_RULE `1 <= k <=> ~(k = 0)`] THEN
REWRITE_TAC[GSYM REAL_OF_NUM_CLAUSES] THEN
ACCUMULATOR_POP_ASSUM_LIST(MP_TAC o end_itlist CONJ o DECARRY_RULE) THEN
DISCH_THEN(fun th -> REWRITE_TAC[th]) THEN
ASM_SIMP_TAC[VAL_WORD_EQ; DIMINDEX_64; BIGDIGIT_BOUND] THEN
REAL_ARITH_TAC;
ALL_TAC] THEN
(*** Break at "montend" to share the end reasoning ***)
GHOST_INTRO_TAC `r0:num` `\s. val(read RAX s)` THEN
REWRITE_TAC[VAL_WORD_GALOIS; DIMINDEX_64] THEN
GLOBALIZE_PRECONDITION_TAC THEN
ENSURES_SEQUENCE_TAC `pc + 0x102`
`\s. read RSP s = stackpointer /\
read RDI s = word k /\
read RSI s = z /\
read R10 s = word nx /\
read RCX s = x /\
read R8 s = m /\
read R9 s = word p /\
read (memory :> bytes64 stackpointer) s = word w /\
read R14 s = word i /\
bignum_from_memory (m,k) s = n /\
bignum_from_memory (word_add x (word (8 * (k + i))),nx - (k + i)) s =
highdigits a (k + i) /\
read R15 s = word cout /\
read RBP s = word q0 /\
read RBX s = word k /\
2 EXP (64 * k) * (bitval(read CF s) + val(read R11 s)) +
2 EXP 64 * bignum_from_memory (z,k - 1) s +
r0 =
lowdigits z1 k + q0 * lowdigits n k` THEN
CONJ_TAC THENL
[ASM_CASES_TAC `k = 1` THENL
[UNDISCH_THEN `k = 1` SUBST_ALL_TAC THEN
X86_SIM_TAC BIGNUM_MONTREDC_EXEC (1--2) THEN
REWRITE_TAC[GSYM BIGNUM_FROM_MEMORY_BYTES] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_TRIVIAL] THEN
ASM_REWRITE_TAC[MULT_CLAUSES; ADD_CLAUSES] THEN
REWRITE_TAC[LOWDIGITS_1] THEN ARITH_TAC;
ALL_TAC] THEN
* * The reduction loop * *
VAL_INT64_TAC `k - 1` THEN
ENSURES_WHILE_PAUP_TAC `1` `k:num` `pc + 0xde` `pc + 0x100`
`\j s. (read RSP s = stackpointer /\
read RDI s = word k /\
read RSI s = z /\
read R10 s = word nx /\
read RCX s = x /\
read R8 s = m /\
read R9 s = word p /\
read (memory :> bytes64 stackpointer) s = word w /\
read R14 s = word i /\
bignum_from_memory (m,k) s = n /\
bignum_from_memory
(word_add x (word (8 * (k + i))),nx - (k + i)) s =
highdigits a (k + i) /\
read R15 s = word cout /\
read RBP s = word q0 /\
read RBX s = word j /\
read R13 s = word(k - j) /\
bignum_from_memory(word_add z (word (8 * j)),k - j) s =
highdigits z1 j /\
bignum_from_memory(word_add m (word (8 * j)),k - j) s =
highdigits n j /\
2 EXP (64 * j) * (bitval(read CF s) + val(read R11 s)) +
2 EXP 64 * bignum_from_memory(z,j-1) s + r0 =
lowdigits z1 j + q0 * lowdigits n j) /\
(read ZF s <=> j = k)` THEN
REPEAT CONJ_TAC THENL
[ASM_REWRITE_TAC[ARITH_RULE `1 < k <=> ~(k = 0 \/ k = 1)`];
REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN ENSURES_INIT_TAC "s0" THEN
X86_STEPS_TAC BIGNUM_MONTREDC_EXEC (1--2) THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[VAL_WORD_SUB_EQ_0] THEN
ASM_REWRITE_TAC[ARITH_RULE `k <= 1 <=> k = 0 \/ k = 1`] THEN
ASM_REWRITE_TAC[VAL_WORD_1; ARITH_RULE `k <= 1 <=> k = 0 \/ k = 1`] THEN
ASM_REWRITE_TAC[WORD_SUB; ARITH_RULE `1 <= k <=> ~(k = 0)`] THEN
REWRITE_TAC[GSYM BIGNUM_FROM_MEMORY_BYTES] THEN
REWRITE_TAC[GSYM BIGNUM_FROM_MEMORY_DIV; BIGNUM_FROM_MEMORY_TRIVIAL] THEN
ASM_REWRITE_TAC[GSYM highdigits; BIGNUM_FROM_MEMORY_BYTES] THEN
ASM_REWRITE_TAC[MULT_CLAUSES; ADD_CLAUSES; LOWDIGITS_1] THEN ARITH_TAC;
X_GEN_TAC `j:num` THEN STRIP_TAC THEN
MAP_EVERY VAL_INT64_TAC [`j:num`; `j - 1`] THEN
SUBGOAL_THEN `word_sub (word j) (word 1):int64 = word(j - 1)`
ASSUME_TAC THENL [ASM_REWRITE_TAC[WORD_SUB]; ALL_TAC] THEN
GHOST_INTRO_TAC `cin:bool` `read CF` THEN
GHOST_INTRO_TAC `hin:int64` `read R11` THEN
MP_TAC(GENL [`x:int64`; `a:num`]
(ISPECL [`x:int64`; `k - j:num`; `a:num`; `j:num`]
BIGNUM_FROM_MEMORY_OFFSET_EQ_HIGHDIGITS)) THEN
ASM_REWRITE_TAC[ARITH_RULE `k - j = 0 <=> ~(j < k)`] THEN
DISCH_THEN(fun th -> ONCE_REWRITE_TAC[th]) THEN
REWRITE_TAC[ARITH_RULE `k - j - 1 = k - (j + 1)`] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_STEP] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN
ENSURES_INIT_TAC "s0" THEN
UNDISCH_THEN `val(word q0:int64) = q0` (K ALL_TAC) THEN
SUBGOAL_THEN `nonoverlapping (word_add z (word (8 * (j - 1))):int64,8)
(word_add x (word (8 * (k + i))),
8 * (nx - (k + i)))`
MP_TAC THEN REWRITE_TAC[NONOVERLAPPING_CLAUSES] THENL
[ASM_CASES_TAC `nx - (k + i) = 0` THEN
ASM_SIMP_TAC[MULT_CLAUSES; NONOVERLAPPING_MODULO_TRIVIAL] THEN
RULE_ASSUM_TAC(REWRITE_RULE[SUB_EQ_0; NOT_LE]) THEN
FIRST_X_ASSUM(DISJ_CASES_THEN2 SUBST_ALL_TAC MP_TAC) THENL
[ALL_TAC;
GEN_REWRITE_TAC LAND_CONV [NONOVERLAPPING_MODULO_SYM] THEN
MATCH_MP_TAC(ONCE_REWRITE_RULE[IMP_CONJ_ALT]
NONOVERLAPPING_MODULO_SUBREGIONS) THEN
CONJ_TAC THEN CONTAINED_TAC] THEN
SUBGOAL_THEN
`word_add z (word (8 * (k + i))):int64 =
word_add (word_add z (word(8 * (j - 1))))
(word(8 + 8 * ((k + i) - j)))`
SUBST1_TAC THENL
[REWRITE_TAC[GSYM WORD_ADD_ASSOC; GSYM WORD_ADD] THEN
AP_TERM_TAC THEN AP_TERM_TAC THEN SIMPLE_ARITH_TAC;
NONOVERLAPPING_TAC];
DISCH_TAC] THEN
ABBREV_TAC `j' = j - 1` THEN
SUBGOAL_THEN `j = j' + 1` SUBST_ALL_TAC THENL
[EXPAND_TAC "j'" THEN UNDISCH_TAC `1 <= j` THEN ARITH_TAC;
ALL_TAC] THEN
RULE_ASSUM_TAC(REWRITE_RULE[ARITH_RULE `(j' + 1) + 1 = j' + 2`]) THEN
REWRITE_TAC[ARITH_RULE `(j' + 1) + 1 = j' + 2`] THEN
MP_TAC(SPEC `j':num` WORD_INDEX_WRAP) THEN DISCH_TAC THEN
X86_ACCSTEPS_TAC BIGNUM_MONTREDC_EXEC [1;4] (1--5) THEN
RULE_ASSUM_TAC(REWRITE_RULE[WORD_RULE
`word_sub x (word_neg y):int64 = word_add x y`]) THEN
ACCUMULATE_ARITH_TAC "s5" THEN
X86_ACCSTEPS_TAC BIGNUM_MONTREDC_EXEC [6] (6--10) THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[] THEN
CONJ_TAC THENL [CONV_TAC WORD_RULE; ALL_TAC] THEN
MATCH_MP_TAC(TAUT `p /\ (p ==> q) ==> p /\ q`) THEN CONJ_TAC THENL
[REWRITE_TAC[ARITH_RULE `k - (j + 2) = k - (j + 1) - 1`] THEN
GEN_REWRITE_TAC RAND_CONV [WORD_SUB] THEN
ASM_REWRITE_TAC[ARITH_RULE `1 <= k - (j + 1) <=> j + 1 < k`];
DISCH_THEN SUBST1_TAC] THEN
CONJ_TAC THENL
[ALL_TAC;
ASM_SIMP_TAC[ARITH_RULE
`j + 1 < k ==> (j + 2 = k <=> k - (j + 2) = 0)`] THEN
REWRITE_TAC[VAL_EQ_0] THEN MATCH_MP_TAC WORD_EQ_0 THEN
REWRITE_TAC[DIMINDEX_64] THEN UNDISCH_TAC `k < 2 EXP 64` THEN
ARITH_TAC] THEN
REWRITE_TAC[ARITH_RULE `(n + 2) - 1 = n + 1`] THEN
REWRITE_TAC[GSYM BIGNUM_FROM_MEMORY_BYTES] THEN
ASM_REWRITE_TAC[BIGNUM_FROM_MEMORY_STEP] THEN
SUBGOAL_THEN `j' + 2 = (j' + 1) + 1` MP_TAC THENL
[ARITH_TAC; DISCH_THEN SUBST_ALL_TAC] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN
ONCE_REWRITE_TAC[LOWDIGITS_CLAUSES] THEN
GEN_REWRITE_TAC RAND_CONV
[ARITH_RULE `(e * d1 + d0) + c * (e * a1 + a0):num =
e * (c * a1 + d1) + d0 + c * a0`] THEN
FIRST_X_ASSUM(fun th ->
GEN_REWRITE_TAC (RAND_CONV o RAND_CONV) [SYM th]) THEN
REWRITE_TAC[EXP_ADD; ARITH_RULE `64 * (i + 1) = 64 * i + 64`] THEN
REWRITE_TAC[GSYM REAL_OF_NUM_CLAUSES] THEN
ACCUMULATOR_POP_ASSUM_LIST(MP_TAC o end_itlist CONJ) THEN
GEN_REWRITE_TAC LAND_CONV
[TAUT `p /\ q /\ r /\ s <=> p /\ s /\ q /\ r`] THEN
DISCH_THEN(MP_TAC o end_itlist CONJ o DECARRY_RULE o CONJUNCTS) THEN
ASM_SIMP_TAC[VAL_WORD_EQ; DIMINDEX_64; BIGDIGIT_BOUND] THEN
REWRITE_TAC[GSYM REAL_OF_NUM_CLAUSES] THEN
DISCH_THEN(fun th -> REWRITE_TAC[th]) THEN REAL_ARITH_TAC;
X_GEN_TAC `j:num` THEN STRIP_TAC THEN
MAP_EVERY VAL_INT64_TAC [`j:num`; `j - 1`] THEN
X86_SIM_TAC BIGNUM_MONTREDC_EXEC [1];
X86_SIM_TAC BIGNUM_MONTREDC_EXEC [1]];
ALL_TAC] THEN
SUBGOAL_THEN `cout < 2` MP_TAC THENL
[SUBGOAL_THEN `q * n + lowdigits a (k + i) < 2 EXP (64 * (k + i)) * 2`
MP_TAC THENL
[MATCH_MP_TAC(ARITH_RULE `x < e /\ y < e ==> x + y < e * 2`) THEN
REWRITE_TAC[LOWDIGITS_BOUND] THEN
REWRITE_TAC[ARITH_RULE `64 * (k + p) = 64 * p + 64 * k`] THEN
ASM_SIMP_TAC[LT_MULT2; EXP_ADD];
FIRST_X_ASSUM(fun th ->
GEN_REWRITE_TAC (LAND_CONV o LAND_CONV) [SYM th]) THEN
REWRITE_TAC[LEFT_ADD_DISTRIB; MULT_ASSOC; GSYM ADD_ASSOC] THEN
REWRITE_TAC[ARITH_RULE `64 * k + 64 * p = 64 * (p + k)`] THEN
DISCH_THEN(MP_TAC o MATCH_MP (ARITH_RULE
`a + b:num < c ==> a < c`)) THEN
REWRITE_TAC[GSYM EXP_ADD; GSYM LEFT_ADD_DISTRIB] THEN
REWRITE_TAC[LT_MULT_LCANCEL; EXP_EQ_0; ARITH_EQ]];
GEN_REWRITE_TAC LAND_CONV [NUM_AS_BITVAL_ALT] THEN
DISCH_THEN(X_CHOOSE_THEN `tc:bool` SUBST_ALL_TAC)] THEN
(*** Just case split over the "off the end" and share remainder ***)
ASM_SIMP_TAC[LOWDIGITS_SELF] THEN
GHOST_INTRO_TAC `cin:bool` `read CF` THEN
GHOST_INTRO_TAC `hin:int64` `read R11` THEN
VAL_INT64_TAC `k - 1` THEN
SUBGOAL_THEN `word_sub (word k) (word 1):int64 = word(k - 1)`
ASSUME_TAC THENL
[ASM_REWRITE_TAC[WORD_SUB; ARITH_RULE `1 <= k <=> ~(k = 0)`];
ALL_TAC] THEN
VAL_INT64_TAC `k + i:num` THEN
MP_TAC(WORD_RULE `word_add (word k) (word i):int64 = word(k + i)`) THEN
DISCH_TAC THEN
MP_TAC(SPEC `k - 1` WORD_INDEX_WRAP) THEN
ASM_SIMP_TAC[SUB_ADD; LE_1] THEN DISCH_TAC THEN
ASM_CASES_TAC `nx:num <= k + i` THENL
[REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN ENSURES_INIT_TAC "s0" THEN
X86_ACCSTEPS_TAC BIGNUM_MONTREDC_EXEC [1] (1--8) THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[] THEN
CONJ_TAC THENL [CONV_TAC WORD_RULE; ALL_TAC] THEN CONJ_TAC THENL
[ASM_SIMP_TAC[ARITH_RULE `nx <= k + i ==> nx - (k + i + 1) = 0`] THEN
REWRITE_TAC[GSYM BIGNUM_FROM_MEMORY_BYTES] THEN CONV_TAC SYM_CONV THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_TRIVIAL] THEN
MATCH_MP_TAC HIGHDIGITS_ZERO THEN
TRANS_TAC LTE_TRANS `2 EXP (64 * nx)` THEN
ASM_REWRITE_TAC[LE_EXP] THEN UNDISCH_TAC `nx:num <= k + i` THEN
ARITH_TAC;
ALL_TAC];
SUBGOAL_THEN `nonoverlapping (word_add z (word (8 * (k - 1))):int64,8)
(word_add x (word (8 * (k + i))),
8 * (nx - (k + i)))`
MP_TAC THEN REWRITE_TAC[NONOVERLAPPING_CLAUSES] THENL
[RULE_ASSUM_TAC(REWRITE_RULE[NOT_LE]) THEN
FIRST_X_ASSUM(DISJ_CASES_THEN2 SUBST_ALL_TAC MP_TAC) THENL
[ALL_TAC;
GEN_REWRITE_TAC LAND_CONV [NONOVERLAPPING_MODULO_SYM] THEN
MATCH_MP_TAC(ONCE_REWRITE_RULE[IMP_CONJ_ALT]
NONOVERLAPPING_MODULO_SUBREGIONS) THEN
CONJ_TAC THEN CONTAINED_TAC] THEN
SUBGOAL_THEN
`word_add z (word (8 * (k + i))):int64 =
word_add (word_add z (word(8 * (k - 1))))
(word(8 + 8 * ((k + i) - k)))`
SUBST1_TAC THENL
[REWRITE_TAC[GSYM WORD_ADD_ASSOC; GSYM WORD_ADD] THEN
AP_TERM_TAC THEN AP_TERM_TAC THEN SIMPLE_ARITH_TAC;
NONOVERLAPPING_TAC];
DISCH_TAC] THEN
GEN_REWRITE_TAC (RATOR_CONV o LAND_CONV o ONCE_DEPTH_CONV)
[BIGNUM_FROM_MEMORY_OFFSET_EQ_HIGHDIGITS] THEN
ASM_REWRITE_TAC[SUB_EQ_0] THEN
REWRITE_TAC[ARITH_RULE `n - (k + i) - 1 = n - (k + i + 1)`] THEN
REWRITE_TAC[ARITH_RULE `(k + i) + 1 = k + i + 1`] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN ENSURES_INIT_TAC "s0" THEN
X86_ACCSTEPS_TAC BIGNUM_MONTREDC_EXEC [1;8;9] (1--11) THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[] THEN
CONJ_TAC THENL [CONV_TAC WORD_RULE; ALL_TAC]] THEN
(MAP_EVERY EXISTS_TAC
[`2 EXP (64 * i) * q0 + q`;
`2 EXP (64 * i) * r0 + r`] THEN
GEN_REWRITE_TAC I [CONJ_ASSOC] THEN CONJ_TAC THENL
[REWRITE_TAC[EXP_ADD; ARITH_RULE `64 * (i + 1) = 64 * i + 64`] THEN
CONJ_TAC THEN MATCH_MP_TAC(ARITH_RULE
`q1 < e /\ q0 < ee /\ (q1 < e ==> (q1 + 1) * ee <= e * ee)
==> ee * q1 + q0 < ee * e`) THEN
ASM_REWRITE_TAC[LE_MULT_RCANCEL; EXP_EQ_0; ARITH_EQ] THEN
ASM_REWRITE_TAC[ARITH_RULE `n + 1 <= m <=> n < m`];
ALL_TAC] THEN
CONJ_TAC THENL
[ALL_TAC;
DISCH_THEN(fun th ->
REPEAT(FIRST_X_ASSUM(STRIP_ASSUME_TAC o C MATCH_MP th))) THEN
ASM_REWRITE_TAC[ADD_EQ_0; MULT_EQ_0; EXP_EQ_0; ARITH_EQ] THEN
MATCH_MP_TAC CONG_IMP_EQ THEN EXISTS_TAC `2 EXP 64` THEN
ASM_REWRITE_TAC[EXP_LT_0; ARITH_EQ] THEN
FIRST_X_ASSUM(MATCH_MP_TAC o MATCH_MP (NUMBER_RULE
`ee * x + e * y + r = z
==> e divides ee /\ (z == 0) (mod e)
==> (r == 0) (mod e)`)) THEN
CONJ_TAC THENL
[MATCH_MP_TAC DIVIDES_EXP_LE_IMP THEN
UNDISCH_TAC `~(k = 0)` THEN ARITH_TAC;
UNDISCH_THEN `(w * z1) MOD 2 EXP 64 = q0` (SUBST1_TAC o SYM)] THEN
REWRITE_TAC[CONG] THEN CONV_TAC MOD_DOWN_CONV THEN
REWRITE_TAC[GSYM CONG] THEN MATCH_MP_TAC(NUMBER_RULE
`(n * w + 1 == 0) (mod e) ==> (z + (w * z) * n == 0) (mod e)`) THEN
ASM_REWRITE_TAC[]] THEN
SUBGOAL_THEN `8 * k = 8 * ((k - 1) + 1)` SUBST1_TAC THENL
[UNDISCH_TAC `~(k = 0)` THEN ARITH_TAC;
REWRITE_TAC[GSYM BIGNUM_FROM_MEMORY_BYTES]] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_STEP] THEN
ASM_REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN
REWRITE_TAC[LEFT_ADD_DISTRIB; MULT_ASSOC; GSYM EXP_ADD] THEN
REWRITE_TAC[GSYM LEFT_ADD_DISTRIB] THEN
SUBGOAL_THEN `(i + 1) + (k - 1) = i + k` SUBST1_TAC THENL
[UNDISCH_TAC `~(k = 0)` THEN ARITH_TAC; ALL_TAC] THEN
REWRITE_TAC[LEFT_ADD_DISTRIB; EXP_ADD; MULT_CLAUSES] THEN
REWRITE_TAC[LOWDIGITS_CLAUSES; ARITH_RULE `k + i + 1 = (k + i) + 1`]) THEN
REWRITE_TAC[ARITH_RULE `64 * (k + i) = 64 * k + 64 * i`; EXP_ADD] THENL
[REWRITE_TAC[VAL_WORD_0; ADD_CLAUSES; MULT_CLAUSES] THEN
SUBGOAL_THEN `bigdigit a (k + i) = 0` SUBST1_TAC THENL
[MATCH_MP_TAC BIGDIGIT_ZERO THEN
TRANS_TAC LTE_TRANS `2 EXP (64 * nx)` THEN
ASM_REWRITE_TAC[LE_EXP] THEN UNDISCH_TAC `nx:num <= k + i` THEN
ARITH_TAC;
REWRITE_TAC[MULT_CLAUSES; ADD_CLAUSES]] THEN
REPEAT(FIRST_X_ASSUM(MP_TAC o check
(can (term_match [] `2 EXP (64 * k) * x + y = z`) o concl))) THEN
REWRITE_TAC[GSYM REAL_OF_NUM_CLAUSES] THEN
ACCUMULATOR_POP_ASSUM_LIST(MP_TAC o end_itlist CONJ o DECARRY_RULE) THEN
ASM_SIMP_TAC[VAL_WORD_EQ; DIMINDEX_64; VAL_WORD_BITVAL; ADD_CLAUSES] THEN
DISCH_THEN(fun th -> REWRITE_TAC[th]) THEN
CONV_TAC REAL_RING;
RULE_ASSUM_TAC(REWRITE_RULE[ADD_CLAUSES; VAL_WORD_BITVAL]) THEN
REPEAT(FIRST_X_ASSUM(MP_TAC o check
(can (term_match [] `2 EXP (64 * k) * x + y = z`) o concl))) THEN
REWRITE_TAC[GSYM REAL_OF_NUM_CLAUSES] THEN
ACCUMULATOR_POP_ASSUM_LIST(MP_TAC o end_itlist CONJ o DECARRY_RULE) THEN
ASM_SIMP_TAC[VAL_WORD_EQ; DIMINDEX_64; VAL_WORD_BITVAL; ADD_CLAUSES;
BIGDIGIT_BOUND] THEN
DISCH_THEN(fun th -> REWRITE_TAC[th]) THEN
CONV_TAC REAL_RING]);;
let BIGNUM_MONTREDC_SUBROUTINE_CORRECT = time prove
(`!k z r x m p a n pc stackpointer returnaddress.
nonoverlapping (word_sub stackpointer (word 56),64) (z,8 * val k) /\
ALL (nonoverlapping (word_sub stackpointer (word 56),56))
[(word pc,0x17d); (x,8 * val r); (m,8 * val k)] /\
ALL (nonoverlapping (z,8 * val k)) [(word pc,0x17d); (m,8 * val k)] /\
(x = z \/ nonoverlapping (x,8 * val r) (z,8 * val k)) /\
val p < 2 EXP 61 /\ val r < 2 EXP 61
==> ensures x86
(\s. bytes_loaded s (word pc) bignum_montredc_mc /\
read RIP s = word pc /\
read RSP s = stackpointer /\
read (memory :> bytes64 stackpointer) s = returnaddress /\
C_ARGUMENTS [k; z; r; x; m; p] s /\
bignum_from_memory (x,val r) s = a /\
bignum_from_memory (m,val k) s = n)
(\s. read RIP s = returnaddress /\
read RSP s = word_add stackpointer (word 8) /\
(ODD n /\
lowdigits a (val k + val p) <= 2 EXP (64 * val p) * n
==> bignum_from_memory (z,val k) s =
(inverse_mod n (2 EXP (64 * val p)) *
lowdigits a (val k + val p)) MOD n))
(MAYCHANGE [RIP; RSP; RAX; RDX; R10; R11] ,,
MAYCHANGE [memory :> bytes(z,8 * val k);
memory :> bytes(word_sub stackpointer (word 56),56)] ,,
MAYCHANGE SOME_FLAGS)`,
X86_PROMOTE_RETURN_STACK_TAC bignum_montredc_mc BIGNUM_MONTREDC_CORRECT
`[RBX; RBP; R12; R13; R14; R15]` 56);;
(* ------------------------------------------------------------------------- *)
(* Correctness of Windows ABI version. *)
(* ------------------------------------------------------------------------- *)
let windows_bignum_montredc_mc = define_from_elf
"windows_bignum_montredc_mc" "x86/generic/bignum_montredc.obj";;
let WINDOWS_BIGNUM_MONTREDC_SUBROUTINE_CORRECT = time prove
(`!k z r x m p a n pc stackpointer returnaddress.
nonoverlapping (word_sub stackpointer (word 72),80) (z,8 * val k) /\
ALL (nonoverlapping (word_sub stackpointer (word 72),72))
[(word pc,0x197); (x,8 * val r); (m,8 * val k)] /\
ALL (nonoverlapping (z,8 * val k)) [(word pc,0x197); (m,8 * val k)] /\
(x = z \/ nonoverlapping (x,8 * val r) (z,8 * val k)) /\
val p < 2 EXP 61 /\ val r < 2 EXP 61
==> ensures x86
(\s. bytes_loaded s (word pc) windows_bignum_montredc_mc /\
read RIP s = word pc /\
read RSP s = stackpointer /\
read (memory :> bytes64 stackpointer) s = returnaddress /\
WINDOWS_C_ARGUMENTS [k; z; r; x; m; p] s /\
bignum_from_memory (x,val r) s = a /\
bignum_from_memory (m,val k) s = n)
(\s. read RIP s = returnaddress /\
read RSP s = word_add stackpointer (word 8) /\
(ODD n /\
lowdigits a (val k + val p) <= 2 EXP (64 * val p) * n
==> bignum_from_memory (z,val k) s =
(inverse_mod n (2 EXP (64 * val p)) *
lowdigits a (val k + val p)) MOD n))
(MAYCHANGE [RIP; RSP; R9; R8; RCX; RAX; RDX; R10; R11] ,,
MAYCHANGE [memory :> bytes(z,8 * val k);
memory :> bytes(word_sub stackpointer (word 72),72)] ,,
MAYCHANGE SOME_FLAGS)`,
WINDOWS_X86_WRAP_STACK_TAC windows_bignum_montredc_mc bignum_montredc_mc
BIGNUM_MONTREDC_CORRECT `[RBX; RBP; R12; R13; R14; R15]` 56);;
| null | https://raw.githubusercontent.com/awslabs/s2n-bignum/824c15f908d7a343af1b2f378cfedd36e880bdde/x86/proofs/bignum_montredc.ml | ocaml | =========================================================================
=========================================================================
*** print_literal_from_elf "x86/generic/bignum_montredc.o";;
***
PUSH (% rbx)
PUSH (% rbp)
PUSH (% r12)
PUSH (% r13)
PUSH (% r14)
PUSH (% r15)
TEST (% rdi) (% rdi)
SUB (% rbx) (% r14)
ADD (% rax) (% r14)
ADD (% rax) (% r14)
ADD (% rax) (% r14)
ADD (% rax) (% r14)
XOR (% r14) (% r14)
TEST (% rbx) (% rbx)
INC (% r14)
XOR (% rbx) (% rbx)
INC (% r14)
XOR (% r15) (% r15)
TEST (% r9) (% r9)
XOR (% r14) (% r14)
ADD (% rax) (% r12)
ADD (% rax) (% r11)
INC (% rbx)
ADC (% r11) (% r15)
ADC (% r15) (Imm8 (word 0))
ADD (% rbx) (% r14)
ADD (% r11) (% rax)
ADC (% r15) (Imm8 (word 0))
INC (% r14)
XOR (% rbx) (% rbx)
INC (% rbx)
NOT (% rbp)
XOR (% r12) (% r12)
XOR (% rbx) (% rbx)
AND (% rax) (% rbp)
NEG (% r12)
INC (% rbx)
ADD (% rsp) (Imm8 (word 8))
POP (% r15)
POP (% r14)
POP (% r13)
POP (% r12)
POP (% rbp)
POP (% rbx)
-------------------------------------------------------------------------
Proof.
-------------------------------------------------------------------------
** Degenerate k = 0 case **
** Initial word-level modular inverse **
** Get a basic bound on k from the nonoverlapping assumptions **
** Initialization of the output buffer **
** Copyloop **
** Now consider the cases again **
** Padloop following copyloop **
** Break at "corrective" to share degenerate cases, corrective ending **
** Comparison operation "cmploop" **
** Corrective subtraction "corrloop" **
** Another semi-degenerate case p = 0 **
** Setup of the main loop **
** This is the main loop invariant: save for later **
** Start on the main outer loop invariant **
** Break at "montend" to share the end reasoning **
** Just case split over the "off the end" and share remainder **
-------------------------------------------------------------------------
Correctness of Windows ABI version.
------------------------------------------------------------------------- |
* Copyright Amazon.com , Inc. or its affiliates . All Rights Reserved .
* SPDX - License - Identifier : Apache-2.0 OR ISC
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0 OR ISC
*)
Montgomery reduction of arbitrary bignum .
let bignum_montredc_mc =
define_assert_from_elf "bignum_montredc_mc" "x86/generic/bignum_montredc.o"
[
SUB ( % rsp ) ( Imm8 ( word 8) )
0x0f; 0x84; 0x57; 0x01; 0x00; 0x00;
JE ( Imm32 ( word 343 ) )
MOV ( % r10 ) ( % rdx )
MOV ( % rax ) ( ( % % ( r8,0 ) ) )
MOV ( % r14 ) ( % rax )
MOV ( % rbx ) ( % rax )
SHL ( % r14 ) ( Imm8 ( word 2 ) )
XOR ( % rbx ) ( Imm8 ( word 2 ) )
MOV ( % r14 ) ( % rbx )
IMUL ( % r14 ) ( % rax )
0xb8; 0x02; 0x00; 0x00; 0x00;
MOV ( % eax ) ( Imm32 ( word 2 ) )
ADD ( % r14 ) ( Imm8 ( word 1 ) )
IMUL ( % rbx ) ( % rax )
IMUL ( % r14 ) ( % r14 )
0xb8; 0x01; 0x00; 0x00; 0x00;
MOV ( % eax ) ( Imm32 ( word 1 ) )
IMUL ( % rbx ) ( % rax )
IMUL ( % r14 ) ( % r14 )
0xb8; 0x01; 0x00; 0x00; 0x00;
MOV ( % eax ) ( Imm32 ( word 1 ) )
IMUL ( % rbx ) ( % rax )
IMUL ( % r14 ) ( % r14 )
0xb8; 0x01; 0x00; 0x00; 0x00;
MOV ( % eax ) ( Imm32 ( word 1 ) )
IMUL ( % rbx ) ( % rax )
MOV ( ( % % ( rsp,0 ) ) ) ( % rbx )
MOV ( % rbx ) ( % rdi )
CMP ( % r10 ) ( % rdi )
CMOVB ( % rbx ) ( % r10 )
JE ( Imm8 ( word 24 ) )
MOV ( % rax ) ( ( % % % ( rcx,3,r14 ) ) )
MOV ( ( % % % ( rsi,3,r14 ) ) ) ( % rax )
CMP ( % r14 ) ( % rbx )
JB ( Imm8 ( word 240 ) )
CMP ( % r14 ) ( % rdi )
JAE ( Imm8 ( word 15 ) )
MOV ( ( % % % ( rsi,3,r14 ) ) ) ( % rbx )
CMP ( % r14 ) ( % rdi )
JB ( Imm8 ( word 244 ) )
JE ( Imm8 ( word 120 ) )
MOV ( % r12 ) ( ( % % ( rsi,0 ) ) )
MOV ( % rbp ) ( ( % % ( rsp,0 ) ) )
IMUL ( % rbp ) ( % r12 )
MOV ( % rax ) ( ( % % ( r8,0 ) ) )
MUL2 ( % rdx,% rax ) ( % rbp )
MOV ( % r11 ) ( % rdx )
0xbb; 0x01; 0x00; 0x00; 0x00;
MOV ( % ebx ) ( Imm32 ( word 1 ) )
MOV ( % r13 ) ( % rdi )
DEC ( % r13 )
JE ( Imm8 ( word 36 ) )
ADC ( % r11 ) ( ( % % % ( ) ) )
SBB ( % r12 ) ( % r12 )
MOV ( % rax ) ( ( % % % ( r8,3,rbx ) ) )
MUL2 ( % rdx,% rax ) ( % rbp )
SUB ( % rdx ) ( % r12 )
0x48; 0x89; 0x44; 0xde; 0xf8;
MOV ( ( % % % % ( rsi,3,rbx,-- & 8) ) ) ( % rax )
MOV ( % r11 ) ( % rdx )
DEC ( % r13 )
JNE ( Imm8 ( word 220 ) )
0x41; 0xbf; 0x00; 0x00; 0x00; 0x00;
MOV ( % r15d ) ( Imm32 ( word 0 ) )
CMP ( % rbx ) ( % r10 )
JAE ( Imm8 ( word 11 ) )
MOV ( % rax ) ( ( % % % ( rcx,3,rbx ) ) )
0x4c; 0x89; 0x5c; 0xfe; 0xf8;
MOV ( ( % % % % ( rsi,3,rdi,-- & 8) ) ) ( % r11 )
CMP ( % r14 ) ( % r9 )
JB ( Imm8 ( word 139 ) )
MOV ( % r10 ) ( % rdi )
MOV ( % rax ) ( ( % % % ( ) ) )
SBB ( % rax ) ( ( % % % ( r8,3,rbx ) ) )
DEC ( % r10 )
JNE ( Imm8 ( word 240 ) )
SBB ( % r15 ) ( Imm8 ( word 0 ) )
SBB ( % rbp ) ( % rbp )
MOV ( % rax ) ( ( % % % ( r8,3,rbx ) ) )
SBB ( ( % % % ( ) ) ) ( % rax )
SBB ( % r12 ) ( % r12 )
CMP ( % rbx ) ( % rdi )
JB ( Imm8 ( word 231 ) )
RET
];;
let BIGNUM_MONTREDC_EXEC = X86_MK_CORE_EXEC_RULE bignum_montredc_mc;;
* * This actually works mod 32 but if anything this is more convenient * *
let WORD_NEGMODINV_SEED_LEMMA_16 = prove
(`!a x:int64.
ODD a /\
word_xor (word_sub (word a) (word_shl (word a) 2)) (word 2) = x
==> (a * val x + 1 == 0) (mod 16)`,
REPEAT STRIP_TAC THEN REWRITE_TAC[CONG; MOD_0] THEN
TRANS_TAC EQ_TRANS
`(val(word a:int64) MOD 16 * val(x:int64) MOD 16 + 1) MOD 16` THEN
REWRITE_TAC[ARITH_RULE `16 = 2 EXP 4`] THEN CONJ_TAC THENL
[REWRITE_TAC[VAL_WORD; DIMINDEX_64; MOD_MOD_EXP_MIN] THEN
CONV_TAC NUM_REDUCE_CONV THEN CONV_TAC MOD_DOWN_CONV THEN REFL_TAC;
REWRITE_TAC[VAL_MOD; NUMSEG_LT; ARITH_EQ; ARITH]] THEN
SUBGOAL_THEN `bit 0 (word a:int64)` MP_TAC THENL
[ASM_REWRITE_TAC[BIT_LSB_WORD];
EXPAND_TAC "x" THEN POP_ASSUM_LIST(K ALL_TAC) THEN DISCH_TAC] THEN
CONV_TAC(ONCE_DEPTH_CONV EXPAND_NSUM_CONV) THEN
CONV_TAC(TOP_DEPTH_CONV BIT_WORD_CONV) THEN
MAP_EVERY ASM_CASES_TAC
[`bit 1 (word a:int64)`;`bit 2 (word a:int64)`;`bit 3 (word a:int64)`] THEN
ASM_REWRITE_TAC[BITVAL_CLAUSES] THEN CONV_TAC NUM_REDUCE_CONV);;
let BIGNUM_MONTREDC_CORRECT = time prove
(`!k z r x m p a n pc stackpointer.
ALL (nonoverlapping (stackpointer,8))
[(word pc,0x17d); (x,8 * val r); (m,8 * val k); (z,8 * val k)] /\
ALL (nonoverlapping (z,8 * val k)) [(word pc,0x17d); (m,8 * val k)] /\
(x = z \/ nonoverlapping (x,8 * val r) (z,8 * val k)) /\
val p < 2 EXP 61 /\ val r < 2 EXP 61
==> ensures x86
(\s. bytes_loaded s (word pc) (BUTLAST bignum_montredc_mc) /\
read RIP s = word(pc + 0xe) /\
read RSP s = stackpointer /\
C_ARGUMENTS [k; z; r; x; m; p] s /\
bignum_from_memory (x,val r) s = a /\
bignum_from_memory (m,val k) s = n)
(\s. read RIP s = word(pc + 0x16e) /\
(ODD n /\
lowdigits a (val k + val p) <= 2 EXP (64 * val p) * n
==> bignum_from_memory (z,val k) s =
(inverse_mod n (2 EXP (64 * val p)) *
lowdigits a (val k + val p)) MOD n))
(MAYCHANGE [RIP; RAX; RBX; RBP; RDX;
R10; R11; R12; R13; R14; R15] ,,
MAYCHANGE [memory :> bytes(z,8 * val k);
memory :> bytes(stackpointer,8)] ,,
MAYCHANGE SOME_FLAGS)`,
W64_GEN_TAC `k:num` THEN X_GEN_TAC `z:int64` THEN
W64_GEN_TAC `nx:num` THEN X_GEN_TAC `x:int64` THEN
X_GEN_TAC `m:int64` THEN W64_GEN_TAC `p:num` THEN
MAP_EVERY X_GEN_TAC [`a:num`; `n:num`; `pc:num`] THEN
X_GEN_TAC `stackpointer:int64` THEN
REWRITE_TAC[ALL; NONOVERLAPPING_CLAUSES] THEN
REWRITE_TAC[C_ARGUMENTS; C_RETURN; SOME_FLAGS] THEN
DISCH_THEN(REPEAT_TCL CONJUNCTS_THEN ASSUME_TAC) THEN
BIGNUM_TERMRANGE_TAC `k:num` `n:num` THEN
BIGNUM_TERMRANGE_TAC `nx:num` `a:num` THEN
ASM_CASES_TAC `k = 0` THENL
[UNDISCH_THEN `k = 0` SUBST_ALL_TAC THEN
REPEAT(FIRST_X_ASSUM(SUBST_ALL_TAC o MATCH_MP (ARITH_RULE
`a < 2 EXP (64 * 0) ==> a = 0`))) THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN
ENSURES_INIT_TAC "s0" THEN X86_STEPS_TAC BIGNUM_MONTREDC_EXEC (1--2) THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[ODD];
ALL_TAC] THEN
ENSURES_SEQUENCE_TAC `pc + 0x75`
`\s. read RSP s = stackpointer /\
read RDI s = word k /\
read RSI s = z /\
read R10 s = word nx /\
read RCX s = x /\
read R8 s = m /\
read R9 s = word p /\
bignum_from_memory (x,nx) s = a /\
bignum_from_memory (m,k) s = n /\
(ODD n ==> (n * val(read RBX s) + 1 == 0) (mod (2 EXP 64)))` THEN
CONJ_TAC THENL
[REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN ENSURES_INIT_TAC "s0" THEN
SUBGOAL_THEN `bignum_from_memory(m,k) s0 = highdigits n 0` MP_TAC THENL
[ASM_REWRITE_TAC[HIGHDIGITS_0; BIGNUM_FROM_MEMORY_BYTES];
GEN_REWRITE_TAC LAND_CONV[BIGNUM_FROM_MEMORY_EQ_HIGHDIGITS] THEN
ASM_REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES; ADD_CLAUSES] THEN
REWRITE_TAC[GSYM LOWDIGITS_1; lowdigits; MULT_CLAUSES] THEN
REWRITE_TAC[GSYM DIMINDEX_64; WORD_MOD_SIZE] THEN
REWRITE_TAC[DIMINDEX_64] THEN STRIP_TAC] THEN
X86_STEPS_TAC BIGNUM_MONTREDC_EXEC (1--9) THEN
SUBGOAL_THEN `ODD n ==> (n * val (read RBX s9) + 1 == 0) (mod 16)`
MP_TAC THENL [ASM_SIMP_TAC[WORD_NEGMODINV_SEED_LEMMA_16]; ALL_TAC] THEN
REABBREV_TAC `x0 = read RBX s9` THEN DISCH_TAC THEN
X86_STEPS_TAC BIGNUM_MONTREDC_EXEC (10--27) THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[] THEN
REWRITE_TAC[VAL_WORD_MUL; VAL_WORD_ADD; VAL_WORD; DIMINDEX_64; CONG] THEN
CONV_TAC MOD_DOWN_CONV THEN REWRITE_TAC[GSYM CONG] THEN
SUBST1_TAC(ARITH_RULE `2 EXP 64 = 16 EXP (2 EXP 4)`) THEN
DISCH_THEN(fun th -> FIRST_X_ASSUM(MP_TAC o C MATCH_MP th)) THEN
SPEC_TAC(`16`,`e:num`) THEN CONV_TAC NUM_REDUCE_CONV THEN
CONV_TAC NUMBER_RULE;
GHOST_INTRO_TAC `w:num` `\s. val(read RBX s)` THEN
REWRITE_TAC[VAL_WORD_GALOIS; DIMINDEX_64]] THEN
GLOBALIZE_PRECONDITION_TAC THEN ASM_REWRITE_TAC[] THEN
VAL_INT64_TAC `w:num` THEN
FIRST_ASSUM(MP_TAC o MATCH_MP (ONCE_REWRITE_RULE[IMP_CONJ]
NONOVERLAPPING_IMP_SMALL_1)) THEN
ANTS_TAC THENL [CONV_TAC NUM_REDUCE_CONV; DISCH_TAC] THEN
ENSURES_SEQUENCE_TAC `pc + 0xb2`
`\s. read RSP s = stackpointer /\
read RDI s = word k /\
read RSI s = z /\
read R10 s = word nx /\
read RCX s = x /\
read R8 s = m /\
read R9 s = word p /\
bignum_from_memory (word_add x (word (8 * k)),nx - k) s =
highdigits a k /\
bignum_from_memory (m,k) s = n /\
read (memory :> bytes64 stackpointer) s = word w /\
bignum_from_memory (z,k) s = lowdigits a k /\
read R15 s = word 0` THEN
CONJ_TAC THENL
[ASM_CASES_TAC `nx = 0` THENL
[UNDISCH_THEN `nx = 0` SUBST_ALL_TAC THEN
REPEAT(FIRST_X_ASSUM(SUBST_ALL_TAC o MATCH_MP (ARITH_RULE
`a < 2 EXP (64 * 0) ==> a = 0`))) THEN
ENSURES_WHILE_UP_TAC `k:num` `pc + 0xa3` `pc + 0xaa`
`\i s. read RSP s = stackpointer /\
read RDI s = word k /\
read RSI s = z /\
read R10 s = word 0 /\
read RCX s = x /\
read R8 s = m /\
read R9 s = word p /\
bignum_from_memory (m,k) s = n /\
read (memory :> bytes64 stackpointer) s = word w /\
read R14 s = word i /\
read RBX s = word 0 /\
bignum_from_memory (z,i) s = 0` THEN
ASM_REWRITE_TAC[] THEN REPEAT CONJ_TAC THENL
[X86_SIM_TAC BIGNUM_MONTREDC_EXEC (1--7) THEN
ASM_SIMP_TAC[LE_1; GSYM BIGNUM_FROM_MEMORY_BYTES] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_TRIVIAL];
X_GEN_TAC `i:num` THEN STRIP_TAC THEN VAL_INT64_TAC `i:num` THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_STEP] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN ENSURES_INIT_TAC "s0" THEN
X86_STEPS_TAC BIGNUM_MONTREDC_EXEC (1--2) THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[GSYM WORD_ADD] THEN
ARITH_TAC;
X_GEN_TAC `i:num` THEN STRIP_TAC THEN VAL_INT64_TAC `i:num` THEN
X86_SIM_TAC BIGNUM_MONTREDC_EXEC (1--2);
REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN ENSURES_INIT_TAC "s0" THEN
X86_STEPS_TAC BIGNUM_MONTREDC_EXEC (1--3) THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[LOWDIGITS_TRIVIAL] THEN
REWRITE_TAC[LE; GSYM BIGNUM_FROM_MEMORY_BYTES] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_TRIVIAL; SUB_0] THEN
REWRITE_TAC[HIGHDIGITS_TRIVIAL]];
ALL_TAC] THEN
ENSURES_WHILE_UP_TAC `MIN k nx` `pc + 0x8b` `pc + 0x96`
`\i s. read RSP s = stackpointer /\
read RDI s = word k /\
read RSI s = z /\
read R10 s = word nx /\
read RCX s = x /\
read R8 s = m /\
read R9 s = word p /\
bignum_from_memory (m,k) s = n /\
read (memory :> bytes64 stackpointer) s = word w /\
read R14 s = word i /\
read RBX s = word(MIN k nx) /\
bignum_from_memory(word_add x (word(8 * i)),nx - i) s =
highdigits a i /\
bignum_from_memory (z,i) s = lowdigits a i` THEN
ASM_REWRITE_TAC[] THEN REPEAT CONJ_TAC THENL
[ASM_REWRITE_TAC[ARITH_RULE `MIN a b = 0 <=> a = 0 \/ b = 0`];
X86_SIM_TAC BIGNUM_MONTREDC_EXEC (1--7) THEN
MATCH_MP_TAC(TAUT `q /\ (q ==> p) /\ r ==> p /\ q /\ r`) THEN
CONJ_TAC THENL [REWRITE_TAC[MIN] THEN MESON_TAC[NOT_LT]; ALL_TAC] THEN
REWRITE_TAC[GSYM BIGNUM_FROM_MEMORY_BYTES; LOWDIGITS_0] THEN
REWRITE_TAC[MULT_CLAUSES; WORD_ADD_0; SUB_0; HIGHDIGITS_0] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_TRIVIAL] THEN
ASM_REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN
DISCH_THEN SUBST1_TAC THEN VAL_INT64_TAC `MIN k nx` THEN
ASM_REWRITE_TAC[ARITH_RULE `MIN a b = 0 <=> a = 0 \/ b = 0`];
X_GEN_TAC `i:num` THEN STRIP_TAC THEN VAL_INT64_TAC `i:num` THEN
SUBGOAL_THEN `i:num < nx /\ i < k` STRIP_ASSUME_TAC THENL
[SIMPLE_ARITH_TAC; ALL_TAC] THEN
GEN_REWRITE_TAC (RATOR_CONV o LAND_CONV o ONCE_DEPTH_CONV)
[BIGNUM_FROM_MEMORY_OFFSET_EQ_HIGHDIGITS] THEN
ASM_REWRITE_TAC[SUB_EQ_0; GSYM NOT_LT] THEN
REWRITE_TAC[ARITH_RULE `k - i - 1 = k - (i + 1)`] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_STEP] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN
ENSURES_INIT_TAC "s0" THEN
X86_STEPS_TAC BIGNUM_MONTREDC_EXEC (1--3) THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[GSYM WORD_ADD] THEN
SIMP_TAC[VAL_WORD_EQ; DIMINDEX_64; BIGDIGIT_BOUND] THEN
REWRITE_TAC[LOWDIGITS_CLAUSES] THEN ARITH_TAC;
X_GEN_TAC `i:num` THEN STRIP_TAC THEN VAL_INT64_TAC `i:num` THEN
X86_SIM_TAC BIGNUM_MONTREDC_EXEC (1--2) THEN
VAL_INT64_TAC `MIN k nx` THEN ASM_REWRITE_TAC[];
ALL_TAC] THEN
ASM_CASES_TAC `k:num <= nx` THENL
[ASM_SIMP_TAC[ARITH_RULE `k <= nx ==> MIN k nx = k`] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN
ENSURES_INIT_TAC "s0" THEN
X86_STEPS_TAC BIGNUM_MONTREDC_EXEC (1--5) THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[];
RULE_ASSUM_TAC(REWRITE_RULE[NOT_LE]) THEN
ASM_SIMP_TAC[ARITH_RULE `nx < k ==> MIN k nx = nx`]] THEN
ENSURES_WHILE_AUP_TAC `nx:num` `k:num` `pc + 0xa3` `pc + 0xaa`
`\i s. read RSP s = stackpointer /\
read RDI s = word k /\
read RSI s = z /\
read R10 s = word nx /\
read RCX s = x /\
read R8 s = m /\
read R9 s = word p /\
bignum_from_memory (m,k) s = n /\
read (memory :> bytes64 stackpointer) s = word w /\
read R14 s = word i /\
read RBX s = word 0 /\
bignum_from_memory (z,i) s = lowdigits a i` THEN
ASM_REWRITE_TAC[] THEN REPEAT CONJ_TAC THENL
[X86_SIM_TAC BIGNUM_MONTREDC_EXEC (1--5);
X_GEN_TAC `i:num` THEN STRIP_TAC THEN VAL_INT64_TAC `i:num` THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_STEP] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN ENSURES_INIT_TAC "s0" THEN
X86_STEPS_TAC BIGNUM_MONTREDC_EXEC (1--2) THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[GSYM WORD_ADD] THEN
SIMP_TAC[VAL_WORD_0; LOWDIGITS_CLAUSES; MULT_CLAUSES; ADD_CLAUSES] THEN
MATCH_MP_TAC(NUM_RING `d = 0 ==> a = e * d + a`) THEN
MATCH_MP_TAC BIGDIGIT_ZERO THEN
TRANS_TAC LTE_TRANS `2 EXP (64 * nx)` THEN
ASM_REWRITE_TAC[LE_EXP] THEN UNDISCH_TAC `nx:num <= i` THEN ARITH_TAC;
X_GEN_TAC `i:num` THEN STRIP_TAC THEN VAL_INT64_TAC `i:num` THEN
X86_SIM_TAC BIGNUM_MONTREDC_EXEC (1--2);
X86_SIM_TAC BIGNUM_MONTREDC_EXEC (1--3) THEN
REWRITE_TAC[GSYM BIGNUM_FROM_MEMORY_BYTES] THEN
ASM_SIMP_TAC[ARITH_RULE `nx < k ==> nx - k = 0`] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_TRIVIAL] THEN
CONV_TAC SYM_CONV THEN MATCH_MP_TAC HIGHDIGITS_ZERO THEN
TRANS_TAC LTE_TRANS `2 EXP (64 * nx)` THEN
ASM_REWRITE_TAC[LE_EXP] THEN UNDISCH_TAC `nx:num < k` THEN ARITH_TAC];
ALL_TAC] THEN
ENSURES_SEQUENCE_TAC `pc + 0x12f`
`\s. read RSP s = stackpointer /\
read RDI s = word k /\
read RSI s = z /\
read R8 s = m /\
bignum_from_memory (m,k) s = n /\
?q r.
q < 2 EXP (64 * p) /\
r < 2 EXP (64 * p) /\
2 EXP (64 * p) *
(2 EXP (64 * k) * val(read R15 s) + bignum_from_memory(z,k) s) + r =
q * n + lowdigits a (k + p) /\
(ODD n ==> r = 0)` THEN
CONJ_TAC THENL
[ALL_TAC;
GHOST_INTRO_TAC `cout:num` `\s. val(read R15 s)` THEN
GHOST_INTRO_TAC `mm:num` `bignum_from_memory(z,k)` THEN
BIGNUM_TERMRANGE_TAC `k:num` `mm:num` THEN
ASM_SIMP_TAC[LOWDIGITS_SELF] THEN
GLOBALIZE_PRECONDITION_TAC THEN ASM_REWRITE_TAC[] THEN
FIRST_X_ASSUM(X_CHOOSE_THEN `q:num` (X_CHOOSE_THEN `r:num`
STRIP_ASSUME_TAC)) THEN
SUBGOAL_THEN `cout < 2` MP_TAC THENL
[SUBGOAL_THEN `q * n + lowdigits a (k + p) < 2 EXP (64 * (k + p)) * 2`
MP_TAC THENL
[MATCH_MP_TAC(ARITH_RULE `x < e /\ y < e ==> x + y < e * 2`) THEN
REWRITE_TAC[LOWDIGITS_BOUND] THEN
REWRITE_TAC[ARITH_RULE `64 * (k + p) = 64 * p + 64 * k`] THEN
ASM_SIMP_TAC[LT_MULT2; EXP_ADD];
FIRST_X_ASSUM(fun th ->
GEN_REWRITE_TAC (LAND_CONV o LAND_CONV) [SYM th]) THEN
REWRITE_TAC[LEFT_ADD_DISTRIB; MULT_ASSOC; GSYM ADD_ASSOC] THEN
REWRITE_TAC[ARITH_RULE `64 * k + 64 * p = 64 * (p + k)`] THEN
DISCH_THEN(MP_TAC o MATCH_MP (ARITH_RULE
`a + b:num < c ==> a < c`)) THEN
REWRITE_TAC[GSYM EXP_ADD; GSYM LEFT_ADD_DISTRIB] THEN
REWRITE_TAC[LT_MULT_LCANCEL; EXP_EQ_0; ARITH_EQ]];
GEN_REWRITE_TAC LAND_CONV [NUM_AS_BITVAL_ALT]] THEN
DISCH_THEN(X_CHOOSE_THEN `c0:bool` SUBST_ALL_TAC) THEN
REWRITE_TAC[VAL_EQ_BITVAL] THEN
ENSURES_WHILE_PUP_TAC `k:num` `pc + 0x135` `pc + 0x143`
`\i s. (read RDI s = word k /\
read RSI s = z /\
read R8 s = m /\
bignum_from_memory (z,k) s = mm /\
bignum_from_memory (m,k) s = n /\
read RBX s = word i /\
read R10 s = word(k - i) /\
read R15 s = word(bitval c0) /\
bignum_from_memory (word_add z (word(8 * i)),k - i) s =
highdigits mm i /\
bignum_from_memory (word_add m (word(8 * i)),k - i) s =
highdigits n i /\
(read CF s <=> lowdigits mm i < lowdigits n i)) /\
(read ZF s <=> i = k)` THEN
ASM_REWRITE_TAC[] THEN REPEAT CONJ_TAC THENL
[REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES; SUB_0] THEN
ENSURES_INIT_TAC "s0" THEN X86_STEPS_TAC BIGNUM_MONTREDC_EXEC (1--2) THEN
ENSURES_FINAL_STATE_TAC THEN
ASM_REWRITE_TAC[LOWDIGITS_0; HIGHDIGITS_0; LT_REFL] THEN
ASM_REWRITE_TAC[MULT_CLAUSES; ADD_CLAUSES; WORD_ADD_0];
X_GEN_TAC `i:num` THEN STRIP_TAC THEN VAL_INT64_TAC `i:num` THEN
GHOST_INTRO_TAC `cin:bool` `read CF` THEN
GEN_REWRITE_TAC (RATOR_CONV o LAND_CONV o ONCE_DEPTH_CONV)
[BIGNUM_FROM_MEMORY_OFFSET_EQ_HIGHDIGITS] THEN
ASM_REWRITE_TAC[SUB_EQ_0; GSYM NOT_LT] THEN
REWRITE_TAC[ARITH_RULE `k - i - 1 = k - (i + 1)`] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_STEP] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN
ENSURES_INIT_TAC "s0" THEN
X86_STEPS_TAC BIGNUM_MONTREDC_EXEC (1--4) THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[] THEN
REWRITE_TAC[WORD_ADD] THEN REPEAT CONJ_TAC THENL
[REWRITE_TAC[ARITH_RULE `p - (n + 1) = p - n - 1`] THEN
GEN_REWRITE_TAC RAND_CONV [WORD_SUB] THEN
ASM_REWRITE_TAC[ARITH_RULE `1 <= p - n <=> n < p`];
REWRITE_TAC[LOWDIGITS_CLAUSES];
REWRITE_TAC[VAL_EQ_0; WORD_SUB_EQ_0] THEN
VAL_INT64_TAC `k - i:num` THEN
ASM_REWRITE_TAC[GSYM VAL_EQ; VAL_WORD_1] THEN ARITH_TAC] THEN
SIMP_TAC[LEXICOGRAPHIC_LT; LOWDIGITS_BOUND] THEN
SIMP_TAC[VAL_WORD_EQ; DIMINDEX_64; BIGDIGIT_BOUND] THEN
POP_ASSUM_LIST(K ALL_TAC) THEN REWRITE_TAC[bitval] THEN ARITH_TAC;
X_GEN_TAC `i:num` THEN STRIP_TAC THEN VAL_INT64_TAC `i:num` THEN
ASM_REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN
ENSURES_INIT_TAC "s0" THEN X86_STEPS_TAC BIGNUM_MONTREDC_EXEC [1] THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[];
ASM_SIMP_TAC[LOWDIGITS_SELF; HIGHDIGITS_ZERO; SUB_REFL] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_TRIVIAL]] THEN
ABBREV_TAC `c <=> n <= 2 EXP (64 * k) * bitval c0 + mm` THEN
ENSURES_WHILE_UP_TAC `k:num` `pc + 0x155` `pc + 0x169`
`\i s. read RDI s = word k /\
read RSI s = z /\
read R8 s = m /\
read RBP s = word_neg(word(bitval c)) /\
read RBX s = word i /\
val(word_neg(read R12 s)) <= 1 /\
bignum_from_memory (word_add z (word(8 * i)),k - i) s =
highdigits mm i /\
bignum_from_memory (word_add m (word(8 * i)),k - i) s =
highdigits n i /\
&(bignum_from_memory(z,i) s):real =
&2 pow (64 * i) * &(val(word_neg(read R12 s))) +
&(lowdigits mm i) - &(bitval c) * &(lowdigits n i)` THEN
ASM_REWRITE_TAC[] THEN REPEAT CONJ_TAC THENL
[REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN
ENSURES_INIT_TAC "s0" THEN X86_STEPS_TAC BIGNUM_MONTREDC_EXEC (1--6) THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[] THEN
REWRITE_TAC[WORD_SUB_LZERO; SUB_0; GSYM BIGNUM_FROM_MEMORY_BYTES] THEN
REWRITE_TAC[WORD_ADD_0; MULT_CLAUSES; BITVAL_CLAUSES; WORD_NEG_0] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_TRIVIAL; LOWDIGITS_0; VAL_WORD_0] THEN
ASM_REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES; HIGHDIGITS_0; LE_0] THEN
REWRITE_TAC[REAL_MUL_RZERO; REAL_ADD_LID; REAL_SUB_REFL] THEN
REWRITE_TAC[WORD_NOT_MASK] THEN EXPAND_TAC "c" THEN
REPLICATE_TAC 3 AP_TERM_TAC THEN REWRITE_TAC[NOT_LT; ADD_CLAUSES] THEN
REWRITE_TAC[VAL_WORD_BITVAL] THEN BOOL_CASES_TAC `c0:bool` THEN
REWRITE_TAC[BITVAL_CLAUSES; ADD_CLAUSES; MULT_CLAUSES] THEN
ASM_SIMP_TAC[ARITH_RULE `n:num < e ==> n <= e + m`; BITVAL_BOUND] THEN
REWRITE_TAC[CONJUNCT1 LE; BITVAL_EQ_0; NOT_LT];
X_GEN_TAC `i:num` THEN STRIP_TAC THEN VAL_INT64_TAC `i:num` THEN
GHOST_INTRO_TAC `cval:num` `\s. val(word_neg(read R12 s))` THEN
GLOBALIZE_PRECONDITION_TAC THEN
FIRST_X_ASSUM(X_CHOOSE_THEN `cin:bool` SUBST_ALL_TAC o
GEN_REWRITE_RULE I [NUM_AS_BITVAL]) THEN
REWRITE_TAC[VAL_EQ_BITVAL] THEN
REWRITE_TAC[WORD_RULE `word_neg x:int64 = y <=> x = word_neg y`] THEN
GEN_REWRITE_TAC (RATOR_CONV o LAND_CONV o ONCE_DEPTH_CONV)
[BIGNUM_FROM_MEMORY_OFFSET_EQ_HIGHDIGITS] THEN
ASM_REWRITE_TAC[SUB_EQ_0; GSYM NOT_LT] THEN
REWRITE_TAC[ARITH_RULE `k - i - 1 = k - (i + 1)`] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_STEP] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN
ENSURES_INIT_TAC "s0" THEN
X86_ACCSTEPS_TAC BIGNUM_MONTREDC_EXEC [4] (1--6) THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[GSYM WORD_ADD] THEN
REWRITE_TAC[WORD_NEG_NEG; VAL_WORD_BITVAL; BITVAL_BOUND] THEN
ACCUMULATOR_POP_ASSUM_LIST(MP_TAC o end_itlist CONJ) THEN
SIMP_TAC[VAL_WORD_EQ; DIMINDEX_64; BIGDIGIT_BOUND] THEN
REWRITE_TAC[WORD_ADD; WORD_NEG_NEG; VAL_WORD_BITVAL; WORD_BITVAL_EQ_0;
LOWDIGITS_CLAUSES; WORD_NEG_EQ_0; BITVAL_BOUND; NOT_LT] THEN
REWRITE_TAC[WORD_AND_MASK] THEN COND_CASES_TAC THEN
REWRITE_TAC[GSYM REAL_OF_NUM_CLAUSES] THEN ASM_REWRITE_TAC[NOT_LT] THEN
SIMP_TAC[VAL_WORD_EQ; DIMINDEX_64; BIGDIGIT_BOUND; VAL_WORD_0;
BITVAL_CLAUSES; ARITH_RULE `64 * (i + 1) = 64 * i + 64`] THEN
REWRITE_TAC[REAL_POW_ADD] THEN CONV_TAC REAL_RING;
X_GEN_TAC `i:num` THEN STRIP_TAC THEN VAL_INT64_TAC `i:num` THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN
ENSURES_INIT_TAC "s0" THEN X86_STEPS_TAC BIGNUM_MONTREDC_EXEC (1--2) THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[];
ASM_SIMP_TAC[BIGNUM_FROM_MEMORY_BYTES; LOWDIGITS_SELF] THEN
ENSURES_INIT_TAC "s0" THEN X86_STEPS_TAC BIGNUM_MONTREDC_EXEC (1--2) THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[VAL_WORD_SUB_EQ_0] THEN
STRIP_TAC THEN UNDISCH_TAC `ODD n ==> r = 0` THEN
ASM_REWRITE_TAC[] THEN DISCH_THEN SUBST_ALL_TAC THEN
RULE_ASSUM_TAC(REWRITE_RULE[ADD_CLAUSES])] THEN
FIRST_ASSUM(ASSUME_TAC o MATCH_MP (MESON[ODD] `ODD n ==> ~(n = 0)`)) THEN
TRANS_TAC EQ_TRANS `(2 EXP (64 * k) * bitval c0 + mm) MOD n` THEN
CONJ_TAC THENL
[REWRITE_TAC[GSYM REAL_OF_NUM_CLAUSES] THEN
MATCH_MP_TAC EQUAL_FROM_CONGRUENT_REAL THEN
MAP_EVERY EXISTS_TAC [`64 * k`; `&0:real`] THEN CONJ_TAC THENL
[REWRITE_TAC[REAL_OF_NUM_CLAUSES; GSYM BIGNUM_FROM_MEMORY_BYTES] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_BOUND; LE_0];
REWRITE_TAC[INTEGER_CLOSED; REAL_POS]] THEN
CONJ_TAC THENL
[REWRITE_TAC[REAL_OF_NUM_CLAUSES] THEN TRANS_TAC LT_TRANS `n:num` THEN
ASM_REWRITE_TAC[MOD_LT_EQ];
ALL_TAC] THEN
MP_TAC(SPECL [`2 EXP (64 * k) * bitval c0 + mm`; `n:num`]
MOD_CASES) THEN
ANTS_TAC THENL
[MATCH_MP_TAC(MESON[LT_MULT_LCANCEL]
`!e. ~(e = 0) /\ e * a < e * b ==> a < b`) THEN
EXISTS_TAC `2 EXP (64 * p)` THEN
ASM_REWRITE_TAC[EXP_EQ_0; ARITH_EQ] THEN
MATCH_MP_TAC(ARITH_RULE
`q * n < e * n /\ aa <= e * n ==> q * n + aa < e * 2 * n`) THEN
ASM_REWRITE_TAC[LT_MULT_RCANCEL];
DISCH_THEN SUBST1_TAC] THEN
REWRITE_TAC[GSYM NOT_LE; COND_SWAP] THEN ONCE_REWRITE_TAC[COND_RAND] THEN
SIMP_TAC[GSYM REAL_OF_NUM_SUB] THEN
ASM_REWRITE_TAC[GSYM REAL_OF_NUM_CLAUSES] THEN
ASM_CASES_TAC `c:bool` THEN ASM_REWRITE_TAC[BITVAL_CLAUSES] THEN
REWRITE_TAC[ONCE_REWRITE_RULE[REAL_MUL_SYM] real_div] THEN
REWRITE_TAC[REAL_ADD_LDISTRIB; REAL_SUB_LDISTRIB; REAL_MUL_ASSOC] THEN
SIMP_TAC[REAL_MUL_LINV; REAL_POW_EQ_0; REAL_OF_NUM_EQ; ARITH_EQ] THEN
REAL_INTEGER_TAC;
REWRITE_TAC[GSYM CONG] THEN
FIRST_ASSUM(MATCH_MP_TAC o MATCH_MP (NUMBER_RULE
`e * x:num = q * n + ab
==> (i * e == 1) (mod n)
==> (x == i * ab) (mod n)`)) THEN
ASM_REWRITE_TAC[INVERSE_MOD_LMUL_EQ; COPRIME_REXP; COPRIME_2]]] THEN
ASM_CASES_TAC `p = 0` THENL
[UNDISCH_THEN `p = 0` SUBST_ALL_TAC THEN
REPEAT(FIRST_X_ASSUM(SUBST_ALL_TAC o MATCH_MP (ARITH_RULE
`a < 2 EXP (64 * 0) ==> a = 0`))) THEN
X86_SIM_TAC BIGNUM_MONTREDC_EXEC (1--2) THEN
REPEAT(EXISTS_TAC `0`) THEN
REWRITE_TAC[MULT_CLAUSES; EXP; ADD_CLAUSES] THEN ARITH_TAC;
ALL_TAC] THEN
ENSURES_WHILE_UP_TAC `p:num` `pc + 0xba` `pc + 0x12a`
`\i s. read RSP s = stackpointer /\
read RDI s = word k /\
read RSI s = z /\
read R10 s = word nx /\
read RCX s = x /\
read R8 s = m /\
read R9 s = word p /\
read (memory :> bytes64 stackpointer) s = word w /\
read R14 s = word i /\
bignum_from_memory (m,k) s = n /\
bignum_from_memory(word_add x (word(8 * (k + i))),nx - (k + i)) s =
highdigits a (k + i) /\
?q r. q < 2 EXP (64 * i) /\ r < 2 EXP (64 * i) /\
2 EXP (64 * i) *
(2 EXP (64 * k) * val(read R15 s) +
bignum_from_memory(z,k) s) +
r =
q * n + lowdigits a (k + i) /\
(ODD n ==> r = 0)` THEN
ASM_REWRITE_TAC[] THEN REPEAT CONJ_TAC THENL
[X86_SIM_TAC BIGNUM_MONTREDC_EXEC (1--3) THEN
ASM_REWRITE_TAC[ADD_CLAUSES; VAL_WORD_0] THEN
REPEAT(EXISTS_TAC `0`) THEN ARITH_TAC;
X_GEN_TAC `i:num` THEN STRIP_TAC THEN VAL_INT64_TAC `i:num` THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN
ENSURES_INIT_TAC "s0" THEN X86_STEPS_TAC BIGNUM_MONTREDC_EXEC (1--2) THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[];
X86_SIM_TAC BIGNUM_MONTREDC_EXEC (1--2)] THEN
X_GEN_TAC `i:num` THEN STRIP_TAC THEN VAL_INT64_TAC `i:num` THEN
GHOST_INTRO_TAC `cout:num` `\s. val(read R15 s)` THEN
GHOST_INTRO_TAC `z1:num` `bignum_from_memory(z,k)` THEN
BIGNUM_TERMRANGE_TAC `k:num` `z1:num` THEN
GLOBALIZE_PRECONDITION_TAC THEN ASM_REWRITE_TAC[] THEN
FIRST_X_ASSUM(X_CHOOSE_THEN `q:num` (X_CHOOSE_THEN `r:num`
STRIP_ASSUME_TAC)) THEN
REWRITE_TAC[VAL_WORD_GALOIS; DIMINDEX_64] THEN
GLOBALIZE_PRECONDITION_TAC THEN
* * The initial prelude of the reduction * *
ABBREV_TAC `q0 = (w * z1) MOD 2 EXP 64` THEN
SUBGOAL_THEN `q0 < 2 EXP 64 /\ val(word q0:int64) = q0`
STRIP_ASSUME_TAC THENL
[EXPAND_TAC "q0" THEN CONJ_TAC THENL [ARITH_TAC; ALL_TAC] THEN
REWRITE_TAC[VAL_WORD; DIMINDEX_64; MOD_MOD_REFL];
ALL_TAC] THEN
ENSURES_SEQUENCE_TAC `pc + 0xd9`
`\s. read RSP s = stackpointer /\
read RDI s = word k /\
read RSI s = z /\
read R10 s = word nx /\
read RCX s = x /\
read R8 s = m /\
read R9 s = word p /\
read (memory :> bytes64 stackpointer) s = word w /\
read R14 s = word i /\
bignum_from_memory (m,k) s = n /\
bignum_from_memory (word_add x (word (8 * (k + i))),nx - (k + i)) s =
highdigits a (k + i) /\
read R15 s = word cout /\
bignum_from_memory (z,k) s = z1 /\
read RBP s = word q0 /\
read RBX s = word 1 /\
read R13 s = word k /\
2 EXP 64 * (bitval(read CF s) + val(read R11 s)) + val(read RAX s) =
q0 * bigdigit n 0 + bigdigit z1 0` THEN
CONJ_TAC THENL
[REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN ENSURES_INIT_TAC "s0" THEN
SUBGOAL_THEN
`bignum_from_memory(m,k) s0 = highdigits n 0 /\
bignum_from_memory(z,k) s0 = highdigits z1 0`
MP_TAC THENL
[ASM_REWRITE_TAC[HIGHDIGITS_0; BIGNUM_FROM_MEMORY_BYTES];
GEN_REWRITE_TAC (LAND_CONV o BINOP_CONV)
[BIGNUM_FROM_MEMORY_EQ_HIGHDIGITS] THEN
ASM_REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES; ADD_CLAUSES] THEN
STRIP_TAC] THEN
X86_ACCSTEPS_TAC BIGNUM_MONTREDC_EXEC [5;6] (1--9) THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[] THEN
MATCH_MP_TAC(TAUT `p /\ (p ==> q) ==> p /\ q`) THEN CONJ_TAC THENL
[UNDISCH_THEN `(w * z1) MOD 2 EXP 64 = q0` (SUBST1_TAC o SYM) THEN
REWRITE_TAC[GSYM WORD_MUL] THEN ONCE_REWRITE_TAC[GSYM WORD_MOD_SIZE] THEN
REWRITE_TAC[GSYM LOWDIGITS_1; lowdigits; MULT_CLAUSES] THEN
REWRITE_TAC[ADD_CLAUSES; DIMINDEX_64; VAL_WORD] THEN
CONV_TAC MOD_DOWN_CONV THEN REWRITE_TAC[MULT_SYM];
DISCH_THEN SUBST_ALL_TAC] THEN
ASM_REWRITE_TAC[WORD_SUB; ARITH_RULE `1 <= k <=> ~(k = 0)`] THEN
REWRITE_TAC[GSYM REAL_OF_NUM_CLAUSES] THEN
ACCUMULATOR_POP_ASSUM_LIST(MP_TAC o end_itlist CONJ o DECARRY_RULE) THEN
DISCH_THEN(fun th -> REWRITE_TAC[th]) THEN
ASM_SIMP_TAC[VAL_WORD_EQ; DIMINDEX_64; BIGDIGIT_BOUND] THEN
REAL_ARITH_TAC;
ALL_TAC] THEN
GHOST_INTRO_TAC `r0:num` `\s. val(read RAX s)` THEN
REWRITE_TAC[VAL_WORD_GALOIS; DIMINDEX_64] THEN
GLOBALIZE_PRECONDITION_TAC THEN
ENSURES_SEQUENCE_TAC `pc + 0x102`
`\s. read RSP s = stackpointer /\
read RDI s = word k /\
read RSI s = z /\
read R10 s = word nx /\
read RCX s = x /\
read R8 s = m /\
read R9 s = word p /\
read (memory :> bytes64 stackpointer) s = word w /\
read R14 s = word i /\
bignum_from_memory (m,k) s = n /\
bignum_from_memory (word_add x (word (8 * (k + i))),nx - (k + i)) s =
highdigits a (k + i) /\
read R15 s = word cout /\
read RBP s = word q0 /\
read RBX s = word k /\
2 EXP (64 * k) * (bitval(read CF s) + val(read R11 s)) +
2 EXP 64 * bignum_from_memory (z,k - 1) s +
r0 =
lowdigits z1 k + q0 * lowdigits n k` THEN
CONJ_TAC THENL
[ASM_CASES_TAC `k = 1` THENL
[UNDISCH_THEN `k = 1` SUBST_ALL_TAC THEN
X86_SIM_TAC BIGNUM_MONTREDC_EXEC (1--2) THEN
REWRITE_TAC[GSYM BIGNUM_FROM_MEMORY_BYTES] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_TRIVIAL] THEN
ASM_REWRITE_TAC[MULT_CLAUSES; ADD_CLAUSES] THEN
REWRITE_TAC[LOWDIGITS_1] THEN ARITH_TAC;
ALL_TAC] THEN
* * The reduction loop * *
VAL_INT64_TAC `k - 1` THEN
ENSURES_WHILE_PAUP_TAC `1` `k:num` `pc + 0xde` `pc + 0x100`
`\j s. (read RSP s = stackpointer /\
read RDI s = word k /\
read RSI s = z /\
read R10 s = word nx /\
read RCX s = x /\
read R8 s = m /\
read R9 s = word p /\
read (memory :> bytes64 stackpointer) s = word w /\
read R14 s = word i /\
bignum_from_memory (m,k) s = n /\
bignum_from_memory
(word_add x (word (8 * (k + i))),nx - (k + i)) s =
highdigits a (k + i) /\
read R15 s = word cout /\
read RBP s = word q0 /\
read RBX s = word j /\
read R13 s = word(k - j) /\
bignum_from_memory(word_add z (word (8 * j)),k - j) s =
highdigits z1 j /\
bignum_from_memory(word_add m (word (8 * j)),k - j) s =
highdigits n j /\
2 EXP (64 * j) * (bitval(read CF s) + val(read R11 s)) +
2 EXP 64 * bignum_from_memory(z,j-1) s + r0 =
lowdigits z1 j + q0 * lowdigits n j) /\
(read ZF s <=> j = k)` THEN
REPEAT CONJ_TAC THENL
[ASM_REWRITE_TAC[ARITH_RULE `1 < k <=> ~(k = 0 \/ k = 1)`];
REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN ENSURES_INIT_TAC "s0" THEN
X86_STEPS_TAC BIGNUM_MONTREDC_EXEC (1--2) THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[VAL_WORD_SUB_EQ_0] THEN
ASM_REWRITE_TAC[ARITH_RULE `k <= 1 <=> k = 0 \/ k = 1`] THEN
ASM_REWRITE_TAC[VAL_WORD_1; ARITH_RULE `k <= 1 <=> k = 0 \/ k = 1`] THEN
ASM_REWRITE_TAC[WORD_SUB; ARITH_RULE `1 <= k <=> ~(k = 0)`] THEN
REWRITE_TAC[GSYM BIGNUM_FROM_MEMORY_BYTES] THEN
REWRITE_TAC[GSYM BIGNUM_FROM_MEMORY_DIV; BIGNUM_FROM_MEMORY_TRIVIAL] THEN
ASM_REWRITE_TAC[GSYM highdigits; BIGNUM_FROM_MEMORY_BYTES] THEN
ASM_REWRITE_TAC[MULT_CLAUSES; ADD_CLAUSES; LOWDIGITS_1] THEN ARITH_TAC;
X_GEN_TAC `j:num` THEN STRIP_TAC THEN
MAP_EVERY VAL_INT64_TAC [`j:num`; `j - 1`] THEN
SUBGOAL_THEN `word_sub (word j) (word 1):int64 = word(j - 1)`
ASSUME_TAC THENL [ASM_REWRITE_TAC[WORD_SUB]; ALL_TAC] THEN
GHOST_INTRO_TAC `cin:bool` `read CF` THEN
GHOST_INTRO_TAC `hin:int64` `read R11` THEN
MP_TAC(GENL [`x:int64`; `a:num`]
(ISPECL [`x:int64`; `k - j:num`; `a:num`; `j:num`]
BIGNUM_FROM_MEMORY_OFFSET_EQ_HIGHDIGITS)) THEN
ASM_REWRITE_TAC[ARITH_RULE `k - j = 0 <=> ~(j < k)`] THEN
DISCH_THEN(fun th -> ONCE_REWRITE_TAC[th]) THEN
REWRITE_TAC[ARITH_RULE `k - j - 1 = k - (j + 1)`] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_STEP] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN
ENSURES_INIT_TAC "s0" THEN
UNDISCH_THEN `val(word q0:int64) = q0` (K ALL_TAC) THEN
SUBGOAL_THEN `nonoverlapping (word_add z (word (8 * (j - 1))):int64,8)
(word_add x (word (8 * (k + i))),
8 * (nx - (k + i)))`
MP_TAC THEN REWRITE_TAC[NONOVERLAPPING_CLAUSES] THENL
[ASM_CASES_TAC `nx - (k + i) = 0` THEN
ASM_SIMP_TAC[MULT_CLAUSES; NONOVERLAPPING_MODULO_TRIVIAL] THEN
RULE_ASSUM_TAC(REWRITE_RULE[SUB_EQ_0; NOT_LE]) THEN
FIRST_X_ASSUM(DISJ_CASES_THEN2 SUBST_ALL_TAC MP_TAC) THENL
[ALL_TAC;
GEN_REWRITE_TAC LAND_CONV [NONOVERLAPPING_MODULO_SYM] THEN
MATCH_MP_TAC(ONCE_REWRITE_RULE[IMP_CONJ_ALT]
NONOVERLAPPING_MODULO_SUBREGIONS) THEN
CONJ_TAC THEN CONTAINED_TAC] THEN
SUBGOAL_THEN
`word_add z (word (8 * (k + i))):int64 =
word_add (word_add z (word(8 * (j - 1))))
(word(8 + 8 * ((k + i) - j)))`
SUBST1_TAC THENL
[REWRITE_TAC[GSYM WORD_ADD_ASSOC; GSYM WORD_ADD] THEN
AP_TERM_TAC THEN AP_TERM_TAC THEN SIMPLE_ARITH_TAC;
NONOVERLAPPING_TAC];
DISCH_TAC] THEN
ABBREV_TAC `j' = j - 1` THEN
SUBGOAL_THEN `j = j' + 1` SUBST_ALL_TAC THENL
[EXPAND_TAC "j'" THEN UNDISCH_TAC `1 <= j` THEN ARITH_TAC;
ALL_TAC] THEN
RULE_ASSUM_TAC(REWRITE_RULE[ARITH_RULE `(j' + 1) + 1 = j' + 2`]) THEN
REWRITE_TAC[ARITH_RULE `(j' + 1) + 1 = j' + 2`] THEN
MP_TAC(SPEC `j':num` WORD_INDEX_WRAP) THEN DISCH_TAC THEN
X86_ACCSTEPS_TAC BIGNUM_MONTREDC_EXEC [1;4] (1--5) THEN
RULE_ASSUM_TAC(REWRITE_RULE[WORD_RULE
`word_sub x (word_neg y):int64 = word_add x y`]) THEN
ACCUMULATE_ARITH_TAC "s5" THEN
X86_ACCSTEPS_TAC BIGNUM_MONTREDC_EXEC [6] (6--10) THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[] THEN
CONJ_TAC THENL [CONV_TAC WORD_RULE; ALL_TAC] THEN
MATCH_MP_TAC(TAUT `p /\ (p ==> q) ==> p /\ q`) THEN CONJ_TAC THENL
[REWRITE_TAC[ARITH_RULE `k - (j + 2) = k - (j + 1) - 1`] THEN
GEN_REWRITE_TAC RAND_CONV [WORD_SUB] THEN
ASM_REWRITE_TAC[ARITH_RULE `1 <= k - (j + 1) <=> j + 1 < k`];
DISCH_THEN SUBST1_TAC] THEN
CONJ_TAC THENL
[ALL_TAC;
ASM_SIMP_TAC[ARITH_RULE
`j + 1 < k ==> (j + 2 = k <=> k - (j + 2) = 0)`] THEN
REWRITE_TAC[VAL_EQ_0] THEN MATCH_MP_TAC WORD_EQ_0 THEN
REWRITE_TAC[DIMINDEX_64] THEN UNDISCH_TAC `k < 2 EXP 64` THEN
ARITH_TAC] THEN
REWRITE_TAC[ARITH_RULE `(n + 2) - 1 = n + 1`] THEN
REWRITE_TAC[GSYM BIGNUM_FROM_MEMORY_BYTES] THEN
ASM_REWRITE_TAC[BIGNUM_FROM_MEMORY_STEP] THEN
SUBGOAL_THEN `j' + 2 = (j' + 1) + 1` MP_TAC THENL
[ARITH_TAC; DISCH_THEN SUBST_ALL_TAC] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN
ONCE_REWRITE_TAC[LOWDIGITS_CLAUSES] THEN
GEN_REWRITE_TAC RAND_CONV
[ARITH_RULE `(e * d1 + d0) + c * (e * a1 + a0):num =
e * (c * a1 + d1) + d0 + c * a0`] THEN
FIRST_X_ASSUM(fun th ->
GEN_REWRITE_TAC (RAND_CONV o RAND_CONV) [SYM th]) THEN
REWRITE_TAC[EXP_ADD; ARITH_RULE `64 * (i + 1) = 64 * i + 64`] THEN
REWRITE_TAC[GSYM REAL_OF_NUM_CLAUSES] THEN
ACCUMULATOR_POP_ASSUM_LIST(MP_TAC o end_itlist CONJ) THEN
GEN_REWRITE_TAC LAND_CONV
[TAUT `p /\ q /\ r /\ s <=> p /\ s /\ q /\ r`] THEN
DISCH_THEN(MP_TAC o end_itlist CONJ o DECARRY_RULE o CONJUNCTS) THEN
ASM_SIMP_TAC[VAL_WORD_EQ; DIMINDEX_64; BIGDIGIT_BOUND] THEN
REWRITE_TAC[GSYM REAL_OF_NUM_CLAUSES] THEN
DISCH_THEN(fun th -> REWRITE_TAC[th]) THEN REAL_ARITH_TAC;
X_GEN_TAC `j:num` THEN STRIP_TAC THEN
MAP_EVERY VAL_INT64_TAC [`j:num`; `j - 1`] THEN
X86_SIM_TAC BIGNUM_MONTREDC_EXEC [1];
X86_SIM_TAC BIGNUM_MONTREDC_EXEC [1]];
ALL_TAC] THEN
SUBGOAL_THEN `cout < 2` MP_TAC THENL
[SUBGOAL_THEN `q * n + lowdigits a (k + i) < 2 EXP (64 * (k + i)) * 2`
MP_TAC THENL
[MATCH_MP_TAC(ARITH_RULE `x < e /\ y < e ==> x + y < e * 2`) THEN
REWRITE_TAC[LOWDIGITS_BOUND] THEN
REWRITE_TAC[ARITH_RULE `64 * (k + p) = 64 * p + 64 * k`] THEN
ASM_SIMP_TAC[LT_MULT2; EXP_ADD];
FIRST_X_ASSUM(fun th ->
GEN_REWRITE_TAC (LAND_CONV o LAND_CONV) [SYM th]) THEN
REWRITE_TAC[LEFT_ADD_DISTRIB; MULT_ASSOC; GSYM ADD_ASSOC] THEN
REWRITE_TAC[ARITH_RULE `64 * k + 64 * p = 64 * (p + k)`] THEN
DISCH_THEN(MP_TAC o MATCH_MP (ARITH_RULE
`a + b:num < c ==> a < c`)) THEN
REWRITE_TAC[GSYM EXP_ADD; GSYM LEFT_ADD_DISTRIB] THEN
REWRITE_TAC[LT_MULT_LCANCEL; EXP_EQ_0; ARITH_EQ]];
GEN_REWRITE_TAC LAND_CONV [NUM_AS_BITVAL_ALT] THEN
DISCH_THEN(X_CHOOSE_THEN `tc:bool` SUBST_ALL_TAC)] THEN
ASM_SIMP_TAC[LOWDIGITS_SELF] THEN
GHOST_INTRO_TAC `cin:bool` `read CF` THEN
GHOST_INTRO_TAC `hin:int64` `read R11` THEN
VAL_INT64_TAC `k - 1` THEN
SUBGOAL_THEN `word_sub (word k) (word 1):int64 = word(k - 1)`
ASSUME_TAC THENL
[ASM_REWRITE_TAC[WORD_SUB; ARITH_RULE `1 <= k <=> ~(k = 0)`];
ALL_TAC] THEN
VAL_INT64_TAC `k + i:num` THEN
MP_TAC(WORD_RULE `word_add (word k) (word i):int64 = word(k + i)`) THEN
DISCH_TAC THEN
MP_TAC(SPEC `k - 1` WORD_INDEX_WRAP) THEN
ASM_SIMP_TAC[SUB_ADD; LE_1] THEN DISCH_TAC THEN
ASM_CASES_TAC `nx:num <= k + i` THENL
[REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN ENSURES_INIT_TAC "s0" THEN
X86_ACCSTEPS_TAC BIGNUM_MONTREDC_EXEC [1] (1--8) THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[] THEN
CONJ_TAC THENL [CONV_TAC WORD_RULE; ALL_TAC] THEN CONJ_TAC THENL
[ASM_SIMP_TAC[ARITH_RULE `nx <= k + i ==> nx - (k + i + 1) = 0`] THEN
REWRITE_TAC[GSYM BIGNUM_FROM_MEMORY_BYTES] THEN CONV_TAC SYM_CONV THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_TRIVIAL] THEN
MATCH_MP_TAC HIGHDIGITS_ZERO THEN
TRANS_TAC LTE_TRANS `2 EXP (64 * nx)` THEN
ASM_REWRITE_TAC[LE_EXP] THEN UNDISCH_TAC `nx:num <= k + i` THEN
ARITH_TAC;
ALL_TAC];
SUBGOAL_THEN `nonoverlapping (word_add z (word (8 * (k - 1))):int64,8)
(word_add x (word (8 * (k + i))),
8 * (nx - (k + i)))`
MP_TAC THEN REWRITE_TAC[NONOVERLAPPING_CLAUSES] THENL
[RULE_ASSUM_TAC(REWRITE_RULE[NOT_LE]) THEN
FIRST_X_ASSUM(DISJ_CASES_THEN2 SUBST_ALL_TAC MP_TAC) THENL
[ALL_TAC;
GEN_REWRITE_TAC LAND_CONV [NONOVERLAPPING_MODULO_SYM] THEN
MATCH_MP_TAC(ONCE_REWRITE_RULE[IMP_CONJ_ALT]
NONOVERLAPPING_MODULO_SUBREGIONS) THEN
CONJ_TAC THEN CONTAINED_TAC] THEN
SUBGOAL_THEN
`word_add z (word (8 * (k + i))):int64 =
word_add (word_add z (word(8 * (k - 1))))
(word(8 + 8 * ((k + i) - k)))`
SUBST1_TAC THENL
[REWRITE_TAC[GSYM WORD_ADD_ASSOC; GSYM WORD_ADD] THEN
AP_TERM_TAC THEN AP_TERM_TAC THEN SIMPLE_ARITH_TAC;
NONOVERLAPPING_TAC];
DISCH_TAC] THEN
GEN_REWRITE_TAC (RATOR_CONV o LAND_CONV o ONCE_DEPTH_CONV)
[BIGNUM_FROM_MEMORY_OFFSET_EQ_HIGHDIGITS] THEN
ASM_REWRITE_TAC[SUB_EQ_0] THEN
REWRITE_TAC[ARITH_RULE `n - (k + i) - 1 = n - (k + i + 1)`] THEN
REWRITE_TAC[ARITH_RULE `(k + i) + 1 = k + i + 1`] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN ENSURES_INIT_TAC "s0" THEN
X86_ACCSTEPS_TAC BIGNUM_MONTREDC_EXEC [1;8;9] (1--11) THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[] THEN
CONJ_TAC THENL [CONV_TAC WORD_RULE; ALL_TAC]] THEN
(MAP_EVERY EXISTS_TAC
[`2 EXP (64 * i) * q0 + q`;
`2 EXP (64 * i) * r0 + r`] THEN
GEN_REWRITE_TAC I [CONJ_ASSOC] THEN CONJ_TAC THENL
[REWRITE_TAC[EXP_ADD; ARITH_RULE `64 * (i + 1) = 64 * i + 64`] THEN
CONJ_TAC THEN MATCH_MP_TAC(ARITH_RULE
`q1 < e /\ q0 < ee /\ (q1 < e ==> (q1 + 1) * ee <= e * ee)
==> ee * q1 + q0 < ee * e`) THEN
ASM_REWRITE_TAC[LE_MULT_RCANCEL; EXP_EQ_0; ARITH_EQ] THEN
ASM_REWRITE_TAC[ARITH_RULE `n + 1 <= m <=> n < m`];
ALL_TAC] THEN
CONJ_TAC THENL
[ALL_TAC;
DISCH_THEN(fun th ->
REPEAT(FIRST_X_ASSUM(STRIP_ASSUME_TAC o C MATCH_MP th))) THEN
ASM_REWRITE_TAC[ADD_EQ_0; MULT_EQ_0; EXP_EQ_0; ARITH_EQ] THEN
MATCH_MP_TAC CONG_IMP_EQ THEN EXISTS_TAC `2 EXP 64` THEN
ASM_REWRITE_TAC[EXP_LT_0; ARITH_EQ] THEN
FIRST_X_ASSUM(MATCH_MP_TAC o MATCH_MP (NUMBER_RULE
`ee * x + e * y + r = z
==> e divides ee /\ (z == 0) (mod e)
==> (r == 0) (mod e)`)) THEN
CONJ_TAC THENL
[MATCH_MP_TAC DIVIDES_EXP_LE_IMP THEN
UNDISCH_TAC `~(k = 0)` THEN ARITH_TAC;
UNDISCH_THEN `(w * z1) MOD 2 EXP 64 = q0` (SUBST1_TAC o SYM)] THEN
REWRITE_TAC[CONG] THEN CONV_TAC MOD_DOWN_CONV THEN
REWRITE_TAC[GSYM CONG] THEN MATCH_MP_TAC(NUMBER_RULE
`(n * w + 1 == 0) (mod e) ==> (z + (w * z) * n == 0) (mod e)`) THEN
ASM_REWRITE_TAC[]] THEN
SUBGOAL_THEN `8 * k = 8 * ((k - 1) + 1)` SUBST1_TAC THENL
[UNDISCH_TAC `~(k = 0)` THEN ARITH_TAC;
REWRITE_TAC[GSYM BIGNUM_FROM_MEMORY_BYTES]] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_STEP] THEN
ASM_REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN
REWRITE_TAC[LEFT_ADD_DISTRIB; MULT_ASSOC; GSYM EXP_ADD] THEN
REWRITE_TAC[GSYM LEFT_ADD_DISTRIB] THEN
SUBGOAL_THEN `(i + 1) + (k - 1) = i + k` SUBST1_TAC THENL
[UNDISCH_TAC `~(k = 0)` THEN ARITH_TAC; ALL_TAC] THEN
REWRITE_TAC[LEFT_ADD_DISTRIB; EXP_ADD; MULT_CLAUSES] THEN
REWRITE_TAC[LOWDIGITS_CLAUSES; ARITH_RULE `k + i + 1 = (k + i) + 1`]) THEN
REWRITE_TAC[ARITH_RULE `64 * (k + i) = 64 * k + 64 * i`; EXP_ADD] THENL
[REWRITE_TAC[VAL_WORD_0; ADD_CLAUSES; MULT_CLAUSES] THEN
SUBGOAL_THEN `bigdigit a (k + i) = 0` SUBST1_TAC THENL
[MATCH_MP_TAC BIGDIGIT_ZERO THEN
TRANS_TAC LTE_TRANS `2 EXP (64 * nx)` THEN
ASM_REWRITE_TAC[LE_EXP] THEN UNDISCH_TAC `nx:num <= k + i` THEN
ARITH_TAC;
REWRITE_TAC[MULT_CLAUSES; ADD_CLAUSES]] THEN
REPEAT(FIRST_X_ASSUM(MP_TAC o check
(can (term_match [] `2 EXP (64 * k) * x + y = z`) o concl))) THEN
REWRITE_TAC[GSYM REAL_OF_NUM_CLAUSES] THEN
ACCUMULATOR_POP_ASSUM_LIST(MP_TAC o end_itlist CONJ o DECARRY_RULE) THEN
ASM_SIMP_TAC[VAL_WORD_EQ; DIMINDEX_64; VAL_WORD_BITVAL; ADD_CLAUSES] THEN
DISCH_THEN(fun th -> REWRITE_TAC[th]) THEN
CONV_TAC REAL_RING;
RULE_ASSUM_TAC(REWRITE_RULE[ADD_CLAUSES; VAL_WORD_BITVAL]) THEN
REPEAT(FIRST_X_ASSUM(MP_TAC o check
(can (term_match [] `2 EXP (64 * k) * x + y = z`) o concl))) THEN
REWRITE_TAC[GSYM REAL_OF_NUM_CLAUSES] THEN
ACCUMULATOR_POP_ASSUM_LIST(MP_TAC o end_itlist CONJ o DECARRY_RULE) THEN
ASM_SIMP_TAC[VAL_WORD_EQ; DIMINDEX_64; VAL_WORD_BITVAL; ADD_CLAUSES;
BIGDIGIT_BOUND] THEN
DISCH_THEN(fun th -> REWRITE_TAC[th]) THEN
CONV_TAC REAL_RING]);;
let BIGNUM_MONTREDC_SUBROUTINE_CORRECT = time prove
(`!k z r x m p a n pc stackpointer returnaddress.
nonoverlapping (word_sub stackpointer (word 56),64) (z,8 * val k) /\
ALL (nonoverlapping (word_sub stackpointer (word 56),56))
[(word pc,0x17d); (x,8 * val r); (m,8 * val k)] /\
ALL (nonoverlapping (z,8 * val k)) [(word pc,0x17d); (m,8 * val k)] /\
(x = z \/ nonoverlapping (x,8 * val r) (z,8 * val k)) /\
val p < 2 EXP 61 /\ val r < 2 EXP 61
==> ensures x86
(\s. bytes_loaded s (word pc) bignum_montredc_mc /\
read RIP s = word pc /\
read RSP s = stackpointer /\
read (memory :> bytes64 stackpointer) s = returnaddress /\
C_ARGUMENTS [k; z; r; x; m; p] s /\
bignum_from_memory (x,val r) s = a /\
bignum_from_memory (m,val k) s = n)
(\s. read RIP s = returnaddress /\
read RSP s = word_add stackpointer (word 8) /\
(ODD n /\
lowdigits a (val k + val p) <= 2 EXP (64 * val p) * n
==> bignum_from_memory (z,val k) s =
(inverse_mod n (2 EXP (64 * val p)) *
lowdigits a (val k + val p)) MOD n))
(MAYCHANGE [RIP; RSP; RAX; RDX; R10; R11] ,,
MAYCHANGE [memory :> bytes(z,8 * val k);
memory :> bytes(word_sub stackpointer (word 56),56)] ,,
MAYCHANGE SOME_FLAGS)`,
X86_PROMOTE_RETURN_STACK_TAC bignum_montredc_mc BIGNUM_MONTREDC_CORRECT
`[RBX; RBP; R12; R13; R14; R15]` 56);;
let windows_bignum_montredc_mc = define_from_elf
"windows_bignum_montredc_mc" "x86/generic/bignum_montredc.obj";;
let WINDOWS_BIGNUM_MONTREDC_SUBROUTINE_CORRECT = time prove
(`!k z r x m p a n pc stackpointer returnaddress.
nonoverlapping (word_sub stackpointer (word 72),80) (z,8 * val k) /\
ALL (nonoverlapping (word_sub stackpointer (word 72),72))
[(word pc,0x197); (x,8 * val r); (m,8 * val k)] /\
ALL (nonoverlapping (z,8 * val k)) [(word pc,0x197); (m,8 * val k)] /\
(x = z \/ nonoverlapping (x,8 * val r) (z,8 * val k)) /\
val p < 2 EXP 61 /\ val r < 2 EXP 61
==> ensures x86
(\s. bytes_loaded s (word pc) windows_bignum_montredc_mc /\
read RIP s = word pc /\
read RSP s = stackpointer /\
read (memory :> bytes64 stackpointer) s = returnaddress /\
WINDOWS_C_ARGUMENTS [k; z; r; x; m; p] s /\
bignum_from_memory (x,val r) s = a /\
bignum_from_memory (m,val k) s = n)
(\s. read RIP s = returnaddress /\
read RSP s = word_add stackpointer (word 8) /\
(ODD n /\
lowdigits a (val k + val p) <= 2 EXP (64 * val p) * n
==> bignum_from_memory (z,val k) s =
(inverse_mod n (2 EXP (64 * val p)) *
lowdigits a (val k + val p)) MOD n))
(MAYCHANGE [RIP; RSP; R9; R8; RCX; RAX; RDX; R10; R11] ,,
MAYCHANGE [memory :> bytes(z,8 * val k);
memory :> bytes(word_sub stackpointer (word 72),72)] ,,
MAYCHANGE SOME_FLAGS)`,
WINDOWS_X86_WRAP_STACK_TAC windows_bignum_montredc_mc bignum_montredc_mc
BIGNUM_MONTREDC_CORRECT `[RBX; RBP; R12; R13; R14; R15]` 56);;
|
f84cd895a19fbfb71111a4d67b7768ab7944f01e045ba558c7b861bef9c170ed | EasyCrypt/easycrypt | ecHiGoal.ml | (* -------------------------------------------------------------------- *)
open EcUtils
open EcLocation
open EcSymbols
open EcParsetree
open EcTypes
open EcFol
open EcEnv
open EcMatching
open EcBaseLogic
open EcProofTerm
open EcCoreGoal
open EcCoreGoal.FApi
open EcLowGoal
module Sid = EcIdent.Sid
module Mid = EcIdent.Mid
module Sp = EcPath.Sp
module ER = EcReduction
module PT = EcProofTerm
module TT = EcTyping
module TTC = EcProofTyping
module LG = EcCoreLib.CI_Logic
(* -------------------------------------------------------------------- *)
type ttenv = {
tt_provers : EcParsetree.pprover_infos -> EcProvers.prover_infos;
tt_smtmode : [`Admit | `Strict | `Standard | `Report];
tt_implicits : bool;
tt_oldip : bool;
tt_redlogic : bool;
tt_und_delta : bool;
}
type engine = ptactic_core -> FApi.backward
(* -------------------------------------------------------------------- *)
let t_simplify_lg ?target ?delta (ttenv, logic) (tc : tcenv1) =
let logic =
match logic with
| `Default -> if ttenv.tt_redlogic then `Full else `ProductCompat
| `Variant -> if ttenv.tt_redlogic then `ProductCompat else `Full
in t_simplify ?target ?delta ~logic:(Some logic) tc
(* -------------------------------------------------------------------- *)
type focus_t = EcParsetree.tfocus
let process_tfocus tc (focus : focus_t) : tfocus =
let count = FApi.tc_count tc in
let check1 i =
let error () = tc_error !$tc "invalid focus index: %d" i in
if i >= 0
then if not (0 < i && i <= count) then error () else i-1
else if -i > count then error () else count+i
in
let checkfs fs =
List.fold_left
(fun rg (i1, i2) ->
let i1 = odfl min_int (omap check1 i1) in
let i2 = odfl max_int (omap check1 i2) in
if i1 <= i2 then ISet.add_range i1 i2 rg else rg)
ISet.empty fs
in
let posfs = omap checkfs (fst focus) in
let negfs = omap checkfs (snd focus) in
fun i ->
odfl true (posfs |> omap (ISet.mem i))
&& odfl true (negfs |> omap (fun fc -> not (ISet.mem i fc)))
(* -------------------------------------------------------------------- *)
let process_assumption (tc : tcenv1) =
EcLowGoal.t_assumption `Conv tc
(* -------------------------------------------------------------------- *)
let process_reflexivity (tc : tcenv1) =
try EcLowGoal.t_reflex tc
with InvalidGoalShape ->
tc_error !!tc "cannot prove goal by reflexivity"
(* -------------------------------------------------------------------- *)
let process_change fp (tc : tcenv1) =
let fp = TTC.tc1_process_formula tc fp in
t_change fp tc
(* -------------------------------------------------------------------- *)
let process_simplify_info ri (tc : tcenv1) =
let env, hyps, _ = FApi.tc1_eflat tc in
let do1 (sop, sid) ps =
match ps.pl_desc with
| ([], s) when LDecl.has_name s hyps ->
let id = fst (LDecl.by_name s hyps) in
(sop, Sid.add id sid)
| qs ->
match EcEnv.Op.lookup_opt qs env with
| None -> tc_lookup_error !!tc ~loc:ps.pl_loc `Operator qs
| Some p -> (Sp.add (fst p) sop, sid)
in
let delta_p, delta_h =
ri.pdelta
|> omap (List.fold_left do1 (Sp.empty, Sid.empty))
|> omap (fun (x, y) -> (fun p -> if Sp.mem p x then `Force else `No), (Sid.mem^~ y))
|> odfl ((fun _ -> `Yes), predT)
in
{
EcReduction.beta = ri.pbeta;
EcReduction.delta_p = delta_p;
EcReduction.delta_h = delta_h;
EcReduction.zeta = ri.pzeta;
EcReduction.iota = ri.piota;
EcReduction.eta = ri.peta;
EcReduction.logic = if ri.plogic then Some `Full else None;
EcReduction.modpath = ri.pmodpath;
EcReduction.user = ri.puser;
EcReduction.cost = ri.pcost;
}
(*-------------------------------------------------------------------- *)
let process_simplify ri (tc : tcenv1) =
t_simplify_with_info (process_simplify_info ri tc) tc
(* -------------------------------------------------------------------- *)
let process_cbv ri (tc : tcenv1) =
t_cbv_with_info (process_simplify_info ri tc) tc
(* -------------------------------------------------------------------- *)
let process_smt ?loc (ttenv : ttenv) pi (tc : tcenv1) =
let pi = ttenv.tt_provers pi in
match ttenv.tt_smtmode with
| `Admit ->
t_admit tc
| (`Standard | `Strict) as mode ->
t_seq (t_simplify ~delta:false) (t_smt ~mode pi) tc
| `Report ->
t_seq (t_simplify ~delta:false) (t_smt ~mode:(`Report loc) pi) tc
(* -------------------------------------------------------------------- *)
let process_clear symbols tc =
let hyps = FApi.tc1_hyps tc in
let toid s =
if not (LDecl.has_name (unloc s) hyps) then
tc_lookup_error !!tc ~loc:s.pl_loc `Local ([], unloc s);
fst (LDecl.by_name (unloc s) hyps)
in
try t_clears (List.map toid symbols) tc
with (ClearError _) as err -> tc_error_exn !!tc err
(* -------------------------------------------------------------------- *)
let process_algebra mode kind eqs (tc : tcenv1) =
let (env, hyps, concl) = FApi.tc1_eflat tc in
if not (EcAlgTactic.is_module_loaded env) then
tacuerror "ring/field cannot be used when AlgTactic is not loaded";
let (ty, f1, f2) =
match sform_of_form concl with
| SFeq (f1, f2) -> (f1.f_ty, f1, f2)
| _ -> tacuerror "conclusion must be an equation"
in
let eqs =
let eq1 { pl_desc = x } =
match LDecl.hyp_exists x hyps with
| false -> tacuerror "cannot find equation referenced by `%s'" x
| true -> begin
match sform_of_form (snd (LDecl.hyp_by_name x hyps)) with
| SFeq (f1, f2) ->
if not (EcReduction.EqTest.for_type env ty f1.f_ty) then
tacuerror "assumption `%s' is not an equation over the right type" x;
(f1, f2)
| _ -> tacuerror "assumption `%s' is not an equation" x
end
in List.map eq1 eqs
in
let tparams = (LDecl.tohyps hyps).h_tvar in
let tactic =
match
match mode, kind with
| `Simpl, `Ring -> `Ring EcAlgTactic.t_ring_simplify
| `Simpl, `Field -> `Field EcAlgTactic.t_field_simplify
| `Solve, `Ring -> `Ring EcAlgTactic.t_ring
| `Solve, `Field -> `Field EcAlgTactic.t_field
with
| `Ring t ->
let r =
match TT.get_ring (tparams, ty) env with
| None -> tacuerror "cannot find a ring structure"
| Some r -> r
in t r eqs (f1, f2)
| `Field t ->
let r =
match TT.get_field (tparams, ty) env with
| None -> tacuerror "cannot find a field structure"
| Some r -> r
in t r eqs (f1, f2)
in
tactic tc
(* -------------------------------------------------------------------- *)
let t_apply_prept pt tc =
EcLowGoal.Apply.t_apply_bwd_r (pt_of_prept tc pt) tc
(* -------------------------------------------------------------------- *)
module LowRewrite = struct
type error =
| LRW_NotAnEquation
| LRW_NothingToRewrite
| LRW_InvalidOccurence
| LRW_CannotInfer
| LRW_IdRewriting
| LRW_RPatternNoMatch
| LRW_RPatternNoRuleMatch
exception RewriteError of error
let rec find_rewrite_patterns ~inpred (dir : rwside) pt =
let hyps = pt.PT.ptev_env.PT.pte_hy in
let env = LDecl.toenv hyps in
let pt = { pt with ptev_ax = snd (PT.concretize pt) } in
let ptc = { pt with ptev_env = EcProofTerm.copy pt.ptev_env } in
let ax = pt.ptev_ax in
let base ax =
match EcFol.sform_of_form ax with
| EcFol.SFeq (f1, f2) -> [(pt, `Eq, (f1, f2))]
| EcFol.SFiff (f1, f2) -> [(pt, `Eq, (f1, f2))]
| EcFol.SFnot f ->
let pt' = pt_of_global_r pt.ptev_env LG.p_negeqF [] in
let pt' = apply_pterm_to_arg_r pt' (PVAFormula f) in
let pt' = apply_pterm_to_arg_r pt' (PVASub pt) in
[(pt', `Eq, (f, f_false))]
| _ -> []
and split ax =
match EcFol.sform_of_form ax with
| EcFol.SFand (`Sym, (f1, f2)) ->
let pt1 =
let pt'= pt_of_global_r pt.ptev_env LG.p_and_proj_l [] in
let pt'= apply_pterm_to_arg_r pt' (PVAFormula f1) in
let pt'= apply_pterm_to_arg_r pt' (PVAFormula f2) in
apply_pterm_to_arg_r pt' (PVASub pt) in
let pt2 =
let pt'= pt_of_global_r pt.ptev_env LG.p_and_proj_r [] in
let pt'= apply_pterm_to_arg_r pt' (PVAFormula f1) in
let pt'= apply_pterm_to_arg_r pt' (PVAFormula f2) in
apply_pterm_to_arg_r pt' (PVASub pt) in
(find_rewrite_patterns ~inpred dir pt2)
@ (find_rewrite_patterns ~inpred dir pt1)
| _ -> []
in
match base ax with
| _::_ as rws -> rws
| [] -> begin
let ptb = Lazy.from_fun (fun () ->
let pt1 = split ax
and pt2 =
if dir = `LtoR then
if ER.EqTest.for_type env ax.f_ty tbool
then Some (ptc, `Bool, (ax, f_true))
else None
else None
and pt3 = omap base
(EcReduction.h_red_opt EcReduction.full_red hyps ax)
in pt1 @ (otolist pt2) @ (odfl [] pt3)) in
let rec doit reduce =
match TTC.destruct_product ~reduce hyps ax with
| None -> begin
if reduce then Lazy.force ptb else
let pts = doit true in
if inpred then pts else (Lazy.force ptb) @ pts
end
| Some _ ->
let pt = EcProofTerm.apply_pterm_to_hole pt in
find_rewrite_patterns ~inpred:(inpred || reduce) dir pt
in doit false
end
let find_rewrite_patterns = find_rewrite_patterns ~inpred:false
type rwinfos = rwside * EcFol.form option * EcMatching.occ option
let t_rewrite_r ?(mode = `Full) ?target ((s, prw, o) : rwinfos) pt tc =
let hyps, tgfp = FApi.tc1_flat ?target tc in
let modes =
match mode with
| `Full -> [{ k_keyed = true; k_conv = false };
{ k_keyed = true; k_conv = true };]
| `Light -> [{ k_keyed = true; k_conv = false }] in
let for1 (pt, mode, (f1, f2)) =
let fp, tp = match s with `LtoR -> f1, f2 | `RtoL -> f2, f1 in
let subf, occmode =
match prw with
| None -> begin
try
PT.pf_find_occurence_lazy pt.PT.ptev_env ~modes ~ptn:fp tgfp
with
| PT.FindOccFailure `MatchFailure ->
raise (RewriteError LRW_NothingToRewrite)
| PT.FindOccFailure `IncompleteMatch ->
raise (RewriteError LRW_CannotInfer)
end
| Some prw -> begin
let prw, _ =
try
PT.pf_find_occurence_lazy
pt.PT.ptev_env ~full:false ~modes ~ptn:prw tgfp;
with PT.FindOccFailure `MatchFailure ->
raise (RewriteError LRW_RPatternNoMatch) in
try
PT.pf_find_occurence_lazy
pt.PT.ptev_env ~rooted:true ~modes ~ptn:fp prw
with
| PT.FindOccFailure `MatchFailure ->
raise (RewriteError LRW_RPatternNoRuleMatch)
| PT.FindOccFailure `IncompleteMatch ->
raise (RewriteError LRW_CannotInfer)
end in
if not occmode.k_keyed then begin
let tp = PT.concretize_form pt.PT.ptev_env tp in
if EcReduction.is_conv hyps fp tp then
raise (RewriteError LRW_IdRewriting);
end;
let pt = fst (PT.concretize pt) in
let cpos =
try FPosition.select_form
~xconv:`AlphaEq ~keyed:occmode.k_keyed
hyps o subf tgfp
with InvalidOccurence -> raise (RewriteError (LRW_InvalidOccurence))
in
EcLowGoal.t_rewrite
~keyed:occmode.k_keyed ?target ~mode pt (s, Some cpos) tc in
let rec do_first = function
| [] -> raise (RewriteError LRW_NothingToRewrite)
| (pt, mode, (f1, f2)) :: pts ->
try for1 (pt, mode, (f1, f2))
with RewriteError (LRW_NothingToRewrite | LRW_IdRewriting) ->
do_first pts
in
let pts = find_rewrite_patterns s pt in
if List.is_empty pts then
raise (RewriteError LRW_NotAnEquation);
do_first (List.rev pts)
let t_rewrite ?target (s, p, o) pt (tc : tcenv1) =
let hyps = FApi.tc1_hyps ?target tc in
let pt, ax = EcLowGoal.LowApply.check `Elim pt (`Hyps (hyps, !!tc)) in
let ptenv = ptenv_of_penv hyps !!tc in
t_rewrite_r ?target (s, p, o)
{ ptev_env = ptenv; ptev_pt = pt; ptev_ax = ax; }
tc
let t_autorewrite lemmas (tc : tcenv1) =
let pts =
let do1 lemma =
PT.pt_of_uglobal !!tc (FApi.tc1_hyps tc) lemma in
List.map do1 lemmas
in
let try1 pt tc =
let pt = { pt with PT.ptev_env = PT.copy pt.ptev_env } in
try t_rewrite_r (`LtoR, None, None) pt tc
with RewriteError _ -> raise InvalidGoalShape
in t_do_r ~focus:0 `Maybe None (t_ors (List.map try1 pts)) !@tc
end
let t_rewrite_prept info pt tc =
LowRewrite.t_rewrite_r info (pt_of_prept tc pt) tc
(* -------------------------------------------------------------------- *)
let process_solve ?bases ?depth (tc : tcenv1) =
match FApi.t_try_base (EcLowGoal.t_solve ~canfail:false ?bases ?depth) tc with
| `Failure _ ->
tc_error (FApi.tc1_penv tc) "[solve]: cannot close goal"
| `Success tc ->
tc
(* -------------------------------------------------------------------- *)
let process_trivial (tc : tcenv1) =
EcPhlAuto.t_pl_trivial ~conv:`Conv tc
(* -------------------------------------------------------------------- *)
let process_crushmode d =
d.cm_simplify, if d.cm_solve then Some process_trivial else None
(* -------------------------------------------------------------------- *)
let process_done tc =
let tc = process_trivial tc in
if not (FApi.tc_done tc) then
tc_error (FApi.tc_penv tc) "[by]: cannot close goals";
tc
(* -------------------------------------------------------------------- *)
let process_apply_bwd ~implicits mode (ff : ppterm) (tc : tcenv1) =
let pt = PT.tc1_process_full_pterm ~implicits tc ff in
try
match mode with
| `Alpha ->
begin try
PT.pf_form_match
pt.ptev_env
~mode:fmrigid
~ptn:pt.ptev_ax
(FApi.tc1_goal tc)
with EcMatching.MatchFailure ->
tc_error !!tc "@[<v>proof-term is not alpha-convertible to conclusion@ @[%a@]@]"
(EcPrinting.pp_form (EcPrinting.PPEnv.ofenv (EcEnv.LDecl.toenv pt.ptev_env.pte_hy))) pt.ptev_ax
end;
EcLowGoal.t_apply (fst (PT.concretize pt)) tc
| `Apply ->
EcLowGoal.Apply.t_apply_bwd_r pt tc
| `Exact ->
let aout = EcLowGoal.Apply.t_apply_bwd_r pt tc in
let aout = FApi.t_onall process_trivial aout in
if not (FApi.tc_done aout) then
tc_error !!tc "cannot close goal";
aout
with (EcLowGoal.Apply.NoInstance _) as err ->
tc_error_exn !!tc err
(* -------------------------------------------------------------------- *)
let process_exacttype qs (tc : tcenv1) =
let env, hyps, _ = FApi.tc1_eflat tc in
let p =
try EcEnv.Ax.lookup_path (EcLocation.unloc qs) env
with LookupFailure cause ->
tc_error !!tc "%a" EcEnv.pp_lookup_failure cause
in
let tys =
List.map (fun (a,_) -> EcTypes.tvar a)
(EcEnv.LDecl.tohyps hyps).h_tvar in
EcLowGoal.t_apply_s p tys ~args:[] ~sk:0 tc
(* -------------------------------------------------------------------- *)
let process_apply_fwd ~implicits (pe, hyp) tc =
let module E = struct exception NoInstance end in
let hyps = FApi.tc1_hyps tc in
if not (LDecl.hyp_exists (unloc hyp) hyps) then
tc_error !!tc "unknown hypothesis: %s" (unloc hyp);
let hyp, fp = LDecl.hyp_by_name (unloc hyp) hyps in
let pte = PT.tc1_process_full_pterm ~implicits tc pe in
try
let rec instantiate pte =
match TTC.destruct_product hyps pte.PT.ptev_ax with
| None -> raise E.NoInstance
| Some (`Forall _) ->
instantiate (PT.apply_pterm_to_hole pte)
| Some (`Imp (f1, f2)) ->
try
PT.pf_form_match ~mode:fmdelta pte.PT.ptev_env ~ptn:f1 fp;
(pte, f2)
with MatchFailure -> raise E.NoInstance
in
let (pte, cutf) = instantiate pte in
if not (PT.can_concretize pte.ptev_env) then
tc_error !!tc "cannot infer all variables";
let pt = fst (PT.concretize pte) in
let pt = { pt with pt_args = pt.pt_args @ [palocal hyp]; } in
let cutf = PT.concretize_form pte.PT.ptev_env cutf in
FApi.t_last
(FApi.t_seq (t_clear hyp) (t_intros_i [hyp]))
(t_cutdef pt cutf tc)
with E.NoInstance ->
tc_error_lazy !!tc
(fun fmt ->
let ppe = EcPrinting.PPEnv.ofenv (FApi.tc1_env tc) in
Format.fprintf fmt
"cannot apply (in %a) the given proof-term for:\n\n%!"
(EcPrinting.pp_local ppe) hyp;
Format.fprintf fmt
" @[%a@]" (EcPrinting.pp_form ppe) pte.PT.ptev_ax)
(* -------------------------------------------------------------------- *)
let process_apply_top tc =
let hyps, concl = FApi.tc1_flat tc in
match TTC.destruct_product hyps concl with
| Some (`Imp _) -> begin
let h = LDecl.fresh_id hyps "h" in
try
EcLowGoal.t_intros_i_seq ~clear:true [h]
(EcLowGoal.Apply.t_apply_bwd { pt_head = PTLocal h; pt_args = []} )
tc
with (EcLowGoal.Apply.NoInstance _) as err ->
tc_error_exn !!tc err
end
| _ -> tc_error !!tc "no top assumption"
(* -------------------------------------------------------------------- *)
let process_rewrite1_core ?mode ?(close = true) ?target (s, p, o) pt tc =
let o = norm_rwocc o in
try
let tc = LowRewrite.t_rewrite_r ?mode ?target (s, p, o) pt tc in
let cl = fun tc ->
if EcFol.f_equal f_true (FApi.tc1_goal tc) then
t_true tc
else t_id tc
in if close then FApi.t_last cl tc else tc
with
| LowRewrite.RewriteError e ->
match e with
| LowRewrite.LRW_NotAnEquation ->
tc_error !!tc "not an equation to rewrite"
| LowRewrite.LRW_NothingToRewrite ->
tc_error !!tc "nothing to rewrite"
| LowRewrite.LRW_InvalidOccurence ->
tc_error !!tc "invalid occurence selector"
| LowRewrite.LRW_CannotInfer ->
tc_error !!tc "cannot infer all placeholders"
| LowRewrite.LRW_IdRewriting ->
tc_error !!tc "refuse to perform an identity rewriting"
| LowRewrite.LRW_RPatternNoMatch ->
tc_error !!tc "r-pattern does not match the goal"
| LowRewrite.LRW_RPatternNoRuleMatch ->
tc_error !!tc "r-pattern does not match the rewriting rule"
(* -------------------------------------------------------------------- *)
let process_delta ~und_delta ?target (s, o, p) tc =
let env, hyps, concl = FApi.tc1_eflat tc in
let o = norm_rwocc o in
let idtg, target =
match target with
| None -> (None, concl)
| Some h -> fst_map some (LDecl.hyp_by_name (unloc h) hyps)
in
match unloc p with
| PFident ({ pl_desc = ([], x) }, None)
when s = `LtoR && EcUtils.is_none o ->
let check_op = fun p -> if sym_equal (EcPath.basename p) x then `Force else `No in
let check_id = fun y -> sym_equal (EcIdent.name y) x in
let ri =
{ EcReduction.no_red with
EcReduction.delta_p = check_op;
EcReduction.delta_h = check_id; } in
let redform = EcReduction.simplify ri hyps target in
if und_delta then begin
if EcFol.f_equal target redform then
EcEnv.notify env `Warning "unused unfold: /%s" x
end;
t_change ~ri ?target:idtg redform tc
| _ ->
(* Continue with matching based unfolding *)
let (ptenv, p) =
let (ps, ue), p = TTC.tc1_process_pattern tc p in
let ev = MEV.of_idents (Mid.keys ps) `Form in
(ptenv !!tc hyps (ue, ev), p)
in
let (tvi, tparams, body, args, dp) =
match sform_of_form p with
| SFop (p, args) -> begin
let op = EcEnv.Op.by_path (fst p) env in
match op.EcDecl.op_kind with
| EcDecl.OB_oper (Some (EcDecl.OP_Plain (e, _))) ->
(snd p, op.EcDecl.op_tparams, form_of_expr EcFol.mhr e, args, Some (fst p))
| EcDecl.OB_pred (Some (EcDecl.PR_Plain f)) ->
(snd p, op.EcDecl.op_tparams, f, args, Some (fst p))
| _ ->
tc_error !!tc "the operator cannot be unfolded"
end
| SFlocal x when LDecl.can_unfold x hyps ->
([], [], LDecl.unfold x hyps, [], None)
| SFother { f_node = Fapp ({ f_node = Flocal x }, args) }
when LDecl.can_unfold x hyps ->
([], [], LDecl.unfold x hyps, args, None)
| _ -> tc_error !!tc "not headed by an operator/predicate"
in
let ri = { EcReduction.full_red with
delta_p = (fun p -> if Some p = dp then `Force else `Yes)} in
let na = List.length args in
match s with
| `LtoR -> begin
let matches =
try ignore (PT.pf_find_occurence ptenv ~ptn:p target); true
with PT.FindOccFailure _ -> false
in
if matches then begin
let p = concretize_form ptenv p in
let cpos =
let test = fun _ fp ->
let fp =
match fp.f_node with
| Fapp (h, hargs) when List.length hargs > na ->
let (a1, a2) = List.takedrop na hargs in
f_app h a1 (toarrow (List.map f_ty a2) fp.f_ty)
| _ -> fp
in
if EcReduction.is_alpha_eq hyps p fp
then `Accept (-1)
else `Continue
in
try FPosition.select ?o test target
with InvalidOccurence ->
tc_error !!tc "invalid occurences selector"
in
let target =
FPosition.map cpos
(fun topfp ->
let (fp, args) = EcFol.destr_app topfp in
match sform_of_form fp with
| SFop ((_, tvi), []) -> begin
FIXME : TC HOOK
let subst = EcTypes.Tvar.init (List.map fst tparams) tvi in
let body = EcFol.Fsubst.subst_tvar subst body in
let body = f_app body args topfp.f_ty in
try EcReduction.h_red EcReduction.beta_red hyps body
with EcEnv.NotReducible -> body
end
| SFlocal _ -> begin
assert (tparams = []);
let body = f_app body args topfp.f_ty in
try EcReduction.h_red EcReduction.beta_red hyps body
with EcEnv.NotReducible -> body
end
| _ -> assert false)
target
in
t_change ~ri ?target:idtg target tc
end else t_id tc
end
| `RtoL ->
let fp =
FIXME : TC HOOK
let subst = EcTypes.Tvar.init (List.map fst tparams) tvi in
let body = EcFol.Fsubst.subst_tvar subst body in
let fp = f_app body args p.f_ty in
try EcReduction.h_red EcReduction.beta_red hyps fp
with EcEnv.NotReducible -> fp
in
let matches =
try ignore (PT.pf_find_occurence ptenv ~ptn:fp target); true
with PT.FindOccFailure _ -> false
in
if matches then begin
let p = concretize_form ptenv p in
let fp = concretize_form ptenv fp in
let cpos =
try FPosition.select_form hyps o fp target
with InvalidOccurence ->
tc_error !!tc "invalid occurences selector"
in
let target = FPosition.map cpos (fun _ -> p) target in
t_change ~ri ?target:idtg target tc
end else t_id tc
(* -------------------------------------------------------------------- *)
let process_rewrite1_r ttenv ?target ri tc =
let implicits = ttenv.tt_implicits in
let und_delta = ttenv.tt_und_delta in
match unloc ri with
| RWDone simpl ->
let tt =
match simpl with
| Some logic ->
let hyps = FApi.tc1_hyps tc in
let target = target |> omap (fst |- LDecl.hyp_by_name^~ hyps |- unloc) in
t_simplify_lg ?target ~delta:false (ttenv, logic)
| None -> t_id
in FApi.t_seq tt process_trivial tc
| RWSimpl logic ->
let hyps = FApi.tc1_hyps tc in
let target = target |> omap (fst |- LDecl.hyp_by_name^~ hyps |- unloc) in
t_simplify_lg ?target ~delta:false (ttenv, logic) tc
| RWDelta ((s, r, o, px), p) -> begin
if Option.is_some px then
tc_error !!tc "cannot use pattern selection in delta-rewrite rules";
let do1 tc = process_delta ~und_delta ?target (s, o, p) tc in
match r with
| None -> do1 tc
| Some (b, n) -> t_do b n do1 tc
end
| RWRw (((s : rwside), r, o, p), pts) -> begin
let do1 (mode : [`Full | `Light]) ((subs : rwside), pt) tc =
let hyps = FApi.tc1_hyps tc in
let target = target |> omap (fst |- LDecl.hyp_by_name^~ hyps |- unloc) in
let hyps = FApi.tc1_hyps ?target tc in
let ptenv, prw =
match p with
| None ->
PT.ptenv_of_penv hyps !!tc, None
| Some p ->
let (ps, ue), p = TTC.tc1_process_pattern tc p in
let ev = MEV.of_idents (Mid.keys ps) `Form in
(PT.ptenv !!tc hyps (ue, ev), Some p) in
let theside =
match s, subs with
| `LtoR, _ -> (subs :> rwside)
| _ , `LtoR -> (s :> rwside)
| `RtoL, `RtoL -> (`LtoR :> rwside) in
let is_baserw p =
EcEnv.BaseRw.is_base p.pl_desc (FApi.tc1_env tc) in
match pt with
| { fp_head = FPNamed (p, None); fp_args = []; }
when pt.fp_mode = `Implicit && is_baserw p
->
let env = FApi.tc1_env tc in
let ls = snd (EcEnv.BaseRw.lookup p.pl_desc env) in
let ls = EcPath.Sp.elements ls in
let do1 lemma tc =
let pt = PT.pt_of_uglobal_r (PT.copy ptenv) lemma in
process_rewrite1_core ~mode ?target (theside, prw, o) pt tc
in t_ors (List.map do1 ls) tc
| { fp_head = FPNamed (p, None); fp_args = []; }
when pt.fp_mode = `Implicit
->
let env = FApi.tc1_env tc in
let ptenv0 = PT.copy ptenv in
let pt = PT.process_full_pterm ~implicits ptenv pt
in
if is_ptglobal pt.PT.ptev_pt.pt_head
&& List.is_empty pt.PT.ptev_pt.pt_args
then begin
let ls = EcEnv.Ax.all ~name:(unloc p) env in
let do1 (lemma, _) tc =
let pt = PT.pt_of_uglobal_r (PT.copy ptenv0) lemma in
process_rewrite1_core ~mode ?target (theside, prw, o) pt tc in
t_ors (List.map do1 ls) tc
end else
process_rewrite1_core ~mode ?target (theside, prw, o) pt tc
| _ ->
let pt = PT.process_full_pterm ~implicits ptenv pt in
process_rewrite1_core ~mode ?target (theside, prw, o) pt tc
in
let doall mode tc = t_ors (List.map (do1 mode) pts) tc in
match r with
| None ->
doall `Full tc
| Some (`Maybe, None) ->
t_seq
(t_do `Maybe (Some 1) (doall `Full))
(t_do `Maybe None (doall `Light))
tc
| Some (b, n) ->
t_do b n (doall `Full) tc
end
| RWPr (x, f) -> begin
if EcUtils.is_some target then
tc_error !!tc "cannot rewrite Pr[] in local assumptions";
EcPhlPrRw.t_pr_rewrite (unloc x, f) tc
end
| RWSmt (false, info) ->
process_smt ~loc:ri.pl_loc ttenv info tc
| RWSmt (true, info) ->
t_or process_done (process_smt ~loc:ri.pl_loc ttenv info) tc
| RWApp fp -> begin
let implicits = ttenv.tt_implicits in
match target with
| None -> process_apply_bwd ~implicits `Apply fp tc
| Some target -> process_apply_fwd ~implicits (fp, target) tc
end
| RWTactic `Ring ->
process_algebra `Solve `Ring [] tc
| RWTactic `Field ->
process_algebra `Solve `Field [] tc
(* -------------------------------------------------------------------- *)
let process_rewrite1 ttenv ?target ri tc =
EcCoreGoal.reloc (loc ri) (process_rewrite1_r ttenv ?target ri) tc
(* -------------------------------------------------------------------- *)
let process_rewrite ttenv ?target ri tc =
let do1 tc gi (fc, ri) =
let ngoals = FApi.tc_count tc in
let dorw = fun i tc ->
if gi = 0 || (i+1) = ngoals
then process_rewrite1 ttenv ?target ri tc
else process_rewrite1 ttenv ri tc
in
match fc |> omap ((process_tfocus tc) |- unloc) with
| None -> FApi.t_onalli dorw tc
| Some fc -> FApi.t_onselecti fc dorw tc
in
List.fold_lefti do1 (tcenv_of_tcenv1 tc) ri
(* -------------------------------------------------------------------- *)
let process_elimT qs tc =
let noelim () = tc_error !!tc "cannot recognize elimination principle" in
let (hyps, concl) = FApi.tc1_flat tc in
let (pf, pfty, _concl) =
match TTC.destruct_product hyps concl with
| Some (`Forall (x, GTty xty, concl)) -> (x, xty, concl)
| _ -> noelim ()
in
let pf = LDecl.fresh_id hyps (EcIdent.name pf) in
let tc = t_intros_i_1 [pf] tc in
let (hyps, concl) = FApi.tc1_flat tc in
let pt = PT.tc1_process_full_pterm tc qs in
let (_xp, xpty, ax) =
match TTC.destruct_product hyps pt.ptev_ax with
| Some (`Forall (xp, GTty xpty, f)) -> (xp, xpty, f)
| _ -> noelim ()
in
begin
let ue = pt.ptev_env.pte_ue in
try EcUnify.unify (LDecl.toenv hyps) ue (tfun pfty tbool) xpty
with EcUnify.UnificationFailure _ -> noelim ()
end;
if not (PT.can_concretize pt.ptev_env) then noelim ();
let ax = PT.concretize_form pt.ptev_env ax in
let rec skip ax =
match TTC.destruct_product hyps ax with
| Some (`Imp (_f1, f2)) -> skip f2
| Some (`Forall (x, GTty xty, f)) -> ((x, xty), f)
| _ -> noelim ()
in
let ((x, _xty), ax) = skip ax in
let fpf = f_local pf pfty in
let ptnpos = FPosition.select_form hyps None fpf concl in
let (_xabs, body) = FPosition.topattern ~x:x ptnpos concl in
let rec skipmatch ax body sk =
match TTC.destruct_product hyps ax, TTC.destruct_product hyps body with
| Some (`Imp (i1, f1)), Some (`Imp (i2, f2)) ->
if EcReduction.is_alpha_eq hyps i1 i2
then skipmatch f1 f2 (sk+1)
else sk
| _ -> sk
in
let sk = skipmatch ax body 0 in
t_seqs
[t_elimT_form (fst (PT.concretize pt)) ~sk fpf;
t_or
(t_clear pf)
(t_seq (t_generalize_hyp pf) (t_clear pf));
t_simplify_with_info EcReduction.beta_red]
tc
(* -------------------------------------------------------------------- *)
let process_view1 pe tc =
let module E = struct
exception NoInstance
exception NoTopAssumption
end in
let destruct hyps fp =
let doit fp =
match EcFol.sform_of_form fp with
| SFquant (Lforall, (x, t), lazy f) -> `Forall (x, t, f)
| SFimp (f1, f2) -> `Imp (f1, f2)
| SFiff (f1, f2) -> `Iff (f1, f2)
| _ -> raise EcProofTyping.NoMatch
in
EcProofTyping.lazy_destruct hyps doit fp
in
let rec instantiate fp ids pte =
let hyps = pte.PT.ptev_env.PT.pte_hy in
match destruct hyps pte.PT.ptev_ax with
| None -> raise E.NoInstance
| Some (`Forall (x, xty, _)) ->
instantiate fp ((x, xty) :: ids) (PT.apply_pterm_to_hole pte)
| Some (`Imp (f1, f2)) -> begin
try
PT.pf_form_match ~mode:fmdelta pte.PT.ptev_env ~ptn:f1 fp;
(pte, ids, f2, `None)
with MatchFailure -> raise E.NoInstance
end
| Some (`Iff (f1, f2)) -> begin
try
PT.pf_form_match ~mode:fmdelta pte.PT.ptev_env ~ptn:f1 fp;
(pte, ids, f2, `IffLR (f1, f2))
with MatchFailure -> try
PT.pf_form_match ~mode:fmdelta pte.PT.ptev_env ~ptn:f2 fp;
(pte, ids, f1, `IffRL (f1, f2))
with MatchFailure ->
raise E.NoInstance
end
in
try
match TTC.destruct_product (tc1_hyps tc) (FApi.tc1_goal tc) with
| None -> raise E.NoTopAssumption
| Some (`Forall _) ->
process_elimT pe tc
| Some (`Imp (f1, _)) when pe.fp_head = FPCut None ->
let hyps = FApi.tc1_hyps tc in
let hid = LDecl.fresh_id hyps "h" in
let hqs = mk_loc _dummy ([], EcIdent.name hid) in
let pe = { pe with fp_head = FPNamed (hqs, None) } in
t_intros_i_seq ~clear:true [hid]
(fun tc ->
let pe = PT.tc1_process_full_pterm tc pe in
let regen =
if PT.can_concretize pe.PT.ptev_env then [] else
snd (List.fold_left_map (fun f1 arg ->
let pre, f1 =
match oget (TTC.destruct_product (tc1_hyps tc) f1) with
| `Imp (_, f1) -> (None, f1)
| `Forall (x, xty, f1) ->
let aout =
match xty with GTty ty -> Some (x, ty) | _ -> None
in (aout, f1)
in
let module E = struct exception Bailout end in
try
let v =
match arg with
| PAFormula { f_node = Flocal x } ->
let meta =
let env = !(pe.PT.ptev_env.pte_ev) in
MEV.mem x `Form env && not (MEV.isset x `Form env) in
if not meta then raise E.Bailout;
let y, yty =
let CPTEnv subst = PT.concretize_env pe.PT.ptev_env in
snd_map subst.fs_ty (oget pre) in
let fy = EcIdent.fresh y in
pe.PT.ptev_env.pte_ev := MEV.set
x (`Form (f_local fy yty)) !(pe.PT.ptev_env.pte_ev);
(fy, yty)
| _ ->
raise E.Bailout
in (f1, Some v)
with E.Bailout -> (f1, None)
) f1 pe.PT.ptev_pt.pt_args)
in
let regen = List.pmap (fun x -> x) regen in
let bds = List.map (fun (x, ty) -> (x, GTty ty)) regen in
if not (PT.can_concretize pe.PT.ptev_env) then
tc_error !!tc "cannot infer all placeholders";
let pt, ax = snd_map (f_forall bds) (PT.concretize pe) in
t_first (fun subtc ->
let regen = List.fst regen in
let ttcut tc =
t_onall
(EcLowGoal.t_generalize_hyps ~clear:`Yes regen)
(EcLowGoal.t_apply pt tc) in
t_intros_i_seq regen ttcut subtc
) (t_cut ax tc)
) tc
| Some (`Imp (f1, _)) ->
let top = LDecl.fresh_id (tc1_hyps tc) "h" in
let tc = t_intros_i_1 [top] tc in
let hyps = tc1_hyps tc in
let pte = PT.tc1_process_full_pterm tc pe in
let inargs = List.length pte.PT.ptev_pt.pt_args in
let (pte, ids, cutf, view) = instantiate f1 [] pte in
let evm = !(pte.PT.ptev_env.PT.pte_ev) in
let args = List.drop inargs pte.PT.ptev_pt.pt_args in
let args = List.combine (List.rev ids) args in
let ids =
let for1 ((_, ty) as idty, arg) =
match ty, arg with
| GTty _, PAFormula { f_node = Flocal x } when MEV.mem x `Form evm ->
if MEV.isset x `Form evm then None else Some (x, idty)
| GTmem _, PAMemory x when MEV.mem x `Mem evm ->
if MEV.isset x `Mem evm then None else Some (x, idty)
| _, _ -> assert false
in List.pmap for1 args
in
let cutf =
let ptenv = PT.copy pte.PT.ptev_env in
let for1 evm (x, idty) =
match idty with
| id, GTty ty -> evm := MEV.set x (`Form (f_local id ty)) !evm
| id, GTmem _ -> evm := MEV.set x (`Mem id) !evm
| _ , GTmodty _ -> assert false
in
List.iter (for1 ptenv.PT.pte_ev) ids;
if not (PT.can_concretize ptenv) then
tc_error !!tc "cannot infer all type variables";
PT.concretize_e_form
(PT.concretize_env ptenv)
(f_forall (List.map snd ids) cutf)
in
let discharge tc =
let intros = List.map (EcIdent.name |- fst |- snd) ids in
let intros = LDecl.fresh_ids hyps intros in
let for1 evm (x, idty) id =
match idty with
| _, GTty ty -> evm := MEV.set x (`Form (f_local id ty)) !evm
| _, GTmem _ -> evm := MEV.set x (`Mem id) !evm
| _, GTmodty _ -> assert false
in
let tc = EcLowGoal.t_intros_i_1 intros tc in
List.iter2 (for1 pte.PT.ptev_env.PT.pte_ev) ids intros;
let pte =
match view with
| `None -> pte
| `IffLR (f1, f2) ->
let vpte = PT.pt_of_global_r pte.PT.ptev_env LG.p_iff_lr [] in
let vpte = PT.apply_pterm_to_arg_r vpte (PVAFormula f1) in
let vpte = PT.apply_pterm_to_arg_r vpte (PVAFormula f2) in
let vpte = PT.apply_pterm_to_arg_r vpte (PVASub pte) in
vpte
| `IffRL (f1, f2) ->
let vpte = PT.pt_of_global_r pte.PT.ptev_env LG.p_iff_rl [] in
let vpte = PT.apply_pterm_to_arg_r vpte (PVAFormula f1) in
let vpte = PT.apply_pterm_to_arg_r vpte (PVAFormula f2) in
let vpte = PT.apply_pterm_to_arg_r vpte (PVASub pte) in
vpte
in
let pt = fst (PT.concretize (PT.apply_pterm_to_hole pte)) in
FApi.t_seq
(EcLowGoal.t_apply pt)
(EcLowGoal.t_apply_hyp top)
tc
in
FApi.t_internal
(FApi.t_seqsub (EcLowGoal.t_cut cutf)
[EcLowGoal.t_close ~who:"view" discharge;
EcLowGoal.t_clear top])
tc
with
| E.NoInstance ->
tc_error !!tc "cannot apply view"
| E.NoTopAssumption ->
tc_error !!tc "no top assumption"
(* -------------------------------------------------------------------- *)
let process_view pes tc =
let views = List.map (t_last |- process_view1) pes in
List.fold_left (fun tc tt -> tt tc) (FApi.tcenv_of_tcenv1 tc) views
(* -------------------------------------------------------------------- *)
module IntroState : sig
type state
type action = [ `Revert | `Dup | `Clear ]
val create : unit -> state
val push : ?name:symbol -> action -> EcIdent.t -> state -> unit
val listing : state -> ([`Gen of genclear | `Clear] * EcIdent.t) list
val naming : state -> (EcIdent.t -> symbol option)
end = struct
type state = {
mutable torev : ([`Gen of genclear | `Clear] * EcIdent.t) list;
mutable naming : symbol option Mid.t;
}
and action = [ `Revert | `Dup | `Clear ]
let create () =
{ torev = []; naming = Mid.empty; }
let push ?name action id st =
let map =
Mid.change (function
| None -> Some name
| Some _ -> assert false)
id st.naming
and action =
match action with
| `Revert -> `Gen `TryClear
| `Dup -> `Gen `NoClear
| `Clear -> `Clear
in
st.torev <- (action, id) :: st.torev;
st.naming <- map
let listing (st : state) =
List.rev st.torev
let naming (st : state) (x : EcIdent.t) =
Mid.find_opt x st.naming |> odfl None
end
(* -------------------------------------------------------------------- *)
exception IntroCollect of [
`InternalBreak
]
exception CollectBreak
exception CollectCore of ipcore located
let rec process_mintros_1 ?(cf = true) ttenv pis gs =
let module ST = IntroState in
let mk_intro ids (hyps, form) =
let (_, torev), ids =
let rec compile (((hyps, form), torev) as acc) newids ids =
match ids with [] -> (acc, newids) | s :: ids ->
let rec destruct fp =
match EcFol.sform_of_form fp with
| SFquant (Lforall, (x, _) , lazy fp) ->
let name = EcIdent.name x in (name, Some name, `Named, fp)
| SFlet (LSymbol (x, _), _, fp) ->
let name = EcIdent.name x in (name, Some name, `Named, fp)
| SFimp (_, fp) ->
("H", None, `Hyp, fp)
| _ -> begin
match EcReduction.h_red_opt EcReduction.full_red hyps fp with
| None -> ("_", None, `None, f_true)
| Some f -> destruct f
end
in
let name, revname, kind, form = destruct form in
let revertid =
if ttenv.tt_oldip then
match unloc s with
| `Revert -> Some (Some false, EcIdent.create "_")
| `Clear -> Some (None , EcIdent.create "_")
| `Named s -> Some (None , EcIdent.create s)
| `Anonymous a ->
if (a = Some None && kind = `None) || a = Some (Some 0)
then None
else Some (None, LDecl.fresh_id hyps name)
else
match unloc s with
| `Revert -> Some (Some false, EcIdent.create "_")
| `Clear -> Some (Some true , EcIdent.create "_")
| `Named s -> Some (None , EcIdent.create s)
| `Anonymous a ->
match a, kind with
| Some None, `None ->
None
| (Some (Some 0), _) ->
None
| _, `Named ->
Some (None, LDecl.fresh_id hyps ("`" ^ name))
| _, _ ->
Some (None, LDecl.fresh_id hyps "_")
in
match revertid with
| Some (revert, id) ->
let id = mk_loc s.pl_loc id in
let hyps = LDecl.add_local id.pl_desc (LD_var (tbool, None)) hyps in
let revert = revert |> omap (fun b -> if b then `Clear else `Revert) in
let torev = revert
|> omap (fun b -> (b, unloc id, revname) :: torev)
|> odfl torev
in
let newids = Tagged (unloc id, Some id.pl_loc) :: newids in
let ((hyps, form), torev), newids =
match unloc s with
| `Anonymous (Some None) when kind <> `None ->
compile ((hyps, form), torev) newids [s]
| `Anonymous (Some (Some i)) when 1 < i ->
let s = mk_loc (loc s) (`Anonymous (Some (Some (i-1)))) in
compile ((hyps, form), torev) newids [s]
| _ -> ((hyps, form), torev), newids
in compile ((hyps, form), torev) newids ids
| None -> compile ((hyps, form), torev) newids ids
in snd_map List.rev (compile ((hyps, form), []) [] ids)
in (List.rev torev, ids)
in
let rec collect intl acc core pis =
let maybe_core () =
let loc = EcLocation.mergeall (List.map loc core) in
match core with
| [] -> acc
| _ -> mk_loc loc (`Core (List.rev core)) :: acc
in
match pis with
| [] -> (maybe_core (), [])
| { pl_loc = ploc } as pi :: pis ->
try
let ip =
match unloc pi with
| IPBreak ->
if intl then raise (IntroCollect `InternalBreak);
raise CollectBreak
| IPCore x -> raise (CollectCore (mk_loc (loc pi) x))
| IPDup -> `Dup
| IPDone x -> `Done x
| IPSmt x -> `Smt x
| IPClear x -> `Clear x
| IPRw x -> `Rw x
| IPDelta x -> `Delta x
| IPView x -> `View x
| IPSubst x -> `Subst x
| IPSimplify x -> `Simpl x
| IPCrush x -> `Crush x
| IPCase (mode, x) ->
let subcollect = List.rev -| fst -| collect true [] [] in
`Case (mode, List.map subcollect x)
| IPSubstTop x -> `SubstTop x
in collect intl (mk_loc ploc ip :: maybe_core ()) [] pis
with
| CollectBreak -> (maybe_core (), pis)
| CollectCore x -> collect intl acc (x :: core) pis
in
let collect pis = collect false [] [] pis in
let rec intro1_core (st : ST.state) ids (tc : tcenv1) =
let torev, ids = mk_intro ids (FApi.tc1_flat tc) in
List.iter (fun (act, id, name) -> ST.push ?name act id st) torev;
t_intros ids tc
and intro1_dup (_ : ST.state) (tc : tcenv1) =
try
let pt = PT.pt_of_uglobal !!tc (FApi.tc1_hyps tc) LG.p_ip_dup in
EcLowGoal.Apply.t_apply_bwd_r ~mode:fmrigid ~canview:false pt tc
with EcLowGoal.Apply.NoInstance _ ->
tc_error !!tc "no top-assumption to duplicate"
and intro1_done (_ : ST.state) simplify (tc : tcenv1) =
let t =
match simplify with
| Some x ->
t_seq (t_simplify_lg ~delta:false (ttenv, x)) process_trivial
| None -> process_trivial
in t tc
and intro1_smt (_ : ST.state) ((dn, pi) : _ * pprover_infos) (tc : tcenv1) =
if dn then
t_or process_done (process_smt ttenv pi) tc
else process_smt ttenv pi tc
and intro1_simplify (_ : ST.state) logic tc =
t_simplify_lg ~delta:false (ttenv, logic) tc
and intro1_clear (_ : ST.state) xs tc =
process_clear xs tc
and intro1_case (st : ST.state) nointro pis gs =
let onsub gs =
if List.is_empty pis then gs else begin
if FApi.tc_count gs <> List.length pis then
tc_error !$gs
"not the right number of intro-patterns (got %d, expecting %d)"
(List.length pis) (FApi.tc_count gs);
t_sub (List.map (dointro1 st false) pis) gs
end
in
let tc = t_ors [t_elimT_ind `Case; t_elim; t_elim_prind `Case] in
let tc =
fun g ->
try tc g
with InvalidGoalShape ->
tc_error !!g "invalid intro-pattern: nothing to eliminate"
in
if nointro && not cf then onsub gs else begin
match pis with
| [] -> t_onall tc gs
| _ -> t_onall (fun gs -> onsub (tc gs)) gs
end
and intro1_full_case (st : ST.state)
((prind, delta), withor, (cnt : icasemode_full option)) pis tc
=
let cnt = cnt |> odfl (`AtMost 1) in
let red = if delta then `Full else `NoDelta in
let t_case =
let t_and, t_or =
if prind then
((fun tc -> fst_map List.singleton (t_elim_iso_and ~reduce:red tc)),
(fun tc -> t_elim_iso_or ~reduce:red tc))
else
((fun tc -> ([2] , t_elim_and ~reduce:red tc)),
(fun tc -> ([1; 1], t_elim_or ~reduce:red tc))) in
let ts = if withor then [t_and; t_or] else [t_and] in
fun tc -> FApi.t_or_map ts tc
in
let onsub gs =
if List.is_empty pis then gs else begin
if FApi.tc_count gs <> List.length pis then
tc_error !$gs
"not the right number of intro-patterns (got %d, expecting %d)"
(List.length pis) (FApi.tc_count gs);
t_sub (List.map (dointro1 st false) pis) gs
end
in
let doit tc =
let rec aux imax tc =
if imax = Some 0 then t_id tc else
try
let ntop, tc = t_case tc in
FApi.t_sublasts
(List.map (fun i tc -> aux (omap ((+) (i-1)) imax) tc) ntop)
tc
with InvalidGoalShape ->
try
tc |> EcLowGoal.t_intro_sx_seq
`Fresh
(fun id ->
t_seq
(aux (omap ((+) (-1)) imax))
(t_generalize_hyps ~clear:`Yes [id]))
with
| EcCoreGoal.TcError _ when EcUtils.is_some imax ->
tc_error !!tc "not enough top-assumptions"
| EcCoreGoal.TcError _ ->
t_id tc
in
match cnt with
| `AtMost cnt -> aux (Some (max 1 cnt)) tc
| `AsMuch -> aux None tc
in
if List.is_empty pis then doit tc else onsub (doit tc)
and intro1_rw (_ : ST.state) (o, s) tc =
let h = EcIdent.create "_" in
let rwt tc =
let pt = PT.pt_of_hyp !!tc (FApi.tc1_hyps tc) h in
process_rewrite1_core ~close:false (s, None, o) pt tc
in t_seqs [t_intros_i [h]; rwt; t_clear h] tc
and intro1_unfold (_ : ST.state) (s, o) p tc =
process_delta ~und_delta:ttenv.tt_und_delta (s, o, p) tc
and intro1_view (_ : ST.state) pe tc =
process_view1 pe tc
and intro1_subst (_ : ST.state) d (tc : tcenv1) =
try
t_intros_i_seq ~clear:true [EcIdent.create "_"]
(EcLowGoal.t_subst ~clear:true ~tside:(d :> tside))
tc
with InvalidGoalShape ->
tc_error !!tc "nothing to substitute"
and intro1_subst_top (_ : ST.state) (omax, osd) (tc : tcenv1) =
let t_subst eqid =
let sk1 = { empty_subst_kind with sk_local = true ; } in
let sk2 = { full_subst_kind with sk_local = false; } in
let side = `All osd in
FApi.t_or
(t_subst ~tside:side ~kind:sk1 ~eqid)
(t_subst ~tside:side ~kind:sk2 ~eqid)
in
let togen = ref [] in
let rec doit i tc =
match omax with Some max when i >= max -> tcenv_of_tcenv1 tc | _ ->
try
let id = EcIdent.create "_" in
let tc = EcLowGoal.t_intros_i_1 [id] tc in
FApi.t_switch (t_subst id) ~ifok:(doit (i+1))
~iffail:(fun tc -> togen := id :: !togen; doit (i+1) tc)
tc
with EcCoreGoal.TcError _ ->
if is_some omax then
tc_error !!tc "not enough top-assumptions";
tcenv_of_tcenv1 tc in
let tc = doit 0 tc in
t_generalize_hyps
~clear:`Yes ~missing:true
(List.rev !togen) (FApi.as_tcenv1 tc)
and intro1_crush (_st : ST.state) (d : crushmode) (gs : tcenv1) =
let delta, tsolve = process_crushmode d in
FApi.t_or
(EcPhlConseq.t_conseqauto ~delta ?tsolve)
(EcLowGoal.t_crush ~delta ?tsolve)
gs
and dointro (st : ST.state) nointro pis (gs : tcenv) =
match pis with [] -> gs | { pl_desc = pi; pl_loc = ploc } :: pis ->
let nointro, gs =
let rl x = EcCoreGoal.reloc ploc x in
match pi with
| `Core ids ->
(false, rl (t_onall (intro1_core st ids)) gs)
| `Dup ->
(false, rl (t_onall (intro1_dup st)) gs)
| `Done b ->
(nointro, rl (t_onall (intro1_done st b)) gs)
| `Smt pi ->
(nointro, rl (t_onall (intro1_smt st pi)) gs)
| `Simpl b ->
(nointro, rl (t_onall (intro1_simplify st b)) gs)
| `Clear xs ->
(nointro, rl (t_onall (intro1_clear st xs)) gs)
| `Case (`One, pis) ->
(false, rl (intro1_case st nointro pis) gs)
| `Case (`Full x, pis) ->
(false, rl (t_onall (intro1_full_case st x pis)) gs)
| `Rw (o, s, None) ->
(false, rl (t_onall (intro1_rw st (o, s))) gs)
| `Rw (o, s, Some i) ->
(false, rl (t_onall (t_do `All i (intro1_rw st (o, s)))) gs)
| `Delta ((o, s), p) ->
(nointro, rl (t_onall (intro1_unfold st (o, s) p)) gs)
| `View pe ->
(false, rl (t_onall (intro1_view st pe)) gs)
| `Subst (d, None) ->
(false, rl (t_onall (intro1_subst st d)) gs)
| `Subst (d, Some i) ->
(false, rl (t_onall (t_do `All i (intro1_subst st d))) gs)
| `SubstTop d ->
(false, rl (t_onall (intro1_subst_top st d)) gs)
| `Crush d ->
(false, rl (t_onall (intro1_crush st d)) gs)
in dointro st nointro pis gs
and dointro1 st nointro pis tc =
dointro st nointro pis (FApi.tcenv_of_tcenv1 tc) in
try
let st = ST.create () in
let ip, pis = collect pis in
let gs = dointro st true (List.rev ip) gs in
let gs =
let ls = ST.listing st in
let gn = List.pmap (function (`Gen x, y) -> Some (x, y) | _ -> None) ls in
let cl = List.pmap (function (`Clear, y) -> Some y | _ -> None) ls in
t_onall (fun tc ->
t_generalize_hyps_x
~missing:true ~naming:(ST.naming st)
gn tc)
(t_onall (t_clears cl) gs)
in
if List.is_empty pis then gs else
gs |> t_onall (fun tc ->
process_mintros_1 ~cf:true ttenv pis (FApi.tcenv_of_tcenv1 tc))
with IntroCollect e -> begin
match e with
| `InternalBreak ->
tc_error !$gs "cannot use internal break in intro-patterns"
end
(* -------------------------------------------------------------------- *)
let process_intros_1 ?cf ttenv pis tc =
process_mintros_1 ?cf ttenv pis (FApi.tcenv_of_tcenv1 tc)
(* -------------------------------------------------------------------- *)
let rec process_mintros ?cf ttenv pis tc =
match pis with [] -> tc | pi :: pis ->
let tc = process_mintros_1 ?cf ttenv pi tc in
process_mintros ~cf:false ttenv pis tc
(* -------------------------------------------------------------------- *)
let process_intros ?cf ttenv pis tc =
process_mintros ?cf ttenv pis (FApi.tcenv_of_tcenv1 tc)
(* -------------------------------------------------------------------- *)
let process_generalize1 ?(doeq = false) pattern (tc : tcenv1) =
let env, hyps, concl = FApi.tc1_eflat tc in
let onresolved ?(tryclear = true) pattern =
let clear = if tryclear then `Yes else `No in
match pattern with
| `Form (occ, pf) -> begin
match pf.pl_desc with
| PFident ({pl_desc = ([], s)}, None)
when not doeq && is_none occ && LDecl.has_name s hyps
->
let id = fst (LDecl.by_name s hyps) in
t_generalize_hyp ~clear id tc
| _ ->
let (ptenv, p) =
let (ps, ue), p = TTC.tc1_process_pattern tc pf in
let ev = MEV.of_idents (Mid.keys ps) `Form in
(ptenv !!tc hyps (ue, ev), p)
in
(try ignore (PT.pf_find_occurence ptenv ~ptn:p concl)
with PT.FindOccFailure _ -> tc_error !!tc "cannot find an occurence");
let p = PT.concretize_form ptenv p in
let occ = norm_rwocc occ in
let cpos =
try FPosition.select_form ~xconv:`AlphaEq hyps occ p concl
with InvalidOccurence -> tacuerror "invalid occurence selector"
in
let name =
match EcParsetree.pf_ident pf with
| None ->
EcIdent.create "x"
| Some x when EcIo.is_sym_ident x ->
EcIdent.create x
| Some _ ->
EcIdent.create (EcTypes.symbol_of_ty p.f_ty)
in
let name, newconcl = FPosition.topattern ~x:name cpos concl in
let newconcl =
if doeq then
if EcReduction.EqTest.for_type env p.f_ty tbool then
f_imps [f_iff p (f_local name p.f_ty)] newconcl
else
f_imps [f_eq p (f_local name p.f_ty)] newconcl
else newconcl in
let newconcl = f_forall [(name, GTty p.f_ty)] newconcl in
let pt = { pt_head = PTCut newconcl; pt_args = [PAFormula p]; } in
EcLowGoal.t_apply pt tc
end
| `ProofTerm fp -> begin
match fp.fp_head with
| FPNamed ({ pl_desc = ([], s) }, None)
when LDecl.has_name s hyps && List.is_empty fp.fp_args
->
let id = fst (LDecl.by_name s hyps) in
t_generalize_hyp ~clear id tc
| _ ->
let pt = PT.tc1_process_full_pterm tc fp in
if not (PT.can_concretize pt.PT.ptev_env) then
tc_error !!tc "cannot infer all placeholders";
let pt, ax = PT.concretize pt in
t_cutdef pt ax tc
end
| `LetIn x ->
let id =
let binding =
try Some (LDecl.by_name (unloc x) hyps)
with EcEnv.LDecl.LdeclError _ -> None in
match binding with
| Some (id, LD_var (_, Some _)) -> id
| _ ->
let msg = "symbol must reference let-in" in
tc_error ~loc:(loc x) !!tc "%s" msg
in t_generalize_hyp ~clear ~letin:true id tc
in
match ffpattern_of_genpattern hyps pattern with
| Some ff ->
let tryclear =
match pattern with
| (`Form (None, { pl_desc = PFident _ })) -> true
| _ -> false
in onresolved ~tryclear (`ProofTerm ff)
| None -> onresolved pattern
(* -------------------------------------------------------------------- *)
let process_generalize ?(doeq = false) patterns (tc : tcenv1) =
try
let patterns = List.mapi (fun i p ->
process_generalize1 ~doeq:(doeq && i = 0) p) patterns in
FApi.t_seqs (List.rev patterns) tc
with (EcCoreGoal.ClearError _) as err ->
tc_error_exn !!tc err
(* -------------------------------------------------------------------- *)
let rec process_mgenintros ?cf ttenv pis tc =
match pis with [] -> tc | pi :: pis ->
let tc =
match pi with
| `Ip pi -> process_mintros_1 ?cf ttenv pi tc
| `Gen gn ->
t_onall (
t_seqs [
process_clear gn.pr_clear;
process_generalize gn.pr_genp
]) tc
in process_mgenintros ~cf:false ttenv pis tc
(* -------------------------------------------------------------------- *)
let process_genintros ?cf ttenv pis tc =
process_mgenintros ?cf ttenv pis (FApi.tcenv_of_tcenv1 tc)
(* -------------------------------------------------------------------- *)
let process_move ?doeq views pr (tc : tcenv1) =
t_seqs
[process_clear pr.pr_clear;
process_generalize ?doeq pr.pr_genp;
process_view views]
tc
(* -------------------------------------------------------------------- *)
let process_pose xsym bds o p (tc : tcenv1) =
let (env, hyps, concl) = FApi.tc1_eflat tc in
let o = norm_rwocc o in
let (ptenv, p) =
let ps = ref Mid.empty in
let ue = TTC.unienv_of_hyps hyps in
let (senv, bds) = EcTyping.trans_binding env ue bds in
let p = EcTyping.trans_pattern senv ps ue p in
let ev = MEV.of_idents (Mid.keys !ps) `Form in
(ptenv !!tc hyps (ue, ev),
f_lambda (List.map (snd_map gtty) bds) p)
in
let dopat =
try
ignore (PT.pf_find_occurence ~occmode:PT.om_rigid ptenv ~ptn:p concl);
true
with PT.FindOccFailure _ ->
if not (PT.can_concretize ptenv) then
if not (EcMatching.MEV.filled !(ptenv.PT.pte_ev)) then
tc_error !!tc "cannot find an occurence"
else
tc_error !!tc "%s - %s"
"cannot find an occurence"
"instantiate type variables manually"
else
false
in
let p = PT.concretize_form ptenv p in
let (x, letin) =
match dopat with
| false -> (EcIdent.create (unloc xsym), concl)
| true -> begin
let cpos =
try FPosition.select_form ~xconv:`AlphaEq hyps o p concl
with InvalidOccurence -> tacuerror "invalid occurence selector"
in
FPosition.topattern ~x:(EcIdent.create (unloc xsym)) cpos concl
end
in
let letin = EcFol.f_let1 x p letin in
FApi.t_seq
(t_change letin)
(t_intros [Tagged (x, Some xsym.pl_loc)]) tc
(* -------------------------------------------------------------------- *)
let process_memory (xsym : psymbol) tc =
let x = EcIdent.create (unloc xsym) in
let m = EcMemory.empty_local_mt ~witharg:false in
FApi.t_sub
[
t_trivial;
FApi.t_seqs [
t_elim_exists ~reduce:`None;
t_intros [Tagged (x, Some xsym.pl_loc)];
t_intros_n ~clear:true 1;
]
]
(t_cut (f_exists [x, GTmem m] f_true) tc)
(* -------------------------------------------------------------------- *)
type apply_t = EcParsetree.apply_info
let process_apply ~implicits ((infos, orv) : apply_t * prevert option) tc =
let do_apply tc =
match infos with
| `ApplyIn (pe, tg) ->
process_apply_fwd ~implicits (pe, tg) tc
| `Apply (pe, mode) ->
let for1 tc pe =
t_last (process_apply_bwd ~implicits `Apply pe) tc in
let tc = List.fold_left for1 (tcenv_of_tcenv1 tc) pe in
if mode = `Exact then t_onall process_done tc else tc
| `Alpha pe ->
process_apply_bwd ~implicits `Alpha pe tc
| `ExactType qs ->
process_exacttype qs tc
| `Top mode ->
let tc = process_apply_top tc in
if mode = `Exact then t_onall process_done tc else tc
in
t_seq
(fun tc -> ofdfl
(fun () -> t_id tc)
(omap (fun rv -> process_move [] rv tc) orv))
do_apply tc
(* -------------------------------------------------------------------- *)
let process_subst syms (tc : tcenv1) =
let resolve symp =
let sym = TTC.tc1_process_form_opt tc None symp in
match sym.f_node with
| Flocal id -> `Local id
| Fglob (mp, mem) -> `Glob (mp, mem)
| Fpvar (pv, mem) -> `PVar (pv, mem)
| _ ->
tc_error !!tc ~loc:symp.pl_loc
"this formula is not subject to substitution"
in
match List.map resolve syms with
| [] -> t_repeat t_subst tc
| syms -> FApi.t_seqs (List.map (fun var tc -> t_subst ~var tc) syms) tc
(* -------------------------------------------------------------------- *)
type cut_t = intropattern * pformula * (ptactics located) option
type cutmode = [`Have | `Suff]
let process_cut ?(mode = `Have) engine ttenv ((ip, phi, t) : cut_t) tc =
let phi = TTC.tc1_process_formula tc phi in
let tc = EcLowGoal.t_cut phi tc in
let applytc tc =
t |> ofold (fun t tc ->
let t = mk_loc (loc t) (Pby (Some (unloc t))) in
t_onall (engine t) tc) (FApi.tcenv_of_tcenv1 tc)
in
match mode with
| `Have ->
FApi.t_first applytc
(FApi.t_last (process_intros_1 ttenv ip) tc)
| `Suff ->
FApi.t_rotate `Left 1
(FApi.t_on1 0 t_id ~ttout:applytc
(FApi.t_last (process_intros_1 ttenv ip) tc))
(* -------------------------------------------------------------------- *)
type cutdef_t = intropattern * pcutdef
let process_cutdef ttenv (ip, pt) (tc : tcenv1) =
let pt = {
fp_mode = `Implicit;
fp_head = FPNamed (pt.ptcd_name, pt.ptcd_tys);
fp_args = pt.ptcd_args;
} in
let pt = PT.tc1_process_full_pterm tc pt in
if not (PT.can_concretize pt.ptev_env) then
tc_error !!tc "cannot infer all placeholders";
let pt, ax = PT.concretize pt in
FApi.t_sub
[EcLowGoal.t_apply pt; process_intros_1 ttenv ip]
(t_cut ax tc)
(* -------------------------------------------------------------------- *)
type cutdef_sc_t = intropattern * pcutdef_schema
let process_cutdef_sc ttenv (ip, inst) (tc : tcenv1) =
let pt,sc_i = PT.tc1_process_sc_instantiation tc inst in
FApi.t_sub
[EcLowGoal.t_apply pt; process_intros_1 ttenv ip]
(t_cut sc_i tc)
(* -------------------------------------------------------------------- *)
let process_left (tc : tcenv1) =
try
t_ors [EcLowGoal.t_left; EcLowGoal.t_or_intro_prind `Left] tc
with InvalidGoalShape ->
tc_error !!tc "cannot apply `left` on that goal"
(* -------------------------------------------------------------------- *)
let process_right (tc : tcenv1) =
try
t_ors [EcLowGoal.t_right; EcLowGoal.t_or_intro_prind `Right] tc
with InvalidGoalShape ->
tc_error !!tc "cannot apply `right` on that goal"
(* -------------------------------------------------------------------- *)
let process_split (tc : tcenv1) =
try t_ors [EcLowGoal.t_split; EcLowGoal.t_split_prind] tc
with InvalidGoalShape ->
tc_error !!tc "cannot apply `split` on that goal"
(* -------------------------------------------------------------------- *)
let process_elim (pe, qs) tc =
let doelim tc =
match qs with
| None -> t_or (t_elimT_ind `Ind) t_elim tc
| Some qs ->
let qs = {
fp_mode = `Implicit;
fp_head = FPNamed (qs, None);
fp_args = [];
} in process_elimT qs tc
in
try
FApi.t_last doelim (process_move [] pe tc)
with EcCoreGoal.InvalidGoalShape ->
tc_error !!tc "don't know what to eliminate"
(* -------------------------------------------------------------------- *)
let process_case ?(doeq = false) gp tc =
let module E = struct exception LEMFailure end in
try
match gp.pr_rev with
| { pr_genp = [`Form (None, pf)] }
when List.is_empty gp.pr_view ->
let env = FApi.tc1_env tc in
let f =
try TTC.process_formula (FApi.tc1_hyps tc) pf
with TT.TyError _ | LocError (_, TT.TyError _) -> raise E.LEMFailure
in
if not (EcReduction.EqTest.for_type env f.f_ty tbool) then
raise E.LEMFailure;
begin
match (fst (destr_app f)).f_node with
| Fop (p, _) when EcEnv.Op.is_prind env p ->
raise E.LEMFailure
| _ -> ()
end;
t_seqs
[process_clear gp.pr_rev.pr_clear; t_case f;
t_simplify_with_info EcReduction.betaiota_red]
tc
| _ -> raise E.LEMFailure
with E.LEMFailure ->
try
FApi.t_last
(t_ors [t_elimT_ind `Case; t_elim; t_elim_prind `Case])
(process_move ~doeq gp.pr_view gp.pr_rev tc)
with EcCoreGoal.InvalidGoalShape ->
tc_error !!tc "don't known what to eliminate"
(* -------------------------------------------------------------------- *)
let process_exists args (tc : tcenv1) =
let hyps = FApi.tc1_hyps tc in
let pte = (TTC.unienv_of_hyps hyps, EcMatching.MEV.empty) in
let pte = PT.ptenv !!tc (FApi.tc1_hyps tc) pte in
let for1 concl arg =
match TTC.destruct_exists hyps concl with
| None -> tc_error !!tc "not an existential"
| Some (`Exists (x, xty, f)) ->
let arg =
match xty with
| GTty _ -> trans_pterm_arg_value pte arg
| GTmem _ -> trans_pterm_arg_mem pte arg
| GTmodty _ -> trans_pterm_arg_mod pte arg
in
PT.check_pterm_arg pte (x, xty) f arg.ptea_arg
in
let _concl, args = List.map_fold for1 (FApi.tc1_goal tc) args in
if not (PT.can_concretize pte) then
tc_error !!tc "cannot infer all placeholders";
let pte = PT.concretize_env pte in
let args = List.map (PT.concretize_e_arg pte) args in
EcLowGoal.t_exists_intro_s args tc
(* -------------------------------------------------------------------- *)
let process_congr tc =
let (env, hyps, concl) = FApi.tc1_eflat tc in
if not (EcFol.is_eq_or_iff concl) then
tc_error !!tc "goal must be an equality or an equivalence";
let ((f1, f2), iseq) =
if EcFol.is_eq concl
then (EcFol.destr_eq concl, true )
else (EcFol.destr_iff concl, false) in
let t_ensure_eq =
if iseq then t_id
else
(fun tc ->
let hyps = FApi.tc1_hyps tc in
EcLowGoal.Apply.t_apply_bwd_r
(PT.pt_of_uglobal !!tc hyps LG.p_eq_iff) tc) in
let t_subgoal = t_ors [t_reflex ~mode:`Alpha; t_assumption `Alpha; t_id] in
match f1.f_node, f2.f_node with
| _, _ when EcReduction.is_alpha_eq hyps f1 f2 ->
FApi.t_seq t_ensure_eq EcLowGoal.t_reflex tc
| Fapp (o1, a1), Fapp (o2, a2)
when EcReduction.is_alpha_eq hyps o1 o2
&& List.length a1 = List.length a2 ->
let tt1 = t_congr (o1, o2) ((List.combine a1 a2), f1.f_ty) in
FApi.t_seqs [t_ensure_eq; tt1; t_subgoal] tc
| Fif (_, { f_ty = cty }, _), Fif _ ->
let tt0 tc =
let hyps = FApi.tc1_hyps tc in
EcLowGoal.Apply.t_apply_bwd_r
(PT.pt_of_global !!tc hyps LG.p_if_congr [cty]) tc
in FApi.t_seqs [tt0; t_subgoal] tc
| Ftuple _, Ftuple _ when iseq ->
FApi.t_seqs [t_split; t_subgoal] tc
| Fproj (f1, i1), Fproj (f2, i2)
when i1 = i2 && EcReduction.EqTest.for_type env f1.f_ty f2.f_ty
-> EcCoreGoal.FApi.xmutate1 tc `CongrProj [f_eq f1 f2]
| _, _ -> tacuerror "not a congruence"
(* -------------------------------------------------------------------- *)
let process_wlog ids wlog tc =
let hyps, _ = FApi.tc1_flat tc in
let toid s =
if not (LDecl.has_name (unloc s) hyps) then
tc_lookup_error !!tc ~loc:s.pl_loc `Local ([], unloc s);
fst (LDecl.by_name (unloc s) hyps) in
let ids = List.map toid ids in
let gen =
let wlog = TTC.tc1_process_formula tc wlog in
let tc = t_rotate `Left 1 (EcLowGoal.t_cut wlog tc) in
let tc = t_first (t_generalize_hyps ~clear:`Yes ids) tc in
FApi.tc_goal tc
in
t_rotate `Left 1
(t_first
(t_seq (t_clears ids) (t_intros_i ids))
(t_cut gen tc))
(* -------------------------------------------------------------------- *)
let process_wlog_suff ids wlog tc =
let hyps, _ = FApi.tc1_flat tc in
let toid s =
if not (LDecl.has_name (unloc s) hyps) then
tc_lookup_error !!tc ~loc:s.pl_loc `Local ([], unloc s);
fst (LDecl.by_name (unloc s) hyps) in
let ids = List.map toid ids in
let wlog =
let wlog = TTC.tc1_process_formula tc wlog in
let tc = t_first (t_generalize_hyps ~clear:`Yes ids) (t_cut wlog tc) in
FApi.tc_goal tc in
t_rotate `Left 1
(t_first
(t_seq (t_clears ids) (t_intros_i ids))
(t_cut wlog tc))
(* -------------------------------------------------------------------- *)
let process_wlog ~suff ids wlog tc =
if suff
then process_wlog_suff ids wlog tc
else process_wlog ids wlog tc
(* -------------------------------------------------------------------- *)
let process_genhave (ttenv : ttenv) ((name, ip, ids, gen) : pgenhave) tc =
let hyps, _ = FApi.tc1_flat tc in
let toid s =
if not (LDecl.has_name (unloc s) hyps) then
tc_lookup_error !!tc ~loc:s.pl_loc `Local ([], unloc s);
fst (LDecl.by_name (unloc s) hyps) in
let ids = List.map toid ids in
let gen =
let gen = TTC.tc1_process_formula tc gen in
let tc = EcLowGoal.t_cut gen tc in
let tc = t_first (t_generalize_hyps ~clear:`Yes ids) tc in
FApi.tc_goal tc in
let doip tc =
let genid = EcIdent.create (unloc name) in
let tc = t_intros_i_1 [genid] tc in
match ip with
| None ->
t_id tc
| Some ip ->
let pt = EcProofTerm.pt_of_hyp !!tc (FApi.tc1_hyps tc) genid in
let pt = List.fold_left EcProofTerm.apply_pterm_to_local pt ids in
let tc = t_cutdef pt.ptev_pt pt.ptev_ax tc in
process_mintros ttenv [ip] tc in
t_sub [
t_seq (t_clears ids) (t_intros_i ids);
doip
] (t_cut gen tc)
| null | https://raw.githubusercontent.com/EasyCrypt/easycrypt/2f98c08673b913635203cbb638011165a813f2e3/src/ecHiGoal.ml | ocaml | --------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
Continue with matching based unfolding
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
-------------------------------------------------------------------- | open EcUtils
open EcLocation
open EcSymbols
open EcParsetree
open EcTypes
open EcFol
open EcEnv
open EcMatching
open EcBaseLogic
open EcProofTerm
open EcCoreGoal
open EcCoreGoal.FApi
open EcLowGoal
module Sid = EcIdent.Sid
module Mid = EcIdent.Mid
module Sp = EcPath.Sp
module ER = EcReduction
module PT = EcProofTerm
module TT = EcTyping
module TTC = EcProofTyping
module LG = EcCoreLib.CI_Logic
type ttenv = {
tt_provers : EcParsetree.pprover_infos -> EcProvers.prover_infos;
tt_smtmode : [`Admit | `Strict | `Standard | `Report];
tt_implicits : bool;
tt_oldip : bool;
tt_redlogic : bool;
tt_und_delta : bool;
}
type engine = ptactic_core -> FApi.backward
let t_simplify_lg ?target ?delta (ttenv, logic) (tc : tcenv1) =
let logic =
match logic with
| `Default -> if ttenv.tt_redlogic then `Full else `ProductCompat
| `Variant -> if ttenv.tt_redlogic then `ProductCompat else `Full
in t_simplify ?target ?delta ~logic:(Some logic) tc
type focus_t = EcParsetree.tfocus
let process_tfocus tc (focus : focus_t) : tfocus =
let count = FApi.tc_count tc in
let check1 i =
let error () = tc_error !$tc "invalid focus index: %d" i in
if i >= 0
then if not (0 < i && i <= count) then error () else i-1
else if -i > count then error () else count+i
in
let checkfs fs =
List.fold_left
(fun rg (i1, i2) ->
let i1 = odfl min_int (omap check1 i1) in
let i2 = odfl max_int (omap check1 i2) in
if i1 <= i2 then ISet.add_range i1 i2 rg else rg)
ISet.empty fs
in
let posfs = omap checkfs (fst focus) in
let negfs = omap checkfs (snd focus) in
fun i ->
odfl true (posfs |> omap (ISet.mem i))
&& odfl true (negfs |> omap (fun fc -> not (ISet.mem i fc)))
let process_assumption (tc : tcenv1) =
EcLowGoal.t_assumption `Conv tc
let process_reflexivity (tc : tcenv1) =
try EcLowGoal.t_reflex tc
with InvalidGoalShape ->
tc_error !!tc "cannot prove goal by reflexivity"
let process_change fp (tc : tcenv1) =
let fp = TTC.tc1_process_formula tc fp in
t_change fp tc
let process_simplify_info ri (tc : tcenv1) =
let env, hyps, _ = FApi.tc1_eflat tc in
let do1 (sop, sid) ps =
match ps.pl_desc with
| ([], s) when LDecl.has_name s hyps ->
let id = fst (LDecl.by_name s hyps) in
(sop, Sid.add id sid)
| qs ->
match EcEnv.Op.lookup_opt qs env with
| None -> tc_lookup_error !!tc ~loc:ps.pl_loc `Operator qs
| Some p -> (Sp.add (fst p) sop, sid)
in
let delta_p, delta_h =
ri.pdelta
|> omap (List.fold_left do1 (Sp.empty, Sid.empty))
|> omap (fun (x, y) -> (fun p -> if Sp.mem p x then `Force else `No), (Sid.mem^~ y))
|> odfl ((fun _ -> `Yes), predT)
in
{
EcReduction.beta = ri.pbeta;
EcReduction.delta_p = delta_p;
EcReduction.delta_h = delta_h;
EcReduction.zeta = ri.pzeta;
EcReduction.iota = ri.piota;
EcReduction.eta = ri.peta;
EcReduction.logic = if ri.plogic then Some `Full else None;
EcReduction.modpath = ri.pmodpath;
EcReduction.user = ri.puser;
EcReduction.cost = ri.pcost;
}
let process_simplify ri (tc : tcenv1) =
t_simplify_with_info (process_simplify_info ri tc) tc
let process_cbv ri (tc : tcenv1) =
t_cbv_with_info (process_simplify_info ri tc) tc
let process_smt ?loc (ttenv : ttenv) pi (tc : tcenv1) =
let pi = ttenv.tt_provers pi in
match ttenv.tt_smtmode with
| `Admit ->
t_admit tc
| (`Standard | `Strict) as mode ->
t_seq (t_simplify ~delta:false) (t_smt ~mode pi) tc
| `Report ->
t_seq (t_simplify ~delta:false) (t_smt ~mode:(`Report loc) pi) tc
let process_clear symbols tc =
let hyps = FApi.tc1_hyps tc in
let toid s =
if not (LDecl.has_name (unloc s) hyps) then
tc_lookup_error !!tc ~loc:s.pl_loc `Local ([], unloc s);
fst (LDecl.by_name (unloc s) hyps)
in
try t_clears (List.map toid symbols) tc
with (ClearError _) as err -> tc_error_exn !!tc err
let process_algebra mode kind eqs (tc : tcenv1) =
let (env, hyps, concl) = FApi.tc1_eflat tc in
if not (EcAlgTactic.is_module_loaded env) then
tacuerror "ring/field cannot be used when AlgTactic is not loaded";
let (ty, f1, f2) =
match sform_of_form concl with
| SFeq (f1, f2) -> (f1.f_ty, f1, f2)
| _ -> tacuerror "conclusion must be an equation"
in
let eqs =
let eq1 { pl_desc = x } =
match LDecl.hyp_exists x hyps with
| false -> tacuerror "cannot find equation referenced by `%s'" x
| true -> begin
match sform_of_form (snd (LDecl.hyp_by_name x hyps)) with
| SFeq (f1, f2) ->
if not (EcReduction.EqTest.for_type env ty f1.f_ty) then
tacuerror "assumption `%s' is not an equation over the right type" x;
(f1, f2)
| _ -> tacuerror "assumption `%s' is not an equation" x
end
in List.map eq1 eqs
in
let tparams = (LDecl.tohyps hyps).h_tvar in
let tactic =
match
match mode, kind with
| `Simpl, `Ring -> `Ring EcAlgTactic.t_ring_simplify
| `Simpl, `Field -> `Field EcAlgTactic.t_field_simplify
| `Solve, `Ring -> `Ring EcAlgTactic.t_ring
| `Solve, `Field -> `Field EcAlgTactic.t_field
with
| `Ring t ->
let r =
match TT.get_ring (tparams, ty) env with
| None -> tacuerror "cannot find a ring structure"
| Some r -> r
in t r eqs (f1, f2)
| `Field t ->
let r =
match TT.get_field (tparams, ty) env with
| None -> tacuerror "cannot find a field structure"
| Some r -> r
in t r eqs (f1, f2)
in
tactic tc
let t_apply_prept pt tc =
EcLowGoal.Apply.t_apply_bwd_r (pt_of_prept tc pt) tc
module LowRewrite = struct
type error =
| LRW_NotAnEquation
| LRW_NothingToRewrite
| LRW_InvalidOccurence
| LRW_CannotInfer
| LRW_IdRewriting
| LRW_RPatternNoMatch
| LRW_RPatternNoRuleMatch
exception RewriteError of error
let rec find_rewrite_patterns ~inpred (dir : rwside) pt =
let hyps = pt.PT.ptev_env.PT.pte_hy in
let env = LDecl.toenv hyps in
let pt = { pt with ptev_ax = snd (PT.concretize pt) } in
let ptc = { pt with ptev_env = EcProofTerm.copy pt.ptev_env } in
let ax = pt.ptev_ax in
let base ax =
match EcFol.sform_of_form ax with
| EcFol.SFeq (f1, f2) -> [(pt, `Eq, (f1, f2))]
| EcFol.SFiff (f1, f2) -> [(pt, `Eq, (f1, f2))]
| EcFol.SFnot f ->
let pt' = pt_of_global_r pt.ptev_env LG.p_negeqF [] in
let pt' = apply_pterm_to_arg_r pt' (PVAFormula f) in
let pt' = apply_pterm_to_arg_r pt' (PVASub pt) in
[(pt', `Eq, (f, f_false))]
| _ -> []
and split ax =
match EcFol.sform_of_form ax with
| EcFol.SFand (`Sym, (f1, f2)) ->
let pt1 =
let pt'= pt_of_global_r pt.ptev_env LG.p_and_proj_l [] in
let pt'= apply_pterm_to_arg_r pt' (PVAFormula f1) in
let pt'= apply_pterm_to_arg_r pt' (PVAFormula f2) in
apply_pterm_to_arg_r pt' (PVASub pt) in
let pt2 =
let pt'= pt_of_global_r pt.ptev_env LG.p_and_proj_r [] in
let pt'= apply_pterm_to_arg_r pt' (PVAFormula f1) in
let pt'= apply_pterm_to_arg_r pt' (PVAFormula f2) in
apply_pterm_to_arg_r pt' (PVASub pt) in
(find_rewrite_patterns ~inpred dir pt2)
@ (find_rewrite_patterns ~inpred dir pt1)
| _ -> []
in
match base ax with
| _::_ as rws -> rws
| [] -> begin
let ptb = Lazy.from_fun (fun () ->
let pt1 = split ax
and pt2 =
if dir = `LtoR then
if ER.EqTest.for_type env ax.f_ty tbool
then Some (ptc, `Bool, (ax, f_true))
else None
else None
and pt3 = omap base
(EcReduction.h_red_opt EcReduction.full_red hyps ax)
in pt1 @ (otolist pt2) @ (odfl [] pt3)) in
let rec doit reduce =
match TTC.destruct_product ~reduce hyps ax with
| None -> begin
if reduce then Lazy.force ptb else
let pts = doit true in
if inpred then pts else (Lazy.force ptb) @ pts
end
| Some _ ->
let pt = EcProofTerm.apply_pterm_to_hole pt in
find_rewrite_patterns ~inpred:(inpred || reduce) dir pt
in doit false
end
let find_rewrite_patterns = find_rewrite_patterns ~inpred:false
type rwinfos = rwside * EcFol.form option * EcMatching.occ option
let t_rewrite_r ?(mode = `Full) ?target ((s, prw, o) : rwinfos) pt tc =
let hyps, tgfp = FApi.tc1_flat ?target tc in
let modes =
match mode with
| `Full -> [{ k_keyed = true; k_conv = false };
{ k_keyed = true; k_conv = true };]
| `Light -> [{ k_keyed = true; k_conv = false }] in
let for1 (pt, mode, (f1, f2)) =
let fp, tp = match s with `LtoR -> f1, f2 | `RtoL -> f2, f1 in
let subf, occmode =
match prw with
| None -> begin
try
PT.pf_find_occurence_lazy pt.PT.ptev_env ~modes ~ptn:fp tgfp
with
| PT.FindOccFailure `MatchFailure ->
raise (RewriteError LRW_NothingToRewrite)
| PT.FindOccFailure `IncompleteMatch ->
raise (RewriteError LRW_CannotInfer)
end
| Some prw -> begin
let prw, _ =
try
PT.pf_find_occurence_lazy
pt.PT.ptev_env ~full:false ~modes ~ptn:prw tgfp;
with PT.FindOccFailure `MatchFailure ->
raise (RewriteError LRW_RPatternNoMatch) in
try
PT.pf_find_occurence_lazy
pt.PT.ptev_env ~rooted:true ~modes ~ptn:fp prw
with
| PT.FindOccFailure `MatchFailure ->
raise (RewriteError LRW_RPatternNoRuleMatch)
| PT.FindOccFailure `IncompleteMatch ->
raise (RewriteError LRW_CannotInfer)
end in
if not occmode.k_keyed then begin
let tp = PT.concretize_form pt.PT.ptev_env tp in
if EcReduction.is_conv hyps fp tp then
raise (RewriteError LRW_IdRewriting);
end;
let pt = fst (PT.concretize pt) in
let cpos =
try FPosition.select_form
~xconv:`AlphaEq ~keyed:occmode.k_keyed
hyps o subf tgfp
with InvalidOccurence -> raise (RewriteError (LRW_InvalidOccurence))
in
EcLowGoal.t_rewrite
~keyed:occmode.k_keyed ?target ~mode pt (s, Some cpos) tc in
let rec do_first = function
| [] -> raise (RewriteError LRW_NothingToRewrite)
| (pt, mode, (f1, f2)) :: pts ->
try for1 (pt, mode, (f1, f2))
with RewriteError (LRW_NothingToRewrite | LRW_IdRewriting) ->
do_first pts
in
let pts = find_rewrite_patterns s pt in
if List.is_empty pts then
raise (RewriteError LRW_NotAnEquation);
do_first (List.rev pts)
let t_rewrite ?target (s, p, o) pt (tc : tcenv1) =
let hyps = FApi.tc1_hyps ?target tc in
let pt, ax = EcLowGoal.LowApply.check `Elim pt (`Hyps (hyps, !!tc)) in
let ptenv = ptenv_of_penv hyps !!tc in
t_rewrite_r ?target (s, p, o)
{ ptev_env = ptenv; ptev_pt = pt; ptev_ax = ax; }
tc
let t_autorewrite lemmas (tc : tcenv1) =
let pts =
let do1 lemma =
PT.pt_of_uglobal !!tc (FApi.tc1_hyps tc) lemma in
List.map do1 lemmas
in
let try1 pt tc =
let pt = { pt with PT.ptev_env = PT.copy pt.ptev_env } in
try t_rewrite_r (`LtoR, None, None) pt tc
with RewriteError _ -> raise InvalidGoalShape
in t_do_r ~focus:0 `Maybe None (t_ors (List.map try1 pts)) !@tc
end
let t_rewrite_prept info pt tc =
LowRewrite.t_rewrite_r info (pt_of_prept tc pt) tc
let process_solve ?bases ?depth (tc : tcenv1) =
match FApi.t_try_base (EcLowGoal.t_solve ~canfail:false ?bases ?depth) tc with
| `Failure _ ->
tc_error (FApi.tc1_penv tc) "[solve]: cannot close goal"
| `Success tc ->
tc
let process_trivial (tc : tcenv1) =
EcPhlAuto.t_pl_trivial ~conv:`Conv tc
let process_crushmode d =
d.cm_simplify, if d.cm_solve then Some process_trivial else None
let process_done tc =
let tc = process_trivial tc in
if not (FApi.tc_done tc) then
tc_error (FApi.tc_penv tc) "[by]: cannot close goals";
tc
let process_apply_bwd ~implicits mode (ff : ppterm) (tc : tcenv1) =
let pt = PT.tc1_process_full_pterm ~implicits tc ff in
try
match mode with
| `Alpha ->
begin try
PT.pf_form_match
pt.ptev_env
~mode:fmrigid
~ptn:pt.ptev_ax
(FApi.tc1_goal tc)
with EcMatching.MatchFailure ->
tc_error !!tc "@[<v>proof-term is not alpha-convertible to conclusion@ @[%a@]@]"
(EcPrinting.pp_form (EcPrinting.PPEnv.ofenv (EcEnv.LDecl.toenv pt.ptev_env.pte_hy))) pt.ptev_ax
end;
EcLowGoal.t_apply (fst (PT.concretize pt)) tc
| `Apply ->
EcLowGoal.Apply.t_apply_bwd_r pt tc
| `Exact ->
let aout = EcLowGoal.Apply.t_apply_bwd_r pt tc in
let aout = FApi.t_onall process_trivial aout in
if not (FApi.tc_done aout) then
tc_error !!tc "cannot close goal";
aout
with (EcLowGoal.Apply.NoInstance _) as err ->
tc_error_exn !!tc err
let process_exacttype qs (tc : tcenv1) =
let env, hyps, _ = FApi.tc1_eflat tc in
let p =
try EcEnv.Ax.lookup_path (EcLocation.unloc qs) env
with LookupFailure cause ->
tc_error !!tc "%a" EcEnv.pp_lookup_failure cause
in
let tys =
List.map (fun (a,_) -> EcTypes.tvar a)
(EcEnv.LDecl.tohyps hyps).h_tvar in
EcLowGoal.t_apply_s p tys ~args:[] ~sk:0 tc
let process_apply_fwd ~implicits (pe, hyp) tc =
let module E = struct exception NoInstance end in
let hyps = FApi.tc1_hyps tc in
if not (LDecl.hyp_exists (unloc hyp) hyps) then
tc_error !!tc "unknown hypothesis: %s" (unloc hyp);
let hyp, fp = LDecl.hyp_by_name (unloc hyp) hyps in
let pte = PT.tc1_process_full_pterm ~implicits tc pe in
try
let rec instantiate pte =
match TTC.destruct_product hyps pte.PT.ptev_ax with
| None -> raise E.NoInstance
| Some (`Forall _) ->
instantiate (PT.apply_pterm_to_hole pte)
| Some (`Imp (f1, f2)) ->
try
PT.pf_form_match ~mode:fmdelta pte.PT.ptev_env ~ptn:f1 fp;
(pte, f2)
with MatchFailure -> raise E.NoInstance
in
let (pte, cutf) = instantiate pte in
if not (PT.can_concretize pte.ptev_env) then
tc_error !!tc "cannot infer all variables";
let pt = fst (PT.concretize pte) in
let pt = { pt with pt_args = pt.pt_args @ [palocal hyp]; } in
let cutf = PT.concretize_form pte.PT.ptev_env cutf in
FApi.t_last
(FApi.t_seq (t_clear hyp) (t_intros_i [hyp]))
(t_cutdef pt cutf tc)
with E.NoInstance ->
tc_error_lazy !!tc
(fun fmt ->
let ppe = EcPrinting.PPEnv.ofenv (FApi.tc1_env tc) in
Format.fprintf fmt
"cannot apply (in %a) the given proof-term for:\n\n%!"
(EcPrinting.pp_local ppe) hyp;
Format.fprintf fmt
" @[%a@]" (EcPrinting.pp_form ppe) pte.PT.ptev_ax)
let process_apply_top tc =
let hyps, concl = FApi.tc1_flat tc in
match TTC.destruct_product hyps concl with
| Some (`Imp _) -> begin
let h = LDecl.fresh_id hyps "h" in
try
EcLowGoal.t_intros_i_seq ~clear:true [h]
(EcLowGoal.Apply.t_apply_bwd { pt_head = PTLocal h; pt_args = []} )
tc
with (EcLowGoal.Apply.NoInstance _) as err ->
tc_error_exn !!tc err
end
| _ -> tc_error !!tc "no top assumption"
let process_rewrite1_core ?mode ?(close = true) ?target (s, p, o) pt tc =
let o = norm_rwocc o in
try
let tc = LowRewrite.t_rewrite_r ?mode ?target (s, p, o) pt tc in
let cl = fun tc ->
if EcFol.f_equal f_true (FApi.tc1_goal tc) then
t_true tc
else t_id tc
in if close then FApi.t_last cl tc else tc
with
| LowRewrite.RewriteError e ->
match e with
| LowRewrite.LRW_NotAnEquation ->
tc_error !!tc "not an equation to rewrite"
| LowRewrite.LRW_NothingToRewrite ->
tc_error !!tc "nothing to rewrite"
| LowRewrite.LRW_InvalidOccurence ->
tc_error !!tc "invalid occurence selector"
| LowRewrite.LRW_CannotInfer ->
tc_error !!tc "cannot infer all placeholders"
| LowRewrite.LRW_IdRewriting ->
tc_error !!tc "refuse to perform an identity rewriting"
| LowRewrite.LRW_RPatternNoMatch ->
tc_error !!tc "r-pattern does not match the goal"
| LowRewrite.LRW_RPatternNoRuleMatch ->
tc_error !!tc "r-pattern does not match the rewriting rule"
let process_delta ~und_delta ?target (s, o, p) tc =
let env, hyps, concl = FApi.tc1_eflat tc in
let o = norm_rwocc o in
let idtg, target =
match target with
| None -> (None, concl)
| Some h -> fst_map some (LDecl.hyp_by_name (unloc h) hyps)
in
match unloc p with
| PFident ({ pl_desc = ([], x) }, None)
when s = `LtoR && EcUtils.is_none o ->
let check_op = fun p -> if sym_equal (EcPath.basename p) x then `Force else `No in
let check_id = fun y -> sym_equal (EcIdent.name y) x in
let ri =
{ EcReduction.no_red with
EcReduction.delta_p = check_op;
EcReduction.delta_h = check_id; } in
let redform = EcReduction.simplify ri hyps target in
if und_delta then begin
if EcFol.f_equal target redform then
EcEnv.notify env `Warning "unused unfold: /%s" x
end;
t_change ~ri ?target:idtg redform tc
| _ ->
let (ptenv, p) =
let (ps, ue), p = TTC.tc1_process_pattern tc p in
let ev = MEV.of_idents (Mid.keys ps) `Form in
(ptenv !!tc hyps (ue, ev), p)
in
let (tvi, tparams, body, args, dp) =
match sform_of_form p with
| SFop (p, args) -> begin
let op = EcEnv.Op.by_path (fst p) env in
match op.EcDecl.op_kind with
| EcDecl.OB_oper (Some (EcDecl.OP_Plain (e, _))) ->
(snd p, op.EcDecl.op_tparams, form_of_expr EcFol.mhr e, args, Some (fst p))
| EcDecl.OB_pred (Some (EcDecl.PR_Plain f)) ->
(snd p, op.EcDecl.op_tparams, f, args, Some (fst p))
| _ ->
tc_error !!tc "the operator cannot be unfolded"
end
| SFlocal x when LDecl.can_unfold x hyps ->
([], [], LDecl.unfold x hyps, [], None)
| SFother { f_node = Fapp ({ f_node = Flocal x }, args) }
when LDecl.can_unfold x hyps ->
([], [], LDecl.unfold x hyps, args, None)
| _ -> tc_error !!tc "not headed by an operator/predicate"
in
let ri = { EcReduction.full_red with
delta_p = (fun p -> if Some p = dp then `Force else `Yes)} in
let na = List.length args in
match s with
| `LtoR -> begin
let matches =
try ignore (PT.pf_find_occurence ptenv ~ptn:p target); true
with PT.FindOccFailure _ -> false
in
if matches then begin
let p = concretize_form ptenv p in
let cpos =
let test = fun _ fp ->
let fp =
match fp.f_node with
| Fapp (h, hargs) when List.length hargs > na ->
let (a1, a2) = List.takedrop na hargs in
f_app h a1 (toarrow (List.map f_ty a2) fp.f_ty)
| _ -> fp
in
if EcReduction.is_alpha_eq hyps p fp
then `Accept (-1)
else `Continue
in
try FPosition.select ?o test target
with InvalidOccurence ->
tc_error !!tc "invalid occurences selector"
in
let target =
FPosition.map cpos
(fun topfp ->
let (fp, args) = EcFol.destr_app topfp in
match sform_of_form fp with
| SFop ((_, tvi), []) -> begin
FIXME : TC HOOK
let subst = EcTypes.Tvar.init (List.map fst tparams) tvi in
let body = EcFol.Fsubst.subst_tvar subst body in
let body = f_app body args topfp.f_ty in
try EcReduction.h_red EcReduction.beta_red hyps body
with EcEnv.NotReducible -> body
end
| SFlocal _ -> begin
assert (tparams = []);
let body = f_app body args topfp.f_ty in
try EcReduction.h_red EcReduction.beta_red hyps body
with EcEnv.NotReducible -> body
end
| _ -> assert false)
target
in
t_change ~ri ?target:idtg target tc
end else t_id tc
end
| `RtoL ->
let fp =
FIXME : TC HOOK
let subst = EcTypes.Tvar.init (List.map fst tparams) tvi in
let body = EcFol.Fsubst.subst_tvar subst body in
let fp = f_app body args p.f_ty in
try EcReduction.h_red EcReduction.beta_red hyps fp
with EcEnv.NotReducible -> fp
in
let matches =
try ignore (PT.pf_find_occurence ptenv ~ptn:fp target); true
with PT.FindOccFailure _ -> false
in
if matches then begin
let p = concretize_form ptenv p in
let fp = concretize_form ptenv fp in
let cpos =
try FPosition.select_form hyps o fp target
with InvalidOccurence ->
tc_error !!tc "invalid occurences selector"
in
let target = FPosition.map cpos (fun _ -> p) target in
t_change ~ri ?target:idtg target tc
end else t_id tc
let process_rewrite1_r ttenv ?target ri tc =
let implicits = ttenv.tt_implicits in
let und_delta = ttenv.tt_und_delta in
match unloc ri with
| RWDone simpl ->
let tt =
match simpl with
| Some logic ->
let hyps = FApi.tc1_hyps tc in
let target = target |> omap (fst |- LDecl.hyp_by_name^~ hyps |- unloc) in
t_simplify_lg ?target ~delta:false (ttenv, logic)
| None -> t_id
in FApi.t_seq tt process_trivial tc
| RWSimpl logic ->
let hyps = FApi.tc1_hyps tc in
let target = target |> omap (fst |- LDecl.hyp_by_name^~ hyps |- unloc) in
t_simplify_lg ?target ~delta:false (ttenv, logic) tc
| RWDelta ((s, r, o, px), p) -> begin
if Option.is_some px then
tc_error !!tc "cannot use pattern selection in delta-rewrite rules";
let do1 tc = process_delta ~und_delta ?target (s, o, p) tc in
match r with
| None -> do1 tc
| Some (b, n) -> t_do b n do1 tc
end
| RWRw (((s : rwside), r, o, p), pts) -> begin
let do1 (mode : [`Full | `Light]) ((subs : rwside), pt) tc =
let hyps = FApi.tc1_hyps tc in
let target = target |> omap (fst |- LDecl.hyp_by_name^~ hyps |- unloc) in
let hyps = FApi.tc1_hyps ?target tc in
let ptenv, prw =
match p with
| None ->
PT.ptenv_of_penv hyps !!tc, None
| Some p ->
let (ps, ue), p = TTC.tc1_process_pattern tc p in
let ev = MEV.of_idents (Mid.keys ps) `Form in
(PT.ptenv !!tc hyps (ue, ev), Some p) in
let theside =
match s, subs with
| `LtoR, _ -> (subs :> rwside)
| _ , `LtoR -> (s :> rwside)
| `RtoL, `RtoL -> (`LtoR :> rwside) in
let is_baserw p =
EcEnv.BaseRw.is_base p.pl_desc (FApi.tc1_env tc) in
match pt with
| { fp_head = FPNamed (p, None); fp_args = []; }
when pt.fp_mode = `Implicit && is_baserw p
->
let env = FApi.tc1_env tc in
let ls = snd (EcEnv.BaseRw.lookup p.pl_desc env) in
let ls = EcPath.Sp.elements ls in
let do1 lemma tc =
let pt = PT.pt_of_uglobal_r (PT.copy ptenv) lemma in
process_rewrite1_core ~mode ?target (theside, prw, o) pt tc
in t_ors (List.map do1 ls) tc
| { fp_head = FPNamed (p, None); fp_args = []; }
when pt.fp_mode = `Implicit
->
let env = FApi.tc1_env tc in
let ptenv0 = PT.copy ptenv in
let pt = PT.process_full_pterm ~implicits ptenv pt
in
if is_ptglobal pt.PT.ptev_pt.pt_head
&& List.is_empty pt.PT.ptev_pt.pt_args
then begin
let ls = EcEnv.Ax.all ~name:(unloc p) env in
let do1 (lemma, _) tc =
let pt = PT.pt_of_uglobal_r (PT.copy ptenv0) lemma in
process_rewrite1_core ~mode ?target (theside, prw, o) pt tc in
t_ors (List.map do1 ls) tc
end else
process_rewrite1_core ~mode ?target (theside, prw, o) pt tc
| _ ->
let pt = PT.process_full_pterm ~implicits ptenv pt in
process_rewrite1_core ~mode ?target (theside, prw, o) pt tc
in
let doall mode tc = t_ors (List.map (do1 mode) pts) tc in
match r with
| None ->
doall `Full tc
| Some (`Maybe, None) ->
t_seq
(t_do `Maybe (Some 1) (doall `Full))
(t_do `Maybe None (doall `Light))
tc
| Some (b, n) ->
t_do b n (doall `Full) tc
end
| RWPr (x, f) -> begin
if EcUtils.is_some target then
tc_error !!tc "cannot rewrite Pr[] in local assumptions";
EcPhlPrRw.t_pr_rewrite (unloc x, f) tc
end
| RWSmt (false, info) ->
process_smt ~loc:ri.pl_loc ttenv info tc
| RWSmt (true, info) ->
t_or process_done (process_smt ~loc:ri.pl_loc ttenv info) tc
| RWApp fp -> begin
let implicits = ttenv.tt_implicits in
match target with
| None -> process_apply_bwd ~implicits `Apply fp tc
| Some target -> process_apply_fwd ~implicits (fp, target) tc
end
| RWTactic `Ring ->
process_algebra `Solve `Ring [] tc
| RWTactic `Field ->
process_algebra `Solve `Field [] tc
let process_rewrite1 ttenv ?target ri tc =
EcCoreGoal.reloc (loc ri) (process_rewrite1_r ttenv ?target ri) tc
let process_rewrite ttenv ?target ri tc =
let do1 tc gi (fc, ri) =
let ngoals = FApi.tc_count tc in
let dorw = fun i tc ->
if gi = 0 || (i+1) = ngoals
then process_rewrite1 ttenv ?target ri tc
else process_rewrite1 ttenv ri tc
in
match fc |> omap ((process_tfocus tc) |- unloc) with
| None -> FApi.t_onalli dorw tc
| Some fc -> FApi.t_onselecti fc dorw tc
in
List.fold_lefti do1 (tcenv_of_tcenv1 tc) ri
let process_elimT qs tc =
let noelim () = tc_error !!tc "cannot recognize elimination principle" in
let (hyps, concl) = FApi.tc1_flat tc in
let (pf, pfty, _concl) =
match TTC.destruct_product hyps concl with
| Some (`Forall (x, GTty xty, concl)) -> (x, xty, concl)
| _ -> noelim ()
in
let pf = LDecl.fresh_id hyps (EcIdent.name pf) in
let tc = t_intros_i_1 [pf] tc in
let (hyps, concl) = FApi.tc1_flat tc in
let pt = PT.tc1_process_full_pterm tc qs in
let (_xp, xpty, ax) =
match TTC.destruct_product hyps pt.ptev_ax with
| Some (`Forall (xp, GTty xpty, f)) -> (xp, xpty, f)
| _ -> noelim ()
in
begin
let ue = pt.ptev_env.pte_ue in
try EcUnify.unify (LDecl.toenv hyps) ue (tfun pfty tbool) xpty
with EcUnify.UnificationFailure _ -> noelim ()
end;
if not (PT.can_concretize pt.ptev_env) then noelim ();
let ax = PT.concretize_form pt.ptev_env ax in
let rec skip ax =
match TTC.destruct_product hyps ax with
| Some (`Imp (_f1, f2)) -> skip f2
| Some (`Forall (x, GTty xty, f)) -> ((x, xty), f)
| _ -> noelim ()
in
let ((x, _xty), ax) = skip ax in
let fpf = f_local pf pfty in
let ptnpos = FPosition.select_form hyps None fpf concl in
let (_xabs, body) = FPosition.topattern ~x:x ptnpos concl in
let rec skipmatch ax body sk =
match TTC.destruct_product hyps ax, TTC.destruct_product hyps body with
| Some (`Imp (i1, f1)), Some (`Imp (i2, f2)) ->
if EcReduction.is_alpha_eq hyps i1 i2
then skipmatch f1 f2 (sk+1)
else sk
| _ -> sk
in
let sk = skipmatch ax body 0 in
t_seqs
[t_elimT_form (fst (PT.concretize pt)) ~sk fpf;
t_or
(t_clear pf)
(t_seq (t_generalize_hyp pf) (t_clear pf));
t_simplify_with_info EcReduction.beta_red]
tc
let process_view1 pe tc =
let module E = struct
exception NoInstance
exception NoTopAssumption
end in
let destruct hyps fp =
let doit fp =
match EcFol.sform_of_form fp with
| SFquant (Lforall, (x, t), lazy f) -> `Forall (x, t, f)
| SFimp (f1, f2) -> `Imp (f1, f2)
| SFiff (f1, f2) -> `Iff (f1, f2)
| _ -> raise EcProofTyping.NoMatch
in
EcProofTyping.lazy_destruct hyps doit fp
in
let rec instantiate fp ids pte =
let hyps = pte.PT.ptev_env.PT.pte_hy in
match destruct hyps pte.PT.ptev_ax with
| None -> raise E.NoInstance
| Some (`Forall (x, xty, _)) ->
instantiate fp ((x, xty) :: ids) (PT.apply_pterm_to_hole pte)
| Some (`Imp (f1, f2)) -> begin
try
PT.pf_form_match ~mode:fmdelta pte.PT.ptev_env ~ptn:f1 fp;
(pte, ids, f2, `None)
with MatchFailure -> raise E.NoInstance
end
| Some (`Iff (f1, f2)) -> begin
try
PT.pf_form_match ~mode:fmdelta pte.PT.ptev_env ~ptn:f1 fp;
(pte, ids, f2, `IffLR (f1, f2))
with MatchFailure -> try
PT.pf_form_match ~mode:fmdelta pte.PT.ptev_env ~ptn:f2 fp;
(pte, ids, f1, `IffRL (f1, f2))
with MatchFailure ->
raise E.NoInstance
end
in
try
match TTC.destruct_product (tc1_hyps tc) (FApi.tc1_goal tc) with
| None -> raise E.NoTopAssumption
| Some (`Forall _) ->
process_elimT pe tc
| Some (`Imp (f1, _)) when pe.fp_head = FPCut None ->
let hyps = FApi.tc1_hyps tc in
let hid = LDecl.fresh_id hyps "h" in
let hqs = mk_loc _dummy ([], EcIdent.name hid) in
let pe = { pe with fp_head = FPNamed (hqs, None) } in
t_intros_i_seq ~clear:true [hid]
(fun tc ->
let pe = PT.tc1_process_full_pterm tc pe in
let regen =
if PT.can_concretize pe.PT.ptev_env then [] else
snd (List.fold_left_map (fun f1 arg ->
let pre, f1 =
match oget (TTC.destruct_product (tc1_hyps tc) f1) with
| `Imp (_, f1) -> (None, f1)
| `Forall (x, xty, f1) ->
let aout =
match xty with GTty ty -> Some (x, ty) | _ -> None
in (aout, f1)
in
let module E = struct exception Bailout end in
try
let v =
match arg with
| PAFormula { f_node = Flocal x } ->
let meta =
let env = !(pe.PT.ptev_env.pte_ev) in
MEV.mem x `Form env && not (MEV.isset x `Form env) in
if not meta then raise E.Bailout;
let y, yty =
let CPTEnv subst = PT.concretize_env pe.PT.ptev_env in
snd_map subst.fs_ty (oget pre) in
let fy = EcIdent.fresh y in
pe.PT.ptev_env.pte_ev := MEV.set
x (`Form (f_local fy yty)) !(pe.PT.ptev_env.pte_ev);
(fy, yty)
| _ ->
raise E.Bailout
in (f1, Some v)
with E.Bailout -> (f1, None)
) f1 pe.PT.ptev_pt.pt_args)
in
let regen = List.pmap (fun x -> x) regen in
let bds = List.map (fun (x, ty) -> (x, GTty ty)) regen in
if not (PT.can_concretize pe.PT.ptev_env) then
tc_error !!tc "cannot infer all placeholders";
let pt, ax = snd_map (f_forall bds) (PT.concretize pe) in
t_first (fun subtc ->
let regen = List.fst regen in
let ttcut tc =
t_onall
(EcLowGoal.t_generalize_hyps ~clear:`Yes regen)
(EcLowGoal.t_apply pt tc) in
t_intros_i_seq regen ttcut subtc
) (t_cut ax tc)
) tc
| Some (`Imp (f1, _)) ->
let top = LDecl.fresh_id (tc1_hyps tc) "h" in
let tc = t_intros_i_1 [top] tc in
let hyps = tc1_hyps tc in
let pte = PT.tc1_process_full_pterm tc pe in
let inargs = List.length pte.PT.ptev_pt.pt_args in
let (pte, ids, cutf, view) = instantiate f1 [] pte in
let evm = !(pte.PT.ptev_env.PT.pte_ev) in
let args = List.drop inargs pte.PT.ptev_pt.pt_args in
let args = List.combine (List.rev ids) args in
let ids =
let for1 ((_, ty) as idty, arg) =
match ty, arg with
| GTty _, PAFormula { f_node = Flocal x } when MEV.mem x `Form evm ->
if MEV.isset x `Form evm then None else Some (x, idty)
| GTmem _, PAMemory x when MEV.mem x `Mem evm ->
if MEV.isset x `Mem evm then None else Some (x, idty)
| _, _ -> assert false
in List.pmap for1 args
in
let cutf =
let ptenv = PT.copy pte.PT.ptev_env in
let for1 evm (x, idty) =
match idty with
| id, GTty ty -> evm := MEV.set x (`Form (f_local id ty)) !evm
| id, GTmem _ -> evm := MEV.set x (`Mem id) !evm
| _ , GTmodty _ -> assert false
in
List.iter (for1 ptenv.PT.pte_ev) ids;
if not (PT.can_concretize ptenv) then
tc_error !!tc "cannot infer all type variables";
PT.concretize_e_form
(PT.concretize_env ptenv)
(f_forall (List.map snd ids) cutf)
in
let discharge tc =
let intros = List.map (EcIdent.name |- fst |- snd) ids in
let intros = LDecl.fresh_ids hyps intros in
let for1 evm (x, idty) id =
match idty with
| _, GTty ty -> evm := MEV.set x (`Form (f_local id ty)) !evm
| _, GTmem _ -> evm := MEV.set x (`Mem id) !evm
| _, GTmodty _ -> assert false
in
let tc = EcLowGoal.t_intros_i_1 intros tc in
List.iter2 (for1 pte.PT.ptev_env.PT.pte_ev) ids intros;
let pte =
match view with
| `None -> pte
| `IffLR (f1, f2) ->
let vpte = PT.pt_of_global_r pte.PT.ptev_env LG.p_iff_lr [] in
let vpte = PT.apply_pterm_to_arg_r vpte (PVAFormula f1) in
let vpte = PT.apply_pterm_to_arg_r vpte (PVAFormula f2) in
let vpte = PT.apply_pterm_to_arg_r vpte (PVASub pte) in
vpte
| `IffRL (f1, f2) ->
let vpte = PT.pt_of_global_r pte.PT.ptev_env LG.p_iff_rl [] in
let vpte = PT.apply_pterm_to_arg_r vpte (PVAFormula f1) in
let vpte = PT.apply_pterm_to_arg_r vpte (PVAFormula f2) in
let vpte = PT.apply_pterm_to_arg_r vpte (PVASub pte) in
vpte
in
let pt = fst (PT.concretize (PT.apply_pterm_to_hole pte)) in
FApi.t_seq
(EcLowGoal.t_apply pt)
(EcLowGoal.t_apply_hyp top)
tc
in
FApi.t_internal
(FApi.t_seqsub (EcLowGoal.t_cut cutf)
[EcLowGoal.t_close ~who:"view" discharge;
EcLowGoal.t_clear top])
tc
with
| E.NoInstance ->
tc_error !!tc "cannot apply view"
| E.NoTopAssumption ->
tc_error !!tc "no top assumption"
let process_view pes tc =
let views = List.map (t_last |- process_view1) pes in
List.fold_left (fun tc tt -> tt tc) (FApi.tcenv_of_tcenv1 tc) views
module IntroState : sig
type state
type action = [ `Revert | `Dup | `Clear ]
val create : unit -> state
val push : ?name:symbol -> action -> EcIdent.t -> state -> unit
val listing : state -> ([`Gen of genclear | `Clear] * EcIdent.t) list
val naming : state -> (EcIdent.t -> symbol option)
end = struct
type state = {
mutable torev : ([`Gen of genclear | `Clear] * EcIdent.t) list;
mutable naming : symbol option Mid.t;
}
and action = [ `Revert | `Dup | `Clear ]
let create () =
{ torev = []; naming = Mid.empty; }
let push ?name action id st =
let map =
Mid.change (function
| None -> Some name
| Some _ -> assert false)
id st.naming
and action =
match action with
| `Revert -> `Gen `TryClear
| `Dup -> `Gen `NoClear
| `Clear -> `Clear
in
st.torev <- (action, id) :: st.torev;
st.naming <- map
let listing (st : state) =
List.rev st.torev
let naming (st : state) (x : EcIdent.t) =
Mid.find_opt x st.naming |> odfl None
end
exception IntroCollect of [
`InternalBreak
]
exception CollectBreak
exception CollectCore of ipcore located
let rec process_mintros_1 ?(cf = true) ttenv pis gs =
let module ST = IntroState in
let mk_intro ids (hyps, form) =
let (_, torev), ids =
let rec compile (((hyps, form), torev) as acc) newids ids =
match ids with [] -> (acc, newids) | s :: ids ->
let rec destruct fp =
match EcFol.sform_of_form fp with
| SFquant (Lforall, (x, _) , lazy fp) ->
let name = EcIdent.name x in (name, Some name, `Named, fp)
| SFlet (LSymbol (x, _), _, fp) ->
let name = EcIdent.name x in (name, Some name, `Named, fp)
| SFimp (_, fp) ->
("H", None, `Hyp, fp)
| _ -> begin
match EcReduction.h_red_opt EcReduction.full_red hyps fp with
| None -> ("_", None, `None, f_true)
| Some f -> destruct f
end
in
let name, revname, kind, form = destruct form in
let revertid =
if ttenv.tt_oldip then
match unloc s with
| `Revert -> Some (Some false, EcIdent.create "_")
| `Clear -> Some (None , EcIdent.create "_")
| `Named s -> Some (None , EcIdent.create s)
| `Anonymous a ->
if (a = Some None && kind = `None) || a = Some (Some 0)
then None
else Some (None, LDecl.fresh_id hyps name)
else
match unloc s with
| `Revert -> Some (Some false, EcIdent.create "_")
| `Clear -> Some (Some true , EcIdent.create "_")
| `Named s -> Some (None , EcIdent.create s)
| `Anonymous a ->
match a, kind with
| Some None, `None ->
None
| (Some (Some 0), _) ->
None
| _, `Named ->
Some (None, LDecl.fresh_id hyps ("`" ^ name))
| _, _ ->
Some (None, LDecl.fresh_id hyps "_")
in
match revertid with
| Some (revert, id) ->
let id = mk_loc s.pl_loc id in
let hyps = LDecl.add_local id.pl_desc (LD_var (tbool, None)) hyps in
let revert = revert |> omap (fun b -> if b then `Clear else `Revert) in
let torev = revert
|> omap (fun b -> (b, unloc id, revname) :: torev)
|> odfl torev
in
let newids = Tagged (unloc id, Some id.pl_loc) :: newids in
let ((hyps, form), torev), newids =
match unloc s with
| `Anonymous (Some None) when kind <> `None ->
compile ((hyps, form), torev) newids [s]
| `Anonymous (Some (Some i)) when 1 < i ->
let s = mk_loc (loc s) (`Anonymous (Some (Some (i-1)))) in
compile ((hyps, form), torev) newids [s]
| _ -> ((hyps, form), torev), newids
in compile ((hyps, form), torev) newids ids
| None -> compile ((hyps, form), torev) newids ids
in snd_map List.rev (compile ((hyps, form), []) [] ids)
in (List.rev torev, ids)
in
let rec collect intl acc core pis =
let maybe_core () =
let loc = EcLocation.mergeall (List.map loc core) in
match core with
| [] -> acc
| _ -> mk_loc loc (`Core (List.rev core)) :: acc
in
match pis with
| [] -> (maybe_core (), [])
| { pl_loc = ploc } as pi :: pis ->
try
let ip =
match unloc pi with
| IPBreak ->
if intl then raise (IntroCollect `InternalBreak);
raise CollectBreak
| IPCore x -> raise (CollectCore (mk_loc (loc pi) x))
| IPDup -> `Dup
| IPDone x -> `Done x
| IPSmt x -> `Smt x
| IPClear x -> `Clear x
| IPRw x -> `Rw x
| IPDelta x -> `Delta x
| IPView x -> `View x
| IPSubst x -> `Subst x
| IPSimplify x -> `Simpl x
| IPCrush x -> `Crush x
| IPCase (mode, x) ->
let subcollect = List.rev -| fst -| collect true [] [] in
`Case (mode, List.map subcollect x)
| IPSubstTop x -> `SubstTop x
in collect intl (mk_loc ploc ip :: maybe_core ()) [] pis
with
| CollectBreak -> (maybe_core (), pis)
| CollectCore x -> collect intl acc (x :: core) pis
in
let collect pis = collect false [] [] pis in
let rec intro1_core (st : ST.state) ids (tc : tcenv1) =
let torev, ids = mk_intro ids (FApi.tc1_flat tc) in
List.iter (fun (act, id, name) -> ST.push ?name act id st) torev;
t_intros ids tc
and intro1_dup (_ : ST.state) (tc : tcenv1) =
try
let pt = PT.pt_of_uglobal !!tc (FApi.tc1_hyps tc) LG.p_ip_dup in
EcLowGoal.Apply.t_apply_bwd_r ~mode:fmrigid ~canview:false pt tc
with EcLowGoal.Apply.NoInstance _ ->
tc_error !!tc "no top-assumption to duplicate"
and intro1_done (_ : ST.state) simplify (tc : tcenv1) =
let t =
match simplify with
| Some x ->
t_seq (t_simplify_lg ~delta:false (ttenv, x)) process_trivial
| None -> process_trivial
in t tc
and intro1_smt (_ : ST.state) ((dn, pi) : _ * pprover_infos) (tc : tcenv1) =
if dn then
t_or process_done (process_smt ttenv pi) tc
else process_smt ttenv pi tc
and intro1_simplify (_ : ST.state) logic tc =
t_simplify_lg ~delta:false (ttenv, logic) tc
and intro1_clear (_ : ST.state) xs tc =
process_clear xs tc
and intro1_case (st : ST.state) nointro pis gs =
let onsub gs =
if List.is_empty pis then gs else begin
if FApi.tc_count gs <> List.length pis then
tc_error !$gs
"not the right number of intro-patterns (got %d, expecting %d)"
(List.length pis) (FApi.tc_count gs);
t_sub (List.map (dointro1 st false) pis) gs
end
in
let tc = t_ors [t_elimT_ind `Case; t_elim; t_elim_prind `Case] in
let tc =
fun g ->
try tc g
with InvalidGoalShape ->
tc_error !!g "invalid intro-pattern: nothing to eliminate"
in
if nointro && not cf then onsub gs else begin
match pis with
| [] -> t_onall tc gs
| _ -> t_onall (fun gs -> onsub (tc gs)) gs
end
and intro1_full_case (st : ST.state)
((prind, delta), withor, (cnt : icasemode_full option)) pis tc
=
let cnt = cnt |> odfl (`AtMost 1) in
let red = if delta then `Full else `NoDelta in
let t_case =
let t_and, t_or =
if prind then
((fun tc -> fst_map List.singleton (t_elim_iso_and ~reduce:red tc)),
(fun tc -> t_elim_iso_or ~reduce:red tc))
else
((fun tc -> ([2] , t_elim_and ~reduce:red tc)),
(fun tc -> ([1; 1], t_elim_or ~reduce:red tc))) in
let ts = if withor then [t_and; t_or] else [t_and] in
fun tc -> FApi.t_or_map ts tc
in
let onsub gs =
if List.is_empty pis then gs else begin
if FApi.tc_count gs <> List.length pis then
tc_error !$gs
"not the right number of intro-patterns (got %d, expecting %d)"
(List.length pis) (FApi.tc_count gs);
t_sub (List.map (dointro1 st false) pis) gs
end
in
let doit tc =
let rec aux imax tc =
if imax = Some 0 then t_id tc else
try
let ntop, tc = t_case tc in
FApi.t_sublasts
(List.map (fun i tc -> aux (omap ((+) (i-1)) imax) tc) ntop)
tc
with InvalidGoalShape ->
try
tc |> EcLowGoal.t_intro_sx_seq
`Fresh
(fun id ->
t_seq
(aux (omap ((+) (-1)) imax))
(t_generalize_hyps ~clear:`Yes [id]))
with
| EcCoreGoal.TcError _ when EcUtils.is_some imax ->
tc_error !!tc "not enough top-assumptions"
| EcCoreGoal.TcError _ ->
t_id tc
in
match cnt with
| `AtMost cnt -> aux (Some (max 1 cnt)) tc
| `AsMuch -> aux None tc
in
if List.is_empty pis then doit tc else onsub (doit tc)
and intro1_rw (_ : ST.state) (o, s) tc =
let h = EcIdent.create "_" in
let rwt tc =
let pt = PT.pt_of_hyp !!tc (FApi.tc1_hyps tc) h in
process_rewrite1_core ~close:false (s, None, o) pt tc
in t_seqs [t_intros_i [h]; rwt; t_clear h] tc
and intro1_unfold (_ : ST.state) (s, o) p tc =
process_delta ~und_delta:ttenv.tt_und_delta (s, o, p) tc
and intro1_view (_ : ST.state) pe tc =
process_view1 pe tc
and intro1_subst (_ : ST.state) d (tc : tcenv1) =
try
t_intros_i_seq ~clear:true [EcIdent.create "_"]
(EcLowGoal.t_subst ~clear:true ~tside:(d :> tside))
tc
with InvalidGoalShape ->
tc_error !!tc "nothing to substitute"
and intro1_subst_top (_ : ST.state) (omax, osd) (tc : tcenv1) =
let t_subst eqid =
let sk1 = { empty_subst_kind with sk_local = true ; } in
let sk2 = { full_subst_kind with sk_local = false; } in
let side = `All osd in
FApi.t_or
(t_subst ~tside:side ~kind:sk1 ~eqid)
(t_subst ~tside:side ~kind:sk2 ~eqid)
in
let togen = ref [] in
let rec doit i tc =
match omax with Some max when i >= max -> tcenv_of_tcenv1 tc | _ ->
try
let id = EcIdent.create "_" in
let tc = EcLowGoal.t_intros_i_1 [id] tc in
FApi.t_switch (t_subst id) ~ifok:(doit (i+1))
~iffail:(fun tc -> togen := id :: !togen; doit (i+1) tc)
tc
with EcCoreGoal.TcError _ ->
if is_some omax then
tc_error !!tc "not enough top-assumptions";
tcenv_of_tcenv1 tc in
let tc = doit 0 tc in
t_generalize_hyps
~clear:`Yes ~missing:true
(List.rev !togen) (FApi.as_tcenv1 tc)
and intro1_crush (_st : ST.state) (d : crushmode) (gs : tcenv1) =
let delta, tsolve = process_crushmode d in
FApi.t_or
(EcPhlConseq.t_conseqauto ~delta ?tsolve)
(EcLowGoal.t_crush ~delta ?tsolve)
gs
and dointro (st : ST.state) nointro pis (gs : tcenv) =
match pis with [] -> gs | { pl_desc = pi; pl_loc = ploc } :: pis ->
let nointro, gs =
let rl x = EcCoreGoal.reloc ploc x in
match pi with
| `Core ids ->
(false, rl (t_onall (intro1_core st ids)) gs)
| `Dup ->
(false, rl (t_onall (intro1_dup st)) gs)
| `Done b ->
(nointro, rl (t_onall (intro1_done st b)) gs)
| `Smt pi ->
(nointro, rl (t_onall (intro1_smt st pi)) gs)
| `Simpl b ->
(nointro, rl (t_onall (intro1_simplify st b)) gs)
| `Clear xs ->
(nointro, rl (t_onall (intro1_clear st xs)) gs)
| `Case (`One, pis) ->
(false, rl (intro1_case st nointro pis) gs)
| `Case (`Full x, pis) ->
(false, rl (t_onall (intro1_full_case st x pis)) gs)
| `Rw (o, s, None) ->
(false, rl (t_onall (intro1_rw st (o, s))) gs)
| `Rw (o, s, Some i) ->
(false, rl (t_onall (t_do `All i (intro1_rw st (o, s)))) gs)
| `Delta ((o, s), p) ->
(nointro, rl (t_onall (intro1_unfold st (o, s) p)) gs)
| `View pe ->
(false, rl (t_onall (intro1_view st pe)) gs)
| `Subst (d, None) ->
(false, rl (t_onall (intro1_subst st d)) gs)
| `Subst (d, Some i) ->
(false, rl (t_onall (t_do `All i (intro1_subst st d))) gs)
| `SubstTop d ->
(false, rl (t_onall (intro1_subst_top st d)) gs)
| `Crush d ->
(false, rl (t_onall (intro1_crush st d)) gs)
in dointro st nointro pis gs
and dointro1 st nointro pis tc =
dointro st nointro pis (FApi.tcenv_of_tcenv1 tc) in
try
let st = ST.create () in
let ip, pis = collect pis in
let gs = dointro st true (List.rev ip) gs in
let gs =
let ls = ST.listing st in
let gn = List.pmap (function (`Gen x, y) -> Some (x, y) | _ -> None) ls in
let cl = List.pmap (function (`Clear, y) -> Some y | _ -> None) ls in
t_onall (fun tc ->
t_generalize_hyps_x
~missing:true ~naming:(ST.naming st)
gn tc)
(t_onall (t_clears cl) gs)
in
if List.is_empty pis then gs else
gs |> t_onall (fun tc ->
process_mintros_1 ~cf:true ttenv pis (FApi.tcenv_of_tcenv1 tc))
with IntroCollect e -> begin
match e with
| `InternalBreak ->
tc_error !$gs "cannot use internal break in intro-patterns"
end
let process_intros_1 ?cf ttenv pis tc =
process_mintros_1 ?cf ttenv pis (FApi.tcenv_of_tcenv1 tc)
let rec process_mintros ?cf ttenv pis tc =
match pis with [] -> tc | pi :: pis ->
let tc = process_mintros_1 ?cf ttenv pi tc in
process_mintros ~cf:false ttenv pis tc
let process_intros ?cf ttenv pis tc =
process_mintros ?cf ttenv pis (FApi.tcenv_of_tcenv1 tc)
let process_generalize1 ?(doeq = false) pattern (tc : tcenv1) =
let env, hyps, concl = FApi.tc1_eflat tc in
let onresolved ?(tryclear = true) pattern =
let clear = if tryclear then `Yes else `No in
match pattern with
| `Form (occ, pf) -> begin
match pf.pl_desc with
| PFident ({pl_desc = ([], s)}, None)
when not doeq && is_none occ && LDecl.has_name s hyps
->
let id = fst (LDecl.by_name s hyps) in
t_generalize_hyp ~clear id tc
| _ ->
let (ptenv, p) =
let (ps, ue), p = TTC.tc1_process_pattern tc pf in
let ev = MEV.of_idents (Mid.keys ps) `Form in
(ptenv !!tc hyps (ue, ev), p)
in
(try ignore (PT.pf_find_occurence ptenv ~ptn:p concl)
with PT.FindOccFailure _ -> tc_error !!tc "cannot find an occurence");
let p = PT.concretize_form ptenv p in
let occ = norm_rwocc occ in
let cpos =
try FPosition.select_form ~xconv:`AlphaEq hyps occ p concl
with InvalidOccurence -> tacuerror "invalid occurence selector"
in
let name =
match EcParsetree.pf_ident pf with
| None ->
EcIdent.create "x"
| Some x when EcIo.is_sym_ident x ->
EcIdent.create x
| Some _ ->
EcIdent.create (EcTypes.symbol_of_ty p.f_ty)
in
let name, newconcl = FPosition.topattern ~x:name cpos concl in
let newconcl =
if doeq then
if EcReduction.EqTest.for_type env p.f_ty tbool then
f_imps [f_iff p (f_local name p.f_ty)] newconcl
else
f_imps [f_eq p (f_local name p.f_ty)] newconcl
else newconcl in
let newconcl = f_forall [(name, GTty p.f_ty)] newconcl in
let pt = { pt_head = PTCut newconcl; pt_args = [PAFormula p]; } in
EcLowGoal.t_apply pt tc
end
| `ProofTerm fp -> begin
match fp.fp_head with
| FPNamed ({ pl_desc = ([], s) }, None)
when LDecl.has_name s hyps && List.is_empty fp.fp_args
->
let id = fst (LDecl.by_name s hyps) in
t_generalize_hyp ~clear id tc
| _ ->
let pt = PT.tc1_process_full_pterm tc fp in
if not (PT.can_concretize pt.PT.ptev_env) then
tc_error !!tc "cannot infer all placeholders";
let pt, ax = PT.concretize pt in
t_cutdef pt ax tc
end
| `LetIn x ->
let id =
let binding =
try Some (LDecl.by_name (unloc x) hyps)
with EcEnv.LDecl.LdeclError _ -> None in
match binding with
| Some (id, LD_var (_, Some _)) -> id
| _ ->
let msg = "symbol must reference let-in" in
tc_error ~loc:(loc x) !!tc "%s" msg
in t_generalize_hyp ~clear ~letin:true id tc
in
match ffpattern_of_genpattern hyps pattern with
| Some ff ->
let tryclear =
match pattern with
| (`Form (None, { pl_desc = PFident _ })) -> true
| _ -> false
in onresolved ~tryclear (`ProofTerm ff)
| None -> onresolved pattern
let process_generalize ?(doeq = false) patterns (tc : tcenv1) =
try
let patterns = List.mapi (fun i p ->
process_generalize1 ~doeq:(doeq && i = 0) p) patterns in
FApi.t_seqs (List.rev patterns) tc
with (EcCoreGoal.ClearError _) as err ->
tc_error_exn !!tc err
let rec process_mgenintros ?cf ttenv pis tc =
match pis with [] -> tc | pi :: pis ->
let tc =
match pi with
| `Ip pi -> process_mintros_1 ?cf ttenv pi tc
| `Gen gn ->
t_onall (
t_seqs [
process_clear gn.pr_clear;
process_generalize gn.pr_genp
]) tc
in process_mgenintros ~cf:false ttenv pis tc
let process_genintros ?cf ttenv pis tc =
process_mgenintros ?cf ttenv pis (FApi.tcenv_of_tcenv1 tc)
let process_move ?doeq views pr (tc : tcenv1) =
t_seqs
[process_clear pr.pr_clear;
process_generalize ?doeq pr.pr_genp;
process_view views]
tc
let process_pose xsym bds o p (tc : tcenv1) =
let (env, hyps, concl) = FApi.tc1_eflat tc in
let o = norm_rwocc o in
let (ptenv, p) =
let ps = ref Mid.empty in
let ue = TTC.unienv_of_hyps hyps in
let (senv, bds) = EcTyping.trans_binding env ue bds in
let p = EcTyping.trans_pattern senv ps ue p in
let ev = MEV.of_idents (Mid.keys !ps) `Form in
(ptenv !!tc hyps (ue, ev),
f_lambda (List.map (snd_map gtty) bds) p)
in
let dopat =
try
ignore (PT.pf_find_occurence ~occmode:PT.om_rigid ptenv ~ptn:p concl);
true
with PT.FindOccFailure _ ->
if not (PT.can_concretize ptenv) then
if not (EcMatching.MEV.filled !(ptenv.PT.pte_ev)) then
tc_error !!tc "cannot find an occurence"
else
tc_error !!tc "%s - %s"
"cannot find an occurence"
"instantiate type variables manually"
else
false
in
let p = PT.concretize_form ptenv p in
let (x, letin) =
match dopat with
| false -> (EcIdent.create (unloc xsym), concl)
| true -> begin
let cpos =
try FPosition.select_form ~xconv:`AlphaEq hyps o p concl
with InvalidOccurence -> tacuerror "invalid occurence selector"
in
FPosition.topattern ~x:(EcIdent.create (unloc xsym)) cpos concl
end
in
let letin = EcFol.f_let1 x p letin in
FApi.t_seq
(t_change letin)
(t_intros [Tagged (x, Some xsym.pl_loc)]) tc
let process_memory (xsym : psymbol) tc =
let x = EcIdent.create (unloc xsym) in
let m = EcMemory.empty_local_mt ~witharg:false in
FApi.t_sub
[
t_trivial;
FApi.t_seqs [
t_elim_exists ~reduce:`None;
t_intros [Tagged (x, Some xsym.pl_loc)];
t_intros_n ~clear:true 1;
]
]
(t_cut (f_exists [x, GTmem m] f_true) tc)
type apply_t = EcParsetree.apply_info
let process_apply ~implicits ((infos, orv) : apply_t * prevert option) tc =
let do_apply tc =
match infos with
| `ApplyIn (pe, tg) ->
process_apply_fwd ~implicits (pe, tg) tc
| `Apply (pe, mode) ->
let for1 tc pe =
t_last (process_apply_bwd ~implicits `Apply pe) tc in
let tc = List.fold_left for1 (tcenv_of_tcenv1 tc) pe in
if mode = `Exact then t_onall process_done tc else tc
| `Alpha pe ->
process_apply_bwd ~implicits `Alpha pe tc
| `ExactType qs ->
process_exacttype qs tc
| `Top mode ->
let tc = process_apply_top tc in
if mode = `Exact then t_onall process_done tc else tc
in
t_seq
(fun tc -> ofdfl
(fun () -> t_id tc)
(omap (fun rv -> process_move [] rv tc) orv))
do_apply tc
let process_subst syms (tc : tcenv1) =
let resolve symp =
let sym = TTC.tc1_process_form_opt tc None symp in
match sym.f_node with
| Flocal id -> `Local id
| Fglob (mp, mem) -> `Glob (mp, mem)
| Fpvar (pv, mem) -> `PVar (pv, mem)
| _ ->
tc_error !!tc ~loc:symp.pl_loc
"this formula is not subject to substitution"
in
match List.map resolve syms with
| [] -> t_repeat t_subst tc
| syms -> FApi.t_seqs (List.map (fun var tc -> t_subst ~var tc) syms) tc
type cut_t = intropattern * pformula * (ptactics located) option
type cutmode = [`Have | `Suff]
let process_cut ?(mode = `Have) engine ttenv ((ip, phi, t) : cut_t) tc =
let phi = TTC.tc1_process_formula tc phi in
let tc = EcLowGoal.t_cut phi tc in
let applytc tc =
t |> ofold (fun t tc ->
let t = mk_loc (loc t) (Pby (Some (unloc t))) in
t_onall (engine t) tc) (FApi.tcenv_of_tcenv1 tc)
in
match mode with
| `Have ->
FApi.t_first applytc
(FApi.t_last (process_intros_1 ttenv ip) tc)
| `Suff ->
FApi.t_rotate `Left 1
(FApi.t_on1 0 t_id ~ttout:applytc
(FApi.t_last (process_intros_1 ttenv ip) tc))
type cutdef_t = intropattern * pcutdef
let process_cutdef ttenv (ip, pt) (tc : tcenv1) =
let pt = {
fp_mode = `Implicit;
fp_head = FPNamed (pt.ptcd_name, pt.ptcd_tys);
fp_args = pt.ptcd_args;
} in
let pt = PT.tc1_process_full_pterm tc pt in
if not (PT.can_concretize pt.ptev_env) then
tc_error !!tc "cannot infer all placeholders";
let pt, ax = PT.concretize pt in
FApi.t_sub
[EcLowGoal.t_apply pt; process_intros_1 ttenv ip]
(t_cut ax tc)
type cutdef_sc_t = intropattern * pcutdef_schema
let process_cutdef_sc ttenv (ip, inst) (tc : tcenv1) =
let pt,sc_i = PT.tc1_process_sc_instantiation tc inst in
FApi.t_sub
[EcLowGoal.t_apply pt; process_intros_1 ttenv ip]
(t_cut sc_i tc)
let process_left (tc : tcenv1) =
try
t_ors [EcLowGoal.t_left; EcLowGoal.t_or_intro_prind `Left] tc
with InvalidGoalShape ->
tc_error !!tc "cannot apply `left` on that goal"
let process_right (tc : tcenv1) =
try
t_ors [EcLowGoal.t_right; EcLowGoal.t_or_intro_prind `Right] tc
with InvalidGoalShape ->
tc_error !!tc "cannot apply `right` on that goal"
let process_split (tc : tcenv1) =
try t_ors [EcLowGoal.t_split; EcLowGoal.t_split_prind] tc
with InvalidGoalShape ->
tc_error !!tc "cannot apply `split` on that goal"
let process_elim (pe, qs) tc =
let doelim tc =
match qs with
| None -> t_or (t_elimT_ind `Ind) t_elim tc
| Some qs ->
let qs = {
fp_mode = `Implicit;
fp_head = FPNamed (qs, None);
fp_args = [];
} in process_elimT qs tc
in
try
FApi.t_last doelim (process_move [] pe tc)
with EcCoreGoal.InvalidGoalShape ->
tc_error !!tc "don't know what to eliminate"
let process_case ?(doeq = false) gp tc =
let module E = struct exception LEMFailure end in
try
match gp.pr_rev with
| { pr_genp = [`Form (None, pf)] }
when List.is_empty gp.pr_view ->
let env = FApi.tc1_env tc in
let f =
try TTC.process_formula (FApi.tc1_hyps tc) pf
with TT.TyError _ | LocError (_, TT.TyError _) -> raise E.LEMFailure
in
if not (EcReduction.EqTest.for_type env f.f_ty tbool) then
raise E.LEMFailure;
begin
match (fst (destr_app f)).f_node with
| Fop (p, _) when EcEnv.Op.is_prind env p ->
raise E.LEMFailure
| _ -> ()
end;
t_seqs
[process_clear gp.pr_rev.pr_clear; t_case f;
t_simplify_with_info EcReduction.betaiota_red]
tc
| _ -> raise E.LEMFailure
with E.LEMFailure ->
try
FApi.t_last
(t_ors [t_elimT_ind `Case; t_elim; t_elim_prind `Case])
(process_move ~doeq gp.pr_view gp.pr_rev tc)
with EcCoreGoal.InvalidGoalShape ->
tc_error !!tc "don't known what to eliminate"
let process_exists args (tc : tcenv1) =
let hyps = FApi.tc1_hyps tc in
let pte = (TTC.unienv_of_hyps hyps, EcMatching.MEV.empty) in
let pte = PT.ptenv !!tc (FApi.tc1_hyps tc) pte in
let for1 concl arg =
match TTC.destruct_exists hyps concl with
| None -> tc_error !!tc "not an existential"
| Some (`Exists (x, xty, f)) ->
let arg =
match xty with
| GTty _ -> trans_pterm_arg_value pte arg
| GTmem _ -> trans_pterm_arg_mem pte arg
| GTmodty _ -> trans_pterm_arg_mod pte arg
in
PT.check_pterm_arg pte (x, xty) f arg.ptea_arg
in
let _concl, args = List.map_fold for1 (FApi.tc1_goal tc) args in
if not (PT.can_concretize pte) then
tc_error !!tc "cannot infer all placeholders";
let pte = PT.concretize_env pte in
let args = List.map (PT.concretize_e_arg pte) args in
EcLowGoal.t_exists_intro_s args tc
let process_congr tc =
let (env, hyps, concl) = FApi.tc1_eflat tc in
if not (EcFol.is_eq_or_iff concl) then
tc_error !!tc "goal must be an equality or an equivalence";
let ((f1, f2), iseq) =
if EcFol.is_eq concl
then (EcFol.destr_eq concl, true )
else (EcFol.destr_iff concl, false) in
let t_ensure_eq =
if iseq then t_id
else
(fun tc ->
let hyps = FApi.tc1_hyps tc in
EcLowGoal.Apply.t_apply_bwd_r
(PT.pt_of_uglobal !!tc hyps LG.p_eq_iff) tc) in
let t_subgoal = t_ors [t_reflex ~mode:`Alpha; t_assumption `Alpha; t_id] in
match f1.f_node, f2.f_node with
| _, _ when EcReduction.is_alpha_eq hyps f1 f2 ->
FApi.t_seq t_ensure_eq EcLowGoal.t_reflex tc
| Fapp (o1, a1), Fapp (o2, a2)
when EcReduction.is_alpha_eq hyps o1 o2
&& List.length a1 = List.length a2 ->
let tt1 = t_congr (o1, o2) ((List.combine a1 a2), f1.f_ty) in
FApi.t_seqs [t_ensure_eq; tt1; t_subgoal] tc
| Fif (_, { f_ty = cty }, _), Fif _ ->
let tt0 tc =
let hyps = FApi.tc1_hyps tc in
EcLowGoal.Apply.t_apply_bwd_r
(PT.pt_of_global !!tc hyps LG.p_if_congr [cty]) tc
in FApi.t_seqs [tt0; t_subgoal] tc
| Ftuple _, Ftuple _ when iseq ->
FApi.t_seqs [t_split; t_subgoal] tc
| Fproj (f1, i1), Fproj (f2, i2)
when i1 = i2 && EcReduction.EqTest.for_type env f1.f_ty f2.f_ty
-> EcCoreGoal.FApi.xmutate1 tc `CongrProj [f_eq f1 f2]
| _, _ -> tacuerror "not a congruence"
let process_wlog ids wlog tc =
let hyps, _ = FApi.tc1_flat tc in
let toid s =
if not (LDecl.has_name (unloc s) hyps) then
tc_lookup_error !!tc ~loc:s.pl_loc `Local ([], unloc s);
fst (LDecl.by_name (unloc s) hyps) in
let ids = List.map toid ids in
let gen =
let wlog = TTC.tc1_process_formula tc wlog in
let tc = t_rotate `Left 1 (EcLowGoal.t_cut wlog tc) in
let tc = t_first (t_generalize_hyps ~clear:`Yes ids) tc in
FApi.tc_goal tc
in
t_rotate `Left 1
(t_first
(t_seq (t_clears ids) (t_intros_i ids))
(t_cut gen tc))
let process_wlog_suff ids wlog tc =
let hyps, _ = FApi.tc1_flat tc in
let toid s =
if not (LDecl.has_name (unloc s) hyps) then
tc_lookup_error !!tc ~loc:s.pl_loc `Local ([], unloc s);
fst (LDecl.by_name (unloc s) hyps) in
let ids = List.map toid ids in
let wlog =
let wlog = TTC.tc1_process_formula tc wlog in
let tc = t_first (t_generalize_hyps ~clear:`Yes ids) (t_cut wlog tc) in
FApi.tc_goal tc in
t_rotate `Left 1
(t_first
(t_seq (t_clears ids) (t_intros_i ids))
(t_cut wlog tc))
let process_wlog ~suff ids wlog tc =
if suff
then process_wlog_suff ids wlog tc
else process_wlog ids wlog tc
let process_genhave (ttenv : ttenv) ((name, ip, ids, gen) : pgenhave) tc =
let hyps, _ = FApi.tc1_flat tc in
let toid s =
if not (LDecl.has_name (unloc s) hyps) then
tc_lookup_error !!tc ~loc:s.pl_loc `Local ([], unloc s);
fst (LDecl.by_name (unloc s) hyps) in
let ids = List.map toid ids in
let gen =
let gen = TTC.tc1_process_formula tc gen in
let tc = EcLowGoal.t_cut gen tc in
let tc = t_first (t_generalize_hyps ~clear:`Yes ids) tc in
FApi.tc_goal tc in
let doip tc =
let genid = EcIdent.create (unloc name) in
let tc = t_intros_i_1 [genid] tc in
match ip with
| None ->
t_id tc
| Some ip ->
let pt = EcProofTerm.pt_of_hyp !!tc (FApi.tc1_hyps tc) genid in
let pt = List.fold_left EcProofTerm.apply_pterm_to_local pt ids in
let tc = t_cutdef pt.ptev_pt pt.ptev_ax tc in
process_mintros ttenv [ip] tc in
t_sub [
t_seq (t_clears ids) (t_intros_i ids);
doip
] (t_cut gen tc)
|
8b11e4d6abaa455b8c56700c8fe12f965b2a8249e6416be0bef21ff4edf709de | ocaml-omake/omake | omake_ir_free_vars.ml | (*
* Compute the free variables of an expression.
* NOTE: this is a little sloppy.
* 1. The language is dynamically scoped;
* we don't catch variables not mentioned statically
* 2. We take the presence of a definition anywhere
* as an indication that the variable is not free.
*)
(*
* Tables of free variables.
*)
type free_vars = Omake_ir_util.VarInfoSet.t
let free_vars_empty = Omake_ir_util.VarInfoSet.empty
(*
* Free variable operations.
*)
let free_vars_add = Omake_ir_util.VarInfoSet.add
let free_vars_remove = Omake_ir_util.VarInfoSet.remove
let free_vars_remove_param_list fv params =
List.fold_left Omake_ir_util.VarInfoSet.remove fv params
let free_vars_remove_opt_param_list fv keywords =
List.fold_left (fun fv (_, v, _) -> Omake_ir_util.VarInfoSet.remove fv v) fv keywords
* Union of two free variable sets .
* Union of two free variable sets.
*)
let free_vars_union fv1 fv2 =
Omake_ir_util.VarInfoSet.fold Omake_ir_util.VarInfoSet.add fv1 fv2
(*
* Free vars of the export.
*)
let free_vars_export_info fv info =
match info with
Omake_ir.ExportNone
| Omake_ir.ExportAll ->
fv
| Omake_ir.ExportList items ->
List.fold_left (fun fv item ->
match item with
Omake_ir.ExportRules
| ExportPhonies ->
fv
| ExportVar v ->
Omake_ir_util.VarInfoSet.add fv v) fv items
(*
* Free vars in optional args.
*)
let rec free_vars_opt_params fv opt_params =
match opt_params with
(_, _, Some s) :: opt_params ->
free_vars_opt_params (free_vars_string_exp fv s) opt_params
| (_, _, None) :: opt_params ->
free_vars_opt_params fv opt_params
| [] ->
fv
(*
* Calculate free vars.
* NOTE: this only calculates the static free variables.
* Since the language is dynamically scoped, this will miss
* the dynamic free variables.
*)
and free_vars_string_exp fv s =
match s with
|Omake_ir.NoneString _
| IntString _
| FloatString _
| WhiteString _
| ConstString _
| ThisString _
| KeyApplyString _
| VarString _ ->
fv
| FunString (_, opt_params, vars, s, export) ->
let fv_body = free_vars_export_info free_vars_empty export in
let fv_body = free_vars_exp_list fv_body s in
let fv_body = free_vars_remove_param_list fv_body vars in
let fv_body = free_vars_remove_opt_param_list fv_body opt_params in
let fv = free_vars_union fv fv_body in
free_vars_opt_params fv opt_params
| ApplyString (_, v, args, kargs)
| MethodApplyString (_, v, _, args, kargs) ->
let fv = free_vars_string_exp_list fv args in
let fv = free_vars_keyword_exp_list fv kargs in
free_vars_add fv v
| SuperApplyString (_, _, _, args, kargs) ->
let fv = free_vars_string_exp_list fv args in
let fv = free_vars_keyword_exp_list fv kargs in
fv
| SequenceString (_, sl)
| ArrayString (_, sl)
| QuoteString (_, sl)
| QuoteStringString (_, _, sl) ->
free_vars_string_exp_list fv sl
| ArrayOfString (_, s)
| LazyString (_, s) ->
free_vars_string_exp fv s
| ObjectString (_, e, export)
| BodyString (_, e, export)
| ExpString (_, e, export) ->
free_vars_exp_list (free_vars_export_info fv export) e
| CasesString (_loc, cases) ->
free_vars_cases fv cases
| LetVarString (_, v, e1, _e2) ->
let fv = free_vars_string_exp fv e1 in
let fv = free_vars_remove fv v in
free_vars_string_exp fv e1
and free_vars_string_exp_list fv sl =
match sl with
s :: sl ->
free_vars_string_exp_list (free_vars_string_exp fv s) sl
| [] ->
fv
and free_vars_keyword_exp_list fv sl =
match sl with
(_, s) :: sl ->
free_vars_keyword_exp_list (free_vars_string_exp fv s) sl
| [] ->
fv
and free_vars_cases fv cases =
match cases with
(_, s, e, export) :: cases ->
free_vars_cases (free_vars_string_exp (free_vars_exp_list (free_vars_export_info fv export) e) s) cases
| [] ->
fv
and free_vars_exp_list fv el =
match el with
e :: el ->
free_vars_exp (free_vars_exp_list fv el) e
| [] ->
fv
and free_vars_exp fv e =
match e with
LetVarExp (_, v, _, _, s) ->
let fv = free_vars_remove fv v in
free_vars_string_exp fv s
| LetFunExp (_, v, _, _, opt_params, vars, el, export) ->
let fv_body = free_vars_export_info free_vars_empty export in
let fv_body = free_vars_exp_list fv_body el in
let fv_body = free_vars_remove_param_list fv_body vars in
let fv_body = free_vars_remove_opt_param_list fv_body opt_params in
let fv = free_vars_union fv fv_body in
let fv = free_vars_remove fv v in
free_vars_opt_params fv opt_params
| LetObjectExp (_, v, _, s, el, export) ->
let fv = free_vars_export_info fv export in
let fv = free_vars_exp_list fv el in
let fv = free_vars_remove fv v in
let fv = free_vars_string_exp fv s in
fv
| IfExp (_, cases) ->
free_vars_if_cases fv cases
| SequenceExp (_, el) ->
free_vars_exp_list fv el
| SectionExp (_, s, el, export) ->
free_vars_string_exp (free_vars_exp_list (free_vars_export_info fv export) el) s
| StaticExp (_, _, _, el) ->
free_vars_exp_list fv el
| IncludeExp (_, s, sl) ->
free_vars_string_exp (free_vars_string_exp_list fv sl) s
| ApplyExp (_, v, args, kargs)
| MethodApplyExp (_, v, _, args, kargs) ->
free_vars_keyword_exp_list (free_vars_string_exp_list (free_vars_add fv v) args) kargs
| SuperApplyExp (_, _, _, args, kargs) ->
free_vars_keyword_exp_list (free_vars_string_exp_list fv args) kargs
| ReturnBodyExp (_, el, _) ->
free_vars_exp_list fv el
| LetKeyExp (_, _, _, s)
| LetThisExp (_, s)
| ShellExp (_, s)
| StringExp (_, s)
| ReturnExp (_, s, _) ->
free_vars_string_exp fv s
| OpenExp _
| KeyExp _
| ReturnObjectExp _
| ReturnSaveExp _ ->
fv
and free_vars_if_cases fv cases =
match cases with
| (s, e, export) :: cases ->
free_vars_if_cases (free_vars_string_exp (free_vars_exp_list (free_vars_export_info fv export) e) s) cases
| [] ->
fv
(*
* Wrapper.
*)
let free_vars_exp e = free_vars_exp free_vars_empty e
let free_vars_exp_list el = free_vars_exp_list free_vars_empty el
let free_vars_set fv = fv
| null | https://raw.githubusercontent.com/ocaml-omake/omake/08b2a83fb558f6eb6847566cbe1a562230da2b14/src/ir/omake_ir_free_vars.ml | ocaml |
* Compute the free variables of an expression.
* NOTE: this is a little sloppy.
* 1. The language is dynamically scoped;
* we don't catch variables not mentioned statically
* 2. We take the presence of a definition anywhere
* as an indication that the variable is not free.
* Tables of free variables.
* Free variable operations.
* Free vars of the export.
* Free vars in optional args.
* Calculate free vars.
* NOTE: this only calculates the static free variables.
* Since the language is dynamically scoped, this will miss
* the dynamic free variables.
* Wrapper.
|
type free_vars = Omake_ir_util.VarInfoSet.t
let free_vars_empty = Omake_ir_util.VarInfoSet.empty
let free_vars_add = Omake_ir_util.VarInfoSet.add
let free_vars_remove = Omake_ir_util.VarInfoSet.remove
let free_vars_remove_param_list fv params =
List.fold_left Omake_ir_util.VarInfoSet.remove fv params
let free_vars_remove_opt_param_list fv keywords =
List.fold_left (fun fv (_, v, _) -> Omake_ir_util.VarInfoSet.remove fv v) fv keywords
* Union of two free variable sets .
* Union of two free variable sets.
*)
let free_vars_union fv1 fv2 =
Omake_ir_util.VarInfoSet.fold Omake_ir_util.VarInfoSet.add fv1 fv2
let free_vars_export_info fv info =
match info with
Omake_ir.ExportNone
| Omake_ir.ExportAll ->
fv
| Omake_ir.ExportList items ->
List.fold_left (fun fv item ->
match item with
Omake_ir.ExportRules
| ExportPhonies ->
fv
| ExportVar v ->
Omake_ir_util.VarInfoSet.add fv v) fv items
let rec free_vars_opt_params fv opt_params =
match opt_params with
(_, _, Some s) :: opt_params ->
free_vars_opt_params (free_vars_string_exp fv s) opt_params
| (_, _, None) :: opt_params ->
free_vars_opt_params fv opt_params
| [] ->
fv
and free_vars_string_exp fv s =
match s with
|Omake_ir.NoneString _
| IntString _
| FloatString _
| WhiteString _
| ConstString _
| ThisString _
| KeyApplyString _
| VarString _ ->
fv
| FunString (_, opt_params, vars, s, export) ->
let fv_body = free_vars_export_info free_vars_empty export in
let fv_body = free_vars_exp_list fv_body s in
let fv_body = free_vars_remove_param_list fv_body vars in
let fv_body = free_vars_remove_opt_param_list fv_body opt_params in
let fv = free_vars_union fv fv_body in
free_vars_opt_params fv opt_params
| ApplyString (_, v, args, kargs)
| MethodApplyString (_, v, _, args, kargs) ->
let fv = free_vars_string_exp_list fv args in
let fv = free_vars_keyword_exp_list fv kargs in
free_vars_add fv v
| SuperApplyString (_, _, _, args, kargs) ->
let fv = free_vars_string_exp_list fv args in
let fv = free_vars_keyword_exp_list fv kargs in
fv
| SequenceString (_, sl)
| ArrayString (_, sl)
| QuoteString (_, sl)
| QuoteStringString (_, _, sl) ->
free_vars_string_exp_list fv sl
| ArrayOfString (_, s)
| LazyString (_, s) ->
free_vars_string_exp fv s
| ObjectString (_, e, export)
| BodyString (_, e, export)
| ExpString (_, e, export) ->
free_vars_exp_list (free_vars_export_info fv export) e
| CasesString (_loc, cases) ->
free_vars_cases fv cases
| LetVarString (_, v, e1, _e2) ->
let fv = free_vars_string_exp fv e1 in
let fv = free_vars_remove fv v in
free_vars_string_exp fv e1
and free_vars_string_exp_list fv sl =
match sl with
s :: sl ->
free_vars_string_exp_list (free_vars_string_exp fv s) sl
| [] ->
fv
and free_vars_keyword_exp_list fv sl =
match sl with
(_, s) :: sl ->
free_vars_keyword_exp_list (free_vars_string_exp fv s) sl
| [] ->
fv
and free_vars_cases fv cases =
match cases with
(_, s, e, export) :: cases ->
free_vars_cases (free_vars_string_exp (free_vars_exp_list (free_vars_export_info fv export) e) s) cases
| [] ->
fv
and free_vars_exp_list fv el =
match el with
e :: el ->
free_vars_exp (free_vars_exp_list fv el) e
| [] ->
fv
and free_vars_exp fv e =
match e with
LetVarExp (_, v, _, _, s) ->
let fv = free_vars_remove fv v in
free_vars_string_exp fv s
| LetFunExp (_, v, _, _, opt_params, vars, el, export) ->
let fv_body = free_vars_export_info free_vars_empty export in
let fv_body = free_vars_exp_list fv_body el in
let fv_body = free_vars_remove_param_list fv_body vars in
let fv_body = free_vars_remove_opt_param_list fv_body opt_params in
let fv = free_vars_union fv fv_body in
let fv = free_vars_remove fv v in
free_vars_opt_params fv opt_params
| LetObjectExp (_, v, _, s, el, export) ->
let fv = free_vars_export_info fv export in
let fv = free_vars_exp_list fv el in
let fv = free_vars_remove fv v in
let fv = free_vars_string_exp fv s in
fv
| IfExp (_, cases) ->
free_vars_if_cases fv cases
| SequenceExp (_, el) ->
free_vars_exp_list fv el
| SectionExp (_, s, el, export) ->
free_vars_string_exp (free_vars_exp_list (free_vars_export_info fv export) el) s
| StaticExp (_, _, _, el) ->
free_vars_exp_list fv el
| IncludeExp (_, s, sl) ->
free_vars_string_exp (free_vars_string_exp_list fv sl) s
| ApplyExp (_, v, args, kargs)
| MethodApplyExp (_, v, _, args, kargs) ->
free_vars_keyword_exp_list (free_vars_string_exp_list (free_vars_add fv v) args) kargs
| SuperApplyExp (_, _, _, args, kargs) ->
free_vars_keyword_exp_list (free_vars_string_exp_list fv args) kargs
| ReturnBodyExp (_, el, _) ->
free_vars_exp_list fv el
| LetKeyExp (_, _, _, s)
| LetThisExp (_, s)
| ShellExp (_, s)
| StringExp (_, s)
| ReturnExp (_, s, _) ->
free_vars_string_exp fv s
| OpenExp _
| KeyExp _
| ReturnObjectExp _
| ReturnSaveExp _ ->
fv
and free_vars_if_cases fv cases =
match cases with
| (s, e, export) :: cases ->
free_vars_if_cases (free_vars_string_exp (free_vars_exp_list (free_vars_export_info fv export) e) s) cases
| [] ->
fv
let free_vars_exp e = free_vars_exp free_vars_empty e
let free_vars_exp_list el = free_vars_exp_list free_vars_empty el
let free_vars_set fv = fv
|
3f689ce89ca7fc56412b93bd78a639693b213f294099b45162f471c3e1c598df | lspitzner/multistate | Strict.hs | # LANGUAGE CPP #
| The multi - valued version of mtl 's State / StateT
module Control.Monad.Trans.MultiState.Strict
(
-- * MultiStateT
MultiStateT(..)
, MultiStateTNull
, MultiState
-- * MonadMultiState class
, MonadMultiGet(..)
, MonadMultiState(..)
-- * run-functions
, runMultiStateT
, runMultiStateTAS
, runMultiStateTSA
, runMultiStateTA
, runMultiStateTS
, runMultiStateT_
, runMultiStateTNil
, runMultiStateTNil_
-- * with-functions (single state)
, withMultiState
, withMultiStateAS
, withMultiStateSA
, withMultiStateA
, withMultiStateS
, withMultiState_
-- * with-functions (multiple states)
, withMultiStates
, withMultiStatesAS
, withMultiStatesSA
, withMultiStatesA
, withMultiStatesS
, withMultiStates_
-- * without-function (single state)
, withoutMultiState
-- * inflate-functions (run single state in multiple states)
, inflateState
, inflateReader
, inflateWriter
-- * other functions
, mapMultiStateT
, mGetRaw
, mPutRaw
) where
import Data.HList.HList
import Data.HList.ContainsType
import Control.Monad.State.Strict ( StateT(..)
, MonadState(..)
, evalStateT
, execStateT
, mapStateT )
import Control.Monad.Reader ( ReaderT(..) )
import Control.Monad.Writer.Strict ( WriterT(..) )
import Control.Monad.Trans.Class ( MonadTrans
, lift )
import Control.Monad.Writer.Class ( MonadWriter
, listen
, tell
, writer
, pass )
import Control.Monad.Trans.MultiState.Class
import Data.Functor.Identity ( Identity )
import Control.Applicative ( Applicative(..)
, Alternative(..)
)
import Control.Monad ( MonadPlus(..)
, liftM
, ap
, void )
import Control.Monad.Base ( MonadBase(..)
, liftBaseDefault
)
import Control.Monad.Trans.Control ( MonadTransControl(..)
, MonadBaseControl(..)
, ComposeSt
, defaultLiftBaseWith
, defaultRestoreM
)
import Data.Monoid ( Monoid )
import Control.Monad.Fix ( MonadFix(..) )
import Control.Monad.IO.Class ( MonadIO(..) )
| A State transformer monad patameterized by :
--
-- * x - The list of types constituting the state,
-- * m - The inner monad.
--
' MultiStateT ' corresponds to mtl 's ' StateT ' , but can contain
-- a heterogenous list of types.
--
This heterogenous list is represented using Types . Data . List , i.e :
--
-- * @'[]@ - The empty list,
* @a ' : b@ - A list where @/a/@ is an arbitrary type
-- and @/b/@ is the rest list.
--
-- For example,
--
-- > MultiStateT '[Int, Bool] :: (* -> *) -> (* -> *)
--
is a State wrapper containing the types [ Int , Bool ] .
newtype MultiStateT x m a = MultiStateT {
runMultiStateTRaw :: StateT (HList x) m a
}
| A MultiState transformer carrying an empty state .
type MultiStateTNull = MultiStateT '[]
-- | A state monad parameterized by the list of types x of the state to carry.
--
Similar to @State s = StateT s Identity@
type MultiState x = MultiStateT x Identity
instance (Functor f) => Functor (MultiStateT x f) where
fmap f = MultiStateT . fmap f . runMultiStateTRaw
instance (Applicative m, Monad m) => Applicative (MultiStateT x m) where
pure = MultiStateT . pure
(<*>) = ap
instance Monad m => Monad (MultiStateT x m) where
return = pure
k >>= f = MultiStateT $ runMultiStateTRaw k >>= (runMultiStateTRaw.f)
instance MonadTrans (MultiStateT x) where
lift = MultiStateT . lift
#if MIN_VERSION_base(4,8,0)
instance {-# OVERLAPPING #-} (Monad m, ContainsType a c)
#else
instance (Monad m, ContainsType a c)
#endif
=> MonadMultiGet a (MultiStateT c m) where
mGet = MultiStateT $ liftM getHListElem get
#if MIN_VERSION_base(4,8,0)
instance {-# OVERLAPPING #-} (Monad m, ContainsType a c)
#else
instance (Monad m, ContainsType a c)
#endif
=> MonadMultiState a (MultiStateT c m) where
mSet v = MultiStateT $ get >>= put . setHListElem v
instance MonadFix m => MonadFix (MultiStateT s m) where
mfix f = MultiStateT $ mfix (runMultiStateTRaw . f)
-- methods
| A raw extractor of the contained HList ( i.e. the complete state ) .
mGetRaw :: Monad m => MultiStateT a m (HList a)
mGetRaw = MultiStateT get
mPutRaw :: Monad m => HList s -> MultiStateT s m ()
mPutRaw = MultiStateT . put
-- | Map both the return value and the state of a computation
-- using the given function.
mapMultiStateT :: (m (a, HList w) -> m' (a', HList w))
-> MultiStateT w m a
-> MultiStateT w m' a'
mapMultiStateT f = MultiStateT . mapStateT f . runMultiStateTRaw
runMultiStateT :: Functor m => HList s -> MultiStateT s m a -> m (a, HList s)
runMultiStateTAS :: Functor m => HList s -> MultiStateT s m a -> m (a, HList s)
runMultiStateTSA :: Monad m => HList s -> MultiStateT s m a -> m (HList s, a)
runMultiStateTA :: Monad m => HList s -> MultiStateT s m a -> m a
runMultiStateTS :: Monad m => HList s -> MultiStateT s m a -> m (HList s)
runMultiStateT_ :: Functor m => HList s -> MultiStateT s m a -> m ()
ghc too dumb for this shortcut , unfortunately
-- runMultiStateT s k = runMultiStateTNil $ withMultiStates s k
-- runMultiStateTAS s k = runMultiStateTNil $ withMultiStatesAS s k
runMultiStateTSA s k = runMultiStateTNil $ withMultiStatesSA s k
runMultiStateTA s k = runMultiStateTNil $ withMultiStatesA s k
runMultiStateTS s k = runMultiStateTNil $ withMultiStatesS s k
-- runMultiStateT_ s k = runMultiStateTNil $ withMultiStates_ s k
runMultiStateT s k = runMultiStateTAS s k
runMultiStateTAS s k = runStateT (runMultiStateTRaw k) s
runMultiStateTSA s k = (\(a,b) -> (b,a)) `liftM` runStateT (runMultiStateTRaw k) s
runMultiStateTA s k = evalStateT (runMultiStateTRaw k) s
runMultiStateTS s k = execStateT (runMultiStateTRaw k) s
runMultiStateT_ s k = void $ runStateT (runMultiStateTRaw k) s
runMultiStateTNil :: Monad m => MultiStateT '[] m a -> m a
runMultiStateTNil_ :: Functor m => MultiStateT '[] m a -> m ()
runMultiStateTNil k = evalStateT (runMultiStateTRaw k) HNil
runMultiStateTNil_ k = void $ runStateT (runMultiStateTRaw k) HNil
withMultiState :: Monad m => s -> MultiStateT (s ': ss) m a -> MultiStateT ss m (a, s)
withMultiStateAS :: Monad m => s -> MultiStateT (s ': ss) m a -> MultiStateT ss m (a, s)
withMultiStateSA :: Monad m => s -> MultiStateT (s ': ss) m a -> MultiStateT ss m (s, a)
withMultiStateA :: Monad m => s -> MultiStateT (s ': ss) m a -> MultiStateT ss m a
withMultiStateS :: Monad m => s -> MultiStateT (s ': ss) m a -> MultiStateT ss m s
withMultiState_ :: (Functor m, Monad m) => s -> MultiStateT (s ': ss) m a -> MultiStateT ss m ()
withMultiState = withMultiStateAS
withMultiStateAS x k = MultiStateT $ do
s <- get
(a, s') <- lift $ runStateT (runMultiStateTRaw k) (x :+: s)
case s' of x' :+: sr' -> do put sr'; return (a, x')
withMultiStateSA s k = (\(a,b) -> (b,a)) `liftM` withMultiStateAS s k
withMultiStateA s k = fst `liftM` withMultiStateAS s k
withMultiStateS s k = snd `liftM` withMultiStateAS s k
withMultiState_ s k = void $ withMultiStateAS s k
withMultiStates :: Monad m => HList s1 -> MultiStateT (Append s1 s2) m a -> MultiStateT s2 m (a, HList s1)
withMultiStatesAS :: Monad m => HList s1 -> MultiStateT (Append s1 s2) m a -> MultiStateT s2 m (a, HList s1)
withMultiStatesSA :: Monad m => HList s1 -> MultiStateT (Append s1 s2) m a -> MultiStateT s2 m (HList s1, a)
withMultiStatesA :: Monad m => HList s1 -> MultiStateT (Append s1 s2) m a -> MultiStateT s2 m a
withMultiStatesS :: Monad m => HList s1 -> MultiStateT (Append s1 s2) m a -> MultiStateT s2 m (HList s1)
withMultiStates_ :: (Functor m, Monad m) => HList s1 -> MultiStateT (Append s1 s2) m a -> MultiStateT s2 m ()
withMultiStates = withMultiStatesAS
withMultiStatesAS HNil = liftM (\r -> (r, HNil))
withMultiStatesAS (x :+: xs) = liftM (\((a, x'), xs') -> (a, x' :+: xs'))
. withMultiStatesAS xs
. withMultiStateAS x
withMultiStatesSA HNil = liftM (\r -> (HNil, r))
withMultiStatesSA (x :+: xs) = liftM (\((a, x'), xs') -> (x' :+: xs', a))
. withMultiStatesAS xs
. withMultiStateAS x
withMultiStatesA HNil = id
withMultiStatesA (x :+: xs) = withMultiStatesA xs . withMultiStateA x
withMultiStatesS HNil = liftM (const HNil)
withMultiStatesS (x :+: xs) = liftM (\(x', xs') -> x' :+: xs')
. withMultiStatesAS xs
. withMultiStateS x
withMultiStates_ HNil = liftM (const ())
withMultiStates_ (x :+: xs) = withMultiStates_ xs . withMultiState_ x
withoutMultiState :: (Functor m, Monad m) => MultiStateT ss m a -> MultiStateT (s ': ss) m a
withoutMultiState k = MultiStateT $ get >>= \case
s :+: sr -> do
(a, sr') <- lift $ runMultiStateT sr k
put (s :+: sr')
return a
inflateState :: (Monad m, ContainsType s ss)
=> StateT s m a
-> MultiStateT ss m a
inflateState k = do
s <- mGet
(x, s') <- lift $ runStateT k s
mSet s'
return x
inflateReader :: (Monad m, ContainsType r ss)
=> ReaderT r m a
-> MultiStateT ss m a
inflateReader k = mGet >>= lift . runReaderT k
inflateWriter :: (Monad m, ContainsType w ss, Monoid w)
=> WriterT w m a
-> MultiStateT ss m a
inflateWriter k = do
(x, w) <- lift $ runWriterT k
mSet w
return x
-- foreign lifting instances
instance (MonadState s m) => MonadState s (MultiStateT c m) where
put = lift . put
get = lift $ get
state = lift . state
instance (MonadWriter w m) => MonadWriter w (MultiStateT c m) where
writer = lift . writer
tell = lift . tell
listen = MultiStateT .
mapStateT (liftM (\((a,w), w') -> ((a, w'), w)) . listen) .
runMultiStateTRaw
pass = MultiStateT .
mapStateT (pass . liftM (\((a, f), w) -> ((a, w), f))) .
runMultiStateTRaw
instance MonadIO m => MonadIO (MultiStateT c m) where
liftIO = lift . liftIO
instance (Functor m, Applicative m, MonadPlus m) => Alternative (MultiStateT s m) where
empty = lift mzero
MultiStateT m <|> MultiStateT n = MultiStateT $ m <|> n
instance MonadPlus m => MonadPlus (MultiStateT s m) where
mzero = MultiStateT $ mzero
MultiStateT m `mplus` MultiStateT n = MultiStateT $ m `mplus` n
instance MonadBase b m => MonadBase b (MultiStateT s m) where
liftBase = liftBaseDefault
instance MonadTransControl (MultiStateT s) where
type StT (MultiStateT s) a = (a, HList s)
liftWith f = MultiStateT $ liftWith $ \s -> f $ \r -> s $ runMultiStateTRaw r
restoreT = MultiStateT . restoreT
instance MonadBaseControl b m => MonadBaseControl b (MultiStateT s m) where
type StM (MultiStateT s m) a = ComposeSt (MultiStateT s) m a
liftBaseWith = defaultLiftBaseWith
restoreM = defaultRestoreM
| null | https://raw.githubusercontent.com/lspitzner/multistate/5f49eff342443ef719158b00e329c860f2e2f54e/src/Control/Monad/Trans/MultiState/Strict.hs | haskell | * MultiStateT
* MonadMultiState class
* run-functions
* with-functions (single state)
* with-functions (multiple states)
* without-function (single state)
* inflate-functions (run single state in multiple states)
* other functions
* x - The list of types constituting the state,
* m - The inner monad.
a heterogenous list of types.
* @'[]@ - The empty list,
and @/b/@ is the rest list.
For example,
> MultiStateT '[Int, Bool] :: (* -> *) -> (* -> *)
| A state monad parameterized by the list of types x of the state to carry.
# OVERLAPPING #
# OVERLAPPING #
methods
| Map both the return value and the state of a computation
using the given function.
runMultiStateT s k = runMultiStateTNil $ withMultiStates s k
runMultiStateTAS s k = runMultiStateTNil $ withMultiStatesAS s k
runMultiStateT_ s k = runMultiStateTNil $ withMultiStates_ s k
foreign lifting instances | # LANGUAGE CPP #
| The multi - valued version of mtl 's State / StateT
module Control.Monad.Trans.MultiState.Strict
(
MultiStateT(..)
, MultiStateTNull
, MultiState
, MonadMultiGet(..)
, MonadMultiState(..)
, runMultiStateT
, runMultiStateTAS
, runMultiStateTSA
, runMultiStateTA
, runMultiStateTS
, runMultiStateT_
, runMultiStateTNil
, runMultiStateTNil_
, withMultiState
, withMultiStateAS
, withMultiStateSA
, withMultiStateA
, withMultiStateS
, withMultiState_
, withMultiStates
, withMultiStatesAS
, withMultiStatesSA
, withMultiStatesA
, withMultiStatesS
, withMultiStates_
, withoutMultiState
, inflateState
, inflateReader
, inflateWriter
, mapMultiStateT
, mGetRaw
, mPutRaw
) where
import Data.HList.HList
import Data.HList.ContainsType
import Control.Monad.State.Strict ( StateT(..)
, MonadState(..)
, evalStateT
, execStateT
, mapStateT )
import Control.Monad.Reader ( ReaderT(..) )
import Control.Monad.Writer.Strict ( WriterT(..) )
import Control.Monad.Trans.Class ( MonadTrans
, lift )
import Control.Monad.Writer.Class ( MonadWriter
, listen
, tell
, writer
, pass )
import Control.Monad.Trans.MultiState.Class
import Data.Functor.Identity ( Identity )
import Control.Applicative ( Applicative(..)
, Alternative(..)
)
import Control.Monad ( MonadPlus(..)
, liftM
, ap
, void )
import Control.Monad.Base ( MonadBase(..)
, liftBaseDefault
)
import Control.Monad.Trans.Control ( MonadTransControl(..)
, MonadBaseControl(..)
, ComposeSt
, defaultLiftBaseWith
, defaultRestoreM
)
import Data.Monoid ( Monoid )
import Control.Monad.Fix ( MonadFix(..) )
import Control.Monad.IO.Class ( MonadIO(..) )
| A State transformer monad patameterized by :
' MultiStateT ' corresponds to mtl 's ' StateT ' , but can contain
This heterogenous list is represented using Types . Data . List , i.e :
* @a ' : b@ - A list where @/a/@ is an arbitrary type
is a State wrapper containing the types [ Int , Bool ] .
newtype MultiStateT x m a = MultiStateT {
runMultiStateTRaw :: StateT (HList x) m a
}
| A MultiState transformer carrying an empty state .
type MultiStateTNull = MultiStateT '[]
Similar to @State s = StateT s Identity@
type MultiState x = MultiStateT x Identity
instance (Functor f) => Functor (MultiStateT x f) where
fmap f = MultiStateT . fmap f . runMultiStateTRaw
instance (Applicative m, Monad m) => Applicative (MultiStateT x m) where
pure = MultiStateT . pure
(<*>) = ap
instance Monad m => Monad (MultiStateT x m) where
return = pure
k >>= f = MultiStateT $ runMultiStateTRaw k >>= (runMultiStateTRaw.f)
instance MonadTrans (MultiStateT x) where
lift = MultiStateT . lift
#if MIN_VERSION_base(4,8,0)
#else
instance (Monad m, ContainsType a c)
#endif
=> MonadMultiGet a (MultiStateT c m) where
mGet = MultiStateT $ liftM getHListElem get
#if MIN_VERSION_base(4,8,0)
#else
instance (Monad m, ContainsType a c)
#endif
=> MonadMultiState a (MultiStateT c m) where
mSet v = MultiStateT $ get >>= put . setHListElem v
instance MonadFix m => MonadFix (MultiStateT s m) where
mfix f = MultiStateT $ mfix (runMultiStateTRaw . f)
| A raw extractor of the contained HList ( i.e. the complete state ) .
mGetRaw :: Monad m => MultiStateT a m (HList a)
mGetRaw = MultiStateT get
mPutRaw :: Monad m => HList s -> MultiStateT s m ()
mPutRaw = MultiStateT . put
mapMultiStateT :: (m (a, HList w) -> m' (a', HList w))
-> MultiStateT w m a
-> MultiStateT w m' a'
mapMultiStateT f = MultiStateT . mapStateT f . runMultiStateTRaw
runMultiStateT :: Functor m => HList s -> MultiStateT s m a -> m (a, HList s)
runMultiStateTAS :: Functor m => HList s -> MultiStateT s m a -> m (a, HList s)
runMultiStateTSA :: Monad m => HList s -> MultiStateT s m a -> m (HList s, a)
runMultiStateTA :: Monad m => HList s -> MultiStateT s m a -> m a
runMultiStateTS :: Monad m => HList s -> MultiStateT s m a -> m (HList s)
runMultiStateT_ :: Functor m => HList s -> MultiStateT s m a -> m ()
ghc too dumb for this shortcut , unfortunately
runMultiStateTSA s k = runMultiStateTNil $ withMultiStatesSA s k
runMultiStateTA s k = runMultiStateTNil $ withMultiStatesA s k
runMultiStateTS s k = runMultiStateTNil $ withMultiStatesS s k
runMultiStateT s k = runMultiStateTAS s k
runMultiStateTAS s k = runStateT (runMultiStateTRaw k) s
runMultiStateTSA s k = (\(a,b) -> (b,a)) `liftM` runStateT (runMultiStateTRaw k) s
runMultiStateTA s k = evalStateT (runMultiStateTRaw k) s
runMultiStateTS s k = execStateT (runMultiStateTRaw k) s
runMultiStateT_ s k = void $ runStateT (runMultiStateTRaw k) s
runMultiStateTNil :: Monad m => MultiStateT '[] m a -> m a
runMultiStateTNil_ :: Functor m => MultiStateT '[] m a -> m ()
runMultiStateTNil k = evalStateT (runMultiStateTRaw k) HNil
runMultiStateTNil_ k = void $ runStateT (runMultiStateTRaw k) HNil
withMultiState :: Monad m => s -> MultiStateT (s ': ss) m a -> MultiStateT ss m (a, s)
withMultiStateAS :: Monad m => s -> MultiStateT (s ': ss) m a -> MultiStateT ss m (a, s)
withMultiStateSA :: Monad m => s -> MultiStateT (s ': ss) m a -> MultiStateT ss m (s, a)
withMultiStateA :: Monad m => s -> MultiStateT (s ': ss) m a -> MultiStateT ss m a
withMultiStateS :: Monad m => s -> MultiStateT (s ': ss) m a -> MultiStateT ss m s
withMultiState_ :: (Functor m, Monad m) => s -> MultiStateT (s ': ss) m a -> MultiStateT ss m ()
withMultiState = withMultiStateAS
withMultiStateAS x k = MultiStateT $ do
s <- get
(a, s') <- lift $ runStateT (runMultiStateTRaw k) (x :+: s)
case s' of x' :+: sr' -> do put sr'; return (a, x')
withMultiStateSA s k = (\(a,b) -> (b,a)) `liftM` withMultiStateAS s k
withMultiStateA s k = fst `liftM` withMultiStateAS s k
withMultiStateS s k = snd `liftM` withMultiStateAS s k
withMultiState_ s k = void $ withMultiStateAS s k
withMultiStates :: Monad m => HList s1 -> MultiStateT (Append s1 s2) m a -> MultiStateT s2 m (a, HList s1)
withMultiStatesAS :: Monad m => HList s1 -> MultiStateT (Append s1 s2) m a -> MultiStateT s2 m (a, HList s1)
withMultiStatesSA :: Monad m => HList s1 -> MultiStateT (Append s1 s2) m a -> MultiStateT s2 m (HList s1, a)
withMultiStatesA :: Monad m => HList s1 -> MultiStateT (Append s1 s2) m a -> MultiStateT s2 m a
withMultiStatesS :: Monad m => HList s1 -> MultiStateT (Append s1 s2) m a -> MultiStateT s2 m (HList s1)
withMultiStates_ :: (Functor m, Monad m) => HList s1 -> MultiStateT (Append s1 s2) m a -> MultiStateT s2 m ()
withMultiStates = withMultiStatesAS
withMultiStatesAS HNil = liftM (\r -> (r, HNil))
withMultiStatesAS (x :+: xs) = liftM (\((a, x'), xs') -> (a, x' :+: xs'))
. withMultiStatesAS xs
. withMultiStateAS x
withMultiStatesSA HNil = liftM (\r -> (HNil, r))
withMultiStatesSA (x :+: xs) = liftM (\((a, x'), xs') -> (x' :+: xs', a))
. withMultiStatesAS xs
. withMultiStateAS x
withMultiStatesA HNil = id
withMultiStatesA (x :+: xs) = withMultiStatesA xs . withMultiStateA x
withMultiStatesS HNil = liftM (const HNil)
withMultiStatesS (x :+: xs) = liftM (\(x', xs') -> x' :+: xs')
. withMultiStatesAS xs
. withMultiStateS x
withMultiStates_ HNil = liftM (const ())
withMultiStates_ (x :+: xs) = withMultiStates_ xs . withMultiState_ x
withoutMultiState :: (Functor m, Monad m) => MultiStateT ss m a -> MultiStateT (s ': ss) m a
withoutMultiState k = MultiStateT $ get >>= \case
s :+: sr -> do
(a, sr') <- lift $ runMultiStateT sr k
put (s :+: sr')
return a
inflateState :: (Monad m, ContainsType s ss)
=> StateT s m a
-> MultiStateT ss m a
inflateState k = do
s <- mGet
(x, s') <- lift $ runStateT k s
mSet s'
return x
inflateReader :: (Monad m, ContainsType r ss)
=> ReaderT r m a
-> MultiStateT ss m a
inflateReader k = mGet >>= lift . runReaderT k
inflateWriter :: (Monad m, ContainsType w ss, Monoid w)
=> WriterT w m a
-> MultiStateT ss m a
inflateWriter k = do
(x, w) <- lift $ runWriterT k
mSet w
return x
instance (MonadState s m) => MonadState s (MultiStateT c m) where
put = lift . put
get = lift $ get
state = lift . state
instance (MonadWriter w m) => MonadWriter w (MultiStateT c m) where
writer = lift . writer
tell = lift . tell
listen = MultiStateT .
mapStateT (liftM (\((a,w), w') -> ((a, w'), w)) . listen) .
runMultiStateTRaw
pass = MultiStateT .
mapStateT (pass . liftM (\((a, f), w) -> ((a, w), f))) .
runMultiStateTRaw
instance MonadIO m => MonadIO (MultiStateT c m) where
liftIO = lift . liftIO
instance (Functor m, Applicative m, MonadPlus m) => Alternative (MultiStateT s m) where
empty = lift mzero
MultiStateT m <|> MultiStateT n = MultiStateT $ m <|> n
instance MonadPlus m => MonadPlus (MultiStateT s m) where
mzero = MultiStateT $ mzero
MultiStateT m `mplus` MultiStateT n = MultiStateT $ m `mplus` n
instance MonadBase b m => MonadBase b (MultiStateT s m) where
liftBase = liftBaseDefault
instance MonadTransControl (MultiStateT s) where
type StT (MultiStateT s) a = (a, HList s)
liftWith f = MultiStateT $ liftWith $ \s -> f $ \r -> s $ runMultiStateTRaw r
restoreT = MultiStateT . restoreT
instance MonadBaseControl b m => MonadBaseControl b (MultiStateT s m) where
type StM (MultiStateT s m) a = ComposeSt (MultiStateT s) m a
liftBaseWith = defaultLiftBaseWith
restoreM = defaultRestoreM
|
8da5b63b9ee3c733ba20dc47eb9ec4a7ea645a403ea3ca758342096e1c2d72cc | system-f/papa | Either.hs | # LANGUAGE NoImplicitPrelude #
module Papa.Base.Export.Data.Either(
Either(Left, Right)
, either
, isLeft
, isRight
, partitionEithers
) where
import Data.Either (
Either(Left, Right)
, either
, isLeft
, isRight
, partitionEithers
)
| null | https://raw.githubusercontent.com/system-f/papa/5c4d71e08b905a882dd9a4a7d0c336411971c360/papa-base-export/src/Papa/Base/Export/Data/Either.hs | haskell | # LANGUAGE NoImplicitPrelude #
module Papa.Base.Export.Data.Either(
Either(Left, Right)
, either
, isLeft
, isRight
, partitionEithers
) where
import Data.Either (
Either(Left, Right)
, either
, isLeft
, isRight
, partitionEithers
)
| |
f9edb4cfae1e7885354cfc92c89e2bd16b6d2a40a3609ab28ab4e013a9c187b6 | racket/plai | student-1.rkt | #lang plai/mutator
; mark-and-sweep-test.rkt - Ben Childs
; Designed to test the mark and sweep collector
Runs three tests :
;
; Allocation of subsequently larger lists
;
; Use of Local variables in a loop (garbage after each iteration)
; Followed by allocation of large list (verifies that they are correctly collected)
;
; Generation of a number of circularly referenced lists
; Followed by allocation of several large lists
;
; Finally it runs the sample tests distributed with the assignment
(allocator-setup "../good-collectors/good-collector.rkt" 80)
; Helper to generate long lists
(define (gen-list x)
(if (zero? x) '() (cons x (gen-list (- x 1)))))
; Function that defines local vars
(define (local-vars)
(let ((x 3) (y 5) (z 10) (a 5))
(+ x (- 10 y))))
(define (loop x)
(printf "Iteration: ~a\n" x)
(if (zero? x) 0
(loop (- (+ (local-vars) (- x 1)) 8))))
; Generate gradually increasing sizes of lists
; To trigger garbage collection at different points
(printf "~a\n" (gen-list 1))
(printf "~a\n" (gen-list 2))
(printf "~a\n" (gen-list 4))
(printf "~a\n" (gen-list 8))
; Run a loop that uses local vars a few times
(printf "Generating Primitives in loops\n")
(loop 20)
(printf "Try Allocating large list again\n")
(printf "~a\n" (gen-list 8))
; Create some circular references
(define (gen-circular)
(let ([x (cons 3 4)])
(let ([y (cons 2 x)])
(set-rest! x y)
x)))
(printf "Testing Circular References\n")
(printf "~a\n" (gen-circular))
(printf "~a\n" (gen-circular))
(printf "~a\n" (gen-circular))
(printf "~a\n" (gen-circular))
(printf "~a\n" (gen-circular))
(printf "~a\n" (gen-circular))
(printf "~a\n" (gen-circular))
(printf "~a\n" (gen-circular))
(printf "~a\n" (gen-circular))
(printf "Try allocating large list again\n")
(printf "~a\n" (gen-list 8))
(printf "~a\n" (gen-list 8))
(printf "~a\n" (gen-list 8))
(printf "~a\n" (gen-list 8))
(printf "~a\n" (gen-list 8))
(printf "Running sample tests\n")
(define (fact x)
(if (zero? x)
1
(* x (fact (sub1 x)))))
(define (fact-help x a)
(if (zero? x)
a
(fact-help (sub1 x) (* x a))))
(define lst (cons 1 (cons 2 (cons 3 empty))))
(define (map-add n lst)
(map (lambda (x) (+ n x)) lst))
(define (map f lst)
(if (cons? lst)
(cons (f (first lst)) (map f (rest lst)))
empty))
(define (filter p lst)
(if (cons? lst)
(if (p (first lst))
(cons (first lst) (filter p (rest lst)))
(filter p (rest lst)))
lst))
(define (append l1 l2)
(if (cons? l1)
(cons (first l1) (append (rest l1) l2))
l2))
(define (length lst)
(if (empty? lst)
0
(add1 (length (rest lst)))))
(define tail (cons 1 empty))
(define head (cons 4 (cons 3 (cons 2 tail))))
(set-rest! tail head)
(printf "res ~a\n" head)
(set! head empty)
(set! tail head)
(printf "res ~a\n" lst)
(printf "res ~a\n" (length '(hello goodbye)))
(printf "res ~a\n" (map sub1 lst))
(printf "(fact-help 15 1): ~a\n" (fact-help 15 1))
(printf "(fact 9): ~a\n" (fact 9))
(printf "(append lst lst): ~a\n" (append lst lst))
(printf "(map-add 5 lst): ~a\n" (map-add 5 lst))
(printf "(filter even? (map sub1 lst)): ~a\n" (filter even? (map sub1 lst)))
(printf "(length lst): ~a\n" (length lst))
| null | https://raw.githubusercontent.com/racket/plai/164f3b763116fcfa7bd827be511650e71fa04319/plai-lib/tests/gc/good-mutators/student-1.rkt | racket | mark-and-sweep-test.rkt - Ben Childs
Designed to test the mark and sweep collector
Allocation of subsequently larger lists
Use of Local variables in a loop (garbage after each iteration)
Followed by allocation of large list (verifies that they are correctly collected)
Generation of a number of circularly referenced lists
Followed by allocation of several large lists
Finally it runs the sample tests distributed with the assignment
Helper to generate long lists
Function that defines local vars
Generate gradually increasing sizes of lists
To trigger garbage collection at different points
Run a loop that uses local vars a few times
Create some circular references | #lang plai/mutator
Runs three tests :
(allocator-setup "../good-collectors/good-collector.rkt" 80)
(define (gen-list x)
(if (zero? x) '() (cons x (gen-list (- x 1)))))
(define (local-vars)
(let ((x 3) (y 5) (z 10) (a 5))
(+ x (- 10 y))))
(define (loop x)
(printf "Iteration: ~a\n" x)
(if (zero? x) 0
(loop (- (+ (local-vars) (- x 1)) 8))))
(printf "~a\n" (gen-list 1))
(printf "~a\n" (gen-list 2))
(printf "~a\n" (gen-list 4))
(printf "~a\n" (gen-list 8))
(printf "Generating Primitives in loops\n")
(loop 20)
(printf "Try Allocating large list again\n")
(printf "~a\n" (gen-list 8))
(define (gen-circular)
(let ([x (cons 3 4)])
(let ([y (cons 2 x)])
(set-rest! x y)
x)))
(printf "Testing Circular References\n")
(printf "~a\n" (gen-circular))
(printf "~a\n" (gen-circular))
(printf "~a\n" (gen-circular))
(printf "~a\n" (gen-circular))
(printf "~a\n" (gen-circular))
(printf "~a\n" (gen-circular))
(printf "~a\n" (gen-circular))
(printf "~a\n" (gen-circular))
(printf "~a\n" (gen-circular))
(printf "Try allocating large list again\n")
(printf "~a\n" (gen-list 8))
(printf "~a\n" (gen-list 8))
(printf "~a\n" (gen-list 8))
(printf "~a\n" (gen-list 8))
(printf "~a\n" (gen-list 8))
(printf "Running sample tests\n")
(define (fact x)
(if (zero? x)
1
(* x (fact (sub1 x)))))
(define (fact-help x a)
(if (zero? x)
a
(fact-help (sub1 x) (* x a))))
(define lst (cons 1 (cons 2 (cons 3 empty))))
(define (map-add n lst)
(map (lambda (x) (+ n x)) lst))
(define (map f lst)
(if (cons? lst)
(cons (f (first lst)) (map f (rest lst)))
empty))
(define (filter p lst)
(if (cons? lst)
(if (p (first lst))
(cons (first lst) (filter p (rest lst)))
(filter p (rest lst)))
lst))
(define (append l1 l2)
(if (cons? l1)
(cons (first l1) (append (rest l1) l2))
l2))
(define (length lst)
(if (empty? lst)
0
(add1 (length (rest lst)))))
(define tail (cons 1 empty))
(define head (cons 4 (cons 3 (cons 2 tail))))
(set-rest! tail head)
(printf "res ~a\n" head)
(set! head empty)
(set! tail head)
(printf "res ~a\n" lst)
(printf "res ~a\n" (length '(hello goodbye)))
(printf "res ~a\n" (map sub1 lst))
(printf "(fact-help 15 1): ~a\n" (fact-help 15 1))
(printf "(fact 9): ~a\n" (fact 9))
(printf "(append lst lst): ~a\n" (append lst lst))
(printf "(map-add 5 lst): ~a\n" (map-add 5 lst))
(printf "(filter even? (map sub1 lst)): ~a\n" (filter even? (map sub1 lst)))
(printf "(length lst): ~a\n" (length lst))
|
4848dfafc451530129239ef61bfc81feaa6365cb7ab3310885d8af30901e0f57 | brianium/clean-todos | spec.cljc | (ns todos.core.entity.spec
(:require [todos.core.entity :as entity]
#?(:clj [clojure.spec.alpha :as s]
:cljs [cljs.spec.alpha :as s])))
(s/def ::id uuid?)
(s/def ::entity/id ::id)
(s/def ::entity (s/keys :req [::entity/id]))
(s/def ::storage-error keyword?)
(s/def ::storage-result (s/or :data (s/or :entity ::entity :entities (s/* ::entity))
:error ::storage-error))
(s/def ::uuid-string entity/uuid-string?)
(s/fdef entity/storage-error?
:args (s/cat :result ::storage-result)
:ret boolean?)
(s/fdef entity/uuid-string?
:args (s/cat :str string?)
:ret boolean?)
(s/fdef entity/make-uuid
:args empty?
:ret ::id)
(s/fdef entity/string->uuid
:args (s/cat :str ::uuid-string)
:ret ::id)
| null | https://raw.githubusercontent.com/brianium/clean-todos/fca2320fe3bca052787c4ace479ce69d23d58a12/src/todos/core/entity/spec.cljc | clojure | (ns todos.core.entity.spec
(:require [todos.core.entity :as entity]
#?(:clj [clojure.spec.alpha :as s]
:cljs [cljs.spec.alpha :as s])))
(s/def ::id uuid?)
(s/def ::entity/id ::id)
(s/def ::entity (s/keys :req [::entity/id]))
(s/def ::storage-error keyword?)
(s/def ::storage-result (s/or :data (s/or :entity ::entity :entities (s/* ::entity))
:error ::storage-error))
(s/def ::uuid-string entity/uuid-string?)
(s/fdef entity/storage-error?
:args (s/cat :result ::storage-result)
:ret boolean?)
(s/fdef entity/uuid-string?
:args (s/cat :str string?)
:ret boolean?)
(s/fdef entity/make-uuid
:args empty?
:ret ::id)
(s/fdef entity/string->uuid
:args (s/cat :str ::uuid-string)
:ret ::id)
| |
47484ddfd008de7f7563e14a8bd543ecf8934954a99318c27d7a0774d1f87a3d | thelema/ocaml-community | main.ml | (***********************************************************************)
(* *)
(* OCaml *)
(* *)
, projet Cristal , INRIA Rocquencourt
OCaml port by and
(* *)
Copyright 1996 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the Q Public License version 1.0 .
(* *)
(***********************************************************************)
open Input_handling
open Question
open Command_line
open Debugger_config
open Checkpoints
open Time_travel
open Parameters
open Program_management
open Frames
open Show_information
open Format
open Primitives
let line_buffer = Lexing.from_function read_user_input
let rec loop ppf =
line_loop ppf line_buffer;
if !loaded && (not (yes_or_no "The program is running. Quit anyway")) then
loop ppf
let current_duration = ref (-1L)
let rec protect ppf restart loop =
try
loop ppf
with
| End_of_file ->
protect ppf restart (function ppf ->
forget_process
!current_checkpoint.c_fd
!current_checkpoint.c_pid;
pp_print_flush ppf ();
stop_user_input ();
restart ppf)
| Toplevel ->
protect ppf restart (function ppf ->
pp_print_flush ppf ();
stop_user_input ();
restart ppf)
| Sys.Break ->
protect ppf restart (function ppf ->
fprintf ppf "Interrupted.@.";
Exec.protect (function () ->
stop_user_input ();
if !loaded then begin
try_select_frame 0;
show_current_event ppf;
end);
restart ppf)
| Current_checkpoint_lost ->
protect ppf restart (function ppf ->
fprintf ppf "Trying to recover...@.";
stop_user_input ();
recover ();
try_select_frame 0;
show_current_event ppf;
restart ppf)
| Current_checkpoint_lost_start_at (time, init_duration) ->
protect ppf restart (function ppf ->
let b =
if !current_duration = -1L then begin
let msg = sprintf "Restart from time %Ld and try to get closer of the problem" time in
stop_user_input ();
if yes_or_no msg then
(current_duration := init_duration; true)
else
false
end
else
true in
if b then
begin
go_to time;
current_duration := Int64.div !current_duration 10L;
if !current_duration > 0L then
while true do
step !current_duration
done
else begin
current_duration := -1L;
stop_user_input ();
show_current_event ppf;
restart ppf;
end
end
else
begin
recover ();
show_current_event ppf;
restart ppf
end)
| x ->
kill_program ();
raise x
let execute_file_if_any () =
let buffer = Buffer.create 128 in
begin
try
let base = ".ocamldebug" in
let file =
if Sys.file_exists base then
base
else
Filename.concat (Sys.getenv "HOME") base in
let ch = open_in file in
fprintf Format.std_formatter "Executing file %s@." file;
while true do
let line = string_trim (input_line ch) in
if line <> "" && line.[0] <> '#' then begin
Buffer.add_string buffer line;
Buffer.add_char buffer '\n'
end
done;
with _ -> ()
end;
let len = Buffer.length buffer in
if len > 0 then
let commands = Buffer.sub buffer 0 (pred len) in
line_loop Format.std_formatter (Lexing.from_string commands)
let toplevel_loop () =
interactif := false;
current_prompt := "";
execute_file_if_any ();
interactif := true;
current_prompt := debugger_prompt;
protect Format.std_formatter loop loop
(* Parsing of command-line arguments *)
exception Found_program_name
let anonymous s =
program_name := Unix_tools.make_absolute s; raise Found_program_name
let add_include d =
default_load_path :=
Misc.expand_directory Config.standard_library d :: !default_load_path
let set_socket s =
socket_name := s
let set_checkpoints n =
checkpoint_max_count := n
let set_directory dir =
Sys.chdir dir
let print_version () =
printf "The OCaml debugger, version %s@." Sys.ocaml_version;
exit 0;
;;
let print_version_num () =
printf "%s@." Sys.ocaml_version;
exit 0;
;;
let speclist = [
"-c", Arg.Int set_checkpoints,
"<count> Set max number of checkpoints kept";
"-cd", Arg.String set_directory,
"<dir> Change working directory";
"-emacs", Arg.Set emacs,
"For running the debugger under emacs";
"-I", Arg.String add_include,
"<dir> Add <dir> to the list of include directories";
"-s", Arg.String set_socket,
"<filename> Set the name of the communication socket";
"-version", Arg.Unit print_version,
" Print version and exit";
"-vnum", Arg.Unit print_version_num,
" Print version number and exit";
]
let function_placeholder () =
raise Not_found
let main () =
Callback.register "Debugger.function_placeholder" function_placeholder;
try
socket_name :=
(match Sys.os_type with
"Win32" ->
(Unix.string_of_inet_addr Unix.inet_addr_loopback)^
":"^
(string_of_int (10000 + ((Unix.getpid ()) mod 10000)))
| _ -> Filename.concat Filename.temp_dir_name
("camldebug" ^ (string_of_int (Unix.getpid ())))
);
begin try
Arg.parse speclist anonymous "";
Arg.usage speclist
"No program name specified\n\
Usage: ocamldebug [options] <program> [arguments]\n\
Options are:";
exit 2
with Found_program_name ->
for j = !Arg.current + 1 to Array.length Sys.argv - 1 do
arguments := !arguments ^ " " ^ (Filename.quote Sys.argv.(j))
done
end;
printf "\tOCaml Debugger version %s@.@." Config.version;
Config.load_path := !default_load_path;
Clflags.recursive_types := true; (* Allow recursive types. *)
Toplevel .
kill_program ();
exit 0
with
Toplevel ->
exit 2
| Env.Error e ->
eprintf "Debugger [version %s] environment error:@ @[@;" Config.version;
Env.report_error err_formatter e;
eprintf "@]@.";
exit 2
| Cmi_format.Error e ->
eprintf "Debugger [version %s] environment error:@ @[@;" Config.version;
Cmi_format.report_error err_formatter e;
eprintf "@]@.";
exit 2
let _ =
Printexc.catch (Unix.handle_unix_error main) ()
| null | https://raw.githubusercontent.com/thelema/ocaml-community/ed0a2424bbf13d1b33292725e089f0d7ba94b540/debugger/main.ml | ocaml | *********************************************************************
OCaml
*********************************************************************
Parsing of command-line arguments
Allow recursive types. | , projet Cristal , INRIA Rocquencourt
OCaml port by and
Copyright 1996 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the Q Public License version 1.0 .
open Input_handling
open Question
open Command_line
open Debugger_config
open Checkpoints
open Time_travel
open Parameters
open Program_management
open Frames
open Show_information
open Format
open Primitives
let line_buffer = Lexing.from_function read_user_input
let rec loop ppf =
line_loop ppf line_buffer;
if !loaded && (not (yes_or_no "The program is running. Quit anyway")) then
loop ppf
let current_duration = ref (-1L)
let rec protect ppf restart loop =
try
loop ppf
with
| End_of_file ->
protect ppf restart (function ppf ->
forget_process
!current_checkpoint.c_fd
!current_checkpoint.c_pid;
pp_print_flush ppf ();
stop_user_input ();
restart ppf)
| Toplevel ->
protect ppf restart (function ppf ->
pp_print_flush ppf ();
stop_user_input ();
restart ppf)
| Sys.Break ->
protect ppf restart (function ppf ->
fprintf ppf "Interrupted.@.";
Exec.protect (function () ->
stop_user_input ();
if !loaded then begin
try_select_frame 0;
show_current_event ppf;
end);
restart ppf)
| Current_checkpoint_lost ->
protect ppf restart (function ppf ->
fprintf ppf "Trying to recover...@.";
stop_user_input ();
recover ();
try_select_frame 0;
show_current_event ppf;
restart ppf)
| Current_checkpoint_lost_start_at (time, init_duration) ->
protect ppf restart (function ppf ->
let b =
if !current_duration = -1L then begin
let msg = sprintf "Restart from time %Ld and try to get closer of the problem" time in
stop_user_input ();
if yes_or_no msg then
(current_duration := init_duration; true)
else
false
end
else
true in
if b then
begin
go_to time;
current_duration := Int64.div !current_duration 10L;
if !current_duration > 0L then
while true do
step !current_duration
done
else begin
current_duration := -1L;
stop_user_input ();
show_current_event ppf;
restart ppf;
end
end
else
begin
recover ();
show_current_event ppf;
restart ppf
end)
| x ->
kill_program ();
raise x
let execute_file_if_any () =
let buffer = Buffer.create 128 in
begin
try
let base = ".ocamldebug" in
let file =
if Sys.file_exists base then
base
else
Filename.concat (Sys.getenv "HOME") base in
let ch = open_in file in
fprintf Format.std_formatter "Executing file %s@." file;
while true do
let line = string_trim (input_line ch) in
if line <> "" && line.[0] <> '#' then begin
Buffer.add_string buffer line;
Buffer.add_char buffer '\n'
end
done;
with _ -> ()
end;
let len = Buffer.length buffer in
if len > 0 then
let commands = Buffer.sub buffer 0 (pred len) in
line_loop Format.std_formatter (Lexing.from_string commands)
let toplevel_loop () =
interactif := false;
current_prompt := "";
execute_file_if_any ();
interactif := true;
current_prompt := debugger_prompt;
protect Format.std_formatter loop loop
exception Found_program_name
let anonymous s =
program_name := Unix_tools.make_absolute s; raise Found_program_name
let add_include d =
default_load_path :=
Misc.expand_directory Config.standard_library d :: !default_load_path
let set_socket s =
socket_name := s
let set_checkpoints n =
checkpoint_max_count := n
let set_directory dir =
Sys.chdir dir
let print_version () =
printf "The OCaml debugger, version %s@." Sys.ocaml_version;
exit 0;
;;
let print_version_num () =
printf "%s@." Sys.ocaml_version;
exit 0;
;;
let speclist = [
"-c", Arg.Int set_checkpoints,
"<count> Set max number of checkpoints kept";
"-cd", Arg.String set_directory,
"<dir> Change working directory";
"-emacs", Arg.Set emacs,
"For running the debugger under emacs";
"-I", Arg.String add_include,
"<dir> Add <dir> to the list of include directories";
"-s", Arg.String set_socket,
"<filename> Set the name of the communication socket";
"-version", Arg.Unit print_version,
" Print version and exit";
"-vnum", Arg.Unit print_version_num,
" Print version number and exit";
]
let function_placeholder () =
raise Not_found
let main () =
Callback.register "Debugger.function_placeholder" function_placeholder;
try
socket_name :=
(match Sys.os_type with
"Win32" ->
(Unix.string_of_inet_addr Unix.inet_addr_loopback)^
":"^
(string_of_int (10000 + ((Unix.getpid ()) mod 10000)))
| _ -> Filename.concat Filename.temp_dir_name
("camldebug" ^ (string_of_int (Unix.getpid ())))
);
begin try
Arg.parse speclist anonymous "";
Arg.usage speclist
"No program name specified\n\
Usage: ocamldebug [options] <program> [arguments]\n\
Options are:";
exit 2
with Found_program_name ->
for j = !Arg.current + 1 to Array.length Sys.argv - 1 do
arguments := !arguments ^ " " ^ (Filename.quote Sys.argv.(j))
done
end;
printf "\tOCaml Debugger version %s@.@." Config.version;
Config.load_path := !default_load_path;
Toplevel .
kill_program ();
exit 0
with
Toplevel ->
exit 2
| Env.Error e ->
eprintf "Debugger [version %s] environment error:@ @[@;" Config.version;
Env.report_error err_formatter e;
eprintf "@]@.";
exit 2
| Cmi_format.Error e ->
eprintf "Debugger [version %s] environment error:@ @[@;" Config.version;
Cmi_format.report_error err_formatter e;
eprintf "@]@.";
exit 2
let _ =
Printexc.catch (Unix.handle_unix_error main) ()
|
ec7af5ec3ac0365ab018ce93b5ace00fa2abf4f6e09822db00458beb7d99d2e5 | qkrgud55/ocamlmulti | location.ml | (***********************************************************************)
(* *)
(* OCaml *)
(* *)
, projet Cristal , INRIA Rocquencourt
(* *)
Copyright 1996 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the Q Public License version 1.0 .
(* *)
(***********************************************************************)
$ I d : location.ml 12511 2012 - 05 - 30 13:29:48Z lefessan $
open Lexing
let absname = ref false
This reference should be in Clflags , but it would create an additional
dependency and make bootstrapping more difficult .
dependency and make bootstrapping Camlp4 more difficult. *)
type t = { loc_start: position; loc_end: position; loc_ghost: bool };;
let in_file name =
let loc = {
pos_fname = name;
pos_lnum = 1;
pos_bol = 0;
pos_cnum = -1;
} in
{ loc_start = loc; loc_end = loc; loc_ghost = true }
;;
let none = in_file "_none_";;
let curr lexbuf = {
loc_start = lexbuf.lex_start_p;
loc_end = lexbuf.lex_curr_p;
loc_ghost = false
};;
let init lexbuf fname =
lexbuf.lex_curr_p <- {
pos_fname = fname;
pos_lnum = 1;
pos_bol = 0;
pos_cnum = 0;
}
;;
let symbol_rloc () = {
loc_start = Parsing.symbol_start_pos ();
loc_end = Parsing.symbol_end_pos ();
loc_ghost = false;
};;
let symbol_gloc () = {
loc_start = Parsing.symbol_start_pos ();
loc_end = Parsing.symbol_end_pos ();
loc_ghost = true;
};;
let rhs_loc n = {
loc_start = Parsing.rhs_start_pos n;
loc_end = Parsing.rhs_end_pos n;
loc_ghost = false;
};;
let input_name = ref "_none_"
let input_lexbuf = ref (None : lexbuf option)
(* Terminal info *)
let status = ref Terminfo.Uninitialised
let num_loc_lines = ref 0 (* number of lines already printed after input *)
(* Highlight the locations using standout mode. *)
let highlight_terminfo ppf num_lines lb loc1 loc2 =
Format.pp_print_flush ppf (); (* avoid mixing Format and normal output *)
Char 0 is at offset -lb.lex_abs_pos in lb.lex_buffer .
let pos0 = -lb.lex_abs_pos in
(* Do nothing if the buffer does not contain the whole phrase. *)
if pos0 < 0 then raise Exit;
(* Count number of lines in phrase *)
let lines = ref !num_loc_lines in
for i = pos0 to lb.lex_buffer_len - 1 do
if lb.lex_buffer.[i] = '\n' then incr lines
done;
(* If too many lines, give up *)
if !lines >= num_lines - 2 then raise Exit;
(* Move cursor up that number of lines *)
flush stdout; Terminfo.backup !lines;
(* Print the input, switching to standout for the location *)
let bol = ref false in
print_string "# ";
for pos = 0 to lb.lex_buffer_len - pos0 - 1 do
if !bol then (print_string " "; bol := false);
if pos = loc1.loc_start.pos_cnum || pos = loc2.loc_start.pos_cnum then
Terminfo.standout true;
if pos = loc1.loc_end.pos_cnum || pos = loc2.loc_end.pos_cnum then
Terminfo.standout false;
let c = lb.lex_buffer.[pos + pos0] in
print_char c;
bol := (c = '\n')
done;
(* Make sure standout mode is over *)
Terminfo.standout false;
(* Position cursor back to original location *)
Terminfo.resume !num_loc_lines;
flush stdout
(* Highlight the location by printing it again. *)
let highlight_dumb ppf lb loc =
Char 0 is at offset -lb.lex_abs_pos in lb.lex_buffer .
let pos0 = -lb.lex_abs_pos in
(* Do nothing if the buffer does not contain the whole phrase. *)
if pos0 < 0 then raise Exit;
let end_pos = lb.lex_buffer_len - pos0 - 1 in
(* Determine line numbers for the start and end points *)
let line_start = ref 0 and line_end = ref 0 in
for pos = 0 to end_pos do
if lb.lex_buffer.[pos + pos0] = '\n' then begin
if loc.loc_start.pos_cnum > pos then incr line_start;
if loc.loc_end.pos_cnum > pos then incr line_end;
end
done;
Print character location ( useful for Emacs )
Format.fprintf ppf "Characters %i-%i:@."
loc.loc_start.pos_cnum loc.loc_end.pos_cnum;
(* Print the input, underlining the location *)
Format.pp_print_string ppf " ";
let line = ref 0 in
let pos_at_bol = ref 0 in
for pos = 0 to end_pos do
let c = lb.lex_buffer.[pos + pos0] in
if c <> '\n' then begin
if !line = !line_start && !line = !line_end then
loc is on one line : print whole line
Format.pp_print_char ppf c
else if !line = !line_start then
first line of multiline loc : print ... before
if pos < loc.loc_start.pos_cnum
then Format.pp_print_char ppf '.'
else Format.pp_print_char ppf c
else if !line = !line_end then
(* last line of multiline loc: print ... after loc_end *)
if pos < loc.loc_end.pos_cnum
then Format.pp_print_char ppf c
else Format.pp_print_char ppf '.'
else if !line > !line_start && !line < !line_end then
intermediate line of multiline loc : print whole line
Format.pp_print_char ppf c
end else begin
if !line = !line_start && !line = !line_end then begin
loc is on one line : underline location
Format.fprintf ppf "@. ";
for i = !pos_at_bol to loc.loc_start.pos_cnum - 1 do
Format.pp_print_char ppf ' '
done;
for i = loc.loc_start.pos_cnum to loc.loc_end.pos_cnum - 1 do
Format.pp_print_char ppf '^'
done
end;
if !line >= !line_start && !line <= !line_end then begin
Format.fprintf ppf "@.";
if pos < loc.loc_end.pos_cnum then Format.pp_print_string ppf " "
end;
incr line;
pos_at_bol := pos + 1;
end
done
(* Highlight the location using one of the supported modes. *)
let rec highlight_locations ppf loc1 loc2 =
match !status with
Terminfo.Uninitialised ->
status := Terminfo.setup stdout; highlight_locations ppf loc1 loc2
| Terminfo.Bad_term ->
begin match !input_lexbuf with
None -> false
| Some lb ->
let norepeat =
try Sys.getenv "TERM" = "norepeat" with Not_found -> false in
if norepeat then false else
try highlight_dumb ppf lb loc1; true
with Exit -> false
end
| Terminfo.Good_term num_lines ->
begin match !input_lexbuf with
None -> false
| Some lb ->
try highlight_terminfo ppf num_lines lb loc1 loc2; true
with Exit -> false
end
(* Print the location in some way or another *)
open Format
let absolute_path s = (* This function could go into Filename *)
let open Filename in
let s = if is_relative s then concat (Sys.getcwd ()) s else s in
(* Now simplify . and .. components *)
let rec aux s =
let base = basename s in
let dir = dirname s in
if dir = s then dir
else if base = current_dir_name then aux dir
else if base = parent_dir_name then dirname (aux dir)
else concat (aux dir) base
in
aux s
let show_filename file =
if !absname then absolute_path file else file
let print_filename ppf file =
Format.fprintf ppf "%s" (show_filename file)
let reset () =
num_loc_lines := 0
let (msg_file, msg_line, msg_chars, msg_to, msg_colon) =
("File \"", "\", line ", ", characters ", "-", ":")
(* return file, line, char from the given position *)
let get_pos_info pos =
(pos.pos_fname, pos.pos_lnum, pos.pos_cnum - pos.pos_bol)
;;
let print_loc ppf loc =
let (file, line, startchar) = get_pos_info loc.loc_start in
let endchar = loc.loc_end.pos_cnum - loc.loc_start.pos_cnum + startchar in
if file = "//toplevel//" then begin
if highlight_locations ppf loc none then () else
fprintf ppf "Characters %i-%i"
loc.loc_start.pos_cnum loc.loc_end.pos_cnum
end else begin
fprintf ppf "%s%a%s%i" msg_file print_filename file msg_line line;
if startchar >= 0 then
fprintf ppf "%s%i%s%i" msg_chars startchar msg_to endchar
end
;;
let print ppf loc =
if loc.loc_start.pos_fname = "//toplevel//"
&& highlight_locations ppf loc none then ()
else fprintf ppf "%a%s@." print_loc loc msg_colon
;;
let print_error ppf loc =
print ppf loc;
fprintf ppf "Error: ";
;;
let print_error_cur_file ppf = print_error ppf (in_file !input_name);;
let print_warning loc ppf w =
if Warnings.is_active w then begin
let printw ppf w =
let n = Warnings.print ppf w in
num_loc_lines := !num_loc_lines + n
in
print ppf loc;
fprintf ppf "Warning %a@." printw w;
pp_print_flush ppf ();
incr num_loc_lines;
end
;;
let prerr_warning loc w = print_warning loc err_formatter w;;
let echo_eof () =
print_newline ();
incr num_loc_lines
type 'a loc = {
txt : 'a;
loc : t;
}
let mkloc txt loc = { txt ; loc }
let mknoloc txt = mkloc txt none
| null | https://raw.githubusercontent.com/qkrgud55/ocamlmulti/74fe84df0ce7be5ee03fb4ac0520fb3e9f4b6d1f/parsing/location.ml | ocaml | *********************************************************************
OCaml
*********************************************************************
Terminal info
number of lines already printed after input
Highlight the locations using standout mode.
avoid mixing Format and normal output
Do nothing if the buffer does not contain the whole phrase.
Count number of lines in phrase
If too many lines, give up
Move cursor up that number of lines
Print the input, switching to standout for the location
Make sure standout mode is over
Position cursor back to original location
Highlight the location by printing it again.
Do nothing if the buffer does not contain the whole phrase.
Determine line numbers for the start and end points
Print the input, underlining the location
last line of multiline loc: print ... after loc_end
Highlight the location using one of the supported modes.
Print the location in some way or another
This function could go into Filename
Now simplify . and .. components
return file, line, char from the given position | , projet Cristal , INRIA Rocquencourt
Copyright 1996 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the Q Public License version 1.0 .
$ I d : location.ml 12511 2012 - 05 - 30 13:29:48Z lefessan $
open Lexing
let absname = ref false
This reference should be in Clflags , but it would create an additional
dependency and make bootstrapping more difficult .
dependency and make bootstrapping Camlp4 more difficult. *)
type t = { loc_start: position; loc_end: position; loc_ghost: bool };;
let in_file name =
let loc = {
pos_fname = name;
pos_lnum = 1;
pos_bol = 0;
pos_cnum = -1;
} in
{ loc_start = loc; loc_end = loc; loc_ghost = true }
;;
let none = in_file "_none_";;
let curr lexbuf = {
loc_start = lexbuf.lex_start_p;
loc_end = lexbuf.lex_curr_p;
loc_ghost = false
};;
let init lexbuf fname =
lexbuf.lex_curr_p <- {
pos_fname = fname;
pos_lnum = 1;
pos_bol = 0;
pos_cnum = 0;
}
;;
let symbol_rloc () = {
loc_start = Parsing.symbol_start_pos ();
loc_end = Parsing.symbol_end_pos ();
loc_ghost = false;
};;
let symbol_gloc () = {
loc_start = Parsing.symbol_start_pos ();
loc_end = Parsing.symbol_end_pos ();
loc_ghost = true;
};;
let rhs_loc n = {
loc_start = Parsing.rhs_start_pos n;
loc_end = Parsing.rhs_end_pos n;
loc_ghost = false;
};;
let input_name = ref "_none_"
let input_lexbuf = ref (None : lexbuf option)
let status = ref Terminfo.Uninitialised
let highlight_terminfo ppf num_lines lb loc1 loc2 =
Char 0 is at offset -lb.lex_abs_pos in lb.lex_buffer .
let pos0 = -lb.lex_abs_pos in
if pos0 < 0 then raise Exit;
let lines = ref !num_loc_lines in
for i = pos0 to lb.lex_buffer_len - 1 do
if lb.lex_buffer.[i] = '\n' then incr lines
done;
if !lines >= num_lines - 2 then raise Exit;
flush stdout; Terminfo.backup !lines;
let bol = ref false in
print_string "# ";
for pos = 0 to lb.lex_buffer_len - pos0 - 1 do
if !bol then (print_string " "; bol := false);
if pos = loc1.loc_start.pos_cnum || pos = loc2.loc_start.pos_cnum then
Terminfo.standout true;
if pos = loc1.loc_end.pos_cnum || pos = loc2.loc_end.pos_cnum then
Terminfo.standout false;
let c = lb.lex_buffer.[pos + pos0] in
print_char c;
bol := (c = '\n')
done;
Terminfo.standout false;
Terminfo.resume !num_loc_lines;
flush stdout
let highlight_dumb ppf lb loc =
Char 0 is at offset -lb.lex_abs_pos in lb.lex_buffer .
let pos0 = -lb.lex_abs_pos in
if pos0 < 0 then raise Exit;
let end_pos = lb.lex_buffer_len - pos0 - 1 in
let line_start = ref 0 and line_end = ref 0 in
for pos = 0 to end_pos do
if lb.lex_buffer.[pos + pos0] = '\n' then begin
if loc.loc_start.pos_cnum > pos then incr line_start;
if loc.loc_end.pos_cnum > pos then incr line_end;
end
done;
Print character location ( useful for Emacs )
Format.fprintf ppf "Characters %i-%i:@."
loc.loc_start.pos_cnum loc.loc_end.pos_cnum;
Format.pp_print_string ppf " ";
let line = ref 0 in
let pos_at_bol = ref 0 in
for pos = 0 to end_pos do
let c = lb.lex_buffer.[pos + pos0] in
if c <> '\n' then begin
if !line = !line_start && !line = !line_end then
loc is on one line : print whole line
Format.pp_print_char ppf c
else if !line = !line_start then
first line of multiline loc : print ... before
if pos < loc.loc_start.pos_cnum
then Format.pp_print_char ppf '.'
else Format.pp_print_char ppf c
else if !line = !line_end then
if pos < loc.loc_end.pos_cnum
then Format.pp_print_char ppf c
else Format.pp_print_char ppf '.'
else if !line > !line_start && !line < !line_end then
intermediate line of multiline loc : print whole line
Format.pp_print_char ppf c
end else begin
if !line = !line_start && !line = !line_end then begin
loc is on one line : underline location
Format.fprintf ppf "@. ";
for i = !pos_at_bol to loc.loc_start.pos_cnum - 1 do
Format.pp_print_char ppf ' '
done;
for i = loc.loc_start.pos_cnum to loc.loc_end.pos_cnum - 1 do
Format.pp_print_char ppf '^'
done
end;
if !line >= !line_start && !line <= !line_end then begin
Format.fprintf ppf "@.";
if pos < loc.loc_end.pos_cnum then Format.pp_print_string ppf " "
end;
incr line;
pos_at_bol := pos + 1;
end
done
let rec highlight_locations ppf loc1 loc2 =
match !status with
Terminfo.Uninitialised ->
status := Terminfo.setup stdout; highlight_locations ppf loc1 loc2
| Terminfo.Bad_term ->
begin match !input_lexbuf with
None -> false
| Some lb ->
let norepeat =
try Sys.getenv "TERM" = "norepeat" with Not_found -> false in
if norepeat then false else
try highlight_dumb ppf lb loc1; true
with Exit -> false
end
| Terminfo.Good_term num_lines ->
begin match !input_lexbuf with
None -> false
| Some lb ->
try highlight_terminfo ppf num_lines lb loc1 loc2; true
with Exit -> false
end
open Format
let open Filename in
let s = if is_relative s then concat (Sys.getcwd ()) s else s in
let rec aux s =
let base = basename s in
let dir = dirname s in
if dir = s then dir
else if base = current_dir_name then aux dir
else if base = parent_dir_name then dirname (aux dir)
else concat (aux dir) base
in
aux s
let show_filename file =
if !absname then absolute_path file else file
let print_filename ppf file =
Format.fprintf ppf "%s" (show_filename file)
let reset () =
num_loc_lines := 0
let (msg_file, msg_line, msg_chars, msg_to, msg_colon) =
("File \"", "\", line ", ", characters ", "-", ":")
let get_pos_info pos =
(pos.pos_fname, pos.pos_lnum, pos.pos_cnum - pos.pos_bol)
;;
let print_loc ppf loc =
let (file, line, startchar) = get_pos_info loc.loc_start in
let endchar = loc.loc_end.pos_cnum - loc.loc_start.pos_cnum + startchar in
if file = "//toplevel//" then begin
if highlight_locations ppf loc none then () else
fprintf ppf "Characters %i-%i"
loc.loc_start.pos_cnum loc.loc_end.pos_cnum
end else begin
fprintf ppf "%s%a%s%i" msg_file print_filename file msg_line line;
if startchar >= 0 then
fprintf ppf "%s%i%s%i" msg_chars startchar msg_to endchar
end
;;
let print ppf loc =
if loc.loc_start.pos_fname = "//toplevel//"
&& highlight_locations ppf loc none then ()
else fprintf ppf "%a%s@." print_loc loc msg_colon
;;
let print_error ppf loc =
print ppf loc;
fprintf ppf "Error: ";
;;
let print_error_cur_file ppf = print_error ppf (in_file !input_name);;
let print_warning loc ppf w =
if Warnings.is_active w then begin
let printw ppf w =
let n = Warnings.print ppf w in
num_loc_lines := !num_loc_lines + n
in
print ppf loc;
fprintf ppf "Warning %a@." printw w;
pp_print_flush ppf ();
incr num_loc_lines;
end
;;
let prerr_warning loc w = print_warning loc err_formatter w;;
let echo_eof () =
print_newline ();
incr num_loc_lines
type 'a loc = {
txt : 'a;
loc : t;
}
let mkloc txt loc = { txt ; loc }
let mknoloc txt = mkloc txt none
|
2fa34ae49cbf5ebfc3d241f9a371f782b442e2160a40288628edc5bba8cd265a | marigold-dev/mankavar | das_test.ml | let () =
Printexc.record_backtrace true ;
Alcotest.run "DAS" [
Consensus_dummy_tests.tests ;
] | null | https://raw.githubusercontent.com/marigold-dev/mankavar/ac6bf1e327ef6a91777e7d045c0f7c0cf1fd0e6e/src/test/das_test.ml | ocaml | let () =
Printexc.record_backtrace true ;
Alcotest.run "DAS" [
Consensus_dummy_tests.tests ;
] | |
f76761a3f937e55e2b61a5015a39bb35b31817a660ffd7ffa5cda468548c5913 | qiao/sicp-solutions | 3.31.scm | ;; If we don't execute the action procedure immediately, then there will be no
;; actions stored in the agenda initially, and thus the simulation will fail.
| null | https://raw.githubusercontent.com/qiao/sicp-solutions/a2fe069ba6909710a0867bdb705b2e58b2a281af/chapter3/3.31.scm | scheme | If we don't execute the action procedure immediately, then there will be no
actions stored in the agenda initially, and thus the simulation will fail. | |
aaf19628229704629a3a19c1fb9dd48bd6db23fdfbb9c23b4dd06dd272a3d323 | Z572/guile-wlroots | time.scm | (define-module (wlroots time)
#:use-module (wlroots types)
#:use-module (wlroots utils)
#:use-module (rnrs bytevectors)
#:use-module (system foreign-library)
#:use-module (bytestructures guile)
#:use-module (oop goops)
#:use-module ((system foreign) #:prefix ffi:)
#:export (clock-gettime
wrap-timespec
unwrap-timespec
<timespec>
.tv-sec
.tv-nsec
value->clockid_t
clockid_t->value))
(define-enumeration value->clockid_t clockid_t->value
(CLOCK_REALTIME 0)
(CLOCK_MONOTONIC 1)
(CLOCK_PROCESS_CPUTIME_ID 2)
(CLOCK_THREAD_CPUTIME_ID 3)
(CLOCK_MONOTONIC_RAW 4)
(CLOCK_REALTIME_COARSE 5)
(CLOCK_MONOTONIC_COARSE 6)
(CLOCK_BOOTTIME 7)
(CLOCK_REALTIME_ALARM 8)
(CLOCK_BOOTTIME_ALARM 9)
(CLOCK_TAI 11))
(define-wlr-types-class timespec ()
(tv-sec #:allocation #:bytestructure #:accessor .tv-sec)
(tv-nsec #:allocation #:bytestructure #:accessor .tv-nsec)
#:descriptor %timespec-struct)
(define %clock-gettime
(foreign-library-function
#f "clock_gettime"
#:return-type ffi:int
#:arg-types (list ffi:int32 '*)))
(define* (clock-gettime clock-id #:optional (timespec (make <timespec>)))
(let* ((clock-id (if (symbol? clock-id) (clockid_t->value clock-id) clock-id))
(o (%clock-gettime clock-id (get-pointer timespec))))
(values o timespec)))
| null | https://raw.githubusercontent.com/Z572/guile-wlroots/c99fcbb8faa7ab2e4a76b4bb8deaf0ff52f9d12b/wlroots/time.scm | scheme | (define-module (wlroots time)
#:use-module (wlroots types)
#:use-module (wlroots utils)
#:use-module (rnrs bytevectors)
#:use-module (system foreign-library)
#:use-module (bytestructures guile)
#:use-module (oop goops)
#:use-module ((system foreign) #:prefix ffi:)
#:export (clock-gettime
wrap-timespec
unwrap-timespec
<timespec>
.tv-sec
.tv-nsec
value->clockid_t
clockid_t->value))
(define-enumeration value->clockid_t clockid_t->value
(CLOCK_REALTIME 0)
(CLOCK_MONOTONIC 1)
(CLOCK_PROCESS_CPUTIME_ID 2)
(CLOCK_THREAD_CPUTIME_ID 3)
(CLOCK_MONOTONIC_RAW 4)
(CLOCK_REALTIME_COARSE 5)
(CLOCK_MONOTONIC_COARSE 6)
(CLOCK_BOOTTIME 7)
(CLOCK_REALTIME_ALARM 8)
(CLOCK_BOOTTIME_ALARM 9)
(CLOCK_TAI 11))
(define-wlr-types-class timespec ()
(tv-sec #:allocation #:bytestructure #:accessor .tv-sec)
(tv-nsec #:allocation #:bytestructure #:accessor .tv-nsec)
#:descriptor %timespec-struct)
(define %clock-gettime
(foreign-library-function
#f "clock_gettime"
#:return-type ffi:int
#:arg-types (list ffi:int32 '*)))
(define* (clock-gettime clock-id #:optional (timespec (make <timespec>)))
(let* ((clock-id (if (symbol? clock-id) (clockid_t->value clock-id) clock-id))
(o (%clock-gettime clock-id (get-pointer timespec))))
(values o timespec)))
| |
f5d58e357939a23a52abc5a6c3352aaa47cdf33bbd58ef00244d0f208a4e2634 | xmonad/xmonad-contrib | OrgMode.hs | # OPTIONS_GHC -Wno - orphans #
# OPTIONS_GHC -Wno - incomplete - patterns #
# LANGUAGE InstanceSigs #
# LANGUAGE TypeApplications #
# LANGUAGE TupleSections #
# LANGUAGE LambdaCase #
module OrgMode where
import XMonad.Prelude hiding ((!?))
import XMonad.Prompt.OrgMode
import qualified Data.Map.Strict as Map
import Data.Map.Strict (Map, (!), (!?))
import Test.Hspec
import Test.Hspec.QuickCheck
import Test.QuickCheck
spec :: Spec
spec = do
prop "prop_encodePreservation" prop_encodePreservation
prop "prop_decodePreservation" prop_decodePreservation
-- Checking for regressions
describe "pInput" $ do
it "works with todo +d 22 january 2021" $ do
pInput "todo +d 22 ja 2021"
`shouldBe` Just
( Deadline
"todo"
(Time {date = Date (22, Just 1, Just 2021), tod = Nothing})
NoPriority
)
it "works with todo +d 22 01 2022" $ do
pInput "todo +d 22 01 2022"
`shouldBe` Just
( Deadline
"todo"
(Time {date = Date (22, Just 1, Just 2022), tod = Nothing})
NoPriority
)
it "works with todo +d 1 01:01" $ do
pInput "todo +d 1 01:01"
`shouldBe` Just
( Deadline
"todo"
(Time {date = Date (1, Nothing, Nothing), tod = Just $ TimeOfDay 1 1})
NoPriority
)
it "works with todo +d 22 jan 2021 01:01 #b" $ do
pInput "todo +d 22 jan 2021 01:01 #b"
`shouldBe` Just
( Deadline
"todo"
(Time {date = Date (22, Just 1, Just 2021), tod = Just $ TimeOfDay 1 1})
B
)
context "no priority#b" $ do
it "parses to the correct thing" $
pInput "no priority#b"
`shouldBe` Just (NormalMsg "no priority#b" NoPriority)
it "encode" $ prop_encodePreservation (OrgMsg "no priority#b")
it "decode" $ prop_decodePreservation (NormalMsg "no priority#b" NoPriority)
context "+d +d f" $ do
it "encode" $ prop_encodePreservation (OrgMsg "+d +d f")
it "decode" $ prop_decodePreservation (Deadline "+d" (Time {date = Next Friday, tod = Nothing}) NoPriority)
context "+d f 1 +d f #c" $ do
it "encode" $ prop_encodePreservation (OrgMsg "+d +d f")
it "decode" $ prop_decodePreservation (Deadline "+d" (Time {date = Next Friday, tod = Nothing}) C)
context "+d f 1 +d f" $ do
it "encode" $ prop_encodePreservation (OrgMsg "+d f 1 +d f")
it "decode" $ prop_decodePreservation (Deadline "+d f 1" (Time {date = Next Friday, tod = Nothing}) NoPriority)
context "+d f 1 +d f #b" $ do
it "encode" $ prop_encodePreservation (OrgMsg "+d f 1 +d f #b")
it "decode" $ prop_decodePreservation (Deadline "+d f 1" (Time {date = Next Friday, tod = Nothing}) B)
-- | Parsing preserves all info that printing does.
prop_encodePreservation :: OrgMsg -> Property
prop_encodePreservation (OrgMsg s) = pInput s === (pInput . ppNote =<< pInput s)
-- | Printing preserves all info that parsing does.
prop_decodePreservation :: Note -> Property
prop_decodePreservation n = Just (ppNote n) === (fmap ppNote . pInput $ ppNote n)
------------------------------------------------------------------------
-- Pretty Printing
ppNote :: Note -> String
ppNote = \case
Scheduled str t p -> str <> " +s " <> ppTime t <> ppPrio p
Deadline str t p -> str <> " +d " <> ppTime t <> ppPrio p
NormalMsg str p -> str <> ppPrio p
ppPrio :: Priority -> String
ppPrio = \case
NoPriority -> ""
prio -> " #" <> show prio
ppTime :: Time -> String
ppTime (Time d t) = ppDate d <> ppTOD t
where
ppTOD :: Maybe TimeOfDay -> String
ppTOD = maybe "" ((' ' :) . show)
ppDate :: Date -> String
ppDate dte = case days !? dte of
Just v -> v
Nothing -> case d of -- only way it can't be in the map
Date (d', mbM, mbY) -> show d'
<> maybe "" ((' ' :) . (months !)) mbM
<> maybe "" ((' ' :) . show) mbY
------------------------------------------------------------------------
-- Arbitrary Instances
-- | An arbitrary (correct) message string.
newtype OrgMsg = OrgMsg String
deriving (Show)
instance Arbitrary OrgMsg where
arbitrary :: Gen OrgMsg
arbitrary
= OrgMsg <$> randomString -- note
<<>> elements [" +s ", " +d ", ""] <<>> dateGen <<>> hourGen -- time and date
<<>> elements ("" : map (reverse . (: " #")) "AaBbCc") -- priority
where
dateGen :: Gen String
dateGen = oneof
[ pure $ days ! Today
, pure $ days ! Tomorrow
, elements $ (days !) . Next <$> [Monday .. Sunday]
17
17 jan
17 jan 2021
17 01
17 01 2021
]
where
rNat, rYear, rMonth :: Gen String
rNat = show <$> posInt
rMonth = show <$> posInt `suchThat` (<= 12)
rYear = show <$> posInt `suchThat` (> 25)
monthGen :: Gen String
monthGen = elements $ Map.elems months
hourGen :: Gen String
hourGen = oneof
[ pure " " <<>> (pad <$> hourInt) <<>> pure ":" <<>> (pad <$> minuteInt)
, pure " " <<>> (pad <$> hourInt) <<>> (pad <$> minuteInt)
, pure ""
]
where
pad :: Int -> String
pad n = (if n <= 9 then "0" else "") <> show n
instance Arbitrary Note where
arbitrary :: Gen Note
arbitrary = do
msg <- randomString
t <- arbitrary
p <- arbitrary
elements [Scheduled msg t p, Deadline msg t p, NormalMsg msg p]
instance Arbitrary Priority where
arbitrary :: Gen Priority
arbitrary = elements [A, B, C, NoPriority]
instance Arbitrary Time where
arbitrary :: Gen Time
arbitrary = Time <$> arbitrary <*> arbitrary
instance Arbitrary Date where
arbitrary :: Gen Date
arbitrary = oneof
[ pure Today
, pure Tomorrow
, Next . toEnum <$> choose (0, 6)
, do d <- posInt
m <- mbPos `suchThat` (<= Just 12)
Date . (d, m, ) <$> if isNothing m
then pure Nothing
else mbPos `suchThat` (>= Just 25)
]
instance Arbitrary TimeOfDay where
arbitrary :: Gen TimeOfDay
arbitrary = TimeOfDay <$> hourInt <*> minuteInt
------------------------------------------------------------------------
-- Util
randomString :: Gen String
randomString = listOf arbitraryPrintableChar <<>> (noSpace <&> (: []))
where
noSpace :: Gen Char
noSpace = arbitraryPrintableChar `suchThat` (/= ' ')
days :: Map Date String
days = Map.fromList
[ (Today, "tod"), (Tomorrow, "tom"), (Next Monday, "m"), (Next Tuesday, "tu")
, (Next Wednesday, "w"), (Next Thursday, "th"), (Next Friday, "f")
, (Next Saturday,"sa"), (Next Sunday,"su")
]
months :: Map Int String
months = Map.fromList
[ (1, "ja"), (2, "f"), (3, "mar"), (4, "ap"), (5, "may"), (6, "jun")
, (7, "jul"), (8, "au"), (9, "s"), (10, "o"), (11, "n"), (12, "d")
]
posInt :: Gen Int
posInt = getPositive <$> arbitrary @(Positive Int)
hourInt :: Gen Int
hourInt = posInt `suchThat` (<= 23)
minuteInt :: Gen Int
minuteInt = posInt `suchThat` (<= 59)
mbPos :: Num a => Gen (Maybe a)
mbPos = fmap (fromIntegral . getPositive) <$> arbitrary @(Maybe (Positive Int))
infixr 6 <<>>
(<<>>) :: (Applicative f, Monoid a) => f a -> f a -> f a
(<<>>) = liftA2 (<>)
| null | https://raw.githubusercontent.com/xmonad/xmonad-contrib/1c6ae39fc9181f9610b90529af7b148840f427b2/tests/OrgMode.hs | haskell | Checking for regressions
| Parsing preserves all info that printing does.
| Printing preserves all info that parsing does.
----------------------------------------------------------------------
Pretty Printing
only way it can't be in the map
----------------------------------------------------------------------
Arbitrary Instances
| An arbitrary (correct) message string.
note
time and date
priority
----------------------------------------------------------------------
Util | # OPTIONS_GHC -Wno - orphans #
# OPTIONS_GHC -Wno - incomplete - patterns #
# LANGUAGE InstanceSigs #
# LANGUAGE TypeApplications #
# LANGUAGE TupleSections #
# LANGUAGE LambdaCase #
module OrgMode where
import XMonad.Prelude hiding ((!?))
import XMonad.Prompt.OrgMode
import qualified Data.Map.Strict as Map
import Data.Map.Strict (Map, (!), (!?))
import Test.Hspec
import Test.Hspec.QuickCheck
import Test.QuickCheck
spec :: Spec
spec = do
prop "prop_encodePreservation" prop_encodePreservation
prop "prop_decodePreservation" prop_decodePreservation
describe "pInput" $ do
it "works with todo +d 22 january 2021" $ do
pInput "todo +d 22 ja 2021"
`shouldBe` Just
( Deadline
"todo"
(Time {date = Date (22, Just 1, Just 2021), tod = Nothing})
NoPriority
)
it "works with todo +d 22 01 2022" $ do
pInput "todo +d 22 01 2022"
`shouldBe` Just
( Deadline
"todo"
(Time {date = Date (22, Just 1, Just 2022), tod = Nothing})
NoPriority
)
it "works with todo +d 1 01:01" $ do
pInput "todo +d 1 01:01"
`shouldBe` Just
( Deadline
"todo"
(Time {date = Date (1, Nothing, Nothing), tod = Just $ TimeOfDay 1 1})
NoPriority
)
it "works with todo +d 22 jan 2021 01:01 #b" $ do
pInput "todo +d 22 jan 2021 01:01 #b"
`shouldBe` Just
( Deadline
"todo"
(Time {date = Date (22, Just 1, Just 2021), tod = Just $ TimeOfDay 1 1})
B
)
context "no priority#b" $ do
it "parses to the correct thing" $
pInput "no priority#b"
`shouldBe` Just (NormalMsg "no priority#b" NoPriority)
it "encode" $ prop_encodePreservation (OrgMsg "no priority#b")
it "decode" $ prop_decodePreservation (NormalMsg "no priority#b" NoPriority)
context "+d +d f" $ do
it "encode" $ prop_encodePreservation (OrgMsg "+d +d f")
it "decode" $ prop_decodePreservation (Deadline "+d" (Time {date = Next Friday, tod = Nothing}) NoPriority)
context "+d f 1 +d f #c" $ do
it "encode" $ prop_encodePreservation (OrgMsg "+d +d f")
it "decode" $ prop_decodePreservation (Deadline "+d" (Time {date = Next Friday, tod = Nothing}) C)
context "+d f 1 +d f" $ do
it "encode" $ prop_encodePreservation (OrgMsg "+d f 1 +d f")
it "decode" $ prop_decodePreservation (Deadline "+d f 1" (Time {date = Next Friday, tod = Nothing}) NoPriority)
context "+d f 1 +d f #b" $ do
it "encode" $ prop_encodePreservation (OrgMsg "+d f 1 +d f #b")
it "decode" $ prop_decodePreservation (Deadline "+d f 1" (Time {date = Next Friday, tod = Nothing}) B)
prop_encodePreservation :: OrgMsg -> Property
prop_encodePreservation (OrgMsg s) = pInput s === (pInput . ppNote =<< pInput s)
prop_decodePreservation :: Note -> Property
prop_decodePreservation n = Just (ppNote n) === (fmap ppNote . pInput $ ppNote n)
ppNote :: Note -> String
ppNote = \case
Scheduled str t p -> str <> " +s " <> ppTime t <> ppPrio p
Deadline str t p -> str <> " +d " <> ppTime t <> ppPrio p
NormalMsg str p -> str <> ppPrio p
ppPrio :: Priority -> String
ppPrio = \case
NoPriority -> ""
prio -> " #" <> show prio
ppTime :: Time -> String
ppTime (Time d t) = ppDate d <> ppTOD t
where
ppTOD :: Maybe TimeOfDay -> String
ppTOD = maybe "" ((' ' :) . show)
ppDate :: Date -> String
ppDate dte = case days !? dte of
Just v -> v
Date (d', mbM, mbY) -> show d'
<> maybe "" ((' ' :) . (months !)) mbM
<> maybe "" ((' ' :) . show) mbY
newtype OrgMsg = OrgMsg String
deriving (Show)
instance Arbitrary OrgMsg where
arbitrary :: Gen OrgMsg
arbitrary
where
dateGen :: Gen String
dateGen = oneof
[ pure $ days ! Today
, pure $ days ! Tomorrow
, elements $ (days !) . Next <$> [Monday .. Sunday]
17
17 jan
17 jan 2021
17 01
17 01 2021
]
where
rNat, rYear, rMonth :: Gen String
rNat = show <$> posInt
rMonth = show <$> posInt `suchThat` (<= 12)
rYear = show <$> posInt `suchThat` (> 25)
monthGen :: Gen String
monthGen = elements $ Map.elems months
hourGen :: Gen String
hourGen = oneof
[ pure " " <<>> (pad <$> hourInt) <<>> pure ":" <<>> (pad <$> minuteInt)
, pure " " <<>> (pad <$> hourInt) <<>> (pad <$> minuteInt)
, pure ""
]
where
pad :: Int -> String
pad n = (if n <= 9 then "0" else "") <> show n
instance Arbitrary Note where
arbitrary :: Gen Note
arbitrary = do
msg <- randomString
t <- arbitrary
p <- arbitrary
elements [Scheduled msg t p, Deadline msg t p, NormalMsg msg p]
instance Arbitrary Priority where
arbitrary :: Gen Priority
arbitrary = elements [A, B, C, NoPriority]
instance Arbitrary Time where
arbitrary :: Gen Time
arbitrary = Time <$> arbitrary <*> arbitrary
instance Arbitrary Date where
arbitrary :: Gen Date
arbitrary = oneof
[ pure Today
, pure Tomorrow
, Next . toEnum <$> choose (0, 6)
, do d <- posInt
m <- mbPos `suchThat` (<= Just 12)
Date . (d, m, ) <$> if isNothing m
then pure Nothing
else mbPos `suchThat` (>= Just 25)
]
instance Arbitrary TimeOfDay where
arbitrary :: Gen TimeOfDay
arbitrary = TimeOfDay <$> hourInt <*> minuteInt
randomString :: Gen String
randomString = listOf arbitraryPrintableChar <<>> (noSpace <&> (: []))
where
noSpace :: Gen Char
noSpace = arbitraryPrintableChar `suchThat` (/= ' ')
days :: Map Date String
days = Map.fromList
[ (Today, "tod"), (Tomorrow, "tom"), (Next Monday, "m"), (Next Tuesday, "tu")
, (Next Wednesday, "w"), (Next Thursday, "th"), (Next Friday, "f")
, (Next Saturday,"sa"), (Next Sunday,"su")
]
months :: Map Int String
months = Map.fromList
[ (1, "ja"), (2, "f"), (3, "mar"), (4, "ap"), (5, "may"), (6, "jun")
, (7, "jul"), (8, "au"), (9, "s"), (10, "o"), (11, "n"), (12, "d")
]
posInt :: Gen Int
posInt = getPositive <$> arbitrary @(Positive Int)
hourInt :: Gen Int
hourInt = posInt `suchThat` (<= 23)
minuteInt :: Gen Int
minuteInt = posInt `suchThat` (<= 59)
mbPos :: Num a => Gen (Maybe a)
mbPos = fmap (fromIntegral . getPositive) <$> arbitrary @(Maybe (Positive Int))
infixr 6 <<>>
(<<>>) :: (Applicative f, Monoid a) => f a -> f a -> f a
(<<>>) = liftA2 (<>)
|
dd97e481cedd10c9fa7cdeab4d41c274bb42b9a1b4bbc0897ea4133a10284e07 | tezos/tezos-mirror | validate.ml | (*****************************************************************************)
(* *)
(* Open Source License *)
Copyright ( c ) 2022 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. *)
(* *)
(*****************************************************************************)
open Validate_errors
open Alpha_context
type consensus_info = {
predecessor_level : Raw_level.t;
predecessor_round : Round.t;
preendorsement_slot_map : (Consensus_key.pk * int) Slot.Map.t;
endorsement_slot_map : (Consensus_key.pk * int) Slot.Map.t;
}
let init_consensus_info ctxt (predecessor_level, predecessor_round) =
{
predecessor_level;
predecessor_round;
preendorsement_slot_map = Consensus.allowed_preendorsements ctxt;
endorsement_slot_map = Consensus.allowed_endorsements ctxt;
}
* Map used to detect consensus operation conflicts . Each delegate
may ( pre)endorse at most once for each level and round , so two
endorsements ( resp . two preendorsements ) conflict when they have
the same slot , level , and round .
Note that when validating a block , all endorsements ( resp . all
preendorsements ) must have the same level and round anyway , so only
the slot is relevant . Taking the level and round into account is
useful in mempool mode , because we want to be able to accept and
propagate consensus operations for multiple close
past / future / cousin blocks .
may (pre)endorse at most once for each level and round, so two
endorsements (resp. two preendorsements) conflict when they have
the same slot, level, and round.
Note that when validating a block, all endorsements (resp. all
preendorsements) must have the same level and round anyway, so only
the slot is relevant. Taking the level and round into account is
useful in mempool mode, because we want to be able to accept and
propagate consensus operations for multiple close
past/future/cousin blocks. *)
module Consensus_conflict_map = Map.Make (struct
type t = Slot.t * Raw_level.t * Round.t
let compare (slot1, level1, round1) (slot2, level2, round2) =
Compare.or_else (Raw_level.compare level1 level2) @@ fun () ->
Compare.or_else (Slot.compare slot1 slot2) @@ fun () ->
Round.compare round1 round2
end)
type consensus_state = {
preendorsements_seen : Operation_hash.t Consensus_conflict_map.t;
endorsements_seen : Operation_hash.t Consensus_conflict_map.t;
dal_attestation_seen : Operation_hash.t Signature.Public_key_hash.Map.t;
}
let consensus_conflict_map_encoding =
let open Data_encoding in
conv
(fun map -> Consensus_conflict_map.bindings map)
(fun l ->
Consensus_conflict_map.(
List.fold_left (fun m (k, v) -> add k v m) empty l))
(list
(tup2
(tup3 Slot.encoding Raw_level.encoding Round.encoding)
Operation_hash.encoding))
let consensus_state_encoding =
let open Data_encoding in
def "consensus_state"
@@ conv
(fun {preendorsements_seen; endorsements_seen; dal_attestation_seen} ->
(preendorsements_seen, endorsements_seen, dal_attestation_seen))
(fun (preendorsements_seen, endorsements_seen, dal_attestation_seen) ->
{preendorsements_seen; endorsements_seen; dal_attestation_seen})
(obj3
(req "preendorsements_seen" consensus_conflict_map_encoding)
(req "endorsements_seen" consensus_conflict_map_encoding)
(req
"dal_attestation_seen"
(Signature.Public_key_hash.Map.encoding Operation_hash.encoding)))
let empty_consensus_state =
{
preendorsements_seen = Consensus_conflict_map.empty;
endorsements_seen = Consensus_conflict_map.empty;
dal_attestation_seen = Signature.Public_key_hash.Map.empty;
}
type voting_state = {
proposals_seen : Operation_hash.t Signature.Public_key_hash.Map.t;
* To each delegate that has submitted a Proposals operation in a
previously validated operation , associates the hash of this
operation . This includes Proposals from a potential Testnet
Dictator .
previously validated operation, associates the hash of this
operation. This includes Proposals from a potential Testnet
Dictator. *)
ballots_seen : Operation_hash.t Signature.Public_key_hash.Map.t;
(** To each delegate that has submitted a ballot in a previously
validated operation, associates the hash of this operation. *)
}
let voting_state_encoding =
let open Data_encoding in
def "voting_state"
@@ conv
(fun {proposals_seen; ballots_seen} -> (proposals_seen, ballots_seen))
(fun (proposals_seen, ballots_seen) -> {proposals_seen; ballots_seen})
(obj2
(req
"proposals_seen"
(Signature.Public_key_hash.Map.encoding Operation_hash.encoding))
(req
"ballots_seen"
(Signature.Public_key_hash.Map.encoding Operation_hash.encoding)))
module Double_baking_evidence_map = struct
include Map.Make (struct
type t = Raw_level.t * Round.t
let compare (l, r) (l', r') =
Compare.or_else (Raw_level.compare l l') @@ fun () ->
Compare.or_else (Round.compare r r') @@ fun () -> 0
end)
let encoding elt_encoding =
Data_encoding.conv
(fun map -> bindings map)
(fun l -> List.fold_left (fun m (k, v) -> add k v m) empty l)
Data_encoding.(
list (tup2 (tup2 Raw_level.encoding Round.encoding) elt_encoding))
end
module Double_endorsing_evidence_map = struct
include Map.Make (struct
type t = Raw_level.t * Round.t * Slot.t
let compare (l, r, s) (l', r', s') =
Compare.or_else (Raw_level.compare l l') @@ fun () ->
Compare.or_else (Round.compare r r') @@ fun () ->
Compare.or_else (Slot.compare s s') @@ fun () -> 0
end)
let encoding elt_encoding =
Data_encoding.conv
(fun map -> bindings map)
(fun l -> List.fold_left (fun m (k, v) -> add k v m) empty l)
Data_encoding.(
list
(tup2
(tup3 Raw_level.encoding Round.encoding Slot.encoding)
elt_encoding))
end
(** State used and modified when validating anonymous operations.
These fields are used to enforce that we do not validate the same
operation multiple times.
Note that as part of {!state}, these maps live
in memory. They are not explicitly bounded here, however:
- In block validation mode, they are bounded by the number of
anonymous operations allowed in the block.
- In mempool mode, bounding the number of operations in this map
is the responsability of the prevalidator on the shell side. *)
type anonymous_state = {
activation_pkhs_seen : Operation_hash.t Ed25519.Public_key_hash.Map.t;
double_baking_evidences_seen : Operation_hash.t Double_baking_evidence_map.t;
double_endorsing_evidences_seen :
Operation_hash.t Double_endorsing_evidence_map.t;
seed_nonce_levels_seen : Operation_hash.t Raw_level.Map.t;
vdf_solution_seen : Operation_hash.t option;
}
let raw_level_map_encoding elt_encoding =
let open Data_encoding in
conv
(fun map -> Raw_level.Map.bindings map)
(fun l ->
Raw_level.Map.(List.fold_left (fun m (k, v) -> add k v m) empty l))
(list (tup2 Raw_level.encoding elt_encoding))
let anonymous_state_encoding =
let open Data_encoding in
def "anonymous_state"
@@ conv
(fun {
activation_pkhs_seen;
double_baking_evidences_seen;
double_endorsing_evidences_seen;
seed_nonce_levels_seen;
vdf_solution_seen;
} ->
( activation_pkhs_seen,
double_baking_evidences_seen,
double_endorsing_evidences_seen,
seed_nonce_levels_seen,
vdf_solution_seen ))
(fun ( activation_pkhs_seen,
double_baking_evidences_seen,
double_endorsing_evidences_seen,
seed_nonce_levels_seen,
vdf_solution_seen ) ->
{
activation_pkhs_seen;
double_baking_evidences_seen;
double_endorsing_evidences_seen;
seed_nonce_levels_seen;
vdf_solution_seen;
})
(obj5
(req
"activation_pkhs_seen"
(Ed25519.Public_key_hash.Map.encoding Operation_hash.encoding))
(req
"double_baking_evidences_seen"
(Double_baking_evidence_map.encoding Operation_hash.encoding))
(req
"double_endorsing_evidences_seen"
(Double_endorsing_evidence_map.encoding Operation_hash.encoding))
(req
"seed_nonce_levels_seen"
(raw_level_map_encoding Operation_hash.encoding))
(opt "vdf_solution_seen" Operation_hash.encoding))
let empty_anonymous_state =
{
activation_pkhs_seen = Ed25519.Public_key_hash.Map.empty;
double_baking_evidences_seen = Double_baking_evidence_map.empty;
double_endorsing_evidences_seen = Double_endorsing_evidence_map.empty;
seed_nonce_levels_seen = Raw_level.Map.empty;
vdf_solution_seen = None;
}
(** Static information used to validate manager operations. *)
type manager_info = {
hard_storage_limit_per_operation : Z.t;
hard_gas_limit_per_operation : Gas.Arith.integral;
}
let init_manager_info ctxt =
{
hard_storage_limit_per_operation =
Constants.hard_storage_limit_per_operation ctxt;
hard_gas_limit_per_operation = Constants.hard_gas_limit_per_operation ctxt;
}
(** State used and modified when validating manager operations. *)
type manager_state = {
managers_seen : Operation_hash.t Signature.Public_key_hash.Map.t;
* To enforce the one - operation - per manager - per - block restriction
( 1 M ) . The operation hash lets us indicate the conflicting
operation in the { ! Manager_restriction } error .
Note that as part of { ! state } , this map
lives in memory . It is not explicitly bounded here , however :
- In block validation mode , it is bounded by the number of
manager operations allowed in the block .
- In mempool mode , bounding the number of operations in this
map is the responsability of the mempool . ( E.g. the plugin used
by has a [ max_prechecked_manager_operations ] parameter to
ensure this . )
(1M). The operation hash lets us indicate the conflicting
operation in the {!Manager_restriction} error.
Note that as part of {!state}, this map
lives in memory. It is not explicitly bounded here, however:
- In block validation mode, it is bounded by the number of
manager operations allowed in the block.
- In mempool mode, bounding the number of operations in this
map is the responsability of the mempool. (E.g. the plugin used
by Octez has a [max_prechecked_manager_operations] parameter to
ensure this.) *)
}
let manager_state_encoding =
let open Data_encoding in
def "manager_state"
@@ conv
(fun {managers_seen} -> managers_seen)
(fun managers_seen -> {managers_seen})
(obj1
(req
"managers_seen"
(Signature.Public_key_hash.Map.encoding Operation_hash.encoding)))
let empty_manager_state = {managers_seen = Signature.Public_key_hash.Map.empty}
(** Information needed to validate consensus operations and/or to
finalize the block in both modes that handle a preexisting block:
[Application] and [Partial_validation]. *)
type block_info = {
round : Round.t;
locked_round : Round.t option;
predecessor_hash : Block_hash.t;
block_producer : Consensus_key.pk;
payload_producer : Consensus_key.pk;
header_contents : Block_header.contents;
}
(** Information needed to validate consensus operations and/or to
finalize the block in [Construction] mode. *)
type construction_info = {
round : Round.t;
predecessor_hash : Block_hash.t;
block_producer : Consensus_key.pk;
payload_producer : Consensus_key.pk;
header_contents : Block_header.contents;
}
(** Circumstances in which operations are validated, and corresponding
specific information.
If you add a new mode, please make sure that it has a way to bound
the size of the maps in the {!operation_conflict_state}. *)
type mode =
| Application of block_info
(** [Application] is used for the validation of a preexisting block,
often in preparation for its future application. *)
| Partial_validation of block_info
(** [Partial_validation] is used to quickly but partially validate a
preexisting block, e.g. to quickly decide whether an alternate
branch seems viable. In this mode, the initial {!type:context} may
come from an ancestor block instead of the predecessor block. Only
consensus operations are validated in this mode. *)
| Construction of construction_info
(** Used for the construction of a new block. *)
| Mempool
(** Used by the mempool ({!module:Mempool_validation}) and by the
[Partial_construction] mode in {!module:Main}, which may itself be
used by RPCs or by another mempool implementation. *)
* { 2 Definition and initialization of [ info ] and [ state ] }
type info = {
ctxt : t; (** The context at the beginning of the block or mempool. *)
mode : mode;
chain_id : Chain_id.t; (** Needed for signature checks. *)
current_level : Level.t;
consensus_info : consensus_info option;
(** Needed to validate consensus operations. This can be [None] during
some RPC calls when some predecessor information is unavailable,
in which case the validation of all consensus operations will
systematically fail. *)
manager_info : manager_info;
}
type operation_conflict_state = {
consensus_state : consensus_state;
voting_state : voting_state;
anonymous_state : anonymous_state;
manager_state : manager_state;
}
let operation_conflict_state_encoding =
let open Data_encoding in
def "operation_conflict_state"
@@ conv
(fun {consensus_state; voting_state; anonymous_state; manager_state} ->
(consensus_state, voting_state, anonymous_state, manager_state))
(fun (consensus_state, voting_state, anonymous_state, manager_state) ->
{consensus_state; voting_state; anonymous_state; manager_state})
(obj4
(req "consensus_state" consensus_state_encoding)
(req "voting_state" voting_state_encoding)
(req "anonymous_state" anonymous_state_encoding)
(req "manager_state" manager_state_encoding))
type block_state = {
op_count : int;
remaining_block_gas : Gas.Arith.fp;
recorded_operations_rev : Operation_hash.t list;
last_op_validation_pass : int option;
locked_round_evidence : (Round.t * int) option;
endorsement_power : int;
}
type validation_state = {
info : info;
operation_state : operation_conflict_state;
block_state : block_state;
}
let ok_unit = Result_syntax.return_unit
let init_info ctxt mode chain_id ~predecessor_level_and_round =
let consensus_info =
Option.map (init_consensus_info ctxt) predecessor_level_and_round
in
{
ctxt;
mode;
chain_id;
current_level = Level.current ctxt;
consensus_info;
manager_info = init_manager_info ctxt;
}
let empty_voting_state =
{
proposals_seen = Signature.Public_key_hash.Map.empty;
ballots_seen = Signature.Public_key_hash.Map.empty;
}
let empty_operation_conflict_state =
{
consensus_state = empty_consensus_state;
voting_state = empty_voting_state;
anonymous_state = empty_anonymous_state;
manager_state = empty_manager_state;
}
let init_block_state vi =
{
op_count = 0;
remaining_block_gas =
Gas.Arith.fp (Constants.hard_gas_limit_per_block vi.ctxt);
recorded_operations_rev = [];
last_op_validation_pass = None;
locked_round_evidence = None;
endorsement_power = 0;
}
let get_initial_ctxt {info; _} = info.ctxt
(** Validation of consensus operations (validation pass [0]):
preendorsement, endorsement, and dal_attestation. *)
module Consensus = struct
open Validate_errors.Consensus
let check_frozen_deposits_are_positive ctxt delegate_pkh =
let open Lwt_result_syntax in
let* frozen_deposits = Delegate.frozen_deposits ctxt delegate_pkh in
fail_unless
Tez.(frozen_deposits.current_amount > zero)
(Zero_frozen_deposits delegate_pkh)
let get_delegate_details slot_map kind slot =
Result.of_option
(Slot.Map.find slot slot_map)
~error:(trace_of_error (Wrong_slot_used_for_consensus_operation {kind}))
(** When validating a block (ie. in [Application],
[Partial_validation], and [Construction] modes), any
preendorsements must point to a round that is strictly before the
block's round. *)
let check_round_before_block ~block_round provided =
error_unless
Round.(provided < block_round)
(Preendorsement_round_too_high {block_round; provided})
let check_level kind expected provided =
(* We use [if] instead of [error_unless] to avoid computing the
error when it is not needed. *)
if Raw_level.equal expected provided then Result.return_unit
else if Raw_level.(expected > provided) then
error (Consensus_operation_for_old_level {kind; expected; provided})
else error (Consensus_operation_for_future_level {kind; expected; provided})
let check_round kind expected provided =
(* We use [if] instead of [error_unless] to avoid computing the
error when it is not needed. *)
if Round.equal expected provided then Result.return_unit
else if Round.(expected > provided) then
error (Consensus_operation_for_old_round {kind; expected; provided})
else error (Consensus_operation_for_future_round {kind; expected; provided})
let check_payload_hash kind expected provided =
error_unless
(Block_payload_hash.equal expected provided)
(Wrong_payload_hash_for_consensus_operation {kind; expected; provided})
(** Preendorsement checks for both [Application] and
[Partial_validation] modes.
Return the slot owner's consensus key and voting power. *)
let check_preexisting_block_preendorsement vi consensus_info block_info
{level; round; block_payload_hash = bph; slot} =
let open Lwt_result_syntax in
let*? locked_round =
match block_info.locked_round with
| Some locked_round -> ok locked_round
| None ->
(* A preexisting block whose fitness has no locked round
should contain no preendorsements. *)
error Unexpected_preendorsement_in_block
in
let kind = Preendorsement in
let*? () = check_round_before_block ~block_round:block_info.round round in
let*? () = check_level kind vi.current_level.level level in
let*? () = check_round kind locked_round round in
let expected_payload_hash = block_info.header_contents.payload_hash in
let*? () = check_payload_hash kind expected_payload_hash bph in
let*? consensus_key, voting_power =
get_delegate_details consensus_info.preendorsement_slot_map kind slot
in
let* () =
check_frozen_deposits_are_positive vi.ctxt consensus_key.delegate
in
return (consensus_key, voting_power)
(** Preendorsement checks for Construction mode.
Return the slot owner's consensus key and voting power. *)
let check_constructed_block_preendorsement vi consensus_info cons_info
{level; round; block_payload_hash = bph; slot} =
let open Lwt_result_syntax in
let expected_payload_hash = cons_info.header_contents.payload_hash in
let*? () =
When the proposal is fresh , a fake [ payload_hash ] of [ zero ]
has been provided . In this case , the block should not contain
any preendorsements .
has been provided. In this case, the block should not contain
any preendorsements. *)
error_when
Block_payload_hash.(expected_payload_hash = zero)
Unexpected_preendorsement_in_block
in
let kind = Preendorsement in
let*? () = check_round_before_block ~block_round:cons_info.round round in
let*? () = check_level kind vi.current_level.level level in
(* We cannot check the exact round here in construction mode, because
there is no preexisting fitness to provide the locked_round. We do
however check that all preendorments have the same round in
[check_construction_preendorsement_round_consistency] further below. *)
let*? () = check_payload_hash kind expected_payload_hash bph in
let*? consensus_key, voting_power =
get_delegate_details consensus_info.preendorsement_slot_map kind slot
in
let* () =
check_frozen_deposits_are_positive vi.ctxt consensus_key.delegate
in
return (consensus_key, voting_power)
* Preendorsement / endorsement checks for mode .
We want this mode to be very permissive , to allow the mempool to
accept and propagate consensus operations even if they point to a
block which is not known to the ( e.g. because the block
has just been validated and the mempool has not had time to
switch its head to it yet , or because the block belongs to a
cousin branch ) . Therefore , we do not check the round nor the
payload , which may correspond to blocks that we do not know of
yet . As to the level , we only require it to be the
[ predecessor_level ] ( aka the level of the mempool 's head ) plus or
minus one , that is :
[ predecessor_level - 1 < = op_level < = predecessor_level + 1 ]
( note that [ predecessor_level + 1 ] is also known as [ current_level ] ) .
Return the slot owner 's consensus key and voting power ( the
latter may be fake because it does n't matter in mode , but
it is included to mirror the check_ ... _block_preendorsement
functions ) .
We want this mode to be very permissive, to allow the mempool to
accept and propagate consensus operations even if they point to a
block which is not known to the mempool (e.g. because the block
has just been validated and the mempool has not had time to
switch its head to it yet, or because the block belongs to a
cousin branch). Therefore, we do not check the round nor the
payload, which may correspond to blocks that we do not know of
yet. As to the level, we only require it to be the
[predecessor_level] (aka the level of the mempool's head) plus or
minus one, that is:
[predecessor_level - 1 <= op_level <= predecessor_level + 1]
(note that [predecessor_level + 1] is also known as [current_level]).
Return the slot owner's consensus key and voting power (the
latter may be fake because it doesn't matter in Mempool mode, but
it is included to mirror the check_..._block_preendorsement
functions). *)
let check_mempool_consensus vi consensus_info kind {level; slot; _} =
let open Lwt_result_syntax in
let*? () =
if Raw_level.(succ level < consensus_info.predecessor_level) then
let expected = consensus_info.predecessor_level and provided = level in
error (Consensus_operation_for_old_level {kind; expected; provided})
else if Raw_level.(level > vi.current_level.level) then
let expected = consensus_info.predecessor_level and provided = level in
error (Consensus_operation_for_future_level {kind; expected; provided})
else ok_unit
in
if Raw_level.(level = consensus_info.predecessor_level) then
(* The operation points to the mempool head's level, which is
the level for which slot maps have been pre-computed. *)
let slot_map =
match kind with
| Preendorsement -> consensus_info.preendorsement_slot_map
| Endorsement -> consensus_info.endorsement_slot_map
| Dal_attestation -> assert false
in
Lwt.return (get_delegate_details slot_map kind slot)
else
We do n't have a pre - computed slot map for the operation 's
level , so we retrieve the key directly from the context . We
return a fake voting power since it wo n't be used anyway in
mode .
level, so we retrieve the key directly from the context. We
return a fake voting power since it won't be used anyway in
Mempool mode. *)
let* (_ctxt : t), consensus_key =
Stake_distribution.slot_owner
vi.ctxt
(Level.from_raw vi.ctxt level)
slot
in
return (consensus_key, 0 (* Fake voting power *))
(* We do not check that the frozen deposits are positive because this
only needs to be true in the context of a block that actually
contains the operation, which may not be the same as the current
mempool's context. *)
let check_preendorsement vi ~check_signature
(operation : Kind.preendorsement operation) =
let open Lwt_result_syntax in
let*? consensus_info =
Option.value_e
~error:(trace_of_error Consensus_operation_not_allowed)
vi.consensus_info
in
let (Single (Preendorsement consensus_content)) =
operation.protocol_data.contents
in
let* consensus_key, voting_power =
match vi.mode with
| Application block_info | Partial_validation block_info ->
check_preexisting_block_preendorsement
vi
consensus_info
block_info
consensus_content
| Construction construction_info ->
check_constructed_block_preendorsement
vi
consensus_info
construction_info
consensus_content
| Mempool ->
check_mempool_consensus
vi
consensus_info
Preendorsement
consensus_content
in
let*? () =
if check_signature then
Operation.check_signature
consensus_key.consensus_pk
vi.chain_id
operation
else ok_unit
in
return voting_power
let check_preendorsement_conflict vs oph (op : Kind.preendorsement operation)
=
let (Single (Preendorsement {slot; level; round; _})) =
op.protocol_data.contents
in
match
Consensus_conflict_map.find_opt
(slot, level, round)
vs.consensus_state.preendorsements_seen
with
| Some existing ->
Error (Operation_conflict {existing; new_operation = oph})
| None -> ok_unit
let wrap_preendorsement_conflict = function
| Ok () -> ok_unit
| Error conflict ->
error
Validate_errors.Consensus.(
Conflicting_consensus_operation {kind = Preendorsement; conflict})
let add_preendorsement vs oph (op : Kind.preendorsement operation) =
let (Single (Preendorsement {slot; level; round; _})) =
op.protocol_data.contents
in
let preendorsements_seen =
Consensus_conflict_map.add
(slot, level, round)
oph
vs.consensus_state.preendorsements_seen
in
{vs with consensus_state = {vs.consensus_state with preendorsements_seen}}
let may_update_locked_round_evidence block_state mode
(consensus_content : consensus_content) voting_power =
let locked_round_evidence =
match mode with
| Mempool -> (* The block_state is not relevant in this mode. *) None
| Application _ | Partial_validation _ | Construction _ -> (
match block_state.locked_round_evidence with
| None -> Some (consensus_content.round, voting_power)
| Some (_stored_round, evidences) ->
[ _ stored_round ] is always equal to [ consensus_content.round ] .
Indeed , this is ensured by
{ ! } in
application and partial validation modes , and by
{ ! check_construction_preendorsement_round_consistency } in
construction mode .
Indeed, this is ensured by
{!check_preendorsement_content_preexisting_block} in
application and partial validation modes, and by
{!check_construction_preendorsement_round_consistency} in
construction mode. *)
Some (consensus_content.round, evidences + voting_power))
in
{block_state with locked_round_evidence}
(* Hypothesis: this function will only be called in mempool mode *)
let remove_preendorsement vs (operation : Kind.preendorsement operation) =
As we are in mempool mode , we do not update
[ locked_round_evidence ] .
[locked_round_evidence]. *)
let (Single (Preendorsement {slot; level; round; _})) =
operation.protocol_data.contents
in
let preendorsements_seen =
Consensus_conflict_map.remove
(slot, level, round)
vs.consensus_state.preendorsements_seen
in
{vs with consensus_state = {vs.consensus_state with preendorsements_seen}}
(** Endorsement checks for all modes that involve a block:
Application, Partial_validation, and Construction.
Return the slot owner's consensus key and voting power. *)
let check_block_endorsement vi consensus_info
{level; round; block_payload_hash = bph; slot} =
let open Lwt_result_syntax in
let*? expected_payload_hash =
match Consensus.endorsement_branch vi.ctxt with
| Some ((_branch : Block_hash.t), payload_hash) -> ok payload_hash
| None ->
[ Consensus.endorsement_branch ] only returns [ None ] when the
predecessor is the block that activates the first protocol
of the family ; this block should not be
endorsed . This can only happen in tests and test
networks .
predecessor is the block that activates the first protocol
of the Tenderbake family; this block should not be
endorsed. This can only happen in tests and test
networks. *)
error Unexpected_endorsement_in_block
in
let kind = Endorsement in
let*? () = check_level kind consensus_info.predecessor_level level in
let*? () = check_round kind consensus_info.predecessor_round round in
let*? () = check_payload_hash kind expected_payload_hash bph in
let*? consensus_key, voting_power =
get_delegate_details consensus_info.endorsement_slot_map kind slot
in
let* () =
check_frozen_deposits_are_positive vi.ctxt consensus_key.delegate
in
return (consensus_key, voting_power)
let check_endorsement vi ~check_signature
(operation : Kind.endorsement operation) =
let open Lwt_result_syntax in
let*? consensus_info =
Option.value_e
~error:(trace_of_error Consensus_operation_not_allowed)
vi.consensus_info
in
let (Single (Endorsement consensus_content)) =
operation.protocol_data.contents
in
let* consensus_key, voting_power =
match vi.mode with
| Application _ | Partial_validation _ | Construction _ ->
check_block_endorsement vi consensus_info consensus_content
| Mempool ->
check_mempool_consensus
vi
consensus_info
Endorsement
consensus_content
in
let*? () =
if check_signature then
Operation.check_signature
consensus_key.consensus_pk
vi.chain_id
operation
else ok_unit
in
return voting_power
let check_endorsement_conflict vs oph (operation : Kind.endorsement operation)
=
let (Single (Endorsement {slot; level; round; _})) =
operation.protocol_data.contents
in
match
Consensus_conflict_map.find_opt
(slot, level, round)
vs.consensus_state.endorsements_seen
with
| None -> ok_unit
| Some existing ->
Error (Operation_conflict {existing; new_operation = oph})
let wrap_endorsement_conflict = function
| Ok () -> ok_unit
| Error conflict ->
error
Validate_errors.Consensus.(
Conflicting_consensus_operation {kind = Endorsement; conflict})
let add_endorsement vs oph (op : Kind.endorsement operation) =
let (Single (Endorsement {slot; level; round; _})) =
op.protocol_data.contents
in
let endorsements_seen =
Consensus_conflict_map.add
(slot, level, round)
oph
vs.consensus_state.endorsements_seen
in
{vs with consensus_state = {vs.consensus_state with endorsements_seen}}
let may_update_endorsement_power vi block_state voting_power =
match vi.mode with
| Mempool -> (* The block_state is not relevant. *) block_state
| Application _ | Partial_validation _ | Construction _ ->
{
block_state with
endorsement_power = block_state.endorsement_power + voting_power;
}
(* Hypothesis: this function will only be called in mempool mode *)
let remove_endorsement vs (operation : Kind.endorsement operation) =
(* We do not remove the endorsement power because it is not
relevant for the mempool mode. *)
let (Single (Endorsement {slot; level; round; _})) =
operation.protocol_data.contents
in
let endorsements_seen =
Consensus_conflict_map.remove
(slot, level, round)
vs.consensus_state.endorsements_seen
in
{vs with consensus_state = {vs.consensus_state with endorsements_seen}}
let check_dal_attestation vi (operation : Kind.dal_attestation operation) =
DAL / FIXME /-/issues/3115
This is a temporary operation . Some checks are missing for the
moment . In particular , the signature is not
checked . Consequently , it is really important to ensure this
operation can not be included into a block when the feature flag
is not set . This is done in order to avoid modifying the
endorsement encoding . However , once the DAL is ready , this
operation should be merged with an endorsement or at least
refined .
This is a temporary operation. Some checks are missing for the
moment. In particular, the signature is not
checked. Consequently, it is really important to ensure this
operation cannot be included into a block when the feature flag
is not set. This is done in order to avoid modifying the
endorsement encoding. However, once the DAL is ready, this
operation should be merged with an endorsement or at least
refined. *)
let open Lwt_result_syntax in
let (Single (Dal_attestation op)) = operation.protocol_data.contents in
let*? () =
(* Note that this function checks the dal feature flag. *)
Dal_apply.validate_attestation vi.ctxt op
in
return_unit
let check_dal_attestation_conflict vs oph
(operation : Kind.dal_attestation operation) =
let (Single (Dal_attestation {attestor; attestation = _; level = _})) =
operation.protocol_data.contents
in
match
Signature.Public_key_hash.Map.find_opt
attestor
vs.consensus_state.dal_attestation_seen
with
| None -> ok_unit
| Some existing ->
Error (Operation_conflict {existing; new_operation = oph})
let wrap_dal_attestation_conflict = function
| Ok () -> ok_unit
| Error conflict ->
error
Validate_errors.Consensus.(
Conflicting_consensus_operation {kind = Dal_attestation; conflict})
let add_dal_attestation vs oph (operation : Kind.dal_attestation operation) =
let (Single (Dal_attestation {attestor; attestation = _; level = _})) =
operation.protocol_data.contents
in
{
vs with
consensus_state =
{
vs.consensus_state with
dal_attestation_seen =
Signature.Public_key_hash.Map.add
attestor
oph
vs.consensus_state.dal_attestation_seen;
};
}
let remove_dal_attestation vs (operation : Kind.dal_attestation operation) =
let (Single (Dal_attestation {attestor; attestation = _; level = _})) =
operation.protocol_data.contents
in
let dal_attestation_seen =
Signature.Public_key_hash.Map.remove
attestor
vs.consensus_state.dal_attestation_seen
in
{vs with consensus_state = {vs.consensus_state with dal_attestation_seen}}
* In Construction mode , check that the preendorsement has the same
round as any previously validated preendorsements .
This check is not needed in other modes because
{ ! check_preendorsement } already checks that all preendorsements
have the same expected round ( the locked_round in Application and
Partial_validation modes when there is one ( otherwise all
preendorsements are rejected so the point is moot ) , or the
predecessor_round in mode ) .
round as any previously validated preendorsements.
This check is not needed in other modes because
{!check_preendorsement} already checks that all preendorsements
have the same expected round (the locked_round in Application and
Partial_validation modes when there is one (otherwise all
preendorsements are rejected so the point is moot), or the
predecessor_round in Mempool mode). *)
let check_construction_preendorsement_round_consistency vi block_state
(consensus_content : consensus_content) =
let open Result_syntax in
match vi.mode with
| Construction _ -> (
match block_state.locked_round_evidence with
| None ->
This is the first validated preendorsement :
there is nothing to check .
there is nothing to check. *)
return_unit
| Some (expected, _power) ->
(* Other preendorsements have already been validated: we check
that the current operation has the same round as them. *)
check_round Preendorsement expected consensus_content.round)
| Application _ | Partial_validation _ | Mempool -> return_unit
let validate_preendorsement ~check_signature info operation_state block_state
oph (operation : Kind.preendorsement operation) =
let open Lwt_result_syntax in
let (Single (Preendorsement consensus_content)) =
operation.protocol_data.contents
in
let* voting_power = check_preendorsement info ~check_signature operation in
let*? () =
check_construction_preendorsement_round_consistency
info
block_state
consensus_content
in
let*? () =
check_preendorsement_conflict operation_state oph operation
|> wrap_preendorsement_conflict
in
(* We need to update the block state *)
let block_state =
may_update_locked_round_evidence
block_state
info.mode
consensus_content
voting_power
in
let operation_state = add_preendorsement operation_state oph operation in
return {info; operation_state; block_state}
let validate_endorsement ~check_signature info operation_state block_state oph
operation =
let open Lwt_result_syntax in
let* power = check_endorsement info ~check_signature operation in
let*? () =
check_endorsement_conflict operation_state oph operation
|> wrap_endorsement_conflict
in
let block_state = may_update_endorsement_power info block_state power in
let operation_state = add_endorsement operation_state oph operation in
return {info; operation_state; block_state}
end
* { 2 Validation of voting operations }
There are two kinds of voting operations :
- Proposals : A delegate submits a list of protocol amendment
proposals . This operation is only accepted during a Proposal period
( see above ) .
- Ballot : A delegate casts a vote for / against the current proposal
( or pass ) . This operation is only accepted during an Exploration
or Promotion period ( see above ) .
There are two kinds of voting operations:
- Proposals: A delegate submits a list of protocol amendment
proposals. This operation is only accepted during a Proposal period
(see above).
- Ballot: A delegate casts a vote for/against the current proposal
(or pass). This operation is only accepted during an Exploration
or Promotion period (see above). *)
module Voting = struct
open Validate_errors.Voting
let check_period_index ~expected period_index =
error_unless
Compare.Int32.(expected = period_index)
(Wrong_voting_period_index {expected; provided = period_index})
let check_proposals_source_is_registered ctxt source =
let open Lwt_result_syntax in
let*! is_registered = Delegate.registered ctxt source in
fail_unless is_registered (Proposals_from_unregistered_delegate source)
(** Check that the list of proposals is not empty and does not contain
duplicates. *)
let check_proposal_list_sanity proposals =
let open Result_syntax in
let* () =
match proposals with [] -> error Empty_proposals | _ :: _ -> ok_unit
in
let* (_ : Protocol_hash.Set.t) =
List.fold_left_e
(fun previous_elements proposal ->
let* () =
error_when
(Protocol_hash.Set.mem proposal previous_elements)
(Proposals_contain_duplicate {proposal})
in
return (Protocol_hash.Set.add proposal previous_elements))
Protocol_hash.Set.empty
proposals
in
return_unit
let check_period_kind_for_proposals current_period =
match current_period.Voting_period.kind with
| Proposal -> ok_unit
| (Exploration | Cooldown | Promotion | Adoption) as current ->
error (Wrong_voting_period_kind {current; expected = [Proposal]})
let check_in_listings ctxt source =
let open Lwt_result_syntax in
let*! in_listings = Vote.in_listings ctxt source in
fail_unless in_listings Source_not_in_vote_listings
let check_count ~count_in_ctxt ~proposals_length =
(* The proposal count of the proposer in the context should never
have been increased above [max_proposals_per_delegate]. *)
assert (Compare.Int.(count_in_ctxt <= Constants.max_proposals_per_delegate)) ;
error_unless
Compare.Int.(
count_in_ctxt + proposals_length <= Constants.max_proposals_per_delegate)
(Too_many_proposals
{previous_count = count_in_ctxt; operation_count = proposals_length})
let check_already_proposed ctxt proposer proposals =
let open Lwt_result_syntax in
List.iter_es
(fun proposal ->
let*! already_proposed = Vote.has_proposed ctxt proposer proposal in
fail_when already_proposed (Already_proposed {proposal}))
proposals
* Check that the [ apply_testnet_dictator_proposals ] function in
{ ! module : Amendment } will not fail .
The current function is designed to be exclusively called by
[ check_proposals ] right below .
@return [ Error Testnet_dictator_multiple_proposals ] if
[ proposals ] has more than one element .
{!module:Amendment} will not fail.
The current function is designed to be exclusively called by
[check_proposals] right below.
@return [Error Testnet_dictator_multiple_proposals] if
[proposals] has more than one element. *)
let check_testnet_dictator_proposals chain_id proposals =
(* This assertion should be ensured by the fact that
{!Amendment.is_testnet_dictator} cannot be [true] on mainnet
(so the current function cannot be called there). However, we
still double check it because of its criticality. *)
assert (Chain_id.(chain_id <> Constants.mainnet_id)) ;
match proposals with
| [] | [_] ->
(* In [Amendment.apply_testnet_dictator_proposals], the call to
{!Vote.init_current_proposal} (in the singleton list case)
cannot fail because {!Vote.clear_current_proposal} is called
right before.
The calls to
{!Voting_period.Testnet_dictator.overwrite_current_kind} may
usually fail when the voting period is not
initialized. However, this cannot happen here because the
current function is only called in [check_proposals] after a
successful call to {!Voting_period.get_current}. *)
ok_unit
| _ :: _ :: _ -> error Testnet_dictator_multiple_proposals
* Check that a Proposals operation can be safely applied .
@return [ Error Wrong_voting_period_index ] if the operation 's
period and the current period in the { ! type : context } do not have
the same index .
@return [ Error Proposals_from_unregistered_delegate ] if the
source is not a registered delegate .
@return [ Error Empty_proposals ] if the list of proposals is empty .
@return [ Error Proposals_contain_duplicate ] if the list of
proposals contains a duplicate element .
@return [ Error Wrong_voting_period_kind ] if the voting period is
not of the Proposal kind .
@return [ Error Source_not_in_vote_listings ] if the source is not
in the vote listings .
@return [ Error Too_many_proposals ] if the operation causes the
source 's total number of proposals during the current voting
period to exceed { ! Constants.max_proposals_per_delegate } .
@return [ Error Already_proposed ] if one of the proposals has
already been proposed by the source in the current voting period .
@return [ Error Testnet_dictator_multiple_proposals ] if the
source is a testnet dictator and the operation contains more than
one proposal .
@return [ Error Operation . Missing_signature ] or [ Error
Operation . Invalid_signature ] if the operation is unsigned or
incorrectly signed .
@return [Error Wrong_voting_period_index] if the operation's
period and the current period in the {!type:context} do not have
the same index.
@return [Error Proposals_from_unregistered_delegate] if the
source is not a registered delegate.
@return [Error Empty_proposals] if the list of proposals is empty.
@return [Error Proposals_contain_duplicate] if the list of
proposals contains a duplicate element.
@return [Error Wrong_voting_period_kind] if the voting period is
not of the Proposal kind.
@return [Error Source_not_in_vote_listings] if the source is not
in the vote listings.
@return [Error Too_many_proposals] if the operation causes the
source's total number of proposals during the current voting
period to exceed {!Constants.max_proposals_per_delegate}.
@return [Error Already_proposed] if one of the proposals has
already been proposed by the source in the current voting period.
@return [Error Testnet_dictator_multiple_proposals] if the
source is a testnet dictator and the operation contains more than
one proposal.
@return [Error Operation.Missing_signature] or [Error
Operation.Invalid_signature] if the operation is unsigned or
incorrectly signed. *)
let check_proposals vi ~check_signature (operation : Kind.proposals operation)
=
let open Lwt_result_syntax in
let (Single (Proposals {source; period; proposals})) =
operation.protocol_data.contents
in
let* current_period = Voting_period.get_current vi.ctxt in
let*? () = check_period_index ~expected:current_period.index period in
let* () =
if Amendment.is_testnet_dictator vi.ctxt vi.chain_id source then
let*? () = check_testnet_dictator_proposals vi.chain_id proposals in
return_unit
else
let* () = check_proposals_source_is_registered vi.ctxt source in
let*? () = check_proposal_list_sanity proposals in
let*? () = check_period_kind_for_proposals current_period in
let* () = check_in_listings vi.ctxt source in
let* count_in_ctxt = Vote.get_delegate_proposal_count vi.ctxt source in
let proposals_length = List.length proposals in
let*? () = check_count ~count_in_ctxt ~proposals_length in
check_already_proposed vi.ctxt source proposals
in
if check_signature then
(* Retrieving the public key should not fail as it *should* be
called after checking that the delegate is in the vote
listings (or is a testnet dictator), which implies that it
is a manager with a revealed key. *)
let* public_key = Contract.get_manager_key vi.ctxt source in
Lwt.return (Operation.check_signature public_key vi.chain_id operation)
else return_unit
* Check that a Proposals operation is compatible with previously
validated operations in the current block / mempool .
@return [ Error Operation_conflict ] if the current block / mempool
already contains a Proposals operation from the same source
( regardless of whether this source is a testnet dictator or an
ordinary manager ) .
validated operations in the current block/mempool.
@return [Error Operation_conflict] if the current block/mempool
already contains a Proposals operation from the same source
(regardless of whether this source is a testnet dictator or an
ordinary manager). *)
let check_proposals_conflict vs oph (operation : Kind.proposals operation) =
let open Result_syntax in
let (Single (Proposals {source; _})) = operation.protocol_data.contents in
match
Signature.Public_key_hash.Map.find_opt
source
vs.voting_state.proposals_seen
with
| None -> return_unit
| Some existing ->
Error (Operation_conflict {existing; new_operation = oph})
let wrap_proposals_conflict = function
| Ok () -> ok_unit
| Error conflict ->
error Validate_errors.Voting.(Conflicting_proposals conflict)
let add_proposals vs oph (operation : Kind.proposals operation) =
let (Single (Proposals {source; _})) = operation.protocol_data.contents in
let proposals_seen =
Signature.Public_key_hash.Map.add
source
oph
vs.voting_state.proposals_seen
in
let voting_state = {vs.voting_state with proposals_seen} in
{vs with voting_state}
let remove_proposals vs (operation : Kind.proposals operation) =
let (Single (Proposals {source; _})) = operation.protocol_data.contents in
let proposals_seen =
Signature.Public_key_hash.Map.remove source vs.voting_state.proposals_seen
in
{vs with voting_state = {vs.voting_state with proposals_seen}}
let check_ballot_source_is_registered ctxt source =
let open Lwt_result_syntax in
let*! is_registered = Delegate.registered ctxt source in
fail_unless is_registered (Ballot_from_unregistered_delegate source)
let check_period_kind_for_ballot current_period =
match current_period.Voting_period.kind with
| Exploration | Promotion -> ok_unit
| (Cooldown | Proposal | Adoption) as current ->
error
(Wrong_voting_period_kind
{current; expected = [Exploration; Promotion]})
let check_current_proposal ctxt op_proposal =
let open Lwt_result_syntax in
let* current_proposal = Vote.get_current_proposal ctxt in
fail_unless
(Protocol_hash.equal op_proposal current_proposal)
(Ballot_for_wrong_proposal
{current = current_proposal; submitted = op_proposal})
let check_source_has_not_already_voted ctxt source =
let open Lwt_result_syntax in
let*! has_ballot = Vote.has_recorded_ballot ctxt source in
fail_when has_ballot Already_submitted_a_ballot
* Check that a Ballot operation can be safely applied .
@return [ Error Ballot_from_unregistered_delegate ] if the source
is not a registered delegate .
@return [ Error Wrong_voting_period_index ] if the operation 's
period and the current period in the { ! type : context } do not have
the same index .
@return [ Error Wrong_voting_period_kind ] if the voting period is
not of the Exploration or Promotion kind .
@return [ Error Ballot_for_wrong_proposal ] if the operation 's
proposal is different from the current proposal in the context .
@return [ Error Already_submitted_a_ballot ] if the source has
already voted during the current voting period .
@return [ Error Source_not_in_vote_listings ] if the source is not
in the vote listings .
@return [ Error Operation . Missing_signature ] or [ Error
Operation . Invalid_signature ] if the operation is unsigned or
incorrectly signed .
@return [Error Ballot_from_unregistered_delegate] if the source
is not a registered delegate.
@return [Error Wrong_voting_period_index] if the operation's
period and the current period in the {!type:context} do not have
the same index.
@return [Error Wrong_voting_period_kind] if the voting period is
not of the Exploration or Promotion kind.
@return [Error Ballot_for_wrong_proposal] if the operation's
proposal is different from the current proposal in the context.
@return [Error Already_submitted_a_ballot] if the source has
already voted during the current voting period.
@return [Error Source_not_in_vote_listings] if the source is not
in the vote listings.
@return [Error Operation.Missing_signature] or [Error
Operation.Invalid_signature] if the operation is unsigned or
incorrectly signed. *)
let check_ballot vi ~check_signature (operation : Kind.ballot operation) =
let open Lwt_result_syntax in
let (Single (Ballot {source; period; proposal; ballot = _})) =
operation.protocol_data.contents
in
let* () = check_ballot_source_is_registered vi.ctxt source in
let* current_period = Voting_period.get_current vi.ctxt in
let*? () = check_period_index ~expected:current_period.index period in
let*? () = check_period_kind_for_ballot current_period in
let* () = check_current_proposal vi.ctxt proposal in
let* () = check_source_has_not_already_voted vi.ctxt source in
let* () = check_in_listings vi.ctxt source in
when_ check_signature (fun () ->
(* Retrieving the public key cannot fail. Indeed, we have
already checked that the delegate is in the vote listings,
which implies that it is a manager with a revealed key. *)
let* public_key = Contract.get_manager_key vi.ctxt source in
Lwt.return (Operation.check_signature public_key vi.chain_id operation))
* Check that a Ballot operation is compatible with previously
validated operations in the current block / mempool .
@return [ Error Operation_conflict ] if the current block / mempool
already contains a Ballot operation from the same source .
validated operations in the current block/mempool.
@return [Error Operation_conflict] if the current block/mempool
already contains a Ballot operation from the same source. *)
let check_ballot_conflict vs oph (operation : Kind.ballot operation) =
let (Single (Ballot {source; _})) = operation.protocol_data.contents in
match
Signature.Public_key_hash.Map.find_opt source vs.voting_state.ballots_seen
with
| None -> ok_unit
| Some existing ->
Error (Operation_conflict {existing; new_operation = oph})
let wrap_ballot_conflict = function
| Ok () -> ok_unit
| Error conflict -> error (Conflicting_ballot conflict)
let add_ballot vs oph (operation : Kind.ballot operation) =
let (Single (Ballot {source; _})) = operation.protocol_data.contents in
let ballots_seen =
Signature.Public_key_hash.Map.add source oph vs.voting_state.ballots_seen
in
let voting_state = {vs.voting_state with ballots_seen} in
{vs with voting_state}
let remove_ballot vs (operation : Kind.ballot operation) =
let (Single (Ballot {source; _})) = operation.protocol_data.contents in
let ballots_seen =
Signature.Public_key_hash.Map.remove source vs.voting_state.ballots_seen
in
{vs with voting_state = {vs.voting_state with ballots_seen}}
end
module Anonymous = struct
open Validate_errors.Anonymous
let check_activate_account vi (operation : Kind.activate_account operation) =
let (Single (Activate_account {id = edpkh; activation_code})) =
operation.protocol_data.contents
in
let open Lwt_result_syntax in
let blinded_pkh =
Blinded_public_key_hash.of_ed25519_pkh activation_code edpkh
in
let*! exists = Commitment.exists vi.ctxt blinded_pkh in
let*? () = error_unless exists (Invalid_activation {pkh = edpkh}) in
return_unit
let check_activate_account_conflict vs oph
(operation : Kind.activate_account operation) =
let (Single (Activate_account {id = edpkh; _})) =
operation.protocol_data.contents
in
match
Ed25519.Public_key_hash.Map.find_opt
edpkh
vs.anonymous_state.activation_pkhs_seen
with
| None -> ok_unit
| Some existing ->
Error (Operation_conflict {existing; new_operation = oph})
let wrap_activate_account_conflict
(operation : Kind.activate_account operation) = function
| Ok () -> ok_unit
| Error conflict ->
let (Single (Activate_account {id = edpkh; _})) =
operation.protocol_data.contents
in
error (Conflicting_activation {edpkh; conflict})
let add_activate_account vs oph (operation : Kind.activate_account operation)
=
let (Single (Activate_account {id = edpkh; _})) =
operation.protocol_data.contents
in
let activation_pkhs_seen =
Ed25519.Public_key_hash.Map.add
edpkh
oph
vs.anonymous_state.activation_pkhs_seen
in
{vs with anonymous_state = {vs.anonymous_state with activation_pkhs_seen}}
let remove_activate_account vs (operation : Kind.activate_account operation) =
let (Single (Activate_account {id = edpkh; _})) =
operation.protocol_data.contents
in
let activation_pkhs_seen =
Ed25519.Public_key_hash.Map.remove
edpkh
vs.anonymous_state.activation_pkhs_seen
in
{vs with anonymous_state = {vs.anonymous_state with activation_pkhs_seen}}
let check_denunciation_age vi kind given_level =
let open Result_syntax in
let current_cycle = vi.current_level.cycle in
let given_cycle = (Level.from_raw vi.ctxt given_level).cycle in
let max_slashing_period = Constants.max_slashing_period vi.ctxt in
let last_slashable_cycle = Cycle.add given_cycle max_slashing_period in
let* () =
error_unless
Cycle.(given_cycle <= current_cycle)
(Too_early_denunciation
{kind; level = given_level; current = vi.current_level.level})
in
error_unless
Cycle.(last_slashable_cycle > current_cycle)
(Outdated_denunciation
{kind; level = given_level; last_cycle = last_slashable_cycle})
let check_double_endorsing_evidence (type kind)
~consensus_operation:denunciation_kind vi
(op1 : kind Kind.consensus Operation.t)
(op2 : kind Kind.consensus Operation.t) =
let open Lwt_result_syntax in
match (op1.protocol_data.contents, op2.protocol_data.contents) with
| Single (Preendorsement e1), Single (Preendorsement e2)
| Single (Endorsement e1), Single (Endorsement e2) ->
let op1_hash = Operation.hash op1 in
let op2_hash = Operation.hash op2 in
let same_levels = Raw_level.(e1.level = e2.level) in
let same_rounds = Round.(e1.round = e2.round) in
let same_payload =
Block_payload_hash.(e1.block_payload_hash = e2.block_payload_hash)
in
let same_branches = Block_hash.(op1.shell.branch = op2.shell.branch) in
let ordered_hashes = Operation_hash.(op1_hash < op2_hash) in
let is_denunciation_consistent =
same_levels && same_rounds
(* Either the payloads or the branches must differ for the
double (pre)endorsement to be punishable. Indeed,
different payloads would endanger the consensus process,
while different branches could be used to spam mempools
with a lot of valid operations. On the other hand, if the
operations have identical levels, rounds, payloads, and
branches (and of course delegates), then only their
signatures are different, which is not considered the
delegate's fault and therefore is not punished. *)
&& ((not same_payload) || not same_branches)
&& (* we require an order on hashes to avoid the existence of
equivalent evidences *)
ordered_hashes
in
let*? () =
error_unless
is_denunciation_consistent
(Invalid_denunciation denunciation_kind)
in
Disambiguate : levels are equal
let level = Level.from_raw vi.ctxt e1.level in
let*? () = check_denunciation_age vi denunciation_kind level.level in
let* ctxt, consensus_key1 =
Stake_distribution.slot_owner vi.ctxt level e1.slot
in
let* ctxt, consensus_key2 =
Stake_distribution.slot_owner ctxt level e2.slot
in
let delegate1, delegate2 =
(consensus_key1.delegate, consensus_key2.delegate)
in
let*? () =
error_unless
(Signature.Public_key_hash.equal delegate1 delegate2)
(Inconsistent_denunciation
{kind = denunciation_kind; delegate1; delegate2})
in
let delegate_pk, delegate = (consensus_key1.consensus_pk, delegate1) in
let* already_slashed =
Delegate.already_slashed_for_double_endorsing ctxt delegate level
in
let*? () =
error_unless
(not already_slashed)
(Already_denounced {kind = denunciation_kind; delegate; level})
in
let*? () = Operation.check_signature delegate_pk vi.chain_id op1 in
let*? () = Operation.check_signature delegate_pk vi.chain_id op2 in
return_unit
let check_double_preendorsement_evidence vi
(operation : Kind.double_preendorsement_evidence operation) =
let (Single (Double_preendorsement_evidence {op1; op2})) =
operation.protocol_data.contents
in
check_double_endorsing_evidence
~consensus_operation:Preendorsement
vi
op1
op2
let check_double_endorsement_evidence vi
(operation : Kind.double_endorsement_evidence operation) =
let (Single (Double_endorsement_evidence {op1; op2})) =
operation.protocol_data.contents
in
check_double_endorsing_evidence ~consensus_operation:Endorsement vi op1 op2
let check_double_endorsing_evidence_conflict (type kind) vs oph
(op1 : kind Kind.consensus Operation.t) =
match op1.protocol_data.contents with
| Single (Preendorsement e1) | Single (Endorsement e1) -> (
match
Double_endorsing_evidence_map.find
(e1.level, e1.round, e1.slot)
vs.anonymous_state.double_endorsing_evidences_seen
with
| None -> ok_unit
| Some existing ->
Error (Operation_conflict {existing; new_operation = oph}))
let check_double_preendorsement_evidence_conflict vs oph
(operation : Kind.double_preendorsement_evidence operation) =
let (Single (Double_preendorsement_evidence {op1; _})) =
operation.protocol_data.contents
in
check_double_endorsing_evidence_conflict vs oph op1
let check_double_endorsement_evidence_conflict vs oph
(operation : Kind.double_endorsement_evidence operation) =
let (Single (Double_endorsement_evidence {op1; _})) =
operation.protocol_data.contents
in
check_double_endorsing_evidence_conflict vs oph op1
let wrap_denunciation_conflict kind = function
| Ok () -> ok_unit
| Error conflict -> error (Conflicting_denunciation {kind; conflict})
let add_double_endorsing_evidence (type kind) vs oph
(op1 : kind Kind.consensus Operation.t) =
match op1.protocol_data.contents with
| Single (Preendorsement e1) | Single (Endorsement e1) ->
let double_endorsing_evidences_seen =
Double_endorsing_evidence_map.add
(e1.level, e1.round, e1.slot)
oph
vs.anonymous_state.double_endorsing_evidences_seen
in
{
vs with
anonymous_state =
{vs.anonymous_state with double_endorsing_evidences_seen};
}
let add_double_endorsement_evidence vs oph
(operation : Kind.double_endorsement_evidence operation) =
let (Single (Double_endorsement_evidence {op1; _})) =
operation.protocol_data.contents
in
add_double_endorsing_evidence vs oph op1
let add_double_preendorsement_evidence vs oph
(operation : Kind.double_preendorsement_evidence operation) =
let (Single (Double_preendorsement_evidence {op1; _})) =
operation.protocol_data.contents
in
add_double_endorsing_evidence vs oph op1
let remove_double_endorsing_evidence (type kind) vs
(op : kind Kind.consensus Operation.t) =
match op.protocol_data.contents with
| Single (Endorsement e) | Single (Preendorsement e) ->
let double_endorsing_evidences_seen =
Double_endorsing_evidence_map.remove
(e.level, e.round, e.slot)
vs.anonymous_state.double_endorsing_evidences_seen
in
let anonymous_state =
{vs.anonymous_state with double_endorsing_evidences_seen}
in
{vs with anonymous_state}
let remove_double_preendorsement_evidence vs
(operation : Kind.double_preendorsement_evidence operation) =
let (Single (Double_preendorsement_evidence {op1; _})) =
operation.protocol_data.contents
in
remove_double_endorsing_evidence vs op1
let remove_double_endorsement_evidence vs
(operation : Kind.double_endorsement_evidence operation) =
let (Single (Double_endorsement_evidence {op1; _})) =
operation.protocol_data.contents
in
remove_double_endorsing_evidence vs op1
let check_double_baking_evidence vi
(operation : Kind.double_baking_evidence operation) =
let open Lwt_result_syntax in
let (Single (Double_baking_evidence {bh1; bh2})) =
operation.protocol_data.contents
in
let hash1 = Block_header.hash bh1 in
let hash2 = Block_header.hash bh2 in
let*? bh1_fitness = Fitness.from_raw bh1.shell.fitness in
let round1 = Fitness.round bh1_fitness in
let*? bh2_fitness = Fitness.from_raw bh2.shell.fitness in
let round2 = Fitness.round bh2_fitness in
let*? level1 = Raw_level.of_int32 bh1.shell.level in
let*? level2 = Raw_level.of_int32 bh2.shell.level in
let*? () =
error_unless
(Raw_level.(level1 = level2)
&& Round.(round1 = round2)
&& (* we require an order on hashes to avoid the existence of
equivalent evidences *)
Block_hash.(hash1 < hash2))
(Invalid_double_baking_evidence
{hash1; level1; round1; hash2; level2; round2})
in
let*? () = check_denunciation_age vi Block level1 in
let level = Level.from_raw vi.ctxt level1 in
let committee_size = Constants.consensus_committee_size vi.ctxt in
let*? slot1 = Round.to_slot round1 ~committee_size in
let* ctxt, consensus_key1 =
Stake_distribution.slot_owner vi.ctxt level slot1
in
let*? slot2 = Round.to_slot round2 ~committee_size in
let* ctxt, consensus_key2 =
Stake_distribution.slot_owner ctxt level slot2
in
let delegate1, delegate2 =
(consensus_key1.delegate, consensus_key2.delegate)
in
let*? () =
error_unless
Signature.Public_key_hash.(delegate1 = delegate2)
(Inconsistent_denunciation {kind = Block; delegate1; delegate2})
in
let delegate_pk, delegate = (consensus_key1.consensus_pk, delegate1) in
let* already_slashed =
Delegate.already_slashed_for_double_baking ctxt delegate level
in
let*? () =
error_unless
(not already_slashed)
(Already_denounced {kind = Block; delegate; level})
in
let*? () = Block_header.check_signature bh1 vi.chain_id delegate_pk in
let*? () = Block_header.check_signature bh2 vi.chain_id delegate_pk in
return_unit
let check_double_baking_evidence_conflict vs oph
(operation : Kind.double_baking_evidence operation) =
let (Single (Double_baking_evidence {bh1; _})) =
operation.protocol_data.contents
in
let bh1_fitness =
Fitness.from_raw bh1.shell.fitness |> function
| Ok f -> f
| Error _ ->
(* We assume the operation valid, it cannot fail anymore *)
assert false
in
let round = Fitness.round bh1_fitness in
let level = Fitness.level bh1_fitness in
match
Double_baking_evidence_map.find
(level, round)
vs.anonymous_state.double_baking_evidences_seen
with
| None -> ok_unit
| Some existing ->
Error (Operation_conflict {existing; new_operation = oph})
let add_double_baking_evidence vs oph
(operation : Kind.double_baking_evidence operation) =
let (Single (Double_baking_evidence {bh1; _})) =
operation.protocol_data.contents
in
let bh1_fitness =
Fitness.from_raw bh1.shell.fitness |> function
| Ok f -> f
| Error _ -> assert false
in
let round = Fitness.round bh1_fitness in
let level = Fitness.level bh1_fitness in
let double_baking_evidences_seen =
Double_baking_evidence_map.add
(level, round)
oph
vs.anonymous_state.double_baking_evidences_seen
in
{
vs with
anonymous_state = {vs.anonymous_state with double_baking_evidences_seen};
}
let remove_double_baking_evidence vs
(operation : Kind.double_baking_evidence operation) =
let (Single (Double_baking_evidence {bh1; _})) =
operation.protocol_data.contents
in
let bh1_fitness, level =
match
(Fitness.from_raw bh1.shell.fitness, Raw_level.of_int32 bh1.shell.level)
with
| Ok v, Ok v' -> (v, v')
| _ ->
(* The operation is valid therefore decoding cannot fail *)
assert false
in
let round = Fitness.round bh1_fitness in
let double_baking_evidences_seen =
Double_baking_evidence_map.remove
(level, round)
vs.anonymous_state.double_baking_evidences_seen
in
let anonymous_state =
{vs.anonymous_state with double_baking_evidences_seen}
in
{vs with anonymous_state}
let check_drain_delegate info ~check_signature
(operation : Kind.drain_delegate Operation.t) =
let open Lwt_result_syntax in
let (Single (Drain_delegate {delegate; destination; consensus_key})) =
operation.protocol_data.contents
in
let*! is_registered = Delegate.registered info.ctxt delegate in
let* () =
fail_unless
is_registered
(Drain_delegate_on_unregistered_delegate delegate)
in
let* active_pk = Delegate.Consensus_key.active_pubkey info.ctxt delegate in
let* () =
fail_unless
(Signature.Public_key_hash.equal active_pk.consensus_pkh consensus_key)
(Invalid_drain_delegate_inactive_key
{
delegate;
consensus_key;
active_consensus_key = active_pk.consensus_pkh;
})
in
let* () =
fail_when
(Signature.Public_key_hash.equal active_pk.consensus_pkh delegate)
(Invalid_drain_delegate_no_consensus_key delegate)
in
let* () =
fail_when
(Signature.Public_key_hash.equal destination delegate)
(Invalid_drain_delegate_noop delegate)
in
let*! is_destination_allocated =
Contract.allocated info.ctxt (Contract.Implicit destination)
in
let* balance =
Contract.get_balance info.ctxt (Contract.Implicit delegate)
in
let*? origination_burn =
if is_destination_allocated then ok Tez.zero
else
let cost_per_byte = Constants.cost_per_byte info.ctxt in
let origination_size = Constants.origination_size info.ctxt in
Tez.(cost_per_byte *? Int64.of_int origination_size)
in
let* drain_fees =
let*? one_percent = Tez.(balance /? 100L) in
return Tez.(max one one_percent)
in
let*? min_amount = Tez.(origination_burn +? drain_fees) in
let* () =
fail_when
Tez.(balance < min_amount)
(Invalid_drain_delegate_insufficient_funds_for_burn_or_fees
{delegate; destination; min_amount})
in
let*? () =
if check_signature then
Operation.check_signature active_pk.consensus_pk info.chain_id operation
else ok_unit
in
return_unit
let check_drain_delegate_conflict state oph
(operation : Kind.drain_delegate Operation.t) =
let (Single (Drain_delegate {delegate; _})) =
operation.protocol_data.contents
in
match
Signature.Public_key_hash.Map.find_opt
delegate
state.manager_state.managers_seen
with
| None -> ok_unit
| Some existing ->
Error (Operation_conflict {existing; new_operation = oph})
let wrap_drain_delegate_conflict (operation : Kind.drain_delegate Operation.t)
=
let (Single (Drain_delegate {delegate; _})) =
operation.protocol_data.contents
in
function
| Ok () -> ok_unit
| Error conflict -> error (Conflicting_drain_delegate {delegate; conflict})
let add_drain_delegate state oph (operation : Kind.drain_delegate Operation.t)
=
let (Single (Drain_delegate {delegate; _})) =
operation.protocol_data.contents
in
let managers_seen =
Signature.Public_key_hash.Map.add
delegate
oph
state.manager_state.managers_seen
in
{state with manager_state = {managers_seen}}
let remove_drain_delegate state (operation : Kind.drain_delegate Operation.t)
=
let (Single (Drain_delegate {delegate; _})) =
operation.protocol_data.contents
in
let managers_seen =
Signature.Public_key_hash.Map.remove
delegate
state.manager_state.managers_seen
in
{state with manager_state = {managers_seen}}
let check_seed_nonce_revelation vi
(operation : Kind.seed_nonce_revelation operation) =
let open Lwt_result_syntax in
let (Single (Seed_nonce_revelation {level = commitment_raw_level; nonce})) =
operation.protocol_data.contents
in
let commitment_level = Level.from_raw vi.ctxt commitment_raw_level in
let* () = Nonce.check_unrevealed vi.ctxt commitment_level nonce in
return_unit
let check_seed_nonce_revelation_conflict vs oph
(operation : Kind.seed_nonce_revelation operation) =
let (Single (Seed_nonce_revelation {level = commitment_raw_level; _})) =
operation.protocol_data.contents
in
match
Raw_level.Map.find_opt
commitment_raw_level
vs.anonymous_state.seed_nonce_levels_seen
with
| None -> ok_unit
| Some existing ->
Error (Operation_conflict {existing; new_operation = oph})
let wrap_seed_nonce_revelation_conflict = function
| Ok () -> ok_unit
| Error conflict -> error (Conflicting_nonce_revelation conflict)
let add_seed_nonce_revelation vs oph
(operation : Kind.seed_nonce_revelation operation) =
let (Single (Seed_nonce_revelation {level = commitment_raw_level; _})) =
operation.protocol_data.contents
in
let seed_nonce_levels_seen =
Raw_level.Map.add
commitment_raw_level
oph
vs.anonymous_state.seed_nonce_levels_seen
in
let anonymous_state = {vs.anonymous_state with seed_nonce_levels_seen} in
{vs with anonymous_state}
let remove_seed_nonce_revelation vs
(operation : Kind.seed_nonce_revelation operation) =
let (Single (Seed_nonce_revelation {level = commitment_raw_level; _})) =
operation.protocol_data.contents
in
let seed_nonce_levels_seen =
Raw_level.Map.remove
commitment_raw_level
vs.anonymous_state.seed_nonce_levels_seen
in
let anonymous_state = {vs.anonymous_state with seed_nonce_levels_seen} in
{vs with anonymous_state}
let check_vdf_revelation vi (operation : Kind.vdf_revelation operation) =
let open Lwt_result_syntax in
let (Single (Vdf_revelation {solution})) =
operation.protocol_data.contents
in
let* () = Seed.check_vdf vi.ctxt solution in
return_unit
let check_vdf_revelation_conflict vs oph =
match vs.anonymous_state.vdf_solution_seen with
| None -> ok_unit
| Some existing ->
Error (Operation_conflict {existing; new_operation = oph})
let wrap_vdf_revelation_conflict = function
| Ok () -> ok_unit
| Error conflict -> error (Conflicting_vdf_revelation conflict)
let add_vdf_revelation vs oph =
{
vs with
anonymous_state = {vs.anonymous_state with vdf_solution_seen = Some oph};
}
let remove_vdf_revelation vs =
let anonymous_state = {vs.anonymous_state with vdf_solution_seen = None} in
{vs with anonymous_state}
end
module Manager = struct
open Validate_errors.Manager
(** State that simulates changes from individual operations that have
an effect on future operations inside the same batch. *)
type batch_state = {
balance : Tez.t;
(** Remaining balance in the contract, used to simulate the
payment of fees by each operation in the batch. *)
is_allocated : bool;
(** Track whether the contract is still allocated. Indeed,
previous operations' fee payment may empty the contract and
this may deallocate the contract.
TODO: /-/issues/3209 Change
empty account cleanup mechanism to avoid the need for this
field. *)
total_gas_used : Gas.Arith.fp;
}
* Check a few simple properties of the batch , and return the
initial { ! batch_state } and the contract public key .
Invariants checked :
- All operations in a batch have the same source .
- The source 's contract is allocated .
- The counters in a batch are successive , and the first of them
is the source 's next expected counter .
- A batch contains at most one Reveal operation that must occur
in first position .
- The source 's public key has been revealed ( either before the
considered batch , or during its first operation ) .
Note that currently , the [ op ] batch contains only one signature ,
so all operations in the batch are required to originate from the
same manager . This may change in the future , in order to allow
several managers to group - sign a sequence of operations .
initial {!batch_state} and the contract public key.
Invariants checked:
- All operations in a batch have the same source.
- The source's contract is allocated.
- The counters in a batch are successive, and the first of them
is the source's next expected counter.
- A batch contains at most one Reveal operation that must occur
in first position.
- The source's public key has been revealed (either before the
considered batch, or during its first operation).
Note that currently, the [op] batch contains only one signature,
so all operations in the batch are required to originate from the
same manager. This may change in the future, in order to allow
several managers to group-sign a sequence of operations. *)
let check_sanity_and_find_public_key vi
(contents_list : _ Kind.manager contents_list) =
let open Result_syntax in
let check_source_and_counter ~expected_source ~source ~previous_counter
~counter =
let* () =
error_unless
(Signature.Public_key_hash.equal expected_source source)
Inconsistent_sources
in
error_unless
Manager_counter.(succ previous_counter = counter)
Inconsistent_counters
in
let rec check_batch_tail_sanity :
type kind.
public_key_hash ->
Manager_counter.t ->
kind Kind.manager contents_list ->
unit tzresult =
fun expected_source previous_counter -> function
| Single (Manager_operation {operation = Reveal _key; _}) ->
error Incorrect_reveal_position
| Cons (Manager_operation {operation = Reveal _key; _}, _res) ->
error Incorrect_reveal_position
| Single (Manager_operation {source; counter; _}) ->
check_source_and_counter
~expected_source
~source
~previous_counter
~counter
| Cons (Manager_operation {source; counter; _}, rest) ->
let open Result_syntax in
let* () =
check_source_and_counter
~expected_source
~source
~previous_counter
~counter
in
check_batch_tail_sanity source counter rest
in
let check_batch :
type kind.
kind Kind.manager contents_list ->
(public_key_hash * public_key option * Manager_counter.t) tzresult =
fun contents_list ->
match contents_list with
| Single (Manager_operation {source; operation = Reveal key; counter; _})
->
ok (source, Some key, counter)
| Single (Manager_operation {source; counter; _}) ->
ok (source, None, counter)
| Cons
(Manager_operation {source; operation = Reveal key; counter; _}, rest)
->
check_batch_tail_sanity source counter rest >>? fun () ->
ok (source, Some key, counter)
| Cons (Manager_operation {source; counter; _}, rest) ->
check_batch_tail_sanity source counter rest >>? fun () ->
ok (source, None, counter)
in
let open Lwt_result_syntax in
let*? source, revealed_key, first_counter = check_batch contents_list in
let* balance = Contract.check_allocated_and_get_balance vi.ctxt source in
let* () = Contract.check_counter_increment vi.ctxt source first_counter in
let* pk =
(* Note that it is important to always retrieve the public
key. This includes the case where the key ends up not being
used because the signature check is skipped in
{!validate_manager_operation} called with
[~check_signature:false]. Indeed, the mempool may use
this argument when it has already checked the signature of
the operation in the past; but if there has been a branch
reorganization since then, the key might not be revealed in
the new branch anymore, in which case
{!Contract.get_manager_key} will return an error. *)
match revealed_key with
| Some pk -> return pk
| None -> Contract.get_manager_key vi.ctxt source
in
let initial_batch_state =
{
balance;
(* Initial contract allocation is ensured by the success of
the call to {!Contract.check_allocated_and_get_balance}
above. *)
is_allocated = true;
total_gas_used = Gas.Arith.zero;
}
in
return (initial_batch_state, pk)
let check_gas_limit info ~gas_limit =
Gas.check_gas_limit
~hard_gas_limit_per_operation:
info.manager_info.hard_gas_limit_per_operation
~gas_limit
let check_storage_limit vi storage_limit =
error_unless
Compare.Z.(
storage_limit <= vi.manager_info.hard_storage_limit_per_operation
&& storage_limit >= Z.zero)
Fees.Storage_limit_too_high
let assert_sc_rollup_feature_enabled vi =
error_unless (Constants.sc_rollup_enable vi.ctxt) Sc_rollup_feature_disabled
let assert_pvm_kind_enabled vi kind =
error_when
((not (Constants.sc_rollup_arith_pvm_enable vi.ctxt))
&& Sc_rollup.Kind.(equal kind Example_arith))
Sc_rollup_arith_pvm_disabled
let assert_not_zero_messages messages =
match messages with
| [] -> error Sc_rollup_errors.Sc_rollup_add_zero_messages
| _ -> ok_unit
let assert_zk_rollup_feature_enabled vi =
error_unless (Constants.zk_rollup_enable vi.ctxt) Zk_rollup_feature_disabled
let consume_decoding_gas remaining_gas lexpr =
record_trace Gas_quota_exceeded_init_deserialize
@@ (* Fail early if the operation does not have enough gas to
cover the deserialization cost. We always consider the full
deserialization cost, independently from the internal state
of the lazy_expr. Otherwise we might risk getting different
results if the operation has already been deserialized
before (e.g. when retrieved in JSON format). Note that the
lazy_expr is not actually decoded here; its deserialization
cost is estimated from the size of its bytes. *)
Script.consume_decoding_gas remaining_gas lexpr
let may_trace_gas_limit_too_high info =
match info.mode with
| Application _ | Partial_validation _ | Construction _ -> fun x -> x
| Mempool ->
(* [Gas.check_limit] will only
raise a "temporary" error, however when
{!validate_operation} is called on a batch in isolation
(like e.g. in the mempool) it must "refuse" operations
whose total gas limit (the sum of the [gas_limit]s of each
operation) is already above the block limit. We add the
"permanent" error [Gas.Gas_limit_too_high] on top of the
trace to this effect. *)
record_trace Gas.Gas_limit_too_high
let check_contents (type kind) vi batch_state
(contents : kind Kind.manager contents) remaining_block_gas =
let open Lwt_result_syntax in
let (Manager_operation
{source; fee; counter = _; operation; gas_limit; storage_limit}) =
contents
in
let*? () = check_gas_limit vi ~gas_limit in
let total_gas_used =
Gas.Arith.(add batch_state.total_gas_used (fp gas_limit))
in
let*? () =
may_trace_gas_limit_too_high vi
@@ error_unless
Gas.Arith.(fp total_gas_used <= remaining_block_gas)
Gas.Block_quota_exceeded
in
let*? remaining_gas =
record_trace
Insufficient_gas_for_manager
(Gas.consume_from
(Gas.Arith.fp gas_limit)
Michelson_v1_gas.Cost_of.manager_operation)
in
let*? () = check_storage_limit vi storage_limit in
let*? () =
(* {!Contract.must_be_allocated} has already been called while
initializing [batch_state]. This checks that the contract has
not been emptied by spending fees for previous operations in
the batch. *)
error_unless
batch_state.is_allocated
(Contract_storage.Empty_implicit_contract source)
in
let*? () =
let open Result_syntax in
match operation with
| Reveal pk -> Contract.check_public_key pk source
| Transaction {parameters; _} ->
let* (_ : Gas.Arith.fp) =
consume_decoding_gas remaining_gas parameters
in
return_unit
| Origination {script; _} ->
let* remaining_gas = consume_decoding_gas remaining_gas script.code in
let* (_ : Gas.Arith.fp) =
consume_decoding_gas remaining_gas script.storage
in
return_unit
| Register_global_constant {value} ->
let* (_ : Gas.Arith.fp) = consume_decoding_gas remaining_gas value in
return_unit
| Delegation (Some pkh) -> Delegate.check_not_tz4 pkh
| Update_consensus_key pk -> Delegate.Consensus_key.check_not_tz4 pk
| Delegation None | Set_deposits_limit _ | Increase_paid_storage _ ->
return_unit
| Transfer_ticket {contents; ty; _} ->
let* remaining_gas = consume_decoding_gas remaining_gas contents in
let* (_ : Gas.Arith.fp) = consume_decoding_gas remaining_gas ty in
return_unit
| Sc_rollup_originate {kind; _} ->
let* () = assert_sc_rollup_feature_enabled vi in
assert_pvm_kind_enabled vi kind
| Sc_rollup_cement _ | Sc_rollup_publish _ | Sc_rollup_refute _
| Sc_rollup_timeout _ | Sc_rollup_execute_outbox_message _ ->
assert_sc_rollup_feature_enabled vi
| Sc_rollup_add_messages {messages; _} ->
let* () = assert_sc_rollup_feature_enabled vi in
assert_not_zero_messages messages
| Sc_rollup_recover_bond _ ->
TODO : /-/issues/3063
Should we successfully precheck Sc_rollup_recover_bond and any
( simple ) Sc rollup operation , or should we add some some checks to make
the operations Branch_delayed if they can not be successfully
prechecked ?
Should we successfully precheck Sc_rollup_recover_bond and any
(simple) Sc rollup operation, or should we add some some checks to make
the operations Branch_delayed if they cannot be successfully
prechecked? *)
assert_sc_rollup_feature_enabled vi
| Dal_publish_slot_header slot_header ->
Dal_apply.validate_publish_slot_header vi.ctxt slot_header
| Zk_rollup_origination _ | Zk_rollup_publish _ | Zk_rollup_update _ ->
assert_zk_rollup_feature_enabled vi
in
(* Gas should no longer be consumed below this point, because it
would not take into account any gas consumed during the pattern
matching right above. If you really need to consume gas here, then you
must make this pattern matching return the [remaining_gas].*)
let* balance, is_allocated =
Contract.simulate_spending
vi.ctxt
~balance:batch_state.balance
~amount:fee
source
in
return {total_gas_used; balance; is_allocated}
* This would be [ fold_left_es ( check_contents vi ) batch_state
contents_list ] if [ contents_list ] were an ordinary [ list ] .
contents_list] if [contents_list] were an ordinary [list]. *)
let rec check_contents_list :
type kind.
info ->
batch_state ->
kind Kind.manager contents_list ->
Gas.Arith.fp ->
Gas.Arith.fp tzresult Lwt.t =
fun vi batch_state contents_list remaining_gas ->
let open Lwt_result_syntax in
match contents_list with
| Single contents ->
let* batch_state =
check_contents vi batch_state contents remaining_gas
in
return batch_state.total_gas_used
| Cons (contents, tail) ->
let* batch_state =
check_contents vi batch_state contents remaining_gas
in
check_contents_list vi batch_state tail remaining_gas
let check_manager_operation vi ~check_signature
(operation : _ Kind.manager operation) remaining_block_gas =
let open Lwt_result_syntax in
let contents_list = operation.protocol_data.contents in
let* batch_state, source_pk =
check_sanity_and_find_public_key vi contents_list
in
let* gas_used =
check_contents_list vi batch_state contents_list remaining_block_gas
in
let*? () =
if check_signature then
Operation.check_signature source_pk vi.chain_id operation
else ok_unit
in
return gas_used
let check_manager_operation_conflict (type kind) vs oph
(operation : kind Kind.manager operation) =
let source =
match operation.protocol_data.contents with
| Single (Manager_operation {source; _})
| Cons (Manager_operation {source; _}, _) ->
source
in
One - operation - per - manager - per - block restriction ( 1 M )
match
Signature.Public_key_hash.Map.find_opt
source
vs.manager_state.managers_seen
with
| None -> ok_unit
| Some existing ->
Error (Operation_conflict {existing; new_operation = oph})
let wrap_check_manager_operation_conflict (type kind)
(operation : kind Kind.manager operation) =
let source =
match operation.protocol_data.contents with
| Single (Manager_operation {source; _})
| Cons (Manager_operation {source; _}, _) ->
source
in
function
| Ok () -> ok_unit
| Error conflict -> error (Manager_restriction {source; conflict})
let add_manager_operation (type kind) vs oph
(operation : kind Kind.manager operation) =
let source =
match operation.protocol_data.contents with
| Single (Manager_operation {source; _})
| Cons (Manager_operation {source; _}, _) ->
source
in
let managers_seen =
Signature.Public_key_hash.Map.add
source
oph
vs.manager_state.managers_seen
in
{vs with manager_state = {managers_seen}}
Return the new [ block_state ] with the updated remaining gas used :
- In non - mempool modes , this value is
[ block_state.remaining_block_gas ] , in which the gas from the
validated operation has been subtracted .
- In [ ] mode , the [ block_state ] should remain
unchanged . Indeed , we only want each batch to not exceed the
block limit individually , without taking other operations
into account .
- In non-mempool modes, this value is
[block_state.remaining_block_gas], in which the gas from the
validated operation has been subtracted.
- In [Mempool] mode, the [block_state] should remain
unchanged. Indeed, we only want each batch to not exceed the
block limit individually, without taking other operations
into account. *)
let may_update_remaining_gas_used mode (block_state : block_state)
operation_gas_used =
match mode with
| Application _ | Partial_validation _ | Construction _ ->
let remaining_block_gas =
Gas.Arith.(sub block_state.remaining_block_gas operation_gas_used)
in
{block_state with remaining_block_gas}
| Mempool -> block_state
let remove_manager_operation (type kind) vs
(operation : kind Kind.manager operation) =
let source =
match operation.protocol_data.contents with
| Single (Manager_operation {source; _})
| Cons (Manager_operation {source; _}, _) ->
source
in
let managers_seen =
Signature.Public_key_hash.Map.remove source vs.manager_state.managers_seen
in
{vs with manager_state = {managers_seen}}
let validate_manager_operation ~check_signature info operation_state
block_state oph operation =
let open Lwt_result_syntax in
let* gas_used =
check_manager_operation
info
~check_signature
operation
block_state.remaining_block_gas
in
let*? () =
check_manager_operation_conflict operation_state oph operation
|> wrap_check_manager_operation_conflict operation
in
let operation_state = add_manager_operation operation_state oph operation in
let block_state =
may_update_remaining_gas_used info.mode block_state gas_used
in
return {info; operation_state; block_state}
end
let init_validation_state ctxt mode chain_id ~predecessor_level_and_round =
let info = init_info ctxt mode chain_id ~predecessor_level_and_round in
let operation_state = empty_operation_conflict_state in
let block_state = init_block_state info in
{info; operation_state; block_state}
(* Pre-condition: Shell block headers' checks have already been done.
These checks must ensure that:
- the block header level is the succ of the predecessor block level
- the timestamp of the predecessor is lower than the current block's
- the fitness of the block is greater than its predecessor's
- the number of operations by validation passes does not exceed the quota
established by the protocol
- the size of an operation does not exceed [max_operation_data_length]
*)
let begin_any_application ctxt chain_id ~predecessor_level
~predecessor_timestamp (block_header : Block_header.t) fitness ~is_partial =
let open Lwt_result_syntax in
let predecessor_round = Fitness.predecessor_round fitness in
let round = Fitness.round fitness in
let current_level = Level.current ctxt in
let* ctxt, _slot, block_producer =
Stake_distribution.baking_rights_owner ctxt current_level ~round
in
let*? () =
Block_header.begin_validate_block_header
~block_header
~chain_id
~predecessor_timestamp
~predecessor_round
~fitness
~timestamp:block_header.shell.timestamp
~delegate_pk:block_producer.consensus_pk
~round_durations:(Constants.round_durations ctxt)
~proof_of_work_threshold:(Constants.proof_of_work_threshold ctxt)
~expected_commitment:current_level.expected_commitment
in
let* () =
Consensus.check_frozen_deposits_are_positive ctxt block_producer.delegate
in
let* ctxt, _slot, payload_producer =
Stake_distribution.baking_rights_owner
ctxt
current_level
~round:block_header.protocol_data.contents.payload_round
in
let predecessor_hash = block_header.shell.predecessor in
let block_info =
{
round;
locked_round = Fitness.locked_round fitness;
predecessor_hash;
block_producer;
payload_producer;
header_contents = block_header.protocol_data.contents;
}
in
let mode =
if is_partial then Partial_validation block_info else Application block_info
in
let validation_state =
init_validation_state
ctxt
mode
chain_id
~predecessor_level_and_round:
(Some (predecessor_level.Level.level, predecessor_round))
in
return validation_state
let begin_partial_validation ctxt chain_id ~predecessor_level
~predecessor_timestamp block_header fitness =
begin_any_application
ctxt
chain_id
~predecessor_level
~predecessor_timestamp
block_header
fitness
~is_partial:true
let begin_application ctxt chain_id ~predecessor_level ~predecessor_timestamp
block_header fitness =
begin_any_application
ctxt
chain_id
~predecessor_level
~predecessor_timestamp
block_header
fitness
~is_partial:false
let begin_full_construction ctxt chain_id ~predecessor_level ~predecessor_round
~predecessor_timestamp ~predecessor_hash round
(header_contents : Block_header.contents) =
let open Lwt_result_syntax in
let round_durations = Constants.round_durations ctxt in
let timestamp = Timestamp.current ctxt in
let*? () =
Block_header.check_timestamp
round_durations
~timestamp
~round
~predecessor_timestamp
~predecessor_round
in
let current_level = Level.current ctxt in
let* ctxt, _slot, block_producer =
Stake_distribution.baking_rights_owner ctxt current_level ~round
in
let* () =
Consensus.check_frozen_deposits_are_positive ctxt block_producer.delegate
in
let* ctxt, _slot, payload_producer =
Stake_distribution.baking_rights_owner
ctxt
current_level
~round:header_contents.payload_round
in
let validation_state =
init_validation_state
ctxt
(Construction
{
round;
predecessor_hash;
block_producer;
payload_producer;
header_contents;
})
chain_id
~predecessor_level_and_round:
(Some (predecessor_level.Level.level, predecessor_round))
in
return validation_state
let begin_partial_construction ctxt chain_id ~predecessor_level
~predecessor_round =
let validation_state =
init_validation_state
ctxt
Mempool
chain_id
~predecessor_level_and_round:
(Some (predecessor_level.Level.level, predecessor_round))
in
validation_state
let begin_no_predecessor_info ctxt chain_id =
init_validation_state ctxt Mempool chain_id ~predecessor_level_and_round:None
let check_operation ?(check_signature = true) info (type kind)
(operation : kind operation) : unit tzresult Lwt.t =
let open Lwt_result_syntax in
match operation.protocol_data.contents with
| Single (Preendorsement _) ->
let* (_voting_power : int) =
Consensus.check_preendorsement info ~check_signature operation
in
return_unit
| Single (Endorsement _) ->
let* (_voting_power : int) =
Consensus.check_endorsement info ~check_signature operation
in
return_unit
| Single (Dal_attestation _) -> Consensus.check_dal_attestation info operation
| Single (Proposals _) ->
Voting.check_proposals info ~check_signature operation
| Single (Ballot _) -> Voting.check_ballot info ~check_signature operation
| Single (Activate_account _) ->
Anonymous.check_activate_account info operation
| Single (Double_preendorsement_evidence _) ->
Anonymous.check_double_preendorsement_evidence info operation
| Single (Double_endorsement_evidence _) ->
Anonymous.check_double_endorsement_evidence info operation
| Single (Double_baking_evidence _) ->
Anonymous.check_double_baking_evidence info operation
| Single (Drain_delegate _) ->
Anonymous.check_drain_delegate info ~check_signature operation
| Single (Seed_nonce_revelation _) ->
Anonymous.check_seed_nonce_revelation info operation
| Single (Vdf_revelation _) -> Anonymous.check_vdf_revelation info operation
| Single (Manager_operation _) ->
let remaining_gas =
Gas.Arith.fp (Constants.hard_gas_limit_per_block info.ctxt)
in
let* (_remaining_gas : Gas.Arith.fp) =
Manager.check_manager_operation
info
~check_signature
operation
remaining_gas
in
return_unit
| Cons (Manager_operation _, _) ->
let remaining_gas =
Gas.Arith.fp (Constants.hard_gas_limit_per_block info.ctxt)
in
let* (_remaining_gas : Gas.Arith.fp) =
Manager.check_manager_operation
info
~check_signature
operation
remaining_gas
in
return_unit
| Single (Failing_noop _) -> tzfail Validate_errors.Failing_noop_error
let check_operation_conflict (type kind) operation_conflict_state oph
(operation : kind operation) =
match operation.protocol_data.contents with
| Single (Preendorsement _) ->
Consensus.check_preendorsement_conflict
operation_conflict_state
oph
operation
| Single (Endorsement _) ->
Consensus.check_endorsement_conflict
operation_conflict_state
oph
operation
| Single (Dal_attestation _) ->
Consensus.check_dal_attestation_conflict
operation_conflict_state
oph
operation
| Single (Proposals _) ->
Voting.check_proposals_conflict operation_conflict_state oph operation
| Single (Ballot _) ->
Voting.check_ballot_conflict operation_conflict_state oph operation
| Single (Activate_account _) ->
Anonymous.check_activate_account_conflict
operation_conflict_state
oph
operation
| Single (Double_preendorsement_evidence _) ->
Anonymous.check_double_preendorsement_evidence_conflict
operation_conflict_state
oph
operation
| Single (Double_endorsement_evidence _) ->
Anonymous.check_double_endorsement_evidence_conflict
operation_conflict_state
oph
operation
| Single (Double_baking_evidence _) ->
Anonymous.check_double_baking_evidence_conflict
operation_conflict_state
oph
operation
| Single (Drain_delegate _) ->
Anonymous.check_drain_delegate_conflict
operation_conflict_state
oph
operation
| Single (Seed_nonce_revelation _) ->
Anonymous.check_seed_nonce_revelation_conflict
operation_conflict_state
oph
operation
| Single (Vdf_revelation _) ->
Anonymous.check_vdf_revelation_conflict operation_conflict_state oph
| Single (Manager_operation _) ->
Manager.check_manager_operation_conflict
operation_conflict_state
oph
operation
| Cons (Manager_operation _, _) ->
Manager.check_manager_operation_conflict
operation_conflict_state
oph
operation
| Single (Failing_noop _) -> (* Nothing to do *) ok_unit
let add_valid_operation operation_conflict_state oph (type kind)
(operation : kind operation) =
match operation.protocol_data.contents with
| Single (Preendorsement _) ->
Consensus.add_preendorsement operation_conflict_state oph operation
| Single (Endorsement _) ->
Consensus.add_endorsement operation_conflict_state oph operation
| Single (Dal_attestation _) ->
Consensus.add_dal_attestation operation_conflict_state oph operation
| Single (Proposals _) ->
Voting.add_proposals operation_conflict_state oph operation
| Single (Ballot _) ->
Voting.add_ballot operation_conflict_state oph operation
| Single (Activate_account _) ->
Anonymous.add_activate_account operation_conflict_state oph operation
| Single (Double_preendorsement_evidence _) ->
Anonymous.add_double_preendorsement_evidence
operation_conflict_state
oph
operation
| Single (Double_endorsement_evidence _) ->
Anonymous.add_double_endorsement_evidence
operation_conflict_state
oph
operation
| Single (Double_baking_evidence _) ->
Anonymous.add_double_baking_evidence
operation_conflict_state
oph
operation
| Single (Drain_delegate _) ->
Anonymous.add_drain_delegate operation_conflict_state oph operation
| Single (Seed_nonce_revelation _) ->
Anonymous.add_seed_nonce_revelation operation_conflict_state oph operation
| Single (Vdf_revelation _) ->
Anonymous.add_vdf_revelation operation_conflict_state oph
| Single (Manager_operation _) ->
Manager.add_manager_operation operation_conflict_state oph operation
| Cons (Manager_operation _, _) ->
Manager.add_manager_operation operation_conflict_state oph operation
| Single (Failing_noop _) -> (* Nothing to do *) operation_conflict_state
(* Hypothesis:
- the [operation] has been validated and is present in [vs];
- this function is only valid for the mempool mode. *)
let remove_operation operation_conflict_state (type kind)
(operation : kind operation) =
match operation.protocol_data.contents with
| Single (Preendorsement _) ->
Consensus.remove_preendorsement operation_conflict_state operation
| Single (Endorsement _) ->
Consensus.remove_endorsement operation_conflict_state operation
| Single (Dal_attestation _) ->
Consensus.remove_dal_attestation operation_conflict_state operation
| Single (Proposals _) ->
Voting.remove_proposals operation_conflict_state operation
| Single (Ballot _) -> Voting.remove_ballot operation_conflict_state operation
| Single (Activate_account _) ->
Anonymous.remove_activate_account operation_conflict_state operation
| Single (Double_preendorsement_evidence _) ->
Anonymous.remove_double_preendorsement_evidence
operation_conflict_state
operation
| Single (Double_endorsement_evidence _) ->
Anonymous.remove_double_endorsement_evidence
operation_conflict_state
operation
| Single (Double_baking_evidence _) ->
Anonymous.remove_double_baking_evidence operation_conflict_state operation
| Single (Drain_delegate _) ->
Anonymous.remove_drain_delegate operation_conflict_state operation
| Single (Seed_nonce_revelation _) ->
Anonymous.remove_seed_nonce_revelation operation_conflict_state operation
| Single (Vdf_revelation _) ->
Anonymous.remove_vdf_revelation operation_conflict_state
| Single (Manager_operation _) ->
Manager.remove_manager_operation operation_conflict_state operation
| Cons (Manager_operation _, _) ->
Manager.remove_manager_operation operation_conflict_state operation
| Single (Failing_noop _) -> (* Nothing to do *) operation_conflict_state
let check_validation_pass_consistency vi vs validation_pass =
let open Lwt_result_syntax in
match vi.mode with
| Mempool | Construction _ -> return vs
| Application _ | Partial_validation _ -> (
match (vs.last_op_validation_pass, validation_pass) with
| None, validation_pass ->
return {vs with last_op_validation_pass = validation_pass}
| Some previous_vp, Some validation_pass ->
let* () =
fail_unless
Compare.Int.(previous_vp <= validation_pass)
(Validate_errors.Block.Inconsistent_validation_passes_in_block
{expected = previous_vp; provided = validation_pass})
in
return {vs with last_op_validation_pass = Some validation_pass}
| Some _, None -> tzfail Validate_errors.Failing_noop_error)
(** Increment [vs.op_count] for all operations, and record
non-consensus operation hashes in [vs.recorded_operations_rev]. *)
let record_operation vs ophash validation_pass_opt =
let op_count = vs.op_count + 1 in
match validation_pass_opt with
| Some n when Compare.Int.(n = Operation_repr.consensus_pass) ->
{vs with op_count}
| _ ->
{
vs with
op_count;
recorded_operations_rev = ophash :: vs.recorded_operations_rev;
}
let validate_operation ?(check_signature = true)
{info; operation_state; block_state} oph
(packed_operation : packed_operation) =
let open Lwt_result_syntax in
let {shell; protocol_data = Operation_data protocol_data} =
packed_operation
in
let validation_pass_opt = Operation.acceptable_pass packed_operation in
let* block_state =
check_validation_pass_consistency info block_state validation_pass_opt
in
let block_state = record_operation block_state oph validation_pass_opt in
let operation : _ operation = {shell; protocol_data} in
match (info.mode, validation_pass_opt) with
| Partial_validation _, Some n
when Compare.Int.(n <> Operation_repr.consensus_pass) ->
(* Do not validate non-consensus operations in
[Partial_validation] mode. *)
return {info; operation_state; block_state}
| (Application _ | Partial_validation _ | Construction _ | Mempool), _ -> (
match operation.protocol_data.contents with
| Single (Preendorsement _) ->
Consensus.validate_preendorsement
~check_signature
info
operation_state
block_state
oph
operation
| Single (Endorsement _) ->
Consensus.validate_endorsement
~check_signature
info
operation_state
block_state
oph
operation
| Single (Dal_attestation _) ->
let open Consensus in
let* () = check_dal_attestation info operation in
let*? () =
check_dal_attestation_conflict operation_state oph operation
|> wrap_dal_attestation_conflict
in
let operation_state =
add_dal_attestation operation_state oph operation
in
return {info; operation_state; block_state}
| Single (Proposals _) ->
let open Voting in
let* () = check_proposals info ~check_signature operation in
let*? () =
check_proposals_conflict operation_state oph operation
|> wrap_proposals_conflict
in
let operation_state = add_proposals operation_state oph operation in
return {info; operation_state; block_state}
| Single (Ballot _) ->
let open Voting in
let* () = check_ballot info ~check_signature operation in
let*? () =
check_ballot_conflict operation_state oph operation
|> wrap_ballot_conflict
in
let operation_state = add_ballot operation_state oph operation in
return {info; operation_state; block_state}
| Single (Activate_account _) ->
let open Anonymous in
let* () = check_activate_account info operation in
let*? () =
check_activate_account_conflict operation_state oph operation
|> wrap_activate_account_conflict operation
in
let operation_state =
add_activate_account operation_state oph operation
in
return {info; operation_state; block_state}
| Single (Double_preendorsement_evidence _) ->
let open Anonymous in
let* () = check_double_preendorsement_evidence info operation in
let*? () =
check_double_preendorsement_evidence_conflict
operation_state
oph
operation
|> wrap_denunciation_conflict Preendorsement
in
let operation_state =
add_double_preendorsement_evidence operation_state oph operation
in
return {info; operation_state; block_state}
| Single (Double_endorsement_evidence _) ->
let open Anonymous in
let* () = check_double_endorsement_evidence info operation in
let*? () =
check_double_endorsement_evidence_conflict
operation_state
oph
operation
|> wrap_denunciation_conflict Endorsement
in
let operation_state =
add_double_endorsement_evidence operation_state oph operation
in
return {info; operation_state; block_state}
| Single (Double_baking_evidence _) ->
let open Anonymous in
let* () = check_double_baking_evidence info operation in
let*? () =
check_double_baking_evidence_conflict operation_state oph operation
|> wrap_denunciation_conflict Block
in
let operation_state =
add_double_baking_evidence operation_state oph operation
in
return {info; operation_state; block_state}
| Single (Drain_delegate _) ->
let open Anonymous in
let* () = check_drain_delegate info ~check_signature operation in
let*? () =
check_drain_delegate_conflict operation_state oph operation
|> wrap_drain_delegate_conflict operation
in
let operation_state =
add_drain_delegate operation_state oph operation
in
return {info; operation_state; block_state}
| Single (Seed_nonce_revelation _) ->
let open Anonymous in
let* () = check_seed_nonce_revelation info operation in
let*? () =
check_seed_nonce_revelation_conflict operation_state oph operation
|> wrap_seed_nonce_revelation_conflict
in
let operation_state =
add_seed_nonce_revelation operation_state oph operation
in
return {info; operation_state; block_state}
| Single (Vdf_revelation _) ->
let open Anonymous in
let* () = check_vdf_revelation info operation in
let*? () =
check_vdf_revelation_conflict operation_state oph
|> wrap_vdf_revelation_conflict
in
let operation_state = add_vdf_revelation operation_state oph in
return {info; operation_state; block_state}
| Single (Manager_operation _) ->
Manager.validate_manager_operation
~check_signature
info
operation_state
block_state
oph
operation
| Cons (Manager_operation _, _) ->
Manager.validate_manager_operation
~check_signature
info
operation_state
block_state
oph
operation
| Single (Failing_noop _) -> tzfail Validate_errors.Failing_noop_error)
let are_endorsements_required vi =
let open Lwt_result_syntax in
let+ first_level = First_level_of_protocol.get vi.ctxt in
[ Comment from Legacy_apply ] NB : the first level is the level
of the migration block . There are no endorsements for this
block . Therefore the block at the next level can not contain
endorsements .
of the migration block. There are no endorsements for this
block. Therefore the block at the next level cannot contain
endorsements. *)
let level_position_in_protocol =
Raw_level.diff vi.current_level.level first_level
in
Compare.Int32.(level_position_in_protocol > 1l)
let check_endorsement_power vi bs =
let required = Constants.consensus_threshold vi.ctxt in
let provided = bs.endorsement_power in
error_unless
Compare.Int.(provided >= required)
(Validate_errors.Block.Not_enough_endorsements {required; provided})
let finalize_validate_block_header vi vs checkable_payload_hash
(block_header_contents : Block_header.contents) round ~fitness_locked_round
=
let locked_round_evidence =
Option.map
(fun (preendorsement_round, preendorsement_count) ->
Block_header.{preendorsement_round; preendorsement_count})
vs.locked_round_evidence
in
Block_header.finalize_validate_block_header
~block_header_contents
~round
~fitness_locked_round
~checkable_payload_hash
~locked_round_evidence
~consensus_threshold:(Constants.consensus_threshold vi.ctxt)
let compute_payload_hash block_state
(block_header_contents : Block_header.contents) ~predecessor_hash =
Block_payload.hash
~predecessor_hash
~payload_round:block_header_contents.payload_round
(List.rev block_state.recorded_operations_rev)
let finalize_block {info; block_state; _} =
let open Lwt_result_syntax in
match info.mode with
| Application {round; locked_round; predecessor_hash; header_contents; _} ->
let* are_endorsements_required = are_endorsements_required info in
let*? () =
if are_endorsements_required then
check_endorsement_power info block_state
else ok_unit
in
let block_payload_hash =
compute_payload_hash block_state header_contents ~predecessor_hash
in
let*? () =
finalize_validate_block_header
info
block_state
(Block_header.Expected_payload_hash block_payload_hash)
header_contents
round
~fitness_locked_round:locked_round
in
return_unit
| Partial_validation _ ->
let* are_endorsements_required = are_endorsements_required info in
let*? () =
if are_endorsements_required then
check_endorsement_power info block_state
else ok_unit
in
return_unit
| Construction {round; predecessor_hash; header_contents; _} ->
let block_payload_hash =
compute_payload_hash block_state header_contents ~predecessor_hash
in
let locked_round_evidence = block_state.locked_round_evidence in
let checkable_payload_hash =
match locked_round_evidence with
| Some _ -> Block_header.Expected_payload_hash block_payload_hash
| None ->
(* In full construction, when there is no locked round
evidence (and thus no preendorsements), the baker cannot
know the payload hash before selecting the operations. We
may dismiss checking the initially given
payload_hash. However, to be valid, the baker must patch
the resulting block header with the actual payload
hash. *)
Block_header.No_check
in
let* are_endorsements_required = are_endorsements_required info in
let*? () =
if are_endorsements_required then
check_endorsement_power info block_state
else ok_unit
in
let*? () =
finalize_validate_block_header
info
block_state
checkable_payload_hash
header_contents
round
~fitness_locked_round:(Option.map fst locked_round_evidence)
in
return_unit
| Mempool ->
(* There is no block to finalize in mempool mode. *)
return_unit
| null | https://raw.githubusercontent.com/tezos/tezos-mirror/17c66930cde5fea79d899e139640eb750f6395b8/src/proto_alpha/lib_protocol/validate.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.
***************************************************************************
* To each delegate that has submitted a ballot in a previously
validated operation, associates the hash of this operation.
* State used and modified when validating anonymous operations.
These fields are used to enforce that we do not validate the same
operation multiple times.
Note that as part of {!state}, these maps live
in memory. They are not explicitly bounded here, however:
- In block validation mode, they are bounded by the number of
anonymous operations allowed in the block.
- In mempool mode, bounding the number of operations in this map
is the responsability of the prevalidator on the shell side.
* Static information used to validate manager operations.
* State used and modified when validating manager operations.
* Information needed to validate consensus operations and/or to
finalize the block in both modes that handle a preexisting block:
[Application] and [Partial_validation].
* Information needed to validate consensus operations and/or to
finalize the block in [Construction] mode.
* Circumstances in which operations are validated, and corresponding
specific information.
If you add a new mode, please make sure that it has a way to bound
the size of the maps in the {!operation_conflict_state}.
* [Application] is used for the validation of a preexisting block,
often in preparation for its future application.
* [Partial_validation] is used to quickly but partially validate a
preexisting block, e.g. to quickly decide whether an alternate
branch seems viable. In this mode, the initial {!type:context} may
come from an ancestor block instead of the predecessor block. Only
consensus operations are validated in this mode.
* Used for the construction of a new block.
* Used by the mempool ({!module:Mempool_validation}) and by the
[Partial_construction] mode in {!module:Main}, which may itself be
used by RPCs or by another mempool implementation.
* The context at the beginning of the block or mempool.
* Needed for signature checks.
* Needed to validate consensus operations. This can be [None] during
some RPC calls when some predecessor information is unavailable,
in which case the validation of all consensus operations will
systematically fail.
* Validation of consensus operations (validation pass [0]):
preendorsement, endorsement, and dal_attestation.
* When validating a block (ie. in [Application],
[Partial_validation], and [Construction] modes), any
preendorsements must point to a round that is strictly before the
block's round.
We use [if] instead of [error_unless] to avoid computing the
error when it is not needed.
We use [if] instead of [error_unless] to avoid computing the
error when it is not needed.
* Preendorsement checks for both [Application] and
[Partial_validation] modes.
Return the slot owner's consensus key and voting power.
A preexisting block whose fitness has no locked round
should contain no preendorsements.
* Preendorsement checks for Construction mode.
Return the slot owner's consensus key and voting power.
We cannot check the exact round here in construction mode, because
there is no preexisting fitness to provide the locked_round. We do
however check that all preendorments have the same round in
[check_construction_preendorsement_round_consistency] further below.
The operation points to the mempool head's level, which is
the level for which slot maps have been pre-computed.
Fake voting power
We do not check that the frozen deposits are positive because this
only needs to be true in the context of a block that actually
contains the operation, which may not be the same as the current
mempool's context.
The block_state is not relevant in this mode.
Hypothesis: this function will only be called in mempool mode
* Endorsement checks for all modes that involve a block:
Application, Partial_validation, and Construction.
Return the slot owner's consensus key and voting power.
The block_state is not relevant.
Hypothesis: this function will only be called in mempool mode
We do not remove the endorsement power because it is not
relevant for the mempool mode.
Note that this function checks the dal feature flag.
Other preendorsements have already been validated: we check
that the current operation has the same round as them.
We need to update the block state
* Check that the list of proposals is not empty and does not contain
duplicates.
The proposal count of the proposer in the context should never
have been increased above [max_proposals_per_delegate].
This assertion should be ensured by the fact that
{!Amendment.is_testnet_dictator} cannot be [true] on mainnet
(so the current function cannot be called there). However, we
still double check it because of its criticality.
In [Amendment.apply_testnet_dictator_proposals], the call to
{!Vote.init_current_proposal} (in the singleton list case)
cannot fail because {!Vote.clear_current_proposal} is called
right before.
The calls to
{!Voting_period.Testnet_dictator.overwrite_current_kind} may
usually fail when the voting period is not
initialized. However, this cannot happen here because the
current function is only called in [check_proposals] after a
successful call to {!Voting_period.get_current}.
Retrieving the public key should not fail as it *should* be
called after checking that the delegate is in the vote
listings (or is a testnet dictator), which implies that it
is a manager with a revealed key.
Retrieving the public key cannot fail. Indeed, we have
already checked that the delegate is in the vote listings,
which implies that it is a manager with a revealed key.
Either the payloads or the branches must differ for the
double (pre)endorsement to be punishable. Indeed,
different payloads would endanger the consensus process,
while different branches could be used to spam mempools
with a lot of valid operations. On the other hand, if the
operations have identical levels, rounds, payloads, and
branches (and of course delegates), then only their
signatures are different, which is not considered the
delegate's fault and therefore is not punished.
we require an order on hashes to avoid the existence of
equivalent evidences
we require an order on hashes to avoid the existence of
equivalent evidences
We assume the operation valid, it cannot fail anymore
The operation is valid therefore decoding cannot fail
* State that simulates changes from individual operations that have
an effect on future operations inside the same batch.
* Remaining balance in the contract, used to simulate the
payment of fees by each operation in the batch.
* Track whether the contract is still allocated. Indeed,
previous operations' fee payment may empty the contract and
this may deallocate the contract.
TODO: /-/issues/3209 Change
empty account cleanup mechanism to avoid the need for this
field.
Note that it is important to always retrieve the public
key. This includes the case where the key ends up not being
used because the signature check is skipped in
{!validate_manager_operation} called with
[~check_signature:false]. Indeed, the mempool may use
this argument when it has already checked the signature of
the operation in the past; but if there has been a branch
reorganization since then, the key might not be revealed in
the new branch anymore, in which case
{!Contract.get_manager_key} will return an error.
Initial contract allocation is ensured by the success of
the call to {!Contract.check_allocated_and_get_balance}
above.
Fail early if the operation does not have enough gas to
cover the deserialization cost. We always consider the full
deserialization cost, independently from the internal state
of the lazy_expr. Otherwise we might risk getting different
results if the operation has already been deserialized
before (e.g. when retrieved in JSON format). Note that the
lazy_expr is not actually decoded here; its deserialization
cost is estimated from the size of its bytes.
[Gas.check_limit] will only
raise a "temporary" error, however when
{!validate_operation} is called on a batch in isolation
(like e.g. in the mempool) it must "refuse" operations
whose total gas limit (the sum of the [gas_limit]s of each
operation) is already above the block limit. We add the
"permanent" error [Gas.Gas_limit_too_high] on top of the
trace to this effect.
{!Contract.must_be_allocated} has already been called while
initializing [batch_state]. This checks that the contract has
not been emptied by spending fees for previous operations in
the batch.
Gas should no longer be consumed below this point, because it
would not take into account any gas consumed during the pattern
matching right above. If you really need to consume gas here, then you
must make this pattern matching return the [remaining_gas].
Pre-condition: Shell block headers' checks have already been done.
These checks must ensure that:
- the block header level is the succ of the predecessor block level
- the timestamp of the predecessor is lower than the current block's
- the fitness of the block is greater than its predecessor's
- the number of operations by validation passes does not exceed the quota
established by the protocol
- the size of an operation does not exceed [max_operation_data_length]
Nothing to do
Nothing to do
Hypothesis:
- the [operation] has been validated and is present in [vs];
- this function is only valid for the mempool mode.
Nothing to do
* Increment [vs.op_count] for all operations, and record
non-consensus operation hashes in [vs.recorded_operations_rev].
Do not validate non-consensus operations in
[Partial_validation] mode.
In full construction, when there is no locked round
evidence (and thus no preendorsements), the baker cannot
know the payload hash before selecting the operations. We
may dismiss checking the initially given
payload_hash. However, to be valid, the baker must patch
the resulting block header with the actual payload
hash.
There is no block to finalize in mempool mode. | Copyright ( c ) 2022 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
open Validate_errors
open Alpha_context
type consensus_info = {
predecessor_level : Raw_level.t;
predecessor_round : Round.t;
preendorsement_slot_map : (Consensus_key.pk * int) Slot.Map.t;
endorsement_slot_map : (Consensus_key.pk * int) Slot.Map.t;
}
let init_consensus_info ctxt (predecessor_level, predecessor_round) =
{
predecessor_level;
predecessor_round;
preendorsement_slot_map = Consensus.allowed_preendorsements ctxt;
endorsement_slot_map = Consensus.allowed_endorsements ctxt;
}
* Map used to detect consensus operation conflicts . Each delegate
may ( pre)endorse at most once for each level and round , so two
endorsements ( resp . two preendorsements ) conflict when they have
the same slot , level , and round .
Note that when validating a block , all endorsements ( resp . all
preendorsements ) must have the same level and round anyway , so only
the slot is relevant . Taking the level and round into account is
useful in mempool mode , because we want to be able to accept and
propagate consensus operations for multiple close
past / future / cousin blocks .
may (pre)endorse at most once for each level and round, so two
endorsements (resp. two preendorsements) conflict when they have
the same slot, level, and round.
Note that when validating a block, all endorsements (resp. all
preendorsements) must have the same level and round anyway, so only
the slot is relevant. Taking the level and round into account is
useful in mempool mode, because we want to be able to accept and
propagate consensus operations for multiple close
past/future/cousin blocks. *)
module Consensus_conflict_map = Map.Make (struct
type t = Slot.t * Raw_level.t * Round.t
let compare (slot1, level1, round1) (slot2, level2, round2) =
Compare.or_else (Raw_level.compare level1 level2) @@ fun () ->
Compare.or_else (Slot.compare slot1 slot2) @@ fun () ->
Round.compare round1 round2
end)
type consensus_state = {
preendorsements_seen : Operation_hash.t Consensus_conflict_map.t;
endorsements_seen : Operation_hash.t Consensus_conflict_map.t;
dal_attestation_seen : Operation_hash.t Signature.Public_key_hash.Map.t;
}
let consensus_conflict_map_encoding =
let open Data_encoding in
conv
(fun map -> Consensus_conflict_map.bindings map)
(fun l ->
Consensus_conflict_map.(
List.fold_left (fun m (k, v) -> add k v m) empty l))
(list
(tup2
(tup3 Slot.encoding Raw_level.encoding Round.encoding)
Operation_hash.encoding))
let consensus_state_encoding =
let open Data_encoding in
def "consensus_state"
@@ conv
(fun {preendorsements_seen; endorsements_seen; dal_attestation_seen} ->
(preendorsements_seen, endorsements_seen, dal_attestation_seen))
(fun (preendorsements_seen, endorsements_seen, dal_attestation_seen) ->
{preendorsements_seen; endorsements_seen; dal_attestation_seen})
(obj3
(req "preendorsements_seen" consensus_conflict_map_encoding)
(req "endorsements_seen" consensus_conflict_map_encoding)
(req
"dal_attestation_seen"
(Signature.Public_key_hash.Map.encoding Operation_hash.encoding)))
let empty_consensus_state =
{
preendorsements_seen = Consensus_conflict_map.empty;
endorsements_seen = Consensus_conflict_map.empty;
dal_attestation_seen = Signature.Public_key_hash.Map.empty;
}
type voting_state = {
proposals_seen : Operation_hash.t Signature.Public_key_hash.Map.t;
* To each delegate that has submitted a Proposals operation in a
previously validated operation , associates the hash of this
operation . This includes Proposals from a potential Testnet
Dictator .
previously validated operation, associates the hash of this
operation. This includes Proposals from a potential Testnet
Dictator. *)
ballots_seen : Operation_hash.t Signature.Public_key_hash.Map.t;
}
let voting_state_encoding =
let open Data_encoding in
def "voting_state"
@@ conv
(fun {proposals_seen; ballots_seen} -> (proposals_seen, ballots_seen))
(fun (proposals_seen, ballots_seen) -> {proposals_seen; ballots_seen})
(obj2
(req
"proposals_seen"
(Signature.Public_key_hash.Map.encoding Operation_hash.encoding))
(req
"ballots_seen"
(Signature.Public_key_hash.Map.encoding Operation_hash.encoding)))
module Double_baking_evidence_map = struct
include Map.Make (struct
type t = Raw_level.t * Round.t
let compare (l, r) (l', r') =
Compare.or_else (Raw_level.compare l l') @@ fun () ->
Compare.or_else (Round.compare r r') @@ fun () -> 0
end)
let encoding elt_encoding =
Data_encoding.conv
(fun map -> bindings map)
(fun l -> List.fold_left (fun m (k, v) -> add k v m) empty l)
Data_encoding.(
list (tup2 (tup2 Raw_level.encoding Round.encoding) elt_encoding))
end
module Double_endorsing_evidence_map = struct
include Map.Make (struct
type t = Raw_level.t * Round.t * Slot.t
let compare (l, r, s) (l', r', s') =
Compare.or_else (Raw_level.compare l l') @@ fun () ->
Compare.or_else (Round.compare r r') @@ fun () ->
Compare.or_else (Slot.compare s s') @@ fun () -> 0
end)
let encoding elt_encoding =
Data_encoding.conv
(fun map -> bindings map)
(fun l -> List.fold_left (fun m (k, v) -> add k v m) empty l)
Data_encoding.(
list
(tup2
(tup3 Raw_level.encoding Round.encoding Slot.encoding)
elt_encoding))
end
type anonymous_state = {
activation_pkhs_seen : Operation_hash.t Ed25519.Public_key_hash.Map.t;
double_baking_evidences_seen : Operation_hash.t Double_baking_evidence_map.t;
double_endorsing_evidences_seen :
Operation_hash.t Double_endorsing_evidence_map.t;
seed_nonce_levels_seen : Operation_hash.t Raw_level.Map.t;
vdf_solution_seen : Operation_hash.t option;
}
let raw_level_map_encoding elt_encoding =
let open Data_encoding in
conv
(fun map -> Raw_level.Map.bindings map)
(fun l ->
Raw_level.Map.(List.fold_left (fun m (k, v) -> add k v m) empty l))
(list (tup2 Raw_level.encoding elt_encoding))
let anonymous_state_encoding =
let open Data_encoding in
def "anonymous_state"
@@ conv
(fun {
activation_pkhs_seen;
double_baking_evidences_seen;
double_endorsing_evidences_seen;
seed_nonce_levels_seen;
vdf_solution_seen;
} ->
( activation_pkhs_seen,
double_baking_evidences_seen,
double_endorsing_evidences_seen,
seed_nonce_levels_seen,
vdf_solution_seen ))
(fun ( activation_pkhs_seen,
double_baking_evidences_seen,
double_endorsing_evidences_seen,
seed_nonce_levels_seen,
vdf_solution_seen ) ->
{
activation_pkhs_seen;
double_baking_evidences_seen;
double_endorsing_evidences_seen;
seed_nonce_levels_seen;
vdf_solution_seen;
})
(obj5
(req
"activation_pkhs_seen"
(Ed25519.Public_key_hash.Map.encoding Operation_hash.encoding))
(req
"double_baking_evidences_seen"
(Double_baking_evidence_map.encoding Operation_hash.encoding))
(req
"double_endorsing_evidences_seen"
(Double_endorsing_evidence_map.encoding Operation_hash.encoding))
(req
"seed_nonce_levels_seen"
(raw_level_map_encoding Operation_hash.encoding))
(opt "vdf_solution_seen" Operation_hash.encoding))
let empty_anonymous_state =
{
activation_pkhs_seen = Ed25519.Public_key_hash.Map.empty;
double_baking_evidences_seen = Double_baking_evidence_map.empty;
double_endorsing_evidences_seen = Double_endorsing_evidence_map.empty;
seed_nonce_levels_seen = Raw_level.Map.empty;
vdf_solution_seen = None;
}
type manager_info = {
hard_storage_limit_per_operation : Z.t;
hard_gas_limit_per_operation : Gas.Arith.integral;
}
let init_manager_info ctxt =
{
hard_storage_limit_per_operation =
Constants.hard_storage_limit_per_operation ctxt;
hard_gas_limit_per_operation = Constants.hard_gas_limit_per_operation ctxt;
}
type manager_state = {
managers_seen : Operation_hash.t Signature.Public_key_hash.Map.t;
* To enforce the one - operation - per manager - per - block restriction
( 1 M ) . The operation hash lets us indicate the conflicting
operation in the { ! Manager_restriction } error .
Note that as part of { ! state } , this map
lives in memory . It is not explicitly bounded here , however :
- In block validation mode , it is bounded by the number of
manager operations allowed in the block .
- In mempool mode , bounding the number of operations in this
map is the responsability of the mempool . ( E.g. the plugin used
by has a [ max_prechecked_manager_operations ] parameter to
ensure this . )
(1M). The operation hash lets us indicate the conflicting
operation in the {!Manager_restriction} error.
Note that as part of {!state}, this map
lives in memory. It is not explicitly bounded here, however:
- In block validation mode, it is bounded by the number of
manager operations allowed in the block.
- In mempool mode, bounding the number of operations in this
map is the responsability of the mempool. (E.g. the plugin used
by Octez has a [max_prechecked_manager_operations] parameter to
ensure this.) *)
}
let manager_state_encoding =
let open Data_encoding in
def "manager_state"
@@ conv
(fun {managers_seen} -> managers_seen)
(fun managers_seen -> {managers_seen})
(obj1
(req
"managers_seen"
(Signature.Public_key_hash.Map.encoding Operation_hash.encoding)))
let empty_manager_state = {managers_seen = Signature.Public_key_hash.Map.empty}
type block_info = {
round : Round.t;
locked_round : Round.t option;
predecessor_hash : Block_hash.t;
block_producer : Consensus_key.pk;
payload_producer : Consensus_key.pk;
header_contents : Block_header.contents;
}
type construction_info = {
round : Round.t;
predecessor_hash : Block_hash.t;
block_producer : Consensus_key.pk;
payload_producer : Consensus_key.pk;
header_contents : Block_header.contents;
}
type mode =
| Application of block_info
| Partial_validation of block_info
| Construction of construction_info
| Mempool
* { 2 Definition and initialization of [ info ] and [ state ] }
type info = {
mode : mode;
current_level : Level.t;
consensus_info : consensus_info option;
manager_info : manager_info;
}
type operation_conflict_state = {
consensus_state : consensus_state;
voting_state : voting_state;
anonymous_state : anonymous_state;
manager_state : manager_state;
}
let operation_conflict_state_encoding =
let open Data_encoding in
def "operation_conflict_state"
@@ conv
(fun {consensus_state; voting_state; anonymous_state; manager_state} ->
(consensus_state, voting_state, anonymous_state, manager_state))
(fun (consensus_state, voting_state, anonymous_state, manager_state) ->
{consensus_state; voting_state; anonymous_state; manager_state})
(obj4
(req "consensus_state" consensus_state_encoding)
(req "voting_state" voting_state_encoding)
(req "anonymous_state" anonymous_state_encoding)
(req "manager_state" manager_state_encoding))
type block_state = {
op_count : int;
remaining_block_gas : Gas.Arith.fp;
recorded_operations_rev : Operation_hash.t list;
last_op_validation_pass : int option;
locked_round_evidence : (Round.t * int) option;
endorsement_power : int;
}
type validation_state = {
info : info;
operation_state : operation_conflict_state;
block_state : block_state;
}
let ok_unit = Result_syntax.return_unit
let init_info ctxt mode chain_id ~predecessor_level_and_round =
let consensus_info =
Option.map (init_consensus_info ctxt) predecessor_level_and_round
in
{
ctxt;
mode;
chain_id;
current_level = Level.current ctxt;
consensus_info;
manager_info = init_manager_info ctxt;
}
let empty_voting_state =
{
proposals_seen = Signature.Public_key_hash.Map.empty;
ballots_seen = Signature.Public_key_hash.Map.empty;
}
let empty_operation_conflict_state =
{
consensus_state = empty_consensus_state;
voting_state = empty_voting_state;
anonymous_state = empty_anonymous_state;
manager_state = empty_manager_state;
}
let init_block_state vi =
{
op_count = 0;
remaining_block_gas =
Gas.Arith.fp (Constants.hard_gas_limit_per_block vi.ctxt);
recorded_operations_rev = [];
last_op_validation_pass = None;
locked_round_evidence = None;
endorsement_power = 0;
}
let get_initial_ctxt {info; _} = info.ctxt
module Consensus = struct
open Validate_errors.Consensus
let check_frozen_deposits_are_positive ctxt delegate_pkh =
let open Lwt_result_syntax in
let* frozen_deposits = Delegate.frozen_deposits ctxt delegate_pkh in
fail_unless
Tez.(frozen_deposits.current_amount > zero)
(Zero_frozen_deposits delegate_pkh)
let get_delegate_details slot_map kind slot =
Result.of_option
(Slot.Map.find slot slot_map)
~error:(trace_of_error (Wrong_slot_used_for_consensus_operation {kind}))
let check_round_before_block ~block_round provided =
error_unless
Round.(provided < block_round)
(Preendorsement_round_too_high {block_round; provided})
let check_level kind expected provided =
if Raw_level.equal expected provided then Result.return_unit
else if Raw_level.(expected > provided) then
error (Consensus_operation_for_old_level {kind; expected; provided})
else error (Consensus_operation_for_future_level {kind; expected; provided})
let check_round kind expected provided =
if Round.equal expected provided then Result.return_unit
else if Round.(expected > provided) then
error (Consensus_operation_for_old_round {kind; expected; provided})
else error (Consensus_operation_for_future_round {kind; expected; provided})
let check_payload_hash kind expected provided =
error_unless
(Block_payload_hash.equal expected provided)
(Wrong_payload_hash_for_consensus_operation {kind; expected; provided})
let check_preexisting_block_preendorsement vi consensus_info block_info
{level; round; block_payload_hash = bph; slot} =
let open Lwt_result_syntax in
let*? locked_round =
match block_info.locked_round with
| Some locked_round -> ok locked_round
| None ->
error Unexpected_preendorsement_in_block
in
let kind = Preendorsement in
let*? () = check_round_before_block ~block_round:block_info.round round in
let*? () = check_level kind vi.current_level.level level in
let*? () = check_round kind locked_round round in
let expected_payload_hash = block_info.header_contents.payload_hash in
let*? () = check_payload_hash kind expected_payload_hash bph in
let*? consensus_key, voting_power =
get_delegate_details consensus_info.preendorsement_slot_map kind slot
in
let* () =
check_frozen_deposits_are_positive vi.ctxt consensus_key.delegate
in
return (consensus_key, voting_power)
let check_constructed_block_preendorsement vi consensus_info cons_info
{level; round; block_payload_hash = bph; slot} =
let open Lwt_result_syntax in
let expected_payload_hash = cons_info.header_contents.payload_hash in
let*? () =
When the proposal is fresh , a fake [ payload_hash ] of [ zero ]
has been provided . In this case , the block should not contain
any preendorsements .
has been provided. In this case, the block should not contain
any preendorsements. *)
error_when
Block_payload_hash.(expected_payload_hash = zero)
Unexpected_preendorsement_in_block
in
let kind = Preendorsement in
let*? () = check_round_before_block ~block_round:cons_info.round round in
let*? () = check_level kind vi.current_level.level level in
let*? () = check_payload_hash kind expected_payload_hash bph in
let*? consensus_key, voting_power =
get_delegate_details consensus_info.preendorsement_slot_map kind slot
in
let* () =
check_frozen_deposits_are_positive vi.ctxt consensus_key.delegate
in
return (consensus_key, voting_power)
* Preendorsement / endorsement checks for mode .
We want this mode to be very permissive , to allow the mempool to
accept and propagate consensus operations even if they point to a
block which is not known to the ( e.g. because the block
has just been validated and the mempool has not had time to
switch its head to it yet , or because the block belongs to a
cousin branch ) . Therefore , we do not check the round nor the
payload , which may correspond to blocks that we do not know of
yet . As to the level , we only require it to be the
[ predecessor_level ] ( aka the level of the mempool 's head ) plus or
minus one , that is :
[ predecessor_level - 1 < = op_level < = predecessor_level + 1 ]
( note that [ predecessor_level + 1 ] is also known as [ current_level ] ) .
Return the slot owner 's consensus key and voting power ( the
latter may be fake because it does n't matter in mode , but
it is included to mirror the check_ ... _block_preendorsement
functions ) .
We want this mode to be very permissive, to allow the mempool to
accept and propagate consensus operations even if they point to a
block which is not known to the mempool (e.g. because the block
has just been validated and the mempool has not had time to
switch its head to it yet, or because the block belongs to a
cousin branch). Therefore, we do not check the round nor the
payload, which may correspond to blocks that we do not know of
yet. As to the level, we only require it to be the
[predecessor_level] (aka the level of the mempool's head) plus or
minus one, that is:
[predecessor_level - 1 <= op_level <= predecessor_level + 1]
(note that [predecessor_level + 1] is also known as [current_level]).
Return the slot owner's consensus key and voting power (the
latter may be fake because it doesn't matter in Mempool mode, but
it is included to mirror the check_..._block_preendorsement
functions). *)
let check_mempool_consensus vi consensus_info kind {level; slot; _} =
let open Lwt_result_syntax in
let*? () =
if Raw_level.(succ level < consensus_info.predecessor_level) then
let expected = consensus_info.predecessor_level and provided = level in
error (Consensus_operation_for_old_level {kind; expected; provided})
else if Raw_level.(level > vi.current_level.level) then
let expected = consensus_info.predecessor_level and provided = level in
error (Consensus_operation_for_future_level {kind; expected; provided})
else ok_unit
in
if Raw_level.(level = consensus_info.predecessor_level) then
let slot_map =
match kind with
| Preendorsement -> consensus_info.preendorsement_slot_map
| Endorsement -> consensus_info.endorsement_slot_map
| Dal_attestation -> assert false
in
Lwt.return (get_delegate_details slot_map kind slot)
else
We do n't have a pre - computed slot map for the operation 's
level , so we retrieve the key directly from the context . We
return a fake voting power since it wo n't be used anyway in
mode .
level, so we retrieve the key directly from the context. We
return a fake voting power since it won't be used anyway in
Mempool mode. *)
let* (_ctxt : t), consensus_key =
Stake_distribution.slot_owner
vi.ctxt
(Level.from_raw vi.ctxt level)
slot
in
let check_preendorsement vi ~check_signature
(operation : Kind.preendorsement operation) =
let open Lwt_result_syntax in
let*? consensus_info =
Option.value_e
~error:(trace_of_error Consensus_operation_not_allowed)
vi.consensus_info
in
let (Single (Preendorsement consensus_content)) =
operation.protocol_data.contents
in
let* consensus_key, voting_power =
match vi.mode with
| Application block_info | Partial_validation block_info ->
check_preexisting_block_preendorsement
vi
consensus_info
block_info
consensus_content
| Construction construction_info ->
check_constructed_block_preendorsement
vi
consensus_info
construction_info
consensus_content
| Mempool ->
check_mempool_consensus
vi
consensus_info
Preendorsement
consensus_content
in
let*? () =
if check_signature then
Operation.check_signature
consensus_key.consensus_pk
vi.chain_id
operation
else ok_unit
in
return voting_power
let check_preendorsement_conflict vs oph (op : Kind.preendorsement operation)
=
let (Single (Preendorsement {slot; level; round; _})) =
op.protocol_data.contents
in
match
Consensus_conflict_map.find_opt
(slot, level, round)
vs.consensus_state.preendorsements_seen
with
| Some existing ->
Error (Operation_conflict {existing; new_operation = oph})
| None -> ok_unit
let wrap_preendorsement_conflict = function
| Ok () -> ok_unit
| Error conflict ->
error
Validate_errors.Consensus.(
Conflicting_consensus_operation {kind = Preendorsement; conflict})
let add_preendorsement vs oph (op : Kind.preendorsement operation) =
let (Single (Preendorsement {slot; level; round; _})) =
op.protocol_data.contents
in
let preendorsements_seen =
Consensus_conflict_map.add
(slot, level, round)
oph
vs.consensus_state.preendorsements_seen
in
{vs with consensus_state = {vs.consensus_state with preendorsements_seen}}
let may_update_locked_round_evidence block_state mode
(consensus_content : consensus_content) voting_power =
let locked_round_evidence =
match mode with
| Application _ | Partial_validation _ | Construction _ -> (
match block_state.locked_round_evidence with
| None -> Some (consensus_content.round, voting_power)
| Some (_stored_round, evidences) ->
[ _ stored_round ] is always equal to [ consensus_content.round ] .
Indeed , this is ensured by
{ ! } in
application and partial validation modes , and by
{ ! check_construction_preendorsement_round_consistency } in
construction mode .
Indeed, this is ensured by
{!check_preendorsement_content_preexisting_block} in
application and partial validation modes, and by
{!check_construction_preendorsement_round_consistency} in
construction mode. *)
Some (consensus_content.round, evidences + voting_power))
in
{block_state with locked_round_evidence}
let remove_preendorsement vs (operation : Kind.preendorsement operation) =
As we are in mempool mode , we do not update
[ locked_round_evidence ] .
[locked_round_evidence]. *)
let (Single (Preendorsement {slot; level; round; _})) =
operation.protocol_data.contents
in
let preendorsements_seen =
Consensus_conflict_map.remove
(slot, level, round)
vs.consensus_state.preendorsements_seen
in
{vs with consensus_state = {vs.consensus_state with preendorsements_seen}}
let check_block_endorsement vi consensus_info
{level; round; block_payload_hash = bph; slot} =
let open Lwt_result_syntax in
let*? expected_payload_hash =
match Consensus.endorsement_branch vi.ctxt with
| Some ((_branch : Block_hash.t), payload_hash) -> ok payload_hash
| None ->
[ Consensus.endorsement_branch ] only returns [ None ] when the
predecessor is the block that activates the first protocol
of the family ; this block should not be
endorsed . This can only happen in tests and test
networks .
predecessor is the block that activates the first protocol
of the Tenderbake family; this block should not be
endorsed. This can only happen in tests and test
networks. *)
error Unexpected_endorsement_in_block
in
let kind = Endorsement in
let*? () = check_level kind consensus_info.predecessor_level level in
let*? () = check_round kind consensus_info.predecessor_round round in
let*? () = check_payload_hash kind expected_payload_hash bph in
let*? consensus_key, voting_power =
get_delegate_details consensus_info.endorsement_slot_map kind slot
in
let* () =
check_frozen_deposits_are_positive vi.ctxt consensus_key.delegate
in
return (consensus_key, voting_power)
let check_endorsement vi ~check_signature
(operation : Kind.endorsement operation) =
let open Lwt_result_syntax in
let*? consensus_info =
Option.value_e
~error:(trace_of_error Consensus_operation_not_allowed)
vi.consensus_info
in
let (Single (Endorsement consensus_content)) =
operation.protocol_data.contents
in
let* consensus_key, voting_power =
match vi.mode with
| Application _ | Partial_validation _ | Construction _ ->
check_block_endorsement vi consensus_info consensus_content
| Mempool ->
check_mempool_consensus
vi
consensus_info
Endorsement
consensus_content
in
let*? () =
if check_signature then
Operation.check_signature
consensus_key.consensus_pk
vi.chain_id
operation
else ok_unit
in
return voting_power
let check_endorsement_conflict vs oph (operation : Kind.endorsement operation)
=
let (Single (Endorsement {slot; level; round; _})) =
operation.protocol_data.contents
in
match
Consensus_conflict_map.find_opt
(slot, level, round)
vs.consensus_state.endorsements_seen
with
| None -> ok_unit
| Some existing ->
Error (Operation_conflict {existing; new_operation = oph})
let wrap_endorsement_conflict = function
| Ok () -> ok_unit
| Error conflict ->
error
Validate_errors.Consensus.(
Conflicting_consensus_operation {kind = Endorsement; conflict})
let add_endorsement vs oph (op : Kind.endorsement operation) =
let (Single (Endorsement {slot; level; round; _})) =
op.protocol_data.contents
in
let endorsements_seen =
Consensus_conflict_map.add
(slot, level, round)
oph
vs.consensus_state.endorsements_seen
in
{vs with consensus_state = {vs.consensus_state with endorsements_seen}}
let may_update_endorsement_power vi block_state voting_power =
match vi.mode with
| Application _ | Partial_validation _ | Construction _ ->
{
block_state with
endorsement_power = block_state.endorsement_power + voting_power;
}
let remove_endorsement vs (operation : Kind.endorsement operation) =
let (Single (Endorsement {slot; level; round; _})) =
operation.protocol_data.contents
in
let endorsements_seen =
Consensus_conflict_map.remove
(slot, level, round)
vs.consensus_state.endorsements_seen
in
{vs with consensus_state = {vs.consensus_state with endorsements_seen}}
let check_dal_attestation vi (operation : Kind.dal_attestation operation) =
DAL / FIXME /-/issues/3115
This is a temporary operation . Some checks are missing for the
moment . In particular , the signature is not
checked . Consequently , it is really important to ensure this
operation can not be included into a block when the feature flag
is not set . This is done in order to avoid modifying the
endorsement encoding . However , once the DAL is ready , this
operation should be merged with an endorsement or at least
refined .
This is a temporary operation. Some checks are missing for the
moment. In particular, the signature is not
checked. Consequently, it is really important to ensure this
operation cannot be included into a block when the feature flag
is not set. This is done in order to avoid modifying the
endorsement encoding. However, once the DAL is ready, this
operation should be merged with an endorsement or at least
refined. *)
let open Lwt_result_syntax in
let (Single (Dal_attestation op)) = operation.protocol_data.contents in
let*? () =
Dal_apply.validate_attestation vi.ctxt op
in
return_unit
let check_dal_attestation_conflict vs oph
(operation : Kind.dal_attestation operation) =
let (Single (Dal_attestation {attestor; attestation = _; level = _})) =
operation.protocol_data.contents
in
match
Signature.Public_key_hash.Map.find_opt
attestor
vs.consensus_state.dal_attestation_seen
with
| None -> ok_unit
| Some existing ->
Error (Operation_conflict {existing; new_operation = oph})
let wrap_dal_attestation_conflict = function
| Ok () -> ok_unit
| Error conflict ->
error
Validate_errors.Consensus.(
Conflicting_consensus_operation {kind = Dal_attestation; conflict})
let add_dal_attestation vs oph (operation : Kind.dal_attestation operation) =
let (Single (Dal_attestation {attestor; attestation = _; level = _})) =
operation.protocol_data.contents
in
{
vs with
consensus_state =
{
vs.consensus_state with
dal_attestation_seen =
Signature.Public_key_hash.Map.add
attestor
oph
vs.consensus_state.dal_attestation_seen;
};
}
let remove_dal_attestation vs (operation : Kind.dal_attestation operation) =
let (Single (Dal_attestation {attestor; attestation = _; level = _})) =
operation.protocol_data.contents
in
let dal_attestation_seen =
Signature.Public_key_hash.Map.remove
attestor
vs.consensus_state.dal_attestation_seen
in
{vs with consensus_state = {vs.consensus_state with dal_attestation_seen}}
* In Construction mode , check that the preendorsement has the same
round as any previously validated preendorsements .
This check is not needed in other modes because
{ ! check_preendorsement } already checks that all preendorsements
have the same expected round ( the locked_round in Application and
Partial_validation modes when there is one ( otherwise all
preendorsements are rejected so the point is moot ) , or the
predecessor_round in mode ) .
round as any previously validated preendorsements.
This check is not needed in other modes because
{!check_preendorsement} already checks that all preendorsements
have the same expected round (the locked_round in Application and
Partial_validation modes when there is one (otherwise all
preendorsements are rejected so the point is moot), or the
predecessor_round in Mempool mode). *)
let check_construction_preendorsement_round_consistency vi block_state
(consensus_content : consensus_content) =
let open Result_syntax in
match vi.mode with
| Construction _ -> (
match block_state.locked_round_evidence with
| None ->
This is the first validated preendorsement :
there is nothing to check .
there is nothing to check. *)
return_unit
| Some (expected, _power) ->
check_round Preendorsement expected consensus_content.round)
| Application _ | Partial_validation _ | Mempool -> return_unit
let validate_preendorsement ~check_signature info operation_state block_state
oph (operation : Kind.preendorsement operation) =
let open Lwt_result_syntax in
let (Single (Preendorsement consensus_content)) =
operation.protocol_data.contents
in
let* voting_power = check_preendorsement info ~check_signature operation in
let*? () =
check_construction_preendorsement_round_consistency
info
block_state
consensus_content
in
let*? () =
check_preendorsement_conflict operation_state oph operation
|> wrap_preendorsement_conflict
in
let block_state =
may_update_locked_round_evidence
block_state
info.mode
consensus_content
voting_power
in
let operation_state = add_preendorsement operation_state oph operation in
return {info; operation_state; block_state}
let validate_endorsement ~check_signature info operation_state block_state oph
operation =
let open Lwt_result_syntax in
let* power = check_endorsement info ~check_signature operation in
let*? () =
check_endorsement_conflict operation_state oph operation
|> wrap_endorsement_conflict
in
let block_state = may_update_endorsement_power info block_state power in
let operation_state = add_endorsement operation_state oph operation in
return {info; operation_state; block_state}
end
* { 2 Validation of voting operations }
There are two kinds of voting operations :
- Proposals : A delegate submits a list of protocol amendment
proposals . This operation is only accepted during a Proposal period
( see above ) .
- Ballot : A delegate casts a vote for / against the current proposal
( or pass ) . This operation is only accepted during an Exploration
or Promotion period ( see above ) .
There are two kinds of voting operations:
- Proposals: A delegate submits a list of protocol amendment
proposals. This operation is only accepted during a Proposal period
(see above).
- Ballot: A delegate casts a vote for/against the current proposal
(or pass). This operation is only accepted during an Exploration
or Promotion period (see above). *)
module Voting = struct
open Validate_errors.Voting
let check_period_index ~expected period_index =
error_unless
Compare.Int32.(expected = period_index)
(Wrong_voting_period_index {expected; provided = period_index})
let check_proposals_source_is_registered ctxt source =
let open Lwt_result_syntax in
let*! is_registered = Delegate.registered ctxt source in
fail_unless is_registered (Proposals_from_unregistered_delegate source)
let check_proposal_list_sanity proposals =
let open Result_syntax in
let* () =
match proposals with [] -> error Empty_proposals | _ :: _ -> ok_unit
in
let* (_ : Protocol_hash.Set.t) =
List.fold_left_e
(fun previous_elements proposal ->
let* () =
error_when
(Protocol_hash.Set.mem proposal previous_elements)
(Proposals_contain_duplicate {proposal})
in
return (Protocol_hash.Set.add proposal previous_elements))
Protocol_hash.Set.empty
proposals
in
return_unit
let check_period_kind_for_proposals current_period =
match current_period.Voting_period.kind with
| Proposal -> ok_unit
| (Exploration | Cooldown | Promotion | Adoption) as current ->
error (Wrong_voting_period_kind {current; expected = [Proposal]})
let check_in_listings ctxt source =
let open Lwt_result_syntax in
let*! in_listings = Vote.in_listings ctxt source in
fail_unless in_listings Source_not_in_vote_listings
let check_count ~count_in_ctxt ~proposals_length =
assert (Compare.Int.(count_in_ctxt <= Constants.max_proposals_per_delegate)) ;
error_unless
Compare.Int.(
count_in_ctxt + proposals_length <= Constants.max_proposals_per_delegate)
(Too_many_proposals
{previous_count = count_in_ctxt; operation_count = proposals_length})
let check_already_proposed ctxt proposer proposals =
let open Lwt_result_syntax in
List.iter_es
(fun proposal ->
let*! already_proposed = Vote.has_proposed ctxt proposer proposal in
fail_when already_proposed (Already_proposed {proposal}))
proposals
* Check that the [ apply_testnet_dictator_proposals ] function in
{ ! module : Amendment } will not fail .
The current function is designed to be exclusively called by
[ check_proposals ] right below .
@return [ Error Testnet_dictator_multiple_proposals ] if
[ proposals ] has more than one element .
{!module:Amendment} will not fail.
The current function is designed to be exclusively called by
[check_proposals] right below.
@return [Error Testnet_dictator_multiple_proposals] if
[proposals] has more than one element. *)
let check_testnet_dictator_proposals chain_id proposals =
assert (Chain_id.(chain_id <> Constants.mainnet_id)) ;
match proposals with
| [] | [_] ->
ok_unit
| _ :: _ :: _ -> error Testnet_dictator_multiple_proposals
* Check that a Proposals operation can be safely applied .
@return [ Error Wrong_voting_period_index ] if the operation 's
period and the current period in the { ! type : context } do not have
the same index .
@return [ Error Proposals_from_unregistered_delegate ] if the
source is not a registered delegate .
@return [ Error Empty_proposals ] if the list of proposals is empty .
@return [ Error Proposals_contain_duplicate ] if the list of
proposals contains a duplicate element .
@return [ Error Wrong_voting_period_kind ] if the voting period is
not of the Proposal kind .
@return [ Error Source_not_in_vote_listings ] if the source is not
in the vote listings .
@return [ Error Too_many_proposals ] if the operation causes the
source 's total number of proposals during the current voting
period to exceed { ! Constants.max_proposals_per_delegate } .
@return [ Error Already_proposed ] if one of the proposals has
already been proposed by the source in the current voting period .
@return [ Error Testnet_dictator_multiple_proposals ] if the
source is a testnet dictator and the operation contains more than
one proposal .
@return [ Error Operation . Missing_signature ] or [ Error
Operation . Invalid_signature ] if the operation is unsigned or
incorrectly signed .
@return [Error Wrong_voting_period_index] if the operation's
period and the current period in the {!type:context} do not have
the same index.
@return [Error Proposals_from_unregistered_delegate] if the
source is not a registered delegate.
@return [Error Empty_proposals] if the list of proposals is empty.
@return [Error Proposals_contain_duplicate] if the list of
proposals contains a duplicate element.
@return [Error Wrong_voting_period_kind] if the voting period is
not of the Proposal kind.
@return [Error Source_not_in_vote_listings] if the source is not
in the vote listings.
@return [Error Too_many_proposals] if the operation causes the
source's total number of proposals during the current voting
period to exceed {!Constants.max_proposals_per_delegate}.
@return [Error Already_proposed] if one of the proposals has
already been proposed by the source in the current voting period.
@return [Error Testnet_dictator_multiple_proposals] if the
source is a testnet dictator and the operation contains more than
one proposal.
@return [Error Operation.Missing_signature] or [Error
Operation.Invalid_signature] if the operation is unsigned or
incorrectly signed. *)
let check_proposals vi ~check_signature (operation : Kind.proposals operation)
=
let open Lwt_result_syntax in
let (Single (Proposals {source; period; proposals})) =
operation.protocol_data.contents
in
let* current_period = Voting_period.get_current vi.ctxt in
let*? () = check_period_index ~expected:current_period.index period in
let* () =
if Amendment.is_testnet_dictator vi.ctxt vi.chain_id source then
let*? () = check_testnet_dictator_proposals vi.chain_id proposals in
return_unit
else
let* () = check_proposals_source_is_registered vi.ctxt source in
let*? () = check_proposal_list_sanity proposals in
let*? () = check_period_kind_for_proposals current_period in
let* () = check_in_listings vi.ctxt source in
let* count_in_ctxt = Vote.get_delegate_proposal_count vi.ctxt source in
let proposals_length = List.length proposals in
let*? () = check_count ~count_in_ctxt ~proposals_length in
check_already_proposed vi.ctxt source proposals
in
if check_signature then
let* public_key = Contract.get_manager_key vi.ctxt source in
Lwt.return (Operation.check_signature public_key vi.chain_id operation)
else return_unit
* Check that a Proposals operation is compatible with previously
validated operations in the current block / mempool .
@return [ Error Operation_conflict ] if the current block / mempool
already contains a Proposals operation from the same source
( regardless of whether this source is a testnet dictator or an
ordinary manager ) .
validated operations in the current block/mempool.
@return [Error Operation_conflict] if the current block/mempool
already contains a Proposals operation from the same source
(regardless of whether this source is a testnet dictator or an
ordinary manager). *)
let check_proposals_conflict vs oph (operation : Kind.proposals operation) =
let open Result_syntax in
let (Single (Proposals {source; _})) = operation.protocol_data.contents in
match
Signature.Public_key_hash.Map.find_opt
source
vs.voting_state.proposals_seen
with
| None -> return_unit
| Some existing ->
Error (Operation_conflict {existing; new_operation = oph})
let wrap_proposals_conflict = function
| Ok () -> ok_unit
| Error conflict ->
error Validate_errors.Voting.(Conflicting_proposals conflict)
let add_proposals vs oph (operation : Kind.proposals operation) =
let (Single (Proposals {source; _})) = operation.protocol_data.contents in
let proposals_seen =
Signature.Public_key_hash.Map.add
source
oph
vs.voting_state.proposals_seen
in
let voting_state = {vs.voting_state with proposals_seen} in
{vs with voting_state}
let remove_proposals vs (operation : Kind.proposals operation) =
let (Single (Proposals {source; _})) = operation.protocol_data.contents in
let proposals_seen =
Signature.Public_key_hash.Map.remove source vs.voting_state.proposals_seen
in
{vs with voting_state = {vs.voting_state with proposals_seen}}
let check_ballot_source_is_registered ctxt source =
let open Lwt_result_syntax in
let*! is_registered = Delegate.registered ctxt source in
fail_unless is_registered (Ballot_from_unregistered_delegate source)
let check_period_kind_for_ballot current_period =
match current_period.Voting_period.kind with
| Exploration | Promotion -> ok_unit
| (Cooldown | Proposal | Adoption) as current ->
error
(Wrong_voting_period_kind
{current; expected = [Exploration; Promotion]})
let check_current_proposal ctxt op_proposal =
let open Lwt_result_syntax in
let* current_proposal = Vote.get_current_proposal ctxt in
fail_unless
(Protocol_hash.equal op_proposal current_proposal)
(Ballot_for_wrong_proposal
{current = current_proposal; submitted = op_proposal})
let check_source_has_not_already_voted ctxt source =
let open Lwt_result_syntax in
let*! has_ballot = Vote.has_recorded_ballot ctxt source in
fail_when has_ballot Already_submitted_a_ballot
* Check that a Ballot operation can be safely applied .
@return [ Error Ballot_from_unregistered_delegate ] if the source
is not a registered delegate .
@return [ Error Wrong_voting_period_index ] if the operation 's
period and the current period in the { ! type : context } do not have
the same index .
@return [ Error Wrong_voting_period_kind ] if the voting period is
not of the Exploration or Promotion kind .
@return [ Error Ballot_for_wrong_proposal ] if the operation 's
proposal is different from the current proposal in the context .
@return [ Error Already_submitted_a_ballot ] if the source has
already voted during the current voting period .
@return [ Error Source_not_in_vote_listings ] if the source is not
in the vote listings .
@return [ Error Operation . Missing_signature ] or [ Error
Operation . Invalid_signature ] if the operation is unsigned or
incorrectly signed .
@return [Error Ballot_from_unregistered_delegate] if the source
is not a registered delegate.
@return [Error Wrong_voting_period_index] if the operation's
period and the current period in the {!type:context} do not have
the same index.
@return [Error Wrong_voting_period_kind] if the voting period is
not of the Exploration or Promotion kind.
@return [Error Ballot_for_wrong_proposal] if the operation's
proposal is different from the current proposal in the context.
@return [Error Already_submitted_a_ballot] if the source has
already voted during the current voting period.
@return [Error Source_not_in_vote_listings] if the source is not
in the vote listings.
@return [Error Operation.Missing_signature] or [Error
Operation.Invalid_signature] if the operation is unsigned or
incorrectly signed. *)
let check_ballot vi ~check_signature (operation : Kind.ballot operation) =
let open Lwt_result_syntax in
let (Single (Ballot {source; period; proposal; ballot = _})) =
operation.protocol_data.contents
in
let* () = check_ballot_source_is_registered vi.ctxt source in
let* current_period = Voting_period.get_current vi.ctxt in
let*? () = check_period_index ~expected:current_period.index period in
let*? () = check_period_kind_for_ballot current_period in
let* () = check_current_proposal vi.ctxt proposal in
let* () = check_source_has_not_already_voted vi.ctxt source in
let* () = check_in_listings vi.ctxt source in
when_ check_signature (fun () ->
let* public_key = Contract.get_manager_key vi.ctxt source in
Lwt.return (Operation.check_signature public_key vi.chain_id operation))
* Check that a Ballot operation is compatible with previously
validated operations in the current block / mempool .
@return [ Error Operation_conflict ] if the current block / mempool
already contains a Ballot operation from the same source .
validated operations in the current block/mempool.
@return [Error Operation_conflict] if the current block/mempool
already contains a Ballot operation from the same source. *)
let check_ballot_conflict vs oph (operation : Kind.ballot operation) =
let (Single (Ballot {source; _})) = operation.protocol_data.contents in
match
Signature.Public_key_hash.Map.find_opt source vs.voting_state.ballots_seen
with
| None -> ok_unit
| Some existing ->
Error (Operation_conflict {existing; new_operation = oph})
let wrap_ballot_conflict = function
| Ok () -> ok_unit
| Error conflict -> error (Conflicting_ballot conflict)
let add_ballot vs oph (operation : Kind.ballot operation) =
let (Single (Ballot {source; _})) = operation.protocol_data.contents in
let ballots_seen =
Signature.Public_key_hash.Map.add source oph vs.voting_state.ballots_seen
in
let voting_state = {vs.voting_state with ballots_seen} in
{vs with voting_state}
let remove_ballot vs (operation : Kind.ballot operation) =
let (Single (Ballot {source; _})) = operation.protocol_data.contents in
let ballots_seen =
Signature.Public_key_hash.Map.remove source vs.voting_state.ballots_seen
in
{vs with voting_state = {vs.voting_state with ballots_seen}}
end
module Anonymous = struct
open Validate_errors.Anonymous
let check_activate_account vi (operation : Kind.activate_account operation) =
let (Single (Activate_account {id = edpkh; activation_code})) =
operation.protocol_data.contents
in
let open Lwt_result_syntax in
let blinded_pkh =
Blinded_public_key_hash.of_ed25519_pkh activation_code edpkh
in
let*! exists = Commitment.exists vi.ctxt blinded_pkh in
let*? () = error_unless exists (Invalid_activation {pkh = edpkh}) in
return_unit
let check_activate_account_conflict vs oph
(operation : Kind.activate_account operation) =
let (Single (Activate_account {id = edpkh; _})) =
operation.protocol_data.contents
in
match
Ed25519.Public_key_hash.Map.find_opt
edpkh
vs.anonymous_state.activation_pkhs_seen
with
| None -> ok_unit
| Some existing ->
Error (Operation_conflict {existing; new_operation = oph})
let wrap_activate_account_conflict
(operation : Kind.activate_account operation) = function
| Ok () -> ok_unit
| Error conflict ->
let (Single (Activate_account {id = edpkh; _})) =
operation.protocol_data.contents
in
error (Conflicting_activation {edpkh; conflict})
let add_activate_account vs oph (operation : Kind.activate_account operation)
=
let (Single (Activate_account {id = edpkh; _})) =
operation.protocol_data.contents
in
let activation_pkhs_seen =
Ed25519.Public_key_hash.Map.add
edpkh
oph
vs.anonymous_state.activation_pkhs_seen
in
{vs with anonymous_state = {vs.anonymous_state with activation_pkhs_seen}}
let remove_activate_account vs (operation : Kind.activate_account operation) =
let (Single (Activate_account {id = edpkh; _})) =
operation.protocol_data.contents
in
let activation_pkhs_seen =
Ed25519.Public_key_hash.Map.remove
edpkh
vs.anonymous_state.activation_pkhs_seen
in
{vs with anonymous_state = {vs.anonymous_state with activation_pkhs_seen}}
let check_denunciation_age vi kind given_level =
let open Result_syntax in
let current_cycle = vi.current_level.cycle in
let given_cycle = (Level.from_raw vi.ctxt given_level).cycle in
let max_slashing_period = Constants.max_slashing_period vi.ctxt in
let last_slashable_cycle = Cycle.add given_cycle max_slashing_period in
let* () =
error_unless
Cycle.(given_cycle <= current_cycle)
(Too_early_denunciation
{kind; level = given_level; current = vi.current_level.level})
in
error_unless
Cycle.(last_slashable_cycle > current_cycle)
(Outdated_denunciation
{kind; level = given_level; last_cycle = last_slashable_cycle})
let check_double_endorsing_evidence (type kind)
~consensus_operation:denunciation_kind vi
(op1 : kind Kind.consensus Operation.t)
(op2 : kind Kind.consensus Operation.t) =
let open Lwt_result_syntax in
match (op1.protocol_data.contents, op2.protocol_data.contents) with
| Single (Preendorsement e1), Single (Preendorsement e2)
| Single (Endorsement e1), Single (Endorsement e2) ->
let op1_hash = Operation.hash op1 in
let op2_hash = Operation.hash op2 in
let same_levels = Raw_level.(e1.level = e2.level) in
let same_rounds = Round.(e1.round = e2.round) in
let same_payload =
Block_payload_hash.(e1.block_payload_hash = e2.block_payload_hash)
in
let same_branches = Block_hash.(op1.shell.branch = op2.shell.branch) in
let ordered_hashes = Operation_hash.(op1_hash < op2_hash) in
let is_denunciation_consistent =
same_levels && same_rounds
&& ((not same_payload) || not same_branches)
ordered_hashes
in
let*? () =
error_unless
is_denunciation_consistent
(Invalid_denunciation denunciation_kind)
in
Disambiguate : levels are equal
let level = Level.from_raw vi.ctxt e1.level in
let*? () = check_denunciation_age vi denunciation_kind level.level in
let* ctxt, consensus_key1 =
Stake_distribution.slot_owner vi.ctxt level e1.slot
in
let* ctxt, consensus_key2 =
Stake_distribution.slot_owner ctxt level e2.slot
in
let delegate1, delegate2 =
(consensus_key1.delegate, consensus_key2.delegate)
in
let*? () =
error_unless
(Signature.Public_key_hash.equal delegate1 delegate2)
(Inconsistent_denunciation
{kind = denunciation_kind; delegate1; delegate2})
in
let delegate_pk, delegate = (consensus_key1.consensus_pk, delegate1) in
let* already_slashed =
Delegate.already_slashed_for_double_endorsing ctxt delegate level
in
let*? () =
error_unless
(not already_slashed)
(Already_denounced {kind = denunciation_kind; delegate; level})
in
let*? () = Operation.check_signature delegate_pk vi.chain_id op1 in
let*? () = Operation.check_signature delegate_pk vi.chain_id op2 in
return_unit
let check_double_preendorsement_evidence vi
(operation : Kind.double_preendorsement_evidence operation) =
let (Single (Double_preendorsement_evidence {op1; op2})) =
operation.protocol_data.contents
in
check_double_endorsing_evidence
~consensus_operation:Preendorsement
vi
op1
op2
let check_double_endorsement_evidence vi
(operation : Kind.double_endorsement_evidence operation) =
let (Single (Double_endorsement_evidence {op1; op2})) =
operation.protocol_data.contents
in
check_double_endorsing_evidence ~consensus_operation:Endorsement vi op1 op2
let check_double_endorsing_evidence_conflict (type kind) vs oph
(op1 : kind Kind.consensus Operation.t) =
match op1.protocol_data.contents with
| Single (Preendorsement e1) | Single (Endorsement e1) -> (
match
Double_endorsing_evidence_map.find
(e1.level, e1.round, e1.slot)
vs.anonymous_state.double_endorsing_evidences_seen
with
| None -> ok_unit
| Some existing ->
Error (Operation_conflict {existing; new_operation = oph}))
let check_double_preendorsement_evidence_conflict vs oph
(operation : Kind.double_preendorsement_evidence operation) =
let (Single (Double_preendorsement_evidence {op1; _})) =
operation.protocol_data.contents
in
check_double_endorsing_evidence_conflict vs oph op1
let check_double_endorsement_evidence_conflict vs oph
(operation : Kind.double_endorsement_evidence operation) =
let (Single (Double_endorsement_evidence {op1; _})) =
operation.protocol_data.contents
in
check_double_endorsing_evidence_conflict vs oph op1
let wrap_denunciation_conflict kind = function
| Ok () -> ok_unit
| Error conflict -> error (Conflicting_denunciation {kind; conflict})
let add_double_endorsing_evidence (type kind) vs oph
(op1 : kind Kind.consensus Operation.t) =
match op1.protocol_data.contents with
| Single (Preendorsement e1) | Single (Endorsement e1) ->
let double_endorsing_evidences_seen =
Double_endorsing_evidence_map.add
(e1.level, e1.round, e1.slot)
oph
vs.anonymous_state.double_endorsing_evidences_seen
in
{
vs with
anonymous_state =
{vs.anonymous_state with double_endorsing_evidences_seen};
}
let add_double_endorsement_evidence vs oph
(operation : Kind.double_endorsement_evidence operation) =
let (Single (Double_endorsement_evidence {op1; _})) =
operation.protocol_data.contents
in
add_double_endorsing_evidence vs oph op1
let add_double_preendorsement_evidence vs oph
(operation : Kind.double_preendorsement_evidence operation) =
let (Single (Double_preendorsement_evidence {op1; _})) =
operation.protocol_data.contents
in
add_double_endorsing_evidence vs oph op1
let remove_double_endorsing_evidence (type kind) vs
(op : kind Kind.consensus Operation.t) =
match op.protocol_data.contents with
| Single (Endorsement e) | Single (Preendorsement e) ->
let double_endorsing_evidences_seen =
Double_endorsing_evidence_map.remove
(e.level, e.round, e.slot)
vs.anonymous_state.double_endorsing_evidences_seen
in
let anonymous_state =
{vs.anonymous_state with double_endorsing_evidences_seen}
in
{vs with anonymous_state}
let remove_double_preendorsement_evidence vs
(operation : Kind.double_preendorsement_evidence operation) =
let (Single (Double_preendorsement_evidence {op1; _})) =
operation.protocol_data.contents
in
remove_double_endorsing_evidence vs op1
let remove_double_endorsement_evidence vs
(operation : Kind.double_endorsement_evidence operation) =
let (Single (Double_endorsement_evidence {op1; _})) =
operation.protocol_data.contents
in
remove_double_endorsing_evidence vs op1
let check_double_baking_evidence vi
(operation : Kind.double_baking_evidence operation) =
let open Lwt_result_syntax in
let (Single (Double_baking_evidence {bh1; bh2})) =
operation.protocol_data.contents
in
let hash1 = Block_header.hash bh1 in
let hash2 = Block_header.hash bh2 in
let*? bh1_fitness = Fitness.from_raw bh1.shell.fitness in
let round1 = Fitness.round bh1_fitness in
let*? bh2_fitness = Fitness.from_raw bh2.shell.fitness in
let round2 = Fitness.round bh2_fitness in
let*? level1 = Raw_level.of_int32 bh1.shell.level in
let*? level2 = Raw_level.of_int32 bh2.shell.level in
let*? () =
error_unless
(Raw_level.(level1 = level2)
&& Round.(round1 = round2)
Block_hash.(hash1 < hash2))
(Invalid_double_baking_evidence
{hash1; level1; round1; hash2; level2; round2})
in
let*? () = check_denunciation_age vi Block level1 in
let level = Level.from_raw vi.ctxt level1 in
let committee_size = Constants.consensus_committee_size vi.ctxt in
let*? slot1 = Round.to_slot round1 ~committee_size in
let* ctxt, consensus_key1 =
Stake_distribution.slot_owner vi.ctxt level slot1
in
let*? slot2 = Round.to_slot round2 ~committee_size in
let* ctxt, consensus_key2 =
Stake_distribution.slot_owner ctxt level slot2
in
let delegate1, delegate2 =
(consensus_key1.delegate, consensus_key2.delegate)
in
let*? () =
error_unless
Signature.Public_key_hash.(delegate1 = delegate2)
(Inconsistent_denunciation {kind = Block; delegate1; delegate2})
in
let delegate_pk, delegate = (consensus_key1.consensus_pk, delegate1) in
let* already_slashed =
Delegate.already_slashed_for_double_baking ctxt delegate level
in
let*? () =
error_unless
(not already_slashed)
(Already_denounced {kind = Block; delegate; level})
in
let*? () = Block_header.check_signature bh1 vi.chain_id delegate_pk in
let*? () = Block_header.check_signature bh2 vi.chain_id delegate_pk in
return_unit
let check_double_baking_evidence_conflict vs oph
(operation : Kind.double_baking_evidence operation) =
let (Single (Double_baking_evidence {bh1; _})) =
operation.protocol_data.contents
in
let bh1_fitness =
Fitness.from_raw bh1.shell.fitness |> function
| Ok f -> f
| Error _ ->
assert false
in
let round = Fitness.round bh1_fitness in
let level = Fitness.level bh1_fitness in
match
Double_baking_evidence_map.find
(level, round)
vs.anonymous_state.double_baking_evidences_seen
with
| None -> ok_unit
| Some existing ->
Error (Operation_conflict {existing; new_operation = oph})
let add_double_baking_evidence vs oph
(operation : Kind.double_baking_evidence operation) =
let (Single (Double_baking_evidence {bh1; _})) =
operation.protocol_data.contents
in
let bh1_fitness =
Fitness.from_raw bh1.shell.fitness |> function
| Ok f -> f
| Error _ -> assert false
in
let round = Fitness.round bh1_fitness in
let level = Fitness.level bh1_fitness in
let double_baking_evidences_seen =
Double_baking_evidence_map.add
(level, round)
oph
vs.anonymous_state.double_baking_evidences_seen
in
{
vs with
anonymous_state = {vs.anonymous_state with double_baking_evidences_seen};
}
let remove_double_baking_evidence vs
(operation : Kind.double_baking_evidence operation) =
let (Single (Double_baking_evidence {bh1; _})) =
operation.protocol_data.contents
in
let bh1_fitness, level =
match
(Fitness.from_raw bh1.shell.fitness, Raw_level.of_int32 bh1.shell.level)
with
| Ok v, Ok v' -> (v, v')
| _ ->
assert false
in
let round = Fitness.round bh1_fitness in
let double_baking_evidences_seen =
Double_baking_evidence_map.remove
(level, round)
vs.anonymous_state.double_baking_evidences_seen
in
let anonymous_state =
{vs.anonymous_state with double_baking_evidences_seen}
in
{vs with anonymous_state}
let check_drain_delegate info ~check_signature
(operation : Kind.drain_delegate Operation.t) =
let open Lwt_result_syntax in
let (Single (Drain_delegate {delegate; destination; consensus_key})) =
operation.protocol_data.contents
in
let*! is_registered = Delegate.registered info.ctxt delegate in
let* () =
fail_unless
is_registered
(Drain_delegate_on_unregistered_delegate delegate)
in
let* active_pk = Delegate.Consensus_key.active_pubkey info.ctxt delegate in
let* () =
fail_unless
(Signature.Public_key_hash.equal active_pk.consensus_pkh consensus_key)
(Invalid_drain_delegate_inactive_key
{
delegate;
consensus_key;
active_consensus_key = active_pk.consensus_pkh;
})
in
let* () =
fail_when
(Signature.Public_key_hash.equal active_pk.consensus_pkh delegate)
(Invalid_drain_delegate_no_consensus_key delegate)
in
let* () =
fail_when
(Signature.Public_key_hash.equal destination delegate)
(Invalid_drain_delegate_noop delegate)
in
let*! is_destination_allocated =
Contract.allocated info.ctxt (Contract.Implicit destination)
in
let* balance =
Contract.get_balance info.ctxt (Contract.Implicit delegate)
in
let*? origination_burn =
if is_destination_allocated then ok Tez.zero
else
let cost_per_byte = Constants.cost_per_byte info.ctxt in
let origination_size = Constants.origination_size info.ctxt in
Tez.(cost_per_byte *? Int64.of_int origination_size)
in
let* drain_fees =
let*? one_percent = Tez.(balance /? 100L) in
return Tez.(max one one_percent)
in
let*? min_amount = Tez.(origination_burn +? drain_fees) in
let* () =
fail_when
Tez.(balance < min_amount)
(Invalid_drain_delegate_insufficient_funds_for_burn_or_fees
{delegate; destination; min_amount})
in
let*? () =
if check_signature then
Operation.check_signature active_pk.consensus_pk info.chain_id operation
else ok_unit
in
return_unit
let check_drain_delegate_conflict state oph
(operation : Kind.drain_delegate Operation.t) =
let (Single (Drain_delegate {delegate; _})) =
operation.protocol_data.contents
in
match
Signature.Public_key_hash.Map.find_opt
delegate
state.manager_state.managers_seen
with
| None -> ok_unit
| Some existing ->
Error (Operation_conflict {existing; new_operation = oph})
let wrap_drain_delegate_conflict (operation : Kind.drain_delegate Operation.t)
=
let (Single (Drain_delegate {delegate; _})) =
operation.protocol_data.contents
in
function
| Ok () -> ok_unit
| Error conflict -> error (Conflicting_drain_delegate {delegate; conflict})
let add_drain_delegate state oph (operation : Kind.drain_delegate Operation.t)
=
let (Single (Drain_delegate {delegate; _})) =
operation.protocol_data.contents
in
let managers_seen =
Signature.Public_key_hash.Map.add
delegate
oph
state.manager_state.managers_seen
in
{state with manager_state = {managers_seen}}
let remove_drain_delegate state (operation : Kind.drain_delegate Operation.t)
=
let (Single (Drain_delegate {delegate; _})) =
operation.protocol_data.contents
in
let managers_seen =
Signature.Public_key_hash.Map.remove
delegate
state.manager_state.managers_seen
in
{state with manager_state = {managers_seen}}
let check_seed_nonce_revelation vi
(operation : Kind.seed_nonce_revelation operation) =
let open Lwt_result_syntax in
let (Single (Seed_nonce_revelation {level = commitment_raw_level; nonce})) =
operation.protocol_data.contents
in
let commitment_level = Level.from_raw vi.ctxt commitment_raw_level in
let* () = Nonce.check_unrevealed vi.ctxt commitment_level nonce in
return_unit
let check_seed_nonce_revelation_conflict vs oph
(operation : Kind.seed_nonce_revelation operation) =
let (Single (Seed_nonce_revelation {level = commitment_raw_level; _})) =
operation.protocol_data.contents
in
match
Raw_level.Map.find_opt
commitment_raw_level
vs.anonymous_state.seed_nonce_levels_seen
with
| None -> ok_unit
| Some existing ->
Error (Operation_conflict {existing; new_operation = oph})
let wrap_seed_nonce_revelation_conflict = function
| Ok () -> ok_unit
| Error conflict -> error (Conflicting_nonce_revelation conflict)
let add_seed_nonce_revelation vs oph
(operation : Kind.seed_nonce_revelation operation) =
let (Single (Seed_nonce_revelation {level = commitment_raw_level; _})) =
operation.protocol_data.contents
in
let seed_nonce_levels_seen =
Raw_level.Map.add
commitment_raw_level
oph
vs.anonymous_state.seed_nonce_levels_seen
in
let anonymous_state = {vs.anonymous_state with seed_nonce_levels_seen} in
{vs with anonymous_state}
let remove_seed_nonce_revelation vs
(operation : Kind.seed_nonce_revelation operation) =
let (Single (Seed_nonce_revelation {level = commitment_raw_level; _})) =
operation.protocol_data.contents
in
let seed_nonce_levels_seen =
Raw_level.Map.remove
commitment_raw_level
vs.anonymous_state.seed_nonce_levels_seen
in
let anonymous_state = {vs.anonymous_state with seed_nonce_levels_seen} in
{vs with anonymous_state}
let check_vdf_revelation vi (operation : Kind.vdf_revelation operation) =
let open Lwt_result_syntax in
let (Single (Vdf_revelation {solution})) =
operation.protocol_data.contents
in
let* () = Seed.check_vdf vi.ctxt solution in
return_unit
let check_vdf_revelation_conflict vs oph =
match vs.anonymous_state.vdf_solution_seen with
| None -> ok_unit
| Some existing ->
Error (Operation_conflict {existing; new_operation = oph})
let wrap_vdf_revelation_conflict = function
| Ok () -> ok_unit
| Error conflict -> error (Conflicting_vdf_revelation conflict)
let add_vdf_revelation vs oph =
{
vs with
anonymous_state = {vs.anonymous_state with vdf_solution_seen = Some oph};
}
let remove_vdf_revelation vs =
let anonymous_state = {vs.anonymous_state with vdf_solution_seen = None} in
{vs with anonymous_state}
end
module Manager = struct
open Validate_errors.Manager
type batch_state = {
balance : Tez.t;
is_allocated : bool;
total_gas_used : Gas.Arith.fp;
}
* Check a few simple properties of the batch , and return the
initial { ! batch_state } and the contract public key .
Invariants checked :
- All operations in a batch have the same source .
- The source 's contract is allocated .
- The counters in a batch are successive , and the first of them
is the source 's next expected counter .
- A batch contains at most one Reveal operation that must occur
in first position .
- The source 's public key has been revealed ( either before the
considered batch , or during its first operation ) .
Note that currently , the [ op ] batch contains only one signature ,
so all operations in the batch are required to originate from the
same manager . This may change in the future , in order to allow
several managers to group - sign a sequence of operations .
initial {!batch_state} and the contract public key.
Invariants checked:
- All operations in a batch have the same source.
- The source's contract is allocated.
- The counters in a batch are successive, and the first of them
is the source's next expected counter.
- A batch contains at most one Reveal operation that must occur
in first position.
- The source's public key has been revealed (either before the
considered batch, or during its first operation).
Note that currently, the [op] batch contains only one signature,
so all operations in the batch are required to originate from the
same manager. This may change in the future, in order to allow
several managers to group-sign a sequence of operations. *)
let check_sanity_and_find_public_key vi
(contents_list : _ Kind.manager contents_list) =
let open Result_syntax in
let check_source_and_counter ~expected_source ~source ~previous_counter
~counter =
let* () =
error_unless
(Signature.Public_key_hash.equal expected_source source)
Inconsistent_sources
in
error_unless
Manager_counter.(succ previous_counter = counter)
Inconsistent_counters
in
let rec check_batch_tail_sanity :
type kind.
public_key_hash ->
Manager_counter.t ->
kind Kind.manager contents_list ->
unit tzresult =
fun expected_source previous_counter -> function
| Single (Manager_operation {operation = Reveal _key; _}) ->
error Incorrect_reveal_position
| Cons (Manager_operation {operation = Reveal _key; _}, _res) ->
error Incorrect_reveal_position
| Single (Manager_operation {source; counter; _}) ->
check_source_and_counter
~expected_source
~source
~previous_counter
~counter
| Cons (Manager_operation {source; counter; _}, rest) ->
let open Result_syntax in
let* () =
check_source_and_counter
~expected_source
~source
~previous_counter
~counter
in
check_batch_tail_sanity source counter rest
in
let check_batch :
type kind.
kind Kind.manager contents_list ->
(public_key_hash * public_key option * Manager_counter.t) tzresult =
fun contents_list ->
match contents_list with
| Single (Manager_operation {source; operation = Reveal key; counter; _})
->
ok (source, Some key, counter)
| Single (Manager_operation {source; counter; _}) ->
ok (source, None, counter)
| Cons
(Manager_operation {source; operation = Reveal key; counter; _}, rest)
->
check_batch_tail_sanity source counter rest >>? fun () ->
ok (source, Some key, counter)
| Cons (Manager_operation {source; counter; _}, rest) ->
check_batch_tail_sanity source counter rest >>? fun () ->
ok (source, None, counter)
in
let open Lwt_result_syntax in
let*? source, revealed_key, first_counter = check_batch contents_list in
let* balance = Contract.check_allocated_and_get_balance vi.ctxt source in
let* () = Contract.check_counter_increment vi.ctxt source first_counter in
let* pk =
match revealed_key with
| Some pk -> return pk
| None -> Contract.get_manager_key vi.ctxt source
in
let initial_batch_state =
{
balance;
is_allocated = true;
total_gas_used = Gas.Arith.zero;
}
in
return (initial_batch_state, pk)
let check_gas_limit info ~gas_limit =
Gas.check_gas_limit
~hard_gas_limit_per_operation:
info.manager_info.hard_gas_limit_per_operation
~gas_limit
let check_storage_limit vi storage_limit =
error_unless
Compare.Z.(
storage_limit <= vi.manager_info.hard_storage_limit_per_operation
&& storage_limit >= Z.zero)
Fees.Storage_limit_too_high
let assert_sc_rollup_feature_enabled vi =
error_unless (Constants.sc_rollup_enable vi.ctxt) Sc_rollup_feature_disabled
let assert_pvm_kind_enabled vi kind =
error_when
((not (Constants.sc_rollup_arith_pvm_enable vi.ctxt))
&& Sc_rollup.Kind.(equal kind Example_arith))
Sc_rollup_arith_pvm_disabled
let assert_not_zero_messages messages =
match messages with
| [] -> error Sc_rollup_errors.Sc_rollup_add_zero_messages
| _ -> ok_unit
let assert_zk_rollup_feature_enabled vi =
error_unless (Constants.zk_rollup_enable vi.ctxt) Zk_rollup_feature_disabled
let consume_decoding_gas remaining_gas lexpr =
record_trace Gas_quota_exceeded_init_deserialize
Script.consume_decoding_gas remaining_gas lexpr
let may_trace_gas_limit_too_high info =
match info.mode with
| Application _ | Partial_validation _ | Construction _ -> fun x -> x
| Mempool ->
record_trace Gas.Gas_limit_too_high
let check_contents (type kind) vi batch_state
(contents : kind Kind.manager contents) remaining_block_gas =
let open Lwt_result_syntax in
let (Manager_operation
{source; fee; counter = _; operation; gas_limit; storage_limit}) =
contents
in
let*? () = check_gas_limit vi ~gas_limit in
let total_gas_used =
Gas.Arith.(add batch_state.total_gas_used (fp gas_limit))
in
let*? () =
may_trace_gas_limit_too_high vi
@@ error_unless
Gas.Arith.(fp total_gas_used <= remaining_block_gas)
Gas.Block_quota_exceeded
in
let*? remaining_gas =
record_trace
Insufficient_gas_for_manager
(Gas.consume_from
(Gas.Arith.fp gas_limit)
Michelson_v1_gas.Cost_of.manager_operation)
in
let*? () = check_storage_limit vi storage_limit in
let*? () =
error_unless
batch_state.is_allocated
(Contract_storage.Empty_implicit_contract source)
in
let*? () =
let open Result_syntax in
match operation with
| Reveal pk -> Contract.check_public_key pk source
| Transaction {parameters; _} ->
let* (_ : Gas.Arith.fp) =
consume_decoding_gas remaining_gas parameters
in
return_unit
| Origination {script; _} ->
let* remaining_gas = consume_decoding_gas remaining_gas script.code in
let* (_ : Gas.Arith.fp) =
consume_decoding_gas remaining_gas script.storage
in
return_unit
| Register_global_constant {value} ->
let* (_ : Gas.Arith.fp) = consume_decoding_gas remaining_gas value in
return_unit
| Delegation (Some pkh) -> Delegate.check_not_tz4 pkh
| Update_consensus_key pk -> Delegate.Consensus_key.check_not_tz4 pk
| Delegation None | Set_deposits_limit _ | Increase_paid_storage _ ->
return_unit
| Transfer_ticket {contents; ty; _} ->
let* remaining_gas = consume_decoding_gas remaining_gas contents in
let* (_ : Gas.Arith.fp) = consume_decoding_gas remaining_gas ty in
return_unit
| Sc_rollup_originate {kind; _} ->
let* () = assert_sc_rollup_feature_enabled vi in
assert_pvm_kind_enabled vi kind
| Sc_rollup_cement _ | Sc_rollup_publish _ | Sc_rollup_refute _
| Sc_rollup_timeout _ | Sc_rollup_execute_outbox_message _ ->
assert_sc_rollup_feature_enabled vi
| Sc_rollup_add_messages {messages; _} ->
let* () = assert_sc_rollup_feature_enabled vi in
assert_not_zero_messages messages
| Sc_rollup_recover_bond _ ->
TODO : /-/issues/3063
Should we successfully precheck Sc_rollup_recover_bond and any
( simple ) Sc rollup operation , or should we add some some checks to make
the operations Branch_delayed if they can not be successfully
prechecked ?
Should we successfully precheck Sc_rollup_recover_bond and any
(simple) Sc rollup operation, or should we add some some checks to make
the operations Branch_delayed if they cannot be successfully
prechecked? *)
assert_sc_rollup_feature_enabled vi
| Dal_publish_slot_header slot_header ->
Dal_apply.validate_publish_slot_header vi.ctxt slot_header
| Zk_rollup_origination _ | Zk_rollup_publish _ | Zk_rollup_update _ ->
assert_zk_rollup_feature_enabled vi
in
let* balance, is_allocated =
Contract.simulate_spending
vi.ctxt
~balance:batch_state.balance
~amount:fee
source
in
return {total_gas_used; balance; is_allocated}
* This would be [ fold_left_es ( check_contents vi ) batch_state
contents_list ] if [ contents_list ] were an ordinary [ list ] .
contents_list] if [contents_list] were an ordinary [list]. *)
let rec check_contents_list :
type kind.
info ->
batch_state ->
kind Kind.manager contents_list ->
Gas.Arith.fp ->
Gas.Arith.fp tzresult Lwt.t =
fun vi batch_state contents_list remaining_gas ->
let open Lwt_result_syntax in
match contents_list with
| Single contents ->
let* batch_state =
check_contents vi batch_state contents remaining_gas
in
return batch_state.total_gas_used
| Cons (contents, tail) ->
let* batch_state =
check_contents vi batch_state contents remaining_gas
in
check_contents_list vi batch_state tail remaining_gas
let check_manager_operation vi ~check_signature
(operation : _ Kind.manager operation) remaining_block_gas =
let open Lwt_result_syntax in
let contents_list = operation.protocol_data.contents in
let* batch_state, source_pk =
check_sanity_and_find_public_key vi contents_list
in
let* gas_used =
check_contents_list vi batch_state contents_list remaining_block_gas
in
let*? () =
if check_signature then
Operation.check_signature source_pk vi.chain_id operation
else ok_unit
in
return gas_used
let check_manager_operation_conflict (type kind) vs oph
(operation : kind Kind.manager operation) =
let source =
match operation.protocol_data.contents with
| Single (Manager_operation {source; _})
| Cons (Manager_operation {source; _}, _) ->
source
in
One - operation - per - manager - per - block restriction ( 1 M )
match
Signature.Public_key_hash.Map.find_opt
source
vs.manager_state.managers_seen
with
| None -> ok_unit
| Some existing ->
Error (Operation_conflict {existing; new_operation = oph})
let wrap_check_manager_operation_conflict (type kind)
(operation : kind Kind.manager operation) =
let source =
match operation.protocol_data.contents with
| Single (Manager_operation {source; _})
| Cons (Manager_operation {source; _}, _) ->
source
in
function
| Ok () -> ok_unit
| Error conflict -> error (Manager_restriction {source; conflict})
let add_manager_operation (type kind) vs oph
(operation : kind Kind.manager operation) =
let source =
match operation.protocol_data.contents with
| Single (Manager_operation {source; _})
| Cons (Manager_operation {source; _}, _) ->
source
in
let managers_seen =
Signature.Public_key_hash.Map.add
source
oph
vs.manager_state.managers_seen
in
{vs with manager_state = {managers_seen}}
Return the new [ block_state ] with the updated remaining gas used :
- In non - mempool modes , this value is
[ block_state.remaining_block_gas ] , in which the gas from the
validated operation has been subtracted .
- In [ ] mode , the [ block_state ] should remain
unchanged . Indeed , we only want each batch to not exceed the
block limit individually , without taking other operations
into account .
- In non-mempool modes, this value is
[block_state.remaining_block_gas], in which the gas from the
validated operation has been subtracted.
- In [Mempool] mode, the [block_state] should remain
unchanged. Indeed, we only want each batch to not exceed the
block limit individually, without taking other operations
into account. *)
let may_update_remaining_gas_used mode (block_state : block_state)
operation_gas_used =
match mode with
| Application _ | Partial_validation _ | Construction _ ->
let remaining_block_gas =
Gas.Arith.(sub block_state.remaining_block_gas operation_gas_used)
in
{block_state with remaining_block_gas}
| Mempool -> block_state
let remove_manager_operation (type kind) vs
(operation : kind Kind.manager operation) =
let source =
match operation.protocol_data.contents with
| Single (Manager_operation {source; _})
| Cons (Manager_operation {source; _}, _) ->
source
in
let managers_seen =
Signature.Public_key_hash.Map.remove source vs.manager_state.managers_seen
in
{vs with manager_state = {managers_seen}}
let validate_manager_operation ~check_signature info operation_state
block_state oph operation =
let open Lwt_result_syntax in
let* gas_used =
check_manager_operation
info
~check_signature
operation
block_state.remaining_block_gas
in
let*? () =
check_manager_operation_conflict operation_state oph operation
|> wrap_check_manager_operation_conflict operation
in
let operation_state = add_manager_operation operation_state oph operation in
let block_state =
may_update_remaining_gas_used info.mode block_state gas_used
in
return {info; operation_state; block_state}
end
let init_validation_state ctxt mode chain_id ~predecessor_level_and_round =
let info = init_info ctxt mode chain_id ~predecessor_level_and_round in
let operation_state = empty_operation_conflict_state in
let block_state = init_block_state info in
{info; operation_state; block_state}
let begin_any_application ctxt chain_id ~predecessor_level
~predecessor_timestamp (block_header : Block_header.t) fitness ~is_partial =
let open Lwt_result_syntax in
let predecessor_round = Fitness.predecessor_round fitness in
let round = Fitness.round fitness in
let current_level = Level.current ctxt in
let* ctxt, _slot, block_producer =
Stake_distribution.baking_rights_owner ctxt current_level ~round
in
let*? () =
Block_header.begin_validate_block_header
~block_header
~chain_id
~predecessor_timestamp
~predecessor_round
~fitness
~timestamp:block_header.shell.timestamp
~delegate_pk:block_producer.consensus_pk
~round_durations:(Constants.round_durations ctxt)
~proof_of_work_threshold:(Constants.proof_of_work_threshold ctxt)
~expected_commitment:current_level.expected_commitment
in
let* () =
Consensus.check_frozen_deposits_are_positive ctxt block_producer.delegate
in
let* ctxt, _slot, payload_producer =
Stake_distribution.baking_rights_owner
ctxt
current_level
~round:block_header.protocol_data.contents.payload_round
in
let predecessor_hash = block_header.shell.predecessor in
let block_info =
{
round;
locked_round = Fitness.locked_round fitness;
predecessor_hash;
block_producer;
payload_producer;
header_contents = block_header.protocol_data.contents;
}
in
let mode =
if is_partial then Partial_validation block_info else Application block_info
in
let validation_state =
init_validation_state
ctxt
mode
chain_id
~predecessor_level_and_round:
(Some (predecessor_level.Level.level, predecessor_round))
in
return validation_state
let begin_partial_validation ctxt chain_id ~predecessor_level
~predecessor_timestamp block_header fitness =
begin_any_application
ctxt
chain_id
~predecessor_level
~predecessor_timestamp
block_header
fitness
~is_partial:true
let begin_application ctxt chain_id ~predecessor_level ~predecessor_timestamp
block_header fitness =
begin_any_application
ctxt
chain_id
~predecessor_level
~predecessor_timestamp
block_header
fitness
~is_partial:false
let begin_full_construction ctxt chain_id ~predecessor_level ~predecessor_round
~predecessor_timestamp ~predecessor_hash round
(header_contents : Block_header.contents) =
let open Lwt_result_syntax in
let round_durations = Constants.round_durations ctxt in
let timestamp = Timestamp.current ctxt in
let*? () =
Block_header.check_timestamp
round_durations
~timestamp
~round
~predecessor_timestamp
~predecessor_round
in
let current_level = Level.current ctxt in
let* ctxt, _slot, block_producer =
Stake_distribution.baking_rights_owner ctxt current_level ~round
in
let* () =
Consensus.check_frozen_deposits_are_positive ctxt block_producer.delegate
in
let* ctxt, _slot, payload_producer =
Stake_distribution.baking_rights_owner
ctxt
current_level
~round:header_contents.payload_round
in
let validation_state =
init_validation_state
ctxt
(Construction
{
round;
predecessor_hash;
block_producer;
payload_producer;
header_contents;
})
chain_id
~predecessor_level_and_round:
(Some (predecessor_level.Level.level, predecessor_round))
in
return validation_state
let begin_partial_construction ctxt chain_id ~predecessor_level
~predecessor_round =
let validation_state =
init_validation_state
ctxt
Mempool
chain_id
~predecessor_level_and_round:
(Some (predecessor_level.Level.level, predecessor_round))
in
validation_state
let begin_no_predecessor_info ctxt chain_id =
init_validation_state ctxt Mempool chain_id ~predecessor_level_and_round:None
let check_operation ?(check_signature = true) info (type kind)
(operation : kind operation) : unit tzresult Lwt.t =
let open Lwt_result_syntax in
match operation.protocol_data.contents with
| Single (Preendorsement _) ->
let* (_voting_power : int) =
Consensus.check_preendorsement info ~check_signature operation
in
return_unit
| Single (Endorsement _) ->
let* (_voting_power : int) =
Consensus.check_endorsement info ~check_signature operation
in
return_unit
| Single (Dal_attestation _) -> Consensus.check_dal_attestation info operation
| Single (Proposals _) ->
Voting.check_proposals info ~check_signature operation
| Single (Ballot _) -> Voting.check_ballot info ~check_signature operation
| Single (Activate_account _) ->
Anonymous.check_activate_account info operation
| Single (Double_preendorsement_evidence _) ->
Anonymous.check_double_preendorsement_evidence info operation
| Single (Double_endorsement_evidence _) ->
Anonymous.check_double_endorsement_evidence info operation
| Single (Double_baking_evidence _) ->
Anonymous.check_double_baking_evidence info operation
| Single (Drain_delegate _) ->
Anonymous.check_drain_delegate info ~check_signature operation
| Single (Seed_nonce_revelation _) ->
Anonymous.check_seed_nonce_revelation info operation
| Single (Vdf_revelation _) -> Anonymous.check_vdf_revelation info operation
| Single (Manager_operation _) ->
let remaining_gas =
Gas.Arith.fp (Constants.hard_gas_limit_per_block info.ctxt)
in
let* (_remaining_gas : Gas.Arith.fp) =
Manager.check_manager_operation
info
~check_signature
operation
remaining_gas
in
return_unit
| Cons (Manager_operation _, _) ->
let remaining_gas =
Gas.Arith.fp (Constants.hard_gas_limit_per_block info.ctxt)
in
let* (_remaining_gas : Gas.Arith.fp) =
Manager.check_manager_operation
info
~check_signature
operation
remaining_gas
in
return_unit
| Single (Failing_noop _) -> tzfail Validate_errors.Failing_noop_error
let check_operation_conflict (type kind) operation_conflict_state oph
(operation : kind operation) =
match operation.protocol_data.contents with
| Single (Preendorsement _) ->
Consensus.check_preendorsement_conflict
operation_conflict_state
oph
operation
| Single (Endorsement _) ->
Consensus.check_endorsement_conflict
operation_conflict_state
oph
operation
| Single (Dal_attestation _) ->
Consensus.check_dal_attestation_conflict
operation_conflict_state
oph
operation
| Single (Proposals _) ->
Voting.check_proposals_conflict operation_conflict_state oph operation
| Single (Ballot _) ->
Voting.check_ballot_conflict operation_conflict_state oph operation
| Single (Activate_account _) ->
Anonymous.check_activate_account_conflict
operation_conflict_state
oph
operation
| Single (Double_preendorsement_evidence _) ->
Anonymous.check_double_preendorsement_evidence_conflict
operation_conflict_state
oph
operation
| Single (Double_endorsement_evidence _) ->
Anonymous.check_double_endorsement_evidence_conflict
operation_conflict_state
oph
operation
| Single (Double_baking_evidence _) ->
Anonymous.check_double_baking_evidence_conflict
operation_conflict_state
oph
operation
| Single (Drain_delegate _) ->
Anonymous.check_drain_delegate_conflict
operation_conflict_state
oph
operation
| Single (Seed_nonce_revelation _) ->
Anonymous.check_seed_nonce_revelation_conflict
operation_conflict_state
oph
operation
| Single (Vdf_revelation _) ->
Anonymous.check_vdf_revelation_conflict operation_conflict_state oph
| Single (Manager_operation _) ->
Manager.check_manager_operation_conflict
operation_conflict_state
oph
operation
| Cons (Manager_operation _, _) ->
Manager.check_manager_operation_conflict
operation_conflict_state
oph
operation
let add_valid_operation operation_conflict_state oph (type kind)
(operation : kind operation) =
match operation.protocol_data.contents with
| Single (Preendorsement _) ->
Consensus.add_preendorsement operation_conflict_state oph operation
| Single (Endorsement _) ->
Consensus.add_endorsement operation_conflict_state oph operation
| Single (Dal_attestation _) ->
Consensus.add_dal_attestation operation_conflict_state oph operation
| Single (Proposals _) ->
Voting.add_proposals operation_conflict_state oph operation
| Single (Ballot _) ->
Voting.add_ballot operation_conflict_state oph operation
| Single (Activate_account _) ->
Anonymous.add_activate_account operation_conflict_state oph operation
| Single (Double_preendorsement_evidence _) ->
Anonymous.add_double_preendorsement_evidence
operation_conflict_state
oph
operation
| Single (Double_endorsement_evidence _) ->
Anonymous.add_double_endorsement_evidence
operation_conflict_state
oph
operation
| Single (Double_baking_evidence _) ->
Anonymous.add_double_baking_evidence
operation_conflict_state
oph
operation
| Single (Drain_delegate _) ->
Anonymous.add_drain_delegate operation_conflict_state oph operation
| Single (Seed_nonce_revelation _) ->
Anonymous.add_seed_nonce_revelation operation_conflict_state oph operation
| Single (Vdf_revelation _) ->
Anonymous.add_vdf_revelation operation_conflict_state oph
| Single (Manager_operation _) ->
Manager.add_manager_operation operation_conflict_state oph operation
| Cons (Manager_operation _, _) ->
Manager.add_manager_operation operation_conflict_state oph operation
let remove_operation operation_conflict_state (type kind)
(operation : kind operation) =
match operation.protocol_data.contents with
| Single (Preendorsement _) ->
Consensus.remove_preendorsement operation_conflict_state operation
| Single (Endorsement _) ->
Consensus.remove_endorsement operation_conflict_state operation
| Single (Dal_attestation _) ->
Consensus.remove_dal_attestation operation_conflict_state operation
| Single (Proposals _) ->
Voting.remove_proposals operation_conflict_state operation
| Single (Ballot _) -> Voting.remove_ballot operation_conflict_state operation
| Single (Activate_account _) ->
Anonymous.remove_activate_account operation_conflict_state operation
| Single (Double_preendorsement_evidence _) ->
Anonymous.remove_double_preendorsement_evidence
operation_conflict_state
operation
| Single (Double_endorsement_evidence _) ->
Anonymous.remove_double_endorsement_evidence
operation_conflict_state
operation
| Single (Double_baking_evidence _) ->
Anonymous.remove_double_baking_evidence operation_conflict_state operation
| Single (Drain_delegate _) ->
Anonymous.remove_drain_delegate operation_conflict_state operation
| Single (Seed_nonce_revelation _) ->
Anonymous.remove_seed_nonce_revelation operation_conflict_state operation
| Single (Vdf_revelation _) ->
Anonymous.remove_vdf_revelation operation_conflict_state
| Single (Manager_operation _) ->
Manager.remove_manager_operation operation_conflict_state operation
| Cons (Manager_operation _, _) ->
Manager.remove_manager_operation operation_conflict_state operation
let check_validation_pass_consistency vi vs validation_pass =
let open Lwt_result_syntax in
match vi.mode with
| Mempool | Construction _ -> return vs
| Application _ | Partial_validation _ -> (
match (vs.last_op_validation_pass, validation_pass) with
| None, validation_pass ->
return {vs with last_op_validation_pass = validation_pass}
| Some previous_vp, Some validation_pass ->
let* () =
fail_unless
Compare.Int.(previous_vp <= validation_pass)
(Validate_errors.Block.Inconsistent_validation_passes_in_block
{expected = previous_vp; provided = validation_pass})
in
return {vs with last_op_validation_pass = Some validation_pass}
| Some _, None -> tzfail Validate_errors.Failing_noop_error)
let record_operation vs ophash validation_pass_opt =
let op_count = vs.op_count + 1 in
match validation_pass_opt with
| Some n when Compare.Int.(n = Operation_repr.consensus_pass) ->
{vs with op_count}
| _ ->
{
vs with
op_count;
recorded_operations_rev = ophash :: vs.recorded_operations_rev;
}
let validate_operation ?(check_signature = true)
{info; operation_state; block_state} oph
(packed_operation : packed_operation) =
let open Lwt_result_syntax in
let {shell; protocol_data = Operation_data protocol_data} =
packed_operation
in
let validation_pass_opt = Operation.acceptable_pass packed_operation in
let* block_state =
check_validation_pass_consistency info block_state validation_pass_opt
in
let block_state = record_operation block_state oph validation_pass_opt in
let operation : _ operation = {shell; protocol_data} in
match (info.mode, validation_pass_opt) with
| Partial_validation _, Some n
when Compare.Int.(n <> Operation_repr.consensus_pass) ->
return {info; operation_state; block_state}
| (Application _ | Partial_validation _ | Construction _ | Mempool), _ -> (
match operation.protocol_data.contents with
| Single (Preendorsement _) ->
Consensus.validate_preendorsement
~check_signature
info
operation_state
block_state
oph
operation
| Single (Endorsement _) ->
Consensus.validate_endorsement
~check_signature
info
operation_state
block_state
oph
operation
| Single (Dal_attestation _) ->
let open Consensus in
let* () = check_dal_attestation info operation in
let*? () =
check_dal_attestation_conflict operation_state oph operation
|> wrap_dal_attestation_conflict
in
let operation_state =
add_dal_attestation operation_state oph operation
in
return {info; operation_state; block_state}
| Single (Proposals _) ->
let open Voting in
let* () = check_proposals info ~check_signature operation in
let*? () =
check_proposals_conflict operation_state oph operation
|> wrap_proposals_conflict
in
let operation_state = add_proposals operation_state oph operation in
return {info; operation_state; block_state}
| Single (Ballot _) ->
let open Voting in
let* () = check_ballot info ~check_signature operation in
let*? () =
check_ballot_conflict operation_state oph operation
|> wrap_ballot_conflict
in
let operation_state = add_ballot operation_state oph operation in
return {info; operation_state; block_state}
| Single (Activate_account _) ->
let open Anonymous in
let* () = check_activate_account info operation in
let*? () =
check_activate_account_conflict operation_state oph operation
|> wrap_activate_account_conflict operation
in
let operation_state =
add_activate_account operation_state oph operation
in
return {info; operation_state; block_state}
| Single (Double_preendorsement_evidence _) ->
let open Anonymous in
let* () = check_double_preendorsement_evidence info operation in
let*? () =
check_double_preendorsement_evidence_conflict
operation_state
oph
operation
|> wrap_denunciation_conflict Preendorsement
in
let operation_state =
add_double_preendorsement_evidence operation_state oph operation
in
return {info; operation_state; block_state}
| Single (Double_endorsement_evidence _) ->
let open Anonymous in
let* () = check_double_endorsement_evidence info operation in
let*? () =
check_double_endorsement_evidence_conflict
operation_state
oph
operation
|> wrap_denunciation_conflict Endorsement
in
let operation_state =
add_double_endorsement_evidence operation_state oph operation
in
return {info; operation_state; block_state}
| Single (Double_baking_evidence _) ->
let open Anonymous in
let* () = check_double_baking_evidence info operation in
let*? () =
check_double_baking_evidence_conflict operation_state oph operation
|> wrap_denunciation_conflict Block
in
let operation_state =
add_double_baking_evidence operation_state oph operation
in
return {info; operation_state; block_state}
| Single (Drain_delegate _) ->
let open Anonymous in
let* () = check_drain_delegate info ~check_signature operation in
let*? () =
check_drain_delegate_conflict operation_state oph operation
|> wrap_drain_delegate_conflict operation
in
let operation_state =
add_drain_delegate operation_state oph operation
in
return {info; operation_state; block_state}
| Single (Seed_nonce_revelation _) ->
let open Anonymous in
let* () = check_seed_nonce_revelation info operation in
let*? () =
check_seed_nonce_revelation_conflict operation_state oph operation
|> wrap_seed_nonce_revelation_conflict
in
let operation_state =
add_seed_nonce_revelation operation_state oph operation
in
return {info; operation_state; block_state}
| Single (Vdf_revelation _) ->
let open Anonymous in
let* () = check_vdf_revelation info operation in
let*? () =
check_vdf_revelation_conflict operation_state oph
|> wrap_vdf_revelation_conflict
in
let operation_state = add_vdf_revelation operation_state oph in
return {info; operation_state; block_state}
| Single (Manager_operation _) ->
Manager.validate_manager_operation
~check_signature
info
operation_state
block_state
oph
operation
| Cons (Manager_operation _, _) ->
Manager.validate_manager_operation
~check_signature
info
operation_state
block_state
oph
operation
| Single (Failing_noop _) -> tzfail Validate_errors.Failing_noop_error)
let are_endorsements_required vi =
let open Lwt_result_syntax in
let+ first_level = First_level_of_protocol.get vi.ctxt in
[ Comment from Legacy_apply ] NB : the first level is the level
of the migration block . There are no endorsements for this
block . Therefore the block at the next level can not contain
endorsements .
of the migration block. There are no endorsements for this
block. Therefore the block at the next level cannot contain
endorsements. *)
let level_position_in_protocol =
Raw_level.diff vi.current_level.level first_level
in
Compare.Int32.(level_position_in_protocol > 1l)
let check_endorsement_power vi bs =
let required = Constants.consensus_threshold vi.ctxt in
let provided = bs.endorsement_power in
error_unless
Compare.Int.(provided >= required)
(Validate_errors.Block.Not_enough_endorsements {required; provided})
let finalize_validate_block_header vi vs checkable_payload_hash
(block_header_contents : Block_header.contents) round ~fitness_locked_round
=
let locked_round_evidence =
Option.map
(fun (preendorsement_round, preendorsement_count) ->
Block_header.{preendorsement_round; preendorsement_count})
vs.locked_round_evidence
in
Block_header.finalize_validate_block_header
~block_header_contents
~round
~fitness_locked_round
~checkable_payload_hash
~locked_round_evidence
~consensus_threshold:(Constants.consensus_threshold vi.ctxt)
let compute_payload_hash block_state
(block_header_contents : Block_header.contents) ~predecessor_hash =
Block_payload.hash
~predecessor_hash
~payload_round:block_header_contents.payload_round
(List.rev block_state.recorded_operations_rev)
let finalize_block {info; block_state; _} =
let open Lwt_result_syntax in
match info.mode with
| Application {round; locked_round; predecessor_hash; header_contents; _} ->
let* are_endorsements_required = are_endorsements_required info in
let*? () =
if are_endorsements_required then
check_endorsement_power info block_state
else ok_unit
in
let block_payload_hash =
compute_payload_hash block_state header_contents ~predecessor_hash
in
let*? () =
finalize_validate_block_header
info
block_state
(Block_header.Expected_payload_hash block_payload_hash)
header_contents
round
~fitness_locked_round:locked_round
in
return_unit
| Partial_validation _ ->
let* are_endorsements_required = are_endorsements_required info in
let*? () =
if are_endorsements_required then
check_endorsement_power info block_state
else ok_unit
in
return_unit
| Construction {round; predecessor_hash; header_contents; _} ->
let block_payload_hash =
compute_payload_hash block_state header_contents ~predecessor_hash
in
let locked_round_evidence = block_state.locked_round_evidence in
let checkable_payload_hash =
match locked_round_evidence with
| Some _ -> Block_header.Expected_payload_hash block_payload_hash
| None ->
Block_header.No_check
in
let* are_endorsements_required = are_endorsements_required info in
let*? () =
if are_endorsements_required then
check_endorsement_power info block_state
else ok_unit
in
let*? () =
finalize_validate_block_header
info
block_state
checkable_payload_hash
header_contents
round
~fitness_locked_round:(Option.map fst locked_round_evidence)
in
return_unit
| Mempool ->
return_unit
|
af67918776a7f77aa9af05e0a8f9210a59af6d6278134343286bd8548ba56f31 | madmax96/brave-clojure-solutions | section_7.clj | (ns clojure-brave.exercises.section-7)
1
(eval (list 'str "Mladjan " "Interstellar"))
(eval '(str "Mladjan " "Interstellar"))
(eval (read-string "(str \"Mladjan \" \"Interstellar\")"))
2
(defmacro infix
[[op1 plus op2 times op3 minus op4]]
(list minus
(list plus
op1
(list times op2 op3))
op4))
(infix (1 + 3 * 4 - 5))
( 1 + 3 * 4 - 5 ) -- > ( - ( + 1 ( * 3 4 ) ) 5 ) | null | https://raw.githubusercontent.com/madmax96/brave-clojure-solutions/3be234bdcf3704acd2aca62d1a46fa03463e5735/section_7.clj | clojure | (ns clojure-brave.exercises.section-7)
1
(eval (list 'str "Mladjan " "Interstellar"))
(eval '(str "Mladjan " "Interstellar"))
(eval (read-string "(str \"Mladjan \" \"Interstellar\")"))
2
(defmacro infix
[[op1 plus op2 times op3 minus op4]]
(list minus
(list plus
op1
(list times op2 op3))
op4))
(infix (1 + 3 * 4 - 5))
( 1 + 3 * 4 - 5 ) -- > ( - ( + 1 ( * 3 4 ) ) 5 ) | |
1a39eba56389a517599251d3e3a984a63b916a080f65fd3d46423206ef9f5fc6 | fredrikt/yxa | local_default.erl | %%%-------------------------------------------------------------------
%%% File : local_default.erl
@author < >
%%% @doc Interface to local functions hooking into lots of
different parts of the various YXA applications .
%%%
@since 03 Jan 2006 by < >
%%% @end
%%% @hidden
%%%-------------------------------------------------------------------
-module(local_default).
-export([
]).
| null | https://raw.githubusercontent.com/fredrikt/yxa/85da46a999d083e6f00b5f156a634ca9be65645b/src/local_default.erl | erlang | -------------------------------------------------------------------
File : local_default.erl
@doc Interface to local functions hooking into lots of
@end
@hidden
------------------------------------------------------------------- | @author < >
different parts of the various YXA applications .
@since 03 Jan 2006 by < >
-module(local_default).
-export([
]).
|
c555d9f6071207c2bf190cf4e415005205efedd3d6f21c36c55d7027961d7653 | austral/austral | MonoType.ml |
Part of the Austral project , under the Apache License v2.0 with LLVM Exceptions .
See LICENSE file for details .
SPDX - License - Identifier : Apache-2.0 WITH LLVM - exception
Part of the Austral project, under the Apache License v2.0 with LLVM Exceptions.
See LICENSE file for details.
SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
*)
(** The monomorphic type system. *)
open Id
open Identifier
open Type
open Region
(** A monomorphic type. *)
type mono_ty =
| MonoUnit
| MonoBoolean
| MonoInteger of signedness * integer_width
| MonoSingleFloat
| MonoDoubleFloat
| MonoNamedType of mono_id
| MonoStaticArray of mono_ty
| MonoRegionTy of region
| MonoReadRef of mono_ty * mono_ty
| MonoWriteRef of mono_ty * mono_ty
| MonoAddress of mono_ty
| MonoPointer of mono_ty
| MonoFnPtr of mono_ty list * mono_ty
| MonoRegionTyVar of identifier * qident
[@@deriving (eq, show)]
(** A monomorphic record slot. *)
type mono_slot = MonoSlot of identifier * mono_ty
(** A monomorphic union case. *)
type mono_case = MonoCase of identifier * mono_slot list
| null | https://raw.githubusercontent.com/austral/austral/69b6f7de36cc9576483acd1ac4a31bf52074dbd1/lib/MonoType.ml | ocaml | * The monomorphic type system.
* A monomorphic type.
* A monomorphic record slot.
* A monomorphic union case. |
Part of the Austral project , under the Apache License v2.0 with LLVM Exceptions .
See LICENSE file for details .
SPDX - License - Identifier : Apache-2.0 WITH LLVM - exception
Part of the Austral project, under the Apache License v2.0 with LLVM Exceptions.
See LICENSE file for details.
SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
*)
open Id
open Identifier
open Type
open Region
type mono_ty =
| MonoUnit
| MonoBoolean
| MonoInteger of signedness * integer_width
| MonoSingleFloat
| MonoDoubleFloat
| MonoNamedType of mono_id
| MonoStaticArray of mono_ty
| MonoRegionTy of region
| MonoReadRef of mono_ty * mono_ty
| MonoWriteRef of mono_ty * mono_ty
| MonoAddress of mono_ty
| MonoPointer of mono_ty
| MonoFnPtr of mono_ty list * mono_ty
| MonoRegionTyVar of identifier * qident
[@@deriving (eq, show)]
type mono_slot = MonoSlot of identifier * mono_ty
type mono_case = MonoCase of identifier * mono_slot list
|
4a441475175c18542ff761f99da76dbfec21ae59534eb9b85c301eee41bdcf04 | ml4tp/tcoq | opaqueproof.mli | (************************************************************************)
v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2017
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
(* // * This file is distributed under the terms of the *)
(* * GNU Lesser General Public License Version 2.1 *)
(************************************************************************)
open Names
open Term
open Mod_subst
(** This module implements the handling of opaque proof terms.
Opaque proof terms are special since:
- they can be lazily computed and substituted
- they are stored in an optionally loaded segment of .vo files
An [opaque] proof terms holds the real data until fully discharged.
In this case it is called [direct].
When it is [turn_indirect] the data is relocated to an opaque table
and the [opaque] is turned into an index. *)
type proofterm = (constr * Univ.universe_context_set) Future.computation
type opaquetab
type opaque
val empty_opaquetab : opaquetab
(** From a [proofterm] to some [opaque]. *)
val create : proofterm -> opaque
* Turn a direct [ opaque ] into an indirect one , also .
* The integer is an hint of the maximum i d used so far
* The integer is an hint of the maximum id used so far *)
val turn_indirect : DirPath.t -> opaque -> opaquetab -> opaque * opaquetab
(** From a [opaque] back to a [constr]. This might use the
indirect opaque accessor configured below. *)
val force_proof : opaquetab -> opaque -> constr
val force_constraints : opaquetab -> opaque -> Univ.universe_context_set
val get_proof : opaquetab -> opaque -> Term.constr Future.computation
val get_constraints :
opaquetab -> opaque -> Univ.universe_context_set Future.computation option
val subst_opaque : substitution -> opaque -> opaque
val iter_direct_opaque : (constr -> unit) -> opaque -> opaque
type work_list = (Univ.Instance.t * Id.t array) Cmap.t *
(Univ.Instance.t * Id.t array) Mindmap.t
type cooking_info = {
modlist : work_list;
abstract : Context.Named.t * Univ.universe_level_subst * Univ.UContext.t }
The type has two caveats :
1 ) cook_constr is defined after
2 ) we have to store the input in the [ opaque ] in order to be able to
discharge it when turning a .vi into a .vo
1) cook_constr is defined after
2) we have to store the input in the [opaque] in order to be able to
discharge it when turning a .vi into a .vo *)
val discharge_direct_opaque :
cook_constr:(constr -> constr) -> cooking_info -> opaque -> opaque
val uuid_opaque : opaquetab -> opaque -> Future.UUID.t option
val join_opaque : opaquetab -> opaque -> unit
val dump : opaquetab ->
Constr.t Future.computation array *
Univ.universe_context_set Future.computation array *
cooking_info list array *
int Future.UUIDMap.t
* When stored indirectly , opaque terms are indexed by their library
dirpath and an integer index . The following two functions activate
this indirect storage , by telling how to store and retrieve terms .
Default creator always returns [ None ] , preventing the creation of
any indirect link , and default accessor always raises an error .
dirpath and an integer index. The following two functions activate
this indirect storage, by telling how to store and retrieve terms.
Default creator always returns [None], preventing the creation of
any indirect link, and default accessor always raises an error.
*)
val set_indirect_opaque_accessor :
(DirPath.t -> int -> Term.constr Future.computation) -> unit
val set_indirect_univ_accessor :
(DirPath.t -> int -> Univ.universe_context_set Future.computation option) -> unit
| null | https://raw.githubusercontent.com/ml4tp/tcoq/7a78c31df480fba721648f277ab0783229c8bece/kernel/opaqueproof.mli | ocaml | **********************************************************************
// * This file is distributed under the terms of the
* GNU Lesser General Public License Version 2.1
**********************************************************************
* This module implements the handling of opaque proof terms.
Opaque proof terms are special since:
- they can be lazily computed and substituted
- they are stored in an optionally loaded segment of .vo files
An [opaque] proof terms holds the real data until fully discharged.
In this case it is called [direct].
When it is [turn_indirect] the data is relocated to an opaque table
and the [opaque] is turned into an index.
* From a [proofterm] to some [opaque].
* From a [opaque] back to a [constr]. This might use the
indirect opaque accessor configured below. | v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2017
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
open Names
open Term
open Mod_subst
type proofterm = (constr * Univ.universe_context_set) Future.computation
type opaquetab
type opaque
val empty_opaquetab : opaquetab
val create : proofterm -> opaque
* Turn a direct [ opaque ] into an indirect one , also .
* The integer is an hint of the maximum i d used so far
* The integer is an hint of the maximum id used so far *)
val turn_indirect : DirPath.t -> opaque -> opaquetab -> opaque * opaquetab
val force_proof : opaquetab -> opaque -> constr
val force_constraints : opaquetab -> opaque -> Univ.universe_context_set
val get_proof : opaquetab -> opaque -> Term.constr Future.computation
val get_constraints :
opaquetab -> opaque -> Univ.universe_context_set Future.computation option
val subst_opaque : substitution -> opaque -> opaque
val iter_direct_opaque : (constr -> unit) -> opaque -> opaque
type work_list = (Univ.Instance.t * Id.t array) Cmap.t *
(Univ.Instance.t * Id.t array) Mindmap.t
type cooking_info = {
modlist : work_list;
abstract : Context.Named.t * Univ.universe_level_subst * Univ.UContext.t }
The type has two caveats :
1 ) cook_constr is defined after
2 ) we have to store the input in the [ opaque ] in order to be able to
discharge it when turning a .vi into a .vo
1) cook_constr is defined after
2) we have to store the input in the [opaque] in order to be able to
discharge it when turning a .vi into a .vo *)
val discharge_direct_opaque :
cook_constr:(constr -> constr) -> cooking_info -> opaque -> opaque
val uuid_opaque : opaquetab -> opaque -> Future.UUID.t option
val join_opaque : opaquetab -> opaque -> unit
val dump : opaquetab ->
Constr.t Future.computation array *
Univ.universe_context_set Future.computation array *
cooking_info list array *
int Future.UUIDMap.t
* When stored indirectly , opaque terms are indexed by their library
dirpath and an integer index . The following two functions activate
this indirect storage , by telling how to store and retrieve terms .
Default creator always returns [ None ] , preventing the creation of
any indirect link , and default accessor always raises an error .
dirpath and an integer index. The following two functions activate
this indirect storage, by telling how to store and retrieve terms.
Default creator always returns [None], preventing the creation of
any indirect link, and default accessor always raises an error.
*)
val set_indirect_opaque_accessor :
(DirPath.t -> int -> Term.constr Future.computation) -> unit
val set_indirect_univ_accessor :
(DirPath.t -> int -> Univ.universe_context_set Future.computation option) -> unit
|
08a7db76d807206cb86f6cdafc5e0eba3a097d7f55f12c824c7f52bbece66abf | commercialhaskell/rio | Time.hs | module RIO.Time
( module Data.Time
, getCurrentTime
, getTimeZone
, getCurrentTimeZone
, getZonedTime
, utcToLocalZonedTime
) where
import Control.Monad.IO.Class
import Data.Time hiding( getCurrentTime, getTimeZone, getCurrentTimeZone
, getZonedTime, utcToLocalZonedTime)
import qualified Data.Time
getCurrentTime :: MonadIO m => m UTCTime
getCurrentTime = liftIO Data.Time.getCurrentTime
getTimeZone :: MonadIO m => UTCTime -> m TimeZone
getTimeZone = liftIO . Data.Time.getTimeZone
getCurrentTimeZone :: MonadIO m => m TimeZone
getCurrentTimeZone = liftIO Data.Time.getCurrentTimeZone
getZonedTime :: MonadIO m => m ZonedTime
getZonedTime = liftIO Data.Time.getZonedTime
utcToLocalZonedTime :: MonadIO m => UTCTime -> m ZonedTime
utcToLocalZonedTime = liftIO . Data.Time.utcToLocalZonedTime
| null | https://raw.githubusercontent.com/commercialhaskell/rio/4eba306d37a60a20f0bed27f40afc23a7c892c40/rio/src/RIO/Time.hs | haskell | module RIO.Time
( module Data.Time
, getCurrentTime
, getTimeZone
, getCurrentTimeZone
, getZonedTime
, utcToLocalZonedTime
) where
import Control.Monad.IO.Class
import Data.Time hiding( getCurrentTime, getTimeZone, getCurrentTimeZone
, getZonedTime, utcToLocalZonedTime)
import qualified Data.Time
getCurrentTime :: MonadIO m => m UTCTime
getCurrentTime = liftIO Data.Time.getCurrentTime
getTimeZone :: MonadIO m => UTCTime -> m TimeZone
getTimeZone = liftIO . Data.Time.getTimeZone
getCurrentTimeZone :: MonadIO m => m TimeZone
getCurrentTimeZone = liftIO Data.Time.getCurrentTimeZone
getZonedTime :: MonadIO m => m ZonedTime
getZonedTime = liftIO Data.Time.getZonedTime
utcToLocalZonedTime :: MonadIO m => UTCTime -> m ZonedTime
utcToLocalZonedTime = liftIO . Data.Time.utcToLocalZonedTime
| |
c0b7274087fe0ee44ea84e4b65145e60895f2f41646443b87ec566619592cd1d | fetburner/compelib | numberTheory.ml | (* 最大公約数 *)
let rec gcd n m =
if m = 0 then n else gcd m (n mod m)
(* 最小公倍数 *)
let lcm n m = n / gcd n m * m
let factorize n =
nをpで割れるだけ割って,割れた数c'にcを加えたものとn / p^c'を返す
let rec iter_div p c n k =
if 0 < n mod p
then k c n
else iter_div p (c + 1) (n / p) k in
(* 素因数分解の処理の本体 *)
let rec factorize f acc p n =
if n <= 1
then acc
else if n < p * p
then f n 1 acc
else iter_div p 0 n @@ fun c ->
factorize f (if c <= 0 then acc else f p c acc) (p + 1) in
fun f acc -> factorize f acc 2 n
(* トーシェント関数φ *)
let totient n = Fun.flip (factorize n) n @@ fun p _ n -> n * (p - 1) / p
(* 昇順にソートされた約数のリスト *)
let divisors n f acc =
let rec divisors acc acc' i =
match compare n (i * i) with
| -1 -> List.fold_left (Fun.flip f) acc' acc
| 0 -> List.fold_left (Fun.flip f) (f i acc') acc
| 1 -> (if 0 < n mod i then divisors acc acc' else divisors (i :: acc) (f (n / i) acc')) (i + 1)
| _ -> raise Not_found in
divisors [] acc 1
let sieve n =
(* 今ふるおうとしている整数 *)
let p = ref 3 in
(* pがどのインデックスに対応するか *)
let i = ref 0 in
(* pの2乗 *)
let pp = ref 9 in
(* p^2がどのインデックスに対応するか *)
let ii = ref 3 in
* 2の倍数は無視し,3 , 5 , 7 , 9 ... が格納されているとみなす
* よって添字から格納されている数へ変換する式は 2i + 3
* 格納されている数から添字へ変換する式は ( x - 3 ) / 2
* 2の倍数は無視し,3, 5, 7, 9 ... が格納されているとみなす
* よって添字から格納されている数へ変換する式は 2i + 3
* 格納されている数から添字へ変換する式は (x - 3) / 2
*)
let m = (n lsr 1) - 1 in
let a = Array.make m true in
let rec sieve_aux k =
if k < !pp
then a.((k - 3) lsr 1)
else begin
let rec mark i =
if i < m then (a.(i) <- false; mark (i + !p)) in
(if a.(!i) then mark !ii);
incr i;
p := !p + 2;
pp := !pp + (!p lsl 1);
ii := !ii + (!p lsl 1) - 2;
sieve_aux k
end in
function
| k when k <= 1 -> false
| 2 -> true
| k -> k land 1 = 1 && sieve_aux k
| null | https://raw.githubusercontent.com/fetburner/compelib/d8fc5d9acd04e676c4d4d2ca9c6a7140f1b85670/lib/numberTheory.ml | ocaml | 最大公約数
最小公倍数
素因数分解の処理の本体
トーシェント関数φ
昇順にソートされた約数のリスト
今ふるおうとしている整数
pがどのインデックスに対応するか
pの2乗
p^2がどのインデックスに対応するか | let rec gcd n m =
if m = 0 then n else gcd m (n mod m)
let lcm n m = n / gcd n m * m
let factorize n =
nをpで割れるだけ割って,割れた数c'にcを加えたものとn / p^c'を返す
let rec iter_div p c n k =
if 0 < n mod p
then k c n
else iter_div p (c + 1) (n / p) k in
let rec factorize f acc p n =
if n <= 1
then acc
else if n < p * p
then f n 1 acc
else iter_div p 0 n @@ fun c ->
factorize f (if c <= 0 then acc else f p c acc) (p + 1) in
fun f acc -> factorize f acc 2 n
let totient n = Fun.flip (factorize n) n @@ fun p _ n -> n * (p - 1) / p
let divisors n f acc =
let rec divisors acc acc' i =
match compare n (i * i) with
| -1 -> List.fold_left (Fun.flip f) acc' acc
| 0 -> List.fold_left (Fun.flip f) (f i acc') acc
| 1 -> (if 0 < n mod i then divisors acc acc' else divisors (i :: acc) (f (n / i) acc')) (i + 1)
| _ -> raise Not_found in
divisors [] acc 1
let sieve n =
let p = ref 3 in
let i = ref 0 in
let pp = ref 9 in
let ii = ref 3 in
* 2の倍数は無視し,3 , 5 , 7 , 9 ... が格納されているとみなす
* よって添字から格納されている数へ変換する式は 2i + 3
* 格納されている数から添字へ変換する式は ( x - 3 ) / 2
* 2の倍数は無視し,3, 5, 7, 9 ... が格納されているとみなす
* よって添字から格納されている数へ変換する式は 2i + 3
* 格納されている数から添字へ変換する式は (x - 3) / 2
*)
let m = (n lsr 1) - 1 in
let a = Array.make m true in
let rec sieve_aux k =
if k < !pp
then a.((k - 3) lsr 1)
else begin
let rec mark i =
if i < m then (a.(i) <- false; mark (i + !p)) in
(if a.(!i) then mark !ii);
incr i;
p := !p + 2;
pp := !pp + (!p lsl 1);
ii := !ii + (!p lsl 1) - 2;
sieve_aux k
end in
function
| k when k <= 1 -> false
| 2 -> true
| k -> k land 1 = 1 && sieve_aux k
|
82cff19c8d21f514990df0a9326d37cb9efc2e836ea531a83a2811acce94f3d7 | cky/guile | effects.scm | Effects analysis on Tree - IL
Copyright ( C ) 2011 , 2012 , 2013 Free Software Foundation , Inc.
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation ; either
version 3 of the License , or ( at your option ) any later version .
;;;;
;;;; This library is distributed in the hope that it will be useful,
;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
;;;; Lesser General Public License for more details.
;;;;
You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
Foundation , Inc. , 51 Franklin Street , Fifth Floor , Boston , USA
(define-module (language tree-il effects)
#:use-module (language tree-il)
#:use-module (language tree-il primitives)
#:use-module (ice-9 match)
#:export (make-effects-analyzer
&mutable-lexical
&toplevel
&fluid
&definite-bailout
&possible-bailout
&zero-values
&allocation
&mutable-data
&type-check
&all-effects
effects-commute?
exclude-effects
effect-free?
constant?
depends-on-effects?
causes-effects?))
;;;
;;; Hey, it's some effects analysis! If you invoke
;;; `make-effects-analyzer', you get a procedure that computes the set
;;; of effects that an expression depends on and causes. This
;;; information is useful when writing algorithms that move code around,
;;; while preserving the semantics of an input program.
;;;
The effects set is represented by a bitfield , as a fixnum . The set
;;; of possible effects is modelled rather coarsely. For example, a
toplevel reference to FOO is modelled as depending on the & toplevel
;;; effect, and causing a &type-check effect. If any intervening code
sets any toplevel variable , that will block motion of FOO .
;;;
For each effect , two bits are reserved : one to indicate that an
;;; expression depends on the effect, and the other to indicate that an
;;; expression causes the effect.
;;;
(define-syntax define-effects
(lambda (x)
(syntax-case x ()
((_ all name ...)
(with-syntax (((n ...) (iota (length #'(name ...)))))
#'(begin
(define-syntax name (identifier-syntax (ash 1 (* n 2))))
...
(define-syntax all (identifier-syntax (logior name ...)))))))))
;; Here we define the effects, indicating the meaning of the effect.
;;
;; Effects that are described in a "depends on" sense can also be used
;; in the "causes" sense.
;;
;; Effects that are described as causing an effect are not usually used
;; in a "depends-on" sense. Although the "depends-on" sense is used
;; when checking for the existence of the "causes" effect, the effects
;; analyzer will not associate the "depends-on" sense of these effects
;; with any expression.
;;
(define-effects &all-effects
;; Indicates that an expression depends on the value of a mutable
;; lexical variable.
&mutable-lexical
;; Indicates that an expression depends on the value of a toplevel
;; variable.
&toplevel
;; Indicates that an expression depends on the value of a fluid
;; variable.
&fluid
;; Indicates that an expression definitely causes a non-local,
;; non-resumable exit -- a bailout. Only used in the "changes" sense.
&definite-bailout
;; Indicates that an expression may cause a bailout.
&possible-bailout
Indicates than an expression may return zero values -- a " causes "
;; effect.
&zero-values
;; Indicates that an expression may return a fresh object -- a
;; "causes" effect.
&allocation
;; Indicates that an expression depends on the value of a mutable data
;; structure.
&mutable-data
;; Indicates that an expression may cause a type check. A type check,
;; for the purposes of this analysis, is the possibility of throwing
an exception the first time an expression is evaluated . If the
;; expression did not cause an exception to be thrown, users can
;; assume that evaluating the expression again will not cause an
;; exception to be thrown.
;;
;; For example, (+ x y) might throw if X or Y are not numbers. But if
;; it doesn't throw, it should be safe to elide a dominated, common
;; subexpression (+ x y).
&type-check)
(define-syntax &no-effects (identifier-syntax 0))
;; Definite bailout is an oddball effect. Since it indicates that an
;; expression definitely causes bailout, it's not in the set of effects
;; of a call to an unknown procedure. At the same time, it's also
;; special in that a definite bailout in a subexpression doesn't always
;; cause an outer expression to include &definite-bailout in its
;; effects. For that reason we have to treat it specially.
;;
(define-syntax &all-effects-but-bailout
(identifier-syntax
(logand &all-effects (lognot &definite-bailout))))
(define-inlinable (cause effect)
(ash effect 1))
(define-inlinable (&depends-on a)
(logand a &all-effects))
(define-inlinable (&causes a)
(logand a (cause &all-effects)))
(define (exclude-effects effects exclude)
(logand effects (lognot (cause exclude))))
(define (effect-free? effects)
(zero? (&causes effects)))
(define (constant? effects)
(zero? effects))
(define-inlinable (depends-on-effects? x effects)
(not (zero? (logand (&depends-on x) effects))))
(define-inlinable (causes-effects? x effects)
(not (zero? (logand (&causes x) (cause effects)))))
(define-inlinable (effects-commute? a b)
(and (not (causes-effects? a (&depends-on b)))
(not (causes-effects? b (&depends-on a)))))
(define (make-effects-analyzer assigned-lexical?)
"Returns a procedure of type EXP -> EFFECTS that analyzes the effects
of an expression."
(let ((cache (make-hash-table)))
(define* (compute-effects exp #:optional (lookup (lambda (x) #f)))
(define (compute-effects exp)
(or (hashq-ref cache exp)
(let ((effects (visit exp)))
(hashq-set! cache exp effects)
effects)))
(define (accumulate-effects exps)
(let lp ((exps exps) (out &no-effects))
(if (null? exps)
out
(lp (cdr exps) (logior out (compute-effects (car exps)))))))
(define (visit exp)
(match exp
(($ <const>)
&no-effects)
(($ <void>)
&no-effects)
(($ <lexical-ref> _ _ gensym)
(if (assigned-lexical? gensym)
&mutable-lexical
&no-effects))
(($ <lexical-set> _ name gensym exp)
(logior (cause &mutable-lexical)
(compute-effects exp)))
(($ <let> _ names gensyms vals body)
(logior (if (or-map assigned-lexical? gensyms)
(cause &allocation)
&no-effects)
(accumulate-effects vals)
(compute-effects body)))
(($ <letrec> _ in-order? names gensyms vals body)
(logior (if (or-map assigned-lexical? gensyms)
(cause &allocation)
&no-effects)
(accumulate-effects vals)
(compute-effects body)))
(($ <fix> _ names gensyms vals body)
(logior (if (or-map assigned-lexical? gensyms)
(cause &allocation)
&no-effects)
(accumulate-effects vals)
(compute-effects body)))
(($ <let-values> _ producer consumer)
(logior (compute-effects producer)
(compute-effects consumer)
(cause &type-check)))
(($ <dynwind> _ winder body unwinder)
(logior (compute-effects winder)
(compute-effects body)
(compute-effects unwinder)))
(($ <dynlet> _ fluids vals body)
(logior (accumulate-effects fluids)
(accumulate-effects vals)
(cause &type-check)
(cause &fluid)
(compute-effects body)))
(($ <dynref> _ fluid)
(logior (compute-effects fluid)
(cause &type-check)
&fluid))
(($ <dynset> _ fluid exp)
(logior (compute-effects fluid)
(compute-effects exp)
(cause &type-check)
(cause &fluid)))
(($ <toplevel-ref>)
(logior &toplevel
(cause &type-check)))
(($ <module-ref>)
(logior &toplevel
(cause &type-check)))
(($ <module-set> _ mod name public? exp)
(logior (cause &toplevel)
(cause &type-check)
(compute-effects exp)))
(($ <toplevel-define> _ name exp)
(logior (cause &toplevel)
(compute-effects exp)))
(($ <toplevel-set> _ name exp)
(logior (cause &toplevel)
(compute-effects exp)))
(($ <primitive-ref>)
&no-effects)
(($ <conditional> _ test consequent alternate)
(let ((tfx (compute-effects test))
(cfx (compute-effects consequent))
(afx (compute-effects alternate)))
(if (causes-effects? (logior tfx (logand afx cfx))
&definite-bailout)
(logior tfx cfx afx)
(exclude-effects (logior tfx cfx afx)
&definite-bailout))))
Zero values .
(($ <application> _ ($ <primitive-ref> _ 'values) ())
(cause &zero-values))
;; Effect-free primitives.
(($ <application> _
($ <primitive-ref> _ (or 'values 'eq? 'eqv? 'equal?))
args)
(accumulate-effects args))
(($ <application> _
($ <primitive-ref> _ (or 'not 'pair? 'null? 'list? 'symbol?
'vector? 'struct? 'string? 'number?
'char?))
(arg))
(compute-effects arg))
;; Primitives that allocate memory.
(($ <application> _ ($ <primitive-ref> _ 'cons) (x y))
(logior (compute-effects x) (compute-effects y)
(cause &allocation)))
(($ <application> _ ($ <primitive-ref> _ (or 'list 'vector)) args)
(logior (accumulate-effects args) (cause &allocation)))
(($ <application> _ ($ <primitive-ref> _ 'make-prompt-tag) ())
(cause &allocation))
(($ <application> _ ($ <primitive-ref> _ 'make-prompt-tag) (arg))
(logior (compute-effects arg) (cause &allocation)))
;; Primitives that are normally effect-free, but which might
;; cause type checks, allocate memory, or access mutable
;; memory. FIXME: expand, to be more precise.
(($ <application> _
($ <primitive-ref> _ (and name
(? effect-free-primitive?)))
args)
(logior (accumulate-effects args)
(cause &type-check)
(if (constructor-primitive? name)
(cause &allocation)
(if (accessor-primitive? name)
&mutable-data
&no-effects))))
;; Lambda applications might throw wrong-number-of-args.
(($ <application> _ ($ <lambda> _ _ body) args)
(logior (accumulate-effects args)
(match body
(($ <lambda-case> _ req #f #f #f () syms body #f)
(logior (compute-effects body)
(if (= (length req) (length args))
0
(cause &type-check))))
(($ <lambda-case>)
(logior (compute-effects body)
(cause &type-check)))
(#f
;; Calling a case-lambda with no clauses
;; definitely causes bailout.
(logior (cause &definite-bailout)
(cause &possible-bailout))))))
Bailout primitives .
(($ <application> src ($ <primitive-ref> _ (? bailout-primitive? name))
args)
(logior (accumulate-effects args)
(cause &definite-bailout)
(cause &possible-bailout)))
;; A call to a lexically bound procedure, perhaps labels
;; allocated.
(($ <application> _ (and proc ($ <lexical-ref> _ _ sym)) args)
(cond
((lookup sym)
=> (lambda (proc)
(compute-effects (make-application #f proc args))))
(else
(logior &all-effects-but-bailout
(cause &all-effects-but-bailout)))))
;; A call to an unknown procedure can do anything.
(($ <application> _ proc args)
(logior &all-effects-but-bailout
(cause &all-effects-but-bailout)))
(($ <lambda> _ meta body)
&no-effects)
(($ <lambda-case> _ req opt rest kw inits gensyms body alt)
(logior (exclude-effects (accumulate-effects inits)
&definite-bailout)
(if (or-map assigned-lexical? gensyms)
(cause &allocation)
&no-effects)
(compute-effects body)
(if alt (compute-effects alt) &no-effects)))
(($ <sequence> _ exps)
(let lp ((exps exps) (effects &no-effects))
(match exps
((tail)
(logior (compute-effects tail)
Returning zero values to a for - effect continuation is
;; not observable.
(exclude-effects effects (cause &zero-values))))
((head . tail)
(lp tail (logior (compute-effects head) effects))))))
(($ <prompt> _ tag body handler)
(logior (compute-effects tag)
(compute-effects body)
(compute-effects handler)))
(($ <abort> _ tag args tail)
(logior &all-effects-but-bailout
(cause &all-effects-but-bailout)))))
(compute-effects exp))
compute-effects))
| null | https://raw.githubusercontent.com/cky/guile/89ce9fb31b00f1f243fe6f2450db50372cc0b86d/module/language/tree-il/effects.scm | scheme | This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
either
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
License along with this library; if not, write to the Free Software
Hey, it's some effects analysis! If you invoke
`make-effects-analyzer', you get a procedure that computes the set
of effects that an expression depends on and causes. This
information is useful when writing algorithms that move code around,
while preserving the semantics of an input program.
of possible effects is modelled rather coarsely. For example, a
effect, and causing a &type-check effect. If any intervening code
expression depends on the effect, and the other to indicate that an
expression causes the effect.
Here we define the effects, indicating the meaning of the effect.
Effects that are described in a "depends on" sense can also be used
in the "causes" sense.
Effects that are described as causing an effect are not usually used
in a "depends-on" sense. Although the "depends-on" sense is used
when checking for the existence of the "causes" effect, the effects
analyzer will not associate the "depends-on" sense of these effects
with any expression.
Indicates that an expression depends on the value of a mutable
lexical variable.
Indicates that an expression depends on the value of a toplevel
variable.
Indicates that an expression depends on the value of a fluid
variable.
Indicates that an expression definitely causes a non-local,
non-resumable exit -- a bailout. Only used in the "changes" sense.
Indicates that an expression may cause a bailout.
effect.
Indicates that an expression may return a fresh object -- a
"causes" effect.
Indicates that an expression depends on the value of a mutable data
structure.
Indicates that an expression may cause a type check. A type check,
for the purposes of this analysis, is the possibility of throwing
expression did not cause an exception to be thrown, users can
assume that evaluating the expression again will not cause an
exception to be thrown.
For example, (+ x y) might throw if X or Y are not numbers. But if
it doesn't throw, it should be safe to elide a dominated, common
subexpression (+ x y).
Definite bailout is an oddball effect. Since it indicates that an
expression definitely causes bailout, it's not in the set of effects
of a call to an unknown procedure. At the same time, it's also
special in that a definite bailout in a subexpression doesn't always
cause an outer expression to include &definite-bailout in its
effects. For that reason we have to treat it specially.
Effect-free primitives.
Primitives that allocate memory.
Primitives that are normally effect-free, but which might
cause type checks, allocate memory, or access mutable
memory. FIXME: expand, to be more precise.
Lambda applications might throw wrong-number-of-args.
Calling a case-lambda with no clauses
definitely causes bailout.
A call to a lexically bound procedure, perhaps labels
allocated.
A call to an unknown procedure can do anything.
not observable. | Effects analysis on Tree - IL
Copyright ( C ) 2011 , 2012 , 2013 Free Software Foundation , Inc.
version 3 of the License , or ( at your option ) any later version .
You should have received a copy of the GNU Lesser General Public
Foundation , Inc. , 51 Franklin Street , Fifth Floor , Boston , USA
(define-module (language tree-il effects)
#:use-module (language tree-il)
#:use-module (language tree-il primitives)
#:use-module (ice-9 match)
#:export (make-effects-analyzer
&mutable-lexical
&toplevel
&fluid
&definite-bailout
&possible-bailout
&zero-values
&allocation
&mutable-data
&type-check
&all-effects
effects-commute?
exclude-effects
effect-free?
constant?
depends-on-effects?
causes-effects?))
The effects set is represented by a bitfield , as a fixnum . The set
toplevel reference to FOO is modelled as depending on the & toplevel
sets any toplevel variable , that will block motion of FOO .
For each effect , two bits are reserved : one to indicate that an
(define-syntax define-effects
(lambda (x)
(syntax-case x ()
((_ all name ...)
(with-syntax (((n ...) (iota (length #'(name ...)))))
#'(begin
(define-syntax name (identifier-syntax (ash 1 (* n 2))))
...
(define-syntax all (identifier-syntax (logior name ...)))))))))
(define-effects &all-effects
&mutable-lexical
&toplevel
&fluid
&definite-bailout
&possible-bailout
Indicates than an expression may return zero values -- a " causes "
&zero-values
&allocation
&mutable-data
an exception the first time an expression is evaluated . If the
&type-check)
(define-syntax &no-effects (identifier-syntax 0))
(define-syntax &all-effects-but-bailout
(identifier-syntax
(logand &all-effects (lognot &definite-bailout))))
(define-inlinable (cause effect)
(ash effect 1))
(define-inlinable (&depends-on a)
(logand a &all-effects))
(define-inlinable (&causes a)
(logand a (cause &all-effects)))
(define (exclude-effects effects exclude)
(logand effects (lognot (cause exclude))))
(define (effect-free? effects)
(zero? (&causes effects)))
(define (constant? effects)
(zero? effects))
(define-inlinable (depends-on-effects? x effects)
(not (zero? (logand (&depends-on x) effects))))
(define-inlinable (causes-effects? x effects)
(not (zero? (logand (&causes x) (cause effects)))))
(define-inlinable (effects-commute? a b)
(and (not (causes-effects? a (&depends-on b)))
(not (causes-effects? b (&depends-on a)))))
(define (make-effects-analyzer assigned-lexical?)
"Returns a procedure of type EXP -> EFFECTS that analyzes the effects
of an expression."
(let ((cache (make-hash-table)))
(define* (compute-effects exp #:optional (lookup (lambda (x) #f)))
(define (compute-effects exp)
(or (hashq-ref cache exp)
(let ((effects (visit exp)))
(hashq-set! cache exp effects)
effects)))
(define (accumulate-effects exps)
(let lp ((exps exps) (out &no-effects))
(if (null? exps)
out
(lp (cdr exps) (logior out (compute-effects (car exps)))))))
(define (visit exp)
(match exp
(($ <const>)
&no-effects)
(($ <void>)
&no-effects)
(($ <lexical-ref> _ _ gensym)
(if (assigned-lexical? gensym)
&mutable-lexical
&no-effects))
(($ <lexical-set> _ name gensym exp)
(logior (cause &mutable-lexical)
(compute-effects exp)))
(($ <let> _ names gensyms vals body)
(logior (if (or-map assigned-lexical? gensyms)
(cause &allocation)
&no-effects)
(accumulate-effects vals)
(compute-effects body)))
(($ <letrec> _ in-order? names gensyms vals body)
(logior (if (or-map assigned-lexical? gensyms)
(cause &allocation)
&no-effects)
(accumulate-effects vals)
(compute-effects body)))
(($ <fix> _ names gensyms vals body)
(logior (if (or-map assigned-lexical? gensyms)
(cause &allocation)
&no-effects)
(accumulate-effects vals)
(compute-effects body)))
(($ <let-values> _ producer consumer)
(logior (compute-effects producer)
(compute-effects consumer)
(cause &type-check)))
(($ <dynwind> _ winder body unwinder)
(logior (compute-effects winder)
(compute-effects body)
(compute-effects unwinder)))
(($ <dynlet> _ fluids vals body)
(logior (accumulate-effects fluids)
(accumulate-effects vals)
(cause &type-check)
(cause &fluid)
(compute-effects body)))
(($ <dynref> _ fluid)
(logior (compute-effects fluid)
(cause &type-check)
&fluid))
(($ <dynset> _ fluid exp)
(logior (compute-effects fluid)
(compute-effects exp)
(cause &type-check)
(cause &fluid)))
(($ <toplevel-ref>)
(logior &toplevel
(cause &type-check)))
(($ <module-ref>)
(logior &toplevel
(cause &type-check)))
(($ <module-set> _ mod name public? exp)
(logior (cause &toplevel)
(cause &type-check)
(compute-effects exp)))
(($ <toplevel-define> _ name exp)
(logior (cause &toplevel)
(compute-effects exp)))
(($ <toplevel-set> _ name exp)
(logior (cause &toplevel)
(compute-effects exp)))
(($ <primitive-ref>)
&no-effects)
(($ <conditional> _ test consequent alternate)
(let ((tfx (compute-effects test))
(cfx (compute-effects consequent))
(afx (compute-effects alternate)))
(if (causes-effects? (logior tfx (logand afx cfx))
&definite-bailout)
(logior tfx cfx afx)
(exclude-effects (logior tfx cfx afx)
&definite-bailout))))
Zero values .
(($ <application> _ ($ <primitive-ref> _ 'values) ())
(cause &zero-values))
(($ <application> _
($ <primitive-ref> _ (or 'values 'eq? 'eqv? 'equal?))
args)
(accumulate-effects args))
(($ <application> _
($ <primitive-ref> _ (or 'not 'pair? 'null? 'list? 'symbol?
'vector? 'struct? 'string? 'number?
'char?))
(arg))
(compute-effects arg))
(($ <application> _ ($ <primitive-ref> _ 'cons) (x y))
(logior (compute-effects x) (compute-effects y)
(cause &allocation)))
(($ <application> _ ($ <primitive-ref> _ (or 'list 'vector)) args)
(logior (accumulate-effects args) (cause &allocation)))
(($ <application> _ ($ <primitive-ref> _ 'make-prompt-tag) ())
(cause &allocation))
(($ <application> _ ($ <primitive-ref> _ 'make-prompt-tag) (arg))
(logior (compute-effects arg) (cause &allocation)))
(($ <application> _
($ <primitive-ref> _ (and name
(? effect-free-primitive?)))
args)
(logior (accumulate-effects args)
(cause &type-check)
(if (constructor-primitive? name)
(cause &allocation)
(if (accessor-primitive? name)
&mutable-data
&no-effects))))
(($ <application> _ ($ <lambda> _ _ body) args)
(logior (accumulate-effects args)
(match body
(($ <lambda-case> _ req #f #f #f () syms body #f)
(logior (compute-effects body)
(if (= (length req) (length args))
0
(cause &type-check))))
(($ <lambda-case>)
(logior (compute-effects body)
(cause &type-check)))
(#f
(logior (cause &definite-bailout)
(cause &possible-bailout))))))
Bailout primitives .
(($ <application> src ($ <primitive-ref> _ (? bailout-primitive? name))
args)
(logior (accumulate-effects args)
(cause &definite-bailout)
(cause &possible-bailout)))
(($ <application> _ (and proc ($ <lexical-ref> _ _ sym)) args)
(cond
((lookup sym)
=> (lambda (proc)
(compute-effects (make-application #f proc args))))
(else
(logior &all-effects-but-bailout
(cause &all-effects-but-bailout)))))
(($ <application> _ proc args)
(logior &all-effects-but-bailout
(cause &all-effects-but-bailout)))
(($ <lambda> _ meta body)
&no-effects)
(($ <lambda-case> _ req opt rest kw inits gensyms body alt)
(logior (exclude-effects (accumulate-effects inits)
&definite-bailout)
(if (or-map assigned-lexical? gensyms)
(cause &allocation)
&no-effects)
(compute-effects body)
(if alt (compute-effects alt) &no-effects)))
(($ <sequence> _ exps)
(let lp ((exps exps) (effects &no-effects))
(match exps
((tail)
(logior (compute-effects tail)
Returning zero values to a for - effect continuation is
(exclude-effects effects (cause &zero-values))))
((head . tail)
(lp tail (logior (compute-effects head) effects))))))
(($ <prompt> _ tag body handler)
(logior (compute-effects tag)
(compute-effects body)
(compute-effects handler)))
(($ <abort> _ tag args tail)
(logior &all-effects-but-bailout
(cause &all-effects-but-bailout)))))
(compute-effects exp))
compute-effects))
|
f29408d4c9ec812b9410e8464119d8840414d7476a75bbc618033323dfe404ee | rpav/cl-freetype2 | glyph.lisp | (in-package :freetype2-tests)
(in-suite freetype2-tests)
(defvar *glyphslot*)
(defvar *metrics*)
(defvar *glyph*)
(test (test-load-glyphslot :depends-on test-set-size)
"Verify basic glyph info"
(finishes (load-char *face* #\j '(:no-bitmap)))
(is (typep (setf *glyphslot* (ft-face-glyph *face*)) 'ft-glyphslot))
(is (typep (setf *metrics* (ft-glyphslot-metrics *glyphslot*)) 'ft-glyph-metrics)))
(test (test-glyph-metrics :depends-on test-load-glyphslot)
(is (= 320 (ft-glyph-metrics-width *metrics*)))
(is (= 1408 (ft-glyph-metrics-height *metrics*)))
(is (= -64 (ft-glyph-metrics-hori-bearing-x *metrics*)))
(is (= 1088 (ft-glyph-metrics-hori-bearing-y *metrics*))))
(test (test-load-glyph :depends-on test-glyph-metrics)
(is (typep (setf *glyph* (get-glyph *face*)) 'ft-outlineglyph)))
(test (test-render-glyph :depends-on test-load-glyph)
(finishes (render-glyph *face*)))
| null | https://raw.githubusercontent.com/rpav/cl-freetype2/96058da730b4812df916c1f4ee18c99b3b15a3de/t/glyph.lisp | lisp | (in-package :freetype2-tests)
(in-suite freetype2-tests)
(defvar *glyphslot*)
(defvar *metrics*)
(defvar *glyph*)
(test (test-load-glyphslot :depends-on test-set-size)
"Verify basic glyph info"
(finishes (load-char *face* #\j '(:no-bitmap)))
(is (typep (setf *glyphslot* (ft-face-glyph *face*)) 'ft-glyphslot))
(is (typep (setf *metrics* (ft-glyphslot-metrics *glyphslot*)) 'ft-glyph-metrics)))
(test (test-glyph-metrics :depends-on test-load-glyphslot)
(is (= 320 (ft-glyph-metrics-width *metrics*)))
(is (= 1408 (ft-glyph-metrics-height *metrics*)))
(is (= -64 (ft-glyph-metrics-hori-bearing-x *metrics*)))
(is (= 1088 (ft-glyph-metrics-hori-bearing-y *metrics*))))
(test (test-load-glyph :depends-on test-glyph-metrics)
(is (typep (setf *glyph* (get-glyph *face*)) 'ft-outlineglyph)))
(test (test-render-glyph :depends-on test-load-glyph)
(finishes (render-glyph *face*)))
| |
2eeee91d036b5081fcd9a6b44a6962cec829a35f115c4f24b7b50ce90343aa64 | fukamachi/clozure-cl | hash.lisp | -*- Mode : Lisp ; Package : CCL -*-
;;;
Copyright ( C ) 2009 Clozure Associates
Copyright ( C ) 1994 - 2001 Digitool , Inc
This file is part of Clozure CL .
;;;
Clozure CL is licensed under the terms of the Lisp Lesser GNU Public
License , known as the LLGPL and distributed with Clozure CL as the
;;; file "LICENSE". The LLGPL consists of a preamble and the LGPL,
which is distributed with Clozure CL as the file " LGPL " . Where these
;;; conflict, the preamble takes precedence.
;;;
;;; Clozure CL is referenced in the preamble as the "LIBRARY."
;;;
;;; The LLGPL is also available online at
;;;
;; This is just the stuff (make-load-form, print-object) that can't be fasloaded earlier.
;;;;;;;;;;;;;
;;
;; hash.lisp
;; New hash table implementation
;;;;;;;;;;;;;
;;
;; Things I didn't do
;;
Save the 32 - bit hash code along with the key so that growing the table can
avoid calling the hashing function ( at least until a GC happens during growing ) .
;;
Maybe use Knuth 's better method for hashing :
find two primes N-2 , N. N is the table size .
First probe is at primary = ( mod ( funcall ( nhash.keytransF h ) key ) N )
Secondary probes are spaced by ( mod ( funcall ( nhash.keytransF h ) key ) N-2 )
;; This does a bit better scrambling of the secondary probes, but costs another divide.
;;
;; Rethink how finalization is reported to the user. Maybe have a finalization function which
;; is called with the hash table and the deleted key & value.
;;;;;;;;;;;;;
;;
;; Documentation
;;
;; MAKE-HASH-TABLE is extended to accept a :HASH-FUNCTION keyword arg which
defaults for the 4 Common Lisp defined : TEST 's . Also , any fbound symbol can
be used for the : TEST argument . The HASH - FUNCTION is a function of one
argument , the key , which returns one or two values :
;;
;; 1) HASH-CODE
2 ) ADDRESSP
;;
The HASH - CODE can be any object . If it is a relocateable object ( not a
fixnum , short float , or immediate ) then ADDRESSP will default to : KEY
and it is an error if NIL is returned for ADDRESSP .
;;
If ADDRESSP is NIL , the hashing code assumes that no addresses were used
in computing the HASH - CODE . If ADDRESSP is : KEY ( which is the default
if the hash function returns only one value and it is relocateable ) then
;; the hashing code assumes that only the KEY's address was used to compute
;; the HASH-CODE. Otherwise, it is assumed that the address of a
;; component of the key was used to compute the HASH-CODE.
;;
;;
;;
;; Some (proposed) functions for using in user hashing functions:
;;
;; (HASH-CODE object)
;;
returns two values :
;;
;; 1) HASH-CODE
2 ) ADDRESSP
;;
;; HASH-CODE is the object transformed into a fixnum by changing its tag
bits to a fixnum 's tag . ADDRESSP is true if the object was
;; relocateable. ;;
;;
;; (FIXNUM-ADD o1 o2)
Combines two objects additively and returns a fixnum .
If the two objects are fixnums , will be the same as ( + o1 o2 ) except
;; that the result can not be a bignum.
;;
( FIXNUM - MULTIPLY o1 o2 )
Combines two objects multiplicatively and returns a fixnum .
;;
;; (FIXNUM-FLOOR dividend &optional divisor)
Same as Common Lisp 's FLOOR function , but converts the objects into
fixnums before doing the divide and returns two fixnums : quotient &
;; remainder.
;;
;;;;;;;;;;;;;
;;
;; Implementation details.
;;
;; Hash table vectors have a header that the garbage collector knows
;; about followed by alternating keys and values. Empty slots have a
key of ( % UNBOUND - MARKER ) , deleted slots are denoted by a key of
( % SLOT - UNBOUND - MARKER ) , except in the case of " lock - free " hash
;; tables, which see below.
;;
Four bits in the nhash.vector.flags fixnum interact with the garbage
;; collector. This description uses the symbols that represent bit numbers
;; in a fixnum. $nhash_xxx_bit has a corresponding $nhash_lap_xxx_bit which
gives the byte offset of the bit for LAP code . The two bytes in
;; question are at offsets $nhash.vector-weak-byte and
;; $nhash.vector-track-keys-byte offsets from the tagged vector.
The raw 32 bits of the fixnum at look like :
;;
;; TKEC0000 00000000 WVFZ0000 00000000
;;
;;
;; $nhash_track_keys_bit "T" in the diagram above
Sign bit of the longword at $ nhash.vector.flags
;; or the byte at $nhash.vector-track-keys-byte.
If set , GC tracks relocation of keys in the
;; vector.
;; $nhash_key_moved_bit "K" in the diagram above
Set by GC to indicate that a key moved .
;; If $nhash_track_keys_bit is clear, this bit is set to
indicate that any GC will require a rehash .
GC never clears this bit , but may set it if
;; $nhash_track_keys_bit is set.
;; $nhash_component_address_bit "C" in the diagram above.
Ignored by GC . Set to indicate that the
;; address of a component of a key was used.
;; Means that $nhash_track_keys_bit will
;; never be set until all such keys are
;; removed.
;; $nhash_weak_bit "W" in the diagram above
;; Sign bit of the byte at $nhash.vector-weak-byte
;; Set to indicate a weak hash table
;; $nhash_weak_value_bit "V" in the diagram above
;; If clear, the table is weak on key
;; If set, the table is weak on value
;; $nhash_finalizeable_bit "F" in the diagram above
;; If set the table is finalizeable:
;; If any key/value pairs are removed, they will be added to
;; the nhash.vector.finalization-alist using cons cells
from
;; $nhash_keys_frozen_bit "Z" in diagram above.
If set , GC will remove weak entries by setting the
;; value to (%slot-unbound-marker), leaving key unchanged.
(in-package "CCL")
(eval-when (:compile-toplevel :execute)
(require "HASHENV" "ccl:xdump;hashenv"))
(defvar *hash-table-class*
(progn
; #+sparc-target (dbg)
(find-class 'hash-table)))
(setf (type-predicate 'hash-table) 'hash-table-p)
(defmethod print-object ((table hash-table) stream)
(print-unreadable-object (table stream :type t :identity t)
(format stream "~S ~S size ~D/~D"
':test (hash-table-test table)
(hash-table-count table)
(hash-table-size table))
(when (readonly-hash-table-p table)
(format stream " (Readonly)"))))
#+vaporware
;;; Of course, the lisp version of this would be too slow ...
(defun hash-table-finalization-list (hash-table)
(unless (hash-table-p hash-table)
(report-bad-arg hash-table 'hash-table))
(let* ((vector (nhash.vector hash-table))
(flags (nhash.vector.flags vector)))
(declare (fixnum flags))
(if (logbitp $nhash_finalizeable_bit flags)
(nhash.vector.finalization-alist vector)
(error "~S is not a finalizeable hash table" hash-table))))
#+vaporware
(defun (setf hash-table-finalization-list) (value hash-table)
(unless (hash-table-p hash-table)
(report-bad-arg hash-table 'hash-table))
(let* ((vector (nhash.vector hash-table))
(flags (nhash.vector.flags vector)))
(declare (fixnum flags))
(if (logbitp $nhash_finalizeable_bit flags)
(setf (nhash.vector.finalization-alist vector) value)
(error "~S is not a finalizeable hash table" hash-table))))
(defsetf gethash puthash)
; Returns nil, :key or :value
(defun hash-table-weak-p (hash)
(unless (hash-table-p hash)
(setq hash (require-type hash 'hash-table)))
(let* ((vector (nhash.vector hash))
(flags (nhash.vector.flags vector)))
(when (logbitp $nhash_weak_bit flags)
(if (logbitp $nhash_weak_value_bit flags)
:value
:key))))
It would be pretty complicated to offer a way of doing ( SETF
;;; HASH-TABLE-WEAK-P) after the hash-table's been created, and
;;; it's not clear that that'd be incredibly useful.
;;;;;;;;;;;;;
;;
;; Mapping functions
;;
(defun next-hash-table-iteration-1 (state)
(do* ((index (nhti.index state) (1+ index))
(keys (nhti.keys state))
(values (nhti.values state))
(nkeys (nhti.nkeys state)))
((>= index nkeys)
(setf (nhti.index state) nkeys)
nil)
(declare (fixnum index nkeys)
(simple-vector keys))
(let* ((key (svref keys index))
(value (svref values index)))
(setf (nhti.index state) (1+ index))
(return (values t key value)))))
(defun maphash (function hash-table)
"For each entry in HASH-TABLE, call the designated two-argument function
on the key and value of the entry. Return NIL."
(with-hash-table-iterator (m hash-table)
(loop
(multiple-value-bind (found key value) (m)
(unless found (return))
(funcall function key value)))))
(defmethod make-load-form ((hash hash-table) &optional env)
(declare (ignore env))
(let ((keytransF (nhash.keytransF hash))
(compareF (nhash.compareF hash))
(vector (nhash.vector hash))
(private (if (nhash.owner hash) '*current-process*))
(lock-free-p (logtest $nhash.lock-free (the fixnum (nhash.lock hash)))))
(flet ((convert (f)
(if (or (fixnump f) (symbolp f))
`',f
`(symbol-function ',(function-name f)))))
(values
`(%cons-hash-table
nil nil nil ,(nhash.grow-threshold hash) ,(nhash.rehash-ratio hash) ,(nhash.rehash-size hash)
nil nil ,private ,lock-free-p)
`(%initialize-hash-table ,hash ,(convert keytransF) ,(convert compareF) ',vector)))))
(defun needs-rehashing (hash)
(%set-needs-rehashing hash))
(defun %initialize-hash-table (hash keytransF compareF vector)
(setf (nhash.keytransF hash) keytransF
(nhash.compareF hash) compareF)
(setf (nhash.find hash)
(case comparef
(0 #'eq-hash-find)
(-1 #'eql-hash-find)
(t #'general-hash-find))
(nhash.find-new hash)
(case comparef
(0 #'eq-hash-find-for-put)
(-1 #'eql-hash-find-for-put)
(t #'general-hash-find-for-put)))
(setf (nhash.vector hash) vector)
(%set-needs-rehashing hash))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;
;; Support for locking hash tables while fasdumping
;;
(defun fasl-lock-hash-table (hash-table)
(setq hash-table (require-type hash-table 'hash-table))
(without-interrupts
(let* ((lock (nhash.exclusion-lock hash-table)))
(if lock
(progn
(if (hash-lock-free-p hash-table)
;; For lock-free hash tables, this only makes sure nobody is
;; rehashing the table. It doesn't necessarily stop readers
;; or writers (unless they need to rehash).
(grab-lock lock)
(write-lock-rwlock lock))
(push hash-table *fcomp-locked-hash-tables*))
(unless (eq (nhash.owner hash-table) *current-process*)
(error "Current process doesn't own hash-table ~s" hash-table))))))
(defun fasl-unlock-hash-tables ()
(dolist (h *fcomp-locked-hash-tables*)
(let* ((lock (nhash.exclusion-lock h)))
(if (hash-lock-free-p h)
(release-lock lock)
(unlock-rwlock lock)))))
; end
| null | https://raw.githubusercontent.com/fukamachi/clozure-cl/4b0c69452386ae57b08984ed815d9b50b4bcc8a2/lib/hash.lisp | lisp | Package : CCL -*-
file "LICENSE". The LLGPL consists of a preamble and the LGPL,
conflict, the preamble takes precedence.
Clozure CL is referenced in the preamble as the "LIBRARY."
The LLGPL is also available online at
This is just the stuff (make-load-form, print-object) that can't be fasloaded earlier.
hash.lisp
New hash table implementation
Things I didn't do
This does a bit better scrambling of the secondary probes, but costs another divide.
Rethink how finalization is reported to the user. Maybe have a finalization function which
is called with the hash table and the deleted key & value.
Documentation
MAKE-HASH-TABLE is extended to accept a :HASH-FUNCTION keyword arg which
1) HASH-CODE
the hashing code assumes that only the KEY's address was used to compute
the HASH-CODE. Otherwise, it is assumed that the address of a
component of the key was used to compute the HASH-CODE.
Some (proposed) functions for using in user hashing functions:
(HASH-CODE object)
1) HASH-CODE
HASH-CODE is the object transformed into a fixnum by changing its tag
relocateable. ;;
(FIXNUM-ADD o1 o2)
that the result can not be a bignum.
(FIXNUM-FLOOR dividend &optional divisor)
remainder.
Implementation details.
Hash table vectors have a header that the garbage collector knows
about followed by alternating keys and values. Empty slots have a
tables, which see below.
collector. This description uses the symbols that represent bit numbers
in a fixnum. $nhash_xxx_bit has a corresponding $nhash_lap_xxx_bit which
question are at offsets $nhash.vector-weak-byte and
$nhash.vector-track-keys-byte offsets from the tagged vector.
TKEC0000 00000000 WVFZ0000 00000000
$nhash_track_keys_bit "T" in the diagram above
or the byte at $nhash.vector-track-keys-byte.
vector.
$nhash_key_moved_bit "K" in the diagram above
If $nhash_track_keys_bit is clear, this bit is set to
$nhash_track_keys_bit is set.
$nhash_component_address_bit "C" in the diagram above.
address of a component of a key was used.
Means that $nhash_track_keys_bit will
never be set until all such keys are
removed.
$nhash_weak_bit "W" in the diagram above
Sign bit of the byte at $nhash.vector-weak-byte
Set to indicate a weak hash table
$nhash_weak_value_bit "V" in the diagram above
If clear, the table is weak on key
If set, the table is weak on value
$nhash_finalizeable_bit "F" in the diagram above
If set the table is finalizeable:
If any key/value pairs are removed, they will be added to
the nhash.vector.finalization-alist using cons cells
$nhash_keys_frozen_bit "Z" in diagram above.
value to (%slot-unbound-marker), leaving key unchanged.
#+sparc-target (dbg)
Of course, the lisp version of this would be too slow ...
Returns nil, :key or :value
HASH-TABLE-WEAK-P) after the hash-table's been created, and
it's not clear that that'd be incredibly useful.
Mapping functions
Support for locking hash tables while fasdumping
For lock-free hash tables, this only makes sure nobody is
rehashing the table. It doesn't necessarily stop readers
or writers (unless they need to rehash).
end | Copyright ( C ) 2009 Clozure Associates
Copyright ( C ) 1994 - 2001 Digitool , Inc
This file is part of Clozure CL .
Clozure CL is licensed under the terms of the Lisp Lesser GNU Public
License , known as the LLGPL and distributed with Clozure CL as the
which is distributed with Clozure CL as the file " LGPL " . Where these
Save the 32 - bit hash code along with the key so that growing the table can
avoid calling the hashing function ( at least until a GC happens during growing ) .
Maybe use Knuth 's better method for hashing :
find two primes N-2 , N. N is the table size .
First probe is at primary = ( mod ( funcall ( nhash.keytransF h ) key ) N )
Secondary probes are spaced by ( mod ( funcall ( nhash.keytransF h ) key ) N-2 )
defaults for the 4 Common Lisp defined : TEST 's . Also , any fbound symbol can
be used for the : TEST argument . The HASH - FUNCTION is a function of one
argument , the key , which returns one or two values :
2 ) ADDRESSP
The HASH - CODE can be any object . If it is a relocateable object ( not a
fixnum , short float , or immediate ) then ADDRESSP will default to : KEY
and it is an error if NIL is returned for ADDRESSP .
If ADDRESSP is NIL , the hashing code assumes that no addresses were used
in computing the HASH - CODE . If ADDRESSP is : KEY ( which is the default
if the hash function returns only one value and it is relocateable ) then
returns two values :
2 ) ADDRESSP
bits to a fixnum 's tag . ADDRESSP is true if the object was
Combines two objects additively and returns a fixnum .
If the two objects are fixnums , will be the same as ( + o1 o2 ) except
( FIXNUM - MULTIPLY o1 o2 )
Combines two objects multiplicatively and returns a fixnum .
Same as Common Lisp 's FLOOR function , but converts the objects into
fixnums before doing the divide and returns two fixnums : quotient &
key of ( % UNBOUND - MARKER ) , deleted slots are denoted by a key of
( % SLOT - UNBOUND - MARKER ) , except in the case of " lock - free " hash
Four bits in the nhash.vector.flags fixnum interact with the garbage
gives the byte offset of the bit for LAP code . The two bytes in
The raw 32 bits of the fixnum at look like :
Sign bit of the longword at $ nhash.vector.flags
If set , GC tracks relocation of keys in the
Set by GC to indicate that a key moved .
indicate that any GC will require a rehash .
GC never clears this bit , but may set it if
Ignored by GC . Set to indicate that the
from
If set , GC will remove weak entries by setting the
(in-package "CCL")
(eval-when (:compile-toplevel :execute)
(require "HASHENV" "ccl:xdump;hashenv"))
(defvar *hash-table-class*
(progn
(find-class 'hash-table)))
(setf (type-predicate 'hash-table) 'hash-table-p)
(defmethod print-object ((table hash-table) stream)
(print-unreadable-object (table stream :type t :identity t)
(format stream "~S ~S size ~D/~D"
':test (hash-table-test table)
(hash-table-count table)
(hash-table-size table))
(when (readonly-hash-table-p table)
(format stream " (Readonly)"))))
#+vaporware
(defun hash-table-finalization-list (hash-table)
(unless (hash-table-p hash-table)
(report-bad-arg hash-table 'hash-table))
(let* ((vector (nhash.vector hash-table))
(flags (nhash.vector.flags vector)))
(declare (fixnum flags))
(if (logbitp $nhash_finalizeable_bit flags)
(nhash.vector.finalization-alist vector)
(error "~S is not a finalizeable hash table" hash-table))))
#+vaporware
(defun (setf hash-table-finalization-list) (value hash-table)
(unless (hash-table-p hash-table)
(report-bad-arg hash-table 'hash-table))
(let* ((vector (nhash.vector hash-table))
(flags (nhash.vector.flags vector)))
(declare (fixnum flags))
(if (logbitp $nhash_finalizeable_bit flags)
(setf (nhash.vector.finalization-alist vector) value)
(error "~S is not a finalizeable hash table" hash-table))))
(defsetf gethash puthash)
(defun hash-table-weak-p (hash)
(unless (hash-table-p hash)
(setq hash (require-type hash 'hash-table)))
(let* ((vector (nhash.vector hash))
(flags (nhash.vector.flags vector)))
(when (logbitp $nhash_weak_bit flags)
(if (logbitp $nhash_weak_value_bit flags)
:value
:key))))
It would be pretty complicated to offer a way of doing ( SETF
(defun next-hash-table-iteration-1 (state)
(do* ((index (nhti.index state) (1+ index))
(keys (nhti.keys state))
(values (nhti.values state))
(nkeys (nhti.nkeys state)))
((>= index nkeys)
(setf (nhti.index state) nkeys)
nil)
(declare (fixnum index nkeys)
(simple-vector keys))
(let* ((key (svref keys index))
(value (svref values index)))
(setf (nhti.index state) (1+ index))
(return (values t key value)))))
(defun maphash (function hash-table)
"For each entry in HASH-TABLE, call the designated two-argument function
on the key and value of the entry. Return NIL."
(with-hash-table-iterator (m hash-table)
(loop
(multiple-value-bind (found key value) (m)
(unless found (return))
(funcall function key value)))))
(defmethod make-load-form ((hash hash-table) &optional env)
(declare (ignore env))
(let ((keytransF (nhash.keytransF hash))
(compareF (nhash.compareF hash))
(vector (nhash.vector hash))
(private (if (nhash.owner hash) '*current-process*))
(lock-free-p (logtest $nhash.lock-free (the fixnum (nhash.lock hash)))))
(flet ((convert (f)
(if (or (fixnump f) (symbolp f))
`',f
`(symbol-function ',(function-name f)))))
(values
`(%cons-hash-table
nil nil nil ,(nhash.grow-threshold hash) ,(nhash.rehash-ratio hash) ,(nhash.rehash-size hash)
nil nil ,private ,lock-free-p)
`(%initialize-hash-table ,hash ,(convert keytransF) ,(convert compareF) ',vector)))))
(defun needs-rehashing (hash)
(%set-needs-rehashing hash))
(defun %initialize-hash-table (hash keytransF compareF vector)
(setf (nhash.keytransF hash) keytransF
(nhash.compareF hash) compareF)
(setf (nhash.find hash)
(case comparef
(0 #'eq-hash-find)
(-1 #'eql-hash-find)
(t #'general-hash-find))
(nhash.find-new hash)
(case comparef
(0 #'eq-hash-find-for-put)
(-1 #'eql-hash-find-for-put)
(t #'general-hash-find-for-put)))
(setf (nhash.vector hash) vector)
(%set-needs-rehashing hash))
(defun fasl-lock-hash-table (hash-table)
(setq hash-table (require-type hash-table 'hash-table))
(without-interrupts
(let* ((lock (nhash.exclusion-lock hash-table)))
(if lock
(progn
(if (hash-lock-free-p hash-table)
(grab-lock lock)
(write-lock-rwlock lock))
(push hash-table *fcomp-locked-hash-tables*))
(unless (eq (nhash.owner hash-table) *current-process*)
(error "Current process doesn't own hash-table ~s" hash-table))))))
(defun fasl-unlock-hash-tables ()
(dolist (h *fcomp-locked-hash-tables*)
(let* ((lock (nhash.exclusion-lock h)))
(if (hash-lock-free-p h)
(release-lock lock)
(unlock-rwlock lock)))))
|
f8a268a1e59056ff77b0c757082541bc9e7644bb2a1d979827eee4cd015aefad | pentlandedge/s4607 | scatterer_rec_tests.erl | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Copyright 2016 Pentland Edge Ltd.
%%
Licensed under the Apache License , Version 2.0 ( the " License " ) ; you may not
%% use this file except in compliance with the License.
%% You may obtain a copy of the License at
%%
%% -2.0
%%
%% Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an " AS IS " BASIS , WITHOUT
%% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
%% License for the specific language governing permissions and limitations
%% under the License.
%%
-module(scatterer_rec_tests).
-include_lib("eunit/include/eunit.hrl").
-export([sample_record1/0]).
%% Define a test generator for scatterer records.
scatterer_rec_test_() ->
[creation_checks(), payloadsize_checks(), encode_decode_checks()].
%% Create a HRR Scatterer Record and check all the fields in the record
creation_checks() ->
creation_checks1(),
creation_checks2(),
creation_checks3(),
creation_checks4().
creation_checks1() ->
{_,_,_, R1} = sample_record1(),
[?_assertEqual(34, scatterer_rec:get_scatterer_magnitude(R1)),
?_assertEqual(0, scatterer_rec:get_scatterer_phase(R1)),
?_assertEqual(0, scatterer_rec:get_range_index(R1)),
?_assertEqual(0, scatterer_rec:get_doppler_index(R1))].
creation_checks2() ->
{_,_,_, R2} = sample_record2(),
[?_assertEqual(834, scatterer_rec:get_scatterer_magnitude(R2)),
?_assertEqual(133, scatterer_rec:get_scatterer_phase(R2)),
?_assertEqual(0, scatterer_rec:get_range_index(R2)),
?_assertEqual(0, scatterer_rec:get_doppler_index(R2))].
creation_checks3() ->
{_,_,_, R3} = sample_record3(),
[?_assertEqual(834, scatterer_rec:get_scatterer_magnitude(R3)),
?_assertEqual(1133, scatterer_rec:get_scatterer_phase(R3)),
?_assertEqual(2341, scatterer_rec:get_range_index(R3)),
?_assertEqual(0, scatterer_rec:get_doppler_index(R3))].
creation_checks4() ->
{_,_,_, R4} = sample_record4(),
[?_assertEqual(34, scatterer_rec:get_scatterer_magnitude(R4)),
?_assertEqual(133, scatterer_rec:get_scatterer_phase(R4)),
?_assertEqual(10320, scatterer_rec:get_range_index(R4)),
?_assertEqual(10432, scatterer_rec:get_doppler_index(R4))].
%% Checks of the encode/decode functions.
encode_decode_checks() ->
encode_decode_checks1(),
encode_decode_checks2(),
encode_decode_checks3(),
encode_decode_checks4().
encode_decode_checks1() ->
% Create a sample record.
{EM, SM, SP, R1} = sample_record1(),
% Display the record
scatterer_rec:display(R1, EM),
% Encode it
Bin = scatterer_rec:encode(R1, EM, SM, SP),
% Decode it again
{ok, SR, _} = scatterer_rec:decode(Bin, EM, SM, SP),
[?_assertEqual(34, scatterer_rec:get_scatterer_magnitude(SR)),
?_assertEqual(0, scatterer_rec:get_scatterer_phase(SR)),
?_assertEqual(0, scatterer_rec:get_range_index(SR)),
?_assertEqual(0, scatterer_rec:get_doppler_index(SR))].
encode_decode_checks2() ->
% Create a sample record.
{EM, SM, SP, R2} = sample_record2(),
% Encode it
Bin = scatterer_rec:encode(R2, EM, SM, SP),
% Decode it again
{ok, SR, _} = scatterer_rec:decode(Bin, EM, SM, SP),
[?_assertEqual(834, scatterer_rec:get_scatterer_magnitude(SR)),
?_assertEqual(133, scatterer_rec:get_scatterer_phase(SR)),
?_assertEqual(0, scatterer_rec:get_range_index(SR)),
?_assertEqual(0, scatterer_rec:get_doppler_index(SR))].
encode_decode_checks3() ->
% Create a sample record.
{EM, SM, SP, R3} = sample_record3(),
% Encode it
Bin = scatterer_rec:encode(R3, EM, SM, SP),
% Decode it again
{ok, SR, _} = scatterer_rec:decode(Bin, EM, SM, SP),
[?_assertEqual(834, scatterer_rec:get_scatterer_magnitude(SR)),
?_assertEqual(1133, scatterer_rec:get_scatterer_phase(SR)),
?_assertEqual(2341, scatterer_rec:get_range_index(SR)),
?_assertEqual(0, scatterer_rec:get_doppler_index(SR))].
encode_decode_checks4() ->
% Create a sample record.
{EM, SM, SP, R4} = sample_record4(),
% Encode it
Bin = scatterer_rec:encode(R4, EM, SM, SP),
% Decode it again
{ok, SR, _} = scatterer_rec:decode(Bin, EM, SM, SP),
[?_assertEqual(34, scatterer_rec:get_scatterer_magnitude(SR)),
?_assertEqual(133, scatterer_rec:get_scatterer_phase(SR)),
?_assertEqual(10320, scatterer_rec:get_range_index(SR)),
?_assertEqual(10432, scatterer_rec:get_doppler_index(SR))].
%% Create a HRR Scatterer Record and check the payload size of the record
payloadsize_checks() ->
payloadsize_checks1(),
payloadsize_checks2(),
payloadsize_checks3(),
payloadsize_checks4().
payloadsize_checks1() ->
{EM,SM,SP,_} = sample_record1(),
[?_assertEqual(1, scatterer_rec:payload_size(EM, SM, SP))].
payloadsize_checks2() ->
{EM,SM,SP,_} = sample_record2(),
[?_assertEqual(3, scatterer_rec:payload_size(EM, SM, SP))].
payloadsize_checks3() ->
{EM,SM,SP,_} = sample_record3(),
[?_assertEqual(6, scatterer_rec:payload_size(EM, SM, SP))].
payloadsize_checks4() ->
{EM,SM,SP,_} = sample_record4(),
[?_assertEqual(7, scatterer_rec:payload_size(EM, SM, SP))].
%% Create a sample scatterer record. Sets mandatory field to a value.
sample_record1() ->
Params = [{scatterer_magnitude, 34}],
% Return a suitable existence mask as well as the actual record.
EM = {1,0,0,0},
SM = 1,
SP = 0,
{EM, SM, SP, scatterer_rec:new(Params)}.
Create a sample target report . Sets first two fields to a value .
sample_record2() ->
Params = [{scatterer_magnitude, 834}, {scatterer_phase, 113}],
% Return a suitable existence mask as well as the actual record.
EM = {1,1,0,0},
SM = 2,
SP = 1,
{EM, SM, SP, scatterer_rec:new(Params)}.
Create a sample target report . Sets first three fields to a value .
sample_record3() ->
Params = [{scatterer_magnitude, 834}, {scatterer_phase, 1133},
{range_index, 2341}],
% Return a suitable existence mask as well as the actual record.
EM = {1,1,1,0},
SM = 2,
SP = 2,
{EM, SM, SP, scatterer_rec:new(Params)}.
%% Create a sample target report. Sets all fields to a value.
sample_record4() ->
Params = [{scatterer_magnitude, 34}, {scatterer_phase, 133},
{range_index, 10320}, {doppler_index, 10432}],
% Return a suitable existence mask as well as the actual record.
EM = {1,1,1,1},
SM = 1,
SP = 2,
{EM, SM, SP, scatterer_rec:new(Params)}.
| null | https://raw.githubusercontent.com/pentlandedge/s4607/b3cdae404ac5bd50419f33259dfa62af9d1a8d60/test/scatterer_rec_tests.erl | erlang |
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
WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
License for the specific language governing permissions and limitations
under the License.
Define a test generator for scatterer records.
Create a HRR Scatterer Record and check all the fields in the record
Checks of the encode/decode functions.
Create a sample record.
Display the record
Encode it
Decode it again
Create a sample record.
Encode it
Decode it again
Create a sample record.
Encode it
Decode it again
Create a sample record.
Encode it
Decode it again
Create a HRR Scatterer Record and check the payload size of the record
Create a sample scatterer record. Sets mandatory field to a value.
Return a suitable existence mask as well as the actual record.
Return a suitable existence mask as well as the actual record.
Return a suitable existence mask as well as the actual record.
Create a sample target report. Sets all fields to a value.
Return a suitable existence mask as well as the actual record. | Copyright 2016 Pentland Edge Ltd.
Licensed under the Apache License , Version 2.0 ( the " License " ) ; you may not
distributed under the License is distributed on an " AS IS " BASIS , WITHOUT
-module(scatterer_rec_tests).
-include_lib("eunit/include/eunit.hrl").
-export([sample_record1/0]).
scatterer_rec_test_() ->
[creation_checks(), payloadsize_checks(), encode_decode_checks()].
creation_checks() ->
creation_checks1(),
creation_checks2(),
creation_checks3(),
creation_checks4().
creation_checks1() ->
{_,_,_, R1} = sample_record1(),
[?_assertEqual(34, scatterer_rec:get_scatterer_magnitude(R1)),
?_assertEqual(0, scatterer_rec:get_scatterer_phase(R1)),
?_assertEqual(0, scatterer_rec:get_range_index(R1)),
?_assertEqual(0, scatterer_rec:get_doppler_index(R1))].
creation_checks2() ->
{_,_,_, R2} = sample_record2(),
[?_assertEqual(834, scatterer_rec:get_scatterer_magnitude(R2)),
?_assertEqual(133, scatterer_rec:get_scatterer_phase(R2)),
?_assertEqual(0, scatterer_rec:get_range_index(R2)),
?_assertEqual(0, scatterer_rec:get_doppler_index(R2))].
creation_checks3() ->
{_,_,_, R3} = sample_record3(),
[?_assertEqual(834, scatterer_rec:get_scatterer_magnitude(R3)),
?_assertEqual(1133, scatterer_rec:get_scatterer_phase(R3)),
?_assertEqual(2341, scatterer_rec:get_range_index(R3)),
?_assertEqual(0, scatterer_rec:get_doppler_index(R3))].
creation_checks4() ->
{_,_,_, R4} = sample_record4(),
[?_assertEqual(34, scatterer_rec:get_scatterer_magnitude(R4)),
?_assertEqual(133, scatterer_rec:get_scatterer_phase(R4)),
?_assertEqual(10320, scatterer_rec:get_range_index(R4)),
?_assertEqual(10432, scatterer_rec:get_doppler_index(R4))].
encode_decode_checks() ->
encode_decode_checks1(),
encode_decode_checks2(),
encode_decode_checks3(),
encode_decode_checks4().
encode_decode_checks1() ->
{EM, SM, SP, R1} = sample_record1(),
scatterer_rec:display(R1, EM),
Bin = scatterer_rec:encode(R1, EM, SM, SP),
{ok, SR, _} = scatterer_rec:decode(Bin, EM, SM, SP),
[?_assertEqual(34, scatterer_rec:get_scatterer_magnitude(SR)),
?_assertEqual(0, scatterer_rec:get_scatterer_phase(SR)),
?_assertEqual(0, scatterer_rec:get_range_index(SR)),
?_assertEqual(0, scatterer_rec:get_doppler_index(SR))].
encode_decode_checks2() ->
{EM, SM, SP, R2} = sample_record2(),
Bin = scatterer_rec:encode(R2, EM, SM, SP),
{ok, SR, _} = scatterer_rec:decode(Bin, EM, SM, SP),
[?_assertEqual(834, scatterer_rec:get_scatterer_magnitude(SR)),
?_assertEqual(133, scatterer_rec:get_scatterer_phase(SR)),
?_assertEqual(0, scatterer_rec:get_range_index(SR)),
?_assertEqual(0, scatterer_rec:get_doppler_index(SR))].
encode_decode_checks3() ->
{EM, SM, SP, R3} = sample_record3(),
Bin = scatterer_rec:encode(R3, EM, SM, SP),
{ok, SR, _} = scatterer_rec:decode(Bin, EM, SM, SP),
[?_assertEqual(834, scatterer_rec:get_scatterer_magnitude(SR)),
?_assertEqual(1133, scatterer_rec:get_scatterer_phase(SR)),
?_assertEqual(2341, scatterer_rec:get_range_index(SR)),
?_assertEqual(0, scatterer_rec:get_doppler_index(SR))].
encode_decode_checks4() ->
{EM, SM, SP, R4} = sample_record4(),
Bin = scatterer_rec:encode(R4, EM, SM, SP),
{ok, SR, _} = scatterer_rec:decode(Bin, EM, SM, SP),
[?_assertEqual(34, scatterer_rec:get_scatterer_magnitude(SR)),
?_assertEqual(133, scatterer_rec:get_scatterer_phase(SR)),
?_assertEqual(10320, scatterer_rec:get_range_index(SR)),
?_assertEqual(10432, scatterer_rec:get_doppler_index(SR))].
payloadsize_checks() ->
payloadsize_checks1(),
payloadsize_checks2(),
payloadsize_checks3(),
payloadsize_checks4().
payloadsize_checks1() ->
{EM,SM,SP,_} = sample_record1(),
[?_assertEqual(1, scatterer_rec:payload_size(EM, SM, SP))].
payloadsize_checks2() ->
{EM,SM,SP,_} = sample_record2(),
[?_assertEqual(3, scatterer_rec:payload_size(EM, SM, SP))].
payloadsize_checks3() ->
{EM,SM,SP,_} = sample_record3(),
[?_assertEqual(6, scatterer_rec:payload_size(EM, SM, SP))].
payloadsize_checks4() ->
{EM,SM,SP,_} = sample_record4(),
[?_assertEqual(7, scatterer_rec:payload_size(EM, SM, SP))].
sample_record1() ->
Params = [{scatterer_magnitude, 34}],
EM = {1,0,0,0},
SM = 1,
SP = 0,
{EM, SM, SP, scatterer_rec:new(Params)}.
Create a sample target report . Sets first two fields to a value .
sample_record2() ->
Params = [{scatterer_magnitude, 834}, {scatterer_phase, 113}],
EM = {1,1,0,0},
SM = 2,
SP = 1,
{EM, SM, SP, scatterer_rec:new(Params)}.
Create a sample target report . Sets first three fields to a value .
sample_record3() ->
Params = [{scatterer_magnitude, 834}, {scatterer_phase, 1133},
{range_index, 2341}],
EM = {1,1,1,0},
SM = 2,
SP = 2,
{EM, SM, SP, scatterer_rec:new(Params)}.
sample_record4() ->
Params = [{scatterer_magnitude, 34}, {scatterer_phase, 133},
{range_index, 10320}, {doppler_index, 10432}],
EM = {1,1,1,1},
SM = 1,
SP = 2,
{EM, SM, SP, scatterer_rec:new(Params)}.
|
e7f28724182ef22c41efa55b574797c1cffe45606a87362ae58f3f231f32dfb5 | metaocaml/ber-metaocaml | test2.ml | (* TEST
files = "puts.c"
use_runtime = "false"
* hasunix
include unix
** setup-ocamlc.byte-build-env
*** ocamlc.byte
flags = "-w a -output-complete-exe puts.c -ccopt -I${ocamlsrcdir}/runtime"
program = "test2"
**** run
program = "./test2"
***** check-program-output
*)
external puts: string -> unit = "caml_puts"
let _ = at_exit (fun () -> print_endline "Program terminated")
let () =
Unix.putenv "FOO" "Hello OCaml!";
puts (Unix.getenv "FOO")
| null | https://raw.githubusercontent.com/metaocaml/ber-metaocaml/4992d1f87fc08ccb958817926cf9d1d739caf3a2/testsuite/tests/output-complete-obj/test2.ml | ocaml | TEST
files = "puts.c"
use_runtime = "false"
* hasunix
include unix
** setup-ocamlc.byte-build-env
*** ocamlc.byte
flags = "-w a -output-complete-exe puts.c -ccopt -I${ocamlsrcdir}/runtime"
program = "test2"
**** run
program = "./test2"
***** check-program-output
|
external puts: string -> unit = "caml_puts"
let _ = at_exit (fun () -> print_endline "Program terminated")
let () =
Unix.putenv "FOO" "Hello OCaml!";
puts (Unix.getenv "FOO")
|
bb34385092fd45b65254a19aee0e7b58838908556a7285c18954420627462b32 | haroldcarr/learn-haskell-coq-ml-etc | ViewPatterns_OCharles.hs | # LANGUAGE ViewPatterns #
module ViewPatterns.ViewPatterns_OCharles where
import qualified Data.Map.Strict as M
import Data.Sequence
24 Days of GHC Extensions : View Patterns
binding extensions : top - level , where / let bindings
ViewPatterns : enable pattern matching on result of function application
example : num downloads for lens library
24 Days of GHC Extensions: View Patterns
binding extensions : top-level defs, where/let bindings
ViewPatterns : enable pattern matching on result of function application
example: num downloads for lens library
-}
{-# ANN downloadsFor0 "HLint: ignore Use fromMaybe" #-}
downloadsFor0 :: String -> M.Map String Int -> Int
downloadsFor0 pkg packages =
case M.lookup pkg packages of
Just n -> n
Nothing -> 0
downloadsFor :: String -> M.Map String Int -> Int
downloadsFor pkg (M.lookup pkg -> Just downloads) = downloads
downloadsFor _ _ = 0
view pattern defined by two parts
- the view : partially applied function
- the pattern match to perform function application result
------------------------------------------------------------------------------
View Patterns as a Tool for Abstraction
key benefit : view a data type as a def that is easy to pattern match on ,
while using a different type for underlying rep
example : finger tree
-- has poor perfomance
data List a = Nil | Cons a ( List a )
Seq uses a finger tree to get better perfomance
but the def is abstract - instead functions are provided to access - but ca n't pattern match
so use ViewPatterns
example analysing a time series : list of data points
view last data point - if exists
last : : Seq a - > Maybe a
last ? ? = Nothing
last ? ? = Just _
can not pattern match directly on a Seq
can view as list from right
data ViewR a = EmptyR | ( Seq a ) :> a
viewr : : Seq a - > ViewR a
ViewR similar to linked list
view pattern defined by two parts
- the view : partially applied function
- the pattern match to perform function application result
------------------------------------------------------------------------------
View Patterns as a Tool for Abstraction
key benefit : view a data type as a def that is easy to pattern match on,
while using a different type for underlying rep
example : finger tree
-- has poor perfomance
data List a = Nil | Cons a (List a)
Seq uses a finger tree to get better perfomance
but the def is abstract - instead functions are provided to access - but can't pattern match
so use ViewPatterns
example analysing a time series : list of data points
view last data point - if exists
last :: Seq a -> Maybe a
last ?? = Nothing
last ?? = Just _
cannot pattern match directly on a Seq
can view as list from right
data ViewR a = EmptyR | (Seq a) :> a
viewr :: Seq a -> ViewR a
ViewR similar to linked list
-}
last :: Seq a -> Maybe a
last (viewr -> _ :> x) = Just x
last (viewr -> EmptyR) = Nothing
last (viewr -> _) = Nothing -- non exhautive pattern match without this
{-
balance overhead of new syntax against productivity gains
-}
| null | https://raw.githubusercontent.com/haroldcarr/learn-haskell-coq-ml-etc/b4e83ec7c7af730de688b7376497b9f49dc24a0e/haskell/topic/ghc-extensions/src/ViewPatterns/ViewPatterns_OCharles.hs | haskell | # ANN downloadsFor0 "HLint: ignore Use fromMaybe" #
----------------------------------------------------------------------------
has poor perfomance
----------------------------------------------------------------------------
has poor perfomance
non exhautive pattern match without this
balance overhead of new syntax against productivity gains
| # LANGUAGE ViewPatterns #
module ViewPatterns.ViewPatterns_OCharles where
import qualified Data.Map.Strict as M
import Data.Sequence
24 Days of GHC Extensions : View Patterns
binding extensions : top - level , where / let bindings
ViewPatterns : enable pattern matching on result of function application
example : num downloads for lens library
24 Days of GHC Extensions: View Patterns
binding extensions : top-level defs, where/let bindings
ViewPatterns : enable pattern matching on result of function application
example: num downloads for lens library
-}
downloadsFor0 :: String -> M.Map String Int -> Int
downloadsFor0 pkg packages =
case M.lookup pkg packages of
Just n -> n
Nothing -> 0
downloadsFor :: String -> M.Map String Int -> Int
downloadsFor pkg (M.lookup pkg -> Just downloads) = downloads
downloadsFor _ _ = 0
view pattern defined by two parts
- the view : partially applied function
- the pattern match to perform function application result
View Patterns as a Tool for Abstraction
key benefit : view a data type as a def that is easy to pattern match on ,
while using a different type for underlying rep
example : finger tree
data List a = Nil | Cons a ( List a )
Seq uses a finger tree to get better perfomance
but the def is abstract - instead functions are provided to access - but ca n't pattern match
so use ViewPatterns
example analysing a time series : list of data points
view last data point - if exists
last : : Seq a - > Maybe a
last ? ? = Nothing
last ? ? = Just _
can not pattern match directly on a Seq
can view as list from right
data ViewR a = EmptyR | ( Seq a ) :> a
viewr : : Seq a - > ViewR a
ViewR similar to linked list
view pattern defined by two parts
- the view : partially applied function
- the pattern match to perform function application result
View Patterns as a Tool for Abstraction
key benefit : view a data type as a def that is easy to pattern match on,
while using a different type for underlying rep
example : finger tree
data List a = Nil | Cons a (List a)
Seq uses a finger tree to get better perfomance
but the def is abstract - instead functions are provided to access - but can't pattern match
so use ViewPatterns
example analysing a time series : list of data points
view last data point - if exists
last :: Seq a -> Maybe a
last ?? = Nothing
last ?? = Just _
cannot pattern match directly on a Seq
can view as list from right
data ViewR a = EmptyR | (Seq a) :> a
viewr :: Seq a -> ViewR a
ViewR similar to linked list
-}
last :: Seq a -> Maybe a
last (viewr -> _ :> x) = Just x
last (viewr -> EmptyR) = Nothing
|
4390650660d1e00d84a904080835235ee64c45dc0ecdad17dcec560241bae6a2 | CloudI/CloudI | ranch_server.erl | Copyright ( c ) 2012 - 2018 , < >
%%
%% Permission to use, copy, modify, and/or distribute this software for any
%% purpose with or without fee is hereby granted, provided that the above
%% copyright notice and this permission notice appear in all copies.
%%
THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES
%% WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
%% MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN
%% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
%% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
-module(ranch_server).
-behaviour(gen_server).
%% API.
-export([start_link/0]).
-export([set_new_listener_opts/5]).
-export([cleanup_listener_opts/1]).
-export([set_connections_sup/2]).
-export([get_connections_sup/1]).
-export([get_connections_sups/0]).
-export([set_listener_sup/2]).
-export([get_listener_sup/1]).
-export([get_listener_sups/0]).
-export([set_addr/2]).
-export([get_addr/1]).
-export([set_max_connections/2]).
-export([get_max_connections/1]).
-export([set_transport_options/2]).
-export([get_transport_options/1]).
-export([set_protocol_options/2]).
-export([get_protocol_options/1]).
-export([get_listener_start_args/1]).
-export([count_connections/1]).
%% gen_server.
-export([init/1]).
-export([handle_call/3]).
-export([handle_cast/2]).
-export([handle_info/2]).
-export([terminate/2]).
-export([code_change/3]).
-define(TAB, ?MODULE).
-type monitors() :: [{{reference(), pid()}, any()}].
-record(state, {
monitors = [] :: monitors()
}).
%% API.
-spec start_link() -> {ok, pid()}.
start_link() ->
gen_server:start_link({local, ?MODULE}, ?MODULE, [], []).
-spec set_new_listener_opts(ranch:ref(), ranch:max_conns(), any(), any(), [any()]) -> ok.
set_new_listener_opts(Ref, MaxConns, TransOpts, ProtoOpts, StartArgs) ->
gen_server:call(?MODULE, {set_new_listener_opts, Ref, MaxConns, TransOpts, ProtoOpts, StartArgs}).
-spec cleanup_listener_opts(ranch:ref()) -> ok.
cleanup_listener_opts(Ref) ->
_ = ets:delete(?TAB, {addr, Ref}),
_ = ets:delete(?TAB, {max_conns, Ref}),
_ = ets:delete(?TAB, {trans_opts, Ref}),
_ = ets:delete(?TAB, {proto_opts, Ref}),
_ = ets:delete(?TAB, {listener_start_args, Ref}),
%% We also remove the pid of the connections supervisor.
%% Depending on the timing, it might already have been deleted
%% when we handled the monitor DOWN message. However, in some
cases when calling followed by get_connections_sup ,
%% we could end up with the pid still being returned, when we
%% expected a crash (because the listener was stopped).
%% Deleting it explictly here removes any possible confusion.
_ = ets:delete(?TAB, {conns_sup, Ref}),
%% Ditto for the listener supervisor.
_ = ets:delete(?TAB, {listener_sup, Ref}),
ok.
-spec set_connections_sup(ranch:ref(), pid()) -> ok.
set_connections_sup(Ref, Pid) ->
gen_server:call(?MODULE, {set_connections_sup, Ref, Pid}).
-spec get_connections_sup(ranch:ref()) -> pid().
get_connections_sup(Ref) ->
ets:lookup_element(?TAB, {conns_sup, Ref}, 2).
-spec get_connections_sups() -> [{ranch:ref(), pid()}].
get_connections_sups() ->
[{Ref, Pid} || [Ref, Pid] <- ets:match(?TAB, {{conns_sup, '$1'}, '$2'})].
-spec set_listener_sup(ranch:ref(), pid()) -> ok.
set_listener_sup(Ref, Pid) ->
gen_server:call(?MODULE, {set_listener_sup, Ref, Pid}).
-spec get_listener_sup(ranch:ref()) -> pid().
get_listener_sup(Ref) ->
ets:lookup_element(?TAB, {listener_sup, Ref}, 2).
-spec get_listener_sups() -> [{ranch:ref(), pid()}].
get_listener_sups() ->
[{Ref, Pid} || [Ref, Pid] <- ets:match(?TAB, {{listener_sup, '$1'}, '$2'})].
-spec set_addr(ranch:ref(), {inet:ip_address(), inet:port_number()} | {undefined, undefined}) -> ok.
set_addr(Ref, Addr) ->
gen_server:call(?MODULE, {set_addr, Ref, Addr}).
-spec get_addr(ranch:ref()) -> {inet:ip_address(), inet:port_number()} | {undefined, undefined}.
get_addr(Ref) ->
ets:lookup_element(?TAB, {addr, Ref}, 2).
-spec set_max_connections(ranch:ref(), ranch:max_conns()) -> ok.
set_max_connections(Ref, MaxConnections) ->
gen_server:call(?MODULE, {set_max_conns, Ref, MaxConnections}).
-spec get_max_connections(ranch:ref()) -> ranch:max_conns().
get_max_connections(Ref) ->
ets:lookup_element(?TAB, {max_conns, Ref}, 2).
-spec set_transport_options(ranch:ref(), any()) -> ok.
set_transport_options(Ref, TransOpts) ->
gen_server:call(?MODULE, {set_trans_opts, Ref, TransOpts}).
-spec get_transport_options(ranch:ref()) -> any().
get_transport_options(Ref) ->
ets:lookup_element(?TAB, {trans_opts, Ref}, 2).
-spec set_protocol_options(ranch:ref(), any()) -> ok.
set_protocol_options(Ref, ProtoOpts) ->
gen_server:call(?MODULE, {set_proto_opts, Ref, ProtoOpts}).
-spec get_protocol_options(ranch:ref()) -> any().
get_protocol_options(Ref) ->
ets:lookup_element(?TAB, {proto_opts, Ref}, 2).
-spec get_listener_start_args(ranch:ref()) -> [any()].
get_listener_start_args(Ref) ->
ets:lookup_element(?TAB, {listener_start_args, Ref}, 2).
-spec count_connections(ranch:ref()) -> non_neg_integer().
count_connections(Ref) ->
ranch_conns_sup:active_connections(get_connections_sup(Ref)).
%% gen_server.
init([]) ->
ConnMonitors = [{{erlang:monitor(process, Pid), Pid}, {conns_sup, Ref}} ||
[Ref, Pid] <- ets:match(?TAB, {{conns_sup, '$1'}, '$2'})],
ListenerMonitors = [{{erlang:monitor(process, Pid), Pid}, {listener_sup, Ref}} ||
[Ref, Pid] <- ets:match(?TAB, {{listener_sup, '$1'}, '$2'})],
{ok, #state{monitors=ConnMonitors++ListenerMonitors}}.
handle_call({set_new_listener_opts, Ref, MaxConns, TransOpts, ProtoOpts, StartArgs}, _, State) ->
ets:insert_new(?TAB, {{max_conns, Ref}, MaxConns}),
ets:insert_new(?TAB, {{trans_opts, Ref}, TransOpts}),
ets:insert_new(?TAB, {{proto_opts, Ref}, ProtoOpts}),
ets:insert_new(?TAB, {{listener_start_args, Ref}, StartArgs}),
{reply, ok, State};
handle_call({set_connections_sup, Ref, Pid}, _, State0) ->
State = set_monitored_process({conns_sup, Ref}, Pid, State0),
{reply, ok, State};
handle_call({set_listener_sup, Ref, Pid}, _, State0) ->
State = set_monitored_process({listener_sup, Ref}, Pid, State0),
{reply, ok, State};
handle_call({set_addr, Ref, Addr}, _, State) ->
true = ets:insert(?TAB, {{addr, Ref}, Addr}),
{reply, ok, State};
handle_call({set_max_conns, Ref, MaxConns}, _, State) ->
ets:insert(?TAB, {{max_conns, Ref}, MaxConns}),
ConnsSup = get_connections_sup(Ref),
ConnsSup ! {set_max_conns, MaxConns},
{reply, ok, State};
handle_call({set_trans_opts, Ref, Opts}, _, State) ->
ets:insert(?TAB, {{trans_opts, Ref}, Opts}),
{reply, ok, State};
handle_call({set_proto_opts, Ref, Opts}, _, State) ->
ets:insert(?TAB, {{proto_opts, Ref}, Opts}),
ConnsSup = get_connections_sup(Ref),
ConnsSup ! {set_opts, Opts},
{reply, ok, State};
handle_call(_Request, _From, State) ->
{reply, ignore, State}.
handle_cast(_Request, State) ->
{noreply, State}.
handle_info({'DOWN', MonitorRef, process, Pid, Reason},
State=#state{monitors=Monitors}) ->
{_, TypeRef} = lists:keyfind({MonitorRef, Pid}, 1, Monitors),
ok = case {TypeRef, Reason} of
{{listener_sup, Ref}, normal} ->
cleanup_listener_opts(Ref);
{{listener_sup, Ref}, shutdown} ->
cleanup_listener_opts(Ref);
{{listener_sup, Ref}, {shutdown, _}} ->
cleanup_listener_opts(Ref);
_ ->
_ = ets:delete(?TAB, TypeRef),
ok
end,
Monitors2 = lists:keydelete({MonitorRef, Pid}, 1, Monitors),
{noreply, State#state{monitors=Monitors2}};
handle_info(_Info, State) ->
{noreply, State}.
terminate(_Reason, _State) ->
ok.
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
Internal .
set_monitored_process(Key, Pid, State=#state{monitors=Monitors0}) ->
%% First we cleanup the monitor if a residual one exists.
%% This can happen during crashes when the restart is faster
%% than the cleanup.
Monitors = case lists:keytake(Key, 2, Monitors0) of
false ->
Monitors0;
{value, {{OldMonitorRef, _}, _}, Monitors1} ->
true = erlang:demonitor(OldMonitorRef, [flush]),
Monitors1
end,
%% Then we unconditionally insert in the ets table.
%% If residual data is there, it will be overwritten.
true = ets:insert(?TAB, {Key, Pid}),
%% Finally we start monitoring this new process.
MonitorRef = erlang:monitor(process, Pid),
State#state{monitors=[{{MonitorRef, Pid}, Key}|Monitors]}.
| null | https://raw.githubusercontent.com/CloudI/CloudI/75b93bb0e7dc4734f5cd1ef913788e44b577a3d5/src/external/cloudi_x_ranch/src/ranch_server.erl | erlang |
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
API.
gen_server.
API.
We also remove the pid of the connections supervisor.
Depending on the timing, it might already have been deleted
when we handled the monitor DOWN message. However, in some
we could end up with the pid still being returned, when we
expected a crash (because the listener was stopped).
Deleting it explictly here removes any possible confusion.
Ditto for the listener supervisor.
gen_server.
First we cleanup the monitor if a residual one exists.
This can happen during crashes when the restart is faster
than the cleanup.
Then we unconditionally insert in the ets table.
If residual data is there, it will be overwritten.
Finally we start monitoring this new process. | Copyright ( c ) 2012 - 2018 , < >
THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES
ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN
-module(ranch_server).
-behaviour(gen_server).
-export([start_link/0]).
-export([set_new_listener_opts/5]).
-export([cleanup_listener_opts/1]).
-export([set_connections_sup/2]).
-export([get_connections_sup/1]).
-export([get_connections_sups/0]).
-export([set_listener_sup/2]).
-export([get_listener_sup/1]).
-export([get_listener_sups/0]).
-export([set_addr/2]).
-export([get_addr/1]).
-export([set_max_connections/2]).
-export([get_max_connections/1]).
-export([set_transport_options/2]).
-export([get_transport_options/1]).
-export([set_protocol_options/2]).
-export([get_protocol_options/1]).
-export([get_listener_start_args/1]).
-export([count_connections/1]).
-export([init/1]).
-export([handle_call/3]).
-export([handle_cast/2]).
-export([handle_info/2]).
-export([terminate/2]).
-export([code_change/3]).
-define(TAB, ?MODULE).
-type monitors() :: [{{reference(), pid()}, any()}].
-record(state, {
monitors = [] :: monitors()
}).
-spec start_link() -> {ok, pid()}.
start_link() ->
gen_server:start_link({local, ?MODULE}, ?MODULE, [], []).
-spec set_new_listener_opts(ranch:ref(), ranch:max_conns(), any(), any(), [any()]) -> ok.
set_new_listener_opts(Ref, MaxConns, TransOpts, ProtoOpts, StartArgs) ->
gen_server:call(?MODULE, {set_new_listener_opts, Ref, MaxConns, TransOpts, ProtoOpts, StartArgs}).
-spec cleanup_listener_opts(ranch:ref()) -> ok.
cleanup_listener_opts(Ref) ->
_ = ets:delete(?TAB, {addr, Ref}),
_ = ets:delete(?TAB, {max_conns, Ref}),
_ = ets:delete(?TAB, {trans_opts, Ref}),
_ = ets:delete(?TAB, {proto_opts, Ref}),
_ = ets:delete(?TAB, {listener_start_args, Ref}),
cases when calling followed by get_connections_sup ,
_ = ets:delete(?TAB, {conns_sup, Ref}),
_ = ets:delete(?TAB, {listener_sup, Ref}),
ok.
-spec set_connections_sup(ranch:ref(), pid()) -> ok.
set_connections_sup(Ref, Pid) ->
gen_server:call(?MODULE, {set_connections_sup, Ref, Pid}).
-spec get_connections_sup(ranch:ref()) -> pid().
get_connections_sup(Ref) ->
ets:lookup_element(?TAB, {conns_sup, Ref}, 2).
-spec get_connections_sups() -> [{ranch:ref(), pid()}].
get_connections_sups() ->
[{Ref, Pid} || [Ref, Pid] <- ets:match(?TAB, {{conns_sup, '$1'}, '$2'})].
-spec set_listener_sup(ranch:ref(), pid()) -> ok.
set_listener_sup(Ref, Pid) ->
gen_server:call(?MODULE, {set_listener_sup, Ref, Pid}).
-spec get_listener_sup(ranch:ref()) -> pid().
get_listener_sup(Ref) ->
ets:lookup_element(?TAB, {listener_sup, Ref}, 2).
-spec get_listener_sups() -> [{ranch:ref(), pid()}].
get_listener_sups() ->
[{Ref, Pid} || [Ref, Pid] <- ets:match(?TAB, {{listener_sup, '$1'}, '$2'})].
-spec set_addr(ranch:ref(), {inet:ip_address(), inet:port_number()} | {undefined, undefined}) -> ok.
set_addr(Ref, Addr) ->
gen_server:call(?MODULE, {set_addr, Ref, Addr}).
-spec get_addr(ranch:ref()) -> {inet:ip_address(), inet:port_number()} | {undefined, undefined}.
get_addr(Ref) ->
ets:lookup_element(?TAB, {addr, Ref}, 2).
-spec set_max_connections(ranch:ref(), ranch:max_conns()) -> ok.
set_max_connections(Ref, MaxConnections) ->
gen_server:call(?MODULE, {set_max_conns, Ref, MaxConnections}).
-spec get_max_connections(ranch:ref()) -> ranch:max_conns().
get_max_connections(Ref) ->
ets:lookup_element(?TAB, {max_conns, Ref}, 2).
-spec set_transport_options(ranch:ref(), any()) -> ok.
set_transport_options(Ref, TransOpts) ->
gen_server:call(?MODULE, {set_trans_opts, Ref, TransOpts}).
-spec get_transport_options(ranch:ref()) -> any().
get_transport_options(Ref) ->
ets:lookup_element(?TAB, {trans_opts, Ref}, 2).
-spec set_protocol_options(ranch:ref(), any()) -> ok.
set_protocol_options(Ref, ProtoOpts) ->
gen_server:call(?MODULE, {set_proto_opts, Ref, ProtoOpts}).
-spec get_protocol_options(ranch:ref()) -> any().
get_protocol_options(Ref) ->
ets:lookup_element(?TAB, {proto_opts, Ref}, 2).
-spec get_listener_start_args(ranch:ref()) -> [any()].
get_listener_start_args(Ref) ->
ets:lookup_element(?TAB, {listener_start_args, Ref}, 2).
-spec count_connections(ranch:ref()) -> non_neg_integer().
count_connections(Ref) ->
ranch_conns_sup:active_connections(get_connections_sup(Ref)).
init([]) ->
ConnMonitors = [{{erlang:monitor(process, Pid), Pid}, {conns_sup, Ref}} ||
[Ref, Pid] <- ets:match(?TAB, {{conns_sup, '$1'}, '$2'})],
ListenerMonitors = [{{erlang:monitor(process, Pid), Pid}, {listener_sup, Ref}} ||
[Ref, Pid] <- ets:match(?TAB, {{listener_sup, '$1'}, '$2'})],
{ok, #state{monitors=ConnMonitors++ListenerMonitors}}.
handle_call({set_new_listener_opts, Ref, MaxConns, TransOpts, ProtoOpts, StartArgs}, _, State) ->
ets:insert_new(?TAB, {{max_conns, Ref}, MaxConns}),
ets:insert_new(?TAB, {{trans_opts, Ref}, TransOpts}),
ets:insert_new(?TAB, {{proto_opts, Ref}, ProtoOpts}),
ets:insert_new(?TAB, {{listener_start_args, Ref}, StartArgs}),
{reply, ok, State};
handle_call({set_connections_sup, Ref, Pid}, _, State0) ->
State = set_monitored_process({conns_sup, Ref}, Pid, State0),
{reply, ok, State};
handle_call({set_listener_sup, Ref, Pid}, _, State0) ->
State = set_monitored_process({listener_sup, Ref}, Pid, State0),
{reply, ok, State};
handle_call({set_addr, Ref, Addr}, _, State) ->
true = ets:insert(?TAB, {{addr, Ref}, Addr}),
{reply, ok, State};
handle_call({set_max_conns, Ref, MaxConns}, _, State) ->
ets:insert(?TAB, {{max_conns, Ref}, MaxConns}),
ConnsSup = get_connections_sup(Ref),
ConnsSup ! {set_max_conns, MaxConns},
{reply, ok, State};
handle_call({set_trans_opts, Ref, Opts}, _, State) ->
ets:insert(?TAB, {{trans_opts, Ref}, Opts}),
{reply, ok, State};
handle_call({set_proto_opts, Ref, Opts}, _, State) ->
ets:insert(?TAB, {{proto_opts, Ref}, Opts}),
ConnsSup = get_connections_sup(Ref),
ConnsSup ! {set_opts, Opts},
{reply, ok, State};
handle_call(_Request, _From, State) ->
{reply, ignore, State}.
handle_cast(_Request, State) ->
{noreply, State}.
handle_info({'DOWN', MonitorRef, process, Pid, Reason},
State=#state{monitors=Monitors}) ->
{_, TypeRef} = lists:keyfind({MonitorRef, Pid}, 1, Monitors),
ok = case {TypeRef, Reason} of
{{listener_sup, Ref}, normal} ->
cleanup_listener_opts(Ref);
{{listener_sup, Ref}, shutdown} ->
cleanup_listener_opts(Ref);
{{listener_sup, Ref}, {shutdown, _}} ->
cleanup_listener_opts(Ref);
_ ->
_ = ets:delete(?TAB, TypeRef),
ok
end,
Monitors2 = lists:keydelete({MonitorRef, Pid}, 1, Monitors),
{noreply, State#state{monitors=Monitors2}};
handle_info(_Info, State) ->
{noreply, State}.
terminate(_Reason, _State) ->
ok.
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
Internal .
set_monitored_process(Key, Pid, State=#state{monitors=Monitors0}) ->
Monitors = case lists:keytake(Key, 2, Monitors0) of
false ->
Monitors0;
{value, {{OldMonitorRef, _}, _}, Monitors1} ->
true = erlang:demonitor(OldMonitorRef, [flush]),
Monitors1
end,
true = ets:insert(?TAB, {Key, Pid}),
MonitorRef = erlang:monitor(process, Pid),
State#state{monitors=[{{MonitorRef, Pid}, Key}|Monitors]}.
|
38e5ef6b04d64966e96263000da6a7c4c263a0f9ef9d58cabedfb978ff4ccc4a | ayazhafiz/plts | eval.ml | open Language
(* Reference store *)
type store = term list
let emptystore = []
let extend_store store v = (List.length store, store @ [ v ])
let lookup_store store loc = List.nth store loc
let update_store store loc v =
let rec f toGo store =
let rest = List.tl store in
match toGo with 0 -> v :: rest | _ -> List.hd store :: f (toGo - 1) rest
in
f loc store
let shift_store store amt = List.map (fun t -> termShift amt t) store
let rec isnumeric t =
match t with
| TmZero _ -> true
| TmSucc (_, term) -> isnumeric term
| _ -> false
let rec isval ctx t =
match t with
| term when isnumeric term -> true
| TmTrue _ | TmFalse _ | TmUnit _ | TmString _ | TmFloat _ | TmInert _
| TmLoc _ ->
true
| TmTag (_, _, term, _) -> isval ctx term
| TmAbs _ | TmTyAbs _ -> true
| TmRecord (_, fields) ->
List.for_all (fun (_, term) -> isval ctx term) fields
| TmPack (_, _, v1, _) when isval ctx v1 -> true
| _ -> false
exception NoRuleApplies
let rec eval' ctx store t =
match t with
| TmVar (info, name, _) -> (
match getbinding info ctx name with
| TmAbbBinding (term, _) -> (term, store)
| _ -> raise NoRuleApplies )
| TmApp (_, TmAbs (_, _, _, t12), v2) when isval ctx v2 ->
(termSubstTop v2 t12, store)
| TmApp (info, t1, t2) when isval ctx t1 ->
let t2', store' = eval' ctx store t2 in
(TmApp (info, t1, t2'), store')
| TmApp (info, t1, t2) ->
let t1', store' = eval' ctx store t1 in
(TmApp (info, t1', t2), store')
| TmIf (_, TmTrue _, thn, _) -> (thn, store)
| TmIf (_, TmFalse _, _, els) -> (els, store)
| TmIf (info, cond, thn, els) ->
let cond', store' = eval' ctx store cond in
(TmIf (info, cond', thn, els), store')
| TmCase (_, TmTag (_, varName, varVal, _), cases) ->
let _, branch = List.assoc varName cases in
(termSubstTop varVal branch, store)
| TmCase (info, cond, cases) ->
let cond', store' = eval' ctx store cond in
(TmCase (info, cond', cases), store')
| TmTag (info, name, term, ty) ->
let term', store' = eval' ctx store term in
(TmTag (info, name, term', ty), store')
| TmLet (_, _, nameVal, body) when isval ctx nameVal ->
(termSubstTop nameVal body, store)
| TmLet (info, name, nameVal, body) ->
let nameVal', store' = eval' ctx store nameVal in
(TmLet (info, name, nameVal', body), store')
| TmFix (_, (TmAbs (_, _, _, body) as term)) as fixedPoint when isval ctx term
->
(termSubstTop fixedPoint body, store)
| TmFix (info, term) ->
let term', store' = eval' ctx store term in
(TmFix (info, term'), store')
| TmAscribe (_, term, _) when isval ctx term -> (term, store)
| TmAscribe (info, term, ty) ->
let term', store' = eval' ctx store term in
(TmAscribe (info, term', ty), store')
| TmRecord (info, terms) ->
let rec evalNextUnevaled fields =
match fields with
| [] -> raise NoRuleApplies
| (name, term) :: rest when isval ctx term ->
let rest', store' = evalNextUnevaled rest in
((name, term) :: rest', store')
| (name, term) :: rest ->
let term', store' = eval' ctx store term in
((name, term') :: rest, store')
in
let terms', store' = evalNextUnevaled terms in
(TmRecord (info, terms'), store')
| TmProj (_, (TmRecord (_, fields) as rcd), key) when isval ctx rcd ->
(List.assoc key fields, store)
| TmProj (info, rcd, key) ->
let rcd', store' = eval' ctx store rcd in
(TmProj (info, rcd', key), store')
| TmTimesfloat (info, TmFloat (_, f1), TmFloat (_, f2)) ->
(TmFloat (info, f1 *. f2), store)
One step at a time : first lower f1 to a float , then f2 .
| TmTimesfloat (info, (TmFloat (_, _) as f1), f2) ->
let f2', store' = eval' ctx store f2 in
(TmTimesfloat (info, f1, f2'), store')
| TmTimesfloat (info, f1, f2) ->
let f1', store' = eval' ctx store f1 in
(TmTimesfloat (info, f1', f2), store')
| TmPlusfloat (info, TmFloat (_, f1), TmFloat (_, f2)) ->
(TmFloat (info, f1 +. f2), store)
One step at a time : first lower f1 to a float , then f2 .
| TmPlusfloat (info, (TmFloat (_, _) as f1), f2) ->
let f2', store' = eval' ctx store f2 in
(TmPlusfloat (info, f1, f2'), store')
| TmPlusfloat (info, f1, f2) ->
let f1', store' = eval' ctx store f1 in
(TmPlusfloat (info, f1', f2), store')
| TmSucc (_, TmPred (_, term)) when isnumeric term -> (term, store)
| TmSucc (info, term) ->
let term', store' = eval' ctx store term in
(TmSucc (info, term'), store')
| TmPred (_, TmSucc (_, term)) when isnumeric term -> (term, store)
| TmPred (info, TmZero _) -> (TmZero info, store)
| TmPred (info, term) ->
let term', store' = eval' ctx store term in
(TmPred (info, term'), store')
| TmIsZero (info, TmZero _) -> (TmTrue info, store)
| TmIsZero (info, TmSucc (_, term)) when isnumeric term ->
(TmFalse info, store)
| TmIsZero (info, term) ->
let term', store' = eval' ctx store term in
(TmIsZero (info, term'), store')
| TmRef (info, value) when isval ctx value ->
let where, store' = extend_store store value in
(TmLoc (info, where), store')
| TmRef (info, value) ->
let value', store' = eval' ctx store value in
(TmRef (info, value'), store')
| TmDeref (_, TmLoc (_, where)) -> (lookup_store store where, store)
| TmDeref (info, term) ->
let term', store' = eval' ctx store term in
(TmDeref (info, term'), store')
| TmRefAssign (info, TmLoc (_, where), term) when isval ctx term ->
let store' = update_store store where term in
(TmUnit info, store')
One step at a time : first lower location , then the value .
| TmRefAssign (info, (TmLoc _ as refLoc), refVal) ->
let refVal', store' = eval' ctx store refVal in
(TmRefAssign (info, refLoc, refVal'), store')
| TmRefAssign (info, refLoc, refVal) ->
let refLoc', store' = eval' ctx store refLoc in
(TmRefAssign (info, refLoc', refVal), store')
| TmTyApp (_, TmTyAbs (_, _, body), tyConcrete) ->
(typeTermSubstTop tyConcrete body, store)
| TmTyApp (info, term, tyConcrete) ->
let term', store' = eval' ctx store term in
(TmTyApp (info, term', tyConcrete), store')
| TmUnpack (_, _, _, TmPack (_, tyConcrete, packTerm, _), inTerm)
when isval ctx packTerm ->
Substitute the packed value in for name used for the unpacked value .
Shift by 1 first to account for the fact that we are substituting in a
term that would still have the unpacked Type bound as well , which we
have n't substituted yet !
Shift by 1 first to account for the fact that we are substituting in a
term that would still have the unpacked Type bound as well, which we
haven't substituted yet! *)
let inTermWithPackedVal = termSubstTop (termShift 1 packTerm) inTerm in
(* Now substitute the concrete type for the type name we unpacked. *)
(typeTermSubstTop tyConcrete inTermWithPackedVal, store)
| TmUnpack (info, n1, n2, t1, t2) ->
let t1', store' = eval' ctx store t1 in
(TmUnpack (info, n1, n2, t1', t2), store')
| TmPack (info, tyC, termC, tySome) ->
let termC', store' = eval' ctx store termC in
(TmPack (info, tyC, termC', tySome), store')
| _ -> raise NoRuleApplies
let rec eval ctx store t =
try
let t', store' = eval' ctx store t in
eval ctx store' t'
with NoRuleApplies -> (t, store)
let evalbinding ctx store binding =
match binding with
| TmAbbBinding (t, ty) ->
let term', store' = eval ctx store t in
(TmAbbBinding (term', ty), store')
| b -> (b, store)
| null | https://raw.githubusercontent.com/ayazhafiz/plts/59b3996642f4fd5941c96a4987643303acc3dee6/tapl/25-systemf/eval.ml | ocaml | Reference store
Now substitute the concrete type for the type name we unpacked. | open Language
type store = term list
let emptystore = []
let extend_store store v = (List.length store, store @ [ v ])
let lookup_store store loc = List.nth store loc
let update_store store loc v =
let rec f toGo store =
let rest = List.tl store in
match toGo with 0 -> v :: rest | _ -> List.hd store :: f (toGo - 1) rest
in
f loc store
let shift_store store amt = List.map (fun t -> termShift amt t) store
let rec isnumeric t =
match t with
| TmZero _ -> true
| TmSucc (_, term) -> isnumeric term
| _ -> false
let rec isval ctx t =
match t with
| term when isnumeric term -> true
| TmTrue _ | TmFalse _ | TmUnit _ | TmString _ | TmFloat _ | TmInert _
| TmLoc _ ->
true
| TmTag (_, _, term, _) -> isval ctx term
| TmAbs _ | TmTyAbs _ -> true
| TmRecord (_, fields) ->
List.for_all (fun (_, term) -> isval ctx term) fields
| TmPack (_, _, v1, _) when isval ctx v1 -> true
| _ -> false
exception NoRuleApplies
let rec eval' ctx store t =
match t with
| TmVar (info, name, _) -> (
match getbinding info ctx name with
| TmAbbBinding (term, _) -> (term, store)
| _ -> raise NoRuleApplies )
| TmApp (_, TmAbs (_, _, _, t12), v2) when isval ctx v2 ->
(termSubstTop v2 t12, store)
| TmApp (info, t1, t2) when isval ctx t1 ->
let t2', store' = eval' ctx store t2 in
(TmApp (info, t1, t2'), store')
| TmApp (info, t1, t2) ->
let t1', store' = eval' ctx store t1 in
(TmApp (info, t1', t2), store')
| TmIf (_, TmTrue _, thn, _) -> (thn, store)
| TmIf (_, TmFalse _, _, els) -> (els, store)
| TmIf (info, cond, thn, els) ->
let cond', store' = eval' ctx store cond in
(TmIf (info, cond', thn, els), store')
| TmCase (_, TmTag (_, varName, varVal, _), cases) ->
let _, branch = List.assoc varName cases in
(termSubstTop varVal branch, store)
| TmCase (info, cond, cases) ->
let cond', store' = eval' ctx store cond in
(TmCase (info, cond', cases), store')
| TmTag (info, name, term, ty) ->
let term', store' = eval' ctx store term in
(TmTag (info, name, term', ty), store')
| TmLet (_, _, nameVal, body) when isval ctx nameVal ->
(termSubstTop nameVal body, store)
| TmLet (info, name, nameVal, body) ->
let nameVal', store' = eval' ctx store nameVal in
(TmLet (info, name, nameVal', body), store')
| TmFix (_, (TmAbs (_, _, _, body) as term)) as fixedPoint when isval ctx term
->
(termSubstTop fixedPoint body, store)
| TmFix (info, term) ->
let term', store' = eval' ctx store term in
(TmFix (info, term'), store')
| TmAscribe (_, term, _) when isval ctx term -> (term, store)
| TmAscribe (info, term, ty) ->
let term', store' = eval' ctx store term in
(TmAscribe (info, term', ty), store')
| TmRecord (info, terms) ->
let rec evalNextUnevaled fields =
match fields with
| [] -> raise NoRuleApplies
| (name, term) :: rest when isval ctx term ->
let rest', store' = evalNextUnevaled rest in
((name, term) :: rest', store')
| (name, term) :: rest ->
let term', store' = eval' ctx store term in
((name, term') :: rest, store')
in
let terms', store' = evalNextUnevaled terms in
(TmRecord (info, terms'), store')
| TmProj (_, (TmRecord (_, fields) as rcd), key) when isval ctx rcd ->
(List.assoc key fields, store)
| TmProj (info, rcd, key) ->
let rcd', store' = eval' ctx store rcd in
(TmProj (info, rcd', key), store')
| TmTimesfloat (info, TmFloat (_, f1), TmFloat (_, f2)) ->
(TmFloat (info, f1 *. f2), store)
One step at a time : first lower f1 to a float , then f2 .
| TmTimesfloat (info, (TmFloat (_, _) as f1), f2) ->
let f2', store' = eval' ctx store f2 in
(TmTimesfloat (info, f1, f2'), store')
| TmTimesfloat (info, f1, f2) ->
let f1', store' = eval' ctx store f1 in
(TmTimesfloat (info, f1', f2), store')
| TmPlusfloat (info, TmFloat (_, f1), TmFloat (_, f2)) ->
(TmFloat (info, f1 +. f2), store)
One step at a time : first lower f1 to a float , then f2 .
| TmPlusfloat (info, (TmFloat (_, _) as f1), f2) ->
let f2', store' = eval' ctx store f2 in
(TmPlusfloat (info, f1, f2'), store')
| TmPlusfloat (info, f1, f2) ->
let f1', store' = eval' ctx store f1 in
(TmPlusfloat (info, f1', f2), store')
| TmSucc (_, TmPred (_, term)) when isnumeric term -> (term, store)
| TmSucc (info, term) ->
let term', store' = eval' ctx store term in
(TmSucc (info, term'), store')
| TmPred (_, TmSucc (_, term)) when isnumeric term -> (term, store)
| TmPred (info, TmZero _) -> (TmZero info, store)
| TmPred (info, term) ->
let term', store' = eval' ctx store term in
(TmPred (info, term'), store')
| TmIsZero (info, TmZero _) -> (TmTrue info, store)
| TmIsZero (info, TmSucc (_, term)) when isnumeric term ->
(TmFalse info, store)
| TmIsZero (info, term) ->
let term', store' = eval' ctx store term in
(TmIsZero (info, term'), store')
| TmRef (info, value) when isval ctx value ->
let where, store' = extend_store store value in
(TmLoc (info, where), store')
| TmRef (info, value) ->
let value', store' = eval' ctx store value in
(TmRef (info, value'), store')
| TmDeref (_, TmLoc (_, where)) -> (lookup_store store where, store)
| TmDeref (info, term) ->
let term', store' = eval' ctx store term in
(TmDeref (info, term'), store')
| TmRefAssign (info, TmLoc (_, where), term) when isval ctx term ->
let store' = update_store store where term in
(TmUnit info, store')
One step at a time : first lower location , then the value .
| TmRefAssign (info, (TmLoc _ as refLoc), refVal) ->
let refVal', store' = eval' ctx store refVal in
(TmRefAssign (info, refLoc, refVal'), store')
| TmRefAssign (info, refLoc, refVal) ->
let refLoc', store' = eval' ctx store refLoc in
(TmRefAssign (info, refLoc', refVal), store')
| TmTyApp (_, TmTyAbs (_, _, body), tyConcrete) ->
(typeTermSubstTop tyConcrete body, store)
| TmTyApp (info, term, tyConcrete) ->
let term', store' = eval' ctx store term in
(TmTyApp (info, term', tyConcrete), store')
| TmUnpack (_, _, _, TmPack (_, tyConcrete, packTerm, _), inTerm)
when isval ctx packTerm ->
Substitute the packed value in for name used for the unpacked value .
Shift by 1 first to account for the fact that we are substituting in a
term that would still have the unpacked Type bound as well , which we
have n't substituted yet !
Shift by 1 first to account for the fact that we are substituting in a
term that would still have the unpacked Type bound as well, which we
haven't substituted yet! *)
let inTermWithPackedVal = termSubstTop (termShift 1 packTerm) inTerm in
(typeTermSubstTop tyConcrete inTermWithPackedVal, store)
| TmUnpack (info, n1, n2, t1, t2) ->
let t1', store' = eval' ctx store t1 in
(TmUnpack (info, n1, n2, t1', t2), store')
| TmPack (info, tyC, termC, tySome) ->
let termC', store' = eval' ctx store termC in
(TmPack (info, tyC, termC', tySome), store')
| _ -> raise NoRuleApplies
let rec eval ctx store t =
try
let t', store' = eval' ctx store t in
eval ctx store' t'
with NoRuleApplies -> (t, store)
let evalbinding ctx store binding =
match binding with
| TmAbbBinding (t, ty) ->
let term', store' = eval ctx store t in
(TmAbbBinding (term', ty), store')
| b -> (b, store)
|
870260c0bd58b77c81ae6e5870035a67638cda9422eb86eb92a5df2ccbe17ff2 | jimcrayne/jhc | case-alt-where.hs | module ShouldCompile where
foo x = case x of
y -> d where d = y
| null | https://raw.githubusercontent.com/jimcrayne/jhc/1ff035af3d697f9175f8761c8d08edbffde03b4e/regress/tests/1_typecheck/2_pass/fixed_bugs/case-alt-where.hs | haskell | module ShouldCompile where
foo x = case x of
y -> d where d = y
| |
2e21e6389c9fc60f4123cc071b225738e3e3da98c008cd81785718e2a2a51933 | jeapostrophe/mode-lambda | core.rkt | #lang racket/base
(require racket/match
racket/contract/base
racket/list
(except-in ffi/unsafe ->)
mode-lambda/util)
(define (ushort? x)
(and (exact-nonnegative-integer? x)
(<= 0 x 65535)))
(define PALETTE-DEPTH 16)
(struct compiled-sprite-db
(atlas-size atlas-bs spr->idx idx->w*h*tx*ty pal-size pal-bs pal->idx))
(define layer/c byte?)
(define-cstruct _layer-data
([cx _float]
[cy _float]
[hw _float]
[hh _float]
[mx _float]
[my _float]
[theta _float]
[mode7-coeff _float]
[horizon _float]
[fov _float]
[wrap-x? _bool]
[wrap-y? _bool]))
(module+ test
(printf "layer-data size: ~v bytes\n" (ctype-sizeof _layer-data)))
(define default-layer
(make-layer-data 0.0 0.0 0.0 0.0 1.0 1.0 0.0 0.0 0.0 1.0 #f #f))
Mode7 Docs :
;; -
;; - -the-gluperspective-matrix-and-other-opengl-matrix-maths/
;; - -to-convert-projected-points-to-screen-coordinatesviewport-matrix
;; - -advanced-lessons/perspective-and-orthographic-projection-matrix/perspective-projection-matrix/
;; -
;; - -an-snes-mode-7-affine-transform-effect-in-pygame
;; - -transforming-3d-to-2d
;; - -to-convert-a-3d-point-into-2d-perspective-projection
FOV should be a multiple of the aspect ratio to look good ,
;; when it is small, it is more zoomed.
( = 0.0 ) & FOV : 1.0 -- no mode7
( = 1.0 ) If Z increases towards top of screen , then it
;; is a ceiling and Hor-Y is Positive and when negative, Z
;; should be +inf.0
;; (coeff = 2.0) If Z increases towards bot of screen, then it
;; is a floor and Hor-Y is Negative and when positive, Z
;; should be +inf.0
( = 3.0 ) If Z increases away from horizon , then it is
;; a cylinder and we want the absolute value of the distance
(define-cstruct&list
_sprite-data _sprite-data:info
([dx _float] ;; 0 0
1 4
2 8
3 12
4 16
5 20
6 24
7 26
8 28
9 29
10 30
11 31
))
(module+ test
(printf "sprite-data size: ~v bytes\n" (ctype-sizeof _sprite-data)))
(define layer-vector/c
(vectorof (or/c false/c layer-data?)))
(define-syntax-rule (backend/c (addl-input ...) output)
(->* (layer-vector/c tree/c tree/c addl-input ...)
(#:r byte? #:g byte? #:b byte?) output))
(define draw!/c
(backend/c () void?))
(define render/c
(backend/c () bytes?))
(define (stage-backend/c output/c)
(-> compiled-sprite-db?
exact-nonnegative-integer?
exact-nonnegative-integer?
byte?
output/c))
(provide
(all-defined-out))
| null | https://raw.githubusercontent.com/jeapostrophe/mode-lambda/64b5ae81f457ded7664458cd9935ce7d3ebfc449/mode-lambda/core.rkt | racket | -
- -the-gluperspective-matrix-and-other-opengl-matrix-maths/
- -to-convert-projected-points-to-screen-coordinatesviewport-matrix
- -advanced-lessons/perspective-and-orthographic-projection-matrix/perspective-projection-matrix/
-
- -an-snes-mode-7-affine-transform-effect-in-pygame
- -transforming-3d-to-2d
- -to-convert-a-3d-point-into-2d-perspective-projection
when it is small, it is more zoomed.
is a ceiling and Hor-Y is Positive and when negative, Z
should be +inf.0
(coeff = 2.0) If Z increases towards bot of screen, then it
is a floor and Hor-Y is Negative and when positive, Z
should be +inf.0
a cylinder and we want the absolute value of the distance
0 0 | #lang racket/base
(require racket/match
racket/contract/base
racket/list
(except-in ffi/unsafe ->)
mode-lambda/util)
(define (ushort? x)
(and (exact-nonnegative-integer? x)
(<= 0 x 65535)))
(define PALETTE-DEPTH 16)
(struct compiled-sprite-db
(atlas-size atlas-bs spr->idx idx->w*h*tx*ty pal-size pal-bs pal->idx))
(define layer/c byte?)
(define-cstruct _layer-data
([cx _float]
[cy _float]
[hw _float]
[hh _float]
[mx _float]
[my _float]
[theta _float]
[mode7-coeff _float]
[horizon _float]
[fov _float]
[wrap-x? _bool]
[wrap-y? _bool]))
(module+ test
(printf "layer-data size: ~v bytes\n" (ctype-sizeof _layer-data)))
(define default-layer
(make-layer-data 0.0 0.0 0.0 0.0 1.0 1.0 0.0 0.0 0.0 1.0 #f #f))
Mode7 Docs :
FOV should be a multiple of the aspect ratio to look good ,
( = 0.0 ) & FOV : 1.0 -- no mode7
( = 1.0 ) If Z increases towards top of screen , then it
( = 3.0 ) If Z increases away from horizon , then it is
(define-cstruct&list
_sprite-data _sprite-data:info
1 4
2 8
3 12
4 16
5 20
6 24
7 26
8 28
9 29
10 30
11 31
))
(module+ test
(printf "sprite-data size: ~v bytes\n" (ctype-sizeof _sprite-data)))
(define layer-vector/c
(vectorof (or/c false/c layer-data?)))
(define-syntax-rule (backend/c (addl-input ...) output)
(->* (layer-vector/c tree/c tree/c addl-input ...)
(#:r byte? #:g byte? #:b byte?) output))
(define draw!/c
(backend/c () void?))
(define render/c
(backend/c () bytes?))
(define (stage-backend/c output/c)
(-> compiled-sprite-db?
exact-nonnegative-integer?
exact-nonnegative-integer?
byte?
output/c))
(provide
(all-defined-out))
|
81a331fc25fac72f926072e47cae27e0f72b0c82f0b4a34281cc0f9336e3c846 | gibiansky/jupyter-haskell | Install.hs | |
Module : Jupyter . Test . Install
Description : Tests for the Jupyter . Install module .
Copyright : ( c ) , 2016
License : MIT
Maintainer :
Stability : stable
Portability : POSIX
Module : Jupyter.Test.Install
Description : Tests for the Jupyter.Install module.
Copyright : (c) Andrew Gibiansky, 2016
License : MIT
Maintainer :
Stability : stable
Portability : POSIX
-}
# LANGUAGE ScopedTypeVariables #
{-# LANGUAGE OverloadedStrings #-}
module Jupyter.Test.Install (installTests) where
-- Imports from 'base'
import Control.Monad (forM_)
import Data.List (isInfixOf)
import Data.Maybe (fromMaybe)
import Data.Proxy (Proxy(..))
import System.Environment (setEnv, lookupEnv)
import System.IO (stderr, stdout)
-- Imports from 'directory'
import System.Directory (setPermissions, getPermissions, Permissions(..), canonicalizePath,
createDirectoryIfMissing, removeFile, doesFileExist)
-- Imports from 'bytestring'
import qualified Data.ByteString.Char8 as CBS
-- Imports from 'aeson'
import Data.Aeson (decodeStrict, Value)
-- Imports from 'text'
import qualified Data.Text as T
-- Imports from 'extra'
import Control.Exception.Extra (bracket)
import System.IO.Extra (withTempDir)
-- Imports from 'silently'
import System.IO.Silently (hCapture_)
-- Imports from 'tasty'
import Test.Tasty (TestTree, testGroup)
Imports from ' tasty - hunit '
import Test.Tasty.HUnit (testCase, (@=?), assertFailure, assertBool)
-- Imports from 'jupyter'
import Jupyter.Install.Internal
import Jupyter.Test.Utils (shouldThrow, inTempDir)
import qualified Jupyter.Install.Internal as I
installTests :: TestTree
installTests = testGroup "Install Tests"
[ testVersionNumberParsing
, testVersionNumberPrinting
, testFindingJupyterExecutable
, testJupyterVersionReading
, testStderrIsUntouched
, testCorrectJupyterVersionsAccepted
, testKernelspecFilesCreated
, testEndToEndInstall
]
-- | Test that version numbers from jupyter --version are properly parsed.
testVersionNumberParsing :: TestTree
testVersionNumberParsing = testCase "Version number parsing" $ do
Just (I.JupyterVersion 10 1 0) @=? I.parseVersion "10.1.0"
Just (I.JupyterVersion 4 1 2000) @=? I.parseVersion "4.1.2000"
Just (I.JupyterVersion 4 1 0) @=? I.parseVersion "4.1"
Just (I.JupyterVersion 4 0 0) @=? I.parseVersion "4"
Nothing @=? I.parseVersion ".xx.4"
Nothing @=? I.parseVersion "4.1.2.1.2"
-- | Test that version numbers from jupyter --version are properly printed to the user.
testVersionNumberPrinting :: TestTree
testVersionNumberPrinting = testCase "Version number printing" $ do
parseThenShow "10.1.0"
parseThenShow "4.1.200"
parseThenShow "4.1.0"
where
parseThenShow str =
Just str @=? (I.showVersion <$> I.parseVersion str)
-- | Set the PATH variable to a particular value during execution of an IO action.
withPath :: String -> IO a -> IO a
withPath newPath action =
bracket resetPath (setEnv "PATH") (const action)
where
resetPath = do
path <- lookupEnv "PATH"
setEnv "PATH" newPath
return $ fromMaybe "" path
-- | Test that `jupyter` is found by `which` if it is on the PATH, and isn't found if its not on the
-- path or isn't executable. Ensures that all returned paths are absolute and canonical.
testFindingJupyterExecutable :: TestTree
testFindingJupyterExecutable = testCase "PATH searching" $
-- Run the entire test in a temporary directory.
inTempDir $ \tmp ->
-- Set up a PATH that has both relative and absolute paths.
withPath (".:test-path/twice:" ++ tmp ++ "/test-path-2") $
-- For each possible location test executable finding.
forM_ [".", "test-path/twice", "test-path-2"] $ \prefix -> do
let path = prefix ++ "/jupyter"
createDirectoryIfMissing True prefix
-- When the file doesn't exist it should not be found.
which "jupyter" `shouldThrow` (Proxy :: Proxy JupyterKernelspecException)
-- When the file is not executable it should not be found.
writeFile path "#!/bin/bash\ntrue"
which "jupyter" `shouldThrow` (Proxy :: Proxy JupyterKernelspecException)
-- When the file is executable, it should be found, and be an absolute path
-- that ultimately resolves to what we expect.
setExecutable path
jupyterLoc <- which "jupyter"
expectedLoc <- canonicalizePath $ tmp ++ "/" ++ prefix ++ "/jupyter"
expectedLoc @=? jupyterLoc
-- Clean up to avoid messing with future tests.
removeFile path
| Test that the install script can parse the version numbers output by .
testJupyterVersionReading :: TestTree
testJupyterVersionReading = testCase "jupyter --version parsing" $
inTempDir $ \_ ->
-- Set up a jupyter executable that outputs what we expect.
withPath "." $ do
writeMockJupyter ""
setExecutable "jupyter"
path <- which "jupyter"
-- Version too low.
writeMockJupyter "1.2.0"
verifyJupyterCommand path `shouldThrow` (Proxy :: Proxy JupyterKernelspecException)
-- Could not parse output.
writeMockJupyter "..."
verifyJupyterCommand path `shouldThrow` (Proxy :: Proxy JupyterKernelspecException)
writeMockJupyter "asdf"
verifyJupyterCommand path `shouldThrow` (Proxy :: Proxy JupyterKernelspecException)
-- Works.
writeMockJupyter "3.0.0"
verifyJupyterCommand path
writeMockJupyter "4.1.4000"
verifyJupyterCommand path
-- | Create a mock 'jupyter' command, which always outputs a particular string to stdout and exits
with exit code zero .
writeMockJupyter :: String -> IO ()
writeMockJupyter out = writeMockJupyter' out "" 0
-- | Create a mock 'jupyter' command, which outputs given strings to stdout and stderr and exits
-- with the provided exit code.
writeMockJupyter' :: String -- ^ What to output on stdout
-> String -- ^ What to output on stderr
-> Int -- ^ What exit code to exit with
-> IO ()
writeMockJupyter' stdoutOut stderrOut errCode =
writeFile "jupyter" $
unlines
[ "#!/bin/bash"
, "echo -n \"" ++ stdoutOut ++ "\""
, "echo -n \"" ++ stderrOut ++ "\" >/dev/stderr"
, "exit " ++ show errCode
]
testStderrIsUntouched :: TestTree
testStderrIsUntouched = testCase "stderr is piped through" $
inTempDir $ \_ ->
-- Set up a jupyter executable that outputs something to stderr.
withPath "." $ do
let msg = "An error"
writeMockJupyter' "Some output" msg 0
setExecutable "jupyter"
-- Check that stderr goes through as usual.
stderrOut <- hCapture_ [stderr] (runJupyterCommand "jupyter" [])
msg @=? stderrOut
-- Check that stdout of the command is not output but is captured.
writeMockJupyter' "stdout" "" 0
stdoutOut <- hCapture_ [stdout] (runJupyterCommand "jupyter" [])
"" @=? stdoutOut
testCorrectJupyterVersionsAccepted :: TestTree
testCorrectJupyterVersionsAccepted = testCase "Correct jupyter versions accepted" $ do
assertBool "Version 3 supported" $ jupyterVersionSupported $ JupyterVersion 3 0 0
assertBool "Version 3.1 supported" $ jupyterVersionSupported $ JupyterVersion 3 1 0
assertBool "Version 4 supported" $ jupyterVersionSupported $ JupyterVersion 4 0 0
assertBool "Version 10 supported" $ jupyterVersionSupported $ JupyterVersion 10 0 0
assertBool "Version 2.3 not supported" $ not $ jupyterVersionSupported $ JupyterVersion 2 3 0
assertBool "Version 1.0 not supported" $ not $ jupyterVersionSupported $ JupyterVersion 1 0 0
testKernelspecFilesCreated :: TestTree
testKernelspecFilesCreated = testCase "kernelspec files created" $
inTempDir $ \tmp -> do
kernelspec <- createTestKernelspec tmp
-- Test that all required files are created
withTempDir $ \kernelspecDir -> do
prepareKernelspecDirectory kernelspec kernelspecDir
assertBool "kernel.js not copied" =<< doesFileExist (kernelspecDir ++ "/kernel.js")
assertBool "logo-64x64.png not copied" =<< doesFileExist (kernelspecDir ++ "/logo-64x64.png")
assertBool "kernel.json not created" =<< doesFileExist (kernelspecDir ++ "/kernel.json")
-- Test that the file is valid JSON and {connection_file} is present.
withTempDir $ \kernelspecDir -> do
prepareKernelspecDirectory kernelspec kernelspecDir
kernelJson <- readFile (kernelspecDir ++ "/kernel.json")
assertBool "{connection_file} not found" $ "\"{connection_file}\"" `isInfixOf` kernelJson
case decodeStrict (CBS.pack kernelJson) :: Maybe Value of
Nothing -> assertFailure "Could not decode kernel.json file as JSON"
Just _ -> return ()
-- Test that all previously-existing files are gone
withTempDir $ \kernelspecDir -> do
let prevFile1 = kernelspecDir ++ "/tmp.file"
prevFile2 = kernelspecDir ++ "/kernel.js"
writeFile prevFile1 "test1"
writeFile prevFile2 "test2"
prepareKernelspecDirectory kernelspec { kernelspecJsFile = Nothing } kernelspecDir
assertBool "previous file still exists" =<< fmap not (doesFileExist prevFile1)
assertBool "previous kernel.js file still exists" =<< fmap not (doesFileExist prevFile2)
Test that end - to - end installs work as expected , and call the ' jupyter kernelspec install '
-- in the way that they are expected to.
testEndToEndInstall :: TestTree
testEndToEndInstall = testCase "installs end-to-end" $
inTempDir $ \tmp -> do
kernelspec <- createTestKernelspec tmp
withPath "." $ do
writeFile "jupyter" $ jupyterScript True
setExecutable "jupyter"
result1 <- installKernel InstallLocal kernelspec
case result1 of
InstallFailed msg -> assertFailure $ "Failed to install kernelspec: " ++ T.unpack msg
_ -> return ()
writeFile "jupyter" $ jupyterScript False
result2 <- installKernel InstallGlobal kernelspec
case result2 of
InstallFailed msg -> assertFailure $ "Failed to install kernelspec: " ++ T.unpack msg
_ -> return ()
where
jupyterScript user =
unlines
[ "#!/bin/bash"
, "if [[ $1 == \"--version\" ]]; then"
, "echo 4.1.0"
, "else"
, "[[ \"$1 $2 $4\" == \"kernelspec install --replace\" ]] || exit 1"
, if user
then "[[ \"$5\" == \"--user\" ]] || exit 0"
else ""
, "fi"
]
-- Create a kernelspec that refers to newly generated files in the provided directory.
createTestKernelspec :: String -> IO Kernelspec
createTestKernelspec tmp = do
let kernelJsFile = tmp ++ "/" ++ "kernel.js"
writeFile kernelJsFile "kernel.js"
let kernelLogoFile = tmp ++ "/" ++ "logo-64x64.png"
writeFile kernelLogoFile "logo-64x64.png"
return
Kernelspec
{ kernelspecDisplayName = "Test"
, kernelspecLanguage = "test"
, kernelspecCommand = \exe conn -> [exe, conn, "--test"]
, kernelspecJsFile = Just kernelJsFile
, kernelspecLogoFile = Just kernelLogoFile
, kernelspecEnv = mempty
}
-- | Make a file executable.
setExecutable :: FilePath -> IO ()
setExecutable path = do
perms <- getPermissions path
setPermissions path perms { executable = True }
| null | https://raw.githubusercontent.com/gibiansky/jupyter-haskell/711502f4e91b9866353c71077a069df7d66f98b3/tests/Jupyter/Test/Install.hs | haskell | # LANGUAGE OverloadedStrings #
Imports from 'base'
Imports from 'directory'
Imports from 'bytestring'
Imports from 'aeson'
Imports from 'text'
Imports from 'extra'
Imports from 'silently'
Imports from 'tasty'
Imports from 'jupyter'
| Test that version numbers from jupyter --version are properly parsed.
| Test that version numbers from jupyter --version are properly printed to the user.
| Set the PATH variable to a particular value during execution of an IO action.
| Test that `jupyter` is found by `which` if it is on the PATH, and isn't found if its not on the
path or isn't executable. Ensures that all returned paths are absolute and canonical.
Run the entire test in a temporary directory.
Set up a PATH that has both relative and absolute paths.
For each possible location test executable finding.
When the file doesn't exist it should not be found.
When the file is not executable it should not be found.
When the file is executable, it should be found, and be an absolute path
that ultimately resolves to what we expect.
Clean up to avoid messing with future tests.
Set up a jupyter executable that outputs what we expect.
Version too low.
Could not parse output.
Works.
| Create a mock 'jupyter' command, which always outputs a particular string to stdout and exits
| Create a mock 'jupyter' command, which outputs given strings to stdout and stderr and exits
with the provided exit code.
^ What to output on stdout
^ What to output on stderr
^ What exit code to exit with
Set up a jupyter executable that outputs something to stderr.
Check that stderr goes through as usual.
Check that stdout of the command is not output but is captured.
Test that all required files are created
Test that the file is valid JSON and {connection_file} is present.
Test that all previously-existing files are gone
in the way that they are expected to.
version\" ]]; then"
replace\" ]] || exit 1"
user\" ]] || exit 0"
Create a kernelspec that refers to newly generated files in the provided directory.
| Make a file executable. | |
Module : Jupyter . Test . Install
Description : Tests for the Jupyter . Install module .
Copyright : ( c ) , 2016
License : MIT
Maintainer :
Stability : stable
Portability : POSIX
Module : Jupyter.Test.Install
Description : Tests for the Jupyter.Install module.
Copyright : (c) Andrew Gibiansky, 2016
License : MIT
Maintainer :
Stability : stable
Portability : POSIX
-}
# LANGUAGE ScopedTypeVariables #
module Jupyter.Test.Install (installTests) where
import Control.Monad (forM_)
import Data.List (isInfixOf)
import Data.Maybe (fromMaybe)
import Data.Proxy (Proxy(..))
import System.Environment (setEnv, lookupEnv)
import System.IO (stderr, stdout)
import System.Directory (setPermissions, getPermissions, Permissions(..), canonicalizePath,
createDirectoryIfMissing, removeFile, doesFileExist)
import qualified Data.ByteString.Char8 as CBS
import Data.Aeson (decodeStrict, Value)
import qualified Data.Text as T
import Control.Exception.Extra (bracket)
import System.IO.Extra (withTempDir)
import System.IO.Silently (hCapture_)
import Test.Tasty (TestTree, testGroup)
Imports from ' tasty - hunit '
import Test.Tasty.HUnit (testCase, (@=?), assertFailure, assertBool)
import Jupyter.Install.Internal
import Jupyter.Test.Utils (shouldThrow, inTempDir)
import qualified Jupyter.Install.Internal as I
installTests :: TestTree
installTests = testGroup "Install Tests"
[ testVersionNumberParsing
, testVersionNumberPrinting
, testFindingJupyterExecutable
, testJupyterVersionReading
, testStderrIsUntouched
, testCorrectJupyterVersionsAccepted
, testKernelspecFilesCreated
, testEndToEndInstall
]
testVersionNumberParsing :: TestTree
testVersionNumberParsing = testCase "Version number parsing" $ do
Just (I.JupyterVersion 10 1 0) @=? I.parseVersion "10.1.0"
Just (I.JupyterVersion 4 1 2000) @=? I.parseVersion "4.1.2000"
Just (I.JupyterVersion 4 1 0) @=? I.parseVersion "4.1"
Just (I.JupyterVersion 4 0 0) @=? I.parseVersion "4"
Nothing @=? I.parseVersion ".xx.4"
Nothing @=? I.parseVersion "4.1.2.1.2"
testVersionNumberPrinting :: TestTree
testVersionNumberPrinting = testCase "Version number printing" $ do
parseThenShow "10.1.0"
parseThenShow "4.1.200"
parseThenShow "4.1.0"
where
parseThenShow str =
Just str @=? (I.showVersion <$> I.parseVersion str)
withPath :: String -> IO a -> IO a
withPath newPath action =
bracket resetPath (setEnv "PATH") (const action)
where
resetPath = do
path <- lookupEnv "PATH"
setEnv "PATH" newPath
return $ fromMaybe "" path
testFindingJupyterExecutable :: TestTree
testFindingJupyterExecutable = testCase "PATH searching" $
inTempDir $ \tmp ->
withPath (".:test-path/twice:" ++ tmp ++ "/test-path-2") $
forM_ [".", "test-path/twice", "test-path-2"] $ \prefix -> do
let path = prefix ++ "/jupyter"
createDirectoryIfMissing True prefix
which "jupyter" `shouldThrow` (Proxy :: Proxy JupyterKernelspecException)
writeFile path "#!/bin/bash\ntrue"
which "jupyter" `shouldThrow` (Proxy :: Proxy JupyterKernelspecException)
setExecutable path
jupyterLoc <- which "jupyter"
expectedLoc <- canonicalizePath $ tmp ++ "/" ++ prefix ++ "/jupyter"
expectedLoc @=? jupyterLoc
removeFile path
| Test that the install script can parse the version numbers output by .
testJupyterVersionReading :: TestTree
testJupyterVersionReading = testCase "jupyter --version parsing" $
inTempDir $ \_ ->
withPath "." $ do
writeMockJupyter ""
setExecutable "jupyter"
path <- which "jupyter"
writeMockJupyter "1.2.0"
verifyJupyterCommand path `shouldThrow` (Proxy :: Proxy JupyterKernelspecException)
writeMockJupyter "..."
verifyJupyterCommand path `shouldThrow` (Proxy :: Proxy JupyterKernelspecException)
writeMockJupyter "asdf"
verifyJupyterCommand path `shouldThrow` (Proxy :: Proxy JupyterKernelspecException)
writeMockJupyter "3.0.0"
verifyJupyterCommand path
writeMockJupyter "4.1.4000"
verifyJupyterCommand path
with exit code zero .
writeMockJupyter :: String -> IO ()
writeMockJupyter out = writeMockJupyter' out "" 0
-> IO ()
writeMockJupyter' stdoutOut stderrOut errCode =
writeFile "jupyter" $
unlines
[ "#!/bin/bash"
, "echo -n \"" ++ stdoutOut ++ "\""
, "echo -n \"" ++ stderrOut ++ "\" >/dev/stderr"
, "exit " ++ show errCode
]
testStderrIsUntouched :: TestTree
testStderrIsUntouched = testCase "stderr is piped through" $
inTempDir $ \_ ->
withPath "." $ do
let msg = "An error"
writeMockJupyter' "Some output" msg 0
setExecutable "jupyter"
stderrOut <- hCapture_ [stderr] (runJupyterCommand "jupyter" [])
msg @=? stderrOut
writeMockJupyter' "stdout" "" 0
stdoutOut <- hCapture_ [stdout] (runJupyterCommand "jupyter" [])
"" @=? stdoutOut
testCorrectJupyterVersionsAccepted :: TestTree
testCorrectJupyterVersionsAccepted = testCase "Correct jupyter versions accepted" $ do
assertBool "Version 3 supported" $ jupyterVersionSupported $ JupyterVersion 3 0 0
assertBool "Version 3.1 supported" $ jupyterVersionSupported $ JupyterVersion 3 1 0
assertBool "Version 4 supported" $ jupyterVersionSupported $ JupyterVersion 4 0 0
assertBool "Version 10 supported" $ jupyterVersionSupported $ JupyterVersion 10 0 0
assertBool "Version 2.3 not supported" $ not $ jupyterVersionSupported $ JupyterVersion 2 3 0
assertBool "Version 1.0 not supported" $ not $ jupyterVersionSupported $ JupyterVersion 1 0 0
testKernelspecFilesCreated :: TestTree
testKernelspecFilesCreated = testCase "kernelspec files created" $
inTempDir $ \tmp -> do
kernelspec <- createTestKernelspec tmp
withTempDir $ \kernelspecDir -> do
prepareKernelspecDirectory kernelspec kernelspecDir
assertBool "kernel.js not copied" =<< doesFileExist (kernelspecDir ++ "/kernel.js")
assertBool "logo-64x64.png not copied" =<< doesFileExist (kernelspecDir ++ "/logo-64x64.png")
assertBool "kernel.json not created" =<< doesFileExist (kernelspecDir ++ "/kernel.json")
withTempDir $ \kernelspecDir -> do
prepareKernelspecDirectory kernelspec kernelspecDir
kernelJson <- readFile (kernelspecDir ++ "/kernel.json")
assertBool "{connection_file} not found" $ "\"{connection_file}\"" `isInfixOf` kernelJson
case decodeStrict (CBS.pack kernelJson) :: Maybe Value of
Nothing -> assertFailure "Could not decode kernel.json file as JSON"
Just _ -> return ()
withTempDir $ \kernelspecDir -> do
let prevFile1 = kernelspecDir ++ "/tmp.file"
prevFile2 = kernelspecDir ++ "/kernel.js"
writeFile prevFile1 "test1"
writeFile prevFile2 "test2"
prepareKernelspecDirectory kernelspec { kernelspecJsFile = Nothing } kernelspecDir
assertBool "previous file still exists" =<< fmap not (doesFileExist prevFile1)
assertBool "previous kernel.js file still exists" =<< fmap not (doesFileExist prevFile2)
Test that end - to - end installs work as expected , and call the ' jupyter kernelspec install '
testEndToEndInstall :: TestTree
testEndToEndInstall = testCase "installs end-to-end" $
inTempDir $ \tmp -> do
kernelspec <- createTestKernelspec tmp
withPath "." $ do
writeFile "jupyter" $ jupyterScript True
setExecutable "jupyter"
result1 <- installKernel InstallLocal kernelspec
case result1 of
InstallFailed msg -> assertFailure $ "Failed to install kernelspec: " ++ T.unpack msg
_ -> return ()
writeFile "jupyter" $ jupyterScript False
result2 <- installKernel InstallGlobal kernelspec
case result2 of
InstallFailed msg -> assertFailure $ "Failed to install kernelspec: " ++ T.unpack msg
_ -> return ()
where
jupyterScript user =
unlines
[ "#!/bin/bash"
, "echo 4.1.0"
, "else"
, if user
else ""
, "fi"
]
createTestKernelspec :: String -> IO Kernelspec
createTestKernelspec tmp = do
let kernelJsFile = tmp ++ "/" ++ "kernel.js"
writeFile kernelJsFile "kernel.js"
let kernelLogoFile = tmp ++ "/" ++ "logo-64x64.png"
writeFile kernelLogoFile "logo-64x64.png"
return
Kernelspec
{ kernelspecDisplayName = "Test"
, kernelspecLanguage = "test"
, kernelspecCommand = \exe conn -> [exe, conn, "--test"]
, kernelspecJsFile = Just kernelJsFile
, kernelspecLogoFile = Just kernelLogoFile
, kernelspecEnv = mempty
}
setExecutable :: FilePath -> IO ()
setExecutable path = do
perms <- getPermissions path
setPermissions path perms { executable = True }
|
567700fd66882a24f1364997134b5c92d79e932ae4973aa5d00fecea9612e2f7 | fdopen/ppx_cstubs | extract_c.mli | This file is part of ppx_cstubs ( )
* Copyright ( c ) 2018 - 2019 fdopen
*
* This program is free software ; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation , with linking exception ;
* either version 2.1 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 Lesser General Public License for more details .
*
* You should have received a copy of the GNU Lesser 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 .
* Copyright (c) 2018-2019 fdopen
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, with linking exception;
* either version 2.1 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser 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.
*)
type extract_info
val prologue : string
type extract_int =
[ `Unchecked_U8
| `Unchecked_U32
| `Any_int
| `Int_type of string
]
val prepare_extract_int :
loc:Mparsetree.Ast_cur.Ast_helper.loc ->
extract_int ->
string ->
extract_info * string * string
val prepare_extract_string :
loc:Mparsetree.Ast_cur.Ast_helper.loc ->
string ->
extract_info * string * string
type obj
val compile : ebuf:Buffer.t -> string -> (obj, string) CCResult.t
type extract_error =
| Info_not_found
| Overflow of string
| Underflow of string
| Not_an_integer
val extract : extract_info -> obj -> (string, extract_error) CCResult.t
| null | https://raw.githubusercontent.com/fdopen/ppx_cstubs/5d5ce9b7cf45d87bb71c046a76d30c17ec6075e5/src/internal/extract_c.mli | ocaml | This file is part of ppx_cstubs ( )
* Copyright ( c ) 2018 - 2019 fdopen
*
* This program is free software ; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation , with linking exception ;
* either version 2.1 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 Lesser General Public License for more details .
*
* You should have received a copy of the GNU Lesser 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 .
* Copyright (c) 2018-2019 fdopen
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, with linking exception;
* either version 2.1 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser 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.
*)
type extract_info
val prologue : string
type extract_int =
[ `Unchecked_U8
| `Unchecked_U32
| `Any_int
| `Int_type of string
]
val prepare_extract_int :
loc:Mparsetree.Ast_cur.Ast_helper.loc ->
extract_int ->
string ->
extract_info * string * string
val prepare_extract_string :
loc:Mparsetree.Ast_cur.Ast_helper.loc ->
string ->
extract_info * string * string
type obj
val compile : ebuf:Buffer.t -> string -> (obj, string) CCResult.t
type extract_error =
| Info_not_found
| Overflow of string
| Underflow of string
| Not_an_integer
val extract : extract_info -> obj -> (string, extract_error) CCResult.t
| |
3b025bb45ffcaa1956ddc5df8048af11590692ffdc592b3e9b5cc5bc9a62255d | vyzo/gerbil | gx-init-static-exe.scm | -*- -*-
( C ) vyzo at hackzen.org
static executable module stub
(##namespace (""))
(declare
(block)
(standard-bindings)
(extended-bindings))
(define (__gx#display-exception e port)
(cond
((method-ref e 'display-exception)
=> (lambda (f) (f e port)))
(else
(##default-display-exception e port))))
(set! ##display-exception-hook __gx#display-exception)
| null | https://raw.githubusercontent.com/vyzo/gerbil/17fbcb95a8302c0de3f88380be1a3eb6fe891b95/src/gerbil/boot/gx-init-static-exe.scm | scheme | -*- -*-
( C ) vyzo at hackzen.org
static executable module stub
(##namespace (""))
(declare
(block)
(standard-bindings)
(extended-bindings))
(define (__gx#display-exception e port)
(cond
((method-ref e 'display-exception)
=> (lambda (f) (f e port)))
(else
(##default-display-exception e port))))
(set! ##display-exception-hook __gx#display-exception)
| |
c68919926f07ce3f990d308837aeccda3b5a35a1ba1973dd90ec48aee193793f | chumsley/jwacs | lex-javascript.lisp | ;;;; lex-javascript.lisp
;;;
Contains the definition of the Javascript lexer used by the parser ,
;;; as well as some lookup structures for dealing with tokens.
;;; Unit tests are in tests/test-lexer.lisp.
;;;
Copyright ( c ) 2005
;;; See LICENSE for full licensing details.
;;;
(in-package :jwacs)
;;;; Token definitions
(defmacro deftoken (symbol &optional key token-type)
"Add a token's symbol and possibly string to the appropriate lookups.
Different actions will be taken depending upon the TOKEN-TYPE:
OPERATOR-TOKENs are infix operators, which are recognized as atomic
tokens regardless of whether they are surrounded by whitespace (unlike
identifier tokens, for example).
KEYWORDs are reserved strings that can never be used as an identifier.
OPERATIONs will never be returned by the lexer, but they are used in the
source model in the same place as tokens (ie, in :op-symbol slots), so
they are treated as tokens for now."
(cond
((eq token-type :operator-token)
`(progn
(setf (gethash ,key *tokens-to-symbols*) ,symbol)
(setf (gethash ,symbol *symbols-to-tokens*) ,key)
(push ,key *operator-tokens*)))
((eq token-type :operation)
`(setf (gethash ,symbol *symbols-to-tokens*) ,key))
((eq token-type :keyword)
`(progn
(setf (gethash ,key *tokens-to-symbols*) ,symbol)
(push ,symbol *keyword-symbols*)))
(key
`(setf (gethash ,key *tokens-to-symbols*) ,symbol))
(t
`(setf (gethash ,symbol *tokens-to-symbols*) ,symbol))))
;;;; Token lookups
(defparameter *tokens-to-symbols* (make-hash-table :test 'equal)
"Map from string to token symbol.
Every symbol that the tokenizer will return is in this map.")
(defparameter *symbols-to-tokens* (make-hash-table :test 'eq)
"Map from token symbol to token string. This contains an entry for every token
in *tokens-to-symbols*, plus additional entries for the 'operation' symbols.")
(defparameter *operator-tokens* nil
"These are operators (as distinct from general tokens) that will be built into
a special regular expression.
We can't just use the keys from *symbols-to-tokens*, because the
order that the tokens appear in this list is significant.
Specifically, each 'long' operator must occur before any operator that
it is a supersequence of. Eg, '<<<' must occur before '<<', which
must occur before '<'. '!=' must occur before both '!' and '='.")
(defparameter *keyword-symbols* nil
"A list of the keyword symbols.")
(defparameter *restricted-tokens* (make-hash-table :test 'eq)
"Tokens that participate in 'restricted productions'. Value should be either
:PRE or :POST. For each of these tokens, the lexer will emit either a
:NO-LINE-TERMINATOR or a :LINE-TERMINATOR token depending upon whether the token
was preceded/followed by a line-break.")
(setf (gethash :plus2 *restricted-tokens*) :pre)
(setf (gethash :minus2 *restricted-tokens*) :pre)
(setf (gethash :break *restricted-tokens*) :post)
(setf (gethash :continue *restricted-tokens*) :post)
(setf (gethash :return *restricted-tokens*) :post)
(setf (gethash :throw *restricted-tokens*) :post)
;; Compound assignment operators
(deftoken :times-equals "*=" :operator-token)
(deftoken :divide-equals "/=" :operator-token)
(deftoken :mod-equals "%=" :operator-token)
(deftoken :plus-equals "+=" :operator-token)
(deftoken :minus-equals "-=" :operator-token)
(deftoken :lshift-equals "<<=" :operator-token)
(deftoken :rshift-equals ">>=" :operator-token)
(deftoken :urshift-equals ">>>=" :operator-token)
(deftoken :and-equals "&=" :operator-token)
(deftoken :xor-equals "^=" :operator-token)
(deftoken :or-equals "|=" :operator-token)
Operators and punctuators
(deftoken :semicolon ";" :operator-token)
(deftoken :comma "," :operator-token)
(deftoken :hook "?" :operator-token)
(deftoken :colon ":" :operator-token)
(deftoken :conditional)
(deftoken :bar2 "||" :operator-token)
(deftoken :ampersand2 "&&" :operator-token)
(deftoken :bar "|" :operator-token)
(deftoken :caret "^" :operator-token)
(deftoken :ampersand "&" :operator-token)
(deftoken :equals3 "===" :operator-token)
(deftoken :not-equals2 "!==" :operator-token)
(deftoken :equals2 "==" :operator-token)
(deftoken :equals "=" :operator-token)
(deftoken :not-equals "!=" :operator-token)
(deftoken :left-arrow "<-" :operator-token)
(deftoken :right-arrow "->" :operator-token)
(deftoken :less-than-equals "<=" :operator-token)
(deftoken :greater-than-equals ">=" :operator-token)
(deftoken :urshift ">>>" :operator-token)
(deftoken :lshift "<<" :operator-token)
(deftoken :rshift ">>" :operator-token)
(deftoken :less-than "<" :operator-token)
(deftoken :greater-than ">" :operator-token)
(deftoken :asterisk "*" :operator-token)
(deftoken :slash "/" :operator-token)
(deftoken :percent "%" :operator-token)
(deftoken :bang "!" :operator-token)
(deftoken :tilde "~" :operator-token)
(deftoken :plus2 "++" :operator-token)
(deftoken :minus2 "--" :operator-token)
(deftoken :plus "+" :operator-token)
(deftoken :minus "-" :operator-token)
(deftoken :dot "." :operator-token)
(deftoken :left-bracket "[" :operator-token)
(deftoken :right-bracket "]" :operator-token)
(deftoken :left-curly "{" :operator-token)
(deftoken :right-curly "}" :operator-token)
(deftoken :left-paren "(" :operator-token)
(deftoken :right-paren ")" :operator-token)
;; These represent operations (addition, etc.) rather than just text tokens.
;; The lexer will never output them, so possibly the whole *symbols-to-tokens*
;; setup wants to be in js-source-model instead of here.
(deftoken :assign "=" :operation)
(deftoken :unary-plus "+" :operation)
(deftoken :unary-minus "-" :operation)
(deftoken :pre-decr "--" :operation)
(deftoken :pre-incr "++" :operation)
(deftoken :post-decr "--" :operation)
(deftoken :post-incr "++" :operation)
(deftoken :logical-and "&&" :operation)
(deftoken :logical-or "||" :operation)
(deftoken :logical-not "!" :operation)
(deftoken :bitwise-and "&" :operation)
(deftoken :bitwise-or "|" :operation)
(deftoken :bitwise-not "~" :operation)
(deftoken :bitwise-xor "^" :operation)
(deftoken :equals "==" :operation)
(deftoken :strict-equals "===" :operation)
(deftoken :strict-not-equals "!==" :operation)
(deftoken :add "+" :operation)
(deftoken :subtract "-" :operation)
(deftoken :multiply "*" :operation)
(deftoken :divide "/" :operation)
(deftoken :modulo "%" :operation)
;; Keywords
(deftoken :break "break" :keyword)
(deftoken :case "case" :keyword)
(deftoken :catch "catch" :keyword)
(deftoken :const "const" :keyword) ;???
(deftoken :continue "continue" :keyword)
(deftoken :debugger "debugger" :keyword) ;???
(deftoken :default "default" :keyword)
(deftoken :delete "delete" :keyword)
(deftoken :do "do" :keyword)
(deftoken :else "else" :keyword)
(deftoken :enum "enum" :keyword) ;???
(deftoken :false "false" :keyword)
(deftoken :finally "finally" :keyword)
(deftoken :for "for" :keyword)
(deftoken :function "function" :keyword)
(deftoken :function_continuation "function_continuation" :keyword) ; jwacs-only syntax
(deftoken :if "if" :keyword)
(deftoken :import "import" :keyword) ; jwacs-only syntax
(deftoken :in "in" :keyword)
(deftoken :instanceof "instanceof" :keyword) ;???
(deftoken :new "new" :keyword)
(deftoken :null "null" :keyword)
(deftoken :resume "resume" :keyword) ; jwacs-only syntax
(deftoken :return "return" :keyword)
(deftoken :suspend "suspend" :keywork) ; jwacs-only syntax
(deftoken :switch "switch" :keyword)
(deftoken :this "this" :keyword)
(deftoken :throw "throw" :keyword)
(deftoken :true "true" :keyword)
(deftoken :try "try" :keyword)
(deftoken :typeof "typeof" :keyword)
(deftoken :var "var" :keyword)
(deftoken :void "void" :keyword) ;???
(deftoken :while "while" :keyword)
(deftoken :with "with" :keyword)
;; Other terminal types
(deftoken :number)
(deftoken :identifier)
(deftoken :re-literal)
(deftoken :string-literal)
(deftoken :inserted-semicolon)
(deftoken :line-terminator)
(deftoken :no-line-terminator)
;;;; Regular expressions
(defparameter floating-re (create-scanner
'(:sequence
:start-anchor
(:alternation
(:sequence
(:greedy-repetition 1 nil :digit-class)
#\.
(:greedy-repetition 0 nil :digit-class)
(:greedy-repetition 0 1
(:sequence (:alternation #\e #\E)
(:greedy-repetition 0 1 (:alternation #\+ #\-))
(:greedy-repetition 1 nil :digit-class))))
(:sequence
#\.
(:greedy-repetition 1 nil :digit-class)
(:greedy-repetition 0 1
(:sequence (:alternation #\e #\E)
(:greedy-repetition 0 1 (:alternation #\+ #\-))
(:greedy-repetition 1 nil :digit-class)))))))
"Regular expression for recognizing floating-point literals")
(defparameter string-re (create-scanner
'(:sequence
:start-anchor
(:alternation
(:sequence
#\"
(:greedy-repetition 0 nil
(:alternation
(:sequence #\\ :everything)
(:inverted-char-class #\")))
#\")
(:sequence
#\'
(:greedy-repetition 0 nil
(:alternation
(:sequence #\\ :everything)
(:inverted-char-class #\')))
#\'))))
"Regular expression for recognizing string literals")
(define-parse-tree-synonym non-terminator
(:inverted-char-class #\Newline #\Return))
(defparameter regexp-re (create-scanner
'(:sequence
:start-anchor
#\/
(:register
(:sequence
First char
(:alternation
(:sequence #\\ non-terminator)
(:inverted-char-class #\* #\\ #\/ #\Newline #\Return))
;; Subsequent chars
(:greedy-repetition 0 nil
(:alternation
(:sequence #\\ non-terminator)
(:inverted-char-class #\\ #\/ #\Newline #\Return)))))
#\/
(:register
(:greedy-repetition 0 nil
(:char-class #\g #\i)))))
"(Lisp) regular expression for recognizing (Javascript) regular expression literals")
(defparameter operator-re (create-scanner
(list :sequence
:start-anchor
(cons :alternation
(reverse *operator-tokens*))))
"Regular expression for recognizing operators")
(defparameter whitespace-and-comments-re (create-scanner
'(:sequence
:start-anchor
(:greedy-repetition 1 nil
(:alternation
(:greedy-repetition 1 nil
:whitespace-char-class)
(:sequence
"//"
(:greedy-repetition 0 nil
(:inverted-char-class #\Newline))
#\Newline)
(:sequence
"/*"
(:greedy-repetition 0 nil
(:branch (:positive-lookahead "*/")
(:alternation :void
(:alternation :everything
:whitespace-char-class))))
"*/")))))
"Regular expression for consuming (and thereby skipping) whitespace and comments")
(defparameter integer-re (create-scanner
'(:sequence
:start-anchor
(:alternation
(:sequence "0x" (:greedy-repetition 1 nil
(:char-class
(:range #\a #\f)
(:range #\A #\F)
:digit-class)))
(:sequence "0" (:greedy-repetition 1 nil (:char-class (:range #\0 #\7))))
(:greedy-repetition 1 nil :digit-class))))
"Regular expression for recognizing integer literals")
;;;; Data structures
(defstruct token
"Represents a token returned by the lexer"
(terminal nil :type symbol)
(value nil :type (or number string (cons string string) null))
(start nil :type (or number null))
(end nil :type (or number null)))
(defmethod make-load-form ((self token) &optional environment)
(make-load-form-saving-slots self :environment environment))
;;;; Helper functions and macros
(defun parse-javascript-integer (integer-str &key (start 0) end)
"Parse integer literals, taking account of 0x and 0 radix-specifiers"
(cond
((and (> (- (length integer-str) start) 2)
(eql #\0 (aref integer-str start))
(eql #\x (aref integer-str (1+ start))))
(parse-integer integer-str :start (+ start 2) :end end :radix 16 :junk-allowed nil))
((scan "^0[0-7]+" integer-str :start start)
(parse-integer integer-str :start (1+ start) :end end :radix 8 :junk-allowed nil))
(t
(parse-integer integer-str :start start :end end :radix 10 :junk-allowed nil))))
(defun unescape-regexp (re-string)
(regex-replace "\\\\/" re-string "/"))
(defun escape-regexp (re-string)
(regex-replace "/" re-string "\\/"))
(defun line-terminator-p (c)
"Return non-NIL if C is a line-terminator character according to the Javascript spec"
(find (char-code c) '(#x0a #x0d #x2028 #x2029)))
;;;; Top-level logic
(defclass javascript-lexer ()
((cursor :initform 0 :accessor cursor)
(text :initarg :text :reader text)
(unget-stack :initform nil :accessor unget-stack)
(encountered-line-terminator :initform nil :accessor encountered-line-terminator))
(:documentation
"Represents the current state of a lexing operation"))
(defun next-token (lexer)
"Returns a token structure containing the next token in the lexing operation
represented by LEXER. This token will have a terminal of NIL at end of stream.
The next token will be fetched from the unget-stack if that stack is non-empty."
;; If we've pushed other input, then return that instead
(when-let (cell (pop (unget-stack lexer)))
(setf (encountered-line-terminator lexer) (cdr cell))
(return-from next-token (car cell)))
;; Skip the whitespace...
(consume-whitespace lexer)
;; .. and grab a token from the text
(let* ((token (consume-token lexer))
(terminal (when token (token-terminal token))))
;; Restricted token handling
(case (gethash terminal *restricted-tokens*)
(:pre
(cond
((encountered-line-terminator lexer)
(push-token lexer token)
(make-token :terminal :line-terminator :value ""
:start (encountered-line-terminator lexer)
:end (1+ (encountered-line-terminator lexer))))
(t
(push-token lexer token)
(make-token :terminal :no-line-terminator :value ""
:start nil :end nil))))
(:post
(let ((saved-terminator (encountered-line-terminator lexer))
(next-terminator (consume-whitespace lexer)))
(if next-terminator
(push-token lexer (make-token :terminal :line-terminator
:value ""
:start next-terminator :end (1+ next-terminator))
next-terminator)
(push-token lexer (make-token :terminal :no-line-terminator
:value "" :start nil :end nil)
nil))
(setf (encountered-line-terminator lexer) saved-terminator)
token))
(otherwise
token))))
(defun push-token (lexer token &optional (encountered-line-terminator (encountered-line-terminator lexer)))
"Push a token onto the top of LEXER's unget stack. The next token fetched by NEXT-TOKEN will be
the pushed token. The state of the ENCOUNTERED-LINE-TERMINATOR flag is also saved and will be
restored by the next NEXT-TOKEN call."
(push (cons token encountered-line-terminator)
(unget-stack lexer)))
(defun set-cursor (lexer new-pos)
"Sets the cursor of the lexer to the position specified by NEW-POS"
(setf (cursor lexer) new-pos))
(defun coerce-token (lexer terminal)
"Force LEXER to interpret the next token as TERMINAL. An error will be raised
if that's not actually possible."
(let ((token-string (gethash terminal *symbols-to-tokens*)))
;; Only coerce constant tokens (ie, :SLASH good, :STRING-LITERAL bad)
(unless (stringp token-string)
(error "~S is not a coerceable terminal type" terminal))
;; Check that this is a feasible request
(unless (string= (subseq (text lexer)
(cursor lexer)
(+ (cursor lexer) (length token-string)))
token-string)
(error "Cannot interpret ~S as a ~S"
(subseq (text lexer)
(cursor lexer)
(+ (cursor lexer) (length token-string)))
terminal))
;; Okay, let's do this thing
(push-token lexer (make-token :terminal terminal
:value token-string
:start (cursor lexer)
:end (+ (cursor lexer) (length token-string))))
(set-cursor lexer (+ (cursor lexer) (length token-string)))))
(defun consume-whitespace (lexer)
"Consumes whitespace and comments. Lexer's cursor is updated to the next
non-whitespace character, and its ENCOUNTERED-LINE-TERMINATOR slot is set
based upon whether or not the skipped whitespace included a newline.
Returns non-NIL if line-terminators were encountered."
(with-slots (cursor text encountered-line-terminator) lexer
(multiple-value-bind (ws-s ws-e)
(scan whitespace-and-comments-re text :start cursor)
(setf encountered-line-terminator nil)
(when ws-s
(set-cursor lexer ws-e)
(setf encountered-line-terminator
(position-if 'line-terminator-p text :start ws-s :end ws-e))))))
(defun consume-token (lexer)
"Reads the next token from LEXER's source text (where 'next' is determined by
the value of LEXER's cursor). The cursor is assumed to point to a non-whitespace
on exit points to the first character after the consumed token .
Returns a token structure. The token's terminal will be NIL on end of input"
(with-slots (text cursor) lexer
(re-cond (text :start cursor)
("^$"
(make-token :terminal nil :start (length text) :end (length text)))
(floating-re
(set-cursor lexer %e)
(make-token :terminal :number :start %s :end %e
:value (read-from-string text nil nil :start %s :end %e)))
(integer-re
(set-cursor lexer %e)
(make-token :terminal :number :start %s :end %e
:value (parse-javascript-integer text :start %s :end %e)))
("^(\\$|\\w)+"
(set-cursor lexer %e)
(let* ((text (subseq text %s %e))
(terminal (or (gethash text *tokens-to-symbols*)
:identifier)))
(make-token :terminal terminal :start %s :end %e :value text)))
(regexp-re
(set-cursor lexer %e)
(make-token :terminal :re-literal :start %s :end %e
:value (cons (unescape-regexp (subseq text (aref %sub-s 0) (aref %sub-e 0)))
(subseq text (aref %sub-s 1) (aref %sub-e 1)))))
(string-re
(set-cursor lexer %e)
(make-token :terminal :string-literal :start %s :end %e
:value (cl-ppcre:regex-replace-all "(^|[^\\\\])\""
(subseq text (1+ %s) (1- %e))
"\\1\\\"")))
(operator-re
(set-cursor lexer %e)
(let* ((text (subseq text %s %e))
(terminal (gethash text *tokens-to-symbols*)))
(make-token :terminal terminal :start %s :end %e
:value text)))
("^\\S+"
(error "unrecognized token: '~A'" (subseq text %s %e)))
(t
(error "coding error - we should never get here")))))
;; TODO Tab handling
(defun position-to-line/column (text index)
"Returns a cons cell containing the 1-based row and column for the character
at INDEX in TEXT."
(let ((newline-count (count #\Newline text :end index))
(final-newline (position #\Newline text :end index :from-end t)))
(if final-newline
(cons (1+ newline-count) (- index final-newline))
(cons 1 (1+ index)))))
Interface function
(defun make-lexer-function (lexer)
"Returns a function of 0 arguments that calls NEXT-TOKEN on LEXER whenever it is called.
This is normally the function that gets passed into a parser."
(lambda ()
(let ((token (next-token lexer)))
(when token
(values (token-terminal token) token)))))
| null | https://raw.githubusercontent.com/chumsley/jwacs/c25adb3bb31fc2dc6e8c8a58346949ee400633d7/lex-javascript.lisp | lisp | lex-javascript.lisp
as well as some lookup structures for dealing with tokens.
Unit tests are in tests/test-lexer.lisp.
See LICENSE for full licensing details.
Token definitions
Token lookups
Compound assignment operators
These represent operations (addition, etc.) rather than just text tokens.
The lexer will never output them, so possibly the whole *symbols-to-tokens*
setup wants to be in js-source-model instead of here.
Keywords
???
???
???
jwacs-only syntax
jwacs-only syntax
???
jwacs-only syntax
jwacs-only syntax
???
Other terminal types
Regular expressions
Subsequent chars
Data structures
Helper functions and macros
Top-level logic
If we've pushed other input, then return that instead
Skip the whitespace...
.. and grab a token from the text
Restricted token handling
Only coerce constant tokens (ie, :SLASH good, :STRING-LITERAL bad)
Check that this is a feasible request
Okay, let's do this thing
TODO Tab handling
| Contains the definition of the Javascript lexer used by the parser ,
Copyright ( c ) 2005
(in-package :jwacs)
(defmacro deftoken (symbol &optional key token-type)
"Add a token's symbol and possibly string to the appropriate lookups.
Different actions will be taken depending upon the TOKEN-TYPE:
OPERATOR-TOKENs are infix operators, which are recognized as atomic
tokens regardless of whether they are surrounded by whitespace (unlike
identifier tokens, for example).
KEYWORDs are reserved strings that can never be used as an identifier.
OPERATIONs will never be returned by the lexer, but they are used in the
source model in the same place as tokens (ie, in :op-symbol slots), so
they are treated as tokens for now."
(cond
((eq token-type :operator-token)
`(progn
(setf (gethash ,key *tokens-to-symbols*) ,symbol)
(setf (gethash ,symbol *symbols-to-tokens*) ,key)
(push ,key *operator-tokens*)))
((eq token-type :operation)
`(setf (gethash ,symbol *symbols-to-tokens*) ,key))
((eq token-type :keyword)
`(progn
(setf (gethash ,key *tokens-to-symbols*) ,symbol)
(push ,symbol *keyword-symbols*)))
(key
`(setf (gethash ,key *tokens-to-symbols*) ,symbol))
(t
`(setf (gethash ,symbol *tokens-to-symbols*) ,symbol))))
(defparameter *tokens-to-symbols* (make-hash-table :test 'equal)
"Map from string to token symbol.
Every symbol that the tokenizer will return is in this map.")
(defparameter *symbols-to-tokens* (make-hash-table :test 'eq)
"Map from token symbol to token string. This contains an entry for every token
in *tokens-to-symbols*, plus additional entries for the 'operation' symbols.")
(defparameter *operator-tokens* nil
"These are operators (as distinct from general tokens) that will be built into
a special regular expression.
We can't just use the keys from *symbols-to-tokens*, because the
order that the tokens appear in this list is significant.
Specifically, each 'long' operator must occur before any operator that
it is a supersequence of. Eg, '<<<' must occur before '<<', which
must occur before '<'. '!=' must occur before both '!' and '='.")
(defparameter *keyword-symbols* nil
"A list of the keyword symbols.")
(defparameter *restricted-tokens* (make-hash-table :test 'eq)
"Tokens that participate in 'restricted productions'. Value should be either
:PRE or :POST. For each of these tokens, the lexer will emit either a
:NO-LINE-TERMINATOR or a :LINE-TERMINATOR token depending upon whether the token
was preceded/followed by a line-break.")
(setf (gethash :plus2 *restricted-tokens*) :pre)
(setf (gethash :minus2 *restricted-tokens*) :pre)
(setf (gethash :break *restricted-tokens*) :post)
(setf (gethash :continue *restricted-tokens*) :post)
(setf (gethash :return *restricted-tokens*) :post)
(setf (gethash :throw *restricted-tokens*) :post)
(deftoken :times-equals "*=" :operator-token)
(deftoken :divide-equals "/=" :operator-token)
(deftoken :mod-equals "%=" :operator-token)
(deftoken :plus-equals "+=" :operator-token)
(deftoken :minus-equals "-=" :operator-token)
(deftoken :lshift-equals "<<=" :operator-token)
(deftoken :rshift-equals ">>=" :operator-token)
(deftoken :urshift-equals ">>>=" :operator-token)
(deftoken :and-equals "&=" :operator-token)
(deftoken :xor-equals "^=" :operator-token)
(deftoken :or-equals "|=" :operator-token)
Operators and punctuators
(deftoken :semicolon ";" :operator-token)
(deftoken :comma "," :operator-token)
(deftoken :hook "?" :operator-token)
(deftoken :colon ":" :operator-token)
(deftoken :conditional)
(deftoken :bar2 "||" :operator-token)
(deftoken :ampersand2 "&&" :operator-token)
(deftoken :bar "|" :operator-token)
(deftoken :caret "^" :operator-token)
(deftoken :ampersand "&" :operator-token)
(deftoken :equals3 "===" :operator-token)
(deftoken :not-equals2 "!==" :operator-token)
(deftoken :equals2 "==" :operator-token)
(deftoken :equals "=" :operator-token)
(deftoken :not-equals "!=" :operator-token)
(deftoken :left-arrow "<-" :operator-token)
(deftoken :right-arrow "->" :operator-token)
(deftoken :less-than-equals "<=" :operator-token)
(deftoken :greater-than-equals ">=" :operator-token)
(deftoken :urshift ">>>" :operator-token)
(deftoken :lshift "<<" :operator-token)
(deftoken :rshift ">>" :operator-token)
(deftoken :less-than "<" :operator-token)
(deftoken :greater-than ">" :operator-token)
(deftoken :asterisk "*" :operator-token)
(deftoken :slash "/" :operator-token)
(deftoken :percent "%" :operator-token)
(deftoken :bang "!" :operator-token)
(deftoken :tilde "~" :operator-token)
(deftoken :plus2 "++" :operator-token)
(deftoken :minus2 "--" :operator-token)
(deftoken :plus "+" :operator-token)
(deftoken :minus "-" :operator-token)
(deftoken :dot "." :operator-token)
(deftoken :left-bracket "[" :operator-token)
(deftoken :right-bracket "]" :operator-token)
(deftoken :left-curly "{" :operator-token)
(deftoken :right-curly "}" :operator-token)
(deftoken :left-paren "(" :operator-token)
(deftoken :right-paren ")" :operator-token)
(deftoken :assign "=" :operation)
(deftoken :unary-plus "+" :operation)
(deftoken :unary-minus "-" :operation)
(deftoken :pre-decr "--" :operation)
(deftoken :pre-incr "++" :operation)
(deftoken :post-decr "--" :operation)
(deftoken :post-incr "++" :operation)
(deftoken :logical-and "&&" :operation)
(deftoken :logical-or "||" :operation)
(deftoken :logical-not "!" :operation)
(deftoken :bitwise-and "&" :operation)
(deftoken :bitwise-or "|" :operation)
(deftoken :bitwise-not "~" :operation)
(deftoken :bitwise-xor "^" :operation)
(deftoken :equals "==" :operation)
(deftoken :strict-equals "===" :operation)
(deftoken :strict-not-equals "!==" :operation)
(deftoken :add "+" :operation)
(deftoken :subtract "-" :operation)
(deftoken :multiply "*" :operation)
(deftoken :divide "/" :operation)
(deftoken :modulo "%" :operation)
(deftoken :break "break" :keyword)
(deftoken :case "case" :keyword)
(deftoken :catch "catch" :keyword)
(deftoken :continue "continue" :keyword)
(deftoken :default "default" :keyword)
(deftoken :delete "delete" :keyword)
(deftoken :do "do" :keyword)
(deftoken :else "else" :keyword)
(deftoken :false "false" :keyword)
(deftoken :finally "finally" :keyword)
(deftoken :for "for" :keyword)
(deftoken :function "function" :keyword)
(deftoken :if "if" :keyword)
(deftoken :in "in" :keyword)
(deftoken :new "new" :keyword)
(deftoken :null "null" :keyword)
(deftoken :return "return" :keyword)
(deftoken :switch "switch" :keyword)
(deftoken :this "this" :keyword)
(deftoken :throw "throw" :keyword)
(deftoken :true "true" :keyword)
(deftoken :try "try" :keyword)
(deftoken :typeof "typeof" :keyword)
(deftoken :var "var" :keyword)
(deftoken :while "while" :keyword)
(deftoken :with "with" :keyword)
(deftoken :number)
(deftoken :identifier)
(deftoken :re-literal)
(deftoken :string-literal)
(deftoken :inserted-semicolon)
(deftoken :line-terminator)
(deftoken :no-line-terminator)
(defparameter floating-re (create-scanner
'(:sequence
:start-anchor
(:alternation
(:sequence
(:greedy-repetition 1 nil :digit-class)
#\.
(:greedy-repetition 0 nil :digit-class)
(:greedy-repetition 0 1
(:sequence (:alternation #\e #\E)
(:greedy-repetition 0 1 (:alternation #\+ #\-))
(:greedy-repetition 1 nil :digit-class))))
(:sequence
#\.
(:greedy-repetition 1 nil :digit-class)
(:greedy-repetition 0 1
(:sequence (:alternation #\e #\E)
(:greedy-repetition 0 1 (:alternation #\+ #\-))
(:greedy-repetition 1 nil :digit-class)))))))
"Regular expression for recognizing floating-point literals")
(defparameter string-re (create-scanner
'(:sequence
:start-anchor
(:alternation
(:sequence
#\"
(:greedy-repetition 0 nil
(:alternation
(:sequence #\\ :everything)
(:inverted-char-class #\")))
#\")
(:sequence
#\'
(:greedy-repetition 0 nil
(:alternation
(:sequence #\\ :everything)
(:inverted-char-class #\')))
#\'))))
"Regular expression for recognizing string literals")
(define-parse-tree-synonym non-terminator
(:inverted-char-class #\Newline #\Return))
(defparameter regexp-re (create-scanner
'(:sequence
:start-anchor
#\/
(:register
(:sequence
First char
(:alternation
(:sequence #\\ non-terminator)
(:inverted-char-class #\* #\\ #\/ #\Newline #\Return))
(:greedy-repetition 0 nil
(:alternation
(:sequence #\\ non-terminator)
(:inverted-char-class #\\ #\/ #\Newline #\Return)))))
#\/
(:register
(:greedy-repetition 0 nil
(:char-class #\g #\i)))))
"(Lisp) regular expression for recognizing (Javascript) regular expression literals")
(defparameter operator-re (create-scanner
(list :sequence
:start-anchor
(cons :alternation
(reverse *operator-tokens*))))
"Regular expression for recognizing operators")
(defparameter whitespace-and-comments-re (create-scanner
'(:sequence
:start-anchor
(:greedy-repetition 1 nil
(:alternation
(:greedy-repetition 1 nil
:whitespace-char-class)
(:sequence
"//"
(:greedy-repetition 0 nil
(:inverted-char-class #\Newline))
#\Newline)
(:sequence
"/*"
(:greedy-repetition 0 nil
(:branch (:positive-lookahead "*/")
(:alternation :void
(:alternation :everything
:whitespace-char-class))))
"*/")))))
"Regular expression for consuming (and thereby skipping) whitespace and comments")
(defparameter integer-re (create-scanner
'(:sequence
:start-anchor
(:alternation
(:sequence "0x" (:greedy-repetition 1 nil
(:char-class
(:range #\a #\f)
(:range #\A #\F)
:digit-class)))
(:sequence "0" (:greedy-repetition 1 nil (:char-class (:range #\0 #\7))))
(:greedy-repetition 1 nil :digit-class))))
"Regular expression for recognizing integer literals")
(defstruct token
"Represents a token returned by the lexer"
(terminal nil :type symbol)
(value nil :type (or number string (cons string string) null))
(start nil :type (or number null))
(end nil :type (or number null)))
(defmethod make-load-form ((self token) &optional environment)
(make-load-form-saving-slots self :environment environment))
(defun parse-javascript-integer (integer-str &key (start 0) end)
"Parse integer literals, taking account of 0x and 0 radix-specifiers"
(cond
((and (> (- (length integer-str) start) 2)
(eql #\0 (aref integer-str start))
(eql #\x (aref integer-str (1+ start))))
(parse-integer integer-str :start (+ start 2) :end end :radix 16 :junk-allowed nil))
((scan "^0[0-7]+" integer-str :start start)
(parse-integer integer-str :start (1+ start) :end end :radix 8 :junk-allowed nil))
(t
(parse-integer integer-str :start start :end end :radix 10 :junk-allowed nil))))
(defun unescape-regexp (re-string)
(regex-replace "\\\\/" re-string "/"))
(defun escape-regexp (re-string)
(regex-replace "/" re-string "\\/"))
(defun line-terminator-p (c)
"Return non-NIL if C is a line-terminator character according to the Javascript spec"
(find (char-code c) '(#x0a #x0d #x2028 #x2029)))
(defclass javascript-lexer ()
((cursor :initform 0 :accessor cursor)
(text :initarg :text :reader text)
(unget-stack :initform nil :accessor unget-stack)
(encountered-line-terminator :initform nil :accessor encountered-line-terminator))
(:documentation
"Represents the current state of a lexing operation"))
(defun next-token (lexer)
"Returns a token structure containing the next token in the lexing operation
represented by LEXER. This token will have a terminal of NIL at end of stream.
The next token will be fetched from the unget-stack if that stack is non-empty."
(when-let (cell (pop (unget-stack lexer)))
(setf (encountered-line-terminator lexer) (cdr cell))
(return-from next-token (car cell)))
(consume-whitespace lexer)
(let* ((token (consume-token lexer))
(terminal (when token (token-terminal token))))
(case (gethash terminal *restricted-tokens*)
(:pre
(cond
((encountered-line-terminator lexer)
(push-token lexer token)
(make-token :terminal :line-terminator :value ""
:start (encountered-line-terminator lexer)
:end (1+ (encountered-line-terminator lexer))))
(t
(push-token lexer token)
(make-token :terminal :no-line-terminator :value ""
:start nil :end nil))))
(:post
(let ((saved-terminator (encountered-line-terminator lexer))
(next-terminator (consume-whitespace lexer)))
(if next-terminator
(push-token lexer (make-token :terminal :line-terminator
:value ""
:start next-terminator :end (1+ next-terminator))
next-terminator)
(push-token lexer (make-token :terminal :no-line-terminator
:value "" :start nil :end nil)
nil))
(setf (encountered-line-terminator lexer) saved-terminator)
token))
(otherwise
token))))
(defun push-token (lexer token &optional (encountered-line-terminator (encountered-line-terminator lexer)))
"Push a token onto the top of LEXER's unget stack. The next token fetched by NEXT-TOKEN will be
the pushed token. The state of the ENCOUNTERED-LINE-TERMINATOR flag is also saved and will be
restored by the next NEXT-TOKEN call."
(push (cons token encountered-line-terminator)
(unget-stack lexer)))
(defun set-cursor (lexer new-pos)
"Sets the cursor of the lexer to the position specified by NEW-POS"
(setf (cursor lexer) new-pos))
(defun coerce-token (lexer terminal)
"Force LEXER to interpret the next token as TERMINAL. An error will be raised
if that's not actually possible."
(let ((token-string (gethash terminal *symbols-to-tokens*)))
(unless (stringp token-string)
(error "~S is not a coerceable terminal type" terminal))
(unless (string= (subseq (text lexer)
(cursor lexer)
(+ (cursor lexer) (length token-string)))
token-string)
(error "Cannot interpret ~S as a ~S"
(subseq (text lexer)
(cursor lexer)
(+ (cursor lexer) (length token-string)))
terminal))
(push-token lexer (make-token :terminal terminal
:value token-string
:start (cursor lexer)
:end (+ (cursor lexer) (length token-string))))
(set-cursor lexer (+ (cursor lexer) (length token-string)))))
(defun consume-whitespace (lexer)
"Consumes whitespace and comments. Lexer's cursor is updated to the next
non-whitespace character, and its ENCOUNTERED-LINE-TERMINATOR slot is set
based upon whether or not the skipped whitespace included a newline.
Returns non-NIL if line-terminators were encountered."
(with-slots (cursor text encountered-line-terminator) lexer
(multiple-value-bind (ws-s ws-e)
(scan whitespace-and-comments-re text :start cursor)
(setf encountered-line-terminator nil)
(when ws-s
(set-cursor lexer ws-e)
(setf encountered-line-terminator
(position-if 'line-terminator-p text :start ws-s :end ws-e))))))
(defun consume-token (lexer)
"Reads the next token from LEXER's source text (where 'next' is determined by
the value of LEXER's cursor). The cursor is assumed to point to a non-whitespace
on exit points to the first character after the consumed token .
Returns a token structure. The token's terminal will be NIL on end of input"
(with-slots (text cursor) lexer
(re-cond (text :start cursor)
("^$"
(make-token :terminal nil :start (length text) :end (length text)))
(floating-re
(set-cursor lexer %e)
(make-token :terminal :number :start %s :end %e
:value (read-from-string text nil nil :start %s :end %e)))
(integer-re
(set-cursor lexer %e)
(make-token :terminal :number :start %s :end %e
:value (parse-javascript-integer text :start %s :end %e)))
("^(\\$|\\w)+"
(set-cursor lexer %e)
(let* ((text (subseq text %s %e))
(terminal (or (gethash text *tokens-to-symbols*)
:identifier)))
(make-token :terminal terminal :start %s :end %e :value text)))
(regexp-re
(set-cursor lexer %e)
(make-token :terminal :re-literal :start %s :end %e
:value (cons (unescape-regexp (subseq text (aref %sub-s 0) (aref %sub-e 0)))
(subseq text (aref %sub-s 1) (aref %sub-e 1)))))
(string-re
(set-cursor lexer %e)
(make-token :terminal :string-literal :start %s :end %e
:value (cl-ppcre:regex-replace-all "(^|[^\\\\])\""
(subseq text (1+ %s) (1- %e))
"\\1\\\"")))
(operator-re
(set-cursor lexer %e)
(let* ((text (subseq text %s %e))
(terminal (gethash text *tokens-to-symbols*)))
(make-token :terminal terminal :start %s :end %e
:value text)))
("^\\S+"
(error "unrecognized token: '~A'" (subseq text %s %e)))
(t
(error "coding error - we should never get here")))))
(defun position-to-line/column (text index)
"Returns a cons cell containing the 1-based row and column for the character
at INDEX in TEXT."
(let ((newline-count (count #\Newline text :end index))
(final-newline (position #\Newline text :end index :from-end t)))
(if final-newline
(cons (1+ newline-count) (- index final-newline))
(cons 1 (1+ index)))))
Interface function
(defun make-lexer-function (lexer)
"Returns a function of 0 arguments that calls NEXT-TOKEN on LEXER whenever it is called.
This is normally the function that gets passed into a parser."
(lambda ()
(let ((token (next-token lexer)))
(when token
(values (token-terminal token) token)))))
|
38b77526f75cd5800d5c1db2e22899bdf18dd305397aec72e85a81a72ef97ea8 | futurice/haskell-mega-repo | API.hs | {-# LANGUAGE DataKinds #-}
# LANGUAGE FlexibleInstances #
# LANGUAGE MultiParamTypeClasses #
{-# LANGUAGE ScopedTypeVariables #-}
# LANGUAGE TypeFamilies #
{-# LANGUAGE TypeOperators #-}
module Futurice.App.HoursApi.API where
import Futurice.Prelude
import Futurice.Servant (SSOUser)
import Prelude ()
import Servant
import FUM.Types.Login (Login)
import Futurice.App.HoursApi.Types
import qualified PlanMill as PM
type HoursEndpoint = "hours" :> SSOUser
:> Description "Get hours for given interval"
:> QueryParam' '[Required] "start-date" Day
:> QueryParam' '[Required] "end-date" Day
:> Get '[JSON] HoursResponse
type FutuhoursV1API =
"projects" :> SSOUser :> Get '[JSON] [Project ReportableTask]
:<|> "user" :> SSOUser :> Get '[JSON] User
:<|> HoursEndpoint
:<|> "entry" :> SSOUser :> ReqBody '[JSON] EntryUpdate :> Post '[JSON] EntryUpdateResponse
:<|> "entry" :> SSOUser :> Capture "id" PM.TimereportId :> ReqBody '[JSON] EntryUpdate :> Put '[JSON] EntryUpdateResponse
:<|> "entry" :> SSOUser :> Capture "id" PM.TimereportId :> Delete '[JSON] EntryUpdateResponse
:<|> "delete-timereports" :> SSOUser :> ReqBody '[JSON] [PM.TimereportId] :> Post '[JSON] EntryUpdateResponse
type FutuhoursAPI = Get '[JSON] Text
:<|> "api" :> "v1" :> FutuhoursV1API
:<|> "debug" :> "users" :> Get '[JSON] [Login]
futuhoursApi :: Proxy FutuhoursAPI
futuhoursApi = Proxy
| null | https://raw.githubusercontent.com/futurice/haskell-mega-repo/2647723f12f5435e2edc373f6738386a9668f603/hours-api/src/Futurice/App/HoursApi/API.hs | haskell | # LANGUAGE DataKinds #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TypeOperators # | # LANGUAGE FlexibleInstances #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE TypeFamilies #
module Futurice.App.HoursApi.API where
import Futurice.Prelude
import Futurice.Servant (SSOUser)
import Prelude ()
import Servant
import FUM.Types.Login (Login)
import Futurice.App.HoursApi.Types
import qualified PlanMill as PM
type HoursEndpoint = "hours" :> SSOUser
:> Description "Get hours for given interval"
:> QueryParam' '[Required] "start-date" Day
:> QueryParam' '[Required] "end-date" Day
:> Get '[JSON] HoursResponse
type FutuhoursV1API =
"projects" :> SSOUser :> Get '[JSON] [Project ReportableTask]
:<|> "user" :> SSOUser :> Get '[JSON] User
:<|> HoursEndpoint
:<|> "entry" :> SSOUser :> ReqBody '[JSON] EntryUpdate :> Post '[JSON] EntryUpdateResponse
:<|> "entry" :> SSOUser :> Capture "id" PM.TimereportId :> ReqBody '[JSON] EntryUpdate :> Put '[JSON] EntryUpdateResponse
:<|> "entry" :> SSOUser :> Capture "id" PM.TimereportId :> Delete '[JSON] EntryUpdateResponse
:<|> "delete-timereports" :> SSOUser :> ReqBody '[JSON] [PM.TimereportId] :> Post '[JSON] EntryUpdateResponse
type FutuhoursAPI = Get '[JSON] Text
:<|> "api" :> "v1" :> FutuhoursV1API
:<|> "debug" :> "users" :> Get '[JSON] [Login]
futuhoursApi :: Proxy FutuhoursAPI
futuhoursApi = Proxy
|
774e9acb29ad731fcb9a51ce7ae6467b6191af06830a3f88149913369ef78a3a | janestreet/incr_dom_partial_render | table.mli | open! Core
open! Import
include Table_intf.Table
module Default_sort_spec : sig
(** A sortable value. The sorting order of a row is specified by specifying a conversion
to this type.
Note that typically, all values will be injected into just one of these variant
constructors. The sorting between different constructors is considered arbitrary. *)
module Sort_key : sig
type t =
| String of string
| Float of float
| Integer of Int63.t
| Null
[@@deriving compare, sexp]
include Table_intf.Sort_key with type t := t
end
module Sort_dir : sig
type t =
| Ascending
| Descending
[@@deriving sexp, compare]
include Table_intf.Sort_dir with type t := t
end
include
Table_intf.Sort_spec with module Sort_key := Sort_key and module Sort_dir := Sort_dir
end
| null | https://raw.githubusercontent.com/janestreet/incr_dom_partial_render/82be6e4688d8491c9a71a2aa7d1591da7aa61eee/src/table.mli | ocaml | * A sortable value. The sorting order of a row is specified by specifying a conversion
to this type.
Note that typically, all values will be injected into just one of these variant
constructors. The sorting between different constructors is considered arbitrary. | open! Core
open! Import
include Table_intf.Table
module Default_sort_spec : sig
module Sort_key : sig
type t =
| String of string
| Float of float
| Integer of Int63.t
| Null
[@@deriving compare, sexp]
include Table_intf.Sort_key with type t := t
end
module Sort_dir : sig
type t =
| Ascending
| Descending
[@@deriving sexp, compare]
include Table_intf.Sort_dir with type t := t
end
include
Table_intf.Sort_spec with module Sort_key := Sort_key and module Sort_dir := Sort_dir
end
|
18ced8670ac4cd6b46c164b1376424cc85905bbf15648b49a560ab70534b5621 | DavidAlphaFox/aiwiki | aiwiki_admin_page_controller.erl | -module(aiwiki_admin_page_controller).
-export([init/2]).
init(Req,State)->
Action = cowboy_req:binding(action,Req),
init(Action,Req,State).
init(<<"edit.php">>,#{method := <<"GET">> } = Req,State) ->
Form = aiwiki_helper:build_form(Req,<<"POST">>),
QS = cowboy_req:parse_qs(Req),
ID = proplists:get_value(<<"id">>, QS),
IntID = ai_string:to_integer(ID),
Page = ai_db:fetch(page,IntID),
TopicID = proplists:get_value(topic_id,Page),
Topics = aiwiki_topic_helper:select(TopicID),
PageModel = aiwiki_helper:view_model(Page),
Context = Form#{
<<"topics">> => Topics,
<<"page">> => PageModel
},
aiwiki_view:render(<<"admin/page/edit">>,
Req,State#{context => Context});
init(<<"edit.php">>,#{method := <<"POST">> } = Req,State) ->
{ok,Body,Req0} = aiwiki_helper:body(Req),
R = ai_url:parse_query(Body),
Session = aiwiki_session_handler:session_id(Req),
case aiwiki_helper:verify_form(Req,R) of
false -> aiwiki_view:error(400,Req0,State);
true -> action(edit,Req0,State#{form => R})
end.
action(edit,Req,#{form := R} = State)->
QS = cowboy_req:parse_qs(Req),
Topic = proplists:get_value(<<"topic">>,R),
IntTopic = ai_string:to_integer(Topic),
Published =
case proplists:get_value(<<"published">>,R) of
undefined -> false;
V -> ai_string:to_boolean(V)
end,
Title = proplists:get_value(<<"title">>,R),
Content = proplists:get_value(<<"content">>,R),
Intro = proplists:get_value(<<"intro">>,R),
Page = aiwiki_page_model:build(Title,Intro,Content,IntTopic,Published),
ID = proplists:get_value(<<"id">>, QS),
IntID = ai_string:to_integer(ID),
Page1 = ai_db:fetch(page,IntID),
PageModel = aiwiki_helper:view_model(Page1),
Form = aiwiki_helper:build_form(Req,<<"POST">>),
Context = Form#{
<<"page">> => PageModel
},
aiwiki_view:render(<<"admin/page/edit">>,
Req,State#{context => Context}).
| null | https://raw.githubusercontent.com/DavidAlphaFox/aiwiki/3a2a78668d4a708fda4af35430f25a69c4b91a7e/src/controller/aiwiki_admin_page_controller.erl | erlang | -module(aiwiki_admin_page_controller).
-export([init/2]).
init(Req,State)->
Action = cowboy_req:binding(action,Req),
init(Action,Req,State).
init(<<"edit.php">>,#{method := <<"GET">> } = Req,State) ->
Form = aiwiki_helper:build_form(Req,<<"POST">>),
QS = cowboy_req:parse_qs(Req),
ID = proplists:get_value(<<"id">>, QS),
IntID = ai_string:to_integer(ID),
Page = ai_db:fetch(page,IntID),
TopicID = proplists:get_value(topic_id,Page),
Topics = aiwiki_topic_helper:select(TopicID),
PageModel = aiwiki_helper:view_model(Page),
Context = Form#{
<<"topics">> => Topics,
<<"page">> => PageModel
},
aiwiki_view:render(<<"admin/page/edit">>,
Req,State#{context => Context});
init(<<"edit.php">>,#{method := <<"POST">> } = Req,State) ->
{ok,Body,Req0} = aiwiki_helper:body(Req),
R = ai_url:parse_query(Body),
Session = aiwiki_session_handler:session_id(Req),
case aiwiki_helper:verify_form(Req,R) of
false -> aiwiki_view:error(400,Req0,State);
true -> action(edit,Req0,State#{form => R})
end.
action(edit,Req,#{form := R} = State)->
QS = cowboy_req:parse_qs(Req),
Topic = proplists:get_value(<<"topic">>,R),
IntTopic = ai_string:to_integer(Topic),
Published =
case proplists:get_value(<<"published">>,R) of
undefined -> false;
V -> ai_string:to_boolean(V)
end,
Title = proplists:get_value(<<"title">>,R),
Content = proplists:get_value(<<"content">>,R),
Intro = proplists:get_value(<<"intro">>,R),
Page = aiwiki_page_model:build(Title,Intro,Content,IntTopic,Published),
ID = proplists:get_value(<<"id">>, QS),
IntID = ai_string:to_integer(ID),
Page1 = ai_db:fetch(page,IntID),
PageModel = aiwiki_helper:view_model(Page1),
Form = aiwiki_helper:build_form(Req,<<"POST">>),
Context = Form#{
<<"page">> => PageModel
},
aiwiki_view:render(<<"admin/page/edit">>,
Req,State#{context => Context}).
| |
51dc09ce2dc68e0193f032592a722ae755849be44b9c03c5ba5467674772ce99 | inaimathi/cl-notebook | evaluators.lisp | (in-package #:cl-notebook)
(defvar *front-end-eval-thread* nil)
(defmethod front-end-eval (cell-language cell-type (contents string))
"A cell that fits no other description returns an error"
(list
(alist
:stdout "" :warnings nil ; Without these, :json encodes this as an array rather than an object
:values (list (alist :type 'error :value
(alist 'condition-type "UNKNOWN-LANGUAGE:TYPE-COMBINATION"
'cell-language cell-language
'cell-type cell-type))))))
(defmethod front-end-eval (cell-language cell-type (contents null)) "")
(defmethod front-end-eval ((cell-language (eql :common-lisp)) (cell-type (eql :tests)) (contents string))
"A Common-Lisp:Test cell is just evaluated, capturing all warnings, stdout emissions and errors.
It's treated differently in export situations."
(capturing-eval contents))
(defmethod front-end-eval ((cell-language (eql :common-lisp)) (cell-type (eql :code)) (contents string))
"A Common-Lisp:Code cell is just evaluated, capturing all warnings, stdout emissions and errors."
(capturing-eval contents))
(defmethod front-end-eval ((cell-language (eql :common-lisp)) (cell-type (eql :markup)) (contents string))
"A Common-Lisp:Markup cell is evaluated as a :cl-who tree"
(list
(alist :stdout "" :warnings nil ; Without these, :json encodes this as an array rather than an object
:values
(handler-case
(list
(alist
:type "string"
:value (eval
`(with-html-output-to-string (s)
,@(read-all contents)))))
(error (e)
(list (alist :type 'error :value (front-end-error nil e))))))))
(defmethod front-end-eval ((cell-language (eql :common-lisp)) (cell-type (eql :parenscript)) (contents string))
"A Common-Lisp:Parenscript cell is evaluated as a `ps` form"
(list
(alist :stdout "" :warnings nil
:values
(handler-case
(list
(alist
:type "js"
:value (apply #'ps* (read-all contents))))
(error (e)
(list (alist :type 'error :value (front-end-error nil e))))))))
(defun front-end-eval-formats ()
(let ((h (make-hash-table)))
(loop for m in (closer-mop:generic-function-methods #'front-end-eval)
for (a b _) = (closer-mop:method-specializers m)
when (and (typep a 'closer-mop:eql-specializer) (typep b 'closer-mop:eql-specializer))
do (push (closer-mop:eql-specializer-object b)
(gethash (closer-mop:eql-specializer-object a) h nil)))
h))
(defmethod eval-notebook ((book notebook) &key (cell-type :code))
(let ((ids (notebook-cell-order book)))
(loop for cell-id in ids
when (lookup book :a cell-id :b :cell-type :c cell-type)
do (let ((stale? (first (lookup book :a cell-id :b :stale :c t)))
(res-fact (first (lookup book :a cell-id :b :result)))
(*package* (namespace book)))
(let ((res
(handler-case
(bt:with-timeout (.1)
(front-end-eval
(caddar (lookup book :a cell-id :b :cell-language))
cell-type
(caddar (lookup book :a cell-id :b :contents))))
#-sbcl (bordeaux-threads:timeout () :timed-out)
#+sbcl (sb-ext:timeout () :timed-out))))
(unless (eq :timed-out res)
(when stale? (delete! book stale?))
(unless (equalp (third res-fact) res)
(let ((new (list cell-id :result res)))
(if res-fact
(change! book res-fact new)
(insert! book new))))))))
(write! book)))
(defmethod empty-expression? ((contents string))
(when (cl-ppcre:scan "^[ \n\t\r]*$" contents) t))
(defmethod eval-cell ((book notebook) cell-id (contents string) res-fact cell-language cell-type)
(unless (empty-expression? contents)
(when (and (bt:threadp *front-end-eval-thread*)
(bt:thread-alive-p *front-end-eval-thread*))
(bt:destroy-thread *front-end-eval-thread*))
(publish-update! book 'starting-eval :target cell-id)
(setf *front-end-eval-thread*
(bt:make-thread
(lambda ()
(let ((*package* (namespace book)))
(let ((res (front-end-eval cell-language cell-type contents)))
(when (and res-fact res)
(change! book res-fact (list cell-id :result res))
(delete! book (list cell-id :stale t))
(write! book))
(publish-update! book 'finished-eval :cell cell-id :contents contents :result res))))))))
(defmethod eval-package ((book notebook) (contents string))
(when (and (bt:threadp *front-end-eval-thread*)
(bt:thread-alive-p *front-end-eval-thread*))
(bt:destroy-thread *front-end-eval-thread*))
(publish-update! book 'starting-eval :target :package)
(setf *front-end-eval-thread*
(bt:make-thread
(lambda ()
(handler-case
(multiple-value-bind (book repackaged?) (repackage-notebook! book contents)
(when repackaged?
(unless (lookup book :b :package-edited?)
(insert-new! book :package-edited? t))
(write! book))
(publish-update! book 'finished-package-eval :contents contents))
(error (e)
(publish-update! book 'finished-package-eval :contents contents :result (front-end-error nil e))))))))
| null | https://raw.githubusercontent.com/inaimathi/cl-notebook/c9879b2d390c02bfe4ccaf245a342dd346040322/src/evaluators.lisp | lisp | Without these, :json encodes this as an array rather than an object
Without these, :json encodes this as an array rather than an object | (in-package #:cl-notebook)
(defvar *front-end-eval-thread* nil)
(defmethod front-end-eval (cell-language cell-type (contents string))
"A cell that fits no other description returns an error"
(list
(alist
:values (list (alist :type 'error :value
(alist 'condition-type "UNKNOWN-LANGUAGE:TYPE-COMBINATION"
'cell-language cell-language
'cell-type cell-type))))))
(defmethod front-end-eval (cell-language cell-type (contents null)) "")
(defmethod front-end-eval ((cell-language (eql :common-lisp)) (cell-type (eql :tests)) (contents string))
"A Common-Lisp:Test cell is just evaluated, capturing all warnings, stdout emissions and errors.
It's treated differently in export situations."
(capturing-eval contents))
(defmethod front-end-eval ((cell-language (eql :common-lisp)) (cell-type (eql :code)) (contents string))
"A Common-Lisp:Code cell is just evaluated, capturing all warnings, stdout emissions and errors."
(capturing-eval contents))
(defmethod front-end-eval ((cell-language (eql :common-lisp)) (cell-type (eql :markup)) (contents string))
"A Common-Lisp:Markup cell is evaluated as a :cl-who tree"
(list
:values
(handler-case
(list
(alist
:type "string"
:value (eval
`(with-html-output-to-string (s)
,@(read-all contents)))))
(error (e)
(list (alist :type 'error :value (front-end-error nil e))))))))
(defmethod front-end-eval ((cell-language (eql :common-lisp)) (cell-type (eql :parenscript)) (contents string))
"A Common-Lisp:Parenscript cell is evaluated as a `ps` form"
(list
(alist :stdout "" :warnings nil
:values
(handler-case
(list
(alist
:type "js"
:value (apply #'ps* (read-all contents))))
(error (e)
(list (alist :type 'error :value (front-end-error nil e))))))))
(defun front-end-eval-formats ()
(let ((h (make-hash-table)))
(loop for m in (closer-mop:generic-function-methods #'front-end-eval)
for (a b _) = (closer-mop:method-specializers m)
when (and (typep a 'closer-mop:eql-specializer) (typep b 'closer-mop:eql-specializer))
do (push (closer-mop:eql-specializer-object b)
(gethash (closer-mop:eql-specializer-object a) h nil)))
h))
(defmethod eval-notebook ((book notebook) &key (cell-type :code))
(let ((ids (notebook-cell-order book)))
(loop for cell-id in ids
when (lookup book :a cell-id :b :cell-type :c cell-type)
do (let ((stale? (first (lookup book :a cell-id :b :stale :c t)))
(res-fact (first (lookup book :a cell-id :b :result)))
(*package* (namespace book)))
(let ((res
(handler-case
(bt:with-timeout (.1)
(front-end-eval
(caddar (lookup book :a cell-id :b :cell-language))
cell-type
(caddar (lookup book :a cell-id :b :contents))))
#-sbcl (bordeaux-threads:timeout () :timed-out)
#+sbcl (sb-ext:timeout () :timed-out))))
(unless (eq :timed-out res)
(when stale? (delete! book stale?))
(unless (equalp (third res-fact) res)
(let ((new (list cell-id :result res)))
(if res-fact
(change! book res-fact new)
(insert! book new))))))))
(write! book)))
(defmethod empty-expression? ((contents string))
(when (cl-ppcre:scan "^[ \n\t\r]*$" contents) t))
(defmethod eval-cell ((book notebook) cell-id (contents string) res-fact cell-language cell-type)
(unless (empty-expression? contents)
(when (and (bt:threadp *front-end-eval-thread*)
(bt:thread-alive-p *front-end-eval-thread*))
(bt:destroy-thread *front-end-eval-thread*))
(publish-update! book 'starting-eval :target cell-id)
(setf *front-end-eval-thread*
(bt:make-thread
(lambda ()
(let ((*package* (namespace book)))
(let ((res (front-end-eval cell-language cell-type contents)))
(when (and res-fact res)
(change! book res-fact (list cell-id :result res))
(delete! book (list cell-id :stale t))
(write! book))
(publish-update! book 'finished-eval :cell cell-id :contents contents :result res))))))))
(defmethod eval-package ((book notebook) (contents string))
(when (and (bt:threadp *front-end-eval-thread*)
(bt:thread-alive-p *front-end-eval-thread*))
(bt:destroy-thread *front-end-eval-thread*))
(publish-update! book 'starting-eval :target :package)
(setf *front-end-eval-thread*
(bt:make-thread
(lambda ()
(handler-case
(multiple-value-bind (book repackaged?) (repackage-notebook! book contents)
(when repackaged?
(unless (lookup book :b :package-edited?)
(insert-new! book :package-edited? t))
(write! book))
(publish-update! book 'finished-package-eval :contents contents))
(error (e)
(publish-update! book 'finished-package-eval :contents contents :result (front-end-error nil e))))))))
|
0222720bf62c4988386ba0baf86542407fef9d137d2142668a4f7cf9da73061c | mtravers/wuwei | wu.lisp | (in-package :wu)
;;; +=========================================================================+
| Copyright ( c ) 2009 - 2011 and CollabRx , Inc |
;;; | |
| Released under the MIT Open Source License |
;;; | -license.php |
;;; | |
;;; | 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. |
;;; +=========================================================================+
#|
Provide slightly higher-level functions for the common case, to make
cleaner looking web code.
|#
;;; Publish an explict URL, body is wrapped in lamda, response generation, HTML
;;; +++ Could extend URL to be list of url + options (eg content-type)
(defmacro wu-publish (url &body body)
`(publish :path ,url :content-type "text/html"
:function #'(lambda (req ent)
(with-http-response-and-body (req ent)
(html
,@body)))))
;;; As above, A continuation that returns HTML (ajax-continuation by default returns javascript)
;;; OPTIONS are passed to AJAX-CONTINUATION
;;; Body is wrapped in HTML macro
(defmacro wu-continuation (options &body body)
`(ajax-continuation (:content-type "text/html" ,@options )
(html
,@body)))
;;; Generate a sequential series of actions, each a continuation of the next (eg a web progn).
;;; Each clause is of the form (<options> . <body>), options are passed to wu-continuation.
;;; Clauses refer to the next page via (-next-).
;;; For an example, see examples/arc-challenge.lisp
;;; Note: this is something you probably never really want to do in a real web app. I wrote this in response
to the ARC challenge . If you DID , you 'd probably want to enable the back button by putting : keep t in
;;; the options.
(defmacro wu-conversation (first &body rest)
do n't feel sad , it only took me the better part of a day to get this quoting right !
(html ,@(cdr first))))
(defmacro wu-conversation-1 (first &body rest)
(when first
`(macrolet ((-next- () `(wu-conversation-1 ,@',rest)))
(wu-continuation ,(car first)
(html ,@(cdr first))))))
| null | https://raw.githubusercontent.com/mtravers/wuwei/c0968cca10554fa12567d48be6f932bf4418dbe1/src/wu.lisp | lisp | +=========================================================================+
| |
| -license.php |
| |
| Permission is hereby granted, free of charge, to any person obtaining |
| a copy of this software and associated documentation files (the |
| without limitation the rights to use, copy, modify, merge, publish, |
| the following conditions: |
| |
| The above copyright notice and this permission notice shall be included |
| |
| 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 |
| TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE |
| SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. |
+=========================================================================+
Provide slightly higher-level functions for the common case, to make
cleaner looking web code.
Publish an explict URL, body is wrapped in lamda, response generation, HTML
+++ Could extend URL to be list of url + options (eg content-type)
As above, A continuation that returns HTML (ajax-continuation by default returns javascript)
OPTIONS are passed to AJAX-CONTINUATION
Body is wrapped in HTML macro
Generate a sequential series of actions, each a continuation of the next (eg a web progn).
Each clause is of the form (<options> . <body>), options are passed to wu-continuation.
Clauses refer to the next page via (-next-).
For an example, see examples/arc-challenge.lisp
Note: this is something you probably never really want to do in a real web app. I wrote this in response
the options. | (in-package :wu)
| Copyright ( c ) 2009 - 2011 and CollabRx , Inc |
| Released under the MIT Open Source License |
| " Software " ) , to deal in the Software without restriction , including |
| distribute , sublicense , and/or sell copies of the Software , and to |
| permit persons to whom the Software is furnished to do so , subject to |
| in all copies or substantial portions of the Software . |
| THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , |
| CLAIM , DAMAGES OR OTHER LIABILITY , WHETHER IN AN ACTION OF CONTRACT , |
(defmacro wu-publish (url &body body)
`(publish :path ,url :content-type "text/html"
:function #'(lambda (req ent)
(with-http-response-and-body (req ent)
(html
,@body)))))
(defmacro wu-continuation (options &body body)
`(ajax-continuation (:content-type "text/html" ,@options )
(html
,@body)))
to the ARC challenge . If you DID , you 'd probably want to enable the back button by putting : keep t in
(defmacro wu-conversation (first &body rest)
do n't feel sad , it only took me the better part of a day to get this quoting right !
(html ,@(cdr first))))
(defmacro wu-conversation-1 (first &body rest)
(when first
`(macrolet ((-next- () `(wu-conversation-1 ,@',rest)))
(wu-continuation ,(car first)
(html ,@(cdr first))))))
|
8381c93982c91930e5df66a4faaf8607a5c8157157b87a9c564a115f7967131b | polysemy-research/polysemy-zoo | More.hs | # LANGUAGE RecursiveDo #
module Polysemy.Reader.More
(
module Polysemy.Reader
-- * Interpretations
, runReaderFixSem
) where
import Polysemy
import Polysemy.Reader
import Polysemy.Fixpoint
------------------------------------------------------------------------------
-- | Runs a 'Reader' effect by running a monadic action /once/, after the
-- 'Sem' has completed, and then providing the result to each request
-- recursively.
runReaderFixSem :: forall i r a
. Member Fixpoint r
=> Sem r i
-> Sem (Reader i ': r) a
-> Sem r a
runReaderFixSem m sem = do
rec
a <- runReader i sem
i <- m
return a
# INLINE runReaderFixSem #
| null | https://raw.githubusercontent.com/polysemy-research/polysemy-zoo/eb0ce40e4d3b9757ede851a3450c05cc42949b49/src/Polysemy/Reader/More.hs | haskell | * Interpretations
----------------------------------------------------------------------------
| Runs a 'Reader' effect by running a monadic action /once/, after the
'Sem' has completed, and then providing the result to each request
recursively. | # LANGUAGE RecursiveDo #
module Polysemy.Reader.More
(
module Polysemy.Reader
, runReaderFixSem
) where
import Polysemy
import Polysemy.Reader
import Polysemy.Fixpoint
runReaderFixSem :: forall i r a
. Member Fixpoint r
=> Sem r i
-> Sem (Reader i ': r) a
-> Sem r a
runReaderFixSem m sem = do
rec
a <- runReader i sem
i <- m
return a
# INLINE runReaderFixSem #
|
65901388297f3e87ada790318ad065a8e51fd659c1f1ee623f7b1c6a2671892b | jimrthy/frereth | session.clj | (ns tracker.model.session
(:require
[clojure.pprint :refer [pprint]]
[clojure.spec.alpha :as s]
[com.fulcrologic.fulcro.server.api-middleware :as fmw]
[com.wsscode.pathom.connect :as pc :refer [defresolver defmutation]]
[datomic.api :as d]
[ghostwheel.core :refer [>defn => | ?]]
[tracker.model.free-database :as db]
[taoensso.timbre :as log]))
(defresolver current-session-resolver [env input]
{::pc/output [{::current-session [:session/valid? :account/name]}]}
(let [{:keys [account/name session/valid?]} (get-in env [:ring/request :session])]
(if valid?
(do
(log/info name "already logged in!")
{::current-session {:session/valid? true :account/name name}})
{::current-session {:session/valid? false}})))
(defn response-updating-session
"Uses `mutation-response` as the actual return value for a mutation, but also stores the data into the (cookie-based) session."
[mutation-env mutation-response]
(let [existing-session (some-> mutation-env :ring/request :session)]
(fmw/augment-response
mutation-response
(fn [resp]
(let [new-session (merge existing-session mutation-response)]
(assoc resp :session new-session))))))
(defmutation login [env {:keys [username password]}]
{::pc/output [:session/valid? :account/name]}
(log/info "Authenticating" username "based around" (keys env) "in"
(with-out-str (pprint env)))
(let [{expected-email :email
expected-password :password
:as credentials} (db/bad-credentials-retrieval db/db-uri username)]
(log/info "Credentials:" credentials)
(if (and (= username expected-email) (= password expected-password))
(response-updating-session env
{:session/valid? true
:account/name username})
(do
(log/error "Invalid credentials supplied for" username)
(throw (ex-info "Invalid credentials" {:username username}))))))
(defmutation logout [env params]
{::pc/output [:session/valid?]}
(response-updating-session env {:session/valid? false :account/name ""}))
(defmutation signup! [env {:keys [email password]}]
{::pc/output [:signup/result]}
(db/bad-create-account! env email password)
{:signup/result "OK"})
(def resolvers [current-session-resolver login logout signup!])
| null | https://raw.githubusercontent.com/jimrthy/frereth/e1c4a5c031355ff1ff3bb60741eb03dff2377e1d/apps/racing/sonic-forces/tracker/src/main/tracker/model/session.clj | clojure | (ns tracker.model.session
(:require
[clojure.pprint :refer [pprint]]
[clojure.spec.alpha :as s]
[com.fulcrologic.fulcro.server.api-middleware :as fmw]
[com.wsscode.pathom.connect :as pc :refer [defresolver defmutation]]
[datomic.api :as d]
[ghostwheel.core :refer [>defn => | ?]]
[tracker.model.free-database :as db]
[taoensso.timbre :as log]))
(defresolver current-session-resolver [env input]
{::pc/output [{::current-session [:session/valid? :account/name]}]}
(let [{:keys [account/name session/valid?]} (get-in env [:ring/request :session])]
(if valid?
(do
(log/info name "already logged in!")
{::current-session {:session/valid? true :account/name name}})
{::current-session {:session/valid? false}})))
(defn response-updating-session
"Uses `mutation-response` as the actual return value for a mutation, but also stores the data into the (cookie-based) session."
[mutation-env mutation-response]
(let [existing-session (some-> mutation-env :ring/request :session)]
(fmw/augment-response
mutation-response
(fn [resp]
(let [new-session (merge existing-session mutation-response)]
(assoc resp :session new-session))))))
(defmutation login [env {:keys [username password]}]
{::pc/output [:session/valid? :account/name]}
(log/info "Authenticating" username "based around" (keys env) "in"
(with-out-str (pprint env)))
(let [{expected-email :email
expected-password :password
:as credentials} (db/bad-credentials-retrieval db/db-uri username)]
(log/info "Credentials:" credentials)
(if (and (= username expected-email) (= password expected-password))
(response-updating-session env
{:session/valid? true
:account/name username})
(do
(log/error "Invalid credentials supplied for" username)
(throw (ex-info "Invalid credentials" {:username username}))))))
(defmutation logout [env params]
{::pc/output [:session/valid?]}
(response-updating-session env {:session/valid? false :account/name ""}))
(defmutation signup! [env {:keys [email password]}]
{::pc/output [:signup/result]}
(db/bad-create-account! env email password)
{:signup/result "OK"})
(def resolvers [current-session-resolver login logout signup!])
| |
e80e1ac0bdf8fbe7d766c6f44b8c200258bb3176c3a08dffd01be24c10e30fa0 | kind2-mc/kind2 | C2I.mli | This file is part of the Kind 2 model checker .
Copyright ( c ) 2015 by the Board of Trustees of the University of Iowa
Licensed under the Apache License , Version 2.0 ( the " License " ) ; you
may not use this file except in compliance with the License . You
may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing , software
distributed under the License is distributed on an " AS IS " BASIS ,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or
implied . See the License for the specific language governing
permissions and limitations under the License .
Copyright (c) 2015 by the Board of Trustees of the University of Iowa
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.
*)
(** C2I is a machine-learning-based invariant generation technique.
See documentation in source file for more details. *)
val main: 'a InputSystem.t -> Analysis.param -> TransSys.t -> unit
val on_exit: TransSys.t option -> unit
Local Variables :
compile - command : " make -C .. -k "
tuareg - interactive - program : " ./kind2.top -I ./_build -I / SExpr "
indent - tabs - mode : nil
End :
Local Variables:
compile-command: "make -C .. -k"
tuareg-interactive-program: "./kind2.top -I ./_build -I ./_build/SExpr"
indent-tabs-mode: nil
End:
*)
| null | https://raw.githubusercontent.com/kind2-mc/kind2/c601470eb68af9bd3b88828b04dbcdbd6bd6bbf5/src/c2i/C2I.mli | ocaml | * C2I is a machine-learning-based invariant generation technique.
See documentation in source file for more details. | This file is part of the Kind 2 model checker .
Copyright ( c ) 2015 by the Board of Trustees of the University of Iowa
Licensed under the Apache License , Version 2.0 ( the " License " ) ; you
may not use this file except in compliance with the License . You
may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing , software
distributed under the License is distributed on an " AS IS " BASIS ,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or
implied . See the License for the specific language governing
permissions and limitations under the License .
Copyright (c) 2015 by the Board of Trustees of the University of Iowa
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.
*)
val main: 'a InputSystem.t -> Analysis.param -> TransSys.t -> unit
val on_exit: TransSys.t option -> unit
Local Variables :
compile - command : " make -C .. -k "
tuareg - interactive - program : " ./kind2.top -I ./_build -I / SExpr "
indent - tabs - mode : nil
End :
Local Variables:
compile-command: "make -C .. -k"
tuareg-interactive-program: "./kind2.top -I ./_build -I ./_build/SExpr"
indent-tabs-mode: nil
End:
*)
|
746221f22e683eb12ecbd74e40ce5e135a2a9fba48ab295227b0b7539b249d60 | TrustInSoft/tis-kernel | builtins_lib_tis_aux.ml | (**************************************************************************)
(* *)
This file is part of .
(* *)
Copyright ( C ) 2016 - 2017
(* *)
is released under GPLv2
(* *)
(**************************************************************************)
open Abstract_interp
let register_builtin = Builtins.register_builtin
let dkey = Value_parameters.register_category "imprecision"
(** Strongly set the C variable errno if it is declared and
if the received value is nonzero *)
let optionally_set_errno errno state =
if Ival.is_zero errno
then state
else
let errno = Ival.diff_if_one errno Ival.zero in
try
let scope = Cil_types.VGlobal in
let errno_var = Globals.Vars.find_from_astinfo "__FC_errno" scope in
let errno_loc = Locations.loc_of_varinfo errno_var in
Eval_op.add_binding ~exact:true ~with_alarms:CilE.warn_none_mode
state errno_loc (Cvalue.V.inject_ival errno)
FIXME
state
(* Helper functions for detection of overlap of memory locations *)
type overlap_status_t = Overlap | Separated | MayOverlap
exception Overlap_status_uncertain
let overlap_status_loc_bits ?(size_in_bytes = false)
loc1 size_loc1 loc2 size_loc2 =
This function checks for overlaps in two zones defined by a Location_Bits
* and a size in bits ( or bytes )
* and a size in bits (or bytes) *)
let bit_units = if size_in_bytes then Bit_utils.sizeofchar() else Int.one in
try (
let min1,max1 = Ival.min_and_max size_loc1 in
let min2,max2 = Ival.min_and_max size_loc2 in
let get_int_base i =
let v = match i with
|Some m -> m
|None -> raise Overlap_status_uncertain
in
let v = Int.mul bit_units v in
Int_Base.inject v
in
let max1_bits = get_int_base max1 in
let max2_bits = get_int_base max2 in
let min1_bits = get_int_base min1 in
let min2_bits = get_int_base min2 in
let is_zero n = Int_Base.equal Int_Base.zero n in
if is_zero max1_bits || is_zero max2_bits
then
Separated
else
begin
(* check separation in worst-case scenario to guarantee no overlap *)
let location1_max = Locations.make_loc loc1 max1_bits in
let location2_max = Locations.make_loc loc2 max2_bits in
let loc1_zone_max =
Locations.enumerate_valid_bits ~for_writing:false location1_max
in
let loc2_zone_max =
Locations.enumerate_valid_bits ~for_writing:true location2_max
in
if not (Locations.Zone.valid_intersects loc1_zone_max loc2_zone_max)
then (* Separation is certain *)
Separated
else
begin
We can not guarantee separation . We try to guarantee
overlap . If anything goes wrong , it means we ca n't and therefore
the status is MayOverlap
overlap. If anything goes wrong, it means we can't and therefore
the status is MayOverlap *)
if one of the locations has more than one base , we can not
guarantee overlap . The Not_found exception will be caught
guarantee overlap. The Not_found exception will be caught *)
let _, offsets1 = Locations.Location_Bits.find_lonely_key loc1 in
let _, offsets2 = Locations.Location_Bits.find_lonely_key loc2 in
from now on we can suppose that each location has only one base ,
* and it must be the same for both locations as otherwise we would
* have already returned Separated
* and it must be the same for both locations as otherwise we would
* have already returned Separated *)
let min_offsets1, max_offsets1 = Ival.min_and_max offsets1 in
let min_offsets2, max_offsets2 = Ival.min_and_max offsets2 in
let min_offsets1 = match min_offsets1 with
|None -> Int.zero | Some m -> Int.max m Int.zero in
let min_offsets2 = match min_offsets2 with
|None -> Int.zero | Some m -> Int.max m Int.zero in
let max_offsets1 = match max_offsets1 with
|None -> Int.zero | Some m -> Int.max m Int.zero in
let max_offsets2 = match max_offsets2 with
|None -> Int.zero | Some m -> Int.max m Int.zero in
let size1 = Int_Base.project min1_bits in
let size2 = Int_Base.project min2_bits in
(* (leq3 a b c) is true iff a <= b <= c *)
let leq3 a b c = (Int.le a b) && (Int.le b c) in
if (
leq3 min_offsets1 max_offsets2 (Int.add min_offsets1 size1)
||leq3 max_offsets2 min_offsets1 (Int.add max_offsets2 size2)
) &&
( leq3 min_offsets2 max_offsets1 (Int.add min_offsets2 size2)
||leq3 max_offsets1 min_offsets2 (Int.add max_offsets1 size1)
)
then
Overlap
else
MayOverlap
end;
end
) with
(* from find_lonely_key or find_lonely_binding *)
| Not_found | Overlap_status_uncertain -> MayOverlap
Checks overlap status of two loc_bytes
let overlap_status_loc_bytes loc1 size1 loc2 size2 =
(* sizes should be in bytes *)
let loc1_bits = Locations.loc_bytes_to_loc_bits loc1
and loc2_bits = Locations.loc_bytes_to_loc_bits loc2
in
overlap_status_loc_bits ~size_in_bytes:true loc1_bits size1 loc2_bits size2
Checks overlap status of two locations ( which can have different sizes )
let overlap_status_loc loc1 loc2 =
let size1 = Ival.inject_singleton (Int_Base.project (Locations.loc_size loc1))
in
let size2 = Ival.inject_singleton (Int_Base.project (Locations.loc_size loc2))
in
let loc1bits =
Locations.loc_bytes_to_loc_bits (Locations.loc_to_loc_without_size loc1)
in
let loc2bits =
Locations.loc_bytes_to_loc_bits (Locations.loc_to_loc_without_size loc2)
in
overlap_status_loc_bits loc1bits size1 loc2bits size2
* Returns a location of size sizeof_loc
( the size is ( ) } by default ) .
(the size is {Bit_utils.sizeofchar ()} by default).*)
let location_of_cvalue ?(sizeof_loc=(Bit_utils.sizeofchar ())) cvalue =
Locations.make_loc
(Locations.loc_bytes_to_loc_bits cvalue)
(Int_Base.inject sizeof_loc)
let additional_ptr_validity_check_for_size_zero
~for_writing
~size
(exp, cvalue, _) =
let location = location_of_cvalue cvalue in
if Cvalue.V.contains_zero size &&
not (Locations.is_valid ~for_writing location) then begin
Value_parameters.warning ~current:true
"@[invalid pointer %a.@ assert(%a is a valid pointer for %s)@]%t"
Cvalue.V.pretty cvalue
Cil_printer.pp_exp exp
(if for_writing then "writing" else "reading")
Value_util.pp_callstack
end
module StringAndArrayUtilities = struct
(* The pseudo-infinity length for string operations. *)
let str_infinity = Integer.two_power_of_int 120
Character Strings / Wide Character Strings
type libc_character_kind =
| Character
| WideCharacter
let get_character_bits string_kind =
let char_typ =
match string_kind with
| Character -> Cil.charType
| WideCharacter -> Cil.(theMachine.wcharType)
in
Int_Base.project (Bit_utils.sizeof char_typ)
TODO : Required for abstract_strcpy and abstract_strcmp
to avoid a forward reference .
to avoid a forward reference. *)
module Strlen = struct
type strlen_alarm_context = {
strlen_alarm_invalid_string : unit -> unit
}
type abstract_strlen_type =
(character_bits:Integer.t ->
max:Abstract_interp.Int.t ->
emit_alarm:strlen_alarm_context ->
Locations.Location_Bytes.t -> Cvalue.Model.t -> Ival.t)
let abstract_strlen_ref : abstract_strlen_type ref =
ref (fun ~character_bits ~max ~emit_alarm str state ->
ignore(character_bits, max, emit_alarm, str, state);
assert false)
let get_abstract_strlen () = !abstract_strlen_ref
end
end
(*
Local Variables:
compile-command: "make -C ../../../../.."
End:
*)
| null | https://raw.githubusercontent.com/TrustInSoft/tis-kernel/748d28baba90c03c0f5f4654d2e7bb47dfbe4e7d/src/plugins/value/domains/cvalue/builtins_lib_tis_aux.ml | ocaml | ************************************************************************
************************************************************************
* Strongly set the C variable errno if it is declared and
if the received value is nonzero
Helper functions for detection of overlap of memory locations
check separation in worst-case scenario to guarantee no overlap
Separation is certain
(leq3 a b c) is true iff a <= b <= c
from find_lonely_key or find_lonely_binding
sizes should be in bytes
The pseudo-infinity length for string operations.
Local Variables:
compile-command: "make -C ../../../../.."
End:
| This file is part of .
Copyright ( C ) 2016 - 2017
is released under GPLv2
open Abstract_interp
let register_builtin = Builtins.register_builtin
let dkey = Value_parameters.register_category "imprecision"
let optionally_set_errno errno state =
if Ival.is_zero errno
then state
else
let errno = Ival.diff_if_one errno Ival.zero in
try
let scope = Cil_types.VGlobal in
let errno_var = Globals.Vars.find_from_astinfo "__FC_errno" scope in
let errno_loc = Locations.loc_of_varinfo errno_var in
Eval_op.add_binding ~exact:true ~with_alarms:CilE.warn_none_mode
state errno_loc (Cvalue.V.inject_ival errno)
FIXME
state
type overlap_status_t = Overlap | Separated | MayOverlap
exception Overlap_status_uncertain
let overlap_status_loc_bits ?(size_in_bytes = false)
loc1 size_loc1 loc2 size_loc2 =
This function checks for overlaps in two zones defined by a Location_Bits
* and a size in bits ( or bytes )
* and a size in bits (or bytes) *)
let bit_units = if size_in_bytes then Bit_utils.sizeofchar() else Int.one in
try (
let min1,max1 = Ival.min_and_max size_loc1 in
let min2,max2 = Ival.min_and_max size_loc2 in
let get_int_base i =
let v = match i with
|Some m -> m
|None -> raise Overlap_status_uncertain
in
let v = Int.mul bit_units v in
Int_Base.inject v
in
let max1_bits = get_int_base max1 in
let max2_bits = get_int_base max2 in
let min1_bits = get_int_base min1 in
let min2_bits = get_int_base min2 in
let is_zero n = Int_Base.equal Int_Base.zero n in
if is_zero max1_bits || is_zero max2_bits
then
Separated
else
begin
let location1_max = Locations.make_loc loc1 max1_bits in
let location2_max = Locations.make_loc loc2 max2_bits in
let loc1_zone_max =
Locations.enumerate_valid_bits ~for_writing:false location1_max
in
let loc2_zone_max =
Locations.enumerate_valid_bits ~for_writing:true location2_max
in
if not (Locations.Zone.valid_intersects loc1_zone_max loc2_zone_max)
Separated
else
begin
We can not guarantee separation . We try to guarantee
overlap . If anything goes wrong , it means we ca n't and therefore
the status is MayOverlap
overlap. If anything goes wrong, it means we can't and therefore
the status is MayOverlap *)
if one of the locations has more than one base , we can not
guarantee overlap . The Not_found exception will be caught
guarantee overlap. The Not_found exception will be caught *)
let _, offsets1 = Locations.Location_Bits.find_lonely_key loc1 in
let _, offsets2 = Locations.Location_Bits.find_lonely_key loc2 in
from now on we can suppose that each location has only one base ,
* and it must be the same for both locations as otherwise we would
* have already returned Separated
* and it must be the same for both locations as otherwise we would
* have already returned Separated *)
let min_offsets1, max_offsets1 = Ival.min_and_max offsets1 in
let min_offsets2, max_offsets2 = Ival.min_and_max offsets2 in
let min_offsets1 = match min_offsets1 with
|None -> Int.zero | Some m -> Int.max m Int.zero in
let min_offsets2 = match min_offsets2 with
|None -> Int.zero | Some m -> Int.max m Int.zero in
let max_offsets1 = match max_offsets1 with
|None -> Int.zero | Some m -> Int.max m Int.zero in
let max_offsets2 = match max_offsets2 with
|None -> Int.zero | Some m -> Int.max m Int.zero in
let size1 = Int_Base.project min1_bits in
let size2 = Int_Base.project min2_bits in
let leq3 a b c = (Int.le a b) && (Int.le b c) in
if (
leq3 min_offsets1 max_offsets2 (Int.add min_offsets1 size1)
||leq3 max_offsets2 min_offsets1 (Int.add max_offsets2 size2)
) &&
( leq3 min_offsets2 max_offsets1 (Int.add min_offsets2 size2)
||leq3 max_offsets1 min_offsets2 (Int.add max_offsets1 size1)
)
then
Overlap
else
MayOverlap
end;
end
) with
| Not_found | Overlap_status_uncertain -> MayOverlap
Checks overlap status of two loc_bytes
let overlap_status_loc_bytes loc1 size1 loc2 size2 =
let loc1_bits = Locations.loc_bytes_to_loc_bits loc1
and loc2_bits = Locations.loc_bytes_to_loc_bits loc2
in
overlap_status_loc_bits ~size_in_bytes:true loc1_bits size1 loc2_bits size2
Checks overlap status of two locations ( which can have different sizes )
let overlap_status_loc loc1 loc2 =
let size1 = Ival.inject_singleton (Int_Base.project (Locations.loc_size loc1))
in
let size2 = Ival.inject_singleton (Int_Base.project (Locations.loc_size loc2))
in
let loc1bits =
Locations.loc_bytes_to_loc_bits (Locations.loc_to_loc_without_size loc1)
in
let loc2bits =
Locations.loc_bytes_to_loc_bits (Locations.loc_to_loc_without_size loc2)
in
overlap_status_loc_bits loc1bits size1 loc2bits size2
* Returns a location of size sizeof_loc
( the size is ( ) } by default ) .
(the size is {Bit_utils.sizeofchar ()} by default).*)
let location_of_cvalue ?(sizeof_loc=(Bit_utils.sizeofchar ())) cvalue =
Locations.make_loc
(Locations.loc_bytes_to_loc_bits cvalue)
(Int_Base.inject sizeof_loc)
let additional_ptr_validity_check_for_size_zero
~for_writing
~size
(exp, cvalue, _) =
let location = location_of_cvalue cvalue in
if Cvalue.V.contains_zero size &&
not (Locations.is_valid ~for_writing location) then begin
Value_parameters.warning ~current:true
"@[invalid pointer %a.@ assert(%a is a valid pointer for %s)@]%t"
Cvalue.V.pretty cvalue
Cil_printer.pp_exp exp
(if for_writing then "writing" else "reading")
Value_util.pp_callstack
end
module StringAndArrayUtilities = struct
let str_infinity = Integer.two_power_of_int 120
Character Strings / Wide Character Strings
type libc_character_kind =
| Character
| WideCharacter
let get_character_bits string_kind =
let char_typ =
match string_kind with
| Character -> Cil.charType
| WideCharacter -> Cil.(theMachine.wcharType)
in
Int_Base.project (Bit_utils.sizeof char_typ)
TODO : Required for abstract_strcpy and abstract_strcmp
to avoid a forward reference .
to avoid a forward reference. *)
module Strlen = struct
type strlen_alarm_context = {
strlen_alarm_invalid_string : unit -> unit
}
type abstract_strlen_type =
(character_bits:Integer.t ->
max:Abstract_interp.Int.t ->
emit_alarm:strlen_alarm_context ->
Locations.Location_Bytes.t -> Cvalue.Model.t -> Ival.t)
let abstract_strlen_ref : abstract_strlen_type ref =
ref (fun ~character_bits ~max ~emit_alarm str state ->
ignore(character_bits, max, emit_alarm, str, state);
assert false)
let get_abstract_strlen () = !abstract_strlen_ref
end
end
|
392e07dba32c7269cbc1af523a6208df29238066159fc10d4ab6a5979a40c788 | nuprl/gradual-typing-performance | norm.rkt | #lang racket/base
(module norm typed/racket
(define-type Point%
(Class (field [x Real] [y Real])))
(define-type Point (Instance Point%))
(: norm (-> Point Real))
(define (norm p)
(+ (abs (get-field x p))
(abs (get-field y p))))
(provide Point norm))
(module user racket
(require (submod ".." norm))
(norm 3))
(require 'user)
| null | https://raw.githubusercontent.com/nuprl/gradual-typing-performance/35442b3221299a9cadba6810573007736b0d65d4/paper/jfp-2016/src/norm.rkt | racket | #lang racket/base
(module norm typed/racket
(define-type Point%
(Class (field [x Real] [y Real])))
(define-type Point (Instance Point%))
(: norm (-> Point Real))
(define (norm p)
(+ (abs (get-field x p))
(abs (get-field y p))))
(provide Point norm))
(module user racket
(require (submod ".." norm))
(norm 3))
(require 'user)
| |
8bc7fe7eea9e1eb7241fdebe09de976219d8e4378da7f49222e22ad74d70c4f9 | re-path/studio | animate.cljs | (ns repath.studio.tools.animate
(:require [repath.studio.tools.base :as tools]))
(derive :animate ::tools/animation)
(defmethod tools/properties :animate [] {:description "The SVG <animate> element provides a way to animate an attribute of an element over time."
:attrs [:href
:attributeType
:attributeName
:begin
:end
:dur
:min
:max
:restart
:repeatCount
:repeatDur
:fill
:calcMode
:values
:keyTimes
:keySplines
:from
:to
:by
:autoReverse
:accelerate
:decelerate
:additive
:accumulate
:id
:class]}) | null | https://raw.githubusercontent.com/re-path/studio/0841056ef12689cffb226a99a9dfe58d7f2c4778/src/repath/studio/tools/animate.cljs | clojure | (ns repath.studio.tools.animate
(:require [repath.studio.tools.base :as tools]))
(derive :animate ::tools/animation)
(defmethod tools/properties :animate [] {:description "The SVG <animate> element provides a way to animate an attribute of an element over time."
:attrs [:href
:attributeType
:attributeName
:begin
:end
:dur
:min
:max
:restart
:repeatCount
:repeatDur
:fill
:calcMode
:values
:keyTimes
:keySplines
:from
:to
:by
:autoReverse
:accelerate
:decelerate
:additive
:accumulate
:id
:class]}) | |
52da4a635387faf9775853f3f11ecda0f132f5024542517a82df82e16290c9a7 | avsm/mirage-duniverse | pkg.ml | #user "topfind"
#require "topkg-jbuilder.auto"
| null | https://raw.githubusercontent.com/avsm/mirage-duniverse/983e115ff5a9fb37e3176c373e227e9379f0d777/ocaml_modules/webmachine/pkg/pkg.ml | ocaml | #user "topfind"
#require "topkg-jbuilder.auto"
| |
c532366b20aa9fe3a33ca6aebf7e34b0a168f47f316f627668d7fae40f374e5f | tnelson/Forge | smallsigstest.rkt | #lang forge
/*$
; there is a sig node, with a field graph of type (set node). (we are not defaulting to one; might in fact later require explicit set/one)
(declare-sig node ((graph node)))
( declare - one - sig left )
( declare - one - sig right )
acyclic graph ( side node : has acyclic relation pred ; is this faster ? )
(fact (no (& iden (^ graph))))
find instance with a path of length 2
(pred pathlen2 (some ([n1 node] [n2 node]) (in n1 (join n2 (^ graph)))))
( run " DAG " )
run command currently has " lower int bound " ; anywhere from 5 - 6 nodes
(run "DAG with path length >= 2" (some ([n1 node] [n2 node]) (in n1 (join n2 (^ graph)))) ((node 3 4)))
*/
| null | https://raw.githubusercontent.com/tnelson/Forge/1687cba0ebdb598c29c51845d43c98a459d0588f/forge/examples/smallsigstest.rkt | racket | there is a sig node, with a field graph of type (set node). (we are not defaulting to one; might in fact later require explicit set/one)
is this faster ? )
anywhere from 5 - 6 nodes | #lang forge
/*$
(declare-sig node ((graph node)))
( declare - one - sig left )
( declare - one - sig right )
(fact (no (& iden (^ graph))))
find instance with a path of length 2
(pred pathlen2 (some ([n1 node] [n2 node]) (in n1 (join n2 (^ graph)))))
( run " DAG " )
(run "DAG with path length >= 2" (some ([n1 node] [n2 node]) (in n1 (join n2 (^ graph)))) ((node 3 4)))
*/
|
261b8b51c1bacf0724bff9f2584d48117ed0859bdea89c04805516eba4889ad7 | danielsz/certificaat | server.clj | (ns certificaat.plugins.server
(:require
[certificaat.kung-fu :as k]
[immutant.web :refer [run stop]]))
(def stop-server stop )
(defn handler [challenges]
(fn [request]
(loop [xs challenges]
(if (= (:uri request) (str "/.well-known/acme-challenge/" (.getToken (first xs))))
{:status 200
:headers {"Content-Type" "text/plain"}
:body (.getAuthorization (first xs))}
(recur (rest xs))))))
(defn start-server [handler port]
(let [server (run handler {:port port})]
server))
(defn listen
([options]
(let [challenges (k/get-challenges options)]
(listen challenges options)))
([challenges {{{port :port enabled :enabled} :httpd} :plugins :as options}]
(when enabled
(let [handler (handler challenges)]
(start-server handler port)))))
| null | https://raw.githubusercontent.com/danielsz/certificaat/955429f6303da9a687cf636d93437281f43ddb71/src/certificaat/plugins/server.clj | clojure | (ns certificaat.plugins.server
(:require
[certificaat.kung-fu :as k]
[immutant.web :refer [run stop]]))
(def stop-server stop )
(defn handler [challenges]
(fn [request]
(loop [xs challenges]
(if (= (:uri request) (str "/.well-known/acme-challenge/" (.getToken (first xs))))
{:status 200
:headers {"Content-Type" "text/plain"}
:body (.getAuthorization (first xs))}
(recur (rest xs))))))
(defn start-server [handler port]
(let [server (run handler {:port port})]
server))
(defn listen
([options]
(let [challenges (k/get-challenges options)]
(listen challenges options)))
([challenges {{{port :port enabled :enabled} :httpd} :plugins :as options}]
(when enabled
(let [handler (handler challenges)]
(start-server handler port)))))
| |
d60d6928258674a6b74b11737d4824fd8d5eea8712cdb96fb5cb1cee2ac504af | democracyworks/imbarcode | characters.cljc | (ns imbarcode.characters
"Handles conversion from codewords to characters.
See section 3.2.5 of the IMb spec."
(:require [imbarcode.character-conversion :refer [codeword->character]]))
(defn codewords->characters-base [codewords]
(map codeword->character codewords))
(defn adjust-character [character fcs-bit]
(if (zero? fcs-bit)
character
(bit-xor character 0x1fff)))
(defn adjust-characters [characters fcs]
(map (fn [char bit-idx]
(adjust-character char (bit-and fcs (bit-shift-left 1 bit-idx))))
characters (range 10)))
(defn codewords->characters [codewords fcs]
(-> codewords
codewords->characters-base
(adjust-characters fcs)
vec))
| null | https://raw.githubusercontent.com/democracyworks/imbarcode/8b4a821a42238c0bd62f5e19fbb51462741b4b9f/src/cljc/imbarcode/characters.cljc | clojure | (ns imbarcode.characters
"Handles conversion from codewords to characters.
See section 3.2.5 of the IMb spec."
(:require [imbarcode.character-conversion :refer [codeword->character]]))
(defn codewords->characters-base [codewords]
(map codeword->character codewords))
(defn adjust-character [character fcs-bit]
(if (zero? fcs-bit)
character
(bit-xor character 0x1fff)))
(defn adjust-characters [characters fcs]
(map (fn [char bit-idx]
(adjust-character char (bit-and fcs (bit-shift-left 1 bit-idx))))
characters (range 10)))
(defn codewords->characters [codewords fcs]
(-> codewords
codewords->characters-base
(adjust-characters fcs)
vec))
| |
bb2e93ed25bf5c790272795802252a9c8e50a9e2485bef003fdab3ed16aa8956 | nklein/Roto-Mortar | types.lisp | (defpackage :x3d
(:use :common-lisp)
(:export #:x3d-property
#:name
#:x3d-name
#:value
#:x3d-value
#:x3d-mesh
#:texture-coordinate-indexes
#:x3d-texture-coordinate-indexes
#:coordinate-indexes
#:x3d-coordinate-indexes
#:coordinates
#:x3d-coordinates
#:original-coordinates
#:x3d-original-coordinates
#:texture-coordinates
#:x3d-texture-coordinates
#:x3d-geometry-object
#:translation
#:x3d-translation
#:scale
#:x3d-scale
#:rotation
#:x3d-rotation
#:diffuse-color
#:x3d-diffuse-color
#:specular-color
#:x3d-specular-color
#:shininess
#:x3d-shininess
#:transparency
#:x3d-transparency
#:texture
#:x3d-texture
#:meshes
#:x3d-meshes
#:x3d-x3d
#:meta-properties
#:x3d-meta-properties
#:ground-color
#:x3d-ground-color
#:sky-color
#:x3d-sky-color
#:shape-list
#:x3d-shape-list
#:get-png-as-texture-id
#:parse))
(in-package :x3d)
(defclass x3d-property ()
((name :initarg :name :accessor x3d-name :type string)
(value :initarg :value :accessor x3d-value :type string)))
(defclass x3d-mesh ()
((texture-coordinate-indexes :initarg :texture-coordinate-indexes :accessor x3d-texture-coordinate-indexes :type list)
(coordinate-indexes :initarg :coordinate-indexes :accessor x3d-coordinate-indexes :type list)
(coordinates :initarg :coordinates :accessor x3d-coordinates :type list)
(original-coordinates :initarg :original-coordinates :accessor x3d-original-coordinates :type list)
(texture-coordinates :initarg :texture-coordinates :accessor x3d-texture-coordinates :type list)))
(defclass x3d-geometry-object ()
((translation :initarg :translation :accessor x3d-translation :type string)
(scale :initarg :scale :accessor x3d-scale :type string)
(rotation :initarg :rotation :accessor x3d-rotation :type string)
(diffuse-color :initarg :diffuse-color :accessor x3d-diffuse-color :type string)
(specular-color :initarg :specular-color :accessor x3d-specular-color :type string)
(shininess :initarg :shininess :accessor x3d-shininess :type real)
(transparency :initarg :transparency :accessor x3d-transparency :type real)
(texture :initarg :texture :accessor x3d-texture :type integer)
(meshes :initarg :meshes :accessor x3d-meshes :type list :initform nil)))
(defclass x3d-x3d ()
((meta-properties :initarg :meta-properties :accessor x3d-meta-properties :type list :initform nil)
(ground-color :initarg :ground-color :accessor x3d-ground-color :type string)
(sky-color :initarg :sky-color :accessor x3d-sky-color :type string)
(shape-list :initarg :shape-list :accessor x3d-shape-list :type list :initform nil)))
| null | https://raw.githubusercontent.com/nklein/Roto-Mortar/dd3bb63aa6a377ee4b359921c8d46a94d2847227/src/types.lisp | lisp | (defpackage :x3d
(:use :common-lisp)
(:export #:x3d-property
#:name
#:x3d-name
#:value
#:x3d-value
#:x3d-mesh
#:texture-coordinate-indexes
#:x3d-texture-coordinate-indexes
#:coordinate-indexes
#:x3d-coordinate-indexes
#:coordinates
#:x3d-coordinates
#:original-coordinates
#:x3d-original-coordinates
#:texture-coordinates
#:x3d-texture-coordinates
#:x3d-geometry-object
#:translation
#:x3d-translation
#:scale
#:x3d-scale
#:rotation
#:x3d-rotation
#:diffuse-color
#:x3d-diffuse-color
#:specular-color
#:x3d-specular-color
#:shininess
#:x3d-shininess
#:transparency
#:x3d-transparency
#:texture
#:x3d-texture
#:meshes
#:x3d-meshes
#:x3d-x3d
#:meta-properties
#:x3d-meta-properties
#:ground-color
#:x3d-ground-color
#:sky-color
#:x3d-sky-color
#:shape-list
#:x3d-shape-list
#:get-png-as-texture-id
#:parse))
(in-package :x3d)
(defclass x3d-property ()
((name :initarg :name :accessor x3d-name :type string)
(value :initarg :value :accessor x3d-value :type string)))
(defclass x3d-mesh ()
((texture-coordinate-indexes :initarg :texture-coordinate-indexes :accessor x3d-texture-coordinate-indexes :type list)
(coordinate-indexes :initarg :coordinate-indexes :accessor x3d-coordinate-indexes :type list)
(coordinates :initarg :coordinates :accessor x3d-coordinates :type list)
(original-coordinates :initarg :original-coordinates :accessor x3d-original-coordinates :type list)
(texture-coordinates :initarg :texture-coordinates :accessor x3d-texture-coordinates :type list)))
(defclass x3d-geometry-object ()
((translation :initarg :translation :accessor x3d-translation :type string)
(scale :initarg :scale :accessor x3d-scale :type string)
(rotation :initarg :rotation :accessor x3d-rotation :type string)
(diffuse-color :initarg :diffuse-color :accessor x3d-diffuse-color :type string)
(specular-color :initarg :specular-color :accessor x3d-specular-color :type string)
(shininess :initarg :shininess :accessor x3d-shininess :type real)
(transparency :initarg :transparency :accessor x3d-transparency :type real)
(texture :initarg :texture :accessor x3d-texture :type integer)
(meshes :initarg :meshes :accessor x3d-meshes :type list :initform nil)))
(defclass x3d-x3d ()
((meta-properties :initarg :meta-properties :accessor x3d-meta-properties :type list :initform nil)
(ground-color :initarg :ground-color :accessor x3d-ground-color :type string)
(sky-color :initarg :sky-color :accessor x3d-sky-color :type string)
(shape-list :initarg :shape-list :accessor x3d-shape-list :type list :initform nil)))
| |
3f900736545130f552ba430ef7b9b81c0e839638f710ae69ed7d1bc09b25b256 | MLstate/opalang | jsWalk.ml |
Copyright © 2011 MLstate
This file is part of .
is free software : you can redistribute it and/or modify it under the
terms of the GNU Affero General Public License , version 3 , as published by
the Free Software Foundation .
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 . If not , see < / > .
Copyright © 2011 MLstate
This file is part of Opa.
Opa is free software: you can redistribute it and/or modify it under the
terms of the GNU Affero General Public License, version 3, as published by
the Free Software Foundation.
Opa 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 Opa. If not, see </>.
*)
*
@author
Traversing JsAst
@author Mathieu Barbin
*)
module List = BaseList
module J = JsAst
let foldmapA traA traB acc e =
match e with
| J.Je_this _ ->
acc, e
| J.Je_ident (_, _) ->
acc, e
| J.Je_array (label, list) ->
let acc, flist = List.fold_left_map_stable traA acc list in
acc,
if list == flist then e else
J.Je_array (label, flist)
| J.Je_comma (label, list, last) ->
let acc, flist = List.fold_left_map_stable traA acc list in
let acc, flast = traA acc last in
acc,
if list == flist && last == flast then e else
J.Je_comma (label, flist, flast)
| J.Je_object (label, fields) ->
let fmap acc ((field, b) as c) =
let acc, fb = traA acc b in
acc,
if b == fb then c else
(field, fb)
in
let acc, ffields = List.fold_left_map_stable fmap acc fields in
acc,
if fields == ffields then e else
J.Je_object (label, ffields)
| J.Je_string (_, _, _) ->
acc, e
| J.Je_num (_, _) ->
acc, e
| J.Je_null _ ->
acc, e
| J.Je_undefined _ ->
acc, e
| J.Je_bool (_, _) ->
acc, e
| J.Je_regexp _ ->
acc, e
| J.Je_function (label, ident, params, body) ->
let acc, fbody = List.fold_left_map_stable traB acc body in
acc,
if body == fbody then e else
J.Je_function (label, ident, params, fbody)
| J.Je_dot (label, expr, field) ->
let acc, fexpr = traA acc expr in
acc,
if expr == fexpr then e else
J.Je_dot (label, fexpr, field)
| J.Je_unop (label, op, expr) ->
let acc, fexpr = traA acc expr in
acc,
if expr == fexpr then e else
J.Je_unop (label, op, fexpr)
| J.Je_binop (label, op, expr1, expr2) ->
let acc, fexpr1 = traA acc expr1 in
let acc, fexpr2 = traA acc expr2 in
acc,
if expr1 == fexpr1 && expr2 == fexpr2 then e else
J.Je_binop (label, op, fexpr1, fexpr2)
| J.Je_cond (label, cond, then_, else_) ->
let acc, fcond = traA acc cond in
let acc, fthen_ = traA acc then_ in
let acc, felse_ = traA acc else_ in
acc,
if cond == fcond && then_ == fthen_ && else_ == felse_ then e else
J.Je_cond (label, fcond, fthen_, felse_)
| J.Je_call (label, fun_, args, pure) ->
let acc, ffun_ = traA acc fun_ in
let acc, fargs = List.fold_left_map_stable traA acc args in
acc,
if fun_ == ffun_ && args == fargs then e else
J.Je_call (label, ffun_, fargs, pure)
| J.Je_new (label, obj, args) ->
let acc, fobj = traA acc obj in
let acc, fargs = List.fold_left_map_stable traA acc args in
acc,
if obj == fobj && args == fargs then e else
J.Je_new (label, fobj, fargs)
| J.Je_hole (_, _) ->
acc, e
| J.Je_runtime _ ->
acc, e
let foldmapB traB traA acc e =
match e with
| J.Js_var (_, _, None) ->
acc, e
| J.Js_var (label, ident, Some expr) ->
let acc, fexpr = traA acc expr in
acc,
if expr == fexpr then e else
J.Js_var (label, ident, Some fexpr)
| J.Js_function (label, ident, params, body) ->
let acc, fbody = List.fold_left_map_stable traB acc body in
acc,
if body == fbody then e else
J.Js_function (label, ident, params, fbody)
| J.Js_return (label, expr) ->
let acc, fexpr = Option.foldmap_stable traA acc expr in
acc,
if expr == fexpr then e else
J.Js_return (label, fexpr)
| J.Js_continue (_, _) ->
acc, e
| J.Js_break (_, _) ->
acc, e
| J.Js_switch (label, expr, cases, default) ->
let fmap acc ((expr, stat) as c) =
let acc, fexpr = traA acc expr in
let acc, fstat = traB acc stat in
acc,
if expr == fexpr && stat == fstat then c else
(fexpr, fstat)
in
let acc, fexpr = traA acc expr in
let acc, fcases = List.fold_left_map_stable fmap acc cases in
let acc, fdefault = Option.foldmap_stable traB acc default in
acc,
if expr == fexpr && cases == fcases && default == fdefault then e else
J.Js_switch (label, fexpr, fcases, fdefault)
| J.Js_if (label, cond, then_, else_) ->
let acc, fcond = traA acc cond in
let acc, fthen_ = traB acc then_ in
let acc, felse_ = Option.foldmap_stable traB acc else_ in
acc,
if cond == fcond && then_ == fthen_ && else_ == felse_ then e else
J.Js_if (label, fcond, fthen_, felse_)
| J.Js_throw (label, expr) ->
let acc, fexpr = traA acc expr in
acc,
if expr == fexpr then e else
J.Js_throw (label, fexpr)
| J.Js_expr (label, expr) ->
let acc, fexpr = traA acc expr in
acc,
if expr == fexpr then e else
J.Js_expr (label, fexpr)
| J.Js_trycatch (label, body, catches, finally) ->
let fmap acc ((ident, expr, stat) as t) =
let acc, fexpr = Option.foldmap_stable traA acc expr in
let acc, fstat = traB acc stat in
acc,
if expr == fexpr && stat = fstat then t else
(ident, fexpr, fstat)
in
let acc, fbody = traB acc body in
let acc, fcatches = List.fold_left_map_stable fmap acc catches in
let acc, ffinally = Option.foldmap_stable traB acc finally in
acc,
if body == fbody && catches == fcatches && finally == ffinally then e else
J.Js_trycatch (label, fbody, fcatches, ffinally)
| J.Js_for (label, init, cond, incr, body) ->
let acc, finit = Option.foldmap_stable traA acc init in
let acc, fcond = Option.foldmap_stable traA acc cond in
let acc, fincr = Option.foldmap_stable traA acc incr in
let acc, fbody = traB acc body in
acc,
if init == finit && cond == fcond && incr == fincr && body == fbody then e else
J.Js_for (label, finit, fcond, fincr, fbody)
| J.Js_forin (label, lhs, rhs, body) ->
let acc, flhs = traA acc lhs in
let acc, frhs = traA acc rhs in
let acc, fbody = traB acc body in
acc,
if flhs == lhs && frhs == rhs && fbody == body then e else
J.Js_forin (label, flhs, frhs, fbody)
| J.Js_dowhile (label, body, cond) ->
let acc, fbody = traB acc body in
let acc, fcond = traA acc cond in
acc,
if body == fbody && cond == fcond then e else
J.Js_dowhile (label, fbody, fcond)
| J.Js_while (label, cond, body) ->
let acc, fcond = traA acc cond in
let acc, fbody = traB acc body in
acc,
if cond == fcond && body == fbody then e else
J.Js_while (label, fcond, fbody)
| J.Js_block (label, body) ->
let acc, fbody = List.fold_left_map_stable traB acc body in
acc,
if body == fbody then e else
J.Js_block (label, fbody)
| J.Js_with (label, expr, body) ->
let acc, fexpr = traA acc expr in
let acc, fbody = traB acc body in
acc,
if expr == fexpr && body == fbody then e else
J.Js_with (label, fexpr, fbody)
| J.Js_label (label, string, stmt) ->
let acc, fstmt = traB acc stmt in
acc,
if stmt == fstmt then e else
J.Js_label (label, string, fstmt)
| J.Js_empty _ ->
acc, e
| J.Js_comment (_, _) ->
acc, e
module AB : TraverseInterface.AB
with type 'a tA = JsAst.expr
constraint 'a = 'b * 'c * 'd
and type 'a tB = JsAst.statement
constraint 'a = 'b * 'c * 'd
=
struct
type 'a tA = JsAst.expr
constraint 'a = 'b * 'c * 'd
type 'a tB = JsAst.statement
constraint 'a = 'b * 'c * 'd
let foldmapA = foldmapA
let foldmapB = foldmapB
let mapA traA traB e = Traverse.Unoptimized.mapAB foldmapA traA traB e
let mapB traB traA e = Traverse.Unoptimized.mapAB foldmapB traB traA e
let iterA traA traB e = Traverse.Unoptimized.iterAB foldmapA traA traB e
let iterB traB traA e = Traverse.Unoptimized.iterAB foldmapB traB traA e
let foldA traA traB acc e = Traverse.Unoptimized.foldAB foldmapA traA traB acc e
let foldB traB traA acc e = Traverse.Unoptimized.foldAB foldmapB traB traA acc e
end
module T = Traverse.MakeAB(AB)
module TExpr = T.A
module TStatement = T.B
module Expr = T.AinA
module Statement = T.BinB
module ExprInStatement = T.AinB
module StatementInExpr = T.BinA
module OnlyExpr = T.OnlyA
module OnlyStatement = T.OnlyB
(* Refreshing the annotations of an expression or a statement *)
module Refresh =
struct
let aux_expr expr = J.JNewAnnot.expr expr (Annot.next ())
let aux_stm stm = J.JNewAnnot.stm stm (Annot.next ())
let expr expr = TExpr.map aux_expr aux_stm expr
let stm stm = TStatement.map aux_stm aux_expr stm
end
| null | https://raw.githubusercontent.com/MLstate/opalang/424b369160ce693406cece6ac033d75d85f5df4f/compiler/jslang/jsWalk.ml | ocaml | Refreshing the annotations of an expression or a statement |
Copyright © 2011 MLstate
This file is part of .
is free software : you can redistribute it and/or modify it under the
terms of the GNU Affero General Public License , version 3 , as published by
the Free Software Foundation .
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 . If not , see < / > .
Copyright © 2011 MLstate
This file is part of Opa.
Opa is free software: you can redistribute it and/or modify it under the
terms of the GNU Affero General Public License, version 3, as published by
the Free Software Foundation.
Opa 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 Opa. If not, see </>.
*)
*
@author
Traversing JsAst
@author Mathieu Barbin
*)
module List = BaseList
module J = JsAst
let foldmapA traA traB acc e =
match e with
| J.Je_this _ ->
acc, e
| J.Je_ident (_, _) ->
acc, e
| J.Je_array (label, list) ->
let acc, flist = List.fold_left_map_stable traA acc list in
acc,
if list == flist then e else
J.Je_array (label, flist)
| J.Je_comma (label, list, last) ->
let acc, flist = List.fold_left_map_stable traA acc list in
let acc, flast = traA acc last in
acc,
if list == flist && last == flast then e else
J.Je_comma (label, flist, flast)
| J.Je_object (label, fields) ->
let fmap acc ((field, b) as c) =
let acc, fb = traA acc b in
acc,
if b == fb then c else
(field, fb)
in
let acc, ffields = List.fold_left_map_stable fmap acc fields in
acc,
if fields == ffields then e else
J.Je_object (label, ffields)
| J.Je_string (_, _, _) ->
acc, e
| J.Je_num (_, _) ->
acc, e
| J.Je_null _ ->
acc, e
| J.Je_undefined _ ->
acc, e
| J.Je_bool (_, _) ->
acc, e
| J.Je_regexp _ ->
acc, e
| J.Je_function (label, ident, params, body) ->
let acc, fbody = List.fold_left_map_stable traB acc body in
acc,
if body == fbody then e else
J.Je_function (label, ident, params, fbody)
| J.Je_dot (label, expr, field) ->
let acc, fexpr = traA acc expr in
acc,
if expr == fexpr then e else
J.Je_dot (label, fexpr, field)
| J.Je_unop (label, op, expr) ->
let acc, fexpr = traA acc expr in
acc,
if expr == fexpr then e else
J.Je_unop (label, op, fexpr)
| J.Je_binop (label, op, expr1, expr2) ->
let acc, fexpr1 = traA acc expr1 in
let acc, fexpr2 = traA acc expr2 in
acc,
if expr1 == fexpr1 && expr2 == fexpr2 then e else
J.Je_binop (label, op, fexpr1, fexpr2)
| J.Je_cond (label, cond, then_, else_) ->
let acc, fcond = traA acc cond in
let acc, fthen_ = traA acc then_ in
let acc, felse_ = traA acc else_ in
acc,
if cond == fcond && then_ == fthen_ && else_ == felse_ then e else
J.Je_cond (label, fcond, fthen_, felse_)
| J.Je_call (label, fun_, args, pure) ->
let acc, ffun_ = traA acc fun_ in
let acc, fargs = List.fold_left_map_stable traA acc args in
acc,
if fun_ == ffun_ && args == fargs then e else
J.Je_call (label, ffun_, fargs, pure)
| J.Je_new (label, obj, args) ->
let acc, fobj = traA acc obj in
let acc, fargs = List.fold_left_map_stable traA acc args in
acc,
if obj == fobj && args == fargs then e else
J.Je_new (label, fobj, fargs)
| J.Je_hole (_, _) ->
acc, e
| J.Je_runtime _ ->
acc, e
let foldmapB traB traA acc e =
match e with
| J.Js_var (_, _, None) ->
acc, e
| J.Js_var (label, ident, Some expr) ->
let acc, fexpr = traA acc expr in
acc,
if expr == fexpr then e else
J.Js_var (label, ident, Some fexpr)
| J.Js_function (label, ident, params, body) ->
let acc, fbody = List.fold_left_map_stable traB acc body in
acc,
if body == fbody then e else
J.Js_function (label, ident, params, fbody)
| J.Js_return (label, expr) ->
let acc, fexpr = Option.foldmap_stable traA acc expr in
acc,
if expr == fexpr then e else
J.Js_return (label, fexpr)
| J.Js_continue (_, _) ->
acc, e
| J.Js_break (_, _) ->
acc, e
| J.Js_switch (label, expr, cases, default) ->
let fmap acc ((expr, stat) as c) =
let acc, fexpr = traA acc expr in
let acc, fstat = traB acc stat in
acc,
if expr == fexpr && stat == fstat then c else
(fexpr, fstat)
in
let acc, fexpr = traA acc expr in
let acc, fcases = List.fold_left_map_stable fmap acc cases in
let acc, fdefault = Option.foldmap_stable traB acc default in
acc,
if expr == fexpr && cases == fcases && default == fdefault then e else
J.Js_switch (label, fexpr, fcases, fdefault)
| J.Js_if (label, cond, then_, else_) ->
let acc, fcond = traA acc cond in
let acc, fthen_ = traB acc then_ in
let acc, felse_ = Option.foldmap_stable traB acc else_ in
acc,
if cond == fcond && then_ == fthen_ && else_ == felse_ then e else
J.Js_if (label, fcond, fthen_, felse_)
| J.Js_throw (label, expr) ->
let acc, fexpr = traA acc expr in
acc,
if expr == fexpr then e else
J.Js_throw (label, fexpr)
| J.Js_expr (label, expr) ->
let acc, fexpr = traA acc expr in
acc,
if expr == fexpr then e else
J.Js_expr (label, fexpr)
| J.Js_trycatch (label, body, catches, finally) ->
let fmap acc ((ident, expr, stat) as t) =
let acc, fexpr = Option.foldmap_stable traA acc expr in
let acc, fstat = traB acc stat in
acc,
if expr == fexpr && stat = fstat then t else
(ident, fexpr, fstat)
in
let acc, fbody = traB acc body in
let acc, fcatches = List.fold_left_map_stable fmap acc catches in
let acc, ffinally = Option.foldmap_stable traB acc finally in
acc,
if body == fbody && catches == fcatches && finally == ffinally then e else
J.Js_trycatch (label, fbody, fcatches, ffinally)
| J.Js_for (label, init, cond, incr, body) ->
let acc, finit = Option.foldmap_stable traA acc init in
let acc, fcond = Option.foldmap_stable traA acc cond in
let acc, fincr = Option.foldmap_stable traA acc incr in
let acc, fbody = traB acc body in
acc,
if init == finit && cond == fcond && incr == fincr && body == fbody then e else
J.Js_for (label, finit, fcond, fincr, fbody)
| J.Js_forin (label, lhs, rhs, body) ->
let acc, flhs = traA acc lhs in
let acc, frhs = traA acc rhs in
let acc, fbody = traB acc body in
acc,
if flhs == lhs && frhs == rhs && fbody == body then e else
J.Js_forin (label, flhs, frhs, fbody)
| J.Js_dowhile (label, body, cond) ->
let acc, fbody = traB acc body in
let acc, fcond = traA acc cond in
acc,
if body == fbody && cond == fcond then e else
J.Js_dowhile (label, fbody, fcond)
| J.Js_while (label, cond, body) ->
let acc, fcond = traA acc cond in
let acc, fbody = traB acc body in
acc,
if cond == fcond && body == fbody then e else
J.Js_while (label, fcond, fbody)
| J.Js_block (label, body) ->
let acc, fbody = List.fold_left_map_stable traB acc body in
acc,
if body == fbody then e else
J.Js_block (label, fbody)
| J.Js_with (label, expr, body) ->
let acc, fexpr = traA acc expr in
let acc, fbody = traB acc body in
acc,
if expr == fexpr && body == fbody then e else
J.Js_with (label, fexpr, fbody)
| J.Js_label (label, string, stmt) ->
let acc, fstmt = traB acc stmt in
acc,
if stmt == fstmt then e else
J.Js_label (label, string, fstmt)
| J.Js_empty _ ->
acc, e
| J.Js_comment (_, _) ->
acc, e
module AB : TraverseInterface.AB
with type 'a tA = JsAst.expr
constraint 'a = 'b * 'c * 'd
and type 'a tB = JsAst.statement
constraint 'a = 'b * 'c * 'd
=
struct
type 'a tA = JsAst.expr
constraint 'a = 'b * 'c * 'd
type 'a tB = JsAst.statement
constraint 'a = 'b * 'c * 'd
let foldmapA = foldmapA
let foldmapB = foldmapB
let mapA traA traB e = Traverse.Unoptimized.mapAB foldmapA traA traB e
let mapB traB traA e = Traverse.Unoptimized.mapAB foldmapB traB traA e
let iterA traA traB e = Traverse.Unoptimized.iterAB foldmapA traA traB e
let iterB traB traA e = Traverse.Unoptimized.iterAB foldmapB traB traA e
let foldA traA traB acc e = Traverse.Unoptimized.foldAB foldmapA traA traB acc e
let foldB traB traA acc e = Traverse.Unoptimized.foldAB foldmapB traB traA acc e
end
module T = Traverse.MakeAB(AB)
module TExpr = T.A
module TStatement = T.B
module Expr = T.AinA
module Statement = T.BinB
module ExprInStatement = T.AinB
module StatementInExpr = T.BinA
module OnlyExpr = T.OnlyA
module OnlyStatement = T.OnlyB
module Refresh =
struct
let aux_expr expr = J.JNewAnnot.expr expr (Annot.next ())
let aux_stm stm = J.JNewAnnot.stm stm (Annot.next ())
let expr expr = TExpr.map aux_expr aux_stm expr
let stm stm = TStatement.map aux_stm aux_expr stm
end
|
32dfa51901b619004c5d0490f01cca2baa14210df128dfa625a1c4777af4c870 | spurious/sagittarius-scheme-mirror | mqtt.scm | -*- mode : scheme ; coding : utf-8 -*-
;;;
;;; net/mq/mqtt.scm - MQTT v3.1.1
;;;
Copyright ( c ) 2010 - 2014 < >
;;;
;;; Redistribution and use in source and binary forms, with or without
;;; modification, are permitted provided that the following conditions
;;; are met:
;;;
;;; 1. Redistributions of source code must retain the above copyright
;;; notice, this list of conditions and the following disclaimer.
;;;
;;; 2. Redistributions in binary form must reproduce the above copyright
;;; notice, this list of conditions and the following disclaimer in the
;;; documentation and/or other materials provided with the distribution.
;;;
;;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
" AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT
;;; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
;;; A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
;;; OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED
;;; TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
;;; PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT ( INCLUDING
;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
;;;
(library (net mq mqtt)
(export :all)
(import (net mq mqtt client)))
| null | https://raw.githubusercontent.com/spurious/sagittarius-scheme-mirror/53f104188934109227c01b1e9a9af5312f9ce997/sitelib/net/mq/mqtt.scm | scheme | coding : utf-8 -*-
net/mq/mqtt.scm - MQTT v3.1.1
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
| Copyright ( c ) 2010 - 2014 < >
" AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT
SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED
LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT ( INCLUDING
(library (net mq mqtt)
(export :all)
(import (net mq mqtt client)))
|
f0533d7cdc52fa907a7af9c0be556592fe505ab565194160621dd8aaef258749 | danlentz/clj-uuid | api_test.clj | (ns clj-uuid.api-test
(:refer-clojure :exclude [uuid?])
(:require [clojure.test :refer :all]
[clj-uuid :refer :all])
(:import
(java.lang IllegalArgumentException)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Protocol Tests
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(deftest check-unique-identifier-protocol
(testing "v0 uuid protocol..."
(let [tmpid +null+]
(is (= (get-word-high tmpid) 0))
(is (= (get-word-low tmpid) 0))
(is (= (null? tmpid) true))
(is (= (seq (to-byte-array tmpid)) [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]))
(is (= (hash-code tmpid) 0))
(is (= (get-version tmpid) 0))
(is (= (to-string tmpid) "00000000-0000-0000-0000-000000000000"))
(is (=
(to-urn-string tmpid)
"urn:uuid:00000000-0000-0000-0000-000000000000"))
(is (= (get-time-low tmpid) 0))
(is (= (get-time-mid tmpid) 0))
(is (= (get-time-high tmpid) 0))
(is (= (get-clk-low tmpid) 0))
(is (= (get-clk-high tmpid) 0))
(is (= (get-node-id tmpid) 0))
(is (= (get-timestamp tmpid) nil))))
(testing "v1 uuid protocol..."
(let [tmpid +namespace-x500+]
(is (= (get-word-high tmpid) 7757371281853190609))
(is (= (get-word-low tmpid) -9172705715073830712))
(is (= (null? tmpid) false))
(is (=
(seq (to-byte-array tmpid))
[107 -89 -72 20 -99 -83 17 -47 -128 -76 0 -64 79 -44 48 -56]))
(is (= (hash-code tmpid) 963287501))
(is (= (get-version tmpid) 1))
(is (= (to-string tmpid) "6ba7b814-9dad-11d1-80b4-00c04fd430c8"))
(is (=
(to-urn-string tmpid)
"urn:uuid:6ba7b814-9dad-11d1-80b4-00c04fd430c8"))
(is (= (get-time-low tmpid) 1806153748))
(is (= (get-time-mid tmpid) 40365))
(is (= (get-time-high tmpid) 4561))
(is (= (get-clk-low tmpid) 128))
(is (= (get-clk-high tmpid) 180))
(is (= (get-node-id tmpid) 825973027016))
(is (= (get-timestamp tmpid) 131059232331511828))))
(testing "v3 uuid protocol..."
(let [tmpid (java.util.UUID/fromString
"d9c53a66-fde2-3d04-b5ad-dce3848df07e")]
(is (= (get-word-high tmpid) -2754731383046652668))
(is (= (get-word-low tmpid) -5355381512134070146))
(is (= (null? tmpid) false))
(is (=
(seq (to-byte-array tmpid))
[-39 -59 58 102 -3 -30 61 4 -75 -83 -36 -29 -124 -115 -16 126]))
(is (= (hash-code tmpid) 352791551))
(is (= (get-version tmpid) 3))
(is (= (to-string tmpid) "d9c53a66-fde2-3d04-b5ad-dce3848df07e"))
(is (=
(to-urn-string tmpid)
"urn:uuid:d9c53a66-fde2-3d04-b5ad-dce3848df07e"))
(is (= (get-time-low tmpid) 3653581414))
(is (= (get-time-mid tmpid) 64994))
(is (= (get-time-high tmpid) 15620))
(is (= (get-clk-low tmpid) 181))
(is (= (get-clk-high tmpid) 173))
(is (= (get-node-id tmpid) 242869739581566))
(is (= (get-timestamp tmpid) nil))))
(testing "v4 uuid protocol..."
(let [tmpid
(java.util.UUID/fromString "3eb1e29a-4747-4a7d-8e40-94e245f57dc0")]
(is (= (get-word-high tmpid) 4517641053478013565))
(is (= (get-word-low tmpid) -8196387622257066560))
(is (= (null? tmpid) false))
(is (=
(seq (to-byte-array tmpid))
[62 -79 -30 -102 71 71 74 125 -114 64 -108 -30 69 -11 125 -64]))
(is (= (hash-code tmpid) -1304215099))
(is (= (get-version tmpid) 4))
(is (= (to-string tmpid) "3eb1e29a-4747-4a7d-8e40-94e245f57dc0"))
(is (=
(to-urn-string tmpid)
"urn:uuid:3eb1e29a-4747-4a7d-8e40-94e245f57dc0"))
(is (= (get-time-low tmpid) 1051845274))
(is (= (get-time-mid tmpid) 18247))
(is (= (get-time-high tmpid) 19069))
(is (= (get-clk-low tmpid) 142))
(is (= (get-clk-high tmpid) 64))
(is (= (get-node-id tmpid) 163699557236160))
(is (= (get-timestamp tmpid) nil)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Predicate Tests
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(deftest check-predicates
(testing "string predicates..."
(is (uuid-string? (to-string (v4))))
(is (uuid-urn-string? (to-urn-string (v4))))))
(deftest nil-test
(testing "Calling certain functions/methods on nil returns nil"
(testing "UUIDNameBytes"
(is (thrown? IllegalArgumentException (as-byte-array nil))))
(testing "UUIDable"
(is (thrown? IllegalArgumentException (as-uuid nil)))
(is (false? (uuidable? nil))))
(testing "UUIDRfc4122"
(is (false? (uuid? nil))))
(is (false? (uuid-string? nil)))
(is (false? (uuid-urn-string? nil)))
(is (false? (uuid-vec? nil)))))
(deftest byte-array-round-trip-test
(testing "round-trip via byte-array"
(let [uuid #uuid "4787199e-c0e2-4609-b5b8-284f2b7d117d"]
(is (= uuid (as-uuid (as-byte-array uuid)))))))
| null | https://raw.githubusercontent.com/danlentz/clj-uuid/5cbd2662dd3fce90ec0b8354e794ca6a1b5ce44c/test/clj_uuid/api_test.clj | clojure |
Protocol Tests
Predicate Tests
| (ns clj-uuid.api-test
(:refer-clojure :exclude [uuid?])
(:require [clojure.test :refer :all]
[clj-uuid :refer :all])
(:import
(java.lang IllegalArgumentException)))
(deftest check-unique-identifier-protocol
(testing "v0 uuid protocol..."
(let [tmpid +null+]
(is (= (get-word-high tmpid) 0))
(is (= (get-word-low tmpid) 0))
(is (= (null? tmpid) true))
(is (= (seq (to-byte-array tmpid)) [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]))
(is (= (hash-code tmpid) 0))
(is (= (get-version tmpid) 0))
(is (= (to-string tmpid) "00000000-0000-0000-0000-000000000000"))
(is (=
(to-urn-string tmpid)
"urn:uuid:00000000-0000-0000-0000-000000000000"))
(is (= (get-time-low tmpid) 0))
(is (= (get-time-mid tmpid) 0))
(is (= (get-time-high tmpid) 0))
(is (= (get-clk-low tmpid) 0))
(is (= (get-clk-high tmpid) 0))
(is (= (get-node-id tmpid) 0))
(is (= (get-timestamp tmpid) nil))))
(testing "v1 uuid protocol..."
(let [tmpid +namespace-x500+]
(is (= (get-word-high tmpid) 7757371281853190609))
(is (= (get-word-low tmpid) -9172705715073830712))
(is (= (null? tmpid) false))
(is (=
(seq (to-byte-array tmpid))
[107 -89 -72 20 -99 -83 17 -47 -128 -76 0 -64 79 -44 48 -56]))
(is (= (hash-code tmpid) 963287501))
(is (= (get-version tmpid) 1))
(is (= (to-string tmpid) "6ba7b814-9dad-11d1-80b4-00c04fd430c8"))
(is (=
(to-urn-string tmpid)
"urn:uuid:6ba7b814-9dad-11d1-80b4-00c04fd430c8"))
(is (= (get-time-low tmpid) 1806153748))
(is (= (get-time-mid tmpid) 40365))
(is (= (get-time-high tmpid) 4561))
(is (= (get-clk-low tmpid) 128))
(is (= (get-clk-high tmpid) 180))
(is (= (get-node-id tmpid) 825973027016))
(is (= (get-timestamp tmpid) 131059232331511828))))
(testing "v3 uuid protocol..."
(let [tmpid (java.util.UUID/fromString
"d9c53a66-fde2-3d04-b5ad-dce3848df07e")]
(is (= (get-word-high tmpid) -2754731383046652668))
(is (= (get-word-low tmpid) -5355381512134070146))
(is (= (null? tmpid) false))
(is (=
(seq (to-byte-array tmpid))
[-39 -59 58 102 -3 -30 61 4 -75 -83 -36 -29 -124 -115 -16 126]))
(is (= (hash-code tmpid) 352791551))
(is (= (get-version tmpid) 3))
(is (= (to-string tmpid) "d9c53a66-fde2-3d04-b5ad-dce3848df07e"))
(is (=
(to-urn-string tmpid)
"urn:uuid:d9c53a66-fde2-3d04-b5ad-dce3848df07e"))
(is (= (get-time-low tmpid) 3653581414))
(is (= (get-time-mid tmpid) 64994))
(is (= (get-time-high tmpid) 15620))
(is (= (get-clk-low tmpid) 181))
(is (= (get-clk-high tmpid) 173))
(is (= (get-node-id tmpid) 242869739581566))
(is (= (get-timestamp tmpid) nil))))
(testing "v4 uuid protocol..."
(let [tmpid
(java.util.UUID/fromString "3eb1e29a-4747-4a7d-8e40-94e245f57dc0")]
(is (= (get-word-high tmpid) 4517641053478013565))
(is (= (get-word-low tmpid) -8196387622257066560))
(is (= (null? tmpid) false))
(is (=
(seq (to-byte-array tmpid))
[62 -79 -30 -102 71 71 74 125 -114 64 -108 -30 69 -11 125 -64]))
(is (= (hash-code tmpid) -1304215099))
(is (= (get-version tmpid) 4))
(is (= (to-string tmpid) "3eb1e29a-4747-4a7d-8e40-94e245f57dc0"))
(is (=
(to-urn-string tmpid)
"urn:uuid:3eb1e29a-4747-4a7d-8e40-94e245f57dc0"))
(is (= (get-time-low tmpid) 1051845274))
(is (= (get-time-mid tmpid) 18247))
(is (= (get-time-high tmpid) 19069))
(is (= (get-clk-low tmpid) 142))
(is (= (get-clk-high tmpid) 64))
(is (= (get-node-id tmpid) 163699557236160))
(is (= (get-timestamp tmpid) nil)))))
(deftest check-predicates
(testing "string predicates..."
(is (uuid-string? (to-string (v4))))
(is (uuid-urn-string? (to-urn-string (v4))))))
(deftest nil-test
(testing "Calling certain functions/methods on nil returns nil"
(testing "UUIDNameBytes"
(is (thrown? IllegalArgumentException (as-byte-array nil))))
(testing "UUIDable"
(is (thrown? IllegalArgumentException (as-uuid nil)))
(is (false? (uuidable? nil))))
(testing "UUIDRfc4122"
(is (false? (uuid? nil))))
(is (false? (uuid-string? nil)))
(is (false? (uuid-urn-string? nil)))
(is (false? (uuid-vec? nil)))))
(deftest byte-array-round-trip-test
(testing "round-trip via byte-array"
(let [uuid #uuid "4787199e-c0e2-4609-b5b8-284f2b7d117d"]
(is (= uuid (as-uuid (as-byte-array uuid)))))))
|
4392bb735378c28679fc3d1b1920f8e11281d8240d4397e79174f3ff45c177c8 | abdulapopoola/SICPBook | Ex2.69.scm | #lang planet neil/sicp
;;Requires code from earlier exercises
(define (successive-merge pairs)
(if (= (length pairs) 1)
(car pairs)
(successive-merge
(adjoin-set (make-code-tree (car pairs)
(cadr pairs))
(cddr pairs)))))
| null | https://raw.githubusercontent.com/abdulapopoola/SICPBook/c8a0228ebf66d9c1ddc5ef1fcc1d05d8684f090a/Chapter%202/2.3/Ex2.69.scm | scheme | Requires code from earlier exercises | #lang planet neil/sicp
(define (successive-merge pairs)
(if (= (length pairs) 1)
(car pairs)
(successive-merge
(adjoin-set (make-code-tree (car pairs)
(cadr pairs))
(cddr pairs)))))
|
e9c529233168b249f0193003199cbda411d8f2577ae5e54f17c607dfc0dea30b | mbillingr/lisp-in-small-pieces | ase-interpreter.scm | (import (builtin core)
(libs utils)
(libs book))
(define (evaluate e r s k)
(if (atom? e)
(if (symbol? e)
(evaluate-variable e r s k)
(evaluate-quote e r s k))
(case (car e)
((quote) (evaluate-quote (cadr e) r s k))
((if) (evalua-if (cadr e) (caddr e) (cadddr e) r s k))
((begin) (evaluate-begin (cdr e) r s k))
((set!) (evaluate-set! (cadr e) (caddr e) r s k))
((lambda) (evaluate-lambda (cadr e) (cddr e) r s k))
(else (evaluate-application (car e) (cdr e) r s k)))))
(define (evaluate-if ec et ef r s k)
(evaluate ec r s
(lambda (v ss)
(evaluate ((v 'boolify) et ef) r ss k))))
(define (evaluate-begin e* r s k)
(if (pair? (cdr e*))
(evaluate (car e*) r s
(lambda (void ss)
(evaluate-begin (cdr e*) r ss k)))
(evaluate (car e*) r s k)))
(define (r.init id)
(wrong "No binding for id" id))
(define (update s a v)
(lambda (aa)
(if (eqv? a aa) v (s aa))))
(define (update* s a* v*)
;; assume (= (length a*) (length v*))
(if (pair? a*)
(update* (update s (car a*) (car v*)) (cdr a*) (cdr v*))
s))
(define (evaluate-variable n r s k)
(k (s (r n)) s))
(define (evaluate-set! n e r s k)
(evaluate e r s
(lambda (v ss)
(k v (update ss (r n) v)))))
(define (evaluate-application e e* r s k)
(define (evaluate-arguments e* r s k)
(if (pair? e*)
(evaluate (car e*) r s
(lambda (v ss)
(evaluate-arguments (cdr e*) r ss
(lambda (v* sss)
(k (cons v v*) sss)))))
(k '() s)))
(evaluate e r s
(lambda (f ss)
(evaluate-arguments e* r ss
(lambda (v* sss)
(if (eq? (f 'type) 'function)
((f 'behavior) v* sss k)
(wrong "Not a function" (car v*))))))))
(define (evaluate-lambda n* e* r s k)
(allocate 1 s
(lambda (a* ss)
(k (create-function
(car a*)
(lambda (v* s k)
(if (= (length n*) (length v*))
(allocate (length n*) s
(lambda (a* ss)
(evaluate-begin e*
(update* r n* a*)
(update* ss a* v*)
k)))
(wrong "Incorrect arity"))))
ss))))
(define (allocate n s q)
(if (> n 0)
(let ((a (new-location s)))
(allocate (- n 1)
(expand-store a s)
(lambda (a* ss)
(q (cons a a*) ss))))
(q '() s)))
(define (expand-store high-location s)
(update s 0 high-location))
(define (new-location s)
(+ 1 (s 0)))
(define s.init
(expand-store 0 (lambda (a) (wrong "No such address" a))))
(define the-empty-list
(lambda (msg)
(case msg
((type) 'null)
((boolify) (lambda (x y) x)))))
(define (create-boolean value)
(let ((combinator (if value (lambda (x y) x) (lambda (x y) y))))
(lambda (msg)
(case msg
((type) 'boolean)
((boolify) combinator)))))
(define (create-symbol v)
(lambda (msg)
(case msg
((type) 'symbol)
((name) v)
((boolify) (lambda (x y) x)))))
(define (create-number v)
(lambda (msg)
(case msg
((type) 'number)
((value) v)
((boolify) (lambda (x y) x)))))
(define (create-function tag behavior)
(lambda (msg)
(case msg
((type) 'function)
((boolify) (lambda (x y) x))
((tag) tag)
((behavior) behavior))))
(define (allocate-list v* s q)
(define (consify v* q)
(if (pair? v*)
(consify (cdr v*) (lambda (v ss)
(allocate-pair (car v*) v ss q)))
(q the-empty-list s)))
(consify v* q))
(define (allocate-pair a d s q)
(allocate 2 s
(lambda (a* ss)
(q (create-pair (car a*) (cadr a*))
(update (update ss (car a*) a) (cadr a*) d)))))
(define (create-pair a d)
(lambda (msg)
(case msg
((type) 'pair)
((boolify) (lambda (x y) x))
((set-car) (lambda (s v) (update s a v)))
((set-cdr) (lambda (s v) (update s d v)))
((car) a)
((cdr) d))))
(define s.global s.init)
(define r.global r.init)
(define (definitial name value)
(allocate 1 s.global
(lambda (a* ss)
(set! r.global (update r.global name (car a*)))
(set! s.global (update ss (car a*) value)))))
(define (defprimitive name value arity)
(definitial name
(allocate 1 s.global
(lambda (a* ss)
(set! s.global (expand-store (car a*) ss))
(create-function
(car a*)
(lambda (v* s k)
(if (= arity (length v*))
(value v* s k)
(wrong "Incorrect arity" name))))))))
(definitial 't (create-boolean #t))
(definitial 'f (create-boolean #f))
(definitial 'nil the-empty-list)
(definitial 'x the-empty-list)
(definitial 'y the-empty-list)
(definitial 'z the-empty-list)
(definitial 'foo the-empty-list)
(definitial 'bar the-empty-list)
(definitial 'fib the-empty-list)
(definitial 'fact the-empty-list)
(defprimitive '<=
(lambda (v* s k)
(if (and (eq? ((car v*) 'type) 'number)
(eq? ((cadr v*) 'type) 'number))
(k (create-boolean (<= ((car v*) 'value)
((cadr v*) 'value)))
s)
(wrong "<= requires numbers")))
2)
(defprimitive '*
(lambda (v* s k)
(if (and (eq? ((car v*) 'type) 'number)
(eq? ((cadr v*) 'type) 'number))
(k (create-number (* ((car v*) 'value)
((cadr v*) 'value)))
s)
(wrong "* requires numbers")))
2)
(defprimitive 'cons
(lambda (v* s k)
(allocate-pair (car v*) (cadr v*) s k))
2)
(defprimitive 'car
(lambda (v* s k)
(if (eq? ((car v*) 'type) 'pair)
(k (s ((car v*) 'car)) s)
(wrong "Not a pair" (car v*))))
1)
(defprimitive 'cdr
(lambda (v* s k)
(if (eq? ((car v*) 'type) 'pair)
(k (s ((car v*) 'cdr)) s)
(wrong "Not a pair" (car v*))))
1)
(defprimitive 'set-cdr
(lambda (v* s k)
(if (eq? ((car v*) 'type) 'pair)
(let ((pair (car v*)))
(k pair ((pair 'set-cdr) s (cadr v*))))
(wrong "Not a pair" (car v*))))
2)
(defprimitive 'set-car
(lambda (v* s k)
(if (eq? ((car v*) 'type) 'pair)
(let ((pair (car v*)))
(k pair ((pair 'set-car) s (cadr v*))))
(wrong "Not a pair" (car v*))))
2)
(defprimitive 'pair?
(lambda (v* s k)
(k (create-boolean (eq? ((car v*) 'type) 'pair)) s))
1)
(defprimitive 'eqv?
(lambda (v* s k)
(k (create-boolean
(if (eq? ((car v*) 'type) ((cadr v*) 'type))
(case ((car v*) 'type)
((null) #t)
((boolean)
(((car v*) 'boolify)
(((cadr v*) 'boolify) #t #f)
(((cadr v*) 'boolify) #f #t)))
((symbol)
(eq? ((car v*) 'name) ((cadr v*) 'name)))
((number)
(eq? ((car v*) 'value) ((cadr v*) 'value)))
((pair)
(and (= ((car v*) 'car) ((cadr v*) 'car))
(= ((car v*) 'cdr) ((cadr v*) 'cdr))))
((function)
(= ((car v*) 'tag) ((cadr v*) 'tag)))
(else #f))
#f))
s))
2)
(define (chapter4-interpreter)
(define (toplevel s)
(evaluate (read)
r.global
s
(lambda (v ss)
(display (transcode-back v ss))
(toplevel ss))))
(toplevel s.global))
(define (transcode-back v s)
(case (v 'type)
((null) '())
((boolean) ((v 'boolify) #t #f))
((symbol) (v 'name))
((string) (v 'chars))
((number) (v 'value))
((pair) (cons (transcode-back (s (v 'car)) s)
(transcode-back (s (v 'cdr)) s)))
((function) v)
(else (wrong "Unknown type" (v 'type)))))
(define (transcode c s q)
(cond ((null? c) (q the-empty-list s))
((boolean? c) (q (create-boolean c) s))
((symbol? c) (q (create-symbol c) s))
((string? c) (q (create-string c) s))
((number? c) (q (create-number c) s))
((pair? c)
(transcode (car c)
s
(lambda (a ss)
(transcode (cdr c)
ss
(lambda (d sss)
(allocate-pair a d sss q))))))))
(define (evaluate-quote c r s k)
(transcode c s k))
(chapter4-interpreter)
| null | https://raw.githubusercontent.com/mbillingr/lisp-in-small-pieces/b2b158dfa91dc95d75af4bd7d93f8df22219047e/04-side-effects/ase-interpreter.scm | scheme | assume (= (length a*) (length v*)) | (import (builtin core)
(libs utils)
(libs book))
(define (evaluate e r s k)
(if (atom? e)
(if (symbol? e)
(evaluate-variable e r s k)
(evaluate-quote e r s k))
(case (car e)
((quote) (evaluate-quote (cadr e) r s k))
((if) (evalua-if (cadr e) (caddr e) (cadddr e) r s k))
((begin) (evaluate-begin (cdr e) r s k))
((set!) (evaluate-set! (cadr e) (caddr e) r s k))
((lambda) (evaluate-lambda (cadr e) (cddr e) r s k))
(else (evaluate-application (car e) (cdr e) r s k)))))
(define (evaluate-if ec et ef r s k)
(evaluate ec r s
(lambda (v ss)
(evaluate ((v 'boolify) et ef) r ss k))))
(define (evaluate-begin e* r s k)
(if (pair? (cdr e*))
(evaluate (car e*) r s
(lambda (void ss)
(evaluate-begin (cdr e*) r ss k)))
(evaluate (car e*) r s k)))
(define (r.init id)
(wrong "No binding for id" id))
(define (update s a v)
(lambda (aa)
(if (eqv? a aa) v (s aa))))
(define (update* s a* v*)
(if (pair? a*)
(update* (update s (car a*) (car v*)) (cdr a*) (cdr v*))
s))
(define (evaluate-variable n r s k)
(k (s (r n)) s))
(define (evaluate-set! n e r s k)
(evaluate e r s
(lambda (v ss)
(k v (update ss (r n) v)))))
(define (evaluate-application e e* r s k)
(define (evaluate-arguments e* r s k)
(if (pair? e*)
(evaluate (car e*) r s
(lambda (v ss)
(evaluate-arguments (cdr e*) r ss
(lambda (v* sss)
(k (cons v v*) sss)))))
(k '() s)))
(evaluate e r s
(lambda (f ss)
(evaluate-arguments e* r ss
(lambda (v* sss)
(if (eq? (f 'type) 'function)
((f 'behavior) v* sss k)
(wrong "Not a function" (car v*))))))))
(define (evaluate-lambda n* e* r s k)
(allocate 1 s
(lambda (a* ss)
(k (create-function
(car a*)
(lambda (v* s k)
(if (= (length n*) (length v*))
(allocate (length n*) s
(lambda (a* ss)
(evaluate-begin e*
(update* r n* a*)
(update* ss a* v*)
k)))
(wrong "Incorrect arity"))))
ss))))
(define (allocate n s q)
(if (> n 0)
(let ((a (new-location s)))
(allocate (- n 1)
(expand-store a s)
(lambda (a* ss)
(q (cons a a*) ss))))
(q '() s)))
(define (expand-store high-location s)
(update s 0 high-location))
(define (new-location s)
(+ 1 (s 0)))
(define s.init
(expand-store 0 (lambda (a) (wrong "No such address" a))))
(define the-empty-list
(lambda (msg)
(case msg
((type) 'null)
((boolify) (lambda (x y) x)))))
(define (create-boolean value)
(let ((combinator (if value (lambda (x y) x) (lambda (x y) y))))
(lambda (msg)
(case msg
((type) 'boolean)
((boolify) combinator)))))
(define (create-symbol v)
(lambda (msg)
(case msg
((type) 'symbol)
((name) v)
((boolify) (lambda (x y) x)))))
(define (create-number v)
(lambda (msg)
(case msg
((type) 'number)
((value) v)
((boolify) (lambda (x y) x)))))
(define (create-function tag behavior)
(lambda (msg)
(case msg
((type) 'function)
((boolify) (lambda (x y) x))
((tag) tag)
((behavior) behavior))))
(define (allocate-list v* s q)
(define (consify v* q)
(if (pair? v*)
(consify (cdr v*) (lambda (v ss)
(allocate-pair (car v*) v ss q)))
(q the-empty-list s)))
(consify v* q))
(define (allocate-pair a d s q)
(allocate 2 s
(lambda (a* ss)
(q (create-pair (car a*) (cadr a*))
(update (update ss (car a*) a) (cadr a*) d)))))
(define (create-pair a d)
(lambda (msg)
(case msg
((type) 'pair)
((boolify) (lambda (x y) x))
((set-car) (lambda (s v) (update s a v)))
((set-cdr) (lambda (s v) (update s d v)))
((car) a)
((cdr) d))))
(define s.global s.init)
(define r.global r.init)
(define (definitial name value)
(allocate 1 s.global
(lambda (a* ss)
(set! r.global (update r.global name (car a*)))
(set! s.global (update ss (car a*) value)))))
(define (defprimitive name value arity)
(definitial name
(allocate 1 s.global
(lambda (a* ss)
(set! s.global (expand-store (car a*) ss))
(create-function
(car a*)
(lambda (v* s k)
(if (= arity (length v*))
(value v* s k)
(wrong "Incorrect arity" name))))))))
(definitial 't (create-boolean #t))
(definitial 'f (create-boolean #f))
(definitial 'nil the-empty-list)
(definitial 'x the-empty-list)
(definitial 'y the-empty-list)
(definitial 'z the-empty-list)
(definitial 'foo the-empty-list)
(definitial 'bar the-empty-list)
(definitial 'fib the-empty-list)
(definitial 'fact the-empty-list)
(defprimitive '<=
(lambda (v* s k)
(if (and (eq? ((car v*) 'type) 'number)
(eq? ((cadr v*) 'type) 'number))
(k (create-boolean (<= ((car v*) 'value)
((cadr v*) 'value)))
s)
(wrong "<= requires numbers")))
2)
(defprimitive '*
(lambda (v* s k)
(if (and (eq? ((car v*) 'type) 'number)
(eq? ((cadr v*) 'type) 'number))
(k (create-number (* ((car v*) 'value)
((cadr v*) 'value)))
s)
(wrong "* requires numbers")))
2)
(defprimitive 'cons
(lambda (v* s k)
(allocate-pair (car v*) (cadr v*) s k))
2)
(defprimitive 'car
(lambda (v* s k)
(if (eq? ((car v*) 'type) 'pair)
(k (s ((car v*) 'car)) s)
(wrong "Not a pair" (car v*))))
1)
(defprimitive 'cdr
(lambda (v* s k)
(if (eq? ((car v*) 'type) 'pair)
(k (s ((car v*) 'cdr)) s)
(wrong "Not a pair" (car v*))))
1)
(defprimitive 'set-cdr
(lambda (v* s k)
(if (eq? ((car v*) 'type) 'pair)
(let ((pair (car v*)))
(k pair ((pair 'set-cdr) s (cadr v*))))
(wrong "Not a pair" (car v*))))
2)
(defprimitive 'set-car
(lambda (v* s k)
(if (eq? ((car v*) 'type) 'pair)
(let ((pair (car v*)))
(k pair ((pair 'set-car) s (cadr v*))))
(wrong "Not a pair" (car v*))))
2)
(defprimitive 'pair?
(lambda (v* s k)
(k (create-boolean (eq? ((car v*) 'type) 'pair)) s))
1)
(defprimitive 'eqv?
(lambda (v* s k)
(k (create-boolean
(if (eq? ((car v*) 'type) ((cadr v*) 'type))
(case ((car v*) 'type)
((null) #t)
((boolean)
(((car v*) 'boolify)
(((cadr v*) 'boolify) #t #f)
(((cadr v*) 'boolify) #f #t)))
((symbol)
(eq? ((car v*) 'name) ((cadr v*) 'name)))
((number)
(eq? ((car v*) 'value) ((cadr v*) 'value)))
((pair)
(and (= ((car v*) 'car) ((cadr v*) 'car))
(= ((car v*) 'cdr) ((cadr v*) 'cdr))))
((function)
(= ((car v*) 'tag) ((cadr v*) 'tag)))
(else #f))
#f))
s))
2)
(define (chapter4-interpreter)
(define (toplevel s)
(evaluate (read)
r.global
s
(lambda (v ss)
(display (transcode-back v ss))
(toplevel ss))))
(toplevel s.global))
(define (transcode-back v s)
(case (v 'type)
((null) '())
((boolean) ((v 'boolify) #t #f))
((symbol) (v 'name))
((string) (v 'chars))
((number) (v 'value))
((pair) (cons (transcode-back (s (v 'car)) s)
(transcode-back (s (v 'cdr)) s)))
((function) v)
(else (wrong "Unknown type" (v 'type)))))
(define (transcode c s q)
(cond ((null? c) (q the-empty-list s))
((boolean? c) (q (create-boolean c) s))
((symbol? c) (q (create-symbol c) s))
((string? c) (q (create-string c) s))
((number? c) (q (create-number c) s))
((pair? c)
(transcode (car c)
s
(lambda (a ss)
(transcode (cdr c)
ss
(lambda (d sss)
(allocate-pair a d sss q))))))))
(define (evaluate-quote c r s k)
(transcode c s k))
(chapter4-interpreter)
|
7de7a390c4a513129d8414bb6846d0d86795de74d3770e628999f229f4c903a5 | mbutterick/aoc-racket | star2.rkt | 2335049
../.. => #.#/###/#.#
#./.. => ..#/.../###
##/.. => .../.##/###
.#/#. => #.#/##./.#.
##/#. => #../#.#/..#
##/## => #.#/#../###
.../.../... => .###/..##/.#../###.
#../.../... => ##.#/.###/#.../##.#
.#./.../... => ..../#.##/..../.#.#
##./.../... => ..#./#.../#.../.###
#.#/.../... => ..##/####/#.#./..##
###/.../... => .##./#.#./###./.#..
.#./#../... => #..#/..#./...#/#.#.
##./#../... => ##../.##./##.#/#..#
..#/#../... => #.##/.##./##.#/.###
#.#/#../... => ...#/#.##/..#./##..
.##/#../... => #.#./..#./##.#/.#.#
###/#../... => #..#/...#/..#./##.#
.../.#./... => .#.#/#.../.##./.#.#
#../.#./... => #.#./.##./..../.#.#
.#./.#./... => .#../#.##/..##/..##
##./.#./... => ..##/##.#/...#/..#.
#.#/.#./... => ...#/.##./####/.#..
###/.#./... => ###./####/...#/####
.#./##./... => ...#/.#.#/#.#./#.#.
##./##./... => ..../...#/#.#./...#
..#/##./... => .##./#.../##.#/.#..
#.#/##./... => .#../.#../...#/....
.##/##./... => ..#./.##./####/.#..
###/##./... => ##../.#.#/##../.#..
.../#.#/... => ..#./.#../.#../.###
#../#.#/... => ####/..../#..#/#...
.#./#.#/... => #.##/##../##.#/##.#
##./#.#/... => ###./..../#.##/###.
#.#/#.#/... => ###./.#../#.#./#.#.
###/#.#/... => ...#/#..#/#.#./..##
.../###/... => .#../...#/...#/....
#../###/... => ####/#.../##../.#.#
.#./###/... => ...#/####/.##./#..#
##./###/... => .###/##.#/..#./.#..
#.#/###/... => ####/###./.###/.###
###/###/... => .#.#/..##/..#./##..
..#/.../#.. => #.../.###/###./...#
#.#/.../#.. => ..../#.../##../..#.
.##/.../#.. => ####/####/...#/####
###/.../#.. => #.../.#../#.#./#.#.
.##/#../#.. => ##../..#./.#../##.#
###/#../#.. => ..../#..#/.###/.###
..#/.#./#.. => ...#/##../.##./##..
#.#/.#./#.. => #.##/.###/#.#./##.#
.##/.#./#.. => ..../..../.#.#/#..#
###/.#./#.. => ##../.#.#/.#.#/####
.##/##./#.. => #.##/##.#/####/....
###/##./#.. => ..../..##/#.#./.###
#../..#/#.. => #.#./...#/#.##/.###
.#./..#/#.. => ####/#.##/.#../.###
##./..#/#.. => .##./..#./.#.#/##.#
#.#/..#/#.. => .#.#/#.##/##../#...
.##/..#/#.. => ..../.###/####/.#..
###/..#/#.. => ##.#/##.#/..##/.#..
#../#.#/#.. => #.##/###./##../....
.#./#.#/#.. => ..../###./####/###.
##./#.#/#.. => ##.#/#.##/##../#.##
..#/#.#/#.. => .###/#.../.#../##..
#.#/#.#/#.. => ##../##.#/#.../.##.
.##/#.#/#.. => ...#/..#./.###/##.#
###/#.#/#.. => #.../#.##/..##/..##
#../.##/#.. => #.##/#.../.##./##..
.#./.##/#.. => #.#./#.../..##/.#..
##./.##/#.. => .###/.#.#/####/.#.#
#.#/.##/#.. => ####/.#../##.#/.###
.##/.##/#.. => .#../##.#/####/#.#.
###/.##/#.. => #.##/#.../...#/....
#../###/#.. => ###./.#.#/##../#..#
.#./###/#.. => #..#/..##/..../....
##./###/#.. => ..#./#.../...#/###.
..#/###/#.. => ##../..##/##../#.##
#.#/###/#.. => ..../..#./.###/##..
.##/###/#.. => #..#/####/.#.#/.##.
###/###/#.. => ###./#.##/##.#/.#..
.#./#.#/.#. => #.../####/#.#./.##.
##./#.#/.#. => ..##/..../.#.#/##..
#.#/#.#/.#. => ####/..##/####/#...
###/#.#/.#. => ##.#/#.#./.##./####
.#./###/.#. => .#.#/.#.#/##.#/###.
##./###/.#. => .#../###./#.##/#...
#.#/###/.#. => #.../.###/.#../.#..
###/###/.#. => #.#./.##./.###/####
#.#/..#/##. => .#../#..#/###./#.##
###/..#/##. => #.#./####/###./###.
.##/#.#/##. => .#.#/...#/..../#.##
###/#.#/##. => ...#/..../#.##/####
#.#/.##/##. => ##../.#../.#.#/##..
###/.##/##. => #.../#.#./#.#./#.#.
.##/###/##. => ..../#.##/#.##/..##
###/###/##. => ####/##.#/#..#/.##.
#.#/.../#.# => ##.#/.#.#/####/.##.
###/.../#.# => #..#/.#.#/#.../#..#
###/#../#.# => ..##/###./.###/..##
#.#/.#./#.# => #.##/#.#./##../...#
###/.#./#.# => ..#./.###/..##/#...
###/##./#.# => #.../...#/..##/.###
#.#/#.#/#.# => #..#/.#../...#/#..#
###/#.#/#.# => ###./#.../##../.##.
#.#/###/#.# => ...#/..#./...#/#..#
###/###/#.# => ###./####/.###/###.
###/#.#/### => .###/.#../..../##.#
###/###/### => #..#/.###/##../.##. | null | https://raw.githubusercontent.com/mbutterick/aoc-racket/2c6cb2f3ad876a91a82f33ce12844f7758b969d6/2017/d21/star2.rkt | racket | 2335049
../.. => #.#/###/#.#
#./.. => ..#/.../###
##/.. => .../.##/###
.#/#. => #.#/##./.#.
##/#. => #../#.#/..#
##/## => #.#/#../###
.../.../... => .###/..##/.#../###.
#../.../... => ##.#/.###/#.../##.#
.#./.../... => ..../#.##/..../.#.#
##./.../... => ..#./#.../#.../.###
#.#/.../... => ..##/####/#.#./..##
###/.../... => .##./#.#./###./.#..
.#./#../... => #..#/..#./...#/#.#.
##./#../... => ##../.##./##.#/#..#
..#/#../... => #.##/.##./##.#/.###
#.#/#../... => ...#/#.##/..#./##..
.##/#../... => #.#./..#./##.#/.#.#
###/#../... => #..#/...#/..#./##.#
.../.#./... => .#.#/#.../.##./.#.#
#../.#./... => #.#./.##./..../.#.#
.#./.#./... => .#../#.##/..##/..##
##./.#./... => ..##/##.#/...#/..#.
#.#/.#./... => ...#/.##./####/.#..
###/.#./... => ###./####/...#/####
.#./##./... => ...#/.#.#/#.#./#.#.
##./##./... => ..../...#/#.#./...#
..#/##./... => .##./#.../##.#/.#..
#.#/##./... => .#../.#../...#/....
.##/##./... => ..#./.##./####/.#..
###/##./... => ##../.#.#/##../.#..
.../#.#/... => ..#./.#../.#../.###
#../#.#/... => ####/..../#..#/#...
.#./#.#/... => #.##/##../##.#/##.#
##./#.#/... => ###./..../#.##/###.
#.#/#.#/... => ###./.#../#.#./#.#.
###/#.#/... => ...#/#..#/#.#./..##
.../###/... => .#../...#/...#/....
#../###/... => ####/#.../##../.#.#
.#./###/... => ...#/####/.##./#..#
##./###/... => .###/##.#/..#./.#..
#.#/###/... => ####/###./.###/.###
###/###/... => .#.#/..##/..#./##..
..#/.../#.. => #.../.###/###./...#
#.#/.../#.. => ..../#.../##../..#.
.##/.../#.. => ####/####/...#/####
###/.../#.. => #.../.#../#.#./#.#.
.##/#../#.. => ##../..#./.#../##.#
###/#../#.. => ..../#..#/.###/.###
..#/.#./#.. => ...#/##../.##./##..
#.#/.#./#.. => #.##/.###/#.#./##.#
.##/.#./#.. => ..../..../.#.#/#..#
###/.#./#.. => ##../.#.#/.#.#/####
.##/##./#.. => #.##/##.#/####/....
###/##./#.. => ..../..##/#.#./.###
#../..#/#.. => #.#./...#/#.##/.###
.#./..#/#.. => ####/#.##/.#../.###
##./..#/#.. => .##./..#./.#.#/##.#
#.#/..#/#.. => .#.#/#.##/##../#...
.##/..#/#.. => ..../.###/####/.#..
###/..#/#.. => ##.#/##.#/..##/.#..
#../#.#/#.. => #.##/###./##../....
.#./#.#/#.. => ..../###./####/###.
##./#.#/#.. => ##.#/#.##/##../#.##
..#/#.#/#.. => .###/#.../.#../##..
#.#/#.#/#.. => ##../##.#/#.../.##.
.##/#.#/#.. => ...#/..#./.###/##.#
###/#.#/#.. => #.../#.##/..##/..##
#../.##/#.. => #.##/#.../.##./##..
.#./.##/#.. => #.#./#.../..##/.#..
##./.##/#.. => .###/.#.#/####/.#.#
#.#/.##/#.. => ####/.#../##.#/.###
.##/.##/#.. => .#../##.#/####/#.#.
###/.##/#.. => #.##/#.../...#/....
#../###/#.. => ###./.#.#/##../#..#
.#./###/#.. => #..#/..##/..../....
##./###/#.. => ..#./#.../...#/###.
..#/###/#.. => ##../..##/##../#.##
#.#/###/#.. => ..../..#./.###/##..
.##/###/#.. => #..#/####/.#.#/.##.
###/###/#.. => ###./#.##/##.#/.#..
.#./#.#/.#. => #.../####/#.#./.##.
##./#.#/.#. => ..##/..../.#.#/##..
#.#/#.#/.#. => ####/..##/####/#...
###/#.#/.#. => ##.#/#.#./.##./####
.#./###/.#. => .#.#/.#.#/##.#/###.
##./###/.#. => .#../###./#.##/#...
#.#/###/.#. => #.../.###/.#../.#..
###/###/.#. => #.#./.##./.###/####
#.#/..#/##. => .#../#..#/###./#.##
###/..#/##. => #.#./####/###./###.
.##/#.#/##. => .#.#/...#/..../#.##
###/#.#/##. => ...#/..../#.##/####
#.#/.##/##. => ##../.#../.#.#/##..
###/.##/##. => #.../#.#./#.#./#.#.
.##/###/##. => ..../#.##/#.##/..##
###/###/##. => ####/##.#/#..#/.##.
#.#/.../#.# => ##.#/.#.#/####/.##.
###/.../#.# => #..#/.#.#/#.../#..#
###/#../#.# => ..##/###./.###/..##
#.#/.#./#.# => #.##/#.#./##../...#
###/.#./#.# => ..#./.###/..##/#...
###/##./#.# => #.../...#/..##/.###
#.#/#.#/#.# => #..#/.#../...#/#..#
###/#.#/#.# => ###./#.../##../.##.
#.#/###/#.# => ...#/..#./...#/#..#
###/###/#.# => ###./####/.###/###.
###/#.#/### => .###/.#../..../##.#
###/###/### => #..#/.###/##../.##. | |
1e8dcc68e3cd70fda5b4e20af1267af7f747f8699b807016613cc12c719d6cbd | keera-studios/keera-hails | Action.hs | -- |
Copyright : ( C ) Keera Studios Ltd , 2020
-- License : BSD3
Maintainer :
--
-- Abstract definition of an operator button in a calculator.
module Data.Action where
-- | Operator button in a calculator. We support both binary number
-- operators and other operatots that whould return the final value.
data Action = Equals | Clear
deriving Eq
| null | https://raw.githubusercontent.com/keera-studios/keera-hails/bf069e5aafc85a1f55fa119ae45a025a2bd4a3d0/demos/keera-hails-demos-small/src/Data/Action.hs | haskell | |
License : BSD3
Abstract definition of an operator button in a calculator.
| Operator button in a calculator. We support both binary number
operators and other operatots that whould return the final value. | Copyright : ( C ) Keera Studios Ltd , 2020
Maintainer :
module Data.Action where
data Action = Equals | Clear
deriving Eq
|
0ce2c7dab1bd694a31ac7fd4cf5d6297e7c97192c576891a5941ea085706c9dd | lemonidas/Alan-Compiler | CopyPropagation.mli | val copy_propagation : OptimizationSupport.flowgraph_t -> unit
| null | https://raw.githubusercontent.com/lemonidas/Alan-Compiler/bbedcbf91028d45a2e26839790df2a1347e8bc52/CopyPropagation.mli | ocaml | val copy_propagation : OptimizationSupport.flowgraph_t -> unit
| |
a05635304893db805881e61bda1fed26274173712419d828fc7ae4118663d635 | protz/mezzo | KindPrinter.ml | (* These printers are used purely for debugging purposes. *)
open MzPprint
open Kind
open TypeCore
open Types
open TypePrinter
(* Prints an abstract data type. Very straightforward. *)
let print_abstract_type_def print_env name kind =
string "abstract" ^^ space ^^ print_name print_env name ^^ space ^^ colon ^^ space ^^
print_kind kind
;;
let print_nameiance = function
| Invariant ->
empty
| Covariant ->
plus
| Contravariant ->
minus
| Bivariant ->
equals
;;
(* Prints a data type defined in the global scope. Assumes [print_env] has been
properly populated. *)
let print_data_type_def (env: env) name kind variance branches =
let params, _return_kind = Kind.as_arrow kind in
(* Turn the list of parameters into letters *)
let letters: string list = name_gen (List.length params) in
let letters = List.map2 (fun variance letter ->
print_nameiance variance ^^ utf8string letter
) variance letters in
let env, _, branches =
bind_datacon_parameters env kind branches
in
let sep = break 1 ^^ bar ^^ space in
(* The whole blurb *)
string "data" ^^ space ^^ lparen ^^
print_name env name ^^ space ^^ colon ^^ space ^^
print_kind kind ^^ rparen ^^ concat_map (precede space) letters ^^
space ^^ equals ^^
jump
(ifflat empty (bar ^^ space) ^^
separate_map sep (print_type env) branches
)
;;
let print_abbrev_type_def (env: env) name kind variance t =
let env, points = make_datacon_letters env kind false in
let letters = List.map (fun p -> get_name env p) points in
let letters = List.map2 (fun variance letter ->
print_nameiance variance ^^ print_name env letter
) variance letters in
let vars = List.map (fun x -> TyOpen x) points in
let t = instantiate_type t vars in
(* The whole blurb *)
string "alias" ^^ space ^^ lparen ^^
print_name env name ^^ space ^^ colon ^^ space ^^
print_kind kind ^^ rparen ^^ concat_map (precede space) letters ^^
space ^^ equals ^^ space ^^ print_type env t
;;
let print_def env name kind variance def =
match def with
| Concrete branches ->
print_data_type_def env name kind variance branches
| Abbrev t ->
print_abbrev_type_def env name kind variance t
| Abstract ->
print_abstract_type_def env name kind
;;
(* This function prints the contents of a [Types.env]. *)
let print_kinds env =
(* Now we have a pretty-printing environment that's ready, proceed. *)
let defs = fold_definitions env (fun acc var definition ->
let name = get_name env var in
let kind = get_kind env var in
let variance = get_variance env var in
print_def env name kind variance definition :: acc
) [] in
separate (twice (break 1)) defs
;;
let print_group env (group: data_type_group) =
let defs = List.map (fun data_type ->
let name = User (module_name env, data_type.data_name) in
print_def env name data_type.data_kind data_type.data_variance data_type.data_definition
) group.group_items in
nest 2 (separate (twice (break 1)) defs) ^^ hardline
;;
let pgroup buf arg =
pdoc buf ((fun (env, group) -> print_group env group), arg)
;;
let print_kinds_and_facts program_env =
colors.red ^^ string "KINDS:" ^^ colors.default ^^
nest 2 (hardline ^^ print_kinds program_env) ^^ hardline ^^
hardline ^^
colors.red ^^ string "FACTS:" ^^ colors.default ^^
nest 2 (hardline ^^ print_facts program_env) ^^ hardline
;;
| null | https://raw.githubusercontent.com/protz/mezzo/4e9d917558bd96067437116341b7a6ea02ab9c39/typing/KindPrinter.ml | ocaml | These printers are used purely for debugging purposes.
Prints an abstract data type. Very straightforward.
Prints a data type defined in the global scope. Assumes [print_env] has been
properly populated.
Turn the list of parameters into letters
The whole blurb
The whole blurb
This function prints the contents of a [Types.env].
Now we have a pretty-printing environment that's ready, proceed. |
open MzPprint
open Kind
open TypeCore
open Types
open TypePrinter
let print_abstract_type_def print_env name kind =
string "abstract" ^^ space ^^ print_name print_env name ^^ space ^^ colon ^^ space ^^
print_kind kind
;;
let print_nameiance = function
| Invariant ->
empty
| Covariant ->
plus
| Contravariant ->
minus
| Bivariant ->
equals
;;
let print_data_type_def (env: env) name kind variance branches =
let params, _return_kind = Kind.as_arrow kind in
let letters: string list = name_gen (List.length params) in
let letters = List.map2 (fun variance letter ->
print_nameiance variance ^^ utf8string letter
) variance letters in
let env, _, branches =
bind_datacon_parameters env kind branches
in
let sep = break 1 ^^ bar ^^ space in
string "data" ^^ space ^^ lparen ^^
print_name env name ^^ space ^^ colon ^^ space ^^
print_kind kind ^^ rparen ^^ concat_map (precede space) letters ^^
space ^^ equals ^^
jump
(ifflat empty (bar ^^ space) ^^
separate_map sep (print_type env) branches
)
;;
let print_abbrev_type_def (env: env) name kind variance t =
let env, points = make_datacon_letters env kind false in
let letters = List.map (fun p -> get_name env p) points in
let letters = List.map2 (fun variance letter ->
print_nameiance variance ^^ print_name env letter
) variance letters in
let vars = List.map (fun x -> TyOpen x) points in
let t = instantiate_type t vars in
string "alias" ^^ space ^^ lparen ^^
print_name env name ^^ space ^^ colon ^^ space ^^
print_kind kind ^^ rparen ^^ concat_map (precede space) letters ^^
space ^^ equals ^^ space ^^ print_type env t
;;
let print_def env name kind variance def =
match def with
| Concrete branches ->
print_data_type_def env name kind variance branches
| Abbrev t ->
print_abbrev_type_def env name kind variance t
| Abstract ->
print_abstract_type_def env name kind
;;
let print_kinds env =
let defs = fold_definitions env (fun acc var definition ->
let name = get_name env var in
let kind = get_kind env var in
let variance = get_variance env var in
print_def env name kind variance definition :: acc
) [] in
separate (twice (break 1)) defs
;;
let print_group env (group: data_type_group) =
let defs = List.map (fun data_type ->
let name = User (module_name env, data_type.data_name) in
print_def env name data_type.data_kind data_type.data_variance data_type.data_definition
) group.group_items in
nest 2 (separate (twice (break 1)) defs) ^^ hardline
;;
let pgroup buf arg =
pdoc buf ((fun (env, group) -> print_group env group), arg)
;;
let print_kinds_and_facts program_env =
colors.red ^^ string "KINDS:" ^^ colors.default ^^
nest 2 (hardline ^^ print_kinds program_env) ^^ hardline ^^
hardline ^^
colors.red ^^ string "FACTS:" ^^ colors.default ^^
nest 2 (hardline ^^ print_facts program_env) ^^ hardline
;;
|
b873b48bd81ffd12a768858b27df1ecfd778e09bbbb87ceea73f27da4a7683f1 | pol-is/polisMath | density_plotting.clj | (ns density-plotting
"# Density plotting test
This doesn't currently work yet, but its an attempt at visualizing a point clouds as a contour map of its density distribution.
The example I'm working from for vega is: -plot/.
Unfortunately, this is vega, not vega-lite, and the vizard lib at the moment only plots vega-lite.
I've added a couple of issues for this (see and #13).
It seems like it should be possible to add this, and maybe if we end up caring enough I can do so.
For now, not super vital."
(:require
[vizard.core :as viz]))
(defonce start-viz
(viz/start-plot-server!))
(def data-values
[{:x 3.4 :y 5.3}
{:x 2.2 :y 9.3}
{:x 4.4 :y 5.1}
{:x 1.7 :y 5.9}
{:x 2.4 :y 6.2}
{:x 7.4 :y 7.4}
{:x 2.8 :y 10.3}
{:x 3.9 :y 8.3}])
(def plot-spec-2
{:width 1000
:height 800
:data {:values data-values}
:layer [{:mark {:type "point" :filled true}
:encoding {:x {:field "x"}
:y {:field "y"}
:size {:value 500}}}]})
(def plot-spec
{:width 500
:height 400
:data [{:name "main"
:values data-values}]
;{:name "contours"
; :source "main"
; :transform [{:type "contour"}]}]
:marks [{:name "dots"
:type "symbol"
:from {:data "main"}
:encode {:x {:field "x"}
:y {:field "y"}}}]})
;(viz/to-json plot-spec-2)
(viz/p! plot-spec-2)
| null | https://raw.githubusercontent.com/pol-is/polisMath/dfe233e8c9207c2ce11e1379286ad0cf0f732067/dev/density_plotting.clj | clojure | {:name "contours"
:source "main"
:transform [{:type "contour"}]}]
(viz/to-json plot-spec-2) | (ns density-plotting
"# Density plotting test
This doesn't currently work yet, but its an attempt at visualizing a point clouds as a contour map of its density distribution.
The example I'm working from for vega is: -plot/.
Unfortunately, this is vega, not vega-lite, and the vizard lib at the moment only plots vega-lite.
I've added a couple of issues for this (see and #13).
It seems like it should be possible to add this, and maybe if we end up caring enough I can do so.
For now, not super vital."
(:require
[vizard.core :as viz]))
(defonce start-viz
(viz/start-plot-server!))
(def data-values
[{:x 3.4 :y 5.3}
{:x 2.2 :y 9.3}
{:x 4.4 :y 5.1}
{:x 1.7 :y 5.9}
{:x 2.4 :y 6.2}
{:x 7.4 :y 7.4}
{:x 2.8 :y 10.3}
{:x 3.9 :y 8.3}])
(def plot-spec-2
{:width 1000
:height 800
:data {:values data-values}
:layer [{:mark {:type "point" :filled true}
:encoding {:x {:field "x"}
:y {:field "y"}
:size {:value 500}}}]})
(def plot-spec
{:width 500
:height 400
:data [{:name "main"
:values data-values}]
:marks [{:name "dots"
:type "symbol"
:from {:data "main"}
:encode {:x {:field "x"}
:y {:field "y"}}}]})
(viz/p! plot-spec-2)
|
a707547415ac7fc961f18f2e43942cf362710f4d31fb25c9b5a3e08f756005d3 | pcostanza/mop-features | all-function-tests.lisp | (let ((gf (make-instance 'standard-generic-function
:lambda-list
#-allegro '(a b c &optional o)
#+allegro '(a b c))))
(when (equal (generic-function-argument-precedence-order gf) '(a b c))
(acknowledge :initialize-lambda-list-initializes-argument-precedence-order)))
(let ((gf (make-instance 'standard-generic-function
:lambda-list
#-allegro '(a b c &optional o)
#+allegro '(a b c)
:argument-precedence-order '(c b a))))
(assert (equal (generic-function-argument-precedence-order gf) '(c b a)))
(reinitialize-instance gf
:lambda-list
#-allegro '(a b c &rest r)
#+allegro '(a b c))
(when (equal (generic-function-argument-precedence-order gf) '(a b c))
(acknowledge :reinitialize-lambda-list-reinitializes-argument-precedence-order)))
(eval-when (:compile-toplevel :load-toplevel :execute)
(defclass test-generic-function (standard-generic-function) ()
(:metaclass funcallable-standard-class))
(defclass test-method (standard-method) ())
(defvar *reinitialize-action* nil)
(defvar *defmethod-called-p* nil)
(defvar *add-method-called-p* nil)
(defvar *the-feature* :initialize-instance-calls-compute-discriminating-function)
(defvar *the-function* nil)
(defmethod reinitialize-instance :after
((function test-generic-function) &key name &allow-other-keys)
(when *reinitialize-action*
(funcall *reinitialize-action* function name)))
(defvar *check-find-method-combination* t)
(defmethod find-method-combination :after
((function test-generic-function)
(method-combination-type-name t)
(method-combination-options t))
(when *check-find-method-combination*
(acknowledge :defgeneric-calls-find-method-combination)))
(acknowledge-function "ENSURE-GENERIC-FUNCTION-USING-CLASS")
(defmethod ensure-generic-function-using-class :after
((function test-generic-function) (name t) &rest initargs)
(declare (ignore initargs))
(acknowledge :defgeneric-calls-ensure-generic-function-using-class))
(defmethod initialize-instance :before
((class test-generic-function) &rest initargs)
(loop for (key nil) on initargs by #'cddr
do (acknowledge (intern (concatenate
'string "GENERIC-FUNCTION-INITIALIZED-WITH-"
(symbol-name key))
:keyword))))
(defmethod initialize-instance :before
((method test-method) &rest initargs)
(declare (ignore initargs))
(when *defmethod-called-p*
(acknowledge :defmethod-calls-initialize-instance)))
#-scl
(when (mop-function-p "MAKE-METHOD-LAMBDA")
(if (= (length (generic-function-lambda-list #'make-method-lambda)) 4)
(progn
(acknowledge :make-method-lambda)
(defmethod make-method-lambda :after
((function test-generic-function)
(method standard-method)
(lambda-expression t)
(environment t))
(when *defmethod-called-p*
(acknowledge :defmethod-calls-make-method-lambda))))
(progn
#+lispworks
(acknowledge :make-method-lambda-lispworks)
#-lispworks
(error "unknown kind of make-method-lambda.")
(defmethod make-method-lambda :after
((function test-generic-function)
(method standard-method)
(lambda-list t)
(declarations t)
(body t)
&optional env)
(when *defmethod-called-p*
(acknowledge :defmethod-calls-make-method-lambda))))))
(when (typep #'compute-applicable-methods 'generic-function)
(acknowledge :compute-applicable-methods-is-generic)
(defmethod compute-applicable-methods :after
((gf test-generic-function) args)
(acknowledge :function-invocation-calls-compute-applicable-methods)))
(when (mop-function-p "COMPUTE-APPLICABLE-METHODS-USING-CLASSES")
(defmethod compute-applicable-methods-using-classes :after
((gf test-generic-function) classes)
(acknowledge :function-invocation-calls-compute-applicable-methods-using-classes)))
(when (mop-function-p "COMPUTE-EFFECTIVE-METHOD")
(acknowledge :compute-effective-method)
(when (typep #'compute-effective-method 'generic-function)
(acknowledge :compute-effective-method-is-generic)
(defmethod compute-effective-method :after
((gf test-generic-function)
(method-combination t)
(methods t))
(acknowledge :function-invocation-calls-compute-effective-method))))
(defmethod compute-discriminating-function :after
((function test-generic-function) #+scl cache)
#+scl (declare (ignore cache))
(when *the-feature*
(acknowledge *the-feature*)))
(when (typep #'find-method 'generic-function)
(acknowledge :find-method-is-generic)
(defmethod find-method :after
((function test-generic-function)
qualifiers specializers &optional errp)
(declare (ignore qualifiers specializers errp))
(when *add-method-called-p*
(acknowledge :add-method-calls-find-method))))
(when (typep #'remove-method 'generic-function)
(acknowledge :remove-method-is-generic)
(defmethod remove-method :after
((function test-generic-function)
(method standard-method))
(when *add-method-called-p*
(acknowledge :add-method-calls-remove-method))))
(defmethod add-method :before
((function test-generic-function)
(method standard-method))
(when *defmethod-called-p*
(acknowledge :defmethod-calls-add-method)))
(defmethod add-method :around
((function test-generic-function)
(method standard-method))
(let ((*add-method-called-p* t))
(call-next-method)))
(when (typep #'generic-function-method-class 'generic-function)
(acknowledge :generic-function-method-class-is-generic)
(defmethod generic-function-method-class :after ((function test-generic-function))
(when (and *defmethod-called-p*
(eq function *the-function*))
(acknowledge :defmethod-calls-generic-function-method-class)))))
(when (mop-function-p "FIND-METHOD-COMBINATION")
(handler-case
(progn
(let ((*check-find-method-combination* nil))
(find-method-combination
(ensure-generic-function (gensym)
:generic-function-class 'test-generic-function)
'standard ()))
(acknowledge :find-method-combination))
(error () nil)))
(defgeneric test-function-nil ()
(:generic-function-class test-generic-function))
(defgeneric test-function (x)
(:generic-function-class test-generic-function)
(:method-class test-method))
(setf *the-function* #'test-function)
(defvar *the-method*
#-(or clozure scl)
(make-instance 'standard-method
:qualifiers '()
:lambda-list '()
:specializers '()
:function
#+(or openmcl mcl) (lambda () nil)
#+sbcl (lambda (&rest args)
(declare (ignore args))
nil)
#-(or openmcl mcl sbcl) (constantly nil))
#+scl
(make-instance 'standard-method
:qualifiers '()
:lambda-list '()
:specializers '()
:function (constantly (constantly nil)))
#+(and clozure (not closer-mop))
(make-instance 'standard-method
:qualifiers '()
:lambda-list '()
:specializers '()
:function (lambda () nil))
#+(and clozure closer-mop)
(make-instance 'standard-method
:qualifiers '()
:lambda-list '()
:specializers '()
:function (lambda (&rest args)
(declare (ignore args))
nil)
:closer-patch t))
(let ((*the-feature* :add-method-calls-compute-discriminating-function))
(add-method #'test-function-nil *the-method*))
(let ((*the-feature* :function-invocation-calls-compute-discriminating-function))
(test-function-nil))
(let ((*the-feature* :reinitialize-instance-calls-compute-discriminating-function))
(reinitialize-instance #'test-function-nil))
(let ((*the-feature* :remove-method-calls-compute-discriminating-function))
(remove-method #'test-function-nil *the-method*))
(setf *the-feature* nil)
(let ((*defmethod-called-p* t))
(eval '(defmethod test-function ((x integer)) nil)))
(let ((*defmethod-called-p* t))
(eval '(defmethod test-function ((x integer)) x)))
(defmethod test-function ((x (eql 5))) 42)
(test-function 5)
(defgeneric test-function-2 (x y)
(:generic-function-class test-generic-function)
(:argument-precedence-order y x)
(declare (optimize speed))
(:documentation "a function")
(:method-combination +)
#-(or clozure mcl)
(:method-class test-method)
(:method + (x y) (+ x y)))
#|
(mapc #'acknowledge-function
'("GENERIC-FUNCTION-ARGUMENT-PRECEDENCE-ORDER"
"GENERIC-FUNCTION-DECLARATIONS"
"GENERIC-FUNCTION-LAMBDA-LIST"
"GENERIC-FUNCTION-METHOD-CLASS"
"GENERIC-FUNCTION-METHOD-COMBINATION"
"GENERIC-FUNCTION-METHODS"
"GENERIC-FUNCTION-NAME"))
|#
(defgeneric test-function-3 (x)
(:generic-function-class test-generic-function))
(defgeneric test-function-3 (x)
(:generic-function-class test-generic-function))
(defmethod test-function-3 (x)
(declare (ignore x))
(print 'hi))
(add-method #'test-function-3
(make-instance 'standard-method
:qualifiers '()
:lambda-list '(x)
:specializers (list (find-class 't))
:function (lambda (x) x)))
(handler-case
(progn
(test-function-3 42)
(acknowledge :method-functions-take-original-parameters))
(error () (acknowledge :method-functions-take-processed-parameters)))
(cond ((member :make-method-lambda-lispworks *mop-features*)
(acknowledge :method-lambdas-are-processed))
((member :make-method-lambda *mop-features*)
(let ((method-lambda '(lambda (x) x)))
(if (eq method-lambda
(make-method-lambda
#'test-function (class-prototype (find-class 'standard-method))
method-lambda nil))
(acknowledge :method-lambdas-are-unchanged)
(acknowledge :method-lambdas-are-processed)))))
(when (mop-setf-function-p "GENERIC-FUNCTION-NAME")
(acknowledge :setf-generic-function-name)
(let ((*reinitialize-action*
(lambda (function name)
(when (and (eq function #'test-function-3)
(eq name 'test-function-4))
(acknowledge :setf-generic-function-name-calls-reinitialize-instance)))))
(setf (generic-function-name #'test-function-3)
'test-function-4)))
#+lispworks4.3
(defmethod compute-discriminating-function ((function t))
(let ((previous nil))
(lambda (&rest args)
(let ((old previous))
(setq previous (car args))
old))))
#-(or cmu clozure mcl)
(progn
(defgeneric test-function-5 (object)
(:generic-function-class test-generic-function))
(defmethod test-function-5 (object) object)
#-scl
(let ((function (compute-discriminating-function #'test-function-5)))
(handler-case
(when (eql (funcall function 4711) 4711)
(acknowledge :discriminating-functions-can-be-funcalled))
(error ())))
(defmethod compute-discriminating-function ((function test-generic-function) #+scl cache)
#+scl (declare (ignore cache))
(let ((previous nil))
(lambda (&rest args)
(let ((old previous))
(setq previous (car args))
old))))
#-scl
(set-funcallable-instance-function
#'test-function-5 (compute-discriminating-function #'test-function-5))
#+scl
(defmethod test-function-5 (object) object)
(handler-case
(when (and (eql (test-function-5 0815) nil)
(eql (test-function-5 666) 0815))
(acknowledge :discriminating-functions-can-be-closures))
(error ())))
#+(and clozure closer-mop)
(progn
(defgeneric test-function-5 (object)
(:generic-function-class test-generic-function))
(defmethod test-function-5 (object) object)
(let ((function (compute-discriminating-function #'test-function-5)))
(handler-case
(when (eql (funcall function 4711) 4711)
(acknowledge :discriminating-functions-can-be-funcalled))
(error ())))
(defmethod compute-discriminating-function ((function test-generic-function))
(let ((previous nil))
(lambda (&rest args)
(let ((old previous))
(setq previous (car args))
old))))
(set-funcallable-instance-function
#'test-function-5 (compute-discriminating-function #'test-function-5))
(handler-case
(when (and (eql (test-function-5 0815) nil)
(eql (test-function-5 666) 0815))
(acknowledge :discriminating-functions-can-be-closures))
(error ())))
(defmethod compute-discriminating-function
((gf test-generic-function) #+scl cache)
#+scl (declare (ignore cache))
(lambda () 'hello-world))
(defgeneric test-function-6 ()
(:generic-function-class test-generic-function))
(handler-case
(when (eq (test-function-6) 'hello-world)
(acknowledge :generic-functions-can-be-empty))
(error ()))
#-mcl
(progn
(defgeneric test-function-7 (x y z))
(set-funcallable-instance-function
#'test-function-7 (lambda (x y z) (* x y z)))
(handler-case
(when (and (eql (test-function-7 2 3 4) (* 2 3 4))
(eql (test-function-7 10 20 30) (* 10 20 30)))
(acknowledge :funcallable-instance-functions-can-be-closures))
(error ())))
| null | https://raw.githubusercontent.com/pcostanza/mop-features/a967752c885285b74473b940103f8cb2872aced8/tests/all-function-tests.lisp | lisp |
(mapc #'acknowledge-function
'("GENERIC-FUNCTION-ARGUMENT-PRECEDENCE-ORDER"
"GENERIC-FUNCTION-DECLARATIONS"
"GENERIC-FUNCTION-LAMBDA-LIST"
"GENERIC-FUNCTION-METHOD-CLASS"
"GENERIC-FUNCTION-METHOD-COMBINATION"
"GENERIC-FUNCTION-METHODS"
"GENERIC-FUNCTION-NAME"))
| (let ((gf (make-instance 'standard-generic-function
:lambda-list
#-allegro '(a b c &optional o)
#+allegro '(a b c))))
(when (equal (generic-function-argument-precedence-order gf) '(a b c))
(acknowledge :initialize-lambda-list-initializes-argument-precedence-order)))
(let ((gf (make-instance 'standard-generic-function
:lambda-list
#-allegro '(a b c &optional o)
#+allegro '(a b c)
:argument-precedence-order '(c b a))))
(assert (equal (generic-function-argument-precedence-order gf) '(c b a)))
(reinitialize-instance gf
:lambda-list
#-allegro '(a b c &rest r)
#+allegro '(a b c))
(when (equal (generic-function-argument-precedence-order gf) '(a b c))
(acknowledge :reinitialize-lambda-list-reinitializes-argument-precedence-order)))
(eval-when (:compile-toplevel :load-toplevel :execute)
(defclass test-generic-function (standard-generic-function) ()
(:metaclass funcallable-standard-class))
(defclass test-method (standard-method) ())
(defvar *reinitialize-action* nil)
(defvar *defmethod-called-p* nil)
(defvar *add-method-called-p* nil)
(defvar *the-feature* :initialize-instance-calls-compute-discriminating-function)
(defvar *the-function* nil)
(defmethod reinitialize-instance :after
((function test-generic-function) &key name &allow-other-keys)
(when *reinitialize-action*
(funcall *reinitialize-action* function name)))
(defvar *check-find-method-combination* t)
(defmethod find-method-combination :after
((function test-generic-function)
(method-combination-type-name t)
(method-combination-options t))
(when *check-find-method-combination*
(acknowledge :defgeneric-calls-find-method-combination)))
(acknowledge-function "ENSURE-GENERIC-FUNCTION-USING-CLASS")
(defmethod ensure-generic-function-using-class :after
((function test-generic-function) (name t) &rest initargs)
(declare (ignore initargs))
(acknowledge :defgeneric-calls-ensure-generic-function-using-class))
(defmethod initialize-instance :before
((class test-generic-function) &rest initargs)
(loop for (key nil) on initargs by #'cddr
do (acknowledge (intern (concatenate
'string "GENERIC-FUNCTION-INITIALIZED-WITH-"
(symbol-name key))
:keyword))))
(defmethod initialize-instance :before
((method test-method) &rest initargs)
(declare (ignore initargs))
(when *defmethod-called-p*
(acknowledge :defmethod-calls-initialize-instance)))
#-scl
(when (mop-function-p "MAKE-METHOD-LAMBDA")
(if (= (length (generic-function-lambda-list #'make-method-lambda)) 4)
(progn
(acknowledge :make-method-lambda)
(defmethod make-method-lambda :after
((function test-generic-function)
(method standard-method)
(lambda-expression t)
(environment t))
(when *defmethod-called-p*
(acknowledge :defmethod-calls-make-method-lambda))))
(progn
#+lispworks
(acknowledge :make-method-lambda-lispworks)
#-lispworks
(error "unknown kind of make-method-lambda.")
(defmethod make-method-lambda :after
((function test-generic-function)
(method standard-method)
(lambda-list t)
(declarations t)
(body t)
&optional env)
(when *defmethod-called-p*
(acknowledge :defmethod-calls-make-method-lambda))))))
(when (typep #'compute-applicable-methods 'generic-function)
(acknowledge :compute-applicable-methods-is-generic)
(defmethod compute-applicable-methods :after
((gf test-generic-function) args)
(acknowledge :function-invocation-calls-compute-applicable-methods)))
(when (mop-function-p "COMPUTE-APPLICABLE-METHODS-USING-CLASSES")
(defmethod compute-applicable-methods-using-classes :after
((gf test-generic-function) classes)
(acknowledge :function-invocation-calls-compute-applicable-methods-using-classes)))
(when (mop-function-p "COMPUTE-EFFECTIVE-METHOD")
(acknowledge :compute-effective-method)
(when (typep #'compute-effective-method 'generic-function)
(acknowledge :compute-effective-method-is-generic)
(defmethod compute-effective-method :after
((gf test-generic-function)
(method-combination t)
(methods t))
(acknowledge :function-invocation-calls-compute-effective-method))))
(defmethod compute-discriminating-function :after
((function test-generic-function) #+scl cache)
#+scl (declare (ignore cache))
(when *the-feature*
(acknowledge *the-feature*)))
(when (typep #'find-method 'generic-function)
(acknowledge :find-method-is-generic)
(defmethod find-method :after
((function test-generic-function)
qualifiers specializers &optional errp)
(declare (ignore qualifiers specializers errp))
(when *add-method-called-p*
(acknowledge :add-method-calls-find-method))))
(when (typep #'remove-method 'generic-function)
(acknowledge :remove-method-is-generic)
(defmethod remove-method :after
((function test-generic-function)
(method standard-method))
(when *add-method-called-p*
(acknowledge :add-method-calls-remove-method))))
(defmethod add-method :before
((function test-generic-function)
(method standard-method))
(when *defmethod-called-p*
(acknowledge :defmethod-calls-add-method)))
(defmethod add-method :around
((function test-generic-function)
(method standard-method))
(let ((*add-method-called-p* t))
(call-next-method)))
(when (typep #'generic-function-method-class 'generic-function)
(acknowledge :generic-function-method-class-is-generic)
(defmethod generic-function-method-class :after ((function test-generic-function))
(when (and *defmethod-called-p*
(eq function *the-function*))
(acknowledge :defmethod-calls-generic-function-method-class)))))
(when (mop-function-p "FIND-METHOD-COMBINATION")
(handler-case
(progn
(let ((*check-find-method-combination* nil))
(find-method-combination
(ensure-generic-function (gensym)
:generic-function-class 'test-generic-function)
'standard ()))
(acknowledge :find-method-combination))
(error () nil)))
(defgeneric test-function-nil ()
(:generic-function-class test-generic-function))
(defgeneric test-function (x)
(:generic-function-class test-generic-function)
(:method-class test-method))
(setf *the-function* #'test-function)
(defvar *the-method*
#-(or clozure scl)
(make-instance 'standard-method
:qualifiers '()
:lambda-list '()
:specializers '()
:function
#+(or openmcl mcl) (lambda () nil)
#+sbcl (lambda (&rest args)
(declare (ignore args))
nil)
#-(or openmcl mcl sbcl) (constantly nil))
#+scl
(make-instance 'standard-method
:qualifiers '()
:lambda-list '()
:specializers '()
:function (constantly (constantly nil)))
#+(and clozure (not closer-mop))
(make-instance 'standard-method
:qualifiers '()
:lambda-list '()
:specializers '()
:function (lambda () nil))
#+(and clozure closer-mop)
(make-instance 'standard-method
:qualifiers '()
:lambda-list '()
:specializers '()
:function (lambda (&rest args)
(declare (ignore args))
nil)
:closer-patch t))
(let ((*the-feature* :add-method-calls-compute-discriminating-function))
(add-method #'test-function-nil *the-method*))
(let ((*the-feature* :function-invocation-calls-compute-discriminating-function))
(test-function-nil))
(let ((*the-feature* :reinitialize-instance-calls-compute-discriminating-function))
(reinitialize-instance #'test-function-nil))
(let ((*the-feature* :remove-method-calls-compute-discriminating-function))
(remove-method #'test-function-nil *the-method*))
(setf *the-feature* nil)
(let ((*defmethod-called-p* t))
(eval '(defmethod test-function ((x integer)) nil)))
(let ((*defmethod-called-p* t))
(eval '(defmethod test-function ((x integer)) x)))
(defmethod test-function ((x (eql 5))) 42)
(test-function 5)
(defgeneric test-function-2 (x y)
(:generic-function-class test-generic-function)
(:argument-precedence-order y x)
(declare (optimize speed))
(:documentation "a function")
(:method-combination +)
#-(or clozure mcl)
(:method-class test-method)
(:method + (x y) (+ x y)))
(defgeneric test-function-3 (x)
(:generic-function-class test-generic-function))
(defgeneric test-function-3 (x)
(:generic-function-class test-generic-function))
(defmethod test-function-3 (x)
(declare (ignore x))
(print 'hi))
(add-method #'test-function-3
(make-instance 'standard-method
:qualifiers '()
:lambda-list '(x)
:specializers (list (find-class 't))
:function (lambda (x) x)))
(handler-case
(progn
(test-function-3 42)
(acknowledge :method-functions-take-original-parameters))
(error () (acknowledge :method-functions-take-processed-parameters)))
(cond ((member :make-method-lambda-lispworks *mop-features*)
(acknowledge :method-lambdas-are-processed))
((member :make-method-lambda *mop-features*)
(let ((method-lambda '(lambda (x) x)))
(if (eq method-lambda
(make-method-lambda
#'test-function (class-prototype (find-class 'standard-method))
method-lambda nil))
(acknowledge :method-lambdas-are-unchanged)
(acknowledge :method-lambdas-are-processed)))))
(when (mop-setf-function-p "GENERIC-FUNCTION-NAME")
(acknowledge :setf-generic-function-name)
(let ((*reinitialize-action*
(lambda (function name)
(when (and (eq function #'test-function-3)
(eq name 'test-function-4))
(acknowledge :setf-generic-function-name-calls-reinitialize-instance)))))
(setf (generic-function-name #'test-function-3)
'test-function-4)))
#+lispworks4.3
(defmethod compute-discriminating-function ((function t))
(let ((previous nil))
(lambda (&rest args)
(let ((old previous))
(setq previous (car args))
old))))
#-(or cmu clozure mcl)
(progn
(defgeneric test-function-5 (object)
(:generic-function-class test-generic-function))
(defmethod test-function-5 (object) object)
#-scl
(let ((function (compute-discriminating-function #'test-function-5)))
(handler-case
(when (eql (funcall function 4711) 4711)
(acknowledge :discriminating-functions-can-be-funcalled))
(error ())))
(defmethod compute-discriminating-function ((function test-generic-function) #+scl cache)
#+scl (declare (ignore cache))
(let ((previous nil))
(lambda (&rest args)
(let ((old previous))
(setq previous (car args))
old))))
#-scl
(set-funcallable-instance-function
#'test-function-5 (compute-discriminating-function #'test-function-5))
#+scl
(defmethod test-function-5 (object) object)
(handler-case
(when (and (eql (test-function-5 0815) nil)
(eql (test-function-5 666) 0815))
(acknowledge :discriminating-functions-can-be-closures))
(error ())))
#+(and clozure closer-mop)
(progn
(defgeneric test-function-5 (object)
(:generic-function-class test-generic-function))
(defmethod test-function-5 (object) object)
(let ((function (compute-discriminating-function #'test-function-5)))
(handler-case
(when (eql (funcall function 4711) 4711)
(acknowledge :discriminating-functions-can-be-funcalled))
(error ())))
(defmethod compute-discriminating-function ((function test-generic-function))
(let ((previous nil))
(lambda (&rest args)
(let ((old previous))
(setq previous (car args))
old))))
(set-funcallable-instance-function
#'test-function-5 (compute-discriminating-function #'test-function-5))
(handler-case
(when (and (eql (test-function-5 0815) nil)
(eql (test-function-5 666) 0815))
(acknowledge :discriminating-functions-can-be-closures))
(error ())))
(defmethod compute-discriminating-function
((gf test-generic-function) #+scl cache)
#+scl (declare (ignore cache))
(lambda () 'hello-world))
(defgeneric test-function-6 ()
(:generic-function-class test-generic-function))
(handler-case
(when (eq (test-function-6) 'hello-world)
(acknowledge :generic-functions-can-be-empty))
(error ()))
#-mcl
(progn
(defgeneric test-function-7 (x y z))
(set-funcallable-instance-function
#'test-function-7 (lambda (x y z) (* x y z)))
(handler-case
(when (and (eql (test-function-7 2 3 4) (* 2 3 4))
(eql (test-function-7 10 20 30) (* 10 20 30)))
(acknowledge :funcallable-instance-functions-can-be-closures))
(error ())))
|
1d8d5f0356ac13d3171240b5acfbff4f6f768ef5ecc914ae1bde4ee173d3134d | cloudkj/lambda-ml | regression_test.clj | (ns lambda-ml.regression-test
(:require [clojure.test :refer :all]
[lambda-ml.core :refer :all]
[lambda-ml.regression :refer :all]))
(deftest test-linear-regression
(let [data [[-2 -1]
[1 1]
[3 2]]
model (make-linear-regression 0.01 0.0 5000)
{coeff :parameters} (regression-fit model data)]
(is (< (Math/abs (- (/ 5 19) (first coeff))) 1E-6))
(is (< (Math/abs (- (/ 23 38) (second coeff))) 1E-6))))
(deftest test-linear-regression-regularization
(let [data (map (fn [[x y]] [x (* x x) (* x x x) (* x x x x) (* x x x x x) y])
[[-0.99768 2.0885]
[-0.69574 1.1646]
[-0.40373 0.3287]
[-0.10236 0.46013]
[0.22024 0.44808]
[0.47742 0.10013]
[0.82229 -0.32952]])
fit-lambda0 (regression-fit (make-linear-regression 0.1 0 10000) data)
fit-lambda1 (regression-fit (make-linear-regression 0.1 1 10000) data)
fit-lambda10 (regression-fit (make-linear-regression 0.1 10 10000) data)]
(is (> (l2-norm (:parameters fit-lambda0))
(l2-norm (:parameters fit-lambda1))))
(is (> (l2-norm (:parameters fit-lambda0))
(l2-norm (:parameters fit-lambda10))))
(is (> (l2-norm (:parameters fit-lambda1))
(l2-norm (:parameters fit-lambda10))))))
(deftest test-linear-regression2
(let [data [[-1 0]
[0 2]
[1 4]
[2 5]]
model (make-linear-regression 0.01 0.0 5000)
{coeff :parameters} (regression-fit model data)]
(is (< (Math/abs (- 1.9 (first coeff))) 1E-6))
(is (< (Math/abs (- 1.7 (second coeff))) 1E-6))))
(deftest test-linear-regression3
(let [data [[4 390]
[9 580]
[10 650]
[14 730]
[4 410]
[7 530]
[12 600]
[22 790]
[1 350]
[3 400]
[8 590]
[11 640]
[5 450]
[6 520]
[10 690]
[11 690]
[16 770]
[13 700]
[13 730]
[10 640]]
model (make-linear-regression 0.01 0.0 10000)
{coeff :parameters} (regression-fit model data)]
(is (< (Math/abs (- 353.16487949889 (first coeff))) 1E-6))
(is (< (Math/abs (- 25.326467777896 (second coeff))) 1E-6))))
(deftest test-logistic-regression
(let [data [[0.50 0]
[0.75 0]
[1.00 0]
[1.25 0]
[1.50 0]
[1.75 0]
[1.75 1]
[2.00 0]
[2.25 1]
[2.50 0]
[2.75 1]
[3.00 0]
[3.25 1]
[3.50 0]
[4.00 1]
[4.25 1]
[4.50 1]
[4.75 1]
[5.00 1]
[5.50 1]]
model (make-logistic-regression 0.1 0 10000)
{coeff :parameters} (regression-fit model data)]
(is (< (Math/abs (- -4.077713 (first coeff))) 1E-6))
(is (< (Math/abs (- 1.504645 (second coeff))) 1E-6))))
| null | https://raw.githubusercontent.com/cloudkj/lambda-ml/a470a375d2b94f5e5e623a5e198ac312b018ffb3/test/lambda_ml/regression_test.clj | clojure | (ns lambda-ml.regression-test
(:require [clojure.test :refer :all]
[lambda-ml.core :refer :all]
[lambda-ml.regression :refer :all]))
(deftest test-linear-regression
(let [data [[-2 -1]
[1 1]
[3 2]]
model (make-linear-regression 0.01 0.0 5000)
{coeff :parameters} (regression-fit model data)]
(is (< (Math/abs (- (/ 5 19) (first coeff))) 1E-6))
(is (< (Math/abs (- (/ 23 38) (second coeff))) 1E-6))))
(deftest test-linear-regression-regularization
(let [data (map (fn [[x y]] [x (* x x) (* x x x) (* x x x x) (* x x x x x) y])
[[-0.99768 2.0885]
[-0.69574 1.1646]
[-0.40373 0.3287]
[-0.10236 0.46013]
[0.22024 0.44808]
[0.47742 0.10013]
[0.82229 -0.32952]])
fit-lambda0 (regression-fit (make-linear-regression 0.1 0 10000) data)
fit-lambda1 (regression-fit (make-linear-regression 0.1 1 10000) data)
fit-lambda10 (regression-fit (make-linear-regression 0.1 10 10000) data)]
(is (> (l2-norm (:parameters fit-lambda0))
(l2-norm (:parameters fit-lambda1))))
(is (> (l2-norm (:parameters fit-lambda0))
(l2-norm (:parameters fit-lambda10))))
(is (> (l2-norm (:parameters fit-lambda1))
(l2-norm (:parameters fit-lambda10))))))
(deftest test-linear-regression2
(let [data [[-1 0]
[0 2]
[1 4]
[2 5]]
model (make-linear-regression 0.01 0.0 5000)
{coeff :parameters} (regression-fit model data)]
(is (< (Math/abs (- 1.9 (first coeff))) 1E-6))
(is (< (Math/abs (- 1.7 (second coeff))) 1E-6))))
(deftest test-linear-regression3
(let [data [[4 390]
[9 580]
[10 650]
[14 730]
[4 410]
[7 530]
[12 600]
[22 790]
[1 350]
[3 400]
[8 590]
[11 640]
[5 450]
[6 520]
[10 690]
[11 690]
[16 770]
[13 700]
[13 730]
[10 640]]
model (make-linear-regression 0.01 0.0 10000)
{coeff :parameters} (regression-fit model data)]
(is (< (Math/abs (- 353.16487949889 (first coeff))) 1E-6))
(is (< (Math/abs (- 25.326467777896 (second coeff))) 1E-6))))
(deftest test-logistic-regression
(let [data [[0.50 0]
[0.75 0]
[1.00 0]
[1.25 0]
[1.50 0]
[1.75 0]
[1.75 1]
[2.00 0]
[2.25 1]
[2.50 0]
[2.75 1]
[3.00 0]
[3.25 1]
[3.50 0]
[4.00 1]
[4.25 1]
[4.50 1]
[4.75 1]
[5.00 1]
[5.50 1]]
model (make-logistic-regression 0.1 0 10000)
{coeff :parameters} (regression-fit model data)]
(is (< (Math/abs (- -4.077713 (first coeff))) 1E-6))
(is (< (Math/abs (- 1.504645 (second coeff))) 1E-6))))
| |
0589c09d67cbbdba3efb6bf644771ddfde783c9473cf4d7cfbacb8602fe487c8 | kupl/LearnML | patch.ml | type btree = Empty | Node of (int * btree * btree)
let rec mem (n : int) (tree : btree) : bool =
match tree with
| Empty -> false
| Node (a, b, c) ->
if a = n then true else if mem n b = true then mem n b else mem n c
| null | https://raw.githubusercontent.com/kupl/LearnML/c98ef2b95ef67e657b8158a2c504330e9cfb7700/result/cafe2/mem/sub19/patch.ml | ocaml | type btree = Empty | Node of (int * btree * btree)
let rec mem (n : int) (tree : btree) : bool =
match tree with
| Empty -> false
| Node (a, b, c) ->
if a = n then true else if mem n b = true then mem n b else mem n c
| |
62aa9eb304a2d445f833de89e5a9bbfb349256e6166197efc36c2647427a832b | patricoferris/meio | meio.ml | let run _stdenv exec_args =
let argsl = String.split_on_char ' ' exec_args in
let executable_filename = List.hd argsl in
let argsl = Array.of_list argsl in
let tmp_dir = Filename.get_temp_dir_name () in
let env =
Array.append
[|
"OCAML_RUNTIME_EVENTS_START=1";
"OCAML_RUNTIME_EVENTS_DIR=" ^ tmp_dir;
"OCAML_RUNTIME_EVENTS_PRESERVE=1";
|]
(Unix.environment ())
in
let child_pid =
Unix.create_process_env executable_filename argsl env Unix.stdin Unix.stdout
Unix.stderr
in
Unix.sleepf 0.2;
let handle = (tmp_dir, child_pid) in
Meio.ui handle;
Unix.kill child_pid Sys.sigkill;
let ring_file =
Filename.concat tmp_dir (string_of_int child_pid ^ ".events")
in
Unix.unlink ring_file
let () = Eio_main.run @@ fun stdenv -> run stdenv Sys.argv.(1)
| null | https://raw.githubusercontent.com/patricoferris/meio/e3104e53d4ebc99285348a7854d4de121529376a/src/bin/meio.ml | ocaml | let run _stdenv exec_args =
let argsl = String.split_on_char ' ' exec_args in
let executable_filename = List.hd argsl in
let argsl = Array.of_list argsl in
let tmp_dir = Filename.get_temp_dir_name () in
let env =
Array.append
[|
"OCAML_RUNTIME_EVENTS_START=1";
"OCAML_RUNTIME_EVENTS_DIR=" ^ tmp_dir;
"OCAML_RUNTIME_EVENTS_PRESERVE=1";
|]
(Unix.environment ())
in
let child_pid =
Unix.create_process_env executable_filename argsl env Unix.stdin Unix.stdout
Unix.stderr
in
Unix.sleepf 0.2;
let handle = (tmp_dir, child_pid) in
Meio.ui handle;
Unix.kill child_pid Sys.sigkill;
let ring_file =
Filename.concat tmp_dir (string_of_int child_pid ^ ".events")
in
Unix.unlink ring_file
let () = Eio_main.run @@ fun stdenv -> run stdenv Sys.argv.(1)
| |
5ab3b6d988adedaeff1c4d8b9c0b80a7d1a54e32b8976d90da887b40e50a36db | astrada/ocaml-extjs | ext_tip_ToolTip.mli | * ToolTip is a Ext.tip . Tip implementation that handl ...
{ % < p > ToolTip is a < a href="#!/api / Ext.tip . Tip " rel="Ext.tip . Tip " class="docClass">Ext.tip . Tip</a > implementation that handles the common case of displaying a
tooltip when hovering over a certain element or elements on the page . It allows fine - grained
control over the tooltip 's alignment relative to the target element or mouse , and the timing
of when it is automatically shown and hidden.</p >
< p > This implementation does < strong > not</strong > have a built - in method of automatically populating the tooltip 's
text based on the target element ; you must either configure a fixed < a href="#!/api / Ext.tip . ToolTip - cfg - html " rel="Ext.tip . ToolTip - cfg - html " class="docClass">html</a > value for each
ToolTip instance , or implement custom logic ( e.g. in a < a href="#!/api / Ext.tip . ToolTip - event - beforeshow " rel="Ext.tip . ToolTip - event - beforeshow " class="docClass">beforeshow</a > event listener ) to
generate the appropriate tooltip content on the fly . See < a href="#!/api / Ext.tip . " rel="Ext.tip . " class="docClass">Ext.tip . QuickTip</a > for a more
convenient way of automatically populating and configuring a tooltip based on specific DOM
attributes of each target element.</p >
< h1 > Basic Example</h1 >
< pre><code > var tip = < a href="#!/api / Ext - method - create " rel="Ext - method - create " class="docClass">Ext.create</a>('<a href="#!/api / Ext.tip . ToolTip " rel="Ext.tip . ToolTip " class="docClass">Ext.tip . ToolTip</a > ' , \ {
target : ' clearButton ' ,
html : ' Press this button to clear the form '
\ } ) ;
< /code></pre >
< p><p><img src= " " alt="Basic Ext.tip . ToolTip " width= " " height=""></p></p >
< h1 > Delegation</h1 >
< p > In addition to attaching a ToolTip to a single element , you can also use delegation to attach
one ToolTip to many elements under a common parent . This is more efficient than creating many
ToolTip instances . To do this , point the < a href="#!/api / Ext.tip . ToolTip - cfg - target " rel="Ext.tip . ToolTip - cfg - target " class="docClass">target</a > config to a common ancestor of all the
elements , and then set the < a href="#!/api / Ext.tip . ToolTip - cfg - delegate " rel="Ext.tip . ToolTip - cfg - delegate " class="docClass">delegate</a > config to a CSS selector that will select all the
appropriate sub - elements.</p >
< p > When using delegation , it is likely that you will want to programmatically change the content
of the ToolTip based on each delegate element ; you can do this by implementing a custom
listener for the < a href="#!/api / Ext.tip . ToolTip - event - beforeshow " rel="Ext.tip . ToolTip - event - beforeshow " class="docClass">beforeshow</a > event . Example:</p >
< pre><code > var store = < a href="#!/api / Ext - method - create " rel="Ext - method - create " class="docClass">Ext.create</a>('<a href="#!/api / Ext.data . ArrayStore " rel="Ext.data . ArrayStore " class="docClass">Ext.data . ArrayStore</a > ' , \ {
fields : [ ' company ' , ' price ' , ' change ' ] ,
data : [
[ ' 3 m Co ' , 71.72 , 0.02 ] ,
[ ' Alcoa Inc ' , 29.01 , 0.42 ] ,
[ ' Altria Group Inc ' , 83.81 , 0.28 ] ,
[ ' American Express Company ' , 52.55 , 0.01 ] ,
[ ' American International Group , Inc. ' , 64.13 , 0.31 ] ,
[ ' AT&T Inc. ' , 31.61 , -0.48 ]
]
\ } ) ;
var grid = < a href="#!/api / Ext - method - create " rel="Ext - method - create " class="docClass">Ext.create</a>('<a href="#!/api / Ext.grid . Panel " rel="Ext.grid . Panel " class="docClass">Ext.grid . Panel</a > ' , \ {
title : ' Array Grid ' ,
store : store ,
columns : [
\{text : ' Company ' , flex : 1 , : ' company'\ } ,
\{text : ' Price ' , width : 75 , : ' price'\ } ,
\{text : ' Change ' , width : 75 , : ' change'\ }
] ,
height : 200 ,
width : 400 ,
renderTo : < a href="#!/api / Ext - method - getBody " rel="Ext - method - getBody " class="docClass">Ext.getBody</a > ( )
\ } ) ;
var view = grid.getView ( ) ;
var tip = < a href="#!/api / Ext - method - create " rel="Ext - method - create " class="docClass">Ext.create</a>('<a href="#!/api / Ext.tip . ToolTip " rel="Ext.tip . ToolTip " class="docClass">Ext.tip . ToolTip</a > ' , \ {
// The overall target element .
target : view.el ,
// Each grid row causes its own separate show and hide .
delegate : view.itemSelector ,
// Moving within the row should not hide the tip .
trackMouse : true ,
// Render immediately so that tip.body can be referenced prior to the first show .
renderTo : < a href="#!/api / Ext - method - getBody " rel="Ext - method - getBody " class="docClass">Ext.getBody</a > ( ) ,
listeners : \ {
// Change content dynamically depending on which element triggered the show .
: function updateTipBody(tip ) \ {
tip.update('Over company " ' + view.getRecord(tip.triggerElement).get('company ' ) + ' " ' ) ;
\ }
\ }
\ } ) ;
< /code></pre >
< p><p><img src= " " alt="Ext.tip . ToolTip with delegation " width= " " height=""></p></p >
< h1 > Alignment</h1 >
< p > The following configuration properties allow control over how the ToolTip is aligned relative to
the target element and/or mouse pointer:</p >
< ul >
< li><a href="#!/api / Ext.tip . ToolTip - cfg - anchor " rel="Ext.tip . ToolTip - cfg - anchor " class="docClass">anchor</a></li >
< li><a href="#!/api / Ext.tip . ToolTip - cfg - anchorToTarget " rel="Ext.tip . ToolTip - cfg - anchorToTarget " class="docClass">anchorToTarget</a></li >
< li><a href="#!/api / Ext.tip . ToolTip - cfg - anchorOffset " rel="Ext.tip . ToolTip - cfg - anchorOffset " class="docClass">anchorOffset</a></li >
< li><a href="#!/api / Ext.tip . ToolTip - cfg - trackMouse " rel="Ext.tip . ToolTip - cfg - trackMouse " class="docClass">trackMouse</a></li >
< li><a href="#!/api / Ext.tip . ToolTip - cfg - mouseOffset " rel="Ext.tip . ToolTip - cfg - mouseOffset " class="docClass">mouseOffset</a></li >
< /ul >
< h1 > Showing / Hiding</h1 >
< p > The following configuration properties allow control over how and when the ToolTip is automatically
shown and hidden:</p >
< ul >
< li><a href="#!/api / Ext.tip . ToolTip - cfg - autoHide " rel="Ext.tip . ToolTip - cfg - autoHide " class="docClass">autoHide</a></li >
< li><a href="#!/api / Ext.tip . ToolTip - cfg - showDelay " rel="Ext.tip . ToolTip - cfg - showDelay " >
< li><a href="#!/api / Ext.tip . ToolTip - cfg - hideDelay " rel="Ext.tip . ToolTip - cfg - hideDelay " class="docClass">hideDelay</a></li >
< li><a href="#!/api / Ext.tip . ToolTip - cfg - dismissDelay " rel="Ext.tip . ToolTip - cfg - dismissDelay " class="docClass">dismissDelay</a></li >
< /ul > % }
{% <p>ToolTip is a <a href="#!/api/Ext.tip.Tip" rel="Ext.tip.Tip" class="docClass">Ext.tip.Tip</a> implementation that handles the common case of displaying a
tooltip when hovering over a certain element or elements on the page. It allows fine-grained
control over the tooltip's alignment relative to the target element or mouse, and the timing
of when it is automatically shown and hidden.</p>
<p>This implementation does <strong>not</strong> have a built-in method of automatically populating the tooltip's
text based on the target element; you must either configure a fixed <a href="#!/api/Ext.tip.ToolTip-cfg-html" rel="Ext.tip.ToolTip-cfg-html" class="docClass">html</a> value for each
ToolTip instance, or implement custom logic (e.g. in a <a href="#!/api/Ext.tip.ToolTip-event-beforeshow" rel="Ext.tip.ToolTip-event-beforeshow" class="docClass">beforeshow</a> event listener) to
generate the appropriate tooltip content on the fly. See <a href="#!/api/Ext.tip.QuickTip" rel="Ext.tip.QuickTip" class="docClass">Ext.tip.QuickTip</a> for a more
convenient way of automatically populating and configuring a tooltip based on specific DOM
attributes of each target element.</p>
<h1>Basic Example</h1>
<pre><code>var tip = <a href="#!/api/Ext-method-create" rel="Ext-method-create" class="docClass">Ext.create</a>('<a href="#!/api/Ext.tip.ToolTip" rel="Ext.tip.ToolTip" class="docClass">Ext.tip.ToolTip</a>', \{
target: 'clearButton',
html: 'Press this button to clear the form'
\});
</code></pre>
<p><p><img src="" alt="Basic Ext.tip.ToolTip" width="" height=""></p></p>
<h1>Delegation</h1>
<p>In addition to attaching a ToolTip to a single element, you can also use delegation to attach
one ToolTip to many elements under a common parent. This is more efficient than creating many
ToolTip instances. To do this, point the <a href="#!/api/Ext.tip.ToolTip-cfg-target" rel="Ext.tip.ToolTip-cfg-target" class="docClass">target</a> config to a common ancestor of all the
elements, and then set the <a href="#!/api/Ext.tip.ToolTip-cfg-delegate" rel="Ext.tip.ToolTip-cfg-delegate" class="docClass">delegate</a> config to a CSS selector that will select all the
appropriate sub-elements.</p>
<p>When using delegation, it is likely that you will want to programmatically change the content
of the ToolTip based on each delegate element; you can do this by implementing a custom
listener for the <a href="#!/api/Ext.tip.ToolTip-event-beforeshow" rel="Ext.tip.ToolTip-event-beforeshow" class="docClass">beforeshow</a> event. Example:</p>
<pre><code>var store = <a href="#!/api/Ext-method-create" rel="Ext-method-create" class="docClass">Ext.create</a>('<a href="#!/api/Ext.data.ArrayStore" rel="Ext.data.ArrayStore" class="docClass">Ext.data.ArrayStore</a>', \{
fields: ['company', 'price', 'change'],
data: [
['3m Co', 71.72, 0.02],
['Alcoa Inc', 29.01, 0.42],
['Altria Group Inc', 83.81, 0.28],
['American Express Company', 52.55, 0.01],
['American International Group, Inc.', 64.13, 0.31],
['AT&T Inc.', 31.61, -0.48]
]
\});
var grid = <a href="#!/api/Ext-method-create" rel="Ext-method-create" class="docClass">Ext.create</a>('<a href="#!/api/Ext.grid.Panel" rel="Ext.grid.Panel" class="docClass">Ext.grid.Panel</a>', \{
title: 'Array Grid',
store: store,
columns: [
\{text: 'Company', flex: 1, dataIndex: 'company'\},
\{text: 'Price', width: 75, dataIndex: 'price'\},
\{text: 'Change', width: 75, dataIndex: 'change'\}
],
height: 200,
width: 400,
renderTo: <a href="#!/api/Ext-method-getBody" rel="Ext-method-getBody" class="docClass">Ext.getBody</a>()
\});
var view = grid.getView();
var tip = <a href="#!/api/Ext-method-create" rel="Ext-method-create" class="docClass">Ext.create</a>('<a href="#!/api/Ext.tip.ToolTip" rel="Ext.tip.ToolTip" class="docClass">Ext.tip.ToolTip</a>', \{
// The overall target element.
target: view.el,
// Each grid row causes its own separate show and hide.
delegate: view.itemSelector,
// Moving within the row should not hide the tip.
trackMouse: true,
// Render immediately so that tip.body can be referenced prior to the first show.
renderTo: <a href="#!/api/Ext-method-getBody" rel="Ext-method-getBody" class="docClass">Ext.getBody</a>(),
listeners: \{
// Change content dynamically depending on which element triggered the show.
beforeshow: function updateTipBody(tip) \{
tip.update('Over company "' + view.getRecord(tip.triggerElement).get('company') + '"');
\}
\}
\});
</code></pre>
<p><p><img src="" alt="Ext.tip.ToolTip with delegation" width="" height=""></p></p>
<h1>Alignment</h1>
<p>The following configuration properties allow control over how the ToolTip is aligned relative to
the target element and/or mouse pointer:</p>
<ul>
<li><a href="#!/api/Ext.tip.ToolTip-cfg-anchor" rel="Ext.tip.ToolTip-cfg-anchor" class="docClass">anchor</a></li>
<li><a href="#!/api/Ext.tip.ToolTip-cfg-anchorToTarget" rel="Ext.tip.ToolTip-cfg-anchorToTarget" class="docClass">anchorToTarget</a></li>
<li><a href="#!/api/Ext.tip.ToolTip-cfg-anchorOffset" rel="Ext.tip.ToolTip-cfg-anchorOffset" class="docClass">anchorOffset</a></li>
<li><a href="#!/api/Ext.tip.ToolTip-cfg-trackMouse" rel="Ext.tip.ToolTip-cfg-trackMouse" class="docClass">trackMouse</a></li>
<li><a href="#!/api/Ext.tip.ToolTip-cfg-mouseOffset" rel="Ext.tip.ToolTip-cfg-mouseOffset" class="docClass">mouseOffset</a></li>
</ul>
<h1>Showing/Hiding</h1>
<p>The following configuration properties allow control over how and when the ToolTip is automatically
shown and hidden:</p>
<ul>
<li><a href="#!/api/Ext.tip.ToolTip-cfg-autoHide" rel="Ext.tip.ToolTip-cfg-autoHide" class="docClass">autoHide</a></li>
<li><a href="#!/api/Ext.tip.ToolTip-cfg-showDelay" rel="Ext.tip.ToolTip-cfg-showDelay" class="docClass">showDelay</a></li>
<li><a href="#!/api/Ext.tip.ToolTip-cfg-hideDelay" rel="Ext.tip.ToolTip-cfg-hideDelay" class="docClass">hideDelay</a></li>
<li><a href="#!/api/Ext.tip.ToolTip-cfg-dismissDelay" rel="Ext.tip.ToolTip-cfg-dismissDelay" class="docClass">dismissDelay</a></li>
</ul> %}
*)
class type t =
object('self)
inherit Ext_tip_Tip.t
method triggerElement : Dom_html.element Js.t Js.prop
* { % < p > When a ToolTip is configured with the < code><a href="#!/api / Ext.tip . ToolTip - cfg - delegate " rel="Ext.tip . ToolTip - cfg - delegate " class="docClass">delegate</a></code >
option to cause selected child elements of the < code><a href="#!/api / Ext.tip . ToolTip - cfg - target " rel="Ext.tip . ToolTip - cfg - target " class="docClass">target</a></code >
Element to each trigger a separate show event , this property is set to
the DOM element which triggered the show.</p > % }
option to cause selected child elements of the <code><a href="#!/api/Ext.tip.ToolTip-cfg-target" rel="Ext.tip.ToolTip-cfg-target" class="docClass">target</a></code>
Element to each trigger a separate show event, this property is set to
the DOM element which triggered the show.</p> %}
*)
method beforeDestroy : unit Js.meth
(** {% <p>Invoked before the Component is destroyed.</p> %}
*)
method hide_tooltip : unit Js.meth
(** {% <p>Hides this tooltip if visible.</p> %}
*)
method setTarget : _ Js.t -> unit Js.meth
* { % < p > Binds this ToolTip to the specified element . The tooltip will be displayed when the mouse moves over the element.</p > % }
{ b Parameters } :
{ ul { - t : [ _ Js.t ]
{ % < p > The Element , HtmlElement , or ID of an element to bind to</p > % }
}
}
{b Parameters}:
{ul {- t: [_ Js.t]
{% <p>The Element, HtmlElement, or ID of an element to bind to</p> %}
}
}
*)
method show_tooltip : unit Js.meth
* { % < p > Shows this tooltip at the current event target XY position.</p > % }
*)
method showAt_arr : Js.number Js.t Js.js_array Js.t -> unit Js.meth
* { % < p > Shows this tip at the specified XY position . Example usage:</p >
< pre><code>// Show the tip at and y:100
tip.showAt([50,100 ] ) ;
< /code></pre > % }
{ b Parameters } :
{ ul { - xy : [ Js.number Js.t Js.js_array Js.t ]
{ % < p > An array containing the x and > % }
}
}
<pre><code>// Show the tip at x:50 and y:100
tip.showAt([50,100]);
</code></pre> %}
{b Parameters}:
{ul {- xy: [Js.number Js.t Js.js_array Js.t]
{% <p>An array containing the x and y coordinates</p> %}
}
}
*)
end
class type configs =
object('self)
inherit Ext_tip_Tip.configs
method anchor : Js.js_string Js.t Js.prop
* { % < p > If specified , indicates that the tip should be anchored to a
particular side of the target element or mouse pointer ( " top " , " right " , " bottom " ,
or " left " ) , with an arrow pointing back at the target or mouse pointer . If
< a href="#!/api / Ext.tip . ToolTip - cfg - constrainPosition " rel="Ext.tip . ToolTip - cfg - constrainPosition " class="docClass">constrainPosition</a > is enabled , this will be used as a preferred value
only and may be flipped as needed.</p > % }
particular side of the target element or mouse pointer ("top", "right", "bottom",
or "left"), with an arrow pointing back at the target or mouse pointer. If
<a href="#!/api/Ext.tip.ToolTip-cfg-constrainPosition" rel="Ext.tip.ToolTip-cfg-constrainPosition" class="docClass">constrainPosition</a> is enabled, this will be used as a preferred value
only and may be flipped as needed.</p> %}
*)
method anchorOffset : Js.number Js.t Js.prop
* { % < p > A numeric pixel value used to offset the default position of the anchor arrow . When the anchor
position is on the top or bottom of the tooltip , < code > > will be used as a horizontal offset .
Likewise , when the anchor position is on the left or right side , < code > > will be used as
a vertical offset.</p > % }
Defaults to : [ 0 ]
position is on the top or bottom of the tooltip, <code>anchorOffset</code> will be used as a horizontal offset.
Likewise, when the anchor position is on the left or right side, <code>anchorOffset</code> will be used as
a vertical offset.</p> %}
Defaults to: [0]
*)
method anchorToTarget : bool Js.t Js.prop
* { % < p > True to anchor the tooltip to the target element , false to anchor it relative to the mouse coordinates .
When < code > anchorToTarget</code > is true , use < code><a href="#!/api / Ext.tip . ToolTip - cfg - defaultAlign " rel="Ext.tip . ToolTip - cfg - defaultAlign " class="docClass">defaultAlign</a></code > to control tooltip alignment to the
target element . When < code > anchorToTarget</code > is false , use < code><a href="#!/api / Ext.tip . ToolTip - cfg - anchor " rel="Ext.tip . ToolTip - cfg - anchor " class="docClass">anchor</a></code > instead to control alignment.</p > % }
Defaults to : [ true ]
When <code>anchorToTarget</code> is true, use <code><a href="#!/api/Ext.tip.ToolTip-cfg-defaultAlign" rel="Ext.tip.ToolTip-cfg-defaultAlign" class="docClass">defaultAlign</a></code> to control tooltip alignment to the
target element. When <code>anchorToTarget</code> is false, use <code><a href="#!/api/Ext.tip.ToolTip-cfg-anchor" rel="Ext.tip.ToolTip-cfg-anchor" class="docClass">anchor</a></code> instead to control alignment.</p> %}
Defaults to: [true]
*)
method autoHide : bool Js.t Js.prop
* { % < p > True to automatically hide the tooltip after the
mouse exits the target element or after the < code><a href="#!/api / Ext.tip . ToolTip - cfg - dismissDelay " rel="Ext.tip . ToolTip - cfg - dismissDelay " class="docClass">dismissDelay</a></code >
has expired if set . If < code><a href="#!/api / Ext.tip . ToolTip - cfg - closable " rel="Ext.tip . ToolTip - cfg - closable " class="docClass">closable</a > = true</code >
a close tool button will be rendered into the tooltip > % }
Defaults to : [ true ]
mouse exits the target element or after the <code><a href="#!/api/Ext.tip.ToolTip-cfg-dismissDelay" rel="Ext.tip.ToolTip-cfg-dismissDelay" class="docClass">dismissDelay</a></code>
has expired if set. If <code><a href="#!/api/Ext.tip.ToolTip-cfg-closable" rel="Ext.tip.ToolTip-cfg-closable" class="docClass">closable</a> = true</code>
a close tool button will be rendered into the tooltip header.</p> %}
Defaults to: [true]
*)
method delegate : Js.js_string Js.t Js.prop
* { % < p > A < a href="#!/api / Ext.dom . Query " rel="Ext.dom . Query " class="docClass">DomQuery</a > selector which allows selection of individual elements within the
< code><a href="#!/api / Ext.tip . ToolTip - cfg - target " rel="Ext.tip . ToolTip - cfg - target " class="docClass">target</a></code > element to trigger showing and hiding the ToolTip as the mouse moves within the
target.</p >
< p > When specified , the child element of the target which caused a show event is placed into the
< code><a href="#!/api / Ext.tip . ToolTip - property - triggerElement " rel="Ext.tip . ToolTip - property - triggerElement " class="docClass">triggerElement</a></code > property before the ToolTip is shown.</p >
< p > This may be useful when a Component has regular , repeating elements in it , each of which need a
ToolTip which contains information specific to that element.</p >
< p > See the delegate example in class documentation of < a href="#!/api / Ext.tip . ToolTip " rel="Ext.tip . ToolTip " class="docClass">Ext.tip . ToolTip</a>.</p > % }
<code><a href="#!/api/Ext.tip.ToolTip-cfg-target" rel="Ext.tip.ToolTip-cfg-target" class="docClass">target</a></code> element to trigger showing and hiding the ToolTip as the mouse moves within the
target.</p>
<p>When specified, the child element of the target which caused a show event is placed into the
<code><a href="#!/api/Ext.tip.ToolTip-property-triggerElement" rel="Ext.tip.ToolTip-property-triggerElement" class="docClass">triggerElement</a></code> property before the ToolTip is shown.</p>
<p>This may be useful when a Component has regular, repeating elements in it, each of which need a
ToolTip which contains information specific to that element.</p>
<p>See the delegate example in class documentation of <a href="#!/api/Ext.tip.ToolTip" rel="Ext.tip.ToolTip" class="docClass">Ext.tip.ToolTip</a>.</p> %}
*)
method dismissDelay : Js.number Js.t Js.prop
* { % < p > Delay in milliseconds before the tooltip automatically hides . To disable automatic hiding , set
dismissDelay = 0.</p > % }
Defaults to : [ 5000 ]
dismissDelay = 0.</p> %}
Defaults to: [5000]
*)
method hideDelay : Js.number Js.t Js.prop
* { % < p > Delay in milliseconds after the mouse exits the target element but before the tooltip actually hides .
Set to 0 for the tooltip to hide immediately.</p > % }
Defaults to : [ 200 ]
Set to 0 for the tooltip to hide immediately.</p> %}
Defaults to: [200]
*)
method mouseOffset : Js.number Js.t Js.js_array Js.t Js.prop
* { % < p > An XY offset from the mouse position where the tooltip should be shown.</p > % }
Defaults to : [ 15,18 ]
Defaults to: [15,18]
*)
method showDelay : Js.number Js.t Js.prop
* { % < p > Delay in milliseconds before the tooltip displays after the mouse enters the target element.</p > % }
Defaults to : [ 500 ]
Defaults to: [500]
*)
method target : _ Js.t Js.prop
* { % < p > The target element or string i d to monitor for mouseover events to trigger
showing this ToolTip.</p > % }
showing this ToolTip.</p> %}
*)
method trackMouse : bool Js.t Js.prop
* { % < p > True to have the tooltip follow the mouse as it moves over the target element.</p > % }
Defaults to : [ false ]
Defaults to: [false]
*)
method beforeDestroy : ('self Js.t, unit -> unit) Js.meth_callback
Js.writeonly_prop
(** See method [t.beforeDestroy] *)
end
class type events =
object
inherit Ext_tip_Tip.events
end
class type statics =
object
inherit Ext_tip_Tip.statics
end
val of_configs : configs Js.t -> t Js.t
(** [of_configs c] casts a config object [c] to an instance of class [t] *)
val to_configs : t Js.t -> configs Js.t
(** [to_configs o] casts instance [o] of class [t] to a config object *)
| null | https://raw.githubusercontent.com/astrada/ocaml-extjs/77df630a75fb84667ee953f218c9ce375b3e7484/lib/ext_tip_ToolTip.mli | ocaml | * {% <p>Invoked before the Component is destroyed.</p> %}
* {% <p>Hides this tooltip if visible.</p> %}
* See method [t.beforeDestroy]
* [of_configs c] casts a config object [c] to an instance of class [t]
* [to_configs o] casts instance [o] of class [t] to a config object | * ToolTip is a Ext.tip . Tip implementation that handl ...
{ % < p > ToolTip is a < a href="#!/api / Ext.tip . Tip " rel="Ext.tip . Tip " class="docClass">Ext.tip . Tip</a > implementation that handles the common case of displaying a
tooltip when hovering over a certain element or elements on the page . It allows fine - grained
control over the tooltip 's alignment relative to the target element or mouse , and the timing
of when it is automatically shown and hidden.</p >
< p > This implementation does < strong > not</strong > have a built - in method of automatically populating the tooltip 's
text based on the target element ; you must either configure a fixed < a href="#!/api / Ext.tip . ToolTip - cfg - html " rel="Ext.tip . ToolTip - cfg - html " class="docClass">html</a > value for each
ToolTip instance , or implement custom logic ( e.g. in a < a href="#!/api / Ext.tip . ToolTip - event - beforeshow " rel="Ext.tip . ToolTip - event - beforeshow " class="docClass">beforeshow</a > event listener ) to
generate the appropriate tooltip content on the fly . See < a href="#!/api / Ext.tip . " rel="Ext.tip . " class="docClass">Ext.tip . QuickTip</a > for a more
convenient way of automatically populating and configuring a tooltip based on specific DOM
attributes of each target element.</p >
< h1 > Basic Example</h1 >
< pre><code > var tip = < a href="#!/api / Ext - method - create " rel="Ext - method - create " class="docClass">Ext.create</a>('<a href="#!/api / Ext.tip . ToolTip " rel="Ext.tip . ToolTip " class="docClass">Ext.tip . ToolTip</a > ' , \ {
target : ' clearButton ' ,
html : ' Press this button to clear the form '
\ } ) ;
< /code></pre >
< p><p><img src= " " alt="Basic Ext.tip . ToolTip " width= " " height=""></p></p >
< h1 > Delegation</h1 >
< p > In addition to attaching a ToolTip to a single element , you can also use delegation to attach
one ToolTip to many elements under a common parent . This is more efficient than creating many
ToolTip instances . To do this , point the < a href="#!/api / Ext.tip . ToolTip - cfg - target " rel="Ext.tip . ToolTip - cfg - target " class="docClass">target</a > config to a common ancestor of all the
elements , and then set the < a href="#!/api / Ext.tip . ToolTip - cfg - delegate " rel="Ext.tip . ToolTip - cfg - delegate " class="docClass">delegate</a > config to a CSS selector that will select all the
appropriate sub - elements.</p >
< p > When using delegation , it is likely that you will want to programmatically change the content
of the ToolTip based on each delegate element ; you can do this by implementing a custom
listener for the < a href="#!/api / Ext.tip . ToolTip - event - beforeshow " rel="Ext.tip . ToolTip - event - beforeshow " class="docClass">beforeshow</a > event . Example:</p >
< pre><code > var store = < a href="#!/api / Ext - method - create " rel="Ext - method - create " class="docClass">Ext.create</a>('<a href="#!/api / Ext.data . ArrayStore " rel="Ext.data . ArrayStore " class="docClass">Ext.data . ArrayStore</a > ' , \ {
fields : [ ' company ' , ' price ' , ' change ' ] ,
data : [
[ ' 3 m Co ' , 71.72 , 0.02 ] ,
[ ' Alcoa Inc ' , 29.01 , 0.42 ] ,
[ ' Altria Group Inc ' , 83.81 , 0.28 ] ,
[ ' American Express Company ' , 52.55 , 0.01 ] ,
[ ' American International Group , Inc. ' , 64.13 , 0.31 ] ,
[ ' AT&T Inc. ' , 31.61 , -0.48 ]
]
\ } ) ;
var grid = < a href="#!/api / Ext - method - create " rel="Ext - method - create " class="docClass">Ext.create</a>('<a href="#!/api / Ext.grid . Panel " rel="Ext.grid . Panel " class="docClass">Ext.grid . Panel</a > ' , \ {
title : ' Array Grid ' ,
store : store ,
columns : [
\{text : ' Company ' , flex : 1 , : ' company'\ } ,
\{text : ' Price ' , width : 75 , : ' price'\ } ,
\{text : ' Change ' , width : 75 , : ' change'\ }
] ,
height : 200 ,
width : 400 ,
renderTo : < a href="#!/api / Ext - method - getBody " rel="Ext - method - getBody " class="docClass">Ext.getBody</a > ( )
\ } ) ;
var view = grid.getView ( ) ;
var tip = < a href="#!/api / Ext - method - create " rel="Ext - method - create " class="docClass">Ext.create</a>('<a href="#!/api / Ext.tip . ToolTip " rel="Ext.tip . ToolTip " class="docClass">Ext.tip . ToolTip</a > ' , \ {
// The overall target element .
target : view.el ,
// Each grid row causes its own separate show and hide .
delegate : view.itemSelector ,
// Moving within the row should not hide the tip .
trackMouse : true ,
// Render immediately so that tip.body can be referenced prior to the first show .
renderTo : < a href="#!/api / Ext - method - getBody " rel="Ext - method - getBody " class="docClass">Ext.getBody</a > ( ) ,
listeners : \ {
// Change content dynamically depending on which element triggered the show .
: function updateTipBody(tip ) \ {
tip.update('Over company " ' + view.getRecord(tip.triggerElement).get('company ' ) + ' " ' ) ;
\ }
\ }
\ } ) ;
< /code></pre >
< p><p><img src= " " alt="Ext.tip . ToolTip with delegation " width= " " height=""></p></p >
< h1 > Alignment</h1 >
< p > The following configuration properties allow control over how the ToolTip is aligned relative to
the target element and/or mouse pointer:</p >
< ul >
< li><a href="#!/api / Ext.tip . ToolTip - cfg - anchor " rel="Ext.tip . ToolTip - cfg - anchor " class="docClass">anchor</a></li >
< li><a href="#!/api / Ext.tip . ToolTip - cfg - anchorToTarget " rel="Ext.tip . ToolTip - cfg - anchorToTarget " class="docClass">anchorToTarget</a></li >
< li><a href="#!/api / Ext.tip . ToolTip - cfg - anchorOffset " rel="Ext.tip . ToolTip - cfg - anchorOffset " class="docClass">anchorOffset</a></li >
< li><a href="#!/api / Ext.tip . ToolTip - cfg - trackMouse " rel="Ext.tip . ToolTip - cfg - trackMouse " class="docClass">trackMouse</a></li >
< li><a href="#!/api / Ext.tip . ToolTip - cfg - mouseOffset " rel="Ext.tip . ToolTip - cfg - mouseOffset " class="docClass">mouseOffset</a></li >
< /ul >
< h1 > Showing / Hiding</h1 >
< p > The following configuration properties allow control over how and when the ToolTip is automatically
shown and hidden:</p >
< ul >
< li><a href="#!/api / Ext.tip . ToolTip - cfg - autoHide " rel="Ext.tip . ToolTip - cfg - autoHide " class="docClass">autoHide</a></li >
< li><a href="#!/api / Ext.tip . ToolTip - cfg - showDelay " rel="Ext.tip . ToolTip - cfg - showDelay " >
< li><a href="#!/api / Ext.tip . ToolTip - cfg - hideDelay " rel="Ext.tip . ToolTip - cfg - hideDelay " class="docClass">hideDelay</a></li >
< li><a href="#!/api / Ext.tip . ToolTip - cfg - dismissDelay " rel="Ext.tip . ToolTip - cfg - dismissDelay " class="docClass">dismissDelay</a></li >
< /ul > % }
{% <p>ToolTip is a <a href="#!/api/Ext.tip.Tip" rel="Ext.tip.Tip" class="docClass">Ext.tip.Tip</a> implementation that handles the common case of displaying a
tooltip when hovering over a certain element or elements on the page. It allows fine-grained
control over the tooltip's alignment relative to the target element or mouse, and the timing
of when it is automatically shown and hidden.</p>
<p>This implementation does <strong>not</strong> have a built-in method of automatically populating the tooltip's
text based on the target element; you must either configure a fixed <a href="#!/api/Ext.tip.ToolTip-cfg-html" rel="Ext.tip.ToolTip-cfg-html" class="docClass">html</a> value for each
ToolTip instance, or implement custom logic (e.g. in a <a href="#!/api/Ext.tip.ToolTip-event-beforeshow" rel="Ext.tip.ToolTip-event-beforeshow" class="docClass">beforeshow</a> event listener) to
generate the appropriate tooltip content on the fly. See <a href="#!/api/Ext.tip.QuickTip" rel="Ext.tip.QuickTip" class="docClass">Ext.tip.QuickTip</a> for a more
convenient way of automatically populating and configuring a tooltip based on specific DOM
attributes of each target element.</p>
<h1>Basic Example</h1>
<pre><code>var tip = <a href="#!/api/Ext-method-create" rel="Ext-method-create" class="docClass">Ext.create</a>('<a href="#!/api/Ext.tip.ToolTip" rel="Ext.tip.ToolTip" class="docClass">Ext.tip.ToolTip</a>', \{
target: 'clearButton',
html: 'Press this button to clear the form'
\});
</code></pre>
<p><p><img src="" alt="Basic Ext.tip.ToolTip" width="" height=""></p></p>
<h1>Delegation</h1>
<p>In addition to attaching a ToolTip to a single element, you can also use delegation to attach
one ToolTip to many elements under a common parent. This is more efficient than creating many
ToolTip instances. To do this, point the <a href="#!/api/Ext.tip.ToolTip-cfg-target" rel="Ext.tip.ToolTip-cfg-target" class="docClass">target</a> config to a common ancestor of all the
elements, and then set the <a href="#!/api/Ext.tip.ToolTip-cfg-delegate" rel="Ext.tip.ToolTip-cfg-delegate" class="docClass">delegate</a> config to a CSS selector that will select all the
appropriate sub-elements.</p>
<p>When using delegation, it is likely that you will want to programmatically change the content
of the ToolTip based on each delegate element; you can do this by implementing a custom
listener for the <a href="#!/api/Ext.tip.ToolTip-event-beforeshow" rel="Ext.tip.ToolTip-event-beforeshow" class="docClass">beforeshow</a> event. Example:</p>
<pre><code>var store = <a href="#!/api/Ext-method-create" rel="Ext-method-create" class="docClass">Ext.create</a>('<a href="#!/api/Ext.data.ArrayStore" rel="Ext.data.ArrayStore" class="docClass">Ext.data.ArrayStore</a>', \{
fields: ['company', 'price', 'change'],
data: [
['3m Co', 71.72, 0.02],
['Alcoa Inc', 29.01, 0.42],
['Altria Group Inc', 83.81, 0.28],
['American Express Company', 52.55, 0.01],
['American International Group, Inc.', 64.13, 0.31],
['AT&T Inc.', 31.61, -0.48]
]
\});
var grid = <a href="#!/api/Ext-method-create" rel="Ext-method-create" class="docClass">Ext.create</a>('<a href="#!/api/Ext.grid.Panel" rel="Ext.grid.Panel" class="docClass">Ext.grid.Panel</a>', \{
title: 'Array Grid',
store: store,
columns: [
\{text: 'Company', flex: 1, dataIndex: 'company'\},
\{text: 'Price', width: 75, dataIndex: 'price'\},
\{text: 'Change', width: 75, dataIndex: 'change'\}
],
height: 200,
width: 400,
renderTo: <a href="#!/api/Ext-method-getBody" rel="Ext-method-getBody" class="docClass">Ext.getBody</a>()
\});
var view = grid.getView();
var tip = <a href="#!/api/Ext-method-create" rel="Ext-method-create" class="docClass">Ext.create</a>('<a href="#!/api/Ext.tip.ToolTip" rel="Ext.tip.ToolTip" class="docClass">Ext.tip.ToolTip</a>', \{
// The overall target element.
target: view.el,
// Each grid row causes its own separate show and hide.
delegate: view.itemSelector,
// Moving within the row should not hide the tip.
trackMouse: true,
// Render immediately so that tip.body can be referenced prior to the first show.
renderTo: <a href="#!/api/Ext-method-getBody" rel="Ext-method-getBody" class="docClass">Ext.getBody</a>(),
listeners: \{
// Change content dynamically depending on which element triggered the show.
beforeshow: function updateTipBody(tip) \{
tip.update('Over company "' + view.getRecord(tip.triggerElement).get('company') + '"');
\}
\}
\});
</code></pre>
<p><p><img src="" alt="Ext.tip.ToolTip with delegation" width="" height=""></p></p>
<h1>Alignment</h1>
<p>The following configuration properties allow control over how the ToolTip is aligned relative to
the target element and/or mouse pointer:</p>
<ul>
<li><a href="#!/api/Ext.tip.ToolTip-cfg-anchor" rel="Ext.tip.ToolTip-cfg-anchor" class="docClass">anchor</a></li>
<li><a href="#!/api/Ext.tip.ToolTip-cfg-anchorToTarget" rel="Ext.tip.ToolTip-cfg-anchorToTarget" class="docClass">anchorToTarget</a></li>
<li><a href="#!/api/Ext.tip.ToolTip-cfg-anchorOffset" rel="Ext.tip.ToolTip-cfg-anchorOffset" class="docClass">anchorOffset</a></li>
<li><a href="#!/api/Ext.tip.ToolTip-cfg-trackMouse" rel="Ext.tip.ToolTip-cfg-trackMouse" class="docClass">trackMouse</a></li>
<li><a href="#!/api/Ext.tip.ToolTip-cfg-mouseOffset" rel="Ext.tip.ToolTip-cfg-mouseOffset" class="docClass">mouseOffset</a></li>
</ul>
<h1>Showing/Hiding</h1>
<p>The following configuration properties allow control over how and when the ToolTip is automatically
shown and hidden:</p>
<ul>
<li><a href="#!/api/Ext.tip.ToolTip-cfg-autoHide" rel="Ext.tip.ToolTip-cfg-autoHide" class="docClass">autoHide</a></li>
<li><a href="#!/api/Ext.tip.ToolTip-cfg-showDelay" rel="Ext.tip.ToolTip-cfg-showDelay" class="docClass">showDelay</a></li>
<li><a href="#!/api/Ext.tip.ToolTip-cfg-hideDelay" rel="Ext.tip.ToolTip-cfg-hideDelay" class="docClass">hideDelay</a></li>
<li><a href="#!/api/Ext.tip.ToolTip-cfg-dismissDelay" rel="Ext.tip.ToolTip-cfg-dismissDelay" class="docClass">dismissDelay</a></li>
</ul> %}
*)
class type t =
object('self)
inherit Ext_tip_Tip.t
method triggerElement : Dom_html.element Js.t Js.prop
* { % < p > When a ToolTip is configured with the < code><a href="#!/api / Ext.tip . ToolTip - cfg - delegate " rel="Ext.tip . ToolTip - cfg - delegate " class="docClass">delegate</a></code >
option to cause selected child elements of the < code><a href="#!/api / Ext.tip . ToolTip - cfg - target " rel="Ext.tip . ToolTip - cfg - target " class="docClass">target</a></code >
Element to each trigger a separate show event , this property is set to
the DOM element which triggered the show.</p > % }
option to cause selected child elements of the <code><a href="#!/api/Ext.tip.ToolTip-cfg-target" rel="Ext.tip.ToolTip-cfg-target" class="docClass">target</a></code>
Element to each trigger a separate show event, this property is set to
the DOM element which triggered the show.</p> %}
*)
method beforeDestroy : unit Js.meth
method hide_tooltip : unit Js.meth
method setTarget : _ Js.t -> unit Js.meth
* { % < p > Binds this ToolTip to the specified element . The tooltip will be displayed when the mouse moves over the element.</p > % }
{ b Parameters } :
{ ul { - t : [ _ Js.t ]
{ % < p > The Element , HtmlElement , or ID of an element to bind to</p > % }
}
}
{b Parameters}:
{ul {- t: [_ Js.t]
{% <p>The Element, HtmlElement, or ID of an element to bind to</p> %}
}
}
*)
method show_tooltip : unit Js.meth
* { % < p > Shows this tooltip at the current event target XY position.</p > % }
*)
method showAt_arr : Js.number Js.t Js.js_array Js.t -> unit Js.meth
* { % < p > Shows this tip at the specified XY position . Example usage:</p >
< pre><code>// Show the tip at and y:100
tip.showAt([50,100 ] ) ;
< /code></pre > % }
{ b Parameters } :
{ ul { - xy : [ Js.number Js.t Js.js_array Js.t ]
{ % < p > An array containing the x and > % }
}
}
<pre><code>// Show the tip at x:50 and y:100
tip.showAt([50,100]);
</code></pre> %}
{b Parameters}:
{ul {- xy: [Js.number Js.t Js.js_array Js.t]
{% <p>An array containing the x and y coordinates</p> %}
}
}
*)
end
class type configs =
object('self)
inherit Ext_tip_Tip.configs
method anchor : Js.js_string Js.t Js.prop
* { % < p > If specified , indicates that the tip should be anchored to a
particular side of the target element or mouse pointer ( " top " , " right " , " bottom " ,
or " left " ) , with an arrow pointing back at the target or mouse pointer . If
< a href="#!/api / Ext.tip . ToolTip - cfg - constrainPosition " rel="Ext.tip . ToolTip - cfg - constrainPosition " class="docClass">constrainPosition</a > is enabled , this will be used as a preferred value
only and may be flipped as needed.</p > % }
particular side of the target element or mouse pointer ("top", "right", "bottom",
or "left"), with an arrow pointing back at the target or mouse pointer. If
<a href="#!/api/Ext.tip.ToolTip-cfg-constrainPosition" rel="Ext.tip.ToolTip-cfg-constrainPosition" class="docClass">constrainPosition</a> is enabled, this will be used as a preferred value
only and may be flipped as needed.</p> %}
*)
method anchorOffset : Js.number Js.t Js.prop
* { % < p > A numeric pixel value used to offset the default position of the anchor arrow . When the anchor
position is on the top or bottom of the tooltip , < code > > will be used as a horizontal offset .
Likewise , when the anchor position is on the left or right side , < code > > will be used as
a vertical offset.</p > % }
Defaults to : [ 0 ]
position is on the top or bottom of the tooltip, <code>anchorOffset</code> will be used as a horizontal offset.
Likewise, when the anchor position is on the left or right side, <code>anchorOffset</code> will be used as
a vertical offset.</p> %}
Defaults to: [0]
*)
method anchorToTarget : bool Js.t Js.prop
* { % < p > True to anchor the tooltip to the target element , false to anchor it relative to the mouse coordinates .
When < code > anchorToTarget</code > is true , use < code><a href="#!/api / Ext.tip . ToolTip - cfg - defaultAlign " rel="Ext.tip . ToolTip - cfg - defaultAlign " class="docClass">defaultAlign</a></code > to control tooltip alignment to the
target element . When < code > anchorToTarget</code > is false , use < code><a href="#!/api / Ext.tip . ToolTip - cfg - anchor " rel="Ext.tip . ToolTip - cfg - anchor " class="docClass">anchor</a></code > instead to control alignment.</p > % }
Defaults to : [ true ]
When <code>anchorToTarget</code> is true, use <code><a href="#!/api/Ext.tip.ToolTip-cfg-defaultAlign" rel="Ext.tip.ToolTip-cfg-defaultAlign" class="docClass">defaultAlign</a></code> to control tooltip alignment to the
target element. When <code>anchorToTarget</code> is false, use <code><a href="#!/api/Ext.tip.ToolTip-cfg-anchor" rel="Ext.tip.ToolTip-cfg-anchor" class="docClass">anchor</a></code> instead to control alignment.</p> %}
Defaults to: [true]
*)
method autoHide : bool Js.t Js.prop
* { % < p > True to automatically hide the tooltip after the
mouse exits the target element or after the < code><a href="#!/api / Ext.tip . ToolTip - cfg - dismissDelay " rel="Ext.tip . ToolTip - cfg - dismissDelay " class="docClass">dismissDelay</a></code >
has expired if set . If < code><a href="#!/api / Ext.tip . ToolTip - cfg - closable " rel="Ext.tip . ToolTip - cfg - closable " class="docClass">closable</a > = true</code >
a close tool button will be rendered into the tooltip > % }
Defaults to : [ true ]
mouse exits the target element or after the <code><a href="#!/api/Ext.tip.ToolTip-cfg-dismissDelay" rel="Ext.tip.ToolTip-cfg-dismissDelay" class="docClass">dismissDelay</a></code>
has expired if set. If <code><a href="#!/api/Ext.tip.ToolTip-cfg-closable" rel="Ext.tip.ToolTip-cfg-closable" class="docClass">closable</a> = true</code>
a close tool button will be rendered into the tooltip header.</p> %}
Defaults to: [true]
*)
method delegate : Js.js_string Js.t Js.prop
* { % < p > A < a href="#!/api / Ext.dom . Query " rel="Ext.dom . Query " class="docClass">DomQuery</a > selector which allows selection of individual elements within the
< code><a href="#!/api / Ext.tip . ToolTip - cfg - target " rel="Ext.tip . ToolTip - cfg - target " class="docClass">target</a></code > element to trigger showing and hiding the ToolTip as the mouse moves within the
target.</p >
< p > When specified , the child element of the target which caused a show event is placed into the
< code><a href="#!/api / Ext.tip . ToolTip - property - triggerElement " rel="Ext.tip . ToolTip - property - triggerElement " class="docClass">triggerElement</a></code > property before the ToolTip is shown.</p >
< p > This may be useful when a Component has regular , repeating elements in it , each of which need a
ToolTip which contains information specific to that element.</p >
< p > See the delegate example in class documentation of < a href="#!/api / Ext.tip . ToolTip " rel="Ext.tip . ToolTip " class="docClass">Ext.tip . ToolTip</a>.</p > % }
<code><a href="#!/api/Ext.tip.ToolTip-cfg-target" rel="Ext.tip.ToolTip-cfg-target" class="docClass">target</a></code> element to trigger showing and hiding the ToolTip as the mouse moves within the
target.</p>
<p>When specified, the child element of the target which caused a show event is placed into the
<code><a href="#!/api/Ext.tip.ToolTip-property-triggerElement" rel="Ext.tip.ToolTip-property-triggerElement" class="docClass">triggerElement</a></code> property before the ToolTip is shown.</p>
<p>This may be useful when a Component has regular, repeating elements in it, each of which need a
ToolTip which contains information specific to that element.</p>
<p>See the delegate example in class documentation of <a href="#!/api/Ext.tip.ToolTip" rel="Ext.tip.ToolTip" class="docClass">Ext.tip.ToolTip</a>.</p> %}
*)
method dismissDelay : Js.number Js.t Js.prop
* { % < p > Delay in milliseconds before the tooltip automatically hides . To disable automatic hiding , set
dismissDelay = 0.</p > % }
Defaults to : [ 5000 ]
dismissDelay = 0.</p> %}
Defaults to: [5000]
*)
method hideDelay : Js.number Js.t Js.prop
* { % < p > Delay in milliseconds after the mouse exits the target element but before the tooltip actually hides .
Set to 0 for the tooltip to hide immediately.</p > % }
Defaults to : [ 200 ]
Set to 0 for the tooltip to hide immediately.</p> %}
Defaults to: [200]
*)
method mouseOffset : Js.number Js.t Js.js_array Js.t Js.prop
* { % < p > An XY offset from the mouse position where the tooltip should be shown.</p > % }
Defaults to : [ 15,18 ]
Defaults to: [15,18]
*)
method showDelay : Js.number Js.t Js.prop
* { % < p > Delay in milliseconds before the tooltip displays after the mouse enters the target element.</p > % }
Defaults to : [ 500 ]
Defaults to: [500]
*)
method target : _ Js.t Js.prop
* { % < p > The target element or string i d to monitor for mouseover events to trigger
showing this ToolTip.</p > % }
showing this ToolTip.</p> %}
*)
method trackMouse : bool Js.t Js.prop
* { % < p > True to have the tooltip follow the mouse as it moves over the target element.</p > % }
Defaults to : [ false ]
Defaults to: [false]
*)
method beforeDestroy : ('self Js.t, unit -> unit) Js.meth_callback
Js.writeonly_prop
end
class type events =
object
inherit Ext_tip_Tip.events
end
class type statics =
object
inherit Ext_tip_Tip.statics
end
val of_configs : configs Js.t -> t Js.t
val to_configs : t Js.t -> configs Js.t
|
a3b1745a54481091134ebd8460b3b3824c8da24bee1cd810236ea44a02f7d922 | input-output-hk/nix-tools | StackRepos.hs | # LANGUAGE LambdaCase #
# LANGUAGE NamedFieldPuns #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE DeriveGeneric #
module StackRepos
( doStackRepos
, stack2nix
) where
import Data.Aeson (ToJSON(..))
import Data.Aeson.Encode.Pretty (encodePretty)
import qualified Data.ByteString.Lazy as LBS (writeFile)
import Data.Yaml (decodeFileEither)
import GHC.Generics (Generic)
import Stack2nix.Stack (Stack(..), Dependency(..), Location(..))
import Stack2nix.External.Resolve
import StackRepos.CLI (Args(..))
data SourceRepos = SourceRepos
{ url :: String
, rev :: String
, sha256 :: Maybe String
, subdirs :: [FilePath]
} deriving (Show, Eq, Ord, Generic)
instance ToJSON SourceRepos
doStackRepos :: Args -> IO ()
doStackRepos args = do
evalue <- decodeFileEither (argStackYaml args)
case evalue of
Left e -> error (show e)
Right value -> stack2nix args
=<< resolveSnapshot (argStackYaml args) value
stack2nix :: Args -> Stack -> IO ()
stack2nix args (Stack _ _ pkgs _ _) =
LBS.writeFile "repos.json" $ encodePretty (
pkgs >>= (\case
(DVCS (Git url rev) sha256 subdirs) ->
[SourceRepos { url, rev, sha256, subdirs }]
_ -> []))
| null | https://raw.githubusercontent.com/input-output-hk/nix-tools/c9c10ab889a7b7f2f5f4bb71e8786fc01d49e53e/lib/StackRepos.hs | haskell | # LANGUAGE OverloadedStrings # | # LANGUAGE LambdaCase #
# LANGUAGE NamedFieldPuns #
# LANGUAGE DeriveGeneric #
module StackRepos
( doStackRepos
, stack2nix
) where
import Data.Aeson (ToJSON(..))
import Data.Aeson.Encode.Pretty (encodePretty)
import qualified Data.ByteString.Lazy as LBS (writeFile)
import Data.Yaml (decodeFileEither)
import GHC.Generics (Generic)
import Stack2nix.Stack (Stack(..), Dependency(..), Location(..))
import Stack2nix.External.Resolve
import StackRepos.CLI (Args(..))
data SourceRepos = SourceRepos
{ url :: String
, rev :: String
, sha256 :: Maybe String
, subdirs :: [FilePath]
} deriving (Show, Eq, Ord, Generic)
instance ToJSON SourceRepos
doStackRepos :: Args -> IO ()
doStackRepos args = do
evalue <- decodeFileEither (argStackYaml args)
case evalue of
Left e -> error (show e)
Right value -> stack2nix args
=<< resolveSnapshot (argStackYaml args) value
stack2nix :: Args -> Stack -> IO ()
stack2nix args (Stack _ _ pkgs _ _) =
LBS.writeFile "repos.json" $ encodePretty (
pkgs >>= (\case
(DVCS (Git url rev) sha256 subdirs) ->
[SourceRepos { url, rev, sha256, subdirs }]
_ -> []))
|
e63ca106679946c7e9f71fb73bb9a7a855e4da01d7cc1fe2cdffb0cd349537cb | themattchan/core | Utils.hs | module Core.Utils where
import Data.Function
import Data.Maybe
import Data.Monoid hiding ((<>))
import Data.Semigroup
import Text.PrettyPrint hiding ((<>))
import Control.Lens ((&), (.~), (<>~))
import Control.Lens.TH
import Generics.Deriving.Monoid (memptydefault, mappenddefault)
import GHC.Generics (Generic)
--------------------------------------------------------------------------------
-- * Misc utilities
vcat' :: [Doc] -> Doc
vcat' = foldr ($$) empty
besides :: [Doc] -> [Doc] -> Doc
besides xs ys = uncurry ((<+>) `on` vcat')
. unzip
$ (zip `on` (++ pad)) xs ys
where
d = abs (length xs - length ys)
pad = replicate d (text "")
--------------------------------------------------------------------------------
-- * Appendix A: Heap data type and associated functions
type Addr = Int
data Heap a = Heap
{ heapSize :: Int
, heapFree :: [Addr]
, heapCts :: [(Addr,a)]
, heapStats :: HeapStats
} deriving Show
data HeapStats = HeapStats
{ heapStatsAllocs :: Sum Int
, heapStatsUpdates :: Sum Int
, heapStatsFrees :: Sum Int
} deriving (Show, Generic)
instance Semigroup HeapStats where
(<>) = mappenddefault
instance Monoid HeapStats where
mempty = memptydefault
mappend = (<>)
makeLensesWith camelCaseFields ''Heap
makeLensesWith camelCaseFields ''HeapStats
hInitial :: Heap a
hInitial = Heap 0 [1..] [] mempty
hAlloc :: Heap a -> a -> (Heap a, Addr)
hAlloc (Heap s (next:free) cts hstats) n =
(Heap (s+1) free ((next,n):cts) (hstats & allocs <>~ Sum 1), next)
hAlloc _ _ = error "hAlloc: heap full"
hUpdate :: Heap a -> Addr -> a -> Heap a
hUpdate h a n = h { heapCts = (a,n) : remove (heapCts h) a
, heapStats = heapStats h & updates <>~ Sum 1
}
hFree :: Heap a -> Addr -> Heap a
hFree h a = h { heapSize = heapSize h -1
, heapFree = a : heapFree h
, heapCts = remove (heapCts h) a
, heapStats = heapStats h & frees <>~ Sum 1
}
hLookup :: Heap a -> Addr -> a
hLookup h a = lookupErr err a (heapCts h)
where err = "can't find node " <> showAddr a <> " in heap"
lookupErr :: Eq a => String -> a -> [(a, b)] -> b
lookupErr err a xs = fromMaybe (error err) (lookup a xs)
hAddresses :: Heap a -> [Addr]
hAddresses = map fst . heapCts
hNull :: Addr
hNull = 0
hIsNull :: Addr -> Bool
hIsNull = (0 ==)
showAddr :: Addr -> String
showAddr = ("#" <>) . show
remove :: [(Addr,a)] -> Addr -> [(Addr,a)]
remove [] a = error ("Attempt to update or free nonexistent address " <> showAddr a)
remove ((a',n):cts) a | a == a' = cts
| a /= a' = (a',n) : remove cts a
| null | https://raw.githubusercontent.com/themattchan/core/ba7e8f62cffc463ddf0143f25a5b692f77d474e1/src/Core/Utils.hs | haskell | ------------------------------------------------------------------------------
* Misc utilities
------------------------------------------------------------------------------
* Appendix A: Heap data type and associated functions | module Core.Utils where
import Data.Function
import Data.Maybe
import Data.Monoid hiding ((<>))
import Data.Semigroup
import Text.PrettyPrint hiding ((<>))
import Control.Lens ((&), (.~), (<>~))
import Control.Lens.TH
import Generics.Deriving.Monoid (memptydefault, mappenddefault)
import GHC.Generics (Generic)
vcat' :: [Doc] -> Doc
vcat' = foldr ($$) empty
besides :: [Doc] -> [Doc] -> Doc
besides xs ys = uncurry ((<+>) `on` vcat')
. unzip
$ (zip `on` (++ pad)) xs ys
where
d = abs (length xs - length ys)
pad = replicate d (text "")
type Addr = Int
data Heap a = Heap
{ heapSize :: Int
, heapFree :: [Addr]
, heapCts :: [(Addr,a)]
, heapStats :: HeapStats
} deriving Show
data HeapStats = HeapStats
{ heapStatsAllocs :: Sum Int
, heapStatsUpdates :: Sum Int
, heapStatsFrees :: Sum Int
} deriving (Show, Generic)
instance Semigroup HeapStats where
(<>) = mappenddefault
instance Monoid HeapStats where
mempty = memptydefault
mappend = (<>)
makeLensesWith camelCaseFields ''Heap
makeLensesWith camelCaseFields ''HeapStats
hInitial :: Heap a
hInitial = Heap 0 [1..] [] mempty
hAlloc :: Heap a -> a -> (Heap a, Addr)
hAlloc (Heap s (next:free) cts hstats) n =
(Heap (s+1) free ((next,n):cts) (hstats & allocs <>~ Sum 1), next)
hAlloc _ _ = error "hAlloc: heap full"
hUpdate :: Heap a -> Addr -> a -> Heap a
hUpdate h a n = h { heapCts = (a,n) : remove (heapCts h) a
, heapStats = heapStats h & updates <>~ Sum 1
}
hFree :: Heap a -> Addr -> Heap a
hFree h a = h { heapSize = heapSize h -1
, heapFree = a : heapFree h
, heapCts = remove (heapCts h) a
, heapStats = heapStats h & frees <>~ Sum 1
}
hLookup :: Heap a -> Addr -> a
hLookup h a = lookupErr err a (heapCts h)
where err = "can't find node " <> showAddr a <> " in heap"
lookupErr :: Eq a => String -> a -> [(a, b)] -> b
lookupErr err a xs = fromMaybe (error err) (lookup a xs)
hAddresses :: Heap a -> [Addr]
hAddresses = map fst . heapCts
hNull :: Addr
hNull = 0
hIsNull :: Addr -> Bool
hIsNull = (0 ==)
showAddr :: Addr -> String
showAddr = ("#" <>) . show
remove :: [(Addr,a)] -> Addr -> [(Addr,a)]
remove [] a = error ("Attempt to update or free nonexistent address " <> showAddr a)
remove ((a',n):cts) a | a == a' = cts
| a /= a' = (a',n) : remove cts a
|
0d236de9f60d291aac2cd730bd2885b9a63eda24a608f5dbce51cf81cb3bd645 | tisnik/clojure-examples | core_test.clj | ;
( C ) Copyright 2016 , 2020 , 2021
;
; All rights reserved. This program and the accompanying materials
; are made available under the terms of the Eclipse Public License v1.0
; which accompanies this distribution, and is available at
-v10.html
;
; Contributors:
;
(ns consume-messages-2.core-test
(:require [clojure.test :refer :all]
[consume-messages-2.core :refer :all]))
(deftest a-test
(testing "FIXME, I fail."
(is (= 0 1))))
| null | https://raw.githubusercontent.com/tisnik/clojure-examples/a5f9d6119b62520b05da64b7929d07b832b957ab/kafka-consume-messages-2/test/consume_messages_2/core_test.clj | clojure |
All rights reserved. This program and the accompanying materials
are made available under the terms of the Eclipse Public License v1.0
which accompanies this distribution, and is available at
Contributors:
| ( C ) Copyright 2016 , 2020 , 2021
-v10.html
(ns consume-messages-2.core-test
(:require [clojure.test :refer :all]
[consume-messages-2.core :refer :all]))
(deftest a-test
(testing "FIXME, I fail."
(is (= 0 1))))
|
39c04ff3276a8c5c6f705a0e953c80d62a5b1f050ec99b811a520b56a7921961 | well-typed-lightbulbs/ocaml-esp32 | persistent_env.ml | (**************************************************************************)
(* *)
(* OCaml *)
(* *)
, projet Gallium , INRIA Rocquencourt
, projet , INRIA Saclay
(* *)
Copyright 2019 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. *)
(* *)
(**************************************************************************)
(* Persistent structure descriptions *)
open Misc
open Cmi_format
module Consistbl = Consistbl.Make (Misc.Stdlib.String)
let add_delayed_check_forward = ref (fun _ -> assert false)
type error =
| Illegal_renaming of modname * modname * filepath
| Inconsistent_import of modname * filepath * filepath
| Need_recursive_types of modname
| Depend_on_unsafe_string_unit of modname
exception Error of error
let error err = raise (Error err)
module Persistent_signature = struct
type t =
{ filename : string;
cmi : Cmi_format.cmi_infos }
let load = ref (fun ~unit_name ->
match Load_path.find_uncap (unit_name ^ ".cmi") with
| filename -> Some { filename; cmi = read_cmi filename }
| exception Not_found -> None)
end
type can_load_cmis =
| Can_load_cmis
| Cannot_load_cmis of EnvLazy.log
type pers_struct = {
ps_name: string;
ps_crcs: (string * Digest.t option) list;
ps_filename: string;
ps_flags: pers_flags list;
}
module String = Misc.Stdlib.String
If a file is missing ( or invalid ) , we
store it as Missing in the cache .
store it as Missing in the cache. *)
type 'a pers_struct_info =
| Missing
| Found of pers_struct * 'a
type 'a t = {
persistent_structures : (string, 'a pers_struct_info) Hashtbl.t;
imported_units: String.Set.t ref;
imported_opaque_units: String.Set.t ref;
crc_units: Consistbl.t;
can_load_cmis: can_load_cmis ref;
}
let empty () = {
persistent_structures = Hashtbl.create 17;
imported_units = ref String.Set.empty;
imported_opaque_units = ref String.Set.empty;
crc_units = Consistbl.create ();
can_load_cmis = ref Can_load_cmis;
}
let clear penv =
let {
persistent_structures;
imported_units;
imported_opaque_units;
crc_units;
can_load_cmis;
} = penv in
Hashtbl.clear persistent_structures;
imported_units := String.Set.empty;
imported_opaque_units := String.Set.empty;
Consistbl.clear crc_units;
can_load_cmis := Can_load_cmis;
()
let clear_missing {persistent_structures; _} =
let missing_entries =
Hashtbl.fold
(fun name r acc -> if r = Missing then name :: acc else acc)
persistent_structures []
in
List.iter (Hashtbl.remove persistent_structures) missing_entries
let add_import {imported_units; _} s =
imported_units := String.Set.add s !imported_units
let add_imported_opaque {imported_opaque_units; _} s =
imported_opaque_units := String.Set.add s !imported_opaque_units
let find_in_cache {persistent_structures; _} s =
match Hashtbl.find persistent_structures s with
| exception Not_found -> None
| Missing -> None
| Found (_ps, pm) -> Some pm
let import_crcs penv ~source crcs =
let {crc_units; _} = penv in
let import_crc (name, crco) =
match crco with
| None -> ()
| Some crc ->
add_import penv name;
Consistbl.check crc_units name crc source
in List.iter import_crc crcs
let check_consistency penv ps =
try import_crcs penv ~source:ps.ps_filename ps.ps_crcs
with Consistbl.Inconsistency(name, source, auth) ->
error (Inconsistent_import(name, auth, source))
let can_load_cmis penv =
!(penv.can_load_cmis)
let set_can_load_cmis penv setting =
penv.can_load_cmis := setting
let without_cmis penv f x =
let log = EnvLazy.log () in
let res =
Misc.(protect_refs
[R (penv.can_load_cmis, Cannot_load_cmis log)]
(fun () -> f x))
in
EnvLazy.backtrack log;
res
let fold {persistent_structures; _} f x =
Hashtbl.fold (fun modname pso x -> match pso with
| Missing -> x
| Found (_, pm) -> f modname pm x)
persistent_structures x
Reading persistent structures from .cmi files
let save_pers_struct penv crc ps pm =
let {persistent_structures; crc_units; _} = penv in
let modname = ps.ps_name in
Hashtbl.add persistent_structures modname (Found (ps, pm));
List.iter
(function
| Rectypes -> ()
| Alerts _ -> ()
| Unsafe_string -> ()
| Opaque -> add_imported_opaque penv modname)
ps.ps_flags;
Consistbl.set crc_units modname crc ps.ps_filename;
add_import penv modname
let acknowledge_pers_struct penv check modname pers_sig pm =
let { Persistent_signature.filename; cmi } = pers_sig in
let name = cmi.cmi_name in
let crcs = cmi.cmi_crcs in
let flags = cmi.cmi_flags in
let ps = { ps_name = name;
ps_crcs = crcs;
ps_filename = filename;
ps_flags = flags;
} in
if ps.ps_name <> modname then
error (Illegal_renaming(modname, ps.ps_name, filename));
List.iter
(function
| Rectypes ->
if not !Clflags.recursive_types then
error (Need_recursive_types(ps.ps_name))
| Unsafe_string ->
if Config.safe_string then
error (Depend_on_unsafe_string_unit(ps.ps_name));
| Alerts _ -> ()
| Opaque -> add_imported_opaque penv modname)
ps.ps_flags;
if check then check_consistency penv ps;
let {persistent_structures; _} = penv in
Hashtbl.add persistent_structures modname (Found (ps, pm));
ps
let read_pers_struct penv val_of_pers_sig check modname filename =
add_import penv modname;
let cmi = read_cmi filename in
let pers_sig = { Persistent_signature.filename; cmi } in
let pm = val_of_pers_sig pers_sig in
let ps = acknowledge_pers_struct penv check modname pers_sig pm in
(ps, pm)
let find_pers_struct penv val_of_pers_sig check name =
let {persistent_structures; _} = penv in
if name = "*predef*" then raise Not_found;
match Hashtbl.find persistent_structures name with
| Found (ps, pm) -> (ps, pm)
| Missing -> raise Not_found
| exception Not_found ->
match can_load_cmis penv with
| Cannot_load_cmis _ -> raise Not_found
| Can_load_cmis ->
let psig =
match !Persistent_signature.load ~unit_name:name with
| Some psig -> psig
| None ->
Hashtbl.add persistent_structures name Missing;
raise Not_found
in
add_import penv name;
let pm = val_of_pers_sig psig in
let ps = acknowledge_pers_struct penv check name psig pm in
(ps, pm)
(* Emits a warning if there is no valid cmi for name *)
let check_pers_struct penv f ~loc name =
try
ignore (find_pers_struct penv f false name)
with
| Not_found ->
let warn = Warnings.No_cmi_file(name, None) in
Location.prerr_warning loc warn
| Cmi_format.Error err ->
let msg = Format.asprintf "%a" Cmi_format.report_error err in
let warn = Warnings.No_cmi_file(name, Some msg) in
Location.prerr_warning loc warn
| Error err ->
let msg =
match err with
| Illegal_renaming(name, ps_name, filename) ->
Format.asprintf
" %a@ contains the compiled interface for @ \
%s when %s was expected"
Location.print_filename filename ps_name name
| Inconsistent_import _ -> assert false
| Need_recursive_types name ->
Format.sprintf
"%s uses recursive types"
name
| Depend_on_unsafe_string_unit name ->
Printf.sprintf "%s uses -unsafe-string"
name
in
let warn = Warnings.No_cmi_file(name, Some msg) in
Location.prerr_warning loc warn
let read penv f modname filename =
snd (read_pers_struct penv f true modname filename)
let find penv f name =
snd (find_pers_struct penv f true name)
let check penv f ~loc name =
let {persistent_structures; _} = penv in
if not (Hashtbl.mem persistent_structures name) then begin
(* PR#6843: record the weak dependency ([add_import]) regardless of
whether the check succeeds, to help make builds more
deterministic. *)
add_import penv name;
if (Warnings.is_active (Warnings.No_cmi_file("", None))) then
!add_delayed_check_forward
(fun () -> check_pers_struct penv f ~loc name)
end
let crc_of_unit penv f name =
let (ps, _pm) = find_pers_struct penv f true name in
let crco =
try
List.assoc name ps.ps_crcs
with Not_found ->
assert false
in
match crco with
None -> assert false
| Some crc -> crc
let imports {imported_units; crc_units; _} =
Consistbl.extract (String.Set.elements !imported_units) crc_units
let looked_up {persistent_structures; _} modname =
Hashtbl.mem persistent_structures modname
let is_imported {imported_units; _} s =
String.Set.mem s !imported_units
let is_imported_opaque {imported_opaque_units; _} s =
String.Set.mem s !imported_opaque_units
let make_cmi penv modname sign alerts =
let flags =
List.concat [
if !Clflags.recursive_types then [Cmi_format.Rectypes] else [];
if !Clflags.opaque then [Cmi_format.Opaque] else [];
(if !Clflags.unsafe_string then [Cmi_format.Unsafe_string] else []);
[Alerts alerts];
]
in
let crcs = imports penv in
{
cmi_name = modname;
cmi_sign = sign;
cmi_crcs = crcs;
cmi_flags = flags
}
let save_cmi penv psig pm =
let { Persistent_signature.filename; cmi } = psig in
Misc.try_finally (fun () ->
let {
cmi_name = modname;
cmi_sign = _;
cmi_crcs = imports;
cmi_flags = flags;
} = cmi in
let crc =
see MPR#7472 , MPR#4991
~mode: [Open_binary] filename
(fun temp_filename oc -> output_cmi temp_filename oc cmi) in
(* Enter signature in persistent table so that imports()
will also return its crc *)
let ps =
{ ps_name = modname;
ps_crcs = (cmi.cmi_name, Some crc) :: imports;
ps_filename = filename;
ps_flags = flags;
} in
save_pers_struct penv crc ps pm
)
~exceptionally:(fun () -> remove_file filename)
let report_error ppf =
let open Format in
function
| Illegal_renaming(modname, ps_name, filename) -> fprintf ppf
"Wrong file naming: %a@ contains the compiled interface for@ \
%s when %s was expected"
Location.print_filename filename ps_name modname
| Inconsistent_import(name, source1, source2) -> fprintf ppf
"@[<hov>The files %a@ and %a@ \
make inconsistent assumptions@ over interface %s@]"
Location.print_filename source1 Location.print_filename source2 name
| Need_recursive_types(import) ->
fprintf ppf
"@[<hov>Invalid import of %s, which uses recursive types.@ %s@]"
import "The compilation flag -rectypes is required"
| Depend_on_unsafe_string_unit(import) ->
fprintf ppf
"@[<hov>Invalid import of %s, compiled with -unsafe-string.@ %s@]"
import "This compiler has been configured in strict \
safe-string mode (-force-safe-string)"
let () =
Location.register_error_of_exn
(function
| Error err ->
Some (Location.error_of_printer_file report_error err)
| _ -> None
)
| null | https://raw.githubusercontent.com/well-typed-lightbulbs/ocaml-esp32/c24fcbfbee0e3aa6bb71c9b467c60c6bac326cc7/typing/persistent_env.ml | ocaml | ************************************************************************
OCaml
en Automatique.
All rights reserved. This file is distributed under the terms of
special exception on linking described in the file LICENSE.
************************************************************************
Persistent structure descriptions
Emits a warning if there is no valid cmi for name
PR#6843: record the weak dependency ([add_import]) regardless of
whether the check succeeds, to help make builds more
deterministic.
Enter signature in persistent table so that imports()
will also return its crc | , projet Gallium , INRIA Rocquencourt
, projet , INRIA Saclay
Copyright 2019 Institut National de Recherche en Informatique et
the GNU Lesser General Public License version 2.1 , with the
open Misc
open Cmi_format
module Consistbl = Consistbl.Make (Misc.Stdlib.String)
let add_delayed_check_forward = ref (fun _ -> assert false)
type error =
| Illegal_renaming of modname * modname * filepath
| Inconsistent_import of modname * filepath * filepath
| Need_recursive_types of modname
| Depend_on_unsafe_string_unit of modname
exception Error of error
let error err = raise (Error err)
module Persistent_signature = struct
type t =
{ filename : string;
cmi : Cmi_format.cmi_infos }
let load = ref (fun ~unit_name ->
match Load_path.find_uncap (unit_name ^ ".cmi") with
| filename -> Some { filename; cmi = read_cmi filename }
| exception Not_found -> None)
end
type can_load_cmis =
| Can_load_cmis
| Cannot_load_cmis of EnvLazy.log
type pers_struct = {
ps_name: string;
ps_crcs: (string * Digest.t option) list;
ps_filename: string;
ps_flags: pers_flags list;
}
module String = Misc.Stdlib.String
If a file is missing ( or invalid ) , we
store it as Missing in the cache .
store it as Missing in the cache. *)
type 'a pers_struct_info =
| Missing
| Found of pers_struct * 'a
type 'a t = {
persistent_structures : (string, 'a pers_struct_info) Hashtbl.t;
imported_units: String.Set.t ref;
imported_opaque_units: String.Set.t ref;
crc_units: Consistbl.t;
can_load_cmis: can_load_cmis ref;
}
let empty () = {
persistent_structures = Hashtbl.create 17;
imported_units = ref String.Set.empty;
imported_opaque_units = ref String.Set.empty;
crc_units = Consistbl.create ();
can_load_cmis = ref Can_load_cmis;
}
let clear penv =
let {
persistent_structures;
imported_units;
imported_opaque_units;
crc_units;
can_load_cmis;
} = penv in
Hashtbl.clear persistent_structures;
imported_units := String.Set.empty;
imported_opaque_units := String.Set.empty;
Consistbl.clear crc_units;
can_load_cmis := Can_load_cmis;
()
let clear_missing {persistent_structures; _} =
let missing_entries =
Hashtbl.fold
(fun name r acc -> if r = Missing then name :: acc else acc)
persistent_structures []
in
List.iter (Hashtbl.remove persistent_structures) missing_entries
let add_import {imported_units; _} s =
imported_units := String.Set.add s !imported_units
let add_imported_opaque {imported_opaque_units; _} s =
imported_opaque_units := String.Set.add s !imported_opaque_units
let find_in_cache {persistent_structures; _} s =
match Hashtbl.find persistent_structures s with
| exception Not_found -> None
| Missing -> None
| Found (_ps, pm) -> Some pm
let import_crcs penv ~source crcs =
let {crc_units; _} = penv in
let import_crc (name, crco) =
match crco with
| None -> ()
| Some crc ->
add_import penv name;
Consistbl.check crc_units name crc source
in List.iter import_crc crcs
let check_consistency penv ps =
try import_crcs penv ~source:ps.ps_filename ps.ps_crcs
with Consistbl.Inconsistency(name, source, auth) ->
error (Inconsistent_import(name, auth, source))
let can_load_cmis penv =
!(penv.can_load_cmis)
let set_can_load_cmis penv setting =
penv.can_load_cmis := setting
let without_cmis penv f x =
let log = EnvLazy.log () in
let res =
Misc.(protect_refs
[R (penv.can_load_cmis, Cannot_load_cmis log)]
(fun () -> f x))
in
EnvLazy.backtrack log;
res
let fold {persistent_structures; _} f x =
Hashtbl.fold (fun modname pso x -> match pso with
| Missing -> x
| Found (_, pm) -> f modname pm x)
persistent_structures x
Reading persistent structures from .cmi files
let save_pers_struct penv crc ps pm =
let {persistent_structures; crc_units; _} = penv in
let modname = ps.ps_name in
Hashtbl.add persistent_structures modname (Found (ps, pm));
List.iter
(function
| Rectypes -> ()
| Alerts _ -> ()
| Unsafe_string -> ()
| Opaque -> add_imported_opaque penv modname)
ps.ps_flags;
Consistbl.set crc_units modname crc ps.ps_filename;
add_import penv modname
let acknowledge_pers_struct penv check modname pers_sig pm =
let { Persistent_signature.filename; cmi } = pers_sig in
let name = cmi.cmi_name in
let crcs = cmi.cmi_crcs in
let flags = cmi.cmi_flags in
let ps = { ps_name = name;
ps_crcs = crcs;
ps_filename = filename;
ps_flags = flags;
} in
if ps.ps_name <> modname then
error (Illegal_renaming(modname, ps.ps_name, filename));
List.iter
(function
| Rectypes ->
if not !Clflags.recursive_types then
error (Need_recursive_types(ps.ps_name))
| Unsafe_string ->
if Config.safe_string then
error (Depend_on_unsafe_string_unit(ps.ps_name));
| Alerts _ -> ()
| Opaque -> add_imported_opaque penv modname)
ps.ps_flags;
if check then check_consistency penv ps;
let {persistent_structures; _} = penv in
Hashtbl.add persistent_structures modname (Found (ps, pm));
ps
let read_pers_struct penv val_of_pers_sig check modname filename =
add_import penv modname;
let cmi = read_cmi filename in
let pers_sig = { Persistent_signature.filename; cmi } in
let pm = val_of_pers_sig pers_sig in
let ps = acknowledge_pers_struct penv check modname pers_sig pm in
(ps, pm)
let find_pers_struct penv val_of_pers_sig check name =
let {persistent_structures; _} = penv in
if name = "*predef*" then raise Not_found;
match Hashtbl.find persistent_structures name with
| Found (ps, pm) -> (ps, pm)
| Missing -> raise Not_found
| exception Not_found ->
match can_load_cmis penv with
| Cannot_load_cmis _ -> raise Not_found
| Can_load_cmis ->
let psig =
match !Persistent_signature.load ~unit_name:name with
| Some psig -> psig
| None ->
Hashtbl.add persistent_structures name Missing;
raise Not_found
in
add_import penv name;
let pm = val_of_pers_sig psig in
let ps = acknowledge_pers_struct penv check name psig pm in
(ps, pm)
let check_pers_struct penv f ~loc name =
try
ignore (find_pers_struct penv f false name)
with
| Not_found ->
let warn = Warnings.No_cmi_file(name, None) in
Location.prerr_warning loc warn
| Cmi_format.Error err ->
let msg = Format.asprintf "%a" Cmi_format.report_error err in
let warn = Warnings.No_cmi_file(name, Some msg) in
Location.prerr_warning loc warn
| Error err ->
let msg =
match err with
| Illegal_renaming(name, ps_name, filename) ->
Format.asprintf
" %a@ contains the compiled interface for @ \
%s when %s was expected"
Location.print_filename filename ps_name name
| Inconsistent_import _ -> assert false
| Need_recursive_types name ->
Format.sprintf
"%s uses recursive types"
name
| Depend_on_unsafe_string_unit name ->
Printf.sprintf "%s uses -unsafe-string"
name
in
let warn = Warnings.No_cmi_file(name, Some msg) in
Location.prerr_warning loc warn
let read penv f modname filename =
snd (read_pers_struct penv f true modname filename)
let find penv f name =
snd (find_pers_struct penv f true name)
let check penv f ~loc name =
let {persistent_structures; _} = penv in
if not (Hashtbl.mem persistent_structures name) then begin
add_import penv name;
if (Warnings.is_active (Warnings.No_cmi_file("", None))) then
!add_delayed_check_forward
(fun () -> check_pers_struct penv f ~loc name)
end
let crc_of_unit penv f name =
let (ps, _pm) = find_pers_struct penv f true name in
let crco =
try
List.assoc name ps.ps_crcs
with Not_found ->
assert false
in
match crco with
None -> assert false
| Some crc -> crc
let imports {imported_units; crc_units; _} =
Consistbl.extract (String.Set.elements !imported_units) crc_units
let looked_up {persistent_structures; _} modname =
Hashtbl.mem persistent_structures modname
let is_imported {imported_units; _} s =
String.Set.mem s !imported_units
let is_imported_opaque {imported_opaque_units; _} s =
String.Set.mem s !imported_opaque_units
let make_cmi penv modname sign alerts =
let flags =
List.concat [
if !Clflags.recursive_types then [Cmi_format.Rectypes] else [];
if !Clflags.opaque then [Cmi_format.Opaque] else [];
(if !Clflags.unsafe_string then [Cmi_format.Unsafe_string] else []);
[Alerts alerts];
]
in
let crcs = imports penv in
{
cmi_name = modname;
cmi_sign = sign;
cmi_crcs = crcs;
cmi_flags = flags
}
let save_cmi penv psig pm =
let { Persistent_signature.filename; cmi } = psig in
Misc.try_finally (fun () ->
let {
cmi_name = modname;
cmi_sign = _;
cmi_crcs = imports;
cmi_flags = flags;
} = cmi in
let crc =
see MPR#7472 , MPR#4991
~mode: [Open_binary] filename
(fun temp_filename oc -> output_cmi temp_filename oc cmi) in
let ps =
{ ps_name = modname;
ps_crcs = (cmi.cmi_name, Some crc) :: imports;
ps_filename = filename;
ps_flags = flags;
} in
save_pers_struct penv crc ps pm
)
~exceptionally:(fun () -> remove_file filename)
let report_error ppf =
let open Format in
function
| Illegal_renaming(modname, ps_name, filename) -> fprintf ppf
"Wrong file naming: %a@ contains the compiled interface for@ \
%s when %s was expected"
Location.print_filename filename ps_name modname
| Inconsistent_import(name, source1, source2) -> fprintf ppf
"@[<hov>The files %a@ and %a@ \
make inconsistent assumptions@ over interface %s@]"
Location.print_filename source1 Location.print_filename source2 name
| Need_recursive_types(import) ->
fprintf ppf
"@[<hov>Invalid import of %s, which uses recursive types.@ %s@]"
import "The compilation flag -rectypes is required"
| Depend_on_unsafe_string_unit(import) ->
fprintf ppf
"@[<hov>Invalid import of %s, compiled with -unsafe-string.@ %s@]"
import "This compiler has been configured in strict \
safe-string mode (-force-safe-string)"
let () =
Location.register_error_of_exn
(function
| Error err ->
Some (Location.error_of_printer_file report_error err)
| _ -> None
)
|
001e3e0e0d6d7874737afafba510325511294a8615ca0733e8d400527aa88fce | fizruk/http-api-data | HttpApiData.hs | {-# LANGUAGE CPP #-}
{-# LANGUAGE DefaultSignatures #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveFoldable #-}
# LANGUAGE DeriveFunctor #
{-# LANGUAGE DeriveTraversable #-}
# LANGUAGE FlexibleInstances #
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeSynonymInstances #-}
-- |
values to and from HTTP API data
-- such as URL pieces, headers and query parameters.
module Web.Internal.HttpApiData where
import Prelude ()
import Prelude.Compat
import Control.Applicative (Const(Const))
import Control.Arrow (left, (&&&))
import Control.Monad ((<=<))
import qualified Data.Attoparsec.Text as Atto
import qualified Data.Attoparsec.Time as Atto
import Data.ByteString (ByteString)
import qualified Data.ByteString as BS
import qualified Data.ByteString.Builder as BS
import qualified Data.ByteString.Lazy as LBS
import Data.Coerce (coerce)
import Data.Data (Data)
import qualified Data.Fixed as F
import Data.Functor.Identity (Identity(Identity))
import Data.Int (Int16, Int32, Int64, Int8)
import Data.Kind (Type)
import qualified Data.Map as Map
import Data.Monoid (All (..), Any (..), Dual (..),
First (..), Last (..),
Product (..), Sum (..))
import Data.Semigroup (Semigroup (..))
import qualified Data.Semigroup as Semi
import Data.Tagged (Tagged (..))
import Data.Text (Text)
import qualified Data.Text as T
import Data.Text.Encoding (decodeUtf8', decodeUtf8With,
encodeUtf8)
import Data.Text.Encoding.Error (lenientDecode)
import qualified Data.Text.Lazy as L
import Data.Text.Read (Reader, decimal, rational,
signed)
import Data.Time.Compat (Day, FormatTime, LocalTime,
NominalDiffTime, TimeOfDay,
UTCTime, ZonedTime, formatTime,
DayOfWeek (..),
nominalDiffTimeToSeconds,
secondsToNominalDiffTime)
import Data.Time.Format.Compat (defaultTimeLocale,
iso8601DateFormat)
import Data.Time.Calendar.Month.Compat (Month)
import Data.Time.Calendar.Quarter.Compat (Quarter, QuarterOfYear (..),
toYearQuarter)
import Data.Typeable (Typeable)
import qualified Data.UUID.Types as UUID
import Data.Version (Version, parseVersion,
showVersion)
import Data.Void (Void, absurd)
import Data.Word (Word16, Word32, Word64, Word8)
import qualified Network.HTTP.Types as H
import Numeric.Natural (Natural)
import Text.ParserCombinators.ReadP (readP_to_S)
import Text.Read (readMaybe)
import Web.Cookie (SetCookie, parseSetCookie,
renderSetCookie)
#if USE_TEXT_SHOW
import TextShow (TextShow, showt)
#endif
-- $setup
> > > data = Text deriving ( Show )
> > > instance FromHttpApiData BasicAuthToken where parseHeader h = < $ > parseHeaderWithPrefix " Basic " h ; parseQueryParam p = < $ > parseQueryParam p
-- >>> import Data.Time.Compat
-- >>> import Data.Version
-- | Convert value to HTTP API data.
--
_ _ WARNING _ _ : Do not derive this using as the generated
-- instance will loop indefinitely.
class ToHttpApiData a where
{-# MINIMAL toUrlPiece | toQueryParam #-}
-- | Convert to URL path piece.
toUrlPiece :: a -> Text
toUrlPiece = toQueryParam
-- | Convert to a URL path piece, making sure to encode any special chars.
The default definition uses @'H.urlEncodeBuilder ' ' False'@
-- but this may be overriden with a more efficient version.
toEncodedUrlPiece :: a -> BS.Builder
toEncodedUrlPiece = H.urlEncodeBuilder False . encodeUtf8 . toUrlPiece
-- | Convert to HTTP header value.
toHeader :: a -> ByteString
toHeader = encodeUtf8 . toUrlPiece
-- | Convert to query param value.
toQueryParam :: a -> Text
toQueryParam = toUrlPiece
-- | Convert to URL query param,
-- The default definition uses @'H.urlEncodeBuilder' 'True'@
-- but this may be overriden with a more efficient version.
--
@since 0.5.1
toEncodedQueryParam :: a -> BS.Builder
toEncodedQueryParam = H.urlEncodeBuilder True . encodeUtf8 . toQueryParam
-- | Parse value from HTTP API data.
--
_ _ WARNING _ _ : Do not derive this using as the generated
-- instance will loop indefinitely.
class FromHttpApiData a where
# MINIMAL parseUrlPiece | parseQueryParam #
-- | Parse URL path piece.
parseUrlPiece :: Text -> Either Text a
parseUrlPiece = parseQueryParam
-- | Parse HTTP header value.
parseHeader :: ByteString -> Either Text a
parseHeader = parseUrlPiece <=< (left (T.pack . show) . decodeUtf8')
-- | Parse query param value.
parseQueryParam :: Text -> Either Text a
parseQueryParam = parseUrlPiece
-- | Convert multiple values to a list of URL pieces.
--
> > > toUrlPieces [ 1 , 2 , 3 ] : : [ Text ]
[ " 1","2","3 " ]
toUrlPieces :: (Functor t, ToHttpApiData a) => t a -> t Text
toUrlPieces = fmap toUrlPiece
-- | Parse multiple URL pieces.
--
-- >>> parseUrlPieces ["true", "false"] :: Either Text [Bool]
-- Right [True,False]
> > > parseUrlPieces [ " 123 " , " hello " , " world " ] : : Either Text [ Int ]
-- Left "could not parse: `hello' (input does not start with a digit)"
parseUrlPieces :: (Traversable t, FromHttpApiData a) => t Text -> Either Text (t a)
parseUrlPieces = traverse parseUrlPiece
-- | Convert multiple values to a list of query parameter values.
--
> > > toQueryParams [ fromGregorian 2015 10 03 , fromGregorian 2015 12 01 ] : : [ Text ]
[ " 2015 - 10 - 03","2015 - 12 - 01 " ]
toQueryParams :: (Functor t, ToHttpApiData a) => t a -> t Text
toQueryParams = fmap toQueryParam
-- | Parse multiple query parameters.
--
> > > parseQueryParams [ " 1 " , " 2 " , " 3 " ] : : Either Text [ Int ]
-- Right [1,2,3]
> > > parseQueryParams [ " 64 " , " 128 " , " 256 " ] : : Either Text [ Word8 ]
Left " out of bounds : ` 256 ' ( should be between 0 and 255 ) "
parseQueryParams :: (Traversable t, FromHttpApiData a) => t Text -> Either Text (t a)
parseQueryParams = traverse parseQueryParam
| Parse URL path piece in a @'Maybe'@.
--
> > > parseUrlPieceMaybe " 12 " : : Maybe Int
Just 12
parseUrlPieceMaybe :: FromHttpApiData a => Text -> Maybe a
parseUrlPieceMaybe = either (const Nothing) Just . parseUrlPiece
| Parse HTTP header value in a @'Maybe'@.
--
-- >>> parseHeaderMaybe "hello" :: Maybe Text
-- Just "hello"
parseHeaderMaybe :: FromHttpApiData a => ByteString -> Maybe a
parseHeaderMaybe = either (const Nothing) Just . parseHeader
| Parse query param value in a @'Maybe'@.
--
> > > parseQueryParamMaybe " true " : : Maybe
-- Just True
parseQueryParamMaybe :: FromHttpApiData a => Text -> Maybe a
parseQueryParamMaybe = either (const Nothing) Just . parseQueryParam
-- | Default parsing error.
defaultParseError :: Text -> Either Text a
defaultParseError input = Left ("could not parse: `" <> input <> "'")
-- | Convert @'Maybe'@ parser into @'Either' 'Text'@ parser with default error message.
parseMaybeTextData :: (Text -> Maybe a) -> (Text -> Either Text a)
parseMaybeTextData parse input =
case parse input of
Nothing -> defaultParseError input
Just val -> Right val
#if USE_TEXT_SHOW
-- | /Lower case/.
--
-- Convert to URL piece using @'TextShow'@ instance.
-- The result is always lower cased.
--
-- >>> showTextData True
-- "true"
--
-- This can be used as a default implementation for enumeration types:
--
-- @
data MyData = Foo | Bar | Baz deriving ( Generic )
--
instance where
-- showt = genericShowt
--
instance ToHttpApiData MyData where
-- toUrlPiece = showTextData
-- @
showTextData :: TextShow a => a -> Text
showTextData = T.toLower . showt
#else
-- | /Lower case/.
--
Convert to URL piece using @'Show'@ instance .
-- The result is always lower cased.
--
-- >>> showTextData True
-- "true"
--
-- This can be used as a default implementation for enumeration types:
--
> > > data MyData = Foo | Bar | Baz deriving ( Show )
> > > instance ToHttpApiData MyData where toUrlPiece = showTextData
-- >>> toUrlPiece Foo
-- "foo"
showTextData :: Show a => a -> Text
showTextData = T.toLower . showt
| Like @'show'@ , but returns @'Text'@.
showt :: Show a => a -> Text
showt = T.pack . show
#endif
-- | /Case insensitive/.
--
Parse given text case insensitive and then parse the rest of the input
using @'parseUrlPiece'@.
--
> > > " Just " " just 10 " : : Either Text Int
-- Right 10
-- >>> parseUrlPieceWithPrefix "Left " "left" :: Either Text Bool
-- Left "could not parse: `left'"
--
-- This can be used to implement @'FromHttpApiData'@ for single field constructors:
--
> > > data deriving ( Show )
> > > instance FromHttpApiData Foo where parseUrlPiece s = Foo < $ > parseUrlPieceWithPrefix " Foo " s
-- >>> parseUrlPiece "foo 1" :: Either Text Foo
Right ( Foo 1 )
parseUrlPieceWithPrefix :: FromHttpApiData a => Text -> Text -> Either Text a
parseUrlPieceWithPrefix pattern input
| T.toLower pattern == T.toLower prefix = parseUrlPiece rest
| otherwise = defaultParseError input
where
(prefix, rest) = T.splitAt (T.length pattern) input
-- | Parse given bytestring then parse the rest of the input using @'parseHeader'@.
--
-- @
data = Text deriving ( Show )
--
-- instance FromHttpApiData BasicAuthToken where
h = \<$\ > parseHeaderWithPrefix " Basic " h
parseQueryParam p = \<$\ > parseQueryParam p
-- @
--
> > > parseHeader " Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ== " : : Either Text
Right ( " QWxhZGRpbjpvcGVuIHNlc2FtZQ== " )
parseHeaderWithPrefix :: FromHttpApiData a => ByteString -> ByteString -> Either Text a
parseHeaderWithPrefix pattern input
| pattern `BS.isPrefixOf` input = parseHeader (BS.drop (BS.length pattern) input)
| otherwise = defaultParseError (showt input)
-- | /Case insensitive/.
--
Parse given text case insensitive and then parse the rest of the input
using @'parseQueryParam'@.
--
-- >>> parseQueryParamWithPrefix "z" "z10" :: Either Text Int
-- Right 10
parseQueryParamWithPrefix :: FromHttpApiData a => Text -> Text -> Either Text a
parseQueryParamWithPrefix pattern input
| T.toLower pattern == T.toLower prefix = parseQueryParam rest
| otherwise = defaultParseError input
where
(prefix, rest) = T.splitAt (T.length pattern) input
#if USE_TEXT_SHOW
-- | /Case insensitive/.
--
Parse values case insensitively based on @'TextShow'@ instance .
--
-- >>> parseBoundedTextData "true" :: Either Text Bool
-- Right True
-- >>> parseBoundedTextData "FALSE" :: Either Text Bool
-- Right False
--
-- This can be used as a default implementation for enumeration types:
--
-- @
data MyData = Foo | Bar | Baz deriving ( Show , Bounded , , Generic )
--
instance where
-- showt = genericShowt
--
instance FromHttpApiData MyData where
-- parseUrlPiece = parseBoundedTextData
-- @
parseBoundedTextData :: (TextShow a, Bounded a, Enum a) => Text -> Either Text a
#else
-- | /Case insensitive/.
--
Parse values case insensitively based on @'Show'@ instance .
--
-- >>> parseBoundedTextData "true" :: Either Text Bool
-- Right True
-- >>> parseBoundedTextData "FALSE" :: Either Text Bool
-- Right False
--
-- This can be used as a default implementation for enumeration types:
--
> > > data MyData = Foo | Bar | Baz deriving ( Show , Bounded , )
> > > instance FromHttpApiData MyData where parseUrlPiece = parseBoundedTextData
-- >>> parseUrlPiece "foo" :: Either Text MyData
-- Right Foo
parseBoundedTextData :: (Show a, Bounded a, Enum a) => Text -> Either Text a
#endif
parseBoundedTextData = parseBoundedEnumOfI showTextData
-- | Lookup values based on a precalculated mapping of their representations.
lookupBoundedEnumOf :: (Bounded a, Enum a, Eq b) => (a -> b) -> b -> Maybe a
lookupBoundedEnumOf f = flip lookup (map (f &&& id) [minBound..maxBound])
| Parse values based on a precalculated mapping of their @'Text'@ representation .
--
-- >>> parseBoundedEnumOf toUrlPiece "true" :: Either Text Bool
-- Right True
--
-- For case insensitive parser see 'parseBoundedEnumOfI'.
parseBoundedEnumOf :: (Bounded a, Enum a) => (a -> Text) -> Text -> Either Text a
parseBoundedEnumOf = parseMaybeTextData . lookupBoundedEnumOf
-- | /Case insensitive/.
--
Parse values case insensitively based on a precalculated mapping
of their @'Text'@ representations .
--
-- >>> parseBoundedEnumOfI toUrlPiece "FALSE" :: Either Text Bool
-- Right False
--
-- For case sensitive parser see 'parseBoundedEnumOf'.
parseBoundedEnumOfI :: (Bounded a, Enum a) => (a -> Text) -> Text -> Either Text a
parseBoundedEnumOfI f = parseBoundedEnumOf (T.toLower . f) . T.toLower
-- | /Case insensitive/.
--
Parse values case insensitively based on @'ToHttpApiData'@ instance .
Uses @'toUrlPiece'@ to get possible values .
parseBoundedUrlPiece :: (ToHttpApiData a, Bounded a, Enum a) => Text -> Either Text a
parseBoundedUrlPiece = parseBoundedEnumOfI toUrlPiece
-- | /Case insensitive/.
--
Parse values case insensitively based on @'ToHttpApiData'@ instance .
-- Uses @'toQueryParam'@ to get possible values.
parseBoundedQueryParam :: (ToHttpApiData a, Bounded a, Enum a) => Text -> Either Text a
parseBoundedQueryParam = parseBoundedEnumOfI toQueryParam
| Parse values based on @'ToHttpApiData'@ instance .
-- Uses @'toHeader'@ to get possible values.
parseBoundedHeader :: (ToHttpApiData a, Bounded a, Enum a) => ByteString -> Either Text a
parseBoundedHeader bs = case lookupBoundedEnumOf toHeader bs of
Nothing -> defaultParseError $ T.pack $ show bs
Just x -> return x
| Parse URL piece using instance .
--
-- Use for types which do not involve letters:
--
> > > readTextData " 1991 - 06 - 02 " : : Either Text Day
Right 1991 - 06 - 02
--
This parser is case sensitive and will not match @'showTextData'@
-- in presence of letters:
--
-- >>> readTextData (showTextData True) :: Either Text Bool
-- Left "could not parse: `true'"
--
-- See @'parseBoundedTextData'@.
readTextData :: Read a => Text -> Either Text a
readTextData = parseMaybeTextData (readMaybe . T.unpack)
-- | Run @'Reader'@ as HTTP API data parser.
runReader :: Reader a -> Text -> Either Text a
runReader reader input =
case reader input of
Left err -> Left ("could not parse: `" <> input <> "' (" <> T.pack err <> ")")
Right (x, rest)
| T.null rest -> Right x
| otherwise -> defaultParseError input
-- | Run @'Reader'@ to parse bounded integral value with bounds checking.
--
> > > parseBounded decimal " 256 " : : Either Text Word8
Left " out of bounds : ` 256 ' ( should be between 0 and 255 ) "
parseBounded :: forall a. (Bounded a, Integral a) => Reader Integer -> Text -> Either Text a
parseBounded reader input = do
n <- runReader reader input
if (n > h || n < l)
then Left ("out of bounds: `" <> input <> "' (should be between " <> showt l <> " and " <> showt h <> ")")
else Right (fromInteger n)
where
l = toInteger (minBound :: a)
h = toInteger (maxBound :: a)
-- | Convert to a URL-encoded path piece using 'toUrlPiece'.
/Note/ : this function does not check if the result contains unescaped characters !
-- This function can be used to override 'toEncodedUrlPiece' as a more efficient implementation
-- when the resulting URL piece /never/ has to be escaped.
unsafeToEncodedUrlPiece :: ToHttpApiData a => a -> BS.Builder
unsafeToEncodedUrlPiece = BS.byteString . encodeUtf8 . toUrlPiece
-- | Convert to a URL-encoded query param using 'toQueryParam'.
/Note/ : this function does not check if the result contains unescaped characters !
--
@since 0.5.1
unsafeToEncodedQueryParam :: ToHttpApiData a => a -> BS.Builder
unsafeToEncodedQueryParam = BS.byteString . encodeUtf8 . toQueryParam
-- |
-- >>> toUrlPiece ()
-- "_"
instance ToHttpApiData () where
toUrlPiece _ = "_"
toHeader _ = "_"
toEncodedUrlPiece _ = "_"
toEncodedQueryParam _ = "_"
instance ToHttpApiData Char where
toUrlPiece = T.singleton
-- |
> > > toUrlPiece ( Version [ 1 , 2 , 3 ] [ ] )
-- "1.2.3"
instance ToHttpApiData Version where
toUrlPiece = T.pack . showVersion
toEncodedUrlPiece = unsafeToEncodedUrlPiece
toEncodedQueryParam = unsafeToEncodedQueryParam
instance ToHttpApiData Void where toUrlPiece = absurd
instance ToHttpApiData Natural where toUrlPiece = showt; toEncodedUrlPiece = unsafeToEncodedUrlPiece; toEncodedQueryParam = unsafeToEncodedQueryParam
instance ToHttpApiData Bool where toUrlPiece = showTextData; toEncodedUrlPiece = unsafeToEncodedUrlPiece; toEncodedQueryParam = unsafeToEncodedQueryParam
instance ToHttpApiData Ordering where toUrlPiece = showTextData; toEncodedUrlPiece = unsafeToEncodedUrlPiece; toEncodedQueryParam = unsafeToEncodedQueryParam
instance ToHttpApiData Double where toUrlPiece = showt; toEncodedUrlPiece = unsafeToEncodedUrlPiece; toEncodedQueryParam = unsafeToEncodedQueryParam
instance ToHttpApiData Float where toUrlPiece = showt; toEncodedUrlPiece = unsafeToEncodedUrlPiece; toEncodedQueryParam = unsafeToEncodedQueryParam
instance ToHttpApiData Int where toUrlPiece = showt; toEncodedUrlPiece = unsafeToEncodedUrlPiece; toEncodedQueryParam = unsafeToEncodedQueryParam
instance ToHttpApiData Int8 where toUrlPiece = showt; toEncodedUrlPiece = unsafeToEncodedUrlPiece; toEncodedQueryParam = unsafeToEncodedQueryParam
instance ToHttpApiData Int16 where toUrlPiece = showt; toEncodedUrlPiece = unsafeToEncodedUrlPiece; toEncodedQueryParam = unsafeToEncodedQueryParam
instance ToHttpApiData Int32 where toUrlPiece = showt; toEncodedUrlPiece = unsafeToEncodedUrlPiece; toEncodedQueryParam = unsafeToEncodedQueryParam
instance ToHttpApiData Int64 where toUrlPiece = showt; toEncodedUrlPiece = unsafeToEncodedUrlPiece; toEncodedQueryParam = unsafeToEncodedQueryParam
instance ToHttpApiData Integer where toUrlPiece = showt; toEncodedUrlPiece = unsafeToEncodedUrlPiece; toEncodedQueryParam = unsafeToEncodedQueryParam
instance ToHttpApiData Word where toUrlPiece = showt; toEncodedUrlPiece = unsafeToEncodedUrlPiece; toEncodedQueryParam = unsafeToEncodedQueryParam
instance ToHttpApiData Word8 where toUrlPiece = showt; toEncodedUrlPiece = unsafeToEncodedUrlPiece; toEncodedQueryParam = unsafeToEncodedQueryParam
instance ToHttpApiData Word16 where toUrlPiece = showt; toEncodedUrlPiece = unsafeToEncodedUrlPiece; toEncodedQueryParam = unsafeToEncodedQueryParam
instance ToHttpApiData Word32 where toUrlPiece = showt; toEncodedUrlPiece = unsafeToEncodedUrlPiece; toEncodedQueryParam = unsafeToEncodedQueryParam
instance ToHttpApiData Word64 where toUrlPiece = showt; toEncodedUrlPiece = unsafeToEncodedUrlPiece; toEncodedQueryParam = unsafeToEncodedQueryParam
-- | Note: this instance is not polykinded
instance F.HasResolution a => ToHttpApiData (F.Fixed (a :: Type)) where toUrlPiece = showt; toEncodedUrlPiece = unsafeToEncodedUrlPiece; toEncodedQueryParam = unsafeToEncodedQueryParam
-- |
> > > toUrlPiece ( fromGregorian 2015 10 03 )
" 2015 - 10 - 03 "
instance ToHttpApiData Day where
toUrlPiece = T.pack . show
toEncodedUrlPiece = unsafeToEncodedUrlPiece
toEncodedQueryParam = unsafeToEncodedQueryParam
timeToUrlPiece :: FormatTime t => String -> t -> Text
timeToUrlPiece fmt = T.pack . formatTime defaultTimeLocale (iso8601DateFormat (Just fmt))
-- |
> > > toUrlPiece $ TimeOfDay 14 55 23.1
" 14:55:23.1 "
instance ToHttpApiData TimeOfDay where
toUrlPiece = T.pack . formatTime defaultTimeLocale "%H:%M:%S%Q"
toEncodedUrlPiece = unsafeToEncodedUrlPiece
-- no toEncodedQueryParam as : is unsafe char.
-- |
> > > toUrlPiece $ LocalTime ( fromGregorian 2015 10 03 ) ( TimeOfDay 14 55 21.687 )
" 2015 - 10 - 03T14:55:21.687 "
instance ToHttpApiData LocalTime where
toUrlPiece = timeToUrlPiece "%H:%M:%S%Q"
toEncodedUrlPiece = unsafeToEncodedUrlPiece
-- no toEncodedQueryParam as : is unsafe char.
-- |
> > > toUrlPiece $ ZonedTime ( LocalTime ( fromGregorian 2015 10 03 ) ( TimeOfDay 14 55 51.001 ) ) utc
" 2015 - 10 - 03T14:55:51.001 + 0000 "
instance ToHttpApiData ZonedTime where
toUrlPiece = timeToUrlPiece "%H:%M:%S%Q%z"
toEncodedUrlPiece = unsafeToEncodedUrlPiece
-- no toEncodedQueryParam as : is unsafe char.
-- |
> > > toUrlPiece $ UTCTime ( fromGregorian 2015 10 03 ) 864.5
" 2015 - 10 - 03T00:14:24.5Z "
instance ToHttpApiData UTCTime where
toUrlPiece = timeToUrlPiece "%H:%M:%S%QZ"
toEncodedUrlPiece = unsafeToEncodedUrlPiece
-- no toEncodedQueryParam as : is unsafe char.
-- |
> > > toUrlPiece Monday
" monday "
instance ToHttpApiData DayOfWeek where
toUrlPiece Monday = "monday"
toUrlPiece Tuesday = "tuesday"
toUrlPiece Wednesday = "wednesday"
toUrlPiece Thursday = "thursday"
toUrlPiece Friday = "friday"
toUrlPiece Saturday = "saturday"
toUrlPiece Sunday = "sunday"
toEncodedUrlPiece = unsafeToEncodedUrlPiece
toEncodedQueryParam = unsafeToEncodedQueryParam
-- |
-- >>> toUrlPiece Q4
-- "q4"
instance ToHttpApiData QuarterOfYear where
toUrlPiece Q1 = "q1"
toUrlPiece Q2 = "q2"
toUrlPiece Q3 = "q3"
toUrlPiece Q4 = "q4"
toEncodedUrlPiece = unsafeToEncodedUrlPiece
toEncodedQueryParam = unsafeToEncodedQueryParam
-- |
-- >>> import Data.Time.Calendar.Quarter.Compat (Quarter (..))
> > >
2010 - Q1
--
> > > toUrlPiece $
" 2010 - q1 "
--
instance ToHttpApiData Quarter where
toUrlPiece q = case toYearQuarter q of
(y, qoy) -> T.pack (show y ++ "-" ++ f qoy)
where
f Q1 = "q1"
f Q2 = "q2"
f Q3 = "q3"
f Q4 = "q4"
toEncodedUrlPiece = unsafeToEncodedUrlPiece
toEncodedQueryParam = unsafeToEncodedQueryParam
-- |
> > > import Data . Time . Calendar . Month . Compat ( Month ( .. ) )
> > > MkMonth 24482
2040 - 03
--
> > > toUrlPiece $ MkMonth 24482
" 2040 - 03 "
--
instance ToHttpApiData Month where
toUrlPiece = T.pack . formatTime defaultTimeLocale "%Y-%m"
toEncodedUrlPiece = unsafeToEncodedUrlPiece
toEncodedQueryParam = unsafeToEncodedQueryParam
instance ToHttpApiData NominalDiffTime where
toUrlPiece = toUrlPiece . nominalDiffTimeToSeconds
toEncodedQueryParam = unsafeToEncodedQueryParam
toEncodedUrlPiece = unsafeToEncodedUrlPiece
instance ToHttpApiData String where toUrlPiece = T.pack
instance ToHttpApiData Text where toUrlPiece = id
instance ToHttpApiData L.Text where toUrlPiece = L.toStrict
instance ToHttpApiData All where
toUrlPiece = coerce (toUrlPiece :: Bool -> Text)
toEncodedUrlPiece = coerce (toEncodedUrlPiece :: Bool -> BS.Builder)
toEncodedQueryParam = coerce (toEncodedQueryParam :: Bool -> BS.Builder)
instance ToHttpApiData Any where
toUrlPiece = coerce (toUrlPiece :: Bool -> Text)
toEncodedUrlPiece = coerce (toEncodedUrlPiece :: Bool -> BS.Builder)
toEncodedQueryParam = coerce (toEncodedQueryParam :: Bool -> BS.Builder)
instance ToHttpApiData a => ToHttpApiData (Dual a) where
toUrlPiece = coerce (toUrlPiece :: a -> Text)
toEncodedUrlPiece = coerce (toEncodedUrlPiece :: a -> BS.Builder)
toEncodedQueryParam = coerce (toEncodedQueryParam :: a -> BS.Builder)
instance ToHttpApiData a => ToHttpApiData (Sum a) where
toUrlPiece = coerce (toUrlPiece :: a -> Text)
toEncodedUrlPiece = coerce (toEncodedUrlPiece :: a -> BS.Builder)
toEncodedQueryParam = coerce (toEncodedQueryParam :: a -> BS.Builder)
instance ToHttpApiData a => ToHttpApiData (Product a) where
toUrlPiece = coerce (toUrlPiece :: a -> Text)
toEncodedUrlPiece = coerce (toEncodedUrlPiece :: a -> BS.Builder)
toEncodedQueryParam = coerce (toEncodedQueryParam :: a -> BS.Builder)
instance ToHttpApiData a => ToHttpApiData (First a) where
toUrlPiece = coerce (toUrlPiece :: Maybe a -> Text)
toEncodedUrlPiece = coerce (toEncodedUrlPiece :: Maybe a -> BS.Builder)
toEncodedQueryParam = coerce (toEncodedQueryParam :: Maybe a -> BS.Builder)
instance ToHttpApiData a => ToHttpApiData (Last a) where
toUrlPiece = coerce (toUrlPiece :: Maybe a -> Text)
toEncodedUrlPiece = coerce (toEncodedUrlPiece :: Maybe a -> BS.Builder)
toEncodedQueryParam = coerce (toEncodedQueryParam :: Maybe a -> BS.Builder)
instance ToHttpApiData a => ToHttpApiData (Semi.Min a) where
toUrlPiece = coerce (toUrlPiece :: a -> Text)
toEncodedUrlPiece = coerce (toEncodedUrlPiece :: a -> BS.Builder)
toEncodedQueryParam = coerce (toEncodedQueryParam :: a -> BS.Builder)
instance ToHttpApiData a => ToHttpApiData (Semi.Max a) where
toUrlPiece = coerce (toUrlPiece :: a -> Text)
toEncodedUrlPiece = coerce (toEncodedUrlPiece :: a -> BS.Builder)
toEncodedQueryParam = coerce (toEncodedQueryParam :: a -> BS.Builder)
instance ToHttpApiData a => ToHttpApiData (Semi.First a) where
toUrlPiece = coerce (toUrlPiece :: a -> Text)
toEncodedUrlPiece = coerce (toEncodedUrlPiece :: a -> BS.Builder)
toEncodedQueryParam = coerce (toEncodedQueryParam :: a -> BS.Builder)
instance ToHttpApiData a => ToHttpApiData (Semi.Last a) where
toUrlPiece = coerce (toUrlPiece :: a -> Text)
toEncodedUrlPiece = coerce (toEncodedUrlPiece :: a -> BS.Builder)
toEncodedQueryParam = coerce (toEncodedQueryParam :: a -> BS.Builder)
-- |
-- >>> toUrlPiece (Just "Hello")
-- "just Hello"
instance ToHttpApiData a => ToHttpApiData (Maybe a) where
toUrlPiece (Just x) = "just " <> toUrlPiece x
toUrlPiece Nothing = "nothing"
-- |
-- >>> toUrlPiece (Left "err" :: Either String Int)
-- "left err"
> > > toUrlPiece ( Right 3 : : Either String Int )
" right 3 "
instance (ToHttpApiData a, ToHttpApiData b) => ToHttpApiData (Either a b) where
toUrlPiece (Left x) = "left " <> toUrlPiece x
toUrlPiece (Right x) = "right " <> toUrlPiece x
-- | /Note:/ this instance works correctly for alphanumeric name and value
--
-- >>> let Right c = parseUrlPiece "SESSID=r2t5uvjq435r4q7ib3vtdjq120" :: Either Text SetCookie
-- >>> toUrlPiece c
-- "SESSID=r2t5uvjq435r4q7ib3vtdjq120"
--
-- >>> toHeader c
-- "SESSID=r2t5uvjq435r4q7ib3vtdjq120"
--
instance ToHttpApiData SetCookie where
toUrlPiece = decodeUtf8With lenientDecode . toHeader
toHeader = LBS.toStrict . BS.toLazyByteString . renderSetCookie
-- toEncodedUrlPiece = renderSetCookie -- doesn't do things.
-- | Note: this instance is not polykinded
instance ToHttpApiData a => ToHttpApiData (Tagged (b :: Type) a) where
toUrlPiece = coerce (toUrlPiece :: a -> Text)
toHeader = coerce (toHeader :: a -> ByteString)
toQueryParam = coerce (toQueryParam :: a -> Text)
toEncodedUrlPiece = coerce (toEncodedUrlPiece :: a -> BS.Builder)
toEncodedQueryParam = coerce (toEncodedQueryParam :: a -> BS.Builder)
-- | @since 0.4.2
instance ToHttpApiData a => ToHttpApiData (Const a b) where
toUrlPiece = coerce (toUrlPiece :: a -> Text)
toHeader = coerce (toHeader :: a -> ByteString)
toQueryParam = coerce (toQueryParam :: a -> Text)
toEncodedUrlPiece = coerce (toEncodedUrlPiece :: a -> BS.Builder)
toEncodedQueryParam = coerce (toEncodedQueryParam :: a -> BS.Builder)
-- | @since 0.4.2
instance ToHttpApiData a => ToHttpApiData (Identity a) where
toUrlPiece = coerce (toUrlPiece :: a -> Text)
toHeader = coerce (toHeader :: a -> ByteString)
toQueryParam = coerce (toQueryParam :: a -> Text)
toEncodedUrlPiece = coerce (toEncodedUrlPiece :: a -> BS.Builder)
toEncodedQueryParam = coerce (toEncodedQueryParam :: a -> BS.Builder)
-- |
-- >>> parseUrlPiece "_" :: Either Text ()
-- Right ()
instance FromHttpApiData () where
parseUrlPiece "_" = pure ()
parseUrlPiece s = defaultParseError s
instance FromHttpApiData Char where
parseUrlPiece s =
case T.uncons s of
Just (c, s') | T.null s' -> pure c
_ -> defaultParseError s
-- |
-- >>> showVersion <$> parseUrlPiece "1.2.3"
-- Right "1.2.3"
instance FromHttpApiData Version where
parseUrlPiece s =
case reverse (readP_to_S parseVersion (T.unpack s)) of
((x, ""):_) -> pure x
_ -> defaultParseError s
| Parsing a value is always an error , considering as a data type with no constructors .
instance FromHttpApiData Void where
parseUrlPiece _ = Left "Void cannot be parsed!"
instance FromHttpApiData Natural where
parseUrlPiece s = do
n <- runReader (signed decimal) s
if n < 0
then Left ("underflow: " <> s <> " (should be a non-negative integer)")
else Right (fromInteger n)
instance FromHttpApiData Bool where parseUrlPiece = parseBoundedUrlPiece
instance FromHttpApiData Ordering where parseUrlPiece = parseBoundedUrlPiece
instance FromHttpApiData Double where parseUrlPiece = runReader rational
instance FromHttpApiData Float where parseUrlPiece = runReader rational
instance FromHttpApiData Int where parseUrlPiece = parseBounded (signed decimal)
instance FromHttpApiData Int8 where parseUrlPiece = parseBounded (signed decimal)
instance FromHttpApiData Int16 where parseUrlPiece = parseBounded (signed decimal)
instance FromHttpApiData Int32 where parseUrlPiece = parseBounded (signed decimal)
instance FromHttpApiData Int64 where parseUrlPiece = parseBounded (signed decimal)
instance FromHttpApiData Integer where parseUrlPiece = runReader (signed decimal)
instance FromHttpApiData Word where parseUrlPiece = parseBounded decimal
instance FromHttpApiData Word8 where parseUrlPiece = parseBounded decimal
instance FromHttpApiData Word16 where parseUrlPiece = parseBounded decimal
instance FromHttpApiData Word32 where parseUrlPiece = parseBounded decimal
instance FromHttpApiData Word64 where parseUrlPiece = parseBounded decimal
instance FromHttpApiData String where parseUrlPiece = Right . T.unpack
instance FromHttpApiData Text where parseUrlPiece = Right
instance FromHttpApiData L.Text where parseUrlPiece = Right . L.fromStrict
-- | Note: this instance is not polykinded
instance F.HasResolution a => FromHttpApiData (F.Fixed (a :: Type)) where
parseUrlPiece = runReader rational
-- |
> > > toGregorian < $ > parseUrlPiece " 2016 - 12 - 01 "
Right ( 2016,12,1 )
instance FromHttpApiData Day where parseUrlPiece = runAtto Atto.day
-- |
> > > parseUrlPiece " 14:55:01.333 " : : Either Text
-- Right 14:55:01.333
instance FromHttpApiData TimeOfDay where parseUrlPiece = runAtto Atto.timeOfDay
-- |
> > > parseUrlPiece " 2015 - 10 - 03T14:55:01 " : : Either Text LocalTime
-- Right 2015-10-03 14:55:01
instance FromHttpApiData LocalTime where parseUrlPiece = runAtto Atto.localTime
-- |
> > > parseUrlPiece " 2015 - 10 - 03T14:55:01 + 0000 " : : Either Text ZonedTime
Right 2015 - 10 - 03 14:55:01 +0000
--
> > > parseQueryParam " 2016 - 12 - 31T01:00:00Z " : : Either Text ZonedTime
Right 2016 - 12 - 31 01:00:00 +0000
instance FromHttpApiData ZonedTime where parseUrlPiece = runAtto Atto.zonedTime
-- |
> > > parseUrlPiece " 2015 - 10 - 03T00:14:24Z " : : Either Text UTCTime
Right 2015 - 10 - 03 00:14:24 UTC
instance FromHttpApiData UTCTime where parseUrlPiece = runAtto Atto.utcTime
-- |
> > > parseUrlPiece " Monday " : : Either Text
-- Right Monday
instance FromHttpApiData DayOfWeek where
parseUrlPiece t = case Map.lookup (T.toLower t) m of
Just dow -> Right dow
Nothing -> Left $ "Incorrect DayOfWeek: " <> T.take 10 t
where
m :: Map.Map Text DayOfWeek
m = Map.fromList [ (toUrlPiece dow, dow) | dow <- [Monday .. Sunday] ]
instance FromHttpApiData NominalDiffTime where parseUrlPiece = fmap secondsToNominalDiffTime . parseUrlPiece
-- |
> > > parseUrlPiece " 2021 - 01 " : : Either Text Month
-- Right 2021-01
instance FromHttpApiData Month where parseUrlPiece = runAtto Atto.month
-- |
> > > parseUrlPiece " 2021 - q1 " : : Either Text Quarter
-- Right 2021-Q1
instance FromHttpApiData Quarter where parseUrlPiece = runAtto Atto.quarter
-- |
> > > parseUrlPiece " q2 " : : Either Text QuarterOfYear
-- Right Q2
--
> > > parseUrlPiece " Q3 " : : Either Text QuarterOfYear
-- Right Q3
instance FromHttpApiData QuarterOfYear where
parseUrlPiece t = case T.toLower t of
"q1" -> return Q1
"q2" -> return Q2
"q3" -> return Q3
"q4" -> return Q4
_ -> Left "Invalid quarter of year"
instance FromHttpApiData All where parseUrlPiece = coerce (parseUrlPiece :: Text -> Either Text Bool)
instance FromHttpApiData Any where parseUrlPiece = coerce (parseUrlPiece :: Text -> Either Text Bool)
instance FromHttpApiData a => FromHttpApiData (Dual a) where parseUrlPiece = coerce (parseUrlPiece :: Text -> Either Text a)
instance FromHttpApiData a => FromHttpApiData (Sum a) where parseUrlPiece = coerce (parseUrlPiece :: Text -> Either Text a)
instance FromHttpApiData a => FromHttpApiData (Product a) where parseUrlPiece = coerce (parseUrlPiece :: Text -> Either Text a)
instance FromHttpApiData a => FromHttpApiData (First a) where parseUrlPiece = coerce (parseUrlPiece :: Text -> Either Text (Maybe a))
instance FromHttpApiData a => FromHttpApiData (Last a) where parseUrlPiece = coerce (parseUrlPiece :: Text -> Either Text (Maybe a))
instance FromHttpApiData a => FromHttpApiData (Semi.Min a) where parseUrlPiece = coerce (parseUrlPiece :: Text -> Either Text a)
instance FromHttpApiData a => FromHttpApiData (Semi.Max a) where parseUrlPiece = coerce (parseUrlPiece :: Text -> Either Text a)
instance FromHttpApiData a => FromHttpApiData (Semi.First a) where parseUrlPiece = coerce (parseUrlPiece :: Text -> Either Text a)
instance FromHttpApiData a => FromHttpApiData (Semi.Last a) where parseUrlPiece = coerce (parseUrlPiece :: Text -> Either Text a)
-- |
> > > parseUrlPiece " Just 123 " : : Either Text ( Maybe Int )
Right ( Just 123 )
instance FromHttpApiData a => FromHttpApiData (Maybe a) where
parseUrlPiece s
| T.toLower (T.take 7 s) == "nothing" = pure Nothing
| otherwise = Just <$> parseUrlPieceWithPrefix "Just " s
-- |
> > > parseUrlPiece " Right 123 " : : Either Text ( Either String Int )
Right ( Right 123 )
instance (FromHttpApiData a, FromHttpApiData b) => FromHttpApiData (Either a b) where
parseUrlPiece s =
Right <$> parseUrlPieceWithPrefix "Right " s
<!> Left <$> parseUrlPieceWithPrefix "Left " s
where
infixl 3 <!>
Left _ <!> y = y
x <!> _ = x
instance ToHttpApiData UUID.UUID where
toUrlPiece = UUID.toText
toHeader = UUID.toASCIIBytes
toEncodedUrlPiece = unsafeToEncodedUrlPiece
instance FromHttpApiData UUID.UUID where
parseUrlPiece = maybe (Left "invalid UUID") Right . UUID.fromText
parseHeader = maybe (Left "invalid UUID") Right . UUID.fromASCIIBytes
-- | Lenient parameters. 'FromHttpApiData' combinators always return `Right`.
--
@since 0.3.5
newtype LenientData a = LenientData { getLenientData :: Either Text a }
deriving (Eq, Ord, Show, Read, Typeable, Data, Functor, Foldable, Traversable)
instance FromHttpApiData a => FromHttpApiData (LenientData a) where
parseUrlPiece = Right . LenientData . parseUrlPiece
parseHeader = Right . LenientData . parseHeader
parseQueryParam = Right . LenientData . parseQueryParam
-- | /Note:/ this instance works correctly for alphanumeric name and value
--
-- >>> parseUrlPiece "SESSID=r2t5uvjq435r4q7ib3vtdjq120" :: Either Text SetCookie
Right ( SetCookie { setCookieName = " SESSID " , setCookieValue = " r2t5uvjq435r4q7ib3vtdjq120 " , setCookiePath = Nothing , setCookieExpires = Nothing , setCookieMaxAge = Nothing , setCookieDomain = Nothing , setCookieHttpOnly = False , setCookieSecure = False , setCookieSameSite = Nothing } )
instance FromHttpApiData SetCookie where
parseUrlPiece = parseHeader . encodeUtf8
parseHeader = Right . parseSetCookie
-- | Note: this instance is not polykinded
instance FromHttpApiData a => FromHttpApiData (Tagged (b :: Type) a) where
parseUrlPiece = coerce (parseUrlPiece :: Text -> Either Text a)
parseHeader = coerce (parseHeader :: ByteString -> Either Text a)
parseQueryParam = coerce (parseQueryParam :: Text -> Either Text a)
-- | @since 0.4.2
instance FromHttpApiData a => FromHttpApiData (Const a b) where
parseUrlPiece = coerce (parseUrlPiece :: Text -> Either Text a)
parseHeader = coerce (parseHeader :: ByteString -> Either Text a)
parseQueryParam = coerce (parseQueryParam :: Text -> Either Text a)
-- | @since 0.4.2
instance FromHttpApiData a => FromHttpApiData (Identity a) where
parseUrlPiece = coerce (parseUrlPiece :: Text -> Either Text a)
parseHeader = coerce (parseHeader :: ByteString -> Either Text a)
parseQueryParam = coerce (parseQueryParam :: Text -> Either Text a)
-------------------------------------------------------------------------------
Attoparsec helpers
-------------------------------------------------------------------------------
runAtto :: Atto.Parser a -> Text -> Either Text a
runAtto p t = case Atto.parseOnly (p <* Atto.endOfInput) t of
Left err -> Left (T.pack err)
Right x -> Right x
| null | https://raw.githubusercontent.com/fizruk/http-api-data/5408b078d1ee960309a9fc6141b7e14bc903b3a0/src/Web/Internal/HttpApiData.hs | haskell | # LANGUAGE CPP #
# LANGUAGE DefaultSignatures #
# LANGUAGE DeriveDataTypeable #
# LANGUAGE DeriveFoldable #
# LANGUAGE DeriveTraversable #
# LANGUAGE KindSignatures #
# LANGUAGE OverloadedStrings #
# LANGUAGE PolyKinds #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TypeSynonymInstances #
|
such as URL pieces, headers and query parameters.
$setup
>>> import Data.Time.Compat
>>> import Data.Version
| Convert value to HTTP API data.
instance will loop indefinitely.
# MINIMAL toUrlPiece | toQueryParam #
| Convert to URL path piece.
| Convert to a URL path piece, making sure to encode any special chars.
but this may be overriden with a more efficient version.
| Convert to HTTP header value.
| Convert to query param value.
| Convert to URL query param,
The default definition uses @'H.urlEncodeBuilder' 'True'@
but this may be overriden with a more efficient version.
| Parse value from HTTP API data.
instance will loop indefinitely.
| Parse URL path piece.
| Parse HTTP header value.
| Parse query param value.
| Convert multiple values to a list of URL pieces.
| Parse multiple URL pieces.
>>> parseUrlPieces ["true", "false"] :: Either Text [Bool]
Right [True,False]
Left "could not parse: `hello' (input does not start with a digit)"
| Convert multiple values to a list of query parameter values.
| Parse multiple query parameters.
Right [1,2,3]
>>> parseHeaderMaybe "hello" :: Maybe Text
Just "hello"
Just True
| Default parsing error.
| Convert @'Maybe'@ parser into @'Either' 'Text'@ parser with default error message.
| /Lower case/.
Convert to URL piece using @'TextShow'@ instance.
The result is always lower cased.
>>> showTextData True
"true"
This can be used as a default implementation for enumeration types:
@
showt = genericShowt
toUrlPiece = showTextData
@
| /Lower case/.
The result is always lower cased.
>>> showTextData True
"true"
This can be used as a default implementation for enumeration types:
>>> toUrlPiece Foo
"foo"
| /Case insensitive/.
Right 10
>>> parseUrlPieceWithPrefix "Left " "left" :: Either Text Bool
Left "could not parse: `left'"
This can be used to implement @'FromHttpApiData'@ for single field constructors:
>>> parseUrlPiece "foo 1" :: Either Text Foo
| Parse given bytestring then parse the rest of the input using @'parseHeader'@.
@
instance FromHttpApiData BasicAuthToken where
@
| /Case insensitive/.
>>> parseQueryParamWithPrefix "z" "z10" :: Either Text Int
Right 10
| /Case insensitive/.
>>> parseBoundedTextData "true" :: Either Text Bool
Right True
>>> parseBoundedTextData "FALSE" :: Either Text Bool
Right False
This can be used as a default implementation for enumeration types:
@
showt = genericShowt
parseUrlPiece = parseBoundedTextData
@
| /Case insensitive/.
>>> parseBoundedTextData "true" :: Either Text Bool
Right True
>>> parseBoundedTextData "FALSE" :: Either Text Bool
Right False
This can be used as a default implementation for enumeration types:
>>> parseUrlPiece "foo" :: Either Text MyData
Right Foo
| Lookup values based on a precalculated mapping of their representations.
>>> parseBoundedEnumOf toUrlPiece "true" :: Either Text Bool
Right True
For case insensitive parser see 'parseBoundedEnumOfI'.
| /Case insensitive/.
>>> parseBoundedEnumOfI toUrlPiece "FALSE" :: Either Text Bool
Right False
For case sensitive parser see 'parseBoundedEnumOf'.
| /Case insensitive/.
| /Case insensitive/.
Uses @'toQueryParam'@ to get possible values.
Uses @'toHeader'@ to get possible values.
Use for types which do not involve letters:
in presence of letters:
>>> readTextData (showTextData True) :: Either Text Bool
Left "could not parse: `true'"
See @'parseBoundedTextData'@.
| Run @'Reader'@ as HTTP API data parser.
| Run @'Reader'@ to parse bounded integral value with bounds checking.
| Convert to a URL-encoded path piece using 'toUrlPiece'.
This function can be used to override 'toEncodedUrlPiece' as a more efficient implementation
when the resulting URL piece /never/ has to be escaped.
| Convert to a URL-encoded query param using 'toQueryParam'.
|
>>> toUrlPiece ()
"_"
|
"1.2.3"
| Note: this instance is not polykinded
|
|
no toEncodedQueryParam as : is unsafe char.
|
no toEncodedQueryParam as : is unsafe char.
|
no toEncodedQueryParam as : is unsafe char.
|
no toEncodedQueryParam as : is unsafe char.
|
|
>>> toUrlPiece Q4
"q4"
|
>>> import Data.Time.Calendar.Quarter.Compat (Quarter (..))
|
|
>>> toUrlPiece (Just "Hello")
"just Hello"
|
>>> toUrlPiece (Left "err" :: Either String Int)
"left err"
| /Note:/ this instance works correctly for alphanumeric name and value
>>> let Right c = parseUrlPiece "SESSID=r2t5uvjq435r4q7ib3vtdjq120" :: Either Text SetCookie
>>> toUrlPiece c
"SESSID=r2t5uvjq435r4q7ib3vtdjq120"
>>> toHeader c
"SESSID=r2t5uvjq435r4q7ib3vtdjq120"
toEncodedUrlPiece = renderSetCookie -- doesn't do things.
| Note: this instance is not polykinded
| @since 0.4.2
| @since 0.4.2
|
>>> parseUrlPiece "_" :: Either Text ()
Right ()
|
>>> showVersion <$> parseUrlPiece "1.2.3"
Right "1.2.3"
| Note: this instance is not polykinded
|
|
Right 14:55:01.333
|
Right 2015-10-03 14:55:01
|
|
|
Right Monday
|
Right 2021-01
|
Right 2021-Q1
|
Right Q2
Right Q3
|
|
| Lenient parameters. 'FromHttpApiData' combinators always return `Right`.
| /Note:/ this instance works correctly for alphanumeric name and value
>>> parseUrlPiece "SESSID=r2t5uvjq435r4q7ib3vtdjq120" :: Either Text SetCookie
| Note: this instance is not polykinded
| @since 0.4.2
| @since 0.4.2
-----------------------------------------------------------------------------
----------------------------------------------------------------------------- | # LANGUAGE DeriveFunctor #
# LANGUAGE FlexibleInstances #
values to and from HTTP API data
module Web.Internal.HttpApiData where
import Prelude ()
import Prelude.Compat
import Control.Applicative (Const(Const))
import Control.Arrow (left, (&&&))
import Control.Monad ((<=<))
import qualified Data.Attoparsec.Text as Atto
import qualified Data.Attoparsec.Time as Atto
import Data.ByteString (ByteString)
import qualified Data.ByteString as BS
import qualified Data.ByteString.Builder as BS
import qualified Data.ByteString.Lazy as LBS
import Data.Coerce (coerce)
import Data.Data (Data)
import qualified Data.Fixed as F
import Data.Functor.Identity (Identity(Identity))
import Data.Int (Int16, Int32, Int64, Int8)
import Data.Kind (Type)
import qualified Data.Map as Map
import Data.Monoid (All (..), Any (..), Dual (..),
First (..), Last (..),
Product (..), Sum (..))
import Data.Semigroup (Semigroup (..))
import qualified Data.Semigroup as Semi
import Data.Tagged (Tagged (..))
import Data.Text (Text)
import qualified Data.Text as T
import Data.Text.Encoding (decodeUtf8', decodeUtf8With,
encodeUtf8)
import Data.Text.Encoding.Error (lenientDecode)
import qualified Data.Text.Lazy as L
import Data.Text.Read (Reader, decimal, rational,
signed)
import Data.Time.Compat (Day, FormatTime, LocalTime,
NominalDiffTime, TimeOfDay,
UTCTime, ZonedTime, formatTime,
DayOfWeek (..),
nominalDiffTimeToSeconds,
secondsToNominalDiffTime)
import Data.Time.Format.Compat (defaultTimeLocale,
iso8601DateFormat)
import Data.Time.Calendar.Month.Compat (Month)
import Data.Time.Calendar.Quarter.Compat (Quarter, QuarterOfYear (..),
toYearQuarter)
import Data.Typeable (Typeable)
import qualified Data.UUID.Types as UUID
import Data.Version (Version, parseVersion,
showVersion)
import Data.Void (Void, absurd)
import Data.Word (Word16, Word32, Word64, Word8)
import qualified Network.HTTP.Types as H
import Numeric.Natural (Natural)
import Text.ParserCombinators.ReadP (readP_to_S)
import Text.Read (readMaybe)
import Web.Cookie (SetCookie, parseSetCookie,
renderSetCookie)
#if USE_TEXT_SHOW
import TextShow (TextShow, showt)
#endif
> > > data = Text deriving ( Show )
> > > instance FromHttpApiData BasicAuthToken where parseHeader h = < $ > parseHeaderWithPrefix " Basic " h ; parseQueryParam p = < $ > parseQueryParam p
_ _ WARNING _ _ : Do not derive this using as the generated
class ToHttpApiData a where
toUrlPiece :: a -> Text
toUrlPiece = toQueryParam
The default definition uses @'H.urlEncodeBuilder ' ' False'@
toEncodedUrlPiece :: a -> BS.Builder
toEncodedUrlPiece = H.urlEncodeBuilder False . encodeUtf8 . toUrlPiece
toHeader :: a -> ByteString
toHeader = encodeUtf8 . toUrlPiece
toQueryParam :: a -> Text
toQueryParam = toUrlPiece
@since 0.5.1
toEncodedQueryParam :: a -> BS.Builder
toEncodedQueryParam = H.urlEncodeBuilder True . encodeUtf8 . toQueryParam
_ _ WARNING _ _ : Do not derive this using as the generated
class FromHttpApiData a where
# MINIMAL parseUrlPiece | parseQueryParam #
parseUrlPiece :: Text -> Either Text a
parseUrlPiece = parseQueryParam
parseHeader :: ByteString -> Either Text a
parseHeader = parseUrlPiece <=< (left (T.pack . show) . decodeUtf8')
parseQueryParam :: Text -> Either Text a
parseQueryParam = parseUrlPiece
> > > toUrlPieces [ 1 , 2 , 3 ] : : [ Text ]
[ " 1","2","3 " ]
toUrlPieces :: (Functor t, ToHttpApiData a) => t a -> t Text
toUrlPieces = fmap toUrlPiece
> > > parseUrlPieces [ " 123 " , " hello " , " world " ] : : Either Text [ Int ]
parseUrlPieces :: (Traversable t, FromHttpApiData a) => t Text -> Either Text (t a)
parseUrlPieces = traverse parseUrlPiece
> > > toQueryParams [ fromGregorian 2015 10 03 , fromGregorian 2015 12 01 ] : : [ Text ]
[ " 2015 - 10 - 03","2015 - 12 - 01 " ]
toQueryParams :: (Functor t, ToHttpApiData a) => t a -> t Text
toQueryParams = fmap toQueryParam
> > > parseQueryParams [ " 1 " , " 2 " , " 3 " ] : : Either Text [ Int ]
> > > parseQueryParams [ " 64 " , " 128 " , " 256 " ] : : Either Text [ Word8 ]
Left " out of bounds : ` 256 ' ( should be between 0 and 255 ) "
parseQueryParams :: (Traversable t, FromHttpApiData a) => t Text -> Either Text (t a)
parseQueryParams = traverse parseQueryParam
| Parse URL path piece in a @'Maybe'@.
> > > parseUrlPieceMaybe " 12 " : : Maybe Int
Just 12
parseUrlPieceMaybe :: FromHttpApiData a => Text -> Maybe a
parseUrlPieceMaybe = either (const Nothing) Just . parseUrlPiece
| Parse HTTP header value in a @'Maybe'@.
parseHeaderMaybe :: FromHttpApiData a => ByteString -> Maybe a
parseHeaderMaybe = either (const Nothing) Just . parseHeader
| Parse query param value in a @'Maybe'@.
> > > parseQueryParamMaybe " true " : : Maybe
parseQueryParamMaybe :: FromHttpApiData a => Text -> Maybe a
parseQueryParamMaybe = either (const Nothing) Just . parseQueryParam
defaultParseError :: Text -> Either Text a
defaultParseError input = Left ("could not parse: `" <> input <> "'")
parseMaybeTextData :: (Text -> Maybe a) -> (Text -> Either Text a)
parseMaybeTextData parse input =
case parse input of
Nothing -> defaultParseError input
Just val -> Right val
#if USE_TEXT_SHOW
data MyData = Foo | Bar | Baz deriving ( Generic )
instance where
instance ToHttpApiData MyData where
showTextData :: TextShow a => a -> Text
showTextData = T.toLower . showt
#else
Convert to URL piece using @'Show'@ instance .
> > > data MyData = Foo | Bar | Baz deriving ( Show )
> > > instance ToHttpApiData MyData where toUrlPiece = showTextData
showTextData :: Show a => a -> Text
showTextData = T.toLower . showt
| Like @'show'@ , but returns @'Text'@.
showt :: Show a => a -> Text
showt = T.pack . show
#endif
Parse given text case insensitive and then parse the rest of the input
using @'parseUrlPiece'@.
> > > " Just " " just 10 " : : Either Text Int
> > > data deriving ( Show )
> > > instance FromHttpApiData Foo where parseUrlPiece s = Foo < $ > parseUrlPieceWithPrefix " Foo " s
Right ( Foo 1 )
parseUrlPieceWithPrefix :: FromHttpApiData a => Text -> Text -> Either Text a
parseUrlPieceWithPrefix pattern input
| T.toLower pattern == T.toLower prefix = parseUrlPiece rest
| otherwise = defaultParseError input
where
(prefix, rest) = T.splitAt (T.length pattern) input
data = Text deriving ( Show )
h = \<$\ > parseHeaderWithPrefix " Basic " h
parseQueryParam p = \<$\ > parseQueryParam p
> > > parseHeader " Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ== " : : Either Text
Right ( " QWxhZGRpbjpvcGVuIHNlc2FtZQ== " )
parseHeaderWithPrefix :: FromHttpApiData a => ByteString -> ByteString -> Either Text a
parseHeaderWithPrefix pattern input
| pattern `BS.isPrefixOf` input = parseHeader (BS.drop (BS.length pattern) input)
| otherwise = defaultParseError (showt input)
Parse given text case insensitive and then parse the rest of the input
using @'parseQueryParam'@.
parseQueryParamWithPrefix :: FromHttpApiData a => Text -> Text -> Either Text a
parseQueryParamWithPrefix pattern input
| T.toLower pattern == T.toLower prefix = parseQueryParam rest
| otherwise = defaultParseError input
where
(prefix, rest) = T.splitAt (T.length pattern) input
#if USE_TEXT_SHOW
Parse values case insensitively based on @'TextShow'@ instance .
data MyData = Foo | Bar | Baz deriving ( Show , Bounded , , Generic )
instance where
instance FromHttpApiData MyData where
parseBoundedTextData :: (TextShow a, Bounded a, Enum a) => Text -> Either Text a
#else
Parse values case insensitively based on @'Show'@ instance .
> > > data MyData = Foo | Bar | Baz deriving ( Show , Bounded , )
> > > instance FromHttpApiData MyData where parseUrlPiece = parseBoundedTextData
parseBoundedTextData :: (Show a, Bounded a, Enum a) => Text -> Either Text a
#endif
parseBoundedTextData = parseBoundedEnumOfI showTextData
lookupBoundedEnumOf :: (Bounded a, Enum a, Eq b) => (a -> b) -> b -> Maybe a
lookupBoundedEnumOf f = flip lookup (map (f &&& id) [minBound..maxBound])
| Parse values based on a precalculated mapping of their @'Text'@ representation .
parseBoundedEnumOf :: (Bounded a, Enum a) => (a -> Text) -> Text -> Either Text a
parseBoundedEnumOf = parseMaybeTextData . lookupBoundedEnumOf
Parse values case insensitively based on a precalculated mapping
of their @'Text'@ representations .
parseBoundedEnumOfI :: (Bounded a, Enum a) => (a -> Text) -> Text -> Either Text a
parseBoundedEnumOfI f = parseBoundedEnumOf (T.toLower . f) . T.toLower
Parse values case insensitively based on @'ToHttpApiData'@ instance .
Uses @'toUrlPiece'@ to get possible values .
parseBoundedUrlPiece :: (ToHttpApiData a, Bounded a, Enum a) => Text -> Either Text a
parseBoundedUrlPiece = parseBoundedEnumOfI toUrlPiece
Parse values case insensitively based on @'ToHttpApiData'@ instance .
parseBoundedQueryParam :: (ToHttpApiData a, Bounded a, Enum a) => Text -> Either Text a
parseBoundedQueryParam = parseBoundedEnumOfI toQueryParam
| Parse values based on @'ToHttpApiData'@ instance .
parseBoundedHeader :: (ToHttpApiData a, Bounded a, Enum a) => ByteString -> Either Text a
parseBoundedHeader bs = case lookupBoundedEnumOf toHeader bs of
Nothing -> defaultParseError $ T.pack $ show bs
Just x -> return x
| Parse URL piece using instance .
> > > readTextData " 1991 - 06 - 02 " : : Either Text Day
Right 1991 - 06 - 02
This parser is case sensitive and will not match @'showTextData'@
readTextData :: Read a => Text -> Either Text a
readTextData = parseMaybeTextData (readMaybe . T.unpack)
runReader :: Reader a -> Text -> Either Text a
runReader reader input =
case reader input of
Left err -> Left ("could not parse: `" <> input <> "' (" <> T.pack err <> ")")
Right (x, rest)
| T.null rest -> Right x
| otherwise -> defaultParseError input
> > > parseBounded decimal " 256 " : : Either Text Word8
Left " out of bounds : ` 256 ' ( should be between 0 and 255 ) "
parseBounded :: forall a. (Bounded a, Integral a) => Reader Integer -> Text -> Either Text a
parseBounded reader input = do
n <- runReader reader input
if (n > h || n < l)
then Left ("out of bounds: `" <> input <> "' (should be between " <> showt l <> " and " <> showt h <> ")")
else Right (fromInteger n)
where
l = toInteger (minBound :: a)
h = toInteger (maxBound :: a)
/Note/ : this function does not check if the result contains unescaped characters !
unsafeToEncodedUrlPiece :: ToHttpApiData a => a -> BS.Builder
unsafeToEncodedUrlPiece = BS.byteString . encodeUtf8 . toUrlPiece
/Note/ : this function does not check if the result contains unescaped characters !
@since 0.5.1
unsafeToEncodedQueryParam :: ToHttpApiData a => a -> BS.Builder
unsafeToEncodedQueryParam = BS.byteString . encodeUtf8 . toQueryParam
instance ToHttpApiData () where
toUrlPiece _ = "_"
toHeader _ = "_"
toEncodedUrlPiece _ = "_"
toEncodedQueryParam _ = "_"
instance ToHttpApiData Char where
toUrlPiece = T.singleton
> > > toUrlPiece ( Version [ 1 , 2 , 3 ] [ ] )
instance ToHttpApiData Version where
toUrlPiece = T.pack . showVersion
toEncodedUrlPiece = unsafeToEncodedUrlPiece
toEncodedQueryParam = unsafeToEncodedQueryParam
instance ToHttpApiData Void where toUrlPiece = absurd
instance ToHttpApiData Natural where toUrlPiece = showt; toEncodedUrlPiece = unsafeToEncodedUrlPiece; toEncodedQueryParam = unsafeToEncodedQueryParam
instance ToHttpApiData Bool where toUrlPiece = showTextData; toEncodedUrlPiece = unsafeToEncodedUrlPiece; toEncodedQueryParam = unsafeToEncodedQueryParam
instance ToHttpApiData Ordering where toUrlPiece = showTextData; toEncodedUrlPiece = unsafeToEncodedUrlPiece; toEncodedQueryParam = unsafeToEncodedQueryParam
instance ToHttpApiData Double where toUrlPiece = showt; toEncodedUrlPiece = unsafeToEncodedUrlPiece; toEncodedQueryParam = unsafeToEncodedQueryParam
instance ToHttpApiData Float where toUrlPiece = showt; toEncodedUrlPiece = unsafeToEncodedUrlPiece; toEncodedQueryParam = unsafeToEncodedQueryParam
instance ToHttpApiData Int where toUrlPiece = showt; toEncodedUrlPiece = unsafeToEncodedUrlPiece; toEncodedQueryParam = unsafeToEncodedQueryParam
instance ToHttpApiData Int8 where toUrlPiece = showt; toEncodedUrlPiece = unsafeToEncodedUrlPiece; toEncodedQueryParam = unsafeToEncodedQueryParam
instance ToHttpApiData Int16 where toUrlPiece = showt; toEncodedUrlPiece = unsafeToEncodedUrlPiece; toEncodedQueryParam = unsafeToEncodedQueryParam
instance ToHttpApiData Int32 where toUrlPiece = showt; toEncodedUrlPiece = unsafeToEncodedUrlPiece; toEncodedQueryParam = unsafeToEncodedQueryParam
instance ToHttpApiData Int64 where toUrlPiece = showt; toEncodedUrlPiece = unsafeToEncodedUrlPiece; toEncodedQueryParam = unsafeToEncodedQueryParam
instance ToHttpApiData Integer where toUrlPiece = showt; toEncodedUrlPiece = unsafeToEncodedUrlPiece; toEncodedQueryParam = unsafeToEncodedQueryParam
instance ToHttpApiData Word where toUrlPiece = showt; toEncodedUrlPiece = unsafeToEncodedUrlPiece; toEncodedQueryParam = unsafeToEncodedQueryParam
instance ToHttpApiData Word8 where toUrlPiece = showt; toEncodedUrlPiece = unsafeToEncodedUrlPiece; toEncodedQueryParam = unsafeToEncodedQueryParam
instance ToHttpApiData Word16 where toUrlPiece = showt; toEncodedUrlPiece = unsafeToEncodedUrlPiece; toEncodedQueryParam = unsafeToEncodedQueryParam
instance ToHttpApiData Word32 where toUrlPiece = showt; toEncodedUrlPiece = unsafeToEncodedUrlPiece; toEncodedQueryParam = unsafeToEncodedQueryParam
instance ToHttpApiData Word64 where toUrlPiece = showt; toEncodedUrlPiece = unsafeToEncodedUrlPiece; toEncodedQueryParam = unsafeToEncodedQueryParam
instance F.HasResolution a => ToHttpApiData (F.Fixed (a :: Type)) where toUrlPiece = showt; toEncodedUrlPiece = unsafeToEncodedUrlPiece; toEncodedQueryParam = unsafeToEncodedQueryParam
> > > toUrlPiece ( fromGregorian 2015 10 03 )
" 2015 - 10 - 03 "
instance ToHttpApiData Day where
toUrlPiece = T.pack . show
toEncodedUrlPiece = unsafeToEncodedUrlPiece
toEncodedQueryParam = unsafeToEncodedQueryParam
timeToUrlPiece :: FormatTime t => String -> t -> Text
timeToUrlPiece fmt = T.pack . formatTime defaultTimeLocale (iso8601DateFormat (Just fmt))
> > > toUrlPiece $ TimeOfDay 14 55 23.1
" 14:55:23.1 "
instance ToHttpApiData TimeOfDay where
toUrlPiece = T.pack . formatTime defaultTimeLocale "%H:%M:%S%Q"
toEncodedUrlPiece = unsafeToEncodedUrlPiece
> > > toUrlPiece $ LocalTime ( fromGregorian 2015 10 03 ) ( TimeOfDay 14 55 21.687 )
" 2015 - 10 - 03T14:55:21.687 "
instance ToHttpApiData LocalTime where
toUrlPiece = timeToUrlPiece "%H:%M:%S%Q"
toEncodedUrlPiece = unsafeToEncodedUrlPiece
> > > toUrlPiece $ ZonedTime ( LocalTime ( fromGregorian 2015 10 03 ) ( TimeOfDay 14 55 51.001 ) ) utc
" 2015 - 10 - 03T14:55:51.001 + 0000 "
instance ToHttpApiData ZonedTime where
toUrlPiece = timeToUrlPiece "%H:%M:%S%Q%z"
toEncodedUrlPiece = unsafeToEncodedUrlPiece
> > > toUrlPiece $ UTCTime ( fromGregorian 2015 10 03 ) 864.5
" 2015 - 10 - 03T00:14:24.5Z "
instance ToHttpApiData UTCTime where
toUrlPiece = timeToUrlPiece "%H:%M:%S%QZ"
toEncodedUrlPiece = unsafeToEncodedUrlPiece
> > > toUrlPiece Monday
" monday "
instance ToHttpApiData DayOfWeek where
toUrlPiece Monday = "monday"
toUrlPiece Tuesday = "tuesday"
toUrlPiece Wednesday = "wednesday"
toUrlPiece Thursday = "thursday"
toUrlPiece Friday = "friday"
toUrlPiece Saturday = "saturday"
toUrlPiece Sunday = "sunday"
toEncodedUrlPiece = unsafeToEncodedUrlPiece
toEncodedQueryParam = unsafeToEncodedQueryParam
instance ToHttpApiData QuarterOfYear where
toUrlPiece Q1 = "q1"
toUrlPiece Q2 = "q2"
toUrlPiece Q3 = "q3"
toUrlPiece Q4 = "q4"
toEncodedUrlPiece = unsafeToEncodedUrlPiece
toEncodedQueryParam = unsafeToEncodedQueryParam
> > >
2010 - Q1
> > > toUrlPiece $
" 2010 - q1 "
instance ToHttpApiData Quarter where
toUrlPiece q = case toYearQuarter q of
(y, qoy) -> T.pack (show y ++ "-" ++ f qoy)
where
f Q1 = "q1"
f Q2 = "q2"
f Q3 = "q3"
f Q4 = "q4"
toEncodedUrlPiece = unsafeToEncodedUrlPiece
toEncodedQueryParam = unsafeToEncodedQueryParam
> > > import Data . Time . Calendar . Month . Compat ( Month ( .. ) )
> > > MkMonth 24482
2040 - 03
> > > toUrlPiece $ MkMonth 24482
" 2040 - 03 "
instance ToHttpApiData Month where
toUrlPiece = T.pack . formatTime defaultTimeLocale "%Y-%m"
toEncodedUrlPiece = unsafeToEncodedUrlPiece
toEncodedQueryParam = unsafeToEncodedQueryParam
instance ToHttpApiData NominalDiffTime where
toUrlPiece = toUrlPiece . nominalDiffTimeToSeconds
toEncodedQueryParam = unsafeToEncodedQueryParam
toEncodedUrlPiece = unsafeToEncodedUrlPiece
instance ToHttpApiData String where toUrlPiece = T.pack
instance ToHttpApiData Text where toUrlPiece = id
instance ToHttpApiData L.Text where toUrlPiece = L.toStrict
instance ToHttpApiData All where
toUrlPiece = coerce (toUrlPiece :: Bool -> Text)
toEncodedUrlPiece = coerce (toEncodedUrlPiece :: Bool -> BS.Builder)
toEncodedQueryParam = coerce (toEncodedQueryParam :: Bool -> BS.Builder)
instance ToHttpApiData Any where
toUrlPiece = coerce (toUrlPiece :: Bool -> Text)
toEncodedUrlPiece = coerce (toEncodedUrlPiece :: Bool -> BS.Builder)
toEncodedQueryParam = coerce (toEncodedQueryParam :: Bool -> BS.Builder)
instance ToHttpApiData a => ToHttpApiData (Dual a) where
toUrlPiece = coerce (toUrlPiece :: a -> Text)
toEncodedUrlPiece = coerce (toEncodedUrlPiece :: a -> BS.Builder)
toEncodedQueryParam = coerce (toEncodedQueryParam :: a -> BS.Builder)
instance ToHttpApiData a => ToHttpApiData (Sum a) where
toUrlPiece = coerce (toUrlPiece :: a -> Text)
toEncodedUrlPiece = coerce (toEncodedUrlPiece :: a -> BS.Builder)
toEncodedQueryParam = coerce (toEncodedQueryParam :: a -> BS.Builder)
instance ToHttpApiData a => ToHttpApiData (Product a) where
toUrlPiece = coerce (toUrlPiece :: a -> Text)
toEncodedUrlPiece = coerce (toEncodedUrlPiece :: a -> BS.Builder)
toEncodedQueryParam = coerce (toEncodedQueryParam :: a -> BS.Builder)
instance ToHttpApiData a => ToHttpApiData (First a) where
toUrlPiece = coerce (toUrlPiece :: Maybe a -> Text)
toEncodedUrlPiece = coerce (toEncodedUrlPiece :: Maybe a -> BS.Builder)
toEncodedQueryParam = coerce (toEncodedQueryParam :: Maybe a -> BS.Builder)
instance ToHttpApiData a => ToHttpApiData (Last a) where
toUrlPiece = coerce (toUrlPiece :: Maybe a -> Text)
toEncodedUrlPiece = coerce (toEncodedUrlPiece :: Maybe a -> BS.Builder)
toEncodedQueryParam = coerce (toEncodedQueryParam :: Maybe a -> BS.Builder)
instance ToHttpApiData a => ToHttpApiData (Semi.Min a) where
toUrlPiece = coerce (toUrlPiece :: a -> Text)
toEncodedUrlPiece = coerce (toEncodedUrlPiece :: a -> BS.Builder)
toEncodedQueryParam = coerce (toEncodedQueryParam :: a -> BS.Builder)
instance ToHttpApiData a => ToHttpApiData (Semi.Max a) where
toUrlPiece = coerce (toUrlPiece :: a -> Text)
toEncodedUrlPiece = coerce (toEncodedUrlPiece :: a -> BS.Builder)
toEncodedQueryParam = coerce (toEncodedQueryParam :: a -> BS.Builder)
instance ToHttpApiData a => ToHttpApiData (Semi.First a) where
toUrlPiece = coerce (toUrlPiece :: a -> Text)
toEncodedUrlPiece = coerce (toEncodedUrlPiece :: a -> BS.Builder)
toEncodedQueryParam = coerce (toEncodedQueryParam :: a -> BS.Builder)
instance ToHttpApiData a => ToHttpApiData (Semi.Last a) where
toUrlPiece = coerce (toUrlPiece :: a -> Text)
toEncodedUrlPiece = coerce (toEncodedUrlPiece :: a -> BS.Builder)
toEncodedQueryParam = coerce (toEncodedQueryParam :: a -> BS.Builder)
instance ToHttpApiData a => ToHttpApiData (Maybe a) where
toUrlPiece (Just x) = "just " <> toUrlPiece x
toUrlPiece Nothing = "nothing"
> > > toUrlPiece ( Right 3 : : Either String Int )
" right 3 "
instance (ToHttpApiData a, ToHttpApiData b) => ToHttpApiData (Either a b) where
toUrlPiece (Left x) = "left " <> toUrlPiece x
toUrlPiece (Right x) = "right " <> toUrlPiece x
instance ToHttpApiData SetCookie where
toUrlPiece = decodeUtf8With lenientDecode . toHeader
toHeader = LBS.toStrict . BS.toLazyByteString . renderSetCookie
instance ToHttpApiData a => ToHttpApiData (Tagged (b :: Type) a) where
toUrlPiece = coerce (toUrlPiece :: a -> Text)
toHeader = coerce (toHeader :: a -> ByteString)
toQueryParam = coerce (toQueryParam :: a -> Text)
toEncodedUrlPiece = coerce (toEncodedUrlPiece :: a -> BS.Builder)
toEncodedQueryParam = coerce (toEncodedQueryParam :: a -> BS.Builder)
instance ToHttpApiData a => ToHttpApiData (Const a b) where
toUrlPiece = coerce (toUrlPiece :: a -> Text)
toHeader = coerce (toHeader :: a -> ByteString)
toQueryParam = coerce (toQueryParam :: a -> Text)
toEncodedUrlPiece = coerce (toEncodedUrlPiece :: a -> BS.Builder)
toEncodedQueryParam = coerce (toEncodedQueryParam :: a -> BS.Builder)
instance ToHttpApiData a => ToHttpApiData (Identity a) where
toUrlPiece = coerce (toUrlPiece :: a -> Text)
toHeader = coerce (toHeader :: a -> ByteString)
toQueryParam = coerce (toQueryParam :: a -> Text)
toEncodedUrlPiece = coerce (toEncodedUrlPiece :: a -> BS.Builder)
toEncodedQueryParam = coerce (toEncodedQueryParam :: a -> BS.Builder)
instance FromHttpApiData () where
parseUrlPiece "_" = pure ()
parseUrlPiece s = defaultParseError s
instance FromHttpApiData Char where
parseUrlPiece s =
case T.uncons s of
Just (c, s') | T.null s' -> pure c
_ -> defaultParseError s
instance FromHttpApiData Version where
parseUrlPiece s =
case reverse (readP_to_S parseVersion (T.unpack s)) of
((x, ""):_) -> pure x
_ -> defaultParseError s
| Parsing a value is always an error , considering as a data type with no constructors .
instance FromHttpApiData Void where
parseUrlPiece _ = Left "Void cannot be parsed!"
instance FromHttpApiData Natural where
parseUrlPiece s = do
n <- runReader (signed decimal) s
if n < 0
then Left ("underflow: " <> s <> " (should be a non-negative integer)")
else Right (fromInteger n)
instance FromHttpApiData Bool where parseUrlPiece = parseBoundedUrlPiece
instance FromHttpApiData Ordering where parseUrlPiece = parseBoundedUrlPiece
instance FromHttpApiData Double where parseUrlPiece = runReader rational
instance FromHttpApiData Float where parseUrlPiece = runReader rational
instance FromHttpApiData Int where parseUrlPiece = parseBounded (signed decimal)
instance FromHttpApiData Int8 where parseUrlPiece = parseBounded (signed decimal)
instance FromHttpApiData Int16 where parseUrlPiece = parseBounded (signed decimal)
instance FromHttpApiData Int32 where parseUrlPiece = parseBounded (signed decimal)
instance FromHttpApiData Int64 where parseUrlPiece = parseBounded (signed decimal)
instance FromHttpApiData Integer where parseUrlPiece = runReader (signed decimal)
instance FromHttpApiData Word where parseUrlPiece = parseBounded decimal
instance FromHttpApiData Word8 where parseUrlPiece = parseBounded decimal
instance FromHttpApiData Word16 where parseUrlPiece = parseBounded decimal
instance FromHttpApiData Word32 where parseUrlPiece = parseBounded decimal
instance FromHttpApiData Word64 where parseUrlPiece = parseBounded decimal
instance FromHttpApiData String where parseUrlPiece = Right . T.unpack
instance FromHttpApiData Text where parseUrlPiece = Right
instance FromHttpApiData L.Text where parseUrlPiece = Right . L.fromStrict
instance F.HasResolution a => FromHttpApiData (F.Fixed (a :: Type)) where
parseUrlPiece = runReader rational
> > > toGregorian < $ > parseUrlPiece " 2016 - 12 - 01 "
Right ( 2016,12,1 )
instance FromHttpApiData Day where parseUrlPiece = runAtto Atto.day
> > > parseUrlPiece " 14:55:01.333 " : : Either Text
instance FromHttpApiData TimeOfDay where parseUrlPiece = runAtto Atto.timeOfDay
> > > parseUrlPiece " 2015 - 10 - 03T14:55:01 " : : Either Text LocalTime
instance FromHttpApiData LocalTime where parseUrlPiece = runAtto Atto.localTime
> > > parseUrlPiece " 2015 - 10 - 03T14:55:01 + 0000 " : : Either Text ZonedTime
Right 2015 - 10 - 03 14:55:01 +0000
> > > parseQueryParam " 2016 - 12 - 31T01:00:00Z " : : Either Text ZonedTime
Right 2016 - 12 - 31 01:00:00 +0000
instance FromHttpApiData ZonedTime where parseUrlPiece = runAtto Atto.zonedTime
> > > parseUrlPiece " 2015 - 10 - 03T00:14:24Z " : : Either Text UTCTime
Right 2015 - 10 - 03 00:14:24 UTC
instance FromHttpApiData UTCTime where parseUrlPiece = runAtto Atto.utcTime
> > > parseUrlPiece " Monday " : : Either Text
instance FromHttpApiData DayOfWeek where
parseUrlPiece t = case Map.lookup (T.toLower t) m of
Just dow -> Right dow
Nothing -> Left $ "Incorrect DayOfWeek: " <> T.take 10 t
where
m :: Map.Map Text DayOfWeek
m = Map.fromList [ (toUrlPiece dow, dow) | dow <- [Monday .. Sunday] ]
instance FromHttpApiData NominalDiffTime where parseUrlPiece = fmap secondsToNominalDiffTime . parseUrlPiece
> > > parseUrlPiece " 2021 - 01 " : : Either Text Month
instance FromHttpApiData Month where parseUrlPiece = runAtto Atto.month
> > > parseUrlPiece " 2021 - q1 " : : Either Text Quarter
instance FromHttpApiData Quarter where parseUrlPiece = runAtto Atto.quarter
> > > parseUrlPiece " q2 " : : Either Text QuarterOfYear
> > > parseUrlPiece " Q3 " : : Either Text QuarterOfYear
instance FromHttpApiData QuarterOfYear where
parseUrlPiece t = case T.toLower t of
"q1" -> return Q1
"q2" -> return Q2
"q3" -> return Q3
"q4" -> return Q4
_ -> Left "Invalid quarter of year"
instance FromHttpApiData All where parseUrlPiece = coerce (parseUrlPiece :: Text -> Either Text Bool)
instance FromHttpApiData Any where parseUrlPiece = coerce (parseUrlPiece :: Text -> Either Text Bool)
instance FromHttpApiData a => FromHttpApiData (Dual a) where parseUrlPiece = coerce (parseUrlPiece :: Text -> Either Text a)
instance FromHttpApiData a => FromHttpApiData (Sum a) where parseUrlPiece = coerce (parseUrlPiece :: Text -> Either Text a)
instance FromHttpApiData a => FromHttpApiData (Product a) where parseUrlPiece = coerce (parseUrlPiece :: Text -> Either Text a)
instance FromHttpApiData a => FromHttpApiData (First a) where parseUrlPiece = coerce (parseUrlPiece :: Text -> Either Text (Maybe a))
instance FromHttpApiData a => FromHttpApiData (Last a) where parseUrlPiece = coerce (parseUrlPiece :: Text -> Either Text (Maybe a))
instance FromHttpApiData a => FromHttpApiData (Semi.Min a) where parseUrlPiece = coerce (parseUrlPiece :: Text -> Either Text a)
instance FromHttpApiData a => FromHttpApiData (Semi.Max a) where parseUrlPiece = coerce (parseUrlPiece :: Text -> Either Text a)
instance FromHttpApiData a => FromHttpApiData (Semi.First a) where parseUrlPiece = coerce (parseUrlPiece :: Text -> Either Text a)
instance FromHttpApiData a => FromHttpApiData (Semi.Last a) where parseUrlPiece = coerce (parseUrlPiece :: Text -> Either Text a)
> > > parseUrlPiece " Just 123 " : : Either Text ( Maybe Int )
Right ( Just 123 )
instance FromHttpApiData a => FromHttpApiData (Maybe a) where
parseUrlPiece s
| T.toLower (T.take 7 s) == "nothing" = pure Nothing
| otherwise = Just <$> parseUrlPieceWithPrefix "Just " s
> > > parseUrlPiece " Right 123 " : : Either Text ( Either String Int )
Right ( Right 123 )
instance (FromHttpApiData a, FromHttpApiData b) => FromHttpApiData (Either a b) where
parseUrlPiece s =
Right <$> parseUrlPieceWithPrefix "Right " s
<!> Left <$> parseUrlPieceWithPrefix "Left " s
where
infixl 3 <!>
Left _ <!> y = y
x <!> _ = x
instance ToHttpApiData UUID.UUID where
toUrlPiece = UUID.toText
toHeader = UUID.toASCIIBytes
toEncodedUrlPiece = unsafeToEncodedUrlPiece
instance FromHttpApiData UUID.UUID where
parseUrlPiece = maybe (Left "invalid UUID") Right . UUID.fromText
parseHeader = maybe (Left "invalid UUID") Right . UUID.fromASCIIBytes
@since 0.3.5
newtype LenientData a = LenientData { getLenientData :: Either Text a }
deriving (Eq, Ord, Show, Read, Typeable, Data, Functor, Foldable, Traversable)
instance FromHttpApiData a => FromHttpApiData (LenientData a) where
parseUrlPiece = Right . LenientData . parseUrlPiece
parseHeader = Right . LenientData . parseHeader
parseQueryParam = Right . LenientData . parseQueryParam
Right ( SetCookie { setCookieName = " SESSID " , setCookieValue = " r2t5uvjq435r4q7ib3vtdjq120 " , setCookiePath = Nothing , setCookieExpires = Nothing , setCookieMaxAge = Nothing , setCookieDomain = Nothing , setCookieHttpOnly = False , setCookieSecure = False , setCookieSameSite = Nothing } )
instance FromHttpApiData SetCookie where
parseUrlPiece = parseHeader . encodeUtf8
parseHeader = Right . parseSetCookie
instance FromHttpApiData a => FromHttpApiData (Tagged (b :: Type) a) where
parseUrlPiece = coerce (parseUrlPiece :: Text -> Either Text a)
parseHeader = coerce (parseHeader :: ByteString -> Either Text a)
parseQueryParam = coerce (parseQueryParam :: Text -> Either Text a)
instance FromHttpApiData a => FromHttpApiData (Const a b) where
parseUrlPiece = coerce (parseUrlPiece :: Text -> Either Text a)
parseHeader = coerce (parseHeader :: ByteString -> Either Text a)
parseQueryParam = coerce (parseQueryParam :: Text -> Either Text a)
instance FromHttpApiData a => FromHttpApiData (Identity a) where
parseUrlPiece = coerce (parseUrlPiece :: Text -> Either Text a)
parseHeader = coerce (parseHeader :: ByteString -> Either Text a)
parseQueryParam = coerce (parseQueryParam :: Text -> Either Text a)
Attoparsec helpers
runAtto :: Atto.Parser a -> Text -> Either Text a
runAtto p t = case Atto.parseOnly (p <* Atto.endOfInput) t of
Left err -> Left (T.pack err)
Right x -> Right x
|
eccd4fe062b89413f3e310280af81718a75b2db1b0ce9a1a5dfed27d2213b1d8 | bevuta/pox | smtp.scm | (module pox-mail/smtp
(smtp-config smtp-send)
(import chicken scheme)
(use hato-smtp pox-log)
(define-logger log mail smtp)
(define smtp-config (make-parameter '()))
(define (smtp-send . args)
(log (debug) (cons 'mail args))
(let ((failures (apply send-mail (append (smtp-config) args))))
(or (null? failures)
(log (critical)
'(message . "could not send mail")
(cons 'failures failures)))))
) | null | https://raw.githubusercontent.com/bevuta/pox/9684d4037573b6c55acf24867c1d50aa8f4ea57e/pox-mail/smtp.scm | scheme | (module pox-mail/smtp
(smtp-config smtp-send)
(import chicken scheme)
(use hato-smtp pox-log)
(define-logger log mail smtp)
(define smtp-config (make-parameter '()))
(define (smtp-send . args)
(log (debug) (cons 'mail args))
(let ((failures (apply send-mail (append (smtp-config) args))))
(or (null? failures)
(log (critical)
'(message . "could not send mail")
(cons 'failures failures)))))
) | |
d42cca8bbd1c9d12df0a68c3b84ad877f0113edebcf26820bc8795f0addbafb9 | GaloisInc/msf-haskell | Module.hs | -- |Interact with exploits, payloads, encoders, etc. Functionality for
-- executing a module with a particular payload is here.
module MSF.Module
( module Types.Module
, module_exploits
, module_auxiliary
, module_post
, module_payloads
, module_encoders
, module_nops
, module_info
, module_options
, module_compatible_payloads
, module_target_compatible_payloads
, module_compatible_sessions
, module_encode
, module_execute_payload
, module_execute
) where
import MSF.Monad
import Types.Module
import qualified RPC.Module as RPC
-- | List modules installed on server. Silent operation.
module_exploits :: (SilentCxt s) => MSF s Modules
module_exploits = prim RPC.module_exploits
-- | List aux modules installed on server. Silent operation.
module_auxiliary :: (SilentCxt s) => MSF s Modules
module_auxiliary = prim RPC.module_auxiliary
-- | List of post modules. Silent operation.
module_post :: (SilentCxt s) => MSF s Modules
module_post = prim RPC.module_post
-- |List of payload modules. Silent operation.
module_payloads :: (SilentCxt s) => MSF s Modules
module_payloads = prim RPC.module_payloads
-- |List of encoder modules. Silent operation.
module_encoders :: (SilentCxt s) => MSF s Modules
module_encoders = prim RPC.module_encoders
|List of nop modules . Silent operation .
module_nops :: (SilentCxt s) => MSF s Modules
module_nops = prim RPC.module_nops
-- | XXX results not parsed. Are only the keys listed in documentation possible here? Silent operation.
module_info :: (SilentCxt s) => ModuleType -> ModuleName -> MSF s ModuleInfo
module_info modTyp modNm = prim $ \ addr auth ->
RPC.module_info addr auth modTyp modNm
-- XXX results are parsed, but parsing needs testing. Silent operation.
module_options :: (SilentCxt s) => ModuleType -> ModuleName -> MSF s ModuleOptions
module_options modTyp modNm = prim $ \ addr auth ->
RPC.module_options addr auth modTyp modNm
-- |Payloads that are compatible with the given exploit. Silent operation.
module_compatible_payloads :: (SilentCxt s) => ModuleName -> MSF s Payloads
module_compatible_payloads modNm = prim $ \ addr auth ->
RPC.module_compatible_payloads addr auth modNm
-- |Probably a silent operation, but not clear how it determines compatibility.
module_target_compatible_payloads :: (SilentCxt s) => ModuleName -> Int -> MSF s Payloads
module_target_compatible_payloads modNm targetIndex = prim $ \ addr auth ->
RPC.module_target_compatible_payloads addr auth modNm targetIndex
-- |Probably silent, but not clear how it determines compatibility.
module_compatible_sessions :: (SilentCxt s) => ModuleName -> MSF s Sessions
module_compatible_sessions modNm = prim $ \ addr auth ->
RPC.module_compatible_sessions addr auth modNm
-- |Silent operation.
module_encode :: (SilentCxt s) => Payload -> ModuleName -> EncodeOptions -> MSF s ModuleEncode
module_encode pl encoderModule opts = prim $ \ addr auth ->
RPC.module_encode addr auth pl encoderModule opts
|Execute a payload type module . This is silent since it just returns a payload from MSF . Return value should be ExecPayload .
module_execute_payload :: (SilentCxt s) => Payload -> ExecuteOptions -> MSF s ExecResult
module_execute_payload (Payload pl) opts =
loud $ module_execute PayloadModuleType (ModuleName pl) opts
-- |Most generic execution of module. Potentially silent and potentially loud.
module_execute :: (LoudCxt s) => ModuleType -> ModuleName -> ExecuteOptions -> MSF s ExecResult
module_execute modTyp modNm opts = prim $ \ addr auth ->
RPC.module_execute addr auth modTyp modNm opts
| null | https://raw.githubusercontent.com/GaloisInc/msf-haskell/76cee10771f9e9d10aa3301198e09f08bde907be/src/MSF/Module.hs | haskell | |Interact with exploits, payloads, encoders, etc. Functionality for
executing a module with a particular payload is here.
| List modules installed on server. Silent operation.
| List aux modules installed on server. Silent operation.
| List of post modules. Silent operation.
|List of payload modules. Silent operation.
|List of encoder modules. Silent operation.
| XXX results not parsed. Are only the keys listed in documentation possible here? Silent operation.
XXX results are parsed, but parsing needs testing. Silent operation.
|Payloads that are compatible with the given exploit. Silent operation.
|Probably a silent operation, but not clear how it determines compatibility.
|Probably silent, but not clear how it determines compatibility.
|Silent operation.
|Most generic execution of module. Potentially silent and potentially loud. | module MSF.Module
( module Types.Module
, module_exploits
, module_auxiliary
, module_post
, module_payloads
, module_encoders
, module_nops
, module_info
, module_options
, module_compatible_payloads
, module_target_compatible_payloads
, module_compatible_sessions
, module_encode
, module_execute_payload
, module_execute
) where
import MSF.Monad
import Types.Module
import qualified RPC.Module as RPC
module_exploits :: (SilentCxt s) => MSF s Modules
module_exploits = prim RPC.module_exploits
module_auxiliary :: (SilentCxt s) => MSF s Modules
module_auxiliary = prim RPC.module_auxiliary
module_post :: (SilentCxt s) => MSF s Modules
module_post = prim RPC.module_post
module_payloads :: (SilentCxt s) => MSF s Modules
module_payloads = prim RPC.module_payloads
module_encoders :: (SilentCxt s) => MSF s Modules
module_encoders = prim RPC.module_encoders
|List of nop modules . Silent operation .
module_nops :: (SilentCxt s) => MSF s Modules
module_nops = prim RPC.module_nops
module_info :: (SilentCxt s) => ModuleType -> ModuleName -> MSF s ModuleInfo
module_info modTyp modNm = prim $ \ addr auth ->
RPC.module_info addr auth modTyp modNm
module_options :: (SilentCxt s) => ModuleType -> ModuleName -> MSF s ModuleOptions
module_options modTyp modNm = prim $ \ addr auth ->
RPC.module_options addr auth modTyp modNm
module_compatible_payloads :: (SilentCxt s) => ModuleName -> MSF s Payloads
module_compatible_payloads modNm = prim $ \ addr auth ->
RPC.module_compatible_payloads addr auth modNm
module_target_compatible_payloads :: (SilentCxt s) => ModuleName -> Int -> MSF s Payloads
module_target_compatible_payloads modNm targetIndex = prim $ \ addr auth ->
RPC.module_target_compatible_payloads addr auth modNm targetIndex
module_compatible_sessions :: (SilentCxt s) => ModuleName -> MSF s Sessions
module_compatible_sessions modNm = prim $ \ addr auth ->
RPC.module_compatible_sessions addr auth modNm
module_encode :: (SilentCxt s) => Payload -> ModuleName -> EncodeOptions -> MSF s ModuleEncode
module_encode pl encoderModule opts = prim $ \ addr auth ->
RPC.module_encode addr auth pl encoderModule opts
|Execute a payload type module . This is silent since it just returns a payload from MSF . Return value should be ExecPayload .
module_execute_payload :: (SilentCxt s) => Payload -> ExecuteOptions -> MSF s ExecResult
module_execute_payload (Payload pl) opts =
loud $ module_execute PayloadModuleType (ModuleName pl) opts
module_execute :: (LoudCxt s) => ModuleType -> ModuleName -> ExecuteOptions -> MSF s ExecResult
module_execute modTyp modNm opts = prim $ \ addr auth ->
RPC.module_execute addr auth modTyp modNm opts
|
1f19cf9557bfad299fdfbbf86d2801fb648faf8a5145e1eb5ef777fa16b44dab | Twinside/Juicy.Pixels | Types.hs | -- | Module provides basic types for image manipulation in the library.
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE FlexibleContexts #-}
# LANGUAGE FlexibleInstances #
# LANGUAGE FunctionalDependencies #
# LANGUAGE MultiParamTypeClasses #
{-# LANGUAGE Rank2Types #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeSynonymInstances #-}
# LANGUAGE UndecidableInstances #
Defined types are used to store all of those _ _ _ _
module Codec.Picture.Types( -- * Types
-- ** Image types
Image( .. )
, MutableImage( .. )
, DynamicImage( .. )
, PalettedImage( .. )
, Palette
, Palette'( .. )
-- ** Image functions
, createMutableImage
, newMutableImage
, freezeImage
, unsafeFreezeImage
, thawImage
, unsafeThawImage
-- ** Image Lenses
, Traversal
, imagePixels
, imageIPixels
-- ** Pixel types
, Pixel8
, Pixel16
, Pixel32
, PixelF
, PixelYA8( .. )
, PixelYA16( .. )
, PixelRGB8( .. )
, PixelRGB16( .. )
, PixelRGBF( .. )
, PixelRGBA8( .. )
, PixelRGBA16( .. )
, PixelCMYK8( .. )
, PixelCMYK16( .. )
, PixelYCbCr8( .. )
, PixelYCbCrK8( .. )
-- * Type classes
, ColorConvertible( .. )
, Pixel(..)
-- $graph
, ColorSpaceConvertible( .. )
, LumaPlaneExtractable( .. )
, TransparentPixel( .. )
-- * Helper functions
, pixelMap
, pixelMapXY
, pixelFold
, pixelFoldM
, pixelFoldMap
, dynamicMap
, dynamicPixelMap
, palettedToTrueColor
, palettedAsImage
, dropAlphaLayer
, withImage
, zipPixelComponent3
, generateImage
, generateFoldImage
, gammaCorrection
, toneMapping
-- * Color plane extraction
, ColorPlane ( )
, PlaneRed( .. )
, PlaneGreen( .. )
, PlaneBlue( .. )
, PlaneAlpha( .. )
, PlaneLuma( .. )
, PlaneCr( .. )
, PlaneCb( .. )
, PlaneCyan( .. )
, PlaneMagenta( .. )
, PlaneYellow( .. )
, PlaneBlack( .. )
, extractComponent
, unsafeExtractComponent
* writing ( unsafe but faster )
, PackeablePixel( .. )
, fillImageWith
, readPackedPixelAt
, writePackedPixelAt
, unsafeWritePixelBetweenAt
) where
#if !MIN_VERSION_base(4,8,0)
import Data.Monoid( Monoid, mempty )
import Control.Applicative( Applicative, pure, (<*>), (<$>) )
#endif
#if !MIN_VERSION_base(4,11,0)
import Data.Monoid( (<>) )
#endif
import Control.Monad( foldM, liftM, ap )
import Control.DeepSeq( NFData( .. ) )
import Control.Monad.ST( ST, runST )
import Control.Monad.Primitive ( PrimMonad, PrimState )
import Foreign.ForeignPtr( castForeignPtr )
import Foreign.Storable ( Storable )
import Data.Bits( unsafeShiftL, unsafeShiftR, (.|.), (.&.) )
import Data.Typeable ( Typeable )
import Data.Word( Word8, Word16, Word32, Word64 )
import Data.Vector.Storable ( (!) )
import qualified Data.Vector.Storable as V
import qualified Data.Vector.Storable.Mutable as M
#include "ConvGraph.hs"
-- | The main type of this package, one that most
-- functions work on, is Image.
--
-- Parameterized by the underlying pixel format it
-- forms a rigid type. If you wish to store images
of different or unknown pixel formats use ' DynamicImage ' .
--
-- Image is essentially a rectangular pixel buffer
-- of specified width and height. The coordinates are
-- assumed to start from the upper-left corner
of the image , with the horizontal position first
and vertical second .
data Image a = Image
{ -- | Width of the image in pixels
imageWidth :: {-# UNPACK #-} !Int
-- | Height of the image in pixels.
, imageHeight :: {-# UNPACK #-} !Int
-- | Image pixel data. To extract pixels at a given position
-- you should use the helper functions.
--
-- Internally pixel data is stored as consecutively packed
-- lines from top to bottom, scanned from left to right
within individual lines , from first to last color
-- component within each pixel.
, imageData :: V.Vector (PixelBaseComponent a)
}
deriving (Typeable)
instance (Eq (PixelBaseComponent a), Storable (PixelBaseComponent a))
=> Eq (Image a) where
a == b = imageWidth a == imageWidth b &&
imageHeight a == imageHeight b &&
imageData a == imageData b
| Type for the palette used in Gif & PNG files .
type Palette = Image PixelRGB8
-- | Class used to describle plane present in the pixel
-- type. If a pixel has a plane description associated,
-- you can use the plane name to extract planes independently.
class ColorPlane pixel planeToken where
-- | Retrieve the index of the component in the
-- given pixel type.
toComponentIndex :: pixel -> planeToken -> Int
-- | Define the plane for the red color component
data PlaneRed = PlaneRed
deriving (Typeable)
-- | Define the plane for the green color component
data PlaneGreen = PlaneGreen
deriving (Typeable)
-- | Define the plane for the blue color component
data PlaneBlue = PlaneBlue
deriving (Typeable)
-- | Define the plane for the alpha (transparency) component
data PlaneAlpha = PlaneAlpha
deriving (Typeable)
-- | Define the plane for the luma component
data PlaneLuma = PlaneLuma
deriving (Typeable)
-- | Define the plane for the Cr component
data PlaneCr = PlaneCr
deriving (Typeable)
| Define the plane for the Cb component
data PlaneCb = PlaneCb
deriving (Typeable)
-- | Define plane for the cyan component of the
-- CMYK color space.
data PlaneCyan = PlaneCyan
deriving (Typeable)
-- | Define plane for the magenta component of the
-- CMYK color space.
data PlaneMagenta = PlaneMagenta
deriving (Typeable)
-- | Define plane for the yellow component of the
-- CMYK color space.
data PlaneYellow = PlaneYellow
deriving (Typeable)
-- | Define plane for the black component of
the CMYK color space .
data PlaneBlack = PlaneBlack
deriving (Typeable)
-- | Extract a color plane from an image given a present plane in the image
-- examples:
--
-- @
-- extractRedPlane :: Image PixelRGB8 -> Image Pixel8
-- extractRedPlane = extractComponent PlaneRed
-- @
--
extractComponent :: forall px plane. ( Pixel px
, Pixel (PixelBaseComponent px)
, PixelBaseComponent (PixelBaseComponent px)
~ PixelBaseComponent px
, ColorPlane px plane )
=> plane -> Image px -> Image (PixelBaseComponent px)
extractComponent plane = unsafeExtractComponent idx
where idx = toComponentIndex (undefined :: px) plane
-- | Extract a plane of an image. Returns the requested color
-- component as a greyscale image.
--
-- If you ask for a component out of bound, the `error` function will
-- be called.
unsafeExtractComponent :: forall a
. ( Pixel a
, Pixel (PixelBaseComponent a)
, PixelBaseComponent (PixelBaseComponent a)
~ PixelBaseComponent a)
^ The component index , beginning at 0 ending at ( componentCount - 1 )
-> Image a -- ^ Source image
-> Image (PixelBaseComponent a)
unsafeExtractComponent comp img@(Image { imageWidth = w, imageHeight = h })
| comp >= padd = error $ "extractComponent : invalid component index ("
++ show comp ++ ", max:" ++ show padd ++ ")"
| otherwise = Image { imageWidth = w, imageHeight = h, imageData = plane }
where plane = stride img padd comp
padd = componentCount (undefined :: a)
-- | For any image with an alpha component (transparency),
-- drop it, returning a pure opaque image.
dropAlphaLayer :: (TransparentPixel a b) => Image a -> Image b
dropAlphaLayer = pixelMap dropTransparency
-- | Class modeling transparent pixel, should provide a method
-- to combine transparent pixels
class (Pixel a, Pixel b) => TransparentPixel a b | a -> b where
-- | Just return the opaque pixel value
dropTransparency :: a -> b
-- | access the transparency (alpha layer) of a given
-- transparent pixel type.
getTransparency :: a -> PixelBaseComponent a
{-# DEPRECATED getTransparency "please use 'pixelOpacity' instead" #-}
instance TransparentPixel PixelRGBA8 PixelRGB8 where
# INLINE dropTransparency #
dropTransparency (PixelRGBA8 r g b _) = PixelRGB8 r g b
# INLINE getTransparency #
getTransparency (PixelRGBA8 _ _ _ a) = a
lineFold :: (Monad m) => a -> Int -> (a -> Int -> m a) -> m a
# INLINE lineFold #
lineFold initial count f = go 0 initial
where go n acc | n >= count = return acc
go n acc = f acc n >>= go (n + 1)
stride :: (Storable (PixelBaseComponent a))
=> Image a -> Int -> Int -> V.Vector (PixelBaseComponent a)
stride Image { imageWidth = w, imageHeight = h, imageData = array }
padd firstComponent = runST $ do
let cell_count = w * h
outArray <- M.new cell_count
let go writeIndex _ | writeIndex >= cell_count = return ()
go writeIndex readIndex = do
(outArray `M.unsafeWrite` writeIndex) $ array `V.unsafeIndex` readIndex
go (writeIndex + 1) $ readIndex + padd
go 0 firstComponent
V.unsafeFreeze outArray
instance NFData (Image a) where
rnf (Image width height dat) = width `seq`
height `seq`
dat `seq`
()
-- | Image or pixel buffer, the coordinates are assumed to start
-- from the upper-left corner of the image, with the horizontal
position first , then the vertical one . The image can be transformed in place .
data MutableImage s a = MutableImage
{ -- | Width of the image in pixels
mutableImageWidth :: {-# UNPACK #-} !Int
-- | Height of the image in pixels.
, mutableImageHeight :: {-# UNPACK #-} !Int
-- | The real image, to extract pixels at some position
-- you should use the helpers functions.
, mutableImageData :: M.STVector s (PixelBaseComponent a)
}
deriving (Typeable)
-- | `O(n)` Yield an immutable copy of an image by making a copy of it
freezeImage :: (Storable (PixelBaseComponent px), PrimMonad m)
=> MutableImage (PrimState m) px -> m (Image px)
freezeImage (MutableImage w h d) = Image w h `liftM` V.freeze d
-- | `O(n)` Yield a mutable copy of an image by making a copy of it.
thawImage :: (Storable (PixelBaseComponent px), PrimMonad m)
=> Image px -> m (MutableImage (PrimState m) px)
thawImage (Image w h d) = MutableImage w h `liftM` V.thaw d
-- | `O(1)` Unsafe convert an imutable image to an mutable one without copying.
-- The source image shouldn't be used after this operation.
unsafeThawImage :: (Storable (PixelBaseComponent px), PrimMonad m)
=> Image px -> m (MutableImage (PrimState m) px)
# NOINLINE unsafeThawImage #
unsafeThawImage (Image w h d) = MutableImage w h `liftM` V.unsafeThaw d
-- | `O(1)` Unsafe convert a mutable image to an immutable one without copying.
-- The mutable image may not be used after this operation.
unsafeFreezeImage :: (Storable (PixelBaseComponent a), PrimMonad m)
=> MutableImage (PrimState m) a -> m (Image a)
unsafeFreezeImage (MutableImage w h d) = Image w h `liftM` V.unsafeFreeze d
-- | Create a mutable image, filled with the given background color.
createMutableImage :: (Pixel px, PrimMonad m)
=> Int -- ^ Width
-> Int -- ^ Height
-> px -- ^ Background color
-> m (MutableImage (PrimState m) px)
createMutableImage width height background =
generateMutableImage (\_ _ -> background) width height
-- | Create a mutable image with garbage as content. All data
-- is uninitialized.
newMutableImage :: forall px m. (Pixel px, PrimMonad m)
=> Int -- ^ Width
-> Int -- ^ Height
-> m (MutableImage (PrimState m) px)
newMutableImage w h = MutableImage w h `liftM` M.new (w * h * compCount)
where compCount = componentCount (undefined :: px)
instance NFData (MutableImage s a) where
rnf (MutableImage width height dat) = width `seq`
height `seq`
dat `seq`
()
-- | Image type enumerating all predefined pixel types.
-- It enables loading and use of images of different
-- pixel types.
data DynamicImage =
-- | A greyscale image.
ImageY8 (Image Pixel8)
| A greyscale image with 16bit components
| ImageY16 (Image Pixel16)
| A greyscale image with 32bit components
| ImageY32 (Image Pixel32)
-- | A greyscale HDR image
| ImageYF (Image PixelF)
-- | An image in greyscale with an alpha channel.
| ImageYA8 (Image PixelYA8)
| An image in greyscale with alpha channel on 16 bits .
| ImageYA16 (Image PixelYA16)
-- | An image in true color.
| ImageRGB8 (Image PixelRGB8)
| An image in true color with 16bit depth .
| ImageRGB16 (Image PixelRGB16)
-- | An image with HDR pixels
| ImageRGBF (Image PixelRGBF)
-- | An image in true color and an alpha channel.
| ImageRGBA8 (Image PixelRGBA8)
| A true color image with alpha on 16 bits .
| ImageRGBA16 (Image PixelRGBA16)
-- | An image in the colorspace used by Jpeg images.
| ImageYCbCr8 (Image PixelYCbCr8)
-- | An image in the colorspace CMYK
| ImageCMYK8 (Image PixelCMYK8)
| An image in the colorspace CMYK and 16 bits precision
| ImageCMYK16 (Image PixelCMYK16)
deriving (Eq, Typeable)
-- | Type used to expose a palette extracted during reading.
-- Use `palettedAsImage` to convert it to a palette usable for
-- writing.
data Palette' px = Palette'
{ -- | Number of element in pixels.
_paletteSize :: !Int
-- | Real data used by the palette.
, _paletteData :: !(V.Vector (PixelBaseComponent px))
}
deriving Typeable
-- | Convert a palette to an image. Used mainly for
-- backward compatibility.
palettedAsImage :: Palette' px -> Image px
palettedAsImage p = Image (_paletteSize p) 1 $ _paletteData p
-- | Describe an image and it's potential associated
-- palette. If no palette is present, fallback to a
DynamicImage
data PalettedImage
^ Fallback
| PalettedY8 (Image Pixel8) (Palette' Pixel8)
| PalettedRGB8 (Image Pixel8) (Palette' PixelRGB8)
| PalettedRGBA8 (Image Pixel8) (Palette' PixelRGBA8)
| PalettedRGB16 (Image Pixel8) (Palette' PixelRGB16)
deriving (Typeable)
| Flatten a PalettedImage to a DynamicImage
palettedToTrueColor :: PalettedImage -> DynamicImage
palettedToTrueColor img = case img of
TrueColorImage d -> d
PalettedY8 i p -> ImageY8 $ toTrueColor 1 (_paletteData p) i
PalettedRGB8 i p -> ImageRGB8 $ toTrueColor 3 (_paletteData p) i
PalettedRGBA8 i p -> ImageRGBA8 $ toTrueColor 4 (_paletteData p) i
PalettedRGB16 i p -> ImageRGB16 $ toTrueColor 3 (_paletteData p) i
where
toTrueColor c vec = pixelMap (unsafePixelAt vec . (c *) . fromIntegral)
-- | Helper function to help extract information from dynamic
-- image. To get the width of a dynamic image, you can use
-- the following snippet:
--
-- > dynWidth :: DynamicImage -> Int
> dynWidth img = dynamicMap
--
dynamicMap :: (forall pixel . (Pixel pixel) => Image pixel -> a)
-> DynamicImage -> a
dynamicMap f (ImageY8 i) = f i
dynamicMap f (ImageY16 i) = f i
dynamicMap f (ImageY32 i) = f i
dynamicMap f (ImageYF i) = f i
dynamicMap f (ImageYA8 i) = f i
dynamicMap f (ImageYA16 i) = f i
dynamicMap f (ImageRGB8 i) = f i
dynamicMap f (ImageRGB16 i) = f i
dynamicMap f (ImageRGBF i) = f i
dynamicMap f (ImageRGBA8 i) = f i
dynamicMap f (ImageRGBA16 i) = f i
dynamicMap f (ImageYCbCr8 i) = f i
dynamicMap f (ImageCMYK8 i) = f i
dynamicMap f (ImageCMYK16 i) = f i
-- | Equivalent of the `pixelMap` function for the dynamic images.
-- You can perform pixel colorspace independant operations with this
-- function.
--
-- For instance, if you want to extract a square crop of any image,
-- without caring about colorspace, you can use the following snippet.
--
> dynSquare : : DynamicImage - > DynamicImage
> dynSquare = dynamicPixelMap squareImage
-- >
-- > squareImage :: Pixel a => Image a -> Image a
> squareImage img = generateImage ( \x y - > pixelAt img x y ) edge edge
> where edge = min ( imageWidth img ) ( imageHeight img )
--
dynamicPixelMap :: (forall pixel . (Pixel pixel) => Image pixel -> Image pixel)
-> DynamicImage -> DynamicImage
dynamicPixelMap f = aux
where
aux (ImageY8 i) = ImageY8 (f i)
aux (ImageY16 i) = ImageY16 (f i)
aux (ImageY32 i) = ImageY32 (f i)
aux (ImageYF i) = ImageYF (f i)
aux (ImageYA8 i) = ImageYA8 (f i)
aux (ImageYA16 i) = ImageYA16 (f i)
aux (ImageRGB8 i) = ImageRGB8 (f i)
aux (ImageRGB16 i) = ImageRGB16 (f i)
aux (ImageRGBF i) = ImageRGBF (f i)
aux (ImageRGBA8 i) = ImageRGBA8 (f i)
aux (ImageRGBA16 i) = ImageRGBA16 (f i)
aux (ImageYCbCr8 i) = ImageYCbCr8 (f i)
aux (ImageCMYK8 i) = ImageCMYK8 (f i)
aux (ImageCMYK16 i) = ImageCMYK16 (f i)
instance NFData DynamicImage where
rnf (ImageY8 img) = rnf img
rnf (ImageY16 img) = rnf img
rnf (ImageY32 img) = rnf img
rnf (ImageYF img) = rnf img
rnf (ImageYA8 img) = rnf img
rnf (ImageYA16 img) = rnf img
rnf (ImageRGB8 img) = rnf img
rnf (ImageRGB16 img) = rnf img
rnf (ImageRGBF img) = rnf img
rnf (ImageRGBA8 img) = rnf img
rnf (ImageRGBA16 img) = rnf img
rnf (ImageYCbCr8 img) = rnf img
rnf (ImageCMYK8 img) = rnf img
rnf (ImageCMYK16 img) = rnf img
| Type alias for 8bit greyscale pixels . For simplicity ,
-- greyscale pixels use plain numbers instead of a separate type.
type Pixel8 = Word8
| Type alias for 16bit greyscale pixels .
type Pixel16 = Word16
| Type alias for 32bit greyscale pixels .
type Pixel32 = Word32
| Type alias for 32bit floating point greyscale pixels . The standard
bounded value range is mapped to the closed interval [ 0,1 ] i.e.
--
> map promotePixel [ 0 , 1 .. 255 : : Pixel8 ] = = [ 0/255 , 1/255 .. 1.0 : : PixelF ]
type PixelF = Float
| Pixel type storing 8bit Luminance ( Y ) and alpha ( A ) information .
-- Values are stored in the following order:
--
-- * Luminance
--
-- * Alpha
--
data PixelYA8 = PixelYA8 {-# UNPACK #-} !Pixel8 -- Luminance
{-# UNPACK #-} !Pixel8 -- Alpha value
deriving (Eq, Ord, Show, Typeable)
-- | Pixel type storing 16bit Luminance (Y) and alpha (A) information.
-- Values are stored in the following order:
--
-- * Luminance
--
-- * Alpha
--
data PixelYA16 = PixelYA16 {-# UNPACK #-} !Pixel16 -- Luminance
{-# UNPACK #-} !Pixel16 -- Alpha value
deriving (Eq, Ord, Show, Typeable)
| Classic pixel type storing 8bit red , green and blue ( RGB ) information .
-- Values are stored in the following order:
--
-- * Red
--
-- * Green
--
-- * Blue
--
data PixelRGB8 = PixelRGB8 {-# UNPACK #-} !Pixel8 -- Red
{-# UNPACK #-} !Pixel8 -- Green
Blue
deriving (Eq, Ord, Show, Typeable)
| Pixel type storing value for the YCCK color space :
--
-- * Y (Luminance)
--
-- * Cb
--
-- * Cr
--
-- * Black
--
data PixelYCbCrK8 = PixelYCbCrK8 {-# UNPACK #-} !Pixel8
{-# UNPACK #-} !Pixel8
{-# UNPACK #-} !Pixel8
{-# UNPACK #-} !Pixel8
deriving (Eq, Ord, Show, Typeable)
| Pixel type storing 16bit red , green and blue ( RGB ) information .
-- Values are stored in the following order:
--
-- * Red
--
-- * Green
--
-- * Blue
--
data PixelRGB16 = PixelRGB16 {-# UNPACK #-} !Pixel16 -- Red
{-# UNPACK #-} !Pixel16 -- Green
Blue
deriving (Eq, Ord, Show, Typeable)
| HDR pixel type storing floating point 32bit red , green and blue ( RGB ) information .
-- Same value range and comments apply as for 'PixelF'.
-- Values are stored in the following order:
--
-- * Red
--
-- * Green
--
-- * Blue
--
data PixelRGBF = PixelRGBF {-# UNPACK #-} !PixelF -- Red
{-# UNPACK #-} !PixelF -- Green
Blue
deriving (Eq, Ord, Show, Typeable)
| Pixel type storing 8bit luminance , blue difference and red difference ( YCbCr ) information .
-- Values are stored in the following order:
--
-- * Y (luminance)
--
-- * Cb
--
-- * Cr
--
data PixelYCbCr8 = PixelYCbCr8 {-# UNPACK #-} !Pixel8 -- Y luminance
Cb blue difference
{-# UNPACK #-} !Pixel8 -- Cr red difference
deriving (Eq, Ord, Show, Typeable)
| Pixel type storing 8bit cyan , magenta , yellow and black ( CMYK ) information .
-- Values are stored in the following order:
--
-- * Cyan
--
-- * Magenta
--
-- * Yellow
--
-- * Black
--
Cyan
{-# UNPACK #-} !Pixel8 -- Magenta
{-# UNPACK #-} !Pixel8 -- Yellow
{-# UNPACK #-} !Pixel8 -- Black
deriving (Eq, Ord, Show, Typeable)
| Pixel type storing 16bit cyan , magenta , yellow and black ( CMYK ) information .
-- Values are stored in the following order:
--
-- * Cyan
--
-- * Magenta
--
-- * Yellow
--
-- * Black
--
Cyan
{-# UNPACK #-} !Pixel16 -- Magenta
{-# UNPACK #-} !Pixel16 -- Yellow
{-# UNPACK #-} !Pixel16 -- Black
deriving (Eq, Ord, Show, Typeable)
| Classical pixel type storing 8bit red , green , blue and alpha ( RGBA ) information .
-- Values are stored in the following order:
--
-- * Red
--
-- * Green
--
-- * Blue
--
-- * Alpha
--
data PixelRGBA8 = PixelRGBA8 {-# UNPACK #-} !Pixel8 -- Red
{-# UNPACK #-} !Pixel8 -- Green
Blue
{-# UNPACK #-} !Pixel8 -- Alpha
deriving (Eq, Ord, Show, Typeable)
| Pixel type storing 16bit red , green , blue and alpha ( RGBA ) information .
-- Values are stored in the following order:
--
-- * Red
--
-- * Green
--
-- * Blue
--
-- * Alpha
--
data PixelRGBA16 = PixelRGBA16 {-# UNPACK #-} !Pixel16 -- Red
{-# UNPACK #-} !Pixel16 -- Green
Blue
{-# UNPACK #-} !Pixel16 -- Alpha
deriving (Eq, Ord, Show, Typeable)
-- | Definition of pixels used in images. Each pixel has a color space, and a representative
-- component (Word8 or Float).
class ( Storable (PixelBaseComponent a)
, Num (PixelBaseComponent a), Eq a ) => Pixel a where
-- | Type of the pixel component, "classical" images
-- would have Word8 type as their PixelBaseComponent,
-- HDR image would have Float for instance
type PixelBaseComponent a :: *
-- | Call the function for every component of the pixels.
-- For example for RGB pixels mixWith is declared like this:
--
> mixWith f ( ) ( PixelRGB8 rb gb bb ) =
-- > PixelRGB8 (f 0 ra rb) (f 1 ga gb) (f 2 ba bb)
--
mixWith :: (Int -> PixelBaseComponent a -> PixelBaseComponent a -> PixelBaseComponent a)
-> a -> a -> a
-- | Extension of the `mixWith` which separate the treatment
-- of the color components of the alpha value (transparency component).
-- For pixel without alpha components, it is equivalent to mixWith.
--
> mixWithAlpha f fa ( PixelRGBA8 ) ( PixelRGB8 rb gb bb ab ) =
> PixelRGBA8 ( f 0 ra rb ) ( f 1 ga gb ) ( f 2 ba bb ) ( )
--
mixWithAlpha :: (Int -> PixelBaseComponent a -> PixelBaseComponent a
-> PixelBaseComponent a) -- ^ Function for color component
-> (PixelBaseComponent a -> PixelBaseComponent a
-> PixelBaseComponent a) -- ^ Function for alpha component
-> a -> a -> a
# INLINE mixWithAlpha #
mixWithAlpha f _ = mixWith f
-- | Return the opacity of a pixel, if the pixel has an
-- alpha layer, return the alpha value. If the pixel
-- doesn't have an alpha value, return a value
-- representing the opaqueness.
pixelOpacity :: a -> PixelBaseComponent a
-- | Return the number of components of the pixel
componentCount :: a -> Int
-- | Apply a function to each component of a pixel.
-- If the color type possess an alpha (transparency channel),
-- it is treated like the other color components.
colorMap :: (PixelBaseComponent a -> PixelBaseComponent a) -> a -> a
-- | Calculate the index for the begining of the pixel
pixelBaseIndex :: Image a -> Int -> Int -> Int
pixelBaseIndex (Image { imageWidth = w }) x y =
(x + y * w) * componentCount (undefined :: a)
-- | Calculate theindex for the begining of the pixel at position x y
mutablePixelBaseIndex :: MutableImage s a -> Int -> Int -> Int
mutablePixelBaseIndex (MutableImage { mutableImageWidth = w }) x y =
(x + y * w) * componentCount (undefined :: a)
-- | Extract a pixel at a given position, (x, y), the origin
-- is assumed to be at the corner top left, positive y to the
-- bottom of the image
pixelAt :: Image a -> Int -> Int -> a
-- | Same as pixelAt but for mutable images.
readPixel :: PrimMonad m => MutableImage (PrimState m) a -> Int -> Int -> m a
-- | Write a pixel in a mutable image at position x y
writePixel :: PrimMonad m => MutableImage (PrimState m) a -> Int -> Int -> a -> m ()
-- | Unsafe version of pixelAt, read a pixel at the given
-- index without bound checking (if possible).
-- The index is expressed in number (PixelBaseComponent a)
unsafePixelAt :: V.Vector (PixelBaseComponent a) -> Int -> a
| Unsafe version of readPixel , read a pixel at the given
-- position without bound checking (if possible). The index
-- is expressed in number (PixelBaseComponent a)
unsafeReadPixel :: PrimMonad m => M.STVector (PrimState m) (PixelBaseComponent a) -> Int -> m a
| Unsafe version of writePixel , write a pixel at the
-- given position without bound checking. This can be _really_ unsafe.
-- The index is expressed in number (PixelBaseComponent a)
unsafeWritePixel :: PrimMonad m => M.STVector (PrimState m) (PixelBaseComponent a) -> Int -> a -> m ()
-- | Implement upcasting for pixel types.
Minimal declaration of ` promotePixel ` .
-- It is strongly recommended to overload promoteImage to keep
-- performance acceptable
class (Pixel a, Pixel b) => ColorConvertible a b where
-- | Convert a pixel type to another pixel type. This
-- operation should never lose any data.
promotePixel :: a -> b
-- | Change the underlying pixel type of an image by performing a full copy
-- of it.
promoteImage :: Image a -> Image b
promoteImage = pixelMap promotePixel
-- | This class abstract colorspace conversion. This
conversion can be lossy , which ColorConvertible can not
class (Pixel a, Pixel b) => ColorSpaceConvertible a b where
| Pass a pixel from a colorspace ( say RGB ) to the second one
( say YCbCr )
convertPixel :: a -> b
-- | Helper function to convert a whole image by taking a
-- copy it.
convertImage :: Image a -> Image b
convertImage = pixelMap convertPixel
generateMutableImage :: forall m px. (Pixel px, PrimMonad m)
=> (Int -> Int -> px) -- ^ Generating function, with `x` and `y` params.
-> Int -- ^ Width in pixels
-> Int -- ^ Height in pixels
-> m (MutableImage (PrimState m) px)
# INLINE generateMutableImage #
generateMutableImage f w h = MutableImage w h `liftM` generated where
compCount = componentCount (undefined :: px)
generated = do
arr <- M.new (w * h * compCount)
let lineGenerator _ !y | y >= h = return ()
lineGenerator !lineIdx y = column lineIdx 0
where column !idx !x | x >= w = lineGenerator idx $ y + 1
column idx x = do
unsafeWritePixel arr idx $ f x y
column (idx + compCount) $ x + 1
lineGenerator 0 0
return arr
-- | Create an image given a function to generate pixels.
-- The function will receive values from 0 to width-1 for the x parameter
and 0 to height-1 for the y parameter . The coordinates 0,0 are the upper
-- left corner of the image, and (width-1, height-1) the lower right corner.
--
-- for example, to create a small gradient image:
--
-- > imageCreator :: String -> IO ()
> imageCreator path = writePng path $ generateImage pixelRenderer 250 300
> where pixelRenderer x y = PixelRGB8 ( fromIntegral x ) ( fromIntegral y ) 128
--
generateImage :: forall px. (Pixel px)
=> (Int -> Int -> px) -- ^ Generating function, with `x` and `y` params.
-> Int -- ^ Width in pixels
-> Int -- ^ Height in pixels
-> Image px
# INLINE generateImage #
generateImage f w h = runST img where
img :: ST s (Image px)
img = generateMutableImage f w h >>= unsafeFreezeImage
-- | Create an image using a monadic initializer function.
-- The function will receive values from 0 to width-1 for the x parameter
and 0 to height-1 for the y parameter . The coordinates 0,0 are the upper
-- left corner of the image, and (width-1, height-1) the lower right corner.
--
The function is called for each pixel in the line from left to right ( 0 to width - 1 )
-- and for each line (0 to height - 1).
withImage :: forall m pixel. (Pixel pixel, PrimMonad m)
=> Int -- ^ Image width
-> Int -- ^ Image height
-> (Int -> Int -> m pixel) -- ^ Generating functions
-> m (Image pixel)
withImage width height pixelGenerator = do
let pixelComponentCount = componentCount (undefined :: pixel)
arr <- M.new (width * height * pixelComponentCount)
let mutImage = MutableImage
{ mutableImageWidth = width
, mutableImageHeight = height
, mutableImageData = arr
}
let pixelPositions = [(x, y) | y <- [0 .. height-1], x <- [0..width-1]]
sequence_ [pixelGenerator x y >>= unsafeWritePixel arr idx
| ((x,y), idx) <- zip pixelPositions [0, pixelComponentCount ..]]
unsafeFreezeImage mutImage
-- | Create an image given a function to generate pixels.
-- The function will receive values from 0 to width-1 for the x parameter
and 0 to height-1 for the y parameter . The coordinates 0,0 are the upper
-- left corner of the image, and (width-1, height-1) the lower right corner.
--
the acc parameter is a user defined one .
--
The function is called for each pixel in the line from left to right ( 0 to width - 1 )
-- and for each line (0 to height - 1).
generateFoldImage :: forall a acc. (Pixel a)
=> (acc -> Int -> Int -> (acc, a)) -- ^ Function taking the state, x and y
-> acc -- ^ Initial state
-> Int -- ^ Width in pixels
-> Int -- ^ Height in pixels
-> (acc, Image a)
generateFoldImage f intialAcc w h =
(finalState, Image { imageWidth = w, imageHeight = h, imageData = generated })
where compCount = componentCount (undefined :: a)
(finalState, generated) = runST $ do
arr <- M.new (w * h * compCount)
let mutImage = MutableImage {
mutableImageWidth = w,
mutableImageHeight = h,
mutableImageData = arr }
foldResult <- foldM (\acc (x,y) -> do
let (acc', px) = f acc x y
writePixel mutImage x y px
return acc') intialAcc [(x,y) | y <- [0 .. h-1], x <- [0 .. w-1]]
frozen <- V.unsafeFreeze arr
return (foldResult, frozen)
-- | Fold over the pixel of an image with a raster scan order:
-- from top to bottom, left to right
{-# INLINE pixelFold #-}
pixelFold :: forall acc pixel. (Pixel pixel)
=> (acc -> Int -> Int -> pixel -> acc) -> acc -> Image pixel -> acc
pixelFold f initialAccumulator img@(Image { imageWidth = w, imageHeight = h }) =
columnFold 0 initialAccumulator 0
where
!compCount = componentCount (undefined :: pixel)
!vec = imageData img
lfold !y acc !x !idx
| x >= w = columnFold (y + 1) acc idx
| otherwise =
lfold y (f acc x y $ unsafePixelAt vec idx) (x + 1) (idx + compCount)
columnFold !y lineAcc !readIdx
| y >= h = lineAcc
| otherwise = lfold y lineAcc 0 readIdx
-- | Fold over the pixel of an image with a raster scan order:
-- from top to bottom, left to right, carrying out a state
pixelFoldM :: (Pixel pixel, Monad m)
=> (acc -> Int -> Int -> pixel -> m acc) -- ^ monadic mapping function
-> acc -- ^ Initial state
-> Image pixel -- ^ Image to fold over
-> m acc
{-# INLINE pixelFoldM #-}
pixelFoldM action initialAccumulator img@(Image { imageWidth = w, imageHeight = h }) =
lineFold initialAccumulator h columnFold
where
pixelFolder y acc x = action acc x y $ pixelAt img x y
columnFold lineAcc y = lineFold lineAcc w (pixelFolder y)
-- | Fold over the pixel of an image with a raster scan order:
-- from top to bottom, left to right. This functions is analog
-- to the foldMap from the 'Foldable' typeclass, but due to the
Pixel constraint , Image can not be made an instance of it .
pixelFoldMap :: forall m px. (Pixel px, Monoid m) => (px -> m) -> Image px -> m
pixelFoldMap f Image { imageWidth = w, imageHeight = h, imageData = vec } = folder 0
where
compCount = componentCount (undefined :: px)
maxi = w * h * compCount
folder idx | idx >= maxi = mempty
folder idx = f (unsafePixelAt vec idx) <> folder (idx + compCount)
-- | `map` equivalent for an image, working at the pixel level.
-- Little example : a brightness function for an rgb image
--
-- > brightnessRGB8 :: Int -> Image PixelRGB8 -> Image PixelRGB8
-- > brightnessRGB8 add = pixelMap brightFunction
-- > where up v = fromIntegral (fromIntegral v + add)
-- > brightFunction (PixelRGB8 r g b) =
-- > PixelRGB8 (up r) (up g) (up b)
--
pixelMap :: forall a b. (Pixel a, Pixel b)
=> (a -> b) -> Image a -> Image b
{-# SPECIALIZE INLINE pixelMap :: (PixelYCbCr8 -> PixelRGB8) -> Image PixelYCbCr8 -> Image PixelRGB8 #-}
# SPECIALIZE INLINE pixelMap : : ( PixelRGB8 - > ) - > Image PixelRGB8 - > Image PixelYCbCr8 #
{-# SPECIALIZE INLINE pixelMap :: (PixelRGB8 -> PixelRGB8) -> Image PixelRGB8 -> Image PixelRGB8 #-}
# SPECIALIZE INLINE pixelMap : : ( PixelRGB8 - > PixelRGBA8 ) - > Image PixelRGB8 - > Image PixelRGBA8 #
# SPECIALIZE INLINE pixelMap : : ( PixelRGBA8 - > PixelRGBA8 ) - > Image PixelRGBA8 - > Image PixelRGBA8 #
{-# SPECIALIZE INLINE pixelMap :: (Pixel8 -> PixelRGB8) -> Image Pixel8 -> Image PixelRGB8 #-}
{-# SPECIALIZE INLINE pixelMap :: (Pixel8 -> Pixel8) -> Image Pixel8 -> Image Pixel8 #-}
pixelMap f Image { imageWidth = w, imageHeight = h, imageData = vec } =
Image w h pixels
where sourceComponentCount = componentCount (undefined :: a)
destComponentCount = componentCount (undefined :: b)
pixels = runST $ do
newArr <- M.new (w * h * destComponentCount)
let lineMapper _ _ y | y >= h = return ()
lineMapper readIdxLine writeIdxLine y = colMapper readIdxLine writeIdxLine 0
where colMapper readIdx writeIdx x
| x >= w = lineMapper readIdx writeIdx $ y + 1
| otherwise = do
unsafeWritePixel newArr writeIdx . f $ unsafePixelAt vec readIdx
colMapper (readIdx + sourceComponentCount)
(writeIdx + destComponentCount)
(x + 1)
lineMapper 0 0 0
unsafeFreeze avoids making a second copy and it will be
safe because newArray ca n't be referenced as a mutable array
-- outside of this where block
V.unsafeFreeze newArr
-- | Helpers to embed a rankNTypes inside an Applicative
newtype GenST a = GenST { genAction :: forall s. ST s (M.STVector s a) }
| Traversal type matching the definition in the Lens package .
type Traversal s t a b =
forall f. Applicative f => (a -> f b) -> s -> f t
writePx :: Pixel px
=> Int -> GenST (PixelBaseComponent px) -> px -> GenST (PixelBaseComponent px)
# INLINE writePx #
writePx idx act px = GenST $ do
vec <- genAction act
unsafeWritePixel vec idx px
return vec
freezeGenST :: Pixel px
=> Int -> Int -> GenST (PixelBaseComponent px) -> Image px
freezeGenST w h act =
Image w h (runST (genAction act >>= V.unsafeFreeze))
-- | Traversal in "raster" order, from left to right the top to bottom.
-- This traversal is matching pixelMap in spirit.
--
Since 3.2.4
imagePixels :: forall pxa pxb. (Pixel pxa, Pixel pxb)
=> Traversal (Image pxa) (Image pxb) pxa pxb
# INLINE imagePixels #
imagePixels f Image { imageWidth = w, imageHeight = h, imageData = vec } =
freezeGenST w h <$> pixels
where
sourceComponentCount = componentCount (undefined :: pxa)
destComponentCount = componentCount (undefined :: pxb)
maxi = w * h * sourceComponentCount
pixels =
go (pure $ GenST $ M.new (w * h * destComponentCount)) 0 0
go act readIdx _ | readIdx >= maxi = act
go act readIdx writeIdx =
go newAct (readIdx + sourceComponentCount) (writeIdx + destComponentCount)
where
px = f (unsafePixelAt vec readIdx)
newAct = writePx writeIdx <$> act <*> px
-- | Traversal providing the pixel position with it's value.
-- The traversal in raster order, from lef to right, then top
-- to bottom. The traversal match pixelMapXY in spirit.
--
Since 3.2.4
imageIPixels :: forall pxa pxb. (Pixel pxa, Pixel pxb)
=> Traversal (Image pxa) (Image pxb) (Int, Int, pxa) pxb
# INLINE imageIPixels #
imageIPixels f Image { imageWidth = w, imageHeight = h, imageData = vec } =
freezeGenST w h <$> pixels
where
sourceComponentCount = componentCount (undefined :: pxa)
destComponentCount = componentCount (undefined :: pxb)
pixels =
lineMapper (pure $ GenST $ M.new (w * h * destComponentCount)) 0 0 0
lineMapper act _ _ y | y >= h = act
lineMapper act readIdxLine writeIdxLine y =
go act readIdxLine writeIdxLine 0
where
go cact readIdx writeIdx x
| x >= w = lineMapper cact readIdx writeIdx $ y + 1
| otherwise = do
let px = f (x, y, unsafePixelAt vec readIdx)
go (writePx writeIdx <$> cact <*> px)
(readIdx + sourceComponentCount)
(writeIdx + destComponentCount)
(x + 1)
-- | Just like `pixelMap` only the function takes the pixel coordinates as
-- additional parameters.
pixelMapXY :: forall a b. (Pixel a, Pixel b)
=> (Int -> Int -> a -> b) -> Image a -> Image b
# SPECIALIZE INLINE pixelMapXY : : ( Int - > Int - > PixelYCbCr8 - > PixelRGB8 )
- > Image PixelYCbCr8 - > Image PixelRGB8 #
-> Image PixelYCbCr8 -> Image PixelRGB8 #-}
# SPECIALIZE INLINE pixelMapXY : : ( Int - > Int - > PixelRGB8 - > )
- > Image PixelRGB8 - > Image PixelYCbCr8 #
-> Image PixelRGB8 -> Image PixelYCbCr8 #-}
# SPECIALIZE INLINE pixelMapXY : : ( Int - > Int - > PixelRGB8 - > PixelRGB8 )
- > Image PixelRGB8 - > Image PixelRGB8 #
-> Image PixelRGB8 -> Image PixelRGB8 #-}
# SPECIALIZE INLINE pixelMapXY : : ( Int - > Int - > PixelRGB8 - > PixelRGBA8 )
- > Image PixelRGB8 - > Image PixelRGBA8 #
-> Image PixelRGB8 -> Image PixelRGBA8 #-}
# SPECIALIZE INLINE pixelMapXY : : ( Int - > Int - > PixelRGBA8 - > PixelRGBA8 )
- > Image PixelRGBA8 - > Image PixelRGBA8 #
-> Image PixelRGBA8 -> Image PixelRGBA8 #-}
# SPECIALIZE INLINE pixelMapXY : : ( Int - > Int - > Pixel8 - > PixelRGB8 )
- > Image Pixel8 - > Image PixelRGB8 #
-> Image Pixel8 -> Image PixelRGB8 #-}
pixelMapXY f Image { imageWidth = w, imageHeight = h, imageData = vec } =
Image w h pixels
where sourceComponentCount = componentCount (undefined :: a)
destComponentCount = componentCount (undefined :: b)
pixels = runST $ do
newArr <- M.new (w * h * destComponentCount)
let lineMapper _ _ y | y >= h = return ()
lineMapper readIdxLine writeIdxLine y = colMapper readIdxLine writeIdxLine 0
where colMapper readIdx writeIdx x
| x >= w = lineMapper readIdx writeIdx $ y + 1
| otherwise = do
unsafeWritePixel newArr writeIdx . f x y $ unsafePixelAt vec readIdx
colMapper (readIdx + sourceComponentCount)
(writeIdx + destComponentCount)
(x + 1)
lineMapper 0 0 0
unsafeFreeze avoids making a second copy and it will be
safe because newArray ca n't be referenced as a mutable array
-- outside of this where block
V.unsafeFreeze newArr
-- | Combine, pixel by pixel and component by component
the values of 3 different images . Usage example :
--
-- > averageBrightNess c1 c2 c3 = clamp $ toInt c1 + toInt c2 + toInt c3
> where clamp = fromIntegral . min 0 . max 255
-- > toInt :: a -> Int
-- > toInt = fromIntegral
-- > ziPixelComponent3 averageBrightNess img1 img2 img3
--
zipPixelComponent3
:: forall px. ( V.Storable (PixelBaseComponent px))
=> (PixelBaseComponent px -> PixelBaseComponent px -> PixelBaseComponent px
-> PixelBaseComponent px)
-> Image px -> Image px -> Image px -> Image px
# INLINE zipPixelComponent3 #
zipPixelComponent3 f i1@(Image { imageWidth = w, imageHeight = h }) i2 i3
| not isDimensionEqual = error "Different image size zipPairwisePixelComponent"
| otherwise = Image { imageWidth = w
, imageHeight = h
, imageData = V.zipWith3 f data1 data2 data3
}
where data1 = imageData i1
data2 = imageData i2
data3 = imageData i3
isDimensionEqual =
w == imageWidth i2 && w == imageWidth i3 &&
h == imageHeight i2 && h == imageHeight i3
-- | Helper class to help extract a luma plane out
-- of an image or a pixel
class (Pixel a, Pixel (PixelBaseComponent a)) => LumaPlaneExtractable a where
-- | Compute the luminance part of a pixel
computeLuma :: a -> PixelBaseComponent a
-- | Extract a luma plane out of an image. This
-- method is in the typeclass to help performant
-- implementation.
--
> jpegToGrayScale : : FilePath - > FilePath - > IO ( )
-- > jpegToGrayScale source dest
extractLumaPlane :: Image a -> Image (PixelBaseComponent a)
extractLumaPlane = pixelMap computeLuma
instance LumaPlaneExtractable Pixel8 where
# INLINE computeLuma #
computeLuma = id
extractLumaPlane = id
instance LumaPlaneExtractable Pixel16 where
# INLINE computeLuma #
computeLuma = id
extractLumaPlane = id
instance LumaPlaneExtractable Pixel32 where
# INLINE computeLuma #
computeLuma = id
extractLumaPlane = id
instance LumaPlaneExtractable PixelF where
# INLINE computeLuma #
computeLuma = id
extractLumaPlane = id
instance LumaPlaneExtractable PixelRGBF where
# INLINE computeLuma #
computeLuma (PixelRGBF r g b) =
0.3 * r + 0.59 * g + 0.11 * b
instance LumaPlaneExtractable PixelRGBA8 where
# INLINE computeLuma #
computeLuma (PixelRGBA8 r g b _) =
floor $ (0.3 :: Double) * fromIntegral r
+ 0.59 * fromIntegral g
+ 0.11 * fromIntegral b
instance LumaPlaneExtractable PixelYCbCr8 where
# INLINE computeLuma #
computeLuma (PixelYCbCr8 y _ _) = y
extractLumaPlane = extractComponent PlaneLuma
-- | Free promotion for identic pixel types
instance (Pixel a) => ColorConvertible a a where
{-# INLINE promotePixel #-}
promotePixel = id
# INLINE promoteImage #
promoteImage = id
--------------------------------------------------
---- Pixel8 instances
--------------------------------------------------
instance Pixel Pixel8 where
type PixelBaseComponent Pixel8 = Word8
# INLINE pixelOpacity #
pixelOpacity = const maxBound
{-# INLINE mixWith #-}
mixWith f = f 0
# INLINE colorMap #
colorMap f = f
{-# INLINE componentCount #-}
componentCount _ = 1
# INLINE pixelAt #
pixelAt (Image { imageWidth = w, imageData = arr }) x y = arr ! (x + y * w)
# INLINE readPixel #
readPixel image@(MutableImage { mutableImageData = arr }) x y =
arr `M.read` mutablePixelBaseIndex image x y
# INLINE writePixel #
writePixel image@(MutableImage { mutableImageData = arr }) x y =
arr `M.write` mutablePixelBaseIndex image x y
# INLINE unsafePixelAt #
unsafePixelAt = V.unsafeIndex
# INLINE unsafeReadPixel #
unsafeReadPixel = M.unsafeRead
# INLINE unsafeWritePixel #
unsafeWritePixel = M.unsafeWrite
instance ColorConvertible Pixel8 PixelYA8 where
{-# INLINE promotePixel #-}
promotePixel c = PixelYA8 c 255
instance ColorConvertible Pixel8 PixelF where
{-# INLINE promotePixel #-}
promotePixel c = fromIntegral c / 255.0
instance ColorConvertible Pixel8 Pixel16 where
{-# INLINE promotePixel #-}
promotePixel c = fromIntegral c * 257
instance ColorConvertible Pixel8 PixelRGB8 where
{-# INLINE promotePixel #-}
promotePixel c = PixelRGB8 c c c
instance ColorConvertible Pixel8 PixelRGB16 where
{-# INLINE promotePixel #-}
promotePixel c = PixelRGB16 (fromIntegral c * 257) (fromIntegral c * 257) (fromIntegral c * 257)
instance ColorConvertible Pixel8 PixelRGBA8 where
{-# INLINE promotePixel #-}
promotePixel c = PixelRGBA8 c c c 255
--------------------------------------------------
---- Pixel16 instances
--------------------------------------------------
instance Pixel Pixel16 where
type PixelBaseComponent Pixel16 = Word16
# INLINE pixelOpacity #
pixelOpacity = const maxBound
{-# INLINE mixWith #-}
mixWith f = f 0
# INLINE colorMap #
colorMap f = f
{-# INLINE componentCount #-}
componentCount _ = 1
# INLINE pixelAt #
pixelAt (Image { imageWidth = w, imageData = arr }) x y = arr ! (x + y * w)
# INLINE readPixel #
readPixel image@(MutableImage { mutableImageData = arr }) x y =
arr `M.read` mutablePixelBaseIndex image x y
# INLINE writePixel #
writePixel image@(MutableImage { mutableImageData = arr }) x y =
arr `M.write` mutablePixelBaseIndex image x y
# INLINE unsafePixelAt #
unsafePixelAt = V.unsafeIndex
# INLINE unsafeReadPixel #
unsafeReadPixel = M.unsafeRead
# INLINE unsafeWritePixel #
unsafeWritePixel = M.unsafeWrite
instance ColorConvertible Pixel16 PixelYA16 where
{-# INLINE promotePixel #-}
promotePixel c = PixelYA16 c maxBound
instance ColorConvertible Pixel16 PixelRGB16 where
{-# INLINE promotePixel #-}
promotePixel c = PixelRGB16 c c c
instance ColorConvertible Pixel16 PixelRGBA16 where
{-# INLINE promotePixel #-}
promotePixel c = PixelRGBA16 c c c maxBound
--------------------------------------------------
---- Pixel32 instances
--------------------------------------------------
instance Pixel Pixel32 where
type PixelBaseComponent Pixel32 = Word32
# INLINE pixelOpacity #
pixelOpacity = const maxBound
{-# INLINE mixWith #-}
mixWith f = f 0
# INLINE colorMap #
colorMap f = f
{-# INLINE componentCount #-}
componentCount _ = 1
# INLINE pixelAt #
pixelAt (Image { imageWidth = w, imageData = arr }) x y = arr ! (x + y * w)
# INLINE readPixel #
readPixel image@(MutableImage { mutableImageData = arr }) x y =
arr `M.read` mutablePixelBaseIndex image x y
# INLINE writePixel #
writePixel image@(MutableImage { mutableImageData = arr }) x y =
arr `M.write` mutablePixelBaseIndex image x y
# INLINE unsafePixelAt #
unsafePixelAt = V.unsafeIndex
# INLINE unsafeReadPixel #
unsafeReadPixel = M.unsafeRead
# INLINE unsafeWritePixel #
unsafeWritePixel = M.unsafeWrite
--------------------------------------------------
---- PixelF instances
--------------------------------------------------
instance Pixel PixelF where
type PixelBaseComponent PixelF = Float
# INLINE pixelOpacity #
pixelOpacity = const 1.0
{-# INLINE mixWith #-}
mixWith f = f 0
# INLINE colorMap #
colorMap f = f
{-# INLINE componentCount #-}
componentCount _ = 1
# INLINE pixelAt #
pixelAt (Image { imageWidth = w, imageData = arr }) x y =
arr ! (x + y * w)
# INLINE readPixel #
readPixel image@(MutableImage { mutableImageData = arr }) x y =
arr `M.read` mutablePixelBaseIndex image x y
# INLINE writePixel #
writePixel image@(MutableImage { mutableImageData = arr }) x y =
arr `M.write` mutablePixelBaseIndex image x y
# INLINE unsafePixelAt #
unsafePixelAt = V.unsafeIndex
# INLINE unsafeReadPixel #
unsafeReadPixel = M.unsafeRead
# INLINE unsafeWritePixel #
unsafeWritePixel = M.unsafeWrite
instance ColorConvertible PixelF PixelRGBF where
{-# INLINE promotePixel #-}
promotePixel c = PixelRGBF c c c-- (c / 0.3) (c / 0.59) (c / 0.11)
--------------------------------------------------
---- PixelYA8 instances
--------------------------------------------------
instance Pixel PixelYA8 where
type PixelBaseComponent PixelYA8 = Word8
# INLINE pixelOpacity #
pixelOpacity (PixelYA8 _ a) = a
{-# INLINE mixWith #-}
mixWith f (PixelYA8 ya aa) (PixelYA8 yb ab) =
PixelYA8 (f 0 ya yb) (f 1 aa ab)
# INLINE colorMap #
colorMap f (PixelYA8 y a) = PixelYA8 (f y) (f a)
{-# INLINE componentCount #-}
componentCount _ = 2
# INLINE pixelAt #
pixelAt image@(Image { imageData = arr }) x y =
PixelYA8 (arr ! (baseIdx + 0)) (arr ! (baseIdx + 1))
where baseIdx = pixelBaseIndex image x y
# INLINE readPixel #
readPixel image@(MutableImage { mutableImageData = arr }) x y = do
yv <- arr `M.read` baseIdx
av <- arr `M.read` (baseIdx + 1)
return $ PixelYA8 yv av
where baseIdx = mutablePixelBaseIndex image x y
# INLINE writePixel #
writePixel image@(MutableImage { mutableImageData = arr }) x y (PixelYA8 yv av) = do
let baseIdx = mutablePixelBaseIndex image x y
(arr `M.write` (baseIdx + 0)) yv
(arr `M.write` (baseIdx + 1)) av
# INLINE unsafePixelAt #
unsafePixelAt v idx =
PixelYA8 (V.unsafeIndex v idx) (V.unsafeIndex v $ idx + 1)
# INLINE unsafeReadPixel #
unsafeReadPixel vec idx =
PixelYA8 `liftM` M.unsafeRead vec idx `ap` M.unsafeRead vec (idx + 1)
# INLINE unsafeWritePixel #
unsafeWritePixel v idx (PixelYA8 y a) =
M.unsafeWrite v idx y >> M.unsafeWrite v (idx + 1) a
instance ColorConvertible PixelYA8 PixelRGB8 where
{-# INLINE promotePixel #-}
promotePixel (PixelYA8 y _) = PixelRGB8 y y y
instance ColorConvertible PixelYA8 PixelRGB16 where
{-# INLINE promotePixel #-}
promotePixel (PixelYA8 y _) = PixelRGB16 (fromIntegral y * 257) (fromIntegral y * 257) (fromIntegral y * 257)
instance ColorConvertible PixelYA8 PixelRGBA8 where
{-# INLINE promotePixel #-}
promotePixel (PixelYA8 y a) = PixelRGBA8 y y y a
instance ColorPlane PixelYA8 PlaneLuma where
toComponentIndex _ _ = 0
instance ColorPlane PixelYA8 PlaneAlpha where
toComponentIndex _ _ = 1
instance TransparentPixel PixelYA8 Pixel8 where
# INLINE dropTransparency #
dropTransparency (PixelYA8 y _) = y
# INLINE getTransparency #
getTransparency (PixelYA8 _ a) = a
instance LumaPlaneExtractable PixelYA8 where
# INLINE computeLuma #
computeLuma (PixelYA8 y _) = y
extractLumaPlane = extractComponent PlaneLuma
--------------------------------------------------
---- PixelYA16 instances
--------------------------------------------------
instance Pixel PixelYA16 where
type PixelBaseComponent PixelYA16 = Word16
# INLINE pixelOpacity #
pixelOpacity (PixelYA16 _ a) = a
{-# INLINE mixWith #-}
mixWith f (PixelYA16 ya aa) (PixelYA16 yb ab) =
PixelYA16 (f 0 ya yb) (f 1 aa ab)
# INLINE mixWithAlpha #
mixWithAlpha f fa (PixelYA16 ya aa) (PixelYA16 yb ab) =
PixelYA16 (f 0 ya yb) (fa aa ab)
# INLINE colorMap #
colorMap f (PixelYA16 y a) = PixelYA16 (f y) (f a)
{-# INLINE componentCount #-}
componentCount _ = 2
# INLINE pixelAt #
pixelAt image@(Image { imageData = arr }) x y = PixelYA16 (arr ! (baseIdx + 0))
(arr ! (baseIdx + 1))
where baseIdx = pixelBaseIndex image x y
# INLINE readPixel #
readPixel image@(MutableImage { mutableImageData = arr }) x y = do
yv <- arr `M.read` baseIdx
av <- arr `M.read` (baseIdx + 1)
return $ PixelYA16 yv av
where baseIdx = mutablePixelBaseIndex image x y
# INLINE writePixel #
writePixel image@(MutableImage { mutableImageData = arr }) x y (PixelYA16 yv av) = do
let baseIdx = mutablePixelBaseIndex image x y
(arr `M.write` (baseIdx + 0)) yv
(arr `M.write` (baseIdx + 1)) av
# INLINE unsafePixelAt #
unsafePixelAt v idx =
PixelYA16 (V.unsafeIndex v idx) (V.unsafeIndex v $ idx + 1)
# INLINE unsafeReadPixel #
unsafeReadPixel vec idx =
PixelYA16 `liftM` M.unsafeRead vec idx `ap` M.unsafeRead vec (idx + 1)
# INLINE unsafeWritePixel #
unsafeWritePixel v idx (PixelYA16 y a) =
M.unsafeWrite v idx y >> M.unsafeWrite v (idx + 1) a
instance ColorConvertible PixelYA16 PixelRGB16 where
{-# INLINE promotePixel #-}
promotePixel (PixelYA16 y _) = PixelRGB16 y y y
instance ColorConvertible PixelYA16 PixelRGBA16 where
{-# INLINE promotePixel #-}
promotePixel (PixelYA16 y a) = PixelRGBA16 y y y a
instance ColorPlane PixelYA16 PlaneLuma where
toComponentIndex _ _ = 0
instance ColorPlane PixelYA16 PlaneAlpha where
toComponentIndex _ _ = 1
instance TransparentPixel PixelYA16 Pixel16 where
# INLINE dropTransparency #
dropTransparency (PixelYA16 y _) = y
# INLINE getTransparency #
getTransparency (PixelYA16 _ a) = a
--------------------------------------------------
-- PixelRGBF instances
--------------------------------------------------
instance Pixel PixelRGBF where
type PixelBaseComponent PixelRGBF = PixelF
# INLINE pixelOpacity #
pixelOpacity = const 1.0
{-# INLINE mixWith #-}
mixWith f (PixelRGBF ra ga ba) (PixelRGBF rb gb bb) =
PixelRGBF (f 0 ra rb) (f 1 ga gb) (f 2 ba bb)
# INLINE colorMap #
colorMap f (PixelRGBF r g b) = PixelRGBF (f r) (f g) (f b)
{-# INLINE componentCount #-}
componentCount _ = 3
# INLINE pixelAt #
pixelAt image@(Image { imageData = arr }) x y = PixelRGBF (arr ! (baseIdx + 0))
(arr ! (baseIdx + 1))
(arr ! (baseIdx + 2))
where baseIdx = pixelBaseIndex image x y
# INLINE readPixel #
readPixel image@(MutableImage { mutableImageData = arr }) x y = do
rv <- arr `M.read` baseIdx
gv <- arr `M.read` (baseIdx + 1)
bv <- arr `M.read` (baseIdx + 2)
return $ PixelRGBF rv gv bv
where baseIdx = mutablePixelBaseIndex image x y
# INLINE writePixel #
writePixel image@(MutableImage { mutableImageData = arr }) x y (PixelRGBF rv gv bv) = do
let baseIdx = mutablePixelBaseIndex image x y
(arr `M.write` (baseIdx + 0)) rv
(arr `M.write` (baseIdx + 1)) gv
(arr `M.write` (baseIdx + 2)) bv
# INLINE unsafePixelAt #
unsafePixelAt v idx =
PixelRGBF (V.unsafeIndex v idx) (V.unsafeIndex v $ idx + 1) (V.unsafeIndex v $ idx + 2)
# INLINE unsafeReadPixel #
unsafeReadPixel vec idx =
PixelRGBF `liftM` M.unsafeRead vec idx
`ap` M.unsafeRead vec (idx + 1)
`ap` M.unsafeRead vec (idx + 2)
# INLINE unsafeWritePixel #
unsafeWritePixel v idx (PixelRGBF r g b) =
M.unsafeWrite v idx r >> M.unsafeWrite v (idx + 1) g
>> M.unsafeWrite v (idx + 2) b
instance ColorPlane PixelRGBF PlaneRed where
toComponentIndex _ _ = 0
instance ColorPlane PixelRGBF PlaneGreen where
toComponentIndex _ _ = 1
instance ColorPlane PixelRGBF PlaneBlue where
toComponentIndex _ _ = 2
--------------------------------------------------
-- PixelRGB16 instances
--------------------------------------------------
instance Pixel PixelRGB16 where
type PixelBaseComponent PixelRGB16 = Pixel16
# INLINE pixelOpacity #
pixelOpacity = const maxBound
{-# INLINE mixWith #-}
mixWith f (PixelRGB16 ra ga ba) (PixelRGB16 rb gb bb) =
PixelRGB16 (f 0 ra rb) (f 1 ga gb) (f 2 ba bb)
# INLINE colorMap #
colorMap f (PixelRGB16 r g b) = PixelRGB16 (f r) (f g) (f b)
{-# INLINE componentCount #-}
componentCount _ = 3
# INLINE pixelAt #
pixelAt image@(Image { imageData = arr }) x y = PixelRGB16 (arr ! (baseIdx + 0))
(arr ! (baseIdx + 1))
(arr ! (baseIdx + 2))
where baseIdx = pixelBaseIndex image x y
# INLINE readPixel #
readPixel image@(MutableImage { mutableImageData = arr }) x y = do
rv <- arr `M.read` baseIdx
gv <- arr `M.read` (baseIdx + 1)
bv <- arr `M.read` (baseIdx + 2)
return $ PixelRGB16 rv gv bv
where baseIdx = mutablePixelBaseIndex image x y
# INLINE writePixel #
writePixel image@(MutableImage { mutableImageData = arr }) x y (PixelRGB16 rv gv bv) = do
let baseIdx = mutablePixelBaseIndex image x y
(arr `M.write` (baseIdx + 0)) rv
(arr `M.write` (baseIdx + 1)) gv
(arr `M.write` (baseIdx + 2)) bv
# INLINE unsafePixelAt #
unsafePixelAt v idx =
PixelRGB16 (V.unsafeIndex v idx) (V.unsafeIndex v $ idx + 1) (V.unsafeIndex v $ idx + 2)
# INLINE unsafeReadPixel #
unsafeReadPixel vec idx =
PixelRGB16 `liftM` M.unsafeRead vec idx
`ap` M.unsafeRead vec (idx + 1)
`ap` M.unsafeRead vec (idx + 2)
# INLINE unsafeWritePixel #
unsafeWritePixel v idx (PixelRGB16 r g b) =
M.unsafeWrite v idx r >> M.unsafeWrite v (idx + 1) g
>> M.unsafeWrite v (idx + 2) b
instance ColorPlane PixelRGB16 PlaneRed where
toComponentIndex _ _ = 0
instance ColorPlane PixelRGB16 PlaneGreen where
toComponentIndex _ _ = 1
instance ColorPlane PixelRGB16 PlaneBlue where
toComponentIndex _ _ = 2
instance ColorSpaceConvertible PixelRGB16 PixelCMYK16 where
# INLINE convertPixel #
convertPixel (PixelRGB16 r g b) = integralRGBToCMYK PixelCMYK16 (r, g, b)
instance ColorConvertible PixelRGB16 PixelRGBA16 where
{-# INLINE promotePixel #-}
promotePixel (PixelRGB16 r g b) = PixelRGBA16 r g b maxBound
instance LumaPlaneExtractable PixelRGB16 where
# INLINE computeLuma #
computeLuma (PixelRGB16 r g b) =
floor $ (0.3 :: Double) * fromIntegral r
+ 0.59 * fromIntegral g
+ 0.11 * fromIntegral b
--------------------------------------------------
---- PixelRGB8 instances
--------------------------------------------------
instance Pixel PixelRGB8 where
type PixelBaseComponent PixelRGB8 = Word8
# INLINE pixelOpacity #
pixelOpacity = const maxBound
{-# INLINE mixWith #-}
mixWith f (PixelRGB8 ra ga ba) (PixelRGB8 rb gb bb) =
PixelRGB8 (f 0 ra rb) (f 1 ga gb) (f 2 ba bb)
# INLINE colorMap #
colorMap f (PixelRGB8 r g b) = PixelRGB8 (f r) (f g) (f b)
{-# INLINE componentCount #-}
componentCount _ = 3
# INLINE pixelAt #
pixelAt image@(Image { imageData = arr }) x y = PixelRGB8 (arr ! (baseIdx + 0))
(arr ! (baseIdx + 1))
(arr ! (baseIdx + 2))
where baseIdx = pixelBaseIndex image x y
# INLINE readPixel #
readPixel image@(MutableImage { mutableImageData = arr }) x y = do
rv <- arr `M.read` baseIdx
gv <- arr `M.read` (baseIdx + 1)
bv <- arr `M.read` (baseIdx + 2)
return $ PixelRGB8 rv gv bv
where baseIdx = mutablePixelBaseIndex image x y
# INLINE writePixel #
writePixel image@(MutableImage { mutableImageData = arr }) x y (PixelRGB8 rv gv bv) = do
let baseIdx = mutablePixelBaseIndex image x y
(arr `M.write` (baseIdx + 0)) rv
(arr `M.write` (baseIdx + 1)) gv
(arr `M.write` (baseIdx + 2)) bv
# INLINE unsafePixelAt #
unsafePixelAt v idx =
PixelRGB8 (V.unsafeIndex v idx) (V.unsafeIndex v $ idx + 1) (V.unsafeIndex v $ idx + 2)
# INLINE unsafeReadPixel #
unsafeReadPixel vec idx =
PixelRGB8 `liftM` M.unsafeRead vec idx
`ap` M.unsafeRead vec (idx + 1)
`ap` M.unsafeRead vec (idx + 2)
# INLINE unsafeWritePixel #
unsafeWritePixel v idx (PixelRGB8 r g b) =
M.unsafeWrite v idx r >> M.unsafeWrite v (idx + 1) g
>> M.unsafeWrite v (idx + 2) b
instance ColorConvertible PixelRGB8 PixelRGBA8 where
{-# INLINE promotePixel #-}
promotePixel (PixelRGB8 r g b) = PixelRGBA8 r g b maxBound
instance ColorConvertible PixelRGB8 PixelRGBF where
{-# INLINE promotePixel #-}
promotePixel (PixelRGB8 r g b) = PixelRGBF (toF r) (toF g) (toF b)
where toF v = fromIntegral v / 255.0
instance ColorConvertible PixelRGB8 PixelRGB16 where
{-# INLINE promotePixel #-}
promotePixel (PixelRGB8 r g b) = PixelRGB16 (promotePixel r) (promotePixel g) (promotePixel b)
instance ColorConvertible PixelRGB8 PixelRGBA16 where
{-# INLINE promotePixel #-}
promotePixel (PixelRGB8 r g b) = PixelRGBA16 (promotePixel r) (promotePixel g) (promotePixel b) maxBound
instance ColorPlane PixelRGB8 PlaneRed where
toComponentIndex _ _ = 0
instance ColorPlane PixelRGB8 PlaneGreen where
toComponentIndex _ _ = 1
instance ColorPlane PixelRGB8 PlaneBlue where
toComponentIndex _ _ = 2
instance LumaPlaneExtractable PixelRGB8 where
# INLINE computeLuma #
computeLuma (PixelRGB8 r g b) =
floor $ (0.3 :: Double) * fromIntegral r
+ 0.59 * fromIntegral g
+ 0.11 * fromIntegral b
--------------------------------------------------
-- PixelRGBA8 instances
--------------------------------------------------
instance Pixel PixelRGBA8 where
type PixelBaseComponent PixelRGBA8 = Word8
# INLINE pixelOpacity #
pixelOpacity (PixelRGBA8 _ _ _ a) = a
{-# INLINE mixWith #-}
mixWith f (PixelRGBA8 ra ga ba aa) (PixelRGBA8 rb gb bb ab) =
PixelRGBA8 (f 0 ra rb) (f 1 ga gb) (f 2 ba bb) (f 3 aa ab)
# INLINE mixWithAlpha #
mixWithAlpha f fa (PixelRGBA8 ra ga ba aa) (PixelRGBA8 rb gb bb ab) =
PixelRGBA8 (f 0 ra rb) (f 1 ga gb) (f 2 ba bb) (fa aa ab)
# INLINE colorMap #
colorMap f (PixelRGBA8 r g b a) = PixelRGBA8 (f r) (f g) (f b) (f a)
{-# INLINE componentCount #-}
componentCount _ = 4
# INLINE pixelAt #
pixelAt image@(Image { imageData = arr }) x y = PixelRGBA8 (arr ! (baseIdx + 0))
(arr ! (baseIdx + 1))
(arr ! (baseIdx + 2))
(arr ! (baseIdx + 3))
where baseIdx = pixelBaseIndex image x y
# INLINE readPixel #
readPixel image@(MutableImage { mutableImageData = arr }) x y = do
rv <- arr `M.read` baseIdx
gv <- arr `M.read` (baseIdx + 1)
bv <- arr `M.read` (baseIdx + 2)
av <- arr `M.read` (baseIdx + 3)
return $ PixelRGBA8 rv gv bv av
where baseIdx = mutablePixelBaseIndex image x y
# INLINE writePixel #
writePixel image@(MutableImage { mutableImageData = arr }) x y (PixelRGBA8 rv gv bv av) = do
let baseIdx = mutablePixelBaseIndex image x y
(arr `M.write` (baseIdx + 0)) rv
(arr `M.write` (baseIdx + 1)) gv
(arr `M.write` (baseIdx + 2)) bv
(arr `M.write` (baseIdx + 3)) av
# INLINE unsafePixelAt #
unsafePixelAt v idx =
PixelRGBA8 (V.unsafeIndex v idx)
(V.unsafeIndex v $ idx + 1)
(V.unsafeIndex v $ idx + 2)
(V.unsafeIndex v $ idx + 3)
# INLINE unsafeReadPixel #
unsafeReadPixel vec idx =
PixelRGBA8 `liftM` M.unsafeRead vec idx
`ap` M.unsafeRead vec (idx + 1)
`ap` M.unsafeRead vec (idx + 2)
`ap` M.unsafeRead vec (idx + 3)
# INLINE unsafeWritePixel #
unsafeWritePixel v idx (PixelRGBA8 r g b a) =
M.unsafeWrite v idx r >> M.unsafeWrite v (idx + 1) g
>> M.unsafeWrite v (idx + 2) b
>> M.unsafeWrite v (idx + 3) a
instance ColorConvertible PixelRGBA8 PixelRGBA16 where
{-# INLINE promotePixel #-}
promotePixel (PixelRGBA8 r g b a) = PixelRGBA16 (promotePixel r) (promotePixel g) (promotePixel b) (promotePixel a)
instance ColorPlane PixelRGBA8 PlaneRed where
toComponentIndex _ _ = 0
instance ColorPlane PixelRGBA8 PlaneGreen where
toComponentIndex _ _ = 1
instance ColorPlane PixelRGBA8 PlaneBlue where
toComponentIndex _ _ = 2
instance ColorPlane PixelRGBA8 PlaneAlpha where
toComponentIndex _ _ = 3
--------------------------------------------------
---- PixelRGBA16 instances
--------------------------------------------------
instance Pixel PixelRGBA16 where
type PixelBaseComponent PixelRGBA16 = Pixel16
# INLINE pixelOpacity #
pixelOpacity (PixelRGBA16 _ _ _ a) = a
{-# INLINE mixWith #-}
mixWith f (PixelRGBA16 ra ga ba aa) (PixelRGBA16 rb gb bb ab) =
PixelRGBA16 (f 0 ra rb) (f 1 ga gb) (f 2 ba bb) (f 3 aa ab)
# INLINE mixWithAlpha #
mixWithAlpha f fa (PixelRGBA16 ra ga ba aa) (PixelRGBA16 rb gb bb ab) =
PixelRGBA16 (f 0 ra rb) (f 1 ga gb) (f 2 ba bb) (fa aa ab)
# INLINE colorMap #
colorMap f (PixelRGBA16 r g b a) = PixelRGBA16 (f r) (f g) (f b) (f a)
{-# INLINE componentCount #-}
componentCount _ = 4
# INLINE pixelAt #
pixelAt image@(Image { imageData = arr }) x y =
PixelRGBA16 (arr ! (baseIdx + 0)) (arr ! (baseIdx + 1))
(arr ! (baseIdx + 2)) (arr ! (baseIdx + 3))
where baseIdx = pixelBaseIndex image x y
# INLINE readPixel #
readPixel image@(MutableImage { mutableImageData = arr }) x y = do
rv <- arr `M.read` baseIdx
gv <- arr `M.read` (baseIdx + 1)
bv <- arr `M.read` (baseIdx + 2)
av <- arr `M.read` (baseIdx + 3)
return $ PixelRGBA16 rv gv bv av
where baseIdx = mutablePixelBaseIndex image x y
# INLINE writePixel #
writePixel image@(MutableImage { mutableImageData = arr }) x y (PixelRGBA16 rv gv bv av) = do
let baseIdx = mutablePixelBaseIndex image x y
(arr `M.write` (baseIdx + 0)) rv
(arr `M.write` (baseIdx + 1)) gv
(arr `M.write` (baseIdx + 2)) bv
(arr `M.write` (baseIdx + 3)) av
# INLINE unsafePixelAt #
unsafePixelAt v idx =
PixelRGBA16 (V.unsafeIndex v idx)
(V.unsafeIndex v $ idx + 1)
(V.unsafeIndex v $ idx + 2)
(V.unsafeIndex v $ idx + 3)
# INLINE unsafeReadPixel #
unsafeReadPixel vec idx =
PixelRGBA16 `liftM` M.unsafeRead vec idx
`ap` M.unsafeRead vec (idx + 1)
`ap` M.unsafeRead vec (idx + 2)
`ap` M.unsafeRead vec (idx + 3)
# INLINE unsafeWritePixel #
unsafeWritePixel v idx (PixelRGBA16 r g b a) =
M.unsafeWrite v idx r >> M.unsafeWrite v (idx + 1) g
>> M.unsafeWrite v (idx + 2) b
>> M.unsafeWrite v (idx + 3) a
instance TransparentPixel PixelRGBA16 PixelRGB16 where
# INLINE dropTransparency #
dropTransparency (PixelRGBA16 r g b _) = PixelRGB16 r g b
# INLINE getTransparency #
getTransparency (PixelRGBA16 _ _ _ a) = a
instance ColorPlane PixelRGBA16 PlaneRed where
toComponentIndex _ _ = 0
instance ColorPlane PixelRGBA16 PlaneGreen where
toComponentIndex _ _ = 1
instance ColorPlane PixelRGBA16 PlaneBlue where
toComponentIndex _ _ = 2
instance ColorPlane PixelRGBA16 PlaneAlpha where
toComponentIndex _ _ = 3
--------------------------------------------------
-- instances
--------------------------------------------------
instance Pixel PixelYCbCr8 where
type PixelBaseComponent PixelYCbCr8 = Word8
# INLINE pixelOpacity #
pixelOpacity = const maxBound
{-# INLINE mixWith #-}
mixWith f (PixelYCbCr8 ya cba cra) (PixelYCbCr8 yb cbb crb) =
PixelYCbCr8 (f 0 ya yb) (f 1 cba cbb) (f 2 cra crb)
# INLINE colorMap #
colorMap f (PixelYCbCr8 y cb cr) = PixelYCbCr8 (f y) (f cb) (f cr)
{-# INLINE componentCount #-}
componentCount _ = 3
# INLINE pixelAt #
pixelAt image@(Image { imageData = arr }) x y = PixelYCbCr8 (arr ! (baseIdx + 0))
(arr ! (baseIdx + 1))
(arr ! (baseIdx + 2))
where baseIdx = pixelBaseIndex image x y
# INLINE readPixel #
readPixel image@(MutableImage { mutableImageData = arr }) x y = do
yv <- arr `M.read` baseIdx
cbv <- arr `M.read` (baseIdx + 1)
crv <- arr `M.read` (baseIdx + 2)
return $ PixelYCbCr8 yv cbv crv
where baseIdx = mutablePixelBaseIndex image x y
# INLINE writePixel #
writePixel image@(MutableImage { mutableImageData = arr }) x y (PixelYCbCr8 yv cbv crv) = do
let baseIdx = mutablePixelBaseIndex image x y
(arr `M.write` (baseIdx + 0)) yv
(arr `M.write` (baseIdx + 1)) cbv
(arr `M.write` (baseIdx + 2)) crv
# INLINE unsafePixelAt #
unsafePixelAt v idx =
PixelYCbCr8 (V.unsafeIndex v idx) (V.unsafeIndex v $ idx + 1) (V.unsafeIndex v $ idx + 2)
# INLINE unsafeReadPixel #
unsafeReadPixel vec idx =
PixelYCbCr8 `liftM` M.unsafeRead vec idx
`ap` M.unsafeRead vec (idx + 1)
`ap` M.unsafeRead vec (idx + 2)
# INLINE unsafeWritePixel #
unsafeWritePixel v idx (PixelYCbCr8 y cb cr) =
M.unsafeWrite v idx y >> M.unsafeWrite v (idx + 1) cb
>> M.unsafeWrite v (idx + 2) cr
instance (Pixel a) => ColorSpaceConvertible a a where
convertPixel = id
convertImage = id
scaleBits, oneHalf :: Int
scaleBits = 16
oneHalf = 1 `unsafeShiftL` (scaleBits - 1)
fix :: Float -> Int
fix x = floor $ x * fromIntegral ((1 :: Int) `unsafeShiftL` scaleBits) + 0.5
rYTab, gYTab, bYTab, rCbTab, gCbTab, bCbTab, gCrTab, bCrTab :: V.Vector Int
rYTab = V.fromListN 256 [fix 0.29900 * i | i <- [0..255] ]
gYTab = V.fromListN 256 [fix 0.58700 * i | i <- [0..255] ]
bYTab = V.fromListN 256 [fix 0.11400 * i + oneHalf | i <- [0..255] ]
rCbTab = V.fromListN 256 [(- fix 0.16874) * i | i <- [0..255] ]
gCbTab = V.fromListN 256 [(- fix 0.33126) * i | i <- [0..255] ]
bCbTab = V.fromListN 256 [fix 0.5 * i + (128 `unsafeShiftL` scaleBits) + oneHalf - 1| i <- [0..255] ]
gCrTab = V.fromListN 256 [(- fix 0.41869) * i | i <- [0..255] ]
bCrTab = V.fromListN 256 [(- fix 0.08131) * i | i <- [0..255] ]
instance ColorSpaceConvertible PixelRGB8 PixelYCbCr8 where
# INLINE convertPixel #
convertPixel (PixelRGB8 r g b) = PixelYCbCr8 (fromIntegral y) (fromIntegral cb) (fromIntegral cr)
where ri = fromIntegral r
gi = fromIntegral g
bi = fromIntegral b
y = (rYTab `V.unsafeIndex` ri + gYTab `V.unsafeIndex` gi + bYTab `V.unsafeIndex` bi) `unsafeShiftR` scaleBits
cb = (rCbTab `V.unsafeIndex` ri + gCbTab `V.unsafeIndex` gi + bCbTab `V.unsafeIndex` bi) `unsafeShiftR` scaleBits
cr = (bCbTab `V.unsafeIndex` ri + gCrTab `V.unsafeIndex` gi + bCrTab `V.unsafeIndex` bi) `unsafeShiftR` scaleBits
convertImage Image { imageWidth = w, imageHeight = h, imageData = d } = Image w h newData
where maxi = w * h
rY = fix 0.29900
gY = fix 0.58700
bY = fix 0.11400
rCb = - fix 0.16874
gCb = - fix 0.33126
bCb = fix 0.5
gCr = - fix 0.41869
bCr = - fix 0.08131
newData = runST $ do
block <- M.new $ maxi * 3
let traductor _ idx | idx >= maxi = return block
traductor readIdx idx = do
let ri = fromIntegral $ d `V.unsafeIndex` readIdx
gi = fromIntegral $ d `V.unsafeIndex` (readIdx + 1)
bi = fromIntegral $ d `V.unsafeIndex` (readIdx + 2)
y = (rY * ri + gY * gi + bY * bi + oneHalf) `unsafeShiftR` scaleBits
cb = (rCb * ri + gCb * gi + bCb * bi + (128 `unsafeShiftL` scaleBits) + oneHalf - 1) `unsafeShiftR` scaleBits
cr = (bCb * ri + (128 `unsafeShiftL` scaleBits) + oneHalf - 1+ gCr * gi + bCr * bi) `unsafeShiftR` scaleBits
(block `M.unsafeWrite` (readIdx + 0)) $ fromIntegral y
(block `M.unsafeWrite` (readIdx + 1)) $ fromIntegral cb
(block `M.unsafeWrite` (readIdx + 2)) $ fromIntegral cr
traductor (readIdx + 3) (idx + 1)
traductor 0 0 >>= V.freeze
crRTab, cbBTab, crGTab, cbGTab :: V.Vector Int
crRTab = V.fromListN 256 [(fix 1.40200 * x + oneHalf) `unsafeShiftR` scaleBits | x <- [-128 .. 127]]
cbBTab = V.fromListN 256 [(fix 1.77200 * x + oneHalf) `unsafeShiftR` scaleBits | x <- [-128 .. 127]]
crGTab = V.fromListN 256 [negate (fix 0.71414) * x | x <- [-128 .. 127]]
cbGTab = V.fromListN 256 [negate (fix 0.34414) * x + oneHalf | x <- [-128 .. 127]]
instance ColorSpaceConvertible PixelYCbCr8 PixelRGB8 where
# INLINE convertPixel #
convertPixel (PixelYCbCr8 y cb cr) = PixelRGB8 (clampWord8 r) (clampWord8 g) (clampWord8 b)
where clampWord8 = fromIntegral . max 0 . min 255
yi = fromIntegral y
cbi = fromIntegral cb
cri = fromIntegral cr
r = yi + crRTab `V.unsafeIndex` cri
g = yi + (cbGTab `V.unsafeIndex` cbi + crGTab `V.unsafeIndex` cri) `unsafeShiftR` scaleBits
b = yi + cbBTab `V.unsafeIndex` cbi
convertImage Image { imageWidth = w, imageHeight = h, imageData = d } = Image w h newData
where maxi = w * h
clampWord8 v | v < 0 = 0
| v > 255 = 255
| otherwise = fromIntegral v
newData = runST $ do
block <- M.new $ maxi * 3
let traductor _ idx | idx >= maxi = return block
traductor readIdx idx = do
let yi = fromIntegral $ d `V.unsafeIndex` readIdx
cbi = fromIntegral $ d `V.unsafeIndex` (readIdx + 1)
cri = fromIntegral $ d `V.unsafeIndex` (readIdx + 2)
r = yi + crRTab `V.unsafeIndex` cri
g = yi + (cbGTab `V.unsafeIndex` cbi + crGTab `V.unsafeIndex` cri) `unsafeShiftR` scaleBits
b = yi + cbBTab `V.unsafeIndex` cbi
(block `M.unsafeWrite` (readIdx + 0)) $ clampWord8 r
(block `M.unsafeWrite` (readIdx + 1)) $ clampWord8 g
(block `M.unsafeWrite` (readIdx + 2)) $ clampWord8 b
traductor (readIdx + 3) (idx + 1)
traductor 0 0 >>= V.freeze
instance ColorPlane PixelYCbCr8 PlaneLuma where
toComponentIndex _ _ = 0
instance ColorPlane PixelYCbCr8 PlaneCb where
toComponentIndex _ _ = 1
instance ColorPlane PixelYCbCr8 PlaneCr where
toComponentIndex _ _ = 2
--------------------------------------------------
---- PixelCMYK8 instances
--------------------------------------------------
instance Pixel PixelCMYK8 where
type PixelBaseComponent PixelCMYK8 = Word8
# INLINE pixelOpacity #
pixelOpacity = const maxBound
{-# INLINE mixWith #-}
mixWith f (PixelCMYK8 ca ma ya ka) (PixelCMYK8 cb mb yb kb) =
PixelCMYK8 (f 0 ca cb) (f 1 ma mb) (f 2 ya yb) (f 3 ka kb)
# INLINE colorMap #
colorMap f (PixelCMYK8 c m y k) = PixelCMYK8 (f c) (f m) (f y) (f k)
{-# INLINE componentCount #-}
componentCount _ = 4
# INLINE pixelAt #
pixelAt image@(Image { imageData = arr }) x y = PixelCMYK8 (arr ! (baseIdx + 0))
(arr ! (baseIdx + 1))
(arr ! (baseIdx + 2))
(arr ! (baseIdx + 3))
where baseIdx = pixelBaseIndex image x y
# INLINE readPixel #
readPixel image@(MutableImage { mutableImageData = arr }) x y = do
rv <- arr `M.read` baseIdx
gv <- arr `M.read` (baseIdx + 1)
bv <- arr `M.read` (baseIdx + 2)
av <- arr `M.read` (baseIdx + 3)
return $ PixelCMYK8 rv gv bv av
where baseIdx = mutablePixelBaseIndex image x y
# INLINE writePixel #
writePixel image@(MutableImage { mutableImageData = arr }) x y (PixelCMYK8 rv gv bv av) = do
let baseIdx = mutablePixelBaseIndex image x y
(arr `M.write` (baseIdx + 0)) rv
(arr `M.write` (baseIdx + 1)) gv
(arr `M.write` (baseIdx + 2)) bv
(arr `M.write` (baseIdx + 3)) av
# INLINE unsafePixelAt #
unsafePixelAt v idx =
PixelCMYK8 (V.unsafeIndex v idx)
(V.unsafeIndex v $ idx + 1)
(V.unsafeIndex v $ idx + 2)
(V.unsafeIndex v $ idx + 3)
# INLINE unsafeReadPixel #
unsafeReadPixel vec idx =
PixelCMYK8 `liftM` M.unsafeRead vec idx
`ap` M.unsafeRead vec (idx + 1)
`ap` M.unsafeRead vec (idx + 2)
`ap` M.unsafeRead vec (idx + 3)
# INLINE unsafeWritePixel #
unsafeWritePixel v idx (PixelCMYK8 r g b a) =
M.unsafeWrite v idx r >> M.unsafeWrite v (idx + 1) g
>> M.unsafeWrite v (idx + 2) b
>> M.unsafeWrite v (idx + 3) a
instance ColorSpaceConvertible PixelCMYK8 PixelRGB8 where
convertPixel (PixelCMYK8 c m y k) =
PixelRGB8 (clampWord8 r) (clampWord8 g) (clampWord8 b)
where
clampWord8 = fromIntegral . max 0 . min 255 . (`div` 255)
ik :: Int
ik = 255 - fromIntegral k
r = (255 - fromIntegral c) * ik
g = (255 - fromIntegral m) * ik
b = (255 - fromIntegral y) * ik
--------------------------------------------------
---- PixelYCbCrK8 instances
--------------------------------------------------
instance Pixel PixelYCbCrK8 where
type PixelBaseComponent PixelYCbCrK8 = Word8
# INLINE pixelOpacity #
pixelOpacity = const maxBound
{-# INLINE mixWith #-}
mixWith f (PixelYCbCrK8 ya cba cra ka) (PixelYCbCrK8 yb cbb crb kb) =
PixelYCbCrK8 (f 0 ya yb) (f 1 cba cbb) (f 2 cra crb) (f 3 ka kb)
# INLINE colorMap #
colorMap f (PixelYCbCrK8 y cb cr k) = PixelYCbCrK8 (f y) (f cb) (f cr) (f k)
{-# INLINE componentCount #-}
componentCount _ = 4
# INLINE pixelAt #
pixelAt image@(Image { imageData = arr }) x y =
PixelYCbCrK8 (arr ! (baseIdx + 0)) (arr ! (baseIdx + 1))
(arr ! (baseIdx + 2)) (arr ! (baseIdx + 3))
where baseIdx = pixelBaseIndex image x y
# INLINE readPixel #
readPixel image@(MutableImage { mutableImageData = arr }) x y = do
yv <- arr `M.read` baseIdx
cbv <- arr `M.read` (baseIdx + 1)
crv <- arr `M.read` (baseIdx + 2)
kv <- arr `M.read` (baseIdx + 3)
return $ PixelYCbCrK8 yv cbv crv kv
where baseIdx = mutablePixelBaseIndex image x y
# INLINE writePixel #
writePixel image@(MutableImage { mutableImageData = arr }) x y (PixelYCbCrK8 yv cbv crv kv) = do
let baseIdx = mutablePixelBaseIndex image x y
(arr `M.write` (baseIdx + 0)) yv
(arr `M.write` (baseIdx + 1)) cbv
(arr `M.write` (baseIdx + 2)) crv
(arr `M.write` (baseIdx + 3)) kv
# INLINE unsafePixelAt #
unsafePixelAt v idx =
PixelYCbCrK8 (V.unsafeIndex v idx)
(V.unsafeIndex v $ idx + 1)
(V.unsafeIndex v $ idx + 2)
(V.unsafeIndex v $ idx + 3)
# INLINE unsafeReadPixel #
unsafeReadPixel vec idx =
PixelYCbCrK8 `liftM` M.unsafeRead vec idx
`ap` M.unsafeRead vec (idx + 1)
`ap` M.unsafeRead vec (idx + 2)
`ap` M.unsafeRead vec (idx + 3)
# INLINE unsafeWritePixel #
unsafeWritePixel v idx (PixelYCbCrK8 y cb cr k) =
M.unsafeWrite v idx y >> M.unsafeWrite v (idx + 1) cb
>> M.unsafeWrite v (idx + 2) cr
>> M.unsafeWrite v (idx + 3) k
instance ColorSpaceConvertible PixelYCbCrK8 PixelRGB8 where
convertPixel (PixelYCbCrK8 y cb cr _k) = PixelRGB8 (clamp r) (clamp g) (clamp b)
where
tof :: Word8 -> Float
tof = fromIntegral
clamp :: Float -> Word8
clamp = floor . max 0 . min 255
yf = tof y
r = yf + 1.402 * tof cr - 179.456
g = yf - 0.3441363 * tof cb - 0.71413636 * tof cr + 135.4589
b = yf + 1.772 * tof cb - 226.816
instance ColorSpaceConvertible PixelYCbCrK8 PixelCMYK8 where
convertPixel (PixelYCbCrK8 y cb cr k) = PixelCMYK8 c m ye k
where
tof :: Word8 -> Float
tof = fromIntegral
clamp :: Float -> Word8
clamp = floor . max 0 . min 255
yf = tof y
r = yf + 1.402 * tof cr - 179.456
g = yf - 0.3441363 * tof cb - 0.71413636 * tof cr + 135.4589
b = yf + 1.772 * tof cb - 226.816
c = clamp $ 255 - r
m = clamp $ 255 - g
ye = clamp $ 255 - b
{-# SPECIALIZE integralRGBToCMYK :: (Word8 -> Word8 -> Word8 -> Word8 -> b)
-> (Word8, Word8, Word8) -> b #-}
# SPECIALIZE integralRGBToCMYK : : ( Word16 - > Word16 - > Word16 - > b )
- > ( Word16 , , b #
-> (Word16, Word16, Word16) -> b #-}
| Convert RGB8 or RGB16 to and CMYK16 respectfully .
--
-- /Note/ - 32bit precision is not supported. Make sure to adjust implementation if ever
used with .
integralRGBToCMYK :: (Bounded a, Integral a)
=> (a -> a -> a -> a -> b) -- ^ Pixel building function
-> (a, a, a) -- ^ RGB sample
-> b -- ^ Resulting sample
integralRGBToCMYK build (r, g, b)
prevent division by zero
| otherwise = build (fromIntegral c) (fromIntegral m) (fromIntegral y) k
where maxVal = maxBound
max32 = fromIntegral maxVal :: Word32
kMax32 = fromIntegral kMax :: Word32
kMax = max r (max g b)
k = maxVal - kMax
c = max32 * (kMax32 - fromIntegral r) `div` kMax32
m = max32 * (kMax32 - fromIntegral g) `div` kMax32
y = max32 * (kMax32 - fromIntegral b) `div` kMax32
instance ColorSpaceConvertible PixelRGB8 PixelCMYK8 where
convertPixel (PixelRGB8 r g b) = integralRGBToCMYK PixelCMYK8 (r, g, b)
instance ColorPlane PixelCMYK8 PlaneCyan where
toComponentIndex _ _ = 0
instance ColorPlane PixelCMYK8 PlaneMagenta where
toComponentIndex _ _ = 1
instance ColorPlane PixelCMYK8 PlaneYellow where
toComponentIndex _ _ = 2
instance ColorPlane PixelCMYK8 PlaneBlack where
toComponentIndex _ _ = 3
--------------------------------------------------
---- PixelCMYK16 instances
--------------------------------------------------
instance Pixel PixelCMYK16 where
type PixelBaseComponent PixelCMYK16 = Word16
# INLINE pixelOpacity #
pixelOpacity = const maxBound
{-# INLINE mixWith #-}
mixWith f (PixelCMYK16 ca ma ya ka) (PixelCMYK16 cb mb yb kb) =
PixelCMYK16 (f 0 ca cb) (f 1 ma mb) (f 2 ya yb) (f 3 ka kb)
# INLINE colorMap #
colorMap f (PixelCMYK16 c m y k) = PixelCMYK16 (f c) (f m) (f y) (f k)
{-# INLINE componentCount #-}
componentCount _ = 4
# INLINE pixelAt #
pixelAt image@(Image { imageData = arr }) x y = PixelCMYK16 (arr ! (baseIdx + 0))
(arr ! (baseIdx + 1))
(arr ! (baseIdx + 2))
(arr ! (baseIdx + 3))
where baseIdx = pixelBaseIndex image x y
# INLINE readPixel #
readPixel image@(MutableImage { mutableImageData = arr }) x y = do
rv <- arr `M.read` baseIdx
gv <- arr `M.read` (baseIdx + 1)
bv <- arr `M.read` (baseIdx + 2)
av <- arr `M.read` (baseIdx + 3)
return $ PixelCMYK16 rv gv bv av
where baseIdx = mutablePixelBaseIndex image x y
# INLINE writePixel #
writePixel image@(MutableImage { mutableImageData = arr }) x y (PixelCMYK16 rv gv bv av) = do
let baseIdx = mutablePixelBaseIndex image x y
(arr `M.write` (baseIdx + 0)) rv
(arr `M.write` (baseIdx + 1)) gv
(arr `M.write` (baseIdx + 2)) bv
(arr `M.write` (baseIdx + 3)) av
# INLINE unsafePixelAt #
unsafePixelAt v idx =
PixelCMYK16 (V.unsafeIndex v idx)
(V.unsafeIndex v $ idx + 1)
(V.unsafeIndex v $ idx + 2)
(V.unsafeIndex v $ idx + 3)
# INLINE unsafeReadPixel #
unsafeReadPixel vec idx =
PixelCMYK16 `liftM` M.unsafeRead vec idx
`ap` M.unsafeRead vec (idx + 1)
`ap` M.unsafeRead vec (idx + 2)
`ap` M.unsafeRead vec (idx + 3)
# INLINE unsafeWritePixel #
unsafeWritePixel v idx (PixelCMYK16 r g b a) =
M.unsafeWrite v idx r >> M.unsafeWrite v (idx + 1) g
>> M.unsafeWrite v (idx + 2) b
>> M.unsafeWrite v (idx + 3) a
instance ColorSpaceConvertible PixelCMYK16 PixelRGB16 where
convertPixel (PixelCMYK16 c m y k) =
PixelRGB16 (clampWord16 r) (clampWord16 g) (clampWord16 b)
where
clampWord16 = fromIntegral . (`unsafeShiftR` 16)
ik :: Int
ik = 65535 - fromIntegral k
r = (65535 - fromIntegral c) * ik
g = (65535 - fromIntegral m) * ik
b = (65535 - fromIntegral y) * ik
instance ColorPlane PixelCMYK16 PlaneCyan where
toComponentIndex _ _ = 0
instance ColorPlane PixelCMYK16 PlaneMagenta where
toComponentIndex _ _ = 1
instance ColorPlane PixelCMYK16 PlaneYellow where
toComponentIndex _ _ = 2
instance ColorPlane PixelCMYK16 PlaneBlack where
toComponentIndex _ _ = 3
-- | Perform a gamma correction for an image with HDR pixels.
^ Gamma value , should be between 0.5 and 3.0
-> Image PixelRGBF -- ^ Image to treat.
-> Image PixelRGBF
gammaCorrection gammaVal = pixelMap gammaCorrector
where gammaExponent = 1.0 / gammaVal
fixVal v = v ** gammaExponent
gammaCorrector (PixelRGBF r g b) =
PixelRGBF (fixVal r) (fixVal g) (fixVal b)
-- | Perform a tone mapping operation on an High dynamic range image.
toneMapping :: PixelF -- ^ Exposure parameter
-> Image PixelRGBF -- ^ Image to treat.
-> Image PixelRGBF
toneMapping exposure img = Image (imageWidth img) (imageHeight img) scaledData
where coeff = exposure * (exposure / maxBrightness + 1.0) / (exposure + 1.0);
maxBrightness = pixelFold (\luma _ _ px -> max luma $ computeLuma px) 0 img
scaledData = V.map (* coeff) $ imageData img
--------------------------------------------------
---- Packable pixel
--------------------------------------------------
-- | This typeclass exist for performance reason, it allow
-- to pack a pixel value to a simpler "primitive" data
-- type to allow faster writing to moemory.
class PackeablePixel a where
-- | Primitive type asociated to the current pixel
It 's Word32 for PixelRGBA8 for instance
type PackedRepresentation a
-- | The packing function, allowing to transform
-- to a primitive.
packPixel :: a -> PackedRepresentation a
-- | Inverse transformation, to speed up
-- reading
unpackPixel :: PackedRepresentation a -> a
instance PackeablePixel Pixel8 where
type PackedRepresentation Pixel8 = Pixel8
packPixel = id
# INLINE packPixel #
unpackPixel = id
{-# INLINE unpackPixel #-}
instance PackeablePixel Pixel16 where
type PackedRepresentation Pixel16 = Pixel16
packPixel = id
# INLINE packPixel #
unpackPixel = id
{-# INLINE unpackPixel #-}
instance PackeablePixel Pixel32 where
type PackedRepresentation Pixel32 = Pixel32
packPixel = id
# INLINE packPixel #
unpackPixel = id
{-# INLINE unpackPixel #-}
instance PackeablePixel PixelF where
type PackedRepresentation PixelF = PixelF
packPixel = id
# INLINE packPixel #
unpackPixel = id
{-# INLINE unpackPixel #-}
instance PackeablePixel PixelRGBA8 where
type PackedRepresentation PixelRGBA8 = Word32
# INLINE packPixel #
packPixel (PixelRGBA8 r g b a) =
(fi r `unsafeShiftL` (0 * bitCount)) .|.
(fi g `unsafeShiftL` (1 * bitCount)) .|.
(fi b `unsafeShiftL` (2 * bitCount)) .|.
(fi a `unsafeShiftL` (3 * bitCount))
where fi = fromIntegral
bitCount = 8
{-# INLINE unpackPixel #-}
unpackPixel w =
PixelRGBA8 (low w)
(low $ w `unsafeShiftR` bitCount)
(low $ w `unsafeShiftR` (2 * bitCount))
(low $ w `unsafeShiftR` (3 * bitCount))
where
low v = fromIntegral (v .&. 0xFF)
bitCount = 8
instance PackeablePixel PixelRGBA16 where
type PackedRepresentation PixelRGBA16 = Word64
# INLINE packPixel #
packPixel (PixelRGBA16 r g b a) =
(fi r `unsafeShiftL` (0 * bitCount)) .|.
(fi g `unsafeShiftL` (1 * bitCount)) .|.
(fi b `unsafeShiftL` (2 * bitCount)) .|.
(fi a `unsafeShiftL` (3 * bitCount))
where fi = fromIntegral
bitCount = 16
{-# INLINE unpackPixel #-}
unpackPixel w =
PixelRGBA16 (low w)
(low $ w `unsafeShiftR` bitCount)
(low $ w `unsafeShiftR` (2 * bitCount))
(low $ w `unsafeShiftR` (3 * bitCount))
where
low v = fromIntegral (v .&. 0xFFFF)
bitCount = 16
instance PackeablePixel PixelCMYK8 where
type PackedRepresentation PixelCMYK8 = Word32
# INLINE packPixel #
packPixel (PixelCMYK8 c m y k) =
(fi c `unsafeShiftL` (0 * bitCount)) .|.
(fi m `unsafeShiftL` (1 * bitCount)) .|.
(fi y `unsafeShiftL` (2 * bitCount)) .|.
(fi k `unsafeShiftL` (3 * bitCount))
where fi = fromIntegral
bitCount = 8
{-# INLINE unpackPixel #-}
unpackPixel w =
PixelCMYK8 (low w)
(low $ w `unsafeShiftR` bitCount)
(low $ w `unsafeShiftR` (2 * bitCount))
(low $ w `unsafeShiftR` (3 * bitCount))
where
low v = fromIntegral (v .&. 0xFF)
bitCount = 8
instance PackeablePixel PixelCMYK16 where
type PackedRepresentation PixelCMYK16 = Word64
# INLINE packPixel #
packPixel (PixelCMYK16 c m y k) =
(fi c `unsafeShiftL` (0 * bitCount)) .|.
(fi m `unsafeShiftL` (1 * bitCount)) .|.
(fi y `unsafeShiftL` (2 * bitCount)) .|.
(fi k `unsafeShiftL` (3 * bitCount))
where fi = fromIntegral
bitCount = 16
{-# INLINE unpackPixel #-}
unpackPixel w =
PixelCMYK16 (low w)
(low $ w `unsafeShiftR` bitCount)
(low $ w `unsafeShiftR` (2 * bitCount))
(low $ w `unsafeShiftR` (3 * bitCount))
where
low v = fromIntegral (v .&. 0xFFFF)
bitCount = 16
instance PackeablePixel PixelYA16 where
type PackedRepresentation PixelYA16 = Word32
# INLINE packPixel #
packPixel (PixelYA16 y a) =
(fi y `unsafeShiftL` (0 * bitCount)) .|.
(fi a `unsafeShiftL` (1 * bitCount))
where fi = fromIntegral
bitCount = 16
{-# INLINE unpackPixel #-}
unpackPixel w = PixelYA16 (low w) (low $ w `unsafeShiftR` bitCount)
where
low v = fromIntegral (v .&. 0xFFFF)
bitCount = 16
instance PackeablePixel PixelYA8 where
type PackedRepresentation PixelYA8 = Word16
# INLINE packPixel #
packPixel (PixelYA8 y a) =
(fi y `unsafeShiftL` (0 * bitCount)) .|.
(fi a `unsafeShiftL` (1 * bitCount))
where fi = fromIntegral
bitCount = 8
{-# INLINE unpackPixel #-}
unpackPixel w = PixelYA8 (low w) (low $ w `unsafeShiftR` bitCount)
where
low v = fromIntegral (v .&. 0xFF)
bitCount = 8
-- | This function will fill an image with a simple packeable
-- pixel. It will be faster than any unsafeWritePixel.
fillImageWith :: ( Pixel px, PackeablePixel px
, PrimMonad m
, M.Storable (PackedRepresentation px))
=> MutableImage (PrimState m) px -> px -> m ()
fillImageWith img px = M.set converted $ packPixel px
where
(ptr, s, s2) = M.unsafeToForeignPtr $ mutableImageData img
!packedPtr = castForeignPtr ptr
!converted =
M.unsafeFromForeignPtr packedPtr s (s2 `div` componentCount px)
| Fill a packeable pixel between two bounds .
unsafeWritePixelBetweenAt
:: ( PrimMonad m
, Pixel px, PackeablePixel px
, M.Storable (PackedRepresentation px))
=> MutableImage (PrimState m) px -- ^ Image to write into
-> px -- ^ Pixel to write
-> Int -- ^ Start index in pixel base component
-> Int -- ^ pixel count of pixel to write
-> m ()
unsafeWritePixelBetweenAt img px start count = M.set converted packed
where
!packed = packPixel px
!pixelData = mutableImageData img
!toSet = M.slice start count pixelData
(ptr, s, s2) = M.unsafeToForeignPtr toSet
!packedPtr = castForeignPtr ptr
!converted =
M.unsafeFromForeignPtr packedPtr s s2
-- | Read a packeable pixel from an image. Equivalent to
-- unsafeReadPixel
readPackedPixelAt :: forall m px.
( Pixel px, PackeablePixel px
, M.Storable (PackedRepresentation px)
, PrimMonad m
)
=> MutableImage (PrimState m) px -- ^ Image to read from
-> Int -- ^ Index in (PixelBaseComponent px) count
-> m px
# INLINE readPackedPixelAt #
readPackedPixelAt img idx = do
unpacked <- M.unsafeRead converted (idx `div` compCount)
return $ unpackPixel unpacked
where
!compCount = componentCount (undefined :: px)
(ptr, s, s2) = M.unsafeToForeignPtr $ mutableImageData img
!packedPtr = castForeignPtr ptr
!converted =
M.unsafeFromForeignPtr packedPtr s s2
-- | Write a packeable pixel into an image. equivalent to unsafeWritePixel.
writePackedPixelAt :: ( Pixel px, PackeablePixel px
, M.Storable (PackedRepresentation px)
, PrimMonad m
)
=> MutableImage (PrimState m) px -- ^ Image to write into
-> Int -- ^ Index in (PixelBaseComponent px) count
-> px -- ^ Pixel to write
-> m ()
# INLINE writePackedPixelAt #
writePackedPixelAt img idx px =
M.unsafeWrite converted (idx `div` compCount) packed
where
!packed = packPixel px
!compCount = componentCount px
(ptr, s, s2) = M.unsafeToForeignPtr $ mutableImageData img
!packedPtr = castForeignPtr ptr
!converted =
M.unsafeFromForeignPtr packedPtr s s2
{-# ANN module "HLint: ignore Reduce duplication" #-}
| null | https://raw.githubusercontent.com/Twinside/Juicy.Pixels/ab41b84403699a7f4d290685e690fbaff42ed95f/src/Codec/Picture/Types.hs | haskell | | Module provides basic types for image manipulation in the library.
# LANGUAGE BangPatterns #
# LANGUAGE CPP #
# LANGUAGE DeriveDataTypeable #
# LANGUAGE FlexibleContexts #
# LANGUAGE Rank2Types #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TypeFamilies #
# LANGUAGE TypeSynonymInstances #
* Types
** Image types
** Image functions
** Image Lenses
** Pixel types
* Type classes
$graph
* Helper functions
* Color plane extraction
| The main type of this package, one that most
functions work on, is Image.
Parameterized by the underlying pixel format it
forms a rigid type. If you wish to store images
Image is essentially a rectangular pixel buffer
of specified width and height. The coordinates are
assumed to start from the upper-left corner
| Width of the image in pixels
# UNPACK #
| Height of the image in pixels.
# UNPACK #
| Image pixel data. To extract pixels at a given position
you should use the helper functions.
Internally pixel data is stored as consecutively packed
lines from top to bottom, scanned from left to right
component within each pixel.
| Class used to describle plane present in the pixel
type. If a pixel has a plane description associated,
you can use the plane name to extract planes independently.
| Retrieve the index of the component in the
given pixel type.
| Define the plane for the red color component
| Define the plane for the green color component
| Define the plane for the blue color component
| Define the plane for the alpha (transparency) component
| Define the plane for the luma component
| Define the plane for the Cr component
| Define plane for the cyan component of the
CMYK color space.
| Define plane for the magenta component of the
CMYK color space.
| Define plane for the yellow component of the
CMYK color space.
| Define plane for the black component of
| Extract a color plane from an image given a present plane in the image
examples:
@
extractRedPlane :: Image PixelRGB8 -> Image Pixel8
extractRedPlane = extractComponent PlaneRed
@
| Extract a plane of an image. Returns the requested color
component as a greyscale image.
If you ask for a component out of bound, the `error` function will
be called.
^ Source image
| For any image with an alpha component (transparency),
drop it, returning a pure opaque image.
| Class modeling transparent pixel, should provide a method
to combine transparent pixels
| Just return the opaque pixel value
| access the transparency (alpha layer) of a given
transparent pixel type.
# DEPRECATED getTransparency "please use 'pixelOpacity' instead" #
| Image or pixel buffer, the coordinates are assumed to start
from the upper-left corner of the image, with the horizontal
| Width of the image in pixels
# UNPACK #
| Height of the image in pixels.
# UNPACK #
| The real image, to extract pixels at some position
you should use the helpers functions.
| `O(n)` Yield an immutable copy of an image by making a copy of it
| `O(n)` Yield a mutable copy of an image by making a copy of it.
| `O(1)` Unsafe convert an imutable image to an mutable one without copying.
The source image shouldn't be used after this operation.
| `O(1)` Unsafe convert a mutable image to an immutable one without copying.
The mutable image may not be used after this operation.
| Create a mutable image, filled with the given background color.
^ Width
^ Height
^ Background color
| Create a mutable image with garbage as content. All data
is uninitialized.
^ Width
^ Height
| Image type enumerating all predefined pixel types.
It enables loading and use of images of different
pixel types.
| A greyscale image.
| A greyscale HDR image
| An image in greyscale with an alpha channel.
| An image in true color.
| An image with HDR pixels
| An image in true color and an alpha channel.
| An image in the colorspace used by Jpeg images.
| An image in the colorspace CMYK
| Type used to expose a palette extracted during reading.
Use `palettedAsImage` to convert it to a palette usable for
writing.
| Number of element in pixels.
| Real data used by the palette.
| Convert a palette to an image. Used mainly for
backward compatibility.
| Describe an image and it's potential associated
palette. If no palette is present, fallback to a
| Helper function to help extract information from dynamic
image. To get the width of a dynamic image, you can use
the following snippet:
> dynWidth :: DynamicImage -> Int
| Equivalent of the `pixelMap` function for the dynamic images.
You can perform pixel colorspace independant operations with this
function.
For instance, if you want to extract a square crop of any image,
without caring about colorspace, you can use the following snippet.
>
> squareImage :: Pixel a => Image a -> Image a
greyscale pixels use plain numbers instead of a separate type.
Values are stored in the following order:
* Luminance
* Alpha
# UNPACK #
Luminance
# UNPACK #
Alpha value
| Pixel type storing 16bit Luminance (Y) and alpha (A) information.
Values are stored in the following order:
* Luminance
* Alpha
# UNPACK #
Luminance
# UNPACK #
Alpha value
Values are stored in the following order:
* Red
* Green
* Blue
# UNPACK #
Red
# UNPACK #
Green
* Y (Luminance)
* Cb
* Cr
* Black
# UNPACK #
# UNPACK #
# UNPACK #
# UNPACK #
Values are stored in the following order:
* Red
* Green
* Blue
# UNPACK #
Red
# UNPACK #
Green
Same value range and comments apply as for 'PixelF'.
Values are stored in the following order:
* Red
* Green
* Blue
# UNPACK #
Red
# UNPACK #
Green
Values are stored in the following order:
* Y (luminance)
* Cb
* Cr
# UNPACK #
Y luminance
# UNPACK #
Cr red difference
Values are stored in the following order:
* Cyan
* Magenta
* Yellow
* Black
# UNPACK #
Magenta
# UNPACK #
Yellow
# UNPACK #
Black
Values are stored in the following order:
* Cyan
* Magenta
* Yellow
* Black
# UNPACK #
Magenta
# UNPACK #
Yellow
# UNPACK #
Black
Values are stored in the following order:
* Red
* Green
* Blue
* Alpha
# UNPACK #
Red
# UNPACK #
Green
# UNPACK #
Alpha
Values are stored in the following order:
* Red
* Green
* Blue
* Alpha
# UNPACK #
Red
# UNPACK #
Green
# UNPACK #
Alpha
| Definition of pixels used in images. Each pixel has a color space, and a representative
component (Word8 or Float).
| Type of the pixel component, "classical" images
would have Word8 type as their PixelBaseComponent,
HDR image would have Float for instance
| Call the function for every component of the pixels.
For example for RGB pixels mixWith is declared like this:
> PixelRGB8 (f 0 ra rb) (f 1 ga gb) (f 2 ba bb)
| Extension of the `mixWith` which separate the treatment
of the color components of the alpha value (transparency component).
For pixel without alpha components, it is equivalent to mixWith.
^ Function for color component
^ Function for alpha component
| Return the opacity of a pixel, if the pixel has an
alpha layer, return the alpha value. If the pixel
doesn't have an alpha value, return a value
representing the opaqueness.
| Return the number of components of the pixel
| Apply a function to each component of a pixel.
If the color type possess an alpha (transparency channel),
it is treated like the other color components.
| Calculate the index for the begining of the pixel
| Calculate theindex for the begining of the pixel at position x y
| Extract a pixel at a given position, (x, y), the origin
is assumed to be at the corner top left, positive y to the
bottom of the image
| Same as pixelAt but for mutable images.
| Write a pixel in a mutable image at position x y
| Unsafe version of pixelAt, read a pixel at the given
index without bound checking (if possible).
The index is expressed in number (PixelBaseComponent a)
position without bound checking (if possible). The index
is expressed in number (PixelBaseComponent a)
given position without bound checking. This can be _really_ unsafe.
The index is expressed in number (PixelBaseComponent a)
| Implement upcasting for pixel types.
It is strongly recommended to overload promoteImage to keep
performance acceptable
| Convert a pixel type to another pixel type. This
operation should never lose any data.
| Change the underlying pixel type of an image by performing a full copy
of it.
| This class abstract colorspace conversion. This
| Helper function to convert a whole image by taking a
copy it.
^ Generating function, with `x` and `y` params.
^ Width in pixels
^ Height in pixels
| Create an image given a function to generate pixels.
The function will receive values from 0 to width-1 for the x parameter
left corner of the image, and (width-1, height-1) the lower right corner.
for example, to create a small gradient image:
> imageCreator :: String -> IO ()
^ Generating function, with `x` and `y` params.
^ Width in pixels
^ Height in pixels
| Create an image using a monadic initializer function.
The function will receive values from 0 to width-1 for the x parameter
left corner of the image, and (width-1, height-1) the lower right corner.
and for each line (0 to height - 1).
^ Image width
^ Image height
^ Generating functions
| Create an image given a function to generate pixels.
The function will receive values from 0 to width-1 for the x parameter
left corner of the image, and (width-1, height-1) the lower right corner.
and for each line (0 to height - 1).
^ Function taking the state, x and y
^ Initial state
^ Width in pixels
^ Height in pixels
| Fold over the pixel of an image with a raster scan order:
from top to bottom, left to right
# INLINE pixelFold #
| Fold over the pixel of an image with a raster scan order:
from top to bottom, left to right, carrying out a state
^ monadic mapping function
^ Initial state
^ Image to fold over
# INLINE pixelFoldM #
| Fold over the pixel of an image with a raster scan order:
from top to bottom, left to right. This functions is analog
to the foldMap from the 'Foldable' typeclass, but due to the
| `map` equivalent for an image, working at the pixel level.
Little example : a brightness function for an rgb image
> brightnessRGB8 :: Int -> Image PixelRGB8 -> Image PixelRGB8
> brightnessRGB8 add = pixelMap brightFunction
> where up v = fromIntegral (fromIntegral v + add)
> brightFunction (PixelRGB8 r g b) =
> PixelRGB8 (up r) (up g) (up b)
# SPECIALIZE INLINE pixelMap :: (PixelYCbCr8 -> PixelRGB8) -> Image PixelYCbCr8 -> Image PixelRGB8 #
# SPECIALIZE INLINE pixelMap :: (PixelRGB8 -> PixelRGB8) -> Image PixelRGB8 -> Image PixelRGB8 #
# SPECIALIZE INLINE pixelMap :: (Pixel8 -> PixelRGB8) -> Image Pixel8 -> Image PixelRGB8 #
# SPECIALIZE INLINE pixelMap :: (Pixel8 -> Pixel8) -> Image Pixel8 -> Image Pixel8 #
outside of this where block
| Helpers to embed a rankNTypes inside an Applicative
| Traversal in "raster" order, from left to right the top to bottom.
This traversal is matching pixelMap in spirit.
| Traversal providing the pixel position with it's value.
The traversal in raster order, from lef to right, then top
to bottom. The traversal match pixelMapXY in spirit.
| Just like `pixelMap` only the function takes the pixel coordinates as
additional parameters.
outside of this where block
| Combine, pixel by pixel and component by component
> averageBrightNess c1 c2 c3 = clamp $ toInt c1 + toInt c2 + toInt c3
> toInt :: a -> Int
> toInt = fromIntegral
> ziPixelComponent3 averageBrightNess img1 img2 img3
| Helper class to help extract a luma plane out
of an image or a pixel
| Compute the luminance part of a pixel
| Extract a luma plane out of an image. This
method is in the typeclass to help performant
implementation.
> jpegToGrayScale source dest
| Free promotion for identic pixel types
# INLINE promotePixel #
------------------------------------------------
-- Pixel8 instances
------------------------------------------------
# INLINE mixWith #
# INLINE componentCount #
# INLINE promotePixel #
# INLINE promotePixel #
# INLINE promotePixel #
# INLINE promotePixel #
# INLINE promotePixel #
# INLINE promotePixel #
------------------------------------------------
-- Pixel16 instances
------------------------------------------------
# INLINE mixWith #
# INLINE componentCount #
# INLINE promotePixel #
# INLINE promotePixel #
# INLINE promotePixel #
------------------------------------------------
-- Pixel32 instances
------------------------------------------------
# INLINE mixWith #
# INLINE componentCount #
------------------------------------------------
-- PixelF instances
------------------------------------------------
# INLINE mixWith #
# INLINE componentCount #
# INLINE promotePixel #
(c / 0.3) (c / 0.59) (c / 0.11)
------------------------------------------------
-- PixelYA8 instances
------------------------------------------------
# INLINE mixWith #
# INLINE componentCount #
# INLINE promotePixel #
# INLINE promotePixel #
# INLINE promotePixel #
------------------------------------------------
-- PixelYA16 instances
------------------------------------------------
# INLINE mixWith #
# INLINE componentCount #
# INLINE promotePixel #
# INLINE promotePixel #
------------------------------------------------
PixelRGBF instances
------------------------------------------------
# INLINE mixWith #
# INLINE componentCount #
------------------------------------------------
PixelRGB16 instances
------------------------------------------------
# INLINE mixWith #
# INLINE componentCount #
# INLINE promotePixel #
------------------------------------------------
-- PixelRGB8 instances
------------------------------------------------
# INLINE mixWith #
# INLINE componentCount #
# INLINE promotePixel #
# INLINE promotePixel #
# INLINE promotePixel #
# INLINE promotePixel #
------------------------------------------------
PixelRGBA8 instances
------------------------------------------------
# INLINE mixWith #
# INLINE componentCount #
# INLINE promotePixel #
------------------------------------------------
-- PixelRGBA16 instances
------------------------------------------------
# INLINE mixWith #
# INLINE componentCount #
------------------------------------------------
instances
------------------------------------------------
# INLINE mixWith #
# INLINE componentCount #
------------------------------------------------
-- PixelCMYK8 instances
------------------------------------------------
# INLINE mixWith #
# INLINE componentCount #
------------------------------------------------
-- PixelYCbCrK8 instances
------------------------------------------------
# INLINE mixWith #
# INLINE componentCount #
# SPECIALIZE integralRGBToCMYK :: (Word8 -> Word8 -> Word8 -> Word8 -> b)
-> (Word8, Word8, Word8) -> b #
/Note/ - 32bit precision is not supported. Make sure to adjust implementation if ever
^ Pixel building function
^ RGB sample
^ Resulting sample
------------------------------------------------
-- PixelCMYK16 instances
------------------------------------------------
# INLINE mixWith #
# INLINE componentCount #
| Perform a gamma correction for an image with HDR pixels.
^ Image to treat.
| Perform a tone mapping operation on an High dynamic range image.
^ Exposure parameter
^ Image to treat.
------------------------------------------------
-- Packable pixel
------------------------------------------------
| This typeclass exist for performance reason, it allow
to pack a pixel value to a simpler "primitive" data
type to allow faster writing to moemory.
| Primitive type asociated to the current pixel
| The packing function, allowing to transform
to a primitive.
| Inverse transformation, to speed up
reading
# INLINE unpackPixel #
# INLINE unpackPixel #
# INLINE unpackPixel #
# INLINE unpackPixel #
# INLINE unpackPixel #
# INLINE unpackPixel #
# INLINE unpackPixel #
# INLINE unpackPixel #
# INLINE unpackPixel #
# INLINE unpackPixel #
| This function will fill an image with a simple packeable
pixel. It will be faster than any unsafeWritePixel.
^ Image to write into
^ Pixel to write
^ Start index in pixel base component
^ pixel count of pixel to write
| Read a packeable pixel from an image. Equivalent to
unsafeReadPixel
^ Image to read from
^ Index in (PixelBaseComponent px) count
| Write a packeable pixel into an image. equivalent to unsafeWritePixel.
^ Image to write into
^ Index in (PixelBaseComponent px) count
^ Pixel to write
# ANN module "HLint: ignore Reduce duplication" # |
# LANGUAGE FlexibleInstances #
# LANGUAGE FunctionalDependencies #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE UndecidableInstances #
Defined types are used to store all of those _ _ _ _
Image( .. )
, MutableImage( .. )
, DynamicImage( .. )
, PalettedImage( .. )
, Palette
, Palette'( .. )
, createMutableImage
, newMutableImage
, freezeImage
, unsafeFreezeImage
, thawImage
, unsafeThawImage
, Traversal
, imagePixels
, imageIPixels
, Pixel8
, Pixel16
, Pixel32
, PixelF
, PixelYA8( .. )
, PixelYA16( .. )
, PixelRGB8( .. )
, PixelRGB16( .. )
, PixelRGBF( .. )
, PixelRGBA8( .. )
, PixelRGBA16( .. )
, PixelCMYK8( .. )
, PixelCMYK16( .. )
, PixelYCbCr8( .. )
, PixelYCbCrK8( .. )
, ColorConvertible( .. )
, Pixel(..)
, ColorSpaceConvertible( .. )
, LumaPlaneExtractable( .. )
, TransparentPixel( .. )
, pixelMap
, pixelMapXY
, pixelFold
, pixelFoldM
, pixelFoldMap
, dynamicMap
, dynamicPixelMap
, palettedToTrueColor
, palettedAsImage
, dropAlphaLayer
, withImage
, zipPixelComponent3
, generateImage
, generateFoldImage
, gammaCorrection
, toneMapping
, ColorPlane ( )
, PlaneRed( .. )
, PlaneGreen( .. )
, PlaneBlue( .. )
, PlaneAlpha( .. )
, PlaneLuma( .. )
, PlaneCr( .. )
, PlaneCb( .. )
, PlaneCyan( .. )
, PlaneMagenta( .. )
, PlaneYellow( .. )
, PlaneBlack( .. )
, extractComponent
, unsafeExtractComponent
* writing ( unsafe but faster )
, PackeablePixel( .. )
, fillImageWith
, readPackedPixelAt
, writePackedPixelAt
, unsafeWritePixelBetweenAt
) where
#if !MIN_VERSION_base(4,8,0)
import Data.Monoid( Monoid, mempty )
import Control.Applicative( Applicative, pure, (<*>), (<$>) )
#endif
#if !MIN_VERSION_base(4,11,0)
import Data.Monoid( (<>) )
#endif
import Control.Monad( foldM, liftM, ap )
import Control.DeepSeq( NFData( .. ) )
import Control.Monad.ST( ST, runST )
import Control.Monad.Primitive ( PrimMonad, PrimState )
import Foreign.ForeignPtr( castForeignPtr )
import Foreign.Storable ( Storable )
import Data.Bits( unsafeShiftL, unsafeShiftR, (.|.), (.&.) )
import Data.Typeable ( Typeable )
import Data.Word( Word8, Word16, Word32, Word64 )
import Data.Vector.Storable ( (!) )
import qualified Data.Vector.Storable as V
import qualified Data.Vector.Storable.Mutable as M
#include "ConvGraph.hs"
of different or unknown pixel formats use ' DynamicImage ' .
of the image , with the horizontal position first
and vertical second .
data Image a = Image
within individual lines , from first to last color
, imageData :: V.Vector (PixelBaseComponent a)
}
deriving (Typeable)
instance (Eq (PixelBaseComponent a), Storable (PixelBaseComponent a))
=> Eq (Image a) where
a == b = imageWidth a == imageWidth b &&
imageHeight a == imageHeight b &&
imageData a == imageData b
| Type for the palette used in Gif & PNG files .
type Palette = Image PixelRGB8
class ColorPlane pixel planeToken where
toComponentIndex :: pixel -> planeToken -> Int
data PlaneRed = PlaneRed
deriving (Typeable)
data PlaneGreen = PlaneGreen
deriving (Typeable)
data PlaneBlue = PlaneBlue
deriving (Typeable)
data PlaneAlpha = PlaneAlpha
deriving (Typeable)
data PlaneLuma = PlaneLuma
deriving (Typeable)
data PlaneCr = PlaneCr
deriving (Typeable)
| Define the plane for the Cb component
data PlaneCb = PlaneCb
deriving (Typeable)
data PlaneCyan = PlaneCyan
deriving (Typeable)
data PlaneMagenta = PlaneMagenta
deriving (Typeable)
data PlaneYellow = PlaneYellow
deriving (Typeable)
the CMYK color space .
data PlaneBlack = PlaneBlack
deriving (Typeable)
extractComponent :: forall px plane. ( Pixel px
, Pixel (PixelBaseComponent px)
, PixelBaseComponent (PixelBaseComponent px)
~ PixelBaseComponent px
, ColorPlane px plane )
=> plane -> Image px -> Image (PixelBaseComponent px)
extractComponent plane = unsafeExtractComponent idx
where idx = toComponentIndex (undefined :: px) plane
unsafeExtractComponent :: forall a
. ( Pixel a
, Pixel (PixelBaseComponent a)
, PixelBaseComponent (PixelBaseComponent a)
~ PixelBaseComponent a)
^ The component index , beginning at 0 ending at ( componentCount - 1 )
-> Image (PixelBaseComponent a)
unsafeExtractComponent comp img@(Image { imageWidth = w, imageHeight = h })
| comp >= padd = error $ "extractComponent : invalid component index ("
++ show comp ++ ", max:" ++ show padd ++ ")"
| otherwise = Image { imageWidth = w, imageHeight = h, imageData = plane }
where plane = stride img padd comp
padd = componentCount (undefined :: a)
dropAlphaLayer :: (TransparentPixel a b) => Image a -> Image b
dropAlphaLayer = pixelMap dropTransparency
class (Pixel a, Pixel b) => TransparentPixel a b | a -> b where
dropTransparency :: a -> b
getTransparency :: a -> PixelBaseComponent a
instance TransparentPixel PixelRGBA8 PixelRGB8 where
# INLINE dropTransparency #
dropTransparency (PixelRGBA8 r g b _) = PixelRGB8 r g b
# INLINE getTransparency #
getTransparency (PixelRGBA8 _ _ _ a) = a
lineFold :: (Monad m) => a -> Int -> (a -> Int -> m a) -> m a
# INLINE lineFold #
lineFold initial count f = go 0 initial
where go n acc | n >= count = return acc
go n acc = f acc n >>= go (n + 1)
stride :: (Storable (PixelBaseComponent a))
=> Image a -> Int -> Int -> V.Vector (PixelBaseComponent a)
stride Image { imageWidth = w, imageHeight = h, imageData = array }
padd firstComponent = runST $ do
let cell_count = w * h
outArray <- M.new cell_count
let go writeIndex _ | writeIndex >= cell_count = return ()
go writeIndex readIndex = do
(outArray `M.unsafeWrite` writeIndex) $ array `V.unsafeIndex` readIndex
go (writeIndex + 1) $ readIndex + padd
go 0 firstComponent
V.unsafeFreeze outArray
instance NFData (Image a) where
rnf (Image width height dat) = width `seq`
height `seq`
dat `seq`
()
position first , then the vertical one . The image can be transformed in place .
data MutableImage s a = MutableImage
, mutableImageData :: M.STVector s (PixelBaseComponent a)
}
deriving (Typeable)
freezeImage :: (Storable (PixelBaseComponent px), PrimMonad m)
=> MutableImage (PrimState m) px -> m (Image px)
freezeImage (MutableImage w h d) = Image w h `liftM` V.freeze d
thawImage :: (Storable (PixelBaseComponent px), PrimMonad m)
=> Image px -> m (MutableImage (PrimState m) px)
thawImage (Image w h d) = MutableImage w h `liftM` V.thaw d
unsafeThawImage :: (Storable (PixelBaseComponent px), PrimMonad m)
=> Image px -> m (MutableImage (PrimState m) px)
# NOINLINE unsafeThawImage #
unsafeThawImage (Image w h d) = MutableImage w h `liftM` V.unsafeThaw d
unsafeFreezeImage :: (Storable (PixelBaseComponent a), PrimMonad m)
=> MutableImage (PrimState m) a -> m (Image a)
unsafeFreezeImage (MutableImage w h d) = Image w h `liftM` V.unsafeFreeze d
createMutableImage :: (Pixel px, PrimMonad m)
-> m (MutableImage (PrimState m) px)
createMutableImage width height background =
generateMutableImage (\_ _ -> background) width height
newMutableImage :: forall px m. (Pixel px, PrimMonad m)
-> m (MutableImage (PrimState m) px)
newMutableImage w h = MutableImage w h `liftM` M.new (w * h * compCount)
where compCount = componentCount (undefined :: px)
instance NFData (MutableImage s a) where
rnf (MutableImage width height dat) = width `seq`
height `seq`
dat `seq`
()
data DynamicImage =
ImageY8 (Image Pixel8)
| A greyscale image with 16bit components
| ImageY16 (Image Pixel16)
| A greyscale image with 32bit components
| ImageY32 (Image Pixel32)
| ImageYF (Image PixelF)
| ImageYA8 (Image PixelYA8)
| An image in greyscale with alpha channel on 16 bits .
| ImageYA16 (Image PixelYA16)
| ImageRGB8 (Image PixelRGB8)
| An image in true color with 16bit depth .
| ImageRGB16 (Image PixelRGB16)
| ImageRGBF (Image PixelRGBF)
| ImageRGBA8 (Image PixelRGBA8)
| A true color image with alpha on 16 bits .
| ImageRGBA16 (Image PixelRGBA16)
| ImageYCbCr8 (Image PixelYCbCr8)
| ImageCMYK8 (Image PixelCMYK8)
| An image in the colorspace CMYK and 16 bits precision
| ImageCMYK16 (Image PixelCMYK16)
deriving (Eq, Typeable)
data Palette' px = Palette'
_paletteSize :: !Int
, _paletteData :: !(V.Vector (PixelBaseComponent px))
}
deriving Typeable
palettedAsImage :: Palette' px -> Image px
palettedAsImage p = Image (_paletteSize p) 1 $ _paletteData p
DynamicImage
data PalettedImage
^ Fallback
| PalettedY8 (Image Pixel8) (Palette' Pixel8)
| PalettedRGB8 (Image Pixel8) (Palette' PixelRGB8)
| PalettedRGBA8 (Image Pixel8) (Palette' PixelRGBA8)
| PalettedRGB16 (Image Pixel8) (Palette' PixelRGB16)
deriving (Typeable)
| Flatten a PalettedImage to a DynamicImage
palettedToTrueColor :: PalettedImage -> DynamicImage
palettedToTrueColor img = case img of
TrueColorImage d -> d
PalettedY8 i p -> ImageY8 $ toTrueColor 1 (_paletteData p) i
PalettedRGB8 i p -> ImageRGB8 $ toTrueColor 3 (_paletteData p) i
PalettedRGBA8 i p -> ImageRGBA8 $ toTrueColor 4 (_paletteData p) i
PalettedRGB16 i p -> ImageRGB16 $ toTrueColor 3 (_paletteData p) i
where
toTrueColor c vec = pixelMap (unsafePixelAt vec . (c *) . fromIntegral)
> dynWidth img = dynamicMap
dynamicMap :: (forall pixel . (Pixel pixel) => Image pixel -> a)
-> DynamicImage -> a
dynamicMap f (ImageY8 i) = f i
dynamicMap f (ImageY16 i) = f i
dynamicMap f (ImageY32 i) = f i
dynamicMap f (ImageYF i) = f i
dynamicMap f (ImageYA8 i) = f i
dynamicMap f (ImageYA16 i) = f i
dynamicMap f (ImageRGB8 i) = f i
dynamicMap f (ImageRGB16 i) = f i
dynamicMap f (ImageRGBF i) = f i
dynamicMap f (ImageRGBA8 i) = f i
dynamicMap f (ImageRGBA16 i) = f i
dynamicMap f (ImageYCbCr8 i) = f i
dynamicMap f (ImageCMYK8 i) = f i
dynamicMap f (ImageCMYK16 i) = f i
> dynSquare : : DynamicImage - > DynamicImage
> dynSquare = dynamicPixelMap squareImage
> squareImage img = generateImage ( \x y - > pixelAt img x y ) edge edge
> where edge = min ( imageWidth img ) ( imageHeight img )
dynamicPixelMap :: (forall pixel . (Pixel pixel) => Image pixel -> Image pixel)
-> DynamicImage -> DynamicImage
dynamicPixelMap f = aux
where
aux (ImageY8 i) = ImageY8 (f i)
aux (ImageY16 i) = ImageY16 (f i)
aux (ImageY32 i) = ImageY32 (f i)
aux (ImageYF i) = ImageYF (f i)
aux (ImageYA8 i) = ImageYA8 (f i)
aux (ImageYA16 i) = ImageYA16 (f i)
aux (ImageRGB8 i) = ImageRGB8 (f i)
aux (ImageRGB16 i) = ImageRGB16 (f i)
aux (ImageRGBF i) = ImageRGBF (f i)
aux (ImageRGBA8 i) = ImageRGBA8 (f i)
aux (ImageRGBA16 i) = ImageRGBA16 (f i)
aux (ImageYCbCr8 i) = ImageYCbCr8 (f i)
aux (ImageCMYK8 i) = ImageCMYK8 (f i)
aux (ImageCMYK16 i) = ImageCMYK16 (f i)
instance NFData DynamicImage where
rnf (ImageY8 img) = rnf img
rnf (ImageY16 img) = rnf img
rnf (ImageY32 img) = rnf img
rnf (ImageYF img) = rnf img
rnf (ImageYA8 img) = rnf img
rnf (ImageYA16 img) = rnf img
rnf (ImageRGB8 img) = rnf img
rnf (ImageRGB16 img) = rnf img
rnf (ImageRGBF img) = rnf img
rnf (ImageRGBA8 img) = rnf img
rnf (ImageRGBA16 img) = rnf img
rnf (ImageYCbCr8 img) = rnf img
rnf (ImageCMYK8 img) = rnf img
rnf (ImageCMYK16 img) = rnf img
| Type alias for 8bit greyscale pixels . For simplicity ,
type Pixel8 = Word8
| Type alias for 16bit greyscale pixels .
type Pixel16 = Word16
| Type alias for 32bit greyscale pixels .
type Pixel32 = Word32
| Type alias for 32bit floating point greyscale pixels . The standard
bounded value range is mapped to the closed interval [ 0,1 ] i.e.
> map promotePixel [ 0 , 1 .. 255 : : Pixel8 ] = = [ 0/255 , 1/255 .. 1.0 : : PixelF ]
type PixelF = Float
| Pixel type storing 8bit Luminance ( Y ) and alpha ( A ) information .
deriving (Eq, Ord, Show, Typeable)
deriving (Eq, Ord, Show, Typeable)
| Classic pixel type storing 8bit red , green and blue ( RGB ) information .
Blue
deriving (Eq, Ord, Show, Typeable)
| Pixel type storing value for the YCCK color space :
deriving (Eq, Ord, Show, Typeable)
| Pixel type storing 16bit red , green and blue ( RGB ) information .
Blue
deriving (Eq, Ord, Show, Typeable)
| HDR pixel type storing floating point 32bit red , green and blue ( RGB ) information .
Blue
deriving (Eq, Ord, Show, Typeable)
| Pixel type storing 8bit luminance , blue difference and red difference ( YCbCr ) information .
Cb blue difference
deriving (Eq, Ord, Show, Typeable)
| Pixel type storing 8bit cyan , magenta , yellow and black ( CMYK ) information .
Cyan
deriving (Eq, Ord, Show, Typeable)
| Pixel type storing 16bit cyan , magenta , yellow and black ( CMYK ) information .
Cyan
deriving (Eq, Ord, Show, Typeable)
| Classical pixel type storing 8bit red , green , blue and alpha ( RGBA ) information .
Blue
deriving (Eq, Ord, Show, Typeable)
| Pixel type storing 16bit red , green , blue and alpha ( RGBA ) information .
Blue
deriving (Eq, Ord, Show, Typeable)
class ( Storable (PixelBaseComponent a)
, Num (PixelBaseComponent a), Eq a ) => Pixel a where
type PixelBaseComponent a :: *
> mixWith f ( ) ( PixelRGB8 rb gb bb ) =
mixWith :: (Int -> PixelBaseComponent a -> PixelBaseComponent a -> PixelBaseComponent a)
-> a -> a -> a
> mixWithAlpha f fa ( PixelRGBA8 ) ( PixelRGB8 rb gb bb ab ) =
> PixelRGBA8 ( f 0 ra rb ) ( f 1 ga gb ) ( f 2 ba bb ) ( )
mixWithAlpha :: (Int -> PixelBaseComponent a -> PixelBaseComponent a
-> (PixelBaseComponent a -> PixelBaseComponent a
-> a -> a -> a
# INLINE mixWithAlpha #
mixWithAlpha f _ = mixWith f
pixelOpacity :: a -> PixelBaseComponent a
componentCount :: a -> Int
colorMap :: (PixelBaseComponent a -> PixelBaseComponent a) -> a -> a
pixelBaseIndex :: Image a -> Int -> Int -> Int
pixelBaseIndex (Image { imageWidth = w }) x y =
(x + y * w) * componentCount (undefined :: a)
mutablePixelBaseIndex :: MutableImage s a -> Int -> Int -> Int
mutablePixelBaseIndex (MutableImage { mutableImageWidth = w }) x y =
(x + y * w) * componentCount (undefined :: a)
pixelAt :: Image a -> Int -> Int -> a
readPixel :: PrimMonad m => MutableImage (PrimState m) a -> Int -> Int -> m a
writePixel :: PrimMonad m => MutableImage (PrimState m) a -> Int -> Int -> a -> m ()
unsafePixelAt :: V.Vector (PixelBaseComponent a) -> Int -> a
| Unsafe version of readPixel , read a pixel at the given
unsafeReadPixel :: PrimMonad m => M.STVector (PrimState m) (PixelBaseComponent a) -> Int -> m a
| Unsafe version of writePixel , write a pixel at the
unsafeWritePixel :: PrimMonad m => M.STVector (PrimState m) (PixelBaseComponent a) -> Int -> a -> m ()
Minimal declaration of ` promotePixel ` .
class (Pixel a, Pixel b) => ColorConvertible a b where
promotePixel :: a -> b
promoteImage :: Image a -> Image b
promoteImage = pixelMap promotePixel
conversion can be lossy , which ColorConvertible can not
class (Pixel a, Pixel b) => ColorSpaceConvertible a b where
| Pass a pixel from a colorspace ( say RGB ) to the second one
( say YCbCr )
convertPixel :: a -> b
convertImage :: Image a -> Image b
convertImage = pixelMap convertPixel
generateMutableImage :: forall m px. (Pixel px, PrimMonad m)
-> m (MutableImage (PrimState m) px)
# INLINE generateMutableImage #
generateMutableImage f w h = MutableImage w h `liftM` generated where
compCount = componentCount (undefined :: px)
generated = do
arr <- M.new (w * h * compCount)
let lineGenerator _ !y | y >= h = return ()
lineGenerator !lineIdx y = column lineIdx 0
where column !idx !x | x >= w = lineGenerator idx $ y + 1
column idx x = do
unsafeWritePixel arr idx $ f x y
column (idx + compCount) $ x + 1
lineGenerator 0 0
return arr
and 0 to height-1 for the y parameter . The coordinates 0,0 are the upper
> imageCreator path = writePng path $ generateImage pixelRenderer 250 300
> where pixelRenderer x y = PixelRGB8 ( fromIntegral x ) ( fromIntegral y ) 128
generateImage :: forall px. (Pixel px)
-> Image px
# INLINE generateImage #
generateImage f w h = runST img where
img :: ST s (Image px)
img = generateMutableImage f w h >>= unsafeFreezeImage
and 0 to height-1 for the y parameter . The coordinates 0,0 are the upper
The function is called for each pixel in the line from left to right ( 0 to width - 1 )
withImage :: forall m pixel. (Pixel pixel, PrimMonad m)
-> m (Image pixel)
withImage width height pixelGenerator = do
let pixelComponentCount = componentCount (undefined :: pixel)
arr <- M.new (width * height * pixelComponentCount)
let mutImage = MutableImage
{ mutableImageWidth = width
, mutableImageHeight = height
, mutableImageData = arr
}
let pixelPositions = [(x, y) | y <- [0 .. height-1], x <- [0..width-1]]
sequence_ [pixelGenerator x y >>= unsafeWritePixel arr idx
| ((x,y), idx) <- zip pixelPositions [0, pixelComponentCount ..]]
unsafeFreezeImage mutImage
and 0 to height-1 for the y parameter . The coordinates 0,0 are the upper
the acc parameter is a user defined one .
The function is called for each pixel in the line from left to right ( 0 to width - 1 )
generateFoldImage :: forall a acc. (Pixel a)
-> (acc, Image a)
generateFoldImage f intialAcc w h =
(finalState, Image { imageWidth = w, imageHeight = h, imageData = generated })
where compCount = componentCount (undefined :: a)
(finalState, generated) = runST $ do
arr <- M.new (w * h * compCount)
let mutImage = MutableImage {
mutableImageWidth = w,
mutableImageHeight = h,
mutableImageData = arr }
foldResult <- foldM (\acc (x,y) -> do
let (acc', px) = f acc x y
writePixel mutImage x y px
return acc') intialAcc [(x,y) | y <- [0 .. h-1], x <- [0 .. w-1]]
frozen <- V.unsafeFreeze arr
return (foldResult, frozen)
pixelFold :: forall acc pixel. (Pixel pixel)
=> (acc -> Int -> Int -> pixel -> acc) -> acc -> Image pixel -> acc
pixelFold f initialAccumulator img@(Image { imageWidth = w, imageHeight = h }) =
columnFold 0 initialAccumulator 0
where
!compCount = componentCount (undefined :: pixel)
!vec = imageData img
lfold !y acc !x !idx
| x >= w = columnFold (y + 1) acc idx
| otherwise =
lfold y (f acc x y $ unsafePixelAt vec idx) (x + 1) (idx + compCount)
columnFold !y lineAcc !readIdx
| y >= h = lineAcc
| otherwise = lfold y lineAcc 0 readIdx
pixelFoldM :: (Pixel pixel, Monad m)
-> m acc
pixelFoldM action initialAccumulator img@(Image { imageWidth = w, imageHeight = h }) =
lineFold initialAccumulator h columnFold
where
pixelFolder y acc x = action acc x y $ pixelAt img x y
columnFold lineAcc y = lineFold lineAcc w (pixelFolder y)
Pixel constraint , Image can not be made an instance of it .
pixelFoldMap :: forall m px. (Pixel px, Monoid m) => (px -> m) -> Image px -> m
pixelFoldMap f Image { imageWidth = w, imageHeight = h, imageData = vec } = folder 0
where
compCount = componentCount (undefined :: px)
maxi = w * h * compCount
folder idx | idx >= maxi = mempty
folder idx = f (unsafePixelAt vec idx) <> folder (idx + compCount)
pixelMap :: forall a b. (Pixel a, Pixel b)
=> (a -> b) -> Image a -> Image b
# SPECIALIZE INLINE pixelMap : : ( PixelRGB8 - > ) - > Image PixelRGB8 - > Image PixelYCbCr8 #
# SPECIALIZE INLINE pixelMap : : ( PixelRGB8 - > PixelRGBA8 ) - > Image PixelRGB8 - > Image PixelRGBA8 #
# SPECIALIZE INLINE pixelMap : : ( PixelRGBA8 - > PixelRGBA8 ) - > Image PixelRGBA8 - > Image PixelRGBA8 #
pixelMap f Image { imageWidth = w, imageHeight = h, imageData = vec } =
Image w h pixels
where sourceComponentCount = componentCount (undefined :: a)
destComponentCount = componentCount (undefined :: b)
pixels = runST $ do
newArr <- M.new (w * h * destComponentCount)
let lineMapper _ _ y | y >= h = return ()
lineMapper readIdxLine writeIdxLine y = colMapper readIdxLine writeIdxLine 0
where colMapper readIdx writeIdx x
| x >= w = lineMapper readIdx writeIdx $ y + 1
| otherwise = do
unsafeWritePixel newArr writeIdx . f $ unsafePixelAt vec readIdx
colMapper (readIdx + sourceComponentCount)
(writeIdx + destComponentCount)
(x + 1)
lineMapper 0 0 0
unsafeFreeze avoids making a second copy and it will be
safe because newArray ca n't be referenced as a mutable array
V.unsafeFreeze newArr
newtype GenST a = GenST { genAction :: forall s. ST s (M.STVector s a) }
| Traversal type matching the definition in the Lens package .
type Traversal s t a b =
forall f. Applicative f => (a -> f b) -> s -> f t
writePx :: Pixel px
=> Int -> GenST (PixelBaseComponent px) -> px -> GenST (PixelBaseComponent px)
# INLINE writePx #
writePx idx act px = GenST $ do
vec <- genAction act
unsafeWritePixel vec idx px
return vec
freezeGenST :: Pixel px
=> Int -> Int -> GenST (PixelBaseComponent px) -> Image px
freezeGenST w h act =
Image w h (runST (genAction act >>= V.unsafeFreeze))
Since 3.2.4
imagePixels :: forall pxa pxb. (Pixel pxa, Pixel pxb)
=> Traversal (Image pxa) (Image pxb) pxa pxb
# INLINE imagePixels #
imagePixels f Image { imageWidth = w, imageHeight = h, imageData = vec } =
freezeGenST w h <$> pixels
where
sourceComponentCount = componentCount (undefined :: pxa)
destComponentCount = componentCount (undefined :: pxb)
maxi = w * h * sourceComponentCount
pixels =
go (pure $ GenST $ M.new (w * h * destComponentCount)) 0 0
go act readIdx _ | readIdx >= maxi = act
go act readIdx writeIdx =
go newAct (readIdx + sourceComponentCount) (writeIdx + destComponentCount)
where
px = f (unsafePixelAt vec readIdx)
newAct = writePx writeIdx <$> act <*> px
Since 3.2.4
imageIPixels :: forall pxa pxb. (Pixel pxa, Pixel pxb)
=> Traversal (Image pxa) (Image pxb) (Int, Int, pxa) pxb
# INLINE imageIPixels #
imageIPixels f Image { imageWidth = w, imageHeight = h, imageData = vec } =
freezeGenST w h <$> pixels
where
sourceComponentCount = componentCount (undefined :: pxa)
destComponentCount = componentCount (undefined :: pxb)
pixels =
lineMapper (pure $ GenST $ M.new (w * h * destComponentCount)) 0 0 0
lineMapper act _ _ y | y >= h = act
lineMapper act readIdxLine writeIdxLine y =
go act readIdxLine writeIdxLine 0
where
go cact readIdx writeIdx x
| x >= w = lineMapper cact readIdx writeIdx $ y + 1
| otherwise = do
let px = f (x, y, unsafePixelAt vec readIdx)
go (writePx writeIdx <$> cact <*> px)
(readIdx + sourceComponentCount)
(writeIdx + destComponentCount)
(x + 1)
pixelMapXY :: forall a b. (Pixel a, Pixel b)
=> (Int -> Int -> a -> b) -> Image a -> Image b
# SPECIALIZE INLINE pixelMapXY : : ( Int - > Int - > PixelYCbCr8 - > PixelRGB8 )
- > Image PixelYCbCr8 - > Image PixelRGB8 #
-> Image PixelYCbCr8 -> Image PixelRGB8 #-}
# SPECIALIZE INLINE pixelMapXY : : ( Int - > Int - > PixelRGB8 - > )
- > Image PixelRGB8 - > Image PixelYCbCr8 #
-> Image PixelRGB8 -> Image PixelYCbCr8 #-}
# SPECIALIZE INLINE pixelMapXY : : ( Int - > Int - > PixelRGB8 - > PixelRGB8 )
- > Image PixelRGB8 - > Image PixelRGB8 #
-> Image PixelRGB8 -> Image PixelRGB8 #-}
# SPECIALIZE INLINE pixelMapXY : : ( Int - > Int - > PixelRGB8 - > PixelRGBA8 )
- > Image PixelRGB8 - > Image PixelRGBA8 #
-> Image PixelRGB8 -> Image PixelRGBA8 #-}
# SPECIALIZE INLINE pixelMapXY : : ( Int - > Int - > PixelRGBA8 - > PixelRGBA8 )
- > Image PixelRGBA8 - > Image PixelRGBA8 #
-> Image PixelRGBA8 -> Image PixelRGBA8 #-}
# SPECIALIZE INLINE pixelMapXY : : ( Int - > Int - > Pixel8 - > PixelRGB8 )
- > Image Pixel8 - > Image PixelRGB8 #
-> Image Pixel8 -> Image PixelRGB8 #-}
pixelMapXY f Image { imageWidth = w, imageHeight = h, imageData = vec } =
Image w h pixels
where sourceComponentCount = componentCount (undefined :: a)
destComponentCount = componentCount (undefined :: b)
pixels = runST $ do
newArr <- M.new (w * h * destComponentCount)
let lineMapper _ _ y | y >= h = return ()
lineMapper readIdxLine writeIdxLine y = colMapper readIdxLine writeIdxLine 0
where colMapper readIdx writeIdx x
| x >= w = lineMapper readIdx writeIdx $ y + 1
| otherwise = do
unsafeWritePixel newArr writeIdx . f x y $ unsafePixelAt vec readIdx
colMapper (readIdx + sourceComponentCount)
(writeIdx + destComponentCount)
(x + 1)
lineMapper 0 0 0
unsafeFreeze avoids making a second copy and it will be
safe because newArray ca n't be referenced as a mutable array
V.unsafeFreeze newArr
the values of 3 different images . Usage example :
> where clamp = fromIntegral . min 0 . max 255
zipPixelComponent3
:: forall px. ( V.Storable (PixelBaseComponent px))
=> (PixelBaseComponent px -> PixelBaseComponent px -> PixelBaseComponent px
-> PixelBaseComponent px)
-> Image px -> Image px -> Image px -> Image px
# INLINE zipPixelComponent3 #
zipPixelComponent3 f i1@(Image { imageWidth = w, imageHeight = h }) i2 i3
| not isDimensionEqual = error "Different image size zipPairwisePixelComponent"
| otherwise = Image { imageWidth = w
, imageHeight = h
, imageData = V.zipWith3 f data1 data2 data3
}
where data1 = imageData i1
data2 = imageData i2
data3 = imageData i3
isDimensionEqual =
w == imageWidth i2 && w == imageWidth i3 &&
h == imageHeight i2 && h == imageHeight i3
class (Pixel a, Pixel (PixelBaseComponent a)) => LumaPlaneExtractable a where
computeLuma :: a -> PixelBaseComponent a
> jpegToGrayScale : : FilePath - > FilePath - > IO ( )
extractLumaPlane :: Image a -> Image (PixelBaseComponent a)
extractLumaPlane = pixelMap computeLuma
instance LumaPlaneExtractable Pixel8 where
# INLINE computeLuma #
computeLuma = id
extractLumaPlane = id
instance LumaPlaneExtractable Pixel16 where
# INLINE computeLuma #
computeLuma = id
extractLumaPlane = id
instance LumaPlaneExtractable Pixel32 where
# INLINE computeLuma #
computeLuma = id
extractLumaPlane = id
instance LumaPlaneExtractable PixelF where
# INLINE computeLuma #
computeLuma = id
extractLumaPlane = id
instance LumaPlaneExtractable PixelRGBF where
# INLINE computeLuma #
computeLuma (PixelRGBF r g b) =
0.3 * r + 0.59 * g + 0.11 * b
instance LumaPlaneExtractable PixelRGBA8 where
# INLINE computeLuma #
computeLuma (PixelRGBA8 r g b _) =
floor $ (0.3 :: Double) * fromIntegral r
+ 0.59 * fromIntegral g
+ 0.11 * fromIntegral b
instance LumaPlaneExtractable PixelYCbCr8 where
# INLINE computeLuma #
computeLuma (PixelYCbCr8 y _ _) = y
extractLumaPlane = extractComponent PlaneLuma
instance (Pixel a) => ColorConvertible a a where
promotePixel = id
# INLINE promoteImage #
promoteImage = id
instance Pixel Pixel8 where
type PixelBaseComponent Pixel8 = Word8
# INLINE pixelOpacity #
pixelOpacity = const maxBound
mixWith f = f 0
# INLINE colorMap #
colorMap f = f
componentCount _ = 1
# INLINE pixelAt #
pixelAt (Image { imageWidth = w, imageData = arr }) x y = arr ! (x + y * w)
# INLINE readPixel #
readPixel image@(MutableImage { mutableImageData = arr }) x y =
arr `M.read` mutablePixelBaseIndex image x y
# INLINE writePixel #
writePixel image@(MutableImage { mutableImageData = arr }) x y =
arr `M.write` mutablePixelBaseIndex image x y
# INLINE unsafePixelAt #
unsafePixelAt = V.unsafeIndex
# INLINE unsafeReadPixel #
unsafeReadPixel = M.unsafeRead
# INLINE unsafeWritePixel #
unsafeWritePixel = M.unsafeWrite
instance ColorConvertible Pixel8 PixelYA8 where
promotePixel c = PixelYA8 c 255
instance ColorConvertible Pixel8 PixelF where
promotePixel c = fromIntegral c / 255.0
instance ColorConvertible Pixel8 Pixel16 where
promotePixel c = fromIntegral c * 257
instance ColorConvertible Pixel8 PixelRGB8 where
promotePixel c = PixelRGB8 c c c
instance ColorConvertible Pixel8 PixelRGB16 where
promotePixel c = PixelRGB16 (fromIntegral c * 257) (fromIntegral c * 257) (fromIntegral c * 257)
instance ColorConvertible Pixel8 PixelRGBA8 where
promotePixel c = PixelRGBA8 c c c 255
instance Pixel Pixel16 where
type PixelBaseComponent Pixel16 = Word16
# INLINE pixelOpacity #
pixelOpacity = const maxBound
mixWith f = f 0
# INLINE colorMap #
colorMap f = f
componentCount _ = 1
# INLINE pixelAt #
pixelAt (Image { imageWidth = w, imageData = arr }) x y = arr ! (x + y * w)
# INLINE readPixel #
readPixel image@(MutableImage { mutableImageData = arr }) x y =
arr `M.read` mutablePixelBaseIndex image x y
# INLINE writePixel #
writePixel image@(MutableImage { mutableImageData = arr }) x y =
arr `M.write` mutablePixelBaseIndex image x y
# INLINE unsafePixelAt #
unsafePixelAt = V.unsafeIndex
# INLINE unsafeReadPixel #
unsafeReadPixel = M.unsafeRead
# INLINE unsafeWritePixel #
unsafeWritePixel = M.unsafeWrite
instance ColorConvertible Pixel16 PixelYA16 where
promotePixel c = PixelYA16 c maxBound
instance ColorConvertible Pixel16 PixelRGB16 where
promotePixel c = PixelRGB16 c c c
instance ColorConvertible Pixel16 PixelRGBA16 where
promotePixel c = PixelRGBA16 c c c maxBound
instance Pixel Pixel32 where
type PixelBaseComponent Pixel32 = Word32
# INLINE pixelOpacity #
pixelOpacity = const maxBound
mixWith f = f 0
# INLINE colorMap #
colorMap f = f
componentCount _ = 1
# INLINE pixelAt #
pixelAt (Image { imageWidth = w, imageData = arr }) x y = arr ! (x + y * w)
# INLINE readPixel #
readPixel image@(MutableImage { mutableImageData = arr }) x y =
arr `M.read` mutablePixelBaseIndex image x y
# INLINE writePixel #
writePixel image@(MutableImage { mutableImageData = arr }) x y =
arr `M.write` mutablePixelBaseIndex image x y
# INLINE unsafePixelAt #
unsafePixelAt = V.unsafeIndex
# INLINE unsafeReadPixel #
unsafeReadPixel = M.unsafeRead
# INLINE unsafeWritePixel #
unsafeWritePixel = M.unsafeWrite
instance Pixel PixelF where
type PixelBaseComponent PixelF = Float
# INLINE pixelOpacity #
pixelOpacity = const 1.0
mixWith f = f 0
# INLINE colorMap #
colorMap f = f
componentCount _ = 1
# INLINE pixelAt #
pixelAt (Image { imageWidth = w, imageData = arr }) x y =
arr ! (x + y * w)
# INLINE readPixel #
readPixel image@(MutableImage { mutableImageData = arr }) x y =
arr `M.read` mutablePixelBaseIndex image x y
# INLINE writePixel #
writePixel image@(MutableImage { mutableImageData = arr }) x y =
arr `M.write` mutablePixelBaseIndex image x y
# INLINE unsafePixelAt #
unsafePixelAt = V.unsafeIndex
# INLINE unsafeReadPixel #
unsafeReadPixel = M.unsafeRead
# INLINE unsafeWritePixel #
unsafeWritePixel = M.unsafeWrite
instance ColorConvertible PixelF PixelRGBF where
instance Pixel PixelYA8 where
type PixelBaseComponent PixelYA8 = Word8
# INLINE pixelOpacity #
pixelOpacity (PixelYA8 _ a) = a
mixWith f (PixelYA8 ya aa) (PixelYA8 yb ab) =
PixelYA8 (f 0 ya yb) (f 1 aa ab)
# INLINE colorMap #
colorMap f (PixelYA8 y a) = PixelYA8 (f y) (f a)
componentCount _ = 2
# INLINE pixelAt #
pixelAt image@(Image { imageData = arr }) x y =
PixelYA8 (arr ! (baseIdx + 0)) (arr ! (baseIdx + 1))
where baseIdx = pixelBaseIndex image x y
# INLINE readPixel #
readPixel image@(MutableImage { mutableImageData = arr }) x y = do
yv <- arr `M.read` baseIdx
av <- arr `M.read` (baseIdx + 1)
return $ PixelYA8 yv av
where baseIdx = mutablePixelBaseIndex image x y
# INLINE writePixel #
writePixel image@(MutableImage { mutableImageData = arr }) x y (PixelYA8 yv av) = do
let baseIdx = mutablePixelBaseIndex image x y
(arr `M.write` (baseIdx + 0)) yv
(arr `M.write` (baseIdx + 1)) av
# INLINE unsafePixelAt #
unsafePixelAt v idx =
PixelYA8 (V.unsafeIndex v idx) (V.unsafeIndex v $ idx + 1)
# INLINE unsafeReadPixel #
unsafeReadPixel vec idx =
PixelYA8 `liftM` M.unsafeRead vec idx `ap` M.unsafeRead vec (idx + 1)
# INLINE unsafeWritePixel #
unsafeWritePixel v idx (PixelYA8 y a) =
M.unsafeWrite v idx y >> M.unsafeWrite v (idx + 1) a
instance ColorConvertible PixelYA8 PixelRGB8 where
promotePixel (PixelYA8 y _) = PixelRGB8 y y y
instance ColorConvertible PixelYA8 PixelRGB16 where
promotePixel (PixelYA8 y _) = PixelRGB16 (fromIntegral y * 257) (fromIntegral y * 257) (fromIntegral y * 257)
instance ColorConvertible PixelYA8 PixelRGBA8 where
promotePixel (PixelYA8 y a) = PixelRGBA8 y y y a
instance ColorPlane PixelYA8 PlaneLuma where
toComponentIndex _ _ = 0
instance ColorPlane PixelYA8 PlaneAlpha where
toComponentIndex _ _ = 1
instance TransparentPixel PixelYA8 Pixel8 where
# INLINE dropTransparency #
dropTransparency (PixelYA8 y _) = y
# INLINE getTransparency #
getTransparency (PixelYA8 _ a) = a
instance LumaPlaneExtractable PixelYA8 where
# INLINE computeLuma #
computeLuma (PixelYA8 y _) = y
extractLumaPlane = extractComponent PlaneLuma
instance Pixel PixelYA16 where
type PixelBaseComponent PixelYA16 = Word16
# INLINE pixelOpacity #
pixelOpacity (PixelYA16 _ a) = a
mixWith f (PixelYA16 ya aa) (PixelYA16 yb ab) =
PixelYA16 (f 0 ya yb) (f 1 aa ab)
# INLINE mixWithAlpha #
mixWithAlpha f fa (PixelYA16 ya aa) (PixelYA16 yb ab) =
PixelYA16 (f 0 ya yb) (fa aa ab)
# INLINE colorMap #
colorMap f (PixelYA16 y a) = PixelYA16 (f y) (f a)
componentCount _ = 2
# INLINE pixelAt #
pixelAt image@(Image { imageData = arr }) x y = PixelYA16 (arr ! (baseIdx + 0))
(arr ! (baseIdx + 1))
where baseIdx = pixelBaseIndex image x y
# INLINE readPixel #
readPixel image@(MutableImage { mutableImageData = arr }) x y = do
yv <- arr `M.read` baseIdx
av <- arr `M.read` (baseIdx + 1)
return $ PixelYA16 yv av
where baseIdx = mutablePixelBaseIndex image x y
# INLINE writePixel #
writePixel image@(MutableImage { mutableImageData = arr }) x y (PixelYA16 yv av) = do
let baseIdx = mutablePixelBaseIndex image x y
(arr `M.write` (baseIdx + 0)) yv
(arr `M.write` (baseIdx + 1)) av
# INLINE unsafePixelAt #
unsafePixelAt v idx =
PixelYA16 (V.unsafeIndex v idx) (V.unsafeIndex v $ idx + 1)
# INLINE unsafeReadPixel #
unsafeReadPixel vec idx =
PixelYA16 `liftM` M.unsafeRead vec idx `ap` M.unsafeRead vec (idx + 1)
# INLINE unsafeWritePixel #
unsafeWritePixel v idx (PixelYA16 y a) =
M.unsafeWrite v idx y >> M.unsafeWrite v (idx + 1) a
instance ColorConvertible PixelYA16 PixelRGB16 where
promotePixel (PixelYA16 y _) = PixelRGB16 y y y
instance ColorConvertible PixelYA16 PixelRGBA16 where
promotePixel (PixelYA16 y a) = PixelRGBA16 y y y a
instance ColorPlane PixelYA16 PlaneLuma where
toComponentIndex _ _ = 0
instance ColorPlane PixelYA16 PlaneAlpha where
toComponentIndex _ _ = 1
instance TransparentPixel PixelYA16 Pixel16 where
# INLINE dropTransparency #
dropTransparency (PixelYA16 y _) = y
# INLINE getTransparency #
getTransparency (PixelYA16 _ a) = a
instance Pixel PixelRGBF where
type PixelBaseComponent PixelRGBF = PixelF
# INLINE pixelOpacity #
pixelOpacity = const 1.0
mixWith f (PixelRGBF ra ga ba) (PixelRGBF rb gb bb) =
PixelRGBF (f 0 ra rb) (f 1 ga gb) (f 2 ba bb)
# INLINE colorMap #
colorMap f (PixelRGBF r g b) = PixelRGBF (f r) (f g) (f b)
componentCount _ = 3
# INLINE pixelAt #
pixelAt image@(Image { imageData = arr }) x y = PixelRGBF (arr ! (baseIdx + 0))
(arr ! (baseIdx + 1))
(arr ! (baseIdx + 2))
where baseIdx = pixelBaseIndex image x y
# INLINE readPixel #
readPixel image@(MutableImage { mutableImageData = arr }) x y = do
rv <- arr `M.read` baseIdx
gv <- arr `M.read` (baseIdx + 1)
bv <- arr `M.read` (baseIdx + 2)
return $ PixelRGBF rv gv bv
where baseIdx = mutablePixelBaseIndex image x y
# INLINE writePixel #
writePixel image@(MutableImage { mutableImageData = arr }) x y (PixelRGBF rv gv bv) = do
let baseIdx = mutablePixelBaseIndex image x y
(arr `M.write` (baseIdx + 0)) rv
(arr `M.write` (baseIdx + 1)) gv
(arr `M.write` (baseIdx + 2)) bv
# INLINE unsafePixelAt #
unsafePixelAt v idx =
PixelRGBF (V.unsafeIndex v idx) (V.unsafeIndex v $ idx + 1) (V.unsafeIndex v $ idx + 2)
# INLINE unsafeReadPixel #
unsafeReadPixel vec idx =
PixelRGBF `liftM` M.unsafeRead vec idx
`ap` M.unsafeRead vec (idx + 1)
`ap` M.unsafeRead vec (idx + 2)
# INLINE unsafeWritePixel #
unsafeWritePixel v idx (PixelRGBF r g b) =
M.unsafeWrite v idx r >> M.unsafeWrite v (idx + 1) g
>> M.unsafeWrite v (idx + 2) b
instance ColorPlane PixelRGBF PlaneRed where
toComponentIndex _ _ = 0
instance ColorPlane PixelRGBF PlaneGreen where
toComponentIndex _ _ = 1
instance ColorPlane PixelRGBF PlaneBlue where
toComponentIndex _ _ = 2
instance Pixel PixelRGB16 where
type PixelBaseComponent PixelRGB16 = Pixel16
# INLINE pixelOpacity #
pixelOpacity = const maxBound
mixWith f (PixelRGB16 ra ga ba) (PixelRGB16 rb gb bb) =
PixelRGB16 (f 0 ra rb) (f 1 ga gb) (f 2 ba bb)
# INLINE colorMap #
colorMap f (PixelRGB16 r g b) = PixelRGB16 (f r) (f g) (f b)
componentCount _ = 3
# INLINE pixelAt #
pixelAt image@(Image { imageData = arr }) x y = PixelRGB16 (arr ! (baseIdx + 0))
(arr ! (baseIdx + 1))
(arr ! (baseIdx + 2))
where baseIdx = pixelBaseIndex image x y
# INLINE readPixel #
readPixel image@(MutableImage { mutableImageData = arr }) x y = do
rv <- arr `M.read` baseIdx
gv <- arr `M.read` (baseIdx + 1)
bv <- arr `M.read` (baseIdx + 2)
return $ PixelRGB16 rv gv bv
where baseIdx = mutablePixelBaseIndex image x y
# INLINE writePixel #
writePixel image@(MutableImage { mutableImageData = arr }) x y (PixelRGB16 rv gv bv) = do
let baseIdx = mutablePixelBaseIndex image x y
(arr `M.write` (baseIdx + 0)) rv
(arr `M.write` (baseIdx + 1)) gv
(arr `M.write` (baseIdx + 2)) bv
# INLINE unsafePixelAt #
unsafePixelAt v idx =
PixelRGB16 (V.unsafeIndex v idx) (V.unsafeIndex v $ idx + 1) (V.unsafeIndex v $ idx + 2)
# INLINE unsafeReadPixel #
unsafeReadPixel vec idx =
PixelRGB16 `liftM` M.unsafeRead vec idx
`ap` M.unsafeRead vec (idx + 1)
`ap` M.unsafeRead vec (idx + 2)
# INLINE unsafeWritePixel #
unsafeWritePixel v idx (PixelRGB16 r g b) =
M.unsafeWrite v idx r >> M.unsafeWrite v (idx + 1) g
>> M.unsafeWrite v (idx + 2) b
instance ColorPlane PixelRGB16 PlaneRed where
toComponentIndex _ _ = 0
instance ColorPlane PixelRGB16 PlaneGreen where
toComponentIndex _ _ = 1
instance ColorPlane PixelRGB16 PlaneBlue where
toComponentIndex _ _ = 2
instance ColorSpaceConvertible PixelRGB16 PixelCMYK16 where
# INLINE convertPixel #
convertPixel (PixelRGB16 r g b) = integralRGBToCMYK PixelCMYK16 (r, g, b)
instance ColorConvertible PixelRGB16 PixelRGBA16 where
promotePixel (PixelRGB16 r g b) = PixelRGBA16 r g b maxBound
instance LumaPlaneExtractable PixelRGB16 where
# INLINE computeLuma #
computeLuma (PixelRGB16 r g b) =
floor $ (0.3 :: Double) * fromIntegral r
+ 0.59 * fromIntegral g
+ 0.11 * fromIntegral b
instance Pixel PixelRGB8 where
type PixelBaseComponent PixelRGB8 = Word8
# INLINE pixelOpacity #
pixelOpacity = const maxBound
mixWith f (PixelRGB8 ra ga ba) (PixelRGB8 rb gb bb) =
PixelRGB8 (f 0 ra rb) (f 1 ga gb) (f 2 ba bb)
# INLINE colorMap #
colorMap f (PixelRGB8 r g b) = PixelRGB8 (f r) (f g) (f b)
componentCount _ = 3
# INLINE pixelAt #
pixelAt image@(Image { imageData = arr }) x y = PixelRGB8 (arr ! (baseIdx + 0))
(arr ! (baseIdx + 1))
(arr ! (baseIdx + 2))
where baseIdx = pixelBaseIndex image x y
# INLINE readPixel #
readPixel image@(MutableImage { mutableImageData = arr }) x y = do
rv <- arr `M.read` baseIdx
gv <- arr `M.read` (baseIdx + 1)
bv <- arr `M.read` (baseIdx + 2)
return $ PixelRGB8 rv gv bv
where baseIdx = mutablePixelBaseIndex image x y
# INLINE writePixel #
writePixel image@(MutableImage { mutableImageData = arr }) x y (PixelRGB8 rv gv bv) = do
let baseIdx = mutablePixelBaseIndex image x y
(arr `M.write` (baseIdx + 0)) rv
(arr `M.write` (baseIdx + 1)) gv
(arr `M.write` (baseIdx + 2)) bv
# INLINE unsafePixelAt #
unsafePixelAt v idx =
PixelRGB8 (V.unsafeIndex v idx) (V.unsafeIndex v $ idx + 1) (V.unsafeIndex v $ idx + 2)
# INLINE unsafeReadPixel #
unsafeReadPixel vec idx =
PixelRGB8 `liftM` M.unsafeRead vec idx
`ap` M.unsafeRead vec (idx + 1)
`ap` M.unsafeRead vec (idx + 2)
# INLINE unsafeWritePixel #
unsafeWritePixel v idx (PixelRGB8 r g b) =
M.unsafeWrite v idx r >> M.unsafeWrite v (idx + 1) g
>> M.unsafeWrite v (idx + 2) b
instance ColorConvertible PixelRGB8 PixelRGBA8 where
promotePixel (PixelRGB8 r g b) = PixelRGBA8 r g b maxBound
instance ColorConvertible PixelRGB8 PixelRGBF where
promotePixel (PixelRGB8 r g b) = PixelRGBF (toF r) (toF g) (toF b)
where toF v = fromIntegral v / 255.0
instance ColorConvertible PixelRGB8 PixelRGB16 where
promotePixel (PixelRGB8 r g b) = PixelRGB16 (promotePixel r) (promotePixel g) (promotePixel b)
instance ColorConvertible PixelRGB8 PixelRGBA16 where
promotePixel (PixelRGB8 r g b) = PixelRGBA16 (promotePixel r) (promotePixel g) (promotePixel b) maxBound
instance ColorPlane PixelRGB8 PlaneRed where
toComponentIndex _ _ = 0
instance ColorPlane PixelRGB8 PlaneGreen where
toComponentIndex _ _ = 1
instance ColorPlane PixelRGB8 PlaneBlue where
toComponentIndex _ _ = 2
instance LumaPlaneExtractable PixelRGB8 where
# INLINE computeLuma #
computeLuma (PixelRGB8 r g b) =
floor $ (0.3 :: Double) * fromIntegral r
+ 0.59 * fromIntegral g
+ 0.11 * fromIntegral b
instance Pixel PixelRGBA8 where
type PixelBaseComponent PixelRGBA8 = Word8
# INLINE pixelOpacity #
pixelOpacity (PixelRGBA8 _ _ _ a) = a
mixWith f (PixelRGBA8 ra ga ba aa) (PixelRGBA8 rb gb bb ab) =
PixelRGBA8 (f 0 ra rb) (f 1 ga gb) (f 2 ba bb) (f 3 aa ab)
# INLINE mixWithAlpha #
mixWithAlpha f fa (PixelRGBA8 ra ga ba aa) (PixelRGBA8 rb gb bb ab) =
PixelRGBA8 (f 0 ra rb) (f 1 ga gb) (f 2 ba bb) (fa aa ab)
# INLINE colorMap #
colorMap f (PixelRGBA8 r g b a) = PixelRGBA8 (f r) (f g) (f b) (f a)
componentCount _ = 4
# INLINE pixelAt #
pixelAt image@(Image { imageData = arr }) x y = PixelRGBA8 (arr ! (baseIdx + 0))
(arr ! (baseIdx + 1))
(arr ! (baseIdx + 2))
(arr ! (baseIdx + 3))
where baseIdx = pixelBaseIndex image x y
# INLINE readPixel #
readPixel image@(MutableImage { mutableImageData = arr }) x y = do
rv <- arr `M.read` baseIdx
gv <- arr `M.read` (baseIdx + 1)
bv <- arr `M.read` (baseIdx + 2)
av <- arr `M.read` (baseIdx + 3)
return $ PixelRGBA8 rv gv bv av
where baseIdx = mutablePixelBaseIndex image x y
# INLINE writePixel #
writePixel image@(MutableImage { mutableImageData = arr }) x y (PixelRGBA8 rv gv bv av) = do
let baseIdx = mutablePixelBaseIndex image x y
(arr `M.write` (baseIdx + 0)) rv
(arr `M.write` (baseIdx + 1)) gv
(arr `M.write` (baseIdx + 2)) bv
(arr `M.write` (baseIdx + 3)) av
# INLINE unsafePixelAt #
unsafePixelAt v idx =
PixelRGBA8 (V.unsafeIndex v idx)
(V.unsafeIndex v $ idx + 1)
(V.unsafeIndex v $ idx + 2)
(V.unsafeIndex v $ idx + 3)
# INLINE unsafeReadPixel #
unsafeReadPixel vec idx =
PixelRGBA8 `liftM` M.unsafeRead vec idx
`ap` M.unsafeRead vec (idx + 1)
`ap` M.unsafeRead vec (idx + 2)
`ap` M.unsafeRead vec (idx + 3)
# INLINE unsafeWritePixel #
unsafeWritePixel v idx (PixelRGBA8 r g b a) =
M.unsafeWrite v idx r >> M.unsafeWrite v (idx + 1) g
>> M.unsafeWrite v (idx + 2) b
>> M.unsafeWrite v (idx + 3) a
instance ColorConvertible PixelRGBA8 PixelRGBA16 where
promotePixel (PixelRGBA8 r g b a) = PixelRGBA16 (promotePixel r) (promotePixel g) (promotePixel b) (promotePixel a)
instance ColorPlane PixelRGBA8 PlaneRed where
toComponentIndex _ _ = 0
instance ColorPlane PixelRGBA8 PlaneGreen where
toComponentIndex _ _ = 1
instance ColorPlane PixelRGBA8 PlaneBlue where
toComponentIndex _ _ = 2
instance ColorPlane PixelRGBA8 PlaneAlpha where
toComponentIndex _ _ = 3
instance Pixel PixelRGBA16 where
type PixelBaseComponent PixelRGBA16 = Pixel16
# INLINE pixelOpacity #
pixelOpacity (PixelRGBA16 _ _ _ a) = a
mixWith f (PixelRGBA16 ra ga ba aa) (PixelRGBA16 rb gb bb ab) =
PixelRGBA16 (f 0 ra rb) (f 1 ga gb) (f 2 ba bb) (f 3 aa ab)
# INLINE mixWithAlpha #
mixWithAlpha f fa (PixelRGBA16 ra ga ba aa) (PixelRGBA16 rb gb bb ab) =
PixelRGBA16 (f 0 ra rb) (f 1 ga gb) (f 2 ba bb) (fa aa ab)
# INLINE colorMap #
colorMap f (PixelRGBA16 r g b a) = PixelRGBA16 (f r) (f g) (f b) (f a)
componentCount _ = 4
# INLINE pixelAt #
pixelAt image@(Image { imageData = arr }) x y =
PixelRGBA16 (arr ! (baseIdx + 0)) (arr ! (baseIdx + 1))
(arr ! (baseIdx + 2)) (arr ! (baseIdx + 3))
where baseIdx = pixelBaseIndex image x y
# INLINE readPixel #
readPixel image@(MutableImage { mutableImageData = arr }) x y = do
rv <- arr `M.read` baseIdx
gv <- arr `M.read` (baseIdx + 1)
bv <- arr `M.read` (baseIdx + 2)
av <- arr `M.read` (baseIdx + 3)
return $ PixelRGBA16 rv gv bv av
where baseIdx = mutablePixelBaseIndex image x y
# INLINE writePixel #
writePixel image@(MutableImage { mutableImageData = arr }) x y (PixelRGBA16 rv gv bv av) = do
let baseIdx = mutablePixelBaseIndex image x y
(arr `M.write` (baseIdx + 0)) rv
(arr `M.write` (baseIdx + 1)) gv
(arr `M.write` (baseIdx + 2)) bv
(arr `M.write` (baseIdx + 3)) av
# INLINE unsafePixelAt #
unsafePixelAt v idx =
PixelRGBA16 (V.unsafeIndex v idx)
(V.unsafeIndex v $ idx + 1)
(V.unsafeIndex v $ idx + 2)
(V.unsafeIndex v $ idx + 3)
# INLINE unsafeReadPixel #
unsafeReadPixel vec idx =
PixelRGBA16 `liftM` M.unsafeRead vec idx
`ap` M.unsafeRead vec (idx + 1)
`ap` M.unsafeRead vec (idx + 2)
`ap` M.unsafeRead vec (idx + 3)
# INLINE unsafeWritePixel #
unsafeWritePixel v idx (PixelRGBA16 r g b a) =
M.unsafeWrite v idx r >> M.unsafeWrite v (idx + 1) g
>> M.unsafeWrite v (idx + 2) b
>> M.unsafeWrite v (idx + 3) a
instance TransparentPixel PixelRGBA16 PixelRGB16 where
# INLINE dropTransparency #
dropTransparency (PixelRGBA16 r g b _) = PixelRGB16 r g b
# INLINE getTransparency #
getTransparency (PixelRGBA16 _ _ _ a) = a
instance ColorPlane PixelRGBA16 PlaneRed where
toComponentIndex _ _ = 0
instance ColorPlane PixelRGBA16 PlaneGreen where
toComponentIndex _ _ = 1
instance ColorPlane PixelRGBA16 PlaneBlue where
toComponentIndex _ _ = 2
instance ColorPlane PixelRGBA16 PlaneAlpha where
toComponentIndex _ _ = 3
instance Pixel PixelYCbCr8 where
type PixelBaseComponent PixelYCbCr8 = Word8
# INLINE pixelOpacity #
pixelOpacity = const maxBound
mixWith f (PixelYCbCr8 ya cba cra) (PixelYCbCr8 yb cbb crb) =
PixelYCbCr8 (f 0 ya yb) (f 1 cba cbb) (f 2 cra crb)
# INLINE colorMap #
colorMap f (PixelYCbCr8 y cb cr) = PixelYCbCr8 (f y) (f cb) (f cr)
componentCount _ = 3
# INLINE pixelAt #
pixelAt image@(Image { imageData = arr }) x y = PixelYCbCr8 (arr ! (baseIdx + 0))
(arr ! (baseIdx + 1))
(arr ! (baseIdx + 2))
where baseIdx = pixelBaseIndex image x y
# INLINE readPixel #
readPixel image@(MutableImage { mutableImageData = arr }) x y = do
yv <- arr `M.read` baseIdx
cbv <- arr `M.read` (baseIdx + 1)
crv <- arr `M.read` (baseIdx + 2)
return $ PixelYCbCr8 yv cbv crv
where baseIdx = mutablePixelBaseIndex image x y
# INLINE writePixel #
writePixel image@(MutableImage { mutableImageData = arr }) x y (PixelYCbCr8 yv cbv crv) = do
let baseIdx = mutablePixelBaseIndex image x y
(arr `M.write` (baseIdx + 0)) yv
(arr `M.write` (baseIdx + 1)) cbv
(arr `M.write` (baseIdx + 2)) crv
# INLINE unsafePixelAt #
unsafePixelAt v idx =
PixelYCbCr8 (V.unsafeIndex v idx) (V.unsafeIndex v $ idx + 1) (V.unsafeIndex v $ idx + 2)
# INLINE unsafeReadPixel #
unsafeReadPixel vec idx =
PixelYCbCr8 `liftM` M.unsafeRead vec idx
`ap` M.unsafeRead vec (idx + 1)
`ap` M.unsafeRead vec (idx + 2)
# INLINE unsafeWritePixel #
unsafeWritePixel v idx (PixelYCbCr8 y cb cr) =
M.unsafeWrite v idx y >> M.unsafeWrite v (idx + 1) cb
>> M.unsafeWrite v (idx + 2) cr
instance (Pixel a) => ColorSpaceConvertible a a where
convertPixel = id
convertImage = id
scaleBits, oneHalf :: Int
scaleBits = 16
oneHalf = 1 `unsafeShiftL` (scaleBits - 1)
fix :: Float -> Int
fix x = floor $ x * fromIntegral ((1 :: Int) `unsafeShiftL` scaleBits) + 0.5
rYTab, gYTab, bYTab, rCbTab, gCbTab, bCbTab, gCrTab, bCrTab :: V.Vector Int
rYTab = V.fromListN 256 [fix 0.29900 * i | i <- [0..255] ]
gYTab = V.fromListN 256 [fix 0.58700 * i | i <- [0..255] ]
bYTab = V.fromListN 256 [fix 0.11400 * i + oneHalf | i <- [0..255] ]
rCbTab = V.fromListN 256 [(- fix 0.16874) * i | i <- [0..255] ]
gCbTab = V.fromListN 256 [(- fix 0.33126) * i | i <- [0..255] ]
bCbTab = V.fromListN 256 [fix 0.5 * i + (128 `unsafeShiftL` scaleBits) + oneHalf - 1| i <- [0..255] ]
gCrTab = V.fromListN 256 [(- fix 0.41869) * i | i <- [0..255] ]
bCrTab = V.fromListN 256 [(- fix 0.08131) * i | i <- [0..255] ]
instance ColorSpaceConvertible PixelRGB8 PixelYCbCr8 where
# INLINE convertPixel #
convertPixel (PixelRGB8 r g b) = PixelYCbCr8 (fromIntegral y) (fromIntegral cb) (fromIntegral cr)
where ri = fromIntegral r
gi = fromIntegral g
bi = fromIntegral b
y = (rYTab `V.unsafeIndex` ri + gYTab `V.unsafeIndex` gi + bYTab `V.unsafeIndex` bi) `unsafeShiftR` scaleBits
cb = (rCbTab `V.unsafeIndex` ri + gCbTab `V.unsafeIndex` gi + bCbTab `V.unsafeIndex` bi) `unsafeShiftR` scaleBits
cr = (bCbTab `V.unsafeIndex` ri + gCrTab `V.unsafeIndex` gi + bCrTab `V.unsafeIndex` bi) `unsafeShiftR` scaleBits
convertImage Image { imageWidth = w, imageHeight = h, imageData = d } = Image w h newData
where maxi = w * h
rY = fix 0.29900
gY = fix 0.58700
bY = fix 0.11400
rCb = - fix 0.16874
gCb = - fix 0.33126
bCb = fix 0.5
gCr = - fix 0.41869
bCr = - fix 0.08131
newData = runST $ do
block <- M.new $ maxi * 3
let traductor _ idx | idx >= maxi = return block
traductor readIdx idx = do
let ri = fromIntegral $ d `V.unsafeIndex` readIdx
gi = fromIntegral $ d `V.unsafeIndex` (readIdx + 1)
bi = fromIntegral $ d `V.unsafeIndex` (readIdx + 2)
y = (rY * ri + gY * gi + bY * bi + oneHalf) `unsafeShiftR` scaleBits
cb = (rCb * ri + gCb * gi + bCb * bi + (128 `unsafeShiftL` scaleBits) + oneHalf - 1) `unsafeShiftR` scaleBits
cr = (bCb * ri + (128 `unsafeShiftL` scaleBits) + oneHalf - 1+ gCr * gi + bCr * bi) `unsafeShiftR` scaleBits
(block `M.unsafeWrite` (readIdx + 0)) $ fromIntegral y
(block `M.unsafeWrite` (readIdx + 1)) $ fromIntegral cb
(block `M.unsafeWrite` (readIdx + 2)) $ fromIntegral cr
traductor (readIdx + 3) (idx + 1)
traductor 0 0 >>= V.freeze
crRTab, cbBTab, crGTab, cbGTab :: V.Vector Int
crRTab = V.fromListN 256 [(fix 1.40200 * x + oneHalf) `unsafeShiftR` scaleBits | x <- [-128 .. 127]]
cbBTab = V.fromListN 256 [(fix 1.77200 * x + oneHalf) `unsafeShiftR` scaleBits | x <- [-128 .. 127]]
crGTab = V.fromListN 256 [negate (fix 0.71414) * x | x <- [-128 .. 127]]
cbGTab = V.fromListN 256 [negate (fix 0.34414) * x + oneHalf | x <- [-128 .. 127]]
instance ColorSpaceConvertible PixelYCbCr8 PixelRGB8 where
# INLINE convertPixel #
convertPixel (PixelYCbCr8 y cb cr) = PixelRGB8 (clampWord8 r) (clampWord8 g) (clampWord8 b)
where clampWord8 = fromIntegral . max 0 . min 255
yi = fromIntegral y
cbi = fromIntegral cb
cri = fromIntegral cr
r = yi + crRTab `V.unsafeIndex` cri
g = yi + (cbGTab `V.unsafeIndex` cbi + crGTab `V.unsafeIndex` cri) `unsafeShiftR` scaleBits
b = yi + cbBTab `V.unsafeIndex` cbi
convertImage Image { imageWidth = w, imageHeight = h, imageData = d } = Image w h newData
where maxi = w * h
clampWord8 v | v < 0 = 0
| v > 255 = 255
| otherwise = fromIntegral v
newData = runST $ do
block <- M.new $ maxi * 3
let traductor _ idx | idx >= maxi = return block
traductor readIdx idx = do
let yi = fromIntegral $ d `V.unsafeIndex` readIdx
cbi = fromIntegral $ d `V.unsafeIndex` (readIdx + 1)
cri = fromIntegral $ d `V.unsafeIndex` (readIdx + 2)
r = yi + crRTab `V.unsafeIndex` cri
g = yi + (cbGTab `V.unsafeIndex` cbi + crGTab `V.unsafeIndex` cri) `unsafeShiftR` scaleBits
b = yi + cbBTab `V.unsafeIndex` cbi
(block `M.unsafeWrite` (readIdx + 0)) $ clampWord8 r
(block `M.unsafeWrite` (readIdx + 1)) $ clampWord8 g
(block `M.unsafeWrite` (readIdx + 2)) $ clampWord8 b
traductor (readIdx + 3) (idx + 1)
traductor 0 0 >>= V.freeze
instance ColorPlane PixelYCbCr8 PlaneLuma where
toComponentIndex _ _ = 0
instance ColorPlane PixelYCbCr8 PlaneCb where
toComponentIndex _ _ = 1
instance ColorPlane PixelYCbCr8 PlaneCr where
toComponentIndex _ _ = 2
instance Pixel PixelCMYK8 where
type PixelBaseComponent PixelCMYK8 = Word8
# INLINE pixelOpacity #
pixelOpacity = const maxBound
mixWith f (PixelCMYK8 ca ma ya ka) (PixelCMYK8 cb mb yb kb) =
PixelCMYK8 (f 0 ca cb) (f 1 ma mb) (f 2 ya yb) (f 3 ka kb)
# INLINE colorMap #
colorMap f (PixelCMYK8 c m y k) = PixelCMYK8 (f c) (f m) (f y) (f k)
componentCount _ = 4
# INLINE pixelAt #
pixelAt image@(Image { imageData = arr }) x y = PixelCMYK8 (arr ! (baseIdx + 0))
(arr ! (baseIdx + 1))
(arr ! (baseIdx + 2))
(arr ! (baseIdx + 3))
where baseIdx = pixelBaseIndex image x y
# INLINE readPixel #
readPixel image@(MutableImage { mutableImageData = arr }) x y = do
rv <- arr `M.read` baseIdx
gv <- arr `M.read` (baseIdx + 1)
bv <- arr `M.read` (baseIdx + 2)
av <- arr `M.read` (baseIdx + 3)
return $ PixelCMYK8 rv gv bv av
where baseIdx = mutablePixelBaseIndex image x y
# INLINE writePixel #
writePixel image@(MutableImage { mutableImageData = arr }) x y (PixelCMYK8 rv gv bv av) = do
let baseIdx = mutablePixelBaseIndex image x y
(arr `M.write` (baseIdx + 0)) rv
(arr `M.write` (baseIdx + 1)) gv
(arr `M.write` (baseIdx + 2)) bv
(arr `M.write` (baseIdx + 3)) av
# INLINE unsafePixelAt #
unsafePixelAt v idx =
PixelCMYK8 (V.unsafeIndex v idx)
(V.unsafeIndex v $ idx + 1)
(V.unsafeIndex v $ idx + 2)
(V.unsafeIndex v $ idx + 3)
# INLINE unsafeReadPixel #
unsafeReadPixel vec idx =
PixelCMYK8 `liftM` M.unsafeRead vec idx
`ap` M.unsafeRead vec (idx + 1)
`ap` M.unsafeRead vec (idx + 2)
`ap` M.unsafeRead vec (idx + 3)
# INLINE unsafeWritePixel #
unsafeWritePixel v idx (PixelCMYK8 r g b a) =
M.unsafeWrite v idx r >> M.unsafeWrite v (idx + 1) g
>> M.unsafeWrite v (idx + 2) b
>> M.unsafeWrite v (idx + 3) a
instance ColorSpaceConvertible PixelCMYK8 PixelRGB8 where
convertPixel (PixelCMYK8 c m y k) =
PixelRGB8 (clampWord8 r) (clampWord8 g) (clampWord8 b)
where
clampWord8 = fromIntegral . max 0 . min 255 . (`div` 255)
ik :: Int
ik = 255 - fromIntegral k
r = (255 - fromIntegral c) * ik
g = (255 - fromIntegral m) * ik
b = (255 - fromIntegral y) * ik
instance Pixel PixelYCbCrK8 where
type PixelBaseComponent PixelYCbCrK8 = Word8
# INLINE pixelOpacity #
pixelOpacity = const maxBound
mixWith f (PixelYCbCrK8 ya cba cra ka) (PixelYCbCrK8 yb cbb crb kb) =
PixelYCbCrK8 (f 0 ya yb) (f 1 cba cbb) (f 2 cra crb) (f 3 ka kb)
# INLINE colorMap #
colorMap f (PixelYCbCrK8 y cb cr k) = PixelYCbCrK8 (f y) (f cb) (f cr) (f k)
componentCount _ = 4
# INLINE pixelAt #
pixelAt image@(Image { imageData = arr }) x y =
PixelYCbCrK8 (arr ! (baseIdx + 0)) (arr ! (baseIdx + 1))
(arr ! (baseIdx + 2)) (arr ! (baseIdx + 3))
where baseIdx = pixelBaseIndex image x y
# INLINE readPixel #
readPixel image@(MutableImage { mutableImageData = arr }) x y = do
yv <- arr `M.read` baseIdx
cbv <- arr `M.read` (baseIdx + 1)
crv <- arr `M.read` (baseIdx + 2)
kv <- arr `M.read` (baseIdx + 3)
return $ PixelYCbCrK8 yv cbv crv kv
where baseIdx = mutablePixelBaseIndex image x y
# INLINE writePixel #
writePixel image@(MutableImage { mutableImageData = arr }) x y (PixelYCbCrK8 yv cbv crv kv) = do
let baseIdx = mutablePixelBaseIndex image x y
(arr `M.write` (baseIdx + 0)) yv
(arr `M.write` (baseIdx + 1)) cbv
(arr `M.write` (baseIdx + 2)) crv
(arr `M.write` (baseIdx + 3)) kv
# INLINE unsafePixelAt #
unsafePixelAt v idx =
PixelYCbCrK8 (V.unsafeIndex v idx)
(V.unsafeIndex v $ idx + 1)
(V.unsafeIndex v $ idx + 2)
(V.unsafeIndex v $ idx + 3)
# INLINE unsafeReadPixel #
unsafeReadPixel vec idx =
PixelYCbCrK8 `liftM` M.unsafeRead vec idx
`ap` M.unsafeRead vec (idx + 1)
`ap` M.unsafeRead vec (idx + 2)
`ap` M.unsafeRead vec (idx + 3)
# INLINE unsafeWritePixel #
unsafeWritePixel v idx (PixelYCbCrK8 y cb cr k) =
M.unsafeWrite v idx y >> M.unsafeWrite v (idx + 1) cb
>> M.unsafeWrite v (idx + 2) cr
>> M.unsafeWrite v (idx + 3) k
instance ColorSpaceConvertible PixelYCbCrK8 PixelRGB8 where
convertPixel (PixelYCbCrK8 y cb cr _k) = PixelRGB8 (clamp r) (clamp g) (clamp b)
where
tof :: Word8 -> Float
tof = fromIntegral
clamp :: Float -> Word8
clamp = floor . max 0 . min 255
yf = tof y
r = yf + 1.402 * tof cr - 179.456
g = yf - 0.3441363 * tof cb - 0.71413636 * tof cr + 135.4589
b = yf + 1.772 * tof cb - 226.816
instance ColorSpaceConvertible PixelYCbCrK8 PixelCMYK8 where
convertPixel (PixelYCbCrK8 y cb cr k) = PixelCMYK8 c m ye k
where
tof :: Word8 -> Float
tof = fromIntegral
clamp :: Float -> Word8
clamp = floor . max 0 . min 255
yf = tof y
r = yf + 1.402 * tof cr - 179.456
g = yf - 0.3441363 * tof cb - 0.71413636 * tof cr + 135.4589
b = yf + 1.772 * tof cb - 226.816
c = clamp $ 255 - r
m = clamp $ 255 - g
ye = clamp $ 255 - b
# SPECIALIZE integralRGBToCMYK : : ( Word16 - > Word16 - > Word16 - > b )
- > ( Word16 , , b #
-> (Word16, Word16, Word16) -> b #-}
| Convert RGB8 or RGB16 to and CMYK16 respectfully .
used with .
integralRGBToCMYK :: (Bounded a, Integral a)
integralRGBToCMYK build (r, g, b)
prevent division by zero
| otherwise = build (fromIntegral c) (fromIntegral m) (fromIntegral y) k
where maxVal = maxBound
max32 = fromIntegral maxVal :: Word32
kMax32 = fromIntegral kMax :: Word32
kMax = max r (max g b)
k = maxVal - kMax
c = max32 * (kMax32 - fromIntegral r) `div` kMax32
m = max32 * (kMax32 - fromIntegral g) `div` kMax32
y = max32 * (kMax32 - fromIntegral b) `div` kMax32
instance ColorSpaceConvertible PixelRGB8 PixelCMYK8 where
convertPixel (PixelRGB8 r g b) = integralRGBToCMYK PixelCMYK8 (r, g, b)
instance ColorPlane PixelCMYK8 PlaneCyan where
toComponentIndex _ _ = 0
instance ColorPlane PixelCMYK8 PlaneMagenta where
toComponentIndex _ _ = 1
instance ColorPlane PixelCMYK8 PlaneYellow where
toComponentIndex _ _ = 2
instance ColorPlane PixelCMYK8 PlaneBlack where
toComponentIndex _ _ = 3
instance Pixel PixelCMYK16 where
type PixelBaseComponent PixelCMYK16 = Word16
# INLINE pixelOpacity #
pixelOpacity = const maxBound
mixWith f (PixelCMYK16 ca ma ya ka) (PixelCMYK16 cb mb yb kb) =
PixelCMYK16 (f 0 ca cb) (f 1 ma mb) (f 2 ya yb) (f 3 ka kb)
# INLINE colorMap #
colorMap f (PixelCMYK16 c m y k) = PixelCMYK16 (f c) (f m) (f y) (f k)
componentCount _ = 4
# INLINE pixelAt #
pixelAt image@(Image { imageData = arr }) x y = PixelCMYK16 (arr ! (baseIdx + 0))
(arr ! (baseIdx + 1))
(arr ! (baseIdx + 2))
(arr ! (baseIdx + 3))
where baseIdx = pixelBaseIndex image x y
# INLINE readPixel #
readPixel image@(MutableImage { mutableImageData = arr }) x y = do
rv <- arr `M.read` baseIdx
gv <- arr `M.read` (baseIdx + 1)
bv <- arr `M.read` (baseIdx + 2)
av <- arr `M.read` (baseIdx + 3)
return $ PixelCMYK16 rv gv bv av
where baseIdx = mutablePixelBaseIndex image x y
# INLINE writePixel #
writePixel image@(MutableImage { mutableImageData = arr }) x y (PixelCMYK16 rv gv bv av) = do
let baseIdx = mutablePixelBaseIndex image x y
(arr `M.write` (baseIdx + 0)) rv
(arr `M.write` (baseIdx + 1)) gv
(arr `M.write` (baseIdx + 2)) bv
(arr `M.write` (baseIdx + 3)) av
# INLINE unsafePixelAt #
unsafePixelAt v idx =
PixelCMYK16 (V.unsafeIndex v idx)
(V.unsafeIndex v $ idx + 1)
(V.unsafeIndex v $ idx + 2)
(V.unsafeIndex v $ idx + 3)
# INLINE unsafeReadPixel #
unsafeReadPixel vec idx =
PixelCMYK16 `liftM` M.unsafeRead vec idx
`ap` M.unsafeRead vec (idx + 1)
`ap` M.unsafeRead vec (idx + 2)
`ap` M.unsafeRead vec (idx + 3)
# INLINE unsafeWritePixel #
unsafeWritePixel v idx (PixelCMYK16 r g b a) =
M.unsafeWrite v idx r >> M.unsafeWrite v (idx + 1) g
>> M.unsafeWrite v (idx + 2) b
>> M.unsafeWrite v (idx + 3) a
instance ColorSpaceConvertible PixelCMYK16 PixelRGB16 where
convertPixel (PixelCMYK16 c m y k) =
PixelRGB16 (clampWord16 r) (clampWord16 g) (clampWord16 b)
where
clampWord16 = fromIntegral . (`unsafeShiftR` 16)
ik :: Int
ik = 65535 - fromIntegral k
r = (65535 - fromIntegral c) * ik
g = (65535 - fromIntegral m) * ik
b = (65535 - fromIntegral y) * ik
instance ColorPlane PixelCMYK16 PlaneCyan where
toComponentIndex _ _ = 0
instance ColorPlane PixelCMYK16 PlaneMagenta where
toComponentIndex _ _ = 1
instance ColorPlane PixelCMYK16 PlaneYellow where
toComponentIndex _ _ = 2
instance ColorPlane PixelCMYK16 PlaneBlack where
toComponentIndex _ _ = 3
^ Gamma value , should be between 0.5 and 3.0
-> Image PixelRGBF
gammaCorrection gammaVal = pixelMap gammaCorrector
where gammaExponent = 1.0 / gammaVal
fixVal v = v ** gammaExponent
gammaCorrector (PixelRGBF r g b) =
PixelRGBF (fixVal r) (fixVal g) (fixVal b)
-> Image PixelRGBF
toneMapping exposure img = Image (imageWidth img) (imageHeight img) scaledData
where coeff = exposure * (exposure / maxBrightness + 1.0) / (exposure + 1.0);
maxBrightness = pixelFold (\luma _ _ px -> max luma $ computeLuma px) 0 img
scaledData = V.map (* coeff) $ imageData img
class PackeablePixel a where
It 's Word32 for PixelRGBA8 for instance
type PackedRepresentation a
packPixel :: a -> PackedRepresentation a
unpackPixel :: PackedRepresentation a -> a
instance PackeablePixel Pixel8 where
type PackedRepresentation Pixel8 = Pixel8
packPixel = id
# INLINE packPixel #
unpackPixel = id
instance PackeablePixel Pixel16 where
type PackedRepresentation Pixel16 = Pixel16
packPixel = id
# INLINE packPixel #
unpackPixel = id
instance PackeablePixel Pixel32 where
type PackedRepresentation Pixel32 = Pixel32
packPixel = id
# INLINE packPixel #
unpackPixel = id
instance PackeablePixel PixelF where
type PackedRepresentation PixelF = PixelF
packPixel = id
# INLINE packPixel #
unpackPixel = id
instance PackeablePixel PixelRGBA8 where
type PackedRepresentation PixelRGBA8 = Word32
# INLINE packPixel #
packPixel (PixelRGBA8 r g b a) =
(fi r `unsafeShiftL` (0 * bitCount)) .|.
(fi g `unsafeShiftL` (1 * bitCount)) .|.
(fi b `unsafeShiftL` (2 * bitCount)) .|.
(fi a `unsafeShiftL` (3 * bitCount))
where fi = fromIntegral
bitCount = 8
unpackPixel w =
PixelRGBA8 (low w)
(low $ w `unsafeShiftR` bitCount)
(low $ w `unsafeShiftR` (2 * bitCount))
(low $ w `unsafeShiftR` (3 * bitCount))
where
low v = fromIntegral (v .&. 0xFF)
bitCount = 8
instance PackeablePixel PixelRGBA16 where
type PackedRepresentation PixelRGBA16 = Word64
# INLINE packPixel #
packPixel (PixelRGBA16 r g b a) =
(fi r `unsafeShiftL` (0 * bitCount)) .|.
(fi g `unsafeShiftL` (1 * bitCount)) .|.
(fi b `unsafeShiftL` (2 * bitCount)) .|.
(fi a `unsafeShiftL` (3 * bitCount))
where fi = fromIntegral
bitCount = 16
unpackPixel w =
PixelRGBA16 (low w)
(low $ w `unsafeShiftR` bitCount)
(low $ w `unsafeShiftR` (2 * bitCount))
(low $ w `unsafeShiftR` (3 * bitCount))
where
low v = fromIntegral (v .&. 0xFFFF)
bitCount = 16
instance PackeablePixel PixelCMYK8 where
type PackedRepresentation PixelCMYK8 = Word32
# INLINE packPixel #
packPixel (PixelCMYK8 c m y k) =
(fi c `unsafeShiftL` (0 * bitCount)) .|.
(fi m `unsafeShiftL` (1 * bitCount)) .|.
(fi y `unsafeShiftL` (2 * bitCount)) .|.
(fi k `unsafeShiftL` (3 * bitCount))
where fi = fromIntegral
bitCount = 8
unpackPixel w =
PixelCMYK8 (low w)
(low $ w `unsafeShiftR` bitCount)
(low $ w `unsafeShiftR` (2 * bitCount))
(low $ w `unsafeShiftR` (3 * bitCount))
where
low v = fromIntegral (v .&. 0xFF)
bitCount = 8
instance PackeablePixel PixelCMYK16 where
type PackedRepresentation PixelCMYK16 = Word64
# INLINE packPixel #
packPixel (PixelCMYK16 c m y k) =
(fi c `unsafeShiftL` (0 * bitCount)) .|.
(fi m `unsafeShiftL` (1 * bitCount)) .|.
(fi y `unsafeShiftL` (2 * bitCount)) .|.
(fi k `unsafeShiftL` (3 * bitCount))
where fi = fromIntegral
bitCount = 16
unpackPixel w =
PixelCMYK16 (low w)
(low $ w `unsafeShiftR` bitCount)
(low $ w `unsafeShiftR` (2 * bitCount))
(low $ w `unsafeShiftR` (3 * bitCount))
where
low v = fromIntegral (v .&. 0xFFFF)
bitCount = 16
instance PackeablePixel PixelYA16 where
type PackedRepresentation PixelYA16 = Word32
# INLINE packPixel #
packPixel (PixelYA16 y a) =
(fi y `unsafeShiftL` (0 * bitCount)) .|.
(fi a `unsafeShiftL` (1 * bitCount))
where fi = fromIntegral
bitCount = 16
unpackPixel w = PixelYA16 (low w) (low $ w `unsafeShiftR` bitCount)
where
low v = fromIntegral (v .&. 0xFFFF)
bitCount = 16
instance PackeablePixel PixelYA8 where
type PackedRepresentation PixelYA8 = Word16
# INLINE packPixel #
packPixel (PixelYA8 y a) =
(fi y `unsafeShiftL` (0 * bitCount)) .|.
(fi a `unsafeShiftL` (1 * bitCount))
where fi = fromIntegral
bitCount = 8
unpackPixel w = PixelYA8 (low w) (low $ w `unsafeShiftR` bitCount)
where
low v = fromIntegral (v .&. 0xFF)
bitCount = 8
fillImageWith :: ( Pixel px, PackeablePixel px
, PrimMonad m
, M.Storable (PackedRepresentation px))
=> MutableImage (PrimState m) px -> px -> m ()
fillImageWith img px = M.set converted $ packPixel px
where
(ptr, s, s2) = M.unsafeToForeignPtr $ mutableImageData img
!packedPtr = castForeignPtr ptr
!converted =
M.unsafeFromForeignPtr packedPtr s (s2 `div` componentCount px)
| Fill a packeable pixel between two bounds .
unsafeWritePixelBetweenAt
:: ( PrimMonad m
, Pixel px, PackeablePixel px
, M.Storable (PackedRepresentation px))
-> m ()
unsafeWritePixelBetweenAt img px start count = M.set converted packed
where
!packed = packPixel px
!pixelData = mutableImageData img
!toSet = M.slice start count pixelData
(ptr, s, s2) = M.unsafeToForeignPtr toSet
!packedPtr = castForeignPtr ptr
!converted =
M.unsafeFromForeignPtr packedPtr s s2
readPackedPixelAt :: forall m px.
( Pixel px, PackeablePixel px
, M.Storable (PackedRepresentation px)
, PrimMonad m
)
-> m px
# INLINE readPackedPixelAt #
readPackedPixelAt img idx = do
unpacked <- M.unsafeRead converted (idx `div` compCount)
return $ unpackPixel unpacked
where
!compCount = componentCount (undefined :: px)
(ptr, s, s2) = M.unsafeToForeignPtr $ mutableImageData img
!packedPtr = castForeignPtr ptr
!converted =
M.unsafeFromForeignPtr packedPtr s s2
writePackedPixelAt :: ( Pixel px, PackeablePixel px
, M.Storable (PackedRepresentation px)
, PrimMonad m
)
-> m ()
# INLINE writePackedPixelAt #
writePackedPixelAt img idx px =
M.unsafeWrite converted (idx `div` compCount) packed
where
!packed = packPixel px
!compCount = componentCount px
(ptr, s, s2) = M.unsafeToForeignPtr $ mutableImageData img
!packedPtr = castForeignPtr ptr
!converted =
M.unsafeFromForeignPtr packedPtr s s2
|
4852d4fbeda503c513f4d018e0db0cdcd42d81d332402b301dc01fee2ce4847d | craigl64/clim-ccl | fids-pre.lisp | ;; See the file LICENSE for the full license governing this code.
;;
(defpackage "SYSTEM"
(:export "PUSH-PATCH")
)
(defmacro sys:push-patch (&rest x)
(declare (ignore x))
nil)
(defpackage "ALLEGRO"
(:nicknames "FRANZ" "EXCL" "CLOS")
(:export "MEMQ" "*FASL-DEFAULT-TYPE*" "INTERN-EQL-SPECIALIZER" "NAMED-FUNCTION"
"PURE-STRCAT")
)
#+acl86win32
(defvar excl:*FASL-DEFAULT-TYPE* "fasl")
#-acl86win32
(defvar excl:*FASL-DEFAULT-TYPE* "fsl")
(defvar SYS::*SOURCE-FILE-TYPES* '("lsp"))
(defun franz:memq (x l)
(member x l :test #'eq))
(defmacro excl::.error (&rest x)
`(error ,@x))
(defpackage "DEFSYS"
(:import-from "ACL" "DYNAMIC-EXTENT"))
(declaim (declaration excl::IGNORE-IF-UNUSED KEYS))
(defun clos:INTERN-EQL-SPECIALIZER (x) (error))
(defmacro excl:NAMED-FUNCTION (&whole form) `(error ',form))
(defun franz:PURE-STRCAT (&rest s)
(apply #'concateneate 'string s))
| null | https://raw.githubusercontent.com/craigl64/clim-ccl/301efbd770745b429f2b00b4e8ca6624de9d9ea9/sys/fids-pre.lisp | lisp | See the file LICENSE for the full license governing this code.
|
(defpackage "SYSTEM"
(:export "PUSH-PATCH")
)
(defmacro sys:push-patch (&rest x)
(declare (ignore x))
nil)
(defpackage "ALLEGRO"
(:nicknames "FRANZ" "EXCL" "CLOS")
(:export "MEMQ" "*FASL-DEFAULT-TYPE*" "INTERN-EQL-SPECIALIZER" "NAMED-FUNCTION"
"PURE-STRCAT")
)
#+acl86win32
(defvar excl:*FASL-DEFAULT-TYPE* "fasl")
#-acl86win32
(defvar excl:*FASL-DEFAULT-TYPE* "fsl")
(defvar SYS::*SOURCE-FILE-TYPES* '("lsp"))
(defun franz:memq (x l)
(member x l :test #'eq))
(defmacro excl::.error (&rest x)
`(error ,@x))
(defpackage "DEFSYS"
(:import-from "ACL" "DYNAMIC-EXTENT"))
(declaim (declaration excl::IGNORE-IF-UNUSED KEYS))
(defun clos:INTERN-EQL-SPECIALIZER (x) (error))
(defmacro excl:NAMED-FUNCTION (&whole form) `(error ',form))
(defun franz:PURE-STRCAT (&rest s)
(apply #'concateneate 'string s))
|
69801c0208967d5963b74ec42786645f769dafac7aad69715af40e5f5efa41df | oakes/play-clj.net | net.clj | (ns play-clj.net
(:require [play-clj.net-utils :as u])
(:import [org.zeromq ZContext ZMQ ZMQ$Socket])
(:gen-class))
(defn ^:private client-listen!
[^ZMQ$Socket socket screen]
(try
(loop []
(let [topic (.recvStr socket)
message (u/read-edn (.recvStr socket))]
(when (and topic message)
(if (map? screen)
(let [execute-fn! (u/get-obj screen :execute-fn-on-gl!)
options (u/get-obj screen :options)]
(execute-fn! (:on-network-receive options)
:topic (keyword topic)
:message message))
(screen (keyword topic) message))
(recur))))
(catch Exception _)))
(defn ^:private server-listen!
[^ZMQ$Socket send-socket ^ZMQ$Socket receive-socket]
(loop []
(let [[topic message] (u/read-edn (.recvStr receive-socket))]
(when (and topic message)
(.sendMore send-socket (name topic))
(.send send-socket (pr-str message))))
(recur)))
(defn subscribe!
"Subscribes the client the given `topics`. The `screen` is a play-clj screen
map that contains a client hash map associated with the :network key.
(subscribe! screen :my-game-level-2)"
[screen & topics]
(doseq [t topics]
(.subscribe (u/get-obj screen :network :receiver) (u/str->bytes (name t)))))
(defn unsubscribe!
"Unsubscribes the client the given `topics`. The `screen` is a play-clj screen
map that contains a client hash map associated with the :network key.
(unsubscribe! screen :my-game-level-2)"
[screen & topics]
(doseq [t topics]
(.unsubscribe (u/get-obj screen :network :receiver) (u/str->bytes t))))
(defn disconnect!
"Closes the sockets and interrupts the receiver thread. The `screen` is a
play-clj screen map that contains a client hash map associated with the :network
key.
(let [screen (update! screen :network (client screen))]
(disconnect! screen))"
[screen]
; destroy the send and receive sockets
(doto (u/get-obj screen :network :context)
(.destroySocket (u/get-obj screen :network :sender))
(.destroySocket (u/get-obj screen :network :receiver)))
; stop the thread
(.interrupt (u/get-obj screen :network :thread))
; remove from the networks atom if it exists
(some-> u/*networks* (swap! dissoc (or (:network screen) screen)))
nil)
(defn broadcast!
"Sends a `message` with the connected server, to be broadcasted to all peers
subscribed to the `topic`. The `screen` is a play-clj screen map that contains a
client hash map associated with the :network key.
(let [screen (update! screen :network (client screen [:my-game-position]))]
(broadcast! screen :my-game-position {:x 10 :y 5}))"
[screen topic message]
(let [encoded-message (pr-str [topic message])
message-size (count (u/str->bytes encoded-message))]
(if (> message-size u/max-message-size)
(throw (Exception. (str "Message is too large to broadcast: "
message-size " > " u/max-message-size)))
(.send (u/get-obj screen :network :sender) encoded-message ZMQ/NOBLOCK)))
nil)
(defn client
"Returns a hash map containing sender and receiver sockets, both of which are
connected to the `send-address` and `receive-address`. The receiver socket is
also subscribed to the `topics`. The `screen` is a play-clj screen map, whose
:on-network-receive function will run when a message is received.
(client screen [:my-game-position])
(client screen [:my-game-position]
\"tcp:4707\" \"tcp:4708\")"
([screen]
(client screen []))
([screen topics]
(client screen topics u/client-send-address u/client-receive-address))
([screen topics send-address receive-address]
(let [context (ZContext.)
push (.createSocket context ZMQ/PUSH)
sub (.createSocket context ZMQ/SUB)
c {:sender (doto push (.connect send-address))
:receiver (doto sub
(.connect receive-address)
((partial apply subscribe!) topics))
:thread (doto (Thread. #(client-listen! sub screen)) .start)
:context context}]
; add to the networks atom if it exists
(some-> u/*networks* (swap! assoc c #(disconnect! c)))
; return client
c)))
(defn server
"Returns a hash map containing sender and receiver sockets, both of which are
bound to the `send-address` and `receive-address`.
(server)
(server \"tcp://*:4708\" \"tcp://*:4707\")"
([]
(server u/server-send-address u/server-receive-address))
([send-address receive-address]
(let [context (ZContext.)
pub (.createSocket context ZMQ/PUB)
pull (.createSocket context ZMQ/PULL)
_ (.setMaxMsgSize pull u/max-message-size)
s {:sender (doto pub (.bind send-address))
:receiver (doto pull (.bind receive-address))
:thread (doto (Thread. #(server-listen! pub pull)) .start)
:context context}]
; add to the networks atom if it exists
(some-> u/*networks* (swap! assoc s #(disconnect! s)))
; return server
s)))
(defn ^:private -main
[& args]
(server))
| null | https://raw.githubusercontent.com/oakes/play-clj.net/36daf280830a4b44e76563ae9457cd25e251c2a9/src/play_clj/net.clj | clojure | destroy the send and receive sockets
stop the thread
remove from the networks atom if it exists
add to the networks atom if it exists
return client
add to the networks atom if it exists
return server | (ns play-clj.net
(:require [play-clj.net-utils :as u])
(:import [org.zeromq ZContext ZMQ ZMQ$Socket])
(:gen-class))
(defn ^:private client-listen!
[^ZMQ$Socket socket screen]
(try
(loop []
(let [topic (.recvStr socket)
message (u/read-edn (.recvStr socket))]
(when (and topic message)
(if (map? screen)
(let [execute-fn! (u/get-obj screen :execute-fn-on-gl!)
options (u/get-obj screen :options)]
(execute-fn! (:on-network-receive options)
:topic (keyword topic)
:message message))
(screen (keyword topic) message))
(recur))))
(catch Exception _)))
(defn ^:private server-listen!
[^ZMQ$Socket send-socket ^ZMQ$Socket receive-socket]
(loop []
(let [[topic message] (u/read-edn (.recvStr receive-socket))]
(when (and topic message)
(.sendMore send-socket (name topic))
(.send send-socket (pr-str message))))
(recur)))
(defn subscribe!
"Subscribes the client the given `topics`. The `screen` is a play-clj screen
map that contains a client hash map associated with the :network key.
(subscribe! screen :my-game-level-2)"
[screen & topics]
(doseq [t topics]
(.subscribe (u/get-obj screen :network :receiver) (u/str->bytes (name t)))))
(defn unsubscribe!
"Unsubscribes the client the given `topics`. The `screen` is a play-clj screen
map that contains a client hash map associated with the :network key.
(unsubscribe! screen :my-game-level-2)"
[screen & topics]
(doseq [t topics]
(.unsubscribe (u/get-obj screen :network :receiver) (u/str->bytes t))))
(defn disconnect!
"Closes the sockets and interrupts the receiver thread. The `screen` is a
play-clj screen map that contains a client hash map associated with the :network
key.
(let [screen (update! screen :network (client screen))]
(disconnect! screen))"
[screen]
(doto (u/get-obj screen :network :context)
(.destroySocket (u/get-obj screen :network :sender))
(.destroySocket (u/get-obj screen :network :receiver)))
(.interrupt (u/get-obj screen :network :thread))
(some-> u/*networks* (swap! dissoc (or (:network screen) screen)))
nil)
(defn broadcast!
"Sends a `message` with the connected server, to be broadcasted to all peers
subscribed to the `topic`. The `screen` is a play-clj screen map that contains a
client hash map associated with the :network key.
(let [screen (update! screen :network (client screen [:my-game-position]))]
(broadcast! screen :my-game-position {:x 10 :y 5}))"
[screen topic message]
(let [encoded-message (pr-str [topic message])
message-size (count (u/str->bytes encoded-message))]
(if (> message-size u/max-message-size)
(throw (Exception. (str "Message is too large to broadcast: "
message-size " > " u/max-message-size)))
(.send (u/get-obj screen :network :sender) encoded-message ZMQ/NOBLOCK)))
nil)
(defn client
"Returns a hash map containing sender and receiver sockets, both of which are
connected to the `send-address` and `receive-address`. The receiver socket is
also subscribed to the `topics`. The `screen` is a play-clj screen map, whose
:on-network-receive function will run when a message is received.
(client screen [:my-game-position])
(client screen [:my-game-position]
\"tcp:4707\" \"tcp:4708\")"
([screen]
(client screen []))
([screen topics]
(client screen topics u/client-send-address u/client-receive-address))
([screen topics send-address receive-address]
(let [context (ZContext.)
push (.createSocket context ZMQ/PUSH)
sub (.createSocket context ZMQ/SUB)
c {:sender (doto push (.connect send-address))
:receiver (doto sub
(.connect receive-address)
((partial apply subscribe!) topics))
:thread (doto (Thread. #(client-listen! sub screen)) .start)
:context context}]
(some-> u/*networks* (swap! assoc c #(disconnect! c)))
c)))
(defn server
"Returns a hash map containing sender and receiver sockets, both of which are
bound to the `send-address` and `receive-address`.
(server)
(server \"tcp://*:4708\" \"tcp://*:4707\")"
([]
(server u/server-send-address u/server-receive-address))
([send-address receive-address]
(let [context (ZContext.)
pub (.createSocket context ZMQ/PUB)
pull (.createSocket context ZMQ/PULL)
_ (.setMaxMsgSize pull u/max-message-size)
s {:sender (doto pub (.bind send-address))
:receiver (doto pull (.bind receive-address))
:thread (doto (Thread. #(server-listen! pub pull)) .start)
:context context}]
(some-> u/*networks* (swap! assoc s #(disconnect! s)))
s)))
(defn ^:private -main
[& args]
(server))
|
f774119cb98dc1adfc9cb41450e294cb41b190ee4eeb1f68ee8d6f1c3181635e | orionsbelt-battlegrounds/obb-rules | unit_test.cljc | (ns obb-rules.unit-test
(:require
[obb-rules.unit :as unit]
#?(:clj [clojure.test :refer [deftest testing is]]
:cljs [cljs.test :refer-macros [deftest testing is]])))
(deftest existing-unit-types
(testing "get-units"
(is (= 21 (count (unit/get-units))))))
(defn- test-unit
[name code]
(let [unit (unit/get-unit-by-name name)
unit-by-code (unit/get-unit-by-code code)]
(is (= unit unit-by-code))
(is (= name (unit/unit-name unit)))
(is (= code (unit/unit-code unit)))
(is (> (unit/unit-attack unit) 0))
(is (unit/unit-movement-type unit))
(is (> (unit/unit-defense unit) 0))))
(defn- verify-unit
[unit]
(testing (test-unit (:name unit) (:code unit))))
(deftest verify-units
(doseq [unit (unit/get-units)]
(verify-unit unit)))
(defn- unit-present?
"Checks if a unit is present"
[uname coll]
(some (fn [u] (= (unit/unit-name u) (name uname))) coll))
(deftest units-by-category-test
(testing "light units"
(let [units (unit/units-by-category :light)]
(is units)
(is (> (count units) 0))
(is (unit-present? :rain units))
(is (unit-present? :toxic units))
(is (not (unit-present? :worm units)))
(is (not (unit-present? :crusader units)))))
(testing "medium units"
(let [units (unit/units-by-category :medium)]
(is units)
(is (> (count units) 0))
(is (unit-present? :worm units))
(is (not (unit-present? :rain units)))
(is (not (unit-present? :crusader units)))))
(testing "heavy units"
(let [units (unit/units-by-category :heavy)]
(is units)
(is (> (count units) 0))
(is (unit-present? :crusader units))
(is (not (unit-present? :rain units)))
(is (not (unit-present? :worm units))))))
(verify-units)
| null | https://raw.githubusercontent.com/orionsbelt-battlegrounds/obb-rules/97fad6506eb81142f74f4722aca58b80d618bf45/test/obb_rules/unit_test.cljc | clojure | (ns obb-rules.unit-test
(:require
[obb-rules.unit :as unit]
#?(:clj [clojure.test :refer [deftest testing is]]
:cljs [cljs.test :refer-macros [deftest testing is]])))
(deftest existing-unit-types
(testing "get-units"
(is (= 21 (count (unit/get-units))))))
(defn- test-unit
[name code]
(let [unit (unit/get-unit-by-name name)
unit-by-code (unit/get-unit-by-code code)]
(is (= unit unit-by-code))
(is (= name (unit/unit-name unit)))
(is (= code (unit/unit-code unit)))
(is (> (unit/unit-attack unit) 0))
(is (unit/unit-movement-type unit))
(is (> (unit/unit-defense unit) 0))))
(defn- verify-unit
[unit]
(testing (test-unit (:name unit) (:code unit))))
(deftest verify-units
(doseq [unit (unit/get-units)]
(verify-unit unit)))
(defn- unit-present?
"Checks if a unit is present"
[uname coll]
(some (fn [u] (= (unit/unit-name u) (name uname))) coll))
(deftest units-by-category-test
(testing "light units"
(let [units (unit/units-by-category :light)]
(is units)
(is (> (count units) 0))
(is (unit-present? :rain units))
(is (unit-present? :toxic units))
(is (not (unit-present? :worm units)))
(is (not (unit-present? :crusader units)))))
(testing "medium units"
(let [units (unit/units-by-category :medium)]
(is units)
(is (> (count units) 0))
(is (unit-present? :worm units))
(is (not (unit-present? :rain units)))
(is (not (unit-present? :crusader units)))))
(testing "heavy units"
(let [units (unit/units-by-category :heavy)]
(is units)
(is (> (count units) 0))
(is (unit-present? :crusader units))
(is (not (unit-present? :rain units)))
(is (not (unit-present? :worm units))))))
(verify-units)
| |
076f158dac28359d736020e80a847948b50f461548123b0d2f292907b01249e0 | binaryage/chromex | history.cljs | (ns chromex.ext.history (:require-macros [chromex.ext.history :refer [gen-wrap]])
(:require [chromex.core]))
-- functions --------------------------------------------------------------------------------------------------------------
(defn search* [config query]
(gen-wrap :function ::search config query))
(defn get-visits* [config details]
(gen-wrap :function ::get-visits config details))
(defn add-url* [config details]
(gen-wrap :function ::add-url config details))
(defn delete-url* [config details]
(gen-wrap :function ::delete-url config details))
(defn delete-range* [config range]
(gen-wrap :function ::delete-range config range))
(defn delete-all* [config]
(gen-wrap :function ::delete-all config))
; -- events -----------------------------------------------------------------------------------------------------------------
(defn on-visited* [config channel & args]
(gen-wrap :event ::on-visited config channel args))
(defn on-visit-removed* [config channel & args]
(gen-wrap :event ::on-visit-removed config channel args))
| null | https://raw.githubusercontent.com/binaryage/chromex/33834ba5dd4f4238a3c51f99caa0416f30c308c5/src/exts/chromex/ext/history.cljs | clojure | -- events ----------------------------------------------------------------------------------------------------------------- | (ns chromex.ext.history (:require-macros [chromex.ext.history :refer [gen-wrap]])
(:require [chromex.core]))
-- functions --------------------------------------------------------------------------------------------------------------
(defn search* [config query]
(gen-wrap :function ::search config query))
(defn get-visits* [config details]
(gen-wrap :function ::get-visits config details))
(defn add-url* [config details]
(gen-wrap :function ::add-url config details))
(defn delete-url* [config details]
(gen-wrap :function ::delete-url config details))
(defn delete-range* [config range]
(gen-wrap :function ::delete-range config range))
(defn delete-all* [config]
(gen-wrap :function ::delete-all config))
(defn on-visited* [config channel & args]
(gen-wrap :event ::on-visited config channel args))
(defn on-visit-removed* [config channel & args]
(gen-wrap :event ::on-visit-removed config channel args))
|
12a0c5c394e27ff1692a1da3c2a0a970dfc43202be7fb1370c1386691a8794fe | Perry961002/SICP | exa3.3.2-queue.scm | ;队列的表示方式:将队列表示为一个表,并带有一个指向表的最后序对的指针
front - ptr,返回队头指针
(define (front-ptr queue) (car queue))
rear - ptr,返回队尾指针
(define (rear-ptr queue) (cdr queue))
修改两个指针
(define (set-front-ptr! queue item) (set-car! queue item))
(define (set-rear-ptr! queue item) (set-cdr! queue item))
;判断队列是否为空,如果一个队列的前端指针等于末端指针,那么就认为队空
(define (empty-queue? queue) (null? (front-ptr queue)))
构造函数
(define (make-queue) (cons '() '()))
;选择函数,得到队列前端的数据项
(define (front-queue queue)
(if (empty-queue? queue)
(error "FRONT called with an empty queue" queue)
(car (front-ptr queue))))
;向队列插入数据项
(define (insert-queue! queue item)
(let ((new-pair (cons item '())))
(cond ((empty-queue? queue)
(set-front-ptr! queue new-pair)
(set-rear-ptr! queue new-pair)
queue)
(else
(set-cdr! (rear-ptr queue) new-pair)
(set-rear-ptr! queue new-pair)
queue))))
删除队列前端的数据项
(define (delete-queue! queue)
(cond ((empty-queue? queue)
(error "DELETE! called with an empty queue" queue))
(else
(set-front-ptr! queue (cdr (front-ptr queue)))
queue))) | null | https://raw.githubusercontent.com/Perry961002/SICP/89d539e600a73bec42d350592f0ac626e041bf16/Chap3/example/exa3.3.2-queue.scm | scheme | 队列的表示方式:将队列表示为一个表,并带有一个指向表的最后序对的指针
判断队列是否为空,如果一个队列的前端指针等于末端指针,那么就认为队空
选择函数,得到队列前端的数据项
向队列插入数据项 |
front - ptr,返回队头指针
(define (front-ptr queue) (car queue))
rear - ptr,返回队尾指针
(define (rear-ptr queue) (cdr queue))
修改两个指针
(define (set-front-ptr! queue item) (set-car! queue item))
(define (set-rear-ptr! queue item) (set-cdr! queue item))
(define (empty-queue? queue) (null? (front-ptr queue)))
构造函数
(define (make-queue) (cons '() '()))
(define (front-queue queue)
(if (empty-queue? queue)
(error "FRONT called with an empty queue" queue)
(car (front-ptr queue))))
(define (insert-queue! queue item)
(let ((new-pair (cons item '())))
(cond ((empty-queue? queue)
(set-front-ptr! queue new-pair)
(set-rear-ptr! queue new-pair)
queue)
(else
(set-cdr! (rear-ptr queue) new-pair)
(set-rear-ptr! queue new-pair)
queue))))
删除队列前端的数据项
(define (delete-queue! queue)
(cond ((empty-queue? queue)
(error "DELETE! called with an empty queue" queue))
(else
(set-front-ptr! queue (cdr (front-ptr queue)))
queue))) |
60f43d85f1bb85b4fa107ee59a3a0e7d56061a8695b7825de906aa5742ab1a45 | lambda-fairy/sylvia | Core.hs | # LANGUAGE TemplateHaskell #
-- |
Module : . Render . Core
Copyright :
--
-- Maintainer :
-- Portability : portable
--
-- This module provides the algorithm used to render expressions.
module Sylvia.Render.Core
(
-- * A function
render
) where
import Control.Applicative
import Data.Foldable (foldMap)
import Data.Lens.Common
import Data.Lens.Template
import Data.List (foldl')
import Data.Monoid
import Data.Void (Void, vacuous)
import Sylvia.Render.Backend
import Sylvia.Render.Pair
import Sylvia.Model
type Rhyme = [RhymeUnit]
-- | Specifies a /rhyme line/: a straight line protruding from the left
-- edge of a bounding box, connecting a variable to the sub-expression
-- that uses it.
data RhymeUnit = RhymeUnit
{ _ruIndex :: Integer
, _ruDest :: Int
}
deriving (Show)
$(makeLens ''RhymeUnit)
-- | The result of a rendering operation.
data Result r = Result
{ _image :: r
-- ^ The rendered image.
, _size :: PInt
-- ^ The size of the image's bounding box in grid units, when all
-- round things are removed.
, _rhyme :: Rhyme
-- ^ The expression's rhyme.
, _midY :: Int
-- ^ The Y offset of the expression's ear and throat, measured
-- from the /bottom/ of its bounding box.
}
deriving (Show)
$(makeLens ''Result)
-- | Render an expression, returning an image along with its size.
render :: Backend r => Exp Void -> (r, PInt)
render e =
let Result image' size' rhyme' _ = render' $ vacuous e
in case rhyme' of
[] -> (image', size')
_ -> error $ "render: the impossible happened -- "
++ "extra free variables: " ++ show rhyme'
-- | Render an expression, with extra juicy options.
render' :: Backend r => Exp Integer -> Result r
render' e = case e of
Ref x -> Result mempty (0 :| 0) [RhymeUnit x 0] 0
Lam e' -> renderLambda e'
App a b -> case a of
Lam _ -> renderBeside a b
_ -> renderAtop a b
| Render two expressions next to each other .
renderBeside :: Backend r => Exp Integer -> Exp Integer -> Result r
renderBeside a b = Result image' size' rhyme' aMidY
where
image' = aImage <> bImage
(Result aImage (aWidth :| aHeight) aRhyme aMidY,
Result bImage (bWidth :| bHeight) bRhyme _)
= alignMiddle
(render' a)
(shiftX (-aWidth) . extendThroatLine (1 :| 0) $ render' b)
size' = (aWidth + bWidth :| max aHeight bHeight)
TODO
| Align two expressions so that their ears and throats are at the same
-- height.
alignMiddle :: Backend r => Result r -> Result r -> (Result r, Result r)
alignMiddle a b
= (shiftY' (highest - a^.midY) a,
shiftY' (highest - b^.midY) b)
where
highest = min (a^.midY) (b^.midY)
| Render the first expression above the second , connected with an
-- applicator dot.
renderAtop :: Backend r => Exp Integer -> Exp Integer -> Result r
renderAtop a b = Result image' size' rhyme' bMidY
where
image' = mconcat $
Draw the two sub - expressions
[ aImage
, bImage
-- Extend the lower sub-expression's rhyme lines so it matches up
with the one above
, relativeTo (-bWidth :| 0)
$ extendAcross (bWidth - aWidth) bRhyme
-- Connect them with a vertical line
, drawLine (0 :| aMidY) (0 :| bMidY)
-- Application dot
, drawDot (0 :| bMidY)
]
Result aImage (aWidth :| aHeight) aRhyme aMidY
= shiftY (-1 - bHeight) . extendThroatLine (bWidth :| 0) $ render' a
Result bImage (bWidth :| bHeight) bRhyme bMidY
= extendThroatLine (1 :| 0) $ render' b
size' = (aWidth :| aHeight + bHeight + 1)
rhyme' = aRhyme ++ bRhyme
-- | Add a small line sticking out of an expression's throat, moving
-- the image and increasing the size to compensate.
extendThroatLine
:: Backend r
=> PInt -- ^ The endpoint of the line, relative to the throat.
-> Result r
-> Result r
extendThroatLine (dx :| dy) a
= modL image (<> line)
. setL midY outerMidY
. shiftX' (-dx)
$ a
where
line = drawZigzag (-dx :| a^.midY) (0 :| outerMidY)
outerMidY = a^.midY + dy
-- | Render a lambda expression.
renderLambda :: Backend r => Exp (Inc Integer) -> Result r
renderLambda = renderLambda' . fmap shiftDown
where
renderLambda' e = enclose . extendRhyme . addLine $ render' e
where
addLine = extendThroatLine . (1 :|) $ if containsLam e then (-1) else 0
-- | Return whether there is a nested box touching the bottom edge of the
-- bounding box. If True, it means that everything in the image should
be shifted down one unit , making the throat line zigzag .
containsLam :: Exp a -> Bool
containsLam e = case e of
Ref _ -> False
Lam _ -> True
App _ b -> containsLam b
-- | Put an expression in a box.
enclose :: Backend r => Result r -> Result r
enclose = enclose' . shiftY (-1)
where
enclose' a
= modL image (<> drawBox (negateP boxSize) boxSize (a^.midY))
. setL size boxSize
$ a
where
boxSize = a^.size |+| (0 :| 2)
-- | Render an expression's rhyme.
extendRhyme :: Backend r => Result r -> Result r
extendRhyme a
= modL image (<> rhymeImage)
. modL rhyme flattenRhyme
. modL size ((fstP ^+= 1) . (sndP ^%= max rhymeHeight))
$ a
where
rhymeHeight = fromInteger . maximum0 $ map (^.ruIndex) (a^.rhyme)
rhymeImage = relativeTo (-(a^.size^.fstP) :| 0) $ foldMap drawRhymeUnit (a^.rhyme)
where drawRhymeUnit (RhymeUnit index dest)
= drawLine (-1 :| makeOffset index) (0 :| dest)
flattenRhyme inner =
[ RhymeUnit (pred index) (makeOffset index)
| RhymeUnit index _ <- inner, index > 0 ]
makeOffset = (a^.midY -) . fromInteger
| Like ' maximum ' , but returns a zero on an empty list rather than
-- throwing a hissy fit.
maximum0 :: (Num a, Ord a) => [a] -> a
maximum0 = foldl' max 0
-- | Shift an image horizontally by a specified amount.
shiftX :: Backend r => Int -> Result r -> Result r
shiftX dx = modL image (relativeTo (dx :| 0))
-- | Like 'shiftX', but expand the image's bounding box rather than shifting it.
shiftX' :: Backend r => Int -> Result r -> Result r
shiftX' dx
= modL size (fstP ^+= abs dx)
. shiftX dx
-- | Shift an image vertically by a specified amount, changing the rhyme
-- and throat position to compensate.
shiftY :: Backend r => Int -> Result r -> Result r
shiftY dy
= modL image (relativeTo (0 :| dy))
. modL rhyme (map (ruDest ^+= dy))
. modL midY (+ dy)
-- | Like 'shiftY', but expand the image's bounding box rather than shifting it.
shiftY' :: Backend r => Int -> Result r -> Result r
shiftY' dy
= modL size (sndP ^+= abs dy)
. shiftY dy
extendAcross :: Backend r => Int -> Rhyme -> r
extendAcross dx = foldMap $ drawLine
<$> ( 0 :|) . getL ruDest
<*> (dx :|) . getL ruDest
| null | https://raw.githubusercontent.com/lambda-fairy/sylvia/8c34f8f6e48a2887c6674e048ea73c971acb1657/Sylvia/Render/Core.hs | haskell | |
Maintainer :
Portability : portable
This module provides the algorithm used to render expressions.
* A function
| Specifies a /rhyme line/: a straight line protruding from the left
edge of a bounding box, connecting a variable to the sub-expression
that uses it.
| The result of a rendering operation.
^ The rendered image.
^ The size of the image's bounding box in grid units, when all
round things are removed.
^ The expression's rhyme.
^ The Y offset of the expression's ear and throat, measured
from the /bottom/ of its bounding box.
| Render an expression, returning an image along with its size.
| Render an expression, with extra juicy options.
height.
applicator dot.
Extend the lower sub-expression's rhyme lines so it matches up
Connect them with a vertical line
Application dot
| Add a small line sticking out of an expression's throat, moving
the image and increasing the size to compensate.
^ The endpoint of the line, relative to the throat.
| Render a lambda expression.
| Return whether there is a nested box touching the bottom edge of the
bounding box. If True, it means that everything in the image should
| Put an expression in a box.
| Render an expression's rhyme.
throwing a hissy fit.
| Shift an image horizontally by a specified amount.
| Like 'shiftX', but expand the image's bounding box rather than shifting it.
| Shift an image vertically by a specified amount, changing the rhyme
and throat position to compensate.
| Like 'shiftY', but expand the image's bounding box rather than shifting it. | # LANGUAGE TemplateHaskell #
Module : . Render . Core
Copyright :
module Sylvia.Render.Core
(
render
) where
import Control.Applicative
import Data.Foldable (foldMap)
import Data.Lens.Common
import Data.Lens.Template
import Data.List (foldl')
import Data.Monoid
import Data.Void (Void, vacuous)
import Sylvia.Render.Backend
import Sylvia.Render.Pair
import Sylvia.Model
type Rhyme = [RhymeUnit]
data RhymeUnit = RhymeUnit
{ _ruIndex :: Integer
, _ruDest :: Int
}
deriving (Show)
$(makeLens ''RhymeUnit)
data Result r = Result
{ _image :: r
, _size :: PInt
, _rhyme :: Rhyme
, _midY :: Int
}
deriving (Show)
$(makeLens ''Result)
render :: Backend r => Exp Void -> (r, PInt)
render e =
let Result image' size' rhyme' _ = render' $ vacuous e
in case rhyme' of
[] -> (image', size')
_ -> error $ "render: the impossible happened -- "
++ "extra free variables: " ++ show rhyme'
render' :: Backend r => Exp Integer -> Result r
render' e = case e of
Ref x -> Result mempty (0 :| 0) [RhymeUnit x 0] 0
Lam e' -> renderLambda e'
App a b -> case a of
Lam _ -> renderBeside a b
_ -> renderAtop a b
| Render two expressions next to each other .
renderBeside :: Backend r => Exp Integer -> Exp Integer -> Result r
renderBeside a b = Result image' size' rhyme' aMidY
where
image' = aImage <> bImage
(Result aImage (aWidth :| aHeight) aRhyme aMidY,
Result bImage (bWidth :| bHeight) bRhyme _)
= alignMiddle
(render' a)
(shiftX (-aWidth) . extendThroatLine (1 :| 0) $ render' b)
size' = (aWidth + bWidth :| max aHeight bHeight)
TODO
| Align two expressions so that their ears and throats are at the same
alignMiddle :: Backend r => Result r -> Result r -> (Result r, Result r)
alignMiddle a b
= (shiftY' (highest - a^.midY) a,
shiftY' (highest - b^.midY) b)
where
highest = min (a^.midY) (b^.midY)
| Render the first expression above the second , connected with an
renderAtop :: Backend r => Exp Integer -> Exp Integer -> Result r
renderAtop a b = Result image' size' rhyme' bMidY
where
image' = mconcat $
Draw the two sub - expressions
[ aImage
, bImage
with the one above
, relativeTo (-bWidth :| 0)
$ extendAcross (bWidth - aWidth) bRhyme
, drawLine (0 :| aMidY) (0 :| bMidY)
, drawDot (0 :| bMidY)
]
Result aImage (aWidth :| aHeight) aRhyme aMidY
= shiftY (-1 - bHeight) . extendThroatLine (bWidth :| 0) $ render' a
Result bImage (bWidth :| bHeight) bRhyme bMidY
= extendThroatLine (1 :| 0) $ render' b
size' = (aWidth :| aHeight + bHeight + 1)
rhyme' = aRhyme ++ bRhyme
extendThroatLine
:: Backend r
-> Result r
-> Result r
extendThroatLine (dx :| dy) a
= modL image (<> line)
. setL midY outerMidY
. shiftX' (-dx)
$ a
where
line = drawZigzag (-dx :| a^.midY) (0 :| outerMidY)
outerMidY = a^.midY + dy
renderLambda :: Backend r => Exp (Inc Integer) -> Result r
renderLambda = renderLambda' . fmap shiftDown
where
renderLambda' e = enclose . extendRhyme . addLine $ render' e
where
addLine = extendThroatLine . (1 :|) $ if containsLam e then (-1) else 0
be shifted down one unit , making the throat line zigzag .
containsLam :: Exp a -> Bool
containsLam e = case e of
Ref _ -> False
Lam _ -> True
App _ b -> containsLam b
enclose :: Backend r => Result r -> Result r
enclose = enclose' . shiftY (-1)
where
enclose' a
= modL image (<> drawBox (negateP boxSize) boxSize (a^.midY))
. setL size boxSize
$ a
where
boxSize = a^.size |+| (0 :| 2)
extendRhyme :: Backend r => Result r -> Result r
extendRhyme a
= modL image (<> rhymeImage)
. modL rhyme flattenRhyme
. modL size ((fstP ^+= 1) . (sndP ^%= max rhymeHeight))
$ a
where
rhymeHeight = fromInteger . maximum0 $ map (^.ruIndex) (a^.rhyme)
rhymeImage = relativeTo (-(a^.size^.fstP) :| 0) $ foldMap drawRhymeUnit (a^.rhyme)
where drawRhymeUnit (RhymeUnit index dest)
= drawLine (-1 :| makeOffset index) (0 :| dest)
flattenRhyme inner =
[ RhymeUnit (pred index) (makeOffset index)
| RhymeUnit index _ <- inner, index > 0 ]
makeOffset = (a^.midY -) . fromInteger
| Like ' maximum ' , but returns a zero on an empty list rather than
maximum0 :: (Num a, Ord a) => [a] -> a
maximum0 = foldl' max 0
shiftX :: Backend r => Int -> Result r -> Result r
shiftX dx = modL image (relativeTo (dx :| 0))
shiftX' :: Backend r => Int -> Result r -> Result r
shiftX' dx
= modL size (fstP ^+= abs dx)
. shiftX dx
shiftY :: Backend r => Int -> Result r -> Result r
shiftY dy
= modL image (relativeTo (0 :| dy))
. modL rhyme (map (ruDest ^+= dy))
. modL midY (+ dy)
shiftY' :: Backend r => Int -> Result r -> Result r
shiftY' dy
= modL size (sndP ^+= abs dy)
. shiftY dy
extendAcross :: Backend r => Int -> Rhyme -> r
extendAcross dx = foldMap $ drawLine
<$> ( 0 :|) . getL ruDest
<*> (dx :|) . getL ruDest
|
4645c8c52fd0e467ed77372a5588f2008c54aa5e92294613c69f5cbc33686644 | metametadata/carry | view_model.cljs | (ns app.view-model
(:require [app.util :as util]
[friend-list.core :as friend-list]
[counter.core :as counter]
[carry-reagent.core :as carry-reagent]))
(def view-model (-> (fn [model]
(carry-reagent/track-keys model [:friend-list-visible? :counter-visible?]))
(util/include-view-model :friend-list-subapp friend-list/view-model)
(util/include-view-model :counter-subapp counter/view-model))) | null | https://raw.githubusercontent.com/metametadata/carry/fa5c7cd0d8f1b71edca70330acc97c6245638efb/examples/subapps/src/app/view_model.cljs | clojure | (ns app.view-model
(:require [app.util :as util]
[friend-list.core :as friend-list]
[counter.core :as counter]
[carry-reagent.core :as carry-reagent]))
(def view-model (-> (fn [model]
(carry-reagent/track-keys model [:friend-list-visible? :counter-visible?]))
(util/include-view-model :friend-list-subapp friend-list/view-model)
(util/include-view-model :counter-subapp counter/view-model))) | |
64b24cb1b6f52ad37f618608449875c73cd0f408aff6f1875c3574aecb9129d4 | kenkeiras/EPC | master.erl | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% master:init().
% master:getImages(URLs).
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-module(master).
Interface
-export([init/0, getImages/1]).
%% Debug methods
-export([printPendingURLs/0]).
%% Internal Exports
-export([loop/3, removeDuplicatedURLs/2, printList/1]).
-define(SLAVE_LIMIT, 50).
-define(PENDING_URLS_LIMIT, 500).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Init
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
init() ->
process_flag(trap_exit, true),
PID = spawn(master, loop, [[], [], 0]),
register(master, PID).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Debug utilities
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
printPendingURLs() ->
master ! printPendingURLs.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Tells the master to enqueue new URLs.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
getImages(URLs) ->
master ! {getImages, URLs}.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Removes duplicated URLs from incoming ones
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
removeDuplicatedURLs(URLsToAdd, ProcessedURLs) ->
removeDuplicatedURLs([URL || URL <- URLsToAdd, not lists:any(fun(ProcessedURL) -> ProcessedURL == URL end, ProcessedURLs)]).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Removes duplicated URLs from incoming ones
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
removeRepeatedInList(URLs) ->
removeRepeatedInList(URLs, []).
removeRepeatedInList([H | T], Acc) ->
case lists:member(H, Acc) of
true ->
removeRepeatedInList(T, Acc);
false ->
removeRepeatedInList(T, [H | Acc])
end;
removeRepeatedInList([], Acc) ->
Acc.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Removes URLs already in database
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
removeDuplicatedURLs(URLs) ->
UniqURLs = removeRepeatedInList(URLs),
[URL || URL <- UniqURLs, not epc_dba:checkURL(URL)].
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Creates slaves to crawl URLs if we have available slots
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
assignURLs([], Slaves, _) -> % No new URLs to assign
{[], Slaves};
assignURLs(PendingURLs, Slaves, 0) -> % No Slave slots
{PendingURLs, Slaves};
assignURLs([URL | T], Slaves, SlaveSlots) ->
Slave = spawn(epc_slave, init, [ URL]),
epc_dba:storeCrawledURL([URL]),
assignURLs(T, [Slave | Slaves], SlaveSlots - 1).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Gets URL sublist
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
trim(URLs, Count) when Count =< ?PENDING_URLS_LIMIT ->
URLs;
trim(URLs, _) ->
lists:sublist(URLs, 1, ?PENDING_URLS_LIMIT).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Pritns list
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
printList([]) ->
io:fwrite("~n", []);
printList([H | T]) ->
io:fwrite("~s~n", [H]),
printList(T).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Store urls in database
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
storeURLs([]) ->
ok;
storeURLs([H | T]) ->
epc_dba:storeCrawledURL(H),
storeURLs(T).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Receive messages
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
checkMessages(PendingURLs, Slaves, SlaveCount) ->
receive
% Debug messages
stop ->
ok;
printPendingURLs ->
printList(PendingURLs),
loop(PendingURLs, Slaves, SlaveCount);
% Client messages
{foundURLs, Slave, {CrawledURLs, NewUrls}} ->
CurrentSlaves = lists:delete(Slave, Slaves),
storeURLs(CrawledURLs),
UrlsToAdd = removeDuplicatedURLs(NewUrls), % Remove duplicated URLs already in database
loop( sets:to_list(sets:from_list(UrlsToAdd ++ PendingURLs)), CurrentSlaves, SlaveCount - 1);
{getImages, URLsToAdd} ->
NewURLs = removeDuplicatedURLs(URLsToAdd), % Remove duplicated URLs
L = NewURLs ++ PendingURLs,
CurrentRemaingURLs = trim(L, length(L)), % Trims the URL list to the maximum number of pending URLs
loop(CurrentRemaingURLs, Slaves, SlaveCount);
{'EXIT', _, _} ->
io:fwrite("Something wrong has happened", []),
exit(self(), error)
after
100 ->
loop(PendingURLs, Slaves, SlaveCount) % Loop forever
end.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Main loop
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
loop(PendingURLs, Slaves, SlaveCount) when SlaveCount < ?SLAVE_LIMIT ->
{RemainingURLs, CurrentSlaves} = assignURLs(PendingURLs, Slaves, ?SLAVE_LIMIT - SlaveCount),
checkMessages(RemainingURLs, CurrentSlaves, length(CurrentSlaves));
loop(PendingURLs, Slaves, SlaveCount) ->
checkMessages(PendingURLs, Slaves, SlaveCount).
| null | https://raw.githubusercontent.com/kenkeiras/EPC/1e903475e1e597fd602158df45c5805a764333bf/src/master.erl | erlang |
master:init().
master:getImages(URLs).
Debug methods
Internal Exports
Debug utilities
Tells the master to enqueue new URLs.
Removes duplicated URLs from incoming ones
Removes duplicated URLs from incoming ones
Removes URLs already in database
Creates slaves to crawl URLs if we have available slots
No new URLs to assign
No Slave slots
Gets URL sublist
Store urls in database
Receive messages
Debug messages
Client messages
Remove duplicated URLs already in database
Remove duplicated URLs
Trims the URL list to the maximum number of pending URLs
Loop forever
Main loop
|
-module(master).
Interface
-export([init/0, getImages/1]).
-export([printPendingURLs/0]).
-export([loop/3, removeDuplicatedURLs/2, printList/1]).
-define(SLAVE_LIMIT, 50).
-define(PENDING_URLS_LIMIT, 500).
Init
init() ->
process_flag(trap_exit, true),
PID = spawn(master, loop, [[], [], 0]),
register(master, PID).
printPendingURLs() ->
master ! printPendingURLs.
getImages(URLs) ->
master ! {getImages, URLs}.
removeDuplicatedURLs(URLsToAdd, ProcessedURLs) ->
removeDuplicatedURLs([URL || URL <- URLsToAdd, not lists:any(fun(ProcessedURL) -> ProcessedURL == URL end, ProcessedURLs)]).
removeRepeatedInList(URLs) ->
removeRepeatedInList(URLs, []).
removeRepeatedInList([H | T], Acc) ->
case lists:member(H, Acc) of
true ->
removeRepeatedInList(T, Acc);
false ->
removeRepeatedInList(T, [H | Acc])
end;
removeRepeatedInList([], Acc) ->
Acc.
removeDuplicatedURLs(URLs) ->
UniqURLs = removeRepeatedInList(URLs),
[URL || URL <- UniqURLs, not epc_dba:checkURL(URL)].
{[], Slaves};
{PendingURLs, Slaves};
assignURLs([URL | T], Slaves, SlaveSlots) ->
Slave = spawn(epc_slave, init, [ URL]),
epc_dba:storeCrawledURL([URL]),
assignURLs(T, [Slave | Slaves], SlaveSlots - 1).
trim(URLs, Count) when Count =< ?PENDING_URLS_LIMIT ->
URLs;
trim(URLs, _) ->
lists:sublist(URLs, 1, ?PENDING_URLS_LIMIT).
Pritns list
printList([]) ->
io:fwrite("~n", []);
printList([H | T]) ->
io:fwrite("~s~n", [H]),
printList(T).
storeURLs([]) ->
ok;
storeURLs([H | T]) ->
epc_dba:storeCrawledURL(H),
storeURLs(T).
checkMessages(PendingURLs, Slaves, SlaveCount) ->
receive
stop ->
ok;
printPendingURLs ->
printList(PendingURLs),
loop(PendingURLs, Slaves, SlaveCount);
{foundURLs, Slave, {CrawledURLs, NewUrls}} ->
CurrentSlaves = lists:delete(Slave, Slaves),
storeURLs(CrawledURLs),
loop( sets:to_list(sets:from_list(UrlsToAdd ++ PendingURLs)), CurrentSlaves, SlaveCount - 1);
{getImages, URLsToAdd} ->
L = NewURLs ++ PendingURLs,
loop(CurrentRemaingURLs, Slaves, SlaveCount);
{'EXIT', _, _} ->
io:fwrite("Something wrong has happened", []),
exit(self(), error)
after
100 ->
end.
loop(PendingURLs, Slaves, SlaveCount) when SlaveCount < ?SLAVE_LIMIT ->
{RemainingURLs, CurrentSlaves} = assignURLs(PendingURLs, Slaves, ?SLAVE_LIMIT - SlaveCount),
checkMessages(RemainingURLs, CurrentSlaves, length(CurrentSlaves));
loop(PendingURLs, Slaves, SlaveCount) ->
checkMessages(PendingURLs, Slaves, SlaveCount).
|
b2cb94024e7916600e9635ec0c0849ca38a3cda0f643ffccc2d54354a17b19f6 | puppetlabs/puppetdb | status_test.clj | (ns puppetlabs.puppetdb.status-test
(:require [clojure.test :refer :all]
[puppetlabs.puppetdb.pdb-routing]
[puppetlabs.puppetdb.scf.storage-utils :as sutils]
[puppetlabs.puppetdb.testutils :as tu]
[puppetlabs.puppetdb.utils :refer [base-url->str-with-prefix]]
[puppetlabs.puppetdb.cheshire :as json]
[clj-http.client :as client]
[puppetlabs.puppetdb.testutils.services :as svc-utils]))
(deftest normal-status
(svc-utils/with-puppetdb-instance
(let [{:keys [body] :as pdb-resp} (-> svc-utils/*base-url*
(assoc :prefix "/status/v1/services")
base-url->str-with-prefix
client/get)
pdb-status (:puppetdb-status (json/parse-string body true))]
(tu/assert-success! pdb-resp)
(is (= "running" (:state pdb-status)))
(is (= {:maintenance_mode? false
:read_db_up? true
:write_db_up? true
:write_dbs_up? true
:write_db {:default {:up? true}}
:queue_depth 0}
(:status pdb-status))))))
(deftest maintenance-mode-status
(with-redefs [puppetlabs.puppetdb.pdb-routing/maint-mode? (constantly true)]
(svc-utils/with-puppetdb-instance
(let [{:keys [body status]} (-> svc-utils/*base-url*
(assoc :prefix "/status/v1/services")
base-url->str-with-prefix
(client/get {:throw-exceptions false}))
pdb-status (:puppetdb-status (json/parse-string body true))]
(is (= 503 status))
(is (= "starting" (:state pdb-status)))
(is (= {:maintenance_mode? true
:read_db_up? true
:write_db_up? true
:write_dbs_up? true
:write_db {:default {:up? true}}
:queue_depth 0}
(:status pdb-status)))))))
(deftest status-when-databases-down
;; FIXME: better test
(svc-utils/with-puppetdb-instance
(with-redefs [sutils/db-up? (constantly false)]
(let [{:keys [body status]} (-> svc-utils/*base-url*
(assoc :prefix "/status/v1/services")
base-url->str-with-prefix
(client/get {:throw-exceptions false}))
pdb-status (:puppetdb-status (json/parse-string body true))]
(is (= 503 status))
(is (= "error" (:state pdb-status)))
(is (= {:maintenance_mode? false
:read_db_up? false
:write_db_up? false
:write_dbs_up? false
:write_db {:default {:up? false}}
:queue_depth 0}
(:status pdb-status)))))))
| null | https://raw.githubusercontent.com/puppetlabs/puppetdb/b3d6d10555561657150fa70b6d1e609fba9c0eda/test/puppetlabs/puppetdb/status_test.clj | clojure | FIXME: better test | (ns puppetlabs.puppetdb.status-test
(:require [clojure.test :refer :all]
[puppetlabs.puppetdb.pdb-routing]
[puppetlabs.puppetdb.scf.storage-utils :as sutils]
[puppetlabs.puppetdb.testutils :as tu]
[puppetlabs.puppetdb.utils :refer [base-url->str-with-prefix]]
[puppetlabs.puppetdb.cheshire :as json]
[clj-http.client :as client]
[puppetlabs.puppetdb.testutils.services :as svc-utils]))
(deftest normal-status
(svc-utils/with-puppetdb-instance
(let [{:keys [body] :as pdb-resp} (-> svc-utils/*base-url*
(assoc :prefix "/status/v1/services")
base-url->str-with-prefix
client/get)
pdb-status (:puppetdb-status (json/parse-string body true))]
(tu/assert-success! pdb-resp)
(is (= "running" (:state pdb-status)))
(is (= {:maintenance_mode? false
:read_db_up? true
:write_db_up? true
:write_dbs_up? true
:write_db {:default {:up? true}}
:queue_depth 0}
(:status pdb-status))))))
(deftest maintenance-mode-status
(with-redefs [puppetlabs.puppetdb.pdb-routing/maint-mode? (constantly true)]
(svc-utils/with-puppetdb-instance
(let [{:keys [body status]} (-> svc-utils/*base-url*
(assoc :prefix "/status/v1/services")
base-url->str-with-prefix
(client/get {:throw-exceptions false}))
pdb-status (:puppetdb-status (json/parse-string body true))]
(is (= 503 status))
(is (= "starting" (:state pdb-status)))
(is (= {:maintenance_mode? true
:read_db_up? true
:write_db_up? true
:write_dbs_up? true
:write_db {:default {:up? true}}
:queue_depth 0}
(:status pdb-status)))))))
(deftest status-when-databases-down
(svc-utils/with-puppetdb-instance
(with-redefs [sutils/db-up? (constantly false)]
(let [{:keys [body status]} (-> svc-utils/*base-url*
(assoc :prefix "/status/v1/services")
base-url->str-with-prefix
(client/get {:throw-exceptions false}))
pdb-status (:puppetdb-status (json/parse-string body true))]
(is (= 503 status))
(is (= "error" (:state pdb-status)))
(is (= {:maintenance_mode? false
:read_db_up? false
:write_db_up? false
:write_dbs_up? false
:write_db {:default {:up? false}}
:queue_depth 0}
(:status pdb-status)))))))
|
46c1d83457f9ba959ef1ee5c9f849ecd51dd82b1cebdd23805535267d53aa8df | collaborativetrust/WikiTrust | text.mli |
Copyright ( c ) 2007 - 2009 The Regents of the University of California
All rights reserved .
Authors :
Redistribution and use in source and binary forms , with or without
modification , are permitted provided that the following conditions are met :
1 . Redistributions of source code must retain the above copyright notice ,
this list of conditions and the following disclaimer .
2 . Redistributions in binary form must reproduce the above copyright notice ,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution .
3 . The names of the contributors may not be used to endorse or promote
products derived from this software without specific prior written
permission .
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS "
AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT LIMITED TO , THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED . IN NO EVENT SHALL THE COPYRIGHT OWNER OR
LIABLE FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR
CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED TO , PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES ; LOSS OF USE , DATA , OR PROFITS ; OR BUSINESS
INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , IN
CONTRACT , STRICT LIABILITY , OR TORT ( INCLUDING NEGLIGENCE OR OTHERWISE )
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE , EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE .
Copyright (c) 2007-2009 The Regents of the University of California
All rights reserved.
Authors: Luca de Alfaro
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. The names of the contributors may not be used to endorse or promote
products derived from this software without specific prior written
permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*)
(** Version number of the code *)
val version: string
(** The type of words *)
type word = string
(** The type of word tokens *)
type sep_t =
Title_start of string * int
(** start sequence for a title *)
| Title_end of string * int
(** end sequence for a title *)
| Par_break of string
(** paragraph break sequence *)
| Bullet of string * int
(** bullet sequence *)
| Indent of string * int
(** indentation sequence *)
| Space of string
(** normal whitespace, without a newline *)
| Newline of string
(** whitespace containing a newline char *)
| Armored_char of string * int
* Armored char such as & nbsp ;
| Table_line of string * int
(** table tag that needs to be alone on a line *)
| Table_cell of string * int
(** table tag that signals the start of a cell *)
| Table_caption of string * int
(** table tag for the caption *)
| Tag of string * int
(** tag, along with the position in the word array *)
| Word of string * int
(** normal word, along with the position in the word array *)
| Redirect of string * int
(** redirection tag, along with the position in the word array *)
* [ split_into_words disarm rearm sv ]
splits a of strings [ sv ] into an array of words .
The [ disarm ] flag controls whether the & amp ; & gt ; and similar tags from the
input are translated into & > and so forth . The rearm flag controls whether
the opposite transformation occurs once the parsing has occurred .
Typically :
To convert from dumps to blobs , use : true false
To convert from to blobs , use : false false
To convert from dumps to xml for use : true true
splits a Vec of strings [sv] into an array of words.
The [disarm] flag controls whether the & > and similar tags from the
input are translated into & > and so forth. The rearm flag controls whether
the opposite transformation occurs once the parsing has occurred.
Typically:
To convert from dumps to blobs, use: true false
To convert from jason to blobs, use: false false
To convert from dumps to xml for mwdumper use: true true
*)
val split_into_words : bool -> bool -> string Vec.t -> word array
* [ split_into_words_seps_and_info disarm rearm sv ] splits a of strings [ sv ] into :
- an array of words ( excluding separators , such as white space , etc )
- an array of trust values of words ( float )
- an array of origins of words ( int )
- an array of authors of words ( string )
- an array giving , for each word , its place in the sep array ( int )
- the array of seps , where words , etc , have their position in the word array
annotated .
- an array of words (excluding separators, such as white space, etc)
- an array of trust values of words (float)
- an array of origins of words (int)
- an array of authors of words (string)
- an array giving, for each word, its place in the sep array (int)
- the array of seps, where words, etc, have their position in the word array
annotated.
*)
val split_into_words_seps_and_info :
bool -> bool -> string Vec.t ->
((word array) * (float array) * (int array) * (string array)
* (int array) * (sep_t array))
* [ split_into_words_and_seps disarm rearm sv ] splits a of strings [ sv ] into :
- an array of words ( excluding separators , such as white space , etc )
- an array giving , for each word , its place in the sep array ( int )
- the array of seps , where words , etc , have their position in the word array
annotated .
- an array of words (excluding separators, such as white space, etc)
- an array giving, for each word, its place in the sep array (int)
- the array of seps, where words, etc, have their position in the word array
annotated.
*)
val split_into_words_and_seps :
bool -> bool -> string Vec.t -> ((word array) * (int array) * (sep_t array))
(** [print_words wa] prints the words in the word array [wa]. *)
val print_words : word array -> unit
(** [print_seps wa] prints the array of separators [wa] *)
val print_seps : sep_t array -> unit
(** [print_words_and_seps ws sp] prints the array of words [ws] and the array of separators [wa] *)
val print_words_and_seps : (word array) -> (sep_t array) -> unit
* Arms and disarms XML & lt ; etc . tags .
val xml_arm : string -> string
val xml_disarm : string -> string
| null | https://raw.githubusercontent.com/collaborativetrust/WikiTrust/9dd056e65c37a22f67d600dd1e87753aa0ec9e2c/analysis/text.mli | ocaml | * Version number of the code
* The type of words
* The type of word tokens
* start sequence for a title
* end sequence for a title
* paragraph break sequence
* bullet sequence
* indentation sequence
* normal whitespace, without a newline
* whitespace containing a newline char
* table tag that needs to be alone on a line
* table tag that signals the start of a cell
* table tag for the caption
* tag, along with the position in the word array
* normal word, along with the position in the word array
* redirection tag, along with the position in the word array
* [print_words wa] prints the words in the word array [wa].
* [print_seps wa] prints the array of separators [wa]
* [print_words_and_seps ws sp] prints the array of words [ws] and the array of separators [wa] |
Copyright ( c ) 2007 - 2009 The Regents of the University of California
All rights reserved .
Authors :
Redistribution and use in source and binary forms , with or without
modification , are permitted provided that the following conditions are met :
1 . Redistributions of source code must retain the above copyright notice ,
this list of conditions and the following disclaimer .
2 . Redistributions in binary form must reproduce the above copyright notice ,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution .
3 . The names of the contributors may not be used to endorse or promote
products derived from this software without specific prior written
permission .
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS "
AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT LIMITED TO , THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED . IN NO EVENT SHALL THE COPYRIGHT OWNER OR
LIABLE FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR
CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED TO , PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES ; LOSS OF USE , DATA , OR PROFITS ; OR BUSINESS
INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , IN
CONTRACT , STRICT LIABILITY , OR TORT ( INCLUDING NEGLIGENCE OR OTHERWISE )
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE , EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE .
Copyright (c) 2007-2009 The Regents of the University of California
All rights reserved.
Authors: Luca de Alfaro
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. The names of the contributors may not be used to endorse or promote
products derived from this software without specific prior written
permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*)
val version: string
type word = string
type sep_t =
Title_start of string * int
| Title_end of string * int
| Par_break of string
| Bullet of string * int
| Indent of string * int
| Space of string
| Newline of string
| Armored_char of string * int
* Armored char such as & nbsp ;
| Table_line of string * int
| Table_cell of string * int
| Table_caption of string * int
| Tag of string * int
| Word of string * int
| Redirect of string * int
* [ split_into_words disarm rearm sv ]
splits a of strings [ sv ] into an array of words .
The [ disarm ] flag controls whether the & amp ; & gt ; and similar tags from the
input are translated into & > and so forth . The rearm flag controls whether
the opposite transformation occurs once the parsing has occurred .
Typically :
To convert from dumps to blobs , use : true false
To convert from to blobs , use : false false
To convert from dumps to xml for use : true true
splits a Vec of strings [sv] into an array of words.
The [disarm] flag controls whether the & > and similar tags from the
input are translated into & > and so forth. The rearm flag controls whether
the opposite transformation occurs once the parsing has occurred.
Typically:
To convert from dumps to blobs, use: true false
To convert from jason to blobs, use: false false
To convert from dumps to xml for mwdumper use: true true
*)
val split_into_words : bool -> bool -> string Vec.t -> word array
* [ split_into_words_seps_and_info disarm rearm sv ] splits a of strings [ sv ] into :
- an array of words ( excluding separators , such as white space , etc )
- an array of trust values of words ( float )
- an array of origins of words ( int )
- an array of authors of words ( string )
- an array giving , for each word , its place in the sep array ( int )
- the array of seps , where words , etc , have their position in the word array
annotated .
- an array of words (excluding separators, such as white space, etc)
- an array of trust values of words (float)
- an array of origins of words (int)
- an array of authors of words (string)
- an array giving, for each word, its place in the sep array (int)
- the array of seps, where words, etc, have their position in the word array
annotated.
*)
val split_into_words_seps_and_info :
bool -> bool -> string Vec.t ->
((word array) * (float array) * (int array) * (string array)
* (int array) * (sep_t array))
* [ split_into_words_and_seps disarm rearm sv ] splits a of strings [ sv ] into :
- an array of words ( excluding separators , such as white space , etc )
- an array giving , for each word , its place in the sep array ( int )
- the array of seps , where words , etc , have their position in the word array
annotated .
- an array of words (excluding separators, such as white space, etc)
- an array giving, for each word, its place in the sep array (int)
- the array of seps, where words, etc, have their position in the word array
annotated.
*)
val split_into_words_and_seps :
bool -> bool -> string Vec.t -> ((word array) * (int array) * (sep_t array))
val print_words : word array -> unit
val print_seps : sep_t array -> unit
val print_words_and_seps : (word array) -> (sep_t array) -> unit
* Arms and disarms XML & lt ; etc . tags .
val xml_arm : string -> string
val xml_disarm : string -> string
|
95188dea4bd973872c06a12306d9773360e52df157a41897e8e4a61cff3a9605 | NorfairKing/easyspec | Eighteen.hs | # LANGUAGE NoImplicitPrelude #
module Eighteen where
import Prelude
(Bool(..), Maybe(..), (&&), (+), (-), (||), concat, const, drop,
map, maybe, not, take)
{-# ANN module "HLint: ignore Use foldr" #-}
myId :: a -> a
myId a = a
myPlusPlus :: [a] -> [a] -> [a]
myPlusPlus (a:as) bs = a : myPlusPlus as bs
myPlusPlus [] bs = bs
myReverse :: [a] -> [a]
myReverse [] = []
myReverse (a:as) = as `myPlusPlus` [a]
| null | https://raw.githubusercontent.com/NorfairKing/easyspec/b038b45a375cc0bed2b00c255b508bc06419c986/examples/runtime/Eighteen.hs | haskell | # ANN module "HLint: ignore Use foldr" # | # LANGUAGE NoImplicitPrelude #
module Eighteen where
import Prelude
(Bool(..), Maybe(..), (&&), (+), (-), (||), concat, const, drop,
map, maybe, not, take)
myId :: a -> a
myId a = a
myPlusPlus :: [a] -> [a] -> [a]
myPlusPlus (a:as) bs = a : myPlusPlus as bs
myPlusPlus [] bs = bs
myReverse :: [a] -> [a]
myReverse [] = []
myReverse (a:as) = as `myPlusPlus` [a]
|
d61d5733d7cd1c88d9ce18d4c24338d55651e3e8c308044785b197b928a8e77a | ryanpbrewster/haskell | data_recovery.hs |
- Your friends decided to make a fun of you . They 've installed a script to
- your computer which shuffled all of the words within a text . It was a joke ,
- so they 've left hints for each sentence which allow you to easily rebuild
- your data . The challenge is to write a program which reconstructs each
- sentence out of a set of words , you need to find out how to use a given hint
- and print out the original sentences .
- Input sample :
-
- Your program should accept as its first argument a path to a filename . Each
- line is a test case . Each test case consists of a set of words and
- a sequence of numbers separated by a semicolon . The words within a set and
- the numbers within a sequence are separated by a single whitespace . E.g.
- 1
- 2
- 3
- 2000 and was not However , implemented 1998 it until;9 8 3 4 1 5 7 2
- programming first The language;3 2 1
- programs Manchester The written ran in from;6 2 1 7 5 3 11 4 8 9
- Output sample :
-
- For each test case print out the reconstructed sentence one per line . E.g.
- 1
- 2
- 3
- However , it was not implemented until 1998 and 2000
- The first programming language
- The Manchester ran programs written in from 1952
-
- Constraints :
- The number of test cases is in range [ 20 , 40 ] .
- The words consist of ASCII upper and lower case letters , digits and punctuation .
- Your friends decided to make a fun of you. They've installed a script to
- your computer which shuffled all of the words within a text. It was a joke,
- so they've left hints for each sentence which allow you to easily rebuild
- your data. The challenge is to write a program which reconstructs each
- sentence out of a set of words, you need to find out how to use a given hint
- and print out the original sentences.
- Input sample:
-
- Your program should accept as its first argument a path to a filename. Each
- line is a test case. Each test case consists of a set of words and
- a sequence of numbers separated by a semicolon. The words within a set and
- the numbers within a sequence are separated by a single whitespace. E.g.
- 1
- 2
- 3
- 2000 and was not However, implemented 1998 it until;9 8 3 4 1 5 7 2
- programming first The language;3 2 1
- programs Manchester The written ran Mark 1952 1 in Autocode from;6 2 1 7 5 3 11 4 8 9
- Output sample:
-
- For each test case print out the reconstructed sentence one per line. E.g.
- 1
- 2
- 3
- However, it was not implemented until 1998 and 2000
- The first programming language
- The Manchester Mark 1 ran programs written in Autocode from 1952
-
- Constraints:
- The number of test cases is in range [20, 40].
- The words consist of ASCII upper and lower case letters, digits and punctuation.
-}
import System.Environment (getArgs)
import Text.ParserCombinators.Parsec
import Data.List (sort)
main = do
args <- getArgs
txt <- readFile (head args)
putStr $ solveProblem txt
solveProblem txt = let lns = lines txt
inps = map parseLine lns
anss = map reconstructSentence inps
in unlines anss
reconstructSentence (ws, hints) =
let n = length ws
last_hint = n*(n+1) `div` 2 - sum hints
hints' = hints ++ [last_hint]
ws' = zip hints' ws
in unwords $ map snd $ sort ws'
{- Input-parsing nonsense -}
pLine = do
sentence <- many (noneOf ";")
char ';'
hints <- sepBy (many digit) (char ' ')
return (words sentence, map read hints)
parseLine :: String -> ([String], [Int])
parseLine input = case parse pLine "" input of
Left _ -> error $ "Improperly formatted line: " ++ input
Right v -> v
| null | https://raw.githubusercontent.com/ryanpbrewster/haskell/6edd0afe234008a48b4871032dedfd143ca6e412/CodeEval/data_recovery.hs | haskell | Input-parsing nonsense |
- Your friends decided to make a fun of you . They 've installed a script to
- your computer which shuffled all of the words within a text . It was a joke ,
- so they 've left hints for each sentence which allow you to easily rebuild
- your data . The challenge is to write a program which reconstructs each
- sentence out of a set of words , you need to find out how to use a given hint
- and print out the original sentences .
- Input sample :
-
- Your program should accept as its first argument a path to a filename . Each
- line is a test case . Each test case consists of a set of words and
- a sequence of numbers separated by a semicolon . The words within a set and
- the numbers within a sequence are separated by a single whitespace . E.g.
- 1
- 2
- 3
- 2000 and was not However , implemented 1998 it until;9 8 3 4 1 5 7 2
- programming first The language;3 2 1
- programs Manchester The written ran in from;6 2 1 7 5 3 11 4 8 9
- Output sample :
-
- For each test case print out the reconstructed sentence one per line . E.g.
- 1
- 2
- 3
- However , it was not implemented until 1998 and 2000
- The first programming language
- The Manchester ran programs written in from 1952
-
- Constraints :
- The number of test cases is in range [ 20 , 40 ] .
- The words consist of ASCII upper and lower case letters , digits and punctuation .
- Your friends decided to make a fun of you. They've installed a script to
- your computer which shuffled all of the words within a text. It was a joke,
- so they've left hints for each sentence which allow you to easily rebuild
- your data. The challenge is to write a program which reconstructs each
- sentence out of a set of words, you need to find out how to use a given hint
- and print out the original sentences.
- Input sample:
-
- Your program should accept as its first argument a path to a filename. Each
- line is a test case. Each test case consists of a set of words and
- a sequence of numbers separated by a semicolon. The words within a set and
- the numbers within a sequence are separated by a single whitespace. E.g.
- 1
- 2
- 3
- 2000 and was not However, implemented 1998 it until;9 8 3 4 1 5 7 2
- programming first The language;3 2 1
- programs Manchester The written ran Mark 1952 1 in Autocode from;6 2 1 7 5 3 11 4 8 9
- Output sample:
-
- For each test case print out the reconstructed sentence one per line. E.g.
- 1
- 2
- 3
- However, it was not implemented until 1998 and 2000
- The first programming language
- The Manchester Mark 1 ran programs written in Autocode from 1952
-
- Constraints:
- The number of test cases is in range [20, 40].
- The words consist of ASCII upper and lower case letters, digits and punctuation.
-}
import System.Environment (getArgs)
import Text.ParserCombinators.Parsec
import Data.List (sort)
main = do
args <- getArgs
txt <- readFile (head args)
putStr $ solveProblem txt
solveProblem txt = let lns = lines txt
inps = map parseLine lns
anss = map reconstructSentence inps
in unlines anss
reconstructSentence (ws, hints) =
let n = length ws
last_hint = n*(n+1) `div` 2 - sum hints
hints' = hints ++ [last_hint]
ws' = zip hints' ws
in unwords $ map snd $ sort ws'
pLine = do
sentence <- many (noneOf ";")
char ';'
hints <- sepBy (many digit) (char ' ')
return (words sentence, map read hints)
parseLine :: String -> ([String], [Int])
parseLine input = case parse pLine "" input of
Left _ -> error $ "Improperly formatted line: " ++ input
Right v -> v
|
ec2078b0fc5ad8b289e3de62199842a5f6fe75a145969f2ded0f15b657146082 | rizo/snowflake-os | closure.ml | (***********************************************************************)
(* *)
(* Objective Caml *)
(* *)
, projet Cristal , INRIA Rocquencourt
(* *)
Copyright 1996 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the Q Public License version 1.0 .
(* *)
(***********************************************************************)
$ Id$
(* Introduction of closures, uncurrying, recognition of direct calls *)
open Misc
open Asttypes
open Primitive
open Lambda
open Switch
open Clambda
Auxiliaries for compiling functions
let rec split_list n l =
if n <= 0 then ([], l) else begin
match l with
[] -> fatal_error "Closure.split_list"
| a::l -> let (l1, l2) = split_list (n-1) l in (a::l1, l2)
end
let rec build_closure_env env_param pos = function
[] -> Tbl.empty
| id :: rem ->
Tbl.add id (Uprim(Pfield pos, [Uvar env_param], Debuginfo.none))
(build_closure_env env_param (pos+1) rem)
Auxiliary for accessing globals . We change the name of the global
to the name of the corresponding asm symbol . This is done here
and no longer in so that approximations stored in .cmx files
contain the right names if the -for - pack option is active .
to the name of the corresponding asm symbol. This is done here
and no longer in Cmmgen so that approximations stored in .cmx files
contain the right names if the -for-pack option is active. *)
let getglobal id =
Uprim(Pgetglobal (Ident.create_persistent (Compilenv.symbol_for_global id)),
[], Debuginfo.none)
(* Check if a variable occurs in a [clambda] term. *)
let occurs_var var u =
let rec occurs = function
Uvar v -> v = var
| Uconst cst -> false
| Udirect_apply(lbl, args, _) -> List.exists occurs args
| Ugeneric_apply(funct, args, _) -> occurs funct || List.exists occurs args
| Uclosure(fundecls, clos) -> List.exists occurs clos
| Uoffset(u, ofs) -> occurs u
| Ulet(id, def, body) -> occurs def || occurs body
| Uletrec(decls, body) ->
List.exists (fun (id, u) -> occurs u) decls || occurs body
| Uprim(p, args, _) -> List.exists occurs args
| Uswitch(arg, s) ->
occurs arg ||
occurs_array s.us_actions_consts || occurs_array s.us_actions_blocks
| Ustaticfail (_, args) -> List.exists occurs args
| Ucatch(_, _, body, hdlr) -> occurs body || occurs hdlr
| Utrywith(body, exn, hdlr) -> occurs body || occurs hdlr
| Uifthenelse(cond, ifso, ifnot) ->
occurs cond || occurs ifso || occurs ifnot
| Usequence(u1, u2) -> occurs u1 || occurs u2
| Uwhile(cond, body) -> occurs cond || occurs body
| Ufor(id, lo, hi, dir, body) -> occurs lo || occurs hi || occurs body
| Uassign(id, u) -> id = var || occurs u
| Usend(_, met, obj, args, _) ->
occurs met || occurs obj || List.exists occurs args
and occurs_array a =
try
for i = 0 to Array.length a - 1 do
if occurs a.(i) then raise Exit
done;
false
with Exit ->
true
in occurs u
Determine whether the estimated size of a clambda term is below
some threshold
some threshold *)
let prim_size prim args =
match prim with
Pidentity -> 0
| Pgetglobal id -> 1
| Psetglobal id -> 1
| Pmakeblock(tag, mut) -> 5 + List.length args
| Pfield f -> 1
| Psetfield(f, isptr) -> if isptr then 4 else 1
| Pfloatfield f -> 1
| Psetfloatfield f -> 1
| Pduprecord _ -> 10 + List.length args
| Pccall p -> (if p.prim_alloc then 10 else 4) + List.length args
| Praise -> 4
| Pstringlength -> 5
| Pstringrefs | Pstringsets -> 6
| Pmakearray kind -> 5 + List.length args
| Parraylength kind -> if kind = Pgenarray then 6 else 2
| Parrayrefu kind -> if kind = Pgenarray then 12 else 2
| Parraysetu kind -> if kind = Pgenarray then 16 else 4
| Parrayrefs kind -> if kind = Pgenarray then 18 else 8
| Parraysets kind -> if kind = Pgenarray then 22 else 10
| Pbittest -> 3
| Pbigarrayref(_, ndims, _, _) -> 4 + ndims * 6
| Pbigarrayset(_, ndims, _, _) -> 4 + ndims * 6
| _ -> 2 (* arithmetic and comparisons *)
(* Very raw approximation of switch cost *)
let lambda_smaller lam threshold =
let size = ref 0 in
let rec lambda_size lam =
if !size > threshold then raise Exit;
match lam with
Uvar v -> ()
| Uconst(Const_base(Const_int _ | Const_char _ | Const_float _ |
Const_int32 _ | Const_int64 _ | Const_nativeint _) |
Const_pointer _) -> incr size
| Uconst _ ->
raise Exit (* avoid duplication of structured constants *)
| Udirect_apply(fn, args, _) ->
size := !size + 4; lambda_list_size args
| Ugeneric_apply(fn, args, _) ->
size := !size + 6; lambda_size fn; lambda_list_size args
| Uclosure(defs, vars) ->
raise Exit (* inlining would duplicate function definitions *)
| Uoffset(lam, ofs) ->
incr size; lambda_size lam
| Ulet(id, lam, body) ->
lambda_size lam; lambda_size body
| Uletrec(bindings, body) ->
raise Exit (* usually too large *)
| Uprim(prim, args, _) ->
size := !size + prim_size prim args;
lambda_list_size args
| Uswitch(lam, cases) ->
if Array.length cases.us_actions_consts > 1 then size := !size + 5 ;
if Array.length cases.us_actions_blocks > 1 then size := !size + 5 ;
lambda_size lam;
lambda_array_size cases.us_actions_consts ;
lambda_array_size cases.us_actions_blocks
| Ustaticfail (_,args) -> lambda_list_size args
| Ucatch(_, _, body, handler) ->
incr size; lambda_size body; lambda_size handler
| Utrywith(body, id, handler) ->
size := !size + 8; lambda_size body; lambda_size handler
| Uifthenelse(cond, ifso, ifnot) ->
size := !size + 2;
lambda_size cond; lambda_size ifso; lambda_size ifnot
| Usequence(lam1, lam2) ->
lambda_size lam1; lambda_size lam2
| Uwhile(cond, body) ->
size := !size + 2; lambda_size cond; lambda_size body
| Ufor(id, low, high, dir, body) ->
size := !size + 4; lambda_size low; lambda_size high; lambda_size body
| Uassign(id, lam) ->
incr size; lambda_size lam
| Usend(_, met, obj, args, _) ->
size := !size + 8;
lambda_size met; lambda_size obj; lambda_list_size args
and lambda_list_size l = List.iter lambda_size l
and lambda_array_size a = Array.iter lambda_size a in
try
lambda_size lam; !size <= threshold
with Exit ->
false
Check if a clambda term is ` ` pure '' ,
that is without side - effects * and * not containing function definitions
that is without side-effects *and* not containing function definitions *)
let rec is_pure_clambda = function
Uvar v -> true
| Uconst cst -> true
| Uprim((Psetglobal _ | Psetfield _ | Psetfloatfield _ | Pduprecord _ |
Pccall _ | Praise | Poffsetref _ | Pstringsetu | Pstringsets |
Parraysetu _ | Parraysets _ | Pbigarrayset _), _, _) -> false
| Uprim(p, args, _) -> List.for_all is_pure_clambda args
| _ -> false
(* Simplify primitive operations on integers *)
let make_const_int n = (Uconst(Const_base(Const_int n)), Value_integer n)
let make_const_ptr n = (Uconst(Const_pointer n), Value_constptr n)
let make_const_bool b = make_const_ptr(if b then 1 else 0)
let simplif_prim_pure p (args, approxs) dbg =
match approxs with
[Value_integer x] ->
begin match p with
Pidentity -> make_const_int x
| Pnegint -> make_const_int (-x)
| Poffsetint y -> make_const_int (x + y)
| _ -> (Uprim(p, args, dbg), Value_unknown)
end
| [Value_integer x; Value_integer y] ->
begin match p with
Paddint -> make_const_int(x + y)
| Psubint -> make_const_int(x - y)
| Pmulint -> make_const_int(x * y)
| Pdivint when y <> 0 -> make_const_int(x / y)
| Pmodint when y <> 0 -> make_const_int(x mod y)
| Pandint -> make_const_int(x land y)
| Porint -> make_const_int(x lor y)
| Pxorint -> make_const_int(x lxor y)
| Plslint -> make_const_int(x lsl y)
| Plsrint -> make_const_int(x lsr y)
| Pasrint -> make_const_int(x asr y)
| Pintcomp cmp ->
let result = match cmp with
Ceq -> x = y
| Cneq -> x <> y
| Clt -> x < y
| Cgt -> x > y
| Cle -> x <= y
| Cge -> x >= y in
make_const_bool result
| _ -> (Uprim(p, args, dbg), Value_unknown)
end
| [Value_constptr x] ->
begin match p with
Pidentity -> make_const_ptr x
| Pnot -> make_const_bool(x = 0)
| Pisint -> make_const_bool true
| _ -> (Uprim(p, args, dbg), Value_unknown)
end
| [Value_constptr x; Value_constptr y] ->
begin match p with
Psequand -> make_const_bool(x <> 0 && y <> 0)
| Psequor -> make_const_bool(x <> 0 || y <> 0)
| _ -> (Uprim(p, args, dbg), Value_unknown)
end
| _ ->
(Uprim(p, args, dbg), Value_unknown)
let simplif_prim p (args, approxs as args_approxs) dbg =
if List.for_all is_pure_clambda args
then simplif_prim_pure p args_approxs dbg
else (Uprim(p, args, dbg), Value_unknown)
(* Substitute variables in a [ulambda] term (a body of an inlined function)
and perform some more simplifications on integer primitives.
Also perform alpha-conversion on let-bound identifiers to avoid
clashes with locally-generated identifiers.
The variables must not be assigned in the term.
This is used to substitute "trivial" arguments for parameters
during inline expansion, and also for the translation of let rec
over functions. *)
let approx_ulam = function
Uconst(Const_base(Const_int n)) -> Value_integer n
| Uconst(Const_base(Const_char c)) -> Value_integer(Char.code c)
| Uconst(Const_pointer n) -> Value_constptr n
| _ -> Value_unknown
let rec substitute sb ulam =
match ulam with
Uvar v ->
begin try Tbl.find v sb with Not_found -> ulam end
| Uconst cst -> ulam
| Udirect_apply(lbl, args, dbg) ->
Udirect_apply(lbl, List.map (substitute sb) args, dbg)
| Ugeneric_apply(fn, args, dbg) ->
Ugeneric_apply(substitute sb fn, List.map (substitute sb) args, dbg)
| Uclosure(defs, env) ->
Question : should we rename function labels as well ? Otherwise ,
there is a risk that function labels are not globally unique .
This should not happen in the current system because :
- Inlined function bodies contain no nodes
( cf . function [ lambda_smaller ] )
- When we substitute offsets for idents bound by let rec
in [ close ] , case [ ] , we discard the original
let rec body and use only the substituted term .
there is a risk that function labels are not globally unique.
This should not happen in the current system because:
- Inlined function bodies contain no Uclosure nodes
(cf. function [lambda_smaller])
- When we substitute offsets for idents bound by let rec
in [close], case [Lletrec], we discard the original
let rec body and use only the substituted term. *)
Uclosure(defs, List.map (substitute sb) env)
| Uoffset(u, ofs) -> Uoffset(substitute sb u, ofs)
| Ulet(id, u1, u2) ->
let id' = Ident.rename id in
Ulet(id', substitute sb u1, substitute (Tbl.add id (Uvar id') sb) u2)
| Uletrec(bindings, body) ->
let bindings1 =
List.map (fun (id, rhs) -> (id, Ident.rename id, rhs)) bindings in
let sb' =
List.fold_right
(fun (id, id', _) s -> Tbl.add id (Uvar id') s)
bindings1 sb in
Uletrec(
List.map (fun (id, id', rhs) -> (id', substitute sb' rhs)) bindings1,
substitute sb' body)
| Uprim(p, args, dbg) ->
let sargs = List.map (substitute sb) args in
let (res, _) = simplif_prim p (sargs, List.map approx_ulam sargs) dbg in
res
| Uswitch(arg, sw) ->
Uswitch(substitute sb arg,
{ sw with
us_actions_consts =
Array.map (substitute sb) sw.us_actions_consts;
us_actions_blocks =
Array.map (substitute sb) sw.us_actions_blocks;
})
| Ustaticfail (nfail, args) ->
Ustaticfail (nfail, List.map (substitute sb) args)
| Ucatch(nfail, ids, u1, u2) ->
Ucatch(nfail, ids, substitute sb u1, substitute sb u2)
| Utrywith(u1, id, u2) ->
let id' = Ident.rename id in
Utrywith(substitute sb u1, id', substitute (Tbl.add id (Uvar id') sb) u2)
| Uifthenelse(u1, u2, u3) ->
begin match substitute sb u1 with
Uconst(Const_pointer n) ->
if n <> 0 then substitute sb u2 else substitute sb u3
| su1 ->
Uifthenelse(su1, substitute sb u2, substitute sb u3)
end
| Usequence(u1, u2) -> Usequence(substitute sb u1, substitute sb u2)
| Uwhile(u1, u2) -> Uwhile(substitute sb u1, substitute sb u2)
| Ufor(id, u1, u2, dir, u3) ->
let id' = Ident.rename id in
Ufor(id', substitute sb u1, substitute sb u2, dir,
substitute (Tbl.add id (Uvar id') sb) u3)
| Uassign(id, u) ->
let id' =
try
match Tbl.find id sb with Uvar i -> i | _ -> assert false
with Not_found ->
id in
Uassign(id', substitute sb u)
| Usend(k, u1, u2, ul, dbg) ->
Usend(k, substitute sb u1, substitute sb u2, List.map (substitute sb) ul, dbg)
(* Perform an inline expansion *)
let is_simple_argument = function
Uvar _ -> true
| Uconst(Const_base(Const_int _ | Const_char _ | Const_float _ |
Const_int32 _ | Const_int64 _ | Const_nativeint _)) ->
true
| Uconst(Const_pointer _) -> true
| _ -> false
let no_effects = function
Uclosure _ -> true
| Uconst(Const_base(Const_string _)) -> true
| u -> is_simple_argument u
let rec bind_params_rec subst params args body =
match (params, args) with
([], []) -> substitute subst body
| (p1 :: pl, a1 :: al) ->
if is_simple_argument a1 then
bind_params_rec (Tbl.add p1 a1 subst) pl al body
else begin
let p1' = Ident.rename p1 in
let body' =
bind_params_rec (Tbl.add p1 (Uvar p1') subst) pl al body in
if occurs_var p1 body then Ulet(p1', a1, body')
else if no_effects a1 then body'
else Usequence(a1, body')
end
| (_, _) -> assert false
let bind_params params args body =
(* Reverse parameters and arguments to preserve right-to-left
evaluation order (PR#2910). *)
bind_params_rec Tbl.empty (List.rev params) (List.rev args) body
(* Check if a lambda term is ``pure'',
that is without side-effects *and* not containing function definitions *)
let rec is_pure = function
Lvar v -> true
| Lconst cst -> true
| Lprim((Psetglobal _ | Psetfield _ | Psetfloatfield _ | Pduprecord _ |
Pccall _ | Praise | Poffsetref _ | Pstringsetu | Pstringsets |
Parraysetu _ | Parraysets _ | Pbigarrayset _), _) -> false
| Lprim(p, args) -> List.for_all is_pure args
| Levent(lam, ev) -> is_pure lam
| _ -> false
(* Generate a direct application *)
let direct_apply fundesc funct ufunct uargs =
let app_args =
if fundesc.fun_closed then uargs else uargs @ [ufunct] in
let app =
match fundesc.fun_inline with
None -> Udirect_apply(fundesc.fun_label, app_args, Debuginfo.none)
| Some(params, body) -> bind_params params app_args body in
If ufunct can contain side - effects or function definitions ,
we must make sure that it is evaluated exactly once .
If the function is not closed , we evaluate ufunct as part of the
arguments .
If the function is closed , we force the evaluation of ufunct first .
we must make sure that it is evaluated exactly once.
If the function is not closed, we evaluate ufunct as part of the
arguments.
If the function is closed, we force the evaluation of ufunct first. *)
if not fundesc.fun_closed || is_pure funct
then app
else Usequence(ufunct, app)
Add [ Value_integer ] or [ ] info to the approximation
of an application
of an application *)
let strengthen_approx appl approx =
match approx_ulam appl with
(Value_integer _ | Value_constptr _) as intapprox -> intapprox
| _ -> approx
If a term has approximation Value_integer or and is pure ,
replace it by an integer constant
replace it by an integer constant *)
let check_constant_result lam ulam approx =
match approx with
Value_integer n when is_pure lam -> make_const_int n
| Value_constptr n when is_pure lam -> make_const_ptr n
| _ -> (ulam, approx)
(* Evaluate an expression with known value for its side effects only,
or discard it if it's pure *)
let sequence_constant_expr lam ulam1 (ulam2, approx2 as res2) =
if is_pure lam then res2 else (Usequence(ulam1, ulam2), approx2)
(* Maintain the approximation of the global structure being defined *)
let global_approx = ref([||] : value_approximation array)
(* Maintain the nesting depth for functions *)
let function_nesting_depth = ref 0
let excessive_function_nesting_depth = 5
Decorate clambda term with debug information
let rec add_debug_info ev u =
match ev.lev_kind with
| Lev_after _ ->
begin match u with
| Udirect_apply(lbl, args, dinfo) ->
Udirect_apply(lbl, args, Debuginfo.from_call ev)
| Ugeneric_apply(Udirect_apply(lbl, args1, dinfo1),
args2, dinfo2) ->
Ugeneric_apply(Udirect_apply(lbl, args1, Debuginfo.from_call ev),
args2, Debuginfo.from_call ev)
| Ugeneric_apply(fn, args, dinfo) ->
Ugeneric_apply(fn, args, Debuginfo.from_call ev)
| Uprim(Praise, args, dinfo) ->
Uprim(Praise, args, Debuginfo.from_call ev)
| Uprim(p, args, dinfo) ->
Uprim(p, args, Debuginfo.from_call ev)
| Usend(kind, u1, u2, args, dinfo) ->
Usend(kind, u1, u2, args, Debuginfo.from_call ev)
| Usequence(u1, u2) ->
Usequence(u1, add_debug_info ev u2)
| _ -> u
end
| _ -> u
Uncurry an expression and explicitate closures .
Also return the approximation of the expression .
The approximation environment [ fenv ] maps idents to approximations .
Idents not bound in [ fenv ] approximate to [ Value_unknown ] .
The closure environment [ cenv ] maps idents to [ ulambda ] terms .
It is used to substitute environment accesses for free identifiers .
Also return the approximation of the expression.
The approximation environment [fenv] maps idents to approximations.
Idents not bound in [fenv] approximate to [Value_unknown].
The closure environment [cenv] maps idents to [ulambda] terms.
It is used to substitute environment accesses for free identifiers. *)
let close_approx_var fenv cenv id =
let approx = try Tbl.find id fenv with Not_found -> Value_unknown in
match approx with
Value_integer n ->
make_const_int n
| Value_constptr n ->
make_const_ptr n
| approx ->
let subst = try Tbl.find id cenv with Not_found -> Uvar id in
(subst, approx)
let close_var fenv cenv id =
let (ulam, app) = close_approx_var fenv cenv id in ulam
let rec close fenv cenv = function
Lvar id ->
close_approx_var fenv cenv id
| Lconst cst ->
begin match cst with
Const_base(Const_int n) -> (Uconst cst, Value_integer n)
| Const_base(Const_char c) -> (Uconst cst, Value_integer(Char.code c))
| Const_pointer n -> (Uconst cst, Value_constptr n)
| _ -> (Uconst cst, Value_unknown)
end
| Lfunction(kind, params, body) as funct ->
close_one_function fenv cenv (Ident.create "fun") funct
| Lapply(funct, args, loc) ->
let nargs = List.length args in
begin match (close fenv cenv funct, close_list fenv cenv args) with
((ufunct, Value_closure(fundesc, approx_res)),
[Uprim(Pmakeblock(_, _), uargs, _)])
when List.length uargs = - fundesc.fun_arity ->
let app = direct_apply fundesc funct ufunct uargs in
(app, strengthen_approx app approx_res)
| ((ufunct, Value_closure(fundesc, approx_res)), uargs)
when nargs = fundesc.fun_arity ->
let app = direct_apply fundesc funct ufunct uargs in
(app, strengthen_approx app approx_res)
| ((ufunct, Value_closure(fundesc, approx_res)), uargs)
when fundesc.fun_arity > 0 && nargs > fundesc.fun_arity ->
let (first_args, rem_args) = split_list fundesc.fun_arity uargs in
(Ugeneric_apply(direct_apply fundesc funct ufunct first_args,
rem_args, Debuginfo.none),
Value_unknown)
| ((ufunct, _), uargs) ->
(Ugeneric_apply(ufunct, uargs, Debuginfo.none), Value_unknown)
end
| Lsend(kind, met, obj, args) ->
let (umet, _) = close fenv cenv met in
let (uobj, _) = close fenv cenv obj in
(Usend(kind, umet, uobj, close_list fenv cenv args, Debuginfo.none),
Value_unknown)
| Llet(str, id, lam, body) ->
let (ulam, alam) = close_named fenv cenv id lam in
begin match (str, alam) with
(Variable, _) ->
let (ubody, abody) = close fenv cenv body in
(Ulet(id, ulam, ubody), abody)
| (_, (Value_integer _ | Value_constptr _))
when str = Alias || is_pure lam ->
close (Tbl.add id alam fenv) cenv body
| (_, _) ->
let (ubody, abody) = close (Tbl.add id alam fenv) cenv body in
(Ulet(id, ulam, ubody), abody)
end
| Lletrec(defs, body) ->
if List.for_all
(function (id, Lfunction(_, _, _)) -> true | _ -> false)
defs
then begin
(* Simple case: only function definitions *)
let (clos, infos) = close_functions fenv cenv defs in
let clos_ident = Ident.create "clos" in
let fenv_body =
List.fold_right
(fun (id, pos, approx) fenv -> Tbl.add id approx fenv)
infos fenv in
let (ubody, approx) = close fenv_body cenv body in
let sb =
List.fold_right
(fun (id, pos, approx) sb ->
Tbl.add id (Uoffset(Uvar clos_ident, pos)) sb)
infos Tbl.empty in
(Ulet(clos_ident, clos, substitute sb ubody),
approx)
end else begin
(* General case: recursive definition of values *)
let rec clos_defs = function
[] -> ([], fenv)
| (id, lam) :: rem ->
let (udefs, fenv_body) = clos_defs rem in
let (ulam, approx) = close fenv cenv lam in
((id, ulam) :: udefs, Tbl.add id approx fenv_body) in
let (udefs, fenv_body) = clos_defs defs in
let (ubody, approx) = close fenv_body cenv body in
(Uletrec(udefs, ubody), approx)
end
| Lprim(Pgetglobal id, []) as lam ->
check_constant_result lam
(getglobal id)
(Compilenv.global_approx id)
| Lprim(Pmakeblock(tag, mut) as prim, lams) ->
let (ulams, approxs) = List.split (List.map (close fenv cenv) lams) in
(Uprim(prim, ulams, Debuginfo.none),
begin match mut with
Immutable -> Value_tuple(Array.of_list approxs)
| Mutable -> Value_unknown
end)
| Lprim(Pfield n, [lam]) ->
let (ulam, approx) = close fenv cenv lam in
let fieldapprox =
match approx with
Value_tuple a when n < Array.length a -> a.(n)
| _ -> Value_unknown in
check_constant_result lam (Uprim(Pfield n, [ulam], Debuginfo.none)) fieldapprox
| Lprim(Psetfield(n, _), [Lprim(Pgetglobal id, []); lam]) ->
let (ulam, approx) = close fenv cenv lam in
(!global_approx).(n) <- approx;
(Uprim(Psetfield(n, false), [getglobal id; ulam], Debuginfo.none),
Value_unknown)
| Lprim(Praise, [Levent(arg, ev)]) ->
let (ulam, approx) = close fenv cenv arg in
(Uprim(Praise, [ulam], Debuginfo.from_raise ev),
Value_unknown)
| Lprim(p, args) ->
simplif_prim p (close_list_approx fenv cenv args) Debuginfo.none
| Lswitch(arg, sw) ->
NB : failaction might get copied , thus it should be some Lstaticraise
let (uarg, _) = close fenv cenv arg in
let const_index, const_actions =
close_switch fenv cenv sw.sw_consts sw.sw_numconsts sw.sw_failaction
and block_index, block_actions =
close_switch fenv cenv sw.sw_blocks sw.sw_numblocks sw.sw_failaction in
(Uswitch(uarg,
{us_index_consts = const_index;
us_actions_consts = const_actions;
us_index_blocks = block_index;
us_actions_blocks = block_actions}),
Value_unknown)
| Lstaticraise (i, args) ->
(Ustaticfail (i, close_list fenv cenv args), Value_unknown)
| Lstaticcatch(body, (i, vars), handler) ->
let (ubody, _) = close fenv cenv body in
let (uhandler, _) = close fenv cenv handler in
(Ucatch(i, vars, ubody, uhandler), Value_unknown)
| Ltrywith(body, id, handler) ->
let (ubody, _) = close fenv cenv body in
let (uhandler, _) = close fenv cenv handler in
(Utrywith(ubody, id, uhandler), Value_unknown)
| Lifthenelse(arg, ifso, ifnot) ->
begin match close fenv cenv arg with
(uarg, Value_constptr n) ->
sequence_constant_expr arg uarg
(close fenv cenv (if n = 0 then ifnot else ifso))
| (uarg, _ ) ->
let (uifso, _) = close fenv cenv ifso in
let (uifnot, _) = close fenv cenv ifnot in
(Uifthenelse(uarg, uifso, uifnot), Value_unknown)
end
| Lsequence(lam1, lam2) ->
let (ulam1, _) = close fenv cenv lam1 in
let (ulam2, approx) = close fenv cenv lam2 in
(Usequence(ulam1, ulam2), approx)
| Lwhile(cond, body) ->
let (ucond, _) = close fenv cenv cond in
let (ubody, _) = close fenv cenv body in
(Uwhile(ucond, ubody), Value_unknown)
| Lfor(id, lo, hi, dir, body) ->
let (ulo, _) = close fenv cenv lo in
let (uhi, _) = close fenv cenv hi in
let (ubody, _) = close fenv cenv body in
(Ufor(id, ulo, uhi, dir, ubody), Value_unknown)
| Lassign(id, lam) ->
let (ulam, _) = close fenv cenv lam in
(Uassign(id, ulam), Value_unknown)
| Levent(lam, ev) ->
let (ulam, approx) = close fenv cenv lam in
(add_debug_info ev ulam, approx)
| Lifused _ ->
assert false
and close_list fenv cenv = function
[] -> []
| lam :: rem ->
let (ulam, _) = close fenv cenv lam in
ulam :: close_list fenv cenv rem
and close_list_approx fenv cenv = function
[] -> ([], [])
| lam :: rem ->
let (ulam, approx) = close fenv cenv lam in
let (ulams, approxs) = close_list_approx fenv cenv rem in
(ulam :: ulams, approx :: approxs)
and close_named fenv cenv id = function
Lfunction(kind, params, body) as funct ->
close_one_function fenv cenv id funct
| lam ->
close fenv cenv lam
(* Build a shared closure for a set of mutually recursive functions *)
and close_functions fenv cenv fun_defs =
(* Update and check nesting depth *)
incr function_nesting_depth;
let initially_closed =
!function_nesting_depth < excessive_function_nesting_depth in
(* Determine the free variables of the functions *)
let fv =
IdentSet.elements (free_variables (Lletrec(fun_defs, lambda_unit))) in
(* Build the function descriptors for the functions.
Initially all functions are assumed not to need their environment
parameter. *)
let uncurried_defs =
List.map
(function
(id, Lfunction(kind, params, body)) ->
let label = Compilenv.make_symbol (Some (Ident.unique_name id)) in
let arity = List.length params in
let fundesc =
{fun_label = label;
fun_arity = (if kind = Tupled then -arity else arity);
fun_closed = initially_closed;
fun_inline = None } in
(id, params, body, fundesc)
| (_, _) -> fatal_error "Closure.close_functions")
fun_defs in
(* Build an approximate fenv for compiling the functions *)
let fenv_rec =
List.fold_right
(fun (id, params, body, fundesc) fenv ->
Tbl.add id (Value_closure(fundesc, Value_unknown)) fenv)
uncurried_defs fenv in
(* Determine the offsets of each function's closure in the shared block *)
let env_pos = ref (-1) in
let clos_offsets =
List.map
(fun (id, params, body, fundesc) ->
let pos = !env_pos + 1 in
env_pos := !env_pos + 1 + (if fundesc.fun_arity <> 1 then 3 else 2);
pos)
uncurried_defs in
let fv_pos = !env_pos in
(* This reference will be set to false if the hypothesis that a function
does not use its environment parameter is invalidated. *)
let useless_env = ref initially_closed in
(* Translate each function definition *)
let clos_fundef (id, params, body, fundesc) env_pos =
let env_param = Ident.create "env" in
let cenv_fv =
build_closure_env env_param (fv_pos - env_pos) fv in
let cenv_body =
List.fold_right2
(fun (id, params, arity, body) pos env ->
Tbl.add id (Uoffset(Uvar env_param, pos - env_pos)) env)
uncurried_defs clos_offsets cenv_fv in
let (ubody, approx) = close fenv_rec cenv_body body in
if !useless_env && occurs_var env_param ubody then useless_env := false;
let fun_params = if !useless_env then params else params @ [env_param] in
((fundesc.fun_label, fundesc.fun_arity, fun_params, ubody),
(id, env_pos, Value_closure(fundesc, approx))) in
(* Translate all function definitions. *)
let clos_info_list =
if initially_closed then begin
let cl = List.map2 clos_fundef uncurried_defs clos_offsets in
(* If the hypothesis that the environment parameters are useless has been
invalidated, then set [fun_closed] to false in all descriptions and
recompile *)
if !useless_env then cl else begin
List.iter
(fun (id, params, body, fundesc) -> fundesc.fun_closed <- false)
uncurried_defs;
List.map2 clos_fundef uncurried_defs clos_offsets
end
end else
(* Excessive closure nesting: assume environment parameter is used *)
List.map2 clos_fundef uncurried_defs clos_offsets
in
(* Update nesting depth *)
decr function_nesting_depth;
Return the node and the list of all identifiers defined ,
with offsets and approximations .
with offsets and approximations. *)
let (clos, infos) = List.split clos_info_list in
(Uclosure(clos, List.map (close_var fenv cenv) fv), infos)
Same , for one non - recursive function
and close_one_function fenv cenv id funct =
match close_functions fenv cenv [id, funct] with
((Uclosure([_, _, params, body], _) as clos),
[_, _, (Value_closure(fundesc, _) as approx)]) ->
(* See if the function can be inlined *)
if lambda_smaller body (!Clflags.inline_threshold + List.length params)
then fundesc.fun_inline <- Some(params, body);
(clos, approx)
| _ -> fatal_error "Closure.close_one_function"
(* Close a switch *)
and close_switch fenv cenv cases num_keys default =
let index = Array.create num_keys 0
and store = mk_store Lambda.same in
First default case
begin match default with
| Some def when List.length cases < num_keys ->
ignore (store.act_store def)
| _ -> ()
end ;
(* Then all other cases *)
List.iter
(fun (key,lam) ->
index.(key) <- store.act_store lam)
cases ;
(* Compile action *)
let actions =
Array.map
(fun lam ->
let ulam,_ = close fenv cenv lam in
ulam)
(store.act_get ()) in
match actions with
May happen when default is None
| _ -> index, actions
(* The entry point *)
let intro size lam =
function_nesting_depth := 0;
global_approx := Array.create size Value_unknown;
Compilenv.set_global_approx(Value_tuple !global_approx);
let (ulam, approx) = close Tbl.empty Tbl.empty lam in
global_approx := [||];
ulam
| null | https://raw.githubusercontent.com/rizo/snowflake-os/51df43d9ba715532d325e8880d3b8b2c589cd075/plugins/ocamlopt.opt/asmcomp/closure.ml | ocaml | *********************************************************************
Objective Caml
*********************************************************************
Introduction of closures, uncurrying, recognition of direct calls
Check if a variable occurs in a [clambda] term.
arithmetic and comparisons
Very raw approximation of switch cost
avoid duplication of structured constants
inlining would duplicate function definitions
usually too large
Simplify primitive operations on integers
Substitute variables in a [ulambda] term (a body of an inlined function)
and perform some more simplifications on integer primitives.
Also perform alpha-conversion on let-bound identifiers to avoid
clashes with locally-generated identifiers.
The variables must not be assigned in the term.
This is used to substitute "trivial" arguments for parameters
during inline expansion, and also for the translation of let rec
over functions.
Perform an inline expansion
Reverse parameters and arguments to preserve right-to-left
evaluation order (PR#2910).
Check if a lambda term is ``pure'',
that is without side-effects *and* not containing function definitions
Generate a direct application
Evaluate an expression with known value for its side effects only,
or discard it if it's pure
Maintain the approximation of the global structure being defined
Maintain the nesting depth for functions
Simple case: only function definitions
General case: recursive definition of values
Build a shared closure for a set of mutually recursive functions
Update and check nesting depth
Determine the free variables of the functions
Build the function descriptors for the functions.
Initially all functions are assumed not to need their environment
parameter.
Build an approximate fenv for compiling the functions
Determine the offsets of each function's closure in the shared block
This reference will be set to false if the hypothesis that a function
does not use its environment parameter is invalidated.
Translate each function definition
Translate all function definitions.
If the hypothesis that the environment parameters are useless has been
invalidated, then set [fun_closed] to false in all descriptions and
recompile
Excessive closure nesting: assume environment parameter is used
Update nesting depth
See if the function can be inlined
Close a switch
Then all other cases
Compile action
The entry point | , projet Cristal , INRIA Rocquencourt
Copyright 1996 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the Q Public License version 1.0 .
$ Id$
open Misc
open Asttypes
open Primitive
open Lambda
open Switch
open Clambda
Auxiliaries for compiling functions
let rec split_list n l =
if n <= 0 then ([], l) else begin
match l with
[] -> fatal_error "Closure.split_list"
| a::l -> let (l1, l2) = split_list (n-1) l in (a::l1, l2)
end
let rec build_closure_env env_param pos = function
[] -> Tbl.empty
| id :: rem ->
Tbl.add id (Uprim(Pfield pos, [Uvar env_param], Debuginfo.none))
(build_closure_env env_param (pos+1) rem)
Auxiliary for accessing globals . We change the name of the global
to the name of the corresponding asm symbol . This is done here
and no longer in so that approximations stored in .cmx files
contain the right names if the -for - pack option is active .
to the name of the corresponding asm symbol. This is done here
and no longer in Cmmgen so that approximations stored in .cmx files
contain the right names if the -for-pack option is active. *)
let getglobal id =
Uprim(Pgetglobal (Ident.create_persistent (Compilenv.symbol_for_global id)),
[], Debuginfo.none)
let occurs_var var u =
let rec occurs = function
Uvar v -> v = var
| Uconst cst -> false
| Udirect_apply(lbl, args, _) -> List.exists occurs args
| Ugeneric_apply(funct, args, _) -> occurs funct || List.exists occurs args
| Uclosure(fundecls, clos) -> List.exists occurs clos
| Uoffset(u, ofs) -> occurs u
| Ulet(id, def, body) -> occurs def || occurs body
| Uletrec(decls, body) ->
List.exists (fun (id, u) -> occurs u) decls || occurs body
| Uprim(p, args, _) -> List.exists occurs args
| Uswitch(arg, s) ->
occurs arg ||
occurs_array s.us_actions_consts || occurs_array s.us_actions_blocks
| Ustaticfail (_, args) -> List.exists occurs args
| Ucatch(_, _, body, hdlr) -> occurs body || occurs hdlr
| Utrywith(body, exn, hdlr) -> occurs body || occurs hdlr
| Uifthenelse(cond, ifso, ifnot) ->
occurs cond || occurs ifso || occurs ifnot
| Usequence(u1, u2) -> occurs u1 || occurs u2
| Uwhile(cond, body) -> occurs cond || occurs body
| Ufor(id, lo, hi, dir, body) -> occurs lo || occurs hi || occurs body
| Uassign(id, u) -> id = var || occurs u
| Usend(_, met, obj, args, _) ->
occurs met || occurs obj || List.exists occurs args
and occurs_array a =
try
for i = 0 to Array.length a - 1 do
if occurs a.(i) then raise Exit
done;
false
with Exit ->
true
in occurs u
Determine whether the estimated size of a clambda term is below
some threshold
some threshold *)
let prim_size prim args =
match prim with
Pidentity -> 0
| Pgetglobal id -> 1
| Psetglobal id -> 1
| Pmakeblock(tag, mut) -> 5 + List.length args
| Pfield f -> 1
| Psetfield(f, isptr) -> if isptr then 4 else 1
| Pfloatfield f -> 1
| Psetfloatfield f -> 1
| Pduprecord _ -> 10 + List.length args
| Pccall p -> (if p.prim_alloc then 10 else 4) + List.length args
| Praise -> 4
| Pstringlength -> 5
| Pstringrefs | Pstringsets -> 6
| Pmakearray kind -> 5 + List.length args
| Parraylength kind -> if kind = Pgenarray then 6 else 2
| Parrayrefu kind -> if kind = Pgenarray then 12 else 2
| Parraysetu kind -> if kind = Pgenarray then 16 else 4
| Parrayrefs kind -> if kind = Pgenarray then 18 else 8
| Parraysets kind -> if kind = Pgenarray then 22 else 10
| Pbittest -> 3
| Pbigarrayref(_, ndims, _, _) -> 4 + ndims * 6
| Pbigarrayset(_, ndims, _, _) -> 4 + ndims * 6
let lambda_smaller lam threshold =
let size = ref 0 in
let rec lambda_size lam =
if !size > threshold then raise Exit;
match lam with
Uvar v -> ()
| Uconst(Const_base(Const_int _ | Const_char _ | Const_float _ |
Const_int32 _ | Const_int64 _ | Const_nativeint _) |
Const_pointer _) -> incr size
| Uconst _ ->
| Udirect_apply(fn, args, _) ->
size := !size + 4; lambda_list_size args
| Ugeneric_apply(fn, args, _) ->
size := !size + 6; lambda_size fn; lambda_list_size args
| Uclosure(defs, vars) ->
| Uoffset(lam, ofs) ->
incr size; lambda_size lam
| Ulet(id, lam, body) ->
lambda_size lam; lambda_size body
| Uletrec(bindings, body) ->
| Uprim(prim, args, _) ->
size := !size + prim_size prim args;
lambda_list_size args
| Uswitch(lam, cases) ->
if Array.length cases.us_actions_consts > 1 then size := !size + 5 ;
if Array.length cases.us_actions_blocks > 1 then size := !size + 5 ;
lambda_size lam;
lambda_array_size cases.us_actions_consts ;
lambda_array_size cases.us_actions_blocks
| Ustaticfail (_,args) -> lambda_list_size args
| Ucatch(_, _, body, handler) ->
incr size; lambda_size body; lambda_size handler
| Utrywith(body, id, handler) ->
size := !size + 8; lambda_size body; lambda_size handler
| Uifthenelse(cond, ifso, ifnot) ->
size := !size + 2;
lambda_size cond; lambda_size ifso; lambda_size ifnot
| Usequence(lam1, lam2) ->
lambda_size lam1; lambda_size lam2
| Uwhile(cond, body) ->
size := !size + 2; lambda_size cond; lambda_size body
| Ufor(id, low, high, dir, body) ->
size := !size + 4; lambda_size low; lambda_size high; lambda_size body
| Uassign(id, lam) ->
incr size; lambda_size lam
| Usend(_, met, obj, args, _) ->
size := !size + 8;
lambda_size met; lambda_size obj; lambda_list_size args
and lambda_list_size l = List.iter lambda_size l
and lambda_array_size a = Array.iter lambda_size a in
try
lambda_size lam; !size <= threshold
with Exit ->
false
Check if a clambda term is ` ` pure '' ,
that is without side - effects * and * not containing function definitions
that is without side-effects *and* not containing function definitions *)
let rec is_pure_clambda = function
Uvar v -> true
| Uconst cst -> true
| Uprim((Psetglobal _ | Psetfield _ | Psetfloatfield _ | Pduprecord _ |
Pccall _ | Praise | Poffsetref _ | Pstringsetu | Pstringsets |
Parraysetu _ | Parraysets _ | Pbigarrayset _), _, _) -> false
| Uprim(p, args, _) -> List.for_all is_pure_clambda args
| _ -> false
let make_const_int n = (Uconst(Const_base(Const_int n)), Value_integer n)
let make_const_ptr n = (Uconst(Const_pointer n), Value_constptr n)
let make_const_bool b = make_const_ptr(if b then 1 else 0)
let simplif_prim_pure p (args, approxs) dbg =
match approxs with
[Value_integer x] ->
begin match p with
Pidentity -> make_const_int x
| Pnegint -> make_const_int (-x)
| Poffsetint y -> make_const_int (x + y)
| _ -> (Uprim(p, args, dbg), Value_unknown)
end
| [Value_integer x; Value_integer y] ->
begin match p with
Paddint -> make_const_int(x + y)
| Psubint -> make_const_int(x - y)
| Pmulint -> make_const_int(x * y)
| Pdivint when y <> 0 -> make_const_int(x / y)
| Pmodint when y <> 0 -> make_const_int(x mod y)
| Pandint -> make_const_int(x land y)
| Porint -> make_const_int(x lor y)
| Pxorint -> make_const_int(x lxor y)
| Plslint -> make_const_int(x lsl y)
| Plsrint -> make_const_int(x lsr y)
| Pasrint -> make_const_int(x asr y)
| Pintcomp cmp ->
let result = match cmp with
Ceq -> x = y
| Cneq -> x <> y
| Clt -> x < y
| Cgt -> x > y
| Cle -> x <= y
| Cge -> x >= y in
make_const_bool result
| _ -> (Uprim(p, args, dbg), Value_unknown)
end
| [Value_constptr x] ->
begin match p with
Pidentity -> make_const_ptr x
| Pnot -> make_const_bool(x = 0)
| Pisint -> make_const_bool true
| _ -> (Uprim(p, args, dbg), Value_unknown)
end
| [Value_constptr x; Value_constptr y] ->
begin match p with
Psequand -> make_const_bool(x <> 0 && y <> 0)
| Psequor -> make_const_bool(x <> 0 || y <> 0)
| _ -> (Uprim(p, args, dbg), Value_unknown)
end
| _ ->
(Uprim(p, args, dbg), Value_unknown)
let simplif_prim p (args, approxs as args_approxs) dbg =
if List.for_all is_pure_clambda args
then simplif_prim_pure p args_approxs dbg
else (Uprim(p, args, dbg), Value_unknown)
let approx_ulam = function
Uconst(Const_base(Const_int n)) -> Value_integer n
| Uconst(Const_base(Const_char c)) -> Value_integer(Char.code c)
| Uconst(Const_pointer n) -> Value_constptr n
| _ -> Value_unknown
let rec substitute sb ulam =
match ulam with
Uvar v ->
begin try Tbl.find v sb with Not_found -> ulam end
| Uconst cst -> ulam
| Udirect_apply(lbl, args, dbg) ->
Udirect_apply(lbl, List.map (substitute sb) args, dbg)
| Ugeneric_apply(fn, args, dbg) ->
Ugeneric_apply(substitute sb fn, List.map (substitute sb) args, dbg)
| Uclosure(defs, env) ->
Question : should we rename function labels as well ? Otherwise ,
there is a risk that function labels are not globally unique .
This should not happen in the current system because :
- Inlined function bodies contain no nodes
( cf . function [ lambda_smaller ] )
- When we substitute offsets for idents bound by let rec
in [ close ] , case [ ] , we discard the original
let rec body and use only the substituted term .
there is a risk that function labels are not globally unique.
This should not happen in the current system because:
- Inlined function bodies contain no Uclosure nodes
(cf. function [lambda_smaller])
- When we substitute offsets for idents bound by let rec
in [close], case [Lletrec], we discard the original
let rec body and use only the substituted term. *)
Uclosure(defs, List.map (substitute sb) env)
| Uoffset(u, ofs) -> Uoffset(substitute sb u, ofs)
| Ulet(id, u1, u2) ->
let id' = Ident.rename id in
Ulet(id', substitute sb u1, substitute (Tbl.add id (Uvar id') sb) u2)
| Uletrec(bindings, body) ->
let bindings1 =
List.map (fun (id, rhs) -> (id, Ident.rename id, rhs)) bindings in
let sb' =
List.fold_right
(fun (id, id', _) s -> Tbl.add id (Uvar id') s)
bindings1 sb in
Uletrec(
List.map (fun (id, id', rhs) -> (id', substitute sb' rhs)) bindings1,
substitute sb' body)
| Uprim(p, args, dbg) ->
let sargs = List.map (substitute sb) args in
let (res, _) = simplif_prim p (sargs, List.map approx_ulam sargs) dbg in
res
| Uswitch(arg, sw) ->
Uswitch(substitute sb arg,
{ sw with
us_actions_consts =
Array.map (substitute sb) sw.us_actions_consts;
us_actions_blocks =
Array.map (substitute sb) sw.us_actions_blocks;
})
| Ustaticfail (nfail, args) ->
Ustaticfail (nfail, List.map (substitute sb) args)
| Ucatch(nfail, ids, u1, u2) ->
Ucatch(nfail, ids, substitute sb u1, substitute sb u2)
| Utrywith(u1, id, u2) ->
let id' = Ident.rename id in
Utrywith(substitute sb u1, id', substitute (Tbl.add id (Uvar id') sb) u2)
| Uifthenelse(u1, u2, u3) ->
begin match substitute sb u1 with
Uconst(Const_pointer n) ->
if n <> 0 then substitute sb u2 else substitute sb u3
| su1 ->
Uifthenelse(su1, substitute sb u2, substitute sb u3)
end
| Usequence(u1, u2) -> Usequence(substitute sb u1, substitute sb u2)
| Uwhile(u1, u2) -> Uwhile(substitute sb u1, substitute sb u2)
| Ufor(id, u1, u2, dir, u3) ->
let id' = Ident.rename id in
Ufor(id', substitute sb u1, substitute sb u2, dir,
substitute (Tbl.add id (Uvar id') sb) u3)
| Uassign(id, u) ->
let id' =
try
match Tbl.find id sb with Uvar i -> i | _ -> assert false
with Not_found ->
id in
Uassign(id', substitute sb u)
| Usend(k, u1, u2, ul, dbg) ->
Usend(k, substitute sb u1, substitute sb u2, List.map (substitute sb) ul, dbg)
let is_simple_argument = function
Uvar _ -> true
| Uconst(Const_base(Const_int _ | Const_char _ | Const_float _ |
Const_int32 _ | Const_int64 _ | Const_nativeint _)) ->
true
| Uconst(Const_pointer _) -> true
| _ -> false
let no_effects = function
Uclosure _ -> true
| Uconst(Const_base(Const_string _)) -> true
| u -> is_simple_argument u
let rec bind_params_rec subst params args body =
match (params, args) with
([], []) -> substitute subst body
| (p1 :: pl, a1 :: al) ->
if is_simple_argument a1 then
bind_params_rec (Tbl.add p1 a1 subst) pl al body
else begin
let p1' = Ident.rename p1 in
let body' =
bind_params_rec (Tbl.add p1 (Uvar p1') subst) pl al body in
if occurs_var p1 body then Ulet(p1', a1, body')
else if no_effects a1 then body'
else Usequence(a1, body')
end
| (_, _) -> assert false
let bind_params params args body =
bind_params_rec Tbl.empty (List.rev params) (List.rev args) body
let rec is_pure = function
Lvar v -> true
| Lconst cst -> true
| Lprim((Psetglobal _ | Psetfield _ | Psetfloatfield _ | Pduprecord _ |
Pccall _ | Praise | Poffsetref _ | Pstringsetu | Pstringsets |
Parraysetu _ | Parraysets _ | Pbigarrayset _), _) -> false
| Lprim(p, args) -> List.for_all is_pure args
| Levent(lam, ev) -> is_pure lam
| _ -> false
let direct_apply fundesc funct ufunct uargs =
let app_args =
if fundesc.fun_closed then uargs else uargs @ [ufunct] in
let app =
match fundesc.fun_inline with
None -> Udirect_apply(fundesc.fun_label, app_args, Debuginfo.none)
| Some(params, body) -> bind_params params app_args body in
If ufunct can contain side - effects or function definitions ,
we must make sure that it is evaluated exactly once .
If the function is not closed , we evaluate ufunct as part of the
arguments .
If the function is closed , we force the evaluation of ufunct first .
we must make sure that it is evaluated exactly once.
If the function is not closed, we evaluate ufunct as part of the
arguments.
If the function is closed, we force the evaluation of ufunct first. *)
if not fundesc.fun_closed || is_pure funct
then app
else Usequence(ufunct, app)
Add [ Value_integer ] or [ ] info to the approximation
of an application
of an application *)
let strengthen_approx appl approx =
match approx_ulam appl with
(Value_integer _ | Value_constptr _) as intapprox -> intapprox
| _ -> approx
If a term has approximation Value_integer or and is pure ,
replace it by an integer constant
replace it by an integer constant *)
let check_constant_result lam ulam approx =
match approx with
Value_integer n when is_pure lam -> make_const_int n
| Value_constptr n when is_pure lam -> make_const_ptr n
| _ -> (ulam, approx)
let sequence_constant_expr lam ulam1 (ulam2, approx2 as res2) =
if is_pure lam then res2 else (Usequence(ulam1, ulam2), approx2)
let global_approx = ref([||] : value_approximation array)
let function_nesting_depth = ref 0
let excessive_function_nesting_depth = 5
Decorate clambda term with debug information
let rec add_debug_info ev u =
match ev.lev_kind with
| Lev_after _ ->
begin match u with
| Udirect_apply(lbl, args, dinfo) ->
Udirect_apply(lbl, args, Debuginfo.from_call ev)
| Ugeneric_apply(Udirect_apply(lbl, args1, dinfo1),
args2, dinfo2) ->
Ugeneric_apply(Udirect_apply(lbl, args1, Debuginfo.from_call ev),
args2, Debuginfo.from_call ev)
| Ugeneric_apply(fn, args, dinfo) ->
Ugeneric_apply(fn, args, Debuginfo.from_call ev)
| Uprim(Praise, args, dinfo) ->
Uprim(Praise, args, Debuginfo.from_call ev)
| Uprim(p, args, dinfo) ->
Uprim(p, args, Debuginfo.from_call ev)
| Usend(kind, u1, u2, args, dinfo) ->
Usend(kind, u1, u2, args, Debuginfo.from_call ev)
| Usequence(u1, u2) ->
Usequence(u1, add_debug_info ev u2)
| _ -> u
end
| _ -> u
Uncurry an expression and explicitate closures .
Also return the approximation of the expression .
The approximation environment [ fenv ] maps idents to approximations .
Idents not bound in [ fenv ] approximate to [ Value_unknown ] .
The closure environment [ cenv ] maps idents to [ ulambda ] terms .
It is used to substitute environment accesses for free identifiers .
Also return the approximation of the expression.
The approximation environment [fenv] maps idents to approximations.
Idents not bound in [fenv] approximate to [Value_unknown].
The closure environment [cenv] maps idents to [ulambda] terms.
It is used to substitute environment accesses for free identifiers. *)
let close_approx_var fenv cenv id =
let approx = try Tbl.find id fenv with Not_found -> Value_unknown in
match approx with
Value_integer n ->
make_const_int n
| Value_constptr n ->
make_const_ptr n
| approx ->
let subst = try Tbl.find id cenv with Not_found -> Uvar id in
(subst, approx)
let close_var fenv cenv id =
let (ulam, app) = close_approx_var fenv cenv id in ulam
let rec close fenv cenv = function
Lvar id ->
close_approx_var fenv cenv id
| Lconst cst ->
begin match cst with
Const_base(Const_int n) -> (Uconst cst, Value_integer n)
| Const_base(Const_char c) -> (Uconst cst, Value_integer(Char.code c))
| Const_pointer n -> (Uconst cst, Value_constptr n)
| _ -> (Uconst cst, Value_unknown)
end
| Lfunction(kind, params, body) as funct ->
close_one_function fenv cenv (Ident.create "fun") funct
| Lapply(funct, args, loc) ->
let nargs = List.length args in
begin match (close fenv cenv funct, close_list fenv cenv args) with
((ufunct, Value_closure(fundesc, approx_res)),
[Uprim(Pmakeblock(_, _), uargs, _)])
when List.length uargs = - fundesc.fun_arity ->
let app = direct_apply fundesc funct ufunct uargs in
(app, strengthen_approx app approx_res)
| ((ufunct, Value_closure(fundesc, approx_res)), uargs)
when nargs = fundesc.fun_arity ->
let app = direct_apply fundesc funct ufunct uargs in
(app, strengthen_approx app approx_res)
| ((ufunct, Value_closure(fundesc, approx_res)), uargs)
when fundesc.fun_arity > 0 && nargs > fundesc.fun_arity ->
let (first_args, rem_args) = split_list fundesc.fun_arity uargs in
(Ugeneric_apply(direct_apply fundesc funct ufunct first_args,
rem_args, Debuginfo.none),
Value_unknown)
| ((ufunct, _), uargs) ->
(Ugeneric_apply(ufunct, uargs, Debuginfo.none), Value_unknown)
end
| Lsend(kind, met, obj, args) ->
let (umet, _) = close fenv cenv met in
let (uobj, _) = close fenv cenv obj in
(Usend(kind, umet, uobj, close_list fenv cenv args, Debuginfo.none),
Value_unknown)
| Llet(str, id, lam, body) ->
let (ulam, alam) = close_named fenv cenv id lam in
begin match (str, alam) with
(Variable, _) ->
let (ubody, abody) = close fenv cenv body in
(Ulet(id, ulam, ubody), abody)
| (_, (Value_integer _ | Value_constptr _))
when str = Alias || is_pure lam ->
close (Tbl.add id alam fenv) cenv body
| (_, _) ->
let (ubody, abody) = close (Tbl.add id alam fenv) cenv body in
(Ulet(id, ulam, ubody), abody)
end
| Lletrec(defs, body) ->
if List.for_all
(function (id, Lfunction(_, _, _)) -> true | _ -> false)
defs
then begin
let (clos, infos) = close_functions fenv cenv defs in
let clos_ident = Ident.create "clos" in
let fenv_body =
List.fold_right
(fun (id, pos, approx) fenv -> Tbl.add id approx fenv)
infos fenv in
let (ubody, approx) = close fenv_body cenv body in
let sb =
List.fold_right
(fun (id, pos, approx) sb ->
Tbl.add id (Uoffset(Uvar clos_ident, pos)) sb)
infos Tbl.empty in
(Ulet(clos_ident, clos, substitute sb ubody),
approx)
end else begin
let rec clos_defs = function
[] -> ([], fenv)
| (id, lam) :: rem ->
let (udefs, fenv_body) = clos_defs rem in
let (ulam, approx) = close fenv cenv lam in
((id, ulam) :: udefs, Tbl.add id approx fenv_body) in
let (udefs, fenv_body) = clos_defs defs in
let (ubody, approx) = close fenv_body cenv body in
(Uletrec(udefs, ubody), approx)
end
| Lprim(Pgetglobal id, []) as lam ->
check_constant_result lam
(getglobal id)
(Compilenv.global_approx id)
| Lprim(Pmakeblock(tag, mut) as prim, lams) ->
let (ulams, approxs) = List.split (List.map (close fenv cenv) lams) in
(Uprim(prim, ulams, Debuginfo.none),
begin match mut with
Immutable -> Value_tuple(Array.of_list approxs)
| Mutable -> Value_unknown
end)
| Lprim(Pfield n, [lam]) ->
let (ulam, approx) = close fenv cenv lam in
let fieldapprox =
match approx with
Value_tuple a when n < Array.length a -> a.(n)
| _ -> Value_unknown in
check_constant_result lam (Uprim(Pfield n, [ulam], Debuginfo.none)) fieldapprox
| Lprim(Psetfield(n, _), [Lprim(Pgetglobal id, []); lam]) ->
let (ulam, approx) = close fenv cenv lam in
(!global_approx).(n) <- approx;
(Uprim(Psetfield(n, false), [getglobal id; ulam], Debuginfo.none),
Value_unknown)
| Lprim(Praise, [Levent(arg, ev)]) ->
let (ulam, approx) = close fenv cenv arg in
(Uprim(Praise, [ulam], Debuginfo.from_raise ev),
Value_unknown)
| Lprim(p, args) ->
simplif_prim p (close_list_approx fenv cenv args) Debuginfo.none
| Lswitch(arg, sw) ->
NB : failaction might get copied , thus it should be some Lstaticraise
let (uarg, _) = close fenv cenv arg in
let const_index, const_actions =
close_switch fenv cenv sw.sw_consts sw.sw_numconsts sw.sw_failaction
and block_index, block_actions =
close_switch fenv cenv sw.sw_blocks sw.sw_numblocks sw.sw_failaction in
(Uswitch(uarg,
{us_index_consts = const_index;
us_actions_consts = const_actions;
us_index_blocks = block_index;
us_actions_blocks = block_actions}),
Value_unknown)
| Lstaticraise (i, args) ->
(Ustaticfail (i, close_list fenv cenv args), Value_unknown)
| Lstaticcatch(body, (i, vars), handler) ->
let (ubody, _) = close fenv cenv body in
let (uhandler, _) = close fenv cenv handler in
(Ucatch(i, vars, ubody, uhandler), Value_unknown)
| Ltrywith(body, id, handler) ->
let (ubody, _) = close fenv cenv body in
let (uhandler, _) = close fenv cenv handler in
(Utrywith(ubody, id, uhandler), Value_unknown)
| Lifthenelse(arg, ifso, ifnot) ->
begin match close fenv cenv arg with
(uarg, Value_constptr n) ->
sequence_constant_expr arg uarg
(close fenv cenv (if n = 0 then ifnot else ifso))
| (uarg, _ ) ->
let (uifso, _) = close fenv cenv ifso in
let (uifnot, _) = close fenv cenv ifnot in
(Uifthenelse(uarg, uifso, uifnot), Value_unknown)
end
| Lsequence(lam1, lam2) ->
let (ulam1, _) = close fenv cenv lam1 in
let (ulam2, approx) = close fenv cenv lam2 in
(Usequence(ulam1, ulam2), approx)
| Lwhile(cond, body) ->
let (ucond, _) = close fenv cenv cond in
let (ubody, _) = close fenv cenv body in
(Uwhile(ucond, ubody), Value_unknown)
| Lfor(id, lo, hi, dir, body) ->
let (ulo, _) = close fenv cenv lo in
let (uhi, _) = close fenv cenv hi in
let (ubody, _) = close fenv cenv body in
(Ufor(id, ulo, uhi, dir, ubody), Value_unknown)
| Lassign(id, lam) ->
let (ulam, _) = close fenv cenv lam in
(Uassign(id, ulam), Value_unknown)
| Levent(lam, ev) ->
let (ulam, approx) = close fenv cenv lam in
(add_debug_info ev ulam, approx)
| Lifused _ ->
assert false
and close_list fenv cenv = function
[] -> []
| lam :: rem ->
let (ulam, _) = close fenv cenv lam in
ulam :: close_list fenv cenv rem
and close_list_approx fenv cenv = function
[] -> ([], [])
| lam :: rem ->
let (ulam, approx) = close fenv cenv lam in
let (ulams, approxs) = close_list_approx fenv cenv rem in
(ulam :: ulams, approx :: approxs)
and close_named fenv cenv id = function
Lfunction(kind, params, body) as funct ->
close_one_function fenv cenv id funct
| lam ->
close fenv cenv lam
and close_functions fenv cenv fun_defs =
incr function_nesting_depth;
let initially_closed =
!function_nesting_depth < excessive_function_nesting_depth in
let fv =
IdentSet.elements (free_variables (Lletrec(fun_defs, lambda_unit))) in
let uncurried_defs =
List.map
(function
(id, Lfunction(kind, params, body)) ->
let label = Compilenv.make_symbol (Some (Ident.unique_name id)) in
let arity = List.length params in
let fundesc =
{fun_label = label;
fun_arity = (if kind = Tupled then -arity else arity);
fun_closed = initially_closed;
fun_inline = None } in
(id, params, body, fundesc)
| (_, _) -> fatal_error "Closure.close_functions")
fun_defs in
let fenv_rec =
List.fold_right
(fun (id, params, body, fundesc) fenv ->
Tbl.add id (Value_closure(fundesc, Value_unknown)) fenv)
uncurried_defs fenv in
let env_pos = ref (-1) in
let clos_offsets =
List.map
(fun (id, params, body, fundesc) ->
let pos = !env_pos + 1 in
env_pos := !env_pos + 1 + (if fundesc.fun_arity <> 1 then 3 else 2);
pos)
uncurried_defs in
let fv_pos = !env_pos in
let useless_env = ref initially_closed in
let clos_fundef (id, params, body, fundesc) env_pos =
let env_param = Ident.create "env" in
let cenv_fv =
build_closure_env env_param (fv_pos - env_pos) fv in
let cenv_body =
List.fold_right2
(fun (id, params, arity, body) pos env ->
Tbl.add id (Uoffset(Uvar env_param, pos - env_pos)) env)
uncurried_defs clos_offsets cenv_fv in
let (ubody, approx) = close fenv_rec cenv_body body in
if !useless_env && occurs_var env_param ubody then useless_env := false;
let fun_params = if !useless_env then params else params @ [env_param] in
((fundesc.fun_label, fundesc.fun_arity, fun_params, ubody),
(id, env_pos, Value_closure(fundesc, approx))) in
let clos_info_list =
if initially_closed then begin
let cl = List.map2 clos_fundef uncurried_defs clos_offsets in
if !useless_env then cl else begin
List.iter
(fun (id, params, body, fundesc) -> fundesc.fun_closed <- false)
uncurried_defs;
List.map2 clos_fundef uncurried_defs clos_offsets
end
end else
List.map2 clos_fundef uncurried_defs clos_offsets
in
decr function_nesting_depth;
Return the node and the list of all identifiers defined ,
with offsets and approximations .
with offsets and approximations. *)
let (clos, infos) = List.split clos_info_list in
(Uclosure(clos, List.map (close_var fenv cenv) fv), infos)
Same , for one non - recursive function
and close_one_function fenv cenv id funct =
match close_functions fenv cenv [id, funct] with
((Uclosure([_, _, params, body], _) as clos),
[_, _, (Value_closure(fundesc, _) as approx)]) ->
if lambda_smaller body (!Clflags.inline_threshold + List.length params)
then fundesc.fun_inline <- Some(params, body);
(clos, approx)
| _ -> fatal_error "Closure.close_one_function"
and close_switch fenv cenv cases num_keys default =
let index = Array.create num_keys 0
and store = mk_store Lambda.same in
First default case
begin match default with
| Some def when List.length cases < num_keys ->
ignore (store.act_store def)
| _ -> ()
end ;
List.iter
(fun (key,lam) ->
index.(key) <- store.act_store lam)
cases ;
let actions =
Array.map
(fun lam ->
let ulam,_ = close fenv cenv lam in
ulam)
(store.act_get ()) in
match actions with
May happen when default is None
| _ -> index, actions
let intro size lam =
function_nesting_depth := 0;
global_approx := Array.create size Value_unknown;
Compilenv.set_global_approx(Value_tuple !global_approx);
let (ulam, approx) = close Tbl.empty Tbl.empty lam in
global_approx := [||];
ulam
|
2af63c2ed76b5059623f72ef471982ee60fb9f302a797be6eb2a18af74422995 | tonymorris/fp-course | Loop.hs | module Network.Server.TicTacToe.Loop where
import Prelude hiding (mapM_, catch)
import System.IO(BufferMode(..))
import Network(PortID(..), sClose, withSocketsDo, listenOn)
import Data.IORef(IORef, newIORef, readIORef)
import Data.Foldable(Foldable, mapM_)
import Control.Applicative(Applicative, pure)
import Control.Monad.Trans(MonadIO(..), MonadTrans(..))
import Control.Monad(liftM)
import Control.Concurrent(forkIO)
import Control.Exception(finally, try, catch, Exception)
import Control.Monad(forever)
import Network.Server.Common.Accept
import Network.Server.Common.HandleLens
import Network.Server.Common.Lens
import Network.Server.Common.Line
import Network.Server.Common.Env
import Network.Server.Common.Ref
import Data.Set(Set)
import qualified Data.Set as S
data Loop v s f a =
Loop (Env v -> s -> f (a, s))
type IOLoop v s a =
Loop v s IO a
type IORefLoop v s a =
IOLoop (IORef v) s a
execLoop ::
Functor f =>
Loop v s f a
-> Env v
-> s
-> f a
execLoop (Loop l) e =
fmap fst . l e
initLoop ::
Functor f =>
(Env v -> f a)
-> Loop v s f a
initLoop f =
Loop $ \env s -> fmap (\a -> (a, s)) . f $ env
instance Functor f => Functor (Loop v s f) where
fmap f (Loop k) =
Loop (\env -> fmap (\(a, t) -> (f a, t)) . k env)
instance Applicative f => Applicative (Loop v s f) where
pure = undefined
(<*>) = undefined
instance Monad f => Monad (Loop v s f) where
return a =
Loop $ \_ s -> return (a, s)
Loop k >>= f =
Loop (\env s -> k env s >>= \(a, t) ->
let Loop l = f a
in l env t)
instance MonadTrans (Loop v s) where
lift x =
Loop (\_ s -> liftM (\a -> (a, s)) x)
instance MonadIO f => MonadIO (Loop v s f) where
liftIO =
lift . liftIO
etry ::
Exception e =>
(Env v -> IO a)
-> IOLoop v s (Either e a)
etry k =
initLoop $ try . k
server ::
IO w -- server initialise
-> (w -> IO v) -- client accepted (pre)
-> s -- initial state
-> IOLoop v s () -- per-client
-> IO a
server i r t l =
let hand s w c = forever $
do q <- accept' s
lSetBuffering q NoBuffering
_ <- atomicModifyIORef_ c (S.insert (refL `getL` q))
x <- r w
forkIO (execLoop l (Env q c x) t)
in withSocketsDo $ do
s <- listenOn (PortNumber 6060)
w <- i
c <- newIORef S.empty
hand s w c `finally` sClose s
perClient ::
IOLoop v s x -- client accepted (post)
-> (String -> IOLoop v s a) -- read line from client
-> IOLoop v s ()
perClient q f =
let lp = do k <- etry lGetLine
case k of Left e -> xprint e
Right [] -> lp
Right l -> f l >> lp
in do _ <- q
lp
loop ::
IO w -- server initialise
-> (w -> IO v) -- client accepted (pre)
-> s -- initial state
-> IOLoop v s x -- client accepted (post)
-> (String -> IOLoop v s w) -- read line from client
-> IO a
loop i r s q f =
server i r s (perClient q f)
iorefServer ::
v -- server initialise
-> s -- initial state
-> IORefLoop v s () -- per-client
-> IO a
iorefServer x s =
server (newIORef x) return s
iorefLoop ::
v -- server initialise
-> s -- initial state
-> IORefLoop v s x -- client accepted (post)
-> (String -> IORefLoop v s w) -- read line from client
-> IO a
iorefLoop x s q f =
iorefServer x s (perClient q f)
pPutStrLn ::
String
-> IOLoop v s ()
pPutStrLn s =
initLoop (`lPutStrLn` s)
(!) ::
Foldable t =>
IOLoop v s (t Ref)
-> String
-> IOLoop v s ()
clients ! msg =
clients >>= purgeClients (\y -> liftIO (lPutStrLn y msg))
infixl 2 !
purgeClients ::
Foldable t =>
(Ref -> IOLoop s v ())
-> t Ref
-> IOLoop s v ()
purgeClients a =
mapM_ (\y ->
ecatch (a y)
(\x -> do _ <- modifyClients (S.delete y)
xprint x)
)
readEnv ::
Applicative f =>
Loop v s f (Env v)
readEnv =
initLoop $ pure
readEnvval ::
Applicative f =>
Loop v s f v
readEnvval =
fmap (envvalL `getL`) readEnv
readIOEnvval ::
IORefLoop a s a
readIOEnvval =
initLoop $ \env ->
readIORef (envvalL `getL` env)
allClientsButThis ::
IOLoop v s (Set Ref)
allClientsButThis =
initLoop $ \env ->
fmap (S.delete ((acceptL .@ refL) `getL` env)) (readIORef (clientsL `getL` env))
Control . . CatchIO
ecatch ::
Exception e =>
IOLoop v s a
-> (e -> IOLoop v s a)
-> IOLoop v s a
ecatch (Loop k) f =
Loop $ \env s -> k env s `catch` (\e -> let Loop l = f e in l env s)
modifyClients ::
(Set Ref -> Set Ref)
-> IOLoop v s (Set Ref)
modifyClients f =
initLoop $ \env ->
atomicModifyIORef_ (clientsL `getL` env) f
| null | https://raw.githubusercontent.com/tonymorris/fp-course/73a64c3d4d0df58654a1a9a0ee9d9b11c3818911/projects/NetworkServer/haskell/src/Network/Server/TicTacToe/Loop.hs | haskell | server initialise
client accepted (pre)
initial state
per-client
client accepted (post)
read line from client
server initialise
client accepted (pre)
initial state
client accepted (post)
read line from client
server initialise
initial state
per-client
server initialise
initial state
client accepted (post)
read line from client | module Network.Server.TicTacToe.Loop where
import Prelude hiding (mapM_, catch)
import System.IO(BufferMode(..))
import Network(PortID(..), sClose, withSocketsDo, listenOn)
import Data.IORef(IORef, newIORef, readIORef)
import Data.Foldable(Foldable, mapM_)
import Control.Applicative(Applicative, pure)
import Control.Monad.Trans(MonadIO(..), MonadTrans(..))
import Control.Monad(liftM)
import Control.Concurrent(forkIO)
import Control.Exception(finally, try, catch, Exception)
import Control.Monad(forever)
import Network.Server.Common.Accept
import Network.Server.Common.HandleLens
import Network.Server.Common.Lens
import Network.Server.Common.Line
import Network.Server.Common.Env
import Network.Server.Common.Ref
import Data.Set(Set)
import qualified Data.Set as S
data Loop v s f a =
Loop (Env v -> s -> f (a, s))
type IOLoop v s a =
Loop v s IO a
type IORefLoop v s a =
IOLoop (IORef v) s a
execLoop ::
Functor f =>
Loop v s f a
-> Env v
-> s
-> f a
execLoop (Loop l) e =
fmap fst . l e
initLoop ::
Functor f =>
(Env v -> f a)
-> Loop v s f a
initLoop f =
Loop $ \env s -> fmap (\a -> (a, s)) . f $ env
instance Functor f => Functor (Loop v s f) where
fmap f (Loop k) =
Loop (\env -> fmap (\(a, t) -> (f a, t)) . k env)
instance Applicative f => Applicative (Loop v s f) where
pure = undefined
(<*>) = undefined
instance Monad f => Monad (Loop v s f) where
return a =
Loop $ \_ s -> return (a, s)
Loop k >>= f =
Loop (\env s -> k env s >>= \(a, t) ->
let Loop l = f a
in l env t)
instance MonadTrans (Loop v s) where
lift x =
Loop (\_ s -> liftM (\a -> (a, s)) x)
instance MonadIO f => MonadIO (Loop v s f) where
liftIO =
lift . liftIO
etry ::
Exception e =>
(Env v -> IO a)
-> IOLoop v s (Either e a)
etry k =
initLoop $ try . k
server ::
-> IO a
server i r t l =
let hand s w c = forever $
do q <- accept' s
lSetBuffering q NoBuffering
_ <- atomicModifyIORef_ c (S.insert (refL `getL` q))
x <- r w
forkIO (execLoop l (Env q c x) t)
in withSocketsDo $ do
s <- listenOn (PortNumber 6060)
w <- i
c <- newIORef S.empty
hand s w c `finally` sClose s
perClient ::
-> IOLoop v s ()
perClient q f =
let lp = do k <- etry lGetLine
case k of Left e -> xprint e
Right [] -> lp
Right l -> f l >> lp
in do _ <- q
lp
loop ::
-> IO a
loop i r s q f =
server i r s (perClient q f)
iorefServer ::
-> IO a
iorefServer x s =
server (newIORef x) return s
iorefLoop ::
-> IO a
iorefLoop x s q f =
iorefServer x s (perClient q f)
pPutStrLn ::
String
-> IOLoop v s ()
pPutStrLn s =
initLoop (`lPutStrLn` s)
(!) ::
Foldable t =>
IOLoop v s (t Ref)
-> String
-> IOLoop v s ()
clients ! msg =
clients >>= purgeClients (\y -> liftIO (lPutStrLn y msg))
infixl 2 !
purgeClients ::
Foldable t =>
(Ref -> IOLoop s v ())
-> t Ref
-> IOLoop s v ()
purgeClients a =
mapM_ (\y ->
ecatch (a y)
(\x -> do _ <- modifyClients (S.delete y)
xprint x)
)
readEnv ::
Applicative f =>
Loop v s f (Env v)
readEnv =
initLoop $ pure
readEnvval ::
Applicative f =>
Loop v s f v
readEnvval =
fmap (envvalL `getL`) readEnv
readIOEnvval ::
IORefLoop a s a
readIOEnvval =
initLoop $ \env ->
readIORef (envvalL `getL` env)
allClientsButThis ::
IOLoop v s (Set Ref)
allClientsButThis =
initLoop $ \env ->
fmap (S.delete ((acceptL .@ refL) `getL` env)) (readIORef (clientsL `getL` env))
Control . . CatchIO
ecatch ::
Exception e =>
IOLoop v s a
-> (e -> IOLoop v s a)
-> IOLoop v s a
ecatch (Loop k) f =
Loop $ \env s -> k env s `catch` (\e -> let Loop l = f e in l env s)
modifyClients ::
(Set Ref -> Set Ref)
-> IOLoop v s (Set Ref)
modifyClients f =
initLoop $ \env ->
atomicModifyIORef_ (clientsL `getL` env) f
|
bf65050f4feeaeb16fc1bcb34853e61ca68d63ad4bdc67b418714b820ecf1713 | nathell/skyscraper | cache.clj | ;;;; Skyscraper - Cache backends
(ns skyscraper.cache
(:refer-clojure :exclude [load load-string])
(:require [clojure.edn :as edn]
[clojure.java.io :as io])
(:import [java.io Closeable InputStream OutputStream]))
;;; Netstrings
(let [bytes-type (type (byte-array []))]
(defn- byte-array? [item]
(= (type item) bytes-type)))
(defn- write-netstring
[^OutputStream stream item]
(let [^bytes b (cond (byte-array? item) item
(string? item) (.getBytes item)
:otherwise (.getBytes (pr-str item)))]
(.write stream (.getBytes (str (count b))))
(.write stream (int \:))
(.write stream b)
(.write stream (int \,))))
(defn- read-netstring
[^InputStream stream]
(loop [len 0]
(let [ch (.read stream)]
(cond (<= 48 ch 57) (recur (+ (* 10 len) ch -48))
(= ch 58) (let [arr (byte-array len)]
(.read stream arr)
(assert (= (.read stream) 44))
arr)
:otherwise (throw (Exception. "colon needed after length"))))))
;;; Actual cache
(defprotocol CacheBackend
"Provides facilities for caching downloaded blobs (typically HTML),
potentially enriched with some metadata (typically headers), in
some kind of storage. Implementations of this protocol can be passed
as `:html-cache` and `:processed-cache` options to
[[skyscraper.core/scrape]]."
(save-blob [cache key blob metadata])
(load-blob [cache key]))
An implementation of CacheBackend that stores the blobs in a
;; filesystem under a specific directory (root-dir). The blobs are
;; stored as netstrings (),
prefixed with metadata EDN also stored as a netstring . The
;; filenames correspond to the stored keys. root-dir must end in a
;; path separator (/).
(deftype FSCache
[root-dir]
CacheBackend
(save-blob [cache key blob metadata]
(let [meta-str (pr-str metadata)
file (str root-dir key)]
(io/make-parents file)
(with-open [f (io/output-stream file)]
(write-netstring f metadata)
(write-netstring f blob))))
(load-blob [cache key]
(try
(with-open [f (io/input-stream (str root-dir key))]
(let [meta-blob (read-netstring f)
blob (read-netstring f)]
{:meta (edn/read-string (String. meta-blob))
:blob blob}))
(catch Exception _ nil)))
Closeable
(close [cache]
nil))
(defn fs
"Creates a filesystem-based cache backend with a given root directory."
[root-dir]
(FSCache. (str root-dir "/")))
A dummy implementation of CacheBackend that does n't actually cache data .
(deftype NullCache
[]
CacheBackend
(save-blob [_ _ _ _] nil)
(load-blob [_ _] nil)
Closeable
(close [_] nil))
(defn null
"Creates a null cache backend."
[]
(NullCache.))
(extend-protocol CacheBackend
nil
(save-blob [_ _ _ _] nil)
(load-blob [_ _] nil))
An in - memory implementation of CacheBackend backed by two atoms .
(deftype MemoryCache
[storage]
CacheBackend
(save-blob [cache key blob metadata]
(swap! storage assoc key {:blob blob, :meta metadata}))
(load-blob [cache key]
(@storage key))
Closeable
(close [cache]
nil))
(defn memory
"Creates a memory cache backend."
[]
(MemoryCache. (atom {})))
| null | https://raw.githubusercontent.com/nathell/skyscraper/4ed589fc7cb3f15cf5080aa45d1ed066dd108e7f/src/skyscraper/cache.clj | clojure | Skyscraper - Cache backends
Netstrings
Actual cache
filesystem under a specific directory (root-dir). The blobs are
stored as netstrings (),
filenames correspond to the stored keys. root-dir must end in a
path separator (/). |
(ns skyscraper.cache
(:refer-clojure :exclude [load load-string])
(:require [clojure.edn :as edn]
[clojure.java.io :as io])
(:import [java.io Closeable InputStream OutputStream]))
(let [bytes-type (type (byte-array []))]
(defn- byte-array? [item]
(= (type item) bytes-type)))
(defn- write-netstring
[^OutputStream stream item]
(let [^bytes b (cond (byte-array? item) item
(string? item) (.getBytes item)
:otherwise (.getBytes (pr-str item)))]
(.write stream (.getBytes (str (count b))))
(.write stream (int \:))
(.write stream b)
(.write stream (int \,))))
(defn- read-netstring
[^InputStream stream]
(loop [len 0]
(let [ch (.read stream)]
(cond (<= 48 ch 57) (recur (+ (* 10 len) ch -48))
(= ch 58) (let [arr (byte-array len)]
(.read stream arr)
(assert (= (.read stream) 44))
arr)
:otherwise (throw (Exception. "colon needed after length"))))))
(defprotocol CacheBackend
"Provides facilities for caching downloaded blobs (typically HTML),
potentially enriched with some metadata (typically headers), in
some kind of storage. Implementations of this protocol can be passed
as `:html-cache` and `:processed-cache` options to
[[skyscraper.core/scrape]]."
(save-blob [cache key blob metadata])
(load-blob [cache key]))
An implementation of CacheBackend that stores the blobs in a
prefixed with metadata EDN also stored as a netstring . The
(deftype FSCache
[root-dir]
CacheBackend
(save-blob [cache key blob metadata]
(let [meta-str (pr-str metadata)
file (str root-dir key)]
(io/make-parents file)
(with-open [f (io/output-stream file)]
(write-netstring f metadata)
(write-netstring f blob))))
(load-blob [cache key]
(try
(with-open [f (io/input-stream (str root-dir key))]
(let [meta-blob (read-netstring f)
blob (read-netstring f)]
{:meta (edn/read-string (String. meta-blob))
:blob blob}))
(catch Exception _ nil)))
Closeable
(close [cache]
nil))
(defn fs
"Creates a filesystem-based cache backend with a given root directory."
[root-dir]
(FSCache. (str root-dir "/")))
A dummy implementation of CacheBackend that does n't actually cache data .
(deftype NullCache
[]
CacheBackend
(save-blob [_ _ _ _] nil)
(load-blob [_ _] nil)
Closeable
(close [_] nil))
(defn null
"Creates a null cache backend."
[]
(NullCache.))
(extend-protocol CacheBackend
nil
(save-blob [_ _ _ _] nil)
(load-blob [_ _] nil))
An in - memory implementation of CacheBackend backed by two atoms .
(deftype MemoryCache
[storage]
CacheBackend
(save-blob [cache key blob metadata]
(swap! storage assoc key {:blob blob, :meta metadata}))
(load-blob [cache key]
(@storage key))
Closeable
(close [cache]
nil))
(defn memory
"Creates a memory cache backend."
[]
(MemoryCache. (atom {})))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.