_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
493299b722921f6b4acdca1a2a2eaaa8bf984e28802cb87580133ba4f35a7aa7
blindglobe/clocc
section17.lisp
section 17 : sequences -*- mode : lisp -*- (in-package :cl-user) (proclaim '(special log)) 17.2.1.1 (check-for-bug :section17-legacy-8 (remove "FOO" '(foo bar "FOO" "BAR" "foo" "bar") :test #'equal) (foo bar "BAR" "foo" "bar")) (check-for-bug :section17-legacy-12 (remove "FOO" '(foo bar "FOO" "BAR" "foo" "bar") :test #'equalp) (foo bar "BAR" "bar")) (check-for-bug :section17-legacy-16 (remove "FOO" '(foo bar "FOO" "BAR" "foo" "bar") :test #'string-equal) (bar "BAR" "bar")) (check-for-bug :section17-legacy-20 (remove "FOO" '(foo bar "FOO" "BAR" "foo" "bar") :test #'string=) (BAR "BAR" "foo" "bar")) (check-for-bug :section17-legacy-24 (remove 1 '(1 1.0 #C(1.0 0.0) 2 2.0 #C(2.0 0.0)) :test-not #'eql) (1)) (check-for-bug :section17-legacy-28 (remove 1 '(1 1.0 #C(1.0 0.0) 2 2.0 #C(2.0 0.0)) :test-not #'=) (1 1.0 #C(1.0 0.0))) (check-for-bug :section17-legacy-32 (remove 1 '(1 1.0 #C(1.0 0.0) 2 2.0 #C(2.0 0.0)) :test (complement #'=)) (1 1.0 #C(1.0 0.0))) (check-for-bug :section17-legacy-36 (count 1 '((one 1) (uno 1) (two 2) (dos 2)) :key #'cadr) 2) (check-for-bug :section17-legacy-40 (count 2.0 '(1 2 3) :test #'eql :key #'float) 1) (check-for-bug :section17-legacy-44 (count "FOO" (list (make-pathname :name "FOO" :type "X") (make-pathname :name "FOO" :type "Y")) :key #'pathname-name :test #'equal) 2) ;;; 17.2.2.1 (check-for-bug :section17-legacy-53 (count-if #'zerop '(1 #C(0.0 0.0) 0 0.0d0 0.0s0 3)) 4) (check-for-bug :section17-legacy-57 (remove-if-not #'symbolp '(0 1 2 3 4 5 6 7 8 9 A B C D E F)) (A B C D E F)) (check-for-bug :section17-legacy-61 (remove-if (complement #'symbolp) '(0 1 2 3 4 5 6 7 8 9 A B C D E F)) (A B C D E F)) (check-for-bug :section17-legacy-65 (count-if #'zerop '("foo" "" "bar" "" "" "baz" "quux") :key #'length) 3) ;;; copy-seq (check-for-bug :section17-legacy-71 (let ((str "a string")) str) "a string") (check-for-bug :section17-legacy-76 (let ((str "a string")) (equalp str (copy-seq str))) t) (check-for-bug :section17-legacy-81 (let ((str "a string")) (eql str (copy-seq str))) nil) ;;; elt (check-for-bug :section17-legacy-88 (let ((str "a string")) (setq str (copy-seq "0123456789"))) "0123456789") (check-for-bug :section17-legacy-93 (let ((str "a string")) (setq str (copy-seq "0123456789")) (elt str 6)) #\6) (check-for-bug :section17-legacy-99 (let ((str "a string")) (setq str (copy-seq "0123456789")) (setf (elt str 0) #\#)) #\#) (check-for-bug :section17-legacy-105 (let ((str "a string")) (setq str (copy-seq "0123456789")) (setf (elt str 0) #\#) str) "#123456789") ;;; fill (check-for-bug :section17-legacy-114 (fill (list 0 1 2 3 4 5) '(444)) ((444) (444) (444) (444) (444) (444))) (check-for-bug :section17-legacy-118 (fill (copy-seq "01234") #\e :start 3) "012ee") (check-for-bug :section17-legacy-122 (setq x (vector 'a 'b 'c 'd 'e)) #(A B C D E)) (check-for-bug :section17-legacy-126 (fill x 'z :start 1 :end 3) #(A Z Z D E)) (check-for-bug :section17-legacy-130 x #(A Z Z D E)) (check-for-bug :section17-legacy-134 (fill x 'p) #(P P P P P)) (check-for-bug :section17-legacy-138 x #(P P P P P)) ;;; make-sequence (check-for-bug :section17-legacy-144 (make-sequence 'list 0) ()) (check-for-bug :section17-legacy-148 (make-sequence 'string 26 :initial-element #\.) "..........................") (check-for-bug :section17-legacy-152 (make-sequence '(vector double-float) 2 :initial-element 1d0) #(1.0d0 1.0d0)) (check-for-bug :section17-legacy-157 (make-sequence '(vector * 2) 3) TYPE-ERROR) (check-for-bug :section17-legacy-161 (make-sequence '(vector * 4) 3) TYPE-ERROR) subseq (check-for-bug :section17-legacy-167 (let ((str (copy-seq "012345"))) str) "012345") (check-for-bug :section17-legacy-172 (let ((str (copy-seq "012345"))) (subseq str 2)) "2345") (check-for-bug :section17-legacy-177 (let ((str (copy-seq "012345"))) (subseq str 3 5)) "34") (check-for-bug :section17-legacy-182 (let ((str (copy-seq "012345"))) (setf (subseq str 4) "abc")) "abc") (check-for-bug :section17-legacy-187 (let ((str (copy-seq "012345"))) (setf (subseq str 4) "abc") str) "0123ab") (check-for-bug :section17-legacy-193 (let ((str (copy-seq "012345"))) (setf (subseq str 4) "abc") (setf (subseq str 0 2) "A")) "A") (check-for-bug :section17-legacy-199 (let ((str (copy-seq "012345"))) (setf (subseq str 4) "abc") (setf (subseq str 0 2) "A") str) "A123ab") ;;; map (check-for-bug :section17-legacy-208 (map 'string #'(lambda (x y) (char "01234567890ABCDEF" (mod (+ x y) 16))) '(1 2 3 4) '(10 9 8 7)) "AAAA") (check-for-bug :section17-legacy-215 (let ((seq (map 'list #'copy-seq '("lower" "UPPER" "" "123")))) seq) ("lower" "UPPER" "" "123")) (check-for-bug :section17-legacy-221 (let ((seq (map 'list #'copy-seq '("lower" "UPPER" "" "123")))) (map nil #'nstring-upcase seq)) NIL) (check-for-bug :section17-legacy-227 (let ((seq (map 'list #'copy-seq '("lower" "UPPER" "" "123")))) (map nil #'nstring-upcase seq) seq) ("LOWER" "UPPER" "" "123")) (check-for-bug :section17-legacy-234 (map 'list #'- '(1 2 3 4)) (-1 -2 -3 -4)) (check-for-bug :section17-legacy-238 (map 'string #'(lambda (x) (if (oddp x) #\1 #\0)) '(1 2 3 4)) "1010") (check-for-bug :section17-legacy-244 (map '(vector * 4) #'cons "abc" "de") TYPE-ERROR) ;;; map-into (check-for-bug :section17-legacy-250 (setq a (list 1 2 3 4) b (list 10 10 10 10)) (10 10 10 10)) (check-for-bug :section17-legacy-254 (map-into a #'+ a b) (11 12 13 14)) (check-for-bug :section17-legacy-258 a (11 12 13 14)) (check-for-bug :section17-legacy-262 b (10 10 10 10)) (check-for-bug :section17-legacy-266 (setq k '(one two three)) (ONE TWO THREE)) (check-for-bug :section17-legacy-270 (map-into a #'cons k a) ((ONE . 11) (TWO . 12) (THREE . 13) 14)) ;;; reduce (check-for-bug :section17-legacy-276 (reduce #'* '(1 2 3 4 5)) 120) (check-for-bug :section17-legacy-280 (reduce #'append '((1) (2)) :initial-value '(i n i t)) (I N I T 1 2)) (check-for-bug :section17-legacy-284 (reduce #'append '((1) (2)) :from-end t :initial-value '(i n i t)) (1 2 I N I T)) (check-for-bug :section17-legacy-289 (reduce #'- '(1 2 3 4)) -8) (check-for-bug :section17-legacy-293 (reduce #'- '(1 2 3 4) :from-end t) -2) (check-for-bug :section17-legacy-297 (reduce #'+ '()) 0) (check-for-bug :section17-legacy-301 (reduce #'+ '(3)) 3) (check-for-bug :section17-legacy-305 (reduce #'+ '(foo)) FOO) (check-for-bug :section17-legacy-309 (reduce #'list '(1 2 3 4)) (((1 2) 3) 4)) (check-for-bug :section17-legacy-313 (reduce #'list '(1 2 3 4) :from-end t) (1 (2 (3 4)))) (check-for-bug :section17-legacy-317 (reduce #'list '(1 2 3 4) :initial-value 'foo) ((((foo 1) 2) 3) 4)) (check-for-bug :section17-legacy-321 (reduce #'list '(1 2 3 4) :from-end t :initial-value 'foo) (1 (2 (3 (4 foo))))) ;;; count (check-for-bug :section17-legacy-328 (count #\a "how many A's are there in here?") 2) (check-for-bug :section17-legacy-332 (count-if-not #'oddp '((1) (2) (3) (4)) :key #'car) 2) (check-for-bug :section17-legacy-336 (count-if #'upper-case-p "The Crying of Lot 49" :start 4) 2) ;; length (check-for-bug :section17-legacy-342 (length "abc") 3) (check-for-bug :section17-legacy-346 (setq str (make-array '(3) :element-type 'character :initial-contents "abc" :fill-pointer t)) "abc") (check-for-bug :section17-legacy-352 (length str) 3) (check-for-bug :section17-legacy-356 (setf (fill-pointer str) 2) 2) (check-for-bug :section17-legacy-360 (length str) 2) ;;; reverse (check-for-bug :section17-legacy-366 (setq str "abc") "abc") (check-for-bug :section17-legacy-370 (reverse str) "cba") (check-for-bug :section17-legacy-374 str "abc") (check-for-bug :section17-legacy-378 (setq str (copy-seq str)) "abc") (check-for-bug :section17-legacy-382 (nreverse str) "cba") (check-for-bug :section17-legacy-386 str #+(or cmu sbcl clisp ecls) "cba" #-(or cmu sbcl clisp ecls) fill-this-in) (check-for-bug :section17-legacy-391 (let ((l (list 1 2 3))) l) (1 2 3)) (check-for-bug :section17-legacy-396 (let ((l (list 1 2 3))) (nreverse l)) (3 2 1)) (check-for-bug :section17-legacy-401 (let ((l (list 1 2 3))) (nreverse l) l) #+(or cmu sbcl ecls) (1) #+clisp (3 2 1) #-(or cmu sbcl clisp ecls) fill-this-in) ;;; sort (check-for-bug :section17-legacy-411 (setq tester (copy-seq "lkjashd")) "lkjashd") (check-for-bug :section17-legacy-415 (sort tester #'char-lessp) "adhjkls") (check-for-bug :section17-legacy-419 (setq tester (list '(1 2 3) '(4 5 6) '(7 8 9))) ((1 2 3) (4 5 6) (7 8 9))) (check-for-bug :section17-legacy-423 (sort tester #'> :key #'car) ((7 8 9) (4 5 6) (1 2 3))) (check-for-bug :section17-legacy-427 (setq tester (list 1 2 3 4 5 6 7 8 9 0)) (1 2 3 4 5 6 7 8 9 0)) (check-for-bug :section17-legacy-431 (stable-sort tester #'(lambda (x y) (and (oddp x) (evenp y)))) (1 3 5 7 9 2 4 6 8 0)) (check-for-bug :section17-legacy-435 (sort (setq committee-data (vector (list (list "JonL" "White") "Iteration") (list (list "Dick" "Waters") "Iteration") (list (list "Dick" "Gabriel") "Objects") (list (list "Kent" "Pitman") "Conditions") (list (list "Gregor" "Kiczales") "Objects") (list (list "David" "Moon") "Objects") (list (list "Kathy" "Chapman") "Editorial") (list (list "Larry" "Masinter") "Cleanup") (list (list "Sandra" "Loosemore") "Compiler"))) #'string-lessp :key #'cadar) #((("Kathy" "Chapman") "Editorial") (("Dick" "Gabriel") "Objects") (("Gregor" "Kiczales") "Objects") (("Sandra" "Loosemore") "Compiler") (("Larry" "Masinter") "Cleanup") (("David" "Moon") "Objects") (("Kent" "Pitman") "Conditions") (("Dick" "Waters") "Iteration") (("JonL" "White") "Iteration"))) ;; Note that individual alphabetical order within `committees' ;; is preserved. (check-for-bug :section17-legacy-460 (setq committee-data (stable-sort committee-data #'string-lessp :key #'cadr)) #((("Larry" "Masinter") "Cleanup") (("Sandra" "Loosemore") "Compiler") (("Kent" "Pitman") "Conditions") (("Kathy" "Chapman") "Editorial") (("Dick" "Waters") "Iteration") (("JonL" "White") "Iteration") (("Dick" "Gabriel") "Objects") (("Gregor" "Kiczales") "Objects") (("David" "Moon") "Objects"))) ;;; find (check-for-bug :section17-legacy-475 (find #\d "here are some letters that can be looked at" :test #'char>) #\Space) (check-for-bug :section17-legacy-479 (find-if #'oddp '(1 2 3 4 5) :end 3 :from-end t) 3) (check-for-bug :section17-legacy-483 (find-if-not #'complexp '#(3.5 2 #C(1.0 0.0) #C(0.0 1.0)) :start 2) NIL) ;;; position (check-for-bug :section17-legacy-492 (position #\a "baobab" :from-end t) 4) (check-for-bug :section17-legacy-496 (position-if #'oddp '((1) (2) (3) (4)) :start 1 :key #'car) 2) (check-for-bug :section17-legacy-500 (position 595 '()) NIL) (check-for-bug :section17-legacy-504 (position-if-not #'integerp '(1 2 3 4 5.0)) 4) ;;; search (check-for-bug :section17-legacy-510 (search "dog" "it's a dog's life") 7) (check-for-bug :section17-legacy-514 (search '(0 1) '(2 4 6 1 3 5) :key #'oddp) 2) ;;; mismatch (check-for-bug :section17-legacy-520 (mismatch "abcd" "ABCDE" :test #'char-equal) 4) (check-for-bug :section17-legacy-524 (mismatch '(3 2 1 1 2 3) '(1 2 3) :from-end t) 3) (check-for-bug :section17-legacy-528 (mismatch '(1 2 3) '(2 3 4) :test-not #'eq :key #'oddp) NIL) (check-for-bug :section17-legacy-532 (mismatch '(1 2 3 4 5 6) '(3 4 5 6 7) :start1 2 :end2 4) NIL) ;;; replace (check-for-bug :section17-legacy-538 (replace (copy-seq "abcdefghij") "0123456789" :start1 4 :end1 7 :start2 4) "abcd456hij") (check-for-bug :section17-legacy-543 (let ((lst (copy-seq "012345678"))) lst) "012345678") (check-for-bug :section17-legacy-548 (let ((lst (copy-seq "012345678"))) (replace lst lst :start1 2 :start2 0)) "010123456") (check-for-bug :section17-legacy-553 (let ((lst (copy-seq "012345678"))) (replace lst lst :start1 2 :start2 0) lst) "010123456") ;;; substitute (check-for-bug :section17-legacy-561 (substitute #\. #\SPACE "0 2 4 6") "0.2.4.6") (check-for-bug :section17-legacy-565 (substitute 9 4 '(1 2 4 1 3 4 5)) (1 2 9 1 3 9 5)) (check-for-bug :section17-legacy-569 (substitute 9 4 '(1 2 4 1 3 4 5) :count 1) (1 2 9 1 3 4 5)) (check-for-bug :section17-legacy-573 (substitute 9 4 '(1 2 4 1 3 4 5) :count 1 :from-end t) (1 2 4 1 3 9 5)) (check-for-bug :section17-legacy-577 (substitute 9 3 '(1 2 4 1 3 4 5) :test #'>) (9 9 4 9 3 4 5)) (check-for-bug :section17-legacy-581 (substitute-if 0 #'evenp '((1) (2) (3) (4)) :start 2 :key #'car) ((1) (2) (3) 0)) (check-for-bug :section17-legacy-585 (substitute-if 9 #'oddp '(1 2 4 1 3 4 5)) (9 2 4 9 9 4 9)) (check-for-bug :section17-legacy-589 (substitute-if 9 #'evenp '(1 2 4 1 3 4 5) :count 1 :from-end t) (1 2 4 1 3 9 5)) (check-for-bug :section17-legacy-593 (setq some-things (list 'a 'car 'b 'cdr 'c)) (A CAR B CDR C)) (check-for-bug :section17-legacy-597 (nsubstitute-if "function was here" #'fboundp some-things :count 1 :from-end t) (A CAR B "function was here" C)) (check-for-bug :section17-legacy-602 some-things (A CAR B "function was here" C)) (check-for-bug :section17-legacy-606 (setq alpha-tester (copy-seq "ab ")) "ab ") (check-for-bug :section17-legacy-610 (nsubstitute-if-not #\z #'alpha-char-p alpha-tester) "abz") (check-for-bug :section17-legacy-614 alpha-tester "abz") ;;; concatenate (check-for-bug :section17-legacy-620 (concatenate 'string "all" " " "together" " " "now") "all together now") (check-for-bug :section17-legacy-624 (concatenate 'list "ABC" '(d e f) #(1 2 3) #*1011) (#\A #\B #\C D E F 1 2 3 1 0 1 1)) (check-for-bug :section17-legacy-628 (concatenate 'list) NIL) (check-for-bug :section17-legacy-632 (concatenate '(vector * 2) "a" "bc") TYPE-ERROR) ;;; merge (check-for-bug :section17-legacy-638 (setq test1 (list 1 3 4 6 7)) (1 3 4 6 7)) (check-for-bug :section17-legacy-642 (setq test2 (list 2 5 8)) (2 5 8)) (check-for-bug :section17-legacy-646 (merge 'list test1 test2 #'<) (1 2 3 4 5 6 7 8)) (check-for-bug :section17-legacy-650 (setq test1 (copy-seq "BOY")) "BOY") (check-for-bug :section17-legacy-654 (setq test2 (copy-seq "nosy")) "nosy") (check-for-bug :section17-legacy-658 (merge 'string test1 test2 #'char-lessp) "BnOosYy") (check-for-bug :section17-legacy-662 (setq test1 (vector '(red . 1) '(blue . 4))) #((RED . 1) (BLUE . 4))) (check-for-bug :section17-legacy-666 (setq test2 (vector '(yellow . 2) '(green . 7))) #((YELLOW . 2) (GREEN . 7))) (check-for-bug :section17-legacy-670 (merge 'vector test1 test2 #'< :key #'cdr) #((RED . 1) (YELLOW . 2) (BLUE . 4) (GREEN . 7))) (check-for-bug :section17-legacy-674 (merge '(vector * 4) '(1 5) '(2 4 6) #'<) TYPE-ERROR) ;;; remove (check-for-bug :section17-legacy-681 (remove 4 '(1 3 4 5 9)) (1 3 5 9)) (check-for-bug :section17-legacy-685 (remove 4 '(1 2 4 1 3 4 5)) (1 2 1 3 5)) (check-for-bug :section17-legacy-689 (remove 4 '(1 2 4 1 3 4 5) :count 1) (1 2 1 3 4 5)) (check-for-bug :section17-legacy-693 (remove 4 '(1 2 4 1 3 4 5) :count 1 :from-end t) (1 2 4 1 3 5)) (check-for-bug :section17-legacy-697 (remove 3 '(1 2 4 1 3 4 5) :test #'>) (4 3 4 5)) (check-for-bug :section17-legacy-701 (setq lst '(list of four elements)) (LIST OF FOUR ELEMENTS)) (check-for-bug :section17-legacy-705 (setq lst2 (copy-seq lst)) (LIST OF FOUR ELEMENTS)) (check-for-bug :section17-legacy-709 (setq lst3 (delete 'four lst)) (LIST OF ELEMENTS)) (check-for-bug :section17-legacy-713 (equal lst lst2) nil) (check-for-bug :section17-legacy-717 (remove-if #'oddp '(1 2 4 1 3 4 5)) (2 4 4)) (check-for-bug :section17-legacy-721 (remove-if #'evenp '(1 2 4 1 3 4 5) :count 1 :from-end t) (1 2 4 1 3 5)) (check-for-bug :section17-legacy-725 (remove-if-not #'evenp '(1 2 3 4 5 6 7 8 9) :count 2 :from-end t) (1 2 3 4 5 6 8)) (check-for-bug :section17-legacy-729 (setq tester (list 1 2 4 1 3 4 5)) (1 2 4 1 3 4 5)) (check-for-bug :section17-legacy-733 (delete 4 tester) (1 2 1 3 5)) (check-for-bug :section17-legacy-737 (setq tester (list 1 2 4 1 3 4 5)) (1 2 4 1 3 4 5)) (check-for-bug :section17-legacy-741 (delete 4 tester :count 1) (1 2 1 3 4 5)) (check-for-bug :section17-legacy-745 (setq tester (list 1 2 4 1 3 4 5)) (1 2 4 1 3 4 5)) (check-for-bug :section17-legacy-749 (delete 4 tester :count 1 :from-end t) (1 2 4 1 3 5)) (check-for-bug :section17-legacy-753 (setq tester (list 1 2 4 1 3 4 5)) (1 2 4 1 3 4 5)) (check-for-bug :section17-legacy-757 (delete 3 tester :test #'>) (4 3 4 5)) (check-for-bug :section17-legacy-761 (setq tester (list 1 2 4 1 3 4 5)) (1 2 4 1 3 4 5)) (check-for-bug :section17-legacy-765 (delete-if #'oddp tester) (2 4 4)) (check-for-bug :section17-legacy-769 (setq tester (list 1 2 4 1 3 4 5)) (1 2 4 1 3 4 5)) (check-for-bug :section17-legacy-773 (delete-if #'evenp tester :count 1 :from-end t) (1 2 4 1 3 5)) (check-for-bug :section17-legacy-777 (setq tester (list 1 2 3 4 5 6)) (1 2 3 4 5 6)) (check-for-bug :section17-legacy-781 (delete-if #'evenp tester) (1 3 5)) (check-for-bug :section17-legacy-785 tester #+(or cmu sbcl clisp ecls) (1 3 5) #-(or cmu sbcl clisp ecls) fill-this-in) (check-for-bug :section17-legacy-790 (setq foo (list 'a 'b 'c)) (A B C)) (check-for-bug :section17-legacy-794 (setq bar (cdr foo)) (B C)) (check-for-bug :section17-legacy-798 (setq foo (delete 'b foo)) (A C)) (check-for-bug :section17-legacy-802 bar #+(or cmu sbcl clisp ecls) (B C) #-(or cmu sbcl clisp ecls) fill-this-in) ; ((C))) or ... (check-for-bug :section17-legacy-808 (eq (cdr foo) (car bar)) #+(or cmu sbcl clisp ecls) nil #-(or cmu sbcl clisp ecls) fill-this-in) ; T or ... ;;; remove-duplicates (check-for-bug :section17-legacy-817 (remove-duplicates "aBcDAbCd" :test #'char-equal :from-end t) "aBcD") (check-for-bug :section17-legacy-821 (remove-duplicates '(a b c b d d e)) (A C B D E)) (check-for-bug :section17-legacy-825 (remove-duplicates '(a b c b d d e) :from-end t) (A B C D E)) (check-for-bug :section17-legacy-829 (remove-duplicates '((foo #\a) (bar #\%) (baz #\A)) :test #'char-equal :key #'cadr) ((BAR #\%) (BAZ #\A))) (check-for-bug :section17-legacy-834 (remove-duplicates '((foo #\a) (bar #\%) (baz #\A)) :test #'char-equal :key #'cadr :from-end t) ((FOO #\a) (BAR #\%))) (check-for-bug :section17-legacy-839 (setq tester (list 0 1 2 3 4 5 6)) (0 1 2 3 4 5 6)) (check-for-bug :section17-legacy-843 (delete-duplicates tester :key #'oddp :start 1 :end 6) (0 4 5 6))
null
https://raw.githubusercontent.com/blindglobe/clocc/a50bb75edb01039b282cf320e4505122a59c59a7/src/tools/ansi-test/section17.lisp
lisp
17.2.2.1 copy-seq elt fill make-sequence map map-into reduce count length reverse sort Note that individual alphabetical order within `committees' is preserved. find position search mismatch replace substitute concatenate merge remove ((C))) or ... T or ... remove-duplicates
section 17 : sequences -*- mode : lisp -*- (in-package :cl-user) (proclaim '(special log)) 17.2.1.1 (check-for-bug :section17-legacy-8 (remove "FOO" '(foo bar "FOO" "BAR" "foo" "bar") :test #'equal) (foo bar "BAR" "foo" "bar")) (check-for-bug :section17-legacy-12 (remove "FOO" '(foo bar "FOO" "BAR" "foo" "bar") :test #'equalp) (foo bar "BAR" "bar")) (check-for-bug :section17-legacy-16 (remove "FOO" '(foo bar "FOO" "BAR" "foo" "bar") :test #'string-equal) (bar "BAR" "bar")) (check-for-bug :section17-legacy-20 (remove "FOO" '(foo bar "FOO" "BAR" "foo" "bar") :test #'string=) (BAR "BAR" "foo" "bar")) (check-for-bug :section17-legacy-24 (remove 1 '(1 1.0 #C(1.0 0.0) 2 2.0 #C(2.0 0.0)) :test-not #'eql) (1)) (check-for-bug :section17-legacy-28 (remove 1 '(1 1.0 #C(1.0 0.0) 2 2.0 #C(2.0 0.0)) :test-not #'=) (1 1.0 #C(1.0 0.0))) (check-for-bug :section17-legacy-32 (remove 1 '(1 1.0 #C(1.0 0.0) 2 2.0 #C(2.0 0.0)) :test (complement #'=)) (1 1.0 #C(1.0 0.0))) (check-for-bug :section17-legacy-36 (count 1 '((one 1) (uno 1) (two 2) (dos 2)) :key #'cadr) 2) (check-for-bug :section17-legacy-40 (count 2.0 '(1 2 3) :test #'eql :key #'float) 1) (check-for-bug :section17-legacy-44 (count "FOO" (list (make-pathname :name "FOO" :type "X") (make-pathname :name "FOO" :type "Y")) :key #'pathname-name :test #'equal) 2) (check-for-bug :section17-legacy-53 (count-if #'zerop '(1 #C(0.0 0.0) 0 0.0d0 0.0s0 3)) 4) (check-for-bug :section17-legacy-57 (remove-if-not #'symbolp '(0 1 2 3 4 5 6 7 8 9 A B C D E F)) (A B C D E F)) (check-for-bug :section17-legacy-61 (remove-if (complement #'symbolp) '(0 1 2 3 4 5 6 7 8 9 A B C D E F)) (A B C D E F)) (check-for-bug :section17-legacy-65 (count-if #'zerop '("foo" "" "bar" "" "" "baz" "quux") :key #'length) 3) (check-for-bug :section17-legacy-71 (let ((str "a string")) str) "a string") (check-for-bug :section17-legacy-76 (let ((str "a string")) (equalp str (copy-seq str))) t) (check-for-bug :section17-legacy-81 (let ((str "a string")) (eql str (copy-seq str))) nil) (check-for-bug :section17-legacy-88 (let ((str "a string")) (setq str (copy-seq "0123456789"))) "0123456789") (check-for-bug :section17-legacy-93 (let ((str "a string")) (setq str (copy-seq "0123456789")) (elt str 6)) #\6) (check-for-bug :section17-legacy-99 (let ((str "a string")) (setq str (copy-seq "0123456789")) (setf (elt str 0) #\#)) #\#) (check-for-bug :section17-legacy-105 (let ((str "a string")) (setq str (copy-seq "0123456789")) (setf (elt str 0) #\#) str) "#123456789") (check-for-bug :section17-legacy-114 (fill (list 0 1 2 3 4 5) '(444)) ((444) (444) (444) (444) (444) (444))) (check-for-bug :section17-legacy-118 (fill (copy-seq "01234") #\e :start 3) "012ee") (check-for-bug :section17-legacy-122 (setq x (vector 'a 'b 'c 'd 'e)) #(A B C D E)) (check-for-bug :section17-legacy-126 (fill x 'z :start 1 :end 3) #(A Z Z D E)) (check-for-bug :section17-legacy-130 x #(A Z Z D E)) (check-for-bug :section17-legacy-134 (fill x 'p) #(P P P P P)) (check-for-bug :section17-legacy-138 x #(P P P P P)) (check-for-bug :section17-legacy-144 (make-sequence 'list 0) ()) (check-for-bug :section17-legacy-148 (make-sequence 'string 26 :initial-element #\.) "..........................") (check-for-bug :section17-legacy-152 (make-sequence '(vector double-float) 2 :initial-element 1d0) #(1.0d0 1.0d0)) (check-for-bug :section17-legacy-157 (make-sequence '(vector * 2) 3) TYPE-ERROR) (check-for-bug :section17-legacy-161 (make-sequence '(vector * 4) 3) TYPE-ERROR) subseq (check-for-bug :section17-legacy-167 (let ((str (copy-seq "012345"))) str) "012345") (check-for-bug :section17-legacy-172 (let ((str (copy-seq "012345"))) (subseq str 2)) "2345") (check-for-bug :section17-legacy-177 (let ((str (copy-seq "012345"))) (subseq str 3 5)) "34") (check-for-bug :section17-legacy-182 (let ((str (copy-seq "012345"))) (setf (subseq str 4) "abc")) "abc") (check-for-bug :section17-legacy-187 (let ((str (copy-seq "012345"))) (setf (subseq str 4) "abc") str) "0123ab") (check-for-bug :section17-legacy-193 (let ((str (copy-seq "012345"))) (setf (subseq str 4) "abc") (setf (subseq str 0 2) "A")) "A") (check-for-bug :section17-legacy-199 (let ((str (copy-seq "012345"))) (setf (subseq str 4) "abc") (setf (subseq str 0 2) "A") str) "A123ab") (check-for-bug :section17-legacy-208 (map 'string #'(lambda (x y) (char "01234567890ABCDEF" (mod (+ x y) 16))) '(1 2 3 4) '(10 9 8 7)) "AAAA") (check-for-bug :section17-legacy-215 (let ((seq (map 'list #'copy-seq '("lower" "UPPER" "" "123")))) seq) ("lower" "UPPER" "" "123")) (check-for-bug :section17-legacy-221 (let ((seq (map 'list #'copy-seq '("lower" "UPPER" "" "123")))) (map nil #'nstring-upcase seq)) NIL) (check-for-bug :section17-legacy-227 (let ((seq (map 'list #'copy-seq '("lower" "UPPER" "" "123")))) (map nil #'nstring-upcase seq) seq) ("LOWER" "UPPER" "" "123")) (check-for-bug :section17-legacy-234 (map 'list #'- '(1 2 3 4)) (-1 -2 -3 -4)) (check-for-bug :section17-legacy-238 (map 'string #'(lambda (x) (if (oddp x) #\1 #\0)) '(1 2 3 4)) "1010") (check-for-bug :section17-legacy-244 (map '(vector * 4) #'cons "abc" "de") TYPE-ERROR) (check-for-bug :section17-legacy-250 (setq a (list 1 2 3 4) b (list 10 10 10 10)) (10 10 10 10)) (check-for-bug :section17-legacy-254 (map-into a #'+ a b) (11 12 13 14)) (check-for-bug :section17-legacy-258 a (11 12 13 14)) (check-for-bug :section17-legacy-262 b (10 10 10 10)) (check-for-bug :section17-legacy-266 (setq k '(one two three)) (ONE TWO THREE)) (check-for-bug :section17-legacy-270 (map-into a #'cons k a) ((ONE . 11) (TWO . 12) (THREE . 13) 14)) (check-for-bug :section17-legacy-276 (reduce #'* '(1 2 3 4 5)) 120) (check-for-bug :section17-legacy-280 (reduce #'append '((1) (2)) :initial-value '(i n i t)) (I N I T 1 2)) (check-for-bug :section17-legacy-284 (reduce #'append '((1) (2)) :from-end t :initial-value '(i n i t)) (1 2 I N I T)) (check-for-bug :section17-legacy-289 (reduce #'- '(1 2 3 4)) -8) (check-for-bug :section17-legacy-293 (reduce #'- '(1 2 3 4) :from-end t) -2) (check-for-bug :section17-legacy-297 (reduce #'+ '()) 0) (check-for-bug :section17-legacy-301 (reduce #'+ '(3)) 3) (check-for-bug :section17-legacy-305 (reduce #'+ '(foo)) FOO) (check-for-bug :section17-legacy-309 (reduce #'list '(1 2 3 4)) (((1 2) 3) 4)) (check-for-bug :section17-legacy-313 (reduce #'list '(1 2 3 4) :from-end t) (1 (2 (3 4)))) (check-for-bug :section17-legacy-317 (reduce #'list '(1 2 3 4) :initial-value 'foo) ((((foo 1) 2) 3) 4)) (check-for-bug :section17-legacy-321 (reduce #'list '(1 2 3 4) :from-end t :initial-value 'foo) (1 (2 (3 (4 foo))))) (check-for-bug :section17-legacy-328 (count #\a "how many A's are there in here?") 2) (check-for-bug :section17-legacy-332 (count-if-not #'oddp '((1) (2) (3) (4)) :key #'car) 2) (check-for-bug :section17-legacy-336 (count-if #'upper-case-p "The Crying of Lot 49" :start 4) 2) (check-for-bug :section17-legacy-342 (length "abc") 3) (check-for-bug :section17-legacy-346 (setq str (make-array '(3) :element-type 'character :initial-contents "abc" :fill-pointer t)) "abc") (check-for-bug :section17-legacy-352 (length str) 3) (check-for-bug :section17-legacy-356 (setf (fill-pointer str) 2) 2) (check-for-bug :section17-legacy-360 (length str) 2) (check-for-bug :section17-legacy-366 (setq str "abc") "abc") (check-for-bug :section17-legacy-370 (reverse str) "cba") (check-for-bug :section17-legacy-374 str "abc") (check-for-bug :section17-legacy-378 (setq str (copy-seq str)) "abc") (check-for-bug :section17-legacy-382 (nreverse str) "cba") (check-for-bug :section17-legacy-386 str #+(or cmu sbcl clisp ecls) "cba" #-(or cmu sbcl clisp ecls) fill-this-in) (check-for-bug :section17-legacy-391 (let ((l (list 1 2 3))) l) (1 2 3)) (check-for-bug :section17-legacy-396 (let ((l (list 1 2 3))) (nreverse l)) (3 2 1)) (check-for-bug :section17-legacy-401 (let ((l (list 1 2 3))) (nreverse l) l) #+(or cmu sbcl ecls) (1) #+clisp (3 2 1) #-(or cmu sbcl clisp ecls) fill-this-in) (check-for-bug :section17-legacy-411 (setq tester (copy-seq "lkjashd")) "lkjashd") (check-for-bug :section17-legacy-415 (sort tester #'char-lessp) "adhjkls") (check-for-bug :section17-legacy-419 (setq tester (list '(1 2 3) '(4 5 6) '(7 8 9))) ((1 2 3) (4 5 6) (7 8 9))) (check-for-bug :section17-legacy-423 (sort tester #'> :key #'car) ((7 8 9) (4 5 6) (1 2 3))) (check-for-bug :section17-legacy-427 (setq tester (list 1 2 3 4 5 6 7 8 9 0)) (1 2 3 4 5 6 7 8 9 0)) (check-for-bug :section17-legacy-431 (stable-sort tester #'(lambda (x y) (and (oddp x) (evenp y)))) (1 3 5 7 9 2 4 6 8 0)) (check-for-bug :section17-legacy-435 (sort (setq committee-data (vector (list (list "JonL" "White") "Iteration") (list (list "Dick" "Waters") "Iteration") (list (list "Dick" "Gabriel") "Objects") (list (list "Kent" "Pitman") "Conditions") (list (list "Gregor" "Kiczales") "Objects") (list (list "David" "Moon") "Objects") (list (list "Kathy" "Chapman") "Editorial") (list (list "Larry" "Masinter") "Cleanup") (list (list "Sandra" "Loosemore") "Compiler"))) #'string-lessp :key #'cadar) #((("Kathy" "Chapman") "Editorial") (("Dick" "Gabriel") "Objects") (("Gregor" "Kiczales") "Objects") (("Sandra" "Loosemore") "Compiler") (("Larry" "Masinter") "Cleanup") (("David" "Moon") "Objects") (("Kent" "Pitman") "Conditions") (("Dick" "Waters") "Iteration") (("JonL" "White") "Iteration"))) (check-for-bug :section17-legacy-460 (setq committee-data (stable-sort committee-data #'string-lessp :key #'cadr)) #((("Larry" "Masinter") "Cleanup") (("Sandra" "Loosemore") "Compiler") (("Kent" "Pitman") "Conditions") (("Kathy" "Chapman") "Editorial") (("Dick" "Waters") "Iteration") (("JonL" "White") "Iteration") (("Dick" "Gabriel") "Objects") (("Gregor" "Kiczales") "Objects") (("David" "Moon") "Objects"))) (check-for-bug :section17-legacy-475 (find #\d "here are some letters that can be looked at" :test #'char>) #\Space) (check-for-bug :section17-legacy-479 (find-if #'oddp '(1 2 3 4 5) :end 3 :from-end t) 3) (check-for-bug :section17-legacy-483 (find-if-not #'complexp '#(3.5 2 #C(1.0 0.0) #C(0.0 1.0)) :start 2) NIL) (check-for-bug :section17-legacy-492 (position #\a "baobab" :from-end t) 4) (check-for-bug :section17-legacy-496 (position-if #'oddp '((1) (2) (3) (4)) :start 1 :key #'car) 2) (check-for-bug :section17-legacy-500 (position 595 '()) NIL) (check-for-bug :section17-legacy-504 (position-if-not #'integerp '(1 2 3 4 5.0)) 4) (check-for-bug :section17-legacy-510 (search "dog" "it's a dog's life") 7) (check-for-bug :section17-legacy-514 (search '(0 1) '(2 4 6 1 3 5) :key #'oddp) 2) (check-for-bug :section17-legacy-520 (mismatch "abcd" "ABCDE" :test #'char-equal) 4) (check-for-bug :section17-legacy-524 (mismatch '(3 2 1 1 2 3) '(1 2 3) :from-end t) 3) (check-for-bug :section17-legacy-528 (mismatch '(1 2 3) '(2 3 4) :test-not #'eq :key #'oddp) NIL) (check-for-bug :section17-legacy-532 (mismatch '(1 2 3 4 5 6) '(3 4 5 6 7) :start1 2 :end2 4) NIL) (check-for-bug :section17-legacy-538 (replace (copy-seq "abcdefghij") "0123456789" :start1 4 :end1 7 :start2 4) "abcd456hij") (check-for-bug :section17-legacy-543 (let ((lst (copy-seq "012345678"))) lst) "012345678") (check-for-bug :section17-legacy-548 (let ((lst (copy-seq "012345678"))) (replace lst lst :start1 2 :start2 0)) "010123456") (check-for-bug :section17-legacy-553 (let ((lst (copy-seq "012345678"))) (replace lst lst :start1 2 :start2 0) lst) "010123456") (check-for-bug :section17-legacy-561 (substitute #\. #\SPACE "0 2 4 6") "0.2.4.6") (check-for-bug :section17-legacy-565 (substitute 9 4 '(1 2 4 1 3 4 5)) (1 2 9 1 3 9 5)) (check-for-bug :section17-legacy-569 (substitute 9 4 '(1 2 4 1 3 4 5) :count 1) (1 2 9 1 3 4 5)) (check-for-bug :section17-legacy-573 (substitute 9 4 '(1 2 4 1 3 4 5) :count 1 :from-end t) (1 2 4 1 3 9 5)) (check-for-bug :section17-legacy-577 (substitute 9 3 '(1 2 4 1 3 4 5) :test #'>) (9 9 4 9 3 4 5)) (check-for-bug :section17-legacy-581 (substitute-if 0 #'evenp '((1) (2) (3) (4)) :start 2 :key #'car) ((1) (2) (3) 0)) (check-for-bug :section17-legacy-585 (substitute-if 9 #'oddp '(1 2 4 1 3 4 5)) (9 2 4 9 9 4 9)) (check-for-bug :section17-legacy-589 (substitute-if 9 #'evenp '(1 2 4 1 3 4 5) :count 1 :from-end t) (1 2 4 1 3 9 5)) (check-for-bug :section17-legacy-593 (setq some-things (list 'a 'car 'b 'cdr 'c)) (A CAR B CDR C)) (check-for-bug :section17-legacy-597 (nsubstitute-if "function was here" #'fboundp some-things :count 1 :from-end t) (A CAR B "function was here" C)) (check-for-bug :section17-legacy-602 some-things (A CAR B "function was here" C)) (check-for-bug :section17-legacy-606 (setq alpha-tester (copy-seq "ab ")) "ab ") (check-for-bug :section17-legacy-610 (nsubstitute-if-not #\z #'alpha-char-p alpha-tester) "abz") (check-for-bug :section17-legacy-614 alpha-tester "abz") (check-for-bug :section17-legacy-620 (concatenate 'string "all" " " "together" " " "now") "all together now") (check-for-bug :section17-legacy-624 (concatenate 'list "ABC" '(d e f) #(1 2 3) #*1011) (#\A #\B #\C D E F 1 2 3 1 0 1 1)) (check-for-bug :section17-legacy-628 (concatenate 'list) NIL) (check-for-bug :section17-legacy-632 (concatenate '(vector * 2) "a" "bc") TYPE-ERROR) (check-for-bug :section17-legacy-638 (setq test1 (list 1 3 4 6 7)) (1 3 4 6 7)) (check-for-bug :section17-legacy-642 (setq test2 (list 2 5 8)) (2 5 8)) (check-for-bug :section17-legacy-646 (merge 'list test1 test2 #'<) (1 2 3 4 5 6 7 8)) (check-for-bug :section17-legacy-650 (setq test1 (copy-seq "BOY")) "BOY") (check-for-bug :section17-legacy-654 (setq test2 (copy-seq "nosy")) "nosy") (check-for-bug :section17-legacy-658 (merge 'string test1 test2 #'char-lessp) "BnOosYy") (check-for-bug :section17-legacy-662 (setq test1 (vector '(red . 1) '(blue . 4))) #((RED . 1) (BLUE . 4))) (check-for-bug :section17-legacy-666 (setq test2 (vector '(yellow . 2) '(green . 7))) #((YELLOW . 2) (GREEN . 7))) (check-for-bug :section17-legacy-670 (merge 'vector test1 test2 #'< :key #'cdr) #((RED . 1) (YELLOW . 2) (BLUE . 4) (GREEN . 7))) (check-for-bug :section17-legacy-674 (merge '(vector * 4) '(1 5) '(2 4 6) #'<) TYPE-ERROR) (check-for-bug :section17-legacy-681 (remove 4 '(1 3 4 5 9)) (1 3 5 9)) (check-for-bug :section17-legacy-685 (remove 4 '(1 2 4 1 3 4 5)) (1 2 1 3 5)) (check-for-bug :section17-legacy-689 (remove 4 '(1 2 4 1 3 4 5) :count 1) (1 2 1 3 4 5)) (check-for-bug :section17-legacy-693 (remove 4 '(1 2 4 1 3 4 5) :count 1 :from-end t) (1 2 4 1 3 5)) (check-for-bug :section17-legacy-697 (remove 3 '(1 2 4 1 3 4 5) :test #'>) (4 3 4 5)) (check-for-bug :section17-legacy-701 (setq lst '(list of four elements)) (LIST OF FOUR ELEMENTS)) (check-for-bug :section17-legacy-705 (setq lst2 (copy-seq lst)) (LIST OF FOUR ELEMENTS)) (check-for-bug :section17-legacy-709 (setq lst3 (delete 'four lst)) (LIST OF ELEMENTS)) (check-for-bug :section17-legacy-713 (equal lst lst2) nil) (check-for-bug :section17-legacy-717 (remove-if #'oddp '(1 2 4 1 3 4 5)) (2 4 4)) (check-for-bug :section17-legacy-721 (remove-if #'evenp '(1 2 4 1 3 4 5) :count 1 :from-end t) (1 2 4 1 3 5)) (check-for-bug :section17-legacy-725 (remove-if-not #'evenp '(1 2 3 4 5 6 7 8 9) :count 2 :from-end t) (1 2 3 4 5 6 8)) (check-for-bug :section17-legacy-729 (setq tester (list 1 2 4 1 3 4 5)) (1 2 4 1 3 4 5)) (check-for-bug :section17-legacy-733 (delete 4 tester) (1 2 1 3 5)) (check-for-bug :section17-legacy-737 (setq tester (list 1 2 4 1 3 4 5)) (1 2 4 1 3 4 5)) (check-for-bug :section17-legacy-741 (delete 4 tester :count 1) (1 2 1 3 4 5)) (check-for-bug :section17-legacy-745 (setq tester (list 1 2 4 1 3 4 5)) (1 2 4 1 3 4 5)) (check-for-bug :section17-legacy-749 (delete 4 tester :count 1 :from-end t) (1 2 4 1 3 5)) (check-for-bug :section17-legacy-753 (setq tester (list 1 2 4 1 3 4 5)) (1 2 4 1 3 4 5)) (check-for-bug :section17-legacy-757 (delete 3 tester :test #'>) (4 3 4 5)) (check-for-bug :section17-legacy-761 (setq tester (list 1 2 4 1 3 4 5)) (1 2 4 1 3 4 5)) (check-for-bug :section17-legacy-765 (delete-if #'oddp tester) (2 4 4)) (check-for-bug :section17-legacy-769 (setq tester (list 1 2 4 1 3 4 5)) (1 2 4 1 3 4 5)) (check-for-bug :section17-legacy-773 (delete-if #'evenp tester :count 1 :from-end t) (1 2 4 1 3 5)) (check-for-bug :section17-legacy-777 (setq tester (list 1 2 3 4 5 6)) (1 2 3 4 5 6)) (check-for-bug :section17-legacy-781 (delete-if #'evenp tester) (1 3 5)) (check-for-bug :section17-legacy-785 tester #+(or cmu sbcl clisp ecls) (1 3 5) #-(or cmu sbcl clisp ecls) fill-this-in) (check-for-bug :section17-legacy-790 (setq foo (list 'a 'b 'c)) (A B C)) (check-for-bug :section17-legacy-794 (setq bar (cdr foo)) (B C)) (check-for-bug :section17-legacy-798 (setq foo (delete 'b foo)) (A C)) (check-for-bug :section17-legacy-802 bar #+(or cmu sbcl clisp ecls) (B C) #-(or cmu sbcl clisp ecls) fill-this-in) (check-for-bug :section17-legacy-808 (eq (cdr foo) (car bar)) #+(or cmu sbcl clisp ecls) nil #-(or cmu sbcl clisp ecls) fill-this-in) (check-for-bug :section17-legacy-817 (remove-duplicates "aBcDAbCd" :test #'char-equal :from-end t) "aBcD") (check-for-bug :section17-legacy-821 (remove-duplicates '(a b c b d d e)) (A C B D E)) (check-for-bug :section17-legacy-825 (remove-duplicates '(a b c b d d e) :from-end t) (A B C D E)) (check-for-bug :section17-legacy-829 (remove-duplicates '((foo #\a) (bar #\%) (baz #\A)) :test #'char-equal :key #'cadr) ((BAR #\%) (BAZ #\A))) (check-for-bug :section17-legacy-834 (remove-duplicates '((foo #\a) (bar #\%) (baz #\A)) :test #'char-equal :key #'cadr :from-end t) ((FOO #\a) (BAR #\%))) (check-for-bug :section17-legacy-839 (setq tester (list 0 1 2 3 4 5 6)) (0 1 2 3 4 5 6)) (check-for-bug :section17-legacy-843 (delete-duplicates tester :key #'oddp :start 1 :end 6) (0 4 5 6))
beae0b045fd73a1d25dddb149fa07bc0b4170b4ff92607b464d5ace27533138e
exoscale/coax
inspect.cljc
(ns exoscale.coax.inspect (:require [clojure.spec.alpha :as s])) (defn- accept-keyword [x] (when (qualified-keyword? x) x)) (defn- accept-symbol [x] (when (qualified-symbol? x) x)) (defn- accept-set [x] (when (set? x) x)) (defn- accept-symbol-call [spec] (when (and (seq? spec) (symbol? (first spec))) spec)) (defn spec-form "Return the spec form or nil." [spec] (some-> spec s/get-spec s/form)) (defn spec-root "Determine the main spec root from a spec form." [spec] (let [spec-def (or (spec-form spec) (accept-symbol spec) (accept-symbol-call spec) (accept-set spec))] (cond-> spec-def (qualified-keyword? spec-def) recur))) (defn parent-spec "Look up for the parent coercer using the spec hierarchy." [k] (or (accept-keyword (s/get-spec k)) (accept-keyword (spec-form k)))) (s/fdef registry-lookup :args (s/cat :registry map? :k qualified-keyword?) :ret any?) (defn registry-lookup "Look for the key in registry, if not found try key spec parent recursively." [registry k] (if-let [c (get registry k)] c (when-let [parent (-> (parent-spec k) accept-keyword)] (recur registry parent))))
null
https://raw.githubusercontent.com/exoscale/coax/c2c127f58bbdac4e035fefea8768d8b4723a3fd4/src/exoscale/coax/inspect.cljc
clojure
(ns exoscale.coax.inspect (:require [clojure.spec.alpha :as s])) (defn- accept-keyword [x] (when (qualified-keyword? x) x)) (defn- accept-symbol [x] (when (qualified-symbol? x) x)) (defn- accept-set [x] (when (set? x) x)) (defn- accept-symbol-call [spec] (when (and (seq? spec) (symbol? (first spec))) spec)) (defn spec-form "Return the spec form or nil." [spec] (some-> spec s/get-spec s/form)) (defn spec-root "Determine the main spec root from a spec form." [spec] (let [spec-def (or (spec-form spec) (accept-symbol spec) (accept-symbol-call spec) (accept-set spec))] (cond-> spec-def (qualified-keyword? spec-def) recur))) (defn parent-spec "Look up for the parent coercer using the spec hierarchy." [k] (or (accept-keyword (s/get-spec k)) (accept-keyword (spec-form k)))) (s/fdef registry-lookup :args (s/cat :registry map? :k qualified-keyword?) :ret any?) (defn registry-lookup "Look for the key in registry, if not found try key spec parent recursively." [registry k] (if-let [c (get registry k)] c (when-let [parent (-> (parent-spec k) accept-keyword)] (recur registry parent))))
5eb9618ebd94cf3f1219179b3419040f0f5c240454e6ede7d020cb6ff7ffd760
stevejenkins/UBNT-EdgeRouter-Example-Configs
config.boot.erl
/* EdgeRouter Lite + Comcast IPv4/IPv6 Dual Stack Config - -EdgeRouter-Example-Configs */ firewall { all-ping enable broadcast-ping disable ipv6-name WANv6_IN { default-action drop description "WANv6 inbound traffic forwarded to LAN" rule 10 { action accept description "Allow established/related" state { established enable related enable } } rule 20 { action drop description "Drop invalid state" state { invalid enable } } rule 30 { action accept description "Allow ICMPv6" log disable protocol icmpv6 } } ipv6-name WANv6_LOCAL { default-action drop description "WANv6 inbound traffic to the router" rule 10 { action accept description "Allow established/related" state { established enable related enable } } rule 20 { action drop description "Drop invalid state" state { invalid enable } } rule 30 { action accept description "Allow ICMPv6" log disable protocol icmpv6 } rule 40 { action accept description "Allow DHCPv6" destination { port 546 } protocol udp source { port 547 } } } ipv6-name WANv6_OUT { default-action accept description "WANv6 outbound traffic" rule 10 { action accept description "Allow established/related" state { established enable related enable } } rule 20 { action reject description "Reject invalid state" state { invalid enable } } } ipv6-receive-redirects disable ipv6-src-route disable ip-src-route disable log-martians enable name LAN_IN { default-action accept description "LAN to Internal" rule 10 { action drop description "Drop invalid state" state { invalid enable } } } name WAN_IN { default-action drop description "WAN to internal" rule 10 { action accept description "Allow established/related" log disable state { established enable invalid disable new disable related enable } } rule 20 { action accept description "Allow ICMP" log disable protocol icmp state { established enable related enable } } rule 100 { action drop description "Drop invalid state" protocol all state { established disable invalid enable new disable related disable } } } name WAN_LOCAL { default-action drop description "WAN to router" rule 10 { action accept description "Allow established/related" state { established enable related enable } } rule 20 { action accept description "Port Forward - Router SSH" destination { address 192.168.1.1 port 22 } protocol tcp } rule 30 { action accept description "Port Forward - Router HTTPS" destination { address 192.168.1.1 port 443 } protocol tcp } rule 100 { action drop description "Drop invalid state" protocol all state { established disable invalid enable new disable related disable } } } name WAN_OUT { default-action accept description "Internal to WAN" rule 10 { action accept description "Allow established/related" log disable state { established enable related enable } } rule 20 { action reject description "Reject invalid state" state { invalid enable } } } options { mss-clamp { interface-type all mss 1412 } } receive-redirects disable send-redirects enable source-validation disable syn-cookies enable } interfaces { ethernet eth0 { address dhcp description WAN dhcpv6-pd { pd 0 { interface eth1 { host-address ::1 prefix-id :0 service slaac } interface eth1.102 { host-address ::1 prefix-id :1 service slaac } interface eth2 { host-address ::1 prefix-id :2 service slaac } prefix-length /60 } rapid-commit enable } duplex auto firewall { in { ipv6-name WANv6_IN name WAN_IN } local { ipv6-name WANv6_LOCAL name WAN_LOCAL } out { ipv6-name WANv6_OUT name WAN_OUT } } speed auto } ethernet eth1 { address 192.168.99.1/24 description "Local Config" duplex auto firewall { in { name LAN_IN } } speed auto } loopback lo { } ethernet eth2 { address 192.168.1.1/24 description LAN duplex auto firewall { in { name LAN_IN } } mtu 1500 speed auto vif 102 { address 172.16.0.1/24 description "Guest Network VLAN" mtu 1500 } } } port-forward { auto-firewall enable hairpin-nat enable lan-interface eth2 rule 10 { description "Router SSH" forward-to { address 192.168.1.1 port 22 } original-port 2222 protocol tcp_udp } rule 20 { description "Router HTTPS" forward-to { address 192.168.1.1 port 443 } original-port 8080 protocol tcp_udp } wan-interface eth0 } service { dhcp-server { disabled false hostfile-update enable shared-network-name Guest { authoritative disable subnet 172.16.0.0/24 { default-router 172.16.0.1 dns-server 8.8.8.8 dns-server 8.8.4.4 domain-name guest.example.com lease 86400 start 172.16.0.10 { stop 172.16.0.254 } } } shared-network-name LAN { authoritative disable subnet 192.168.1.0/24 { default-router 192.168.1.1 dns-server 192.168.1.1 dns-server 8.8.8.8 dns-server 8.8.4.4 domain-name example.com lease 86400 start 192.168.1.101 { stop 192.168.1.254 } } } shared-network-name Config { authoritative disable subnet 192.168.99.0/24 { default-router 192.168.99.1 dns-server 8.8.8.8 dns-server 8.8.4.4 lease 86400 start 192.168.99.101 { stop 192.168.99.255 } } } use-dnsmasq disable } dns { forwarding { cache-size 500 listen-on eth2 name-server 2001:4860:4860::8888 name-server 2001:4860:4860::8844 name-server 8.8.8.8 name-server 8.8.4.4 } } gui { http-port 80 https-port 443 older-ciphers enable } nat { rule 5000 { description "Masquerade for WAN" log disable outbound-interface eth0 protocol all type masquerade } } ssh { port 22 protocol-version v2 } upnp2 { listen-on eth2 nat-pmp disable secure-mode enable wan eth0 } } system { host-name UBNT-gateway login { user ubnt { authentication { encrypted-password $1$zKNoUbAo$gomzUbYvgyUMcD436Wo66. plaintext-password "" } full-name "UBNT Admin" level admin } } name-server 2001:4860:4860::8888 name-server 2001:4860:4860::8844 name-server 8.8.8.8 name-server 8.8.4.4 ntp { server 0.ubnt.pool.ntp.org { } server 1.ubnt.pool.ntp.org { } server 2.ubnt.pool.ntp.org { } server 3.ubnt.pool.ntp.org { } } offload { hwnat disable ipsec enable ipv4 { forwarding enable vlan enable } ipv6 { forwarding enable vlan enable } } package { repository wheezy { components "main contrib non-free" distribution wheezy password "" url username "" } } syslog { global { facility all { level notice } facility protocols { level debug } } } time-zone America/Denver traffic-analysis { dpi enable export enable } } /* Warning: Do not remove the following line. */ /* === vyatta-config-version: "config-management@1:conntrack@1:cron@1:dhcp-relay@1:dhcp-server@4:firewall@5:ipsec@5:nat@3:qos@1:quagga@2:system@4:ubnt-pptp@1:ubnt-util@1:vrrp@1:webgui@1:webproxy@1:zone-policy@1" === */ /* Release version: v1.9.1.4939093.161214.0705 */
null
https://raw.githubusercontent.com/stevejenkins/UBNT-EdgeRouter-Example-Configs/2eb96e7e618db69ff0481833f57044ac3060d99a/Comcast/config.boot.erl
erlang
/* EdgeRouter Lite + Comcast IPv4/IPv6 Dual Stack Config - -EdgeRouter-Example-Configs */ firewall { all-ping enable broadcast-ping disable ipv6-name WANv6_IN { default-action drop description "WANv6 inbound traffic forwarded to LAN" rule 10 { action accept description "Allow established/related" state { established enable related enable } } rule 20 { action drop description "Drop invalid state" state { invalid enable } } rule 30 { action accept description "Allow ICMPv6" log disable protocol icmpv6 } } ipv6-name WANv6_LOCAL { default-action drop description "WANv6 inbound traffic to the router" rule 10 { action accept description "Allow established/related" state { established enable related enable } } rule 20 { action drop description "Drop invalid state" state { invalid enable } } rule 30 { action accept description "Allow ICMPv6" log disable protocol icmpv6 } rule 40 { action accept description "Allow DHCPv6" destination { port 546 } protocol udp source { port 547 } } } ipv6-name WANv6_OUT { default-action accept description "WANv6 outbound traffic" rule 10 { action accept description "Allow established/related" state { established enable related enable } } rule 20 { action reject description "Reject invalid state" state { invalid enable } } } ipv6-receive-redirects disable ipv6-src-route disable ip-src-route disable log-martians enable name LAN_IN { default-action accept description "LAN to Internal" rule 10 { action drop description "Drop invalid state" state { invalid enable } } } name WAN_IN { default-action drop description "WAN to internal" rule 10 { action accept description "Allow established/related" log disable state { established enable invalid disable new disable related enable } } rule 20 { action accept description "Allow ICMP" log disable protocol icmp state { established enable related enable } } rule 100 { action drop description "Drop invalid state" protocol all state { established disable invalid enable new disable related disable } } } name WAN_LOCAL { default-action drop description "WAN to router" rule 10 { action accept description "Allow established/related" state { established enable related enable } } rule 20 { action accept description "Port Forward - Router SSH" destination { address 192.168.1.1 port 22 } protocol tcp } rule 30 { action accept description "Port Forward - Router HTTPS" destination { address 192.168.1.1 port 443 } protocol tcp } rule 100 { action drop description "Drop invalid state" protocol all state { established disable invalid enable new disable related disable } } } name WAN_OUT { default-action accept description "Internal to WAN" rule 10 { action accept description "Allow established/related" log disable state { established enable related enable } } rule 20 { action reject description "Reject invalid state" state { invalid enable } } } options { mss-clamp { interface-type all mss 1412 } } receive-redirects disable send-redirects enable source-validation disable syn-cookies enable } interfaces { ethernet eth0 { address dhcp description WAN dhcpv6-pd { pd 0 { interface eth1 { host-address ::1 prefix-id :0 service slaac } interface eth1.102 { host-address ::1 prefix-id :1 service slaac } interface eth2 { host-address ::1 prefix-id :2 service slaac } prefix-length /60 } rapid-commit enable } duplex auto firewall { in { ipv6-name WANv6_IN name WAN_IN } local { ipv6-name WANv6_LOCAL name WAN_LOCAL } out { ipv6-name WANv6_OUT name WAN_OUT } } speed auto } ethernet eth1 { address 192.168.99.1/24 description "Local Config" duplex auto firewall { in { name LAN_IN } } speed auto } loopback lo { } ethernet eth2 { address 192.168.1.1/24 description LAN duplex auto firewall { in { name LAN_IN } } mtu 1500 speed auto vif 102 { address 172.16.0.1/24 description "Guest Network VLAN" mtu 1500 } } } port-forward { auto-firewall enable hairpin-nat enable lan-interface eth2 rule 10 { description "Router SSH" forward-to { address 192.168.1.1 port 22 } original-port 2222 protocol tcp_udp } rule 20 { description "Router HTTPS" forward-to { address 192.168.1.1 port 443 } original-port 8080 protocol tcp_udp } wan-interface eth0 } service { dhcp-server { disabled false hostfile-update enable shared-network-name Guest { authoritative disable subnet 172.16.0.0/24 { default-router 172.16.0.1 dns-server 8.8.8.8 dns-server 8.8.4.4 domain-name guest.example.com lease 86400 start 172.16.0.10 { stop 172.16.0.254 } } } shared-network-name LAN { authoritative disable subnet 192.168.1.0/24 { default-router 192.168.1.1 dns-server 192.168.1.1 dns-server 8.8.8.8 dns-server 8.8.4.4 domain-name example.com lease 86400 start 192.168.1.101 { stop 192.168.1.254 } } } shared-network-name Config { authoritative disable subnet 192.168.99.0/24 { default-router 192.168.99.1 dns-server 8.8.8.8 dns-server 8.8.4.4 lease 86400 start 192.168.99.101 { stop 192.168.99.255 } } } use-dnsmasq disable } dns { forwarding { cache-size 500 listen-on eth2 name-server 2001:4860:4860::8888 name-server 2001:4860:4860::8844 name-server 8.8.8.8 name-server 8.8.4.4 } } gui { http-port 80 https-port 443 older-ciphers enable } nat { rule 5000 { description "Masquerade for WAN" log disable outbound-interface eth0 protocol all type masquerade } } ssh { port 22 protocol-version v2 } upnp2 { listen-on eth2 nat-pmp disable secure-mode enable wan eth0 } } system { host-name UBNT-gateway login { user ubnt { authentication { encrypted-password $1$zKNoUbAo$gomzUbYvgyUMcD436Wo66. plaintext-password "" } full-name "UBNT Admin" level admin } } name-server 2001:4860:4860::8888 name-server 2001:4860:4860::8844 name-server 8.8.8.8 name-server 8.8.4.4 ntp { server 0.ubnt.pool.ntp.org { } server 1.ubnt.pool.ntp.org { } server 2.ubnt.pool.ntp.org { } server 3.ubnt.pool.ntp.org { } } offload { hwnat disable ipsec enable ipv4 { forwarding enable vlan enable } ipv6 { forwarding enable vlan enable } } package { repository wheezy { components "main contrib non-free" distribution wheezy password "" url username "" } } syslog { global { facility all { level notice } facility protocols { level debug } } } time-zone America/Denver traffic-analysis { dpi enable export enable } } /* Warning: Do not remove the following line. */ /* === vyatta-config-version: "config-management@1:conntrack@1:cron@1:dhcp-relay@1:dhcp-server@4:firewall@5:ipsec@5:nat@3:qos@1:quagga@2:system@4:ubnt-pptp@1:ubnt-util@1:vrrp@1:webgui@1:webproxy@1:zone-policy@1" === */ /* Release version: v1.9.1.4939093.161214.0705 */
95050b1ff2f55d5e5b838165df885f9882eb73280a6c1a53b440bd2abb8bf9f2
codinuum/volt
custom.ml
let () = Bolt.Filter.register "myfilter" (fun e -> (e.Bolt.Event.line mod 2) = 0) let () = Bolt.Layout.register "mylayout" ([], [], (fun e -> Printf.sprintf "file \"%s\" says \"%s\" with level \"%s\" (line: %d)" e.Bolt.Event.file e.Bolt.Event.message (Bolt.Level.to_string e.Bolt.Event.level) e.Bolt.Event.line))
null
https://raw.githubusercontent.com/codinuum/volt/546207693ef102a2f02c85af935f64a8f16882e6/tests/03-customize/custom.ml
ocaml
let () = Bolt.Filter.register "myfilter" (fun e -> (e.Bolt.Event.line mod 2) = 0) let () = Bolt.Layout.register "mylayout" ([], [], (fun e -> Printf.sprintf "file \"%s\" says \"%s\" with level \"%s\" (line: %d)" e.Bolt.Event.file e.Bolt.Event.message (Bolt.Level.to_string e.Bolt.Event.level) e.Bolt.Event.line))
10fa08821d1ce244e55f8b562758a120ddfa4b1cad10add2a9f48fb09559e9d5
footprintanalytics/footprint-web
add_dimension_projections_test.clj
(ns metabase.query-processor.middleware.add-dimension-projections-test (:require [clojure.test :refer :all] [metabase.models.dimension :refer [Dimension]] [metabase.models.field :refer [Field]] [metabase.query-processor.context.default :as context.default] [metabase.query-processor.middleware.add-dimension-projections :as qp.add-dimension-projections] [metabase.test :as mt] [metabase.test.fixtures :as fixtures] [toucan.db :as db])) (use-fixtures :once (fixtures/initialize :db)) ;;; ----------------------------------------- add-fk-remaps (pre-processing) ----------------------------------------- (def ^:private remapped-field (delay {:id 1000 :name "Product" :field_id (mt/id :venues :category_id) :human_readable_field_id (mt/id :categories :name) :field_name "CATEGORY_ID" :human_readable_field_name "NAME"})) (defn- do-with-fake-remappings-for-category-id [f] (with-redefs [qp.add-dimension-projections/fields->field-id->remapping-dimension (constantly {(mt/id :venues :category_id) @remapped-field})] (f))) (deftest remap-column-infos-test (testing "make sure we create the remap column tuples correctly" (do-with-fake-remappings-for-category-id (fn [] (is (= [{:original-field-clause [:field (mt/id :venues :category_id) nil] :new-field-clause [:field (mt/id :categories :name) {:source-field (mt/id :venues :category_id) ::qp.add-dimension-projections/new-field-dimension-id 1000}] :dimension @remapped-field}] (#'qp.add-dimension-projections/remap-column-infos [[:field (mt/id :venues :price) nil] [:field (mt/id :venues :longitude) nil] [:field (mt/id :venues :category_id) nil]]))))))) (deftest add-fk-remaps-add-fields-test (do-with-fake-remappings-for-category-id (fn [] (testing "make sure FK remaps add an entry for the FK field to `:fields`, and returns a pair of [dimension-info updated-query]" (let [{:keys [remaps query]} (#'qp.add-dimension-projections/add-fk-remaps (mt/mbql-query venues {:fields [$price $longitude $category_id]}))] (is (= [@remapped-field] remaps)) (is (query= (mt/mbql-query venues {:fields [$price $longitude [:field %category_id {::qp.add-dimension-projections/original-field-dimension-id 1000}] [:field %categories.name {:source-field %category_id ::qp.add-dimension-projections/new-field-dimension-id 1000}]]}) query))))))) (deftest add-fk-remaps-do-not-add-duplicate-fields-test (testing "make sure we don't duplicate remappings" (do-with-fake-remappings-for-category-id (fn [] ;; make sure that we don't add duplicate columns even if the column has some weird unexpected options, i.e. we ;; need to do 'normalized' Field comparison for preventing duplicates. (doseq [category-name-options (mt/$ids venues [{:source-field %category_id} {:source-field %category_id ::some-other-namespaced-key true}])] (testing (format "\ncategories.name field options = %s" (pr-str category-name-options)) (let [{:keys [remaps query]} (#'qp.add-dimension-projections/add-fk-remaps (mt/mbql-query venues {:fields [$price $category_id [:field %categories.name category-name-options] [:expression "WOW"] $longitude]}))] (is (= [@remapped-field] remaps)) (is (query= (mt/mbql-query venues {:fields [$price [:field %category_id {::qp.add-dimension-projections/original-field-dimension-id 1000}] [:field %categories.name (assoc category-name-options ::qp.add-dimension-projections/new-field-dimension-id 1000)] [:expression "WOW"] $longitude]}) query)) (testing "Preprocessing query again should not result in duplicate columns being added" (is (query= query (:query (#'qp.add-dimension-projections/add-fk-remaps query)))))))))))) (deftest add-fk-remaps-replace-order-bys-test (testing "adding FK remaps should replace any existing order-bys for a field with order bys for the FK remapping Field" (do-with-fake-remappings-for-category-id (fn [] (let [{:keys [remaps query]} (#'qp.add-dimension-projections/add-fk-remaps (mt/mbql-query venues {:fields [$price $longitude $category_id] :order-by [[:asc $category_id]]}))] (is (= [@remapped-field] remaps)) (is (= (mt/mbql-query venues {:fields [$price $longitude [:field %category_id {::qp.add-dimension-projections/original-field-dimension-id 1000}] [:field %categories.name {:source-field %category_id ::qp.add-dimension-projections/new-field-dimension-id 1000}]] :order-by [[:asc [:field %categories.name {:source-field %category_id ::qp.add-dimension-projections/new-field-dimension-id 1000}]]]}) query))))))) (deftest add-fk-remaps-replace-breakouts-test (testing "adding FK remaps should replace any existing breakouts for a field with order bys for the FK remapping Field" (do-with-fake-remappings-for-category-id (fn [] (let [{:keys [remaps query]} (#'qp.add-dimension-projections/add-fk-remaps (mt/mbql-query venues {:breakout [$category_id] :aggregation [[:count]]}))] (is (= [@remapped-field] remaps)) (is (query= (mt/mbql-query venues {:breakout [[:field %categories.name {:source-field %category_id ::qp.add-dimension-projections/new-field-dimension-id 1000}] [:field %category_id {::qp.add-dimension-projections/original-field-dimension-id 1000}]] :aggregation [[:count]]}) query))))))) (deftest add-fk-remaps-nested-queries-test (testing "make sure FK remaps work with nested queries" (do-with-fake-remappings-for-category-id (fn [] (let [{:keys [remaps query]} (#'qp.add-dimension-projections/add-fk-remaps (mt/mbql-query venues {:source-query {:source-table $$venues :fields [$price $longitude $category_id]}}))] (is (= [@remapped-field] remaps)) (is (query= (mt/mbql-query venues {:source-query {:source-table $$venues :fields [$price $longitude [:field %category_id {::qp.add-dimension-projections/original-field-dimension-id 1000}] [:field %categories.name {:source-field %category_id ::qp.add-dimension-projections/new-field-dimension-id 1000}]]}}) query))))))) ;;; ---------------------------------------- remap-results (post-processing) ----------------------------------------- (defn- remap-results [query metadata rows] (let [rff (qp.add-dimension-projections/remap-results query context.default/default-rff) rf (rff metadata)] (transduce identity rf rows))) (deftest remap-human-readable-values-test (testing "remapping columns with `human_readable_values`" (mt/with-temp-vals-in-db Field (mt/id :venues :category_id) {:display_name "Foo"} (mt/with-column-remappings [venues.category_id {4 "Foo", 11 "Bar", 29 "Baz", 20 "Qux", nil "Quux"}] (is (partial= {:status :completed :row_count 6 :data {:rows [[1 "Red Medicine" 4 3 "Foo"] [2 "Stout Burgers & Beers" 11 2 "Bar"] [3 "The Apple Pan" 11 2 "Bar"] [4 "Wurstküche" 29 2 "Baz"] [5 "Brite Spot Family Restaurant" 20 2 "Qux"] [6 "Spaghetti Warehouse" nil 2 "Quux"]] :cols [{:name "ID"} {:name "NAME"} {:name "CATEGORY_ID", :remapped_to "Foo [internal remap]"} {:name "PRICE"} {:name "Foo [internal remap]", :remapped_from "CATEGORY_ID"}]}} (remap-results {} {:cols [{:name "ID"} {:name "NAME"} {:name "CATEGORY_ID", :id (mt/id :venues :category_id)} {:name "PRICE"}]} [[1 "Red Medicine" 4 3] [2 "Stout Burgers & Beers" 11 2] [3 "The Apple Pan" 11 2] [4 "Wurstküche" 29 2] [5 "Brite Spot Family Restaurant" 20 2] [6 "Spaghetti Warehouse" nil 2]]))))))) (deftest remap-human-readable-string-column-test (testing "remapping string columns with `human_readable_values`" (mt/with-temp-vals-in-db Field (mt/id :venues :name) {:display_name "Foo"} (mt/with-column-remappings [venues.name {"apple" "Appletini" "banana" "Bananasplit" "kiwi" "Kiwi-flavored Thing"}] (is (partial= {:status :completed :row_count 3 :data {:rows [[1 "apple" 4 3 "Appletini"] [2 "banana" 11 2 "Bananasplit"] [3 "kiwi" 11 2 "Kiwi-flavored Thing"]] :cols [{:name "ID"} {:name "NAME", :remapped_to "Foo [internal remap]"} {:name "CATEGORY_ID"} {:name "PRICE"} {:name "Foo [internal remap]", :remapped_from "NAME"}]}} (remap-results {} {:cols [{:name "ID"} {:name "NAME", :id (mt/id :venues :name)} {:name "CATEGORY_ID"} {:name "PRICE"}]} [[1 "apple" 4 3] [2 "banana" 11 2] [3 "kiwi" 11 2]]))))))) (deftest transform-values-for-col-test (testing "test that different columns types are transformed" (is (= (map list [123M 123.0 123N 123 "123"]) (map #(#'qp.add-dimension-projections/transform-values-for-col {:base_type %} [123]) [:type/Decimal :type/Float :type/BigInteger :type/Integer :type/Text]))))) (deftest external-remappings-metadata-test (testing "test that external remappings get the appropriate `:remapped_from`/`:remapped_to` info" (mt/with-temp Field [{category-id :id} {:name "CATEGORY", :display_name "Category"}] (is (partial= {:status :completed :row_count 0 :data {:rows [] :cols [{:name "ID"} {:name "NAME"} {:name "CATEGORY_ID" :remapped_to "CATEGORY"} {:name "PRICE"} {:name "CATEGORY" :remapped_from "CATEGORY_ID" :display_name "My Venue Category"}]}} (remap-results {::qp.add-dimension-projections/external-remaps [{:id 1000 :name "My Venue Category" :field_id (mt/id :venues :category_id) :field_name "category_id" :human_readable_field_id category-id :human_readable_field_name "category_name"}]} {:cols [{:name "ID"} {:name "NAME"} {:name "CATEGORY_ID" :id (mt/id :venues :category_id) :options {::qp.add-dimension-projections/original-field-dimension-id 1000}} {:name "PRICE"} {:name "CATEGORY" :id category-id :options {::qp.add-dimension-projections/new-field-dimension-id 1000}}]} [])))))) (deftest dimension-remappings-test (testing "Make sure columns from remapping Dimensions are spliced into the query during pre-processing" (mt/dataset sample-dataset (mt/with-column-remappings [orders.product_id products.title] (let [query (mt/mbql-query orders {:fields [$id $user_id $product_id $subtotal $tax $total $discount !default.created_at $quantity] :joins [{:fields :all :source-table $$products :condition [:= $product_id &Products.products.id] :alias "Products"}] :order-by [[:asc $id]] :limit 2}) dimension-id (db/select-one-id Dimension :field_id (mt/id :orders :product_id))] (doseq [nesting-level [0 1] :let [query (mt/nest-query query nesting-level)]] (testing (format "nesting level = %d" nesting-level) (is (= (-> query (assoc-in (concat [:query] (repeat nesting-level :source-query) [:fields]) (mt/$ids orders [$id $user_id [:field %product_id {::qp.add-dimension-projections/original-field-dimension-id dimension-id}] $subtotal $tax $total $discount !default.created_at $quantity [:field %products.title {:source-field %product_id ::qp.add-dimension-projections/new-field-dimension-id dimension-id}]])) (assoc ::qp.add-dimension-projections/external-remaps [{:id dimension-id :field_id (mt/id :orders :product_id) :name "Product ID [external remap]" :human_readable_field_id (mt/id :products :title) :field_name "PRODUCT_ID" :human_readable_field_name "TITLE"}])) (#'qp.add-dimension-projections/add-remapped-columns query)))))))))) (deftest fk-remaps-with-multiple-columns-with-same-name-test (testing "Make sure we remap to the correct column when some of them have duplicate names" (mt/with-column-remappings [venues.category_id categories.name] (let [query (mt/mbql-query venues {:fields [$name $category_id] :order-by [[:asc $name]] :limit 4}) {remap-info :remaps, preprocessed :query} (#'qp.add-dimension-projections/add-fk-remaps query) dimension-id (db/select-one-id Dimension :field_id (mt/id :venues :category_id) :human_readable_field_id (mt/id :categories :name))] (is (integer? dimension-id)) (testing "Preprocessing" (testing "Remap info" (is (query= (mt/$ids venues [{:id dimension-id :field_id %category_id :name "Category ID [external remap]" :human_readable_field_id %categories.name :field_name "CATEGORY_ID" :human_readable_field_name "NAME"}]) remap-info))) (testing "query" (is (query= (mt/mbql-query venues {:fields [$name [:field %category_id {::qp.add-dimension-projections/original-field-dimension-id dimension-id}] [:field %categories.name {:source-field %category_id ::qp.add-dimension-projections/new-field-dimension-id dimension-id}]] :order-by [[:asc $name]] :limit 4}) preprocessed)))) (testing "Post-processing" (let [metadata (mt/$ids venues {:cols [{:name "NAME" :id %name :display_name "Name"} {:name "CATEGORY_ID" :id %category_id :display_name "Category ID" :options {::qp.add-dimension-projections/original-field-dimension-id dimension-id}} {:name "NAME_2" :id %categories.name :display_name "Category → Name" :fk_field_id %category_id :options {::qp.add-dimension-projections/new-field-dimension-id dimension-id}}]})] (testing "metadata" (is (partial= {:cols [{:name "NAME", :display_name "Name"} {:name "CATEGORY_ID", :display_name "Category ID", :remapped_to "NAME_2"} {:name "NAME_2", :display_name "Category ID [external remap]", :remapped_from "CATEGORY_ID"}]} (#'qp.add-dimension-projections/add-remapped-to-and-from-metadata metadata remap-info nil)))))))))) (deftest multiple-fk-remaps-test (testing "Should be able to do multiple FK remaps via different FKs from Table A to Table B (#9236)\n" (mt/dataset avian-singles (mt/with-column-remappings [messages.sender_id users.name messages.receiver_id users.name] (let [query (mt/mbql-query messages {:fields [$sender_id $receiver_id $text] :order-by [[:asc $id]] :limit 3}) sender-dimension-id (db/select-one-id Dimension :field_id (mt/id :messages :sender_id) :human_readable_field_id (mt/id :users :name)) receiver-dimension-id (db/select-one-id Dimension :field_id (mt/id :messages :receiver_id) :human_readable_field_id (mt/id :users :name)) {remap-info :remaps, preprocessed :query} (#'qp.add-dimension-projections/add-fk-remaps query)] (testing "Pre-processing" (testing "Remap info" (is (query= (mt/$ids messages [{:id sender-dimension-id :field_id %sender_id :name "Sender ID [external remap]" :human_readable_field_id %users.name :field_name "SENDER_ID" :human_readable_field_name "NAME"} {:id receiver-dimension-id :field_id %receiver_id :name "Receiver ID [external remap]" :human_readable_field_id %users.name :field_name "RECEIVER_ID" :human_readable_field_name "NAME_2"}]) remap-info)))) (testing "query" (is (query= (mt/mbql-query messages {:fields [[:field %sender_id {::qp.add-dimension-projections/original-field-dimension-id sender-dimension-id}] [:field %receiver_id {::qp.add-dimension-projections/original-field-dimension-id receiver-dimension-id}] $text [:field %users.name {:source-field %sender_id ::qp.add-dimension-projections/new-field-dimension-id sender-dimension-id}] [:field %users.name {:source-field %receiver_id ::qp.add-dimension-projections/new-field-dimension-id receiver-dimension-id}]] :order-by [[:asc $id]] :limit 3}) preprocessed))) (testing "Post-processing" (let [metadata (mt/$ids messages {:cols [{:name "SENDER_ID" :id %sender_id :display_name "Sender ID" :options {::qp.add-dimension-projections/original-field-dimension-id sender-dimension-id}} {:name "RECEIVER_ID" :id %receiver_id :display_name "Receiver ID" :options {::qp.add-dimension-projections/original-field-dimension-id receiver-dimension-id}} {:name "TEXT" :id %text :display_name "Text"} {:name "NAME" :id %users.name :display_name "Sender → Name" :fk_field_id %sender_id :options {::qp.add-dimension-projections/new-field-dimension-id sender-dimension-id}} {:name "NAME_2" :id %users.name :display_name "Receiver → Name" :fk_field_id %receiver_id :options {::qp.add-dimension-projections/new-field-dimension-id receiver-dimension-id}}]})] (testing "metadata" (is (partial= {:cols [{:display_name "Sender ID", :name "SENDER_ID", :remapped_to "NAME"} {:display_name "Receiver ID", :name "RECEIVER_ID", :remapped_to "NAME_2"} {:display_name "Text", :name "TEXT"} {:display_name "Sender ID [external remap]", :name "NAME", :remapped_from "SENDER_ID"} {:display_name "Receiver ID [external remap]", :name "NAME_2", :remapped_from "RECEIVER_ID"}]} (#'qp.add-dimension-projections/add-remapped-to-and-from-metadata metadata remap-info nil))))))))))) (deftest add-remappings-inside-joins-test (testing "Remappings should work inside joins (#15578)" (mt/dataset sample-dataset (mt/with-column-remappings [orders.product_id products.title] (is (partial (mt/mbql-query products {:joins [{:source-query {:source-table $$orders} :alias "Q1" :fields [&Q1.orders.id &Q1.orders.product_id &PRODUCTS__via__PRODUCT_ID.orders.product_id->title] :condition [:= $id &Q1.orders.product_id] :strategy :left-join} {:source-table $$products :alias "PRODUCTS__via__PRODUCT_ID" :condition [:= $orders.product_id &PRODUCTS__via__PRODUCT_ID.products.id] :strategy :left-join :fk-field-id %orders.product_id}] :fields [&Q1.orders.id &Q1.orders.product_id &PRODUCTS__via__PRODUCT_ID.orders.product_id->products.title] :limit 2}) (:query (#'qp.add-dimension-projections/add-fk-remaps (mt/mbql-query products {:joins [{:strategy :left-join :source-query {:source-table $$orders} :alias "Q1" :condition [:= $id &Q1.orders.product_id] :fields [&Q1.orders.id &Q1.orders.product_id]}] :fields [&Q1.orders.id &Q1.orders.product_id] :limit 2})))))))))
null
https://raw.githubusercontent.com/footprintanalytics/footprint-web/d3090d943dd9fcea493c236f79e7ef8a36ae17fc/test/metabase/query_processor/middleware/add_dimension_projections_test.clj
clojure
----------------------------------------- add-fk-remaps (pre-processing) ----------------------------------------- make sure that we don't add duplicate columns even if the column has some weird unexpected options, i.e. we need to do 'normalized' Field comparison for preventing duplicates. ---------------------------------------- remap-results (post-processing) -----------------------------------------
(ns metabase.query-processor.middleware.add-dimension-projections-test (:require [clojure.test :refer :all] [metabase.models.dimension :refer [Dimension]] [metabase.models.field :refer [Field]] [metabase.query-processor.context.default :as context.default] [metabase.query-processor.middleware.add-dimension-projections :as qp.add-dimension-projections] [metabase.test :as mt] [metabase.test.fixtures :as fixtures] [toucan.db :as db])) (use-fixtures :once (fixtures/initialize :db)) (def ^:private remapped-field (delay {:id 1000 :name "Product" :field_id (mt/id :venues :category_id) :human_readable_field_id (mt/id :categories :name) :field_name "CATEGORY_ID" :human_readable_field_name "NAME"})) (defn- do-with-fake-remappings-for-category-id [f] (with-redefs [qp.add-dimension-projections/fields->field-id->remapping-dimension (constantly {(mt/id :venues :category_id) @remapped-field})] (f))) (deftest remap-column-infos-test (testing "make sure we create the remap column tuples correctly" (do-with-fake-remappings-for-category-id (fn [] (is (= [{:original-field-clause [:field (mt/id :venues :category_id) nil] :new-field-clause [:field (mt/id :categories :name) {:source-field (mt/id :venues :category_id) ::qp.add-dimension-projections/new-field-dimension-id 1000}] :dimension @remapped-field}] (#'qp.add-dimension-projections/remap-column-infos [[:field (mt/id :venues :price) nil] [:field (mt/id :venues :longitude) nil] [:field (mt/id :venues :category_id) nil]]))))))) (deftest add-fk-remaps-add-fields-test (do-with-fake-remappings-for-category-id (fn [] (testing "make sure FK remaps add an entry for the FK field to `:fields`, and returns a pair of [dimension-info updated-query]" (let [{:keys [remaps query]} (#'qp.add-dimension-projections/add-fk-remaps (mt/mbql-query venues {:fields [$price $longitude $category_id]}))] (is (= [@remapped-field] remaps)) (is (query= (mt/mbql-query venues {:fields [$price $longitude [:field %category_id {::qp.add-dimension-projections/original-field-dimension-id 1000}] [:field %categories.name {:source-field %category_id ::qp.add-dimension-projections/new-field-dimension-id 1000}]]}) query))))))) (deftest add-fk-remaps-do-not-add-duplicate-fields-test (testing "make sure we don't duplicate remappings" (do-with-fake-remappings-for-category-id (fn [] (doseq [category-name-options (mt/$ids venues [{:source-field %category_id} {:source-field %category_id ::some-other-namespaced-key true}])] (testing (format "\ncategories.name field options = %s" (pr-str category-name-options)) (let [{:keys [remaps query]} (#'qp.add-dimension-projections/add-fk-remaps (mt/mbql-query venues {:fields [$price $category_id [:field %categories.name category-name-options] [:expression "WOW"] $longitude]}))] (is (= [@remapped-field] remaps)) (is (query= (mt/mbql-query venues {:fields [$price [:field %category_id {::qp.add-dimension-projections/original-field-dimension-id 1000}] [:field %categories.name (assoc category-name-options ::qp.add-dimension-projections/new-field-dimension-id 1000)] [:expression "WOW"] $longitude]}) query)) (testing "Preprocessing query again should not result in duplicate columns being added" (is (query= query (:query (#'qp.add-dimension-projections/add-fk-remaps query)))))))))))) (deftest add-fk-remaps-replace-order-bys-test (testing "adding FK remaps should replace any existing order-bys for a field with order bys for the FK remapping Field" (do-with-fake-remappings-for-category-id (fn [] (let [{:keys [remaps query]} (#'qp.add-dimension-projections/add-fk-remaps (mt/mbql-query venues {:fields [$price $longitude $category_id] :order-by [[:asc $category_id]]}))] (is (= [@remapped-field] remaps)) (is (= (mt/mbql-query venues {:fields [$price $longitude [:field %category_id {::qp.add-dimension-projections/original-field-dimension-id 1000}] [:field %categories.name {:source-field %category_id ::qp.add-dimension-projections/new-field-dimension-id 1000}]] :order-by [[:asc [:field %categories.name {:source-field %category_id ::qp.add-dimension-projections/new-field-dimension-id 1000}]]]}) query))))))) (deftest add-fk-remaps-replace-breakouts-test (testing "adding FK remaps should replace any existing breakouts for a field with order bys for the FK remapping Field" (do-with-fake-remappings-for-category-id (fn [] (let [{:keys [remaps query]} (#'qp.add-dimension-projections/add-fk-remaps (mt/mbql-query venues {:breakout [$category_id] :aggregation [[:count]]}))] (is (= [@remapped-field] remaps)) (is (query= (mt/mbql-query venues {:breakout [[:field %categories.name {:source-field %category_id ::qp.add-dimension-projections/new-field-dimension-id 1000}] [:field %category_id {::qp.add-dimension-projections/original-field-dimension-id 1000}]] :aggregation [[:count]]}) query))))))) (deftest add-fk-remaps-nested-queries-test (testing "make sure FK remaps work with nested queries" (do-with-fake-remappings-for-category-id (fn [] (let [{:keys [remaps query]} (#'qp.add-dimension-projections/add-fk-remaps (mt/mbql-query venues {:source-query {:source-table $$venues :fields [$price $longitude $category_id]}}))] (is (= [@remapped-field] remaps)) (is (query= (mt/mbql-query venues {:source-query {:source-table $$venues :fields [$price $longitude [:field %category_id {::qp.add-dimension-projections/original-field-dimension-id 1000}] [:field %categories.name {:source-field %category_id ::qp.add-dimension-projections/new-field-dimension-id 1000}]]}}) query))))))) (defn- remap-results [query metadata rows] (let [rff (qp.add-dimension-projections/remap-results query context.default/default-rff) rf (rff metadata)] (transduce identity rf rows))) (deftest remap-human-readable-values-test (testing "remapping columns with `human_readable_values`" (mt/with-temp-vals-in-db Field (mt/id :venues :category_id) {:display_name "Foo"} (mt/with-column-remappings [venues.category_id {4 "Foo", 11 "Bar", 29 "Baz", 20 "Qux", nil "Quux"}] (is (partial= {:status :completed :row_count 6 :data {:rows [[1 "Red Medicine" 4 3 "Foo"] [2 "Stout Burgers & Beers" 11 2 "Bar"] [3 "The Apple Pan" 11 2 "Bar"] [4 "Wurstküche" 29 2 "Baz"] [5 "Brite Spot Family Restaurant" 20 2 "Qux"] [6 "Spaghetti Warehouse" nil 2 "Quux"]] :cols [{:name "ID"} {:name "NAME"} {:name "CATEGORY_ID", :remapped_to "Foo [internal remap]"} {:name "PRICE"} {:name "Foo [internal remap]", :remapped_from "CATEGORY_ID"}]}} (remap-results {} {:cols [{:name "ID"} {:name "NAME"} {:name "CATEGORY_ID", :id (mt/id :venues :category_id)} {:name "PRICE"}]} [[1 "Red Medicine" 4 3] [2 "Stout Burgers & Beers" 11 2] [3 "The Apple Pan" 11 2] [4 "Wurstküche" 29 2] [5 "Brite Spot Family Restaurant" 20 2] [6 "Spaghetti Warehouse" nil 2]]))))))) (deftest remap-human-readable-string-column-test (testing "remapping string columns with `human_readable_values`" (mt/with-temp-vals-in-db Field (mt/id :venues :name) {:display_name "Foo"} (mt/with-column-remappings [venues.name {"apple" "Appletini" "banana" "Bananasplit" "kiwi" "Kiwi-flavored Thing"}] (is (partial= {:status :completed :row_count 3 :data {:rows [[1 "apple" 4 3 "Appletini"] [2 "banana" 11 2 "Bananasplit"] [3 "kiwi" 11 2 "Kiwi-flavored Thing"]] :cols [{:name "ID"} {:name "NAME", :remapped_to "Foo [internal remap]"} {:name "CATEGORY_ID"} {:name "PRICE"} {:name "Foo [internal remap]", :remapped_from "NAME"}]}} (remap-results {} {:cols [{:name "ID"} {:name "NAME", :id (mt/id :venues :name)} {:name "CATEGORY_ID"} {:name "PRICE"}]} [[1 "apple" 4 3] [2 "banana" 11 2] [3 "kiwi" 11 2]]))))))) (deftest transform-values-for-col-test (testing "test that different columns types are transformed" (is (= (map list [123M 123.0 123N 123 "123"]) (map #(#'qp.add-dimension-projections/transform-values-for-col {:base_type %} [123]) [:type/Decimal :type/Float :type/BigInteger :type/Integer :type/Text]))))) (deftest external-remappings-metadata-test (testing "test that external remappings get the appropriate `:remapped_from`/`:remapped_to` info" (mt/with-temp Field [{category-id :id} {:name "CATEGORY", :display_name "Category"}] (is (partial= {:status :completed :row_count 0 :data {:rows [] :cols [{:name "ID"} {:name "NAME"} {:name "CATEGORY_ID" :remapped_to "CATEGORY"} {:name "PRICE"} {:name "CATEGORY" :remapped_from "CATEGORY_ID" :display_name "My Venue Category"}]}} (remap-results {::qp.add-dimension-projections/external-remaps [{:id 1000 :name "My Venue Category" :field_id (mt/id :venues :category_id) :field_name "category_id" :human_readable_field_id category-id :human_readable_field_name "category_name"}]} {:cols [{:name "ID"} {:name "NAME"} {:name "CATEGORY_ID" :id (mt/id :venues :category_id) :options {::qp.add-dimension-projections/original-field-dimension-id 1000}} {:name "PRICE"} {:name "CATEGORY" :id category-id :options {::qp.add-dimension-projections/new-field-dimension-id 1000}}]} [])))))) (deftest dimension-remappings-test (testing "Make sure columns from remapping Dimensions are spliced into the query during pre-processing" (mt/dataset sample-dataset (mt/with-column-remappings [orders.product_id products.title] (let [query (mt/mbql-query orders {:fields [$id $user_id $product_id $subtotal $tax $total $discount !default.created_at $quantity] :joins [{:fields :all :source-table $$products :condition [:= $product_id &Products.products.id] :alias "Products"}] :order-by [[:asc $id]] :limit 2}) dimension-id (db/select-one-id Dimension :field_id (mt/id :orders :product_id))] (doseq [nesting-level [0 1] :let [query (mt/nest-query query nesting-level)]] (testing (format "nesting level = %d" nesting-level) (is (= (-> query (assoc-in (concat [:query] (repeat nesting-level :source-query) [:fields]) (mt/$ids orders [$id $user_id [:field %product_id {::qp.add-dimension-projections/original-field-dimension-id dimension-id}] $subtotal $tax $total $discount !default.created_at $quantity [:field %products.title {:source-field %product_id ::qp.add-dimension-projections/new-field-dimension-id dimension-id}]])) (assoc ::qp.add-dimension-projections/external-remaps [{:id dimension-id :field_id (mt/id :orders :product_id) :name "Product ID [external remap]" :human_readable_field_id (mt/id :products :title) :field_name "PRODUCT_ID" :human_readable_field_name "TITLE"}])) (#'qp.add-dimension-projections/add-remapped-columns query)))))))))) (deftest fk-remaps-with-multiple-columns-with-same-name-test (testing "Make sure we remap to the correct column when some of them have duplicate names" (mt/with-column-remappings [venues.category_id categories.name] (let [query (mt/mbql-query venues {:fields [$name $category_id] :order-by [[:asc $name]] :limit 4}) {remap-info :remaps, preprocessed :query} (#'qp.add-dimension-projections/add-fk-remaps query) dimension-id (db/select-one-id Dimension :field_id (mt/id :venues :category_id) :human_readable_field_id (mt/id :categories :name))] (is (integer? dimension-id)) (testing "Preprocessing" (testing "Remap info" (is (query= (mt/$ids venues [{:id dimension-id :field_id %category_id :name "Category ID [external remap]" :human_readable_field_id %categories.name :field_name "CATEGORY_ID" :human_readable_field_name "NAME"}]) remap-info))) (testing "query" (is (query= (mt/mbql-query venues {:fields [$name [:field %category_id {::qp.add-dimension-projections/original-field-dimension-id dimension-id}] [:field %categories.name {:source-field %category_id ::qp.add-dimension-projections/new-field-dimension-id dimension-id}]] :order-by [[:asc $name]] :limit 4}) preprocessed)))) (testing "Post-processing" (let [metadata (mt/$ids venues {:cols [{:name "NAME" :id %name :display_name "Name"} {:name "CATEGORY_ID" :id %category_id :display_name "Category ID" :options {::qp.add-dimension-projections/original-field-dimension-id dimension-id}} {:name "NAME_2" :id %categories.name :display_name "Category → Name" :fk_field_id %category_id :options {::qp.add-dimension-projections/new-field-dimension-id dimension-id}}]})] (testing "metadata" (is (partial= {:cols [{:name "NAME", :display_name "Name"} {:name "CATEGORY_ID", :display_name "Category ID", :remapped_to "NAME_2"} {:name "NAME_2", :display_name "Category ID [external remap]", :remapped_from "CATEGORY_ID"}]} (#'qp.add-dimension-projections/add-remapped-to-and-from-metadata metadata remap-info nil)))))))))) (deftest multiple-fk-remaps-test (testing "Should be able to do multiple FK remaps via different FKs from Table A to Table B (#9236)\n" (mt/dataset avian-singles (mt/with-column-remappings [messages.sender_id users.name messages.receiver_id users.name] (let [query (mt/mbql-query messages {:fields [$sender_id $receiver_id $text] :order-by [[:asc $id]] :limit 3}) sender-dimension-id (db/select-one-id Dimension :field_id (mt/id :messages :sender_id) :human_readable_field_id (mt/id :users :name)) receiver-dimension-id (db/select-one-id Dimension :field_id (mt/id :messages :receiver_id) :human_readable_field_id (mt/id :users :name)) {remap-info :remaps, preprocessed :query} (#'qp.add-dimension-projections/add-fk-remaps query)] (testing "Pre-processing" (testing "Remap info" (is (query= (mt/$ids messages [{:id sender-dimension-id :field_id %sender_id :name "Sender ID [external remap]" :human_readable_field_id %users.name :field_name "SENDER_ID" :human_readable_field_name "NAME"} {:id receiver-dimension-id :field_id %receiver_id :name "Receiver ID [external remap]" :human_readable_field_id %users.name :field_name "RECEIVER_ID" :human_readable_field_name "NAME_2"}]) remap-info)))) (testing "query" (is (query= (mt/mbql-query messages {:fields [[:field %sender_id {::qp.add-dimension-projections/original-field-dimension-id sender-dimension-id}] [:field %receiver_id {::qp.add-dimension-projections/original-field-dimension-id receiver-dimension-id}] $text [:field %users.name {:source-field %sender_id ::qp.add-dimension-projections/new-field-dimension-id sender-dimension-id}] [:field %users.name {:source-field %receiver_id ::qp.add-dimension-projections/new-field-dimension-id receiver-dimension-id}]] :order-by [[:asc $id]] :limit 3}) preprocessed))) (testing "Post-processing" (let [metadata (mt/$ids messages {:cols [{:name "SENDER_ID" :id %sender_id :display_name "Sender ID" :options {::qp.add-dimension-projections/original-field-dimension-id sender-dimension-id}} {:name "RECEIVER_ID" :id %receiver_id :display_name "Receiver ID" :options {::qp.add-dimension-projections/original-field-dimension-id receiver-dimension-id}} {:name "TEXT" :id %text :display_name "Text"} {:name "NAME" :id %users.name :display_name "Sender → Name" :fk_field_id %sender_id :options {::qp.add-dimension-projections/new-field-dimension-id sender-dimension-id}} {:name "NAME_2" :id %users.name :display_name "Receiver → Name" :fk_field_id %receiver_id :options {::qp.add-dimension-projections/new-field-dimension-id receiver-dimension-id}}]})] (testing "metadata" (is (partial= {:cols [{:display_name "Sender ID", :name "SENDER_ID", :remapped_to "NAME"} {:display_name "Receiver ID", :name "RECEIVER_ID", :remapped_to "NAME_2"} {:display_name "Text", :name "TEXT"} {:display_name "Sender ID [external remap]", :name "NAME", :remapped_from "SENDER_ID"} {:display_name "Receiver ID [external remap]", :name "NAME_2", :remapped_from "RECEIVER_ID"}]} (#'qp.add-dimension-projections/add-remapped-to-and-from-metadata metadata remap-info nil))))))))))) (deftest add-remappings-inside-joins-test (testing "Remappings should work inside joins (#15578)" (mt/dataset sample-dataset (mt/with-column-remappings [orders.product_id products.title] (is (partial (mt/mbql-query products {:joins [{:source-query {:source-table $$orders} :alias "Q1" :fields [&Q1.orders.id &Q1.orders.product_id &PRODUCTS__via__PRODUCT_ID.orders.product_id->title] :condition [:= $id &Q1.orders.product_id] :strategy :left-join} {:source-table $$products :alias "PRODUCTS__via__PRODUCT_ID" :condition [:= $orders.product_id &PRODUCTS__via__PRODUCT_ID.products.id] :strategy :left-join :fk-field-id %orders.product_id}] :fields [&Q1.orders.id &Q1.orders.product_id &PRODUCTS__via__PRODUCT_ID.orders.product_id->products.title] :limit 2}) (:query (#'qp.add-dimension-projections/add-fk-remaps (mt/mbql-query products {:joins [{:strategy :left-join :source-query {:source-table $$orders} :alias "Q1" :condition [:= $id &Q1.orders.product_id] :fields [&Q1.orders.id &Q1.orders.product_id]}] :fields [&Q1.orders.id &Q1.orders.product_id] :limit 2})))))))))
3e41921c15e3c3616c768fcc4a3b9c028aa4f230a2cca0b85fcb2b582d7578f3
alexandroid000/improv
BinaryIter.hs
-- |Binary iteratee-style serialization helpers for working with ROS -- message types. This module is used by the automatically-generated -- code for ROS .msg types. module Ros.Node.BinaryIter (streamIn, getServiceResult) where import Control.Applicative import Control.Concurrent (myThreadId, killThread) import Control.Monad.IO.Class import Control.Monad.Trans.Maybe import Data.Binary.Get import qualified Data.ByteString as BS import qualified Data.ByteString.Lazy as BL import System.IO (Handle) import Ros.Topic import Ros.Internal.RosBinary (RosBinary(get)) import Ros.Service.ServiceTypes(ServiceResponseExcept(..)) import Data.ByteString.Lazy.Char8 (unpack) import Control.Monad.Except (ExceptT(..), throwError) -- Get the specified number of bytes from a 'Handle'. Returns a -- wrapped-up 'Nothing' if the client shutdown (indicated by receiving a message of zero length ) . hGetAll :: Handle -> Int -> MaybeT IO BL.ByteString hGetAll h n = go n [] where go 0 acc = return . BL.fromChunks $ reverse acc go n' acc = do bs <- liftIO $ BS.hGet h n' case BS.length bs of 0 -> MaybeT $ return Nothing x -> go (n' - x) (bs:acc) -- |The function that does the work of streaming members of the ' RosBinary ' class in from a ' Handle ' . streamIn :: RosBinary a => Handle -> Topic IO a streamIn h = Topic go where go = do item <- runMaybeT $ do len <- runGet getInt <$> hGetAll h 4 runGet get <$> hGetAll h len case item of Nothing -> putStrLn "Publisher stopped" >> myThreadId >>= killThread >> return undefined Just item' -> return (item', Topic go) getInt :: Get Int getInt = fromIntegral <$> getWord32le -- | Get the result back from a service call (called by the service client) ( see ) getServiceResult :: RosBinary a => Handle -> ExceptT ServiceResponseExcept IO a getServiceResult h = do okByte <- runGet getWord8 <$> hGetAllET h 1 (ResponseReadExcept "Could not read okByte") case okByte of 0 -> do len <- runGet getInt <$> hGetAllET h 4 (ResponseReadExcept "Could not read length for notOk message") message <- hGetAllET h len (ResponseReadExcept "Could not read notOk message") throwError . NotOkExcept $ unpack message _ -> do len <- runGet getInt <$> hGetAllET h 4 (ResponseReadExcept "Could not read length") runGet get <$> hGetAllET h len (ResponseReadExcept "Could not read response message") hGetAllET :: Handle -> Int -> ServiceResponseExcept -> ExceptT ServiceResponseExcept IO BL.ByteString hGetAllET h n exceptMessage = do maybeData <- liftIO . runMaybeT $ hGetAll h n case maybeData of Nothing -> throwError exceptMessage Just b -> ExceptT . return $ Right b
null
https://raw.githubusercontent.com/alexandroid000/improv/ef0f4a6a5f99a9c7ff3d25f50529417aba9f757c/roshask/src/Ros/Node/BinaryIter.hs
haskell
|Binary iteratee-style serialization helpers for working with ROS message types. This module is used by the automatically-generated code for ROS .msg types. Get the specified number of bytes from a 'Handle'. Returns a wrapped-up 'Nothing' if the client shutdown (indicated by receiving |The function that does the work of streaming members of the | Get the result back from a service call (called by the service client)
module Ros.Node.BinaryIter (streamIn, getServiceResult) where import Control.Applicative import Control.Concurrent (myThreadId, killThread) import Control.Monad.IO.Class import Control.Monad.Trans.Maybe import Data.Binary.Get import qualified Data.ByteString as BS import qualified Data.ByteString.Lazy as BL import System.IO (Handle) import Ros.Topic import Ros.Internal.RosBinary (RosBinary(get)) import Ros.Service.ServiceTypes(ServiceResponseExcept(..)) import Data.ByteString.Lazy.Char8 (unpack) import Control.Monad.Except (ExceptT(..), throwError) a message of zero length ) . hGetAll :: Handle -> Int -> MaybeT IO BL.ByteString hGetAll h n = go n [] where go 0 acc = return . BL.fromChunks $ reverse acc go n' acc = do bs <- liftIO $ BS.hGet h n' case BS.length bs of 0 -> MaybeT $ return Nothing x -> go (n' - x) (bs:acc) ' RosBinary ' class in from a ' Handle ' . streamIn :: RosBinary a => Handle -> Topic IO a streamIn h = Topic go where go = do item <- runMaybeT $ do len <- runGet getInt <$> hGetAll h 4 runGet get <$> hGetAll h len case item of Nothing -> putStrLn "Publisher stopped" >> myThreadId >>= killThread >> return undefined Just item' -> return (item', Topic go) getInt :: Get Int getInt = fromIntegral <$> getWord32le ( see ) getServiceResult :: RosBinary a => Handle -> ExceptT ServiceResponseExcept IO a getServiceResult h = do okByte <- runGet getWord8 <$> hGetAllET h 1 (ResponseReadExcept "Could not read okByte") case okByte of 0 -> do len <- runGet getInt <$> hGetAllET h 4 (ResponseReadExcept "Could not read length for notOk message") message <- hGetAllET h len (ResponseReadExcept "Could not read notOk message") throwError . NotOkExcept $ unpack message _ -> do len <- runGet getInt <$> hGetAllET h 4 (ResponseReadExcept "Could not read length") runGet get <$> hGetAllET h len (ResponseReadExcept "Could not read response message") hGetAllET :: Handle -> Int -> ServiceResponseExcept -> ExceptT ServiceResponseExcept IO BL.ByteString hGetAllET h n exceptMessage = do maybeData <- liftIO . runMaybeT $ hGetAll h n case maybeData of Nothing -> throwError exceptMessage Just b -> ExceptT . return $ Right b
53eae0860be66a7a86005d49ac1649c3585dfa805175418313b71f680daace1d
luminus-framework/luminus-template
core.cljs
(ns <<project-ns>>.core) (defn<% if shadow-cljs %> ^:dev/after-load<% endif %> mount-components [] (let [content (js/document.getElementById "app")] (while (.hasChildNodes content) (.removeChild content (.-lastChild content))) (.appendChild content (js/document.createTextNode "Welcome to <<name>>")))) (defn init! [] (mount-components))
null
https://raw.githubusercontent.com/luminus-framework/luminus-template/3278aa727cef0a173ed3ca722dfd6afa6b4bbc8f/resources/leiningen/new/luminus/cljs/src/cljs/core.cljs
clojure
(ns <<project-ns>>.core) (defn<% if shadow-cljs %> ^:dev/after-load<% endif %> mount-components [] (let [content (js/document.getElementById "app")] (while (.hasChildNodes content) (.removeChild content (.-lastChild content))) (.appendChild content (js/document.createTextNode "Welcome to <<name>>")))) (defn init! [] (mount-components))
547c7d7fd2f77d1af831f3a6de5321a0b1083e91e93432a8f4397f9ffb92b3e5
INRIA/zelus
printer.ml
(***********************************************************************) (* *) (* *) (* Zelus, a synchronous language for hybrid systems *) (* *) ( c ) 2020 Paris ( see the file ) (* *) (* Copyright Institut National de Recherche en Informatique et en *) Automatique . All rights reserved . This file is distributed under the terms of the INRIA Non - Commercial License Agreement ( see the (* LICENSE file). *) (* *) (* *********************************************************************) (* the printer *) open Zlocation open Zmisc open Zelus open Deftypes open Ptypes open Global open Modules open Pp_tools open Format let no_op ff _ = () (* Infix chars are surrounded by parenthesis *) let is_infix = let module StrSet = Set.Make(String) in let set_infix = List.fold_right StrSet.add ["or"; "quo"; "mod"; "land"; "lor"; "lxor"; "lsl"; "lsr"; "asr"] StrSet.empty in fun s -> StrSet.mem s set_infix let parenthesis s = let c = String.get s 0 in if is_infix s then "(" ^ s ^ ")" else match c with | 'a' .. 'z' | 'A' .. 'Z' | '_' | '`' -> s | '*' -> "( " ^ s ^ " )" | _ -> if s = "()" then s else "(" ^ s ^ ")" let shortname ff s = fprintf ff "%s" (parenthesis s) let qualident ff { Lident.qual = m; Lident.id = s } = fprintf ff "%s.%s" m (parenthesis s) let longname ff ln = let ln = Initial.short (currentname ln) in match ln with | Lident.Name(m) -> shortname ff m | Lident.Modname(qual) -> qualident ff qual let name ff n = shortname ff (Zident.name n) let source_name ff n = shortname ff (Zident.source n) let immediate ff = function | Eint i -> fprintf ff "%d" i | Efloat f -> fprintf ff "%f" f | Ebool b -> if b then fprintf ff "true" else fprintf ff "false" | Estring s -> fprintf ff "%S" s | Echar c -> fprintf ff "'%c'" c | Evoid -> fprintf ff "()" let constant ff = function | Cimmediate(i) -> immediate ff i | Cglobal(ln) -> longname ff ln let print_opt_magic print ff = function | None -> pp_print_string ff "Obj.magic ()" | Some(e) -> print ff e let rec pattern ff ({ p_typ = ty; p_caus = caus_list } as pat) = let rec pattern ff pat = match pat.p_desc with | Evarpat(n) -> fprintf ff "@[(%a : %a)@]" name n Ptypes.output ty | Ewildpat -> fprintf ff "_" | Econstpat(im) -> immediate ff im | Econstr0pat(ln) -> longname ff ln | Econstr1pat(ln, pat_list) -> fprintf ff "@[%a%a@]" longname ln (pattern_list "(" "," ")") pat_list | Etuplepat(pat_list) -> pattern_list "(" "," ")" ff pat_list | Etypeconstraintpat(p, ty_exp) -> fprintf ff "@[(%a:%a)@]" pattern p ptype ty_exp | Erecordpat(n_pat_list) -> print_record (print_couple longname pattern """ =""") ff n_pat_list | Ealiaspat(p, n) -> fprintf ff "%a as %a" pattern p name n | Eorpat(pat1, pat2) -> fprintf ff "%a | %a" pattern pat1 pattern pat2 in (* fprintf ff "@[%a (* caus: %a *)@]" pattern pat Pcaus.caus_list caus_list *) pattern ff pat and pattern_list po sep pf ff pat_list = fprintf ff "@[%a@]" (print_list_r pattern po sep pf) pat_list and ptype ff ty = let operator = function Splus -> "+" | Sminus -> "-" in let priority = function Splus -> 0 | Sminus -> 1 in let rec psize prio ff { desc = desc } = match desc with | Sconst(i) -> fprintf ff "%d" i | Sglobal(ln) -> longname ff ln | Sname(n) -> name ff n | Sop(op, e1, e2) -> let prio_op = priority op in if prio > prio_op then fprintf ff "("; fprintf ff "@[%a %s %a@]" (psize prio_op) e1 (operator op) (psize prio_op) e2; if prio > prio_op then fprintf ff ")" in match ty.desc with | Etypevar(s) -> fprintf ff "'%s" s | Etypeconstr(ln, ty_list) -> fprintf ff "@[<hov2>%a@]%a" (print_list_r_empty ptype "("","")") ty_list longname ln | Etypetuple(ty_list) -> fprintf ff "@[<hov2>%a@]" (print_list_r ptype "(""*"")") ty_list | Etypefun(k, n_opt, ty_arg, ty_res) -> let pas ff (n_opt, ty_arg) = match n_opt with | None -> () | Some(n) -> fprintf ff "(%a : %a)" name n ptype ty_arg in let s = match k with | S -> "-S->" | A -> "-A->" | AD -> "-AD->" | D -> "-D->" | C -> "-C->" | AS -> "-AS->" | P -> "~D~>" in fprintf ff "@[<hov2>%a %s %a@]" pas (n_opt, ty_arg) s ptype ty_res | Etypevec(ty_arg, size) -> fprintf ff "@[%a[%a]@]" ptype ty_arg (psize 0) size let default ff = function | Init(v) -> fprintf ff " init %a" constant v | Default(v) -> fprintf ff " default %a" constant v let combine ff v = fprintf ff " with %a" longname v let print_vardec_list ff vardec_list = let vardec ff { vardec_name = n; vardec_default = d_opt; vardec_combine = c_opt } = fprintf ff "@[%a%a%a@]" name n (Zmisc.optional_unit default) d_opt (Zmisc.optional_unit combine) c_opt in if vardec_list <> [] then fprintf ff "@[<v 2>%a@ @]" (print_list_r vardec "local " "," "") vardec_list let kind k = match k with | Cont -> "cont" | Zero -> "zero" | Period -> "period" | Horizon -> "horizon" | Encore -> "encore" | Major -> "major" let print_binding ff (n, { t_sort = sort; t_typ = typ }) = let default ff v = fprintf ff " default %a" constant v in let combine ff v = fprintf ff " with %a" longname v in let init ff i_opt = match i_opt with | Noinit -> () | InitEq -> fprintf ff " init" | InitDecl(c) -> fprintf ff " init %a" constant c in let next ff is_n = fprintf ff "%s" (if is_n then "next " else "cur ") in let previous p = if p then "last " else "" in let kind ff k = fprintf ff "%s" (kind k) in match sort with | Sstatic -> fprintf ff "@[static %a: %a@,@]" name n Ptypes.output typ | Sval -> fprintf ff "@[val %a: %a@,@]" name n Ptypes.output typ | Svar { v_combine = c_opt; v_default = d_opt } -> fprintf ff "@[var %a: %a%a%a@,@]" name n Ptypes.output typ (Zmisc.optional_unit default) d_opt (Zmisc.optional_unit combine) c_opt | Smem { m_kind = k; m_next = n_opt; m_previous = p; m_init = i_opt; m_combine = c_opt } -> fprintf ff "@[%a%s%a mem %a: %a%a%a@,@]" (Zmisc.optional_unit next) n_opt (previous p) (Zmisc.optional_unit kind) k name n Ptypes.output typ init i_opt (Zmisc.optional_unit combine) c_opt let print_env ff env = if !vverbose then begin let env = Zident.Env.bindings env in if env <> [] then fprintf ff "@[<v 0>(* defs: %a *)@,@]" (print_list_r print_binding """;""") env end let print_writes ff { dv = dv; di = di; der = der; nv = nv; mv = mv } = if !vverbose then begin let dv = Zident.S.elements dv in let di = Zident.S.elements di in let der = Zident.S.elements der in let nv = Zident.S.elements nv in let mv = Zident.S.elements mv in open_box 0; if dv <> [] then fprintf ff "@[<v 0>(* dv = {@[%a@]} *)@ @]" (print_list_r name "" "," "") dv; if di <> [] then fprintf ff "@[<v 0>(* di = {@[%a@]} *)@ @]" (print_list_r name "" "," "") di; if der <> [] then fprintf ff "@[<v 0>(* der = {@[%a@]} *)@ @]" (print_list_r name "" "," "") der; if nv <> [] then fprintf ff "@[<v 0>(* next = {@[%a@]} *)@ @]" (print_list_r name "" "," "") nv; if mv <> [] then fprintf ff "@[<v 0>(* der = {@[%a@]} *)@ @]" (print_list_r name "" "," "") mv; close_box () end let print_eq_info ff { eq_write = w; eq_safe = s; eq_index = i } = print_writes ff w print a block surrounded by two braces [ po ] and [ pf ] let block locals body po pf ff { b_vars = vardec_list; b_locals = l; b_body = b; b_write = w; b_env = n_env } = fprintf ff "@[<hov 0>@[%a@]@[%a@]@[%a@]@[%a@]@[%a@]@]" print_vardec_list vardec_list print_writes w print_env n_env locals l (body po pf) b let match_handler body ff { m_pat = pat; m_body = b; m_env = env; m_reset = r; m_zero = z } = fprintf ff "@[<hov 4>| %a -> %s%s@,%a%a@]" pattern pat (if r then "(* reset *)" else "") (if z then "(* zero *)" else "") print_env env body b let present_handler scondpat body ff { p_cond = scpat; p_body = b; p_env = env } = fprintf ff "@[<hov4>| (%a) ->@ @[<v 0>%a%a@]@]" scondpat scpat print_env env body b let period expression ff { p_phase = opt_phase; p_period = p } = match opt_phase with | None -> fprintf ff "@[(%a)@]" expression p | Some(phase) -> fprintf ff "@[(%a|%a)@]" expression phase expression p let rec expression ff e = if Deftypes.is_no_typ e.e_typ && !vverbose then fprintf ff "@[(* %a *)@]" Ptypes.output e.e_typ; match e.e_desc with | Elocal n -> name ff n | Eglobal { lname = ln } -> longname ff ln | Eop(op, e_list) -> operator ff op e_list | Elast x -> fprintf ff "last %a" name x | Econstr0(ln) -> longname ff ln | Econst c -> immediate ff c | Eapp({ app_inline = i; app_statefull = r }, e, e_list) -> fprintf ff "@[(%s%s%a %a)@]" (if i then "inline " else "") (if r then "run " else "") expression e (print_list_r expression "" "" "") e_list | Econstr1(ln, e_list) -> fprintf ff "@[%a%a@]" longname ln (print_list_r expression "("","")") e_list | Etuple(e_list) -> fprintf ff "@[%a@]" (print_list_r expression "("","")") e_list | Erecord_access(e, field) -> fprintf ff "@[%a.%a@]" expression e longname field | Erecord(ln_e_list) -> print_record (print_couple longname expression """ =""") ff ln_e_list | Erecord_with(e, ln_e_list) -> fprintf ff "@[{ %a with %a }@]" expression e (print_list_r (print_couple longname expression """ =""") "" ";" "") ln_e_list | Elet(l, e) -> fprintf ff "@[<v 0>%a@ %a@]" local l expression e | Eblock(b, e) -> fprintf ff "@[<v 0>%a in@ %a@]" (block_equation_list "do " "") b expression e | Etypeconstraint(e, typ) -> fprintf ff "@[(%a: %a)@]" expression e ptype typ | Eseq(e1, e2) -> fprintf ff "@[%a;@,%a@]" expression e1 expression e2 | Eperiod(p) -> fprintf ff "@[period %a@]" (period expression) p | Ematch(total, e, match_handler_list) -> fprintf ff "@[<v>@[<hov 2>%smatch %a with@ @[%a@]@]@]" (if !total then "total " else "") expression e (print_list_l (match_handler expression) """""") match_handler_list | Epresent(present_handler_list, opt_e) -> fprintf ff "@[<v>@[<hov 2>present@ @[%a@]@]@ @[%a@]@]" (print_list_l (present_handler scondpat expression) """""") present_handler_list (print_opt2 expression "else ") opt_e and operator ff op e_list = match op, e_list with | Eunarypre, [e] -> fprintf ff "pre %a" expression e | Efby, [e1;e2] -> fprintf ff "%a fby %a" expression e1 expression e2 | Eminusgreater, [e1;e2] -> fprintf ff "%a -> %a" expression e1 expression e2 | Eifthenelse,[e1;e2;e3] -> fprintf ff "@[(if %a then %a@ else %a)@]" expression e1 expression e2 expression e3 | Eup, [e] -> fprintf ff "up %a" expression e | Etest, [e] -> fprintf ff "? %a" expression e | Edisc, [e] -> fprintf ff "disc %a" expression e | Ehorizon, [e] -> fprintf ff "@[horizon@ @[%a@]@]" expression e | Einitial, [] -> fprintf ff "init" | Eaccess, [e1; e2] -> fprintf ff "@[%a.(%a)@]" expression e1 expression e2 | Eupdate, [e1; i; e2] -> fprintf ff "@[{%a with@ (%a) = %a}@]" expression e1 expression i expression e2 | Eatomic, [e] -> fprintf ff "atomic %a" expression e | _ -> assert false and equation ff ({ eq_desc = desc } as eq) = print_eq_info ff eq; match desc with | EQeq(p, e) -> fprintf ff "@[<hov 2>%a =@ %a@]" pattern p expression e | EQder(n, e, e0_opt, []) -> fprintf ff "@[<hov 2>der %a =@ %a %a@]" name n expression e (optional_unit (fun ff e -> fprintf ff "init %a " expression e)) e0_opt | EQder(n, e, e0_opt, present_handler_list) -> fprintf ff "@[<hov 2>der %a =@ %a %a@ @[<hov 2>reset@ @[%a@]@]@]" name n expression e (optional_unit (fun ff e -> fprintf ff "init %a " expression e)) e0_opt (print_list_l (present_handler scondpat expression) """""") present_handler_list | EQinit(n, e0) -> fprintf ff "@[<hov2>init %a =@ %a@]" name n expression e0 | EQpluseq(n, e) -> fprintf ff "@[<hov2>%a +=@ %a@]" name n expression e | EQnext(n, e, None) -> fprintf ff "@[<hov 2>next %a =@ %a@]" name n expression e | EQnext(n, e, Some(e0)) -> fprintf ff "@[<hov2>next %a =@ @[%a@ init %a@]@]" name n expression e expression e0 | EQautomaton(is_weak, s_h_list, e_opt) -> fprintf ff "@[<hov0>automaton%s@ @[%a@]@,%a@]" (if is_weak then "(* weak *)" else "(* strong *)") (state_handler_list is_weak) s_h_list (print_opt (print_with_braces state " init" "")) e_opt | EQmatch(total, e, match_handler_list) -> fprintf ff "@[<hov0>%smatch %a with@ @[%a@]@]" (if !total then "total " else "") expression e (print_list_l (match_handler (block_equation_list "do " " done")) """""") match_handler_list | EQpresent(present_handler_list, None) -> fprintf ff "@[<hov0>present@ @[%a@]@]" (print_list_l (present_handler scondpat (block_equation_list "do " " done")) """""") present_handler_list | EQpresent(present_handler_list, Some(b)) -> fprintf ff "@[<hov0>present@ @[%a@]@ else @[%a@]@]" (print_list_l (present_handler scondpat (block_equation_list "do " " done")) """""") present_handler_list (block_equation_list "do " " done") b | EQreset(eq_list, e) -> fprintf ff "@[<hov2>reset@ @[%a@]@ @[<hov 2>every@ %a@]@]" (equation_list "" "") eq_list expression e | EQemit(n, opt_e) -> begin match opt_e with | None -> fprintf ff "@[emit %a@]" name n | Some(e) -> fprintf ff "@[emit %a = %a@]" name n expression e end | EQblock(b_eq_list) -> block_equation_list "do " " done" ff b_eq_list | EQand(and_eq_list) -> print_list_l equation "do " "and " " done" ff and_eq_list | EQbefore(before_eq_list) -> print_list_l equation "" "before " "" ff before_eq_list | EQforall { for_index = i_list; for_init = init_list; for_body = b_eq_list; for_in_env = in_env; for_out_env = out_env } -> let index ff { desc = desc } = match desc with | Einput(i, e) -> fprintf ff "@[%a in %a@]" name i expression e | Eoutput(i, j) -> fprintf ff "@[%a out %a@]" name i name j | Eindex(i, e1, e2) -> fprintf ff "@[%a in %a .. %a@]" name i expression e1 expression e2 in let init ff { desc = desc } = match desc with | Einit_last(i, e) -> fprintf ff "@[last %a = %a@]" name i expression e in fprintf ff "@[<hov 2>forall %a@,@[<v>%a@,%a@,%a@ \ @[<v 1>initialize@ @[<v>%a@]@]@ done @]@]" (print_list_r index "" "," "") i_list print_env in_env print_env out_env (block_equation_list "do " "") b_eq_list (print_list_l init "" "and " "") init_list and block_equation_list po pf ff b = block locals equation_list po pf ff b and equation_list po pf ff eq_list = match eq_list with | [] -> fprintf ff "%s%s" po pf | [eq] -> equation ff eq | _ -> print_list_l equation po "and " pf ff eq_list and state_handler_list is_weak ff s_h_list = print_list_l (state_handler is_weak) """""" ff s_h_list and state_handler is_weak ff { s_state = s; s_body = b; s_trans = trans; s_env = env } = let print ff trans = if trans = [] then fprintf ff "done" else print_list_r escape (if is_weak then "until " else "unless ") "" "" ff trans in fprintf ff "@[<v 4>| %a ->@ %a@[<v>%a@,%a@]@]" statepat s print_env env (block_equation_list "do " "") b print trans and escape ff { e_cond = scpat; e_reset = r; e_block = b_opt; e_next_state = ns; e_env = env } = match b_opt with | None -> fprintf ff "@[<v4>| %a %a%s@ %a@]" scondpat scpat print_env env (if r then "then" else "continue") state ns | Some(b) -> fprintf ff "@[<v4>| %a %a%s@ %a in %a@]" scondpat scpat print_env env (if r then "then" else "continue") (block_equation_list "do " "") b state ns and scondpat ff scpat = match scpat.desc with | Econdand(scpat1, scpat2) -> fprintf ff "@[%a &@ %a@]" scondpat scpat1 scondpat scpat2 | Econdor(scpat1, scpat2) -> fprintf ff "@[%a |@ %a@]" scondpat scpat1 scondpat scpat2 | Econdexp(e) -> expression ff e | Econdpat(e, pat) -> fprintf ff "%a(%a)" expression e pattern pat | Econdon(scpat1, e) -> fprintf ff "@[%a on@ %a@]" scondpat scpat1 expression e and statepat ff spat = match spat.desc with | Estate0pat(n) -> name ff n | Estate1pat(n, n_list) -> fprintf ff "%a%a" name n (print_list_r name "("","")") n_list and state ff se = match se.desc with | Estate0(n) -> name ff n | Estate1(n, e_list) -> fprintf ff "%a%a" name n (print_list_r expression "("","")") e_list and locals ff l = if l <> [] then fprintf ff "@[%a@]" (print_list_l local """""") l and local ff { l_rec = is_rec; l_eq = eq_list; l_env = env } = let s = if is_rec then "rec " else "" in fprintf ff "@[<v 0>%alet %a@]" print_env env (equation_list s " in") eq_list let constr_decl ff { desc = desc } = match desc with | Econstr0decl(n) -> fprintf ff "%s" n | Econstr1decl(n, ty_list) -> fprintf ff "@[%s of %a@]" n (print_list_l ptype "(" "* " ")") ty_list let type_decl ff { desc = desc } = match desc with | Eabstract_type -> () | Eabbrev(ty) -> fprintf ff " = %a" ptype ty | Evariant_type(constr_decl_list) -> fprintf ff " = %a" (print_list_l constr_decl "" "|" "") constr_decl_list | Erecord_type(n_ty_list) -> fprintf ff " = %a" (print_record (print_couple shortname ptype """ :""")) n_ty_list Debug printer for ( Zident.t * ) . State.t let state_ident_typ = let fprint_v ff (id, ty) = fprintf ff "@[%a:%a@]" Zident.fprint_t id Ptypes.output ty in Zmisc.State.fprint_t fprint_v (* Debug printer for Hybrid.eq Zmisc.State.t *) let state_eq = Zmisc.State.fprint_t equation let open_module ff n = fprintf ff "@[open "; shortname ff n; fprintf ff "@.@]" let funexp ff { f_kind = k; f_args = p_list; f_body = e; f_env = env } = fprintf ff "@[<v 2>%s %a . @ %a%a@]" (match k with | S -> "sfun" | A -> "fun" | AD -> "dfun" | AS -> "asfun" | D -> "node" | C -> "hybrid" | P -> "proba") (pattern_list "" "" "") p_list print_env env expression e let implementation ff impl = match impl.desc with | Eopen(n) -> open_module ff n | Etypedecl(n, params, ty_decl) -> fprintf ff "@[<v 2>type %a%s %a@.@.@]" Ptypes.print_type_params params n type_decl ty_decl | Econstdecl(n, is_static, e) -> fprintf ff "@[<v 2>let %s%a =@ %a@.@.@]" (if is_static then "static " else "") shortname n expression e | Efundecl(n, body) -> fprintf ff "@[<v 2>let %a =@ %a@.@]" shortname n funexp body let implementation_list ff imp_list = List.iter (implementation ff) imp_list let interface ff inter = match inter.desc with | Einter_open(n) -> open_module ff n | Einter_typedecl(n, params, ty_decl) -> fprintf ff "@[<v 2>type %a%s %a@.@.@]" Ptypes.print_type_params params n type_decl ty_decl | Einter_constdecl(n, ty) -> fprintf ff "@[<v 2>val %a : %a@.@.@]" shortname n ptype ty let interface_list ff int_list = List.iter (interface ff) int_list (* Print a value from the global environment *) let rec print_value_code ff { value_exp = ve; value_name = vn } = match vn with | None -> print_value ff ve | Some(qual) -> Format.fprintf ff "@[{%a is %a}@]" print_value ve qualident qual and print_value ff ve = match ve with | Vconst(i) -> immediate ff i | Vconstr0(qual) -> qualident ff qual | Vconstr1(qual, vc_list) -> fprintf ff "@[%a%a@]" qualident qual (print_list_r print_value_code "("","")") vc_list | Vtuple(vc_list) -> fprintf ff "@[%a@]" (print_list_r print_value_code "("","")") vc_list | Vrecord(ln_vc_list) -> print_record (print_couple qualident print_value_code """ =""") ff ln_vc_list | Vperiod(p) -> fprintf ff "@[period %a@]" (period print_value_code) p | Vfun(body, venv) -> fprintf ff "@[<hov0><%a,@,%a>@]" funexp body (Zident.Env.fprint_t print_value_code) venv | Vabstract(qual) -> qualident ff qual
null
https://raw.githubusercontent.com/INRIA/zelus/685428574b0f9100ad5a41bbaa416cd7a2506d5e/compiler/global/printer.ml
ocaml
********************************************************************* Zelus, a synchronous language for hybrid systems Copyright Institut National de Recherche en Informatique et en LICENSE file). ******************************************************************** the printer Infix chars are surrounded by parenthesis fprintf ff "@[%a (* caus: %a Debug printer for Hybrid.eq Zmisc.State.t Print a value from the global environment
( c ) 2020 Paris ( see the file ) Automatique . All rights reserved . This file is distributed under the terms of the INRIA Non - Commercial License Agreement ( see the open Zlocation open Zmisc open Zelus open Deftypes open Ptypes open Global open Modules open Pp_tools open Format let no_op ff _ = () let is_infix = let module StrSet = Set.Make(String) in let set_infix = List.fold_right StrSet.add ["or"; "quo"; "mod"; "land"; "lor"; "lxor"; "lsl"; "lsr"; "asr"] StrSet.empty in fun s -> StrSet.mem s set_infix let parenthesis s = let c = String.get s 0 in if is_infix s then "(" ^ s ^ ")" else match c with | 'a' .. 'z' | 'A' .. 'Z' | '_' | '`' -> s | '*' -> "( " ^ s ^ " )" | _ -> if s = "()" then s else "(" ^ s ^ ")" let shortname ff s = fprintf ff "%s" (parenthesis s) let qualident ff { Lident.qual = m; Lident.id = s } = fprintf ff "%s.%s" m (parenthesis s) let longname ff ln = let ln = Initial.short (currentname ln) in match ln with | Lident.Name(m) -> shortname ff m | Lident.Modname(qual) -> qualident ff qual let name ff n = shortname ff (Zident.name n) let source_name ff n = shortname ff (Zident.source n) let immediate ff = function | Eint i -> fprintf ff "%d" i | Efloat f -> fprintf ff "%f" f | Ebool b -> if b then fprintf ff "true" else fprintf ff "false" | Estring s -> fprintf ff "%S" s | Echar c -> fprintf ff "'%c'" c | Evoid -> fprintf ff "()" let constant ff = function | Cimmediate(i) -> immediate ff i | Cglobal(ln) -> longname ff ln let print_opt_magic print ff = function | None -> pp_print_string ff "Obj.magic ()" | Some(e) -> print ff e let rec pattern ff ({ p_typ = ty; p_caus = caus_list } as pat) = let rec pattern ff pat = match pat.p_desc with | Evarpat(n) -> fprintf ff "@[(%a : %a)@]" name n Ptypes.output ty | Ewildpat -> fprintf ff "_" | Econstpat(im) -> immediate ff im | Econstr0pat(ln) -> longname ff ln | Econstr1pat(ln, pat_list) -> fprintf ff "@[%a%a@]" longname ln (pattern_list "(" "," ")") pat_list | Etuplepat(pat_list) -> pattern_list "(" "," ")" ff pat_list | Etypeconstraintpat(p, ty_exp) -> fprintf ff "@[(%a:%a)@]" pattern p ptype ty_exp | Erecordpat(n_pat_list) -> print_record (print_couple longname pattern """ =""") ff n_pat_list | Ealiaspat(p, n) -> fprintf ff "%a as %a" pattern p name n | Eorpat(pat1, pat2) -> fprintf ff "%a | %a" pattern pat1 pattern pat2 in pattern ff pat and pattern_list po sep pf ff pat_list = fprintf ff "@[%a@]" (print_list_r pattern po sep pf) pat_list and ptype ff ty = let operator = function Splus -> "+" | Sminus -> "-" in let priority = function Splus -> 0 | Sminus -> 1 in let rec psize prio ff { desc = desc } = match desc with | Sconst(i) -> fprintf ff "%d" i | Sglobal(ln) -> longname ff ln | Sname(n) -> name ff n | Sop(op, e1, e2) -> let prio_op = priority op in if prio > prio_op then fprintf ff "("; fprintf ff "@[%a %s %a@]" (psize prio_op) e1 (operator op) (psize prio_op) e2; if prio > prio_op then fprintf ff ")" in match ty.desc with | Etypevar(s) -> fprintf ff "'%s" s | Etypeconstr(ln, ty_list) -> fprintf ff "@[<hov2>%a@]%a" (print_list_r_empty ptype "("","")") ty_list longname ln | Etypetuple(ty_list) -> fprintf ff "@[<hov2>%a@]" (print_list_r ptype "(""*"")") ty_list | Etypefun(k, n_opt, ty_arg, ty_res) -> let pas ff (n_opt, ty_arg) = match n_opt with | None -> () | Some(n) -> fprintf ff "(%a : %a)" name n ptype ty_arg in let s = match k with | S -> "-S->" | A -> "-A->" | AD -> "-AD->" | D -> "-D->" | C -> "-C->" | AS -> "-AS->" | P -> "~D~>" in fprintf ff "@[<hov2>%a %s %a@]" pas (n_opt, ty_arg) s ptype ty_res | Etypevec(ty_arg, size) -> fprintf ff "@[%a[%a]@]" ptype ty_arg (psize 0) size let default ff = function | Init(v) -> fprintf ff " init %a" constant v | Default(v) -> fprintf ff " default %a" constant v let combine ff v = fprintf ff " with %a" longname v let print_vardec_list ff vardec_list = let vardec ff { vardec_name = n; vardec_default = d_opt; vardec_combine = c_opt } = fprintf ff "@[%a%a%a@]" name n (Zmisc.optional_unit default) d_opt (Zmisc.optional_unit combine) c_opt in if vardec_list <> [] then fprintf ff "@[<v 2>%a@ @]" (print_list_r vardec "local " "," "") vardec_list let kind k = match k with | Cont -> "cont" | Zero -> "zero" | Period -> "period" | Horizon -> "horizon" | Encore -> "encore" | Major -> "major" let print_binding ff (n, { t_sort = sort; t_typ = typ }) = let default ff v = fprintf ff " default %a" constant v in let combine ff v = fprintf ff " with %a" longname v in let init ff i_opt = match i_opt with | Noinit -> () | InitEq -> fprintf ff " init" | InitDecl(c) -> fprintf ff " init %a" constant c in let next ff is_n = fprintf ff "%s" (if is_n then "next " else "cur ") in let previous p = if p then "last " else "" in let kind ff k = fprintf ff "%s" (kind k) in match sort with | Sstatic -> fprintf ff "@[static %a: %a@,@]" name n Ptypes.output typ | Sval -> fprintf ff "@[val %a: %a@,@]" name n Ptypes.output typ | Svar { v_combine = c_opt; v_default = d_opt } -> fprintf ff "@[var %a: %a%a%a@,@]" name n Ptypes.output typ (Zmisc.optional_unit default) d_opt (Zmisc.optional_unit combine) c_opt | Smem { m_kind = k; m_next = n_opt; m_previous = p; m_init = i_opt; m_combine = c_opt } -> fprintf ff "@[%a%s%a mem %a: %a%a%a@,@]" (Zmisc.optional_unit next) n_opt (previous p) (Zmisc.optional_unit kind) k name n Ptypes.output typ init i_opt (Zmisc.optional_unit combine) c_opt let print_env ff env = if !vverbose then begin let env = Zident.Env.bindings env in if env <> [] then fprintf ff "@[<v 0>(* defs: %a *)@,@]" (print_list_r print_binding """;""") env end let print_writes ff { dv = dv; di = di; der = der; nv = nv; mv = mv } = if !vverbose then begin let dv = Zident.S.elements dv in let di = Zident.S.elements di in let der = Zident.S.elements der in let nv = Zident.S.elements nv in let mv = Zident.S.elements mv in open_box 0; if dv <> [] then fprintf ff "@[<v 0>(* dv = {@[%a@]} *)@ @]" (print_list_r name "" "," "") dv; if di <> [] then fprintf ff "@[<v 0>(* di = {@[%a@]} *)@ @]" (print_list_r name "" "," "") di; if der <> [] then fprintf ff "@[<v 0>(* der = {@[%a@]} *)@ @]" (print_list_r name "" "," "") der; if nv <> [] then fprintf ff "@[<v 0>(* next = {@[%a@]} *)@ @]" (print_list_r name "" "," "") nv; if mv <> [] then fprintf ff "@[<v 0>(* der = {@[%a@]} *)@ @]" (print_list_r name "" "," "") mv; close_box () end let print_eq_info ff { eq_write = w; eq_safe = s; eq_index = i } = print_writes ff w print a block surrounded by two braces [ po ] and [ pf ] let block locals body po pf ff { b_vars = vardec_list; b_locals = l; b_body = b; b_write = w; b_env = n_env } = fprintf ff "@[<hov 0>@[%a@]@[%a@]@[%a@]@[%a@]@[%a@]@]" print_vardec_list vardec_list print_writes w print_env n_env locals l (body po pf) b let match_handler body ff { m_pat = pat; m_body = b; m_env = env; m_reset = r; m_zero = z } = fprintf ff "@[<hov 4>| %a -> %s%s@,%a%a@]" pattern pat (if r then "(* reset *)" else "") (if z then "(* zero *)" else "") print_env env body b let present_handler scondpat body ff { p_cond = scpat; p_body = b; p_env = env } = fprintf ff "@[<hov4>| (%a) ->@ @[<v 0>%a%a@]@]" scondpat scpat print_env env body b let period expression ff { p_phase = opt_phase; p_period = p } = match opt_phase with | None -> fprintf ff "@[(%a)@]" expression p | Some(phase) -> fprintf ff "@[(%a|%a)@]" expression phase expression p let rec expression ff e = if Deftypes.is_no_typ e.e_typ && !vverbose then fprintf ff "@[(* %a *)@]" Ptypes.output e.e_typ; match e.e_desc with | Elocal n -> name ff n | Eglobal { lname = ln } -> longname ff ln | Eop(op, e_list) -> operator ff op e_list | Elast x -> fprintf ff "last %a" name x | Econstr0(ln) -> longname ff ln | Econst c -> immediate ff c | Eapp({ app_inline = i; app_statefull = r }, e, e_list) -> fprintf ff "@[(%s%s%a %a)@]" (if i then "inline " else "") (if r then "run " else "") expression e (print_list_r expression "" "" "") e_list | Econstr1(ln, e_list) -> fprintf ff "@[%a%a@]" longname ln (print_list_r expression "("","")") e_list | Etuple(e_list) -> fprintf ff "@[%a@]" (print_list_r expression "("","")") e_list | Erecord_access(e, field) -> fprintf ff "@[%a.%a@]" expression e longname field | Erecord(ln_e_list) -> print_record (print_couple longname expression """ =""") ff ln_e_list | Erecord_with(e, ln_e_list) -> fprintf ff "@[{ %a with %a }@]" expression e (print_list_r (print_couple longname expression """ =""") "" ";" "") ln_e_list | Elet(l, e) -> fprintf ff "@[<v 0>%a@ %a@]" local l expression e | Eblock(b, e) -> fprintf ff "@[<v 0>%a in@ %a@]" (block_equation_list "do " "") b expression e | Etypeconstraint(e, typ) -> fprintf ff "@[(%a: %a)@]" expression e ptype typ | Eseq(e1, e2) -> fprintf ff "@[%a;@,%a@]" expression e1 expression e2 | Eperiod(p) -> fprintf ff "@[period %a@]" (period expression) p | Ematch(total, e, match_handler_list) -> fprintf ff "@[<v>@[<hov 2>%smatch %a with@ @[%a@]@]@]" (if !total then "total " else "") expression e (print_list_l (match_handler expression) """""") match_handler_list | Epresent(present_handler_list, opt_e) -> fprintf ff "@[<v>@[<hov 2>present@ @[%a@]@]@ @[%a@]@]" (print_list_l (present_handler scondpat expression) """""") present_handler_list (print_opt2 expression "else ") opt_e and operator ff op e_list = match op, e_list with | Eunarypre, [e] -> fprintf ff "pre %a" expression e | Efby, [e1;e2] -> fprintf ff "%a fby %a" expression e1 expression e2 | Eminusgreater, [e1;e2] -> fprintf ff "%a -> %a" expression e1 expression e2 | Eifthenelse,[e1;e2;e3] -> fprintf ff "@[(if %a then %a@ else %a)@]" expression e1 expression e2 expression e3 | Eup, [e] -> fprintf ff "up %a" expression e | Etest, [e] -> fprintf ff "? %a" expression e | Edisc, [e] -> fprintf ff "disc %a" expression e | Ehorizon, [e] -> fprintf ff "@[horizon@ @[%a@]@]" expression e | Einitial, [] -> fprintf ff "init" | Eaccess, [e1; e2] -> fprintf ff "@[%a.(%a)@]" expression e1 expression e2 | Eupdate, [e1; i; e2] -> fprintf ff "@[{%a with@ (%a) = %a}@]" expression e1 expression i expression e2 | Eatomic, [e] -> fprintf ff "atomic %a" expression e | _ -> assert false and equation ff ({ eq_desc = desc } as eq) = print_eq_info ff eq; match desc with | EQeq(p, e) -> fprintf ff "@[<hov 2>%a =@ %a@]" pattern p expression e | EQder(n, e, e0_opt, []) -> fprintf ff "@[<hov 2>der %a =@ %a %a@]" name n expression e (optional_unit (fun ff e -> fprintf ff "init %a " expression e)) e0_opt | EQder(n, e, e0_opt, present_handler_list) -> fprintf ff "@[<hov 2>der %a =@ %a %a@ @[<hov 2>reset@ @[%a@]@]@]" name n expression e (optional_unit (fun ff e -> fprintf ff "init %a " expression e)) e0_opt (print_list_l (present_handler scondpat expression) """""") present_handler_list | EQinit(n, e0) -> fprintf ff "@[<hov2>init %a =@ %a@]" name n expression e0 | EQpluseq(n, e) -> fprintf ff "@[<hov2>%a +=@ %a@]" name n expression e | EQnext(n, e, None) -> fprintf ff "@[<hov 2>next %a =@ %a@]" name n expression e | EQnext(n, e, Some(e0)) -> fprintf ff "@[<hov2>next %a =@ @[%a@ init %a@]@]" name n expression e expression e0 | EQautomaton(is_weak, s_h_list, e_opt) -> fprintf ff "@[<hov0>automaton%s@ @[%a@]@,%a@]" (if is_weak then "(* weak *)" else "(* strong *)") (state_handler_list is_weak) s_h_list (print_opt (print_with_braces state " init" "")) e_opt | EQmatch(total, e, match_handler_list) -> fprintf ff "@[<hov0>%smatch %a with@ @[%a@]@]" (if !total then "total " else "") expression e (print_list_l (match_handler (block_equation_list "do " " done")) """""") match_handler_list | EQpresent(present_handler_list, None) -> fprintf ff "@[<hov0>present@ @[%a@]@]" (print_list_l (present_handler scondpat (block_equation_list "do " " done")) """""") present_handler_list | EQpresent(present_handler_list, Some(b)) -> fprintf ff "@[<hov0>present@ @[%a@]@ else @[%a@]@]" (print_list_l (present_handler scondpat (block_equation_list "do " " done")) """""") present_handler_list (block_equation_list "do " " done") b | EQreset(eq_list, e) -> fprintf ff "@[<hov2>reset@ @[%a@]@ @[<hov 2>every@ %a@]@]" (equation_list "" "") eq_list expression e | EQemit(n, opt_e) -> begin match opt_e with | None -> fprintf ff "@[emit %a@]" name n | Some(e) -> fprintf ff "@[emit %a = %a@]" name n expression e end | EQblock(b_eq_list) -> block_equation_list "do " " done" ff b_eq_list | EQand(and_eq_list) -> print_list_l equation "do " "and " " done" ff and_eq_list | EQbefore(before_eq_list) -> print_list_l equation "" "before " "" ff before_eq_list | EQforall { for_index = i_list; for_init = init_list; for_body = b_eq_list; for_in_env = in_env; for_out_env = out_env } -> let index ff { desc = desc } = match desc with | Einput(i, e) -> fprintf ff "@[%a in %a@]" name i expression e | Eoutput(i, j) -> fprintf ff "@[%a out %a@]" name i name j | Eindex(i, e1, e2) -> fprintf ff "@[%a in %a .. %a@]" name i expression e1 expression e2 in let init ff { desc = desc } = match desc with | Einit_last(i, e) -> fprintf ff "@[last %a = %a@]" name i expression e in fprintf ff "@[<hov 2>forall %a@,@[<v>%a@,%a@,%a@ \ @[<v 1>initialize@ @[<v>%a@]@]@ done @]@]" (print_list_r index "" "," "") i_list print_env in_env print_env out_env (block_equation_list "do " "") b_eq_list (print_list_l init "" "and " "") init_list and block_equation_list po pf ff b = block locals equation_list po pf ff b and equation_list po pf ff eq_list = match eq_list with | [] -> fprintf ff "%s%s" po pf | [eq] -> equation ff eq | _ -> print_list_l equation po "and " pf ff eq_list and state_handler_list is_weak ff s_h_list = print_list_l (state_handler is_weak) """""" ff s_h_list and state_handler is_weak ff { s_state = s; s_body = b; s_trans = trans; s_env = env } = let print ff trans = if trans = [] then fprintf ff "done" else print_list_r escape (if is_weak then "until " else "unless ") "" "" ff trans in fprintf ff "@[<v 4>| %a ->@ %a@[<v>%a@,%a@]@]" statepat s print_env env (block_equation_list "do " "") b print trans and escape ff { e_cond = scpat; e_reset = r; e_block = b_opt; e_next_state = ns; e_env = env } = match b_opt with | None -> fprintf ff "@[<v4>| %a %a%s@ %a@]" scondpat scpat print_env env (if r then "then" else "continue") state ns | Some(b) -> fprintf ff "@[<v4>| %a %a%s@ %a in %a@]" scondpat scpat print_env env (if r then "then" else "continue") (block_equation_list "do " "") b state ns and scondpat ff scpat = match scpat.desc with | Econdand(scpat1, scpat2) -> fprintf ff "@[%a &@ %a@]" scondpat scpat1 scondpat scpat2 | Econdor(scpat1, scpat2) -> fprintf ff "@[%a |@ %a@]" scondpat scpat1 scondpat scpat2 | Econdexp(e) -> expression ff e | Econdpat(e, pat) -> fprintf ff "%a(%a)" expression e pattern pat | Econdon(scpat1, e) -> fprintf ff "@[%a on@ %a@]" scondpat scpat1 expression e and statepat ff spat = match spat.desc with | Estate0pat(n) -> name ff n | Estate1pat(n, n_list) -> fprintf ff "%a%a" name n (print_list_r name "("","")") n_list and state ff se = match se.desc with | Estate0(n) -> name ff n | Estate1(n, e_list) -> fprintf ff "%a%a" name n (print_list_r expression "("","")") e_list and locals ff l = if l <> [] then fprintf ff "@[%a@]" (print_list_l local """""") l and local ff { l_rec = is_rec; l_eq = eq_list; l_env = env } = let s = if is_rec then "rec " else "" in fprintf ff "@[<v 0>%alet %a@]" print_env env (equation_list s " in") eq_list let constr_decl ff { desc = desc } = match desc with | Econstr0decl(n) -> fprintf ff "%s" n | Econstr1decl(n, ty_list) -> fprintf ff "@[%s of %a@]" n (print_list_l ptype "(" "* " ")") ty_list let type_decl ff { desc = desc } = match desc with | Eabstract_type -> () | Eabbrev(ty) -> fprintf ff " = %a" ptype ty | Evariant_type(constr_decl_list) -> fprintf ff " = %a" (print_list_l constr_decl "" "|" "") constr_decl_list | Erecord_type(n_ty_list) -> fprintf ff " = %a" (print_record (print_couple shortname ptype """ :""")) n_ty_list Debug printer for ( Zident.t * ) . State.t let state_ident_typ = let fprint_v ff (id, ty) = fprintf ff "@[%a:%a@]" Zident.fprint_t id Ptypes.output ty in Zmisc.State.fprint_t fprint_v let state_eq = Zmisc.State.fprint_t equation let open_module ff n = fprintf ff "@[open "; shortname ff n; fprintf ff "@.@]" let funexp ff { f_kind = k; f_args = p_list; f_body = e; f_env = env } = fprintf ff "@[<v 2>%s %a . @ %a%a@]" (match k with | S -> "sfun" | A -> "fun" | AD -> "dfun" | AS -> "asfun" | D -> "node" | C -> "hybrid" | P -> "proba") (pattern_list "" "" "") p_list print_env env expression e let implementation ff impl = match impl.desc with | Eopen(n) -> open_module ff n | Etypedecl(n, params, ty_decl) -> fprintf ff "@[<v 2>type %a%s %a@.@.@]" Ptypes.print_type_params params n type_decl ty_decl | Econstdecl(n, is_static, e) -> fprintf ff "@[<v 2>let %s%a =@ %a@.@.@]" (if is_static then "static " else "") shortname n expression e | Efundecl(n, body) -> fprintf ff "@[<v 2>let %a =@ %a@.@]" shortname n funexp body let implementation_list ff imp_list = List.iter (implementation ff) imp_list let interface ff inter = match inter.desc with | Einter_open(n) -> open_module ff n | Einter_typedecl(n, params, ty_decl) -> fprintf ff "@[<v 2>type %a%s %a@.@.@]" Ptypes.print_type_params params n type_decl ty_decl | Einter_constdecl(n, ty) -> fprintf ff "@[<v 2>val %a : %a@.@.@]" shortname n ptype ty let interface_list ff int_list = List.iter (interface ff) int_list let rec print_value_code ff { value_exp = ve; value_name = vn } = match vn with | None -> print_value ff ve | Some(qual) -> Format.fprintf ff "@[{%a is %a}@]" print_value ve qualident qual and print_value ff ve = match ve with | Vconst(i) -> immediate ff i | Vconstr0(qual) -> qualident ff qual | Vconstr1(qual, vc_list) -> fprintf ff "@[%a%a@]" qualident qual (print_list_r print_value_code "("","")") vc_list | Vtuple(vc_list) -> fprintf ff "@[%a@]" (print_list_r print_value_code "("","")") vc_list | Vrecord(ln_vc_list) -> print_record (print_couple qualident print_value_code """ =""") ff ln_vc_list | Vperiod(p) -> fprintf ff "@[period %a@]" (period print_value_code) p | Vfun(body, venv) -> fprintf ff "@[<hov0><%a,@,%a>@]" funexp body (Zident.Env.fprint_t print_value_code) venv | Vabstract(qual) -> qualident ff qual
49447014099d322dee449e75415feeaf98e1ee0755d7d3d532ba98990515cd51
Gadjib/ocamlhomeworks
p2.ml
let string_n n = let s = ref "" in begin for i = 1 to n do s:=!s^"*"; done; !s; end ;; let main n = let s = ref "" in begin for i = 1 to n do s:=!s^(string_n n)^"\n"; done; !s; end; ;; print_string (main (read_int()));;
null
https://raw.githubusercontent.com/Gadjib/ocamlhomeworks/d5568d4830d4306ea56749f17af355bc35001eff/8%20%D0%BA%D0%BB%D0%B0%D1%81%D1%81/2019.04.03/p2.ml
ocaml
let string_n n = let s = ref "" in begin for i = 1 to n do s:=!s^"*"; done; !s; end ;; let main n = let s = ref "" in begin for i = 1 to n do s:=!s^(string_n n)^"\n"; done; !s; end; ;; print_string (main (read_int()));;
313f5915d0c6528b60c3cec49d6794dae7fc8aa8c09c514deaef9070343ee20f
semerdzhiev/fp-2020-21
04-filter.rkt
#lang racket (require rackunit) (require rackunit/text-ui) ; filter ; приема едноместен предикат и списък връща списък само с елементите на оригиналния , които изпълняват условието (define (filter p? ys) (void) ) (define tests (test-suite "filter" (check-equal? (filter even? '(1 2 3)) '(2)) (check-equal? (filter (lambda (x) (> x 200)) '(1 2 3)) '()) (check-equal? (filter (lambda (x) (or (= x 1) (= x 3))) '(1 2 3)) '(1 3)) ) ) (run-tests tests 'verbose)
null
https://raw.githubusercontent.com/semerdzhiev/fp-2020-21/64fa00c4f940f75a28cc5980275b124ca21244bc/group-b/exercises/05.more-lists/04-filter.rkt
racket
filter приема едноместен предикат и списък
#lang racket (require rackunit) (require rackunit/text-ui) връща списък само с елементите на оригиналния , които изпълняват условието (define (filter p? ys) (void) ) (define tests (test-suite "filter" (check-equal? (filter even? '(1 2 3)) '(2)) (check-equal? (filter (lambda (x) (> x 200)) '(1 2 3)) '()) (check-equal? (filter (lambda (x) (or (= x 1) (= x 3))) '(1 2 3)) '(1 3)) ) ) (run-tests tests 'verbose)
1fb0d27bfcfcd344423407615fd21aa1c1be29ecad5a93f071dd820a398bbf18
locusmath/locus
func.clj
(ns locus.set.mapping.function.indexing.func (:require [locus.set.logic.core.set :refer :all] [locus.set.logic.numeric.nms :refer :all] [locus.set.logic.structure.protocols :refer :all] [locus.set.mapping.general.core.object :refer :all] [locus.set.logic.limit.product :refer :all])) ; An indexing function is essentially just a presentation of an ordinary ; sequence like (a,b,c) as a function from a subset of the natural numbers ; to the value at the index in the list. This allows for lists and sequences ; to be treated like objects in the topos of functions, for example, when ; constructing subobject and congruence lattices. (deftype IndexingFunction [coll] ConcreteMorphism (inputs [this] (->Upto (count coll))) (outputs [this] (set coll)) AbstractMorphism (source-object [this] (inputs this)) (target-object [this] (outputs this)) ConcreteObject (underlying-set [this] (->CartesianCoproduct [(inputs this) (outputs this)])) clojure.lang.IFn (invoke [this i] (nth coll i)) (applyTo [this args] (clojure.lang.AFn/applyToHelper this args))) (derive IndexingFunction :locus.set.logic.structure.protocols/set-function) ; Constructor for indexing functions (defn indexing-function [coll] (IndexingFunction. coll)) ; Generalized conversion methods for indexing functions (defmulti to-indexing-function type) (defmethod to-indexing-function clojure.lang.Seqable [coll] (indexing-function (seq coll))) (defmethod to-indexing-function IndexingFunction [indexing-function] indexing-function) ; Ontology of indexing functions (defmulti indexing-function? type) (defmethod indexing-function? IndexingFunction [func] true) (defmethod indexing-function? :default [func] (and (set-function? func) (natural-range? (inputs func)))) (defn injective-indexing-function? [func] (and (injective? func) (indexing-function? func))) (defn constant-indexing-function? [func] (and (indexing-function? func) (constant-function? func)))
null
https://raw.githubusercontent.com/locusmath/locus/fb6068bd78977b51fd3c5783545a5f9986e4235c/src/clojure/locus/set/mapping/function/indexing/func.clj
clojure
An indexing function is essentially just a presentation of an ordinary sequence like (a,b,c) as a function from a subset of the natural numbers to the value at the index in the list. This allows for lists and sequences to be treated like objects in the topos of functions, for example, when constructing subobject and congruence lattices. Constructor for indexing functions Generalized conversion methods for indexing functions Ontology of indexing functions
(ns locus.set.mapping.function.indexing.func (:require [locus.set.logic.core.set :refer :all] [locus.set.logic.numeric.nms :refer :all] [locus.set.logic.structure.protocols :refer :all] [locus.set.mapping.general.core.object :refer :all] [locus.set.logic.limit.product :refer :all])) (deftype IndexingFunction [coll] ConcreteMorphism (inputs [this] (->Upto (count coll))) (outputs [this] (set coll)) AbstractMorphism (source-object [this] (inputs this)) (target-object [this] (outputs this)) ConcreteObject (underlying-set [this] (->CartesianCoproduct [(inputs this) (outputs this)])) clojure.lang.IFn (invoke [this i] (nth coll i)) (applyTo [this args] (clojure.lang.AFn/applyToHelper this args))) (derive IndexingFunction :locus.set.logic.structure.protocols/set-function) (defn indexing-function [coll] (IndexingFunction. coll)) (defmulti to-indexing-function type) (defmethod to-indexing-function clojure.lang.Seqable [coll] (indexing-function (seq coll))) (defmethod to-indexing-function IndexingFunction [indexing-function] indexing-function) (defmulti indexing-function? type) (defmethod indexing-function? IndexingFunction [func] true) (defmethod indexing-function? :default [func] (and (set-function? func) (natural-range? (inputs func)))) (defn injective-indexing-function? [func] (and (injective? func) (indexing-function? func))) (defn constant-indexing-function? [func] (and (indexing-function? func) (constant-function? func)))
5ffb1d3ffe242f3a662d281f5d840c8c50b55e9302bba7cc96aac44b9b212580
AndrasKovacs/ELTE-func-lang
Notes12.hs
# LANGUAGE InstanceSigs , DeriveFunctor , , DeriveTraversable # DeriveTraversable #-} import Data.Foldable import Data.Traversable import Control.Monad import Control.Applicative -- many, some isDigit : : Bool digitToInt : : Int import Debug.Trace -- trace :: String -> a -> a -- traceShow :: Show b => b -> a -> a import Control.Monad.State Következő canvas feladat : ismétlő kisfeladat -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- Canvas feladat data List a = Nil | Cons1 a (List a) | Cons2 a a (List a) deriving (Eq, Show) instance Functor List where fmap f Nil = Nil fmap f (Cons1 a as) = Cons1 (f a) (fmap f as) fmap f (Cons2 a1 a2 as) = Cons2 (f a1) (f a2) (fmap f as) instance Foldable List where -- egyiket definiáld foldr f b Nil = b foldr f b (Cons1 a as) = f a (foldr f b as) foldr f b (Cons2 a1 a2 as) = f a1 (f a2 (foldr f b as)) foldMap f Nil = mempty foldMap f (Cons1 a as) = f a <> foldMap f as foldMap f (Cons2 a1 a2 as) = f a1 <> f a2 <> foldMap f as instance Traversable List where traverse f Nil = pure Nil traverse f (Cons1 a as) = Cons1 <$> f a <*> traverse f as traverse f (Cons2 a1 a2 as) = Cons2 <$> f a1 <*> f a2 <*> traverse f as PARSER LIBRARY -------------------------------------------------------------------------------- newtype Parser a = Parser {runParser :: String -> Maybe (a, String)} deriving Functor instance Applicative Parser where pure = return (<*>) = ap instance Monad Parser where fogyaszt inputot return :: a -> Parser a return a = Parser $ \s -> Just (a, s) egymás után (>>=) :: Parser a -> (a -> Parser b) -> Parser b Parser f >>= g = Parser $ \s -> case f s of Nothing -> Nothing Just (a, s') -> runParser (g a) s' parserek közötti választás instance Alternative Parser where empty :: Parser a empty = Parser $ \_ -> Nothing (<|>) :: Parser a -> Parser a -> Parser a Parser f <|> Parser g = Parser $ \s -> case f s of Nothing -> g s x -> x -- üres String olvasása eof :: Parser () eof = Parser $ \s -> case s of [] -> Just ((), []) _ -> Nothing , satisfy :: (Char -> Bool) -> Parser Char satisfy f = Parser $ \s -> case s of c:s | f c -> Just (c, s) -- output String 1-el rövidebb! _ -> Nothing satisfy_ :: (Char -> Bool) -> Parser () satisfy_ f = () <$ satisfy f char :: Char -> Parser () char c = () <$ satisfy (==c) parser hívásakor kiír egy String üzenetet debug :: String -> Parser a -> Parser a debug msg pa = Parser $ \s -> trace (msg ++ " : " ++ s) (runParser pa s) bármilyen anyChar :: Parser Char anyChar = satisfy (\_ -> True) -- konkrét String-et próbál olvasni string :: String -> Parser () string = traverse_ char Control . Applicative - ból ( ): many : : a - > Parser [ a ] -- 0 - szor vagy többször olvasás some : : a - > Parser [ a ] -- 1 - szer vagy többször olvasás many_ :: Parser a -> Parser () many_ pa = some_ pa <|> pure () some_ :: Parser a -> Parser () some_ pa = pa >> many_ pa -- Functor/Applicative operátorok ( < $ ) kicserélni parser értékre -- (<$>) fmap ( < * ) két parser - t futtat , -- (*>) két parser-t futtat, a második értékét visszaadja -- whitespace elfogyasztása ws :: Parser () ws = many_ (char ' ') Olvassuk pa - t 0 - szor vagy többször , psep - el elválasztva sepBy :: Parser a -> Parser sep -> Parser [a] sepBy pa psep = sepBy1 pa psep <|> pure [] Olvassuk pa - t 1 - szor vagy többször , psep - el elválasztva sepBy1 :: Parser a -> Parser sep -> Parser [a] sepBy1 pa psep = (:) <$> pa <*> many (psep *> pa) -- egy számjegy olvasása digit :: Parser Int digit = digitToInt <$> satisfy isDigit topLevel :: Parser a -> Parser a topLevel pa = ws *> pa <* eof intLit' :: Parser Int intLit' = do isNeg <- (True <$ char '-') <|> pure False n <- read <$> some (satisfy isDigit) ws if isNeg then pure (n * (-1)) else pure n char' :: Char -> Parser () char' c = char c <* ws string' :: String -> Parser () string' str = string str <* ws min 1 pa olvasás , psep - el elválasztva , " combine " fv - el kombinálva balra asszociáltan infixLeft :: Parser a -> Parser sep -> (a -> a -> a) -> Parser a infixLeft pa psep combine = foldl1 combine <$> sepBy1 pa psep min 1 pa olvasás , psep - el elválasztva , " combine " fv - el kombinálva infixRight :: Parser a -> Parser sep -> (a -> a -> a) -> Parser a infixRight pa psep combine = foldr1 combine <$> sepBy1 pa psep infixNonAssoc :: Parser a -> Parser sep -> (a -> a -> a) -> Parser a infixNonAssoc pa psep combine = do exps <- sepBy1 pa psep case exps of 1 db pa kifejezés exp1 ` psep ` exp2 _ -> empty ( nyelv kifejezésekkel + állításokkal ) -------------------------------------------------------------------------------- Precedenciák : - literál ( bool / int ) , - * ( jobb ) - + ( jobb ) - = = ( ) Precedenciák: - literál (bool/int), zárójel - * (jobb asszoc) - + (jobb asszoc) - == (nem asszoc) -} data Exp = IntLit Int | BoolLit Bool | Add Exp Exp | Mul Exp Exp | Eq Exp Exp | Var String -- változónév deriving (Eq, Show) type Program = [Statement] data Statement = Assign String Exp -- x := exp | IfThenElse Exp Program Program -- if e1 then p1 else p2 end | While Exp Program -- while e do p end deriving (Eq, Show) legyen minden statement ; -vel elválasztva cél : Program - ot olvassunk keywords :: [String] keywords = ["if", "then", "else", "while", "do", "end"] keyword' :: String -> Parser () keyword' str = do string str x <- many (satisfy isLetter) <* ws case x of "" -> pure () _ -> empty ident' :: Parser String ident' = do x <- some (satisfy isLetter) <* ws if elem x keywords then empty else pure x -- kifejezések -------------------------------------------------------------------------------- atom :: Parser Exp atom = (IntLit <$> intLit') <|> (char' '(' *> eqExp <* char' ')') <|> (BoolLit <$> (True <$ keyword' "true")) <|> (BoolLit <$> (False <$ keyword' "false")) <|> (Var <$> ident') mulExp :: Parser Exp mulExp = infixRight atom (char' '*') Mul addExp :: Parser Exp addExp = infixRight mulExp (char' '+') Add eqExp :: Parser Exp eqExp = infixNonAssoc addExp (string' "==") Eq -- statement olvasás -------------------------------------------------------------------------------- pIf = keyword' "if" pThen = keyword' "then" pElse = keyword' "else" pWhile = keyword' "while" pDo = keyword' "do" pEnd = keyword' "end" nincs statement :: Parser Statement statement = (Assign <$> (ident' <* pAssign) <*> eqExp) <|> (IfThenElse <$> (pIf *> eqExp) <*> (pThen *> program) <*> (pElse *> program <* pEnd)) <|> (While <$> (pWhile *> eqExp <* pDo) <*> (program <* pEnd)) program :: Parser Program program = sepBy statement (char' ';') parseProgram :: Parser Program parseProgram = topLevel program példa p1 :: String p1 = unlines [ "x := 100;", "y := 1000;", "while x == 0 do", " y := y + 1", "end" ] -- Interpreter -------------------------------------------------------------------------------- -- értékek data Val = VInt Int | VBool Bool deriving (Eq, Show) -- környezet type Env = [(String, Val)] evalExp :: Env -> Exp -> Val evalExp env exp = case exp of IntLit n -> VInt n BoolLit b -> VBool b Add e1 e2 -> case (evalExp env e1, evalExp env e2) of (VInt n1, VInt n2) -> VInt (n1 + n2) _ -> error "type error" Mul e1 e2 -> case (evalExp env e1, evalExp env e2) of (VInt n1, VInt n2) -> VInt (n1 * n2) _ -> error "type error" Eq e1 e2 -> case (evalExp env e1, evalExp env e2) of (VInt n1, VInt n2) -> VBool (n1 == n2) (VBool b1, VBool b2) -> VBool (b1 == b2) _ -> error "type error" Var x -> case lookup x env of Nothing -> error $ "name not in scope: " ++ x Just v -> v updateEnv :: String -> Val -> Env -> Env updateEnv x v [] = [(x, v)] updateEnv x v ((x', v'):env) | x == x' = (x, v):env | otherwise = (x', v'): updateEnv x v env evalStatement :: Statement -> State Env () evalStatement st = case st of Assign x e -> do env <- get let v = evalExp env e put $ updateEnv x v env IfThenElse e p1 p2 -> do env <- get case evalExp env e of VBool b -> if b then evalProgram p1 else evalProgram p2 _ -> error "type error" While e p -> do env <- get case evalExp env e of VBool b -> if b then evalProgram p >> evalStatement (While e p) else pure () _ -> error "type error" evalProgram :: Program -> State Env () evalProgram = traverse_ evalStatement run :: String -> Env run str = case runParser parseProgram str of Nothing -> error "parse error" Just (p, _) -> execState (evalProgram p) [] -- Canvas feladat -------------------------------------------------------------------------------- atom : ( ) ( & & ): jobb ( || ): jobb data Exp2 = BoolLit2 Bool | And2 Exp2 Exp2 | Or2 Exp2 Exp2 deriving (Eq, Show) atom2 :: Parser Exp2 atom2 = (BoolLit2 True <$ string' "true") <|> (BoolLit2 False <$ string' "false") <|> (char' '(' *> orExp2 <* char' ')') andExp2 :: Parser Exp2 andExp2 = infixRight atom2 (string' "&&") And2 orExp2 :: Parser Exp2 orExp2 = infixRight andExp2 (string' "||") Or2 parseExp2 :: Parser Exp2 parseExp2 = topLevel orExp2 : extra műveletek a kifejezésekben -------------------------------------------------------------------------------- egészítsd ki a kifejezéseket a : -- And :: Exp -> Exp -> Exp -- Or :: Exp -> Exp -> Exp -- Not :: Exp -> Exp a parsert And , Or és Not olvasásával úgy , hogy a precedenciák a : - atom : literál , zárójelezés - not alkalmazás ( " not " kulcsszó után atom olvasása ) - * ( jobb ) - + ( jobb ) - & & ( jobb ) ( And ) - || ( jobb ) ( Or ) - = = ( ) - if e1 then e2 else e3 ( prefix ) - atom: literál, zárójelezés - not alkalmazás ("not" kulcsszó után atom olvasása) - * (jobb asszoc) - + (jobb asszoc) - && (jobb asszoc) (logikai And) - || (jobb asszoc) (logikai Or) - == (nem asszoc) - if e1 then e2 else e3 (prefix) -} Add az új ! : String literálok és String műveletek -------------------------------------------------------------------------------- a kifejezéseket a : -- StringLit :: String -> Exp -- Append :: Exp -> Exp -> Exp -- Head :: Exp -> Exp -- Tail :: Exp -> Exp -- Length :: Exp -> Exp a parser - t , a : - atom : Int / Bool / String literál , zárójelezés - " not " , " head " , " tail " , " length " alkalmazás ( kulcsszó után atom olvasása ) - * ( jobb ) - + ( jobb ) - & & ( jobb ) ( And ) - || ( jobb ) ( Or ) - + + ( jobb ) ( String összefűzés ) - = = ( ) - if e1 then e2 else e3 ( prefix ) - atom: Int/Bool/String literál, zárójelezés - "not", "head", "tail", "length" alkalmazás (kulcsszó után atom olvasása) - * (jobb asszoc) - + (jobb asszoc) - && (jobb asszoc) (logikai And) - || (jobb asszoc) (logikai Or) - ++ (jobb asszoc) (String összefűzés) - == (nem asszoc) - if e1 then e2 else e3 (prefix) -} A " head " , " tail " és " length " ! String literál : 0 vagy több tetszőleges nem ' " ' karakter olvasva , ' " ' karakter között . a ` Val ` definíciót String értékekkel ! is ! Az új , , típusú . --------------------------------------------------------------------------------
null
https://raw.githubusercontent.com/AndrasKovacs/ELTE-func-lang/41fc0127a81733007a54024d51f94d2964db3288/2021-22-1/gyak_1/Notes12.hs
haskell
many, some trace :: String -> a -> a traceShow :: Show b => b -> a -> a ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ Canvas feladat egyiket definiáld ------------------------------------------------------------------------------ üres String olvasása output String 1-el rövidebb! konkrét String-et próbál olvasni 0 - szor vagy többször olvasás 1 - szer vagy többször olvasás Functor/Applicative operátorok (<$>) fmap (*>) két parser-t futtat, a második értékét visszaadja whitespace elfogyasztása egy számjegy olvasása ------------------------------------------------------------------------------ változónév x := exp if e1 then p1 else p2 end while e do p end kifejezések ------------------------------------------------------------------------------ statement olvasás ------------------------------------------------------------------------------ Interpreter ------------------------------------------------------------------------------ értékek környezet Canvas feladat ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ And :: Exp -> Exp -> Exp Or :: Exp -> Exp -> Exp Not :: Exp -> Exp ------------------------------------------------------------------------------ StringLit :: String -> Exp Append :: Exp -> Exp -> Exp Head :: Exp -> Exp Tail :: Exp -> Exp Length :: Exp -> Exp ------------------------------------------------------------------------------
# LANGUAGE InstanceSigs , DeriveFunctor , , DeriveTraversable # DeriveTraversable #-} import Data.Foldable import Data.Traversable import Control.Monad isDigit : : Bool digitToInt : : Int import Control.Monad.State Következő canvas feladat : ismétlő kisfeladat data List a = Nil | Cons1 a (List a) | Cons2 a a (List a) deriving (Eq, Show) instance Functor List where fmap f Nil = Nil fmap f (Cons1 a as) = Cons1 (f a) (fmap f as) fmap f (Cons2 a1 a2 as) = Cons2 (f a1) (f a2) (fmap f as) instance Foldable List where foldr f b Nil = b foldr f b (Cons1 a as) = f a (foldr f b as) foldr f b (Cons2 a1 a2 as) = f a1 (f a2 (foldr f b as)) foldMap f Nil = mempty foldMap f (Cons1 a as) = f a <> foldMap f as foldMap f (Cons2 a1 a2 as) = f a1 <> f a2 <> foldMap f as instance Traversable List where traverse f Nil = pure Nil traverse f (Cons1 a as) = Cons1 <$> f a <*> traverse f as traverse f (Cons2 a1 a2 as) = Cons2 <$> f a1 <*> f a2 <*> traverse f as PARSER LIBRARY newtype Parser a = Parser {runParser :: String -> Maybe (a, String)} deriving Functor instance Applicative Parser where pure = return (<*>) = ap instance Monad Parser where fogyaszt inputot return :: a -> Parser a return a = Parser $ \s -> Just (a, s) egymás után (>>=) :: Parser a -> (a -> Parser b) -> Parser b Parser f >>= g = Parser $ \s -> case f s of Nothing -> Nothing Just (a, s') -> runParser (g a) s' parserek közötti választás instance Alternative Parser where empty :: Parser a empty = Parser $ \_ -> Nothing (<|>) :: Parser a -> Parser a -> Parser a Parser f <|> Parser g = Parser $ \s -> case f s of Nothing -> g s x -> x eof :: Parser () eof = Parser $ \s -> case s of [] -> Just ((), []) _ -> Nothing , satisfy :: (Char -> Bool) -> Parser Char satisfy f = Parser $ \s -> case s of _ -> Nothing satisfy_ :: (Char -> Bool) -> Parser () satisfy_ f = () <$ satisfy f char :: Char -> Parser () char c = () <$ satisfy (==c) parser hívásakor kiír egy String üzenetet debug :: String -> Parser a -> Parser a debug msg pa = Parser $ \s -> trace (msg ++ " : " ++ s) (runParser pa s) bármilyen anyChar :: Parser Char anyChar = satisfy (\_ -> True) string :: String -> Parser () string = traverse_ char Control . Applicative - ból ( ): many_ :: Parser a -> Parser () many_ pa = some_ pa <|> pure () some_ :: Parser a -> Parser () some_ pa = pa >> many_ pa ( < $ ) kicserélni parser értékre ( < * ) két parser - t futtat , ws :: Parser () ws = many_ (char ' ') Olvassuk pa - t 0 - szor vagy többször , psep - el elválasztva sepBy :: Parser a -> Parser sep -> Parser [a] sepBy pa psep = sepBy1 pa psep <|> pure [] Olvassuk pa - t 1 - szor vagy többször , psep - el elválasztva sepBy1 :: Parser a -> Parser sep -> Parser [a] sepBy1 pa psep = (:) <$> pa <*> many (psep *> pa) digit :: Parser Int digit = digitToInt <$> satisfy isDigit topLevel :: Parser a -> Parser a topLevel pa = ws *> pa <* eof intLit' :: Parser Int intLit' = do isNeg <- (True <$ char '-') <|> pure False n <- read <$> some (satisfy isDigit) ws if isNeg then pure (n * (-1)) else pure n char' :: Char -> Parser () char' c = char c <* ws string' :: String -> Parser () string' str = string str <* ws min 1 pa olvasás , psep - el elválasztva , " combine " fv - el kombinálva balra asszociáltan infixLeft :: Parser a -> Parser sep -> (a -> a -> a) -> Parser a infixLeft pa psep combine = foldl1 combine <$> sepBy1 pa psep min 1 pa olvasás , psep - el elválasztva , " combine " fv - el kombinálva infixRight :: Parser a -> Parser sep -> (a -> a -> a) -> Parser a infixRight pa psep combine = foldr1 combine <$> sepBy1 pa psep infixNonAssoc :: Parser a -> Parser sep -> (a -> a -> a) -> Parser a infixNonAssoc pa psep combine = do exps <- sepBy1 pa psep case exps of 1 db pa kifejezés exp1 ` psep ` exp2 _ -> empty ( nyelv kifejezésekkel + állításokkal ) Precedenciák : - literál ( bool / int ) , - * ( jobb ) - + ( jobb ) - = = ( ) Precedenciák: - literál (bool/int), zárójel - * (jobb asszoc) - + (jobb asszoc) - == (nem asszoc) -} data Exp = IntLit Int | BoolLit Bool | Add Exp Exp | Mul Exp Exp | Eq Exp Exp deriving (Eq, Show) type Program = [Statement] data Statement deriving (Eq, Show) legyen minden statement ; -vel elválasztva cél : Program - ot olvassunk keywords :: [String] keywords = ["if", "then", "else", "while", "do", "end"] keyword' :: String -> Parser () keyword' str = do string str x <- many (satisfy isLetter) <* ws case x of "" -> pure () _ -> empty ident' :: Parser String ident' = do x <- some (satisfy isLetter) <* ws if elem x keywords then empty else pure x atom :: Parser Exp atom = (IntLit <$> intLit') <|> (char' '(' *> eqExp <* char' ')') <|> (BoolLit <$> (True <$ keyword' "true")) <|> (BoolLit <$> (False <$ keyword' "false")) <|> (Var <$> ident') mulExp :: Parser Exp mulExp = infixRight atom (char' '*') Mul addExp :: Parser Exp addExp = infixRight mulExp (char' '+') Add eqExp :: Parser Exp eqExp = infixNonAssoc addExp (string' "==") Eq pIf = keyword' "if" pThen = keyword' "then" pElse = keyword' "else" pWhile = keyword' "while" pDo = keyword' "do" pEnd = keyword' "end" nincs statement :: Parser Statement statement = (Assign <$> (ident' <* pAssign) <*> eqExp) <|> (IfThenElse <$> (pIf *> eqExp) <*> (pThen *> program) <*> (pElse *> program <* pEnd)) <|> (While <$> (pWhile *> eqExp <* pDo) <*> (program <* pEnd)) program :: Parser Program program = sepBy statement (char' ';') parseProgram :: Parser Program parseProgram = topLevel program példa p1 :: String p1 = unlines [ "x := 100;", "y := 1000;", "while x == 0 do", " y := y + 1", "end" ] data Val = VInt Int | VBool Bool deriving (Eq, Show) type Env = [(String, Val)] evalExp :: Env -> Exp -> Val evalExp env exp = case exp of IntLit n -> VInt n BoolLit b -> VBool b Add e1 e2 -> case (evalExp env e1, evalExp env e2) of (VInt n1, VInt n2) -> VInt (n1 + n2) _ -> error "type error" Mul e1 e2 -> case (evalExp env e1, evalExp env e2) of (VInt n1, VInt n2) -> VInt (n1 * n2) _ -> error "type error" Eq e1 e2 -> case (evalExp env e1, evalExp env e2) of (VInt n1, VInt n2) -> VBool (n1 == n2) (VBool b1, VBool b2) -> VBool (b1 == b2) _ -> error "type error" Var x -> case lookup x env of Nothing -> error $ "name not in scope: " ++ x Just v -> v updateEnv :: String -> Val -> Env -> Env updateEnv x v [] = [(x, v)] updateEnv x v ((x', v'):env) | x == x' = (x, v):env | otherwise = (x', v'): updateEnv x v env evalStatement :: Statement -> State Env () evalStatement st = case st of Assign x e -> do env <- get let v = evalExp env e put $ updateEnv x v env IfThenElse e p1 p2 -> do env <- get case evalExp env e of VBool b -> if b then evalProgram p1 else evalProgram p2 _ -> error "type error" While e p -> do env <- get case evalExp env e of VBool b -> if b then evalProgram p >> evalStatement (While e p) else pure () _ -> error "type error" evalProgram :: Program -> State Env () evalProgram = traverse_ evalStatement run :: String -> Env run str = case runParser parseProgram str of Nothing -> error "parse error" Just (p, _) -> execState (evalProgram p) [] atom : ( ) ( & & ): jobb ( || ): jobb data Exp2 = BoolLit2 Bool | And2 Exp2 Exp2 | Or2 Exp2 Exp2 deriving (Eq, Show) atom2 :: Parser Exp2 atom2 = (BoolLit2 True <$ string' "true") <|> (BoolLit2 False <$ string' "false") <|> (char' '(' *> orExp2 <* char' ')') andExp2 :: Parser Exp2 andExp2 = infixRight atom2 (string' "&&") And2 orExp2 :: Parser Exp2 orExp2 = infixRight andExp2 (string' "||") Or2 parseExp2 :: Parser Exp2 parseExp2 = topLevel orExp2 : extra műveletek a kifejezésekben egészítsd ki a kifejezéseket a : a parsert And , Or és Not olvasásával úgy , hogy a precedenciák a : - atom : literál , zárójelezés - not alkalmazás ( " not " kulcsszó után atom olvasása ) - * ( jobb ) - + ( jobb ) - & & ( jobb ) ( And ) - || ( jobb ) ( Or ) - = = ( ) - if e1 then e2 else e3 ( prefix ) - atom: literál, zárójelezés - not alkalmazás ("not" kulcsszó után atom olvasása) - * (jobb asszoc) - + (jobb asszoc) - && (jobb asszoc) (logikai And) - || (jobb asszoc) (logikai Or) - == (nem asszoc) - if e1 then e2 else e3 (prefix) -} Add az új ! : String literálok és String műveletek a kifejezéseket a : a parser - t , a : - atom : Int / Bool / String literál , zárójelezés - " not " , " head " , " tail " , " length " alkalmazás ( kulcsszó után atom olvasása ) - * ( jobb ) - + ( jobb ) - & & ( jobb ) ( And ) - || ( jobb ) ( Or ) - + + ( jobb ) ( String összefűzés ) - = = ( ) - if e1 then e2 else e3 ( prefix ) - atom: Int/Bool/String literál, zárójelezés - "not", "head", "tail", "length" alkalmazás (kulcsszó után atom olvasása) - * (jobb asszoc) - + (jobb asszoc) - && (jobb asszoc) (logikai And) - || (jobb asszoc) (logikai Or) - ++ (jobb asszoc) (String összefűzés) - == (nem asszoc) - if e1 then e2 else e3 (prefix) -} A " head " , " tail " és " length " ! String literál : 0 vagy több tetszőleges nem ' " ' karakter olvasva , ' " ' karakter között . a ` Val ` definíciót String értékekkel ! is ! Az új , , típusú .
7ce9cf11b52f600385fd4fa430dfc301202974886e6e1fbfe0f9f8b1c35d4398
csabahruska/jhc-components
Type.hs
module FrontEnd.Tc.Type( Kind(..), KBase(..), MetaVar(..), MetaVarType(..), Pred(..), Preds(), Qual(..), Tycon(..), Type(..), Tyvar(..), kindStar, kindFunRet, kindUTuple, unfoldKind, fn, fromTAp, fromTArrow, module FrontEnd.Tc.Type, prettyPrintType, tForAll, tList, Constraint(..), Class(), Kindvar(..), tTTuple, tTTuple', tAp, tArrow, tyvar ) where import Control.Monad.Identity import Control.Monad.Writer import Data.IORef import Data.List import qualified Data.Map as Map import qualified Data.Set as S import Doc.DocLike import Doc.PPrint import FrontEnd.Representation import FrontEnd.SrcLoc import FrontEnd.Tc.Kind import Name.Name import Name.Names import Support.FreeVars import Support.Tickle type Sigma' = Sigma type Tau' = Tau type Rho' = Rho type Sigma = Type type Rho = Type type Tau = Type type SkolemTV = Tyvar type BoundTV = Tyvar type Preds = [Pred] data Constraint = Equality { constraintSrcLoc :: SrcLoc, constraintType1 :: Type, constraintType2 :: Type } instance HasLocation Constraint where srcLoc Equality { constraintSrcLoc = sl } = sl applyTyvarMap :: [(Tyvar,Type)] -> Type -> Type applyTyvarMap ts t = f initMp t where initMp = Map.fromList [ (tyvarName v,t) | (v,t) <- ts ] -- XXX name capture! f mp (TForAll as qt) = TForAll as (fq (foldr Map.delete mp (map tyvarName as)) qt) f mp (TExists as qt) = TExists as (fq (foldr Map.delete mp (map tyvarName as)) qt) f mp (TVar tv) = case Map.lookup (tyvarName tv) mp of Just t' -> t' Nothing -> (TVar tv) f mp t = tickle (f mp) t fq mp (ps :=> t) = map (tickle (f mp)) ps :=> f mp t applyTyvarMapQT :: [(Tyvar,Type)] -> Qual Type -> Qual Type applyTyvarMapQT ts qt = qt' where (TForAll [] qt') = applyTyvarMap ts (TForAll [] qt) typeOfType :: Type -> (MetaVarType,Bool) typeOfType TForAll { typeArgs = as, typeBody = _ :=> t } = (Sigma,isBoxy t) typeOfType t | isTau' t = (Tau,isBoxy t) typeOfType t = (Rho,isBoxy t) fromType :: Sigma -> ([Tyvar],[Pred],Type) fromType s = case s of TForAll as (ps :=> r) -> (as,ps,r) r -> ([],[],r) isTau :: Type -> Bool isTau TForAll {} = False isTau (TMetaVar MetaVar { metaType = t }) | t == Tau = True | otherwise = False isTau t = getAll $ tickleCollect (All . isTau) t isTau' :: Type -> Bool isTau' TForAll {} = False isTau' t = getAll $ tickleCollect (All . isTau') t isBoxy :: Type -> Bool isBoxy (TMetaVar MetaVar { metaType = t }) | t > Tau = True isBoxy t = getAny $ tickleCollect (Any . isBoxy) t isRho' :: Type -> Bool isRho' TForAll {} = False isRho' _ = True isRho :: Type -> Bool isRho r = isRho' r && not (isBoxy r) isBoxyMetaVar :: MetaVar -> Bool isBoxyMetaVar MetaVar { metaType = t } = t > Tau extractTyVar :: Monad m => Type -> m Tyvar extractTyVar (TVar tv) = return tv extractTyVar t = fail $ "not a Var:" ++ show t extractMetaVar :: Monad m => Type -> m MetaVar extractMetaVar (TMetaVar t) = return t extractMetaVar t = fail $ "not a metaTyVar:" ++ show t extractBox :: Monad m => Type -> m MetaVar extractBox (TMetaVar mv) | metaType mv > Tau = return mv extractBox t = fail $ "not a metaTyVar:" ++ show t newtype UnVarOpt = UnVarOpt { failEmptyMetaVar :: Bool } {-# SPECIALIZE flattenType :: MonadIO m => Type -> m Type #-} flattenType :: (MonadIO m, UnVar t) => t -> m t flattenType t = liftIO $ unVar' t class UnVar t where unVar' :: t -> IO t instance UnVar t => UnVar [t] where unVar' xs = mapM unVar' xs instance UnVar Pred where unVar' (IsIn c t) = IsIn c `liftM` unVar' t unVar' (IsEq t1 t2) = liftM2 IsEq (unVar' t1) (unVar' t2) instance (UnVar a,UnVar b) => UnVar (a,b) where unVar' (a,b) = do a <- unVar' a b <- unVar' b return (a,b) instance UnVar t => UnVar (Qual t) where unVar' (ps :=> t) = liftM2 (:=>) (unVar' ps) (unVar' t) instance UnVar Type where unVar' tv = do let ft (TForAll vs qt) = do qt' <- unVar' qt return $ TForAll vs qt' ft (TExists vs qt) = do qt' <- unVar' qt return $ TExists vs qt' ft (TAp (TAp (TCon arr) a1) a2) | tyconName arr == tc_Arrow = ft (TArrow a1 a2) ft t@(TMetaVar _) = return t ft t = tickleM (unVar' . (id :: Type -> Type)) t tv' <- findType tv ft tv' followTaus :: MonadIO m => Type -> m Type followTaus tv@(TMetaVar mv@MetaVar {metaRef = r }) | not (isBoxyMetaVar mv) = liftIO $ do rt <- readIORef r case rt of Nothing -> return tv Just t -> do t' <- followTaus t writeIORef r (Just t') return t' followTaus tv = return tv findType :: MonadIO m => Type -> m Type findType tv@(TMetaVar MetaVar {metaRef = r }) = liftIO $ do rt <- readIORef r case rt of Nothing -> return tv Just t -> do t' <- findType t writeIORef r (Just t') return t' findType tv = return tv readMetaVar :: MonadIO m => MetaVar -> m (Maybe Type) readMetaVar MetaVar { metaRef = r } = liftIO $ do rt <- readIORef r case rt of Nothing -> return Nothing Just t -> do t' <- findType t writeIORef r (Just t') return (Just t') freeMetaVars : : Type - > S.Set MetaVar freeMetaVars ( TMetaVar mv ) = S.singleton mv freeMetaVars t = tickleCollect freeMetaVars t freeMetaVars : : Type - > S.Set MetaVar freeMetaVars t = worker t S.empty where worker : : Type - > ( S.Set MetaVar - > S.Set MetaVar ) worker ( TMetaVar mv ) = S.insert mv worker ( TAp l r ) = worker l . worker r worker ( TArrow l r ) = worker l . worker r worker ( TAssoc c cas eas ) = foldr ( . ) i d ( map worker cas ) . foldr ( . ) i d ( map worker eas ) worker ( TForAll ta ( ps : = > t ) ) = foldr ( . ) i d ( map worker2 ps ) . worker t worker ( TExists ta ( ps : = > t ) ) = foldr ( . ) i d ( map worker2 ps ) . worker t worker _ = i d worker2 : : Pred - > ( S.Set MetaVar - > S.Set MetaVar ) worker2 ( IsIn c t ) = worker t worker2 ( IsEq t1 t2 ) = worker t1 . worker t2 freeMetaVars :: Type -> S.Set MetaVar freeMetaVars (TMetaVar mv) = S.singleton mv freeMetaVars t = tickleCollect freeMetaVars t freeMetaVars :: Type -> S.Set MetaVar freeMetaVars t = worker t S.empty where worker :: Type -> (S.Set MetaVar -> S.Set MetaVar) worker (TMetaVar mv) = S.insert mv worker (TAp l r) = worker l . worker r worker (TArrow l r) = worker l . worker r worker (TAssoc c cas eas) = foldr (.) id (map worker cas) . foldr (.) id (map worker eas) worker (TForAll ta (ps :=> t)) = foldr (.) id (map worker2 ps) . worker t worker (TExists ta (ps :=> t)) = foldr (.) id (map worker2 ps) . worker t worker _ = id worker2 :: Pred -> (S.Set MetaVar -> S.Set MetaVar) worker2 (IsIn c t) = worker t worker2 (IsEq t1 t2) = worker t1 . worker t2 -} freeMetaVars :: Type -> S.Set MetaVar freeMetaVars t = f t where f (TMetaVar mv) = S.singleton mv f (TAp l r) = f l `S.union` f r f (TArrow l r) = f l `S.union` f r f (TAssoc c cas eas) = S.unions (map f cas ++ map f eas) f (TForAll ta (ps :=> t)) = S.unions (f t:map f2 ps) f (TExists ta (ps :=> t)) = S.unions (f t:map f2 ps) f _ = S.empty f2 (IsIn c t) = f t f2 (IsEq t1 t2) = f t1 `S.union` f t2 instance FreeVars Type [Tyvar] where freeVars (TVar u) = [u] freeVars (TForAll vs qt) = freeVars qt Data.List.\\ vs freeVars (TExists vs qt) = freeVars qt Data.List.\\ vs freeVars t = foldr union [] $ tickleCollect ((:[]) . (freeVars :: Type -> [Tyvar])) t instance FreeVars Type [MetaVar] where freeVars t = S.toList $ freeMetaVars t instance FreeVars Type (S.Set MetaVar) where freeVars t = freeMetaVars t instance (FreeVars t b,FreeVars Pred b) => FreeVars (Qual t) b where freeVars (ps :=> t) = freeVars t `mappend` freeVars ps instance FreeVars Type b => FreeVars Pred b where freeVars (IsIn _c t) = freeVars t freeVars (IsEq t1 t2) = freeVars (t1,t2) instance Tickleable Type Pred where tickleM f (IsIn c t) = liftM (IsIn c) (f t) tickleM f (IsEq t1 t2) = liftM2 IsEq (f t1) (f t2) instance Tickleable Type Type where tickleM f (TAp l r) = liftM2 tAp (f l) (f r) tickleM f (TArrow l r) = liftM2 TArrow (f l) (f r) tickleM f (TAssoc c cas eas) = liftM2 (TAssoc c) (mapM f cas) (mapM f eas) tickleM f (TForAll ta (ps :=> t)) = do ps <- mapM (tickleM f) ps liftM (TForAll ta . (ps :=>)) (f t) tickleM f (TExists ta (ps :=> t)) = do ps <- mapM (tickleM f) ps liftM (TExists ta . (ps :=>)) (f t) tickleM _ t = return t data Rule = RuleSpec { ruleUniq :: (Module,Int), ruleName :: Name, ruleSuper :: Bool, ruleType :: Type } | RuleUser { ruleUniq :: (Module,Int), ruleFreeTVars :: [(Name,Kind)] } CTFun f = > \g . \y - > f ( g y ) data CoerceTerm = CTId | CTAp [Type] | CTAbs [Tyvar] | CTFun CoerceTerm | CTCompose CoerceTerm CoerceTerm instance Show CoerceTerm where showsPrec _ CTId = showString "id" showsPrec n (CTAp ts) = ptrans (n > 10) parens $ char '@' <+> hsep (map (parens . prettyPrintType) ts) showsPrec n (CTAbs ts) = ptrans (n > 10) parens $ char '\\' <+> hsep (map pprint ts) showsPrec n (CTFun ct) = ptrans (n > 10) parens $ text "->" <+> showsPrec 11 ct showsPrec n (CTCompose ct1 ct2) = ptrans (n > 10) parens $ (showsPrec 11 ct1) <+> char '.' <+> (showsPrec 11 ct2) -- | Apply the function if the 'Bool' is 'True'. ptrans :: Bool -> (a -> a) -> (a -> a) ptrans b f = if b then f else id instance Monoid CoerceTerm where mempty = CTId mappend = composeCoerce ctFun :: CoerceTerm -> CoerceTerm ctFun CTId = CTId ctFun x = CTFun x ctAbs :: [Tyvar] -> CoerceTerm ctAbs [] = CTId ctAbs xs = CTAbs xs ctAp :: [Type] -> CoerceTerm ctAp [] = CTId ctAp xs = CTAp xs ctId :: CoerceTerm ctId = CTId composeCoerce :: CoerceTerm -> CoerceTerm -> CoerceTerm composeCoerce ( CTFun a ) ( CTFun b ) = ctFun ( a ` composeCoerce ` b ) composeCoerce CTId x = x composeCoerce x CTId = x composeCoerce ( CTAbs ts ) ( CTAbs ts ' ) = CTAbs ( ts + + ts ' ) composeCoerce ( CTAp ts ) ( CTAp ts ' ) = CTAp ( ts + + ts ' ) composeCoerce ( CTAbs ts ) ( CTAp ts ' ) = f ts ts ' where f ( t : ts ) ( TVar t':ts ' ) | t = = t ' = f ts ts ' -- f [] [] = CTId f _ _ = CTCompose ( CTAbs ts ) ( CTAp ts ' ) composeCoerce x y = CTCompose x y instance UnVar Type => UnVar CoerceTerm where unVar' (CTAp ts) = CTAp `liftM` unVar' ts unVar' (CTFun ct) = CTFun `liftM` unVar' ct unVar' (CTCompose c1 c2) = liftM2 CTCompose (unVar' c1) (unVar' c2) unVar' x = return x
null
https://raw.githubusercontent.com/csabahruska/jhc-components/a7dace481d017f5a83fbfc062bdd2d099133adf1/jhc-frontend/src/FrontEnd/Tc/Type.hs
haskell
XXX name capture! # SPECIALIZE flattenType :: MonadIO m => Type -> m Type # | Apply the function if the 'Bool' is 'True'. f [] [] = CTId
module FrontEnd.Tc.Type( Kind(..), KBase(..), MetaVar(..), MetaVarType(..), Pred(..), Preds(), Qual(..), Tycon(..), Type(..), Tyvar(..), kindStar, kindFunRet, kindUTuple, unfoldKind, fn, fromTAp, fromTArrow, module FrontEnd.Tc.Type, prettyPrintType, tForAll, tList, Constraint(..), Class(), Kindvar(..), tTTuple, tTTuple', tAp, tArrow, tyvar ) where import Control.Monad.Identity import Control.Monad.Writer import Data.IORef import Data.List import qualified Data.Map as Map import qualified Data.Set as S import Doc.DocLike import Doc.PPrint import FrontEnd.Representation import FrontEnd.SrcLoc import FrontEnd.Tc.Kind import Name.Name import Name.Names import Support.FreeVars import Support.Tickle type Sigma' = Sigma type Tau' = Tau type Rho' = Rho type Sigma = Type type Rho = Type type Tau = Type type SkolemTV = Tyvar type BoundTV = Tyvar type Preds = [Pred] data Constraint = Equality { constraintSrcLoc :: SrcLoc, constraintType1 :: Type, constraintType2 :: Type } instance HasLocation Constraint where srcLoc Equality { constraintSrcLoc = sl } = sl applyTyvarMap :: [(Tyvar,Type)] -> Type -> Type applyTyvarMap ts t = f initMp t where initMp = Map.fromList [ (tyvarName v,t) | (v,t) <- ts ] f mp (TForAll as qt) = TForAll as (fq (foldr Map.delete mp (map tyvarName as)) qt) f mp (TExists as qt) = TExists as (fq (foldr Map.delete mp (map tyvarName as)) qt) f mp (TVar tv) = case Map.lookup (tyvarName tv) mp of Just t' -> t' Nothing -> (TVar tv) f mp t = tickle (f mp) t fq mp (ps :=> t) = map (tickle (f mp)) ps :=> f mp t applyTyvarMapQT :: [(Tyvar,Type)] -> Qual Type -> Qual Type applyTyvarMapQT ts qt = qt' where (TForAll [] qt') = applyTyvarMap ts (TForAll [] qt) typeOfType :: Type -> (MetaVarType,Bool) typeOfType TForAll { typeArgs = as, typeBody = _ :=> t } = (Sigma,isBoxy t) typeOfType t | isTau' t = (Tau,isBoxy t) typeOfType t = (Rho,isBoxy t) fromType :: Sigma -> ([Tyvar],[Pred],Type) fromType s = case s of TForAll as (ps :=> r) -> (as,ps,r) r -> ([],[],r) isTau :: Type -> Bool isTau TForAll {} = False isTau (TMetaVar MetaVar { metaType = t }) | t == Tau = True | otherwise = False isTau t = getAll $ tickleCollect (All . isTau) t isTau' :: Type -> Bool isTau' TForAll {} = False isTau' t = getAll $ tickleCollect (All . isTau') t isBoxy :: Type -> Bool isBoxy (TMetaVar MetaVar { metaType = t }) | t > Tau = True isBoxy t = getAny $ tickleCollect (Any . isBoxy) t isRho' :: Type -> Bool isRho' TForAll {} = False isRho' _ = True isRho :: Type -> Bool isRho r = isRho' r && not (isBoxy r) isBoxyMetaVar :: MetaVar -> Bool isBoxyMetaVar MetaVar { metaType = t } = t > Tau extractTyVar :: Monad m => Type -> m Tyvar extractTyVar (TVar tv) = return tv extractTyVar t = fail $ "not a Var:" ++ show t extractMetaVar :: Monad m => Type -> m MetaVar extractMetaVar (TMetaVar t) = return t extractMetaVar t = fail $ "not a metaTyVar:" ++ show t extractBox :: Monad m => Type -> m MetaVar extractBox (TMetaVar mv) | metaType mv > Tau = return mv extractBox t = fail $ "not a metaTyVar:" ++ show t newtype UnVarOpt = UnVarOpt { failEmptyMetaVar :: Bool } flattenType :: (MonadIO m, UnVar t) => t -> m t flattenType t = liftIO $ unVar' t class UnVar t where unVar' :: t -> IO t instance UnVar t => UnVar [t] where unVar' xs = mapM unVar' xs instance UnVar Pred where unVar' (IsIn c t) = IsIn c `liftM` unVar' t unVar' (IsEq t1 t2) = liftM2 IsEq (unVar' t1) (unVar' t2) instance (UnVar a,UnVar b) => UnVar (a,b) where unVar' (a,b) = do a <- unVar' a b <- unVar' b return (a,b) instance UnVar t => UnVar (Qual t) where unVar' (ps :=> t) = liftM2 (:=>) (unVar' ps) (unVar' t) instance UnVar Type where unVar' tv = do let ft (TForAll vs qt) = do qt' <- unVar' qt return $ TForAll vs qt' ft (TExists vs qt) = do qt' <- unVar' qt return $ TExists vs qt' ft (TAp (TAp (TCon arr) a1) a2) | tyconName arr == tc_Arrow = ft (TArrow a1 a2) ft t@(TMetaVar _) = return t ft t = tickleM (unVar' . (id :: Type -> Type)) t tv' <- findType tv ft tv' followTaus :: MonadIO m => Type -> m Type followTaus tv@(TMetaVar mv@MetaVar {metaRef = r }) | not (isBoxyMetaVar mv) = liftIO $ do rt <- readIORef r case rt of Nothing -> return tv Just t -> do t' <- followTaus t writeIORef r (Just t') return t' followTaus tv = return tv findType :: MonadIO m => Type -> m Type findType tv@(TMetaVar MetaVar {metaRef = r }) = liftIO $ do rt <- readIORef r case rt of Nothing -> return tv Just t -> do t' <- findType t writeIORef r (Just t') return t' findType tv = return tv readMetaVar :: MonadIO m => MetaVar -> m (Maybe Type) readMetaVar MetaVar { metaRef = r } = liftIO $ do rt <- readIORef r case rt of Nothing -> return Nothing Just t -> do t' <- findType t writeIORef r (Just t') return (Just t') freeMetaVars : : Type - > S.Set MetaVar freeMetaVars ( TMetaVar mv ) = S.singleton mv freeMetaVars t = tickleCollect freeMetaVars t freeMetaVars : : Type - > S.Set MetaVar freeMetaVars t = worker t S.empty where worker : : Type - > ( S.Set MetaVar - > S.Set MetaVar ) worker ( TMetaVar mv ) = S.insert mv worker ( TAp l r ) = worker l . worker r worker ( TArrow l r ) = worker l . worker r worker ( TAssoc c cas eas ) = foldr ( . ) i d ( map worker cas ) . foldr ( . ) i d ( map worker eas ) worker ( TForAll ta ( ps : = > t ) ) = foldr ( . ) i d ( map worker2 ps ) . worker t worker ( TExists ta ( ps : = > t ) ) = foldr ( . ) i d ( map worker2 ps ) . worker t worker _ = i d worker2 : : Pred - > ( S.Set MetaVar - > S.Set MetaVar ) worker2 ( IsIn c t ) = worker t worker2 ( IsEq t1 t2 ) = worker t1 . worker t2 freeMetaVars :: Type -> S.Set MetaVar freeMetaVars (TMetaVar mv) = S.singleton mv freeMetaVars t = tickleCollect freeMetaVars t freeMetaVars :: Type -> S.Set MetaVar freeMetaVars t = worker t S.empty where worker :: Type -> (S.Set MetaVar -> S.Set MetaVar) worker (TMetaVar mv) = S.insert mv worker (TAp l r) = worker l . worker r worker (TArrow l r) = worker l . worker r worker (TAssoc c cas eas) = foldr (.) id (map worker cas) . foldr (.) id (map worker eas) worker (TForAll ta (ps :=> t)) = foldr (.) id (map worker2 ps) . worker t worker (TExists ta (ps :=> t)) = foldr (.) id (map worker2 ps) . worker t worker _ = id worker2 :: Pred -> (S.Set MetaVar -> S.Set MetaVar) worker2 (IsIn c t) = worker t worker2 (IsEq t1 t2) = worker t1 . worker t2 -} freeMetaVars :: Type -> S.Set MetaVar freeMetaVars t = f t where f (TMetaVar mv) = S.singleton mv f (TAp l r) = f l `S.union` f r f (TArrow l r) = f l `S.union` f r f (TAssoc c cas eas) = S.unions (map f cas ++ map f eas) f (TForAll ta (ps :=> t)) = S.unions (f t:map f2 ps) f (TExists ta (ps :=> t)) = S.unions (f t:map f2 ps) f _ = S.empty f2 (IsIn c t) = f t f2 (IsEq t1 t2) = f t1 `S.union` f t2 instance FreeVars Type [Tyvar] where freeVars (TVar u) = [u] freeVars (TForAll vs qt) = freeVars qt Data.List.\\ vs freeVars (TExists vs qt) = freeVars qt Data.List.\\ vs freeVars t = foldr union [] $ tickleCollect ((:[]) . (freeVars :: Type -> [Tyvar])) t instance FreeVars Type [MetaVar] where freeVars t = S.toList $ freeMetaVars t instance FreeVars Type (S.Set MetaVar) where freeVars t = freeMetaVars t instance (FreeVars t b,FreeVars Pred b) => FreeVars (Qual t) b where freeVars (ps :=> t) = freeVars t `mappend` freeVars ps instance FreeVars Type b => FreeVars Pred b where freeVars (IsIn _c t) = freeVars t freeVars (IsEq t1 t2) = freeVars (t1,t2) instance Tickleable Type Pred where tickleM f (IsIn c t) = liftM (IsIn c) (f t) tickleM f (IsEq t1 t2) = liftM2 IsEq (f t1) (f t2) instance Tickleable Type Type where tickleM f (TAp l r) = liftM2 tAp (f l) (f r) tickleM f (TArrow l r) = liftM2 TArrow (f l) (f r) tickleM f (TAssoc c cas eas) = liftM2 (TAssoc c) (mapM f cas) (mapM f eas) tickleM f (TForAll ta (ps :=> t)) = do ps <- mapM (tickleM f) ps liftM (TForAll ta . (ps :=>)) (f t) tickleM f (TExists ta (ps :=> t)) = do ps <- mapM (tickleM f) ps liftM (TExists ta . (ps :=>)) (f t) tickleM _ t = return t data Rule = RuleSpec { ruleUniq :: (Module,Int), ruleName :: Name, ruleSuper :: Bool, ruleType :: Type } | RuleUser { ruleUniq :: (Module,Int), ruleFreeTVars :: [(Name,Kind)] } CTFun f = > \g . \y - > f ( g y ) data CoerceTerm = CTId | CTAp [Type] | CTAbs [Tyvar] | CTFun CoerceTerm | CTCompose CoerceTerm CoerceTerm instance Show CoerceTerm where showsPrec _ CTId = showString "id" showsPrec n (CTAp ts) = ptrans (n > 10) parens $ char '@' <+> hsep (map (parens . prettyPrintType) ts) showsPrec n (CTAbs ts) = ptrans (n > 10) parens $ char '\\' <+> hsep (map pprint ts) showsPrec n (CTFun ct) = ptrans (n > 10) parens $ text "->" <+> showsPrec 11 ct showsPrec n (CTCompose ct1 ct2) = ptrans (n > 10) parens $ (showsPrec 11 ct1) <+> char '.' <+> (showsPrec 11 ct2) ptrans :: Bool -> (a -> a) -> (a -> a) ptrans b f = if b then f else id instance Monoid CoerceTerm where mempty = CTId mappend = composeCoerce ctFun :: CoerceTerm -> CoerceTerm ctFun CTId = CTId ctFun x = CTFun x ctAbs :: [Tyvar] -> CoerceTerm ctAbs [] = CTId ctAbs xs = CTAbs xs ctAp :: [Type] -> CoerceTerm ctAp [] = CTId ctAp xs = CTAp xs ctId :: CoerceTerm ctId = CTId composeCoerce :: CoerceTerm -> CoerceTerm -> CoerceTerm composeCoerce ( CTFun a ) ( CTFun b ) = ctFun ( a ` composeCoerce ` b ) composeCoerce CTId x = x composeCoerce x CTId = x composeCoerce ( CTAbs ts ) ( CTAbs ts ' ) = CTAbs ( ts + + ts ' ) composeCoerce ( CTAp ts ) ( CTAp ts ' ) = CTAp ( ts + + ts ' ) composeCoerce ( CTAbs ts ) ( CTAp ts ' ) = f ts ts ' where f ( t : ts ) ( TVar t':ts ' ) | t = = t ' = f ts ts ' f _ _ = CTCompose ( CTAbs ts ) ( CTAp ts ' ) composeCoerce x y = CTCompose x y instance UnVar Type => UnVar CoerceTerm where unVar' (CTAp ts) = CTAp `liftM` unVar' ts unVar' (CTFun ct) = CTFun `liftM` unVar' ct unVar' (CTCompose c1 c2) = liftM2 CTCompose (unVar' c1) (unVar' c2) unVar' x = return x
c04adcc1490f5ea1417202f8854bf116a28a01f95f865c82870f3dccfd3160ce
GaloisInc/semmc
Extract.hs
# LANGUAGE FlexibleContexts # {-# LANGUAGE GADTs #-} # LANGUAGE PolyKinds # {-# LANGUAGE RankNTypes #-} # LANGUAGE ScopedTypeVariables # # LANGUAGE TypeApplications # module SemMC.Stochastic.Extract ( extractFormula ) where import qualified GHC.Err.Located as L import Control.Monad.Trans ( liftIO ) import qualified Data.Foldable as F import Data.Proxy ( Proxy(..) ) import qualified Data.Set as S import qualified Data.Parameterized.Classes as P import qualified Data.Parameterized.Context as Ctx import qualified Data.Parameterized.Map as MapF import Data.Parameterized.Pair ( Pair(..) ) import Data.Parameterized.Some ( Some(..) ) import Data.Parameterized.TraversableFC ( fmapFC, foldrFC, traverseFC ) import qualified Data.Parameterized.List as SL import qualified What4.Interface as C import What4.Protocol.Online (OnlineSolver) import qualified What4.Expr.Builder as SB import qualified Lang.Crucible.Backend as CB import qualified SemMC.Architecture as A import qualified SemMC.Architecture.Concrete as AC import qualified SemMC.Architecture.View as V import qualified SemMC.BoundVar as BV import qualified SemMC.Formula as F import qualified SemMC.Log as L import SemMC.Symbolic ( Sym ) import qualified SemMC.Util as U import SemMC.Stochastic.Monad import SemMC.Stochastic.IORelation ( IORelation(..), OperandRef(..) ) | Given a formula derived from a learned program ( ) , extract a -- 'F.ParameterizedFormula' that has holes for the given 'Opcode'. extractFormula :: forall arch t solver fs sh . (SynC arch, OnlineSolver solver) => AC.RegisterizedInstruction arch -> A.Opcode arch (A.Operand arch) sh -> SL.List (A.Operand arch) sh -> F.Formula (Sym t fs) arch -> IORelation arch sh -> Syn solver t fs arch (F.ParameterizedFormula (Sym t fs) arch sh) extractFormula ri opc ops progForm iorel = do L.logM L.Info ("Extracting formula from " ++ show progForm) go (MapF.empty, MapF.empty) (F.toList (outputs iorel)) where go (locDefs, locVars) [] = do extractedFormula <- makeFreshFormula locDefs locVars L.logM L.Info ("Fresh formula is " ++ show extractedFormula) pf0 <- parameterizeFormula ri opc ops extractedFormula renameVariables ops pf0 go acc (out:rest) = case out of ImplicitOperand (Some (V.View _ loc)) -> let Just expr = MapF.lookup loc (F.formDefs progForm) in go (defineLocation progForm loc expr acc) rest OperandRef (Some idx) -> do let operand = ops SL.!! idx Just loc = A.operandToLocation (Proxy @arch) operand Just expr = MapF.lookup loc (F.formDefs progForm) go (defineLocation progForm loc expr acc) rest -- | Take a pass through the formula to rename variables standing in for -- parameters into friendlier names. -- -- The names we get out of 'parameterizeFormula' are named after the concrete -- locations that were used in the candidate program discovered by the -- stochastic synthesis. This makes it difficult to visually distinguish -- between parameter values and implicit parameters. -- -- We only need to replace the bound vars in 'pfOperandVars' and then use the -- replaced list with 'S.replaceVars' to update 'pfDefs'. renameVariables :: forall arch sh t solver fs . (SynC arch, OnlineSolver solver) => SL.List (A.Operand arch) sh -> F.ParameterizedFormula (Sym t fs) arch sh -> Syn solver t fs arch (F.ParameterizedFormula (Sym t fs) arch sh) renameVariables oplist pf0 = do withSym $ \sym -> do (sva, opVars') <- liftIO (buildRenameList sym (F.pfOperandVars pf0)) defs' <- liftIO (MapF.traverseWithKey (doReplace sym sva) (F.pfDefs pf0)) return pf0 { F.pfOperandVars = opVars' , F.pfDefs = defs' } where doReplace sym sva _k v = F.replaceVars sym sva v buildRenameList :: Sym t fs -> SL.List (BV.BoundVar (Sym t fs) arch) sh -> IO (Pair (Ctx.Assignment (C.BoundVar (Sym t fs))) (Ctx.Assignment (C.SymExpr (Sym t fs))), SL.List (BV.BoundVar (Sym t fs) arch) sh) buildRenameList sym opVarList = do A shaped list with the same shape , but with pairs where the first is the original name and the second is the newly - allocated variable ( with -- a more sensible name) that will be used as a replacement. opVarListRenames <- SL.itraverse (allocateSensibleVariableName sym) opVarList varExprPairs <- traverseFC convertToVarExprPair opVarListRenames let sva = foldrFC addToAssignmentPair (Pair Ctx.empty Ctx.empty) varExprPairs return (sva, fmapFC secondVar opVarListRenames) allocateSensibleVariableName :: forall tp . Sym t fs -> SL.Index sh tp -> BV.BoundVar (Sym t fs) arch tp -> IO (VarPair (BV.BoundVar (Sym t fs) arch) (BV.BoundVar (Sym t fs) arch) tp) allocateSensibleVariableName sym ix bv = do let operand = oplist SL.!! ix fresh <- C.freshBoundVar sym (U.makeSymbol ("operand" ++ show (SL.indexValue ix))) (AC.operandType (Proxy @arch) operand) return (VarPair bv (BV.BoundVar fresh)) -- Given a correspondence between and old var and a new var, create a pair -- mapping the old pair to a new expr (which is just the new var wrapped into a SymExpr ) convertToVarExprPair :: forall tp . VarPair (BV.BoundVar (Sym t fs) arch) (BV.BoundVar (Sym t fs) arch) tp -> IO (VarPair (BV.BoundVar (Sym t fs) arch) (EltWrapper t arch) tp) convertToVarExprPair (VarPair oldVar (BV.BoundVar newVar)) = return $ VarPair oldVar (EltWrapper (SB.BoundVarExpr newVar)) addToAssignmentPair (VarPair (BV.BoundVar v) (EltWrapper e)) (Pair vars exprs) = Pair (Ctx.extend vars v) (Ctx.extend exprs e) newtype EltWrapper sym arch op = EltWrapper (SB.Expr sym (A.OperandType arch op)) data VarPair a b tp = VarPair (a tp) (b tp) secondVar :: VarPair a b tp -> b tp secondVar (VarPair _ v) = v -- | Given the components of a formula, allocate a set of fresh variables for -- each location and create a new formula. -- The intermediate f0 is invalid , but we use ' F.copyFormula ' to create a fresh -- set of bound variables that are unique. makeFreshFormula :: (AC.ConcreteArchitecture arch, OnlineSolver solver) => MapF.MapF (A.Location arch) (C.SymExpr (Sym t fs)) -> MapF.MapF (A.Location arch) (C.BoundVar (Sym t fs)) -> Syn solver t fs arch (F.Formula (Sym t fs) arch) makeFreshFormula exprs vars = withSym $ \sym -> do liftIO $ F.copyFormula sym F.Formula { F.formParamVars = vars , F.formDefs = exprs } -- | Collect the locations that we need to define this formula; we collect into a ' MapF.MapF ' instead of a ' ' so that we do n't have a very invalid -- formula lying around. defineLocation :: forall t fs arch tp . (AC.ConcreteArchitecture arch) => F.Formula (Sym t fs) arch -> A.Location arch tp -> SB.Expr t tp -> (MapF.MapF (A.Location arch) (C.SymExpr (Sym t fs)), MapF.MapF (A.Location arch) (C.BoundVar (Sym t fs))) -> (MapF.MapF (A.Location arch) (C.SymExpr (Sym t fs)), MapF.MapF (A.Location arch) (C.BoundVar (Sym t fs))) defineLocation frm loc expr (defs, vars) = (MapF.insert loc expr defs, collectVars frm expr vars) collectVars :: forall t fs tp arch . (C.TestEquality (C.BoundVar (Sym t fs)), P.OrdF (A.Location arch)) => F.Formula (Sym t fs) arch -> SB.Expr t tp -> MapF.MapF (A.Location arch) (C.BoundVar (Sym t fs)) -> MapF.MapF (A.Location arch) (C.BoundVar (Sym t fs)) collectVars frm expr m = MapF.union m neededVars where neededVars = U.extractUsedLocs (F.formParamVars frm) expr -- | Based on the iorelation, identify the inputs of the opcode (and the -- corresponding operands). For each input operand backed by a location, create a boundvar and substitute them for the corresponding expressions in formulas . -- -- For operands not backed by a location, we expect a corresponding index in the ' AC.RegisterizedInstruction ' , which will tell us the mapping to another -- location that represents the immediate. We can use the variable representing -- that location as the hole for the immediate. parameterizeFormula :: forall arch sh t solver fs . (AC.ConcreteArchitecture arch, OnlineSolver solver) => AC.RegisterizedInstruction arch -> A.Opcode arch (A.Operand arch) sh -> SL.List (A.Operand arch) sh -> F.Formula (Sym t fs) arch -> Syn solver t fs arch (F.ParameterizedFormula (Sym t fs) arch sh) parameterizeFormula { AC.riLiteralLocs = regLitLocs } opcode oplist f = do -- The pfLiteralVars are the parameters from the original formula not -- corresponding to any parameters let litVars = U.filterMapF (keepNonParams paramLocs) (F.formParamVars f) L.logM L.Info ("litVars = " ++ show litVars) let (nonParamDefs, paramDefs) = SL.ifoldr (replaceParameters (Proxy @arch)) (F.formDefs f, MapF.empty) oplist defs = MapF.foldrWithKey liftImplicitLocations paramDefs nonParamDefs L.logM L.Info ("nonParamDefs = " ++ show nonParamDefs) L.logM L.Info ("paramDefs = " ++ show paramDefs) L.logM L.Info ("defs = " ++ show defs) -- After we have extracted all of the necessary definitions of parameters, we have all of the formulas we actually care about . Next , we need to identify -- all of the variables in those formulas corresponding to explicit operands -- (pfOperandVars) and implicit operands (pfLiteralVars) -- -- FIXME: Do we need to allocate fresh vars when we do that? Probably not, -- since we copied 'f' when we created it. -- -- FIXME: Do we really need variables for output-only locations? It seems to -- produce formulas that reference useless variables opVars <- SL.itraverse (findVarForOperand opcode ri (F.formParamVars f)) oplist L.logM L.Info ("opVars = " ++ show opVars) -- Uses are: -- 1 ) All of the keys of ' pfDefs ' ( used as in defined here ) -- 2 ) The locations in ' pfLiteralVars ' -- 3 ) The typed indices of ' pfOperandVars ' let uses = collectUses oplist litVars defs return F.ParameterizedFormula { F.pfUses = uses , F.pfOperandVars = opVars , F.pfLiteralVars = litVars , F.pfDefs = defs } where Param locs needs to include registerization locations naturalParamLocs = foldrFC (collectParamLocs (Proxy @arch)) S.empty oplist registerizedParamLocs = S.fromList (MapF.elems regLitLocs) paramLocs = naturalParamLocs `S.union` registerizedParamLocs collectUses :: forall arch sh a b . (AC.ConcreteArchitecture arch) => SL.List (A.Operand arch) sh -> MapF.MapF (A.Location arch) a -> MapF.MapF (F.Parameter arch sh) b -> S.Set (Some (F.Parameter arch sh)) collectUses opVars litVars defs = S.unions [defUses, litUses, opUses] where defUses = MapF.foldrWithKey collectKeys S.empty defs litUses = MapF.foldrWithKey wrapLocations S.empty litVars opUses = SL.ifoldr wrapIndexes S.empty opVars collectKeys k _ = S.insert (Some k) wrapLocations loc _ = S.insert (Some (F.LiteralParameter loc)) wrapIndexes :: forall tp . SL.Index sh tp -> A.Operand arch tp -> S.Set (Some (F.Parameter arch sh)) -> S.Set (Some (F.Parameter arch sh)) wrapIndexes ix op = S.insert (Some (F.OperandParameter (AC.operandType (Proxy @arch) op) ix)) -- | Given an operand, find the 'BV.BoundVar' the represents it. -- For operands with ' A.Location 's ( e.g. , registers ) , this can be found in the given ' MapF.MapF ' . For operands without ' A.Location 's ( i.e. , immediates ) , we have to look up the corresponding mapping in the ' AC.RegisterizedInstruction ' -- that records which 'A.Location' is standing in for the immediate. findVarForOperand :: forall arch sh tp t solver fs . (AC.ConcreteArchitecture arch, OnlineSolver solver) => A.Opcode arch (A.Operand arch) sh -> AC.RegisterizedInstruction arch -> MapF.MapF (A.Location arch) (C.BoundVar (Sym t fs)) -> SL.Index sh tp -> A.Operand arch tp -> Syn solver t fs arch (BV.BoundVar (Sym t fs) arch tp) findVarForOperand opc (AC.RI { AC.riLiteralLocs = lls, AC.riOpcode = rop }) formulaBindings ix op | Just P.Refl <- P.testEquality rop opc = case A.operandToLocation (Proxy @arch) op of Just loc -> case MapF.lookup loc formulaBindings of Nothing -> do -- If we didn't find a variable for this binding, it is an output -- operand that is not used as an input at all. That is fine, but -- we need to allocate a fresh variable here for use in the -- parameterized formula. withSym $ \sym -> do BV.BoundVar <$> liftIO (C.freshBoundVar sym (U.makeSymbol (P.showF loc)) (A.locationType loc)) Just bv -> return (BV.BoundVar bv) Nothing -> do -- In this case, we are dealing with an immediate operand (since it -- doesn't have a location representation). We can find the corresponding location in the RegisterizedInstruction . case MapF.lookup (AC.LiteralRef ix) lls of Just loc -> case MapF.lookup loc formulaBindings of Just bv -> return (BV.BoundVar bv) Nothing -> L.error ("Expected a binding for location " ++ P.showF loc) Nothing -> L.error ("Expected a location mapping for operand at index " ++ show ix) | otherwise = L.error ("Unexpected opcode mismatch: " ++ P.showF opc ++ " vs " ++ P.showF rop) liftImplicitLocations :: (P.OrdF (A.Location arch)) => A.Location arch tp -> C.SymExpr (Sym t fs) tp -> MapF.MapF (F.Parameter arch sh) (C.SymExpr (Sym t fs)) -> MapF.MapF (F.Parameter arch sh) (C.SymExpr (Sym t fs)) liftImplicitLocations loc expr = MapF.insert (F.LiteralParameter loc) expr keepNonParams :: (P.OrdF f) => S.Set (Some f) -> f tp -> g tp -> Bool keepNonParams paramLocs loc _ = S.notMember (Some loc) paramLocs collectParamLocs :: (AC.ConcreteArchitecture arch) => proxy arch -> A.Operand arch tp -> S.Set (Some (A.Location arch)) -> S.Set (Some (A.Location arch)) collectParamLocs proxy op s = case AC.operandToSemanticView proxy op of Nothing -> s Just (V.SemanticView { V.semvView = V.View _ loc }) -> S.insert (Some loc) s -- | For locations referenced in an operand list *and* defined by a formula (the definitions of the formula are the first element of the pair ) , add them to a -- new map (suitable for a ParameterizedFormula). -- -- This just involves wrapping the location with an 'F.Operand' constructor. -- -- We remove the promoted locations from the original definition map, since we -- need to know which locations are left (they are handled by -- 'liftImplicitLocations'). -- FIXME : Do we need to pass in the IORelation so that we are sure we are only -- defining output registers? Or is that not a concern because we already used IORelations to limit the formula we are generalizing . replaceParameters :: (AC.ConcreteArchitecture arch) => proxy arch -> SL.Index sh tp -> A.Operand arch tp -> (MapF.MapF (A.Location arch) (C.SymExpr (Sym t fs)), MapF.MapF (F.Parameter arch sh) (C.SymExpr (Sym t fs))) -> (MapF.MapF (A.Location arch) (C.SymExpr (Sym t fs)), MapF.MapF (F.Parameter arch sh) (C.SymExpr (Sym t fs))) replaceParameters proxy ix op (defs, m) = case A.operandToLocation proxy op of Nothing -> (defs, m) Just loc -> case MapF.lookup loc defs of Nothing -> -- This lookup would fail on a purely input operand that had no -- definition in the final formula (defs, m) Just expr -> (MapF.delete loc defs, MapF.insert (F.OperandParameter (A.locationType loc) ix) expr m)
null
https://raw.githubusercontent.com/GaloisInc/semmc/3d9bc90f92a7f7ef59ff4943369dea9c0eb4b3ae/semmc-learning/src/SemMC/Stochastic/Extract.hs
haskell
# LANGUAGE GADTs # # LANGUAGE RankNTypes # 'F.ParameterizedFormula' that has holes for the given 'Opcode'. | Take a pass through the formula to rename variables standing in for parameters into friendlier names. The names we get out of 'parameterizeFormula' are named after the concrete locations that were used in the candidate program discovered by the stochastic synthesis. This makes it difficult to visually distinguish between parameter values and implicit parameters. We only need to replace the bound vars in 'pfOperandVars' and then use the replaced list with 'S.replaceVars' to update 'pfDefs'. a more sensible name) that will be used as a replacement. Given a correspondence between and old var and a new var, create a pair mapping the old pair to a new expr (which is just the new var wrapped | Given the components of a formula, allocate a set of fresh variables for each location and create a new formula. set of bound variables that are unique. | Collect the locations that we need to define this formula; we collect into formula lying around. | Based on the iorelation, identify the inputs of the opcode (and the corresponding operands). For each input operand backed by a location, create For operands not backed by a location, we expect a corresponding index in the location that represents the immediate. We can use the variable representing that location as the hole for the immediate. The pfLiteralVars are the parameters from the original formula not corresponding to any parameters After we have extracted all of the necessary definitions of parameters, we all of the variables in those formulas corresponding to explicit operands (pfOperandVars) and implicit operands (pfLiteralVars) FIXME: Do we need to allocate fresh vars when we do that? Probably not, since we copied 'f' when we created it. FIXME: Do we really need variables for output-only locations? It seems to produce formulas that reference useless variables Uses are: | Given an operand, find the 'BV.BoundVar' the represents it. that records which 'A.Location' is standing in for the immediate. If we didn't find a variable for this binding, it is an output operand that is not used as an input at all. That is fine, but we need to allocate a fresh variable here for use in the parameterized formula. In this case, we are dealing with an immediate operand (since it doesn't have a location representation). We can find the corresponding | For locations referenced in an operand list *and* defined by a formula (the new map (suitable for a ParameterizedFormula). This just involves wrapping the location with an 'F.Operand' constructor. We remove the promoted locations from the original definition map, since we need to know which locations are left (they are handled by 'liftImplicitLocations'). defining output registers? Or is that not a concern because we already used This lookup would fail on a purely input operand that had no definition in the final formula
# LANGUAGE FlexibleContexts # # LANGUAGE PolyKinds # # LANGUAGE ScopedTypeVariables # # LANGUAGE TypeApplications # module SemMC.Stochastic.Extract ( extractFormula ) where import qualified GHC.Err.Located as L import Control.Monad.Trans ( liftIO ) import qualified Data.Foldable as F import Data.Proxy ( Proxy(..) ) import qualified Data.Set as S import qualified Data.Parameterized.Classes as P import qualified Data.Parameterized.Context as Ctx import qualified Data.Parameterized.Map as MapF import Data.Parameterized.Pair ( Pair(..) ) import Data.Parameterized.Some ( Some(..) ) import Data.Parameterized.TraversableFC ( fmapFC, foldrFC, traverseFC ) import qualified Data.Parameterized.List as SL import qualified What4.Interface as C import What4.Protocol.Online (OnlineSolver) import qualified What4.Expr.Builder as SB import qualified Lang.Crucible.Backend as CB import qualified SemMC.Architecture as A import qualified SemMC.Architecture.Concrete as AC import qualified SemMC.Architecture.View as V import qualified SemMC.BoundVar as BV import qualified SemMC.Formula as F import qualified SemMC.Log as L import SemMC.Symbolic ( Sym ) import qualified SemMC.Util as U import SemMC.Stochastic.Monad import SemMC.Stochastic.IORelation ( IORelation(..), OperandRef(..) ) | Given a formula derived from a learned program ( ) , extract a extractFormula :: forall arch t solver fs sh . (SynC arch, OnlineSolver solver) => AC.RegisterizedInstruction arch -> A.Opcode arch (A.Operand arch) sh -> SL.List (A.Operand arch) sh -> F.Formula (Sym t fs) arch -> IORelation arch sh -> Syn solver t fs arch (F.ParameterizedFormula (Sym t fs) arch sh) extractFormula ri opc ops progForm iorel = do L.logM L.Info ("Extracting formula from " ++ show progForm) go (MapF.empty, MapF.empty) (F.toList (outputs iorel)) where go (locDefs, locVars) [] = do extractedFormula <- makeFreshFormula locDefs locVars L.logM L.Info ("Fresh formula is " ++ show extractedFormula) pf0 <- parameterizeFormula ri opc ops extractedFormula renameVariables ops pf0 go acc (out:rest) = case out of ImplicitOperand (Some (V.View _ loc)) -> let Just expr = MapF.lookup loc (F.formDefs progForm) in go (defineLocation progForm loc expr acc) rest OperandRef (Some idx) -> do let operand = ops SL.!! idx Just loc = A.operandToLocation (Proxy @arch) operand Just expr = MapF.lookup loc (F.formDefs progForm) go (defineLocation progForm loc expr acc) rest renameVariables :: forall arch sh t solver fs . (SynC arch, OnlineSolver solver) => SL.List (A.Operand arch) sh -> F.ParameterizedFormula (Sym t fs) arch sh -> Syn solver t fs arch (F.ParameterizedFormula (Sym t fs) arch sh) renameVariables oplist pf0 = do withSym $ \sym -> do (sva, opVars') <- liftIO (buildRenameList sym (F.pfOperandVars pf0)) defs' <- liftIO (MapF.traverseWithKey (doReplace sym sva) (F.pfDefs pf0)) return pf0 { F.pfOperandVars = opVars' , F.pfDefs = defs' } where doReplace sym sva _k v = F.replaceVars sym sva v buildRenameList :: Sym t fs -> SL.List (BV.BoundVar (Sym t fs) arch) sh -> IO (Pair (Ctx.Assignment (C.BoundVar (Sym t fs))) (Ctx.Assignment (C.SymExpr (Sym t fs))), SL.List (BV.BoundVar (Sym t fs) arch) sh) buildRenameList sym opVarList = do A shaped list with the same shape , but with pairs where the first is the original name and the second is the newly - allocated variable ( with opVarListRenames <- SL.itraverse (allocateSensibleVariableName sym) opVarList varExprPairs <- traverseFC convertToVarExprPair opVarListRenames let sva = foldrFC addToAssignmentPair (Pair Ctx.empty Ctx.empty) varExprPairs return (sva, fmapFC secondVar opVarListRenames) allocateSensibleVariableName :: forall tp . Sym t fs -> SL.Index sh tp -> BV.BoundVar (Sym t fs) arch tp -> IO (VarPair (BV.BoundVar (Sym t fs) arch) (BV.BoundVar (Sym t fs) arch) tp) allocateSensibleVariableName sym ix bv = do let operand = oplist SL.!! ix fresh <- C.freshBoundVar sym (U.makeSymbol ("operand" ++ show (SL.indexValue ix))) (AC.operandType (Proxy @arch) operand) return (VarPair bv (BV.BoundVar fresh)) into a SymExpr ) convertToVarExprPair :: forall tp . VarPair (BV.BoundVar (Sym t fs) arch) (BV.BoundVar (Sym t fs) arch) tp -> IO (VarPair (BV.BoundVar (Sym t fs) arch) (EltWrapper t arch) tp) convertToVarExprPair (VarPair oldVar (BV.BoundVar newVar)) = return $ VarPair oldVar (EltWrapper (SB.BoundVarExpr newVar)) addToAssignmentPair (VarPair (BV.BoundVar v) (EltWrapper e)) (Pair vars exprs) = Pair (Ctx.extend vars v) (Ctx.extend exprs e) newtype EltWrapper sym arch op = EltWrapper (SB.Expr sym (A.OperandType arch op)) data VarPair a b tp = VarPair (a tp) (b tp) secondVar :: VarPair a b tp -> b tp secondVar (VarPair _ v) = v The intermediate f0 is invalid , but we use ' F.copyFormula ' to create a fresh makeFreshFormula :: (AC.ConcreteArchitecture arch, OnlineSolver solver) => MapF.MapF (A.Location arch) (C.SymExpr (Sym t fs)) -> MapF.MapF (A.Location arch) (C.BoundVar (Sym t fs)) -> Syn solver t fs arch (F.Formula (Sym t fs) arch) makeFreshFormula exprs vars = withSym $ \sym -> do liftIO $ F.copyFormula sym F.Formula { F.formParamVars = vars , F.formDefs = exprs } a ' MapF.MapF ' instead of a ' ' so that we do n't have a very invalid defineLocation :: forall t fs arch tp . (AC.ConcreteArchitecture arch) => F.Formula (Sym t fs) arch -> A.Location arch tp -> SB.Expr t tp -> (MapF.MapF (A.Location arch) (C.SymExpr (Sym t fs)), MapF.MapF (A.Location arch) (C.BoundVar (Sym t fs))) -> (MapF.MapF (A.Location arch) (C.SymExpr (Sym t fs)), MapF.MapF (A.Location arch) (C.BoundVar (Sym t fs))) defineLocation frm loc expr (defs, vars) = (MapF.insert loc expr defs, collectVars frm expr vars) collectVars :: forall t fs tp arch . (C.TestEquality (C.BoundVar (Sym t fs)), P.OrdF (A.Location arch)) => F.Formula (Sym t fs) arch -> SB.Expr t tp -> MapF.MapF (A.Location arch) (C.BoundVar (Sym t fs)) -> MapF.MapF (A.Location arch) (C.BoundVar (Sym t fs)) collectVars frm expr m = MapF.union m neededVars where neededVars = U.extractUsedLocs (F.formParamVars frm) expr a boundvar and substitute them for the corresponding expressions in formulas . ' AC.RegisterizedInstruction ' , which will tell us the mapping to another parameterizeFormula :: forall arch sh t solver fs . (AC.ConcreteArchitecture arch, OnlineSolver solver) => AC.RegisterizedInstruction arch -> A.Opcode arch (A.Operand arch) sh -> SL.List (A.Operand arch) sh -> F.Formula (Sym t fs) arch -> Syn solver t fs arch (F.ParameterizedFormula (Sym t fs) arch sh) parameterizeFormula { AC.riLiteralLocs = regLitLocs } opcode oplist f = do let litVars = U.filterMapF (keepNonParams paramLocs) (F.formParamVars f) L.logM L.Info ("litVars = " ++ show litVars) let (nonParamDefs, paramDefs) = SL.ifoldr (replaceParameters (Proxy @arch)) (F.formDefs f, MapF.empty) oplist defs = MapF.foldrWithKey liftImplicitLocations paramDefs nonParamDefs L.logM L.Info ("nonParamDefs = " ++ show nonParamDefs) L.logM L.Info ("paramDefs = " ++ show paramDefs) L.logM L.Info ("defs = " ++ show defs) have all of the formulas we actually care about . Next , we need to identify opVars <- SL.itraverse (findVarForOperand opcode ri (F.formParamVars f)) oplist L.logM L.Info ("opVars = " ++ show opVars) 1 ) All of the keys of ' pfDefs ' ( used as in defined here ) 2 ) The locations in ' pfLiteralVars ' 3 ) The typed indices of ' pfOperandVars ' let uses = collectUses oplist litVars defs return F.ParameterizedFormula { F.pfUses = uses , F.pfOperandVars = opVars , F.pfLiteralVars = litVars , F.pfDefs = defs } where Param locs needs to include registerization locations naturalParamLocs = foldrFC (collectParamLocs (Proxy @arch)) S.empty oplist registerizedParamLocs = S.fromList (MapF.elems regLitLocs) paramLocs = naturalParamLocs `S.union` registerizedParamLocs collectUses :: forall arch sh a b . (AC.ConcreteArchitecture arch) => SL.List (A.Operand arch) sh -> MapF.MapF (A.Location arch) a -> MapF.MapF (F.Parameter arch sh) b -> S.Set (Some (F.Parameter arch sh)) collectUses opVars litVars defs = S.unions [defUses, litUses, opUses] where defUses = MapF.foldrWithKey collectKeys S.empty defs litUses = MapF.foldrWithKey wrapLocations S.empty litVars opUses = SL.ifoldr wrapIndexes S.empty opVars collectKeys k _ = S.insert (Some k) wrapLocations loc _ = S.insert (Some (F.LiteralParameter loc)) wrapIndexes :: forall tp . SL.Index sh tp -> A.Operand arch tp -> S.Set (Some (F.Parameter arch sh)) -> S.Set (Some (F.Parameter arch sh)) wrapIndexes ix op = S.insert (Some (F.OperandParameter (AC.operandType (Proxy @arch) op) ix)) For operands with ' A.Location 's ( e.g. , registers ) , this can be found in the given ' MapF.MapF ' . For operands without ' A.Location 's ( i.e. , immediates ) , we have to look up the corresponding mapping in the ' AC.RegisterizedInstruction ' findVarForOperand :: forall arch sh tp t solver fs . (AC.ConcreteArchitecture arch, OnlineSolver solver) => A.Opcode arch (A.Operand arch) sh -> AC.RegisterizedInstruction arch -> MapF.MapF (A.Location arch) (C.BoundVar (Sym t fs)) -> SL.Index sh tp -> A.Operand arch tp -> Syn solver t fs arch (BV.BoundVar (Sym t fs) arch tp) findVarForOperand opc (AC.RI { AC.riLiteralLocs = lls, AC.riOpcode = rop }) formulaBindings ix op | Just P.Refl <- P.testEquality rop opc = case A.operandToLocation (Proxy @arch) op of Just loc -> case MapF.lookup loc formulaBindings of Nothing -> do withSym $ \sym -> do BV.BoundVar <$> liftIO (C.freshBoundVar sym (U.makeSymbol (P.showF loc)) (A.locationType loc)) Just bv -> return (BV.BoundVar bv) Nothing -> do location in the RegisterizedInstruction . case MapF.lookup (AC.LiteralRef ix) lls of Just loc -> case MapF.lookup loc formulaBindings of Just bv -> return (BV.BoundVar bv) Nothing -> L.error ("Expected a binding for location " ++ P.showF loc) Nothing -> L.error ("Expected a location mapping for operand at index " ++ show ix) | otherwise = L.error ("Unexpected opcode mismatch: " ++ P.showF opc ++ " vs " ++ P.showF rop) liftImplicitLocations :: (P.OrdF (A.Location arch)) => A.Location arch tp -> C.SymExpr (Sym t fs) tp -> MapF.MapF (F.Parameter arch sh) (C.SymExpr (Sym t fs)) -> MapF.MapF (F.Parameter arch sh) (C.SymExpr (Sym t fs)) liftImplicitLocations loc expr = MapF.insert (F.LiteralParameter loc) expr keepNonParams :: (P.OrdF f) => S.Set (Some f) -> f tp -> g tp -> Bool keepNonParams paramLocs loc _ = S.notMember (Some loc) paramLocs collectParamLocs :: (AC.ConcreteArchitecture arch) => proxy arch -> A.Operand arch tp -> S.Set (Some (A.Location arch)) -> S.Set (Some (A.Location arch)) collectParamLocs proxy op s = case AC.operandToSemanticView proxy op of Nothing -> s Just (V.SemanticView { V.semvView = V.View _ loc }) -> S.insert (Some loc) s definitions of the formula are the first element of the pair ) , add them to a FIXME : Do we need to pass in the IORelation so that we are sure we are only IORelations to limit the formula we are generalizing . replaceParameters :: (AC.ConcreteArchitecture arch) => proxy arch -> SL.Index sh tp -> A.Operand arch tp -> (MapF.MapF (A.Location arch) (C.SymExpr (Sym t fs)), MapF.MapF (F.Parameter arch sh) (C.SymExpr (Sym t fs))) -> (MapF.MapF (A.Location arch) (C.SymExpr (Sym t fs)), MapF.MapF (F.Parameter arch sh) (C.SymExpr (Sym t fs))) replaceParameters proxy ix op (defs, m) = case A.operandToLocation proxy op of Nothing -> (defs, m) Just loc -> case MapF.lookup loc defs of Nothing -> (defs, m) Just expr -> (MapF.delete loc defs, MapF.insert (F.OperandParameter (A.locationType loc) ix) expr m)
85c921b05046dfa6c00e0a03f182522cb9795ef7e7daed89f94a7e160c645163
rescript-lang/rescript-compiler
ext_color.mli
Copyright ( C ) 2015 - 2016 Bloomberg Finance L.P. * * 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 , either version 3 of the License , or * ( at your option ) any later version . * * In addition to the permissions granted to you by the LGPL , you may combine * or link a " work that uses the Library " with a publicly distributed version * of this file to produce a combined library or application , then distribute * that combined work under the terms of your choosing , with no requirement * to comply with the obligations normally placed on you by section 4 of the * LGPL version 3 ( or the corresponding section of a later version of the LGPL * should you choose to use a 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 . * * 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, either version 3 of the License, or * (at your option) any later version. * * In addition to the permissions granted to you by the LGPL, you may combine * or link a "work that uses the Library" with a publicly distributed version * of this file to produce a combined library or application, then distribute * that combined work under the terms of your choosing, with no requirement * to comply with the obligations normally placed on you by section 4 of the * LGPL version 3 (or the corresponding section of a later version of the LGPL * should you choose to use a 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 color = Black | Red | Green | Yellow | Blue | Magenta | Cyan | White type style = FG of color | BG of color | Bold | Dim val ansi_of_tag : Format.stag -> string (** Input is the tag for example `@{<warning>@}` return escape code *) val reset_lit : string
null
https://raw.githubusercontent.com/rescript-lang/rescript-compiler/3a6999082bb842e7d00b99f1e70b39b595b35ba9/jscomp/ext/ext_color.mli
ocaml
* Input is the tag for example `@{<warning>@}` return escape code
Copyright ( C ) 2015 - 2016 Bloomberg Finance L.P. * * 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 , either version 3 of the License , or * ( at your option ) any later version . * * In addition to the permissions granted to you by the LGPL , you may combine * or link a " work that uses the Library " with a publicly distributed version * of this file to produce a combined library or application , then distribute * that combined work under the terms of your choosing , with no requirement * to comply with the obligations normally placed on you by section 4 of the * LGPL version 3 ( or the corresponding section of a later version of the LGPL * should you choose to use a 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 . * * 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, either version 3 of the License, or * (at your option) any later version. * * In addition to the permissions granted to you by the LGPL, you may combine * or link a "work that uses the Library" with a publicly distributed version * of this file to produce a combined library or application, then distribute * that combined work under the terms of your choosing, with no requirement * to comply with the obligations normally placed on you by section 4 of the * LGPL version 3 (or the corresponding section of a later version of the LGPL * should you choose to use a 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 color = Black | Red | Green | Yellow | Blue | Magenta | Cyan | White type style = FG of color | BG of color | Bold | Dim val ansi_of_tag : Format.stag -> string val reset_lit : string
56db45766cdf4f9fb447950f10c12a53a6c99dc0259cecf5fc78fdf7aead31ed
ekmett/machines
Is.hs
# LANGUAGE GADTs , TypeFamilies , TypeOperators # ----------------------------------------------------------------------------- -- | -- Module : Data.Machine.Is Copyright : ( C ) 2012 -- License : BSD-style (see the file LICENSE) -- Maintainer : < > -- Stability : provisional Portability : GADTs , Type Families -- ---------------------------------------------------------------------------- module Data.Machine.Is ( Is(..) ) where import Control.Category import Data.Semigroup import Prelude -- | Witnessed type equality data Is a b where Refl :: Is a a instance Show (Is a b) where showsPrec _ Refl = showString "Refl" instance Eq (Is a b) where Refl == Refl = True # INLINE (= =) # instance Ord (Is a b) where Refl `compare` Refl = EQ # INLINE compare # instance (a ~ b) => Semigroup (Is a b) where Refl <> Refl = Refl {-# INLINE (<>) #-} instance (a ~ b) => Monoid (Is a b) where mempty = Refl # INLINE mempty # mappend = (<>) # INLINE mappend # instance (a ~ b) => Read (Is a b) where readsPrec d = readParen (d > 10) (\r -> [(Refl,s) | ("Refl",s) <- lex r ]) instance Category Is where id = Refl {-# INLINE id #-} Refl . Refl = Refl {-# INLINE (.) #-}
null
https://raw.githubusercontent.com/ekmett/machines/58e39c953e7961e22765898d29ce1981f8147804/src/Data/Machine/Is.hs
haskell
--------------------------------------------------------------------------- | Module : Data.Machine.Is License : BSD-style (see the file LICENSE) Stability : provisional -------------------------------------------------------------------------- | Witnessed type equality # INLINE (<>) # # INLINE id # # INLINE (.) #
# LANGUAGE GADTs , TypeFamilies , TypeOperators # Copyright : ( C ) 2012 Maintainer : < > Portability : GADTs , Type Families module Data.Machine.Is ( Is(..) ) where import Control.Category import Data.Semigroup import Prelude data Is a b where Refl :: Is a a instance Show (Is a b) where showsPrec _ Refl = showString "Refl" instance Eq (Is a b) where Refl == Refl = True # INLINE (= =) # instance Ord (Is a b) where Refl `compare` Refl = EQ # INLINE compare # instance (a ~ b) => Semigroup (Is a b) where Refl <> Refl = Refl instance (a ~ b) => Monoid (Is a b) where mempty = Refl # INLINE mempty # mappend = (<>) # INLINE mappend # instance (a ~ b) => Read (Is a b) where readsPrec d = readParen (d > 10) (\r -> [(Refl,s) | ("Refl",s) <- lex r ]) instance Category Is where id = Refl Refl . Refl = Refl
c7a4aaba521a426f3a7525abc7e551612b7d80bf8c4bf8240de2a519283dc16a
haskell/deepseq
DeepSeq.hs
# LANGUAGE CPP # # LANGUAGE DefaultSignatures # # LANGUAGE EmptyCase # # LANGUAGE FlexibleContexts # # LANGUAGE FlexibleInstances # # LANGUAGE MultiParamTypeClasses # # LANGUAGE PolyKinds # # LANGUAGE QuantifiedConstraints # {-# LANGUAGE Safe #-} # LANGUAGE TypeFamilies # # LANGUAGE TypeOperators # #if __GLASGOW_HASKELL__ >= 811 && __GLASGOW_HASKELL__ < 901 For the Option instance ( ) # OPTIONS_GHC -Wno - deprecations # #endif ----------------------------------------------------------------------------- -- | Module : Control . Copyright : ( c ) The University of Glasgow 2001 - 2009 -- License : BSD-style (see the file LICENSE) -- -- Maintainer : -- Stability : stable -- Portability : portable -- -- This module provides overloaded functions, such as 'deepseq' and -- 'rnf', for fully evaluating data structures (that is, evaluating to -- \"Normal Form\"). -- -- A typical use is to prevent resource leaks in lazy IO programs, by -- forcing all characters from a file to be read. For example: -- -- > import System.IO > import Control . -- > import Control.Exception (evaluate) -- > -- > readFile' :: FilePath -> IO String -- > readFile' fn = do -- > h <- openFile fn ReadMode -- > s <- hGetContents h > evaluate ( rnf s ) > -- > return s -- -- __Note__: The example above should rather be written in terms of -- 'Control.Exception.bracket' to ensure releasing file-descriptors in -- a timely matter (see the description of 'force' for an example). -- -- 'deepseq' differs from 'seq' as it traverses data structures deeply, for example , ' seq ' will evaluate only to the first constructor in -- the list: -- > > [ 1,2,undefined ] ` seq ` 3 > 3 -- -- While 'deepseq' will force evaluation of all the list elements: -- > > [ 1,2,undefined ] ` deepseq ` 3 -- > *** Exception: Prelude.undefined -- -- Another common use is to ensure any exceptions hidden within lazy -- fields of a data structure do not leak outside the scope of the exception handler , or to force evaluation of a data structure in one -- thread, before passing to another thread (preventing work moving to -- the wrong threads). -- -- @since 1.1.0.0 module Control.DeepSeq ( -- * 'NFData' class NFData (rnf), -- * Helper functions deepseq, force, ($!!), (<$!!>), rwhnf, * of the ' NFData ' class -- ** For unary constructors NFData1 (liftRnf), rnf1, -- ** For binary constructors NFData2 (liftRnf2), rnf2, ) where import Control.Applicative import Control.Concurrent (MVar, ThreadId) import Control.Exception (MaskingState (..)) import Data.Array import Data.Complex import Data.Fixed import Data.Functor.Compose import Data.Functor.Identity (Identity (..)) import qualified Data.Functor.Product as Functor import qualified Data.Functor.Sum as Functor import Data.IORef import Data.Int import Data.List.NonEmpty (NonEmpty (..)) import Data.Monoid as Mon import Data.Ord (Down (Down)) import Data.Proxy (Proxy (Proxy)) import Data.Ratio import Data.STRef import Data.Semigroup as Semi import Data.Type.Equality ((:~:), (:~~:)) import Data.Typeable (TyCon, TypeRep, rnfTyCon, rnfTypeRep) import Data.Unique (Unique) import Data.Version import Data.Void (Void, absurd) import Data.Word import Foreign.C.Types import Foreign.Ptr import GHC.Fingerprint.Type (Fingerprint (..)) import GHC.Generics import GHC.Stack.Types (CallStack (..), SrcLoc (..)) import Numeric.Natural (Natural) import System.Exit (ExitCode (..)) import System.Mem.StableName (StableName) import qualified Type.Reflection as Reflection #ifdef MIN_VERSION_ghc_prim #if MIN_VERSION_ghc_prim(0,7,0) import GHC.Tuple (Solo (..)) #endif #endif #if MIN_VERSION_base(4,17,0) import Data.Array.Byte (ByteArray(..), MutableByteArray(..)) #endif -- | Hidden internal type-class class GNFData arity f where grnf :: RnfArgs arity a -> f a -> () instance GNFData arity V1 where grnf _ x = case x of {} data Zero data One data family RnfArgs arity a data instance RnfArgs Zero a = RnfArgs0 newtype instance RnfArgs One a = RnfArgs1 (a -> ()) instance GNFData arity U1 where grnf _ U1 = () instance NFData a => GNFData arity (K1 i a) where grnf _ = rnf . unK1 # INLINEABLE grnf # instance GNFData arity a => GNFData arity (M1 i c a) where grnf args = grnf args . unM1 # INLINEABLE grnf # instance GNFData arity (URec a) where Every URec data instance consists of a single data -- constructor containing a single strict field, so reducing any URec instance to WHNF suffices to reduce it to NF . # INLINEABLE grnf # instance (GNFData arity a, GNFData arity b) => GNFData arity (a :*: b) where grnf args (x :*: y) = grnf args x `seq` grnf args y # INLINEABLE grnf # instance (GNFData arity a, GNFData arity b) => GNFData arity (a :+: b) where grnf args (L1 x) = grnf args x grnf args (R1 x) = grnf args x # INLINEABLE grnf # instance GNFData One Par1 where grnf (RnfArgs1 r) = r . unPar1 instance NFData1 f => GNFData One (Rec1 f) where grnf (RnfArgs1 r) = liftRnf r . unRec1 instance (NFData1 f, GNFData One g) => GNFData One (f :.: g) where grnf args = liftRnf (grnf args) . unComp1 infixr 0 $!! infixr 0 `deepseq` | ' deepseq ' : fully evaluates the first argument , before returning the second . -- -- The name 'deepseq' is used to illustrate the relationship to 'seq': -- where 'seq' is shallow in the sense that it only evaluates the top -- level of its argument, 'deepseq' traverses the entire data structure -- evaluating it completely. -- -- 'deepseq' can be useful for forcing pending exceptions, -- eradicating space leaks, or forcing lazy I/O to happen. It is also useful in conjunction with parallel Strategies ( see the -- @parallel@ package). -- -- There is no guarantee about the ordering of evaluation. The -- implementation may evaluate the components of the structure in -- any order or in parallel. To impose an actual order on -- evaluation, use 'pseq' from "Control.Parallel" in the -- @parallel@ package. -- -- @since 1.1.0.0 deepseq :: NFData a => a -> b -> b deepseq a b = rnf a `seq` b | the deep analogue of ' $ ! ' . In the expression @f $ ! ! , @x@ is fully evaluated before the function @f@ is applied to it . -- @since 1.2.0.0 ($!!) :: (NFData a) => (a -> b) -> a -> b f $!! x = x `deepseq` f x -- | a variant of 'deepseq' that is useful in some circumstances: -- -- > force x = x `deepseq` x -- @force x@ fully evaluates @x@ , and then returns it . Note that @force x@ only performs evaluation when the value of @force x@ -- itself is demanded, so essentially it turns shallow evaluation into -- deep evaluation. -- ' force ' can be conveniently used in combination with : -- > { - # LANGUAGE BangPatterns , ViewPatterns # - } > import Control . -- > > someFun : : ComplexData - > SomeResult -- > someFun (force -> !arg) = {- 'arg' will be fully evaluated -} -- -- Another useful application is to combine 'force' with ' Control.Exception.evaluate ' in order to force deep evaluation -- relative to other 'IO' operations: -- -- > import Control.Exception (evaluate) > import Control . -- > -- > main = do -- > result <- evaluate $ force $ pureComputation -- > {- 'result' will be fully evaluated at this point -} -- > return () -- Finally , here 's an exception safe variant of the @readFile'@ example : -- -- > readFile' :: FilePath -> IO String -- > readFile' fn = bracket (openFile fn ReadMode) hClose $ \h -> -- > evaluate . force =<< hGetContents h -- @since 1.2.0.0 force :: (NFData a) => a -> a force x = x `deepseq` x -- | Deeply strict version of 'Control.Applicative.<$>'. -- @since 1.4.3.0 (<$!!>) :: (Monad m, NFData b) => (a -> b) -> m a -> m b f <$!!> m = m >>= \x -> pure $!! f x infixl 4 <$!!> -- | Reduce to weak head normal form -- -- Equivalent to @\\x -> 'seq' x ()@. -- Useful for defining ' NFData ' for types for which NF = WHNF holds . -- -- > data T = C1 | C2 | C3 -- > instance NFData T where rnf = rwhnf -- @since 1.4.3.0 rwhnf :: a -> () rwhnf = (`seq` ()) # INLINE rwhnf # -- Note: the 'rwhnf' is defined point-free to help aggressive inlining -- | A class of types that can be fully evaluated. -- -- @since 1.1.0.0 class NFData a where -- | 'rnf' should reduce its argument to normal form (that is, fully -- evaluate all sub-components), and then return '()'. -- -- === 'Generic' 'NFData' deriving -- Starting with GHC 7.2 , you can automatically derive instances for types possessing a ' Generic ' instance . -- Note : ' Generic1 ' can be auto - derived starting with GHC 7.4 -- -- > {-# LANGUAGE DeriveGeneric #-} -- > > import ( Generic , Generic1 ) > import Control . -- > > data a = Foo a String > deriving ( Eq , Generic , Generic1 ) -- > > instance NFData a = > NFData ( a ) > instance -- > -- > data Colour = Red | Green | Blue > deriving Generic -- > > instance NFData Colour -- Starting with GHC 7.10 , the example above can be written more concisely by enabling the new extension : -- -- > {-# LANGUAGE DeriveGeneric, DeriveAnyClass #-} -- > > import ( Generic ) > import Control . -- > > data a = Foo a String > deriving ( Eq , Generic , Generic1 , NFData , NFData1 ) -- > -- > data Colour = Red | Green | Blue > deriving ( Generic , NFData ) -- > -- -- === Compatibility with previous @deepseq@ versions -- -- Prior to version 1.4.0.0, the default implementation of the 'rnf' -- method was defined as -- @'rnf ' a = ' seq ' a ( ) @ -- However , starting with @deepseq-1.4.0.0@ , the default -- implementation is based on @DefaultSignatures@ allowing for -- more accurate auto-derived 'NFData' instances. If you need the -- previously used exact default 'rnf' method implementation -- semantics, use -- > instance NFData Colour where rnf x = seq x ( ) -- -- or alternatively -- > instance NFData Colour where rnf = rwhnf -- -- or -- -- > {-# LANGUAGE BangPatterns #-} > instance NFData Colour where rnf ! _ = ( ) rnf :: a -> () default rnf :: (Generic a, GNFData Zero (Rep a)) => a -> () rnf = grnf RnfArgs0 . from -- | A class of functors that can be fully evaluated. -- In ` deepseq-1.5.0.0 ` this class was updated to include superclasses . -- @since 1.4.3.0 class (forall a. NFData a => NFData (f a)) => NFData1 f where | ' liftRnf ' should reduce its argument to normal form ( that is , fully -- evaluate all sub-components), given an argument to reduce @a@ arguments, -- and then return '()'. -- -- See 'rnf' for the generic deriving. liftRnf :: (a -> ()) -> f a -> () default liftRnf :: (Generic1 f, GNFData One (Rep1 f)) => (a -> ()) -> f a -> () liftRnf r = grnf (RnfArgs1 r) . from1 -- | Lift the standard 'rnf' function through the type constructor. -- @since 1.4.3.0 rnf1 :: (NFData1 f, NFData a) => f a -> () rnf1 = liftRnf rnf -- | A class of bifunctors that can be fully evaluated. -- In ` deepseq-1.5.0.0 ` this class was updated to include superclasses . -- @since 1.4.3.0 class (forall a. NFData a => NFData1 (p a)) => NFData2 p where -- | 'liftRnf2' should reduce its argument to normal form (that -- is, fully evaluate all sub-components), given functions to reduce @a@ and @b@ arguments respectively , and then return ' ( ) ' . -- _ _ Note _ _ : Unlike for the unary ' liftRnf ' , there is currently no -- support for generically deriving 'liftRnf2'. liftRnf2 :: (a -> ()) -> (b -> ()) -> p a b -> () -- | Lift the standard 'rnf' function through the type constructor. -- @since 1.4.3.0 rnf2 :: (NFData2 p, NFData a, NFData b) => p a b -> () rnf2 = liftRnf2 rnf rnf instance NFData Int where rnf = rwhnf instance NFData Word where rnf = rwhnf instance NFData Integer where rnf = rwhnf instance NFData Float where rnf = rwhnf instance NFData Double where rnf = rwhnf instance NFData Char where rnf = rwhnf instance NFData Bool where rnf = rwhnf instance NFData Ordering where rnf = rwhnf instance NFData () where rnf = rwhnf instance NFData Int8 where rnf = rwhnf instance NFData Int16 where rnf = rwhnf instance NFData Int32 where rnf = rwhnf instance NFData Int64 where rnf = rwhnf instance NFData Word8 where rnf = rwhnf instance NFData Word16 where rnf = rwhnf instance NFData Word32 where rnf = rwhnf instance NFData Word64 where rnf = rwhnf | @since 1.4.4.0 instance NFData MaskingState where rnf = rwhnf -- | @since 1.4.0.0 instance NFData (Proxy a) where rnf Proxy = () | @since 1.4.3.0 instance NFData1 Proxy where liftRnf _ Proxy = () | @since 1.4.3.0 instance NFData (a :~: b) where rnf = rwhnf | @since 1.4.3.0 instance NFData1 ((:~:) a) where liftRnf _ = rwhnf | @since 1.4.3.0 instance NFData2 (:~:) where liftRnf2 _ _ = rwhnf | @since 1.4.3.0 instance NFData (a :~~: b) where rnf = rwhnf | @since 1.4.3.0 instance NFData1 ((:~~:) a) where liftRnf _ = rwhnf | @since 1.4.3.0 instance NFData2 (:~~:) where liftRnf2 _ _ = rwhnf -- | @since 1.4.0.0 instance NFData a => NFData (Identity a) where rnf = rnf1 | @since 1.4.3.0 instance NFData1 Identity where liftRnf r = r . runIdentity | Defined as @'rnf ' = ' absurd'@. -- -- @since 1.4.0.0 instance NFData Void where rnf = absurd -- | @since 1.4.0.0 instance NFData Natural where rnf = rwhnf | @since 1.3.0.0 instance NFData (Fixed a) where rnf = rwhnf | @since 1.4.3.0 instance NFData1 Fixed where liftRnf _ = rwhnf -- | This instance is for convenience and consistency with 'seq'. This assumes that WHNF is equivalent to NF for functions . -- @since 1.3.0.0 instance NFData (a -> b) where rnf = rwhnf -- Rational and complex numbers. | Available on @base > = 4.9@ -- @since 1.4.3.0 instance NFData1 Ratio where liftRnf r x = r (numerator x) `seq` r (denominator x) | @since 1.4.3.0 instance (NFData1 f, NFData1 g) => NFData1 (Compose f g) where liftRnf r = liftRnf (liftRnf r) . getCompose | Note : in @deepseq-1.5.0.0@ this instance 's superclasses were changed . -- @since 1.4.3.0 instance (NFData (f (g a))) => NFData (Compose f g a) where rnf (Compose fga) = rnf fga | @since 1.4.3.0 instance (NFData1 f, NFData1 g) => NFData1 (Functor.Sum f g) where liftRnf rnf0 (Functor.InL l) = liftRnf rnf0 l liftRnf rnf0 (Functor.InR r) = liftRnf rnf0 r | Note : in @deepseq-1.5.0.0@ this instance 's superclasses were changed . -- @since 1.4.3.0 instance (NFData (f a), NFData (g a)) => NFData (Functor.Sum f g a) where rnf (Functor.InL fa) = rnf fa rnf (Functor.InR ga) = rnf ga | @since 1.4.3.0 instance (NFData1 f, NFData1 g) => NFData1 (Functor.Product f g) where liftRnf rnf0 (Functor.Pair f g) = liftRnf rnf0 f `seq` liftRnf rnf0 g | Note : in @deepseq-1.5.0.0@ this instance 's superclasses were changed . -- @since 1.4.3.0 instance (NFData (f a), NFData (g a)) => NFData (Functor.Product f g a) where rnf (Functor.Pair fa ga) = rnf fa `seq` rnf ga instance NFData a => NFData (Ratio a) where rnf x = rnf (numerator x, denominator x) instance (NFData a) => NFData (Complex a) where rnf (x :+ y) = rnf x `seq` rnf y `seq` () instance NFData a => NFData (Maybe a) where rnf = rnf1 | @since 1.4.3.0 instance NFData1 Maybe where liftRnf _r Nothing = () liftRnf r (Just x) = r x instance (NFData a, NFData b) => NFData (Either a b) where rnf = rnf1 | @since 1.4.3.0 instance (NFData a) => NFData1 (Either a) where liftRnf = liftRnf2 rnf | @since 1.4.3.0 instance NFData2 Either where liftRnf2 l _r (Left x) = l x liftRnf2 _l r (Right y) = r y | @since 1.3.0.0 instance NFData Data.Version.Version where rnf (Data.Version.Version branch tags) = rnf branch `seq` rnf tags instance NFData a => NFData [a] where rnf = rnf1 | @since 1.4.3.0 instance NFData1 [] where liftRnf r = go where go [] = () go (x : xs) = r x `seq` go xs -- | @since 1.4.0.0 instance NFData a => NFData (ZipList a) where rnf = rnf1 | @since 1.4.3.0 instance NFData1 ZipList where liftRnf r = liftRnf r . getZipList -- | @since 1.4.0.0 instance NFData a => NFData (Const a b) where rnf = rnf . getConst | @since 1.4.3.0 instance NFData a => NFData1 (Const a) where liftRnf _ = rnf . getConst | @since 1.4.3.0 instance NFData2 Const where liftRnf2 r _ = r . getConst We should use array(0,5,1,1 ) but that 's not possible . -- There isn't an underscore to not break C preprocessor instance (NFData a, NFData b) => NFData (Array a b) where rnf x = rnf (bounds x, Data.Array.elems x) | @since 1.4.3.0 instance (NFData a) => NFData1 (Array a) where liftRnf r x = rnf (bounds x) `seq` liftRnf r (Data.Array.elems x) | @since 1.4.3.0 instance NFData2 Array where liftRnf2 r r' x = liftRnf2 r r (bounds x) `seq` liftRnf r' (Data.Array.elems x) -- | @since 1.4.0.0 instance NFData a => NFData (Down a) where rnf = rnf1 | @since 1.4.3.0 instance NFData1 Down where liftRnf r (Down x) = r x -- | @since 1.4.0.0 instance NFData a => NFData (Dual a) where rnf = rnf1 | @since 1.4.3.0 instance NFData1 Dual where liftRnf r (Dual x) = r x -- | @since 1.4.0.0 instance NFData a => NFData (Mon.First a) where rnf = rnf1 | @since 1.4.3.0 instance NFData1 Mon.First where liftRnf r (Mon.First x) = liftRnf r x -- | @since 1.4.0.0 instance NFData a => NFData (Mon.Last a) where rnf = rnf1 | @since 1.4.3.0 instance NFData1 Mon.Last where liftRnf r (Mon.Last x) = liftRnf r x -- | @since 1.4.0.0 instance NFData Any where rnf = rnf . getAny -- | @since 1.4.0.0 instance NFData All where rnf = rnf . getAll -- | @since 1.4.0.0 instance NFData a => NFData (Sum a) where rnf = rnf1 | @since 1.4.3.0 instance NFData1 Sum where liftRnf r (Sum x) = r x -- | @since 1.4.0.0 instance NFData a => NFData (Product a) where rnf = rnf1 | @since 1.4.3.0 instance NFData1 Product where liftRnf r (Product x) = r x -- | @since 1.4.0.0 instance NFData (StableName a) where assumes ` data StableName a = StableName ( StableName # a ) ` | @since 1.4.3.0 instance NFData1 StableName where liftRnf _ = rwhnf -- | @since 1.4.0.0 instance NFData ThreadId where rnf = rwhnf -- assumes `data ThreadId = ThreadId ThreadId#` -- | @since 1.4.0.0 instance NFData Unique where rnf = rwhnf -- assumes `newtype Unique = Unique Integer` -- | __NOTE__: Prior to @deepseq-1.4.4.0@ this instance was only defined for @base-4.8.0.0@ and later. -- -- @since 1.4.0.0 instance NFData TypeRep where rnf tyrep = rnfTypeRep tyrep -- | __NOTE__: Prior to @deepseq-1.4.4.0@ this instance was only defined for @base-4.8.0.0@ and later. -- -- @since 1.4.0.0 instance NFData TyCon where rnf tycon = rnfTyCon tycon | @since 1.4.8.0 instance NFData (Reflection.TypeRep a) where rnf tr = Reflection.rnfTypeRep tr | @since 1.4.8.0 instance NFData Reflection.Module where rnf modul = Reflection.rnfModule modul -- | __NOTE__: Only strict in the reference and not the referenced value. -- -- @since 1.4.2.0 instance NFData (IORef a) where rnf = rwhnf | @since 1.4.3.0 instance NFData1 IORef where liftRnf _ = rwhnf -- | __NOTE__: Only strict in the reference and not the referenced value. -- -- @since 1.4.2.0 instance NFData (STRef s a) where rnf = rwhnf | @since 1.4.3.0 instance NFData1 (STRef s) where liftRnf _ = rwhnf | @since 1.4.3.0 instance NFData2 STRef where liftRnf2 _ _ = rwhnf -- | __NOTE__: Only strict in the reference and not the referenced value. -- -- @since 1.4.2.0 instance NFData (MVar a) where rnf = rwhnf | @since 1.4.3.0 instance NFData1 MVar where liftRnf _ = rwhnf ---------------------------------------------------------------------------- GHC Specifics -- | @since 1.4.0.0 instance NFData Fingerprint where rnf (Fingerprint _ _) = () ---------------------------------------------------------------------------- -- Foreign.Ptr | @since 1.4.2.0 instance NFData (Ptr a) where rnf = rwhnf | @since 1.4.3.0 instance NFData1 Ptr where liftRnf _ = rwhnf | @since 1.4.2.0 instance NFData (FunPtr a) where rnf = rwhnf | @since 1.4.3.0 instance NFData1 FunPtr where liftRnf _ = rwhnf ---------------------------------------------------------------------------- Foreign . C.Types -- | @since 1.4.0.0 instance NFData CChar where rnf = rwhnf -- | @since 1.4.0.0 instance NFData CSChar where rnf = rwhnf -- | @since 1.4.0.0 instance NFData CUChar where rnf = rwhnf -- | @since 1.4.0.0 instance NFData CShort where rnf = rwhnf -- | @since 1.4.0.0 instance NFData CUShort where rnf = rwhnf -- | @since 1.4.0.0 instance NFData CInt where rnf = rwhnf -- | @since 1.4.0.0 instance NFData CUInt where rnf = rwhnf -- | @since 1.4.0.0 instance NFData CLong where rnf = rwhnf -- | @since 1.4.0.0 instance NFData CULong where rnf = rwhnf -- | @since 1.4.0.0 instance NFData CPtrdiff where rnf = rwhnf -- | @since 1.4.0.0 instance NFData CSize where rnf = rwhnf -- | @since 1.4.0.0 instance NFData CWchar where rnf = rwhnf -- | @since 1.4.0.0 instance NFData CSigAtomic where rnf = rwhnf -- | @since 1.4.0.0 instance NFData CLLong where rnf = rwhnf -- | @since 1.4.0.0 instance NFData CULLong where rnf = rwhnf -- | @since 1.4.0.0 instance NFData CIntPtr where rnf = rwhnf -- | @since 1.4.0.0 instance NFData CUIntPtr where rnf = rwhnf -- | @since 1.4.0.0 instance NFData CIntMax where rnf = rwhnf -- | @since 1.4.0.0 instance NFData CUIntMax where rnf = rwhnf -- | @since 1.4.0.0 instance NFData CClock where rnf = rwhnf -- | @since 1.4.0.0 instance NFData CTime where rnf = rwhnf -- | @since 1.4.0.0 instance NFData CUSeconds where rnf = rwhnf -- | @since 1.4.0.0 instance NFData CSUSeconds where rnf = rwhnf -- | @since 1.4.0.0 instance NFData CFloat where rnf = rwhnf -- | @since 1.4.0.0 instance NFData CDouble where rnf = rwhnf NOTE : The types ` CFile ` , ` CFPos ` , and ` CJmpBuf ` below are not -- newtype wrappers rather defined as field-less single-constructor -- types. -- | @since 1.4.0.0 instance NFData CFile where rnf = rwhnf -- | @since 1.4.0.0 instance NFData CFpos where rnf = rwhnf -- | @since 1.4.0.0 instance NFData CJmpBuf where rnf = rwhnf | @since 1.4.3.0 instance NFData CBool where rnf = rwhnf ---------------------------------------------------------------------------- -- System.Exit | @since 1.4.2.0 instance NFData ExitCode where rnf (ExitFailure n) = rnf n rnf ExitSuccess = () ---------------------------------------------------------------------------- -- instances previously provided by semigroups package | @since 1.4.2.0 instance NFData a => NFData (NonEmpty a) where rnf = rnf1 | @since 1.4.3.0 instance NFData1 NonEmpty where liftRnf r (x :| xs) = r x `seq` liftRnf r xs | @since 1.4.2.0 instance NFData a => NFData (Min a) where rnf = rnf1 | @since 1.4.3.0 instance NFData1 Min where liftRnf r (Min a) = r a | @since 1.4.2.0 instance NFData a => NFData (Max a) where rnf = rnf1 | @since 1.4.3.0 instance NFData1 Max where liftRnf r (Max a) = r a | @since 1.4.2.0 instance (NFData a, NFData b) => NFData (Arg a b) where rnf = rnf2 | @since 1.4.3.0 instance (NFData a) => NFData1 (Arg a) where liftRnf = liftRnf2 rnf | @since 1.4.3.0 instance NFData2 Arg where liftRnf2 r r' (Arg a b) = r a `seq` r' b `seq` () | @since 1.4.2.0 instance NFData a => NFData (Semi.First a) where rnf = rnf1 | @since 1.4.3.0 instance NFData1 Semi.First where liftRnf r (Semi.First a) = r a | @since 1.4.2.0 instance NFData a => NFData (Semi.Last a) where rnf = rnf1 | @since 1.4.3.0 instance NFData1 Semi.Last where liftRnf r (Semi.Last a) = r a | @since 1.4.2.0 instance NFData m => NFData (WrappedMonoid m) where rnf = rnf1 | @since 1.4.3.0 instance NFData1 WrappedMonoid where liftRnf r (WrapMonoid a) = r a #if __GLASGOW_HASKELL__ < 901 -- |@since 1.4.2.0 instance NFData a => NFData (Option a) where rnf = rnf1 |@since 1.4.3.0 instance NFData1 Option where liftRnf r (Option a) = liftRnf r a #endif ---------------------------------------------------------------------------- -- GHC.Stack | @since 1.4.2.0 instance NFData SrcLoc where rnf (SrcLoc a b c d e f g) = rnf a `seq` rnf b `seq` rnf c `seq` rnf d `seq` rnf e `seq` rnf f `seq` rnf g | @since 1.4.2.0 instance NFData CallStack where rnf EmptyCallStack = () rnf (PushCallStack a b c) = rnf a `seq` rnf b `seq` rnf c rnf (FreezeCallStack a) = rnf a ---------------------------------------------------------------------------- Tuples #ifdef MIN_VERSION_ghc_prim #if MIN_VERSION_ghc_prim(0,7,0) |@since 1.4.6.0 instance NFData a => NFData (Solo a) where #if MIN_VERSION_ghc_prim(0,10,0) rnf (MkSolo a) = rnf a #else rnf (Solo a) = rnf a #endif |@since 1.4.6.0 instance NFData1 Solo where #if MIN_VERSION_ghc_prim(0,10,0) liftRnf r (MkSolo a) = r a #else liftRnf r (Solo a) = r a #endif #endif #endif instance (NFData a, NFData b) => NFData (a, b) where rnf = rnf2 | @since 1.4.3.0 instance (NFData a) => NFData1 ((,) a) where liftRnf = liftRnf2 rnf | @since 1.4.3.0 instance NFData2 (,) where liftRnf2 r r' (x, y) = r x `seq` r' y -- Code below is generated, see generate-nfdata-tuple.hs instance (NFData a1, NFData a2, NFData a3) => NFData (a1, a2, a3) where rnf = rnf2 | @since 1.4.3.0 instance (NFData a1, NFData a2) => NFData1 ((,,) a1 a2) where liftRnf = liftRnf2 rnf | @since 1.4.3.0 instance (NFData a1) => NFData2 ((,,) a1) where liftRnf2 r r' (x1, x2, x3) = rnf x1 `seq` r x2 `seq` r' x3 instance (NFData a1, NFData a2, NFData a3, NFData a4) => NFData (a1, a2, a3, a4) where rnf = rnf2 | @since 1.4.3.0 instance (NFData a1, NFData a2, NFData a3) => NFData1 ((,,,) a1 a2 a3) where liftRnf = liftRnf2 rnf | @since 1.4.3.0 instance (NFData a1, NFData a2) => NFData2 ((,,,) a1 a2) where liftRnf2 r r' (x1, x2, x3, x4) = rnf x1 `seq` rnf x2 `seq` r x3 `seq` r' x4 instance (NFData a1, NFData a2, NFData a3, NFData a4, NFData a5) => NFData (a1, a2, a3, a4, a5) where rnf = rnf2 | @since 1.4.3.0 instance (NFData a1, NFData a2, NFData a3, NFData a4) => NFData1 ((,,,,) a1 a2 a3 a4) where liftRnf = liftRnf2 rnf | @since 1.4.3.0 instance (NFData a1, NFData a2, NFData a3) => NFData2 ((,,,,) a1 a2 a3) where liftRnf2 r r' (x1, x2, x3, x4, x5) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` r x4 `seq` r' x5 instance (NFData a1, NFData a2, NFData a3, NFData a4, NFData a5, NFData a6) => NFData (a1, a2, a3, a4, a5, a6) where rnf = rnf2 | @since 1.4.3.0 instance (NFData a1, NFData a2, NFData a3, NFData a4, NFData a5) => NFData1 ((,,,,,) a1 a2 a3 a4 a5) where liftRnf = liftRnf2 rnf | @since 1.4.3.0 instance (NFData a1, NFData a2, NFData a3, NFData a4) => NFData2 ((,,,,,) a1 a2 a3 a4) where liftRnf2 r r' (x1, x2, x3, x4, x5, x6) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` r x5 `seq` r' x6 instance (NFData a1, NFData a2, NFData a3, NFData a4, NFData a5, NFData a6, NFData a7) => NFData (a1, a2, a3, a4, a5, a6, a7) where rnf = rnf2 | @since 1.4.3.0 instance (NFData a1, NFData a2, NFData a3, NFData a4, NFData a5, NFData a6) => NFData1 ((,,,,,,) a1 a2 a3 a4 a5 a6) where liftRnf = liftRnf2 rnf | @since 1.4.3.0 instance (NFData a1, NFData a2, NFData a3, NFData a4, NFData a5) => NFData2 ((,,,,,,) a1 a2 a3 a4 a5) where liftRnf2 r r' (x1, x2, x3, x4, x5, x6, x7) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` rnf x5 `seq` r x6 `seq` r' x7 instance (NFData a1, NFData a2, NFData a3, NFData a4, NFData a5, NFData a6, NFData a7, NFData a8) => NFData (a1, a2, a3, a4, a5, a6, a7, a8) where rnf = rnf2 | @since 1.4.3.0 instance (NFData a1, NFData a2, NFData a3, NFData a4, NFData a5, NFData a6, NFData a7) => NFData1 ((,,,,,,,) a1 a2 a3 a4 a5 a6 a7) where liftRnf = liftRnf2 rnf | @since 1.4.3.0 instance (NFData a1, NFData a2, NFData a3, NFData a4, NFData a5, NFData a6) => NFData2 ((,,,,,,,) a1 a2 a3 a4 a5 a6) where liftRnf2 r r' (x1, x2, x3, x4, x5, x6, x7, x8) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` rnf x5 `seq` rnf x6 `seq` r x7 `seq` r' x8 instance (NFData a1, NFData a2, NFData a3, NFData a4, NFData a5, NFData a6, NFData a7, NFData a8, NFData a9) => NFData (a1, a2, a3, a4, a5, a6, a7, a8, a9) where rnf = rnf2 | @since 1.4.3.0 instance (NFData a1, NFData a2, NFData a3, NFData a4, NFData a5, NFData a6, NFData a7, NFData a8) => NFData1 ((,,,,,,,,) a1 a2 a3 a4 a5 a6 a7 a8) where liftRnf = liftRnf2 rnf | @since 1.4.3.0 instance (NFData a1, NFData a2, NFData a3, NFData a4, NFData a5, NFData a6, NFData a7) => NFData2 ((,,,,,,,,) a1 a2 a3 a4 a5 a6 a7) where liftRnf2 r r' (x1, x2, x3, x4, x5, x6, x7, x8, x9) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` rnf x5 `seq` rnf x6 `seq` rnf x7 `seq` r x8 `seq` r' x9 ---------------------------------------------------------------------------- ByteArray #if MIN_VERSION_base(4,17,0) |@since 1.4.7.0 instance NFData ByteArray where rnf (ByteArray _) = () -- |@since 1.4.8.0 instance NFData (MutableByteArray s) where rnf (MutableByteArray _) = () #endif
null
https://raw.githubusercontent.com/haskell/deepseq/be30621bdc318c58b5438603f3ddad160f5339b6/Control/DeepSeq.hs
haskell
# LANGUAGE Safe # --------------------------------------------------------------------------- | License : BSD-style (see the file LICENSE) Maintainer : Stability : stable Portability : portable This module provides overloaded functions, such as 'deepseq' and 'rnf', for fully evaluating data structures (that is, evaluating to \"Normal Form\"). A typical use is to prevent resource leaks in lazy IO programs, by forcing all characters from a file to be read. For example: > import System.IO > import Control.Exception (evaluate) > > readFile' :: FilePath -> IO String > readFile' fn = do > h <- openFile fn ReadMode > s <- hGetContents h > return s __Note__: The example above should rather be written in terms of 'Control.Exception.bracket' to ensure releasing file-descriptors in a timely matter (see the description of 'force' for an example). 'deepseq' differs from 'seq' as it traverses data structures deeply, the list: While 'deepseq' will force evaluation of all the list elements: > *** Exception: Prelude.undefined Another common use is to ensure any exceptions hidden within lazy fields of a data structure do not leak outside the scope of the thread, before passing to another thread (preventing work moving to the wrong threads). @since 1.1.0.0 * 'NFData' class * Helper functions ** For unary constructors ** For binary constructors | Hidden internal type-class constructor containing a single strict field, so reducing The name 'deepseq' is used to illustrate the relationship to 'seq': where 'seq' is shallow in the sense that it only evaluates the top level of its argument, 'deepseq' traverses the entire data structure evaluating it completely. 'deepseq' can be useful for forcing pending exceptions, eradicating space leaks, or forcing lazy I/O to happen. It is @parallel@ package). There is no guarantee about the ordering of evaluation. The implementation may evaluate the components of the structure in any order or in parallel. To impose an actual order on evaluation, use 'pseq' from "Control.Parallel" in the @parallel@ package. @since 1.1.0.0 | a variant of 'deepseq' that is useful in some circumstances: > force x = x `deepseq` x itself is demanded, so essentially it turns shallow evaluation into deep evaluation. > > someFun (force -> !arg) = {- 'arg' will be fully evaluated -} Another useful application is to combine 'force' with relative to other 'IO' operations: > import Control.Exception (evaluate) > > main = do > result <- evaluate $ force $ pureComputation > {- 'result' will be fully evaluated at this point -} > return () > readFile' :: FilePath -> IO String > readFile' fn = bracket (openFile fn ReadMode) hClose $ \h -> > evaluate . force =<< hGetContents h | Deeply strict version of 'Control.Applicative.<$>'. | Reduce to weak head normal form Equivalent to @\\x -> 'seq' x ()@. > data T = C1 | C2 | C3 > instance NFData T where rnf = rwhnf Note: the 'rwhnf' is defined point-free to help aggressive inlining | A class of types that can be fully evaluated. @since 1.1.0.0 | 'rnf' should reduce its argument to normal form (that is, fully evaluate all sub-components), and then return '()'. === 'Generic' 'NFData' deriving > {-# LANGUAGE DeriveGeneric #-} > > > > > data Colour = Red | Green | Blue > > {-# LANGUAGE DeriveGeneric, DeriveAnyClass #-} > > > > data Colour = Red | Green | Blue > === Compatibility with previous @deepseq@ versions Prior to version 1.4.0.0, the default implementation of the 'rnf' method was defined as implementation is based on @DefaultSignatures@ allowing for more accurate auto-derived 'NFData' instances. If you need the previously used exact default 'rnf' method implementation semantics, use or alternatively or > {-# LANGUAGE BangPatterns #-} | A class of functors that can be fully evaluated. evaluate all sub-components), given an argument to reduce @a@ arguments, and then return '()'. See 'rnf' for the generic deriving. | Lift the standard 'rnf' function through the type constructor. | A class of bifunctors that can be fully evaluated. | 'liftRnf2' should reduce its argument to normal form (that is, fully evaluate all sub-components), given functions to support for generically deriving 'liftRnf2'. | Lift the standard 'rnf' function through the type constructor. | @since 1.4.0.0 | @since 1.4.0.0 @since 1.4.0.0 | @since 1.4.0.0 | This instance is for convenience and consistency with 'seq'. Rational and complex numbers. | @since 1.4.0.0 | @since 1.4.0.0 There isn't an underscore to not break C preprocessor | @since 1.4.0.0 | @since 1.4.0.0 | @since 1.4.0.0 | @since 1.4.0.0 | @since 1.4.0.0 | @since 1.4.0.0 | @since 1.4.0.0 | @since 1.4.0.0 | @since 1.4.0.0 | @since 1.4.0.0 assumes `data ThreadId = ThreadId ThreadId#` | @since 1.4.0.0 assumes `newtype Unique = Unique Integer` | __NOTE__: Prior to @deepseq-1.4.4.0@ this instance was only defined for @base-4.8.0.0@ and later. @since 1.4.0.0 | __NOTE__: Prior to @deepseq-1.4.4.0@ this instance was only defined for @base-4.8.0.0@ and later. @since 1.4.0.0 | __NOTE__: Only strict in the reference and not the referenced value. @since 1.4.2.0 | __NOTE__: Only strict in the reference and not the referenced value. @since 1.4.2.0 | __NOTE__: Only strict in the reference and not the referenced value. @since 1.4.2.0 -------------------------------------------------------------------------- | @since 1.4.0.0 -------------------------------------------------------------------------- Foreign.Ptr -------------------------------------------------------------------------- | @since 1.4.0.0 | @since 1.4.0.0 | @since 1.4.0.0 | @since 1.4.0.0 | @since 1.4.0.0 | @since 1.4.0.0 | @since 1.4.0.0 | @since 1.4.0.0 | @since 1.4.0.0 | @since 1.4.0.0 | @since 1.4.0.0 | @since 1.4.0.0 | @since 1.4.0.0 | @since 1.4.0.0 | @since 1.4.0.0 | @since 1.4.0.0 | @since 1.4.0.0 | @since 1.4.0.0 | @since 1.4.0.0 | @since 1.4.0.0 | @since 1.4.0.0 | @since 1.4.0.0 | @since 1.4.0.0 | @since 1.4.0.0 | @since 1.4.0.0 newtype wrappers rather defined as field-less single-constructor types. | @since 1.4.0.0 | @since 1.4.0.0 | @since 1.4.0.0 -------------------------------------------------------------------------- System.Exit -------------------------------------------------------------------------- instances previously provided by semigroups package |@since 1.4.2.0 -------------------------------------------------------------------------- GHC.Stack -------------------------------------------------------------------------- Code below is generated, see generate-nfdata-tuple.hs -------------------------------------------------------------------------- |@since 1.4.8.0
# LANGUAGE CPP # # LANGUAGE DefaultSignatures # # LANGUAGE EmptyCase # # LANGUAGE FlexibleContexts # # LANGUAGE FlexibleInstances # # LANGUAGE MultiParamTypeClasses # # LANGUAGE PolyKinds # # LANGUAGE QuantifiedConstraints # # LANGUAGE TypeFamilies # # LANGUAGE TypeOperators # #if __GLASGOW_HASKELL__ >= 811 && __GLASGOW_HASKELL__ < 901 For the Option instance ( ) # OPTIONS_GHC -Wno - deprecations # #endif Module : Control . Copyright : ( c ) The University of Glasgow 2001 - 2009 > import Control . > evaluate ( rnf s ) > for example , ' seq ' will evaluate only to the first constructor in > > [ 1,2,undefined ] ` seq ` 3 > 3 > > [ 1,2,undefined ] ` deepseq ` 3 exception handler , or to force evaluation of a data structure in one module Control.DeepSeq ( NFData (rnf), deepseq, force, ($!!), (<$!!>), rwhnf, * of the ' NFData ' class NFData1 (liftRnf), rnf1, NFData2 (liftRnf2), rnf2, ) where import Control.Applicative import Control.Concurrent (MVar, ThreadId) import Control.Exception (MaskingState (..)) import Data.Array import Data.Complex import Data.Fixed import Data.Functor.Compose import Data.Functor.Identity (Identity (..)) import qualified Data.Functor.Product as Functor import qualified Data.Functor.Sum as Functor import Data.IORef import Data.Int import Data.List.NonEmpty (NonEmpty (..)) import Data.Monoid as Mon import Data.Ord (Down (Down)) import Data.Proxy (Proxy (Proxy)) import Data.Ratio import Data.STRef import Data.Semigroup as Semi import Data.Type.Equality ((:~:), (:~~:)) import Data.Typeable (TyCon, TypeRep, rnfTyCon, rnfTypeRep) import Data.Unique (Unique) import Data.Version import Data.Void (Void, absurd) import Data.Word import Foreign.C.Types import Foreign.Ptr import GHC.Fingerprint.Type (Fingerprint (..)) import GHC.Generics import GHC.Stack.Types (CallStack (..), SrcLoc (..)) import Numeric.Natural (Natural) import System.Exit (ExitCode (..)) import System.Mem.StableName (StableName) import qualified Type.Reflection as Reflection #ifdef MIN_VERSION_ghc_prim #if MIN_VERSION_ghc_prim(0,7,0) import GHC.Tuple (Solo (..)) #endif #endif #if MIN_VERSION_base(4,17,0) import Data.Array.Byte (ByteArray(..), MutableByteArray(..)) #endif class GNFData arity f where grnf :: RnfArgs arity a -> f a -> () instance GNFData arity V1 where grnf _ x = case x of {} data Zero data One data family RnfArgs arity a data instance RnfArgs Zero a = RnfArgs0 newtype instance RnfArgs One a = RnfArgs1 (a -> ()) instance GNFData arity U1 where grnf _ U1 = () instance NFData a => GNFData arity (K1 i a) where grnf _ = rnf . unK1 # INLINEABLE grnf # instance GNFData arity a => GNFData arity (M1 i c a) where grnf args = grnf args . unM1 # INLINEABLE grnf # instance GNFData arity (URec a) where Every URec data instance consists of a single data any URec instance to WHNF suffices to reduce it to NF . # INLINEABLE grnf # instance (GNFData arity a, GNFData arity b) => GNFData arity (a :*: b) where grnf args (x :*: y) = grnf args x `seq` grnf args y # INLINEABLE grnf # instance (GNFData arity a, GNFData arity b) => GNFData arity (a :+: b) where grnf args (L1 x) = grnf args x grnf args (R1 x) = grnf args x # INLINEABLE grnf # instance GNFData One Par1 where grnf (RnfArgs1 r) = r . unPar1 instance NFData1 f => GNFData One (Rec1 f) where grnf (RnfArgs1 r) = liftRnf r . unRec1 instance (NFData1 f, GNFData One g) => GNFData One (f :.: g) where grnf args = liftRnf (grnf args) . unComp1 infixr 0 $!! infixr 0 `deepseq` | ' deepseq ' : fully evaluates the first argument , before returning the second . also useful in conjunction with parallel Strategies ( see the deepseq :: NFData a => a -> b -> b deepseq a b = rnf a `seq` b | the deep analogue of ' $ ! ' . In the expression @f $ ! ! , @x@ is fully evaluated before the function @f@ is applied to it . @since 1.2.0.0 ($!!) :: (NFData a) => (a -> b) -> a -> b f $!! x = x `deepseq` f x @force x@ fully evaluates @x@ , and then returns it . Note that @force x@ only performs evaluation when the value of @force x@ ' force ' can be conveniently used in combination with : > { - # LANGUAGE BangPatterns , ViewPatterns # - } > import Control . > someFun : : ComplexData - > SomeResult ' Control.Exception.evaluate ' in order to force deep evaluation > import Control . Finally , here 's an exception safe variant of the @readFile'@ example : @since 1.2.0.0 force :: (NFData a) => a -> a force x = x `deepseq` x @since 1.4.3.0 (<$!!>) :: (Monad m, NFData b) => (a -> b) -> m a -> m b f <$!!> m = m >>= \x -> pure $!! f x infixl 4 <$!!> Useful for defining ' NFData ' for types for which NF = WHNF holds . @since 1.4.3.0 rwhnf :: a -> () rwhnf = (`seq` ()) # INLINE rwhnf # class NFData a where Starting with GHC 7.2 , you can automatically derive instances for types possessing a ' Generic ' instance . Note : ' Generic1 ' can be auto - derived starting with GHC 7.4 > import ( Generic , Generic1 ) > import Control . > data a = Foo a String > deriving ( Eq , Generic , Generic1 ) > instance NFData a = > NFData ( a ) > instance > deriving Generic > instance NFData Colour Starting with GHC 7.10 , the example above can be written more concisely by enabling the new extension : > import ( Generic ) > import Control . > data a = Foo a String > deriving ( Eq , Generic , Generic1 , NFData , NFData1 ) > deriving ( Generic , NFData ) @'rnf ' a = ' seq ' a ( ) @ However , starting with @deepseq-1.4.0.0@ , the default > instance NFData Colour where rnf x = seq x ( ) > instance NFData Colour where rnf = rwhnf > instance NFData Colour where rnf ! _ = ( ) rnf :: a -> () default rnf :: (Generic a, GNFData Zero (Rep a)) => a -> () rnf = grnf RnfArgs0 . from In ` deepseq-1.5.0.0 ` this class was updated to include superclasses . @since 1.4.3.0 class (forall a. NFData a => NFData (f a)) => NFData1 f where | ' liftRnf ' should reduce its argument to normal form ( that is , fully liftRnf :: (a -> ()) -> f a -> () default liftRnf :: (Generic1 f, GNFData One (Rep1 f)) => (a -> ()) -> f a -> () liftRnf r = grnf (RnfArgs1 r) . from1 @since 1.4.3.0 rnf1 :: (NFData1 f, NFData a) => f a -> () rnf1 = liftRnf rnf In ` deepseq-1.5.0.0 ` this class was updated to include superclasses . @since 1.4.3.0 class (forall a. NFData a => NFData1 (p a)) => NFData2 p where reduce @a@ and @b@ arguments respectively , and then return ' ( ) ' . _ _ Note _ _ : Unlike for the unary ' liftRnf ' , there is currently no liftRnf2 :: (a -> ()) -> (b -> ()) -> p a b -> () @since 1.4.3.0 rnf2 :: (NFData2 p, NFData a, NFData b) => p a b -> () rnf2 = liftRnf2 rnf rnf instance NFData Int where rnf = rwhnf instance NFData Word where rnf = rwhnf instance NFData Integer where rnf = rwhnf instance NFData Float where rnf = rwhnf instance NFData Double where rnf = rwhnf instance NFData Char where rnf = rwhnf instance NFData Bool where rnf = rwhnf instance NFData Ordering where rnf = rwhnf instance NFData () where rnf = rwhnf instance NFData Int8 where rnf = rwhnf instance NFData Int16 where rnf = rwhnf instance NFData Int32 where rnf = rwhnf instance NFData Int64 where rnf = rwhnf instance NFData Word8 where rnf = rwhnf instance NFData Word16 where rnf = rwhnf instance NFData Word32 where rnf = rwhnf instance NFData Word64 where rnf = rwhnf | @since 1.4.4.0 instance NFData MaskingState where rnf = rwhnf instance NFData (Proxy a) where rnf Proxy = () | @since 1.4.3.0 instance NFData1 Proxy where liftRnf _ Proxy = () | @since 1.4.3.0 instance NFData (a :~: b) where rnf = rwhnf | @since 1.4.3.0 instance NFData1 ((:~:) a) where liftRnf _ = rwhnf | @since 1.4.3.0 instance NFData2 (:~:) where liftRnf2 _ _ = rwhnf | @since 1.4.3.0 instance NFData (a :~~: b) where rnf = rwhnf | @since 1.4.3.0 instance NFData1 ((:~~:) a) where liftRnf _ = rwhnf | @since 1.4.3.0 instance NFData2 (:~~:) where liftRnf2 _ _ = rwhnf instance NFData a => NFData (Identity a) where rnf = rnf1 | @since 1.4.3.0 instance NFData1 Identity where liftRnf r = r . runIdentity | Defined as @'rnf ' = ' absurd'@. instance NFData Void where rnf = absurd instance NFData Natural where rnf = rwhnf | @since 1.3.0.0 instance NFData (Fixed a) where rnf = rwhnf | @since 1.4.3.0 instance NFData1 Fixed where liftRnf _ = rwhnf This assumes that WHNF is equivalent to NF for functions . @since 1.3.0.0 instance NFData (a -> b) where rnf = rwhnf | Available on @base > = 4.9@ @since 1.4.3.0 instance NFData1 Ratio where liftRnf r x = r (numerator x) `seq` r (denominator x) | @since 1.4.3.0 instance (NFData1 f, NFData1 g) => NFData1 (Compose f g) where liftRnf r = liftRnf (liftRnf r) . getCompose | Note : in @deepseq-1.5.0.0@ this instance 's superclasses were changed . @since 1.4.3.0 instance (NFData (f (g a))) => NFData (Compose f g a) where rnf (Compose fga) = rnf fga | @since 1.4.3.0 instance (NFData1 f, NFData1 g) => NFData1 (Functor.Sum f g) where liftRnf rnf0 (Functor.InL l) = liftRnf rnf0 l liftRnf rnf0 (Functor.InR r) = liftRnf rnf0 r | Note : in @deepseq-1.5.0.0@ this instance 's superclasses were changed . @since 1.4.3.0 instance (NFData (f a), NFData (g a)) => NFData (Functor.Sum f g a) where rnf (Functor.InL fa) = rnf fa rnf (Functor.InR ga) = rnf ga | @since 1.4.3.0 instance (NFData1 f, NFData1 g) => NFData1 (Functor.Product f g) where liftRnf rnf0 (Functor.Pair f g) = liftRnf rnf0 f `seq` liftRnf rnf0 g | Note : in @deepseq-1.5.0.0@ this instance 's superclasses were changed . @since 1.4.3.0 instance (NFData (f a), NFData (g a)) => NFData (Functor.Product f g a) where rnf (Functor.Pair fa ga) = rnf fa `seq` rnf ga instance NFData a => NFData (Ratio a) where rnf x = rnf (numerator x, denominator x) instance (NFData a) => NFData (Complex a) where rnf (x :+ y) = rnf x `seq` rnf y `seq` () instance NFData a => NFData (Maybe a) where rnf = rnf1 | @since 1.4.3.0 instance NFData1 Maybe where liftRnf _r Nothing = () liftRnf r (Just x) = r x instance (NFData a, NFData b) => NFData (Either a b) where rnf = rnf1 | @since 1.4.3.0 instance (NFData a) => NFData1 (Either a) where liftRnf = liftRnf2 rnf | @since 1.4.3.0 instance NFData2 Either where liftRnf2 l _r (Left x) = l x liftRnf2 _l r (Right y) = r y | @since 1.3.0.0 instance NFData Data.Version.Version where rnf (Data.Version.Version branch tags) = rnf branch `seq` rnf tags instance NFData a => NFData [a] where rnf = rnf1 | @since 1.4.3.0 instance NFData1 [] where liftRnf r = go where go [] = () go (x : xs) = r x `seq` go xs instance NFData a => NFData (ZipList a) where rnf = rnf1 | @since 1.4.3.0 instance NFData1 ZipList where liftRnf r = liftRnf r . getZipList instance NFData a => NFData (Const a b) where rnf = rnf . getConst | @since 1.4.3.0 instance NFData a => NFData1 (Const a) where liftRnf _ = rnf . getConst | @since 1.4.3.0 instance NFData2 Const where liftRnf2 r _ = r . getConst We should use array(0,5,1,1 ) but that 's not possible . instance (NFData a, NFData b) => NFData (Array a b) where rnf x = rnf (bounds x, Data.Array.elems x) | @since 1.4.3.0 instance (NFData a) => NFData1 (Array a) where liftRnf r x = rnf (bounds x) `seq` liftRnf r (Data.Array.elems x) | @since 1.4.3.0 instance NFData2 Array where liftRnf2 r r' x = liftRnf2 r r (bounds x) `seq` liftRnf r' (Data.Array.elems x) instance NFData a => NFData (Down a) where rnf = rnf1 | @since 1.4.3.0 instance NFData1 Down where liftRnf r (Down x) = r x instance NFData a => NFData (Dual a) where rnf = rnf1 | @since 1.4.3.0 instance NFData1 Dual where liftRnf r (Dual x) = r x instance NFData a => NFData (Mon.First a) where rnf = rnf1 | @since 1.4.3.0 instance NFData1 Mon.First where liftRnf r (Mon.First x) = liftRnf r x instance NFData a => NFData (Mon.Last a) where rnf = rnf1 | @since 1.4.3.0 instance NFData1 Mon.Last where liftRnf r (Mon.Last x) = liftRnf r x instance NFData Any where rnf = rnf . getAny instance NFData All where rnf = rnf . getAll instance NFData a => NFData (Sum a) where rnf = rnf1 | @since 1.4.3.0 instance NFData1 Sum where liftRnf r (Sum x) = r x instance NFData a => NFData (Product a) where rnf = rnf1 | @since 1.4.3.0 instance NFData1 Product where liftRnf r (Product x) = r x instance NFData (StableName a) where assumes ` data StableName a = StableName ( StableName # a ) ` | @since 1.4.3.0 instance NFData1 StableName where liftRnf _ = rwhnf instance NFData ThreadId where instance NFData Unique where instance NFData TypeRep where rnf tyrep = rnfTypeRep tyrep instance NFData TyCon where rnf tycon = rnfTyCon tycon | @since 1.4.8.0 instance NFData (Reflection.TypeRep a) where rnf tr = Reflection.rnfTypeRep tr | @since 1.4.8.0 instance NFData Reflection.Module where rnf modul = Reflection.rnfModule modul instance NFData (IORef a) where rnf = rwhnf | @since 1.4.3.0 instance NFData1 IORef where liftRnf _ = rwhnf instance NFData (STRef s a) where rnf = rwhnf | @since 1.4.3.0 instance NFData1 (STRef s) where liftRnf _ = rwhnf | @since 1.4.3.0 instance NFData2 STRef where liftRnf2 _ _ = rwhnf instance NFData (MVar a) where rnf = rwhnf | @since 1.4.3.0 instance NFData1 MVar where liftRnf _ = rwhnf GHC Specifics instance NFData Fingerprint where rnf (Fingerprint _ _) = () | @since 1.4.2.0 instance NFData (Ptr a) where rnf = rwhnf | @since 1.4.3.0 instance NFData1 Ptr where liftRnf _ = rwhnf | @since 1.4.2.0 instance NFData (FunPtr a) where rnf = rwhnf | @since 1.4.3.0 instance NFData1 FunPtr where liftRnf _ = rwhnf Foreign . C.Types instance NFData CChar where rnf = rwhnf instance NFData CSChar where rnf = rwhnf instance NFData CUChar where rnf = rwhnf instance NFData CShort where rnf = rwhnf instance NFData CUShort where rnf = rwhnf instance NFData CInt where rnf = rwhnf instance NFData CUInt where rnf = rwhnf instance NFData CLong where rnf = rwhnf instance NFData CULong where rnf = rwhnf instance NFData CPtrdiff where rnf = rwhnf instance NFData CSize where rnf = rwhnf instance NFData CWchar where rnf = rwhnf instance NFData CSigAtomic where rnf = rwhnf instance NFData CLLong where rnf = rwhnf instance NFData CULLong where rnf = rwhnf instance NFData CIntPtr where rnf = rwhnf instance NFData CUIntPtr where rnf = rwhnf instance NFData CIntMax where rnf = rwhnf instance NFData CUIntMax where rnf = rwhnf instance NFData CClock where rnf = rwhnf instance NFData CTime where rnf = rwhnf instance NFData CUSeconds where rnf = rwhnf instance NFData CSUSeconds where rnf = rwhnf instance NFData CFloat where rnf = rwhnf instance NFData CDouble where rnf = rwhnf NOTE : The types ` CFile ` , ` CFPos ` , and ` CJmpBuf ` below are not instance NFData CFile where rnf = rwhnf instance NFData CFpos where rnf = rwhnf instance NFData CJmpBuf where rnf = rwhnf | @since 1.4.3.0 instance NFData CBool where rnf = rwhnf | @since 1.4.2.0 instance NFData ExitCode where rnf (ExitFailure n) = rnf n rnf ExitSuccess = () | @since 1.4.2.0 instance NFData a => NFData (NonEmpty a) where rnf = rnf1 | @since 1.4.3.0 instance NFData1 NonEmpty where liftRnf r (x :| xs) = r x `seq` liftRnf r xs | @since 1.4.2.0 instance NFData a => NFData (Min a) where rnf = rnf1 | @since 1.4.3.0 instance NFData1 Min where liftRnf r (Min a) = r a | @since 1.4.2.0 instance NFData a => NFData (Max a) where rnf = rnf1 | @since 1.4.3.0 instance NFData1 Max where liftRnf r (Max a) = r a | @since 1.4.2.0 instance (NFData a, NFData b) => NFData (Arg a b) where rnf = rnf2 | @since 1.4.3.0 instance (NFData a) => NFData1 (Arg a) where liftRnf = liftRnf2 rnf | @since 1.4.3.0 instance NFData2 Arg where liftRnf2 r r' (Arg a b) = r a `seq` r' b `seq` () | @since 1.4.2.0 instance NFData a => NFData (Semi.First a) where rnf = rnf1 | @since 1.4.3.0 instance NFData1 Semi.First where liftRnf r (Semi.First a) = r a | @since 1.4.2.0 instance NFData a => NFData (Semi.Last a) where rnf = rnf1 | @since 1.4.3.0 instance NFData1 Semi.Last where liftRnf r (Semi.Last a) = r a | @since 1.4.2.0 instance NFData m => NFData (WrappedMonoid m) where rnf = rnf1 | @since 1.4.3.0 instance NFData1 WrappedMonoid where liftRnf r (WrapMonoid a) = r a #if __GLASGOW_HASKELL__ < 901 instance NFData a => NFData (Option a) where rnf = rnf1 |@since 1.4.3.0 instance NFData1 Option where liftRnf r (Option a) = liftRnf r a #endif | @since 1.4.2.0 instance NFData SrcLoc where rnf (SrcLoc a b c d e f g) = rnf a `seq` rnf b `seq` rnf c `seq` rnf d `seq` rnf e `seq` rnf f `seq` rnf g | @since 1.4.2.0 instance NFData CallStack where rnf EmptyCallStack = () rnf (PushCallStack a b c) = rnf a `seq` rnf b `seq` rnf c rnf (FreezeCallStack a) = rnf a Tuples #ifdef MIN_VERSION_ghc_prim #if MIN_VERSION_ghc_prim(0,7,0) |@since 1.4.6.0 instance NFData a => NFData (Solo a) where #if MIN_VERSION_ghc_prim(0,10,0) rnf (MkSolo a) = rnf a #else rnf (Solo a) = rnf a #endif |@since 1.4.6.0 instance NFData1 Solo where #if MIN_VERSION_ghc_prim(0,10,0) liftRnf r (MkSolo a) = r a #else liftRnf r (Solo a) = r a #endif #endif #endif instance (NFData a, NFData b) => NFData (a, b) where rnf = rnf2 | @since 1.4.3.0 instance (NFData a) => NFData1 ((,) a) where liftRnf = liftRnf2 rnf | @since 1.4.3.0 instance NFData2 (,) where liftRnf2 r r' (x, y) = r x `seq` r' y instance (NFData a1, NFData a2, NFData a3) => NFData (a1, a2, a3) where rnf = rnf2 | @since 1.4.3.0 instance (NFData a1, NFData a2) => NFData1 ((,,) a1 a2) where liftRnf = liftRnf2 rnf | @since 1.4.3.0 instance (NFData a1) => NFData2 ((,,) a1) where liftRnf2 r r' (x1, x2, x3) = rnf x1 `seq` r x2 `seq` r' x3 instance (NFData a1, NFData a2, NFData a3, NFData a4) => NFData (a1, a2, a3, a4) where rnf = rnf2 | @since 1.4.3.0 instance (NFData a1, NFData a2, NFData a3) => NFData1 ((,,,) a1 a2 a3) where liftRnf = liftRnf2 rnf | @since 1.4.3.0 instance (NFData a1, NFData a2) => NFData2 ((,,,) a1 a2) where liftRnf2 r r' (x1, x2, x3, x4) = rnf x1 `seq` rnf x2 `seq` r x3 `seq` r' x4 instance (NFData a1, NFData a2, NFData a3, NFData a4, NFData a5) => NFData (a1, a2, a3, a4, a5) where rnf = rnf2 | @since 1.4.3.0 instance (NFData a1, NFData a2, NFData a3, NFData a4) => NFData1 ((,,,,) a1 a2 a3 a4) where liftRnf = liftRnf2 rnf | @since 1.4.3.0 instance (NFData a1, NFData a2, NFData a3) => NFData2 ((,,,,) a1 a2 a3) where liftRnf2 r r' (x1, x2, x3, x4, x5) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` r x4 `seq` r' x5 instance (NFData a1, NFData a2, NFData a3, NFData a4, NFData a5, NFData a6) => NFData (a1, a2, a3, a4, a5, a6) where rnf = rnf2 | @since 1.4.3.0 instance (NFData a1, NFData a2, NFData a3, NFData a4, NFData a5) => NFData1 ((,,,,,) a1 a2 a3 a4 a5) where liftRnf = liftRnf2 rnf | @since 1.4.3.0 instance (NFData a1, NFData a2, NFData a3, NFData a4) => NFData2 ((,,,,,) a1 a2 a3 a4) where liftRnf2 r r' (x1, x2, x3, x4, x5, x6) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` r x5 `seq` r' x6 instance (NFData a1, NFData a2, NFData a3, NFData a4, NFData a5, NFData a6, NFData a7) => NFData (a1, a2, a3, a4, a5, a6, a7) where rnf = rnf2 | @since 1.4.3.0 instance (NFData a1, NFData a2, NFData a3, NFData a4, NFData a5, NFData a6) => NFData1 ((,,,,,,) a1 a2 a3 a4 a5 a6) where liftRnf = liftRnf2 rnf | @since 1.4.3.0 instance (NFData a1, NFData a2, NFData a3, NFData a4, NFData a5) => NFData2 ((,,,,,,) a1 a2 a3 a4 a5) where liftRnf2 r r' (x1, x2, x3, x4, x5, x6, x7) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` rnf x5 `seq` r x6 `seq` r' x7 instance (NFData a1, NFData a2, NFData a3, NFData a4, NFData a5, NFData a6, NFData a7, NFData a8) => NFData (a1, a2, a3, a4, a5, a6, a7, a8) where rnf = rnf2 | @since 1.4.3.0 instance (NFData a1, NFData a2, NFData a3, NFData a4, NFData a5, NFData a6, NFData a7) => NFData1 ((,,,,,,,) a1 a2 a3 a4 a5 a6 a7) where liftRnf = liftRnf2 rnf | @since 1.4.3.0 instance (NFData a1, NFData a2, NFData a3, NFData a4, NFData a5, NFData a6) => NFData2 ((,,,,,,,) a1 a2 a3 a4 a5 a6) where liftRnf2 r r' (x1, x2, x3, x4, x5, x6, x7, x8) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` rnf x5 `seq` rnf x6 `seq` r x7 `seq` r' x8 instance (NFData a1, NFData a2, NFData a3, NFData a4, NFData a5, NFData a6, NFData a7, NFData a8, NFData a9) => NFData (a1, a2, a3, a4, a5, a6, a7, a8, a9) where rnf = rnf2 | @since 1.4.3.0 instance (NFData a1, NFData a2, NFData a3, NFData a4, NFData a5, NFData a6, NFData a7, NFData a8) => NFData1 ((,,,,,,,,) a1 a2 a3 a4 a5 a6 a7 a8) where liftRnf = liftRnf2 rnf | @since 1.4.3.0 instance (NFData a1, NFData a2, NFData a3, NFData a4, NFData a5, NFData a6, NFData a7) => NFData2 ((,,,,,,,,) a1 a2 a3 a4 a5 a6 a7) where liftRnf2 r r' (x1, x2, x3, x4, x5, x6, x7, x8, x9) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` rnf x5 `seq` rnf x6 `seq` rnf x7 `seq` r x8 `seq` r' x9 ByteArray #if MIN_VERSION_base(4,17,0) |@since 1.4.7.0 instance NFData ByteArray where rnf (ByteArray _) = () instance NFData (MutableByteArray s) where rnf (MutableByteArray _) = () #endif
600e803aa74a78a10fa40e8b54acebf1cb82f6dcee8ed69a3f58d443e5d8544f
BranchTaken/Hemlock
test_hd.ml
open! Basis.Rudiments open! Basis open Q let test () = let rec fn i n t = begin match i <= n with | false -> () | true -> begin let elm = hd t in File.Fmt.stdout |> Fmt.fmt "hd " |> (pp Uns.pp) t |> Fmt.fmt " = " |> Uns.pp elm |> Fmt.fmt "\n" |> ignore; fn (succ i) n (push_back i t) end end in (* halts if we start with empty *) fn 1L 4L (push_back 0L empty) let _ = test ()
null
https://raw.githubusercontent.com/BranchTaken/Hemlock/f3604ceda4f75cf18b6ee2b1c2f3c5759ad495a5/bootstrap/test/basis/q/test_hd.ml
ocaml
halts if we start with empty
open! Basis.Rudiments open! Basis open Q let test () = let rec fn i n t = begin match i <= n with | false -> () | true -> begin let elm = hd t in File.Fmt.stdout |> Fmt.fmt "hd " |> (pp Uns.pp) t |> Fmt.fmt " = " |> Uns.pp elm |> Fmt.fmt "\n" |> ignore; fn (succ i) n (push_back i t) end end in fn 1L 4L (push_back 0L empty) let _ = test ()
e30fbda146978dcde1be417444c34027f384c3e0e6e0d1884a8d616fed23693b
braidchat/braid
core.cljc
(ns braid.embeds-website.core "If a message contains a link, displays a generic website embed" (:require [braid.base.api :as base] [braid.embeds.api :as embeds] #?@(:cljs [[braid.embeds-website.styles :as styles] [braid.embeds-website.views :as views]] :clj [[braid.embeds-website.link-extract :as link-extract]])) #?(:clj (:import (java.net URLDecoder)))) (defn init! [] #?(:cljs (do (embeds/register-embed! {:handler views/handler :styles styles/styles :priority -1})) :clj (do (base/register-public-http-route! [:get "/extract" (fn [request] (let [url (URLDecoder/decode (get-in request [:params :url]))] {:body (link-extract/extract url)}))]))))
null
https://raw.githubusercontent.com/braidchat/braid/2e44eb6e77f1d203115f9b9c529bd865fa3d7302/src/braid/embeds_website/core.cljc
clojure
(ns braid.embeds-website.core "If a message contains a link, displays a generic website embed" (:require [braid.base.api :as base] [braid.embeds.api :as embeds] #?@(:cljs [[braid.embeds-website.styles :as styles] [braid.embeds-website.views :as views]] :clj [[braid.embeds-website.link-extract :as link-extract]])) #?(:clj (:import (java.net URLDecoder)))) (defn init! [] #?(:cljs (do (embeds/register-embed! {:handler views/handler :styles styles/styles :priority -1})) :clj (do (base/register-public-http-route! [:get "/extract" (fn [request] (let [url (URLDecoder/decode (get-in request [:params :url]))] {:body (link-extract/extract url)}))]))))
e78eb08bcad9463fe5a469223c10f6f152049d6f2a1c303c66676a183e1dd6d1
mbenke/zpf2013
sudoku-par2.hs
import Sudoku import Control.Exception import System.Environment import Data.Maybe import Control.Monad.Par main :: IO () main = do [f] <- getArgs grids <- fmap lines $ readFile f let (as,bs) = splitAt (length grids `div` 2) grids print $ length $ filter isJust $ runPar $ do i1 <- new i2 <- new fork $ put i1 (map solve as) fork $ put i2 (map solve bs) as' <- get i1 bs' <- get i2 return (as' ++ bs')
null
https://raw.githubusercontent.com/mbenke/zpf2013/85f32747e17f07a74e1c3cb064b1d6acaca3f2f0/Code/Par/Marlow/sudoku-par2.hs
haskell
import Sudoku import Control.Exception import System.Environment import Data.Maybe import Control.Monad.Par main :: IO () main = do [f] <- getArgs grids <- fmap lines $ readFile f let (as,bs) = splitAt (length grids `div` 2) grids print $ length $ filter isJust $ runPar $ do i1 <- new i2 <- new fork $ put i1 (map solve as) fork $ put i2 (map solve bs) as' <- get i1 bs' <- get i2 return (as' ++ bs')
b99f228fb3fa4ebd89d8997aa657d499a7ea1c46b5dd9644bfcbb52f70b79ef0
holyjak/fulcro-billing-app
charge.cljc
(ns billing-app.model.billing.invoice.charge "A single invoice line - an employee X is charged some amount for a particular service" (:refer-clojure :exclude [name]) (:require #?@(:clj [[com.wsscode.pathom.connect :as pc :refer [defmutation]] [billing-app.components.billing-data :as billing-data] [billing-app.model.cache :as dev]] :cljs [[com.fulcrologic.fulcro.mutations :as m :refer [defmutation]]]) [clojure.string :as str] [com.wsscode.pathom.connect :as pc] [com.fulcrologic.rad.attributes :as attr :refer [defattr]] [com.fulcrologic.rad.attributes-options :as ao] [com.fulcrologic.rad.report-options :as ro])) A synthetic ID composed of invoice - id : : idx b / c RAD and Pathom require that everything has a simple ID of its own (defattr synt-id :charge/synt-id :string {ao/identity? true}) (defattr service-name :charge/service-name :string we could leave ao / identities since RAD auto - generated resolvers do not work with composed PK anyway (defattr usage :charge/usage :decimal {ao/identities #{:charge/synt-id}}) (defattr period-from :charge/period-from :inst {ao/identities #{:charge/synt-id}}) (defattr period-to :charge/period-to :inst {ao/identities #{:charge/synt-id}}) (defattr included? "True if the charge is included in the resulting usage, false if it is ignored due to business rules." :charge/included? :boolean {ao/identities #{:charge/synt-id}}) (defn charge-view [invoice-id idx {:kd/keys [sid usage-inc-vat] :keys [period serviceType chargeType] {:keys [invoice name]} :debug :as charge}] (merge (select-keys charge [:kd/charge-type]) {:charge/synt-id (clojure.string/join ":" [invoice-id sid idx]) :charge/invoice invoice :charge/included? (:billing-app.components.billing-data/included? charge) :charge/charge-type chargeType :charge/service-name name :charge/service-type serviceType :charge/usage usage-inc-vat :charge/period-from (:billing/startDate period) :charge/period-to (:billing/endDate period)})) #?(:clj (pc/defresolver invoice-employee-charges [env _] {::pc/input #{} ::pc/output [{:invoice-employee-charges [:charge/synt-id :charge/invoice :charge/charge-type :charge/service-name :charge/service-type :charge/usage :charge/period-from :charge/period-to :charge/included? ;; Extra props: :kd/charge-type]}]} (let [ds (get-in env [:com.fulcrologic.rad.database-adapters.sql/connection-pools :billing]) {invoice-id :invoice/id sid :br-employee/employee-id} (:query-params env) _ (do (assert invoice-id) (assert sid)) batches (->> (dev/caching #'billing-data/employee-batches ds invoice-id sid) (apply concat) (map-indexed (partial charge-view invoice-id)) (remove (comp zero? :charge/usage)) (sort-by :charge/usage) (reverse) vec)] {:invoice-employee-charges batches}))) (def attributes [synt-id service-name usage period-from period-to included?])
null
https://raw.githubusercontent.com/holyjak/fulcro-billing-app/568bf28552989e1e611773b2d946c9990e1edc3d/src/shared/billing_app/model/billing/invoice/charge.cljc
clojure
Extra props:
(ns billing-app.model.billing.invoice.charge "A single invoice line - an employee X is charged some amount for a particular service" (:refer-clojure :exclude [name]) (:require #?@(:clj [[com.wsscode.pathom.connect :as pc :refer [defmutation]] [billing-app.components.billing-data :as billing-data] [billing-app.model.cache :as dev]] :cljs [[com.fulcrologic.fulcro.mutations :as m :refer [defmutation]]]) [clojure.string :as str] [com.wsscode.pathom.connect :as pc] [com.fulcrologic.rad.attributes :as attr :refer [defattr]] [com.fulcrologic.rad.attributes-options :as ao] [com.fulcrologic.rad.report-options :as ro])) A synthetic ID composed of invoice - id : : idx b / c RAD and Pathom require that everything has a simple ID of its own (defattr synt-id :charge/synt-id :string {ao/identity? true}) (defattr service-name :charge/service-name :string we could leave ao / identities since RAD auto - generated resolvers do not work with composed PK anyway (defattr usage :charge/usage :decimal {ao/identities #{:charge/synt-id}}) (defattr period-from :charge/period-from :inst {ao/identities #{:charge/synt-id}}) (defattr period-to :charge/period-to :inst {ao/identities #{:charge/synt-id}}) (defattr included? "True if the charge is included in the resulting usage, false if it is ignored due to business rules." :charge/included? :boolean {ao/identities #{:charge/synt-id}}) (defn charge-view [invoice-id idx {:kd/keys [sid usage-inc-vat] :keys [period serviceType chargeType] {:keys [invoice name]} :debug :as charge}] (merge (select-keys charge [:kd/charge-type]) {:charge/synt-id (clojure.string/join ":" [invoice-id sid idx]) :charge/invoice invoice :charge/included? (:billing-app.components.billing-data/included? charge) :charge/charge-type chargeType :charge/service-name name :charge/service-type serviceType :charge/usage usage-inc-vat :charge/period-from (:billing/startDate period) :charge/period-to (:billing/endDate period)})) #?(:clj (pc/defresolver invoice-employee-charges [env _] {::pc/input #{} ::pc/output [{:invoice-employee-charges [:charge/synt-id :charge/invoice :charge/charge-type :charge/service-name :charge/service-type :charge/usage :charge/period-from :charge/period-to :charge/included? :kd/charge-type]}]} (let [ds (get-in env [:com.fulcrologic.rad.database-adapters.sql/connection-pools :billing]) {invoice-id :invoice/id sid :br-employee/employee-id} (:query-params env) _ (do (assert invoice-id) (assert sid)) batches (->> (dev/caching #'billing-data/employee-batches ds invoice-id sid) (apply concat) (map-indexed (partial charge-view invoice-id)) (remove (comp zero? :charge/usage)) (sort-by :charge/usage) (reverse) vec)] {:invoice-employee-charges batches}))) (def attributes [synt-id service-name usage period-from period-to included?])
d9dad567710e915d2da4e60074dbe650ab0c38f02d5f5e90f70cea0dd3bb8431
practicalli/clojure-through-code
composing_functions.clj
(ns clojure-through-code.composing-functions) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; map over collections with partial ;; We can map over a collection of words and increment them by writing an anonymous function. (map (fn [animal] (str animal "s")) ["pig" "cow" "goat" "cat" "dog" "rabbit"]) ;; or using the syntactic sugar form of an anonymous function we get (map #(str % "s") ["pig" "cow" "goat" "cat" "dog" "rabbit"]) ;; by default map returns a list/sequence. We can specify a vector be returned instead using `mapv' (mapv #(str % "s") ["pig" "cow" "goat" "cat" "dog" "rabbit"]) ;; what about sheep, where the plural is sheep? We would want to add a condition or filter somewhere ;; first lets abstact out the annonymous function (defn pluralise "Pluralise a given string value" [animal] (str animal "s")) ;; and give a name to our collection of animals (def animals ["pig" "cow" "goat" "cat" "dog" "rabbit"]) (map pluralise animals) ;; using an if statement as a filter (defn pluralise "Pluralise a given string value" [string] (if (= string "sheep") string (str string "s"))) (map pluralise animals) ;; but there are quite a lot of animals that do not have a plural form ;; define a collection of animals that are not plural (def non-plural-words ["deer" "sheep" "shrimp" ]) (defn pluralise "Pluralise a given string value" [string] (if (some #{string} non-plural-words) string (str string "s"))) (def animals ["pig" "cow" "goat" "cat" "dog" "rabbit" "sheep" "shrimp" "deer"]) (map pluralise animals) ;; to keep the function pure, we should really pass the non-plural-words as an argument (defn pluralise "Pluralise a given string value" [string non-plural-words] (if (some #{string} non-plural-words) string (str string "s"))) using an anonymous function we can send the two arguments required to the pluralise function , as map will replace the % character with an element from the animals collection for each element in the collection . (map #(pluralise % non-plural-words) animals) (map (fn [animal] (pluralise animal non-plural-words)) animals) ;; we could also use a partial function, saving on having to create an anonymous (defn pluralise "Pluralise a given string value" [non-plural-words string] (if (some #{string} non-plural-words) string (str string "s"))) ;; Now we can call pluralise by wrapping it as a partical function. The argument that is the non-plural-words is constant, its the individual elements of animals I want to get out via map. So when map runs it gets an element from the animals collection and adds it to the call to pluralise, along with non-plural-words (map (partial pluralise non-plural-words) animals) ;;; Its like calling (pluralise non-plural-words ,,,) but each time including an element from animals where the ,,, is. at first I was getting incorrect output , [ " deer " " sheep " " shrimp " ] , then I realised that it was returning the non - plural - words as string , so the arguements from the partial function were being sent in the wrong order . So I simply changed the order in the pluralise function and it worked . I checked this by adding some old - fashioned print statement . There are probably better ways to do that in Clojure though . (defn pluralise "Pluralise a given string value" [non-plural-words string] (if (some #{string} non-plural-words) (do (println (str string " its true")) string) (do (println (str string " its false")) (str string "s")))) ;; comp ;; Takes a set of functions and returns a fn that is the composition of those fns . The returned fn takes a variable number of args , applies the rightmost of fns to the args , the next ;; fn (right-to-left) to the result, etc. ((comp str +) 8 8 8) (filter (comp not zero?) [0 1 0 2 0 3 0 4]) (defn f1 "append 1 to string x" [x] (str x "1")) (defn f2 "append 2 to string x" [x] (str x "2")) (defn f3 "append 3 to string x" [x] (str x "3")) (f1 "a") ; "a1" (def g (comp f3 f2 f1 )) (g "x") ; "x123" ;; (g "a" "x") 1 . Unhandled clojure.lang . ArityException Wrong number of args ( 2 ) passed to : user / f1 because f1 only takes 1 arg ;; example of apply ;; apply just takes all of its args, and feed to the function as multiple args, like unwrap the bracket (apply str ["a" "b"]) ; "ab" " 1ab " " 12ab " ;; here's what str does str takes 1 or more args of string , and return a joined string (str "a" "b") ; "ab" can be just 1 arg (str "a" ) ; "a" ;; if arg is not a string, it's converted to string (str "a" ["a" "b"]) ; "a[\"a\" \"b\"]" (str "a" 1) ; "a1" ;; Applying a sequence with functions that take individual arguments (def my-square [10 8 20 12 4]) (defn draw-square [x y width height corner] (str "X: " x " Y: " y " Width: " width " Height: " height " Corner: " corner)) (apply draw-square my-square) = > " X : 10 Y : 8 Width : 20 Height : 12 Corner : 4 " ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Misc ;; clojure.core/trampoline ;; (trampoline f args) ;; call f with args. If it returns a function, call it again (with no args). Repeat until it returns a value that is not a function, return that value. ;; clojure.core/constantly ;; (constantly x) ;; Returns a function that takes any number of arguments and returns x. ;; clojure.core/complement ;; (complement f) ;; Takes a fn f and returns a fn that takes the same arguments as f, has the same effects, if any, and returns the opposite truth value. ;; clojure.core/memoize ;; (memoize f) ;; Returns a memoized version of a referentially transparent function. The memoized version of the function keeps a cache of the mapping from arguments to results and, when calls with the same arguments are repeated often, has higher performance at the expense of higher memory use. ;;; Processing maps problem ??? ;; you have several maps which have name and id keys. The value of the id becomes the new key and the name becomes the new value. [{:name "mike" :id 0} {:name "mike" :id 0} {:name "mike" :id 0}]
null
https://raw.githubusercontent.com/practicalli/clojure-through-code/82834cdab6b5315aea630386c851200f98d5e48f/src/clojure_through_code/composing_functions.clj
clojure
map over collections with partial We can map over a collection of words and increment them by writing an anonymous function. or using the syntactic sugar form of an anonymous function we get by default map returns a list/sequence. We can specify a vector be returned instead using `mapv' what about sheep, where the plural is sheep? We would want to add a condition or filter somewhere first lets abstact out the annonymous function and give a name to our collection of animals using an if statement as a filter but there are quite a lot of animals that do not have a plural form define a collection of animals that are not plural to keep the function pure, we should really pass the non-plural-words as an argument we could also use a partial function, saving on having to create an anonymous Now we can call pluralise by wrapping it as a partical function. The argument that is the non-plural-words is constant, its the individual elements of animals I want to get out via map. So when map runs it gets an element from the animals collection and adds it to the call to pluralise, along with non-plural-words Its like calling (pluralise non-plural-words ,,,) but each time including an element from animals where the ,,, is. comp Takes a set of functions and returns a fn that is the composition fn (right-to-left) to the result, etc. "a1" "x123" (g "a" "x") example of apply apply just takes all of its args, and feed to the function as multiple args, like unwrap the bracket "ab" here's what str does "ab" "a" if arg is not a string, it's converted to string "a[\"a\" \"b\"]" "a1" Applying a sequence with functions that take individual arguments Misc clojure.core/trampoline (trampoline f args) call f with args. If it returns a function, call it again (with no args). Repeat until it returns a value that is not a function, return that value. clojure.core/constantly (constantly x) Returns a function that takes any number of arguments and returns x. clojure.core/complement (complement f) Takes a fn f and returns a fn that takes the same arguments as f, has the same effects, if any, and returns the opposite truth value. clojure.core/memoize (memoize f) Returns a memoized version of a referentially transparent function. The memoized version of the function keeps a cache of the mapping from arguments to results and, when calls with the same arguments are repeated often, has higher performance at the expense of higher memory use. Processing maps problem ??? you have several maps which have name and id keys. The value of the id becomes the new key and the name becomes the new value.
(ns clojure-through-code.composing-functions) (map (fn [animal] (str animal "s")) ["pig" "cow" "goat" "cat" "dog" "rabbit"]) (map #(str % "s") ["pig" "cow" "goat" "cat" "dog" "rabbit"]) (mapv #(str % "s") ["pig" "cow" "goat" "cat" "dog" "rabbit"]) (defn pluralise "Pluralise a given string value" [animal] (str animal "s")) (def animals ["pig" "cow" "goat" "cat" "dog" "rabbit"]) (map pluralise animals) (defn pluralise "Pluralise a given string value" [string] (if (= string "sheep") string (str string "s"))) (map pluralise animals) (def non-plural-words ["deer" "sheep" "shrimp" ]) (defn pluralise "Pluralise a given string value" [string] (if (some #{string} non-plural-words) string (str string "s"))) (def animals ["pig" "cow" "goat" "cat" "dog" "rabbit" "sheep" "shrimp" "deer"]) (map pluralise animals) (defn pluralise "Pluralise a given string value" [string non-plural-words] (if (some #{string} non-plural-words) string (str string "s"))) using an anonymous function we can send the two arguments required to the pluralise function , as map will replace the % character with an element from the animals collection for each element in the collection . (map #(pluralise % non-plural-words) animals) (map (fn [animal] (pluralise animal non-plural-words)) animals) (defn pluralise "Pluralise a given string value" [non-plural-words string] (if (some #{string} non-plural-words) string (str string "s"))) (map (partial pluralise non-plural-words) animals) at first I was getting incorrect output , [ " deer " " sheep " " shrimp " ] , then I realised that it was returning the non - plural - words as string , so the arguements from the partial function were being sent in the wrong order . So I simply changed the order in the pluralise function and it worked . I checked this by adding some old - fashioned print statement . There are probably better ways to do that in Clojure though . (defn pluralise "Pluralise a given string value" [non-plural-words string] (if (some #{string} non-plural-words) (do (println (str string " its true")) string) (do (println (str string " its false")) (str string "s")))) of those fns . The returned fn takes a variable number of args , applies the rightmost of fns to the args , the next ((comp str +) 8 8 8) (filter (comp not zero?) [0 1 0 2 0 3 0 4]) (defn f1 "append 1 to string x" [x] (str x "1")) (defn f2 "append 2 to string x" [x] (str x "2")) (defn f3 "append 3 to string x" [x] (str x "3")) (def g (comp f3 f2 f1 )) 1 . Unhandled clojure.lang . ArityException Wrong number of args ( 2 ) passed to : user / f1 because f1 only takes 1 arg " 1ab " " 12ab " str takes 1 or more args of string , and return a joined string can be just 1 arg (def my-square [10 8 20 12 4]) (defn draw-square [x y width height corner] (str "X: " x " Y: " y " Width: " width " Height: " height " Corner: " corner)) (apply draw-square my-square) = > " X : 10 Y : 8 Width : 20 Height : 12 Corner : 4 " [{:name "mike" :id 0} {:name "mike" :id 0} {:name "mike" :id 0}]
cce3629c444c35434226d36fd60aa016f521be5afc4ebe55acd2bfdbc541d647
acieroid/scala-am
treiber-stack.scm
; Treiber stack as an example of a lock-free data structure using atoms. (define (new-stack) (atom '())) (define (push stk el) (let loop ((top (read stk))) (if (not (compare-and-set! stk top (cons el top))) (loop (read stk))))) (define (pop stk) (let loop ((top (read stk))) (cond ((null? top) #f) ((compare-and-set! stk top (cdr top)) (car top)) (else (loop (read stk)))))) (define (loop stk n f) (if (> n 0) (let ((next (f stk n))) (loop stk next f)))) (define stack (new-stack)) (define f1 (future (loop stack 25 (lambda (s n) (push s n) (- n 1))))) (define f2 (future (loop stack 25 (lambda (s n) (if (pop s) (- n 1) n))))) (deref f1) (deref f2) (not (pop stack))
null
https://raw.githubusercontent.com/acieroid/scala-am/13ef3befbfc664b77f31f56847c30d60f4ee7dfe/test/concurrentScheme/futures/treiber-stack.scm
scheme
Treiber stack as an example of a lock-free data structure using atoms.
(define (new-stack) (atom '())) (define (push stk el) (let loop ((top (read stk))) (if (not (compare-and-set! stk top (cons el top))) (loop (read stk))))) (define (pop stk) (let loop ((top (read stk))) (cond ((null? top) #f) ((compare-and-set! stk top (cdr top)) (car top)) (else (loop (read stk)))))) (define (loop stk n f) (if (> n 0) (let ((next (f stk n))) (loop stk next f)))) (define stack (new-stack)) (define f1 (future (loop stack 25 (lambda (s n) (push s n) (- n 1))))) (define f2 (future (loop stack 25 (lambda (s n) (if (pop s) (- n 1) n))))) (deref f1) (deref f2) (not (pop stack))
47c888d5511cb4bb3a781016d2fa6aa25f06fb858356118c0d36addabe8c0421
channable/alfred-margaret
Main.hs
module Main where import Test.Hspec (describe, hspec) import Data.Text.AhoCorasickSpec as AhoCorasickSpec import Data.Text.BoyerMooreSpec as BoyerMooreSpec import Data.Text.BoyerMooreCISpec as BoyerMooreCISpec import Data.Text.Utf8Spec as Utf8Spec main :: IO () main = hspec $ do describe "Data.Text.AhoCorasick" AhoCorasickSpec.spec describe "Data.Text.BoyerMoore" BoyerMooreSpec.spec describe "Data.Text.BoyerMooreCI" BoyerMooreCISpec.spec describe "Data.Text.Utf8" Utf8Spec.spec
null
https://raw.githubusercontent.com/channable/alfred-margaret/be96f07bb74c5aa65ce01d664de5d98badbee307/tests/Main.hs
haskell
module Main where import Test.Hspec (describe, hspec) import Data.Text.AhoCorasickSpec as AhoCorasickSpec import Data.Text.BoyerMooreSpec as BoyerMooreSpec import Data.Text.BoyerMooreCISpec as BoyerMooreCISpec import Data.Text.Utf8Spec as Utf8Spec main :: IO () main = hspec $ do describe "Data.Text.AhoCorasick" AhoCorasickSpec.spec describe "Data.Text.BoyerMoore" BoyerMooreSpec.spec describe "Data.Text.BoyerMooreCI" BoyerMooreCISpec.spec describe "Data.Text.Utf8" Utf8Spec.spec
4b8fd969445183945a8e62996318021a34cc034f139abc868c60e05e5fac1c5b
odis-labs/onix
Onix_lock_opam.ml
let gen ~opam_lock_file_path lock_file = Onix_core.Utils.Out_channel.with_open_text opam_lock_file_path (fun chan -> let out = Format.formatter_of_out_channel chan in Fmt.pf out "%a" Pp.pp lock_file); Logs.info (fun log -> log "Created an opam lock file at %S." opam_lock_file_path)
null
https://raw.githubusercontent.com/odis-labs/onix/81cc82953ef062425656ac9bf80474f2ce642f5b/src/onix_lock_opam/Onix_lock_opam.ml
ocaml
let gen ~opam_lock_file_path lock_file = Onix_core.Utils.Out_channel.with_open_text opam_lock_file_path (fun chan -> let out = Format.formatter_of_out_channel chan in Fmt.pf out "%a" Pp.pp lock_file); Logs.info (fun log -> log "Created an opam lock file at %S." opam_lock_file_path)
fb154adcf8029096147940c5b52ed045a856f9f17f975f16fb601261f26ba9c3
2600hz/kazoo
cb_presence.erl
%%%----------------------------------------------------------------------------- ( C ) 2013 - 2020 , 2600Hz %%% @doc This Source Code Form is subject to the terms of the Mozilla Public License , v. 2.0 . If a copy of the MPL was not distributed with this file , You can obtain one at /. %%% %%% @end %%%----------------------------------------------------------------------------- -module('cb_presence'). -export([init/0 ,authenticate/1, authenticate/2 ,authorize/1, authorize/2 ,allowed_methods/0, allowed_methods/1 ,resource_exists/0, resource_exists/1 ,content_types_provided/2 ,validate/1, validate/2 ,post/1, post/2 ]). -include("crossbar.hrl"). -define(MOD_CONFIG_CAT, <<(?CONFIG_CAT)/binary, ".presence">>). -define(PRESENTITY_KEY, <<"include_presentity">>). -define(PRESENTITY_CFG_KEY, <<"query_include_presentity">>). -define(PRESENCE_QUERY_TIMEOUT_KEY, <<"query_presence_timeout">>). -define(PRESENCE_QUERY_DEFAULT_TIMEOUT, 5000). -define(PRESENCE_QUERY_TIMEOUT, kapps_config:get_integer(?MOD_CONFIG_CAT ,?PRESENCE_QUERY_TIMEOUT_KEY ,?PRESENCE_QUERY_DEFAULT_TIMEOUT ) ). -define(REPORT_CONTENT_TYPE, [{'send_file', [{<<"application">>, <<"json">>, '*'}]}]). -define(REPORT_PREFIX, "report-"). -define(MATCH_REPORT_PREFIX(ReportId), <<?REPORT_PREFIX, ReportId/binary>>). -define(MATCH_REPORT_PREFIX, <<?REPORT_PREFIX, _ReportId/binary>>). -define(MANUAL_PRESENCE_DOC, <<"manual_presence">>). -define(CONFIRMED, <<"confirmed">>). -define(EARLY, <<"early">>). -define(TERMINATED, <<"terminated">>). -define(PRESENCE_STATES, [?CONFIRMED, ?EARLY, ?TERMINATED]). -type search_result() :: {'ok', kz_json:object()} | {'error', any()}. %%%============================================================================= %%% API %%%============================================================================= %%------------------------------------------------------------------------------ %% @doc %% @end %%------------------------------------------------------------------------------ -spec init() -> ok. init() -> Bindings = [{<<"*.allowed_methods.presence">>, 'allowed_methods'} ,{<<"*.authenticate.presence">>, 'authenticate'} ,{<<"*.authorize.presence">>, 'authorize'} ,{<<"*.resource_exists.presence">>, 'resource_exists'} ,{<<"*.content_types_provided.presence">>, 'content_types_provided'} ,{<<"*.validate.presence">>, 'validate'} ,{<<"*.execute.post.presence">>, 'post'} ], _ = cb_modules_util:bind(?MODULE, Bindings), ok. -spec authenticate(cb_context:context()) -> boolean(). authenticate(Context) -> authenticate_nouns(Context, cb_context:req_nouns(Context), cb_context:req_verb(Context)). -spec authenticate(cb_context:context(), path_token()) -> boolean(). authenticate(Context, _) -> authenticate_nouns(Context, cb_context:req_nouns(Context), cb_context:req_verb(Context)). -spec authenticate_nouns(cb_context:context(), req_nouns(), http_method()) -> boolean(). authenticate_nouns(Context, [{<<"presence">>,[?MATCH_REPORT_PREFIX]}], ?HTTP_GET) -> cb_context:magic_pathed(Context); authenticate_nouns(_Context, _Nouns, _Verb) -> 'false'. %%------------------------------------------------------------------------------ %% @doc %% @end %%------------------------------------------------------------------------------ -spec authorize(cb_context:context()) -> boolean(). authorize(Context) -> authorize_nouns(Context, cb_context:req_nouns(Context), cb_context:req_verb(Context)). -spec authorize(cb_context:context(), path_token()) -> boolean(). authorize(Context, _) -> authorize_nouns(Context, cb_context:req_nouns(Context), cb_context:req_verb(Context)). -spec authorize_nouns(cb_context:context(), req_nouns(), http_method()) -> boolean(). authorize_nouns(Context, [{<<"presence">>,[?MATCH_REPORT_PREFIX]}], ?HTTP_GET) -> cb_context:magic_pathed(Context); authorize_nouns(_Context, _Nouns, _Verb) -> 'false'. %%------------------------------------------------------------------------------ %% @doc This function determines the verbs that are appropriate for the %% given Nouns. For example `/accounts/' can only accept `GET' and `PUT'. %% %% Failure here returns `405 Method Not Allowed'. %% @end %%------------------------------------------------------------------------------ -spec allowed_methods() -> http_methods(). allowed_methods() -> [?HTTP_GET, ?HTTP_POST]. -spec allowed_methods(path_token()) -> http_methods(). allowed_methods(?MATCH_REPORT_PREFIX) -> [?HTTP_GET]; allowed_methods(_Extension) -> [?HTTP_GET, ?HTTP_POST]. %%------------------------------------------------------------------------------ %% @doc This function determines if the provided list of Nouns are valid. Failure here returns ` 404 Not Found ' . %% @end %%------------------------------------------------------------------------------ -spec resource_exists() -> 'true'. resource_exists() -> 'true'. -spec resource_exists(path_token()) -> 'true'. resource_exists(_Extension) -> 'true'. %%------------------------------------------------------------------------------ %% @doc This function allows report to be downloaded. %% @end %%------------------------------------------------------------------------------ -spec content_types_provided(cb_context:context(), path_token()) -> cb_context:context(). content_types_provided(Context, ?MATCH_REPORT_PREFIX(Report)) -> content_types_provided_for_report(Context, Report); content_types_provided(Context, _) -> Context. -spec content_types_provided_for_report(cb_context:context(), kz_term:ne_binary()) -> cb_context:context(). content_types_provided_for_report(Context, Report) -> File = <<"/tmp/", Report/binary, ".json">>, case filelib:is_file(File) of 'false' -> Context; 'true' -> cb_context:set_content_types_provided(Context, ?REPORT_CONTENT_TYPE) end. %%------------------------------------------------------------------------------ %% @doc This function determines if the parameters and content are correct %% for this request %% Failure here returns 400 . %% @end %%------------------------------------------------------------------------------ -spec validate(cb_context:context()) -> cb_context:context(). validate(Context) -> validate_thing(Context, cb_context:req_verb(Context)). -spec validate(cb_context:context(), path_token()) -> cb_context:context(). validate(Context, ?MATCH_REPORT_PREFIX(Report)) -> load_report(Context, Report); validate(Context, Extension) -> search_detail(Context, Extension). -spec validate_thing(cb_context:context(), http_method()) -> cb_context:context(). validate_thing(Context, ?HTTP_GET) -> search_summary(Context); validate_thing(Context, ?HTTP_POST) -> validate_presence_thing(Context). -spec search_summary(cb_context:context()) -> cb_context:context(). search_summary(Context) -> search_result(Context, search_req(Context, <<"summary">>)). -spec search_detail(cb_context:context(), kz_term:ne_binary()) -> cb_context:context(). search_detail(Context, Extension) -> search_result(Context, search_req(Context, <<"detail">>, Extension)). -spec search_result(cb_context:context(), search_result()) -> cb_context:context(). search_result(Context, {'ok', JObj}) -> Routines = [{fun cb_context:set_resp_data/2, JObj} ,{fun cb_context:set_resp_status/2, 'success'} ], cb_context:setters(Context, Routines); search_result(Context, {'error', Error}) -> cb_context:add_system_error(Error, Context). -spec search_req(cb_context:context(), kz_term:ne_binary()) -> search_result(). search_req(Context, SearchType) -> search_req(Context, SearchType, 'undefined'). -spec search_req(cb_context:context(), kz_term:ne_binary(), kz_term:api_binary()) -> search_result(). search_req(Context, SearchType, Username) -> Req = [{<<"Realm">>, cb_context:account_realm(Context)} ,{<<"Username">>, Username} ,{<<"Search-Type">>, SearchType} ,{<<"Event-Package">>, cb_context:req_param(Context, <<"event">>)} ,{<<"System-Log-ID">>, cb_context:req_id(Context)} ,{<<"Msg-ID">>, kz_binary:rand_hex(16)} | kz_api:default_headers(?APP_NAME, ?APP_VERSION) ], Count = kz_nodes:node_role_count(<<"Presence">>, 'true'), lager:debug("requesting presence ~s from ~B servers", [SearchType, Count]), case kz_amqp_worker:call_collect(Req ,fun kapi_presence:publish_search_req/1 ,{fun collect_results/2, {0, Count}} ) of {'error', _R}=Err -> Err; {'ok', JObjs} when is_list(JObjs) -> process_responses(JObjs, SearchType, 'null'); {'timeout', JObjs} when is_list(JObjs) -> process_responses(JObjs, SearchType, 'true') end. -type collect_params() :: {integer(), integer()}. -type collect_result() :: 'true' | {'false', collect_params()}. -spec collect_results(kz_json:objects(), collect_params()) -> collect_result(). collect_results([Response | _], {Count, Max}) -> case Count + search_resp_value(kz_api:event_name(Response)) of Max -> 'true'; V -> {'false', {V, Max}} end. -spec search_resp_value(kz_term:ne_binary()) -> 0..1. search_resp_value(<<"search_resp">>) -> 1; search_resp_value(_) -> 0. -type acc_function() :: fun((kz_json:object(), kz_json:object()) -> kz_json:object()). -spec accumulator_fun(kz_term:ne_binary()) -> acc_function(). accumulator_fun(<<"summary">>) -> fun kz_json:sum/2; accumulator_fun(<<"detail">>) -> fun kz_json:merge/2. -spec process_responses(kz_json:objects(), kz_term:ne_binary(), atom()) -> {'ok', kz_json:object()}. process_responses(JObjs, SearchType, Timeout) -> Fun = accumulator_fun(SearchType), Subscriptions = extract_subscriptions(JObjs, Fun), {'ok', kz_json:set_value(<<"timeout">>, Timeout, Subscriptions)}. -spec extract_subscriptions(kz_json:objects(), acc_function()) -> kz_json:object(). extract_subscriptions(JObjs, Fun) -> lists:foldl(fun(JObj, Acc) -> Fun(kz_api:remove_defaults(JObj), Acc) end, kz_json:new(), JObjs). -spec validate_presence_thing(cb_context:context()) -> cb_context:context(). validate_presence_thing(Context) -> validate_presence_thing(Context, cb_context:req_nouns(Context)). -spec validate_presence_thing(cb_context:context(), req_nouns()) -> cb_context:context(). validate_presence_thing(Context, [{<<"presence">>, _} ,{<<"devices">>, [DeviceId]} ,{<<"accounts">>, [_AccountId]} ]) -> validate_action(load_device(Context, DeviceId)); validate_presence_thing(Context, [{<<"presence">>, _} ,{<<"users">>, [UserId]} ,{<<"accounts">>, [_AccountId]} ]) -> validate_action(load_presence_for_user(Context, UserId)); validate_presence_thing(Context, _ReqNouns) -> crossbar_util:response_faulty_request(Context). -spec load_device(cb_context:context(), kz_term:ne_binary()) -> cb_context:context(). load_device(Context, ThingId) -> %% validating device crossbar_doc:load(ThingId, Context, ?TYPE_CHECK_OPTION(kzd_devices:type())). -spec load_presence_for_user(cb_context:context(), kz_term:ne_binary()) -> cb_context:context(). load_presence_for_user(Context, UserId) -> %% load the user_doc if it has a presence_id set, otherwise load all the user's devices Context1 = crossbar_doc:load(UserId, Context, ?TYPE_CHECK_OPTION(kzd_users:type())), case cb_context:resp_status(Context1) of 'success' -> maybe_load_user_devices(Context1); _ -> Context end. -spec maybe_load_user_devices(cb_context:context()) -> cb_context:context(). maybe_load_user_devices(Context) -> User = cb_context:doc(Context), case kzd_users:presence_id(User) of 'undefined' -> load_user_devices(Context); _PresenceId -> Context end. -spec load_user_devices(cb_context:context()) -> cb_context:context(). load_user_devices(Context) -> User = cb_context:doc(Context), Devices = kz_attributes:owned_by_docs(kz_doc:id(User), cb_context:account_id(Context)), cb_context:set_doc(Context, Devices). -spec validate_action(cb_context:context()) -> cb_context:context(). validate_action(Context) -> case cb_context:resp_status(Context) of 'success' -> validate_action(Context, cb_context:req_data(Context)); _ -> Context end. validate_action(Context, ReqData) -> DeprecatedReset = case kz_json:get_value(<<"reset">>, ReqData, 'false') of 'true' -> <<"reset">>; 'false' -> 'undefined' end, validate_action(Context, ReqData, kz_json:get_value(<<"action">>, ReqData, DeprecatedReset)). validate_action(Context, _ReqData, <<"reset">>) -> Context; validate_action(Context, ReqData, <<"set">>) -> State = kz_json:get_value(<<"state">>, ReqData), case lists:member(State, ?PRESENCE_STATES) of 'true' -> Context; 'false' -> invalid_state(Context) end; validate_action(Context, _ReqData, _InvalidAction) -> invalid_action(Context). -spec invalid_action(cb_context:context()) -> cb_context:context(). invalid_action(Context) -> cb_context:add_validation_error(<<"action">> ,<<"invalid">> ,kz_json:from_list( [{<<"message">>, <<"Field must be set to a valid action">>} ,{<<"target">>, <<"invalid">>} ] ) ,Context ). -spec invalid_state(cb_context:context()) -> cb_context:context(). invalid_state(Context) -> cb_context:add_validation_error(<<"state">> ,<<"invalid">> ,kz_json:from_list( [{<<"message">>, <<"Field must be set to a valid state">>} ,{<<"target">>, <<"invalid">>} ] ) ,Context ). -spec post(cb_context:context()) -> cb_context:context(). post(Context) -> ReqData = cb_context:req_data(Context), Things = cb_context:doc(Context), post_things(Context, Things, kz_json:get_value(<<"action">>, ReqData)). -spec post(cb_context:context(), kz_term:ne_binary()) -> cb_context:context(). post(Context, Extension) -> _ = collect_report(Context, Extension), publish_presence_reset(Context, Extension), crossbar_util:response_202(<<"reset command sent for extension ", Extension/binary>>, Context). -spec post_things(cb_context:context(), kz_json:object() | kz_json:objects(), kz_term:ne_binary()) -> cb_context:context(). post_things(Context, Things, <<"reset">>) -> _ = collect_report(Context, Things), send_command(Context, fun publish_presence_reset/2, Things); post_things(Context, Things, <<"set">>) -> State = kz_json:get_value(<<"state">>, cb_context:req_data(Context)), send_command(Context, fun(C, Id) -> publish_presence_update(C, Id, State) end, Things). -type presence_command_fun() :: fun((cb_context:context(), kz_term:api_binary()) -> any()). -spec send_command(cb_context:context(), presence_command_fun(), kz_json:object() | kz_json:objects()) -> cb_context:context(). send_command(Context, _CommandFun, []) -> lager:debug("nothing to send command to"), crossbar_util:response(<<"nothing to send command to">>, Context); send_command(Context, CommandFun, [_|_]=Things) -> lists:foreach(fun(Thing) -> CommandFun(Context, find_presence_id(Thing)) end, Things), crossbar_util:response_202(<<"command sent">>, Context); send_command(Context, CommandFun, Thing) -> send_command(Context, CommandFun, [Thing]). -spec publish_presence_reset(cb_context:context(), kz_term:api_binary()) -> 'ok'. publish_presence_reset(_Context, 'undefined') -> 'ok'; publish_presence_reset(Context, PresenceId) -> Realm = cb_context:account_realm(Context), lager:debug("resetting ~s@~s", [PresenceId, Realm]), API = [{<<"Realm">>, Realm} ,{<<"Username">>, PresenceId} ,{<<"Msg-ID">>, kz_log:get_callid()} | kz_api:default_headers(?APP_NAME, ?APP_VERSION) ], kz_amqp_worker:cast(API, fun kapi_presence:publish_reset/1). -spec publish_presence_update(cb_context:context(), kz_term:api_binary(), kz_term:ne_binary()) -> 'ok'. publish_presence_update(_Context, 'undefined', _PresenceState) -> 'ok'; publish_presence_update(Context, PresenceId, PresenceState) -> Realm = cb_context:account_realm(Context), AccountDb = cb_context:db_name(Context), lager:debug("updating presence for ~s@~s to state ~s", [PresenceId, Realm, PresenceState]), %% persist presence setting Update = [{PresenceId, PresenceState}], UpdateOptions = [{'update', Update}], {'ok', _} = kz_datamgr:update_doc(AccountDb, ?MANUAL_PRESENCE_DOC, UpdateOptions), PresenceString = <<PresenceId/binary, "@", Realm/binary>>, kapps_call_command:presence(PresenceState, PresenceString, kz_term:to_hex_binary(crypto:hash('md5', PresenceString))). -spec find_presence_id(kz_json:object()) -> kz_term:api_binary(). find_presence_id(JObj) -> case kzd_devices:is_device(JObj) of 'true' -> kzd_devices:presence_id(JObj); 'false' -> kzd_users:presence_id(JObj) end. -spec load_report(cb_context:context(), path_token()) -> cb_context:context(). load_report(Context, Report) -> File = <<"/tmp/", Report/binary, ".json">>, case filelib:is_file(File) of 'true' -> set_report(Context, File); 'false' -> lager:error("invalid file while fetching report file ~s", [File]), cb_context:add_system_error('bad_identifier', kz_json:from_list([{<<"cause">>, Report}]), Context) end. -spec set_report(cb_context:context(), kz_term:ne_binary()) -> cb_context:context(). set_report(Context, File) -> Name = kz_term:to_binary(filename:basename(File)), Headers = #{<<"Content-Disposition">> => <<"attachment; filename=", Name/binary>>}, cb_context:setters(Context, [{fun cb_context:set_resp_file/2, File} ,{fun cb_context:set_resp_etag/2, 'undefined'} ,{fun cb_context:add_resp_headers/2, Headers} ,{fun cb_context:set_resp_status/2, 'success'} ] ). -spec collect_report(cb_context:context(), kz_term:ne_binary() | kz_json:object() | kz_json:objects()) -> any(). collect_report(_Context, []) -> lager:debug("nothing to collect"); collect_report(Context, Param) -> lager:debug("collecting report for ~s", [Param]), kz_process:spawn(fun send_report/2, [search_detail(Context, Param), Param]). -spec send_report(cb_context:context(), kz_term:ne_binary() | kz_json:object() | kz_json:objects()) -> 'ok'. send_report(Context, Extension) when is_binary(Extension) -> Msg = <<"presence reset received for extension ", Extension/binary>>, format_and_send_report(Context, Msg); send_report(Context, Things) when is_list(Things) -> Format = "presence reset received for user_id ~s~n~ndevices:~p", Ids = list_to_binary([io_lib:format("~n~s", [kz_doc:id(Thing)]) || Thing <- Things]), Msg = io_lib:format(Format, [cb_context:user_id(Context), Ids]), format_and_send_report(Context, Msg); send_report(Context, Thing) -> Format = "presence reset received for ~s: ~s", Msg = io_lib:format(Format, [kz_doc:type(Thing), kz_doc:id(Thing)]), format_and_send_report(Context, Msg). -spec format_and_send_report(cb_context:context(), iodata()) -> 'ok'. format_and_send_report(Context, Msg) -> lager:debug("formatting and sending report"), {ReportId, URL} = save_report(Context), Subject = io_lib:format("presence reset for account ~s", [cb_context:account_id(Context)]), Props = [{<<"Report-ID">>, ReportId} ,{<<"Node">>, node()} ], Headers = [{<<"Attachment-URL">>, URL} ,{<<"Account-ID">>, cb_context:account_id(Context)} ,{<<"Request-ID">>, cb_context:req_id(Context)} ], kz_notify:detailed_alert(Subject, Msg, Props, Headers). -spec save_report(cb_context:context()) -> {kz_term:ne_binary(), kz_term:ne_binary()}. save_report(Context) -> JObj = kz_json:encode(cb_context:resp_data(Context)), Report = kz_binary:rand_hex(16), File = <<"/tmp/", Report/binary, ".json">>, 'ok' = file:write_file(File, JObj), Args = [cb_context:api_version(Context) ,cb_context:account_id(Context) ,?MATCH_REPORT_PREFIX(Report) ], Path = io_lib:format("/~s/accounts/~s/presence/~s", Args), MagicPath = kapps_util:to_magic_hash(Path), HostURL = cb_context:host_url(Context), URL = <<HostURL/binary, "/", MagicPath/binary>>, {Report, URL}.
null
https://raw.githubusercontent.com/2600hz/kazoo/24519b9af9792caa67f7c09bbb9d27e2418f7ad6/applications/crossbar/src/modules/cb_presence.erl
erlang
----------------------------------------------------------------------------- @doc @end ----------------------------------------------------------------------------- ============================================================================= API ============================================================================= ------------------------------------------------------------------------------ @doc @end ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ @doc @end ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ @doc This function determines the verbs that are appropriate for the given Nouns. For example `/accounts/' can only accept `GET' and `PUT'. Failure here returns `405 Method Not Allowed'. @end ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ @doc This function determines if the provided list of Nouns are valid. @end ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ @doc This function allows report to be downloaded. @end ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ @doc This function determines if the parameters and content are correct for this request @end ------------------------------------------------------------------------------ validating device load the user_doc if it has a presence_id set, otherwise load all the user's devices persist presence setting
( C ) 2013 - 2020 , 2600Hz This Source Code Form is subject to the terms of the Mozilla Public License , v. 2.0 . If a copy of the MPL was not distributed with this file , You can obtain one at /. -module('cb_presence'). -export([init/0 ,authenticate/1, authenticate/2 ,authorize/1, authorize/2 ,allowed_methods/0, allowed_methods/1 ,resource_exists/0, resource_exists/1 ,content_types_provided/2 ,validate/1, validate/2 ,post/1, post/2 ]). -include("crossbar.hrl"). -define(MOD_CONFIG_CAT, <<(?CONFIG_CAT)/binary, ".presence">>). -define(PRESENTITY_KEY, <<"include_presentity">>). -define(PRESENTITY_CFG_KEY, <<"query_include_presentity">>). -define(PRESENCE_QUERY_TIMEOUT_KEY, <<"query_presence_timeout">>). -define(PRESENCE_QUERY_DEFAULT_TIMEOUT, 5000). -define(PRESENCE_QUERY_TIMEOUT, kapps_config:get_integer(?MOD_CONFIG_CAT ,?PRESENCE_QUERY_TIMEOUT_KEY ,?PRESENCE_QUERY_DEFAULT_TIMEOUT ) ). -define(REPORT_CONTENT_TYPE, [{'send_file', [{<<"application">>, <<"json">>, '*'}]}]). -define(REPORT_PREFIX, "report-"). -define(MATCH_REPORT_PREFIX(ReportId), <<?REPORT_PREFIX, ReportId/binary>>). -define(MATCH_REPORT_PREFIX, <<?REPORT_PREFIX, _ReportId/binary>>). -define(MANUAL_PRESENCE_DOC, <<"manual_presence">>). -define(CONFIRMED, <<"confirmed">>). -define(EARLY, <<"early">>). -define(TERMINATED, <<"terminated">>). -define(PRESENCE_STATES, [?CONFIRMED, ?EARLY, ?TERMINATED]). -type search_result() :: {'ok', kz_json:object()} | {'error', any()}. -spec init() -> ok. init() -> Bindings = [{<<"*.allowed_methods.presence">>, 'allowed_methods'} ,{<<"*.authenticate.presence">>, 'authenticate'} ,{<<"*.authorize.presence">>, 'authorize'} ,{<<"*.resource_exists.presence">>, 'resource_exists'} ,{<<"*.content_types_provided.presence">>, 'content_types_provided'} ,{<<"*.validate.presence">>, 'validate'} ,{<<"*.execute.post.presence">>, 'post'} ], _ = cb_modules_util:bind(?MODULE, Bindings), ok. -spec authenticate(cb_context:context()) -> boolean(). authenticate(Context) -> authenticate_nouns(Context, cb_context:req_nouns(Context), cb_context:req_verb(Context)). -spec authenticate(cb_context:context(), path_token()) -> boolean(). authenticate(Context, _) -> authenticate_nouns(Context, cb_context:req_nouns(Context), cb_context:req_verb(Context)). -spec authenticate_nouns(cb_context:context(), req_nouns(), http_method()) -> boolean(). authenticate_nouns(Context, [{<<"presence">>,[?MATCH_REPORT_PREFIX]}], ?HTTP_GET) -> cb_context:magic_pathed(Context); authenticate_nouns(_Context, _Nouns, _Verb) -> 'false'. -spec authorize(cb_context:context()) -> boolean(). authorize(Context) -> authorize_nouns(Context, cb_context:req_nouns(Context), cb_context:req_verb(Context)). -spec authorize(cb_context:context(), path_token()) -> boolean(). authorize(Context, _) -> authorize_nouns(Context, cb_context:req_nouns(Context), cb_context:req_verb(Context)). -spec authorize_nouns(cb_context:context(), req_nouns(), http_method()) -> boolean(). authorize_nouns(Context, [{<<"presence">>,[?MATCH_REPORT_PREFIX]}], ?HTTP_GET) -> cb_context:magic_pathed(Context); authorize_nouns(_Context, _Nouns, _Verb) -> 'false'. -spec allowed_methods() -> http_methods(). allowed_methods() -> [?HTTP_GET, ?HTTP_POST]. -spec allowed_methods(path_token()) -> http_methods(). allowed_methods(?MATCH_REPORT_PREFIX) -> [?HTTP_GET]; allowed_methods(_Extension) -> [?HTTP_GET, ?HTTP_POST]. Failure here returns ` 404 Not Found ' . -spec resource_exists() -> 'true'. resource_exists() -> 'true'. -spec resource_exists(path_token()) -> 'true'. resource_exists(_Extension) -> 'true'. -spec content_types_provided(cb_context:context(), path_token()) -> cb_context:context(). content_types_provided(Context, ?MATCH_REPORT_PREFIX(Report)) -> content_types_provided_for_report(Context, Report); content_types_provided(Context, _) -> Context. -spec content_types_provided_for_report(cb_context:context(), kz_term:ne_binary()) -> cb_context:context(). content_types_provided_for_report(Context, Report) -> File = <<"/tmp/", Report/binary, ".json">>, case filelib:is_file(File) of 'false' -> Context; 'true' -> cb_context:set_content_types_provided(Context, ?REPORT_CONTENT_TYPE) end. Failure here returns 400 . -spec validate(cb_context:context()) -> cb_context:context(). validate(Context) -> validate_thing(Context, cb_context:req_verb(Context)). -spec validate(cb_context:context(), path_token()) -> cb_context:context(). validate(Context, ?MATCH_REPORT_PREFIX(Report)) -> load_report(Context, Report); validate(Context, Extension) -> search_detail(Context, Extension). -spec validate_thing(cb_context:context(), http_method()) -> cb_context:context(). validate_thing(Context, ?HTTP_GET) -> search_summary(Context); validate_thing(Context, ?HTTP_POST) -> validate_presence_thing(Context). -spec search_summary(cb_context:context()) -> cb_context:context(). search_summary(Context) -> search_result(Context, search_req(Context, <<"summary">>)). -spec search_detail(cb_context:context(), kz_term:ne_binary()) -> cb_context:context(). search_detail(Context, Extension) -> search_result(Context, search_req(Context, <<"detail">>, Extension)). -spec search_result(cb_context:context(), search_result()) -> cb_context:context(). search_result(Context, {'ok', JObj}) -> Routines = [{fun cb_context:set_resp_data/2, JObj} ,{fun cb_context:set_resp_status/2, 'success'} ], cb_context:setters(Context, Routines); search_result(Context, {'error', Error}) -> cb_context:add_system_error(Error, Context). -spec search_req(cb_context:context(), kz_term:ne_binary()) -> search_result(). search_req(Context, SearchType) -> search_req(Context, SearchType, 'undefined'). -spec search_req(cb_context:context(), kz_term:ne_binary(), kz_term:api_binary()) -> search_result(). search_req(Context, SearchType, Username) -> Req = [{<<"Realm">>, cb_context:account_realm(Context)} ,{<<"Username">>, Username} ,{<<"Search-Type">>, SearchType} ,{<<"Event-Package">>, cb_context:req_param(Context, <<"event">>)} ,{<<"System-Log-ID">>, cb_context:req_id(Context)} ,{<<"Msg-ID">>, kz_binary:rand_hex(16)} | kz_api:default_headers(?APP_NAME, ?APP_VERSION) ], Count = kz_nodes:node_role_count(<<"Presence">>, 'true'), lager:debug("requesting presence ~s from ~B servers", [SearchType, Count]), case kz_amqp_worker:call_collect(Req ,fun kapi_presence:publish_search_req/1 ,{fun collect_results/2, {0, Count}} ) of {'error', _R}=Err -> Err; {'ok', JObjs} when is_list(JObjs) -> process_responses(JObjs, SearchType, 'null'); {'timeout', JObjs} when is_list(JObjs) -> process_responses(JObjs, SearchType, 'true') end. -type collect_params() :: {integer(), integer()}. -type collect_result() :: 'true' | {'false', collect_params()}. -spec collect_results(kz_json:objects(), collect_params()) -> collect_result(). collect_results([Response | _], {Count, Max}) -> case Count + search_resp_value(kz_api:event_name(Response)) of Max -> 'true'; V -> {'false', {V, Max}} end. -spec search_resp_value(kz_term:ne_binary()) -> 0..1. search_resp_value(<<"search_resp">>) -> 1; search_resp_value(_) -> 0. -type acc_function() :: fun((kz_json:object(), kz_json:object()) -> kz_json:object()). -spec accumulator_fun(kz_term:ne_binary()) -> acc_function(). accumulator_fun(<<"summary">>) -> fun kz_json:sum/2; accumulator_fun(<<"detail">>) -> fun kz_json:merge/2. -spec process_responses(kz_json:objects(), kz_term:ne_binary(), atom()) -> {'ok', kz_json:object()}. process_responses(JObjs, SearchType, Timeout) -> Fun = accumulator_fun(SearchType), Subscriptions = extract_subscriptions(JObjs, Fun), {'ok', kz_json:set_value(<<"timeout">>, Timeout, Subscriptions)}. -spec extract_subscriptions(kz_json:objects(), acc_function()) -> kz_json:object(). extract_subscriptions(JObjs, Fun) -> lists:foldl(fun(JObj, Acc) -> Fun(kz_api:remove_defaults(JObj), Acc) end, kz_json:new(), JObjs). -spec validate_presence_thing(cb_context:context()) -> cb_context:context(). validate_presence_thing(Context) -> validate_presence_thing(Context, cb_context:req_nouns(Context)). -spec validate_presence_thing(cb_context:context(), req_nouns()) -> cb_context:context(). validate_presence_thing(Context, [{<<"presence">>, _} ,{<<"devices">>, [DeviceId]} ,{<<"accounts">>, [_AccountId]} ]) -> validate_action(load_device(Context, DeviceId)); validate_presence_thing(Context, [{<<"presence">>, _} ,{<<"users">>, [UserId]} ,{<<"accounts">>, [_AccountId]} ]) -> validate_action(load_presence_for_user(Context, UserId)); validate_presence_thing(Context, _ReqNouns) -> crossbar_util:response_faulty_request(Context). -spec load_device(cb_context:context(), kz_term:ne_binary()) -> cb_context:context(). load_device(Context, ThingId) -> crossbar_doc:load(ThingId, Context, ?TYPE_CHECK_OPTION(kzd_devices:type())). -spec load_presence_for_user(cb_context:context(), kz_term:ne_binary()) -> cb_context:context(). load_presence_for_user(Context, UserId) -> Context1 = crossbar_doc:load(UserId, Context, ?TYPE_CHECK_OPTION(kzd_users:type())), case cb_context:resp_status(Context1) of 'success' -> maybe_load_user_devices(Context1); _ -> Context end. -spec maybe_load_user_devices(cb_context:context()) -> cb_context:context(). maybe_load_user_devices(Context) -> User = cb_context:doc(Context), case kzd_users:presence_id(User) of 'undefined' -> load_user_devices(Context); _PresenceId -> Context end. -spec load_user_devices(cb_context:context()) -> cb_context:context(). load_user_devices(Context) -> User = cb_context:doc(Context), Devices = kz_attributes:owned_by_docs(kz_doc:id(User), cb_context:account_id(Context)), cb_context:set_doc(Context, Devices). -spec validate_action(cb_context:context()) -> cb_context:context(). validate_action(Context) -> case cb_context:resp_status(Context) of 'success' -> validate_action(Context, cb_context:req_data(Context)); _ -> Context end. validate_action(Context, ReqData) -> DeprecatedReset = case kz_json:get_value(<<"reset">>, ReqData, 'false') of 'true' -> <<"reset">>; 'false' -> 'undefined' end, validate_action(Context, ReqData, kz_json:get_value(<<"action">>, ReqData, DeprecatedReset)). validate_action(Context, _ReqData, <<"reset">>) -> Context; validate_action(Context, ReqData, <<"set">>) -> State = kz_json:get_value(<<"state">>, ReqData), case lists:member(State, ?PRESENCE_STATES) of 'true' -> Context; 'false' -> invalid_state(Context) end; validate_action(Context, _ReqData, _InvalidAction) -> invalid_action(Context). -spec invalid_action(cb_context:context()) -> cb_context:context(). invalid_action(Context) -> cb_context:add_validation_error(<<"action">> ,<<"invalid">> ,kz_json:from_list( [{<<"message">>, <<"Field must be set to a valid action">>} ,{<<"target">>, <<"invalid">>} ] ) ,Context ). -spec invalid_state(cb_context:context()) -> cb_context:context(). invalid_state(Context) -> cb_context:add_validation_error(<<"state">> ,<<"invalid">> ,kz_json:from_list( [{<<"message">>, <<"Field must be set to a valid state">>} ,{<<"target">>, <<"invalid">>} ] ) ,Context ). -spec post(cb_context:context()) -> cb_context:context(). post(Context) -> ReqData = cb_context:req_data(Context), Things = cb_context:doc(Context), post_things(Context, Things, kz_json:get_value(<<"action">>, ReqData)). -spec post(cb_context:context(), kz_term:ne_binary()) -> cb_context:context(). post(Context, Extension) -> _ = collect_report(Context, Extension), publish_presence_reset(Context, Extension), crossbar_util:response_202(<<"reset command sent for extension ", Extension/binary>>, Context). -spec post_things(cb_context:context(), kz_json:object() | kz_json:objects(), kz_term:ne_binary()) -> cb_context:context(). post_things(Context, Things, <<"reset">>) -> _ = collect_report(Context, Things), send_command(Context, fun publish_presence_reset/2, Things); post_things(Context, Things, <<"set">>) -> State = kz_json:get_value(<<"state">>, cb_context:req_data(Context)), send_command(Context, fun(C, Id) -> publish_presence_update(C, Id, State) end, Things). -type presence_command_fun() :: fun((cb_context:context(), kz_term:api_binary()) -> any()). -spec send_command(cb_context:context(), presence_command_fun(), kz_json:object() | kz_json:objects()) -> cb_context:context(). send_command(Context, _CommandFun, []) -> lager:debug("nothing to send command to"), crossbar_util:response(<<"nothing to send command to">>, Context); send_command(Context, CommandFun, [_|_]=Things) -> lists:foreach(fun(Thing) -> CommandFun(Context, find_presence_id(Thing)) end, Things), crossbar_util:response_202(<<"command sent">>, Context); send_command(Context, CommandFun, Thing) -> send_command(Context, CommandFun, [Thing]). -spec publish_presence_reset(cb_context:context(), kz_term:api_binary()) -> 'ok'. publish_presence_reset(_Context, 'undefined') -> 'ok'; publish_presence_reset(Context, PresenceId) -> Realm = cb_context:account_realm(Context), lager:debug("resetting ~s@~s", [PresenceId, Realm]), API = [{<<"Realm">>, Realm} ,{<<"Username">>, PresenceId} ,{<<"Msg-ID">>, kz_log:get_callid()} | kz_api:default_headers(?APP_NAME, ?APP_VERSION) ], kz_amqp_worker:cast(API, fun kapi_presence:publish_reset/1). -spec publish_presence_update(cb_context:context(), kz_term:api_binary(), kz_term:ne_binary()) -> 'ok'. publish_presence_update(_Context, 'undefined', _PresenceState) -> 'ok'; publish_presence_update(Context, PresenceId, PresenceState) -> Realm = cb_context:account_realm(Context), AccountDb = cb_context:db_name(Context), lager:debug("updating presence for ~s@~s to state ~s", [PresenceId, Realm, PresenceState]), Update = [{PresenceId, PresenceState}], UpdateOptions = [{'update', Update}], {'ok', _} = kz_datamgr:update_doc(AccountDb, ?MANUAL_PRESENCE_DOC, UpdateOptions), PresenceString = <<PresenceId/binary, "@", Realm/binary>>, kapps_call_command:presence(PresenceState, PresenceString, kz_term:to_hex_binary(crypto:hash('md5', PresenceString))). -spec find_presence_id(kz_json:object()) -> kz_term:api_binary(). find_presence_id(JObj) -> case kzd_devices:is_device(JObj) of 'true' -> kzd_devices:presence_id(JObj); 'false' -> kzd_users:presence_id(JObj) end. -spec load_report(cb_context:context(), path_token()) -> cb_context:context(). load_report(Context, Report) -> File = <<"/tmp/", Report/binary, ".json">>, case filelib:is_file(File) of 'true' -> set_report(Context, File); 'false' -> lager:error("invalid file while fetching report file ~s", [File]), cb_context:add_system_error('bad_identifier', kz_json:from_list([{<<"cause">>, Report}]), Context) end. -spec set_report(cb_context:context(), kz_term:ne_binary()) -> cb_context:context(). set_report(Context, File) -> Name = kz_term:to_binary(filename:basename(File)), Headers = #{<<"Content-Disposition">> => <<"attachment; filename=", Name/binary>>}, cb_context:setters(Context, [{fun cb_context:set_resp_file/2, File} ,{fun cb_context:set_resp_etag/2, 'undefined'} ,{fun cb_context:add_resp_headers/2, Headers} ,{fun cb_context:set_resp_status/2, 'success'} ] ). -spec collect_report(cb_context:context(), kz_term:ne_binary() | kz_json:object() | kz_json:objects()) -> any(). collect_report(_Context, []) -> lager:debug("nothing to collect"); collect_report(Context, Param) -> lager:debug("collecting report for ~s", [Param]), kz_process:spawn(fun send_report/2, [search_detail(Context, Param), Param]). -spec send_report(cb_context:context(), kz_term:ne_binary() | kz_json:object() | kz_json:objects()) -> 'ok'. send_report(Context, Extension) when is_binary(Extension) -> Msg = <<"presence reset received for extension ", Extension/binary>>, format_and_send_report(Context, Msg); send_report(Context, Things) when is_list(Things) -> Format = "presence reset received for user_id ~s~n~ndevices:~p", Ids = list_to_binary([io_lib:format("~n~s", [kz_doc:id(Thing)]) || Thing <- Things]), Msg = io_lib:format(Format, [cb_context:user_id(Context), Ids]), format_and_send_report(Context, Msg); send_report(Context, Thing) -> Format = "presence reset received for ~s: ~s", Msg = io_lib:format(Format, [kz_doc:type(Thing), kz_doc:id(Thing)]), format_and_send_report(Context, Msg). -spec format_and_send_report(cb_context:context(), iodata()) -> 'ok'. format_and_send_report(Context, Msg) -> lager:debug("formatting and sending report"), {ReportId, URL} = save_report(Context), Subject = io_lib:format("presence reset for account ~s", [cb_context:account_id(Context)]), Props = [{<<"Report-ID">>, ReportId} ,{<<"Node">>, node()} ], Headers = [{<<"Attachment-URL">>, URL} ,{<<"Account-ID">>, cb_context:account_id(Context)} ,{<<"Request-ID">>, cb_context:req_id(Context)} ], kz_notify:detailed_alert(Subject, Msg, Props, Headers). -spec save_report(cb_context:context()) -> {kz_term:ne_binary(), kz_term:ne_binary()}. save_report(Context) -> JObj = kz_json:encode(cb_context:resp_data(Context)), Report = kz_binary:rand_hex(16), File = <<"/tmp/", Report/binary, ".json">>, 'ok' = file:write_file(File, JObj), Args = [cb_context:api_version(Context) ,cb_context:account_id(Context) ,?MATCH_REPORT_PREFIX(Report) ], Path = io_lib:format("/~s/accounts/~s/presence/~s", Args), MagicPath = kapps_util:to_magic_hash(Path), HostURL = cb_context:host_url(Context), URL = <<HostURL/binary, "/", MagicPath/binary>>, {Report, URL}.
5cff4c83b1ef3e91f224952ded14dc9d97c4ea8b5e8c10f9ec1e6046dd7f8436
choener/ADPfusion
Core.hs
-- | -- -- TODO the 'mkStream' instances here are probably wonky for everything that is -- non-static. -- TODO should @d@ in each case here be @d==0@ ? What is the exact meaning @d@ -- should convey? module ADPfusion.Unit.Core where import Data.Proxy import Data.Vector.Fusion.Stream.Monadic (singleton,map,filter,Step(..)) import Debug.Trace import Prelude hiding (map,filter) import Data.PrimitiveArray hiding (map) import ADPfusion.Core.Classes import ADPfusion.Core.Multi type instance InitialContext (Unit I) = IStatic 0 type instance InitialContext (Unit O) = OStatic 0 type instance InitialContext (Unit C) = Complement data instance RunningIndex (Unit t) = RiUnit instance ( Monad m ) ⇒ MkStream m (IStatic d) S (Unit I) where mkStream Proxy S grd LtUnit Unit = staticCheck# grd . singleton $ ElmS RiUnit {-# Inline mkStream #-} instance ( Monad m ) ⇒ MkStream m (IVariable d) S (Unit I) where mkStream Proxy S grd LtUnit Unit = staticCheck# grd . singleton $ ElmS RiUnit {-# Inline mkStream #-} instance ( Monad m ) ⇒ MkStream m (OStatic d) S (Unit O) where mkStream Proxy S grd LtUnit Unit = staticCheck# grd . singleton $ ElmS RiUnit {-# Inline mkStream #-} instance ( Monad m ) ⇒ MkStream m Complement S (Unit C) where mkStream Proxy S grd LtUnit Unit = staticCheck# grd . singleton $ ElmS RiUnit {-# Inline mkStream #-} --instance forall m ps p is . ( Monad m , MkStream m ps S is -- ) ⇒ m ( ' (: . ) ps p ) S ( is:.Unit I ) where -- mkStream Proxy S grd (us:.._) (is:._) = map ( ) - > ElmS $ zi : . : RiU ) -- $ mkStream (Proxy ∷ Proxy ps) S grd us is -- {-# Inline mkStream #-} -- --instance forall m ps p is . ( Monad m , MkStream m ps S is -- ) ⇒ m ( ' (: . ) ps p ) S ( is:.Unit O ) where -- mkStream Proxy S grd (us:.._) (is:._) = map ( ) - > ElmS $ zi : . : RiU ) -- $ mkStream (Proxy ∷ Proxy ps) S grd us is -- {-# Inline mkStream #-} -- --instance forall m ps p is . ( Monad m , MkStream m ps S is -- ) ⇒ m ( ' (: . ) ps p ) S ( is:.Unit C ) where -- mkStream Proxy S grd (us:.._) (is:._) = map ( ) - > ElmS $ zi : . : RiU ) -- $ mkStream (Proxy ∷ Proxy ps) S grd us is -- {-# Inline mkStream #-} -- -- -- instance TableStaticVar pos c u ( Unit I ) where -- tableStreamIndex _ _ _ _ = Unit -- {-# Inline [0] tableStreamIndex #-} -- instance TableStaticVar pos c u ( Unit O ) where -- tableStreamIndex _ _ _ _ = Unit -- {-# Inline [0] tableStreamIndex #-} -- instance TableStaticVar pos c u ( Unit C ) where -- tableStreamIndex _ _ _ _ = Unit -- {-# Inline [0] tableStreamIndex #-}
null
https://raw.githubusercontent.com/choener/ADPfusion/fcbbf05d0f438883928077e3d8a7f1cbf8c2e58d/ADPfusion/Unit/Core.hs
haskell
| TODO the 'mkStream' instances here are probably wonky for everything that is non-static. should convey? # Inline mkStream # # Inline mkStream # # Inline mkStream # # Inline mkStream # instance ) mkStream Proxy S grd (us:.._) (is:._) $ mkStream (Proxy ∷ Proxy ps) S grd us is {-# Inline mkStream #-} instance ) mkStream Proxy S grd (us:.._) (is:._) $ mkStream (Proxy ∷ Proxy ps) S grd us is {-# Inline mkStream #-} instance ) mkStream Proxy S grd (us:.._) (is:._) $ mkStream (Proxy ∷ Proxy ps) S grd us is {-# Inline mkStream #-} tableStreamIndex _ _ _ _ = Unit {-# Inline [0] tableStreamIndex #-} tableStreamIndex _ _ _ _ = Unit {-# Inline [0] tableStreamIndex #-} tableStreamIndex _ _ _ _ = Unit {-# Inline [0] tableStreamIndex #-}
TODO should @d@ in each case here be @d==0@ ? What is the exact meaning @d@ module ADPfusion.Unit.Core where import Data.Proxy import Data.Vector.Fusion.Stream.Monadic (singleton,map,filter,Step(..)) import Debug.Trace import Prelude hiding (map,filter) import Data.PrimitiveArray hiding (map) import ADPfusion.Core.Classes import ADPfusion.Core.Multi type instance InitialContext (Unit I) = IStatic 0 type instance InitialContext (Unit O) = OStatic 0 type instance InitialContext (Unit C) = Complement data instance RunningIndex (Unit t) = RiUnit instance ( Monad m ) ⇒ MkStream m (IStatic d) S (Unit I) where mkStream Proxy S grd LtUnit Unit = staticCheck# grd . singleton $ ElmS RiUnit instance ( Monad m ) ⇒ MkStream m (IVariable d) S (Unit I) where mkStream Proxy S grd LtUnit Unit = staticCheck# grd . singleton $ ElmS RiUnit instance ( Monad m ) ⇒ MkStream m (OStatic d) S (Unit O) where mkStream Proxy S grd LtUnit Unit = staticCheck# grd . singleton $ ElmS RiUnit instance ( Monad m ) ⇒ MkStream m Complement S (Unit C) where mkStream Proxy S grd LtUnit Unit = staticCheck# grd . singleton $ ElmS RiUnit forall m ps p is . ( Monad m , MkStream m ps S is ⇒ m ( ' (: . ) ps p ) S ( is:.Unit I ) where = map ( ) - > ElmS $ zi : . : RiU ) forall m ps p is . ( Monad m , MkStream m ps S is ⇒ m ( ' (: . ) ps p ) S ( is:.Unit O ) where = map ( ) - > ElmS $ zi : . : RiU ) forall m ps p is . ( Monad m , MkStream m ps S is ⇒ m ( ' (: . ) ps p ) S ( is:.Unit C ) where = map ( ) - > ElmS $ zi : . : RiU ) instance TableStaticVar pos c u ( Unit I ) where instance TableStaticVar pos c u ( Unit O ) where instance TableStaticVar pos c u ( Unit C ) where
610f8a3a011ee0dda6755976e7e548fc0e7fbbbb1bb2a1cc3069be77b2b6c3fc
jiesoul/soul-talk
effects.cljs
(ns soul-talk.effects (:require [re-frame.core :as rf :refer [dispatch reg-fx reg-event-fx reg-event-db]] [accountant.core :as accountant] [ajax.core :as ajax] [reagent.core :as r])) (reg-event-fx :ajax-error (fn [_ [_ {:keys [response status] :as resp}]] (let [message (:message response)] {:dispatch-n (condp = status 400 (list [:set-error (str "错误的请求!" message)]) 401 (list [:set-error (str "请示验证失败! " message)] [:logout]) 403 (list [:set-error (str "错误的请求! " message)] [:logout]) 404 (list [:set-error (str "所请求的资源未找到,请检查!" message)]) 500 (list [:set-error (str "发生内部错误,请联系管理员或重试!") message]) (list [:set-error "发生未知错误!"]))}))) (reg-fx :http (fn [{:keys [method url success-event error-event ignore-response-body ajax-map] :or {error-event [:ajax-error] ajax-map {}}}] (dispatch [:set-loading]) (method url (merge {:handler (fn [response] (when success-event (dispatch (if ignore-response-body success-event (conj success-event response)))) (dispatch [:unset-loading])) :error-handler (fn [resp] (dispatch (conj error-event resp)) (dispatch [:unset-loading]))} ajax-map)))) (defonce timeouts (r/atom {})) (reg-fx :timeout (fn [{:keys [id event time]}] (when-some [existing (get @timeouts id)] (js/clearTimeout existing) (swap! timeouts dissoc id)) (when (some? event) (swap! timeouts assoc id (js/setTimeout (fn [] (dispatch event)) time))))) (reg-fx :navigate (fn [url] (accountant/navigate! url))) (reg-fx :reload-page (fn [_] (accountant/dispatch-current!))) ;; 响应事件 (defn query [db [event-id]] (event-id db))
null
https://raw.githubusercontent.com/jiesoul/soul-talk/630de08c6549b206d59023764d5f2576d97d1030/admin/src/soul_talk/effects.cljs
clojure
响应事件
(ns soul-talk.effects (:require [re-frame.core :as rf :refer [dispatch reg-fx reg-event-fx reg-event-db]] [accountant.core :as accountant] [ajax.core :as ajax] [reagent.core :as r])) (reg-event-fx :ajax-error (fn [_ [_ {:keys [response status] :as resp}]] (let [message (:message response)] {:dispatch-n (condp = status 400 (list [:set-error (str "错误的请求!" message)]) 401 (list [:set-error (str "请示验证失败! " message)] [:logout]) 403 (list [:set-error (str "错误的请求! " message)] [:logout]) 404 (list [:set-error (str "所请求的资源未找到,请检查!" message)]) 500 (list [:set-error (str "发生内部错误,请联系管理员或重试!") message]) (list [:set-error "发生未知错误!"]))}))) (reg-fx :http (fn [{:keys [method url success-event error-event ignore-response-body ajax-map] :or {error-event [:ajax-error] ajax-map {}}}] (dispatch [:set-loading]) (method url (merge {:handler (fn [response] (when success-event (dispatch (if ignore-response-body success-event (conj success-event response)))) (dispatch [:unset-loading])) :error-handler (fn [resp] (dispatch (conj error-event resp)) (dispatch [:unset-loading]))} ajax-map)))) (defonce timeouts (r/atom {})) (reg-fx :timeout (fn [{:keys [id event time]}] (when-some [existing (get @timeouts id)] (js/clearTimeout existing) (swap! timeouts dissoc id)) (when (some? event) (swap! timeouts assoc id (js/setTimeout (fn [] (dispatch event)) time))))) (reg-fx :navigate (fn [url] (accountant/navigate! url))) (reg-fx :reload-page (fn [_] (accountant/dispatch-current!))) (defn query [db [event-id]] (event-id db))
030028be0f7ea2e6a6c6775a27fad59810708808d8c0920e1478bd9e846eec0f
velveteer/slacker
Button.hs
module Slacker.Blocks.Elements.Button ( ButtonElement(..) , HasButton(..) , defaultButton ) where import qualified Data.Aeson as Aeson import Data.Text (Text) import GHC.Generics (Generic) import Slacker.Blocks.Elements.TextObject import Slacker.Util (toJSONWithTypeField) data ButtonElement = ButtonElement { text :: !PlainTextObject , action_id :: !Text , url :: !(Maybe Text) , value :: !(Maybe Text) , style :: !(Maybe Text) , accessibility_label :: !(Maybe Text) } deriving stock (Generic, Show, Eq, Ord) class HasButton a where button :: ButtonElement -> a button_ :: Text -> Text -> a button_ txt actId = button $ defaultButton txt actId instance HasButton ButtonElement where button = id defaultButton :: Text -> Text -> ButtonElement defaultButton txt actId = ButtonElement { text = plaintext_ txt , action_id = actId , url = Nothing , value = Nothing , style = Nothing , accessibility_label = Nothing } instance Aeson.ToJSON ButtonElement where toJSON = toJSONWithTypeField "button" . Aeson.genericToJSON Aeson.defaultOptions { Aeson.omitNothingFields = True }
null
https://raw.githubusercontent.com/velveteer/slacker/3f2046b2631624d0684834347f4b0a08b2d9dcdb/src/Slacker/Blocks/Elements/Button.hs
haskell
module Slacker.Blocks.Elements.Button ( ButtonElement(..) , HasButton(..) , defaultButton ) where import qualified Data.Aeson as Aeson import Data.Text (Text) import GHC.Generics (Generic) import Slacker.Blocks.Elements.TextObject import Slacker.Util (toJSONWithTypeField) data ButtonElement = ButtonElement { text :: !PlainTextObject , action_id :: !Text , url :: !(Maybe Text) , value :: !(Maybe Text) , style :: !(Maybe Text) , accessibility_label :: !(Maybe Text) } deriving stock (Generic, Show, Eq, Ord) class HasButton a where button :: ButtonElement -> a button_ :: Text -> Text -> a button_ txt actId = button $ defaultButton txt actId instance HasButton ButtonElement where button = id defaultButton :: Text -> Text -> ButtonElement defaultButton txt actId = ButtonElement { text = plaintext_ txt , action_id = actId , url = Nothing , value = Nothing , style = Nothing , accessibility_label = Nothing } instance Aeson.ToJSON ButtonElement where toJSON = toJSONWithTypeField "button" . Aeson.genericToJSON Aeson.defaultOptions { Aeson.omitNothingFields = True }
315731398dc0abd2dce2415c1f75630d296046fde70484c2845d32fd25df0134
yuriy-chumak/ol
gl-3.scm
(define-library (lib gl-3) (import (scheme base) (owl math) (otus async) (lib gl config) (lib gl-2) (OpenGL version-3-0)) (export gl:set-context-version ; recreate OpenGL with version (exports (lib gl-2)) (exports (OpenGL version-3-0))) ; -=( 3.0+ )=------------------------- ; Higher OpenGL versions support (cond-expand TODO : dev only , please rename to Android (begin (define (gl:set-context-version major minor) #false) )) (Linux (import (OpenGL GLX ARB create_context)) (begin (define (gl:set-context-version major minor) (let*((context (await (mail 'opengl ['get-context]))) ;#(display screen window cx) (display screen window cx context) this functions requires GLX 1.3 + (glXChooseFBConfig (GL_LIBRARY fft-void* "glXChooseFBConfig" fft-void* fft-int fft-int* fft-int&))) ( glXGetVisualFromFBConfig ( GLX fft - void * " glXGetVisualFromFBConfig " fft - void * fft - void * ) ) ;; (print "display: " display) ;; (print "screen: " screen) (define visual_attribs (list GLX_X_RENDERABLE #x8010 1 ; GLX_DRAWABLE_TYPE GLX_WINDOW_BIT GLX_X_VISUAL_TYPE GLX_TRUE_COLOR #x8011 1 ; GLX_RENDER_TYPE GLX_RGBA_BIT 8 (config 'red 5) ; GLX_RED_SIZE 9 (config 'green 6) ; GLX_GREEN_SIZE 10 (config 'blue 5) ; GLX_BLUE_SIZE 12 (config 'depth 24); GLX_DEPTH_SIZE 5 1 ; GLX_DOUBLEBUFFER 0)) (define fbcount (box 0)) (define fbc* (glXChooseFBConfig display screen visual_attribs fbcount)) ;; (print "fbcount: " (unbox fbcount)) (define fbc (vptr->bytevector fbc* (* (size nullptr) (unbox fbcount)))) (define bestFbc (bytevector->void* fbc 0)) ;; (define vi (glXGetVisualFromFBConfig display bestFbc)) (define contextAttribs (list GLX_CONTEXT_MAJOR_VERSION_ARB major GLX_CONTEXT_MINOR_VERSION_ARB minor 0)) (define new_cx (glXCreateContextAttribsARB display bestFbc NULL 1 contextAttribs)) (define new_context [display screen window new_cx]) ; disable and destroy old context (native:disable-context context) ; todo: destroy ; set new context (mail 'opengl ['set 'context new_context]) (native:enable-context new_context) #true)))) (Windows ( import ( OpenGL WGL ARB create_context ) ) (begin (define (gl:set-context-version major minor) #false))) ) (begin #true))
null
https://raw.githubusercontent.com/yuriy-chumak/ol/5e00a1d1df8a8f20d5d6b7714275a1578a56b8a0/libraries/lib/gl-3.scm
scheme
recreate OpenGL with version -=( 3.0+ )=------------------------- Higher OpenGL versions support #(display screen window cx) (print "display: " display) (print "screen: " screen) GLX_DRAWABLE_TYPE GLX_WINDOW_BIT GLX_RENDER_TYPE GLX_RGBA_BIT GLX_RED_SIZE GLX_GREEN_SIZE GLX_BLUE_SIZE GLX_DEPTH_SIZE GLX_DOUBLEBUFFER (print "fbcount: " (unbox fbcount)) (define vi (glXGetVisualFromFBConfig display bestFbc)) disable and destroy old context todo: destroy set new context
(define-library (lib gl-3) (import (scheme base) (owl math) (otus async) (lib gl config) (lib gl-2) (OpenGL version-3-0)) (export (exports (lib gl-2)) (exports (OpenGL version-3-0))) (cond-expand TODO : dev only , please rename to Android (begin (define (gl:set-context-version major minor) #false) )) (Linux (import (OpenGL GLX ARB create_context)) (begin (define (gl:set-context-version major minor) (display screen window cx context) this functions requires GLX 1.3 + (glXChooseFBConfig (GL_LIBRARY fft-void* "glXChooseFBConfig" fft-void* fft-int fft-int* fft-int&))) ( glXGetVisualFromFBConfig ( GLX fft - void * " glXGetVisualFromFBConfig " fft - void * fft - void * ) ) (define visual_attribs (list GLX_X_RENDERABLE GLX_X_VISUAL_TYPE GLX_TRUE_COLOR 0)) (define fbcount (box 0)) (define fbc* (glXChooseFBConfig display screen visual_attribs fbcount)) (define fbc (vptr->bytevector fbc* (* (size nullptr) (unbox fbcount)))) (define bestFbc (bytevector->void* fbc 0)) (define contextAttribs (list GLX_CONTEXT_MAJOR_VERSION_ARB major GLX_CONTEXT_MINOR_VERSION_ARB minor 0)) (define new_cx (glXCreateContextAttribsARB display bestFbc NULL 1 contextAttribs)) (define new_context [display screen window new_cx]) (mail 'opengl ['set 'context new_context]) (native:enable-context new_context) #true)))) (Windows ( import ( OpenGL WGL ARB create_context ) ) (begin (define (gl:set-context-version major minor) #false))) ) (begin #true))
8445b2d27f2555d995bf748e4699d4b70eb464fecf08910a0e965997ea559fcd
8c6794b6/haskell-sc-scratch
SCShell.hs
# LANGUAGE FlexibleInstances # # LANGUAGE UndecidableInstances # ------------------------------------------------------------------------------ -- | -- Module : $Header$ -- License : BSD3 Maintainer : -- Stability : unstable -- Portability : non-portable -- -- Interactive shell for scsynth nodes. -- Note that , backend used in this module is customized . Modified mtl version in dependency list of Shellac - haskeline 's cabal file from 1.1.1.1 to 2.0.1 . -- module SCShell where import Control.Monad.Trans (liftIO) import System.Console.Shell import System.Console.Shell.Backend.Haskeline import System.Console.Shell.ShellMonad import Sound.SC3 import Sound.SC3.Lepton import Parser1 import SampleData import SCZipper -- | -- TODO: -- * Add synth protocol and port number in state ( default : udp 57110 ) . -- * Reuse synth connection inside shell. -- main :: IO () main = do ini <- (flip SCZipper []) `fmap` withSC3 getRootNode runShell shellDesc haskelineBackend ini putStrLn "Bye." shellDesc :: ShellDescription SCZipper shellDesc = (mkShellDescription cmds work) { prompt = \st -> return $ makePrompt st , greetingText = Just ("Type ':q' to quit\n") } makePrompt :: SCZipper -> String makePrompt z = foldr f "/" ns ++ g (focus z) ++ " > " where ns = filter (\(SCPath n _ _) -> n /= 0) $ reverse $ scPaths z f (SCPath n _ _) cs = "/" ++ show n ++ cs g n | nodeId n == 0 = "" | otherwise = case n of Group gid _ -> show gid Synth nid def _ -> show nid ++ "[" ++ def ++ "]" cmds :: [ShellCommand SCZipper] cmds = [exitCommand "q"] -- | -- TODO: -- Use Parsec and write below commands : -- -- * DONE, but not so useful: 'pwd' -- * DONE: 'cd', specifying destination in absolute and relative path. -- * DONE: 'ls', take optional directory path to show. -- * DONE: 'tree', show nodes under given path with 'drawSCNode' function. * DONE : ' set ' , sends n_set OSC command * DONE : ' free ' , sends n_free OSC command * DONE : ' set ' , with n_map and n_mapn . -- * DONE: 'mv', to move around node with specifying new position -- * 'find', querying node like, find command, or WHERE clause in SQL. -- work :: String -> Sh SCZipper () work cs | null $ dropWhile (== ' ') cs = return () | otherwise = case parseCmd cs of Left err -> shellPutErrLn $ show err Right cmd -> case cmd of Pwd -> shellPutStrLn . show =<< getShellSt Ls f -> shellPutStr . showNode . focus . f =<< getShellSt Tree f -> shellPutStr . drawSCNode . focus . f =<< getShellSt Cd f -> modifyShellSt f Mv act source target -> do liftIO $ withSC3 $ flip send $ n_order act source target t <- liftIO $ withSC3 getRootNode putShellSt $ SCZipper t [] Set nid f -> do newNode <- (f . nodeById nid) `fmap` getShellSt liftIO $ withSC3 $ setNode newNode modifyShellSt $ \st -> insert' newNode AddReplace (nodeId newNode) st Free ns -> do modifyShellSt (foldr (.) id (map delete ns)) liftIO $ withSC3 $ flip send $ n_free ns New i param -> case param of Nothing -> do st <- getShellSt let st' = insert (Group i []) st j = nodeId $ focus st putShellSt st' liftIO $ withSC3 $ flip send $ g_new [(i,AddToTail,j)] Just (name,ps) -> do st <- getShellSt let newNode = Synth i name ps st' = insert newNode st j = nodeId $ focus st putShellSt st' liftIO $ withSC3 $ addNode j newNode Run r -> do nid <- (nodeId . focus) `fmap` getShellSt liftIO $ withSC3 $ flip send $ n_run [(nid,r)] Status -> liftIO $ withSC3 serverStatus >>= mapM_ putStrLn Refresh -> do t <- liftIO $ withSC3 getRootNode putShellSt $ SCZipper t [] -- | Show synth node in ls command. showNode :: SCNode -> String showNode s = case s of Synth _ _ ps -> foldr f [] ps where f p ps = show p ++ "\n" ++ ps Group nid ss -> foldr f [] ss where f n ns = g n ++ "\n" ++ ns g n = case n of Group nid _ -> "g:" ++ show nid Synth nid name _ -> "s:" ++ show nid ++ "[" ++ name ++ "]"
null
https://raw.githubusercontent.com/8c6794b6/haskell-sc-scratch/22de2199359fa56f256b544609cd6513b5e40f43/Scratch/Repl/SCShell.hs
haskell
---------------------------------------------------------------------------- | Module : $Header$ License : BSD3 Stability : unstable Portability : non-portable Interactive shell for scsynth nodes. | TODO: * Reuse synth connection inside shell. | TODO: * DONE, but not so useful: 'pwd' * DONE: 'cd', specifying destination in absolute and relative path. * DONE: 'ls', take optional directory path to show. * DONE: 'tree', show nodes under given path with 'drawSCNode' function. * DONE: 'mv', to move around node with specifying new position * 'find', querying node like, find command, or WHERE clause in SQL. | Show synth node in ls command.
# LANGUAGE FlexibleInstances # # LANGUAGE UndecidableInstances # Maintainer : Note that , backend used in this module is customized . Modified mtl version in dependency list of Shellac - haskeline 's cabal file from 1.1.1.1 to 2.0.1 . module SCShell where import Control.Monad.Trans (liftIO) import System.Console.Shell import System.Console.Shell.Backend.Haskeline import System.Console.Shell.ShellMonad import Sound.SC3 import Sound.SC3.Lepton import Parser1 import SampleData import SCZipper * Add synth protocol and port number in state ( default : udp 57110 ) . main :: IO () main = do ini <- (flip SCZipper []) `fmap` withSC3 getRootNode runShell shellDesc haskelineBackend ini putStrLn "Bye." shellDesc :: ShellDescription SCZipper shellDesc = (mkShellDescription cmds work) { prompt = \st -> return $ makePrompt st , greetingText = Just ("Type ':q' to quit\n") } makePrompt :: SCZipper -> String makePrompt z = foldr f "/" ns ++ g (focus z) ++ " > " where ns = filter (\(SCPath n _ _) -> n /= 0) $ reverse $ scPaths z f (SCPath n _ _) cs = "/" ++ show n ++ cs g n | nodeId n == 0 = "" | otherwise = case n of Group gid _ -> show gid Synth nid def _ -> show nid ++ "[" ++ def ++ "]" cmds :: [ShellCommand SCZipper] cmds = [exitCommand "q"] Use Parsec and write below commands : * DONE : ' set ' , sends n_set OSC command * DONE : ' free ' , sends n_free OSC command * DONE : ' set ' , with n_map and n_mapn . work :: String -> Sh SCZipper () work cs | null $ dropWhile (== ' ') cs = return () | otherwise = case parseCmd cs of Left err -> shellPutErrLn $ show err Right cmd -> case cmd of Pwd -> shellPutStrLn . show =<< getShellSt Ls f -> shellPutStr . showNode . focus . f =<< getShellSt Tree f -> shellPutStr . drawSCNode . focus . f =<< getShellSt Cd f -> modifyShellSt f Mv act source target -> do liftIO $ withSC3 $ flip send $ n_order act source target t <- liftIO $ withSC3 getRootNode putShellSt $ SCZipper t [] Set nid f -> do newNode <- (f . nodeById nid) `fmap` getShellSt liftIO $ withSC3 $ setNode newNode modifyShellSt $ \st -> insert' newNode AddReplace (nodeId newNode) st Free ns -> do modifyShellSt (foldr (.) id (map delete ns)) liftIO $ withSC3 $ flip send $ n_free ns New i param -> case param of Nothing -> do st <- getShellSt let st' = insert (Group i []) st j = nodeId $ focus st putShellSt st' liftIO $ withSC3 $ flip send $ g_new [(i,AddToTail,j)] Just (name,ps) -> do st <- getShellSt let newNode = Synth i name ps st' = insert newNode st j = nodeId $ focus st putShellSt st' liftIO $ withSC3 $ addNode j newNode Run r -> do nid <- (nodeId . focus) `fmap` getShellSt liftIO $ withSC3 $ flip send $ n_run [(nid,r)] Status -> liftIO $ withSC3 serverStatus >>= mapM_ putStrLn Refresh -> do t <- liftIO $ withSC3 getRootNode putShellSt $ SCZipper t [] showNode :: SCNode -> String showNode s = case s of Synth _ _ ps -> foldr f [] ps where f p ps = show p ++ "\n" ++ ps Group nid ss -> foldr f [] ss where f n ns = g n ++ "\n" ++ ns g n = case n of Group nid _ -> "g:" ++ show nid Synth nid name _ -> "s:" ++ show nid ++ "[" ++ name ++ "]"
9f08b8b9afadc399bd128c6573efabed50723631e9a30e56538722503f4a8e05
bos/rwh
PodDownload.hs
{-- snippet all --} module PodDownload where import PodTypes import PodDB import PodParser import Network.HTTP import System.IO import Database.HDBC import Data.Maybe import Network.URI {- | Download a URL. (Left errorMessage) if an error, (Right doc) if success. -} downloadURL :: String -> IO (Either String String) downloadURL url = do resp <- simpleHTTP request case resp of Left x -> return $ Left ("Error connecting: " ++ show x) Right r -> case rspCode r of (2,_,_) -> return $ Right (rspBody r) (3,_,_) -> -- A HTTP redirect case findHeader HdrLocation r of Nothing -> return $ Left (show r) Just url -> downloadURL url _ -> return $ Left (show r) where request = Request {rqURI = uri, rqMethod = GET, rqHeaders = [], rqBody = ""} uri = fromJust $ parseURI url {- | Update the podcast in the database. -} updatePodcastFromFeed :: IConnection conn => conn -> Podcast -> IO () updatePodcastFromFeed dbh pc = do resp <- downloadURL (castURL pc) case resp of Left x -> putStrLn x Right doc -> updateDB doc where updateDB doc = do mapM_ (addEpisode dbh) episodes commit dbh where feed = parse doc (castURL pc) episodes = map (item2ep pc) (items feed) {- | Downloads an episode, returning a String representing the filename it was placed into, or Nothing on error. -} getEpisode :: IConnection conn => conn -> Episode -> IO (Maybe String) getEpisode dbh ep = do resp <- downloadURL (epURL ep) case resp of Left x -> do putStrLn x return Nothing Right doc -> do file <- openBinaryFile filename WriteMode hPutStr file doc hClose file updateEpisode dbh (ep {epDone = True}) commit dbh return (Just filename) -- This function ought to apply an extension based on the filetype where filename = "pod." ++ (show . castId . epCast $ ep) ++ "." ++ (show (epId ep)) ++ ".mp3" {-- /snippet all --}
null
https://raw.githubusercontent.com/bos/rwh/7fd1e467d54aef832f5476ebf5f4f6a898a895d1/examples/ch23/PodDownload.hs
haskell
- snippet all - | Download a URL. (Left errorMessage) if an error, (Right doc) if success. A HTTP redirect | Update the podcast in the database. | Downloads an episode, returning a String representing the filename it was placed into, or Nothing on error. This function ought to apply an extension based on the filetype - /snippet all -
module PodDownload where import PodTypes import PodDB import PodParser import Network.HTTP import System.IO import Database.HDBC import Data.Maybe import Network.URI downloadURL :: String -> IO (Either String String) downloadURL url = do resp <- simpleHTTP request case resp of Left x -> return $ Left ("Error connecting: " ++ show x) Right r -> case rspCode r of (2,_,_) -> return $ Right (rspBody r) case findHeader HdrLocation r of Nothing -> return $ Left (show r) Just url -> downloadURL url _ -> return $ Left (show r) where request = Request {rqURI = uri, rqMethod = GET, rqHeaders = [], rqBody = ""} uri = fromJust $ parseURI url updatePodcastFromFeed :: IConnection conn => conn -> Podcast -> IO () updatePodcastFromFeed dbh pc = do resp <- downloadURL (castURL pc) case resp of Left x -> putStrLn x Right doc -> updateDB doc where updateDB doc = do mapM_ (addEpisode dbh) episodes commit dbh where feed = parse doc (castURL pc) episodes = map (item2ep pc) (items feed) getEpisode :: IConnection conn => conn -> Episode -> IO (Maybe String) getEpisode dbh ep = do resp <- downloadURL (epURL ep) case resp of Left x -> do putStrLn x return Nothing Right doc -> do file <- openBinaryFile filename WriteMode hPutStr file doc hClose file updateEpisode dbh (ep {epDone = True}) commit dbh return (Just filename) where filename = "pod." ++ (show . castId . epCast $ ep) ++ "." ++ (show (epId ep)) ++ ".mp3"
016d42bf5264cf392cadcda93e79172539c41bcb8574e5ad88962acec2dc8539
v0d1ch/plaid
TransactionsRefreshBody.hs
module Data.Proof.TransactionsRefreshBody ( HasTransactionsRefreshBody , proveTransactionsRefreshBody ) where import Data.Api.Types import Data.Proof.Named import Data.Text (Text) data HasTransactionsRefreshBody plaidEnv accessToken = Proof proveTransactionsRefreshBody :: Named plaidEnv PlaidEnv -> Named accessToken AccessToken -> Either Text (HasTransactionsRefreshBody plaidEnv accessToken) proveTransactionsRefreshBody _ atoken = case unWrapNamed atoken of (AccessToken "") -> Left "AccessToken cannot be empty" (AccessToken _ ) -> Right Proof
null
https://raw.githubusercontent.com/v0d1ch/plaid/9a9a37e4284f890a1dbebfcd515eea72510bf805/Data/Proof/TransactionsRefreshBody.hs
haskell
module Data.Proof.TransactionsRefreshBody ( HasTransactionsRefreshBody , proveTransactionsRefreshBody ) where import Data.Api.Types import Data.Proof.Named import Data.Text (Text) data HasTransactionsRefreshBody plaidEnv accessToken = Proof proveTransactionsRefreshBody :: Named plaidEnv PlaidEnv -> Named accessToken AccessToken -> Either Text (HasTransactionsRefreshBody plaidEnv accessToken) proveTransactionsRefreshBody _ atoken = case unWrapNamed atoken of (AccessToken "") -> Left "AccessToken cannot be empty" (AccessToken _ ) -> Right Proof
d4412080e881c71f97aeefa02ebc3989c639f7b36211784c37857616e9b3a241
liqd/aula
SeleniumSpec.hs
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables #-} # LANGUAGE ViewPatterns # # OPTIONS_GHC -Werror -Wall -fno - warn - incomplete - patterns # -- | selenium tests. -- -- run these by running `make selenium` in a terminal in the aula-docker image. -- for debugging , you have two options : -- 1 . sprinkle @getSource > > = writeFile " /page.html"@ , @saveScreenshot " /screenshot.png"@ over your ' WD ' monads . 2 . watch with vncviewer ( see ` /docs / testing.md ` ) . module SeleniumSpec where import Data.Aeson import qualified Data.HashMap.Strict as HM import Data.Text as ST import Test.Hspec import Test.WebDriver import Test.WebDriver.Missing import Arbitrary () import AulaTests spec :: Spec spec = do describe "@Selenium" . around withServer $ do it "works" $ \wreq -> runWDAula (openPage (mkUri wreq "") >> findElem (ByTag "h1") >>= getText) `shouldReturn` Just "Willkommen bei Aula" it "proofs a concept" $ \wreq -> do imgdata <- runWDAula $ do -- login and visit own profile openPage (mkUri wreq "") sendKeys "admin" =<< findElem (ByXPath "//input[@id='/login.user']") sendKeys "pssst" =<< findElem (ByXPath "//input[@id='/login.pass']") submit =<< findElem (ByXPath ".//input[@type='submit']") click =<< findElem (ByXPath ".//span[@class='user-name']") jsGetBase64Image "//img" -- liftIO $ print imgdata -- Just (Object (fromList [("value",String "data:image/png;base64,[...]")])) case imgdata of Just (Object (HM.toList -> [("value", String value)])) -> ST.unpack value `shouldContain` "data:image/png;base64,"
null
https://raw.githubusercontent.com/liqd/aula/f96dbf85cd80d0b445e7d198c9b2866bed9c4e3d/tests/SeleniumSpec.hs
haskell
# LANGUAGE OverloadedStrings # # LANGUAGE ScopedTypeVariables # | selenium tests. run these by running `make selenium` in a terminal in the aula-docker image. login and visit own profile liftIO $ print imgdata Just (Object (fromList [("value",String "data:image/png;base64,[...]")]))
# LANGUAGE ViewPatterns # # OPTIONS_GHC -Werror -Wall -fno - warn - incomplete - patterns # for debugging , you have two options : 1 . sprinkle @getSource > > = writeFile " /page.html"@ , @saveScreenshot " /screenshot.png"@ over your ' WD ' monads . 2 . watch with vncviewer ( see ` /docs / testing.md ` ) . module SeleniumSpec where import Data.Aeson import qualified Data.HashMap.Strict as HM import Data.Text as ST import Test.Hspec import Test.WebDriver import Test.WebDriver.Missing import Arbitrary () import AulaTests spec :: Spec spec = do describe "@Selenium" . around withServer $ do it "works" $ \wreq -> runWDAula (openPage (mkUri wreq "") >> findElem (ByTag "h1") >>= getText) `shouldReturn` Just "Willkommen bei Aula" it "proofs a concept" $ \wreq -> do imgdata <- runWDAula $ do openPage (mkUri wreq "") sendKeys "admin" =<< findElem (ByXPath "//input[@id='/login.user']") sendKeys "pssst" =<< findElem (ByXPath "//input[@id='/login.pass']") submit =<< findElem (ByXPath ".//input[@type='submit']") click =<< findElem (ByXPath ".//span[@class='user-name']") jsGetBase64Image "//img" case imgdata of Just (Object (HM.toList -> [("value", String value)])) -> ST.unpack value `shouldContain` "data:image/png;base64,"
e325ff927a0551fcfaeed6a2385d14e5dbb539c0d790b879a937bc4914962ac8
melisgl/mgl-pax
util.lisp
(in-package :mgl-pax) (defmacro with-standard-io-syntax* (&body body) `(with-standard-io-syntax With * PRINT - READABLY * , CLISP insists on printing FOO as |FOO| . (let (#+clisp (*print-readably* nil)) ,@body))) (defun find-package* (name) On AllegroCL , FIND - PACKAGE will signal an error if a relative ;; package name has too many leading dots. (ignore-errors (find-package name))) (defun external-symbol-p (symbol) (eq (nth-value 1 (find-symbol (symbol-name symbol) (symbol-package symbol))) :external)) (defun symbol-global-value (symbol) #+allegro (multiple-value-bind (value bound) (sys:global-symbol-value symbol) (values value (eq bound :unbound))) #+ccl (let ((value (ccl::%sym-global-value symbol))) (values value (eq value (ccl::%unbound-marker)))) #+sbcl (ignore-errors (sb-ext:symbol-global-value symbol)) #-(or allegro ccl sbcl) (ignore-errors (symbol-value symbol))) ;;; Like SYMBOL-FUNCTION*, but sees through encapsulated functions. (defun symbol-function* (symbol) #+abcl (or (system::untraced-function symbol) (symbol-function symbol)) #+clisp (or (system::get-traced-definition symbol) (symbol-function symbol)) #+cmucl (eval `(function ,symbol)) #-(or abcl cmucl clisp) (unencapsulated-function (symbol-function symbol))) (defun unencapsulated-function (function) (or #+ccl (ccl::find-unencapsulated-definition function) #+ecl (find-type-in-sexp (function-lambda-expression function) 'function) #+sbcl (maybe-find-encapsulated-function function) function)) #+sbcl ;;; Tracing typically encapsulate a function in a closure. The ;;; function we need is at the end of the encapsulation chain. (defun maybe-find-encapsulated-function (function) (declare (type function function)) (if (eq (sb-impl::%fun-name function) 'sb-impl::encapsulation) (maybe-find-encapsulated-function (sb-impl::encapsulation-info-definition (sb-impl::encapsulation-info function))) function)) #+ecl (defun find-type-in-sexp (form type) (dolist (x form) (cond ((listp x) (let ((r (find-type-in-sexp x type))) (when r (return-from find-type-in-sexp r)))) ((typep x type) (return-from find-type-in-sexp x)) (t nil)))) (defun function-name (function) (let* ((function (unencapsulated-function function)) (name #+clisp (system::function-name function) #-clisp (swank-backend:function-name function))) ABCL has function names like ( FOO ( SYSTEM::INTERPRETED ) ) . (if (listp name) (first name) name))) (defun arglist (function-designator) (let ((function-designator (if (symbolp function-designator) function-designator (unencapsulated-function function-designator)))) #+abcl (multiple-value-bind (arglist foundp) (extensions:arglist function-designator) (cond (foundp arglist) ((typep function-designator 'generic-function) (mop:generic-function-lambda-list function-designator)) ((and (symbolp function-designator) (typep (symbol-function* function-designator) 'generic-function)) (mop:generic-function-lambda-list (symbol-function* function-designator))))) #+allegro (handler-case (let* ((symbol (if (symbolp function-designator) function-designator (function-name function-designator))) (lambda-expression (ignore-errors (function-lambda-expression (symbol-function symbol))))) (if lambda-expression (second lambda-expression) (excl:arglist symbol))) (simple-error () :not-available)) #+ccl (let ((arglist (swank-backend:arglist function-designator))) ;; Function arglist don't have the default values of &KEY and & OPTIONAL arguments . Get those from CCL : FUNCTION - SOURCE - NOTE . (or (and (or (find '&key arglist) (find '&optional arglist)) (function-arglist-from-source-note function-designator)) (if (listp arglist) ;; &KEY arguments are given as keywords, which screws up ;; WITH-DISLOCATED-SYMBOLS when generating documentation ;; for functions. (mapcar (lambda (x) (if (keywordp x) (intern (string x)) x)) arglist) arglist))) #-(or abcl allegro ccl) (swank-backend:arglist function-designator))) #+ccl (defun function-arglist-from-source-note (function-designator) (multiple-value-bind (function-name function) (if (functionp function-designator) (values (function-name function-designator) function-designator) (values function-designator (fdefinition function-designator))) (when function (let ((source-note (ccl:function-source-note function))) (when source-note (let ((text (ccl:source-note-text source-note))) (when text (lambda-list-from-source-note-text text function-name)))))))) ;;; Extract the lambda list from TEXT, which is like "(defun foo (x ;;; &optional (o 1)) ...". #+ccl (defun lambda-list-from-source-note-text (text symbol) ;; This is a heuristic. It is impossible to determine what *PACKAGE* ;; was when the definition form was read. (let ((*package* (symbol-package symbol))) (with-input-from-string (s text) (when (eql (read-char s nil) #\() Skip DEFUN and the name . (let ((*read-suppress* t)) (read s nil) (read s nil)) (ignore-errors (read s)))))) (defun find-method* (function-designator qualifiers specializers &optional (errorp t)) (find-method (if (symbolp function-designator) (symbol-function* function-designator) function-designator) qualifiers (specializers-to-objects specializers) errorp)) (defun specializers-to-objects (specializers) #-(or allegro ccl clisp) specializers #+(or allegro ccl clisp) (mapcar #'specializer-to-object specializers)) #+(or allegro ccl clisp) (defun specializer-to-object (specializer) (cond ((symbolp specializer) (find-class specializer)) ((and (listp specializer) (= (length specializer) 2) (eq (first specializer) 'eql)) #+allegro (aclmop:intern-eql-specializer (second specializer)) #+ccl (ccl:intern-eql-specializer (second specializer)) #+clisp specializer) (t specializer))) (defmacro with-debugger-hook (fn &body body) (alexandria:with-gensyms (prev-debugger-hook condition this-hook) `(let* ((,prev-debugger-hook *debugger-hook*) (*debugger-hook* (lambda (,condition ,this-hook) (declare (ignore ,this-hook)) (funcall ,fn ,condition) (let ((*debugger-hook* ,prev-debugger-hook)) (invoke-debugger ,condition))))) ,@body))) ;;; Convert to full width character string. Useful for prettier ;;; printing and ensuring canonical form. (defun character-string (string) (make-array (length string) :element-type 'character :initial-contents string)) (defun subseq* (seq start) (subseq seq (min (length seq) start))) (defun relativize-pathname (pathname reference-pathname) "Return a pathname that's equivalent to PATHNAME but relative to REFERENCE-PATHNAME if possible. Like ENOUGH-NAMESTRING, but inserts :UP components if necessary." (let ((pathname (merge-pathnames pathname *default-pathname-defaults*)) (reference-pathname (merge-pathnames reference-pathname *default-pathname-defaults*))) (assert (equal (pathname-host pathname) (pathname-host reference-pathname))) (assert (equal (pathname-device pathname) (pathname-device reference-pathname))) (let* ((dir (pathname-directory pathname)) (ref-dir (pathname-directory reference-pathname)) (mismatch-index (or (mismatch dir ref-dir :test #'equal) (length dir)))) (normalize-pathname (make-pathname :directory (nconc (list :relative) (make-list (- (length ref-dir) mismatch-index) :initial-element :up) (subseq dir mismatch-index)) :defaults pathname))))) (defun normalize-pathname (pathname) (if (equal '(:relative) (pathname-directory pathname)) ;; Some implementations print (:RELATIVE) as "", some as "./", ;; no such troubles with the equivalent (). (make-pathname :directory () :defaults pathname) pathname)) ;;;; String utilities (eval-when (:compile-toplevel :load-toplevel :execute) (defparameter *whitespace-chars* '(#\Space #\Tab #\Return #\Newline #\Linefeed #\Page))) (defun whitespacep (char) (member char *whitespace-chars*)) (defun blankp (string) (every #'whitespacep string)) (defun trim-whitespace (string) (string-trim #.(format nil "~{~A~}" *whitespace-chars*) string)) ;;; Add PREFIX to every line in STRING. (defun prefix-lines (prefix string &key exclude-first-line-p) (with-output-to-string (out) (with-input-from-string (in string) (loop for i upfrom 0 do (multiple-value-bind (line missing-newline-p) (read-line in nil nil) (unless line (return)) (if (and exclude-first-line-p (= i 0)) (format out "~a" line) (format out "~a~a" prefix line)) (unless missing-newline-p (terpri out)))))))
null
https://raw.githubusercontent.com/melisgl/mgl-pax/bdd4cd21e41460610796a58812f021b054e0d463/src/navigate/util.lisp
lisp
package name has too many leading dots. Like SYMBOL-FUNCTION*, but sees through encapsulated functions. Tracing typically encapsulate a function in a closure. The function we need is at the end of the encapsulation chain. Function arglist don't have the default values of &KEY and &KEY arguments are given as keywords, which screws up WITH-DISLOCATED-SYMBOLS when generating documentation for functions. Extract the lambda list from TEXT, which is like "(defun foo (x &optional (o 1)) ...". This is a heuristic. It is impossible to determine what *PACKAGE* was when the definition form was read. Convert to full width character string. Useful for prettier printing and ensuring canonical form. Some implementations print (:RELATIVE) as "", some as "./", no such troubles with the equivalent (). String utilities Add PREFIX to every line in STRING.
(in-package :mgl-pax) (defmacro with-standard-io-syntax* (&body body) `(with-standard-io-syntax With * PRINT - READABLY * , CLISP insists on printing FOO as |FOO| . (let (#+clisp (*print-readably* nil)) ,@body))) (defun find-package* (name) On AllegroCL , FIND - PACKAGE will signal an error if a relative (ignore-errors (find-package name))) (defun external-symbol-p (symbol) (eq (nth-value 1 (find-symbol (symbol-name symbol) (symbol-package symbol))) :external)) (defun symbol-global-value (symbol) #+allegro (multiple-value-bind (value bound) (sys:global-symbol-value symbol) (values value (eq bound :unbound))) #+ccl (let ((value (ccl::%sym-global-value symbol))) (values value (eq value (ccl::%unbound-marker)))) #+sbcl (ignore-errors (sb-ext:symbol-global-value symbol)) #-(or allegro ccl sbcl) (ignore-errors (symbol-value symbol))) (defun symbol-function* (symbol) #+abcl (or (system::untraced-function symbol) (symbol-function symbol)) #+clisp (or (system::get-traced-definition symbol) (symbol-function symbol)) #+cmucl (eval `(function ,symbol)) #-(or abcl cmucl clisp) (unencapsulated-function (symbol-function symbol))) (defun unencapsulated-function (function) (or #+ccl (ccl::find-unencapsulated-definition function) #+ecl (find-type-in-sexp (function-lambda-expression function) 'function) #+sbcl (maybe-find-encapsulated-function function) function)) #+sbcl (defun maybe-find-encapsulated-function (function) (declare (type function function)) (if (eq (sb-impl::%fun-name function) 'sb-impl::encapsulation) (maybe-find-encapsulated-function (sb-impl::encapsulation-info-definition (sb-impl::encapsulation-info function))) function)) #+ecl (defun find-type-in-sexp (form type) (dolist (x form) (cond ((listp x) (let ((r (find-type-in-sexp x type))) (when r (return-from find-type-in-sexp r)))) ((typep x type) (return-from find-type-in-sexp x)) (t nil)))) (defun function-name (function) (let* ((function (unencapsulated-function function)) (name #+clisp (system::function-name function) #-clisp (swank-backend:function-name function))) ABCL has function names like ( FOO ( SYSTEM::INTERPRETED ) ) . (if (listp name) (first name) name))) (defun arglist (function-designator) (let ((function-designator (if (symbolp function-designator) function-designator (unencapsulated-function function-designator)))) #+abcl (multiple-value-bind (arglist foundp) (extensions:arglist function-designator) (cond (foundp arglist) ((typep function-designator 'generic-function) (mop:generic-function-lambda-list function-designator)) ((and (symbolp function-designator) (typep (symbol-function* function-designator) 'generic-function)) (mop:generic-function-lambda-list (symbol-function* function-designator))))) #+allegro (handler-case (let* ((symbol (if (symbolp function-designator) function-designator (function-name function-designator))) (lambda-expression (ignore-errors (function-lambda-expression (symbol-function symbol))))) (if lambda-expression (second lambda-expression) (excl:arglist symbol))) (simple-error () :not-available)) #+ccl (let ((arglist (swank-backend:arglist function-designator))) & OPTIONAL arguments . Get those from CCL : FUNCTION - SOURCE - NOTE . (or (and (or (find '&key arglist) (find '&optional arglist)) (function-arglist-from-source-note function-designator)) (if (listp arglist) (mapcar (lambda (x) (if (keywordp x) (intern (string x)) x)) arglist) arglist))) #-(or abcl allegro ccl) (swank-backend:arglist function-designator))) #+ccl (defun function-arglist-from-source-note (function-designator) (multiple-value-bind (function-name function) (if (functionp function-designator) (values (function-name function-designator) function-designator) (values function-designator (fdefinition function-designator))) (when function (let ((source-note (ccl:function-source-note function))) (when source-note (let ((text (ccl:source-note-text source-note))) (when text (lambda-list-from-source-note-text text function-name)))))))) #+ccl (defun lambda-list-from-source-note-text (text symbol) (let ((*package* (symbol-package symbol))) (with-input-from-string (s text) (when (eql (read-char s nil) #\() Skip DEFUN and the name . (let ((*read-suppress* t)) (read s nil) (read s nil)) (ignore-errors (read s)))))) (defun find-method* (function-designator qualifiers specializers &optional (errorp t)) (find-method (if (symbolp function-designator) (symbol-function* function-designator) function-designator) qualifiers (specializers-to-objects specializers) errorp)) (defun specializers-to-objects (specializers) #-(or allegro ccl clisp) specializers #+(or allegro ccl clisp) (mapcar #'specializer-to-object specializers)) #+(or allegro ccl clisp) (defun specializer-to-object (specializer) (cond ((symbolp specializer) (find-class specializer)) ((and (listp specializer) (= (length specializer) 2) (eq (first specializer) 'eql)) #+allegro (aclmop:intern-eql-specializer (second specializer)) #+ccl (ccl:intern-eql-specializer (second specializer)) #+clisp specializer) (t specializer))) (defmacro with-debugger-hook (fn &body body) (alexandria:with-gensyms (prev-debugger-hook condition this-hook) `(let* ((,prev-debugger-hook *debugger-hook*) (*debugger-hook* (lambda (,condition ,this-hook) (declare (ignore ,this-hook)) (funcall ,fn ,condition) (let ((*debugger-hook* ,prev-debugger-hook)) (invoke-debugger ,condition))))) ,@body))) (defun character-string (string) (make-array (length string) :element-type 'character :initial-contents string)) (defun subseq* (seq start) (subseq seq (min (length seq) start))) (defun relativize-pathname (pathname reference-pathname) "Return a pathname that's equivalent to PATHNAME but relative to REFERENCE-PATHNAME if possible. Like ENOUGH-NAMESTRING, but inserts :UP components if necessary." (let ((pathname (merge-pathnames pathname *default-pathname-defaults*)) (reference-pathname (merge-pathnames reference-pathname *default-pathname-defaults*))) (assert (equal (pathname-host pathname) (pathname-host reference-pathname))) (assert (equal (pathname-device pathname) (pathname-device reference-pathname))) (let* ((dir (pathname-directory pathname)) (ref-dir (pathname-directory reference-pathname)) (mismatch-index (or (mismatch dir ref-dir :test #'equal) (length dir)))) (normalize-pathname (make-pathname :directory (nconc (list :relative) (make-list (- (length ref-dir) mismatch-index) :initial-element :up) (subseq dir mismatch-index)) :defaults pathname))))) (defun normalize-pathname (pathname) (if (equal '(:relative) (pathname-directory pathname)) (make-pathname :directory () :defaults pathname) pathname)) (eval-when (:compile-toplevel :load-toplevel :execute) (defparameter *whitespace-chars* '(#\Space #\Tab #\Return #\Newline #\Linefeed #\Page))) (defun whitespacep (char) (member char *whitespace-chars*)) (defun blankp (string) (every #'whitespacep string)) (defun trim-whitespace (string) (string-trim #.(format nil "~{~A~}" *whitespace-chars*) string)) (defun prefix-lines (prefix string &key exclude-first-line-p) (with-output-to-string (out) (with-input-from-string (in string) (loop for i upfrom 0 do (multiple-value-bind (line missing-newline-p) (read-line in nil nil) (unless line (return)) (if (and exclude-first-line-p (= i 0)) (format out "~a" line) (format out "~a~a" prefix line)) (unless missing-newline-p (terpri out)))))))
9dbbe1fb78551b3944788f9640257d191da2b6de3ececb75640f470c5ec3732a
aisamanra/apicius
ReverseTree.hs
# LANGUAGE ParallelListComp # module Apicius.ReverseTree where import Apicius.AST import Data.Monoid ((<>)) import Data.Text (Text) import qualified Data.Text as T An ' ActionChunk ' represents a set of actions in between two join -- points. This is 'reversed' from what we'd expect: the 'name' is -- actually the name of the join point at the end of a sequence of -- actions, or the string DONE, while the 'prev' is the name of the -- join point that came at the beginning, or the ingredients list -- that started the rule. The actions also will appear in reverse -- order. -- Maybe an explanation is in order: this rule -- ingredients -> a -> $x -> b -> c -> $y; will produce two ActionChunks : -- ActionChunk $y [c, b] (Right $x) -- and -- ActionChunk $x [a] (Left ingredients) data ActionChunk = ActionChunk { acName :: Text, acRules :: [Text], acPrev :: Either IngredientList Text } deriving (Eq, Show) -- This is the function that actually splits apart the action into -- ActionChunks. It's grosser than I'd hoped, but it's mostly a lot -- of fiddly but straightforward traversing. splitApart :: Either IngredientList Text -> [Action] -> [ActionChunk] splitApart i = toChunk [] . reverse where toChunk cs (Join t : xs) = gather t xs [] cs toChunk cs (Action "DONE" _ : xs) = gather "DONE" xs [] cs toChunk cs (Done : xs) = gather "DONE" xs [] cs toChunk _ (Action _ _ : _) = error "expected chunk to end with a join or DONE" toChunk cs [] = cs gather n xs@(Join t : _) as cs = toChunk (ActionChunk n (reverse as) (Right t) : cs) xs gather n (Action t _ : xs) as cs = gather n xs (t : as) cs gather _ (Done : _) _ _ = error "unsure how to handle this case" gather n [] as cs = ActionChunk n (reverse as) i : cs Here we take a recipe and pull all the ActionChunks into a single -- list. getChunks :: Recipe -> [ActionChunk] getChunks Recipe {rRecipe = st} = mconcat (map getActions st) where getActions (Step (InpJoin t) as) = splitApart (Right t) as getActions (Step (InpIngredients is) as) = splitApart (Left is) as -- The ReverseGraph is a tree rooted at the DONE node. The 'children' -- are actually the steps leading up to a given node. Only childless nodes should have an IngredientList associated with them , but we -- don't encode this invariant in the type. data ReverseGraph = ReverseGraph { rStep :: Either IngredientList Text, rPrevs :: [ReverseGraph] } deriving (Eq, Show) Take a list of ActionChunks and stitch them back together so that -- we can build a ReverseGraph of them. Again, fiddly but straightforward -- traversing of the data structures. buildReverseGraph :: [ActionChunk] -> ReverseGraph buildReverseGraph as = ReverseGraph (Right "DONE") (concat (map buildFrom (findChunks "DONE"))) where findChunks n = [chunk | chunk <- as, acName chunk == n] buildFrom (ActionChunk _ rs p) = go rs p go [] (Right p) = concat $ map buildFrom (findChunks p) go [] (Left i) = [ReverseGraph (Left i) []] go (r : rs) p = [ReverseGraph (Right r) (go rs p)] Prettily convert a ReverseGraph to a readable tree . This will give -- us a recipe tree in reverse order, starting with the DONE, and -- gradually going back to the ingredients. prettyGraph :: ReverseGraph -> Text prettyGraph = go 0 where go n (ReverseGraph t rs) = indent n <> stepName t <> "\n" <> T.concat (map (go (n + 2)) rs) indent n = T.replicate n " " stepName :: Either IngredientList Text -> Text stepName (Right t) = t stepName (Left (IngredientList is)) = T.intercalate "; " [ingName i | i <- is] ingName :: Ingredient -> Text ingName (Ingredient (Just amt) name) = amt <> " " <> name ingName (Ingredient Nothing name) = name showFragments :: Recipe -> Text showFragments = T.pack . show . getChunks showReverseTree :: Recipe -> Text showReverseTree = prettyGraph . buildReverseGraph . getChunks
null
https://raw.githubusercontent.com/aisamanra/apicius/2ea26530f99adbdbac139175922ecf61b596d408/Apicius/ReverseTree.hs
haskell
points. This is 'reversed' from what we'd expect: the 'name' is actually the name of the join point at the end of a sequence of actions, or the string DONE, while the 'prev' is the name of the join point that came at the beginning, or the ingredients list that started the rule. The actions also will appear in reverse order. Maybe an explanation is in order: this rule ingredients -> a -> $x -> b -> c -> $y; ActionChunk $y [c, b] (Right $x) and ActionChunk $x [a] (Left ingredients) This is the function that actually splits apart the action into ActionChunks. It's grosser than I'd hoped, but it's mostly a lot of fiddly but straightforward traversing. list. The ReverseGraph is a tree rooted at the DONE node. The 'children' are actually the steps leading up to a given node. Only childless don't encode this invariant in the type. we can build a ReverseGraph of them. Again, fiddly but straightforward traversing of the data structures. us a recipe tree in reverse order, starting with the DONE, and gradually going back to the ingredients.
# LANGUAGE ParallelListComp # module Apicius.ReverseTree where import Apicius.AST import Data.Monoid ((<>)) import Data.Text (Text) import qualified Data.Text as T An ' ActionChunk ' represents a set of actions in between two join will produce two ActionChunks : data ActionChunk = ActionChunk { acName :: Text, acRules :: [Text], acPrev :: Either IngredientList Text } deriving (Eq, Show) splitApart :: Either IngredientList Text -> [Action] -> [ActionChunk] splitApart i = toChunk [] . reverse where toChunk cs (Join t : xs) = gather t xs [] cs toChunk cs (Action "DONE" _ : xs) = gather "DONE" xs [] cs toChunk cs (Done : xs) = gather "DONE" xs [] cs toChunk _ (Action _ _ : _) = error "expected chunk to end with a join or DONE" toChunk cs [] = cs gather n xs@(Join t : _) as cs = toChunk (ActionChunk n (reverse as) (Right t) : cs) xs gather n (Action t _ : xs) as cs = gather n xs (t : as) cs gather _ (Done : _) _ _ = error "unsure how to handle this case" gather n [] as cs = ActionChunk n (reverse as) i : cs Here we take a recipe and pull all the ActionChunks into a single getChunks :: Recipe -> [ActionChunk] getChunks Recipe {rRecipe = st} = mconcat (map getActions st) where getActions (Step (InpJoin t) as) = splitApart (Right t) as getActions (Step (InpIngredients is) as) = splitApart (Left is) as nodes should have an IngredientList associated with them , but we data ReverseGraph = ReverseGraph { rStep :: Either IngredientList Text, rPrevs :: [ReverseGraph] } deriving (Eq, Show) Take a list of ActionChunks and stitch them back together so that buildReverseGraph :: [ActionChunk] -> ReverseGraph buildReverseGraph as = ReverseGraph (Right "DONE") (concat (map buildFrom (findChunks "DONE"))) where findChunks n = [chunk | chunk <- as, acName chunk == n] buildFrom (ActionChunk _ rs p) = go rs p go [] (Right p) = concat $ map buildFrom (findChunks p) go [] (Left i) = [ReverseGraph (Left i) []] go (r : rs) p = [ReverseGraph (Right r) (go rs p)] Prettily convert a ReverseGraph to a readable tree . This will give prettyGraph :: ReverseGraph -> Text prettyGraph = go 0 where go n (ReverseGraph t rs) = indent n <> stepName t <> "\n" <> T.concat (map (go (n + 2)) rs) indent n = T.replicate n " " stepName :: Either IngredientList Text -> Text stepName (Right t) = t stepName (Left (IngredientList is)) = T.intercalate "; " [ingName i | i <- is] ingName :: Ingredient -> Text ingName (Ingredient (Just amt) name) = amt <> " " <> name ingName (Ingredient Nothing name) = name showFragments :: Recipe -> Text showFragments = T.pack . show . getChunks showReverseTree :: Recipe -> Text showReverseTree = prettyGraph . buildReverseGraph . getChunks
809b1b04216183f4426cc645301873c48742020c1467056562195db6129dd0e1
onedata/op-worker
mi_transfers.erl
%%%------------------------------------------------------------------- @author ( C ) 2021 ACK CYFRONET AGH This software is released under the MIT license cited in ' LICENSE.txt ' . %%% @end %%%------------------------------------------------------------------- %%% @doc Interface for managing transfers ( requests are delegated to middleware_worker ) . %%% @end %%%------------------------------------------------------------------- -module(mi_transfers). -author("Bartosz Walkowicz"). -include("middleware/middleware.hrl"). %% API -export([ schedule_file_transfer/5, schedule_view_transfer/7 ]). %%%=================================================================== %%% API %%%=================================================================== -spec schedule_file_transfer( session:id(), lfm:file_key(), ReplicatingProviderId :: undefined | od_provider:id(), EvictingProviderId :: undefined | od_provider:id(), transfer:callback() ) -> transfer:id() | no_return(). schedule_file_transfer(SessionId, FileKey, ReplicatingProviderId, EvictingProviderId, Callback) -> FileGuid = lfm_file_key:resolve_file_key(SessionId, FileKey, do_not_resolve_symlink), middleware_worker:check_exec(SessionId, FileGuid, #file_transfer_schedule_request{ replicating_provider_id = ReplicatingProviderId, evicting_provider_id = EvictingProviderId, callback = Callback }). -spec schedule_view_transfer( session:id(), od_space:id(), transfer:view_name(), transfer:query_view_params(), ReplicatingProviderId :: undefined | od_provider:id(), EvictingProviderId :: undefined | od_provider:id(), transfer:callback() ) -> transfer:id() | no_return(). schedule_view_transfer( SessionId, SpaceId, ViewName, QueryViewParams, ReplicatingProviderId, EvictingProviderId, Callback ) -> SpaceGuid = fslogic_file_id:spaceid_to_space_dir_guid(SpaceId), middleware_worker:check_exec(SessionId, SpaceGuid, #view_transfer_schedule_request{ replicating_provider_id = ReplicatingProviderId, evicting_provider_id = EvictingProviderId, view_name = ViewName, query_view_params = QueryViewParams, callback = Callback }).
null
https://raw.githubusercontent.com/onedata/op-worker/a48082aad45530ab40cbe15a69c5057970a4bba1/src/middleware/interface/mi_transfers.erl
erlang
------------------------------------------------------------------- @end ------------------------------------------------------------------- @doc @end ------------------------------------------------------------------- API =================================================================== API ===================================================================
@author ( C ) 2021 ACK CYFRONET AGH This software is released under the MIT license cited in ' LICENSE.txt ' . Interface for managing transfers ( requests are delegated to middleware_worker ) . -module(mi_transfers). -author("Bartosz Walkowicz"). -include("middleware/middleware.hrl"). -export([ schedule_file_transfer/5, schedule_view_transfer/7 ]). -spec schedule_file_transfer( session:id(), lfm:file_key(), ReplicatingProviderId :: undefined | od_provider:id(), EvictingProviderId :: undefined | od_provider:id(), transfer:callback() ) -> transfer:id() | no_return(). schedule_file_transfer(SessionId, FileKey, ReplicatingProviderId, EvictingProviderId, Callback) -> FileGuid = lfm_file_key:resolve_file_key(SessionId, FileKey, do_not_resolve_symlink), middleware_worker:check_exec(SessionId, FileGuid, #file_transfer_schedule_request{ replicating_provider_id = ReplicatingProviderId, evicting_provider_id = EvictingProviderId, callback = Callback }). -spec schedule_view_transfer( session:id(), od_space:id(), transfer:view_name(), transfer:query_view_params(), ReplicatingProviderId :: undefined | od_provider:id(), EvictingProviderId :: undefined | od_provider:id(), transfer:callback() ) -> transfer:id() | no_return(). schedule_view_transfer( SessionId, SpaceId, ViewName, QueryViewParams, ReplicatingProviderId, EvictingProviderId, Callback ) -> SpaceGuid = fslogic_file_id:spaceid_to_space_dir_guid(SpaceId), middleware_worker:check_exec(SessionId, SpaceGuid, #view_transfer_schedule_request{ replicating_provider_id = ReplicatingProviderId, evicting_provider_id = EvictingProviderId, view_name = ViewName, query_view_params = QueryViewParams, callback = Callback }).
544d6d7bc57f5c55b55d601fdf52ce8af6019124a895a36cfb1483a5c61abaae
imitator-model-checker/imitator
AlgoEFgen.mli
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * IMITATOR * * Université Paris 13 , LIPN , CNRS , France * Université de Lorraine , CNRS , , LORIA , Nancy , France * * Module description : generic EFsynth algorithm [ JLR15 ] * * File contributors : * Created : 2015/11/25 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * IMITATOR * * Université Paris 13, LIPN, CNRS, France * Université de Lorraine, CNRS, Inria, LORIA, Nancy, France * * Module description: generic EFsynth algorithm [JLR15] * * File contributors : Étienne André * Created : 2015/11/25 * ************************************************************) (************************************************************) (* Modules *) (************************************************************) open AlgoStateBased open State (************************************************************) (* Class definition *) (************************************************************) class virtual algoEFgen : AbstractProperty.state_predicate -> object inherit algoStateBased (************************************************************) (* Class variables *) (************************************************************) method virtual algorithm_name : string (* Non-necessarily convex parameter constraint of the initial state (constant object used as a shortcut, as it is used at the end of the algorithm) *) (*** WARNING: these lines are copied from AlgoDeadlockFree ***) val init_p_nnconvex_constraint : LinearConstraint.p_nnconvex_constraint (************************************************************) (* Class methods *) (************************************************************) method run : unit -> Result.imitator_result method initialize_variables : unit (*------------------------------------------------------------*) (* Add a new state to the state space (if indeed needed) *) (* Return true if the state is not discarded by the algorithm, i.e., if it is either added OR was already present before *) Can raise an exception TerminateAnalysis to lead to an immediate termination (*------------------------------------------------------------*) (*** TODO: return the list of actually added states ***) method add_a_new_state : state_index -> StateSpace.combined_transition -> State.state -> bool (*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*) (** Actions to perform with the initial state; returns true unless the initial state cannot be kept (in which case the algorithm will stop immediately) *) (*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*) method process_initial_state : State.state -> bool (*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*) (* Actions to perform when meeting a state with no successors: nothing to do for this algorithm *) (*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*) method process_deadlock_state : state_index -> unit (*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*) (** Actions to perform at the end of the computation of the *successors* of post^n (i.e., when this method is called, the successors were just computed). Nothing to do for this algorithm. *) (*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*) method process_post_n : state_index list -> unit (*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*) (** Check whether the algorithm should terminate at the end of some post, independently of the number of states to be processed (e.g., if the constraint is already true or false) *) (*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*) method check_termination_at_post_n : bool method virtual compute_result : Result.imitator_result end
null
https://raw.githubusercontent.com/imitator-model-checker/imitator/105408ae2bd8c3e3291f286e4d127defd492a58b/src/AlgoEFgen.mli
ocaml
********************************************************** Modules ********************************************************** ********************************************************** Class definition ********************************************************** ********************************************************** Class variables ********************************************************** Non-necessarily convex parameter constraint of the initial state (constant object used as a shortcut, as it is used at the end of the algorithm) ** WARNING: these lines are copied from AlgoDeadlockFree ** ********************************************************** Class methods ********************************************************** ------------------------------------------------------------ Add a new state to the state space (if indeed needed) Return true if the state is not discarded by the algorithm, i.e., if it is either added OR was already present before ------------------------------------------------------------ ** TODO: return the list of actually added states ** -*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*- * Actions to perform with the initial state; returns true unless the initial state cannot be kept (in which case the algorithm will stop immediately) -*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*- -*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*- Actions to perform when meeting a state with no successors: nothing to do for this algorithm -*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*- -*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*- * Actions to perform at the end of the computation of the *successors* of post^n (i.e., when this method is called, the successors were just computed). Nothing to do for this algorithm. -*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*- -*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*- * Check whether the algorithm should terminate at the end of some post, independently of the number of states to be processed (e.g., if the constraint is already true or false) -*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * IMITATOR * * Université Paris 13 , LIPN , CNRS , France * Université de Lorraine , CNRS , , LORIA , Nancy , France * * Module description : generic EFsynth algorithm [ JLR15 ] * * File contributors : * Created : 2015/11/25 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * IMITATOR * * Université Paris 13, LIPN, CNRS, France * Université de Lorraine, CNRS, Inria, LORIA, Nancy, France * * Module description: generic EFsynth algorithm [JLR15] * * File contributors : Étienne André * Created : 2015/11/25 * ************************************************************) open AlgoStateBased open State class virtual algoEFgen : AbstractProperty.state_predicate -> object inherit algoStateBased method virtual algorithm_name : string val init_p_nnconvex_constraint : LinearConstraint.p_nnconvex_constraint method run : unit -> Result.imitator_result method initialize_variables : unit Can raise an exception TerminateAnalysis to lead to an immediate termination method add_a_new_state : state_index -> StateSpace.combined_transition -> State.state -> bool method process_initial_state : State.state -> bool method process_deadlock_state : state_index -> unit method process_post_n : state_index list -> unit method check_termination_at_post_n : bool method virtual compute_result : Result.imitator_result end
21a9f862217fa251e2f1d6fc49a1dc783bcea95151ac28e0e9ed7f11498f7583
noteed/mojito
SExpr.hs
# LANGUAGE FlexibleContexts # module Language.Mojito.Syntax.SExpr where import Text.ParserCombinators.Parsec hiding (State) import Control.Monad.Except ---------------------------------------------------------------------- -- S-Expressions ---------------------------------------------------------------------- -- An s-expression is either an atom or a list of s-expression. -- An atom can be a floating or integral number, a string, or -- a symbol (anything else). data SExpr = Sym String | FltNum Double | IntNum Integer | Str String | List [SExpr] deriving (Eq, Show) isSym :: SExpr -> Bool isSym (Sym _) = True isSym _ = False ---------------------------------------------------------------------- -- S-Expressions parsing ---------------------------------------------------------------------- Like parseSExpr but turns the Parsec ParseError into a string . parseSExpr' :: MonadError String m => String -> m SExpr parseSExpr' s = case parseSExpr s of Left err -> throwError $ show err Right r -> return r Like parseSExprs but turns the Parsec ParseError into a string . parseSExprs' :: MonadError String m => String -> m [SExpr] parseSExprs' s = case parseSExprs s of Left err -> throwError $ show err Right r -> return r an s - expression and return either a parse error -- or the parsed s-expression. parseSExpr :: String -> Either ParseError SExpr parseSExpr = parse (skipMany blank >> parseExpr) "s-expression" parseSExprs :: String -> Either ParseError [SExpr] parseSExprs = parse (many (skipMany blank >> parseExpr)) "s-expressions" Parse a complete symbol . parseSymbol :: Parser SExpr parseSymbol = do a <- (noneOf " \t\n\"()0123456789") b <- many (noneOf " \t\n\"()") return $ Sym (a : b) Parse a number , i.e. any symbol beginning with a digit . parseNumber :: Parser SExpr parseNumber = (intConstant >>= return . IntNum) <|> (floatingConstant >>= return . FltNum) -- Parse a string in double quotes. parseString :: Parser SExpr parseString = do _ <- char '"' x <- many (noneOf "\t\n\"") _ <- char '"' return $ Str x -- Parse an atom. The () atom is handled by parseList. parseAtom :: Parser SExpr parseAtom = parseSymbol <|> parseNumber <|> parseString Parse a list , i.e. many expressions bracketed by parens -- or the () atom. parseList :: Parser SExpr parseList = do _ <- char '(' skipMany blank x <- parseExprs _ <- char ')' return $ if null x then Sym "()" else List x -- Parse an expression (an atom or a list). parseExpr :: Parser SExpr parseExpr = do s <- (parseAtom <|> parseList) skipMany blank return s Parse many expressions ( parens not included ) . parseExprs :: Parser [SExpr] parseExprs = many parseExpr ---------------------------------------------------------------------- -- Number parsing (taken from language-glsl). ---------------------------------------------------------------------- TODO the size of the int should fit its type . intConstant :: Parser Integer intConstant = choice [ hexadecimal , octal , badOctal >> fail "Invalid octal number" , decimal ] floatingConstant :: Parser Double floatingConstant = choice [ floatExponent , floatPoint , pointFloat ] ---------------------------------------------------------------------- -- Lexical elements helpers ---------------------------------------------------------------------- comment :: Parser () comment = do _ <- string "--- " _ <- manyTill anyChar ((newline >> return ()) <|> eof) return () blank :: Parser () blank = try comment <|> (space >> return ()) hexadecimal :: Parser Integer hexadecimal = try $ do _ <- char '0' _ <- oneOf "Xx" d <- many1 hexDigit TODO return $ read ("0x" ++ d) octal :: Parser Integer octal = try $ do _ <- char '0' d <- many1 octDigit TODO return $ read ("0o" ++ d) badOctal :: Parser () badOctal = try $ char '0' >> many1 hexDigit >> return () decimal :: Parser Integer decimal = try $ do d <- many1 digit notFollowedBy (char '.' <|> (expo >> return ' ')) TODO return $ read d floatExponent :: Parser Double floatExponent = try $ do d <- many1 digit e <- expo TODO return $ read $ d ++ e floatPoint :: Parser Double floatPoint = try $ do d <- many1 digit _ <- char '.' d' <- many digit let d'' = if null d' then "0" else d' e <- optionMaybe expo TODO return $ read $ d ++ "." ++ d'' ++ maybe "" id e pointFloat :: Parser Double pointFloat = try $ do _ <- char '.' d <- many1 digit e <- optionMaybe expo TODO return $ read $ "0." ++ d ++ maybe "" id e expo :: Parser String expo = try $ do _ <- oneOf "Ee" s <- optionMaybe (oneOf "+-") d <- many1 digit return $ "e" ++ maybe "" (:[]) s ++ d
null
https://raw.githubusercontent.com/noteed/mojito/893d1d826d969b0db7bbc8884df3b417db151d14/Language/Mojito/Syntax/SExpr.hs
haskell
-------------------------------------------------------------------- S-Expressions -------------------------------------------------------------------- An s-expression is either an atom or a list of s-expression. An atom can be a floating or integral number, a string, or a symbol (anything else). -------------------------------------------------------------------- S-Expressions parsing -------------------------------------------------------------------- or the parsed s-expression. Parse a string in double quotes. Parse an atom. The () atom is handled by parseList. or the () atom. Parse an expression (an atom or a list). -------------------------------------------------------------------- Number parsing (taken from language-glsl). -------------------------------------------------------------------- -------------------------------------------------------------------- Lexical elements helpers --------------------------------------------------------------------
# LANGUAGE FlexibleContexts # module Language.Mojito.Syntax.SExpr where import Text.ParserCombinators.Parsec hiding (State) import Control.Monad.Except data SExpr = Sym String | FltNum Double | IntNum Integer | Str String | List [SExpr] deriving (Eq, Show) isSym :: SExpr -> Bool isSym (Sym _) = True isSym _ = False Like parseSExpr but turns the Parsec ParseError into a string . parseSExpr' :: MonadError String m => String -> m SExpr parseSExpr' s = case parseSExpr s of Left err -> throwError $ show err Right r -> return r Like parseSExprs but turns the Parsec ParseError into a string . parseSExprs' :: MonadError String m => String -> m [SExpr] parseSExprs' s = case parseSExprs s of Left err -> throwError $ show err Right r -> return r an s - expression and return either a parse error parseSExpr :: String -> Either ParseError SExpr parseSExpr = parse (skipMany blank >> parseExpr) "s-expression" parseSExprs :: String -> Either ParseError [SExpr] parseSExprs = parse (many (skipMany blank >> parseExpr)) "s-expressions" Parse a complete symbol . parseSymbol :: Parser SExpr parseSymbol = do a <- (noneOf " \t\n\"()0123456789") b <- many (noneOf " \t\n\"()") return $ Sym (a : b) Parse a number , i.e. any symbol beginning with a digit . parseNumber :: Parser SExpr parseNumber = (intConstant >>= return . IntNum) <|> (floatingConstant >>= return . FltNum) parseString :: Parser SExpr parseString = do _ <- char '"' x <- many (noneOf "\t\n\"") _ <- char '"' return $ Str x parseAtom :: Parser SExpr parseAtom = parseSymbol <|> parseNumber <|> parseString Parse a list , i.e. many expressions bracketed by parens parseList :: Parser SExpr parseList = do _ <- char '(' skipMany blank x <- parseExprs _ <- char ')' return $ if null x then Sym "()" else List x parseExpr :: Parser SExpr parseExpr = do s <- (parseAtom <|> parseList) skipMany blank return s Parse many expressions ( parens not included ) . parseExprs :: Parser [SExpr] parseExprs = many parseExpr TODO the size of the int should fit its type . intConstant :: Parser Integer intConstant = choice [ hexadecimal , octal , badOctal >> fail "Invalid octal number" , decimal ] floatingConstant :: Parser Double floatingConstant = choice [ floatExponent , floatPoint , pointFloat ] comment :: Parser () comment = do _ <- string "--- " _ <- manyTill anyChar ((newline >> return ()) <|> eof) return () blank :: Parser () blank = try comment <|> (space >> return ()) hexadecimal :: Parser Integer hexadecimal = try $ do _ <- char '0' _ <- oneOf "Xx" d <- many1 hexDigit TODO return $ read ("0x" ++ d) octal :: Parser Integer octal = try $ do _ <- char '0' d <- many1 octDigit TODO return $ read ("0o" ++ d) badOctal :: Parser () badOctal = try $ char '0' >> many1 hexDigit >> return () decimal :: Parser Integer decimal = try $ do d <- many1 digit notFollowedBy (char '.' <|> (expo >> return ' ')) TODO return $ read d floatExponent :: Parser Double floatExponent = try $ do d <- many1 digit e <- expo TODO return $ read $ d ++ e floatPoint :: Parser Double floatPoint = try $ do d <- many1 digit _ <- char '.' d' <- many digit let d'' = if null d' then "0" else d' e <- optionMaybe expo TODO return $ read $ d ++ "." ++ d'' ++ maybe "" id e pointFloat :: Parser Double pointFloat = try $ do _ <- char '.' d <- many1 digit e <- optionMaybe expo TODO return $ read $ "0." ++ d ++ maybe "" id e expo :: Parser String expo = try $ do _ <- oneOf "Ee" s <- optionMaybe (oneOf "+-") d <- many1 digit return $ "e" ++ maybe "" (:[]) s ++ d
7b261c762190c765efa21a596b56ba1fe0682df6215a70f34aeed3cc18a4a4cd
nklein/grid-generators
taxicab.lisp
;;;; taxicab.lisp (in-package #:grid-generators-tests) (nst:def-test-group 1d-taxicab-generator-tests () (nst:def-test 1d-taxicab (generates ((0) (-1) (1) (-2) (2))) (grid-generators:make-taxicab-generator 1 :minimum-steps 0 :maximum-steps 2)) (nst:def-test 1d-taxicab-default-min (generates ((0) (-1) (1) (-2) (2))) (grid-generators:make-taxicab-generator 1 :maximum-steps 2)) (nst:def-test 1d-taxicab-annulus (generates ((-2) (2) (-3) (3))) (grid-generators:make-taxicab-generator 1 :minimum-steps 2 :maximum-steps 3)) (nst:def-test 1d-taxicab-monotonic (monotonic :key #'grid-generators:taxicab-distance) (grid-generators:make-taxicab-generator 1 :minimum-steps 1 :maximum-steps 4)) (nst:def-test 1d-taxicab-no-maximum (:equal 128) (loop :with g := (grid-generators:make-taxicab-generator 1) :for v := (funcall g) :repeat 257 :maximizing (grid-generators:taxicab-distance v)))) (nst:def-test-group 2d-taxicab-generator-tests () (nst:def-test 2d-taxicab (generates ((0 0) (-1 0) (1 0) (0 -1) (0 1) (-2 0) (2 0) (0 -2) (0 2) (-1 -1) (-1 1) (1 -1) (1 1))) (grid-generators:make-taxicab-generator 2 :minimum-steps 0 :maximum-steps 2)) (nst:def-test 2d-taxicab-annulus (generates ((-3 0) (3 0) (-2 -1) (-2 1) (2 -1) (2 1) (-1 -2) (-1 2) (1 -2) (1 2) (0 -3) (0 3))) (grid-generators:make-taxicab-generator 2 :minimum-steps 3 :maximum-steps 3)) (nst:def-test 2d-taxicab-scale-single-number (generates ((-6 0) (6 0) (-4 -2) (-4 2) (4 -2) (4 2) (-2 -4) (-2 4) (2 -4) (2 4) (0 -6) (0 6))) (grid-generators:make-taxicab-generator 2 :minimum-steps 3 :maximum-steps 3 :scale 2)) (nst:def-test 2d-taxicab-scale-and-offset (generates ((-5 2) (7 2) (-3 0) (-3 4) (5 0) (5 4) (-1 -2) (-1 6) (3 -2) (3 6) (1 -4) (1 8))) (grid-generators:make-taxicab-generator 2 :minimum-steps 3 :maximum-steps 3 :scale 2 :offset '(1 2))) (nst:def-test 2d-taxicab-scale-list (generates ((-6 0) (6 0) (-4 -1/2) (-4 1/2) (4 -1/2) (4 1/2) (-2 -1) (-2 1) (2 -1) (2 1) (0 -3/2) (0 3/2))) (grid-generators:make-taxicab-generator 2 :minimum-steps 3 :maximum-steps 3 :scale '(2 1/2))) (nst:def-test 2d-taxicab-monotonic (monotonic :key #'grid-generators:taxicab-distance) (grid-generators:make-taxicab-generator 2 :minimum-steps 0 :maximum-steps 3))) (nst:def-test-group 4d-taxicab-generator-tests () (nst:def-test 4d-taxicab (generates ((0 0 0 0) ; steps 0 steps 1 (0 1 0 0) (0 -1 0 0) (0 0 1 0) (0 0 -1 0) (0 0 0 1) (0 0 0 -1) steps 2 (1 -1 0 0) (-1 -1 0 0) (1 0 1 0) (-1 0 1 0) (1 0 -1 0) (-1 0 -1 0) (1 0 0 1) (-1 0 0 1) (1 0 0 -1) (-1 0 0 -1) (0 1 1 0) (0 -1 1 0) (0 1 -1 0) (0 -1 -1 0) (0 1 0 1) (0 -1 0 1) (0 1 0 -1) (0 -1 0 -1) (0 0 1 1) (0 0 -1 1) (0 0 1 -1) (0 0 -1 -1) (2 0 0 0) (-2 0 0 0) (0 2 0 0) (0 -2 0 0) (0 0 2 0) (0 0 -2 0) (0 0 0 2) (0 0 0 -2))) (grid-generators:make-taxicab-generator 4 :minimum-steps 0 :maximum-steps 2))) (nst:def-test-group taxicab-bad-parameters-tests () (nst:def-test dimensions-not-integer (:err) (grid-generators:make-taxicab-generator 1.5)) (nst:def-test dimensions-not-positive (:err) (grid-generators:make-taxicab-generator 0)) (nst:def-test minimum-not-integer (:err) (grid-generators:make-taxicab-generator 1 :minimum-steps 1.5)) (nst:def-test minimum-not-non-negative (:err) (grid-generators:make-taxicab-generator 1 :minimum-steps -1)) (nst:def-test maximum-not-integer (:err) (grid-generators:make-taxicab-generator 1 :maximum-steps 1.5)) (nst:def-test maximum-not-non-negative (:err) (grid-generators:make-taxicab-generator 1 :maximum-steps -1)) (nst:def-test maximum-less-than-minimum (:err) (grid-generators:make-taxicab-generator 1 :minimum-steps 2 :maximum-steps 1)) (nst:def-test scale-not-a-number (:err) (grid-generators:make-taxicab-generator 1 :minimum-steps 2 :scale :a)) (nst:def-test scale-not-a-list-of-number (:err) (grid-generators:make-taxicab-generator 1 :minimum-steps 2 :scale '(:a))) (nst:def-test scale-not-a-correct-length (:err) (grid-generators:make-taxicab-generator 1 :minimum-steps 2 :scale '(1 2))) (nst:def-test offset-not-a-list (:err) (grid-generators:make-taxicab-generator 1 :minimum-steps 2 :offset 1)) (nst:def-test offset-not-a-list-of-numbers (:err) (grid-generators:make-taxicab-generator 1 :minimum-steps 2 :offset '(:a))) (nst:def-test offset-not-right-length (:err) (grid-generators:make-taxicab-generator 1 :minimum-steps 2 :offset '(1 2 4))))
null
https://raw.githubusercontent.com/nklein/grid-generators/5f7b790c339123f84710d907ddafdb52c160d44e/test/taxicab.lisp
lisp
taxicab.lisp steps 0
(in-package #:grid-generators-tests) (nst:def-test-group 1d-taxicab-generator-tests () (nst:def-test 1d-taxicab (generates ((0) (-1) (1) (-2) (2))) (grid-generators:make-taxicab-generator 1 :minimum-steps 0 :maximum-steps 2)) (nst:def-test 1d-taxicab-default-min (generates ((0) (-1) (1) (-2) (2))) (grid-generators:make-taxicab-generator 1 :maximum-steps 2)) (nst:def-test 1d-taxicab-annulus (generates ((-2) (2) (-3) (3))) (grid-generators:make-taxicab-generator 1 :minimum-steps 2 :maximum-steps 3)) (nst:def-test 1d-taxicab-monotonic (monotonic :key #'grid-generators:taxicab-distance) (grid-generators:make-taxicab-generator 1 :minimum-steps 1 :maximum-steps 4)) (nst:def-test 1d-taxicab-no-maximum (:equal 128) (loop :with g := (grid-generators:make-taxicab-generator 1) :for v := (funcall g) :repeat 257 :maximizing (grid-generators:taxicab-distance v)))) (nst:def-test-group 2d-taxicab-generator-tests () (nst:def-test 2d-taxicab (generates ((0 0) (-1 0) (1 0) (0 -1) (0 1) (-2 0) (2 0) (0 -2) (0 2) (-1 -1) (-1 1) (1 -1) (1 1))) (grid-generators:make-taxicab-generator 2 :minimum-steps 0 :maximum-steps 2)) (nst:def-test 2d-taxicab-annulus (generates ((-3 0) (3 0) (-2 -1) (-2 1) (2 -1) (2 1) (-1 -2) (-1 2) (1 -2) (1 2) (0 -3) (0 3))) (grid-generators:make-taxicab-generator 2 :minimum-steps 3 :maximum-steps 3)) (nst:def-test 2d-taxicab-scale-single-number (generates ((-6 0) (6 0) (-4 -2) (-4 2) (4 -2) (4 2) (-2 -4) (-2 4) (2 -4) (2 4) (0 -6) (0 6))) (grid-generators:make-taxicab-generator 2 :minimum-steps 3 :maximum-steps 3 :scale 2)) (nst:def-test 2d-taxicab-scale-and-offset (generates ((-5 2) (7 2) (-3 0) (-3 4) (5 0) (5 4) (-1 -2) (-1 6) (3 -2) (3 6) (1 -4) (1 8))) (grid-generators:make-taxicab-generator 2 :minimum-steps 3 :maximum-steps 3 :scale 2 :offset '(1 2))) (nst:def-test 2d-taxicab-scale-list (generates ((-6 0) (6 0) (-4 -1/2) (-4 1/2) (4 -1/2) (4 1/2) (-2 -1) (-2 1) (2 -1) (2 1) (0 -3/2) (0 3/2))) (grid-generators:make-taxicab-generator 2 :minimum-steps 3 :maximum-steps 3 :scale '(2 1/2))) (nst:def-test 2d-taxicab-monotonic (monotonic :key #'grid-generators:taxicab-distance) (grid-generators:make-taxicab-generator 2 :minimum-steps 0 :maximum-steps 3))) (nst:def-test-group 4d-taxicab-generator-tests () steps 1 (0 1 0 0) (0 -1 0 0) (0 0 1 0) (0 0 -1 0) (0 0 0 1) (0 0 0 -1) steps 2 (1 -1 0 0) (-1 -1 0 0) (1 0 1 0) (-1 0 1 0) (1 0 -1 0) (-1 0 -1 0) (1 0 0 1) (-1 0 0 1) (1 0 0 -1) (-1 0 0 -1) (0 1 1 0) (0 -1 1 0) (0 1 -1 0) (0 -1 -1 0) (0 1 0 1) (0 -1 0 1) (0 1 0 -1) (0 -1 0 -1) (0 0 1 1) (0 0 -1 1) (0 0 1 -1) (0 0 -1 -1) (2 0 0 0) (-2 0 0 0) (0 2 0 0) (0 -2 0 0) (0 0 2 0) (0 0 -2 0) (0 0 0 2) (0 0 0 -2))) (grid-generators:make-taxicab-generator 4 :minimum-steps 0 :maximum-steps 2))) (nst:def-test-group taxicab-bad-parameters-tests () (nst:def-test dimensions-not-integer (:err) (grid-generators:make-taxicab-generator 1.5)) (nst:def-test dimensions-not-positive (:err) (grid-generators:make-taxicab-generator 0)) (nst:def-test minimum-not-integer (:err) (grid-generators:make-taxicab-generator 1 :minimum-steps 1.5)) (nst:def-test minimum-not-non-negative (:err) (grid-generators:make-taxicab-generator 1 :minimum-steps -1)) (nst:def-test maximum-not-integer (:err) (grid-generators:make-taxicab-generator 1 :maximum-steps 1.5)) (nst:def-test maximum-not-non-negative (:err) (grid-generators:make-taxicab-generator 1 :maximum-steps -1)) (nst:def-test maximum-less-than-minimum (:err) (grid-generators:make-taxicab-generator 1 :minimum-steps 2 :maximum-steps 1)) (nst:def-test scale-not-a-number (:err) (grid-generators:make-taxicab-generator 1 :minimum-steps 2 :scale :a)) (nst:def-test scale-not-a-list-of-number (:err) (grid-generators:make-taxicab-generator 1 :minimum-steps 2 :scale '(:a))) (nst:def-test scale-not-a-correct-length (:err) (grid-generators:make-taxicab-generator 1 :minimum-steps 2 :scale '(1 2))) (nst:def-test offset-not-a-list (:err) (grid-generators:make-taxicab-generator 1 :minimum-steps 2 :offset 1)) (nst:def-test offset-not-a-list-of-numbers (:err) (grid-generators:make-taxicab-generator 1 :minimum-steps 2 :offset '(:a))) (nst:def-test offset-not-right-length (:err) (grid-generators:make-taxicab-generator 1 :minimum-steps 2 :offset '(1 2 4))))
0243eab83c9b570d2b30ce285692951fa6b50a6177b18302c2c4754588fa3127
penpot/penpot
render.cljs
This Source Code Form is subject to the terms of the Mozilla Public License , v. 2.0 . If a copy of the MPL was not distributed with this file , You can obtain one at /. ;; ;; Copyright (c) KALEIDOS INC (ns app.libs.render (:require [app.common.uuid :as uuid] [app.main.render :as r] [beicon.core :as rx] [promesa.core :as p])) (defn render-page-export [file ^string page-id] Better to expose the api as a promise to be consumed from JS (let [page-id (uuid/uuid page-id) file-data (.-file file) data (get-in file-data [:data :pages-index page-id])] (p/create (fn [resolve reject] (->> (r/render-page data) (rx/take 1) (rx/subs resolve reject))) ))) (defn exports [] #js {:renderPage render-page-export})
null
https://raw.githubusercontent.com/penpot/penpot/cc18f84d620e37d8efafc5bed1bcdbe70ec23c1e/frontend/src/app/libs/render.cljs
clojure
Copyright (c) KALEIDOS INC
This Source Code Form is subject to the terms of the Mozilla Public License , v. 2.0 . If a copy of the MPL was not distributed with this file , You can obtain one at /. (ns app.libs.render (:require [app.common.uuid :as uuid] [app.main.render :as r] [beicon.core :as rx] [promesa.core :as p])) (defn render-page-export [file ^string page-id] Better to expose the api as a promise to be consumed from JS (let [page-id (uuid/uuid page-id) file-data (.-file file) data (get-in file-data [:data :pages-index page-id])] (p/create (fn [resolve reject] (->> (r/render-page data) (rx/take 1) (rx/subs resolve reject))) ))) (defn exports [] #js {:renderPage render-page-export})
86df1b07576ff3c9ad60315a7249e8459339157076ba2189ac9483001c453c9c
otherjoel/beeswax
for-pollen.rkt
#lang racket/base (require (prefix-in pollen: pollen/render) pollen/setup racket/match racket/path sugar/file "render.rkt") ; This is a renderer specifically for use by Pollen (provide external-renderer) (define (external-renderer source-path orig-template-path output-path) (case (path-get-extension source-path) [(#".pm" #".pmd") (match-define-values ((cons render-result _) _ ms _) (time-apply render (list source-path output-path))) (log-info "beeswax rendered /~a (~ams)" (find-relative-path (current-project-root) output-path) ms) render-result] [else (pollen:render source-path orig-template-path)]))
null
https://raw.githubusercontent.com/otherjoel/beeswax/993b5364b474ff0d8a1f8c26dac192cb4408f385/for-pollen.rkt
racket
This is a renderer specifically for use by Pollen
#lang racket/base (require (prefix-in pollen: pollen/render) pollen/setup racket/match racket/path sugar/file "render.rkt") (provide external-renderer) (define (external-renderer source-path orig-template-path output-path) (case (path-get-extension source-path) [(#".pm" #".pmd") (match-define-values ((cons render-result _) _ ms _) (time-apply render (list source-path output-path))) (log-info "beeswax rendered /~a (~ams)" (find-relative-path (current-project-root) output-path) ms) render-result] [else (pollen:render source-path orig-template-path)]))
6b954123c95df2e9ac9b7ac05607b97ed2be2381b16dc520c2875e14204d6d6d
wireapp/wire-server
GroupInfoBundle.hs
-- This file is part of the Wire Server implementation. -- Copyright ( C ) 2022 Wire Swiss GmbH < > -- -- This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation , either version 3 of the License , or ( at your option ) any -- later version. -- -- This program is distributed in the hope that it will be useful, but WITHOUT -- ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -- FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more -- details. -- You should have received a copy of the GNU Affero General Public License along -- with this program. If not, see </>. module Wire.API.MLS.GroupInfoBundle where import Control.Lens (view, (.~)) import Data.ProtoLens (Message (defMessage)) import Imports import qualified Proto.Mls import qualified Proto.Mls_Fields as Proto.Mls import Test.QuickCheck import Wire.API.ConverProtoLens import Wire.API.MLS.PublicGroupState import Wire.API.MLS.Serialisation import Wire.Arbitrary data GroupInfoType = GroupInfoTypePublicGroupState | UnencryptedGroupInfo | JweEncryptedGroupInfo deriving stock (Eq, Show, Generic, Enum, Bounded) deriving (Arbitrary) via (GenericUniform GroupInfoType) instance ConvertProtoLens Proto.Mls.GroupInfoType GroupInfoType where fromProtolens Proto.Mls.PUBLIC_GROUP_STATE = pure GroupInfoTypePublicGroupState fromProtolens Proto.Mls.GROUP_INFO = pure UnencryptedGroupInfo fromProtolens Proto.Mls.GROUP_INFO_JWE = pure JweEncryptedGroupInfo toProtolens GroupInfoTypePublicGroupState = Proto.Mls.PUBLIC_GROUP_STATE toProtolens UnencryptedGroupInfo = Proto.Mls.GROUP_INFO toProtolens JweEncryptedGroupInfo = Proto.Mls.GROUP_INFO_JWE data RatchetTreeType = TreeFull | TreeDelta | TreeByRef deriving stock (Eq, Show, Generic, Bounded, Enum) deriving (Arbitrary) via (GenericUniform RatchetTreeType) instance ConvertProtoLens Proto.Mls.RatchetTreeType RatchetTreeType where fromProtolens Proto.Mls.FULL = pure TreeFull fromProtolens Proto.Mls.DELTA = pure TreeDelta fromProtolens Proto.Mls.REFERENCE = pure TreeByRef toProtolens TreeFull = Proto.Mls.FULL toProtolens TreeDelta = Proto.Mls.DELTA toProtolens TreeByRef = Proto.Mls.REFERENCE data GroupInfoBundle = GroupInfoBundle { gipGroupInfoType :: GroupInfoType, gipRatchetTreeType :: RatchetTreeType, gipGroupState :: RawMLS PublicGroupState } deriving stock (Eq, Show, Generic) instance ConvertProtoLens Proto.Mls.GroupInfoBundle GroupInfoBundle where fromProtolens protoBundle = protoLabel "GroupInfoBundle" $ GroupInfoBundle <$> protoLabel "field group_info_type" (fromProtolens (view Proto.Mls.groupInfoType protoBundle)) <*> protoLabel "field ratchet_tree_type" (fromProtolens (view Proto.Mls.ratchetTreeType protoBundle)) <*> protoLabel "field group_info" (decodeMLS' (view Proto.Mls.groupInfo protoBundle)) toProtolens bundle = let encryptionType = toProtolens (gipGroupInfoType bundle) treeType = toProtolens (gipRatchetTreeType bundle) in ( defMessage & Proto.Mls.groupInfoType .~ encryptionType & Proto.Mls.ratchetTreeType .~ treeType & Proto.Mls.groupInfo .~ rmRaw (gipGroupState bundle) ) instance Arbitrary GroupInfoBundle where arbitrary = GroupInfoBundle <$> arbitrary <*> arbitrary <*> (mkRawMLS <$> arbitrary) instance ParseMLS GroupInfoBundle where parseMLS = GroupInfoBundle <$> parseMLSEnum @Word8 "GroupInfoTypeEnum" <*> parseMLSEnum @Word8 "RatchetTreeEnum" <*> parseMLS instance SerialiseMLS GroupInfoBundle where serialiseMLS (GroupInfoBundle e t pgs) = do serialiseMLSEnum @Word8 e serialiseMLSEnum @Word8 t serialiseMLS pgs
null
https://raw.githubusercontent.com/wireapp/wire-server/8d0c53abd7eb1e0237b39dfdd216acd88d537d98/libs/wire-api/src/Wire/API/MLS/GroupInfoBundle.hs
haskell
This file is part of the Wire Server implementation. This program is free software: you can redistribute it and/or modify it under later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. with this program. If not, see </>.
Copyright ( C ) 2022 Wire Swiss GmbH < > the terms of the GNU Affero General Public License as published by the Free Software Foundation , either version 3 of the License , or ( at your option ) any You should have received a copy of the GNU Affero General Public License along module Wire.API.MLS.GroupInfoBundle where import Control.Lens (view, (.~)) import Data.ProtoLens (Message (defMessage)) import Imports import qualified Proto.Mls import qualified Proto.Mls_Fields as Proto.Mls import Test.QuickCheck import Wire.API.ConverProtoLens import Wire.API.MLS.PublicGroupState import Wire.API.MLS.Serialisation import Wire.Arbitrary data GroupInfoType = GroupInfoTypePublicGroupState | UnencryptedGroupInfo | JweEncryptedGroupInfo deriving stock (Eq, Show, Generic, Enum, Bounded) deriving (Arbitrary) via (GenericUniform GroupInfoType) instance ConvertProtoLens Proto.Mls.GroupInfoType GroupInfoType where fromProtolens Proto.Mls.PUBLIC_GROUP_STATE = pure GroupInfoTypePublicGroupState fromProtolens Proto.Mls.GROUP_INFO = pure UnencryptedGroupInfo fromProtolens Proto.Mls.GROUP_INFO_JWE = pure JweEncryptedGroupInfo toProtolens GroupInfoTypePublicGroupState = Proto.Mls.PUBLIC_GROUP_STATE toProtolens UnencryptedGroupInfo = Proto.Mls.GROUP_INFO toProtolens JweEncryptedGroupInfo = Proto.Mls.GROUP_INFO_JWE data RatchetTreeType = TreeFull | TreeDelta | TreeByRef deriving stock (Eq, Show, Generic, Bounded, Enum) deriving (Arbitrary) via (GenericUniform RatchetTreeType) instance ConvertProtoLens Proto.Mls.RatchetTreeType RatchetTreeType where fromProtolens Proto.Mls.FULL = pure TreeFull fromProtolens Proto.Mls.DELTA = pure TreeDelta fromProtolens Proto.Mls.REFERENCE = pure TreeByRef toProtolens TreeFull = Proto.Mls.FULL toProtolens TreeDelta = Proto.Mls.DELTA toProtolens TreeByRef = Proto.Mls.REFERENCE data GroupInfoBundle = GroupInfoBundle { gipGroupInfoType :: GroupInfoType, gipRatchetTreeType :: RatchetTreeType, gipGroupState :: RawMLS PublicGroupState } deriving stock (Eq, Show, Generic) instance ConvertProtoLens Proto.Mls.GroupInfoBundle GroupInfoBundle where fromProtolens protoBundle = protoLabel "GroupInfoBundle" $ GroupInfoBundle <$> protoLabel "field group_info_type" (fromProtolens (view Proto.Mls.groupInfoType protoBundle)) <*> protoLabel "field ratchet_tree_type" (fromProtolens (view Proto.Mls.ratchetTreeType protoBundle)) <*> protoLabel "field group_info" (decodeMLS' (view Proto.Mls.groupInfo protoBundle)) toProtolens bundle = let encryptionType = toProtolens (gipGroupInfoType bundle) treeType = toProtolens (gipRatchetTreeType bundle) in ( defMessage & Proto.Mls.groupInfoType .~ encryptionType & Proto.Mls.ratchetTreeType .~ treeType & Proto.Mls.groupInfo .~ rmRaw (gipGroupState bundle) ) instance Arbitrary GroupInfoBundle where arbitrary = GroupInfoBundle <$> arbitrary <*> arbitrary <*> (mkRawMLS <$> arbitrary) instance ParseMLS GroupInfoBundle where parseMLS = GroupInfoBundle <$> parseMLSEnum @Word8 "GroupInfoTypeEnum" <*> parseMLSEnum @Word8 "RatchetTreeEnum" <*> parseMLS instance SerialiseMLS GroupInfoBundle where serialiseMLS (GroupInfoBundle e t pgs) = do serialiseMLSEnum @Word8 e serialiseMLSEnum @Word8 t serialiseMLS pgs
9782f3c3f7f78a57bfd8e093d659e213758f06f34ef1dcd71960a644a20c9daa
andrewthad/sockets
Error.hs
module Socket.Error ( die ) where die :: String -> IO a die = fail
null
https://raw.githubusercontent.com/andrewthad/sockets/90d314bd2ec71b248a90da6ad964c679f75cfcca/src-err/Socket/Error.hs
haskell
module Socket.Error ( die ) where die :: String -> IO a die = fail
6b56a7f3c1eb9d1c94e4a7846e7dc5526ae79e53105c08f1d478361da0efe204
sbcl/sbcl
fndb.lisp
;;;; This file defines all the standard functions to be known ;;;; functions. Each function has type and side-effect information, ;;;; and may also have IR1 optimizers. 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-C") ;;;; information for known functions: (defknown coerce (t type-specifier) t ;; Note: ;; This is not FLUSHABLE because it's defined to signal errors. (movable) : DERIVE - TYPE RESULT - TYPE - SPEC - NTH - ARG 1 ? Nope ... ( COERCE 1 ' COMPLEX ) returns REAL / INTEGER , not COMPLEX . ) ;; These each check their input sequence for type-correctness, ;; but not the output type specifier, because MAKE-SEQUENCE will do that. (defknown list-to-vector* (list type-specifier) vector (no-verify-arg-count)) (defknown vector-to-vector* (vector type-specifier) vector (no-verify-arg-count)) FIXME : Is this really FOLDABLE ? A counterexample seems to be : ( LET ( ( S : S ) ) ( VALUES ( TYPE - OF S ) ( UNINTERN S ' KEYWORD ) ( TYPE - OF S ) S ) ) ;; Anyway, the TYPE-SPECIFIER type is more inclusive than the actual ;; possible return values. Most of the time it will be (OR LIST SYMBOL). ;; CLASS can be returned only when you've got an object whose class-name ;; does not properly name its class. (defknown type-of (t) (or list symbol class) (foldable flushable)) These can be affected by type definitions , so they 're not FOLDABLE . (defknown (upgraded-complex-part-type upgraded-array-element-type) (type-specifier &optional lexenv-designator) (or list symbol) (unsafely-flushable)) ;;;; from the "Predicates" chapter: FIXME : Is it right to have TYPEP ( and TYPE - OF , elsewhere ; and perhaps SPECIAL - OPERATOR - P and others ) be FOLDABLE in the ;;; cross-compilation host? After all, some type relationships (e.g. ) might be different between host and target . Perhaps this property should be protected by # -SB - XC - HOST ? Perhaps we need 3 - stage bootstrapping after all ? ( Ugh ! It 's * so * slow already ! ) (defknown typep (t type-specifier &optional lexenv-designator) boolean Unlike SUBTYPEP or UPGRADED - ARRAY - ELEMENT - TYPE and friends , this seems to be FOLDABLE . Like SUBTYPEP , it 's affected by type definitions , but unlike SUBTYPEP , there should be no way to make a TYPEP expression with constant arguments which does n't return ;; an error before the type declaration (because of undefined ;; type). E.g. you can do ( SUBTYPEP ' INTEGER ' FOO ) = > NIL , NIL ( DEFTYPE FOO ( ) T ) ( SUBTYPEP ' INTEGER ' FOO ) = > T , T ;; but the analogous ( TYPEP 12 ' FOO ) ( DEFTYPE FOO ( ) T ) ( TYPEP 12 ' FOO ) does n't work because the first call is an error . ;; ;; (UPGRADED-ARRAY-ELEMENT-TYPE and UPGRADED-COMPLEX-PART-TYPE have behavior like SUBTYPEP in this respect , not like TYPEP . ) (foldable)) (defknown subtypep (type-specifier type-specifier &optional lexenv-designator) (values boolean boolean) This is not FOLDABLE because its value is affected by type ;; definitions. ;; ;; FIXME: Is it OK to fold this when the types have already been defined ? Does the code inherited from CMU CL already do this ? (unsafely-flushable)) (defknown (null symbolp atom consp listp numberp integerp rationalp floatp complexp characterp stringp bit-vector-p vectorp simple-vector-p simple-string-p simple-bit-vector-p arrayp packagep functionp compiled-function-p not) (t) boolean (movable foldable flushable)) (defknown (eq eql %eql/integer) (t t) boolean (movable foldable flushable commutative)) (defknown (equal equalp) (t t) boolean (foldable flushable recursive)) #+(or x86 x86-64 arm arm64) (defknown fixnum-mod-p (t fixnum) boolean (movable flushable always-translatable)) ;;;; classes FIXME : disagrees w/ LEGAL - CLASS - NAME - P (defknown find-classoid (name-for-class &optional t) (or classoid null) ()) (defknown classoid-of (t) classoid (flushable)) (defknown wrapper-of (t) wrapper (flushable)) (defknown wrapper-depthoid (wrapper) layout-depthoid (flushable)) #+64-bit (defknown layout-depthoid (sb-vm:layout) layout-depthoid (flushable always-translatable)) #+(or x86 x86-64) (defknown (layout-depthoid-ge) (sb-vm:layout integer) boolean (flushable)) (defknown %structure-is-a (instance t) boolean (foldable flushable)) (defknown structure-typep (t t) boolean (foldable flushable)) (defknown classoid-cell-typep (t t) boolean (foldable flushable no-verify-arg-count)) (defknown copy-structure (structure-object) structure-object (flushable) :derive-type #'result-type-first-arg) from the " Control Structure " chapter : ;;; This is not FLUSHABLE, since it's required to signal an error if ;;; unbound. (defknown symbol-value (symbol) t () :derive-type #'symbol-value-derive-type) (defknown about-to-modify-symbol-value (symbol t &optional t t) null ()) ;;; From CLHS, "If the symbol is globally defined as a macro or a ;;; special operator, an object of implementation-dependent nature and ;;; identity is returned. If the symbol is not globally defined as ;;; either a macro or a special operator, and if the symbol is fbound, ;;; a function object is returned". Our objects of ;;; implementation-dependent nature happen to be functions. (defknown (symbol-function) (symbol) function (unsafely-flushable)) (defknown boundp (symbol) boolean (flushable)) (defknown fboundp ((or symbol cons)) (or null function) (unsafely-flushable)) (defknown special-operator-p (symbol) t ;; The set of special operators never changes. (movable foldable flushable)) (defknown set (symbol t) t () :derive-type #'result-type-last-arg) (defknown fdefinition ((or symbol cons)) function ()) (defknown ((setf fdefinition)) (function (or symbol cons)) function () :derive-type #'result-type-first-arg) (defknown makunbound (symbol) symbol () :derive-type #'result-type-first-arg) (defknown fmakunbound ((or symbol cons)) (or symbol cons) () :derive-type #'result-type-first-arg) # # # Last arg must be List ... (defknown funcall (function-designator &rest t) *) (defknown (mapcar maplist) (function-designator list &rest list) list (call)) ;;; According to CLHS the result must be a LIST, but we do not check ;;; it. (defknown (mapcan mapcon) (function-designator list &rest list) t (call)) (defknown (mapc mapl) (function-designator list &rest list) list (foldable call)) ;;; We let VALUES-LIST be foldable, since constant-folding will turn ;;; it into VALUES. VALUES is not foldable, since MV constants are ;;; represented by a call to VALUES. (defknown values (&rest t) * (movable flushable)) (defknown values-list (list) * (movable foldable unsafely-flushable)) from the " Macros " chapter : (defknown macro-function (symbol &optional lexenv-designator) (or function null) (flushable)) (defknown (macroexpand macroexpand-1 %macroexpand %macroexpand-1) (t &optional lexenv-designator) (values form &optional boolean)) (defknown compiler-macro-function (t &optional lexenv-designator) (or function null) (flushable)) from the " Declarations " chapter : (defknown proclaim (list) (values) (recursive)) ;;;; from the "Symbols" chapter: (defknown get (symbol t &optional t) t (flushable)) (defknown sb-impl::get3 (symbol t t) t (flushable no-verify-arg-count)) (defknown remprop (symbol t) t) (defknown symbol-plist (symbol) list (flushable)) (defknown getf (list t &optional t) t (foldable flushable)) (defknown get-properties (list list) (values t t list) (foldable flushable)) (defknown symbol-name (symbol) simple-string (movable foldable flushable)) (defknown make-symbol (string) symbol (flushable)) ;; %make-symbol is the internal API, but the primitive object allocator ;; is %%make-symbol, because when immobile space feature is present, ;; we dispatch to either the C allocator or the Lisp allocator. (defknown %make-symbol (fixnum simple-string) symbol (flushable)) (defknown sb-vm::%%make-symbol (simple-string) symbol (flushable)) (defknown copy-symbol (symbol &optional t) symbol (flushable)) (defknown gensym (&optional (or string unsigned-byte)) symbol ()) (defknown symbol-package (symbol) (or package null) (flushable)) (defknown %symbol-package (t) (or package null) (flushable)) ;; doesn't check the type. (defknown keywordp (t) boolean (flushable)) ; semi-foldable, see src/compiler/typetran ;;;; from the "Packages" chapter: (defknown gentemp (&optional string package-designator) symbol) (defknown make-package (string-designator &key (:use list) (:nicknames list) # # # extensions ... (:internal-symbols index) (:external-symbols index)) package) (defknown find-package (package-designator) (or package null) (flushable)) (defknown find-undeleted-package-or-lose (package-designator) package) ; not flushable (defknown package-name (package-designator) (or simple-string null) (unsafely-flushable)) (defknown package-nicknames (package-designator) list (unsafely-flushable)) (defknown rename-package (package-designator package-designator &optional list) package) (defknown package-use-list (package-designator) list (unsafely-flushable)) (defknown package-used-by-list (package-designator) list (unsafely-flushable)) (defknown package-shadowing-symbols (package-designator) list (unsafely-flushable)) (defknown list-all-packages () list (flushable)) (defknown intern (string &optional package-designator) (values symbol (member :internal :external :inherited nil)) ()) (defknown find-symbol (string &optional package-designator) (values symbol (member :internal :external :inherited nil)) (flushable)) (defknown (export import) (symbols-designator &optional package-designator) (eql t)) (defknown unintern (symbol &optional package-designator) boolean) (defknown unexport (symbols-designator &optional package-designator) (eql t)) (defknown shadowing-import (symbols-designator &optional package-designator) (eql t)) (defknown shadow ((or symbol character string list) &optional package-designator) (eql t)) (defknown (use-package unuse-package) ((or list package-designator) &optional package-designator) (eql t)) (defknown find-all-symbols (string-designator) list (flushable)) ;; private (defknown package-iter-step (fixnum index simple-vector list) (values fixnum index simple-vector list symbol symbol)) ;;;; from the "Numbers" chapter: (defknown zerop (number) boolean (movable foldable flushable)) (defknown (plusp minusp) (real) boolean (movable foldable flushable)) (defknown (oddp evenp) (integer) boolean (movable foldable flushable)) (defknown (=) (number &rest number) boolean (movable foldable flushable commutative)) (defknown (/=) (number &rest number) boolean (movable foldable flushable)) (defknown (< > <= >=) (real &rest real) boolean (movable foldable flushable)) (defknown (max min) (real &rest real) real (movable foldable flushable)) (defknown (+ *) (&rest number) number (movable foldable flushable commutative)) (defknown - (number &rest number) number (movable foldable flushable)) (defknown / (number &rest number) number (movable foldable unsafely-flushable)) (defknown (1+ 1-) (number) number (movable foldable flushable)) (defknown (two-arg-* two-arg-+ two-arg-- two-arg-/) (number number) number (no-verify-arg-count)) (defknown sb-kernel::integer-/-integer (integer integer) rational (no-verify-arg-count unsafely-flushable)) (defknown (two-arg-< two-arg-= two-arg-> two-arg-<= two-arg->=) (number number) boolean (no-verify-arg-count)) (defknown (range< range<= range<<= range<=<) (fixnum real fixnum) boolean (foldable flushable movable no-verify-arg-count)) (defknown (two-arg-gcd two-arg-lcm two-arg-and two-arg-ior two-arg-xor two-arg-eqv) (integer integer) integer (no-verify-arg-count)) (defknown conjugate (number) number (movable foldable flushable)) (defknown gcd (&rest integer) unsigned-byte (movable foldable flushable)) (defknown sb-kernel::fixnum-gcd (fixnum fixnum) (integer 0 #.(1+ most-positive-fixnum)) (movable foldable flushable no-verify-arg-count)) (defknown lcm (&rest integer) unsigned-byte (movable foldable flushable)) (defknown exp (number) irrational (movable foldable flushable recursive)) (defknown expt (number number) number (movable foldable flushable recursive)) (defknown log (number &optional real) irrational (movable foldable flushable recursive)) (defknown sqrt (number) irrational (movable foldable flushable)) (defknown isqrt (unsigned-byte) unsigned-byte (movable foldable flushable recursive)) (defknown (abs phase signum) (number) number (movable foldable flushable)) (defknown cis (real) (complex float) (movable foldable flushable)) (defknown (sin cos) (number) (or (float $-1.0 $1.0) (complex float)) (movable foldable flushable recursive)) (defknown atan (number &optional real) irrational (movable foldable unsafely-flushable recursive)) (defknown (tan sinh cosh tanh asinh) (number) irrational (movable foldable flushable recursive)) (defknown (asin acos acosh atanh) (number) irrational (movable foldable flushable recursive)) (defknown float (real &optional float) float (movable foldable flushable)) (defknown (rational) (real) rational (movable foldable flushable)) (defknown (rationalize) (real) rational (movable foldable flushable recursive)) (defknown numerator (rational) integer (movable foldable flushable)) (defknown denominator (rational) (integer 1) (movable foldable flushable)) (defknown (floor ceiling round) (real &optional real) (values integer real) (movable foldable flushable)) (defknown truncate (real &optional real) (values integer real) (movable foldable flushable recursive)) (defknown unary-truncate (real) (values integer real) (movable foldable flushable no-verify-arg-count)) : Do n't fold these , the compiler may call it on floats that ;;; do not truncate into a bignum, and the functions do not check ;;; their input values and produce corrupted memory. (defknown unary-truncate-single-float-to-bignum (single-float) (values bignum (eql $0f0)) (#+(or) foldable movable flushable fixed-args)) (defknown unary-truncate-double-float-to-bignum (double-float) (values #+64-bit bignum #-64-bit integer (and #+(and 64-bit (not (or riscv ppc64))) ;; they can't survive cold-init (eql $0d0) double-float)) (#+(or) foldable movable flushable fixed-args)) (defknown %unary-truncate-single-float-to-bignum (single-float) bignum (#+(or) foldable movable flushable fixed-args)) (defknown %unary-truncate-double-float-to-bignum (double-float) bignum (#+(or) foldable movable flushable fixed-args)) (defknown (subtract-bignum add-bignums) (bignum bignum) integer (movable flushable no-verify-arg-count)) (defknown (add-bignum-fixnum subtract-bignum-fixnum) (bignum fixnum) integer (movable flushable no-verify-arg-count)) (defknown subtract-fixnum-bignum (fixnum bignum) integer (movable flushable no-verify-arg-count)) (defknown sxhash-bignum-double-float (double-float) hash-code (foldable movable flushable fixed-args)) (defknown sxhash-bignum-single-float (single-float) hash-code (foldable movable flushable fixed-args)) (defknown %multiply-high (word word) word (movable foldable flushable)) (defknown multiply-fixnums (fixnum fixnum) integer (movable foldable flushable no-verify-arg-count)) (defknown %signed-multiply-high (sb-vm:signed-word sb-vm:signed-word) sb-vm:signed-word (movable foldable flushable)) (defknown (mod rem) (real real) real (movable foldable flushable)) (defknown (ffloor fceiling fround ftruncate) (real &optional real) (values float real) (movable foldable flushable)) (defknown decode-float (float) (values float float-exponent float) (movable foldable unsafely-flushable)) (defknown scale-float (float integer) float (movable foldable unsafely-flushable)) (defknown float-radix (float) float-radix (movable foldable unsafely-flushable)) ;;; This says "unsafely flushable" as if to imply that there is a possibility ;;; of signaling a condition in safe code, but in practice we can never trap on a NaN because the implementation uses foo - FLOAT - BITS instead of ;;; performing a floating-point comparison. I think that is done on purpose, ;;; so at best the "unsafely-" is disingenuous, and at worst our code is wrong. e.g. the behavior if the first arg is a NaN is well - defined as we have it , but what about the second arg ? We need some test cases around this . (defknown float-sign (float &optional float) float (movable foldable unsafely-flushable) :derive-type (lambda (call &aux (args (combination-args call)) (type (unless (cdr args) (lvar-type (first args))))) (cond ((and type (csubtypep type (specifier-type 'single-float))) (specifier-type '(member $1f0 $-1f0))) ((and type (csubtypep type (specifier-type 'double-float))) (specifier-type '(member $1d0 $-1d0))) (type (specifier-type '(member $1f0 $-1f0 $1d0 $-1d0))) (t (specifier-type 'float))))) (defknown (float-digits float-precision) (float) float-digits (movable foldable unsafely-flushable)) (defknown integer-decode-float (float) (values integer float-int-exponent (member -1 1)) (movable foldable unsafely-flushable)) (defknown single-float-sign (single-float) single-float (movable foldable flushable)) (defknown single-float-copysign (single-float single-float) single-float (movable foldable flushable)) (defknown complex (real &optional real) number (movable foldable flushable)) (defknown (realpart imagpart) (number) real (movable foldable flushable)) (defknown (logior logxor logand logeqv) (&rest integer) integer (movable foldable flushable commutative)) (defknown (lognand lognor logandc1 logandc2 logorc1 logorc2) (integer integer) integer (movable foldable flushable)) (defknown boole (boole-code integer integer) integer (movable foldable flushable)) (defknown lognot (integer) integer (movable foldable flushable)) (defknown logtest (integer integer) boolean (movable foldable flushable commutative)) (defknown logbitp (unsigned-byte integer) boolean (movable foldable flushable)) (defknown ash (integer integer) integer (movable foldable flushable)) (defknown %ash/right ((or word sb-vm:signed-word) (mod #.sb-vm:n-word-bits)) (or word sb-vm:signed-word) (movable foldable flushable always-translatable)) (defknown (logcount integer-length) (integer) bit-index (movable foldable flushable)) FIXME : According to the ANSI spec , it 's legal to use any nonnegative indices for BYTE arguments , not just BIT - INDEX . It 's ;;; hard to come up with useful ways to do this, but it is possible to ;;; come up with *legal* ways to do this, so it would be nice ;;; to fix this so we comply with the spec. (defknown byte (bit-index bit-index) byte-specifier (movable foldable flushable)) (defknown (byte-size byte-position) (byte-specifier) bit-index (movable foldable flushable)) (defknown ldb (byte-specifier integer) unsigned-byte (movable foldable flushable)) (defknown ldb-test (byte-specifier integer) boolean (movable foldable flushable)) (defknown mask-field (byte-specifier integer) unsigned-byte (movable foldable flushable)) (defknown dpb (integer byte-specifier integer) integer (movable foldable flushable)) (defknown deposit-field (integer byte-specifier integer) integer (movable foldable flushable)) (defknown random ((or (float ($0.0f0)) (integer 1)) &optional random-state) (or (float $0.0f0) (integer 0)) ()) (defknown make-random-state (&optional (or random-state (member nil t))) random-state (flushable)) SBCL extension (or (member nil t) random-state unsigned-byte (simple-array (unsigned-byte 8) (*)) (simple-array (unsigned-byte 32) (*)))) random-state (flushable)) (defknown random-state-p (t) boolean (movable foldable flushable)) ;;;; from the "Characters" chapter: (defknown (standard-char-p graphic-char-p alpha-char-p upper-case-p lower-case-p both-case-p alphanumericp) (character) boolean (movable foldable flushable)) (defknown digit-char-p (character &optional (integer 2 36)) (or (integer 0 35) null) (movable foldable flushable)) Character predicates : if the 2 - argument predicate which underlies the N - argument predicate unavoidably type - checks its 2 args , ;; then the N-argument form should not type-check anything except in the degenerate case of 1 actual argument . All of the case - sensitive functions have the check of the first arg ;; generated by the compiler, and successive args checked by hand. ;; The case-insensitive functions don't need any checks, since the underlying two - arg case - insensitive function does it , except when it is n't called . (defknown (char=) (character &rest character) boolean (movable foldable flushable commutative)) (defknown (char/= char< char> char<= char>= char-not-equal) (character &rest character) boolean (movable foldable flushable)) (defknown (char-equal char-lessp char-greaterp char-not-greaterp char-not-lessp) (character &rest character) boolean (movable foldable flushable)) (defknown (two-arg-char-equal) (character character) boolean (movable foldable flushable commutative no-verify-arg-count)) (defknown (two-arg-char-not-equal two-arg-char-lessp two-arg-char-not-lessp two-arg-char-greaterp two-arg-char-not-greaterp) (character character) boolean (movable foldable flushable no-verify-arg-count)) (defknown character (t) character (movable foldable unsafely-flushable)) (defknown char-code (character) char-code (movable foldable flushable)) (defknown (char-upcase char-downcase) (character) character (movable foldable flushable)) (defknown digit-char (unsigned-byte &optional (integer 2 36)) (or character null) (movable foldable flushable)) (defknown char-int (character) char-code (movable foldable flushable)) (defknown char-name (character) (or simple-string null) (movable foldable flushable)) (defknown name-char (string-designator) (or character null) (movable foldable flushable)) (defknown code-char (char-code) character ;; By suppressing constant folding on CODE-CHAR when the ;; cross-compiler is running in the cross-compilation host vanilla ;; ANSI Common Lisp, we can use CODE-CHAR expressions to delay until ;; target Lisp run time the generation of CHARACTERs which aren't ;; STANDARD-CHARACTERs. That way, we don't need to rely on the host ;; Common Lisp being able to handle any characters other than those guaranteed by the ANSI spec . (movable #-sb-xc-host foldable flushable)) ;;;; from the "Sequences" chapter: (defknown elt (proper-sequence index) t (foldable unsafely-flushable)) (defknown subseq (proper-sequence index &optional sequence-end) consed-sequence (flushable)) (defknown copy-seq (proper-sequence) consed-sequence (flushable) :derive-type (sequence-result-nth-arg 0 :preserve-dimensions t)) (defknown length (proper-sequence) index (foldable flushable dx-safe)) (defknown reverse (proper-sequence) consed-sequence (flushable) :derive-type (sequence-result-nth-arg 0 :preserve-dimensions t)) (defknown nreverse ((modifying sequence)) sequence (important-result) :derive-type (sequence-result-nth-arg 0 :preserve-dimensions t :preserve-vector-type t)) (defknown make-sequence (type-specifier index &key (:initial-element t)) consed-sequence (movable) :derive-type (creation-result-type-specifier-nth-arg 0)) (defknown concatenate (type-specifier &rest proper-sequence) consed-sequence () :derive-type (creation-result-type-specifier-nth-arg 0)) (defknown %concatenate-to-string (&rest sequence) simple-string (flushable no-verify-arg-count)) (defknown %concatenate-to-base-string (&rest sequence) simple-base-string (flushable no-verify-arg-count)) (defknown %concatenate-to-list (&rest sequence) list (flushable no-verify-arg-count)) (defknown %concatenate-to-simple-vector (&rest sequence) simple-vector (flushable no-verify-arg-count)) (defknown %concatenate-to-vector ((unsigned-byte #.sb-vm:n-widetag-bits) &rest sequence) vector (flushable no-verify-arg-count)) (defknown map (type-specifier (function-designator ((nth-arg 2 :sequence t) (rest-args :sequence t)) (nth-arg 0 :sequence-type t)) proper-sequence &rest proper-sequence) consed-sequence (call)) (defknown %map (type-specifier function-designator &rest sequence) consed-sequence (call no-verify-arg-count)) (defknown %map-for-effect-arity-1 (function-designator sequence) null (call no-verify-arg-count)) (defknown %map-to-list-arity-1 ((function-designator ((nth-arg 1 :sequence t))) sequence) list (flushable call no-verify-arg-count)) (defknown %map-to-simple-vector-arity-1 ((function-designator ((nth-arg 1 :sequence t))) sequence) simple-vector (flushable call no-verify-arg-count)) (defknown map-into ((modifying sequence) (function-designator ((rest-args :sequence t)) (nth-arg 0 :sequence t)) &rest proper-sequence) sequence (call) :derive-type (sequence-result-nth-arg 0 :preserve-dimensions t :preserve-vector-type t)) (defknown #.(loop for info across sb-vm:*specialized-array-element-type-properties* collect (intern (concatenate 'string "VECTOR-MAP-INTO/" (string (sb-vm:saetp-primitive-type-name info))) :sb-impl)) (simple-array index index function list) index (call no-verify-arg-count)) ;;; returns the result from the predicate... (defknown some (function-designator proper-sequence &rest proper-sequence) t (foldable unsafely-flushable call)) (defknown (every notany notevery) (function-designator proper-sequence &rest proper-sequence) boolean (foldable unsafely-flushable call)) (defknown reduce ((function-designator ((nth-arg 1 :sequence t :key :key :value :initial-value) (nth-arg 1 :sequence t :key :key))) proper-sequence &rest t &key (:from-end t) (:start (inhibit-flushing index 0)) (:end (inhibit-flushing sequence-end nil)) (:initial-value t) (:key (function-designator ((nth-arg 1 :sequence t))))) t (foldable flushable call)) (defknown fill ((modifying sequence) t &rest t &key (:start index) (:end sequence-end)) sequence () :derive-type (sequence-result-nth-arg 0 :preserve-dimensions t :preserve-vector-type t) :result-arg 0) Like FILL but with no keyword argument parsing (defknown quickfill ((modifying (simple-array * 1)) t) (simple-array * 1) () :derive-type #'result-type-first-arg :result-arg 0) Special case of FILL that takes either a machine word with which to fill , ;;; or a keyword indicating a certain behavior to compute the word. ;;; In either case the supplied count is lispwords, not elements. ;;; This might be a no-op depending on whether memory is prezeroized. (defknown sb-vm::splat ((modifying (simple-array * 1)) index (or symbol sb-vm:word)) (simple-array * 1) (always-translatable) :derive-type #'result-type-first-arg :result-arg 0) (defknown replace ((modifying sequence) proper-sequence &rest t &key (:start1 index) (:end1 sequence-end) (:start2 index) (:end2 sequence-end)) sequence () :derive-type (sequence-result-nth-arg 0 :preserve-dimensions t :preserve-vector-type t) :result-arg 0) (defknown remove (t proper-sequence &rest t &key (:from-end t) (:test (function-designator ((nth-arg 0) (nth-arg 1 :sequence t :key :key)))) (:test-not (function-designator ((nth-arg 0) (nth-arg 1 :sequence t :key :key)))) (:start (inhibit-flushing index 0)) (:end (inhibit-flushing sequence-end nil)) (:count sequence-count) (:key (function-designator ((nth-arg 1 :sequence t))))) consed-sequence (flushable call) :derive-type (sequence-result-nth-arg 1)) (defknown substitute (t t proper-sequence &rest t &key (:from-end t) (:test (function-designator ((nth-arg 1) (nth-arg 2 :sequence t :key :key)))) (:test-not (function-designator ((nth-arg 1) (nth-arg 2 :sequence t :key :key)))) (:start (inhibit-flushing index 0)) (:end (inhibit-flushing sequence-end nil)) (:count sequence-count) (:key (function-designator ((nth-arg 2 :sequence t))))) consed-sequence (flushable call) :derive-type (sequence-result-nth-arg 2)) (defknown (remove-if remove-if-not) ((function-designator ((nth-arg 1 :sequence t :key :key))) proper-sequence &rest t &key (:from-end t) (:count sequence-count) (:start (inhibit-flushing index 0)) (:end (inhibit-flushing sequence-end nil)) (:key (function-designator ((nth-arg 1 :sequence t))))) consed-sequence (flushable call) :derive-type (sequence-result-nth-arg 1)) (defknown (substitute-if substitute-if-not) (t (function-designator ((nth-arg 2 :sequence t :key :key))) proper-sequence &rest t &key (:from-end t) (:start (inhibit-flushing index 0)) (:end (inhibit-flushing sequence-end nil)) (:count sequence-count) (:key (function-designator ((nth-arg 2 :sequence t))))) consed-sequence (flushable call) :derive-type (sequence-result-nth-arg 2)) (defknown delete (t (modifying sequence) &rest t &key (:from-end t) (:test (function-designator ((nth-arg 0) (nth-arg 1 :sequence t :key :key)))) (:test-not (function-designator ((nth-arg 0) (nth-arg 1 :sequence t :key :key)))) (:start index) (:end sequence-end) (:count sequence-count) (:key (function-designator ((nth-arg 1 :sequence t))))) sequence (call important-result) :derive-type (sequence-result-nth-arg 1)) (defknown nsubstitute (t t (modifying sequence) &rest t &key (:from-end t) (:test (function-designator ((nth-arg 1) (nth-arg 2 :sequence t :key :key)))) (:test-not (function-designator ((nth-arg 1) (nth-arg 2 :sequence t :key :key)))) (:start index) (:end sequence-end) (:count sequence-count) (:key (function-designator ((nth-arg 2 :sequence t))))) sequence (call) :derive-type (sequence-result-nth-arg 2)) (defknown (delete-if delete-if-not) ((function-designator ((nth-arg 1 :sequence t :key :key))) (modifying sequence) &rest t &key (:from-end t) (:start index) (:end sequence-end) (:count sequence-count) (:key (function-designator ((nth-arg 1 :sequence t))))) sequence (call important-result) :derive-type (sequence-result-nth-arg 1)) (defknown (nsubstitute-if nsubstitute-if-not) (t (function-designator ((nth-arg 2 :sequence t :key :key))) (modifying sequence) &rest t &key (:from-end t) (:start index) (:end sequence-end) (:count sequence-count) (:key (function-designator ((nth-arg 2 :sequence t))))) sequence (call) :derive-type (sequence-result-nth-arg 2)) (defknown remove-duplicates (proper-sequence &rest t &key (:test (function-designator ((nth-arg 0 :sequence t :key :key) (nth-arg 0 :sequence t :key :key)))) (:test-not (function-designator ((nth-arg 0 :sequence t :key :key) (nth-arg 0 :sequence t :key :key)))) (:start (inhibit-flushing index 0)) (:end (inhibit-flushing sequence-end nil)) (:from-end t) (:key (function-designator ((nth-arg 0 :sequence t))))) consed-sequence (flushable call) :derive-type (sequence-result-nth-arg 0)) (defknown delete-duplicates ((modifying sequence) &rest t &key (:test (function-designator ((nth-arg 0 :sequence t :key :key) (nth-arg 0 :sequence t :key :key)))) (:test-not (function-designator ((nth-arg 0 :sequence t :key :key) (nth-arg 0 :sequence t :key :key)))) (:start index) (:from-end t) (:end sequence-end) (:key (function-designator ((nth-arg 0 :sequence t))))) sequence (call important-result) :derive-type (sequence-result-nth-arg 0)) (defknown find (t proper-sequence &rest t &key (:test (function-designator ((nth-arg 0) (nth-arg 1 :sequence t :key :key)))) (:test-not (function-designator ((nth-arg 0) (nth-arg 1 :sequence t :key :key)))) (:start (inhibit-flushing index 0)) (:end (inhibit-flushing sequence-end nil)) (:from-end t) (:key (function-designator ((nth-arg 1 :sequence t))))) t (foldable flushable call)) (defknown (find-if find-if-not) ((function-designator ((nth-arg 1 :sequence t :key :key))) proper-sequence &rest t &key (:from-end t) (:start (inhibit-flushing index 0)) (:end (inhibit-flushing sequence-end nil)) (:key (function-designator ((nth-arg 1 :sequence t))))) t (foldable flushable call)) (defknown position (t proper-sequence &rest t &key (:test (function-designator ((nth-arg 0) (nth-arg 1 :sequence t :key :key)))) (:test-not (function-designator ((nth-arg 0) (nth-arg 1 :sequence t :key :key)))) (:start (inhibit-flushing index 0)) (:end (inhibit-flushing sequence-end nil)) (:from-end t) (:key (function-designator ((nth-arg 1 :sequence t))))) (or (mod #.(1- array-dimension-limit)) null) (foldable flushable call)) (defknown (position-if position-if-not) ((function-designator ((nth-arg 1 :sequence t :key :key))) proper-sequence &rest t &key (:from-end t) (:start (inhibit-flushing index 0)) (:end (inhibit-flushing sequence-end nil)) (:key (function-designator ((nth-arg 1 :sequence t))))) (or (mod #.(1- array-dimension-limit)) null) (foldable flushable call)) (defknown (%bit-position/0 %bit-position/1) (simple-bit-vector t index index) (or (mod #.(1- array-dimension-limit)) null) (foldable flushable no-verify-arg-count)) (defknown (%bit-pos-fwd/0 %bit-pos-fwd/1 %bit-pos-rev/0 %bit-pos-rev/1) (simple-bit-vector index index) (or (mod #.(1- array-dimension-limit)) null) (foldable flushable no-verify-arg-count)) (defknown %bit-position (t simple-bit-vector t index index) (or (mod #.(1- array-dimension-limit)) null) (foldable flushable no-verify-arg-count)) (defknown (%bit-pos-fwd %bit-pos-rev) (t simple-bit-vector index index) (or (mod #.(1- array-dimension-limit)) null) (foldable flushable no-verify-arg-count)) (defknown count (t proper-sequence &rest t &key (:test (function-designator ((nth-arg 0) (nth-arg 1 :sequence t :key :key)))) (:test-not (function-designator ((nth-arg 0) (nth-arg 1 :sequence t :key :key)))) (:from-end t) (:start (inhibit-flushing index 0)) (:end (inhibit-flushing sequence-end nil)) (:key (function-designator ((nth-arg 1 :sequence t))))) index (foldable flushable call)) (defknown (count-if count-if-not) ((function-designator ((nth-arg 1 :sequence t :key :key))) proper-sequence &rest t &key (:from-end t) (:start (inhibit-flushing index 0)) (:end (inhibit-flushing sequence-end nil)) (:key (function-designator ((nth-arg 1 :sequence t))))) index (foldable flushable call)) (defknown (mismatch search) (proper-sequence proper-sequence &rest t &key (:from-end t) (:test (function-designator ((nth-arg 0 :sequence t :key :key) (nth-arg 1 :sequence t :key :key)))) (:test-not (function-designator ((nth-arg 0 :sequence t :key :key) (nth-arg 1 :sequence t :key :key)))) (:start1 (inhibit-flushing index 0)) (:end1 (inhibit-flushing sequence-end nil)) (:start2 (inhibit-flushing index 0)) (:end2 (inhibit-flushing sequence-end nil)) (:key (function-designator ((or (nth-arg 0 :sequence t) (nth-arg 1 :sequence t)))))) (or index null) (foldable flushable call)) not FLUSHABLE , since vector sort guaranteed in - place ... (defknown (stable-sort sort) ((modifying sequence) (function-designator ((nth-arg 0 :sequence t :key :key) (nth-arg 0 :sequence t :key :key))) &rest t &key (:key (function-designator ((nth-arg 0 :sequence t))))) sequence (call) :derive-type (sequence-result-nth-arg 0 :preserve-dimensions t :preserve-vector-type t)) (defknown sb-impl::stable-sort-list (list function function) list (call important-result no-verify-arg-count)) (defknown sb-impl::sort-vector (vector index index function (or function null)) SORT - VECTOR works through side - effect (call no-verify-arg-count)) (defknown sb-impl::stable-sort-vector (vector function (or function null)) vector (call no-verify-arg-count)) (defknown sb-impl::stable-sort-simple-vector (simple-vector function (or function null)) simple-vector (call no-verify-arg-count)) (defknown merge (type-specifier (modifying sequence) (modifying sequence) (function-designator ((nth-arg 1 :sequence t :key :key) (nth-arg 2 :sequence t :key :key))) &key (:key (function-designator ((or (nth-arg 1 :sequence t) (nth-arg 2 :sequence t)))))) sequence (call important-result) :derive-type (creation-result-type-specifier-nth-arg 0)) (defknown read-sequence ((modifying sequence) stream &key (:start index) (:end sequence-end)) (index) ()) (defknown write-sequence (proper-sequence stream &key (:start index) (:end sequence-end)) sequence (recursive) :derive-type #'result-type-first-arg) from the " Manipulating List Structure " chapter : (defknown (car cdr first rest) (list) t (foldable flushable)) ;; Correct argument type restrictions for these functions are ;; complicated, so we just declare them to accept LISTs and suppress ;; flushing in safe code. (defknown (caar cadr cdar cddr caaar caadr cadar caddr cdaar cdadr cddar cdddr caaaar caaadr caadar caaddr cadaar cadadr caddar cadddr cdaaar cdaadr cdadar cdaddr cddaar cddadr cdddar cddddr second third fourth fifth sixth seventh eighth ninth tenth) (list) t (foldable unsafely-flushable)) (defknown cons (t t) cons (movable flushable)) (defknown tree-equal (t t &key (:test (function-designator (t t))) (:test-not (function-designator (t t)))) boolean (foldable flushable call)) (defknown endp (list) boolean (foldable flushable movable)) (defknown list-length (proper-or-circular-list) (or index null) (foldable unsafely-flushable)) (defknown (nth fast-&rest-nth) (unsigned-byte list) t (foldable flushable)) (defknown nthcdr (unsigned-byte list) t (foldable unsafely-flushable)) (defknown last (list &optional unsigned-byte) t (foldable flushable)) (defknown %last0 (list) t (foldable flushable no-verify-arg-count)) (defknown %last1 (list) t (foldable flushable no-verify-arg-count)) (defknown %lastn/fixnum (list (and unsigned-byte fixnum)) t (foldable flushable no-verify-arg-count)) (defknown %lastn/bignum (list (and unsigned-byte bignum)) t (foldable flushable no-verify-arg-count)) (defknown list (&rest t) list (movable flushable)) (defknown list* (t &rest t) t (movable flushable)) ;;; The length constraint on MAKE-LIST is such that: ;;; - not every byte of addressable memory can be used up. ;;; - the number of bytes to allocate should be a fixnum ;;; - type-checking can use use efficient bit-masking approach to combine the fixnum + range test into one instruction (eval-when (:compile-toplevel :load-toplevel :execute) (defconstant make-list-limit (ash most-positive-fixnum (- (+ sb-vm:word-shift 1))))) (defknown make-list ((integer 0 #.make-list-limit) &key (:initial-element t)) list (movable flushable)) (defknown %make-list ((integer 0 #.make-list-limit) t) list (movable flushable no-verify-arg-count)) (defknown sb-impl::|List| (&rest t) list (movable flushable)) (defknown sb-impl::|List*| (t &rest t) t (movable flushable)) (defknown sb-impl::|Append| (&rest t) t (movable flushable)) (defknown sb-impl::|Vector| (&rest t) simple-vector (movable flushable)) ;;; All but last must be of type LIST, but there seems to be no way to ;;; express that in this syntax. (defknown append (&rest t) t (flushable) :call-type-deriver #'append-call-type-deriver) (defknown sb-impl::append2 (list t) t (flushable no-verify-arg-count) :call-type-deriver #'append-call-type-deriver) (defknown copy-list (proper-or-dotted-list) list (flushable)) (defknown copy-alist (proper-list) list (flushable)) (defknown copy-tree (t) t (flushable recursive)) (defknown revappend (proper-list t) t (flushable)) (defknown nconc (&rest (modifying t :butlast t)) t ()) (defknown nreconc ((modifying list) t) t (important-result)) (defknown butlast (proper-or-dotted-list &optional unsigned-byte) list (flushable)) (defknown nbutlast ((modifying list) &optional unsigned-byte) list ()) (defknown ldiff (proper-or-dotted-list t) list (flushable)) (defknown (rplaca rplacd) ((modifying cons) t) cons ()) (defknown subst (t t t &key (:test (function-designator ((nth-arg 1) (nth-arg 2 :sequence t :key :key)))) (:test-not (function-designator ((nth-arg 1) (nth-arg 2 :sequence t :key :key)))) (:key (function-designator ((nth-arg 2 :sequence t))))) t (flushable call)) (defknown nsubst (t t (modifying t) &key (:test (function-designator ((nth-arg 1) (nth-arg 2 :sequence t :key :key)))) (:test-not (function-designator ((nth-arg 1) (nth-arg 2 :sequence t :key :key)))) (:key (function-designator ((nth-arg 2 :sequence t))))) t (call)) (defknown (subst-if subst-if-not) (t (function-designator ((nth-arg 2 :sequence t :key :key))) t &key (:key (function-designator ((nth-arg 2 :sequence t))))) t (flushable call)) (defknown (nsubst-if nsubst-if-not) (t (function-designator ((nth-arg 2 :sequence t :key :key))) (modifying t) &key (:key (function-designator ((nth-arg 2 :sequence t))))) t (call)) (defknown sublis (proper-list t &key (:test (function-designator ((nth-arg 1 :sequence t :key :key) (nth-arg 0 :sequence t)))) (:test-not (function-designator ((nth-arg 1 :sequence t :key :key) (nth-arg 0 :sequence t)))) (:key (function-designator ((nth-arg 1 :sequence t))))) t (flushable call)) (defknown nsublis (list (modifying t) &key (:test (function-designator ((nth-arg 1 :sequence t :key :key) (nth-arg 0 :sequence t)))) (:test-not (function-designator ((nth-arg 1 :sequence t :key :key) (nth-arg 0 :sequence t)))) (:key (function-designator ((nth-arg 1 :sequence t))))) t (flushable call)) (defknown member (t proper-list &key (:test (function-designator ((nth-arg 0) (nth-arg 1 :sequence t :key :key)))) (:test-not (function-designator ((nth-arg 0) (nth-arg 1 :sequence t :key :key)))) (:key (function-designator ((nth-arg 1 :sequence t))))) list (foldable flushable call)) (defknown (member-if member-if-not) ((function-designator ((nth-arg 1 :sequence t :key :key))) proper-list &key (:key (function-designator ((nth-arg 1 :sequence t))))) list (foldable flushable call)) (defknown tailp (t list) boolean (foldable flushable)) (defknown adjoin (t proper-list &key (:key (function-designator ((or (nth-arg 0) (nth-arg 1 :sequence t))))) (:test (function-designator ((nth-arg 0 :key :key) (nth-arg 1 :sequence t :key :key)))) (:test-not (function-designator ((nth-arg 0 :key :key) (nth-arg 1 :sequence t :key :key))))) cons (flushable call)) (defknown (union intersection set-difference set-exclusive-or) (proper-list proper-list &key (:key (function-designator ((or (nth-arg 0 :sequence t) (nth-arg 1 :sequence t))))) (:test (function-designator ((nth-arg 0 :sequence t :key :key) (nth-arg 1 :sequence t :key :key)))) (:test-not (function-designator ((nth-arg 0 :sequence t :key :key) (nth-arg 1 :sequence t :key :key))))) list (foldable flushable call)) (defknown (nunion nintersection nset-difference nset-exclusive-or) ((modifying list) (modifying list) &key (:key (function-designator ((or (nth-arg 0 :sequence t) (nth-arg 1 :sequence t))))) (:test (function-designator ((nth-arg 0 :sequence t :key :key) (nth-arg 1 :sequence t :key :key)))) (:test-not (function-designator ((nth-arg 0 :sequence t :key :key) (nth-arg 1 :sequence t :key :key))))) list (foldable flushable call important-result)) (defknown subsetp (proper-list proper-list &key (:key (function-designator ((or (nth-arg 0 :sequence t) (nth-arg 1 :sequence t))))) (:test (function-designator ((nth-arg 0 :sequence t :key :key) (nth-arg 1 :sequence t :key :key)))) (:test-not (function-designator ((nth-arg 0 :sequence t :key :key) (nth-arg 1 :sequence t :key :key))))) boolean (foldable flushable call)) (defknown acons (t t t) cons (movable flushable)) (defknown pairlis (t t &optional t) list (flushable)) (defknown (rassoc assoc) (t proper-list &key (:key (function-designator ((nth-arg 1 :sequence t)))) (:test (function-designator ((nth-arg 0) (nth-arg 1 :sequence t :key :key)))) (:test-not (function-designator ((nth-arg 0) (nth-arg 1 :sequence t :key :key))))) list (foldable flushable call)) (defknown (assoc-if-not assoc-if rassoc-if rassoc-if-not) ((function-designator ((nth-arg 1 :sequence t :key :key))) proper-list &key (:key (function-designator ((nth-arg 1 :sequence t))))) list (foldable flushable call)) (defknown (memq assq) (t proper-list) list (foldable flushable)) (defknown (delq delq1) (t (modifying list)) list (flushable)) from the " Hash Tables " chapter : (defknown make-hash-table (&key (:test function-designator) (:size unsigned-byte) (:rehash-size (or (integer 1) (float ($1.0)))) (:rehash-threshold (real 0 1)) (:hash-function (or null function-designator)) (:weakness (member nil :key :value :key-and-value :key-or-value)) (:synchronized t)) hash-table (flushable)) (defknown sb-impl::make-hash-table-using-defaults (integer) hash-table (flushable)) (defknown hash-table-p (t) boolean (movable foldable flushable)) (defknown gethash (t hash-table &optional t) (values t boolean) not FOLDABLE , since hash table contents can change (defknown sb-impl::gethash3 (t hash-table t) (values t boolean) not FOLDABLE , since hash table contents can change (defknown %puthash (t (modifying hash-table) t) t (no-verify-arg-count) :derive-type #'result-type-last-arg) (defknown remhash (t (modifying hash-table)) boolean ()) (defknown maphash ((function-designator (t t)) hash-table) null (flushable call)) (defknown clrhash ((modifying hash-table)) hash-table ()) (defknown hash-table-count (hash-table) index (flushable)) (defknown hash-table-rehash-size (hash-table) (or index (single-float ($1.0))) (foldable flushable)) (defknown hash-table-rehash-threshold (hash-table) (single-float ($0.0) $1.0) (foldable flushable)) (defknown hash-table-size (hash-table) index (flushable)) (defknown hash-table-test (hash-table) function-designator (foldable flushable)) (defknown (sxhash psxhash) (t) hash-code (foldable flushable)) (defknown hash-table-equalp (hash-table hash-table) boolean (foldable flushable)) (defknown sb-impl::install-hash-table-lock (hash-table) sb-thread:mutex ()) ;; To avoid emitting code to test for nil-function-returned (defknown (sb-impl::signal-corrupt-hash-table sb-impl::signal-corrupt-hash-table-bucket) (t) nil ()) ;;;; from the "Arrays" chapter (defknown make-array ((or index list) &key (:element-type type-specifier) (:initial-element t) (:initial-contents t) (:adjustable t) (:fill-pointer (or index boolean)) (:displaced-to (or array null)) (:displaced-index-offset index)) array (flushable)) (defknown %make-array ((or index list) (unsigned-byte #.sb-vm:n-widetag-bits) (mod #.sb-vm:n-word-bits) &key (:element-type type-specifier) (:initial-element t) (:initial-contents t) (:adjustable t) (:fill-pointer (or index boolean)) (:displaced-to (or array null)) (:displaced-index-offset index)) array (flushable no-verify-arg-count)) (defknown sb-vm::initial-contents-error (t t) nil (no-verify-arg-count)) (defknown fill-data-vector (vector list sequence) vector (no-verify-arg-count) :result-arg 0) INITIAL - CONTENTS is the first argument to FILL - ARRAY because ;; of the possibility of source-transforming it for various recognized ;; contents after the source-transform for MAKE-ARRAY has run. ;; The original MAKE-ARRAY call might resemble either of: ;; (MAKE-ARRAY DIMS :ELEMENT-TYPE (F) :INITIAL-CONTENTS (G)) ;; (MAKE-ARRAY DIMS :INITIAL-CONTENTS (F) :ELEMENT-TYPE (G)) ;; and in general we must bind temporaries to preserve left-to-right ;; evaluation of F and G if they have side effects. ;; Now ideally :ELEMENT-TYPE will be a constant, so it doesn't matter if it moves . But if INITIAL - CONTENTS were the second argument to FILL - ARRAY , ;; then the multi-dimensional array creation form would look like ;; (FILL-ARRAY (allocate-array) initial-contents) ;; which would mean that if the user expressed the MAKE- call the second way shown above , we would have to bind INITIAL - CONTENTS , ;; to ensure its evaluation before the allocation, ;; causing difficulty if doing any futher macro-like processing. (defknown fill-array (sequence simple-array) (simple-array) (flushable no-verify-arg-count) :result-arg 1) (defknown vector (&rest t) simple-vector (flushable)) (defknown aref (array &rest index) t (foldable) :call-type-deriver #'array-call-type-deriver) (defknown row-major-aref (array index) t (foldable) :call-type-deriver (lambda (call trusted) (array-call-type-deriver call trusted nil t))) (defknown array-element-type (array) (or list symbol) (foldable flushable)) (defknown array-rank (array) array-rank (foldable flushable)) ;; FIXME: there's a fencepost bug, but for all practical purposes our ;; ARRAY-RANK-LIMIT is infinite, thus masking the bug. e.g. if the exclusive limit on rank were 8 , then your dimension numbers can be in the range 0 through 6 , not 0 through 7 . (defknown array-dimension (array array-rank) index (foldable flushable)) (defknown array-dimensions (array) list (foldable flushable)) (defknown array-in-bounds-p (array &rest integer) boolean (foldable flushable) :call-type-deriver #'array-call-type-deriver) (defknown array-row-major-index (array &rest index) array-total-size (foldable flushable) :call-type-deriver #'array-call-type-deriver) (defknown array-total-size (array) array-total-size (foldable flushable)) (defknown adjustable-array-p (array) boolean (movable foldable flushable)) (defknown svref (simple-vector index) t (foldable flushable)) (defknown bit ((array bit) &rest index) bit (foldable flushable)) (defknown sbit ((simple-array bit) &rest index) bit (foldable flushable)) ;;; FIXME: MODIFYING for these is complicated. (defknown (bit-and bit-ior bit-xor bit-eqv bit-nand bit-nor bit-andc1 bit-andc2 bit-orc1 bit-orc2) ((array bit) (array bit) &optional (or (array bit) (member t nil))) (array bit) () #|:derive-type #'result-type-last-arg|#) (defknown bit-not ((array bit) &optional (or (array bit) (member t nil))) (array bit) () #|:derive-type #'result-type-last-arg|#) (defknown bit-vector-= (bit-vector bit-vector) boolean (movable foldable flushable no-verify-arg-count)) (defknown array-has-fill-pointer-p (array) boolean (movable foldable flushable)) (defknown fill-pointer (complex-vector) index (unsafely-flushable)) (defknown sb-vm::fill-pointer-error (t) nil (no-verify-arg-count)) (defknown vector-push (t (modifying complex-vector)) (or index null) ()) (defknown vector-push-extend (t (modifying complex-vector) &optional (and index (integer 1))) index ()) (defknown vector-pop ((modifying complex-vector)) t ()) ;;; FIXME: complicated MODIFYING (defknown adjust-array (array (or index list) &key (:element-type type-specifier) (:initial-element t) (:initial-contents t) (:fill-pointer (or index boolean)) (:displaced-to (or array null)) (:displaced-index-offset index)) ;; This is a special case in CHECK-IMPORTANT-RESULT because it is not ;; necessary to use the result if the array is adjustable. array (important-result)) ; :derive-type 'result-type-arg1) Not even close... ;;;; from the "Strings" chapter: (defknown char (string index) character (foldable flushable)) (defknown schar (simple-string index) character (foldable flushable)) (defknown (string= string-equal) (string-designator string-designator &key (:start1 (inhibit-flushing index 0)) (:end1 (inhibit-flushing sequence-end nil)) (:start2 (inhibit-flushing index 0)) (:end2 (inhibit-flushing sequence-end nil))) boolean (foldable flushable)) (defknown (string< string> string<= string>= string/= string-lessp string-greaterp string-not-lessp string-not-greaterp string-not-equal) (string-designator string-designator &key (:start1 (inhibit-flushing index 0)) (:end1 (inhibit-flushing sequence-end nil)) (:start2 (inhibit-flushing index 0)) (:end2 (inhibit-flushing sequence-end nil))) (or index null) (foldable flushable)) (defknown (two-arg-string= two-arg-string-equal) (string-designator string-designator) boolean (foldable flushable no-verify-arg-count)) (defknown (two-arg-string< two-arg-string> two-arg-string<= two-arg-string>= two-arg-string/= two-arg-string-lessp two-arg-string-greaterp two-arg-string-not-lessp two-arg-string-not-greaterp two-arg-string-not-equal) (string-designator string-designator) (or index null) (foldable flushable no-verify-arg-count)) (defknown make-string (index &key (:element-type type-specifier) (:initial-element character)) simple-string (flushable)) (defknown (string-trim string-left-trim string-right-trim) (proper-sequence string-designator) string (flushable)) (defknown (string-upcase string-downcase string-capitalize) (string-designator &key (:start (inhibit-flushing index 0)) (:end (inhibit-flushing sequence-end nil))) simple-string (flushable) :derive-type (sequence-result-nth-arg 0 :preserve-dimensions t)) (defknown (nstring-upcase nstring-downcase nstring-capitalize) ((modifying string) &key (:start index) (:end sequence-end)) string () :derive-type #'result-type-first-arg) (defknown string (string-designator) string (flushable)) ;;;; internal non-keyword versions of string predicates: (defknown (string<* string>* string<=* string>=* string/=*) (string-designator string-designator (inhibit-flushing index 0) (inhibit-flushing sequence-end nil) (inhibit-flushing index 0) (inhibit-flushing sequence-end nil)) (or index null) (foldable flushable no-verify-arg-count)) (defknown string=* (string-designator string-designator (inhibit-flushing index 0) (inhibit-flushing sequence-end nil) (inhibit-flushing index 0) (inhibit-flushing sequence-end nil)) boolean (foldable flushable no-verify-arg-count)) (defknown simple-base-string= (simple-base-string simple-base-string (inhibit-flushing index 0) (inhibit-flushing sequence-end nil) (inhibit-flushing index 0) (inhibit-flushing sequence-end nil)) boolean (foldable flushable no-verify-arg-count)) (defknown simple-character-string= (simple-character-string simple-character-string (inhibit-flushing index 0) (inhibit-flushing sequence-end nil) (inhibit-flushing index 0) (inhibit-flushing sequence-end nil)) boolean (foldable flushable no-verify-arg-count)) from the " Eval " chapter : (defknown eval (t) * (recursive)) (defknown constantp (t &optional lexenv-designator) boolean (foldable flushable)) ;;;; from the "Streams" chapter: (defknown make-synonym-stream (symbol) synonym-stream (flushable)) (defknown make-broadcast-stream (&rest stream) broadcast-stream (unsafely-flushable)) (defknown make-concatenated-stream (&rest stream) concatenated-stream (unsafely-flushable)) (defknown make-two-way-stream (stream stream) two-way-stream (unsafely-flushable)) (defknown make-echo-stream (stream stream) echo-stream (flushable)) (defknown make-string-input-stream (string &optional index sequence-end) sb-impl::string-input-stream (flushable)) (defknown sb-impl::%init-string-input-stream (instance string &optional index sequence-end) (values sb-impl::string-input-stream index &optional) (flushable)) (defknown sb-impl::%init-string-output-stream (instance t t) sb-impl::string-output-stream Not flushable , for two reasons : - possibly need to verify that the second arg is a type specifier ;; - if you don't initialize the stream, then GET-OUTPUT-STRING-STREAM will crash (no-verify-arg-count)) (defknown make-string-output-stream (&key (:element-type type-specifier)) sb-impl::string-output-stream (flushable)) (defknown get-output-stream-string (stream) simple-string ()) (defknown streamp (t) boolean (movable foldable flushable)) (defknown stream-element-type (stream) type-specifier ; can it return a CLASS? (movable foldable flushable)) (defknown stream-external-format (stream) t (flushable)) (defknown (output-stream-p input-stream-p) (stream) boolean (movable foldable flushable)) (defknown open-stream-p (stream) boolean (flushable)) (defknown close (stream &key (:abort t)) (eql t) ()) (defknown file-string-length (stream (or string character)) (or unsigned-byte null) (flushable)) ;;;; from the "Input/Output" chapter: ;;; (The I/O functions are given effects ANY under the theory that ;;; code motion over I/O operations is particularly confusing and not ;;; very important for efficiency.) (defknown copy-readtable (&optional (or readtable null) (or readtable null)) readtable ()) (defknown readtablep (t) boolean (movable foldable flushable)) (defknown set-syntax-from-char (character character &optional readtable (or readtable null)) (eql t) ()) (defknown set-macro-character (character (function-designator (t t) * :no-function-conversion t) &optional t (or readtable null)) (eql t) (call)) (defknown get-macro-character (character &optional (or readtable null)) (values function-designator boolean) (flushable)) (defknown make-dispatch-macro-character (character &optional t readtable) (eql t) ()) ;;; FIXME: (function-designator ...) causes a style warning in the :UNICODE-DISPATCH-MACROS test in reader.impure.lisp The function NIL is called by SET - DISPATCH - MACRO - CHARACTER with three arguments , but wants exactly two . (defknown set-dispatch-macro-character (character character (function-designator (t t t) * :no-function-conversion t) &optional (or readtable null)) (eql t) (call)) (defknown get-dispatch-macro-character (character character &optional (or readtable null)) (or function-designator null) ()) (defknown copy-pprint-dispatch (&optional (or sb-pretty:pprint-dispatch-table null)) sb-pretty:pprint-dispatch-table ()) (defknown pprint-dispatch (t &optional (or sb-pretty:pprint-dispatch-table null)) (values function-designator boolean) ()) (defknown (pprint-fill pprint-linear) (stream-designator t &optional t t) null ()) (defknown pprint-tabular (stream-designator t &optional t t unsigned-byte) null ()) (defknown pprint-indent ((member :block :current) real &optional stream-designator) null ()) (defknown pprint-newline ((member :linear :fill :miser :mandatory) &optional stream-designator) null ()) (defknown pprint-tab ((member :line :section :line-relative :section-relative) unsigned-byte unsigned-byte &optional stream-designator) null ()) (defknown set-pprint-dispatch (type-specifier (function-designator (t t) * :no-function-conversion t) &optional real sb-pretty:pprint-dispatch-table) null (call)) ;;; may return any type due to eof-value... ;;; and because READ generally returns anything. (defknown (read read-preserving-whitespace) (&optional stream-designator t t t) t ()) (defknown read-char (&optional stream-designator t t t) t () :derive-type (read-elt-type-deriver nil 'character nil)) (defknown read-char-no-hang (&optional stream-designator t t t) t () :derive-type (read-elt-type-deriver nil 'character t)) (defknown read-delimited-list (character &optional stream-designator t) list ()) ;; FIXME: add a type-deriver => (values (or string eof-value) boolean) (defknown read-line (&optional stream-designator t t t) (values t boolean) ()) (defknown unread-char (character &optional stream-designator) t ()) (defknown peek-char (&optional (or character (member nil t)) stream-designator t t t) t () :derive-type (read-elt-type-deriver t 'character nil)) (defknown listen (&optional stream-designator) boolean (flushable)) (defknown clear-input (&optional stream-designator) null ()) (defknown read-from-string (string &optional t t &key (:start index) (:end sequence-end) (:preserve-whitespace t)) (values t index)) (defknown parse-integer (string &key (:start index) (:end sequence-end) (:radix (integer 2 36)) (:junk-allowed t)) (values (or integer null ()) index)) (defknown read-byte (stream &optional t t) t () :derive-type (read-elt-type-deriver nil 'integer nil)) (defknown (prin1 print princ) (t &optional stream-designator) t (any) :derive-type #'result-type-first-arg) (defknown output-object (t stream) null (any)) (defknown %write (t stream-designator) t (any no-verify-arg-count)) (defknown (pprint) (t &optional stream-designator) (values) ()) (macrolet ((deffrob (name keys returns attributes &rest more) `(defknown ,name (t &key ,@keys (:escape t) (:radix t) (:base (integer 2 36)) (:circle t) (:pretty t) (:readably t) (:level (or unsigned-byte null)) (:length (or unsigned-byte null)) (:case t) (:array t) (:gensym t) (:lines (or unsigned-byte null)) (:right-margin (or unsigned-byte null)) (:miser-width (or unsigned-byte null)) (:pprint-dispatch t) (:suppress-errors t)) ,returns ,attributes ,@more))) (deffrob write ((:stream stream-designator)) t (any) :derive-type #'result-type-first-arg) ;;; xxx-TO-STRING functions are not foldable because they depend on ;;; the dynamic environment, the state of the pretty printer dispatch ;;; table, and probably other run-time factors. (deffrob write-to-string () simple-string (unsafely-flushable))) (defknown (prin1-to-string princ-to-string) (t) simple-string (unsafely-flushable)) (defknown sb-impl::stringify-object (t) simple-string (no-verify-arg-count)) (defknown write-char (character &optional stream-designator) character () :derive-type #'result-type-first-arg) (defknown (write-string write-line) (string &optional stream-designator &key (:start index) (:end sequence-end)) string () :derive-type #'result-type-first-arg) (defknown (terpri finish-output force-output clear-output) (&optional stream-designator) null ()) (defknown fresh-line (&optional stream-designator) boolean ()) (defknown write-byte (integer stream) integer () :derive-type #'result-type-first-arg) ;;; FIXME: complicated MODIFYING (defknown format ((or (member nil t) stream string) (or string function) &rest t) (or string null) ()) (defknown sb-format::format-error* (string list &rest t &key &allow-other-keys) nil) (defknown sb-format:format-error (string &rest t) nil) (defknown sb-format::format-error-at* ((or null string) (or null index) string list &rest t &key &allow-other-keys) nil) (defknown sb-format::format-error-at ((or null string) (or null index) string &rest t) nil) (defknown sb-format::args-exhausted (string integer) nil) (defknown (y-or-n-p yes-or-no-p) (&optional (or string null function) &rest t) boolean ()) from the " File System Interface " chapter : ( No pathname functions are FOLDABLE because they all potentially depend on * DEFAULT - PATHNAME - DEFAULTS * , e.g. to provide a default ;;; host when parsing a namestring. They are not FLUSHABLE because ;;; parsing of a PATHNAME-DESIGNATOR might signal an error.) (defknown wild-pathname-p (pathname-designator &optional (member nil :host :device :directory :name :type :version)) generalized-boolean (recursive)) (defknown pathname-match-p (pathname-designator pathname-designator) generalized-boolean ()) (defknown translate-pathname (pathname-designator pathname-designator pathname-designator &key) pathname ()) (defknown logical-pathname (pathname-designator) logical-pathname ()) (defknown translate-logical-pathname (pathname-designator &key) pathname (recursive)) (defknown load-logical-pathname-translations (string) t ()) (defknown logical-pathname-translations (logical-host-designator) list ()) (defknown pathname (pathname-designator) pathname ()) (defknown truename (pathname-designator) pathname ()) (defknown parse-namestring (pathname-designator &optional (or list host string (member :unspecific)) pathname-designator &key (:start index) (:end sequence-end) (:junk-allowed t)) (values (or pathname null) sequence-end) (recursive)) (defknown merge-pathnames (pathname-designator &optional pathname-designator pathname-version) pathname ()) (defknown make-pathname (&key (:defaults pathname-designator) (:host (or string pathname-host)) (:device (or string pathname-device)) (:directory (or pathname-directory string (member :wild))) (:name (or pathname-name string (member :wild))) (:type (or pathname-type string (member :wild))) (:version pathname-version) (:case pathname-component-case)) pathname (unsafely-flushable)) (defknown pathnamep (t) boolean (movable flushable)) (defknown pathname-host (pathname-designator &key (:case pathname-component-case)) pathname-host (flushable)) (defknown pathname-device (pathname-designator &key (:case pathname-component-case)) pathname-device (flushable)) (defknown pathname-directory (pathname-designator &key (:case pathname-component-case)) pathname-directory (flushable)) (defknown pathname-name (pathname-designator &key (:case pathname-component-case)) pathname-name (flushable)) (defknown pathname-type (pathname-designator &key (:case pathname-component-case)) pathname-type (flushable)) (defknown pathname-version (pathname-designator) pathname-version (flushable)) (defknown pathname= (pathname pathname) boolean (movable foldable flushable)) (defknown (namestring file-namestring directory-namestring host-namestring) (pathname-designator) (or simple-string null) (unsafely-flushable)) (defknown enough-namestring (pathname-designator &optional pathname-designator) simple-string (unsafely-flushable)) (defknown user-homedir-pathname (&optional t) pathname (flushable)) (defknown open (pathname-designator &key (:class symbol) (:direction (member :input :output :io :probe)) (:element-type type-specifier) (:if-exists (member :error :new-version :rename :rename-and-delete :overwrite :append :supersede nil)) (:if-does-not-exist (member :error :create nil)) (:external-format external-format-designator) #+win32 (:overlapped t)) (or stream null)) (defknown rename-file (pathname-designator filename) (values pathname pathname pathname)) (defknown delete-file (pathname-designator) (eql t)) (defknown probe-file (pathname-designator) (or pathname null) ()) (defknown file-write-date (pathname-designator) (or unsigned-byte null) ()) (defknown file-author (pathname-designator) (or simple-string null) ()) (defknown file-position (stream &optional (or unsigned-byte (member :start :end))) (or unsigned-byte (member t nil))) (defknown file-length ((or file-stream synonym-stream broadcast-stream)) (or unsigned-byte null) (unsafely-flushable)) (defknown load ((or filename stream) &key (:verbose t) (:print t) (:if-does-not-exist t) (:external-format external-format-designator)) boolean) (defknown directory (pathname-designator &key (:resolve-symlinks t)) list ()) from the " Conditions " chapter : (defknown (signal warn) (condition-designator-head &rest t) null) (defknown error (condition-designator-head &rest t) nil) (defknown cerror (format-control condition-designator-head &rest t) null) FIXME : first arg is METHOD (defknown method-combination-error (format-control &rest t) *) (defknown assert-error (t &rest t) null) (defknown check-type-error (t t type-specifier &optional (or null string)) t) (defknown invoke-debugger (condition) nil) (defknown break (&optional format-control &rest t) null) (defknown make-condition (type-specifier &rest t) condition ()) (defknown compute-restarts (&optional (or condition null)) list) (defknown find-restart (restart-designator &optional (or condition null)) (or restart null)) (defknown invoke-restart (restart-designator &rest t) *) (defknown invoke-restart-interactively (restart-designator) *) (defknown restart-name (restart) symbol) (defknown (abort muffle-warning) (&optional (or condition null)) nil) (defknown continue (&optional (or condition null)) null) (defknown (store-value use-value) (t &optional (or condition null)) null) and analogous SBCL extension : (defknown sb-impl::%failed-aver (t) nil (no-verify-arg-count)) (defknown sb-impl::unreachable () nil) (defknown bug (t &rest t) nil) ; never returns (defknown simple-reader-error (stream string &rest t) nil) (defknown sb-kernel:reader-eof-error (stream string) nil) ;;;; from the "Miscellaneous" Chapter: (defknown compile ((or symbol cons) &optional (or list function)) (values (or function symbol cons) boolean boolean)) (defknown compile-file (pathname-designator &key ANSI options (:output-file pathname-designator) (:verbose t) (:print t) (:external-format external-format-designator) ;; extensions (:progress t) (:trace-file t) (:block-compile t) (:entry-points list) (:emit-cfasl t)) (values (or pathname null) boolean boolean)) (defknown (compile-file-pathname) (pathname-designator &key (:output-file (or pathname-designator null (member t))) &allow-other-keys) pathname) (defknown disassemble ((or extended-function-designator (cons (member lambda)) code-component) &key (:stream stream) (:use-labels t)) null) (defknown describe (t &optional stream-designator) (values)) (defknown function-lambda-expression (function) (values t boolean t)) (defknown inspect (t) (values)) (defknown room (&optional (member t nil :default)) (values)) (defknown ed (&optional (or symbol cons filename)) t) (defknown dribble (&optional filename &key (:if-exists t)) (values)) (defknown apropos (string-designator &optional package-designator t) (values)) (defknown apropos-list (string-designator &optional package-designator t) list (flushable recursive)) (defknown get-decoded-time () (values (integer 0 59) (integer 0 59) (integer 0 23) (integer 1 31) (integer 1 12) unsigned-byte (integer 0 6) boolean (rational -24 24)) (flushable)) (defknown get-universal-time () unsigned-byte (flushable)) (defknown decode-universal-time (unsigned-byte &optional (or null (rational -24 24))) (values (integer 0 59) (integer 0 59) (integer 0 23) (integer 1 31) (integer 1 12) unsigned-byte (integer 0 6) boolean (rational -24 24)) (flushable)) (defknown encode-universal-time ((integer 0 59) (integer 0 59) (integer 0 23) (integer 1 31) (integer 1 12) unsigned-byte &optional (or null (rational -24 24))) unsigned-byte (flushable)) (defknown (get-internal-run-time get-internal-real-time) () internal-time (flushable)) (defknown sleep ((real 0)) null ()) (defknown call-with-timing (function-designator function-designator &rest t) * (call)) ;;; Even though ANSI defines LISP-IMPLEMENTATION-TYPE and LISP - IMPLEMENTATION - VERSION to possibly punt and return NIL , we ;;; know that there's no valid reason for our implementations to ever ;;; do so, so we can safely guarantee that they'll return strings. (defknown (lisp-implementation-type lisp-implementation-version) () simple-string (flushable)) ;;; For any of these functions, meaningful information might not be ;;; available, so -- unlike the related LISP-IMPLEMENTATION-FOO functions -- these really can return NIL . (defknown (machine-type machine-version machine-instance software-type software-version short-site-name long-site-name) () (or simple-string null) (flushable)) (defknown identity (t) t (movable foldable flushable) :derive-type #'result-type-first-arg) (defknown constantly (t) function (movable flushable)) (defknown complement (function) function (movable flushable)) ;;;; miscellaneous extensions (defknown symbol-global-value (symbol) t () :derive-type #'symbol-value-derive-type) (defknown set-symbol-global-value (symbol t) t () :derive-type #'result-type-last-arg) (defknown get-bytes-consed () unsigned-byte (flushable)) (defknown mask-signed-field ((integer 0 *) integer) integer (movable flushable foldable)) (defknown array-storage-vector (array) (simple-array * (*)) (any)) ;;;; magical compiler frobs (defknown %rest-values (t t t) * (always-translatable)) (defknown %rest-ref (t t t t &optional boolean) * (always-translatable)) (defknown %rest-length (t t t) * (always-translatable)) (defknown %rest-null (t t t t) * (always-translatable)) (defknown %rest-true (t t t) * (always-translatable)) (defknown %unary-truncate/single-float (single-float) integer (movable foldable flushable no-verify-arg-count)) (defknown %unary-truncate/double-float (double-float) integer (movable foldable flushable no-verify-arg-count)) ;;; We can't fold this in general because of SATISFIES. There is a ;;; special optimizer anyway. (defknown %typep (t (or type-specifier ctype)) boolean (movable flushable no-verify-arg-count)) (defknown %instance-typep (t (or type-specifier ctype wrapper)) boolean (movable flushable always-translatable)) ;;; We should never emit a call to %typep-wrapper (defknown %typep-wrapper (t t (or type-specifier ctype)) t (movable flushable always-translatable)) (defknown %type-constraint (t (or type-specifier ctype)) t (always-translatable)) ;;; An identity wrapper to avoid complaints about constant modification (defknown ltv-wrapper (t) t (movable flushable always-translatable) :derive-type #'result-type-first-arg) (defknown %cleanup-point (&rest t) t (reoptimize-when-unlinking)) (defknown %special-bind (t t) t) (defknown %special-unbind (&rest symbol) t) (defknown %listify-rest-args (t index) list (flushable)) (defknown %more-arg-context (t t) (values t index) (flushable)) (defknown %more-arg (t index) t (flushable)) (defknown %more-keyword-pair (t fixnum) (values t t) (flushable)) #+stack-grows-downward-not-upward FIXME : The second argument here should really be NEGATIVE - INDEX , but doing that breaks the build , and I can not seem to figure out why . --NS 2006 - 06 - 29 (defknown %more-kw-arg (t fixnum) (values t t)) (defknown %more-arg-values (t index index) * (flushable)) (defknown %verify-arg-count (index index) (values)) (defknown %arg-count-error (t) nil) (defknown %local-arg-count-error (t t) nil) (defknown %unknown-values () *) (defknown %catch (t t) t) (defknown %unwind-protect (t t) t) (defknown (%catch-breakup %unwind-protect-breakup %lexical-exit-breakup) (t) t) (defknown %unwind (t t t) nil) (defknown %continue-unwind () nil) (defknown %throw (t &rest t) nil) ; This is MV-called. (defknown %nlx-entry (t) *) (defknown %%primitive (t t &rest t) *) (defknown %pop-values (t) t) (defknown %nip-values (t t &rest t) (values)) (defknown %dummy-dx-alloc (t t) t) (defknown %type-check-error (t t t) nil) (defknown %type-check-error/c (t t t) nil) ;; %compile-time-type-error does not return, but due to the implementation ;; of FILTER-LVAR we cannot write it here. (defknown (%compile-time-type-error %compile-time-type-style-warn) (t t t t t t) *) (defknown (etypecase-failure ecase-failure) (t t) nil) (defknown %odd-key-args-error () nil) (defknown %unknown-key-arg-error (t t) nil) (defknown (%ldb %mask-field) (bit-index bit-index integer) unsigned-byte (movable foldable flushable no-verify-arg-count)) (defknown (%dpb %deposit-field) (integer bit-index bit-index integer) integer (movable foldable flushable no-verify-arg-count)) (defknown %negate (number) number (movable foldable flushable no-verify-arg-count)) (defknown (%check-bound check-bound) (array index t) index (dx-safe)) (defknown data-vector-ref (simple-array index) t (foldable flushable always-translatable)) (defknown data-vector-ref-with-offset (simple-array fixnum fixnum) t (foldable flushable always-translatable)) (defknown data-nil-vector-ref (simple-array index) nil (always-translatable)) ;;; The lowest-level vector SET operators should not return a value. ;;; Functions built upon them may return the input value. (defknown data-vector-set (array index t) (values) (dx-safe always-translatable)) (defknown data-vector-set-with-offset (array fixnum fixnum t) (values) (dx-safe always-translatable)) (defknown hairy-data-vector-ref (array index) t (foldable flushable no-verify-arg-count)) (defknown hairy-data-vector-set (array index t) t (no-verify-arg-count)) (defknown hairy-data-vector-ref/check-bounds (array index) t (foldable no-verify-arg-count)) (defknown hairy-data-vector-set/check-bounds (array index t) t (no-verify-arg-count)) (defknown %caller-frame () t (flushable)) (defknown %caller-pc () system-area-pointer (flushable)) (defknown %with-array-data (array index (or index null)) (values (simple-array * (*)) index index index) (foldable flushable no-verify-arg-count)) (defknown %with-array-data/fp (array index (or index null)) (values (simple-array * (*)) index index index) (foldable flushable no-verify-arg-count)) (defknown %set-symbol-package (symbol t) t ()) (defknown (%coerce-callable-to-fun %coerce-callable-for-call) (function-designator) function (flushable)) (defknown array-bounding-indices-bad-error (t t t) nil) (defknown sequence-bounding-indices-bad-error (t t t) nil) (defknown %find-position (t sequence t index sequence-end (function (t)) (function (t t))) (values t (or index null)) (flushable call)) (defknown (%find-position-if %find-position-if-not) (function sequence t index sequence-end function) (values t (or index null)) (call no-verify-arg-count)) (defknown effective-find-position-test (function-designator function-designator) function (flushable foldable)) (defknown effective-find-position-key (function-designator) function (flushable foldable)) (defknown (%adjoin %adjoin-eq) (t list) list (flushable no-verify-arg-count)) (defknown (%member %member-eq %assoc %assoc-eq %rassoc %rassoc-eq) (t list) list (foldable flushable no-verify-arg-count)) (defknown (%adjoin-key %adjoin-key-eq) (t list (function (t))) list (flushable call no-verify-arg-count)) (defknown (%member-key %member-key-eq %assoc-key %assoc-key-eq %rassoc-key %rassoc-key-eq) (t list (function (t))) list (foldable flushable call no-verify-arg-count)) (defknown (%assoc-if %assoc-if-not %rassoc-if %rassoc-if-not %member-if %member-if-not) ((function (t)) list) list (foldable flushable call no-verify-arg-count)) (defknown (%assoc-if-key %assoc-if-not-key %rassoc-if-key %rassoc-if-not-key %member-if-key %member-if-not-key) ((function (t)) list (function (t))) list (foldable flushable call no-verify-arg-count)) (defknown (%adjoin-test %adjoin-test-not) (t list (function (t t))) list (flushable call no-verify-arg-count)) (defknown (%member-test %member-test-not %assoc-test %assoc-test-not %rassoc-test %rassoc-test-not) (t list (function (t t))) list (foldable flushable call no-verify-arg-count)) (defknown (%adjoin-key-test %adjoin-key-test-not) (t list (function (t)) (function (t t))) list (flushable call no-verify-arg-count)) (defknown (%member-key-test %member-key-test-not %assoc-key-test %assoc-key-test-not %rassoc-key-test %rassoc-key-test-not) (t list (function (t)) (function (t t))) list (foldable flushable call no-verify-arg-count)) (defknown %check-vector-sequence-bounds (vector index sequence-end) index (unwind)) SETF inverses (defknown (setf aref) (t (modifying array) &rest index) t () :call-type-deriver (lambda (call trusted) (array-call-type-deriver call trusted t))) (defknown %set-row-major-aref ((modifying array) index t) t () :call-type-deriver (lambda (call trusted) (array-call-type-deriver call trusted t t))) (defknown (%rplaca %rplacd) ((modifying cons) t) t () :derive-type #'result-type-last-arg) (defknown %put (symbol t t) t (no-verify-arg-count)) (defknown %setelt ((modifying sequence) index t) t () :derive-type #'result-type-last-arg) (defknown %svset ((modifying simple-vector) index t) t ()) (defknown (setf bit) (bit (modifying (array bit)) &rest index) bit ()) (defknown (setf sbit) (bit (modifying (simple-array bit)) &rest index) bit ()) (defknown %charset ((modifying string) index character) character ()) (defknown %scharset ((modifying simple-string) index character) character ()) (defknown %set-symbol-value (symbol t) t ()) (defknown (setf symbol-function) (function symbol) function ()) Does this really need a type deriver ? It 's inline , and returns its 1st arg , ;; i.e. we know exactly what object it returns, which is more precise than ;; just knowing the type. (defknown (setf symbol-plist) (list symbol) list () :derive-type #'result-type-first-arg) (defknown (setf documentation) ((or string null) t symbol) (or string null) ()) (defknown %setnth (unsigned-byte (modifying list) t) t () :derive-type #'result-type-last-arg) (defknown %set-fill-pointer ((modifying complex-vector) index) index () :derive-type #'result-type-last-arg) ALIEN and call - out - to - C stuff (defknown %alien-funcall ((or string system-area-pointer) alien-type &rest t) *) ;; Used by WITH-PINNED-OBJECTS (defknown sb-vm::touch-object (t) (values) (always-translatable)) (defknown sb-vm::touch-object-identity (t) t (always-translatable)) (defknown foreign-symbol-dataref-sap (simple-string) system-area-pointer (movable flushable)) (defknown foreign-symbol-sap (simple-string &optional boolean) system-area-pointer (movable flushable)) (defknown foreign-symbol-address (simple-string &optional boolean) (values integer boolean) (movable flushable)) ;;;; miscellaneous internal utilities (defknown %fun-name (function) t (flushable)) (defknown (setf %fun-name) (t function) t ()) (defknown policy-quality (policy symbol) policy-quality (flushable)) (defknown %program-error (&optional t &rest t) nil ()) (defknown compiler-error (t &rest t) nil ()) (defknown (compiler-warn compiler-style-warn) (t &rest t) (values) ()) (defknown (compiler-mumble note-lossage note-unwinnage) (string &rest t) (values) ()) (defknown (compiler-notify maybe-compiler-notify) ((or format-control symbol) &rest t) (values) ()) (defknown style-warn (t &rest t) null ()) ;;; The following defknowns are essentially a workaround for a deficiency in at least some versions of CCL which do not agree that NIL is legal here : ;;; * (declaim (ftype (function () nil) missing-arg)) ;;; * (defun call-it (a) (if a 'ok (missing-arg))) Compiler warnings : ;;; In CALL-IT: Conflicting type declarations for BUG ;;; ;;; Unfortunately it prints that noise at each call site. ;;; Using DEFKNOWN we can make the proclamation effective when ;;; running the cross-compiler but not when building it. Alternatively we could use PROCLAIM , except that that ;;; doesn't exist soon enough, and would need conditionals guarding ;;; it, which is sort of the very thing this is trying to avoid. (defknown missing-arg () nil (no-verify-arg-count)) (defknown give-up-ir1-transform (&rest t) nil) (defknown coerce-to-condition ((or condition symbol string function) type-specifier symbol &rest t) condition ()) (defknown coerce-symbol-to-fun (symbol) function (no-verify-arg-count)) (defknown sc-number-or-lose (symbol) sc-number (foldable)) (defknown set-info-value (t info-number t) t () :derive-type #'result-type-last-arg) ;;;; memory barriers (defknown sb-vm:%compiler-barrier () (values) ()) (defknown sb-vm:%memory-barrier () (values) ()) (defknown sb-vm:%read-barrier () (values) ()) (defknown sb-vm:%write-barrier () (values) ()) (defknown sb-vm:%data-dependency-barrier () (values) ()) #+sb-safepoint ;;; Note: This known function does not have an out-of-line definition; ;;; and if such a definition were needed, it would not need to "call" ;;; itself inline, but could be a no-op, because the compiler inserts a use of the VOP in the function prologue anyway . (defknown sb-kernel::gc-safepoint () (values) ()) ;;;; atomic ops the CAS functions are transformed to something else rather than " translated " . ;;; either way, they should not be called. (defknown (cas svref) (t t simple-vector index) t (always-translatable)) (defknown (cas symbol-value) (t t symbol) t (always-translatable)) (defknown %compare-and-swap-svref (simple-vector index t t) t ()) (defknown (%compare-and-swap-symbol-value #+x86-64 %cas-symbol-global-value) (symbol t t) t (unwind)) (defknown (%atomic-dec-symbol-global-value %atomic-inc-symbol-global-value) (symbol fixnum) fixnum) (defknown (%atomic-dec-car %atomic-inc-car %atomic-dec-cdr %atomic-inc-cdr) (cons fixnum) fixnum) (defknown spin-loop-hint () (values) (always-translatable)) ;;;; Stream methods ;;; Avoid a ton of FBOUNDP checks in the string stream constructors etc, ;;; by wiring in the needed functions instead of dereferencing their fdefns. (defknown (ill-in ill-bin ill-out ill-bout sb-impl::string-in-misc sb-impl::string-sout sb-impl::finite-base-string-ouch sb-impl::finite-base-string-out-misc sb-impl::fill-pointer-ouch sb-impl::fill-pointer-sout sb-impl::fill-pointer-misc sb-impl::case-frob-upcase-out sb-impl::case-frob-upcase-sout sb-impl::case-frob-downcase-out sb-impl::case-frob-downcase-sout sb-impl::case-frob-capitalize-out sb-impl::case-frob-capitalize-sout sb-impl::case-frob-capitalize-first-out sb-impl::case-frob-capitalize-first-sout sb-impl::case-frob-capitalize-aux-out sb-impl::case-frob-capitalize-aux-sout sb-impl::case-frob-misc sb-pretty::pretty-out sb-pretty::pretty-misc) * *) (defknown sb-pretty::pretty-sout * * (recursive)) PCL (defknown sb-pcl::pcl-instance-p (t) boolean (movable foldable flushable)) ;; FIXME: should T be be (OR INSTANCE FUNCALLABLE-INSTANCE) etc? (defknown (slot-value slot-makunbound) (t symbol) t (any)) (defknown (slot-boundp slot-exists-p) (t symbol) boolean) (defknown sb-pcl::set-slot-value (t symbol t) t (any)) (defknown find-class (symbol &optional t lexenv-designator) (or class null) ()) (defknown class-of (t) class (flushable)) (defknown class-name (class) symbol (flushable)) (defknown finalize (t (function-designator () *) &key (:dont-save t)) *) (defknown (sb-impl::%with-standard-io-syntax sb-impl::%with-rebound-io-syntax sb-impl::call-with-sane-io-syntax) (function) *) (defknown sb-debug::funcall-with-debug-io-syntax (function &rest t) *) (defknown sb-impl::%print-unreadable-object (t t t &optional function) null) #+sb-thread (progn (defknown (sb-thread::call-with-mutex sb-thread::call-with-recursive-lock) (function t t t) *) (defknown (sb-thread::call-with-system-mutex sb-thread::call-with-system-mutex/allow-with-interrupts sb-thread::call-with-system-mutex/without-gcing sb-thread::call-with-recursive-system-lock) (function t) *)) #+round-float (progn (defknown round-double (double-float #1=(member :round :floor :ceiling :truncate)) double-float (foldable flushable movable always-translatable)) (defknown round-single (single-float #1#) single-float (foldable flushable movable always-translatable))) (defknown fixnum* (fixnum fixnum t) fixnum (movable always-translatable)) (defknown (signed* signed+ signed-) (sb-vm:signed-word sb-vm:signed-word t) sb-vm:signed-word (movable always-translatable)) (defknown (unsigned* unsigned+ unsigned-) (word word t) word (movable always-translatable)) (defknown (unsigned+signed unsigned-signed) (word sb-vm:signed-word t) integer (movable always-translatable)) (defknown (signed-unsigned) (sb-vm:signed-word word t) integer (movable always-translatable))
null
https://raw.githubusercontent.com/sbcl/sbcl/6bb4483ae43d485f0a09eb354dd4e03fe5ac7eae/src/compiler/fndb.lisp
lisp
This file defines all the standard functions to be known functions. Each function has type and side-effect information, and may also have IR1 optimizers. 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. information for known functions: Note: This is not FLUSHABLE because it's defined to signal errors. These each check their input sequence for type-correctness, but not the output type specifier, because MAKE-SEQUENCE will do that. Anyway, the TYPE-SPECIFIER type is more inclusive than the actual possible return values. Most of the time it will be (OR LIST SYMBOL). CLASS can be returned only when you've got an object whose class-name does not properly name its class. from the "Predicates" chapter: and cross-compilation host? After all, some type relationships (e.g. an error before the type declaration (because of undefined type). E.g. you can do but the analogous (UPGRADED-ARRAY-ELEMENT-TYPE and UPGRADED-COMPLEX-PART-TYPE have definitions. FIXME: Is it OK to fold this when the types have already been classes This is not FLUSHABLE, since it's required to signal an error if unbound. From CLHS, "If the symbol is globally defined as a macro or a special operator, an object of implementation-dependent nature and identity is returned. If the symbol is not globally defined as either a macro or a special operator, and if the symbol is fbound, a function object is returned". Our objects of implementation-dependent nature happen to be functions. The set of special operators never changes. According to CLHS the result must be a LIST, but we do not check it. We let VALUES-LIST be foldable, since constant-folding will turn it into VALUES. VALUES is not foldable, since MV constants are represented by a call to VALUES. from the "Symbols" chapter: %make-symbol is the internal API, but the primitive object allocator is %%make-symbol, because when immobile space feature is present, we dispatch to either the C allocator or the Lisp allocator. doesn't check the type. semi-foldable, see src/compiler/typetran from the "Packages" chapter: not flushable private from the "Numbers" chapter: do not truncate into a bignum, and the functions do not check their input values and produce corrupted memory. they can't survive cold-init This says "unsafely flushable" as if to imply that there is a possibility of signaling a condition in safe code, but in practice we can never trap performing a floating-point comparison. I think that is done on purpose, so at best the "unsafely-" is disingenuous, and at worst our code is wrong. hard to come up with useful ways to do this, but it is possible to come up with *legal* ways to do this, so it would be nice to fix this so we comply with the spec. from the "Characters" chapter: then the N-argument form should not type-check anything generated by the compiler, and successive args checked by hand. The case-insensitive functions don't need any checks, since the underlying By suppressing constant folding on CODE-CHAR when the cross-compiler is running in the cross-compilation host vanilla ANSI Common Lisp, we can use CODE-CHAR expressions to delay until target Lisp run time the generation of CHARACTERs which aren't STANDARD-CHARACTERs. That way, we don't need to rely on the host Common Lisp being able to handle any characters other than those from the "Sequences" chapter: returns the result from the predicate... or a keyword indicating a certain behavior to compute the word. In either case the supplied count is lispwords, not elements. This might be a no-op depending on whether memory is prezeroized. Correct argument type restrictions for these functions are complicated, so we just declare them to accept LISTs and suppress flushing in safe code. The length constraint on MAKE-LIST is such that: - not every byte of addressable memory can be used up. - the number of bytes to allocate should be a fixnum - type-checking can use use efficient bit-masking approach All but last must be of type LIST, but there seems to be no way to express that in this syntax. To avoid emitting code to test for nil-function-returned from the "Arrays" chapter of the possibility of source-transforming it for various recognized contents after the source-transform for MAKE-ARRAY has run. The original MAKE-ARRAY call might resemble either of: (MAKE-ARRAY DIMS :ELEMENT-TYPE (F) :INITIAL-CONTENTS (G)) (MAKE-ARRAY DIMS :INITIAL-CONTENTS (F) :ELEMENT-TYPE (G)) and in general we must bind temporaries to preserve left-to-right evaluation of F and G if they have side effects. Now ideally :ELEMENT-TYPE will be a constant, so it doesn't matter then the multi-dimensional array creation form would look like (FILL-ARRAY (allocate-array) initial-contents) which would mean that if the user expressed the MAKE- call the to ensure its evaluation before the allocation, causing difficulty if doing any futher macro-like processing. FIXME: there's a fencepost bug, but for all practical purposes our ARRAY-RANK-LIMIT is infinite, thus masking the bug. e.g. if the FIXME: MODIFYING for these is complicated. :derive-type #'result-type-last-arg :derive-type #'result-type-last-arg FIXME: complicated MODIFYING This is a special case in CHECK-IMPORTANT-RESULT because it is not necessary to use the result if the array is adjustable. :derive-type 'result-type-arg1) Not even close... from the "Strings" chapter: internal non-keyword versions of string predicates: from the "Streams" chapter: - if you don't initialize the stream, then GET-OUTPUT-STRING-STREAM will crash can it return a CLASS? from the "Input/Output" chapter: (The I/O functions are given effects ANY under the theory that code motion over I/O operations is particularly confusing and not very important for efficiency.) FIXME: (function-designator ...) causes a style warning in the :UNICODE-DISPATCH-MACROS may return any type due to eof-value... and because READ generally returns anything. FIXME: add a type-deriver => (values (or string eof-value) boolean) xxx-TO-STRING functions are not foldable because they depend on the dynamic environment, the state of the pretty printer dispatch table, and probably other run-time factors. FIXME: complicated MODIFYING host when parsing a namestring. They are not FLUSHABLE because parsing of a PATHNAME-DESIGNATOR might signal an error.) never returns from the "Miscellaneous" Chapter: extensions Even though ANSI defines LISP-IMPLEMENTATION-TYPE and know that there's no valid reason for our implementations to ever do so, so we can safely guarantee that they'll return strings. For any of these functions, meaningful information might not be available, so -- unlike the related LISP-IMPLEMENTATION-FOO miscellaneous extensions magical compiler frobs We can't fold this in general because of SATISFIES. There is a special optimizer anyway. We should never emit a call to %typep-wrapper An identity wrapper to avoid complaints about constant modification This is MV-called. %compile-time-type-error does not return, but due to the implementation of FILTER-LVAR we cannot write it here. The lowest-level vector SET operators should not return a value. Functions built upon them may return the input value. i.e. we know exactly what object it returns, which is more precise than just knowing the type. Used by WITH-PINNED-OBJECTS miscellaneous internal utilities The following defknowns are essentially a workaround for a deficiency in * (declaim (ftype (function () nil) missing-arg)) * (defun call-it (a) (if a 'ok (missing-arg))) In CALL-IT: Conflicting type declarations for BUG Unfortunately it prints that noise at each call site. Using DEFKNOWN we can make the proclamation effective when running the cross-compiler but not when building it. doesn't exist soon enough, and would need conditionals guarding it, which is sort of the very thing this is trying to avoid. memory barriers Note: This known function does not have an out-of-line definition; and if such a definition were needed, it would not need to "call" itself inline, but could be a no-op, because the compiler inserts a atomic ops either way, they should not be called. Stream methods Avoid a ton of FBOUNDP checks in the string stream constructors etc, by wiring in the needed functions instead of dereferencing their fdefns. FIXME: should T be be (OR INSTANCE FUNCALLABLE-INSTANCE) etc?
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-C") (defknown coerce (t type-specifier) t (movable) : DERIVE - TYPE RESULT - TYPE - SPEC - NTH - ARG 1 ? Nope ... ( COERCE 1 ' COMPLEX ) returns REAL / INTEGER , not COMPLEX . ) (defknown list-to-vector* (list type-specifier) vector (no-verify-arg-count)) (defknown vector-to-vector* (vector type-specifier) vector (no-verify-arg-count)) FIXME : Is this really FOLDABLE ? A counterexample seems to be : ( LET ( ( S : S ) ) ( VALUES ( TYPE - OF S ) ( UNINTERN S ' KEYWORD ) ( TYPE - OF S ) S ) ) (defknown type-of (t) (or list symbol class) (foldable flushable)) These can be affected by type definitions , so they 're not FOLDABLE . (defknown (upgraded-complex-part-type upgraded-array-element-type) (type-specifier &optional lexenv-designator) (or list symbol) (unsafely-flushable)) perhaps SPECIAL - OPERATOR - P and others ) be FOLDABLE in the ) might be different between host and target . Perhaps this property should be protected by # -SB - XC - HOST ? Perhaps we need 3 - stage bootstrapping after all ? ( Ugh ! It 's * so * slow already ! ) (defknown typep (t type-specifier &optional lexenv-designator) boolean Unlike SUBTYPEP or UPGRADED - ARRAY - ELEMENT - TYPE and friends , this seems to be FOLDABLE . Like SUBTYPEP , it 's affected by type definitions , but unlike SUBTYPEP , there should be no way to make a TYPEP expression with constant arguments which does n't return ( SUBTYPEP ' INTEGER ' FOO ) = > NIL , NIL ( DEFTYPE FOO ( ) T ) ( SUBTYPEP ' INTEGER ' FOO ) = > T , T ( TYPEP 12 ' FOO ) ( DEFTYPE FOO ( ) T ) ( TYPEP 12 ' FOO ) does n't work because the first call is an error . behavior like SUBTYPEP in this respect , not like TYPEP . ) (foldable)) (defknown subtypep (type-specifier type-specifier &optional lexenv-designator) (values boolean boolean) This is not FOLDABLE because its value is affected by type defined ? Does the code inherited from CMU CL already do this ? (unsafely-flushable)) (defknown (null symbolp atom consp listp numberp integerp rationalp floatp complexp characterp stringp bit-vector-p vectorp simple-vector-p simple-string-p simple-bit-vector-p arrayp packagep functionp compiled-function-p not) (t) boolean (movable foldable flushable)) (defknown (eq eql %eql/integer) (t t) boolean (movable foldable flushable commutative)) (defknown (equal equalp) (t t) boolean (foldable flushable recursive)) #+(or x86 x86-64 arm arm64) (defknown fixnum-mod-p (t fixnum) boolean (movable flushable always-translatable)) FIXME : disagrees w/ LEGAL - CLASS - NAME - P (defknown find-classoid (name-for-class &optional t) (or classoid null) ()) (defknown classoid-of (t) classoid (flushable)) (defknown wrapper-of (t) wrapper (flushable)) (defknown wrapper-depthoid (wrapper) layout-depthoid (flushable)) #+64-bit (defknown layout-depthoid (sb-vm:layout) layout-depthoid (flushable always-translatable)) #+(or x86 x86-64) (defknown (layout-depthoid-ge) (sb-vm:layout integer) boolean (flushable)) (defknown %structure-is-a (instance t) boolean (foldable flushable)) (defknown structure-typep (t t) boolean (foldable flushable)) (defknown classoid-cell-typep (t t) boolean (foldable flushable no-verify-arg-count)) (defknown copy-structure (structure-object) structure-object (flushable) :derive-type #'result-type-first-arg) from the " Control Structure " chapter : (defknown symbol-value (symbol) t () :derive-type #'symbol-value-derive-type) (defknown about-to-modify-symbol-value (symbol t &optional t t) null ()) (defknown (symbol-function) (symbol) function (unsafely-flushable)) (defknown boundp (symbol) boolean (flushable)) (defknown fboundp ((or symbol cons)) (or null function) (unsafely-flushable)) (defknown special-operator-p (symbol) t (movable foldable flushable)) (defknown set (symbol t) t () :derive-type #'result-type-last-arg) (defknown fdefinition ((or symbol cons)) function ()) (defknown ((setf fdefinition)) (function (or symbol cons)) function () :derive-type #'result-type-first-arg) (defknown makunbound (symbol) symbol () :derive-type #'result-type-first-arg) (defknown fmakunbound ((or symbol cons)) (or symbol cons) () :derive-type #'result-type-first-arg) # # # Last arg must be List ... (defknown funcall (function-designator &rest t) *) (defknown (mapcar maplist) (function-designator list &rest list) list (call)) (defknown (mapcan mapcon) (function-designator list &rest list) t (call)) (defknown (mapc mapl) (function-designator list &rest list) list (foldable call)) (defknown values (&rest t) * (movable flushable)) (defknown values-list (list) * (movable foldable unsafely-flushable)) from the " Macros " chapter : (defknown macro-function (symbol &optional lexenv-designator) (or function null) (flushable)) (defknown (macroexpand macroexpand-1 %macroexpand %macroexpand-1) (t &optional lexenv-designator) (values form &optional boolean)) (defknown compiler-macro-function (t &optional lexenv-designator) (or function null) (flushable)) from the " Declarations " chapter : (defknown proclaim (list) (values) (recursive)) (defknown get (symbol t &optional t) t (flushable)) (defknown sb-impl::get3 (symbol t t) t (flushable no-verify-arg-count)) (defknown remprop (symbol t) t) (defknown symbol-plist (symbol) list (flushable)) (defknown getf (list t &optional t) t (foldable flushable)) (defknown get-properties (list list) (values t t list) (foldable flushable)) (defknown symbol-name (symbol) simple-string (movable foldable flushable)) (defknown make-symbol (string) symbol (flushable)) (defknown %make-symbol (fixnum simple-string) symbol (flushable)) (defknown sb-vm::%%make-symbol (simple-string) symbol (flushable)) (defknown copy-symbol (symbol &optional t) symbol (flushable)) (defknown gensym (&optional (or string unsigned-byte)) symbol ()) (defknown symbol-package (symbol) (or package null) (flushable)) (defknown gentemp (&optional string package-designator) symbol) (defknown make-package (string-designator &key (:use list) (:nicknames list) # # # extensions ... (:internal-symbols index) (:external-symbols index)) package) (defknown find-package (package-designator) (or package null) (flushable)) (defknown find-undeleted-package-or-lose (package-designator) (defknown package-name (package-designator) (or simple-string null) (unsafely-flushable)) (defknown package-nicknames (package-designator) list (unsafely-flushable)) (defknown rename-package (package-designator package-designator &optional list) package) (defknown package-use-list (package-designator) list (unsafely-flushable)) (defknown package-used-by-list (package-designator) list (unsafely-flushable)) (defknown package-shadowing-symbols (package-designator) list (unsafely-flushable)) (defknown list-all-packages () list (flushable)) (defknown intern (string &optional package-designator) (values symbol (member :internal :external :inherited nil)) ()) (defknown find-symbol (string &optional package-designator) (values symbol (member :internal :external :inherited nil)) (flushable)) (defknown (export import) (symbols-designator &optional package-designator) (eql t)) (defknown unintern (symbol &optional package-designator) boolean) (defknown unexport (symbols-designator &optional package-designator) (eql t)) (defknown shadowing-import (symbols-designator &optional package-designator) (eql t)) (defknown shadow ((or symbol character string list) &optional package-designator) (eql t)) (defknown (use-package unuse-package) ((or list package-designator) &optional package-designator) (eql t)) (defknown find-all-symbols (string-designator) list (flushable)) (defknown package-iter-step (fixnum index simple-vector list) (values fixnum index simple-vector list symbol symbol)) (defknown zerop (number) boolean (movable foldable flushable)) (defknown (plusp minusp) (real) boolean (movable foldable flushable)) (defknown (oddp evenp) (integer) boolean (movable foldable flushable)) (defknown (=) (number &rest number) boolean (movable foldable flushable commutative)) (defknown (/=) (number &rest number) boolean (movable foldable flushable)) (defknown (< > <= >=) (real &rest real) boolean (movable foldable flushable)) (defknown (max min) (real &rest real) real (movable foldable flushable)) (defknown (+ *) (&rest number) number (movable foldable flushable commutative)) (defknown - (number &rest number) number (movable foldable flushable)) (defknown / (number &rest number) number (movable foldable unsafely-flushable)) (defknown (1+ 1-) (number) number (movable foldable flushable)) (defknown (two-arg-* two-arg-+ two-arg-- two-arg-/) (number number) number (no-verify-arg-count)) (defknown sb-kernel::integer-/-integer (integer integer) rational (no-verify-arg-count unsafely-flushable)) (defknown (two-arg-< two-arg-= two-arg-> two-arg-<= two-arg->=) (number number) boolean (no-verify-arg-count)) (defknown (range< range<= range<<= range<=<) (fixnum real fixnum) boolean (foldable flushable movable no-verify-arg-count)) (defknown (two-arg-gcd two-arg-lcm two-arg-and two-arg-ior two-arg-xor two-arg-eqv) (integer integer) integer (no-verify-arg-count)) (defknown conjugate (number) number (movable foldable flushable)) (defknown gcd (&rest integer) unsigned-byte (movable foldable flushable)) (defknown sb-kernel::fixnum-gcd (fixnum fixnum) (integer 0 #.(1+ most-positive-fixnum)) (movable foldable flushable no-verify-arg-count)) (defknown lcm (&rest integer) unsigned-byte (movable foldable flushable)) (defknown exp (number) irrational (movable foldable flushable recursive)) (defknown expt (number number) number (movable foldable flushable recursive)) (defknown log (number &optional real) irrational (movable foldable flushable recursive)) (defknown sqrt (number) irrational (movable foldable flushable)) (defknown isqrt (unsigned-byte) unsigned-byte (movable foldable flushable recursive)) (defknown (abs phase signum) (number) number (movable foldable flushable)) (defknown cis (real) (complex float) (movable foldable flushable)) (defknown (sin cos) (number) (or (float $-1.0 $1.0) (complex float)) (movable foldable flushable recursive)) (defknown atan (number &optional real) irrational (movable foldable unsafely-flushable recursive)) (defknown (tan sinh cosh tanh asinh) (number) irrational (movable foldable flushable recursive)) (defknown (asin acos acosh atanh) (number) irrational (movable foldable flushable recursive)) (defknown float (real &optional float) float (movable foldable flushable)) (defknown (rational) (real) rational (movable foldable flushable)) (defknown (rationalize) (real) rational (movable foldable flushable recursive)) (defknown numerator (rational) integer (movable foldable flushable)) (defknown denominator (rational) (integer 1) (movable foldable flushable)) (defknown (floor ceiling round) (real &optional real) (values integer real) (movable foldable flushable)) (defknown truncate (real &optional real) (values integer real) (movable foldable flushable recursive)) (defknown unary-truncate (real) (values integer real) (movable foldable flushable no-verify-arg-count)) : Do n't fold these , the compiler may call it on floats that (defknown unary-truncate-single-float-to-bignum (single-float) (values bignum (eql $0f0)) (#+(or) foldable movable flushable fixed-args)) (defknown unary-truncate-double-float-to-bignum (double-float) (values #+64-bit bignum #-64-bit integer (and #+(and 64-bit (eql $0d0) double-float)) (#+(or) foldable movable flushable fixed-args)) (defknown %unary-truncate-single-float-to-bignum (single-float) bignum (#+(or) foldable movable flushable fixed-args)) (defknown %unary-truncate-double-float-to-bignum (double-float) bignum (#+(or) foldable movable flushable fixed-args)) (defknown (subtract-bignum add-bignums) (bignum bignum) integer (movable flushable no-verify-arg-count)) (defknown (add-bignum-fixnum subtract-bignum-fixnum) (bignum fixnum) integer (movable flushable no-verify-arg-count)) (defknown subtract-fixnum-bignum (fixnum bignum) integer (movable flushable no-verify-arg-count)) (defknown sxhash-bignum-double-float (double-float) hash-code (foldable movable flushable fixed-args)) (defknown sxhash-bignum-single-float (single-float) hash-code (foldable movable flushable fixed-args)) (defknown %multiply-high (word word) word (movable foldable flushable)) (defknown multiply-fixnums (fixnum fixnum) integer (movable foldable flushable no-verify-arg-count)) (defknown %signed-multiply-high (sb-vm:signed-word sb-vm:signed-word) sb-vm:signed-word (movable foldable flushable)) (defknown (mod rem) (real real) real (movable foldable flushable)) (defknown (ffloor fceiling fround ftruncate) (real &optional real) (values float real) (movable foldable flushable)) (defknown decode-float (float) (values float float-exponent float) (movable foldable unsafely-flushable)) (defknown scale-float (float integer) float (movable foldable unsafely-flushable)) (defknown float-radix (float) float-radix (movable foldable unsafely-flushable)) on a NaN because the implementation uses foo - FLOAT - BITS instead of e.g. the behavior if the first arg is a NaN is well - defined as we have it , but what about the second arg ? We need some test cases around this . (defknown float-sign (float &optional float) float (movable foldable unsafely-flushable) :derive-type (lambda (call &aux (args (combination-args call)) (type (unless (cdr args) (lvar-type (first args))))) (cond ((and type (csubtypep type (specifier-type 'single-float))) (specifier-type '(member $1f0 $-1f0))) ((and type (csubtypep type (specifier-type 'double-float))) (specifier-type '(member $1d0 $-1d0))) (type (specifier-type '(member $1f0 $-1f0 $1d0 $-1d0))) (t (specifier-type 'float))))) (defknown (float-digits float-precision) (float) float-digits (movable foldable unsafely-flushable)) (defknown integer-decode-float (float) (values integer float-int-exponent (member -1 1)) (movable foldable unsafely-flushable)) (defknown single-float-sign (single-float) single-float (movable foldable flushable)) (defknown single-float-copysign (single-float single-float) single-float (movable foldable flushable)) (defknown complex (real &optional real) number (movable foldable flushable)) (defknown (realpart imagpart) (number) real (movable foldable flushable)) (defknown (logior logxor logand logeqv) (&rest integer) integer (movable foldable flushable commutative)) (defknown (lognand lognor logandc1 logandc2 logorc1 logorc2) (integer integer) integer (movable foldable flushable)) (defknown boole (boole-code integer integer) integer (movable foldable flushable)) (defknown lognot (integer) integer (movable foldable flushable)) (defknown logtest (integer integer) boolean (movable foldable flushable commutative)) (defknown logbitp (unsigned-byte integer) boolean (movable foldable flushable)) (defknown ash (integer integer) integer (movable foldable flushable)) (defknown %ash/right ((or word sb-vm:signed-word) (mod #.sb-vm:n-word-bits)) (or word sb-vm:signed-word) (movable foldable flushable always-translatable)) (defknown (logcount integer-length) (integer) bit-index (movable foldable flushable)) FIXME : According to the ANSI spec , it 's legal to use any nonnegative indices for BYTE arguments , not just BIT - INDEX . It 's (defknown byte (bit-index bit-index) byte-specifier (movable foldable flushable)) (defknown (byte-size byte-position) (byte-specifier) bit-index (movable foldable flushable)) (defknown ldb (byte-specifier integer) unsigned-byte (movable foldable flushable)) (defknown ldb-test (byte-specifier integer) boolean (movable foldable flushable)) (defknown mask-field (byte-specifier integer) unsigned-byte (movable foldable flushable)) (defknown dpb (integer byte-specifier integer) integer (movable foldable flushable)) (defknown deposit-field (integer byte-specifier integer) integer (movable foldable flushable)) (defknown random ((or (float ($0.0f0)) (integer 1)) &optional random-state) (or (float $0.0f0) (integer 0)) ()) (defknown make-random-state (&optional (or random-state (member nil t))) random-state (flushable)) SBCL extension (or (member nil t) random-state unsigned-byte (simple-array (unsigned-byte 8) (*)) (simple-array (unsigned-byte 32) (*)))) random-state (flushable)) (defknown random-state-p (t) boolean (movable foldable flushable)) (defknown (standard-char-p graphic-char-p alpha-char-p upper-case-p lower-case-p both-case-p alphanumericp) (character) boolean (movable foldable flushable)) (defknown digit-char-p (character &optional (integer 2 36)) (or (integer 0 35) null) (movable foldable flushable)) Character predicates : if the 2 - argument predicate which underlies the N - argument predicate unavoidably type - checks its 2 args , except in the degenerate case of 1 actual argument . All of the case - sensitive functions have the check of the first arg two - arg case - insensitive function does it , except when it is n't called . (defknown (char=) (character &rest character) boolean (movable foldable flushable commutative)) (defknown (char/= char< char> char<= char>= char-not-equal) (character &rest character) boolean (movable foldable flushable)) (defknown (char-equal char-lessp char-greaterp char-not-greaterp char-not-lessp) (character &rest character) boolean (movable foldable flushable)) (defknown (two-arg-char-equal) (character character) boolean (movable foldable flushable commutative no-verify-arg-count)) (defknown (two-arg-char-not-equal two-arg-char-lessp two-arg-char-not-lessp two-arg-char-greaterp two-arg-char-not-greaterp) (character character) boolean (movable foldable flushable no-verify-arg-count)) (defknown character (t) character (movable foldable unsafely-flushable)) (defknown char-code (character) char-code (movable foldable flushable)) (defknown (char-upcase char-downcase) (character) character (movable foldable flushable)) (defknown digit-char (unsigned-byte &optional (integer 2 36)) (or character null) (movable foldable flushable)) (defknown char-int (character) char-code (movable foldable flushable)) (defknown char-name (character) (or simple-string null) (movable foldable flushable)) (defknown name-char (string-designator) (or character null) (movable foldable flushable)) (defknown code-char (char-code) character guaranteed by the ANSI spec . (movable #-sb-xc-host foldable flushable)) (defknown elt (proper-sequence index) t (foldable unsafely-flushable)) (defknown subseq (proper-sequence index &optional sequence-end) consed-sequence (flushable)) (defknown copy-seq (proper-sequence) consed-sequence (flushable) :derive-type (sequence-result-nth-arg 0 :preserve-dimensions t)) (defknown length (proper-sequence) index (foldable flushable dx-safe)) (defknown reverse (proper-sequence) consed-sequence (flushable) :derive-type (sequence-result-nth-arg 0 :preserve-dimensions t)) (defknown nreverse ((modifying sequence)) sequence (important-result) :derive-type (sequence-result-nth-arg 0 :preserve-dimensions t :preserve-vector-type t)) (defknown make-sequence (type-specifier index &key (:initial-element t)) consed-sequence (movable) :derive-type (creation-result-type-specifier-nth-arg 0)) (defknown concatenate (type-specifier &rest proper-sequence) consed-sequence () :derive-type (creation-result-type-specifier-nth-arg 0)) (defknown %concatenate-to-string (&rest sequence) simple-string (flushable no-verify-arg-count)) (defknown %concatenate-to-base-string (&rest sequence) simple-base-string (flushable no-verify-arg-count)) (defknown %concatenate-to-list (&rest sequence) list (flushable no-verify-arg-count)) (defknown %concatenate-to-simple-vector (&rest sequence) simple-vector (flushable no-verify-arg-count)) (defknown %concatenate-to-vector ((unsigned-byte #.sb-vm:n-widetag-bits) &rest sequence) vector (flushable no-verify-arg-count)) (defknown map (type-specifier (function-designator ((nth-arg 2 :sequence t) (rest-args :sequence t)) (nth-arg 0 :sequence-type t)) proper-sequence &rest proper-sequence) consed-sequence (call)) (defknown %map (type-specifier function-designator &rest sequence) consed-sequence (call no-verify-arg-count)) (defknown %map-for-effect-arity-1 (function-designator sequence) null (call no-verify-arg-count)) (defknown %map-to-list-arity-1 ((function-designator ((nth-arg 1 :sequence t))) sequence) list (flushable call no-verify-arg-count)) (defknown %map-to-simple-vector-arity-1 ((function-designator ((nth-arg 1 :sequence t))) sequence) simple-vector (flushable call no-verify-arg-count)) (defknown map-into ((modifying sequence) (function-designator ((rest-args :sequence t)) (nth-arg 0 :sequence t)) &rest proper-sequence) sequence (call) :derive-type (sequence-result-nth-arg 0 :preserve-dimensions t :preserve-vector-type t)) (defknown #.(loop for info across sb-vm:*specialized-array-element-type-properties* collect (intern (concatenate 'string "VECTOR-MAP-INTO/" (string (sb-vm:saetp-primitive-type-name info))) :sb-impl)) (simple-array index index function list) index (call no-verify-arg-count)) (defknown some (function-designator proper-sequence &rest proper-sequence) t (foldable unsafely-flushable call)) (defknown (every notany notevery) (function-designator proper-sequence &rest proper-sequence) boolean (foldable unsafely-flushable call)) (defknown reduce ((function-designator ((nth-arg 1 :sequence t :key :key :value :initial-value) (nth-arg 1 :sequence t :key :key))) proper-sequence &rest t &key (:from-end t) (:start (inhibit-flushing index 0)) (:end (inhibit-flushing sequence-end nil)) (:initial-value t) (:key (function-designator ((nth-arg 1 :sequence t))))) t (foldable flushable call)) (defknown fill ((modifying sequence) t &rest t &key (:start index) (:end sequence-end)) sequence () :derive-type (sequence-result-nth-arg 0 :preserve-dimensions t :preserve-vector-type t) :result-arg 0) Like FILL but with no keyword argument parsing (defknown quickfill ((modifying (simple-array * 1)) t) (simple-array * 1) () :derive-type #'result-type-first-arg :result-arg 0) Special case of FILL that takes either a machine word with which to fill , (defknown sb-vm::splat ((modifying (simple-array * 1)) index (or symbol sb-vm:word)) (simple-array * 1) (always-translatable) :derive-type #'result-type-first-arg :result-arg 0) (defknown replace ((modifying sequence) proper-sequence &rest t &key (:start1 index) (:end1 sequence-end) (:start2 index) (:end2 sequence-end)) sequence () :derive-type (sequence-result-nth-arg 0 :preserve-dimensions t :preserve-vector-type t) :result-arg 0) (defknown remove (t proper-sequence &rest t &key (:from-end t) (:test (function-designator ((nth-arg 0) (nth-arg 1 :sequence t :key :key)))) (:test-not (function-designator ((nth-arg 0) (nth-arg 1 :sequence t :key :key)))) (:start (inhibit-flushing index 0)) (:end (inhibit-flushing sequence-end nil)) (:count sequence-count) (:key (function-designator ((nth-arg 1 :sequence t))))) consed-sequence (flushable call) :derive-type (sequence-result-nth-arg 1)) (defknown substitute (t t proper-sequence &rest t &key (:from-end t) (:test (function-designator ((nth-arg 1) (nth-arg 2 :sequence t :key :key)))) (:test-not (function-designator ((nth-arg 1) (nth-arg 2 :sequence t :key :key)))) (:start (inhibit-flushing index 0)) (:end (inhibit-flushing sequence-end nil)) (:count sequence-count) (:key (function-designator ((nth-arg 2 :sequence t))))) consed-sequence (flushable call) :derive-type (sequence-result-nth-arg 2)) (defknown (remove-if remove-if-not) ((function-designator ((nth-arg 1 :sequence t :key :key))) proper-sequence &rest t &key (:from-end t) (:count sequence-count) (:start (inhibit-flushing index 0)) (:end (inhibit-flushing sequence-end nil)) (:key (function-designator ((nth-arg 1 :sequence t))))) consed-sequence (flushable call) :derive-type (sequence-result-nth-arg 1)) (defknown (substitute-if substitute-if-not) (t (function-designator ((nth-arg 2 :sequence t :key :key))) proper-sequence &rest t &key (:from-end t) (:start (inhibit-flushing index 0)) (:end (inhibit-flushing sequence-end nil)) (:count sequence-count) (:key (function-designator ((nth-arg 2 :sequence t))))) consed-sequence (flushable call) :derive-type (sequence-result-nth-arg 2)) (defknown delete (t (modifying sequence) &rest t &key (:from-end t) (:test (function-designator ((nth-arg 0) (nth-arg 1 :sequence t :key :key)))) (:test-not (function-designator ((nth-arg 0) (nth-arg 1 :sequence t :key :key)))) (:start index) (:end sequence-end) (:count sequence-count) (:key (function-designator ((nth-arg 1 :sequence t))))) sequence (call important-result) :derive-type (sequence-result-nth-arg 1)) (defknown nsubstitute (t t (modifying sequence) &rest t &key (:from-end t) (:test (function-designator ((nth-arg 1) (nth-arg 2 :sequence t :key :key)))) (:test-not (function-designator ((nth-arg 1) (nth-arg 2 :sequence t :key :key)))) (:start index) (:end sequence-end) (:count sequence-count) (:key (function-designator ((nth-arg 2 :sequence t))))) sequence (call) :derive-type (sequence-result-nth-arg 2)) (defknown (delete-if delete-if-not) ((function-designator ((nth-arg 1 :sequence t :key :key))) (modifying sequence) &rest t &key (:from-end t) (:start index) (:end sequence-end) (:count sequence-count) (:key (function-designator ((nth-arg 1 :sequence t))))) sequence (call important-result) :derive-type (sequence-result-nth-arg 1)) (defknown (nsubstitute-if nsubstitute-if-not) (t (function-designator ((nth-arg 2 :sequence t :key :key))) (modifying sequence) &rest t &key (:from-end t) (:start index) (:end sequence-end) (:count sequence-count) (:key (function-designator ((nth-arg 2 :sequence t))))) sequence (call) :derive-type (sequence-result-nth-arg 2)) (defknown remove-duplicates (proper-sequence &rest t &key (:test (function-designator ((nth-arg 0 :sequence t :key :key) (nth-arg 0 :sequence t :key :key)))) (:test-not (function-designator ((nth-arg 0 :sequence t :key :key) (nth-arg 0 :sequence t :key :key)))) (:start (inhibit-flushing index 0)) (:end (inhibit-flushing sequence-end nil)) (:from-end t) (:key (function-designator ((nth-arg 0 :sequence t))))) consed-sequence (flushable call) :derive-type (sequence-result-nth-arg 0)) (defknown delete-duplicates ((modifying sequence) &rest t &key (:test (function-designator ((nth-arg 0 :sequence t :key :key) (nth-arg 0 :sequence t :key :key)))) (:test-not (function-designator ((nth-arg 0 :sequence t :key :key) (nth-arg 0 :sequence t :key :key)))) (:start index) (:from-end t) (:end sequence-end) (:key (function-designator ((nth-arg 0 :sequence t))))) sequence (call important-result) :derive-type (sequence-result-nth-arg 0)) (defknown find (t proper-sequence &rest t &key (:test (function-designator ((nth-arg 0) (nth-arg 1 :sequence t :key :key)))) (:test-not (function-designator ((nth-arg 0) (nth-arg 1 :sequence t :key :key)))) (:start (inhibit-flushing index 0)) (:end (inhibit-flushing sequence-end nil)) (:from-end t) (:key (function-designator ((nth-arg 1 :sequence t))))) t (foldable flushable call)) (defknown (find-if find-if-not) ((function-designator ((nth-arg 1 :sequence t :key :key))) proper-sequence &rest t &key (:from-end t) (:start (inhibit-flushing index 0)) (:end (inhibit-flushing sequence-end nil)) (:key (function-designator ((nth-arg 1 :sequence t))))) t (foldable flushable call)) (defknown position (t proper-sequence &rest t &key (:test (function-designator ((nth-arg 0) (nth-arg 1 :sequence t :key :key)))) (:test-not (function-designator ((nth-arg 0) (nth-arg 1 :sequence t :key :key)))) (:start (inhibit-flushing index 0)) (:end (inhibit-flushing sequence-end nil)) (:from-end t) (:key (function-designator ((nth-arg 1 :sequence t))))) (or (mod #.(1- array-dimension-limit)) null) (foldable flushable call)) (defknown (position-if position-if-not) ((function-designator ((nth-arg 1 :sequence t :key :key))) proper-sequence &rest t &key (:from-end t) (:start (inhibit-flushing index 0)) (:end (inhibit-flushing sequence-end nil)) (:key (function-designator ((nth-arg 1 :sequence t))))) (or (mod #.(1- array-dimension-limit)) null) (foldable flushable call)) (defknown (%bit-position/0 %bit-position/1) (simple-bit-vector t index index) (or (mod #.(1- array-dimension-limit)) null) (foldable flushable no-verify-arg-count)) (defknown (%bit-pos-fwd/0 %bit-pos-fwd/1 %bit-pos-rev/0 %bit-pos-rev/1) (simple-bit-vector index index) (or (mod #.(1- array-dimension-limit)) null) (foldable flushable no-verify-arg-count)) (defknown %bit-position (t simple-bit-vector t index index) (or (mod #.(1- array-dimension-limit)) null) (foldable flushable no-verify-arg-count)) (defknown (%bit-pos-fwd %bit-pos-rev) (t simple-bit-vector index index) (or (mod #.(1- array-dimension-limit)) null) (foldable flushable no-verify-arg-count)) (defknown count (t proper-sequence &rest t &key (:test (function-designator ((nth-arg 0) (nth-arg 1 :sequence t :key :key)))) (:test-not (function-designator ((nth-arg 0) (nth-arg 1 :sequence t :key :key)))) (:from-end t) (:start (inhibit-flushing index 0)) (:end (inhibit-flushing sequence-end nil)) (:key (function-designator ((nth-arg 1 :sequence t))))) index (foldable flushable call)) (defknown (count-if count-if-not) ((function-designator ((nth-arg 1 :sequence t :key :key))) proper-sequence &rest t &key (:from-end t) (:start (inhibit-flushing index 0)) (:end (inhibit-flushing sequence-end nil)) (:key (function-designator ((nth-arg 1 :sequence t))))) index (foldable flushable call)) (defknown (mismatch search) (proper-sequence proper-sequence &rest t &key (:from-end t) (:test (function-designator ((nth-arg 0 :sequence t :key :key) (nth-arg 1 :sequence t :key :key)))) (:test-not (function-designator ((nth-arg 0 :sequence t :key :key) (nth-arg 1 :sequence t :key :key)))) (:start1 (inhibit-flushing index 0)) (:end1 (inhibit-flushing sequence-end nil)) (:start2 (inhibit-flushing index 0)) (:end2 (inhibit-flushing sequence-end nil)) (:key (function-designator ((or (nth-arg 0 :sequence t) (nth-arg 1 :sequence t)))))) (or index null) (foldable flushable call)) not FLUSHABLE , since vector sort guaranteed in - place ... (defknown (stable-sort sort) ((modifying sequence) (function-designator ((nth-arg 0 :sequence t :key :key) (nth-arg 0 :sequence t :key :key))) &rest t &key (:key (function-designator ((nth-arg 0 :sequence t))))) sequence (call) :derive-type (sequence-result-nth-arg 0 :preserve-dimensions t :preserve-vector-type t)) (defknown sb-impl::stable-sort-list (list function function) list (call important-result no-verify-arg-count)) (defknown sb-impl::sort-vector (vector index index function (or function null)) SORT - VECTOR works through side - effect (call no-verify-arg-count)) (defknown sb-impl::stable-sort-vector (vector function (or function null)) vector (call no-verify-arg-count)) (defknown sb-impl::stable-sort-simple-vector (simple-vector function (or function null)) simple-vector (call no-verify-arg-count)) (defknown merge (type-specifier (modifying sequence) (modifying sequence) (function-designator ((nth-arg 1 :sequence t :key :key) (nth-arg 2 :sequence t :key :key))) &key (:key (function-designator ((or (nth-arg 1 :sequence t) (nth-arg 2 :sequence t)))))) sequence (call important-result) :derive-type (creation-result-type-specifier-nth-arg 0)) (defknown read-sequence ((modifying sequence) stream &key (:start index) (:end sequence-end)) (index) ()) (defknown write-sequence (proper-sequence stream &key (:start index) (:end sequence-end)) sequence (recursive) :derive-type #'result-type-first-arg) from the " Manipulating List Structure " chapter : (defknown (car cdr first rest) (list) t (foldable flushable)) (defknown (caar cadr cdar cddr caaar caadr cadar caddr cdaar cdadr cddar cdddr caaaar caaadr caadar caaddr cadaar cadadr caddar cadddr cdaaar cdaadr cdadar cdaddr cddaar cddadr cdddar cddddr second third fourth fifth sixth seventh eighth ninth tenth) (list) t (foldable unsafely-flushable)) (defknown cons (t t) cons (movable flushable)) (defknown tree-equal (t t &key (:test (function-designator (t t))) (:test-not (function-designator (t t)))) boolean (foldable flushable call)) (defknown endp (list) boolean (foldable flushable movable)) (defknown list-length (proper-or-circular-list) (or index null) (foldable unsafely-flushable)) (defknown (nth fast-&rest-nth) (unsigned-byte list) t (foldable flushable)) (defknown nthcdr (unsigned-byte list) t (foldable unsafely-flushable)) (defknown last (list &optional unsigned-byte) t (foldable flushable)) (defknown %last0 (list) t (foldable flushable no-verify-arg-count)) (defknown %last1 (list) t (foldable flushable no-verify-arg-count)) (defknown %lastn/fixnum (list (and unsigned-byte fixnum)) t (foldable flushable no-verify-arg-count)) (defknown %lastn/bignum (list (and unsigned-byte bignum)) t (foldable flushable no-verify-arg-count)) (defknown list (&rest t) list (movable flushable)) (defknown list* (t &rest t) t (movable flushable)) to combine the fixnum + range test into one instruction (eval-when (:compile-toplevel :load-toplevel :execute) (defconstant make-list-limit (ash most-positive-fixnum (- (+ sb-vm:word-shift 1))))) (defknown make-list ((integer 0 #.make-list-limit) &key (:initial-element t)) list (movable flushable)) (defknown %make-list ((integer 0 #.make-list-limit) t) list (movable flushable no-verify-arg-count)) (defknown sb-impl::|List| (&rest t) list (movable flushable)) (defknown sb-impl::|List*| (t &rest t) t (movable flushable)) (defknown sb-impl::|Append| (&rest t) t (movable flushable)) (defknown sb-impl::|Vector| (&rest t) simple-vector (movable flushable)) (defknown append (&rest t) t (flushable) :call-type-deriver #'append-call-type-deriver) (defknown sb-impl::append2 (list t) t (flushable no-verify-arg-count) :call-type-deriver #'append-call-type-deriver) (defknown copy-list (proper-or-dotted-list) list (flushable)) (defknown copy-alist (proper-list) list (flushable)) (defknown copy-tree (t) t (flushable recursive)) (defknown revappend (proper-list t) t (flushable)) (defknown nconc (&rest (modifying t :butlast t)) t ()) (defknown nreconc ((modifying list) t) t (important-result)) (defknown butlast (proper-or-dotted-list &optional unsigned-byte) list (flushable)) (defknown nbutlast ((modifying list) &optional unsigned-byte) list ()) (defknown ldiff (proper-or-dotted-list t) list (flushable)) (defknown (rplaca rplacd) ((modifying cons) t) cons ()) (defknown subst (t t t &key (:test (function-designator ((nth-arg 1) (nth-arg 2 :sequence t :key :key)))) (:test-not (function-designator ((nth-arg 1) (nth-arg 2 :sequence t :key :key)))) (:key (function-designator ((nth-arg 2 :sequence t))))) t (flushable call)) (defknown nsubst (t t (modifying t) &key (:test (function-designator ((nth-arg 1) (nth-arg 2 :sequence t :key :key)))) (:test-not (function-designator ((nth-arg 1) (nth-arg 2 :sequence t :key :key)))) (:key (function-designator ((nth-arg 2 :sequence t))))) t (call)) (defknown (subst-if subst-if-not) (t (function-designator ((nth-arg 2 :sequence t :key :key))) t &key (:key (function-designator ((nth-arg 2 :sequence t))))) t (flushable call)) (defknown (nsubst-if nsubst-if-not) (t (function-designator ((nth-arg 2 :sequence t :key :key))) (modifying t) &key (:key (function-designator ((nth-arg 2 :sequence t))))) t (call)) (defknown sublis (proper-list t &key (:test (function-designator ((nth-arg 1 :sequence t :key :key) (nth-arg 0 :sequence t)))) (:test-not (function-designator ((nth-arg 1 :sequence t :key :key) (nth-arg 0 :sequence t)))) (:key (function-designator ((nth-arg 1 :sequence t))))) t (flushable call)) (defknown nsublis (list (modifying t) &key (:test (function-designator ((nth-arg 1 :sequence t :key :key) (nth-arg 0 :sequence t)))) (:test-not (function-designator ((nth-arg 1 :sequence t :key :key) (nth-arg 0 :sequence t)))) (:key (function-designator ((nth-arg 1 :sequence t))))) t (flushable call)) (defknown member (t proper-list &key (:test (function-designator ((nth-arg 0) (nth-arg 1 :sequence t :key :key)))) (:test-not (function-designator ((nth-arg 0) (nth-arg 1 :sequence t :key :key)))) (:key (function-designator ((nth-arg 1 :sequence t))))) list (foldable flushable call)) (defknown (member-if member-if-not) ((function-designator ((nth-arg 1 :sequence t :key :key))) proper-list &key (:key (function-designator ((nth-arg 1 :sequence t))))) list (foldable flushable call)) (defknown tailp (t list) boolean (foldable flushable)) (defknown adjoin (t proper-list &key (:key (function-designator ((or (nth-arg 0) (nth-arg 1 :sequence t))))) (:test (function-designator ((nth-arg 0 :key :key) (nth-arg 1 :sequence t :key :key)))) (:test-not (function-designator ((nth-arg 0 :key :key) (nth-arg 1 :sequence t :key :key))))) cons (flushable call)) (defknown (union intersection set-difference set-exclusive-or) (proper-list proper-list &key (:key (function-designator ((or (nth-arg 0 :sequence t) (nth-arg 1 :sequence t))))) (:test (function-designator ((nth-arg 0 :sequence t :key :key) (nth-arg 1 :sequence t :key :key)))) (:test-not (function-designator ((nth-arg 0 :sequence t :key :key) (nth-arg 1 :sequence t :key :key))))) list (foldable flushable call)) (defknown (nunion nintersection nset-difference nset-exclusive-or) ((modifying list) (modifying list) &key (:key (function-designator ((or (nth-arg 0 :sequence t) (nth-arg 1 :sequence t))))) (:test (function-designator ((nth-arg 0 :sequence t :key :key) (nth-arg 1 :sequence t :key :key)))) (:test-not (function-designator ((nth-arg 0 :sequence t :key :key) (nth-arg 1 :sequence t :key :key))))) list (foldable flushable call important-result)) (defknown subsetp (proper-list proper-list &key (:key (function-designator ((or (nth-arg 0 :sequence t) (nth-arg 1 :sequence t))))) (:test (function-designator ((nth-arg 0 :sequence t :key :key) (nth-arg 1 :sequence t :key :key)))) (:test-not (function-designator ((nth-arg 0 :sequence t :key :key) (nth-arg 1 :sequence t :key :key))))) boolean (foldable flushable call)) (defknown acons (t t t) cons (movable flushable)) (defknown pairlis (t t &optional t) list (flushable)) (defknown (rassoc assoc) (t proper-list &key (:key (function-designator ((nth-arg 1 :sequence t)))) (:test (function-designator ((nth-arg 0) (nth-arg 1 :sequence t :key :key)))) (:test-not (function-designator ((nth-arg 0) (nth-arg 1 :sequence t :key :key))))) list (foldable flushable call)) (defknown (assoc-if-not assoc-if rassoc-if rassoc-if-not) ((function-designator ((nth-arg 1 :sequence t :key :key))) proper-list &key (:key (function-designator ((nth-arg 1 :sequence t))))) list (foldable flushable call)) (defknown (memq assq) (t proper-list) list (foldable flushable)) (defknown (delq delq1) (t (modifying list)) list (flushable)) from the " Hash Tables " chapter : (defknown make-hash-table (&key (:test function-designator) (:size unsigned-byte) (:rehash-size (or (integer 1) (float ($1.0)))) (:rehash-threshold (real 0 1)) (:hash-function (or null function-designator)) (:weakness (member nil :key :value :key-and-value :key-or-value)) (:synchronized t)) hash-table (flushable)) (defknown sb-impl::make-hash-table-using-defaults (integer) hash-table (flushable)) (defknown hash-table-p (t) boolean (movable foldable flushable)) (defknown gethash (t hash-table &optional t) (values t boolean) not FOLDABLE , since hash table contents can change (defknown sb-impl::gethash3 (t hash-table t) (values t boolean) not FOLDABLE , since hash table contents can change (defknown %puthash (t (modifying hash-table) t) t (no-verify-arg-count) :derive-type #'result-type-last-arg) (defknown remhash (t (modifying hash-table)) boolean ()) (defknown maphash ((function-designator (t t)) hash-table) null (flushable call)) (defknown clrhash ((modifying hash-table)) hash-table ()) (defknown hash-table-count (hash-table) index (flushable)) (defknown hash-table-rehash-size (hash-table) (or index (single-float ($1.0))) (foldable flushable)) (defknown hash-table-rehash-threshold (hash-table) (single-float ($0.0) $1.0) (foldable flushable)) (defknown hash-table-size (hash-table) index (flushable)) (defknown hash-table-test (hash-table) function-designator (foldable flushable)) (defknown (sxhash psxhash) (t) hash-code (foldable flushable)) (defknown hash-table-equalp (hash-table hash-table) boolean (foldable flushable)) (defknown sb-impl::install-hash-table-lock (hash-table) sb-thread:mutex ()) (defknown (sb-impl::signal-corrupt-hash-table sb-impl::signal-corrupt-hash-table-bucket) (t) nil ()) (defknown make-array ((or index list) &key (:element-type type-specifier) (:initial-element t) (:initial-contents t) (:adjustable t) (:fill-pointer (or index boolean)) (:displaced-to (or array null)) (:displaced-index-offset index)) array (flushable)) (defknown %make-array ((or index list) (unsigned-byte #.sb-vm:n-widetag-bits) (mod #.sb-vm:n-word-bits) &key (:element-type type-specifier) (:initial-element t) (:initial-contents t) (:adjustable t) (:fill-pointer (or index boolean)) (:displaced-to (or array null)) (:displaced-index-offset index)) array (flushable no-verify-arg-count)) (defknown sb-vm::initial-contents-error (t t) nil (no-verify-arg-count)) (defknown fill-data-vector (vector list sequence) vector (no-verify-arg-count) :result-arg 0) INITIAL - CONTENTS is the first argument to FILL - ARRAY because if it moves . But if INITIAL - CONTENTS were the second argument to FILL - ARRAY , second way shown above , we would have to bind INITIAL - CONTENTS , (defknown fill-array (sequence simple-array) (simple-array) (flushable no-verify-arg-count) :result-arg 1) (defknown vector (&rest t) simple-vector (flushable)) (defknown aref (array &rest index) t (foldable) :call-type-deriver #'array-call-type-deriver) (defknown row-major-aref (array index) t (foldable) :call-type-deriver (lambda (call trusted) (array-call-type-deriver call trusted nil t))) (defknown array-element-type (array) (or list symbol) (foldable flushable)) (defknown array-rank (array) array-rank (foldable flushable)) exclusive limit on rank were 8 , then your dimension numbers can be in the range 0 through 6 , not 0 through 7 . (defknown array-dimension (array array-rank) index (foldable flushable)) (defknown array-dimensions (array) list (foldable flushable)) (defknown array-in-bounds-p (array &rest integer) boolean (foldable flushable) :call-type-deriver #'array-call-type-deriver) (defknown array-row-major-index (array &rest index) array-total-size (foldable flushable) :call-type-deriver #'array-call-type-deriver) (defknown array-total-size (array) array-total-size (foldable flushable)) (defknown adjustable-array-p (array) boolean (movable foldable flushable)) (defknown svref (simple-vector index) t (foldable flushable)) (defknown bit ((array bit) &rest index) bit (foldable flushable)) (defknown sbit ((simple-array bit) &rest index) bit (foldable flushable)) (defknown (bit-and bit-ior bit-xor bit-eqv bit-nand bit-nor bit-andc1 bit-andc2 bit-orc1 bit-orc2) ((array bit) (array bit) &optional (or (array bit) (member t nil))) (array bit) () (defknown bit-not ((array bit) &optional (or (array bit) (member t nil))) (array bit) () (defknown bit-vector-= (bit-vector bit-vector) boolean (movable foldable flushable no-verify-arg-count)) (defknown array-has-fill-pointer-p (array) boolean (movable foldable flushable)) (defknown fill-pointer (complex-vector) index (unsafely-flushable)) (defknown sb-vm::fill-pointer-error (t) nil (no-verify-arg-count)) (defknown vector-push (t (modifying complex-vector)) (or index null) ()) (defknown vector-push-extend (t (modifying complex-vector) &optional (and index (integer 1))) index ()) (defknown vector-pop ((modifying complex-vector)) t ()) (defknown adjust-array (array (or index list) &key (:element-type type-specifier) (:initial-element t) (:initial-contents t) (:fill-pointer (or index boolean)) (:displaced-to (or array null)) (:displaced-index-offset index)) array (important-result)) (defknown char (string index) character (foldable flushable)) (defknown schar (simple-string index) character (foldable flushable)) (defknown (string= string-equal) (string-designator string-designator &key (:start1 (inhibit-flushing index 0)) (:end1 (inhibit-flushing sequence-end nil)) (:start2 (inhibit-flushing index 0)) (:end2 (inhibit-flushing sequence-end nil))) boolean (foldable flushable)) (defknown (string< string> string<= string>= string/= string-lessp string-greaterp string-not-lessp string-not-greaterp string-not-equal) (string-designator string-designator &key (:start1 (inhibit-flushing index 0)) (:end1 (inhibit-flushing sequence-end nil)) (:start2 (inhibit-flushing index 0)) (:end2 (inhibit-flushing sequence-end nil))) (or index null) (foldable flushable)) (defknown (two-arg-string= two-arg-string-equal) (string-designator string-designator) boolean (foldable flushable no-verify-arg-count)) (defknown (two-arg-string< two-arg-string> two-arg-string<= two-arg-string>= two-arg-string/= two-arg-string-lessp two-arg-string-greaterp two-arg-string-not-lessp two-arg-string-not-greaterp two-arg-string-not-equal) (string-designator string-designator) (or index null) (foldable flushable no-verify-arg-count)) (defknown make-string (index &key (:element-type type-specifier) (:initial-element character)) simple-string (flushable)) (defknown (string-trim string-left-trim string-right-trim) (proper-sequence string-designator) string (flushable)) (defknown (string-upcase string-downcase string-capitalize) (string-designator &key (:start (inhibit-flushing index 0)) (:end (inhibit-flushing sequence-end nil))) simple-string (flushable) :derive-type (sequence-result-nth-arg 0 :preserve-dimensions t)) (defknown (nstring-upcase nstring-downcase nstring-capitalize) ((modifying string) &key (:start index) (:end sequence-end)) string () :derive-type #'result-type-first-arg) (defknown string (string-designator) string (flushable)) (defknown (string<* string>* string<=* string>=* string/=*) (string-designator string-designator (inhibit-flushing index 0) (inhibit-flushing sequence-end nil) (inhibit-flushing index 0) (inhibit-flushing sequence-end nil)) (or index null) (foldable flushable no-verify-arg-count)) (defknown string=* (string-designator string-designator (inhibit-flushing index 0) (inhibit-flushing sequence-end nil) (inhibit-flushing index 0) (inhibit-flushing sequence-end nil)) boolean (foldable flushable no-verify-arg-count)) (defknown simple-base-string= (simple-base-string simple-base-string (inhibit-flushing index 0) (inhibit-flushing sequence-end nil) (inhibit-flushing index 0) (inhibit-flushing sequence-end nil)) boolean (foldable flushable no-verify-arg-count)) (defknown simple-character-string= (simple-character-string simple-character-string (inhibit-flushing index 0) (inhibit-flushing sequence-end nil) (inhibit-flushing index 0) (inhibit-flushing sequence-end nil)) boolean (foldable flushable no-verify-arg-count)) from the " Eval " chapter : (defknown eval (t) * (recursive)) (defknown constantp (t &optional lexenv-designator) boolean (foldable flushable)) (defknown make-synonym-stream (symbol) synonym-stream (flushable)) (defknown make-broadcast-stream (&rest stream) broadcast-stream (unsafely-flushable)) (defknown make-concatenated-stream (&rest stream) concatenated-stream (unsafely-flushable)) (defknown make-two-way-stream (stream stream) two-way-stream (unsafely-flushable)) (defknown make-echo-stream (stream stream) echo-stream (flushable)) (defknown make-string-input-stream (string &optional index sequence-end) sb-impl::string-input-stream (flushable)) (defknown sb-impl::%init-string-input-stream (instance string &optional index sequence-end) (values sb-impl::string-input-stream index &optional) (flushable)) (defknown sb-impl::%init-string-output-stream (instance t t) sb-impl::string-output-stream Not flushable , for two reasons : - possibly need to verify that the second arg is a type specifier (no-verify-arg-count)) (defknown make-string-output-stream (&key (:element-type type-specifier)) sb-impl::string-output-stream (flushable)) (defknown get-output-stream-string (stream) simple-string ()) (defknown streamp (t) boolean (movable foldable flushable)) (movable foldable flushable)) (defknown stream-external-format (stream) t (flushable)) (defknown (output-stream-p input-stream-p) (stream) boolean (movable foldable flushable)) (defknown open-stream-p (stream) boolean (flushable)) (defknown close (stream &key (:abort t)) (eql t) ()) (defknown file-string-length (stream (or string character)) (or unsigned-byte null) (flushable)) (defknown copy-readtable (&optional (or readtable null) (or readtable null)) readtable ()) (defknown readtablep (t) boolean (movable foldable flushable)) (defknown set-syntax-from-char (character character &optional readtable (or readtable null)) (eql t) ()) (defknown set-macro-character (character (function-designator (t t) * :no-function-conversion t) &optional t (or readtable null)) (eql t) (call)) (defknown get-macro-character (character &optional (or readtable null)) (values function-designator boolean) (flushable)) (defknown make-dispatch-macro-character (character &optional t readtable) (eql t) ()) test in reader.impure.lisp The function NIL is called by SET - DISPATCH - MACRO - CHARACTER with three arguments , but wants exactly two . (defknown set-dispatch-macro-character (character character (function-designator (t t t) * :no-function-conversion t) &optional (or readtable null)) (eql t) (call)) (defknown get-dispatch-macro-character (character character &optional (or readtable null)) (or function-designator null) ()) (defknown copy-pprint-dispatch (&optional (or sb-pretty:pprint-dispatch-table null)) sb-pretty:pprint-dispatch-table ()) (defknown pprint-dispatch (t &optional (or sb-pretty:pprint-dispatch-table null)) (values function-designator boolean) ()) (defknown (pprint-fill pprint-linear) (stream-designator t &optional t t) null ()) (defknown pprint-tabular (stream-designator t &optional t t unsigned-byte) null ()) (defknown pprint-indent ((member :block :current) real &optional stream-designator) null ()) (defknown pprint-newline ((member :linear :fill :miser :mandatory) &optional stream-designator) null ()) (defknown pprint-tab ((member :line :section :line-relative :section-relative) unsigned-byte unsigned-byte &optional stream-designator) null ()) (defknown set-pprint-dispatch (type-specifier (function-designator (t t) * :no-function-conversion t) &optional real sb-pretty:pprint-dispatch-table) null (call)) (defknown (read read-preserving-whitespace) (&optional stream-designator t t t) t ()) (defknown read-char (&optional stream-designator t t t) t () :derive-type (read-elt-type-deriver nil 'character nil)) (defknown read-char-no-hang (&optional stream-designator t t t) t () :derive-type (read-elt-type-deriver nil 'character t)) (defknown read-delimited-list (character &optional stream-designator t) list ()) (defknown read-line (&optional stream-designator t t t) (values t boolean) ()) (defknown unread-char (character &optional stream-designator) t ()) (defknown peek-char (&optional (or character (member nil t)) stream-designator t t t) t () :derive-type (read-elt-type-deriver t 'character nil)) (defknown listen (&optional stream-designator) boolean (flushable)) (defknown clear-input (&optional stream-designator) null ()) (defknown read-from-string (string &optional t t &key (:start index) (:end sequence-end) (:preserve-whitespace t)) (values t index)) (defknown parse-integer (string &key (:start index) (:end sequence-end) (:radix (integer 2 36)) (:junk-allowed t)) (values (or integer null ()) index)) (defknown read-byte (stream &optional t t) t () :derive-type (read-elt-type-deriver nil 'integer nil)) (defknown (prin1 print princ) (t &optional stream-designator) t (any) :derive-type #'result-type-first-arg) (defknown output-object (t stream) null (any)) (defknown %write (t stream-designator) t (any no-verify-arg-count)) (defknown (pprint) (t &optional stream-designator) (values) ()) (macrolet ((deffrob (name keys returns attributes &rest more) `(defknown ,name (t &key ,@keys (:escape t) (:radix t) (:base (integer 2 36)) (:circle t) (:pretty t) (:readably t) (:level (or unsigned-byte null)) (:length (or unsigned-byte null)) (:case t) (:array t) (:gensym t) (:lines (or unsigned-byte null)) (:right-margin (or unsigned-byte null)) (:miser-width (or unsigned-byte null)) (:pprint-dispatch t) (:suppress-errors t)) ,returns ,attributes ,@more))) (deffrob write ((:stream stream-designator)) t (any) :derive-type #'result-type-first-arg) (deffrob write-to-string () simple-string (unsafely-flushable))) (defknown (prin1-to-string princ-to-string) (t) simple-string (unsafely-flushable)) (defknown sb-impl::stringify-object (t) simple-string (no-verify-arg-count)) (defknown write-char (character &optional stream-designator) character () :derive-type #'result-type-first-arg) (defknown (write-string write-line) (string &optional stream-designator &key (:start index) (:end sequence-end)) string () :derive-type #'result-type-first-arg) (defknown (terpri finish-output force-output clear-output) (&optional stream-designator) null ()) (defknown fresh-line (&optional stream-designator) boolean ()) (defknown write-byte (integer stream) integer () :derive-type #'result-type-first-arg) (defknown format ((or (member nil t) stream string) (or string function) &rest t) (or string null) ()) (defknown sb-format::format-error* (string list &rest t &key &allow-other-keys) nil) (defknown sb-format:format-error (string &rest t) nil) (defknown sb-format::format-error-at* ((or null string) (or null index) string list &rest t &key &allow-other-keys) nil) (defknown sb-format::format-error-at ((or null string) (or null index) string &rest t) nil) (defknown sb-format::args-exhausted (string integer) nil) (defknown (y-or-n-p yes-or-no-p) (&optional (or string null function) &rest t) boolean ()) from the " File System Interface " chapter : ( No pathname functions are FOLDABLE because they all potentially depend on * DEFAULT - PATHNAME - DEFAULTS * , e.g. to provide a default (defknown wild-pathname-p (pathname-designator &optional (member nil :host :device :directory :name :type :version)) generalized-boolean (recursive)) (defknown pathname-match-p (pathname-designator pathname-designator) generalized-boolean ()) (defknown translate-pathname (pathname-designator pathname-designator pathname-designator &key) pathname ()) (defknown logical-pathname (pathname-designator) logical-pathname ()) (defknown translate-logical-pathname (pathname-designator &key) pathname (recursive)) (defknown load-logical-pathname-translations (string) t ()) (defknown logical-pathname-translations (logical-host-designator) list ()) (defknown pathname (pathname-designator) pathname ()) (defknown truename (pathname-designator) pathname ()) (defknown parse-namestring (pathname-designator &optional (or list host string (member :unspecific)) pathname-designator &key (:start index) (:end sequence-end) (:junk-allowed t)) (values (or pathname null) sequence-end) (recursive)) (defknown merge-pathnames (pathname-designator &optional pathname-designator pathname-version) pathname ()) (defknown make-pathname (&key (:defaults pathname-designator) (:host (or string pathname-host)) (:device (or string pathname-device)) (:directory (or pathname-directory string (member :wild))) (:name (or pathname-name string (member :wild))) (:type (or pathname-type string (member :wild))) (:version pathname-version) (:case pathname-component-case)) pathname (unsafely-flushable)) (defknown pathnamep (t) boolean (movable flushable)) (defknown pathname-host (pathname-designator &key (:case pathname-component-case)) pathname-host (flushable)) (defknown pathname-device (pathname-designator &key (:case pathname-component-case)) pathname-device (flushable)) (defknown pathname-directory (pathname-designator &key (:case pathname-component-case)) pathname-directory (flushable)) (defknown pathname-name (pathname-designator &key (:case pathname-component-case)) pathname-name (flushable)) (defknown pathname-type (pathname-designator &key (:case pathname-component-case)) pathname-type (flushable)) (defknown pathname-version (pathname-designator) pathname-version (flushable)) (defknown pathname= (pathname pathname) boolean (movable foldable flushable)) (defknown (namestring file-namestring directory-namestring host-namestring) (pathname-designator) (or simple-string null) (unsafely-flushable)) (defknown enough-namestring (pathname-designator &optional pathname-designator) simple-string (unsafely-flushable)) (defknown user-homedir-pathname (&optional t) pathname (flushable)) (defknown open (pathname-designator &key (:class symbol) (:direction (member :input :output :io :probe)) (:element-type type-specifier) (:if-exists (member :error :new-version :rename :rename-and-delete :overwrite :append :supersede nil)) (:if-does-not-exist (member :error :create nil)) (:external-format external-format-designator) #+win32 (:overlapped t)) (or stream null)) (defknown rename-file (pathname-designator filename) (values pathname pathname pathname)) (defknown delete-file (pathname-designator) (eql t)) (defknown probe-file (pathname-designator) (or pathname null) ()) (defknown file-write-date (pathname-designator) (or unsigned-byte null) ()) (defknown file-author (pathname-designator) (or simple-string null) ()) (defknown file-position (stream &optional (or unsigned-byte (member :start :end))) (or unsigned-byte (member t nil))) (defknown file-length ((or file-stream synonym-stream broadcast-stream)) (or unsigned-byte null) (unsafely-flushable)) (defknown load ((or filename stream) &key (:verbose t) (:print t) (:if-does-not-exist t) (:external-format external-format-designator)) boolean) (defknown directory (pathname-designator &key (:resolve-symlinks t)) list ()) from the " Conditions " chapter : (defknown (signal warn) (condition-designator-head &rest t) null) (defknown error (condition-designator-head &rest t) nil) (defknown cerror (format-control condition-designator-head &rest t) null) FIXME : first arg is METHOD (defknown method-combination-error (format-control &rest t) *) (defknown assert-error (t &rest t) null) (defknown check-type-error (t t type-specifier &optional (or null string)) t) (defknown invoke-debugger (condition) nil) (defknown break (&optional format-control &rest t) null) (defknown make-condition (type-specifier &rest t) condition ()) (defknown compute-restarts (&optional (or condition null)) list) (defknown find-restart (restart-designator &optional (or condition null)) (or restart null)) (defknown invoke-restart (restart-designator &rest t) *) (defknown invoke-restart-interactively (restart-designator) *) (defknown restart-name (restart) symbol) (defknown (abort muffle-warning) (&optional (or condition null)) nil) (defknown continue (&optional (or condition null)) null) (defknown (store-value use-value) (t &optional (or condition null)) null) and analogous SBCL extension : (defknown sb-impl::%failed-aver (t) nil (no-verify-arg-count)) (defknown sb-impl::unreachable () nil) (defknown simple-reader-error (stream string &rest t) nil) (defknown sb-kernel:reader-eof-error (stream string) nil) (defknown compile ((or symbol cons) &optional (or list function)) (values (or function symbol cons) boolean boolean)) (defknown compile-file (pathname-designator &key ANSI options (:output-file pathname-designator) (:verbose t) (:print t) (:external-format external-format-designator) (:progress t) (:trace-file t) (:block-compile t) (:entry-points list) (:emit-cfasl t)) (values (or pathname null) boolean boolean)) (defknown (compile-file-pathname) (pathname-designator &key (:output-file (or pathname-designator null (member t))) &allow-other-keys) pathname) (defknown disassemble ((or extended-function-designator (cons (member lambda)) code-component) &key (:stream stream) (:use-labels t)) null) (defknown describe (t &optional stream-designator) (values)) (defknown function-lambda-expression (function) (values t boolean t)) (defknown inspect (t) (values)) (defknown room (&optional (member t nil :default)) (values)) (defknown ed (&optional (or symbol cons filename)) t) (defknown dribble (&optional filename &key (:if-exists t)) (values)) (defknown apropos (string-designator &optional package-designator t) (values)) (defknown apropos-list (string-designator &optional package-designator t) list (flushable recursive)) (defknown get-decoded-time () (values (integer 0 59) (integer 0 59) (integer 0 23) (integer 1 31) (integer 1 12) unsigned-byte (integer 0 6) boolean (rational -24 24)) (flushable)) (defknown get-universal-time () unsigned-byte (flushable)) (defknown decode-universal-time (unsigned-byte &optional (or null (rational -24 24))) (values (integer 0 59) (integer 0 59) (integer 0 23) (integer 1 31) (integer 1 12) unsigned-byte (integer 0 6) boolean (rational -24 24)) (flushable)) (defknown encode-universal-time ((integer 0 59) (integer 0 59) (integer 0 23) (integer 1 31) (integer 1 12) unsigned-byte &optional (or null (rational -24 24))) unsigned-byte (flushable)) (defknown (get-internal-run-time get-internal-real-time) () internal-time (flushable)) (defknown sleep ((real 0)) null ()) (defknown call-with-timing (function-designator function-designator &rest t) * (call)) LISP - IMPLEMENTATION - VERSION to possibly punt and return NIL , we (defknown (lisp-implementation-type lisp-implementation-version) () simple-string (flushable)) functions -- these really can return NIL . (defknown (machine-type machine-version machine-instance software-type software-version short-site-name long-site-name) () (or simple-string null) (flushable)) (defknown identity (t) t (movable foldable flushable) :derive-type #'result-type-first-arg) (defknown constantly (t) function (movable flushable)) (defknown complement (function) function (movable flushable)) (defknown symbol-global-value (symbol) t () :derive-type #'symbol-value-derive-type) (defknown set-symbol-global-value (symbol t) t () :derive-type #'result-type-last-arg) (defknown get-bytes-consed () unsigned-byte (flushable)) (defknown mask-signed-field ((integer 0 *) integer) integer (movable flushable foldable)) (defknown array-storage-vector (array) (simple-array * (*)) (any)) (defknown %rest-values (t t t) * (always-translatable)) (defknown %rest-ref (t t t t &optional boolean) * (always-translatable)) (defknown %rest-length (t t t) * (always-translatable)) (defknown %rest-null (t t t t) * (always-translatable)) (defknown %rest-true (t t t) * (always-translatable)) (defknown %unary-truncate/single-float (single-float) integer (movable foldable flushable no-verify-arg-count)) (defknown %unary-truncate/double-float (double-float) integer (movable foldable flushable no-verify-arg-count)) (defknown %typep (t (or type-specifier ctype)) boolean (movable flushable no-verify-arg-count)) (defknown %instance-typep (t (or type-specifier ctype wrapper)) boolean (movable flushable always-translatable)) (defknown %typep-wrapper (t t (or type-specifier ctype)) t (movable flushable always-translatable)) (defknown %type-constraint (t (or type-specifier ctype)) t (always-translatable)) (defknown ltv-wrapper (t) t (movable flushable always-translatable) :derive-type #'result-type-first-arg) (defknown %cleanup-point (&rest t) t (reoptimize-when-unlinking)) (defknown %special-bind (t t) t) (defknown %special-unbind (&rest symbol) t) (defknown %listify-rest-args (t index) list (flushable)) (defknown %more-arg-context (t t) (values t index) (flushable)) (defknown %more-arg (t index) t (flushable)) (defknown %more-keyword-pair (t fixnum) (values t t) (flushable)) #+stack-grows-downward-not-upward FIXME : The second argument here should really be NEGATIVE - INDEX , but doing that breaks the build , and I can not seem to figure out why . --NS 2006 - 06 - 29 (defknown %more-kw-arg (t fixnum) (values t t)) (defknown %more-arg-values (t index index) * (flushable)) (defknown %verify-arg-count (index index) (values)) (defknown %arg-count-error (t) nil) (defknown %local-arg-count-error (t t) nil) (defknown %unknown-values () *) (defknown %catch (t t) t) (defknown %unwind-protect (t t) t) (defknown (%catch-breakup %unwind-protect-breakup %lexical-exit-breakup) (t) t) (defknown %unwind (t t t) nil) (defknown %continue-unwind () nil) (defknown %nlx-entry (t) *) (defknown %%primitive (t t &rest t) *) (defknown %pop-values (t) t) (defknown %nip-values (t t &rest t) (values)) (defknown %dummy-dx-alloc (t t) t) (defknown %type-check-error (t t t) nil) (defknown %type-check-error/c (t t t) nil) (defknown (%compile-time-type-error %compile-time-type-style-warn) (t t t t t t) *) (defknown (etypecase-failure ecase-failure) (t t) nil) (defknown %odd-key-args-error () nil) (defknown %unknown-key-arg-error (t t) nil) (defknown (%ldb %mask-field) (bit-index bit-index integer) unsigned-byte (movable foldable flushable no-verify-arg-count)) (defknown (%dpb %deposit-field) (integer bit-index bit-index integer) integer (movable foldable flushable no-verify-arg-count)) (defknown %negate (number) number (movable foldable flushable no-verify-arg-count)) (defknown (%check-bound check-bound) (array index t) index (dx-safe)) (defknown data-vector-ref (simple-array index) t (foldable flushable always-translatable)) (defknown data-vector-ref-with-offset (simple-array fixnum fixnum) t (foldable flushable always-translatable)) (defknown data-nil-vector-ref (simple-array index) nil (always-translatable)) (defknown data-vector-set (array index t) (values) (dx-safe always-translatable)) (defknown data-vector-set-with-offset (array fixnum fixnum t) (values) (dx-safe always-translatable)) (defknown hairy-data-vector-ref (array index) t (foldable flushable no-verify-arg-count)) (defknown hairy-data-vector-set (array index t) t (no-verify-arg-count)) (defknown hairy-data-vector-ref/check-bounds (array index) t (foldable no-verify-arg-count)) (defknown hairy-data-vector-set/check-bounds (array index t) t (no-verify-arg-count)) (defknown %caller-frame () t (flushable)) (defknown %caller-pc () system-area-pointer (flushable)) (defknown %with-array-data (array index (or index null)) (values (simple-array * (*)) index index index) (foldable flushable no-verify-arg-count)) (defknown %with-array-data/fp (array index (or index null)) (values (simple-array * (*)) index index index) (foldable flushable no-verify-arg-count)) (defknown %set-symbol-package (symbol t) t ()) (defknown (%coerce-callable-to-fun %coerce-callable-for-call) (function-designator) function (flushable)) (defknown array-bounding-indices-bad-error (t t t) nil) (defknown sequence-bounding-indices-bad-error (t t t) nil) (defknown %find-position (t sequence t index sequence-end (function (t)) (function (t t))) (values t (or index null)) (flushable call)) (defknown (%find-position-if %find-position-if-not) (function sequence t index sequence-end function) (values t (or index null)) (call no-verify-arg-count)) (defknown effective-find-position-test (function-designator function-designator) function (flushable foldable)) (defknown effective-find-position-key (function-designator) function (flushable foldable)) (defknown (%adjoin %adjoin-eq) (t list) list (flushable no-verify-arg-count)) (defknown (%member %member-eq %assoc %assoc-eq %rassoc %rassoc-eq) (t list) list (foldable flushable no-verify-arg-count)) (defknown (%adjoin-key %adjoin-key-eq) (t list (function (t))) list (flushable call no-verify-arg-count)) (defknown (%member-key %member-key-eq %assoc-key %assoc-key-eq %rassoc-key %rassoc-key-eq) (t list (function (t))) list (foldable flushable call no-verify-arg-count)) (defknown (%assoc-if %assoc-if-not %rassoc-if %rassoc-if-not %member-if %member-if-not) ((function (t)) list) list (foldable flushable call no-verify-arg-count)) (defknown (%assoc-if-key %assoc-if-not-key %rassoc-if-key %rassoc-if-not-key %member-if-key %member-if-not-key) ((function (t)) list (function (t))) list (foldable flushable call no-verify-arg-count)) (defknown (%adjoin-test %adjoin-test-not) (t list (function (t t))) list (flushable call no-verify-arg-count)) (defknown (%member-test %member-test-not %assoc-test %assoc-test-not %rassoc-test %rassoc-test-not) (t list (function (t t))) list (foldable flushable call no-verify-arg-count)) (defknown (%adjoin-key-test %adjoin-key-test-not) (t list (function (t)) (function (t t))) list (flushable call no-verify-arg-count)) (defknown (%member-key-test %member-key-test-not %assoc-key-test %assoc-key-test-not %rassoc-key-test %rassoc-key-test-not) (t list (function (t)) (function (t t))) list (foldable flushable call no-verify-arg-count)) (defknown %check-vector-sequence-bounds (vector index sequence-end) index (unwind)) SETF inverses (defknown (setf aref) (t (modifying array) &rest index) t () :call-type-deriver (lambda (call trusted) (array-call-type-deriver call trusted t))) (defknown %set-row-major-aref ((modifying array) index t) t () :call-type-deriver (lambda (call trusted) (array-call-type-deriver call trusted t t))) (defknown (%rplaca %rplacd) ((modifying cons) t) t () :derive-type #'result-type-last-arg) (defknown %put (symbol t t) t (no-verify-arg-count)) (defknown %setelt ((modifying sequence) index t) t () :derive-type #'result-type-last-arg) (defknown %svset ((modifying simple-vector) index t) t ()) (defknown (setf bit) (bit (modifying (array bit)) &rest index) bit ()) (defknown (setf sbit) (bit (modifying (simple-array bit)) &rest index) bit ()) (defknown %charset ((modifying string) index character) character ()) (defknown %scharset ((modifying simple-string) index character) character ()) (defknown %set-symbol-value (symbol t) t ()) (defknown (setf symbol-function) (function symbol) function ()) Does this really need a type deriver ? It 's inline , and returns its 1st arg , (defknown (setf symbol-plist) (list symbol) list () :derive-type #'result-type-first-arg) (defknown (setf documentation) ((or string null) t symbol) (or string null) ()) (defknown %setnth (unsigned-byte (modifying list) t) t () :derive-type #'result-type-last-arg) (defknown %set-fill-pointer ((modifying complex-vector) index) index () :derive-type #'result-type-last-arg) ALIEN and call - out - to - C stuff (defknown %alien-funcall ((or string system-area-pointer) alien-type &rest t) *) (defknown sb-vm::touch-object (t) (values) (always-translatable)) (defknown sb-vm::touch-object-identity (t) t (always-translatable)) (defknown foreign-symbol-dataref-sap (simple-string) system-area-pointer (movable flushable)) (defknown foreign-symbol-sap (simple-string &optional boolean) system-area-pointer (movable flushable)) (defknown foreign-symbol-address (simple-string &optional boolean) (values integer boolean) (movable flushable)) (defknown %fun-name (function) t (flushable)) (defknown (setf %fun-name) (t function) t ()) (defknown policy-quality (policy symbol) policy-quality (flushable)) (defknown %program-error (&optional t &rest t) nil ()) (defknown compiler-error (t &rest t) nil ()) (defknown (compiler-warn compiler-style-warn) (t &rest t) (values) ()) (defknown (compiler-mumble note-lossage note-unwinnage) (string &rest t) (values) ()) (defknown (compiler-notify maybe-compiler-notify) ((or format-control symbol) &rest t) (values) ()) (defknown style-warn (t &rest t) null ()) at least some versions of CCL which do not agree that NIL is legal here : Compiler warnings : Alternatively we could use PROCLAIM , except that that (defknown missing-arg () nil (no-verify-arg-count)) (defknown give-up-ir1-transform (&rest t) nil) (defknown coerce-to-condition ((or condition symbol string function) type-specifier symbol &rest t) condition ()) (defknown coerce-symbol-to-fun (symbol) function (no-verify-arg-count)) (defknown sc-number-or-lose (symbol) sc-number (foldable)) (defknown set-info-value (t info-number t) t () :derive-type #'result-type-last-arg) (defknown sb-vm:%compiler-barrier () (values) ()) (defknown sb-vm:%memory-barrier () (values) ()) (defknown sb-vm:%read-barrier () (values) ()) (defknown sb-vm:%write-barrier () (values) ()) (defknown sb-vm:%data-dependency-barrier () (values) ()) #+sb-safepoint use of the VOP in the function prologue anyway . (defknown sb-kernel::gc-safepoint () (values) ()) the CAS functions are transformed to something else rather than " translated " . (defknown (cas svref) (t t simple-vector index) t (always-translatable)) (defknown (cas symbol-value) (t t symbol) t (always-translatable)) (defknown %compare-and-swap-svref (simple-vector index t t) t ()) (defknown (%compare-and-swap-symbol-value #+x86-64 %cas-symbol-global-value) (symbol t t) t (unwind)) (defknown (%atomic-dec-symbol-global-value %atomic-inc-symbol-global-value) (symbol fixnum) fixnum) (defknown (%atomic-dec-car %atomic-inc-car %atomic-dec-cdr %atomic-inc-cdr) (cons fixnum) fixnum) (defknown spin-loop-hint () (values) (always-translatable)) (defknown (ill-in ill-bin ill-out ill-bout sb-impl::string-in-misc sb-impl::string-sout sb-impl::finite-base-string-ouch sb-impl::finite-base-string-out-misc sb-impl::fill-pointer-ouch sb-impl::fill-pointer-sout sb-impl::fill-pointer-misc sb-impl::case-frob-upcase-out sb-impl::case-frob-upcase-sout sb-impl::case-frob-downcase-out sb-impl::case-frob-downcase-sout sb-impl::case-frob-capitalize-out sb-impl::case-frob-capitalize-sout sb-impl::case-frob-capitalize-first-out sb-impl::case-frob-capitalize-first-sout sb-impl::case-frob-capitalize-aux-out sb-impl::case-frob-capitalize-aux-sout sb-impl::case-frob-misc sb-pretty::pretty-out sb-pretty::pretty-misc) * *) (defknown sb-pretty::pretty-sout * * (recursive)) PCL (defknown sb-pcl::pcl-instance-p (t) boolean (movable foldable flushable)) (defknown (slot-value slot-makunbound) (t symbol) t (any)) (defknown (slot-boundp slot-exists-p) (t symbol) boolean) (defknown sb-pcl::set-slot-value (t symbol t) t (any)) (defknown find-class (symbol &optional t lexenv-designator) (or class null) ()) (defknown class-of (t) class (flushable)) (defknown class-name (class) symbol (flushable)) (defknown finalize (t (function-designator () *) &key (:dont-save t)) *) (defknown (sb-impl::%with-standard-io-syntax sb-impl::%with-rebound-io-syntax sb-impl::call-with-sane-io-syntax) (function) *) (defknown sb-debug::funcall-with-debug-io-syntax (function &rest t) *) (defknown sb-impl::%print-unreadable-object (t t t &optional function) null) #+sb-thread (progn (defknown (sb-thread::call-with-mutex sb-thread::call-with-recursive-lock) (function t t t) *) (defknown (sb-thread::call-with-system-mutex sb-thread::call-with-system-mutex/allow-with-interrupts sb-thread::call-with-system-mutex/without-gcing sb-thread::call-with-recursive-system-lock) (function t) *)) #+round-float (progn (defknown round-double (double-float #1=(member :round :floor :ceiling :truncate)) double-float (foldable flushable movable always-translatable)) (defknown round-single (single-float #1#) single-float (foldable flushable movable always-translatable))) (defknown fixnum* (fixnum fixnum t) fixnum (movable always-translatable)) (defknown (signed* signed+ signed-) (sb-vm:signed-word sb-vm:signed-word t) sb-vm:signed-word (movable always-translatable)) (defknown (unsigned* unsigned+ unsigned-) (word word t) word (movable always-translatable)) (defknown (unsigned+signed unsigned-signed) (word sb-vm:signed-word t) integer (movable always-translatable)) (defknown (signed-unsigned) (sb-vm:signed-word word t) integer (movable always-translatable))
b3808a820d448fcc30f3accfda01f9a377ad439730f60adb83e8c62717e15fbd
mentat-collective/MathBox.cljs
closed_line.clj
^#:nextjournal.clerk {:toc true :no-cache true :visibility :hide-ns} (ns mathbox.examples.test.closed-line (:require [mentat.clerk-utils.show :refer [show-sci]] [nextjournal.clerk :as clerk])) ^{::clerk/visibility {:code :hide :result :hide}} (clerk/eval-cljs ;; These aliases only apply inside this namespace. '(require '[mathbox.core :as mathbox]) '(require '[mathbox.primitives :as mb])) ;; # Closed Line ^{:nextjournal.clerk/width :wide} (show-sci [mathbox/MathBox {:container {:style {:height "500px" :width "100%"}} :renderer {:background-color 0xffffff} :scale 720 :focus 3} [mb/Camera {:proxy true :position [0 0 3]}] [mb/Cartesian {:range [[-1 1] [-1 1] [-1 1]] :scale [1 1 1]} [mb/Array {:bufferWidth 20 :width 12 :channels 3 :expr (fn [emit i] (let [angle (* 2 Math/PI (/ i 12))] (emit (Math/cos angle) 0 (Math/sin angle))))}] [mb/Transform {:position [0 1 0] :scale [0.5 0.5 0.5]} [mb/Line {:closed true :color 0x3090ff :width 15 :join "miter"}]] [mb/Transform {:position [0 0.8 0] :scale [0.5 0.5 0.5]} [mb/Line {:color 0x3090ff :width 15 :join "miter"}]] [mb/Transform {:position [0 0.1 0] :scale [0.5 0.5 0.5]} [mb/Line {:closed true :color 0x50bf30 :width 15 :join "round"}]] [mb/Transform {:position [0 -0.1 0] :scale [0.5 0.5 0.5]} [mb/Line {:color 0x50bf30 :width 15 :join "round"}]] [mb/Transform {:position [0 -0.8 0] :scale [0.5 0.5 0.5]} [mb/Line {:closed true :color 0xbf2060 :width 15 :join "bevel"}]] [mb/Transform {:position [0 -1 0] :scale [0.5 0.5 0.5]} [mb/Line {:color 0xbf2060 :width 15 :join "bevel"}]] [mb/Transform {:position [0 1 0]} [mb/Line {:closed true :color 0x3090ff :width 15 :join "miter" :start true :end true}]] [mb/Transform {:position [0 0.8 0]} [mb/Line {:color 0x3090ff :width 15 :join "miter" :start true :end true}]] [mb/Transform {:position [0 0.1 0]} [mb/Line {:closed true :color 0x50bf30 :width 15 :join "round" :start true :end true}]] [mb/Transform {:position [0 -0.1 0]} [mb/Line {:color 0x50bf30 :width 15 :join "round" :start true :end true}]] [mb/Transform {:position [0 -0.8 0]} [mb/Line {:closed true :color 0xbf2060 :width 15 :join "bevel" :start true :end true}]] [mb/Transform {:position [0 -1 0]} [mb/Line {:color 0xbf2060 :width 15 :join "bevel" :start true :end true}]]]])
null
https://raw.githubusercontent.com/mentat-collective/MathBox.cljs/665a0d5f01fb2ed9b0bfeee6f9ad679915f13465/dev/mathbox/examples/test/closed_line.clj
clojure
These aliases only apply inside this namespace. # Closed Line
^#:nextjournal.clerk {:toc true :no-cache true :visibility :hide-ns} (ns mathbox.examples.test.closed-line (:require [mentat.clerk-utils.show :refer [show-sci]] [nextjournal.clerk :as clerk])) ^{::clerk/visibility {:code :hide :result :hide}} (clerk/eval-cljs '(require '[mathbox.core :as mathbox]) '(require '[mathbox.primitives :as mb])) ^{:nextjournal.clerk/width :wide} (show-sci [mathbox/MathBox {:container {:style {:height "500px" :width "100%"}} :renderer {:background-color 0xffffff} :scale 720 :focus 3} [mb/Camera {:proxy true :position [0 0 3]}] [mb/Cartesian {:range [[-1 1] [-1 1] [-1 1]] :scale [1 1 1]} [mb/Array {:bufferWidth 20 :width 12 :channels 3 :expr (fn [emit i] (let [angle (* 2 Math/PI (/ i 12))] (emit (Math/cos angle) 0 (Math/sin angle))))}] [mb/Transform {:position [0 1 0] :scale [0.5 0.5 0.5]} [mb/Line {:closed true :color 0x3090ff :width 15 :join "miter"}]] [mb/Transform {:position [0 0.8 0] :scale [0.5 0.5 0.5]} [mb/Line {:color 0x3090ff :width 15 :join "miter"}]] [mb/Transform {:position [0 0.1 0] :scale [0.5 0.5 0.5]} [mb/Line {:closed true :color 0x50bf30 :width 15 :join "round"}]] [mb/Transform {:position [0 -0.1 0] :scale [0.5 0.5 0.5]} [mb/Line {:color 0x50bf30 :width 15 :join "round"}]] [mb/Transform {:position [0 -0.8 0] :scale [0.5 0.5 0.5]} [mb/Line {:closed true :color 0xbf2060 :width 15 :join "bevel"}]] [mb/Transform {:position [0 -1 0] :scale [0.5 0.5 0.5]} [mb/Line {:color 0xbf2060 :width 15 :join "bevel"}]] [mb/Transform {:position [0 1 0]} [mb/Line {:closed true :color 0x3090ff :width 15 :join "miter" :start true :end true}]] [mb/Transform {:position [0 0.8 0]} [mb/Line {:color 0x3090ff :width 15 :join "miter" :start true :end true}]] [mb/Transform {:position [0 0.1 0]} [mb/Line {:closed true :color 0x50bf30 :width 15 :join "round" :start true :end true}]] [mb/Transform {:position [0 -0.1 0]} [mb/Line {:color 0x50bf30 :width 15 :join "round" :start true :end true}]] [mb/Transform {:position [0 -0.8 0]} [mb/Line {:closed true :color 0xbf2060 :width 15 :join "bevel" :start true :end true}]] [mb/Transform {:position [0 -1 0]} [mb/Line {:color 0xbf2060 :width 15 :join "bevel" :start true :end true}]]]])
b8984e3855b197b32cae8906ca1b48b8a9d348d683ad6058b86d495c27fa0888
fuchsto/drool
Disco.hs
----------------------------------------------------------------------------- -- -- Module : Drool.UI.Visuals.Disco Copyright : License : MIT -- -- Maintainer : -- Stability : experimental -- Portability : POSIX -- -- | -- ----------------------------------------------------------------------------- {-# OPTIONS -O2 -Wall #-} module Drool.UI.Visuals.Disco ( DiscoState, -- hidden type constructor newDiscoVisual, newDiscoState ) where -- Imports -- {{{ import Drool.UI.Visuals.Visual as Visual import Data.IORef ( IORef, newIORef, readIORef, modifyIORef ) import qualified Drool.Utils.RenderHelpers as RH ( RenderSettings(..), color4MulAlpha ) import qualified Drool.ApplicationContext as AC ( ContextSettings(..), MaterialConfig(..) ) import qualified Drool.Utils.SigGen as SigGen ( SignalGenerator(..) ) import Drool.Utils.FeatureExtraction as FE ( SignalFeatures(..), SignalFeaturesList(..), FeatureTarget(..), featureTargetFromIndex ) import Graphics.UI.GLUT ( Object(Sphere'), renderObject, Flavour(..) ) import Graphics.Rendering.OpenGL as GL ( ($=), GLfloat, Face(..), materialEmission, materialAmbient, materialDiffuse, materialSpecular, materialShininess, colorMaterial, ColorMaterialParameter(..) ) -- }}} data DiscoState = DiscoState { contextSettings :: AC.ContextSettings, renderSettings :: RH.RenderSettings, gridMaterial :: AC.MaterialConfig, surfaceMaterial :: AC.MaterialConfig, gridOpacity :: GLfloat, surfaceOpacity :: GLfloat, radius :: GLfloat, numSamples :: Int } instance VState DiscoState where vsRenderSettings = renderSettings -- Hook Visual state IORef to concrete implementations: newDiscoVisual :: IORef AC.ContextSettings -> IORef DiscoState -> Visual newDiscoVisual contextSettingsIORef stateIORef = Visual { dimensions = spheresDimensions stateIORef, update = spheresUpdate contextSettingsIORef stateIORef, render = spheresRender stateIORef } newDiscoState :: IORef AC.ContextSettings -> IO DiscoState -- {{{ newDiscoState cSettingsIORef = do cSettings <- readIORef cSettingsIORef let settings = DiscoState { contextSettings = cSettings, renderSettings = undefined, gridMaterial = undefined, surfaceMaterial = undefined, gridOpacity = undefined, surfaceOpacity = undefined, radius = 1, numSamples = 0 } return settings -- }}} spheresDimensions :: IORef DiscoState -> IO (GLfloat,GLfloat,GLfloat) -- {{{ spheresDimensions visualIORef = do visual <- readIORef $ visualIORef let width = r * 2.0 height = r * 2.0 depth = r * 2.0 r = radius visual return (width,height,depth) -- }}} spheresUpdate :: IORef AC.ContextSettings -> IORef DiscoState -> RH.RenderSettings -> Int -> IO () -- {{{ spheresUpdate cSettingsIORef visualIORef rSettings t = do cSettings <- readIORef cSettingsIORef visualPrev <- readIORef visualIORef let target = FE.LocalTarget fBuf <- readIORef $ RH.featuresBuf rSettings let features = head (FE.signalFeaturesList fBuf) let loudness = realToFrac $ FE.totalEnergy features basslevel = realToFrac $ FE.bassEnergy features lTarget = FE.featureTargetFromIndex $ AC.featureSignalEnergyTargetIdx cSettings bTarget = FE.featureTargetFromIndex $ AC.featureBassEnergyTargetIdx cSettings lCoeff = if lTarget == target || lTarget == FE.GlobalAndLocalTarget then ( realToFrac $ AC.featureSignalEnergyGridCoeff cSettings ) else 0.0 bCoeff = if bTarget == target || bTarget == FE.GlobalAndLocalTarget then ( realToFrac $ AC.featureBassEnergyGridCoeff cSettings ) else 0.0 let gBaseOpacity = (AC.gridOpacity cSettings) / 100.0 :: GLfloat gOpacity = gBaseOpacity + (lCoeff * loudness) + (bCoeff * basslevel) gMaterial = AC.gridMaterial cSettings let sBaseOpacity = (AC.surfaceOpacity cSettings) / 100.0 :: GLfloat sOpacity = sBaseOpacity + (lCoeff * loudness) + (bCoeff * basslevel) sMaterial = AC.surfaceMaterial cSettings let newRadius = realToFrac $ 0.3 + (lCoeff * loudness) + (bCoeff * basslevel) let sigGen = RH.signalGenerator rSettings let nSamples = SigGen.numSamples sigGen let visual = visualPrev { renderSettings = rSettings, contextSettings = cSettings, gridMaterial = gMaterial, surfaceMaterial = sMaterial, gridOpacity = gOpacity, surfaceOpacity = sOpacity, radius = newRadius, numSamples = nSamples } modifyIORef visualIORef ( \_ -> visual ) return () -- }}} spheresRender :: IORef DiscoState -> IO () -- {{{ spheresRender visualIORef = do visual <- readIORef visualIORef let r = realToFrac $ radius visual gMaterial = gridMaterial visual gOpacity = gridOpacity visual sMaterial = surfaceMaterial visual sOpacity = surfaceOpacity visual materialAmbient FrontAndBack $= RH.color4MulAlpha (AC.materialAmbient sMaterial) sOpacity materialDiffuse FrontAndBack $= RH.color4MulAlpha (AC.materialDiffuse sMaterial) sOpacity materialSpecular FrontAndBack $= RH.color4MulAlpha (AC.materialSpecular sMaterial) sOpacity materialEmission FrontAndBack $= RH.color4MulAlpha (AC.materialEmission sMaterial) sOpacity materialShininess FrontAndBack $= AC.materialShininess sMaterial renderObject Solid (Sphere' r 50 50) materialAmbient FrontAndBack $= RH.color4MulAlpha (AC.materialAmbient gMaterial) gOpacity materialDiffuse FrontAndBack $= RH.color4MulAlpha (AC.materialDiffuse gMaterial) gOpacity materialSpecular FrontAndBack $= RH.color4MulAlpha (AC.materialSpecular gMaterial) gOpacity materialEmission FrontAndBack $= RH.color4MulAlpha (AC.materialEmission gMaterial) gOpacity materialShininess FrontAndBack $= AC.materialShininess gMaterial renderObject Wireframe (Sphere' (r * 1.01) 40 40) -- }}}
null
https://raw.githubusercontent.com/fuchsto/drool/d9318c641a6a94a8450b5118db7b3213a93209ea/src/Drool/UI/Visuals/Disco.hs
haskell
--------------------------------------------------------------------------- Module : Drool.UI.Visuals.Disco Maintainer : Stability : experimental Portability : POSIX | --------------------------------------------------------------------------- # OPTIONS -O2 -Wall # hidden type constructor Imports {{{ }}} Hook Visual state IORef to concrete implementations: {{{ }}} {{{ }}} {{{ }}} {{{ }}}
Copyright : License : MIT module Drool.UI.Visuals.Disco ( newDiscoVisual, newDiscoState ) where import Drool.UI.Visuals.Visual as Visual import Data.IORef ( IORef, newIORef, readIORef, modifyIORef ) import qualified Drool.Utils.RenderHelpers as RH ( RenderSettings(..), color4MulAlpha ) import qualified Drool.ApplicationContext as AC ( ContextSettings(..), MaterialConfig(..) ) import qualified Drool.Utils.SigGen as SigGen ( SignalGenerator(..) ) import Drool.Utils.FeatureExtraction as FE ( SignalFeatures(..), SignalFeaturesList(..), FeatureTarget(..), featureTargetFromIndex ) import Graphics.UI.GLUT ( Object(Sphere'), renderObject, Flavour(..) ) import Graphics.Rendering.OpenGL as GL ( ($=), GLfloat, Face(..), materialEmission, materialAmbient, materialDiffuse, materialSpecular, materialShininess, colorMaterial, ColorMaterialParameter(..) ) data DiscoState = DiscoState { contextSettings :: AC.ContextSettings, renderSettings :: RH.RenderSettings, gridMaterial :: AC.MaterialConfig, surfaceMaterial :: AC.MaterialConfig, gridOpacity :: GLfloat, surfaceOpacity :: GLfloat, radius :: GLfloat, numSamples :: Int } instance VState DiscoState where vsRenderSettings = renderSettings newDiscoVisual :: IORef AC.ContextSettings -> IORef DiscoState -> Visual newDiscoVisual contextSettingsIORef stateIORef = Visual { dimensions = spheresDimensions stateIORef, update = spheresUpdate contextSettingsIORef stateIORef, render = spheresRender stateIORef } newDiscoState :: IORef AC.ContextSettings -> IO DiscoState newDiscoState cSettingsIORef = do cSettings <- readIORef cSettingsIORef let settings = DiscoState { contextSettings = cSettings, renderSettings = undefined, gridMaterial = undefined, surfaceMaterial = undefined, gridOpacity = undefined, surfaceOpacity = undefined, radius = 1, numSamples = 0 } return settings spheresDimensions :: IORef DiscoState -> IO (GLfloat,GLfloat,GLfloat) spheresDimensions visualIORef = do visual <- readIORef $ visualIORef let width = r * 2.0 height = r * 2.0 depth = r * 2.0 r = radius visual return (width,height,depth) spheresUpdate :: IORef AC.ContextSettings -> IORef DiscoState -> RH.RenderSettings -> Int -> IO () spheresUpdate cSettingsIORef visualIORef rSettings t = do cSettings <- readIORef cSettingsIORef visualPrev <- readIORef visualIORef let target = FE.LocalTarget fBuf <- readIORef $ RH.featuresBuf rSettings let features = head (FE.signalFeaturesList fBuf) let loudness = realToFrac $ FE.totalEnergy features basslevel = realToFrac $ FE.bassEnergy features lTarget = FE.featureTargetFromIndex $ AC.featureSignalEnergyTargetIdx cSettings bTarget = FE.featureTargetFromIndex $ AC.featureBassEnergyTargetIdx cSettings lCoeff = if lTarget == target || lTarget == FE.GlobalAndLocalTarget then ( realToFrac $ AC.featureSignalEnergyGridCoeff cSettings ) else 0.0 bCoeff = if bTarget == target || bTarget == FE.GlobalAndLocalTarget then ( realToFrac $ AC.featureBassEnergyGridCoeff cSettings ) else 0.0 let gBaseOpacity = (AC.gridOpacity cSettings) / 100.0 :: GLfloat gOpacity = gBaseOpacity + (lCoeff * loudness) + (bCoeff * basslevel) gMaterial = AC.gridMaterial cSettings let sBaseOpacity = (AC.surfaceOpacity cSettings) / 100.0 :: GLfloat sOpacity = sBaseOpacity + (lCoeff * loudness) + (bCoeff * basslevel) sMaterial = AC.surfaceMaterial cSettings let newRadius = realToFrac $ 0.3 + (lCoeff * loudness) + (bCoeff * basslevel) let sigGen = RH.signalGenerator rSettings let nSamples = SigGen.numSamples sigGen let visual = visualPrev { renderSettings = rSettings, contextSettings = cSettings, gridMaterial = gMaterial, surfaceMaterial = sMaterial, gridOpacity = gOpacity, surfaceOpacity = sOpacity, radius = newRadius, numSamples = nSamples } modifyIORef visualIORef ( \_ -> visual ) return () spheresRender :: IORef DiscoState -> IO () spheresRender visualIORef = do visual <- readIORef visualIORef let r = realToFrac $ radius visual gMaterial = gridMaterial visual gOpacity = gridOpacity visual sMaterial = surfaceMaterial visual sOpacity = surfaceOpacity visual materialAmbient FrontAndBack $= RH.color4MulAlpha (AC.materialAmbient sMaterial) sOpacity materialDiffuse FrontAndBack $= RH.color4MulAlpha (AC.materialDiffuse sMaterial) sOpacity materialSpecular FrontAndBack $= RH.color4MulAlpha (AC.materialSpecular sMaterial) sOpacity materialEmission FrontAndBack $= RH.color4MulAlpha (AC.materialEmission sMaterial) sOpacity materialShininess FrontAndBack $= AC.materialShininess sMaterial renderObject Solid (Sphere' r 50 50) materialAmbient FrontAndBack $= RH.color4MulAlpha (AC.materialAmbient gMaterial) gOpacity materialDiffuse FrontAndBack $= RH.color4MulAlpha (AC.materialDiffuse gMaterial) gOpacity materialSpecular FrontAndBack $= RH.color4MulAlpha (AC.materialSpecular gMaterial) gOpacity materialEmission FrontAndBack $= RH.color4MulAlpha (AC.materialEmission gMaterial) gOpacity materialShininess FrontAndBack $= AC.materialShininess gMaterial renderObject Wireframe (Sphere' (r * 1.01) 40 40)
1f14dfe2a71f978fb689bd14e86c68b2e09c1801c38c0de847425c6b242b8eb6
flipstone/orville
Conduit.hs
| Module : Database . Orville . PostgreSQL.Conduit Copyright : Flipstone Technology Partners 2016 - 2018 License : MIT Module : Database.Orville.PostgreSQL.Conduit Copyright : Flipstone Technology Partners 2016-2018 License : MIT -} # LANGUAGE CPP # module Database.Orville.PostgreSQL.Conduit ( selectConduit #if MIN_VERSION_conduit(1,3,0) , streamPages #endif ) where ! ! ! WARNING ! ! ! Basically this entire file is forked using conditional compilation on the version of conduit that is being used . Only ' feedRows ' is shared below , and even that needs a different type signature . If you 're changing this file , you should probably take the time to run some earlier LTS versions to double check that conduit support works correctly with different library versions . !!! WARNING !!! Basically this entire file is forked using conditional compilation on the version of conduit that is being used. Only 'feedRows' is shared below, and even that needs a different type signature. If you're changing this file, you should probably take the time to run some earlier LTS versions to double check that conduit support works correctly with different library versions. -} #if MIN_VERSION_conduit(1,3,0) import Conduit ( Acquire , ReleaseType(..) , allocateAcquire , mkAcquire , mkAcquireType , yieldMany ) import Control.Monad (void) import Control.Monad.Catch import Control.Monad.Trans import Control.Monad.Trans.Resource (MonadResource, release) import Data.Conduit import Data.Pool import Database.HDBC hiding (withTransaction) import Database.Orville.PostgreSQL.Internal.Monad import Database.Orville.PostgreSQL.Internal.Select import Database.Orville.PostgreSQL.Internal.Types import Database.Orville.PostgreSQL.Internal.Where import Database.Orville.PostgreSQL.Pagination (Pagination(..), buildPagination) | ' selectConduit ' provides a way to stream the results of a ' Select ' query from the database one by one using the conduit library . You can ' fuse ' the conduit built by this function with your own conduit pipeline to handle rows individually in whatever fashion you need ( e.g. turning them into rows of CSV ) . This is useful if you want to be able to process many rows one by one . You can aggregate the results however you require as part of the conduit processing and then use ' runConduit ' ( or ' runConduitRes ' ) from the conduit library to execute the processing pipeline . Alternatively , your web server ( ' wai ' , ' servant ' , etc ) may provide support for converting a conduit into a streaming HTTP response . Beware : this function must load all the results into memory before streaming can begin . For why , see -single-row-mode.html . If memory use is a concern , try ' streamPages ' instead . 'selectConduit' provides a way to stream the results of a 'Select' query from the database one by one using the conduit library. You can 'fuse' the conduit built by this function with your own conduit pipeline to handle rows individually in whatever fashion you need (e.g. turning them into rows of CSV). This is useful if you want to be able to process many rows one by one. You can aggregate the results however you require as part of the conduit processing and then use 'runConduit' (or 'runConduitRes') from the conduit library to execute the processing pipeline. Alternatively, your web server ('wai', 'servant', etc) may provide support for converting a conduit into a streaming HTTP response. Beware: this function must load all the results into memory before streaming can begin. For why, see -single-row-mode.html. If memory use is a concern, try 'streamPages' instead. -} selectConduit :: (Monad m, MonadOrville conn m, MonadCatch m, MonadResource m) => Select row -> ConduitT () row m () selectConduit select = do pool <- ormEnvPool <$> lift getOrvilleEnv (releaseKey, query) <- allocateAcquire (acquireStatement pool (selectSql select)) void $ liftIO $ execute query $ selectValues select result <- feedRows (selectBuilder select) query -- Note this doesn't use finally to release this, but it will be released -- automatically at the end of runResourceT. finally cannot be used here because Conduit does n't offer MonadMask . Alternatively we could use -- withAllocate here, but that would require an UNLiftIO instance release releaseKey pure result acquireConnection :: Pool conn -> Acquire conn acquireConnection pool = fst <$> mkAcquireType (takeResource pool) releaseConnection where releaseConnection (conn, local) releaseType = case releaseType of ReleaseEarly -> putResource local conn ReleaseNormal -> putResource local conn ReleaseException -> destroyResource pool local conn acquireStatement :: IConnection conn => Pool conn -> String -> Acquire Statement acquireStatement pool sql = do conn <- acquireConnection pool mkAcquire (prepare conn sql) finish #else import qualified Control.Exception as E import Control.Monad import Control.Monad.Catch import Control.Monad.Trans import Data.Conduit import Data.IORef import Data.Pool import Database.HDBC hiding (withTransaction) import Database.Orville.PostgreSQL.Internal.Monad import Database.Orville.PostgreSQL.Internal.Select import Database.Orville.PostgreSQL.Internal.Types -- All the masking manual cleanup in this function amounts to a -- poor man's ResourceT that I *hope* is correct. The constraints -- hat lead to this are: -- -- * The immediate purpose of conduit queries to to provide streaming responses in a Happstack App -- * does not offer a side - effect controlled streaming response solution at the moment . It relies in Lazy Bytestrings -- -- * The conduit lazy consume specifically warns that you need to -- ensure you consume the whole list before ResourceT returns, which I can not guarantee in ( in fact , I believe it -- specifically will *not* happen that way) -- * Data . Pool.withResource depends on MonadBaseControl , which Conduit does not offer -- * also does not offer MonadMask , so I can not use -- mask/restore in the normal way -- -- So, we instead we mask exceptions while registering cleanup and -- finish actions in vars while masked and then ensure those vars -- are read and executed at the appropriate times. -- -- Beware: this function must load all the results into memory before streaming -- can begin. For why, see -single-row-mode.html. If memory use is a concern , try ' streamPages ' instead . selectConduit :: (Monad m, MonadOrville conn m, MonadCatch m) => Select row -> Source m row selectConduit select = do pool <- ormEnvPool <$> lift getOrvilleEnv cleanupRef <- liftIO $ newIORef (pure ()) finishRef <- liftIO $ newIORef (pure ()) let acquire = lift $ liftIO $ E.mask_ $ do (conn, local) <- takeResource pool writeIORef cleanupRef $ destroyResource pool local conn writeIORef finishRef $ putResource local conn pure conn runCleanup = liftIO $ join (readIORef cleanupRef) runFinish = liftIO $ join (readIORef finishRef) go = do conn <- acquire query <- liftIO $ prepare conn $ selectSql select addCleanup (const $ liftIO $ finish $ query) $ do void $ liftIO $ execute query $ selectValues select feedRows (selectBuilder select) query result <- go `onException` runCleanup runFinish pure result #endif feedRows :: #if MIN_VERSION_conduit(1,3,0) (Monad m, MonadIO m) => FromSql row -> Statement -> ConduitT () row m () #else (Monad m, MonadIO m) => FromSql row -> Statement -> Source m row #endif feedRows builder query = do row <- liftIO $ fetchRowAL query case runFromSql builder <$> row of Nothing -> pure () Just (Left _) -> pure () Just (Right r) -> yield r >> feedRows builder query #if MIN_VERSION_conduit(1,3,0) | Build a conduit source that is fed by querying one page worth of results at a time . When the last row of the last page is consumed , the stream ends . streamPages :: (MonadOrville conn m, Bounded orderField, Enum orderField) => TableDefinition readEnt write key -> FieldDefinition NotNull orderField -> (readEnt -> orderField) -> Maybe WhereCondition -> Word -- ^ number of rows fetched per page -> ConduitT () readEnt m () streamPages tableDef orderField getOrderField mbWhereCond pageSize = loop =<< lift (buildPagination tableDef orderField getOrderField mbWhereCond pageSize) where loop pagination = do yieldMany (pageRows pagination) case pageNext pagination of Nothing -> pure () Just nxtPage -> loop =<< lift nxtPage #endif
null
https://raw.githubusercontent.com/flipstone/orville/aee8d7a47ab3a7b442fdb274dbb5a95d687a23ce/orville-postgresql/src/Database/Orville/PostgreSQL/Conduit.hs
haskell
Note this doesn't use finally to release this, but it will be released automatically at the end of runResourceT. finally cannot be used here withAllocate here, but that would require an UNLiftIO instance All the masking manual cleanup in this function amounts to a poor man's ResourceT that I *hope* is correct. The constraints hat lead to this are: * The immediate purpose of conduit queries to to provide streaming * The conduit lazy consume specifically warns that you need to ensure you consume the whole list before ResourceT returns, specifically will *not* happen that way) mask/restore in the normal way So, we instead we mask exceptions while registering cleanup and finish actions in vars while masked and then ensure those vars are read and executed at the appropriate times. Beware: this function must load all the results into memory before streaming can begin. For why, see -single-row-mode.html. ^ number of rows fetched per page
| Module : Database . Orville . PostgreSQL.Conduit Copyright : Flipstone Technology Partners 2016 - 2018 License : MIT Module : Database.Orville.PostgreSQL.Conduit Copyright : Flipstone Technology Partners 2016-2018 License : MIT -} # LANGUAGE CPP # module Database.Orville.PostgreSQL.Conduit ( selectConduit #if MIN_VERSION_conduit(1,3,0) , streamPages #endif ) where ! ! ! WARNING ! ! ! Basically this entire file is forked using conditional compilation on the version of conduit that is being used . Only ' feedRows ' is shared below , and even that needs a different type signature . If you 're changing this file , you should probably take the time to run some earlier LTS versions to double check that conduit support works correctly with different library versions . !!! WARNING !!! Basically this entire file is forked using conditional compilation on the version of conduit that is being used. Only 'feedRows' is shared below, and even that needs a different type signature. If you're changing this file, you should probably take the time to run some earlier LTS versions to double check that conduit support works correctly with different library versions. -} #if MIN_VERSION_conduit(1,3,0) import Conduit ( Acquire , ReleaseType(..) , allocateAcquire , mkAcquire , mkAcquireType , yieldMany ) import Control.Monad (void) import Control.Monad.Catch import Control.Monad.Trans import Control.Monad.Trans.Resource (MonadResource, release) import Data.Conduit import Data.Pool import Database.HDBC hiding (withTransaction) import Database.Orville.PostgreSQL.Internal.Monad import Database.Orville.PostgreSQL.Internal.Select import Database.Orville.PostgreSQL.Internal.Types import Database.Orville.PostgreSQL.Internal.Where import Database.Orville.PostgreSQL.Pagination (Pagination(..), buildPagination) | ' selectConduit ' provides a way to stream the results of a ' Select ' query from the database one by one using the conduit library . You can ' fuse ' the conduit built by this function with your own conduit pipeline to handle rows individually in whatever fashion you need ( e.g. turning them into rows of CSV ) . This is useful if you want to be able to process many rows one by one . You can aggregate the results however you require as part of the conduit processing and then use ' runConduit ' ( or ' runConduitRes ' ) from the conduit library to execute the processing pipeline . Alternatively , your web server ( ' wai ' , ' servant ' , etc ) may provide support for converting a conduit into a streaming HTTP response . Beware : this function must load all the results into memory before streaming can begin . For why , see -single-row-mode.html . If memory use is a concern , try ' streamPages ' instead . 'selectConduit' provides a way to stream the results of a 'Select' query from the database one by one using the conduit library. You can 'fuse' the conduit built by this function with your own conduit pipeline to handle rows individually in whatever fashion you need (e.g. turning them into rows of CSV). This is useful if you want to be able to process many rows one by one. You can aggregate the results however you require as part of the conduit processing and then use 'runConduit' (or 'runConduitRes') from the conduit library to execute the processing pipeline. Alternatively, your web server ('wai', 'servant', etc) may provide support for converting a conduit into a streaming HTTP response. Beware: this function must load all the results into memory before streaming can begin. For why, see -single-row-mode.html. If memory use is a concern, try 'streamPages' instead. -} selectConduit :: (Monad m, MonadOrville conn m, MonadCatch m, MonadResource m) => Select row -> ConduitT () row m () selectConduit select = do pool <- ormEnvPool <$> lift getOrvilleEnv (releaseKey, query) <- allocateAcquire (acquireStatement pool (selectSql select)) void $ liftIO $ execute query $ selectValues select result <- feedRows (selectBuilder select) query because Conduit does n't offer MonadMask . Alternatively we could use release releaseKey pure result acquireConnection :: Pool conn -> Acquire conn acquireConnection pool = fst <$> mkAcquireType (takeResource pool) releaseConnection where releaseConnection (conn, local) releaseType = case releaseType of ReleaseEarly -> putResource local conn ReleaseNormal -> putResource local conn ReleaseException -> destroyResource pool local conn acquireStatement :: IConnection conn => Pool conn -> String -> Acquire Statement acquireStatement pool sql = do conn <- acquireConnection pool mkAcquire (prepare conn sql) finish #else import qualified Control.Exception as E import Control.Monad import Control.Monad.Catch import Control.Monad.Trans import Data.Conduit import Data.IORef import Data.Pool import Database.HDBC hiding (withTransaction) import Database.Orville.PostgreSQL.Internal.Monad import Database.Orville.PostgreSQL.Internal.Select import Database.Orville.PostgreSQL.Internal.Types responses in a Happstack App * does not offer a side - effect controlled streaming response solution at the moment . It relies in Lazy Bytestrings which I can not guarantee in ( in fact , I believe it * Data . Pool.withResource depends on MonadBaseControl , which Conduit does not offer * also does not offer MonadMask , so I can not use If memory use is a concern , try ' streamPages ' instead . selectConduit :: (Monad m, MonadOrville conn m, MonadCatch m) => Select row -> Source m row selectConduit select = do pool <- ormEnvPool <$> lift getOrvilleEnv cleanupRef <- liftIO $ newIORef (pure ()) finishRef <- liftIO $ newIORef (pure ()) let acquire = lift $ liftIO $ E.mask_ $ do (conn, local) <- takeResource pool writeIORef cleanupRef $ destroyResource pool local conn writeIORef finishRef $ putResource local conn pure conn runCleanup = liftIO $ join (readIORef cleanupRef) runFinish = liftIO $ join (readIORef finishRef) go = do conn <- acquire query <- liftIO $ prepare conn $ selectSql select addCleanup (const $ liftIO $ finish $ query) $ do void $ liftIO $ execute query $ selectValues select feedRows (selectBuilder select) query result <- go `onException` runCleanup runFinish pure result #endif feedRows :: #if MIN_VERSION_conduit(1,3,0) (Monad m, MonadIO m) => FromSql row -> Statement -> ConduitT () row m () #else (Monad m, MonadIO m) => FromSql row -> Statement -> Source m row #endif feedRows builder query = do row <- liftIO $ fetchRowAL query case runFromSql builder <$> row of Nothing -> pure () Just (Left _) -> pure () Just (Right r) -> yield r >> feedRows builder query #if MIN_VERSION_conduit(1,3,0) | Build a conduit source that is fed by querying one page worth of results at a time . When the last row of the last page is consumed , the stream ends . streamPages :: (MonadOrville conn m, Bounded orderField, Enum orderField) => TableDefinition readEnt write key -> FieldDefinition NotNull orderField -> (readEnt -> orderField) -> Maybe WhereCondition -> ConduitT () readEnt m () streamPages tableDef orderField getOrderField mbWhereCond pageSize = loop =<< lift (buildPagination tableDef orderField getOrderField mbWhereCond pageSize) where loop pagination = do yieldMany (pageRows pagination) case pageNext pagination of Nothing -> pure () Just nxtPage -> loop =<< lift nxtPage #endif
57e46575ec0f3d275a258e5780c2f68654b1959aaa13d053da4b756ef294733c
opencog/pln
amusing-friend-bc.scm
Like moses-pln-synergy-pm.scm but relies on the backward chainer . ;; Set logger to DEBUG ;; (ure-logger-set-sync! #t) ;; (ure-logger-set-stdout! #t) (ure-logger-set-level! "debug") ;; Load the background knowledge (load "kb.scm") ;; Load the PLN configuration for this demo (load "pln-bc-config.scm") Run the BC on each steps as described in amusing-friend-pm.scm , for ;; debugging. ;; (define step-1 ;; (Evaluation ;; (Predicate "is-honest") ( Concept " " ) ) ;; ) ( pln - bc step-1 ) ;; (define step-2 ;; (Implication ;; (Lambda ( VariableList ( TypedVariable ;; (Variable "$X") ( Type " ConceptNode " ) ) ( TypedVariable ;; (Variable "$Y") ( Type " ConceptNode " ) ) ) ;; (Evaluation ;; (Predicate "will-be-friends") ;; (List ;; (Variable "$X") ;; (Variable "$Y")))) ;; (Lambda ( VariableList ( TypedVariable ;; (Variable "$X") ( Type " ConceptNode " ) ) ( TypedVariable ;; (Variable "$Y") ( Type " ConceptNode " ) ) ) ;; (And ;; (Evaluation ;; (Predicate "is-honest") ;; (Variable "$X")) ;; (Evaluation ;; (Predicate "is-honest") ;; (Variable "$Y"))))) ;; ) ( pln - bc step-2 ) ( define step-3 ;; (Lambda ( VariableList ( ;; (Variable "$X") ( Type " ConceptNode " ) ) ( ;; (Variable "$Y") ( Type " ConceptNode " ) ) ) ;; (Evaluation ;; (Predicate "will-be-friends") ;; (List ;; (Variable "$X") ;; (Variable "$Y")))) ;; ) ( pln - bc step-3 ) ;; ;; Skipped for now ( define step-4 ;; (Lambda ( VariableList ;; (TypedVariable ;; (Variable "$X") ( Type " ConceptNode " ) ) ;; (TypedVariable ;; (Variable "$Y") ( Type " ConceptNode " ) ) ) ;; (And ;; (Evaluation ;; (Predicate "is-honest") ;; (Variable "$X")) ;; (Evaluation ;; (Predicate "is-honest") ;; (Variable "$Y")))) ;; ) ( pln - bc step-4 ) ;; (define step-5 ;; (Implication ;; (Lambda ( VariableList ( TypedVariable ;; (Variable "$X") ( Type " ConceptNode " ) ) ( TypedVariable ;; (Variable "$Y") ( Type " ConceptNode " ) ) ) ;; (And ;; (Evaluation ;; (Predicate "is-honest") ;; (Variable "$X")) ;; (Evaluation ;; (Predicate "is-honest") ;; (Variable "$Y")))) ;; (Lambda ( VariableList ( TypedVariable ;; (Variable "$X") ( Type " ConceptNode " ) ) ( TypedVariable ;; (Variable "$Y") ( Type " ConceptNode " ) ) ) ;; (Evaluation ;; (Predicate "will-be-friends") ;; (List ;; (Variable "$X") ;; (Variable "$Y"))))) ;; ) ( pln - bc step-5 ) ;; (define step-6 ;; (Implication ( LambdaLink ( VariableList ( TypedVariable ;; (Variable "$X") ( Type " ConceptNode " ) ) ( TypedVariable ;; (Variable "$Y") ( Type " ConceptNode " ) ) ) ;; (And ;; (Inheritance ;; (Variable "$X") ;; (Concept "human")) ;; (Inheritance ;; (Variable "$Y") ;; (Concept "human")) ;; (Evaluation ;; (Predicate "acquainted") ;; (List ;; (Variable "$X") ;; (Variable "$Y"))))) ( LambdaLink ( VariableList ( TypedVariable ;; (Variable "$X") ( Type " ConceptNode " ) ) ( TypedVariable ;; (Variable "$Y") ( Type " ConceptNode " ) ) ) ;; (Evaluation ;; (Predicate "will-be-friends") ;; (List ;; (Variable "$X") ;; (Variable "$Y"))))) ;; ) ( pln - bc step-6 ) ;; (define step-7 ( ImplicationLink ( AndLink ( LambdaLink ( VariableList ;; (TypedVariableLink ( VariableNode " $ X " ) ( " ConceptNode " ) ;; ) ;; (TypedVariableLink ( VariableNode " $ Y " ) ( " ConceptNode " ) ;; ) ;; ) ( AndLink ( EvaluationLink ( PredicateNode " is - honest " ) ( VariableNode " $ X " ) ;; ) ( EvaluationLink ( PredicateNode " is - honest " ) ( VariableNode " $ Y " ) ;; ) ;; ) ;; ) ( LambdaLink ( VariableList ;; (TypedVariableLink ( VariableNode " $ X " ) ( " ConceptNode " ) ;; ) ;; (TypedVariableLink ( VariableNode " $ Y " ) ( " ConceptNode " ) ;; ) ;; ) ( AndLink ( InheritanceLink ( VariableNode " $ X " ) ( ConceptNode " human " ) ;; ) ( InheritanceLink ( VariableNode " $ Y " ) ( ConceptNode " human " ) ;; ) ( EvaluationLink ( PredicateNode " acquainted " ) ( ( VariableNode " $ X " ) ( VariableNode " $ Y " ) ;; ) ;; ) ;; ) ;; ) ;; ) ( LambdaLink ( VariableList ;; (TypedVariableLink ( VariableNode " $ X " ) ( " ConceptNode " ) ;; ) ;; (TypedVariableLink ( VariableNode " $ Y " ) ( " ConceptNode " ) ;; ) ;; ) ;; (EvaluationLink ( PredicateNode " will - be - friends " ) ( ( VariableNode " $ X " ) ( VariableNode " $ Y " ) ) ) ) ) ;; ) ( pln - bc step-7 ) ;; (define step-8 ( ImplicationLink ( LambdaLink ( VariableList ;; (TypedVariableLink ( VariableNode " $ X " ) ( " ConceptNode " ) ;; ) ;; (TypedVariableLink ( VariableNode " $ Y " ) ( " ConceptNode " ) ;; ) ;; ) ( AndLink ;; (EvaluationLink ( PredicateNode " is - honest " ) ( VariableNode " $ X " ) ;; ) ;; (EvaluationLink ( PredicateNode " is - honest " ) ( VariableNode " $ Y " ) ;; ) ( InheritanceLink ( VariableNode " $ X " ) ( ConceptNode " human " ) ;; ) ( InheritanceLink ( VariableNode " $ Y " ) ( ConceptNode " human " ) ;; ) ;; (EvaluationLink ( PredicateNode " acquainted " ) ( ( VariableNode " $ X " ) ( VariableNode " $ Y " ) ;; ) ;; ) ;; ) ;; ) ( AndLink ( LambdaLink ( VariableList ;; (TypedVariableLink ( VariableNode " $ X " ) ( " ConceptNode " ) ;; ) ;; (TypedVariableLink ( VariableNode " $ Y " ) ( " ConceptNode " ) ;; ) ;; ) ( AndLink ( EvaluationLink ( PredicateNode " is - honest " ) ( VariableNode " $ X " ) ;; ) ( EvaluationLink ( PredicateNode " is - honest " ) ( VariableNode " $ Y " ) ;; ) ;; ) ;; ) ( LambdaLink ( VariableList ;; (TypedVariableLink ( VariableNode " $ X " ) ( " ConceptNode " ) ;; ) ;; (TypedVariableLink ( VariableNode " $ Y " ) ( " ConceptNode " ) ;; ) ;; ) ( AndLink ( InheritanceLink ( VariableNode " $ X " ) ( ConceptNode " human " ) ;; ) ( InheritanceLink ( VariableNode " $ Y " ) ( ConceptNode " human " ) ;; ) ( EvaluationLink ( PredicateNode " acquainted " ) ( ( VariableNode " $ X " ) ( VariableNode " $ Y " ) ) ) ) ) ) ) ;; ) ( pln - bc step-8 ) ;; For step-8, rather than defining a hacky rule for this we paste it ;; here as axiom. Later this will have to be replaced by scheme ;; generated higher order facts. (ImplicationLink (stv 1 1) (LambdaLink (VariableList (TypedVariableLink (VariableNode "$X") (TypeNode "ConceptNode") ) (TypedVariableLink (VariableNode "$Y") (TypeNode "ConceptNode") ) ) (AndLink (EvaluationLink (PredicateNode "is-honest") (VariableNode "$X") ) (EvaluationLink (PredicateNode "is-honest") (VariableNode "$Y") ) (InheritanceLink (VariableNode "$X") (ConceptNode "human") ) (InheritanceLink (VariableNode "$Y") (ConceptNode "human") ) (EvaluationLink (PredicateNode "acquainted") (ListLink (VariableNode "$X") (VariableNode "$Y") ) ) ) ) (AndLink (LambdaLink (VariableList (TypedVariableLink (VariableNode "$X") (TypeNode "ConceptNode") ) (TypedVariableLink (VariableNode "$Y") (TypeNode "ConceptNode") ) ) (AndLink (EvaluationLink (PredicateNode "is-honest") (VariableNode "$X") ) (EvaluationLink (PredicateNode "is-honest") (VariableNode "$Y") ) ) ) (LambdaLink (VariableList (TypedVariableLink (VariableNode "$X") (TypeNode "ConceptNode") ) (TypedVariableLink (VariableNode "$Y") (TypeNode "ConceptNode") ) ) (AndLink (InheritanceLink (VariableNode "$X") (ConceptNode "human") ) (InheritanceLink (VariableNode "$Y") (ConceptNode "human") ) (EvaluationLink (PredicateNode "acquainted") (ListLink (VariableNode "$X") (VariableNode "$Y") ) ) ) ) ) ) (define step-9 (ImplicationLink (LambdaLink (VariableList (TypedVariableLink (VariableNode "$X") (TypeNode "ConceptNode") ) (TypedVariableLink (VariableNode "$Y") (TypeNode "ConceptNode") ) ) (AndLink (EvaluationLink (PredicateNode "is-honest") (VariableNode "$X") ) (EvaluationLink (PredicateNode "is-honest") (VariableNode "$Y") ) (InheritanceLink (VariableNode "$X") (ConceptNode "human") ) (InheritanceLink (VariableNode "$Y") (ConceptNode "human") ) (EvaluationLink (PredicateNode "acquainted") (ListLink (VariableNode "$X") (VariableNode "$Y") ) ) ) ) (LambdaLink (VariableList (TypedVariableLink (VariableNode "$X") (TypeNode "ConceptNode") ) (TypedVariableLink (VariableNode "$Y") (TypeNode "ConceptNode") ) ) (EvaluationLink (PredicateNode "will-be-friends") (ListLink (VariableNode "$X") (VariableNode "$Y") ) ) ) ) ) (pln-bc step-9) ;; (define target ;; (And ;; (Evaluation ;; (Predicate "will-be-friends") ;; (List ;; (Concept "Self") ;; (Variable "$friend"))) ;; (Evaluation ;; (Predicate "is-amusing") ;; (Variable "$friend")) ;; (Evaluation ;; (Predicate "is-honest") ;; (Variable "$friend"))) ;; ) ( pln - bc target )
null
https://raw.githubusercontent.com/opencog/pln/52dc099e21393892cf5529fef687a69682436b2d/examples/pln/amusing-friend/amusing-friend-bc.scm
scheme
Set logger to DEBUG (ure-logger-set-sync! #t) (ure-logger-set-stdout! #t) Load the background knowledge Load the PLN configuration for this demo debugging. (define step-1 (Evaluation (Predicate "is-honest") ) (define step-2 (Implication (Lambda (Variable "$X") (Variable "$Y") (Evaluation (Predicate "will-be-friends") (List (Variable "$X") (Variable "$Y")))) (Lambda (Variable "$X") (Variable "$Y") (And (Evaluation (Predicate "is-honest") (Variable "$X")) (Evaluation (Predicate "is-honest") (Variable "$Y"))))) ) (Lambda (Variable "$X") (Variable "$Y") (Evaluation (Predicate "will-be-friends") (List (Variable "$X") (Variable "$Y")))) ) ;; Skipped for now (Lambda (TypedVariable (Variable "$X") (TypedVariable (Variable "$Y") (And (Evaluation (Predicate "is-honest") (Variable "$X")) (Evaluation (Predicate "is-honest") (Variable "$Y")))) ) (define step-5 (Implication (Lambda (Variable "$X") (Variable "$Y") (And (Evaluation (Predicate "is-honest") (Variable "$X")) (Evaluation (Predicate "is-honest") (Variable "$Y")))) (Lambda (Variable "$X") (Variable "$Y") (Evaluation (Predicate "will-be-friends") (List (Variable "$X") (Variable "$Y"))))) ) (define step-6 (Implication (Variable "$X") (Variable "$Y") (And (Inheritance (Variable "$X") (Concept "human")) (Inheritance (Variable "$Y") (Concept "human")) (Evaluation (Predicate "acquainted") (List (Variable "$X") (Variable "$Y"))))) (Variable "$X") (Variable "$Y") (Evaluation (Predicate "will-be-friends") (List (Variable "$X") (Variable "$Y"))))) ) (define step-7 (TypedVariableLink ) (TypedVariableLink ) ) ) ) ) ) (TypedVariableLink ) (TypedVariableLink ) ) ) ) ) ) ) ) ) (TypedVariableLink ) (TypedVariableLink ) ) (EvaluationLink ) (define step-8 (TypedVariableLink ) (TypedVariableLink ) ) (EvaluationLink ) (EvaluationLink ) ) ) (EvaluationLink ) ) ) ) (TypedVariableLink ) (TypedVariableLink ) ) ) ) ) ) (TypedVariableLink ) (TypedVariableLink ) ) ) ) ) For step-8, rather than defining a hacky rule for this we paste it here as axiom. Later this will have to be replaced by scheme generated higher order facts. (define target (And (Evaluation (Predicate "will-be-friends") (List (Concept "Self") (Variable "$friend"))) (Evaluation (Predicate "is-amusing") (Variable "$friend")) (Evaluation (Predicate "is-honest") (Variable "$friend"))) )
Like moses-pln-synergy-pm.scm but relies on the backward chainer . (ure-logger-set-level! "debug") (load "kb.scm") (load "pln-bc-config.scm") Run the BC on each steps as described in amusing-friend-pm.scm , for ( Concept " " ) ) ( pln - bc step-1 ) ( VariableList ( TypedVariable ( Type " ConceptNode " ) ) ( TypedVariable ( Type " ConceptNode " ) ) ) ( VariableList ( TypedVariable ( Type " ConceptNode " ) ) ( TypedVariable ( Type " ConceptNode " ) ) ) ( pln - bc step-2 ) ( define step-3 ( VariableList ( ( Type " ConceptNode " ) ) ( ( Type " ConceptNode " ) ) ) ( pln - bc step-3 ) ( define step-4 ( VariableList ( Type " ConceptNode " ) ) ( Type " ConceptNode " ) ) ) ( pln - bc step-4 ) ( VariableList ( TypedVariable ( Type " ConceptNode " ) ) ( TypedVariable ( Type " ConceptNode " ) ) ) ( VariableList ( TypedVariable ( Type " ConceptNode " ) ) ( TypedVariable ( Type " ConceptNode " ) ) ) ( pln - bc step-5 ) ( LambdaLink ( VariableList ( TypedVariable ( Type " ConceptNode " ) ) ( TypedVariable ( Type " ConceptNode " ) ) ) ( LambdaLink ( VariableList ( TypedVariable ( Type " ConceptNode " ) ) ( TypedVariable ( Type " ConceptNode " ) ) ) ( pln - bc step-6 ) ( ImplicationLink ( AndLink ( LambdaLink ( VariableList ( VariableNode " $ X " ) ( " ConceptNode " ) ( VariableNode " $ Y " ) ( " ConceptNode " ) ( AndLink ( EvaluationLink ( PredicateNode " is - honest " ) ( VariableNode " $ X " ) ( EvaluationLink ( PredicateNode " is - honest " ) ( VariableNode " $ Y " ) ( LambdaLink ( VariableList ( VariableNode " $ X " ) ( " ConceptNode " ) ( VariableNode " $ Y " ) ( " ConceptNode " ) ( AndLink ( InheritanceLink ( VariableNode " $ X " ) ( ConceptNode " human " ) ( InheritanceLink ( VariableNode " $ Y " ) ( ConceptNode " human " ) ( EvaluationLink ( PredicateNode " acquainted " ) ( ( VariableNode " $ X " ) ( VariableNode " $ Y " ) ( LambdaLink ( VariableList ( VariableNode " $ X " ) ( " ConceptNode " ) ( VariableNode " $ Y " ) ( " ConceptNode " ) ( PredicateNode " will - be - friends " ) ( ( VariableNode " $ X " ) ( VariableNode " $ Y " ) ) ) ) ) ( pln - bc step-7 ) ( ImplicationLink ( LambdaLink ( VariableList ( VariableNode " $ X " ) ( " ConceptNode " ) ( VariableNode " $ Y " ) ( " ConceptNode " ) ( AndLink ( PredicateNode " is - honest " ) ( VariableNode " $ X " ) ( PredicateNode " is - honest " ) ( VariableNode " $ Y " ) ( InheritanceLink ( VariableNode " $ X " ) ( ConceptNode " human " ) ( InheritanceLink ( VariableNode " $ Y " ) ( ConceptNode " human " ) ( PredicateNode " acquainted " ) ( ( VariableNode " $ X " ) ( VariableNode " $ Y " ) ( AndLink ( LambdaLink ( VariableList ( VariableNode " $ X " ) ( " ConceptNode " ) ( VariableNode " $ Y " ) ( " ConceptNode " ) ( AndLink ( EvaluationLink ( PredicateNode " is - honest " ) ( VariableNode " $ X " ) ( EvaluationLink ( PredicateNode " is - honest " ) ( VariableNode " $ Y " ) ( LambdaLink ( VariableList ( VariableNode " $ X " ) ( " ConceptNode " ) ( VariableNode " $ Y " ) ( " ConceptNode " ) ( AndLink ( InheritanceLink ( VariableNode " $ X " ) ( ConceptNode " human " ) ( InheritanceLink ( VariableNode " $ Y " ) ( ConceptNode " human " ) ( EvaluationLink ( PredicateNode " acquainted " ) ( ( VariableNode " $ X " ) ( VariableNode " $ Y " ) ) ) ) ) ) ) ( pln - bc step-8 ) (ImplicationLink (stv 1 1) (LambdaLink (VariableList (TypedVariableLink (VariableNode "$X") (TypeNode "ConceptNode") ) (TypedVariableLink (VariableNode "$Y") (TypeNode "ConceptNode") ) ) (AndLink (EvaluationLink (PredicateNode "is-honest") (VariableNode "$X") ) (EvaluationLink (PredicateNode "is-honest") (VariableNode "$Y") ) (InheritanceLink (VariableNode "$X") (ConceptNode "human") ) (InheritanceLink (VariableNode "$Y") (ConceptNode "human") ) (EvaluationLink (PredicateNode "acquainted") (ListLink (VariableNode "$X") (VariableNode "$Y") ) ) ) ) (AndLink (LambdaLink (VariableList (TypedVariableLink (VariableNode "$X") (TypeNode "ConceptNode") ) (TypedVariableLink (VariableNode "$Y") (TypeNode "ConceptNode") ) ) (AndLink (EvaluationLink (PredicateNode "is-honest") (VariableNode "$X") ) (EvaluationLink (PredicateNode "is-honest") (VariableNode "$Y") ) ) ) (LambdaLink (VariableList (TypedVariableLink (VariableNode "$X") (TypeNode "ConceptNode") ) (TypedVariableLink (VariableNode "$Y") (TypeNode "ConceptNode") ) ) (AndLink (InheritanceLink (VariableNode "$X") (ConceptNode "human") ) (InheritanceLink (VariableNode "$Y") (ConceptNode "human") ) (EvaluationLink (PredicateNode "acquainted") (ListLink (VariableNode "$X") (VariableNode "$Y") ) ) ) ) ) ) (define step-9 (ImplicationLink (LambdaLink (VariableList (TypedVariableLink (VariableNode "$X") (TypeNode "ConceptNode") ) (TypedVariableLink (VariableNode "$Y") (TypeNode "ConceptNode") ) ) (AndLink (EvaluationLink (PredicateNode "is-honest") (VariableNode "$X") ) (EvaluationLink (PredicateNode "is-honest") (VariableNode "$Y") ) (InheritanceLink (VariableNode "$X") (ConceptNode "human") ) (InheritanceLink (VariableNode "$Y") (ConceptNode "human") ) (EvaluationLink (PredicateNode "acquainted") (ListLink (VariableNode "$X") (VariableNode "$Y") ) ) ) ) (LambdaLink (VariableList (TypedVariableLink (VariableNode "$X") (TypeNode "ConceptNode") ) (TypedVariableLink (VariableNode "$Y") (TypeNode "ConceptNode") ) ) (EvaluationLink (PredicateNode "will-be-friends") (ListLink (VariableNode "$X") (VariableNode "$Y") ) ) ) ) ) (pln-bc step-9) ( pln - bc target )
cc989e6bd68df35ba57c39cc0b09883f03833ea32088f8cb5a0a4b670c97d47d
duncanatt/detecter
cow_hpack.erl
Copyright ( c ) 2015 - 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. %% The current implementation is not suitable for use in %% intermediaries as the information about headers that %% should never be indexed is currently lost. -module(cow_hpack). -dialyzer(no_improper_lists). -export([init/0]). -export([init/1]). -export([set_max_size/2]). -export([decode/1]). -export([decode/2]). -export([encode/1]). -export([encode/2]). -export([encode/3]). -record(state, { size = 0 :: non_neg_integer(), max_size = 4096 :: non_neg_integer(), configured_max_size = 4096 :: non_neg_integer(), dyn_table = [] :: [{pos_integer(), {binary(), binary()}}] }). -opaque state() :: #state{}. -export_type([state/0]). -type opts() :: map(). -export_type([opts/0]). %%-ifdef(TEST). %%-include_lib("proper/include/proper.hrl"). %%-endif. State initialization . -spec init() -> state(). init() -> #state{}. -spec init(non_neg_integer()) -> state(). init(MaxSize) -> #state{max_size=MaxSize, configured_max_size=MaxSize}. %% Update the configured max size. %% %% When decoding, the local endpoint also needs to send a SETTINGS %% frame with this value and it is then up to the remote endpoint %% to decide what actual limit it will use. The actual limit is %% signaled via dynamic table size updates in the encoded data. %% %% When encoding, the local endpoint will call this function after %% receiving a SETTINGS frame with this value. The encoder will %% then use this value as the new max after signaling via a dynamic %% table size update. The value given as argument may be lower %% than the one received in the SETTINGS. -spec set_max_size(non_neg_integer(), State) -> State when State::state(). set_max_size(MaxSize, State) -> State#state{configured_max_size=MaxSize}. %% Decoding. -spec decode(binary()) -> {cow_http:headers(), state()}. decode(Data) -> decode(Data, init()). -spec decode(binary(), State) -> {cow_http:headers(), State} when State::state(). %% Dynamic table size update is only allowed at the beginning of a HEADERS block. decode(<< 0:2, 1:1, Rest/bits >>, State=#state{configured_max_size=ConfigMaxSize}) -> {MaxSize, Rest2} = dec_int5(Rest), if MaxSize =< ConfigMaxSize -> State2 = table_update_size(MaxSize, State), decode(Rest2, State2) end; decode(Data, State) -> decode(Data, State, []). decode(<<>>, State, Acc) -> {lists:reverse(Acc), State}; %% Indexed header field representation. decode(<< 1:1, Rest/bits >>, State, Acc) -> dec_indexed(Rest, State, Acc); %% Literal header field with incremental indexing: new name. decode(<< 0:1, 1:1, 0:6, Rest/bits >>, State, Acc) -> dec_lit_index_new_name(Rest, State, Acc); %% Literal header field with incremental indexing: indexed name. decode(<< 0:1, 1:1, Rest/bits >>, State, Acc) -> dec_lit_index_indexed_name(Rest, State, Acc); %% Literal header field without indexing: new name. decode(<< 0:8, Rest/bits >>, State, Acc) -> dec_lit_no_index_new_name(Rest, State, Acc); %% Literal header field without indexing: indexed name. decode(<< 0:4, Rest/bits >>, State, Acc) -> dec_lit_no_index_indexed_name(Rest, State, Acc); %% Literal header field never indexed: new name. %% @todo Keep track of "never indexed" headers. decode(<< 0:3, 1:1, 0:4, Rest/bits >>, State, Acc) -> dec_lit_no_index_new_name(Rest, State, Acc); %% Literal header field never indexed: indexed name. %% @todo Keep track of "never indexed" headers. decode(<< 0:3, 1:1, Rest/bits >>, State, Acc) -> dec_lit_no_index_indexed_name(Rest, State, Acc). %% Indexed header field representation. %% We do the integer decoding inline where appropriate, falling %% back to dec_big_int for larger values. dec_indexed(<<2#1111111:7, 0:1, Int:7, Rest/bits>>, State, Acc) -> {Name, Value} = table_get(127 + Int, State), decode(Rest, State, [{Name, Value}|Acc]); dec_indexed(<<2#1111111:7, Rest0/bits>>, State, Acc) -> {Index, Rest} = dec_big_int(Rest0, 127, 0), {Name, Value} = table_get(Index, State), decode(Rest, State, [{Name, Value}|Acc]); dec_indexed(<<Index:7, Rest/bits>>, State, Acc) -> {Name, Value} = table_get(Index, State), decode(Rest, State, [{Name, Value}|Acc]). %% Literal header field with incremental indexing. dec_lit_index_new_name(Rest, State, Acc) -> {Name, Rest2} = dec_str(Rest), dec_lit_index(Rest2, State, Acc, Name). %% We do the integer decoding inline where appropriate, falling %% back to dec_big_int for larger values. dec_lit_index_indexed_name(<<2#111111:6, 0:1, Int:7, Rest/bits>>, State, Acc) -> Name = table_get_name(63 + Int, State), dec_lit_index(Rest, State, Acc, Name); dec_lit_index_indexed_name(<<2#111111:6, Rest0/bits>>, State, Acc) -> {Index, Rest} = dec_big_int(Rest0, 63, 0), Name = table_get_name(Index, State), dec_lit_index(Rest, State, Acc, Name); dec_lit_index_indexed_name(<<Index:6, Rest/bits>>, State, Acc) -> Name = table_get_name(Index, State), dec_lit_index(Rest, State, Acc, Name). dec_lit_index(Rest, State, Acc, Name) -> {Value, Rest2} = dec_str(Rest), State2 = table_insert({Name, Value}, State), decode(Rest2, State2, [{Name, Value}|Acc]). %% Literal header field without indexing. dec_lit_no_index_new_name(Rest, State, Acc) -> {Name, Rest2} = dec_str(Rest), dec_lit_no_index(Rest2, State, Acc, Name). %% We do the integer decoding inline where appropriate, falling %% back to dec_big_int for larger values. dec_lit_no_index_indexed_name(<<2#1111:4, 0:1, Int:7, Rest/bits>>, State, Acc) -> Name = table_get_name(15 + Int, State), dec_lit_no_index(Rest, State, Acc, Name); dec_lit_no_index_indexed_name(<<2#1111:4, Rest0/bits>>, State, Acc) -> {Index, Rest} = dec_big_int(Rest0, 15, 0), Name = table_get_name(Index, State), dec_lit_no_index(Rest, State, Acc, Name); dec_lit_no_index_indexed_name(<<Index:4, Rest/bits>>, State, Acc) -> Name = table_get_name(Index, State), dec_lit_no_index(Rest, State, Acc, Name). dec_lit_no_index(Rest, State, Acc, Name) -> {Value, Rest2} = dec_str(Rest), decode(Rest2, State, [{Name, Value}|Acc]). %% @todo Literal header field never indexed. %% Decode an integer. The HPACK format has 4 different integer prefixes length ( from 4 to 7 ) %% and each can be used to create an indefinite length integer if all bits of the prefix are set to 1 . dec_int5(<< 2#11111:5, Rest/bits >>) -> dec_big_int(Rest, 31, 0); dec_int5(<< Int:5, Rest/bits >>) -> {Int, Rest}. dec_big_int(<< 0:1, Value:7, Rest/bits >>, Int, M) -> {Int + (Value bsl M), Rest}; dec_big_int(<< 1:1, Value:7, Rest/bits >>, Int, M) -> dec_big_int(Rest, Int + (Value bsl M), M + 7). %% Decode a string. dec_str(<<0:1, 2#1111111:7, Rest0/bits>>) -> {Length, Rest1} = dec_big_int(Rest0, 127, 0), <<Str:Length/binary, Rest/bits>> = Rest1, {Str, Rest}; dec_str(<<0:1, Length:7, Rest0/bits>>) -> <<Str:Length/binary, Rest/bits>> = Rest0, {Str, Rest}; dec_str(<<1:1, 2#1111111:7, Rest0/bits>>) -> {Length, Rest} = dec_big_int(Rest0, 127, 0), dec_huffman(Rest, Length, 0, <<>>); dec_str(<<1:1, Length:7, Rest/bits>>) -> dec_huffman(Rest, Length, 0, <<>>). %% We use a lookup table that allows us to benefit from %% the binary match context optimization. A more naive %% implementation using bit pattern matching cannot reuse %% a match context because it wouldn't always match on %% byte boundaries. %% %% See cow_hpack_dec_huffman_lookup.hrl for more details. dec_huffman(<<A:4, B:4, R/bits>>, Len, Huff0, Acc) when Len > 1 -> {_, CharA, Huff1} = dec_huffman_lookup(Huff0, A), {_, CharB, Huff} = dec_huffman_lookup(Huff1, B), case {CharA, CharB} of {undefined, undefined} -> dec_huffman(R, Len - 1, Huff, Acc); {CharA, undefined} -> dec_huffman(R, Len - 1, Huff, <<Acc/binary, CharA>>); {undefined, CharB} -> dec_huffman(R, Len - 1, Huff, <<Acc/binary, CharB>>); {CharA, CharB} -> dec_huffman(R, Len - 1, Huff, <<Acc/binary, CharA, CharB>>) end; dec_huffman(<<A:4, B:4, Rest/bits>>, 1, Huff0, Acc) -> {_, CharA, Huff} = dec_huffman_lookup(Huff0, A), {ok, CharB, _} = dec_huffman_lookup(Huff, B), case {CharA, CharB} of { undefined , undefined } ( > 7 - bit final padding ) is rejected with a crash . {CharA, undefined} -> {<<Acc/binary, CharA>>, Rest}; {undefined, CharB} -> {<<Acc/binary, CharB>>, Rest}; _ -> {<<Acc/binary, CharA, CharB>>, Rest} end; %% Can only be reached when the string length to decode is 0. dec_huffman(Rest, 0, _, <<>>) -> {<<>>, Rest}. -include("cow_hpack_dec_huffman_lookup.hrl"). %%-ifdef(TEST). %%%% Test case extracted from h2spec. decode_reject_eos_test ( ) - > { ' EXIT ' , _ } = ( catch decode(<<16#0085f2b24a84ff874951fffffffa7f:120 > > ) ) , %% ok. %% %%req_decode_test() -> % % First request ( raw then ) . %% {Headers1, State1} = decode(<< 16#828684410f7777772e6578616d706c652e636f6d:160 >>), %% {Headers1, State1} = decode(<< 16#828684418cf1e3c2e5f23a6ba0ab90f4ff:136 >>), %% Headers1 = [ %% {<<":method">>, <<"GET">>}, %% {<<":scheme">>, <<"http">>}, %% {<<":path">>, <<"/">>}, %% {<<":authority">>, <<"www.example.com">>} %% ], %% #state{size=57, dyn_table=[{57,{<<":authority">>, <<"www.example.com">>}}]} = State1, % % Second request ( raw then ) . { Headers2 , State2 } = decode ( < < 16#828684be58086e6f2d6361636865:112 > > , State1 ) , %% {Headers2, State2} = decode(<< 16#828684be5886a8eb10649cbf:96 >>, State1), %% Headers2 = [ %% {<<":method">>, <<"GET">>}, %% {<<":scheme">>, <<"http">>}, %% {<<":path">>, <<"/">>}, %% {<<":authority">>, <<"www.example.com">>}, %% {<<"cache-control">>, <<"no-cache">>} %% ], %% #state{size=110, dyn_table=[ { 53,{<<"cache - control " > > , < < " no - cache " > > } } , %% {57,{<<":authority">>, <<"www.example.com">>}}]} = State2, % % Third request ( raw then ) . { Headers3 , State3 } = decode ( < < 16#828785bf400a637573746f6d2d6b65790c637573746f6d2d76616c7565:232 > > , State2 ) , { Headers3 , State3 } = decode ( < < 16#828785bf408825a849e95ba97d7f8925a849e95bb8e8b4bf:192 > > , State2 ) , Headers3 = [ %% {<<":method">>, <<"GET">>}, %% {<<":scheme">>, <<"https">>}, { < < " : path " > > , < < " /index.html " > > } , %% {<<":authority">>, <<"www.example.com">>}, %% {<<"custom-key">>, <<"custom-value">>} %% ], # state{size=164 , dyn_table= [ { 54,{<<"custom - key " > > , < < " custom - value " > > } } , { 53,{<<"cache - control " > > , < < " no - cache " > > } } , %% {57,{<<":authority">>, <<"www.example.com">>}}]} = State3, %% ok. %% %%resp_decode_test() -> % % Use a max_size of 256 to trigger header evictions . %% State0 = init(256), % % First response ( raw then ) . { Headers1 , State1 } = decode ( < < 16#4803333032580770726976617465611d4d6f6e2c203231204f637420323031332032303a31333a323120474d546e1768747470733a2f2f7777772e6578616d706c652e636f6d:560 > > , State0 ) , { Headers1 , State1 } = decode ( < < 16#488264025885aec3771a4b6196d07abe941054d444a8200595040b8166e082a62d1bff6e919d29ad171863c78f0b97c8e9ae82ae43d3:432 > > , State0 ) , %% Headers1 = [ { < < " : status " > > , < < " 302 " > > } , %% {<<"cache-control">>, <<"private">>}, { < < " date " > > , < < " Mon , 21 Oct 2013 20:13:21 GMT " > > } , %% {<<"location">>, <<"">>} %% ], %% #state{size=222, dyn_table=[ %% {63,{<<"location">>, <<"">>}}, { 65,{<<"date " > > , < < " Mon , 21 Oct 2013 20:13:21 GMT " > > } } , { 52,{<<"cache - control " > > , < < " private " > > } } , { 42,{<<":status " > > , < < " 302 " > > } } ] } = State1 , % % Second response ( raw then ) . { Headers2 , State2 } = decode ( < < 16#4803333037c1c0bf:64 > > , State1 ) , { Headers2 , State2 } = decode ( < < 16#4883640effc1c0bf:64 > > , State1 ) , %% Headers2 = [ { < < " : status " > > , < < " 307 " > > } , %% {<<"cache-control">>, <<"private">>}, { < < " date " > > , < < " Mon , 21 Oct 2013 20:13:21 GMT " > > } , %% {<<"location">>, <<"">>} %% ], %% #state{size=222, dyn_table=[ { 42,{<<":status " > > , < < " 307 " > > } } , %% {63,{<<"location">>, <<"">>}}, { 65,{<<"date " > > , < < " Mon , 21 Oct 2013 20:13:21 GMT " > > } } , { 52,{<<"cache - control " > > , < < " private " > > } } ] } = State2 , % % Third response ( raw then ) . { Headers3 , State3 } = decode ( < < 16#88c1611d4d6f6e2c203231204f637420323031332032303a31333a323220474d54c05a04677a69707738666f6f3d4153444a4b48514b425a584f5157454f50495541585157454f49553b206d61782d6167653d333630303b2076657273696f6e3d31:784 > > , State2 ) , { Headers3 , State3 } = decode ( < < 16#88c16196d07abe941054d444a8200595040b8166e084a62d1bffc05a839bd9ab77ad94e7821dd7f2e6c7b335dfdfcd5b3960d5af27087f3672c1ab270fb5291f9587316065c003ed4ee5b1063d5007:632 > > , State2 ) , Headers3 = [ { < < " : status " > > , < < " 200 " > > } , %% {<<"cache-control">>, <<"private">>}, { < < " date " > > , < < " Mon , 21 Oct 2013 20:13:22 GMT " > > } , %% {<<"location">>, <<"">>}, %% {<<"content-encoding">>, <<"gzip">>}, { < < " set - cookie " > > , < < " foo = ASDJKHQKBZXOQWEOPIUAXQWEOIU ; max - age=3600 ; version=1 " > > } %% ], %% #state{size=215, dyn_table=[ { 98,{<<"set - cookie " > > , < < " foo = ASDJKHQKBZXOQWEOPIUAXQWEOIU ; max - age=3600 ; version=1 " > > } } , %% {52,{<<"content-encoding">>, <<"gzip">>}}, { 65,{<<"date " > > , < < " Mon , 21 Oct 2013 20:13:22 GMT " > > } } ] } = State3 , %% ok. %% %%table_update_decode_test() -> % % Use a max_size of 256 to trigger header evictions % % when the code is not updating the size . %% State0 = init(256), % % First response ( raw then ) . { Headers1 , State1 } = decode ( < < 16#4803333032580770726976617465611d4d6f6e2c203231204f637420323031332032303a31333a323120474d546e1768747470733a2f2f7777772e6578616d706c652e636f6d:560 > > , State0 ) , { Headers1 , State1 } = decode ( < < 16#488264025885aec3771a4b6196d07abe941054d444a8200595040b8166e082a62d1bff6e919d29ad171863c78f0b97c8e9ae82ae43d3:432 > > , State0 ) , %% Headers1 = [ { < < " : status " > > , < < " 302 " > > } , %% {<<"cache-control">>, <<"private">>}, { < < " date " > > , < < " Mon , 21 Oct 2013 20:13:21 GMT " > > } , %% {<<"location">>, <<"">>} %% ], %% #state{size=222, configured_max_size=256, dyn_table=[ %% {63,{<<"location">>, <<"">>}}, { 65,{<<"date " > > , < < " Mon , 21 Oct 2013 20:13:21 GMT " > > } } , { 52,{<<"cache - control " > > , < < " private " > > } } , { 42,{<<":status " > > , < < " 302 " > > } } ] } = State1 , %% %% Set a new configured max_size to avoid header evictions. %% State2 = set_max_size(512, State1), % % Second response with the table size update ( raw then ) . MaxSize = enc_big_int(512 - 31 , < < > > ) , %% {Headers2, State3} = decode( iolist_to_binary ( [ < < 2#00111111 > > , MaxSize , < < 16#4803333037c1c0bf:64 > > ] ) , %% State2), %% {Headers2, State3} = decode( iolist_to_binary ( [ < < 2#00111111 > > , MaxSize , < < 16#4883640effc1c0bf:64 > > ] ) , %% State2), %% Headers2 = [ { < < " : status " > > , < < " 307 " > > } , %% {<<"cache-control">>, <<"private">>}, { < < " date " > > , < < " Mon , 21 Oct 2013 20:13:21 GMT " > > } , %% {<<"location">>, <<"">>} %% ], # state{size=264 , configured_max_size=512 , dyn_table= [ { 42,{<<":status " > > , < < " 307 " > > } } , %% {63,{<<"location">>, <<"">>}}, { 65,{<<"date " > > , < < " Mon , 21 Oct 2013 20:13:21 GMT " > > } } , { 52,{<<"cache - control " > > , < < " private " > > } } , { 42,{<<":status " > > , < < " 302 " > > } } ] } = State3 , %% ok. %% %%table_update_decode_smaller_test() -> % % Use a max_size of 256 to trigger header evictions % % when the code is not updating the size . %% State0 = init(256), % % First response ( raw then ) . { Headers1 , State1 } = decode ( < < 16#4803333032580770726976617465611d4d6f6e2c203231204f637420323031332032303a31333a323120474d546e1768747470733a2f2f7777772e6578616d706c652e636f6d:560 > > , State0 ) , { Headers1 , State1 } = decode ( < < 16#488264025885aec3771a4b6196d07abe941054d444a8200595040b8166e082a62d1bff6e919d29ad171863c78f0b97c8e9ae82ae43d3:432 > > , State0 ) , %% Headers1 = [ { < < " : status " > > , < < " 302 " > > } , %% {<<"cache-control">>, <<"private">>}, { < < " date " > > , < < " Mon , 21 Oct 2013 20:13:21 GMT " > > } , %% {<<"location">>, <<"">>} %% ], %% #state{size=222, configured_max_size=256, dyn_table=[ %% {63,{<<"location">>, <<"">>}}, { 65,{<<"date " > > , < < " Mon , 21 Oct 2013 20:13:21 GMT " > > } } , { 52,{<<"cache - control " > > , < < " private " > > } } , { 42,{<<":status " > > , < < " 302 " > > } } ] } = State1 , %% %% Set a new configured max_size to avoid header evictions. %% State2 = set_max_size(512, State1), % % Second response with the table size update smaller than the limit ( raw then ) . MaxSize = enc_big_int(400 - 31 , < < > > ) , %% {Headers2, State3} = decode( iolist_to_binary ( [ < < 2#00111111 > > , MaxSize , < < 16#4803333037c1c0bf:64 > > ] ) , %% State2), %% {Headers2, State3} = decode( iolist_to_binary ( [ < < 2#00111111 > > , MaxSize , < < 16#4883640effc1c0bf:64 > > ] ) , %% State2), %% Headers2 = [ { < < " : status " > > , < < " 307 " > > } , %% {<<"cache-control">>, <<"private">>}, { < < " date " > > , < < " Mon , 21 Oct 2013 20:13:21 GMT " > > } , %% {<<"location">>, <<"">>} %% ], # state{size=264 , configured_max_size=512 , dyn_table= [ { 42,{<<":status " > > , < < " 307 " > > } } , %% {63,{<<"location">>, <<"">>}}, { 65,{<<"date " > > , < < " Mon , 21 Oct 2013 20:13:21 GMT " > > } } , { 52,{<<"cache - control " > > , < < " private " > > } } , { 42,{<<":status " > > , < < " 302 " > > } } ] } = State3 , %% ok. %% %%table_update_decode_too_large_test() -> % % Use a max_size of 256 to trigger header evictions % % when the code is not updating the size . %% State0 = init(256), % % First response ( raw then ) . { Headers1 , State1 } = decode ( < < 16#4803333032580770726976617465611d4d6f6e2c203231204f637420323031332032303a31333a323120474d546e1768747470733a2f2f7777772e6578616d706c652e636f6d:560 > > , State0 ) , { Headers1 , State1 } = decode ( < < 16#488264025885aec3771a4b6196d07abe941054d444a8200595040b8166e082a62d1bff6e919d29ad171863c78f0b97c8e9ae82ae43d3:432 > > , State0 ) , %% Headers1 = [ { < < " : status " > > , < < " 302 " > > } , %% {<<"cache-control">>, <<"private">>}, { < < " date " > > , < < " Mon , 21 Oct 2013 20:13:21 GMT " > > } , %% {<<"location">>, <<"">>} %% ], %% #state{size=222, configured_max_size=256, dyn_table=[ %% {63,{<<"location">>, <<"">>}}, { 65,{<<"date " > > , < < " Mon , 21 Oct 2013 20:13:21 GMT " > > } } , { 52,{<<"cache - control " > > , < < " private " > > } } , { 42,{<<":status " > > , < < " 302 " > > } } ] } = State1 , %% %% Set a new configured max_size to avoid header evictions. %% State2 = set_max_size(512, State1), % % Second response with the table size update ( raw then ) . MaxSize = enc_big_int(1024 - 31 , < < > > ) , { ' EXIT ' , _ } = ( catch decode ( iolist_to_binary ( [ < < 2#00111111 > > , MaxSize , < < 16#4803333037c1c0bf:64 > > ] ) , %% State2)), { ' EXIT ' , _ } = ( catch decode ( iolist_to_binary ( [ < < 2#00111111 > > , MaxSize , < < 16#4883640effc1c0bf:64 > > ] ) , %% State2)), %% ok. %% %%table_update_decode_zero_test() -> %% State0 = init(256), % % First response ( raw then ) . { Headers1 , State1 } = decode ( < < 16#4803333032580770726976617465611d4d6f6e2c203231204f637420323031332032303a31333a323120474d546e1768747470733a2f2f7777772e6578616d706c652e636f6d:560 > > , State0 ) , { Headers1 , State1 } = decode ( < < 16#488264025885aec3771a4b6196d07abe941054d444a8200595040b8166e082a62d1bff6e919d29ad171863c78f0b97c8e9ae82ae43d3:432 > > , State0 ) , %% Headers1 = [ { < < " : status " > > , < < " 302 " > > } , %% {<<"cache-control">>, <<"private">>}, { < < " date " > > , < < " Mon , 21 Oct 2013 20:13:21 GMT " > > } , %% {<<"location">>, <<"">>} %% ], %% #state{size=222, configured_max_size=256, dyn_table=[ %% {63,{<<"location">>, <<"">>}}, { 65,{<<"date " > > , < < " Mon , 21 Oct 2013 20:13:21 GMT " > > } } , { 52,{<<"cache - control " > > , < < " private " > > } } , { 42,{<<":status " > > , < < " 302 " > > } } ] } = State1 , %% %% Set a new configured max_size to avoid header evictions. %% State2 = set_max_size(512, State1), % % Second response with the table size update ( raw then ) . %% %% We set the table size to 0 to evict all values before setting % % it to 512 so we only get the second request indexed . MaxSize = enc_big_int(512 - 31 , < < > > ) , %% {Headers1, State3} = decode(iolist_to_binary([ < < 2#00100000 , 2#00111111 > > , MaxSize , < < 16#4803333032580770726976617465611d4d6f6e2c203231204f637420323031332032303a31333a323120474d546e1768747470733a2f2f7777772e6578616d706c652e636f6d:560 > > ] ) , %% State2), %% {Headers1, State3} = decode(iolist_to_binary([ < < 2#00100000 , 2#00111111 > > , MaxSize , < < 16#488264025885aec3771a4b6196d07abe941054d444a8200595040b8166e082a62d1bff6e919d29ad171863c78f0b97c8e9ae82ae43d3:432 > > ] ) , %% State2), # state{size=222 , configured_max_size=512 , dyn_table= [ %% {63,{<<"location">>, <<"">>}}, { 65,{<<"date " > > , < < " Mon , 21 Oct 2013 20:13:21 GMT " > > } } , { 52,{<<"cache - control " > > , < < " private " > > } } , { 42,{<<":status " > > , < < " 302 " > > } } ] } = State3 , %% ok. %% %%horse_decode_raw() -> %% horse:repeat(20000, %% do_horse_decode_raw() %% ). %% %%do_horse_decode_raw() -> %% {_, State1} = decode(<<16#828684410f7777772e6578616d706c652e636f6d:160>>), %% {_, State2} = decode(<<16#828684be58086e6f2d6361636865:112>>, State1), %% {_, _} = decode(<<16#828785bf400a637573746f6d2d6b65790c637573746f6d2d76616c7565:232>>, State2), %% ok. %% horse_decode_huffman ( ) - > %% horse:repeat(20000, %% do_horse_decode_huffman() %% ). %% %%do_horse_decode_huffman() -> %% {_, State1} = decode(<<16#828684418cf1e3c2e5f23a6ba0ab90f4ff:136>>), { _ , State2 } = > > , State1 ) , %% {_, _} = decode(<<16#828785bf408825a849e95ba97d7f8925a849e95bb8e8b4bf:192>>, State2), %% ok. %%-endif. %% Encoding. -spec encode(cow_http:headers()) -> {iodata(), state()}. encode(Headers) -> encode(Headers, init(), huffman, []). -spec encode(cow_http:headers(), State) -> {iodata(), State} when State::state(). encode(Headers, State=#state{max_size=MaxSize, configured_max_size=MaxSize}) -> encode(Headers, State, huffman, []); encode(Headers, State0=#state{configured_max_size=MaxSize}) -> {Data, State} = encode(Headers, State0#state{max_size=MaxSize}, huffman, []), {[enc_int5(MaxSize, 2#001)|Data], State}. -spec encode(cow_http:headers(), State, opts()) -> {iodata(), State} when State::state(). encode(Headers, State=#state{max_size=MaxSize, configured_max_size=MaxSize}, Opts) -> encode(Headers, State, huffman_opt(Opts), []); encode(Headers, State0=#state{configured_max_size=MaxSize}, Opts) -> {Data, State} = encode(Headers, State0#state{max_size=MaxSize}, huffman_opt(Opts), []), {[enc_int5(MaxSize, 2#001)|Data], State}. huffman_opt(#{huffman := false}) -> no_huffman; huffman_opt(_) -> huffman. %% @todo Handle cases where no/never indexing is expected. encode([], State, _, Acc) -> {lists:reverse(Acc), State}; encode([{Name, Value0}|Tail], State, HuffmanOpt, Acc) -> %% We conditionally call iolist_to_binary/1 because a small %% but noticeable speed improvement happens when we do this. Value = if is_binary(Value0) -> Value0; true -> iolist_to_binary(Value0) end, Header = {Name, Value}, case table_find(Header, State) of %% Indexed header field representation. {field, Index} -> encode(Tail, State, HuffmanOpt, [enc_int7(Index, 2#1)|Acc]); %% Literal header field representation: indexed name. {name, Index} -> State2 = table_insert(Header, State), encode(Tail, State2, HuffmanOpt, [[enc_int6(Index, 2#01)|enc_str(Value, HuffmanOpt)]|Acc]); %% Literal header field representation: new name. not_found -> State2 = table_insert(Header, State), encode(Tail, State2, HuffmanOpt, [[<< 0:1, 1:1, 0:6 >>|[enc_str(Name, HuffmanOpt)|enc_str(Value, HuffmanOpt)]]|Acc]) end. %% Encode an integer. enc_int5(Int, Prefix) when Int < 31 -> << Prefix:3, Int:5 >>; enc_int5(Int, Prefix) -> enc_big_int(Int - 31, << Prefix:3, 2#11111:5 >>). enc_int6(Int, Prefix) when Int < 63 -> << Prefix:2, Int:6 >>; enc_int6(Int, Prefix) -> enc_big_int(Int - 63, << Prefix:2, 2#111111:6 >>). enc_int7(Int, Prefix) when Int < 127 -> << Prefix:1, Int:7 >>; enc_int7(Int, Prefix) -> enc_big_int(Int - 127, << Prefix:1, 2#1111111:7 >>). enc_big_int(Int, Acc) when Int < 128 -> <<Acc/binary, Int:8>>; enc_big_int(Int, Acc) -> enc_big_int(Int bsr 7, <<Acc/binary, 1:1, Int:7>>). %% Encode a string. enc_str(Str, huffman) -> Str2 = enc_huffman(Str, <<>>), [enc_int7(byte_size(Str2), 2#1)|Str2]; enc_str(Str, no_huffman) -> [enc_int7(byte_size(Str), 2#0)|Str]. enc_huffman(<<>>, Acc) -> case bit_size(Acc) rem 8 of 1 -> << Acc/bits, 2#1111111:7 >>; 2 -> << Acc/bits, 2#111111:6 >>; 3 -> << Acc/bits, 2#11111:5 >>; 4 -> << Acc/bits, 2#1111:4 >>; 5 -> << Acc/bits, 2#111:3 >>; 6 -> << Acc/bits, 2#11:2 >>; 7 -> << Acc/bits, 2#1:1 >>; 0 -> Acc end; enc_huffman(<< 0, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111000:13 >>); enc_huffman(<< 1, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#11111111111111111011000:23 >>); enc_huffman(<< 2, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111111111111111100010:28 >>); enc_huffman(<< 3, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111111111111111100011:28 >>); enc_huffman(<< 4, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111111111111111100100:28 >>); enc_huffman(<< 5, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111111111111111100101:28 >>); enc_huffman(<< 6, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111111111111111100110:28 >>); enc_huffman(<< 7, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111111111111111100111:28 >>); enc_huffman(<< 8, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111111111111111101000:28 >>); enc_huffman(<< 9, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#111111111111111111101010:24 >>); enc_huffman(<< 10, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#111111111111111111111111111100:30 >>); enc_huffman(<< 11, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111111111111111101001:28 >>); enc_huffman(<< 12, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111111111111111101010:28 >>); enc_huffman(<< 13, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#111111111111111111111111111101:30 >>); enc_huffman(<< 14, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111111111111111101011:28 >>); enc_huffman(<< 15, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111111111111111101100:28 >>); enc_huffman(<< 16, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111111111111111101101:28 >>); enc_huffman(<< 17, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111111111111111101110:28 >>); enc_huffman(<< 18, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111111111111111101111:28 >>); enc_huffman(<< 19, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111111111111111110000:28 >>); enc_huffman(<< 20, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111111111111111110001:28 >>); enc_huffman(<< 21, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111111111111111110010:28 >>); enc_huffman(<< 22, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#111111111111111111111111111110:30 >>); enc_huffman(<< 23, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111111111111111110011:28 >>); enc_huffman(<< 24, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111111111111111110100:28 >>); enc_huffman(<< 25, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111111111111111110101:28 >>); enc_huffman(<< 26, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111111111111111110110:28 >>); enc_huffman(<< 27, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111111111111111110111:28 >>); enc_huffman(<< 28, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111111111111111111000:28 >>); enc_huffman(<< 29, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111111111111111111001:28 >>); enc_huffman(<< 30, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111111111111111111010:28 >>); enc_huffman(<< 31, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111111111111111111011:28 >>); enc_huffman(<< 32, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#010100:6 >>); enc_huffman(<< 33, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111000:10 >>); enc_huffman(<< 34, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111001:10 >>); enc_huffman(<< 35, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#111111111010:12 >>); enc_huffman(<< 36, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111001:13 >>); enc_huffman(<< 37, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#010101:6 >>); enc_huffman(<< 38, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#11111000:8 >>); enc_huffman(<< 39, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#11111111010:11 >>); enc_huffman(<< 40, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111010:10 >>); enc_huffman(<< 41, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111011:10 >>); enc_huffman(<< 42, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#11111001:8 >>); enc_huffman(<< 43, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#11111111011:11 >>); enc_huffman(<< 44, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#11111010:8 >>); enc_huffman(<< 45, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#010110:6 >>); enc_huffman(<< 46, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#010111:6 >>); enc_huffman(<< 47, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#011000:6 >>); enc_huffman(<< 48, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#00000:5 >>); enc_huffman(<< 49, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#00001:5 >>); enc_huffman(<< 50, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#00010:5 >>); enc_huffman(<< 51, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#011001:6 >>); enc_huffman(<< 52, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#011010:6 >>); enc_huffman(<< 53, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#011011:6 >>); enc_huffman(<< 54, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#011100:6 >>); enc_huffman(<< 55, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#011101:6 >>); enc_huffman(<< 56, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#011110:6 >>); enc_huffman(<< 57, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#011111:6 >>); enc_huffman(<< 58, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1011100:7 >>); enc_huffman(<< 59, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#11111011:8 >>); enc_huffman(<< 60, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#111111111111100:15 >>); enc_huffman(<< 61, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#100000:6 >>); enc_huffman(<< 62, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#111111111011:12 >>); enc_huffman(<< 63, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111100:10 >>); enc_huffman(<< 64, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111010:13 >>); enc_huffman(<< 65, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#100001:6 >>); enc_huffman(<< 66, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1011101:7 >>); enc_huffman(<< 67, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1011110:7 >>); enc_huffman(<< 68, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1011111:7 >>); enc_huffman(<< 69, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1100000:7 >>); enc_huffman(<< 70, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1100001:7 >>); enc_huffman(<< 71, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1100010:7 >>); enc_huffman(<< 72, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1100011:7 >>); enc_huffman(<< 73, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1100100:7 >>); enc_huffman(<< 74, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1100101:7 >>); enc_huffman(<< 75, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1100110:7 >>); enc_huffman(<< 76, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1100111:7 >>); enc_huffman(<< 77, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1101000:7 >>); enc_huffman(<< 78, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1101001:7 >>); enc_huffman(<< 79, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1101010:7 >>); enc_huffman(<< 80, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1101011:7 >>); enc_huffman(<< 81, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1101100:7 >>); enc_huffman(<< 82, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1101101:7 >>); enc_huffman(<< 83, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1101110:7 >>); enc_huffman(<< 84, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1101111:7 >>); enc_huffman(<< 85, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1110000:7 >>); enc_huffman(<< 86, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1110001:7 >>); enc_huffman(<< 87, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1110010:7 >>); enc_huffman(<< 88, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#11111100:8 >>); enc_huffman(<< 89, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1110011:7 >>); enc_huffman(<< 90, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#11111101:8 >>); enc_huffman(<< 91, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111011:13 >>); enc_huffman(<< 92, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111111110000:19 >>); enc_huffman(<< 93, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111100:13 >>); enc_huffman(<< 94, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#11111111111100:14 >>); enc_huffman(<< 95, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#100010:6 >>); enc_huffman(<< 96, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#111111111111101:15 >>); enc_huffman(<< 97, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#00011:5 >>); enc_huffman(<< 98, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#100011:6 >>); enc_huffman(<< 99, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#00100:5 >>); enc_huffman(<< 100, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#100100:6 >>); enc_huffman(<< 101, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#00101:5 >>); enc_huffman(<< 102, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#100101:6 >>); enc_huffman(<< 103, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#100110:6 >>); enc_huffman(<< 104, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#100111:6 >>); enc_huffman(<< 105, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#00110:5 >>); enc_huffman(<< 106, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1110100:7 >>); enc_huffman(<< 107, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1110101:7 >>); enc_huffman(<< 108, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#101000:6 >>); enc_huffman(<< 109, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#101001:6 >>); enc_huffman(<< 110, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#101010:6 >>); enc_huffman(<< 111, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#00111:5 >>); enc_huffman(<< 112, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#101011:6 >>); enc_huffman(<< 113, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1110110:7 >>); enc_huffman(<< 114, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#101100:6 >>); enc_huffman(<< 115, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#01000:5 >>); enc_huffman(<< 116, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#01001:5 >>); enc_huffman(<< 117, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#101101:6 >>); enc_huffman(<< 118, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1110111:7 >>); enc_huffman(<< 119, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111000:7 >>); enc_huffman(<< 120, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111001:7 >>); enc_huffman(<< 121, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111010:7 >>); enc_huffman(<< 122, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111011:7 >>); enc_huffman(<< 123, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#111111111111110:15 >>); enc_huffman(<< 124, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#11111111100:11 >>); enc_huffman(<< 125, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#11111111111101:14 >>); enc_huffman(<< 126, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111101:13 >>); enc_huffman(<< 127, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111111111111111111100:28 >>); enc_huffman(<< 128, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#11111111111111100110:20 >>); enc_huffman(<< 129, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111111111010010:22 >>); enc_huffman(<< 130, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#11111111111111100111:20 >>); enc_huffman(<< 131, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#11111111111111101000:20 >>); enc_huffman(<< 132, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111111111010011:22 >>); enc_huffman(<< 133, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111111111010100:22 >>); enc_huffman(<< 134, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111111111010101:22 >>); enc_huffman(<< 135, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#11111111111111111011001:23 >>); enc_huffman(<< 136, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111111111010110:22 >>); enc_huffman(<< 137, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#11111111111111111011010:23 >>); enc_huffman(<< 138, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#11111111111111111011011:23 >>); enc_huffman(<< 139, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#11111111111111111011100:23 >>); enc_huffman(<< 140, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#11111111111111111011101:23 >>); enc_huffman(<< 141, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#11111111111111111011110:23 >>); enc_huffman(<< 142, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#111111111111111111101011:24 >>); enc_huffman(<< 143, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#11111111111111111011111:23 >>); enc_huffman(<< 144, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#111111111111111111101100:24 >>); enc_huffman(<< 145, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#111111111111111111101101:24 >>); enc_huffman(<< 146, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111111111010111:22 >>); enc_huffman(<< 147, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#11111111111111111100000:23 >>); enc_huffman(<< 148, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#111111111111111111101110:24 >>); enc_huffman(<< 149, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#11111111111111111100001:23 >>); enc_huffman(<< 150, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#11111111111111111100010:23 >>); enc_huffman(<< 151, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#11111111111111111100011:23 >>); enc_huffman(<< 152, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#11111111111111111100100:23 >>); enc_huffman(<< 153, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#111111111111111011100:21 >>); enc_huffman(<< 154, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111111111011000:22 >>); enc_huffman(<< 155, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#11111111111111111100101:23 >>); enc_huffman(<< 156, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111111111011001:22 >>); enc_huffman(<< 157, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#11111111111111111100110:23 >>); enc_huffman(<< 158, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#11111111111111111100111:23 >>); enc_huffman(<< 159, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#111111111111111111101111:24 >>); enc_huffman(<< 160, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111111111011010:22 >>); enc_huffman(<< 161, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#111111111111111011101:21 >>); enc_huffman(<< 162, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#11111111111111101001:20 >>); enc_huffman(<< 163, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111111111011011:22 >>); enc_huffman(<< 164, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111111111011100:22 >>); enc_huffman(<< 165, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#11111111111111111101000:23 >>); enc_huffman(<< 166, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#11111111111111111101001:23 >>); enc_huffman(<< 167, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#111111111111111011110:21 >>); enc_huffman(<< 168, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#11111111111111111101010:23 >>); enc_huffman(<< 169, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111111111011101:22 >>); enc_huffman(<< 170, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111111111011110:22 >>); enc_huffman(<< 171, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#111111111111111111110000:24 >>); enc_huffman(<< 172, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#111111111111111011111:21 >>); enc_huffman(<< 173, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111111111011111:22 >>); enc_huffman(<< 174, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#11111111111111111101011:23 >>); enc_huffman(<< 175, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#11111111111111111101100:23 >>); enc_huffman(<< 176, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#111111111111111100000:21 >>); enc_huffman(<< 177, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#111111111111111100001:21 >>); enc_huffman(<< 178, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111111111100000:22 >>); enc_huffman(<< 179, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#111111111111111100010:21 >>); enc_huffman(<< 180, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#11111111111111111101101:23 >>); enc_huffman(<< 181, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111111111100001:22 >>); enc_huffman(<< 182, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#11111111111111111101110:23 >>); enc_huffman(<< 183, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#11111111111111111101111:23 >>); enc_huffman(<< 184, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#11111111111111101010:20 >>); enc_huffman(<< 185, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111111111100010:22 >>); enc_huffman(<< 186, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111111111100011:22 >>); enc_huffman(<< 187, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111111111100100:22 >>); enc_huffman(<< 188, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#11111111111111111110000:23 >>); enc_huffman(<< 189, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111111111100101:22 >>); enc_huffman(<< 190, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111111111100110:22 >>); enc_huffman(<< 191, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#11111111111111111110001:23 >>); enc_huffman(<< 192, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#11111111111111111111100000:26 >>); enc_huffman(<< 193, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#11111111111111111111100001:26 >>); enc_huffman(<< 194, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#11111111111111101011:20 >>); enc_huffman(<< 195, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111111110001:19 >>); enc_huffman(<< 196, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111111111100111:22 >>); enc_huffman(<< 197, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#11111111111111111110010:23 >>); enc_huffman(<< 198, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111111111101000:22 >>); enc_huffman(<< 199, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111111111111101100:25 >>); enc_huffman(<< 200, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#11111111111111111111100010:26 >>); enc_huffman(<< 201, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#11111111111111111111100011:26 >>); enc_huffman(<< 202, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#11111111111111111111100100:26 >>); enc_huffman(<< 203, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#111111111111111111111011110:27 >>); enc_huffman(<< 204, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#111111111111111111111011111:27 >>); enc_huffman(<< 205, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#11111111111111111111100101:26 >>); enc_huffman(<< 206, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#111111111111111111110001:24 >>); enc_huffman(<< 207, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111111111111101101:25 >>); enc_huffman(<< 208, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111111110010:19 >>); enc_huffman(<< 209, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#111111111111111100011:21 >>); enc_huffman(<< 210, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#11111111111111111111100110:26 >>); enc_huffman(<< 211, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#111111111111111111111100000:27 >>); enc_huffman(<< 212, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#111111111111111111111100001:27 >>); enc_huffman(<< 213, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#11111111111111111111100111:26 >>); enc_huffman(<< 214, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#111111111111111111111100010:27 >>); enc_huffman(<< 215, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#111111111111111111110010:24 >>); enc_huffman(<< 216, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#111111111111111100100:21 >>); enc_huffman(<< 217, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#111111111111111100101:21 >>); enc_huffman(<< 218, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#11111111111111111111101000:26 >>); enc_huffman(<< 219, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#11111111111111111111101001:26 >>); enc_huffman(<< 220, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111111111111111111101:28 >>); enc_huffman(<< 221, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#111111111111111111111100011:27 >>); enc_huffman(<< 222, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#111111111111111111111100100:27 >>); enc_huffman(<< 223, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#111111111111111111111100101:27 >>); enc_huffman(<< 224, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#11111111111111101100:20 >>); enc_huffman(<< 225, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#111111111111111111110011:24 >>); enc_huffman(<< 226, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#11111111111111101101:20 >>); enc_huffman(<< 227, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#111111111111111100110:21 >>); enc_huffman(<< 228, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111111111101001:22 >>); enc_huffman(<< 229, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#111111111111111100111:21 >>); enc_huffman(<< 230, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#111111111111111101000:21 >>); enc_huffman(<< 231, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#11111111111111111110011:23 >>); enc_huffman(<< 232, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111111111101010:22 >>); enc_huffman(<< 233, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111111111101011:22 >>); enc_huffman(<< 234, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111111111111101110:25 >>); enc_huffman(<< 235, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111111111111101111:25 >>); enc_huffman(<< 236, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#111111111111111111110100:24 >>); enc_huffman(<< 237, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#111111111111111111110101:24 >>); enc_huffman(<< 238, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#11111111111111111111101010:26 >>); enc_huffman(<< 239, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#11111111111111111110100:23 >>); enc_huffman(<< 240, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#11111111111111111111101011:26 >>); enc_huffman(<< 241, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#111111111111111111111100110:27 >>); enc_huffman(<< 242, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#11111111111111111111101100:26 >>); enc_huffman(<< 243, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#11111111111111111111101101:26 >>); enc_huffman(<< 244, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#111111111111111111111100111:27 >>); enc_huffman(<< 245, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#111111111111111111111101000:27 >>); enc_huffman(<< 246, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#111111111111111111111101001:27 >>); enc_huffman(<< 247, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#111111111111111111111101010:27 >>); enc_huffman(<< 248, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#111111111111111111111101011:27 >>); enc_huffman(<< 249, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111111111111111111110:28 >>); enc_huffman(<< 250, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#111111111111111111111101100:27 >>); enc_huffman(<< 251, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#111111111111111111111101101:27 >>); enc_huffman(<< 252, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#111111111111111111111101110:27 >>); enc_huffman(<< 253, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#111111111111111111111101111:27 >>); enc_huffman(<< 254, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#111111111111111111111110000:27 >>); enc_huffman(<< 255, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#11111111111111111111101110:26 >>). %%-ifdef(TEST). %%req_encode_test() -> % % First request ( raw then ) . %% Headers1 = [ %% {<<":method">>, <<"GET">>}, %% {<<":scheme">>, <<"http">>}, %% {<<":path">>, <<"/">>}, %% {<<":authority">>, <<"www.example.com">>} %% ], { Raw1 , State1 } = encode(Headers1 , init ( ) , # { huffman = > false } ) , %% << 16#828684410f7777772e6578616d706c652e636f6d:160 >> = iolist_to_binary(Raw1), %% {Huff1, State1} = encode(Headers1), %% << 16#828684418cf1e3c2e5f23a6ba0ab90f4ff:136 >> = iolist_to_binary(Huff1), %% #state{size=57, dyn_table=[{57,{<<":authority">>, <<"www.example.com">>}}]} = State1, % % Second request ( raw then ) . %% Headers2 = [ %% {<<":method">>, <<"GET">>}, %% {<<":scheme">>, <<"http">>}, %% {<<":path">>, <<"/">>}, %% {<<":authority">>, <<"www.example.com">>}, %% {<<"cache-control">>, <<"no-cache">>} %% ], %% {Raw2, State2} = encode(Headers2, State1, #{huffman => false}), < < 16#828684be58086e6f2d6361636865:112 > > = iolist_to_binary(Raw2 ) , %% {Huff2, State2} = encode(Headers2, State1), %% << 16#828684be5886a8eb10649cbf:96 >> = iolist_to_binary(Huff2), %% #state{size=110, dyn_table=[ { 53,{<<"cache - control " > > , < < " no - cache " > > } } , %% {57,{<<":authority">>, <<"www.example.com">>}}]} = State2, % % Third request ( raw then ) . Headers3 = [ %% {<<":method">>, <<"GET">>}, %% {<<":scheme">>, <<"https">>}, { < < " : path " > > , < < " /index.html " > > } , %% {<<":authority">>, <<"www.example.com">>}, %% {<<"custom-key">>, <<"custom-value">>} %% ], { Raw3 , State3 } = encode(Headers3 , State2 , # { huffman = > false } ) , < < 16#828785bf400a637573746f6d2d6b65790c637573746f6d2d76616c7565:232 > > = iolist_to_binary(Raw3 ) , { Huff3 , State3 } = encode(Headers3 , State2 ) , < < 16#828785bf408825a849e95ba97d7f8925a849e95bb8e8b4bf:192 > > = iolist_to_binary(Huff3 ) , # state{size=164 , dyn_table= [ { 54,{<<"custom - key " > > , < < " custom - value " > > } } , { 53,{<<"cache - control " > > , < < " no - cache " > > } } , %% {57,{<<":authority">>, <<"www.example.com">>}}]} = State3, %% ok. %% %%resp_encode_test() -> % % Use a max_size of 256 to trigger header evictions . %% State0 = init(256), % % First response ( raw then ) . %% Headers1 = [ { < < " : status " > > , < < " 302 " > > } , %% {<<"cache-control">>, <<"private">>}, { < < " date " > > , < < " Mon , 21 Oct 2013 20:13:21 GMT " > > } , %% {<<"location">>, <<"">>} %% ], %% {Raw1, State1} = encode(Headers1, State0, #{huffman => false}), < < 16#4803333032580770726976617465611d4d6f6e2c203231204f637420323031332032303a31333a323120474d546e1768747470733a2f2f7777772e6578616d706c652e636f6d:560 > > = iolist_to_binary(Raw1 ) , %% {Huff1, State1} = encode(Headers1, State0), < < 16#488264025885aec3771a4b6196d07abe941054d444a8200595040b8166e082a62d1bff6e919d29ad171863c78f0b97c8e9ae82ae43d3:432 > > = iolist_to_binary(Huff1 ) , %% #state{size=222, dyn_table=[ %% {63,{<<"location">>, <<"">>}}, { 65,{<<"date " > > , < < " Mon , 21 Oct 2013 20:13:21 GMT " > > } } , { 52,{<<"cache - control " > > , < < " private " > > } } , { 42,{<<":status " > > , < < " 302 " > > } } ] } = State1 , % % Second response ( raw then ) . %% Headers2 = [ { < < " : status " > > , < < " 307 " > > } , %% {<<"cache-control">>, <<"private">>}, { < < " date " > > , < < " Mon , 21 Oct 2013 20:13:21 GMT " > > } , %% {<<"location">>, <<"">>} %% ], %% {Raw2, State2} = encode(Headers2, State1, #{huffman => false}), < < 16#4803333037c1c0bf:64 > > = iolist_to_binary(Raw2 ) , %% {Huff2, State2} = encode(Headers2, State1), %% << 16#4883640effc1c0bf:64 >> = iolist_to_binary(Huff2), %% #state{size=222, dyn_table=[ { 42,{<<":status " > > , < < " 307 " > > } } , %% {63,{<<"location">>, <<"">>}}, { 65,{<<"date " > > , < < " Mon , 21 Oct 2013 20:13:21 GMT " > > } } , { 52,{<<"cache - control " > > , < < " private " > > } } ] } = State2 , % % Third response ( raw then ) . Headers3 = [ { < < " : status " > > , < < " 200 " > > } , %% {<<"cache-control">>, <<"private">>}, { < < " date " > > , < < " Mon , 21 Oct 2013 20:13:22 GMT " > > } , %% {<<"location">>, <<"">>}, %% {<<"content-encoding">>, <<"gzip">>}, { < < " set - cookie " > > , < < " foo = ASDJKHQKBZXOQWEOPIUAXQWEOIU ; max - age=3600 ; version=1 " > > } %% ], { Raw3 , State3 } = encode(Headers3 , State2 , # { huffman = > false } ) , %% << 16#88c1611d4d6f6e2c203231204f637420323031332032303a31333a323220474d54c05a04677a69707738666f6f3d4153444a4b48514b425a584f5157454f50495541585157454f49553b206d61782d6167653d333630303b2076657273696f6e3d31:784 >> = iolist_to_binary(Raw3), { Huff3 , State3 } = encode(Headers3 , State2 ) , < < 16#88c16196d07abe941054d444a8200595040b8166e084a62d1bffc05a839bd9ab77ad94e7821dd7f2e6c7b335dfdfcd5b3960d5af27087f3672c1ab270fb5291f9587316065c003ed4ee5b1063d5007:632 > > = iolist_to_binary(Huff3 ) , %% #state{size=215, dyn_table=[ { 98,{<<"set - cookie " > > , < < " foo = ASDJKHQKBZXOQWEOPIUAXQWEOIU ; max - age=3600 ; version=1 " > > } } , %% {52,{<<"content-encoding">>, <<"gzip">>}}, { 65,{<<"date " > > , < < " Mon , 21 Oct 2013 20:13:22 GMT " > > } } ] } = State3 , %% ok. %% %%%% This test assumes that table updates work correctly when decoding. %%table_update_encode_test() -> % % Use a max_size of 256 to trigger header evictions % % when the code is not updating the size . %% DecState0 = EncState0 = init(256), % % First response . %% Headers1 = [ { < < " : status " > > , < < " 302 " > > } , %% {<<"cache-control">>, <<"private">>}, { < < " date " > > , < < " Mon , 21 Oct 2013 20:13:21 GMT " > > } , %% {<<"location">>, <<"">>} %% ], { Encoded1 , EncState1 } = encode(Headers1 , ) , { Headers1 , DecState1 } = decode(iolist_to_binary(Encoded1 ) , DecState0 ) , %% #state{size=222, configured_max_size=256, dyn_table=[ %% {63,{<<"location">>, <<"">>}}, { 65,{<<"date " > > , < < " Mon , 21 Oct 2013 20:13:21 GMT " > > } } , { 52,{<<"cache - control " > > , < < " private " > > } } , { 42,{<<":status " > > , < < " 302 " > > } } ] } = DecState1 , %% #state{size=222, configured_max_size=256, dyn_table=[ %% {63,{<<"location">>, <<"">>}}, { 65,{<<"date " > > , < < " Mon , 21 Oct 2013 20:13:21 GMT " > > } } , { 52,{<<"cache - control " > > , < < " private " > > } } , { 42,{<<":status " > > , < < " 302 " > > } } ] } = EncState1 , %% %% Set a new configured max_size to avoid header evictions. DecState2 = set_max_size(512 , DecState1 ) , EncState2 = set_max_size(512 , EncState1 ) , % % Second response . %% Headers2 = [ { < < " : status " > > , < < " 307 " > > } , %% {<<"cache-control">>, <<"private">>}, { < < " date " > > , < < " Mon , 21 Oct 2013 20:13:21 GMT " > > } , %% {<<"location">>, <<"">>} %% ], { Encoded2 , EncState3 } = encode(Headers2 , EncState2 ) , { Headers2 , } = decode(iolist_to_binary(Encoded2 ) , DecState2 ) , # state{size=264 , max_size=512 , dyn_table= [ { 42,{<<":status " > > , < < " 307 " > > } } , %% {63,{<<"location">>, <<"">>}}, { 65,{<<"date " > > , < < " Mon , 21 Oct 2013 20:13:21 GMT " > > } } , { 52,{<<"cache - control " > > , < < " private " > > } } , { 42,{<<":status " > > , < < " 302 " > > } } ] } = DecState3 , # state{size=264 , max_size=512 , dyn_table= [ { 42,{<<":status " > > , < < " 307 " > > } } , %% {63,{<<"location">>, <<"">>}}, { 65,{<<"date " > > , < < " Mon , 21 Oct 2013 20:13:21 GMT " > > } } , { 52,{<<"cache - control " > > , < < " private " > > } } , { 42,{<<":status " > > , < < " 302 " > > } } ] } = EncState3 , %% ok. %% %%encode_iolist_test() -> %% Headers = [ %% {<<":method">>, <<"GET">>}, %% {<<":scheme">>, <<"http">>}, %% {<<":path">>, <<"/">>}, %% {<<":authority">>, <<"www.example.com">>}, %% {<<"content-type">>, [<<"image">>,<<"/">>,<<"png">>,<<>>]} %% ], { _ , _ } = encode(Headers ) , %% ok. %% %%horse_encode_raw() -> %% horse:repeat(20000, %% do_horse_encode_raw() %% ). %% do_horse_encode_raw ( ) - > %% Headers1 = [ %% {<<":method">>, <<"GET">>}, %% {<<":scheme">>, <<"http">>}, %% {<<":path">>, <<"/">>}, %% {<<":authority">>, <<"www.example.com">>} %% ], { _ , State1 } = encode(Headers1 , init ( ) , # { huffman = > false } ) , %% Headers2 = [ %% {<<":method">>, <<"GET">>}, %% {<<":scheme">>, <<"http">>}, %% {<<":path">>, <<"/">>}, %% {<<":authority">>, <<"www.example.com">>}, %% {<<"cache-control">>, <<"no-cache">>} %% ], %% {_, State2} = encode(Headers2, State1, #{huffman => false}), Headers3 = [ %% {<<":method">>, <<"GET">>}, %% {<<":scheme">>, <<"https">>}, { < < " : path " > > , < < " /index.html " > > } , %% {<<":authority">>, <<"www.example.com">>}, %% {<<"custom-key">>, <<"custom-value">>} %% ], { _ , _ } = encode(Headers3 , State2 , # { huffman = > false } ) , %% ok. %% %%horse_encode_huffman() -> %% horse:repeat(20000, %% do_horse_encode_huffman() %% ). %% %%do_horse_encode_huffman() -> %% Headers1 = [ %% {<<":method">>, <<"GET">>}, %% {<<":scheme">>, <<"http">>}, %% {<<":path">>, <<"/">>}, %% {<<":authority">>, <<"www.example.com">>} %% ], %% {_, State1} = encode(Headers1), %% Headers2 = [ %% {<<":method">>, <<"GET">>}, %% {<<":scheme">>, <<"http">>}, %% {<<":path">>, <<"/">>}, %% {<<":authority">>, <<"www.example.com">>}, %% {<<"cache-control">>, <<"no-cache">>} %% ], %% {_, State2} = encode(Headers2, State1), Headers3 = [ %% {<<":method">>, <<"GET">>}, %% {<<":scheme">>, <<"https">>}, { < < " : path " > > , < < " /index.html " > > } , %% {<<":authority">>, <<"www.example.com">>}, %% {<<"custom-key">>, <<"custom-value">>} %% ], { _ , _ } = encode(Headers3 , State2 ) , %% ok. %%-endif. %% Static and dynamic tables. %% @todo There must be a more efficient way. table_find(Header = {Name, _}, State) -> case table_find_field(Header, State) of not_found -> case table_find_name(Name, State) of NotFound = not_found -> NotFound; Found -> {name, Found} end; Found -> {field, Found} end. table_find_field({<<":authority">>, <<>>}, _) -> 1; table_find_field({<<":method">>, <<"GET">>}, _) -> 2; table_find_field({<<":method">>, <<"POST">>}, _) -> 3; table_find_field({<<":path">>, <<"/">>}, _) -> 4; table_find_field({<<":path">>, <<"/index.html">>}, _) -> 5; table_find_field({<<":scheme">>, <<"http">>}, _) -> 6; table_find_field({<<":scheme">>, <<"https">>}, _) -> 7; table_find_field({<<":status">>, <<"200">>}, _) -> 8; table_find_field({<<":status">>, <<"204">>}, _) -> 9; table_find_field({<<":status">>, <<"206">>}, _) -> 10; table_find_field({<<":status">>, <<"304">>}, _) -> 11; table_find_field({<<":status">>, <<"400">>}, _) -> 12; table_find_field({<<":status">>, <<"404">>}, _) -> 13; table_find_field({<<":status">>, <<"500">>}, _) -> 14; table_find_field({<<"accept-charset">>, <<>>}, _) -> 15; table_find_field({<<"accept-encoding">>, <<"gzip, deflate">>}, _) -> 16; table_find_field({<<"accept-language">>, <<>>}, _) -> 17; table_find_field({<<"accept-ranges">>, <<>>}, _) -> 18; table_find_field({<<"accept">>, <<>>}, _) -> 19; table_find_field({<<"access-control-allow-origin">>, <<>>}, _) -> 20; table_find_field({<<"age">>, <<>>}, _) -> 21; table_find_field({<<"allow">>, <<>>}, _) -> 22; table_find_field({<<"authorization">>, <<>>}, _) -> 23; table_find_field({<<"cache-control">>, <<>>}, _) -> 24; table_find_field({<<"content-disposition">>, <<>>}, _) -> 25; table_find_field({<<"content-encoding">>, <<>>}, _) -> 26; table_find_field({<<"content-language">>, <<>>}, _) -> 27; table_find_field({<<"content-length">>, <<>>}, _) -> 28; table_find_field({<<"content-location">>, <<>>}, _) -> 29; table_find_field({<<"content-range">>, <<>>}, _) -> 30; table_find_field({<<"content-type">>, <<>>}, _) -> 31; table_find_field({<<"cookie">>, <<>>}, _) -> 32; table_find_field({<<"date">>, <<>>}, _) -> 33; table_find_field({<<"etag">>, <<>>}, _) -> 34; table_find_field({<<"expect">>, <<>>}, _) -> 35; table_find_field({<<"expires">>, <<>>}, _) -> 36; table_find_field({<<"from">>, <<>>}, _) -> 37; table_find_field({<<"host">>, <<>>}, _) -> 38; table_find_field({<<"if-match">>, <<>>}, _) -> 39; table_find_field({<<"if-modified-since">>, <<>>}, _) -> 40; table_find_field({<<"if-none-match">>, <<>>}, _) -> 41; table_find_field({<<"if-range">>, <<>>}, _) -> 42; table_find_field({<<"if-unmodified-since">>, <<>>}, _) -> 43; table_find_field({<<"last-modified">>, <<>>}, _) -> 44; table_find_field({<<"link">>, <<>>}, _) -> 45; table_find_field({<<"location">>, <<>>}, _) -> 46; table_find_field({<<"max-forwards">>, <<>>}, _) -> 47; table_find_field({<<"proxy-authenticate">>, <<>>}, _) -> 48; table_find_field({<<"proxy-authorization">>, <<>>}, _) -> 49; table_find_field({<<"range">>, <<>>}, _) -> 50; table_find_field({<<"referer">>, <<>>}, _) -> 51; table_find_field({<<"refresh">>, <<>>}, _) -> 52; table_find_field({<<"retry-after">>, <<>>}, _) -> 53; table_find_field({<<"server">>, <<>>}, _) -> 54; table_find_field({<<"set-cookie">>, <<>>}, _) -> 55; table_find_field({<<"strict-transport-security">>, <<>>}, _) -> 56; table_find_field({<<"transfer-encoding">>, <<>>}, _) -> 57; table_find_field({<<"user-agent">>, <<>>}, _) -> 58; table_find_field({<<"vary">>, <<>>}, _) -> 59; table_find_field({<<"via">>, <<>>}, _) -> 60; table_find_field({<<"www-authenticate">>, <<>>}, _) -> 61; table_find_field(Header, #state{dyn_table=DynamicTable}) -> table_find_field_dyn(Header, DynamicTable, 62). table_find_field_dyn(_, [], _) -> not_found; table_find_field_dyn(Header, [{_, Header}|_], Index) -> Index; table_find_field_dyn(Header, [_|Tail], Index) -> table_find_field_dyn(Header, Tail, Index + 1). table_find_name(<<":authority">>, _) -> 1; table_find_name(<<":method">>, _) -> 2; table_find_name(<<":path">>, _) -> 4; table_find_name(<<":scheme">>, _) -> 6; table_find_name(<<":status">>, _) -> 8; table_find_name(<<"accept-charset">>, _) -> 15; table_find_name(<<"accept-encoding">>, _) -> 16; table_find_name(<<"accept-language">>, _) -> 17; table_find_name(<<"accept-ranges">>, _) -> 18; table_find_name(<<"accept">>, _) -> 19; table_find_name(<<"access-control-allow-origin">>, _) -> 20; table_find_name(<<"age">>, _) -> 21; table_find_name(<<"allow">>, _) -> 22; table_find_name(<<"authorization">>, _) -> 23; table_find_name(<<"cache-control">>, _) -> 24; table_find_name(<<"content-disposition">>, _) -> 25; table_find_name(<<"content-encoding">>, _) -> 26; table_find_name(<<"content-language">>, _) -> 27; table_find_name(<<"content-length">>, _) -> 28; table_find_name(<<"content-location">>, _) -> 29; table_find_name(<<"content-range">>, _) -> 30; table_find_name(<<"content-type">>, _) -> 31; table_find_name(<<"cookie">>, _) -> 32; table_find_name(<<"date">>, _) -> 33; table_find_name(<<"etag">>, _) -> 34; table_find_name(<<"expect">>, _) -> 35; table_find_name(<<"expires">>, _) -> 36; table_find_name(<<"from">>, _) -> 37; table_find_name(<<"host">>, _) -> 38; table_find_name(<<"if-match">>, _) -> 39; table_find_name(<<"if-modified-since">>, _) -> 40; table_find_name(<<"if-none-match">>, _) -> 41; table_find_name(<<"if-range">>, _) -> 42; table_find_name(<<"if-unmodified-since">>, _) -> 43; table_find_name(<<"last-modified">>, _) -> 44; table_find_name(<<"link">>, _) -> 45; table_find_name(<<"location">>, _) -> 46; table_find_name(<<"max-forwards">>, _) -> 47; table_find_name(<<"proxy-authenticate">>, _) -> 48; table_find_name(<<"proxy-authorization">>, _) -> 49; table_find_name(<<"range">>, _) -> 50; table_find_name(<<"referer">>, _) -> 51; table_find_name(<<"refresh">>, _) -> 52; table_find_name(<<"retry-after">>, _) -> 53; table_find_name(<<"server">>, _) -> 54; table_find_name(<<"set-cookie">>, _) -> 55; table_find_name(<<"strict-transport-security">>, _) -> 56; table_find_name(<<"transfer-encoding">>, _) -> 57; table_find_name(<<"user-agent">>, _) -> 58; table_find_name(<<"vary">>, _) -> 59; table_find_name(<<"via">>, _) -> 60; table_find_name(<<"www-authenticate">>, _) -> 61; table_find_name(Name, #state{dyn_table=DynamicTable}) -> table_find_name_dyn(Name, DynamicTable, 62). table_find_name_dyn(_, [], _) -> not_found; table_find_name_dyn(Name, [{Name, _}|_], Index) -> Index; table_find_name_dyn(Name, [_|Tail], Index) -> table_find_name_dyn(Name, Tail, Index + 1). table_get(1, _) -> {<<":authority">>, <<>>}; table_get(2, _) -> {<<":method">>, <<"GET">>}; table_get(3, _) -> {<<":method">>, <<"POST">>}; table_get(4, _) -> {<<":path">>, <<"/">>}; table_get(5, _) -> {<<":path">>, <<"/index.html">>}; table_get(6, _) -> {<<":scheme">>, <<"http">>}; table_get(7, _) -> {<<":scheme">>, <<"https">>}; table_get(8, _) -> {<<":status">>, <<"200">>}; table_get(9, _) -> {<<":status">>, <<"204">>}; table_get(10, _) -> {<<":status">>, <<"206">>}; table_get(11, _) -> {<<":status">>, <<"304">>}; table_get(12, _) -> {<<":status">>, <<"400">>}; table_get(13, _) -> {<<":status">>, <<"404">>}; table_get(14, _) -> {<<":status">>, <<"500">>}; table_get(15, _) -> {<<"accept-charset">>, <<>>}; table_get(16, _) -> {<<"accept-encoding">>, <<"gzip, deflate">>}; table_get(17, _) -> {<<"accept-language">>, <<>>}; table_get(18, _) -> {<<"accept-ranges">>, <<>>}; table_get(19, _) -> {<<"accept">>, <<>>}; table_get(20, _) -> {<<"access-control-allow-origin">>, <<>>}; table_get(21, _) -> {<<"age">>, <<>>}; table_get(22, _) -> {<<"allow">>, <<>>}; table_get(23, _) -> {<<"authorization">>, <<>>}; table_get(24, _) -> {<<"cache-control">>, <<>>}; table_get(25, _) -> {<<"content-disposition">>, <<>>}; table_get(26, _) -> {<<"content-encoding">>, <<>>}; table_get(27, _) -> {<<"content-language">>, <<>>}; table_get(28, _) -> {<<"content-length">>, <<>>}; table_get(29, _) -> {<<"content-location">>, <<>>}; table_get(30, _) -> {<<"content-range">>, <<>>}; table_get(31, _) -> {<<"content-type">>, <<>>}; table_get(32, _) -> {<<"cookie">>, <<>>}; table_get(33, _) -> {<<"date">>, <<>>}; table_get(34, _) -> {<<"etag">>, <<>>}; table_get(35, _) -> {<<"expect">>, <<>>}; table_get(36, _) -> {<<"expires">>, <<>>}; table_get(37, _) -> {<<"from">>, <<>>}; table_get(38, _) -> {<<"host">>, <<>>}; table_get(39, _) -> {<<"if-match">>, <<>>}; table_get(40, _) -> {<<"if-modified-since">>, <<>>}; table_get(41, _) -> {<<"if-none-match">>, <<>>}; table_get(42, _) -> {<<"if-range">>, <<>>}; table_get(43, _) -> {<<"if-unmodified-since">>, <<>>}; table_get(44, _) -> {<<"last-modified">>, <<>>}; table_get(45, _) -> {<<"link">>, <<>>}; table_get(46, _) -> {<<"location">>, <<>>}; table_get(47, _) -> {<<"max-forwards">>, <<>>}; table_get(48, _) -> {<<"proxy-authenticate">>, <<>>}; table_get(49, _) -> {<<"proxy-authorization">>, <<>>}; table_get(50, _) -> {<<"range">>, <<>>}; table_get(51, _) -> {<<"referer">>, <<>>}; table_get(52, _) -> {<<"refresh">>, <<>>}; table_get(53, _) -> {<<"retry-after">>, <<>>}; table_get(54, _) -> {<<"server">>, <<>>}; table_get(55, _) -> {<<"set-cookie">>, <<>>}; table_get(56, _) -> {<<"strict-transport-security">>, <<>>}; table_get(57, _) -> {<<"transfer-encoding">>, <<>>}; table_get(58, _) -> {<<"user-agent">>, <<>>}; table_get(59, _) -> {<<"vary">>, <<>>}; table_get(60, _) -> {<<"via">>, <<>>}; table_get(61, _) -> {<<"www-authenticate">>, <<>>}; table_get(Index, #state{dyn_table=DynamicTable}) -> {_, Header} = lists:nth(Index - 61, DynamicTable), Header. table_get_name(1, _) -> <<":authority">>; table_get_name(2, _) -> <<":method">>; table_get_name(3, _) -> <<":method">>; table_get_name(4, _) -> <<":path">>; table_get_name(5, _) -> <<":path">>; table_get_name(6, _) -> <<":scheme">>; table_get_name(7, _) -> <<":scheme">>; table_get_name(8, _) -> <<":status">>; table_get_name(9, _) -> <<":status">>; table_get_name(10, _) -> <<":status">>; table_get_name(11, _) -> <<":status">>; table_get_name(12, _) -> <<":status">>; table_get_name(13, _) -> <<":status">>; table_get_name(14, _) -> <<":status">>; table_get_name(15, _) -> <<"accept-charset">>; table_get_name(16, _) -> <<"accept-encoding">>; table_get_name(17, _) -> <<"accept-language">>; table_get_name(18, _) -> <<"accept-ranges">>; table_get_name(19, _) -> <<"accept">>; table_get_name(20, _) -> <<"access-control-allow-origin">>; table_get_name(21, _) -> <<"age">>; table_get_name(22, _) -> <<"allow">>; table_get_name(23, _) -> <<"authorization">>; table_get_name(24, _) -> <<"cache-control">>; table_get_name(25, _) -> <<"content-disposition">>; table_get_name(26, _) -> <<"content-encoding">>; table_get_name(27, _) -> <<"content-language">>; table_get_name(28, _) -> <<"content-length">>; table_get_name(29, _) -> <<"content-location">>; table_get_name(30, _) -> <<"content-range">>; table_get_name(31, _) -> <<"content-type">>; table_get_name(32, _) -> <<"cookie">>; table_get_name(33, _) -> <<"date">>; table_get_name(34, _) -> <<"etag">>; table_get_name(35, _) -> <<"expect">>; table_get_name(36, _) -> <<"expires">>; table_get_name(37, _) -> <<"from">>; table_get_name(38, _) -> <<"host">>; table_get_name(39, _) -> <<"if-match">>; table_get_name(40, _) -> <<"if-modified-since">>; table_get_name(41, _) -> <<"if-none-match">>; table_get_name(42, _) -> <<"if-range">>; table_get_name(43, _) -> <<"if-unmodified-since">>; table_get_name(44, _) -> <<"last-modified">>; table_get_name(45, _) -> <<"link">>; table_get_name(46, _) -> <<"location">>; table_get_name(47, _) -> <<"max-forwards">>; table_get_name(48, _) -> <<"proxy-authenticate">>; table_get_name(49, _) -> <<"proxy-authorization">>; table_get_name(50, _) -> <<"range">>; table_get_name(51, _) -> <<"referer">>; table_get_name(52, _) -> <<"refresh">>; table_get_name(53, _) -> <<"retry-after">>; table_get_name(54, _) -> <<"server">>; table_get_name(55, _) -> <<"set-cookie">>; table_get_name(56, _) -> <<"strict-transport-security">>; table_get_name(57, _) -> <<"transfer-encoding">>; table_get_name(58, _) -> <<"user-agent">>; table_get_name(59, _) -> <<"vary">>; table_get_name(60, _) -> <<"via">>; table_get_name(61, _) -> <<"www-authenticate">>; table_get_name(Index, #state{dyn_table=DynamicTable}) -> {_, {Name, _}} = lists:nth(Index - 61, DynamicTable), Name. table_insert(Entry = {Name, Value}, State=#state{size=Size, max_size=MaxSize, dyn_table=DynamicTable}) -> EntrySize = byte_size(Name) + byte_size(Value) + 32, {DynamicTable2, Size2} = if Size + EntrySize > MaxSize -> table_resize(DynamicTable, MaxSize - EntrySize, 0, []); true -> {DynamicTable, Size} end, State#state{size=Size2 + EntrySize, dyn_table=[{EntrySize, Entry}|DynamicTable2]}. table_resize([], _, Size, Acc) -> {lists:reverse(Acc), Size}; table_resize([{EntrySize, _}|_], MaxSize, Size, Acc) when Size + EntrySize > MaxSize -> {lists:reverse(Acc), Size}; table_resize([Entry = {EntrySize, _}|Tail], MaxSize, Size, Acc) -> table_resize(Tail, MaxSize, Size + EntrySize, [Entry|Acc]). table_update_size(0, State) -> State#state{size=0, max_size=0, dyn_table=[]}; table_update_size(MaxSize, State=#state{max_size=CurrentMaxSize}) when CurrentMaxSize =< MaxSize -> State#state{max_size=MaxSize}; table_update_size(MaxSize, State=#state{dyn_table=DynTable}) -> {DynTable2, Size} = table_resize(DynTable, MaxSize, 0, []), State#state{size=Size, max_size=MaxSize, dyn_table=DynTable2}. %%-ifdef(TEST). %%prop_str_raw() -> ? FORALL(Str , binary ( ) , begin { Str , < < > > } = : = dec_str(iolist_to_binary(enc_str(Str , ) ) ) %% end). %% %%prop_str_huffman() -> ? FORALL(Str , binary ( ) , begin { Str , < < > > } = : = dec_str(iolist_to_binary(enc_str(Str , ) ) ) %% end). %%-endif.
null
https://raw.githubusercontent.com/duncanatt/detecter/95b6a758ce6c60f3b7377c07607f24d126cbdacf/experiments/coordination_2022/src/cowlib/cow_hpack.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. The current implementation is not suitable for use in intermediaries as the information about headers that should never be indexed is currently lost. -ifdef(TEST). -include_lib("proper/include/proper.hrl"). -endif. Update the configured max size. When decoding, the local endpoint also needs to send a SETTINGS frame with this value and it is then up to the remote endpoint to decide what actual limit it will use. The actual limit is signaled via dynamic table size updates in the encoded data. When encoding, the local endpoint will call this function after receiving a SETTINGS frame with this value. The encoder will then use this value as the new max after signaling via a dynamic table size update. The value given as argument may be lower than the one received in the SETTINGS. Decoding. Dynamic table size update is only allowed at the beginning of a HEADERS block. Indexed header field representation. Literal header field with incremental indexing: new name. Literal header field with incremental indexing: indexed name. Literal header field without indexing: new name. Literal header field without indexing: indexed name. Literal header field never indexed: new name. @todo Keep track of "never indexed" headers. Literal header field never indexed: indexed name. @todo Keep track of "never indexed" headers. Indexed header field representation. We do the integer decoding inline where appropriate, falling back to dec_big_int for larger values. Literal header field with incremental indexing. We do the integer decoding inline where appropriate, falling back to dec_big_int for larger values. Literal header field without indexing. We do the integer decoding inline where appropriate, falling back to dec_big_int for larger values. @todo Literal header field never indexed. Decode an integer. and each can be used to create an indefinite length integer if all bits Decode a string. We use a lookup table that allows us to benefit from the binary match context optimization. A more naive implementation using bit pattern matching cannot reuse a match context because it wouldn't always match on byte boundaries. See cow_hpack_dec_huffman_lookup.hrl for more details. Can only be reached when the string length to decode is 0. -ifdef(TEST). Test case extracted from h2spec. ok. req_decode_test() -> % First request ( raw then ) . {Headers1, State1} = decode(<< 16#828684410f7777772e6578616d706c652e636f6d:160 >>), {Headers1, State1} = decode(<< 16#828684418cf1e3c2e5f23a6ba0ab90f4ff:136 >>), Headers1 = [ {<<":method">>, <<"GET">>}, {<<":scheme">>, <<"http">>}, {<<":path">>, <<"/">>}, {<<":authority">>, <<"www.example.com">>} ], #state{size=57, dyn_table=[{57,{<<":authority">>, <<"www.example.com">>}}]} = State1, % Second request ( raw then ) . {Headers2, State2} = decode(<< 16#828684be5886a8eb10649cbf:96 >>, State1), Headers2 = [ {<<":method">>, <<"GET">>}, {<<":scheme">>, <<"http">>}, {<<":path">>, <<"/">>}, {<<":authority">>, <<"www.example.com">>}, {<<"cache-control">>, <<"no-cache">>} ], #state{size=110, dyn_table=[ {57,{<<":authority">>, <<"www.example.com">>}}]} = State2, % Third request ( raw then ) . {<<":method">>, <<"GET">>}, {<<":scheme">>, <<"https">>}, {<<":authority">>, <<"www.example.com">>}, {<<"custom-key">>, <<"custom-value">>} ], {57,{<<":authority">>, <<"www.example.com">>}}]} = State3, ok. resp_decode_test() -> % Use a max_size of 256 to trigger header evictions . State0 = init(256), % First response ( raw then ) . Headers1 = [ {<<"cache-control">>, <<"private">>}, {<<"location">>, <<"">>} ], #state{size=222, dyn_table=[ {63,{<<"location">>, <<"">>}}, % Second response ( raw then ) . Headers2 = [ {<<"cache-control">>, <<"private">>}, {<<"location">>, <<"">>} ], #state{size=222, dyn_table=[ {63,{<<"location">>, <<"">>}}, % Third response ( raw then ) . {<<"cache-control">>, <<"private">>}, {<<"location">>, <<"">>}, {<<"content-encoding">>, <<"gzip">>}, ], #state{size=215, dyn_table=[ {52,{<<"content-encoding">>, <<"gzip">>}}, ok. table_update_decode_test() -> % Use a max_size of 256 to trigger header evictions % when the code is not updating the size . State0 = init(256), % First response ( raw then ) . Headers1 = [ {<<"cache-control">>, <<"private">>}, {<<"location">>, <<"">>} ], #state{size=222, configured_max_size=256, dyn_table=[ {63,{<<"location">>, <<"">>}}, %% Set a new configured max_size to avoid header evictions. State2 = set_max_size(512, State1), % Second response with the table size update ( raw then ) . {Headers2, State3} = decode( State2), {Headers2, State3} = decode( State2), Headers2 = [ {<<"cache-control">>, <<"private">>}, {<<"location">>, <<"">>} ], {63,{<<"location">>, <<"">>}}, ok. table_update_decode_smaller_test() -> % Use a max_size of 256 to trigger header evictions % when the code is not updating the size . State0 = init(256), % First response ( raw then ) . Headers1 = [ {<<"cache-control">>, <<"private">>}, {<<"location">>, <<"">>} ], #state{size=222, configured_max_size=256, dyn_table=[ {63,{<<"location">>, <<"">>}}, %% Set a new configured max_size to avoid header evictions. State2 = set_max_size(512, State1), % Second response with the table size update smaller than the limit ( raw then ) . {Headers2, State3} = decode( State2), {Headers2, State3} = decode( State2), Headers2 = [ {<<"cache-control">>, <<"private">>}, {<<"location">>, <<"">>} ], {63,{<<"location">>, <<"">>}}, ok. table_update_decode_too_large_test() -> % Use a max_size of 256 to trigger header evictions % when the code is not updating the size . State0 = init(256), % First response ( raw then ) . Headers1 = [ {<<"cache-control">>, <<"private">>}, {<<"location">>, <<"">>} ], #state{size=222, configured_max_size=256, dyn_table=[ {63,{<<"location">>, <<"">>}}, %% Set a new configured max_size to avoid header evictions. State2 = set_max_size(512, State1), % Second response with the table size update ( raw then ) . State2)), State2)), ok. table_update_decode_zero_test() -> State0 = init(256), % First response ( raw then ) . Headers1 = [ {<<"cache-control">>, <<"private">>}, {<<"location">>, <<"">>} ], #state{size=222, configured_max_size=256, dyn_table=[ {63,{<<"location">>, <<"">>}}, %% Set a new configured max_size to avoid header evictions. State2 = set_max_size(512, State1), % Second response with the table size update ( raw then ) . %% We set the table size to 0 to evict all values before setting % it to 512 so we only get the second request indexed . {Headers1, State3} = decode(iolist_to_binary([ State2), {Headers1, State3} = decode(iolist_to_binary([ State2), {63,{<<"location">>, <<"">>}}, ok. horse_decode_raw() -> horse:repeat(20000, do_horse_decode_raw() ). do_horse_decode_raw() -> {_, State1} = decode(<<16#828684410f7777772e6578616d706c652e636f6d:160>>), {_, State2} = decode(<<16#828684be58086e6f2d6361636865:112>>, State1), {_, _} = decode(<<16#828785bf400a637573746f6d2d6b65790c637573746f6d2d76616c7565:232>>, State2), ok. horse:repeat(20000, do_horse_decode_huffman() ). do_horse_decode_huffman() -> {_, State1} = decode(<<16#828684418cf1e3c2e5f23a6ba0ab90f4ff:136>>), {_, _} = decode(<<16#828785bf408825a849e95ba97d7f8925a849e95bb8e8b4bf:192>>, State2), ok. -endif. Encoding. @todo Handle cases where no/never indexing is expected. We conditionally call iolist_to_binary/1 because a small but noticeable speed improvement happens when we do this. Indexed header field representation. Literal header field representation: indexed name. Literal header field representation: new name. Encode an integer. Encode a string. -ifdef(TEST). req_encode_test() -> % First request ( raw then ) . Headers1 = [ {<<":method">>, <<"GET">>}, {<<":scheme">>, <<"http">>}, {<<":path">>, <<"/">>}, {<<":authority">>, <<"www.example.com">>} ], << 16#828684410f7777772e6578616d706c652e636f6d:160 >> = iolist_to_binary(Raw1), {Huff1, State1} = encode(Headers1), << 16#828684418cf1e3c2e5f23a6ba0ab90f4ff:136 >> = iolist_to_binary(Huff1), #state{size=57, dyn_table=[{57,{<<":authority">>, <<"www.example.com">>}}]} = State1, % Second request ( raw then ) . Headers2 = [ {<<":method">>, <<"GET">>}, {<<":scheme">>, <<"http">>}, {<<":path">>, <<"/">>}, {<<":authority">>, <<"www.example.com">>}, {<<"cache-control">>, <<"no-cache">>} ], {Raw2, State2} = encode(Headers2, State1, #{huffman => false}), {Huff2, State2} = encode(Headers2, State1), << 16#828684be5886a8eb10649cbf:96 >> = iolist_to_binary(Huff2), #state{size=110, dyn_table=[ {57,{<<":authority">>, <<"www.example.com">>}}]} = State2, % Third request ( raw then ) . {<<":method">>, <<"GET">>}, {<<":scheme">>, <<"https">>}, {<<":authority">>, <<"www.example.com">>}, {<<"custom-key">>, <<"custom-value">>} ], {57,{<<":authority">>, <<"www.example.com">>}}]} = State3, ok. resp_encode_test() -> % Use a max_size of 256 to trigger header evictions . State0 = init(256), % First response ( raw then ) . Headers1 = [ {<<"cache-control">>, <<"private">>}, {<<"location">>, <<"">>} ], {Raw1, State1} = encode(Headers1, State0, #{huffman => false}), {Huff1, State1} = encode(Headers1, State0), #state{size=222, dyn_table=[ {63,{<<"location">>, <<"">>}}, % Second response ( raw then ) . Headers2 = [ {<<"cache-control">>, <<"private">>}, {<<"location">>, <<"">>} ], {Raw2, State2} = encode(Headers2, State1, #{huffman => false}), {Huff2, State2} = encode(Headers2, State1), << 16#4883640effc1c0bf:64 >> = iolist_to_binary(Huff2), #state{size=222, dyn_table=[ {63,{<<"location">>, <<"">>}}, % Third response ( raw then ) . {<<"cache-control">>, <<"private">>}, {<<"location">>, <<"">>}, {<<"content-encoding">>, <<"gzip">>}, ], << 16#88c1611d4d6f6e2c203231204f637420323031332032303a31333a323220474d54c05a04677a69707738666f6f3d4153444a4b48514b425a584f5157454f50495541585157454f49553b206d61782d6167653d333630303b2076657273696f6e3d31:784 >> = iolist_to_binary(Raw3), #state{size=215, dyn_table=[ {52,{<<"content-encoding">>, <<"gzip">>}}, ok. This test assumes that table updates work correctly when decoding. table_update_encode_test() -> % Use a max_size of 256 to trigger header evictions % when the code is not updating the size . DecState0 = EncState0 = init(256), % First response . Headers1 = [ {<<"cache-control">>, <<"private">>}, {<<"location">>, <<"">>} ], #state{size=222, configured_max_size=256, dyn_table=[ {63,{<<"location">>, <<"">>}}, #state{size=222, configured_max_size=256, dyn_table=[ {63,{<<"location">>, <<"">>}}, %% Set a new configured max_size to avoid header evictions. % Second response . Headers2 = [ {<<"cache-control">>, <<"private">>}, {<<"location">>, <<"">>} ], {63,{<<"location">>, <<"">>}}, {63,{<<"location">>, <<"">>}}, ok. encode_iolist_test() -> Headers = [ {<<":method">>, <<"GET">>}, {<<":scheme">>, <<"http">>}, {<<":path">>, <<"/">>}, {<<":authority">>, <<"www.example.com">>}, {<<"content-type">>, [<<"image">>,<<"/">>,<<"png">>,<<>>]} ], ok. horse_encode_raw() -> horse:repeat(20000, do_horse_encode_raw() ). Headers1 = [ {<<":method">>, <<"GET">>}, {<<":scheme">>, <<"http">>}, {<<":path">>, <<"/">>}, {<<":authority">>, <<"www.example.com">>} ], Headers2 = [ {<<":method">>, <<"GET">>}, {<<":scheme">>, <<"http">>}, {<<":path">>, <<"/">>}, {<<":authority">>, <<"www.example.com">>}, {<<"cache-control">>, <<"no-cache">>} ], {_, State2} = encode(Headers2, State1, #{huffman => false}), {<<":method">>, <<"GET">>}, {<<":scheme">>, <<"https">>}, {<<":authority">>, <<"www.example.com">>}, {<<"custom-key">>, <<"custom-value">>} ], ok. horse_encode_huffman() -> horse:repeat(20000, do_horse_encode_huffman() ). do_horse_encode_huffman() -> Headers1 = [ {<<":method">>, <<"GET">>}, {<<":scheme">>, <<"http">>}, {<<":path">>, <<"/">>}, {<<":authority">>, <<"www.example.com">>} ], {_, State1} = encode(Headers1), Headers2 = [ {<<":method">>, <<"GET">>}, {<<":scheme">>, <<"http">>}, {<<":path">>, <<"/">>}, {<<":authority">>, <<"www.example.com">>}, {<<"cache-control">>, <<"no-cache">>} ], {_, State2} = encode(Headers2, State1), {<<":method">>, <<"GET">>}, {<<":scheme">>, <<"https">>}, {<<":authority">>, <<"www.example.com">>}, {<<"custom-key">>, <<"custom-value">>} ], ok. -endif. Static and dynamic tables. @todo There must be a more efficient way. -ifdef(TEST). prop_str_raw() -> end). prop_str_huffman() -> end). -endif.
Copyright ( c ) 2015 - 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(cow_hpack). -dialyzer(no_improper_lists). -export([init/0]). -export([init/1]). -export([set_max_size/2]). -export([decode/1]). -export([decode/2]). -export([encode/1]). -export([encode/2]). -export([encode/3]). -record(state, { size = 0 :: non_neg_integer(), max_size = 4096 :: non_neg_integer(), configured_max_size = 4096 :: non_neg_integer(), dyn_table = [] :: [{pos_integer(), {binary(), binary()}}] }). -opaque state() :: #state{}. -export_type([state/0]). -type opts() :: map(). -export_type([opts/0]). State initialization . -spec init() -> state(). init() -> #state{}. -spec init(non_neg_integer()) -> state(). init(MaxSize) -> #state{max_size=MaxSize, configured_max_size=MaxSize}. -spec set_max_size(non_neg_integer(), State) -> State when State::state(). set_max_size(MaxSize, State) -> State#state{configured_max_size=MaxSize}. -spec decode(binary()) -> {cow_http:headers(), state()}. decode(Data) -> decode(Data, init()). -spec decode(binary(), State) -> {cow_http:headers(), State} when State::state(). decode(<< 0:2, 1:1, Rest/bits >>, State=#state{configured_max_size=ConfigMaxSize}) -> {MaxSize, Rest2} = dec_int5(Rest), if MaxSize =< ConfigMaxSize -> State2 = table_update_size(MaxSize, State), decode(Rest2, State2) end; decode(Data, State) -> decode(Data, State, []). decode(<<>>, State, Acc) -> {lists:reverse(Acc), State}; decode(<< 1:1, Rest/bits >>, State, Acc) -> dec_indexed(Rest, State, Acc); decode(<< 0:1, 1:1, 0:6, Rest/bits >>, State, Acc) -> dec_lit_index_new_name(Rest, State, Acc); decode(<< 0:1, 1:1, Rest/bits >>, State, Acc) -> dec_lit_index_indexed_name(Rest, State, Acc); decode(<< 0:8, Rest/bits >>, State, Acc) -> dec_lit_no_index_new_name(Rest, State, Acc); decode(<< 0:4, Rest/bits >>, State, Acc) -> dec_lit_no_index_indexed_name(Rest, State, Acc); decode(<< 0:3, 1:1, 0:4, Rest/bits >>, State, Acc) -> dec_lit_no_index_new_name(Rest, State, Acc); decode(<< 0:3, 1:1, Rest/bits >>, State, Acc) -> dec_lit_no_index_indexed_name(Rest, State, Acc). dec_indexed(<<2#1111111:7, 0:1, Int:7, Rest/bits>>, State, Acc) -> {Name, Value} = table_get(127 + Int, State), decode(Rest, State, [{Name, Value}|Acc]); dec_indexed(<<2#1111111:7, Rest0/bits>>, State, Acc) -> {Index, Rest} = dec_big_int(Rest0, 127, 0), {Name, Value} = table_get(Index, State), decode(Rest, State, [{Name, Value}|Acc]); dec_indexed(<<Index:7, Rest/bits>>, State, Acc) -> {Name, Value} = table_get(Index, State), decode(Rest, State, [{Name, Value}|Acc]). dec_lit_index_new_name(Rest, State, Acc) -> {Name, Rest2} = dec_str(Rest), dec_lit_index(Rest2, State, Acc, Name). dec_lit_index_indexed_name(<<2#111111:6, 0:1, Int:7, Rest/bits>>, State, Acc) -> Name = table_get_name(63 + Int, State), dec_lit_index(Rest, State, Acc, Name); dec_lit_index_indexed_name(<<2#111111:6, Rest0/bits>>, State, Acc) -> {Index, Rest} = dec_big_int(Rest0, 63, 0), Name = table_get_name(Index, State), dec_lit_index(Rest, State, Acc, Name); dec_lit_index_indexed_name(<<Index:6, Rest/bits>>, State, Acc) -> Name = table_get_name(Index, State), dec_lit_index(Rest, State, Acc, Name). dec_lit_index(Rest, State, Acc, Name) -> {Value, Rest2} = dec_str(Rest), State2 = table_insert({Name, Value}, State), decode(Rest2, State2, [{Name, Value}|Acc]). dec_lit_no_index_new_name(Rest, State, Acc) -> {Name, Rest2} = dec_str(Rest), dec_lit_no_index(Rest2, State, Acc, Name). dec_lit_no_index_indexed_name(<<2#1111:4, 0:1, Int:7, Rest/bits>>, State, Acc) -> Name = table_get_name(15 + Int, State), dec_lit_no_index(Rest, State, Acc, Name); dec_lit_no_index_indexed_name(<<2#1111:4, Rest0/bits>>, State, Acc) -> {Index, Rest} = dec_big_int(Rest0, 15, 0), Name = table_get_name(Index, State), dec_lit_no_index(Rest, State, Acc, Name); dec_lit_no_index_indexed_name(<<Index:4, Rest/bits>>, State, Acc) -> Name = table_get_name(Index, State), dec_lit_no_index(Rest, State, Acc, Name). dec_lit_no_index(Rest, State, Acc, Name) -> {Value, Rest2} = dec_str(Rest), decode(Rest2, State, [{Name, Value}|Acc]). The HPACK format has 4 different integer prefixes length ( from 4 to 7 ) of the prefix are set to 1 . dec_int5(<< 2#11111:5, Rest/bits >>) -> dec_big_int(Rest, 31, 0); dec_int5(<< Int:5, Rest/bits >>) -> {Int, Rest}. dec_big_int(<< 0:1, Value:7, Rest/bits >>, Int, M) -> {Int + (Value bsl M), Rest}; dec_big_int(<< 1:1, Value:7, Rest/bits >>, Int, M) -> dec_big_int(Rest, Int + (Value bsl M), M + 7). dec_str(<<0:1, 2#1111111:7, Rest0/bits>>) -> {Length, Rest1} = dec_big_int(Rest0, 127, 0), <<Str:Length/binary, Rest/bits>> = Rest1, {Str, Rest}; dec_str(<<0:1, Length:7, Rest0/bits>>) -> <<Str:Length/binary, Rest/bits>> = Rest0, {Str, Rest}; dec_str(<<1:1, 2#1111111:7, Rest0/bits>>) -> {Length, Rest} = dec_big_int(Rest0, 127, 0), dec_huffman(Rest, Length, 0, <<>>); dec_str(<<1:1, Length:7, Rest/bits>>) -> dec_huffman(Rest, Length, 0, <<>>). dec_huffman(<<A:4, B:4, R/bits>>, Len, Huff0, Acc) when Len > 1 -> {_, CharA, Huff1} = dec_huffman_lookup(Huff0, A), {_, CharB, Huff} = dec_huffman_lookup(Huff1, B), case {CharA, CharB} of {undefined, undefined} -> dec_huffman(R, Len - 1, Huff, Acc); {CharA, undefined} -> dec_huffman(R, Len - 1, Huff, <<Acc/binary, CharA>>); {undefined, CharB} -> dec_huffman(R, Len - 1, Huff, <<Acc/binary, CharB>>); {CharA, CharB} -> dec_huffman(R, Len - 1, Huff, <<Acc/binary, CharA, CharB>>) end; dec_huffman(<<A:4, B:4, Rest/bits>>, 1, Huff0, Acc) -> {_, CharA, Huff} = dec_huffman_lookup(Huff0, A), {ok, CharB, _} = dec_huffman_lookup(Huff, B), case {CharA, CharB} of { undefined , undefined } ( > 7 - bit final padding ) is rejected with a crash . {CharA, undefined} -> {<<Acc/binary, CharA>>, Rest}; {undefined, CharB} -> {<<Acc/binary, CharB>>, Rest}; _ -> {<<Acc/binary, CharA, CharB>>, Rest} end; dec_huffman(Rest, 0, _, <<>>) -> {<<>>, Rest}. -include("cow_hpack_dec_huffman_lookup.hrl"). decode_reject_eos_test ( ) - > { ' EXIT ' , _ } = ( catch decode(<<16#0085f2b24a84ff874951fffffffa7f:120 > > ) ) , { Headers2 , State2 } = decode ( < < 16#828684be58086e6f2d6361636865:112 > > , State1 ) , { 53,{<<"cache - control " > > , < < " no - cache " > > } } , { Headers3 , State3 } = decode ( < < 16#828785bf400a637573746f6d2d6b65790c637573746f6d2d76616c7565:232 > > , State2 ) , { Headers3 , State3 } = decode ( < < 16#828785bf408825a849e95ba97d7f8925a849e95bb8e8b4bf:192 > > , State2 ) , Headers3 = [ { < < " : path " > > , < < " /index.html " > > } , # state{size=164 , dyn_table= [ { 54,{<<"custom - key " > > , < < " custom - value " > > } } , { 53,{<<"cache - control " > > , < < " no - cache " > > } } , { Headers1 , State1 } = decode ( < < 16#4803333032580770726976617465611d4d6f6e2c203231204f637420323031332032303a31333a323120474d546e1768747470733a2f2f7777772e6578616d706c652e636f6d:560 > > , State0 ) , { Headers1 , State1 } = decode ( < < 16#488264025885aec3771a4b6196d07abe941054d444a8200595040b8166e082a62d1bff6e919d29ad171863c78f0b97c8e9ae82ae43d3:432 > > , State0 ) , { < < " : status " > > , < < " 302 " > > } , { < < " date " > > , < < " Mon , 21 Oct 2013 20:13:21 GMT " > > } , { 65,{<<"date " > > , < < " Mon , 21 Oct 2013 20:13:21 GMT " > > } } , { 52,{<<"cache - control " > > , < < " private " > > } } , { 42,{<<":status " > > , < < " 302 " > > } } ] } = State1 , { Headers2 , State2 } = decode ( < < 16#4803333037c1c0bf:64 > > , State1 ) , { Headers2 , State2 } = decode ( < < 16#4883640effc1c0bf:64 > > , State1 ) , { < < " : status " > > , < < " 307 " > > } , { < < " date " > > , < < " Mon , 21 Oct 2013 20:13:21 GMT " > > } , { 42,{<<":status " > > , < < " 307 " > > } } , { 65,{<<"date " > > , < < " Mon , 21 Oct 2013 20:13:21 GMT " > > } } , { 52,{<<"cache - control " > > , < < " private " > > } } ] } = State2 , { Headers3 , State3 } = decode ( < < 16#88c1611d4d6f6e2c203231204f637420323031332032303a31333a323220474d54c05a04677a69707738666f6f3d4153444a4b48514b425a584f5157454f50495541585157454f49553b206d61782d6167653d333630303b2076657273696f6e3d31:784 > > , State2 ) , { Headers3 , State3 } = decode ( < < 16#88c16196d07abe941054d444a8200595040b8166e084a62d1bffc05a839bd9ab77ad94e7821dd7f2e6c7b335dfdfcd5b3960d5af27087f3672c1ab270fb5291f9587316065c003ed4ee5b1063d5007:632 > > , State2 ) , Headers3 = [ { < < " : status " > > , < < " 200 " > > } , { < < " date " > > , < < " Mon , 21 Oct 2013 20:13:22 GMT " > > } , { < < " set - cookie " > > , < < " foo = ASDJKHQKBZXOQWEOPIUAXQWEOIU ; max - age=3600 ; version=1 " > > } { 98,{<<"set - cookie " > > , < < " foo = ASDJKHQKBZXOQWEOPIUAXQWEOIU ; max - age=3600 ; version=1 " > > } } , { 65,{<<"date " > > , < < " Mon , 21 Oct 2013 20:13:22 GMT " > > } } ] } = State3 , { Headers1 , State1 } = decode ( < < 16#4803333032580770726976617465611d4d6f6e2c203231204f637420323031332032303a31333a323120474d546e1768747470733a2f2f7777772e6578616d706c652e636f6d:560 > > , State0 ) , { Headers1 , State1 } = decode ( < < 16#488264025885aec3771a4b6196d07abe941054d444a8200595040b8166e082a62d1bff6e919d29ad171863c78f0b97c8e9ae82ae43d3:432 > > , State0 ) , { < < " : status " > > , < < " 302 " > > } , { < < " date " > > , < < " Mon , 21 Oct 2013 20:13:21 GMT " > > } , { 65,{<<"date " > > , < < " Mon , 21 Oct 2013 20:13:21 GMT " > > } } , { 52,{<<"cache - control " > > , < < " private " > > } } , { 42,{<<":status " > > , < < " 302 " > > } } ] } = State1 , MaxSize = enc_big_int(512 - 31 , < < > > ) , iolist_to_binary ( [ < < 2#00111111 > > , MaxSize , < < 16#4803333037c1c0bf:64 > > ] ) , iolist_to_binary ( [ < < 2#00111111 > > , MaxSize , < < 16#4883640effc1c0bf:64 > > ] ) , { < < " : status " > > , < < " 307 " > > } , { < < " date " > > , < < " Mon , 21 Oct 2013 20:13:21 GMT " > > } , # state{size=264 , configured_max_size=512 , dyn_table= [ { 42,{<<":status " > > , < < " 307 " > > } } , { 65,{<<"date " > > , < < " Mon , 21 Oct 2013 20:13:21 GMT " > > } } , { 52,{<<"cache - control " > > , < < " private " > > } } , { 42,{<<":status " > > , < < " 302 " > > } } ] } = State3 , { Headers1 , State1 } = decode ( < < 16#4803333032580770726976617465611d4d6f6e2c203231204f637420323031332032303a31333a323120474d546e1768747470733a2f2f7777772e6578616d706c652e636f6d:560 > > , State0 ) , { Headers1 , State1 } = decode ( < < 16#488264025885aec3771a4b6196d07abe941054d444a8200595040b8166e082a62d1bff6e919d29ad171863c78f0b97c8e9ae82ae43d3:432 > > , State0 ) , { < < " : status " > > , < < " 302 " > > } , { < < " date " > > , < < " Mon , 21 Oct 2013 20:13:21 GMT " > > } , { 65,{<<"date " > > , < < " Mon , 21 Oct 2013 20:13:21 GMT " > > } } , { 52,{<<"cache - control " > > , < < " private " > > } } , { 42,{<<":status " > > , < < " 302 " > > } } ] } = State1 , MaxSize = enc_big_int(400 - 31 , < < > > ) , iolist_to_binary ( [ < < 2#00111111 > > , MaxSize , < < 16#4803333037c1c0bf:64 > > ] ) , iolist_to_binary ( [ < < 2#00111111 > > , MaxSize , < < 16#4883640effc1c0bf:64 > > ] ) , { < < " : status " > > , < < " 307 " > > } , { < < " date " > > , < < " Mon , 21 Oct 2013 20:13:21 GMT " > > } , # state{size=264 , configured_max_size=512 , dyn_table= [ { 42,{<<":status " > > , < < " 307 " > > } } , { 65,{<<"date " > > , < < " Mon , 21 Oct 2013 20:13:21 GMT " > > } } , { 52,{<<"cache - control " > > , < < " private " > > } } , { 42,{<<":status " > > , < < " 302 " > > } } ] } = State3 , { Headers1 , State1 } = decode ( < < 16#4803333032580770726976617465611d4d6f6e2c203231204f637420323031332032303a31333a323120474d546e1768747470733a2f2f7777772e6578616d706c652e636f6d:560 > > , State0 ) , { Headers1 , State1 } = decode ( < < 16#488264025885aec3771a4b6196d07abe941054d444a8200595040b8166e082a62d1bff6e919d29ad171863c78f0b97c8e9ae82ae43d3:432 > > , State0 ) , { < < " : status " > > , < < " 302 " > > } , { < < " date " > > , < < " Mon , 21 Oct 2013 20:13:21 GMT " > > } , { 65,{<<"date " > > , < < " Mon , 21 Oct 2013 20:13:21 GMT " > > } } , { 52,{<<"cache - control " > > , < < " private " > > } } , { 42,{<<":status " > > , < < " 302 " > > } } ] } = State1 , MaxSize = enc_big_int(1024 - 31 , < < > > ) , { ' EXIT ' , _ } = ( catch decode ( iolist_to_binary ( [ < < 2#00111111 > > , MaxSize , < < 16#4803333037c1c0bf:64 > > ] ) , { ' EXIT ' , _ } = ( catch decode ( iolist_to_binary ( [ < < 2#00111111 > > , MaxSize , < < 16#4883640effc1c0bf:64 > > ] ) , { Headers1 , State1 } = decode ( < < 16#4803333032580770726976617465611d4d6f6e2c203231204f637420323031332032303a31333a323120474d546e1768747470733a2f2f7777772e6578616d706c652e636f6d:560 > > , State0 ) , { Headers1 , State1 } = decode ( < < 16#488264025885aec3771a4b6196d07abe941054d444a8200595040b8166e082a62d1bff6e919d29ad171863c78f0b97c8e9ae82ae43d3:432 > > , State0 ) , { < < " : status " > > , < < " 302 " > > } , { < < " date " > > , < < " Mon , 21 Oct 2013 20:13:21 GMT " > > } , { 65,{<<"date " > > , < < " Mon , 21 Oct 2013 20:13:21 GMT " > > } } , { 52,{<<"cache - control " > > , < < " private " > > } } , { 42,{<<":status " > > , < < " 302 " > > } } ] } = State1 , MaxSize = enc_big_int(512 - 31 , < < > > ) , < < 2#00100000 , 2#00111111 > > , MaxSize , < < 16#4803333032580770726976617465611d4d6f6e2c203231204f637420323031332032303a31333a323120474d546e1768747470733a2f2f7777772e6578616d706c652e636f6d:560 > > ] ) , < < 2#00100000 , 2#00111111 > > , MaxSize , < < 16#488264025885aec3771a4b6196d07abe941054d444a8200595040b8166e082a62d1bff6e919d29ad171863c78f0b97c8e9ae82ae43d3:432 > > ] ) , # state{size=222 , configured_max_size=512 , dyn_table= [ { 65,{<<"date " > > , < < " Mon , 21 Oct 2013 20:13:21 GMT " > > } } , { 52,{<<"cache - control " > > , < < " private " > > } } , { 42,{<<":status " > > , < < " 302 " > > } } ] } = State3 , horse_decode_huffman ( ) - > { _ , State2 } = > > , State1 ) , -spec encode(cow_http:headers()) -> {iodata(), state()}. encode(Headers) -> encode(Headers, init(), huffman, []). -spec encode(cow_http:headers(), State) -> {iodata(), State} when State::state(). encode(Headers, State=#state{max_size=MaxSize, configured_max_size=MaxSize}) -> encode(Headers, State, huffman, []); encode(Headers, State0=#state{configured_max_size=MaxSize}) -> {Data, State} = encode(Headers, State0#state{max_size=MaxSize}, huffman, []), {[enc_int5(MaxSize, 2#001)|Data], State}. -spec encode(cow_http:headers(), State, opts()) -> {iodata(), State} when State::state(). encode(Headers, State=#state{max_size=MaxSize, configured_max_size=MaxSize}, Opts) -> encode(Headers, State, huffman_opt(Opts), []); encode(Headers, State0=#state{configured_max_size=MaxSize}, Opts) -> {Data, State} = encode(Headers, State0#state{max_size=MaxSize}, huffman_opt(Opts), []), {[enc_int5(MaxSize, 2#001)|Data], State}. huffman_opt(#{huffman := false}) -> no_huffman; huffman_opt(_) -> huffman. encode([], State, _, Acc) -> {lists:reverse(Acc), State}; encode([{Name, Value0}|Tail], State, HuffmanOpt, Acc) -> Value = if is_binary(Value0) -> Value0; true -> iolist_to_binary(Value0) end, Header = {Name, Value}, case table_find(Header, State) of {field, Index} -> encode(Tail, State, HuffmanOpt, [enc_int7(Index, 2#1)|Acc]); {name, Index} -> State2 = table_insert(Header, State), encode(Tail, State2, HuffmanOpt, [[enc_int6(Index, 2#01)|enc_str(Value, HuffmanOpt)]|Acc]); not_found -> State2 = table_insert(Header, State), encode(Tail, State2, HuffmanOpt, [[<< 0:1, 1:1, 0:6 >>|[enc_str(Name, HuffmanOpt)|enc_str(Value, HuffmanOpt)]]|Acc]) end. enc_int5(Int, Prefix) when Int < 31 -> << Prefix:3, Int:5 >>; enc_int5(Int, Prefix) -> enc_big_int(Int - 31, << Prefix:3, 2#11111:5 >>). enc_int6(Int, Prefix) when Int < 63 -> << Prefix:2, Int:6 >>; enc_int6(Int, Prefix) -> enc_big_int(Int - 63, << Prefix:2, 2#111111:6 >>). enc_int7(Int, Prefix) when Int < 127 -> << Prefix:1, Int:7 >>; enc_int7(Int, Prefix) -> enc_big_int(Int - 127, << Prefix:1, 2#1111111:7 >>). enc_big_int(Int, Acc) when Int < 128 -> <<Acc/binary, Int:8>>; enc_big_int(Int, Acc) -> enc_big_int(Int bsr 7, <<Acc/binary, 1:1, Int:7>>). enc_str(Str, huffman) -> Str2 = enc_huffman(Str, <<>>), [enc_int7(byte_size(Str2), 2#1)|Str2]; enc_str(Str, no_huffman) -> [enc_int7(byte_size(Str), 2#0)|Str]. enc_huffman(<<>>, Acc) -> case bit_size(Acc) rem 8 of 1 -> << Acc/bits, 2#1111111:7 >>; 2 -> << Acc/bits, 2#111111:6 >>; 3 -> << Acc/bits, 2#11111:5 >>; 4 -> << Acc/bits, 2#1111:4 >>; 5 -> << Acc/bits, 2#111:3 >>; 6 -> << Acc/bits, 2#11:2 >>; 7 -> << Acc/bits, 2#1:1 >>; 0 -> Acc end; enc_huffman(<< 0, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111000:13 >>); enc_huffman(<< 1, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#11111111111111111011000:23 >>); enc_huffman(<< 2, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111111111111111100010:28 >>); enc_huffman(<< 3, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111111111111111100011:28 >>); enc_huffman(<< 4, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111111111111111100100:28 >>); enc_huffman(<< 5, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111111111111111100101:28 >>); enc_huffman(<< 6, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111111111111111100110:28 >>); enc_huffman(<< 7, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111111111111111100111:28 >>); enc_huffman(<< 8, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111111111111111101000:28 >>); enc_huffman(<< 9, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#111111111111111111101010:24 >>); enc_huffman(<< 10, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#111111111111111111111111111100:30 >>); enc_huffman(<< 11, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111111111111111101001:28 >>); enc_huffman(<< 12, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111111111111111101010:28 >>); enc_huffman(<< 13, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#111111111111111111111111111101:30 >>); enc_huffman(<< 14, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111111111111111101011:28 >>); enc_huffman(<< 15, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111111111111111101100:28 >>); enc_huffman(<< 16, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111111111111111101101:28 >>); enc_huffman(<< 17, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111111111111111101110:28 >>); enc_huffman(<< 18, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111111111111111101111:28 >>); enc_huffman(<< 19, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111111111111111110000:28 >>); enc_huffman(<< 20, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111111111111111110001:28 >>); enc_huffman(<< 21, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111111111111111110010:28 >>); enc_huffman(<< 22, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#111111111111111111111111111110:30 >>); enc_huffman(<< 23, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111111111111111110011:28 >>); enc_huffman(<< 24, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111111111111111110100:28 >>); enc_huffman(<< 25, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111111111111111110101:28 >>); enc_huffman(<< 26, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111111111111111110110:28 >>); enc_huffman(<< 27, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111111111111111110111:28 >>); enc_huffman(<< 28, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111111111111111111000:28 >>); enc_huffman(<< 29, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111111111111111111001:28 >>); enc_huffman(<< 30, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111111111111111111010:28 >>); enc_huffman(<< 31, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111111111111111111011:28 >>); enc_huffman(<< 32, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#010100:6 >>); enc_huffman(<< 33, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111000:10 >>); enc_huffman(<< 34, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111001:10 >>); enc_huffman(<< 35, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#111111111010:12 >>); enc_huffman(<< 36, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111001:13 >>); enc_huffman(<< 37, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#010101:6 >>); enc_huffman(<< 38, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#11111000:8 >>); enc_huffman(<< 39, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#11111111010:11 >>); enc_huffman(<< 40, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111010:10 >>); enc_huffman(<< 41, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111011:10 >>); enc_huffman(<< 42, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#11111001:8 >>); enc_huffman(<< 43, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#11111111011:11 >>); enc_huffman(<< 44, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#11111010:8 >>); enc_huffman(<< 45, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#010110:6 >>); enc_huffman(<< 46, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#010111:6 >>); enc_huffman(<< 47, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#011000:6 >>); enc_huffman(<< 48, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#00000:5 >>); enc_huffman(<< 49, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#00001:5 >>); enc_huffman(<< 50, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#00010:5 >>); enc_huffman(<< 51, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#011001:6 >>); enc_huffman(<< 52, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#011010:6 >>); enc_huffman(<< 53, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#011011:6 >>); enc_huffman(<< 54, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#011100:6 >>); enc_huffman(<< 55, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#011101:6 >>); enc_huffman(<< 56, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#011110:6 >>); enc_huffman(<< 57, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#011111:6 >>); enc_huffman(<< 58, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1011100:7 >>); enc_huffman(<< 59, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#11111011:8 >>); enc_huffman(<< 60, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#111111111111100:15 >>); enc_huffman(<< 61, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#100000:6 >>); enc_huffman(<< 62, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#111111111011:12 >>); enc_huffman(<< 63, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111100:10 >>); enc_huffman(<< 64, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111010:13 >>); enc_huffman(<< 65, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#100001:6 >>); enc_huffman(<< 66, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1011101:7 >>); enc_huffman(<< 67, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1011110:7 >>); enc_huffman(<< 68, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1011111:7 >>); enc_huffman(<< 69, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1100000:7 >>); enc_huffman(<< 70, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1100001:7 >>); enc_huffman(<< 71, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1100010:7 >>); enc_huffman(<< 72, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1100011:7 >>); enc_huffman(<< 73, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1100100:7 >>); enc_huffman(<< 74, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1100101:7 >>); enc_huffman(<< 75, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1100110:7 >>); enc_huffman(<< 76, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1100111:7 >>); enc_huffman(<< 77, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1101000:7 >>); enc_huffman(<< 78, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1101001:7 >>); enc_huffman(<< 79, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1101010:7 >>); enc_huffman(<< 80, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1101011:7 >>); enc_huffman(<< 81, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1101100:7 >>); enc_huffman(<< 82, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1101101:7 >>); enc_huffman(<< 83, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1101110:7 >>); enc_huffman(<< 84, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1101111:7 >>); enc_huffman(<< 85, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1110000:7 >>); enc_huffman(<< 86, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1110001:7 >>); enc_huffman(<< 87, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1110010:7 >>); enc_huffman(<< 88, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#11111100:8 >>); enc_huffman(<< 89, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1110011:7 >>); enc_huffman(<< 90, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#11111101:8 >>); enc_huffman(<< 91, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111011:13 >>); enc_huffman(<< 92, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111111110000:19 >>); enc_huffman(<< 93, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111100:13 >>); enc_huffman(<< 94, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#11111111111100:14 >>); enc_huffman(<< 95, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#100010:6 >>); enc_huffman(<< 96, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#111111111111101:15 >>); enc_huffman(<< 97, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#00011:5 >>); enc_huffman(<< 98, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#100011:6 >>); enc_huffman(<< 99, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#00100:5 >>); enc_huffman(<< 100, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#100100:6 >>); enc_huffman(<< 101, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#00101:5 >>); enc_huffman(<< 102, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#100101:6 >>); enc_huffman(<< 103, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#100110:6 >>); enc_huffman(<< 104, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#100111:6 >>); enc_huffman(<< 105, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#00110:5 >>); enc_huffman(<< 106, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1110100:7 >>); enc_huffman(<< 107, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1110101:7 >>); enc_huffman(<< 108, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#101000:6 >>); enc_huffman(<< 109, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#101001:6 >>); enc_huffman(<< 110, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#101010:6 >>); enc_huffman(<< 111, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#00111:5 >>); enc_huffman(<< 112, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#101011:6 >>); enc_huffman(<< 113, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1110110:7 >>); enc_huffman(<< 114, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#101100:6 >>); enc_huffman(<< 115, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#01000:5 >>); enc_huffman(<< 116, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#01001:5 >>); enc_huffman(<< 117, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#101101:6 >>); enc_huffman(<< 118, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1110111:7 >>); enc_huffman(<< 119, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111000:7 >>); enc_huffman(<< 120, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111001:7 >>); enc_huffman(<< 121, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111010:7 >>); enc_huffman(<< 122, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111011:7 >>); enc_huffman(<< 123, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#111111111111110:15 >>); enc_huffman(<< 124, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#11111111100:11 >>); enc_huffman(<< 125, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#11111111111101:14 >>); enc_huffman(<< 126, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111101:13 >>); enc_huffman(<< 127, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111111111111111111100:28 >>); enc_huffman(<< 128, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#11111111111111100110:20 >>); enc_huffman(<< 129, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111111111010010:22 >>); enc_huffman(<< 130, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#11111111111111100111:20 >>); enc_huffman(<< 131, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#11111111111111101000:20 >>); enc_huffman(<< 132, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111111111010011:22 >>); enc_huffman(<< 133, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111111111010100:22 >>); enc_huffman(<< 134, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111111111010101:22 >>); enc_huffman(<< 135, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#11111111111111111011001:23 >>); enc_huffman(<< 136, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111111111010110:22 >>); enc_huffman(<< 137, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#11111111111111111011010:23 >>); enc_huffman(<< 138, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#11111111111111111011011:23 >>); enc_huffman(<< 139, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#11111111111111111011100:23 >>); enc_huffman(<< 140, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#11111111111111111011101:23 >>); enc_huffman(<< 141, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#11111111111111111011110:23 >>); enc_huffman(<< 142, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#111111111111111111101011:24 >>); enc_huffman(<< 143, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#11111111111111111011111:23 >>); enc_huffman(<< 144, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#111111111111111111101100:24 >>); enc_huffman(<< 145, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#111111111111111111101101:24 >>); enc_huffman(<< 146, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111111111010111:22 >>); enc_huffman(<< 147, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#11111111111111111100000:23 >>); enc_huffman(<< 148, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#111111111111111111101110:24 >>); enc_huffman(<< 149, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#11111111111111111100001:23 >>); enc_huffman(<< 150, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#11111111111111111100010:23 >>); enc_huffman(<< 151, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#11111111111111111100011:23 >>); enc_huffman(<< 152, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#11111111111111111100100:23 >>); enc_huffman(<< 153, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#111111111111111011100:21 >>); enc_huffman(<< 154, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111111111011000:22 >>); enc_huffman(<< 155, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#11111111111111111100101:23 >>); enc_huffman(<< 156, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111111111011001:22 >>); enc_huffman(<< 157, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#11111111111111111100110:23 >>); enc_huffman(<< 158, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#11111111111111111100111:23 >>); enc_huffman(<< 159, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#111111111111111111101111:24 >>); enc_huffman(<< 160, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111111111011010:22 >>); enc_huffman(<< 161, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#111111111111111011101:21 >>); enc_huffman(<< 162, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#11111111111111101001:20 >>); enc_huffman(<< 163, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111111111011011:22 >>); enc_huffman(<< 164, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111111111011100:22 >>); enc_huffman(<< 165, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#11111111111111111101000:23 >>); enc_huffman(<< 166, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#11111111111111111101001:23 >>); enc_huffman(<< 167, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#111111111111111011110:21 >>); enc_huffman(<< 168, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#11111111111111111101010:23 >>); enc_huffman(<< 169, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111111111011101:22 >>); enc_huffman(<< 170, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111111111011110:22 >>); enc_huffman(<< 171, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#111111111111111111110000:24 >>); enc_huffman(<< 172, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#111111111111111011111:21 >>); enc_huffman(<< 173, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111111111011111:22 >>); enc_huffman(<< 174, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#11111111111111111101011:23 >>); enc_huffman(<< 175, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#11111111111111111101100:23 >>); enc_huffman(<< 176, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#111111111111111100000:21 >>); enc_huffman(<< 177, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#111111111111111100001:21 >>); enc_huffman(<< 178, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111111111100000:22 >>); enc_huffman(<< 179, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#111111111111111100010:21 >>); enc_huffman(<< 180, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#11111111111111111101101:23 >>); enc_huffman(<< 181, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111111111100001:22 >>); enc_huffman(<< 182, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#11111111111111111101110:23 >>); enc_huffman(<< 183, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#11111111111111111101111:23 >>); enc_huffman(<< 184, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#11111111111111101010:20 >>); enc_huffman(<< 185, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111111111100010:22 >>); enc_huffman(<< 186, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111111111100011:22 >>); enc_huffman(<< 187, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111111111100100:22 >>); enc_huffman(<< 188, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#11111111111111111110000:23 >>); enc_huffman(<< 189, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111111111100101:22 >>); enc_huffman(<< 190, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111111111100110:22 >>); enc_huffman(<< 191, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#11111111111111111110001:23 >>); enc_huffman(<< 192, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#11111111111111111111100000:26 >>); enc_huffman(<< 193, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#11111111111111111111100001:26 >>); enc_huffman(<< 194, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#11111111111111101011:20 >>); enc_huffman(<< 195, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111111110001:19 >>); enc_huffman(<< 196, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111111111100111:22 >>); enc_huffman(<< 197, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#11111111111111111110010:23 >>); enc_huffman(<< 198, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111111111101000:22 >>); enc_huffman(<< 199, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111111111111101100:25 >>); enc_huffman(<< 200, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#11111111111111111111100010:26 >>); enc_huffman(<< 201, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#11111111111111111111100011:26 >>); enc_huffman(<< 202, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#11111111111111111111100100:26 >>); enc_huffman(<< 203, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#111111111111111111111011110:27 >>); enc_huffman(<< 204, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#111111111111111111111011111:27 >>); enc_huffman(<< 205, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#11111111111111111111100101:26 >>); enc_huffman(<< 206, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#111111111111111111110001:24 >>); enc_huffman(<< 207, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111111111111101101:25 >>); enc_huffman(<< 208, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111111110010:19 >>); enc_huffman(<< 209, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#111111111111111100011:21 >>); enc_huffman(<< 210, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#11111111111111111111100110:26 >>); enc_huffman(<< 211, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#111111111111111111111100000:27 >>); enc_huffman(<< 212, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#111111111111111111111100001:27 >>); enc_huffman(<< 213, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#11111111111111111111100111:26 >>); enc_huffman(<< 214, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#111111111111111111111100010:27 >>); enc_huffman(<< 215, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#111111111111111111110010:24 >>); enc_huffman(<< 216, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#111111111111111100100:21 >>); enc_huffman(<< 217, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#111111111111111100101:21 >>); enc_huffman(<< 218, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#11111111111111111111101000:26 >>); enc_huffman(<< 219, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#11111111111111111111101001:26 >>); enc_huffman(<< 220, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111111111111111111101:28 >>); enc_huffman(<< 221, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#111111111111111111111100011:27 >>); enc_huffman(<< 222, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#111111111111111111111100100:27 >>); enc_huffman(<< 223, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#111111111111111111111100101:27 >>); enc_huffman(<< 224, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#11111111111111101100:20 >>); enc_huffman(<< 225, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#111111111111111111110011:24 >>); enc_huffman(<< 226, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#11111111111111101101:20 >>); enc_huffman(<< 227, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#111111111111111100110:21 >>); enc_huffman(<< 228, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111111111101001:22 >>); enc_huffman(<< 229, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#111111111111111100111:21 >>); enc_huffman(<< 230, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#111111111111111101000:21 >>); enc_huffman(<< 231, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#11111111111111111110011:23 >>); enc_huffman(<< 232, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111111111101010:22 >>); enc_huffman(<< 233, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111111111101011:22 >>); enc_huffman(<< 234, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111111111111101110:25 >>); enc_huffman(<< 235, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111111111111101111:25 >>); enc_huffman(<< 236, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#111111111111111111110100:24 >>); enc_huffman(<< 237, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#111111111111111111110101:24 >>); enc_huffman(<< 238, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#11111111111111111111101010:26 >>); enc_huffman(<< 239, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#11111111111111111110100:23 >>); enc_huffman(<< 240, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#11111111111111111111101011:26 >>); enc_huffman(<< 241, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#111111111111111111111100110:27 >>); enc_huffman(<< 242, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#11111111111111111111101100:26 >>); enc_huffman(<< 243, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#11111111111111111111101101:26 >>); enc_huffman(<< 244, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#111111111111111111111100111:27 >>); enc_huffman(<< 245, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#111111111111111111111101000:27 >>); enc_huffman(<< 246, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#111111111111111111111101001:27 >>); enc_huffman(<< 247, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#111111111111111111111101010:27 >>); enc_huffman(<< 248, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#111111111111111111111101011:27 >>); enc_huffman(<< 249, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#1111111111111111111111111110:28 >>); enc_huffman(<< 250, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#111111111111111111111101100:27 >>); enc_huffman(<< 251, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#111111111111111111111101101:27 >>); enc_huffman(<< 252, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#111111111111111111111101110:27 >>); enc_huffman(<< 253, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#111111111111111111111101111:27 >>); enc_huffman(<< 254, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#111111111111111111111110000:27 >>); enc_huffman(<< 255, R/bits >>, A) -> enc_huffman(R, << A/bits, 2#11111111111111111111101110:26 >>). { Raw1 , State1 } = encode(Headers1 , init ( ) , # { huffman = > false } ) , < < 16#828684be58086e6f2d6361636865:112 > > = iolist_to_binary(Raw2 ) , { 53,{<<"cache - control " > > , < < " no - cache " > > } } , Headers3 = [ { < < " : path " > > , < < " /index.html " > > } , { Raw3 , State3 } = encode(Headers3 , State2 , # { huffman = > false } ) , < < 16#828785bf400a637573746f6d2d6b65790c637573746f6d2d76616c7565:232 > > = iolist_to_binary(Raw3 ) , { Huff3 , State3 } = encode(Headers3 , State2 ) , < < 16#828785bf408825a849e95ba97d7f8925a849e95bb8e8b4bf:192 > > = iolist_to_binary(Huff3 ) , # state{size=164 , dyn_table= [ { 54,{<<"custom - key " > > , < < " custom - value " > > } } , { 53,{<<"cache - control " > > , < < " no - cache " > > } } , { < < " : status " > > , < < " 302 " > > } , { < < " date " > > , < < " Mon , 21 Oct 2013 20:13:21 GMT " > > } , < < 16#4803333032580770726976617465611d4d6f6e2c203231204f637420323031332032303a31333a323120474d546e1768747470733a2f2f7777772e6578616d706c652e636f6d:560 > > = iolist_to_binary(Raw1 ) , < < 16#488264025885aec3771a4b6196d07abe941054d444a8200595040b8166e082a62d1bff6e919d29ad171863c78f0b97c8e9ae82ae43d3:432 > > = iolist_to_binary(Huff1 ) , { 65,{<<"date " > > , < < " Mon , 21 Oct 2013 20:13:21 GMT " > > } } , { 52,{<<"cache - control " > > , < < " private " > > } } , { 42,{<<":status " > > , < < " 302 " > > } } ] } = State1 , { < < " : status " > > , < < " 307 " > > } , { < < " date " > > , < < " Mon , 21 Oct 2013 20:13:21 GMT " > > } , < < 16#4803333037c1c0bf:64 > > = iolist_to_binary(Raw2 ) , { 42,{<<":status " > > , < < " 307 " > > } } , { 65,{<<"date " > > , < < " Mon , 21 Oct 2013 20:13:21 GMT " > > } } , { 52,{<<"cache - control " > > , < < " private " > > } } ] } = State2 , Headers3 = [ { < < " : status " > > , < < " 200 " > > } , { < < " date " > > , < < " Mon , 21 Oct 2013 20:13:22 GMT " > > } , { < < " set - cookie " > > , < < " foo = ASDJKHQKBZXOQWEOPIUAXQWEOIU ; max - age=3600 ; version=1 " > > } { Raw3 , State3 } = encode(Headers3 , State2 , # { huffman = > false } ) , { Huff3 , State3 } = encode(Headers3 , State2 ) , < < 16#88c16196d07abe941054d444a8200595040b8166e084a62d1bffc05a839bd9ab77ad94e7821dd7f2e6c7b335dfdfcd5b3960d5af27087f3672c1ab270fb5291f9587316065c003ed4ee5b1063d5007:632 > > = iolist_to_binary(Huff3 ) , { 98,{<<"set - cookie " > > , < < " foo = ASDJKHQKBZXOQWEOPIUAXQWEOIU ; max - age=3600 ; version=1 " > > } } , { 65,{<<"date " > > , < < " Mon , 21 Oct 2013 20:13:22 GMT " > > } } ] } = State3 , { < < " : status " > > , < < " 302 " > > } , { < < " date " > > , < < " Mon , 21 Oct 2013 20:13:21 GMT " > > } , { Encoded1 , EncState1 } = encode(Headers1 , ) , { Headers1 , DecState1 } = decode(iolist_to_binary(Encoded1 ) , DecState0 ) , { 65,{<<"date " > > , < < " Mon , 21 Oct 2013 20:13:21 GMT " > > } } , { 52,{<<"cache - control " > > , < < " private " > > } } , { 42,{<<":status " > > , < < " 302 " > > } } ] } = DecState1 , { 65,{<<"date " > > , < < " Mon , 21 Oct 2013 20:13:21 GMT " > > } } , { 52,{<<"cache - control " > > , < < " private " > > } } , { 42,{<<":status " > > , < < " 302 " > > } } ] } = EncState1 , DecState2 = set_max_size(512 , DecState1 ) , EncState2 = set_max_size(512 , EncState1 ) , { < < " : status " > > , < < " 307 " > > } , { < < " date " > > , < < " Mon , 21 Oct 2013 20:13:21 GMT " > > } , { Encoded2 , EncState3 } = encode(Headers2 , EncState2 ) , { Headers2 , } = decode(iolist_to_binary(Encoded2 ) , DecState2 ) , # state{size=264 , max_size=512 , dyn_table= [ { 42,{<<":status " > > , < < " 307 " > > } } , { 65,{<<"date " > > , < < " Mon , 21 Oct 2013 20:13:21 GMT " > > } } , { 52,{<<"cache - control " > > , < < " private " > > } } , { 42,{<<":status " > > , < < " 302 " > > } } ] } = DecState3 , # state{size=264 , max_size=512 , dyn_table= [ { 42,{<<":status " > > , < < " 307 " > > } } , { 65,{<<"date " > > , < < " Mon , 21 Oct 2013 20:13:21 GMT " > > } } , { 52,{<<"cache - control " > > , < < " private " > > } } , { 42,{<<":status " > > , < < " 302 " > > } } ] } = EncState3 , { _ , _ } = encode(Headers ) , do_horse_encode_raw ( ) - > { _ , State1 } = encode(Headers1 , init ( ) , # { huffman = > false } ) , Headers3 = [ { < < " : path " > > , < < " /index.html " > > } , { _ , _ } = encode(Headers3 , State2 , # { huffman = > false } ) , Headers3 = [ { < < " : path " > > , < < " /index.html " > > } , { _ , _ } = encode(Headers3 , State2 ) , table_find(Header = {Name, _}, State) -> case table_find_field(Header, State) of not_found -> case table_find_name(Name, State) of NotFound = not_found -> NotFound; Found -> {name, Found} end; Found -> {field, Found} end. table_find_field({<<":authority">>, <<>>}, _) -> 1; table_find_field({<<":method">>, <<"GET">>}, _) -> 2; table_find_field({<<":method">>, <<"POST">>}, _) -> 3; table_find_field({<<":path">>, <<"/">>}, _) -> 4; table_find_field({<<":path">>, <<"/index.html">>}, _) -> 5; table_find_field({<<":scheme">>, <<"http">>}, _) -> 6; table_find_field({<<":scheme">>, <<"https">>}, _) -> 7; table_find_field({<<":status">>, <<"200">>}, _) -> 8; table_find_field({<<":status">>, <<"204">>}, _) -> 9; table_find_field({<<":status">>, <<"206">>}, _) -> 10; table_find_field({<<":status">>, <<"304">>}, _) -> 11; table_find_field({<<":status">>, <<"400">>}, _) -> 12; table_find_field({<<":status">>, <<"404">>}, _) -> 13; table_find_field({<<":status">>, <<"500">>}, _) -> 14; table_find_field({<<"accept-charset">>, <<>>}, _) -> 15; table_find_field({<<"accept-encoding">>, <<"gzip, deflate">>}, _) -> 16; table_find_field({<<"accept-language">>, <<>>}, _) -> 17; table_find_field({<<"accept-ranges">>, <<>>}, _) -> 18; table_find_field({<<"accept">>, <<>>}, _) -> 19; table_find_field({<<"access-control-allow-origin">>, <<>>}, _) -> 20; table_find_field({<<"age">>, <<>>}, _) -> 21; table_find_field({<<"allow">>, <<>>}, _) -> 22; table_find_field({<<"authorization">>, <<>>}, _) -> 23; table_find_field({<<"cache-control">>, <<>>}, _) -> 24; table_find_field({<<"content-disposition">>, <<>>}, _) -> 25; table_find_field({<<"content-encoding">>, <<>>}, _) -> 26; table_find_field({<<"content-language">>, <<>>}, _) -> 27; table_find_field({<<"content-length">>, <<>>}, _) -> 28; table_find_field({<<"content-location">>, <<>>}, _) -> 29; table_find_field({<<"content-range">>, <<>>}, _) -> 30; table_find_field({<<"content-type">>, <<>>}, _) -> 31; table_find_field({<<"cookie">>, <<>>}, _) -> 32; table_find_field({<<"date">>, <<>>}, _) -> 33; table_find_field({<<"etag">>, <<>>}, _) -> 34; table_find_field({<<"expect">>, <<>>}, _) -> 35; table_find_field({<<"expires">>, <<>>}, _) -> 36; table_find_field({<<"from">>, <<>>}, _) -> 37; table_find_field({<<"host">>, <<>>}, _) -> 38; table_find_field({<<"if-match">>, <<>>}, _) -> 39; table_find_field({<<"if-modified-since">>, <<>>}, _) -> 40; table_find_field({<<"if-none-match">>, <<>>}, _) -> 41; table_find_field({<<"if-range">>, <<>>}, _) -> 42; table_find_field({<<"if-unmodified-since">>, <<>>}, _) -> 43; table_find_field({<<"last-modified">>, <<>>}, _) -> 44; table_find_field({<<"link">>, <<>>}, _) -> 45; table_find_field({<<"location">>, <<>>}, _) -> 46; table_find_field({<<"max-forwards">>, <<>>}, _) -> 47; table_find_field({<<"proxy-authenticate">>, <<>>}, _) -> 48; table_find_field({<<"proxy-authorization">>, <<>>}, _) -> 49; table_find_field({<<"range">>, <<>>}, _) -> 50; table_find_field({<<"referer">>, <<>>}, _) -> 51; table_find_field({<<"refresh">>, <<>>}, _) -> 52; table_find_field({<<"retry-after">>, <<>>}, _) -> 53; table_find_field({<<"server">>, <<>>}, _) -> 54; table_find_field({<<"set-cookie">>, <<>>}, _) -> 55; table_find_field({<<"strict-transport-security">>, <<>>}, _) -> 56; table_find_field({<<"transfer-encoding">>, <<>>}, _) -> 57; table_find_field({<<"user-agent">>, <<>>}, _) -> 58; table_find_field({<<"vary">>, <<>>}, _) -> 59; table_find_field({<<"via">>, <<>>}, _) -> 60; table_find_field({<<"www-authenticate">>, <<>>}, _) -> 61; table_find_field(Header, #state{dyn_table=DynamicTable}) -> table_find_field_dyn(Header, DynamicTable, 62). table_find_field_dyn(_, [], _) -> not_found; table_find_field_dyn(Header, [{_, Header}|_], Index) -> Index; table_find_field_dyn(Header, [_|Tail], Index) -> table_find_field_dyn(Header, Tail, Index + 1). table_find_name(<<":authority">>, _) -> 1; table_find_name(<<":method">>, _) -> 2; table_find_name(<<":path">>, _) -> 4; table_find_name(<<":scheme">>, _) -> 6; table_find_name(<<":status">>, _) -> 8; table_find_name(<<"accept-charset">>, _) -> 15; table_find_name(<<"accept-encoding">>, _) -> 16; table_find_name(<<"accept-language">>, _) -> 17; table_find_name(<<"accept-ranges">>, _) -> 18; table_find_name(<<"accept">>, _) -> 19; table_find_name(<<"access-control-allow-origin">>, _) -> 20; table_find_name(<<"age">>, _) -> 21; table_find_name(<<"allow">>, _) -> 22; table_find_name(<<"authorization">>, _) -> 23; table_find_name(<<"cache-control">>, _) -> 24; table_find_name(<<"content-disposition">>, _) -> 25; table_find_name(<<"content-encoding">>, _) -> 26; table_find_name(<<"content-language">>, _) -> 27; table_find_name(<<"content-length">>, _) -> 28; table_find_name(<<"content-location">>, _) -> 29; table_find_name(<<"content-range">>, _) -> 30; table_find_name(<<"content-type">>, _) -> 31; table_find_name(<<"cookie">>, _) -> 32; table_find_name(<<"date">>, _) -> 33; table_find_name(<<"etag">>, _) -> 34; table_find_name(<<"expect">>, _) -> 35; table_find_name(<<"expires">>, _) -> 36; table_find_name(<<"from">>, _) -> 37; table_find_name(<<"host">>, _) -> 38; table_find_name(<<"if-match">>, _) -> 39; table_find_name(<<"if-modified-since">>, _) -> 40; table_find_name(<<"if-none-match">>, _) -> 41; table_find_name(<<"if-range">>, _) -> 42; table_find_name(<<"if-unmodified-since">>, _) -> 43; table_find_name(<<"last-modified">>, _) -> 44; table_find_name(<<"link">>, _) -> 45; table_find_name(<<"location">>, _) -> 46; table_find_name(<<"max-forwards">>, _) -> 47; table_find_name(<<"proxy-authenticate">>, _) -> 48; table_find_name(<<"proxy-authorization">>, _) -> 49; table_find_name(<<"range">>, _) -> 50; table_find_name(<<"referer">>, _) -> 51; table_find_name(<<"refresh">>, _) -> 52; table_find_name(<<"retry-after">>, _) -> 53; table_find_name(<<"server">>, _) -> 54; table_find_name(<<"set-cookie">>, _) -> 55; table_find_name(<<"strict-transport-security">>, _) -> 56; table_find_name(<<"transfer-encoding">>, _) -> 57; table_find_name(<<"user-agent">>, _) -> 58; table_find_name(<<"vary">>, _) -> 59; table_find_name(<<"via">>, _) -> 60; table_find_name(<<"www-authenticate">>, _) -> 61; table_find_name(Name, #state{dyn_table=DynamicTable}) -> table_find_name_dyn(Name, DynamicTable, 62). table_find_name_dyn(_, [], _) -> not_found; table_find_name_dyn(Name, [{Name, _}|_], Index) -> Index; table_find_name_dyn(Name, [_|Tail], Index) -> table_find_name_dyn(Name, Tail, Index + 1). table_get(1, _) -> {<<":authority">>, <<>>}; table_get(2, _) -> {<<":method">>, <<"GET">>}; table_get(3, _) -> {<<":method">>, <<"POST">>}; table_get(4, _) -> {<<":path">>, <<"/">>}; table_get(5, _) -> {<<":path">>, <<"/index.html">>}; table_get(6, _) -> {<<":scheme">>, <<"http">>}; table_get(7, _) -> {<<":scheme">>, <<"https">>}; table_get(8, _) -> {<<":status">>, <<"200">>}; table_get(9, _) -> {<<":status">>, <<"204">>}; table_get(10, _) -> {<<":status">>, <<"206">>}; table_get(11, _) -> {<<":status">>, <<"304">>}; table_get(12, _) -> {<<":status">>, <<"400">>}; table_get(13, _) -> {<<":status">>, <<"404">>}; table_get(14, _) -> {<<":status">>, <<"500">>}; table_get(15, _) -> {<<"accept-charset">>, <<>>}; table_get(16, _) -> {<<"accept-encoding">>, <<"gzip, deflate">>}; table_get(17, _) -> {<<"accept-language">>, <<>>}; table_get(18, _) -> {<<"accept-ranges">>, <<>>}; table_get(19, _) -> {<<"accept">>, <<>>}; table_get(20, _) -> {<<"access-control-allow-origin">>, <<>>}; table_get(21, _) -> {<<"age">>, <<>>}; table_get(22, _) -> {<<"allow">>, <<>>}; table_get(23, _) -> {<<"authorization">>, <<>>}; table_get(24, _) -> {<<"cache-control">>, <<>>}; table_get(25, _) -> {<<"content-disposition">>, <<>>}; table_get(26, _) -> {<<"content-encoding">>, <<>>}; table_get(27, _) -> {<<"content-language">>, <<>>}; table_get(28, _) -> {<<"content-length">>, <<>>}; table_get(29, _) -> {<<"content-location">>, <<>>}; table_get(30, _) -> {<<"content-range">>, <<>>}; table_get(31, _) -> {<<"content-type">>, <<>>}; table_get(32, _) -> {<<"cookie">>, <<>>}; table_get(33, _) -> {<<"date">>, <<>>}; table_get(34, _) -> {<<"etag">>, <<>>}; table_get(35, _) -> {<<"expect">>, <<>>}; table_get(36, _) -> {<<"expires">>, <<>>}; table_get(37, _) -> {<<"from">>, <<>>}; table_get(38, _) -> {<<"host">>, <<>>}; table_get(39, _) -> {<<"if-match">>, <<>>}; table_get(40, _) -> {<<"if-modified-since">>, <<>>}; table_get(41, _) -> {<<"if-none-match">>, <<>>}; table_get(42, _) -> {<<"if-range">>, <<>>}; table_get(43, _) -> {<<"if-unmodified-since">>, <<>>}; table_get(44, _) -> {<<"last-modified">>, <<>>}; table_get(45, _) -> {<<"link">>, <<>>}; table_get(46, _) -> {<<"location">>, <<>>}; table_get(47, _) -> {<<"max-forwards">>, <<>>}; table_get(48, _) -> {<<"proxy-authenticate">>, <<>>}; table_get(49, _) -> {<<"proxy-authorization">>, <<>>}; table_get(50, _) -> {<<"range">>, <<>>}; table_get(51, _) -> {<<"referer">>, <<>>}; table_get(52, _) -> {<<"refresh">>, <<>>}; table_get(53, _) -> {<<"retry-after">>, <<>>}; table_get(54, _) -> {<<"server">>, <<>>}; table_get(55, _) -> {<<"set-cookie">>, <<>>}; table_get(56, _) -> {<<"strict-transport-security">>, <<>>}; table_get(57, _) -> {<<"transfer-encoding">>, <<>>}; table_get(58, _) -> {<<"user-agent">>, <<>>}; table_get(59, _) -> {<<"vary">>, <<>>}; table_get(60, _) -> {<<"via">>, <<>>}; table_get(61, _) -> {<<"www-authenticate">>, <<>>}; table_get(Index, #state{dyn_table=DynamicTable}) -> {_, Header} = lists:nth(Index - 61, DynamicTable), Header. table_get_name(1, _) -> <<":authority">>; table_get_name(2, _) -> <<":method">>; table_get_name(3, _) -> <<":method">>; table_get_name(4, _) -> <<":path">>; table_get_name(5, _) -> <<":path">>; table_get_name(6, _) -> <<":scheme">>; table_get_name(7, _) -> <<":scheme">>; table_get_name(8, _) -> <<":status">>; table_get_name(9, _) -> <<":status">>; table_get_name(10, _) -> <<":status">>; table_get_name(11, _) -> <<":status">>; table_get_name(12, _) -> <<":status">>; table_get_name(13, _) -> <<":status">>; table_get_name(14, _) -> <<":status">>; table_get_name(15, _) -> <<"accept-charset">>; table_get_name(16, _) -> <<"accept-encoding">>; table_get_name(17, _) -> <<"accept-language">>; table_get_name(18, _) -> <<"accept-ranges">>; table_get_name(19, _) -> <<"accept">>; table_get_name(20, _) -> <<"access-control-allow-origin">>; table_get_name(21, _) -> <<"age">>; table_get_name(22, _) -> <<"allow">>; table_get_name(23, _) -> <<"authorization">>; table_get_name(24, _) -> <<"cache-control">>; table_get_name(25, _) -> <<"content-disposition">>; table_get_name(26, _) -> <<"content-encoding">>; table_get_name(27, _) -> <<"content-language">>; table_get_name(28, _) -> <<"content-length">>; table_get_name(29, _) -> <<"content-location">>; table_get_name(30, _) -> <<"content-range">>; table_get_name(31, _) -> <<"content-type">>; table_get_name(32, _) -> <<"cookie">>; table_get_name(33, _) -> <<"date">>; table_get_name(34, _) -> <<"etag">>; table_get_name(35, _) -> <<"expect">>; table_get_name(36, _) -> <<"expires">>; table_get_name(37, _) -> <<"from">>; table_get_name(38, _) -> <<"host">>; table_get_name(39, _) -> <<"if-match">>; table_get_name(40, _) -> <<"if-modified-since">>; table_get_name(41, _) -> <<"if-none-match">>; table_get_name(42, _) -> <<"if-range">>; table_get_name(43, _) -> <<"if-unmodified-since">>; table_get_name(44, _) -> <<"last-modified">>; table_get_name(45, _) -> <<"link">>; table_get_name(46, _) -> <<"location">>; table_get_name(47, _) -> <<"max-forwards">>; table_get_name(48, _) -> <<"proxy-authenticate">>; table_get_name(49, _) -> <<"proxy-authorization">>; table_get_name(50, _) -> <<"range">>; table_get_name(51, _) -> <<"referer">>; table_get_name(52, _) -> <<"refresh">>; table_get_name(53, _) -> <<"retry-after">>; table_get_name(54, _) -> <<"server">>; table_get_name(55, _) -> <<"set-cookie">>; table_get_name(56, _) -> <<"strict-transport-security">>; table_get_name(57, _) -> <<"transfer-encoding">>; table_get_name(58, _) -> <<"user-agent">>; table_get_name(59, _) -> <<"vary">>; table_get_name(60, _) -> <<"via">>; table_get_name(61, _) -> <<"www-authenticate">>; table_get_name(Index, #state{dyn_table=DynamicTable}) -> {_, {Name, _}} = lists:nth(Index - 61, DynamicTable), Name. table_insert(Entry = {Name, Value}, State=#state{size=Size, max_size=MaxSize, dyn_table=DynamicTable}) -> EntrySize = byte_size(Name) + byte_size(Value) + 32, {DynamicTable2, Size2} = if Size + EntrySize > MaxSize -> table_resize(DynamicTable, MaxSize - EntrySize, 0, []); true -> {DynamicTable, Size} end, State#state{size=Size2 + EntrySize, dyn_table=[{EntrySize, Entry}|DynamicTable2]}. table_resize([], _, Size, Acc) -> {lists:reverse(Acc), Size}; table_resize([{EntrySize, _}|_], MaxSize, Size, Acc) when Size + EntrySize > MaxSize -> {lists:reverse(Acc), Size}; table_resize([Entry = {EntrySize, _}|Tail], MaxSize, Size, Acc) -> table_resize(Tail, MaxSize, Size + EntrySize, [Entry|Acc]). table_update_size(0, State) -> State#state{size=0, max_size=0, dyn_table=[]}; table_update_size(MaxSize, State=#state{max_size=CurrentMaxSize}) when CurrentMaxSize =< MaxSize -> State#state{max_size=MaxSize}; table_update_size(MaxSize, State=#state{dyn_table=DynTable}) -> {DynTable2, Size} = table_resize(DynTable, MaxSize, 0, []), State#state{size=Size, max_size=MaxSize, dyn_table=DynTable2}. ? FORALL(Str , binary ( ) , begin { Str , < < > > } = : = dec_str(iolist_to_binary(enc_str(Str , ) ) ) ? FORALL(Str , binary ( ) , begin { Str , < < > > } = : = dec_str(iolist_to_binary(enc_str(Str , ) ) )
7c7836ffcb4d5ca49264297d933afedd0d11bef4f9917a59bb5318954633809b
ku-fpg/kansas-lava
Wakarusa.hs
# LANGUAGE ScopedTypeVariables , RankNTypes , TypeFamilies , FlexibleContexts , ExistentialQuantification # module Wakarusa where import Language.KansasLava import Test import Language.KansasLava.Fabric import Language.KansasLava.Wakarusa import Data.Sized.Ix import Data.Sized.Unsigned import Data.Sized.Matrix tests :: TestSeq -> IO () tests testSeq@(TestSeq test _) = do let driver = return () res = delay 99 :: Seq Int in test "wakarusa/unit/1" 1000 (compileToFabric prog1) (driver >> matchExpected "o0" res) let driver = return () res = delay $ delay 9 :: Seq Int in test "wakarusa/unit/2" 1000 (compileToFabric prog2) (driver >> matchExpected "o0" res) let driver = outStdLogicVector "i0" (toS [100..] :: Seq Int) res = delay $ toS [100..] :: Seq Int in test "wakarusa/unit/3" 1000 (compileToFabric prog3) (driver >> matchExpected "o0" res) let driver = return () res = delay $ delay $ 10 :: Seq Int in test "wakarusa/unit/4" 1000 (compileToFabric prog4) (driver >> matchExpected "o0" res) let driver = return () res = delay $ toS [0..] :: Seq Int in test "wakarusa/unit/5" 1000 (compileToFabric prog5) (driver >> matchExpected "o0" res) let driver = return () res = delay $ delay $ toS (concat [ [n,n,n] | n <- [1..]]) :: Seq Int in test "wakarusa/unit/6" 1000 (compileToFabric prog6) (driver >> matchExpected "o0" res) let driver = outStdLogic "i0" (toS $ map Ack $ cycle [False,False,True]) res = toS $ concat [ [ Just x, Just x, Just x ] | x <- [1..] ] :: Seq (Maybe Int) in test "wakarusa/unit/7" 1000 (compileToFabric prog7) (driver >> matchExpected "o0" res) let driver = outStdLogicVector "i0" (toS [1..] :: Seq Int) res = toS [2,4..] :: Seq Int in test "wakarusa/unit/8" 1000 (compileToFabric prog8) (driver >> matchExpected "o0" res) testStream testSeq "wakarusa/unit/9" $ StreamTest { theStream = run9 , correctnessCondition = \ as bs -> case () of _ | as == bs -> Nothing | otherwise -> return (show (as,bs)) , theStreamTestCount = 100 , theStreamTestCycles = 1000 , theStreamName = "fifo" } let driver = return () res = toS $ cycle [ Just (Just (),Nothing) , Just (Nothing,Just 9) , Just (Nothing,Nothing) ] :: Seq (Enabled (Enabled (),Enabled Int)) in test "wakarusa/unit/14" 1000 (compileToFabric prog14) (driver >> matchExpected "o0" res) return () ------------------------------------------------------------------------ prog1 :: STMT () prog1 = do o0 :: REG Int <- OUTPUT (outStdLogicVector "o0" . delayEnabled) SPARK $ \ loop -> do o0 := 99 GOTO loop ------------------------------------------------------------------------ prog2 :: STMT () prog2 = do o0 :: REG Int <- OUTPUT (outStdLogicVector "o0" . delayEnabled) VAR v0 :: VAR Int <- SIGNAL $ var 9 SPARK $ \ loop -> do loop <- LABEL o0 := v0 GOTO loop ------------------------------------------------------------------------ prog3 :: STMT () prog3 = do o0 :: REG Int <- OUTPUT (outStdLogicVector "o0" . delayEnabled) i0 :: EXPR Int <- INPUT (inStdLogicVector "i0") SPARK $ \ loop -> do o0 := i0 ||| GOTO loop ------------------------------------------------------------------------ prog4 :: STMT () prog4 = do o0 :: REG Int <- OUTPUT (outStdLogicVector "o0" . delayEnabled) VAR v0 :: VAR Int <- SIGNAL $ var 9 SPARK $ \ loop -> do v0 := 10 o0 := v0 GOTO loop ------------------------------------------------------------------------ prog5 :: STMT () prog5 = do o0 :: REG Int <- OUTPUT (outStdLogicVector "o0" . delayEnabled) VAR v0 :: VAR Int <- SIGNAL $ var 0 SPARK $ \ loop -> do (v0 := v0 + 1) ||| (o0 := v0) ||| GOTO loop ------------------------------------------------------------------------ prog6 :: STMT () prog6 = do o0 :: REG Int <- OUTPUT (outStdLogicVector "o0" . delayEnabled . probeS "o0") VAR v0 :: VAR Int <- SIGNAL $ var 0 SPARK $ \ loop -> do v0 := v0 + 1 o0 := v0 GOTO loop ------------------------------------------------------------------------ a small value writer using the protocol . prog7 :: STMT () prog7 = do wAckBox@(WriteAckBox oB iB) :: WriteAckBox Int <- connectWriteAckBox "o0" "i0" VAR v0 :: VAR Int <- SIGNAL $ var 1 SPARK $ \ loop -> do putAckBox wAckBox v0 ||| (v0 := v0 + 1) ||| GOTO loop ------------------------------------------------------------------------ prog8 :: STMT () prog8 = do o0 :: REG Int <- OUTPUT (outStdLogicVector "o0" . enabledVal) i0 :: EXPR Int <- INPUT (inStdLogicVector "i0") VAR v0 :: VAR Int <- SIGNAL $ var 1 SPARK $ \ loop -> do o0 := i0 + v0 ||| (v0 := v0 + 1) ||| GOTO loop ------------------------------------------------------------------------ prog9 :: STMT () prog9 = do rAckBox :: ReadAckBox Int <- connectReadAckBox "iA" "oA" wAckBox :: WriteAckBox Int <- connectWriteAckBox "out" "ack" VAR v0 :: VAR Int <- SIGNAL $ undefinedVar SPARK $ \ loop -> do takeAckBox rAckBox $ \ e -> v0 := e putAckBox wAckBox v0 ||| GOTO loop run9 :: Patch (Seq (Enabled Int)) (Seq (Enabled Int)) (Seq Ack) (Seq Ack) run9 ~(inp,outAck) = runPure $ runFabricWithDriver (compileToFabric prog9) $ do outStdLogicVector "iA" inp inAck <- inStdLogic "oA" outStdLogic "ack" outAck out <- inStdLogicVector "out" return (inAck,out) ------------------------------------------------------------------------ type T14 = (Enabled (),Enabled Int) prog14 :: STMT () prog14 = do o0 :: REG T14 <- OUTPUT (outStdLogicVector "o0") (rst :: REG (),inp_src :: REG Int,res :: EXPR T14) <- mkChannel2 (\ a b -> pack (a,b)) let byte = 0 :: EXPR U8 always $ do o0 := res SPARK $ \ label -> do rst := OP0 (pureS ()) inp_src := 9 GOTO label return () fab14 = compileToFabric prog14 run14 :: Seq (Enabled T14) run14 = runPure $ runFabricWithDriver fab14 $ do inStdLogicVector "o0" ------------------------------------------------------------------------ ------------------------------------------------------------------------ ------------------------------------------------------------------------ ------------------------------------------------------------------------ ------------------------------------------------------------------------
null
https://raw.githubusercontent.com/ku-fpg/kansas-lava/cc0be29bd8392b57060c3c11e7f3b799a6d437e1/tests/Wakarusa.hs
haskell
---------------------------------------------------------------------- ---------------------------------------------------------------------- ---------------------------------------------------------------------- ---------------------------------------------------------------------- ---------------------------------------------------------------------- ---------------------------------------------------------------------- ---------------------------------------------------------------------- ---------------------------------------------------------------------- ---------------------------------------------------------------------- ---------------------------------------------------------------------- ---------------------------------------------------------------------- ---------------------------------------------------------------------- ---------------------------------------------------------------------- ---------------------------------------------------------------------- ----------------------------------------------------------------------
# LANGUAGE ScopedTypeVariables , RankNTypes , TypeFamilies , FlexibleContexts , ExistentialQuantification # module Wakarusa where import Language.KansasLava import Test import Language.KansasLava.Fabric import Language.KansasLava.Wakarusa import Data.Sized.Ix import Data.Sized.Unsigned import Data.Sized.Matrix tests :: TestSeq -> IO () tests testSeq@(TestSeq test _) = do let driver = return () res = delay 99 :: Seq Int in test "wakarusa/unit/1" 1000 (compileToFabric prog1) (driver >> matchExpected "o0" res) let driver = return () res = delay $ delay 9 :: Seq Int in test "wakarusa/unit/2" 1000 (compileToFabric prog2) (driver >> matchExpected "o0" res) let driver = outStdLogicVector "i0" (toS [100..] :: Seq Int) res = delay $ toS [100..] :: Seq Int in test "wakarusa/unit/3" 1000 (compileToFabric prog3) (driver >> matchExpected "o0" res) let driver = return () res = delay $ delay $ 10 :: Seq Int in test "wakarusa/unit/4" 1000 (compileToFabric prog4) (driver >> matchExpected "o0" res) let driver = return () res = delay $ toS [0..] :: Seq Int in test "wakarusa/unit/5" 1000 (compileToFabric prog5) (driver >> matchExpected "o0" res) let driver = return () res = delay $ delay $ toS (concat [ [n,n,n] | n <- [1..]]) :: Seq Int in test "wakarusa/unit/6" 1000 (compileToFabric prog6) (driver >> matchExpected "o0" res) let driver = outStdLogic "i0" (toS $ map Ack $ cycle [False,False,True]) res = toS $ concat [ [ Just x, Just x, Just x ] | x <- [1..] ] :: Seq (Maybe Int) in test "wakarusa/unit/7" 1000 (compileToFabric prog7) (driver >> matchExpected "o0" res) let driver = outStdLogicVector "i0" (toS [1..] :: Seq Int) res = toS [2,4..] :: Seq Int in test "wakarusa/unit/8" 1000 (compileToFabric prog8) (driver >> matchExpected "o0" res) testStream testSeq "wakarusa/unit/9" $ StreamTest { theStream = run9 , correctnessCondition = \ as bs -> case () of _ | as == bs -> Nothing | otherwise -> return (show (as,bs)) , theStreamTestCount = 100 , theStreamTestCycles = 1000 , theStreamName = "fifo" } let driver = return () res = toS $ cycle [ Just (Just (),Nothing) , Just (Nothing,Just 9) , Just (Nothing,Nothing) ] :: Seq (Enabled (Enabled (),Enabled Int)) in test "wakarusa/unit/14" 1000 (compileToFabric prog14) (driver >> matchExpected "o0" res) return () prog1 :: STMT () prog1 = do o0 :: REG Int <- OUTPUT (outStdLogicVector "o0" . delayEnabled) SPARK $ \ loop -> do o0 := 99 GOTO loop prog2 :: STMT () prog2 = do o0 :: REG Int <- OUTPUT (outStdLogicVector "o0" . delayEnabled) VAR v0 :: VAR Int <- SIGNAL $ var 9 SPARK $ \ loop -> do loop <- LABEL o0 := v0 GOTO loop prog3 :: STMT () prog3 = do o0 :: REG Int <- OUTPUT (outStdLogicVector "o0" . delayEnabled) i0 :: EXPR Int <- INPUT (inStdLogicVector "i0") SPARK $ \ loop -> do o0 := i0 ||| GOTO loop prog4 :: STMT () prog4 = do o0 :: REG Int <- OUTPUT (outStdLogicVector "o0" . delayEnabled) VAR v0 :: VAR Int <- SIGNAL $ var 9 SPARK $ \ loop -> do v0 := 10 o0 := v0 GOTO loop prog5 :: STMT () prog5 = do o0 :: REG Int <- OUTPUT (outStdLogicVector "o0" . delayEnabled) VAR v0 :: VAR Int <- SIGNAL $ var 0 SPARK $ \ loop -> do (v0 := v0 + 1) ||| (o0 := v0) ||| GOTO loop prog6 :: STMT () prog6 = do o0 :: REG Int <- OUTPUT (outStdLogicVector "o0" . delayEnabled . probeS "o0") VAR v0 :: VAR Int <- SIGNAL $ var 0 SPARK $ \ loop -> do v0 := v0 + 1 o0 := v0 GOTO loop a small value writer using the protocol . prog7 :: STMT () prog7 = do wAckBox@(WriteAckBox oB iB) :: WriteAckBox Int <- connectWriteAckBox "o0" "i0" VAR v0 :: VAR Int <- SIGNAL $ var 1 SPARK $ \ loop -> do putAckBox wAckBox v0 ||| (v0 := v0 + 1) ||| GOTO loop prog8 :: STMT () prog8 = do o0 :: REG Int <- OUTPUT (outStdLogicVector "o0" . enabledVal) i0 :: EXPR Int <- INPUT (inStdLogicVector "i0") VAR v0 :: VAR Int <- SIGNAL $ var 1 SPARK $ \ loop -> do o0 := i0 + v0 ||| (v0 := v0 + 1) ||| GOTO loop prog9 :: STMT () prog9 = do rAckBox :: ReadAckBox Int <- connectReadAckBox "iA" "oA" wAckBox :: WriteAckBox Int <- connectWriteAckBox "out" "ack" VAR v0 :: VAR Int <- SIGNAL $ undefinedVar SPARK $ \ loop -> do takeAckBox rAckBox $ \ e -> v0 := e putAckBox wAckBox v0 ||| GOTO loop run9 :: Patch (Seq (Enabled Int)) (Seq (Enabled Int)) (Seq Ack) (Seq Ack) run9 ~(inp,outAck) = runPure $ runFabricWithDriver (compileToFabric prog9) $ do outStdLogicVector "iA" inp inAck <- inStdLogic "oA" outStdLogic "ack" outAck out <- inStdLogicVector "out" return (inAck,out) type T14 = (Enabled (),Enabled Int) prog14 :: STMT () prog14 = do o0 :: REG T14 <- OUTPUT (outStdLogicVector "o0") (rst :: REG (),inp_src :: REG Int,res :: EXPR T14) <- mkChannel2 (\ a b -> pack (a,b)) let byte = 0 :: EXPR U8 always $ do o0 := res SPARK $ \ label -> do rst := OP0 (pureS ()) inp_src := 9 GOTO label return () fab14 = compileToFabric prog14 run14 :: Seq (Enabled T14) run14 = runPure $ runFabricWithDriver fab14 $ do inStdLogicVector "o0"
f7799417f15dd41924a8e2cc2381385b212f0dd6124546b110fe60f0af687b0f
NalaGinrut/artanis
upload.scm
#!/usr/bin/env guile !# -*- indent - tabs - mode : nil ; coding : utf-8 -*- ;; Copyright (C) 2013,2014,2015 " Mu Lei " known as " NalaGinrut " < > Artanis is free software : you can redistribute it and/or modify it under the terms of the GNU General Public License and GNU Lesser General Public License published by the Free Software Foundation , either version 3 of the License , or ( at your option ) ;; any later version. Artanis is distributed in the hope that it will be useful , ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU General Public License and GNU Lesser General Public License ;; for more details. You should have received a copy of the GNU General Public License ;; and GNU Lesser General Public License along with this program. ;; If not, see </>. (use-modules (artanis artanis) (artanis config)) ;; the example of multi files upload (init-server) ( conf - set ! ' ( host addr ) " 0.0.0.0 " ) (conf-set! '(server engine) 'guile) (conf-set! '(upload size) 10000000000) (define upload-form '(form (@ (method "POST") (enctype "multipart/form-data") (action "upload")) "File to upload: " (input (@ (type "file") (name "upfile"))) (br) "Notes about the file: " (input (@ (type "text") (name "note"))) (br) (br) (input (@ (type "submit") (value "Press")) "to upload the file!"))) (get "/upload" (lambda () (tpl->response upload-form))) (post "/upload" #:from-post '(store #:path "upload" #:sync #f) (lambda (rc) (case (:from-post rc 'store) ((success) (response-emit "upload succeeded!")) ((none) (response-emit "No uploaded files!")) (else (response-emit "Impossible! please report bug!"))))) (run #:debug #f)
null
https://raw.githubusercontent.com/NalaGinrut/artanis/3412d6eb5b46fde71b0965598ba085bacc2a6c12/examples/upload.scm
scheme
coding : utf-8 -*- Copyright (C) 2013,2014,2015 any later version. but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License and GNU Lesser General Public License for more details. and GNU Lesser General Public License along with this program. If not, see </>. the example of multi files upload
#!/usr/bin/env guile !# " Mu Lei " known as " NalaGinrut " < > Artanis is free software : you can redistribute it and/or modify it under the terms of the GNU General Public License and GNU Lesser General Public License published by the Free Software Foundation , either version 3 of the License , or ( at your option ) Artanis is distributed in the hope that it will be useful , You should have received a copy of the GNU General Public License (use-modules (artanis artanis) (artanis config)) (init-server) ( conf - set ! ' ( host addr ) " 0.0.0.0 " ) (conf-set! '(server engine) 'guile) (conf-set! '(upload size) 10000000000) (define upload-form '(form (@ (method "POST") (enctype "multipart/form-data") (action "upload")) "File to upload: " (input (@ (type "file") (name "upfile"))) (br) "Notes about the file: " (input (@ (type "text") (name "note"))) (br) (br) (input (@ (type "submit") (value "Press")) "to upload the file!"))) (get "/upload" (lambda () (tpl->response upload-form))) (post "/upload" #:from-post '(store #:path "upload" #:sync #f) (lambda (rc) (case (:from-post rc 'store) ((success) (response-emit "upload succeeded!")) ((none) (response-emit "No uploaded files!")) (else (response-emit "Impossible! please report bug!"))))) (run #:debug #f)
03e5ac4a90746fb83965bd819dc5d535e83c00e73d022e7e0591388c1052e891
zudov/haskell-comark
EmphLink.hs
{-# LANGUAGE OverloadedStrings #-} # LANGUAGE RecordWildCards # {-# LANGUAGE ViewPatterns #-} -- | Code and data types for parsing emphasis and links module Comark.Parser.Inline.EmphLink where import Data.Text (Text) import qualified Data.Text as Text import Comark.Parser.Reference import Comark.Syntax import Data.Sequence (Seq, ViewR(..), singleton, viewr, (<|), (><), (|>)) type DelimStack = Seq Token data EmphDelim = EmphDelim { emphIndicator :: EmphIndicator , emphLength :: Int , emphCanOpen :: Bool , emphCanClose :: Bool } deriving (Show, Eq) unEmphDelim :: EmphDelim -> Inlines Text unEmphDelim EmphDelim{..} = singleton . Str . Text.replicate emphLength . Text.singleton . indicatorChar $ emphIndicator data LinkOpen = LinkOpen { linkOpenerType :: OpenerType , linkActive :: Bool , linkLabel :: Maybe LinkText , linkContent :: Inlines Text } deriving (Show, Eq) unLinkOpen :: LinkOpen -> Inlines Text unLinkOpen l = case linkOpenerType l of LinkOpener -> Str "[" ImageOpener -> Str "![" <| linkContent l data Token = InlineToken (Inlines Text) | EmphDelimToken EmphDelim | LinkOpenToken LinkOpen deriving (Show, Eq) unToken :: Token -> Inlines Text unToken (InlineToken is) = is unToken (EmphDelimToken e) = unEmphDelim e unToken (LinkOpenToken l) = unLinkOpen l isLinkOpener :: Token -> Bool isLinkOpener LinkOpenToken{} = True isLinkOpener _ = False isEmphDelim :: Token -> Bool isEmphDelim EmphDelimToken{} = True isEmphDelim _ = False data EmphIndicator = AsteriskIndicator | UnderscoreIndicator deriving (Show, Eq) isAsterisk :: EmphIndicator -> Bool isAsterisk AsteriskIndicator = True isAsterisk UnderscoreIndicator = False indicatorChar :: EmphIndicator -> Char indicatorChar AsteriskIndicator = '*' indicatorChar UnderscoreIndicator = '_' data OpenerType = LinkOpener | ImageOpener deriving (Show, Eq) deactivate :: Token -> Token deactivate (LinkOpenToken l) = LinkOpenToken l { linkActive = linkOpenerType l == ImageOpener } deactivate t = t addInline :: DelimStack -> Inline Text -> DelimStack addInline (viewr -> ts :> LinkOpenToken l) i = ts |> LinkOpenToken l { linkContent = linkContent l |> i } addInline (viewr -> ts :> InlineToken is) i = ts |> InlineToken (is |> i) addInline ts i = ts |> InlineToken (singleton i) addInlines :: DelimStack -> Inlines Text -> DelimStack addInlines (viewr -> ts :> InlineToken is) i = ts |> InlineToken (is >< i) addInlines (viewr -> ts :> LinkOpenToken l) i = ts |> LinkOpenToken l { linkContent = linkContent l >< i } addInlines ts i = ts |> InlineToken i
null
https://raw.githubusercontent.com/zudov/haskell-comark/b84cf1d5623008673402da3a5353bdc5891d3a75/comark-parser/src/Comark/Parser/Inline/EmphLink.hs
haskell
# LANGUAGE OverloadedStrings # # LANGUAGE ViewPatterns # | Code and data types for parsing emphasis and links
# LANGUAGE RecordWildCards # module Comark.Parser.Inline.EmphLink where import Data.Text (Text) import qualified Data.Text as Text import Comark.Parser.Reference import Comark.Syntax import Data.Sequence (Seq, ViewR(..), singleton, viewr, (<|), (><), (|>)) type DelimStack = Seq Token data EmphDelim = EmphDelim { emphIndicator :: EmphIndicator , emphLength :: Int , emphCanOpen :: Bool , emphCanClose :: Bool } deriving (Show, Eq) unEmphDelim :: EmphDelim -> Inlines Text unEmphDelim EmphDelim{..} = singleton . Str . Text.replicate emphLength . Text.singleton . indicatorChar $ emphIndicator data LinkOpen = LinkOpen { linkOpenerType :: OpenerType , linkActive :: Bool , linkLabel :: Maybe LinkText , linkContent :: Inlines Text } deriving (Show, Eq) unLinkOpen :: LinkOpen -> Inlines Text unLinkOpen l = case linkOpenerType l of LinkOpener -> Str "[" ImageOpener -> Str "![" <| linkContent l data Token = InlineToken (Inlines Text) | EmphDelimToken EmphDelim | LinkOpenToken LinkOpen deriving (Show, Eq) unToken :: Token -> Inlines Text unToken (InlineToken is) = is unToken (EmphDelimToken e) = unEmphDelim e unToken (LinkOpenToken l) = unLinkOpen l isLinkOpener :: Token -> Bool isLinkOpener LinkOpenToken{} = True isLinkOpener _ = False isEmphDelim :: Token -> Bool isEmphDelim EmphDelimToken{} = True isEmphDelim _ = False data EmphIndicator = AsteriskIndicator | UnderscoreIndicator deriving (Show, Eq) isAsterisk :: EmphIndicator -> Bool isAsterisk AsteriskIndicator = True isAsterisk UnderscoreIndicator = False indicatorChar :: EmphIndicator -> Char indicatorChar AsteriskIndicator = '*' indicatorChar UnderscoreIndicator = '_' data OpenerType = LinkOpener | ImageOpener deriving (Show, Eq) deactivate :: Token -> Token deactivate (LinkOpenToken l) = LinkOpenToken l { linkActive = linkOpenerType l == ImageOpener } deactivate t = t addInline :: DelimStack -> Inline Text -> DelimStack addInline (viewr -> ts :> LinkOpenToken l) i = ts |> LinkOpenToken l { linkContent = linkContent l |> i } addInline (viewr -> ts :> InlineToken is) i = ts |> InlineToken (is |> i) addInline ts i = ts |> InlineToken (singleton i) addInlines :: DelimStack -> Inlines Text -> DelimStack addInlines (viewr -> ts :> InlineToken is) i = ts |> InlineToken (is >< i) addInlines (viewr -> ts :> LinkOpenToken l) i = ts |> LinkOpenToken l { linkContent = linkContent l >< i } addInlines ts i = ts |> InlineToken i
3fb8f70683936f03f84dc77e9ea6dfc291d631bdd30a02e2888f4d8203278fce
NB-Iot/emqx-hw-coap
emqx_hw_coap_mqtt_adapter.erl
%%-------------------------------------------------------------------- Copyright ( c ) 2013 - 2017 EMQ Enterprise , Inc. ( ) %% 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(emqx_hw_coap_mqtt_adapter). -behaviour(gen_server). -include("emqx_hw_coap.hrl"). -include_lib("emqx/include/emqx.hrl"). -include_lib("emqx/include/emqx_mqtt.hrl"). %% API. -export([subscribe/2, unsubscribe/2, publish/3, keepalive/1]). -export([client_pid/4, stop/1]). %% gen_server. -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). -record(state, {proto, peer, keepalive, sub_topics = [], enable_stats}). -define(DEFAULT_KEEP_ALIVE_DURATION, 60*2). -define(HUAWEI_NB_OBSERVE_TOPIC, <<"t/d">>). -define(NB_CLIENT_ID_PREFIX, <<"nbiot">>). -define(LOG(Level, Format, Args), lager:Level("CoAP-MQTT: " ++ Format, Args)). -ifdef(TEST). -define(PROTO_INIT(A, B, C, D, E), test_mqtt_broker:start(A, B, C, D, E)). -define(PROTO_SUBSCRIBE(X, Y), test_mqtt_broker:subscribe(X)). -define(PROTO_UNSUBSCRIBE(X, Y), test_mqtt_broker:unsubscribe(X)). -define(PROTO_PUBLISH(A1, A2, P), test_mqtt_broker:publish(A1, A2)). -define(PROTO_DELIVER_ACK(A1, A2), A2). -define(PROTO_SHUTDOWN(A, B), ok). -define(PROTO_SEND(A, B), {ok, B}). -define(PROTO_GET_CLIENT_ID(A), test_mqtt_broker:clientid(A)). -define(PROTO_STATS(A), test_mqtt_broker:stats(A)). -define(SET_CLIENT_STATS(A,B), test_mqtt_broker:set_client_stats(A,B)). -else. -define(PROTO_INIT(A, B, C, D, E), proto_init(A, B, C, D, E)). -define(PROTO_SUBSCRIBE(X, Y), proto_subscribe(X, Y)). -define(PROTO_UNSUBSCRIBE(X, Y), proto_unsubscribe(X, Y)). -define(PROTO_PUBLISH(A1, A2, P), proto_publish(A1, A2, P)). -define(PROTO_DELIVER_ACK(Msg, State), proto_deliver_ack(Msg, State)). -define(PROTO_SHUTDOWN(A, B), emqx_protocol:shutdown(A, B)). -define(PROTO_SEND(A, B), emqx_protocol:send(A, B)). -define(PROTO_GET_CLIENT_ID(A), emqx_protocol:clientid(A)). -define(PROTO_STATS(A), emqx_protocol:stats(A)). -define(SET_CLIENT_STATS(A,B), emqx_stats:set_client_stats(A,B)). -endif. -define(SOCK_STATS, [recv_oct, recv_cnt, send_oct, send_cnt, send_pend]). %%-------------------------------------------------------------------- %% API %%-------------------------------------------------------------------- client_pid(undefined, _Username, _Password, _Channel) -> {error, bad_request}; client_pid(ClientId, Username, Password, Channel) -> % check authority case start(ClientId, Username, Password, Channel) of {ok, Pid1} -> {ok, Pid1}; {error, {already_started, Pid2}} -> {ok, Pid2}; {error, auth_failure} -> {error, auth_failure}; Other -> {error, Other} end. start(ClientId, Username, Password, Channel) -> DO NOT use start_link , since multiple coap_reponsder may have relation with one mqtt adapter , one coap_responder crashes should not make mqtt adapter crash too % And coap_responder is not a system process, it is dangerous to link mqtt adapter to coap_responder gen_server:start({via, emq_hw_coap_registry, {ClientId, Username, Password}}, ?MODULE, {ClientId, Username, Password, Channel}, []). stop(Pid) -> gen_server:stop(Pid). subscribe(Pid, Topic) -> gen_server:call(Pid, {subscribe, Topic, self()}). unsubscribe(Pid, Topic) -> gen_server:call(Pid, {unsubscribe, Topic, self()}). publish(Pid, Topic, Payload) -> gen_server:call(Pid, {publish, Topic, Payload}). keepalive(Pid)-> gen_server:cast(Pid, keepalive). %%-------------------------------------------------------------------- %% gen_server Callbacks %%-------------------------------------------------------------------- init({ClientId, Username, Password, Channel}) -> ?LOG(debug, "try to start adapter ClientId=~p, Username=~p, Password=~p, Channel=~p", [ClientId, Username, Password, Channel]), EnableStats = application:get_env(?APP, enable_stats, false), case ?PROTO_INIT(ClientId, Username, Password, Channel, EnableStats) of {ok, Proto} -> {ok, #state{proto = Proto, peer = Channel, enable_stats = EnableStats}}; {stop, auth_failure} -> {stop, auth_failure}; Other -> {stop, Other} end. handle_call({subscribe, Topic, CoapPid}, _From, State=#state{proto = Proto, sub_topics = TopicList}) -> NewTopics = proplists:delete(Topic, TopicList), IsWild = emqx_topic:wildcard(Topic), NewProto = ?PROTO_SUBSCRIBE(Topic, Proto), {reply, ok, State#state{proto = NewProto, sub_topics = [{Topic, {IsWild, CoapPid}}|NewTopics]}, hibernate}; handle_call({unsubscribe, Topic, _CoapPid}, _From, State=#state{proto = Proto, sub_topics = TopicList}) -> NewTopics = proplists:delete(Topic, TopicList), NewProto = ?PROTO_UNSUBSCRIBE(Topic, Proto), {reply, ok, State#state{proto = NewProto, sub_topics = NewTopics}, hibernate}; handle_call({publish, Topic, Payload}, _From, State=#state{proto = Proto}) -> NewProto = ?PROTO_PUBLISH(Topic, Payload, Proto), {reply, ok, State#state{proto = NewProto}}; handle_call(info, From, State = #state{proto = ProtoState, peer = Channel}) -> ProtoInfo = emqx_protocol:info(ProtoState), ClientInfo = [{peername, Channel}], {reply, Stats, _, _} = handle_call(stats, From, State), {reply, lists:append([ClientInfo, ProtoInfo, Stats]), State}; handle_call(stats, _From, State = #state{proto = ProtoState}) -> {reply, lists:append([emqx_misc:proc_stats(), ?PROTO_STATS(ProtoState), socket_stats(undefined, ?SOCK_STATS)]), State, hibernate}; handle_call(kick, _From, State) -> {stop, {shutdown, kick}, ok, State}; handle_call({set_rate_limit, _Rl}, _From, State) -> ?LOG(error, "set_rate_limit is not support", []), {reply, ok, State}; handle_call(get_rate_limit, _From, State) -> ?LOG(error, "get_rate_limit is not support", []), {reply, ok, State}; handle_call(session, _From, State = #state{proto = ProtoState}) -> {reply, emqx_protocol:session(ProtoState), State}; handle_call(Request, _From, State) -> ?LOG(error, "adapter unexpected call ~p", [Request]), {reply, ignored, State, hibernate}. handle_cast(keepalive, State=#state{keepalive = undefined}) -> {noreply, State, hibernate}; handle_cast(keepalive, State=#state{keepalive = Keepalive}) -> emit_stats(State), NewKeepalive = emqx_hw_coap_timer:kick_timer(Keepalive), {noreply, State#state{keepalive = NewKeepalive}, hibernate}; handle_cast(Msg, State) -> ?LOG(error, "broker_api unexpected cast ~p", [Msg]), {noreply, State, hibernate}. handle_info({deliver, Msg = #mqtt_message{topic = TopicName, payload = Payload}}, State = #state{proto = Proto, sub_topics = Subscribers}) -> %% handle PUBLISH from broker ?LOG(debug, "deliver message from broker Topic=~p, Payload=~p, Subscribers=~p", [TopicName, Payload, Subscribers]), NewProto = ?PROTO_DELIVER_ACK(Msg, Proto), deliver_to_coap(TopicName, Payload, Subscribers), {ok, NewerProto} = ?PROTO_SEND(Msg, NewProto), {noreply, State#state{proto = NewerProto}}; handle_info({observe_nb_device, CoapRespPid}, State = #state{proto = ProtoState}) -> send OBSERVE to NB device ClientId = ?PROTO_GET_CLIENT_ID(ProtoState), ?LOG(debug, "send observe message to client id=~p, topic=~p~n", [ClientId, ?HUAWEI_NB_OBSERVE_TOPIC]), deliver_observe_to_coap(?HUAWEI_NB_OBSERVE_TOPIC, CoapRespPid, ClientId), {noreply, State}; handle_info({suback, _MsgId, [_GrantedQos]}, State) -> {noreply, State, hibernate}; handle_info({subscribe,_}, State) -> {noreply, State}; handle_info({keepalive, start, Interval}, StateData) -> ?LOG(debug, "Keepalive at the interval of ~p", [Interval]), KeepAlive = emqx_hw_coap_timer:start_timer(Interval, {keepalive, check}), {noreply, StateData#state{keepalive = KeepAlive}, hibernate}; handle_info({keepalive, check}, StateData = #state{keepalive = KeepAlive}) -> case emqx_hw_coap_timer:is_timeout(KeepAlive) of false -> ?LOG(debug, "Keepalive checked ok", []); %NewKeepAlive = emq_hw_coap_timer:restart_timer(KeepAlive), { noreply , StateData#state{keepalive = NewKeepAlive } } ; true -> ?LOG(debug, "Keepalive timeout, still keep alive", []) %{stop, normal, StateData} end, NewKeepAlive = emqx_coap_timer:restart_timer(KeepAlive), {noreply, StateData#state{keepalive = NewKeepAlive}}; handle_info(emit_stats, State) -> {noreply, emit_stats(State), hibernate}; handle_info(timeout, State) -> {stop, {shutdown, idle_timeout}, State}; handle_info({shutdown, Error}, State) -> {stop, {shutdown, Error}, State}; handle_info({shutdown, conflict, {ClientId, NewPid}}, State) -> ?LOG(warning, "clientid '~s' conflict with ~p", [ClientId, NewPid]), {stop, {shutdown, conflict}, State}; handle_info(Info, State) -> ?LOG(error, "adapter unexpected info ~p", [Info]), {noreply, State, hibernate}. terminate(Reason, #state{proto = Proto, keepalive = KeepAlive}) -> emqx_hw_coap_timer:cancel_timer(KeepAlive), case {Proto, Reason} of {undefined, _} -> ok; {_, {shutdown, Error}} -> ?PROTO_SHUTDOWN(Error, Proto); {_, Reason} -> ?PROTO_SHUTDOWN(Reason, Proto) end. code_change(_OldVsn, State, _Extra) -> {ok, State}. %%-------------------------------------------------------------------- %% Internal Functions %%-------------------------------------------------------------------- proto_init(ClientId, Username, Password, Channel, EnableStats) -> SendFun = fun(_Packet) -> ok end, PktOpts = [{max_clientid_len, 96}, {max_packet_size, 512}, {client_enable_stats, EnableStats}], Proto = emqx_protocol:init(Channel, SendFun, PktOpts), ConnPkt = #mqtt_packet_connect{client_id = ClientId, username = Username, password = Password, clean_sess = true, keep_alive = application:get_env(?APP, keepalive, ?DEFAULT_KEEP_ALIVE_DURATION)}, case emqx_protocol:received(?CONNECT_PACKET(ConnPkt), Proto) of {ok, Proto1} -> {ok, Proto1}; {stop, {shutdown, auth_failure}, _Proto2} -> {stop, auth_failure}; Other -> error(Other) end. proto_subscribe(Topic, Proto) -> ?LOG(debug, "subscribe Topic=~p", [Topic]), case emqx_protocol:received(?SUBSCRIBE_PACKET(1, [{Topic, ?QOS1}]), Proto) of {ok, Proto1} -> Proto1; Other -> error(Other) end. proto_unsubscribe(Topic, Proto) -> ?LOG(debug, "unsubscribe Topic=~p", [Topic]), case emqx_protocol:received(?UNSUBSCRIBE_PACKET(1, [Topic]), Proto) of {ok, Proto1} -> Proto1; Other -> error(Other) end. proto_publish(Topic, Payload, Proto) -> ?LOG(debug, "publish Topic=~p, Payload=~p", [Topic, Payload]), Publish = #mqtt_packet{header = #mqtt_packet_header{type = ?PUBLISH, qos = ?QOS0}, variable = #mqtt_packet_publish{topic_name = Topic, packet_id = 1}, payload = Payload}, case emqx_protocol:received(Publish, Proto) of {ok, Proto1} -> Proto1; Other -> error(Other) end. proto_deliver_ack(#mqtt_message{qos = ?QOS0, pktid = _PacketId}, Proto) -> Proto; proto_deliver_ack(#mqtt_message{qos = ?QOS1, pktid = PacketId}, Proto) -> case emqx_protocol:received(?PUBACK_PACKET(?PUBACK, PacketId), Proto) of {ok, NewProto} -> NewProto; Other -> error(Other) end; proto_deliver_ack(#mqtt_message{qos = ?QOS2, pktid = PacketId}, Proto) -> case emqx_protocol:received(?PUBACK_PACKET(?PUBREC, PacketId), Proto) of {ok, NewProto} -> case emqx_protocol:received(?PUBACK_PACKET(?PUBCOMP, PacketId), NewProto) of {ok, CurrentProto} -> CurrentProto; Another -> error(Another) end; Other -> error(Other) end. deliver_to_coap(_TopicName, _Payload, []) -> ok; deliver_to_coap(TopicName, Payload, [{TopicFilter, {IsWild, CoapPid}}|T]) -> Matched = case IsWild of true -> emqx_topic:match(TopicName, TopicFilter); false -> TopicName =:= TopicFilter end, ?LOG(debug, "deliver_to_coap Matched=~p, CoapPid=~p, TopicName=~p, Payload=~p, T=~p", [Matched, CoapPid, TopicName, Payload, T]), case Matched of true -> case binary:match(TopicName, ?NB_CLIENT_ID_PREFIX) of nomatch -> (CoapPid ! {dispatch, TopicName, Payload}); {_Pos, _Len} -> UriPathList = binary:split(?HUAWEI_NB_OBSERVE_TOPIC, <<$/>>, [global]), Here we notice that in every dl msg that sent by Huawei CDP server includes the observe=0 option , it is obviously unnecessary , and we doubt why Huawei CDP acts this way . So we remove the observe option here , and the Huawei NB - Iot device can receive the dl message correctly as well , that means we can use AT+NMGR to receive correct payload . %% If we encounter dl msg receiving failure in the future, maybe we could check this point here. %% Msg = lwm2m_coap_message:request(con, post, Payload, [{uri_path, UriPathList}, {observe, 0}]), Msg = lwm2m_coap_message:request(con, post, Payload, [{uri_path, UriPathList}]), ?LOG(debug, "deliver_to_coap will send request=~p to CoapRespPid=~p~n", [Msg, CoapPid]), CoapPid ! {dispatch_request, Msg, undefined} end; false -> ok end, deliver_to_coap(TopicName, Payload, T). deliver_observe_to_coap(Observe_uri, CoapRespPid, Clientid) -> case is_process_alive(CoapRespPid) of true -> ?LOG(debug, "deliver_observe_to_coap will send to responder Pid=~p~n", [CoapRespPid]), UriPathList = binary:split(Observe_uri, <<$/>>, [global]), Msg = lwm2m_coap_message:request(con, get, <<>>, [{uri_path, UriPathList}, {observe, 0}]), CoapRespPid ! {dispatch_request, Msg, Clientid}; false -> ?LOG(debug, "CoapRespPid =~p is not a PID, skip observe", [CoapRespPid]) end. %% here we keep the original socket_stats implementation, which will be put into use when we can get socket fd in emq_coap_mqtt_adapter process %socket_stats(Sock, Stats) when is_port(Sock), is_list(Stats)-> %inet:getstat(Sock, Stats). %%this socket_stats is a fake funtion socket_stats(undefined, Stats) when is_list(Stats)-> FakeSockOpt = [0, 0, 0, 0, 0], List = lists:zip(Stats, FakeSockOpt), ?LOG(debug, "The List=~p", [List]), List. emit_stats(StateData=#state{proto=ProtoState}) -> emit_stats(?PROTO_GET_CLIENT_ID(ProtoState), StateData). emit_stats(_ClientId, State = #state{enable_stats = false}) -> ? , " The enable_stats is false , skip emit_state ~ n " , [ ] ) , State; emit_stats(ClientId, State) -> {reply, Stats, _, _} = handle_call(stats, undefined, State), ?SET_CLIENT_STATS(ClientId, Stats), State.
null
https://raw.githubusercontent.com/NB-Iot/emqx-hw-coap/76436492a22eaa0cd6560b4f135275ecf16245d0/src/emqx_hw_coap_mqtt_adapter.erl
erlang
-------------------------------------------------------------------- you may not use this file except in compliance with the License. You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, software WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -------------------------------------------------------------------- API. gen_server. -------------------------------------------------------------------- API -------------------------------------------------------------------- check authority And coap_responder is not a system process, it is dangerous to link mqtt adapter to coap_responder -------------------------------------------------------------------- gen_server Callbacks -------------------------------------------------------------------- handle PUBLISH from broker NewKeepAlive = emq_hw_coap_timer:restart_timer(KeepAlive), {stop, normal, StateData} -------------------------------------------------------------------- Internal Functions -------------------------------------------------------------------- If we encounter dl msg receiving failure in the future, maybe we could check this point here. Msg = lwm2m_coap_message:request(con, post, Payload, [{uri_path, UriPathList}, {observe, 0}]), here we keep the original socket_stats implementation, which will be put into use when we can get socket fd in emq_coap_mqtt_adapter process socket_stats(Sock, Stats) when is_port(Sock), is_list(Stats)-> inet:getstat(Sock, Stats). this socket_stats is a fake funtion
Copyright ( c ) 2013 - 2017 EMQ Enterprise , Inc. ( ) Licensed under the Apache License , Version 2.0 ( the " License " ) ; distributed under the License is distributed on an " AS IS " BASIS , -module(emqx_hw_coap_mqtt_adapter). -behaviour(gen_server). -include("emqx_hw_coap.hrl"). -include_lib("emqx/include/emqx.hrl"). -include_lib("emqx/include/emqx_mqtt.hrl"). -export([subscribe/2, unsubscribe/2, publish/3, keepalive/1]). -export([client_pid/4, stop/1]). -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). -record(state, {proto, peer, keepalive, sub_topics = [], enable_stats}). -define(DEFAULT_KEEP_ALIVE_DURATION, 60*2). -define(HUAWEI_NB_OBSERVE_TOPIC, <<"t/d">>). -define(NB_CLIENT_ID_PREFIX, <<"nbiot">>). -define(LOG(Level, Format, Args), lager:Level("CoAP-MQTT: " ++ Format, Args)). -ifdef(TEST). -define(PROTO_INIT(A, B, C, D, E), test_mqtt_broker:start(A, B, C, D, E)). -define(PROTO_SUBSCRIBE(X, Y), test_mqtt_broker:subscribe(X)). -define(PROTO_UNSUBSCRIBE(X, Y), test_mqtt_broker:unsubscribe(X)). -define(PROTO_PUBLISH(A1, A2, P), test_mqtt_broker:publish(A1, A2)). -define(PROTO_DELIVER_ACK(A1, A2), A2). -define(PROTO_SHUTDOWN(A, B), ok). -define(PROTO_SEND(A, B), {ok, B}). -define(PROTO_GET_CLIENT_ID(A), test_mqtt_broker:clientid(A)). -define(PROTO_STATS(A), test_mqtt_broker:stats(A)). -define(SET_CLIENT_STATS(A,B), test_mqtt_broker:set_client_stats(A,B)). -else. -define(PROTO_INIT(A, B, C, D, E), proto_init(A, B, C, D, E)). -define(PROTO_SUBSCRIBE(X, Y), proto_subscribe(X, Y)). -define(PROTO_UNSUBSCRIBE(X, Y), proto_unsubscribe(X, Y)). -define(PROTO_PUBLISH(A1, A2, P), proto_publish(A1, A2, P)). -define(PROTO_DELIVER_ACK(Msg, State), proto_deliver_ack(Msg, State)). -define(PROTO_SHUTDOWN(A, B), emqx_protocol:shutdown(A, B)). -define(PROTO_SEND(A, B), emqx_protocol:send(A, B)). -define(PROTO_GET_CLIENT_ID(A), emqx_protocol:clientid(A)). -define(PROTO_STATS(A), emqx_protocol:stats(A)). -define(SET_CLIENT_STATS(A,B), emqx_stats:set_client_stats(A,B)). -endif. -define(SOCK_STATS, [recv_oct, recv_cnt, send_oct, send_cnt, send_pend]). client_pid(undefined, _Username, _Password, _Channel) -> {error, bad_request}; client_pid(ClientId, Username, Password, Channel) -> case start(ClientId, Username, Password, Channel) of {ok, Pid1} -> {ok, Pid1}; {error, {already_started, Pid2}} -> {ok, Pid2}; {error, auth_failure} -> {error, auth_failure}; Other -> {error, Other} end. start(ClientId, Username, Password, Channel) -> DO NOT use start_link , since multiple coap_reponsder may have relation with one mqtt adapter , one coap_responder crashes should not make mqtt adapter crash too gen_server:start({via, emq_hw_coap_registry, {ClientId, Username, Password}}, ?MODULE, {ClientId, Username, Password, Channel}, []). stop(Pid) -> gen_server:stop(Pid). subscribe(Pid, Topic) -> gen_server:call(Pid, {subscribe, Topic, self()}). unsubscribe(Pid, Topic) -> gen_server:call(Pid, {unsubscribe, Topic, self()}). publish(Pid, Topic, Payload) -> gen_server:call(Pid, {publish, Topic, Payload}). keepalive(Pid)-> gen_server:cast(Pid, keepalive). init({ClientId, Username, Password, Channel}) -> ?LOG(debug, "try to start adapter ClientId=~p, Username=~p, Password=~p, Channel=~p", [ClientId, Username, Password, Channel]), EnableStats = application:get_env(?APP, enable_stats, false), case ?PROTO_INIT(ClientId, Username, Password, Channel, EnableStats) of {ok, Proto} -> {ok, #state{proto = Proto, peer = Channel, enable_stats = EnableStats}}; {stop, auth_failure} -> {stop, auth_failure}; Other -> {stop, Other} end. handle_call({subscribe, Topic, CoapPid}, _From, State=#state{proto = Proto, sub_topics = TopicList}) -> NewTopics = proplists:delete(Topic, TopicList), IsWild = emqx_topic:wildcard(Topic), NewProto = ?PROTO_SUBSCRIBE(Topic, Proto), {reply, ok, State#state{proto = NewProto, sub_topics = [{Topic, {IsWild, CoapPid}}|NewTopics]}, hibernate}; handle_call({unsubscribe, Topic, _CoapPid}, _From, State=#state{proto = Proto, sub_topics = TopicList}) -> NewTopics = proplists:delete(Topic, TopicList), NewProto = ?PROTO_UNSUBSCRIBE(Topic, Proto), {reply, ok, State#state{proto = NewProto, sub_topics = NewTopics}, hibernate}; handle_call({publish, Topic, Payload}, _From, State=#state{proto = Proto}) -> NewProto = ?PROTO_PUBLISH(Topic, Payload, Proto), {reply, ok, State#state{proto = NewProto}}; handle_call(info, From, State = #state{proto = ProtoState, peer = Channel}) -> ProtoInfo = emqx_protocol:info(ProtoState), ClientInfo = [{peername, Channel}], {reply, Stats, _, _} = handle_call(stats, From, State), {reply, lists:append([ClientInfo, ProtoInfo, Stats]), State}; handle_call(stats, _From, State = #state{proto = ProtoState}) -> {reply, lists:append([emqx_misc:proc_stats(), ?PROTO_STATS(ProtoState), socket_stats(undefined, ?SOCK_STATS)]), State, hibernate}; handle_call(kick, _From, State) -> {stop, {shutdown, kick}, ok, State}; handle_call({set_rate_limit, _Rl}, _From, State) -> ?LOG(error, "set_rate_limit is not support", []), {reply, ok, State}; handle_call(get_rate_limit, _From, State) -> ?LOG(error, "get_rate_limit is not support", []), {reply, ok, State}; handle_call(session, _From, State = #state{proto = ProtoState}) -> {reply, emqx_protocol:session(ProtoState), State}; handle_call(Request, _From, State) -> ?LOG(error, "adapter unexpected call ~p", [Request]), {reply, ignored, State, hibernate}. handle_cast(keepalive, State=#state{keepalive = undefined}) -> {noreply, State, hibernate}; handle_cast(keepalive, State=#state{keepalive = Keepalive}) -> emit_stats(State), NewKeepalive = emqx_hw_coap_timer:kick_timer(Keepalive), {noreply, State#state{keepalive = NewKeepalive}, hibernate}; handle_cast(Msg, State) -> ?LOG(error, "broker_api unexpected cast ~p", [Msg]), {noreply, State, hibernate}. handle_info({deliver, Msg = #mqtt_message{topic = TopicName, payload = Payload}}, State = #state{proto = Proto, sub_topics = Subscribers}) -> ?LOG(debug, "deliver message from broker Topic=~p, Payload=~p, Subscribers=~p", [TopicName, Payload, Subscribers]), NewProto = ?PROTO_DELIVER_ACK(Msg, Proto), deliver_to_coap(TopicName, Payload, Subscribers), {ok, NewerProto} = ?PROTO_SEND(Msg, NewProto), {noreply, State#state{proto = NewerProto}}; handle_info({observe_nb_device, CoapRespPid}, State = #state{proto = ProtoState}) -> send OBSERVE to NB device ClientId = ?PROTO_GET_CLIENT_ID(ProtoState), ?LOG(debug, "send observe message to client id=~p, topic=~p~n", [ClientId, ?HUAWEI_NB_OBSERVE_TOPIC]), deliver_observe_to_coap(?HUAWEI_NB_OBSERVE_TOPIC, CoapRespPid, ClientId), {noreply, State}; handle_info({suback, _MsgId, [_GrantedQos]}, State) -> {noreply, State, hibernate}; handle_info({subscribe,_}, State) -> {noreply, State}; handle_info({keepalive, start, Interval}, StateData) -> ?LOG(debug, "Keepalive at the interval of ~p", [Interval]), KeepAlive = emqx_hw_coap_timer:start_timer(Interval, {keepalive, check}), {noreply, StateData#state{keepalive = KeepAlive}, hibernate}; handle_info({keepalive, check}, StateData = #state{keepalive = KeepAlive}) -> case emqx_hw_coap_timer:is_timeout(KeepAlive) of false -> ?LOG(debug, "Keepalive checked ok", []); { noreply , StateData#state{keepalive = NewKeepAlive } } ; true -> ?LOG(debug, "Keepalive timeout, still keep alive", []) end, NewKeepAlive = emqx_coap_timer:restart_timer(KeepAlive), {noreply, StateData#state{keepalive = NewKeepAlive}}; handle_info(emit_stats, State) -> {noreply, emit_stats(State), hibernate}; handle_info(timeout, State) -> {stop, {shutdown, idle_timeout}, State}; handle_info({shutdown, Error}, State) -> {stop, {shutdown, Error}, State}; handle_info({shutdown, conflict, {ClientId, NewPid}}, State) -> ?LOG(warning, "clientid '~s' conflict with ~p", [ClientId, NewPid]), {stop, {shutdown, conflict}, State}; handle_info(Info, State) -> ?LOG(error, "adapter unexpected info ~p", [Info]), {noreply, State, hibernate}. terminate(Reason, #state{proto = Proto, keepalive = KeepAlive}) -> emqx_hw_coap_timer:cancel_timer(KeepAlive), case {Proto, Reason} of {undefined, _} -> ok; {_, {shutdown, Error}} -> ?PROTO_SHUTDOWN(Error, Proto); {_, Reason} -> ?PROTO_SHUTDOWN(Reason, Proto) end. code_change(_OldVsn, State, _Extra) -> {ok, State}. proto_init(ClientId, Username, Password, Channel, EnableStats) -> SendFun = fun(_Packet) -> ok end, PktOpts = [{max_clientid_len, 96}, {max_packet_size, 512}, {client_enable_stats, EnableStats}], Proto = emqx_protocol:init(Channel, SendFun, PktOpts), ConnPkt = #mqtt_packet_connect{client_id = ClientId, username = Username, password = Password, clean_sess = true, keep_alive = application:get_env(?APP, keepalive, ?DEFAULT_KEEP_ALIVE_DURATION)}, case emqx_protocol:received(?CONNECT_PACKET(ConnPkt), Proto) of {ok, Proto1} -> {ok, Proto1}; {stop, {shutdown, auth_failure}, _Proto2} -> {stop, auth_failure}; Other -> error(Other) end. proto_subscribe(Topic, Proto) -> ?LOG(debug, "subscribe Topic=~p", [Topic]), case emqx_protocol:received(?SUBSCRIBE_PACKET(1, [{Topic, ?QOS1}]), Proto) of {ok, Proto1} -> Proto1; Other -> error(Other) end. proto_unsubscribe(Topic, Proto) -> ?LOG(debug, "unsubscribe Topic=~p", [Topic]), case emqx_protocol:received(?UNSUBSCRIBE_PACKET(1, [Topic]), Proto) of {ok, Proto1} -> Proto1; Other -> error(Other) end. proto_publish(Topic, Payload, Proto) -> ?LOG(debug, "publish Topic=~p, Payload=~p", [Topic, Payload]), Publish = #mqtt_packet{header = #mqtt_packet_header{type = ?PUBLISH, qos = ?QOS0}, variable = #mqtt_packet_publish{topic_name = Topic, packet_id = 1}, payload = Payload}, case emqx_protocol:received(Publish, Proto) of {ok, Proto1} -> Proto1; Other -> error(Other) end. proto_deliver_ack(#mqtt_message{qos = ?QOS0, pktid = _PacketId}, Proto) -> Proto; proto_deliver_ack(#mqtt_message{qos = ?QOS1, pktid = PacketId}, Proto) -> case emqx_protocol:received(?PUBACK_PACKET(?PUBACK, PacketId), Proto) of {ok, NewProto} -> NewProto; Other -> error(Other) end; proto_deliver_ack(#mqtt_message{qos = ?QOS2, pktid = PacketId}, Proto) -> case emqx_protocol:received(?PUBACK_PACKET(?PUBREC, PacketId), Proto) of {ok, NewProto} -> case emqx_protocol:received(?PUBACK_PACKET(?PUBCOMP, PacketId), NewProto) of {ok, CurrentProto} -> CurrentProto; Another -> error(Another) end; Other -> error(Other) end. deliver_to_coap(_TopicName, _Payload, []) -> ok; deliver_to_coap(TopicName, Payload, [{TopicFilter, {IsWild, CoapPid}}|T]) -> Matched = case IsWild of true -> emqx_topic:match(TopicName, TopicFilter); false -> TopicName =:= TopicFilter end, ?LOG(debug, "deliver_to_coap Matched=~p, CoapPid=~p, TopicName=~p, Payload=~p, T=~p", [Matched, CoapPid, TopicName, Payload, T]), case Matched of true -> case binary:match(TopicName, ?NB_CLIENT_ID_PREFIX) of nomatch -> (CoapPid ! {dispatch, TopicName, Payload}); {_Pos, _Len} -> UriPathList = binary:split(?HUAWEI_NB_OBSERVE_TOPIC, <<$/>>, [global]), Here we notice that in every dl msg that sent by Huawei CDP server includes the observe=0 option , it is obviously unnecessary , and we doubt why Huawei CDP acts this way . So we remove the observe option here , and the Huawei NB - Iot device can receive the dl message correctly as well , that means we can use AT+NMGR to receive correct payload . Msg = lwm2m_coap_message:request(con, post, Payload, [{uri_path, UriPathList}]), ?LOG(debug, "deliver_to_coap will send request=~p to CoapRespPid=~p~n", [Msg, CoapPid]), CoapPid ! {dispatch_request, Msg, undefined} end; false -> ok end, deliver_to_coap(TopicName, Payload, T). deliver_observe_to_coap(Observe_uri, CoapRespPid, Clientid) -> case is_process_alive(CoapRespPid) of true -> ?LOG(debug, "deliver_observe_to_coap will send to responder Pid=~p~n", [CoapRespPid]), UriPathList = binary:split(Observe_uri, <<$/>>, [global]), Msg = lwm2m_coap_message:request(con, get, <<>>, [{uri_path, UriPathList}, {observe, 0}]), CoapRespPid ! {dispatch_request, Msg, Clientid}; false -> ?LOG(debug, "CoapRespPid =~p is not a PID, skip observe", [CoapRespPid]) end. socket_stats(undefined, Stats) when is_list(Stats)-> FakeSockOpt = [0, 0, 0, 0, 0], List = lists:zip(Stats, FakeSockOpt), ?LOG(debug, "The List=~p", [List]), List. emit_stats(StateData=#state{proto=ProtoState}) -> emit_stats(?PROTO_GET_CLIENT_ID(ProtoState), StateData). emit_stats(_ClientId, State = #state{enable_stats = false}) -> ? , " The enable_stats is false , skip emit_state ~ n " , [ ] ) , State; emit_stats(ClientId, State) -> {reply, Stats, _, _} = handle_call(stats, undefined, State), ?SET_CLIENT_STATS(ClientId, Stats), State.
dafe4b0a5081992237e021dc2b5511df5d20f25f7ddebae090220d06e96690df
yallop/ocaml-asp
sexp_staged_combinator_parser.ml
* Copyright ( c ) 2018 and * * This file is distributed under the terms of the MIT License . * See the file LICENSE for details . * Copyright (c) 2018 Neelakantan Krishnaswami and Jeremy Yallop * * This file is distributed under the terms of the MIT License. * See the file LICENSE for details. *) module P1 = Asp.Staged.Parse(Asp.Utilities.Unstaged.Char_element) module P2 = Asp.Staged.Parse(Sexp_tokens) module Lexer = struct open P1 let chr c = tok (Asp.Utilities.Unstaged.Chr c) let charset s = let len = String.length s in let rec loop i acc = if i < len then loop (i+1) (acc <|> chr s.[i]) else acc in loop 0 bot let lower = charset "abcdefghijklmnopqrstuvwxyz" let upper = charset "ABCDEFGHIJKLMNOPQRSTUVWXYZ" let digit = charset "0123456789" let whitespace = charset " \t\r\n" let lex = fix @@ fun self -> ((any [lower; upper] >>> star (any [lower; upper; digit])) $ fun x -> .< Some (Sexp_tokens_base.T (Sexp_tokens_base.ATOM, fst .~x :: snd .~x)) >.) <|> ((whitespace >>> self) $ fun x -> .< snd .~x >.) <|> (chr '(' $ fun _ -> .< Some (Sexp_tokens_base.T (Sexp_tokens_base.LPAREN, ())) >.) <|> (chr ')' $ fun _ -> .< Some (Sexp_tokens_base.T (Sexp_tokens_base.RPAREN, ())) >.) <|> (eps .<None>.) let lexcode = let module R = P1.Parser(Asp_streamcode.Stringcode) in R.compile (type_check lex) let staged_lexer = Runnative.run lexcode let next s = let i = ref 0 in fun _ -> let tok, i' = staged_lexer ~index:!i s in i := i'; tok let staged_lexer_stream : string -> Sexp_tokens_base.t Stream.t = fun s -> Stream.from (next s) end module Parser = struct open P2 let parse = let open Sexp_tokens_base in fix @@ fun sexp -> ((tok LPAREN >>> star sexp >>> tok RPAREN) $ fun x -> .<List.fold_left (+) 0 (snd (fst .~x)) >.) <|> (tok ATOM $ fun _ -> .<1>.) let parsecode = let module R = P2.Parser(Asp_streamcode.Streamcode(struct type t = Sexp_tokens_base.t end)) in R.compile (type_check parse) let staged_parser : Sexp_tokens_base.t Stream.t -> int = Runnative.run parsecode let staged_complete : string -> int = fun s -> staged_parser (Lexer.staged_lexer_stream s) end
null
https://raw.githubusercontent.com/yallop/ocaml-asp/a092f17ea55d427c63414899e39a8fe80b30db14/benchmarks/sexp/sexp_staged_combinator_parser.ml
ocaml
* Copyright ( c ) 2018 and * * This file is distributed under the terms of the MIT License . * See the file LICENSE for details . * Copyright (c) 2018 Neelakantan Krishnaswami and Jeremy Yallop * * This file is distributed under the terms of the MIT License. * See the file LICENSE for details. *) module P1 = Asp.Staged.Parse(Asp.Utilities.Unstaged.Char_element) module P2 = Asp.Staged.Parse(Sexp_tokens) module Lexer = struct open P1 let chr c = tok (Asp.Utilities.Unstaged.Chr c) let charset s = let len = String.length s in let rec loop i acc = if i < len then loop (i+1) (acc <|> chr s.[i]) else acc in loop 0 bot let lower = charset "abcdefghijklmnopqrstuvwxyz" let upper = charset "ABCDEFGHIJKLMNOPQRSTUVWXYZ" let digit = charset "0123456789" let whitespace = charset " \t\r\n" let lex = fix @@ fun self -> ((any [lower; upper] >>> star (any [lower; upper; digit])) $ fun x -> .< Some (Sexp_tokens_base.T (Sexp_tokens_base.ATOM, fst .~x :: snd .~x)) >.) <|> ((whitespace >>> self) $ fun x -> .< snd .~x >.) <|> (chr '(' $ fun _ -> .< Some (Sexp_tokens_base.T (Sexp_tokens_base.LPAREN, ())) >.) <|> (chr ')' $ fun _ -> .< Some (Sexp_tokens_base.T (Sexp_tokens_base.RPAREN, ())) >.) <|> (eps .<None>.) let lexcode = let module R = P1.Parser(Asp_streamcode.Stringcode) in R.compile (type_check lex) let staged_lexer = Runnative.run lexcode let next s = let i = ref 0 in fun _ -> let tok, i' = staged_lexer ~index:!i s in i := i'; tok let staged_lexer_stream : string -> Sexp_tokens_base.t Stream.t = fun s -> Stream.from (next s) end module Parser = struct open P2 let parse = let open Sexp_tokens_base in fix @@ fun sexp -> ((tok LPAREN >>> star sexp >>> tok RPAREN) $ fun x -> .<List.fold_left (+) 0 (snd (fst .~x)) >.) <|> (tok ATOM $ fun _ -> .<1>.) let parsecode = let module R = P2.Parser(Asp_streamcode.Streamcode(struct type t = Sexp_tokens_base.t end)) in R.compile (type_check parse) let staged_parser : Sexp_tokens_base.t Stream.t -> int = Runnative.run parsecode let staged_complete : string -> int = fun s -> staged_parser (Lexer.staged_lexer_stream s) end
9c034d5c233a79e30275898342ae2dc55c9802c9d4d0c4108efbde640853a507
LaurentMazare/ocaml-minipy
bc_list.mli
open Base val attrs : Bc_value.t Queue.t -> attr:string -> Bc_value.t
null
https://raw.githubusercontent.com/LaurentMazare/ocaml-minipy/e83d4bfad55819a27195109d401437faa0f65f69/src/bc_list.mli
ocaml
open Base val attrs : Bc_value.t Queue.t -> attr:string -> Bc_value.t
da4931b8949a5d12da24904a81aa240ae33c24ece2302d96c01f631abdd74281
robrix/starlight
Faction.hs
# LANGUAGE DataKinds # # LANGUAGE DeriveGeneric # {-# LANGUAGE DeriveTraversable #-} {-# LANGUAGE RankNTypes #-} # LANGUAGE TypeApplications # module Starlight.Faction ( Factions , factions_ , factions , getFactions , Faction(..) , name_ , relationships_ ) where import Control.Lens import Data.Generics.Product.Fields import Data.IntMap as IntMap import Data.Text (Text) import GHC.Generics (Generic) import UI.Colour newtype Factions = Factions (forall v . [v] -> [Faction v]) factions_ :: Iso' Factions (IntMap (Faction Int)) factions_ = iso getFactions factions factions :: IntMap (Faction Int) -> Factions factions fs = Factions (\ vs -> go vs <$> IntMap.elems fs) where go vs f = f & relationships_.traversed._1 %~ (vs !!) getFactions :: Factions -> IntMap (Faction Int) getFactions (Factions fs) = IntMap.fromDistinctAscList (zip [0..] (fs [0..])) data Faction a = Faction { name :: Text , colour :: Colour Float , relationships :: [(a, Double)] } deriving (Eq, Foldable, Functor, Generic, Ord, Show, Traversable) instance HasColour (Faction a) name_ :: Lens' (Faction a) Text name_ = field @"name" relationships_ :: Lens (Faction a) (Faction b) [(a, Double)] [(b, Double)] relationships_ = field @"relationships"
null
https://raw.githubusercontent.com/robrix/starlight/ad80ab74dc2eedbb52a75ac8ce507661d32f488e/src/Starlight/Faction.hs
haskell
# LANGUAGE DeriveTraversable # # LANGUAGE RankNTypes #
# LANGUAGE DataKinds # # LANGUAGE DeriveGeneric # # LANGUAGE TypeApplications # module Starlight.Faction ( Factions , factions_ , factions , getFactions , Faction(..) , name_ , relationships_ ) where import Control.Lens import Data.Generics.Product.Fields import Data.IntMap as IntMap import Data.Text (Text) import GHC.Generics (Generic) import UI.Colour newtype Factions = Factions (forall v . [v] -> [Faction v]) factions_ :: Iso' Factions (IntMap (Faction Int)) factions_ = iso getFactions factions factions :: IntMap (Faction Int) -> Factions factions fs = Factions (\ vs -> go vs <$> IntMap.elems fs) where go vs f = f & relationships_.traversed._1 %~ (vs !!) getFactions :: Factions -> IntMap (Faction Int) getFactions (Factions fs) = IntMap.fromDistinctAscList (zip [0..] (fs [0..])) data Faction a = Faction { name :: Text , colour :: Colour Float , relationships :: [(a, Double)] } deriving (Eq, Foldable, Functor, Generic, Ord, Show, Traversable) instance HasColour (Faction a) name_ :: Lens' (Faction a) Text name_ = field @"name" relationships_ :: Lens (Faction a) (Faction b) [(a, Double)] [(b, Double)] relationships_ = field @"relationships"
5e6f116478c2289f07fc433d4fbc6c60c525cbc9f186021a3d3692d6231ecf11
lambdacube3d/lambdacube-compiler
Reducer.hs
-- efficient lazy evaluation for lambda calculus with constructors and delta functions -- eliminators are used instead of case expressions # LANGUAGE LambdaCase # {-# LANGUAGE RankNTypes #-} import Control.Monad.ST import Control.Monad.Fix import System.Environment import Data.STRef -------------------------------------------------------------------------------- data Exp s = Ref !(STRef s (Exp s)) | Lam !(Exp s -> Exp s) | App (Exp s) (Exp s) | Action !(ST s (Exp s)) | Con !ConName [Exp s] | Int !Int | LetRec (Exp s -> Exp s) (Exp s -> Exp s) infixl 1 `App` type VarName = Int data ConName = T2 | CTrue | CFalse | Nil | Cons deriving (Eq, Show) instance Show (Exp s) where show = \case Int i -> show i -------------------------------------------------------------------------------- pureEval :: (forall s . Exp s) -> String pureEval e = runST (show <$> evalN e) -- eval to some normal form (not needed in the current test case) evalN :: Exp s -> ST s (Exp s) evalN x = eval x >>= \case Con f es -> Con f <$> mapM evalN es c -> return c -- eval to weak head normal form eval :: Exp s -> ST s (Exp s) eval = \case App (Lam f) x -> eval . f =<< addHeap x -- optimization App l x -> eval l >>= \(Lam f) -> eval . f =<< addHeap x Action m -> m Ref i -> do x <- readSTRef i if reduced x then return x else do -- optimization -- writeSTRef i $ error "cycle in spine" -- optional test z <- eval x writeSTRef i z return z LetRec f g -> eval . g =<< mfix (fmap Ref . newSTRef . f) x -> return x reduced = \case App{} -> False Action{} -> False _ -> True addHeap :: Exp s -> ST s (Exp s) addHeap e = if reduced e then return e else Ref <$> newSTRef e iSqrt :: Int -> Int iSqrt = round . sqrt . fromIntegral -------------------------------------------------------------------------------- example codes infixl 1 @@, @@. (@@), (@@.) :: Exp s -> Exp s -> Exp s (@@) = App (@@.) = (@@) f0 s = Action s f1 s = Lam $ \v0 -> Action $ s v0 f2 s = Lam $ \v0 -> Lam $ \v1 -> Action $ s v0 v1 f3 s = Lam $ \v0 -> Lam $ \v1 -> Lam $ \v2 -> Action $ s v0 v1 v2 c0 s = Con s [] c1 s = Lam $ \v0 -> Con s [v0] c2 s = Lam $ \v0 -> Lam $ \v1 -> Con s [v0, v1] c3 s = Lam $ \v0 -> Lam $ \v1 -> Lam $ \v2 -> Con s [v0, v1, v2] intOp g = f2 $ \a b -> do Int x <- eval a Int y <- eval b return $ Int $ g x y boolOp g = f2 $ \a b -> do Int x <- eval a Int y <- eval b return $ if g x y then true else false undef = f0 $ return $ error "undef" -- tuples t2 = c2 T2 elimT2 = f2 $ \t f -> eval t >>= eval . \(Con _ (x: y:_)) -> f `App` x `App` y -- booleans false = c0 CFalse true = c0 CTrue elimBool = f3 $ \xs f g -> eval xs >>= eval . \case Con CFalse _ -> f Con CTrue _ -> g and' = Lam $ \v0 -> Lam $ \v1 -> elimBool @@ v0 @@ false @@ v1 -- lists nil = c0 Nil cons = c2 Cons elimList = f3 $ \xs f g -> eval xs >>= eval . \case Con Nil _ -> f Con Cons (x: y:_) -> g `App` x `App` y -- integers zero = Int 0 one = Int 1 two = Int 2 add = intOp (+) sub = intOp (-) mod' = intOp mod eq = boolOp (==) neq = boolOp (/=) leq = boolOp (<=) geq = boolOp (>=) iSqrt' = f1 $ \x -> eval x >>= \(Int n) -> return $ Int (iSqrt n) nthPrime n = LetRec (\r -> Lam $ \v0 -> cons @@. v0 @@. (r @@ (add @@. one @@. v0))) $ \from -> LetRec (\r -> Lam $ \v0 -> Lam $ \v1 -> Lam $ \v2 -> elimList @@. v2 @@. v1 @@. (Lam $ \v3 -> Lam $ \v4 -> v0 @@ v3 @@ (r @@ v0 @@ v1 @@ v4))) $ \foldr' -> LetRec (\r -> Lam $ \v0 -> Lam $ \v1 -> elimList @@. v1 @@. nil @@. (Lam $ \v2 -> Lam $ \v3 -> elimBool @@. (v0 @@ v2) @@. nil @@. (cons @@. v2 @@. (r @@ v0 @@ v3)))) $ \takeWhile' -> LetRec (\r -> Lam $ \v0 -> Lam $ \v1 -> elimList @@. v0 @@. undef @@. (Lam $ \v2 -> Lam $ \v3 -> elimBool @@. (eq @@. v1 @@. zero) @@. (r @@ v3 @@ (sub @@. v1 @@. one)) @@. v2)) $ \nth -> let map_ = Lam $ \v0 -> foldr' @@ (Lam $ \v1 -> Lam $ \v2 -> cons @@. (v0 @@ v1) @@. v2) @@ nil and'' = foldr' @@ and' @@ true filter' = Lam $ \v0 -> foldr' @@ (Lam $ \v1 -> Lam $ \v2 -> elimBool @@. (v0 @@ v1) @@. v2 @@. (cons @@. v1 @@. v2)) @@ nil in LetRec (\r -> cons @@. Int 2 @@. (cons @@. Int 3 @@. (filter' @@ (Lam $ \v0 -> and'' @@ (map_ @@. (Lam $ \v1 -> neq @@. zero @@. (mod' @@. v0 @@. v1)) @@ (takeWhile' @@ (geq @@ (iSqrt' @@. v0)) @@ r))) @@ (from @@ Int 5)))) $ \primes -> nth @@ primes @@ Int n main = getArgs >>= \case [n] -> putStrLn $ pureEval $ nthPrime $ read n [_, n] -> print $ primes !! read n primes = 2:3: filter (\n -> and $ map (\p -> n `mod` p /= 0) (takeWhile (<= iSqrt n) primes)) [5..]
null
https://raw.githubusercontent.com/lambdacube3d/lambdacube-compiler/ca8d65a210a8801c8358fc29a9ead427afc9fce4/prototypes/Reducer.hs
haskell
efficient lazy evaluation for lambda calculus with constructors and delta functions eliminators are used instead of case expressions # LANGUAGE RankNTypes # ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ eval to some normal form (not needed in the current test case) eval to weak head normal form optimization optimization writeSTRef i $ error "cycle in spine" -- optional test ------------------------------------------------------------------------------ example codes tuples booleans lists integers
# LANGUAGE LambdaCase # import Control.Monad.ST import Control.Monad.Fix import System.Environment import Data.STRef data Exp s = Ref !(STRef s (Exp s)) | Lam !(Exp s -> Exp s) | App (Exp s) (Exp s) | Action !(ST s (Exp s)) | Con !ConName [Exp s] | Int !Int | LetRec (Exp s -> Exp s) (Exp s -> Exp s) infixl 1 `App` type VarName = Int data ConName = T2 | CTrue | CFalse | Nil | Cons deriving (Eq, Show) instance Show (Exp s) where show = \case Int i -> show i pureEval :: (forall s . Exp s) -> String pureEval e = runST (show <$> evalN e) evalN :: Exp s -> ST s (Exp s) evalN x = eval x >>= \case Con f es -> Con f <$> mapM evalN es c -> return c eval :: Exp s -> ST s (Exp s) eval = \case App l x -> eval l >>= \(Lam f) -> eval . f =<< addHeap x Action m -> m Ref i -> do x <- readSTRef i z <- eval x writeSTRef i z return z LetRec f g -> eval . g =<< mfix (fmap Ref . newSTRef . f) x -> return x reduced = \case App{} -> False Action{} -> False _ -> True addHeap :: Exp s -> ST s (Exp s) addHeap e = if reduced e then return e else Ref <$> newSTRef e iSqrt :: Int -> Int iSqrt = round . sqrt . fromIntegral infixl 1 @@, @@. (@@), (@@.) :: Exp s -> Exp s -> Exp s (@@) = App (@@.) = (@@) f0 s = Action s f1 s = Lam $ \v0 -> Action $ s v0 f2 s = Lam $ \v0 -> Lam $ \v1 -> Action $ s v0 v1 f3 s = Lam $ \v0 -> Lam $ \v1 -> Lam $ \v2 -> Action $ s v0 v1 v2 c0 s = Con s [] c1 s = Lam $ \v0 -> Con s [v0] c2 s = Lam $ \v0 -> Lam $ \v1 -> Con s [v0, v1] c3 s = Lam $ \v0 -> Lam $ \v1 -> Lam $ \v2 -> Con s [v0, v1, v2] intOp g = f2 $ \a b -> do Int x <- eval a Int y <- eval b return $ Int $ g x y boolOp g = f2 $ \a b -> do Int x <- eval a Int y <- eval b return $ if g x y then true else false undef = f0 $ return $ error "undef" t2 = c2 T2 elimT2 = f2 $ \t f -> eval t >>= eval . \(Con _ (x: y:_)) -> f `App` x `App` y false = c0 CFalse true = c0 CTrue elimBool = f3 $ \xs f g -> eval xs >>= eval . \case Con CFalse _ -> f Con CTrue _ -> g and' = Lam $ \v0 -> Lam $ \v1 -> elimBool @@ v0 @@ false @@ v1 nil = c0 Nil cons = c2 Cons elimList = f3 $ \xs f g -> eval xs >>= eval . \case Con Nil _ -> f Con Cons (x: y:_) -> g `App` x `App` y zero = Int 0 one = Int 1 two = Int 2 add = intOp (+) sub = intOp (-) mod' = intOp mod eq = boolOp (==) neq = boolOp (/=) leq = boolOp (<=) geq = boolOp (>=) iSqrt' = f1 $ \x -> eval x >>= \(Int n) -> return $ Int (iSqrt n) nthPrime n = LetRec (\r -> Lam $ \v0 -> cons @@. v0 @@. (r @@ (add @@. one @@. v0))) $ \from -> LetRec (\r -> Lam $ \v0 -> Lam $ \v1 -> Lam $ \v2 -> elimList @@. v2 @@. v1 @@. (Lam $ \v3 -> Lam $ \v4 -> v0 @@ v3 @@ (r @@ v0 @@ v1 @@ v4))) $ \foldr' -> LetRec (\r -> Lam $ \v0 -> Lam $ \v1 -> elimList @@. v1 @@. nil @@. (Lam $ \v2 -> Lam $ \v3 -> elimBool @@. (v0 @@ v2) @@. nil @@. (cons @@. v2 @@. (r @@ v0 @@ v3)))) $ \takeWhile' -> LetRec (\r -> Lam $ \v0 -> Lam $ \v1 -> elimList @@. v0 @@. undef @@. (Lam $ \v2 -> Lam $ \v3 -> elimBool @@. (eq @@. v1 @@. zero) @@. (r @@ v3 @@ (sub @@. v1 @@. one)) @@. v2)) $ \nth -> let map_ = Lam $ \v0 -> foldr' @@ (Lam $ \v1 -> Lam $ \v2 -> cons @@. (v0 @@ v1) @@. v2) @@ nil and'' = foldr' @@ and' @@ true filter' = Lam $ \v0 -> foldr' @@ (Lam $ \v1 -> Lam $ \v2 -> elimBool @@. (v0 @@ v1) @@. v2 @@. (cons @@. v1 @@. v2)) @@ nil in LetRec (\r -> cons @@. Int 2 @@. (cons @@. Int 3 @@. (filter' @@ (Lam $ \v0 -> and'' @@ (map_ @@. (Lam $ \v1 -> neq @@. zero @@. (mod' @@. v0 @@. v1)) @@ (takeWhile' @@ (geq @@ (iSqrt' @@. v0)) @@ r))) @@ (from @@ Int 5)))) $ \primes -> nth @@ primes @@ Int n main = getArgs >>= \case [n] -> putStrLn $ pureEval $ nthPrime $ read n [_, n] -> print $ primes !! read n primes = 2:3: filter (\n -> and $ map (\p -> n `mod` p /= 0) (takeWhile (<= iSqrt n) primes)) [5..]
eafa9ca840a31878b1d8dd41764bfdf78ecadc6f3182bcac22288f9862184477
bbc/haskell-workshop
C4SyntaxInFunctions.hs
module C4SyntaxInFunctions where -- Pattern Matching -- finish this fibonaacci function using pattern matching fib 10 should return 89 fib :: Int -> Int fib 0 = 1 fib 1 = 1 fib n = fib (n - 1) + fib (n - 2) -- write a safeTail function that returns the tail of a list if it is not empty -- otherwise returns an empty list, [] -- use pattern matching -- (note that the patterns are not filled in like they are in the fib example, you will need to write the patterns yourself) safeTail :: [String] -> [String] safeTail [] = [] safeTail (x:xs) = xs -- write the reverse function using pattern matching myReverse :: [a] -> [a] myReverse [] = [] myReverse (x:xs) = myReverse xs ++ [x] -- Guards Write a function that takes two Ints and returns 1 if the first one is greater than the second -- returns 0 if they are equal and returns -1 if the second is greater -- Use guards - do not use if-statements -- Something to think about: Why can you not use pattern matching for this? mySort :: Int -> Int -> Int mySort a b | a < b = (-1) | a == b = 0 | otherwise = 1
null
https://raw.githubusercontent.com/bbc/haskell-workshop/475b9bac04167665030d7863798ccd27dfd589d0/chrisb/exercises/src/C4SyntaxInFunctions.hs
haskell
Pattern Matching finish this fibonaacci function using pattern matching write a safeTail function that returns the tail of a list if it is not empty otherwise returns an empty list, [] use pattern matching (note that the patterns are not filled in like they are in the fib example, you will need to write the patterns yourself) write the reverse function using pattern matching Guards returns 0 if they are equal Use guards - do not use if-statements Something to think about: Why can you not use pattern matching for this?
module C4SyntaxInFunctions where fib 10 should return 89 fib :: Int -> Int fib 0 = 1 fib 1 = 1 fib n = fib (n - 1) + fib (n - 2) safeTail :: [String] -> [String] safeTail [] = [] safeTail (x:xs) = xs myReverse :: [a] -> [a] myReverse [] = [] myReverse (x:xs) = myReverse xs ++ [x] Write a function that takes two Ints and returns 1 if the first one is greater than the second and returns -1 if the second is greater mySort :: Int -> Int -> Int mySort a b | a < b = (-1) | a == b = 0 | otherwise = 1
fead82f89a88797df8a923ee71732c805c486701ea55ad4c7f4863b08c44ed40
sharplispers/montezuma
tc-term-info.lisp
(in-package #:montezuma) (deftestfun test-term-info (let ((ti-1 (make-instance 'term-info :doc-freq 1 :freq-pointer 2 :prox-pointer 3 :skip-offset 1))) (test term-info-1 (doc-freq ti-1) 1) (test term-info-2 (freq-pointer ti-1) 2) (test term-info-3 (prox-pointer ti-1) 3) (test term-info-4 (skip-offset ti-1) 1) (let ((ti-2 (clone ti-1))) (test term-info-5 (and (term-info= ti-1 ti-2) T) T) (setf ti-2 (make-instance 'term-info :doc-freq 10 :freq-pointer 9 :prox-pointer 8)) (test term-info-6 (term-info= ti-1 ti-2) NIL) (set-from-term-info ti-2 ti-1) (test term-info-7 (term-info= ti-1 ti-2) T))))
null
https://raw.githubusercontent.com/sharplispers/montezuma/ee2129eece7065760de4ebbaeffaadcb27644738/tests/unit/index/tc-term-info.lisp
lisp
(in-package #:montezuma) (deftestfun test-term-info (let ((ti-1 (make-instance 'term-info :doc-freq 1 :freq-pointer 2 :prox-pointer 3 :skip-offset 1))) (test term-info-1 (doc-freq ti-1) 1) (test term-info-2 (freq-pointer ti-1) 2) (test term-info-3 (prox-pointer ti-1) 3) (test term-info-4 (skip-offset ti-1) 1) (let ((ti-2 (clone ti-1))) (test term-info-5 (and (term-info= ti-1 ti-2) T) T) (setf ti-2 (make-instance 'term-info :doc-freq 10 :freq-pointer 9 :prox-pointer 8)) (test term-info-6 (term-info= ti-1 ti-2) NIL) (set-from-term-info ti-2 ti-1) (test term-info-7 (term-info= ti-1 ti-2) T))))
66c4d8d6dbbc23988b16a8b6028c4a113492382964589927c5fbe3977899f21d
rabeckett/Temporal-NetKAT
fdd.mli
open Common open Syntax type 'a fdd (** Forwarding Decision Diagram over polymorphic leaf type *) type 'a mem * An FDD memory to ensure unicity of nodes , functions require a memory from which to perform hashconsing . Memories should be global and reused to ensure correctness functions require a memory from which to perform hashconsing. Memories should be global and reused to ensure correctness *) type rules = ((field_val list) * updates) list (** Forwarding rules contain match * action pairs *) module FddType (X: sig type t end) : (Set.OrderedType with type t = X.t fdd) (** Module for bulding efficient sets/maps over fdds *) module FddType2 (X: sig type t end) (Y: sig type t end) : (Set.OrderedType with type t = X.t fdd * Y.t fdd) (** Module for bulding efficient sets/maps over fdds *) val create_mem: ('a -> int) -> ('a -> 'a -> bool) -> 'a mem (** Create a memory with a equality and hash function *) val node: 'a mem -> field_val -> 'a fdd -> 'a fdd -> 'a fdd * Build a new fdd node from old nodes and a field + value val value: 'a mem -> 'a -> 'a fdd (** Build a leaf fdd node from a value of type 'a *) val apply: 'b mem -> ('a -> 'a -> 'b) -> 'a fdd -> 'a fdd -> 'b fdd * Standard apply operator over an fdd . Base element type can change val map: 'b mem -> ('a -> 'b) -> 'a fdd -> 'b fdd (** Map over elements of an fdd. Base element type can change *) val map_path: 'b mem -> (Syntax.update -> 'a -> 'b) -> 'a fdd -> 'b fdd * Map over elements of an fdd , with field - value sequence of the path provided val elements: 'a fdd -> 'a Bag.t * Return all of the leaf elements of the fdd as a bag val replace: 'a mem -> field_val -> 'a fdd -> updates fdd -> 'a fdd * Performs substitution for a field - value with an expression ( updates fdd ) val eval: 'a fdd -> Syntax.update -> 'a * Evaluate an fdd given concrete values for fields and corresponding values val show_fdd: ('a -> string) -> 'a fdd -> string * Get a string representation for an fdd val updates_mem: updates mem * Specialized memory for where leaves are specialized to NetKAT modifications val bot: updates fdd (** Fdd representing false *) val top: updates fdd (** Fdd representing true *) val var: field_val -> updates fdd (** Fdd for a test, i.e., f = v *) val assign: field_val -> updates fdd (** Fdd for an assignment, i.e., f <- v *) val plus: updates fdd -> updates fdd -> updates fdd * Sum of two fdds representing NetKAT ( + ) operator val seq: updates fdd -> updates fdd -> updates fdd * Sequence of two fdds representing NetKAT ( ;) operator val neg: updates fdd -> updates fdd * Negation of an fdd representing NetKAT not operator val star: updates fdd -> updates fdd * fixpoint of an fdd val create: Syntax.term -> updates fdd * Create an fdd from a NetKAT term val rules: updates fdd -> rules * rules * rules * int * Generate forwarding rules from an fdd ( return multiple values for stats ) val write_rules: out_channel -> rules -> unit (** Write rules to an out channel for simplicity *) module Test: sig val unit_tests: unit -> unit end
null
https://raw.githubusercontent.com/rabeckett/Temporal-NetKAT/829d1847c18d77f40501fe4d988eec6e7867c94d/src/fdd.mli
ocaml
* Forwarding Decision Diagram over polymorphic leaf type * Forwarding rules contain match * action pairs * Module for bulding efficient sets/maps over fdds * Module for bulding efficient sets/maps over fdds * Create a memory with a equality and hash function * Build a leaf fdd node from a value of type 'a * Map over elements of an fdd. Base element type can change * Fdd representing false * Fdd representing true * Fdd for a test, i.e., f = v * Fdd for an assignment, i.e., f <- v * Write rules to an out channel for simplicity
open Common open Syntax type 'a fdd type 'a mem * An FDD memory to ensure unicity of nodes , functions require a memory from which to perform hashconsing . Memories should be global and reused to ensure correctness functions require a memory from which to perform hashconsing. Memories should be global and reused to ensure correctness *) type rules = ((field_val list) * updates) list module FddType (X: sig type t end) : (Set.OrderedType with type t = X.t fdd) module FddType2 (X: sig type t end) (Y: sig type t end) : (Set.OrderedType with type t = X.t fdd * Y.t fdd) val create_mem: ('a -> int) -> ('a -> 'a -> bool) -> 'a mem val node: 'a mem -> field_val -> 'a fdd -> 'a fdd -> 'a fdd * Build a new fdd node from old nodes and a field + value val value: 'a mem -> 'a -> 'a fdd val apply: 'b mem -> ('a -> 'a -> 'b) -> 'a fdd -> 'a fdd -> 'b fdd * Standard apply operator over an fdd . Base element type can change val map: 'b mem -> ('a -> 'b) -> 'a fdd -> 'b fdd val map_path: 'b mem -> (Syntax.update -> 'a -> 'b) -> 'a fdd -> 'b fdd * Map over elements of an fdd , with field - value sequence of the path provided val elements: 'a fdd -> 'a Bag.t * Return all of the leaf elements of the fdd as a bag val replace: 'a mem -> field_val -> 'a fdd -> updates fdd -> 'a fdd * Performs substitution for a field - value with an expression ( updates fdd ) val eval: 'a fdd -> Syntax.update -> 'a * Evaluate an fdd given concrete values for fields and corresponding values val show_fdd: ('a -> string) -> 'a fdd -> string * Get a string representation for an fdd val updates_mem: updates mem * Specialized memory for where leaves are specialized to NetKAT modifications val bot: updates fdd val top: updates fdd val var: field_val -> updates fdd val assign: field_val -> updates fdd val plus: updates fdd -> updates fdd -> updates fdd * Sum of two fdds representing NetKAT ( + ) operator val seq: updates fdd -> updates fdd -> updates fdd * Sequence of two fdds representing NetKAT ( ;) operator val neg: updates fdd -> updates fdd * Negation of an fdd representing NetKAT not operator val star: updates fdd -> updates fdd * fixpoint of an fdd val create: Syntax.term -> updates fdd * Create an fdd from a NetKAT term val rules: updates fdd -> rules * rules * rules * int * Generate forwarding rules from an fdd ( return multiple values for stats ) val write_rules: out_channel -> rules -> unit module Test: sig val unit_tests: unit -> unit end
44cd4ab7e2a4fc594d368118bfc4b60982ea9305d0ab0be7575309b393675b81
esl/amoc-arsenal-xmpp
mongoose_muc.erl
%============================================================================== 2019 - 2020 Erlang Solutions Ltd. Licensed under the Apache License , Version 2.0 ( see LICENSE file ) %% @end %% %% @doc %% In this scenario, users are entering MUC Rooms and exchanging messages. Each room has one sender . %% %% == User steps: == %% 1 . Connect to the XMPP host . %% 2 . Send presence ` available ' . %% 3 . Enter selected MUC rooms . After each entered room , wait for ` delay_after_entering_room ' before joining another MUC room . %% 4 . Wait for the ` delay_before_sending_messages ' . %% 5 . Start sending messages to the selected MUC rooms . The number of messages %% to be sent per room is defined by the `messages_to_send_per_room' variable. %% The rate of messages that is being sent is defined by the ` message_interval_per_room ' variable . %% 6 . Receive messages , notifications and presences from the MUC rooms and update %% the metrics accordingly. %% %% == Metrics exposed by this scenario: == %% %% === Counters: === - muc_rooms_created - incremented for every MUC room that has been created . %% - muc_occupants - incremented for every user that joins a MUC room . %% - muc_messages_sent - incremented for every MUC message that is being sent . %% - muc_messages_received - incremented for every MUC message that is being received . %% - muc_presences_received - incremented for every received MUC presence . %% - muc_notifications_received - incremented for every received MUC notification . %% %% - timeouts - incremented for every request that resulted in a timeout. %% %% === Times: === %% - response - response time for every request that was sent. %% %% - muc_message_tdd - MUC message time to delivery %% %% @end %%============================================================================== -module(mongoose_muc). -behaviour(amoc_scenario). -export([init/0, start/1]). -include_lib("exml/include/exml.hrl"). -include_lib("kernel/include/logger.hrl"). -required_variable([ #{name => rooms_per_user, default_value => 10, description => "rooms per user"}, #{name => users_per_room, default_value => 20, description => "users per room"}, #{name => delay_before_sending_messages, default_value => 0, description => "delay before sending messages"}, #{name => delay_after_entering_room, default_value => 10000, description => "delay after entering room"}, #{name => messages_to_send_per_room, default_value => 1000, description => "messages to send per room"}, #{name => message_interval_per_room, default_value => 1000, description => "message interval per room"} ]). -spec init() -> ok. init() -> ?LOG_INFO("init the scenario"), amoc_metrics:init(counters, muc_rooms_created), amoc_metrics:init(counters, muc_occupants), amoc_metrics:init(counters, muc_messages_sent), amoc_metrics:init(counters, muc_messages_received), amoc_metrics:init(counters, muc_presences_received), amoc_metrics:init(counters, muc_notifications_received), amoc_metrics:init(counters, timeouts), amoc_metrics:init(times, response), amoc_metrics:init(times, muc_message_ttd), ok. -spec start(amoc_scenario:user_id()) -> any(). start(Id) -> {ok, Client, _Spec} = amoc_xmpp:connect_or_exit(Id, extra_user_spec()), send_presence_available(Client), RoomIds = amoc_xmpp_muc:rooms_to_join(Id, cfg(rooms_per_user), cfg(users_per_room)), RoomJids = [room_jid(RoomId) || RoomId <- RoomIds], enter_rooms(Client, RoomJids), escalus_connection:wait(Client, cfg(delay_before_sending_messages)), ' rooms_to_create/3 ' assigns one creator to each room In this case it is used to assign one sender to each room RoomIdsToSend = amoc_xmpp_muc:rooms_to_create(Id, cfg(rooms_per_user), cfg(users_per_room)), RoomJidsToSend = [room_jid(RoomId) || RoomId <- RoomIdsToSend], send_messages(Client, my_timetable(RoomJidsToSend), 0), escalus_connection:wait_forever(Client). extra_user_spec() -> [{sent_stanza_handlers, sent_stanza_handlers()}, {received_stanza_handlers, received_stanza_handlers()}]. send_presence_available(Client) -> Pres = escalus_stanza:presence(<<"available">>), Pred = fun(Stanza) -> escalus_pred:is_presence_with_type(<<"available">>, Stanza) andalso escalus_pred:is_stanza_from(Client, Stanza) end, amoc_xmpp:send_request_and_get_response(Client, Pres, Pred, response, 10000). enter_rooms(_Client, []) -> ok; enter_rooms(Client, [RoomJid | Rest]) -> enter_room(Client, RoomJid), escalus_connection:wait(Client, cfg(delay_after_entering_room)), enter_rooms(Client, Rest). enter_room(Client, RoomJid) -> Nick = escalus_client:username(Client), RoomFullJid = room_full_jid(RoomJid, Nick), Req = stanza_muc_enter_room(RoomFullJid), Resp = amoc_xmpp:send_request_and_get_response( Client, Req, fun(Stanza) -> is_muc_presence_resp(Req, Stanza) end, response, 10000), amoc_metrics:update_counter(muc_presences_received), case room_entry_response_type(Resp) of created -> amoc_metrics:update_counter(muc_rooms_created), ?LOG_INFO("~s created room ~s", [Nick, RoomJid]); joined -> ?LOG_INFO("~s joined room ~s", [Nick, RoomJid]) end, amoc_metrics:update_counter(muc_occupants). send_messages(Client, [{Time, MessageType} | TimeTable], TimePassed) -> TimeDiff = max(0, Time - TimePassed), escalus_connection:wait(Client, TimeDiff), send_message(Client, MessageType), send_messages(Client, TimeTable, TimePassed + TimeDiff); send_messages(_Client, [], _TimePassed) -> ok. send_message(Client, {muc_message, RoomJid}) -> escalus_connection:send(Client, message_to_room(RoomJid)). message_to_room(RoomJid) -> Timestamp = integer_to_binary(os:system_time(microsecond)), escalus_stanza:groupchat_to(RoomJid, Timestamp). my_timetable(RoomJidsToSend) -> lists:merge([room_message_timetable(RoomJid) || RoomJid <- RoomJidsToSend]). room_message_timetable(RoomJid) -> Count = cfg(messages_to_send_per_room), Interval = cfg(message_interval_per_room), Offset = rand:uniform(Interval), timetable({muc_message, RoomJid}, Count, Interval, Offset). timetable(Event, Count, Interval, Offset) -> [{Interval * I + Offset, Event} || I <- lists:seq(0, Count - 1)]. stanza_muc_enter_room(RoomJid) -> escalus_stanza:to(escalus_stanza:presence(<<"available">>), RoomJid). room_entry_response_type(Stanza) -> case exml_query:attr(Stanza, <<"type">>) of undefined -> StatusList = exml_query:paths(Stanza, [{element, <<"x">>}, {element, <<"status">>}, {attr, <<"code">>}]), [Affiliation] = exml_query:paths(Stanza, [{element, <<"x">>}, {element, <<"item">>}, {attr, <<"affiliation">>}]), [Role] = exml_query:paths(Stanza, [{element, <<"x">>}, {element, <<"item">>}, {attr, <<"role">>}]), room_entry_success_response_type(lists:sort(StatusList), Affiliation, Role); <<"error">> -> true = escalus_pred:is_error(<<"cancel">>, <<"item-not-found">>, Stanza), locked end. room_entry_success_response_type([<<"110">>, <<"201">>], <<"owner">>, <<"moderator">>) -> created; room_entry_success_response_type([<<"110">>], <<"none">>, <<"participant">>) -> joined. %% Handlers sent_stanza_handlers() -> amoc_xmpp_handlers:make_stanza_handlers( [{fun is_muc_message/1, fun() -> amoc_metrics:update_counter(muc_messages_sent) end}]). received_stanza_handlers() -> amoc_xmpp_handlers:make_stanza_handlers( [{fun is_muc_presence/1, fun() -> amoc_metrics:update_counter(muc_presences_received) end}, {fun is_muc_subject_notification/1, fun() -> amoc_metrics:update_counter(muc_notifications_received) end}, {fun is_muc_message/1, fun(_, Stanza, Metadata) -> amoc_metrics:update_counter(muc_messages_received), amoc_metrics:update_time(muc_message_ttd, ttd(Stanza, Metadata)) end}, {fun(_) -> true end, fun(_, Stanza) -> ?LOG_WARNING("Skipping received stanza ~p", [Stanza]) end}]). %% Predicates is_muc_presence_resp(Req, Resp = #xmlel{name = <<"presence">>}) -> is_muc_presence(Resp) andalso escalus_utils:jid_to_lower(exml_query:attr(Req, <<"to">>)) =:= escalus_utils:jid_to_lower(exml_query:attr(Resp, <<"from">>)); is_muc_presence_resp(_, _) -> false. is_muc_presence(Stanza) -> exml_query:path(Stanza, [{element, <<"x">>}, {attr, <<"xmlns">>}]) =:= ns(muc_user). is_muc_subject_notification(Stanza) -> is_muc_message(Stanza) andalso exml_query:subelement(Stanza, <<"subject">>) =/= undefined andalso lists:member(exml_query:path(Stanza, [{element, <<"body">>}, cdata]), [<<>>, undefined]). is_muc_message(Stanza = #xmlel{name = <<"message">>}) -> exml_query:attr(Stanza, <<"type">>) =:= <<"groupchat">>; is_muc_message(_) -> false. %% Helpers ttd(Stanza, #{recv_timestamp := Recv}) -> SentBin = exml_query:path(Stanza, [{element, <<"body">>}, cdata]), Recv - binary_to_integer(SentBin). cfg(Name) -> amoc_config:get(Name). room_full_jid(RoomJid, Nick) -> <<RoomJid/binary, $/, Nick/binary>>. room_jid(RoomId) -> <<(room_name(RoomId))/binary, $@, (muc_host())/binary>>. room_name(RoomId) -> <<"room_", (integer_to_binary(RoomId))/binary>>. muc_host() -> <<"muc.localhost">>. ns(muc_user) -> <<"#user">>.
null
https://raw.githubusercontent.com/esl/amoc-arsenal-xmpp/5422d01a0e0f6c588b8139891de131e1fbf964e7/src/scenarios/mongoose_muc.erl
erlang
============================================================================== @end @doc In this scenario, users are entering MUC Rooms and exchanging messages. == User steps: == to be sent per room is defined by the `messages_to_send_per_room' variable. The rate of messages that is being sent is defined by the the metrics accordingly. == Metrics exposed by this scenario: == === Counters: === - timeouts - incremented for every request that resulted in a timeout. === Times: === - response - response time for every request that was sent. - muc_message_tdd - MUC message time to delivery @end ============================================================================== Handlers Predicates Helpers
2019 - 2020 Erlang Solutions Ltd. Licensed under the Apache License , Version 2.0 ( see LICENSE file ) Each room has one sender . 1 . Connect to the XMPP host . 2 . Send presence ` available ' . 3 . Enter selected MUC rooms . After each entered room , wait for ` delay_after_entering_room ' before joining another MUC room . 4 . Wait for the ` delay_before_sending_messages ' . 5 . Start sending messages to the selected MUC rooms . The number of messages ` message_interval_per_room ' variable . 6 . Receive messages , notifications and presences from the MUC rooms and update - muc_rooms_created - incremented for every MUC room that has been created . - muc_occupants - incremented for every user that joins a MUC room . - muc_messages_sent - incremented for every MUC message that is being sent . - muc_messages_received - incremented for every MUC message that is being received . - muc_presences_received - incremented for every received MUC presence . - muc_notifications_received - incremented for every received MUC notification . -module(mongoose_muc). -behaviour(amoc_scenario). -export([init/0, start/1]). -include_lib("exml/include/exml.hrl"). -include_lib("kernel/include/logger.hrl"). -required_variable([ #{name => rooms_per_user, default_value => 10, description => "rooms per user"}, #{name => users_per_room, default_value => 20, description => "users per room"}, #{name => delay_before_sending_messages, default_value => 0, description => "delay before sending messages"}, #{name => delay_after_entering_room, default_value => 10000, description => "delay after entering room"}, #{name => messages_to_send_per_room, default_value => 1000, description => "messages to send per room"}, #{name => message_interval_per_room, default_value => 1000, description => "message interval per room"} ]). -spec init() -> ok. init() -> ?LOG_INFO("init the scenario"), amoc_metrics:init(counters, muc_rooms_created), amoc_metrics:init(counters, muc_occupants), amoc_metrics:init(counters, muc_messages_sent), amoc_metrics:init(counters, muc_messages_received), amoc_metrics:init(counters, muc_presences_received), amoc_metrics:init(counters, muc_notifications_received), amoc_metrics:init(counters, timeouts), amoc_metrics:init(times, response), amoc_metrics:init(times, muc_message_ttd), ok. -spec start(amoc_scenario:user_id()) -> any(). start(Id) -> {ok, Client, _Spec} = amoc_xmpp:connect_or_exit(Id, extra_user_spec()), send_presence_available(Client), RoomIds = amoc_xmpp_muc:rooms_to_join(Id, cfg(rooms_per_user), cfg(users_per_room)), RoomJids = [room_jid(RoomId) || RoomId <- RoomIds], enter_rooms(Client, RoomJids), escalus_connection:wait(Client, cfg(delay_before_sending_messages)), ' rooms_to_create/3 ' assigns one creator to each room In this case it is used to assign one sender to each room RoomIdsToSend = amoc_xmpp_muc:rooms_to_create(Id, cfg(rooms_per_user), cfg(users_per_room)), RoomJidsToSend = [room_jid(RoomId) || RoomId <- RoomIdsToSend], send_messages(Client, my_timetable(RoomJidsToSend), 0), escalus_connection:wait_forever(Client). extra_user_spec() -> [{sent_stanza_handlers, sent_stanza_handlers()}, {received_stanza_handlers, received_stanza_handlers()}]. send_presence_available(Client) -> Pres = escalus_stanza:presence(<<"available">>), Pred = fun(Stanza) -> escalus_pred:is_presence_with_type(<<"available">>, Stanza) andalso escalus_pred:is_stanza_from(Client, Stanza) end, amoc_xmpp:send_request_and_get_response(Client, Pres, Pred, response, 10000). enter_rooms(_Client, []) -> ok; enter_rooms(Client, [RoomJid | Rest]) -> enter_room(Client, RoomJid), escalus_connection:wait(Client, cfg(delay_after_entering_room)), enter_rooms(Client, Rest). enter_room(Client, RoomJid) -> Nick = escalus_client:username(Client), RoomFullJid = room_full_jid(RoomJid, Nick), Req = stanza_muc_enter_room(RoomFullJid), Resp = amoc_xmpp:send_request_and_get_response( Client, Req, fun(Stanza) -> is_muc_presence_resp(Req, Stanza) end, response, 10000), amoc_metrics:update_counter(muc_presences_received), case room_entry_response_type(Resp) of created -> amoc_metrics:update_counter(muc_rooms_created), ?LOG_INFO("~s created room ~s", [Nick, RoomJid]); joined -> ?LOG_INFO("~s joined room ~s", [Nick, RoomJid]) end, amoc_metrics:update_counter(muc_occupants). send_messages(Client, [{Time, MessageType} | TimeTable], TimePassed) -> TimeDiff = max(0, Time - TimePassed), escalus_connection:wait(Client, TimeDiff), send_message(Client, MessageType), send_messages(Client, TimeTable, TimePassed + TimeDiff); send_messages(_Client, [], _TimePassed) -> ok. send_message(Client, {muc_message, RoomJid}) -> escalus_connection:send(Client, message_to_room(RoomJid)). message_to_room(RoomJid) -> Timestamp = integer_to_binary(os:system_time(microsecond)), escalus_stanza:groupchat_to(RoomJid, Timestamp). my_timetable(RoomJidsToSend) -> lists:merge([room_message_timetable(RoomJid) || RoomJid <- RoomJidsToSend]). room_message_timetable(RoomJid) -> Count = cfg(messages_to_send_per_room), Interval = cfg(message_interval_per_room), Offset = rand:uniform(Interval), timetable({muc_message, RoomJid}, Count, Interval, Offset). timetable(Event, Count, Interval, Offset) -> [{Interval * I + Offset, Event} || I <- lists:seq(0, Count - 1)]. stanza_muc_enter_room(RoomJid) -> escalus_stanza:to(escalus_stanza:presence(<<"available">>), RoomJid). room_entry_response_type(Stanza) -> case exml_query:attr(Stanza, <<"type">>) of undefined -> StatusList = exml_query:paths(Stanza, [{element, <<"x">>}, {element, <<"status">>}, {attr, <<"code">>}]), [Affiliation] = exml_query:paths(Stanza, [{element, <<"x">>}, {element, <<"item">>}, {attr, <<"affiliation">>}]), [Role] = exml_query:paths(Stanza, [{element, <<"x">>}, {element, <<"item">>}, {attr, <<"role">>}]), room_entry_success_response_type(lists:sort(StatusList), Affiliation, Role); <<"error">> -> true = escalus_pred:is_error(<<"cancel">>, <<"item-not-found">>, Stanza), locked end. room_entry_success_response_type([<<"110">>, <<"201">>], <<"owner">>, <<"moderator">>) -> created; room_entry_success_response_type([<<"110">>], <<"none">>, <<"participant">>) -> joined. sent_stanza_handlers() -> amoc_xmpp_handlers:make_stanza_handlers( [{fun is_muc_message/1, fun() -> amoc_metrics:update_counter(muc_messages_sent) end}]). received_stanza_handlers() -> amoc_xmpp_handlers:make_stanza_handlers( [{fun is_muc_presence/1, fun() -> amoc_metrics:update_counter(muc_presences_received) end}, {fun is_muc_subject_notification/1, fun() -> amoc_metrics:update_counter(muc_notifications_received) end}, {fun is_muc_message/1, fun(_, Stanza, Metadata) -> amoc_metrics:update_counter(muc_messages_received), amoc_metrics:update_time(muc_message_ttd, ttd(Stanza, Metadata)) end}, {fun(_) -> true end, fun(_, Stanza) -> ?LOG_WARNING("Skipping received stanza ~p", [Stanza]) end}]). is_muc_presence_resp(Req, Resp = #xmlel{name = <<"presence">>}) -> is_muc_presence(Resp) andalso escalus_utils:jid_to_lower(exml_query:attr(Req, <<"to">>)) =:= escalus_utils:jid_to_lower(exml_query:attr(Resp, <<"from">>)); is_muc_presence_resp(_, _) -> false. is_muc_presence(Stanza) -> exml_query:path(Stanza, [{element, <<"x">>}, {attr, <<"xmlns">>}]) =:= ns(muc_user). is_muc_subject_notification(Stanza) -> is_muc_message(Stanza) andalso exml_query:subelement(Stanza, <<"subject">>) =/= undefined andalso lists:member(exml_query:path(Stanza, [{element, <<"body">>}, cdata]), [<<>>, undefined]). is_muc_message(Stanza = #xmlel{name = <<"message">>}) -> exml_query:attr(Stanza, <<"type">>) =:= <<"groupchat">>; is_muc_message(_) -> false. ttd(Stanza, #{recv_timestamp := Recv}) -> SentBin = exml_query:path(Stanza, [{element, <<"body">>}, cdata]), Recv - binary_to_integer(SentBin). cfg(Name) -> amoc_config:get(Name). room_full_jid(RoomJid, Nick) -> <<RoomJid/binary, $/, Nick/binary>>. room_jid(RoomId) -> <<(room_name(RoomId))/binary, $@, (muc_host())/binary>>. room_name(RoomId) -> <<"room_", (integer_to_binary(RoomId))/binary>>. muc_host() -> <<"muc.localhost">>. ns(muc_user) -> <<"#user">>.
3fa42e0245d178322b09bd4254a6dc8908a7f3150159d23ed4ec61d3acc087d0
Bogdanp/marionette
page.rkt
#lang racket/base (require json net/base64 net/url racket/contract racket/match racket/string "private/browser.rkt" "private/json.rkt" "private/marionette.rkt" "private/template.rkt" "rect.rkt") ;; page ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (provide cookie/c exn:fail:marionette:page? exn:fail:marionette:page:script? exn:fail:marionette:page:script-cause (contract-out [make-page (-> browser? string? page?)] [page? (-> any/c boolean?)] [page=? (-> page? page? boolean?)] [page-id (-> page? string?)] [page-close! (-> page? void?)] [page-refresh! (-> page? void?)] [page-goto! (-> page? (or/c url? string?) void?)] [page-go-back! (-> page? void?)] [page-go-forward! (-> page? void?)] [page-execute! (-> page? string? jsexpr? ... any/c)] [page-execute-async! (-> page? string? jsexpr? ... any/c)] [page-wait-for! (->* (page? string?) (#:timeout (and/c real? (not/c negative?)) #:visible? boolean?) (or/c #f element?))] [page-query-selector! (-> page? string? (or/c #f element?))] [page-query-selector-all! (-> page? string? (listof element?))] [page-interactive? (-> page? boolean?)] [page-loaded? (-> page? boolean?)] [page-title (-> page? string?)] [page-url (-> page? url?)] [page-content (-> page? string?)] [set-page-content! (-> page? string? void?)] [page-cookies (-> page? (listof cookie/c))] [page-add-cookie! (-> page? cookie/c void?)] [page-delete-all-cookies! (-> page? void?)] [page-delete-cookie! (-> page? string? void?)] [page-alert-text (-> page? string?)] [page-alert-accept! (-> page? void?)] [page-alert-dismiss! (-> page? void?)] [page-alert-type! (-> page? string? void?)] [call-with-page-pdf! (-> page? (-> bytes? any) any)] [call-with-page-screenshot! (->* (page? (-> bytes? any)) (#:full? boolean?) any)])) (struct exn:fail:marionette:page exn:fail:marionette ()) (struct exn:fail:marionette:page:script exn:fail:marionette:page (cause)) (struct page (browser id)) (define (make-page b id) (page b id)) (define (page=? page-1 page-2) (and (eq? (page-browser page-1) (page-browser page-2)) (equal? (page-id page-1) (page-id page-2)))) (define (page-marionette p) (browser-marionette (page-browser p))) (define (page-focused? p) (browser-current-page=? (page-browser p) p)) (define (call-with-page p proc) (dynamic-wind (λ () (unless (page-focused? p) (sync/enable-break (marionette-switch-to-window! (page-marionette p) (page-id p))) (set-browser-current-page! (page-browser p) p))) (λ () (proc)) (λ () (void)))) (define-syntax-rule (with-page p e0 e ...) (call-with-page p (λ () e0 e ...))) (define (page-close! p) (with-page p (syncv (marionette-close-window! (page-marionette p))))) (define (page-refresh! p) (with-page p (syncv (marionette-refresh! (page-marionette p))))) (define (page-goto! p u) (with-page p (syncv (marionette-navigate! (page-marionette p) (if (url? u) (url->string u) u))))) (define (page-go-back! p) (with-page p (syncv (marionette-back! (page-marionette p))))) (define (page-go-forward! p) (with-page p (syncv (marionette-forward! (page-marionette p))))) (define (page-execute! p s . args) (with-page p (sync (handle-evt (marionette-execute-script! (page-marionette p) s args) res-value)))) (define (wrap-async-script body) (template "support/wrap-async-script.js")) (define (page-execute-async! p s . args) (with-page p (sync (handle-evt (marionette-execute-async-script! (page-marionette p) (wrap-async-script s) args) (λ (res) (match (hash-ref res 'value) [(hash-table ('error (js-null)) ('value value )) value] [(hash-table ('error err)) (raise (exn:fail:marionette:page:script (format "async script execution failed: ~a" err) (current-continuation-marks) err))] [(js-null) (raise (exn:fail:marionette:page:script "async script execution aborted" (current-continuation-marks) #f))])))))) (define (page-title p) (with-page p (sync (handle-evt (marionette-get-title! (page-marionette p)) res-value)))) (define (page-url p) (with-page p (sync (handle-evt (marionette-get-current-url! (page-marionette p)) (compose1 string->url res-value))))) (define (page-content p) (with-page p (sync (handle-evt (marionette-get-page-source! (page-marionette p)) res-value)))) (define (set-page-content! p c) (void (page-execute! p "document.documentElement.innerHTML = arguments[0]" c))) (define (page-readystate p) (page-execute! p "return document.readyState")) (define (page-interactive? p) (and (member (page-readystate p) '("interactive" "complete")) #t)) (define (page-loaded? p) (and (member (page-readystate p) '("complete")) #t)) (define cookie/c jsexpr?) (define (page-cookies p) (with-page p (sync (marionette-get-cookies! (page-marionette p))))) (define (page-add-cookie! p c) (with-page p (syncv (marionette-add-cookie! (page-marionette p) c)))) (define (page-delete-all-cookies! p) (with-page p (syncv (marionette-delete-all-cookies! (page-marionette p))))) (define (page-delete-cookie! p name) (with-page p (syncv (marionette-delete-cookie! (page-marionette p) name)))) (define wait-for-element-script (template "support/wait-for-element.js")) (define (page-wait-for! p selector #:timeout [timeout 30] #:visible? [visible? #t]) (define res-ch (make-channel)) (thread (λ () (let loop () (define handle (with-handlers ([exn:fail:marionette? (λ (e) (cond [(or (string-contains? (exn-message e) "unloaded") (string-contains? (exn-message e) "async script execution failed") (string-contains? (exn-message e) "async script execution aborted") (string-contains? (exn-message e) "context has been discarded")) (loop)] [else e]))]) (with-page p (page-execute-async! p wait-for-element-script selector (* timeout 1000) visible?)))) (if (exn:fail? handle) (channel-put res-ch handle) (channel-put res-ch (and handle (with-page p (page-query-selector! p selector)))))))) (sync/timeout timeout (handle-evt res-ch (λ (res) (begin0 res (when (exn:fail? res) (raise res))))))) (define (page-query-selector! p selector) (with-handlers ([exn:fail:marionette:command? (λ (e) (cond [(string-contains? (exn-message e) "Unable to locate element") #f] [else (raise e)]))]) (with-page p (sync (handle-evt (marionette-find-element! (page-marionette p) selector) (λ (r) (element p (res-value r)))))))) (define (page-query-selector-all! p selector) (with-page p (sync (handle-evt (marionette-find-elements! (page-marionette p) selector) (λ (ids) (for/list ([id (in-list ids)]) (element p id))))))) (define (page-alert-text p) (sync (handle-evt (marionette-get-alert-text! (page-marionette p)) res-value))) (define (page-alert-accept! p) (with-page p (syncv (marionette-accept-alert! (page-marionette p))))) (define (page-alert-dismiss! p) (with-page p (syncv (marionette-dismiss-alert! (page-marionette p))))) (define (page-alert-type! p text) (syncv (marionette-send-alert-text! (page-marionette p) text))) (define (call-with-page-pdf! p proc) (with-page p (proc (sync (handle-evt (marionette-print! (page-marionette p)) res-value/decode))))) (define (call-with-page-screenshot! p proc #:full? [full? #t]) (with-page p (proc (sync (handle-evt (marionette-take-screenshot! (page-marionette p) full?) res-value/decode))))) ;; element ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (provide (contract-out [element? (-> any/c boolean?)] [element=? (-> element? element? boolean?)] [element-click! (-> element? void?)] [element-clear! (-> element? void?)] [element-type! (-> element? string? void?)] [element-query-selector! (-> element? string? (or/c #f element?))] [element-query-selector-all! (-> element? string? (listof element?))] [element-enabled? (-> element? boolean?)] [element-selected? (-> element? boolean?)] [element-visible? (-> element? boolean?)] [element-handle (-> element? any/c)] [element-tag (-> element? string?)] [element-text (-> element? string?)] [element-rect (-> element? rect?)] [element-attribute (-> element? string? (or/c #f string?))] [element-property (-> element? string? (or/c #f string?))] [call-with-element-screenshot! (-> element? (-> bytes? any) any)])) (struct element (page handle)) (define (element=? element-1 element-2) (and (eq? (element-page element-1) (element-page element-2)) (equal? (element-handle element-1) (element-handle element-2)))) (define (element-marionette e) (page-marionette (element-page e))) (define (element-id e) (for/first ([(_ v) (in-hash (element-handle e))]) v)) (define (element-click! e) (with-page (element-page e) (syncv (marionette-element-click! (element-marionette e) (element-id e))))) (define (element-clear! e) (with-page (element-page e) (syncv (marionette-element-clear! (element-marionette e) (element-id e))))) (define (element-type! e text) (with-page (element-page e) (syncv (marionette-element-send-keys! (element-marionette e) (element-id e) text)))) (define (element-query-selector! e selector) (with-handlers ([exn:fail:marionette:command? (lambda (ex) (cond [(regexp-match? #rx"Unable to locate element" (exn-message ex)) #f] [else (raise ex)]))]) (with-page (element-page e) (sync (handle-evt (marionette-find-element! (element-marionette e) selector (element-id e)) (lambda (r) (element (element-page e) (res-value r)))))))) (define (element-query-selector-all! e selector) (define p (element-page e)) (with-page p (sync (handle-evt (marionette-find-elements! (element-marionette e) selector (element-id e)) (lambda (ids) (for/list ([id (in-list ids)]) (element p id))))))) (define (element-enabled? e) (with-page (element-page e) (sync (handle-evt (marionette-is-element-enabled! (element-marionette e) (element-id e)) res-value)))) (define (element-selected? e) (with-page (element-page e) (sync (handle-evt (marionette-is-element-selected! (element-marionette e) (element-id e)) res-value)))) (define (element-visible? e) (with-page (element-page e) (sync (handle-evt (marionette-is-element-displayed! (element-marionette e) (element-id e)) res-value)))) (define (element-tag e) (with-page (element-page e) (sync (handle-evt (marionette-get-element-tag-name! (element-marionette e) (element-id e)) res-value)))) (define (element-text e) (with-page (element-page e) (sync (handle-evt (marionette-get-element-text! (element-marionette e) (element-id e)) res-value)))) (define (element-rect e) (with-page (element-page e) (sync (handle-evt (marionette-get-element-rect! (element-marionette e) (element-id e)) (match-lambda [(hash-table ('x x) ('y y) ('width w) ('height h)) (rect x y w h)]))))) (define (element-attribute e name) (with-page (element-page e) (sync (handle-evt (marionette-get-element-attribute! (element-marionette e) (element-id e) name) (match-lambda [(hash-table ('value (js-null))) #f ] [(hash-table ('value value )) value]))))) (define (element-property e name) (with-page (element-page e) (sync (handle-evt (marionette-get-element-property! (element-marionette e) (element-id e) name) (match-lambda [(hash-table ('value (js-null))) #f] [(hash-table ('value value )) value]))))) (define (call-with-element-screenshot! e proc) (with-page (element-page e) (proc (sync (handle-evt (marionette-take-screenshot! (element-marionette e) #f (element-id e)) res-value/decode))))) ;; common ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define syncv (compose1 void sync)) (define (res-value r) (hash-ref r 'value)) (define res-value/decode (compose1 base64-decode string->bytes/utf-8 res-value))
null
https://raw.githubusercontent.com/Bogdanp/marionette/dad793f0cda19801316ef2ff4d70b7f6af466036/marionette-lib/page.rkt
racket
page ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; element ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; common ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
#lang racket/base (require json net/base64 net/url racket/contract racket/match racket/string "private/browser.rkt" "private/json.rkt" "private/marionette.rkt" "private/template.rkt" "rect.rkt") (provide cookie/c exn:fail:marionette:page? exn:fail:marionette:page:script? exn:fail:marionette:page:script-cause (contract-out [make-page (-> browser? string? page?)] [page? (-> any/c boolean?)] [page=? (-> page? page? boolean?)] [page-id (-> page? string?)] [page-close! (-> page? void?)] [page-refresh! (-> page? void?)] [page-goto! (-> page? (or/c url? string?) void?)] [page-go-back! (-> page? void?)] [page-go-forward! (-> page? void?)] [page-execute! (-> page? string? jsexpr? ... any/c)] [page-execute-async! (-> page? string? jsexpr? ... any/c)] [page-wait-for! (->* (page? string?) (#:timeout (and/c real? (not/c negative?)) #:visible? boolean?) (or/c #f element?))] [page-query-selector! (-> page? string? (or/c #f element?))] [page-query-selector-all! (-> page? string? (listof element?))] [page-interactive? (-> page? boolean?)] [page-loaded? (-> page? boolean?)] [page-title (-> page? string?)] [page-url (-> page? url?)] [page-content (-> page? string?)] [set-page-content! (-> page? string? void?)] [page-cookies (-> page? (listof cookie/c))] [page-add-cookie! (-> page? cookie/c void?)] [page-delete-all-cookies! (-> page? void?)] [page-delete-cookie! (-> page? string? void?)] [page-alert-text (-> page? string?)] [page-alert-accept! (-> page? void?)] [page-alert-dismiss! (-> page? void?)] [page-alert-type! (-> page? string? void?)] [call-with-page-pdf! (-> page? (-> bytes? any) any)] [call-with-page-screenshot! (->* (page? (-> bytes? any)) (#:full? boolean?) any)])) (struct exn:fail:marionette:page exn:fail:marionette ()) (struct exn:fail:marionette:page:script exn:fail:marionette:page (cause)) (struct page (browser id)) (define (make-page b id) (page b id)) (define (page=? page-1 page-2) (and (eq? (page-browser page-1) (page-browser page-2)) (equal? (page-id page-1) (page-id page-2)))) (define (page-marionette p) (browser-marionette (page-browser p))) (define (page-focused? p) (browser-current-page=? (page-browser p) p)) (define (call-with-page p proc) (dynamic-wind (λ () (unless (page-focused? p) (sync/enable-break (marionette-switch-to-window! (page-marionette p) (page-id p))) (set-browser-current-page! (page-browser p) p))) (λ () (proc)) (λ () (void)))) (define-syntax-rule (with-page p e0 e ...) (call-with-page p (λ () e0 e ...))) (define (page-close! p) (with-page p (syncv (marionette-close-window! (page-marionette p))))) (define (page-refresh! p) (with-page p (syncv (marionette-refresh! (page-marionette p))))) (define (page-goto! p u) (with-page p (syncv (marionette-navigate! (page-marionette p) (if (url? u) (url->string u) u))))) (define (page-go-back! p) (with-page p (syncv (marionette-back! (page-marionette p))))) (define (page-go-forward! p) (with-page p (syncv (marionette-forward! (page-marionette p))))) (define (page-execute! p s . args) (with-page p (sync (handle-evt (marionette-execute-script! (page-marionette p) s args) res-value)))) (define (wrap-async-script body) (template "support/wrap-async-script.js")) (define (page-execute-async! p s . args) (with-page p (sync (handle-evt (marionette-execute-async-script! (page-marionette p) (wrap-async-script s) args) (λ (res) (match (hash-ref res 'value) [(hash-table ('error (js-null)) ('value value )) value] [(hash-table ('error err)) (raise (exn:fail:marionette:page:script (format "async script execution failed: ~a" err) (current-continuation-marks) err))] [(js-null) (raise (exn:fail:marionette:page:script "async script execution aborted" (current-continuation-marks) #f))])))))) (define (page-title p) (with-page p (sync (handle-evt (marionette-get-title! (page-marionette p)) res-value)))) (define (page-url p) (with-page p (sync (handle-evt (marionette-get-current-url! (page-marionette p)) (compose1 string->url res-value))))) (define (page-content p) (with-page p (sync (handle-evt (marionette-get-page-source! (page-marionette p)) res-value)))) (define (set-page-content! p c) (void (page-execute! p "document.documentElement.innerHTML = arguments[0]" c))) (define (page-readystate p) (page-execute! p "return document.readyState")) (define (page-interactive? p) (and (member (page-readystate p) '("interactive" "complete")) #t)) (define (page-loaded? p) (and (member (page-readystate p) '("complete")) #t)) (define cookie/c jsexpr?) (define (page-cookies p) (with-page p (sync (marionette-get-cookies! (page-marionette p))))) (define (page-add-cookie! p c) (with-page p (syncv (marionette-add-cookie! (page-marionette p) c)))) (define (page-delete-all-cookies! p) (with-page p (syncv (marionette-delete-all-cookies! (page-marionette p))))) (define (page-delete-cookie! p name) (with-page p (syncv (marionette-delete-cookie! (page-marionette p) name)))) (define wait-for-element-script (template "support/wait-for-element.js")) (define (page-wait-for! p selector #:timeout [timeout 30] #:visible? [visible? #t]) (define res-ch (make-channel)) (thread (λ () (let loop () (define handle (with-handlers ([exn:fail:marionette? (λ (e) (cond [(or (string-contains? (exn-message e) "unloaded") (string-contains? (exn-message e) "async script execution failed") (string-contains? (exn-message e) "async script execution aborted") (string-contains? (exn-message e) "context has been discarded")) (loop)] [else e]))]) (with-page p (page-execute-async! p wait-for-element-script selector (* timeout 1000) visible?)))) (if (exn:fail? handle) (channel-put res-ch handle) (channel-put res-ch (and handle (with-page p (page-query-selector! p selector)))))))) (sync/timeout timeout (handle-evt res-ch (λ (res) (begin0 res (when (exn:fail? res) (raise res))))))) (define (page-query-selector! p selector) (with-handlers ([exn:fail:marionette:command? (λ (e) (cond [(string-contains? (exn-message e) "Unable to locate element") #f] [else (raise e)]))]) (with-page p (sync (handle-evt (marionette-find-element! (page-marionette p) selector) (λ (r) (element p (res-value r)))))))) (define (page-query-selector-all! p selector) (with-page p (sync (handle-evt (marionette-find-elements! (page-marionette p) selector) (λ (ids) (for/list ([id (in-list ids)]) (element p id))))))) (define (page-alert-text p) (sync (handle-evt (marionette-get-alert-text! (page-marionette p)) res-value))) (define (page-alert-accept! p) (with-page p (syncv (marionette-accept-alert! (page-marionette p))))) (define (page-alert-dismiss! p) (with-page p (syncv (marionette-dismiss-alert! (page-marionette p))))) (define (page-alert-type! p text) (syncv (marionette-send-alert-text! (page-marionette p) text))) (define (call-with-page-pdf! p proc) (with-page p (proc (sync (handle-evt (marionette-print! (page-marionette p)) res-value/decode))))) (define (call-with-page-screenshot! p proc #:full? [full? #t]) (with-page p (proc (sync (handle-evt (marionette-take-screenshot! (page-marionette p) full?) res-value/decode))))) (provide (contract-out [element? (-> any/c boolean?)] [element=? (-> element? element? boolean?)] [element-click! (-> element? void?)] [element-clear! (-> element? void?)] [element-type! (-> element? string? void?)] [element-query-selector! (-> element? string? (or/c #f element?))] [element-query-selector-all! (-> element? string? (listof element?))] [element-enabled? (-> element? boolean?)] [element-selected? (-> element? boolean?)] [element-visible? (-> element? boolean?)] [element-handle (-> element? any/c)] [element-tag (-> element? string?)] [element-text (-> element? string?)] [element-rect (-> element? rect?)] [element-attribute (-> element? string? (or/c #f string?))] [element-property (-> element? string? (or/c #f string?))] [call-with-element-screenshot! (-> element? (-> bytes? any) any)])) (struct element (page handle)) (define (element=? element-1 element-2) (and (eq? (element-page element-1) (element-page element-2)) (equal? (element-handle element-1) (element-handle element-2)))) (define (element-marionette e) (page-marionette (element-page e))) (define (element-id e) (for/first ([(_ v) (in-hash (element-handle e))]) v)) (define (element-click! e) (with-page (element-page e) (syncv (marionette-element-click! (element-marionette e) (element-id e))))) (define (element-clear! e) (with-page (element-page e) (syncv (marionette-element-clear! (element-marionette e) (element-id e))))) (define (element-type! e text) (with-page (element-page e) (syncv (marionette-element-send-keys! (element-marionette e) (element-id e) text)))) (define (element-query-selector! e selector) (with-handlers ([exn:fail:marionette:command? (lambda (ex) (cond [(regexp-match? #rx"Unable to locate element" (exn-message ex)) #f] [else (raise ex)]))]) (with-page (element-page e) (sync (handle-evt (marionette-find-element! (element-marionette e) selector (element-id e)) (lambda (r) (element (element-page e) (res-value r)))))))) (define (element-query-selector-all! e selector) (define p (element-page e)) (with-page p (sync (handle-evt (marionette-find-elements! (element-marionette e) selector (element-id e)) (lambda (ids) (for/list ([id (in-list ids)]) (element p id))))))) (define (element-enabled? e) (with-page (element-page e) (sync (handle-evt (marionette-is-element-enabled! (element-marionette e) (element-id e)) res-value)))) (define (element-selected? e) (with-page (element-page e) (sync (handle-evt (marionette-is-element-selected! (element-marionette e) (element-id e)) res-value)))) (define (element-visible? e) (with-page (element-page e) (sync (handle-evt (marionette-is-element-displayed! (element-marionette e) (element-id e)) res-value)))) (define (element-tag e) (with-page (element-page e) (sync (handle-evt (marionette-get-element-tag-name! (element-marionette e) (element-id e)) res-value)))) (define (element-text e) (with-page (element-page e) (sync (handle-evt (marionette-get-element-text! (element-marionette e) (element-id e)) res-value)))) (define (element-rect e) (with-page (element-page e) (sync (handle-evt (marionette-get-element-rect! (element-marionette e) (element-id e)) (match-lambda [(hash-table ('x x) ('y y) ('width w) ('height h)) (rect x y w h)]))))) (define (element-attribute e name) (with-page (element-page e) (sync (handle-evt (marionette-get-element-attribute! (element-marionette e) (element-id e) name) (match-lambda [(hash-table ('value (js-null))) #f ] [(hash-table ('value value )) value]))))) (define (element-property e name) (with-page (element-page e) (sync (handle-evt (marionette-get-element-property! (element-marionette e) (element-id e) name) (match-lambda [(hash-table ('value (js-null))) #f] [(hash-table ('value value )) value]))))) (define (call-with-element-screenshot! e proc) (with-page (element-page e) (proc (sync (handle-evt (marionette-take-screenshot! (element-marionette e) #f (element-id e)) res-value/decode))))) (define syncv (compose1 void sync)) (define (res-value r) (hash-ref r 'value)) (define res-value/decode (compose1 base64-decode string->bytes/utf-8 res-value))
68e547df6a49265cf589661eb9c43b53810279a9e60d7924ac8c216b29486c91
reborg/clojure-essential-reference
5.clj
< 1 > (into (subvec v 0 idx) (subvec v (inc idx) (count v)))) < 2 > ;; [0 1 2 4 5]
null
https://raw.githubusercontent.com/reborg/clojure-essential-reference/c37fa19d45dd52b2995a191e3e96f0ebdc3f6d69/Vectors/subvec/5.clj
clojure
[0 1 2 4 5]
< 1 > (into (subvec v 0 idx) (subvec v (inc idx) (count v)))) < 2 >
e5b6c9a13788b6737a1567563b612c3682ad12ccab00934a84f78988d9f652d0
ocaml-sf/learn-ocaml-corpus
test.ml
open Report open Test_lib let sampler () = Random.int 10000 let () = set_result @@ ast_sanity_check code_ast @@ fun () -> [ Section ([ Text "Exercise 1:" ; Code "multiple_of" ], test_function_2_against_solution [%ty: int -> int -> bool] "multiple_of" [ 4, 2 ; 8,3 ; 13, 2 ; 12, 4 ]) ; Section ([ Text "Exercise 2:" ; Code "integer_square_root" ], test_function_1_against_solution ~sampler [%ty: int -> int] "integer_square_root" [ 2 ; 16 ; 144 ; 89 ]) ]
null
https://raw.githubusercontent.com/ocaml-sf/learn-ocaml-corpus/7dcf4d72b49863a3e37e41b3c3097aa4c6101a69/exercises/mooc/week1/seq4/ex1/test.ml
ocaml
open Report open Test_lib let sampler () = Random.int 10000 let () = set_result @@ ast_sanity_check code_ast @@ fun () -> [ Section ([ Text "Exercise 1:" ; Code "multiple_of" ], test_function_2_against_solution [%ty: int -> int -> bool] "multiple_of" [ 4, 2 ; 8,3 ; 13, 2 ; 12, 4 ]) ; Section ([ Text "Exercise 2:" ; Code "integer_square_root" ], test_function_1_against_solution ~sampler [%ty: int -> int] "integer_square_root" [ 2 ; 16 ; 144 ; 89 ]) ]
329b211ca5675aa0daf0fc53060ccc74e6245beda7e16f31cde912cb05df3204
robert-dodier/maxima-jupyter
kernel.lisp
(in-package #:maxima-jupyter) (defparameter +status-complete+ "complete") (defparameter +status-incomplete+ "incomplete") (defparameter +status-invalid+ "invalid") (defparameter +status-unknown+ "unknown") (defvar *page-output* nil) (defvar +abort-report+ "Exit debugger and halt cell execution.") (defparameter overrides (make-hash-table)) (define-condition maxima-syntax-error (error) ((message :initarg :message :reader maxima-syntax-error-message)) (:documentation "Maxima syntax error.") (:report (lambda (condition stream) (write-string (maxima-syntax-error-message condition) stream)))) (defclass kernel (common-lisp-jupyter:kernel) ((in-maxima :initform t :accessor kernel-in-maxima)) (:default-initargs :name "maxima-jupyter" :package (find-package :maxima) :version "0.7" :banner "maxima-jupyter: a Maxima Jupyter kernel; (C) 2019-2021 Robert Dodier (BSD)" :language-name "maxima" :debugger t :language-version maxima::*autoconf-version* :mime-type *maxima-mime-type* :file-extension ".mac" :pygments-lexer "maxima" :codemirror-mode "maxima" :help-links '(("Maxima Reference Manual" . "") ("Maxima Documentation" . "")))) (defmethod jupyter::start :before ((k kernel)) (setq maxima::$linenum 0) (setq maxima::*display-labels-p* t)) ;; This is the entry point for a saved lisp image created by ;; trivial-dump-core:save-executable or equivalent. (defun kernel-start-exec () IS THERE OTHER STUFF HANDLED BY MAXIMA INIT - CL.LISP THAT WE NEED TO DUPLICATE HERE ? ? (setq *read-default-float-format* 'double-float) (jupyter:run-kernel 'kernel (car (uiop:command-line-arguments)))) (defun my-mread (input) (let ((maxima::*mread-prompt* "") (maxima::*prompt-on-read-hang*)) (declare (special maxima::*mread-prompt* maxima::*prompt-on-read-hang*)) (or (maxima::mread input) :eof))) (defun my-lread (input) (read input nil :eof)) (defun apply-overrides () (iter (for (fun-name handler) in-hashtable overrides) (when (fboundp fun-name) (eval `(setf (fdefinition (quote ,fun-name)) (lambda (&rest args) (apply ,handler ,(fdefinition fun-name) args)))) (remhash fun-name overrides)))) (defun my-eval (code) (apply-overrides) (setq maxima::$__ (third code)) (let ((result (maxima::meval* code))) (setq maxima::$_ maxima::$__) result)) (defmethod jupyter:evaluate-form ((kernel kernel) stream source-path breakpoints &optional line column) (cond ((kernel-in-maxima kernel) (when (and source-path line) (dolist (instream maxima::*stream-alist*) (when (equal (maxima::instream-stream-name instream) (namestring source-path)) (setf (maxima::instream-line instream) (1- line))))) (let ((form (my-mread stream))) (unless (eq form :eof) (let ((in-label (maxima::makelabel maxima::$inchar)) (out-label (maxima::makelabel maxima::$outchar))) (jupyter:inform :info kernel "Parsed expression to evaluate: ~W~%" form) (incf maxima::$linenum) (setf maxima::*step-next* nil maxima::*break-step* nil) (unless maxima::$nolabels (setf (symbol-value in-label) (third form))) (let ((result (my-eval form))) (jupyter:inform :info kernel "Evaluated result: ~W~%" result) (unless (keyword-result-p result) (setq maxima::$% (caddr result))) (when (displayinput-result-p result) (let ((value `((maxima::mlabel) ,out-label ,(third result)))) (unless maxima::$nolabels (setf (symbol-value out-label) (third result))) (jupyter:execute-result (jupyter:make-mime-bundle (list :object-plist *plain-text-mime-type* (mexpr-to-text value) *latex-mime-type* (mexpr-to-latex value) *maxima-mime-type* (mexpr-to-maxima value)))))))) t))) (t (call-next-method)))) (defmethod jupyter:evaluate-code :around ((k kernel) code &optional source-path breakpoints) (multiple-value-bind (ename evalue traceback) (catch 'maxima::macsyma-quit (maxima::$debugmode (jupyter:kernel-debugger-started k)) (let ((maxima::$load_pathname (when source-path (namestring source-path))) (maxima::*alt-display1d* #'my-displa) (maxima::*alt-display2d* #'my-displa) (maxima::*prompt-prefix* (jupyter:kernel-prompt-prefix jupyter:*kernel*)) (maxima::*prompt-suffix* (jupyter:kernel-prompt-suffix jupyter:*kernel*)) (maxima::$stdin *query-io*) (maxima::$stderr *error-output*) (maxima::$stdout *standard-output*)) (call-next-method))) (if (equal ename 'maxima::maxima-error) (values "MAXIMA-ERROR" (second maxima::$error) nil) (values ename evalue traceback)))) (defmethod jupyter:debug-continue ((k kernel) environment &optional restart-number) (cond ((not (kernel-in-maxima k)) (call-next-method)) (restart-number (invoke-restart-interactively (elt (jupyter:debug-environment-restarts environment) restart-number))) (t (invoke-restart 'step-continue)))) (defmethod jupyter:debug-next ((k kernel) environment) (if (kernel-in-maxima k) (invoke-restart 'step-next) (call-next-method))) (defmethod jupyter:debug-in ((k kernel) environment) (if (kernel-in-maxima k) (invoke-restart 'step-into) (call-next-method))) (defmethod jupyter:debug-out ((k kernel) environment) (if (kernel-in-maxima k) (error "No step out") (call-next-method))) (defmethod jupyter:debug-evaluate-form ((kernel kernel) environment stream frame context) (if (kernel-in-maxima kernel) (let ((form (my-mread stream))) (unless (eq form :eof) (let ((result (maxima::meval* form))) (when (displayinput-result-p result) (jupyter:display (jupyter:make-mime-bundle (list :object-plist *plain-text-mime-type* (mexpr-to-text (third result)) *latex-mime-type* (mexpr-to-latex (third result)) *maxima-mime-type* (mexpr-to-maxima (third result))))))))) (call-next-method))) (defun state-change-p (expr) (and (listp expr) (or (eq (car expr) 'maxima::$to_lisp) (eq (car expr) 'maxima::to-maxima) (some #'state-change-p expr)))) (defmethod jupyter:code-is-complete ((k kernel) code) (handler-case (iter (with *standard-output* = (make-string-output-stream)) (with *error-output* = (make-string-output-stream)) (with input = (make-string-input-stream code)) (with in-maxima = (kernel-in-maxima k)) (initially (apply-overrides)) (for char = (peek-char nil input nil)) (while char) (for parsed = (if in-maxima (maxima::mread input nil) (my-lread input))) (when (state-change-p parsed) (leave +status-unknown+)) (finally (return +status-complete+))) (end-of-file () +status-incomplete+) #+sbcl (sb-int:simple-reader-error () +status-incomplete+) (simple-condition (err) (if (equal (simple-condition-format-control err) "parser: end of file while scanning expression.") +status-incomplete+ +status-invalid+)) (condition () +status-invalid+) (simple-error () +status-invalid+))) (defun to-lisp () (setf (kernel-in-maxima jupyter:*kernel*) nil) :no-output) (defun to-maxima () (setf (kernel-in-maxima jupyter:*kernel*) t) (values)) (defun my-displa (form) (if (mtext-result-p form) (let ((maxima::*alt-display1d* nil) (maxima::*alt-display2d* nil)) (maxima::displa form)) (jupyter:display form))) (defun symbol-char-p (c) (and (characterp c) (or (alphanumericp c) (member c '(#\_ #\%))))) (defun symbol-string-at-position (value pos) (let ((start-pos (if (and (< pos (length value)) (symbol-char-p (char value pos))) pos (if (zerop pos) 0 (1- pos))))) (if (symbol-char-p (char value start-pos)) (let ((start (1+ (or (position-if-not #'symbol-char-p value :end start-pos :from-end t) -1))) (end (or (position-if-not #'symbol-char-p value :start start-pos) (length value)))) (values (subseq value start end) start end)) (values nil nil nil)))) (defmethod jupyter:complete-code ((k kernel) ms code cursor-pos) (if (kernel-in-maxima k) (jupyter:handling-errors (multiple-value-bind (word start end) (symbol-string-at-position code cursor-pos) (when word (let ((name (concatenate 'string "$" (maxima::maybe-invert-string-case word)))) (with-slots (package) k (iter (for sym in-package package) (for sym-name next (symbol-name sym)) (when (starts-with-subseq name sym-name) (jupyter:match-set-add ms (maxima::print-invert-case (maxima::stripdollar sym-name)) start end :type (if (fboundp sym) "function" "variable")))))))) (values)) (call-next-method))) (defmethod jupyter:inspect-code ((k kernel) code cursor-pos detail-level) (declare (ignore detail-level)) (if (kernel-in-maxima k) (jupyter:handling-errors (multiple-value-bind (word start end) (symbol-string-at-position code cursor-pos) (when word (jupyter:inform :info k "Inspect ~A~%" word) (jupyter:text (string-trim '(#\Newline) (with-output-to-string (*standard-output*) (cl-info::info-exact word))))))) (call-next-method))) (defclass debug-frame (jupyter:debug-frame) ()) (defclass debug-local-scope (jupyter:debug-scope) () (:default-initargs :name "Locals" :presentation-hint "locals")) (defclass debug-globals-scope (jupyter:debug-scope) () (:default-initargs :name "Globals" :presentation-hint "globals")) (defclass debug-variable (jupyter:debug-variable) ()) (defun calculate-debug-frames () (do ((i maxima::*current-frame* (1+ i)) frames) (nil) (multiple-value-bind (fname vals params backtr lineinfo bdlist) (maxima::frame-info i) (declare (ignore vals params backtr bdlist)) (unless fname (return (nreverse frames))) (push (make-instance 'debug-frame :data i :source (make-instance 'jupyter:debug-source :name (maxima::short-name (cadr lineinfo)) :path (cadr lineinfo)) :line (1+ (car lineinfo)) :name (maxima::$sconcat fname)) frames)))) (defmethod jupyter:debug-object-children-resolve ((instance debug-frame)) (list (make-instance 'debug-local-scope :environment (jupyter:debug-object-environment instance) :parent instance))) (defun make-debug-variable (name &optional (value nil value-present-p) (env nil env-present-p)) (let ((var (make-instance 'debug-variable :name (maxima::$sconcat name)))) (when value-present-p (setf (jupyter:debug-object-value var) (maxima::$sconcat value) (jupyter:debug-object-type var) (write-to-string (type-of value)) (jupyter:debug-object-data var) value)) (unless (or (typep value 'standard-object) (typep value 'structure-object)) (setf (jupyter:debug-object-id var) 0)) (when env-present-p (setf (jupyter::debug-object-environment var) env) (jupyter::register-debug-object var)) var)) (defmethod jupyter:debug-object-children-resolve ((instance debug-local-scope)) (multiple-value-bind (fname vals params backtr lineinfo bdlist) (maxima::frame-info (jupyter:debug-object-data (jupyter:debug-object-parent instance))) (declare (ignore fname backtr lineinfo bdlist)) (mapcar #'make-debug-variable params vals))) (defmethod jupyter:debug-inspect-variables ((kernel kernel) environment) (if (kernel-in-maxima kernel) (let (variables) (setf (fill-pointer (jupyter::debug-environment-objects environment)) 1) (dolist (symbol (cdr maxima::$values)) (push (make-debug-variable symbol (symbol-value symbol) environment) variables)) (stable-sort variables #'string< :key (lambda (variable) (write-to-string (jupyter:debug-object-name variable))))) (call-next-method))) (defun activate-breakpoint (index) (unless (first (elt maxima::*break-points* index)) (pop (elt maxima::*break-points* index)))) (defun deactivate-breakpoint (index) (when (first (elt maxima::*break-points* index)) (push nil (elt maxima::*break-points* index)))) (defun breakpoint-match-p (source breakpoint index &aux (bp (elt maxima::*break-points* index)) (path (namestring source)) (line (1- (jupyter:debug-breakpoint-line breakpoint)))) (values (or (and (null (first bp)) (equal path (third bp)) (equal line (fourth bp))) (and (first bp) (equal path (second bp)) (equal line (third bp)))) (and (first bp) t))) (defmethod jupyter:debug-remove-breakpoint ((kernel kernel) source breakpoint) (j:inform :info kernel "dffg") (dotimes (i (length maxima::*break-points*)) (multiple-value-bind (matches active) (breakpoint-match-p source breakpoint i) (when (and matches active) (deactivate-breakpoint i))))) (defun make-breakpoint (path line) (do-symbols (sym "MAXIMA") (let ((info (maxima::set-full-lineinfo sym))) (when (typep info 'vector) (map nil (lambda (form-info) (when (listp form-info) (let ((line-info (maxima::get-lineinfo form-info))) (j:inform :info nil "~a" line-info) (when (and (equal (first line-info) line) (equal (second line-info) path)) (maxima::insert-break-point (maxima::make-bkpt :form form-info :file-line line :file path :function (fourth line-info))))))) info))))) (defmethod jupyter:debug-activate-breakpoints ((kernel kernel) source breakpoints) (declare (ignore kernel)) (dolist (breakpoint breakpoints) (dotimes (i (length maxima::*break-points*) (make-breakpoint (namestring source) (1- (jupyter:debug-breakpoint-line breakpoint)))) (multiple-value-bind (matches active) (breakpoint-match-p source breakpoint i) (when matches (unless active (activate-breakpoint i)) (return))))))
null
https://raw.githubusercontent.com/robert-dodier/maxima-jupyter/0e2ead13b5e4da93f0c35ea6c411df35b246b31b/src/kernel.lisp
lisp
This is the entry point for a saved lisp image created by trivial-dump-core:save-executable or equivalent.
(in-package #:maxima-jupyter) (defparameter +status-complete+ "complete") (defparameter +status-incomplete+ "incomplete") (defparameter +status-invalid+ "invalid") (defparameter +status-unknown+ "unknown") (defvar *page-output* nil) (defvar +abort-report+ "Exit debugger and halt cell execution.") (defparameter overrides (make-hash-table)) (define-condition maxima-syntax-error (error) ((message :initarg :message :reader maxima-syntax-error-message)) (:documentation "Maxima syntax error.") (:report (lambda (condition stream) (write-string (maxima-syntax-error-message condition) stream)))) (defclass kernel (common-lisp-jupyter:kernel) ((in-maxima :initform t :accessor kernel-in-maxima)) (:default-initargs :name "maxima-jupyter" :package (find-package :maxima) :version "0.7" :banner "maxima-jupyter: a Maxima Jupyter kernel; (C) 2019-2021 Robert Dodier (BSD)" :language-name "maxima" :debugger t :language-version maxima::*autoconf-version* :mime-type *maxima-mime-type* :file-extension ".mac" :pygments-lexer "maxima" :codemirror-mode "maxima" :help-links '(("Maxima Reference Manual" . "") ("Maxima Documentation" . "")))) (defmethod jupyter::start :before ((k kernel)) (setq maxima::$linenum 0) (setq maxima::*display-labels-p* t)) (defun kernel-start-exec () IS THERE OTHER STUFF HANDLED BY MAXIMA INIT - CL.LISP THAT WE NEED TO DUPLICATE HERE ? ? (setq *read-default-float-format* 'double-float) (jupyter:run-kernel 'kernel (car (uiop:command-line-arguments)))) (defun my-mread (input) (let ((maxima::*mread-prompt* "") (maxima::*prompt-on-read-hang*)) (declare (special maxima::*mread-prompt* maxima::*prompt-on-read-hang*)) (or (maxima::mread input) :eof))) (defun my-lread (input) (read input nil :eof)) (defun apply-overrides () (iter (for (fun-name handler) in-hashtable overrides) (when (fboundp fun-name) (eval `(setf (fdefinition (quote ,fun-name)) (lambda (&rest args) (apply ,handler ,(fdefinition fun-name) args)))) (remhash fun-name overrides)))) (defun my-eval (code) (apply-overrides) (setq maxima::$__ (third code)) (let ((result (maxima::meval* code))) (setq maxima::$_ maxima::$__) result)) (defmethod jupyter:evaluate-form ((kernel kernel) stream source-path breakpoints &optional line column) (cond ((kernel-in-maxima kernel) (when (and source-path line) (dolist (instream maxima::*stream-alist*) (when (equal (maxima::instream-stream-name instream) (namestring source-path)) (setf (maxima::instream-line instream) (1- line))))) (let ((form (my-mread stream))) (unless (eq form :eof) (let ((in-label (maxima::makelabel maxima::$inchar)) (out-label (maxima::makelabel maxima::$outchar))) (jupyter:inform :info kernel "Parsed expression to evaluate: ~W~%" form) (incf maxima::$linenum) (setf maxima::*step-next* nil maxima::*break-step* nil) (unless maxima::$nolabels (setf (symbol-value in-label) (third form))) (let ((result (my-eval form))) (jupyter:inform :info kernel "Evaluated result: ~W~%" result) (unless (keyword-result-p result) (setq maxima::$% (caddr result))) (when (displayinput-result-p result) (let ((value `((maxima::mlabel) ,out-label ,(third result)))) (unless maxima::$nolabels (setf (symbol-value out-label) (third result))) (jupyter:execute-result (jupyter:make-mime-bundle (list :object-plist *plain-text-mime-type* (mexpr-to-text value) *latex-mime-type* (mexpr-to-latex value) *maxima-mime-type* (mexpr-to-maxima value)))))))) t))) (t (call-next-method)))) (defmethod jupyter:evaluate-code :around ((k kernel) code &optional source-path breakpoints) (multiple-value-bind (ename evalue traceback) (catch 'maxima::macsyma-quit (maxima::$debugmode (jupyter:kernel-debugger-started k)) (let ((maxima::$load_pathname (when source-path (namestring source-path))) (maxima::*alt-display1d* #'my-displa) (maxima::*alt-display2d* #'my-displa) (maxima::*prompt-prefix* (jupyter:kernel-prompt-prefix jupyter:*kernel*)) (maxima::*prompt-suffix* (jupyter:kernel-prompt-suffix jupyter:*kernel*)) (maxima::$stdin *query-io*) (maxima::$stderr *error-output*) (maxima::$stdout *standard-output*)) (call-next-method))) (if (equal ename 'maxima::maxima-error) (values "MAXIMA-ERROR" (second maxima::$error) nil) (values ename evalue traceback)))) (defmethod jupyter:debug-continue ((k kernel) environment &optional restart-number) (cond ((not (kernel-in-maxima k)) (call-next-method)) (restart-number (invoke-restart-interactively (elt (jupyter:debug-environment-restarts environment) restart-number))) (t (invoke-restart 'step-continue)))) (defmethod jupyter:debug-next ((k kernel) environment) (if (kernel-in-maxima k) (invoke-restart 'step-next) (call-next-method))) (defmethod jupyter:debug-in ((k kernel) environment) (if (kernel-in-maxima k) (invoke-restart 'step-into) (call-next-method))) (defmethod jupyter:debug-out ((k kernel) environment) (if (kernel-in-maxima k) (error "No step out") (call-next-method))) (defmethod jupyter:debug-evaluate-form ((kernel kernel) environment stream frame context) (if (kernel-in-maxima kernel) (let ((form (my-mread stream))) (unless (eq form :eof) (let ((result (maxima::meval* form))) (when (displayinput-result-p result) (jupyter:display (jupyter:make-mime-bundle (list :object-plist *plain-text-mime-type* (mexpr-to-text (third result)) *latex-mime-type* (mexpr-to-latex (third result)) *maxima-mime-type* (mexpr-to-maxima (third result))))))))) (call-next-method))) (defun state-change-p (expr) (and (listp expr) (or (eq (car expr) 'maxima::$to_lisp) (eq (car expr) 'maxima::to-maxima) (some #'state-change-p expr)))) (defmethod jupyter:code-is-complete ((k kernel) code) (handler-case (iter (with *standard-output* = (make-string-output-stream)) (with *error-output* = (make-string-output-stream)) (with input = (make-string-input-stream code)) (with in-maxima = (kernel-in-maxima k)) (initially (apply-overrides)) (for char = (peek-char nil input nil)) (while char) (for parsed = (if in-maxima (maxima::mread input nil) (my-lread input))) (when (state-change-p parsed) (leave +status-unknown+)) (finally (return +status-complete+))) (end-of-file () +status-incomplete+) #+sbcl (sb-int:simple-reader-error () +status-incomplete+) (simple-condition (err) (if (equal (simple-condition-format-control err) "parser: end of file while scanning expression.") +status-incomplete+ +status-invalid+)) (condition () +status-invalid+) (simple-error () +status-invalid+))) (defun to-lisp () (setf (kernel-in-maxima jupyter:*kernel*) nil) :no-output) (defun to-maxima () (setf (kernel-in-maxima jupyter:*kernel*) t) (values)) (defun my-displa (form) (if (mtext-result-p form) (let ((maxima::*alt-display1d* nil) (maxima::*alt-display2d* nil)) (maxima::displa form)) (jupyter:display form))) (defun symbol-char-p (c) (and (characterp c) (or (alphanumericp c) (member c '(#\_ #\%))))) (defun symbol-string-at-position (value pos) (let ((start-pos (if (and (< pos (length value)) (symbol-char-p (char value pos))) pos (if (zerop pos) 0 (1- pos))))) (if (symbol-char-p (char value start-pos)) (let ((start (1+ (or (position-if-not #'symbol-char-p value :end start-pos :from-end t) -1))) (end (or (position-if-not #'symbol-char-p value :start start-pos) (length value)))) (values (subseq value start end) start end)) (values nil nil nil)))) (defmethod jupyter:complete-code ((k kernel) ms code cursor-pos) (if (kernel-in-maxima k) (jupyter:handling-errors (multiple-value-bind (word start end) (symbol-string-at-position code cursor-pos) (when word (let ((name (concatenate 'string "$" (maxima::maybe-invert-string-case word)))) (with-slots (package) k (iter (for sym in-package package) (for sym-name next (symbol-name sym)) (when (starts-with-subseq name sym-name) (jupyter:match-set-add ms (maxima::print-invert-case (maxima::stripdollar sym-name)) start end :type (if (fboundp sym) "function" "variable")))))))) (values)) (call-next-method))) (defmethod jupyter:inspect-code ((k kernel) code cursor-pos detail-level) (declare (ignore detail-level)) (if (kernel-in-maxima k) (jupyter:handling-errors (multiple-value-bind (word start end) (symbol-string-at-position code cursor-pos) (when word (jupyter:inform :info k "Inspect ~A~%" word) (jupyter:text (string-trim '(#\Newline) (with-output-to-string (*standard-output*) (cl-info::info-exact word))))))) (call-next-method))) (defclass debug-frame (jupyter:debug-frame) ()) (defclass debug-local-scope (jupyter:debug-scope) () (:default-initargs :name "Locals" :presentation-hint "locals")) (defclass debug-globals-scope (jupyter:debug-scope) () (:default-initargs :name "Globals" :presentation-hint "globals")) (defclass debug-variable (jupyter:debug-variable) ()) (defun calculate-debug-frames () (do ((i maxima::*current-frame* (1+ i)) frames) (nil) (multiple-value-bind (fname vals params backtr lineinfo bdlist) (maxima::frame-info i) (declare (ignore vals params backtr bdlist)) (unless fname (return (nreverse frames))) (push (make-instance 'debug-frame :data i :source (make-instance 'jupyter:debug-source :name (maxima::short-name (cadr lineinfo)) :path (cadr lineinfo)) :line (1+ (car lineinfo)) :name (maxima::$sconcat fname)) frames)))) (defmethod jupyter:debug-object-children-resolve ((instance debug-frame)) (list (make-instance 'debug-local-scope :environment (jupyter:debug-object-environment instance) :parent instance))) (defun make-debug-variable (name &optional (value nil value-present-p) (env nil env-present-p)) (let ((var (make-instance 'debug-variable :name (maxima::$sconcat name)))) (when value-present-p (setf (jupyter:debug-object-value var) (maxima::$sconcat value) (jupyter:debug-object-type var) (write-to-string (type-of value)) (jupyter:debug-object-data var) value)) (unless (or (typep value 'standard-object) (typep value 'structure-object)) (setf (jupyter:debug-object-id var) 0)) (when env-present-p (setf (jupyter::debug-object-environment var) env) (jupyter::register-debug-object var)) var)) (defmethod jupyter:debug-object-children-resolve ((instance debug-local-scope)) (multiple-value-bind (fname vals params backtr lineinfo bdlist) (maxima::frame-info (jupyter:debug-object-data (jupyter:debug-object-parent instance))) (declare (ignore fname backtr lineinfo bdlist)) (mapcar #'make-debug-variable params vals))) (defmethod jupyter:debug-inspect-variables ((kernel kernel) environment) (if (kernel-in-maxima kernel) (let (variables) (setf (fill-pointer (jupyter::debug-environment-objects environment)) 1) (dolist (symbol (cdr maxima::$values)) (push (make-debug-variable symbol (symbol-value symbol) environment) variables)) (stable-sort variables #'string< :key (lambda (variable) (write-to-string (jupyter:debug-object-name variable))))) (call-next-method))) (defun activate-breakpoint (index) (unless (first (elt maxima::*break-points* index)) (pop (elt maxima::*break-points* index)))) (defun deactivate-breakpoint (index) (when (first (elt maxima::*break-points* index)) (push nil (elt maxima::*break-points* index)))) (defun breakpoint-match-p (source breakpoint index &aux (bp (elt maxima::*break-points* index)) (path (namestring source)) (line (1- (jupyter:debug-breakpoint-line breakpoint)))) (values (or (and (null (first bp)) (equal path (third bp)) (equal line (fourth bp))) (and (first bp) (equal path (second bp)) (equal line (third bp)))) (and (first bp) t))) (defmethod jupyter:debug-remove-breakpoint ((kernel kernel) source breakpoint) (j:inform :info kernel "dffg") (dotimes (i (length maxima::*break-points*)) (multiple-value-bind (matches active) (breakpoint-match-p source breakpoint i) (when (and matches active) (deactivate-breakpoint i))))) (defun make-breakpoint (path line) (do-symbols (sym "MAXIMA") (let ((info (maxima::set-full-lineinfo sym))) (when (typep info 'vector) (map nil (lambda (form-info) (when (listp form-info) (let ((line-info (maxima::get-lineinfo form-info))) (j:inform :info nil "~a" line-info) (when (and (equal (first line-info) line) (equal (second line-info) path)) (maxima::insert-break-point (maxima::make-bkpt :form form-info :file-line line :file path :function (fourth line-info))))))) info))))) (defmethod jupyter:debug-activate-breakpoints ((kernel kernel) source breakpoints) (declare (ignore kernel)) (dolist (breakpoint breakpoints) (dotimes (i (length maxima::*break-points*) (make-breakpoint (namestring source) (1- (jupyter:debug-breakpoint-line breakpoint)))) (multiple-value-bind (matches active) (breakpoint-match-p source breakpoint i) (when matches (unless active (activate-breakpoint i)) (return))))))
1c27519790b79a79c6bdbc9cf984eaee2c39dbc6c9f907ae6f71e032c19d4f02
imitator-model-checker/imitator
Input.mli
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * IMITATOR * * Laboratoire Spécification et Vérification ( ENS Cachan & CNRS , France ) * Université Paris 13 , LIPN , CNRS , France * Université de Lorraine , CNRS , , LORIA , Nancy , France * * Module description : Global input elements ( model , property ) * * File contributors : * Created : 2012/06/15 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * IMITATOR * * Laboratoire Spécification et Vérification (ENS Cachan & CNRS, France) * Université Paris 13, LIPN, CNRS, France * Université de Lorraine, CNRS, Inria, LORIA, Nancy, France * * Module description: Global input elements (model, property) * * File contributors : Étienne André * Created : 2012/06/15 * ************************************************************) open Options val set_model: AbstractModel.abstract_model -> unit val get_model: unit -> AbstractModel.abstract_model val set_property: AbstractProperty.abstract_property -> unit val has_property: unit -> bool val get_property: unit -> AbstractProperty.abstract_property val get_options: unit -> imitator_options val set_options: imitator_options -> unit
null
https://raw.githubusercontent.com/imitator-model-checker/imitator/105408ae2bd8c3e3291f286e4d127defd492a58b/src/Input.mli
ocaml
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * IMITATOR * * Laboratoire Spécification et Vérification ( ENS Cachan & CNRS , France ) * Université Paris 13 , LIPN , CNRS , France * Université de Lorraine , CNRS , , LORIA , Nancy , France * * Module description : Global input elements ( model , property ) * * File contributors : * Created : 2012/06/15 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * IMITATOR * * Laboratoire Spécification et Vérification (ENS Cachan & CNRS, France) * Université Paris 13, LIPN, CNRS, France * Université de Lorraine, CNRS, Inria, LORIA, Nancy, France * * Module description: Global input elements (model, property) * * File contributors : Étienne André * Created : 2012/06/15 * ************************************************************) open Options val set_model: AbstractModel.abstract_model -> unit val get_model: unit -> AbstractModel.abstract_model val set_property: AbstractProperty.abstract_property -> unit val has_property: unit -> bool val get_property: unit -> AbstractProperty.abstract_property val get_options: unit -> imitator_options val set_options: imitator_options -> unit
a04dbc35bfa116c7048de1ad1019a3ccab425f19f06024855da603b2a787f184
Factual/skuld
admin.clj
(ns skuld.admin "Administrative cluster-management tasks." (:require [clj-helix.admin :as helix] [skuld.node :as node])) (defn admin "Create an administrator tool. Options: :cluster the name of the skuld cluster (default \"skuld\") :zookeeper a zookeeper connect string (\"localhost:2181\") :partitions number of partitions to shard into (1) :replicas number of replicas to maintain (3) :max-partitions-per-node (:partitions)" [opts] {:helix (helix/helix-admin (get opts :zookeeper "localhost:2181")) :cluster (get opts :cluster "skuld") :partitions (get opts :partitions 1) :replicas (get opts :replicas 3) :max-partitions-per-node (get opts :max-partitions-per-node (get opts :partitions 1))}) (defn shutdown! "Shuts down an admin tool." [admin] (.close (:helix admin))) (defn destroy-cluster! [admin] (helix/drop-cluster (:helix admin) (:cluster admin))) (defn create-cluster! [admin] ; Create cluster itself (helix/add-cluster (:helix admin) (:cluster admin)) Set FSM (helix/add-fsm-definition (:helix admin) (:cluster admin) node/fsm-def) ; Create resource (helix/add-resource (:helix admin) (:cluster admin) {:resource :skuld :partitions (:partitions admin) :max-partitions-per-node (:max-partitions-per-node admin) :replicas (:replicas admin) :state-model (:name node/fsm-def)})) (defn add-node! "Adds an node to the cluster." [admin node] (helix/add-instance (:helix admin) (:cluster admin) (select-keys node [:host :port])))
null
https://raw.githubusercontent.com/Factual/skuld/79599f9b13aee35c680183d6bf9e2fcbfde1d7c7/src/skuld/admin.clj
clojure
Create cluster itself Create resource
(ns skuld.admin "Administrative cluster-management tasks." (:require [clj-helix.admin :as helix] [skuld.node :as node])) (defn admin "Create an administrator tool. Options: :cluster the name of the skuld cluster (default \"skuld\") :zookeeper a zookeeper connect string (\"localhost:2181\") :partitions number of partitions to shard into (1) :replicas number of replicas to maintain (3) :max-partitions-per-node (:partitions)" [opts] {:helix (helix/helix-admin (get opts :zookeeper "localhost:2181")) :cluster (get opts :cluster "skuld") :partitions (get opts :partitions 1) :replicas (get opts :replicas 3) :max-partitions-per-node (get opts :max-partitions-per-node (get opts :partitions 1))}) (defn shutdown! "Shuts down an admin tool." [admin] (.close (:helix admin))) (defn destroy-cluster! [admin] (helix/drop-cluster (:helix admin) (:cluster admin))) (defn create-cluster! [admin] (helix/add-cluster (:helix admin) (:cluster admin)) Set FSM (helix/add-fsm-definition (:helix admin) (:cluster admin) node/fsm-def) (helix/add-resource (:helix admin) (:cluster admin) {:resource :skuld :partitions (:partitions admin) :max-partitions-per-node (:max-partitions-per-node admin) :replicas (:replicas admin) :state-model (:name node/fsm-def)})) (defn add-node! "Adds an node to the cluster." [admin node] (helix/add-instance (:helix admin) (:cluster admin) (select-keys node [:host :port])))
b89f63ee7e69236d98daff1fe0393a7d33959b3b7c3fa7ca19c741a36b94649b
lindig/lipsum
weave.mli
(** Weaving is called the process of formatting a literate program as documentation (in contrast to formatting its embedded code for compilation). This module provides formatters for weaving a literate program. *) exception NoSuchFormat of string (** requested format doesn't exist *) type t = out_channel -> Litprog.doc -> unit (* emit doc to channel *) val lookup : string -> t (** lookup named format *) val formats : string list (** names of available formats *)
null
https://raw.githubusercontent.com/lindig/lipsum/c441d7fddb6ecb0f6e306e536e5ed44bc40ccd93/src/weave.mli
ocaml
* Weaving is called the process of formatting a literate program as documentation (in contrast to formatting its embedded code for compilation). This module provides formatters for weaving a literate program. * requested format doesn't exist emit doc to channel * lookup named format * names of available formats
type t = out_channel -> Litprog.doc -> unit val lookup : string -> t val formats : string list
d346385497530f979c097a29a6e151d53544d3eb2452f24edbffd5c9eb74505e
nomeata/free-theorems-static-webui
NameStores.hs
-- | Provides functions to generate new variable names of different kinds. module Language.Haskell.FreeTheorems.NameStores ( typeNameStore , relationNameStore , typeExpressionNameStore , functionNameStore1 , functionNameStore2 , variableNameStore ) where import Data.List (unfoldr) -- | An infinite list of names for type variables. typeNameStore :: [String] typeNameStore = createNames "abcde" 'a' -- | An infinite list of names for relation variables. relationNameStore :: [String] relationNameStore = createNames "RS" 'R' -- | An infinite list of names for type expressions. typeExpressionNameStore :: [String] typeExpressionNameStore = createNames "" 't' -- | An infinite list of names for function variables. functionNameStore1 :: [String] functionNameStore1 = createNames "fgh" 'f' -- | Another infinite list of names for function variables. functionNameStore2 :: [String] functionNameStore2 = createNames "pqrs" 'p' -- | An infinite list of names for term variables. variableNameStore :: [String] variableNameStore = createNames "xyzvwabcdeijklmn" 'x' -- | Creates an infinite list of names based on a list of simple names and a -- default prefix. After simple names have been used, the numbers starting from 1 are appended to the default prefix to generate more names . createNames :: [Char] -> Char -> [String] createNames prefixes prefix = let unpack is = case is of { (c:cs) -> Just ([c], cs) ; otherwise -> Nothing } in unfoldr unpack prefixes ++ (map (\i -> prefix : show i) [1..])
null
https://raw.githubusercontent.com/nomeata/free-theorems-static-webui/44149706c2b809734ab3848047e314359bc59ccb/free-theorems/src/Language/Haskell/FreeTheorems/NameStores.hs
haskell
| Provides functions to generate new variable names of different kinds. | An infinite list of names for type variables. | An infinite list of names for relation variables. | An infinite list of names for type expressions. | An infinite list of names for function variables. | Another infinite list of names for function variables. | An infinite list of names for term variables. | Creates an infinite list of names based on a list of simple names and a default prefix. After simple names have been used, the numbers starting
module Language.Haskell.FreeTheorems.NameStores ( typeNameStore , relationNameStore , typeExpressionNameStore , functionNameStore1 , functionNameStore2 , variableNameStore ) where import Data.List (unfoldr) typeNameStore :: [String] typeNameStore = createNames "abcde" 'a' relationNameStore :: [String] relationNameStore = createNames "RS" 'R' typeExpressionNameStore :: [String] typeExpressionNameStore = createNames "" 't' functionNameStore1 :: [String] functionNameStore1 = createNames "fgh" 'f' functionNameStore2 :: [String] functionNameStore2 = createNames "pqrs" 'p' variableNameStore :: [String] variableNameStore = createNames "xyzvwabcdeijklmn" 'x' from 1 are appended to the default prefix to generate more names . createNames :: [Char] -> Char -> [String] createNames prefixes prefix = let unpack is = case is of { (c:cs) -> Just ([c], cs) ; otherwise -> Nothing } in unfoldr unpack prefixes ++ (map (\i -> prefix : show i) [1..])
b07aacdc4ca42a73bc45bdb97999dc273bf522838b6d1e81731f113394441091
mirage/bechamel
select.ml
let invalid_arg fmt = Format.ksprintf (fun s -> invalid_arg s) fmt let load_file filename = let ic = open_in filename in let ln = in_channel_length ic in let rs = Bytes.create ln in let () = really_input ic rs 0 ln in Bytes.unsafe_to_string rs let sexp_linux = "(-lrt)" let sexp_empty = "()" let () = let system, output = match Sys.argv with | [| _; "--system"; system; "-o"; output |] -> let system = match system with | "linux" | "linux_eabihf" | "linux_elf" | "elf" -> `Linux | "freebsd" -> `FreeBSD | "windows" | "mingw64" | "cygwin" -> `Windows | "macosx" -> `MacOSX | v -> invalid_arg "Invalid argument of system option: %s" v in (system, output) | _ -> invalid_arg "Expected `%s --system <system> -o <output>' got `%s'" Sys.argv.(0) (String.concat " " (Array.to_list Sys.argv)) in let oc_ml, oc_c, oc_sexp = ( open_out (output ^ ".ml") , open_out (output ^ "_stubs.c") , open_out (output ^ ".sexp") ) in let ml, c = match system with | `Linux | `FreeBSD -> (load_file "clock_linux.ml", load_file "clock_linux_stubs.c") | `Windows -> (load_file "clock_windows.ml", load_file "clock_windows_stubs.c") | `MacOSX -> (load_file "clock_mach.ml", load_file "clock_mach_stubs.c") in let sexp = if system = `Linux then sexp_linux else sexp_empty in Printf.fprintf oc_ml "%s%!" ml; Printf.fprintf oc_c "%s%!" c; Printf.fprintf oc_sexp "%s%!" sexp; close_out oc_ml; close_out oc_c; close_out oc_sexp
null
https://raw.githubusercontent.com/mirage/bechamel/8e1a3e64c6723d1d9b2081aeb06d725024f88012/lib/monotonic_clock/select/select.ml
ocaml
let invalid_arg fmt = Format.ksprintf (fun s -> invalid_arg s) fmt let load_file filename = let ic = open_in filename in let ln = in_channel_length ic in let rs = Bytes.create ln in let () = really_input ic rs 0 ln in Bytes.unsafe_to_string rs let sexp_linux = "(-lrt)" let sexp_empty = "()" let () = let system, output = match Sys.argv with | [| _; "--system"; system; "-o"; output |] -> let system = match system with | "linux" | "linux_eabihf" | "linux_elf" | "elf" -> `Linux | "freebsd" -> `FreeBSD | "windows" | "mingw64" | "cygwin" -> `Windows | "macosx" -> `MacOSX | v -> invalid_arg "Invalid argument of system option: %s" v in (system, output) | _ -> invalid_arg "Expected `%s --system <system> -o <output>' got `%s'" Sys.argv.(0) (String.concat " " (Array.to_list Sys.argv)) in let oc_ml, oc_c, oc_sexp = ( open_out (output ^ ".ml") , open_out (output ^ "_stubs.c") , open_out (output ^ ".sexp") ) in let ml, c = match system with | `Linux | `FreeBSD -> (load_file "clock_linux.ml", load_file "clock_linux_stubs.c") | `Windows -> (load_file "clock_windows.ml", load_file "clock_windows_stubs.c") | `MacOSX -> (load_file "clock_mach.ml", load_file "clock_mach_stubs.c") in let sexp = if system = `Linux then sexp_linux else sexp_empty in Printf.fprintf oc_ml "%s%!" ml; Printf.fprintf oc_c "%s%!" c; Printf.fprintf oc_sexp "%s%!" sexp; close_out oc_ml; close_out oc_c; close_out oc_sexp
da70107e1578d00b30cace532c4a3e0d39d306e95d2dfe33fb63d47d6860c1b7
hexlet-codebattle/battle_asserts
core_test.clj
(ns battle-asserts.core-test (:require [test-helper :as h] [clojure.string :as s] [clojure.test :refer [deftest]] [clojure.java.io :as io] [clojure.tools.namespace.find :as nsf])) (defn test-issue [issue-ns-name] (require [issue-ns-name]) (let [issue-name (s/replace (last (s/split (str issue-ns-name) #"\.")) #"-" "_") build-generator (ns-resolve issue-ns-name 'arguments-generator) solution (ns-resolve issue-ns-name 'solution) difficulty @(ns-resolve issue-ns-name 'level) disabled (ns-resolve issue-ns-name 'disabled) signature (ns-resolve issue-ns-name 'signature) description @(ns-resolve issue-ns-name 'description) samples @(ns-resolve issue-ns-name 'test-data)] (when-not disabled (h/run-test-data-spec-test samples signature issue-name) (h/run-description-test description issue-name) (h/run-difficulty-test difficulty issue-name) (when-not (nil? solution) (h/run-solution-test samples solution issue-name)) (when-not (nil? build-generator) (h/run-generator-spec-test build-generator signature issue-name)) (when-not (and (nil? build-generator) (nil? solution)) (h/run-solution-spec-test build-generator signature solution issue-name))))) (deftest core-test (let [namespaces (-> "src/battle_asserts/issues" io/as-file nsf/find-namespaces-in-dir)] (doseq [namespace namespaces] (test-issue namespace))))
null
https://raw.githubusercontent.com/hexlet-codebattle/battle_asserts/db9a3666c994c2a1fdbc013c69060ff512a8335d/test/battle_asserts/core_test.clj
clojure
(ns battle-asserts.core-test (:require [test-helper :as h] [clojure.string :as s] [clojure.test :refer [deftest]] [clojure.java.io :as io] [clojure.tools.namespace.find :as nsf])) (defn test-issue [issue-ns-name] (require [issue-ns-name]) (let [issue-name (s/replace (last (s/split (str issue-ns-name) #"\.")) #"-" "_") build-generator (ns-resolve issue-ns-name 'arguments-generator) solution (ns-resolve issue-ns-name 'solution) difficulty @(ns-resolve issue-ns-name 'level) disabled (ns-resolve issue-ns-name 'disabled) signature (ns-resolve issue-ns-name 'signature) description @(ns-resolve issue-ns-name 'description) samples @(ns-resolve issue-ns-name 'test-data)] (when-not disabled (h/run-test-data-spec-test samples signature issue-name) (h/run-description-test description issue-name) (h/run-difficulty-test difficulty issue-name) (when-not (nil? solution) (h/run-solution-test samples solution issue-name)) (when-not (nil? build-generator) (h/run-generator-spec-test build-generator signature issue-name)) (when-not (and (nil? build-generator) (nil? solution)) (h/run-solution-spec-test build-generator signature solution issue-name))))) (deftest core-test (let [namespaces (-> "src/battle_asserts/issues" io/as-file nsf/find-namespaces-in-dir)] (doseq [namespace namespaces] (test-issue namespace))))
def292b43e51746eda7a485a8542f0d6786cf8bc2b9eba2488036b0e06fe82f1
troy-west/kstream-examples
serdes.clj
(ns troy-west.serdes (:require [cognitect.transit :as transit]) (:import (org.apache.kafka.common.serialization Deserializer Serializer Serde) (java.io ByteArrayInputStream ByteArrayOutputStream))) (defn do-serialize [format data] (when data (let [stream (ByteArrayOutputStream.)] (transit/write (transit/writer stream format nil) data) (.toByteArray stream)))) (defn do-deserialize [format data] (when data (transit/read (transit/reader (ByteArrayInputStream. data) format nil)))) (deftype JsonSerializer [] Serializer (configure [_ _ _]) (serialize [_ _ data] (do-serialize :json data)) (close [_])) (deftype JsonDeserializer [] Deserializer (configure [_ _ _]) (deserialize [_ _ data] (do-deserialize :json data)) (close [_])) (deftype JsonSerde [] Serde (configure [_ _ _]) (close [_]) (serializer [_] (JsonSerializer.)) (deserializer [_] (JsonDeserializer.))) (deftype JsonVerboseSerializer [] Serializer (configure [_ _ _]) (serialize [_ _ data] (do-serialize :json-verbose data)) (close [_])) (deftype JsonVerboseDeserializer [] Deserializer (configure [_ _ _]) (deserialize [_ _ data] (do-deserialize :json-verbose data)) (close [_])) (deftype JsonVerboseSerde [] Serde (configure [_ _ _]) (close [_]) (serializer [_] (JsonSerializer.)) (deserializer [_] (JsonDeserializer.))) (deftype MsgpackSerializer [] Serializer (configure [_ _ _]) (serialize [_ _ data] (do-serialize :msgpack data)) (close [_])) (deftype MsgpackDeserializer [] Deserializer (configure [_ _ _]) (deserialize [_ _ data] (do-deserialize :msgpack data)) (close [_])) (deftype MsgpackSerde [] Serde (configure [_ _ _]) (close [_]) (serializer [_] (MsgpackSerializer.)) (deserializer [_] (MsgpackDeserializer.))) (defn serializer [format] (case format :json (->JsonSerializer) :json-verbose (->JsonVerboseSerializer) :msgpack (->MsgpackSerializer))) (defn deserializer [format] (case format :json (->JsonDeserializer) :json-verbose (->JsonVerboseDeserializer) :msgpack (->MsgpackDeserializer))) (defn serde [format] (case format :json (->JsonSerde) :json-verbose (->JsonVerboseSerde) :msgpack (->MsgpackSerde)))
null
https://raw.githubusercontent.com/troy-west/kstream-examples/bda1d0d898829ca44a07cf8ee488e940431e427f/src/troy_west/serdes.clj
clojure
(ns troy-west.serdes (:require [cognitect.transit :as transit]) (:import (org.apache.kafka.common.serialization Deserializer Serializer Serde) (java.io ByteArrayInputStream ByteArrayOutputStream))) (defn do-serialize [format data] (when data (let [stream (ByteArrayOutputStream.)] (transit/write (transit/writer stream format nil) data) (.toByteArray stream)))) (defn do-deserialize [format data] (when data (transit/read (transit/reader (ByteArrayInputStream. data) format nil)))) (deftype JsonSerializer [] Serializer (configure [_ _ _]) (serialize [_ _ data] (do-serialize :json data)) (close [_])) (deftype JsonDeserializer [] Deserializer (configure [_ _ _]) (deserialize [_ _ data] (do-deserialize :json data)) (close [_])) (deftype JsonSerde [] Serde (configure [_ _ _]) (close [_]) (serializer [_] (JsonSerializer.)) (deserializer [_] (JsonDeserializer.))) (deftype JsonVerboseSerializer [] Serializer (configure [_ _ _]) (serialize [_ _ data] (do-serialize :json-verbose data)) (close [_])) (deftype JsonVerboseDeserializer [] Deserializer (configure [_ _ _]) (deserialize [_ _ data] (do-deserialize :json-verbose data)) (close [_])) (deftype JsonVerboseSerde [] Serde (configure [_ _ _]) (close [_]) (serializer [_] (JsonSerializer.)) (deserializer [_] (JsonDeserializer.))) (deftype MsgpackSerializer [] Serializer (configure [_ _ _]) (serialize [_ _ data] (do-serialize :msgpack data)) (close [_])) (deftype MsgpackDeserializer [] Deserializer (configure [_ _ _]) (deserialize [_ _ data] (do-deserialize :msgpack data)) (close [_])) (deftype MsgpackSerde [] Serde (configure [_ _ _]) (close [_]) (serializer [_] (MsgpackSerializer.)) (deserializer [_] (MsgpackDeserializer.))) (defn serializer [format] (case format :json (->JsonSerializer) :json-verbose (->JsonVerboseSerializer) :msgpack (->MsgpackSerializer))) (defn deserializer [format] (case format :json (->JsonDeserializer) :json-verbose (->JsonVerboseDeserializer) :msgpack (->MsgpackDeserializer))) (defn serde [format] (case format :json (->JsonSerde) :json-verbose (->JsonVerboseSerde) :msgpack (->MsgpackSerde)))
18d62180f2ff41f979ef9b48ca6fb7a7cf5aca2d82c922d6480b8bce45d153f4
camllight/camllight
ouster-f16.10.ml
#open "tk";; let parse_color line = let sep = function ` ` | `\t` -> true | _ -> false in let l = support__split_str sep line in let r::rest = l in let g::rest = rest in let b::rest = rest in let name = support__catenate_sep " " rest in r,g,b,name ;; (* Same bug as in the book (when color name contains spaces) e.g. selection get will return "{ghost white}" *) let top = OpenTk () in let lb = listbox__create top [] in pack [lb][]; let f = open_in "/usr/lib/X11/rgb.txt" in begin try while true do let _,_,_,name = parse_color (input_line f) in listbox__insert lb End [name] done with End_of_file -> close_in f end; bind lb [[Double], WhatButton 1] (BindSet([], function _ -> listbox__configure lb [Background (NamedColor (selection__get()))])); MainLoop() ;;
null
https://raw.githubusercontent.com/camllight/camllight/0cc537de0846393322058dbb26449427bfc76786/sources/contrib/camltk/books-examples/ouster-f16.10.ml
ocaml
Same bug as in the book (when color name contains spaces) e.g. selection get will return "{ghost white}"
#open "tk";; let parse_color line = let sep = function ` ` | `\t` -> true | _ -> false in let l = support__split_str sep line in let r::rest = l in let g::rest = rest in let b::rest = rest in let name = support__catenate_sep " " rest in r,g,b,name ;; let top = OpenTk () in let lb = listbox__create top [] in pack [lb][]; let f = open_in "/usr/lib/X11/rgb.txt" in begin try while true do let _,_,_,name = parse_color (input_line f) in listbox__insert lb End [name] done with End_of_file -> close_in f end; bind lb [[Double], WhatButton 1] (BindSet([], function _ -> listbox__configure lb [Background (NamedColor (selection__get()))])); MainLoop() ;;
2ec22f4a89d6bd6c9ddd4fe511b8afe4d443cbb2254762c2b94bf6362ee62ded
kadena-io/chainweaver
Orphans.hs
# LANGUAGE GeneralizedNewtypeDeriving # # LANGUAGE StandaloneDeriving # # OPTIONS_GHC -Wno - orphans # module Common.Orphans where import Data.Aeson (FromJSONKey, ToJSONKey) import qualified Pact.Types.ChainId as Pact deriving instance Ord Pact.ChainId deriving instance ToJSONKey Pact.ChainId deriving instance FromJSONKey Pact.ChainId
null
https://raw.githubusercontent.com/kadena-io/chainweaver/3ea0bb317c07ddf954d4ebf24b33d1be7d5f9c45/common/src/Common/Orphans.hs
haskell
# LANGUAGE GeneralizedNewtypeDeriving # # LANGUAGE StandaloneDeriving # # OPTIONS_GHC -Wno - orphans # module Common.Orphans where import Data.Aeson (FromJSONKey, ToJSONKey) import qualified Pact.Types.ChainId as Pact deriving instance Ord Pact.ChainId deriving instance ToJSONKey Pact.ChainId deriving instance FromJSONKey Pact.ChainId
62422df20c27a80c513839ddd03ac52033931cfb8d888ffaa8b63b56dc9150db
m4dc4p/haskelldb
DBSpecToDBDirect.hs
----------------------------------------------------------- -- | -- Module : DBSpecToDBDirect Copyright : HWT Group ( c ) 2004 , -- License : BSD-style -- Maintainer : -- Stability : experimental -- Portability : non-portable -- Converts a DBSpec - generated database to a set of ( FilePath , Doc ) , that can be used to generate definition files usable in HaskellDB ( the generation itself is done in DBDirect ) -- -- ----------------------------------------------------------- module Database.HaskellDB.DBSpec.DBSpecToDBDirect (specToHDB, dbInfoToModuleFiles) where import Prelude hiding ((<>)) import Database.HaskellDB.FieldType (toHaskellType, ) import Database.HaskellDB.DBSpec.DBInfo (TInfo(TInfo), CInfo(CInfo), DBInfo, descr, cols, tname, cname, tbls, dbInfoToDoc, opts, makeIdent, finalizeSpec, constructNonClashingDBInfo, ) import Database.HaskellDB.DBSpec.PPHelpers (MakeIdentifiers, moduleName, toType, identifier, checkChars, ppComment, newline, ) import Control.Monad (unless) import Data.List (isPrefixOf) import System.Directory (createDirectory, doesDirectoryExist) import Text.PrettyPrint.HughesPJ -- | Common header for all files header :: Doc header = ppComment ["Generated by DB/Direct"] -- | Adds LANGUAGE pragrams to the top of generated files languageOptions :: Doc languageOptions = text "{-# LANGUAGE EmptyDataDecls, TypeSynonymInstances #-}" -- | Adds an appropriate -fcontext-stackXX OPTIONS pragma at the top -- of the generated file. contextStackPragma :: TInfo -> Doc contextStackPragma ti = text "{-# OPTIONS_GHC" <+> text flag <+> text "#-}" where flag = "-fcontext-stack" ++ (show (40 + length (cols ti))) -- | All imports generated files have dependencies on. Nowadays, this -- should only be Database.HaskellDB.DBLayout imports :: Doc imports = text "import Database.HaskellDB.DBLayout" | Create module files in the given directory for the given dbInfoToModuleFiles :: FilePath -- ^ base directory -> String -- ^ top-level module name -> DBInfo -> IO () dbInfoToModuleFiles d name = createModules d name . specToHDB name . finalizeSpec -- | Creates modules createModules :: FilePath -- ^ Base directory -> String -- ^ Name of directory and top-level module for the database modules -> [(String,Doc)] -- ^ Module names and module contents -> IO () createModules basedir dbname files = do let dir = withPrefix basedir (replace '.' '/' dbname) createPath dir mapM_ (\ (name,doc) -> writeFile (moduleNameToFile basedir name) (render doc)) files -- | Make a filename from a module name moduleNameToFile :: FilePath -> String -> FilePath moduleNameToFile base mod = withPrefix base f where f = replace '.' '/' mod ++ ".hs" withPrefix :: FilePath -> String -> FilePath withPrefix base f | null base = f | otherwise = base ++ "/" ++ f replace :: Eq a => a -> a -> [a] -> [a] replace x y zs = [if z == x then y else z | z <- zs] -- | Like createDirectory, but creates all the directories in -- the path. createPath :: FilePath -> IO () createPath p | "/" `isPrefixOf` p = createPath' "/" (dropWhile (=='/') p) | otherwise = createPath' "" p where createPath' _ "" = return () createPath' b p = do let (d,r) = break (=='/') p n = withPrefix b d createDirIfNotExists n createPath' n (dropWhile (=='/') r) createDirIfNotExists :: FilePath -> IO () createDirIfNotExists p = do exists <- doesDirectoryExist p unless exists (createDirectory p) -- | Converts a database specification to a set of module names and module contents . The first element of the returned list -- is the top-level module. specToHDB :: String -- ^ Top level module name -> DBInfo -> [(String,Doc)] specToHDB name dbinfo = genDocs name (constructNonClashingDBInfo dbinfo) -- | Does the actual conversion work genDocs :: String -- ^ Top-level module name -> DBInfo -> [(String,Doc)] -- ^ list of module name, module contents pairs genDocs name dbinfo = (name, header $$ text "module" <+> text name <+> text "where" <> newline $$ imports <> newline $$ vcat (map (text . ("import qualified " ++)) tbnames) <> newline $$ dbInfoToDoc dbinfo) : rest where rest = map (tInfoToModule (makeIdent (opts dbinfo)) name) $ filter hasName $ tbls dbinfo hasName TInfo{tname=name} = name /= "" tbnames = map fst rest | Makes a module from a TInfo tInfoToModule :: MakeIdentifiers -> String -- ^ The name of our main module -> TInfo -> (String,Doc) -- ^ Module name and module contents tInfoToModule mi dbname tinfo@TInfo{tname=name,cols=col} = (modname, languageOptions $$ contextStackPragma tinfo $$ header $$ text "module" <+> text modname <+> text "where" <> newline $$ imports <> newline $$ ppComment ["Table type"] <> newline $$ ppTableType mi tinfo <> newline $$ ppComment ["Table"] $$ ppTable mi tinfo $$ ppComment ["Fields"] $$ if null col then empty -- no fields, don't do anything weird else vcat (map (ppField mi) (columnNamesTypes tinfo))) where modname = dbname ++ "." ++ moduleName mi name ppTableType :: MakeIdentifiers -> TInfo -> Doc ppTableType mi (TInfo { tname = tiName, cols = tiColumns }) = hang decl 4 types where decl = text "type" <+> text (toType mi tiName) <+> text "=" types = ppColumns mi tiColumns | Pretty prints a TableInfo ppTable :: MakeIdentifiers -> TInfo -> Doc ppTable mi (TInfo tiName tiColumns) = hang (text (identifier mi tiName) <+> text "::" <+> text "Table") 4 (text (toType mi tiName)) $$ text (identifier mi tiName) <+> text "=" <+> hang (text "baseTable" <+> doubleQuotes (text (checkChars tiName)) <+> text "$") 0 (vcat $ punctuate (text " #") (map (ppColumnValue mi) tiColumns)) <> newline | Pretty prints a list of ColumnInfo ppColumns _ [] = text "" ppColumns mi [c] = parens (ppColumnType mi c <+> text "RecNil") ppColumns mi (c:cs) = parens (ppColumnType mi c $$ ppColumns mi cs) | Pretty prints the type field in a ColumnInfo ppColumnType :: MakeIdentifiers -> CInfo -> Doc ppColumnType mi (CInfo ciName (ciType,ciAllowNull)) = text "RecCons" <+> ((text $ toType mi ciName) <+> parens (text "Expr" <+> (if (ciAllowNull) then parens (text "Maybe" <+> text (toHaskellType ciType)) else text (toHaskellType ciType) ))) | Pretty prints the value field in a ColumnInfo ppColumnValue :: MakeIdentifiers -> CInfo -> Doc ppColumnValue mi (CInfo ciName _) = text "hdbMakeEntry" <+> text (toType mi ciName) -- | Pretty prints Field definitions ppField :: MakeIdentifiers -> (String, String) -> Doc ppField mi (name,typeof) = ppComment [toType mi name ++ " Field"] <> newline $$ text "data" <+> bname <+> equals <+> bname -- <+> text "deriving Show" <> newline $$ hang (text "instance FieldTag" <+> bname <+> text "where") 4 (text "fieldName _" <+> equals <+> doubleQuotes (text (checkChars name))) <> newline $$ iname <+> text "::" <+> text "Attr" <+> bname <+> text typeof $$ iname <+> equals <+> text "mkAttr" <+> bname <> newline where bname = text (toType mi name) iname = text (identifier mi name) | Extracts all the column names from a TableInfo columnNames :: TInfo -> [String] columnNames table = map cname (cols table) | Extracts all the column types from a TableInfo columnTypes :: TInfo -> [String] columnTypes table = [if b then ("(Maybe " ++ t ++ ")") else t | (t,b) <- zippedlist] where zippedlist = zip typelist null_list typelist = map (toHaskellType . fst . descr) (cols table) null_list = map (snd . descr) (cols table) | Combines the results of columnNames and columnNamesTypes :: TInfo -> [(String,String)] columnNamesTypes table@(TInfo tname fields) = zip (columnNames table) (columnTypes table)
null
https://raw.githubusercontent.com/m4dc4p/haskelldb/a1fbc8a2eca8c70ebe382bf4c022275836d9d510/src/Database/HaskellDB/DBSpec/DBSpecToDBDirect.hs
haskell
--------------------------------------------------------- | Module : DBSpecToDBDirect License : BSD-style Stability : experimental Portability : non-portable --------------------------------------------------------- | Common header for all files | Adds LANGUAGE pragrams to the top of generated files | Adds an appropriate -fcontext-stackXX OPTIONS pragma at the top of the generated file. | All imports generated files have dependencies on. Nowadays, this should only be Database.HaskellDB.DBLayout ^ base directory ^ top-level module name | Creates modules ^ Base directory ^ Name of directory and top-level module for the database modules ^ Module names and module contents | Make a filename from a module name | Like createDirectory, but creates all the directories in the path. | Converts a database specification to a set of module names is the top-level module. ^ Top level module name | Does the actual conversion work ^ Top-level module name ^ list of module name, module contents pairs ^ The name of our main module ^ Module name and module contents no fields, don't do anything weird | Pretty prints Field definitions <+> text "deriving Show"
Copyright : HWT Group ( c ) 2004 , Maintainer : Converts a DBSpec - generated database to a set of ( FilePath , Doc ) , that can be used to generate definition files usable in HaskellDB ( the generation itself is done in DBDirect ) module Database.HaskellDB.DBSpec.DBSpecToDBDirect (specToHDB, dbInfoToModuleFiles) where import Prelude hiding ((<>)) import Database.HaskellDB.FieldType (toHaskellType, ) import Database.HaskellDB.DBSpec.DBInfo (TInfo(TInfo), CInfo(CInfo), DBInfo, descr, cols, tname, cname, tbls, dbInfoToDoc, opts, makeIdent, finalizeSpec, constructNonClashingDBInfo, ) import Database.HaskellDB.DBSpec.PPHelpers (MakeIdentifiers, moduleName, toType, identifier, checkChars, ppComment, newline, ) import Control.Monad (unless) import Data.List (isPrefixOf) import System.Directory (createDirectory, doesDirectoryExist) import Text.PrettyPrint.HughesPJ header :: Doc header = ppComment ["Generated by DB/Direct"] languageOptions :: Doc languageOptions = text "{-# LANGUAGE EmptyDataDecls, TypeSynonymInstances #-}" contextStackPragma :: TInfo -> Doc contextStackPragma ti = text "{-# OPTIONS_GHC" <+> text flag <+> text "#-}" where flag = "-fcontext-stack" ++ (show (40 + length (cols ti))) imports :: Doc imports = text "import Database.HaskellDB.DBLayout" | Create module files in the given directory for the given -> DBInfo -> IO () dbInfoToModuleFiles d name = createModules d name . specToHDB name . finalizeSpec -> IO () createModules basedir dbname files = do let dir = withPrefix basedir (replace '.' '/' dbname) createPath dir mapM_ (\ (name,doc) -> writeFile (moduleNameToFile basedir name) (render doc)) files moduleNameToFile :: FilePath -> String -> FilePath moduleNameToFile base mod = withPrefix base f where f = replace '.' '/' mod ++ ".hs" withPrefix :: FilePath -> String -> FilePath withPrefix base f | null base = f | otherwise = base ++ "/" ++ f replace :: Eq a => a -> a -> [a] -> [a] replace x y zs = [if z == x then y else z | z <- zs] createPath :: FilePath -> IO () createPath p | "/" `isPrefixOf` p = createPath' "/" (dropWhile (=='/') p) | otherwise = createPath' "" p where createPath' _ "" = return () createPath' b p = do let (d,r) = break (=='/') p n = withPrefix b d createDirIfNotExists n createPath' n (dropWhile (=='/') r) createDirIfNotExists :: FilePath -> IO () createDirIfNotExists p = do exists <- doesDirectoryExist p unless exists (createDirectory p) and module contents . The first element of the returned list -> DBInfo -> [(String,Doc)] specToHDB name dbinfo = genDocs name (constructNonClashingDBInfo dbinfo) -> DBInfo genDocs name dbinfo = (name, header $$ text "module" <+> text name <+> text "where" <> newline $$ imports <> newline $$ vcat (map (text . ("import qualified " ++)) tbnames) <> newline $$ dbInfoToDoc dbinfo) : rest where rest = map (tInfoToModule (makeIdent (opts dbinfo)) name) $ filter hasName $ tbls dbinfo hasName TInfo{tname=name} = name /= "" tbnames = map fst rest | Makes a module from a TInfo tInfoToModule :: MakeIdentifiers -> TInfo tInfoToModule mi dbname tinfo@TInfo{tname=name,cols=col} = (modname, languageOptions $$ contextStackPragma tinfo $$ header $$ text "module" <+> text modname <+> text "where" <> newline $$ imports <> newline $$ ppComment ["Table type"] <> newline $$ ppTableType mi tinfo <> newline $$ ppComment ["Table"] $$ ppTable mi tinfo $$ ppComment ["Fields"] $$ if null col else vcat (map (ppField mi) (columnNamesTypes tinfo))) where modname = dbname ++ "." ++ moduleName mi name ppTableType :: MakeIdentifiers -> TInfo -> Doc ppTableType mi (TInfo { tname = tiName, cols = tiColumns }) = hang decl 4 types where decl = text "type" <+> text (toType mi tiName) <+> text "=" types = ppColumns mi tiColumns | Pretty prints a TableInfo ppTable :: MakeIdentifiers -> TInfo -> Doc ppTable mi (TInfo tiName tiColumns) = hang (text (identifier mi tiName) <+> text "::" <+> text "Table") 4 (text (toType mi tiName)) $$ text (identifier mi tiName) <+> text "=" <+> hang (text "baseTable" <+> doubleQuotes (text (checkChars tiName)) <+> text "$") 0 (vcat $ punctuate (text " #") (map (ppColumnValue mi) tiColumns)) <> newline | Pretty prints a list of ColumnInfo ppColumns _ [] = text "" ppColumns mi [c] = parens (ppColumnType mi c <+> text "RecNil") ppColumns mi (c:cs) = parens (ppColumnType mi c $$ ppColumns mi cs) | Pretty prints the type field in a ColumnInfo ppColumnType :: MakeIdentifiers -> CInfo -> Doc ppColumnType mi (CInfo ciName (ciType,ciAllowNull)) = text "RecCons" <+> ((text $ toType mi ciName) <+> parens (text "Expr" <+> (if (ciAllowNull) then parens (text "Maybe" <+> text (toHaskellType ciType)) else text (toHaskellType ciType) ))) | Pretty prints the value field in a ColumnInfo ppColumnValue :: MakeIdentifiers -> CInfo -> Doc ppColumnValue mi (CInfo ciName _) = text "hdbMakeEntry" <+> text (toType mi ciName) ppField :: MakeIdentifiers -> (String, String) -> Doc ppField mi (name,typeof) = ppComment [toType mi name ++ " Field"] <> newline $$ <> newline $$ hang (text "instance FieldTag" <+> bname <+> text "where") 4 (text "fieldName _" <+> equals <+> doubleQuotes (text (checkChars name))) <> newline $$ iname <+> text "::" <+> text "Attr" <+> bname <+> text typeof $$ iname <+> equals <+> text "mkAttr" <+> bname <> newline where bname = text (toType mi name) iname = text (identifier mi name) | Extracts all the column names from a TableInfo columnNames :: TInfo -> [String] columnNames table = map cname (cols table) | Extracts all the column types from a TableInfo columnTypes :: TInfo -> [String] columnTypes table = [if b then ("(Maybe " ++ t ++ ")") else t | (t,b) <- zippedlist] where zippedlist = zip typelist null_list typelist = map (toHaskellType . fst . descr) (cols table) null_list = map (snd . descr) (cols table) | Combines the results of columnNames and columnNamesTypes :: TInfo -> [(String,String)] columnNamesTypes table@(TInfo tname fields) = zip (columnNames table) (columnTypes table)
7f2a4890e62d27a2d31711696e22066152a36a5a630a5a29799c12df72d0e6e7
fredlund/McErlang
mce_behav_schedulerOps.erl
Copyright ( c ) 2009 , %% All rights reserved. %% %% Redistribution and use in source and binary forms, with or without %% modification, are permitted provided that the following conditions are met: %% %% Redistributions of source code must retain the above copyright %% notice, this list of conditions and the following disclaimer. %% %% Redistributions in binary form must reproduce the above copyright %% notice, this list of conditions and the following disclaimer in the %% documentation and/or other materials provided with the distribution. %% %% Neither the name of the copyright holders nor the %% names of its contributors may be used to endorse or promote products %% derived from this software without specific prior written permission. %% %% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' %% AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE %% ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND 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. @author 2006 - 2009 %% @doc @private -module(mce_behav_schedulerOps). -include("sched.hrl"). -export([init/2,choose/4,willCommit/1]). init(SchedModule,SchedArgs) -> {ok,SchedState} = SchedModule:init(SchedArgs), {ok,#sched{module=SchedModule,contents=SchedState}}. willCommit(Sched) -> (Sched#sched.module):willCommit(Sched#sched.contents). choose(Transitions,Sched,Monitor,Conf) -> case (Sched#sched.module): choose(Transitions,Sched#sched.contents,Monitor,Conf) of {ok,{Result,NewSched}} -> {ok,{Result,Sched#sched{contents=NewSched}}}; Other -> Other end.
null
https://raw.githubusercontent.com/fredlund/McErlang/25b38a38a729fdb3c3d2afb9be016bbb14237792/behaviours/src/mce_behav_schedulerOps.erl
erlang
All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: %% Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. %% Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. %% Neither the name of the copyright holders nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS 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. @doc
Copyright ( c ) 2009 , IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE BE LIABLE FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR @author 2006 - 2009 @private -module(mce_behav_schedulerOps). -include("sched.hrl"). -export([init/2,choose/4,willCommit/1]). init(SchedModule,SchedArgs) -> {ok,SchedState} = SchedModule:init(SchedArgs), {ok,#sched{module=SchedModule,contents=SchedState}}. willCommit(Sched) -> (Sched#sched.module):willCommit(Sched#sched.contents). choose(Transitions,Sched,Monitor,Conf) -> case (Sched#sched.module): choose(Transitions,Sched#sched.contents,Monitor,Conf) of {ok,{Result,NewSched}} -> {ok,{Result,Sched#sched{contents=NewSched}}}; Other -> Other end.
d7d983b7c25a73a557ae5bf3ba8cb9cefb3701b1b67512e5a28dfd08d52aa4fe
metosin/metosin-common
dates.cljc
(ns metosin.edn.dates "EDN tag readers and writers for JodaTime and goog.date. Supports two types: - DateTime (org.joda.time.DateTime, goog.date.UtcDateTime) - LocalDate (org.joda.time.LocalDate, goog.date.Date) Represents DateTimes in RFC 3339 format: yyyy-mm-ddTHH:MM:SS.sssZ. RFC 3339 format is an specific profile of ISO 8601 DateTime format. Some consideration has been made to provide performant read implemenation for ClojureScript." (:require [metosin.dates :as d]) #?(:clj (:import [org.joda.time DateTime LocalDate] [java.io Writer]))) (defn- date-time->reader-str ^String [d] (str "#DateTime \"" (d/to-string d) \")) (defn- date->reader-str ^String [d] (str "#Date \"" (d/to-string d) \")) #?(:clj (do (defmethod print-dup DateTime [^DateTime d ^Writer out] (.write out (date-time->reader-str d))) (defmethod print-method DateTime [^DateTime d ^Writer out] (.write out (date-time->reader-str d))) (defmethod print-dup LocalDate [^LocalDate d ^Writer out] (.write out (date->reader-str d))) (defmethod print-method LocalDate [^LocalDate d ^Writer out] (.write out (date->reader-str d)))) :cljs (extend-protocol IPrintWithWriter goog.date.DateTime (-pr-writer [d out _opts] (-write out (date-time->reader-str d))) goog.date.Date (-pr-writer [d out _opts] (-write out (date->reader-str d))))) (def readers {'Date d/date 'DateTime d/date-time})
null
https://raw.githubusercontent.com/metosin/metosin-common/6f6471052a82f85828c647b86905edd3890c825d/src/cljc/metosin/edn/dates.cljc
clojure
(ns metosin.edn.dates "EDN tag readers and writers for JodaTime and goog.date. Supports two types: - DateTime (org.joda.time.DateTime, goog.date.UtcDateTime) - LocalDate (org.joda.time.LocalDate, goog.date.Date) Represents DateTimes in RFC 3339 format: yyyy-mm-ddTHH:MM:SS.sssZ. RFC 3339 format is an specific profile of ISO 8601 DateTime format. Some consideration has been made to provide performant read implemenation for ClojureScript." (:require [metosin.dates :as d]) #?(:clj (:import [org.joda.time DateTime LocalDate] [java.io Writer]))) (defn- date-time->reader-str ^String [d] (str "#DateTime \"" (d/to-string d) \")) (defn- date->reader-str ^String [d] (str "#Date \"" (d/to-string d) \")) #?(:clj (do (defmethod print-dup DateTime [^DateTime d ^Writer out] (.write out (date-time->reader-str d))) (defmethod print-method DateTime [^DateTime d ^Writer out] (.write out (date-time->reader-str d))) (defmethod print-dup LocalDate [^LocalDate d ^Writer out] (.write out (date->reader-str d))) (defmethod print-method LocalDate [^LocalDate d ^Writer out] (.write out (date->reader-str d)))) :cljs (extend-protocol IPrintWithWriter goog.date.DateTime (-pr-writer [d out _opts] (-write out (date-time->reader-str d))) goog.date.Date (-pr-writer [d out _opts] (-write out (date->reader-str d))))) (def readers {'Date d/date 'DateTime d/date-time})
8deeca4c8d698155926c8bebcc588a9ea113f6a16710c6e3868e60a8d1aab6d6
ThoughtWorksInc/stonecutter
middleware.clj
(ns stonecutter.test.middleware (:require [midje.sweet :refer :all] [stonecutter.middleware :as middleware])) (defn example-handler [request] "return value") (defn wrap-function [handler] (fn [request] "wrap function return value")) (def handlers {:handler-1 example-handler :handler-2 example-handler :handler-3 example-handler}) (facts "about wrap-handlers-except" (fact "wrap handlers wraps all handlers in a wrap-function" (let [wrapped-handlers (middleware/wrap-handlers-except handlers wrap-function nil)] ((:handler-1 wrapped-handlers) "request") => "wrap function return value" ((:handler-2 wrapped-handlers) "request") => "wrap function return value" ((:handler-3 wrapped-handlers) "request") => "wrap function return value")) (fact "wrap handlers takes a set of exclusions which are not wrapped" (let [wrapped-handlers (middleware/wrap-handlers-except handlers wrap-function #{:handler-1 :handler-3})] ((:handler-1 wrapped-handlers) "request") => "return value" ((:handler-2 wrapped-handlers) "request") => "wrap function return value" ((:handler-3 wrapped-handlers) "request") => "return value"))) (facts "wrap-just-these-handlers only wraps the specified handlers" (let [wrapped-handlers (middleware/wrap-just-these-handlers handlers wrap-function #{:handler-2 :handler-3})] ((:handler-1 wrapped-handlers) "request") => "return value" ((:handler-2 wrapped-handlers) "request") => "wrap function return value" ((:handler-3 wrapped-handlers) "request") => "wrap function return value")) (fact "renders 403 error page when response status is 403" (let [handler-that-always-403s (fn [req] {:status 403}) stub-error-403-handler (fn [req] ...error-403-response...) wrapped-handler (middleware/wrap-handle-403 handler-that-always-403s stub-error-403-handler)] (wrapped-handler ...request...) => ...error-403-response...)) (facts "about wrap-authorised" (fact "passes request to wrapped handler when user is authorised" (let [wrapped-handler (middleware/wrap-authorised example-handler (constantly true))] (wrapped-handler "request") => "return value")) (fact "returns nil when user is not authorised" (let [wrapped-handler (middleware/wrap-authorised example-handler (constantly false))] (wrapped-handler "request") => nil)) )
null
https://raw.githubusercontent.com/ThoughtWorksInc/stonecutter/37ed22dd276ac652176c4d880e0f1b0c1e27abfe/test/stonecutter/test/middleware.clj
clojure
(ns stonecutter.test.middleware (:require [midje.sweet :refer :all] [stonecutter.middleware :as middleware])) (defn example-handler [request] "return value") (defn wrap-function [handler] (fn [request] "wrap function return value")) (def handlers {:handler-1 example-handler :handler-2 example-handler :handler-3 example-handler}) (facts "about wrap-handlers-except" (fact "wrap handlers wraps all handlers in a wrap-function" (let [wrapped-handlers (middleware/wrap-handlers-except handlers wrap-function nil)] ((:handler-1 wrapped-handlers) "request") => "wrap function return value" ((:handler-2 wrapped-handlers) "request") => "wrap function return value" ((:handler-3 wrapped-handlers) "request") => "wrap function return value")) (fact "wrap handlers takes a set of exclusions which are not wrapped" (let [wrapped-handlers (middleware/wrap-handlers-except handlers wrap-function #{:handler-1 :handler-3})] ((:handler-1 wrapped-handlers) "request") => "return value" ((:handler-2 wrapped-handlers) "request") => "wrap function return value" ((:handler-3 wrapped-handlers) "request") => "return value"))) (facts "wrap-just-these-handlers only wraps the specified handlers" (let [wrapped-handlers (middleware/wrap-just-these-handlers handlers wrap-function #{:handler-2 :handler-3})] ((:handler-1 wrapped-handlers) "request") => "return value" ((:handler-2 wrapped-handlers) "request") => "wrap function return value" ((:handler-3 wrapped-handlers) "request") => "wrap function return value")) (fact "renders 403 error page when response status is 403" (let [handler-that-always-403s (fn [req] {:status 403}) stub-error-403-handler (fn [req] ...error-403-response...) wrapped-handler (middleware/wrap-handle-403 handler-that-always-403s stub-error-403-handler)] (wrapped-handler ...request...) => ...error-403-response...)) (facts "about wrap-authorised" (fact "passes request to wrapped handler when user is authorised" (let [wrapped-handler (middleware/wrap-authorised example-handler (constantly true))] (wrapped-handler "request") => "return value")) (fact "returns nil when user is not authorised" (let [wrapped-handler (middleware/wrap-authorised example-handler (constantly false))] (wrapped-handler "request") => nil)) )
57ddb629e97a1aacd8424d3981790e52339113d588e2a483bd6ecae10b06d558
haskellari/splitmix
MiniQC.hs
# LANGUAGE DeriveFunctor # -- | This QC doesn't shrink :( module MiniQC where import Control.Monad (ap) import Data.Int (Int32, Int64) import Data.Word (Word32, Word64) import Prelude () import Prelude.Compat import Test.Framework.Providers.API (Test, TestName) import Test.Framework.Providers.HUnit (testCase) import Test.HUnit (assertFailure) import System.Random.SplitMix newtype Gen a = Gen { unGen :: SMGen -> a } deriving (Functor) instance Applicative Gen where pure x = Gen (const x) (<*>) = ap instance Monad Gen where return = pure m >>= k = Gen $ \g -> let (g1, g2) = splitSMGen g in unGen (k (unGen m g1)) g2 class Arbitrary a where arbitrary :: Gen a instance Arbitrary Word32 where arbitrary = Gen $ \g -> fst (nextWord32 g) instance Arbitrary Word64 where arbitrary = Gen $ \g -> fst (nextWord64 g) instance Arbitrary Int32 where arbitrary = Gen $ \g -> fromIntegral (fst (nextWord32 g)) instance Arbitrary Int64 where arbitrary = Gen $ \g -> fromIntegral (fst (nextWord64 g)) instance Arbitrary Double where arbitrary = Gen $ \g -> fst (nextDouble g) newtype Property = Property { unProperty :: Gen ([String], Bool) } class Testable a where property :: a -> Property instance Testable Property where property = id instance Testable Bool where property b = Property $ pure ([show b], b) instance (Arbitrary a, Show a, Testable b) => Testable (a -> b) where property f = Property $ do x <- arbitrary (xs, b) <- unProperty (property (f x)) return (show x : xs, b) forAllBlind :: Testable prop => Gen a -> (a -> prop) -> Property forAllBlind g f = Property $ do x <- g (xs, b) <- unProperty (property (f x)) return ("<blind>" : xs, b) counterexample :: Testable prop => String -> prop -> Property counterexample msg prop = Property $ do (xs, b) <- unProperty (property prop) return (msg : xs, b) testMiniProperty :: Testable prop => TestName -> prop -> Test testMiniProperty name prop = testCase name $ do g <- newSMGen go (100 :: Int) g where go n _ | n <= 0 = return () go n g = do let (g1, g2) = splitSMGen g case unGen (unProperty (property prop)) g1 of (_, True) -> return () (xs, False) -> assertFailure (unlines (reverse xs)) go (pred n) g2
null
https://raw.githubusercontent.com/haskellari/splitmix/f89a4bb6a5f87565d15e88c3b3c0023546bbd0ff/tests/MiniQC.hs
haskell
| This QC doesn't shrink :(
# LANGUAGE DeriveFunctor # module MiniQC where import Control.Monad (ap) import Data.Int (Int32, Int64) import Data.Word (Word32, Word64) import Prelude () import Prelude.Compat import Test.Framework.Providers.API (Test, TestName) import Test.Framework.Providers.HUnit (testCase) import Test.HUnit (assertFailure) import System.Random.SplitMix newtype Gen a = Gen { unGen :: SMGen -> a } deriving (Functor) instance Applicative Gen where pure x = Gen (const x) (<*>) = ap instance Monad Gen where return = pure m >>= k = Gen $ \g -> let (g1, g2) = splitSMGen g in unGen (k (unGen m g1)) g2 class Arbitrary a where arbitrary :: Gen a instance Arbitrary Word32 where arbitrary = Gen $ \g -> fst (nextWord32 g) instance Arbitrary Word64 where arbitrary = Gen $ \g -> fst (nextWord64 g) instance Arbitrary Int32 where arbitrary = Gen $ \g -> fromIntegral (fst (nextWord32 g)) instance Arbitrary Int64 where arbitrary = Gen $ \g -> fromIntegral (fst (nextWord64 g)) instance Arbitrary Double where arbitrary = Gen $ \g -> fst (nextDouble g) newtype Property = Property { unProperty :: Gen ([String], Bool) } class Testable a where property :: a -> Property instance Testable Property where property = id instance Testable Bool where property b = Property $ pure ([show b], b) instance (Arbitrary a, Show a, Testable b) => Testable (a -> b) where property f = Property $ do x <- arbitrary (xs, b) <- unProperty (property (f x)) return (show x : xs, b) forAllBlind :: Testable prop => Gen a -> (a -> prop) -> Property forAllBlind g f = Property $ do x <- g (xs, b) <- unProperty (property (f x)) return ("<blind>" : xs, b) counterexample :: Testable prop => String -> prop -> Property counterexample msg prop = Property $ do (xs, b) <- unProperty (property prop) return (msg : xs, b) testMiniProperty :: Testable prop => TestName -> prop -> Test testMiniProperty name prop = testCase name $ do g <- newSMGen go (100 :: Int) g where go n _ | n <= 0 = return () go n g = do let (g1, g2) = splitSMGen g case unGen (unProperty (property prop)) g1 of (_, True) -> return () (xs, False) -> assertFailure (unlines (reverse xs)) go (pred n) g2
5e14a55db0536f05380873a13c22b8eb0e6608d2c0407f2f93abc32637a7de7b
waldheinz/bling
Heightmap.hs
module Graphics.Bling.Primitive.Heightmap ( heightMap ) where import Graphics.Bling.Primitive import Graphics.Bling.Primitive.TriangleMesh import Graphics.Bling.Reflection import Graphics.Bling.Texture import qualified Data.Vector.Unboxed as UV heightMap :: ScalarMap2d -> PixelSize -> Material -> Transform -> [Primitive] heightMap elev (ns, nt) mat t = mkTriangleMesh t mat ps is norms uvs where (fns, fnt) = (fromIntegral ns, fromIntegral nt) -- triangle indices is = UV.fromList $ concatMap tris [(x, y) | y <- [0..(nt-2)], x <- [0..(ns-2)]] tris pos = fstTri pos ++ sndTri pos fstTri (x, y) = [vert (x, y), vert (x+1, y), vert (x+1, y+1)] sndTri (x, y) = [vert (x, y), vert (x+1, y+1), vert (x, y+1)] vert (x, y) = x + y * ns -- coordinates coords = [(fromIntegral x / (fns - 1), fromIntegral z / (fnt - 1)) | z <- [0..nt-1], x <- [0..ns-1]] ps = UV.fromList $ map pt coords pt (x, z) = mkPoint (x, elev $ Cartesian (x, z), z) -- normals (ex, ez) = (1 / fns, 1 / fnt) -- epsilon in x and z norms = Just $ UV.fromList $ map norm coords norm (x, z) = - (normalize $ mkV (dx, ex + ez, dz)) where dx = elev (Cartesian (x - ex, z)) - elev (Cartesian (x + ex, z)) dz = elev (Cartesian (x, z - ez)) - elev (Cartesian (x, z + ez)) -- uv uvs = Just $ UV.fromList $ map uv coords uv (x, z) = (x / (fns - 1), z / (fns - 1))
null
https://raw.githubusercontent.com/waldheinz/bling/1f338f4b8dbd6a2708cb10787f4a2ac55f66d5a8/src/lib/Graphics/Bling/Primitive/Heightmap.hs
haskell
triangle indices coordinates normals epsilon in x and z uv
module Graphics.Bling.Primitive.Heightmap ( heightMap ) where import Graphics.Bling.Primitive import Graphics.Bling.Primitive.TriangleMesh import Graphics.Bling.Reflection import Graphics.Bling.Texture import qualified Data.Vector.Unboxed as UV heightMap :: ScalarMap2d -> PixelSize -> Material -> Transform -> [Primitive] heightMap elev (ns, nt) mat t = mkTriangleMesh t mat ps is norms uvs where (fns, fnt) = (fromIntegral ns, fromIntegral nt) is = UV.fromList $ concatMap tris [(x, y) | y <- [0..(nt-2)], x <- [0..(ns-2)]] tris pos = fstTri pos ++ sndTri pos fstTri (x, y) = [vert (x, y), vert (x+1, y), vert (x+1, y+1)] sndTri (x, y) = [vert (x, y), vert (x+1, y+1), vert (x, y+1)] vert (x, y) = x + y * ns coords = [(fromIntegral x / (fns - 1), fromIntegral z / (fnt - 1)) | z <- [0..nt-1], x <- [0..ns-1]] ps = UV.fromList $ map pt coords pt (x, z) = mkPoint (x, elev $ Cartesian (x, z), z) norms = Just $ UV.fromList $ map norm coords norm (x, z) = - (normalize $ mkV (dx, ex + ez, dz)) where dx = elev (Cartesian (x - ex, z)) - elev (Cartesian (x + ex, z)) dz = elev (Cartesian (x, z - ez)) - elev (Cartesian (x, z + ez)) uvs = Just $ UV.fromList $ map uv coords uv (x, z) = (x / (fns - 1), z / (fns - 1))
8427a251175887be87af8f7c2601093ac6105afddddc4505e2b25ecf68614a73
AlexKnauth/toki-pi-kalama-musi
chord-names-in-C.rkt
#lang racket/base (provide toki-pona-string->chord-names-in-C) (require (only-in (submod music/data/note/note example) C4) "chord-names.rkt") (module+ main (require racket/file racket/string rackunit "../../common/command-line.rkt")) (module+ test (require racket/file racket/string racket/runtime-path rackunit) (define-runtime-path introduction.toki-pona.txt "../../../../examples/introduction.toki-pona.txt") (define-runtime-path introduction.diatonic-inversion-chord-names-in-C.txt "../../../../examples/introduction.diatonic-inversion-chord-names-in-C.txt")) ;; --------------------------------------------------------- ;; toki-pona-string->chord-names-in-C : String -> String (module+ test (check-equal? (toki-pona-string->chord-names-in-C (file->string introduction.toki-pona.txt)) (string-trim (file->string introduction.diatonic-inversion-chord-names-in-C.txt))) ) (define (toki-pona-string->chord-names-in-C s) (toki-pona-string->chord-names s #:key C4)) ;; --------------------------------------------------------- (module+ main (command-line/file-suffix-bidirectional #:program "diatonic-inversion-chord-names-in-C" #:input-suffix ".toki-pona.txt" #:output-suffix ".diatonic-inversion-chord-names-in-C.txt" #:force (λ (ip op) (call-with-output-file* op (λ (out) (displayln (toki-pona-string->chord-names-in-C (file->string ip)) out)) #:exists 'replace)) #:check (λ (ip op) (check-equal? (toki-pona-string->chord-names-in-C (file->string ip)) (string-trim (file->string op)))) #:infer (λ (ip op) (call-with-output-file* op (λ (out) (displayln (toki-pona-string->chord-names-in-C (file->string ip)) out)) #:exists 'error))))
null
https://raw.githubusercontent.com/AlexKnauth/toki-pi-kalama-musi/b8a892f67fb5a2e370e982afa2c5c0ed2a8a3a44/racket/toki-pi-kalama-musi-lib/diatonic/inversion/chord-names-in-C.rkt
racket
--------------------------------------------------------- toki-pona-string->chord-names-in-C : String -> String ---------------------------------------------------------
#lang racket/base (provide toki-pona-string->chord-names-in-C) (require (only-in (submod music/data/note/note example) C4) "chord-names.rkt") (module+ main (require racket/file racket/string rackunit "../../common/command-line.rkt")) (module+ test (require racket/file racket/string racket/runtime-path rackunit) (define-runtime-path introduction.toki-pona.txt "../../../../examples/introduction.toki-pona.txt") (define-runtime-path introduction.diatonic-inversion-chord-names-in-C.txt "../../../../examples/introduction.diatonic-inversion-chord-names-in-C.txt")) (module+ test (check-equal? (toki-pona-string->chord-names-in-C (file->string introduction.toki-pona.txt)) (string-trim (file->string introduction.diatonic-inversion-chord-names-in-C.txt))) ) (define (toki-pona-string->chord-names-in-C s) (toki-pona-string->chord-names s #:key C4)) (module+ main (command-line/file-suffix-bidirectional #:program "diatonic-inversion-chord-names-in-C" #:input-suffix ".toki-pona.txt" #:output-suffix ".diatonic-inversion-chord-names-in-C.txt" #:force (λ (ip op) (call-with-output-file* op (λ (out) (displayln (toki-pona-string->chord-names-in-C (file->string ip)) out)) #:exists 'replace)) #:check (λ (ip op) (check-equal? (toki-pona-string->chord-names-in-C (file->string ip)) (string-trim (file->string op)))) #:infer (λ (ip op) (call-with-output-file* op (λ (out) (displayln (toki-pona-string->chord-names-in-C (file->string ip)) out)) #:exists 'error))))
29198d6461ea2f41c9e4c9df0f491e949aeec68fbc64d94cb858c0066e66194e
skanev/playground
80.scm
SICP exercise 2.80 ; Define a generic predicate = zero ? that tests if its argument is zero , and ; instal it in the generic artihmetic package. The operation should work for ; ordinary numbers, rational numbers, and complex numbers. ; It would have been awesome if we could base this on the previous exercise. ; Our type system, however, unboxes the type tags and we cannot directly ; delegate to equ?. Unfortunatelly, we need to implement it ourselves. Again, ; we shall define it in a separate package. The solution, due to Racket ; scoping rules, is at the end. We start with the arithmetic package. First , let 's start with the dispatch table . (define table (make-hash)) (define (put op type item) (hash-set! table (list op type) item)) (define (get op type) (hash-ref table (list op type))) ; Now the procedures we need for the type system: (define (attach-tag type-tag contents) (cons type-tag contents)) (define (type-tag datum) (if (pair? datum) (car datum) (error "Bad tagged datum - TYPE-TAG" datum))) (define (contents datum) (if (pair? datum) (cdr datum) (error "Bad tagged datum - CONTENTS" datum))) (define (apply-generic op . args) (let ((type-tags (map type-tag args))) (let ((proc (get op type-tags))) (if proc (apply proc (map contents args)) (error "No method for these types - APPLY-GENERIC" (list op type-tags)))))) ; Some auxilary functions: (define (square a) (* a a)) ; Now the generic arithmemtic procedures: (define (add x y) (apply-generic 'add x y)) (define (sub x y) (apply-generic 'sub x y)) (define (mul x y) (apply-generic 'mul x y)) (define (div x y) (apply-generic 'div x y)) ; And now - the scheme number package: (define (install-scheme-number-package) (define (tag x) (attach-tag 'scheme-number x)) (put 'add '(scheme-number scheme-number) (lambda (x y) (tag (+ x y)))) (put 'sub '(scheme-number scheme-number) (lambda (x y) (tag (- x y)))) (put 'mul '(scheme-number scheme-number) (lambda (x y) (tag (* x y)))) (put 'div '(scheme-number scheme-number) (lambda (x y) (tag (/ x y)))) (put 'make 'scheme-number (lambda (x) (tag x))) 'done) (define (make-scheme-number n) ((get 'make 'scheme-number) n)) ; The next one is the rational numbers: (define (install-rational-package) (define (numer x) (car x)) (define (denom x) (cdr x)) (define (make-rat n d) (let ((g (gcd n d))) (cons (/ n g) (/ d g)))) (define (add-rat x y) (make-rat (+ (* (numer x) (denom y)) (* (numer y) (denom x))) (* (denom x) (denom y)))) (define (sub-rat x y) (make-rat (- (* (numer x) (denom y)) (* (numer y) (denom x))) (* (denom x) (denom y)))) (define (mul-rat x y) (make-rat (* (numer x) (numer y)) (* (denom x) (denom y)))) (define (div-rat x y) (make-rat (* (numer x) (denom y)) (* (denom x) (numer y)))) (define (tag x) (attach-tag 'rational x)) (put 'add '(rational rational) (lambda (x y) (tag (add-rat x y)))) (put 'sub '(rational rational) (lambda (x y) (tag (sub-rat x y)))) (put 'mul '(rational rational) (lambda (x y) (tag (mul-rat x y)))) (put 'div '(rational rational) (lambda (x y) (tag (div-rat x y)))) (put 'make 'rational (lambda (n d) (tag (make-rat n d)))) 'done) (define (make-rational n d) ((get 'make 'rational) n d)) ; Now we need the complex numbers. They are trickier. We start with the ; selector procedures: (define (real-part z) (apply-generic 'real-part z)) (define (imag-part z) (apply-generic 'imag-part z)) (define (magnitude z) (apply-generic 'magnitude z)) (define (angle z) (apply-generic 'angle z)) (define (make-from-real-imag x y) ((get 'make-from-real-imag 'rectangular) x y)) (define (make-from-mag-ang r a) ((get 'make-from-mag-ang 'polar) r a)) ; They are followed by the rectangular package: (define (install-rectangular-package) (define (real-part z) (car z)) (define (imag-part z) (cdr z)) (define (make-from-real-imag x y) (cons x y)) (define (magnitude z) (sqrt (+ (square (real-part z)) (square (imag-part z))))) (define (angle z) (atan (imag-part z) (real-part z))) (define (make-from-mag-ang r a) (cons (* r (cos a)) (* r (sin a)))) (define (tag x) (attach-tag 'rectangular x)) (put 'real-part '(rectangular) real-part) (put 'imag-part '(rectangular) imag-part) (put 'angle '(rectangular) angle) (put 'magnitude '(rectangular) magnitude) (put 'make-from-real-imag 'rectangular (lambda (x y) (tag (make-from-real-imag x y)))) (put 'make-from-mag-ang 'rectangular (lambda (r a) (tag (make-from-mag-ang r a)))) 'done) Second , the polar package : (define (install-polar-package) (define (magnitude z) (car z)) (define (angle z) (cdr z)) (define (make-from-mag-ang r a) (cons r a)) (define (real-part z) (* (magnitude z) (cos (angle z)))) (define (imag-part z) (* (magnitude z) (sin (angle z)))) (define (make-from-real-imag x y) (cons (sqrt (+ (square x) (square y))) (atan y x))) (define (tag x) (attach-tag 'polar x)) (put 'real-part '(polar) real-part) (put 'imag-part '(polar) imag-part) (put 'magnitude '(polar) magnitude) (put 'angle '(polar) angle) (put 'make-from-real-imag 'polar (lambda (x y) (tag (make-from-real-imag x y)))) (put 'make-from-mag-ang 'polar (lambda (r a) (tag (make-from-mag-ang r a)))) 'done) ; And finally, the complex package: (define (install-complex-package) (define (make-from-real-imag x y) ((get 'make-from-real-imag 'rectangular) x y)) (define (make-from-mag-ang r a) ((get 'make-from-mag-ang 'polar) r a)) (define (add-complex z1 z2) (make-from-real-imag (+ (real-part z1) (real-part z2)) (+ (imag-part z1) (imag-part z2)))) (define (sub-complex z1 z2) (make-from-real-imag (- (real-part z1) (real-part z2)) (- (imag-part z1) (imag-part z2)))) (define (mul-complex z1 z2) (make-from-mag-ang (* (magnitude z1) (magnitude z2)) (+ (angle z1) (angle z2)))) (define (div-complex z1 z2) (make-from-mag-ang (/ (magnitude z1) (magnitude z2)) (- (angle z1) (angle z2)))) (define (tag x) (attach-tag 'complex x)) (put 'real-part '(complex) real-part) (put 'imag-part '(complex) imag-part) (put 'magnitude '(complex) magnitude) (put 'angle '(complex) angle) (put 'add '(complex complex) (lambda (z1 z2) (tag (add-complex z1 z2)))) (put 'sub '(complex complex) (lambda (z1 z2) (tag (sub-complex z1 z2)))) (put 'mul '(complex complex) (lambda (z1 z2) (tag (mul-complex z1 z2)))) (put 'div '(complex complex) (lambda (z1 z2) (tag (div-complex z1 z2)))) (put 'make-from-real-imag 'complex (lambda (x y) (tag (make-from-real-imag x y)))) (put 'make-from-mag-ang 'complex (lambda (r a) (tag (make-from-mag-ang r a)))) 'done) (define (make-complex-from-real-imag x y) ((get 'make-from-real-imag 'complex) x y)) (define (make-complex-from-mag-ang r a) ((get 'make-from-mag-ang 'complex) r a)) ; Finally, we install the packages: (install-scheme-number-package) (install-rational-package) (install-rectangular-package) (install-polar-package) (install-complex-package) ; Finally, the solution. Note that, again, it is slightly hacky because the ; rational package does not expose enough interface to have a clean level of ; abstraction. We end up having to compare representations. (define (install-=zero?-package) (put '=zero? '(scheme-number) (lambda (x) (= x 0))) (put '=zero? '(rational) (lambda (x) (equal? x (contents (make-rational 0 1))))) (put '=zero? '(complex) (lambda (z) (and (= (real-part z) 0) (= (imag-part z) 0)))) 'done) (define (=zero? x) (apply-generic '=zero? x)) (install-=zero?-package)
null
https://raw.githubusercontent.com/skanev/playground/d88e53a7f277b35041c2f709771a0b96f993b310/scheme/sicp/02/80.scm
scheme
instal it in the generic artihmetic package. The operation should work for ordinary numbers, rational numbers, and complex numbers. It would have been awesome if we could base this on the previous exercise. Our type system, however, unboxes the type tags and we cannot directly delegate to equ?. Unfortunatelly, we need to implement it ourselves. Again, we shall define it in a separate package. The solution, due to Racket scoping rules, is at the end. We start with the arithmetic package. Now the procedures we need for the type system: Some auxilary functions: Now the generic arithmemtic procedures: And now - the scheme number package: The next one is the rational numbers: Now we need the complex numbers. They are trickier. We start with the selector procedures: They are followed by the rectangular package: And finally, the complex package: Finally, we install the packages: Finally, the solution. Note that, again, it is slightly hacky because the rational package does not expose enough interface to have a clean level of abstraction. We end up having to compare representations.
SICP exercise 2.80 Define a generic predicate = zero ? that tests if its argument is zero , and First , let 's start with the dispatch table . (define table (make-hash)) (define (put op type item) (hash-set! table (list op type) item)) (define (get op type) (hash-ref table (list op type))) (define (attach-tag type-tag contents) (cons type-tag contents)) (define (type-tag datum) (if (pair? datum) (car datum) (error "Bad tagged datum - TYPE-TAG" datum))) (define (contents datum) (if (pair? datum) (cdr datum) (error "Bad tagged datum - CONTENTS" datum))) (define (apply-generic op . args) (let ((type-tags (map type-tag args))) (let ((proc (get op type-tags))) (if proc (apply proc (map contents args)) (error "No method for these types - APPLY-GENERIC" (list op type-tags)))))) (define (square a) (* a a)) (define (add x y) (apply-generic 'add x y)) (define (sub x y) (apply-generic 'sub x y)) (define (mul x y) (apply-generic 'mul x y)) (define (div x y) (apply-generic 'div x y)) (define (install-scheme-number-package) (define (tag x) (attach-tag 'scheme-number x)) (put 'add '(scheme-number scheme-number) (lambda (x y) (tag (+ x y)))) (put 'sub '(scheme-number scheme-number) (lambda (x y) (tag (- x y)))) (put 'mul '(scheme-number scheme-number) (lambda (x y) (tag (* x y)))) (put 'div '(scheme-number scheme-number) (lambda (x y) (tag (/ x y)))) (put 'make 'scheme-number (lambda (x) (tag x))) 'done) (define (make-scheme-number n) ((get 'make 'scheme-number) n)) (define (install-rational-package) (define (numer x) (car x)) (define (denom x) (cdr x)) (define (make-rat n d) (let ((g (gcd n d))) (cons (/ n g) (/ d g)))) (define (add-rat x y) (make-rat (+ (* (numer x) (denom y)) (* (numer y) (denom x))) (* (denom x) (denom y)))) (define (sub-rat x y) (make-rat (- (* (numer x) (denom y)) (* (numer y) (denom x))) (* (denom x) (denom y)))) (define (mul-rat x y) (make-rat (* (numer x) (numer y)) (* (denom x) (denom y)))) (define (div-rat x y) (make-rat (* (numer x) (denom y)) (* (denom x) (numer y)))) (define (tag x) (attach-tag 'rational x)) (put 'add '(rational rational) (lambda (x y) (tag (add-rat x y)))) (put 'sub '(rational rational) (lambda (x y) (tag (sub-rat x y)))) (put 'mul '(rational rational) (lambda (x y) (tag (mul-rat x y)))) (put 'div '(rational rational) (lambda (x y) (tag (div-rat x y)))) (put 'make 'rational (lambda (n d) (tag (make-rat n d)))) 'done) (define (make-rational n d) ((get 'make 'rational) n d)) (define (real-part z) (apply-generic 'real-part z)) (define (imag-part z) (apply-generic 'imag-part z)) (define (magnitude z) (apply-generic 'magnitude z)) (define (angle z) (apply-generic 'angle z)) (define (make-from-real-imag x y) ((get 'make-from-real-imag 'rectangular) x y)) (define (make-from-mag-ang r a) ((get 'make-from-mag-ang 'polar) r a)) (define (install-rectangular-package) (define (real-part z) (car z)) (define (imag-part z) (cdr z)) (define (make-from-real-imag x y) (cons x y)) (define (magnitude z) (sqrt (+ (square (real-part z)) (square (imag-part z))))) (define (angle z) (atan (imag-part z) (real-part z))) (define (make-from-mag-ang r a) (cons (* r (cos a)) (* r (sin a)))) (define (tag x) (attach-tag 'rectangular x)) (put 'real-part '(rectangular) real-part) (put 'imag-part '(rectangular) imag-part) (put 'angle '(rectangular) angle) (put 'magnitude '(rectangular) magnitude) (put 'make-from-real-imag 'rectangular (lambda (x y) (tag (make-from-real-imag x y)))) (put 'make-from-mag-ang 'rectangular (lambda (r a) (tag (make-from-mag-ang r a)))) 'done) Second , the polar package : (define (install-polar-package) (define (magnitude z) (car z)) (define (angle z) (cdr z)) (define (make-from-mag-ang r a) (cons r a)) (define (real-part z) (* (magnitude z) (cos (angle z)))) (define (imag-part z) (* (magnitude z) (sin (angle z)))) (define (make-from-real-imag x y) (cons (sqrt (+ (square x) (square y))) (atan y x))) (define (tag x) (attach-tag 'polar x)) (put 'real-part '(polar) real-part) (put 'imag-part '(polar) imag-part) (put 'magnitude '(polar) magnitude) (put 'angle '(polar) angle) (put 'make-from-real-imag 'polar (lambda (x y) (tag (make-from-real-imag x y)))) (put 'make-from-mag-ang 'polar (lambda (r a) (tag (make-from-mag-ang r a)))) 'done) (define (install-complex-package) (define (make-from-real-imag x y) ((get 'make-from-real-imag 'rectangular) x y)) (define (make-from-mag-ang r a) ((get 'make-from-mag-ang 'polar) r a)) (define (add-complex z1 z2) (make-from-real-imag (+ (real-part z1) (real-part z2)) (+ (imag-part z1) (imag-part z2)))) (define (sub-complex z1 z2) (make-from-real-imag (- (real-part z1) (real-part z2)) (- (imag-part z1) (imag-part z2)))) (define (mul-complex z1 z2) (make-from-mag-ang (* (magnitude z1) (magnitude z2)) (+ (angle z1) (angle z2)))) (define (div-complex z1 z2) (make-from-mag-ang (/ (magnitude z1) (magnitude z2)) (- (angle z1) (angle z2)))) (define (tag x) (attach-tag 'complex x)) (put 'real-part '(complex) real-part) (put 'imag-part '(complex) imag-part) (put 'magnitude '(complex) magnitude) (put 'angle '(complex) angle) (put 'add '(complex complex) (lambda (z1 z2) (tag (add-complex z1 z2)))) (put 'sub '(complex complex) (lambda (z1 z2) (tag (sub-complex z1 z2)))) (put 'mul '(complex complex) (lambda (z1 z2) (tag (mul-complex z1 z2)))) (put 'div '(complex complex) (lambda (z1 z2) (tag (div-complex z1 z2)))) (put 'make-from-real-imag 'complex (lambda (x y) (tag (make-from-real-imag x y)))) (put 'make-from-mag-ang 'complex (lambda (r a) (tag (make-from-mag-ang r a)))) 'done) (define (make-complex-from-real-imag x y) ((get 'make-from-real-imag 'complex) x y)) (define (make-complex-from-mag-ang r a) ((get 'make-from-mag-ang 'complex) r a)) (install-scheme-number-package) (install-rational-package) (install-rectangular-package) (install-polar-package) (install-complex-package) (define (install-=zero?-package) (put '=zero? '(scheme-number) (lambda (x) (= x 0))) (put '=zero? '(rational) (lambda (x) (equal? x (contents (make-rational 0 1))))) (put '=zero? '(complex) (lambda (z) (and (= (real-part z) 0) (= (imag-part z) 0)))) 'done) (define (=zero? x) (apply-generic '=zero? x)) (install-=zero?-package)
ffa5ad2ee6f998a830b7fe2a9e1f73cd8838d19a0b9d096bdef1d60e0a9d4b19
nixeagle/nisp
util.lisp
(defpackage #:nisp.fbi.util (:use :cl :iterate) (:export #:make-keyword)) (in-package :nisp.fbi.util) (defun make-keyword (string) "Convert STRING to a keyword (uppercased)." (declare (type string string)) (intern (string-upcase string) :keyword))
null
https://raw.githubusercontent.com/nixeagle/nisp/680b40b3b9ea4c33db0455ac73cbe3756afdbb1e/fbi/util.lisp
lisp
(defpackage #:nisp.fbi.util (:use :cl :iterate) (:export #:make-keyword)) (in-package :nisp.fbi.util) (defun make-keyword (string) "Convert STRING to a keyword (uppercased)." (declare (type string string)) (intern (string-upcase string) :keyword))
a9d2a5961a062bceefb4f1d0f2e72f5f3cdb8f6db61c4186c5c974cebfdf51dc
billstclair/trubanc-lisp
md5.lisp
;;;; This file implements The MD5 Message-Digest Algorithm, as defined in RFC 1321 by , published April 1992 . ;;;; It was written by , with copious input from the cmucl - help mailing - list hosted at cons.org , in November 2001 and ;;;; has been placed into the public domain. ;;;; $ I d : md5.lisp , v 1.3 2003/09/16 12:07:39 crhodes Exp $ ;;;; ;;;; While the implementation should work on all conforming Common Lisp implementations , it has only been optimized for CMU CL , ;;;; where it achieved comparable performance to the standard md5sum utility ( within a factor of 1.5 or less on iA32 and UltraSparc ;;;; hardware). ;;;; ;;;; Since the implementation makes heavy use of arithmetic on ( unsigned - byte 32 ) numbers , acceptable performance is likely only on CL implementations that support unboxed arithmetic on such numbers in some form . For other CL implementations a 16bit implementation of MD5 is probably more suitable . ;;;; ;;;; The code implements correct operation for files of unbounded size ;;;; as is, at the cost of having to do a single generic integer ;;;; addition for each call to update-md5-state. If you call ;;;; update-md5-state frequently with little data, this can pose a ;;;; performance problem. If you can live with a size restriction of 512 MB , then you can enable fast fixnum arithmetic by putting ;;;; :md5-small-length onto *features* prior to compiling this file. ;;;; ;;;; This software is "as is", and has no warranty of any kind. The ;;;; authors assume no responsibility for the consequences of any use ;;;; of this software. (in-package :crypto) ;;; Section 3.4: Table T (eval-when (:compile-toplevel :load-toplevel :execute) (defparameter *t* (make-array 64 :element-type '(unsigned-byte 32) :initial-contents (loop for i from 1 to 64 collect (truncate (* 4294967296 (abs (sin (float i 0.0d0))))))))) ;;; Section 3.3: (Initial) MD5 Working Set (define-digest-registers (md5 :endian :little) (a #x67452301) (b #xefcdab89) (c #x98badcfe) (d #x10325476)) (defconst +pristine-md5-registers+ (initial-md5-regs)) Section 3.4 : Operation on 16 - Word Blocks (macrolet ((with-md5-round ((op block) &rest clauses) (loop for (a b c d k s i) in clauses collect `(setq ,a (mod32+ ,b (rol32 (mod32+ (mod32+ ,a (,op ,b ,c ,d)) (mod32+ (aref ,block ,k) ,(aref *t* (1- i)))) ,s))) into result finally (return `(progn ,@result))))) (defun update-md5-block (regs block) "This is the core part of the MD5 algorithm. It takes a complete 16 word block of input, and updates the working state in A, B, C, and D accordingly." (declare (type md5-regs regs) (type (simple-array (unsigned-byte 32) (16)) block) #.(burn-baby-burn)) (let ((a (md5-regs-a regs)) (b (md5-regs-b regs)) (c (md5-regs-c regs)) (d (md5-regs-d regs))) (declare (type (unsigned-byte 32) a b c d)) (flet ((f (x y z) (declare (type (unsigned-byte 32) x y z)) #+cmu (kernel:32bit-logical-xor z (kernel:32bit-logical-and x (kernel:32bit-logical-xor y z))) #-cmu (logxor z (logand x (logxor y z)))) (g (x y z) (declare (type (unsigned-byte 32) x y z)) #+cmu (kernel:32bit-logical-xor y (kernel:32bit-logical-and z (kernel:32bit-logical-xor x y))) #-cmu (logxor y (logand z (logxor x y)))) (h (x y z) (declare (type (unsigned-byte 32) x y z)) #+cmu (kernel:32bit-logical-xor x (kernel:32bit-logical-xor y z)) #-cmu (logxor x y z)) (i (x y z) (declare (type (unsigned-byte 32) x y z)) #+cmu (kernel:32bit-logical-xor y (kernel:32bit-logical-orc2 x z)) #-cmu (ldb (byte 32 0) (logxor y (logorc2 x z))))) (declare (inline f g h i)) ;; Round 1 (with-md5-round (f block) (A B C D 0 7 1)(D A B C 1 12 2)(C D A B 2 17 3)(B C D A 3 22 4) (A B C D 4 7 5)(D A B C 5 12 6)(C D A B 6 17 7)(B C D A 7 22 8) (A B C D 8 7 9)(D A B C 9 12 10)(C D A B 10 17 11)(B C D A 11 22 12) (A B C D 12 7 13)(D A B C 13 12 14)(C D A B 14 17 15)(B C D A 15 22 16)) ;; Round 2 (with-md5-round (g block) (A B C D 1 5 17)(D A B C 6 9 18)(C D A B 11 14 19)(B C D A 0 20 20) (A B C D 5 5 21)(D A B C 10 9 22)(C D A B 15 14 23)(B C D A 4 20 24) (A B C D 9 5 25)(D A B C 14 9 26)(C D A B 3 14 27)(B C D A 8 20 28) (A B C D 13 5 29)(D A B C 2 9 30)(C D A B 7 14 31)(B C D A 12 20 32)) ;; Round 3 (with-md5-round (h block) (A B C D 5 4 33)(D A B C 8 11 34)(C D A B 11 16 35)(B C D A 14 23 36) (A B C D 1 4 37)(D A B C 4 11 38)(C D A B 7 16 39)(B C D A 10 23 40) (A B C D 13 4 41)(D A B C 0 11 42)(C D A B 3 16 43)(B C D A 6 23 44) (A B C D 9 4 45)(D A B C 12 11 46)(C D A B 15 16 47)(B C D A 2 23 48)) ;; Round 4 (with-md5-round (i block) (A B C D 0 6 49)(D A B C 7 10 50)(C D A B 14 15 51)(B C D A 5 21 52) (A B C D 12 6 53)(D A B C 3 10 54)(C D A B 10 15 55)(B C D A 1 21 56) (A B C D 8 6 57)(D A B C 15 10 58)(C D A B 6 15 59)(B C D A 13 21 60) (A B C D 4 6 61)(D A B C 11 10 62)(C D A B 2 15 63)(B C D A 9 21 64)) ;; Update and return (setf (md5-regs-a regs) (mod32+ (md5-regs-a regs) a) (md5-regs-b regs) (mod32+ (md5-regs-b regs) b) (md5-regs-c regs) (mod32+ (md5-regs-c regs) c) (md5-regs-d regs) (mod32+ (md5-regs-d regs) d)) regs))) MACROLET ;;; Mid-Level Drivers (defstruct (md5 (:constructor %make-md5-digest) (:constructor %make-md5-state (regs amount block buffer buffer-index)) (:copier nil)) (regs (initial-md5-regs) :type md5-regs :read-only t) (amount 0 :type (unsigned-byte 64)) (block (make-array 16 :element-type '(unsigned-byte 32)) :type (simple-array (unsigned-byte 32) (16)) :read-only t) (buffer (make-array 64 :element-type '(unsigned-byte 8)) :type (simple-array (unsigned-byte 8) (64)) :read-only t) (buffer-index 0 :type (integer 0 63))) (defmethod reinitialize-instance ((state md5) &rest initargs) (declare (ignore initargs)) (replace (md5-regs state) +pristine-md5-registers+) (setf (md5-amount state) 0 (md5-buffer-index state) 0) state) (defmethod copy-digest ((state md5)) (%make-md5-state (copy-seq (md5-regs state)) (md5-amount state) (copy-seq (md5-block state)) (copy-seq (md5-buffer state)) (md5-buffer-index state))) (define-digest-updater md5 "Update the given md5-state from sequence, which is either a simple-string or a simple-array with element-type (unsigned-byte 8), bounded by start and end, which must be numeric bounding-indices." (let* ((regs (md5-regs state)) (block (md5-block state)) (buffer (md5-buffer state)) (buffer-index (md5-buffer-index state)) (length (- end start))) (declare (type md5-regs regs) (type fixnum length) (type (integer 0 63) buffer-index) (type (simple-array (unsigned-byte 32) (16)) block) (type (simple-array (unsigned-byte 8) (64)) buffer)) ;; Handle old rest (unless (zerop buffer-index) (let ((amount (min (- 64 buffer-index) length))) (declare (type (integer 0 63) amount)) (copy-to-buffer sequence start amount buffer buffer-index) (setq start (the fixnum (+ start amount))) (let ((new-index (mod (+ buffer-index amount) 64))) (when (zerop new-index) (fill-block-ub8-le block buffer 0) (update-md5-block regs block)) (when (>= start end) (setf (md5-buffer-index state) new-index) (incf (md5-amount state) length) (return-from update-digest state))))) (loop for offset of-type index from start below end by 64 until (< (- end offset) 64) do (fill-block-ub8-le block sequence offset) (update-md5-block regs block) finally (let ((amount (- end offset))) (unless (zerop amount) (copy-to-buffer sequence offset amount buffer 0)) (setf (md5-buffer-index state) amount))) (incf (md5-amount state) length) state)) (define-digest-finalizer md5 16 "If the given md5-state has not already been finalized, finalize it, by processing any remaining input in its buffer, with suitable padding and appended bit-length, as specified by the MD5 standard. The resulting MD5 message-digest is returned as an array of sixteen (unsigned-byte 8) values. Calling UPDATE-MD5-STATE after a call to FINALIZE-MD5-STATE results in unspecified behaviour." (let ((regs (md5-regs state)) (block (md5-block state)) (buffer (md5-buffer state)) (buffer-index (md5-buffer-index state)) (total-length (* 8 (md5-amount state)))) (declare (type md5-regs regs) (type (integer 0 63) buffer-index) (type (simple-array (unsigned-byte 32) (16)) block) (type (simple-array (unsigned-byte 8) (64)) buffer)) Add mandatory bit 1 padding (setf (aref buffer buffer-index) #x80) ;; Fill with 0 bit padding (loop for index of-type (integer 0 64) from (1+ buffer-index) below 64 do (setf (aref buffer index) #x00)) (fill-block-ub8-le block buffer 0) Flush block first if length would n't fit (when (>= buffer-index 56) (update-md5-block regs block) ;; Create new fully 0 padded block (loop for index of-type (integer 0 16) from 0 below 16 do (setf (aref block index) #x00000000))) ;; Add 64bit message bit length (store-data-length block total-length 14) ;; Flush last block (update-md5-block regs block) ;; Done, remember digest for later calls (finalize-registers state regs))) (defdigest md5 :digest-length 16)
null
https://raw.githubusercontent.com/billstclair/trubanc-lisp/5436d2eca5b1ed10bc47eec7080f6cb90f98ca65/systems/ironclad_0.26/md5.lisp
lisp
This file implements The MD5 Message-Digest Algorithm, as defined in has been placed into the public domain. While the implementation should work on all conforming Common where it achieved comparable performance to the standard md5sum hardware). Since the implementation makes heavy use of arithmetic on The code implements correct operation for files of unbounded size as is, at the cost of having to do a single generic integer addition for each call to update-md5-state. If you call update-md5-state frequently with little data, this can pose a performance problem. If you can live with a size restriction of :md5-small-length onto *features* prior to compiling this file. This software is "as is", and has no warranty of any kind. The authors assume no responsibility for the consequences of any use of this software. Section 3.4: Table T Section 3.3: (Initial) MD5 Working Set Round 1 Round 2 Round 3 Round 4 Update and return Mid-Level Drivers Handle old rest Fill with 0 bit padding Create new fully 0 padded block Add 64bit message bit length Flush last block Done, remember digest for later calls
RFC 1321 by , published April 1992 . It was written by , with copious input from the cmucl - help mailing - list hosted at cons.org , in November 2001 and $ I d : md5.lisp , v 1.3 2003/09/16 12:07:39 crhodes Exp $ Lisp implementations , it has only been optimized for CMU CL , utility ( within a factor of 1.5 or less on iA32 and UltraSparc ( unsigned - byte 32 ) numbers , acceptable performance is likely only on CL implementations that support unboxed arithmetic on such numbers in some form . For other CL implementations a 16bit implementation of MD5 is probably more suitable . 512 MB , then you can enable fast fixnum arithmetic by putting (in-package :crypto) (eval-when (:compile-toplevel :load-toplevel :execute) (defparameter *t* (make-array 64 :element-type '(unsigned-byte 32) :initial-contents (loop for i from 1 to 64 collect (truncate (* 4294967296 (abs (sin (float i 0.0d0))))))))) (define-digest-registers (md5 :endian :little) (a #x67452301) (b #xefcdab89) (c #x98badcfe) (d #x10325476)) (defconst +pristine-md5-registers+ (initial-md5-regs)) Section 3.4 : Operation on 16 - Word Blocks (macrolet ((with-md5-round ((op block) &rest clauses) (loop for (a b c d k s i) in clauses collect `(setq ,a (mod32+ ,b (rol32 (mod32+ (mod32+ ,a (,op ,b ,c ,d)) (mod32+ (aref ,block ,k) ,(aref *t* (1- i)))) ,s))) into result finally (return `(progn ,@result))))) (defun update-md5-block (regs block) "This is the core part of the MD5 algorithm. It takes a complete 16 word block of input, and updates the working state in A, B, C, and D accordingly." (declare (type md5-regs regs) (type (simple-array (unsigned-byte 32) (16)) block) #.(burn-baby-burn)) (let ((a (md5-regs-a regs)) (b (md5-regs-b regs)) (c (md5-regs-c regs)) (d (md5-regs-d regs))) (declare (type (unsigned-byte 32) a b c d)) (flet ((f (x y z) (declare (type (unsigned-byte 32) x y z)) #+cmu (kernel:32bit-logical-xor z (kernel:32bit-logical-and x (kernel:32bit-logical-xor y z))) #-cmu (logxor z (logand x (logxor y z)))) (g (x y z) (declare (type (unsigned-byte 32) x y z)) #+cmu (kernel:32bit-logical-xor y (kernel:32bit-logical-and z (kernel:32bit-logical-xor x y))) #-cmu (logxor y (logand z (logxor x y)))) (h (x y z) (declare (type (unsigned-byte 32) x y z)) #+cmu (kernel:32bit-logical-xor x (kernel:32bit-logical-xor y z)) #-cmu (logxor x y z)) (i (x y z) (declare (type (unsigned-byte 32) x y z)) #+cmu (kernel:32bit-logical-xor y (kernel:32bit-logical-orc2 x z)) #-cmu (ldb (byte 32 0) (logxor y (logorc2 x z))))) (declare (inline f g h i)) (with-md5-round (f block) (A B C D 0 7 1)(D A B C 1 12 2)(C D A B 2 17 3)(B C D A 3 22 4) (A B C D 4 7 5)(D A B C 5 12 6)(C D A B 6 17 7)(B C D A 7 22 8) (A B C D 8 7 9)(D A B C 9 12 10)(C D A B 10 17 11)(B C D A 11 22 12) (A B C D 12 7 13)(D A B C 13 12 14)(C D A B 14 17 15)(B C D A 15 22 16)) (with-md5-round (g block) (A B C D 1 5 17)(D A B C 6 9 18)(C D A B 11 14 19)(B C D A 0 20 20) (A B C D 5 5 21)(D A B C 10 9 22)(C D A B 15 14 23)(B C D A 4 20 24) (A B C D 9 5 25)(D A B C 14 9 26)(C D A B 3 14 27)(B C D A 8 20 28) (A B C D 13 5 29)(D A B C 2 9 30)(C D A B 7 14 31)(B C D A 12 20 32)) (with-md5-round (h block) (A B C D 5 4 33)(D A B C 8 11 34)(C D A B 11 16 35)(B C D A 14 23 36) (A B C D 1 4 37)(D A B C 4 11 38)(C D A B 7 16 39)(B C D A 10 23 40) (A B C D 13 4 41)(D A B C 0 11 42)(C D A B 3 16 43)(B C D A 6 23 44) (A B C D 9 4 45)(D A B C 12 11 46)(C D A B 15 16 47)(B C D A 2 23 48)) (with-md5-round (i block) (A B C D 0 6 49)(D A B C 7 10 50)(C D A B 14 15 51)(B C D A 5 21 52) (A B C D 12 6 53)(D A B C 3 10 54)(C D A B 10 15 55)(B C D A 1 21 56) (A B C D 8 6 57)(D A B C 15 10 58)(C D A B 6 15 59)(B C D A 13 21 60) (A B C D 4 6 61)(D A B C 11 10 62)(C D A B 2 15 63)(B C D A 9 21 64)) (setf (md5-regs-a regs) (mod32+ (md5-regs-a regs) a) (md5-regs-b regs) (mod32+ (md5-regs-b regs) b) (md5-regs-c regs) (mod32+ (md5-regs-c regs) c) (md5-regs-d regs) (mod32+ (md5-regs-d regs) d)) regs))) MACROLET (defstruct (md5 (:constructor %make-md5-digest) (:constructor %make-md5-state (regs amount block buffer buffer-index)) (:copier nil)) (regs (initial-md5-regs) :type md5-regs :read-only t) (amount 0 :type (unsigned-byte 64)) (block (make-array 16 :element-type '(unsigned-byte 32)) :type (simple-array (unsigned-byte 32) (16)) :read-only t) (buffer (make-array 64 :element-type '(unsigned-byte 8)) :type (simple-array (unsigned-byte 8) (64)) :read-only t) (buffer-index 0 :type (integer 0 63))) (defmethod reinitialize-instance ((state md5) &rest initargs) (declare (ignore initargs)) (replace (md5-regs state) +pristine-md5-registers+) (setf (md5-amount state) 0 (md5-buffer-index state) 0) state) (defmethod copy-digest ((state md5)) (%make-md5-state (copy-seq (md5-regs state)) (md5-amount state) (copy-seq (md5-block state)) (copy-seq (md5-buffer state)) (md5-buffer-index state))) (define-digest-updater md5 "Update the given md5-state from sequence, which is either a simple-string or a simple-array with element-type (unsigned-byte 8), bounded by start and end, which must be numeric bounding-indices." (let* ((regs (md5-regs state)) (block (md5-block state)) (buffer (md5-buffer state)) (buffer-index (md5-buffer-index state)) (length (- end start))) (declare (type md5-regs regs) (type fixnum length) (type (integer 0 63) buffer-index) (type (simple-array (unsigned-byte 32) (16)) block) (type (simple-array (unsigned-byte 8) (64)) buffer)) (unless (zerop buffer-index) (let ((amount (min (- 64 buffer-index) length))) (declare (type (integer 0 63) amount)) (copy-to-buffer sequence start amount buffer buffer-index) (setq start (the fixnum (+ start amount))) (let ((new-index (mod (+ buffer-index amount) 64))) (when (zerop new-index) (fill-block-ub8-le block buffer 0) (update-md5-block regs block)) (when (>= start end) (setf (md5-buffer-index state) new-index) (incf (md5-amount state) length) (return-from update-digest state))))) (loop for offset of-type index from start below end by 64 until (< (- end offset) 64) do (fill-block-ub8-le block sequence offset) (update-md5-block regs block) finally (let ((amount (- end offset))) (unless (zerop amount) (copy-to-buffer sequence offset amount buffer 0)) (setf (md5-buffer-index state) amount))) (incf (md5-amount state) length) state)) (define-digest-finalizer md5 16 "If the given md5-state has not already been finalized, finalize it, by processing any remaining input in its buffer, with suitable padding and appended bit-length, as specified by the MD5 standard. The resulting MD5 message-digest is returned as an array of sixteen (unsigned-byte 8) values. Calling UPDATE-MD5-STATE after a call to FINALIZE-MD5-STATE results in unspecified behaviour." (let ((regs (md5-regs state)) (block (md5-block state)) (buffer (md5-buffer state)) (buffer-index (md5-buffer-index state)) (total-length (* 8 (md5-amount state)))) (declare (type md5-regs regs) (type (integer 0 63) buffer-index) (type (simple-array (unsigned-byte 32) (16)) block) (type (simple-array (unsigned-byte 8) (64)) buffer)) Add mandatory bit 1 padding (setf (aref buffer buffer-index) #x80) (loop for index of-type (integer 0 64) from (1+ buffer-index) below 64 do (setf (aref buffer index) #x00)) (fill-block-ub8-le block buffer 0) Flush block first if length would n't fit (when (>= buffer-index 56) (update-md5-block regs block) (loop for index of-type (integer 0 16) from 0 below 16 do (setf (aref block index) #x00000000))) (store-data-length block total-length 14) (update-md5-block regs block) (finalize-registers state regs))) (defdigest md5 :digest-length 16)
72ecbfe98f688437c36fd4e2de773d227e3d81c0d2e0f733f0511963c6921726
ronxin/stolzen
container.scm
#lang scheme (define (container) (define hash (make-hash)) (define (put op type item) (hash-set! hash (cons op type) item) ) (define (get op type) (let ((key (cons op type))) (if (hash-has-key? hash key) (hash-ref hash key) false ) ) ) (lambda (name) (cond ((eq? name 'get) get) ((eq? name 'put) put) ((eq? name 'hash) hash) ) ) ) (define storage (container)) (define put (storage 'put)) (define get (storage 'get)) (provide put get)
null
https://raw.githubusercontent.com/ronxin/stolzen/bb13d0a7deea53b65253bb4b61aaf2abe4467f0d/sicp/chapter2/2.5/generic-ops/container.scm
scheme
#lang scheme (define (container) (define hash (make-hash)) (define (put op type item) (hash-set! hash (cons op type) item) ) (define (get op type) (let ((key (cons op type))) (if (hash-has-key? hash key) (hash-ref hash key) false ) ) ) (lambda (name) (cond ((eq? name 'get) get) ((eq? name 'put) put) ((eq? name 'hash) hash) ) ) ) (define storage (container)) (define put (storage 'put)) (define get (storage 'get)) (provide put get)
f923c2960b96089572378c685fea7627cc5b50cd1906ed07265fd9a7ec035e66
Oblosys/proxima
DocTypes_Generated.hs
# LANGUAGE StandaloneDeriving # module DocTypes_Generated where import Common.CommonTypes import Evaluation.DocTypes import Presentation.PresTypes import Data.List import Data.Char import Data.Generics data UserToken = KeyTk String -- StrTk is for keywords, so eq takes the string value into account | IntTk | LIdentTk | UIdentTk | OpTk | SymTk deriving (Show, Eq, Ord, Typeable) type HeliumTypeInfo = ([HeliumMessage],[(String,String)], [(PathDoc, String)]) data HeliumMessage = HMessage [String] | HError [String] [PathDoc] [PathDoc] [PathDoc] deriving (Show, Data, Typeable) deriving instance Data PathDoc deriving instance Typeable PathDoc ----- GENERATED PART STARTS HERE. DO NOT EDIT ON OR BEYOND THIS LINE ----- -------------------------------------------------------------------------- Proxima data type -- -------------------------------------------------------------------------- data Document = RootDoc Root | HoleDocument | ParseErrDocument (ParseError Document EnrichedDoc Node ClipDoc UserToken) deriving (Show, Data, Typeable) data Root = Root IDP List_Decl | HoleRoot | ParseErrRoot (ParseError Document EnrichedDoc Node ClipDoc UserToken) deriving (Show, Data, Typeable) data EnrichedDoc = RootEnr RootE HeliumTypeInfo | HoleEnrichedDoc | ParseErrEnrichedDoc (ParseError Document EnrichedDoc Node ClipDoc UserToken) deriving (Show, Data, Typeable) data RootE = RootE IDP List_Decl List_Decl | HoleRootE | ParseErrRootE (ParseError Document EnrichedDoc Node ClipDoc UserToken) deriving (Show, Data, Typeable) data Decl = Decl IDP IDP IDP IDP Bool Bool Ident Exp | BoardDecl IDP IDP Board | PPPresentationDecl IDP IDP PPPresentation | HoleDecl | ParseErrDecl (ParseError Document EnrichedDoc Node ClipDoc UserToken) deriving (Show, Data, Typeable) data Ident = Ident IDP IDP String | HoleIdent | ParseErrIdent (ParseError Document EnrichedDoc Node ClipDoc UserToken) deriving (Show, Data, Typeable) data Exp = PlusExp IDP Exp Exp | TimesExp IDP Exp Exp | DivExp IDP Exp Exp | PowerExp IDP Exp Exp | BoolExp IDP Bool | IntExp IDP Int | LamExp IDP IDP Ident Exp | AppExp Exp Exp | CaseExp IDP IDP Exp List_Alt | LetExp IDP IDP List_Decl Exp | IdentExp Ident | IfExp IDP IDP IDP Exp Exp Exp | ParenExp IDP IDP Exp | ListExp IDP IDP [IDP] List_Exp | ProductExp IDP IDP [IDP] List_Exp | HoleExp | ParseErrExp (ParseError Document EnrichedDoc Node ClipDoc UserToken) deriving (Show, Data, Typeable) data Alt = Alt IDP IDP Ident Exp | HoleAlt | ParseErrAlt (ParseError Document EnrichedDoc Node ClipDoc UserToken) deriving (Show, Data, Typeable) data Board = Board BoardRow BoardRow BoardRow BoardRow BoardRow BoardRow BoardRow BoardRow | HoleBoard | ParseErrBoard (ParseError Document EnrichedDoc Node ClipDoc UserToken) deriving (Show, Data, Typeable) data BoardRow = BoardRow BoardSquare BoardSquare BoardSquare BoardSquare BoardSquare BoardSquare BoardSquare BoardSquare | HoleBoardRow | ParseErrBoardRow (ParseError Document EnrichedDoc Node ClipDoc UserToken) deriving (Show, Data, Typeable) data BoardSquare = Queen Bool | King Bool | Bishop Bool | Knight Bool | Rook Bool | Pawn Bool | Empty | HoleBoardSquare | ParseErrBoardSquare (ParseError Document EnrichedDoc Node ClipDoc UserToken) deriving (Show, Data, Typeable) data PPPresentation = PPPresentation Bool List_Slide | HolePPPresentation | ParseErrPPPresentation (ParseError Document EnrichedDoc Node ClipDoc UserToken) deriving (Show, Data, Typeable) data Slide = Slide String ItemList | HoleSlide | ParseErrSlide (ParseError Document EnrichedDoc Node ClipDoc UserToken) deriving (Show, Data, Typeable) data ItemList = ItemList ListType List_Item | HoleItemList | ParseErrItemList (ParseError Document EnrichedDoc Node ClipDoc UserToken) deriving (Show, Data, Typeable) data ListType = Bullet | Number | Alpha | HoleListType | ParseErrListType (ParseError Document EnrichedDoc Node ClipDoc UserToken) deriving (Show, Data, Typeable) data Item = StringItem String | HeliumItem Exp | ListItem ItemList | HoleItem | ParseErrItem (ParseError Document EnrichedDoc Node ClipDoc UserToken) deriving (Show, Data, Typeable) data List_Decl = List_Decl ConsList_Decl | HoleList_Decl | ParseErrList_Decl (ParseError Document EnrichedDoc Node ClipDoc UserToken) deriving (Show, Data, Typeable) data List_Alt = List_Alt ConsList_Alt | HoleList_Alt | ParseErrList_Alt (ParseError Document EnrichedDoc Node ClipDoc UserToken) deriving (Show, Data, Typeable) data List_Exp = List_Exp ConsList_Exp | HoleList_Exp | ParseErrList_Exp (ParseError Document EnrichedDoc Node ClipDoc UserToken) deriving (Show, Data, Typeable) data List_Slide = List_Slide ConsList_Slide | HoleList_Slide | ParseErrList_Slide (ParseError Document EnrichedDoc Node ClipDoc UserToken) deriving (Show, Data, Typeable) data List_Item = List_Item ConsList_Item | HoleList_Item | ParseErrList_Item (ParseError Document EnrichedDoc Node ClipDoc UserToken) deriving (Show, Data, Typeable) data ConsList_Decl = Cons_Decl Decl ConsList_Decl | Nil_Decl deriving (Show, Data, Typeable) data ConsList_Alt = Cons_Alt Alt ConsList_Alt | Nil_Alt deriving (Show, Data, Typeable) data ConsList_Exp = Cons_Exp Exp ConsList_Exp | Nil_Exp deriving (Show, Data, Typeable) data ConsList_Slide = Cons_Slide Slide ConsList_Slide | Nil_Slide deriving (Show, Data, Typeable) data ConsList_Item = Cons_Item Item ConsList_Item | Nil_Item deriving (Show, Data, Typeable) -------------------------------------------------------------------------- ClipDoc -- -------------------------------------------------------------------------- data ClipDoc = Clip_Document Document | Clip_Root Root | Clip_EnrichedDoc EnrichedDoc | Clip_RootE RootE | Clip_Decl Decl | Clip_Ident Ident | Clip_Exp Exp | Clip_Alt Alt | Clip_Board Board | Clip_BoardRow BoardRow | Clip_BoardSquare BoardSquare | Clip_PPPresentation PPPresentation | Clip_Slide Slide | Clip_ItemList ItemList | Clip_ListType ListType | Clip_Item Item | Clip_List_Decl List_Decl | Clip_List_Alt List_Alt | Clip_List_Exp List_Exp | Clip_List_Slide List_Slide | Clip_List_Item List_Item | Clip_Bool Bool | Clip_Int Int | Clip_String String | Clip_Float Float | Clip_Nothing deriving (Show, Typeable) -------------------------------------------------------------------------- -- Node -- -------------------------------------------------------------------------- data Node = NoNode | Node_RootDoc Document Path | Node_HoleDocument Document Path | Node_ParseErrDocument Document Path | Node_Root Root Path | Node_HoleRoot Root Path | Node_ParseErrRoot Root Path | Node_RootEnr EnrichedDoc Path | Node_HoleEnrichedDoc EnrichedDoc Path | Node_ParseErrEnrichedDoc EnrichedDoc Path | Node_RootE RootE Path | Node_HoleRootE RootE Path | Node_ParseErrRootE RootE Path | Node_Decl Decl Path | Node_BoardDecl Decl Path | Node_PPPresentationDecl Decl Path | Node_HoleDecl Decl Path | Node_ParseErrDecl Decl Path | Node_Ident Ident Path | Node_HoleIdent Ident Path | Node_ParseErrIdent Ident Path | Node_PlusExp Exp Path | Node_TimesExp Exp Path | Node_DivExp Exp Path | Node_PowerExp Exp Path | Node_BoolExp Exp Path | Node_IntExp Exp Path | Node_LamExp Exp Path | Node_AppExp Exp Path | Node_CaseExp Exp Path | Node_LetExp Exp Path | Node_IdentExp Exp Path | Node_IfExp Exp Path | Node_ParenExp Exp Path | Node_ListExp Exp Path | Node_ProductExp Exp Path | Node_HoleExp Exp Path | Node_ParseErrExp Exp Path | Node_Alt Alt Path | Node_HoleAlt Alt Path | Node_ParseErrAlt Alt Path | Node_Board Board Path | Node_HoleBoard Board Path | Node_ParseErrBoard Board Path | Node_BoardRow BoardRow Path | Node_HoleBoardRow BoardRow Path | Node_ParseErrBoardRow BoardRow Path | Node_Queen BoardSquare Path | Node_King BoardSquare Path | Node_Bishop BoardSquare Path | Node_Knight BoardSquare Path | Node_Rook BoardSquare Path | Node_Pawn BoardSquare Path | Node_Empty BoardSquare Path | Node_HoleBoardSquare BoardSquare Path | Node_ParseErrBoardSquare BoardSquare Path | Node_PPPresentation PPPresentation Path | Node_HolePPPresentation PPPresentation Path | Node_ParseErrPPPresentation PPPresentation Path | Node_Slide Slide Path | Node_HoleSlide Slide Path | Node_ParseErrSlide Slide Path | Node_ItemList ItemList Path | Node_HoleItemList ItemList Path | Node_ParseErrItemList ItemList Path | Node_Bullet ListType Path | Node_Number ListType Path | Node_Alpha ListType Path | Node_HoleListType ListType Path | Node_ParseErrListType ListType Path | Node_StringItem Item Path | Node_HeliumItem Item Path | Node_ListItem Item Path | Node_HoleItem Item Path | Node_ParseErrItem Item Path | Node_List_Decl List_Decl Path | Node_HoleList_Decl List_Decl Path | Node_ParseErrList_Decl List_Decl Path | Node_List_Alt List_Alt Path | Node_HoleList_Alt List_Alt Path | Node_ParseErrList_Alt List_Alt Path | Node_List_Exp List_Exp Path | Node_HoleList_Exp List_Exp Path | Node_ParseErrList_Exp List_Exp Path | Node_List_Slide List_Slide Path | Node_HoleList_Slide List_Slide Path | Node_ParseErrList_Slide List_Slide Path | Node_List_Item List_Item Path | Node_HoleList_Item List_Item Path | Node_ParseErrList_Item List_Item Path deriving Typeable -------------------------------------------------------------------------- -- Show instance for Node -- -------------------------------------------------------------------------- instance Show Node where show NoNode = "NoNode" show (Node_RootDoc _ _) = "Node_RootDoc" show (Node_HoleDocument _ _) = "Node_HoleDocument" show (Node_ParseErrDocument _ _) = "Node_ParseErrDocument" show (Node_Root _ _) = "Node_Root" show (Node_HoleRoot _ _) = "Node_HoleRoot" show (Node_ParseErrRoot _ _) = "Node_ParseErrRoot" show (Node_RootEnr _ _) = "Node_RootEnr" show (Node_HoleEnrichedDoc _ _) = "Node_HoleEnrichedDoc" show (Node_ParseErrEnrichedDoc _ _) = "Node_ParseErrEnrichedDoc" show (Node_RootE _ _) = "Node_RootE" show (Node_HoleRootE _ _) = "Node_HoleRootE" show (Node_ParseErrRootE _ _) = "Node_ParseErrRootE" show (Node_Decl _ _) = "Node_Decl" show (Node_BoardDecl _ _) = "Node_BoardDecl" show (Node_PPPresentationDecl _ _) = "Node_PPPresentationDecl" show (Node_HoleDecl _ _) = "Node_HoleDecl" show (Node_ParseErrDecl _ _) = "Node_ParseErrDecl" show (Node_Ident _ _) = "Node_Ident" show (Node_HoleIdent _ _) = "Node_HoleIdent" show (Node_ParseErrIdent _ _) = "Node_ParseErrIdent" show (Node_PlusExp _ _) = "Node_PlusExp" show (Node_TimesExp _ _) = "Node_TimesExp" show (Node_DivExp _ _) = "Node_DivExp" show (Node_PowerExp _ _) = "Node_PowerExp" show (Node_BoolExp _ _) = "Node_BoolExp" show (Node_IntExp _ _) = "Node_IntExp" show (Node_LamExp _ _) = "Node_LamExp" show (Node_AppExp _ _) = "Node_AppExp" show (Node_CaseExp _ _) = "Node_CaseExp" show (Node_LetExp _ _) = "Node_LetExp" show (Node_IdentExp _ _) = "Node_IdentExp" show (Node_IfExp _ _) = "Node_IfExp" show (Node_ParenExp _ _) = "Node_ParenExp" show (Node_ListExp _ _) = "Node_ListExp" show (Node_ProductExp _ _) = "Node_ProductExp" show (Node_HoleExp _ _) = "Node_HoleExp" show (Node_ParseErrExp _ _) = "Node_ParseErrExp" show (Node_Alt _ _) = "Node_Alt" show (Node_HoleAlt _ _) = "Node_HoleAlt" show (Node_ParseErrAlt _ _) = "Node_ParseErrAlt" show (Node_Board _ _) = "Node_Board" show (Node_HoleBoard _ _) = "Node_HoleBoard" show (Node_ParseErrBoard _ _) = "Node_ParseErrBoard" show (Node_BoardRow _ _) = "Node_BoardRow" show (Node_HoleBoardRow _ _) = "Node_HoleBoardRow" show (Node_ParseErrBoardRow _ _) = "Node_ParseErrBoardRow" show (Node_Queen _ _) = "Node_Queen" show (Node_King _ _) = "Node_King" show (Node_Bishop _ _) = "Node_Bishop" show (Node_Knight _ _) = "Node_Knight" show (Node_Rook _ _) = "Node_Rook" show (Node_Pawn _ _) = "Node_Pawn" show (Node_Empty _ _) = "Node_Empty" show (Node_HoleBoardSquare _ _) = "Node_HoleBoardSquare" show (Node_ParseErrBoardSquare _ _) = "Node_ParseErrBoardSquare" show (Node_PPPresentation _ _) = "Node_PPPresentation" show (Node_HolePPPresentation _ _) = "Node_HolePPPresentation" show (Node_ParseErrPPPresentation _ _) = "Node_ParseErrPPPresentation" show (Node_Slide _ _) = "Node_Slide" show (Node_HoleSlide _ _) = "Node_HoleSlide" show (Node_ParseErrSlide _ _) = "Node_ParseErrSlide" show (Node_ItemList _ _) = "Node_ItemList" show (Node_HoleItemList _ _) = "Node_HoleItemList" show (Node_ParseErrItemList _ _) = "Node_ParseErrItemList" show (Node_Bullet _ _) = "Node_Bullet" show (Node_Number _ _) = "Node_Number" show (Node_Alpha _ _) = "Node_Alpha" show (Node_HoleListType _ _) = "Node_HoleListType" show (Node_ParseErrListType _ _) = "Node_ParseErrListType" show (Node_StringItem _ _) = "Node_StringItem" show (Node_HeliumItem _ _) = "Node_HeliumItem" show (Node_ListItem _ _) = "Node_ListItem" show (Node_HoleItem _ _) = "Node_HoleItem" show (Node_ParseErrItem _ _) = "Node_ParseErrItem" show (Node_List_Decl _ _) = "Node_List_Decl" show (Node_HoleList_Decl _ _) = "Node_HoleList_Decl" show (Node_ParseErrList_Decl _ _) = "Node_ParseErrList_Decl" show (Node_List_Alt _ _) = "Node_List_Alt" show (Node_HoleList_Alt _ _) = "Node_HoleList_Alt" show (Node_ParseErrList_Alt _ _) = "Node_ParseErrList_Alt" show (Node_List_Exp _ _) = "Node_List_Exp" show (Node_HoleList_Exp _ _) = "Node_HoleList_Exp" show (Node_ParseErrList_Exp _ _) = "Node_ParseErrList_Exp" show (Node_List_Slide _ _) = "Node_List_Slide" show (Node_HoleList_Slide _ _) = "Node_HoleList_Slide" show (Node_ParseErrList_Slide _ _) = "Node_ParseErrList_Slide" show (Node_List_Item _ _) = "Node_List_Item" show (Node_HoleList_Item _ _) = "Node_HoleList_Item" show (Node_ParseErrList_Item _ _) = "Node_ParseErrList_Item"
null
https://raw.githubusercontent.com/Oblosys/proxima/f154dff2ccb8afe00eeb325d9d06f5e2a5ee7589/helium-editor/src/DocTypes_Generated.hs
haskell
StrTk is for keywords, so eq takes the string value into account --- GENERATED PART STARTS HERE. DO NOT EDIT ON OR BEYOND THIS LINE ----- ------------------------------------------------------------------------ ------------------------------------------------------------------------ ------------------------------------------------------------------------ ------------------------------------------------------------------------ ------------------------------------------------------------------------ Node -- ------------------------------------------------------------------------ ------------------------------------------------------------------------ Show instance for Node -- ------------------------------------------------------------------------
# LANGUAGE StandaloneDeriving # module DocTypes_Generated where import Common.CommonTypes import Evaluation.DocTypes import Presentation.PresTypes import Data.List import Data.Char import Data.Generics | IntTk | LIdentTk | UIdentTk | OpTk | SymTk deriving (Show, Eq, Ord, Typeable) type HeliumTypeInfo = ([HeliumMessage],[(String,String)], [(PathDoc, String)]) data HeliumMessage = HMessage [String] | HError [String] [PathDoc] [PathDoc] [PathDoc] deriving (Show, Data, Typeable) deriving instance Data PathDoc deriving instance Typeable PathDoc data Document = RootDoc Root | HoleDocument | ParseErrDocument (ParseError Document EnrichedDoc Node ClipDoc UserToken) deriving (Show, Data, Typeable) data Root = Root IDP List_Decl | HoleRoot | ParseErrRoot (ParseError Document EnrichedDoc Node ClipDoc UserToken) deriving (Show, Data, Typeable) data EnrichedDoc = RootEnr RootE HeliumTypeInfo | HoleEnrichedDoc | ParseErrEnrichedDoc (ParseError Document EnrichedDoc Node ClipDoc UserToken) deriving (Show, Data, Typeable) data RootE = RootE IDP List_Decl List_Decl | HoleRootE | ParseErrRootE (ParseError Document EnrichedDoc Node ClipDoc UserToken) deriving (Show, Data, Typeable) data Decl = Decl IDP IDP IDP IDP Bool Bool Ident Exp | BoardDecl IDP IDP Board | PPPresentationDecl IDP IDP PPPresentation | HoleDecl | ParseErrDecl (ParseError Document EnrichedDoc Node ClipDoc UserToken) deriving (Show, Data, Typeable) data Ident = Ident IDP IDP String | HoleIdent | ParseErrIdent (ParseError Document EnrichedDoc Node ClipDoc UserToken) deriving (Show, Data, Typeable) data Exp = PlusExp IDP Exp Exp | TimesExp IDP Exp Exp | DivExp IDP Exp Exp | PowerExp IDP Exp Exp | BoolExp IDP Bool | IntExp IDP Int | LamExp IDP IDP Ident Exp | AppExp Exp Exp | CaseExp IDP IDP Exp List_Alt | LetExp IDP IDP List_Decl Exp | IdentExp Ident | IfExp IDP IDP IDP Exp Exp Exp | ParenExp IDP IDP Exp | ListExp IDP IDP [IDP] List_Exp | ProductExp IDP IDP [IDP] List_Exp | HoleExp | ParseErrExp (ParseError Document EnrichedDoc Node ClipDoc UserToken) deriving (Show, Data, Typeable) data Alt = Alt IDP IDP Ident Exp | HoleAlt | ParseErrAlt (ParseError Document EnrichedDoc Node ClipDoc UserToken) deriving (Show, Data, Typeable) data Board = Board BoardRow BoardRow BoardRow BoardRow BoardRow BoardRow BoardRow BoardRow | HoleBoard | ParseErrBoard (ParseError Document EnrichedDoc Node ClipDoc UserToken) deriving (Show, Data, Typeable) data BoardRow = BoardRow BoardSquare BoardSquare BoardSquare BoardSquare BoardSquare BoardSquare BoardSquare BoardSquare | HoleBoardRow | ParseErrBoardRow (ParseError Document EnrichedDoc Node ClipDoc UserToken) deriving (Show, Data, Typeable) data BoardSquare = Queen Bool | King Bool | Bishop Bool | Knight Bool | Rook Bool | Pawn Bool | Empty | HoleBoardSquare | ParseErrBoardSquare (ParseError Document EnrichedDoc Node ClipDoc UserToken) deriving (Show, Data, Typeable) data PPPresentation = PPPresentation Bool List_Slide | HolePPPresentation | ParseErrPPPresentation (ParseError Document EnrichedDoc Node ClipDoc UserToken) deriving (Show, Data, Typeable) data Slide = Slide String ItemList | HoleSlide | ParseErrSlide (ParseError Document EnrichedDoc Node ClipDoc UserToken) deriving (Show, Data, Typeable) data ItemList = ItemList ListType List_Item | HoleItemList | ParseErrItemList (ParseError Document EnrichedDoc Node ClipDoc UserToken) deriving (Show, Data, Typeable) data ListType = Bullet | Number | Alpha | HoleListType | ParseErrListType (ParseError Document EnrichedDoc Node ClipDoc UserToken) deriving (Show, Data, Typeable) data Item = StringItem String | HeliumItem Exp | ListItem ItemList | HoleItem | ParseErrItem (ParseError Document EnrichedDoc Node ClipDoc UserToken) deriving (Show, Data, Typeable) data List_Decl = List_Decl ConsList_Decl | HoleList_Decl | ParseErrList_Decl (ParseError Document EnrichedDoc Node ClipDoc UserToken) deriving (Show, Data, Typeable) data List_Alt = List_Alt ConsList_Alt | HoleList_Alt | ParseErrList_Alt (ParseError Document EnrichedDoc Node ClipDoc UserToken) deriving (Show, Data, Typeable) data List_Exp = List_Exp ConsList_Exp | HoleList_Exp | ParseErrList_Exp (ParseError Document EnrichedDoc Node ClipDoc UserToken) deriving (Show, Data, Typeable) data List_Slide = List_Slide ConsList_Slide | HoleList_Slide | ParseErrList_Slide (ParseError Document EnrichedDoc Node ClipDoc UserToken) deriving (Show, Data, Typeable) data List_Item = List_Item ConsList_Item | HoleList_Item | ParseErrList_Item (ParseError Document EnrichedDoc Node ClipDoc UserToken) deriving (Show, Data, Typeable) data ConsList_Decl = Cons_Decl Decl ConsList_Decl | Nil_Decl deriving (Show, Data, Typeable) data ConsList_Alt = Cons_Alt Alt ConsList_Alt | Nil_Alt deriving (Show, Data, Typeable) data ConsList_Exp = Cons_Exp Exp ConsList_Exp | Nil_Exp deriving (Show, Data, Typeable) data ConsList_Slide = Cons_Slide Slide ConsList_Slide | Nil_Slide deriving (Show, Data, Typeable) data ConsList_Item = Cons_Item Item ConsList_Item | Nil_Item deriving (Show, Data, Typeable) data ClipDoc = Clip_Document Document | Clip_Root Root | Clip_EnrichedDoc EnrichedDoc | Clip_RootE RootE | Clip_Decl Decl | Clip_Ident Ident | Clip_Exp Exp | Clip_Alt Alt | Clip_Board Board | Clip_BoardRow BoardRow | Clip_BoardSquare BoardSquare | Clip_PPPresentation PPPresentation | Clip_Slide Slide | Clip_ItemList ItemList | Clip_ListType ListType | Clip_Item Item | Clip_List_Decl List_Decl | Clip_List_Alt List_Alt | Clip_List_Exp List_Exp | Clip_List_Slide List_Slide | Clip_List_Item List_Item | Clip_Bool Bool | Clip_Int Int | Clip_String String | Clip_Float Float | Clip_Nothing deriving (Show, Typeable) data Node = NoNode | Node_RootDoc Document Path | Node_HoleDocument Document Path | Node_ParseErrDocument Document Path | Node_Root Root Path | Node_HoleRoot Root Path | Node_ParseErrRoot Root Path | Node_RootEnr EnrichedDoc Path | Node_HoleEnrichedDoc EnrichedDoc Path | Node_ParseErrEnrichedDoc EnrichedDoc Path | Node_RootE RootE Path | Node_HoleRootE RootE Path | Node_ParseErrRootE RootE Path | Node_Decl Decl Path | Node_BoardDecl Decl Path | Node_PPPresentationDecl Decl Path | Node_HoleDecl Decl Path | Node_ParseErrDecl Decl Path | Node_Ident Ident Path | Node_HoleIdent Ident Path | Node_ParseErrIdent Ident Path | Node_PlusExp Exp Path | Node_TimesExp Exp Path | Node_DivExp Exp Path | Node_PowerExp Exp Path | Node_BoolExp Exp Path | Node_IntExp Exp Path | Node_LamExp Exp Path | Node_AppExp Exp Path | Node_CaseExp Exp Path | Node_LetExp Exp Path | Node_IdentExp Exp Path | Node_IfExp Exp Path | Node_ParenExp Exp Path | Node_ListExp Exp Path | Node_ProductExp Exp Path | Node_HoleExp Exp Path | Node_ParseErrExp Exp Path | Node_Alt Alt Path | Node_HoleAlt Alt Path | Node_ParseErrAlt Alt Path | Node_Board Board Path | Node_HoleBoard Board Path | Node_ParseErrBoard Board Path | Node_BoardRow BoardRow Path | Node_HoleBoardRow BoardRow Path | Node_ParseErrBoardRow BoardRow Path | Node_Queen BoardSquare Path | Node_King BoardSquare Path | Node_Bishop BoardSquare Path | Node_Knight BoardSquare Path | Node_Rook BoardSquare Path | Node_Pawn BoardSquare Path | Node_Empty BoardSquare Path | Node_HoleBoardSquare BoardSquare Path | Node_ParseErrBoardSquare BoardSquare Path | Node_PPPresentation PPPresentation Path | Node_HolePPPresentation PPPresentation Path | Node_ParseErrPPPresentation PPPresentation Path | Node_Slide Slide Path | Node_HoleSlide Slide Path | Node_ParseErrSlide Slide Path | Node_ItemList ItemList Path | Node_HoleItemList ItemList Path | Node_ParseErrItemList ItemList Path | Node_Bullet ListType Path | Node_Number ListType Path | Node_Alpha ListType Path | Node_HoleListType ListType Path | Node_ParseErrListType ListType Path | Node_StringItem Item Path | Node_HeliumItem Item Path | Node_ListItem Item Path | Node_HoleItem Item Path | Node_ParseErrItem Item Path | Node_List_Decl List_Decl Path | Node_HoleList_Decl List_Decl Path | Node_ParseErrList_Decl List_Decl Path | Node_List_Alt List_Alt Path | Node_HoleList_Alt List_Alt Path | Node_ParseErrList_Alt List_Alt Path | Node_List_Exp List_Exp Path | Node_HoleList_Exp List_Exp Path | Node_ParseErrList_Exp List_Exp Path | Node_List_Slide List_Slide Path | Node_HoleList_Slide List_Slide Path | Node_ParseErrList_Slide List_Slide Path | Node_List_Item List_Item Path | Node_HoleList_Item List_Item Path | Node_ParseErrList_Item List_Item Path deriving Typeable instance Show Node where show NoNode = "NoNode" show (Node_RootDoc _ _) = "Node_RootDoc" show (Node_HoleDocument _ _) = "Node_HoleDocument" show (Node_ParseErrDocument _ _) = "Node_ParseErrDocument" show (Node_Root _ _) = "Node_Root" show (Node_HoleRoot _ _) = "Node_HoleRoot" show (Node_ParseErrRoot _ _) = "Node_ParseErrRoot" show (Node_RootEnr _ _) = "Node_RootEnr" show (Node_HoleEnrichedDoc _ _) = "Node_HoleEnrichedDoc" show (Node_ParseErrEnrichedDoc _ _) = "Node_ParseErrEnrichedDoc" show (Node_RootE _ _) = "Node_RootE" show (Node_HoleRootE _ _) = "Node_HoleRootE" show (Node_ParseErrRootE _ _) = "Node_ParseErrRootE" show (Node_Decl _ _) = "Node_Decl" show (Node_BoardDecl _ _) = "Node_BoardDecl" show (Node_PPPresentationDecl _ _) = "Node_PPPresentationDecl" show (Node_HoleDecl _ _) = "Node_HoleDecl" show (Node_ParseErrDecl _ _) = "Node_ParseErrDecl" show (Node_Ident _ _) = "Node_Ident" show (Node_HoleIdent _ _) = "Node_HoleIdent" show (Node_ParseErrIdent _ _) = "Node_ParseErrIdent" show (Node_PlusExp _ _) = "Node_PlusExp" show (Node_TimesExp _ _) = "Node_TimesExp" show (Node_DivExp _ _) = "Node_DivExp" show (Node_PowerExp _ _) = "Node_PowerExp" show (Node_BoolExp _ _) = "Node_BoolExp" show (Node_IntExp _ _) = "Node_IntExp" show (Node_LamExp _ _) = "Node_LamExp" show (Node_AppExp _ _) = "Node_AppExp" show (Node_CaseExp _ _) = "Node_CaseExp" show (Node_LetExp _ _) = "Node_LetExp" show (Node_IdentExp _ _) = "Node_IdentExp" show (Node_IfExp _ _) = "Node_IfExp" show (Node_ParenExp _ _) = "Node_ParenExp" show (Node_ListExp _ _) = "Node_ListExp" show (Node_ProductExp _ _) = "Node_ProductExp" show (Node_HoleExp _ _) = "Node_HoleExp" show (Node_ParseErrExp _ _) = "Node_ParseErrExp" show (Node_Alt _ _) = "Node_Alt" show (Node_HoleAlt _ _) = "Node_HoleAlt" show (Node_ParseErrAlt _ _) = "Node_ParseErrAlt" show (Node_Board _ _) = "Node_Board" show (Node_HoleBoard _ _) = "Node_HoleBoard" show (Node_ParseErrBoard _ _) = "Node_ParseErrBoard" show (Node_BoardRow _ _) = "Node_BoardRow" show (Node_HoleBoardRow _ _) = "Node_HoleBoardRow" show (Node_ParseErrBoardRow _ _) = "Node_ParseErrBoardRow" show (Node_Queen _ _) = "Node_Queen" show (Node_King _ _) = "Node_King" show (Node_Bishop _ _) = "Node_Bishop" show (Node_Knight _ _) = "Node_Knight" show (Node_Rook _ _) = "Node_Rook" show (Node_Pawn _ _) = "Node_Pawn" show (Node_Empty _ _) = "Node_Empty" show (Node_HoleBoardSquare _ _) = "Node_HoleBoardSquare" show (Node_ParseErrBoardSquare _ _) = "Node_ParseErrBoardSquare" show (Node_PPPresentation _ _) = "Node_PPPresentation" show (Node_HolePPPresentation _ _) = "Node_HolePPPresentation" show (Node_ParseErrPPPresentation _ _) = "Node_ParseErrPPPresentation" show (Node_Slide _ _) = "Node_Slide" show (Node_HoleSlide _ _) = "Node_HoleSlide" show (Node_ParseErrSlide _ _) = "Node_ParseErrSlide" show (Node_ItemList _ _) = "Node_ItemList" show (Node_HoleItemList _ _) = "Node_HoleItemList" show (Node_ParseErrItemList _ _) = "Node_ParseErrItemList" show (Node_Bullet _ _) = "Node_Bullet" show (Node_Number _ _) = "Node_Number" show (Node_Alpha _ _) = "Node_Alpha" show (Node_HoleListType _ _) = "Node_HoleListType" show (Node_ParseErrListType _ _) = "Node_ParseErrListType" show (Node_StringItem _ _) = "Node_StringItem" show (Node_HeliumItem _ _) = "Node_HeliumItem" show (Node_ListItem _ _) = "Node_ListItem" show (Node_HoleItem _ _) = "Node_HoleItem" show (Node_ParseErrItem _ _) = "Node_ParseErrItem" show (Node_List_Decl _ _) = "Node_List_Decl" show (Node_HoleList_Decl _ _) = "Node_HoleList_Decl" show (Node_ParseErrList_Decl _ _) = "Node_ParseErrList_Decl" show (Node_List_Alt _ _) = "Node_List_Alt" show (Node_HoleList_Alt _ _) = "Node_HoleList_Alt" show (Node_ParseErrList_Alt _ _) = "Node_ParseErrList_Alt" show (Node_List_Exp _ _) = "Node_List_Exp" show (Node_HoleList_Exp _ _) = "Node_HoleList_Exp" show (Node_ParseErrList_Exp _ _) = "Node_ParseErrList_Exp" show (Node_List_Slide _ _) = "Node_List_Slide" show (Node_HoleList_Slide _ _) = "Node_HoleList_Slide" show (Node_ParseErrList_Slide _ _) = "Node_ParseErrList_Slide" show (Node_List_Item _ _) = "Node_List_Item" show (Node_HoleList_Item _ _) = "Node_HoleList_Item" show (Node_ParseErrList_Item _ _) = "Node_ParseErrList_Item"
3acfc7c25dd491fda5fdc87abf7b1c8c4634d760fc0311e01c2339900a74bc66
andrewberls/predis
zset.clj
(ns predis.util.zset) (defn zset-compare [[member-a score-a] [member-b score-b]] (let [score-comp (compare score-a score-b)] (if (zero? score-comp) (compare member-a member-b) score-comp))) (defn sort-zset [zset] (sort zset-compare zset)) (defn parse-zmin [score] (if (= score "-inf") Float/NEGATIVE_INFINITY (long score))) (defn parse-zmax [score] (if (= score "+inf") Float/POSITIVE_INFINITY (long score))) TODO : exclusive range " ( 5 " (defn zmember-in-range? [min-score max-score [m score :as zmember]] (let [min-score' (parse-zmin min-score) max-score' (parse-zmax max-score)] (and (>= score min-score') (<= score max-score')))) (defn zrangebyscore "Filter members of zset within min-score and max-score and return a seq of [member score] tuples sorted by ascending score" [min-score max-score zset] (->> (filter (partial zmember-in-range? min-score max-score) zset) (sort-zset))) (defn zset-response "Given a seq of pre-sorted [member score] tuples, return an appropriate response based on the boolean withscores option" [tups withscores] (if withscores (apply concat tups) (map first tups)))
null
https://raw.githubusercontent.com/andrewberls/predis/9479323a757dc73ee5101c4904b6bd7ef742aed6/src/predis/util/zset.clj
clojure
(ns predis.util.zset) (defn zset-compare [[member-a score-a] [member-b score-b]] (let [score-comp (compare score-a score-b)] (if (zero? score-comp) (compare member-a member-b) score-comp))) (defn sort-zset [zset] (sort zset-compare zset)) (defn parse-zmin [score] (if (= score "-inf") Float/NEGATIVE_INFINITY (long score))) (defn parse-zmax [score] (if (= score "+inf") Float/POSITIVE_INFINITY (long score))) TODO : exclusive range " ( 5 " (defn zmember-in-range? [min-score max-score [m score :as zmember]] (let [min-score' (parse-zmin min-score) max-score' (parse-zmax max-score)] (and (>= score min-score') (<= score max-score')))) (defn zrangebyscore "Filter members of zset within min-score and max-score and return a seq of [member score] tuples sorted by ascending score" [min-score max-score zset] (->> (filter (partial zmember-in-range? min-score max-score) zset) (sort-zset))) (defn zset-response "Given a seq of pre-sorted [member score] tuples, return an appropriate response based on the boolean withscores option" [tups withscores] (if withscores (apply concat tups) (map first tups)))
7dfa23e323d3febe91a404dca5cbf5078b9bb96e1ab34910e71537f43da7b7af
eareese/htdp-exercises
119-illegal-sentences.rkt
; (define (f "x") x) ;; This is illegal because "x" is a value, not a variable, since it is in quote marks. Therefore, (f "x") is not legal syntax for the "as many variables as you wish" part of the define syntax. ; (define (f x y z) (x)) ;; This would be legal, if not for the (x), which is not valid syntax for an expression since a variable should not be enclosed in ().
null
https://raw.githubusercontent.com/eareese/htdp-exercises/a85ff3111d459dda0e94d9b463d01a09accbf9bf/part01-fixed-size-data/119-illegal-sentences.rkt
racket
(define (f "x") x) This is illegal because "x" is a value, not a variable, since it is in quote marks. Therefore, (f "x") is not legal syntax for the "as many variables as you wish" part of the define syntax. (define (f x y z) (x)) This would be legal, if not for the (x), which is not valid syntax for an expression since a variable should not be enclosed in ().
33d17f839665b6111b121ae4fa51bcb62d597ded91e280b98e7220322040ace0
manuel-serrano/bigloo
loops.scm
;*=====================================================================*/ * serrano / prgm / project / bigloo / api / libuv / examples / loops.scm * / ;* ------------------------------------------------------------- */ * Author : * / * Creation : Tue May 6 12:10:13 2014 * / * Last change : Thu Oct 23 08:20:28 2014 ( serrano ) * / * Copyright : 2014 * / ;* ------------------------------------------------------------- */ * LIBUV multiple loops * / ;*=====================================================================*/ ;*---------------------------------------------------------------------*/ ;* The module */ ;*---------------------------------------------------------------------*/ (module libuv_hello (library libuv pthread) (main main)) ;*---------------------------------------------------------------------*/ ;* main ... */ ;*---------------------------------------------------------------------*/ (define (main args) (thread-start! (instantiate::pthread (body (lambda () (loop "loop1" #u64:500))))) (thread-join! (thread-start-joinable! (instantiate::pthread (body (lambda () (loop "loop2" #u64:700))))))) ;*---------------------------------------------------------------------*/ ;* loop ... */ ;*---------------------------------------------------------------------*/ (define (loop id delay) (let ((loop (instantiate::UvLoop))) (letrec* ((n 5) (timer (instantiate::UvTimer (loop loop) (cb (lambda (t s) (print id ": n=" n " T=" t) (set! n (-fx n 1)) (when (=fx n 0) (uv-timer-stop t))))))) (uv-timer-start timer (*u64 #u64:2 delay) delay) (uv-run loop))))
null
https://raw.githubusercontent.com/manuel-serrano/bigloo/d315487d6a97ef7b4483e919d1823a408337bd07/api/libbacktrace/examples/loops.scm
scheme
*=====================================================================*/ * ------------------------------------------------------------- */ * ------------------------------------------------------------- */ *=====================================================================*/ *---------------------------------------------------------------------*/ * The module */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * main ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * loop ... */ *---------------------------------------------------------------------*/
* serrano / prgm / project / bigloo / api / libuv / examples / loops.scm * / * Author : * / * Creation : Tue May 6 12:10:13 2014 * / * Last change : Thu Oct 23 08:20:28 2014 ( serrano ) * / * Copyright : 2014 * / * LIBUV multiple loops * / (module libuv_hello (library libuv pthread) (main main)) (define (main args) (thread-start! (instantiate::pthread (body (lambda () (loop "loop1" #u64:500))))) (thread-join! (thread-start-joinable! (instantiate::pthread (body (lambda () (loop "loop2" #u64:700))))))) (define (loop id delay) (let ((loop (instantiate::UvLoop))) (letrec* ((n 5) (timer (instantiate::UvTimer (loop loop) (cb (lambda (t s) (print id ": n=" n " T=" t) (set! n (-fx n 1)) (when (=fx n 0) (uv-timer-stop t))))))) (uv-timer-start timer (*u64 #u64:2 delay) delay) (uv-run loop))))
93635109fd82ceb9eabab1cbd04c4c0c1bead883b00de40cd8fc4fb7bb391114
input-output-hk/cardano-wallet
TxOut.hs
# LANGUAGE DeriveGeneric # # LANGUAGE DuplicateRecordFields # # LANGUAGE NamedFieldPuns # # LANGUAGE OverloadedLabels # # LANGUAGE TypeApplications # -- | Copyright : © 2018 - 2022 IOHK -- License: Apache-2.0 -- -- This module defines the 'TxOut' type. -- module Cardano.Wallet.Primitive.Types.Tx.TxOut ( -- * Type TxOut (..) -- * Queries , assetIds , coin -- * Modifiers , addCoin , mapAssetIds , removeAssetId , subtractCoin ) where import Prelude import Cardano.Wallet.Primitive.Types.Address ( Address (..) ) import Cardano.Wallet.Primitive.Types.Coin ( Coin (..) ) import Cardano.Wallet.Primitive.Types.TokenBundle ( TokenBundle ) import Cardano.Wallet.Primitive.Types.TokenMap ( AssetId, Lexicographic (..) ) import Control.DeepSeq ( NFData (..) ) import Data.Bifunctor ( first ) import Data.Generics.Internal.VL.Lens ( over, view ) import Data.Generics.Labels () import Data.Ord ( comparing ) import Data.Set ( Set ) import Fmt ( Buildable (..), blockMapF, prefixF, suffixF ) import GHC.Generics ( Generic ) import qualified Cardano.Wallet.Primitive.Types.Coin as Coin import qualified Cardano.Wallet.Primitive.Types.TokenBundle as TokenBundle import qualified Cardano.Wallet.Primitive.Types.TokenMap as TokenMap -------------------------------------------------------------------------------- -- Type -------------------------------------------------------------------------------- data TxOut = TxOut { address :: !Address , tokens :: !TokenBundle } deriving (Read, Show, Generic, Eq) -------------------------------------------------------------------------------- -- Instances -------------------------------------------------------------------------------- Since the ' TokenBundle ' type deliberately does not provide an ' Ord ' instance -- (as that would lead to arithmetically invalid orderings), this means we can't automatically derive an ' Ord ' instance for the ' TxOut ' type . -- -- Instead, we define an 'Ord' instance that makes comparisons based on lexicographic ordering of ' TokenBundle ' values . -- instance Ord TxOut where compare = comparing projection where projection (TxOut address bundle) = (address, Lexicographic bundle) instance NFData TxOut instance Buildable TxOut where build txOut = buildMap [ ("address" , addressShort) , ("coin" , build (coin txOut)) , ("tokens" , build (TokenMap.Nested $ view (#tokens . #tokens) txOut)) ] where addressShort = mempty <> prefixF 8 addressFull <> "..." <> suffixF 8 addressFull addressFull = build $ view #address txOut buildMap = blockMapF . fmap (first $ id @String) -------------------------------------------------------------------------------- Queries -------------------------------------------------------------------------------- -- | Gets the current set of asset identifiers from a transaction output. -- assetIds :: TxOut -> Set AssetId assetIds (TxOut _ bundle) = TokenBundle.getAssets bundle -- | Gets the current 'Coin' value from a transaction output. -- ' Coin ' values correspond to the ada asset . -- coin :: TxOut -> Coin coin = TokenBundle.getCoin . view #tokens -------------------------------------------------------------------------------- -- Modifiers -------------------------------------------------------------------------------- -- | Increments the 'Coin' value of a 'TxOut'. -- -- Satisfies the following property for all values of 'c': -- -- >>> subtractCoin c . addCoin c == id -- addCoin :: Coin -> TxOut -> TxOut addCoin val TxOut {address, tokens} = TxOut address (tokens <> TokenBundle.fromCoin val) -- | Applies the given function to all asset identifiers in a 'TxOut'. -- mapAssetIds :: (AssetId -> AssetId) -> TxOut -> TxOut mapAssetIds f (TxOut address bundle) = TxOut address (TokenBundle.mapAssetIds f bundle) | Removes the asset corresponding to the given ' AssetId ' from a ' TxOut ' . -- removeAssetId :: TxOut -> AssetId -> TxOut removeAssetId (TxOut address bundle) asset = TxOut address (TokenBundle.setQuantity bundle asset mempty) -- | Decrements the 'Coin' value of a 'TxOut'. -- -- Satisfies the following property for all values of 'c': -- -- >>> subtractCoin c . addCoin c == id -- -- If the given 'Coin' is greater than the 'Coin' value of the given 'TxOut', the resulting ' TxOut ' will have a ' Coin ' value of zero . -- subtractCoin :: Coin -> TxOut -> TxOut subtractCoin toSubtract = over (#tokens . #coin) (`Coin.difference` toSubtract)
null
https://raw.githubusercontent.com/input-output-hk/cardano-wallet/157a6d5f977f4600373596b7cfa9700138e8e140/lib/primitive/lib/Cardano/Wallet/Primitive/Types/Tx/TxOut.hs
haskell
| License: Apache-2.0 This module defines the 'TxOut' type. * Type * Queries * Modifiers ------------------------------------------------------------------------------ Type ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ Instances ------------------------------------------------------------------------------ (as that would lead to arithmetically invalid orderings), this means we can't Instead, we define an 'Ord' instance that makes comparisons based on ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ | Gets the current set of asset identifiers from a transaction output. | Gets the current 'Coin' value from a transaction output. ------------------------------------------------------------------------------ Modifiers ------------------------------------------------------------------------------ | Increments the 'Coin' value of a 'TxOut'. Satisfies the following property for all values of 'c': >>> subtractCoin c . addCoin c == id | Applies the given function to all asset identifiers in a 'TxOut'. | Decrements the 'Coin' value of a 'TxOut'. Satisfies the following property for all values of 'c': >>> subtractCoin c . addCoin c == id If the given 'Coin' is greater than the 'Coin' value of the given 'TxOut',
# LANGUAGE DeriveGeneric # # LANGUAGE DuplicateRecordFields # # LANGUAGE NamedFieldPuns # # LANGUAGE OverloadedLabels # # LANGUAGE TypeApplications # Copyright : © 2018 - 2022 IOHK module Cardano.Wallet.Primitive.Types.Tx.TxOut ( TxOut (..) , assetIds , coin , addCoin , mapAssetIds , removeAssetId , subtractCoin ) where import Prelude import Cardano.Wallet.Primitive.Types.Address ( Address (..) ) import Cardano.Wallet.Primitive.Types.Coin ( Coin (..) ) import Cardano.Wallet.Primitive.Types.TokenBundle ( TokenBundle ) import Cardano.Wallet.Primitive.Types.TokenMap ( AssetId, Lexicographic (..) ) import Control.DeepSeq ( NFData (..) ) import Data.Bifunctor ( first ) import Data.Generics.Internal.VL.Lens ( over, view ) import Data.Generics.Labels () import Data.Ord ( comparing ) import Data.Set ( Set ) import Fmt ( Buildable (..), blockMapF, prefixF, suffixF ) import GHC.Generics ( Generic ) import qualified Cardano.Wallet.Primitive.Types.Coin as Coin import qualified Cardano.Wallet.Primitive.Types.TokenBundle as TokenBundle import qualified Cardano.Wallet.Primitive.Types.TokenMap as TokenMap data TxOut = TxOut { address :: !Address , tokens :: !TokenBundle } deriving (Read, Show, Generic, Eq) Since the ' TokenBundle ' type deliberately does not provide an ' Ord ' instance automatically derive an ' Ord ' instance for the ' TxOut ' type . lexicographic ordering of ' TokenBundle ' values . instance Ord TxOut where compare = comparing projection where projection (TxOut address bundle) = (address, Lexicographic bundle) instance NFData TxOut instance Buildable TxOut where build txOut = buildMap [ ("address" , addressShort) , ("coin" , build (coin txOut)) , ("tokens" , build (TokenMap.Nested $ view (#tokens . #tokens) txOut)) ] where addressShort = mempty <> prefixF 8 addressFull <> "..." <> suffixF 8 addressFull addressFull = build $ view #address txOut buildMap = blockMapF . fmap (first $ id @String) Queries assetIds :: TxOut -> Set AssetId assetIds (TxOut _ bundle) = TokenBundle.getAssets bundle ' Coin ' values correspond to the ada asset . coin :: TxOut -> Coin coin = TokenBundle.getCoin . view #tokens addCoin :: Coin -> TxOut -> TxOut addCoin val TxOut {address, tokens} = TxOut address (tokens <> TokenBundle.fromCoin val) mapAssetIds :: (AssetId -> AssetId) -> TxOut -> TxOut mapAssetIds f (TxOut address bundle) = TxOut address (TokenBundle.mapAssetIds f bundle) | Removes the asset corresponding to the given ' AssetId ' from a ' TxOut ' . removeAssetId :: TxOut -> AssetId -> TxOut removeAssetId (TxOut address bundle) asset = TxOut address (TokenBundle.setQuantity bundle asset mempty) the resulting ' TxOut ' will have a ' Coin ' value of zero . subtractCoin :: Coin -> TxOut -> TxOut subtractCoin toSubtract = over (#tokens . #coin) (`Coin.difference` toSubtract)
ee670aa1107dbf7e952cb09c863792b2592b99c3febe223e6329952d6d473238
wargrey/graphics
mesh.rkt
#lang racket/base (provide cairo-mesh-pattern) ; for tamer/prefab.rkt (require "../../digitama/unsafe/pangocairo.rkt") ;;; -cairo-pattern-t.html#cairo-pattern-create-mesh (define (cairo-mesh-pattern width height ratio density) (define-values (bmp cr) (make-cairo-image width height density #true)) (define pattern (cairo_pattern_create_mesh)) (define-values (side rest) (values (* height ratio) (* height (- 1.0 ratio)))) (define-values (tx ty) (values (- width (* side 0.5)) (- height (* side 0.5)))) Add a Coons patch (cairo_mesh_pattern_begin_patch pattern) (cairo_mesh_pattern_move_to pattern 0.0 0.0) (cairo_mesh_pattern_curve_to pattern side (- side) (* side 2.0) side tx 0.0) (cairo_mesh_pattern_curve_to pattern (* side 2.0) side width (* side 2.0) tx ty) (cairo_mesh_pattern_curve_to pattern (* side 2.0) rest side height 0.0 ty) (cairo_mesh_pattern_curve_to pattern side rest (- side) side 0.0 0.0) (cairo_mesh_pattern_set_corner_color_rgba pattern 0 2.0 0.0 0.0 1.0) (cairo_mesh_pattern_set_corner_color_rgba pattern 1 0.0 1.0 0.0 1.0) (cairo_mesh_pattern_set_corner_color_rgba pattern 2 0.0 0.0 1.0 1.0) (cairo_mesh_pattern_set_corner_color_rgba pattern 3 1.0 1.0 0.0 1.0) (cairo_mesh_pattern_end_patch pattern) ; Add a Gouraud-shaded triangle (cairo_mesh_pattern_begin_patch pattern) (cairo_mesh_pattern_move_to pattern tx ty) (cairo_mesh_pattern_line_to pattern width rest) (cairo_mesh_pattern_line_to pattern width height) (cairo_mesh_pattern_set_corner_color_rgba pattern 0 1.0 0.0 0.0 1.0) (cairo_mesh_pattern_set_corner_color_rgba pattern 1 0.0 1.0 0.0 1.0) (cairo_mesh_pattern_set_corner_color_rgba pattern 2 0.0 0.0 1.0 1.0) (cairo_mesh_pattern_end_patch pattern) (cairo_set_source cr pattern) (cairo_paint cr) bmp) (module+ main (cairo-mesh-pattern 256.0 256.0 0.32 2.0))
null
https://raw.githubusercontent.com/wargrey/graphics/50751297f244a01ac734099b9a1e9be97cd36f3f/bitmap/tamer/cairo/mesh.rkt
racket
for tamer/prefab.rkt -cairo-pattern-t.html#cairo-pattern-create-mesh Add a Gouraud-shaded triangle
#lang racket/base (require "../../digitama/unsafe/pangocairo.rkt") (define (cairo-mesh-pattern width height ratio density) (define-values (bmp cr) (make-cairo-image width height density #true)) (define pattern (cairo_pattern_create_mesh)) (define-values (side rest) (values (* height ratio) (* height (- 1.0 ratio)))) (define-values (tx ty) (values (- width (* side 0.5)) (- height (* side 0.5)))) Add a Coons patch (cairo_mesh_pattern_begin_patch pattern) (cairo_mesh_pattern_move_to pattern 0.0 0.0) (cairo_mesh_pattern_curve_to pattern side (- side) (* side 2.0) side tx 0.0) (cairo_mesh_pattern_curve_to pattern (* side 2.0) side width (* side 2.0) tx ty) (cairo_mesh_pattern_curve_to pattern (* side 2.0) rest side height 0.0 ty) (cairo_mesh_pattern_curve_to pattern side rest (- side) side 0.0 0.0) (cairo_mesh_pattern_set_corner_color_rgba pattern 0 2.0 0.0 0.0 1.0) (cairo_mesh_pattern_set_corner_color_rgba pattern 1 0.0 1.0 0.0 1.0) (cairo_mesh_pattern_set_corner_color_rgba pattern 2 0.0 0.0 1.0 1.0) (cairo_mesh_pattern_set_corner_color_rgba pattern 3 1.0 1.0 0.0 1.0) (cairo_mesh_pattern_end_patch pattern) (cairo_mesh_pattern_begin_patch pattern) (cairo_mesh_pattern_move_to pattern tx ty) (cairo_mesh_pattern_line_to pattern width rest) (cairo_mesh_pattern_line_to pattern width height) (cairo_mesh_pattern_set_corner_color_rgba pattern 0 1.0 0.0 0.0 1.0) (cairo_mesh_pattern_set_corner_color_rgba pattern 1 0.0 1.0 0.0 1.0) (cairo_mesh_pattern_set_corner_color_rgba pattern 2 0.0 0.0 1.0 1.0) (cairo_mesh_pattern_end_patch pattern) (cairo_set_source cr pattern) (cairo_paint cr) bmp) (module+ main (cairo-mesh-pattern 256.0 256.0 0.32 2.0))
264bbf6ce9c3844719466ba3fc488945bf8b621116e6f9bcc4f67148ff059fa6
PrecursorApp/precursor
common.clj
(ns pc.views.common (:require [pc.assets] [pc.profile :refer (prod-assets?)])) (defn cdn-base-url [] (if (prod-assets?) (pc.profile/cdn-base-url) "")) (defn cdn-path [path] (str (cdn-base-url) path)) (defn external-cdn-path [path] (str "" path)) (defn head-style [] " #om-app { background-image: linear-gradient(to bottom, rgba(85, 85, 85, .25) 10%, rgba(85, 85, 85, 0) 10%), linear-gradient(to right, rgba(85, 85, 85, .25) 10%, rgba(85, 85, 85, 0) 10%), linear-gradient(to bottom, rgba(85, 85, 85, .57) 1%, rgba(85, 85, 85, 0) 1%), linear-gradient(to right, rgba(85, 85, 85, .57) 1%, rgba(85, 85, 85, 0) 1%); background-size: 10px 10px, 10px 10px, 100px 100px, 100px 100px; background-color: rgba(51, 51, 51, 1); min-height: 100vh; } #om-app:active { cursor: wait; } ")
null
https://raw.githubusercontent.com/PrecursorApp/precursor/30202e40365f6883c4767e423d6299f0d13dc528/src/pc/views/common.clj
clojure
(ns pc.views.common (:require [pc.assets] [pc.profile :refer (prod-assets?)])) (defn cdn-base-url [] (if (prod-assets?) (pc.profile/cdn-base-url) "")) (defn cdn-path [path] (str (cdn-base-url) path)) (defn external-cdn-path [path] (str "" path)) (defn head-style [] " #om-app { background-image: linear-gradient(to bottom, rgba(85, 85, 85, .25) 10%, rgba(85, 85, 85, 0) 10%), linear-gradient(to right, rgba(85, 85, 85, .25) 10%, rgba(85, 85, 85, 0) 10%), linear-gradient(to bottom, rgba(85, 85, 85, .57) 1%, rgba(85, 85, 85, 0) 1%), } #om-app:active { } ")
12f932e5f1c22f79a4b68345fb81dc9808d68fb756a2d6cd28fb7e7d12d43929
ijvcms/chuanqi_dev
node_merge.erl
%%%------------------------------------------------------------------- %%% @author qhb ( C ) 2016 , < COMPANY > %%% @doc %%% 合服相关节点 %%% @end Created : 15 . 六月 2016 上午9:58 %%%------------------------------------------------------------------- -module(node_merge). %% API -export([ start/0 ]). start() -> merge_db:init_mysql(), ServerIds = merge_cfg:get_source_servers(), lists:foreach(fun(ServerId) -> merge_db:connect(ServerId) end, ServerIds), ModList = [{misc_timer}, {mod_randseed},{merge_mod}], ok = util:start_mod(permanent, ModList), ok.
null
https://raw.githubusercontent.com/ijvcms/chuanqi_dev/7742184bded15f25be761c4f2d78834249d78097/server/trunk/server/src/node/node_merge.erl
erlang
------------------------------------------------------------------- @author qhb @doc 合服相关节点 @end ------------------------------------------------------------------- API
( C ) 2016 , < COMPANY > Created : 15 . 六月 2016 上午9:58 -module(node_merge). -export([ start/0 ]). start() -> merge_db:init_mysql(), ServerIds = merge_cfg:get_source_servers(), lists:foreach(fun(ServerId) -> merge_db:connect(ServerId) end, ServerIds), ModList = [{misc_timer}, {mod_randseed},{merge_mod}], ok = util:start_mod(permanent, ModList), ok.
534fd017bb1a2a34960c9ccbe11b6865a0a06c81bb47e8b3f8ce88d1c395b6ce
ocaml/ocamlbuild
lexers.mli
(***********************************************************************) (* *) (* ocamlbuild *) (* *) , , projet Gallium , INRIA Rocquencourt (* *) Copyright 2007 Institut National de Recherche en Informatique et en Automatique . All rights reserved . This file is distributed under the terms of the GNU Library General Public License , with (* the special exception on linking described in file ../LICENSE. *) (* *) (***********************************************************************) Original author : exception Error of (string * Loc.location) type conf_values = { plus_tags : (string * Loc.location) list; minus_tags : (string * Loc.location) list } type conf = (Glob.globber * conf_values) list val ocamldep_output : Loc.source -> Lexing.lexbuf -> (string * string list) list val space_sep_strings : Loc.source -> Lexing.lexbuf -> string list val blank_sep_strings : Loc.source -> Lexing.lexbuf -> string list val comma_sep_strings : Loc.source -> Lexing.lexbuf -> string list val comma_or_blank_sep_strings : Loc.source -> Lexing.lexbuf -> string list val trim_blanks : Loc.source -> Lexing.lexbuf -> string Parse an environment path ( i.e. $ PATH ) . This is a colon separated string . Note : successive colons means an empty string . Example : " : : : " - > [ " " ; " aaa " ; " bbb " ; " " ; " " ; " " ; " " ] This is a colon separated string. Note: successive colons means an empty string. Example: ":aaa:bbb:::ccc:" -> [""; "aaa"; "bbb"; ""; ""; "ccc"; ""] *) val parse_environment_path : Loc.source -> Lexing.lexbuf -> string list (* Same one, for Windows (PATH is ;-separated) *) val parse_environment_path_w : Loc.source -> Lexing.lexbuf -> string list val conf_lines : string option -> Loc.source -> Lexing.lexbuf -> conf val path_scheme : bool -> Loc.source -> Lexing.lexbuf -> [ `Word of string | `Var of (string * Glob.globber) ] list val ocamlfind_query : Loc.source -> Lexing.lexbuf -> string * string * string * string * string * string val tag_gen : Loc.source -> Lexing.lexbuf -> string * string option
null
https://raw.githubusercontent.com/ocaml/ocamlbuild/792b7c8abdbc712c98ed7e69469ed354b87e125b/src/lexers.mli
ocaml
********************************************************************* ocamlbuild the special exception on linking described in file ../LICENSE. ********************************************************************* Same one, for Windows (PATH is ;-separated)
, , projet Gallium , INRIA Rocquencourt Copyright 2007 Institut National de Recherche en Informatique et en Automatique . All rights reserved . This file is distributed under the terms of the GNU Library General Public License , with Original author : exception Error of (string * Loc.location) type conf_values = { plus_tags : (string * Loc.location) list; minus_tags : (string * Loc.location) list } type conf = (Glob.globber * conf_values) list val ocamldep_output : Loc.source -> Lexing.lexbuf -> (string * string list) list val space_sep_strings : Loc.source -> Lexing.lexbuf -> string list val blank_sep_strings : Loc.source -> Lexing.lexbuf -> string list val comma_sep_strings : Loc.source -> Lexing.lexbuf -> string list val comma_or_blank_sep_strings : Loc.source -> Lexing.lexbuf -> string list val trim_blanks : Loc.source -> Lexing.lexbuf -> string Parse an environment path ( i.e. $ PATH ) . This is a colon separated string . Note : successive colons means an empty string . Example : " : : : " - > [ " " ; " aaa " ; " bbb " ; " " ; " " ; " " ; " " ] This is a colon separated string. Note: successive colons means an empty string. Example: ":aaa:bbb:::ccc:" -> [""; "aaa"; "bbb"; ""; ""; "ccc"; ""] *) val parse_environment_path : Loc.source -> Lexing.lexbuf -> string list val parse_environment_path_w : Loc.source -> Lexing.lexbuf -> string list val conf_lines : string option -> Loc.source -> Lexing.lexbuf -> conf val path_scheme : bool -> Loc.source -> Lexing.lexbuf -> [ `Word of string | `Var of (string * Glob.globber) ] list val ocamlfind_query : Loc.source -> Lexing.lexbuf -> string * string * string * string * string * string val tag_gen : Loc.source -> Lexing.lexbuf -> string * string option
1b50ec9ef201647d3a22a0f124b6a592867476aed334c4716f5f841974ec53d7
nikomatsakis/a-mir-formality
wfwc--hrtb.rkt
#lang racket (require redex/reduction-semantics "../../util.rkt" "../../ty/user-ty.rkt" "../grammar.rkt" "../prove.rkt" "../libcore.rkt" ) #;(module+ test (redex-let* formality-decl [(; trait Wf { } TraitDecl_Wf (term (trait Wf ((type Self)) where [] {}))) (; impl<T> Wf for T { } TraitImplDecl_Wf_for_T (term (impl[(type T)] (Wf[T]) where [] {}))) struct RequiresOrd<'a , T : Ord > AdtDecl_RequiresOrd (term (struct RequiresOrd[(lifetime a) (type T)] where [(T : core:Ord[])] {}))) (CrateDecl (C)) ] (traced '() (test-equal (decl:is-crate-ok [core-crate-decl ] ) #t)) ) )
null
https://raw.githubusercontent.com/nikomatsakis/a-mir-formality/71be4d5c4bd5e91d326277eaedd19a7abe3ac76a/racket-src/rust/test/wfwc--hrtb.rkt
racket
(module+ test trait Wf { } impl<T> Wf for T { }
#lang racket (require redex/reduction-semantics "../../util.rkt" "../../ty/user-ty.rkt" "../grammar.rkt" "../prove.rkt" "../libcore.rkt" ) (redex-let* formality-decl TraitDecl_Wf (term (trait Wf ((type Self)) where [] {}))) TraitImplDecl_Wf_for_T (term (impl[(type T)] (Wf[T]) where [] {}))) struct RequiresOrd<'a , T : Ord > AdtDecl_RequiresOrd (term (struct RequiresOrd[(lifetime a) (type T)] where [(T : core:Ord[])] {}))) (CrateDecl (C)) ] (traced '() (test-equal (decl:is-crate-ok [core-crate-decl ] ) #t)) ) )
6be2568325d940ed091809cef33c1dd3868f56a7081e3dbbbca82c999be64242
ttuegel/pipes-ghc-events
ghc-events-count.hs
module Main (main) where import qualified GHC.RTS.Events as GHC import qualified System.Environment as System main :: IO () main = do [filename] <- System.getArgs eventLog <- GHC.readEventLogFromFile filename >>= either error return let events = GHC.events $ GHC.dat eventLog print (length events) return ()
null
https://raw.githubusercontent.com/ttuegel/pipes-ghc-events/9b658e8947f18cb1195e84d2b0c8a7c244161652/ghc-events-count.hs
haskell
module Main (main) where import qualified GHC.RTS.Events as GHC import qualified System.Environment as System main :: IO () main = do [filename] <- System.getArgs eventLog <- GHC.readEventLogFromFile filename >>= either error return let events = GHC.events $ GHC.dat eventLog print (length events) return ()
c8fdb00877aa3e9be4c6053da8133da3ad5057cdcf685c628870e8700097cfed
RedPRL/stagedtt
Staging.ml
open Prelude type mode = | Inner | Outer type _ Effect.t += | GetStage : int Effect.t let run ~(stage:int) k = let open Effect.Deep in try_with k () { effc = fun (type a) (eff : a Effect.t) -> match eff with | GetStage -> Option.some @@ fun (k : (a, _) continuation) -> continue k stage | _ -> None } let get_stage () = Effect.perform GetStage let incr_stage stage k = let current_stage = Effect.perform GetStage in let mode = if current_stage + 1 > stage then Outer else Inner in run ~stage:(current_stage + 1) @@ fun () -> k mode let decr_stage stage k = let current_stage = Effect.perform GetStage in let mode = if current_stage - 1 <= stage then Inner else Outer in run ~stage:(current_stage - 1) @@ fun () -> k mode
null
https://raw.githubusercontent.com/RedPRL/stagedtt/f88538036b51cebb83ebb0b418ec9b089550275d/lib/eff/Staging.ml
ocaml
open Prelude type mode = | Inner | Outer type _ Effect.t += | GetStage : int Effect.t let run ~(stage:int) k = let open Effect.Deep in try_with k () { effc = fun (type a) (eff : a Effect.t) -> match eff with | GetStage -> Option.some @@ fun (k : (a, _) continuation) -> continue k stage | _ -> None } let get_stage () = Effect.perform GetStage let incr_stage stage k = let current_stage = Effect.perform GetStage in let mode = if current_stage + 1 > stage then Outer else Inner in run ~stage:(current_stage + 1) @@ fun () -> k mode let decr_stage stage k = let current_stage = Effect.perform GetStage in let mode = if current_stage - 1 <= stage then Inner else Outer in run ~stage:(current_stage - 1) @@ fun () -> k mode
da46332cb6e70fe08d6f4305e401f6671373ae00f61ef9100e13b0948d61362f
amnh/PCG
Internal.hs
----------------------------------------------------------------------------- -- | Module : Analysis . . Dynamic . DirectOptimization . Pairwise . Internal Copyright : ( c ) 2015 - 2021 Ward Wheeler -- License : BSD-style -- -- Maintainer : -- Stability : provisional -- Portability : portable -- Defines the primitive operations for standard Needleman - Wunsch and -- algorithms for performing a direct optimization heuristic alignment between two dynamic characters . -- ----------------------------------------------------------------------------- {-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE DerivingStrategies #-} {-# LANGUAGE FlexibleContexts #-} # LANGUAGE MultiParamTypeClasses # # LANGUAGE TypeFamilies # module Analysis.Parsimony.Dynamic.DirectOptimization.Pairwise.Internal ( Cost , Direction(..) , DOCharConstraint , MatrixConstraint , MatrixFunction , NeedlemanWunchMatrix , OverlapFunction -- * Direct Optimization primitive construction functions , directOptimization , handleMissingCharacter , handleMissingCharacterThreeway , measureCharacters , measureAndUngapCharacters , needlemanWunschDefinition -- , renderCostMatrix -- , traceback ) where import Bio.Character.Encodable import Control.Monad.State.Strict import Data.DList (snoc) import Data.Foldable import Data.IntMap (IntMap) import Data.Key import qualified Data.List.NonEmpty as NE import Data.Matrix.NotStupid (Matrix) import Data.Maybe (fromMaybe) import Data.MonoTraversable import Data.Ord import qualified Data.Vector.Generic as G import qualified Data.Vector.Generic.Mutable as M import qualified Data.Vector.Primitive as P import qualified Data.Vector.Unboxed as U import Data.Word (Word8) import Numeric.Extended.Natural import Prelude hiding (lookup, zipWith) -- | -- Which direction to align the character at a given matrix point. -- It should be noted that the ordering of the three arrow types are important , as it guarantees that the derived ' ' instance will have the following -- property: -- DiagArrow < LeftArrow < UpArrow -- -- This means: -- - DiagArrow has highest precedence when one or more costs are equal -- - LeftArrow has second highest precedence when one or more costs are equal -- - UpArrow has lowest precedence when one or more costs are equal -- Using this ' ' instance , we can resolve ambiguous transformations in a -- deterministic way. Without loss of generality in determining the ordering, we choose the same biasing as the C code called from the FFI for consistency . data Direction = DiagArrow | LeftArrow | UpArrow deriving stock (Eq, Ord) -- | -- This internal type used for computing the alignment cost. This type has an -- "infinity" value that is conveniently used for the barrier costs. The cost is -- strictly non-negative, and possibly infinite. type Cost = ExtendedNatural -- | -- A representation of an alignment matrix for DO. -- The matrix itself stores tuples of the cost and direction at that position. -- We also store a vector of characters that are generated. type NeedlemanWunchMatrix = Matrix (Cost, Direction) -- | -- Constraints on the input dynamic characters that direct optimization requires -- to operate. , Show ( Element s ) , Show s , Show ( Element s ) , Integral ( Element s ) -- | -- Constraints on the type of structure a "matrix" exposes to be used in rendering -- and traceback functions. type MatrixConstraint m = (Foldable m, Functor m, Indexable m, Key m ~ (Int, Int)) -- | -- A parameterized function to generate an alignment matrix. type MatrixFunction m s = OverlapFunction (Subcomponent (Element s)) -> s -> s -> m (Cost, Direction) -- | -- A generalized function representation: the "overlap" between dynamic character elements , supplying the corresponding median and cost to align the two -- characters. type OverlapFunction e = e -> e -> (e, Word) newtype instance U.MVector s Direction = MV_Direction (P.MVector s Word8) newtype instance U.Vector Direction = V_Direction (P.Vector Word8) instance U.Unbox Direction instance M.MVector U.MVector Direction where # INLINE basicLength # basicLength (MV_Direction v) = M.basicLength v # INLINE basicUnsafeSlice # basicUnsafeSlice i n (MV_Direction v) = MV_Direction $ M.basicUnsafeSlice i n v # INLINE basicOverlaps # basicOverlaps (MV_Direction v1) (MV_Direction v2) = M.basicOverlaps v1 v2 # INLINE basicUnsafeNew # basicUnsafeNew n = MV_Direction <$> M.basicUnsafeNew n # INLINE basicInitialize # basicInitialize (MV_Direction v) = M.basicInitialize v # INLINE basicUnsafeReplicate # basicUnsafeReplicate n x = MV_Direction <$> M.basicUnsafeReplicate n (fromDirection x) # INLINE basicUnsafeRead # basicUnsafeRead (MV_Direction v) i = toDirection <$> M.basicUnsafeRead v i # INLINE basicUnsafeWrite # basicUnsafeWrite (MV_Direction v) i x = M.basicUnsafeWrite v i (fromDirection x) # INLINE basicClear # basicClear (MV_Direction v) = M.basicClear v # INLINE basicSet # basicSet (MV_Direction v) x = M.basicSet v (fromDirection x) # INLINE basicUnsafeCopy # basicUnsafeCopy (MV_Direction v1) (MV_Direction v2) = M.basicUnsafeCopy v1 v2 basicUnsafeMove (MV_Direction v1) (MV_Direction v2) = M.basicUnsafeMove v1 v2 # INLINE basicUnsafeGrow # basicUnsafeGrow (MV_Direction v) n = MV_Direction <$> M.basicUnsafeGrow v n instance G.Vector U.Vector Direction where # INLINE basicUnsafeFreeze # basicUnsafeFreeze (MV_Direction v) = V_Direction <$> G.basicUnsafeFreeze v # INLINE basicUnsafeThaw # basicUnsafeThaw (V_Direction v) = MV_Direction <$> G.basicUnsafeThaw v # INLINE basicLength # basicLength (V_Direction v) = G.basicLength v # INLINE basicUnsafeSlice # basicUnsafeSlice i n (V_Direction v) = V_Direction $ G.basicUnsafeSlice i n v # INLINE basicUnsafeIndexM # basicUnsafeIndexM (V_Direction v) i = toDirection <$> G.basicUnsafeIndexM v i basicUnsafeCopy (MV_Direction mv) (V_Direction v) = G.basicUnsafeCopy mv v # INLINE elemseq # elemseq _ = seq instance Show Direction where show DiagArrow = "↖" show LeftArrow = "←" show UpArrow = "↑" -- | -- Wraps the primitive operations in this module to a cohesive operation that is -- parameterized by an 'OverlapFunction'. -- -- Reused internally by different implementations. # SCC directOptimization # # INLINE directOptimization # { - # SPECIALISE directOptimization : : MatrixConstraint m = > DynamicCharacter - > DynamicCharacter - > OverlapFunction DynamicCharacterElement - > MatrixFunction m DynamicCharacter - > ( Word , DynamicCharacter , DynamicCharacter , DynamicCharacter , DynamicCharacter ) # - } directOptimization :: ( DOCharConstraint s , MatrixConstraint m ) => OverlapFunction (Subcomponent (Element s)) -> s -> s -> MatrixFunction m s -> (Word, s) directOptimization overlapλ char1 char2 matrixFunction = let (swapped, gapsLesser, gapsLonger, shorterChar, longerChar) = measureAndUngapCharacters char1 char2 (alignmentCost, ungappedAlignment) = if olength shorterChar == 0 then if olength longerChar == 0 -- Neither character was Missing, but both are empty when gaps are removed then (0, toMissing char1) Neither character was Missing , but one of them is empty when gaps are removed else let gap = getMedian $ gapOfStream char1 f x = let m = getMedian x in deleteElement (fst $ overlapλ m gap) m in (0, omap f longerChar) -- Both have some non-gap elements, perform string alignment else let traversalMatrix = matrixFunction overlapλ longerChar shorterChar in traceback overlapλ traversalMatrix longerChar shorterChar transformation = if swapped then omap swapContext else id regappedAlignment = insertGaps gapsLesser gapsLonger ungappedAlignment alignmentContext = transformation regappedAlignment in handleMissingCharacter char1 char2 (alignmentCost, alignmentContext) -- | -- A generalized function to handle missing dynamic characters. -- -- Intended to be reused by multiple, differing implementations. # INLINE handleMissingCharacter # # SPECIALISE handleMissingCharacter : : DynamicCharacter - > DynamicCharacter - > ( Word , DynamicCharacter ) - > ( Word , DynamicCharacter ) # handleMissingCharacter :: PossiblyMissingCharacter s => s -> s -> (Word, s) -> (Word, s) handleMissingCharacter lhs rhs v = -- Appropriately handle missing data: case (isMissing lhs, isMissing rhs) of (True , True ) -> (0, lhs) (True , False) -> (0, rhs) (False, True ) -> (0, lhs) (False, False) -> v -- | As ` handleMissingCharacter ` , but with three inputs . -- For use in FFI 3D calls to C. # INLINE handleMissingCharacterThreeway # # SPECIALISE handleMissingCharacterThreeway : : ( DynamicCharacter - > DynamicCharacter - > ( Word , DynamicCharacter , DynamicCharacter , DynamicCharacter , DynamicCharacter ) ) - > DynamicCharacter - > DynamicCharacter - > DynamicCharacter - > ( Word , DynamicCharacter , DynamicCharacter , DynamicCharacter , DynamicCharacter , DynamicCharacter ) - > ( Word , DynamicCharacter , DynamicCharacter , DynamicCharacter , DynamicCharacter , DynamicCharacter ) # handleMissingCharacterThreeway :: PossiblyMissingCharacter s fn takes two inputs , gives back cost , , gapped , two alignments -> s -> s -> s -> (Word, s, s, s, s, s) -> (Word, s, s, s, s, s) handleMissingCharacterThreeway f a b c v = -- Appropriately handle missing data: case (isMissing a, isMissing b, isMissing c) of WLOG . return cost = 0 (True , True , False) -> (0, c, c, c, c, c) (True , False, True ) -> (0, b, b, b, b, b) (True , False, False) -> let (cost, ungapd, gapd, lhs, rhs) = f b c in (cost, ungapd, gapd, undefined, lhs, rhs) (False, True , True ) -> (0, a, a, a, a, a) (False, True , False) -> let (cost, ungapd, gapd, lhs, rhs) = f a c in (cost, ungapd, gapd, lhs, undefined, rhs) (False, False, True ) -> let (cost, ungapd, gapd, lhs, rhs) = f a b in (cost, ungapd, gapd, lhs, rhs, undefined) (False, False, False) -> v -- | -- /O(1)/ for input characters of differing lengths -- /O(k)/ for input characters of equal length , where is the shared prefix of -- both characters. -- Returns the dynamic character that is shorter first , longer second , and notes -- whether or not the inputs were swapped to place the characters in this ordering. -- -- Handles equal length characters by considering the lexicographically larger -- character as longer. -- Handles equality of inputs by /not/ swapping . # INLINE measureCharacters # # SPECIALISE measureCharacters : : DynamicCharacter - > DynamicCharacter - > ( Ordering , DynamicCharacter , DynamicCharacter ) # measureCharacters :: ( EncodableDynamicCharacterElement (Element s) , MonoFoldable s , Ord (Element s) , Ord (Subcomponent (Element s)) ) => s -> s -> (Ordering, s, s) measureCharacters lhs rhs | lhsOrdering == GT = (lhsOrdering, rhs, lhs) | otherwise = (lhsOrdering, lhs, rhs) where lhsOrdering = First , compare inputs by length . case comparing olength lhs rhs of -- If the inputs are equal length, -- Then compare by the (arbitrary) lexicographical ordering of the median states. EQ -> let x = otoList lhs y = otoList rhs f = fmap getMedian in case f x `compare` f y of -- If the input median states have the same ordering, -- Lastly, we compare by the lexicographic ordering of the "tagged triples." -- -- If they are equal after this step, -- Then the inputs are representationally equal. Actually , honest to goodness 100 % equal ! EQ -> x `compare` y v -> v v -> v -- | -- /O(1)/ for input characters of differing lengths -- /O(k)/ for input characters of equal length , where is the shared prefix of -- both characters. -- -- Considers the median values of the characters, ignores the left/right tagging. -- First remove the gaps from the input characters . -- -- If both "ungapped" inputs are empty, we measure the original "gapped" inputs to -- determine if the inputs need to be swapped. This is required to ensure comutativity -- of subsequent operations which use this method. -- Returns the " ungapped " dynamic character that is " shorter " first , " longer " second , -- the removed gap mappings (in the same order), and notes whether or not the inputs -- were swapped to place the characters in this ordering. -- -- Handles equal length characters by considering the lexicographically larger -- character as longer. -- Handles equality of inputs by /not/ swapping . # INLINE measureAndUngapCharacters # # SPECIALISE measureAndUngapCharacters : : DynamicCharacter - > DynamicCharacter - > ( , IntMap Word , IntMap Word , DynamicCharacter , DynamicCharacter ) # measureAndUngapCharacters :: ( EncodableDynamicCharacter s , Ord (Subcomponent (Element s)) ) => s -> s -> (Bool, IntMap Word, IntMap Word, s, s) measureAndUngapCharacters char1 char2 | swapInputs = (True , gapsChar2, gapsChar1, ungappedChar2, ungappedChar1) | otherwise = (False, gapsChar1, gapsChar2, ungappedChar1, ungappedChar2) where swapInputs = measure == GT (gapsChar1, ungappedChar1) = deleteGaps char1 (gapsChar2, ungappedChar2) = deleteGaps char2 (measure, _, _) = case measureCharacters ungappedChar1 ungappedChar2 of (EQ,_,_) -> measureCharacters char1 char2 x -> x -- | Internal generator function for the matrices based on the - Wunsch -- definition described in their paper. # INLINE needlemanWunschDefinition # { - # SPECIALISE needlemanWunschDefinition : : ( f , Key f ~ ( Int , Int ) ) = > DynamicCharacter - > DynamicCharacter - > OverlapFunction DynamicCharacterElement - > f ( Cost , Direction , ) - > ( Int , Int ) - > ( Cost , Direction , ) # - } needlemanWunschDefinition :: ( DOCharConstraint s , Indexable f , Key f ~ (Int, Int) ) => OverlapFunction (Subcomponent (Element s)) -> s -> s -> f (Cost, Direction) -> (Int, Int) -> (Cost, Direction) needlemanWunschDefinition overlapFunction topChar leftChar memo p@(row, col) | p == (0,0) = ( 0, DiagArrow) | otherwise = (minCost, minDir) where -- | Lookup with a default value of infinite cost. {-# INLINE (!?) #-} (!?) m k = fromMaybe (infinity, DiagArrow) $ k `lookup` m gap = gapOfStream topChar gapGroup = getMedian gap topElement = getMedian . fromMaybe gap $ topChar `lookupStream` (col - 1) leftElement = getMedian . fromMaybe gap $ leftChar `lookupStream` (row - 1) (leftwardValue, _) = memo !? (row , col - 1) (diagonalValue, _) = memo !? (row - 1, col - 1) ( upwardValue, _) = memo !? (row - 1, col ) (_, rightOverlapCost) = fromFinite <$> overlapFunction topElement gapGroup (_, diagOverlapCost) = fromFinite <$> overlapFunction topElement leftElement (_, downOverlapCost) = fromFinite <$> overlapFunction gapGroup leftElement rightCost = rightOverlapCost + leftwardValue diagCost = diagOverlapCost + diagonalValue downCost = downOverlapCost + upwardValue (minCost, minDir) = minimum [ (diagCost , DiagArrow) , (rightCost, LeftArrow) , (downCost , UpArrow ) ] - -- | -- Serializes an alignment matrix to a ' String ' . Uses input characters for row -- and column labelings . -- -- Useful for debugging purposes . renderCostMatrix : : ( DOCharConstraint s , Foldable f , Functor f , f , Key f ~ ( Int , Int ) , Show a , Show b ) = > s - > s - > f ( a , b ) -- ^ The - Wunsch alignment matrix - > String renderCostMatrix lhs rhs mtx = unlines [ dimensionPrefix , headerRow , barRow , renderedRows ] where ( _ , longer , lesser ) = measureCharacters lhs rhs longerTokens = toShownIntegers longer = toShownIntegers lesser -- toShownIntegers = fmap ( show . showBitsValue ) . otoList toShownIntegers = fmap ( const " # " ) . otoList matrixTokens = showCell < $ > mtx showCell ( c , d ) = show c < > show d maxPrefixWidth = maxLengthOf lesserTokens maxColumnWidth = max ( maxLengthOf longerTokens ) . maxLengthOf $ toList matrixTokens maxLengthOf = maximum . fmap length { - showBitsValue : : FiniteBits b = > b - > Word showBitsValue b = go ( finiteBitSize b ) 0 where go 0 v = v go i v = let i ' = i-1 v ' | b ` testBit ` i ' = v + bit i ' | otherwise = v in go i ' v ' -- | -- Serializes an alignment matrix to a 'String'. Uses input characters for row -- and column labelings. -- -- Useful for debugging purposes. renderCostMatrix :: ( DOCharConstraint s , Foldable f , Functor f , Indexable f , Key f ~ (Int, Int) , Show a , Show b ) => s -> s -> f (a, b) -- ^ The Needleman-Wunsch alignment matrix -> String renderCostMatrix lhs rhs mtx = unlines [ dimensionPrefix , headerRow , barRow , renderedRows ] where (_,longer,lesser) = measureCharacters lhs rhs longerTokens = toShownIntegers longer lesserTokens = toShownIntegers lesser -- toShownIntegers = fmap (show . showBitsValue) . otoList toShownIntegers = fmap (const "#") . otoList matrixTokens = showCell <$> mtx showCell (c,d) = show c <> show d maxPrefixWidth = maxLengthOf lesserTokens maxColumnWidth = max (maxLengthOf longerTokens) . maxLengthOf $ toList matrixTokens maxLengthOf = maximum . fmap length {- showBitsValue :: FiniteBits b => b -> Word showBitsValue b = go (finiteBitSize b) 0 where go 0 v = v go i v = let i' = i-1 v' | b `testBit` i' = v + bit i' | otherwise = v in go i' v' -} colCount = olength longer + 1 rowCount = olength lesser + 1 dimensionPrefix = " " <> unwords [ "Dimensions:" , show rowCount , "X" , show colCount ] headerRow = mconcat [ " " , pad maxPrefixWidth "\\" , "| " , pad maxColumnWidth "*" , concatMap (pad maxColumnWidth) longerTokens ] barRow = mconcat [ " " , bar maxPrefixWidth , "+" , concatMap (const (bar maxColumnWidth)) $ undefined : longerTokens ] where bar n = replicate (n+1) '-' renderedRows = unlines . zipWith renderRow ("*":lesserTokens) $ getRows matrixTokens where renderRow e vs = " " <> pad maxPrefixWidth e <> "| " <> concatMap (pad maxColumnWidth) vs getRows m = (`getRow'` m) <$> [0 .. rowCount - 1] getRow' i m = g <$> [0 .. colCount - 1] where g j = fromMaybe "" $ (i,j) `lookup` m pad :: Int -> String -> String pad n e = replicate (n - len) ' ' <> e <> " " where len = length e --} -- | -- Performs the traceback of an 'NeedlemanWunchMatrix'. -- Takes in an ' NeedlemanWunchMatrix ' , two ' EncodableDynamicCharacter 's and returns an -- aligned 'EncodableDynamicCharacter', as well as the aligned versions of the two inputs . Essentially does the second step of Needleman - Wunsch , following -- the arrows from the bottom right corner, accumulating the sequences as it goes, but returns three alignments : the left character , the right character , and the parent . The child alignments * should * be biased toward the shorter of the two -- dynamic characters. # INLINE traceback # { - # SPECIALISE traceback : : ( f , Key f ~ ( Int , Int ) ) = > f ( Cost , Direction , ) - > DynamicCharacter - > DynamicCharacter - > ( Word , DynamicCharacter , DynamicCharacter , DynamicCharacter , DynamicCharacter ) # - } traceback :: ( DOCharConstraint s -- , Foldable f -- , Functor f , Indexable f , Key f ~ (Int, Int) ) => OverlapFunction (Subcomponent (Element s)) -> f (Cost, Direction) -> s -> s -> (Word, s) --traceback _ alignMatrix longerChar lesserChar | trace (renderCostMatrix longerChar lesserChar alignMatrix) False = undefined traceback overlapFunction alignMatrix longerChar lesserChar = (finalCost, alignmentContext) where f x y = fst $ overlapFunction x y finalCost = unsafeToFinite cost alignmentContext = dlistToDynamic $ go lastCell lastCell = (row, col) (cost, _) = alignMatrix ! lastCell dlistToDynamic = constructDynamic . NE.fromList . toList col = olength longerChar row = olength lesserChar gap = getMedian $ gapOfStream longerChar go p@(i, j) | p == (0,0) = mempty | otherwise = previousSequence `snoc` localContext where previousSequence = go (row', col') (_, directionArrow) = alignMatrix ! p (row', col', localContext) = case directionArrow of LeftArrow -> let j' = j-1 y = getMedian $ longerChar `indexStream` j' e = deleteElement (f gap y) y in (i , j', e) UpArrow -> let i' = i-1 x = getMedian $ lesserChar `indexStream` i' e = insertElement (f x gap) x in (i', j , e) DiagArrow -> let i' = i-1 j' = j-1 x = getMedian $ lesserChar `indexStream` i' y = getMedian $ longerChar `indexStream` j' e = alignElement (f x y) x y in (i', j', e) {- {-# INLINE getMinimalCostDirection #-} # SPECIALISE getMinimalCostDirection : : ( Cost , ) - > ( Cost , ) - > ( Cost , ) - > ( Cost , , Direction ) # getMinimalCostDirection :: (EncodableStreamElement e, Ord c) => (c, e) -> (c, e) -> (c, e) -> (c, e, Direction) getMinimalCostDirection (diagCost, diagChar) (rightCost, rightChar) (downCost, downChar) = minimumBy (comparing (\(c,d) -> (c,d))) [ (diagCost , DiagArrow) , (rightCost, LeftArrow) , (downCost , UpArrow ) ] where gap = getGapElement diagChar -} # INLINE fromDirection # fromDirection :: Direction -> Word8 fromDirection DiagArrow = 0 fromDirection LeftArrow = 1 fromDirection UpArrow = 2 # INLINE toDirection # toDirection :: Word8 -> Direction toDirection 0 = DiagArrow toDirection 1 = LeftArrow toDirection _ = UpArrow
null
https://raw.githubusercontent.com/amnh/PCG/9341efe0ec2053302c22b4466157d0a24ed18154/lib/core/analysis/src/Analysis/Parsimony/Dynamic/DirectOptimization/Pairwise/Internal.hs
haskell
--------------------------------------------------------------------------- | License : BSD-style Maintainer : Stability : provisional Portability : portable algorithms for performing a direct optimization heuristic alignment between --------------------------------------------------------------------------- # LANGUAGE ConstraintKinds # # LANGUAGE DerivingStrategies # # LANGUAGE FlexibleContexts # * Direct Optimization primitive construction functions , renderCostMatrix , traceback | Which direction to align the character at a given matrix point. property: This means: deterministic way. Without loss of generality in determining the ordering, | This internal type used for computing the alignment cost. This type has an "infinity" value that is conveniently used for the barrier costs. The cost is strictly non-negative, and possibly infinite. | A representation of an alignment matrix for DO. The matrix itself stores tuples of the cost and direction at that position. We also store a vector of characters that are generated. | Constraints on the input dynamic characters that direct optimization requires to operate. | Constraints on the type of structure a "matrix" exposes to be used in rendering and traceback functions. | A parameterized function to generate an alignment matrix. | A generalized function representation: the "overlap" between dynamic character characters. | Wraps the primitive operations in this module to a cohesive operation that is parameterized by an 'OverlapFunction'. Reused internally by different implementations. Neither character was Missing, but both are empty when gaps are removed Both have some non-gap elements, perform string alignment | A generalized function to handle missing dynamic characters. Intended to be reused by multiple, differing implementations. Appropriately handle missing data: | Appropriately handle missing data: | /O(1)/ for input characters of differing lengths both characters. whether or not the inputs were swapped to place the characters in this ordering. Handles equal length characters by considering the lexicographically larger character as longer. If the inputs are equal length, Then compare by the (arbitrary) lexicographical ordering of the median states. If the input median states have the same ordering, Lastly, we compare by the lexicographic ordering of the "tagged triples." If they are equal after this step, Then the inputs are representationally equal. | /O(1)/ for input characters of differing lengths both characters. Considers the median values of the characters, ignores the left/right tagging. If both "ungapped" inputs are empty, we measure the original "gapped" inputs to determine if the inputs need to be swapped. This is required to ensure comutativity of subsequent operations which use this method. the removed gap mappings (in the same order), and notes whether or not the inputs were swapped to place the characters in this ordering. Handles equal length characters by considering the lexicographically larger character as longer. | definition described in their paper. | Lookup with a default value of infinite cost. # INLINE (!?) # | Serializes an alignment matrix to a ' String ' . Uses input characters for row and column labelings . Useful for debugging purposes . ^ The - Wunsch alignment matrix toShownIntegers = fmap ( show . showBitsValue ) . otoList | Serializes an alignment matrix to a 'String'. Uses input characters for row and column labelings. Useful for debugging purposes. ^ The Needleman-Wunsch alignment matrix toShownIntegers = fmap (show . showBitsValue) . otoList showBitsValue :: FiniteBits b => b -> Word showBitsValue b = go (finiteBitSize b) 0 where go 0 v = v go i v = let i' = i-1 v' | b `testBit` i' = v + bit i' | otherwise = v in go i' v' } | Performs the traceback of an 'NeedlemanWunchMatrix'. aligned 'EncodableDynamicCharacter', as well as the aligned versions of the the arrows from the bottom right corner, accumulating the sequences as it goes, dynamic characters. , Foldable f , Functor f traceback _ alignMatrix longerChar lesserChar | trace (renderCostMatrix longerChar lesserChar alignMatrix) False = undefined {-# INLINE getMinimalCostDirection #
Module : Analysis . . Dynamic . DirectOptimization . Pairwise . Internal Copyright : ( c ) 2015 - 2021 Ward Wheeler Defines the primitive operations for standard Needleman - Wunsch and two dynamic characters . # LANGUAGE MultiParamTypeClasses # # LANGUAGE TypeFamilies # module Analysis.Parsimony.Dynamic.DirectOptimization.Pairwise.Internal ( Cost , Direction(..) , DOCharConstraint , MatrixConstraint , MatrixFunction , NeedlemanWunchMatrix , OverlapFunction , directOptimization , handleMissingCharacter , handleMissingCharacterThreeway , measureCharacters , measureAndUngapCharacters , needlemanWunschDefinition ) where import Bio.Character.Encodable import Control.Monad.State.Strict import Data.DList (snoc) import Data.Foldable import Data.IntMap (IntMap) import Data.Key import qualified Data.List.NonEmpty as NE import Data.Matrix.NotStupid (Matrix) import Data.Maybe (fromMaybe) import Data.MonoTraversable import Data.Ord import qualified Data.Vector.Generic as G import qualified Data.Vector.Generic.Mutable as M import qualified Data.Vector.Primitive as P import qualified Data.Vector.Unboxed as U import Data.Word (Word8) import Numeric.Extended.Natural import Prelude hiding (lookup, zipWith) It should be noted that the ordering of the three arrow types are important , as it guarantees that the derived ' ' instance will have the following DiagArrow < LeftArrow < UpArrow - DiagArrow has highest precedence when one or more costs are equal - LeftArrow has second highest precedence when one or more costs are equal - UpArrow has lowest precedence when one or more costs are equal Using this ' ' instance , we can resolve ambiguous transformations in a we choose the same biasing as the C code called from the FFI for consistency . data Direction = DiagArrow | LeftArrow | UpArrow deriving stock (Eq, Ord) type Cost = ExtendedNatural type NeedlemanWunchMatrix = Matrix (Cost, Direction) , Show ( Element s ) , Show s , Show ( Element s ) , Integral ( Element s ) type MatrixConstraint m = (Foldable m, Functor m, Indexable m, Key m ~ (Int, Int)) type MatrixFunction m s = OverlapFunction (Subcomponent (Element s)) -> s -> s -> m (Cost, Direction) elements , supplying the corresponding median and cost to align the two type OverlapFunction e = e -> e -> (e, Word) newtype instance U.MVector s Direction = MV_Direction (P.MVector s Word8) newtype instance U.Vector Direction = V_Direction (P.Vector Word8) instance U.Unbox Direction instance M.MVector U.MVector Direction where # INLINE basicLength # basicLength (MV_Direction v) = M.basicLength v # INLINE basicUnsafeSlice # basicUnsafeSlice i n (MV_Direction v) = MV_Direction $ M.basicUnsafeSlice i n v # INLINE basicOverlaps # basicOverlaps (MV_Direction v1) (MV_Direction v2) = M.basicOverlaps v1 v2 # INLINE basicUnsafeNew # basicUnsafeNew n = MV_Direction <$> M.basicUnsafeNew n # INLINE basicInitialize # basicInitialize (MV_Direction v) = M.basicInitialize v # INLINE basicUnsafeReplicate # basicUnsafeReplicate n x = MV_Direction <$> M.basicUnsafeReplicate n (fromDirection x) # INLINE basicUnsafeRead # basicUnsafeRead (MV_Direction v) i = toDirection <$> M.basicUnsafeRead v i # INLINE basicUnsafeWrite # basicUnsafeWrite (MV_Direction v) i x = M.basicUnsafeWrite v i (fromDirection x) # INLINE basicClear # basicClear (MV_Direction v) = M.basicClear v # INLINE basicSet # basicSet (MV_Direction v) x = M.basicSet v (fromDirection x) # INLINE basicUnsafeCopy # basicUnsafeCopy (MV_Direction v1) (MV_Direction v2) = M.basicUnsafeCopy v1 v2 basicUnsafeMove (MV_Direction v1) (MV_Direction v2) = M.basicUnsafeMove v1 v2 # INLINE basicUnsafeGrow # basicUnsafeGrow (MV_Direction v) n = MV_Direction <$> M.basicUnsafeGrow v n instance G.Vector U.Vector Direction where # INLINE basicUnsafeFreeze # basicUnsafeFreeze (MV_Direction v) = V_Direction <$> G.basicUnsafeFreeze v # INLINE basicUnsafeThaw # basicUnsafeThaw (V_Direction v) = MV_Direction <$> G.basicUnsafeThaw v # INLINE basicLength # basicLength (V_Direction v) = G.basicLength v # INLINE basicUnsafeSlice # basicUnsafeSlice i n (V_Direction v) = V_Direction $ G.basicUnsafeSlice i n v # INLINE basicUnsafeIndexM # basicUnsafeIndexM (V_Direction v) i = toDirection <$> G.basicUnsafeIndexM v i basicUnsafeCopy (MV_Direction mv) (V_Direction v) = G.basicUnsafeCopy mv v # INLINE elemseq # elemseq _ = seq instance Show Direction where show DiagArrow = "↖" show LeftArrow = "←" show UpArrow = "↑" # SCC directOptimization # # INLINE directOptimization # { - # SPECIALISE directOptimization : : MatrixConstraint m = > DynamicCharacter - > DynamicCharacter - > OverlapFunction DynamicCharacterElement - > MatrixFunction m DynamicCharacter - > ( Word , DynamicCharacter , DynamicCharacter , DynamicCharacter , DynamicCharacter ) # - } directOptimization :: ( DOCharConstraint s , MatrixConstraint m ) => OverlapFunction (Subcomponent (Element s)) -> s -> s -> MatrixFunction m s -> (Word, s) directOptimization overlapλ char1 char2 matrixFunction = let (swapped, gapsLesser, gapsLonger, shorterChar, longerChar) = measureAndUngapCharacters char1 char2 (alignmentCost, ungappedAlignment) = if olength shorterChar == 0 then if olength longerChar == 0 then (0, toMissing char1) Neither character was Missing , but one of them is empty when gaps are removed else let gap = getMedian $ gapOfStream char1 f x = let m = getMedian x in deleteElement (fst $ overlapλ m gap) m in (0, omap f longerChar) else let traversalMatrix = matrixFunction overlapλ longerChar shorterChar in traceback overlapλ traversalMatrix longerChar shorterChar transformation = if swapped then omap swapContext else id regappedAlignment = insertGaps gapsLesser gapsLonger ungappedAlignment alignmentContext = transformation regappedAlignment in handleMissingCharacter char1 char2 (alignmentCost, alignmentContext) # INLINE handleMissingCharacter # # SPECIALISE handleMissingCharacter : : DynamicCharacter - > DynamicCharacter - > ( Word , DynamicCharacter ) - > ( Word , DynamicCharacter ) # handleMissingCharacter :: PossiblyMissingCharacter s => s -> s -> (Word, s) -> (Word, s) handleMissingCharacter lhs rhs v = case (isMissing lhs, isMissing rhs) of (True , True ) -> (0, lhs) (True , False) -> (0, rhs) (False, True ) -> (0, lhs) (False, False) -> v As ` handleMissingCharacter ` , but with three inputs . For use in FFI 3D calls to C. # INLINE handleMissingCharacterThreeway # # SPECIALISE handleMissingCharacterThreeway : : ( DynamicCharacter - > DynamicCharacter - > ( Word , DynamicCharacter , DynamicCharacter , DynamicCharacter , DynamicCharacter ) ) - > DynamicCharacter - > DynamicCharacter - > DynamicCharacter - > ( Word , DynamicCharacter , DynamicCharacter , DynamicCharacter , DynamicCharacter , DynamicCharacter ) - > ( Word , DynamicCharacter , DynamicCharacter , DynamicCharacter , DynamicCharacter , DynamicCharacter ) # handleMissingCharacterThreeway :: PossiblyMissingCharacter s fn takes two inputs , gives back cost , , gapped , two alignments -> s -> s -> s -> (Word, s, s, s, s, s) -> (Word, s, s, s, s, s) handleMissingCharacterThreeway f a b c v = case (isMissing a, isMissing b, isMissing c) of WLOG . return cost = 0 (True , True , False) -> (0, c, c, c, c, c) (True , False, True ) -> (0, b, b, b, b, b) (True , False, False) -> let (cost, ungapd, gapd, lhs, rhs) = f b c in (cost, ungapd, gapd, undefined, lhs, rhs) (False, True , True ) -> (0, a, a, a, a, a) (False, True , False) -> let (cost, ungapd, gapd, lhs, rhs) = f a c in (cost, ungapd, gapd, lhs, undefined, rhs) (False, False, True ) -> let (cost, ungapd, gapd, lhs, rhs) = f a b in (cost, ungapd, gapd, lhs, rhs, undefined) (False, False, False) -> v /O(k)/ for input characters of equal length , where is the shared prefix of Returns the dynamic character that is shorter first , longer second , and notes Handles equality of inputs by /not/ swapping . # INLINE measureCharacters # # SPECIALISE measureCharacters : : DynamicCharacter - > DynamicCharacter - > ( Ordering , DynamicCharacter , DynamicCharacter ) # measureCharacters :: ( EncodableDynamicCharacterElement (Element s) , MonoFoldable s , Ord (Element s) , Ord (Subcomponent (Element s)) ) => s -> s -> (Ordering, s, s) measureCharacters lhs rhs | lhsOrdering == GT = (lhsOrdering, rhs, lhs) | otherwise = (lhsOrdering, lhs, rhs) where lhsOrdering = First , compare inputs by length . case comparing olength lhs rhs of EQ -> let x = otoList lhs y = otoList rhs f = fmap getMedian in case f x `compare` f y of Actually , honest to goodness 100 % equal ! EQ -> x `compare` y v -> v v -> v /O(k)/ for input characters of equal length , where is the shared prefix of First remove the gaps from the input characters . Returns the " ungapped " dynamic character that is " shorter " first , " longer " second , Handles equality of inputs by /not/ swapping . # INLINE measureAndUngapCharacters # # SPECIALISE measureAndUngapCharacters : : DynamicCharacter - > DynamicCharacter - > ( , IntMap Word , IntMap Word , DynamicCharacter , DynamicCharacter ) # measureAndUngapCharacters :: ( EncodableDynamicCharacter s , Ord (Subcomponent (Element s)) ) => s -> s -> (Bool, IntMap Word, IntMap Word, s, s) measureAndUngapCharacters char1 char2 | swapInputs = (True , gapsChar2, gapsChar1, ungappedChar2, ungappedChar1) | otherwise = (False, gapsChar1, gapsChar2, ungappedChar1, ungappedChar2) where swapInputs = measure == GT (gapsChar1, ungappedChar1) = deleteGaps char1 (gapsChar2, ungappedChar2) = deleteGaps char2 (measure, _, _) = case measureCharacters ungappedChar1 ungappedChar2 of (EQ,_,_) -> measureCharacters char1 char2 x -> x Internal generator function for the matrices based on the - Wunsch # INLINE needlemanWunschDefinition # { - # SPECIALISE needlemanWunschDefinition : : ( f , Key f ~ ( Int , Int ) ) = > DynamicCharacter - > DynamicCharacter - > OverlapFunction DynamicCharacterElement - > f ( Cost , Direction , ) - > ( Int , Int ) - > ( Cost , Direction , ) # - } needlemanWunschDefinition :: ( DOCharConstraint s , Indexable f , Key f ~ (Int, Int) ) => OverlapFunction (Subcomponent (Element s)) -> s -> s -> f (Cost, Direction) -> (Int, Int) -> (Cost, Direction) needlemanWunschDefinition overlapFunction topChar leftChar memo p@(row, col) | p == (0,0) = ( 0, DiagArrow) | otherwise = (minCost, minDir) where (!?) m k = fromMaybe (infinity, DiagArrow) $ k `lookup` m gap = gapOfStream topChar gapGroup = getMedian gap topElement = getMedian . fromMaybe gap $ topChar `lookupStream` (col - 1) leftElement = getMedian . fromMaybe gap $ leftChar `lookupStream` (row - 1) (leftwardValue, _) = memo !? (row , col - 1) (diagonalValue, _) = memo !? (row - 1, col - 1) ( upwardValue, _) = memo !? (row - 1, col ) (_, rightOverlapCost) = fromFinite <$> overlapFunction topElement gapGroup (_, diagOverlapCost) = fromFinite <$> overlapFunction topElement leftElement (_, downOverlapCost) = fromFinite <$> overlapFunction gapGroup leftElement rightCost = rightOverlapCost + leftwardValue diagCost = diagOverlapCost + diagonalValue downCost = downOverlapCost + upwardValue (minCost, minDir) = minimum [ (diagCost , DiagArrow) , (rightCost, LeftArrow) , (downCost , UpArrow ) ] - renderCostMatrix : : ( DOCharConstraint s , Foldable f , Functor f , f , Key f ~ ( Int , Int ) , Show a , Show b ) = > s - > s - > String renderCostMatrix lhs rhs mtx = unlines [ dimensionPrefix , headerRow , barRow , renderedRows ] where ( _ , longer , lesser ) = measureCharacters lhs rhs longerTokens = toShownIntegers longer = toShownIntegers lesser toShownIntegers = fmap ( const " # " ) . otoList matrixTokens = showCell < $ > mtx showCell ( c , d ) = show c < > show d maxPrefixWidth = maxLengthOf lesserTokens maxColumnWidth = max ( maxLengthOf longerTokens ) . maxLengthOf $ toList matrixTokens maxLengthOf = maximum . fmap length { - showBitsValue : : FiniteBits b = > b - > Word showBitsValue b = go ( finiteBitSize b ) 0 where go 0 v = v go i v = let i ' = i-1 v ' | b ` testBit ` i ' = v + bit i ' | otherwise = v in go i ' v ' renderCostMatrix :: ( DOCharConstraint s , Foldable f , Functor f , Indexable f , Key f ~ (Int, Int) , Show a , Show b ) => s -> s -> String renderCostMatrix lhs rhs mtx = unlines [ dimensionPrefix , headerRow , barRow , renderedRows ] where (_,longer,lesser) = measureCharacters lhs rhs longerTokens = toShownIntegers longer lesserTokens = toShownIntegers lesser toShownIntegers = fmap (const "#") . otoList matrixTokens = showCell <$> mtx showCell (c,d) = show c <> show d maxPrefixWidth = maxLengthOf lesserTokens maxColumnWidth = max (maxLengthOf longerTokens) . maxLengthOf $ toList matrixTokens maxLengthOf = maximum . fmap length colCount = olength longer + 1 rowCount = olength lesser + 1 dimensionPrefix = " " <> unwords [ "Dimensions:" , show rowCount , "X" , show colCount ] headerRow = mconcat [ " " , pad maxPrefixWidth "\\" , "| " , pad maxColumnWidth "*" , concatMap (pad maxColumnWidth) longerTokens ] barRow = mconcat [ " " , bar maxPrefixWidth , "+" , concatMap (const (bar maxColumnWidth)) $ undefined : longerTokens ] where bar n = replicate (n+1) '-' renderedRows = unlines . zipWith renderRow ("*":lesserTokens) $ getRows matrixTokens where renderRow e vs = " " <> pad maxPrefixWidth e <> "| " <> concatMap (pad maxColumnWidth) vs getRows m = (`getRow'` m) <$> [0 .. rowCount - 1] getRow' i m = g <$> [0 .. colCount - 1] where g j = fromMaybe "" $ (i,j) `lookup` m pad :: Int -> String -> String pad n e = replicate (n - len) ' ' <> e <> " " where len = length e Takes in an ' NeedlemanWunchMatrix ' , two ' EncodableDynamicCharacter 's and returns an two inputs . Essentially does the second step of Needleman - Wunsch , following but returns three alignments : the left character , the right character , and the parent . The child alignments * should * be biased toward the shorter of the two # INLINE traceback # { - # SPECIALISE traceback : : ( f , Key f ~ ( Int , Int ) ) = > f ( Cost , Direction , ) - > DynamicCharacter - > DynamicCharacter - > ( Word , DynamicCharacter , DynamicCharacter , DynamicCharacter , DynamicCharacter ) # - } traceback :: ( DOCharConstraint s , Indexable f , Key f ~ (Int, Int) ) => OverlapFunction (Subcomponent (Element s)) -> f (Cost, Direction) -> s -> s -> (Word, s) traceback overlapFunction alignMatrix longerChar lesserChar = (finalCost, alignmentContext) where f x y = fst $ overlapFunction x y finalCost = unsafeToFinite cost alignmentContext = dlistToDynamic $ go lastCell lastCell = (row, col) (cost, _) = alignMatrix ! lastCell dlistToDynamic = constructDynamic . NE.fromList . toList col = olength longerChar row = olength lesserChar gap = getMedian $ gapOfStream longerChar go p@(i, j) | p == (0,0) = mempty | otherwise = previousSequence `snoc` localContext where previousSequence = go (row', col') (_, directionArrow) = alignMatrix ! p (row', col', localContext) = case directionArrow of LeftArrow -> let j' = j-1 y = getMedian $ longerChar `indexStream` j' e = deleteElement (f gap y) y in (i , j', e) UpArrow -> let i' = i-1 x = getMedian $ lesserChar `indexStream` i' e = insertElement (f x gap) x in (i', j , e) DiagArrow -> let i' = i-1 j' = j-1 x = getMedian $ lesserChar `indexStream` i' y = getMedian $ longerChar `indexStream` j' e = alignElement (f x y) x y in (i', j', e) # SPECIALISE getMinimalCostDirection : : ( Cost , ) - > ( Cost , ) - > ( Cost , ) - > ( Cost , , Direction ) # getMinimalCostDirection :: (EncodableStreamElement e, Ord c) => (c, e) -> (c, e) -> (c, e) -> (c, e, Direction) getMinimalCostDirection (diagCost, diagChar) (rightCost, rightChar) (downCost, downChar) = minimumBy (comparing (\(c,d) -> (c,d))) [ (diagCost , DiagArrow) , (rightCost, LeftArrow) , (downCost , UpArrow ) ] where gap = getGapElement diagChar -} # INLINE fromDirection # fromDirection :: Direction -> Word8 fromDirection DiagArrow = 0 fromDirection LeftArrow = 1 fromDirection UpArrow = 2 # INLINE toDirection # toDirection :: Word8 -> Direction toDirection 0 = DiagArrow toDirection 1 = LeftArrow toDirection _ = UpArrow
84a69f2f966bb5f90daf9e59c3682f79dd5e59acb88338b2fef79a7783b8e44f
janestreet/async_kernel
async_condition.mli
* Async 's implementation of the standard notion of a " condition " variable . This is analogous to 's [ Condition ] module . The main guarantee that a condition variable provides is that a call to [ signal ] ( or [ broadcast ] ) after a call to [ wait ] will be seen by the waiter . Unlike the use of condition variables in ordinary threaded programs , Async condition variables do not require a mutex , since Async programs are cooperatively threaded . This is analogous to OCaml's [Condition] module. The main guarantee that a condition variable provides is that a call to [signal] (or [broadcast]) after a call to [wait] will be seen by the waiter. Unlike the use of condition variables in ordinary threaded programs, Async condition variables do not require a mutex, since Async programs are cooperatively threaded. *) open! Core type 'a t [@@deriving sexp_of] val create : unit -> _ t val signal : 'a t -> 'a -> unit val broadcast : 'a t -> 'a -> unit val wait : 'a t -> 'a Deferred.t
null
https://raw.githubusercontent.com/janestreet/async_kernel/9575c63faac6c2d6af20f0f21ec535401f310296/src/async_condition.mli
ocaml
* Async 's implementation of the standard notion of a " condition " variable . This is analogous to 's [ Condition ] module . The main guarantee that a condition variable provides is that a call to [ signal ] ( or [ broadcast ] ) after a call to [ wait ] will be seen by the waiter . Unlike the use of condition variables in ordinary threaded programs , Async condition variables do not require a mutex , since Async programs are cooperatively threaded . This is analogous to OCaml's [Condition] module. The main guarantee that a condition variable provides is that a call to [signal] (or [broadcast]) after a call to [wait] will be seen by the waiter. Unlike the use of condition variables in ordinary threaded programs, Async condition variables do not require a mutex, since Async programs are cooperatively threaded. *) open! Core type 'a t [@@deriving sexp_of] val create : unit -> _ t val signal : 'a t -> 'a -> unit val broadcast : 'a t -> 'a -> unit val wait : 'a t -> 'a Deferred.t