_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
76d67fbddc91f32f6623e5e832ebb710c700dae8aa975b7375fbaca18a84c680
skanev/playground
25-tests.scm
(require rackunit rackunit/text-ui) (load-relative "../../support/eopl.scm") (load-relative "../25.scm") (load-relative "helpers/proc.scm") (define eopl-3.25-tests (test-suite "Tests for EOPL exercise 3.25" (check-equal? (run the-example-program) 12) )) (exit (run-tests eopl-3.25-tests))
null
https://raw.githubusercontent.com/skanev/playground/d88e53a7f277b35041c2f709771a0b96f993b310/scheme/eopl/03/tests/25-tests.scm
scheme
(require rackunit rackunit/text-ui) (load-relative "../../support/eopl.scm") (load-relative "../25.scm") (load-relative "helpers/proc.scm") (define eopl-3.25-tests (test-suite "Tests for EOPL exercise 3.25" (check-equal? (run the-example-program) 12) )) (exit (run-tests eopl-3.25-tests))
8acfc1596719391fbf2c4b76c8a90d24e78fa6643355dafa3ea9461295ecc9fd
magthe/sandi
Base16Bench.hs
module Codec.Binary.Base16Bench where import Criterion.Main (bench, nf) import Codec.Binary.Base16 mkBenchs data1M data10M = let enc1M = encode data1M enc10M = encode data10M in [ bench "enc base 16 1M" $ nf encode data1M , bench "dec base 16 1M" $ nf decode enc1M , bench "enc base 16 10M" $ nf encode data10M , bench "dec base 16 10M" $ nf decode enc10M ]
null
https://raw.githubusercontent.com/magthe/sandi/a8ef86ec3798a640d86342421a7fa7fa97bdedd4/sandi/bench-src/Codec/Binary/Base16Bench.hs
haskell
module Codec.Binary.Base16Bench where import Criterion.Main (bench, nf) import Codec.Binary.Base16 mkBenchs data1M data10M = let enc1M = encode data1M enc10M = encode data10M in [ bench "enc base 16 1M" $ nf encode data1M , bench "dec base 16 1M" $ nf decode enc1M , bench "enc base 16 10M" $ nf encode data10M , bench "dec base 16 10M" $ nf decode enc10M ]
9198558be8c16707bc45f92ded835e35bf74b1d19f7c66002ec4a91193cce100
soulomoon/SICP
Exercise 2.80.scm
Exercise 2.79 : Define a generic equality predicate equ ? that tests the equality of two numbers , and install it in the generic arithmetic package . This operation should work for ordinary numbers , rational numbers , and complex numbers . (define (make-table) (let ((local-table (list '*table*))) (define (lookup key-1 key-2) (let ((subtable (assoc key-1 (cdr local-table)))) (if subtable (let ((record (assoc key-2 (cdr subtable)))) (if record (cdr record) false)) false))) (define (insert! key-1 key-2 value) (let ((subtable (assoc key-1 (cdr local-table)))) (if subtable (let ((record (assoc key-2 (cdr subtable)))) (if record (set-cdr! record value) (set-cdr! subtable (cons (cons key-2 value) (cdr subtable))))) (set-cdr! local-table (cons (list key-1 (cons key-2 value)) (cdr local-table))))) 'ok) (define (dispatch m) (cond ((eq? m 'lookup-proc) lookup) ((eq? m 'insert-proc!) insert!) (else (error "Unknown operation -- TABLE" m)))) dispatch)) (define operation-table (make-table)) (define get (operation-table 'lookup-proc)) (define put (operation-table 'insert-proc!)) (define (attach-tag type-tag contents) (cons type-tag contents)) (define (type-tag datum) (cond ((number? datum) 'scheme-number) ((pair? datum) (car datum)) (else (error "Bad tagged datum: TYPE-TAG" datum)) ) ) (define (contents datum) (cond ((number? datum) datum) ((pair? datum) (cdr datum)) (else (error "Bad tagged datum: CONTENTS" datum)) ) ) (define (install-scheme-number-package) (define (tag x) x) (put '=zero? '(scheme-number) (lambda (x) (tag (= x 0)))) (put 'equ? '(scheme-number scheme-number) (lambda (x y) (tag (= x y)))) (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))) 'scheme-number-package-done) (install-scheme-number-package) (define (install-rational-package) ;; internal procedures (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 (equ? x y) (if (and (= (numer x) (numer y)) (= (denom x) (denom y))) true false ) ) (define (rational_zero? x) (= 0 (numer x)) ) ;; interface to rest of the system (define (tag x) (attach-tag 'rational x)) (put '=zero? '(rational) rational_zero?) (put 'equ? '(rational rational) equ? ) (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)))) 'rational-package-done) (install-rational-package) (define (install-rectangular-package) ;; internal procedures (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)))) ;; interface to the rest of the system (define (tag x) (attach-tag 'rectangular x)) (put 'real-part '(rectangular) real-part) (put 'imag-part '(rectangular) imag-part) (put 'magnitude '(rectangular) magnitude) (put 'angle '(rectangular) angle) (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)))) 'rectangular-package-done) (install-rectangular-package) (define (install-polar-package) ;; internal procedures (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))) ;; interface to the rest of the system (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)))) 'polar-package-done) (install-polar-package) (define (install-complex-package) ;; imported procedures from rectangular ;; and polar packages (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)) ;; internal procedures (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 (equ? z1 z2) (if (and (= (real-part z1) (real-part z2)) (= (imag-part z1) (imag-part z2))) true false ) ) ;; interface to rest of the system (define (tag z) (attach-tag 'complex z)) (put '=zero? '(complex) (lambda (z1) (and (= (real-part z1) 0) (= (imag-part z1) 0)))) (put 'equ? '(complex complex) equ?) (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)))) 'complex-package-done) (install-complex-package) (define (install-zero?-package) (define (ordinary_zero? x) (= x 0) ) (define (complex_zero? x) (= x 0) ) (put 'zero '(scheme-number) ordinary_zero?) (put 'zero '(complex) complex_zero?) ) (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 (add . args) (apply apply-generic (cons 'add args))) (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 (equ? x y) (apply-generic 'equ? x y)) (define (make-scheme-number n) ((get 'make 'scheme-number) n)) (define (make-rational n d) ((get 'make 'rational) n d)) (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)) (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 (=zero? x) (apply-generic '=zero? x)) (define (equ? x y) (apply-generic 'equ? x y)) (define a (make-complex-from-real-imag 0 0)) (define b (make-complex-from-real-imag 1 0)) (define c (make-rational 0 3)) (define d (make-rational 1 3)) (display (=zero? a))(newline) (display (=zero? b))(newline) (display (=zero? 0))(newline) (display (=zero? 1))(newline) (display (=zero? c))(newline) (display (=zero? d))(newline) Welcome to , version 6.7 [ 3 m ] . Language : SICP ( PLaneT 1.18 ) ; memory limit : 128 MB . ; 'scheme-number-package-done ; 'rational-package-done ; 'rectangular-package-done ; 'polar-package-done ; 'complex-package-done ; #t ; #f ; #t ; #f ; #t ; #f ; >
null
https://raw.githubusercontent.com/soulomoon/SICP/1c6cbf5ecf6397eaeb990738a938d48c193af1bb/Chapter2/Exercise%202.80.scm
scheme
internal procedures interface to rest of the system internal procedures interface to the rest of the system internal procedures interface to the rest of the system imported procedures from rectangular and polar packages internal procedures interface to rest of the system memory limit : 128 MB . 'scheme-number-package-done 'rational-package-done 'rectangular-package-done 'polar-package-done 'complex-package-done #t #f #t #f #t #f >
Exercise 2.79 : Define a generic equality predicate equ ? that tests the equality of two numbers , and install it in the generic arithmetic package . This operation should work for ordinary numbers , rational numbers , and complex numbers . (define (make-table) (let ((local-table (list '*table*))) (define (lookup key-1 key-2) (let ((subtable (assoc key-1 (cdr local-table)))) (if subtable (let ((record (assoc key-2 (cdr subtable)))) (if record (cdr record) false)) false))) (define (insert! key-1 key-2 value) (let ((subtable (assoc key-1 (cdr local-table)))) (if subtable (let ((record (assoc key-2 (cdr subtable)))) (if record (set-cdr! record value) (set-cdr! subtable (cons (cons key-2 value) (cdr subtable))))) (set-cdr! local-table (cons (list key-1 (cons key-2 value)) (cdr local-table))))) 'ok) (define (dispatch m) (cond ((eq? m 'lookup-proc) lookup) ((eq? m 'insert-proc!) insert!) (else (error "Unknown operation -- TABLE" m)))) dispatch)) (define operation-table (make-table)) (define get (operation-table 'lookup-proc)) (define put (operation-table 'insert-proc!)) (define (attach-tag type-tag contents) (cons type-tag contents)) (define (type-tag datum) (cond ((number? datum) 'scheme-number) ((pair? datum) (car datum)) (else (error "Bad tagged datum: TYPE-TAG" datum)) ) ) (define (contents datum) (cond ((number? datum) datum) ((pair? datum) (cdr datum)) (else (error "Bad tagged datum: CONTENTS" datum)) ) ) (define (install-scheme-number-package) (define (tag x) x) (put '=zero? '(scheme-number) (lambda (x) (tag (= x 0)))) (put 'equ? '(scheme-number scheme-number) (lambda (x y) (tag (= x y)))) (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))) 'scheme-number-package-done) (install-scheme-number-package) (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 (equ? x y) (if (and (= (numer x) (numer y)) (= (denom x) (denom y))) true false ) ) (define (rational_zero? x) (= 0 (numer x)) ) (define (tag x) (attach-tag 'rational x)) (put '=zero? '(rational) rational_zero?) (put 'equ? '(rational rational) equ? ) (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)))) 'rational-package-done) (install-rational-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 'magnitude '(rectangular) magnitude) (put 'angle '(rectangular) angle) (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)))) 'rectangular-package-done) (install-rectangular-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)))) 'polar-package-done) (install-polar-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 (equ? z1 z2) (if (and (= (real-part z1) (real-part z2)) (= (imag-part z1) (imag-part z2))) true false ) ) (define (tag z) (attach-tag 'complex z)) (put '=zero? '(complex) (lambda (z1) (and (= (real-part z1) 0) (= (imag-part z1) 0)))) (put 'equ? '(complex complex) equ?) (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)))) 'complex-package-done) (install-complex-package) (define (install-zero?-package) (define (ordinary_zero? x) (= x 0) ) (define (complex_zero? x) (= x 0) ) (put 'zero '(scheme-number) ordinary_zero?) (put 'zero '(complex) complex_zero?) ) (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 (add . args) (apply apply-generic (cons 'add args))) (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 (equ? x y) (apply-generic 'equ? x y)) (define (make-scheme-number n) ((get 'make 'scheme-number) n)) (define (make-rational n d) ((get 'make 'rational) n d)) (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)) (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 (=zero? x) (apply-generic '=zero? x)) (define (equ? x y) (apply-generic 'equ? x y)) (define a (make-complex-from-real-imag 0 0)) (define b (make-complex-from-real-imag 1 0)) (define c (make-rational 0 3)) (define d (make-rational 1 3)) (display (=zero? a))(newline) (display (=zero? b))(newline) (display (=zero? 0))(newline) (display (=zero? 1))(newline) (display (=zero? c))(newline) (display (=zero? d))(newline) Welcome to , version 6.7 [ 3 m ] .
b95eb6696b4686198f29f3d0151aa117b6b46246f000718b7ac9dbd87177bf3d
haskell/text-icu
Types.hs
-- | Module : Data . Text . Copyright : ( c ) 2010 -- -- License : BSD-style -- Maintainer : -- Stability : experimental Portability : GHC -- Types for use when manipulating Unicode text , using the bindings to the International Components for Unicode ( ICU ) libraries . module Data.Text.ICU.Types ( -- * Widely used types LocaleName(..) , ParseError(errError, errLine, errOffset) ) where import Data.Text.ICU.Error.Internal (ParseError(..)) import Data.Text.ICU.Internal (LocaleName(..))
null
https://raw.githubusercontent.com/haskell/text-icu/5ab84d8106c06fbabb87a0f173faa6049775a148/Data/Text/ICU/Types.hs
haskell
| License : BSD-style Maintainer : Stability : experimental * Widely used types
Module : Data . Text . Copyright : ( c ) 2010 Portability : GHC Types for use when manipulating Unicode text , using the bindings to the International Components for Unicode ( ICU ) libraries . module Data.Text.ICU.Types ( LocaleName(..) , ParseError(errError, errLine, errOffset) ) where import Data.Text.ICU.Error.Internal (ParseError(..)) import Data.Text.ICU.Internal (LocaleName(..))
69999e5839275eda8802f0500251920be9d6be4fea0078cc5b42b6b6124388ad
tonyg/kali-scheme
ilength.scm
Copyright ( c ) 1993 , 1994 by and . Copyright ( c ) 1996 by NEC Research Institute , Inc. See file COPYING . Integer - length , a la Common Lisp , written in portable Scheme . (define-syntax cons-stream (syntax-rules () ((cons-stream head tail) (cons head (delay tail))))) (define head car) (define (tail s) (force (cdr s))) (define integer-length (let () (define useful (let loop ((p 256) (n 4)) (cons-stream (cons p n) (loop (* p p) (* n 2))))) (define (recur n) (if (< n 16) (vector-ref '#(0 1 2 2 3 3 3 3 4 4 4 4 4 4 4 4) n) (let loop ((s useful) (prev 16)) (let ((z (head s))) (if (< n (car z)) (+ (cdr z) (recur (quotient n prev))) (loop (tail s) (car z))))))) (define (integer-length n) (if (exact? n) (if (< n 0) (recur (- -1 n)) (recur n)) (integer-length (inexact->exact n)))) integer-length))
null
https://raw.githubusercontent.com/tonyg/kali-scheme/79bf76b4964729b63fce99c4d2149b32cb067ac0/scheme/misc/ilength.scm
scheme
Copyright ( c ) 1993 , 1994 by and . Copyright ( c ) 1996 by NEC Research Institute , Inc. See file COPYING . Integer - length , a la Common Lisp , written in portable Scheme . (define-syntax cons-stream (syntax-rules () ((cons-stream head tail) (cons head (delay tail))))) (define head car) (define (tail s) (force (cdr s))) (define integer-length (let () (define useful (let loop ((p 256) (n 4)) (cons-stream (cons p n) (loop (* p p) (* n 2))))) (define (recur n) (if (< n 16) (vector-ref '#(0 1 2 2 3 3 3 3 4 4 4 4 4 4 4 4) n) (let loop ((s useful) (prev 16)) (let ((z (head s))) (if (< n (car z)) (+ (cdr z) (recur (quotient n prev))) (loop (tail s) (car z))))))) (define (integer-length n) (if (exact? n) (if (< n 0) (recur (- -1 n)) (recur n)) (integer-length (inexact->exact n)))) integer-length))
91fea0f8f594ce84393420a7751975f39f1546b8e62794cd78d562155c4fffe6
yi-editor/yi-rope
Rope.hs
{-# language CPP #-} # language BangPatterns # {-# language DeriveDataTypeable #-} # language LambdaCase # # language MultiParamTypeClasses # {-# language OverloadedStrings #-} {-# language ScopedTypeVariables #-} # language ViewPatterns # {-# options_haddock show-extensions #-} -- | -- Module : Yi.Rope -- License : GPL-2 -- Maintainer : -- Stability : experimental -- Portability : portable -- This module defines a @rope@ data structure for use in . This -- specific implementation uses a fingertree over Text. -- -- In contrast to our old implementation, we can now reap all the -- benefits of Text: automatic unicode handling and blazing fast -- implementation on underlying strings. This frees us from a lot of book - keeping . We do n't lose out on not using ByteString directly -- because the old implementation encoded it into UTF8 anyway, making -- it unsuitable for storing anything but text. module Yi.Rope ( Yi.Rope.YiString, * Conversions to Yi.Rope.fromString, Yi.Rope.fromText, Yi.Rope.fromString', Yi.Rope.fromText', * Conversions from Yi.Rope.toString, Yi.Rope.toReverseString, Yi.Rope.toText, Yi.Rope.toReverseText, -- * Functions over content Yi.Rope.null, Yi.Rope.empty, Yi.Rope.take, Yi.Rope.drop, Yi.Rope.length, Yi.Rope.reverse, Yi.Rope.countNewLines, Yi.Rope.lines, Yi.Rope.lines', Yi.Rope.unlines, Yi.Rope.splitAt, Yi.Rope.splitAtLine, Yi.Rope.cons, Yi.Rope.snoc, Yi.Rope.singleton, Yi.Rope.head, Yi.Rope.last, Yi.Rope.append, Yi.Rope.concat, Yi.Rope.any, Yi.Rope.all, Yi.Rope.dropWhile, Yi.Rope.takeWhile, Yi.Rope.dropWhileEnd, Yi.Rope.takeWhileEnd, Yi.Rope.intercalate, Yi.Rope.intersperse, Yi.Rope.filter, Yi.Rope.map, Yi.Rope.words, Yi.Rope.unwords, Yi.Rope.split, Yi.Rope.init, Yi.Rope.tail, Yi.Rope.span, Yi.Rope.break, Yi.Rope.foldl', Yi.Rope.replicate, Yi.Rope.replicateChar, -- * IO Yi.Rope.readFile, Yi.Rope.writeFile, -- * Escape latches to underlying content. Note that these are safe -- to use but it does not mean they should. Yi.Rope.fromRope, Yi.Rope.withText, Yi.Rope.unsafeWithText ) where import Control.DeepSeq import Control.Exception (try) import Data.Binary import qualified Data.ByteString.Lazy as BSL import Data.Char (isSpace) import qualified Data.FingerTree as T import Data.FingerTree hiding (null, empty, reverse, split) import qualified Data.List as L (foldl') import Data.Maybe import Data.Monoid import Data.String (IsString(..)) import qualified Data.Text as TX import qualified Data.Text.Encoding.Error as TXEE import qualified Data.Text.Lazy as TXL import qualified Data.Text.Lazy.Encoding as TXLE import qualified Data.Text.IO as TXIO (writeFile) import Data.Typeable import Prelude hiding (drop) -- | Used to cache the size of the strings. data Size = Indices { charIndex :: {-# UNPACK #-} !Int -- ^ How many characters under here? , lineIndex :: Int -- ^ How many lines under here? } deriving (Eq, Show, Typeable) -- | A chunk storing the string of the type it is indexed by. It -- caches the length of stored string. data YiChunk = Chunk { chunkSize :: {-# UNPACK #-} !Int , _fromChunk :: {-# UNPACK #-} !TX.Text } deriving (Show, Eq, Typeable) -- | Makes a chunk from a given string. We allow for an arbitrary -- length function here to allow us to bypass the calculation with -- 'const' in case the length is known ahead of time. In most cases, -- the use of this is -- > mkChunk ' ' someText mkChunk :: (TX.Text -> Int) -- ^ The length function to use. -> TX.Text -> YiChunk mkChunk l t = Chunk (l t) t -- | Transform the chunk content. It's vital that the transformation -- preserves the length of the content. overChunk :: (TX.Text -> TX.Text) -- ^ Length-preserving content transformation. -> YiChunk -> YiChunk overChunk f (Chunk l t) = Chunk l (f t) -- | Counts number of newlines in the given 'TX.Text'. countNl :: TX.Text -> Int countNl = TX.count "\n" #if __GLASGOW_HASKELL__ >= 804 instance Semigroup Size where (<>) = mappend #endif instance Monoid Size where mempty = Indices 0 0 Indices c l `mappend` Indices c' l' = Indices (c + c') (l + l') instance Measured Size YiChunk where measure (Chunk l t) = Indices l (countNl t) | A ' ' is a ' FingerTree ' with cached char and line counts -- over chunks of 'TX.Text'. newtype YiString = YiString { fromRope :: FingerTree Size YiChunk } deriving (Show, Typeable) | Two ' 's are equal if their underlying text is . -- -- Implementation note: This just uses 'TX.Text' equality as there is -- no real opportunity for optimisation here except for a cached length check first . We could unroll the trees and mess around with -- matching prefixes but the overhead would be higher than a simple conversion and relying on GHC optimisation . -- The derived Eq implementation for the underlying tree only passes -- the equality check if the chunks are the same too which is not what -- we want. instance Eq YiString where t == t' = Yi.Rope.length t == Yi.Rope.length t' && toText t == toText t' instance NFData Size where rnf (Indices !c !l) = c `seq` l `seq` () instance NFData YiChunk where rnf (Chunk !i !t) = i `seq` rnf t instance NFData YiString where rnf = rnf . toText instance IsString YiString where fromString = Yi.Rope.fromString #if __GLASGOW_HASKELL__ >= 804 instance Semigroup YiString where (<>) = mappend #endif instance Monoid YiString where mempty = Yi.Rope.empty mappend = Yi.Rope.append mconcat = Yi.Rope.concat instance Ord YiString where compare x y = toText x `compare` toText y (-|) :: YiChunk -> FingerTree Size YiChunk -> FingerTree Size YiChunk b -| t | chunkSize b == 0 = t | otherwise = b <| t (|-) :: FingerTree Size YiChunk -> YiChunk -> FingerTree Size YiChunk t |- b | chunkSize b == 0 = t | otherwise = t |> b -- | Default size chunk to use. Currently @1200@ as this is what -- benchmarks suggest. -- -- This makes the biggest difference with 'lines'-like and -- 'concat'-like functions. Bigger chunks make 'concat' (much) faster -- but 'lines' slower. In general it seems that we benefit more from larger chunks and 1200 seems to be the sweet spot . defaultChunkSize :: Int defaultChunkSize = 1200 -- | Reverse the whole underlying string. -- -- This involves reversing the order of the chunks as well as content -- of the chunks. We use a little optimisation here that re-uses the -- content of each chunk but this exposes a potential problem: after -- many transformations, our chunks size might become quite varied -- (but never more than the default size), perhaps we should -- periodically rechunk the tree to recover nice sizes? reverse :: YiString -> YiString reverse = YiString . fmap' (overChunk TX.reverse) . T.reverse . fromRope -- | See 'fromText'. fromString :: String -> YiString fromString = fromText . TX.pack -- | See 'fromText''. fromString' :: Int -> String -> YiString fromString' n = fromText' n . TX.pack -- | See 'toText'. toString :: YiString -> String toString = TX.unpack . toText -- | See 'toReverseText'. -- Note that it is actually ~4.5 times faster to use ' toReverseText ' -- and unpack the result than to convert to 'String' and use -- 'Prelude.reverse'. toReverseString :: YiString -> String toReverseString = TX.unpack . toReverseText -- | This is like 'fromText' but it allows the user to specify the -- chunk size to be used. Uses 'defaultChunkSize' if the given -- size is <= 0. fromText' :: Int -> TX.Text -> YiString fromText' n | n <= 0 = fromText' defaultChunkSize | otherwise = YiString . r T.empty . f where f = TX.chunksOf n -- Convert the given string into chunks in the tree. We have a -- special case for a single element case: because we split on -- predetermined chunk size, we know that all chunks but the last -- one will be the specified size so we can optimise here instead -- of having to recompute chunk size at creation. r :: FingerTree Size YiChunk -> [TX.Text] -> FingerTree Size YiChunk r !tr [] = tr r !tr (t:[]) = tr |- mkChunk TX.length t r !tr (t:ts) = let r' = tr |- mkChunk (const n) t in r r' ts | Converts a ' TX.Text ' into a ' ' using -- 'defaultChunkSize'-sized chunks for the underlying tree. fromText :: TX.Text -> YiString fromText = fromText' defaultChunkSize fromLazyText :: TXL.Text -> YiString fromLazyText = YiString . T.fromList . fmap (mkChunk TX.length) . TXL.toChunks -- | Consider whether you really need to use this! toText :: YiString -> TX.Text toText = TX.concat . go . fromRope where go :: FingerTree Size YiChunk -> [TX.Text] go t = case viewl t of Chunk _ !c :< cs -> c : go cs EmptyL -> [] -- | Spits out the underlying string, reversed. -- -- Note that this is actually slightly faster than manually unrolling -- the tree from the end, 'TX.reverse'ing each chunk and -- 'TX.concat'ing, at least with -O2 which you really need to be using -- with 'TX.Text' anyway. toReverseText :: YiString -> TX.Text toReverseText = TX.reverse . toText | Checks if the given ' ' is actually empty . null :: YiString -> Bool null = T.null . fromRope | Creates an empty ' ' . empty :: YiString empty = YiString T.empty -- | Length of the whole underlying string. -- Amortized constant time . length :: YiString -> Int length = charIndex . measure . fromRope -- | Count the number of newlines in the underlying string. This is -- actually amortized constant time as we cache this information in -- the underlying tree. countNewLines :: YiString -> Int countNewLines = lineIndex . measure . fromRope | Append two ' 's . -- -- We take the extra time to optimise this append for many small -- insertions. With naive append of the inner fingertree with 'T.><', -- it is often the case that we end up with a large collection of tiny -- chunks. This function instead tries to join the underlying trees at -- outermost chunks up to 'defaultChunkSize' which while slower, -- should improve memory usage. -- -- I suspect that this pays for itself as we'd spend more time -- computing over all the little chunks than few large ones anyway. append :: YiString -> YiString -> YiString append (YiString t) (YiString t') = case (viewr t, viewl t') of (EmptyR, _) -> YiString t' (_, EmptyL) -> YiString t (ts :> Chunk l x, Chunk l' x' :< ts') -> let len = l + l' in case compare len defaultChunkSize of GT -> YiString (t <> t') _ -> YiString (ts |- Chunk len (x <> x') <> ts') | Concat a list of ' 's . concat :: [YiString] -> YiString concat = L.foldl' append empty | Take the first character of the underlying string if possible . head :: YiString -> Maybe Char head (YiString t) = case viewl t of EmptyL -> Nothing Chunk _ x :< _ -> if TX.null x then Nothing else Just (TX.head x) -- | Take the last character of the underlying string if possible. last :: YiString -> Maybe Char last (YiString t) = case viewr t of EmptyR -> Nothing _ :> Chunk _ x -> if TX.null x then Nothing else Just (TX.last x) -- | Takes every character but the last one: returns Nothing on empty -- string. init :: YiString -> Maybe YiString init (YiString t) = case viewr t of EmptyR -> Nothing ts :> Chunk 0 _ -> Yi.Rope.init (YiString ts) ts :> Chunk l x -> Just . YiString $ ts |- Chunk (l - 1) (TX.init x) -- | Takes the tail of the underlying string. If the string is empty -- to begin with, returns Nothing. tail :: YiString -> Maybe YiString tail (YiString t) = case viewl t of EmptyL -> Nothing Chunk 0 _ :< ts -> Yi.Rope.tail (YiString ts) Chunk l x :< ts -> Just . YiString $ Chunk (l - 1) (TX.tail x) -| ts -- | Splits the string at given character position. -- -- If @position <= 0@ then the left string is empty and the right string -- contains everything else. -- -- If @position >= length of the string@ then the left string contains -- everything and the right string is empty. -- -- Implementation note: the way this works is by splitting the -- underlying finger at a closest chunk that goes *over* the given -- position (see 'T.split'). This either results in a perfect split at -- which point we're done or more commonly, it leaves as few characters short and we need to take few characters from the first -- chunk of the right side of the split. We do precisely that. -- -- All together, this split is only as expensive as underlying ' T.split ' , the cost of splitting a chunk into two , the cost of one cons and one cons of a chunk and lastly the cost of ' T.splitAt ' of -- the underlying 'TX.Text'. It turns out to be fairly fast all -- together. splitAt :: Int -> YiString -> (YiString, YiString) splitAt n (YiString t) | n <= 0 = (mempty, YiString t) | otherwise = case viewl s of Chunk l x :< ts | n' /= 0 -> let (lx, rx) = TX.splitAt n' x in (YiString $ f |> Chunk n' lx, YiString $ Chunk (l - n') rx -| ts) _ -> (YiString f, YiString s) where (f, s) = T.split ((> n) . charIndex) t n' = n - charIndex (measure f) | Takes the first n given characters . take :: Int -> YiString -> YiString take 1 = maybe mempty Yi.Rope.singleton . Yi.Rope.head take n = fst . Yi.Rope.splitAt n | Drops the first n characters . drop :: Int -> YiString -> YiString drop 1 = fromMaybe mempty . Yi.Rope.tail drop n = snd . Yi.Rope.splitAt n | The usual ' Prelude.dropWhile ' optimised for ' 's . dropWhile :: (Char -> Bool) -> YiString -> YiString dropWhile p = YiString . go . fromRope where go t = case viewl t of EmptyL -> T.empty Chunk 0 _ :< ts -> go ts Chunk l x :< ts -> let r = TX.dropWhile p x l' = TX.length r in case compare l' l of -- We dropped nothing so we must be done. EQ -> t -- We dropped something, if it was everything then drop from -- next chunk. LT | TX.null r -> go ts -- It wasn't everything and we have left-overs, we must be done. | otherwise -> Chunk l' r <| ts -- We shouldn't really get here or it would mean that -- dropping stuff resulted in more content than we had. This -- can only happen if unsafe functions don't preserve the -- chunk size and it goes out of sync with the text length. -- Preserve this abomination, it may be useful for -- debugging. _ -> Chunk l' r -| ts -- | As 'Yi.Rope.dropWhile' but drops from the end instead. dropWhileEnd :: (Char -> Bool) -> YiString -> YiString dropWhileEnd p = YiString . go . fromRope where go t = case viewr t of EmptyR -> T.empty ts :> Chunk 0 _ -> go ts ts :> Chunk l x -> let r = TX.dropWhileEnd p x l' = TX.length r in case compare l' l of EQ -> t LT | TX.null r -> go ts | otherwise -> ts |> Chunk l' r _ -> ts |- Chunk l' r | The usual ' Prelude.takeWhile ' optimised for ' 's . takeWhile :: (Char -> Bool) -> YiString -> YiString takeWhile p = YiString . go . fromRope where go t = case viewl t of EmptyL -> T.empty Chunk 0 _ :< ts -> go ts Chunk l x :< ts -> let r = TX.takeWhile p x l' = TX.length r in case compare l' l of -- We took the whole chunk, keep taking more. EQ -> Chunk l x -| go ts -- We took some stuff but not everything so we're done. -- Alternatively, we took more than the size chunk so -- preserve this wonder. This should only ever happen if you use unsafe functions and Chunk size goes out of sync with -- actual text length. _ -> T.singleton $ Chunk l' r | Like ' Yi . Rope.takeWhile ' but takes from the end instead . takeWhileEnd :: (Char -> Bool) -> YiString -> YiString takeWhileEnd p = YiString . go . fromRope where go t = case viewr t of EmptyR -> T.empty ts :> Chunk 0 _ -> go ts ts :> Chunk l x -> case compare l' l of EQ -> go ts |> Chunk l x _ -> T.singleton $ Chunk l' r where -- no TX.takeWhileEnd – r = TX.reverse . TX.takeWhile p . TX.reverse $ x l' = TX.length r | Returns a pair whose first element is the longest prefix ( possibly empty ) of t of elements that satisfy p , and whose second is the remainder of the string . See also ' TX.span ' . -- This implementation uses . Rope.splitAt ' which actually is just as fast as hand - unrolling the tree . GHC sure is great ! span :: (Char -> Bool) -> YiString -> (YiString, YiString) span p y = let x = Yi.Rope.takeWhile p y in case Yi.Rope.splitAt (Yi.Rope.length x) y of -- Re-using ‘x’ seems to gain us a minor performance -- boost. (_, y') -> (x, y') -- | Just like 'Yi.Rope.span' but with the predicate negated. break :: (Char -> Bool) -> YiString -> (YiString, YiString) break p = Yi.Rope.span (not . p) | Concatenates the list of ' 's after inserting the user - provided ' ' between the elements . -- Empty ' 's are not ignored and will end up as strings of length 1 . If you do n't want this , it 's up to you to pre - process the -- list. Just as with 'Yi.Rope.intersperse', it is up to the user to -- pre-process the list. intercalate :: YiString -> [YiString] -> YiString intercalate _ [] = mempty intercalate (YiString t') (YiString s:ss) = YiString $ go s ss where go !acc [] = acc go acc (YiString t : ts') = go (acc >< t' >< t) ts' | Intersperses the given character between the ' 's . This is -- useful when you have a bunch of strings you just want to separate -- something with, comma or a dash. Note that it only inserts the -- character between the elements. -- What 's more , the result is a single ' ' . You can easily -- achieve a version that blindly inserts elements to the back by -- mapping over the list instead of using this function. -- -- You can think of it as a specialised version of ' Yi.Rope.intercalate ' . Note that what this does _ _ not _ _ do is -- intersperse characters into the underlying text, you should convert -- and use 'TX.intersperse' for that instead. intersperse :: Char -> [YiString] -> YiString intersperse _ [] = mempty intersperse c (t:ts) = go t ts where go !acc [] = acc go acc (t':ts') = go (acc <> (c `cons` t')) ts' | Add a ' ' in front of a ' ' . cons :: Char -> YiString -> YiString cons c (YiString t) = case viewl t of EmptyL -> Yi.Rope.singleton c Chunk l x :< ts | l < defaultChunkSize -> YiString $ Chunk (l + 1) (c `TX.cons` x) <| ts _ -> YiString $ Chunk 1 (TX.singleton c) <| t | Add a ' ' in the back of a ' ' . snoc :: YiString -> Char -> YiString snoc (YiString t) c = case viewr t of EmptyR -> Yi.Rope.singleton c ts :> Chunk l x | l < defaultChunkSize -> YiString $ ts |> Chunk (l + 1) (x `TX.snoc` c) _ -> YiString $ t |> Chunk 1 (TX.singleton c) | Single character ' ' . Consider whether it 's worth creating -- this, maybe you can use 'cons' or 'snoc' instead? singleton :: Char -> YiString singleton c = YiString . T.singleton $ Chunk 1 (TX.singleton c) -- | Splits the underlying string before the given line number. Zero - indexed lines . -- -- Splitting at line <= 0 gives you an empty string. Splitting at @n > 0@ gives you the first n lines . -- -- Also see 'splitAtLine''. splitAtLine :: Int -> YiString -> (YiString, YiString) splitAtLine n r | n <= 0 = (empty, r) | otherwise = splitAtLine' (n - 1) r -- | Splits the underlying string after the given line number. Zero - indexed lines . -- Splitting at line < = 0 gives you the first line . Splitting at @n > 0@ gives you the first n + 1 lines . -- -- The implementation is similar to that of 'splitAt' except we are -- now looking for extra newlines in the next chunk rather than extra -- characters. splitAtLine' :: Int -> YiString -> (YiString, YiString) splitAtLine' p (YiString tr) = case viewl s of ch@(Chunk _ x) :< r -> let excess = lineIndex (measure f) + lineIndex (measure ch) - p - 1 (lx, rx) = cutExcess excess x in (YiString $ f |- mkChunk TX.length lx, YiString $ mkChunk TX.length rx -| r) _ -> (YiString f, YiString s) where (f, s) = T.split ((p <) . lineIndex) tr cutExcess :: Int -> TX.Text -> (TX.Text, TX.Text) cutExcess n t = case TX.length t of 0 -> (TX.empty, TX.empty) _ -> let ns = countNl t ls = TX.lines t front = TX.unlines $ Prelude.take (ns - n) ls back = TX.drop (TX.length front) t in if n >= ns then (t, TX.empty) else (front, back) -- | This is like 'lines'' but it does *not* preserve newlines. -- -- Specifically, we just strip the newlines from the result of -- 'lines''. -- -- This behaves slightly differently than the old split: the number of -- resulting strings here is equal to the number of newline characters -- in the underlying string. This is much more consistent than the old behaviour which blindly used @ByteString@s split and stitched the -- result back together which was inconsistent with the rest of the -- interface which worked with number of newlines. lines :: YiString -> [YiString] lines = Prelude.map dropNl . lines' where dropNl (YiString t) = case viewr t of EmptyR -> Yi.Rope.empty ts :> ch@(Chunk l tx) -> YiString $ ts |- if TX.null tx then ch else case TX.last tx of '\n' -> Chunk (l - 1) (TX.init tx) _ -> ch | Splits the ' ' into a list of ' ' each containing a -- line. -- -- Note that in old implementation this allowed an arbitrary character -- to split on. If you want to do that, manually convert 'toText' and -- use 'TX.splitOn' to suit your needs. This case is optimised for -- newlines only which seems to have been the only use of the original -- function. -- -- The newlines are preserved so this should hold: -- -- > 'toText' . 'concat' . 'lines'' ≡ 'toText' -- -- but the underlying structure might change: notably, chunks will -- most likely change sizes. lines' :: YiString -> [YiString] lines' t = let (YiString f, YiString s) = splitAtLine' 0 t in if T.null s then if T.null f then [] else [YiString f] else YiString f : lines' (YiString s) -- | Joins up lines by a newline character. It does not leave a -- newline after the last line. If you want a more classical -- 'Prelude.unlines' behaviour, use 'Yi.Rope.map' along with -- 'Yi.Rope.snoc'. unlines :: [YiString] -> YiString unlines = Yi.Rope.intersperse '\n' | ' ' specialised @any@. -- -- Implementation note: this currently just does any by doing ‘TX.Text’ -- conversions upon consecutive chunks. We should be able to speed it -- up by running it in parallel over multiple chunks. any :: (Char -> Bool) -> YiString -> Bool any p = go . fromRope where go x = case viewl x of EmptyL -> False Chunk _ t :< ts -> TX.any p t || go ts | ' ' specialised @all@. -- -- See the implementation note for 'Yi.Rope.any'. all :: (Char -> Bool) -> YiString -> Bool all p = go . fromRope where go x = case viewl x of EmptyL -> True Chunk _ t :< ts -> TX.all p t && go ts | To serialise a ' ' , we turn it into a regular ' String ' -- first. instance Binary YiString where put = put . toString get = Yi.Rope.fromString <$> get | Write a ' ' into the given file . -- -- It's up to the user to handle exceptions. writeFile :: FilePath -> YiString -> IO () writeFile f = TXIO.writeFile f . toText -- | Reads file into the rope, also returning the 'ConverterName' that -- was used for decoding. You should resupply this to 'writeFile' if -- you're aiming to preserve the original encoding. -- -- If we fail to guess the encoding used, error message is given -- instead. -- -- It is up to the user to handle exceptions not directly related to -- character decoding. readFile :: FilePath -> IO (Either TX.Text YiString) readFile fp = BSL.readFile fp >>= go decoders where go [] _ = pure (Left err) go (d : ds) bytes = try (pure (d bytes)) >>= \case Left (_ :: TXEE.UnicodeException) -> go ds bytes Right text -> pure (Right (fromLazyText text)) err = "Could not guess the encoding of " <> TX.pack fp decoders = [ TXLE.decodeUtf8 , TXLE.decodeUtf16LE , TXLE.decodeUtf16BE , TXLE.decodeUtf32LE , TXLE.decodeUtf32BE ] -- | Filters the characters from the underlying string. -- -- >>> filter (/= 'a') "bac" -- "bc" filter :: (Char -> Bool) -> YiString -> YiString filter p = YiString . go . fromRope where go t = case viewl t of EmptyL -> T.empty Chunk _ x :< ts -> mkChunk TX.length (TX.filter p x) -| go ts -- | Maps the characters over the underlying string. map :: (Char -> Char) -> YiString -> YiString map f = YiString . go . fromRope where go t = case viewl t of EmptyL -> T.empty Chunk l x :< ts -> Chunk l (TX.map f x) <| go ts | Join given ' 's with a space . Empty lines will be filtered out first . unwords :: [YiString] -> YiString unwords = Yi.Rope.intersperse ' ' | Splits the given ' ' into a list of words , where spaces -- are determined by 'isSpace'. No empty strings are in the result -- list. words :: YiString -> [YiString] words = Prelude.filter (not . Yi.Rope.null) . Yi.Rope.split isSpace | Splits the ' ' on characters matching the predicate , like ' ' . -- -- For splitting on newlines use 'Yi.Rope.lines' or 'Yi.Rope.lines'' -- instead. -- Implementation note : GHC actually makes this naive implementation -- about as fast and in cases with lots of splits, faster, as a -- hand-rolled version on chunks with appends which is quite amazing -- in itself. split :: (Char -> Bool) -> YiString -> [YiString] split p = fmap fromText . TX.split p . toText -- | Left fold. -- Benchmarks show that folding is actually Pretty Damn Slow ™ : consider -- whether folding is really the best thing to use in your scenario. foldl' :: (a -> Char -> a) -> a -> YiString -> a foldl' f a = go a . fromRope where go acc t = case viewl t of EmptyL -> acc Chunk _ x :< ts -> let r = TX.foldl' f acc x in r `seq` go r ts | Replicate the given set number of times , concatenating -- the results. Also see 'Yi.Rope.replicateChar'. replicate :: Int -> YiString -> YiString replicate n t | n <= 0 = mempty | otherwise = t <> Yi.Rope.replicate (n - 1) t -- | Replicate the given character set number of times and pack the result into a ' ' . -- -- >>> replicateChar 4 ' ' -- " " replicateChar :: Int -> Char -> YiString replicateChar n = fromText . TX.replicate n . TX.singleton -- | Helper function doing conversions of to and from underlying -- 'TX.Text'. You should aim to implement everything in terms of ' ' instead . -- -- Please note that this maps over each __chunk__ so this can only be -- used with layout-agnostic functions. For example -- > > > let t = ' fromString ' " abc " < > ' fromString ' " def " > > > ' toString ' $ ' withText ' ' ' t -- "cbafed" -- -- Probably doesn't do what you wanted, but 'TX.toUpper' would. -- Specifically, for any @f : 'TX.Text' → 'TX.Text'@, 'withText' will -- only do the ‘expected’ thing iff -- -- @f x <> f y ≡ f (x <> y)@ -- -- which should look very familiar. withText :: (TX.Text -> TX.Text) -> YiString -> YiString withText f = YiString . T.fmap' (mkChunk TX.length . f . _fromChunk) . fromRope -- | Maps over each __chunk__ which means this function is UNSAFE! If you use this with functions which do n't preserve ' ' , that is -- the chunk length and number of newlines, things will break really, -- really badly. You should not need to use this. -- Also see ' T.unsafeFmap ' unsafeWithText :: (TX.Text -> TX.Text) -> YiString -> YiString unsafeWithText f = YiString . T.unsafeFmap g . fromRope where g (Chunk l t) = Chunk l (f t)
null
https://raw.githubusercontent.com/yi-editor/yi-rope/f3b925e2f4c55092957cecc3c037f36baff582bb/src/Yi/Rope.hs
haskell
# language CPP # # language DeriveDataTypeable # # language OverloadedStrings # # language ScopedTypeVariables # # options_haddock show-extensions # | Module : Yi.Rope License : GPL-2 Maintainer : Stability : experimental Portability : portable specific implementation uses a fingertree over Text. In contrast to our old implementation, we can now reap all the benefits of Text: automatic unicode handling and blazing fast implementation on underlying strings. This frees us from a lot of because the old implementation encoded it into UTF8 anyway, making it unsuitable for storing anything but text. * Functions over content * IO * Escape latches to underlying content. Note that these are safe to use but it does not mean they should. | Used to cache the size of the strings. # UNPACK # ^ How many characters under here? ^ How many lines under here? | A chunk storing the string of the type it is indexed by. It caches the length of stored string. # UNPACK # # UNPACK # | Makes a chunk from a given string. We allow for an arbitrary length function here to allow us to bypass the calculation with 'const' in case the length is known ahead of time. In most cases, the use of this is ^ The length function to use. | Transform the chunk content. It's vital that the transformation preserves the length of the content. ^ Length-preserving content transformation. | Counts number of newlines in the given 'TX.Text'. over chunks of 'TX.Text'. Implementation note: This just uses 'TX.Text' equality as there is no real opportunity for optimisation here except for a cached matching prefixes but the overhead would be higher than a simple the equality check if the chunks are the same too which is not what we want. | Default size chunk to use. Currently @1200@ as this is what benchmarks suggest. This makes the biggest difference with 'lines'-like and 'concat'-like functions. Bigger chunks make 'concat' (much) faster but 'lines' slower. In general it seems that we benefit more from | Reverse the whole underlying string. This involves reversing the order of the chunks as well as content of the chunks. We use a little optimisation here that re-uses the content of each chunk but this exposes a potential problem: after many transformations, our chunks size might become quite varied (but never more than the default size), perhaps we should periodically rechunk the tree to recover nice sizes? | See 'fromText'. | See 'fromText''. | See 'toText'. | See 'toReverseText'. and unpack the result than to convert to 'String' and use 'Prelude.reverse'. | This is like 'fromText' but it allows the user to specify the chunk size to be used. Uses 'defaultChunkSize' if the given size is <= 0. Convert the given string into chunks in the tree. We have a special case for a single element case: because we split on predetermined chunk size, we know that all chunks but the last one will be the specified size so we can optimise here instead of having to recompute chunk size at creation. 'defaultChunkSize'-sized chunks for the underlying tree. | Consider whether you really need to use this! | Spits out the underlying string, reversed. Note that this is actually slightly faster than manually unrolling the tree from the end, 'TX.reverse'ing each chunk and 'TX.concat'ing, at least with -O2 which you really need to be using with 'TX.Text' anyway. | Length of the whole underlying string. | Count the number of newlines in the underlying string. This is actually amortized constant time as we cache this information in the underlying tree. We take the extra time to optimise this append for many small insertions. With naive append of the inner fingertree with 'T.><', it is often the case that we end up with a large collection of tiny chunks. This function instead tries to join the underlying trees at outermost chunks up to 'defaultChunkSize' which while slower, should improve memory usage. I suspect that this pays for itself as we'd spend more time computing over all the little chunks than few large ones anyway. | Take the last character of the underlying string if possible. | Takes every character but the last one: returns Nothing on empty string. | Takes the tail of the underlying string. If the string is empty to begin with, returns Nothing. | Splits the string at given character position. If @position <= 0@ then the left string is empty and the right string contains everything else. If @position >= length of the string@ then the left string contains everything and the right string is empty. Implementation note: the way this works is by splitting the underlying finger at a closest chunk that goes *over* the given position (see 'T.split'). This either results in a perfect split at which point we're done or more commonly, it leaves as few chunk of the right side of the split. We do precisely that. All together, this split is only as expensive as underlying the underlying 'TX.Text'. It turns out to be fairly fast all together. We dropped nothing so we must be done. We dropped something, if it was everything then drop from next chunk. It wasn't everything and we have left-overs, we must be done. We shouldn't really get here or it would mean that dropping stuff resulted in more content than we had. This can only happen if unsafe functions don't preserve the chunk size and it goes out of sync with the text length. Preserve this abomination, it may be useful for debugging. | As 'Yi.Rope.dropWhile' but drops from the end instead. We took the whole chunk, keep taking more. We took some stuff but not everything so we're done. Alternatively, we took more than the size chunk so preserve this wonder. This should only ever happen if you actual text length. no TX.takeWhileEnd – Re-using ‘x’ seems to gain us a minor performance boost. | Just like 'Yi.Rope.span' but with the predicate negated. list. Just as with 'Yi.Rope.intersperse', it is up to the user to pre-process the list. useful when you have a bunch of strings you just want to separate something with, comma or a dash. Note that it only inserts the character between the elements. achieve a version that blindly inserts elements to the back by mapping over the list instead of using this function. You can think of it as a specialised version of intersperse characters into the underlying text, you should convert and use 'TX.intersperse' for that instead. this, maybe you can use 'cons' or 'snoc' instead? | Splits the underlying string before the given line number. Splitting at line <= 0 gives you an empty string. Splitting at Also see 'splitAtLine''. | Splits the underlying string after the given line number. The implementation is similar to that of 'splitAt' except we are now looking for extra newlines in the next chunk rather than extra characters. | This is like 'lines'' but it does *not* preserve newlines. Specifically, we just strip the newlines from the result of 'lines''. This behaves slightly differently than the old split: the number of resulting strings here is equal to the number of newline characters in the underlying string. This is much more consistent than the old result back together which was inconsistent with the rest of the interface which worked with number of newlines. line. Note that in old implementation this allowed an arbitrary character to split on. If you want to do that, manually convert 'toText' and use 'TX.splitOn' to suit your needs. This case is optimised for newlines only which seems to have been the only use of the original function. The newlines are preserved so this should hold: > 'toText' . 'concat' . 'lines'' ≡ 'toText' but the underlying structure might change: notably, chunks will most likely change sizes. | Joins up lines by a newline character. It does not leave a newline after the last line. If you want a more classical 'Prelude.unlines' behaviour, use 'Yi.Rope.map' along with 'Yi.Rope.snoc'. Implementation note: this currently just does any by doing ‘TX.Text’ conversions upon consecutive chunks. We should be able to speed it up by running it in parallel over multiple chunks. See the implementation note for 'Yi.Rope.any'. first. It's up to the user to handle exceptions. | Reads file into the rope, also returning the 'ConverterName' that was used for decoding. You should resupply this to 'writeFile' if you're aiming to preserve the original encoding. If we fail to guess the encoding used, error message is given instead. It is up to the user to handle exceptions not directly related to character decoding. | Filters the characters from the underlying string. >>> filter (/= 'a') "bac" "bc" | Maps the characters over the underlying string. are determined by 'isSpace'. No empty strings are in the result list. For splitting on newlines use 'Yi.Rope.lines' or 'Yi.Rope.lines'' instead. about as fast and in cases with lots of splits, faster, as a hand-rolled version on chunks with appends which is quite amazing in itself. | Left fold. whether folding is really the best thing to use in your scenario. the results. Also see 'Yi.Rope.replicateChar'. | Replicate the given character set number of times and pack the >>> replicateChar 4 ' ' " " | Helper function doing conversions of to and from underlying 'TX.Text'. You should aim to implement everything in terms of Please note that this maps over each __chunk__ so this can only be used with layout-agnostic functions. For example "cbafed" Probably doesn't do what you wanted, but 'TX.toUpper' would. Specifically, for any @f : 'TX.Text' → 'TX.Text'@, 'withText' will only do the ‘expected’ thing iff @f x <> f y ≡ f (x <> y)@ which should look very familiar. | Maps over each __chunk__ which means this function is UNSAFE! If the chunk length and number of newlines, things will break really, really badly. You should not need to use this.
# language BangPatterns # # language LambdaCase # # language MultiParamTypeClasses # # language ViewPatterns # This module defines a @rope@ data structure for use in . This book - keeping . We do n't lose out on not using ByteString directly module Yi.Rope ( Yi.Rope.YiString, * Conversions to Yi.Rope.fromString, Yi.Rope.fromText, Yi.Rope.fromString', Yi.Rope.fromText', * Conversions from Yi.Rope.toString, Yi.Rope.toReverseString, Yi.Rope.toText, Yi.Rope.toReverseText, Yi.Rope.null, Yi.Rope.empty, Yi.Rope.take, Yi.Rope.drop, Yi.Rope.length, Yi.Rope.reverse, Yi.Rope.countNewLines, Yi.Rope.lines, Yi.Rope.lines', Yi.Rope.unlines, Yi.Rope.splitAt, Yi.Rope.splitAtLine, Yi.Rope.cons, Yi.Rope.snoc, Yi.Rope.singleton, Yi.Rope.head, Yi.Rope.last, Yi.Rope.append, Yi.Rope.concat, Yi.Rope.any, Yi.Rope.all, Yi.Rope.dropWhile, Yi.Rope.takeWhile, Yi.Rope.dropWhileEnd, Yi.Rope.takeWhileEnd, Yi.Rope.intercalate, Yi.Rope.intersperse, Yi.Rope.filter, Yi.Rope.map, Yi.Rope.words, Yi.Rope.unwords, Yi.Rope.split, Yi.Rope.init, Yi.Rope.tail, Yi.Rope.span, Yi.Rope.break, Yi.Rope.foldl', Yi.Rope.replicate, Yi.Rope.replicateChar, Yi.Rope.readFile, Yi.Rope.writeFile, Yi.Rope.fromRope, Yi.Rope.withText, Yi.Rope.unsafeWithText ) where import Control.DeepSeq import Control.Exception (try) import Data.Binary import qualified Data.ByteString.Lazy as BSL import Data.Char (isSpace) import qualified Data.FingerTree as T import Data.FingerTree hiding (null, empty, reverse, split) import qualified Data.List as L (foldl') import Data.Maybe import Data.Monoid import Data.String (IsString(..)) import qualified Data.Text as TX import qualified Data.Text.Encoding.Error as TXEE import qualified Data.Text.Lazy as TXL import qualified Data.Text.Lazy.Encoding as TXLE import qualified Data.Text.IO as TXIO (writeFile) import Data.Typeable import Prelude hiding (drop) , lineIndex :: Int } deriving (Eq, Show, Typeable) } deriving (Show, Eq, Typeable) > mkChunk ' ' someText -> TX.Text -> YiChunk mkChunk l t = Chunk (l t) t -> YiChunk -> YiChunk overChunk f (Chunk l t) = Chunk l (f t) countNl :: TX.Text -> Int countNl = TX.count "\n" #if __GLASGOW_HASKELL__ >= 804 instance Semigroup Size where (<>) = mappend #endif instance Monoid Size where mempty = Indices 0 0 Indices c l `mappend` Indices c' l' = Indices (c + c') (l + l') instance Measured Size YiChunk where measure (Chunk l t) = Indices l (countNl t) | A ' ' is a ' FingerTree ' with cached char and line counts newtype YiString = YiString { fromRope :: FingerTree Size YiChunk } deriving (Show, Typeable) | Two ' 's are equal if their underlying text is . length check first . We could unroll the trees and mess around with conversion and relying on GHC optimisation . The derived Eq implementation for the underlying tree only passes instance Eq YiString where t == t' = Yi.Rope.length t == Yi.Rope.length t' && toText t == toText t' instance NFData Size where rnf (Indices !c !l) = c `seq` l `seq` () instance NFData YiChunk where rnf (Chunk !i !t) = i `seq` rnf t instance NFData YiString where rnf = rnf . toText instance IsString YiString where fromString = Yi.Rope.fromString #if __GLASGOW_HASKELL__ >= 804 instance Semigroup YiString where (<>) = mappend #endif instance Monoid YiString where mempty = Yi.Rope.empty mappend = Yi.Rope.append mconcat = Yi.Rope.concat instance Ord YiString where compare x y = toText x `compare` toText y (-|) :: YiChunk -> FingerTree Size YiChunk -> FingerTree Size YiChunk b -| t | chunkSize b == 0 = t | otherwise = b <| t (|-) :: FingerTree Size YiChunk -> YiChunk -> FingerTree Size YiChunk t |- b | chunkSize b == 0 = t | otherwise = t |> b larger chunks and 1200 seems to be the sweet spot . defaultChunkSize :: Int defaultChunkSize = 1200 reverse :: YiString -> YiString reverse = YiString . fmap' (overChunk TX.reverse) . T.reverse . fromRope fromString :: String -> YiString fromString = fromText . TX.pack fromString' :: Int -> String -> YiString fromString' n = fromText' n . TX.pack toString :: YiString -> String toString = TX.unpack . toText Note that it is actually ~4.5 times faster to use ' toReverseText ' toReverseString :: YiString -> String toReverseString = TX.unpack . toReverseText fromText' :: Int -> TX.Text -> YiString fromText' n | n <= 0 = fromText' defaultChunkSize | otherwise = YiString . r T.empty . f where f = TX.chunksOf n r :: FingerTree Size YiChunk -> [TX.Text] -> FingerTree Size YiChunk r !tr [] = tr r !tr (t:[]) = tr |- mkChunk TX.length t r !tr (t:ts) = let r' = tr |- mkChunk (const n) t in r r' ts | Converts a ' TX.Text ' into a ' ' using fromText :: TX.Text -> YiString fromText = fromText' defaultChunkSize fromLazyText :: TXL.Text -> YiString fromLazyText = YiString . T.fromList . fmap (mkChunk TX.length) . TXL.toChunks toText :: YiString -> TX.Text toText = TX.concat . go . fromRope where go :: FingerTree Size YiChunk -> [TX.Text] go t = case viewl t of Chunk _ !c :< cs -> c : go cs EmptyL -> [] toReverseText :: YiString -> TX.Text toReverseText = TX.reverse . toText | Checks if the given ' ' is actually empty . null :: YiString -> Bool null = T.null . fromRope | Creates an empty ' ' . empty :: YiString empty = YiString T.empty Amortized constant time . length :: YiString -> Int length = charIndex . measure . fromRope countNewLines :: YiString -> Int countNewLines = lineIndex . measure . fromRope | Append two ' 's . append :: YiString -> YiString -> YiString append (YiString t) (YiString t') = case (viewr t, viewl t') of (EmptyR, _) -> YiString t' (_, EmptyL) -> YiString t (ts :> Chunk l x, Chunk l' x' :< ts') -> let len = l + l' in case compare len defaultChunkSize of GT -> YiString (t <> t') _ -> YiString (ts |- Chunk len (x <> x') <> ts') | Concat a list of ' 's . concat :: [YiString] -> YiString concat = L.foldl' append empty | Take the first character of the underlying string if possible . head :: YiString -> Maybe Char head (YiString t) = case viewl t of EmptyL -> Nothing Chunk _ x :< _ -> if TX.null x then Nothing else Just (TX.head x) last :: YiString -> Maybe Char last (YiString t) = case viewr t of EmptyR -> Nothing _ :> Chunk _ x -> if TX.null x then Nothing else Just (TX.last x) init :: YiString -> Maybe YiString init (YiString t) = case viewr t of EmptyR -> Nothing ts :> Chunk 0 _ -> Yi.Rope.init (YiString ts) ts :> Chunk l x -> Just . YiString $ ts |- Chunk (l - 1) (TX.init x) tail :: YiString -> Maybe YiString tail (YiString t) = case viewl t of EmptyL -> Nothing Chunk 0 _ :< ts -> Yi.Rope.tail (YiString ts) Chunk l x :< ts -> Just . YiString $ Chunk (l - 1) (TX.tail x) -| ts characters short and we need to take few characters from the first ' T.split ' , the cost of splitting a chunk into two , the cost of one cons and one cons of a chunk and lastly the cost of ' T.splitAt ' of splitAt :: Int -> YiString -> (YiString, YiString) splitAt n (YiString t) | n <= 0 = (mempty, YiString t) | otherwise = case viewl s of Chunk l x :< ts | n' /= 0 -> let (lx, rx) = TX.splitAt n' x in (YiString $ f |> Chunk n' lx, YiString $ Chunk (l - n') rx -| ts) _ -> (YiString f, YiString s) where (f, s) = T.split ((> n) . charIndex) t n' = n - charIndex (measure f) | Takes the first n given characters . take :: Int -> YiString -> YiString take 1 = maybe mempty Yi.Rope.singleton . Yi.Rope.head take n = fst . Yi.Rope.splitAt n | Drops the first n characters . drop :: Int -> YiString -> YiString drop 1 = fromMaybe mempty . Yi.Rope.tail drop n = snd . Yi.Rope.splitAt n | The usual ' Prelude.dropWhile ' optimised for ' 's . dropWhile :: (Char -> Bool) -> YiString -> YiString dropWhile p = YiString . go . fromRope where go t = case viewl t of EmptyL -> T.empty Chunk 0 _ :< ts -> go ts Chunk l x :< ts -> let r = TX.dropWhile p x l' = TX.length r in case compare l' l of EQ -> t LT | TX.null r -> go ts | otherwise -> Chunk l' r <| ts _ -> Chunk l' r -| ts dropWhileEnd :: (Char -> Bool) -> YiString -> YiString dropWhileEnd p = YiString . go . fromRope where go t = case viewr t of EmptyR -> T.empty ts :> Chunk 0 _ -> go ts ts :> Chunk l x -> let r = TX.dropWhileEnd p x l' = TX.length r in case compare l' l of EQ -> t LT | TX.null r -> go ts | otherwise -> ts |> Chunk l' r _ -> ts |- Chunk l' r | The usual ' Prelude.takeWhile ' optimised for ' 's . takeWhile :: (Char -> Bool) -> YiString -> YiString takeWhile p = YiString . go . fromRope where go t = case viewl t of EmptyL -> T.empty Chunk 0 _ :< ts -> go ts Chunk l x :< ts -> let r = TX.takeWhile p x l' = TX.length r in case compare l' l of EQ -> Chunk l x -| go ts use unsafe functions and Chunk size goes out of sync with _ -> T.singleton $ Chunk l' r | Like ' Yi . Rope.takeWhile ' but takes from the end instead . takeWhileEnd :: (Char -> Bool) -> YiString -> YiString takeWhileEnd p = YiString . go . fromRope where go t = case viewr t of EmptyR -> T.empty ts :> Chunk 0 _ -> go ts ts :> Chunk l x -> case compare l' l of EQ -> go ts |> Chunk l x _ -> T.singleton $ Chunk l' r where r = TX.reverse . TX.takeWhile p . TX.reverse $ x l' = TX.length r | Returns a pair whose first element is the longest prefix ( possibly empty ) of t of elements that satisfy p , and whose second is the remainder of the string . See also ' TX.span ' . This implementation uses . Rope.splitAt ' which actually is just as fast as hand - unrolling the tree . GHC sure is great ! span :: (Char -> Bool) -> YiString -> (YiString, YiString) span p y = let x = Yi.Rope.takeWhile p y in case Yi.Rope.splitAt (Yi.Rope.length x) y of (_, y') -> (x, y') break :: (Char -> Bool) -> YiString -> (YiString, YiString) break p = Yi.Rope.span (not . p) | Concatenates the list of ' 's after inserting the user - provided ' ' between the elements . Empty ' 's are not ignored and will end up as strings of length 1 . If you do n't want this , it 's up to you to pre - process the intercalate :: YiString -> [YiString] -> YiString intercalate _ [] = mempty intercalate (YiString t') (YiString s:ss) = YiString $ go s ss where go !acc [] = acc go acc (YiString t : ts') = go (acc >< t' >< t) ts' | Intersperses the given character between the ' 's . This is What 's more , the result is a single ' ' . You can easily ' Yi.Rope.intercalate ' . Note that what this does _ _ not _ _ do is intersperse :: Char -> [YiString] -> YiString intersperse _ [] = mempty intersperse c (t:ts) = go t ts where go !acc [] = acc go acc (t':ts') = go (acc <> (c `cons` t')) ts' | Add a ' ' in front of a ' ' . cons :: Char -> YiString -> YiString cons c (YiString t) = case viewl t of EmptyL -> Yi.Rope.singleton c Chunk l x :< ts | l < defaultChunkSize -> YiString $ Chunk (l + 1) (c `TX.cons` x) <| ts _ -> YiString $ Chunk 1 (TX.singleton c) <| t | Add a ' ' in the back of a ' ' . snoc :: YiString -> Char -> YiString snoc (YiString t) c = case viewr t of EmptyR -> Yi.Rope.singleton c ts :> Chunk l x | l < defaultChunkSize -> YiString $ ts |> Chunk (l + 1) (x `TX.snoc` c) _ -> YiString $ t |> Chunk 1 (TX.singleton c) | Single character ' ' . Consider whether it 's worth creating singleton :: Char -> YiString singleton c = YiString . T.singleton $ Chunk 1 (TX.singleton c) Zero - indexed lines . @n > 0@ gives you the first n lines . splitAtLine :: Int -> YiString -> (YiString, YiString) splitAtLine n r | n <= 0 = (empty, r) | otherwise = splitAtLine' (n - 1) r Zero - indexed lines . Splitting at line < = 0 gives you the first line . Splitting at @n > 0@ gives you the first n + 1 lines . splitAtLine' :: Int -> YiString -> (YiString, YiString) splitAtLine' p (YiString tr) = case viewl s of ch@(Chunk _ x) :< r -> let excess = lineIndex (measure f) + lineIndex (measure ch) - p - 1 (lx, rx) = cutExcess excess x in (YiString $ f |- mkChunk TX.length lx, YiString $ mkChunk TX.length rx -| r) _ -> (YiString f, YiString s) where (f, s) = T.split ((p <) . lineIndex) tr cutExcess :: Int -> TX.Text -> (TX.Text, TX.Text) cutExcess n t = case TX.length t of 0 -> (TX.empty, TX.empty) _ -> let ns = countNl t ls = TX.lines t front = TX.unlines $ Prelude.take (ns - n) ls back = TX.drop (TX.length front) t in if n >= ns then (t, TX.empty) else (front, back) behaviour which blindly used @ByteString@s split and stitched the lines :: YiString -> [YiString] lines = Prelude.map dropNl . lines' where dropNl (YiString t) = case viewr t of EmptyR -> Yi.Rope.empty ts :> ch@(Chunk l tx) -> YiString $ ts |- if TX.null tx then ch else case TX.last tx of '\n' -> Chunk (l - 1) (TX.init tx) _ -> ch | Splits the ' ' into a list of ' ' each containing a lines' :: YiString -> [YiString] lines' t = let (YiString f, YiString s) = splitAtLine' 0 t in if T.null s then if T.null f then [] else [YiString f] else YiString f : lines' (YiString s) unlines :: [YiString] -> YiString unlines = Yi.Rope.intersperse '\n' | ' ' specialised @any@. any :: (Char -> Bool) -> YiString -> Bool any p = go . fromRope where go x = case viewl x of EmptyL -> False Chunk _ t :< ts -> TX.any p t || go ts | ' ' specialised @all@. all :: (Char -> Bool) -> YiString -> Bool all p = go . fromRope where go x = case viewl x of EmptyL -> True Chunk _ t :< ts -> TX.all p t && go ts | To serialise a ' ' , we turn it into a regular ' String ' instance Binary YiString where put = put . toString get = Yi.Rope.fromString <$> get | Write a ' ' into the given file . writeFile :: FilePath -> YiString -> IO () writeFile f = TXIO.writeFile f . toText readFile :: FilePath -> IO (Either TX.Text YiString) readFile fp = BSL.readFile fp >>= go decoders where go [] _ = pure (Left err) go (d : ds) bytes = try (pure (d bytes)) >>= \case Left (_ :: TXEE.UnicodeException) -> go ds bytes Right text -> pure (Right (fromLazyText text)) err = "Could not guess the encoding of " <> TX.pack fp decoders = [ TXLE.decodeUtf8 , TXLE.decodeUtf16LE , TXLE.decodeUtf16BE , TXLE.decodeUtf32LE , TXLE.decodeUtf32BE ] filter :: (Char -> Bool) -> YiString -> YiString filter p = YiString . go . fromRope where go t = case viewl t of EmptyL -> T.empty Chunk _ x :< ts -> mkChunk TX.length (TX.filter p x) -| go ts map :: (Char -> Char) -> YiString -> YiString map f = YiString . go . fromRope where go t = case viewl t of EmptyL -> T.empty Chunk l x :< ts -> Chunk l (TX.map f x) <| go ts | Join given ' 's with a space . Empty lines will be filtered out first . unwords :: [YiString] -> YiString unwords = Yi.Rope.intersperse ' ' | Splits the given ' ' into a list of words , where spaces words :: YiString -> [YiString] words = Prelude.filter (not . Yi.Rope.null) . Yi.Rope.split isSpace | Splits the ' ' on characters matching the predicate , like ' ' . Implementation note : GHC actually makes this naive implementation split :: (Char -> Bool) -> YiString -> [YiString] split p = fmap fromText . TX.split p . toText Benchmarks show that folding is actually Pretty Damn Slow ™ : consider foldl' :: (a -> Char -> a) -> a -> YiString -> a foldl' f a = go a . fromRope where go acc t = case viewl t of EmptyL -> acc Chunk _ x :< ts -> let r = TX.foldl' f acc x in r `seq` go r ts | Replicate the given set number of times , concatenating replicate :: Int -> YiString -> YiString replicate n t | n <= 0 = mempty | otherwise = t <> Yi.Rope.replicate (n - 1) t result into a ' ' . replicateChar :: Int -> Char -> YiString replicateChar n = fromText . TX.replicate n . TX.singleton ' ' instead . > > > let t = ' fromString ' " abc " < > ' fromString ' " def " > > > ' toString ' $ ' withText ' ' ' t withText :: (TX.Text -> TX.Text) -> YiString -> YiString withText f = YiString . T.fmap' (mkChunk TX.length . f . _fromChunk) . fromRope you use this with functions which do n't preserve ' ' , that is Also see ' T.unsafeFmap ' unsafeWithText :: (TX.Text -> TX.Text) -> YiString -> YiString unsafeWithText f = YiString . T.unsafeFmap g . fromRope where g (Chunk l t) = Chunk l (f t)
c645156eaa822a8223ddfdf4cc1caea87b76ce975753926d2f16ea828c1dbd98
mitchellwrosen/hspolls
GetPoll.hs
module Hp.ResponseBody.GetPoll ( GetPollResponseBody(..) , makeGetPollResponseBody ) where import Hp.Entity.Poll (Poll) import Hp.PollFormElement (PollFormElement) import Hp.PollQuestionAnswer (PollQuestionAnswer) import Data.Aeson (ToJSON) import Data.Time (DiffTime, UTCTime) data GetPollResponseBody = GetPollResponseBody { created :: UTCTime , duration :: DiffTime , poll :: [PollFormElement] , answers :: Vector [PollQuestionAnswer] } deriving stock (Generic) deriving anyclass (ToJSON) makeGetPollResponseBody :: Poll -> Vector [PollQuestionAnswer] -> GetPollResponseBody makeGetPollResponseBody poll answers = GetPollResponseBody { created = poll ^. #created , duration = poll ^. #duration , poll = poll ^. #elements , answers = answers }
null
https://raw.githubusercontent.com/mitchellwrosen/hspolls/22efea743194ade091f7daa112a2d9ce985a4500/src/Hp/ResponseBody/GetPoll.hs
haskell
module Hp.ResponseBody.GetPoll ( GetPollResponseBody(..) , makeGetPollResponseBody ) where import Hp.Entity.Poll (Poll) import Hp.PollFormElement (PollFormElement) import Hp.PollQuestionAnswer (PollQuestionAnswer) import Data.Aeson (ToJSON) import Data.Time (DiffTime, UTCTime) data GetPollResponseBody = GetPollResponseBody { created :: UTCTime , duration :: DiffTime , poll :: [PollFormElement] , answers :: Vector [PollQuestionAnswer] } deriving stock (Generic) deriving anyclass (ToJSON) makeGetPollResponseBody :: Poll -> Vector [PollQuestionAnswer] -> GetPollResponseBody makeGetPollResponseBody poll answers = GetPollResponseBody { created = poll ^. #created , duration = poll ^. #duration , poll = poll ^. #elements , answers = answers }
f21230ef8f5447d13e21eab931e0232843506df47a47ba6ec1112b33eb044aa5
scorphus/advent-of-code-2022
main.rkt
#lang racket/base (module+ test (require rackunit)) ;; Notice ;; To install (from within the package directory): $ raco pkg install ;; To install (once uploaded to pkgs.racket-lang.org): $ raco pkg install < < name > > ;; To uninstall: $ raco pkg remove < < name > > ;; To view documentation: ;; $ raco docs <<name>> ;; ;; For your convenience, we have included LICENSE-MIT and LICENSE-APACHE files. ;; If you would prefer to use a different license, replace those files with the ;; desired license. ;; ;; Some users like to add a `private/` directory, place auxiliary files there, ;; and require them in `main.rkt`. ;; ;; See the current version of the racket style guide here: -lang.org/style/index.html ;; Code here (module+ test Any code in this ` test ` submodule runs when this file is run using ;; or with `raco test`. The code here does not run when this file is ;; required by another module. (check-equal? (+ 2 2) 4)) (module+ main ;; (Optional) main submodule. Put code here if you need it to be executed when this file is run using or the ` racket ` executable . The code here ;; does not run when this file is required by another module. Documentation: -lang.org/guide/Module_Syntax.html#%28part._main-and-test%29 (require racket/cmdline) (define who (box "world")) (command-line #:program "my-program" #:once-each [("-n" "--name") name "Who to say hello to" (set-box! who name)] #:args () (printf "hello ~a~n" (unbox who))))
null
https://raw.githubusercontent.com/scorphus/advent-of-code-2022/07e5385116f8c889b44122f5ca2c6dffac12c037/main.rkt
racket
Notice To install (from within the package directory): To install (once uploaded to pkgs.racket-lang.org): To uninstall: To view documentation: $ raco docs <<name>> For your convenience, we have included LICENSE-MIT and LICENSE-APACHE files. If you would prefer to use a different license, replace those files with the desired license. Some users like to add a `private/` directory, place auxiliary files there, and require them in `main.rkt`. See the current version of the racket style guide here: Code here or with `raco test`. The code here does not run when this file is required by another module. (Optional) main submodule. Put code here if you need it to be executed when does not run when this file is required by another module. Documentation:
#lang racket/base (module+ test (require rackunit)) $ raco pkg install $ raco pkg install < < name > > $ raco pkg remove < < name > > -lang.org/style/index.html (module+ test Any code in this ` test ` submodule runs when this file is run using (check-equal? (+ 2 2) 4)) (module+ main this file is run using or the ` racket ` executable . The code here -lang.org/guide/Module_Syntax.html#%28part._main-and-test%29 (require racket/cmdline) (define who (box "world")) (command-line #:program "my-program" #:once-each [("-n" "--name") name "Who to say hello to" (set-box! who name)] #:args () (printf "hello ~a~n" (unbox who))))
580c12c379f06b66c94d65b64e87d4ffb7b75ec57b9c0ef1af71a2fe92b05ca8
picrin-scheme/picrin
roundtrip.scm
(import (scheme base) (srfi 27) (scheme inexact) (picrin test)) (test-begin) (define (rountrip-ok number) (let ((radix 10)) (eqv? number (string->number (number->string number radix) radix)))) (test #t (rountrip-ok -nan.0)) (test #t (rountrip-ok +nan.0)) (test #t (rountrip-ok -inf.0)) (test #t (rountrip-ok +inf.0)) (test #t (rountrip-ok +0.0)) (test #t (rountrip-ok -0.0)) (test #t (rountrip-ok 0.0)) (test -inf.0 (string->number "-inf.0")) (test +inf.0 (string->number "+inf.0")) (test #t (nan? (string->number "-nan.0"))) (test #t (nan? (string->number "+nan.0"))) (define (random-roundtrip) (let ((r (random-real))) (if (rountrip-ok r) #t r))) (test #t (random-roundtrip)) (test #t (random-roundtrip)) (test #t (random-roundtrip)) (test #t (random-roundtrip)) (test #t (random-roundtrip)) (test #t (random-roundtrip)) (test #t (random-roundtrip)) (test #t (random-roundtrip)) (test #t (random-roundtrip)) (test #t (random-roundtrip)) (test #t (random-roundtrip)) (test #t (random-roundtrip)) (test #t (random-roundtrip)) (test-end)
null
https://raw.githubusercontent.com/picrin-scheme/picrin/2af16bc88fbfca2efafd27ca9e5006d73c06f6fb/contrib/10.roundtrip/t/roundtrip.scm
scheme
(import (scheme base) (srfi 27) (scheme inexact) (picrin test)) (test-begin) (define (rountrip-ok number) (let ((radix 10)) (eqv? number (string->number (number->string number radix) radix)))) (test #t (rountrip-ok -nan.0)) (test #t (rountrip-ok +nan.0)) (test #t (rountrip-ok -inf.0)) (test #t (rountrip-ok +inf.0)) (test #t (rountrip-ok +0.0)) (test #t (rountrip-ok -0.0)) (test #t (rountrip-ok 0.0)) (test -inf.0 (string->number "-inf.0")) (test +inf.0 (string->number "+inf.0")) (test #t (nan? (string->number "-nan.0"))) (test #t (nan? (string->number "+nan.0"))) (define (random-roundtrip) (let ((r (random-real))) (if (rountrip-ok r) #t r))) (test #t (random-roundtrip)) (test #t (random-roundtrip)) (test #t (random-roundtrip)) (test #t (random-roundtrip)) (test #t (random-roundtrip)) (test #t (random-roundtrip)) (test #t (random-roundtrip)) (test #t (random-roundtrip)) (test #t (random-roundtrip)) (test #t (random-roundtrip)) (test #t (random-roundtrip)) (test #t (random-roundtrip)) (test #t (random-roundtrip)) (test-end)
daba47ba93977107055c7b918ff050870278774114a451d67aababe1ff0f7c00
boolexpr/boolexpr
BoolExpr.hs
# LANGUAGE GeneralizedNewtypeDeriving , TypeFamilies # -------------------------------------------------------------------- -- | -- Module : Data.BoolExpr Copyright : ( c ) 2008,2009 -- License : BSD3 -- Maintainer : < > -- Stability : provisional -- Portability: -- -- Boolean expressions and various representations. -------------------------------------------------------------------- module Data.BoolExpr (-- * A boolean class Boolean(..) * Generic functions derived from Boolean ,bAnd ,bAll ,bOr ,bAny -- * Boolean trees ,BoolExpr(..) ,reduceBoolExpr ,evalBoolExpr -- * Boolean evaluation semantic ,Eval(..) ,runEvalId -- * Signed constants ,Signed(..) ,negateSigned ,evalSigned ,reduceSigned ,constants ,negateConstant -- * Conjunctive Normal Form ,CNF(..),Conj(..) ,fromCNF ,boolTreeToCNF ,reduceCNF -- * Disjunctive Normal Form ,Disj(..),DNF(..) ,fromDNF ,boolTreeToDNF ,reduceDNF -- * Other transformations ,dualize ,fromBoolExpr ,pushNotInwards ) where -- import Test.QuickCheck hiding (Positive) import Control . Applicative import Control.Monad (ap) import Data.Traversable -- | Signed values are either positive or negative. data Signed a = Positive a | Negative a deriving (Eq, Ord, Show, Read) instance Functor Signed where fmap f (Positive x) = Positive (f x) fmap f (Negative x) = Negative (f x) instance Traversable Signed where traverse f (Positive x) = Positive <$> f x traverse f (Negative x) = Negative <$> f x instance Foldable Signed where foldMap = foldMapDefault instance Applicative Signed where pure = Positive (<*>) = ap instance Monad Signed where return = Positive Positive x >>= f = f x Negative x >>= f = negateSigned $ f x infix /\ infix \/ -- | A boolean type class. class Boolean f where ( /\ ) :: f a -> f a -> f a ( \/ ) :: f a -> f a -> f a bNot :: f a -> f a bTrue :: f a bFalse :: f a bConst :: Signed a -> f a -- | Generalized 'Data.Foldable.and'. bAnd :: (Foldable t, Boolean f) => t (f b) -> f b bAnd = foldr (/\) bTrue -- | Generalized 'Data.Foldable.all'. bAll :: (Foldable t, Boolean f) => (a -> f b) -> t a -> f b bAll f = foldr (\x y -> f x /\ y) bTrue -- | Generalized 'Data.Foldable.or'. bOr :: (Foldable t, Boolean f) => t (f b) -> f b bOr = foldr (\/) bFalse -- | Generalized 'Data.Foldable.any'. bAny :: (Foldable t, Boolean f) => (a -> f b) -> t a -> f b bAny f = foldr (\x y -> f x \/ y) bFalse -- | Syntax of boolean expressions parameterized over a -- set of leaves, named constants. data BoolExpr a = BAnd (BoolExpr a) (BoolExpr a) | BOr (BoolExpr a) (BoolExpr a) | BNot (BoolExpr a) | BTrue | BFalse | BConst (Signed a) deriving (Eq, Ord, Show) {-! derive : Arbitrary !-} instance Functor BoolExpr where fmap f (BAnd a b) = BAnd (fmap f a) (fmap f b) fmap f (BOr a b) = BOr (fmap f a) (fmap f b) fmap f (BNot t ) = BNot (fmap f t) fmap _ BTrue = BTrue fmap _ BFalse = BFalse fmap f (BConst x) = BConst (fmap f x) instance Traversable BoolExpr where traverse f (BAnd a b) = BAnd <$> traverse f a <*> traverse f b traverse f (BOr a b) = BOr <$> traverse f a <*> traverse f b traverse f (BNot t ) = BNot <$> traverse f t traverse _ BTrue = pure BTrue traverse _ BFalse = pure BFalse traverse f (BConst x) = BConst <$> traverse f x instance Foldable BoolExpr where foldMap = foldMapDefault instance Boolean BoolExpr where ( /\ ) = BAnd ( \/ ) = BOr bNot = BNot bTrue = BTrue bFalse = BFalse bConst = BConst newtype Eval b a = Eval { runEval :: (a -> b) -> b } runEvalId :: Eval a a -> a runEvalId e = runEval e id instance b ~ Bool => Boolean (Eval b) where ( /\ ) = liftE2 (&&) ( \/ ) = liftE2 (||) bNot = liftE not bTrue = Eval $ const True bFalse = Eval $ const False bConst = Eval . flip evalSigned liftE :: (b -> b) -> Eval b a -> Eval b a liftE f (Eval x) = Eval (f . x) liftE2 :: (b -> b -> b) -> Eval b a -> Eval b a -> Eval b a liftE2 f (Eval x) (Eval y) = Eval (\e -> f (x e) (y e)) -- | Turns a boolean tree into any boolean type. fromBoolExpr :: Boolean f => BoolExpr a -> f a fromBoolExpr (BAnd l r) = fromBoolExpr l /\ fromBoolExpr r fromBoolExpr (BOr l r) = fromBoolExpr l \/ fromBoolExpr r fromBoolExpr (BNot t ) = bNot $ fromBoolExpr t fromBoolExpr BTrue = bTrue fromBoolExpr BFalse = bFalse fromBoolExpr (BConst c) = bConst c --- | Disjunction of atoms ('a') newtype Disj a = Disj { unDisj :: [a] } deriving (Show, Functor, Semigroup, Monoid) --- | Conjunction of atoms ('a') newtype Conj a = Conj { unConj :: [a] } deriving (Show, Functor, Semigroup, Monoid) --- | Conjunctive Normal Form newtype CNF a = CNF { unCNF :: Conj (Disj (Signed a)) } deriving (Show, Semigroup, Monoid) --- | Disjunctive Normal Form newtype DNF a = DNF { unDNF :: Disj (Conj (Signed a)) } deriving (Show, Semigroup, Monoid) instance Functor CNF where fmap f (CNF x) = CNF (fmap (fmap (fmap f)) x) instance Boolean CNF where l /\ r = l `mappend` r l \/ r = CNF $ Conj [ x `mappend` y | x <- unConj $ unCNF l , y <- unConj $ unCNF r ] bNot = error "bNot on CNF" bTrue = CNF $ Conj[] bFalse = CNF $ Conj[Disj[]] bConst x = CNF $ Conj[Disj[x]] instance Functor DNF where fmap f (DNF x) = DNF (fmap (fmap (fmap f)) x) instance Boolean DNF where l /\ r = DNF $ Disj [ x `mappend` y | x <- unDisj $ unDNF l , y <- unDisj $ unDNF r ] l \/ r = l `mappend` r bNot = error "bNot on CNF" bTrue = DNF $ Disj[Conj[]] bFalse = DNF $ Disj[] bConst x = DNF $ Disj[Conj[x]] -- | Reduce a boolean tree annotated by booleans to a single boolean. reduceBoolExpr :: BoolExpr Bool -> Bool reduceBoolExpr = evalBoolExpr id -- Given a evaluation function of constants, returns an evaluation -- function over boolean trees. -- -- Note that since 'BoolExpr' is a functor, one can simply use -- 'reduceBoolExpr': -- -- @ evalBoolExpr f = reduceBoolExpr . fmap ( f$ ) -- @ evalBoolExpr :: (a -> Bool) -> (BoolExpr a -> Bool) evalBoolExpr env expr = runEval (fromBoolExpr expr) env -- | Returns constants used in a given boolean tree, these constants are returned signed depending one how many -- negations stands over a given constant. constants :: BoolExpr a -> [Signed a] constants = go True where go sign (BAnd a b) = go sign a ++ go sign b go sign (BOr a b) = go sign a ++ go sign b go sign (BNot t) = go (not sign) t go _ BTrue = [] go _ BFalse = [] go sign (BConst x) = [if sign then x else negateSigned x] dualize :: Boolean f => BoolExpr a -> f a dualize (BAnd l r) = dualize l \/ dualize r dualize (BOr l r) = dualize l /\ dualize r dualize BTrue = bFalse dualize BFalse = bTrue dualize (BConst c) = negateConstant c dualize (BNot e) = fromBoolExpr e When dualize is used by pushNotInwards not BNot remain , -- hence it makes sense to assert that dualize does not have to work on BNot . However ` dualize ` can be freely -- used as a fancy `bNot`. -- dualize (BNot _) = error "dualize: impossible" -- | Push the negations inwards as much as possible. -- The resulting boolean tree no longer use negations. pushNotInwards :: Boolean f => BoolExpr a -> f a pushNotInwards (BAnd l r) = pushNotInwards l /\ pushNotInwards r pushNotInwards (BOr l r) = pushNotInwards l \/ pushNotInwards r pushNotInwards (BNot t ) = dualize $ pushNotInwards t pushNotInwards BTrue = bTrue pushNotInwards BFalse = bFalse pushNotInwards (BConst c) = bConst c -- | Convert a 'CNF' (a boolean expression in conjunctive normal form) -- to any other form supported by 'Boolean'. fromCNF :: Boolean f => CNF a -> f a fromCNF = bAll (bAny bConst . unDisj) . unConj . unCNF -- | Convert a 'DNF' (a boolean expression in disjunctive normal form) -- to any other form supported by 'Boolean'. fromDNF :: Boolean f => DNF a -> f a fromDNF = bAny (bAll bConst . unConj) . unDisj . unDNF -- | Convert a boolean tree to a conjunctive normal form. boolTreeToCNF :: BoolExpr a -> CNF a boolTreeToCNF = pushNotInwards -- | Convert a boolean tree to a disjunctive normal form. boolTreeToDNF :: BoolExpr a -> DNF a boolTreeToDNF = pushNotInwards -- | Reduce a boolean expression in conjunctive normal form to a single -- boolean. reduceCNF :: CNF Bool -> Bool reduceCNF = runEvalId . fromCNF -- | Reduce a boolean expression in disjunctive normal form to a single -- boolean. reduceDNF :: DNF Bool -> Bool reduceDNF = runEvalId . fromDNF evalSigned :: (a -> Bool) -> Signed a -> Bool evalSigned f (Positive x) = f x evalSigned f (Negative x) = not $ f x reduceSigned :: Signed Bool -> Bool reduceSigned = evalSigned id negateSigned :: Signed a -> Signed a negateSigned (Positive x) = Negative x negateSigned (Negative x) = Positive x negateConstant :: Boolean f => Signed a -> f a negateConstant = bConst . negateSigned prop_reduceBoolExpr_EQ_reduceCNF t = reduceBoolExpr t = = reduceCNF ( boolTreeToCNF t ) prop_reduceBoolExpr_EQ_reduceCNF_Bool = prop_reduceBoolExpr_EQ_reduceCNF ( BConst . not ) prop_reduceBoolExpr_EQ_reduceDNF t = reduceBoolExpr t = = reduceDNF ( boolTreeToDNF t ) prop_reduceBoolExpr_EQ_reduceDNF_Bool = prop_reduceBoolExpr_EQ_reduceDNF ( BConst . not ) { - * Generated by DrIFT : Look , but Do n't Touch . * prop_reduceBoolExpr_EQ_reduceCNF t = reduceBoolExpr t == reduceCNF (boolTreeToCNF t) prop_reduceBoolExpr_EQ_reduceCNF_Bool = prop_reduceBoolExpr_EQ_reduceCNF (BConst . not) prop_reduceBoolExpr_EQ_reduceDNF t = reduceBoolExpr t == reduceDNF (boolTreeToDNF t) prop_reduceBoolExpr_EQ_reduceDNF_Bool = prop_reduceBoolExpr_EQ_reduceDNF (BConst . not) {-* Generated by DrIFT : Look, but Don't Touch. *-} instance (Arbitrary a) => Arbitrary (BoolExpr a) where arbitrary = do x <- choose (1::Int,6) -- :: Int inserted manually case x of 1 -> do v1 <- arbitrary v2 <- arbitrary return (BAnd v1 v2) 2 -> do v1 <- arbitrary v2 <- arbitrary return (BOr v1 v2) 3 -> do v1 <- arbitrary return (BNot v1) 4 -> do return (BTrue ) 5 -> do return (BFalse ) 6 -> do v1 <- arbitrary return (BConst v1) = error " not yet supported " -- quickcheck2 -}
null
https://raw.githubusercontent.com/boolexpr/boolexpr/023185a3a2c8b90ef156c2392dfd554447fbeee4/Data/BoolExpr.hs
haskell
------------------------------------------------------------------ | Module : Data.BoolExpr License : BSD3 Stability : provisional Portability: Boolean expressions and various representations. ------------------------------------------------------------------ * A boolean class * Boolean trees * Boolean evaluation semantic * Signed constants * Conjunctive Normal Form * Disjunctive Normal Form * Other transformations import Test.QuickCheck hiding (Positive) | Signed values are either positive or negative. | A boolean type class. | Generalized 'Data.Foldable.and'. | Generalized 'Data.Foldable.all'. | Generalized 'Data.Foldable.or'. | Generalized 'Data.Foldable.any'. | Syntax of boolean expressions parameterized over a set of leaves, named constants. ! derive : Arbitrary ! | Turns a boolean tree into any boolean type. - | Disjunction of atoms ('a') - | Conjunction of atoms ('a') - | Conjunctive Normal Form - | Disjunctive Normal Form | Reduce a boolean tree annotated by booleans to a single boolean. Given a evaluation function of constants, returns an evaluation function over boolean trees. Note that since 'BoolExpr' is a functor, one can simply use 'reduceBoolExpr': @ @ | Returns constants used in a given boolean tree, these negations stands over a given constant. hence it makes sense to assert that dualize does not used as a fancy `bNot`. dualize (BNot _) = error "dualize: impossible" | Push the negations inwards as much as possible. The resulting boolean tree no longer use negations. | Convert a 'CNF' (a boolean expression in conjunctive normal form) to any other form supported by 'Boolean'. | Convert a 'DNF' (a boolean expression in disjunctive normal form) to any other form supported by 'Boolean'. | Convert a boolean tree to a conjunctive normal form. | Convert a boolean tree to a disjunctive normal form. | Reduce a boolean expression in conjunctive normal form to a single boolean. | Reduce a boolean expression in disjunctive normal form to a single boolean. * Generated by DrIFT : Look, but Don't Touch. * :: Int inserted manually quickcheck2
# LANGUAGE GeneralizedNewtypeDeriving , TypeFamilies # Copyright : ( c ) 2008,2009 Maintainer : < > module Data.BoolExpr Boolean(..) * Generic functions derived from Boolean ,bAnd ,bAll ,bOr ,bAny ,BoolExpr(..) ,reduceBoolExpr ,evalBoolExpr ,Eval(..) ,runEvalId ,Signed(..) ,negateSigned ,evalSigned ,reduceSigned ,constants ,negateConstant ,CNF(..),Conj(..) ,fromCNF ,boolTreeToCNF ,reduceCNF ,Disj(..),DNF(..) ,fromDNF ,boolTreeToDNF ,reduceDNF ,dualize ,fromBoolExpr ,pushNotInwards ) where import Control . Applicative import Control.Monad (ap) import Data.Traversable data Signed a = Positive a | Negative a deriving (Eq, Ord, Show, Read) instance Functor Signed where fmap f (Positive x) = Positive (f x) fmap f (Negative x) = Negative (f x) instance Traversable Signed where traverse f (Positive x) = Positive <$> f x traverse f (Negative x) = Negative <$> f x instance Foldable Signed where foldMap = foldMapDefault instance Applicative Signed where pure = Positive (<*>) = ap instance Monad Signed where return = Positive Positive x >>= f = f x Negative x >>= f = negateSigned $ f x infix /\ infix \/ class Boolean f where ( /\ ) :: f a -> f a -> f a ( \/ ) :: f a -> f a -> f a bNot :: f a -> f a bTrue :: f a bFalse :: f a bConst :: Signed a -> f a bAnd :: (Foldable t, Boolean f) => t (f b) -> f b bAnd = foldr (/\) bTrue bAll :: (Foldable t, Boolean f) => (a -> f b) -> t a -> f b bAll f = foldr (\x y -> f x /\ y) bTrue bOr :: (Foldable t, Boolean f) => t (f b) -> f b bOr = foldr (\/) bFalse bAny :: (Foldable t, Boolean f) => (a -> f b) -> t a -> f b bAny f = foldr (\x y -> f x \/ y) bFalse data BoolExpr a = BAnd (BoolExpr a) (BoolExpr a) | BOr (BoolExpr a) (BoolExpr a) | BNot (BoolExpr a) | BTrue | BFalse | BConst (Signed a) instance Functor BoolExpr where fmap f (BAnd a b) = BAnd (fmap f a) (fmap f b) fmap f (BOr a b) = BOr (fmap f a) (fmap f b) fmap f (BNot t ) = BNot (fmap f t) fmap _ BTrue = BTrue fmap _ BFalse = BFalse fmap f (BConst x) = BConst (fmap f x) instance Traversable BoolExpr where traverse f (BAnd a b) = BAnd <$> traverse f a <*> traverse f b traverse f (BOr a b) = BOr <$> traverse f a <*> traverse f b traverse f (BNot t ) = BNot <$> traverse f t traverse _ BTrue = pure BTrue traverse _ BFalse = pure BFalse traverse f (BConst x) = BConst <$> traverse f x instance Foldable BoolExpr where foldMap = foldMapDefault instance Boolean BoolExpr where ( /\ ) = BAnd ( \/ ) = BOr bNot = BNot bTrue = BTrue bFalse = BFalse bConst = BConst newtype Eval b a = Eval { runEval :: (a -> b) -> b } runEvalId :: Eval a a -> a runEvalId e = runEval e id instance b ~ Bool => Boolean (Eval b) where ( /\ ) = liftE2 (&&) ( \/ ) = liftE2 (||) bNot = liftE not bTrue = Eval $ const True bFalse = Eval $ const False bConst = Eval . flip evalSigned liftE :: (b -> b) -> Eval b a -> Eval b a liftE f (Eval x) = Eval (f . x) liftE2 :: (b -> b -> b) -> Eval b a -> Eval b a -> Eval b a liftE2 f (Eval x) (Eval y) = Eval (\e -> f (x e) (y e)) fromBoolExpr :: Boolean f => BoolExpr a -> f a fromBoolExpr (BAnd l r) = fromBoolExpr l /\ fromBoolExpr r fromBoolExpr (BOr l r) = fromBoolExpr l \/ fromBoolExpr r fromBoolExpr (BNot t ) = bNot $ fromBoolExpr t fromBoolExpr BTrue = bTrue fromBoolExpr BFalse = bFalse fromBoolExpr (BConst c) = bConst c newtype Disj a = Disj { unDisj :: [a] } deriving (Show, Functor, Semigroup, Monoid) newtype Conj a = Conj { unConj :: [a] } deriving (Show, Functor, Semigroup, Monoid) newtype CNF a = CNF { unCNF :: Conj (Disj (Signed a)) } deriving (Show, Semigroup, Monoid) newtype DNF a = DNF { unDNF :: Disj (Conj (Signed a)) } deriving (Show, Semigroup, Monoid) instance Functor CNF where fmap f (CNF x) = CNF (fmap (fmap (fmap f)) x) instance Boolean CNF where l /\ r = l `mappend` r l \/ r = CNF $ Conj [ x `mappend` y | x <- unConj $ unCNF l , y <- unConj $ unCNF r ] bNot = error "bNot on CNF" bTrue = CNF $ Conj[] bFalse = CNF $ Conj[Disj[]] bConst x = CNF $ Conj[Disj[x]] instance Functor DNF where fmap f (DNF x) = DNF (fmap (fmap (fmap f)) x) instance Boolean DNF where l /\ r = DNF $ Disj [ x `mappend` y | x <- unDisj $ unDNF l , y <- unDisj $ unDNF r ] l \/ r = l `mappend` r bNot = error "bNot on CNF" bTrue = DNF $ Disj[Conj[]] bFalse = DNF $ Disj[] bConst x = DNF $ Disj[Conj[x]] reduceBoolExpr :: BoolExpr Bool -> Bool reduceBoolExpr = evalBoolExpr id evalBoolExpr f = reduceBoolExpr . fmap ( f$ ) evalBoolExpr :: (a -> Bool) -> (BoolExpr a -> Bool) evalBoolExpr env expr = runEval (fromBoolExpr expr) env constants are returned signed depending one how many constants :: BoolExpr a -> [Signed a] constants = go True where go sign (BAnd a b) = go sign a ++ go sign b go sign (BOr a b) = go sign a ++ go sign b go sign (BNot t) = go (not sign) t go _ BTrue = [] go _ BFalse = [] go sign (BConst x) = [if sign then x else negateSigned x] dualize :: Boolean f => BoolExpr a -> f a dualize (BAnd l r) = dualize l \/ dualize r dualize (BOr l r) = dualize l /\ dualize r dualize BTrue = bFalse dualize BFalse = bTrue dualize (BConst c) = negateConstant c dualize (BNot e) = fromBoolExpr e When dualize is used by pushNotInwards not BNot remain , have to work on BNot . However ` dualize ` can be freely pushNotInwards :: Boolean f => BoolExpr a -> f a pushNotInwards (BAnd l r) = pushNotInwards l /\ pushNotInwards r pushNotInwards (BOr l r) = pushNotInwards l \/ pushNotInwards r pushNotInwards (BNot t ) = dualize $ pushNotInwards t pushNotInwards BTrue = bTrue pushNotInwards BFalse = bFalse pushNotInwards (BConst c) = bConst c fromCNF :: Boolean f => CNF a -> f a fromCNF = bAll (bAny bConst . unDisj) . unConj . unCNF fromDNF :: Boolean f => DNF a -> f a fromDNF = bAny (bAll bConst . unConj) . unDisj . unDNF boolTreeToCNF :: BoolExpr a -> CNF a boolTreeToCNF = pushNotInwards boolTreeToDNF :: BoolExpr a -> DNF a boolTreeToDNF = pushNotInwards reduceCNF :: CNF Bool -> Bool reduceCNF = runEvalId . fromCNF reduceDNF :: DNF Bool -> Bool reduceDNF = runEvalId . fromDNF evalSigned :: (a -> Bool) -> Signed a -> Bool evalSigned f (Positive x) = f x evalSigned f (Negative x) = not $ f x reduceSigned :: Signed Bool -> Bool reduceSigned = evalSigned id negateSigned :: Signed a -> Signed a negateSigned (Positive x) = Negative x negateSigned (Negative x) = Positive x negateConstant :: Boolean f => Signed a -> f a negateConstant = bConst . negateSigned prop_reduceBoolExpr_EQ_reduceCNF t = reduceBoolExpr t = = reduceCNF ( boolTreeToCNF t ) prop_reduceBoolExpr_EQ_reduceCNF_Bool = prop_reduceBoolExpr_EQ_reduceCNF ( BConst . not ) prop_reduceBoolExpr_EQ_reduceDNF t = reduceBoolExpr t = = reduceDNF ( boolTreeToDNF t ) prop_reduceBoolExpr_EQ_reduceDNF_Bool = prop_reduceBoolExpr_EQ_reduceDNF ( BConst . not ) { - * Generated by DrIFT : Look , but Do n't Touch . * prop_reduceBoolExpr_EQ_reduceCNF t = reduceBoolExpr t == reduceCNF (boolTreeToCNF t) prop_reduceBoolExpr_EQ_reduceCNF_Bool = prop_reduceBoolExpr_EQ_reduceCNF (BConst . not) prop_reduceBoolExpr_EQ_reduceDNF t = reduceBoolExpr t == reduceDNF (boolTreeToDNF t) prop_reduceBoolExpr_EQ_reduceDNF_Bool = prop_reduceBoolExpr_EQ_reduceDNF (BConst . not) instance (Arbitrary a) => Arbitrary (BoolExpr a) where case x of 1 -> do v1 <- arbitrary v2 <- arbitrary return (BAnd v1 v2) 2 -> do v1 <- arbitrary v2 <- arbitrary return (BOr v1 v2) 3 -> do v1 <- arbitrary return (BNot v1) 4 -> do return (BTrue ) 5 -> do return (BFalse ) 6 -> do v1 <- arbitrary return (BConst v1) -}
b4758a001bb6c440be4963512c36f7ca7c62afdec5476b9a370e753460f08f05
HealthSamurai/unit-map
reader.cljc
(ns unit-map.impl.reader (:require [unit-map.impl.system :as system])) (defn process-urange [pprev prev next-useq nnext] {:pre [(and (not-every? nil? [pprev nnext]) (every? some? [prev next-useq]))]} (let [start (or pprev prev) end (or nnext next-useq) step (if (nil? pprev) (if (integer? next-useq) (- nnext next-useq) next-useq) (if (integer? prev) (- prev pprev) prev))] (system/create-urange start end step))) (defn process-enumeration [s] (loop [[pprev prev x next-useq nnext & rest] (concat [nil nil] s [nil nil]) result [] buffer []] (cond (nil? x) (vec (concat result buffer)) (= '.. x) (recur (concat [nil nil] rest) (concat result (drop-last 2 buffer) [(process-urange pprev prev next-useq nnext)]) []) :else (recur (concat [prev x next-useq nnext] rest) result (conj buffer x))))) (defn process-useq* [s] (process-enumeration s)) (def process-useq (memoize process-useq*)) (defn read-useq [form] (process-useq form))
null
https://raw.githubusercontent.com/HealthSamurai/unit-map/eb90c2c427c2fb0f48cb54e58d1565f3255ec16d/src/unit_map/impl/reader.cljc
clojure
(ns unit-map.impl.reader (:require [unit-map.impl.system :as system])) (defn process-urange [pprev prev next-useq nnext] {:pre [(and (not-every? nil? [pprev nnext]) (every? some? [prev next-useq]))]} (let [start (or pprev prev) end (or nnext next-useq) step (if (nil? pprev) (if (integer? next-useq) (- nnext next-useq) next-useq) (if (integer? prev) (- prev pprev) prev))] (system/create-urange start end step))) (defn process-enumeration [s] (loop [[pprev prev x next-useq nnext & rest] (concat [nil nil] s [nil nil]) result [] buffer []] (cond (nil? x) (vec (concat result buffer)) (= '.. x) (recur (concat [nil nil] rest) (concat result (drop-last 2 buffer) [(process-urange pprev prev next-useq nnext)]) []) :else (recur (concat [prev x next-useq nnext] rest) result (conj buffer x))))) (defn process-useq* [s] (process-enumeration s)) (def process-useq (memoize process-useq*)) (defn read-useq [form] (process-useq form))
63bd44691e88ba9a273dab4ded78b6b3c51a998de55119da59ee3264475458ed
mariari/Misc-Lisp-Scripts
arrow.lisp
;; (load "./data-structures/tuple.lisp") (eval-when (:compile-toplevel :load-toplevel :execute) (use-package 'tuple)) (defun **** (&rest fns) (flet ((func (f g) (lambda (x) (tup (funcall f (fst x)) (funcall g (snd x)))))) (reduce #'func fns :from-end t))) (defun &&& (&rest fns) (flet ((func (f g) (lambda (x) (tup (funcall f x) (funcall g x))))) (reduce #'func fns :from-end t))) (defun ***** (&rest functions) (lambda (xs) (mapcar (lambda (f x) (funcall f x)) functions xs)))
null
https://raw.githubusercontent.com/mariari/Misc-Lisp-Scripts/acecadc75fcbe15e6b97e084d179aacdbbde06a8/data-structures/arrow.lisp
lisp
(load "./data-structures/tuple.lisp")
(eval-when (:compile-toplevel :load-toplevel :execute) (use-package 'tuple)) (defun **** (&rest fns) (flet ((func (f g) (lambda (x) (tup (funcall f (fst x)) (funcall g (snd x)))))) (reduce #'func fns :from-end t))) (defun &&& (&rest fns) (flet ((func (f g) (lambda (x) (tup (funcall f x) (funcall g x))))) (reduce #'func fns :from-end t))) (defun ***** (&rest functions) (lambda (xs) (mapcar (lambda (f x) (funcall f x)) functions xs)))
f69f0a1f7e332059514f118fdfd30a8df3a160671091f1282d3c64ab9fdc7681
thoughtstem/morugamu
emoji-numb.rkt
#lang racket (provide theme) (require 2htdp/image) (define dot (bitmap "./emojis/dot.png")) (define 1-pic dot) (define 2-pic (beside dot dot)) (define 3-pic (above dot (beside dot dot))) (define 4-pic (above (beside dot dot) (beside dot dot))) (define 5-pic (above (beside dot dot) dot (beside dot dot))) (define 6-pic (beside (above dot dot dot) (above dot dot dot))) (define 7-pic (beside (above dot dot dot) dot (above dot dot dot))) (define 8-pic (beside (above dot dot dot) (above dot dot) (above dot dot dot))) (define 9-pic (beside (above dot dot dot) (above dot dot dot) (above dot dot dot))) (define theme (list (bitmap "./emojis/Next.png") (bitmap "./emojis/Previous.png") (bitmap "./emojis/0.png") 1-pic 2-pic 3-pic 4-pic 5-pic 6-pic 7-pic 8-pic 9-pic (bitmap "./emojis/add.png") (bitmap "./emojis/sub.png")))
null
https://raw.githubusercontent.com/thoughtstem/morugamu/a9095ddebe364adffb036c3faed95c873a4d9f3c/themes/emoji-numb.rkt
racket
#lang racket (provide theme) (require 2htdp/image) (define dot (bitmap "./emojis/dot.png")) (define 1-pic dot) (define 2-pic (beside dot dot)) (define 3-pic (above dot (beside dot dot))) (define 4-pic (above (beside dot dot) (beside dot dot))) (define 5-pic (above (beside dot dot) dot (beside dot dot))) (define 6-pic (beside (above dot dot dot) (above dot dot dot))) (define 7-pic (beside (above dot dot dot) dot (above dot dot dot))) (define 8-pic (beside (above dot dot dot) (above dot dot) (above dot dot dot))) (define 9-pic (beside (above dot dot dot) (above dot dot dot) (above dot dot dot))) (define theme (list (bitmap "./emojis/Next.png") (bitmap "./emojis/Previous.png") (bitmap "./emojis/0.png") 1-pic 2-pic 3-pic 4-pic 5-pic 6-pic 7-pic 8-pic 9-pic (bitmap "./emojis/add.png") (bitmap "./emojis/sub.png")))
7dd479d7cd2fbe5dab892d444840139e847f7f6b61af10685a4410cfec6cfe05
ghc/testsuite
T4917.hs
# LANGUAGE GADTs , ScopedTypeVariables , EmptyDataDecls , RankNTypes # module T4917 where only works on ghc6 but not on ghc7 type Const a b = a newtype Fix f n = In { out :: f (Fix f) n } mcata :: forall f a b . (forall x c . (forall d . x d -> Const b d) -> f x c -> Const b c) -> Fix f a -> Const b a mcata f x = f {- x=(Fix f), c=a -} mcataf outx where outx :: f (Fix f) a outx = out x mcataf :: forall d. Fix f d -> Const b d mcataf y = mcata {- f=f, a=d, b=b0 -} f (y :: Fix f d) -- Const b d ~ Const b0 d -- Expected type of f :: forall x c. (forall d. x d -> Const b0 d) -> f x c -> Const b0 c
null
https://raw.githubusercontent.com/ghc/testsuite/998a816ae89c4fd573f4abd7c6abb346cf7ee9af/tests/typecheck/should_compile/T4917.hs
haskell
x=(Fix f), c=a f=f, a=d, b=b0 Const b d ~ Const b0 d Expected type of f :: forall x c. (forall d. x d -> Const b0 d) -> f x c -> Const b0 c
# LANGUAGE GADTs , ScopedTypeVariables , EmptyDataDecls , RankNTypes # module T4917 where only works on ghc6 but not on ghc7 type Const a b = a newtype Fix f n = In { out :: f (Fix f) n } mcata :: forall f a b . (forall x c . (forall d . x d -> Const b d) -> f x c -> Const b c) -> Fix f a -> Const b a where outx :: f (Fix f) a outx = out x mcataf :: forall d. Fix f d -> Const b d
0797ab33e5a6b01dbdea03c4996d6942a81d45edf2822958295c89942e69fbf4
gndl/graffophone
gCurve.ml
* Copyright ( C ) 2015 Ga � * * All rights reserved . This file is distributed under the terms of the * GNU General Public License version 3.0 . * * This program is distributed in the hope that it will be useful , * but WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the * GNU Lesser General Public License for more details . * * You should have received a copy of the GNU Lesser General Public License * along with this program ; if not , write to the Free Software * Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA . * Copyright (C) 2015 Ga�tan Dubreil * * All rights reserved.This file is distributed under the terms of the * GNU General Public License version 3.0. * * 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. *) open Graffophone_plugin open Usual module SF = SampleFormat module Bus = EventBus let width = 256 let curveHeight = 101 let marginRate = 5. /. 100. let margin = iof(foi curveHeight *. marginRate) let height = curveHeight + 2 * margin class c pVoice (pSsnCtrl : SessionControler.c) = object (self) val mDrawingArea = GMisc.drawing_area ~width:1 ~height () val mutable mPixmap = Gdk.Pixmap.create ~width:1 ~height ~depth:24 () val mControls = GPack.hbox () val mVoiceColor = Style.makeVoiceGdkColor pVoice val mVoiceLabel = GMisc.label ~text:(Voice.getIdentity pVoice) () val mRemoveButton = GButton.tool_button ~stock:`CLOSE ~expand:false () val mValueRuler = GRange.ruler `VERTICAL ~metric:`PIXELS (*INCHES CENTIMETERS*) ~lower:(-1.) ~upper:1. (*~max_size:float*) ~position:0. () val mutable mLeftTick = 0 val mutable mPixelsPerTick = 0. val mutable mWidth = 0; val mutable mSelectedTimeRangeStartX = 0 val mutable mSelectedTimeRangeEndX = 0 val mutable mButtonReleaseTime = Int32.zero val mutable mPoints = [] val mutable mExposed = false initializer Bus.addObserver self#observe; let ctrlBox = GPack.vbox ~packing:mControls#add () in ctrlBox#add mVoiceLabel#coerce; let tb = GButton.toolbar ~orientation:`VERTICAL ~style:`ICONS ~tooltips:true () in tb#insert mRemoveButton; tb#set_icon_size`MENU; ctrlBox#add tb#coerce; mValueRuler#misc#set_size_request ~width:30 ~height (); mControls#pack ~expand:false mValueRuler#coerce; ignore(mDrawingArea#event#connect#expose ~callback:(fun ev -> self#expose(GdkEvent.Expose.area ev))); mDrawingArea#event#add [`BUTTON_PRESS; `BUTTON_RELEASE]; ignore(mDrawingArea#event#connect#button_release ~callback:(fun ev -> let button = GdkEvent.Button.button ev in let time = GdkEvent.Button.time ev in let x = GdkEvent.Button.x ev in let clickTick = mLeftTick + iof(x /. mPixelsPerTick) in let doubleClick = Int32.(to_int(sub time mButtonReleaseTime)) < 250 in trace("button released at "^sof x^" at "^ Int32.to_string time^" on "^Voice.getIdentity pVoice^(if doubleClick then " double click" else "")); if button = 1 then ( if doubleClick then pSsnCtrl#curve#zoomIn() else pSsnCtrl#setStartTick clickTick ) else if button = 3 then ( if doubleClick then pSsnCtrl#curve#zoomOut() else pSsnCtrl#setEndTick clickTick ); mButtonReleaseTime <- time; true) ) method getCurve = mDrawingArea#coerce method getControls = mControls#coerce method getRemoveButton = mRemoveButton method voiceIsFrom tkrId port = Voice.isFrom tkrId port pVoice method expose area = if not mExposed then ( mExposed <- true; self#drawPoints mPoints mWidth (height / 2); ); let win = mDrawingArea#misc#window in let gc = Gdk.GC.create win in let x = Gdk.Rectangle.x area in let y = Gdk.Rectangle.y area in let width = Gdk.Rectangle.width area in let height = Gdk.Rectangle.height area in Gdk.Draw.pixmap win gc ~xsrc:x ~ysrc:y ~xdest:x ~ydest:y ~width ~height mPixmap; self#drawSelectedTimeRange x width; true method draw leftTick ticksCount width pixelsPerTick = trace("leftTick "^soi leftTick^", ticksCount "^soi ticksCount^", width "^soi width^", pixelsPerTick "^sof pixelsPerTick); mLeftTick <- leftTick; mPixelsPerTick <- pixelsPerTick; mWidth <- width; let chunkIndex = ticksCount / SF.chunkSize in let lastLen = ticksCount mod SF.chunkSize in let values = A.make_matrix ~dimx:(chunkIndex + 1) ~dimy:SF.chunkSize 0. in let minVal = ref max_float in let maxVal = ref min_float in let readChunk i l () = let t = leftTick + SF.chunkSize * i in let vr = Listen.voice pVoice t l in for j = 0 to Listen.getLength vr - 1 do let v = Listen.(vr @+ j) in if v < !minVal then minVal := v; if v > !maxVal then maxVal := v; values.(i).(j) <- v; done; in for i = 0 to chunkIndex - 1 do pSsnCtrl#synchronize(readChunk i SF.chunkSize); done; pSsnCtrl#synchronize(readChunk chunkIndex lastLen); let valMargin = (!maxVal -. !minVal) *. marginRate in let bottom = !minVal -. valMargin in let top = !maxVal +. valMargin in let coef = foi height /. (bottom -. top) in mValueRuler#set_lower top; mValueRuler#set_upper bottom; let rec mkPoints i j ft x minY maxY points = let newX = iof (ft *. pixelsPerTick) in let newY = iof((values.(i).(j) -. bottom) *. coef) + height - 1 in let (minY, maxY, points) = if newX = x then ( if newY < minY then (newY, maxY, points) else if newY > maxY then (minY, newY, points) else (minY, maxY, points) ) else ( if minY = maxY then (newY, newY, (x, maxY)::points) else (newY, newY, (x, minY)::(x, maxY)::points) ) in if j > 0 then mkPoints i (j - 1) (ft -. 1.) newX minY maxY points else if i > 0 then mkPoints (i - 1) (SF.chunkSize - 1) (ft -. 1.) newX minY maxY points else points in let fLen = foi ticksCount in let mid = height / 2 in mPoints <- mkPoints chunkIndex (lastLen - 1) (fLen -. 1.) (width - 1) mid mid []; if mExposed then ( self#drawPoints mPoints width mid; ) method drawPoints points width mid = let window = mDrawingArea#misc#window in let (pixmapWidth, _) = Gdk.Drawable.get_size mPixmap in if width > pixmapWidth then ( mPixmap <- Gdk.Pixmap.create ~window ~width ~height (); Gdk.Window.set_back_pixmap window (`PIXMAP mPixmap); ); let gc = Gdk.GC.create window in Gdk.GC.set_foreground gc Style.gdkBackgroundColor; Gdk.Draw.rectangle mPixmap gc ~x:0 ~y:0 ~width ~height ~filled:true (); Gdk.GC.set_foreground gc mVoiceColor; Gdk.Draw.lines mPixmap gc points; Gdk.GC.set_foreground gc Style.gdkDelimitationColor; Gdk.Draw.line mPixmap gc ~x:0 ~y:mid ~x:(width - 1) ~y:mid; self#clear(); method drawSelectedTimeRange _ _ = if mSelectedTimeRangeStartX <> mSelectedTimeRangeEndX then ( let (x, width, color) = if mSelectedTimeRangeStartX <= mSelectedTimeRangeEndX then ( (mSelectedTimeRangeStartX, (mSelectedTimeRangeEndX - mSelectedTimeRangeStartX), Style.gdkSelectionColor) ) else ( (mSelectedTimeRangeEndX, (mSelectedTimeRangeStartX - mSelectedTimeRangeEndX), Style.gdkReverseSelectionColor) ) in let win = mDrawingArea#misc#window in let gc = Gdk.GC.create win in Gdk.GC.set_foreground gc color; Gdk.GC.set_line_attributes gc ~width:margin ~style:`SOLID ~cap:`BUTT ~join:`MITER; let alfMargin = margin / 2 in let x = x - alfMargin - 1 in let width = width + margin + 1 in let height = height - margin in Gdk.Draw.rectangle win gc ~x ~y:alfMargin ~width ~height ~filled:false (); ); let leftX = mini mSelectedTimeRangeStartX mSelectedTimeRangeEndX in let rightX = maxi mSelectedTimeRangeStartX mSelectedTimeRangeEndX in if leftX < = x + width & & rightX > = x then ( Gdk . GC.set_foreground gc Style.gdkSelectionColor ; if mSelectedTimeRangeStartX > = x & & mSelectedTimeRangeStartX < = x + width then ( Gdk.Draw.line win gc ~x:(mSelectedTimeRangeStartX - 1 ) ~y:0 ~x:(mSelectedTimeRangeStartX - 1 ) ~y : height ; Gdk.Draw.line win gc ~x:(mSelectedTimeRangeStartX + 1 ) ~y:0 ~x:(mSelectedTimeRangeStartX + 1 ) ~y : height ; ) ; if leftX < > rightX then ( if mSelectedTimeRangeEndX > = x & & mSelectedTimeRangeEndX < = x + width then ( Gdk.Draw.line win gc ~x : mSelectedTimeRangeEndX ~y:0 ~x : mSelectedTimeRangeEndX ~y : height ; ) ; let selectedTimeRangeWidth = rightX - leftX in win gc ~x : leftX ~y:0 ~width : selectedTimeRangeWidth ~height : margin ~filled : true ( ) ; win gc ~x : leftX ~y:(height - margin ) ~width : selectedTimeRangeWidth ~height : margin ~filled : true ( ) ; ) ; ) ; let leftX = mini mSelectedTimeRangeStartX mSelectedTimeRangeEndX in let rightX = maxi mSelectedTimeRangeStartX mSelectedTimeRangeEndX in if leftX <= x + width && rightX >= x then ( Gdk.GC.set_foreground gc Style.gdkSelectionColor; if mSelectedTimeRangeStartX >= x && mSelectedTimeRangeStartX <= x + width then ( Gdk.Draw.line win gc ~x:(mSelectedTimeRangeStartX - 1) ~y:0 ~x:(mSelectedTimeRangeStartX - 1) ~y:height; Gdk.Draw.line win gc ~x:(mSelectedTimeRangeStartX + 1) ~y:0 ~x:(mSelectedTimeRangeStartX + 1) ~y:height; ); if leftX <> rightX then ( if mSelectedTimeRangeEndX >= x && mSelectedTimeRangeEndX <= x + width then ( Gdk.Draw.line win gc ~x:mSelectedTimeRangeEndX ~y:0 ~x:mSelectedTimeRangeEndX ~y:height; ); let selectedTimeRangeWidth = rightX - leftX in Gdk.Draw.rectangle win gc ~x:leftX ~y:0 ~width:selectedTimeRangeWidth ~height:margin ~filled:true (); Gdk.Draw.rectangle win gc ~x:leftX ~y:(height - margin) ~width:selectedTimeRangeWidth ~height:margin ~filled:true (); ); ); *) method drawTick lastX x = let window = mDrawingArea#misc#window in let gc = Gdk.GC.create window in Gdk.Draw.pixmap window gc ~xsrc:lastX ~ysrc:0 ~xdest:lastX ~ydest:0 ~width:1 ~height mPixmap; Gdk.GC.set_foreground gc Style.gdkMarkerColor; Gdk.Draw.line window gc ~x ~y:0 ~x ~y:height; method clear() = let window = mDrawingArea#misc#window in Gdk.Window.clear window; self#drawSelectedTimeRange mSelectedTimeRangeStartX (mSelectedTimeRangeEndX - mSelectedTimeRangeStartX); method setSelectedTimeRangeX startX endX = mSelectedTimeRangeStartX <- startX; mSelectedTimeRangeEndX <- endX; (* observer methods *) method observe = function | Bus.TalkerRenamed tkrId -> if (Voice.getTalker pVoice)#getId = tkrId then mVoiceLabel#set_label(Voice.getIdentity pVoice) | _ -> () end let make voice pSsnCtrl = new c voice pSsnCtrl
null
https://raw.githubusercontent.com/gndl/graffophone/71a12fcf8e799bb8ebfc37141b300ecbc9475c43/src/gCurve.ml
ocaml
INCHES CENTIMETERS ~max_size:float observer methods
* Copyright ( C ) 2015 Ga � * * All rights reserved . This file is distributed under the terms of the * GNU General Public License version 3.0 . * * This program is distributed in the hope that it will be useful , * but WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the * GNU Lesser General Public License for more details . * * You should have received a copy of the GNU Lesser General Public License * along with this program ; if not , write to the Free Software * Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA . * Copyright (C) 2015 Ga�tan Dubreil * * All rights reserved.This file is distributed under the terms of the * GNU General Public License version 3.0. * * 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. *) open Graffophone_plugin open Usual module SF = SampleFormat module Bus = EventBus let width = 256 let curveHeight = 101 let marginRate = 5. /. 100. let margin = iof(foi curveHeight *. marginRate) let height = curveHeight + 2 * margin class c pVoice (pSsnCtrl : SessionControler.c) = object (self) val mDrawingArea = GMisc.drawing_area ~width:1 ~height () val mutable mPixmap = Gdk.Pixmap.create ~width:1 ~height ~depth:24 () val mControls = GPack.hbox () val mVoiceColor = Style.makeVoiceGdkColor pVoice val mVoiceLabel = GMisc.label ~text:(Voice.getIdentity pVoice) () val mRemoveButton = GButton.tool_button ~stock:`CLOSE ~expand:false () val mutable mLeftTick = 0 val mutable mPixelsPerTick = 0. val mutable mWidth = 0; val mutable mSelectedTimeRangeStartX = 0 val mutable mSelectedTimeRangeEndX = 0 val mutable mButtonReleaseTime = Int32.zero val mutable mPoints = [] val mutable mExposed = false initializer Bus.addObserver self#observe; let ctrlBox = GPack.vbox ~packing:mControls#add () in ctrlBox#add mVoiceLabel#coerce; let tb = GButton.toolbar ~orientation:`VERTICAL ~style:`ICONS ~tooltips:true () in tb#insert mRemoveButton; tb#set_icon_size`MENU; ctrlBox#add tb#coerce; mValueRuler#misc#set_size_request ~width:30 ~height (); mControls#pack ~expand:false mValueRuler#coerce; ignore(mDrawingArea#event#connect#expose ~callback:(fun ev -> self#expose(GdkEvent.Expose.area ev))); mDrawingArea#event#add [`BUTTON_PRESS; `BUTTON_RELEASE]; ignore(mDrawingArea#event#connect#button_release ~callback:(fun ev -> let button = GdkEvent.Button.button ev in let time = GdkEvent.Button.time ev in let x = GdkEvent.Button.x ev in let clickTick = mLeftTick + iof(x /. mPixelsPerTick) in let doubleClick = Int32.(to_int(sub time mButtonReleaseTime)) < 250 in trace("button released at "^sof x^" at "^ Int32.to_string time^" on "^Voice.getIdentity pVoice^(if doubleClick then " double click" else "")); if button = 1 then ( if doubleClick then pSsnCtrl#curve#zoomIn() else pSsnCtrl#setStartTick clickTick ) else if button = 3 then ( if doubleClick then pSsnCtrl#curve#zoomOut() else pSsnCtrl#setEndTick clickTick ); mButtonReleaseTime <- time; true) ) method getCurve = mDrawingArea#coerce method getControls = mControls#coerce method getRemoveButton = mRemoveButton method voiceIsFrom tkrId port = Voice.isFrom tkrId port pVoice method expose area = if not mExposed then ( mExposed <- true; self#drawPoints mPoints mWidth (height / 2); ); let win = mDrawingArea#misc#window in let gc = Gdk.GC.create win in let x = Gdk.Rectangle.x area in let y = Gdk.Rectangle.y area in let width = Gdk.Rectangle.width area in let height = Gdk.Rectangle.height area in Gdk.Draw.pixmap win gc ~xsrc:x ~ysrc:y ~xdest:x ~ydest:y ~width ~height mPixmap; self#drawSelectedTimeRange x width; true method draw leftTick ticksCount width pixelsPerTick = trace("leftTick "^soi leftTick^", ticksCount "^soi ticksCount^", width "^soi width^", pixelsPerTick "^sof pixelsPerTick); mLeftTick <- leftTick; mPixelsPerTick <- pixelsPerTick; mWidth <- width; let chunkIndex = ticksCount / SF.chunkSize in let lastLen = ticksCount mod SF.chunkSize in let values = A.make_matrix ~dimx:(chunkIndex + 1) ~dimy:SF.chunkSize 0. in let minVal = ref max_float in let maxVal = ref min_float in let readChunk i l () = let t = leftTick + SF.chunkSize * i in let vr = Listen.voice pVoice t l in for j = 0 to Listen.getLength vr - 1 do let v = Listen.(vr @+ j) in if v < !minVal then minVal := v; if v > !maxVal then maxVal := v; values.(i).(j) <- v; done; in for i = 0 to chunkIndex - 1 do pSsnCtrl#synchronize(readChunk i SF.chunkSize); done; pSsnCtrl#synchronize(readChunk chunkIndex lastLen); let valMargin = (!maxVal -. !minVal) *. marginRate in let bottom = !minVal -. valMargin in let top = !maxVal +. valMargin in let coef = foi height /. (bottom -. top) in mValueRuler#set_lower top; mValueRuler#set_upper bottom; let rec mkPoints i j ft x minY maxY points = let newX = iof (ft *. pixelsPerTick) in let newY = iof((values.(i).(j) -. bottom) *. coef) + height - 1 in let (minY, maxY, points) = if newX = x then ( if newY < minY then (newY, maxY, points) else if newY > maxY then (minY, newY, points) else (minY, maxY, points) ) else ( if minY = maxY then (newY, newY, (x, maxY)::points) else (newY, newY, (x, minY)::(x, maxY)::points) ) in if j > 0 then mkPoints i (j - 1) (ft -. 1.) newX minY maxY points else if i > 0 then mkPoints (i - 1) (SF.chunkSize - 1) (ft -. 1.) newX minY maxY points else points in let fLen = foi ticksCount in let mid = height / 2 in mPoints <- mkPoints chunkIndex (lastLen - 1) (fLen -. 1.) (width - 1) mid mid []; if mExposed then ( self#drawPoints mPoints width mid; ) method drawPoints points width mid = let window = mDrawingArea#misc#window in let (pixmapWidth, _) = Gdk.Drawable.get_size mPixmap in if width > pixmapWidth then ( mPixmap <- Gdk.Pixmap.create ~window ~width ~height (); Gdk.Window.set_back_pixmap window (`PIXMAP mPixmap); ); let gc = Gdk.GC.create window in Gdk.GC.set_foreground gc Style.gdkBackgroundColor; Gdk.Draw.rectangle mPixmap gc ~x:0 ~y:0 ~width ~height ~filled:true (); Gdk.GC.set_foreground gc mVoiceColor; Gdk.Draw.lines mPixmap gc points; Gdk.GC.set_foreground gc Style.gdkDelimitationColor; Gdk.Draw.line mPixmap gc ~x:0 ~y:mid ~x:(width - 1) ~y:mid; self#clear(); method drawSelectedTimeRange _ _ = if mSelectedTimeRangeStartX <> mSelectedTimeRangeEndX then ( let (x, width, color) = if mSelectedTimeRangeStartX <= mSelectedTimeRangeEndX then ( (mSelectedTimeRangeStartX, (mSelectedTimeRangeEndX - mSelectedTimeRangeStartX), Style.gdkSelectionColor) ) else ( (mSelectedTimeRangeEndX, (mSelectedTimeRangeStartX - mSelectedTimeRangeEndX), Style.gdkReverseSelectionColor) ) in let win = mDrawingArea#misc#window in let gc = Gdk.GC.create win in Gdk.GC.set_foreground gc color; Gdk.GC.set_line_attributes gc ~width:margin ~style:`SOLID ~cap:`BUTT ~join:`MITER; let alfMargin = margin / 2 in let x = x - alfMargin - 1 in let width = width + margin + 1 in let height = height - margin in Gdk.Draw.rectangle win gc ~x ~y:alfMargin ~width ~height ~filled:false (); ); let leftX = mini mSelectedTimeRangeStartX mSelectedTimeRangeEndX in let rightX = maxi mSelectedTimeRangeStartX mSelectedTimeRangeEndX in if leftX < = x + width & & rightX > = x then ( Gdk . GC.set_foreground gc Style.gdkSelectionColor ; if mSelectedTimeRangeStartX > = x & & mSelectedTimeRangeStartX < = x + width then ( Gdk.Draw.line win gc ~x:(mSelectedTimeRangeStartX - 1 ) ~y:0 ~x:(mSelectedTimeRangeStartX - 1 ) ~y : height ; Gdk.Draw.line win gc ~x:(mSelectedTimeRangeStartX + 1 ) ~y:0 ~x:(mSelectedTimeRangeStartX + 1 ) ~y : height ; ) ; if leftX < > rightX then ( if mSelectedTimeRangeEndX > = x & & mSelectedTimeRangeEndX < = x + width then ( Gdk.Draw.line win gc ~x : mSelectedTimeRangeEndX ~y:0 ~x : mSelectedTimeRangeEndX ~y : height ; ) ; let selectedTimeRangeWidth = rightX - leftX in win gc ~x : leftX ~y:0 ~width : selectedTimeRangeWidth ~height : margin ~filled : true ( ) ; win gc ~x : leftX ~y:(height - margin ) ~width : selectedTimeRangeWidth ~height : margin ~filled : true ( ) ; ) ; ) ; let leftX = mini mSelectedTimeRangeStartX mSelectedTimeRangeEndX in let rightX = maxi mSelectedTimeRangeStartX mSelectedTimeRangeEndX in if leftX <= x + width && rightX >= x then ( Gdk.GC.set_foreground gc Style.gdkSelectionColor; if mSelectedTimeRangeStartX >= x && mSelectedTimeRangeStartX <= x + width then ( Gdk.Draw.line win gc ~x:(mSelectedTimeRangeStartX - 1) ~y:0 ~x:(mSelectedTimeRangeStartX - 1) ~y:height; Gdk.Draw.line win gc ~x:(mSelectedTimeRangeStartX + 1) ~y:0 ~x:(mSelectedTimeRangeStartX + 1) ~y:height; ); if leftX <> rightX then ( if mSelectedTimeRangeEndX >= x && mSelectedTimeRangeEndX <= x + width then ( Gdk.Draw.line win gc ~x:mSelectedTimeRangeEndX ~y:0 ~x:mSelectedTimeRangeEndX ~y:height; ); let selectedTimeRangeWidth = rightX - leftX in Gdk.Draw.rectangle win gc ~x:leftX ~y:0 ~width:selectedTimeRangeWidth ~height:margin ~filled:true (); Gdk.Draw.rectangle win gc ~x:leftX ~y:(height - margin) ~width:selectedTimeRangeWidth ~height:margin ~filled:true (); ); ); *) method drawTick lastX x = let window = mDrawingArea#misc#window in let gc = Gdk.GC.create window in Gdk.Draw.pixmap window gc ~xsrc:lastX ~ysrc:0 ~xdest:lastX ~ydest:0 ~width:1 ~height mPixmap; Gdk.GC.set_foreground gc Style.gdkMarkerColor; Gdk.Draw.line window gc ~x ~y:0 ~x ~y:height; method clear() = let window = mDrawingArea#misc#window in Gdk.Window.clear window; self#drawSelectedTimeRange mSelectedTimeRangeStartX (mSelectedTimeRangeEndX - mSelectedTimeRangeStartX); method setSelectedTimeRangeX startX endX = mSelectedTimeRangeStartX <- startX; mSelectedTimeRangeEndX <- endX; method observe = function | Bus.TalkerRenamed tkrId -> if (Voice.getTalker pVoice)#getId = tkrId then mVoiceLabel#set_label(Voice.getIdentity pVoice) | _ -> () end let make voice pSsnCtrl = new c voice pSsnCtrl
bbcff9faa18bfbdf39c253ff28deed8ff7262d3cc2fc5838553987e1c8215508
skynet-gh/skylobby
spads.clj
(ns skylobby.spads (:require [clojure.string :as string])) (set! *warn-on-reflection* true) (def spads-message-types [ [:vote-progress #"Vote in progress: \"(.*)\" \[y:(.*)/(.*), n:(\d+)/([^,]+)(.*)\] \((.*) remaining\)"] [:greeting #"Hi (.*)! Current battle type is (.*)\."] [:called-vote #"\* (.*) called a vote for command \"(.*)\" \[!vote y, !vote n, !vote b\]"] [:allowed-vote #"User\(s\) allowed to vote: (.*)"] [:vote-passed #"Vote for command \"(.*)\" passed(.*)\."] [:vote-failed #"Vote for command \"(.*)\" failed(.*)\."] [:awaiting-votes #"Awaiting following vote\(s\): (.*)"] [:ringing #"Ringing (.*)"] [:balance #"Balancing according to current balance mode: (.*) \((.*)balance deviation: (.*)%\)"] [:add-spec #"Adding user (.*) as spectator"] [:already-added #"Player \"(.*)\" has already been added (.*)"] [:away-vote #"Away vote mode for (.*)"] [:unable-to-start-game #"Unable to start game, (.*)"] [:game-time #"A game is in progress since (.*)\."] [:promoting #"Promoting battle (.*)"] [:unable-to-ring #" Unable to ring (.*) \(ring spam protection, please wait (.*)\)"] [:flood-protection #"\* (.*), please wait (.*) before calling another vote \(vote flood protection\)\."] [:already-voted #"\* (.*), you have already voted for current vote\."] [:allowed-to-vote #"(.*) users allowed to vote."] [:not-allowed-vote #"\* (.*), you are not allowed to vote for current vote."] [:not-allowed-value #"Value \"(.*)\" for (.*) setting \"(.*)\" is not allowed in current preset"] [:no-vote #"\* (.*), you cannot vote currently, there is no vote in progress."] [:already-a-vote #"(.*), there is already a vote in progress, please wait for it to finish before calling another one\."] [:not-valid-setting #"\"(.*)\" is not a valid battle setting for current mod and map \(use \"!list bSettings\" to list available battle settings\)"] [:not-allowed #"\* (.*), you are not allowed to call command \"(.*)\" in current context\."] [:invalid #"Invalid command \"(.*)\""] [:already-set #"\* Global setting \"(.*)\" is already set to value \"(.*)\""] [:force-spec #"Forcing spectator mode for (.*) \[(.*)\] \((.*)\)"] [:vote-cancelled #"Vote cancelled by (.*)"] [:bar-manager #"BarManager\|(.*)"] [:mute #"In-game mute added for (.*) by (.*) \((.*)\)"] [:cancelling-vote #"\* Cancelling \"(.*)\" vote \((.*)\)"] [:game-starting-cancel #"Game starting, cancelling \"(.*)\" vote"] [:stopped #"Server stopped \((.*)\)"] [:award #" (.*) award:\s+(.*)\s+\((.*)\)(.*)"] [:ally-team-won #"Ally team (.*) won! \((.*)\)"] [:won #"(.*) won!"] [:vote-cancelled-game-launch #"Vote cancelled, launching game\.\.\."] [:game-launch #"Launching game\.\.\."] [:force-start #"Forcing game start by (.*)"] [:random-map #"Automatic random map rotation: next map is \"(.*)\""] [:auto-forcing #"Auto-forcing game start \(only already in-game or unsynced spectators are missing\)"] [:map-changed #"Map changed by (.*): (.*)"] [:no-one-to-ring #"There is no one to ring"]]) (def message-types (sort (map first spads-message-types))) (defn parse-spads-message [text] (some (fn [[k re]] (when-let [parsed (re-find re text)] {:text text :spads-parsed parsed :spads-message-type k})) spads-message-types)) (defn parse-command-message [text] (when text (let [trimmed (string/trim text)] (when (string/starts-with? trimmed "!") (let [command (subs trimmed 1) vote (cond (= command "y") :y (= command "n") :n (= command "b") :b (re-find #"vote\s+y" command) :y (re-find #"vote\s+n" command) :n (re-find #"vote\s+b" command) :b (re-find #"^cv" command) :cv (re-find #"^callvote" command) :cv :else nil)] {:command command :vote vote}))))) (defn parse-relay-message [text] (when text (let [trimmed (string/trim text)] (when (string/starts-with? trimmed "<") (let [[_all username] (re-find #"<([^\s]+)>" trimmed)] {:on-behalf-of username})))))
null
https://raw.githubusercontent.com/skynet-gh/skylobby/f5f5df8ab24dd324c488e8de1e41a04154c6a661/graal/clj/skylobby/spads.clj
clojure
(ns skylobby.spads (:require [clojure.string :as string])) (set! *warn-on-reflection* true) (def spads-message-types [ [:vote-progress #"Vote in progress: \"(.*)\" \[y:(.*)/(.*), n:(\d+)/([^,]+)(.*)\] \((.*) remaining\)"] [:greeting #"Hi (.*)! Current battle type is (.*)\."] [:called-vote #"\* (.*) called a vote for command \"(.*)\" \[!vote y, !vote n, !vote b\]"] [:allowed-vote #"User\(s\) allowed to vote: (.*)"] [:vote-passed #"Vote for command \"(.*)\" passed(.*)\."] [:vote-failed #"Vote for command \"(.*)\" failed(.*)\."] [:awaiting-votes #"Awaiting following vote\(s\): (.*)"] [:ringing #"Ringing (.*)"] [:balance #"Balancing according to current balance mode: (.*) \((.*)balance deviation: (.*)%\)"] [:add-spec #"Adding user (.*) as spectator"] [:already-added #"Player \"(.*)\" has already been added (.*)"] [:away-vote #"Away vote mode for (.*)"] [:unable-to-start-game #"Unable to start game, (.*)"] [:game-time #"A game is in progress since (.*)\."] [:promoting #"Promoting battle (.*)"] [:unable-to-ring #" Unable to ring (.*) \(ring spam protection, please wait (.*)\)"] [:flood-protection #"\* (.*), please wait (.*) before calling another vote \(vote flood protection\)\."] [:already-voted #"\* (.*), you have already voted for current vote\."] [:allowed-to-vote #"(.*) users allowed to vote."] [:not-allowed-vote #"\* (.*), you are not allowed to vote for current vote."] [:not-allowed-value #"Value \"(.*)\" for (.*) setting \"(.*)\" is not allowed in current preset"] [:no-vote #"\* (.*), you cannot vote currently, there is no vote in progress."] [:already-a-vote #"(.*), there is already a vote in progress, please wait for it to finish before calling another one\."] [:not-valid-setting #"\"(.*)\" is not a valid battle setting for current mod and map \(use \"!list bSettings\" to list available battle settings\)"] [:not-allowed #"\* (.*), you are not allowed to call command \"(.*)\" in current context\."] [:invalid #"Invalid command \"(.*)\""] [:already-set #"\* Global setting \"(.*)\" is already set to value \"(.*)\""] [:force-spec #"Forcing spectator mode for (.*) \[(.*)\] \((.*)\)"] [:vote-cancelled #"Vote cancelled by (.*)"] [:bar-manager #"BarManager\|(.*)"] [:mute #"In-game mute added for (.*) by (.*) \((.*)\)"] [:cancelling-vote #"\* Cancelling \"(.*)\" vote \((.*)\)"] [:game-starting-cancel #"Game starting, cancelling \"(.*)\" vote"] [:stopped #"Server stopped \((.*)\)"] [:award #" (.*) award:\s+(.*)\s+\((.*)\)(.*)"] [:ally-team-won #"Ally team (.*) won! \((.*)\)"] [:won #"(.*) won!"] [:vote-cancelled-game-launch #"Vote cancelled, launching game\.\.\."] [:game-launch #"Launching game\.\.\."] [:force-start #"Forcing game start by (.*)"] [:random-map #"Automatic random map rotation: next map is \"(.*)\""] [:auto-forcing #"Auto-forcing game start \(only already in-game or unsynced spectators are missing\)"] [:map-changed #"Map changed by (.*): (.*)"] [:no-one-to-ring #"There is no one to ring"]]) (def message-types (sort (map first spads-message-types))) (defn parse-spads-message [text] (some (fn [[k re]] (when-let [parsed (re-find re text)] {:text text :spads-parsed parsed :spads-message-type k})) spads-message-types)) (defn parse-command-message [text] (when text (let [trimmed (string/trim text)] (when (string/starts-with? trimmed "!") (let [command (subs trimmed 1) vote (cond (= command "y") :y (= command "n") :n (= command "b") :b (re-find #"vote\s+y" command) :y (re-find #"vote\s+n" command) :n (re-find #"vote\s+b" command) :b (re-find #"^cv" command) :cv (re-find #"^callvote" command) :cv :else nil)] {:command command :vote vote}))))) (defn parse-relay-message [text] (when text (let [trimmed (string/trim text)] (when (string/starts-with? trimmed "<") (let [[_all username] (re-find #"<([^\s]+)>" trimmed)] {:on-behalf-of username})))))
66e90e79253301d578c553de3380c8f3651bc6580fef3ae5619f1d046d91d43f
Decentralized-Pictures/T4L3NT
gas_monad.mli
(*****************************************************************************) (* *) (* Open Source License *) Copyright ( c ) 2021 Nomadic Labs < > (* *) (* Permission is hereby granted, free of charge, to any person obtaining a *) (* copy of this software and associated documentation files (the "Software"),*) to deal in the Software without restriction , including without limitation (* the rights to use, copy, modify, merge, publish, distribute, sublicense, *) and/or sell copies of the Software , and to permit persons to whom the (* Software is furnished to do so, subject to the following conditions: *) (* *) (* The above copyright notice and this permission notice shall be included *) (* in all copies or substantial portions of the Software. *) (* *) THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR (* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *) (* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *) (* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*) LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING (* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *) (* DEALINGS IN THE SOFTWARE. *) (* *) (*****************************************************************************) open Alpha_context * This monad combines : - a state monad where the state is the context - two levels of error monad to distinguish gas exhaustion from other errors It is useful for backtracking on type checking errors without backtracking the consumed gas . - a state monad where the state is the context - two levels of error monad to distinguish gas exhaustion from other errors It is useful for backtracking on type checking errors without backtracking the consumed gas. *) type ('a, 'trace) t * of [ ( ' a , ' trace ) t ] to avoid confusion when the module is open type ('a, 'trace) gas_monad = ('a, 'trace) t (** monadic return operator of the gas monad *) val return : 'a -> ('a, 'trace) t (** Binding operator for the gas monad *) val ( >>$ ) : ('a, 'trace) t -> ('a -> ('b, 'trace) t) -> ('b, 'trace) t (** Mapping operator for the gas monad, [m >|$ f] is equivalent to [m >>$ fun x -> return (f x)] *) val ( >|$ ) : ('a, 'trace) t -> ('a -> 'b) -> ('b, 'trace) t (** Variant of [( >>$ )] to bind uncarbonated functions *) val ( >?$ ) : ('a, 'trace) t -> ('a -> ('b, 'trace) result) -> ('b, 'trace) t (** Another variant of [( >>$ )] that lets recover from inner errors *) val ( >??$ ) : ('a, 'trace) t -> (('a, 'trace) result -> ('b, 'trace) t) -> ('b, 'trace) t * gas - free embedding of tzresult values . [ x ] is equivalent to [ return ( ) > ? $ fun ( ) - > x ] val of_result : ('a, 'trace) result -> ('a, 'trace) t (** A wrapper around Gas.consume. If that fails, the whole computation within the Gas_monad returns an error. See the Alpha_context.Gas module for details.*) val consume_gas : Gas.cost -> (unit, 'trace) t (** Escaping the gas monad *) val run : context -> ('a, 'trace) t -> (('a, 'trace) result * context) tzresult (** re-export of [Error_monad.record_trace_eval]. This function has no effect in the case of a gas-exhaustion error. *) val record_trace_eval : (unit -> 'err) -> ('a, 'err trace) t -> ('a, 'err trace) t
null
https://raw.githubusercontent.com/Decentralized-Pictures/T4L3NT/6d4d3edb2d73575384282ad5a633518cba3d29e3/src/proto_012_Psithaca/lib_protocol/gas_monad.mli
ocaml
*************************************************************************** Open Source License Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), the rights to use, copy, modify, merge, publish, distribute, sublicense, Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *************************************************************************** * monadic return operator of the gas monad * Binding operator for the gas monad * Mapping operator for the gas monad, [m >|$ f] is equivalent to [m >>$ fun x -> return (f x)] * Variant of [( >>$ )] to bind uncarbonated functions * Another variant of [( >>$ )] that lets recover from inner errors * A wrapper around Gas.consume. If that fails, the whole computation within the Gas_monad returns an error. See the Alpha_context.Gas module for details. * Escaping the gas monad * re-export of [Error_monad.record_trace_eval]. This function has no effect in the case of a gas-exhaustion error.
Copyright ( c ) 2021 Nomadic Labs < > to deal in the Software without restriction , including without limitation and/or sell copies of the Software , and to permit persons to whom the THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING open Alpha_context * This monad combines : - a state monad where the state is the context - two levels of error monad to distinguish gas exhaustion from other errors It is useful for backtracking on type checking errors without backtracking the consumed gas . - a state monad where the state is the context - two levels of error monad to distinguish gas exhaustion from other errors It is useful for backtracking on type checking errors without backtracking the consumed gas. *) type ('a, 'trace) t * of [ ( ' a , ' trace ) t ] to avoid confusion when the module is open type ('a, 'trace) gas_monad = ('a, 'trace) t val return : 'a -> ('a, 'trace) t val ( >>$ ) : ('a, 'trace) t -> ('a -> ('b, 'trace) t) -> ('b, 'trace) t val ( >|$ ) : ('a, 'trace) t -> ('a -> 'b) -> ('b, 'trace) t val ( >?$ ) : ('a, 'trace) t -> ('a -> ('b, 'trace) result) -> ('b, 'trace) t val ( >??$ ) : ('a, 'trace) t -> (('a, 'trace) result -> ('b, 'trace) t) -> ('b, 'trace) t * gas - free embedding of tzresult values . [ x ] is equivalent to [ return ( ) > ? $ fun ( ) - > x ] val of_result : ('a, 'trace) result -> ('a, 'trace) t val consume_gas : Gas.cost -> (unit, 'trace) t val run : context -> ('a, 'trace) t -> (('a, 'trace) result * context) tzresult val record_trace_eval : (unit -> 'err) -> ('a, 'err trace) t -> ('a, 'err trace) t
b224696d18bdfbb2be117eb84f79212fba0500409fb32d31121eaf9fdcfb4223
helium/helium-packet-router
hpr_test_packet_router_service.erl
-module(hpr_test_packet_router_service). -behaviour(helium_packet_router_packet_bhvr). -export([ init/2, route/2, handle_info/2 ]). -spec init(atom(), StreamState :: grpcbox_stream:t()) -> grpcbox_stream:t(). init(RPC, StreamState) -> ct : print("TEST : initializing stream for ~p : ~p " , [ RPC , StreamState ] ) , F = application:get_env(hpr, packet_service_init_fun, fun(_, _) -> StreamState end), F(RPC, StreamState). -spec route(hpr_envelope_up:envelope(), grpcbox_stream:t()) -> {ok, grpcbox_stream:t()} | grpcbox_stream:grpc_error_response(). route(Env, StreamState) -> %% ct:print("TEST: route: ~p", [Env]), F = application:get_env(hpr, packet_service_route_fun, fun(_, _) -> StreamState end), F(Env, StreamState). -spec handle_info(Msg :: any(), StreamState :: grpcbox_stream:t()) -> grpcbox_stream:t(). handle_info(Msg, StreamState) -> %% ct:print("TEST: handle_info: ~p", [Msg]), F = application:get_env(hpr, packet_service_handle_info_fun, fun(_, _) -> StreamState end), F(Msg, StreamState).
null
https://raw.githubusercontent.com/helium/helium-packet-router/d6458e1a7e6460d4e95ad3a08b3c67030702f360/test/hpr_test_packet_router_service.erl
erlang
ct:print("TEST: route: ~p", [Env]), ct:print("TEST: handle_info: ~p", [Msg]),
-module(hpr_test_packet_router_service). -behaviour(helium_packet_router_packet_bhvr). -export([ init/2, route/2, handle_info/2 ]). -spec init(atom(), StreamState :: grpcbox_stream:t()) -> grpcbox_stream:t(). init(RPC, StreamState) -> ct : print("TEST : initializing stream for ~p : ~p " , [ RPC , StreamState ] ) , F = application:get_env(hpr, packet_service_init_fun, fun(_, _) -> StreamState end), F(RPC, StreamState). -spec route(hpr_envelope_up:envelope(), grpcbox_stream:t()) -> {ok, grpcbox_stream:t()} | grpcbox_stream:grpc_error_response(). route(Env, StreamState) -> F = application:get_env(hpr, packet_service_route_fun, fun(_, _) -> StreamState end), F(Env, StreamState). -spec handle_info(Msg :: any(), StreamState :: grpcbox_stream:t()) -> grpcbox_stream:t(). handle_info(Msg, StreamState) -> F = application:get_env(hpr, packet_service_handle_info_fun, fun(_, _) -> StreamState end), F(Msg, StreamState).
8242618cb656a0a47f36719a0165422e0375cab543ccaea832f5f4712d96a807
mirage/xentropyd
s.ml
* Copyright ( c ) 2014 Citrix Systems Inc * * Permission to use , copy , modify , and 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 . * Copyright (c) 2014 Citrix Systems Inc * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. *) module type CONSOLE = sig include V1_LWT.CONSOLE with type 'a io = 'a Lwt.t with type id = string end
null
https://raw.githubusercontent.com/mirage/xentropyd/4705bb2f6c10ae84f842a5c39cd8a513ea8c761a/console/s.ml
ocaml
* Copyright ( c ) 2014 Citrix Systems Inc * * Permission to use , copy , modify , and 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 . * Copyright (c) 2014 Citrix Systems Inc * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. *) module type CONSOLE = sig include V1_LWT.CONSOLE with type 'a io = 'a Lwt.t with type id = string end
7b6e685434a50d2f397485cd251b897d96f460bbe0fbf210c03e2f148ff38d10
manuel-serrano/bigloo
crc16.scm
;*=====================================================================*/ * serrano / prgm / project / bigloo / runtime / Unsafe / crc16.scm * / ;* ------------------------------------------------------------- */ * Author : * / * Creation : Mon Nov 26 09:34:19 2007 * / * Last change : Tue Apr 17 07:52:39 2012 ( serrano ) * / * Copyright : 2007 - 12 * / ;* ------------------------------------------------------------- */ ;* CRC16 encoding */ ;* ------------------------------------------------------------- */ ;* crc16 is equivalent to (crc 'ibm-16 :init #xFFFF ...) */ ;*=====================================================================*/ ;*---------------------------------------------------------------------*/ ;* The module */ ;*---------------------------------------------------------------------*/ (module __crc16 (use __type __bigloo __tvector __bexit __object __thread __rgc __bit __bignum __r4_numbers_6_5 __r4_numbers_6_5_fixnum __r4_numbers_6_5_flonum __r4_booleans_6_1 __r4_symbols_6_4 __r4_vectors_6_8 __r4_control_features_6_9 __r4_pairs_and_lists_6_3 __r4_characters_6_6 __r4_equivalence_6_2 __r4_strings_6_7 __r4_ports_6_10_1 __r4_input_6_10_2 __r5_control_features_6_4 __mmap __foreign __error __evenv __os __srfi4 __base64) (import __param) (export (crc16::int ::obj) (crc16-mmap::int ::mmap) (crc16-string::int ::bstring) (crc16-port::int ::input-port) (crc16-file::int ::bstring))) ;*---------------------------------------------------------------------*/ ;* crc16-polynomial ... */ ;*---------------------------------------------------------------------*/ (define (crc16-polynomial::long) #x8005) ;*---------------------------------------------------------------------*/ ;* crc16 ... */ ;*---------------------------------------------------------------------*/ (define (crc16 obj) (cond ((mmap? obj) (crc16-mmap obj)) ((string? obj) (crc16-string obj)) ((input-port? obj) (crc16-port obj)) (else (error 'crc16 "Illegal argument" obj)))) ;*---------------------------------------------------------------------*/ ;* crc-value ... */ ;*---------------------------------------------------------------------*/ (define (crc-value::long val::long crc::long) (let loop ((i 0) (value::long (bit-lsh val 8)) (crc::long crc)) (if (=fx i 8) crc (let ((value::long (bit-lsh value 1)) (crc::long (bit-lsh crc 1))) (loop (+fx i 1) value (if (=fx 0 (bit-and #x10000 (bit-xor crc value))) crc (bit-xor crc (crc16-polynomial)))))))) ;*---------------------------------------------------------------------*/ ;* crc16-mmap ... */ ;*---------------------------------------------------------------------*/ (define (crc16-mmap mmap) (let ((len (mmap-length mmap))) (let loop ((i 0) (crc::long #xffff)) (if (=fx i len) (bit-and crc #xffff) (loop (+fx i 1) (crc-value (char->integer ($mmap-ref mmap i)) crc)))))) ;*---------------------------------------------------------------------*/ ;* crc16-string ... */ ;*---------------------------------------------------------------------*/ (define (crc16-string string) (let ((len (string-length string))) (let loop ((i 0) (crc::long #xffff)) (if (=fx i len) (bit-and crc #xffff) (loop (+fx i 1) (crc-value (char->integer (string-ref string i)) crc)))))) ;*---------------------------------------------------------------------*/ ;* crc16-port ... */ ;*---------------------------------------------------------------------*/ (define (crc16-port port) (let loop ((crc::long #xffff)) (let ((byte::long (read-byte port))) (if (eof-object? byte) (bit-and crc #xffff) (loop (crc-value byte crc)))))) ;*---------------------------------------------------------------------*/ ;* crc16-file ... */ ;*---------------------------------------------------------------------*/ (define (crc16-file file) (with-input-from-file file (lambda () (crc16-port (current-input-port)))))
null
https://raw.githubusercontent.com/manuel-serrano/bigloo/eb650ed4429155f795a32465e009706bbf1b8d74/runtime/Unsafe/crc16.scm
scheme
*=====================================================================*/ * ------------------------------------------------------------- */ * ------------------------------------------------------------- */ * CRC16 encoding */ * ------------------------------------------------------------- */ * crc16 is equivalent to (crc 'ibm-16 :init #xFFFF ...) */ *=====================================================================*/ *---------------------------------------------------------------------*/ * The module */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * crc16-polynomial ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * crc16 ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * crc-value ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * crc16-mmap ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * crc16-string ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * crc16-port ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * crc16-file ... */ *---------------------------------------------------------------------*/
* serrano / prgm / project / bigloo / runtime / Unsafe / crc16.scm * / * Author : * / * Creation : Mon Nov 26 09:34:19 2007 * / * Last change : Tue Apr 17 07:52:39 2012 ( serrano ) * / * Copyright : 2007 - 12 * / (module __crc16 (use __type __bigloo __tvector __bexit __object __thread __rgc __bit __bignum __r4_numbers_6_5 __r4_numbers_6_5_fixnum __r4_numbers_6_5_flonum __r4_booleans_6_1 __r4_symbols_6_4 __r4_vectors_6_8 __r4_control_features_6_9 __r4_pairs_and_lists_6_3 __r4_characters_6_6 __r4_equivalence_6_2 __r4_strings_6_7 __r4_ports_6_10_1 __r4_input_6_10_2 __r5_control_features_6_4 __mmap __foreign __error __evenv __os __srfi4 __base64) (import __param) (export (crc16::int ::obj) (crc16-mmap::int ::mmap) (crc16-string::int ::bstring) (crc16-port::int ::input-port) (crc16-file::int ::bstring))) (define (crc16-polynomial::long) #x8005) (define (crc16 obj) (cond ((mmap? obj) (crc16-mmap obj)) ((string? obj) (crc16-string obj)) ((input-port? obj) (crc16-port obj)) (else (error 'crc16 "Illegal argument" obj)))) (define (crc-value::long val::long crc::long) (let loop ((i 0) (value::long (bit-lsh val 8)) (crc::long crc)) (if (=fx i 8) crc (let ((value::long (bit-lsh value 1)) (crc::long (bit-lsh crc 1))) (loop (+fx i 1) value (if (=fx 0 (bit-and #x10000 (bit-xor crc value))) crc (bit-xor crc (crc16-polynomial)))))))) (define (crc16-mmap mmap) (let ((len (mmap-length mmap))) (let loop ((i 0) (crc::long #xffff)) (if (=fx i len) (bit-and crc #xffff) (loop (+fx i 1) (crc-value (char->integer ($mmap-ref mmap i)) crc)))))) (define (crc16-string string) (let ((len (string-length string))) (let loop ((i 0) (crc::long #xffff)) (if (=fx i len) (bit-and crc #xffff) (loop (+fx i 1) (crc-value (char->integer (string-ref string i)) crc)))))) (define (crc16-port port) (let loop ((crc::long #xffff)) (let ((byte::long (read-byte port))) (if (eof-object? byte) (bit-and crc #xffff) (loop (crc-value byte crc)))))) (define (crc16-file file) (with-input-from-file file (lambda () (crc16-port (current-input-port)))))
9fde5c81b84efbe51e61aab76abb64c1af4bf8b5e8960450876b036e74bbe5de
fp-works/2019-winter-Haskell-school
LogAnalysis.hs
# OPTIONS_GHC -Wall # # LANGUAGE ViewPatterns # module LogAnalysis where import Log import Text.Read (readMaybe) Exercise 1 -- parseMessage : : String - > LogMessage -- parseMessage logStr = -- case words logStr of -- ("I":ts:rest) -> case ts : : Maybe Int of -- Just i -> LogMessage Info i (unwords rest) -- _ -> Unknown logStr -- ("W":ts:rest) -> case ts : : Maybe Int of -- Just i -> LogMessage Warning i (unwords rest) -- _ -> Unknown logStr -- ("E":lv:ts:rest) -> case ( lv : : Maybe Int , readMaybe ts : : Maybe Int ) of ( Just i , Just j ) - > LogMessage ( Error i ) j ( unwords rest ) -- _ -> Unknown logStr -- _ -> Unknown logStr -- Use ViewPatterns -- parseMessage :: String -> LogMessage parseMessage (words -> "I":(readMaybe -> Just ts):msg) = LogMessage Info ts (unwords msg) parseMessage (words -> "W":(readMaybe -> Just ts):msg) = LogMessage Warning ts (unwords msg) parseMessage (words -> "E":(readMaybe -> Just lvl):(readMaybe -> Just ts):msg) = LogMessage (Error lvl) ts (unwords msg) parseMessage logStr = Unknown logStr parse :: String -> [LogMessage] parse = fmap parseMessage . lines Exercise 2 -- constrcutTreeByTs :: Ord a => a -> a -> LogMessage -> LogMessage -> MessageTree -> MessageTree -> MessageTree constrcutTreeByTs ts1 ts2 log1 log2 left right | ts1 > ts2 = Node left log2 (insert log1 right) | ts1 < ts2 = Node (insert log1 left) log2 right | otherwise = Node left log2 right insert :: LogMessage -> MessageTree -> MessageTree insert log1 Leaf = Node Leaf log1 Leaf insert log1@(LogMessage _ ts1 _) (Node left log2@(LogMessage _ ts2 _) right) = constrcutTreeByTs ts1 ts2 log1 log2 left right insert _ msgTree = msgTree Exercise 3 -- build :: [LogMessage] -> MessageTree build = foldr insert Leaf Exercise 4 -- inOrder :: MessageTree -> [LogMessage] inOrder (Node left log2 right) = inOrder left ++ [log2] ++ inOrder right inOrder _ = [] Exercise 5 -- getErrorLvlOver50 :: LogMessage -> Bool getErrorLvlOver50 (LogMessage (Error lvl) _ _) = lvl > 50 getErrorLvlOver50 _ = False getErrorDescription :: LogMessage -> String getErrorDescription (LogMessage (Error _) _ description) = description getErrorDescription _ = "" whatWentWrong :: [LogMessage] -> [String] whatWentWrong = map getErrorDescription . filter getErrorLvlOver50 . inOrder . build
null
https://raw.githubusercontent.com/fp-works/2019-winter-Haskell-school/823b67f019b9e7bc0d3be36711c0cc7da4eba7d2/cis194/week2/tien/homework2/src/LogAnalysis.hs
haskell
parseMessage logStr = case words logStr of ("I":ts:rest) -> Just i -> LogMessage Info i (unwords rest) _ -> Unknown logStr ("W":ts:rest) -> Just i -> LogMessage Warning i (unwords rest) _ -> Unknown logStr ("E":lv:ts:rest) -> _ -> Unknown logStr _ -> Unknown logStr Use ViewPatterns --
# OPTIONS_GHC -Wall # # LANGUAGE ViewPatterns # module LogAnalysis where import Log import Text.Read (readMaybe) parseMessage : : String - > LogMessage case ts : : Maybe Int of case ts : : Maybe Int of case ( lv : : Maybe Int , readMaybe ts : : Maybe Int ) of ( Just i , Just j ) - > LogMessage ( Error i ) j ( unwords rest ) parseMessage :: String -> LogMessage parseMessage (words -> "I":(readMaybe -> Just ts):msg) = LogMessage Info ts (unwords msg) parseMessage (words -> "W":(readMaybe -> Just ts):msg) = LogMessage Warning ts (unwords msg) parseMessage (words -> "E":(readMaybe -> Just lvl):(readMaybe -> Just ts):msg) = LogMessage (Error lvl) ts (unwords msg) parseMessage logStr = Unknown logStr parse :: String -> [LogMessage] parse = fmap parseMessage . lines constrcutTreeByTs :: Ord a => a -> a -> LogMessage -> LogMessage -> MessageTree -> MessageTree -> MessageTree constrcutTreeByTs ts1 ts2 log1 log2 left right | ts1 > ts2 = Node left log2 (insert log1 right) | ts1 < ts2 = Node (insert log1 left) log2 right | otherwise = Node left log2 right insert :: LogMessage -> MessageTree -> MessageTree insert log1 Leaf = Node Leaf log1 Leaf insert log1@(LogMessage _ ts1 _) (Node left log2@(LogMessage _ ts2 _) right) = constrcutTreeByTs ts1 ts2 log1 log2 left right insert _ msgTree = msgTree build :: [LogMessage] -> MessageTree build = foldr insert Leaf inOrder :: MessageTree -> [LogMessage] inOrder (Node left log2 right) = inOrder left ++ [log2] ++ inOrder right inOrder _ = [] getErrorLvlOver50 :: LogMessage -> Bool getErrorLvlOver50 (LogMessage (Error lvl) _ _) = lvl > 50 getErrorLvlOver50 _ = False getErrorDescription :: LogMessage -> String getErrorDescription (LogMessage (Error _) _ description) = description getErrorDescription _ = "" whatWentWrong :: [LogMessage] -> [String] whatWentWrong = map getErrorDescription . filter getErrorLvlOver50 . inOrder . build
70fd352780f7804aa8224c44e7a238e8f842c20b0344ad22744225c2545f5976
hoelzl/Snark
constraint-purify.lisp
;;; -*- Mode: Lisp; Syntax: Common-Lisp; Package: snark -*- ;;; File: constraint-purify.lisp The contents of this file are subject to the Mozilla Public License ;;; Version 1.1 (the "License"); you may not use this file except in ;;; compliance with the License. You may obtain a copy of the License at ;;; / ;;; Software distributed under the License is distributed on an " AS IS " ;;; basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the ;;; License for the specific language governing rights and limitations ;;; under the License. ;;; The Original Code is SNARK . The Initial Developer of the Original Code is SRI International . Portions created by the Initial Developer are Copyright ( C ) 1981 - 2011 . All Rights Reserved . ;;; Contributor(s ): < > . (in-package :snark) (defun constraint-purify-wff (wff) (let ((ucp (use-constraint-purification?))) if ucp = 1 , add equality constraints to wff instead of constraint - alist if ucp = 2 , add all constraints to wff instead of constraint - alist (let ((vars (nontheory-variables wff)) (constraint-alist-additions nil) (cache nil)) (labels ((constraint-purify-atom (atom polarity) (dereference atom nil :if-constant atom :if-variable (not-wff-error atom) :if-compound-cons (not-wff-error atom) :if-compound-appl (let* ((head (heada atom)) (args (argsa atom)) (theory2 (function-constraint-theory head)) (args* (constraint-purify-terms args theory2)) (atom* (if (eq args args*) atom (make-compound* head args*)))) (if (null theory2) atom* (ecase polarity (:pos (add-constraint atom* theory2) false) (:neg (add-constraint (negate atom*) theory2) true)))))) (constraint-purify-term (term theory1) (let ((theory2 nil) (dont-abstract nil)) (dereference term nil :if-variable (setf dont-abstract (not (member term vars))) :if-constant (setf dont-abstract (constant-constructor term)) :if-compound (let* ((head (head term)) (args (args term)) (args* (constraint-purify-terms args (if (setf dont-abstract (function-constructor head)) theory1 ;constructor symbols are transparent wrt theory (setf theory2 (function-constraint-theory head)))))) (unless (eq args args*) (setf term (make-compound* head args*))))) (cond ((or dont-abstract (eq theory1 theory2)) term) (theory1 (variable-for term (or theory2 'equality))) (t (variable-for (variable-for term (or theory2 'equality)) 'equality))))) (constraint-purify-terms (terms theory) (lcons (constraint-purify-term (first terms) theory) (constraint-purify-terms (rest terms) theory) terms)) (add-constraint (lit theory) (setf constraint-alist-additions (disjoin-alist1 theory lit constraint-alist-additions))) (variable-for (term theory) ;; create a variable to use in place of term and store ($$eq var term) in theory constraint (or (cdr (assoc term cache :test #'equal-p)) (let ((eq (input-relation-symbol (intern (to-string :$$eq_ theory) :snark) 2)) (var (make-variable (term-sort term)))) (add-constraint (make-compound *not* (make-compound eq var term)) theory) (setf cache (acons term var cache)) var)))) (let ((wff* (map-atoms-in-wff-and-compose-result #'constraint-purify-atom wff))) (if constraint-alist-additions (values (disjoin* (cons wff* (mapcan #'(lambda (p) (if (or (eql 2 ucp) (and (eql 1 ucp) (eq 'equality (car p)))) (list (cdr p)) nil)) constraint-alist-additions))) (mapcan #'(lambda (p) (if (or (eql 2 ucp) (and (eql 1 ucp) (eq 'equality (car p)))) nil (list p))) constraint-alist-additions)) wff)))))) (defun constraint-purified-p (x &optional subst) (let ((variable-theory-alist nil)) (labels ((cpp (x theory1) (dereference x subst :if-variable (let ((p (assoc x variable-theory-alist))) (cond ((null p) (unless (eq none theory1) (setf variable-theory-alist (acons x theory1 variable-theory-alist))) t) (t (or (eq none theory1) (eq theory1 (cdr p)))))) :if-constant (or (eq none theory1) (null theory1) (constant-constructor x)) :if-compound (let* ((head (head x)) (theory2 (cond ((function-logical-symbol-p head) none) ((function-constructor head) theory1) ;constructor symbols are transparent wrt theory ((eq 'equality (function-constraint-theory head)) none) (t (function-constraint-theory head))))) (and (or (eq none theory1) (eq theory1 theory2)) (dolist (arg (args x) t) (unless (cpp arg theory2) (return nil)))))))) (cpp x none)))) (defun constraint-purified-row-p (row) ;; ignore answer and ordering-constraint (constraint-purified-p (cons (row-wff row) (remove-if #'(lambda (x) (eq (car x) 'ordering)) (row-constraints row))))) (defun variable-occurs-purely-p (var x &optional subst atom) (let ((theory none)) (labels ((vop (x th) (dereference x subst :if-variable (when (eq var x) (unless (eq theory th) (if (eq none theory) (setf theory th) (return-from variable-occurs-purely-p nil)))) :if-compound-cons (progn (vop (carc x) th) (vop (cdrc x) th)) :if-compound-appl (unless (eq atom x) ;ignore atom being resolved away (let ((th (if (function-constructor (heada x)) th (function-constraint-theory (heada x))))) (dolist (arg (args x)) (vop arg th))))))) (vop x nil)) t)) (defun variable-occurs-purely-in-row-p (var row &optional atom) (variable-occurs-purely-p var (list* (row-wff row) (row-answer row) (remove-if #'(lambda (x) (eq (car x) 'ordering)) (row-constraints row))) nil atom)) constraint-purify.lisp EOF
null
https://raw.githubusercontent.com/hoelzl/Snark/06f86a31f476b2e4c28519765ab1e1519a4cc932/src/constraint-purify.lisp
lisp
-*- Mode: Lisp; Syntax: Common-Lisp; Package: snark -*- File: constraint-purify.lisp Version 1.1 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at / basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. constructor symbols are transparent wrt theory create a variable to use in place of term and store ($$eq var term) in theory constraint constructor symbols are transparent wrt theory ignore answer and ordering-constraint ignore atom being resolved away
The contents of this file are subject to the Mozilla Public License Software distributed under the License is distributed on an " AS IS " The Original Code is SNARK . The Initial Developer of the Original Code is SRI International . Portions created by the Initial Developer are Copyright ( C ) 1981 - 2011 . All Rights Reserved . Contributor(s ): < > . (in-package :snark) (defun constraint-purify-wff (wff) (let ((ucp (use-constraint-purification?))) if ucp = 1 , add equality constraints to wff instead of constraint - alist if ucp = 2 , add all constraints to wff instead of constraint - alist (let ((vars (nontheory-variables wff)) (constraint-alist-additions nil) (cache nil)) (labels ((constraint-purify-atom (atom polarity) (dereference atom nil :if-constant atom :if-variable (not-wff-error atom) :if-compound-cons (not-wff-error atom) :if-compound-appl (let* ((head (heada atom)) (args (argsa atom)) (theory2 (function-constraint-theory head)) (args* (constraint-purify-terms args theory2)) (atom* (if (eq args args*) atom (make-compound* head args*)))) (if (null theory2) atom* (ecase polarity (:pos (add-constraint atom* theory2) false) (:neg (add-constraint (negate atom*) theory2) true)))))) (constraint-purify-term (term theory1) (let ((theory2 nil) (dont-abstract nil)) (dereference term nil :if-variable (setf dont-abstract (not (member term vars))) :if-constant (setf dont-abstract (constant-constructor term)) :if-compound (let* ((head (head term)) (args (args term)) (args* (constraint-purify-terms args (if (setf dont-abstract (function-constructor head)) (setf theory2 (function-constraint-theory head)))))) (unless (eq args args*) (setf term (make-compound* head args*))))) (cond ((or dont-abstract (eq theory1 theory2)) term) (theory1 (variable-for term (or theory2 'equality))) (t (variable-for (variable-for term (or theory2 'equality)) 'equality))))) (constraint-purify-terms (terms theory) (lcons (constraint-purify-term (first terms) theory) (constraint-purify-terms (rest terms) theory) terms)) (add-constraint (lit theory) (setf constraint-alist-additions (disjoin-alist1 theory lit constraint-alist-additions))) (variable-for (term theory) (or (cdr (assoc term cache :test #'equal-p)) (let ((eq (input-relation-symbol (intern (to-string :$$eq_ theory) :snark) 2)) (var (make-variable (term-sort term)))) (add-constraint (make-compound *not* (make-compound eq var term)) theory) (setf cache (acons term var cache)) var)))) (let ((wff* (map-atoms-in-wff-and-compose-result #'constraint-purify-atom wff))) (if constraint-alist-additions (values (disjoin* (cons wff* (mapcan #'(lambda (p) (if (or (eql 2 ucp) (and (eql 1 ucp) (eq 'equality (car p)))) (list (cdr p)) nil)) constraint-alist-additions))) (mapcan #'(lambda (p) (if (or (eql 2 ucp) (and (eql 1 ucp) (eq 'equality (car p)))) nil (list p))) constraint-alist-additions)) wff)))))) (defun constraint-purified-p (x &optional subst) (let ((variable-theory-alist nil)) (labels ((cpp (x theory1) (dereference x subst :if-variable (let ((p (assoc x variable-theory-alist))) (cond ((null p) (unless (eq none theory1) (setf variable-theory-alist (acons x theory1 variable-theory-alist))) t) (t (or (eq none theory1) (eq theory1 (cdr p)))))) :if-constant (or (eq none theory1) (null theory1) (constant-constructor x)) :if-compound (let* ((head (head x)) (theory2 (cond ((function-logical-symbol-p head) none) ((function-constructor head) ((eq 'equality (function-constraint-theory head)) none) (t (function-constraint-theory head))))) (and (or (eq none theory1) (eq theory1 theory2)) (dolist (arg (args x) t) (unless (cpp arg theory2) (return nil)))))))) (cpp x none)))) (defun constraint-purified-row-p (row) (constraint-purified-p (cons (row-wff row) (remove-if #'(lambda (x) (eq (car x) 'ordering)) (row-constraints row))))) (defun variable-occurs-purely-p (var x &optional subst atom) (let ((theory none)) (labels ((vop (x th) (dereference x subst :if-variable (when (eq var x) (unless (eq theory th) (if (eq none theory) (setf theory th) (return-from variable-occurs-purely-p nil)))) :if-compound-cons (progn (vop (carc x) th) (vop (cdrc x) th)) (let ((th (if (function-constructor (heada x)) th (function-constraint-theory (heada x))))) (dolist (arg (args x)) (vop arg th))))))) (vop x nil)) t)) (defun variable-occurs-purely-in-row-p (var row &optional atom) (variable-occurs-purely-p var (list* (row-wff row) (row-answer row) (remove-if #'(lambda (x) (eq (car x) 'ordering)) (row-constraints row))) nil atom)) constraint-purify.lisp EOF
dd65b184347a708d46fec4a99ef8763d6a6a1827c5b5bdda3641de9fe91c9ea1
utkarshkukreti/reaml
HelloWorld.ml
module R = Reaml let main = R.h1 [ R.id "hello" ] [ R.string "Hello, world!" ] let () = main |> R.renderTo "main"
null
https://raw.githubusercontent.com/utkarshkukreti/reaml/5640a36293ba2a765171225deddb644f4d6c5d26/examples/HelloWorld.ml
ocaml
module R = Reaml let main = R.h1 [ R.id "hello" ] [ R.string "Hello, world!" ] let () = main |> R.renderTo "main"
3ced4125127b91d33e58d985eb833bd3df70a5c1dc1d353090371fa0da76f214
emotiq/emotiq
deps.lisp
(ql-dist:install-dist "-01-31/distinfo.txt" :replace t :prompt nil) (ql-dist:install-dist "-east-1.amazonaws.com/emotiq-quickdist/emotiq.txt" :replace t :prompt nil) (setf (ql-dist:preference (ql-dist:dist "emotiq")) (1+ (ql-dist:preference (ql-dist:dist "quicklisp")))) (ql:quickload :ironclad) (ql:quickload :cl-ppcre) (ql:quickload :optima) (ql:quickload :trivia) (ql:quickload :cffi) (ql:quickload :s-base64) (ql:quickload :key-value-store) (ql:quickload :ccl-metering) (ql:quickload :illogical-pathnames)
null
https://raw.githubusercontent.com/emotiq/emotiq/9af78023f670777895a3dac29a2bbe98e19b6249/ci/deps.lisp
lisp
(ql-dist:install-dist "-01-31/distinfo.txt" :replace t :prompt nil) (ql-dist:install-dist "-east-1.amazonaws.com/emotiq-quickdist/emotiq.txt" :replace t :prompt nil) (setf (ql-dist:preference (ql-dist:dist "emotiq")) (1+ (ql-dist:preference (ql-dist:dist "quicklisp")))) (ql:quickload :ironclad) (ql:quickload :cl-ppcre) (ql:quickload :optima) (ql:quickload :trivia) (ql:quickload :cffi) (ql:quickload :s-base64) (ql:quickload :key-value-store) (ql:quickload :ccl-metering) (ql:quickload :illogical-pathnames)
8c058f35a5668f16c0a6f9653d9a18801015e17cd4e4370d55a42a6713fcc3f6
geoffder/olm-ml
account_test.ml
open! Core open! Olm open! Helpers.ResultInfix let%test "creation" = Account.create () |> Result.is_ok let%test "pickle" = begin Account.create () >>= fun chad -> Account.identity_keys chad >>= fun keys -> Account.pickle chad >>= Account.from_pickle >>= Account.identity_keys >>| fun unpickled_keys -> Account.IdentityKeys.equal keys unpickled_keys end |> function | Ok true -> true | _ -> false let%test "invalid pickle" = match Account.from_pickle "" with | Error (`ValueError _) -> true | _ -> false let%test "passphrase pickle" = let pass = "password" in begin Account.create () >>= fun chad -> Account.identity_keys chad >>= fun keys -> Account.pickle chad ~pass >>= Account.from_pickle ~pass >>= Account.identity_keys >>| fun unpickled_keys -> Account.IdentityKeys.equal keys unpickled_keys end |> function | Ok true -> true | _ -> false let%test "wrong passphrase pickle" = begin Account.create () >>= Account.pickle ~pass:"foo" >>= Account.from_pickle ~pass:"bar" end |> function | Error `BadAccountKey -> true | _ -> false let%test "get identity keys" = begin Account.create () >>= Account.identity_keys end |> Result.is_ok let%test "generate one-time keys" = begin Account.create () >>= fun bob -> Account.generate_one_time_keys bob 2 >>= fun _ -> Account.one_time_keys bob >>| fun keys -> Map.length keys.curve25519 end |> function | Ok num_keys when num_keys = 2 -> true | _ -> false let%test "max one-time keys" = begin Account.create () >>= Account.max_one_time_keys end |> function | Ok n when n > 0 -> true | _ -> false let%test "valid signature" = let message = "It was me, Dio!" in let utility = Utility.create () in begin Account.create () >>= fun dio -> Account.sign dio message >>= fun signature -> Account.identity_keys dio >>= fun keys -> Utility.ed25519_verify utility keys.ed25519 message signature end |> Result.is_ok let%test "invalid signature" = let message = "It was me, Dio!" in let utility = Utility.create () in begin Account.create () >>= fun dio -> Account.create () >>= fun jojo -> Account.sign jojo message >>= fun signature -> Account.identity_keys dio >>= fun keys -> Utility.ed25519_verify utility keys.ed25519 message signature end |> function | Error `BadMessageMac -> true | _ -> false let%test "signature verification twice" = let message = "It was me, Dio!" in let utility = Utility.create () in begin Account.create () >>= fun dio -> Account.sign dio message >>= fun signature -> Account.identity_keys dio >>= fun keys -> let repeat_sign () = Account.sign dio message |> function | Ok s when String.equal s signature -> Result.return () | _ -> Result.fail `SignatureMismatch in Utility.ed25519_verify utility keys.ed25519 message signature >>= fun _ -> repeat_sign () >>= fun _ -> Utility.ed25519_verify utility keys.ed25519 message signature >>= fun _ -> repeat_sign () end |> Result.is_ok
null
https://raw.githubusercontent.com/geoffder/olm-ml/6ab791c5f4cacb54cf8939d78bd2a6820ec136b3/olm/test/account_test.ml
ocaml
open! Core open! Olm open! Helpers.ResultInfix let%test "creation" = Account.create () |> Result.is_ok let%test "pickle" = begin Account.create () >>= fun chad -> Account.identity_keys chad >>= fun keys -> Account.pickle chad >>= Account.from_pickle >>= Account.identity_keys >>| fun unpickled_keys -> Account.IdentityKeys.equal keys unpickled_keys end |> function | Ok true -> true | _ -> false let%test "invalid pickle" = match Account.from_pickle "" with | Error (`ValueError _) -> true | _ -> false let%test "passphrase pickle" = let pass = "password" in begin Account.create () >>= fun chad -> Account.identity_keys chad >>= fun keys -> Account.pickle chad ~pass >>= Account.from_pickle ~pass >>= Account.identity_keys >>| fun unpickled_keys -> Account.IdentityKeys.equal keys unpickled_keys end |> function | Ok true -> true | _ -> false let%test "wrong passphrase pickle" = begin Account.create () >>= Account.pickle ~pass:"foo" >>= Account.from_pickle ~pass:"bar" end |> function | Error `BadAccountKey -> true | _ -> false let%test "get identity keys" = begin Account.create () >>= Account.identity_keys end |> Result.is_ok let%test "generate one-time keys" = begin Account.create () >>= fun bob -> Account.generate_one_time_keys bob 2 >>= fun _ -> Account.one_time_keys bob >>| fun keys -> Map.length keys.curve25519 end |> function | Ok num_keys when num_keys = 2 -> true | _ -> false let%test "max one-time keys" = begin Account.create () >>= Account.max_one_time_keys end |> function | Ok n when n > 0 -> true | _ -> false let%test "valid signature" = let message = "It was me, Dio!" in let utility = Utility.create () in begin Account.create () >>= fun dio -> Account.sign dio message >>= fun signature -> Account.identity_keys dio >>= fun keys -> Utility.ed25519_verify utility keys.ed25519 message signature end |> Result.is_ok let%test "invalid signature" = let message = "It was me, Dio!" in let utility = Utility.create () in begin Account.create () >>= fun dio -> Account.create () >>= fun jojo -> Account.sign jojo message >>= fun signature -> Account.identity_keys dio >>= fun keys -> Utility.ed25519_verify utility keys.ed25519 message signature end |> function | Error `BadMessageMac -> true | _ -> false let%test "signature verification twice" = let message = "It was me, Dio!" in let utility = Utility.create () in begin Account.create () >>= fun dio -> Account.sign dio message >>= fun signature -> Account.identity_keys dio >>= fun keys -> let repeat_sign () = Account.sign dio message |> function | Ok s when String.equal s signature -> Result.return () | _ -> Result.fail `SignatureMismatch in Utility.ed25519_verify utility keys.ed25519 message signature >>= fun _ -> repeat_sign () >>= fun _ -> Utility.ed25519_verify utility keys.ed25519 message signature >>= fun _ -> repeat_sign () end |> Result.is_ok
a7b87f349bd91865603c45a1226be5882a5f84657a4d6e7bc2afec897b597d87
blindglobe/clocc
gimage.lisp
-*- Mode : Common - Lisp ; Package : PICTURES ; -*- ;;; ;;; ;;; TEXAS INSTRUMENTS INCORPORATED P.O. BOX 149149 AUSTIN , TEXAS 78714 - 9149 ;;; Copyright ( C)1987,1988,1989,1990 Texas Instruments Incorporated . ;;; ;;; Permission is granted to any individual or institution to use, copy, modify, ;;; and distribute this software, provided that this complete copyright and ;;; permission notice is maintained, intact, in all copies and supporting ;;; documentation. ;;; Texas Instruments Incorporated provides this software " as is " without ;;; express or implied warranty. ;;; Authors : , , Contributors : , , (in-package "PICTURES") (EXPORT '( graphic-image-content make-graphic-image graphic-image-base-x graphic-image-base-y graphic-image-gravity graphic-image-tile-p ) 'pictures) (DEFMACRO compute-base-origin-if-not-set (base-x base-y) `(UNLESS (AND ,base-x ,base-y) (MULTIPLE-VALUE-BIND (x y) (compute-base-origin graphic-image view) (SETF ,base-x x) (SETF ,base-y y)))) (defclass graphic-image (extent-cache graphic) ((image-content :type (OR null :bitmap :xy-pixmap :z-pixmap) :initarg :image-content :initform nil :accessor graphic-image-content :documentation "the numeric values for the graphic-image") (graphic-image-base-x :type (OR wcoord null) :initarg :base-x :initform nil :accessor graphic-image-base-x :documentation "object x-coordinate of base point for the image") (graphic-image-base-y :type (OR wcoord null) :initarg :base-y :initform nil :accessor graphic-image-base-y :documentation "object y-coordinate of base point for the image") (graphic-image-extent-x :type (OR wcoord null) :initarg :extent-x :initform nil :accessor graphic-image-extent-x :documentation "object x-coordinate of the user defined extent for the image") (graphic-image-extent-y :type (OR wcoord null) :initarg :extent-y :initform nil :accessor graphic-image-extent-y :documentation "object y-coordinate of the user defined extent for the image") (graphic-image-extent-width :type (OR wcoord null) :initarg :extent-width :initform nil :accessor graphic-image-extent-width :documentation "object width of the user defined extent for the image") (graphic-image-extent-height :type (OR wcoord null) :initarg :extent-height :initform nil :accessor graphic-image-extent-height :documentation "object height of the user defined extent for the image") (graphic-image-gravity :type symbol :accessor graphic-image-gravity :initarg :gravity :initform :southwest :documentation "the gravity of the graphic-image within a frame") (graphic-image-tile-p :type boolean :accessor graphic-image-tile-p :initarg :tile-p :initform nil :documentation "a flag to signal if the graphic image is to tile when drawn") (graphic-image-scale :type number :accessor graphic-image-scale :initform 1 :documentation "the scale factor at which the image was formed") ) (:documentation "The graphic class for drawing a graphic-image in object coordinates")) (DEFUN make-graphic-image (image &key tile-p base-x base-y extent-x extent-y extent-width extent-height (gravity :southwest) gstate transform parent (sensitivity :editable) plist) (FUNCALL #'MAKE-INSTANCE 'graphic-image :allow-other-keys t :base-x base-x :base-y base-y :image-content image :extent-x extent-x :extent-y extent-y :extent-width extent-width :extent-height extent-height :gravity gravity :gstate gstate :parent parent :transform transform :sensitivity sensitivity :tile-p tile-p :plist plist )) (DEFMETHOD initialize-instance :after ((graphic-image graphic-image) &key extent-x extent-y ) (with-slots (gstate graphic-image-base-x graphic-image-base-y views extent extent-valid-p) graphic-image (SETF (gstate-fill-style graphic-image) :tiled) (UNLESS (OR (AND graphic-image-base-x graphic-image-base-y) (AND extent-x extent-y)) (SETF graphic-image-base-x 0) (SETF graphic-image-base-y 0)) )) (DEFMETHOD (SETF graphic-image-base-x) :before (x (graphic-image graphic-image) ) (with-slots (extent graphic-image-extent-x graphic-image-base-x) graphic-image (WHEN graphic-image-extent-x (SETF graphic-image-extent-x (+ graphic-image-extent-x (- x graphic-image-base-x))))) (extent-changed graphic-image)) (DEFMETHOD (SETF graphic-image-base-y) :before ( y (graphic-image graphic-image)) (with-slots (extent graphic-image-extent-y graphic-image-base-y) graphic-image (WHEN graphic-image-extent-y (SETF graphic-image-extent-y (+ graphic-image-extent-y (- y graphic-image-base-y))))) (extent-changed graphic-image)) (DEFMETHOD (SETF graphic-image-extent-x) :before (x (graphic-image graphic-image)) (DECLARE (IGNORE x)) (extent-changed graphic-image) (with-slots (transform graphic-image-base-x) graphic-image (SETF transform nil) (SETF graphic-image-base-x nil))) (DEFMETHOD (SETF graphic-image-extent-y) :before (y (graphic-image graphic-image)) (DECLARE (IGNORE y)) (extent-changed graphic-image) (with-slots (transform graphic-image-base-y) graphic-image (SETF transform nil) (SETF graphic-image-base-y nil))) (DEFMETHOD (SETF graphic-image-gravity) :after (gravity (graphic-image graphic-image)) (DECLARE (IGNORE gravity)) (with-slots ( graphic-image-base-x graphic-image-base-y ) graphic-image (SETF graphic-image-base-x nil) (SETF graphic-image-base-y nil))) (DEFMETHOD extent-compute ((graphic-image graphic-image)) (LET ((scale-x (view-scale-x (graphic-view graphic-image))) (scale-y (view-scale-y (graphic-view graphic-image)))) (with-slots (extent graphic-image-base-x graphic-image-base-y graphic-image-extent-x graphic-image-extent-y graphic-image-extent-width graphic-image-extent-height image-content transform) graphic-image (IF (AND graphic-image-extent-x graphic-image-extent-y graphic-image-extent-width graphic-image-extent-height) (MULTIPLE-VALUE-BIND (x-min y-min)(transform-point transform graphic-image-extent-x graphic-image-extent-y) (MULTIPLE-VALUE-BIND (x-max y-max) (transform-point transform (+ x-min graphic-image-extent-width) (+ y-min graphic-image-extent-height)) (with-coercion ((x-min y-min x-max y-max) extent-element) (make-extent-rect :xmin x-min :ymin y-min :xmax x-max :ymax y-max :valid t)))) (MULTIPLE-VALUE-BIND (x-min y-min) (transform-point transform graphic-image-base-x graphic-image-base-y) (let ((xmax (+ x-min (/ (image-width image-content) scale-x))) (ymax (+ y-min (/ (image-height image-content) scale-y)))) (with-coercion ((x-min y-min xmax ymax) extent-element) (make-extent-rect :xmin x-min :ymin y-min :xmax xmax :ymax ymax :valid t)))))))) (DEFMACRO get-tile-x (x) ` (transform-x view ,x)) (DEFMACRO get-tile-y (y) `(transform-y view ,y)) (DEFMETHOD draw-graphic ((graphic-image graphic-image) (view view) &optional min-x min-y width height) (DECLARE (type (OR null wcoord) min-x min-y width height)) (with-slots (gstate extent graphic-image-scale transform graphic-image-base-x graphic-image-base-y image-content (tile-p graphic-image-tile-p)) graphic-image (WHEN (visible-p graphic-image) (compute-base-origin-if-not-set graphic-image-base-x graphic-image-base-y) (LET ((world-extent (extent-transform (graphic-world-transform graphic-image) extent)) (scale-x (view-scale-x view)) (scale-y (view-scale-y view))) (WHEN (NOT (= (view-scale view) graphic-image-scale)) (SETF graphic-image-scale (view-scale view)) (extent-changed graphic-image) (graphic-extent graphic-image)) (IF tile-p (PROGN (MULTIPLE-VALUE-BIND (tx ty) (compute-base-origin graphic-image view) (MULTIPLE-VALUE-SETQ (tx ty) (transform-point (graphic-world-transform graphic-image) tx ty)) (SETF (gstate-value gstate :ts-x) (get-tile-x tx)) (SETF (gstate-value gstate :ts-y) (get-tile-y ty))) (view-draw-image view (extent-rect-xmin world-extent) (extent-rect-ymin world-extent) (extent-rect-xmax world-extent) (extent-rect-ymax world-extent) image-content gstate)) (MULTIPLE-VALUE-BIND (x y) (transform-point (graphic-world-transform graphic-image) graphic-image-base-x graphic-image-base-y) (MULTIPLE-VALUE-BIND (x-max y-max) (transform-point (graphic-world-transform graphic-image) (+ graphic-image-base-x (/ (image-width image-content) scale-x)) (+ graphic-image-base-y (/ (image-height image-content) scale-y))) (SETF (gstate-value gstate :ts-x) (get-tile-x x)) (SETF (gstate-value gstate :ts-y) (get-tile-y y)) (view-draw-image view x y x-max y-max image-content gstate)))))))) (DEFMETHOD normalize-graphic :before ((graphic-image graphic-image)) (with-slots (extent graphic-image-base-x graphic-image-base-y graphic-image-extent-x graphic-image-extent-y graphic-image-extent-width graphic-image-extent-height image-content transform) graphic-image (IF (AND graphic-image-extent-x graphic-image-extent-y graphic-image-extent-width graphic-image-extent-height) (MULTIPLE-VALUE-BIND (x-min y-min) (transform-point transform graphic-image-extent-x graphic-image-extent-y) (MULTIPLE-VALUE-BIND (x-max y-max) (transform-point transform (+ x-min graphic-image-extent-width) (+ y-min graphic-image-extent-height)) (SETF graphic-image-extent-x x-min graphic-image-extent-y y-min graphic-image-extent-width (ABS (- x-max x-min)) graphic-image-extent-height (ABS (- y-max y-min))))) (MULTIPLE-VALUE-BIND (x y) (transform-point transform graphic-image-base-x graphic-image-base-y) (SETF (graphic-image-base-x graphic-image) x (graphic-image-base-y graphic-image) y))) )) (DEFUN compute-base-origin (graphic-image view) "Return the baseline coordinate of the graphic-image" (with-slots (graphic-image-gravity transform image-content extent graphic) graphic-image (LET ((world-extent (IF (valid-extent-p extent) extent (graphic-extent graphic-image)))) (with-extent-values world-extent extent-xmin extent-ymin extent-xmax extent-ymax extent-width extent-height (LET* ( (scale-x (view-scale-x view)) (scale-y (view-scale-y view)) (width (/ (image-width image-content) scale-x)) (height (/ (image-height image-content) scale-y))) (CASE graphic-image-gravity (:southwest (VALUES extent-xmin extent-ymin )) (:northwest (VALUES extent-xmin (- extent-ymax height))) (:south (VALUES (+ (- extent-xmin (/ width 2.0)) (/ extent-width 2.0) ) extent-ymin)) (:north (VALUES (+ (- extent-xmin (/ width 2.0)) (/ extent-width 2.0) ) (- extent-ymax height))) (:west (VALUES extent-xmin (+ extent-ymin (- (/ extent-height 2.0) (/ height 2.0))))) (:center (VALUES (+ (- extent-xmin (/ width 2.0)) (/ extent-width 2.0) ) (+ extent-ymin (- (/ extent-height 2.0 ) (/ height 2.0))))) (:southeast (VALUES (- extent-xmax width) extent-ymin)) (:northeast (VALUES (- extent-xmax width) (- extent-ymax height))) (:east (VALUES (- extent-xmax width) (+ (- extent-ymin (/ height 2.0)) (/ extent-height 2.0 )))) (t (VALUES extent-xmin extent-ymin))))))))
null
https://raw.githubusercontent.com/blindglobe/clocc/a50bb75edb01039b282cf320e4505122a59c59a7/src/gui/clue/pictures/gimage.lisp
lisp
Package : PICTURES ; -*- Permission is granted to any individual or institution to use, copy, modify, and distribute this software, provided that this complete copyright and permission notice is maintained, intact, in all copies and supporting documentation. express or implied warranty.
TEXAS INSTRUMENTS INCORPORATED P.O. BOX 149149 AUSTIN , TEXAS 78714 - 9149 Copyright ( C)1987,1988,1989,1990 Texas Instruments Incorporated . Texas Instruments Incorporated provides this software " as is " without Authors : , , Contributors : , , (in-package "PICTURES") (EXPORT '( graphic-image-content make-graphic-image graphic-image-base-x graphic-image-base-y graphic-image-gravity graphic-image-tile-p ) 'pictures) (DEFMACRO compute-base-origin-if-not-set (base-x base-y) `(UNLESS (AND ,base-x ,base-y) (MULTIPLE-VALUE-BIND (x y) (compute-base-origin graphic-image view) (SETF ,base-x x) (SETF ,base-y y)))) (defclass graphic-image (extent-cache graphic) ((image-content :type (OR null :bitmap :xy-pixmap :z-pixmap) :initarg :image-content :initform nil :accessor graphic-image-content :documentation "the numeric values for the graphic-image") (graphic-image-base-x :type (OR wcoord null) :initarg :base-x :initform nil :accessor graphic-image-base-x :documentation "object x-coordinate of base point for the image") (graphic-image-base-y :type (OR wcoord null) :initarg :base-y :initform nil :accessor graphic-image-base-y :documentation "object y-coordinate of base point for the image") (graphic-image-extent-x :type (OR wcoord null) :initarg :extent-x :initform nil :accessor graphic-image-extent-x :documentation "object x-coordinate of the user defined extent for the image") (graphic-image-extent-y :type (OR wcoord null) :initarg :extent-y :initform nil :accessor graphic-image-extent-y :documentation "object y-coordinate of the user defined extent for the image") (graphic-image-extent-width :type (OR wcoord null) :initarg :extent-width :initform nil :accessor graphic-image-extent-width :documentation "object width of the user defined extent for the image") (graphic-image-extent-height :type (OR wcoord null) :initarg :extent-height :initform nil :accessor graphic-image-extent-height :documentation "object height of the user defined extent for the image") (graphic-image-gravity :type symbol :accessor graphic-image-gravity :initarg :gravity :initform :southwest :documentation "the gravity of the graphic-image within a frame") (graphic-image-tile-p :type boolean :accessor graphic-image-tile-p :initarg :tile-p :initform nil :documentation "a flag to signal if the graphic image is to tile when drawn") (graphic-image-scale :type number :accessor graphic-image-scale :initform 1 :documentation "the scale factor at which the image was formed") ) (:documentation "The graphic class for drawing a graphic-image in object coordinates")) (DEFUN make-graphic-image (image &key tile-p base-x base-y extent-x extent-y extent-width extent-height (gravity :southwest) gstate transform parent (sensitivity :editable) plist) (FUNCALL #'MAKE-INSTANCE 'graphic-image :allow-other-keys t :base-x base-x :base-y base-y :image-content image :extent-x extent-x :extent-y extent-y :extent-width extent-width :extent-height extent-height :gravity gravity :gstate gstate :parent parent :transform transform :sensitivity sensitivity :tile-p tile-p :plist plist )) (DEFMETHOD initialize-instance :after ((graphic-image graphic-image) &key extent-x extent-y ) (with-slots (gstate graphic-image-base-x graphic-image-base-y views extent extent-valid-p) graphic-image (SETF (gstate-fill-style graphic-image) :tiled) (UNLESS (OR (AND graphic-image-base-x graphic-image-base-y) (AND extent-x extent-y)) (SETF graphic-image-base-x 0) (SETF graphic-image-base-y 0)) )) (DEFMETHOD (SETF graphic-image-base-x) :before (x (graphic-image graphic-image) ) (with-slots (extent graphic-image-extent-x graphic-image-base-x) graphic-image (WHEN graphic-image-extent-x (SETF graphic-image-extent-x (+ graphic-image-extent-x (- x graphic-image-base-x))))) (extent-changed graphic-image)) (DEFMETHOD (SETF graphic-image-base-y) :before ( y (graphic-image graphic-image)) (with-slots (extent graphic-image-extent-y graphic-image-base-y) graphic-image (WHEN graphic-image-extent-y (SETF graphic-image-extent-y (+ graphic-image-extent-y (- y graphic-image-base-y))))) (extent-changed graphic-image)) (DEFMETHOD (SETF graphic-image-extent-x) :before (x (graphic-image graphic-image)) (DECLARE (IGNORE x)) (extent-changed graphic-image) (with-slots (transform graphic-image-base-x) graphic-image (SETF transform nil) (SETF graphic-image-base-x nil))) (DEFMETHOD (SETF graphic-image-extent-y) :before (y (graphic-image graphic-image)) (DECLARE (IGNORE y)) (extent-changed graphic-image) (with-slots (transform graphic-image-base-y) graphic-image (SETF transform nil) (SETF graphic-image-base-y nil))) (DEFMETHOD (SETF graphic-image-gravity) :after (gravity (graphic-image graphic-image)) (DECLARE (IGNORE gravity)) (with-slots ( graphic-image-base-x graphic-image-base-y ) graphic-image (SETF graphic-image-base-x nil) (SETF graphic-image-base-y nil))) (DEFMETHOD extent-compute ((graphic-image graphic-image)) (LET ((scale-x (view-scale-x (graphic-view graphic-image))) (scale-y (view-scale-y (graphic-view graphic-image)))) (with-slots (extent graphic-image-base-x graphic-image-base-y graphic-image-extent-x graphic-image-extent-y graphic-image-extent-width graphic-image-extent-height image-content transform) graphic-image (IF (AND graphic-image-extent-x graphic-image-extent-y graphic-image-extent-width graphic-image-extent-height) (MULTIPLE-VALUE-BIND (x-min y-min)(transform-point transform graphic-image-extent-x graphic-image-extent-y) (MULTIPLE-VALUE-BIND (x-max y-max) (transform-point transform (+ x-min graphic-image-extent-width) (+ y-min graphic-image-extent-height)) (with-coercion ((x-min y-min x-max y-max) extent-element) (make-extent-rect :xmin x-min :ymin y-min :xmax x-max :ymax y-max :valid t)))) (MULTIPLE-VALUE-BIND (x-min y-min) (transform-point transform graphic-image-base-x graphic-image-base-y) (let ((xmax (+ x-min (/ (image-width image-content) scale-x))) (ymax (+ y-min (/ (image-height image-content) scale-y)))) (with-coercion ((x-min y-min xmax ymax) extent-element) (make-extent-rect :xmin x-min :ymin y-min :xmax xmax :ymax ymax :valid t)))))))) (DEFMACRO get-tile-x (x) ` (transform-x view ,x)) (DEFMACRO get-tile-y (y) `(transform-y view ,y)) (DEFMETHOD draw-graphic ((graphic-image graphic-image) (view view) &optional min-x min-y width height) (DECLARE (type (OR null wcoord) min-x min-y width height)) (with-slots (gstate extent graphic-image-scale transform graphic-image-base-x graphic-image-base-y image-content (tile-p graphic-image-tile-p)) graphic-image (WHEN (visible-p graphic-image) (compute-base-origin-if-not-set graphic-image-base-x graphic-image-base-y) (LET ((world-extent (extent-transform (graphic-world-transform graphic-image) extent)) (scale-x (view-scale-x view)) (scale-y (view-scale-y view))) (WHEN (NOT (= (view-scale view) graphic-image-scale)) (SETF graphic-image-scale (view-scale view)) (extent-changed graphic-image) (graphic-extent graphic-image)) (IF tile-p (PROGN (MULTIPLE-VALUE-BIND (tx ty) (compute-base-origin graphic-image view) (MULTIPLE-VALUE-SETQ (tx ty) (transform-point (graphic-world-transform graphic-image) tx ty)) (SETF (gstate-value gstate :ts-x) (get-tile-x tx)) (SETF (gstate-value gstate :ts-y) (get-tile-y ty))) (view-draw-image view (extent-rect-xmin world-extent) (extent-rect-ymin world-extent) (extent-rect-xmax world-extent) (extent-rect-ymax world-extent) image-content gstate)) (MULTIPLE-VALUE-BIND (x y) (transform-point (graphic-world-transform graphic-image) graphic-image-base-x graphic-image-base-y) (MULTIPLE-VALUE-BIND (x-max y-max) (transform-point (graphic-world-transform graphic-image) (+ graphic-image-base-x (/ (image-width image-content) scale-x)) (+ graphic-image-base-y (/ (image-height image-content) scale-y))) (SETF (gstate-value gstate :ts-x) (get-tile-x x)) (SETF (gstate-value gstate :ts-y) (get-tile-y y)) (view-draw-image view x y x-max y-max image-content gstate)))))))) (DEFMETHOD normalize-graphic :before ((graphic-image graphic-image)) (with-slots (extent graphic-image-base-x graphic-image-base-y graphic-image-extent-x graphic-image-extent-y graphic-image-extent-width graphic-image-extent-height image-content transform) graphic-image (IF (AND graphic-image-extent-x graphic-image-extent-y graphic-image-extent-width graphic-image-extent-height) (MULTIPLE-VALUE-BIND (x-min y-min) (transform-point transform graphic-image-extent-x graphic-image-extent-y) (MULTIPLE-VALUE-BIND (x-max y-max) (transform-point transform (+ x-min graphic-image-extent-width) (+ y-min graphic-image-extent-height)) (SETF graphic-image-extent-x x-min graphic-image-extent-y y-min graphic-image-extent-width (ABS (- x-max x-min)) graphic-image-extent-height (ABS (- y-max y-min))))) (MULTIPLE-VALUE-BIND (x y) (transform-point transform graphic-image-base-x graphic-image-base-y) (SETF (graphic-image-base-x graphic-image) x (graphic-image-base-y graphic-image) y))) )) (DEFUN compute-base-origin (graphic-image view) "Return the baseline coordinate of the graphic-image" (with-slots (graphic-image-gravity transform image-content extent graphic) graphic-image (LET ((world-extent (IF (valid-extent-p extent) extent (graphic-extent graphic-image)))) (with-extent-values world-extent extent-xmin extent-ymin extent-xmax extent-ymax extent-width extent-height (LET* ( (scale-x (view-scale-x view)) (scale-y (view-scale-y view)) (width (/ (image-width image-content) scale-x)) (height (/ (image-height image-content) scale-y))) (CASE graphic-image-gravity (:southwest (VALUES extent-xmin extent-ymin )) (:northwest (VALUES extent-xmin (- extent-ymax height))) (:south (VALUES (+ (- extent-xmin (/ width 2.0)) (/ extent-width 2.0) ) extent-ymin)) (:north (VALUES (+ (- extent-xmin (/ width 2.0)) (/ extent-width 2.0) ) (- extent-ymax height))) (:west (VALUES extent-xmin (+ extent-ymin (- (/ extent-height 2.0) (/ height 2.0))))) (:center (VALUES (+ (- extent-xmin (/ width 2.0)) (/ extent-width 2.0) ) (+ extent-ymin (- (/ extent-height 2.0 ) (/ height 2.0))))) (:southeast (VALUES (- extent-xmax width) extent-ymin)) (:northeast (VALUES (- extent-xmax width) (- extent-ymax height))) (:east (VALUES (- extent-xmax width) (+ (- extent-ymin (/ height 2.0)) (/ extent-height 2.0 )))) (t (VALUES extent-xmin extent-ymin))))))))
143bc50b05b10770b26d0c2ee061faa51b7f96703935f900455095d8110f14e5
hyperledger-archives/fabric-chaintool
api.clj
Copyright London Stock Exchange Group 2016 All Rights Reserved . ;; Licensed under the Apache License , Version 2.0 ( the " License " ) ; ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; -2.0 ;; ;; Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an " AS IS " BASIS , ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. (ns chaintool.platforms.api) (defprotocol Platform ;; Displays environment variables relevant to the build environment (env [this params]) ;; Compiles the platform (build [this params]) Downloads any missing for the platform (deps [this params]) ;; Cleans any previous builds of the platform (clean [this params]) ;; Packages the chaincode project according to the platform (package [this params]))
null
https://raw.githubusercontent.com/hyperledger-archives/fabric-chaintool/57d8f460d0bfdc7cb4ddea0147fea16f15a06258/src/chaintool/platforms/api.clj
clojure
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. Displays environment variables relevant to the build environment Compiles the platform Cleans any previous builds of the platform Packages the chaincode project according to the platform
Copyright London Stock Exchange Group 2016 All Rights Reserved . distributed under the License is distributed on an " AS IS " BASIS , (ns chaintool.platforms.api) (defprotocol Platform (env [this params]) (build [this params]) Downloads any missing for the platform (deps [this params]) (clean [this params]) (package [this params]))
bb8602bbd094be16a1fb99473d1307b468b7c557014f37dce7152d0be8b10b8d
ndpar/erlang
echo_active.erl
% % % 1 > echo_active : start(4321 ) . % telnet localhost 4321 % -module(echo_active). -author('Alain O\'Dea'). -export([start/1]). -define(TCP_OPTIONS, [list, {packet, line}, {reuseaddr, true}, {active, true}]). start(Port) -> {ok, Listen} = gen_tcp:listen(Port, ?TCP_OPTIONS), spawn(fun() -> par_connect(Listen) end). par_connect(Listen) -> {ok, Socket} = gen_tcp:accept(Listen), spawn(fun() -> par_connect(Listen) end), io:format("Client connected~n"), echo(Socket). echo(Socket) -> receive {tcp, Socket, Line} -> gen_tcp:send(Socket, Line), echo(Socket); {tcp_closed, Socket} -> io:format("Client disconnected~n") end.
null
https://raw.githubusercontent.com/ndpar/erlang/e215841a1d370e0fc5eb6b9ff40ea7ae78fc8763/tcp/src/echo_active.erl
erlang
1 > echo_active : start(4321 ) . telnet localhost 4321 -module(echo_active). -author('Alain O\'Dea'). -export([start/1]). -define(TCP_OPTIONS, [list, {packet, line}, {reuseaddr, true}, {active, true}]). start(Port) -> {ok, Listen} = gen_tcp:listen(Port, ?TCP_OPTIONS), spawn(fun() -> par_connect(Listen) end). par_connect(Listen) -> {ok, Socket} = gen_tcp:accept(Listen), spawn(fun() -> par_connect(Listen) end), io:format("Client connected~n"), echo(Socket). echo(Socket) -> receive {tcp, Socket, Line} -> gen_tcp:send(Socket, Line), echo(Socket); {tcp_closed, Socket} -> io:format("Client disconnected~n") end.
ed7eb16c2b886ead1f8082416172caa34cefccb142c1682ebbaa48838434c819
mlabs-haskell/hydra-demo
Spec.hs
module Main (main) where import Test.Tasty qualified as Tasty import Prelude import EndToEnd.Spec (headTests) import OffChain.Test (offChainTests) import Tx.Spec qualified as Tx (tests) main :: IO () main = do spec <- headTests Tasty.defaultMain $ Tasty.testGroup "Hydra-demo" [ offChainTests , Tx.tests , spec ]
null
https://raw.githubusercontent.com/mlabs-haskell/hydra-demo/c5e5411d40556bd7ad7d6d041e29ed8d1405378f/test/Spec.hs
haskell
module Main (main) where import Test.Tasty qualified as Tasty import Prelude import EndToEnd.Spec (headTests) import OffChain.Test (offChainTests) import Tx.Spec qualified as Tx (tests) main :: IO () main = do spec <- headTests Tasty.defaultMain $ Tasty.testGroup "Hydra-demo" [ offChainTests , Tx.tests , spec ]
ebb8a091848cc1c9811494fbdec81f0868ad3fd25bfa7d262eaa0211c8cc56b5
leo-project/simplenfs
simplenfs_sup.erl
-module(simplenfs_sup). -behaviour(supervisor). %% Include -include("nfs_prot3.hrl"). -include("mount3.hrl"). %% API. -export([start_link/0]). %% supervisor. -export([init/1]). %% API. -spec start_link() -> {ok, pid()}. start_link() -> supervisor:start_link({local, ?MODULE}, ?MODULE, []). %% supervisor. init([]) -> {ok, {{one_for_one, 10, 10}, []}}.
null
https://raw.githubusercontent.com/leo-project/simplenfs/15dfecd6324b5d464ea8056b2ec8eed7463ed1e1/src/simplenfs_sup.erl
erlang
Include API. supervisor. API. supervisor.
-module(simplenfs_sup). -behaviour(supervisor). -include("nfs_prot3.hrl"). -include("mount3.hrl"). -export([start_link/0]). -export([init/1]). -spec start_link() -> {ok, pid()}. start_link() -> supervisor:start_link({local, ?MODULE}, ?MODULE, []). init([]) -> {ok, {{one_for_one, 10, 10}, []}}.
144b8aa7a1373ed7b799a892f5b473347a3305fb9ccf3ab961b41ef81674c390
flipstone/haskell-for-beginners
6_monad_laws.hs
justAddOne :: Int -> Maybe Int justAddOne x = Just (x + 1) Demonstrate the left identity law with the Maybe Monad -- leftIdMaybe :: Bool leftIdMaybe = (return 3 >>= justAddOne) == (justAddOne 3) Demonstrate the right identity law with the Maybe Monad -- rightIdMaybe :: Bool rightIdMaybe = (Just 3 >>= return) == Just 3 Demonstrate the associative law with the Maybe Monad -- associativeMaybe :: Bool associativeMaybe = ((Just 3 >>= justAddOne) >>= justAddOne) == (Just 3 >>= (\x -> justAddOne x >>= justAddOne)) Demonstrate all 3 laws for the List Monad -- addOneOrTwo :: Int -> [Int] addOneOrTwo x = [x + 1, x + 2] leftIdList, rightIdList, associativeList :: Bool leftIdList = (return 3 >>= addOneOrTwo) == (addOneOrTwo 3) rightIdList = ([3] >>= return) == [3] associativeList = ([3] >>= addOneOrTwo >>= addOneOrTwo) == ([3] >>= (\x -> addOneOrTwo 3 >>= addOneOrTwo))
null
https://raw.githubusercontent.com/flipstone/haskell-for-beginners/e586a1f3ef08f21d5181171fe7a7b27057391f0b/answers/chapter_12/6_monad_laws.hs
haskell
justAddOne :: Int -> Maybe Int justAddOne x = Just (x + 1) Demonstrate the left identity law with the Maybe Monad leftIdMaybe :: Bool leftIdMaybe = (return 3 >>= justAddOne) == (justAddOne 3) Demonstrate the right identity law with the Maybe Monad rightIdMaybe :: Bool rightIdMaybe = (Just 3 >>= return) == Just 3 Demonstrate the associative law with the Maybe Monad associativeMaybe :: Bool associativeMaybe = ((Just 3 >>= justAddOne) >>= justAddOne) == (Just 3 >>= (\x -> justAddOne x >>= justAddOne)) Demonstrate all 3 laws for the List Monad addOneOrTwo :: Int -> [Int] addOneOrTwo x = [x + 1, x + 2] leftIdList, rightIdList, associativeList :: Bool leftIdList = (return 3 >>= addOneOrTwo) == (addOneOrTwo 3) rightIdList = ([3] >>= return) == [3] associativeList = ([3] >>= addOneOrTwo >>= addOneOrTwo) == ([3] >>= (\x -> addOneOrTwo 3 >>= addOneOrTwo))
468d245bec06cc85dfbde24e7be783fee5be4e34952308ba69d240a8aeb0a53e
grin-compiler/ghc-wpc-sample-programs
MemView.hs
-- | Module : Data . . MemView -- License : BSD-style Maintainer : < > -- Stability : stable -- Portability : Good -- module Data.ByteArray.MemView ( MemView(..) , memViewPlus ) where import Foreign.Ptr import Data.ByteArray.Types import Data.Memory.Internal.Imports -- | A simple abstraction to a piece of memory. -- -- Do beware that garbage collection related to -- piece of memory could be triggered before this -- is used. -- -- Only use with the appropriate handler has been -- used (e.g. withForeignPtr on ForeignPtr) -- data MemView = MemView {-# UNPACK #-} !(Ptr Word8) {-# UNPACK #-} !Int deriving (Show,Eq) instance ByteArrayAccess MemView where length (MemView _ l) = l withByteArray (MemView p _) f = f (castPtr p) -- | Increase the memory view while reducing the size of the window -- -- this is useful as an abtraction to represent the current offset -- in a buffer, and the remaining bytes left. memViewPlus :: MemView -> Int -> MemView memViewPlus (MemView p len) n = MemView (p `plusPtr` n) (len - n)
null
https://raw.githubusercontent.com/grin-compiler/ghc-wpc-sample-programs/0e3a9b8b7cc3fa0da7c77fb7588dd4830fb087f7/memory-0.15.0/Data/ByteArray/MemView.hs
haskell
| License : BSD-style Stability : stable Portability : Good | A simple abstraction to a piece of memory. Do beware that garbage collection related to piece of memory could be triggered before this is used. Only use with the appropriate handler has been used (e.g. withForeignPtr on ForeignPtr) # UNPACK # # UNPACK # | Increase the memory view while reducing the size of the window this is useful as an abtraction to represent the current offset in a buffer, and the remaining bytes left.
Module : Data . . MemView Maintainer : < > module Data.ByteArray.MemView ( MemView(..) , memViewPlus ) where import Foreign.Ptr import Data.ByteArray.Types import Data.Memory.Internal.Imports deriving (Show,Eq) instance ByteArrayAccess MemView where length (MemView _ l) = l withByteArray (MemView p _) f = f (castPtr p) memViewPlus :: MemView -> Int -> MemView memViewPlus (MemView p len) n = MemView (p `plusPtr` n) (len - n)
57344cb7ceefdf8081cf58d707fcca2d8f81cbc4450f8b5af6953c5e32686b73
Apress/beg-haskell
ExprMonad.hs
module Chapter14.ExprMonad where import Control.Applicative import Control.Monad.Reader import Control.Monad.Writer data Expr a = AmountOf a | PriceOf a | TotalNumberProducts | TotalPrice | IVal Int | FVal Float | (Expr a) :+: (Expr a) | (Expr a) :*: (Expr a) | (Expr a) :<: (Expr a) | (Expr a) :<=: (Expr a) | (Expr a) :>: (Expr a) | (Expr a) :>=: (Expr a) | (Expr a) :&&: (Expr a) | (Expr a) :||: (Expr a) | Not (Expr a) exprExample :: Expr Char exprExample = (AmountOf 'a' :<: IVal 2) :&&: (FVal 300.0 :<: TotalPrice) productsExample :: [(Char,Float)] productsExample = [('a',15.0), ('b',400.0)] executeExpr :: Eq a => Expr a -> [(a, Float)] -> Result executeExpr e p = execWriter (runReaderT (sem e) p) newtype Result = Result (Maybe Int, Maybe Float, Maybe Bool) deriving Show instance Monoid Result where _ `mappend` r2 = r2 mempty = Result (Nothing, Nothing, Nothing) sem :: Eq a => Expr a -> ReaderT [(a,Float)] (Writer Result) () sem (AmountOf p) = do products <- ask tell $ Result (Just (length $ filter (\(d,_) -> d == p) products), Nothing, Nothing) sem (PriceOf p) = do products <- ask tell $ Result (Nothing, Just $ foldr (\(_,pr) x -> pr + x) 0.0 $ filter (\(d,_) -> d == p) products, Nothing) sem TotalNumberProducts = do products <- ask tell $ Result (Just (length products), Nothing, Nothing) sem TotalPrice = do products <- ask tell $ Result (Nothing, Just (foldr (\(_,p) x -> p + x) 0.0 products), Nothing) sem (IVal i) = tell $ Result (Just i, Nothing, Nothing) sem (FVal f) = tell $ Result (Nothing, Just f, Nothing) sem (e1 :+: e2) = do (_, Result (i1, f1, _)) <- listen (sem e1) (_, Result (i2, f2, _)) <- listen (sem e2) tell $ Result ((+) <$> i1 <*> i2, (+) <$> f1 <*> f2, Nothing) sem (e1 :*: e2) = do (_, Result (i1, f1, _)) <- listen (sem e1) (_, Result (i2, f2, _)) <- listen (sem e2) tell $ Result ((*) <$> i1 <*> i2, (*) <$> f1 <*> f2, Nothing) sem (e1 :<: e2) = do (_, Result (i1, f1, _)) <- listen (sem e1) (_, Result (i2, f2, _)) <- listen (sem e2) tell $ Result (Nothing, Nothing, ((<) <$> i1 <*> i2) <|> ((<) <$> f1 <*> f2)) sem (e1 :<=: e2) = do (_, Result (i1, f1, _)) <- listen (sem e1) (_, Result (i2, f2, _)) <- listen (sem e2) tell $ Result (Nothing, Nothing, ((<=) <$> i1 <*> i2) <|> ((<=) <$> f1 <*> f2)) sem (e1 :>: e2) = do (_, Result (i1, f1, _)) <- listen (sem e1) (_, Result (i2, f2, _)) <- listen (sem e2) tell $ Result (Nothing, Nothing, ((>) <$> i1 <*> i2) <|> ((>) <$> f1 <*> f2)) sem (e1 :>=: e2) = do (_, Result (i1, f1, _)) <- listen (sem e1) (_, Result (i2, f2, _)) <- listen (sem e2) tell $ Result (Nothing, Nothing, ((>=) <$> i1 <*> i2) <|> ((>=) <$> f1 <*> f2)) sem (e1 :&&: e2) = do (_, Result (_,_,b1)) <- listen (sem e1) (_, Result (_,_,b2)) <- listen (sem e2) tell $ Result (Nothing, Nothing, (&&) <$> b1 <*> b2) sem (e1 :||: e2) = do (_, Result (_,_,b1)) <- listen (sem e1) (_, Result (_,_,b2)) <- listen (sem e2) tell $ Result (Nothing, Nothing, (||) <$> b1 <*> b2) sem (Not e) = do (_, Result (_,_,b)) <- listen (sem e) tell $ Result (Nothing, Nothing, not <$> b)
null
https://raw.githubusercontent.com/Apress/beg-haskell/aaacbf047d553e6177c38807e662cc465409dffd/chapter14/src/Chapter14/ExprMonad.hs
haskell
module Chapter14.ExprMonad where import Control.Applicative import Control.Monad.Reader import Control.Monad.Writer data Expr a = AmountOf a | PriceOf a | TotalNumberProducts | TotalPrice | IVal Int | FVal Float | (Expr a) :+: (Expr a) | (Expr a) :*: (Expr a) | (Expr a) :<: (Expr a) | (Expr a) :<=: (Expr a) | (Expr a) :>: (Expr a) | (Expr a) :>=: (Expr a) | (Expr a) :&&: (Expr a) | (Expr a) :||: (Expr a) | Not (Expr a) exprExample :: Expr Char exprExample = (AmountOf 'a' :<: IVal 2) :&&: (FVal 300.0 :<: TotalPrice) productsExample :: [(Char,Float)] productsExample = [('a',15.0), ('b',400.0)] executeExpr :: Eq a => Expr a -> [(a, Float)] -> Result executeExpr e p = execWriter (runReaderT (sem e) p) newtype Result = Result (Maybe Int, Maybe Float, Maybe Bool) deriving Show instance Monoid Result where _ `mappend` r2 = r2 mempty = Result (Nothing, Nothing, Nothing) sem :: Eq a => Expr a -> ReaderT [(a,Float)] (Writer Result) () sem (AmountOf p) = do products <- ask tell $ Result (Just (length $ filter (\(d,_) -> d == p) products), Nothing, Nothing) sem (PriceOf p) = do products <- ask tell $ Result (Nothing, Just $ foldr (\(_,pr) x -> pr + x) 0.0 $ filter (\(d,_) -> d == p) products, Nothing) sem TotalNumberProducts = do products <- ask tell $ Result (Just (length products), Nothing, Nothing) sem TotalPrice = do products <- ask tell $ Result (Nothing, Just (foldr (\(_,p) x -> p + x) 0.0 products), Nothing) sem (IVal i) = tell $ Result (Just i, Nothing, Nothing) sem (FVal f) = tell $ Result (Nothing, Just f, Nothing) sem (e1 :+: e2) = do (_, Result (i1, f1, _)) <- listen (sem e1) (_, Result (i2, f2, _)) <- listen (sem e2) tell $ Result ((+) <$> i1 <*> i2, (+) <$> f1 <*> f2, Nothing) sem (e1 :*: e2) = do (_, Result (i1, f1, _)) <- listen (sem e1) (_, Result (i2, f2, _)) <- listen (sem e2) tell $ Result ((*) <$> i1 <*> i2, (*) <$> f1 <*> f2, Nothing) sem (e1 :<: e2) = do (_, Result (i1, f1, _)) <- listen (sem e1) (_, Result (i2, f2, _)) <- listen (sem e2) tell $ Result (Nothing, Nothing, ((<) <$> i1 <*> i2) <|> ((<) <$> f1 <*> f2)) sem (e1 :<=: e2) = do (_, Result (i1, f1, _)) <- listen (sem e1) (_, Result (i2, f2, _)) <- listen (sem e2) tell $ Result (Nothing, Nothing, ((<=) <$> i1 <*> i2) <|> ((<=) <$> f1 <*> f2)) sem (e1 :>: e2) = do (_, Result (i1, f1, _)) <- listen (sem e1) (_, Result (i2, f2, _)) <- listen (sem e2) tell $ Result (Nothing, Nothing, ((>) <$> i1 <*> i2) <|> ((>) <$> f1 <*> f2)) sem (e1 :>=: e2) = do (_, Result (i1, f1, _)) <- listen (sem e1) (_, Result (i2, f2, _)) <- listen (sem e2) tell $ Result (Nothing, Nothing, ((>=) <$> i1 <*> i2) <|> ((>=) <$> f1 <*> f2)) sem (e1 :&&: e2) = do (_, Result (_,_,b1)) <- listen (sem e1) (_, Result (_,_,b2)) <- listen (sem e2) tell $ Result (Nothing, Nothing, (&&) <$> b1 <*> b2) sem (e1 :||: e2) = do (_, Result (_,_,b1)) <- listen (sem e1) (_, Result (_,_,b2)) <- listen (sem e2) tell $ Result (Nothing, Nothing, (||) <$> b1 <*> b2) sem (Not e) = do (_, Result (_,_,b)) <- listen (sem e) tell $ Result (Nothing, Nothing, not <$> b)
dc4d898c1ccf147fc7cc62f3e224c9571d1d50b89fa05d30370b7cdd204e7154
codinuum/cca
py_lib.ml
Copyright 2012 - 2020 Codinuum Software Lab < > Licensed under the Apache License , Version 2.0 ( the " License " ) ; you may not use this file except in compliance with the License . You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing , software distributed under the License is distributed on an " AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied . See the License for the specific language governing permissions and limitations under the License . Copyright 2012-2020 Codinuum Software Lab <> 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. *) (* py_lib.ml *) include Py_lib_base module Analyzing = Analyzing.F (Label) let extract_change options tree1 tree2 uidmapping edits = [], [], [], (Xset.create 0) (* not yet *) let _ = Lang.register Spython.parser_name (new Lang.c ~make_tree_comparator:(new Analyzing.tree_comparator) ~make_tree_builder:(new tree_builder) ~extract_change:extract_change ~extract_fact:extract_fact )
null
https://raw.githubusercontent.com/codinuum/cca/88ea07f3fe3671b78518769d804fdebabcd28e90/src/ast/analyzing/langs/python/py_lib.ml
ocaml
py_lib.ml not yet
Copyright 2012 - 2020 Codinuum Software Lab < > Licensed under the Apache License , Version 2.0 ( the " License " ) ; you may not use this file except in compliance with the License . You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing , software distributed under the License is distributed on an " AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied . See the License for the specific language governing permissions and limitations under the License . Copyright 2012-2020 Codinuum Software Lab <> 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. *) include Py_lib_base module Analyzing = Analyzing.F (Label) let extract_change options tree1 tree2 uidmapping edits = let _ = Lang.register Spython.parser_name (new Lang.c ~make_tree_comparator:(new Analyzing.tree_comparator) ~make_tree_builder:(new tree_builder) ~extract_change:extract_change ~extract_fact:extract_fact )
743a6ac3bee7f4301cc6029816e2d3fd0f7936d9144d6b75a04e88fdd4e84119
satos---jp/mincaml_self_hosting
parsing.mli
Parser.toplevel Lexer.main ( ) Parser.toplevel Lexer.main (Lexing.from_channel stdin) *) type parsingact = | Shift of int | Reduce of int * int | Error val my_parsing : (int -> int) * ((int list) list) * ((int * parsingact) list) list -> (unit -> 'a) -> (('a parsing_data) -> int) -> ('a parsing_data)
null
https://raw.githubusercontent.com/satos---jp/mincaml_self_hosting/5fdf8b5083437d7607a924142eea52d9b1de0439/lib/ml/parsing.mli
ocaml
Parser.toplevel Lexer.main ( ) Parser.toplevel Lexer.main (Lexing.from_channel stdin) *) type parsingact = | Shift of int | Reduce of int * int | Error val my_parsing : (int -> int) * ((int list) list) * ((int * parsingact) list) list -> (unit -> 'a) -> (('a parsing_data) -> int) -> ('a parsing_data)
c797287cae5a88ba6afe9a77218c2f473080edc79e054402e4f9b7a72ec3b217
Leystryku/mpbomberman_racket
cl_sound.rkt
#lang racket ;; imports (require (only-in racket/gui/base play-sound)) (require ffi/unsafe) (require "sh_config.rkt") (require "sh_config_snds.rkt") ;; exports (provide (all-defined-out)) ;; [sound-fn] calls the proper sound functions for the OS using rackets foreign function interface (define (sound-fn str) (cond [(equal? soundEnabled 1) (lambda (x) (define mci-send-string (get-ffi-obj "mciSendStringA" "Winmm" (_fun _string [_pointer = #f] [_int = 0] [_pointer = #f] -> [ret : _int])) ) (mci-send-string str))(str) ] [(equal? soundEnabled 2) (lambda (x) (define mci-send-string (get-ffi-obj "mciSendStringA" "Winmm" (_fun _string [_pointer = #f] [_int = 0] [_pointer = #f] -> [ret : _int])) ) (mci-send-string str))(str) ] [else str] ) ) ;; [windows-play-sound] is a wrapper around sound-fn for playing sounds using the windows sound cmd (define (windows-play-sound snd) (if soundEnabled (sound-fn (string-append (string-append "play " snd))) (windows-stop-sound snd) ) ) ;; [windows-stop-sound] is a wrapper around sound-fn for stopping sounds using the windows sound cmd (define (windows-stop-sound snd) (sound-fn (string-append (string-append "stop " snd))) ) ;; [play-our-sound] is a wrapper around the play sound functions for the os's (define (play-our-sound snd) (cond [(equal? soundEnabled 1) (windows-play-sound snd)] [(equal? soundEnabled -1) (play-sound snd #t)] [else snd] ) ) ;; [stop-our-sound] is a wrapper around the sound stop functions for the os's (define (stop-our-sound) (cond [(equal? soundEnabled 1) (windows-stop-sound)] [else #t] ) )
null
https://raw.githubusercontent.com/Leystryku/mpbomberman_racket/059d95040cfad2e27237f8dd41fc32a4fc698afe/game/cl_sound.rkt
racket
imports exports [sound-fn] calls the proper sound functions for the OS using rackets foreign function interface [windows-play-sound] is a wrapper around sound-fn for playing sounds using the windows sound cmd [windows-stop-sound] is a wrapper around sound-fn for stopping sounds using the windows sound cmd [play-our-sound] is a wrapper around the play sound functions for the os's [stop-our-sound] is a wrapper around the sound stop functions for the os's
#lang racket (require (only-in racket/gui/base play-sound)) (require ffi/unsafe) (require "sh_config.rkt") (require "sh_config_snds.rkt") (provide (all-defined-out)) (define (sound-fn str) (cond [(equal? soundEnabled 1) (lambda (x) (define mci-send-string (get-ffi-obj "mciSendStringA" "Winmm" (_fun _string [_pointer = #f] [_int = 0] [_pointer = #f] -> [ret : _int])) ) (mci-send-string str))(str) ] [(equal? soundEnabled 2) (lambda (x) (define mci-send-string (get-ffi-obj "mciSendStringA" "Winmm" (_fun _string [_pointer = #f] [_int = 0] [_pointer = #f] -> [ret : _int])) ) (mci-send-string str))(str) ] [else str] ) ) (define (windows-play-sound snd) (if soundEnabled (sound-fn (string-append (string-append "play " snd))) (windows-stop-sound snd) ) ) (define (windows-stop-sound snd) (sound-fn (string-append (string-append "stop " snd))) ) (define (play-our-sound snd) (cond [(equal? soundEnabled 1) (windows-play-sound snd)] [(equal? soundEnabled -1) (play-sound snd #t)] [else snd] ) ) (define (stop-our-sound) (cond [(equal? soundEnabled 1) (windows-stop-sound)] [else #t] ) )
28282960ef2706f8dfdcbfc4184222e52296205424d17058df0f90d7fbd5d646
luminus-framework/examples
home.clj
(ns multi-client-ws-aleph.routes.home (:require [multi-client-ws-aleph.layout :as layout] [multi-client-ws-aleph.middleware :as middleware] [ring.util.http-response :as response] [clojure.tools.logging :as log] [aleph.http :as http] [manifold.stream :as s] [manifold.deferred :as d] [manifold.bus :as bus])) (defn home-page [request] (layout/render request "home.html")) (def events (bus/event-bus)) (defn chat-handler [req] (log/info "got a Websocket request from:" (:uri req)) (d/let-flow [conn (d/catch (http/websocket-connection req) (fn [_] nil))] (if-not conn (response/bad-request "Expected a websocket request.") (do (s/connect (bus/subscribe events "chat") conn) (s/consume #(bus/publish! events "chat" %) (s/buffer 100 conn))))) ;; return nil to Ring handler nil) (defn home-routes [] ["" {:middleware [middleware/wrap-csrf middleware/wrap-formats]} ["/" {:get home-page}] ["/ws" {:get chat-handler}]])
null
https://raw.githubusercontent.com/luminus-framework/examples/cbeee2fef8f457a6a6bac2cae0b640370ae2499b/multi-client-ws-aleph/src/clj/multi_client_ws_aleph/routes/home.clj
clojure
return nil to Ring handler
(ns multi-client-ws-aleph.routes.home (:require [multi-client-ws-aleph.layout :as layout] [multi-client-ws-aleph.middleware :as middleware] [ring.util.http-response :as response] [clojure.tools.logging :as log] [aleph.http :as http] [manifold.stream :as s] [manifold.deferred :as d] [manifold.bus :as bus])) (defn home-page [request] (layout/render request "home.html")) (def events (bus/event-bus)) (defn chat-handler [req] (log/info "got a Websocket request from:" (:uri req)) (d/let-flow [conn (d/catch (http/websocket-connection req) (fn [_] nil))] (if-not conn (response/bad-request "Expected a websocket request.") (do (s/connect (bus/subscribe events "chat") conn) (s/consume #(bus/publish! events "chat" %) (s/buffer 100 conn))))) nil) (defn home-routes [] ["" {:middleware [middleware/wrap-csrf middleware/wrap-formats]} ["/" {:get home-page}] ["/ws" {:get chat-handler}]])
9faf72ada55bfa34db6b4c4174dac3acb0f300c54b09195242966dcd7f605017
erlware/erlware_commons
ec_plists.erl
-*- mode : Erlang ; fill - column : 80 ; comment - column : 75 ; -*- %%% vi:ts=4 sw=4 et %%% The MIT License %%% Copyright ( c ) 2007 %%% %%% Permission is hereby granted, free of charge, to any person obtaining a copy %%% of this software and associated documentation files (the "Software"), to deal in the Software without restriction , including without limitation the rights %%% to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software , and to permit persons to whom the Software is %%% furnished to do so, subject to the following conditions: %%% %%% The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software . %%% THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR %%% IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, %%% FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE %%% AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING FROM , %%% OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN %%% THE SOFTWARE. %%%--------------------------------------------------------------------------- @author 2007 freeyourmind + + [ $ @|gmail.com ] %%% @doc %%% plists is a drop-in replacement for module <a %%% href="">lists</a>, making %%% most list operations parallel. It can operate on each element in %%% parallel, for IO-bound operations, on sublists in parallel, for %%% taking advantage of multi-core machines with CPU-bound operations, and across erlang nodes , for parallelizing inside a cluster . It %%% handles errors and node failures. It can be configured, tuned, and %%% tweaked to get optimal performance while minimizing overhead. %%% %%% Almost all the functions are identical to equivalent functions in %%% lists, returning exactly the same result, and having both a form %%% with an identical syntax that operates on each element in parallel %%% and a form which takes an optional "malt", a specification for how %%% to parallelize the operation. %%% fold is the one exception , parallel fold is different from linear %%% fold. This module also include a simple mapreduce implementation, %%% and the function runmany. All the other functions are implemented %%% with runmany, which is as a generalization of parallel list %%% operations. %%% Malts %%% ===== %%% %%% A malt specifies how to break a list into sublists, and can optionally %%% specify a timeout, which nodes to run on, and how many processes to start %%% per node. %%% %%% Malt = MaltComponent | [MaltComponent] %%% MaltComponent = SubListSize::integer() | {processes, integer()} | %%% {processes, schedulers} | { timeout , Milliseconds::integer ( ) } | { nodes , [ NodeSpec]}<br/ > %%% %%% NodeSpec = Node::atom() | {Node::atom(), NumProcesses::integer()} | %%% {Node::atom(), schedulers} %%% An integer can be given to specify the exact size for sublists . 1 %%% is a good choice for IO-bound operations and when the operation on %%% each list element is expensive. Larger numbers minimize overhead %%% and are faster for cheap operations. %%% %%% If the integer is omitted, and you have specified a `{processes, %%% X}`, the list is split into X sublists. This is only useful when %%% the time to process each element is close to identical and you %%% know exactly how many lines of execution are available to you. %%% If neither of the above applies , the sublist size defaults to 1 . %%% %%% You can use `{processes, X}` to have the list processed by `X` %%% processes on the local machine. A good choice for `X` is the %%% number of lines of execution (cores) the machine provides. This %%% can be done automatically with {processes, schedulers}, which sets the number of processes to the number of schedulers in the erlang %%% virtual machine (probably equal to the number of cores). %%% ` { timeout , ` specifies a timeout . This is a timeout %%% for the entire operation, both operating on the sublists and %%% combining the results. exit(timeout) is evaluated if the timeout %%% is exceeded. %%% ` { nodes , NodeList } ` specifies that the operation should be done across nodes . Every element of NodeList is of the form ` { NodeName , } ` or NodeName , which means the same as ` { NodeName , 1 } ` . plists runs NumProcesses processes on NodeName concurrently . A good choice for NumProcesses is the number of %%% lines of execution (cores) a node provides plus one. This ensures %%% the node is completely busy even when fetching a new sublist. This can be done automatically with ` { NodeName , schedulers } ` , in which %%% case plists uses a cached value if it has one, and otherwise finds %%% the number of schedulers in the remote node and adds one. This will ensure at least one busy process per core ( assuming the node %%% has a scheduler for each core). %%% %%% plists is able to recover if a node goes down. If all nodes go %%% down, exit(allnodescrashed) is evaluated. %%% %%% Any of the above may be used as a malt, or may be combined into a list . ` { nodes , NodeList } ` and { processes , X } may not be combined . %%% %%% Examples %%% ======== %%% % % start a process for each element ( 1 - element sublists ) < 1 %%% % % start a process for each ten elements ( 10 - element sublists ) 10 %%% % % split the list into two sublists and process in two processes { processes , 2 } %%% %%% %% split the list into X sublists and process in X processes, %%% %% where X is the number of cores in the machine %%% {processes, schedulers} %%% % % split the list into 10 - element sublists and process in two processes [ 10 , { processes , 2 } ] %%% % % timeout after one second . Assumes that a process should be started %%% %% for each element.<br/> { timeout , 1000 } %%% % % Runs 3 processes at a time on apple@desktop , and 2 on orange@laptop %%% %% This is the best way to utilize all the CPU-power of a dual-core<br/> %%% %% desktop and a single-core laptop. Assumes that the list should be<br/> % % split into 1 - element sublists.<br/ > { nodes , [ { apple@desktop , 3 } , { orange@laptop , 2 } ] } %%% %%% %% Like above, but makes plists figure out how many processes to use. %%% {nodes, [{apple@desktop, schedulers}, {orange@laptop, schedulers}]} %%% % % Gives apple and orange three seconds to process the list as < br/ > % % 100 - element sublists.<br/ > [ 100 , { timeout , 3000 } , { nodes , [ { apple@desktop , 3 } , { orange@laptop , 2 } ] } ] %%% Aside : Why ? %%% ================ %%% %%% I needed a word for this concept, so maybe my subconsciousness %%% gave me one by making me misspell multiply. Maybe it is an acronym for is A List Tearing Specification . Maybe it is a beer %%% metaphor, suggesting that code only runs in parallel if bribed %%% with spirits. It's jargon, learn it or you can't be part of the %%% in-group. %%% %%% Messages and Errors %%% =================== %%% %%% plists assures that no extraneous messages are left in or will %%% later enter the message queue. This is guaranteed even in the %%% event of an error. %%% %%% Errors in spawned processes are caught and propagated to the %%% calling process. If you invoke %%% plists : map(fun ( X ) - > 1 / X end , [ 1 , 2 , 3 , 0 ] ) . %%% %%% you get a badarith error, exactly like when you use lists:map. %%% %%% plists uses monitors to watch the processes it spawns. It is not a %%% good idea to invoke plists when you are already monitoring processes . If one of them does a non - normal exit , plists receives %%% the 'DOWN' message believing it to be from one of its own %%% processes. The error propagation system goes into effect, which %%% results in the error occurring in the calling process. %%% -module(ec_plists). -export([all/2, all/3, any/2, any/3, filter/2, filter/3, fold/3, fold/4, fold/5, foreach/2, foreach/3, map/2, map/3, ftmap/2, ftmap/3, partition/2, partition/3, sort/1, sort/2, sort/3, usort/1, usort/2, usort/3, mapreduce/2, mapreduce/3, mapreduce/5, runmany/3, runmany/4]). -export_type([malt/0, malt_component/0, node_spec/0, fuse/0, fuse_fun/0]). %%============================================================================ %% types %%============================================================================ -type malt() :: malt_component() | [malt_component()]. -type malt_component() :: SubListSize::integer() | {processes, integer()} | {processes, schedulers} | {timeout, Milliseconds::integer()} | {nodes, [node_spec()]}. -type node_spec() :: Node::atom() | {Node::atom(), NumProcesses::integer()} | {Node::atom(), schedulers}. -type fuse_fun() :: fun((term(), term()) -> term()). -type fuse() :: fuse_fun() | {recursive, fuse_fun()} | {reverse, fuse_fun()}. -type el_fun() :: fun((term()) -> term()). %%============================================================================ %% API %%============================================================================ %% Everything here is defined in terms of runmany. %% The following methods are convient interfaces to runmany. %% @doc Same semantics as in module %% <a href="">lists</a>. -spec all(el_fun(), list()) -> boolean(). all(Fun, List) -> all(Fun, List, 1). %% @doc Same semantics as in module %% <a href="">lists</a>. -spec all(el_fun(), list(), malt()) -> boolean(). all(Fun, List, Malt) -> try runmany(fun (L) -> B = lists:all(Fun, L), if B -> nil; true -> erlang:throw(notall) end end, fun (_A1, _A2) -> nil end, List, Malt), true catch throw:notall -> false end. %% @doc Same semantics as in module %% <a href="">lists</a>. -spec any(fun(), list()) -> boolean(). any(Fun, List) -> any(Fun, List, 1). %% @doc Same semantics as in module %% <a href="">lists</a>. -spec any(fun(), list(), malt()) -> boolean(). any(Fun, List, Malt) -> try runmany(fun (L) -> B = lists:any(Fun, L), if B -> erlang:throw(any); true -> nil end end, fun (_A1, _A2) -> nil end, List, Malt) of _ -> false catch throw:any -> true end. %% @doc Same semantics as in module %% <a href="">lists</a>. -spec filter(fun(), list()) -> list(). filter(Fun, List) -> filter(Fun, List, 1). %% @doc Same semantics as in module %% <a href="">lists</a>. -spec filter(fun(), list(), malt()) -> list(). filter(Fun, List, Malt) -> runmany(fun (L) -> lists:filter(Fun, L) end, {reverse, fun (A1, A2) -> A1 ++ A2 end}, List, Malt). %% Note that with parallel fold there is not foldl and foldr, instead just one fold that can fuse Accumlators . @doc Like below , but assumes 1 as the . This function is almost useless , %% and is intended only to aid converting code from using lists to plists. -spec fold(fun(), InitAcc::term(), list()) -> term(). fold(Fun, InitAcc, List) -> fold(Fun, Fun, InitAcc, List, 1). @doc Like below , but uses the Fun as the by default . -spec fold(fun(), InitAcc::term(), list(), malt()) -> term(). fold(Fun, InitAcc, List, Malt) -> fold(Fun, Fun, InitAcc, List, Malt). %% @doc fold is more complex when made parallel. There is no foldl and %% foldr, accumulators aren't passed in any defined order. The list %% is split into sublists which are folded together. Fun is identical %% to the function passed to lists:fold[lr], it takes (an element, and %% the accumulator) and returns -> a new accumulator. It is used for the initial stage of folding sublists . fuses together the %% results, it takes (Results1, Result2) and returns -> a new result. %% By default sublists are fused left to right, each result of a fuse being fed into the first element of the next fuse . The result of %% the last fuse is the result. %% %% Fusing may also run in parallel using a recursive algorithm, by specifying the fuse as { recursive , } . See %% the discussion in {@link runmany/4}. %% %% Malt is the malt for the initial folding of sublists, and for the %% possible recursive fuse. -spec fold(fun(), fuse(), InitAcc::term(), list(), malt()) -> term(). fold(Fun, Fuse, InitAcc, List, Malt) -> Fun2 = fun (L) -> lists:foldl(Fun, InitAcc, L) end, runmany(Fun2, Fuse, List, Malt). %% @doc Similar to foreach in module %% <a href="">lists</a> %% except it makes no guarantee about the order it processes list elements. -spec foreach(fun(), list()) -> ok. foreach(Fun, List) -> foreach(Fun, List, 1). %% @doc Similar to foreach in module %% <a href="">lists</a> %% except it makes no guarantee about the order it processes list elements. -spec foreach(fun(), list(), malt()) -> ok. foreach(Fun, List, Malt) -> runmany(fun (L) -> lists:foreach(Fun, L) end, fun (_A1, _A2) -> ok end, List, Malt). %% @doc Same semantics as in module %% <a href="">lists</a>. -spec map(fun(), list()) -> list(). map(Fun, List) -> map(Fun, List, 1). %% @doc Same semantics as in module %% <a href="">lists</a>. -spec map(fun(), list(), malt()) -> list(). map(Fun, List, Malt) -> runmany(fun (L) -> lists:map(Fun, L) end, {reverse, fun (A1, A2) -> A1 ++ A2 end}, List, Malt). %% @doc values are returned as {value, term()}. -spec ftmap(fun(), list()) -> list(). ftmap(Fun, List) -> map(fun(L) -> try {value, Fun(L)} catch Class:Type -> {error, {Class, Type}} end end, List). %% @doc values are returned as {value, term()}. -spec ftmap(fun(), list(), malt()) -> list(). ftmap(Fun, List, Malt) -> map(fun(L) -> try {value, Fun(L)} catch Class:Type -> {error, {Class, Type}} end end, List, Malt). %% @doc Same semantics as in module %% <a href="">lists</a>. -spec partition(fun(), list()) -> {list(), list()}. partition(Fun, List) -> partition(Fun, List, 1). %% @doc Same semantics as in module %% <a href="">lists</a>. -spec partition(fun(), list(), malt()) -> {list(), list()}. partition(Fun, List, Malt) -> runmany(fun (L) -> lists:partition(Fun, L) end, {reverse, fun ({True1, False1}, {True2, False2}) -> {True1 ++ True2, False1 ++ False2} end}, List, Malt). SORTMALT needs to be tuned -define(SORTMALT, 100). %% @doc Same semantics as in module %% <a href="">lists</a>. -spec sort(list()) -> list(). sort(List) -> sort(fun (A, B) -> A =< B end, List). %% @doc Same semantics as in module %% <a href="">lists</a>. -spec sort(fun(), list()) -> list(). sort(Fun, List) -> sort(Fun, List, ?SORTMALT). %% @doc This version lets you specify your own malt for sort. %% %% sort splits the list into sublists and sorts them, and it merges the %% sorted lists together. These are done in parallel. Each sublist is %% sorted in a separate process, and each merging of results is done in a separate process . Malt defaults to 100 , causing the list to be split into 100 - element sublists . -spec sort(fun(), list(), malt()) -> list(). sort(Fun, List, Malt) -> Fun2 = fun (L) -> lists:sort(Fun, L) end, Fuse = fun (A1, A2) -> lists:merge(Fun, A1, A2) end, runmany(Fun2, {recursive, Fuse}, List, Malt). %% @doc Same semantics as in module %% <a href="">lists</a>. -spec usort(list()) -> list(). usort(List) -> usort(fun (A, B) -> A =< B end, List). %% @doc Same semantics as in module %% <a href="">lists</a>. -spec usort(fun(), list()) -> list(). usort(Fun, List) -> usort(Fun, List, ?SORTMALT). @doc This version lets you specify your own malt for usort . %% usort splits the list into sublists and sorts them , and it merges the %% sorted lists together. These are done in parallel. Each sublist is %% sorted in a separate process, and each merging of results is done in a separate process . Malt defaults to 100 , causing the list to be split into 100 - element sublists . %% usort removes duplicate elements while it sorts . -spec usort(fun(), list(), malt()) -> list(). usort(Fun, List, Malt) -> Fun2 = fun (L) -> lists:usort(Fun, L) end, Fuse = fun (A1, A2) -> lists:umerge(Fun, A1, A2) end, runmany(Fun2, {recursive, Fuse}, List, Malt). @doc Like below , assumes default MapMalt of 1 . -ifdef(namespaced_types). -spec mapreduce(MapFunc, list()) -> dict:dict() when MapFunc :: fun((term()) -> DeepListOfKeyValuePairs), DeepListOfKeyValuePairs :: [DeepListOfKeyValuePairs] | {Key::term(), Value::term()}. -else. -spec mapreduce(MapFunc, list()) -> dict() when MapFunc :: fun((term()) -> DeepListOfKeyValuePairs), DeepListOfKeyValuePairs :: [DeepListOfKeyValuePairs] | {Key::term(), Value::term()}. -endif. mapreduce(MapFunc, List) -> mapreduce(MapFunc, List, 1). %% Like below, but uses a default reducer that collects all %% {Key, Value} pairs into a %% <a href="">dict</a>, with values { Key , [ Value1 , Value2 ... ] } . %% This dict is returned as the result. mapreduce(MapFunc, List, MapMalt) -> mapreduce(MapFunc, List, dict:new(), fun add_key/3, MapMalt). %% @doc This is a very basic mapreduce. You won't write a Google - rivaling search engine with it . It has no equivalent in lists . Each element in the list is run through the MapFunc , which %% produces either a {Key, Value} pair, or a lists of key value pairs, %% or a list of lists of key value pairs...etc. A reducer process runs %% in parallel with the mapping processes, collecting the key value pairs . It starts with a state given by InitState , and for each { Key , Value } pair that it receives it invokes ReduceFunc(OldState , %% Key, Value) to compute its new state. mapreduce returns the %% reducer's final state. %% MapMalt is the malt for the mapping operation , with a default value of 1 , %% meaning each element of the list is mapped by a separate process. %% mapreduce requires OTP R11B , or it may leave monitoring messages in the %% message queue. -ifdef(namespaced_types). -spec mapreduce(MapFunc, list(), InitState::term(), ReduceFunc, malt()) -> dict:dict() when MapFunc :: fun((term()) -> DeepListOfKeyValuePairs), DeepListOfKeyValuePairs :: [DeepListOfKeyValuePairs] | {Key::term(), Value::term()}, ReduceFunc :: fun((OldState::term(), Key::term(), Value::term()) -> NewState::term()). -else. -spec mapreduce(MapFunc, list(), InitState::term(), ReduceFunc, malt()) -> dict() when MapFunc :: fun((term()) -> DeepListOfKeyValuePairs), DeepListOfKeyValuePairs :: [DeepListOfKeyValuePairs] | {Key::term(), Value::term()}, ReduceFunc :: fun((OldState::term(), Key::term(), Value::term()) -> NewState::term()). -endif. mapreduce(MapFunc, List, InitState, ReduceFunc, MapMalt) -> Parent = self(), {Reducer, ReducerRef} = erlang:spawn_monitor(fun () -> reducer(Parent, 0, InitState, ReduceFunc) end), MapFunc2 = fun (L) -> Reducer ! lists:map(MapFunc, L), 1 end, SentMessages = try runmany(MapFunc2, fun (A, B) -> A+B end, List, MapMalt) catch exit:Reason -> erlang:demonitor(ReducerRef, [flush]), Reducer ! die, exit(Reason) end, Reducer ! {mappers, done, SentMessages}, Results = receive {Reducer, Results2} -> Results2; {'DOWN', _, _, Reducer, Reason2} -> exit(Reason2) end, receive {'DOWN', _, _, Reducer, normal} -> nil end, Results. reducer(Parent, NumReceived, State, Func) -> receive die -> nil; {mappers, done, NumReceived} -> Parent ! {self (), State}; Keys -> reducer(Parent, NumReceived + 1, each_key(State, Func, Keys), Func) end. each_key(State, Func, {Key, Value}) -> Func(State, Key, Value); each_key(State, Func, [List|Keys]) -> each_key(each_key(State, Func, List), Func, Keys); each_key(State, _, []) -> State. add_key(Dict, Key, Value) -> case dict:is_key(Key, Dict) of true -> dict:append(Key, Value, Dict); false -> dict:store(Key, [Value], Dict) end. @doc Like below , but assumes a of 1 , %% meaning each element of the list is processed by a separate process. -spec runmany(fun(), fuse(), list()) -> term(). runmany(Fun, Fuse, List) -> runmany(Fun, Fuse, List, 1). %% Begin internal stuff (though runmany/4 is exported). %% @doc All of the other functions are implemented with runmany. runmany %% takes a List, splits it into sublists, and starts processes to operate on each sublist , all done according to . Each process passes its sublist %% into Fun and sends the result back. %% The results are then fused together to get the final result . There are two ways this can operate , lineraly and recursively . If is a function , %% a fuse is done linearly left-to-right on the sublists, the results of processing the first and second sublists being passed to , then the result of the first fuse and processing the third sublits , and so on . If is { reverse , FuseFunc } , then a fuse is done right - to - left , the results of processing the second - to - last and last sublists being passed to FuseFunc , then the results of processing the third - to - last sublist and the results of the first fuse , and and so forth . %% Both methods preserve the original order of the lists elements. %% To do a recursive fuse , pass as { recursive , FuseFunc } . %% The recursive fuse makes no guarantee about the order the results of %% sublists, or the results of fuses are passed to FuseFunc. It %% continues fusing pairs of results until it is down to one. %% %% Recursive fuse is down in parallel with processing the sublists, and a %% process is spawned to fuse each pair of results. It is a parallelized %% algorithm. Linear fuse is done after all results of processing sublists %% have been collected, and can only run in a single process. %% %% Even if you pass {recursive, FuseFunc}, a recursive fuse is only done if the malt contains { nodes , NodeList } or { processes , X } . If this is not the %% case, a linear fuse is done. -spec runmany(fun(([term()]) -> term()), fuse(), list(), malt()) -> term(). runmany(Fun, Fuse, List, Malt) when erlang:is_list(Malt) -> runmany(Fun, Fuse, List, local, no_split, Malt); runmany(Fun, Fuse, List, Malt) -> runmany(Fun, Fuse, List, [Malt]). runmany(Fun, Fuse, List, Nodes, no_split, [MaltTerm|Malt]) when erlang:is_integer(MaltTerm) -> runmany(Fun, Fuse, List, Nodes, MaltTerm, Malt); runmany(Fun, Fuse, List, local, Split, [{processes, schedulers}|Malt]) -> %% run a process for each scheduler S = erlang:system_info(schedulers), runmany(Fun, Fuse, List, local, Split, [{processes, S}|Malt]); runmany(Fun, Fuse, List, local, no_split, [{processes, X}|_]=Malt) -> %% Split the list into X sublists, where X is the number of processes L = erlang:length(List), case (L rem X) of 0 -> runmany(Fun, Fuse, List, local, (L / X), Malt); _ -> runmany(Fun, Fuse, List, local, (L / X) + 1, Malt) end; runmany(Fun, Fuse, List, local, Split, [{processes, X}|Malt]) -> %% run X process on local machine Nodes = lists:duplicate(X, node()), runmany(Fun, Fuse, List, Nodes, Split, Malt); runmany(Fun, Fuse, List, Nodes, Split, [{timeout, X}|Malt]) -> Parent = erlang:self(), Timer = proc_lib:spawn(fun () -> receive stoptimer -> Parent ! {timerstopped, erlang:self()} after X -> Parent ! {timerrang, erlang:self()}, receive stoptimer -> Parent ! {timerstopped, erlang:self()} end end end), Ans = try runmany(Fun, Fuse, List, Nodes, Split, Malt) catch %% we really just want the after block, the syntax %% makes this catch necessary. willneverhappen -> nil after Timer ! stoptimer, cleanup_timer(Timer) end, Ans; runmany(Fun, Fuse, List, local, Split, [{nodes, NodeList}|Malt]) -> Nodes = lists:foldl(fun ({Node, schedulers}, A) -> X = schedulers_on_node(Node) + 1, lists:reverse(lists:duplicate(X, Node), A); ({Node, X}, A) -> lists:reverse(lists:duplicate(X, Node), A); (Node, A) -> [Node|A] end, [], NodeList), runmany(Fun, Fuse, List, Nodes, Split, Malt); runmany(Fun, {recursive, Fuse}, List, local, Split, []) -> %% local recursive fuse, for when we weren't invoked with {processes, X} or { nodes , NodeList } . Degenerates recursive fuse into linear fuse . runmany(Fun, Fuse, List, local, Split, []); runmany(Fun, Fuse, List, Nodes, no_split, []) -> %% by default, operate on each element separately runmany(Fun, Fuse, List, Nodes, 1, []); runmany(Fun, Fuse, List, local, Split, []) -> List2 = splitmany(List, Split), local_runmany(Fun, Fuse, List2); runmany(Fun, Fuse, List, Nodes, Split, []) -> List2 = splitmany(List, Split), cluster_runmany(Fun, Fuse, List2, Nodes). cleanup_timer(Timer) -> receive {timerrang, Timer} -> cleanup_timer(Timer); {timerstopped, Timer} -> nil end. schedulers_on_node(Node) -> case erlang:get(ec_plists_schedulers_on_nodes) of undefined -> X = determine_schedulers(Node), erlang:put(ec_plists_schedulers_on_nodes, dict:store(Node, X, dict:new())), X; Dict -> case dict:is_key(Node, Dict) of true -> dict:fetch(Node, Dict); false -> X = determine_schedulers(Node), erlang:put(ec_plists_schedulers_on_nodes, dict:store(Node, X, Dict)), X end end. determine_schedulers(Node) -> Parent = erlang:self(), Child = proc_lib:spawn(Node, fun () -> Parent ! {self(), erlang:system_info(schedulers)} end), erlang:monitor(process, Child), receive {Child, X} -> receive {'DOWN', _, _, Child, _Reason} -> nil end, X; {'DOWN', _, _, Child, Reason} when Reason =/= normal -> 0 end. %% @doc local runmany, for when we weren't invoked with {processes, X} or { nodes , NodeList } . Every sublist is processed in parallel . local_runmany(Fun, Fuse, List) -> Parent = self (), Pids = lists:map(fun (L) -> F = fun () -> Parent ! {self (), Fun(L)} end, {Pid, _} = erlang:spawn_monitor(F), Pid end, List), Answers = try lists:map(fun receivefrom/1, Pids) catch throw:Message -> {BadPid, Reason} = Message, handle_error(BadPid, Reason, Pids) end, lists:foreach(fun (Pid) -> normal_cleanup(Pid) end, Pids), fuse(Fuse, Answers). receivefrom(Pid) -> receive {Pid, R} -> R; {'DOWN', _, _, Pid, Reason} when Reason =/= normal -> erlang:throw({Pid, Reason}); {timerrang, _} -> erlang:throw({nil, timeout}) end. %% Convert List into [{Number, Sublist}] cluster_runmany(Fun, Fuse, List, Nodes) -> {List2, _} = lists:foldl(fun (X, {L, Count}) -> {[{Count, X}|L], Count+1} end, {[], 0}, List), cluster_runmany(Fun, Fuse, List2, Nodes, [], []). @doc Add a pair of results into the TaskList as a fusing task cluster_runmany(Fun, {recursive, Fuse}, [], Nodes, Running, [{_, R1}, {_, R2}|Results]) -> cluster_runmany(Fun, {recursive, Fuse}, [{fuse, R1, R2}], Nodes, Running, Results); cluster_runmany(_, {recursive, _Fuse}, [], _Nodes, [], [{_, Result}]) -> %% recursive fuse done, return result Result; cluster_runmany(_, {recursive, _Fuse}, [], _Nodes, [], []) -> %% edge case where we are asked to do nothing []; cluster_runmany(_, Fuse, [], _Nodes, [], Results) -> %% We're done, now we just have to [linear] fuse the results fuse(Fuse, lists:map(fun ({_, R}) -> R end, lists:sort(fun ({A, _}, {B, _}) -> A =< B end, lists:reverse(Results)))); cluster_runmany(Fun, Fuse, [Task|TaskList], [N|Nodes], Running, Results) -> %% We have a ready node and a sublist or fuse to be processed, so we start %% a new process Parent = erlang:self(), case Task of {Num, L2} -> Fun2 = fun () -> Parent ! {erlang:self(), Num, Fun(L2)} end; {fuse, R1, R2} -> {recursive, FuseFunc} = Fuse, Fun2 = fun () -> Parent ! {erlang:self(), fuse, FuseFunc(R1, R2)} end end, Fun3 = fun() -> runmany_wrap(Fun2, Parent) end, Pid = proc_lib:spawn(N, Fun3), erlang:monitor(process, Pid), cluster_runmany(Fun, Fuse, TaskList, Nodes, [{Pid, N, Task}|Running], Results); cluster_runmany(Fun, Fuse, TaskList, Nodes, Running, Results) when length(Running) > 0 -> %% We can't start a new process, but can watch over already running ones receive {_Pid, error, Reason} -> RunningPids = lists:map(fun ({Pid, _, _}) -> Pid end, Running), handle_error(junkvalue, Reason, RunningPids); {Pid, Num, Result} -> throw out the exit message , should be %% normal, noproc, or noconnection receive {'DOWN', _, _, Pid, _Reason} -> nil end, {Running2, FinishedNode, _} = delete_running(Pid, Running, []), cluster_runmany(Fun, Fuse, TaskList, [FinishedNode|Nodes], Running2, [{Num, Result}|Results]); {timerrang, _} -> RunningPids = lists:map(fun ({Pid, _, _}) -> Pid end, Running), handle_error(nil, timeout, RunningPids); %% node failure {'DOWN', _, _, Pid, noconnection} -> {Running2, _DeadNode, Task} = delete_running(Pid, Running, []), cluster_runmany(Fun, Fuse, [Task|TaskList], Nodes, Running2, Results); %% could a noproc exit message come before the message from %% the process? we are assuming it can't. %% this clause is unlikely to get invoked due to cluster_runmany's %% spawned processes. It will still catch errors in mapreduce's %% reduce process, however. {'DOWN', _, _, BadPid, Reason} when Reason =/= normal -> RunningPids = lists:map(fun ({Pid, _, _}) -> Pid end, Running), handle_error(BadPid, Reason, RunningPids) end; cluster_runmany(_, _, [_Non|_Empty], []=_Nodes, []=_Running, _) -> %% We have data, but no nodes either available or occupied erlang:exit(allnodescrashed). -ifdef(fun_stacktrace). runmany_wrap(Fun, Parent) -> try Fun catch exit:siblingdied -> ok; exit:Reason -> Parent ! {erlang:self(), error, Reason}; error:R -> Parent ! {erlang:self(), error, {R, erlang:get_stacktrace()}}; throw:R -> Parent ! {erlang:self(), error, {{nocatch, R}, erlang:get_stacktrace()}} end. -else. runmany_wrap(Fun, Parent) -> try Fun catch exit:siblingdied -> ok; exit:Reason -> Parent ! {erlang:self(), error, Reason}; error:R:Stacktrace -> Parent ! {erlang:self(), error, {R, Stacktrace}}; throw:R:Stacktrace -> Parent ! {erlang:self(), error, {{nocatch, R}, Stacktrace}} end. -endif. delete_running(Pid, [{Pid, Node, List}|Running], Acc) -> {Running ++ Acc, Node, List}; delete_running(Pid, [R|Running], Acc) -> delete_running(Pid, Running, [R|Acc]). handle_error(BadPid, Reason, Pids) -> lists:foreach(fun (Pid) -> erlang:exit(Pid, siblingdied) end, Pids), lists:foreach(fun (Pid) -> error_cleanup(Pid, BadPid) end, Pids), erlang:exit(Reason). error_cleanup(BadPid, BadPid) -> ok; error_cleanup(Pid, BadPid) -> receive {Pid, _} -> error_cleanup(Pid, BadPid); {Pid, _, _} -> error_cleanup(Pid, BadPid); {'DOWN', _, _, Pid, _Reason} -> ok end. normal_cleanup(Pid) -> receive {'DOWN', _, _, Pid, _Reason} -> ok end. %% edge case fuse(_, []) -> []; fuse({reverse, _}=Fuse, Results) -> [RL|ResultsR] = lists:reverse(Results), fuse(Fuse, ResultsR, RL); fuse(Fuse, [R1|Results]) -> fuse(Fuse, Results, R1). fuse({reverse, FuseFunc}=Fuse, [R2|Results], R1) -> fuse(Fuse, Results, FuseFunc(R2, R1)); fuse(Fuse, [R2|Results], R1) -> fuse(Fuse, Results, Fuse(R1, R2)); fuse(_, [], R) -> R. @doc Splits a list into a list of sublists , each of size , %% except for the last element which is less if the original list %% could not be evenly divided into Size-sized lists. splitmany(List, Size) -> splitmany(List, [], Size). splitmany([], Acc, _) -> lists:reverse(Acc); splitmany(List, Acc, Size) -> {Top, NList} = split(Size, List), splitmany(NList, [Top|Acc], Size). @doc Like lists : split , except it splits a list smaller than its first %% parameter split(Size, List) -> split(Size, List, []). split(0, List, Acc) -> {lists:reverse(Acc), List}; split(Size, [H|List], Acc) -> split(Size - 1, List, [H|Acc]); split(_, [], Acc) -> {lists:reverse(Acc), []}.
null
https://raw.githubusercontent.com/erlware/erlware_commons/eeb25f4b7f4d9f423a0470461d225fb6a61217d2/src/ec_plists.erl
erlang
vi:ts=4 sw=4 et The MIT License Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal to use, copy, modify, merge, publish, distribute, sublicense, and/or sell furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. --------------------------------------------------------------------------- @doc plists is a drop-in replacement for module <a href="">lists</a>, making most list operations parallel. It can operate on each element in parallel, for IO-bound operations, on sublists in parallel, for taking advantage of multi-core machines with CPU-bound operations, handles errors and node failures. It can be configured, tuned, and tweaked to get optimal performance while minimizing overhead. Almost all the functions are identical to equivalent functions in lists, returning exactly the same result, and having both a form with an identical syntax that operates on each element in parallel and a form which takes an optional "malt", a specification for how to parallelize the operation. fold. This module also include a simple mapreduce implementation, and the function runmany. All the other functions are implemented with runmany, which is as a generalization of parallel list operations. ===== A malt specifies how to break a list into sublists, and can optionally specify a timeout, which nodes to run on, and how many processes to start per node. Malt = MaltComponent | [MaltComponent] MaltComponent = SubListSize::integer() | {processes, integer()} | {processes, schedulers} | NodeSpec = Node::atom() | {Node::atom(), NumProcesses::integer()} | {Node::atom(), schedulers} is a good choice for IO-bound operations and when the operation on each list element is expensive. Larger numbers minimize overhead and are faster for cheap operations. If the integer is omitted, and you have specified a `{processes, X}`, the list is split into X sublists. This is only useful when the time to process each element is close to identical and you know exactly how many lines of execution are available to you. You can use `{processes, X}` to have the list processed by `X` processes on the local machine. A good choice for `X` is the number of lines of execution (cores) the machine provides. This can be done automatically with {processes, schedulers}, which sets virtual machine (probably equal to the number of cores). for the entire operation, both operating on the sublists and combining the results. exit(timeout) is evaluated if the timeout is exceeded. lines of execution (cores) a node provides plus one. This ensures the node is completely busy even when fetching a new sublist. This case plists uses a cached value if it has one, and otherwise finds the number of schedulers in the remote node and adds one. This has a scheduler for each core). plists is able to recover if a node goes down. If all nodes go down, exit(allnodescrashed) is evaluated. Any of the above may be used as a malt, or may be combined into a Examples ======== % start a process for each element ( 1 - element sublists ) < % start a process for each ten elements ( 10 - element sublists ) % split the list into two sublists and process in two processes %% split the list into X sublists and process in X processes, %% where X is the number of cores in the machine {processes, schedulers} % split the list into 10 - element sublists and process in two processes % timeout after one second . Assumes that a process should be started %% for each element.<br/> % Runs 3 processes at a time on apple@desktop , and 2 on orange@laptop %% This is the best way to utilize all the CPU-power of a dual-core<br/> %% desktop and a single-core laptop. Assumes that the list should be<br/> % split into 1 - element sublists.<br/ > %% Like above, but makes plists figure out how many processes to use. {nodes, [{apple@desktop, schedulers}, {orange@laptop, schedulers}]} % Gives apple and orange three seconds to process the list as < br/ > % 100 - element sublists.<br/ > ================ I needed a word for this concept, so maybe my subconsciousness gave me one by making me misspell multiply. Maybe it is an acronym metaphor, suggesting that code only runs in parallel if bribed with spirits. It's jargon, learn it or you can't be part of the in-group. Messages and Errors =================== plists assures that no extraneous messages are left in or will later enter the message queue. This is guaranteed even in the event of an error. Errors in spawned processes are caught and propagated to the calling process. If you invoke you get a badarith error, exactly like when you use lists:map. plists uses monitors to watch the processes it spawns. It is not a good idea to invoke plists when you are already monitoring the 'DOWN' message believing it to be from one of its own processes. The error propagation system goes into effect, which results in the error occurring in the calling process. ============================================================================ types ============================================================================ ============================================================================ API ============================================================================ Everything here is defined in terms of runmany. The following methods are convient interfaces to runmany. @doc Same semantics as in module <a href="">lists</a>. @doc Same semantics as in module <a href="">lists</a>. @doc Same semantics as in module <a href="">lists</a>. @doc Same semantics as in module <a href="">lists</a>. @doc Same semantics as in module <a href="">lists</a>. @doc Same semantics as in module <a href="">lists</a>. Note that with parallel fold there is not foldl and foldr, and is intended only to aid converting code from using lists to plists. @doc fold is more complex when made parallel. There is no foldl and foldr, accumulators aren't passed in any defined order. The list is split into sublists which are folded together. Fun is identical to the function passed to lists:fold[lr], it takes (an element, and the accumulator) and returns -> a new accumulator. It is used for results, it takes (Results1, Result2) and returns -> a new result. By default sublists are fused left to right, each result of a fuse the last fuse is the result. Fusing may also run in parallel using a recursive algorithm, the discussion in {@link runmany/4}. Malt is the malt for the initial folding of sublists, and for the possible recursive fuse. @doc Similar to foreach in module <a href="">lists</a> except it makes no guarantee about the order it processes list elements. @doc Similar to foreach in module <a href="">lists</a> except it makes no guarantee about the order it processes list elements. @doc Same semantics as in module <a href="">lists</a>. @doc Same semantics as in module <a href="">lists</a>. @doc values are returned as {value, term()}. @doc values are returned as {value, term()}. @doc Same semantics as in module <a href="">lists</a>. @doc Same semantics as in module <a href="">lists</a>. @doc Same semantics as in module <a href="">lists</a>. @doc Same semantics as in module <a href="">lists</a>. @doc This version lets you specify your own malt for sort. sort splits the list into sublists and sorts them, and it merges the sorted lists together. These are done in parallel. Each sublist is sorted in a separate process, and each merging of results is done in a @doc Same semantics as in module <a href="">lists</a>. @doc Same semantics as in module <a href="">lists</a>. sorted lists together. These are done in parallel. Each sublist is sorted in a separate process, and each merging of results is done in a Like below, but uses a default reducer that collects all {Key, Value} pairs into a <a href="">dict</a>, This dict is returned as the result. @doc This is a very basic mapreduce. You won't write a produces either a {Key, Value} pair, or a lists of key value pairs, or a list of lists of key value pairs...etc. A reducer process runs in parallel with the mapping processes, collecting the key value Key, Value) to compute its new state. mapreduce returns the reducer's final state. meaning each element of the list is mapped by a separate process. message queue. meaning each element of the list is processed by a separate process. Begin internal stuff (though runmany/4 is exported). @doc All of the other functions are implemented with runmany. runmany takes a List, splits it into sublists, and starts processes to operate on into Fun and sends the result back. a fuse is done linearly left-to-right on the sublists, the results Both methods preserve the original order of the lists elements. The recursive fuse makes no guarantee about the order the results of sublists, or the results of fuses are passed to FuseFunc. It continues fusing pairs of results until it is down to one. Recursive fuse is down in parallel with processing the sublists, and a process is spawned to fuse each pair of results. It is a parallelized algorithm. Linear fuse is done after all results of processing sublists have been collected, and can only run in a single process. Even if you pass {recursive, FuseFunc}, a recursive fuse is only done if case, a linear fuse is done. run a process for each scheduler Split the list into X sublists, where X is the number of processes run X process on local machine we really just want the after block, the syntax makes this catch necessary. local recursive fuse, for when we weren't invoked with {processes, X} by default, operate on each element separately @doc local runmany, for when we weren't invoked with {processes, X} Convert List into [{Number, Sublist}] recursive fuse done, return result edge case where we are asked to do nothing We're done, now we just have to [linear] fuse the results We have a ready node and a sublist or fuse to be processed, so we start a new process We can't start a new process, but can watch over already running ones normal, noproc, or noconnection node failure could a noproc exit message come before the message from the process? we are assuming it can't. this clause is unlikely to get invoked due to cluster_runmany's spawned processes. It will still catch errors in mapreduce's reduce process, however. We have data, but no nodes either available or occupied edge case except for the last element which is less if the original list could not be evenly divided into Size-sized lists. parameter
-*- mode : Erlang ; fill - column : 80 ; comment - column : 75 ; -*- Copyright ( c ) 2007 in the Software without restriction , including without limitation the rights copies of the Software , and to permit persons to whom the Software is all copies or substantial portions of the Software . THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING FROM , @author 2007 freeyourmind + + [ $ @|gmail.com ] and across erlang nodes , for parallelizing inside a cluster . It fold is the one exception , parallel fold is different from linear Malts { timeout , Milliseconds::integer ( ) } | { nodes , [ NodeSpec]}<br/ > An integer can be given to specify the exact size for sublists . 1 If neither of the above applies , the sublist size defaults to 1 . the number of processes to the number of schedulers in the erlang ` { timeout , ` specifies a timeout . This is a timeout ` { nodes , NodeList } ` specifies that the operation should be done across nodes . Every element of NodeList is of the form ` { NodeName , } ` or NodeName , which means the same as ` { NodeName , 1 } ` . plists runs NumProcesses processes on NodeName concurrently . A good choice for NumProcesses is the number of can be done automatically with ` { NodeName , schedulers } ` , in which will ensure at least one busy process per core ( assuming the node list . ` { nodes , NodeList } ` and { processes , X } may not be combined . 1 10 { processes , 2 } [ 10 , { processes , 2 } ] { timeout , 1000 } { nodes , [ { apple@desktop , 3 } , { orange@laptop , 2 } ] } [ 100 , { timeout , 3000 } , { nodes , [ { apple@desktop , 3 } , { orange@laptop , 2 } ] } ] Aside : Why ? for is A List Tearing Specification . Maybe it is a beer plists : map(fun ( X ) - > 1 / X end , [ 1 , 2 , 3 , 0 ] ) . processes . If one of them does a non - normal exit , plists receives -module(ec_plists). -export([all/2, all/3, any/2, any/3, filter/2, filter/3, fold/3, fold/4, fold/5, foreach/2, foreach/3, map/2, map/3, ftmap/2, ftmap/3, partition/2, partition/3, sort/1, sort/2, sort/3, usort/1, usort/2, usort/3, mapreduce/2, mapreduce/3, mapreduce/5, runmany/3, runmany/4]). -export_type([malt/0, malt_component/0, node_spec/0, fuse/0, fuse_fun/0]). -type malt() :: malt_component() | [malt_component()]. -type malt_component() :: SubListSize::integer() | {processes, integer()} | {processes, schedulers} | {timeout, Milliseconds::integer()} | {nodes, [node_spec()]}. -type node_spec() :: Node::atom() | {Node::atom(), NumProcesses::integer()} | {Node::atom(), schedulers}. -type fuse_fun() :: fun((term(), term()) -> term()). -type fuse() :: fuse_fun() | {recursive, fuse_fun()} | {reverse, fuse_fun()}. -type el_fun() :: fun((term()) -> term()). -spec all(el_fun(), list()) -> boolean(). all(Fun, List) -> all(Fun, List, 1). -spec all(el_fun(), list(), malt()) -> boolean(). all(Fun, List, Malt) -> try runmany(fun (L) -> B = lists:all(Fun, L), if B -> nil; true -> erlang:throw(notall) end end, fun (_A1, _A2) -> nil end, List, Malt), true catch throw:notall -> false end. -spec any(fun(), list()) -> boolean(). any(Fun, List) -> any(Fun, List, 1). -spec any(fun(), list(), malt()) -> boolean(). any(Fun, List, Malt) -> try runmany(fun (L) -> B = lists:any(Fun, L), if B -> erlang:throw(any); true -> nil end end, fun (_A1, _A2) -> nil end, List, Malt) of _ -> false catch throw:any -> true end. -spec filter(fun(), list()) -> list(). filter(Fun, List) -> filter(Fun, List, 1). -spec filter(fun(), list(), malt()) -> list(). filter(Fun, List, Malt) -> runmany(fun (L) -> lists:filter(Fun, L) end, {reverse, fun (A1, A2) -> A1 ++ A2 end}, List, Malt). instead just one fold that can fuse Accumlators . @doc Like below , but assumes 1 as the . This function is almost useless , -spec fold(fun(), InitAcc::term(), list()) -> term(). fold(Fun, InitAcc, List) -> fold(Fun, Fun, InitAcc, List, 1). @doc Like below , but uses the Fun as the by default . -spec fold(fun(), InitAcc::term(), list(), malt()) -> term(). fold(Fun, InitAcc, List, Malt) -> fold(Fun, Fun, InitAcc, List, Malt). the initial stage of folding sublists . fuses together the being fed into the first element of the next fuse . The result of by specifying the fuse as { recursive , } . See -spec fold(fun(), fuse(), InitAcc::term(), list(), malt()) -> term(). fold(Fun, Fuse, InitAcc, List, Malt) -> Fun2 = fun (L) -> lists:foldl(Fun, InitAcc, L) end, runmany(Fun2, Fuse, List, Malt). -spec foreach(fun(), list()) -> ok. foreach(Fun, List) -> foreach(Fun, List, 1). -spec foreach(fun(), list(), malt()) -> ok. foreach(Fun, List, Malt) -> runmany(fun (L) -> lists:foreach(Fun, L) end, fun (_A1, _A2) -> ok end, List, Malt). -spec map(fun(), list()) -> list(). map(Fun, List) -> map(Fun, List, 1). -spec map(fun(), list(), malt()) -> list(). map(Fun, List, Malt) -> runmany(fun (L) -> lists:map(Fun, L) end, {reverse, fun (A1, A2) -> A1 ++ A2 end}, List, Malt). -spec ftmap(fun(), list()) -> list(). ftmap(Fun, List) -> map(fun(L) -> try {value, Fun(L)} catch Class:Type -> {error, {Class, Type}} end end, List). -spec ftmap(fun(), list(), malt()) -> list(). ftmap(Fun, List, Malt) -> map(fun(L) -> try {value, Fun(L)} catch Class:Type -> {error, {Class, Type}} end end, List, Malt). -spec partition(fun(), list()) -> {list(), list()}. partition(Fun, List) -> partition(Fun, List, 1). -spec partition(fun(), list(), malt()) -> {list(), list()}. partition(Fun, List, Malt) -> runmany(fun (L) -> lists:partition(Fun, L) end, {reverse, fun ({True1, False1}, {True2, False2}) -> {True1 ++ True2, False1 ++ False2} end}, List, Malt). SORTMALT needs to be tuned -define(SORTMALT, 100). -spec sort(list()) -> list(). sort(List) -> sort(fun (A, B) -> A =< B end, List). -spec sort(fun(), list()) -> list(). sort(Fun, List) -> sort(Fun, List, ?SORTMALT). separate process . Malt defaults to 100 , causing the list to be split into 100 - element sublists . -spec sort(fun(), list(), malt()) -> list(). sort(Fun, List, Malt) -> Fun2 = fun (L) -> lists:sort(Fun, L) end, Fuse = fun (A1, A2) -> lists:merge(Fun, A1, A2) end, runmany(Fun2, {recursive, Fuse}, List, Malt). -spec usort(list()) -> list(). usort(List) -> usort(fun (A, B) -> A =< B end, List). -spec usort(fun(), list()) -> list(). usort(Fun, List) -> usort(Fun, List, ?SORTMALT). @doc This version lets you specify your own malt for usort . usort splits the list into sublists and sorts them , and it merges the separate process . Malt defaults to 100 , causing the list to be split into 100 - element sublists . usort removes duplicate elements while it sorts . -spec usort(fun(), list(), malt()) -> list(). usort(Fun, List, Malt) -> Fun2 = fun (L) -> lists:usort(Fun, L) end, Fuse = fun (A1, A2) -> lists:umerge(Fun, A1, A2) end, runmany(Fun2, {recursive, Fuse}, List, Malt). @doc Like below , assumes default MapMalt of 1 . -ifdef(namespaced_types). -spec mapreduce(MapFunc, list()) -> dict:dict() when MapFunc :: fun((term()) -> DeepListOfKeyValuePairs), DeepListOfKeyValuePairs :: [DeepListOfKeyValuePairs] | {Key::term(), Value::term()}. -else. -spec mapreduce(MapFunc, list()) -> dict() when MapFunc :: fun((term()) -> DeepListOfKeyValuePairs), DeepListOfKeyValuePairs :: [DeepListOfKeyValuePairs] | {Key::term(), Value::term()}. -endif. mapreduce(MapFunc, List) -> mapreduce(MapFunc, List, 1). with values { Key , [ Value1 , Value2 ... ] } . mapreduce(MapFunc, List, MapMalt) -> mapreduce(MapFunc, List, dict:new(), fun add_key/3, MapMalt). Google - rivaling search engine with it . It has no equivalent in lists . Each element in the list is run through the MapFunc , which pairs . It starts with a state given by InitState , and for each { Key , Value } pair that it receives it invokes ReduceFunc(OldState , MapMalt is the malt for the mapping operation , with a default value of 1 , mapreduce requires OTP R11B , or it may leave monitoring messages in the -ifdef(namespaced_types). -spec mapreduce(MapFunc, list(), InitState::term(), ReduceFunc, malt()) -> dict:dict() when MapFunc :: fun((term()) -> DeepListOfKeyValuePairs), DeepListOfKeyValuePairs :: [DeepListOfKeyValuePairs] | {Key::term(), Value::term()}, ReduceFunc :: fun((OldState::term(), Key::term(), Value::term()) -> NewState::term()). -else. -spec mapreduce(MapFunc, list(), InitState::term(), ReduceFunc, malt()) -> dict() when MapFunc :: fun((term()) -> DeepListOfKeyValuePairs), DeepListOfKeyValuePairs :: [DeepListOfKeyValuePairs] | {Key::term(), Value::term()}, ReduceFunc :: fun((OldState::term(), Key::term(), Value::term()) -> NewState::term()). -endif. mapreduce(MapFunc, List, InitState, ReduceFunc, MapMalt) -> Parent = self(), {Reducer, ReducerRef} = erlang:spawn_monitor(fun () -> reducer(Parent, 0, InitState, ReduceFunc) end), MapFunc2 = fun (L) -> Reducer ! lists:map(MapFunc, L), 1 end, SentMessages = try runmany(MapFunc2, fun (A, B) -> A+B end, List, MapMalt) catch exit:Reason -> erlang:demonitor(ReducerRef, [flush]), Reducer ! die, exit(Reason) end, Reducer ! {mappers, done, SentMessages}, Results = receive {Reducer, Results2} -> Results2; {'DOWN', _, _, Reducer, Reason2} -> exit(Reason2) end, receive {'DOWN', _, _, Reducer, normal} -> nil end, Results. reducer(Parent, NumReceived, State, Func) -> receive die -> nil; {mappers, done, NumReceived} -> Parent ! {self (), State}; Keys -> reducer(Parent, NumReceived + 1, each_key(State, Func, Keys), Func) end. each_key(State, Func, {Key, Value}) -> Func(State, Key, Value); each_key(State, Func, [List|Keys]) -> each_key(each_key(State, Func, List), Func, Keys); each_key(State, _, []) -> State. add_key(Dict, Key, Value) -> case dict:is_key(Key, Dict) of true -> dict:append(Key, Value, Dict); false -> dict:store(Key, [Value], Dict) end. @doc Like below , but assumes a of 1 , -spec runmany(fun(), fuse(), list()) -> term(). runmany(Fun, Fuse, List) -> runmany(Fun, Fuse, List, 1). each sublist , all done according to . Each process passes its sublist The results are then fused together to get the final result . There are two ways this can operate , lineraly and recursively . If is a function , of processing the first and second sublists being passed to , then the result of the first fuse and processing the third sublits , and so on . If is { reverse , FuseFunc } , then a fuse is done right - to - left , the results of processing the second - to - last and last sublists being passed to FuseFunc , then the results of processing the third - to - last sublist and the results of the first fuse , and and so forth . To do a recursive fuse , pass as { recursive , FuseFunc } . the malt contains { nodes , NodeList } or { processes , X } . If this is not the -spec runmany(fun(([term()]) -> term()), fuse(), list(), malt()) -> term(). runmany(Fun, Fuse, List, Malt) when erlang:is_list(Malt) -> runmany(Fun, Fuse, List, local, no_split, Malt); runmany(Fun, Fuse, List, Malt) -> runmany(Fun, Fuse, List, [Malt]). runmany(Fun, Fuse, List, Nodes, no_split, [MaltTerm|Malt]) when erlang:is_integer(MaltTerm) -> runmany(Fun, Fuse, List, Nodes, MaltTerm, Malt); runmany(Fun, Fuse, List, local, Split, [{processes, schedulers}|Malt]) -> S = erlang:system_info(schedulers), runmany(Fun, Fuse, List, local, Split, [{processes, S}|Malt]); runmany(Fun, Fuse, List, local, no_split, [{processes, X}|_]=Malt) -> L = erlang:length(List), case (L rem X) of 0 -> runmany(Fun, Fuse, List, local, (L / X), Malt); _ -> runmany(Fun, Fuse, List, local, (L / X) + 1, Malt) end; runmany(Fun, Fuse, List, local, Split, [{processes, X}|Malt]) -> Nodes = lists:duplicate(X, node()), runmany(Fun, Fuse, List, Nodes, Split, Malt); runmany(Fun, Fuse, List, Nodes, Split, [{timeout, X}|Malt]) -> Parent = erlang:self(), Timer = proc_lib:spawn(fun () -> receive stoptimer -> Parent ! {timerstopped, erlang:self()} after X -> Parent ! {timerrang, erlang:self()}, receive stoptimer -> Parent ! {timerstopped, erlang:self()} end end end), Ans = try runmany(Fun, Fuse, List, Nodes, Split, Malt) catch willneverhappen -> nil after Timer ! stoptimer, cleanup_timer(Timer) end, Ans; runmany(Fun, Fuse, List, local, Split, [{nodes, NodeList}|Malt]) -> Nodes = lists:foldl(fun ({Node, schedulers}, A) -> X = schedulers_on_node(Node) + 1, lists:reverse(lists:duplicate(X, Node), A); ({Node, X}, A) -> lists:reverse(lists:duplicate(X, Node), A); (Node, A) -> [Node|A] end, [], NodeList), runmany(Fun, Fuse, List, Nodes, Split, Malt); runmany(Fun, {recursive, Fuse}, List, local, Split, []) -> or { nodes , NodeList } . Degenerates recursive fuse into linear fuse . runmany(Fun, Fuse, List, local, Split, []); runmany(Fun, Fuse, List, Nodes, no_split, []) -> runmany(Fun, Fuse, List, Nodes, 1, []); runmany(Fun, Fuse, List, local, Split, []) -> List2 = splitmany(List, Split), local_runmany(Fun, Fuse, List2); runmany(Fun, Fuse, List, Nodes, Split, []) -> List2 = splitmany(List, Split), cluster_runmany(Fun, Fuse, List2, Nodes). cleanup_timer(Timer) -> receive {timerrang, Timer} -> cleanup_timer(Timer); {timerstopped, Timer} -> nil end. schedulers_on_node(Node) -> case erlang:get(ec_plists_schedulers_on_nodes) of undefined -> X = determine_schedulers(Node), erlang:put(ec_plists_schedulers_on_nodes, dict:store(Node, X, dict:new())), X; Dict -> case dict:is_key(Node, Dict) of true -> dict:fetch(Node, Dict); false -> X = determine_schedulers(Node), erlang:put(ec_plists_schedulers_on_nodes, dict:store(Node, X, Dict)), X end end. determine_schedulers(Node) -> Parent = erlang:self(), Child = proc_lib:spawn(Node, fun () -> Parent ! {self(), erlang:system_info(schedulers)} end), erlang:monitor(process, Child), receive {Child, X} -> receive {'DOWN', _, _, Child, _Reason} -> nil end, X; {'DOWN', _, _, Child, Reason} when Reason =/= normal -> 0 end. or { nodes , NodeList } . Every sublist is processed in parallel . local_runmany(Fun, Fuse, List) -> Parent = self (), Pids = lists:map(fun (L) -> F = fun () -> Parent ! {self (), Fun(L)} end, {Pid, _} = erlang:spawn_monitor(F), Pid end, List), Answers = try lists:map(fun receivefrom/1, Pids) catch throw:Message -> {BadPid, Reason} = Message, handle_error(BadPid, Reason, Pids) end, lists:foreach(fun (Pid) -> normal_cleanup(Pid) end, Pids), fuse(Fuse, Answers). receivefrom(Pid) -> receive {Pid, R} -> R; {'DOWN', _, _, Pid, Reason} when Reason =/= normal -> erlang:throw({Pid, Reason}); {timerrang, _} -> erlang:throw({nil, timeout}) end. cluster_runmany(Fun, Fuse, List, Nodes) -> {List2, _} = lists:foldl(fun (X, {L, Count}) -> {[{Count, X}|L], Count+1} end, {[], 0}, List), cluster_runmany(Fun, Fuse, List2, Nodes, [], []). @doc Add a pair of results into the TaskList as a fusing task cluster_runmany(Fun, {recursive, Fuse}, [], Nodes, Running, [{_, R1}, {_, R2}|Results]) -> cluster_runmany(Fun, {recursive, Fuse}, [{fuse, R1, R2}], Nodes, Running, Results); cluster_runmany(_, {recursive, _Fuse}, [], _Nodes, [], [{_, Result}]) -> Result; cluster_runmany(_, {recursive, _Fuse}, [], _Nodes, [], []) -> []; cluster_runmany(_, Fuse, [], _Nodes, [], Results) -> fuse(Fuse, lists:map(fun ({_, R}) -> R end, lists:sort(fun ({A, _}, {B, _}) -> A =< B end, lists:reverse(Results)))); cluster_runmany(Fun, Fuse, [Task|TaskList], [N|Nodes], Running, Results) -> Parent = erlang:self(), case Task of {Num, L2} -> Fun2 = fun () -> Parent ! {erlang:self(), Num, Fun(L2)} end; {fuse, R1, R2} -> {recursive, FuseFunc} = Fuse, Fun2 = fun () -> Parent ! {erlang:self(), fuse, FuseFunc(R1, R2)} end end, Fun3 = fun() -> runmany_wrap(Fun2, Parent) end, Pid = proc_lib:spawn(N, Fun3), erlang:monitor(process, Pid), cluster_runmany(Fun, Fuse, TaskList, Nodes, [{Pid, N, Task}|Running], Results); cluster_runmany(Fun, Fuse, TaskList, Nodes, Running, Results) when length(Running) > 0 -> receive {_Pid, error, Reason} -> RunningPids = lists:map(fun ({Pid, _, _}) -> Pid end, Running), handle_error(junkvalue, Reason, RunningPids); {Pid, Num, Result} -> throw out the exit message , should be receive {'DOWN', _, _, Pid, _Reason} -> nil end, {Running2, FinishedNode, _} = delete_running(Pid, Running, []), cluster_runmany(Fun, Fuse, TaskList, [FinishedNode|Nodes], Running2, [{Num, Result}|Results]); {timerrang, _} -> RunningPids = lists:map(fun ({Pid, _, _}) -> Pid end, Running), handle_error(nil, timeout, RunningPids); {'DOWN', _, _, Pid, noconnection} -> {Running2, _DeadNode, Task} = delete_running(Pid, Running, []), cluster_runmany(Fun, Fuse, [Task|TaskList], Nodes, Running2, Results); {'DOWN', _, _, BadPid, Reason} when Reason =/= normal -> RunningPids = lists:map(fun ({Pid, _, _}) -> Pid end, Running), handle_error(BadPid, Reason, RunningPids) end; cluster_runmany(_, _, [_Non|_Empty], []=_Nodes, []=_Running, _) -> erlang:exit(allnodescrashed). -ifdef(fun_stacktrace). runmany_wrap(Fun, Parent) -> try Fun catch exit:siblingdied -> ok; exit:Reason -> Parent ! {erlang:self(), error, Reason}; error:R -> Parent ! {erlang:self(), error, {R, erlang:get_stacktrace()}}; throw:R -> Parent ! {erlang:self(), error, {{nocatch, R}, erlang:get_stacktrace()}} end. -else. runmany_wrap(Fun, Parent) -> try Fun catch exit:siblingdied -> ok; exit:Reason -> Parent ! {erlang:self(), error, Reason}; error:R:Stacktrace -> Parent ! {erlang:self(), error, {R, Stacktrace}}; throw:R:Stacktrace -> Parent ! {erlang:self(), error, {{nocatch, R}, Stacktrace}} end. -endif. delete_running(Pid, [{Pid, Node, List}|Running], Acc) -> {Running ++ Acc, Node, List}; delete_running(Pid, [R|Running], Acc) -> delete_running(Pid, Running, [R|Acc]). handle_error(BadPid, Reason, Pids) -> lists:foreach(fun (Pid) -> erlang:exit(Pid, siblingdied) end, Pids), lists:foreach(fun (Pid) -> error_cleanup(Pid, BadPid) end, Pids), erlang:exit(Reason). error_cleanup(BadPid, BadPid) -> ok; error_cleanup(Pid, BadPid) -> receive {Pid, _} -> error_cleanup(Pid, BadPid); {Pid, _, _} -> error_cleanup(Pid, BadPid); {'DOWN', _, _, Pid, _Reason} -> ok end. normal_cleanup(Pid) -> receive {'DOWN', _, _, Pid, _Reason} -> ok end. fuse(_, []) -> []; fuse({reverse, _}=Fuse, Results) -> [RL|ResultsR] = lists:reverse(Results), fuse(Fuse, ResultsR, RL); fuse(Fuse, [R1|Results]) -> fuse(Fuse, Results, R1). fuse({reverse, FuseFunc}=Fuse, [R2|Results], R1) -> fuse(Fuse, Results, FuseFunc(R2, R1)); fuse(Fuse, [R2|Results], R1) -> fuse(Fuse, Results, Fuse(R1, R2)); fuse(_, [], R) -> R. @doc Splits a list into a list of sublists , each of size , splitmany(List, Size) -> splitmany(List, [], Size). splitmany([], Acc, _) -> lists:reverse(Acc); splitmany(List, Acc, Size) -> {Top, NList} = split(Size, List), splitmany(NList, [Top|Acc], Size). @doc Like lists : split , except it splits a list smaller than its first split(Size, List) -> split(Size, List, []). split(0, List, Acc) -> {lists:reverse(Acc), List}; split(Size, [H|List], Acc) -> split(Size - 1, List, [H|Acc]); split(_, [], Acc) -> {lists:reverse(Acc), []}.
1fdae212c077702eea63b5fbb6408673c79f4f619e3110ceee2924f77547691e
ghc/testsuite
simpl005.hs
-- !!! CPR on newtype with polymorphic argument {-# OPTIONS -O #-} module ShouldCompile where data StateM m s a = STM (s -> m (a,s)) instance Functor m => Functor (StateM m s) where fmap f (STM xs) = STM (\s -> fmap (\ (x,s') -> (f x, s')) (xs s) ) With GHC 4.04 ( first release ) this program gave : panic ! ( the ` impossible ' happened ): mk_cpr_let : not a product forall a{-ruq panic! (the `impossible' happened): mk_cpr_let: not a product rur rur -> MonadLibrary.StateM{-r2o,x-} m{-a30Y-} s{-a30Z-} a{-ruq-} rur The reason: 'Functor' is a newtype, whose element is a for-all type. newtype Functor f = Functor (forall a,b. (a->b) -> f a -> f b) -}
null
https://raw.githubusercontent.com/ghc/testsuite/998a816ae89c4fd573f4abd7c6abb346cf7ee9af/tests/simplCore/should_compile/simpl005.hs
haskell
!!! CPR on newtype with polymorphic argument # OPTIONS -O # ruq panic! (the `impossible' happened): mk_cpr_let: not a product rur rur -> MonadLibrary.StateM{-r2o,x a30Y a30Z ruq
module ShouldCompile where data StateM m s a = STM (s -> m (a,s)) instance Functor m => Functor (StateM m s) where fmap f (STM xs) = STM (\s -> fmap (\ (x,s') -> (f x, s')) (xs s) ) With GHC 4.04 ( first release ) this program gave : panic ! ( the ` impossible ' happened ): mk_cpr_let : not a product rur The reason: 'Functor' is a newtype, whose element is a for-all type. newtype Functor f = Functor (forall a,b. (a->b) -> f a -> f b) -}
1b991543716ae7e8bd34cb432586d6b4148daa3b9165b67cd8e4226055e40584
philnguyen/soft-contract
zo-shell.rkt
#lang racket/base ;; Command-line UI for exploring decompiled bytecode. ;; (Use `raco make` to generate bytecode) (provide init) (require benchmark-util (only-in racket/string string-split string-join string-trim) racket/match) (require "zo-string.rkt" "zo-transition.rkt" "zo-find.rkt" compiler/zo-parse) ;; ----------------------------------------------------------------------------- ;; --- constants & contracts ;; when set, print extra debugging information (define DEBUG #f) ;; For aesthetic purposes (define VERSION 1.0) (define VNAME "vortex") ( define - type Context ( U zo ( ) ( result ) ) ) ;(define-type History (Listof Context)) ( define - type History * ( ) ) ;; --- API functions Entry point to the REPL , expects command - line arguments passed as a list . ;; In the future, there may be more entry points. (define (init args) (match args ['#() (print-usage)] ;; Catch --help flag, and any others [(? has-any-flags?) (print-usage)] [(vector fname) (filename->shell fname)] [(vector fname args ...) (find-all fname args)])) ;; --- Commands (could go in their own file) (struct command ( name num-args aliases help-msg ) #:transparent) ;(define-type Command command) (define index? integer?) (define ALST (command "alst" 0 (list "a" "alias" "aliases") "Print command aliases")) (define BACK (command "back" 0 (list "b" "up" "u" ".." "../" "cd .." "cd ../") "Move up to the previous context")) (define DIVE (command "dive" 1 (list "d" "cd" "next" "step") "Step into struct field ARG")) (define FIND (command "find" 1 (list "f" "query" "search" "look") "Search the current subtree for structs with the name ARG")) (define HELP (command "help" 0 (list "h" "-h" "--h" "-help" "--help") "Print this message")) (define INFO (command "info" 0 (list "i" "ls" "print" "p" "show") "Show information about current context")) (define JUMP (command "jump" 0 (list "j" "warp" "top") "Revert to last saved position")) (define SAVE (command "save" 0 (list "mark") "Save the current context as jump target")) (define QUIT (command "quit" 0 (list "q" "exit" "leave" "bye") "Exit the interpreter")) (define COMMANDS (list ALST BACK DIVE FIND HELP INFO JUMP SAVE QUIT)) (define ((cmd? c) str) (define splt (string-split str)) (or ;; Special cases (and (string=? "back" (command-name c)) (member? str (list "cd .." "cd ../"))) ;; Everything else (and ;; Has the right number of arguments (= (sub1 (length splt)) (command-num-args c)) First word matches command name ( or an alias ) (or (string=? (car splt) (command-name c)) (member? (car splt) (command-aliases c)))))) ;; --- REPL Start REPL from a filename (define (filename->shell name) (print-info (format "Loading bytecode file '~a'..." name)) (call-with-input-file name (lambda (port ) (print-info "Parsing bytecode...") (define ctx (zo-parse port)) (print-info "Parsing complete!") (print-welcome) ((repl ctx '() '()) '())))) (define (zo->shell z) ;; (-> zo? void?) (print-welcome) ((repl z '() '()) '())) Split a path like " cd .. /BLAH/ .. " into a list of commands " cd .. ; ; cd .. " (define (split-cd cmd*) ( - > ( string ? ) ( listof string ? ) ) (match cmd* ['() '()] [(cons cd-cmd rest) #:when (starts-with? cd-cmd "cd ") ;; Split "cd " commands by "/" (append (map (lambda (x) (string-append "cd " x)) (string-split (substring cd-cmd 3) "/")) (split-cd rest))] [(cons cmd rest) ;; Leave other commands alone (cons cmd (split-cd rest))])) ;; The REPL loop. Process a command using context `ctx` and history `hist`. (define ((repl ctx hist pre-hist) cmd*) (when DEBUG (print-history hist)) (match cmd* ['() (print-prompt ctx) (define ln (read-line)) (if (eof-object? ln) (error 'zo-shell:repl "EOF: you have penetrated me") ((repl ctx hist pre-hist) (split-cd (for/list ([str (in-list (string-split ln ";"))]) (string-trim str)))))] [(cons (? (cmd? ALST) raw) cmd*) (print-alias) ((repl ctx hist pre-hist) cmd*)] [(cons (? (cmd? BACK) raw) cmd*) ((call-with-values (lambda () (back raw ctx hist pre-hist)) repl) cmd*)] [(cons (? (cmd? DIVE) raw) cmd*) ((call-with-values (lambda () (dive raw ctx hist pre-hist)) repl) cmd*)] [(cons (? (cmd? FIND) raw) cmd*) ((call-with-values (lambda () (find raw ctx hist pre-hist)) repl) cmd*)] [(cons (? (cmd? HELP) raw) cmd*) (begin (print-help) ((repl ctx hist pre-hist) cmd*))] [(cons (? (cmd? INFO) raw) cmd*) (begin (print-context ctx) ((repl ctx hist pre-hist) cmd*))] [(cons (? (cmd? JUMP) raw) cmd*) ((call-with-values (lambda () (jump raw ctx hist pre-hist)) repl) cmd*)] [(cons (? (cmd? SAVE) raw) cmd*) ((call-with-values (lambda () (save raw ctx hist pre-hist)) repl) cmd*)] [(cons (? (cmd? QUIT) raw) cmd*) (print-goodbye)] [(cons raw cmd*) (begin (print-unknown raw) ((repl ctx hist pre-hist) cmd*))])) ;; --- command implementations 2015 - 01 - 23 : Warn about possible - unexpected behavior (define BACK-WARNING (string-append "BACK removing most recent 'save' mark. " "Be sure to save if you want to continue exploring search result.")) ;; Step back to a previous context, if any, and reduce the history. ;; Try popping from `hist`, fall back to list-of-histories `pre-hist`. (define (back raw ctx hist pre-hist) (match (list hist pre-hist) [(list '() '()) ;; Nothing to pop from (print-unknown raw) (values ctx hist pre-hist)] [(list '() _) ;; Pop from pre-history (displayln BACK-WARNING) (define-values (hist* pre-hist*) (pop pre-hist)) (back raw ctx hist* pre-hist*)] [_ (define-values (ctx* hist*) (pop hist)) (values ctx* hist* pre-hist)])) ;; Search context `ctx` for a new context matching string `raw`. ;; Push `ctx` onto the stack `hist` on success. (define (dive raw ctx hist pre-hist) (define arg (split-snd raw)) (define-values (ctx* hist*) (cond [(not arg) ;; Failed to parse argument, (print-unknown raw) (values ctx hist)] [(list? ctx) ;; Context is a list, try accessing by index (dive-list ctx hist arg)] [(zo? ctx) ;; Context is a zo, try looking up field (dive-zo ctx hist arg)] [else ;; Should never happen! REPL controls the context. (error 'zo-shell:dive (format "Invalid context '~a'" ctx))])) ;; Return pre-hist unchanged (values ctx* hist* pre-hist)) ;; Parse the string `arg` to an integer n. ;; If n is within the bounds of the list `ctx`, ;; push `ctx` onto the stack `hist` and return the n-th element of `ctx`. ;; Otherwise, return `ctx` and `hist` unchanged. (define (dive-list ctx hist arg) (define index (string->number arg)) (cond [(or (not index) (not (index? index)) (< index 0) (>= index (length ctx))) ;; Index out of bounds, or not a number. Cannot dive. (print-unknown (format "dive ~a" arg)) (values ctx hist)] [else ;; Select from list, (define res (list-ref ctx index)) ;; If list elements are search results, current `hist` can be safely ignored. (if (result? res) (values (result-zo res) (result-path res)) (values res (push hist ctx)))])) ;; Use the string `field` to access a field in the zo struct `ctx`. ;; If the field exists and denotes another zo struct, return that ;; struct and push `ctx` on to the stack `hist`. ;; Otherwise, return `ctx` and `hist` unchanged. (define (dive-zo ctx hist field) (define-values (ctx* success?) (zo-transition ctx field)) (cond [success? (values ctx* (push hist ctx))] [else (print-unknown (format "dive ~a" field)) (values ctx hist)])) Parse argument , then search for & save results . (define (find raw ctx hist pre-hist) (define arg (split-snd raw)) (cond [(and arg (zo? ctx)) (define results (zo-find ctx arg)) (printf "FIND returned ~a results\n" (length results)) (match results ['() ;; No results, don't make a save mark (values ctx hist pre-hist)] [_ Success ! Show the results and save them , to allow jumps (printf "FIND automatically saving context\n") (print-context results) (save "" results (push hist ctx) pre-hist)])] [else (print-unknown raw) (values ctx hist pre-hist)])) ;; Jump back to a previously-saved location, if any. (define (jump raw ctx hist pre-hist) (match pre-hist ['() ;; Nothing to jump to (print-unknown raw) (values ctx hist pre-hist)] [_ (define-values (hist* pre-hist*) (pop pre-hist)) (back raw ctx hist* pre-hist*)])) ;; Save the current context and history to the pre-history ;; For now, erases current history. (define (save raw ctx hist pre-hist) (values ctx '() (push pre-hist (push hist ctx)))) ;; --- history manipulation ;; Add the context `ctx` to the stack `hist`. (define (push hist ctx) (cons ctx hist)) ;; Remove the top context from the stack `hist`. ;; Return the popped value and tail of `hist`. ;; Callers must avoid calling `pop` on empty stacks. (define (pop hist) (values (car hist) (cdr hist))) ;; --- print (define (print-alias) ;; (-> void?) (displayln "At your service. Command aliases:") (displayln (string-join (for/list ([cmd COMMANDS]) (format " ~a ~a" (command-name cmd) (string-join (command-aliases cmd)))))) (newline)) ;; Print a history object. (define (print-history hist) ;; (-> history? void?) (printf "History is: ~a\n" hist)) ;; Print a help message for the REPL. (define (print-help) ;; (-> void?) (displayln "At your service. Available commands:") (displayln (string-join (for/list ([cmd COMMANDS]) (format " ~a~a ~a" (command-name cmd) (if (= 1 (command-num-args cmd)) " ARG" " ") ;; hack (command-help-msg cmd))) "\n"))) ;; Print a context. (define (print-context ctx) ;; (-> context? void?) (match ctx [(? zo?) (displayln (zo->string ctx))] ['() (displayln "'()")] [(cons x _) (define z (if (result? x) (result-zo x) x)) (printf "~a[~a]\n" (zo->string z #:deep? #f) (length ctx))] [_ (error 'zo-shell:info (format "Unknown context '~a'" ctx))])) ;; Print an error message (after receiving an undefined/invalid command). (define (print-unknown raw) (printf "'~a' not permitted.\n" raw)) ;; Print a goodbye message (when the user exits the REPL). (define (print-goodbye) (printf "Ascending to second-level meditation. Goodbye.\n\n")) ;; Print a debugging message. (define (print-debug str) ;; (-> string? void?) (printf "DEBUG: ~a\n" str)) ;; Print a welcome message (when the user enters the REPL). (define (print-welcome) (display (format "\033[1;34m--- Welcome to the .zo shell, version ~a '~a' ---\033[0;0m\n" VERSION VNAME))) ;; Print the REPL prompt. (define (print-prompt ctx) (define tag (cond [(list? ctx) (format "[~a]" (length ctx))] [(zo? ctx) (format "(~a)" (car (zo->spec ctx)))] [else ""])) (display (string-append tag " \033[1;32mzo> \033[0;0m"))) ;; Print an informative message. (define (print-info str) ;; (-> string? void?) (printf "INFO: ~a\n" str)) ;; Print a warning. (define (print-warn str) ;; (-> string? void?) (printf "WARN: ~a\n" str)) ;; Print an error message. (define (print-error str) ;; (-> string? void?) (printf "ERROR: ~a\n" str)) ;; Print usage information. (define USAGE "Usage: zo-shell <OPTIONS> FILE.zo") (define (print-usage) (displayln USAGE)) ;; --- misc (define (member? s str*) (if (member s str*) #t #f)) Check if second arg is a prefix of the first (define (starts-with? str prefix) ;; (-> string? string? boolean?) (and (<= (string-length prefix) (string-length str)) (for/and ([c1 (in-string str)] [c2 (in-string prefix)]) (char=? c1 c2)))) (define (find-all name args #:limit [lim #f]) (print-info (format "Loading bytecode file '~a'..." name)) (call-with-input-file name (lambda (port) (print-info "Parsing bytecode...") (define ctx (zo-parse port)) (print-info "Parsing complete! Searching...") (for ([arg (in-list args)]) (printf "FIND '~a' : " arg) (printf "~a results\n" (length (zo-find ctx arg #:limit lim)))) (displayln "All done!")))) ;; Split the string `raw` by whitespace and return the second element of the split , if any . ;; Otherwise return `#f`. (define (split-snd raw) (define splt (string-split raw)) (match splt [(list _ x) x] [(list _ x ys ...) (print-warn (format "Ignoring extra arguments: '~a'" ys)) x] [_ #f])) ;; True if the vector contains any command-line flags. ;; All flags begin with a hyphen, - (define (has-any-flags? v) ;; (-> (vectorof string) boolean?) (for/or ([str (in-vector v)]) (and (< 0 (string-length str)) (eq? #\- (string-ref str 0)))))
null
https://raw.githubusercontent.com/philnguyen/soft-contract/5e07dc2d622ee80b961f4e8aebd04ce950720239/soft-contract/test/gradual-typing-benchmarks/zordoz.6.3/zo-shell.rkt
racket
Command-line UI for exploring decompiled bytecode. (Use `raco make` to generate bytecode) ----------------------------------------------------------------------------- --- constants & contracts when set, print extra debugging information For aesthetic purposes (define-type History (Listof Context)) --- API functions In the future, there may be more entry points. Catch --help flag, and any others --- Commands (could go in their own file) (define-type Command command) Special cases Everything else Has the right number of arguments --- REPL (-> zo? void?) Split "cd " commands by "/" Leave other commands alone The REPL loop. Process a command using context `ctx` and history `hist`. --- command implementations Step back to a previous context, if any, and reduce the history. Try popping from `hist`, fall back to list-of-histories `pre-hist`. Nothing to pop from Pop from pre-history Search context `ctx` for a new context matching string `raw`. Push `ctx` onto the stack `hist` on success. Failed to parse argument, Context is a list, try accessing by index Context is a zo, try looking up field Should never happen! REPL controls the context. Return pre-hist unchanged Parse the string `arg` to an integer n. If n is within the bounds of the list `ctx`, push `ctx` onto the stack `hist` and return the n-th element of `ctx`. Otherwise, return `ctx` and `hist` unchanged. Index out of bounds, or not a number. Cannot dive. Select from list, If list elements are search results, current `hist` can be safely ignored. Use the string `field` to access a field in the zo struct `ctx`. If the field exists and denotes another zo struct, return that struct and push `ctx` on to the stack `hist`. Otherwise, return `ctx` and `hist` unchanged. No results, don't make a save mark Jump back to a previously-saved location, if any. Nothing to jump to Save the current context and history to the pre-history For now, erases current history. --- history manipulation Add the context `ctx` to the stack `hist`. Remove the top context from the stack `hist`. Return the popped value and tail of `hist`. Callers must avoid calling `pop` on empty stacks. --- print (-> void?) Print a history object. (-> history? void?) Print a help message for the REPL. (-> void?) hack Print a context. (-> context? void?) Print an error message (after receiving an undefined/invalid command). Print a goodbye message (when the user exits the REPL). Print a debugging message. (-> string? void?) Print a welcome message (when the user enters the REPL). Print the REPL prompt. Print an informative message. (-> string? void?) Print a warning. (-> string? void?) Print an error message. (-> string? void?) Print usage information. --- misc (-> string? string? boolean?) Split the string `raw` by whitespace and Otherwise return `#f`. True if the vector contains any command-line flags. All flags begin with a hyphen, - (-> (vectorof string) boolean?)
#lang racket/base (provide init) (require benchmark-util (only-in racket/string string-split string-join string-trim) racket/match) (require "zo-string.rkt" "zo-transition.rkt" "zo-find.rkt" compiler/zo-parse) (define DEBUG #f) (define VERSION 1.0) (define VNAME "vortex") ( define - type Context ( U zo ( ) ( result ) ) ) ( define - type History * ( ) ) Entry point to the REPL , expects command - line arguments passed as a list . (define (init args) (match args ['#() (print-usage)] [(? has-any-flags?) (print-usage)] [(vector fname) (filename->shell fname)] [(vector fname args ...) (find-all fname args)])) (struct command ( name num-args aliases help-msg ) #:transparent) (define index? integer?) (define ALST (command "alst" 0 (list "a" "alias" "aliases") "Print command aliases")) (define BACK (command "back" 0 (list "b" "up" "u" ".." "../" "cd .." "cd ../") "Move up to the previous context")) (define DIVE (command "dive" 1 (list "d" "cd" "next" "step") "Step into struct field ARG")) (define FIND (command "find" 1 (list "f" "query" "search" "look") "Search the current subtree for structs with the name ARG")) (define HELP (command "help" 0 (list "h" "-h" "--h" "-help" "--help") "Print this message")) (define INFO (command "info" 0 (list "i" "ls" "print" "p" "show") "Show information about current context")) (define JUMP (command "jump" 0 (list "j" "warp" "top") "Revert to last saved position")) (define SAVE (command "save" 0 (list "mark") "Save the current context as jump target")) (define QUIT (command "quit" 0 (list "q" "exit" "leave" "bye") "Exit the interpreter")) (define COMMANDS (list ALST BACK DIVE FIND HELP INFO JUMP SAVE QUIT)) (define ((cmd? c) str) (define splt (string-split str)) (or (and (string=? "back" (command-name c)) (member? str (list "cd .." "cd ../"))) (and (= (sub1 (length splt)) (command-num-args c)) First word matches command name ( or an alias ) (or (string=? (car splt) (command-name c)) (member? (car splt) (command-aliases c)))))) Start REPL from a filename (define (filename->shell name) (print-info (format "Loading bytecode file '~a'..." name)) (call-with-input-file name (lambda (port ) (print-info "Parsing bytecode...") (define ctx (zo-parse port)) (print-info "Parsing complete!") (print-welcome) ((repl ctx '() '()) '())))) (define (zo->shell z) (print-welcome) ((repl z '() '()) '())) Split a path like " cd .. /BLAH/ .. " into a list of commands " cd .. ; ; cd .. " (define (split-cd cmd*) ( - > ( string ? ) ( listof string ? ) ) (match cmd* ['() '()] [(cons cd-cmd rest) #:when (starts-with? cd-cmd "cd ") (append (map (lambda (x) (string-append "cd " x)) (string-split (substring cd-cmd 3) "/")) (split-cd rest))] [(cons cmd rest) (cons cmd (split-cd rest))])) (define ((repl ctx hist pre-hist) cmd*) (when DEBUG (print-history hist)) (match cmd* ['() (print-prompt ctx) (define ln (read-line)) (if (eof-object? ln) (error 'zo-shell:repl "EOF: you have penetrated me") ((repl ctx hist pre-hist) (split-cd (for/list ([str (in-list (string-split ln ";"))]) (string-trim str)))))] [(cons (? (cmd? ALST) raw) cmd*) (print-alias) ((repl ctx hist pre-hist) cmd*)] [(cons (? (cmd? BACK) raw) cmd*) ((call-with-values (lambda () (back raw ctx hist pre-hist)) repl) cmd*)] [(cons (? (cmd? DIVE) raw) cmd*) ((call-with-values (lambda () (dive raw ctx hist pre-hist)) repl) cmd*)] [(cons (? (cmd? FIND) raw) cmd*) ((call-with-values (lambda () (find raw ctx hist pre-hist)) repl) cmd*)] [(cons (? (cmd? HELP) raw) cmd*) (begin (print-help) ((repl ctx hist pre-hist) cmd*))] [(cons (? (cmd? INFO) raw) cmd*) (begin (print-context ctx) ((repl ctx hist pre-hist) cmd*))] [(cons (? (cmd? JUMP) raw) cmd*) ((call-with-values (lambda () (jump raw ctx hist pre-hist)) repl) cmd*)] [(cons (? (cmd? SAVE) raw) cmd*) ((call-with-values (lambda () (save raw ctx hist pre-hist)) repl) cmd*)] [(cons (? (cmd? QUIT) raw) cmd*) (print-goodbye)] [(cons raw cmd*) (begin (print-unknown raw) ((repl ctx hist pre-hist) cmd*))])) 2015 - 01 - 23 : Warn about possible - unexpected behavior (define BACK-WARNING (string-append "BACK removing most recent 'save' mark. " "Be sure to save if you want to continue exploring search result.")) (define (back raw ctx hist pre-hist) (match (list hist pre-hist) [(list '() '()) (print-unknown raw) (values ctx hist pre-hist)] [(list '() _) (displayln BACK-WARNING) (define-values (hist* pre-hist*) (pop pre-hist)) (back raw ctx hist* pre-hist*)] [_ (define-values (ctx* hist*) (pop hist)) (values ctx* hist* pre-hist)])) (define (dive raw ctx hist pre-hist) (define arg (split-snd raw)) (define-values (ctx* hist*) (cond [(not arg) (print-unknown raw) (values ctx hist)] [(list? ctx) (dive-list ctx hist arg)] [(zo? ctx) (dive-zo ctx hist arg)] [else (error 'zo-shell:dive (format "Invalid context '~a'" ctx))])) (values ctx* hist* pre-hist)) (define (dive-list ctx hist arg) (define index (string->number arg)) (cond [(or (not index) (not (index? index)) (< index 0) (>= index (length ctx))) (print-unknown (format "dive ~a" arg)) (values ctx hist)] [else (define res (list-ref ctx index)) (if (result? res) (values (result-zo res) (result-path res)) (values res (push hist ctx)))])) (define (dive-zo ctx hist field) (define-values (ctx* success?) (zo-transition ctx field)) (cond [success? (values ctx* (push hist ctx))] [else (print-unknown (format "dive ~a" field)) (values ctx hist)])) Parse argument , then search for & save results . (define (find raw ctx hist pre-hist) (define arg (split-snd raw)) (cond [(and arg (zo? ctx)) (define results (zo-find ctx arg)) (printf "FIND returned ~a results\n" (length results)) (match results ['() (values ctx hist pre-hist)] [_ Success ! Show the results and save them , to allow jumps (printf "FIND automatically saving context\n") (print-context results) (save "" results (push hist ctx) pre-hist)])] [else (print-unknown raw) (values ctx hist pre-hist)])) (define (jump raw ctx hist pre-hist) (match pre-hist ['() (print-unknown raw) (values ctx hist pre-hist)] [_ (define-values (hist* pre-hist*) (pop pre-hist)) (back raw ctx hist* pre-hist*)])) (define (save raw ctx hist pre-hist) (values ctx '() (push pre-hist (push hist ctx)))) (define (push hist ctx) (cons ctx hist)) (define (pop hist) (values (car hist) (cdr hist))) (define (print-alias) (displayln "At your service. Command aliases:") (displayln (string-join (for/list ([cmd COMMANDS]) (format " ~a ~a" (command-name cmd) (string-join (command-aliases cmd)))))) (newline)) (define (print-history hist) (printf "History is: ~a\n" hist)) (define (print-help) (displayln "At your service. Available commands:") (displayln (string-join (for/list ([cmd COMMANDS]) (format " ~a~a ~a" (command-name cmd) (command-help-msg cmd))) "\n"))) (define (print-context ctx) (match ctx [(? zo?) (displayln (zo->string ctx))] ['() (displayln "'()")] [(cons x _) (define z (if (result? x) (result-zo x) x)) (printf "~a[~a]\n" (zo->string z #:deep? #f) (length ctx))] [_ (error 'zo-shell:info (format "Unknown context '~a'" ctx))])) (define (print-unknown raw) (printf "'~a' not permitted.\n" raw)) (define (print-goodbye) (printf "Ascending to second-level meditation. Goodbye.\n\n")) (define (print-debug str) (printf "DEBUG: ~a\n" str)) (define (print-welcome) (display (format "\033[1;34m--- Welcome to the .zo shell, version ~a '~a' ---\033[0;0m\n" VERSION VNAME))) (define (print-prompt ctx) (define tag (cond [(list? ctx) (format "[~a]" (length ctx))] [(zo? ctx) (format "(~a)" (car (zo->spec ctx)))] [else ""])) (display (string-append tag " \033[1;32mzo> \033[0;0m"))) (define (print-info str) (printf "INFO: ~a\n" str)) (define (print-warn str) (printf "WARN: ~a\n" str)) (define (print-error str) (printf "ERROR: ~a\n" str)) (define USAGE "Usage: zo-shell <OPTIONS> FILE.zo") (define (print-usage) (displayln USAGE)) (define (member? s str*) (if (member s str*) #t #f)) Check if second arg is a prefix of the first (define (starts-with? str prefix) (and (<= (string-length prefix) (string-length str)) (for/and ([c1 (in-string str)] [c2 (in-string prefix)]) (char=? c1 c2)))) (define (find-all name args #:limit [lim #f]) (print-info (format "Loading bytecode file '~a'..." name)) (call-with-input-file name (lambda (port) (print-info "Parsing bytecode...") (define ctx (zo-parse port)) (print-info "Parsing complete! Searching...") (for ([arg (in-list args)]) (printf "FIND '~a' : " arg) (printf "~a results\n" (length (zo-find ctx arg #:limit lim)))) (displayln "All done!")))) return the second element of the split , if any . (define (split-snd raw) (define splt (string-split raw)) (match splt [(list _ x) x] [(list _ x ys ...) (print-warn (format "Ignoring extra arguments: '~a'" ys)) x] [_ #f])) (define (has-any-flags? v) (for/or ([str (in-vector v)]) (and (< 0 (string-length str)) (eq? #\- (string-ref str 0)))))
84ba9844801e769918f1d95ab8b660472efed2cbf3157166ba6714bb05956338
mrphlip/aoc
06.hs
# OPTIONS_GHC -Wno - tabs # import Data.List import Control.Exception import Utils type Stacks = [[Char]] type Move = (Integer, Integer, Integer) getInput :: IO String getInput = readFile "06.txt" findSingleton :: Integer -> String -> Integer findSingleton n s = (+n) $ genericLength $ takeWhile ((/=n).genericLength.nub) $ window n s tests :: IO () tests = do check $ map (findSingleton 4) testData == [7, 5, 6, 10, 11] check $ map (findSingleton 14) testData == [19, 23, 23, 29, 26] where testData = [ "mjqjpqmgbljsphdztnvjfqwrcgsmlb", "bvwbjplbgvbhsrlpgdmjqwftvncz", "nppdvjthqldpwncqszvftbrmjlhg", "nznrnfrfntjfmvfwmzdfjlvtqnbhcprsg", "zcfzfwzzqfrljwzlrfnpqdbhtmscgvjw"] check True = return () check False = throwIO $ AssertionFailed "test failed" main :: IO () main = do tests dat <- getInput print $ findSingleton 4 dat print $ findSingleton 14 dat
null
https://raw.githubusercontent.com/mrphlip/aoc/65bd3b3801dde8050cd585f1f1d3815d47964c9a/2022/06.hs
haskell
# OPTIONS_GHC -Wno - tabs # import Data.List import Control.Exception import Utils type Stacks = [[Char]] type Move = (Integer, Integer, Integer) getInput :: IO String getInput = readFile "06.txt" findSingleton :: Integer -> String -> Integer findSingleton n s = (+n) $ genericLength $ takeWhile ((/=n).genericLength.nub) $ window n s tests :: IO () tests = do check $ map (findSingleton 4) testData == [7, 5, 6, 10, 11] check $ map (findSingleton 14) testData == [19, 23, 23, 29, 26] where testData = [ "mjqjpqmgbljsphdztnvjfqwrcgsmlb", "bvwbjplbgvbhsrlpgdmjqwftvncz", "nppdvjthqldpwncqszvftbrmjlhg", "nznrnfrfntjfmvfwmzdfjlvtqnbhcprsg", "zcfzfwzzqfrljwzlrfnpqdbhtmscgvjw"] check True = return () check False = throwIO $ AssertionFailed "test failed" main :: IO () main = do tests dat <- getInput print $ findSingleton 4 dat print $ findSingleton 14 dat
d2c556daf063d348729bdf7d41e53695666f3de23bf3409af346083f2471b728
hiroshi-unno/coar
solver.ml
open Core open Common open Common.Ext open Ast open Ast.LogicOld module Make (Cfg: Config.ConfigType) = struct let config = Cfg.config module Debug = Debug.Make (val Debug.Config.(if config.verbose then enable else disable)) let ctx = let options = match config.timeout with | None -> [] | Some timeout -> ["timeout", string_of_int @@ timeout * 1000] in Z3.mk_context options let solver = Z3.Fixedpoint.mk_fixedpoint ctx let solve ?(print_sol=false) pcsp = assert (Set.Poly.is_empty @@ PCSP.Problem.wfpvs_of pcsp && Set.Poly.is_empty @@ PCSP.Problem.fnpvs_of pcsp ToDo : check if pcsp is of CHC let pcsp = pcsp |> PCSP.Problem.to_nnf |> PCSP.Problem.to_cnf in let cls = pcsp |> PCSP.Problem.clauses_of in let dtenv = Z3Smt.Z3interface.z3_dtenv_of_dtenv ctx @@ PCSP.Problem.dtenv_of pcsp in let query_name = "__query__" in let exi_senv = Map.Poly.add_exn (PCSP.Problem.senv_of pcsp) ~key:(Ident.Tvar query_name) ~data:Logic.BoolTerm.SBool in let fenv = PCSP.Problem.fenv_of pcsp in let penv = List.map (Map.Poly.to_alist @@ exi_senv) ~f:(fun (Ident.Tvar name, sort) -> let arg_sorts = Logic.Sort.args_of sort |> List.map ~f:(fun s -> Z3Smt.Z3interface.of_sort ctx dtenv @@ Logic.ExtTerm.to_old_sort s) in let symbol = Z3.Symbol.mk_string ctx name in let func_decl = Z3.FuncDecl.mk_func_decl ctx symbol arg_sorts (Z3.Boolean.mk_sort ctx) in (Ident.Pvar name, func_decl)) in List.iter ~f:(fun (_, funcdecl) -> Z3.Fixedpoint.register_relation solver funcdecl) penv; Set.Poly.iter cls ~f:(fun (uni_senv, ps, ns, phi) -> (** assume that [phi] is alpha-renamed *) let lenv = Logic.Term.let_sort_env_of phi in let uni_senv' = Map.force_merge uni_senv lenv in let ps = match Set.Poly.length ps with | 0 -> Set.Poly.singleton (Atom.mk_app (Predicate.mk_var (Ident.Pvar query_name) []) []) | 1 -> Set.Poly.map ps ~f:(fun t -> Logic.ExtTerm.to_old_atom exi_senv uni_senv t []) | _ -> assert false in let ns = Set.Poly.map ns ~f:(fun t -> Logic.ExtTerm.to_old_atom exi_senv uni_senv t []) in let body = Formula.mk_neg (Logic.ExtTerm.to_old_formula exi_senv uni_senv phi [] |> Normalizer.normalize_let |> Formula.equivalent_valid) :: (ns |> Set.Poly.map ~f:Formula.mk_atom |> Set.Poly.to_list) |> Formula.and_of in let head = ps |> Set.Poly.map ~f:Formula.mk_atom |> Set.Poly.to_list |> Formula.and_of in let phi' = Formula.mk_imply body head in Debug.print @@ lazy (Formula.str_of phi'); let tenv = Map.Poly.to_alist uni_senv' |> List.map ~f:(fun (x, s) -> x, Logic.ExtTerm.to_old_sort s) in let c = Z3Smt.Z3interface.of_formula ctx tenv penv fenv dtenv phi' in Z3.Fixedpoint.add_rule solver c None); try let solution = match Z3.Fixedpoint.query_r solver [List.Assoc.find_exn penv ~equal:Stdlib.(=) (Ident.Pvar query_name)] with | Z3.Solver.UNSATISFIABLE -> PCSP.Problem.Sat Map.Poly.empty(** ToDo: return a solution *) | Z3.Solver.SATISFIABLE -> PCSP.Problem.Unsat | Z3.Solver.UNKNOWN -> PCSP.Problem.Unknown in if print_sol then print_endline (PCSP.Problem.str_of_solution solution); Or_error.return solution with | Z3.Error reason -> if String.(reason = "spacer canceled" || reason = "canceled") then ToDo else begin Debug.print @@ lazy (Printf.sprintf "Z3 Error: %s" reason); Or_error.return (PCSP.Problem.Unknown) (* Or_error.error_string reason*) end end
null
https://raw.githubusercontent.com/hiroshi-unno/coar/90a23a09332c68f380efd4115b3f6fdc825f413d/lib/SPACER/solver.ml
ocaml
* assume that [phi] is alpha-renamed * ToDo: return a solution Or_error.error_string reason
open Core open Common open Common.Ext open Ast open Ast.LogicOld module Make (Cfg: Config.ConfigType) = struct let config = Cfg.config module Debug = Debug.Make (val Debug.Config.(if config.verbose then enable else disable)) let ctx = let options = match config.timeout with | None -> [] | Some timeout -> ["timeout", string_of_int @@ timeout * 1000] in Z3.mk_context options let solver = Z3.Fixedpoint.mk_fixedpoint ctx let solve ?(print_sol=false) pcsp = assert (Set.Poly.is_empty @@ PCSP.Problem.wfpvs_of pcsp && Set.Poly.is_empty @@ PCSP.Problem.fnpvs_of pcsp ToDo : check if pcsp is of CHC let pcsp = pcsp |> PCSP.Problem.to_nnf |> PCSP.Problem.to_cnf in let cls = pcsp |> PCSP.Problem.clauses_of in let dtenv = Z3Smt.Z3interface.z3_dtenv_of_dtenv ctx @@ PCSP.Problem.dtenv_of pcsp in let query_name = "__query__" in let exi_senv = Map.Poly.add_exn (PCSP.Problem.senv_of pcsp) ~key:(Ident.Tvar query_name) ~data:Logic.BoolTerm.SBool in let fenv = PCSP.Problem.fenv_of pcsp in let penv = List.map (Map.Poly.to_alist @@ exi_senv) ~f:(fun (Ident.Tvar name, sort) -> let arg_sorts = Logic.Sort.args_of sort |> List.map ~f:(fun s -> Z3Smt.Z3interface.of_sort ctx dtenv @@ Logic.ExtTerm.to_old_sort s) in let symbol = Z3.Symbol.mk_string ctx name in let func_decl = Z3.FuncDecl.mk_func_decl ctx symbol arg_sorts (Z3.Boolean.mk_sort ctx) in (Ident.Pvar name, func_decl)) in List.iter ~f:(fun (_, funcdecl) -> Z3.Fixedpoint.register_relation solver funcdecl) penv; Set.Poly.iter cls ~f:(fun (uni_senv, ps, ns, phi) -> let lenv = Logic.Term.let_sort_env_of phi in let uni_senv' = Map.force_merge uni_senv lenv in let ps = match Set.Poly.length ps with | 0 -> Set.Poly.singleton (Atom.mk_app (Predicate.mk_var (Ident.Pvar query_name) []) []) | 1 -> Set.Poly.map ps ~f:(fun t -> Logic.ExtTerm.to_old_atom exi_senv uni_senv t []) | _ -> assert false in let ns = Set.Poly.map ns ~f:(fun t -> Logic.ExtTerm.to_old_atom exi_senv uni_senv t []) in let body = Formula.mk_neg (Logic.ExtTerm.to_old_formula exi_senv uni_senv phi [] |> Normalizer.normalize_let |> Formula.equivalent_valid) :: (ns |> Set.Poly.map ~f:Formula.mk_atom |> Set.Poly.to_list) |> Formula.and_of in let head = ps |> Set.Poly.map ~f:Formula.mk_atom |> Set.Poly.to_list |> Formula.and_of in let phi' = Formula.mk_imply body head in Debug.print @@ lazy (Formula.str_of phi'); let tenv = Map.Poly.to_alist uni_senv' |> List.map ~f:(fun (x, s) -> x, Logic.ExtTerm.to_old_sort s) in let c = Z3Smt.Z3interface.of_formula ctx tenv penv fenv dtenv phi' in Z3.Fixedpoint.add_rule solver c None); try let solution = match Z3.Fixedpoint.query_r solver [List.Assoc.find_exn penv ~equal:Stdlib.(=) (Ident.Pvar query_name)] with | Z3.Solver.SATISFIABLE -> PCSP.Problem.Unsat | Z3.Solver.UNKNOWN -> PCSP.Problem.Unknown in if print_sol then print_endline (PCSP.Problem.str_of_solution solution); Or_error.return solution with | Z3.Error reason -> if String.(reason = "spacer canceled" || reason = "canceled") then ToDo else begin Debug.print @@ lazy (Printf.sprintf "Z3 Error: %s" reason); Or_error.return (PCSP.Problem.Unknown) end end
b02215be002cbd698e0b4305613ef25c34d22ed4c23f8fa63365aadd76b99364
Clojure2D/clojure2d-examples
ray.clj
(ns rt4.in-one-weekend.ch08b.ray (:require [fastmath.vector :as v] [fastmath.core :as m])) (set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) (m/use-primitive-operators) (defprotocol RayProto (at [ray t])) (defrecord Ray [origin direction] RayProto (at [_ t] (v/add origin (v/mult direction t)))) (defn ray [origin direction] (->Ray origin direction))
null
https://raw.githubusercontent.com/Clojure2D/clojure2d-examples/ead92d6f17744b91070e6308157364ad4eab8a1b/src/rt4/in_one_weekend/ch08b/ray.clj
clojure
(ns rt4.in-one-weekend.ch08b.ray (:require [fastmath.vector :as v] [fastmath.core :as m])) (set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) (m/use-primitive-operators) (defprotocol RayProto (at [ray t])) (defrecord Ray [origin direction] RayProto (at [_ t] (v/add origin (v/mult direction t)))) (defn ray [origin direction] (->Ray origin direction))
80de30b5a9772e8a0881883d68eeb0fc135ce5ce387585e3132a7ac60761e461
shriphani/sleipnir
handler.clj
(ns sleipnir.handler (:require [cheshire.core :refer :all] [clojure.java.io :as io] [clojure.string :as string] [compojure.core :refer :all] [ring.middleware.resource :refer [wrap-resource]] [ring.middleware.file-info :refer [wrap-file-info]] [ring.middleware.json :as middleware] [hiccup.middleware :refer [wrap-base-url]] [compojure.handler :as handler] [compojure.route :as route] [sleipnir.core :as core] [org.httpkit.server :as server] [heritrix-clojure.core :as heritrix]) (:import [java.io StringReader] [java.net URLDecoder] [org.apache.commons.lang3 StringEscapeUtils])) (defn init [] (println "sleipnir is starting")) (defn destroy [] (println "sleipnir is shutting down")) (def app-config (atom {:extractor core/extract-anchors :port 3000 :archive? false :writer core/write-clj-obj})) (defn process-request [request] [(-> request :params :url (URLDecoder/decode "UTF-8")) (-> request :params :body (StringEscapeUtils/unescapeHtml4))]) (defn extractor [extractor-routine request] (let [[decoded-uri unescaped-html] (process-request request)] (generate-string (extractor-routine decoded-uri unescaped-html)))) (defn writer [writer-routine request out-file] (when out-file (let [wrtr (io/writer out-file :append true) [decoded-uri unescaped-html] (process-request request)] (writer-routine decoded-uri unescaped-html wrtr) (.close wrtr)))) (defroutes app-routes (POST "/extract" request (extractor (:extractor @app-config) request)) (POST "/write" request (writer (:writer @app-config) request (:out-file @app-config)))) (defn crawl "Sets up a crawl. Expects heritrix to be running!!" [config] (let [heritrix-engine-addr (:heritrix-addr config) job-dir (:job-dir config) heritrix-uname (:username config) password (:password config) seeds (:seeds-file config) job-name (-> job-dir (string/split #"/") last) new-config (merge config {:extractor-address (str ":" (or (:port config) (:port @app-config)) "/extract") :writer-address (if (:out-file config) (str ":" (or (:port config) (:port @app-config)) "/write") "blank")})] (do (swap! app-config merge new-config) ; resolve the config ;; spin up webservice (server/run-server (handler/site #'app-routes) {:port (:port @app-config)}) ;; create the directory (when-not (.exists (io/as-file job-dir)) (.mkdir (io/as-file job-dir))) ;; generate-config-file (let [new-config-file (core/generate-config-file @app-config)] (spit (str job-dir "/crawler-beans.cxml") new-config-file)) ;; add-job to heritrix (heritrix/add heritrix-engine-addr job-dir heritrix-uname password) (let [job-addr (str heritrix-engine-addr "/job/" job-name)] ;; build (heritrix/build job-addr heritrix-uname password) ;; launch (heritrix/launch job-addr heritrix-uname password) (str "Job is launched at: " job-addr)))))
null
https://raw.githubusercontent.com/shriphani/sleipnir/2eeb711c63cea61ba25dba46e1144cfd59e4f1dc/src/sleipnir/handler.clj
clojure
resolve the config spin up webservice create the directory generate-config-file add-job to heritrix build launch
(ns sleipnir.handler (:require [cheshire.core :refer :all] [clojure.java.io :as io] [clojure.string :as string] [compojure.core :refer :all] [ring.middleware.resource :refer [wrap-resource]] [ring.middleware.file-info :refer [wrap-file-info]] [ring.middleware.json :as middleware] [hiccup.middleware :refer [wrap-base-url]] [compojure.handler :as handler] [compojure.route :as route] [sleipnir.core :as core] [org.httpkit.server :as server] [heritrix-clojure.core :as heritrix]) (:import [java.io StringReader] [java.net URLDecoder] [org.apache.commons.lang3 StringEscapeUtils])) (defn init [] (println "sleipnir is starting")) (defn destroy [] (println "sleipnir is shutting down")) (def app-config (atom {:extractor core/extract-anchors :port 3000 :archive? false :writer core/write-clj-obj})) (defn process-request [request] [(-> request :params :url (URLDecoder/decode "UTF-8")) (-> request :params :body (StringEscapeUtils/unescapeHtml4))]) (defn extractor [extractor-routine request] (let [[decoded-uri unescaped-html] (process-request request)] (generate-string (extractor-routine decoded-uri unescaped-html)))) (defn writer [writer-routine request out-file] (when out-file (let [wrtr (io/writer out-file :append true) [decoded-uri unescaped-html] (process-request request)] (writer-routine decoded-uri unescaped-html wrtr) (.close wrtr)))) (defroutes app-routes (POST "/extract" request (extractor (:extractor @app-config) request)) (POST "/write" request (writer (:writer @app-config) request (:out-file @app-config)))) (defn crawl "Sets up a crawl. Expects heritrix to be running!!" [config] (let [heritrix-engine-addr (:heritrix-addr config) job-dir (:job-dir config) heritrix-uname (:username config) password (:password config) seeds (:seeds-file config) job-name (-> job-dir (string/split #"/") last) new-config (merge config {:extractor-address (str ":" (or (:port config) (:port @app-config)) "/extract") :writer-address (if (:out-file config) (str ":" (or (:port config) (:port @app-config)) "/write") "blank")})] (server/run-server (handler/site #'app-routes) {:port (:port @app-config)}) (when-not (.exists (io/as-file job-dir)) (.mkdir (io/as-file job-dir))) (let [new-config-file (core/generate-config-file @app-config)] (spit (str job-dir "/crawler-beans.cxml") new-config-file)) (heritrix/add heritrix-engine-addr job-dir heritrix-uname password) (let [job-addr (str heritrix-engine-addr "/job/" job-name)] (heritrix/build job-addr heritrix-uname password) (heritrix/launch job-addr heritrix-uname password) (str "Job is launched at: " job-addr)))))
20b654565ca865dee2afb0ad320ee48c4afe04deee04492a0d6c740aa0a2c7bc
adaliu-gh/htdp
6-space invader game.rkt
The first three lines of this file were inserted by . They record metadata ;; about the language level of this file in a form that our tools can easily process. #reader(lib "htdp-beginner-reader.ss" "lang")((modname |6-space invader game|) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f () #f))) ; REQUIREMENTS ;------------- (require 2htdp/image) (require 2htdp/universe) ;------------- ; CONSTANTS ;------------- (define HEIGHT 500) (define WIDTH 400) (define UFO-DELTA 3) (define MIS-DELTA (* 4 UFO-DELTA)) (define TANK-DELTA 8) (define UFO (overlay (circle 10 "solid" "green") (rectangle 50 8 "solid" "green"))) (define MISSILE (triangle 10 "solid" "red")) (define TANK (rectangle 40 30 "solid" "blue")) (define BG (empty-scene WIDTH HEIGHT)) ;------------- ; DATA DEFINITION ;------------- (define-struct aim [ufo tank]) (define-struct fired [ufo tank missile]) ; A UFO is a Posn ; interpretation (make-posn x y) is the UFO's location ; (using the top-down, left-to-right convention) (define-struct tank [loc vel]) ; A Tank is a structure: ; (make-tank Number Number) ; interpretation (make-tank x dx) specifies the position: ( x , HEIGHT ) and the tank 's speed : dx pixels / tick A is a Posn ; interpretation (make-pson x y) is the missile's place A SIGS is one of : ; - (make-aim UFO Tank) ; - (make-fired UFO Tank Missle) ; interpretation represents the complete state of a ; space invader game ;------------------------- ; Auxiliary Functions ;------------------------- ; UFO Image -> Image ; adds u to the given image im (define (ufo-render u im) (place-image UFO (posn-x u) (posn-y u) im)) ; Tank Image -> Image ; adds t to the given image im (define (tank-render t im) (place-image TANK (tank-loc t) HEIGHT im)) Image ; adds m to the given image im (define (mis-render m im) (place-image MISSILE (posn-x m) (posn-y m) im)) ; Number -> Number ; make sure that the x-coordinate of objectives are in the right range [0, WIDTH] (define (get-x n) (cond [(< n 0) 0] [(> n WIDTH) WIDTH] [else n])) ; Number -> Number ; get a random number (negative + positive) (define (random-range n) (* (if (odd? (random n)) -1 1) (random n))) ; UFO -> UFO ; ufo falls at a constant speed and jumps a bit to the sides (define (ufo-move u) (make-posn (get-x (+ (random-range 10) (posn-x u))) (if (> (+ (posn-y u) UFO-DELTA) HEIGHT) HEIGHT (+ (posn-y u) UFO-DELTA)))) ; Tank -> Tank ; and tank moves at a constant speed horizontally ; change direction when the tank touches the boundary (define (tank-move t) (make-tank (get-x (+ (tank-loc t) (tank-vel t))) (if (or (<= (+ (tank-loc t) (tank-vel t)) 0) (>= (+ (tank-loc t) (tank-vel t)) WIDTH)) (* -1 (tank-vel t)) (tank-vel t)))) ; Missile -> Missile ; missile moves (if any) vertically at a constant speed (define (mis-move m) (make-posn (posn-x m) (- (posn-y m) MIS-DELTA))) ; SIGS String -> SIGS ; change the direction of tank (define (change-dir s str) (cond [(aim? s) (make-aim (aim-ufo s) (make-tank (tank-loc (aim-tank s)) (* TANK-DELTA (if (string=? str "left") -1 1))))] [(fired? s) (make-fired (fired-ufo s) (make-tank (tank-loc (fired-tank s)) (* TANK-DELTA (if (string=? str "left") -1 1))) (fired-missile s))])) ;------------------------- ; Main Functions ;------------------------- ; SIGS -> Image adds Tank , UFO , and possibly Missile to the BG scene (define (si-render s) (cond [(aim? s)(tank-render (aim-tank s) (ufo-render (aim-ufo s) BG))] [(fired? s)(mis-render (fired-missile s) (tank-render (fired-tank s) (ufo-render (fired-ufo s) BG)))])) ; SIGS -> Boolean if ufo lands or the missle hits the ufo , stop the game (define (si-game-over? s) (cond [(aim? s) (= HEIGHT (posn-y (aim-ufo s)))] [(fired? s) (or (= HEIGHT (posn-y (fired-ufo s))) (and (< (abs (- (posn-y (fired-ufo s)) (posn-y (fired-missile s)))) (/ (image-height UFO) 2)) (< (abs (- (posn-x (fired-ufo s)) [posn-x [fired-missile s]])) (/ (image-width UFO) 2))))])) ; SIGS -> Image ; renders the "game over" image (define (over-render s) (overlay (text "GAME OVER" 30 "black") (si-render s))) ; SIGS -> SIGS ; moves the objects for every clock tick (define (si-move s) (cond [(aim? s)(make-aim (ufo-move (aim-ufo s)) (tank-move (aim-tank s)))] [(fired? s) (if (<= (posn-y (fired-missile s)) (posn-y (fired-ufo s))) (make-aim (ufo-move (fired-ufo s)) (tank-move (fired-tank s))) (make-fired (ufo-move (fired-ufo s)) (tank-move (fired-tank s)) (mis-move (fired-missile s))))])) - > SIGS ; launch the missile (if not yet) when "space" pressed ; change the directiof of tank to left when "left" pressed ; change the direction of tank to right when "right" pressed (define (si-control s ke) (cond [(or (key=? ke "left") (key=? ke "right")) (change-dir s ke)] [(and (key=? ke " ") (aim? s)) (make-fired (aim-ufo s) (aim-tank s) (make-posn (tank-loc (aim-tank s)) HEIGHT))] [else s])) ;------------------------- ; Booter ;------------------------- (define s1 (make-aim (make-posn 50 0) (make-tank 30 8))) ; SIGS -> SIGS (define (main s) (big-bang s [on-tick si-move] [on-key si-control] [to-draw si-render] [stop-when si-game-over? over-render])) ;-------------------------
null
https://raw.githubusercontent.com/adaliu-gh/htdp/a0fca8af2ae8bdcef40d56f6f45021dd92df2995/1-7%20Fixed-Size%20Data/6-space%20invader%20game.rkt
racket
about the language level of this file in a form that our tools can easily process. REQUIREMENTS ------------- ------------- CONSTANTS ------------- ------------- DATA DEFINITION ------------- A UFO is a Posn interpretation (make-posn x y) is the UFO's location (using the top-down, left-to-right convention) A Tank is a structure: (make-tank Number Number) interpretation (make-tank x dx) specifies the position: interpretation (make-pson x y) is the missile's place - (make-aim UFO Tank) - (make-fired UFO Tank Missle) interpretation represents the complete state of a space invader game ------------------------- Auxiliary Functions ------------------------- UFO Image -> Image adds u to the given image im Tank Image -> Image adds t to the given image im adds m to the given image im Number -> Number make sure that the x-coordinate of objectives are in the right range [0, WIDTH] Number -> Number get a random number (negative + positive) UFO -> UFO ufo falls at a constant speed and jumps a bit to the sides Tank -> Tank and tank moves at a constant speed horizontally change direction when the tank touches the boundary Missile -> Missile missile moves (if any) vertically at a constant speed SIGS String -> SIGS change the direction of tank ------------------------- Main Functions ------------------------- SIGS -> Image SIGS -> Boolean SIGS -> Image renders the "game over" image SIGS -> SIGS moves the objects for every clock tick launch the missile (if not yet) when "space" pressed change the directiof of tank to left when "left" pressed change the direction of tank to right when "right" pressed ------------------------- Booter ------------------------- SIGS -> SIGS -------------------------
The first three lines of this file were inserted by . They record metadata #reader(lib "htdp-beginner-reader.ss" "lang")((modname |6-space invader game|) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f () #f))) (require 2htdp/image) (require 2htdp/universe) (define HEIGHT 500) (define WIDTH 400) (define UFO-DELTA 3) (define MIS-DELTA (* 4 UFO-DELTA)) (define TANK-DELTA 8) (define UFO (overlay (circle 10 "solid" "green") (rectangle 50 8 "solid" "green"))) (define MISSILE (triangle 10 "solid" "red")) (define TANK (rectangle 40 30 "solid" "blue")) (define BG (empty-scene WIDTH HEIGHT)) (define-struct aim [ufo tank]) (define-struct fired [ufo tank missile]) (define-struct tank [loc vel]) ( x , HEIGHT ) and the tank 's speed : dx pixels / tick A is a Posn A SIGS is one of : (define (ufo-render u im) (place-image UFO (posn-x u) (posn-y u) im)) (define (tank-render t im) (place-image TANK (tank-loc t) HEIGHT im)) Image (define (mis-render m im) (place-image MISSILE (posn-x m) (posn-y m) im)) (define (get-x n) (cond [(< n 0) 0] [(> n WIDTH) WIDTH] [else n])) (define (random-range n) (* (if (odd? (random n)) -1 1) (random n))) (define (ufo-move u) (make-posn (get-x (+ (random-range 10) (posn-x u))) (if (> (+ (posn-y u) UFO-DELTA) HEIGHT) HEIGHT (+ (posn-y u) UFO-DELTA)))) (define (tank-move t) (make-tank (get-x (+ (tank-loc t) (tank-vel t))) (if (or (<= (+ (tank-loc t) (tank-vel t)) 0) (>= (+ (tank-loc t) (tank-vel t)) WIDTH)) (* -1 (tank-vel t)) (tank-vel t)))) (define (mis-move m) (make-posn (posn-x m) (- (posn-y m) MIS-DELTA))) (define (change-dir s str) (cond [(aim? s) (make-aim (aim-ufo s) (make-tank (tank-loc (aim-tank s)) (* TANK-DELTA (if (string=? str "left") -1 1))))] [(fired? s) (make-fired (fired-ufo s) (make-tank (tank-loc (fired-tank s)) (* TANK-DELTA (if (string=? str "left") -1 1))) (fired-missile s))])) adds Tank , UFO , and possibly Missile to the BG scene (define (si-render s) (cond [(aim? s)(tank-render (aim-tank s) (ufo-render (aim-ufo s) BG))] [(fired? s)(mis-render (fired-missile s) (tank-render (fired-tank s) (ufo-render (fired-ufo s) BG)))])) if ufo lands or the missle hits the ufo , stop the game (define (si-game-over? s) (cond [(aim? s) (= HEIGHT (posn-y (aim-ufo s)))] [(fired? s) (or (= HEIGHT (posn-y (fired-ufo s))) (and (< (abs (- (posn-y (fired-ufo s)) (posn-y (fired-missile s)))) (/ (image-height UFO) 2)) (< (abs (- (posn-x (fired-ufo s)) [posn-x [fired-missile s]])) (/ (image-width UFO) 2))))])) (define (over-render s) (overlay (text "GAME OVER" 30 "black") (si-render s))) (define (si-move s) (cond [(aim? s)(make-aim (ufo-move (aim-ufo s)) (tank-move (aim-tank s)))] [(fired? s) (if (<= (posn-y (fired-missile s)) (posn-y (fired-ufo s))) (make-aim (ufo-move (fired-ufo s)) (tank-move (fired-tank s))) (make-fired (ufo-move (fired-ufo s)) (tank-move (fired-tank s)) (mis-move (fired-missile s))))])) - > SIGS (define (si-control s ke) (cond [(or (key=? ke "left") (key=? ke "right")) (change-dir s ke)] [(and (key=? ke " ") (aim? s)) (make-fired (aim-ufo s) (aim-tank s) (make-posn (tank-loc (aim-tank s)) HEIGHT))] [else s])) (define s1 (make-aim (make-posn 50 0) (make-tank 30 8))) (define (main s) (big-bang s [on-tick si-move] [on-key si-control] [to-draw si-render] [stop-when si-game-over? over-render]))
60a67e320f908937d35af65d68612c231ca9efdb006edaaf8381c375b6fd5f55
pkrumins/the-little-mler
03-cons-magnificent.ml
* * Chapter 3 of The Little MLer : * * Cons Is Still Magnificent * * * * Code examples assembled by ( ) . * * His blog is at -- good coders code , great reuse . * * * * Get yourself this wonderful book at Amazon : ** Chapter 3 of The Little MLer: ** Cons Is Still Magnificent ** ** Code examples assembled by Peteris Krumins (). ** His blog is at -- good coders code, great reuse. ** ** Get yourself this wonderful book at Amazon: *) (* A new datatype - pizza *) datatype pizza = Crust | Cheese of pizza | Onion of pizza | Anchovy of pizza | Sausage of pizza; (* Our favorite pizza *) Anchovy(Onion(Anchovy(Anchovy(Cheese(Crust))))); Let 's remove to make it less salty *) fun remove_anchovy(Crust) = Crust | remove_anchovy(Cheese(x)) = Cheese(remove_anchovy(x)) | remove_anchovy(Onion(x)) = Onion(remove_anchovy(x)) | remove_anchovy(Anchovy(x)) = remove_anchovy(x) | remove_anchovy(Sausage(x)) = Sausage(remove_anchovy(x)); (* The datatype of remove_anchovy is remove_anchovy: pizza -> pizza *) remove_anchovy; (* Example of remove_anchovy *) remove_anchovy( Anchovy( Onion( Anchovy( Anchovy( Cheese( Crust)))))); (* Onion(Cheese(Crust)) *) (* Let's top Anchovy with Cheese *) fun top_anchovy_with_cheese(Crust) = Crust | top_anchovy_with_cheese(Cheese(x)) = Cheese(top_anchovy_with_cheese(x)) | top_anchovy_with_cheese(Onion(x)) = Onion(top_anchovy_with_cheese(x)) | top_anchovy_with_cheese(Anchovy(x)) = Cheese(Anchovy(top_anchovy_with_cheese(x))) | top_anchovy_with_cheese(Sausage(x)) = Sausage(top_anchovy_with_cheese(x)); The datatype of top_anchovy_with_cheese is pizza - > pizza *) top_anchovy_with_cheese; (* Example of top_anchovy_with_cheese *) top_anchovy_with_cheese( Onion( Anchovy( Cheese( Cheese( Anchovy( Crust)))))); Onion(Cheese(Anchovy(Cheese(Cheese(Cheese(Anchovy(Crust ) ) ) ) ) ) ) (* Combine remove_anchovy with top_anchovy_with_cheese *) top_anchovy_with_cheese( remove_anchovy( Onion( Anchovy( Cheese( Anchovy( Crust)))))); (* Onion(Cheese(Crust)) *) remove_anchovy( top_anchovy_with_cheese( Onion( Anchovy( Cheese( Anchovy( Crust)))))); (* Onion(Cheese(Cheese(Cheese(Crust)))) *) Substitute Achovy for Cheese *) fun subst_anchovy_by_cheese(x) = remove_anchovy( top_anchovy_with_cheese(x)); Datatype of subst_anchovy_by_cheese is pizza - > pizza *) subst_anchovy_by_cheese; (* Example of subst_anchovy_by_cheese *) subst_anchovy_by_cheese( Onion( Anchovy( Cheese( Anchovy( Crust))))); (* Onion(Cheese(Cheese(Cheese(Crust)))) *) (* Another way to write subst_anchovy_by_cheese *) fun subst_anchovy_by_cheese2(Crust) = Crust | subst_anchovy_by_cheese2(Cheese(x)) = Cheese(subst_anchovy_by_cheese2(x)) | subst_anchovy_by_cheese2(Onion(x)) = Onion(subst_anchovy_by_cheese2(x)) | subst_anchovy_by_cheese2(Anchovy(x)) = Cheese(subst_anchovy_by_cheese2(x)) | subst_anchovy_by_cheese2(Sausage(x)) = Sausage(subst_anchovy_by_cheese2(x)); (* Example of subst_anchovy_by_cheese2 *) subst_anchovy_by_cheese2( Onion( Anchovy( Cheese( Anchovy( Crust))))); (* Onion(Cheese(Cheese(Cheese(Crust)))) *) * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * The third moral : * * * * Functions that produce values of a datatype must use the associated * * constructors to build data of that type . * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * The third moral: * * * * Functions that produce values of a datatype must use the associated * * constructors to build data of that type. * * * *****************************************************************************) * * Go get yourself this wonderful book and have fun with ML language ! * * * * Shortened URL to the book at Amazon.com : * * * * Sincerely , * * * * ** Go get yourself this wonderful book and have fun with ML language! ** ** Shortened URL to the book at Amazon.com: ** ** Sincerely, ** Peteris Krumins ** *)
null
https://raw.githubusercontent.com/pkrumins/the-little-mler/369745c04daee42a52cf54f48f27cac8092b0f83/03-cons-magnificent.ml
ocaml
A new datatype - pizza Our favorite pizza The datatype of remove_anchovy is remove_anchovy: pizza -> pizza Example of remove_anchovy Onion(Cheese(Crust)) Let's top Anchovy with Cheese Example of top_anchovy_with_cheese Combine remove_anchovy with top_anchovy_with_cheese Onion(Cheese(Crust)) Onion(Cheese(Cheese(Cheese(Crust)))) Example of subst_anchovy_by_cheese Onion(Cheese(Cheese(Cheese(Crust)))) Another way to write subst_anchovy_by_cheese Example of subst_anchovy_by_cheese2 Onion(Cheese(Cheese(Cheese(Crust))))
* * Chapter 3 of The Little MLer : * * Cons Is Still Magnificent * * * * Code examples assembled by ( ) . * * His blog is at -- good coders code , great reuse . * * * * Get yourself this wonderful book at Amazon : ** Chapter 3 of The Little MLer: ** Cons Is Still Magnificent ** ** Code examples assembled by Peteris Krumins (). ** His blog is at -- good coders code, great reuse. ** ** Get yourself this wonderful book at Amazon: *) datatype pizza = Crust | Cheese of pizza | Onion of pizza | Anchovy of pizza | Sausage of pizza; Anchovy(Onion(Anchovy(Anchovy(Cheese(Crust))))); Let 's remove to make it less salty *) fun remove_anchovy(Crust) = Crust | remove_anchovy(Cheese(x)) = Cheese(remove_anchovy(x)) | remove_anchovy(Onion(x)) = Onion(remove_anchovy(x)) | remove_anchovy(Anchovy(x)) = remove_anchovy(x) | remove_anchovy(Sausage(x)) = Sausage(remove_anchovy(x)); remove_anchovy; remove_anchovy( Anchovy( Onion( Anchovy( Anchovy( Cheese( fun top_anchovy_with_cheese(Crust) = Crust | top_anchovy_with_cheese(Cheese(x)) = Cheese(top_anchovy_with_cheese(x)) | top_anchovy_with_cheese(Onion(x)) = Onion(top_anchovy_with_cheese(x)) | top_anchovy_with_cheese(Anchovy(x)) = Cheese(Anchovy(top_anchovy_with_cheese(x))) | top_anchovy_with_cheese(Sausage(x)) = Sausage(top_anchovy_with_cheese(x)); The datatype of top_anchovy_with_cheese is pizza - > pizza *) top_anchovy_with_cheese; top_anchovy_with_cheese( Onion( Anchovy( Cheese( Cheese( Anchovy( Crust)))))); Onion(Cheese(Anchovy(Cheese(Cheese(Cheese(Anchovy(Crust ) ) ) ) ) ) ) top_anchovy_with_cheese( remove_anchovy( Onion( Anchovy( Cheese( Anchovy( remove_anchovy( top_anchovy_with_cheese( Onion( Anchovy( Cheese( Anchovy( Substitute Achovy for Cheese *) fun subst_anchovy_by_cheese(x) = remove_anchovy( top_anchovy_with_cheese(x)); Datatype of subst_anchovy_by_cheese is pizza - > pizza *) subst_anchovy_by_cheese; subst_anchovy_by_cheese( Onion( Anchovy( Cheese( Anchovy( fun subst_anchovy_by_cheese2(Crust) = Crust | subst_anchovy_by_cheese2(Cheese(x)) = Cheese(subst_anchovy_by_cheese2(x)) | subst_anchovy_by_cheese2(Onion(x)) = Onion(subst_anchovy_by_cheese2(x)) | subst_anchovy_by_cheese2(Anchovy(x)) = Cheese(subst_anchovy_by_cheese2(x)) | subst_anchovy_by_cheese2(Sausage(x)) = Sausage(subst_anchovy_by_cheese2(x)); subst_anchovy_by_cheese2( Onion( Anchovy( Cheese( Anchovy( * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * The third moral : * * * * Functions that produce values of a datatype must use the associated * * constructors to build data of that type . * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * The third moral: * * * * Functions that produce values of a datatype must use the associated * * constructors to build data of that type. * * * *****************************************************************************) * * Go get yourself this wonderful book and have fun with ML language ! * * * * Shortened URL to the book at Amazon.com : * * * * Sincerely , * * * * ** Go get yourself this wonderful book and have fun with ML language! ** ** Shortened URL to the book at Amazon.com: ** ** Sincerely, ** Peteris Krumins ** *)
6e4f883010e2ef232881789624906a714cda0c76cd5d94f11e172ddcdd519762
pkel/cpr
tailstormll.ml
open Cpr_lib let incentive_schemes = Tailstorm.incentive_schemes let subblock_selections = Tailstorm.subblock_selections module type Parameters = Tailstorm.Parameters module Make (Parameters : Parameters) = struct open Parameters let key = let open Options in Format.asprintf "tailstormll-%i-%a-%a" k pp incentive_scheme pp subblock_selection ;; let description = Format.asprintf "Tailstorm/ll with k=%i, %a rewards, and %a sub-block selection" Parameters.k Options.pp incentive_scheme Options.pp subblock_selection ;; let info = let open Info in [ string "family" "tailstormll" ; int "k" k ; Options.info "incentive_scheme" incentive_scheme ; Options.info "subblock_selection" subblock_selection ] ;; type data = { block : int ; vote : int ; miner : int option } let height h = h.block let depth h = h.vote let progress x = (x.block * k) + x.vote |> float_of_int let is_vote h = h.vote > 0 let is_block h = h.vote = 0 let describe h = let ty = if is_vote h then "vote" else "block" in Printf.sprintf "%s (%i|%i)" ty h.block h.vote ;; let roots = [ { block = 0; vote = 0; miner = None } ] module Referee (D : BlockDAG with type data = data) = struct include D let info x = let x = data x in let open Info in if is_vote x then [ string "kind" "vote"; int "height" x.block; int "depth" x.vote ] else [ string "kind" "summary"; int "height" x.block ] ;; let label x = let x = data x in if is_vote x then Printf.sprintf "summary %i" x.block else Printf.sprintf "vote (%i|%i)" x.block x.vote ;; let dag_fail (type a) vertices msg : a = let meta x = [ Info.string "label" (label x) ] in raise_invalid_dag meta vertices msg ;; let is_vote x = is_vote (data x) let is_block x = is_block (data x) let height x = height (data x) let depth x = depth (data x) let progress x = progress (data x) let rec last_block x = if is_block x then x else ( match parents x with | [ x ] -> last_block x | parents -> dag_fail (x :: parents) "last_block: votes have exactly one parent by dag_validity") ;; (* smaller is better *) let compare_votes_in_block = let get x = let d = data x and hash = pow x |> Option.value ~default:min_pow in d.vote, hash and ty = Compare.(tuple (neg int) compare_pow) in Compare.(by ty get) ;; module BlockSet = Set.Make (Block) let acc_votes unfold l = let open BlockSet in let rec f acc stack l = match l, stack with | [], [] -> acc | [], hd :: tl -> f acc tl hd | hd :: tl, stack when is_vote hd -> f (add hd acc) (unfold hd :: stack) tl | _ :: tl, stack -> f acc stack tl in f empty [] l ;; let confirmed_votes x = assert (is_block x); acc_votes parents (parents x) ;; let confirming_votes x = assert (is_block x); acc_votes children (children x) ;; let validity vertex = let child = data vertex in child.block >= 0 && child.vote >= 0 && child.vote < k && pow vertex |> Option.is_some && child.miner |> Option.is_some && match is_vote vertex, parents vertex with | true, [ p ] -> (* child is vote *) let parent = data p in child.block = parent.block && child.vote = parent.vote + 1 | false, p :: votes -> (* child is block *) let parent = data p in let unique_votes = acc_votes parents votes |> BlockSet.cardinal and sorted_votes = Compare.is_sorted ~unique:true compare_votes_in_block votes in is_block p && sorted_votes && List.for_all is_vote votes && unique_votes = k - 1 && child.block = parent.block + 1 && child.vote = 0 | _ -> false ;; (** better is bigger *) let compare_blocks = let open Compare in let cmp = by int height $ by int (fun x -> BlockSet.cardinal (confirming_votes x)) in skip_eq Block.eq cmp ;; let winner l = assert (List.for_all is_block l); Compare.first (Compare.neg compare_blocks) 1 l |> Option.get |> List.hd ;; let precursor this = List.nth_opt (parents this) 0 let assign c x = match (data x).miner with | Some x -> [ x, c ] | None -> [] ;; let reward' ~max_reward_per_block ~discount ~punish x = let k = float_of_int k in let c = max_reward_per_block /. k in if is_block x then ( match parents x |> List.filter is_vote with | [] -> [] | first :: _ as all -> let depth = depth first in let r = if discount then (float_of_int depth +. 1.) /. k *. c else c in let votes = if punish then BlockSet.add x (acc_votes parents [ first ]) else BlockSet.add x (acc_votes parents all) in BlockSet.elements votes |> List.concat_map (assign r)) else [] ;; let reward = let reward = reward' ~max_reward_per_block:(float_of_int k) in match incentive_scheme with | `Constant -> reward ~discount:false ~punish:false | `Discount -> reward ~discount:true ~punish:false | `Punish -> reward ~discount:false ~punish:true | `Hybrid -> reward ~discount:true ~punish:true ;; end let referee (type a) (module D : BlockDAG with type block = a and type data = data) : (a, data) referee = (module Referee (D)) ;; module Honest (V : View with type data = data) = struct include V open Referee (V) type state = block let preferred state = state let init ~roots = match roots with | [ genesis ] -> genesis | roots -> dag_fail roots "init: expected single root" ;; let appended_by_me x = match visibility x with | `Received -> false | `Withheld | `Released -> true ;; * Algorithm for selecting sub blocks quickly . This version picks the longest branches first . If a branches does not fit into the quorum , it is cut down until it fits . The chosen sub blocks do not maximize rewards for the miner of the block . Thus this implementation does not align with 's description of . This version picks the longest branches first. If a branches does not fit into the quorum, it is cut down until it fits. The chosen sub blocks do not maximize rewards for the miner of the block. Thus this implementation does not align with George's description of Tailstorm. *) let altruistic_quorum ~children b = let rec f acc n q l = if n = k - 1 then Some (List.rev q) else ( match l with | [] -> None | hd :: tl -> let fresh, n_fresh = BlockSet.fold (fun el (fresh, n_fresh) -> if BlockSet.mem el acc then fresh, n_fresh else BlockSet.add el fresh, n_fresh + 1) (acc_votes parents [ hd ]) (BlockSet.empty, 0) in let n' = n + n_fresh in if n' > k - 1 || n_fresh < 1 then (* quorum would grow to big *) f acc n q tl else f (BlockSet.union fresh acc) n' (hd :: q) tl) in acc_votes children (children b) |> BlockSet.elements |> List.sort Compare.( by (tuple (neg int) (tuple int float)) (fun x -> (data x).vote, ((if appended_by_me x then 0 else 1), visible_since x))) |> f BlockSet.empty 0 [] |> Option.map (List.sort Compare.( by (tuple (neg int) compare_pow) (fun x -> let d = data x and hash = pow x |> Option.value ~default:max_pow in d.vote, hash))) ;; * Algorithm for selecting sub block heuristically but quickly . This version tries to select the sub blocks that maximize a miner 's own rewards . We assume constant reward scheme . We first find all branches of depth k-1 or less . We then sort the branches by own reward , assuming that the branch will be confirmed in the future . We then add the most valuable branch to the quorum . If some (= k ' ) sub blocks are missing after the first iteration , we search for all remaining branches that would add k ' or less sub blocks . We sort the branches by the amount of reward they would add . We add the most valuable branch an reiterate until enough sub blocks are added . This version tries to select the sub blocks that maximize a miner's own rewards. We assume constant reward scheme. We first find all branches of depth k-1 or less. We then sort the branches by own reward, assuming that the branch will be confirmed in the future. We then add the most valuable branch to the quorum. If some (= k') sub blocks are missing after the first iteration, we search for all remaining branches that would add k' or less sub blocks. We sort the branches by the amount of reward they would add. We add the most valuable branch an reiterate until enough sub blocks are added. *) let heuristic_quorum ~children b = let leaves = ref BlockSet.empty and votes = ref BlockSet.empty and n = ref (k - 1) in let included x = BlockSet.mem x !votes in let include_ x = assert (not (included x)); leaves := BlockSet.add x !leaves; acc_votes parents [ x ] |> BlockSet.iter (fun x -> if not (included x) then ( votes := BlockSet.add x !votes; decr n)) and reward ?(all = false) x = let i = ref 0 in let () = acc_votes parents [ x ] |> BlockSet.iter (fun x -> if (not (included x)) && (all || appended_by_me x) then incr i) in !i in let rec loop () = assert (!n >= 0); if !n > 0 then ( acc_votes children (children b) |> BlockSet.elements |> List.filter (fun x -> not (included x)) |> (* calculate own and overall reward for branch *) List.map (fun x -> x, reward x, reward ~all:true x) |> (* ensure branch fits into quorum *) List.filter (fun (_, _, x) -> x <= !n) |> (* prefer own reward, then overall reward *) List.sort Compare.( by int (fun (_, x, _) -> x) |> neg $ (by int (fun (_, _, x) -> x) |> neg)) |> function | [] -> None (* no branches left, not enough votes *) | (x, _, _) :: _ -> (* add best branch, continue *) include_ x; loop ()) else (* quorum complete. Ensure that it satisfies quorum validity *) Some (BlockSet.elements !leaves |> List.sort compare_votes_in_block) in loop () ;; * Algorithm for reward - optimizing sub block choice Input : last block b 1 . Find all confirming sub blocks of b. Put them into array a. 2 . Check |a| > k. Abort if not . 3 . Prepare mutable list For each choice , check connectivity . Calculate rewards for connected choice ; add to l. 4 . Sort l by reward , pick optimal choice q. 5 . Reduce q such that only sub block tree leaves remain . 6 . Sort q by branch depth , descending . 7 . Return q. Sorting sub blocks on step ( 1 . ) by dag - imposed partial order can simplify connectivity check in ( 3 . ) ; e.g. , we can iterate the choice in dag - imposed order and check if all predecessors have been visited before or equal b. We can find the leaves with the same technique . Iterate choice in dag - imposed order , for each block mark all its predecessors as redundant . After the iteration , leaves are still unmarked . It 's also easy to select the branch with the highest depth : just pick the last entry of q. Maybe we can exploit that [ iter_n_choose_k ] returns the choice in ( reverse ) sorted manner . If we start relying on this , we 'd have to add a test for that . Calculating rewards will be interesting . We can not use the reward function of the referee , because the block is not yet appended . But maybe we can reuse parts to avoid error - prone redundancy . Input: last block b 1. Find all confirming sub blocks of b. Put them into array a. 2. Check |a| > k. Abort if not. 3. Prepare mutable list l. Iterate |a| choose k. For each choice, check connectivity. Calculate rewards for connected choice; add to l. 4. Sort l by reward, pick optimal choice q. 5. Reduce q such that only sub block tree leaves remain. 6. Sort q by branch depth, descending. 7. Return q. Sorting sub blocks on step (1.) by dag-imposed partial order can simplify connectivity check in (3.); e.g., we can iterate the choice in dag-imposed order and check if all predecessors have been visited before or equal b. We can find the leaves with the same technique. Iterate choice in dag-imposed order, for each block mark all its predecessors as redundant. After the iteration, leaves are still unmarked. It's also easy to select the branch with the highest depth: just pick the last entry of q. Maybe we can exploit that [iter_n_choose_k] returns the choice in (reverse) sorted manner. If we start relying on this, we'd have to add a test for that. Calculating rewards will be interesting. We cannot use the reward function of the referee, because the block is not yet appended. But maybe we can reuse parts to avoid error-prone redundancy. *) let optimal_quorum ~max_options ~children b = assert (is_block b); if k = 1 then Some [] else ( let a = acc_votes children (children b) |> BlockSet.to_seq |> Array.of_seq in let n = Array.length a in if Combinatorics.n_choose_k n k > max_options then heuristic_quorum ~children b else if n < k - 1 then None else ( let a' = let module BlockMap = Map.Make (Block) in let _, m = Array.fold_left (fun (i, m) x -> i + 1, BlockMap.add x i m) (0, BlockMap.empty) a in fun x -> BlockMap.find x m in let leaves = let reach_buf = Array.make n false in let leave_buf = Array.make n true in let reset () = for i = 0 to n - 1 do reach_buf.(i) <- false; leave_buf.(i) <- true done in let rec f = function | hd :: tl -> (* check connectivity, mark non-leaves *) if List.for_all (fun p -> leave_buf.(a' p) <- false; reach_buf.(a' p)) (parents a.(hd) |> List.filter is_vote) then ( let () = reach_buf.(hd) <- true in f tl) else `Not_connected | [] -> (* check quorum size (debugging) *) assert ( Array.fold_left ( fun c b - > if b then c + 1 else c ) 0 reach_buf = k - 1 ) ; let leaves = let l = ref [] in let () = for i = 1 to n do let i' = n - i in if reach_buf.(i') && leave_buf.(i') then l := a.(i') :: !l done in List.sort compare_votes_in_block !l in let reward = let rewarded_votes = match incentive_scheme with | `Constant | `Discount -> acc_votes parents leaves | `Punish | `Hybrid -> acc_votes parents [ List.hd leaves ] and per_vote = match incentive_scheme with | `Constant | `Punish -> 1. | `Discount | `Hybrid -> let depth = (List.hd leaves |> data).vote in float_of_int (depth + 1) /. float_of_int k in BlockSet.fold (fun x acc -> if appended_by_me x then acc +. per_vote else acc) rewarded_votes 1. in `Ok (reward, leaves) in fun c -> reset (); f c in let q = let opt_choice, opt_reward = ref None, ref (-1.) in let () = Combinatorics.iter_n_choose_k (Array.length a) (k - 1) (fun c -> assert ( c = k - 1 ) ; match leaves c with | `Not_connected -> () | `Ok (reward, choice) -> if reward > !opt_reward then ( opt_reward := reward; opt_choice := Some choice)) in match !opt_choice with | Some x -> x | None -> failwith "reward_optim_quorum: no choice" in assert (acc_votes parents q |> BlockSet.cardinal = k - 1); Some q)) ;; let quorum = match subblock_selection with | `Altruistic -> altruistic_quorum | `Heuristic -> heuristic_quorum | `Optimal -> optimal_quorum ~max_options:100 ;; let puzzle_payload' ~vote_filter b = let children x = children x |> List.filter vote_filter in assert (is_block b); match quorum ~children b with | Some q -> { parents = b :: q ; sign = false ; data = { block = height b + 1; vote = 0; miner = Some my_id } } | None -> let votes = acc_votes children (children b) |> BlockSet.elements |> List.sort compare_votes_in_block in let parent = match votes with | hd :: _ -> hd | _ -> b in { parents = [ parent ] ; sign = false ; data = { block = height b; vote = (data parent).vote + 1; miner = Some my_id } } ;; let puzzle_payload = puzzle_payload' ~vote_filter:(fun _ -> true) let compare_blocks ~vote_filter = let children x = children x |> List.filter vote_filter in let open Compare in let count x = acc_votes children (children x) |> BlockSet.cardinal in let cmp = by int height $ by int count (* embed A_k *) TODO . Maybe this should be received_at ? in skip_eq Block.eq cmp ;; let update_head ?(vote_filter = Fun.const true) ~old consider = assert (is_block consider); if compare_blocks ~vote_filter consider old > 0 then consider else old ;; let handler preferred = function | Append _x -> failwith "not implemented" | ProofOfWork x | Network x -> let b = last_block x in let share = match visibility x with | `Withheld -> [ x ] | _ -> [] in update_head ~old:preferred b |> return ~share ;; end let honest (type a) ((module V) : (a, data) view) : (a, data) node = Node (module Honest (V)) ;; end
null
https://raw.githubusercontent.com/pkel/cpr/9a08c2a9533866ce52c2e08c42bbf8fcd9d6636c/simulator/protocols/tailstormll.ml
ocaml
smaller is better child is vote child is block * better is bigger quorum would grow to big calculate own and overall reward for branch ensure branch fits into quorum prefer own reward, then overall reward no branches left, not enough votes add best branch, continue quorum complete. Ensure that it satisfies quorum validity check connectivity, mark non-leaves check quorum size (debugging) embed A_k
open Cpr_lib let incentive_schemes = Tailstorm.incentive_schemes let subblock_selections = Tailstorm.subblock_selections module type Parameters = Tailstorm.Parameters module Make (Parameters : Parameters) = struct open Parameters let key = let open Options in Format.asprintf "tailstormll-%i-%a-%a" k pp incentive_scheme pp subblock_selection ;; let description = Format.asprintf "Tailstorm/ll with k=%i, %a rewards, and %a sub-block selection" Parameters.k Options.pp incentive_scheme Options.pp subblock_selection ;; let info = let open Info in [ string "family" "tailstormll" ; int "k" k ; Options.info "incentive_scheme" incentive_scheme ; Options.info "subblock_selection" subblock_selection ] ;; type data = { block : int ; vote : int ; miner : int option } let height h = h.block let depth h = h.vote let progress x = (x.block * k) + x.vote |> float_of_int let is_vote h = h.vote > 0 let is_block h = h.vote = 0 let describe h = let ty = if is_vote h then "vote" else "block" in Printf.sprintf "%s (%i|%i)" ty h.block h.vote ;; let roots = [ { block = 0; vote = 0; miner = None } ] module Referee (D : BlockDAG with type data = data) = struct include D let info x = let x = data x in let open Info in if is_vote x then [ string "kind" "vote"; int "height" x.block; int "depth" x.vote ] else [ string "kind" "summary"; int "height" x.block ] ;; let label x = let x = data x in if is_vote x then Printf.sprintf "summary %i" x.block else Printf.sprintf "vote (%i|%i)" x.block x.vote ;; let dag_fail (type a) vertices msg : a = let meta x = [ Info.string "label" (label x) ] in raise_invalid_dag meta vertices msg ;; let is_vote x = is_vote (data x) let is_block x = is_block (data x) let height x = height (data x) let depth x = depth (data x) let progress x = progress (data x) let rec last_block x = if is_block x then x else ( match parents x with | [ x ] -> last_block x | parents -> dag_fail (x :: parents) "last_block: votes have exactly one parent by dag_validity") ;; let compare_votes_in_block = let get x = let d = data x and hash = pow x |> Option.value ~default:min_pow in d.vote, hash and ty = Compare.(tuple (neg int) compare_pow) in Compare.(by ty get) ;; module BlockSet = Set.Make (Block) let acc_votes unfold l = let open BlockSet in let rec f acc stack l = match l, stack with | [], [] -> acc | [], hd :: tl -> f acc tl hd | hd :: tl, stack when is_vote hd -> f (add hd acc) (unfold hd :: stack) tl | _ :: tl, stack -> f acc stack tl in f empty [] l ;; let confirmed_votes x = assert (is_block x); acc_votes parents (parents x) ;; let confirming_votes x = assert (is_block x); acc_votes children (children x) ;; let validity vertex = let child = data vertex in child.block >= 0 && child.vote >= 0 && child.vote < k && pow vertex |> Option.is_some && child.miner |> Option.is_some && match is_vote vertex, parents vertex with | true, [ p ] -> let parent = data p in child.block = parent.block && child.vote = parent.vote + 1 | false, p :: votes -> let parent = data p in let unique_votes = acc_votes parents votes |> BlockSet.cardinal and sorted_votes = Compare.is_sorted ~unique:true compare_votes_in_block votes in is_block p && sorted_votes && List.for_all is_vote votes && unique_votes = k - 1 && child.block = parent.block + 1 && child.vote = 0 | _ -> false ;; let compare_blocks = let open Compare in let cmp = by int height $ by int (fun x -> BlockSet.cardinal (confirming_votes x)) in skip_eq Block.eq cmp ;; let winner l = assert (List.for_all is_block l); Compare.first (Compare.neg compare_blocks) 1 l |> Option.get |> List.hd ;; let precursor this = List.nth_opt (parents this) 0 let assign c x = match (data x).miner with | Some x -> [ x, c ] | None -> [] ;; let reward' ~max_reward_per_block ~discount ~punish x = let k = float_of_int k in let c = max_reward_per_block /. k in if is_block x then ( match parents x |> List.filter is_vote with | [] -> [] | first :: _ as all -> let depth = depth first in let r = if discount then (float_of_int depth +. 1.) /. k *. c else c in let votes = if punish then BlockSet.add x (acc_votes parents [ first ]) else BlockSet.add x (acc_votes parents all) in BlockSet.elements votes |> List.concat_map (assign r)) else [] ;; let reward = let reward = reward' ~max_reward_per_block:(float_of_int k) in match incentive_scheme with | `Constant -> reward ~discount:false ~punish:false | `Discount -> reward ~discount:true ~punish:false | `Punish -> reward ~discount:false ~punish:true | `Hybrid -> reward ~discount:true ~punish:true ;; end let referee (type a) (module D : BlockDAG with type block = a and type data = data) : (a, data) referee = (module Referee (D)) ;; module Honest (V : View with type data = data) = struct include V open Referee (V) type state = block let preferred state = state let init ~roots = match roots with | [ genesis ] -> genesis | roots -> dag_fail roots "init: expected single root" ;; let appended_by_me x = match visibility x with | `Received -> false | `Withheld | `Released -> true ;; * Algorithm for selecting sub blocks quickly . This version picks the longest branches first . If a branches does not fit into the quorum , it is cut down until it fits . The chosen sub blocks do not maximize rewards for the miner of the block . Thus this implementation does not align with 's description of . This version picks the longest branches first. If a branches does not fit into the quorum, it is cut down until it fits. The chosen sub blocks do not maximize rewards for the miner of the block. Thus this implementation does not align with George's description of Tailstorm. *) let altruistic_quorum ~children b = let rec f acc n q l = if n = k - 1 then Some (List.rev q) else ( match l with | [] -> None | hd :: tl -> let fresh, n_fresh = BlockSet.fold (fun el (fresh, n_fresh) -> if BlockSet.mem el acc then fresh, n_fresh else BlockSet.add el fresh, n_fresh + 1) (acc_votes parents [ hd ]) (BlockSet.empty, 0) in let n' = n + n_fresh in if n' > k - 1 || n_fresh < 1 else f (BlockSet.union fresh acc) n' (hd :: q) tl) in acc_votes children (children b) |> BlockSet.elements |> List.sort Compare.( by (tuple (neg int) (tuple int float)) (fun x -> (data x).vote, ((if appended_by_me x then 0 else 1), visible_since x))) |> f BlockSet.empty 0 [] |> Option.map (List.sort Compare.( by (tuple (neg int) compare_pow) (fun x -> let d = data x and hash = pow x |> Option.value ~default:max_pow in d.vote, hash))) ;; * Algorithm for selecting sub block heuristically but quickly . This version tries to select the sub blocks that maximize a miner 's own rewards . We assume constant reward scheme . We first find all branches of depth k-1 or less . We then sort the branches by own reward , assuming that the branch will be confirmed in the future . We then add the most valuable branch to the quorum . If some (= k ' ) sub blocks are missing after the first iteration , we search for all remaining branches that would add k ' or less sub blocks . We sort the branches by the amount of reward they would add . We add the most valuable branch an reiterate until enough sub blocks are added . This version tries to select the sub blocks that maximize a miner's own rewards. We assume constant reward scheme. We first find all branches of depth k-1 or less. We then sort the branches by own reward, assuming that the branch will be confirmed in the future. We then add the most valuable branch to the quorum. If some (= k') sub blocks are missing after the first iteration, we search for all remaining branches that would add k' or less sub blocks. We sort the branches by the amount of reward they would add. We add the most valuable branch an reiterate until enough sub blocks are added. *) let heuristic_quorum ~children b = let leaves = ref BlockSet.empty and votes = ref BlockSet.empty and n = ref (k - 1) in let included x = BlockSet.mem x !votes in let include_ x = assert (not (included x)); leaves := BlockSet.add x !leaves; acc_votes parents [ x ] |> BlockSet.iter (fun x -> if not (included x) then ( votes := BlockSet.add x !votes; decr n)) and reward ?(all = false) x = let i = ref 0 in let () = acc_votes parents [ x ] |> BlockSet.iter (fun x -> if (not (included x)) && (all || appended_by_me x) then incr i) in !i in let rec loop () = assert (!n >= 0); if !n > 0 then ( acc_votes children (children b) |> BlockSet.elements |> List.filter (fun x -> not (included x)) List.map (fun x -> x, reward x, reward ~all:true x) List.sort Compare.( by int (fun (_, x, _) -> x) |> neg $ (by int (fun (_, _, x) -> x) |> neg)) |> function | (x, _, _) :: _ -> include_ x; loop ()) else Some (BlockSet.elements !leaves |> List.sort compare_votes_in_block) in loop () ;; * Algorithm for reward - optimizing sub block choice Input : last block b 1 . Find all confirming sub blocks of b. Put them into array a. 2 . Check |a| > k. Abort if not . 3 . Prepare mutable list For each choice , check connectivity . Calculate rewards for connected choice ; add to l. 4 . Sort l by reward , pick optimal choice q. 5 . Reduce q such that only sub block tree leaves remain . 6 . Sort q by branch depth , descending . 7 . Return q. Sorting sub blocks on step ( 1 . ) by dag - imposed partial order can simplify connectivity check in ( 3 . ) ; e.g. , we can iterate the choice in dag - imposed order and check if all predecessors have been visited before or equal b. We can find the leaves with the same technique . Iterate choice in dag - imposed order , for each block mark all its predecessors as redundant . After the iteration , leaves are still unmarked . It 's also easy to select the branch with the highest depth : just pick the last entry of q. Maybe we can exploit that [ iter_n_choose_k ] returns the choice in ( reverse ) sorted manner . If we start relying on this , we 'd have to add a test for that . Calculating rewards will be interesting . We can not use the reward function of the referee , because the block is not yet appended . But maybe we can reuse parts to avoid error - prone redundancy . Input: last block b 1. Find all confirming sub blocks of b. Put them into array a. 2. Check |a| > k. Abort if not. 3. Prepare mutable list l. Iterate |a| choose k. For each choice, check connectivity. Calculate rewards for connected choice; add to l. 4. Sort l by reward, pick optimal choice q. 5. Reduce q such that only sub block tree leaves remain. 6. Sort q by branch depth, descending. 7. Return q. Sorting sub blocks on step (1.) by dag-imposed partial order can simplify connectivity check in (3.); e.g., we can iterate the choice in dag-imposed order and check if all predecessors have been visited before or equal b. We can find the leaves with the same technique. Iterate choice in dag-imposed order, for each block mark all its predecessors as redundant. After the iteration, leaves are still unmarked. It's also easy to select the branch with the highest depth: just pick the last entry of q. Maybe we can exploit that [iter_n_choose_k] returns the choice in (reverse) sorted manner. If we start relying on this, we'd have to add a test for that. Calculating rewards will be interesting. We cannot use the reward function of the referee, because the block is not yet appended. But maybe we can reuse parts to avoid error-prone redundancy. *) let optimal_quorum ~max_options ~children b = assert (is_block b); if k = 1 then Some [] else ( let a = acc_votes children (children b) |> BlockSet.to_seq |> Array.of_seq in let n = Array.length a in if Combinatorics.n_choose_k n k > max_options then heuristic_quorum ~children b else if n < k - 1 then None else ( let a' = let module BlockMap = Map.Make (Block) in let _, m = Array.fold_left (fun (i, m) x -> i + 1, BlockMap.add x i m) (0, BlockMap.empty) a in fun x -> BlockMap.find x m in let leaves = let reach_buf = Array.make n false in let leave_buf = Array.make n true in let reset () = for i = 0 to n - 1 do reach_buf.(i) <- false; leave_buf.(i) <- true done in let rec f = function | hd :: tl -> if List.for_all (fun p -> leave_buf.(a' p) <- false; reach_buf.(a' p)) (parents a.(hd) |> List.filter is_vote) then ( let () = reach_buf.(hd) <- true in f tl) else `Not_connected | [] -> assert ( Array.fold_left ( fun c b - > if b then c + 1 else c ) 0 reach_buf = k - 1 ) ; let leaves = let l = ref [] in let () = for i = 1 to n do let i' = n - i in if reach_buf.(i') && leave_buf.(i') then l := a.(i') :: !l done in List.sort compare_votes_in_block !l in let reward = let rewarded_votes = match incentive_scheme with | `Constant | `Discount -> acc_votes parents leaves | `Punish | `Hybrid -> acc_votes parents [ List.hd leaves ] and per_vote = match incentive_scheme with | `Constant | `Punish -> 1. | `Discount | `Hybrid -> let depth = (List.hd leaves |> data).vote in float_of_int (depth + 1) /. float_of_int k in BlockSet.fold (fun x acc -> if appended_by_me x then acc +. per_vote else acc) rewarded_votes 1. in `Ok (reward, leaves) in fun c -> reset (); f c in let q = let opt_choice, opt_reward = ref None, ref (-1.) in let () = Combinatorics.iter_n_choose_k (Array.length a) (k - 1) (fun c -> assert ( c = k - 1 ) ; match leaves c with | `Not_connected -> () | `Ok (reward, choice) -> if reward > !opt_reward then ( opt_reward := reward; opt_choice := Some choice)) in match !opt_choice with | Some x -> x | None -> failwith "reward_optim_quorum: no choice" in assert (acc_votes parents q |> BlockSet.cardinal = k - 1); Some q)) ;; let quorum = match subblock_selection with | `Altruistic -> altruistic_quorum | `Heuristic -> heuristic_quorum | `Optimal -> optimal_quorum ~max_options:100 ;; let puzzle_payload' ~vote_filter b = let children x = children x |> List.filter vote_filter in assert (is_block b); match quorum ~children b with | Some q -> { parents = b :: q ; sign = false ; data = { block = height b + 1; vote = 0; miner = Some my_id } } | None -> let votes = acc_votes children (children b) |> BlockSet.elements |> List.sort compare_votes_in_block in let parent = match votes with | hd :: _ -> hd | _ -> b in { parents = [ parent ] ; sign = false ; data = { block = height b; vote = (data parent).vote + 1; miner = Some my_id } } ;; let puzzle_payload = puzzle_payload' ~vote_filter:(fun _ -> true) let compare_blocks ~vote_filter = let children x = children x |> List.filter vote_filter in let open Compare in let count x = acc_votes children (children x) |> BlockSet.cardinal in let cmp = by int height TODO . Maybe this should be received_at ? in skip_eq Block.eq cmp ;; let update_head ?(vote_filter = Fun.const true) ~old consider = assert (is_block consider); if compare_blocks ~vote_filter consider old > 0 then consider else old ;; let handler preferred = function | Append _x -> failwith "not implemented" | ProofOfWork x | Network x -> let b = last_block x in let share = match visibility x with | `Withheld -> [ x ] | _ -> [] in update_head ~old:preferred b |> return ~share ;; end let honest (type a) ((module V) : (a, data) view) : (a, data) node = Node (module Honest (V)) ;; end
942174e327c2a3776c6c9110a904c830f93555b8cd0756b5afb44d584afce99b
clingen-data-model/genegraph
variation_descriptor.clj
(ns genegraph.source.graphql.schema.variation-descriptor (:require [genegraph.database.query :as q] [io.pedestal.log :as log] [genegraph.database.names :as names])) (def variation-descriptor {:name :VariationDescriptor :graphql-type :object :description "A descriptor containing a reference to a GA4GH Variation object, commonly an allele." :implements [:Resource] :fields {:canonical_reference {:type '(list :Resource) :description "A list canonicalizations considered appropriate for the allele described therein." :path [:ga4gh/CanonicalReference]}}}) (def vrs-extension {:name :Extension :graphql-type :object :description "A VRS Extension object" :implements [:Resource] :fields {:name {:type 'String :description "Name of the extension" :path [:vrs/name]} :value {:type 'String :description "Value of the extension" :path [:rdf/value]}}}) (def vrs-allele {:name :Allele :graphql-type :object :description "A GA4GH Allele" :implements [:Resource] :fields {:location {:type :SequenceLocation :path [:vrs/location]} :state {:type :LiteralSequenceExpression :path [:vrs/state]}}}) (def vrs-absolute-copy-number {:name :AbsoluteCopyNumber :graphql-type :object :description "GA4GH Absolute Copy Number Variation" :implements [:Resource] :fields {:subject {:type :SequenceLocation :path [:vrs/subject]} :copies {:type :Number :path [:vrs/copies]}}}) (def vrs-text {:name :Text :graphql-type :object :description "A GA4GH Text variation" :implements [:Resource] :fields {:definition {:type 'String :path [:vrs/definition]}}}) (def vrs-canonical-variation {:name :CanonicalVariation :graphql-type :object :description "A GA4GH CanonicalVariation" :implements [:Resource] :fields {:complement {:type 'Boolean :path [:vrs/complement]} TODO may consider using unions to self - document what types these may be :variation {:type :Resource :description "Variation. May be an Allele, Text, or other types" :path [:vrs/variation]}}}) (def vrs-literal-sequence-expression {:name :LiteralSequenceExpression :graphql-type :object :description "A literal sequence expression" :implements [:Resource] :fields {:sequence {:type 'String :path [:vrs/sequence]}}}) (def vrs-sequence-location {:name :SequenceLocation :graphql-type :object :description "A sequence location" :implements [:Resource] :fields {:interval {:type :SequenceInterval :path [:vrs/interval]} :sequence_id {:type 'String :path [:vrs/sequence-id]}}}) (def vrs-number {:name :Number :graphql-type :object :description "A number with a value" :implements [:Resource] :fields {:value {:type 'Int :path [:vrs/value]}}}) (def vrs-sequence-interval {:name :SequenceInterval :graphql-type :object :description "A sequence interval" :implements [:Resource] :fields {:start {:type :Number :path [:vrs/start]} :end {:type :Number :path [:vrs/end]}}}) (def vrs-expression {:name :Expression :graphql-type :object :description "Expressions of a variation" :implements [:Resource] :fields {:value {:type 'String :description "Value of the expression" :path [:rdf/value]} :syntax {:type 'String :description "A syntax identifier indicating what form the expression is in." :path [:vrs/syntax]} :syntax_version {:type 'String :description "A version of the syntax. (Often not provided)" :path [:vrs/syntax-version]}}}) (def vrs-variation-member {:name :VariationMember :graphql-type :object :description "A VariationMember of an grouping of variation representations." :implements [:Resource] :fields {:expressions {:type '(list :Expression) :description "Expressions for a single variation representation" :path [:vrs/expressions]}}}) (def categorical-variation-descriptor {:name :CategoricalVariationDescriptor :graphql-type :object :description "Descriptor for a categorical variation" :implements [:Resource] :fields {:value {:type :Resource :description "CanonicalVariation or AbsoluteCopyNumber variation" :path [:rdf/value]} :xrefs {:type '(list String) :path [:vrs/xrefs]} :members {:type '(list :VariationMember) :description "Noncanonical variation representations. Exists alongside the canonical representation of the variation." :path [:vrs/members]} :extensions {:type '(list :Extension) :path [:vrs/extensions]}}}) (defn resource-has-predicate? "Accepts and RDFResource and a property name key (e.g. :dc/has-version)" [resource predicate-key] (let [spql "SELECT ?pred_value WHERE { ?resource ?pred ?pred_value }" results (q/select spql {:resource resource :pred predicate-key})] (< 0 (count results)))) (defn resource-has-edge? "Accepts and RDFResource and an incoming or outgoing edge (e.g. [:dc/has-version :<])" [resource edge] (let [vals (q/ld-> resource [edge])] (< 0 (count vals)))) (defn resource-has-type? "Returns true when RDFResource r has a type specified by class-kw. class-kw is resolved against genegraph.database.names/local-class-names" [r class-kw] (let [type-qualified (str (get names/local-class-names class-kw))] (assert (not (nil? type-qualified)) (str "Type could not be resolved: " class-kw)) (log/debug :fn :resource-has-type? :r r :class-kw class-kw :type-qualified type-qualified) (< 0 (count (q/select "SELECT ?iri WHERE { ?iri a ?type }" {:iri r :type (q/resource type-qualified)}))))) (defn variation-descriptor-resolver [context args value] (log/info :fn ::variation-descriptor-resolver :args args :value value) Variation IRIs in the predicate are not resources , they are string literals . So can not use the q / ld- > inverse relation lookup , have to use explicitly . (let [{variation-iri :variation_iri} args variation-resource (q/resource variation-iri) descriptor-resources (if (resource-has-type? variation-resource :vrs/CategoricalVariationDescriptor) [variation-resource] (q/select "SELECT ?descriptor WHERE { ?descriptor :vrs/xrefs ?variation_iri }" {:variation_iri (str variation-resource)}))] (log/debug :variation-iri variation-iri) (log/debug :variation-resource variation-resource) (log/debug :descriptor-resources descriptor-resources) (->> descriptor-resources (sort-by (fn [r] (q/ld1-> r [:owl/version-info]))) last))) (def variation-descriptor-query {:name :variation_descriptor_query :graphql-type :query :description "Find variation descriptors" :type :CategoricalVariationDescriptor :args {:variation_iri {:type 'String :description "An IRI for the thing (variation) described by the descriptors"} :version {:type 'String :description (str "Version to retrieve. This accepts a YYYY-MM-DDTHH-mm-ss.SSSZ datetime string, " "or a static value below:\n" "LATEST: return the latest version of a record matching this criteria.") :default-value "LATEST"}} :resolve variation-descriptor-resolver})
null
https://raw.githubusercontent.com/clingen-data-model/genegraph/10e435cc20461d9232313a98752d4fc0917c00d5/src/genegraph/source/graphql/schema/variation_descriptor.clj
clojure
(ns genegraph.source.graphql.schema.variation-descriptor (:require [genegraph.database.query :as q] [io.pedestal.log :as log] [genegraph.database.names :as names])) (def variation-descriptor {:name :VariationDescriptor :graphql-type :object :description "A descriptor containing a reference to a GA4GH Variation object, commonly an allele." :implements [:Resource] :fields {:canonical_reference {:type '(list :Resource) :description "A list canonicalizations considered appropriate for the allele described therein." :path [:ga4gh/CanonicalReference]}}}) (def vrs-extension {:name :Extension :graphql-type :object :description "A VRS Extension object" :implements [:Resource] :fields {:name {:type 'String :description "Name of the extension" :path [:vrs/name]} :value {:type 'String :description "Value of the extension" :path [:rdf/value]}}}) (def vrs-allele {:name :Allele :graphql-type :object :description "A GA4GH Allele" :implements [:Resource] :fields {:location {:type :SequenceLocation :path [:vrs/location]} :state {:type :LiteralSequenceExpression :path [:vrs/state]}}}) (def vrs-absolute-copy-number {:name :AbsoluteCopyNumber :graphql-type :object :description "GA4GH Absolute Copy Number Variation" :implements [:Resource] :fields {:subject {:type :SequenceLocation :path [:vrs/subject]} :copies {:type :Number :path [:vrs/copies]}}}) (def vrs-text {:name :Text :graphql-type :object :description "A GA4GH Text variation" :implements [:Resource] :fields {:definition {:type 'String :path [:vrs/definition]}}}) (def vrs-canonical-variation {:name :CanonicalVariation :graphql-type :object :description "A GA4GH CanonicalVariation" :implements [:Resource] :fields {:complement {:type 'Boolean :path [:vrs/complement]} TODO may consider using unions to self - document what types these may be :variation {:type :Resource :description "Variation. May be an Allele, Text, or other types" :path [:vrs/variation]}}}) (def vrs-literal-sequence-expression {:name :LiteralSequenceExpression :graphql-type :object :description "A literal sequence expression" :implements [:Resource] :fields {:sequence {:type 'String :path [:vrs/sequence]}}}) (def vrs-sequence-location {:name :SequenceLocation :graphql-type :object :description "A sequence location" :implements [:Resource] :fields {:interval {:type :SequenceInterval :path [:vrs/interval]} :sequence_id {:type 'String :path [:vrs/sequence-id]}}}) (def vrs-number {:name :Number :graphql-type :object :description "A number with a value" :implements [:Resource] :fields {:value {:type 'Int :path [:vrs/value]}}}) (def vrs-sequence-interval {:name :SequenceInterval :graphql-type :object :description "A sequence interval" :implements [:Resource] :fields {:start {:type :Number :path [:vrs/start]} :end {:type :Number :path [:vrs/end]}}}) (def vrs-expression {:name :Expression :graphql-type :object :description "Expressions of a variation" :implements [:Resource] :fields {:value {:type 'String :description "Value of the expression" :path [:rdf/value]} :syntax {:type 'String :description "A syntax identifier indicating what form the expression is in." :path [:vrs/syntax]} :syntax_version {:type 'String :description "A version of the syntax. (Often not provided)" :path [:vrs/syntax-version]}}}) (def vrs-variation-member {:name :VariationMember :graphql-type :object :description "A VariationMember of an grouping of variation representations." :implements [:Resource] :fields {:expressions {:type '(list :Expression) :description "Expressions for a single variation representation" :path [:vrs/expressions]}}}) (def categorical-variation-descriptor {:name :CategoricalVariationDescriptor :graphql-type :object :description "Descriptor for a categorical variation" :implements [:Resource] :fields {:value {:type :Resource :description "CanonicalVariation or AbsoluteCopyNumber variation" :path [:rdf/value]} :xrefs {:type '(list String) :path [:vrs/xrefs]} :members {:type '(list :VariationMember) :description "Noncanonical variation representations. Exists alongside the canonical representation of the variation." :path [:vrs/members]} :extensions {:type '(list :Extension) :path [:vrs/extensions]}}}) (defn resource-has-predicate? "Accepts and RDFResource and a property name key (e.g. :dc/has-version)" [resource predicate-key] (let [spql "SELECT ?pred_value WHERE { ?resource ?pred ?pred_value }" results (q/select spql {:resource resource :pred predicate-key})] (< 0 (count results)))) (defn resource-has-edge? "Accepts and RDFResource and an incoming or outgoing edge (e.g. [:dc/has-version :<])" [resource edge] (let [vals (q/ld-> resource [edge])] (< 0 (count vals)))) (defn resource-has-type? "Returns true when RDFResource r has a type specified by class-kw. class-kw is resolved against genegraph.database.names/local-class-names" [r class-kw] (let [type-qualified (str (get names/local-class-names class-kw))] (assert (not (nil? type-qualified)) (str "Type could not be resolved: " class-kw)) (log/debug :fn :resource-has-type? :r r :class-kw class-kw :type-qualified type-qualified) (< 0 (count (q/select "SELECT ?iri WHERE { ?iri a ?type }" {:iri r :type (q/resource type-qualified)}))))) (defn variation-descriptor-resolver [context args value] (log/info :fn ::variation-descriptor-resolver :args args :value value) Variation IRIs in the predicate are not resources , they are string literals . So can not use the q / ld- > inverse relation lookup , have to use explicitly . (let [{variation-iri :variation_iri} args variation-resource (q/resource variation-iri) descriptor-resources (if (resource-has-type? variation-resource :vrs/CategoricalVariationDescriptor) [variation-resource] (q/select "SELECT ?descriptor WHERE { ?descriptor :vrs/xrefs ?variation_iri }" {:variation_iri (str variation-resource)}))] (log/debug :variation-iri variation-iri) (log/debug :variation-resource variation-resource) (log/debug :descriptor-resources descriptor-resources) (->> descriptor-resources (sort-by (fn [r] (q/ld1-> r [:owl/version-info]))) last))) (def variation-descriptor-query {:name :variation_descriptor_query :graphql-type :query :description "Find variation descriptors" :type :CategoricalVariationDescriptor :args {:variation_iri {:type 'String :description "An IRI for the thing (variation) described by the descriptors"} :version {:type 'String :description (str "Version to retrieve. This accepts a YYYY-MM-DDTHH-mm-ss.SSSZ datetime string, " "or a static value below:\n" "LATEST: return the latest version of a record matching this criteria.") :default-value "LATEST"}} :resolve variation-descriptor-resolver})
24528f02eda46904e9de9239f2572d0102ecbbc52d669affd15c111a9130d49e
ezrakilty/narc
Fallible.hs
# LANGUAGE FlexibleContexts # module Database.Narc.Fallible where import Control.Monad.Error hiding (when, join) import Gensym import Database.Narc.Debug Fallible and ErrorGensym monads -------------------------------------- ( TBD : this is more general than Narc ; factor it out . ) data Fallible a = Failure String | Success a deriving (Eq, Show) instance Monad Fallible where return = Success fail = Failure x >>= k = case x of Failure err -> Failure err Success x' -> k x' runFallible :: Fallible t -> t runFallible (Failure e) = breakFlag $ error e runFallible (Success x) = x fromEither :: Either String a -> Fallible a fromEither (Left err) = Failure err fromEither (Right x) = Success x isError :: Fallible t -> Bool isError (Failure _) = True isError (Success _) = False isSuccess :: Fallible t -> Bool isSuccess (Failure _) = False isSuccess (Success _) = True type FallibleGensym a = ErrorT String Gensym a | Run an ErrorGensym action , raising errors with ` error ' . runFallibleGensym :: ErrorT String Gensym a -> a runFallibleGensym = runFallible . fromEither . runGensym . runErrorT | Try running an ErrorGensym action , packaging result in an Either -- | with Left as failure, Right as success. tryFallibleGensym :: ErrorT String Gensym a -> Fallible a tryFallibleGensym = fromEither . runGensym . runErrorT fromFallible :: (String -> b) -> (a -> b) -> Fallible a -> b fromFallible f _g (Failure err) = f err fromFallible _f g (Success x) = g x under :: MonadError String m => Fallible a -> m a under x = fromFallible throwError return x instance Error () where noMsg = () strMsg _ = ()
null
https://raw.githubusercontent.com/ezrakilty/narc/76310e6ac528fe038d8bdd4aa78fa8c555501fad/Database/Narc/Fallible.hs
haskell
------------------------------------ | with Left as failure, Right as success.
# LANGUAGE FlexibleContexts # module Database.Narc.Fallible where import Control.Monad.Error hiding (when, join) import Gensym import Database.Narc.Debug ( TBD : this is more general than Narc ; factor it out . ) data Fallible a = Failure String | Success a deriving (Eq, Show) instance Monad Fallible where return = Success fail = Failure x >>= k = case x of Failure err -> Failure err Success x' -> k x' runFallible :: Fallible t -> t runFallible (Failure e) = breakFlag $ error e runFallible (Success x) = x fromEither :: Either String a -> Fallible a fromEither (Left err) = Failure err fromEither (Right x) = Success x isError :: Fallible t -> Bool isError (Failure _) = True isError (Success _) = False isSuccess :: Fallible t -> Bool isSuccess (Failure _) = False isSuccess (Success _) = True type FallibleGensym a = ErrorT String Gensym a | Run an ErrorGensym action , raising errors with ` error ' . runFallibleGensym :: ErrorT String Gensym a -> a runFallibleGensym = runFallible . fromEither . runGensym . runErrorT | Try running an ErrorGensym action , packaging result in an Either tryFallibleGensym :: ErrorT String Gensym a -> Fallible a tryFallibleGensym = fromEither . runGensym . runErrorT fromFallible :: (String -> b) -> (a -> b) -> Fallible a -> b fromFallible f _g (Failure err) = f err fromFallible _f g (Success x) = g x under :: MonadError String m => Fallible a -> m a under x = fromFallible throwError return x instance Error () where noMsg = () strMsg _ = ()
7557871aea79f8f34ef9079604a6ed9bfd08ff64a96b456648eb02cc6458492b
dinosaure/bob
relay.ml
let run timeout inet_addr port secure_port backlog = let sockaddr01 = Unix.ADDR_INET (inet_addr, port) in let sockaddr02 = Unix.ADDR_INET (inet_addr, secure_port) in let socket01 = Unix.socket ~cloexec:true (Unix.domain_of_sockaddr sockaddr01) Unix.SOCK_STREAM 0 in Unix.setsockopt socket01 Unix.SO_REUSEADDR true; let socket02 = Unix.socket ~cloexec:true (Unix.domain_of_sockaddr sockaddr02) Unix.SOCK_STREAM 0 in Unix.setsockopt socket02 Unix.SO_REUSEADDR true; let secured = Bob_unix.create_secure_room () in Unix.bind socket01 sockaddr01; Unix.bind socket02 sockaddr02; Unix.listen socket01 backlog; Unix.listen socket02 backlog; let stop = Fiber.Ivar.create () in Sys.set_signal Sys.sigint (Signal_handle (fun _sigint -> Logs.debug (fun m -> m "The user wants to stop the relay."); if Fiber.Ivar.is_empty stop then Fiber.Ivar.fill stop ())); Fiber.run Fiber.( fork_and_join (fun () -> Bob_clear.relay ~timeout socket01 secured ~stop) (fun () -> Bob_unix.secure_room ~timeout socket02 secured ~stop) >>= fun ((), ()) -> Fiber.return ()); Unix.close socket01; Unix.close socket02; `Ok 0 let run _quiet daemonize timeout inet_addr port secure_port backlog () = match daemonize with | Some path -> Daemon.daemonize ~path (fun () -> run timeout inet_addr port secure_port backlog) | None -> run timeout inet_addr port secure_port backlog open Cmdliner open Args let daemonize = let doc = "Daemonize the process and show the PID." in Arg.(value & opt (some string) None & info [ "daemonize" ] ~doc) let timeout = let doc = "How long the relay can keep an active connection (in seconds)." in Arg.(value & opt float 3600. & info [ "t"; "timeout" ] ~doc ~docv:"<seconds>") let inet_addr = let doc = "Set the source address where the relay will be bound." in Arg.( value & pos 0 inet_addr Unix.inet_addr_any & info [] ~doc ~docv:"<inet-addr>") let port = let doc = "Set the port where the relay will listen." in Arg.(value & pos 1 int 9000 & info [] ~doc ~docv:"<port>") let backlog = let doc = "The maximum length to which the queue of pending connections may grow." in Arg.(value & opt int 40 & info [ "b"; "backlog" ] ~doc ~docv:"<backlog>") let pid = let doc = "Write into a file the PID of the relay." in let env = Cmd.Env.info "BOB_PID" in let fpath = Arg.conv (Bob_fpath.of_string, Bob_fpath.pp) in Arg.( value & opt (some fpath) None & info [ "p"; "pid" ] ~env ~doc ~docv:"<filename>") let setup_pid = function | None -> () | Some fpath -> let pid = Unix.getpid () in let oc = open_out_bin (Bob_fpath.to_string fpath) in output_string oc (Fmt.str "%d" pid); close_out oc let term_setup_pid = Term.(const setup_pid $ pid) let cmd = let doc = "Launch the Bob relay." in let man = [ `S Manpage.s_description; `P "$(tname) launches a Bob relay which is able to handle peers and let \ them to do handshakes and transfer files. The relay can be safely \ killed by a $(b,SIGINT) (^C) signal."; ] in Cmd.v (Cmd.info "relay" ~doc ~man) Term.( ret (const run $ term_setup_logs $ daemonize $ timeout $ inet_addr $ port $ secure_port $ backlog $ term_setup_pid)) type configuration = { quiet : bool; daemonize : string option; timeout : float; inet_addr : Unix.inet_addr; port : int; secure_port : int; backlog : int; } let setup_relay quiet daemonize timeout inet_addr port secure_port backlog () = { quiet; daemonize; timeout; inet_addr; port; secure_port; backlog } open Args let inet_addr = let doc = "Set the source address where the relay will be bound." in Arg.( value & pos 1 inet_addr Unix.inet_addr_any & info [] ~doc ~docv:"<inet-addr>") let port = let doc = "Set the port where the relay will listen." in Arg.(value & pos 2 int 9000 & info [] ~doc ~docv:"<port>") let term_setup_relay = Term.( const setup_relay $ term_setup_logs $ daemonize $ timeout $ inet_addr $ port $ secure_port $ backlog $ term_setup_pid)
null
https://raw.githubusercontent.com/dinosaure/bob/7ce049a8fa96f2106c73253f47e18e7f955a9880/bin/relay.ml
ocaml
let run timeout inet_addr port secure_port backlog = let sockaddr01 = Unix.ADDR_INET (inet_addr, port) in let sockaddr02 = Unix.ADDR_INET (inet_addr, secure_port) in let socket01 = Unix.socket ~cloexec:true (Unix.domain_of_sockaddr sockaddr01) Unix.SOCK_STREAM 0 in Unix.setsockopt socket01 Unix.SO_REUSEADDR true; let socket02 = Unix.socket ~cloexec:true (Unix.domain_of_sockaddr sockaddr02) Unix.SOCK_STREAM 0 in Unix.setsockopt socket02 Unix.SO_REUSEADDR true; let secured = Bob_unix.create_secure_room () in Unix.bind socket01 sockaddr01; Unix.bind socket02 sockaddr02; Unix.listen socket01 backlog; Unix.listen socket02 backlog; let stop = Fiber.Ivar.create () in Sys.set_signal Sys.sigint (Signal_handle (fun _sigint -> Logs.debug (fun m -> m "The user wants to stop the relay."); if Fiber.Ivar.is_empty stop then Fiber.Ivar.fill stop ())); Fiber.run Fiber.( fork_and_join (fun () -> Bob_clear.relay ~timeout socket01 secured ~stop) (fun () -> Bob_unix.secure_room ~timeout socket02 secured ~stop) >>= fun ((), ()) -> Fiber.return ()); Unix.close socket01; Unix.close socket02; `Ok 0 let run _quiet daemonize timeout inet_addr port secure_port backlog () = match daemonize with | Some path -> Daemon.daemonize ~path (fun () -> run timeout inet_addr port secure_port backlog) | None -> run timeout inet_addr port secure_port backlog open Cmdliner open Args let daemonize = let doc = "Daemonize the process and show the PID." in Arg.(value & opt (some string) None & info [ "daemonize" ] ~doc) let timeout = let doc = "How long the relay can keep an active connection (in seconds)." in Arg.(value & opt float 3600. & info [ "t"; "timeout" ] ~doc ~docv:"<seconds>") let inet_addr = let doc = "Set the source address where the relay will be bound." in Arg.( value & pos 0 inet_addr Unix.inet_addr_any & info [] ~doc ~docv:"<inet-addr>") let port = let doc = "Set the port where the relay will listen." in Arg.(value & pos 1 int 9000 & info [] ~doc ~docv:"<port>") let backlog = let doc = "The maximum length to which the queue of pending connections may grow." in Arg.(value & opt int 40 & info [ "b"; "backlog" ] ~doc ~docv:"<backlog>") let pid = let doc = "Write into a file the PID of the relay." in let env = Cmd.Env.info "BOB_PID" in let fpath = Arg.conv (Bob_fpath.of_string, Bob_fpath.pp) in Arg.( value & opt (some fpath) None & info [ "p"; "pid" ] ~env ~doc ~docv:"<filename>") let setup_pid = function | None -> () | Some fpath -> let pid = Unix.getpid () in let oc = open_out_bin (Bob_fpath.to_string fpath) in output_string oc (Fmt.str "%d" pid); close_out oc let term_setup_pid = Term.(const setup_pid $ pid) let cmd = let doc = "Launch the Bob relay." in let man = [ `S Manpage.s_description; `P "$(tname) launches a Bob relay which is able to handle peers and let \ them to do handshakes and transfer files. The relay can be safely \ killed by a $(b,SIGINT) (^C) signal."; ] in Cmd.v (Cmd.info "relay" ~doc ~man) Term.( ret (const run $ term_setup_logs $ daemonize $ timeout $ inet_addr $ port $ secure_port $ backlog $ term_setup_pid)) type configuration = { quiet : bool; daemonize : string option; timeout : float; inet_addr : Unix.inet_addr; port : int; secure_port : int; backlog : int; } let setup_relay quiet daemonize timeout inet_addr port secure_port backlog () = { quiet; daemonize; timeout; inet_addr; port; secure_port; backlog } open Args let inet_addr = let doc = "Set the source address where the relay will be bound." in Arg.( value & pos 1 inet_addr Unix.inet_addr_any & info [] ~doc ~docv:"<inet-addr>") let port = let doc = "Set the port where the relay will listen." in Arg.(value & pos 2 int 9000 & info [] ~doc ~docv:"<port>") let term_setup_relay = Term.( const setup_relay $ term_setup_logs $ daemonize $ timeout $ inet_addr $ port $ secure_port $ backlog $ term_setup_pid)
4ec4540a870f0b3f386a4644d2ebb3941e77a6c6610bae9215b49ecb93b578ee
tonsky/compact-uuids
project.clj
(defproject compact-uuids "0.2.1" :description "Compact 26-char URL-safe representation of UUIDs" :license { :name "Eclipse" :url "-v10.html" } :url "-uuids" :dependencies [ [org.clojure/clojure "1.9.0-RC1"] [org.clojure/clojurescript "1.9.946" :scope "provided"] ] :plugins [ [lein-cljsbuild "1.1.7"] ] :profiles { :dev { :dependencies [[criterium "0.4.4"]] } } :aliases {"test-all" ["do" ["clean"] ["test"] ["cljsbuild" "test"]] "bench" [["run" "-m" "compact-uuids.core.bench"]]} :cljsbuild { :test-commands {"test" ["node" "test_node.js"]} :builds [ { :id "advanced" :source-paths ["src" "test"] :compiler { :main compact_uuids.core.test :output-to "target/compact_uuids.js" :output-dir "target/advanced" :optimizations :advanced :parallel-build true } } { :id "none" :source-paths ["src" "test"] :compiler { :main compact_uuids.core.test :output-to "target/compact_uuids.js" :output-dir "target/none" :optimizations :none :parallel-build true } } ]} :mirrors { "central" {:name "central" :url "/"} } )
null
https://raw.githubusercontent.com/tonsky/compact-uuids/b4546a2831f04f5e0c23543e91770af4cddb3b57/project.clj
clojure
(defproject compact-uuids "0.2.1" :description "Compact 26-char URL-safe representation of UUIDs" :license { :name "Eclipse" :url "-v10.html" } :url "-uuids" :dependencies [ [org.clojure/clojure "1.9.0-RC1"] [org.clojure/clojurescript "1.9.946" :scope "provided"] ] :plugins [ [lein-cljsbuild "1.1.7"] ] :profiles { :dev { :dependencies [[criterium "0.4.4"]] } } :aliases {"test-all" ["do" ["clean"] ["test"] ["cljsbuild" "test"]] "bench" [["run" "-m" "compact-uuids.core.bench"]]} :cljsbuild { :test-commands {"test" ["node" "test_node.js"]} :builds [ { :id "advanced" :source-paths ["src" "test"] :compiler { :main compact_uuids.core.test :output-to "target/compact_uuids.js" :output-dir "target/advanced" :optimizations :advanced :parallel-build true } } { :id "none" :source-paths ["src" "test"] :compiler { :main compact_uuids.core.test :output-to "target/compact_uuids.js" :output-dir "target/none" :optimizations :none :parallel-build true } } ]} :mirrors { "central" {:name "central" :url "/"} } )
61edcd9495cab8892fe8773319e16bb4f2569df523bcc08d95f8ceac65dc9aa4
rsnikhil/Forvis_RISCV-ISA-Spec
Forvis_Spec_I.hs
Copyright ( c ) 2018 -- See LICENSE for license details module Forvis_Spec_I where -- ================================================================ -- Part of: specification of all RISC-V instructions. This module is the specification of the RISC - V ' I ' ( Base ) instructions -- ================================================================ -- Haskell lib imports import Data.Bits -- For bit-wise 'and' (.&.) etc. -- Local imports import Bit_Utils import ALU import Arch_Defs import Machine_State import CSR_File import Virtual_Mem import Forvis_Spec_Common -- Canonical ways for finish an instruction -- ================================================================ -- 'I' Base instruction set -- NOTE: opcode_XXX, funct3_XXX are defined in module Arch_Defs -- ================================================================ -- The following is a list of all the specification functions defined below. instr_specs_I :: [(Instr_Spec, String)] instr_specs_I = [(spec_LUI, "LUI"), (spec_AUIPC, "AUIPC"), (spec_JAL, "JAL"), (spec_JALR, "JALR"), (spec_BRANCH, "BRANCH"), (spec_LOAD, "LOAD"), (spec_STORE, "STORE"), (spec_OP_IMM, "OP_IMM"), (spec_OP, "OP"), (spec_MISC_MEM, "MISC_MEM"), (spec_SYSTEM_ECALL, "SYSTEM_ECALL"), (spec_SYSTEM_EBREAK, "SYSTEM_EBREAK"), (spec_SYSTEM_CSRRW, "SYSTEM_CSRRW"), (spec_SYSTEM_CSRR_S_C, "SYSTEM_CSRR_S_C"), (spec_OP_IMM_32, "OP_IMM_32"), (spec_OP_32, "OP_32") ] -- ================================================================ LUI spec_LUI :: Machine_State -> Instr -> Bool -> (Bool, Machine_State) spec_LUI mstate instr is_C = let -- Instr fields: U-type (imm20, rd, opcode) = ifields_U_type instr -- Decode check is_legal = (opcode == opcode_LUI) Semantics xlen = mstate_xlen_read mstate imm32 = shiftL imm20 12 rd_val = sign_extend 32 xlen imm32 mstate1 = finish_rd_and_pc_incr mstate rd rd_val is_C in (is_legal, mstate1) -- ================================================================ AUIPC spec_AUIPC :: Machine_State -> Instr -> Bool -> (Bool, Machine_State) spec_AUIPC mstate instr is_C = let -- Instr fields: U-type (imm20, rd, opcode) = ifields_U_type instr -- Decode check is_legal = (opcode == opcode_AUIPC) Semantics xlen = mstate_xlen_read mstate pc = mstate_pc_read mstate imm32 = shiftL imm20 12 s_offset = sign_extend 32 xlen imm32 rd_val = alu_add xlen pc s_offset mstate1 = finish_rd_and_pc_incr mstate rd rd_val is_C in (is_legal, mstate1) -- ================================================================ JAL spec_JAL :: Machine_State -> Instr -> Bool -> (Bool, Machine_State) spec_JAL mstate instr is_C = let -- Instr fields: J-type (imm21, rd, opcode) = ifields_J_type instr -- Decode check is_legal = (opcode == opcode_JAL) Semantics rv = mstate_rv_read mstate misa = mstate_csr_read mstate csr_addr_misa xlen = mstate_xlen_read mstate pc = mstate_pc_read mstate rd_val = if is_C then pc + 2 else pc + 4 s_offset = sign_extend 21 xlen imm21 new_pc = alu_add xlen pc s_offset aligned = if (misa_flag misa 'C') then ((new_pc .&. 0x1) == 0) else ((new_pc .&. 0x3) == 0) mstate1 = if aligned then finish_rd_and_pc mstate rd rd_val new_pc else finish_trap mstate exc_code_instr_addr_misaligned new_pc in (is_legal, mstate1) -- ================================================================ -- JALR spec_JALR :: Machine_State -> Instr -> Bool -> (Bool, Machine_State) spec_JALR mstate instr is_C = let -- Instr fields: I-type (imm12, rs1, funct3, rd, opcode) = ifields_I_type instr -- Decode check is_legal = (( opcode == opcode_JALR) && (funct3 == funct3_JALR)) Semantics rv = mstate_rv_read mstate misa = mstate_csr_read mstate csr_addr_misa xlen = mstate_xlen_read mstate pc = mstate_pc_read mstate rd_val = if is_C then pc + 2 else pc + 4 s_offset = sign_extend 12 xlen imm12 rs1_val = mstate_gpr_read mstate rs1 new_pc = alu_add xlen rs1_val s_offset new_pc' = clearBit new_pc 0 aligned = if (misa_flag misa 'C') then True else ((new_pc' .&. 0x3) == 0) mstate1 = if aligned then finish_rd_and_pc mstate rd rd_val new_pc' else finish_trap mstate exc_code_instr_addr_misaligned new_pc' in (is_legal, mstate1) -- ================================================================ BRANCH : BEQ , BNE , BLT , BGE , BLTU , BGEU spec_BRANCH :: Machine_State -> Instr -> Bool -> (Bool, Machine_State) spec_BRANCH mstate instr is_C = let -- Instr fields: B-type (imm13, rs2, rs1, funct3, opcode) = ifields_B_type instr -- Decode check is_BEQ = (funct3 == funct3_BEQ) is_BNE = (funct3 == funct3_BNE) is_BLT = (funct3 == funct3_BLT) is_BGE = (funct3 == funct3_BGE) is_BLTU = (funct3 == funct3_BLTU) is_BGEU = (funct3 == funct3_BGEU) is_legal = ((opcode == opcode_BRANCH) && (is_BEQ || is_BNE || is_BLT || is_BGE || is_BLTU || is_BGEU)) Semantics xlen = mstate_xlen_read mstate rs1_val = mstate_gpr_read mstate rs1 rs2_val = mstate_gpr_read mstate rs2 taken | is_BEQ = alu_eq xlen rs1_val rs2_val | is_BNE = alu_ne xlen rs1_val rs2_val | is_BLT = alu_lt xlen rs1_val rs2_val | is_BGE = alu_ge xlen rs1_val rs2_val | is_BLTU = alu_ltu xlen rs1_val rs2_val | is_BGEU = alu_geu xlen rs1_val rs2_val pc = mstate_pc_read mstate s_offset = sign_extend 13 xlen imm13 target = alu_add xlen pc s_offset new_pc = if taken then target else if is_C then pc + 2 else pc + 4 misa = mstate_csr_read mstate csr_addr_misa new_pc[0 ] known to be 0 , new_pc[1 ] must be 0 if ' C ' is not supported aligned = (misa_flag misa 'C' || (new_pc .&. 0x2 == 0)) mstate1 = if aligned then finish_pc mstate new_pc else finish_trap mstate exc_code_instr_addr_misaligned new_pc in (is_legal, mstate1) -- ================================================================ -- LOAD: RV32 : LB , LH , LW , LBU , LHU : LWU , LD spec_LOAD :: Machine_State -> Instr -> Bool -> (Bool, Machine_State) spec_LOAD mstate instr is_C = let -- Instr fields: I-type (imm12, rs1, funct3, rd, opcode) = ifields_I_type instr -- Decode check rv = mstate_rv_read mstate xlen = mstate_xlen_read mstate is_LB = (funct3 == funct3_LB) is_LH = (funct3 == funct3_LH) is_LW = (funct3 == funct3_LW) is_LD = (funct3 == funct3_LD) is_LBU = (funct3 == funct3_LBU) is_LHU = (funct3 == funct3_LHU) is_LWU = (funct3 == funct3_LWU) is_legal = ((opcode == opcode_LOAD) && (is_LB || is_LH || is_LW || (is_LD && (rv == RV64)) || is_LBU || is_LHU || (is_LWU && (rv == RV64)))) Semantics -- Compute effective address rs1_val = mstate_gpr_read mstate rs1 s_imm12 = sign_extend 12 xlen imm12 eaddr1 = alu_add xlen rs1_val s_imm12 eaddr2 = if (rv == RV64) then eaddr1 else (eaddr1 .&. 0xffffFFFF) -- If Virtual Mem is active, translate to a physical addr is_instr = False is_read = True (result1, mstate1) = if (fn_vm_is_active mstate is_instr) then vm_translate mstate is_instr is_read eaddr2 else (Mem_Result_Ok eaddr2, mstate) -- If no trap due to Virtual Mem translation, read from memory (result2, mstate2) = case result1 of Mem_Result_Err exc_code -> (result1, mstate1) Mem_Result_Ok eaddr2_pa -> mstate_mem_read mstate1 exc_code_load_access_fault funct3 eaddr2_pa -- Finally: finish with trap, or finish with loading Rd with load-value mstate3 = case result2 of Mem_Result_Err exc_code -> finish_trap mstate2 exc_code eaddr2 Mem_Result_Ok d -> let rd_val | is_LB = sign_extend 8 xlen d | is_LH = sign_extend 16 xlen d | is_LW = sign_extend 32 xlen d | True = d in finish_rd_and_pc_incr mstate2 rd rd_val is_C in (is_legal, mstate3) -- ================================================================ -- STORE: : SB , SH , SW : SD spec_STORE :: Machine_State -> Instr -> Bool -> (Bool, Machine_State) spec_STORE mstate instr is_C = let -- Instr fields: S-type (imm12, rs2, rs1, funct3, opcode) = ifields_S_type instr -- Decode check rv = mstate_rv_read mstate xlen = mstate_xlen_read mstate is_SB = (funct3 == funct3_SB) is_SH = (funct3 == funct3_SH) is_SW = (funct3 == funct3_SW) is_SD = ((funct3 == funct3_SD) && (rv == RV64)) is_legal = ((opcode == opcode_STORE) && (is_SB || is_SH || is_SW || is_SD)) Semantics rs2_val = mstate_gpr_read mstate rs2 -- store value -- Compute effective address rs1_val = mstate_gpr_read mstate rs1 -- address base s_imm12 = sign_extend 12 xlen imm12 eaddr1 = alu_add xlen rs1_val s_imm12 eaddr2 = if (rv == RV64) then eaddr1 else (eaddr1 .&. 0xffffFFFF) -- If Virtual Mem is active, translate to a physical addr is_instr = False is_read = False (result1, mstate1) = if (fn_vm_is_active mstate is_instr) then vm_translate mstate is_instr is_read eaddr2 else (Mem_Result_Ok eaddr2, mstate) -- If no trap due to Virtual Mem translation, store to memory (result2, mstate2) = case result1 of Mem_Result_Err exc_code -> (result1, mstate1) Mem_Result_Ok eaddr2_pa -> mstate_mem_write mstate1 funct3 eaddr2_pa rs2_val -- Finally: finish with trap, or finish with fall-through mstate3 = case result2 of Mem_Result_Err exc_code -> finish_trap mstate2 exc_code eaddr2 Mem_Result_Ok _ -> finish_pc_incr mstate2 is_C in (is_legal, mstate3) -- ================================================================ OP_IMM : ADDI , SLTI , SLTIU , XORI , ORI , ANDI , SLLI , SRLI , SRAI spec_OP_IMM :: Machine_State -> Instr -> Bool -> (Bool, Machine_State) spec_OP_IMM mstate instr is_C = let -- Instr fields: I-type (imm12, rs1, funct3, rd, opcode) = ifields_I_type instr (msbs7, shamt5) = ifields_I_type_imm12_32 imm12 (msbs6, shamt6) = ifields_I_type_imm12_64 imm12 -- Decode check rv = mstate_rv_read mstate xlen = mstate_xlen_read mstate is_ADDI = (funct3 == funct3_ADDI) is_SLTI = (funct3 == funct3_SLTI) is_SLTIU = (funct3 == funct3_SLTIU) is_XORI = (funct3 == funct3_XORI) is_ORI = (funct3 == funct3_ORI) is_ANDI = (funct3 == funct3_ANDI) is_SLLI = ((funct3 == funct3_SLLI) && (( (rv == RV32) && (msbs7 == msbs7_SLLI)) || ((rv == RV64) && (msbs6 == msbs6_SLLI)))) is_SRLI = ((funct3 == funct3_SRLI) && (( (rv == RV32) && (msbs7 == msbs7_SRLI)) || ((rv == RV64) && (msbs6 == msbs6_SRLI)))) is_SRAI = ((funct3 == funct3_SRAI) && (( (rv == RV32) && (msbs7 == msbs7_SRAI)) || ((rv == RV64) && (msbs6 == msbs6_SRAI)))) is_legal = ((opcode == opcode_OP_IMM) && (is_ADDI || is_SLTI || is_SLTIU || is_XORI || is_ORI || is_ANDI || is_SLLI || is_SRLI || is_SRAI )) Semantics rs1_val = mstate_gpr_read mstate rs1 s_imm12 = sign_extend 12 xlen imm12 rd_val | is_ADDI = alu_add xlen rs1_val s_imm12 | is_SLTI = alu_slt xlen rs1_val s_imm12 | is_SLTIU = alu_sltu xlen rs1_val s_imm12 | is_XORI = alu_xor xlen rs1_val s_imm12 | is_ORI = alu_or xlen rs1_val s_imm12 | is_ANDI = alu_and xlen rs1_val s_imm12 | is_SLLI = alu_sll xlen rs1_val imm12 | is_SRLI = alu_srl xlen rs1_val imm12 | is_SRAI = alu_sra xlen rs1_val imm12 mstate1 = finish_rd_and_pc_incr mstate rd rd_val is_C in (is_legal, mstate1) -- ================================================================ OP : ADD , SUB , SLT , SLTU , XOR , OR , AND , SLL , SRL , SRA -- \begin_latex{spec_ADD_1} spec_OP :: Machine_State -> Instr -> Bool -> (Bool, Machine_State) spec_OP mstate instr is_C = let -- Instr fields: R-type (funct7, rs2, rs1, funct3, rd, opcode) = ifields_R_type instr -- Decode check is_ADD = ((funct3 == funct3_ADD) && (funct7 == funct7_ADD)) is_SUB = ((funct3 == funct3_SUB) && (funct7 == funct7_SUB)) -- \end_latex{spec_ADD_1} is_SLT = ((funct3 == funct3_SLT) && (funct7 == funct7_SLT)) is_SLTU = ((funct3 == funct3_SLTU) && (funct7 == funct7_SLTU)) is_XOR = ((funct3 == funct3_XOR) && (funct7 == funct7_XOR)) is_OR = ((funct3 == funct3_OR) && (funct7 == funct7_OR)) is_AND = ((funct3 == funct3_AND) && (funct7 == funct7_AND)) is_SLL = ((funct3 == funct3_SLL) && (funct7 == funct7_SLL)) is_SRL = ((funct3 == funct3_SRL) && (funct7 == funct7_SRL)) is_SRA = ((funct3 == funct3_SRA) && (funct7 == funct7_SRA)) -- \begin_latex{spec_ADD_2} is_legal = ((opcode == opcode_OP) && (is_ADD || is_SUB || is_SLT -- \end_latex{spec_ADD_2} || is_SLTU || is_XOR || is_OR || is_AND || is_SLL || is_SRL || is_SRA )) -- \begin_latex{spec_ADD_3} Semantics xlen = mstate_xlen_read mstate -- \end_latex{spec_ADD_3} rs1_val = mstate_gpr_read mstate rs1 rs2_val = mstate_gpr_read mstate rs2 -- \begin_latex{spec_ADD_4} rd_val | is_ADD = alu_add xlen rs1_val rs2_val | is_SUB = alu_sub xlen rs1_val rs2_val | is_SLT = alu_slt xlen rs1_val rs2_val | is_SLTU = alu_sltu xlen rs1_val rs2_val -- \end_latex{spec_ADD_4} | is_XOR = alu_xor xlen rs1_val rs2_val | is_OR = alu_or xlen rs1_val rs2_val | is_AND = alu_and xlen rs1_val rs2_val | is_SLL = alu_sll xlen rs1_val rs2_val | is_SRL = alu_srl xlen rs1_val rs2_val | is_SRA = alu_sra xlen rs1_val rs2_val -- \begin_latex{spec_ADD_5} mstate1 = finish_rd_and_pc_incr mstate rd rd_val is_C in (is_legal, mstate1) -- \end_latex{spec_ADD_5} -- ================================================================ MISC_MEM : FENCE , FENCE.I -- These are technically architectural 'no-ops', but they can modify -- hidden micro-arch state that affects future memory ops spec_MISC_MEM :: Machine_State -> Instr -> Bool -> (Bool, Machine_State) spec_MISC_MEM mstate instr is_C = let -- Instr fields: R-type (imm12, rs1, funct3, rd, opcode) = ifields_I_type instr (msbs4, pred, succ) = ifields_I_type_imm12_FENCE imm12 -- Decode check is_FENCE = ((funct3 == funct3_FENCE) && (rd == 0) && (rs1 == 0) && (msbs4 == 0)) is_FENCE_I = ((funct3 == funct3_FENCE_I) && (rd == 0) && (rs1 == 0) && (imm12 == 0)) is_legal = ((opcode == opcode_MISC_MEM) && (is_FENCE || is_FENCE_I)) Semantics mstate1 | is_FENCE = mstate_mem_fence mstate | is_FENCE_I = mstate_mem_fence_i mstate mstate2 = finish_pc_incr mstate1 is_C in (is_legal, mstate2) -- ================================================================ -- SYSTEM instructions in Base Instruction Set: -- PRIV: ECALL, EBREAK other : CSRRW , CSRRS , CSRRC , CSRRWI , CSRRSI , CSRRCI -- ---------------- -- SYSTEM.PRIV.ECALL spec_SYSTEM_ECALL :: Machine_State -> Instr -> Bool -> (Bool, Machine_State) spec_SYSTEM_ECALL mstate instr is_C = let -- Instr fields: I-type (funct12, rs1, funct3, rd, opcode) = ifields_I_type instr -- Decode check is_legal = ((opcode == opcode_SYSTEM) && (funct3 == funct3_PRIV) && (funct12 == funct12_ECALL) && (rs1 == 0) && (rd == 0)) Semantics priv = mstate_priv_read mstate exc_code | priv == m_Priv_Level = exc_code_ECall_from_M | priv == s_Priv_Level = exc_code_ECall_from_S | priv == u_Priv_Level = exc_code_ECall_from_U | True = error ("Illegal priv " ++ show (priv)) tval = 0 mstate1 = finish_trap mstate exc_code tval in (is_legal, mstate1) -- ---------------- SYSTEM.PRIV.EBREAK spec_SYSTEM_EBREAK :: Machine_State -> Instr -> Bool -> (Bool, Machine_State) spec_SYSTEM_EBREAK mstate instr is_C = let -- Instr fields: I-type (funct12, rs1, funct3, rd, opcode) = ifields_I_type instr -- Decode check is_legal = ((opcode == opcode_SYSTEM) && (funct3 == funct3_PRIV) && (funct12 == funct12_EBREAK) && (rs1 == 0) && (rd == 0)) Semantics exc_code = exc_code_breakpoint tval = mstate_pc_read mstate mstate1 = finish_trap mstate exc_code tval in (is_legal, mstate1) -- ---------------- SYSTEM.not PRIV : CSRRW , CSRRS , CSRRC , CSRRWI , CSRRSI , CSRRCI spec_SYSTEM_CSRRW :: Machine_State -> Instr -> Bool -> (Bool, Machine_State) spec_SYSTEM_CSRRW mstate instr is_C = let -- Instr fields: I-Type (csr_addr, rs1, funct3, rd, opcode) = ifields_I_type instr zimm = rs1 -- Decode check is_CSRRW = (funct3 == funct3_CSRRW) is_CSRRWI = (funct3 == funct3_CSRRWI) is_legal = ((opcode == opcode_SYSTEM) && (is_CSRRW || is_CSRRWI)) Semantics priv = mstate_priv_read mstate permission = mstate_csr_read_permission mstate priv csr_addr legal2 = (permission == CSR_Permission_RW) -- Read CSR only if rd is not 0 old_csr_val = if (rd /= 0) then if (csr_addr == csr_addr_time) then let CSR TIME is a read - only shadow of MTIME , -- which is actually a memory-mapped location, -- not a CSR mtime = mstate_mem_read_mtime mstate in mtime else mstate_csr_read mstate csr_addr else 0 -- arbitrary; will be discarded (rd==0) rs1_val = mstate_gpr_read mstate rs1 new_csr_val | is_CSRRW = rs1_val | is_CSRRWI = rs1 rd_val = old_csr_val mstate1 = if legal2 then FCSR consists of two sub - CSRs , there is a special function -- to handle writes to FCSR let mstate_a = mstate_csr_write mstate csr_addr new_csr_val in finish_rd_and_pc_incr mstate_a rd rd_val is_C else let tval = instr in finish_trap mstate exc_code_illegal_instruction tval in (is_legal, mstate1) spec_SYSTEM_CSRR_S_C :: Machine_State -> Instr -> Bool -> (Bool, Machine_State) spec_SYSTEM_CSRR_S_C mstate instr is_C = let -- Instr fields: I-Type (csr_addr, rs1, funct3, rd, opcode) = ifields_I_type instr zimm = rs1 -- Decode check is_CSRRS = (funct3 == funct3_CSRRS) is_CSRRC = (funct3 == funct3_CSRRC) is_CSRRSI = (funct3 == funct3_CSRRSI) is_CSRRCI = (funct3 == funct3_CSRRCI) is_legal = ((opcode == opcode_SYSTEM) && (is_CSRRS || is_CSRRC || is_CSRRSI || is_CSRRCI)) Semantics priv = mstate_priv_read mstate permission = mstate_csr_read_permission mstate priv csr_addr legal2 | (permission == CSR_Permission_None) = False | (permission == CSR_Permission_RO) = (rs1 == 0) | (permission == CSR_Permission_RW) = True old_csr_val = mstate_csr_read mstate csr_addr rs1_val = mstate_gpr_read mstate rs1 new_csr_val | is_CSRRS = old_csr_val .|. rs1_val | is_CSRRC = old_csr_val .&. (complement rs1_val) | is_CSRRSI = old_csr_val .|. rs1 | is_CSRRCI = old_csr_val .&. (complement rs1) rd_val = old_csr_val mstate1 = if legal2 then -- Write CSR only if rs1/zimm is not 0 let mstate_a | (rs1 /= 0) = mstate_csr_write mstate csr_addr new_csr_val | True = mstate in finish_rd_and_pc_incr mstate_a rd rd_val is_C else let tval = instr in finish_trap mstate exc_code_illegal_instruction tval in (is_legal, mstate1) -- ================================================================ OP - IMM-32 : ADDIW , SLLIW , SRLIW , SRAIW spec_OP_IMM_32 :: Machine_State -> Instr -> Bool -> (Bool, Machine_State) spec_OP_IMM_32 mstate instr is_C = let -- Instr fields: R-type (imm12, rs1, funct3, rd, opcode) = ifields_I_type instr (funct7, shamt_5) = ifields_I_type_imm12_32 imm12 -- Decode check rv = mstate_rv_read mstate xlen = mstate_xlen_read mstate is_ADDIW = ( funct3 == funct3_ADDIW) is_SLLIW = ((funct3 == funct3_SLLIW) && (funct7 == funct7_SLLIW)) is_SRLIW = ((funct3 == funct3_SRLIW) && (funct7 == funct7_SRLIW)) is_SRAIW = ((funct3 == funct3_SRAIW) && (funct7 == funct7_SRAIW)) is_legal = ((rv == RV64) && (opcode == opcode_OP_IMM_32) && (is_ADDIW || is_SLLIW || is_SRLIW || is_SRAIW )) Semantics rs1_val = mstate_gpr_read mstate rs1 rd_val | is_ADDIW = alu_addw rs1_val (sign_extend 12 xlen imm12) | is_SLLIW = alu_sllw rs1_val shamt_5 | is_SRLIW = alu_srlw rs1_val shamt_5 | is_SRAIW = alu_sraw rs1_val shamt_5 mstate1 = finish_rd_and_pc_incr mstate rd rd_val is_C in (is_legal, mstate1) -- ================================================================ OP-32 : for : ADDW , SUBW , SLLW , , SRAW spec_OP_32 :: Machine_State -> Instr -> Bool -> (Bool, Machine_State) spec_OP_32 mstate instr is_C = let -- Instr fields: R-type (funct7, rs2, rs1, funct3, rd, opcode) = ifields_R_type instr -- Decode check rv = mstate_rv_read mstate is_ADDW = ((funct3 == funct3_ADDW) && (funct7 == funct7_ADDW)) is_SUBW = ((funct3 == funct3_SUBW) && (funct7 == funct7_SUBW)) is_SLLW = ((funct3 == funct3_SLLW) && (funct7 == funct7_SLLW)) is_SRLW = ((funct3 == funct3_SRLW) && (funct7 == funct7_SRLW)) is_SRAW = ((funct3 == funct3_SRAW) && (funct7 == funct7_SRAW)) is_legal = ((rv == RV64) && (opcode == opcode_OP_32) && (is_ADDW || is_SUBW || is_SLLW || is_SRLW || is_SRAW)) Semantics rs1_val = mstate_gpr_read mstate rs1 rs2_val = mstate_gpr_read mstate rs2 rd_val | is_ADDW = alu_addw rs1_val rs2_val | is_SUBW = alu_subw rs1_val rs2_val | is_SLLW = alu_sllw rs1_val rs2_val | is_SRLW = alu_srlw rs1_val rs2_val | is_SRAW = alu_sraw rs1_val rs2_val mstate1 = finish_rd_and_pc_incr mstate rd rd_val is_C in (is_legal, mstate1) -- ================================================================
null
https://raw.githubusercontent.com/rsnikhil/Forvis_RISCV-ISA-Spec/0c5590a12f4b39644d0497fa6285ad5e33003dfc/ZZ_OLD/v3/Forvis_Spec_I.hs
haskell
See LICENSE for license details ================================================================ Part of: specification of all RISC-V instructions. ================================================================ Haskell lib imports For bit-wise 'and' (.&.) etc. Local imports Canonical ways for finish an instruction ================================================================ 'I' Base instruction set NOTE: opcode_XXX, funct3_XXX are defined in module Arch_Defs ================================================================ The following is a list of all the specification functions defined below. ================================================================ Instr fields: U-type Decode check ================================================================ Instr fields: U-type Decode check ================================================================ Instr fields: J-type Decode check ================================================================ JALR Instr fields: I-type Decode check ================================================================ Instr fields: B-type Decode check ================================================================ LOAD: Instr fields: I-type Decode check Compute effective address If Virtual Mem is active, translate to a physical addr If no trap due to Virtual Mem translation, read from memory Finally: finish with trap, or finish with loading Rd with load-value ================================================================ STORE: Instr fields: S-type Decode check store value Compute effective address address base If Virtual Mem is active, translate to a physical addr If no trap due to Virtual Mem translation, store to memory Finally: finish with trap, or finish with fall-through ================================================================ Instr fields: I-type Decode check ================================================================ \begin_latex{spec_ADD_1} Instr fields: R-type Decode check \end_latex{spec_ADD_1} \begin_latex{spec_ADD_2} \end_latex{spec_ADD_2} \begin_latex{spec_ADD_3} \end_latex{spec_ADD_3} \begin_latex{spec_ADD_4} \end_latex{spec_ADD_4} \begin_latex{spec_ADD_5} \end_latex{spec_ADD_5} ================================================================ These are technically architectural 'no-ops', but they can modify hidden micro-arch state that affects future memory ops Instr fields: R-type Decode check ================================================================ SYSTEM instructions in Base Instruction Set: PRIV: ECALL, EBREAK ---------------- SYSTEM.PRIV.ECALL Instr fields: I-type Decode check ---------------- Instr fields: I-type Decode check ---------------- Instr fields: I-Type Decode check Read CSR only if rd is not 0 which is actually a memory-mapped location, not a CSR arbitrary; will be discarded (rd==0) to handle writes to FCSR Instr fields: I-Type Decode check Write CSR only if rs1/zimm is not 0 ================================================================ Instr fields: R-type Decode check ================================================================ Instr fields: R-type Decode check ================================================================
Copyright ( c ) 2018 module Forvis_Spec_I where This module is the specification of the RISC - V ' I ' ( Base ) instructions import Bit_Utils import ALU import Arch_Defs import Machine_State import CSR_File import Virtual_Mem instr_specs_I :: [(Instr_Spec, String)] instr_specs_I = [(spec_LUI, "LUI"), (spec_AUIPC, "AUIPC"), (spec_JAL, "JAL"), (spec_JALR, "JALR"), (spec_BRANCH, "BRANCH"), (spec_LOAD, "LOAD"), (spec_STORE, "STORE"), (spec_OP_IMM, "OP_IMM"), (spec_OP, "OP"), (spec_MISC_MEM, "MISC_MEM"), (spec_SYSTEM_ECALL, "SYSTEM_ECALL"), (spec_SYSTEM_EBREAK, "SYSTEM_EBREAK"), (spec_SYSTEM_CSRRW, "SYSTEM_CSRRW"), (spec_SYSTEM_CSRR_S_C, "SYSTEM_CSRR_S_C"), (spec_OP_IMM_32, "OP_IMM_32"), (spec_OP_32, "OP_32") ] LUI spec_LUI :: Machine_State -> Instr -> Bool -> (Bool, Machine_State) spec_LUI mstate instr is_C = let (imm20, rd, opcode) = ifields_U_type instr is_legal = (opcode == opcode_LUI) Semantics xlen = mstate_xlen_read mstate imm32 = shiftL imm20 12 rd_val = sign_extend 32 xlen imm32 mstate1 = finish_rd_and_pc_incr mstate rd rd_val is_C in (is_legal, mstate1) AUIPC spec_AUIPC :: Machine_State -> Instr -> Bool -> (Bool, Machine_State) spec_AUIPC mstate instr is_C = let (imm20, rd, opcode) = ifields_U_type instr is_legal = (opcode == opcode_AUIPC) Semantics xlen = mstate_xlen_read mstate pc = mstate_pc_read mstate imm32 = shiftL imm20 12 s_offset = sign_extend 32 xlen imm32 rd_val = alu_add xlen pc s_offset mstate1 = finish_rd_and_pc_incr mstate rd rd_val is_C in (is_legal, mstate1) JAL spec_JAL :: Machine_State -> Instr -> Bool -> (Bool, Machine_State) spec_JAL mstate instr is_C = let (imm21, rd, opcode) = ifields_J_type instr is_legal = (opcode == opcode_JAL) Semantics rv = mstate_rv_read mstate misa = mstate_csr_read mstate csr_addr_misa xlen = mstate_xlen_read mstate pc = mstate_pc_read mstate rd_val = if is_C then pc + 2 else pc + 4 s_offset = sign_extend 21 xlen imm21 new_pc = alu_add xlen pc s_offset aligned = if (misa_flag misa 'C') then ((new_pc .&. 0x1) == 0) else ((new_pc .&. 0x3) == 0) mstate1 = if aligned then finish_rd_and_pc mstate rd rd_val new_pc else finish_trap mstate exc_code_instr_addr_misaligned new_pc in (is_legal, mstate1) spec_JALR :: Machine_State -> Instr -> Bool -> (Bool, Machine_State) spec_JALR mstate instr is_C = let (imm12, rs1, funct3, rd, opcode) = ifields_I_type instr is_legal = (( opcode == opcode_JALR) && (funct3 == funct3_JALR)) Semantics rv = mstate_rv_read mstate misa = mstate_csr_read mstate csr_addr_misa xlen = mstate_xlen_read mstate pc = mstate_pc_read mstate rd_val = if is_C then pc + 2 else pc + 4 s_offset = sign_extend 12 xlen imm12 rs1_val = mstate_gpr_read mstate rs1 new_pc = alu_add xlen rs1_val s_offset new_pc' = clearBit new_pc 0 aligned = if (misa_flag misa 'C') then True else ((new_pc' .&. 0x3) == 0) mstate1 = if aligned then finish_rd_and_pc mstate rd rd_val new_pc' else finish_trap mstate exc_code_instr_addr_misaligned new_pc' in (is_legal, mstate1) BRANCH : BEQ , BNE , BLT , BGE , BLTU , BGEU spec_BRANCH :: Machine_State -> Instr -> Bool -> (Bool, Machine_State) spec_BRANCH mstate instr is_C = let (imm13, rs2, rs1, funct3, opcode) = ifields_B_type instr is_BEQ = (funct3 == funct3_BEQ) is_BNE = (funct3 == funct3_BNE) is_BLT = (funct3 == funct3_BLT) is_BGE = (funct3 == funct3_BGE) is_BLTU = (funct3 == funct3_BLTU) is_BGEU = (funct3 == funct3_BGEU) is_legal = ((opcode == opcode_BRANCH) && (is_BEQ || is_BNE || is_BLT || is_BGE || is_BLTU || is_BGEU)) Semantics xlen = mstate_xlen_read mstate rs1_val = mstate_gpr_read mstate rs1 rs2_val = mstate_gpr_read mstate rs2 taken | is_BEQ = alu_eq xlen rs1_val rs2_val | is_BNE = alu_ne xlen rs1_val rs2_val | is_BLT = alu_lt xlen rs1_val rs2_val | is_BGE = alu_ge xlen rs1_val rs2_val | is_BLTU = alu_ltu xlen rs1_val rs2_val | is_BGEU = alu_geu xlen rs1_val rs2_val pc = mstate_pc_read mstate s_offset = sign_extend 13 xlen imm13 target = alu_add xlen pc s_offset new_pc = if taken then target else if is_C then pc + 2 else pc + 4 misa = mstate_csr_read mstate csr_addr_misa new_pc[0 ] known to be 0 , new_pc[1 ] must be 0 if ' C ' is not supported aligned = (misa_flag misa 'C' || (new_pc .&. 0x2 == 0)) mstate1 = if aligned then finish_pc mstate new_pc else finish_trap mstate exc_code_instr_addr_misaligned new_pc in (is_legal, mstate1) RV32 : LB , LH , LW , LBU , LHU : LWU , LD spec_LOAD :: Machine_State -> Instr -> Bool -> (Bool, Machine_State) spec_LOAD mstate instr is_C = let (imm12, rs1, funct3, rd, opcode) = ifields_I_type instr rv = mstate_rv_read mstate xlen = mstate_xlen_read mstate is_LB = (funct3 == funct3_LB) is_LH = (funct3 == funct3_LH) is_LW = (funct3 == funct3_LW) is_LD = (funct3 == funct3_LD) is_LBU = (funct3 == funct3_LBU) is_LHU = (funct3 == funct3_LHU) is_LWU = (funct3 == funct3_LWU) is_legal = ((opcode == opcode_LOAD) && (is_LB || is_LH || is_LW || (is_LD && (rv == RV64)) || is_LBU || is_LHU || (is_LWU && (rv == RV64)))) Semantics rs1_val = mstate_gpr_read mstate rs1 s_imm12 = sign_extend 12 xlen imm12 eaddr1 = alu_add xlen rs1_val s_imm12 eaddr2 = if (rv == RV64) then eaddr1 else (eaddr1 .&. 0xffffFFFF) is_instr = False is_read = True (result1, mstate1) = if (fn_vm_is_active mstate is_instr) then vm_translate mstate is_instr is_read eaddr2 else (Mem_Result_Ok eaddr2, mstate) (result2, mstate2) = case result1 of Mem_Result_Err exc_code -> (result1, mstate1) Mem_Result_Ok eaddr2_pa -> mstate_mem_read mstate1 exc_code_load_access_fault funct3 eaddr2_pa mstate3 = case result2 of Mem_Result_Err exc_code -> finish_trap mstate2 exc_code eaddr2 Mem_Result_Ok d -> let rd_val | is_LB = sign_extend 8 xlen d | is_LH = sign_extend 16 xlen d | is_LW = sign_extend 32 xlen d | True = d in finish_rd_and_pc_incr mstate2 rd rd_val is_C in (is_legal, mstate3) : SB , SH , SW : SD spec_STORE :: Machine_State -> Instr -> Bool -> (Bool, Machine_State) spec_STORE mstate instr is_C = let (imm12, rs2, rs1, funct3, opcode) = ifields_S_type instr rv = mstate_rv_read mstate xlen = mstate_xlen_read mstate is_SB = (funct3 == funct3_SB) is_SH = (funct3 == funct3_SH) is_SW = (funct3 == funct3_SW) is_SD = ((funct3 == funct3_SD) && (rv == RV64)) is_legal = ((opcode == opcode_STORE) && (is_SB || is_SH || is_SW || is_SD)) Semantics s_imm12 = sign_extend 12 xlen imm12 eaddr1 = alu_add xlen rs1_val s_imm12 eaddr2 = if (rv == RV64) then eaddr1 else (eaddr1 .&. 0xffffFFFF) is_instr = False is_read = False (result1, mstate1) = if (fn_vm_is_active mstate is_instr) then vm_translate mstate is_instr is_read eaddr2 else (Mem_Result_Ok eaddr2, mstate) (result2, mstate2) = case result1 of Mem_Result_Err exc_code -> (result1, mstate1) Mem_Result_Ok eaddr2_pa -> mstate_mem_write mstate1 funct3 eaddr2_pa rs2_val mstate3 = case result2 of Mem_Result_Err exc_code -> finish_trap mstate2 exc_code eaddr2 Mem_Result_Ok _ -> finish_pc_incr mstate2 is_C in (is_legal, mstate3) OP_IMM : ADDI , SLTI , SLTIU , XORI , ORI , ANDI , SLLI , SRLI , SRAI spec_OP_IMM :: Machine_State -> Instr -> Bool -> (Bool, Machine_State) spec_OP_IMM mstate instr is_C = let (imm12, rs1, funct3, rd, opcode) = ifields_I_type instr (msbs7, shamt5) = ifields_I_type_imm12_32 imm12 (msbs6, shamt6) = ifields_I_type_imm12_64 imm12 rv = mstate_rv_read mstate xlen = mstate_xlen_read mstate is_ADDI = (funct3 == funct3_ADDI) is_SLTI = (funct3 == funct3_SLTI) is_SLTIU = (funct3 == funct3_SLTIU) is_XORI = (funct3 == funct3_XORI) is_ORI = (funct3 == funct3_ORI) is_ANDI = (funct3 == funct3_ANDI) is_SLLI = ((funct3 == funct3_SLLI) && (( (rv == RV32) && (msbs7 == msbs7_SLLI)) || ((rv == RV64) && (msbs6 == msbs6_SLLI)))) is_SRLI = ((funct3 == funct3_SRLI) && (( (rv == RV32) && (msbs7 == msbs7_SRLI)) || ((rv == RV64) && (msbs6 == msbs6_SRLI)))) is_SRAI = ((funct3 == funct3_SRAI) && (( (rv == RV32) && (msbs7 == msbs7_SRAI)) || ((rv == RV64) && (msbs6 == msbs6_SRAI)))) is_legal = ((opcode == opcode_OP_IMM) && (is_ADDI || is_SLTI || is_SLTIU || is_XORI || is_ORI || is_ANDI || is_SLLI || is_SRLI || is_SRAI )) Semantics rs1_val = mstate_gpr_read mstate rs1 s_imm12 = sign_extend 12 xlen imm12 rd_val | is_ADDI = alu_add xlen rs1_val s_imm12 | is_SLTI = alu_slt xlen rs1_val s_imm12 | is_SLTIU = alu_sltu xlen rs1_val s_imm12 | is_XORI = alu_xor xlen rs1_val s_imm12 | is_ORI = alu_or xlen rs1_val s_imm12 | is_ANDI = alu_and xlen rs1_val s_imm12 | is_SLLI = alu_sll xlen rs1_val imm12 | is_SRLI = alu_srl xlen rs1_val imm12 | is_SRAI = alu_sra xlen rs1_val imm12 mstate1 = finish_rd_and_pc_incr mstate rd rd_val is_C in (is_legal, mstate1) OP : ADD , SUB , SLT , SLTU , XOR , OR , AND , SLL , SRL , SRA spec_OP :: Machine_State -> Instr -> Bool -> (Bool, Machine_State) spec_OP mstate instr is_C = let (funct7, rs2, rs1, funct3, rd, opcode) = ifields_R_type instr is_ADD = ((funct3 == funct3_ADD) && (funct7 == funct7_ADD)) is_SUB = ((funct3 == funct3_SUB) && (funct7 == funct7_SUB)) is_SLT = ((funct3 == funct3_SLT) && (funct7 == funct7_SLT)) is_SLTU = ((funct3 == funct3_SLTU) && (funct7 == funct7_SLTU)) is_XOR = ((funct3 == funct3_XOR) && (funct7 == funct7_XOR)) is_OR = ((funct3 == funct3_OR) && (funct7 == funct7_OR)) is_AND = ((funct3 == funct3_AND) && (funct7 == funct7_AND)) is_SLL = ((funct3 == funct3_SLL) && (funct7 == funct7_SLL)) is_SRL = ((funct3 == funct3_SRL) && (funct7 == funct7_SRL)) is_legal = ((opcode == opcode_OP) && (is_ADD || is_SUB || is_SLTU || is_XOR || is_OR || is_AND || is_SLL || is_SRL || is_SRA )) Semantics rs1_val = mstate_gpr_read mstate rs1 rs2_val = mstate_gpr_read mstate rs2 rd_val | is_ADD = alu_add xlen rs1_val rs2_val | is_SUB = alu_sub xlen rs1_val rs2_val | is_SLT = alu_slt xlen rs1_val rs2_val | is_SLTU = alu_sltu xlen rs1_val rs2_val | is_XOR = alu_xor xlen rs1_val rs2_val | is_OR = alu_or xlen rs1_val rs2_val | is_AND = alu_and xlen rs1_val rs2_val | is_SLL = alu_sll xlen rs1_val rs2_val | is_SRL = alu_srl xlen rs1_val rs2_val | is_SRA = alu_sra xlen rs1_val rs2_val mstate1 = finish_rd_and_pc_incr mstate rd rd_val is_C in (is_legal, mstate1) MISC_MEM : FENCE , FENCE.I spec_MISC_MEM :: Machine_State -> Instr -> Bool -> (Bool, Machine_State) spec_MISC_MEM mstate instr is_C = let (imm12, rs1, funct3, rd, opcode) = ifields_I_type instr (msbs4, pred, succ) = ifields_I_type_imm12_FENCE imm12 is_FENCE = ((funct3 == funct3_FENCE) && (rd == 0) && (rs1 == 0) && (msbs4 == 0)) is_FENCE_I = ((funct3 == funct3_FENCE_I) && (rd == 0) && (rs1 == 0) && (imm12 == 0)) is_legal = ((opcode == opcode_MISC_MEM) && (is_FENCE || is_FENCE_I)) Semantics mstate1 | is_FENCE = mstate_mem_fence mstate | is_FENCE_I = mstate_mem_fence_i mstate mstate2 = finish_pc_incr mstate1 is_C in (is_legal, mstate2) other : CSRRW , CSRRS , CSRRC , CSRRWI , CSRRSI , CSRRCI spec_SYSTEM_ECALL :: Machine_State -> Instr -> Bool -> (Bool, Machine_State) spec_SYSTEM_ECALL mstate instr is_C = let (funct12, rs1, funct3, rd, opcode) = ifields_I_type instr is_legal = ((opcode == opcode_SYSTEM) && (funct3 == funct3_PRIV) && (funct12 == funct12_ECALL) && (rs1 == 0) && (rd == 0)) Semantics priv = mstate_priv_read mstate exc_code | priv == m_Priv_Level = exc_code_ECall_from_M | priv == s_Priv_Level = exc_code_ECall_from_S | priv == u_Priv_Level = exc_code_ECall_from_U | True = error ("Illegal priv " ++ show (priv)) tval = 0 mstate1 = finish_trap mstate exc_code tval in (is_legal, mstate1) SYSTEM.PRIV.EBREAK spec_SYSTEM_EBREAK :: Machine_State -> Instr -> Bool -> (Bool, Machine_State) spec_SYSTEM_EBREAK mstate instr is_C = let (funct12, rs1, funct3, rd, opcode) = ifields_I_type instr is_legal = ((opcode == opcode_SYSTEM) && (funct3 == funct3_PRIV) && (funct12 == funct12_EBREAK) && (rs1 == 0) && (rd == 0)) Semantics exc_code = exc_code_breakpoint tval = mstate_pc_read mstate mstate1 = finish_trap mstate exc_code tval in (is_legal, mstate1) SYSTEM.not PRIV : CSRRW , CSRRS , CSRRC , CSRRWI , CSRRSI , CSRRCI spec_SYSTEM_CSRRW :: Machine_State -> Instr -> Bool -> (Bool, Machine_State) spec_SYSTEM_CSRRW mstate instr is_C = let (csr_addr, rs1, funct3, rd, opcode) = ifields_I_type instr zimm = rs1 is_CSRRW = (funct3 == funct3_CSRRW) is_CSRRWI = (funct3 == funct3_CSRRWI) is_legal = ((opcode == opcode_SYSTEM) && (is_CSRRW || is_CSRRWI)) Semantics priv = mstate_priv_read mstate permission = mstate_csr_read_permission mstate priv csr_addr legal2 = (permission == CSR_Permission_RW) old_csr_val = if (rd /= 0) then if (csr_addr == csr_addr_time) then let CSR TIME is a read - only shadow of MTIME , mtime = mstate_mem_read_mtime mstate in mtime else mstate_csr_read mstate csr_addr else rs1_val = mstate_gpr_read mstate rs1 new_csr_val | is_CSRRW = rs1_val | is_CSRRWI = rs1 rd_val = old_csr_val mstate1 = if legal2 then FCSR consists of two sub - CSRs , there is a special function let mstate_a = mstate_csr_write mstate csr_addr new_csr_val in finish_rd_and_pc_incr mstate_a rd rd_val is_C else let tval = instr in finish_trap mstate exc_code_illegal_instruction tval in (is_legal, mstate1) spec_SYSTEM_CSRR_S_C :: Machine_State -> Instr -> Bool -> (Bool, Machine_State) spec_SYSTEM_CSRR_S_C mstate instr is_C = let (csr_addr, rs1, funct3, rd, opcode) = ifields_I_type instr zimm = rs1 is_CSRRS = (funct3 == funct3_CSRRS) is_CSRRC = (funct3 == funct3_CSRRC) is_CSRRSI = (funct3 == funct3_CSRRSI) is_CSRRCI = (funct3 == funct3_CSRRCI) is_legal = ((opcode == opcode_SYSTEM) && (is_CSRRS || is_CSRRC || is_CSRRSI || is_CSRRCI)) Semantics priv = mstate_priv_read mstate permission = mstate_csr_read_permission mstate priv csr_addr legal2 | (permission == CSR_Permission_None) = False | (permission == CSR_Permission_RO) = (rs1 == 0) | (permission == CSR_Permission_RW) = True old_csr_val = mstate_csr_read mstate csr_addr rs1_val = mstate_gpr_read mstate rs1 new_csr_val | is_CSRRS = old_csr_val .|. rs1_val | is_CSRRC = old_csr_val .&. (complement rs1_val) | is_CSRRSI = old_csr_val .|. rs1 | is_CSRRCI = old_csr_val .&. (complement rs1) rd_val = old_csr_val mstate1 = if legal2 then let mstate_a | (rs1 /= 0) = mstate_csr_write mstate csr_addr new_csr_val | True = mstate in finish_rd_and_pc_incr mstate_a rd rd_val is_C else let tval = instr in finish_trap mstate exc_code_illegal_instruction tval in (is_legal, mstate1) OP - IMM-32 : ADDIW , SLLIW , SRLIW , SRAIW spec_OP_IMM_32 :: Machine_State -> Instr -> Bool -> (Bool, Machine_State) spec_OP_IMM_32 mstate instr is_C = let (imm12, rs1, funct3, rd, opcode) = ifields_I_type instr (funct7, shamt_5) = ifields_I_type_imm12_32 imm12 rv = mstate_rv_read mstate xlen = mstate_xlen_read mstate is_ADDIW = ( funct3 == funct3_ADDIW) is_SLLIW = ((funct3 == funct3_SLLIW) && (funct7 == funct7_SLLIW)) is_SRLIW = ((funct3 == funct3_SRLIW) && (funct7 == funct7_SRLIW)) is_SRAIW = ((funct3 == funct3_SRAIW) && (funct7 == funct7_SRAIW)) is_legal = ((rv == RV64) && (opcode == opcode_OP_IMM_32) && (is_ADDIW || is_SLLIW || is_SRLIW || is_SRAIW )) Semantics rs1_val = mstate_gpr_read mstate rs1 rd_val | is_ADDIW = alu_addw rs1_val (sign_extend 12 xlen imm12) | is_SLLIW = alu_sllw rs1_val shamt_5 | is_SRLIW = alu_srlw rs1_val shamt_5 | is_SRAIW = alu_sraw rs1_val shamt_5 mstate1 = finish_rd_and_pc_incr mstate rd rd_val is_C in (is_legal, mstate1) OP-32 : for : ADDW , SUBW , SLLW , , SRAW spec_OP_32 :: Machine_State -> Instr -> Bool -> (Bool, Machine_State) spec_OP_32 mstate instr is_C = let (funct7, rs2, rs1, funct3, rd, opcode) = ifields_R_type instr rv = mstate_rv_read mstate is_ADDW = ((funct3 == funct3_ADDW) && (funct7 == funct7_ADDW)) is_SUBW = ((funct3 == funct3_SUBW) && (funct7 == funct7_SUBW)) is_SLLW = ((funct3 == funct3_SLLW) && (funct7 == funct7_SLLW)) is_SRLW = ((funct3 == funct3_SRLW) && (funct7 == funct7_SRLW)) is_SRAW = ((funct3 == funct3_SRAW) && (funct7 == funct7_SRAW)) is_legal = ((rv == RV64) && (opcode == opcode_OP_32) && (is_ADDW || is_SUBW || is_SLLW || is_SRLW || is_SRAW)) Semantics rs1_val = mstate_gpr_read mstate rs1 rs2_val = mstate_gpr_read mstate rs2 rd_val | is_ADDW = alu_addw rs1_val rs2_val | is_SUBW = alu_subw rs1_val rs2_val | is_SLLW = alu_sllw rs1_val rs2_val | is_SRLW = alu_srlw rs1_val rs2_val | is_SRAW = alu_sraw rs1_val rs2_val mstate1 = finish_rd_and_pc_incr mstate rd rd_val is_C in (is_legal, mstate1)
89593223e0e442f899129c196e3991b081b747da24f41bcc8191bce869be9fc2
hbr/albatross
prover.ml
Copyright ( C ) < helmut dot brandl at gmx dot net > This file is distributed under the terms of the GNU General Public License version 2 ( GPLv2 ) as published by the Free Software Foundation . This file is distributed under the terms of the GNU General Public License version 2 (GPLv2) as published by the Free Software Foundation. *) open Container open Support open Term open Proof open Printf module PC = Proof_context | pointer to subgoal | | + ------------------------------------------+ | s1 s2 ... | | ^ subgoals | alt1 | alt2 ... | | backward reasoning |------------------------------------------| | all ( ... ) p1 = = > p2 = = > ... = = > tgt | ^ | | | enter | goal | |------------------------------------------| | par1 | par2 | ... | + ------------------------------------------+ | | backpointer to parent | with goal # , alternative and subgoal within alternative - An alternative fails if one of its subgoals fails - A ( sub)goal becomes obsolete all alternatives which need it are failed or obsolete . - All alternatives to prove an obsolete goal become obsolete . | pointer to subgoal | | +------------------------------------------+ | s1 s2 ... | | ^ subgoals | alt1 | alt2 ... | | backward reasoning |------------------------------------------| | all(...) p1 ==> p2 ==> ... ==> tgt | ^ | | | enter | goal | |------------------------------------------| | par1 | par2 | ... | +------------------------------------------+ | | backpointer to parent | with goal #, alternative and subgoal within alternative - An alternative fails if one of its subgoals fails - A (sub)goal becomes obsolete all alternatives which need it are failed or obsolete. - All alternatives to prove an obsolete goal become obsolete. *) module Statistics: sig type t val make: unit -> t val add_proof: t -> unit val add_goal: t -> unit val add_alternatives: int -> t -> unit val add_falses: int -> t -> unit val push: t -> unit val pop: t -> unit val print_and_pop: Format.formatter -> t -> unit val print: Format.formatter -> t -> unit end = struct type entry = { mutable nproofs: int; mutable ngoals: int; mutable nalternatives: int; mutable nfalses: int; } type t = { mutable stack: entry list; entry: entry } let make_entry (): entry = { nproofs = 0; ngoals = 0; nalternatives = 0; nfalses = 0; } let copy_entry (e:entry): entry = { nproofs = e.nproofs; ngoals = e.ngoals; nalternatives = e.nalternatives; nfalses = e.nfalses} let make (): t = {stack = []; entry = make_entry () } let add_proof (s:t): unit = s.entry.nproofs <- s.entry.nproofs + 1 let add_goal (s:t): unit = s.entry.ngoals <- s.entry.ngoals + 1 let add_alternatives (n:int) (s:t): unit = s.entry.nalternatives <- s.entry.nalternatives + n - 1 let add_falses (n:int) (s:t): unit = s.entry.nfalses <- s.entry.nfalses + n - 1 let push (s:t): unit = s.stack <- copy_entry s.entry :: s.stack let pop (s:t): unit = match s.stack with | [] -> assert false (* Illegal call *) | hd :: tl -> s.stack <- tl let print_delta (f:Format.formatter) (e:entry ) (s:t): unit = let nproofs = s.entry.nproofs - e.nproofs and ngoals = s.entry.ngoals - e.ngoals and nalternatives = s.entry.nalternatives - e.nalternatives and nfalses = s.entry.nfalses - e.nfalses in let open Format in fprintf f "@[<v>Statistics@,"; if nproofs > 1 then fprintf f "nproofs %d@," nproofs; fprintf f "%s%s(false)@,%6d%16d(%5d)" "ngoals" " nalternatives" ngoals (nalternatives + nfalses) nfalses; if nproofs > 1 then fprintf f "@,%6.1f%16.1f(%5.1f)" (float_of_int ngoals /. float_of_int nproofs) (float_of_int (nalternatives + nfalses) /. float_of_int nproofs) (float_of_int nfalses /. float_of_int nproofs); fprintf f "@,@]" let print_and_pop (f:Format.formatter) (s:t): unit = match s.stack with | [] -> assert false (* Illegal call *) | hd :: tl -> s.stack <- tl; print_delta f hd s let print (f:Format.formatter) (s:t): unit = print_delta f (make_entry ()) s end let statistics = Statistics.make () let push_statistics (): unit = Statistics.push statistics let print_statistics_and_pop (str:string): unit = let open Format in printf "@[%s" str; Statistics.print_and_pop std_formatter statistics; printf "@]@." type context = {pc:PC.t; mutable map: int TermMap.t} type alternative = { subgoal , pos in proved assertions mutable npremises: int; (* number of premises still to prove *) bwd_idx: int; (* index of the backward rule *) mutable failed: bool; mutable obsolete: bool; } type goal = { goal: term; ctxt: context; mutable black: IntSet.t; (* Blacklist of rules which are no longer to be considered *) mutable target: term; (* The target is the same as the goal, if the goal is not a general implication chain, otherwise its the target of the chain. *) mutable tgt_ctxt: context; mutable visited: bool; mutable ancestors: IntSet.t; parent , alternative , subgoal Backpointer to parent , alternative in the parent and subgoal within the alternative . within the alternative. *) mutable alternatives: alternative array; mutable nfailed: int; (* number of failed alternatives *) mutable pos: int option; (* position in proof table *) mutable obsolete: bool; mutable failed: bool } type t = { goals: goal Seq.t; mutable reactivated: int list; verbosity: int; trace: bool; } let goal_report_threshold = 500 let goal_limit_ref = ref 2000 let goal_limit () = !goal_limit_ref let count (gs:t): int = Seq.count gs.goals let item (i:int) (gs:t): goal = assert (i < count gs); Seq.elem i gs.goals let goal (g:term) (i:int) (black:IntSet.t) (parents:(int*int*int) list) (ctxt:context) (gs:t) : goal = (*assert (PC.is_well_typed g pc);*) {goal = g; ctxt; black; target = g; tgt_ctxt = ctxt; visited = false; ancestors = IntSet.add i (List.fold_left (fun set (ipar,_,_) -> IntSet.union set (item ipar gs).ancestors ) IntSet.empty parents); parents; alternatives = [||]; nfailed = 0; pos = None; obsolete = false; failed = false } let root_goal (g:term) (pc: PC.t) (gs:t): goal = goal g 0 IntSet.empty [] {pc; map = TermMap.empty} gs exception Root_succeeded let has_succeeded (i:int) (gs:t): bool = (item i gs).pos <> None let is_visitable (i:int) (gs:t): bool = let g = item i gs in not (g.visited || g.obsolete) let init (g:term) (pc:PC.t): t = let gs = {goals = Seq.empty (); reactivated = []; verbosity = PC.verbosity pc; trace = PC.is_tracing pc} in let goal = root_goal g pc gs in Seq.push goal gs.goals; gs let rec reactivate_goal (i:int) (gs:t): unit = (* Reactivate the goal [i] if it has become obsolete and has not yet failed. *) let g = item i gs in if g.obsolete && not g.failed && g.pos = None then begin assert (g.pos = None); g.obsolete <- false; gs.reactivated <- i :: gs.reactivated; Array.iter (fun alt -> reactivate_alternative alt gs ) g.alternatives end and reactivate_alternative (alt:alternative) (gs:t): unit = (* Reactivate the alternative [alt] if it has become obsolete and has not yet failed. *) if alt.obsolete && not alt.failed then begin alt.obsolete <- false; Array.iter (fun (j,jpos) -> if jpos = None then reactivate_goal j gs ) alt.premises end let rec set_goal_obsolete (i:int) (gs:t): unit = (* A goal becomes obsolete if alternatives which use it are either failed or obsolte. *) let g = item i gs in if List.for_all (fun (ipar,ialt,isub) -> assert (0 <= ialt); assert (ialt < Array.length (item ipar gs).alternatives); let alt = (item ipar gs).alternatives.(ialt) in alt.failed || alt.obsolete ) g.parents then begin g.obsolete <- true; for ialt = g.nfailed to Array.length g.alternatives - 1 do set_alternative_obsolete ialt i gs done end and set_alternative_obsolete (ialt:int) (i:int) (gs:t): unit = (* The alternative [ialt] of the goal [i] becomes obsolete because the goal has become obsolete. *) let g = item i gs in let alt = g.alternatives.(ialt) in alt.obsolete <- true; Array.iter (fun (p,pos) -> match pos with | None -> set_goal_obsolete p gs | _ -> () ) alt.premises and set_alternative_failed (ialt:int) (i:int) (gs:t): unit = The alternative [ ialt ] of the goal [ i ] fails because one of its subgoals failed . The other subgoals of the alternative become obsolete . failed. The other subgoals of the alternative become obsolete. *) let g = item i gs in let alt = g.alternatives.(ialt) in if not alt.failed then begin g.nfailed <- 1 + g.nfailed; alt.failed <- true; Array.iter (fun (p,pos) -> match pos with | None -> set_goal_obsolete p gs | _ -> () ) alt.premises end; if g.nfailed = Array.length g.alternatives then set_goal_failed i gs and set_goal_failed (i:int) (gs:t): unit = (* The goal [i] has failed. If the goal is the root goal then the whole proof is failed. If the goal is not the root goal then it belongs to an alternative of its parent. The alternative is failed. All other subgoals of the parent become obsolete. If the alternative is the last alternative then the parent fails as well. *) let g = item i gs in if not g.failed then begin if gs.trace then begin let prefix = PC.trace_prefix g.ctxt.pc in printf "%sfailed goal %d: %s\n" prefix i (PC.string_of_term g.goal g.ctxt.pc); end; g.failed <- true; if g.parents = [] then begin assert (i = 0); raise (Proof_failed "") end; List.iter (fun (ipar,ialt,isub) -> set_alternative_failed ialt ipar gs ) g.parents end let pc_discharged (pos:int) (pc:PC.t): term * proof_term = try PC.discharged pos pc with Not_found -> assert false (* cannot happen in generated proof *) let discharged (pos:int) (pc:PC.t): int * PC.t = let t,pt = pc_discharged pos pc and cnt0 = PC.count_previous pc and pc = PC.pop pc in assert (cnt0 <= PC.count pc); let delta = PC.count pc - cnt0 in let pos = PC.add_proved_with_delta t pt delta pc in PC.clear_work pc; pos, pc let discharge_target (pos:int) (g:goal): unit = (* The target of the goal [g] has succeeded and it is at [pos] in the target context. The target has to be discharged with all variables and assumptions and the discharged term and proof term has to be inserted into the goal context *) let depth = PC.depth g.ctxt.pc in let rec discharge pos pc = if PC.depth pc = depth then pos else let pos, pc = discharged pos pc in discharge pos pc in let pos = discharge pos g.tgt_ctxt.pc in g.pos <- Some pos let succeed_alternative (ialt:int) (g:goal): int = (* The alternative [ialt] of the goal [g] has succeeded because all subgoals of the alternative have succeeded. Apply the modus ponens law and calculate the position of the goal in the assertion table. *) let alt = g.alternatives.(ialt) in let n = Array.length alt.premises in let rec premise (i:int) (a_idx:int): int = if i = n then a_idx else begin let _,pos = alt.premises.(i) in match pos with | None -> assert false | Some pos -> let a_idx = PC.add_mp pos a_idx false g.tgt_ctxt.pc in premise (i+1) a_idx end in premise 0 alt.bwd_idx let rec set_goal_succeeded (i:int) (gs:t): unit = (* The goal [i] has succeeded. If the goal is the root goal then the proof is done. If the goal is not the root goal then it belongs to an alternative of its parent. *) let g = item i gs in if gs.trace then begin let prefix = PC.trace_prefix g.ctxt.pc and obs = if g.obsolete then " of obsolete" else "" in printf "%ssuccess%s goal %d: %s\n" prefix obs i (PC.string_long_of_term g.goal g.ctxt.pc); end; let g_pos = match g.pos with | Some pos -> pos | _ -> assert false (* The goal has succeeded *) in assert (g_pos < PC.count g.ctxt.pc); if g.parents = [] then begin assert (i = 0); raise Root_succeeded end; List.iter (fun (ipar,ialt,isub) -> let par = item ipar gs in assert (ialt < Array.length par.alternatives); let alt = par.alternatives.(ialt) in assert (isub < Array.length alt.premises); let p,pos = alt.premises.(isub) in assert (p = i); if pos = None then begin assert (pos = None); assert (0 < alt.npremises); alt.premises.(isub) <- p, Some g_pos; alt.npremises <- alt.npremises - 1; if alt.npremises = 0 then begin (* The alternative has succeeded. *) let pos = succeed_alternative ialt par in discharge_target pos par; set_goal_succeeded ipar gs; (* All other alternatives become obsolete. *) for jalt = 0 to Array.length par.alternatives - 1 do if jalt <> ialt then set_alternative_obsolete jalt ipar gs done end end ) g.parents let enter (i:int) (gs:t): unit = (* Check if the goal is a generalized implication chain i.e. universally quantified and/or and implication chain. If yes, create a new target and a target context, push the assumptions and close the context. Iterate the procedure if the target is universally quantified and/or an implication chain. *) let g = item i gs in let rec do_enter gl ctxt = let tps,fgs,ps_rev,tgt = PC.split_general_implication_chain gl ctxt.pc in let n = Formals.count tps in if n = 0 && ps_rev = [] then () else begin let pc = PC.push_typed0 tps fgs ctxt.pc in let tgt_ctxt = {pc; map = TermMap.empty} in List.iter (fun p -> ignore (PC.add_assumption p true pc); ) (List.rev ps_rev); if ps_rev <> [] then PC.close_assumptions pc; g.target <- tgt; g.tgt_ctxt <- tgt_ctxt; do_enter tgt tgt_ctxt end in do_enter g.goal g.ctxt let prove_trivially (g:goal): unit = let idx = PC.find_goal g.target g.tgt_ctxt.pc in discharge_target idx g let calc_blacklist (cons:bool) (idx:int) (used:IntSet.t) (pc:PC.t): IntSet.t = let used = if cons then used else List.fold_left (fun set i -> IntSet.add i set ) used (PC.previous_schematics idx pc) in IntSet.add idx used let trace_target_subgoals (i:int) (gs:t): unit = let g = item i gs in let pc = g.tgt_ctxt.pc in let prefix = PC.trace_prefix pc in printf "%starget %d: %s\n" prefix i (PC.string_of_term g.target pc); for ialt = 0 to Array.length g.alternatives - 1 do let alt = g.alternatives.(ialt) in Array.iter (fun (i,_) -> let sg = item i gs in printf "%s %2d subgoal %d: %s\n" prefix ialt i (PC.string_of_term sg.goal sg.ctxt.pc)) alt.premises done exception Cyclic let generate_subgoal (p:term) (cons:bool) (j:int) (j_idx:int) (jsub:int) (i:int) (gs:t): int = Generate a subgoal [ p ] where [ cons ] indicates if the subgoal is conservative for the alternative [ j ] ( at position [ j_idx ] in the assertion table ) of the goal [ i ] . conservative for the alternative [j] (at position [j_idx] in the assertion table) of the goal [i]. *) let cnt = count gs in let g = item i gs in (* Parent goal *) let generate (): int = let black = calc_blacklist cons j_idx g.black g.tgt_ctxt.pc in let sub = goal p cnt black [i,j,jsub] g.tgt_ctxt gs in Statistics.add_goal statistics; Seq.push sub gs.goals; cnt in try let isub = TermMap.find p g.tgt_ctxt.map in if gs.trace then printf "%sduplicate subgoal %d: %s\n" (PC.trace_prefix g.tgt_ctxt.pc) isub (PC.string_of_term p g.tgt_ctxt.pc); if IntSet.mem isub g.ancestors then begin if gs.trace then printf "%scyclic subgoal %d: %s\n" (PC.trace_prefix g.ctxt.pc) isub (PC.string_of_term p g.ctxt.pc); raise Cyclic end; let sub = item in let black = calc_blacklist cons j_idx g.black g.tgt_ctxt.pc in sub.black < - IntSet.union black sub.black ; i , j , ) : : ; if ( item isub gs).obsolete then reactivate_goal ; let black = calc_blacklist cons j_idx g.black g.tgt_ctxt.pc in sub.black <- IntSet.union black sub.black; sub.parents <- (i,j,jsub) :: sub.parents; if (item isub gs).obsolete then reactivate_goal isub gs;*) isub with Not_found -> g.tgt_ctxt.map <- TermMap.add p cnt g.tgt_ctxt.map; generate () let generate_subgoals (i:int) (gs:t): unit = (* Generate the subgoals of all alternatives of the goal [i]. *) let g = item i gs in let alts = PC.find_backward_goal g.target g.black g.tgt_ctxt.pc in let _, alts, patches = List.fold_left (* all alternatives *) (fun (j,alts,patches) bwd_idx -> let cnt = count gs in try let ps = PC.premises bwd_idx g.tgt_ctxt.pc in let ps,_,npremises,patches = List.fold_left (* all premises i.e. subgoals *) (fun (ps,jsub,npremises,patches) (p,cons) -> let cnt = count gs in let k = generate_subgoal p cons j bwd_idx jsub i gs in let k_pos = (item k gs).pos in (k, k_pos) :: ps, jsub+1, npremises + (if k_pos = None then 1 else 0), if k < cnt then (k,cons,i,j,bwd_idx,jsub) :: patches else patches ) ([],0,0,patches) ps in let ps = List.rev ps in let ps = Array.of_list ps in (j+1), {premises = ps; bwd_idx; npremises; failed = false; obsolete = false} :: alts, patches with Cyclic -> interval_iter (fun k -> g.tgt_ctxt.map <- TermMap.remove (item k gs).goal g.tgt_ctxt.map ) cnt (count gs); Seq.keep cnt gs.goals; j, alts, patches ) (0,[],[]) alts in g.alternatives <- Array.of_list (List.rev alts); let nalts = Array.length g.alternatives in if Term.equivalent g.target (PC.false_constant g.tgt_ctxt.pc) then Statistics.add_falses nalts statistics else Statistics.add_alternatives nalts statistics; List.iter (fun (k,cons,ipar,ialt,bwd_idx,isub) -> let sub = item k gs and par = item ipar gs in let black = calc_blacklist cons bwd_idx par.black par.tgt_ctxt.pc in sub.black <- IntSet.union black sub.black; sub.parents <- (ipar,ialt,isub) :: sub.parents; if sub.obsolete then reactivate_goal k gs; if sub.failed then set_alternative_failed ialt i gs ) patches; if Array.length g.alternatives = 0 then set_goal_failed i gs; if gs.trace then trace_target_subgoals i gs; try let ialt = Search.array_find_min (fun alt -> alt.npremises = 0) g.alternatives in let pos = succeed_alternative ialt g in discharge_target pos g; set_goal_succeeded i gs; with Not_found -> () let ancestors (i:int) (gs:t): int list = IntSet.elements (item i gs).ancestors let trace_ancestors (i:int) (gs:t): unit = let g = item i gs in let ancs = ancestors i gs in let str = String.concat "," (List.map string_of_int ancs) in let prefix = PC.trace_prefix g.ctxt.pc in printf "%sancestors [%s]\n" prefix str let trace_visit (i:int) (gs:t): unit = let g = item i gs in let prefix = PC.trace_prefix g.ctxt.pc in printf "\n%svisit goal %d: %s\n" prefix i (PC.string_long_of_term g.goal g.ctxt.pc); printf " %s\n" (Term.to_string g.goal); List.iter (fun (ipar,ialt,isub) -> let par = item ipar gs in trace_ancestors i gs; printf "%s parent %d %s\n" prefix ipar (PC.string_of_term par.goal par.ctxt.pc); if par.goal <> par.target then printf "%s parent target %s\n" prefix (PC.string_of_term par.target par.tgt_ctxt.pc)(*; let alt = par.alternatives.(ialt) in printf "%salternative %s\n" prefix (PC.string_of_term_i alt.a_idx par.tgt_ctxt)*) ) g.parents let visit (i:int) (gs:t): unit = assert (i < count gs); assert (is_visitable i gs); assert (not (has_succeeded i gs)); let g = item i gs in if gs.trace then trace_visit i gs; g.visited <- true; try prove_trivially g; set_goal_succeeded i gs with Not_found -> enter i gs; try prove_trivially g; set_goal_succeeded i gs with Not_found -> generate_subgoals i gs let trace_viable_subgoals (gs:t): unit = let max_level = 10 in let prefix level = String.make (2*level) ' ' in let rec trace (i:int) (level:int): unit = let pref = prefix level in let g = item i gs in printf "%sgoal %d %s\n" pref i (PC.string_of_term g.goal g.ctxt.pc); printf "%s failed %b, obsolete %b, proved %b\n" pref g.failed g.obsolete (g.pos <> None); if level = 10 then printf "level %d reached\n" max_level; if not (g.failed || g.obsolete || g.pos <> None) && level < max_level then Array.iteri (fun i (alt:alternative) -> if not (alt.obsolete || alt.failed) then begin assert (alt.bwd_idx >= 0); printf "%salternative %d %s\n" pref i (PC.string_of_term_i alt.bwd_idx g.tgt_ctxt.pc); Array.iter (fun (j,pos) -> trace j (level+1)) alt.premises end ) g.alternatives in trace 0 0 let proof_term (g:term) (pc:PC.t): term * proof_term = let pc = PC.push_empty pc in PC.close_assumptions pc; Statistics.push statistics; Statistics.add_proof statistics; let gs = init g pc in if gs.trace then begin printf "\n%strying to prove: %s\n" (PC.trace_prefix pc) (PC.string_long_of_term g pc); if PC.verbosity pc > 3 then printf "%s %s\n" (PC.trace_prefix pc) (Term.to_string g); printf "\n" end; if not (PC.is_global pc) then PC.close pc; let rec round (i:int) (start:int): unit = if PC.is_interface_check pc && 1 < i then raise (Proof_failed ""); if PC.verbosity pc >= 1 && start >= goal_report_threshold then begin printf "next round entered with %d goals\n" start; let g0 = Seq.elem 0 gs.goals in printf " hard to prove %s\n" (PC.string_of_term g0.goal g0.ctxt.pc); flush_all () end; if goal_limit () <= start then raise (Proof_failed (", goal limit " ^ (string_of_int (goal_limit())) ^ " exceeded")); let cnt = count gs in if PC.is_tracing pc then printf "%s-- round %d with %d goals starting from %d --\n" (PC.trace_prefix pc) i (cnt - start) start; for j = start to cnt - 1 do if is_visitable j gs then visit j gs done; while gs.reactivated <> [] do let lst = List.rev gs.reactivated in gs.reactivated <- []; List.iter (fun j -> if is_visitable j gs then visit j gs) lst; done; assert (gs.reactivated = []); if cnt = count gs then begin (*if PC.is_tracing pc then trace_viable_subgoals gs;*) raise (Proof_failed (" (subgoals exhausted)")) end; assert (cnt < count gs); if PC.is_tracing pc then printf "\n"; round (i+1) cnt in try round 0 0; assert false (* shall not happen, because either we succeed or we fail, but we cannot fall through *) with | Root_succeeded -> let g = item 0 gs in let g_pos = match g.pos with | Some pos -> pos | _ -> assert false (* Root goal has succeeded *) in assert (g_pos < PC.count g.ctxt.pc); if gs.trace then print_statistics_and_pop (PC.trace_prefix pc) else Statistics.pop statistics; pc_discharged g_pos g.ctxt.pc | Proof_failed msg -> Statistics.pop statistics; raise (Proof_failed msg) let is_provable (g:term) (pc:PC.t): bool = try let _ = proof_term g pc in true with Proof_failed _ -> false let prove (g:term) (pc:PC.t): unit = let _ = proof_term g pc in () let prove_and_insert (g:term) (pc:PC.t): int = let t,pt = proof_term g pc in PC.add_proved_with_delta t pt 0 pc
null
https://raw.githubusercontent.com/hbr/albatross/8f28ef97951f92f30dc69cf94c0bbe20d64fba21/ocaml/alba1/prover.ml
ocaml
Illegal call Illegal call number of premises still to prove index of the backward rule Blacklist of rules which are no longer to be considered The target is the same as the goal, if the goal is not a general implication chain, otherwise its the target of the chain. number of failed alternatives position in proof table assert (PC.is_well_typed g pc); Reactivate the goal [i] if it has become obsolete and has not yet failed. Reactivate the alternative [alt] if it has become obsolete and has not yet failed. A goal becomes obsolete if alternatives which use it are either failed or obsolte. The alternative [ialt] of the goal [i] becomes obsolete because the goal has become obsolete. The goal [i] has failed. If the goal is the root goal then the whole proof is failed. If the goal is not the root goal then it belongs to an alternative of its parent. The alternative is failed. All other subgoals of the parent become obsolete. If the alternative is the last alternative then the parent fails as well. cannot happen in generated proof The target of the goal [g] has succeeded and it is at [pos] in the target context. The target has to be discharged with all variables and assumptions and the discharged term and proof term has to be inserted into the goal context The alternative [ialt] of the goal [g] has succeeded because all subgoals of the alternative have succeeded. Apply the modus ponens law and calculate the position of the goal in the assertion table. The goal [i] has succeeded. If the goal is the root goal then the proof is done. If the goal is not the root goal then it belongs to an alternative of its parent. The goal has succeeded The alternative has succeeded. All other alternatives become obsolete. Check if the goal is a generalized implication chain i.e. universally quantified and/or and implication chain. If yes, create a new target and a target context, push the assumptions and close the context. Iterate the procedure if the target is universally quantified and/or an implication chain. Parent goal Generate the subgoals of all alternatives of the goal [i]. all alternatives all premises i.e. subgoals ; let alt = par.alternatives.(ialt) in printf "%salternative %s\n" prefix (PC.string_of_term_i alt.a_idx par.tgt_ctxt) if PC.is_tracing pc then trace_viable_subgoals gs; shall not happen, because either we succeed or we fail, but we cannot fall through Root goal has succeeded
Copyright ( C ) < helmut dot brandl at gmx dot net > This file is distributed under the terms of the GNU General Public License version 2 ( GPLv2 ) as published by the Free Software Foundation . This file is distributed under the terms of the GNU General Public License version 2 (GPLv2) as published by the Free Software Foundation. *) open Container open Support open Term open Proof open Printf module PC = Proof_context | pointer to subgoal | | + ------------------------------------------+ | s1 s2 ... | | ^ subgoals | alt1 | alt2 ... | | backward reasoning |------------------------------------------| | all ( ... ) p1 = = > p2 = = > ... = = > tgt | ^ | | | enter | goal | |------------------------------------------| | par1 | par2 | ... | + ------------------------------------------+ | | backpointer to parent | with goal # , alternative and subgoal within alternative - An alternative fails if one of its subgoals fails - A ( sub)goal becomes obsolete all alternatives which need it are failed or obsolete . - All alternatives to prove an obsolete goal become obsolete . | pointer to subgoal | | +------------------------------------------+ | s1 s2 ... | | ^ subgoals | alt1 | alt2 ... | | backward reasoning |------------------------------------------| | all(...) p1 ==> p2 ==> ... ==> tgt | ^ | | | enter | goal | |------------------------------------------| | par1 | par2 | ... | +------------------------------------------+ | | backpointer to parent | with goal #, alternative and subgoal within alternative - An alternative fails if one of its subgoals fails - A (sub)goal becomes obsolete all alternatives which need it are failed or obsolete. - All alternatives to prove an obsolete goal become obsolete. *) module Statistics: sig type t val make: unit -> t val add_proof: t -> unit val add_goal: t -> unit val add_alternatives: int -> t -> unit val add_falses: int -> t -> unit val push: t -> unit val pop: t -> unit val print_and_pop: Format.formatter -> t -> unit val print: Format.formatter -> t -> unit end = struct type entry = { mutable nproofs: int; mutable ngoals: int; mutable nalternatives: int; mutable nfalses: int; } type t = { mutable stack: entry list; entry: entry } let make_entry (): entry = { nproofs = 0; ngoals = 0; nalternatives = 0; nfalses = 0; } let copy_entry (e:entry): entry = { nproofs = e.nproofs; ngoals = e.ngoals; nalternatives = e.nalternatives; nfalses = e.nfalses} let make (): t = {stack = []; entry = make_entry () } let add_proof (s:t): unit = s.entry.nproofs <- s.entry.nproofs + 1 let add_goal (s:t): unit = s.entry.ngoals <- s.entry.ngoals + 1 let add_alternatives (n:int) (s:t): unit = s.entry.nalternatives <- s.entry.nalternatives + n - 1 let add_falses (n:int) (s:t): unit = s.entry.nfalses <- s.entry.nfalses + n - 1 let push (s:t): unit = s.stack <- copy_entry s.entry :: s.stack let pop (s:t): unit = match s.stack with | [] -> | hd :: tl -> s.stack <- tl let print_delta (f:Format.formatter) (e:entry ) (s:t): unit = let nproofs = s.entry.nproofs - e.nproofs and ngoals = s.entry.ngoals - e.ngoals and nalternatives = s.entry.nalternatives - e.nalternatives and nfalses = s.entry.nfalses - e.nfalses in let open Format in fprintf f "@[<v>Statistics@,"; if nproofs > 1 then fprintf f "nproofs %d@," nproofs; fprintf f "%s%s(false)@,%6d%16d(%5d)" "ngoals" " nalternatives" ngoals (nalternatives + nfalses) nfalses; if nproofs > 1 then fprintf f "@,%6.1f%16.1f(%5.1f)" (float_of_int ngoals /. float_of_int nproofs) (float_of_int (nalternatives + nfalses) /. float_of_int nproofs) (float_of_int nfalses /. float_of_int nproofs); fprintf f "@,@]" let print_and_pop (f:Format.formatter) (s:t): unit = match s.stack with | [] -> | hd :: tl -> s.stack <- tl; print_delta f hd s let print (f:Format.formatter) (s:t): unit = print_delta f (make_entry ()) s end let statistics = Statistics.make () let push_statistics (): unit = Statistics.push statistics let print_statistics_and_pop (str:string): unit = let open Format in printf "@[%s" str; Statistics.print_and_pop std_formatter statistics; printf "@]@." type context = {pc:PC.t; mutable map: int TermMap.t} type alternative = { subgoal , pos in proved assertions mutable failed: bool; mutable obsolete: bool; } type goal = { goal: term; ctxt: context; mutable target: term; mutable tgt_ctxt: context; mutable visited: bool; mutable ancestors: IntSet.t; parent , alternative , subgoal Backpointer to parent , alternative in the parent and subgoal within the alternative . within the alternative. *) mutable alternatives: alternative array; mutable obsolete: bool; mutable failed: bool } type t = { goals: goal Seq.t; mutable reactivated: int list; verbosity: int; trace: bool; } let goal_report_threshold = 500 let goal_limit_ref = ref 2000 let goal_limit () = !goal_limit_ref let count (gs:t): int = Seq.count gs.goals let item (i:int) (gs:t): goal = assert (i < count gs); Seq.elem i gs.goals let goal (g:term) (i:int) (black:IntSet.t) (parents:(int*int*int) list) (ctxt:context) (gs:t) : goal = {goal = g; ctxt; black; target = g; tgt_ctxt = ctxt; visited = false; ancestors = IntSet.add i (List.fold_left (fun set (ipar,_,_) -> IntSet.union set (item ipar gs).ancestors ) IntSet.empty parents); parents; alternatives = [||]; nfailed = 0; pos = None; obsolete = false; failed = false } let root_goal (g:term) (pc: PC.t) (gs:t): goal = goal g 0 IntSet.empty [] {pc; map = TermMap.empty} gs exception Root_succeeded let has_succeeded (i:int) (gs:t): bool = (item i gs).pos <> None let is_visitable (i:int) (gs:t): bool = let g = item i gs in not (g.visited || g.obsolete) let init (g:term) (pc:PC.t): t = let gs = {goals = Seq.empty (); reactivated = []; verbosity = PC.verbosity pc; trace = PC.is_tracing pc} in let goal = root_goal g pc gs in Seq.push goal gs.goals; gs let rec reactivate_goal (i:int) (gs:t): unit = let g = item i gs in if g.obsolete && not g.failed && g.pos = None then begin assert (g.pos = None); g.obsolete <- false; gs.reactivated <- i :: gs.reactivated; Array.iter (fun alt -> reactivate_alternative alt gs ) g.alternatives end and reactivate_alternative (alt:alternative) (gs:t): unit = if alt.obsolete && not alt.failed then begin alt.obsolete <- false; Array.iter (fun (j,jpos) -> if jpos = None then reactivate_goal j gs ) alt.premises end let rec set_goal_obsolete (i:int) (gs:t): unit = let g = item i gs in if List.for_all (fun (ipar,ialt,isub) -> assert (0 <= ialt); assert (ialt < Array.length (item ipar gs).alternatives); let alt = (item ipar gs).alternatives.(ialt) in alt.failed || alt.obsolete ) g.parents then begin g.obsolete <- true; for ialt = g.nfailed to Array.length g.alternatives - 1 do set_alternative_obsolete ialt i gs done end and set_alternative_obsolete (ialt:int) (i:int) (gs:t): unit = let g = item i gs in let alt = g.alternatives.(ialt) in alt.obsolete <- true; Array.iter (fun (p,pos) -> match pos with | None -> set_goal_obsolete p gs | _ -> () ) alt.premises and set_alternative_failed (ialt:int) (i:int) (gs:t): unit = The alternative [ ialt ] of the goal [ i ] fails because one of its subgoals failed . The other subgoals of the alternative become obsolete . failed. The other subgoals of the alternative become obsolete. *) let g = item i gs in let alt = g.alternatives.(ialt) in if not alt.failed then begin g.nfailed <- 1 + g.nfailed; alt.failed <- true; Array.iter (fun (p,pos) -> match pos with | None -> set_goal_obsolete p gs | _ -> () ) alt.premises end; if g.nfailed = Array.length g.alternatives then set_goal_failed i gs and set_goal_failed (i:int) (gs:t): unit = let g = item i gs in if not g.failed then begin if gs.trace then begin let prefix = PC.trace_prefix g.ctxt.pc in printf "%sfailed goal %d: %s\n" prefix i (PC.string_of_term g.goal g.ctxt.pc); end; g.failed <- true; if g.parents = [] then begin assert (i = 0); raise (Proof_failed "") end; List.iter (fun (ipar,ialt,isub) -> set_alternative_failed ialt ipar gs ) g.parents end let pc_discharged (pos:int) (pc:PC.t): term * proof_term = try PC.discharged pos pc with Not_found -> let discharged (pos:int) (pc:PC.t): int * PC.t = let t,pt = pc_discharged pos pc and cnt0 = PC.count_previous pc and pc = PC.pop pc in assert (cnt0 <= PC.count pc); let delta = PC.count pc - cnt0 in let pos = PC.add_proved_with_delta t pt delta pc in PC.clear_work pc; pos, pc let discharge_target (pos:int) (g:goal): unit = let depth = PC.depth g.ctxt.pc in let rec discharge pos pc = if PC.depth pc = depth then pos else let pos, pc = discharged pos pc in discharge pos pc in let pos = discharge pos g.tgt_ctxt.pc in g.pos <- Some pos let succeed_alternative (ialt:int) (g:goal): int = let alt = g.alternatives.(ialt) in let n = Array.length alt.premises in let rec premise (i:int) (a_idx:int): int = if i = n then a_idx else begin let _,pos = alt.premises.(i) in match pos with | None -> assert false | Some pos -> let a_idx = PC.add_mp pos a_idx false g.tgt_ctxt.pc in premise (i+1) a_idx end in premise 0 alt.bwd_idx let rec set_goal_succeeded (i:int) (gs:t): unit = let g = item i gs in if gs.trace then begin let prefix = PC.trace_prefix g.ctxt.pc and obs = if g.obsolete then " of obsolete" else "" in printf "%ssuccess%s goal %d: %s\n" prefix obs i (PC.string_long_of_term g.goal g.ctxt.pc); end; let g_pos = match g.pos with | Some pos -> pos in assert (g_pos < PC.count g.ctxt.pc); if g.parents = [] then begin assert (i = 0); raise Root_succeeded end; List.iter (fun (ipar,ialt,isub) -> let par = item ipar gs in assert (ialt < Array.length par.alternatives); let alt = par.alternatives.(ialt) in assert (isub < Array.length alt.premises); let p,pos = alt.premises.(isub) in assert (p = i); if pos = None then begin assert (pos = None); assert (0 < alt.npremises); alt.premises.(isub) <- p, Some g_pos; alt.npremises <- alt.npremises - 1; if alt.npremises = 0 then begin let pos = succeed_alternative ialt par in discharge_target pos par; set_goal_succeeded ipar gs; for jalt = 0 to Array.length par.alternatives - 1 do if jalt <> ialt then set_alternative_obsolete jalt ipar gs done end end ) g.parents let enter (i:int) (gs:t): unit = let g = item i gs in let rec do_enter gl ctxt = let tps,fgs,ps_rev,tgt = PC.split_general_implication_chain gl ctxt.pc in let n = Formals.count tps in if n = 0 && ps_rev = [] then () else begin let pc = PC.push_typed0 tps fgs ctxt.pc in let tgt_ctxt = {pc; map = TermMap.empty} in List.iter (fun p -> ignore (PC.add_assumption p true pc); ) (List.rev ps_rev); if ps_rev <> [] then PC.close_assumptions pc; g.target <- tgt; g.tgt_ctxt <- tgt_ctxt; do_enter tgt tgt_ctxt end in do_enter g.goal g.ctxt let prove_trivially (g:goal): unit = let idx = PC.find_goal g.target g.tgt_ctxt.pc in discharge_target idx g let calc_blacklist (cons:bool) (idx:int) (used:IntSet.t) (pc:PC.t): IntSet.t = let used = if cons then used else List.fold_left (fun set i -> IntSet.add i set ) used (PC.previous_schematics idx pc) in IntSet.add idx used let trace_target_subgoals (i:int) (gs:t): unit = let g = item i gs in let pc = g.tgt_ctxt.pc in let prefix = PC.trace_prefix pc in printf "%starget %d: %s\n" prefix i (PC.string_of_term g.target pc); for ialt = 0 to Array.length g.alternatives - 1 do let alt = g.alternatives.(ialt) in Array.iter (fun (i,_) -> let sg = item i gs in printf "%s %2d subgoal %d: %s\n" prefix ialt i (PC.string_of_term sg.goal sg.ctxt.pc)) alt.premises done exception Cyclic let generate_subgoal (p:term) (cons:bool) (j:int) (j_idx:int) (jsub:int) (i:int) (gs:t): int = Generate a subgoal [ p ] where [ cons ] indicates if the subgoal is conservative for the alternative [ j ] ( at position [ j_idx ] in the assertion table ) of the goal [ i ] . conservative for the alternative [j] (at position [j_idx] in the assertion table) of the goal [i]. *) let cnt = count gs in let generate (): int = let black = calc_blacklist cons j_idx g.black g.tgt_ctxt.pc in let sub = goal p cnt black [i,j,jsub] g.tgt_ctxt gs in Statistics.add_goal statistics; Seq.push sub gs.goals; cnt in try let isub = TermMap.find p g.tgt_ctxt.map in if gs.trace then printf "%sduplicate subgoal %d: %s\n" (PC.trace_prefix g.tgt_ctxt.pc) isub (PC.string_of_term p g.tgt_ctxt.pc); if IntSet.mem isub g.ancestors then begin if gs.trace then printf "%scyclic subgoal %d: %s\n" (PC.trace_prefix g.ctxt.pc) isub (PC.string_of_term p g.ctxt.pc); raise Cyclic end; let sub = item in let black = calc_blacklist cons j_idx g.black g.tgt_ctxt.pc in sub.black < - IntSet.union black sub.black ; i , j , ) : : ; if ( item isub gs).obsolete then reactivate_goal ; let black = calc_blacklist cons j_idx g.black g.tgt_ctxt.pc in sub.black <- IntSet.union black sub.black; sub.parents <- (i,j,jsub) :: sub.parents; if (item isub gs).obsolete then reactivate_goal isub gs;*) isub with Not_found -> g.tgt_ctxt.map <- TermMap.add p cnt g.tgt_ctxt.map; generate () let generate_subgoals (i:int) (gs:t): unit = let g = item i gs in let alts = PC.find_backward_goal g.target g.black g.tgt_ctxt.pc in let _, alts, patches = (fun (j,alts,patches) bwd_idx -> let cnt = count gs in try let ps = PC.premises bwd_idx g.tgt_ctxt.pc in let ps,_,npremises,patches = (fun (ps,jsub,npremises,patches) (p,cons) -> let cnt = count gs in let k = generate_subgoal p cons j bwd_idx jsub i gs in let k_pos = (item k gs).pos in (k, k_pos) :: ps, jsub+1, npremises + (if k_pos = None then 1 else 0), if k < cnt then (k,cons,i,j,bwd_idx,jsub) :: patches else patches ) ([],0,0,patches) ps in let ps = List.rev ps in let ps = Array.of_list ps in (j+1), {premises = ps; bwd_idx; npremises; failed = false; obsolete = false} :: alts, patches with Cyclic -> interval_iter (fun k -> g.tgt_ctxt.map <- TermMap.remove (item k gs).goal g.tgt_ctxt.map ) cnt (count gs); Seq.keep cnt gs.goals; j, alts, patches ) (0,[],[]) alts in g.alternatives <- Array.of_list (List.rev alts); let nalts = Array.length g.alternatives in if Term.equivalent g.target (PC.false_constant g.tgt_ctxt.pc) then Statistics.add_falses nalts statistics else Statistics.add_alternatives nalts statistics; List.iter (fun (k,cons,ipar,ialt,bwd_idx,isub) -> let sub = item k gs and par = item ipar gs in let black = calc_blacklist cons bwd_idx par.black par.tgt_ctxt.pc in sub.black <- IntSet.union black sub.black; sub.parents <- (ipar,ialt,isub) :: sub.parents; if sub.obsolete then reactivate_goal k gs; if sub.failed then set_alternative_failed ialt i gs ) patches; if Array.length g.alternatives = 0 then set_goal_failed i gs; if gs.trace then trace_target_subgoals i gs; try let ialt = Search.array_find_min (fun alt -> alt.npremises = 0) g.alternatives in let pos = succeed_alternative ialt g in discharge_target pos g; set_goal_succeeded i gs; with Not_found -> () let ancestors (i:int) (gs:t): int list = IntSet.elements (item i gs).ancestors let trace_ancestors (i:int) (gs:t): unit = let g = item i gs in let ancs = ancestors i gs in let str = String.concat "," (List.map string_of_int ancs) in let prefix = PC.trace_prefix g.ctxt.pc in printf "%sancestors [%s]\n" prefix str let trace_visit (i:int) (gs:t): unit = let g = item i gs in let prefix = PC.trace_prefix g.ctxt.pc in printf "\n%svisit goal %d: %s\n" prefix i (PC.string_long_of_term g.goal g.ctxt.pc); printf " %s\n" (Term.to_string g.goal); List.iter (fun (ipar,ialt,isub) -> let par = item ipar gs in trace_ancestors i gs; printf "%s parent %d %s\n" prefix ipar (PC.string_of_term par.goal par.ctxt.pc); if par.goal <> par.target then printf "%s parent target %s\n" ) g.parents let visit (i:int) (gs:t): unit = assert (i < count gs); assert (is_visitable i gs); assert (not (has_succeeded i gs)); let g = item i gs in if gs.trace then trace_visit i gs; g.visited <- true; try prove_trivially g; set_goal_succeeded i gs with Not_found -> enter i gs; try prove_trivially g; set_goal_succeeded i gs with Not_found -> generate_subgoals i gs let trace_viable_subgoals (gs:t): unit = let max_level = 10 in let prefix level = String.make (2*level) ' ' in let rec trace (i:int) (level:int): unit = let pref = prefix level in let g = item i gs in printf "%sgoal %d %s\n" pref i (PC.string_of_term g.goal g.ctxt.pc); printf "%s failed %b, obsolete %b, proved %b\n" pref g.failed g.obsolete (g.pos <> None); if level = 10 then printf "level %d reached\n" max_level; if not (g.failed || g.obsolete || g.pos <> None) && level < max_level then Array.iteri (fun i (alt:alternative) -> if not (alt.obsolete || alt.failed) then begin assert (alt.bwd_idx >= 0); printf "%salternative %d %s\n" pref i (PC.string_of_term_i alt.bwd_idx g.tgt_ctxt.pc); Array.iter (fun (j,pos) -> trace j (level+1)) alt.premises end ) g.alternatives in trace 0 0 let proof_term (g:term) (pc:PC.t): term * proof_term = let pc = PC.push_empty pc in PC.close_assumptions pc; Statistics.push statistics; Statistics.add_proof statistics; let gs = init g pc in if gs.trace then begin printf "\n%strying to prove: %s\n" (PC.trace_prefix pc) (PC.string_long_of_term g pc); if PC.verbosity pc > 3 then printf "%s %s\n" (PC.trace_prefix pc) (Term.to_string g); printf "\n" end; if not (PC.is_global pc) then PC.close pc; let rec round (i:int) (start:int): unit = if PC.is_interface_check pc && 1 < i then raise (Proof_failed ""); if PC.verbosity pc >= 1 && start >= goal_report_threshold then begin printf "next round entered with %d goals\n" start; let g0 = Seq.elem 0 gs.goals in printf " hard to prove %s\n" (PC.string_of_term g0.goal g0.ctxt.pc); flush_all () end; if goal_limit () <= start then raise (Proof_failed (", goal limit " ^ (string_of_int (goal_limit())) ^ " exceeded")); let cnt = count gs in if PC.is_tracing pc then printf "%s-- round %d with %d goals starting from %d --\n" (PC.trace_prefix pc) i (cnt - start) start; for j = start to cnt - 1 do if is_visitable j gs then visit j gs done; while gs.reactivated <> [] do let lst = List.rev gs.reactivated in gs.reactivated <- []; List.iter (fun j -> if is_visitable j gs then visit j gs) lst; done; assert (gs.reactivated = []); if cnt = count gs then begin raise (Proof_failed (" (subgoals exhausted)")) end; assert (cnt < count gs); if PC.is_tracing pc then printf "\n"; round (i+1) cnt in try round 0 0; with | Root_succeeded -> let g = item 0 gs in let g_pos = match g.pos with | Some pos -> pos in assert (g_pos < PC.count g.ctxt.pc); if gs.trace then print_statistics_and_pop (PC.trace_prefix pc) else Statistics.pop statistics; pc_discharged g_pos g.ctxt.pc | Proof_failed msg -> Statistics.pop statistics; raise (Proof_failed msg) let is_provable (g:term) (pc:PC.t): bool = try let _ = proof_term g pc in true with Proof_failed _ -> false let prove (g:term) (pc:PC.t): unit = let _ = proof_term g pc in () let prove_and_insert (g:term) (pc:PC.t): int = let t,pt = proof_term g pc in PC.add_proved_with_delta t pt 0 pc
d752111835fd3446b0d8c9acbde58e73bd804979dec3a6488b5ce57ff34a3d55
fourmolu/fourmolu
output-LetMixed-InRightAlign-indent=4.hs
{-- should be the same in every option --} let_oneline_empty = let in 10 let_oneline_single = let a = 1 in a + 2 let_oneline_multi = let a = 1; b = 2 in a + b {-- pure let expressions --} let_empty = let in 10 let_single = let a = 1 in a + 2 let_single_sig = let a :: Int a = 1 in a + 2 let_single_comment = let -- a comment a = 1 in a + 2 let_multi = let a = 1 b = 2 in a + b let_single_newline = let a = 1 in a + 2 let_multi_newline = let a = 1 b = 2 in a + b {-- do-block --} test_do = do let let a = 1 let b = 2 c = 3 let d = "hello" in print d let d = "hello" e = "world" in print (d ++ e) let f = 1 in print f {-- list comprehension --} test_list = [ x + a + b + c | x <- xs , let , let a = 1 , let b = 2 c = 2 ] test_list_do = do x <- [ x + a + b + c | x <- xs , let , let a = 1 , let b = 2 c = 3 ] [ x + y + a + b + c | y <- ys , let , let a = 1 , let b = 2 c = 3 ]
null
https://raw.githubusercontent.com/fourmolu/fourmolu/f47860f01cb3cac3b973c5df6ecbae48bbb4c295/data/fourmolu/let-style/output-LetMixed-InRightAlign-indent%3D4.hs
haskell
- should be the same in every option - - pure let expressions - a comment - do-block - - list comprehension -
let_oneline_empty = let in 10 let_oneline_single = let a = 1 in a + 2 let_oneline_multi = let a = 1; b = 2 in a + b let_empty = let in 10 let_single = let a = 1 in a + 2 let_single_sig = let a :: Int a = 1 in a + 2 let_single_comment = a = 1 in a + 2 let_multi = let a = 1 b = 2 in a + b let_single_newline = let a = 1 in a + 2 let_multi_newline = let a = 1 b = 2 in a + b test_do = do let let a = 1 let b = 2 c = 3 let d = "hello" in print d let d = "hello" e = "world" in print (d ++ e) let f = 1 in print f test_list = [ x + a + b + c | x <- xs , let , let a = 1 , let b = 2 c = 2 ] test_list_do = do x <- [ x + a + b + c | x <- xs , let , let a = 1 , let b = 2 c = 3 ] [ x + y + a + b + c | y <- ys , let , let a = 1 , let b = 2 c = 3 ]
d06cbc6d91b3a7153a9431491419b1a1abeed89777d4598fe73eb2067146c8d8
jyh/metaprl
czf_itt_subset.mli
* Subset predicate . * * ---------------------------------------------------------------- * * Copyright ( C ) 2000 , Caltech * * This program is free software ; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation ; either version 2 * of the License , or ( at your option ) any later version . * * This program is distributed in the hope that it will be useful , * but WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the * GNU General Public License for more details . * * You should have received a copy of the GNU General Public License * along with this program ; if not , write to the Free Software * Foundation , Inc. , 675 Mass Ave , Cambridge , , USA . * * Author : * * Subset predicate. * * ---------------------------------------------------------------- * * Copyright (C) 2000 Jason Hickey, Caltech * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * * Author: Jason Hickey * *) extends Czf_itt_dall declare \subset{'s1; 's2} rewrite unfold_subset : \subset{'s1; 's2} <--> dall{'s1; x. mem{'x; 's2}} prec prec_subset (* * -*- * Local Variables: * Caml-master: "compile" * End: * -*- *)
null
https://raw.githubusercontent.com/jyh/metaprl/51ba0bbbf409ecb7f96f5abbeb91902fdec47a19/theories/czf/czf_itt_subset.mli
ocaml
* -*- * Local Variables: * Caml-master: "compile" * End: * -*-
* Subset predicate . * * ---------------------------------------------------------------- * * Copyright ( C ) 2000 , Caltech * * This program is free software ; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation ; either version 2 * of the License , or ( at your option ) any later version . * * This program is distributed in the hope that it will be useful , * but WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the * GNU General Public License for more details . * * You should have received a copy of the GNU General Public License * along with this program ; if not , write to the Free Software * Foundation , Inc. , 675 Mass Ave , Cambridge , , USA . * * Author : * * Subset predicate. * * ---------------------------------------------------------------- * * Copyright (C) 2000 Jason Hickey, Caltech * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * * Author: Jason Hickey * *) extends Czf_itt_dall declare \subset{'s1; 's2} rewrite unfold_subset : \subset{'s1; 's2} <--> dall{'s1; x. mem{'x; 's2}} prec prec_subset
8c125ede5141838b79224930970f1f9d9d831d5b9aec214048e81e4a040c9f1a
msszczep/pequod-cljs
prod.cljs
(ns pequod-cljs.prod (:require [pequod-cljs.core :as core])) ;;ignore println statements in prod (set! *print-fn* (fn [& _])) (core/init!)
null
https://raw.githubusercontent.com/msszczep/pequod-cljs/986ad97fa39d5b83828c07daf80655460b27d2dd/env/prod/cljs/pequod_cljs/prod.cljs
clojure
ignore println statements in prod
(ns pequod-cljs.prod (:require [pequod-cljs.core :as core])) (set! *print-fn* (fn [& _])) (core/init!)
665fad98b9ea30c55c50f0da3fb18f367d80ee20c4a5043f5177544272ff3d40
sneerteam/sneer
util.cljc
(ns reagent-spike.util) (defn foo-cljc [x] "I don't do a whole lot." [x] (println x "Hello, World!"))
null
https://raw.githubusercontent.com/sneerteam/sneer/b093c46321a5a42ae9418df427dbb237489b7bcb/spikes/reagent-spike/src/cljc/reagent_spike/util.cljc
clojure
(ns reagent-spike.util) (defn foo-cljc [x] "I don't do a whole lot." [x] (println x "Hello, World!"))
6d2f3f25a2550eecfb2a683bccf111d1ca6c7378ebb49c053008e57983749969
tisnik/clojure-examples
core.clj
; ( C ) Copyright 2018 , 2020 ; ; All rights reserved. This program and the accompanying materials ; are made available under the terms of the Eclipse Public License v1.0 ; which accompanies this distribution, and is available at -v10.html ; ; Contributors: ; (ns cucumber+expect3.core (:gen-class)) funkce faktorial obsahuje i test na (defn factorial [n] (if (neg? n) (throw (IllegalArgumentException. "negative numbers are not supported!")) (apply * (range 1M (inc n))))) otestujeme funkci faktorial (defn -main [& args] (doseq [i (range 0 10)] (println i "! = " (factorial i))))
null
https://raw.githubusercontent.com/tisnik/clojure-examples/984af4a3e20d994b4f4989678ee1330e409fdae3/cucumber%2Bexpect3/src/cucumber%2Bexpect3/core.clj
clojure
All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 which accompanies this distribution, and is available at Contributors:
( C ) Copyright 2018 , 2020 -v10.html (ns cucumber+expect3.core (:gen-class)) funkce faktorial obsahuje i test na (defn factorial [n] (if (neg? n) (throw (IllegalArgumentException. "negative numbers are not supported!")) (apply * (range 1M (inc n))))) otestujeme funkci faktorial (defn -main [& args] (doseq [i (range 0 10)] (println i "! = " (factorial i))))
26be583cb85319e3ac42ee0b7799576823b8b3df69685633480384ccd8524c6f
Spin1Half/Advent-Of-Coalton-2022
aoc3.lisp
(in-package :coalton-user) (coalton-toplevel for part 1 (declare match-first-back (String -> Char)) (define (match-first-back str) (let line-len = (string:length str)) (let halfway = (math:div line-len 2)) (let str-a = (substring str 0 halfway)) (let str-b = (substring str halfway line-len)) (list:car (list:intersection (lisp (List Char) (str-a) (cl:coerce str-a 'cl:list)) (lisp (List Char) (str-b) (cl:coerce str-b 'cl:list))))) (declare char-value (Char -> Integer)) (define (char-value ch) (lisp Integer (ch) (cl:let ((val (cl:char-int ch))) (cl:if (cl:> val 90) (cl:- val 96) (cl:- val 38))))) part2 (declare group-val (String -> String -> String -> Integer)) (define (group-val str-a str-b str-c) (char-value (list:car (list:intersection (list:intersection (lisp (List Char) (str-a) (cl:coerce str-a 'cl:list)) (lisp (List Char) (str-b) (cl:coerce str-b 'cl:list))) (lisp (List Char) (str-c) (cl:coerce str-c 'cl:list))))))) #+part1 (cl:let ((curr-count 0)) (cl:with-open-file (f "lisp/advent-of-coalton-2022/aoc3input.txt" :direction :input) (cl:do ((line (cl:read-line f nil) (cl:read-line f nil))) ((cl:null line)) (cl:incf curr-count (char-value (match-first-back line))) (cl:print line))) (cl:print curr-count)) part2 (cl:let ((curr-count 0)) (cl:with-open-file (f "lisp/advent-of-coalton-2022/aoc3input.txt" :direction :input) (cl:do* ((line1 (cl:read-line f nil) (cl:read-line f nil)) (line2 (cl:read-line f nil) (cl:read-line f nil)) (line3 (cl:read-line f nil) (cl:read-line f nil))) ((cl:null line3)) (cl:incf curr-count (group-val line1 line2 line3)) (cl:print line1))) (cl:print curr-count))
null
https://raw.githubusercontent.com/Spin1Half/Advent-Of-Coalton-2022/ceef0801aff069f7e116b8d9339efb9d7664571a/aoc3.lisp
lisp
(in-package :coalton-user) (coalton-toplevel for part 1 (declare match-first-back (String -> Char)) (define (match-first-back str) (let line-len = (string:length str)) (let halfway = (math:div line-len 2)) (let str-a = (substring str 0 halfway)) (let str-b = (substring str halfway line-len)) (list:car (list:intersection (lisp (List Char) (str-a) (cl:coerce str-a 'cl:list)) (lisp (List Char) (str-b) (cl:coerce str-b 'cl:list))))) (declare char-value (Char -> Integer)) (define (char-value ch) (lisp Integer (ch) (cl:let ((val (cl:char-int ch))) (cl:if (cl:> val 90) (cl:- val 96) (cl:- val 38))))) part2 (declare group-val (String -> String -> String -> Integer)) (define (group-val str-a str-b str-c) (char-value (list:car (list:intersection (list:intersection (lisp (List Char) (str-a) (cl:coerce str-a 'cl:list)) (lisp (List Char) (str-b) (cl:coerce str-b 'cl:list))) (lisp (List Char) (str-c) (cl:coerce str-c 'cl:list))))))) #+part1 (cl:let ((curr-count 0)) (cl:with-open-file (f "lisp/advent-of-coalton-2022/aoc3input.txt" :direction :input) (cl:do ((line (cl:read-line f nil) (cl:read-line f nil))) ((cl:null line)) (cl:incf curr-count (char-value (match-first-back line))) (cl:print line))) (cl:print curr-count)) part2 (cl:let ((curr-count 0)) (cl:with-open-file (f "lisp/advent-of-coalton-2022/aoc3input.txt" :direction :input) (cl:do* ((line1 (cl:read-line f nil) (cl:read-line f nil)) (line2 (cl:read-line f nil) (cl:read-line f nil)) (line3 (cl:read-line f nil) (cl:read-line f nil))) ((cl:null line3)) (cl:incf curr-count (group-val line1 line2 line3)) (cl:print line1))) (cl:print curr-count))
061418912b31561764ed16ef9e6b7320b1f0ee682fcbd420b2612041567cf55e
aaronc/fx-clj
convert.clj
(ns ^:no-doc fx-clj.core.convert (:require [fx-clj.core.extensibility :refer [convert-arg]] [fx-clj.util :as util] [clojure.core.async :refer [put!]] [ : as csk ] [org.tobereplaced.lettercase :as lettercase]) (:import (javafx.event EventHandler) (clojure.core.async.impl.channels ManyToManyChannel) (javafx.util Callback) (javafx.collections ObservableList FXCollections) (javafx.scene Node) (javax.swing JComponent) (javafx.embed.swing SwingNode) (javafx.beans.property Property) (fx_clj.binding ReactiveAtomObservable) [freactive IReactiveAtom])) (defmethod convert-arg :default [_ v _] v) (defmethod convert-arg [EventHandler clojure.lang.IFn] [_ f _] (util/event-handler* f)) (defmethod convert-arg [EventHandler ManyToManyChannel] [_ ch _] (util/event-handler [e] (put! ch e))) (defmethod convert-arg [Callback clojure.lang.IFn] [_ f _] (util/callback* f)) (defmethod convert-arg [Enum clojure.lang.Keyword] [enum kw _] (Enum/valueOf enum (lettercase/upper-underscore-name kw))) (defmethod convert-arg [ObservableList clojure.lang.Sequential] [_ v {:keys [element-type] :or {element-type Object}}] (FXCollections/observableList (for [x v] (convert-arg element-type x nil)))) (prefer-method convert-arg [ObservableList clojure.lang.Sequential] [Object clojure.lang.PersistentVector]) (defmethod convert-arg [Node JComponent] [nt jc _] (doto (SwingNode.) (.setContent jc))) (defmethod convert-arg [Property IReactiveAtom] [_ a _] (ReactiveAtomObservable. a))
null
https://raw.githubusercontent.com/aaronc/fx-clj/29639356d8d1253438ecf61e123caacefa9269ec/src/fx_clj/core/convert.clj
clojure
(ns ^:no-doc fx-clj.core.convert (:require [fx-clj.core.extensibility :refer [convert-arg]] [fx-clj.util :as util] [clojure.core.async :refer [put!]] [ : as csk ] [org.tobereplaced.lettercase :as lettercase]) (:import (javafx.event EventHandler) (clojure.core.async.impl.channels ManyToManyChannel) (javafx.util Callback) (javafx.collections ObservableList FXCollections) (javafx.scene Node) (javax.swing JComponent) (javafx.embed.swing SwingNode) (javafx.beans.property Property) (fx_clj.binding ReactiveAtomObservable) [freactive IReactiveAtom])) (defmethod convert-arg :default [_ v _] v) (defmethod convert-arg [EventHandler clojure.lang.IFn] [_ f _] (util/event-handler* f)) (defmethod convert-arg [EventHandler ManyToManyChannel] [_ ch _] (util/event-handler [e] (put! ch e))) (defmethod convert-arg [Callback clojure.lang.IFn] [_ f _] (util/callback* f)) (defmethod convert-arg [Enum clojure.lang.Keyword] [enum kw _] (Enum/valueOf enum (lettercase/upper-underscore-name kw))) (defmethod convert-arg [ObservableList clojure.lang.Sequential] [_ v {:keys [element-type] :or {element-type Object}}] (FXCollections/observableList (for [x v] (convert-arg element-type x nil)))) (prefer-method convert-arg [ObservableList clojure.lang.Sequential] [Object clojure.lang.PersistentVector]) (defmethod convert-arg [Node JComponent] [nt jc _] (doto (SwingNode.) (.setContent jc))) (defmethod convert-arg [Property IReactiveAtom] [_ a _] (ReactiveAtomObservable. a))
8f27b442eb72c2f5ae7819fdee787775af092417472433259fb4a5f76bdfd4b6
prg-titech/Kani-CUDA
diffusion3d-temporal-seq-synth.rkt
#lang rosette (require "diffusion3d-baseline.rkt" "../../lang.rkt" racket/hash) (require rosette/query/debug rosette/lib/render) (current-bitwidth 7) (define switch 0) (define (diffusion-kernel-temporal-blocking in mid out nx ny nz ce cw cn cs ct cb cc) ;; Number of elements in xy plane of input (:= int xy (*/LS nx ny)) (: int i j c sc i2 j2 c2 sc2) (:= int NUM_SMEM 3) (:= int BLOCKAREA (*/LS (block-dim 0) (block-dim 1))) (:shared real sb[NUM_SMEM][BLOCKAREA]) (:= int sb1 0) (:= int sb2 1) (:= int sb3 2) (: real mid[(*/LS NUM_SMEM BLOCKAREA ) ] ) (= i (+/LS (*/LS (-/LS (block-dim 0) 2) (block-idx 0)) (thread-idx 0) -1)) (= i (max/LS i 0)) (= i (min/LS i (-/LS nx 1))) (= j (+/LS (*/LS (-/LS (block-dim 1) 2) (block-idx 1)) (thread-idx 1) -1)) (= j (max/LS j 0)) (= j (min/LS j (-/LS ny 1))) (= c (+/LS i (*/LS j nx))) (print c) (= sc (+/LS (thread-idx 0) (*/LS (thread-idx 1) (block-dim 0)))) (= i2 (+/LS (*/LS (-/LS (block-dim 0) 2) (block-idx 0)) (min/LS (thread-idx 0) (-/LS (block-dim 0) 3)))) (= i2 (min/LS i2 (-/LS nx 1))) (= j2 (+/LS (*/LS (-/LS (block-dim 1) 2) (block-idx 1)) (min/LS (thread-idx 1) (-/LS (block-dim 1) 3)))) (= j2 (min/LS j2 (-/LS ny 1))) (= c2 (+/LS i2 (*/LS j2 nx))) (= sc2 (+/LS (modulo/LS i2 (-/LS (block-dim 0) 2)) (*/LS (block-dim 0) (+/LS (modulo/LS j2 (-/LS (block-dim 1) 2)) 1)) 1)) (:= int w (?: (eq?/LS i 0) c (-/LS c 1))) (:= int e (?: (eq?/LS i (-/LS nx 1)) c (+/LS c 1))) (:= int n (?: (eq?/LS j 0) c (-/LS c nx))) (:= int s (?: (eq?/LS j (-/LS ny 1)) c (+/LS c nx))) (:= int b c) (:= int t (?: (eq?/LS nz 1) c (+/LS c xy))) (:= real v (+/LS (*/LS cc [in c]) (*/LS cw [in w]) (*/LS ce [in e]) (*/LS cs [in s]) (*/LS cn [in n]) (*/LS cb [in b]) (*/LS ct [in t]))) (= [mid (+/LS (*/LS sb2 BLOCKAREA) sc)] v) (+= c xy) (:= int k 1) (for- [: (</LS k nz) : (++ k)] (= w (?: (eq?/LS i 0) c (-/LS c 1))) (= e (?: (eq?/LS i (-/LS nx 1)) c (+/LS c 1))) (= n (?: (eq?/LS j 0) c (-/LS c nx))) (= s (?: (eq?/LS j (-/LS ny 1)) c (+/LS c nx))) (= b (?: (eq?/LS k 0) c (-/LS c xy))) (= t (?: (eq?/LS k (-/LS nz 1)) c (+/LS c xy))) (:= real v (+/LS (*/LS cc [in c]) (*/LS cw [in w]) (*/LS ce [in e]) (*/LS cs [in s]) (*/LS cn [in n]) (*/LS cb [in b]) (*/LS ct [in t]))) (= [mid c] v) (+= c xy) (choose (syncthreads) (void)) (= w (?: (eq?/LS i2 0) sc2 (-/LS sc2 1))) (= e (?: (eq?/LS i2 (-/LS nx 1)) sc2 (+/LS sc2 1))) (= n (?: (eq?/LS j2 0) sc2 (-/LS sc2 (block-dim 0)))) (= s (?: (eq?/LS j2 (-/LS ny 1)) sc2 (+/LS sc2 (block-dim 0)))) (:= int bv (?: (eq?/LS (-/LS k 1) 0) sb2 sb1)) (:= int tv sb3) (if- (&&/LS (</LS (thread-idx 0) (-/LS (block-dim 0) 2)) (</LS (thread-idx 1) (-/LS (block-dim 1) 2))) (= [out c2] (+/LS (*/LS cc [mid (+/LS (*/LS sb2 BLOCKAREA) c)]) (*/LS cw [mid (+/LS (*/LS sb2 BLOCKAREA) w)]) (*/LS ce [mid (+/LS (*/LS sb2 BLOCKAREA) e)]) (*/LS cn [mid (+/LS (*/LS sb2 BLOCKAREA) n)]) (*/LS cs [mid (+/LS (*/LS sb2 BLOCKAREA) s)]) (*/LS cb [mid (+/LS (*/LS bv BLOCKAREA) b)]) (*/LS ct [mid (+/LS (*/LS tv BLOCKAREA) t)])))) (+= c2 xy) (syncthreads) (:= int sb-temp sb1) (= sb1 sb2) (= sb2 sb3) (= sb3 sb-temp)) (: = sb1 ) ; (= sb1 sb2) (= sb2 sb3 ) ; (= sb3 sb-temp)) (= w (?: (eq?/LS i2 0) sc2 (-/LS sc2 1))) (= e (?: (eq?/LS i2 (-/LS nx 1)) sc2 (+/LS sc2 1))) (= n (?: (eq?/LS j2 0) sc2 (-/LS sc2 (block-dim 0)))) (= s (?: (eq?/LS j2 (-/LS ny 1)) sc2 (+/LS sc2 (block-dim 0)))) (:= int bv (?: (eq?/LS (-/LS k 1) 0) sb2 sb1)) (:= int tv sb3) (if- (&&/LS (</LS (thread-idx 0) (-/LS (block-dim 0) 2)) (</LS (thread-idx 1) (-/LS (block-dim 1) 2))) (= [out c2] (+/LS (*/LS cc [mid (+/LS (*/LS sb2 BLOCKAREA) c)]) (*/LS cw [mid (+/LS (*/LS sb2 BLOCKAREA) w)]) (*/LS ce [mid (+/LS (*/LS sb2 BLOCKAREA) e)]) (*/LS cn [mid (+/LS (*/LS sb2 BLOCKAREA) n)]) (*/LS cs [mid (+/LS (*/LS sb2 BLOCKAREA) s)]) (*/LS cb [mid (+/LS (*/LS bv BLOCKAREA) b)]) (*/LS ct [mid (+/LS (*/LS tv BLOCKAREA) t)]))))) (= w ( ? : ( eq?/LS i2 0 ) sc2 ( -/LS sc2 1 ) ) ) (= e ( ? : ( eq?/LS i2 ( -/LS nx 1 ) ) sc2 ( + /LS sc2 1 ) ) ) (= n ( ? : ( eq?/LS j2 0 ) sc2 ( -/LS sc2 ( block - dim 0 ) ) ) ) (= s ( ? : ( eq?/LS j2 ( -/LS ny 1 ) ) sc2 ( + /LS sc2 ( block - dim 0 ) ) ) ) ; (:= int bv sb1) ; (:= int tv sb2) ; ;(printf "sb2 = ~a\n" sb2) ( if- ( & & /LS ( < /LS ( thread - idx 0 ) ( -/LS ( block - dim 0 ) 2 ) ) ( < /LS ( thread - idx 1 ) ( -/LS ( block - dim 1 ) 2 ) ) ) (= [ out c2 ] ( + /LS ( * /LS cc [ sb sb2 sc2 ] ) ( * /LS cw [ sb sb2 w ] ) ( * /LS ce [ sb sb2 e ] ) ( * /LS cs [ sb sb2 s ] ) ; (*/LS cn [sb sb2 n]) (*/LS cb [sb bv sc2]) (*/LS ct [sb tv sc2]))))) (define (diffusion-run-kernel grid block count in mid out nx ny nz ce cw cn cs ct cb cc) (define temp 0) (for ([i (in-range count)]) (invoke-kernel diffusion-kernel-temporal-blocking grid block in mid out nx ny nz ce cw cn cs ct cb cc) (set! out in))) ;; Add a constraint that it is equal to each of the elements of two arrays , arr1 and arr2 , to asserts . (define (array-eq-verify arr1 arr2 len) (for ([i (in-range len)]) (assert (eq? (array-ref-host arr1 i) (array-ref-host arr2 i))))) (define (r) (define-symbolic* r real?) r) (define-values (SIZEX SIZEY SIZEZ) (values 6 6 3)) (define SIZE (* SIZEX SIZEY SIZEZ)) (define-values (BLOCKSIZEX BLOCKSIZEY) (values 5 5)) (define CPU-in (make-array (for/vector ([i SIZE]) (make-element (r))) SIZE)) (define CPU-out (make-array (for/vector ([i SIZE]) (make-element i)) SIZE)) (define GPU-in (make-array (for/vector ([i SIZE]) (make-element (array-ref-host CPU-in i))) SIZE)) (define GPU-mid (make-array (for/vector ([i SIZE]) (make-element i)) SIZE)) (define GPU-out (make-array (for/vector ([i SIZE]) (make-element i)) SIZE)) (define-symbolic e w n s t b c real?) ( define - values ( e w n s t b c ) ( values 1 1 1 1 1 1 1 ) ) ;; Execute a diffusion program on CPU ;; Execute a diffusion program on GPU (define lst (for/list ([i SIZE]) (array-ref-host CPU-in i))) (define (synth-stencil) (time (synthesize #:forall (append lst (list e w n s t b c)) #:guarantee (begin (diffusion3d-baseline 2 CPU-in CPU-out SIZEX SIZEY SIZEZ e w n s t b c) (diffusion-run-kernel (list (quotient SIZEX (- BLOCKSIZEX 2)) (quotient SIZEY (- BLOCKSIZEY 2))) (list BLOCKSIZEX BLOCKSIZEY) 1 GPU-in GPU-mid GPU-out SIZEX SIZEY SIZEZ e w n s t b c) (array-eq-verify CPU-in GPU-out SIZE))))) ;(map syntax->datum (generate-forms (synth-stencil))) (define (seq-synth-stencil n) (time (set! switch 0) (define ans (model (synth-stencil))) (for ([i (in-range 1 n)]) (set! switch i) (set! ans (hash-union ans (model (synth-stencil)))) ) (map syntax->datum (generate-forms (sat ans)))) (set! switch -1))
null
https://raw.githubusercontent.com/prg-titech/Kani-CUDA/e97c4bede43a5fc4031a7d2cfc32d71b01ac26c4/Emulator/Examples/Diffusion3d/diffusion3d-temporal-seq-synth.rkt
racket
Number of elements in xy plane of input (= sb1 sb2) (= sb3 sb-temp)) (:= int bv sb1) (:= int tv sb2) ;(printf "sb2 = ~a\n" sb2) (*/LS cn [sb sb2 n]) (*/LS cb [sb bv sc2]) (*/LS ct [sb tv sc2]))))) Add a constraint that it is equal to each of the elements of Execute a diffusion program on CPU Execute a diffusion program on GPU (map syntax->datum (generate-forms (synth-stencil)))
#lang rosette (require "diffusion3d-baseline.rkt" "../../lang.rkt" racket/hash) (require rosette/query/debug rosette/lib/render) (current-bitwidth 7) (define switch 0) (define (diffusion-kernel-temporal-blocking in mid out nx ny nz ce cw cn cs ct cb cc) (:= int xy (*/LS nx ny)) (: int i j c sc i2 j2 c2 sc2) (:= int NUM_SMEM 3) (:= int BLOCKAREA (*/LS (block-dim 0) (block-dim 1))) (:shared real sb[NUM_SMEM][BLOCKAREA]) (:= int sb1 0) (:= int sb2 1) (:= int sb3 2) (: real mid[(*/LS NUM_SMEM BLOCKAREA ) ] ) (= i (+/LS (*/LS (-/LS (block-dim 0) 2) (block-idx 0)) (thread-idx 0) -1)) (= i (max/LS i 0)) (= i (min/LS i (-/LS nx 1))) (= j (+/LS (*/LS (-/LS (block-dim 1) 2) (block-idx 1)) (thread-idx 1) -1)) (= j (max/LS j 0)) (= j (min/LS j (-/LS ny 1))) (= c (+/LS i (*/LS j nx))) (print c) (= sc (+/LS (thread-idx 0) (*/LS (thread-idx 1) (block-dim 0)))) (= i2 (+/LS (*/LS (-/LS (block-dim 0) 2) (block-idx 0)) (min/LS (thread-idx 0) (-/LS (block-dim 0) 3)))) (= i2 (min/LS i2 (-/LS nx 1))) (= j2 (+/LS (*/LS (-/LS (block-dim 1) 2) (block-idx 1)) (min/LS (thread-idx 1) (-/LS (block-dim 1) 3)))) (= j2 (min/LS j2 (-/LS ny 1))) (= c2 (+/LS i2 (*/LS j2 nx))) (= sc2 (+/LS (modulo/LS i2 (-/LS (block-dim 0) 2)) (*/LS (block-dim 0) (+/LS (modulo/LS j2 (-/LS (block-dim 1) 2)) 1)) 1)) (:= int w (?: (eq?/LS i 0) c (-/LS c 1))) (:= int e (?: (eq?/LS i (-/LS nx 1)) c (+/LS c 1))) (:= int n (?: (eq?/LS j 0) c (-/LS c nx))) (:= int s (?: (eq?/LS j (-/LS ny 1)) c (+/LS c nx))) (:= int b c) (:= int t (?: (eq?/LS nz 1) c (+/LS c xy))) (:= real v (+/LS (*/LS cc [in c]) (*/LS cw [in w]) (*/LS ce [in e]) (*/LS cs [in s]) (*/LS cn [in n]) (*/LS cb [in b]) (*/LS ct [in t]))) (= [mid (+/LS (*/LS sb2 BLOCKAREA) sc)] v) (+= c xy) (:= int k 1) (for- [: (</LS k nz) : (++ k)] (= w (?: (eq?/LS i 0) c (-/LS c 1))) (= e (?: (eq?/LS i (-/LS nx 1)) c (+/LS c 1))) (= n (?: (eq?/LS j 0) c (-/LS c nx))) (= s (?: (eq?/LS j (-/LS ny 1)) c (+/LS c nx))) (= b (?: (eq?/LS k 0) c (-/LS c xy))) (= t (?: (eq?/LS k (-/LS nz 1)) c (+/LS c xy))) (:= real v (+/LS (*/LS cc [in c]) (*/LS cw [in w]) (*/LS ce [in e]) (*/LS cs [in s]) (*/LS cn [in n]) (*/LS cb [in b]) (*/LS ct [in t]))) (= [mid c] v) (+= c xy) (choose (syncthreads) (void)) (= w (?: (eq?/LS i2 0) sc2 (-/LS sc2 1))) (= e (?: (eq?/LS i2 (-/LS nx 1)) sc2 (+/LS sc2 1))) (= n (?: (eq?/LS j2 0) sc2 (-/LS sc2 (block-dim 0)))) (= s (?: (eq?/LS j2 (-/LS ny 1)) sc2 (+/LS sc2 (block-dim 0)))) (:= int bv (?: (eq?/LS (-/LS k 1) 0) sb2 sb1)) (:= int tv sb3) (if- (&&/LS (</LS (thread-idx 0) (-/LS (block-dim 0) 2)) (</LS (thread-idx 1) (-/LS (block-dim 1) 2))) (= [out c2] (+/LS (*/LS cc [mid (+/LS (*/LS sb2 BLOCKAREA) c)]) (*/LS cw [mid (+/LS (*/LS sb2 BLOCKAREA) w)]) (*/LS ce [mid (+/LS (*/LS sb2 BLOCKAREA) e)]) (*/LS cn [mid (+/LS (*/LS sb2 BLOCKAREA) n)]) (*/LS cs [mid (+/LS (*/LS sb2 BLOCKAREA) s)]) (*/LS cb [mid (+/LS (*/LS bv BLOCKAREA) b)]) (*/LS ct [mid (+/LS (*/LS tv BLOCKAREA) t)])))) (+= c2 xy) (syncthreads) (:= int sb-temp sb1) (= sb1 sb2) (= sb2 sb3) (= sb3 sb-temp)) (: = sb1 ) (= sb2 sb3 ) (= w (?: (eq?/LS i2 0) sc2 (-/LS sc2 1))) (= e (?: (eq?/LS i2 (-/LS nx 1)) sc2 (+/LS sc2 1))) (= n (?: (eq?/LS j2 0) sc2 (-/LS sc2 (block-dim 0)))) (= s (?: (eq?/LS j2 (-/LS ny 1)) sc2 (+/LS sc2 (block-dim 0)))) (:= int bv (?: (eq?/LS (-/LS k 1) 0) sb2 sb1)) (:= int tv sb3) (if- (&&/LS (</LS (thread-idx 0) (-/LS (block-dim 0) 2)) (</LS (thread-idx 1) (-/LS (block-dim 1) 2))) (= [out c2] (+/LS (*/LS cc [mid (+/LS (*/LS sb2 BLOCKAREA) c)]) (*/LS cw [mid (+/LS (*/LS sb2 BLOCKAREA) w)]) (*/LS ce [mid (+/LS (*/LS sb2 BLOCKAREA) e)]) (*/LS cn [mid (+/LS (*/LS sb2 BLOCKAREA) n)]) (*/LS cs [mid (+/LS (*/LS sb2 BLOCKAREA) s)]) (*/LS cb [mid (+/LS (*/LS bv BLOCKAREA) b)]) (*/LS ct [mid (+/LS (*/LS tv BLOCKAREA) t)]))))) (= w ( ? : ( eq?/LS i2 0 ) sc2 ( -/LS sc2 1 ) ) ) (= e ( ? : ( eq?/LS i2 ( -/LS nx 1 ) ) sc2 ( + /LS sc2 1 ) ) ) (= n ( ? : ( eq?/LS j2 0 ) sc2 ( -/LS sc2 ( block - dim 0 ) ) ) ) (= s ( ? : ( eq?/LS j2 ( -/LS ny 1 ) ) sc2 ( + /LS sc2 ( block - dim 0 ) ) ) ) ( if- ( & & /LS ( < /LS ( thread - idx 0 ) ( -/LS ( block - dim 0 ) 2 ) ) ( < /LS ( thread - idx 1 ) ( -/LS ( block - dim 1 ) 2 ) ) ) (= [ out c2 ] ( + /LS ( * /LS cc [ sb sb2 sc2 ] ) ( * /LS cw [ sb sb2 w ] ) ( * /LS ce [ sb sb2 e ] ) ( * /LS cs [ sb sb2 s ] ) (define (diffusion-run-kernel grid block count in mid out nx ny nz ce cw cn cs ct cb cc) (define temp 0) (for ([i (in-range count)]) (invoke-kernel diffusion-kernel-temporal-blocking grid block in mid out nx ny nz ce cw cn cs ct cb cc) (set! out in))) two arrays , arr1 and arr2 , to asserts . (define (array-eq-verify arr1 arr2 len) (for ([i (in-range len)]) (assert (eq? (array-ref-host arr1 i) (array-ref-host arr2 i))))) (define (r) (define-symbolic* r real?) r) (define-values (SIZEX SIZEY SIZEZ) (values 6 6 3)) (define SIZE (* SIZEX SIZEY SIZEZ)) (define-values (BLOCKSIZEX BLOCKSIZEY) (values 5 5)) (define CPU-in (make-array (for/vector ([i SIZE]) (make-element (r))) SIZE)) (define CPU-out (make-array (for/vector ([i SIZE]) (make-element i)) SIZE)) (define GPU-in (make-array (for/vector ([i SIZE]) (make-element (array-ref-host CPU-in i))) SIZE)) (define GPU-mid (make-array (for/vector ([i SIZE]) (make-element i)) SIZE)) (define GPU-out (make-array (for/vector ([i SIZE]) (make-element i)) SIZE)) (define-symbolic e w n s t b c real?) ( define - values ( e w n s t b c ) ( values 1 1 1 1 1 1 1 ) ) (define lst (for/list ([i SIZE]) (array-ref-host CPU-in i))) (define (synth-stencil) (time (synthesize #:forall (append lst (list e w n s t b c)) #:guarantee (begin (diffusion3d-baseline 2 CPU-in CPU-out SIZEX SIZEY SIZEZ e w n s t b c) (diffusion-run-kernel (list (quotient SIZEX (- BLOCKSIZEX 2)) (quotient SIZEY (- BLOCKSIZEY 2))) (list BLOCKSIZEX BLOCKSIZEY) 1 GPU-in GPU-mid GPU-out SIZEX SIZEY SIZEZ e w n s t b c) (array-eq-verify CPU-in GPU-out SIZE))))) (define (seq-synth-stencil n) (time (set! switch 0) (define ans (model (synth-stencil))) (for ([i (in-range 1 n)]) (set! switch i) (set! ans (hash-union ans (model (synth-stencil)))) ) (map syntax->datum (generate-forms (sat ans)))) (set! switch -1))
bc045522df395e5f3310abdce4d8a69218d020c798ef3042df0461fe5ba72947
broadinstitute/firecloud-ui
common.cljs
(ns broadfcui.page.method-repo.method.common (:require [dmohs.react :as react] [clojure.string :as string] [broadfcui.common.components :as comps] [broadfcui.common.icons :as icons] [broadfcui.common.links :as links] [broadfcui.common.method.config-io :as config-io] [broadfcui.common.style :as style] [broadfcui.common.table :refer [Table]] [broadfcui.common.table.style :as table-style] [broadfcui.components.spinner :refer [spinner]] [broadfcui.endpoints :as endpoints] [broadfcui.net :as net] [broadfcui.utils :as utils] [broadfcui.utils.ajax :as ajax] )) (react/defc- IOView {:render (fn [{:keys [props state]}] (let [{:keys [error inputs-outputs]} @state] (cond error [comps/ErrorViewer (:error error)] inputs-outputs [config-io/IOTables {:style {:marginTop "1rem"} :inputs-outputs inputs-outputs :values (:values props) :default-hidden? (:default-hidden? props)}] :else (spinner "Loading inputs/outputs...")))) :component-did-mount (fn [{:keys [props state]}] (endpoints/call-ajax-orch {:endpoint endpoints/get-inputs-outputs :payload (:method-ref props) :headers ajax/content-type=json :on-done (fn [{:keys [success? get-parsed-response]}] (if success? (swap! state assoc :inputs-outputs (get-parsed-response)) (swap! state assoc :error (get-parsed-response false))))}))}) (react/defc ConfigTable {:refresh (fn [{:keys [props state]}] (swap! state dissoc :associated-configs :compatible-configs :resolved-configs :configs-error) (endpoints/call-ajax-orch {:endpoint (endpoints/get-agora-method-configs (:method-id props)) :on-done (net/handle-ajax-response (fn [{:keys [success? parsed-response]}] (if success? (swap! state assoc :associated-configs parsed-response) (swap! state assoc :configs-error (:message parsed-response)))))}) (endpoints/call-ajax-orch {:endpoint (endpoints/get-agora-compatible-configs (conj (:method-id props) (select-keys props [:snapshot-id]))) :on-done (net/handle-ajax-response (fn [{:keys [success? parsed-response]}] (if success? (swap! state assoc :compatible-configs (set parsed-response)) (swap! state assoc :configs-error (:message parsed-response)))))})) :render (fn [{:keys [props state]}] (let [{:keys [style make-config-link-props snapshot-id]} props {:keys [resolved-configs configs-error]} @state] (cond configs-error [:div {:style {:textAlign "center" :color (:state-exception style/colors)}} "Error loading configs: " configs-error] (not resolved-configs) [:div {:style {:textAlign "center" :padding "1rem"}} (spinner "Loading configs...")] :else [Table {:data-test-id "config-table" :data resolved-configs :body {:empty-message "You don't have access to any published configurations for this method." :style (utils/deep-merge table-style/table-light {:table {:backgroundColor "white"}} style) :behavior {:reorderable-columns? false} :columns [{:id "compatible?" :initial-width 30 :resizable? false :sortable? false :filterable? false :column-data :compatible? :as-text (fn [c] (when-not c (str "This configuration is not fully compatible with snapshot " snapshot-id))) :render (fn [c] (when-not c (icons/render-icon {:style {:color (:state-warning style/colors)}} :error)))} {:header "Configuration" :initial-width 400 :as-text (fn [{:keys [name namespace snapshotId]}] (str namespace "/" name " snapshot " snapshotId)) :sort-by #(replace % [:namespace :name :snapshotId]) :render (fn [{:keys [name namespace snapshotId] :as config}] (links/create-internal (merge {:data-test-id (str namespace "-" name "-" snapshotId "-link")} (make-config-link-props config)) (style/render-name-id (str namespace "/" name) snapshotId)))} {:header "Method Snapshot" :initial-width 135 :filterable? false :column-data #(get-in % [:payloadObject :methodRepoMethod :methodVersion])} {:header "Synopsis" :initial-width :auto :column-data :synopsis}]} :toolbar {:style {:padding 2} ;; gives room for highlight around filter field :filter-bar {:inner {:width 300}}}}]))) :component-did-mount (fn [{:keys [this]}] (this :refresh)) :component-did-update (fn [{:keys [props prev-state state]}] (let [has-both? (fn [s] (and (:associated-configs s) (:compatible-configs s)))] (when (and (not (has-both? prev-state)) (has-both? @state)) (let [resolved-configs (mapv (fn [config] (assoc config :compatible? (contains? (:compatible-configs @state) config))) (:associated-configs @state)) {:keys [on-load]} props] (when on-load (on-load resolved-configs)) (swap! state assoc :resolved-configs resolved-configs)))))}) (defn render-config-details [{:keys [managers method payloadObject snapshotComment]}] [:div {} [:div {:style {:display "flex"}} (style/create-summary-block (str "Configuration Owner" (when (> (count managers) 1) "s")) (string/join ", " managers)) (style/create-summary-block "Designed For" (str "Method Snapshot " (:snapshotId method)))] [:div {:style {:display "flex"}} (some->> (:rootEntityType payloadObject) (style/create-summary-block "Root Entity Type")) Snapshot comments for configs can only be created by the API . Hide the comment field if it does n't ;; exist to avoid tantalizing UI-only users with something they can't have (at least until GAWB-2702) (some->> snapshotComment (style/create-summary-block "Snapshot Comment"))] (style/create-subsection-header "Connections") [IOView {:method-ref {:methodNamespace (:namespace method) :methodName (:name method) :methodVersion (:snapshotId method)} :values (select-keys payloadObject [:inputs :outputs])}]])
null
https://raw.githubusercontent.com/broadinstitute/firecloud-ui/8eb077bc137ead105db5665a8fa47a7523145633/src/cljs/main/broadfcui/page/method_repo/method/common.cljs
clojure
gives room for highlight around filter field exist to avoid tantalizing UI-only users with something they can't have (at least until GAWB-2702)
(ns broadfcui.page.method-repo.method.common (:require [dmohs.react :as react] [clojure.string :as string] [broadfcui.common.components :as comps] [broadfcui.common.icons :as icons] [broadfcui.common.links :as links] [broadfcui.common.method.config-io :as config-io] [broadfcui.common.style :as style] [broadfcui.common.table :refer [Table]] [broadfcui.common.table.style :as table-style] [broadfcui.components.spinner :refer [spinner]] [broadfcui.endpoints :as endpoints] [broadfcui.net :as net] [broadfcui.utils :as utils] [broadfcui.utils.ajax :as ajax] )) (react/defc- IOView {:render (fn [{:keys [props state]}] (let [{:keys [error inputs-outputs]} @state] (cond error [comps/ErrorViewer (:error error)] inputs-outputs [config-io/IOTables {:style {:marginTop "1rem"} :inputs-outputs inputs-outputs :values (:values props) :default-hidden? (:default-hidden? props)}] :else (spinner "Loading inputs/outputs...")))) :component-did-mount (fn [{:keys [props state]}] (endpoints/call-ajax-orch {:endpoint endpoints/get-inputs-outputs :payload (:method-ref props) :headers ajax/content-type=json :on-done (fn [{:keys [success? get-parsed-response]}] (if success? (swap! state assoc :inputs-outputs (get-parsed-response)) (swap! state assoc :error (get-parsed-response false))))}))}) (react/defc ConfigTable {:refresh (fn [{:keys [props state]}] (swap! state dissoc :associated-configs :compatible-configs :resolved-configs :configs-error) (endpoints/call-ajax-orch {:endpoint (endpoints/get-agora-method-configs (:method-id props)) :on-done (net/handle-ajax-response (fn [{:keys [success? parsed-response]}] (if success? (swap! state assoc :associated-configs parsed-response) (swap! state assoc :configs-error (:message parsed-response)))))}) (endpoints/call-ajax-orch {:endpoint (endpoints/get-agora-compatible-configs (conj (:method-id props) (select-keys props [:snapshot-id]))) :on-done (net/handle-ajax-response (fn [{:keys [success? parsed-response]}] (if success? (swap! state assoc :compatible-configs (set parsed-response)) (swap! state assoc :configs-error (:message parsed-response)))))})) :render (fn [{:keys [props state]}] (let [{:keys [style make-config-link-props snapshot-id]} props {:keys [resolved-configs configs-error]} @state] (cond configs-error [:div {:style {:textAlign "center" :color (:state-exception style/colors)}} "Error loading configs: " configs-error] (not resolved-configs) [:div {:style {:textAlign "center" :padding "1rem"}} (spinner "Loading configs...")] :else [Table {:data-test-id "config-table" :data resolved-configs :body {:empty-message "You don't have access to any published configurations for this method." :style (utils/deep-merge table-style/table-light {:table {:backgroundColor "white"}} style) :behavior {:reorderable-columns? false} :columns [{:id "compatible?" :initial-width 30 :resizable? false :sortable? false :filterable? false :column-data :compatible? :as-text (fn [c] (when-not c (str "This configuration is not fully compatible with snapshot " snapshot-id))) :render (fn [c] (when-not c (icons/render-icon {:style {:color (:state-warning style/colors)}} :error)))} {:header "Configuration" :initial-width 400 :as-text (fn [{:keys [name namespace snapshotId]}] (str namespace "/" name " snapshot " snapshotId)) :sort-by #(replace % [:namespace :name :snapshotId]) :render (fn [{:keys [name namespace snapshotId] :as config}] (links/create-internal (merge {:data-test-id (str namespace "-" name "-" snapshotId "-link")} (make-config-link-props config)) (style/render-name-id (str namespace "/" name) snapshotId)))} {:header "Method Snapshot" :initial-width 135 :filterable? false :column-data #(get-in % [:payloadObject :methodRepoMethod :methodVersion])} {:header "Synopsis" :initial-width :auto :column-data :synopsis}]} :filter-bar {:inner {:width 300}}}}]))) :component-did-mount (fn [{:keys [this]}] (this :refresh)) :component-did-update (fn [{:keys [props prev-state state]}] (let [has-both? (fn [s] (and (:associated-configs s) (:compatible-configs s)))] (when (and (not (has-both? prev-state)) (has-both? @state)) (let [resolved-configs (mapv (fn [config] (assoc config :compatible? (contains? (:compatible-configs @state) config))) (:associated-configs @state)) {:keys [on-load]} props] (when on-load (on-load resolved-configs)) (swap! state assoc :resolved-configs resolved-configs)))))}) (defn render-config-details [{:keys [managers method payloadObject snapshotComment]}] [:div {} [:div {:style {:display "flex"}} (style/create-summary-block (str "Configuration Owner" (when (> (count managers) 1) "s")) (string/join ", " managers)) (style/create-summary-block "Designed For" (str "Method Snapshot " (:snapshotId method)))] [:div {:style {:display "flex"}} (some->> (:rootEntityType payloadObject) (style/create-summary-block "Root Entity Type")) Snapshot comments for configs can only be created by the API . Hide the comment field if it does n't (some->> snapshotComment (style/create-summary-block "Snapshot Comment"))] (style/create-subsection-header "Connections") [IOView {:method-ref {:methodNamespace (:namespace method) :methodName (:name method) :methodVersion (:snapshotId method)} :values (select-keys payloadObject [:inputs :outputs])}]])
e2b826f188cb1a873bb717eadf20801f872a8a73ef10cf4cd908dd6a689d4a35
jayrbolton/coursework
TrustMe.hs
{-# LANGUAGE EmptyDataDecls , ExistentialQuantification , ScopedTypeVariables , NoMonomorphismRestriction #-} module MAlonzo.Relation.Binary.PropositionalEquality.TrustMe where import qualified Unsafe.Coerce import qualified MAlonzo.Relation.Binary.Core import qualified MAlonzo.Relation.Binary.PropositionalEquality name7 = ("Relation.Binary.PropositionalEquality.TrustMe.primTrustMe") d7 = (\ v0 -> (\ v1 -> (\ v2 -> (MAlonzo.Relation.Binary.Core.C240)))) name11 = ("Relation.Binary.PropositionalEquality.TrustMe.trustMe") d11 v0 v1 v2 = ((Unsafe.Coerce.unsafeCoerce) ((((d7) ((Unsafe.Coerce.unsafeCoerce) (v0))) ((Unsafe.Coerce.unsafeCoerce) (v1))) ((Unsafe.Coerce.unsafeCoerce) (v2))))
null
https://raw.githubusercontent.com/jayrbolton/coursework/f0da276527d42a6751fb8d29c76de35ce358fe65/computability_and_formal_languages/project__/agda/MAlonzo/Relation/Binary/PropositionalEquality/TrustMe.hs
haskell
# LANGUAGE EmptyDataDecls , ExistentialQuantification , ScopedTypeVariables , NoMonomorphismRestriction #
module MAlonzo.Relation.Binary.PropositionalEquality.TrustMe where import qualified Unsafe.Coerce import qualified MAlonzo.Relation.Binary.Core import qualified MAlonzo.Relation.Binary.PropositionalEquality name7 = ("Relation.Binary.PropositionalEquality.TrustMe.primTrustMe") d7 = (\ v0 -> (\ v1 -> (\ v2 -> (MAlonzo.Relation.Binary.Core.C240)))) name11 = ("Relation.Binary.PropositionalEquality.TrustMe.trustMe") d11 v0 v1 v2 = ((Unsafe.Coerce.unsafeCoerce) ((((d7) ((Unsafe.Coerce.unsafeCoerce) (v0))) ((Unsafe.Coerce.unsafeCoerce) (v1))) ((Unsafe.Coerce.unsafeCoerce) (v2))))
93a34db7c672547a8558626d0a8bea28c5af2c805346381cdb2750d0d0b4696c
ChaosEternal/guile-scsh
rw.scm
;;; Basic read and write Copyright ( c ) 1993 by . See file COPYING . ;;; Note: read ops should check to see if their string args are mutable. (define-module (scsh rw) :use-module (ice-9 rw) :use-module (scsh errno) :use-module (scsh optional) :use-module (ice-9 optargs) :use-module (scsh let-optionals-aster) from ( ice-9 rw ) :export (bogus-substring-spec? read-string/partial read-string! read-string write-string)) (define (bogus-substring-spec? s start end) (or (< start 0) (< (string-length s) end) (< end start))) ;;; Best-effort/forward-progress reading ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define (read-string/partial len . maybe-fd/port) (let* ((s (make-string len)) (fd/port (:optional maybe-fd/port (current-input-port))) (nread (read-string!/partial s fd/port 0 len))) EOF ((= nread len) s) (else (substring s 0 nread))))) ;;; Persistent reading ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define (generic-read-string! s start end reader source) (if (bogus-substring-spec? s start end) (error "Bad substring indices" reader source s start end)) (let loop ((i start)) (if (>= i end) (- i start) (catch 'system-error (lambda () (let ((nread (reader s source i end))) EOF (let ((result (- i start))) (and (not (zero? result)) result)) (loop (+ i nread))))) (lambda args ;; Give info on partially-read data in error packet. (set-cdr! (list-ref args 4) s) (apply scm-error args)))))) (define (read-string! s . args) (let-optionals* args ((fd/port (current-input-port)) (start 0) (end (string-length s))) (generic-read-string! s start end read-string!/partial fd/port))) (define (read-string len . maybe-fd/port) (let* ((s (make-string len)) (fd/port (:optional maybe-fd/port (current-input-port))) (nread (read-string! s fd/port 0 len))) EOF ((= nread len) s) (else (substring s 0 nread))))) ;;; Persistent writing ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define (generic-write-string s start end writer target) (if (bogus-substring-spec? s start end) (error "Bad substring indices" writer s start end target)) (let loop ((i start)) (if (< i end) (catch 'system-error (lambda () (let ((nwritten (writer s target i end))) (loop (+ i nwritten)))) (lambda args (apply scm-error args)))))) (define (write-string s . args) (let-optionals* args ((fd/port (current-output-port)) (start 0) (end (string-length s))) (generic-write-string s start end uniform-array-write fd/port)))
null
https://raw.githubusercontent.com/ChaosEternal/guile-scsh/1a76e006e193a6a8c9f93d23bacb9e51a1ff6c4c/scsh/rw.scm
scheme
Basic read and write Note: read ops should check to see if their string args are mutable. Best-effort/forward-progress reading Persistent reading Give info on partially-read data in error packet. Persistent writing
Copyright ( c ) 1993 by . See file COPYING . (define-module (scsh rw) :use-module (ice-9 rw) :use-module (scsh errno) :use-module (scsh optional) :use-module (ice-9 optargs) :use-module (scsh let-optionals-aster) from ( ice-9 rw ) :export (bogus-substring-spec? read-string/partial read-string! read-string write-string)) (define (bogus-substring-spec? s start end) (or (< start 0) (< (string-length s) end) (< end start))) (define (read-string/partial len . maybe-fd/port) (let* ((s (make-string len)) (fd/port (:optional maybe-fd/port (current-input-port))) (nread (read-string!/partial s fd/port 0 len))) EOF ((= nread len) s) (else (substring s 0 nread))))) (define (generic-read-string! s start end reader source) (if (bogus-substring-spec? s start end) (error "Bad substring indices" reader source s start end)) (let loop ((i start)) (if (>= i end) (- i start) (catch 'system-error (lambda () (let ((nread (reader s source i end))) EOF (let ((result (- i start))) (and (not (zero? result)) result)) (loop (+ i nread))))) (lambda args (set-cdr! (list-ref args 4) s) (apply scm-error args)))))) (define (read-string! s . args) (let-optionals* args ((fd/port (current-input-port)) (start 0) (end (string-length s))) (generic-read-string! s start end read-string!/partial fd/port))) (define (read-string len . maybe-fd/port) (let* ((s (make-string len)) (fd/port (:optional maybe-fd/port (current-input-port))) (nread (read-string! s fd/port 0 len))) EOF ((= nread len) s) (else (substring s 0 nread))))) (define (generic-write-string s start end writer target) (if (bogus-substring-spec? s start end) (error "Bad substring indices" writer s start end target)) (let loop ((i start)) (if (< i end) (catch 'system-error (lambda () (let ((nwritten (writer s target i end))) (loop (+ i nwritten)))) (lambda args (apply scm-error args)))))) (define (write-string s . args) (let-optionals* args ((fd/port (current-output-port)) (start 0) (end (string-length s))) (generic-write-string s start end uniform-array-write fd/port)))
fe3de137742ee042fcdd3ffac214ab9bc526158b9d92d6b360b009017439b64a
kadena-io/pact
Runtime.hs
# LANGUAGE FlexibleInstances # # LANGUAGE RecordWildCards # {-# LANGUAGE RankNTypes #-} # LANGUAGE TemplateHaskell # # LANGUAGE GeneralizedNewtypeDeriving # {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE BangPatterns #-} # LANGUAGE ScopedTypeVariables # {-# LANGUAGE GADTs #-} # LANGUAGE DeriveGeneric # # LANGUAGE LambdaCase # -- | -- Module : Pact.Types.Runtime Copyright : ( C ) 2016 -- License : BSD-style (see the file LICENSE) Maintainer : < > -- -- 'Eval' monad and utilities. Exports Lang and Util , so this is the " default import " for most pact things . -- module Pact.Types.Runtime ( evalError,evalError', failTx,failTx', argsError,argsError', throwDbError,throwEither,throwEitherText,throwErr, PactId(..), PactEvent(..), eventName, eventParams, eventModule, eventModuleHash, RefStore(..),rsNatives, EvalEnv(..),eeRefStore,eeMsgSigs,eeMsgBody,eeMode,eeEntity,eePactStep,eePactDbVar,eeInRepl, eePactDb,eePurity,eeHash,eeGas, eeGasEnv,eeNamespacePolicy,eeSPVSupport,eePublicData,eeExecutionConfig, eeAdvice, eeWarnings, toPactId, Purity(..), RefState(..),rsLoaded,rsLoadedModules,rsNamespace,rsQualifiedDeps, EvalState(..),evalRefs,evalCallStack,evalPactExec, evalCapabilities,evalLogGas,evalEvents, Eval(..),runEval,runEval',catchesPactError, call,method, readRow,writeRow,keys,txids,createUserTable,getUserTableInfo,beginTx,commitTx,rollbackTx,getTxLog, KeyPredBuiltins(..),keyPredBuiltins, NamespacePolicy(..), permissiveNamespacePolicy, ExecutionConfig(..),ExecutionFlag(..),ecFlags,isExecutionFlagSet,flagRep,flagReps, mkExecutionConfig, ifExecutionFlagSet,ifExecutionFlagSet', whenExecutionFlagSet, unlessExecutionFlagSet, emitPactWarning, PactWarning(..), module Pact.Types.Lang, module Pact.Types.Util, module Pact.Types.Persistence, module Pact.Types.Gas, module Pact.Types.ChainMeta, module Pact.Types.PactError, liftIO, eAdvise ) where import Control.Arrow ((&&&)) import Control.Concurrent.MVar import Control.Lens hiding ((.=),DefName) import Control.Exception.Safe import Control.Monad.Reader import Control.Monad.State.Strict import Control.DeepSeq import Data.Aeson hiding (Object) import Data.Default import Data.IORef(IORef, modifyIORef') import qualified Data.HashMap.Strict as HM import qualified Data.Map.Strict as M import qualified Data.Set as S import Data.String import Data.Text (Text,pack) import Data.Set(Set) import GHC.Generics (Generic) import Pact.Types.Capability import Pact.Types.ChainMeta import Pact.Types.Continuation import Pact.Types.Gas import Pact.Types.Lang import Pact.Types.Orphans () import Pact.Types.PactError import Pact.Types.PactValue import Pact.Types.Advice import Pact.Types.Persistence import Pact.Types.Pretty import Pact.Types.SPV import Pact.Types.Util import Pact.Types.Namespace data KeyPredBuiltins = KeysAll|KeysAny|Keys2 deriving (Eq,Show,Enum,Bounded) instance AsString KeyPredBuiltins where asString KeysAll = "keys-all" asString KeysAny = "keys-any" asString Keys2 = "keys-2" keyPredBuiltins :: M.Map Name KeyPredBuiltins keyPredBuiltins = M.fromList $ map (Name . (`BareName` def) . asString &&& id) [minBound .. maxBound] -- | Storage for natives. data RefStore = RefStore { _rsNatives :: HM.HashMap Text Ref } deriving (Eq, Show) makeLenses ''RefStore instance Default RefStore where def = RefStore HM.empty -- | Indicates level of db access offered in current Eval monad. data Purity = -- | Read-only access to systables. PSysOnly | -- | Read-only access to systables and module tables. PReadOnly | -- | All database access allowed (normal). PImpure deriving (Eq,Show,Ord,Bounded,Enum) instance Default Purity where def = PImpure -- All warnings pact emits at runtime data PactWarning -- | Deprecated native, with help message = DeprecatedNative NativeDefName Text -- | Deprecated overload with help message | DeprecatedOverload NativeDefName Text deriving (Show, Eq, Ord, Generic) instance ToJSON PactWarning instance FromJSON PactWarning instance Pretty PactWarning where pretty = \case DeprecatedNative ndef msg -> "Warning: Using deprecated native" <+> pretty ndef <> ":" <+> pretty msg DeprecatedOverload ndef msg -> "Warning: using deprecated native overload for" <+> pretty ndef <> ":" <+> pretty msg -- | Execution flags specify behavior of the runtime environment, -- with an orientation towards some alteration of a default behavior. -- Thus, a flag should _not_ describe "normal behavior" (the default), -- but instead should enable some "unusual" option. data ExecutionFlag -- | Disable user module install = FlagDisableModuleInstall -- | Disable database history queries in transactional mode (local-only) | FlagDisableHistoryInTransactionalMode -- | Preserve runReadOnly failing inside of runSysOnly | FlagOldReadOnlyBehavior -- | Disable table module guard for read operations in local | FlagAllowReadInLocal -- | Preserve namespace module governance bug | FlagPreserveModuleNameBug -- | Preserve namespace module acquire gov bug | FlagPreserveNsModuleInstallBug -- | Disable emission of pact events | FlagDisablePactEvents -- | Preserve module implemented interface namespacing bug | FlagPreserveModuleIfacesBug | Preserve Show in reduce for Def , Native | FlagPreserveShowDefs -- | Disable Pact 4.0 features | FlagDisablePact40 -- | Enforce key formats. "Positive" polarity to not break legacy repl tests. | FlagEnforceKeyFormats -- | Disable Pact 4.2.0 db sorted key guarantees, and row persistence | FlagDisablePact420 -- | Disable memory limit check | FlagDisableInlineMemCheck -- | Disable new non-inlined modules | FlagDisablePact43 | Disable pact 4.3 features | FlagDisablePact431 -- | Disable Pact 4.4 features | FlagDisablePact44 | Disable new transcendental impls | FlagDisableNewTrans -- | Disable Pact 4.5 Features | FlagDisablePact45 -- | Disable Pact 4.6 Features | FlagDisablePact46 deriving (Eq,Ord,Show,Enum,Bounded) -- | Flag string representation flagRep :: ExecutionFlag -> Text flagRep = pack . drop 4 . show -- | Flag string representations flagReps :: M.Map Text ExecutionFlag flagReps = M.fromList $ map go [minBound .. maxBound] where go f = (flagRep f,f) instance Pretty ExecutionFlag where pretty = pretty . flagRep instance ToJSON ExecutionFlag where toJSON = String . flagRep instance FromJSON ExecutionFlag where parseJSON = withText "ExecutionFlag" $ \t -> case M.lookup t flagReps of Nothing -> fail "Invalid ExecutionFlag value" Just f -> return f -- | Execution configuration flags, where empty is the "default". newtype ExecutionConfig = ExecutionConfig { _ecFlags :: S.Set ExecutionFlag } deriving (Eq,Show,ToJSON,FromJSON) makeLenses ''ExecutionConfig instance Default ExecutionConfig where def = ExecutionConfig def instance Pretty ExecutionConfig where pretty = pretty . S.toList . _ecFlags mkExecutionConfig :: [ExecutionFlag] -> ExecutionConfig mkExecutionConfig = ExecutionConfig . S.fromList | Interpreter reader environment , parameterized over back - end MVar state type . data EvalEnv e = EvalEnv { -- | Environment references. _eeRefStore :: !RefStore -- | Verified keys from message. , _eeMsgSigs :: !(M.Map PublicKeyText (S.Set UserCapability)) -- | JSON body accompanying message. , _eeMsgBody :: !Value -- | Execution mode , _eeMode :: ExecutionMode -- | Entity governing private/encrypted 'pact' executions. , _eeEntity :: !(Maybe EntityName) -- | Step value for 'pact' executions. , _eePactStep :: !(Maybe PactStep) | Back - end state MVar . , _eePactDbVar :: MVar e -- | Back-end function record. , _eePactDb :: PactDb e -- | Pure indicator , _eePurity :: Purity -- | Transaction hash , _eeHash :: Hash -- | Gas Environment , _eeGasEnv :: GasEnv -- | Tallied gas , _eeGas :: IORef Gas -- | Namespace Policy , _eeNamespacePolicy :: NamespacePolicy | SPV backend , _eeSPVSupport :: SPVSupport -- | Env public data , _eePublicData :: PublicData -- | Execution configuration flags , _eeExecutionConfig :: ExecutionConfig -- | Advice bracketer , _eeAdvice :: !Advice -- | Are we in the repl? If not, ignore info , _eeInRepl :: Bool -- | Warnings ref , _eeWarnings :: IORef (Set PactWarning) } makeLenses ''EvalEnv -- | 'PactId' -> 'Hash' conversion toPactId :: Hash -> PactId toPactId = PactId . hashToText -- | Dynamic storage for loaded names and modules, and current namespace. data RefState = RefState { | Imported Module - local defs and natives . _rsLoaded :: HM.HashMap Text (Ref, Maybe (ModuleHash)) -- | Modules that were loaded, and flag if updated. , _rsLoadedModules :: HM.HashMap ModuleName (ModuleData Ref, Bool) -- | Current Namespace , _rsNamespace :: Maybe (Namespace (Term Name)) -- | Map of all fully qualified names in scope, including transitive dependencies. , _rsQualifiedDeps :: HM.HashMap FullyQualifiedName Ref } deriving (Eq,Show,Generic) makeLenses ''RefState instance NFData RefState instance Default RefState where def = RefState HM.empty HM.empty Nothing HM.empty data PactEvent = PactEvent { _eventName :: !Text , _eventParams :: ![PactValue] , _eventModule :: !ModuleName , _eventModuleHash :: !ModuleHash } deriving (Eq, Show, Generic) instance NFData PactEvent instance ToJSON PactEvent where toJSON = lensyToJSON 6 instance FromJSON PactEvent where parseJSON = lensyParseJSON 6 makeLenses ''PactEvent -- | Interpreter mutable state. data EvalState = EvalState { | New or imported modules and defs . _evalRefs :: !RefState -- | Current call stack. , _evalCallStack :: ![StackFrame] -- | Pact execution trace, if any , _evalPactExec :: !(Maybe PactExec) -- | Capability list , _evalCapabilities :: Capabilities -- | Tracks gas logs if enabled (i.e. Just) , _evalLogGas :: Maybe [(Text,Gas)] -- | Accumulate events , _evalEvents :: ![PactEvent] } deriving (Show, Generic) makeLenses ''EvalState instance NFData EvalState instance Default EvalState where def = EvalState def def def def def def | Interpreter monad , parameterized over back - end MVar state type . newtype Eval e a = Eval { unEval :: ReaderT (EvalEnv e) (StateT EvalState IO) a } deriving (Functor,Applicative,Monad,MonadState EvalState, MonadReader (EvalEnv e),MonadThrow,MonadCatch,MonadMask,MonadIO) -- | "Production" runEval throws exceptions, meaning the state can be lost, -- which is useful for reporting stack traces in the REPL. runEval :: EvalState -> EvalEnv e -> Eval e a -> IO (a,EvalState) runEval s env act = runStateT (runReaderT (unEval act) env) s # INLINE runEval # -- | "Dev" runEval' is the old version that always returns the state -- along with the Either. runEval' :: EvalState -> EvalEnv e -> Eval e a -> IO (Either PactError a,EvalState) runEval' s env act = runStateT (catchesPactError $ runReaderT (unEval act) env) s catchesPactError :: (MonadCatch m) => m a -> m (Either PactError a) catchesPactError action = catches (Right <$> action) [ Handler (\(e :: PactError) -> return $ Left e) ,Handler (\(e :: SomeException) -> return $ Left . PactError EvalError def def . viaShow $ e) ] isExecutionFlagSet :: ExecutionFlag -> Eval e Bool isExecutionFlagSet f = S.member f <$> view (eeExecutionConfig . ecFlags) ifExecutionFlagSet :: ExecutionFlag -> Eval e a -> Eval e a -> Eval e a ifExecutionFlagSet f onTrue onFalse = do b <- isExecutionFlagSet f if b then onTrue else onFalse ifExecutionFlagSet' :: ExecutionFlag -> a -> a -> Eval e a ifExecutionFlagSet' f onTrue onFalse = ifExecutionFlagSet f (return onTrue) (return onFalse) whenExecutionFlagSet :: ExecutionFlag -> Eval e a -> Eval e () whenExecutionFlagSet f onTrue = ifExecutionFlagSet f (void onTrue) (return ()) unlessExecutionFlagSet :: ExecutionFlag -> Eval e a -> Eval e () unlessExecutionFlagSet f onFalse = ifExecutionFlagSet f (return ()) (void onFalse) -- | Bracket interpreter action pushing and popping frame on call stack. call :: StackFrame -> Eval e (Gas,a) -> Eval e a call s act = do evalCallStack %= (s:) (_gas,r) <- act evalCallStack %= drop 1 return r # INLINE call # | Invoke a backend method , catching all exceptions as ' DbError ' method :: Info -> (PactDb e -> Method e a) -> Eval e a method i f = do EvalEnv {..} <- ask handleAny (throwErr DbError i . viaShow) (liftIO $ f _eePactDb _eePactDbVar) emitPactWarning :: PactWarning -> Eval e () emitPactWarning pw = view eeWarnings >>= \e -> liftIO (modifyIORef' e (S.insert pw)) -- -- Methods for invoking backend function-record function. -- -- | Invoke '_readRow' readRow :: (IsString k,FromJSON v) => Info -> Domain k v -> k -> Eval e (Maybe v) readRow i d k = method i $ \db -> _readRow db d k -- | Invoke '_writeRow' writeRow :: (AsString k,ToJSON v) => Info -> WriteType -> Domain k v -> k -> v -> Eval e () writeRow i w d k v = method i $ \db -> _writeRow db w d k v -- | Invoke '_keys' keys :: (AsString k,IsString k) => Info -> Domain k v -> Eval e [k] keys i t = method i $ \db -> _keys db t -- | Invoke '_txids' txids :: Info -> TableName -> TxId -> Eval e [TxId] txids i tn tid = method i $ \db -> _txids db tn tid -- | Invoke '_createUserTable' createUserTable :: Info -> TableName -> ModuleName -> Eval e () createUserTable i t m = method i $ \db -> _createUserTable db t m -- | Invoke _getUserTableInfo getUserTableInfo :: Info -> TableName -> Eval e ModuleName getUserTableInfo i t = method i $ \db -> _getUserTableInfo db t -- | Invoke _beginTx beginTx :: Info -> ExecutionMode -> Eval e (Maybe TxId) beginTx i t = method i $ \db -> _beginTx db t | Invoke _ commitTx commitTx :: Info -> Eval e [TxLog Value] commitTx i = method i $ \db -> _commitTx db -- | Invoke _rollbackTx rollbackTx :: Info -> Eval e () rollbackTx i = method i $ \db -> _rollbackTx db -- | Invoke _getTxLog getTxLog :: (IsString k,FromJSON v) => Info -> Domain k v -> TxId -> Eval e [TxLog v] getTxLog i d t = method i $ \db -> _getTxLog db d t # INLINE readRow # # INLINE writeRow # {-# INLINE createUserTable #-} # INLINE getUserTableInfo # # INLINE commitTx # # INLINE beginTx # {-# INLINE rollbackTx #-} {-# INLINE getTxLog #-} # INLINE keys # # INLINE txids # throwArgsError :: FunApp -> [Term Name] -> Text -> Eval e a throwArgsError FunApp {..} args s = throwErr ArgsError _faInfo $ pretty s <> ", received " <> bracketsSep (map pretty args) <> " for " <> prettyFunTypes _faTypes throwErr :: PactErrorType -> Info -> Doc -> Eval e a throwErr ctor i err = get >>= \s -> throwM (PactError ctor i (_evalCallStack s) err) evalError :: Info -> Doc -> Eval e a evalError i = throwErr EvalError i evalError' :: HasInfo i => i -> Doc -> Eval e a evalError' = evalError . getInfo failTx :: Info -> Doc -> Eval e a failTx i = throwErr TxFailure i failTx' :: HasInfo i => i -> Doc -> Eval e a failTx' = failTx . getInfo throwDbError :: MonadThrow m => Doc -> m a throwDbError = throwM . PactError DbError def def -- | Throw an error coming from an Except/Either context. throwEither :: (MonadThrow m,Exception e) => Either e a -> m a throwEither = either throwM return throwEitherText :: PactErrorType -> Info -> Doc -> Either Text a -> Eval e a throwEitherText typ i d = either (\e -> throwErr typ i (d <> ":" <> pretty e)) return argsError :: FunApp -> [Term Name] -> Eval e a argsError i as = throwArgsError i as "Invalid arguments" argsError' :: FunApp -> [Term Ref] -> Eval e a argsError' i as = throwArgsError i (map (toTerm.abbrev) as) "Invalid arguments" eAdvise :: Info -> AdviceContext r -> Eval e (r,a) -> Eval e a eAdvise i m a = view eeAdvice >>= \adv -> advise i adv m a
null
https://raw.githubusercontent.com/kadena-io/pact/6bf5477a6ee3c78faf606471894b3e986deefe3d/src/Pact/Types/Runtime.hs
haskell
# LANGUAGE RankNTypes # # LANGUAGE OverloadedStrings # # LANGUAGE BangPatterns # # LANGUAGE GADTs # | Module : Pact.Types.Runtime License : BSD-style (see the file LICENSE) 'Eval' monad and utilities. | Storage for natives. | Indicates level of db access offered in current Eval monad. | Read-only access to systables. | Read-only access to systables and module tables. | All database access allowed (normal). All warnings pact emits at runtime | Deprecated native, with help message | Deprecated overload with help message | Execution flags specify behavior of the runtime environment, with an orientation towards some alteration of a default behavior. Thus, a flag should _not_ describe "normal behavior" (the default), but instead should enable some "unusual" option. | Disable user module install | Disable database history queries in transactional mode (local-only) | Preserve runReadOnly failing inside of runSysOnly | Disable table module guard for read operations in local | Preserve namespace module governance bug | Preserve namespace module acquire gov bug | Disable emission of pact events | Preserve module implemented interface namespacing bug | Disable Pact 4.0 features | Enforce key formats. "Positive" polarity to not break legacy repl tests. | Disable Pact 4.2.0 db sorted key guarantees, and row persistence | Disable memory limit check | Disable new non-inlined modules | Disable Pact 4.4 features | Disable Pact 4.5 Features | Disable Pact 4.6 Features | Flag string representation | Flag string representations | Execution configuration flags, where empty is the "default". | Environment references. | Verified keys from message. | JSON body accompanying message. | Execution mode | Entity governing private/encrypted 'pact' executions. | Step value for 'pact' executions. | Back-end function record. | Pure indicator | Transaction hash | Gas Environment | Tallied gas | Namespace Policy | Env public data | Execution configuration flags | Advice bracketer | Are we in the repl? If not, ignore info | Warnings ref | 'PactId' -> 'Hash' conversion | Dynamic storage for loaded names and modules, and current namespace. | Modules that were loaded, and flag if updated. | Current Namespace | Map of all fully qualified names in scope, including transitive dependencies. | Interpreter mutable state. | Current call stack. | Pact execution trace, if any | Capability list | Tracks gas logs if enabled (i.e. Just) | Accumulate events | "Production" runEval throws exceptions, meaning the state can be lost, which is useful for reporting stack traces in the REPL. | "Dev" runEval' is the old version that always returns the state along with the Either. | Bracket interpreter action pushing and popping frame on call stack. Methods for invoking backend function-record function. | Invoke '_readRow' | Invoke '_writeRow' | Invoke '_keys' | Invoke '_txids' | Invoke '_createUserTable' | Invoke _getUserTableInfo | Invoke _beginTx | Invoke _rollbackTx | Invoke _getTxLog # INLINE createUserTable # # INLINE rollbackTx # # INLINE getTxLog # | Throw an error coming from an Except/Either context.
# LANGUAGE FlexibleInstances # # LANGUAGE RecordWildCards # # LANGUAGE TemplateHaskell # # LANGUAGE GeneralizedNewtypeDeriving # # LANGUAGE ScopedTypeVariables # # LANGUAGE DeriveGeneric # # LANGUAGE LambdaCase # Copyright : ( C ) 2016 Maintainer : < > Exports Lang and Util , so this is the " default import " for most pact things . module Pact.Types.Runtime ( evalError,evalError', failTx,failTx', argsError,argsError', throwDbError,throwEither,throwEitherText,throwErr, PactId(..), PactEvent(..), eventName, eventParams, eventModule, eventModuleHash, RefStore(..),rsNatives, EvalEnv(..),eeRefStore,eeMsgSigs,eeMsgBody,eeMode,eeEntity,eePactStep,eePactDbVar,eeInRepl, eePactDb,eePurity,eeHash,eeGas, eeGasEnv,eeNamespacePolicy,eeSPVSupport,eePublicData,eeExecutionConfig, eeAdvice, eeWarnings, toPactId, Purity(..), RefState(..),rsLoaded,rsLoadedModules,rsNamespace,rsQualifiedDeps, EvalState(..),evalRefs,evalCallStack,evalPactExec, evalCapabilities,evalLogGas,evalEvents, Eval(..),runEval,runEval',catchesPactError, call,method, readRow,writeRow,keys,txids,createUserTable,getUserTableInfo,beginTx,commitTx,rollbackTx,getTxLog, KeyPredBuiltins(..),keyPredBuiltins, NamespacePolicy(..), permissiveNamespacePolicy, ExecutionConfig(..),ExecutionFlag(..),ecFlags,isExecutionFlagSet,flagRep,flagReps, mkExecutionConfig, ifExecutionFlagSet,ifExecutionFlagSet', whenExecutionFlagSet, unlessExecutionFlagSet, emitPactWarning, PactWarning(..), module Pact.Types.Lang, module Pact.Types.Util, module Pact.Types.Persistence, module Pact.Types.Gas, module Pact.Types.ChainMeta, module Pact.Types.PactError, liftIO, eAdvise ) where import Control.Arrow ((&&&)) import Control.Concurrent.MVar import Control.Lens hiding ((.=),DefName) import Control.Exception.Safe import Control.Monad.Reader import Control.Monad.State.Strict import Control.DeepSeq import Data.Aeson hiding (Object) import Data.Default import Data.IORef(IORef, modifyIORef') import qualified Data.HashMap.Strict as HM import qualified Data.Map.Strict as M import qualified Data.Set as S import Data.String import Data.Text (Text,pack) import Data.Set(Set) import GHC.Generics (Generic) import Pact.Types.Capability import Pact.Types.ChainMeta import Pact.Types.Continuation import Pact.Types.Gas import Pact.Types.Lang import Pact.Types.Orphans () import Pact.Types.PactError import Pact.Types.PactValue import Pact.Types.Advice import Pact.Types.Persistence import Pact.Types.Pretty import Pact.Types.SPV import Pact.Types.Util import Pact.Types.Namespace data KeyPredBuiltins = KeysAll|KeysAny|Keys2 deriving (Eq,Show,Enum,Bounded) instance AsString KeyPredBuiltins where asString KeysAll = "keys-all" asString KeysAny = "keys-any" asString Keys2 = "keys-2" keyPredBuiltins :: M.Map Name KeyPredBuiltins keyPredBuiltins = M.fromList $ map (Name . (`BareName` def) . asString &&& id) [minBound .. maxBound] data RefStore = RefStore { _rsNatives :: HM.HashMap Text Ref } deriving (Eq, Show) makeLenses ''RefStore instance Default RefStore where def = RefStore HM.empty data Purity = PSysOnly | PReadOnly | PImpure deriving (Eq,Show,Ord,Bounded,Enum) instance Default Purity where def = PImpure data PactWarning = DeprecatedNative NativeDefName Text | DeprecatedOverload NativeDefName Text deriving (Show, Eq, Ord, Generic) instance ToJSON PactWarning instance FromJSON PactWarning instance Pretty PactWarning where pretty = \case DeprecatedNative ndef msg -> "Warning: Using deprecated native" <+> pretty ndef <> ":" <+> pretty msg DeprecatedOverload ndef msg -> "Warning: using deprecated native overload for" <+> pretty ndef <> ":" <+> pretty msg data ExecutionFlag = FlagDisableModuleInstall | FlagDisableHistoryInTransactionalMode | FlagOldReadOnlyBehavior | FlagAllowReadInLocal | FlagPreserveModuleNameBug | FlagPreserveNsModuleInstallBug | FlagDisablePactEvents | FlagPreserveModuleIfacesBug | Preserve Show in reduce for Def , Native | FlagPreserveShowDefs | FlagDisablePact40 | FlagEnforceKeyFormats | FlagDisablePact420 | FlagDisableInlineMemCheck | FlagDisablePact43 | Disable pact 4.3 features | FlagDisablePact431 | FlagDisablePact44 | Disable new transcendental impls | FlagDisableNewTrans | FlagDisablePact45 | FlagDisablePact46 deriving (Eq,Ord,Show,Enum,Bounded) flagRep :: ExecutionFlag -> Text flagRep = pack . drop 4 . show flagReps :: M.Map Text ExecutionFlag flagReps = M.fromList $ map go [minBound .. maxBound] where go f = (flagRep f,f) instance Pretty ExecutionFlag where pretty = pretty . flagRep instance ToJSON ExecutionFlag where toJSON = String . flagRep instance FromJSON ExecutionFlag where parseJSON = withText "ExecutionFlag" $ \t -> case M.lookup t flagReps of Nothing -> fail "Invalid ExecutionFlag value" Just f -> return f newtype ExecutionConfig = ExecutionConfig { _ecFlags :: S.Set ExecutionFlag } deriving (Eq,Show,ToJSON,FromJSON) makeLenses ''ExecutionConfig instance Default ExecutionConfig where def = ExecutionConfig def instance Pretty ExecutionConfig where pretty = pretty . S.toList . _ecFlags mkExecutionConfig :: [ExecutionFlag] -> ExecutionConfig mkExecutionConfig = ExecutionConfig . S.fromList | Interpreter reader environment , parameterized over back - end MVar state type . data EvalEnv e = EvalEnv { _eeRefStore :: !RefStore , _eeMsgSigs :: !(M.Map PublicKeyText (S.Set UserCapability)) , _eeMsgBody :: !Value , _eeMode :: ExecutionMode , _eeEntity :: !(Maybe EntityName) , _eePactStep :: !(Maybe PactStep) | Back - end state MVar . , _eePactDbVar :: MVar e , _eePactDb :: PactDb e , _eePurity :: Purity , _eeHash :: Hash , _eeGasEnv :: GasEnv , _eeGas :: IORef Gas , _eeNamespacePolicy :: NamespacePolicy | SPV backend , _eeSPVSupport :: SPVSupport , _eePublicData :: PublicData , _eeExecutionConfig :: ExecutionConfig , _eeAdvice :: !Advice , _eeInRepl :: Bool , _eeWarnings :: IORef (Set PactWarning) } makeLenses ''EvalEnv toPactId :: Hash -> PactId toPactId = PactId . hashToText data RefState = RefState { | Imported Module - local defs and natives . _rsLoaded :: HM.HashMap Text (Ref, Maybe (ModuleHash)) , _rsLoadedModules :: HM.HashMap ModuleName (ModuleData Ref, Bool) , _rsNamespace :: Maybe (Namespace (Term Name)) , _rsQualifiedDeps :: HM.HashMap FullyQualifiedName Ref } deriving (Eq,Show,Generic) makeLenses ''RefState instance NFData RefState instance Default RefState where def = RefState HM.empty HM.empty Nothing HM.empty data PactEvent = PactEvent { _eventName :: !Text , _eventParams :: ![PactValue] , _eventModule :: !ModuleName , _eventModuleHash :: !ModuleHash } deriving (Eq, Show, Generic) instance NFData PactEvent instance ToJSON PactEvent where toJSON = lensyToJSON 6 instance FromJSON PactEvent where parseJSON = lensyParseJSON 6 makeLenses ''PactEvent data EvalState = EvalState { | New or imported modules and defs . _evalRefs :: !RefState , _evalCallStack :: ![StackFrame] , _evalPactExec :: !(Maybe PactExec) , _evalCapabilities :: Capabilities , _evalLogGas :: Maybe [(Text,Gas)] , _evalEvents :: ![PactEvent] } deriving (Show, Generic) makeLenses ''EvalState instance NFData EvalState instance Default EvalState where def = EvalState def def def def def def | Interpreter monad , parameterized over back - end MVar state type . newtype Eval e a = Eval { unEval :: ReaderT (EvalEnv e) (StateT EvalState IO) a } deriving (Functor,Applicative,Monad,MonadState EvalState, MonadReader (EvalEnv e),MonadThrow,MonadCatch,MonadMask,MonadIO) runEval :: EvalState -> EvalEnv e -> Eval e a -> IO (a,EvalState) runEval s env act = runStateT (runReaderT (unEval act) env) s # INLINE runEval # runEval' :: EvalState -> EvalEnv e -> Eval e a -> IO (Either PactError a,EvalState) runEval' s env act = runStateT (catchesPactError $ runReaderT (unEval act) env) s catchesPactError :: (MonadCatch m) => m a -> m (Either PactError a) catchesPactError action = catches (Right <$> action) [ Handler (\(e :: PactError) -> return $ Left e) ,Handler (\(e :: SomeException) -> return $ Left . PactError EvalError def def . viaShow $ e) ] isExecutionFlagSet :: ExecutionFlag -> Eval e Bool isExecutionFlagSet f = S.member f <$> view (eeExecutionConfig . ecFlags) ifExecutionFlagSet :: ExecutionFlag -> Eval e a -> Eval e a -> Eval e a ifExecutionFlagSet f onTrue onFalse = do b <- isExecutionFlagSet f if b then onTrue else onFalse ifExecutionFlagSet' :: ExecutionFlag -> a -> a -> Eval e a ifExecutionFlagSet' f onTrue onFalse = ifExecutionFlagSet f (return onTrue) (return onFalse) whenExecutionFlagSet :: ExecutionFlag -> Eval e a -> Eval e () whenExecutionFlagSet f onTrue = ifExecutionFlagSet f (void onTrue) (return ()) unlessExecutionFlagSet :: ExecutionFlag -> Eval e a -> Eval e () unlessExecutionFlagSet f onFalse = ifExecutionFlagSet f (return ()) (void onFalse) call :: StackFrame -> Eval e (Gas,a) -> Eval e a call s act = do evalCallStack %= (s:) (_gas,r) <- act evalCallStack %= drop 1 return r # INLINE call # | Invoke a backend method , catching all exceptions as ' DbError ' method :: Info -> (PactDb e -> Method e a) -> Eval e a method i f = do EvalEnv {..} <- ask handleAny (throwErr DbError i . viaShow) (liftIO $ f _eePactDb _eePactDbVar) emitPactWarning :: PactWarning -> Eval e () emitPactWarning pw = view eeWarnings >>= \e -> liftIO (modifyIORef' e (S.insert pw)) readRow :: (IsString k,FromJSON v) => Info -> Domain k v -> k -> Eval e (Maybe v) readRow i d k = method i $ \db -> _readRow db d k writeRow :: (AsString k,ToJSON v) => Info -> WriteType -> Domain k v -> k -> v -> Eval e () writeRow i w d k v = method i $ \db -> _writeRow db w d k v keys :: (AsString k,IsString k) => Info -> Domain k v -> Eval e [k] keys i t = method i $ \db -> _keys db t txids :: Info -> TableName -> TxId -> Eval e [TxId] txids i tn tid = method i $ \db -> _txids db tn tid createUserTable :: Info -> TableName -> ModuleName -> Eval e () createUserTable i t m = method i $ \db -> _createUserTable db t m getUserTableInfo :: Info -> TableName -> Eval e ModuleName getUserTableInfo i t = method i $ \db -> _getUserTableInfo db t beginTx :: Info -> ExecutionMode -> Eval e (Maybe TxId) beginTx i t = method i $ \db -> _beginTx db t | Invoke _ commitTx commitTx :: Info -> Eval e [TxLog Value] commitTx i = method i $ \db -> _commitTx db rollbackTx :: Info -> Eval e () rollbackTx i = method i $ \db -> _rollbackTx db getTxLog :: (IsString k,FromJSON v) => Info -> Domain k v -> TxId -> Eval e [TxLog v] getTxLog i d t = method i $ \db -> _getTxLog db d t # INLINE readRow # # INLINE writeRow # # INLINE getUserTableInfo # # INLINE commitTx # # INLINE beginTx # # INLINE keys # # INLINE txids # throwArgsError :: FunApp -> [Term Name] -> Text -> Eval e a throwArgsError FunApp {..} args s = throwErr ArgsError _faInfo $ pretty s <> ", received " <> bracketsSep (map pretty args) <> " for " <> prettyFunTypes _faTypes throwErr :: PactErrorType -> Info -> Doc -> Eval e a throwErr ctor i err = get >>= \s -> throwM (PactError ctor i (_evalCallStack s) err) evalError :: Info -> Doc -> Eval e a evalError i = throwErr EvalError i evalError' :: HasInfo i => i -> Doc -> Eval e a evalError' = evalError . getInfo failTx :: Info -> Doc -> Eval e a failTx i = throwErr TxFailure i failTx' :: HasInfo i => i -> Doc -> Eval e a failTx' = failTx . getInfo throwDbError :: MonadThrow m => Doc -> m a throwDbError = throwM . PactError DbError def def throwEither :: (MonadThrow m,Exception e) => Either e a -> m a throwEither = either throwM return throwEitherText :: PactErrorType -> Info -> Doc -> Either Text a -> Eval e a throwEitherText typ i d = either (\e -> throwErr typ i (d <> ":" <> pretty e)) return argsError :: FunApp -> [Term Name] -> Eval e a argsError i as = throwArgsError i as "Invalid arguments" argsError' :: FunApp -> [Term Ref] -> Eval e a argsError' i as = throwArgsError i (map (toTerm.abbrev) as) "Invalid arguments" eAdvise :: Info -> AdviceContext r -> Eval e (r,a) -> Eval e a eAdvise i m a = view eeAdvice >>= \adv -> advise i adv m a
70369dfeb51e590532a19acb5a2c1f9762c286238440c7e57f77ff73ebd94d3b
AbstractMachinesLab/caramel
ast_helper.mli
(**************************************************************************) (* *) (* OCaml *) (* *) , LexiFi (* *) Copyright 2012 Institut National de Recherche en Informatique et (* en Automatique. *) (* *) (* All rights reserved. This file is distributed under the terms of *) the GNU Lesser General Public License version 2.1 , with the (* special exception on linking described in the file LICENSE. *) (* *) (**************************************************************************) * Helpers to produce Parsetree fragments open Asttypes open Docstrings open Parsetree type lid = Longident.t loc type str = string loc type loc = Location.t type attrs = attribute list val const_string : string -> constant * { 2 Default locations } val default_loc: loc ref (** Default value for all optional location arguments. *) val with_default_loc: loc -> (unit -> 'a) -> 'a (** Set the [default_loc] within the scope of the execution of the provided function. *) * { 2 Constants } module Const : sig val char : char -> constant val string : ?quotation_delimiter:string -> string -> constant val integer : ?suffix:char -> string -> constant val int : ?suffix:char -> int -> constant val int32 : ?suffix:char -> int32 -> constant val int64 : ?suffix:char -> int64 -> constant val nativeint : ?suffix:char -> nativeint -> constant val float : ?suffix:char -> string -> constant end * { 2 Core language } (** Type expressions *) module Typ : sig val mk: ?loc:loc -> ?attrs:attrs -> core_type_desc -> core_type val attr: core_type -> attribute -> core_type val any: ?loc:loc -> ?attrs:attrs -> unit -> core_type val var: ?loc:loc -> ?attrs:attrs -> string -> core_type val arrow: ?loc:loc -> ?attrs:attrs -> arg_label -> core_type -> core_type -> core_type val tuple: ?loc:loc -> ?attrs:attrs -> core_type list -> core_type val constr: ?loc:loc -> ?attrs:attrs -> lid -> core_type list -> core_type val object_: ?loc:loc -> ?attrs:attrs -> (str * attributes * core_type) list -> closed_flag -> core_type val class_: ?loc:loc -> ?attrs:attrs -> lid -> core_type list -> core_type val alias: ?loc:loc -> ?attrs:attrs -> core_type -> string -> core_type val variant: ?loc:loc -> ?attrs:attrs -> row_field list -> closed_flag -> label list option -> core_type val poly: ?loc:loc -> ?attrs:attrs -> str list -> core_type -> core_type val package: ?loc:loc -> ?attrs:attrs -> lid -> (lid * core_type) list -> core_type val extension: ?loc:loc -> ?attrs:attrs -> extension -> core_type val force_poly: core_type -> core_type val varify_constructors: str list -> core_type -> core_type * [ varify_constructors newtypes te ] is type expression [ te ] , of which any of nullary type constructor [ tc ] is replaced by type variable of the same name , if [ tc ] 's name appears in [ newtypes ] . Raise [ Syntaxerr . Variable_in_scope ] if any type variable inside [ te ] appears in [ newtypes ] . @since 4.05 any of nullary type constructor [tc] is replaced by type variable of the same name, if [tc]'s name appears in [newtypes]. Raise [Syntaxerr.Variable_in_scope] if any type variable inside [te] appears in [newtypes]. @since 4.05 *) end (** Patterns *) module Pat: sig val mk: ?loc:loc -> ?attrs:attrs -> pattern_desc -> pattern val attr:pattern -> attribute -> pattern val any: ?loc:loc -> ?attrs:attrs -> unit -> pattern val var: ?loc:loc -> ?attrs:attrs -> str -> pattern val alias: ?loc:loc -> ?attrs:attrs -> pattern -> str -> pattern val constant: ?loc:loc -> ?attrs:attrs -> constant -> pattern val interval: ?loc:loc -> ?attrs:attrs -> constant -> constant -> pattern val tuple: ?loc:loc -> ?attrs:attrs -> pattern list -> pattern val construct: ?loc:loc -> ?attrs:attrs -> lid -> pattern option -> pattern val variant: ?loc:loc -> ?attrs:attrs -> label -> pattern option -> pattern val record: ?loc:loc -> ?attrs:attrs -> (lid * pattern) list -> closed_flag -> pattern val array: ?loc:loc -> ?attrs:attrs -> pattern list -> pattern val or_: ?loc:loc -> ?attrs:attrs -> pattern -> pattern -> pattern val constraint_: ?loc:loc -> ?attrs:attrs -> pattern -> core_type -> pattern val type_: ?loc:loc -> ?attrs:attrs -> lid -> pattern val lazy_: ?loc:loc -> ?attrs:attrs -> pattern -> pattern val unpack: ?loc:loc -> ?attrs:attrs -> str -> pattern val open_: ?loc:loc -> ?attrs:attrs -> lid -> pattern -> pattern val exception_: ?loc:loc -> ?attrs:attrs -> pattern -> pattern val extension: ?loc:loc -> ?attrs:attrs -> extension -> pattern end (** Expressions *) module Exp: sig val mk: ?loc:loc -> ?attrs:attrs -> expression_desc -> expression val attr: expression -> attribute -> expression val ident: ?loc:loc -> ?attrs:attrs -> lid -> expression val constant: ?loc:loc -> ?attrs:attrs -> constant -> expression val let_: ?loc:loc -> ?attrs:attrs -> rec_flag -> value_binding list -> expression -> expression val fun_: ?loc:loc -> ?attrs:attrs -> arg_label -> expression option -> pattern -> expression -> expression val function_: ?loc:loc -> ?attrs:attrs -> case list -> expression val apply: ?loc:loc -> ?attrs:attrs -> expression -> (arg_label * expression) list -> expression val match_: ?loc:loc -> ?attrs:attrs -> expression -> case list -> expression val try_: ?loc:loc -> ?attrs:attrs -> expression -> case list -> expression val tuple: ?loc:loc -> ?attrs:attrs -> expression list -> expression val construct: ?loc:loc -> ?attrs:attrs -> lid -> expression option -> expression val variant: ?loc:loc -> ?attrs:attrs -> label -> expression option -> expression val record: ?loc:loc -> ?attrs:attrs -> (lid * expression) list -> expression option -> expression val field: ?loc:loc -> ?attrs:attrs -> expression -> lid -> expression val setfield: ?loc:loc -> ?attrs:attrs -> expression -> lid -> expression -> expression val array: ?loc:loc -> ?attrs:attrs -> expression list -> expression val ifthenelse: ?loc:loc -> ?attrs:attrs -> expression -> expression -> expression option -> expression val sequence: ?loc:loc -> ?attrs:attrs -> expression -> expression -> expression val while_: ?loc:loc -> ?attrs:attrs -> expression -> expression -> expression val for_: ?loc:loc -> ?attrs:attrs -> pattern -> expression -> expression -> direction_flag -> expression -> expression val coerce: ?loc:loc -> ?attrs:attrs -> expression -> core_type option -> core_type -> expression val constraint_: ?loc:loc -> ?attrs:attrs -> expression -> core_type -> expression val send: ?loc:loc -> ?attrs:attrs -> expression -> str -> expression val new_: ?loc:loc -> ?attrs:attrs -> lid -> expression val setinstvar: ?loc:loc -> ?attrs:attrs -> str -> expression -> expression val override: ?loc:loc -> ?attrs:attrs -> (str * expression) list -> expression val letmodule: ?loc:loc -> ?attrs:attrs -> str -> module_expr -> expression -> expression val letmodule_no_opt: ?loc:loc -> ?attrs:attrs -> label -> module_expr -> expression -> expression val letexception: ?loc:loc -> ?attrs:attrs -> extension_constructor -> expression -> expression val assert_: ?loc:loc -> ?attrs:attrs -> expression -> expression val lazy_: ?loc:loc -> ?attrs:attrs -> expression -> expression val poly: ?loc:loc -> ?attrs:attrs -> expression -> core_type option -> expression val object_: ?loc:loc -> ?attrs:attrs -> class_structure -> expression val newtype: ?loc:loc -> ?attrs:attrs -> str -> expression -> expression val pack: ?loc:loc -> ?attrs:attrs -> module_expr -> expression val open_: ?loc:loc -> ?attrs:attrs -> override_flag -> lid -> expression -> expression val extension: ?loc:loc -> ?attrs:attrs -> extension -> expression val unreachable: ?loc:loc -> ?attrs:attrs -> unit -> expression val case: pattern -> ?guard:expression -> expression -> case end (** Value declarations *) module Val: sig val mk: ?loc:loc -> ?attrs:attrs -> ?docs:docs -> ?prim:string list -> str -> core_type -> value_description end (** Type declarations *) module Type: sig val mk: ?loc:loc -> ?attrs:attrs -> ?docs:docs -> ?text:text -> ?params:(core_type * variance) list -> ?cstrs:(core_type * core_type * loc) list -> ?kind:type_kind -> ?priv:private_flag -> ?manifest:core_type -> str -> type_declaration val constructor: ?loc:loc -> ?attrs:attrs -> ?info:info -> ?args:constructor_arguments -> ?res:core_type -> str -> constructor_declaration val field: ?loc:loc -> ?attrs:attrs -> ?info:info -> ?mut:mutable_flag -> str -> core_type -> label_declaration end (** Type extensions *) module Te: sig val mk: ?attrs:attrs -> ?docs:docs -> ?params:(core_type * variance) list -> ?priv:private_flag -> lid -> extension_constructor list -> type_extension val constructor: ?loc:loc -> ?attrs:attrs -> ?docs:docs -> ?info:info -> str -> extension_constructor_kind -> extension_constructor val decl: ?loc:loc -> ?attrs:attrs -> ?docs:docs -> ?info:info -> ?args:constructor_arguments -> ?res:core_type -> str -> extension_constructor val rebind: ?loc:loc -> ?attrs:attrs -> ?docs:docs -> ?info:info -> str -> lid -> extension_constructor end * { 2 Module language } (** Module type expressions *) module Mty: sig val mk: ?loc:loc -> ?attrs:attrs -> module_type_desc -> module_type val attr: module_type -> attribute -> module_type val ident: ?loc:loc -> ?attrs:attrs -> lid -> module_type val alias: ?loc:loc -> ?attrs:attrs -> lid -> module_type val signature: ?loc:loc -> ?attrs:attrs -> signature -> module_type val functor_: ?loc:loc -> ?attrs:attrs -> str -> module_type option -> module_type -> module_type val with_: ?loc:loc -> ?attrs:attrs -> module_type -> with_constraint list -> module_type val typeof_: ?loc:loc -> ?attrs:attrs -> module_expr -> module_type val extension: ?loc:loc -> ?attrs:attrs -> extension -> module_type end (** Module expressions *) module Mod: sig val mk: ?loc:loc -> ?attrs:attrs -> module_expr_desc -> module_expr val attr: module_expr -> attribute -> module_expr val ident: ?loc:loc -> ?attrs:attrs -> lid -> module_expr val structure: ?loc:loc -> ?attrs:attrs -> structure -> module_expr val functor_: ?loc:loc -> ?attrs:attrs -> str -> module_type option -> module_expr -> module_expr val apply: ?loc:loc -> ?attrs:attrs -> module_expr -> module_expr -> module_expr val constraint_: ?loc:loc -> ?attrs:attrs -> module_expr -> module_type -> module_expr val unpack: ?loc:loc -> ?attrs:attrs -> expression -> module_expr val extension: ?loc:loc -> ?attrs:attrs -> extension -> module_expr end (** Signature items *) module Sig: sig val mk: ?loc:loc -> signature_item_desc -> signature_item val value: ?loc:loc -> value_description -> signature_item val type_: ?loc:loc -> rec_flag -> type_declaration list -> signature_item val type_extension: ?loc:loc -> type_extension -> signature_item val exception_: ?loc:loc -> extension_constructor -> signature_item val module_: ?loc:loc -> module_declaration -> signature_item val rec_module: ?loc:loc -> module_declaration list -> signature_item val modtype: ?loc:loc -> module_type_declaration -> signature_item val open_: ?loc:loc -> open_description -> signature_item val include_: ?loc:loc -> include_description -> signature_item val class_: ?loc:loc -> class_description list -> signature_item val class_type: ?loc:loc -> class_type_declaration list -> signature_item val extension: ?loc:loc -> ?attrs:attrs -> extension -> signature_item val attribute: ?loc:loc -> attribute -> signature_item val text: text -> signature_item list end (** Structure items *) module Str: sig val mk: ?loc:loc -> structure_item_desc -> structure_item val eval: ?loc:loc -> ?attrs:attributes -> expression -> structure_item val value: ?loc:loc -> rec_flag -> value_binding list -> structure_item val primitive: ?loc:loc -> value_description -> structure_item val type_: ?loc:loc -> rec_flag -> type_declaration list -> structure_item val type_extension: ?loc:loc -> type_extension -> structure_item val exception_: ?loc:loc -> extension_constructor -> structure_item val module_: ?loc:loc -> module_binding -> structure_item val rec_module: ?loc:loc -> module_binding list -> structure_item val modtype: ?loc:loc -> module_type_declaration -> structure_item val open_: ?loc:loc -> open_description -> structure_item val class_: ?loc:loc -> class_declaration list -> structure_item val class_type: ?loc:loc -> class_type_declaration list -> structure_item val include_: ?loc:loc -> include_declaration -> structure_item val extension: ?loc:loc -> ?attrs:attrs -> extension -> structure_item val attribute: ?loc:loc -> attribute -> structure_item val text: text -> structure_item list end (** Module declarations *) module Md: sig val mk: ?loc:loc -> ?attrs:attrs -> ?docs:docs -> ?text:text -> str -> module_type -> module_declaration end (** Module type declarations *) module Mtd: sig val mk: ?loc:loc -> ?attrs:attrs -> ?docs:docs -> ?text:text -> ?typ:module_type -> str -> module_type_declaration end (** Module bindings *) module Mb: sig val mk: ?loc:loc -> ?attrs:attrs -> ?docs:docs -> ?text:text -> str -> module_expr -> module_binding end (** Opens *) module Opn: sig val mk: ?loc: loc -> ?attrs:attrs -> ?docs:docs -> ?override:override_flag -> lid -> open_description end (** Includes *) module Incl: sig val mk: ?loc: loc -> ?attrs:attrs -> ?docs:docs -> 'a -> 'a include_infos end (** Value bindings *) module Vb: sig val mk: ?loc: loc -> ?attrs:attrs -> ?docs:docs -> ?text:text -> pattern -> expression -> value_binding end * { 2 Class language } (** Class type expressions *) module Cty: sig val mk: ?loc:loc -> ?attrs:attrs -> class_type_desc -> class_type val attr: class_type -> attribute -> class_type val constr: ?loc:loc -> ?attrs:attrs -> lid -> core_type list -> class_type val signature: ?loc:loc -> ?attrs:attrs -> class_signature -> class_type val arrow: ?loc:loc -> ?attrs:attrs -> arg_label -> core_type -> class_type -> class_type val extension: ?loc:loc -> ?attrs:attrs -> extension -> class_type end (** Class type fields *) module Ctf: sig val mk: ?loc:loc -> ?attrs:attrs -> ?docs:docs -> class_type_field_desc -> class_type_field val attr: class_type_field -> attribute -> class_type_field val inherit_: ?loc:loc -> ?attrs:attrs -> class_type -> class_type_field val val_: ?loc:loc -> ?attrs:attrs -> str -> mutable_flag -> virtual_flag -> core_type -> class_type_field val method_: ?loc:loc -> ?attrs:attrs -> str -> private_flag -> virtual_flag -> core_type -> class_type_field val constraint_: ?loc:loc -> ?attrs:attrs -> core_type -> core_type -> class_type_field val extension: ?loc:loc -> ?attrs:attrs -> extension -> class_type_field val attribute: ?loc:loc -> attribute -> class_type_field val text: text -> class_type_field list end (** Class expressions *) module Cl: sig val mk: ?loc:loc -> ?attrs:attrs -> class_expr_desc -> class_expr val attr: class_expr -> attribute -> class_expr val constr: ?loc:loc -> ?attrs:attrs -> lid -> core_type list -> class_expr val structure: ?loc:loc -> ?attrs:attrs -> class_structure -> class_expr val fun_: ?loc:loc -> ?attrs:attrs -> arg_label -> expression option -> pattern -> class_expr -> class_expr val apply: ?loc:loc -> ?attrs:attrs -> class_expr -> (arg_label * expression) list -> class_expr val let_: ?loc:loc -> ?attrs:attrs -> rec_flag -> value_binding list -> class_expr -> class_expr val constraint_: ?loc:loc -> ?attrs:attrs -> class_expr -> class_type -> class_expr val extension: ?loc:loc -> ?attrs:attrs -> extension -> class_expr end (** Class fields *) module Cf: sig val mk: ?loc:loc -> ?attrs:attrs -> ?docs:docs -> class_field_desc -> class_field val attr: class_field -> attribute -> class_field val inherit_: ?loc:loc -> ?attrs:attrs -> override_flag -> class_expr -> str option -> class_field val val_: ?loc:loc -> ?attrs:attrs -> str -> mutable_flag -> class_field_kind -> class_field val method_: ?loc:loc -> ?attrs:attrs -> str -> private_flag -> class_field_kind -> class_field val constraint_: ?loc:loc -> ?attrs:attrs -> core_type -> core_type -> class_field val initializer_: ?loc:loc -> ?attrs:attrs -> expression -> class_field val extension: ?loc:loc -> ?attrs:attrs -> extension -> class_field val attribute: ?loc:loc -> attribute -> class_field val text: text -> class_field list val virtual_: core_type -> class_field_kind val concrete: override_flag -> expression -> class_field_kind end (** Classes *) module Ci: sig val mk: ?loc:loc -> ?attrs:attrs -> ?docs:docs -> ?text:text -> ?virt:virtual_flag -> ?params:(core_type * variance) list -> str -> 'a -> 'a class_infos end (** Class signatures *) module Csig: sig val mk: core_type -> class_type_field list -> class_signature end (** Class structures *) module Cstr: sig val mk: pattern -> class_field list -> class_structure end * : refactored out of Parser type let_binding = { lb_pattern: pattern; lb_expression: expression; lb_attributes: attributes; lb_docs: docs Lazy.t; lb_text: text Lazy.t; lb_loc: Location.t; } type let_bindings = { lbs_bindings: let_binding list; lbs_rec: rec_flag; lbs_extension: string Asttypes.loc option; lbs_loc: Location.t } (* merlin specific *) val no_label : arg_label val extract_str_payload : payload -> (string * Location.t) option backported from 4.08 (** {1 Attributes} *) module Attr : sig val mk: ?loc:loc -> str -> payload -> attribute val as_tuple : attribute -> str * payload end
null
https://raw.githubusercontent.com/AbstractMachinesLab/caramel/7d4e505d6032e22a630d2e3bd7085b77d0efbb0c/vendor/ocaml-lsp-1.4.0/ocaml-lsp-server/vendor/merlin/src/ocaml/parsing/405/ast_helper.mli
ocaml
************************************************************************ OCaml en Automatique. All rights reserved. This file is distributed under the terms of special exception on linking described in the file LICENSE. ************************************************************************ * Default value for all optional location arguments. * Set the [default_loc] within the scope of the execution of the provided function. * Type expressions * Patterns * Expressions * Value declarations * Type declarations * Type extensions * Module type expressions * Module expressions * Signature items * Structure items * Module declarations * Module type declarations * Module bindings * Opens * Includes * Value bindings * Class type expressions * Class type fields * Class expressions * Class fields * Classes * Class signatures * Class structures merlin specific * {1 Attributes}
, LexiFi Copyright 2012 Institut National de Recherche en Informatique et the GNU Lesser General Public License version 2.1 , with the * Helpers to produce Parsetree fragments open Asttypes open Docstrings open Parsetree type lid = Longident.t loc type str = string loc type loc = Location.t type attrs = attribute list val const_string : string -> constant * { 2 Default locations } val default_loc: loc ref val with_default_loc: loc -> (unit -> 'a) -> 'a * { 2 Constants } module Const : sig val char : char -> constant val string : ?quotation_delimiter:string -> string -> constant val integer : ?suffix:char -> string -> constant val int : ?suffix:char -> int -> constant val int32 : ?suffix:char -> int32 -> constant val int64 : ?suffix:char -> int64 -> constant val nativeint : ?suffix:char -> nativeint -> constant val float : ?suffix:char -> string -> constant end * { 2 Core language } module Typ : sig val mk: ?loc:loc -> ?attrs:attrs -> core_type_desc -> core_type val attr: core_type -> attribute -> core_type val any: ?loc:loc -> ?attrs:attrs -> unit -> core_type val var: ?loc:loc -> ?attrs:attrs -> string -> core_type val arrow: ?loc:loc -> ?attrs:attrs -> arg_label -> core_type -> core_type -> core_type val tuple: ?loc:loc -> ?attrs:attrs -> core_type list -> core_type val constr: ?loc:loc -> ?attrs:attrs -> lid -> core_type list -> core_type val object_: ?loc:loc -> ?attrs:attrs -> (str * attributes * core_type) list -> closed_flag -> core_type val class_: ?loc:loc -> ?attrs:attrs -> lid -> core_type list -> core_type val alias: ?loc:loc -> ?attrs:attrs -> core_type -> string -> core_type val variant: ?loc:loc -> ?attrs:attrs -> row_field list -> closed_flag -> label list option -> core_type val poly: ?loc:loc -> ?attrs:attrs -> str list -> core_type -> core_type val package: ?loc:loc -> ?attrs:attrs -> lid -> (lid * core_type) list -> core_type val extension: ?loc:loc -> ?attrs:attrs -> extension -> core_type val force_poly: core_type -> core_type val varify_constructors: str list -> core_type -> core_type * [ varify_constructors newtypes te ] is type expression [ te ] , of which any of nullary type constructor [ tc ] is replaced by type variable of the same name , if [ tc ] 's name appears in [ newtypes ] . Raise [ Syntaxerr . Variable_in_scope ] if any type variable inside [ te ] appears in [ newtypes ] . @since 4.05 any of nullary type constructor [tc] is replaced by type variable of the same name, if [tc]'s name appears in [newtypes]. Raise [Syntaxerr.Variable_in_scope] if any type variable inside [te] appears in [newtypes]. @since 4.05 *) end module Pat: sig val mk: ?loc:loc -> ?attrs:attrs -> pattern_desc -> pattern val attr:pattern -> attribute -> pattern val any: ?loc:loc -> ?attrs:attrs -> unit -> pattern val var: ?loc:loc -> ?attrs:attrs -> str -> pattern val alias: ?loc:loc -> ?attrs:attrs -> pattern -> str -> pattern val constant: ?loc:loc -> ?attrs:attrs -> constant -> pattern val interval: ?loc:loc -> ?attrs:attrs -> constant -> constant -> pattern val tuple: ?loc:loc -> ?attrs:attrs -> pattern list -> pattern val construct: ?loc:loc -> ?attrs:attrs -> lid -> pattern option -> pattern val variant: ?loc:loc -> ?attrs:attrs -> label -> pattern option -> pattern val record: ?loc:loc -> ?attrs:attrs -> (lid * pattern) list -> closed_flag -> pattern val array: ?loc:loc -> ?attrs:attrs -> pattern list -> pattern val or_: ?loc:loc -> ?attrs:attrs -> pattern -> pattern -> pattern val constraint_: ?loc:loc -> ?attrs:attrs -> pattern -> core_type -> pattern val type_: ?loc:loc -> ?attrs:attrs -> lid -> pattern val lazy_: ?loc:loc -> ?attrs:attrs -> pattern -> pattern val unpack: ?loc:loc -> ?attrs:attrs -> str -> pattern val open_: ?loc:loc -> ?attrs:attrs -> lid -> pattern -> pattern val exception_: ?loc:loc -> ?attrs:attrs -> pattern -> pattern val extension: ?loc:loc -> ?attrs:attrs -> extension -> pattern end module Exp: sig val mk: ?loc:loc -> ?attrs:attrs -> expression_desc -> expression val attr: expression -> attribute -> expression val ident: ?loc:loc -> ?attrs:attrs -> lid -> expression val constant: ?loc:loc -> ?attrs:attrs -> constant -> expression val let_: ?loc:loc -> ?attrs:attrs -> rec_flag -> value_binding list -> expression -> expression val fun_: ?loc:loc -> ?attrs:attrs -> arg_label -> expression option -> pattern -> expression -> expression val function_: ?loc:loc -> ?attrs:attrs -> case list -> expression val apply: ?loc:loc -> ?attrs:attrs -> expression -> (arg_label * expression) list -> expression val match_: ?loc:loc -> ?attrs:attrs -> expression -> case list -> expression val try_: ?loc:loc -> ?attrs:attrs -> expression -> case list -> expression val tuple: ?loc:loc -> ?attrs:attrs -> expression list -> expression val construct: ?loc:loc -> ?attrs:attrs -> lid -> expression option -> expression val variant: ?loc:loc -> ?attrs:attrs -> label -> expression option -> expression val record: ?loc:loc -> ?attrs:attrs -> (lid * expression) list -> expression option -> expression val field: ?loc:loc -> ?attrs:attrs -> expression -> lid -> expression val setfield: ?loc:loc -> ?attrs:attrs -> expression -> lid -> expression -> expression val array: ?loc:loc -> ?attrs:attrs -> expression list -> expression val ifthenelse: ?loc:loc -> ?attrs:attrs -> expression -> expression -> expression option -> expression val sequence: ?loc:loc -> ?attrs:attrs -> expression -> expression -> expression val while_: ?loc:loc -> ?attrs:attrs -> expression -> expression -> expression val for_: ?loc:loc -> ?attrs:attrs -> pattern -> expression -> expression -> direction_flag -> expression -> expression val coerce: ?loc:loc -> ?attrs:attrs -> expression -> core_type option -> core_type -> expression val constraint_: ?loc:loc -> ?attrs:attrs -> expression -> core_type -> expression val send: ?loc:loc -> ?attrs:attrs -> expression -> str -> expression val new_: ?loc:loc -> ?attrs:attrs -> lid -> expression val setinstvar: ?loc:loc -> ?attrs:attrs -> str -> expression -> expression val override: ?loc:loc -> ?attrs:attrs -> (str * expression) list -> expression val letmodule: ?loc:loc -> ?attrs:attrs -> str -> module_expr -> expression -> expression val letmodule_no_opt: ?loc:loc -> ?attrs:attrs -> label -> module_expr -> expression -> expression val letexception: ?loc:loc -> ?attrs:attrs -> extension_constructor -> expression -> expression val assert_: ?loc:loc -> ?attrs:attrs -> expression -> expression val lazy_: ?loc:loc -> ?attrs:attrs -> expression -> expression val poly: ?loc:loc -> ?attrs:attrs -> expression -> core_type option -> expression val object_: ?loc:loc -> ?attrs:attrs -> class_structure -> expression val newtype: ?loc:loc -> ?attrs:attrs -> str -> expression -> expression val pack: ?loc:loc -> ?attrs:attrs -> module_expr -> expression val open_: ?loc:loc -> ?attrs:attrs -> override_flag -> lid -> expression -> expression val extension: ?loc:loc -> ?attrs:attrs -> extension -> expression val unreachable: ?loc:loc -> ?attrs:attrs -> unit -> expression val case: pattern -> ?guard:expression -> expression -> case end module Val: sig val mk: ?loc:loc -> ?attrs:attrs -> ?docs:docs -> ?prim:string list -> str -> core_type -> value_description end module Type: sig val mk: ?loc:loc -> ?attrs:attrs -> ?docs:docs -> ?text:text -> ?params:(core_type * variance) list -> ?cstrs:(core_type * core_type * loc) list -> ?kind:type_kind -> ?priv:private_flag -> ?manifest:core_type -> str -> type_declaration val constructor: ?loc:loc -> ?attrs:attrs -> ?info:info -> ?args:constructor_arguments -> ?res:core_type -> str -> constructor_declaration val field: ?loc:loc -> ?attrs:attrs -> ?info:info -> ?mut:mutable_flag -> str -> core_type -> label_declaration end module Te: sig val mk: ?attrs:attrs -> ?docs:docs -> ?params:(core_type * variance) list -> ?priv:private_flag -> lid -> extension_constructor list -> type_extension val constructor: ?loc:loc -> ?attrs:attrs -> ?docs:docs -> ?info:info -> str -> extension_constructor_kind -> extension_constructor val decl: ?loc:loc -> ?attrs:attrs -> ?docs:docs -> ?info:info -> ?args:constructor_arguments -> ?res:core_type -> str -> extension_constructor val rebind: ?loc:loc -> ?attrs:attrs -> ?docs:docs -> ?info:info -> str -> lid -> extension_constructor end * { 2 Module language } module Mty: sig val mk: ?loc:loc -> ?attrs:attrs -> module_type_desc -> module_type val attr: module_type -> attribute -> module_type val ident: ?loc:loc -> ?attrs:attrs -> lid -> module_type val alias: ?loc:loc -> ?attrs:attrs -> lid -> module_type val signature: ?loc:loc -> ?attrs:attrs -> signature -> module_type val functor_: ?loc:loc -> ?attrs:attrs -> str -> module_type option -> module_type -> module_type val with_: ?loc:loc -> ?attrs:attrs -> module_type -> with_constraint list -> module_type val typeof_: ?loc:loc -> ?attrs:attrs -> module_expr -> module_type val extension: ?loc:loc -> ?attrs:attrs -> extension -> module_type end module Mod: sig val mk: ?loc:loc -> ?attrs:attrs -> module_expr_desc -> module_expr val attr: module_expr -> attribute -> module_expr val ident: ?loc:loc -> ?attrs:attrs -> lid -> module_expr val structure: ?loc:loc -> ?attrs:attrs -> structure -> module_expr val functor_: ?loc:loc -> ?attrs:attrs -> str -> module_type option -> module_expr -> module_expr val apply: ?loc:loc -> ?attrs:attrs -> module_expr -> module_expr -> module_expr val constraint_: ?loc:loc -> ?attrs:attrs -> module_expr -> module_type -> module_expr val unpack: ?loc:loc -> ?attrs:attrs -> expression -> module_expr val extension: ?loc:loc -> ?attrs:attrs -> extension -> module_expr end module Sig: sig val mk: ?loc:loc -> signature_item_desc -> signature_item val value: ?loc:loc -> value_description -> signature_item val type_: ?loc:loc -> rec_flag -> type_declaration list -> signature_item val type_extension: ?loc:loc -> type_extension -> signature_item val exception_: ?loc:loc -> extension_constructor -> signature_item val module_: ?loc:loc -> module_declaration -> signature_item val rec_module: ?loc:loc -> module_declaration list -> signature_item val modtype: ?loc:loc -> module_type_declaration -> signature_item val open_: ?loc:loc -> open_description -> signature_item val include_: ?loc:loc -> include_description -> signature_item val class_: ?loc:loc -> class_description list -> signature_item val class_type: ?loc:loc -> class_type_declaration list -> signature_item val extension: ?loc:loc -> ?attrs:attrs -> extension -> signature_item val attribute: ?loc:loc -> attribute -> signature_item val text: text -> signature_item list end module Str: sig val mk: ?loc:loc -> structure_item_desc -> structure_item val eval: ?loc:loc -> ?attrs:attributes -> expression -> structure_item val value: ?loc:loc -> rec_flag -> value_binding list -> structure_item val primitive: ?loc:loc -> value_description -> structure_item val type_: ?loc:loc -> rec_flag -> type_declaration list -> structure_item val type_extension: ?loc:loc -> type_extension -> structure_item val exception_: ?loc:loc -> extension_constructor -> structure_item val module_: ?loc:loc -> module_binding -> structure_item val rec_module: ?loc:loc -> module_binding list -> structure_item val modtype: ?loc:loc -> module_type_declaration -> structure_item val open_: ?loc:loc -> open_description -> structure_item val class_: ?loc:loc -> class_declaration list -> structure_item val class_type: ?loc:loc -> class_type_declaration list -> structure_item val include_: ?loc:loc -> include_declaration -> structure_item val extension: ?loc:loc -> ?attrs:attrs -> extension -> structure_item val attribute: ?loc:loc -> attribute -> structure_item val text: text -> structure_item list end module Md: sig val mk: ?loc:loc -> ?attrs:attrs -> ?docs:docs -> ?text:text -> str -> module_type -> module_declaration end module Mtd: sig val mk: ?loc:loc -> ?attrs:attrs -> ?docs:docs -> ?text:text -> ?typ:module_type -> str -> module_type_declaration end module Mb: sig val mk: ?loc:loc -> ?attrs:attrs -> ?docs:docs -> ?text:text -> str -> module_expr -> module_binding end module Opn: sig val mk: ?loc: loc -> ?attrs:attrs -> ?docs:docs -> ?override:override_flag -> lid -> open_description end module Incl: sig val mk: ?loc: loc -> ?attrs:attrs -> ?docs:docs -> 'a -> 'a include_infos end module Vb: sig val mk: ?loc: loc -> ?attrs:attrs -> ?docs:docs -> ?text:text -> pattern -> expression -> value_binding end * { 2 Class language } module Cty: sig val mk: ?loc:loc -> ?attrs:attrs -> class_type_desc -> class_type val attr: class_type -> attribute -> class_type val constr: ?loc:loc -> ?attrs:attrs -> lid -> core_type list -> class_type val signature: ?loc:loc -> ?attrs:attrs -> class_signature -> class_type val arrow: ?loc:loc -> ?attrs:attrs -> arg_label -> core_type -> class_type -> class_type val extension: ?loc:loc -> ?attrs:attrs -> extension -> class_type end module Ctf: sig val mk: ?loc:loc -> ?attrs:attrs -> ?docs:docs -> class_type_field_desc -> class_type_field val attr: class_type_field -> attribute -> class_type_field val inherit_: ?loc:loc -> ?attrs:attrs -> class_type -> class_type_field val val_: ?loc:loc -> ?attrs:attrs -> str -> mutable_flag -> virtual_flag -> core_type -> class_type_field val method_: ?loc:loc -> ?attrs:attrs -> str -> private_flag -> virtual_flag -> core_type -> class_type_field val constraint_: ?loc:loc -> ?attrs:attrs -> core_type -> core_type -> class_type_field val extension: ?loc:loc -> ?attrs:attrs -> extension -> class_type_field val attribute: ?loc:loc -> attribute -> class_type_field val text: text -> class_type_field list end module Cl: sig val mk: ?loc:loc -> ?attrs:attrs -> class_expr_desc -> class_expr val attr: class_expr -> attribute -> class_expr val constr: ?loc:loc -> ?attrs:attrs -> lid -> core_type list -> class_expr val structure: ?loc:loc -> ?attrs:attrs -> class_structure -> class_expr val fun_: ?loc:loc -> ?attrs:attrs -> arg_label -> expression option -> pattern -> class_expr -> class_expr val apply: ?loc:loc -> ?attrs:attrs -> class_expr -> (arg_label * expression) list -> class_expr val let_: ?loc:loc -> ?attrs:attrs -> rec_flag -> value_binding list -> class_expr -> class_expr val constraint_: ?loc:loc -> ?attrs:attrs -> class_expr -> class_type -> class_expr val extension: ?loc:loc -> ?attrs:attrs -> extension -> class_expr end module Cf: sig val mk: ?loc:loc -> ?attrs:attrs -> ?docs:docs -> class_field_desc -> class_field val attr: class_field -> attribute -> class_field val inherit_: ?loc:loc -> ?attrs:attrs -> override_flag -> class_expr -> str option -> class_field val val_: ?loc:loc -> ?attrs:attrs -> str -> mutable_flag -> class_field_kind -> class_field val method_: ?loc:loc -> ?attrs:attrs -> str -> private_flag -> class_field_kind -> class_field val constraint_: ?loc:loc -> ?attrs:attrs -> core_type -> core_type -> class_field val initializer_: ?loc:loc -> ?attrs:attrs -> expression -> class_field val extension: ?loc:loc -> ?attrs:attrs -> extension -> class_field val attribute: ?loc:loc -> attribute -> class_field val text: text -> class_field list val virtual_: core_type -> class_field_kind val concrete: override_flag -> expression -> class_field_kind end module Ci: sig val mk: ?loc:loc -> ?attrs:attrs -> ?docs:docs -> ?text:text -> ?virt:virtual_flag -> ?params:(core_type * variance) list -> str -> 'a -> 'a class_infos end module Csig: sig val mk: core_type -> class_type_field list -> class_signature end module Cstr: sig val mk: pattern -> class_field list -> class_structure end * : refactored out of Parser type let_binding = { lb_pattern: pattern; lb_expression: expression; lb_attributes: attributes; lb_docs: docs Lazy.t; lb_text: text Lazy.t; lb_loc: Location.t; } type let_bindings = { lbs_bindings: let_binding list; lbs_rec: rec_flag; lbs_extension: string Asttypes.loc option; lbs_loc: Location.t } val no_label : arg_label val extract_str_payload : payload -> (string * Location.t) option backported from 4.08 module Attr : sig val mk: ?loc:loc -> str -> payload -> attribute val as_tuple : attribute -> str * payload end
20cb3dad1fb97821d0d334e2c2ee177fbf35c343190f6c0eabfa37eab9a915f2
msgpack/msgpack-haskell
Result.hs
{-# LANGUAGE CPP #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveFoldable #-} {-# LANGUAGE DeriveFunctor #-} # LANGUAGE DeriveGeneric # {-# LANGUAGE DeriveTraversable #-} -- | -- Module : Data.MessagePack.Integer Copyright : © 2019 -- License : BSD3 -- Type representing MessagePack integers -- -- @since 1.1.0.0 module Data.MessagePack.Result ( Result(..) ) where import Compat.Prelude import qualified Control.Monad.Fail as Fail | The result of decoding from MessagePack -- -- @since 1.1.0.0 data Result a = Error String | Success a deriving (Eq, Show, Functor, Typeable, Generic, Foldable, Traversable) instance NFData a => NFData (Result a) where rnf (Error e) = rnf e rnf (Success a) = rnf a instance Applicative Result where pure = Success (<*>) = ap instance Monad Result where Success a >>= m = m a Error err >>= _ = Error err #if !MIN_VERSION_base(4,13,0) return = pure fail = Fail.fail #endif instance Fail.MonadFail Result where fail = Error instance Alternative Result where empty = fail "Alternative(empty)" a@(Success _) <|> _ = a _ <|> b = b
null
https://raw.githubusercontent.com/msgpack/msgpack-haskell/f52a5d2db620a7be70810eca648fd152141f8b14/msgpack/src/Data/MessagePack/Result.hs
haskell
# LANGUAGE CPP # # LANGUAGE DeriveDataTypeable # # LANGUAGE DeriveFoldable # # LANGUAGE DeriveFunctor # # LANGUAGE DeriveTraversable # | Module : Data.MessagePack.Integer License : BSD3 @since 1.1.0.0 @since 1.1.0.0
# LANGUAGE DeriveGeneric # Copyright : © 2019 Type representing MessagePack integers module Data.MessagePack.Result ( Result(..) ) where import Compat.Prelude import qualified Control.Monad.Fail as Fail | The result of decoding from MessagePack data Result a = Error String | Success a deriving (Eq, Show, Functor, Typeable, Generic, Foldable, Traversable) instance NFData a => NFData (Result a) where rnf (Error e) = rnf e rnf (Success a) = rnf a instance Applicative Result where pure = Success (<*>) = ap instance Monad Result where Success a >>= m = m a Error err >>= _ = Error err #if !MIN_VERSION_base(4,13,0) return = pure fail = Fail.fail #endif instance Fail.MonadFail Result where fail = Error instance Alternative Result where empty = fail "Alternative(empty)" a@(Success _) <|> _ = a _ <|> b = b
48dc6cedfb4c947bbf4692ba66969e6c1bbe136181d0c91c8855ef5373f6c1b4
vikram/lisplibraries
forms.lisp
;;;; -*- lisp -*- (in-package :it.bese.ucw-user) ;;;; the file uploading example and test (defclass file-upload-example (widget-component template-component) ((file :accessor file-upload-example.file :initform "")) (:metaclass standard-component-class) (:default-initargs :template-name "ucw/examples/upload.tal") (:documentation "Form for uploading a file.")) (defaction upload ((form file-upload-example)) (call 'file-upload-viewer :file-data (file-upload-example.file form))) (defclass file-upload-viewer (widget-component) ((file-data :initarg :file-data)) (:metaclass standard-component-class) (:documentation "View a file uplodaed by the file-upload-example component.")) (defmethod render ((viewer file-upload-viewer)) (<:table (<:tr (<:th "Header") (<:th "Value")) (dolist* ((name . value) (mime-part-headers (slot-value viewer 'file-data))) (<:tr (<:td (<:as-html name)) (<:td (<:as-html value))))) (<:p "Body:") (<:pre (<:as-html (mime-part-body (slot-value viewer 'file-data)))) (<ucw:a :action (ok viewer) "Ok.")) ;;;; web form example (defcomponent example-form (simple-form) ((string-input :accessor string-input :initform (make-instance 'string-field :input-size 18 :validators (list (make-instance 'length-validator :min-length 4 :max-length 18)))) (password-input :accessor password-input :initform (make-instance 'password-field :input-size 12)) (number-input :accessor number-input :initform (make-instance 'number-field :input-size 4)) (limited-number-input :accessor limited-number-input :initform (make-instance 'number-field :input-size 4 :validators (list (make-instance 'number-range-validator :min-value 13/3 :max-value 7.92)))) (integer-input :accessor integer-input :initform (make-instance 'integer-field :input-size 4 :validators (list (make-instance 'not-empty-validator)))) (textarea-input :accessor textarea-input :initform (make-instance 'textarea-field :rows 2)) (date-input :accessor date-input :initform (make-instance 'dmy-date-field)) (submit-button :accessor submit-button :initform (make-instance 'submit-button)) (messages :accessor messages :initform '()))) (defmethod shared-initialize :after ((form example-form) slot-names &rest initargs) (declare (ignore slot-names initargs)) (push (make-instance 'string=-validator :other-field (string-input form)) (validators (password-input form)))) (defaction refresh-component :after ((form example-form)) (setf (messages form) '()) (flet ((push-message-unless-valid (field name) (multiple-value-bind (validp failed-validators) (validp field) (unless validp (push (format nil "~A failed~{ ~A~} check~P." name (mapcar (compose #'class-name #'class-of) failed-validators) (length failed-validators)) (messages form)))))) (push-message-unless-valid (string-input form) "First string field") (push-message-unless-valid (password-input form) "Password field") (push-message-unless-valid (number-input form) "First number field") (push-message-unless-valid (limited-number-input form) "Second number field (range)") (push-message-unless-valid (integer-input form) "First integer field") (push-message-unless-valid (textarea-input form) "Second string field") (setf (messages form) (nreverse (messages form))))) (defmethod render ((form example-form)) (when (messages form) (<:ul (dolist (message (messages form)) (<:li (<:b (<:as-html message)))))) (<:table (<:tr (<:th "Label") (<:th (<:&nbsp)) (<:th "Constraints")) (<:tr (<:td "String") (<:td (render (string-input form))) (<:td "Must be between 4 and 18 characters.")) (<:tr (<:td "Password") (<:td (render (password-input form))) (<:td "Must be equal to the string field above.")) (<:tr (<:td "Number") (<:td (render (number-input form))) (<:td "Any number (try fractions!)")) (<:tr (<:td "Number in a range") (<:td (render (limited-number-input form))) (<:td "Must be between 13/3 and 7.92.")) (<:tr (<:td "Integer") (<:td (render (integer-input form))) (<:td "Required field.")) (<:tr (<:td "Another sting") (<:td (render (textarea-input form))) (<:td "No constraints.")) (<:tr (<:td "A date") (<:td (render (date-input form)) "(dd/mm/yyyy)") (<:td "No constraints.")) (<:tr (<:td :colspan 3 :align "center" (render (submit-button form)))))) ;;;; using the web form example to create a dynamic form (defcomponent dynamic-form (simple-form) ((select-field :accessor select-field :initform (make-instance 'select-field :data-set (list 'string-field 'textarea-field 'integer-field))) (fields :accessor fields :initform '()))) (defaction add-field ((f dynamic-form)) (when (value (select-field f)) (push (make-instance (value (select-field f))) (fields f)))) (defaction delete-field ((f dynamic-form) field) (setf (fields f) (delete field (fields f)))) (defmethod render ((form dynamic-form)) (<:table (<:tr (<:td "Add new field of type") (<:td :colspan 2 (render (select-field form))) (<:td (<ucw:submit :action (add-field form) :value "Add"))) (dolist* (field (fields form)) (<:tr (<:td (<:as-html (class-name (class-of field))) ":") (<:td (render field)) (<:td (inspect-anchor form (value field))) (<:td (<ucw:input :type "submit" :action (delete-field form field) :value "Delete")))) (<:tr (<:td :colspan 4 (<ucw:submit :action (refresh-component form)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Copyright ( c ) 2003 - 2005 ;;; All rights reserved. ;;; ;;; Redistribution and use in source and binary forms, with or without ;;; modification, are permitted provided that the following conditions are ;;; met: ;;; ;;; - Redistributions of source code must retain the above copyright ;;; notice, this list of conditions and the following disclaimer. ;;; ;;; - Redistributions in binary form must reproduce the above copyright ;;; notice, this list of conditions and the following disclaimer in the ;;; documentation and/or other materials provided with the distribution. ;;; - Neither the name of , nor , 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 OWNER OR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ; LOSS OF USE , ;;; DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT ;;; (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ;;; OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
null
https://raw.githubusercontent.com/vikram/lisplibraries/105e3ef2d165275eb78f36f5090c9e2cdd0754dd/site/ucw-boxset/ucw_dev/examples/forms.lisp
lisp
-*- lisp -*- the file uploading example and test web form example using the web form example to create a dynamic form 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. of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT LOSS OF USE , DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
(in-package :it.bese.ucw-user) (defclass file-upload-example (widget-component template-component) ((file :accessor file-upload-example.file :initform "")) (:metaclass standard-component-class) (:default-initargs :template-name "ucw/examples/upload.tal") (:documentation "Form for uploading a file.")) (defaction upload ((form file-upload-example)) (call 'file-upload-viewer :file-data (file-upload-example.file form))) (defclass file-upload-viewer (widget-component) ((file-data :initarg :file-data)) (:metaclass standard-component-class) (:documentation "View a file uplodaed by the file-upload-example component.")) (defmethod render ((viewer file-upload-viewer)) (<:table (<:tr (<:th "Header") (<:th "Value")) (dolist* ((name . value) (mime-part-headers (slot-value viewer 'file-data))) (<:tr (<:td (<:as-html name)) (<:td (<:as-html value))))) (<:p "Body:") (<:pre (<:as-html (mime-part-body (slot-value viewer 'file-data)))) (<ucw:a :action (ok viewer) "Ok.")) (defcomponent example-form (simple-form) ((string-input :accessor string-input :initform (make-instance 'string-field :input-size 18 :validators (list (make-instance 'length-validator :min-length 4 :max-length 18)))) (password-input :accessor password-input :initform (make-instance 'password-field :input-size 12)) (number-input :accessor number-input :initform (make-instance 'number-field :input-size 4)) (limited-number-input :accessor limited-number-input :initform (make-instance 'number-field :input-size 4 :validators (list (make-instance 'number-range-validator :min-value 13/3 :max-value 7.92)))) (integer-input :accessor integer-input :initform (make-instance 'integer-field :input-size 4 :validators (list (make-instance 'not-empty-validator)))) (textarea-input :accessor textarea-input :initform (make-instance 'textarea-field :rows 2)) (date-input :accessor date-input :initform (make-instance 'dmy-date-field)) (submit-button :accessor submit-button :initform (make-instance 'submit-button)) (messages :accessor messages :initform '()))) (defmethod shared-initialize :after ((form example-form) slot-names &rest initargs) (declare (ignore slot-names initargs)) (push (make-instance 'string=-validator :other-field (string-input form)) (validators (password-input form)))) (defaction refresh-component :after ((form example-form)) (setf (messages form) '()) (flet ((push-message-unless-valid (field name) (multiple-value-bind (validp failed-validators) (validp field) (unless validp (push (format nil "~A failed~{ ~A~} check~P." name (mapcar (compose #'class-name #'class-of) failed-validators) (length failed-validators)) (messages form)))))) (push-message-unless-valid (string-input form) "First string field") (push-message-unless-valid (password-input form) "Password field") (push-message-unless-valid (number-input form) "First number field") (push-message-unless-valid (limited-number-input form) "Second number field (range)") (push-message-unless-valid (integer-input form) "First integer field") (push-message-unless-valid (textarea-input form) "Second string field") (setf (messages form) (nreverse (messages form))))) (defmethod render ((form example-form)) (when (messages form) (<:ul (dolist (message (messages form)) (<:li (<:b (<:as-html message)))))) (<:table (<:tr (<:th "Label") (<:th (<:&nbsp)) (<:th "Constraints")) (<:tr (<:td "String") (<:td (render (string-input form))) (<:td "Must be between 4 and 18 characters.")) (<:tr (<:td "Password") (<:td (render (password-input form))) (<:td "Must be equal to the string field above.")) (<:tr (<:td "Number") (<:td (render (number-input form))) (<:td "Any number (try fractions!)")) (<:tr (<:td "Number in a range") (<:td (render (limited-number-input form))) (<:td "Must be between 13/3 and 7.92.")) (<:tr (<:td "Integer") (<:td (render (integer-input form))) (<:td "Required field.")) (<:tr (<:td "Another sting") (<:td (render (textarea-input form))) (<:td "No constraints.")) (<:tr (<:td "A date") (<:td (render (date-input form)) "(dd/mm/yyyy)") (<:td "No constraints.")) (<:tr (<:td :colspan 3 :align "center" (render (submit-button form)))))) (defcomponent dynamic-form (simple-form) ((select-field :accessor select-field :initform (make-instance 'select-field :data-set (list 'string-field 'textarea-field 'integer-field))) (fields :accessor fields :initform '()))) (defaction add-field ((f dynamic-form)) (when (value (select-field f)) (push (make-instance (value (select-field f))) (fields f)))) (defaction delete-field ((f dynamic-form) field) (setf (fields f) (delete field (fields f)))) (defmethod render ((form dynamic-form)) (<:table (<:tr (<:td "Add new field of type") (<:td :colspan 2 (render (select-field form))) (<:td (<ucw:submit :action (add-field form) :value "Add"))) (dolist* (field (fields form)) (<:tr (<:td (<:as-html (class-name (class-of field))) ":") (<:td (render field)) (<:td (inspect-anchor form (value field))) (<:td (<ucw:input :type "submit" :action (delete-field form field) :value "Delete")))) (<:tr (<:td :colspan 4 (<ucw:submit :action (refresh-component form)))))) Copyright ( c ) 2003 - 2005 - Neither the name of , nor , nor the names " AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT OWNER OR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT
c69dbd63744fd0a9b49bcda0254f1d56d9bb9c420be1948170c3d7f55fc817c3
REPROSEC/dolev-yao-star
Lib_RawIntTypes.ml
open Prims let (u8_from_UInt8 : FStar_UInt8.t -> FStar_UInt8.t) = fun x -> x let (u16_from_UInt16 : FStar_UInt16.t -> FStar_UInt16.t) = fun x -> x let (u32_from_UInt32 : FStar_UInt32.t -> FStar_UInt32.t) = fun x -> x let (u64_from_UInt64 : FStar_UInt64.t -> FStar_UInt64.t) = fun x -> x let (u128_from_UInt128 : FStar_UInt128.t -> FStar_UInt128.t) = fun x -> x let (size_from_UInt32 : FStar_UInt32.t -> FStar_UInt32.t) = fun x -> x let (u8_to_UInt8 : FStar_UInt8.t -> FStar_UInt8.t) = fun x -> x let (u16_to_UInt16 : FStar_UInt16.t -> FStar_UInt16.t) = fun x -> x let (u32_to_UInt32 : FStar_UInt32.t -> FStar_UInt32.t) = fun x -> x let (u64_to_UInt64 : FStar_UInt64.t -> FStar_UInt64.t) = fun x -> x let (u128_to_UInt128 : FStar_UInt128.t -> FStar_UInt128.t) = fun x -> x let (size_to_UInt32 : FStar_UInt32.t -> FStar_UInt32.t) = fun x -> x let (uint_to_nat : Lib_IntTypes.inttype -> Lib_IntTypes.secrecy_level -> Obj.t -> Prims.nat) = fun t -> fun l -> fun x -> Lib_IntTypes.v t l x
null
https://raw.githubusercontent.com/REPROSEC/dolev-yao-star/d97a8dd4d07f2322437f186e4db6a1f4d5ee9230/concrete/hacl-star-snapshot/ml/Lib_RawIntTypes.ml
ocaml
open Prims let (u8_from_UInt8 : FStar_UInt8.t -> FStar_UInt8.t) = fun x -> x let (u16_from_UInt16 : FStar_UInt16.t -> FStar_UInt16.t) = fun x -> x let (u32_from_UInt32 : FStar_UInt32.t -> FStar_UInt32.t) = fun x -> x let (u64_from_UInt64 : FStar_UInt64.t -> FStar_UInt64.t) = fun x -> x let (u128_from_UInt128 : FStar_UInt128.t -> FStar_UInt128.t) = fun x -> x let (size_from_UInt32 : FStar_UInt32.t -> FStar_UInt32.t) = fun x -> x let (u8_to_UInt8 : FStar_UInt8.t -> FStar_UInt8.t) = fun x -> x let (u16_to_UInt16 : FStar_UInt16.t -> FStar_UInt16.t) = fun x -> x let (u32_to_UInt32 : FStar_UInt32.t -> FStar_UInt32.t) = fun x -> x let (u64_to_UInt64 : FStar_UInt64.t -> FStar_UInt64.t) = fun x -> x let (u128_to_UInt128 : FStar_UInt128.t -> FStar_UInt128.t) = fun x -> x let (size_to_UInt32 : FStar_UInt32.t -> FStar_UInt32.t) = fun x -> x let (uint_to_nat : Lib_IntTypes.inttype -> Lib_IntTypes.secrecy_level -> Obj.t -> Prims.nat) = fun t -> fun l -> fun x -> Lib_IntTypes.v t l x
f0829dd74eb0f13d35629fcbf61ef05c1f1f9c8530425e6a429eb237223706cb
soegaard/metapict
linear-equations.rkt
#lang racket (require "../def.rkt") (module+ test (require rackunit "../def.rkt")) ; A linear expression is represented as an expr struct. The field coefs contains a hash table that maps variables to numbers ( ) . The " variable " 1 is mapped to the constant term . (struct expr (coefs) #:transparent) ; Example: (module+ test (def 2x+y=7 (expr #hash((x . 2) (y . 1) (1 . -7)))) (def 4x+2y=14 (expr #hash((x . 4) (y . 2) (1 . -14)))) (def 6x+3y=21 (expr #hash((x . 6) (y . 3) (1 . -21)))) (def 2x+2y=9 (expr #hash((x . 2) (y . 2) (1 . -9)))) (def x (expr #hash((x . 1) (1 . 0)))) (def y (expr #hash((y . 1) (1 . 0)))) (def one (expr #hash((1 . 1))))) (define (variable? v) (symbol? v)) (define (variable-or-1? v) (or (variable? v) (equal? v 1))) ; expr-hash-ref : expr-hash variable -> number ; return the coeffecient of the variable v (define (expr-hash-ref h v) (unless (variable-or-1? v) (error 'expr-hash-ref (~a "variable or 1 expected, got " v))) (hash-ref h v 0)) ; ref : (or expr expr-hash) variable -> number (define (ref e-or-h v) (match e-or-h [(expr h) (expr-hash-ref h v)] [(? hash? h) (expr-hash-ref h v)] [_ (error 'ref "expr or hash expected")])) (module+ test (check-equal? (ref 2x+y=7 'x) 2) (check-equal? (ref 2x+y=7 'y) 1) (check-equal? (ref 2x+y=7 '1) -7) (check-equal? (ref 2x+y=7 'z) 0) (check-equal? (ref #hash((x . 2)) 'x) 2)) ; constant-term : expr -> number ; return the constant term of the expression (define (constant-term e) (ref e 1)) (module+ test (check-equal? (constant-term 2x+y=7) -7) (check-equal? (constant-term x) 0)) ; variables-in-equation : expr -> (setof variable) ; return set of the variables in the expression (define (variables-in-expr e) (defm (expr h) e) (set-remove (list->set (hash-keys h)) 1)) (module+ test (check-equal? (variables-in-expr 2x+y=7) (set 'x 'y))) ; variables-in-exprs : exprs -> (setof variable) ; return set of all variables used in the expressions (define (variables-in-exprs es) (apply set-union (map variables-in-expr es))) (module+ test (check-equal? (variables-in-exprs (list 2x+y=7 x y)) (set 'x 'y))) ; expr= : expr expr -> boolean ; do the exprs represent the same mathematical expression? (define (expr= e1 e2) (defm (expr h) e1) (defm (expr k) e2) (and (= (hash-count h) (hash-count k)) (for/and ([(v c) (in-hash h)]) (= c (hash-ref k v))))) ; expr* : number expr -> expr ; multiply all coeffecients in the expression e with k (define (expr* k e) (defm (expr h) e) (match k [0 zero-expr] [_ (expr (for/hash ([(v c) (in-hash h)]) (values v (* k c))))])) (module+ test (check-true (expr= (expr* 3 2x+y=7) 6x+3y=21))) ; expr+ : expr expr -> expr ; return an expr representing the sum of e1 and e2 (define (expr+ e1 e2) (defm (expr h) e1) (defm (expr k) e2) (def vs (append (hash-keys h) (hash-keys k))) (expr (for/hash ([v (in-list vs)] #:unless (= (+ (ref h v) (ref k v)) 0)) (values v (+ (ref h v) (ref k v)))))) (module+ test (check-true (expr= (expr+ 2x+y=7 2x+y=7) 4x+2y=14))) ; expr-lincomb : number expr number expr -> expr ; compute the linear combination a*e1+b*e2 (define (expr-lincomb a e1 b e2) (expr+ (expr* a e1) (expr* b e2))) (module+ test (check-true (expr= (expr-lincomb 2 x 1 (expr-lincomb 1 y -7 one)) 2x+y=7))) ; expr~ : expr -> expr ; negate the expression e (define (expr~ e) (defm (expr h) e) (expr (for/hash ([(v c) h]) (values v (- c))))) (module+ test (check-true (expr= (expr~ 2x+y=7) (expr* -1 2x+y=7)))) ; known A table in which the keys are known variables and the values are expressions ; giving the values of those variables in terms of inputs and unknowns. ; value initially contains only inputs; the value of an input x is x. (def known (make-parameter #hash())) (define (register-known v c) (def k (known)) (when (hash-has-key? k v) (error 'register-known (~a "The variable " v " is already known."))) (known (hash-set k v c))) (module+ test (parameterize ([known #hash()]) (register-known 'x 42) (check-equal? (ref (known) 'x) 42)) (check-equal? (ref (known) 'x) 0)) ; fill-in-knowns : expr -> expr ; eliminate the known variables from the expr e (define (fill-in-knowns e) (defm (expr h) e) (def k (known)) (define (known? v) (hash-has-key? k v)) (def var-part (for/list ([(v c) h] #:unless (or (equal? v 1) (known? v))) (cons v c))) (def const-part (+ (constant-term e) (for/sum ([(v c) h] #:when (and (known? v) (not (equal? v 1)))) (* c (ref k v))))) (expr (make-hash `((1 . ,const-part) ,@var-part)))) (module+ test (parameterize ([known #hash((x . 2))]) (expr= (fill-in-knowns 2x+y=7) (expr #hash((y . 1) (1 . -7)))))) fill - in - one - known : expr variable number - > expr ; substitute n for v in e (define (fill-in-one-known e v n) (defm (expr h) e) (def c (ref h v)) (def t (ref h 1)) (expr (hash-set (hash-remove h v) 1 (+ t (* c n))))) (module+ test (check-true (expr= (fill-in-one-known 2x+y=7 'x 3) (expr #hash((y . 1) (1 . -1)))))) non - constant - variables : expr - > ( listof variable ) ; return list of variables (define (non-constant-variables e) (defm (expr h) e) (for/list ([(v c) h] #:unless (equal? v 1)) v)) (module+ test (check-equal? (sort (non-constant-variables 2x+y=7) variable<) '(x y))) A trivial equation is an equation with one non - constant variable . ; trivial? : expr -> boolean ; is e a trivial expression? (define (trivial? e) (= 1 (length (non-constant-variables e)))) (module+ test (def 2x=7 (expr #hash((x . 2) (1 . -7)))) (check-true (trivial? 2x=7)) (check-false (trivial? 2x+y=7))) ; solve-trivial : expr -> (values variable number) (define (solve-trivial e) (unless (trivial? e) (error 'solve-trivial (~a "trivial expr expected, got" e))) (defm (expr h) e) (def t (constant-term e)) (def v (first (non-constant-variables e))) (def c (ref e v)) (when (= c 0) (error 'solve-trivial (~a "coeffecient to " v "is zero"))) (values v (/ (- t) c))) (module+ test (let () (defv (x v) (solve-trivial 2x=7)) (check-equal? (list x v) '(x 7/2)))) zeroes A list of expressions that are known to be zero . ; It is computed initially by subtracting the right-hand sides of the ; equations from the left-hand sides. (def zeroes (make-parameter (list))) (define (find-expr-with-max-coef v es) (argmax (λ(e) (ref e v)) es)) (define (reduce r v e) assume to v in r is 1 (expr-lincomb 1 e (- (ref e v)) r)) (define (row-reduce exprs) (def vars (variables-in-exprs exprs)) (for/fold ([used '()] [remaining exprs]) ([v (in-set vars)] #:break (empty? remaining)) (def em (find-expr-with-max-coef v remaining)) (let ([remaining (remove em remaining eq?)]) (def e (expr* (/ 1 (ref em v)) em)) (def (reduce/e expr) (reduce e v expr)) (values (cons e (map reduce/e used)) (map reduce/e remaining))))) (module+ test (defv (done todo) (row-reduce (list 2x+y=7 2x+2y=9))) (displayln (list done todo))) solve : ( expr ) ( hash ( var . number ) ) - > ? ; Inputs are known variables ; inputs: The set of input variables. #;(define (solve equations inputs) pending A temporary list , holding zero - valued expressions from which no variable ; can be eliminated. These pending expressions are returned to zeroes at ; the end of each step of the solving algorithm. ; constraints A list of constraints that must be satisfied if the equations are to ; have a solution. They come from equations in which all variables are ; known. The list is initially empty. ; invariants i ) No variable in zeroes , pending , or constraints is dependent . ; Note: i) => dependent vars are in value ; ii) No variable appearing in an expression in value is dependent. ; Note: Before putting expressions in value, eliminate the dependent variables iii ) If all the variables on one side of a balance are known , then ; all the variables on the other side of that balance are known. Note : Balances not in use in MetaPost / Font iv ) Values in zeroes , pending , constraints , and value are all represented as sums of ; linear terms. ; Note: No problem! (define (solve-loop known zeroes pending) (match zeroes [(? empty?) (match pending [(? empty?) (make-all-dependent-variables-known) (build-and-return-solution)] [_ (error 'solve-loop "underdetermined")])] [(list* z zs) (cond [(is-there-v-in-z-that-can-be-eliminated) (eliminate-v-from-z) ...] [(has-unknown-variable? z) (solve-loop known zs (cons z pending))] [else ???])])) (solve-loop (known) (zeroes) '())) #;(define (input->equation i) (expr (make-hash (match (ref inputs i) [0 (list (cons i 1))] [k (list (cons i 1) (cons 1 (- k)))])))) #;(solve-loop (map input->equation inputs) ; value equations ; zeroes '()) ; pending ; (declare a) (= = ( * 2 a ) 3 ) (= = ( + ( * 2 a ) b ) 21 ) ; (value-of a) ;;; ;;; Printing ;;; (define (variable< s t) (match* (s t) [((? number? x) (? number? y)) (< x y)] [((? number? x) (? symbol? y)) #f] [((? symbol? x) (? number? y)) #t] [((? symbol? x) (? symbol? y)) (string<? (symbol->string x) (symbol->string y))])) (module+ test (check-true (variable< 'a 'b)) (check-true (variable< 'a 2)) (check-true (variable< 2 3)) (check-false (variable< 2 'a))) ; expr->string : expr -> string (define (expr->string e) (defm (expr h) e) (def vcs (for/list ([(v c) (in-hash h)] #:unless (= c 0)) (list v c))) (def s (string-join (for/list ([vc (in-list (sort vcs variable< #:key first))]) (defm (list v c) vc) (~a (match c [(? negative?) (~a "(" c ")")] [1 (match v [1 1] [_ ""])] [_ c]) (match v [1 ""] [_ v]))) "+")) (match s ["" "0"] [_ s])) (module+ test (check-equal? (expr->string (expr (make-hash '((x . 2) (y . 2) (1 . 3))))) "2x+2y+3") (check-equal? (expr->string (expr (make-hash '((x . 2) (y . -2) (1 . 3))))) "2x+(-2)y+3")) (define (display-expr e) (display (expr->string e))) (def zero-expr (expr (make-hash '((1 . 0))))) (module+ test (check-equal? (expr->string zero-expr) "0")) 2x+ y= 7 2x+3y=11 (expr->string eq1) (expr->string (expr~ eq1)) (expr->string (expr~ (expr~ eq1))) (expr= eq1 eq1) (expr->string (expr* 2 eq1)) (expr->string (expr+ eq1 eq1)) (expr->string (expr+ eq1 (expr~ eq1)))
null
https://raw.githubusercontent.com/soegaard/metapict/47ae265f73cbb92ff3e7bdd61e49f4af17597fdf/metapict/todo/linear-equations.rkt
racket
A linear expression is represented as an expr struct. Example: expr-hash-ref : expr-hash variable -> number return the coeffecient of the variable v ref : (or expr expr-hash) variable -> number constant-term : expr -> number return the constant term of the expression variables-in-equation : expr -> (setof variable) return set of the variables in the expression variables-in-exprs : exprs -> (setof variable) return set of all variables used in the expressions expr= : expr expr -> boolean do the exprs represent the same mathematical expression? expr* : number expr -> expr multiply all coeffecients in the expression e with k expr+ : expr expr -> expr return an expr representing the sum of e1 and e2 expr-lincomb : number expr number expr -> expr compute the linear combination a*e1+b*e2 expr~ : expr -> expr negate the expression e known A table in which the keys are known variables and the values are expressions giving the values of those variables in terms of inputs and unknowns. value initially contains only inputs; the value of an input x is x. fill-in-knowns : expr -> expr eliminate the known variables from the expr e substitute n for v in e return list of variables trivial? : expr -> boolean is e a trivial expression? solve-trivial : expr -> (values variable number) It is computed initially by subtracting the right-hand sides of the equations from the left-hand sides. Inputs are known variables inputs: The set of input variables. (define (solve equations inputs) can be eliminated. These pending expressions are returned to zeroes at the end of each step of the solving algorithm. constraints A list of constraints that must be satisfied if the equations are to have a solution. They come from equations in which all variables are known. The list is initially empty. invariants Note: i) => dependent vars are in value ii) No variable appearing in an expression in value is dependent. Note: Before putting expressions in value, eliminate the dependent variables all the variables on the other side of that balance are known. linear terms. Note: No problem! (define (input->equation i) (solve-loop (map input->equation inputs) ; value zeroes pending (declare a) (value-of a) Printing expr->string : expr -> string
#lang racket (require "../def.rkt") (module+ test (require rackunit "../def.rkt")) The field coefs contains a hash table that maps variables to numbers ( ) . The " variable " 1 is mapped to the constant term . (struct expr (coefs) #:transparent) (module+ test (def 2x+y=7 (expr #hash((x . 2) (y . 1) (1 . -7)))) (def 4x+2y=14 (expr #hash((x . 4) (y . 2) (1 . -14)))) (def 6x+3y=21 (expr #hash((x . 6) (y . 3) (1 . -21)))) (def 2x+2y=9 (expr #hash((x . 2) (y . 2) (1 . -9)))) (def x (expr #hash((x . 1) (1 . 0)))) (def y (expr #hash((y . 1) (1 . 0)))) (def one (expr #hash((1 . 1))))) (define (variable? v) (symbol? v)) (define (variable-or-1? v) (or (variable? v) (equal? v 1))) (define (expr-hash-ref h v) (unless (variable-or-1? v) (error 'expr-hash-ref (~a "variable or 1 expected, got " v))) (hash-ref h v 0)) (define (ref e-or-h v) (match e-or-h [(expr h) (expr-hash-ref h v)] [(? hash? h) (expr-hash-ref h v)] [_ (error 'ref "expr or hash expected")])) (module+ test (check-equal? (ref 2x+y=7 'x) 2) (check-equal? (ref 2x+y=7 'y) 1) (check-equal? (ref 2x+y=7 '1) -7) (check-equal? (ref 2x+y=7 'z) 0) (check-equal? (ref #hash((x . 2)) 'x) 2)) (define (constant-term e) (ref e 1)) (module+ test (check-equal? (constant-term 2x+y=7) -7) (check-equal? (constant-term x) 0)) (define (variables-in-expr e) (defm (expr h) e) (set-remove (list->set (hash-keys h)) 1)) (module+ test (check-equal? (variables-in-expr 2x+y=7) (set 'x 'y))) (define (variables-in-exprs es) (apply set-union (map variables-in-expr es))) (module+ test (check-equal? (variables-in-exprs (list 2x+y=7 x y)) (set 'x 'y))) (define (expr= e1 e2) (defm (expr h) e1) (defm (expr k) e2) (and (= (hash-count h) (hash-count k)) (for/and ([(v c) (in-hash h)]) (= c (hash-ref k v))))) (define (expr* k e) (defm (expr h) e) (match k [0 zero-expr] [_ (expr (for/hash ([(v c) (in-hash h)]) (values v (* k c))))])) (module+ test (check-true (expr= (expr* 3 2x+y=7) 6x+3y=21))) (define (expr+ e1 e2) (defm (expr h) e1) (defm (expr k) e2) (def vs (append (hash-keys h) (hash-keys k))) (expr (for/hash ([v (in-list vs)] #:unless (= (+ (ref h v) (ref k v)) 0)) (values v (+ (ref h v) (ref k v)))))) (module+ test (check-true (expr= (expr+ 2x+y=7 2x+y=7) 4x+2y=14))) (define (expr-lincomb a e1 b e2) (expr+ (expr* a e1) (expr* b e2))) (module+ test (check-true (expr= (expr-lincomb 2 x 1 (expr-lincomb 1 y -7 one)) 2x+y=7))) (define (expr~ e) (defm (expr h) e) (expr (for/hash ([(v c) h]) (values v (- c))))) (module+ test (check-true (expr= (expr~ 2x+y=7) (expr* -1 2x+y=7)))) (def known (make-parameter #hash())) (define (register-known v c) (def k (known)) (when (hash-has-key? k v) (error 'register-known (~a "The variable " v " is already known."))) (known (hash-set k v c))) (module+ test (parameterize ([known #hash()]) (register-known 'x 42) (check-equal? (ref (known) 'x) 42)) (check-equal? (ref (known) 'x) 0)) (define (fill-in-knowns e) (defm (expr h) e) (def k (known)) (define (known? v) (hash-has-key? k v)) (def var-part (for/list ([(v c) h] #:unless (or (equal? v 1) (known? v))) (cons v c))) (def const-part (+ (constant-term e) (for/sum ([(v c) h] #:when (and (known? v) (not (equal? v 1)))) (* c (ref k v))))) (expr (make-hash `((1 . ,const-part) ,@var-part)))) (module+ test (parameterize ([known #hash((x . 2))]) (expr= (fill-in-knowns 2x+y=7) (expr #hash((y . 1) (1 . -7)))))) fill - in - one - known : expr variable number - > expr (define (fill-in-one-known e v n) (defm (expr h) e) (def c (ref h v)) (def t (ref h 1)) (expr (hash-set (hash-remove h v) 1 (+ t (* c n))))) (module+ test (check-true (expr= (fill-in-one-known 2x+y=7 'x 3) (expr #hash((y . 1) (1 . -1)))))) non - constant - variables : expr - > ( listof variable ) (define (non-constant-variables e) (defm (expr h) e) (for/list ([(v c) h] #:unless (equal? v 1)) v)) (module+ test (check-equal? (sort (non-constant-variables 2x+y=7) variable<) '(x y))) A trivial equation is an equation with one non - constant variable . (define (trivial? e) (= 1 (length (non-constant-variables e)))) (module+ test (def 2x=7 (expr #hash((x . 2) (1 . -7)))) (check-true (trivial? 2x=7)) (check-false (trivial? 2x+y=7))) (define (solve-trivial e) (unless (trivial? e) (error 'solve-trivial (~a "trivial expr expected, got" e))) (defm (expr h) e) (def t (constant-term e)) (def v (first (non-constant-variables e))) (def c (ref e v)) (when (= c 0) (error 'solve-trivial (~a "coeffecient to " v "is zero"))) (values v (/ (- t) c))) (module+ test (let () (defv (x v) (solve-trivial 2x=7)) (check-equal? (list x v) '(x 7/2)))) zeroes A list of expressions that are known to be zero . (def zeroes (make-parameter (list))) (define (find-expr-with-max-coef v es) (argmax (λ(e) (ref e v)) es)) (define (reduce r v e) assume to v in r is 1 (expr-lincomb 1 e (- (ref e v)) r)) (define (row-reduce exprs) (def vars (variables-in-exprs exprs)) (for/fold ([used '()] [remaining exprs]) ([v (in-set vars)] #:break (empty? remaining)) (def em (find-expr-with-max-coef v remaining)) (let ([remaining (remove em remaining eq?)]) (def e (expr* (/ 1 (ref em v)) em)) (def (reduce/e expr) (reduce e v expr)) (values (cons e (map reduce/e used)) (map reduce/e remaining))))) (module+ test (defv (done todo) (row-reduce (list 2x+y=7 2x+2y=9))) (displayln (list done todo))) solve : ( expr ) ( hash ( var . number ) ) - > ? pending A temporary list , holding zero - valued expressions from which no variable i ) No variable in zeroes , pending , or constraints is dependent . iii ) If all the variables on one side of a balance are known , then Note : Balances not in use in MetaPost / Font iv ) Values in zeroes , pending , constraints , and value are all represented as sums of (define (solve-loop known zeroes pending) (match zeroes [(? empty?) (match pending [(? empty?) (make-all-dependent-variables-known) (build-and-return-solution)] [_ (error 'solve-loop "underdetermined")])] [(list* z zs) (cond [(is-there-v-in-z-that-can-be-eliminated) (eliminate-v-from-z) ...] [(has-unknown-variable? z) (solve-loop known zs (cons z pending))] [else ???])])) (solve-loop (known) (zeroes) '())) (expr (make-hash (match (ref inputs i) [0 (list (cons i 1))] [k (list (cons i 1) (cons 1 (- k)))])))) (= = ( * 2 a ) 3 ) (= = ( + ( * 2 a ) b ) 21 ) (define (variable< s t) (match* (s t) [((? number? x) (? number? y)) (< x y)] [((? number? x) (? symbol? y)) #f] [((? symbol? x) (? number? y)) #t] [((? symbol? x) (? symbol? y)) (string<? (symbol->string x) (symbol->string y))])) (module+ test (check-true (variable< 'a 'b)) (check-true (variable< 'a 2)) (check-true (variable< 2 3)) (check-false (variable< 2 'a))) (define (expr->string e) (defm (expr h) e) (def vcs (for/list ([(v c) (in-hash h)] #:unless (= c 0)) (list v c))) (def s (string-join (for/list ([vc (in-list (sort vcs variable< #:key first))]) (defm (list v c) vc) (~a (match c [(? negative?) (~a "(" c ")")] [1 (match v [1 1] [_ ""])] [_ c]) (match v [1 ""] [_ v]))) "+")) (match s ["" "0"] [_ s])) (module+ test (check-equal? (expr->string (expr (make-hash '((x . 2) (y . 2) (1 . 3))))) "2x+2y+3") (check-equal? (expr->string (expr (make-hash '((x . 2) (y . -2) (1 . 3))))) "2x+(-2)y+3")) (define (display-expr e) (display (expr->string e))) (def zero-expr (expr (make-hash '((1 . 0))))) (module+ test (check-equal? (expr->string zero-expr) "0")) 2x+ y= 7 2x+3y=11 (expr->string eq1) (expr->string (expr~ eq1)) (expr->string (expr~ (expr~ eq1))) (expr= eq1 eq1) (expr->string (expr* 2 eq1)) (expr->string (expr+ eq1 eq1)) (expr->string (expr+ eq1 (expr~ eq1)))
4143bcf55b8126ec4c08890a0c3477d1e59c69f476ac845a02a73c79c30c282b
erlang/otp
annotations.erl
%% %CopyrightBegin% %% Copyright Ericsson AB 1997 - 2022 . All Rights Reserved . %% Licensed under the Apache License , Version 2.0 ( the " License " ) ; %% you may not use this file except in compliance with the License. %% You may obtain a copy of the License at %% %% -2.0 %% %% Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an " AS IS " BASIS , %% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %% See the License for the specific language governing permissions and %% limitations under the License. %% %% %CopyrightEnd% -module(annotations). -export([t0/0]). %% Check annotations, do not add lines before this function without %% changing the location annotation. t0() -> ssa% ( ) when post_ssa_opt - > ssa% _ = call(fun return_int/0 ) { result_type = > { t_integer,{17,17 } } , ssa% location = > { _ , 32 } } , %ssa% _ = call(fun return_tuple/0) { ssa% result_type = > { t_tuple,2,true,#{1 = > { t_integer,{1,1 } } , ssa% 2 = > { t_integer,{2,2 } } } } ssa% } . X = return_int(), Y = return_tuple(), {X, Y}. return_int() -> 17. return_tuple() -> {1,2}.
null
https://raw.githubusercontent.com/erlang/otp/1a3e3c492378d119e96a0f24f71b9d0313076447/lib/compiler/test/beam_ssa_check_SUITE_data/annotations.erl
erlang
%CopyrightBegin% you may not use this file except in compliance with the License. You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, software WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. %CopyrightEnd% Check annotations, do not add lines before this function without changing the location annotation. ( ) when post_ssa_opt - > _ = call(fun return_int/0 ) { result_type = > { t_integer,{17,17 } } , location = > { _ , 32 } } , ssa% _ = call(fun return_tuple/0) { result_type = > { t_tuple,2,true,#{1 = > { t_integer,{1,1 } } , 2 = > { t_integer,{2,2 } } } } } .
Copyright Ericsson AB 1997 - 2022 . All Rights Reserved . Licensed under the Apache License , Version 2.0 ( the " License " ) ; distributed under the License is distributed on an " AS IS " BASIS , -module(annotations). -export([t0/0]). t0() -> X = return_int(), Y = return_tuple(), {X, Y}. return_int() -> 17. return_tuple() -> {1,2}.
3fb7b71808f02f87e98cf7947e0fac02d40e6df87b101935bfdc41998aa9fc51
EligiusSantori/L2Apf
refresh_quest_list.scm
(module system racket/base (provide game-client-packet/refresh-quest-list) (require "../../packet.scm") (define (game-client-packet/refresh-quest-list) (let ((s (open-output-bytes))) (begin (write-byte #x63 s) (get-output-bytes s) ) ) ) )
null
https://raw.githubusercontent.com/EligiusSantori/L2Apf/30ffe0828e8a401f58d39984efd862c8aeab8c30/packet/game/client/refresh_quest_list.scm
scheme
(module system racket/base (provide game-client-packet/refresh-quest-list) (require "../../packet.scm") (define (game-client-packet/refresh-quest-list) (let ((s (open-output-bytes))) (begin (write-byte #x63 s) (get-output-bytes s) ) ) ) )
1c207fdfe7a7eb0e63eeef53083d7386cdf535612e3858a60e84a5699ad8c0e7
fiddlerwoaroof/lisp-sandbox
qtools-demo.lisp
(defpackage :qtools-demo (:use :cl)) (in-package :qtools-demo) (defun make-slider () (prog1-bind (the-widget (make-instance 'qui:slider)) )) (defun main () (cl+qt:with-main-window (w (make-instance 'qui:panel-container)) (qui:add-widget (make-instance 'qui:panel :title "An empty panel :(") w) (qui:add-widget (make-instance 'qui:panel :title "A slider, whoa!" :center (make-slider)) w) (qui:add-widget (make-instance 'qui:listing :title "A slider, whoa!" :center (make-instance 'qui:slider)) w)) )
null
https://raw.githubusercontent.com/fiddlerwoaroof/lisp-sandbox/38ff817c95af35db042faf760b477675264220d2/qtools-demo.lisp
lisp
(defpackage :qtools-demo (:use :cl)) (in-package :qtools-demo) (defun make-slider () (prog1-bind (the-widget (make-instance 'qui:slider)) )) (defun main () (cl+qt:with-main-window (w (make-instance 'qui:panel-container)) (qui:add-widget (make-instance 'qui:panel :title "An empty panel :(") w) (qui:add-widget (make-instance 'qui:panel :title "A slider, whoa!" :center (make-slider)) w) (qui:add-widget (make-instance 'qui:listing :title "A slider, whoa!" :center (make-instance 'qui:slider)) w)) )
6991e445a5226176e75b2c4cc5bf1a6331da3d906e1310e4ddf3510f330512f6
processone/ejabberd
eldap_pool.erl
%%%------------------------------------------------------------------- %%% File : eldap_pool.erl Author : < > %%% Purpose : LDAP connections pool Created : 12 Nov 2006 by < > %%% %%% ejabberd , Copyright ( C ) 2002 - 2023 ProcessOne %%% %%% This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation ; either version 2 of the %%% License, or (at your option) any later version. %%% %%% This program is distributed in the hope that it will be useful, %%% but WITHOUT ANY WARRANTY; without even the implied warranty of %%% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU %%% General Public License for more details. %%% You should have received a copy of the GNU General Public License along with this program ; if not , write to the Free Software Foundation , Inc. , 51 Franklin Street , Fifth Floor , Boston , USA . %%% %%%------------------------------------------------------------------- -module(eldap_pool). -author(''). %% API -export([start_link/7, bind/3, search/2, modify_passwd/3]). -include("logger.hrl"). -ifdef(USE_OLD_PG2). pg_create(PoolName) -> pg2:create(PoolName). pg_join(PoolName, Pid) -> pg2:join(PoolName, Pid). pg_get_closest_pid(Name) -> pg2:get_closest_pid(Name). -else. pg_create(_) -> pg:start_link(). pg_join(PoolName, Pid) -> pg:join(PoolName, Pid). pg_get_closest_pid(Group) -> case pg:get_local_members(Group) of [] -> case pg:get_members(Group) of [] -> {error, {no_process, Group}}; [Pid | _] -> Pid end; [Pid | _] -> Pid end. -endif. %%==================================================================== %% API %%==================================================================== bind(PoolName, DN, Passwd) -> do_request(PoolName, {bind, [DN, Passwd]}). search(PoolName, Opts) -> do_request(PoolName, {search, [Opts]}). modify_passwd(PoolName, DN, Passwd) -> do_request(PoolName, {modify_passwd, [DN, Passwd]}). start_link(Name, Hosts, Backups, Port, Rootdn, Passwd, Opts) -> PoolName = make_id(Name), pg_create(PoolName), lists:foreach(fun (Host) -> ID = list_to_binary(erlang:ref_to_list(make_ref())), case catch eldap:start_link(ID, [Host | Backups], Port, Rootdn, Passwd, Opts) of {ok, Pid} -> pg_join(PoolName, Pid); Err -> ?ERROR_MSG("Err = ~p", [Err]), error end end, Hosts). %%==================================================================== Internal functions %%==================================================================== do_request(Name, {F, Args}) -> case pg_get_closest_pid(make_id(Name)) of Pid when is_pid(Pid) -> case catch apply(eldap, F, [Pid | Args]) of {'EXIT', {timeout, _}} -> ?ERROR_MSG("LDAP request failed: timed out", []); {'EXIT', Reason} -> ?ERROR_MSG("LDAP request failed: eldap:~p(~p)~nReason: ~p", [F, Args, Reason]), {error, Reason}; Reply -> Reply end; Err -> Err end. make_id(Name) -> misc:binary_to_atom(<<"eldap_pool_", Name/binary>>).
null
https://raw.githubusercontent.com/processone/ejabberd/c103182bc7e5b8a8ab123ce02d1959a54e939480/src/eldap_pool.erl
erlang
------------------------------------------------------------------- File : eldap_pool.erl Purpose : LDAP connections pool This program is free software; you can redistribute it and/or License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ------------------------------------------------------------------- API ==================================================================== API ==================================================================== ==================================================================== ====================================================================
Author : < > Created : 12 Nov 2006 by < > ejabberd , Copyright ( C ) 2002 - 2023 ProcessOne modify it under the terms of the GNU General Public License as published by the Free Software Foundation ; either version 2 of the You should have received a copy of the GNU General Public License along with this program ; if not , write to the Free Software Foundation , Inc. , 51 Franklin Street , Fifth Floor , Boston , USA . -module(eldap_pool). -author(''). -export([start_link/7, bind/3, search/2, modify_passwd/3]). -include("logger.hrl"). -ifdef(USE_OLD_PG2). pg_create(PoolName) -> pg2:create(PoolName). pg_join(PoolName, Pid) -> pg2:join(PoolName, Pid). pg_get_closest_pid(Name) -> pg2:get_closest_pid(Name). -else. pg_create(_) -> pg:start_link(). pg_join(PoolName, Pid) -> pg:join(PoolName, Pid). pg_get_closest_pid(Group) -> case pg:get_local_members(Group) of [] -> case pg:get_members(Group) of [] -> {error, {no_process, Group}}; [Pid | _] -> Pid end; [Pid | _] -> Pid end. -endif. bind(PoolName, DN, Passwd) -> do_request(PoolName, {bind, [DN, Passwd]}). search(PoolName, Opts) -> do_request(PoolName, {search, [Opts]}). modify_passwd(PoolName, DN, Passwd) -> do_request(PoolName, {modify_passwd, [DN, Passwd]}). start_link(Name, Hosts, Backups, Port, Rootdn, Passwd, Opts) -> PoolName = make_id(Name), pg_create(PoolName), lists:foreach(fun (Host) -> ID = list_to_binary(erlang:ref_to_list(make_ref())), case catch eldap:start_link(ID, [Host | Backups], Port, Rootdn, Passwd, Opts) of {ok, Pid} -> pg_join(PoolName, Pid); Err -> ?ERROR_MSG("Err = ~p", [Err]), error end end, Hosts). Internal functions do_request(Name, {F, Args}) -> case pg_get_closest_pid(make_id(Name)) of Pid when is_pid(Pid) -> case catch apply(eldap, F, [Pid | Args]) of {'EXIT', {timeout, _}} -> ?ERROR_MSG("LDAP request failed: timed out", []); {'EXIT', Reason} -> ?ERROR_MSG("LDAP request failed: eldap:~p(~p)~nReason: ~p", [F, Args, Reason]), {error, Reason}; Reply -> Reply end; Err -> Err end. make_id(Name) -> misc:binary_to_atom(<<"eldap_pool_", Name/binary>>).
f922eb85c9484499a9b2870d1bd8e66a588d7ea804e3ff108a76f9c605579ad4
REPROSEC/dolev-yao-star
Vale_Def_Words_s.ml
open Prims type 'a two = { lo: 'a ; hi: 'a } let __proj__Mktwo__item__lo : 'a . 'a two -> 'a = fun projectee -> match projectee with | { lo; hi;_} -> lo let __proj__Mktwo__item__hi : 'a . 'a two -> 'a = fun projectee -> match projectee with | { lo; hi;_} -> hi type 'a four = { lo0: 'a ; lo1: 'a ; hi2: 'a ; hi3: 'a } let __proj__Mkfour__item__lo0 : 'a . 'a four -> 'a = fun projectee -> match projectee with | { lo0; lo1; hi2; hi3;_} -> lo0 let __proj__Mkfour__item__lo1 : 'a . 'a four -> 'a = fun projectee -> match projectee with | { lo0; lo1; hi2; hi3;_} -> lo1 let __proj__Mkfour__item__hi2 : 'a . 'a four -> 'a = fun projectee -> match projectee with | { lo0; lo1; hi2; hi3;_} -> hi2 let __proj__Mkfour__item__hi3 : 'a . 'a four -> 'a = fun projectee -> match projectee with | { lo0; lo1; hi2; hi3;_} -> hi3 type 'a eight = { lo_0: 'a ; lo_1: 'a ; lo_2: 'a ; lo_3: 'a ; hi_4: 'a ; hi_5: 'a ; hi_6: 'a ; hi_7: 'a } let __proj__Mkeight__item__lo_0 : 'a . 'a eight -> 'a = fun projectee -> match projectee with | { lo_0; lo_1; lo_2; lo_3; hi_4; hi_5; hi_6; hi_7;_} -> lo_0 let __proj__Mkeight__item__lo_1 : 'a . 'a eight -> 'a = fun projectee -> match projectee with | { lo_0; lo_1; lo_2; lo_3; hi_4; hi_5; hi_6; hi_7;_} -> lo_1 let __proj__Mkeight__item__lo_2 : 'a . 'a eight -> 'a = fun projectee -> match projectee with | { lo_0; lo_1; lo_2; lo_3; hi_4; hi_5; hi_6; hi_7;_} -> lo_2 let __proj__Mkeight__item__lo_3 : 'a . 'a eight -> 'a = fun projectee -> match projectee with | { lo_0; lo_1; lo_2; lo_3; hi_4; hi_5; hi_6; hi_7;_} -> lo_3 let __proj__Mkeight__item__hi_4 : 'a . 'a eight -> 'a = fun projectee -> match projectee with | { lo_0; lo_1; lo_2; lo_3; hi_4; hi_5; hi_6; hi_7;_} -> hi_4 let __proj__Mkeight__item__hi_5 : 'a . 'a eight -> 'a = fun projectee -> match projectee with | { lo_0; lo_1; lo_2; lo_3; hi_4; hi_5; hi_6; hi_7;_} -> hi_5 let __proj__Mkeight__item__hi_6 : 'a . 'a eight -> 'a = fun projectee -> match projectee with | { lo_0; lo_1; lo_2; lo_3; hi_4; hi_5; hi_6; hi_7;_} -> hi_6 let __proj__Mkeight__item__hi_7 : 'a . 'a eight -> 'a = fun projectee -> match projectee with | { lo_0; lo_1; lo_2; lo_3; hi_4; hi_5; hi_6; hi_7;_} -> hi_7 let (pow2_norm : Prims.nat -> Prims.pos) = fun n -> match n with | uu___ when uu___ = Prims.int_zero -> Prims.int_one | uu___ -> (Prims.of_int (2)) * (Prims.pow2 (n - Prims.int_one)) let (pow2_1 : Prims.int) = (Prims.of_int (0x2)) let (pow2_2 : Prims.int) = (Prims.of_int (0x4)) let (pow2_4 : Prims.int) = (Prims.of_int (0x10)) let (pow2_8 : Prims.int) = (Prims.of_int (0x100)) let (pow2_16 : Prims.int) = (Prims.parse_int "0x10000") let (pow2_32 : Prims.int) = (Prims.parse_int "0x100000000") let (pow2_64 : Prims.int) = (Prims.parse_int "0x10000000000000000") let (pow2_128 : Prims.int) = (Prims.parse_int "0x100000000000000000000000000000000") type 'n natN = Prims.nat type nat1 = unit natN type nat2 = unit natN type nat4 = unit natN type nat8 = unit natN type nat16 = unit natN type nat32 = unit natN type nat64 = unit natN type nat128 = unit natN let (int_to_natN : Prims.pos -> Prims.int -> unit natN) = fun n -> fun i -> i mod n
null
https://raw.githubusercontent.com/REPROSEC/dolev-yao-star/d97a8dd4d07f2322437f186e4db6a1f4d5ee9230/concrete/hacl-star-snapshot/ml/Vale_Def_Words_s.ml
ocaml
open Prims type 'a two = { lo: 'a ; hi: 'a } let __proj__Mktwo__item__lo : 'a . 'a two -> 'a = fun projectee -> match projectee with | { lo; hi;_} -> lo let __proj__Mktwo__item__hi : 'a . 'a two -> 'a = fun projectee -> match projectee with | { lo; hi;_} -> hi type 'a four = { lo0: 'a ; lo1: 'a ; hi2: 'a ; hi3: 'a } let __proj__Mkfour__item__lo0 : 'a . 'a four -> 'a = fun projectee -> match projectee with | { lo0; lo1; hi2; hi3;_} -> lo0 let __proj__Mkfour__item__lo1 : 'a . 'a four -> 'a = fun projectee -> match projectee with | { lo0; lo1; hi2; hi3;_} -> lo1 let __proj__Mkfour__item__hi2 : 'a . 'a four -> 'a = fun projectee -> match projectee with | { lo0; lo1; hi2; hi3;_} -> hi2 let __proj__Mkfour__item__hi3 : 'a . 'a four -> 'a = fun projectee -> match projectee with | { lo0; lo1; hi2; hi3;_} -> hi3 type 'a eight = { lo_0: 'a ; lo_1: 'a ; lo_2: 'a ; lo_3: 'a ; hi_4: 'a ; hi_5: 'a ; hi_6: 'a ; hi_7: 'a } let __proj__Mkeight__item__lo_0 : 'a . 'a eight -> 'a = fun projectee -> match projectee with | { lo_0; lo_1; lo_2; lo_3; hi_4; hi_5; hi_6; hi_7;_} -> lo_0 let __proj__Mkeight__item__lo_1 : 'a . 'a eight -> 'a = fun projectee -> match projectee with | { lo_0; lo_1; lo_2; lo_3; hi_4; hi_5; hi_6; hi_7;_} -> lo_1 let __proj__Mkeight__item__lo_2 : 'a . 'a eight -> 'a = fun projectee -> match projectee with | { lo_0; lo_1; lo_2; lo_3; hi_4; hi_5; hi_6; hi_7;_} -> lo_2 let __proj__Mkeight__item__lo_3 : 'a . 'a eight -> 'a = fun projectee -> match projectee with | { lo_0; lo_1; lo_2; lo_3; hi_4; hi_5; hi_6; hi_7;_} -> lo_3 let __proj__Mkeight__item__hi_4 : 'a . 'a eight -> 'a = fun projectee -> match projectee with | { lo_0; lo_1; lo_2; lo_3; hi_4; hi_5; hi_6; hi_7;_} -> hi_4 let __proj__Mkeight__item__hi_5 : 'a . 'a eight -> 'a = fun projectee -> match projectee with | { lo_0; lo_1; lo_2; lo_3; hi_4; hi_5; hi_6; hi_7;_} -> hi_5 let __proj__Mkeight__item__hi_6 : 'a . 'a eight -> 'a = fun projectee -> match projectee with | { lo_0; lo_1; lo_2; lo_3; hi_4; hi_5; hi_6; hi_7;_} -> hi_6 let __proj__Mkeight__item__hi_7 : 'a . 'a eight -> 'a = fun projectee -> match projectee with | { lo_0; lo_1; lo_2; lo_3; hi_4; hi_5; hi_6; hi_7;_} -> hi_7 let (pow2_norm : Prims.nat -> Prims.pos) = fun n -> match n with | uu___ when uu___ = Prims.int_zero -> Prims.int_one | uu___ -> (Prims.of_int (2)) * (Prims.pow2 (n - Prims.int_one)) let (pow2_1 : Prims.int) = (Prims.of_int (0x2)) let (pow2_2 : Prims.int) = (Prims.of_int (0x4)) let (pow2_4 : Prims.int) = (Prims.of_int (0x10)) let (pow2_8 : Prims.int) = (Prims.of_int (0x100)) let (pow2_16 : Prims.int) = (Prims.parse_int "0x10000") let (pow2_32 : Prims.int) = (Prims.parse_int "0x100000000") let (pow2_64 : Prims.int) = (Prims.parse_int "0x10000000000000000") let (pow2_128 : Prims.int) = (Prims.parse_int "0x100000000000000000000000000000000") type 'n natN = Prims.nat type nat1 = unit natN type nat2 = unit natN type nat4 = unit natN type nat8 = unit natN type nat16 = unit natN type nat32 = unit natN type nat64 = unit natN type nat128 = unit natN let (int_to_natN : Prims.pos -> Prims.int -> unit natN) = fun n -> fun i -> i mod n
30dbbbb6e182bf7a302c46963388a9f8278d0b072728da7494859d96be084108
apache/couchdb-chttpd
chttpd_auth_request.erl
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(chttpd_auth_request). -export([authorize_request/1]). -include_lib("couch/include/couch_db.hrl"). authorize_request(#httpd{auth=Auth, user_ctx=Ctx} = Req) -> try authorize_request_int(Req) catch throw:{forbidden, Msg} -> case {Auth, Ctx} of {{cookie_auth_failed, {Error, Reason}}, _} -> throw({forbidden, {Error, Reason}}); {_, #user_ctx{name=null}} -> throw({unauthorized, Msg}); {_, _} -> throw({forbidden, Msg}) end end. authorize_request_int(#httpd{path_parts=[]}=Req) -> Req; authorize_request_int(#httpd{path_parts=[<<"favicon.ico">>|_]}=Req) -> Req; authorize_request_int(#httpd{path_parts=[<<"_all_dbs">>|_]}=Req) -> Req; authorize_request_int(#httpd{path_parts=[<<"_replicator">>], method='PUT'}=Req) -> require_admin(Req); authorize_request_int(#httpd{path_parts=[<<"_replicator">>], method='DELETE'}=Req) -> require_admin(Req); authorize_request_int(#httpd{path_parts=[<<"_replicator">>,<<"_all_docs">>|_]}=Req) -> require_admin(Req); authorize_request_int(#httpd{path_parts=[<<"_replicator">>,<<"_changes">>|_]}=Req) -> require_admin(Req); authorize_request_int(#httpd{path_parts=[<<"_replicator">>|_]}=Req) -> db_authorization_check(Req); authorize_request_int(#httpd{path_parts=[<<"_users">>], method='PUT'}=Req) -> require_admin(Req); authorize_request_int(#httpd{path_parts=[<<"_users">>], method='DELETE'}=Req) -> require_admin(Req); authorize_request_int(#httpd{path_parts=[<<"_users">>,<<"_all_docs">>|_]}=Req) -> require_admin(Req); authorize_request_int(#httpd{path_parts=[<<"_users">>,<<"_changes">>|_]}=Req) -> require_admin(Req); authorize_request_int(#httpd{path_parts=[<<"_users">>|_]}=Req) -> db_authorization_check(Req); authorize_request_int(#httpd{path_parts=[<<"_", _/binary>>|_]}=Req) -> server_authorization_check(Req); authorize_request_int(#httpd{path_parts=[_DbName], method='PUT'}=Req) -> require_admin(Req); authorize_request_int(#httpd{path_parts=[_DbName], method='DELETE'}=Req) -> require_admin(Req); authorize_request_int(#httpd{path_parts=[_DbName|_]}=Req) -> db_authorization_check(Req). server_authorization_check(#httpd{path_parts=[<<"_up">>]}=Req) -> Req; server_authorization_check(#httpd{path_parts=[<<"_uuids">>]}=Req) -> Req; server_authorization_check(#httpd{path_parts=[<<"_session">>]}=Req) -> Req; server_authorization_check(#httpd{path_parts=[<<"_replicate">>]}=Req) -> Req; server_authorization_check(#httpd{path_parts=[<<"_stats">>]}=Req) -> Req; server_authorization_check(#httpd{path_parts=[<<"_active_tasks">>]}=Req) -> Req; server_authorization_check(#httpd{method=Method, path_parts=[<<"_utils">>|_]}=Req) when Method =:= 'HEAD' orelse Method =:= 'GET' -> Req; server_authorization_check(#httpd{path_parts=[<<"_", _/binary>>|_]}=Req) -> require_admin(Req). db_authorization_check(#httpd{path_parts=[DbName|_],user_ctx=Ctx}=Req) -> {_} = fabric:get_security(DbName, [{user_ctx, Ctx}]), Req. require_admin(Req) -> ok = couch_httpd:verify_is_server_admin(Req), Req.
null
https://raw.githubusercontent.com/apache/couchdb-chttpd/74002101513c03df74a4c25f3c892f5d003fa5da/src/chttpd_auth_request.erl
erlang
use this file except in compliance with the License. You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, software WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
Licensed under the Apache License , Version 2.0 ( the " License " ) ; you may not distributed under the License is distributed on an " AS IS " BASIS , WITHOUT -module(chttpd_auth_request). -export([authorize_request/1]). -include_lib("couch/include/couch_db.hrl"). authorize_request(#httpd{auth=Auth, user_ctx=Ctx} = Req) -> try authorize_request_int(Req) catch throw:{forbidden, Msg} -> case {Auth, Ctx} of {{cookie_auth_failed, {Error, Reason}}, _} -> throw({forbidden, {Error, Reason}}); {_, #user_ctx{name=null}} -> throw({unauthorized, Msg}); {_, _} -> throw({forbidden, Msg}) end end. authorize_request_int(#httpd{path_parts=[]}=Req) -> Req; authorize_request_int(#httpd{path_parts=[<<"favicon.ico">>|_]}=Req) -> Req; authorize_request_int(#httpd{path_parts=[<<"_all_dbs">>|_]}=Req) -> Req; authorize_request_int(#httpd{path_parts=[<<"_replicator">>], method='PUT'}=Req) -> require_admin(Req); authorize_request_int(#httpd{path_parts=[<<"_replicator">>], method='DELETE'}=Req) -> require_admin(Req); authorize_request_int(#httpd{path_parts=[<<"_replicator">>,<<"_all_docs">>|_]}=Req) -> require_admin(Req); authorize_request_int(#httpd{path_parts=[<<"_replicator">>,<<"_changes">>|_]}=Req) -> require_admin(Req); authorize_request_int(#httpd{path_parts=[<<"_replicator">>|_]}=Req) -> db_authorization_check(Req); authorize_request_int(#httpd{path_parts=[<<"_users">>], method='PUT'}=Req) -> require_admin(Req); authorize_request_int(#httpd{path_parts=[<<"_users">>], method='DELETE'}=Req) -> require_admin(Req); authorize_request_int(#httpd{path_parts=[<<"_users">>,<<"_all_docs">>|_]}=Req) -> require_admin(Req); authorize_request_int(#httpd{path_parts=[<<"_users">>,<<"_changes">>|_]}=Req) -> require_admin(Req); authorize_request_int(#httpd{path_parts=[<<"_users">>|_]}=Req) -> db_authorization_check(Req); authorize_request_int(#httpd{path_parts=[<<"_", _/binary>>|_]}=Req) -> server_authorization_check(Req); authorize_request_int(#httpd{path_parts=[_DbName], method='PUT'}=Req) -> require_admin(Req); authorize_request_int(#httpd{path_parts=[_DbName], method='DELETE'}=Req) -> require_admin(Req); authorize_request_int(#httpd{path_parts=[_DbName|_]}=Req) -> db_authorization_check(Req). server_authorization_check(#httpd{path_parts=[<<"_up">>]}=Req) -> Req; server_authorization_check(#httpd{path_parts=[<<"_uuids">>]}=Req) -> Req; server_authorization_check(#httpd{path_parts=[<<"_session">>]}=Req) -> Req; server_authorization_check(#httpd{path_parts=[<<"_replicate">>]}=Req) -> Req; server_authorization_check(#httpd{path_parts=[<<"_stats">>]}=Req) -> Req; server_authorization_check(#httpd{path_parts=[<<"_active_tasks">>]}=Req) -> Req; server_authorization_check(#httpd{method=Method, path_parts=[<<"_utils">>|_]}=Req) when Method =:= 'HEAD' orelse Method =:= 'GET' -> Req; server_authorization_check(#httpd{path_parts=[<<"_", _/binary>>|_]}=Req) -> require_admin(Req). db_authorization_check(#httpd{path_parts=[DbName|_],user_ctx=Ctx}=Req) -> {_} = fabric:get_security(DbName, [{user_ctx, Ctx}]), Req. require_admin(Req) -> ok = couch_httpd:verify_is_server_admin(Req), Req.
814baf5e4c33bc03ebc76a60efb876412638cf194a5676c4532eaeda0605a57a
dgiot/dgiot
dgiot_hjt212_decoder.erl
%%-------------------------------------------------------------------- Copyright ( c ) 2020 - 2021 DGIOT Technologies Co. , Ltd. All Rights Reserved . %% Licensed under the Apache License , Version 2.0 ( the " License " ) ; %% you may not use this file except in compliance with the License. %% You may obtain a copy of the License at %% %% -2.0 %% %% Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an " AS IS " BASIS , %% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %% See the License for the specific language governing permissions and %% limitations under the License. %%-------------------------------------------------------------------- -module(dgiot_hjt212_decoder). -include_lib("dgiot_hjt212.hrl"). -author("stoneliu"). -include_lib("dgiot/include/logger.hrl"). -protocol([?HJT212]). -define(CRLF, "\r\n"). %% API -export([parse_frame/2, to_frame/1]). parse_frame(Buff, Opts) -> parse_frame(Buff, [], Opts). parse_frame(<<>>, Acc, _Opts) -> {ok, Acc}; %% HJ 212-2017 6.3 通讯协议数据结构 所有的通讯包都是由 ASCII 码(汉字除外,采用 UTF-8 码,8 位,1 字节)字符组成。通讯协议数 据结构如图 4 所示 。 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% 定 义 | 类型 | 长度 | 描 述 | %------------------------------------------------------------------------------------------------------------------------ %% 包头 | 字符 | 2 | 固定为## | %------------------------------------------------------------------------------------------------------------------------- 数据段长度 | 十进制整型 | 2 | 数据段的 ASCII 字符数,例如:长 255,则写为“0255 ” | %------------------------------------------------------------------------------------------------------------------------- 数据段 | 字符 | 0 ≤ n ≤ 1024 | 变长的数据,详见 6.3.2 章节的表 3《数据段结构组成表 》 | %------------------------------------------------------------------------------------------------------------------------- CRC 校验 | 十六进制整数 | 4 | 数据段的校验结果,CRC 校验算法见附录 A。接收到一条命令 , | | | | 如果 CRC 错误,执行结束 | %------------------------------------------------------------------------------------------------------------------------- %% 包尾 | 字符 | 2 | 固定为<CR><LF>(回车、换行) | %------------------------------------------------------------------------------------------------------------------------- parse_frame(<<"##", Length:4/binary, Tail/binary>>, Acc, State) -> Len = binary_to_integer(Length, 10), {Rest1, Acc1} = case Len > -1 andalso Len < 1025 of true -> case Tail of <<UserZone:Len/binary, Crc:4/binary, ?CRLF, Rest/binary>> -> CheckCrc = dgiot_hjt212_utils:crc16(UserZone), case Crc of CheckCrc -> {Rest, Acc ++ [parse_userzone(UserZone, State)]}; _ -> {<<>>, Acc} end; _ -> {<<>>, Acc} end; _ -> {<<>>, Acc} end, parse_frame(Rest1, Acc1, State); parse_frame(<<_:8, Data/binary>> = _Rest, Acc, Opts) -> parse_frame(Data, Acc, Opts). 6.3.2 数据段结构组成 %% 数据段结构组成见表 3,表 3 中“长度”包含字段名称、‘=’、字段内容三部分内容。 表 3 数据段结构组成表 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %| 名称 | 类型 | 长度 | 描述 | | 请求编码 QN | 字符 | 20 | 精确到毫秒的时间戳 : QN = YYYYMMDDhhmmsszzz,用来唯一标识一次命令交互 | %------------------------------------------------------------------------------------------------------------------------ | 系统编码 ST | 字符 | 5 | ST = 系统编码 , 系统编码取值详见 6.6.1 章节的表 5《系统编码表 》 | | 命令编码 CN | 字符 | 7 | CN = 命令编码 , 命令编码取值详见 6.6.5 章节的表 9《命令编码表 》 | | 访问密码 | 字符 | 9 | PW = 访问密码 | |----------------------------------------------------------------------------------------------------------------------| %| | | | MN=设备唯一标识,这个标识固化在设备中,用于唯一标识一个设备。MN 由 EPC-96 | | | | | 编码转化的字符串组成,即 MN 由 24 个 0~9,A ~ F 的字符组成 | %| | | | _______________________________________________________________ | | 设备唯一标识 MN | 字符 | 27 | | EPC-96 编码结构 | | %| | | | |------------------------------------------------------------- | | | | | | | 名称 | 标头 | 厂商识别代码 | 对象分类代码 | 序列号 | | %| | | | --------------------------------------------------------------- | | | | | | 长度(比特 | 8 | 28 | 24 | 36 | | |----------------------------------------------------------------------------------------------------------------------| %| | | | Flag=标志位,这个标志位包含标准版本号、是否拆分包、数据是否应答。 | %| | | | —————————————————————————————————————————— | %| | | | | V5 | V4 | V3 | V2 | V1 | V0 | D | A | | %| | | | ------------------------------------------- | %| 拆分包及应答标志 | 整数 | 8 | V5~V0:标准版本号;Bit:000000 表示标准 HJ/T 212-2005,000001 | | Flag | ( 0 - 255)| | | | | | | A:命令是否应答;Bit:1 - 应答,0 - 不应答 。 | %| | | | D:是否有数据包序号;Bit:1-数据包中包含包号和总包数两部分, | %| | | | 0-数据包中不包含包号和总包数两部分。 | %| | | | 示例:Flag=7 表示标准版本为本次修订版本号,数据段需要拆分并且命令需要应答 | |----------------------------------------------------------------------------------------------------------------------| | 总包数PNUM | 字符 | 9 | PNUM 指示本次通讯中总共包含的包数 , 注:不分包时可以没有本字段,与标志位有关 | |----------------------------------------------------------------------------------------------------------------------| | 包号 PNO | 字符 | 8 | PNO 指示当前数据包的包号 , 注:不分包时可以没有本字段,与标志位有关 |----------------------------------------------------------------------------------------------------------------------| | 指令参数 CP | 字符 | 0≤n≤950| CP=&&数据区&&,数据区定义见 6.3.3 章节 | |----------------------------------------------------------------------------------------------------------------------| / binary,";ST= " , ST:2 / binary , " ; CN= " , CN:4 / binary , " ; PW= " , PWD:6 / binary , " ; " , MN:24 / binary , " ; Flag= " , Flag:2 / binary , PNUM:9 / binary , PNO:8 / binary , " ; CP= " , CP / binary > > , _ State ) - > parse_userzone(UserZone, _State) -> lists:foldl(fun(X, Acc) -> case X of <<"CP=&&", CP/binary>> -> Acc#{<<"CP">> => dgiot_hjt212_utils:get_cps(CP)}; _ -> case re:split(X, <<"=">>) of [K, V] -> Acc#{K => V}; _ -> Acc end end end, #{}, re:split(UserZone, <<";">>)). to_frame(#{<<"QN">> := QN, <<"ST">> := ST, <<"CN">> := CN, <<"PW">> := PW, <<"MN">> := MN, <<"Flag">> := Flag, <<"CP">> := CP, <<"PNUM">> := PNUM, <<"PNO">> := PNO}) -> Rdata = <<"QN=", QN/binary, ";ST=", ST/binary, ";CN=", CN/binary, ";PW=", PW/binary, ";MN=", MN/binary, ";Flag=", Flag/binary, ";PNUM=",PNUM/binary,";PNO=", PNO/binary, ";CP=&&", CP/binary, "&&">>, Len = dgiot_hjt212_utils:get_len(Rdata), Crc = dgiot_hjt212_utils:crc16(Rdata), <<"##", Len/binary, Rdata/binary, Crc/binary, "\r\n">>; to_frame(#{<<"QN">> := QN, <<"ST">> := ST, <<"CN">> := CN, <<"PW">> := PW, <<"MN">> := MN, <<"Flag">> := Flag, <<"CP">> := CP}) -> Rdata = <<"QN=", QN/binary, ";ST=", ST/binary, ";CN=", CN/binary, ";PW=", PW/binary, ";MN=", MN/binary, ";Flag=", Flag/binary, ";CP=&&", CP/binary, "&&">>, Len = dgiot_hjt212_utils:get_len(Rdata), Crc = dgiot_hjt212_utils:crc16(Rdata), <<"##", Len/binary, Rdata/binary, Crc/binary, "\r\n">>.
null
https://raw.githubusercontent.com/dgiot/dgiot/a6b816a094b1c9bd024ce40b8142375a0f0289d8/apps/dgiot_hjt212/src/protocol/dgiot_hjt212_decoder.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 HJ 212-2017 定 义 | 类型 | 长度 | 描 述 | ------------------------------------------------------------------------------------------------------------------------ 包头 | 字符 | 2 | 固定为## | ------------------------------------------------------------------------------------------------------------------------- ------------------------------------------------------------------------------------------------------------------------- ------------------------------------------------------------------------------------------------------------------------- ------------------------------------------------------------------------------------------------------------------------- 包尾 | 字符 | 2 | 固定为<CR><LF>(回车、换行) | ------------------------------------------------------------------------------------------------------------------------- 数据段结构组成见表 3,表 3 中“长度”包含字段名称、‘=’、字段内容三部分内容。 | 名称 | 类型 | 长度 | 描述 | ------------------------------------------------------------------------------------------------------------------------ | | | | MN=设备唯一标识,这个标识固化在设备中,用于唯一标识一个设备。MN 由 EPC-96 | | | | | _______________________________________________________________ | | | | | |------------------------------------------------------------- | | | | | | --------------------------------------------------------------- | | | | | Flag=标志位,这个标志位包含标准版本号、是否拆分包、数据是否应答。 | | | | | —————————————————————————————————————————— | | | | | | V5 | V4 | V3 | V2 | V1 | V0 | D | A | | | | | | ------------------------------------------- | | 拆分包及应答标志 | 整数 | 8 | V5~V0:标准版本号;Bit:000000 表示标准 HJ/T 212-2005,000001 | | | | | D:是否有数据包序号;Bit:1-数据包中包含包号和总包数两部分, | | | | | 0-数据包中不包含包号和总包数两部分。 | | | | | 示例:Flag=7 表示标准版本为本次修订版本号,数据段需要拆分并且命令需要应答 |
Copyright ( c ) 2020 - 2021 DGIOT Technologies Co. , Ltd. All Rights Reserved . Licensed under the Apache License , Version 2.0 ( the " License " ) ; distributed under the License is distributed on an " AS IS " BASIS , -module(dgiot_hjt212_decoder). -include_lib("dgiot_hjt212.hrl"). -author("stoneliu"). -include_lib("dgiot/include/logger.hrl"). -protocol([?HJT212]). -define(CRLF, "\r\n"). -export([parse_frame/2, to_frame/1]). parse_frame(Buff, Opts) -> parse_frame(Buff, [], Opts). parse_frame(<<>>, Acc, _Opts) -> {ok, Acc}; 6.3 通讯协议数据结构 所有的通讯包都是由 ASCII 码(汉字除外,采用 UTF-8 码,8 位,1 字节)字符组成。通讯协议数 据结构如图 4 所示 。 数据段长度 | 十进制整型 | 2 | 数据段的 ASCII 字符数,例如:长 255,则写为“0255 ” | 数据段 | 字符 | 0 ≤ n ≤ 1024 | 变长的数据,详见 6.3.2 章节的表 3《数据段结构组成表 》 | CRC 校验 | 十六进制整数 | 4 | 数据段的校验结果,CRC 校验算法见附录 A。接收到一条命令 , | | | | 如果 CRC 错误,执行结束 | parse_frame(<<"##", Length:4/binary, Tail/binary>>, Acc, State) -> Len = binary_to_integer(Length, 10), {Rest1, Acc1} = case Len > -1 andalso Len < 1025 of true -> case Tail of <<UserZone:Len/binary, Crc:4/binary, ?CRLF, Rest/binary>> -> CheckCrc = dgiot_hjt212_utils:crc16(UserZone), case Crc of CheckCrc -> {Rest, Acc ++ [parse_userzone(UserZone, State)]}; _ -> {<<>>, Acc} end; _ -> {<<>>, Acc} end; _ -> {<<>>, Acc} end, parse_frame(Rest1, Acc1, State); parse_frame(<<_:8, Data/binary>> = _Rest, Acc, Opts) -> parse_frame(Data, Acc, Opts). 6.3.2 数据段结构组成 表 3 数据段结构组成表 | 请求编码 QN | 字符 | 20 | 精确到毫秒的时间戳 : QN = YYYYMMDDhhmmsszzz,用来唯一标识一次命令交互 | | 系统编码 ST | 字符 | 5 | ST = 系统编码 , 系统编码取值详见 6.6.1 章节的表 5《系统编码表 》 | | 命令编码 CN | 字符 | 7 | CN = 命令编码 , 命令编码取值详见 6.6.5 章节的表 9《命令编码表 》 | | 访问密码 | 字符 | 9 | PW = 访问密码 | |----------------------------------------------------------------------------------------------------------------------| | | | | 编码转化的字符串组成,即 MN 由 24 个 0~9,A ~ F 的字符组成 | | 设备唯一标识 MN | 字符 | 27 | | EPC-96 编码结构 | | | | | | | 名称 | 标头 | 厂商识别代码 | 对象分类代码 | 序列号 | | | | | | | 长度(比特 | 8 | 28 | 24 | 36 | | |----------------------------------------------------------------------------------------------------------------------| | Flag | ( 0 - 255)| | | | | | | A:命令是否应答;Bit:1 - 应答,0 - 不应答 。 | |----------------------------------------------------------------------------------------------------------------------| | 总包数PNUM | 字符 | 9 | PNUM 指示本次通讯中总共包含的包数 , 注:不分包时可以没有本字段,与标志位有关 | |----------------------------------------------------------------------------------------------------------------------| | 包号 PNO | 字符 | 8 | PNO 指示当前数据包的包号 , 注:不分包时可以没有本字段,与标志位有关 |----------------------------------------------------------------------------------------------------------------------| | 指令参数 CP | 字符 | 0≤n≤950| CP=&&数据区&&,数据区定义见 6.3.3 章节 | |----------------------------------------------------------------------------------------------------------------------| / binary,";ST= " , ST:2 / binary , " ; CN= " , CN:4 / binary , " ; PW= " , PWD:6 / binary , " ; " , MN:24 / binary , " ; Flag= " , Flag:2 / binary , PNUM:9 / binary , PNO:8 / binary , " ; CP= " , CP / binary > > , _ State ) - > parse_userzone(UserZone, _State) -> lists:foldl(fun(X, Acc) -> case X of <<"CP=&&", CP/binary>> -> Acc#{<<"CP">> => dgiot_hjt212_utils:get_cps(CP)}; _ -> case re:split(X, <<"=">>) of [K, V] -> Acc#{K => V}; _ -> Acc end end end, #{}, re:split(UserZone, <<";">>)). to_frame(#{<<"QN">> := QN, <<"ST">> := ST, <<"CN">> := CN, <<"PW">> := PW, <<"MN">> := MN, <<"Flag">> := Flag, <<"CP">> := CP, <<"PNUM">> := PNUM, <<"PNO">> := PNO}) -> Rdata = <<"QN=", QN/binary, ";ST=", ST/binary, ";CN=", CN/binary, ";PW=", PW/binary, ";MN=", MN/binary, ";Flag=", Flag/binary, ";PNUM=",PNUM/binary,";PNO=", PNO/binary, ";CP=&&", CP/binary, "&&">>, Len = dgiot_hjt212_utils:get_len(Rdata), Crc = dgiot_hjt212_utils:crc16(Rdata), <<"##", Len/binary, Rdata/binary, Crc/binary, "\r\n">>; to_frame(#{<<"QN">> := QN, <<"ST">> := ST, <<"CN">> := CN, <<"PW">> := PW, <<"MN">> := MN, <<"Flag">> := Flag, <<"CP">> := CP}) -> Rdata = <<"QN=", QN/binary, ";ST=", ST/binary, ";CN=", CN/binary, ";PW=", PW/binary, ";MN=", MN/binary, ";Flag=", Flag/binary, ";CP=&&", CP/binary, "&&">>, Len = dgiot_hjt212_utils:get_len(Rdata), Crc = dgiot_hjt212_utils:crc16(Rdata), <<"##", Len/binary, Rdata/binary, Crc/binary, "\r\n">>.
acfbe9962543cc01587374f06b43ecc4f1484eae1d40a578faadd9ab8110e56f
vrnithinkumar/ETC
grad.erl
-module(grad). % -export([pattern_test/1]). -spec pattern_test(integer()) -> {}. pattern_test(1) -> true; pattern_test(X) -> {}.
null
https://raw.githubusercontent.com/vrnithinkumar/ETC/b2954186e2bc56d9308bb9858c98b6dbe9c3c6ac/btc_test_suit/test_cases/grad.erl
erlang
-export([pattern_test/1]).
-module(grad). -spec pattern_test(integer()) -> {}. pattern_test(1) -> true; pattern_test(X) -> {}.
48e7144e7ec7cfe0d69d110b97d4a6e2ecd33039b05074a4354403d5eace5272
hemml/OMGlib
omgui.lisp
(defpackage :omgui (:use cl omg jscl bordeaux-threads omgdaemon) (:export add-event-handler add-style add-youtube-player append-element async-bind allow-page-close browser-case check-element close-current-dialog create-element dialog-ok disable-back-button disable-scroll dragabble-list dragabble-list-elements dragabble-list-insert dragabble-list-insert-position element-width element-height enable-back-button enable-scroll ensure-element ensure-last-version execute-after find-widget gensym2 get-dialog-data get-element-id get-omg-cookie-name get-my-version js-get-element-by-id jsceil jsfloor jstrunc jsln jslog jsmax jsmin js-parse-float jssin jscos jstan jsasin jsacos jsatan jsatan2 jsrandom load-js-script local-storage make-dialog make-dragabble-list make-js-function make-js-object make-svg make-tab-form modal-dialog on-element-remove page-width page-height parent-element prevent-page-close register-hash-cb remove-element rm-event-handler session-storage show-notification visible-width visible-height visible-left visible-top winref)) (in-package :omgui) (defun-f winref (name) (jscl::oget (jscl::%js-vref "window") name)) (defun-f js-parse-float (s) (funcall (winref "parseFloat") (jscl::lisp-to-js s))) (defun-f local-storage (key &optional def) (let ((vl ((jscl::oget (winref "localStorage") "getItem") (jscl::lisp-to-js key)))) (if (jscl::js-null-p vl) def vl))) (defun-f (setf local-storage) (val key) ((jscl::oget (winref "localStorage") "setItem") (jscl::lisp-to-js key) val)) (defun-f session-storage (key &optional def) (let ((vl ((jscl::oget (winref "sessionStorage") "getItem") (jscl::lisp-to-js key)))) (if (jscl::js-null-p vl) def vl))) (defun-f (setf session-storage) (val key) ((jscl::oget (winref "sessionStorage") "setItem") (jscl::lisp-to-js key) val)) (defmacro-f async-bind (vcmd &rest cod) (let ((res (gensym))) `(funcall (jscl::oget (jscl::%js-vref "jscl") "omgAsyncRPC") (write-to-string (list ,(package-name *package*) ',(caadr vcmd) (list ,@(cdadr vcmd)) omg::*session-id*)) (lambda (,(car vcmd)) ,@cod)))) (defun-f make-svg (&rest cod) (labels ((process-cmd (cmd args) (let* ((symname (symbol-name cmd)) (symdown (string-downcase symname)) (el ((jscl::oget (jscl::%js-vref "document") "createElementNS") "" (if (equal symname (string-upcase symname)) symdown symname)))) (process-cmd-tail el args))) (process-cmd-tail (el cod) (if cod (cond ((symbolp (car cod)) (let* ((path (js-string-split (symbol-name (car cod)) #\.)) (obj (deep-oget-1 el path)) (fld (car (last path)))) (if (> (length path) 1) (jscl::oset (cadr cod) obj fld) ((jscl::oget el "setAttribute") (symbol-name (car cod)) (cadr cod))) (process-cmd-tail el (cddr cod)))) ((listp (car cod)) (progn ((jscl::oget el "appendChild") (process-cmd (caar cod) (cdar cod))) (process-cmd-tail el (cdr cod)))) ((stringp (car cod)) (let ((txt ((jscl::oget (jscl::%js-vref "document") "createTextNode") (car cod)))) ((jscl::oget el "appendChild") txt) (process-cmd-tail el (cdr cod)))) (t (progn (jslog "Invalid cmd:" (car cod)) (process-cmd-tail el (cdr cod))))) el))) (process-cmd :svg cod))) (defun-f system-font () "The system font for dialogs, etc. Defined as a function because functions are automatically updated in browsers." "1.2em Gill Sans,Gill Sans MT,Calibri,sans-serif") (defun-f jslog (&rest args) "Log function for js" (apply (jscl::oget (jscl::%js-vref "console") "log") args) nil) (defun-f jsrandom () "Return a random number in 0..1 range" (funcall (jscl::oget (jscl::%js-vref "Math") "random"))) (defun-f jsfloor (x) "Math.floor function" ((jscl::oget (jscl::%js-vref "Math") "floor") x)) (defun-f jsceil (x) "Math.ceil function" ((jscl::oget (jscl::%js-vref "Math") "ceil") x)) (defun-f jstrunc (x) "Math.trunc function" ((jscl::oget (jscl::%js-vref "Math") "trunc") x)) (defun-f jsln (&rest args) "Math.log function" (apply (jscl::oget (jscl::%js-vref "Math") "log") args)) (defun-f jssin (&rest args) "Math.sin function" (apply (jscl::oget (jscl::%js-vref "Math") "sin") args)) (defun-f jscos (&rest args) "Math.cos function" (apply (jscl::oget (jscl::%js-vref "Math") "cos") args)) (defun-f jstan (&rest args) "Math.tan function" (apply (jscl::oget (jscl::%js-vref "Math") "tan") args)) (defun-f jsasin (&rest args) "Math.asin function" (apply (jscl::oget (jscl::%js-vref "Math") "asin") args)) (defun-f jsacos (&rest args) "Math.acos function" (apply (jscl::oget (jscl::%js-vref "Math") "acos") args)) (defun-f jsatan (&rest args) "Math.atan function" (apply (jscl::oget (jscl::%js-vref "Math") "atan") args)) (defun-f jsatan2 (&rest args) "Math.atan2 function" (apply (jscl::oget (jscl::%js-vref "Math") "atan2") args)) (defun-f jsmin (&rest args) "Math.min function" (apply (jscl::oget (jscl::%js-vref "Math") "min") args)) (defun-f jsmax (&rest args) "Math.max function" (apply (jscl::oget (jscl::%js-vref "Math") "max") args)) (defun-f js-get-element-by-id (id) "Get DOM object by ID (must not be called on host!)" ((jscl::oget (jscl::%js-vref "document") "getElementById") id)) (defun-f check-element (id) "Check if element with ``id'' exists in DOM" (not (jscl::js-null-p (js-get-element-by-id id)))) (defun-f random-id () "Get an unique random string to use as a DOM id" (let* ((chrs "ABCDEFGHIJKLMOPQRSTUVWXYZ") (id (map 'string (lambda (x) (declare (ignore x)) (char chrs (jsfloor (* (jsrandom) (length chrs))))) (make-string 8)))) (if (check-element id) (random-id) id))) (defun-f get-element-id (el) "Returns an id of the element el" (let ((id (jscl::oget el "id"))) (if (> (length id) 0) id (let ((nid (random-id))) (setf (jscl::oget el "id") nid) nid)))) (defun-f js-string-split (path ch) "Split a string path by the character ch, much, much fater then JSCL function" (let* ((pos (position ch path)) (p0 (subseq path 0 pos))) (cons p0 (if pos (js-string-split (subseq path (+ pos 1)) ch) (list))))) (defun-f deep-oget-1 (el path) "Get a value of el.the.list.of.the.property.path" (if (cdr path) (deep-oget-1 (jscl::oget el (car path)) (cdr path)) el)) (defun-f create-element (typ &rest args) "Create and return a DOM element type ``typ'' and specified attributes: (create-element \"A\" '|href| \"\")" (let ((el ((jscl::oget (jscl::%js-vref "document") "createElement") typ))) (loop for (k v) on args by (function cddr) do (labels ((app-el (nel) (append-element (if (stringp v) ((jscl::oget (jscl::%js-vref "document") "createTextNode") nel) nel) el))) (cond ((equal k :append-element) (app-el v)) ((equal k :append-elements) (map nil #'app-el v)) ((equal k :add-style) (add-style el v)) (t (let* ((path (js-string-split (symbol-name k) #\.)) (obj (deep-oget-1 el path)) (fld (car (last path)))) (jscl::oset v obj fld)))))) el)) (defun-f append-element (el &optional parent) "Append the element el as a child to the parent" (let ((el1 (if (stringp el) ((jscl::oget (jscl::%js-vref "document") "createTextNode") el) el))) (if parent ((jscl::oget parent "appendChild") el1) ((jscl::oget (jscl::%js-vref "document") "body" "appendChild") el1)) el1)) (defun-f parent-element (el) "Get parent of the element el" (jscl::oget el "parentNode")) (defun-f remove-element (el) "Remove the element el from it's parent children" ((jscl::oget (parent-element el) "removeChild") el)) (defun-f element-width (el) "Get element width in pixels" (jscl::oget el "clientWidth")) (defun-f element-height (el) "Get element height in pixels" (jscl::oget el "clientHeight")) (defun-f page-width () "Get the browser page width" (jsmax (jscl::oget (jscl::%js-vref "document") "body" "scrollWidth") (jscl::oget (jscl::%js-vref "document") "documentElement" "scrollWidth") (jscl::oget (jscl::%js-vref "document") "body" "offsetWidth") (jscl::oget (jscl::%js-vref "document") "documentElement" "offsetWidth") (jscl::oget (jscl::%js-vref "document") "documentElement" "clientWidth"))) (defun-f page-height () "Get the browser page height" (jsmax (jscl::oget (jscl::%js-vref "document") "body" "scrollHeight") (jscl::oget (jscl::%js-vref "document") "documentElement" "scrollHeight") (jscl::oget (jscl::%js-vref "document") "body" "offsetHeight") (jscl::oget (jscl::%js-vref "document") "documentElement" "offsetHeight") (jscl::oget (jscl::%js-vref "document") "documentElement" "clientHeight"))) (defun-f visible-width () "Get the browser page visible width" (jscl::oget (jscl::%js-vref "document") "body" "clientWidth")) (defun-f visible-height () "Get the browser page visible height" (jscl::oget (jscl::%js-vref "document") "body" "clientHeight")) (defun-f visible-left () "Get the browser page left coordinate" (jscl::oget (jscl::%js-vref "document") "body" "scrollLeft")) (defun-f visible-top () "Get the browser page top coordinate" (jscl::oget (jscl::%js-vref "document") "body" "scrollTop")) (defparameter-f *scroll-disabled* nil) (defun-f disable-scroll () "Disable browser page scroll" (if (not *scroll-disabled*) (progn (setf (jscl::oget (jscl::%js-vref "document") "body" "style" "overflow") "hidden") (setf *scroll-disabled* t) t))) (defun-f enable-scroll () "Enable browser page scroll" (if *scroll-disabled* (progn (setf (jscl::oget (jscl::%js-vref "document") "body" "style" "overflow") "") (setf *scroll-disabled* nil) t))) (defun-f curtain () "Create a curtain, to shadow elements while modal dialog active" (create-element "div" :|style.opacity| "80%" :|style.background| "white" :|style.width| (page-width) :|style.height| (page-height) :|style.position| "absolute" :|style.top| "0" :|style.left| "0" :|class| "blurbg" :|zIndex| 100000)) (defun-f dialog-frame () "Create a modal dialog outer frame" (create-element "div" :|style.opacity| "0" :|style.border| "0.1em solid black" :|style.border-radius| "0.5em" :|style.padding| "0" :|style.overflowX| "hidden" :|style.width| "auto" :|style.background| "#fffff0" :|style.display| "inline-block" :|style.font| (system-font) :|style.boxShadow| "0.5em 0.5em 1em gray" :|style.position| "absolute" :|omgwidget| "dialog" :|zIndex| 200000)) (defun-f dialog-header (header) "Create a modal dialog header" (let* ((hdr (create-element "div" :|style.width| "auto" :|style.background| "#a0f0a0" :|style.padding| "0.5em" :|style.minHeight| "1em" :|innerHTML| (if header header ""))) (close-btn (create-element "div" :|style.width| "0.75em" :|style.height| "0.75em" :|style.margin| "0" :|style.borderRadius| "0.2em" :|style.background| "red" :|style.float| "right" :|style.boxShadow| "0 0 0.5em grey" :|style.cursor| "pointer" :|title| "close" :|onclick| #'close-current-dialog))) (append-element close-btn hdr) hdr)) (defun-f execute-after (tim cb) "Schedule an execution of cb after tim seconds" (funcall (jscl::%js-vref "setTimeout") cb (* tim 1000.0))) (defparameter-f *dialog-stack* nil) (defun-f form-line (key txt &optional params) "Create modal dialog table line" (let* ((row (create-element "div" :|style.display| "table-row" :|style.width| "auto")) (c1 (create-element "div" :|style.display| "table-cell" :|style.padding| "0.3em" :|style.width| "auto" :|style.text-align| "right" :|style.fontWeight| "lighter" :|style.verticalAlign| "bottom" :|innerHTML| txt)) (c2 (create-element "div" :|style.display| "table-cell" :|style.padding| "0.3em" :|style.width| "50%" :|style.verticalAlign| "bottom")) (typ (getf params :type)) (def1 (getf params :default)) (def (if def1 def1 "")) (inp (create-element "input" :|type| (if typ typ "text") :|value| def :|style.font| "inherit" :|style.fontStyle| "italic" :|style.fontWeight| "lighter" :|style.width| "100%")) (last-val def) (cb (getf params :filter)) (current-dialog (car *dialog-stack*)) (data (cdr (assoc :data current-dialog)))) (if (not (assoc key data)) (progn (push (cons key def) data) (setf (cdr (assoc :data current-dialog)) data))) (labels ((tcb (ev) ;; the callback is called after every field update (execute-after 0 (lambda () (let ((val (jscl::oget inp "value"))) (if (not (equal last-val val)) (let ((new-val (if cb (funcall cb val) val)) (current-dialog (car *dialog-stack*)) (data (cdr (assoc :data current-dialog)))) (setf last-val (if (stringp new-val) new-val val)) (if (stringp new-val) (let ((selection-start (jscl::oget inp "selectionStart")) (selection-end (jscl::oget inp "selectionEnd"))) (setf (jscl::oget inp "value") new-val) (if (not (assoc key data)) (push (cons key new-val) data) (setf (cdr (assoc key data)) new-val)) JSCL bug workaround ((jscl::oget inp "setSelectionRange") selection-start selection-end)))))))) t)) (setf (jscl::oget inp "onchange") #'tcb) (setf (jscl::oget inp "onkeyup") #'tcb) (setf (jscl::oget inp "onkeydown") #'tcb) (setf (jscl::oget inp "onpaste") #'tcb) (setf (jscl::oget inp "ondrop") #'tcb)) (append-element inp c2) (append-element c1 row) (append-element c2 row) row)) (defun-f form-button-row (btns) "Create a row with buttons for dialog" (let* ((row (create-element "div" :|style.display| "table-caption" :|style.width| "auto" :|style.captionSide| "bottom")) (cl (create-element "div" :|style.display| "flex" :|style.width| "100%" :|style.height| "100%" :|style.text-align| "center" :|style.justifyContent| "center" :|style.alignItems| "center" :|style.paddingBottom| "0.5em"))) (map nil (lambda (b) (cond ((listp b) (append-element (create-element "button" :|innerHTML| (car b) :|style.marginBottom| "0.3em" :|style.marginLeft| "1em" :|style.marginRight| "1em" :|onclick| (lambda (ev) (funcall (eval (cadr b))))) cl)))) btns) (append-element cl row) row)) (defun-f dialog-table (lines) "Create modal dialog table" (let ((tbl (create-element "div" :|style.display| "table" :|style.width| "auto" :|style.padding| "1em"))) (loop for (k v) on lines by (function cddr) do (if (equal k :buttons) (append-element (form-button-row v) tbl) (if (listp v) (cond ((stringp (car v)) (append-element (form-line k (car v) (cdr v)) tbl))) (append-element (form-line k v) tbl)))) tbl)) (defparameter *dialog-wait-list* (make-hash-table)) (defun-r dialog-wl-send (id dat) (let ((sem (gethash id *dialog-wait-list*))) (if sem (progn (setf (gethash id *dialog-wait-list*) (remove-if (lambda (x) (equal (car x) 'dialog-id)) dat)) (signal-semaphore sem)))) nil) (defun-f close-current-dialog (&optional ev no-sem) (let ((current-dialog (pop *dialog-stack*))) (if (assoc :scroll-disabled current-dialog) (enable-scroll)) (let* ((outer (cdr (assoc :outer current-dialog))) (curtain (cdr (assoc :curtain current-dialog))) (dat (cdr (assoc :data current-dialog))) (id (assoc 'dialog-id dat))) (if outer (remove-element outer)) (if curtain (remove-element curtain)) (if (and (cdr id) (not no-sem)) (dialog-wl-send (cdr id) nil))))) (defun-f get-dialog-data () (cdr (assoc :data (car *dialog-stack*)))) (defun-f make-dialog (header-text dialog-text &key lines id) "Create modal dialog with header, text and lines. " (let* ((curtain (curtain)) (outer (dialog-frame))) (setf *dialog-stack* (cons (list (cons :scroll-disabled (disable-scroll)) (cons :curtain curtain) (cons :outer outer) (cons :data (list (cons 'dialog-id id)))) *dialog-stack*)) (let* ((hdr (dialog-header header-text)) (tbl (dialog-table lines)) (txt (create-element "div" :|innerHTML| dialog-text :|style.fontWeight| "lighter" :|style.marginTop| "1em" :|style.marginLeft| "1em" :|style.marginRight| "1em" :|style.width| "auto"))) (append-element hdr outer) (if dialog-text (append-element txt outer)) (append-element tbl outer) (append-element curtain) (append-element outer) (setf (jscl::oget outer "style" "left") (jscl::concat (write-to-string (+ (visible-left) (jsfloor (/ (- (visible-width) (element-width outer)) 2)))) "px")) (setf (jscl::oget outer "style" "top") (jscl::concat (write-to-string (+ (visible-top) (jsfloor (/ (- (visible-height) (element-height outer)) 2)))) "px")) (setf (jscl::oget outer "style" "opacity") "100%") (get-element-id curtain)))) (defun-f dialog-ok () (let* ((current-dialog (car *dialog-stack*)) (dat (cdr (assoc :data current-dialog))) (id (assoc 'dialog-id dat))) (close-current-dialog nil t) (if id (dialog-wl-send (cdr id) dat)))) (defmacro modal-dialog (header-text dialog-text &key lines) `(if (current-session-id) (let* ((id (intern (symbol-name (omg::random-key *dialog-wait-list*)) :omgui)) (sem (make-semaphore)) (ht ,header-text) (dt ,dialog-text) (lins ,lines)) (setf (gethash id *dialog-wait-list*) sem) (if (remote-exec `(make-dialog ,ht ,dt :lines ',lins :id ',id)) (progn (wait-on-semaphore sem) (let ((res (gethash id *dialog-wait-list*))) (remhash id *dialog-wait-list*) res)))))) (defun-f load-js-script (src &optional onload) (let ((el (create-element "script" :|src| src))) (if onload (setf (jscl::oget el "onload") onload)) (append-element el))) (defun-f make-js-function (name code) (setf (jscl::oget (jscl::%js-vref "window") name) code)) (defun-f make-js-object (&rest plist) (let ((obj (jscl::new))) (loop for (k v) on plist by #'cddr do (setf (jscl::oget obj (symbol-name k)) v)) obj)) (defun-f allow-page-close () (setf *disable-page-unload* nil) nil) (defparameter-f *disable-back* nil) (defparameter-f *backcnt* 0) (defparameter-f *fback* t) (defparameter-f *onpopstate-installed* nil) (defun-f disable-back-button (&optional cb) (if (not *onpopstate-installed*) (progn ((jscl::oget (jscl::%js-vref "history") "pushState") "" "" (jscl::oget (jscl::%js-vref "window") "location" "href")) ((jscl::oget (jscl::%js-vref "history") "back")) (setf *onpopstate-installed* t) (setf (jscl::oget (jscl::%js-vref "window") "onpopstate") (lambda (ev) JSCL bug workaround (fb *fback*)) (setf *backcnt* (+ 1 *backcnt*)) (if *disable-back* ((jscl::oget (jscl::%js-vref "history") "forward"))) (if (equal bcnt 1) (progn (if (and cb (not fb)) (funcall cb)) (setf *fback* nil) (setf *backcnt* 0)))))))) (setf *disable-back* t) nil) (defun-f enable-back-button () (setf *disable-back* nil) ((jscl::oget (jscl::%js-vref "history") "back")) nil) (defparameter-f *beforeunload-installed* nil) (defparameter-f *disable-page-unload* nil) (defun-f prevent-page-close () (if (not *beforeunload-installed*) (progn ((jscl::oget (jscl::%js-vref "window") "addEventListener") "beforeunload" (lambda (ev) (if *disable-page-unload* (progn ((jscl::oget ev "preventDefault")) (setf (jscl::oget ev "returnValue") ""))))) (setf *beforeunload-installed* t))) (setf *disable-page-unload* t) nil) (defparameter-f *youtube-js-loaded* nil) (defun-f add-youtube-player (element &key onready onstatechange onqualitychange onratechange onerror onapichange width height video-id) (let ((cfg (make-js-object :|events| (make-js-object :|onReady| (lambda (ev) (setf *youtube-js-loaded* t) (if onready (funcall onready ev))) :|onStateChange| (lambda (ev) (if onstatechange (funcall onstatechange ev))) :|onPlaybackQualityChange| (lambda (ev) (if onqualitychange (funcall onqualitychange ev))) :|onPlaybackRateChange| (lambda (ev) (if onratechange (funcall onratechange ev))) :|onError| (lambda (ev) (if onerror (funcall onerror ev))) :|onApiChange| (lambda (ev) (if onapichange (funcall onapichange ev))))))) (if width (setf (jscl::oget cfg "width") width)) (if height (setf (jscl::oget cfg "height") height)) (if video-id (setf (jscl::oget cfg "videoId") video-id)) (labels ((make-player () (jscl::make-new (jscl::oget (jscl::%js-vref "YT") "Player") element cfg))) (if (not *youtube-js-loaded*) (progn (make-js-function "onYouTubeIframeAPIReady" (lambda () (jslog "YouTube API loaded") (setf *youtube-js-loaded* t) (make-player))) (load-js-script "")) (make-player)))) nil) (defparameter-f *hash-change-cbs* nil) (defun-f register-hash-cb (hsh cb) (labels ((mcb (&optional ev) (let* ((hs (jscl::oget (jscl::%js-vref "location") "hash")) (cb (assoc hs *hash-change-cbs* :test #'equal))) (if cb (funcall (cdr cb)))))) (let ((need-mcb (not *hash-change-cbs*))) (push (cons hsh cb) *hash-change-cbs*) (if need-mcb (progn (setf (jscl::oget (jscl::%js-vref "window") "onhashchange") #'mcb) (mcb))))) nil) (defun-f gensym2 (&rest args) (intern (symbol-name (apply #'gensym args)))) ;; use: ;; (browser-case (: ( jslog " detected ! " ) ) ( (: firefox : chrome ) ( jslog " FF or Chrome ! " ) ) ;; (:opera (jslog "Opera!")) ;; (:edge (jslog "Edge!"))) ;; (t (jslog "Unknown browser!")) (defmacro-f browser-case (&rest cod) (let ((agent (gensym2)) (browser (gensym2))) `(let* ((,agent (string-downcase (jscl::oget (jscl::%js-vref "navigator") "userAgent"))) (,browser (cond ((or (search "chrome" ,agent) (search "chromium" ,agent) (search "crios" ,agent)) :chrome) ((or (search "firefox" ,agent) (search "fxios" ,agent)) :firefox) ((search "safari" ,agent) :safari) ((search "opr" ,agent) :opera) ((search "edg" ,agent) :edge) (t nil)))) (cond ,@(mapcar (lambda (c) `(,(if (listp (car c)) `(or ,@(mapcar (lambda (s) `(equal ,browser ,s)) (car c))) (if (equal t (car c)) (car c) `(equal ,browser ,(car c)))) ,@(cdr c))) cod))))) (defparameter-f *style-cache* nil) (defun-f add-style (el css-text) (let* ((sid (assoc css-text *style-cache* :test #'equal)) (chrs "ABCDEFGHIJKLMOPQRSTUVWXYZ") (clsid (if sid (cdr sid) (map 'string (lambda (x) (declare (ignore x)) (char chrs (jsfloor (* (jsrandom) (length chrs))))) (make-string 8))))) (if (not sid) (progn (append-element (create-element "style" :|innerHTML| (jscl::concat "." clsid css-text)) (jscl::oget (jscl::%js-vref "document") "head")) (push (cons css-text clsid) *style-cache*))) ((jscl::oget el "classList" "add") clsid))) (defparameter-f *notification-container* nil) (defun-f element-on-page-p (el) (or (equal el (jscl::%js-vref "document")) (and (not (jscl::js-null-p el)) (element-on-page-p (jscl::oget el "parentNode"))))) (defparameter-f *global-observer-handlers* nil) (defun-f on-element-remove (el cb) (if (not *global-observer-handlers*) (let ((obs (jscl::make-new (winref "MutationObserver") (lambda (&rest args) (let ((rems nil)) (map nil (lambda (eh) (if (not (element-on-page-p (car eh))) (if (not (funcall (cdr eh) (car eh))) (push eh rems)))) *global-observer-handlers*) (setf *global-observer-handlers* (remove-if (lambda (x) (position x rems :test #'equal)) *global-observer-handlers*)) nil))))) ((jscl::oget obs "observe") (jscl::oget (jscl::%js-vref "document") "body") (make-js-object :|childList| t)))) (push (cons el cb) *global-observer-handlers*)) (defun-f show-notification (header body &key period check) (let* ((frame (create-element "div" :|style.border| "1pt solid black" :|style.position| "relative" :|style.margin| "0.5em" :|style.background| "white" :|style.width| "15em" :|style.borderRadius| "0.2em" :|style.minHeight| "5em" :|style.boxShadow| "0 0 1em grey" :|style.right| 0 :|omgwidget| "notification")) (head-line (create-element "div" :|style.left| 0 :|style.right| 0 :|style.top| 0 :|style.padding| "0.25em" :|style.position| "relative" :|style.font| (omgui::system-font))) (close-btn (create-element "div" :|style.borderRadius| "0.2em" :|style.background| "red" :|style.right| "0.25em" :|style.top| "0.25em" :|style.width| "0.5em" :|style.aspectRatio| 1 :|style.boxShadow| "0 0 0.5em grey" :|style.cursor| "pointer" :|style.position| "absolute" :|title| "close" :|onclick| (lambda (ev) (remove-element frame)))) (body-cont (create-element "div" :|style.padding| "0.25em" :|style.font| (omgui::system-font))) (ncont (if *notification-container* *notification-container* (create-element "div" :|style.position| "absolute" :|style.right| 0 :|style.top| 0)))) (if (not *notification-container*) (progn (setf *notification-container* ncont) (append-element ncont))) (append-element header head-line) (append-element close-btn head-line) (append-element head-line frame) (append-element body body-cont) (append-element body-cont frame) (append-element frame ncont) (if period (on-element-remove frame (lambda (el) (if (or (not check) (funcall check)) (progn (execute-after period (lambda () (append-element frame ncont))) t) nil)))))) (defun-f find-widget (ev &optional type) (labels ((get-wg (el) (let ((w (jscl::oget el "omgwidget"))) (if (and w (or (not type) (equal w type))) el (let ((par (jscl::oget el "parentNode"))) (if (and par (not (jscl::js-null-p par))) (get-wg par))))))) (get-wg (jscl::oget ev "target")))) (defun-r need-reload () (and (not (equal *omg-version* +devel-version+)) (not (equal *omg-version* *omg-last-version*)))) (defun-r get-omg-cookie-name () +omg-version-cookie+) (defun-r get-last-version () *omg-last-version*) (defun-r get-my-version () *omg-version*) (defun-f ensure-last-version () (if (need-reload) (progn (setf (jscl::oget (jscl::%js-vref "document") "cookie") (format nil "~A=~A" (get-omg-cookie-name) (get-last-version))) ((jscl::oget (jscl::%js-vref "location") "reload") t)))) (defmacro-f ensure-element (e &rest body) (let ((fn (gensym2))) `(labels ((,fn () (if (> (jscl::oget ,e "clientWidth") 0) (progn ,@body) (execute-after 0.1 #',fn)))) (,fn)))) (defparameter-f *global-event-handlers* nil) (defun-f add-event-handler (path handler) (let ((handlers (assoc path *global-event-handlers* :test #'equal))) (if (not handlers) (let* ((path-l (omgui::js-string-split path #\.)) (obj (omgui::deep-oget-1 (jscl::%js-vref "window") (butlast path-l)))) (setf (jscl::oget obj (car (last path-l))) (lambda (ev) (map nil (lambda (cb) (funcall cb ev)) (cdr (assoc path *global-event-handlers* :test #'equal))))) (push (cons path (list handler)) *global-event-handlers*)) (push handler (cdr handlers))))) (defun-f rm-event-handler (path handler) (setf *global-event-handlers* (mapcar (lambda (hnd) (if (equal path (car hnd)) (cons path (remove-if (lambda (h) (equal h handler)) (cdr hnd))) hnd)) *global-event-handlers*))) (defun-f make-tab-form (tab-list) (let* ((tab-div (create-element "div" :|style.display| "flex" :|style.position| "relative")) (content (create-element "div" :|style.padding| "1em" :|style.borderLeft| "1px solid gray" :|style.borderRight| "1px solid gray" :|style.borderBottom| "1px solid gray")) (outer (create-element "div" :append-element tab-div :append-element content)) (tbs nil)) (map nil (lambda (tab num) (append-element (let ((tb (create-element "div" :|style.borderTop| "1px solid gray" :|style.borderLeft| "1px solid gray" :|style.borderRight| "1px solid gray" :|style.borderBottom| (if (= 0 num) "none" "1px solid gray") :|style.background| (if (= 0 num) "#ffffff" "#f0f0f0") :|style.paddingTop| "0.25em" :|style.paddingBottom| "0.25em" :|style.paddingLeft| "1em" :|style.paddingRight| "1em" :|style.borderRadius| "0.5em 0.5em 0 0" :|style.display| "inline-block" :append-element (create-element "a" :|href| "#" :append-element (car tab) :|onclick| (lambda (ev) (map nil (lambda (tab) (setf (jscl::oget (cdr tab) "style" "display") "none") (setf (jscl::oget (cdr tab) "style" "display") "none")) tab-list) (map nil (lambda (th tn) (setf (jscl::oget th "style" "background") (if (= tn num) "#ffffff" "#f0f0f0")) (setf (jscl::oget th "style" "borderBottom") (if (= tn num) "none" "1px solid gray"))) tbs (loop for i below (length tbs) collect i)) (setf (jscl::oget (cdr tab) "style" "display") "block") nil))))) (setf tbs `(,@tbs ,tb)) (setf (jscl::oget (cdr tab) "style" "display") (if (= num 0) "block" "none")) (append-element (cdr tab) content) tb) tab-div)) tab-list (loop for i below (length tab-list) collect i)) (append-element (create-element "div" :|style.display| "inline-block" :|style.width| "auto" :|style.borderBottom| "1px solid gray" :|style.flexGrow| 1) tab-div) outer)) (defun-f make-dragabble-list (elements &key (outer-type "div") reorder-cb on-drag insert-el) (let* ((trans "all 0.5s linear") (insert-gizmo (if insert-el (create-element outer-type :|style.position| "absolute" :|style.right| "100%" :|style.z-index| 20 :|style.display| "block" :|style.visibility| (if elements "hidden" "visible") :|style.transition| "opacity 0.5s linear" :append-element insert-el))) (insert-gizmo-width nil) (inner (create-element "div" :|style.position| "relative")) (moving-el nil) (moving-el-height nil) (moving-el-num nil) (max-top nil) (last-shift nil) (els-pos nil) (els-mid nil) (element-stack nil) (client-y0 nil) (page-y0 nil) (cur-top nil) (last-min-pos nil)) (if insert-el (progn (add-style insert-gizmo ":hover {cursor: pointer;}") (setf (jscl::oget insert-gizmo "onmouseover") (lambda (ev) (if (and (not moving-el) last-min-pos) (progn (setf (jscl::oget inner"omg-insert-position") last-min-pos) (loop for i from (max 0 last-min-pos) to (min last-min-pos (- (length element-stack) 1)) do (progn (setf (jscl::oget (nth i element-stack) "style" "transition") "all 0.1s linear") (setf (jscl::oget (nth i element-stack) "style" "transform") (if (< i last-min-pos) "translateY(-0.5em)" "translateY(0.5em)")))))))) (setf (jscl::oget insert-gizmo "onmouseout") (lambda (ev) (if (and (not moving-el) last-min-pos) (progn (setf (jscl::oget inner "omg-insert-position") nil) (map nil (lambda (el) (setf (jscl::oget el "style" "transform") "translateY(0)")) element-stack))))) (append-element insert-gizmo inner) (setf (jscl::oget inner "omg-insert-position") nil))) (labels ((set-els-pos () (setf els-pos (mapcar (lambda (el) (let ((top (jscl::oget el "offsetTop"))) (cons top (+ top (jscl::oget el "offsetHeight"))))) element-stack)) (setf els-mid (mapcar (lambda (pos) (* 0.5 (+ (car pos) (cdr pos)))) els-pos))) (up-handler (ev) (if moving-el (progn (setf (jscl::oget moving-el "style" "top") 0) (if insert-el (setf (jscl::oget insert-gizmo "style" "display") "block")) (map nil (lambda (el) (if (not (equal el moving-el)) (progn (setf (jscl::oget el "style" "transition") "none") (setf (jscl::oget el "style" "transform") "translateY(0)")) (setf (jscl::oget el "style" "transform") (format nil "translateY(~Apx)" (- cur-top (car (nth last-shift els-pos))))))) element-stack) (let ((el moving-el)) (execute-after 0.1 (lambda () (setf (jscl::oget el "style" "scale") "100%") (setf (jscl::oget el "style" "boxShadow") "0 0 0") (setf (jscl::oget el "style" "zIndex") 10) (setf (jscl::oget el "style" "transform") "translateY(0)")))) (if (and (not (equal moving-el-num last-shift)) (not (and reorder-cb (not (funcall reorder-cb moving-el-num last-shift inner))))) (progn (remove-element moving-el) (if (> last-shift moving-el-num) (if (not (equal last-shift (- (length element-stack) 1))) ((jscl::oget inner "insertBefore") moving-el (nth (+ last-shift 1) element-stack)) (append-element moving-el inner)) ((jscl::oget inner "insertBefore") moving-el (nth last-shift element-stack))) (if (> last-shift moving-el-num) (setf element-stack `(,@(subseq element-stack 0 moving-el-num) ,@(subseq element-stack (+ 1 moving-el-num) (+ last-shift 1)) ,moving-el ,@(subseq element-stack (+ last-shift 1)))) (setf element-stack `(,@(subseq element-stack 0 last-shift) ,moving-el ,@(subseq element-stack last-shift moving-el-num) ,@(subseq element-stack (+ 1 moving-el-num))))) (setf (jscl::oget inner "omg-list-elements") (mapcar (lambda (el) (jscl::oget el "omg-orig-element")) element-stack)))) (setf moving-el nil) (setf last-shift nil) (set-els-pos)))) (move-handler (ev) (let* ((x1 (jscl::oget ev "pageX")) (y1 (jscl::oget ev "pageY"))) (if moving-el (progn (setf cur-top (max 0 (min max-top (+ (- y1 page-y0) client-y0)))) (setf (jscl::oget moving-el "style" "top") (format nil "~Apx" (- cur-top client-y0))) ((jscl::oget (funcall (winref "getSelection")) "empty")) ((jscl::oget ev "stopPropagation")) (let* ((mid (+ cur-top (* 0.5 moving-el-height))) (pos (position-if (lambda (el) (and (> mid (car el)) (< mid (cdr el)))) els-pos))) (if (and pos (not (equal pos last-shift))) (let ((ls1 (if last-shift last-shift pos))) (loop for i from (max 0 (min (- ls1 1) pos)) to (min (- (length element-stack) 1) (max (+ ls1 1) pos)) do (setf (jscl::oget (nth i element-stack) "style" "transform") (format nil "translateY(~Apx)" (cond ((and (>= i pos) (< i moving-el-num)) moving-el-height) ((and (<= i pos) (> i moving-el-num)) (- moving-el-height)) (t 0))))) (setf last-shift pos) (if on-drag (funcall on-drag moving-el pos))))) nil) (if (and insert-el insert-gizmo-width) (let* ((rect ((jscl::oget inner "getBoundingClientRect"))) (top (+ (jscl::oget rect "top") (winref "scrollY"))) (left (+ (jscl::oget rect "left") (winref "scrollX"))) (y1 (- y1 top)) (minpos (if els-mid (if (< y1 (car els-mid)) '(0 . 0) (if (> y1 (car (last els-mid))) `(,(cdar (last els-pos)) . ,(length els-mid)) (loop for i below (length els-mid) when (< y1 (nth i els-mid)) return `(,(cdr (nth (- i 1) els-pos)) . ,i))))))) (if (and (< x1 (+ left (* 0.5 (jscl::oget rect "width")))) (> x1 (- left (* 2 insert-gizmo-width)))) (if (not (equal (jscl::oget insert-gizmo "style" "display") "block")) (progn (setf (jscl::oget insert-gizmo "style" "display") "block") (setf (jscl::oget insert-gizmo "style" "visibility") "visible") (setf (jscl::oget insert-gizmo "style" "opacity") 0) (ensure-element insert-gizmo (setf (jscl::oget insert-gizmo "style" "opacity") 1))) (progn (if (not (equal last-min-pos (cdr minpos))) (progn (setf (jscl::oget insert-gizmo "style" "top") (car minpos)) (setf last-min-pos (cdr minpos)))))) (if (and els-mid (equal (jscl::oget insert-gizmo "style" "display") "block")) (progn (setf (jscl::oget insert-gizmo "style" "opacity") 0) (execute-after 0.5 (lambda () (setf (jscl::oget insert-gizmo "style" "display") "none"))))))))))) (make-rec (el) (let* ((rec (create-element "div" :|style.position| "relative" :|style.transition| trans :|style.zIndex| 10 :append-element el))) (setf (jscl::oget rec "omg-orig-element") el) (setf (jscl::oget rec "onmousedown") (lambda (ev) (if (equal (jscl::oget ev "button") 0) (progn (if insert-el (setf (jscl::oget insert-gizmo "style" "display") "none")) (setf moving-el rec) (setf moving-el-num (position rec element-stack)) (setf (jscl::oget rec "style" "scale") "101%") (setf (jscl::oget rec "style" "boxShadow") "0 0 1em 0.2em #909090") (setf (jscl::oget rec "style" "zIndex") 100) (setf client-y0 (- (jscl::oget ((jscl::oget rec "getBoundingClientRect")) "top") (jscl::oget ((jscl::oget inner "getBoundingClientRect")) "top"))) (setf cur-top client-y0) (setf page-y0 (jscl::oget ev "pageY")) (setf max-top (- (jscl::oget inner "offsetHeight") (jscl::oget rec "offsetHeight"))) (set-els-pos) ( jscl::oget rec " " ) ) (map nil (lambda (el) (setf (jscl::oget el "style" "transition") trans)) element-stack) (setf (jscl::oget rec "style" "transition") "all 0.1s linear"))))) rec))) (setf element-stack (mapcar (lambda (el) (let ((rec (make-rec el))) (append-element rec inner) rec)) elements)) (ensure-element inner (set-els-pos)) (setf (jscl::oget inner "omg-list-elements") elements) (setf (jscl::oget inner "omg-insert-fn") (lambda (el pos) (let ((rec (make-rec el))) (setf (jscl::oget rec "style" "transition") "none") (setf (jscl::oget rec "style" "visibility") "hidden") (setf (jscl::oget rec "style" "opacity") 0) (append-element rec inner) (ensure-element rec (let ((h (jscl::oget ((jscl::oget rec "getBoundingClientRect")) "height"))) (remove-element rec) (loop for i below (length element-stack) for el = (nth i element-stack) do (progn (setf (jscl::oget el "style" "transition") "none") (if (>= i pos) (setf (jscl::oget el "style" "transform") (format nil "translateY(~Apx)" (- h)))))) (if (>= pos (length element-stack)) (append-element rec inner) ((jscl::oget inner "insertBefore") rec (nth pos element-stack))) (setf element-stack `(,@(subseq element-stack 0 pos) ,rec ,@(subseq element-stack pos))) (setf (jscl::oget inner "omg-list-elements") (mapcar (lambda (el) (jscl::oget el "omg-orig-element")) element-stack)) (execute-after 0.1 (lambda () (setf (jscl::oget rec "style" "transition") trans) (setf (jscl::oget rec "style" "visibility") "visible") (setf (jscl::oget rec "style" "opacity") 1) (map nil (lambda (el) (setf (jscl::oget el "style" "transition") trans) (setf (jscl::oget el "style" "transform") "translateY(0)")) element-stack) (execute-after 0.5 (lambda () (set-els-pos)))))))))) (ensure-element insert-gizmo (setf insert-gizmo-width (jscl::oget ((jscl::oget insert-gizmo "getBoundingClientRect")) "width"))) (add-event-handler "document.onmouseup" #'up-handler) (add-event-handler "document.onmousemove" #'move-handler) (on-element-remove inner (lambda (el) (rm-event-handler "document.onmouseup" #'up-handler) (rm-event-handler "document.onmousemove" #'move-handler))) inner))) (defun-f dragabble-list-elements (inner) (jscl::oget inner "omg-list-elements")) (defun-f dragabble-list-insert-position (inner) (if (dragabble-list-elements inner) (jscl::oget inner "omg-insert-position") 0)) (defun-f dragabble-list-insert (inner el &optional pos) (funcall (jscl::oget inner "omg-insert-fn") el (if pos pos (dragabble-list-insert-position inner))))
null
https://raw.githubusercontent.com/hemml/OMGlib/4a9007e809eac2f066d8010484e4051188f74604/omgui.lisp
lisp
the callback is called after every field update use: (browser-case (:opera (jslog "Opera!")) (:edge (jslog "Edge!"))) (t (jslog "Unknown browser!"))
(defpackage :omgui (:use cl omg jscl bordeaux-threads omgdaemon) (:export add-event-handler add-style add-youtube-player append-element async-bind allow-page-close browser-case check-element close-current-dialog create-element dialog-ok disable-back-button disable-scroll dragabble-list dragabble-list-elements dragabble-list-insert dragabble-list-insert-position element-width element-height enable-back-button enable-scroll ensure-element ensure-last-version execute-after find-widget gensym2 get-dialog-data get-element-id get-omg-cookie-name get-my-version js-get-element-by-id jsceil jsfloor jstrunc jsln jslog jsmax jsmin js-parse-float jssin jscos jstan jsasin jsacos jsatan jsatan2 jsrandom load-js-script local-storage make-dialog make-dragabble-list make-js-function make-js-object make-svg make-tab-form modal-dialog on-element-remove page-width page-height parent-element prevent-page-close register-hash-cb remove-element rm-event-handler session-storage show-notification visible-width visible-height visible-left visible-top winref)) (in-package :omgui) (defun-f winref (name) (jscl::oget (jscl::%js-vref "window") name)) (defun-f js-parse-float (s) (funcall (winref "parseFloat") (jscl::lisp-to-js s))) (defun-f local-storage (key &optional def) (let ((vl ((jscl::oget (winref "localStorage") "getItem") (jscl::lisp-to-js key)))) (if (jscl::js-null-p vl) def vl))) (defun-f (setf local-storage) (val key) ((jscl::oget (winref "localStorage") "setItem") (jscl::lisp-to-js key) val)) (defun-f session-storage (key &optional def) (let ((vl ((jscl::oget (winref "sessionStorage") "getItem") (jscl::lisp-to-js key)))) (if (jscl::js-null-p vl) def vl))) (defun-f (setf session-storage) (val key) ((jscl::oget (winref "sessionStorage") "setItem") (jscl::lisp-to-js key) val)) (defmacro-f async-bind (vcmd &rest cod) (let ((res (gensym))) `(funcall (jscl::oget (jscl::%js-vref "jscl") "omgAsyncRPC") (write-to-string (list ,(package-name *package*) ',(caadr vcmd) (list ,@(cdadr vcmd)) omg::*session-id*)) (lambda (,(car vcmd)) ,@cod)))) (defun-f make-svg (&rest cod) (labels ((process-cmd (cmd args) (let* ((symname (symbol-name cmd)) (symdown (string-downcase symname)) (el ((jscl::oget (jscl::%js-vref "document") "createElementNS") "" (if (equal symname (string-upcase symname)) symdown symname)))) (process-cmd-tail el args))) (process-cmd-tail (el cod) (if cod (cond ((symbolp (car cod)) (let* ((path (js-string-split (symbol-name (car cod)) #\.)) (obj (deep-oget-1 el path)) (fld (car (last path)))) (if (> (length path) 1) (jscl::oset (cadr cod) obj fld) ((jscl::oget el "setAttribute") (symbol-name (car cod)) (cadr cod))) (process-cmd-tail el (cddr cod)))) ((listp (car cod)) (progn ((jscl::oget el "appendChild") (process-cmd (caar cod) (cdar cod))) (process-cmd-tail el (cdr cod)))) ((stringp (car cod)) (let ((txt ((jscl::oget (jscl::%js-vref "document") "createTextNode") (car cod)))) ((jscl::oget el "appendChild") txt) (process-cmd-tail el (cdr cod)))) (t (progn (jslog "Invalid cmd:" (car cod)) (process-cmd-tail el (cdr cod))))) el))) (process-cmd :svg cod))) (defun-f system-font () "The system font for dialogs, etc. Defined as a function because functions are automatically updated in browsers." "1.2em Gill Sans,Gill Sans MT,Calibri,sans-serif") (defun-f jslog (&rest args) "Log function for js" (apply (jscl::oget (jscl::%js-vref "console") "log") args) nil) (defun-f jsrandom () "Return a random number in 0..1 range" (funcall (jscl::oget (jscl::%js-vref "Math") "random"))) (defun-f jsfloor (x) "Math.floor function" ((jscl::oget (jscl::%js-vref "Math") "floor") x)) (defun-f jsceil (x) "Math.ceil function" ((jscl::oget (jscl::%js-vref "Math") "ceil") x)) (defun-f jstrunc (x) "Math.trunc function" ((jscl::oget (jscl::%js-vref "Math") "trunc") x)) (defun-f jsln (&rest args) "Math.log function" (apply (jscl::oget (jscl::%js-vref "Math") "log") args)) (defun-f jssin (&rest args) "Math.sin function" (apply (jscl::oget (jscl::%js-vref "Math") "sin") args)) (defun-f jscos (&rest args) "Math.cos function" (apply (jscl::oget (jscl::%js-vref "Math") "cos") args)) (defun-f jstan (&rest args) "Math.tan function" (apply (jscl::oget (jscl::%js-vref "Math") "tan") args)) (defun-f jsasin (&rest args) "Math.asin function" (apply (jscl::oget (jscl::%js-vref "Math") "asin") args)) (defun-f jsacos (&rest args) "Math.acos function" (apply (jscl::oget (jscl::%js-vref "Math") "acos") args)) (defun-f jsatan (&rest args) "Math.atan function" (apply (jscl::oget (jscl::%js-vref "Math") "atan") args)) (defun-f jsatan2 (&rest args) "Math.atan2 function" (apply (jscl::oget (jscl::%js-vref "Math") "atan2") args)) (defun-f jsmin (&rest args) "Math.min function" (apply (jscl::oget (jscl::%js-vref "Math") "min") args)) (defun-f jsmax (&rest args) "Math.max function" (apply (jscl::oget (jscl::%js-vref "Math") "max") args)) (defun-f js-get-element-by-id (id) "Get DOM object by ID (must not be called on host!)" ((jscl::oget (jscl::%js-vref "document") "getElementById") id)) (defun-f check-element (id) "Check if element with ``id'' exists in DOM" (not (jscl::js-null-p (js-get-element-by-id id)))) (defun-f random-id () "Get an unique random string to use as a DOM id" (let* ((chrs "ABCDEFGHIJKLMOPQRSTUVWXYZ") (id (map 'string (lambda (x) (declare (ignore x)) (char chrs (jsfloor (* (jsrandom) (length chrs))))) (make-string 8)))) (if (check-element id) (random-id) id))) (defun-f get-element-id (el) "Returns an id of the element el" (let ((id (jscl::oget el "id"))) (if (> (length id) 0) id (let ((nid (random-id))) (setf (jscl::oget el "id") nid) nid)))) (defun-f js-string-split (path ch) "Split a string path by the character ch, much, much fater then JSCL function" (let* ((pos (position ch path)) (p0 (subseq path 0 pos))) (cons p0 (if pos (js-string-split (subseq path (+ pos 1)) ch) (list))))) (defun-f deep-oget-1 (el path) "Get a value of el.the.list.of.the.property.path" (if (cdr path) (deep-oget-1 (jscl::oget el (car path)) (cdr path)) el)) (defun-f create-element (typ &rest args) "Create and return a DOM element type ``typ'' and specified attributes: (create-element \"A\" '|href| \"\")" (let ((el ((jscl::oget (jscl::%js-vref "document") "createElement") typ))) (loop for (k v) on args by (function cddr) do (labels ((app-el (nel) (append-element (if (stringp v) ((jscl::oget (jscl::%js-vref "document") "createTextNode") nel) nel) el))) (cond ((equal k :append-element) (app-el v)) ((equal k :append-elements) (map nil #'app-el v)) ((equal k :add-style) (add-style el v)) (t (let* ((path (js-string-split (symbol-name k) #\.)) (obj (deep-oget-1 el path)) (fld (car (last path)))) (jscl::oset v obj fld)))))) el)) (defun-f append-element (el &optional parent) "Append the element el as a child to the parent" (let ((el1 (if (stringp el) ((jscl::oget (jscl::%js-vref "document") "createTextNode") el) el))) (if parent ((jscl::oget parent "appendChild") el1) ((jscl::oget (jscl::%js-vref "document") "body" "appendChild") el1)) el1)) (defun-f parent-element (el) "Get parent of the element el" (jscl::oget el "parentNode")) (defun-f remove-element (el) "Remove the element el from it's parent children" ((jscl::oget (parent-element el) "removeChild") el)) (defun-f element-width (el) "Get element width in pixels" (jscl::oget el "clientWidth")) (defun-f element-height (el) "Get element height in pixels" (jscl::oget el "clientHeight")) (defun-f page-width () "Get the browser page width" (jsmax (jscl::oget (jscl::%js-vref "document") "body" "scrollWidth") (jscl::oget (jscl::%js-vref "document") "documentElement" "scrollWidth") (jscl::oget (jscl::%js-vref "document") "body" "offsetWidth") (jscl::oget (jscl::%js-vref "document") "documentElement" "offsetWidth") (jscl::oget (jscl::%js-vref "document") "documentElement" "clientWidth"))) (defun-f page-height () "Get the browser page height" (jsmax (jscl::oget (jscl::%js-vref "document") "body" "scrollHeight") (jscl::oget (jscl::%js-vref "document") "documentElement" "scrollHeight") (jscl::oget (jscl::%js-vref "document") "body" "offsetHeight") (jscl::oget (jscl::%js-vref "document") "documentElement" "offsetHeight") (jscl::oget (jscl::%js-vref "document") "documentElement" "clientHeight"))) (defun-f visible-width () "Get the browser page visible width" (jscl::oget (jscl::%js-vref "document") "body" "clientWidth")) (defun-f visible-height () "Get the browser page visible height" (jscl::oget (jscl::%js-vref "document") "body" "clientHeight")) (defun-f visible-left () "Get the browser page left coordinate" (jscl::oget (jscl::%js-vref "document") "body" "scrollLeft")) (defun-f visible-top () "Get the browser page top coordinate" (jscl::oget (jscl::%js-vref "document") "body" "scrollTop")) (defparameter-f *scroll-disabled* nil) (defun-f disable-scroll () "Disable browser page scroll" (if (not *scroll-disabled*) (progn (setf (jscl::oget (jscl::%js-vref "document") "body" "style" "overflow") "hidden") (setf *scroll-disabled* t) t))) (defun-f enable-scroll () "Enable browser page scroll" (if *scroll-disabled* (progn (setf (jscl::oget (jscl::%js-vref "document") "body" "style" "overflow") "") (setf *scroll-disabled* nil) t))) (defun-f curtain () "Create a curtain, to shadow elements while modal dialog active" (create-element "div" :|style.opacity| "80%" :|style.background| "white" :|style.width| (page-width) :|style.height| (page-height) :|style.position| "absolute" :|style.top| "0" :|style.left| "0" :|class| "blurbg" :|zIndex| 100000)) (defun-f dialog-frame () "Create a modal dialog outer frame" (create-element "div" :|style.opacity| "0" :|style.border| "0.1em solid black" :|style.border-radius| "0.5em" :|style.padding| "0" :|style.overflowX| "hidden" :|style.width| "auto" :|style.background| "#fffff0" :|style.display| "inline-block" :|style.font| (system-font) :|style.boxShadow| "0.5em 0.5em 1em gray" :|style.position| "absolute" :|omgwidget| "dialog" :|zIndex| 200000)) (defun-f dialog-header (header) "Create a modal dialog header" (let* ((hdr (create-element "div" :|style.width| "auto" :|style.background| "#a0f0a0" :|style.padding| "0.5em" :|style.minHeight| "1em" :|innerHTML| (if header header ""))) (close-btn (create-element "div" :|style.width| "0.75em" :|style.height| "0.75em" :|style.margin| "0" :|style.borderRadius| "0.2em" :|style.background| "red" :|style.float| "right" :|style.boxShadow| "0 0 0.5em grey" :|style.cursor| "pointer" :|title| "close" :|onclick| #'close-current-dialog))) (append-element close-btn hdr) hdr)) (defun-f execute-after (tim cb) "Schedule an execution of cb after tim seconds" (funcall (jscl::%js-vref "setTimeout") cb (* tim 1000.0))) (defparameter-f *dialog-stack* nil) (defun-f form-line (key txt &optional params) "Create modal dialog table line" (let* ((row (create-element "div" :|style.display| "table-row" :|style.width| "auto")) (c1 (create-element "div" :|style.display| "table-cell" :|style.padding| "0.3em" :|style.width| "auto" :|style.text-align| "right" :|style.fontWeight| "lighter" :|style.verticalAlign| "bottom" :|innerHTML| txt)) (c2 (create-element "div" :|style.display| "table-cell" :|style.padding| "0.3em" :|style.width| "50%" :|style.verticalAlign| "bottom")) (typ (getf params :type)) (def1 (getf params :default)) (def (if def1 def1 "")) (inp (create-element "input" :|type| (if typ typ "text") :|value| def :|style.font| "inherit" :|style.fontStyle| "italic" :|style.fontWeight| "lighter" :|style.width| "100%")) (last-val def) (cb (getf params :filter)) (current-dialog (car *dialog-stack*)) (data (cdr (assoc :data current-dialog)))) (if (not (assoc key data)) (progn (push (cons key def) data) (setf (cdr (assoc :data current-dialog)) data))) (execute-after 0 (lambda () (let ((val (jscl::oget inp "value"))) (if (not (equal last-val val)) (let ((new-val (if cb (funcall cb val) val)) (current-dialog (car *dialog-stack*)) (data (cdr (assoc :data current-dialog)))) (setf last-val (if (stringp new-val) new-val val)) (if (stringp new-val) (let ((selection-start (jscl::oget inp "selectionStart")) (selection-end (jscl::oget inp "selectionEnd"))) (setf (jscl::oget inp "value") new-val) (if (not (assoc key data)) (push (cons key new-val) data) (setf (cdr (assoc key data)) new-val)) JSCL bug workaround ((jscl::oget inp "setSelectionRange") selection-start selection-end)))))))) t)) (setf (jscl::oget inp "onchange") #'tcb) (setf (jscl::oget inp "onkeyup") #'tcb) (setf (jscl::oget inp "onkeydown") #'tcb) (setf (jscl::oget inp "onpaste") #'tcb) (setf (jscl::oget inp "ondrop") #'tcb)) (append-element inp c2) (append-element c1 row) (append-element c2 row) row)) (defun-f form-button-row (btns) "Create a row with buttons for dialog" (let* ((row (create-element "div" :|style.display| "table-caption" :|style.width| "auto" :|style.captionSide| "bottom")) (cl (create-element "div" :|style.display| "flex" :|style.width| "100%" :|style.height| "100%" :|style.text-align| "center" :|style.justifyContent| "center" :|style.alignItems| "center" :|style.paddingBottom| "0.5em"))) (map nil (lambda (b) (cond ((listp b) (append-element (create-element "button" :|innerHTML| (car b) :|style.marginBottom| "0.3em" :|style.marginLeft| "1em" :|style.marginRight| "1em" :|onclick| (lambda (ev) (funcall (eval (cadr b))))) cl)))) btns) (append-element cl row) row)) (defun-f dialog-table (lines) "Create modal dialog table" (let ((tbl (create-element "div" :|style.display| "table" :|style.width| "auto" :|style.padding| "1em"))) (loop for (k v) on lines by (function cddr) do (if (equal k :buttons) (append-element (form-button-row v) tbl) (if (listp v) (cond ((stringp (car v)) (append-element (form-line k (car v) (cdr v)) tbl))) (append-element (form-line k v) tbl)))) tbl)) (defparameter *dialog-wait-list* (make-hash-table)) (defun-r dialog-wl-send (id dat) (let ((sem (gethash id *dialog-wait-list*))) (if sem (progn (setf (gethash id *dialog-wait-list*) (remove-if (lambda (x) (equal (car x) 'dialog-id)) dat)) (signal-semaphore sem)))) nil) (defun-f close-current-dialog (&optional ev no-sem) (let ((current-dialog (pop *dialog-stack*))) (if (assoc :scroll-disabled current-dialog) (enable-scroll)) (let* ((outer (cdr (assoc :outer current-dialog))) (curtain (cdr (assoc :curtain current-dialog))) (dat (cdr (assoc :data current-dialog))) (id (assoc 'dialog-id dat))) (if outer (remove-element outer)) (if curtain (remove-element curtain)) (if (and (cdr id) (not no-sem)) (dialog-wl-send (cdr id) nil))))) (defun-f get-dialog-data () (cdr (assoc :data (car *dialog-stack*)))) (defun-f make-dialog (header-text dialog-text &key lines id) "Create modal dialog with header, text and lines. " (let* ((curtain (curtain)) (outer (dialog-frame))) (setf *dialog-stack* (cons (list (cons :scroll-disabled (disable-scroll)) (cons :curtain curtain) (cons :outer outer) (cons :data (list (cons 'dialog-id id)))) *dialog-stack*)) (let* ((hdr (dialog-header header-text)) (tbl (dialog-table lines)) (txt (create-element "div" :|innerHTML| dialog-text :|style.fontWeight| "lighter" :|style.marginTop| "1em" :|style.marginLeft| "1em" :|style.marginRight| "1em" :|style.width| "auto"))) (append-element hdr outer) (if dialog-text (append-element txt outer)) (append-element tbl outer) (append-element curtain) (append-element outer) (setf (jscl::oget outer "style" "left") (jscl::concat (write-to-string (+ (visible-left) (jsfloor (/ (- (visible-width) (element-width outer)) 2)))) "px")) (setf (jscl::oget outer "style" "top") (jscl::concat (write-to-string (+ (visible-top) (jsfloor (/ (- (visible-height) (element-height outer)) 2)))) "px")) (setf (jscl::oget outer "style" "opacity") "100%") (get-element-id curtain)))) (defun-f dialog-ok () (let* ((current-dialog (car *dialog-stack*)) (dat (cdr (assoc :data current-dialog))) (id (assoc 'dialog-id dat))) (close-current-dialog nil t) (if id (dialog-wl-send (cdr id) dat)))) (defmacro modal-dialog (header-text dialog-text &key lines) `(if (current-session-id) (let* ((id (intern (symbol-name (omg::random-key *dialog-wait-list*)) :omgui)) (sem (make-semaphore)) (ht ,header-text) (dt ,dialog-text) (lins ,lines)) (setf (gethash id *dialog-wait-list*) sem) (if (remote-exec `(make-dialog ,ht ,dt :lines ',lins :id ',id)) (progn (wait-on-semaphore sem) (let ((res (gethash id *dialog-wait-list*))) (remhash id *dialog-wait-list*) res)))))) (defun-f load-js-script (src &optional onload) (let ((el (create-element "script" :|src| src))) (if onload (setf (jscl::oget el "onload") onload)) (append-element el))) (defun-f make-js-function (name code) (setf (jscl::oget (jscl::%js-vref "window") name) code)) (defun-f make-js-object (&rest plist) (let ((obj (jscl::new))) (loop for (k v) on plist by #'cddr do (setf (jscl::oget obj (symbol-name k)) v)) obj)) (defun-f allow-page-close () (setf *disable-page-unload* nil) nil) (defparameter-f *disable-back* nil) (defparameter-f *backcnt* 0) (defparameter-f *fback* t) (defparameter-f *onpopstate-installed* nil) (defun-f disable-back-button (&optional cb) (if (not *onpopstate-installed*) (progn ((jscl::oget (jscl::%js-vref "history") "pushState") "" "" (jscl::oget (jscl::%js-vref "window") "location" "href")) ((jscl::oget (jscl::%js-vref "history") "back")) (setf *onpopstate-installed* t) (setf (jscl::oget (jscl::%js-vref "window") "onpopstate") (lambda (ev) JSCL bug workaround (fb *fback*)) (setf *backcnt* (+ 1 *backcnt*)) (if *disable-back* ((jscl::oget (jscl::%js-vref "history") "forward"))) (if (equal bcnt 1) (progn (if (and cb (not fb)) (funcall cb)) (setf *fback* nil) (setf *backcnt* 0)))))))) (setf *disable-back* t) nil) (defun-f enable-back-button () (setf *disable-back* nil) ((jscl::oget (jscl::%js-vref "history") "back")) nil) (defparameter-f *beforeunload-installed* nil) (defparameter-f *disable-page-unload* nil) (defun-f prevent-page-close () (if (not *beforeunload-installed*) (progn ((jscl::oget (jscl::%js-vref "window") "addEventListener") "beforeunload" (lambda (ev) (if *disable-page-unload* (progn ((jscl::oget ev "preventDefault")) (setf (jscl::oget ev "returnValue") ""))))) (setf *beforeunload-installed* t))) (setf *disable-page-unload* t) nil) (defparameter-f *youtube-js-loaded* nil) (defun-f add-youtube-player (element &key onready onstatechange onqualitychange onratechange onerror onapichange width height video-id) (let ((cfg (make-js-object :|events| (make-js-object :|onReady| (lambda (ev) (setf *youtube-js-loaded* t) (if onready (funcall onready ev))) :|onStateChange| (lambda (ev) (if onstatechange (funcall onstatechange ev))) :|onPlaybackQualityChange| (lambda (ev) (if onqualitychange (funcall onqualitychange ev))) :|onPlaybackRateChange| (lambda (ev) (if onratechange (funcall onratechange ev))) :|onError| (lambda (ev) (if onerror (funcall onerror ev))) :|onApiChange| (lambda (ev) (if onapichange (funcall onapichange ev))))))) (if width (setf (jscl::oget cfg "width") width)) (if height (setf (jscl::oget cfg "height") height)) (if video-id (setf (jscl::oget cfg "videoId") video-id)) (labels ((make-player () (jscl::make-new (jscl::oget (jscl::%js-vref "YT") "Player") element cfg))) (if (not *youtube-js-loaded*) (progn (make-js-function "onYouTubeIframeAPIReady" (lambda () (jslog "YouTube API loaded") (setf *youtube-js-loaded* t) (make-player))) (load-js-script "")) (make-player)))) nil) (defparameter-f *hash-change-cbs* nil) (defun-f register-hash-cb (hsh cb) (labels ((mcb (&optional ev) (let* ((hs (jscl::oget (jscl::%js-vref "location") "hash")) (cb (assoc hs *hash-change-cbs* :test #'equal))) (if cb (funcall (cdr cb)))))) (let ((need-mcb (not *hash-change-cbs*))) (push (cons hsh cb) *hash-change-cbs*) (if need-mcb (progn (setf (jscl::oget (jscl::%js-vref "window") "onhashchange") #'mcb) (mcb))))) nil) (defun-f gensym2 (&rest args) (intern (symbol-name (apply #'gensym args)))) (: ( jslog " detected ! " ) ) ( (: firefox : chrome ) ( jslog " FF or Chrome ! " ) ) (defmacro-f browser-case (&rest cod) (let ((agent (gensym2)) (browser (gensym2))) `(let* ((,agent (string-downcase (jscl::oget (jscl::%js-vref "navigator") "userAgent"))) (,browser (cond ((or (search "chrome" ,agent) (search "chromium" ,agent) (search "crios" ,agent)) :chrome) ((or (search "firefox" ,agent) (search "fxios" ,agent)) :firefox) ((search "safari" ,agent) :safari) ((search "opr" ,agent) :opera) ((search "edg" ,agent) :edge) (t nil)))) (cond ,@(mapcar (lambda (c) `(,(if (listp (car c)) `(or ,@(mapcar (lambda (s) `(equal ,browser ,s)) (car c))) (if (equal t (car c)) (car c) `(equal ,browser ,(car c)))) ,@(cdr c))) cod))))) (defparameter-f *style-cache* nil) (defun-f add-style (el css-text) (let* ((sid (assoc css-text *style-cache* :test #'equal)) (chrs "ABCDEFGHIJKLMOPQRSTUVWXYZ") (clsid (if sid (cdr sid) (map 'string (lambda (x) (declare (ignore x)) (char chrs (jsfloor (* (jsrandom) (length chrs))))) (make-string 8))))) (if (not sid) (progn (append-element (create-element "style" :|innerHTML| (jscl::concat "." clsid css-text)) (jscl::oget (jscl::%js-vref "document") "head")) (push (cons css-text clsid) *style-cache*))) ((jscl::oget el "classList" "add") clsid))) (defparameter-f *notification-container* nil) (defun-f element-on-page-p (el) (or (equal el (jscl::%js-vref "document")) (and (not (jscl::js-null-p el)) (element-on-page-p (jscl::oget el "parentNode"))))) (defparameter-f *global-observer-handlers* nil) (defun-f on-element-remove (el cb) (if (not *global-observer-handlers*) (let ((obs (jscl::make-new (winref "MutationObserver") (lambda (&rest args) (let ((rems nil)) (map nil (lambda (eh) (if (not (element-on-page-p (car eh))) (if (not (funcall (cdr eh) (car eh))) (push eh rems)))) *global-observer-handlers*) (setf *global-observer-handlers* (remove-if (lambda (x) (position x rems :test #'equal)) *global-observer-handlers*)) nil))))) ((jscl::oget obs "observe") (jscl::oget (jscl::%js-vref "document") "body") (make-js-object :|childList| t)))) (push (cons el cb) *global-observer-handlers*)) (defun-f show-notification (header body &key period check) (let* ((frame (create-element "div" :|style.border| "1pt solid black" :|style.position| "relative" :|style.margin| "0.5em" :|style.background| "white" :|style.width| "15em" :|style.borderRadius| "0.2em" :|style.minHeight| "5em" :|style.boxShadow| "0 0 1em grey" :|style.right| 0 :|omgwidget| "notification")) (head-line (create-element "div" :|style.left| 0 :|style.right| 0 :|style.top| 0 :|style.padding| "0.25em" :|style.position| "relative" :|style.font| (omgui::system-font))) (close-btn (create-element "div" :|style.borderRadius| "0.2em" :|style.background| "red" :|style.right| "0.25em" :|style.top| "0.25em" :|style.width| "0.5em" :|style.aspectRatio| 1 :|style.boxShadow| "0 0 0.5em grey" :|style.cursor| "pointer" :|style.position| "absolute" :|title| "close" :|onclick| (lambda (ev) (remove-element frame)))) (body-cont (create-element "div" :|style.padding| "0.25em" :|style.font| (omgui::system-font))) (ncont (if *notification-container* *notification-container* (create-element "div" :|style.position| "absolute" :|style.right| 0 :|style.top| 0)))) (if (not *notification-container*) (progn (setf *notification-container* ncont) (append-element ncont))) (append-element header head-line) (append-element close-btn head-line) (append-element head-line frame) (append-element body body-cont) (append-element body-cont frame) (append-element frame ncont) (if period (on-element-remove frame (lambda (el) (if (or (not check) (funcall check)) (progn (execute-after period (lambda () (append-element frame ncont))) t) nil)))))) (defun-f find-widget (ev &optional type) (labels ((get-wg (el) (let ((w (jscl::oget el "omgwidget"))) (if (and w (or (not type) (equal w type))) el (let ((par (jscl::oget el "parentNode"))) (if (and par (not (jscl::js-null-p par))) (get-wg par))))))) (get-wg (jscl::oget ev "target")))) (defun-r need-reload () (and (not (equal *omg-version* +devel-version+)) (not (equal *omg-version* *omg-last-version*)))) (defun-r get-omg-cookie-name () +omg-version-cookie+) (defun-r get-last-version () *omg-last-version*) (defun-r get-my-version () *omg-version*) (defun-f ensure-last-version () (if (need-reload) (progn (setf (jscl::oget (jscl::%js-vref "document") "cookie") (format nil "~A=~A" (get-omg-cookie-name) (get-last-version))) ((jscl::oget (jscl::%js-vref "location") "reload") t)))) (defmacro-f ensure-element (e &rest body) (let ((fn (gensym2))) `(labels ((,fn () (if (> (jscl::oget ,e "clientWidth") 0) (progn ,@body) (execute-after 0.1 #',fn)))) (,fn)))) (defparameter-f *global-event-handlers* nil) (defun-f add-event-handler (path handler) (let ((handlers (assoc path *global-event-handlers* :test #'equal))) (if (not handlers) (let* ((path-l (omgui::js-string-split path #\.)) (obj (omgui::deep-oget-1 (jscl::%js-vref "window") (butlast path-l)))) (setf (jscl::oget obj (car (last path-l))) (lambda (ev) (map nil (lambda (cb) (funcall cb ev)) (cdr (assoc path *global-event-handlers* :test #'equal))))) (push (cons path (list handler)) *global-event-handlers*)) (push handler (cdr handlers))))) (defun-f rm-event-handler (path handler) (setf *global-event-handlers* (mapcar (lambda (hnd) (if (equal path (car hnd)) (cons path (remove-if (lambda (h) (equal h handler)) (cdr hnd))) hnd)) *global-event-handlers*))) (defun-f make-tab-form (tab-list) (let* ((tab-div (create-element "div" :|style.display| "flex" :|style.position| "relative")) (content (create-element "div" :|style.padding| "1em" :|style.borderLeft| "1px solid gray" :|style.borderRight| "1px solid gray" :|style.borderBottom| "1px solid gray")) (outer (create-element "div" :append-element tab-div :append-element content)) (tbs nil)) (map nil (lambda (tab num) (append-element (let ((tb (create-element "div" :|style.borderTop| "1px solid gray" :|style.borderLeft| "1px solid gray" :|style.borderRight| "1px solid gray" :|style.borderBottom| (if (= 0 num) "none" "1px solid gray") :|style.background| (if (= 0 num) "#ffffff" "#f0f0f0") :|style.paddingTop| "0.25em" :|style.paddingBottom| "0.25em" :|style.paddingLeft| "1em" :|style.paddingRight| "1em" :|style.borderRadius| "0.5em 0.5em 0 0" :|style.display| "inline-block" :append-element (create-element "a" :|href| "#" :append-element (car tab) :|onclick| (lambda (ev) (map nil (lambda (tab) (setf (jscl::oget (cdr tab) "style" "display") "none") (setf (jscl::oget (cdr tab) "style" "display") "none")) tab-list) (map nil (lambda (th tn) (setf (jscl::oget th "style" "background") (if (= tn num) "#ffffff" "#f0f0f0")) (setf (jscl::oget th "style" "borderBottom") (if (= tn num) "none" "1px solid gray"))) tbs (loop for i below (length tbs) collect i)) (setf (jscl::oget (cdr tab) "style" "display") "block") nil))))) (setf tbs `(,@tbs ,tb)) (setf (jscl::oget (cdr tab) "style" "display") (if (= num 0) "block" "none")) (append-element (cdr tab) content) tb) tab-div)) tab-list (loop for i below (length tab-list) collect i)) (append-element (create-element "div" :|style.display| "inline-block" :|style.width| "auto" :|style.borderBottom| "1px solid gray" :|style.flexGrow| 1) tab-div) outer)) (defun-f make-dragabble-list (elements &key (outer-type "div") reorder-cb on-drag insert-el) (let* ((trans "all 0.5s linear") (insert-gizmo (if insert-el (create-element outer-type :|style.position| "absolute" :|style.right| "100%" :|style.z-index| 20 :|style.display| "block" :|style.visibility| (if elements "hidden" "visible") :|style.transition| "opacity 0.5s linear" :append-element insert-el))) (insert-gizmo-width nil) (inner (create-element "div" :|style.position| "relative")) (moving-el nil) (moving-el-height nil) (moving-el-num nil) (max-top nil) (last-shift nil) (els-pos nil) (els-mid nil) (element-stack nil) (client-y0 nil) (page-y0 nil) (cur-top nil) (last-min-pos nil)) (if insert-el (progn (add-style insert-gizmo ":hover {cursor: pointer;}") (setf (jscl::oget insert-gizmo "onmouseover") (lambda (ev) (if (and (not moving-el) last-min-pos) (progn (setf (jscl::oget inner"omg-insert-position") last-min-pos) (loop for i from (max 0 last-min-pos) to (min last-min-pos (- (length element-stack) 1)) do (progn (setf (jscl::oget (nth i element-stack) "style" "transition") "all 0.1s linear") (setf (jscl::oget (nth i element-stack) "style" "transform") (if (< i last-min-pos) "translateY(-0.5em)" "translateY(0.5em)")))))))) (setf (jscl::oget insert-gizmo "onmouseout") (lambda (ev) (if (and (not moving-el) last-min-pos) (progn (setf (jscl::oget inner "omg-insert-position") nil) (map nil (lambda (el) (setf (jscl::oget el "style" "transform") "translateY(0)")) element-stack))))) (append-element insert-gizmo inner) (setf (jscl::oget inner "omg-insert-position") nil))) (labels ((set-els-pos () (setf els-pos (mapcar (lambda (el) (let ((top (jscl::oget el "offsetTop"))) (cons top (+ top (jscl::oget el "offsetHeight"))))) element-stack)) (setf els-mid (mapcar (lambda (pos) (* 0.5 (+ (car pos) (cdr pos)))) els-pos))) (up-handler (ev) (if moving-el (progn (setf (jscl::oget moving-el "style" "top") 0) (if insert-el (setf (jscl::oget insert-gizmo "style" "display") "block")) (map nil (lambda (el) (if (not (equal el moving-el)) (progn (setf (jscl::oget el "style" "transition") "none") (setf (jscl::oget el "style" "transform") "translateY(0)")) (setf (jscl::oget el "style" "transform") (format nil "translateY(~Apx)" (- cur-top (car (nth last-shift els-pos))))))) element-stack) (let ((el moving-el)) (execute-after 0.1 (lambda () (setf (jscl::oget el "style" "scale") "100%") (setf (jscl::oget el "style" "boxShadow") "0 0 0") (setf (jscl::oget el "style" "zIndex") 10) (setf (jscl::oget el "style" "transform") "translateY(0)")))) (if (and (not (equal moving-el-num last-shift)) (not (and reorder-cb (not (funcall reorder-cb moving-el-num last-shift inner))))) (progn (remove-element moving-el) (if (> last-shift moving-el-num) (if (not (equal last-shift (- (length element-stack) 1))) ((jscl::oget inner "insertBefore") moving-el (nth (+ last-shift 1) element-stack)) (append-element moving-el inner)) ((jscl::oget inner "insertBefore") moving-el (nth last-shift element-stack))) (if (> last-shift moving-el-num) (setf element-stack `(,@(subseq element-stack 0 moving-el-num) ,@(subseq element-stack (+ 1 moving-el-num) (+ last-shift 1)) ,moving-el ,@(subseq element-stack (+ last-shift 1)))) (setf element-stack `(,@(subseq element-stack 0 last-shift) ,moving-el ,@(subseq element-stack last-shift moving-el-num) ,@(subseq element-stack (+ 1 moving-el-num))))) (setf (jscl::oget inner "omg-list-elements") (mapcar (lambda (el) (jscl::oget el "omg-orig-element")) element-stack)))) (setf moving-el nil) (setf last-shift nil) (set-els-pos)))) (move-handler (ev) (let* ((x1 (jscl::oget ev "pageX")) (y1 (jscl::oget ev "pageY"))) (if moving-el (progn (setf cur-top (max 0 (min max-top (+ (- y1 page-y0) client-y0)))) (setf (jscl::oget moving-el "style" "top") (format nil "~Apx" (- cur-top client-y0))) ((jscl::oget (funcall (winref "getSelection")) "empty")) ((jscl::oget ev "stopPropagation")) (let* ((mid (+ cur-top (* 0.5 moving-el-height))) (pos (position-if (lambda (el) (and (> mid (car el)) (< mid (cdr el)))) els-pos))) (if (and pos (not (equal pos last-shift))) (let ((ls1 (if last-shift last-shift pos))) (loop for i from (max 0 (min (- ls1 1) pos)) to (min (- (length element-stack) 1) (max (+ ls1 1) pos)) do (setf (jscl::oget (nth i element-stack) "style" "transform") (format nil "translateY(~Apx)" (cond ((and (>= i pos) (< i moving-el-num)) moving-el-height) ((and (<= i pos) (> i moving-el-num)) (- moving-el-height)) (t 0))))) (setf last-shift pos) (if on-drag (funcall on-drag moving-el pos))))) nil) (if (and insert-el insert-gizmo-width) (let* ((rect ((jscl::oget inner "getBoundingClientRect"))) (top (+ (jscl::oget rect "top") (winref "scrollY"))) (left (+ (jscl::oget rect "left") (winref "scrollX"))) (y1 (- y1 top)) (minpos (if els-mid (if (< y1 (car els-mid)) '(0 . 0) (if (> y1 (car (last els-mid))) `(,(cdar (last els-pos)) . ,(length els-mid)) (loop for i below (length els-mid) when (< y1 (nth i els-mid)) return `(,(cdr (nth (- i 1) els-pos)) . ,i))))))) (if (and (< x1 (+ left (* 0.5 (jscl::oget rect "width")))) (> x1 (- left (* 2 insert-gizmo-width)))) (if (not (equal (jscl::oget insert-gizmo "style" "display") "block")) (progn (setf (jscl::oget insert-gizmo "style" "display") "block") (setf (jscl::oget insert-gizmo "style" "visibility") "visible") (setf (jscl::oget insert-gizmo "style" "opacity") 0) (ensure-element insert-gizmo (setf (jscl::oget insert-gizmo "style" "opacity") 1))) (progn (if (not (equal last-min-pos (cdr minpos))) (progn (setf (jscl::oget insert-gizmo "style" "top") (car minpos)) (setf last-min-pos (cdr minpos)))))) (if (and els-mid (equal (jscl::oget insert-gizmo "style" "display") "block")) (progn (setf (jscl::oget insert-gizmo "style" "opacity") 0) (execute-after 0.5 (lambda () (setf (jscl::oget insert-gizmo "style" "display") "none"))))))))))) (make-rec (el) (let* ((rec (create-element "div" :|style.position| "relative" :|style.transition| trans :|style.zIndex| 10 :append-element el))) (setf (jscl::oget rec "omg-orig-element") el) (setf (jscl::oget rec "onmousedown") (lambda (ev) (if (equal (jscl::oget ev "button") 0) (progn (if insert-el (setf (jscl::oget insert-gizmo "style" "display") "none")) (setf moving-el rec) (setf moving-el-num (position rec element-stack)) (setf (jscl::oget rec "style" "scale") "101%") (setf (jscl::oget rec "style" "boxShadow") "0 0 1em 0.2em #909090") (setf (jscl::oget rec "style" "zIndex") 100) (setf client-y0 (- (jscl::oget ((jscl::oget rec "getBoundingClientRect")) "top") (jscl::oget ((jscl::oget inner "getBoundingClientRect")) "top"))) (setf cur-top client-y0) (setf page-y0 (jscl::oget ev "pageY")) (setf max-top (- (jscl::oget inner "offsetHeight") (jscl::oget rec "offsetHeight"))) (set-els-pos) ( jscl::oget rec " " ) ) (map nil (lambda (el) (setf (jscl::oget el "style" "transition") trans)) element-stack) (setf (jscl::oget rec "style" "transition") "all 0.1s linear"))))) rec))) (setf element-stack (mapcar (lambda (el) (let ((rec (make-rec el))) (append-element rec inner) rec)) elements)) (ensure-element inner (set-els-pos)) (setf (jscl::oget inner "omg-list-elements") elements) (setf (jscl::oget inner "omg-insert-fn") (lambda (el pos) (let ((rec (make-rec el))) (setf (jscl::oget rec "style" "transition") "none") (setf (jscl::oget rec "style" "visibility") "hidden") (setf (jscl::oget rec "style" "opacity") 0) (append-element rec inner) (ensure-element rec (let ((h (jscl::oget ((jscl::oget rec "getBoundingClientRect")) "height"))) (remove-element rec) (loop for i below (length element-stack) for el = (nth i element-stack) do (progn (setf (jscl::oget el "style" "transition") "none") (if (>= i pos) (setf (jscl::oget el "style" "transform") (format nil "translateY(~Apx)" (- h)))))) (if (>= pos (length element-stack)) (append-element rec inner) ((jscl::oget inner "insertBefore") rec (nth pos element-stack))) (setf element-stack `(,@(subseq element-stack 0 pos) ,rec ,@(subseq element-stack pos))) (setf (jscl::oget inner "omg-list-elements") (mapcar (lambda (el) (jscl::oget el "omg-orig-element")) element-stack)) (execute-after 0.1 (lambda () (setf (jscl::oget rec "style" "transition") trans) (setf (jscl::oget rec "style" "visibility") "visible") (setf (jscl::oget rec "style" "opacity") 1) (map nil (lambda (el) (setf (jscl::oget el "style" "transition") trans) (setf (jscl::oget el "style" "transform") "translateY(0)")) element-stack) (execute-after 0.5 (lambda () (set-els-pos)))))))))) (ensure-element insert-gizmo (setf insert-gizmo-width (jscl::oget ((jscl::oget insert-gizmo "getBoundingClientRect")) "width"))) (add-event-handler "document.onmouseup" #'up-handler) (add-event-handler "document.onmousemove" #'move-handler) (on-element-remove inner (lambda (el) (rm-event-handler "document.onmouseup" #'up-handler) (rm-event-handler "document.onmousemove" #'move-handler))) inner))) (defun-f dragabble-list-elements (inner) (jscl::oget inner "omg-list-elements")) (defun-f dragabble-list-insert-position (inner) (if (dragabble-list-elements inner) (jscl::oget inner "omg-insert-position") 0)) (defun-f dragabble-list-insert (inner el &optional pos) (funcall (jscl::oget inner "omg-insert-fn") el (if pos pos (dragabble-list-insert-position inner))))
de90d17e48e70983905f8c352f372c03ae9fbd852b6e383ce95b6d212add4ae2
shamazmazum/easy-audio
flac2wav.lisp
Copyright ( c ) 2012 , ;; All rights reserved. ;; Redistribution and use in source and binary forms, with or without ;; modification, are permitted provided that the following conditions are met: 1 . Redistributions of source code must retain the above copyright notice , this ;; list of conditions and the following disclaimer. 2 . Redistributions in binary form must reproduce the above copyright notice , ;; this list of conditions and the following disclaimer in the documentation ;; and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS " AND ;; ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED . IN NO EVENT SHALL THE COPYRIGHT OWNER OR FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ; ;; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT ;; (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS ;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. (in-package :easy-audio.flac-examples) Works only for 8 or 16 bps (defun flac2wav (flac-name wav-name) "Decodes flac to wav. Works only for 8 or 16 bps, fixed block size and if total samples in stream is known" (with-open-flac (in-reader flac-name) (let* ((blocks (read-metadata in-reader)) (streaminfo (the streaminfo (first blocks))) (minblocksize (streaminfo-minblocksize streaminfo)) (maxblocksize (streaminfo-maxblocksize streaminfo)) (totalsamples (streaminfo-totalsamples streaminfo)) (blocksize minblocksize) (bps (streaminfo-bitspersample streaminfo)) (channels (streaminfo-channels streaminfo)) (samplerate (streaminfo-samplerate streaminfo))) (when (zerop totalsamples) (error "Number of total samples is unknown")) (when (/= minblocksize maxblocksize) (error "Block size must be fixed")) (unless (or (= 8 bps) (= 16 bps)) (error "Bps must be 16 or 8")) (with-output-to-wav (out-stream wav-name :supersede t :samplerate samplerate :channels channels :bps bps :totalsamples totalsamples) (with-output-buffers (streaminfo) (loop for i below totalsamples by blocksize for bufsize = (min (- totalsamples i) blocksize) for buf = (make-array (* bufsize channels) :element-type '(signed-byte 32)) do (write-sequence (mixchannels buf (frame-decode (read-frame in-reader streaminfo))) out-stream)))))))
null
https://raw.githubusercontent.com/shamazmazum/easy-audio/4944f4ac12ffbe96f2d6bb7b116deae8203080e8/flac/examples/flac2wav.lisp
lisp
All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: list of conditions and the following disclaimer. this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Copyright ( c ) 2012 , 1 . Redistributions of source code must retain the above copyright notice , this 2 . Redistributions in binary form must reproduce the above copyright notice , THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS " AND DISCLAIMED . IN NO EVENT SHALL THE COPYRIGHT OWNER OR FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ON ANY THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT (in-package :easy-audio.flac-examples) Works only for 8 or 16 bps (defun flac2wav (flac-name wav-name) "Decodes flac to wav. Works only for 8 or 16 bps, fixed block size and if total samples in stream is known" (with-open-flac (in-reader flac-name) (let* ((blocks (read-metadata in-reader)) (streaminfo (the streaminfo (first blocks))) (minblocksize (streaminfo-minblocksize streaminfo)) (maxblocksize (streaminfo-maxblocksize streaminfo)) (totalsamples (streaminfo-totalsamples streaminfo)) (blocksize minblocksize) (bps (streaminfo-bitspersample streaminfo)) (channels (streaminfo-channels streaminfo)) (samplerate (streaminfo-samplerate streaminfo))) (when (zerop totalsamples) (error "Number of total samples is unknown")) (when (/= minblocksize maxblocksize) (error "Block size must be fixed")) (unless (or (= 8 bps) (= 16 bps)) (error "Bps must be 16 or 8")) (with-output-to-wav (out-stream wav-name :supersede t :samplerate samplerate :channels channels :bps bps :totalsamples totalsamples) (with-output-buffers (streaminfo) (loop for i below totalsamples by blocksize for bufsize = (min (- totalsamples i) blocksize) for buf = (make-array (* bufsize channels) :element-type '(signed-byte 32)) do (write-sequence (mixchannels buf (frame-decode (read-frame in-reader streaminfo))) out-stream)))))))
ccd6d6f92176fa93cba543bca2c890729500df57fcb823dfb44161369350e197
owickstrom/komposition
Base.hs
{-# LANGUAGE ConstraintKinds #-} # LANGUAGE FlexibleContexts # # LANGUAGE PolyKinds # {-# LANGUAGE RankNTypes #-} module Komposition.Application.Base ((>>), (>>=), ivoid, Application, module X) where import Komposition.Prelude as X hiding (State, get, (>>), (>>=)) import Control.Effect import Control.Monad.Indexed.Trans as X import Komposition.Logging as X import Komposition.UserInterface import Komposition.UserInterface.WindowUserInterface import Komposition.UserInterface.Dialog import Komposition.UserInterface.Help import Motor.FSM as X hiding (Delete, delete) (>>) :: IxMonad m => m i j a -> m j k b -> m i k b (>>) = (>>>) (>>=) :: IxMonad m => m i j a -> (a -> m j k b) -> m i k b (>>=) = (>>>=) ivoid :: IxMonad m => m i i a -> m i i () ivoid = (>>> (ireturn ())) type Application t m sig = ( IxPointed (t m) , IxMonad (t m) , IxMonadTrans t , Member Log sig , Carrier sig m , Monad m , WindowUserInterface (t m) , UserInterfaceMarkup (WindowMarkup (t m)) , DialogView (WindowMarkup (t m)) , HelpView (WindowMarkup (t m)) )
null
https://raw.githubusercontent.com/owickstrom/komposition/64893d50941b90f44d77fea0dc6d30c061464cf3/src/Komposition/Application/Base.hs
haskell
# LANGUAGE ConstraintKinds # # LANGUAGE RankNTypes #
# LANGUAGE FlexibleContexts # # LANGUAGE PolyKinds # module Komposition.Application.Base ((>>), (>>=), ivoid, Application, module X) where import Komposition.Prelude as X hiding (State, get, (>>), (>>=)) import Control.Effect import Control.Monad.Indexed.Trans as X import Komposition.Logging as X import Komposition.UserInterface import Komposition.UserInterface.WindowUserInterface import Komposition.UserInterface.Dialog import Komposition.UserInterface.Help import Motor.FSM as X hiding (Delete, delete) (>>) :: IxMonad m => m i j a -> m j k b -> m i k b (>>) = (>>>) (>>=) :: IxMonad m => m i j a -> (a -> m j k b) -> m i k b (>>=) = (>>>=) ivoid :: IxMonad m => m i i a -> m i i () ivoid = (>>> (ireturn ())) type Application t m sig = ( IxPointed (t m) , IxMonad (t m) , IxMonadTrans t , Member Log sig , Carrier sig m , Monad m , WindowUserInterface (t m) , UserInterfaceMarkup (WindowMarkup (t m)) , DialogView (WindowMarkup (t m)) , HelpView (WindowMarkup (t m)) )
155efce2d3bef747e97ef76595ca0a79775a14ff23ed64ef0b8f00b0339a15df
mfoemmel/erlang-otp
xref_scanner.erl
%% %% %CopyrightBegin% %% Copyright Ericsson AB 2000 - 2009 . All Rights Reserved . %% The contents of this file are subject to the Erlang Public License , Version 1.1 , ( the " License " ) ; you may not use this file except in %% compliance with the License. You should have received a copy of the %% Erlang Public License along with this software. If not, it can be %% retrieved online at /. %% Software distributed under the License is distributed on an " AS IS " %% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See %% the License for the specific language governing rights and limitations %% under the License. %% %% %CopyrightEnd% %% -module(xref_scanner). -export([scan/1]). scan(Chars) -> case erl_scan:string(Chars) of {ok, Tokens, _Line} -> {ok, lex(a1(Tokens))}; {error, {Line,Module,Info}, _EndLine} -> {error, Module:format_error(Info), Line} end. a1([{'-',N},{integer,N,1} | L]) -> [{integer,N,-1} | a1(L)]; a1([T | L]) -> [T | a1(L)]; a1([]) -> []. -define(MFA(M,F,A,N), {atom,N,M}, {':',_}, {atom,_,F}, {'/',_}, {integer,_,A}). -define(MFA2(M,F,A,N), {'{',N},{atom,_,M},{',',_},{atom,_,F},{',',_},{integer,_,A},{'}',_}). -define(DECL(N1,N2,T), {':',N1},{var,N2,T}). lex([{atom,N,V1},{'->',_},{atom,_,V2} | L]) -> Constant = {constant, unknown, edge, {V1,V2}}, [{edge,N,Constant} | lex(L)]; lex([{'{',N},{atom,_,V1},{',',_},{atom,_,V2},{'}',_} | L]) -> Constant = {constant, unknown, edge, {V1,V2}}, [{edge,N,Constant} | lex(L)]; lex([?MFA(M,F,A,N),{'->',_},?MFA(M2,F2,A2,_) | L]) -> Constant = {constant, 'Fun', edge, {{M,F,A},{M2,F2,A2}}}, [{edge,N,Constant} | lex(L)]; lex([?MFA(M,F,A,N) | L]) -> Constant = {constant, 'Fun', vertex, {M,F,A}}, [{vertex,N,Constant} | lex(L)]; lex([{'{',N},?MFA2(M,F,A,_),{',',_},?MFA2(M2,F2,A2,_),{'}',_} | L]) -> Constant = {constant, 'Fun', edge, {{M,F,A},{M2,F2,A2}}}, [{edge,N,Constant} | lex(L)]; lex([?MFA2(M,F,A,N) | L]) -> Constant = {constant, 'Fun', vertex, {M,F,A}}, [{vertex,N,Constant} | lex(L)]; lex([?DECL(N1,N2,Decl) | L]) -> case is_type(Decl) of false -> [?DECL(N1, N2, Decl) | lex(L)]; true -> [{decl,N1,Decl} | lex(L)] end; lex([{':',N},{'=',_} | L]) -> [{':=',N} | lex(L)]; lex([{'||',N},{'|',_} | L]) -> [{'|||',N} | lex(L)]; lex([V={var,N,Var} | L]) -> T = case is_type(Var) of false -> V; true -> {cast,N,Var} end, [T | lex(L)]; lex([T | Ts]) -> [T | lex(Ts)]; lex([]) -> [{'$end', -1}]. is_type('Rel') -> true; is_type('App') -> true; is_type('Mod') -> true; is_type('Fun') -> true; is_type('Lin') -> true; is_type('LLin') -> true; is_type('XLin') -> true; is_type('ELin') -> true; is_type('XXL') -> true; is_type(_) -> false.
null
https://raw.githubusercontent.com/mfoemmel/erlang-otp/9c6fdd21e4e6573ca6f567053ff3ac454d742bc2/lib/tools/src/xref_scanner.erl
erlang
%CopyrightBegin% compliance with the License. You should have received a copy of the Erlang Public License along with this software. If not, it can be retrieved online at /. basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. %CopyrightEnd%
Copyright Ericsson AB 2000 - 2009 . All Rights Reserved . The contents of this file are subject to the Erlang Public License , Version 1.1 , ( the " License " ) ; you may not use this file except in Software distributed under the License is distributed on an " AS IS " -module(xref_scanner). -export([scan/1]). scan(Chars) -> case erl_scan:string(Chars) of {ok, Tokens, _Line} -> {ok, lex(a1(Tokens))}; {error, {Line,Module,Info}, _EndLine} -> {error, Module:format_error(Info), Line} end. a1([{'-',N},{integer,N,1} | L]) -> [{integer,N,-1} | a1(L)]; a1([T | L]) -> [T | a1(L)]; a1([]) -> []. -define(MFA(M,F,A,N), {atom,N,M}, {':',_}, {atom,_,F}, {'/',_}, {integer,_,A}). -define(MFA2(M,F,A,N), {'{',N},{atom,_,M},{',',_},{atom,_,F},{',',_},{integer,_,A},{'}',_}). -define(DECL(N1,N2,T), {':',N1},{var,N2,T}). lex([{atom,N,V1},{'->',_},{atom,_,V2} | L]) -> Constant = {constant, unknown, edge, {V1,V2}}, [{edge,N,Constant} | lex(L)]; lex([{'{',N},{atom,_,V1},{',',_},{atom,_,V2},{'}',_} | L]) -> Constant = {constant, unknown, edge, {V1,V2}}, [{edge,N,Constant} | lex(L)]; lex([?MFA(M,F,A,N),{'->',_},?MFA(M2,F2,A2,_) | L]) -> Constant = {constant, 'Fun', edge, {{M,F,A},{M2,F2,A2}}}, [{edge,N,Constant} | lex(L)]; lex([?MFA(M,F,A,N) | L]) -> Constant = {constant, 'Fun', vertex, {M,F,A}}, [{vertex,N,Constant} | lex(L)]; lex([{'{',N},?MFA2(M,F,A,_),{',',_},?MFA2(M2,F2,A2,_),{'}',_} | L]) -> Constant = {constant, 'Fun', edge, {{M,F,A},{M2,F2,A2}}}, [{edge,N,Constant} | lex(L)]; lex([?MFA2(M,F,A,N) | L]) -> Constant = {constant, 'Fun', vertex, {M,F,A}}, [{vertex,N,Constant} | lex(L)]; lex([?DECL(N1,N2,Decl) | L]) -> case is_type(Decl) of false -> [?DECL(N1, N2, Decl) | lex(L)]; true -> [{decl,N1,Decl} | lex(L)] end; lex([{':',N},{'=',_} | L]) -> [{':=',N} | lex(L)]; lex([{'||',N},{'|',_} | L]) -> [{'|||',N} | lex(L)]; lex([V={var,N,Var} | L]) -> T = case is_type(Var) of false -> V; true -> {cast,N,Var} end, [T | lex(L)]; lex([T | Ts]) -> [T | lex(Ts)]; lex([]) -> [{'$end', -1}]. is_type('Rel') -> true; is_type('App') -> true; is_type('Mod') -> true; is_type('Fun') -> true; is_type('Lin') -> true; is_type('LLin') -> true; is_type('XLin') -> true; is_type('ELin') -> true; is_type('XXL') -> true; is_type(_) -> false.
a64573a126aa5b9fef43124df3862e3ddefb4de187f5ed7b43706bfd3d4b0fe7
ezyang/reflex-backpack
Base.hs
| This module defines ' PostBuildT ' , the standard implementation of ' PostBuild ' . # LANGUAGE CPP # # LANGUAGE DataKinds # # LANGUAGE FlexibleInstances # # LANGUAGE GeneralizedNewtypeDeriving # # LANGUAGE MultiParamTypeClasses # # LANGUAGE RecursiveDo # # LANGUAGE ScopedTypeVariables # # LANGUAGE TypeFamilies # # LANGUAGE TypeOperators # # LANGUAGE UndecidableInstances # #ifdef USE_REFLEX_OPTIMIZER {-# OPTIONS_GHC -fplugin=Reflex.Optimizer #-} #endif module Reflex.PostBuild.Base ( PostBuildT (..) , runPostBuildT ) where import Reflex.Basics import Reflex.Host.Basics import Reflex.PerformEvent.Class import Reflex.PostBuild.Class import Reflex.TriggerEvent.Class import Control.Monad.Exception import Control.Monad.Primitive import Control.Monad.Reader import Control.Monad.Ref import Control.Monad.Trans.Control import qualified Data.Dependent.Map as DMap | Provides a basic implementation of ' PostBuild ' . newtype PostBuildT t m a = PostBuildT { unPostBuildT :: ReaderT (Event t ()) m a } deriving (Functor, Applicative, Monad, MonadFix, MonadIO, MonadTrans, MonadException, MonadAsyncException) | Run a ' PostBuildT ' action . An ' Event ' should be provided that fires -- immediately after the action is finished running; no other 'Event's should fire first . # INLINABLE runPostBuildT # runPostBuildT :: PostBuildT t m a -> Event t () -> m a runPostBuildT (PostBuildT a) = runReaderT a instance PrimMonad m => PrimMonad (PostBuildT x m) where type PrimState (PostBuildT x m) = PrimState m primitive = lift . primitive instance MonadTransControl (PostBuildT t) where type StT (PostBuildT t) a = StT (ReaderT (Event t ())) a # INLINABLE liftWith # liftWith = defaultLiftWith PostBuildT unPostBuildT # INLINABLE restoreT # restoreT = defaultRestoreT PostBuildT instance (HasTimeline t, Monad m) => PostBuild t (PostBuildT t m) where {-# INLINABLE getPostBuild #-} getPostBuild = PostBuildT ask instance MonadSample (Impl t) m => MonadSample (Impl t) (PostBuildT t m) where # INLINABLE sample # sample = lift . sample instance MonadHold (Impl t) m => MonadHold (Impl t) (PostBuildT t m) where # INLINABLE hold # hold v0 = lift . hold v0 # INLINABLE holdDyn # holdDyn v0 = lift . holdDyn v0 # INLINABLE holdIncremental # holdIncremental v0 = lift . holdIncremental v0 instance PerformEvent t m => PerformEvent t (PostBuildT t m) where type Performable (PostBuildT t m) = PostBuildT t (Performable m) # INLINABLE performEvent _ # performEvent_ e = liftWith $ \run -> performEvent_ $ fmap run e # INLINABLE performEvent # performEvent e = liftWith $ \run -> performEvent $ fmap run e instance (HasTimeline t, MonadReflexCreateTrigger t m) => MonadReflexCreateTrigger t (PostBuildT t m) where {-# INLINABLE newEventWithTrigger #-} newEventWithTrigger = PostBuildT . lift . newEventWithTrigger # INLINABLE newFanEventWithTrigger # newFanEventWithTrigger f = PostBuildT $ lift $ newFanEventWithTrigger f instance TriggerEvent t m => TriggerEvent t (PostBuildT t m) where # INLINABLE newTriggerEvent # newTriggerEvent = lift newTriggerEvent # INLINABLE newTriggerEventWithOnComplete # newTriggerEventWithOnComplete = lift newTriggerEventWithOnComplete newEventWithLazyTriggerWithOnComplete = lift . newEventWithLazyTriggerWithOnComplete instance MonadRef m => MonadRef (PostBuildT t m) where type Ref (PostBuildT t m) = Ref m # INLINABLE newRef # newRef = lift . newRef # INLINABLE readRef # readRef = lift . readRef # INLINABLE writeRef # writeRef r = lift . writeRef r instance MonadAtomicRef m => MonadAtomicRef (PostBuildT t m) where # INLINABLE atomicModifyRef # atomicModifyRef r = lift . atomicModifyRef r instance (HasTimeline t, MonadHold (Impl t) m, MonadFix m, MonadAdjust t m, PerformEvent t m) => MonadAdjust t (PostBuildT t m) where runWithReplace a0 a' = do postBuild <- getPostBuild lift $ do rec result@(_, result') <- runWithReplace (runPostBuildT a0 postBuild) $ fmap (\v -> runPostBuildT v =<< headE voidResult') a' let voidResult' = fmapCheap (\_ -> ()) result' return result sequenceDMapWithAdjust dm0 dm' = do postBuild <- getPostBuild let loweredDm0 = DMap.map (`runPostBuildT` postBuild) dm0 lift $ do rec (result0, result') <- sequenceDMapWithAdjust loweredDm0 loweredDm' let voidResult' = fmapCheap (\_ -> ()) result' let loweredDm' = ffor dm' $ \(PatchDMap p) -> PatchDMap $ DMap.map (ComposeMaybe . fmap (\v -> runPostBuildT v =<< headE voidResult') . getComposeMaybe) p --TODO: Avoid doing this headE so many times; once per loweredDm' firing ought to be OK, but it's not totally trivial to do because result' might be firing at the same time, and we don't want *that* to be the postBuild occurrence return (result0, result')
null
https://raw.githubusercontent.com/ezyang/reflex-backpack/247898fde872d8909392ebe2539f4623c7449067/host/Reflex/PostBuild/Base.hs
haskell
# OPTIONS_GHC -fplugin=Reflex.Optimizer # immediately after the action is finished running; no other 'Event's should # INLINABLE getPostBuild # # INLINABLE newEventWithTrigger # TODO: Avoid doing this headE so many times; once per loweredDm' firing ought to be OK, but it's not totally trivial to do because result' might be firing at the same time, and we don't want *that* to be the postBuild occurrence
| This module defines ' PostBuildT ' , the standard implementation of ' PostBuild ' . # LANGUAGE CPP # # LANGUAGE DataKinds # # LANGUAGE FlexibleInstances # # LANGUAGE GeneralizedNewtypeDeriving # # LANGUAGE MultiParamTypeClasses # # LANGUAGE RecursiveDo # # LANGUAGE ScopedTypeVariables # # LANGUAGE TypeFamilies # # LANGUAGE TypeOperators # # LANGUAGE UndecidableInstances # #ifdef USE_REFLEX_OPTIMIZER #endif module Reflex.PostBuild.Base ( PostBuildT (..) , runPostBuildT ) where import Reflex.Basics import Reflex.Host.Basics import Reflex.PerformEvent.Class import Reflex.PostBuild.Class import Reflex.TriggerEvent.Class import Control.Monad.Exception import Control.Monad.Primitive import Control.Monad.Reader import Control.Monad.Ref import Control.Monad.Trans.Control import qualified Data.Dependent.Map as DMap | Provides a basic implementation of ' PostBuild ' . newtype PostBuildT t m a = PostBuildT { unPostBuildT :: ReaderT (Event t ()) m a } deriving (Functor, Applicative, Monad, MonadFix, MonadIO, MonadTrans, MonadException, MonadAsyncException) | Run a ' PostBuildT ' action . An ' Event ' should be provided that fires fire first . # INLINABLE runPostBuildT # runPostBuildT :: PostBuildT t m a -> Event t () -> m a runPostBuildT (PostBuildT a) = runReaderT a instance PrimMonad m => PrimMonad (PostBuildT x m) where type PrimState (PostBuildT x m) = PrimState m primitive = lift . primitive instance MonadTransControl (PostBuildT t) where type StT (PostBuildT t) a = StT (ReaderT (Event t ())) a # INLINABLE liftWith # liftWith = defaultLiftWith PostBuildT unPostBuildT # INLINABLE restoreT # restoreT = defaultRestoreT PostBuildT instance (HasTimeline t, Monad m) => PostBuild t (PostBuildT t m) where getPostBuild = PostBuildT ask instance MonadSample (Impl t) m => MonadSample (Impl t) (PostBuildT t m) where # INLINABLE sample # sample = lift . sample instance MonadHold (Impl t) m => MonadHold (Impl t) (PostBuildT t m) where # INLINABLE hold # hold v0 = lift . hold v0 # INLINABLE holdDyn # holdDyn v0 = lift . holdDyn v0 # INLINABLE holdIncremental # holdIncremental v0 = lift . holdIncremental v0 instance PerformEvent t m => PerformEvent t (PostBuildT t m) where type Performable (PostBuildT t m) = PostBuildT t (Performable m) # INLINABLE performEvent _ # performEvent_ e = liftWith $ \run -> performEvent_ $ fmap run e # INLINABLE performEvent # performEvent e = liftWith $ \run -> performEvent $ fmap run e instance (HasTimeline t, MonadReflexCreateTrigger t m) => MonadReflexCreateTrigger t (PostBuildT t m) where newEventWithTrigger = PostBuildT . lift . newEventWithTrigger # INLINABLE newFanEventWithTrigger # newFanEventWithTrigger f = PostBuildT $ lift $ newFanEventWithTrigger f instance TriggerEvent t m => TriggerEvent t (PostBuildT t m) where # INLINABLE newTriggerEvent # newTriggerEvent = lift newTriggerEvent # INLINABLE newTriggerEventWithOnComplete # newTriggerEventWithOnComplete = lift newTriggerEventWithOnComplete newEventWithLazyTriggerWithOnComplete = lift . newEventWithLazyTriggerWithOnComplete instance MonadRef m => MonadRef (PostBuildT t m) where type Ref (PostBuildT t m) = Ref m # INLINABLE newRef # newRef = lift . newRef # INLINABLE readRef # readRef = lift . readRef # INLINABLE writeRef # writeRef r = lift . writeRef r instance MonadAtomicRef m => MonadAtomicRef (PostBuildT t m) where # INLINABLE atomicModifyRef # atomicModifyRef r = lift . atomicModifyRef r instance (HasTimeline t, MonadHold (Impl t) m, MonadFix m, MonadAdjust t m, PerformEvent t m) => MonadAdjust t (PostBuildT t m) where runWithReplace a0 a' = do postBuild <- getPostBuild lift $ do rec result@(_, result') <- runWithReplace (runPostBuildT a0 postBuild) $ fmap (\v -> runPostBuildT v =<< headE voidResult') a' let voidResult' = fmapCheap (\_ -> ()) result' return result sequenceDMapWithAdjust dm0 dm' = do postBuild <- getPostBuild let loweredDm0 = DMap.map (`runPostBuildT` postBuild) dm0 lift $ do rec (result0, result') <- sequenceDMapWithAdjust loweredDm0 loweredDm' let voidResult' = fmapCheap (\_ -> ()) result' let loweredDm' = ffor dm' $ \(PatchDMap p) -> PatchDMap $ return (result0, result')
198ef95c5ae8a52f5b7541ad3289cd7ef110843a930596b6b17c3dd2f3d2308d
haskell/time
CalendarDiffTime.hs
{-# LANGUAGE Safe #-} module Data.Time.LocalTime.Internal.CalendarDiffTime ( -- * Calendar Duration module Data.Time.LocalTime.Internal.CalendarDiffTime, ) where import Control.DeepSeq import Data.Data import Data.Time.Calendar.CalendarDiffDays import Data.Time.Clock.Internal.NominalDiffTime data CalendarDiffTime = CalendarDiffTime { ctMonths :: Integer , ctTime :: NominalDiffTime } deriving ( Eq | @since 1.9.2 Data | @since 1.9.2 Typeable ) instance NFData CalendarDiffTime where rnf (CalendarDiffTime m t) = rnf m `seq` rnf t `seq` () -- | Additive instance Semigroup CalendarDiffTime where CalendarDiffTime m1 d1 <> CalendarDiffTime m2 d2 = CalendarDiffTime (m1 + m2) (d1 + d2) -- | Additive instance Monoid CalendarDiffTime where mempty = CalendarDiffTime 0 0 mappend = (<>) calendarTimeDays :: CalendarDiffDays -> CalendarDiffTime calendarTimeDays (CalendarDiffDays m d) = CalendarDiffTime m $ fromInteger d * nominalDay calendarTimeTime :: NominalDiffTime -> CalendarDiffTime calendarTimeTime dt = CalendarDiffTime 0 dt | Scale by a factor . Note that @scaleCalendarDiffTime ( -1)@ will not perfectly invert a duration , due to variable month lengths . scaleCalendarDiffTime :: Integer -> CalendarDiffTime -> CalendarDiffTime scaleCalendarDiffTime k (CalendarDiffTime m d) = CalendarDiffTime (k * m) (fromInteger k * d)
null
https://raw.githubusercontent.com/haskell/time/919018368011669090dd8d59cfe3daacd3d30529/lib/Data/Time/LocalTime/Internal/CalendarDiffTime.hs
haskell
# LANGUAGE Safe # * Calendar Duration | Additive | Additive
module Data.Time.LocalTime.Internal.CalendarDiffTime ( module Data.Time.LocalTime.Internal.CalendarDiffTime, ) where import Control.DeepSeq import Data.Data import Data.Time.Calendar.CalendarDiffDays import Data.Time.Clock.Internal.NominalDiffTime data CalendarDiffTime = CalendarDiffTime { ctMonths :: Integer , ctTime :: NominalDiffTime } deriving ( Eq | @since 1.9.2 Data | @since 1.9.2 Typeable ) instance NFData CalendarDiffTime where rnf (CalendarDiffTime m t) = rnf m `seq` rnf t `seq` () instance Semigroup CalendarDiffTime where CalendarDiffTime m1 d1 <> CalendarDiffTime m2 d2 = CalendarDiffTime (m1 + m2) (d1 + d2) instance Monoid CalendarDiffTime where mempty = CalendarDiffTime 0 0 mappend = (<>) calendarTimeDays :: CalendarDiffDays -> CalendarDiffTime calendarTimeDays (CalendarDiffDays m d) = CalendarDiffTime m $ fromInteger d * nominalDay calendarTimeTime :: NominalDiffTime -> CalendarDiffTime calendarTimeTime dt = CalendarDiffTime 0 dt | Scale by a factor . Note that @scaleCalendarDiffTime ( -1)@ will not perfectly invert a duration , due to variable month lengths . scaleCalendarDiffTime :: Integer -> CalendarDiffTime -> CalendarDiffTime scaleCalendarDiffTime k (CalendarDiffTime m d) = CalendarDiffTime (k * m) (fromInteger k * d)
ddad16f18540144f695292e99a0f69280e614331dbea6e42d4826f6fc0547d69
hasktorch/hasktorch
Vision.hs
# LANGUAGE FlexibleContexts # # LANGUAGE FlexibleInstances # # LANGUAGE KindSignatures # # LANGUAGE LambdaCase # # LANGUAGE MultiParamTypeClasses # # LANGUAGE QuasiQuotes # # LANGUAGE RecordWildCards # # LANGUAGE ScopedTypeVariables # # LANGUAGE TemplateHaskell # module Torch.Vision where import qualified Codec.Picture as I import Control.Exception.Safe ( SomeException (..), throwIO, try, ) import Control.Monad ( MonadPlus, forM_, when, ) import qualified Data.ByteString as BS import qualified Data.ByteString.Internal as BSI import Data.Int import qualified Data.Vector.Storable as V import Data.Word import qualified Foreign.ForeignPtr as F import qualified Foreign.Ptr as F import GHC.Exts (IsList (fromList)) import qualified Language.C.Inline as C import Pipes import System.IO.Unsafe import System.Random (mkStdGen, randoms) import qualified Torch.DType as D import Torch.Data.Pipeline import Torch.Data.StreamedPipeline import Torch.Functional hiding (take) import qualified Torch.Functional as D import Torch.Internal.Cast import qualified Torch.Internal.Managed.TensorFactories as LibTorch import Torch.NN import Torch.Tensor import qualified Torch.Tensor as D import qualified Torch.TensorOptions as D import qualified Torch.Typed.Vision as I import Prelude hiding (max, min) import qualified Prelude as P C.include "<stdint.h>" data MNIST (m :: * -> *) = MNIST { batchSize :: Int, mnistData :: I.MnistData } instance Monad m => Datastream m Int (MNIST m) (Tensor, Tensor) where streamSamples MNIST {..} seed = Select $ for (each [1 .. numIters]) $ \iter -> do let from = (iter -1) * batchSize to = (iter * batchSize) - 1 indexes = [from .. to] target = getLabels' batchSize mnistData indexes let input = getImages' batchSize 784 mnistData indexes yield (input, target) where numIters = I.length mnistData `Prelude.div` batchSize instance Applicative m => Dataset m (MNIST m) Int (Tensor, Tensor) where getItem MNIST {..} ix = let indexes = [ix * batchSize .. (ix + 1) * batchSize - 1] imgs = getImages' batchSize 784 mnistData indexes labels = getLabels' batchSize mnistData indexes in pure (imgs, labels) keys MNIST {..} = fromList [0 .. I.length mnistData `Prelude.div` batchSize - 1] getLabels' :: Int -> I.MnistData -> [Int] -> Tensor getLabels' n mnist imageIdxs = asTensor $ map (I.getLabel mnist) . take n $ imageIdxs getImages' :: number of observations in minibatch Int -> -- dimensionality of the data I.MnistData -> -- mnist data representation [Int] -> -- indices of the dataset Tensor getImages' n dataDim mnist imageIdxs = unsafePerformIO $ do let (BSI.PS fptr off len) = I.images mnist t <- (cast2 LibTorch.empty_lo :: [Int] -> D.TensorOptions -> IO D.Tensor) [n, dataDim] (D.withDType D.UInt8 D.defaultOpts) D.withTensor t $ \ptr1 -> do F.withForeignPtr fptr $ \ptr2 -> do forM_ (zip [0 .. (n -1)] imageIdxs) $ \(i, idx) -> do BSI.memcpy (F.plusPtr ptr1 (dataDim * i)) (F.plusPtr ptr2 (off + 16 + dataDim * idx)) dataDim return $ D.toType D.Float t -- / grayScale10 = " .:-=+*#%@" grayScale70 = reverse "$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\\|()1{}[]?-_+~<>i!lI;:,\"^`'. " -- Display an MNIST image tensor as ascii text dispImage :: Tensor -> IO () dispImage img = do mapM ( \row -> mapM ( \col -> putChar $ grayScale !! (P.floor $ scaled !! row !! col) ) [0, downSamp .. 27] >> putStrLn "" ) [0, downSamp .. 27] pure () where downSamp = 2 grayScale = grayScale10 paletteMax = (fromIntegral $ length grayScale) - 1.0 img' = reshape [28, 28] img scaled :: [[Float]] = let (mn, mx) = (min img', max img') in asValue $ (img' - mn) / (mx - mn) * paletteMax data PixelFormat = Y8 | YF | YA8 | RGB8 | RGBF | RGBA8 | YCbCr8 | CMYK8 | CMYK16 | RGBA16 | RGB16 | Y16 | YA16 | Y32 deriving (Show, Eq) readImage :: FilePath -> IO (Either String (D.Tensor, PixelFormat)) readImage file = I.readImage file >>= \case Left err -> return $ Left err Right img' -> return $ Right $ (fromDynImage img', pixelFormat img') readImageAsRGB8 :: FilePath -> IO (Either String D.Tensor) readImageAsRGB8 file = I.readImage file >>= \case Left err -> return $ Left err Right img' -> return . Right . fromDynImage . I.ImageRGB8 . I.convertRGB8 $ img' readImageAsRGB8WithScaling :: FilePath -> Int -> Int -> Bool -> IO (Either String (I.Image I.PixelRGB8, D.Tensor)) readImageAsRGB8WithScaling file width height keepAspectRatio = I.readImage file >>= \case Left err -> return $ Left err Right img' -> do let img = (resizeRGB8 width height keepAspectRatio) . I.convertRGB8 $ img' return $ Right (img, fromDynImage . I.ImageRGB8 $ img) centerCrop :: Int -> Int -> I.Image I.PixelRGB8 -> I.Image I.PixelRGB8 centerCrop width height input = unsafePerformIO $ do let channel = 3 :: Int (I.Image org_w org_h org_vec) = input img@(I.Image w h vec) = I.generateImage (\_ _ -> (I.PixelRGB8 0 0 0)) width height :: I.Image I.PixelRGB8 (org_fptr, org_len) = V.unsafeToForeignPtr0 org_vec org_whc = fromIntegral $ org_w * org_h * channel (fptr, len) = V.unsafeToForeignPtr0 vec whc = fromIntegral $ w * h * channel F.withForeignPtr org_fptr $ \ptr1 -> F.withForeignPtr fptr $ \ptr2 -> do let src = F.castPtr ptr1 dst = F.castPtr ptr2 iw = fromIntegral w ih = fromIntegral h iorg_w = fromIntegral org_w iorg_h = fromIntegral org_h ichannel = fromIntegral channel [C.block| void { uint8_t* src = $(uint8_t* src); uint8_t* dst = $(uint8_t* dst); int w = $(int iw); int h = $(int ih); int channel = $(int ichannel); int ow = $(int iorg_w); int oh = $(int iorg_h); int offsetx = (ow - w)/2; int offsety = (oh - h)/2; for(int y=0;y<h;y++){ for(int x=0;x<w;x++){ for(int c=0;c<channel;c++){ int sy = y + offsety; int sx = x + offsetx; if(sx >= 0 && sx < ow && sy >= 0 && sy < oh){ dst[(y*w+x)*channel+c] = src[(sy*ow+sx)*channel+c]; } } } } } |] return img drawLine :: Int -> Int -> Int -> Int -> (Int, Int, Int) -> I.Image I.PixelRGB8 -> IO () drawLine x0 y0 x1 y1 (r, g, b) input = do let img@(I.Image w h vec) = input (fptr, len) = V.unsafeToForeignPtr0 vec F.withForeignPtr fptr $ \ptr2 -> do let iw = fromIntegral w ih = fromIntegral h ix0 = fromIntegral x0 iy0 = fromIntegral y0 ix1 = fromIntegral x1 iy1 = fromIntegral y1 ir = fromIntegral r ig = fromIntegral g ib = fromIntegral b dst = F.castPtr ptr2 [C.block| void { uint8_t* dst = $(uint8_t* dst); int w = $(int iw); int h = $(int ih); int x0 = $(int ix0); int y0 = $(int iy0); int x1 = $(int ix1); int y1 = $(int iy1); int r = $(int ir); int g = $(int ig); int b = $(int ib); int channel = 3; int sign_x = x1 - x0 >= 0 ? 1 : -1; int sign_y = y1 - y0 >= 0 ? 1 : -1; int abs_x = x1 - x0 >= 0 ? x1 - x0 : x0 - x1; int abs_y = y1 - y0 >= 0 ? y1 - y0 : y0 - y1; if(abs_x>=abs_y){ for(int x=x0;x!=x1;x+=sign_x){ int y = (x-x0) * (y1-y0) / (x1-x0) + y0; if(y >=0 && y < h && x >=0 && x < w) { dst[(y*w+x)*channel+0] = r; dst[(y*w+x)*channel+1] = g; dst[(y*w+x)*channel+2] = b; } } } else { for(int y=y0;y!=y1;y+=sign_y){ int x = (y-y0) * (x1-x0) / (y1-y0) + x0; if(y >=0 && y < h && x >=0 && x < w) { dst[(y*w+x)*channel+0] = r; dst[(y*w+x)*channel+1] = g; dst[(y*w+x)*channel+2] = b; } } } } |] drawRect :: Int -> Int -> Int -> Int -> (Int, Int, Int) -> I.Image I.PixelRGB8 -> IO () drawRect x0 y0 x1 y1 (r, g, b) input = do drawLine x0 y0 (x1 + 1) y0 (r, g, b) input drawLine x0 y0 x0 (y1 + 1) (r, g, b) input drawLine x0 y1 (x1 + 1) y1 (r, g, b) input drawLine x1 y0 x1 (y1 + 1) (r, g, b) input drawString :: String -> Int -> Int -> (Int, Int, Int) -> (Int, Int, Int) -> I.Image I.PixelRGB8 -> IO () drawString text x0 y0 (r, g, b) (br, bg, bb) input = do forM_ (zip [0 ..] text) $ \(i, ch) -> do drawChar (fromEnum ch) (x0 + i * 8) y0 (r, g, b) (br, bg, bb) input drawChar :: Int -> Int -> Int -> (Int, Int, Int) -> (Int, Int, Int) -> I.Image I.PixelRGB8 -> IO () drawChar ascii_code x0 y0 (r, g, b) (br, bg, bb) input = do let img@(I.Image w h vec) = input (fptr, len) = V.unsafeToForeignPtr0 vec F.withForeignPtr fptr $ \ptr2 -> do let iw = fromIntegral w ih = fromIntegral h ix0 = fromIntegral x0 iy0 = fromIntegral y0 ir = fromIntegral r ig = fromIntegral g ib = fromIntegral b ibr = fromIntegral br ibg = fromIntegral bg ibb = fromIntegral bb dst = F.castPtr ptr2 iascii_code = fromIntegral ascii_code [C.block| void { uint8_t* dst = $(uint8_t* dst); int w = $(int iw); int h = $(int ih); int x0 = $(int ix0); int y0 = $(int iy0); int r = $(int ir); int g = $(int ig); int b = $(int ib); int br = $(int ibr); int bg = $(int ibg); int bb = $(int ibb); int ascii_code = $(int iascii_code); int channel = 3; int char_width = 8; int char_height = 8; char fonts[95][8] = { // 0x20 to 0x7e { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, { 0x18, 0x3C, 0x3C, 0x18, 0x18, 0x00, 0x18, 0x00}, { 0x36, 0x36, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, { 0x36, 0x36, 0x7F, 0x36, 0x7F, 0x36, 0x36, 0x00}, { 0x0C, 0x3E, 0x03, 0x1E, 0x30, 0x1F, 0x0C, 0x00}, { 0x00, 0x63, 0x33, 0x18, 0x0C, 0x66, 0x63, 0x00}, { 0x1C, 0x36, 0x1C, 0x6E, 0x3B, 0x33, 0x6E, 0x00}, { 0x06, 0x06, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00}, { 0x18, 0x0C, 0x06, 0x06, 0x06, 0x0C, 0x18, 0x00}, { 0x06, 0x0C, 0x18, 0x18, 0x18, 0x0C, 0x06, 0x00}, { 0x00, 0x66, 0x3C, 0xFF, 0x3C, 0x66, 0x00, 0x00}, { 0x00, 0x0C, 0x0C, 0x3F, 0x0C, 0x0C, 0x00, 0x00}, { 0x00, 0x00, 0x00, 0x00, 0x00, 0x0C, 0x0C, 0x06}, { 0x00, 0x00, 0x00, 0x3F, 0x00, 0x00, 0x00, 0x00}, { 0x00, 0x00, 0x00, 0x00, 0x00, 0x0C, 0x0C, 0x00}, { 0x60, 0x30, 0x18, 0x0C, 0x06, 0x03, 0x01, 0x00}, { 0x3E, 0x63, 0x73, 0x7B, 0x6F, 0x67, 0x3E, 0x00}, { 0x0C, 0x0E, 0x0C, 0x0C, 0x0C, 0x0C, 0x3F, 0x00}, { 0x1E, 0x33, 0x30, 0x1C, 0x06, 0x33, 0x3F, 0x00}, { 0x1E, 0x33, 0x30, 0x1C, 0x30, 0x33, 0x1E, 0x00}, { 0x38, 0x3C, 0x36, 0x33, 0x7F, 0x30, 0x78, 0x00}, { 0x3F, 0x03, 0x1F, 0x30, 0x30, 0x33, 0x1E, 0x00}, { 0x1C, 0x06, 0x03, 0x1F, 0x33, 0x33, 0x1E, 0x00}, { 0x3F, 0x33, 0x30, 0x18, 0x0C, 0x0C, 0x0C, 0x00}, { 0x1E, 0x33, 0x33, 0x1E, 0x33, 0x33, 0x1E, 0x00}, { 0x1E, 0x33, 0x33, 0x3E, 0x30, 0x18, 0x0E, 0x00}, { 0x00, 0x0C, 0x0C, 0x00, 0x00, 0x0C, 0x0C, 0x00}, { 0x00, 0x0C, 0x0C, 0x00, 0x00, 0x0C, 0x0C, 0x06}, { 0x18, 0x0C, 0x06, 0x03, 0x06, 0x0C, 0x18, 0x00}, { 0x00, 0x00, 0x3F, 0x00, 0x00, 0x3F, 0x00, 0x00}, { 0x06, 0x0C, 0x18, 0x30, 0x18, 0x0C, 0x06, 0x00}, { 0x1E, 0x33, 0x30, 0x18, 0x0C, 0x00, 0x0C, 0x00}, { 0x3E, 0x63, 0x7B, 0x7B, 0x7B, 0x03, 0x1E, 0x00}, { 0x0C, 0x1E, 0x33, 0x33, 0x3F, 0x33, 0x33, 0x00}, { 0x3F, 0x66, 0x66, 0x3E, 0x66, 0x66, 0x3F, 0x00}, { 0x3C, 0x66, 0x03, 0x03, 0x03, 0x66, 0x3C, 0x00}, { 0x1F, 0x36, 0x66, 0x66, 0x66, 0x36, 0x1F, 0x00}, { 0x7F, 0x46, 0x16, 0x1E, 0x16, 0x46, 0x7F, 0x00}, { 0x7F, 0x46, 0x16, 0x1E, 0x16, 0x06, 0x0F, 0x00}, { 0x3C, 0x66, 0x03, 0x03, 0x73, 0x66, 0x7C, 0x00}, { 0x33, 0x33, 0x33, 0x3F, 0x33, 0x33, 0x33, 0x00}, { 0x1E, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x1E, 0x00}, { 0x78, 0x30, 0x30, 0x30, 0x33, 0x33, 0x1E, 0x00}, { 0x67, 0x66, 0x36, 0x1E, 0x36, 0x66, 0x67, 0x00}, { 0x0F, 0x06, 0x06, 0x06, 0x46, 0x66, 0x7F, 0x00}, { 0x63, 0x77, 0x7F, 0x7F, 0x6B, 0x63, 0x63, 0x00}, { 0x63, 0x67, 0x6F, 0x7B, 0x73, 0x63, 0x63, 0x00}, { 0x1C, 0x36, 0x63, 0x63, 0x63, 0x36, 0x1C, 0x00}, { 0x3F, 0x66, 0x66, 0x3E, 0x06, 0x06, 0x0F, 0x00}, { 0x1E, 0x33, 0x33, 0x33, 0x3B, 0x1E, 0x38, 0x00}, { 0x3F, 0x66, 0x66, 0x3E, 0x36, 0x66, 0x67, 0x00}, { 0x1E, 0x33, 0x07, 0x0E, 0x38, 0x33, 0x1E, 0x00}, { 0x3F, 0x2D, 0x0C, 0x0C, 0x0C, 0x0C, 0x1E, 0x00}, { 0x33, 0x33, 0x33, 0x33, 0x33, 0x33, 0x3F, 0x00}, { 0x33, 0x33, 0x33, 0x33, 0x33, 0x1E, 0x0C, 0x00}, { 0x63, 0x63, 0x63, 0x6B, 0x7F, 0x77, 0x63, 0x00}, { 0x63, 0x63, 0x36, 0x1C, 0x1C, 0x36, 0x63, 0x00}, { 0x33, 0x33, 0x33, 0x1E, 0x0C, 0x0C, 0x1E, 0x00}, { 0x7F, 0x63, 0x31, 0x18, 0x4C, 0x66, 0x7F, 0x00}, { 0x1E, 0x06, 0x06, 0x06, 0x06, 0x06, 0x1E, 0x00}, { 0x03, 0x06, 0x0C, 0x18, 0x30, 0x60, 0x40, 0x00}, { 0x1E, 0x18, 0x18, 0x18, 0x18, 0x18, 0x1E, 0x00}, { 0x08, 0x1C, 0x36, 0x63, 0x00, 0x00, 0x00, 0x00}, { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF}, { 0x0C, 0x0C, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00}, { 0x00, 0x00, 0x1E, 0x30, 0x3E, 0x33, 0x6E, 0x00}, { 0x07, 0x06, 0x06, 0x3E, 0x66, 0x66, 0x3B, 0x00}, { 0x00, 0x00, 0x1E, 0x33, 0x03, 0x33, 0x1E, 0x00}, { 0x38, 0x30, 0x30, 0x3e, 0x33, 0x33, 0x6E, 0x00}, { 0x00, 0x00, 0x1E, 0x33, 0x3f, 0x03, 0x1E, 0x00}, { 0x1C, 0x36, 0x06, 0x0f, 0x06, 0x06, 0x0F, 0x00}, { 0x00, 0x00, 0x6E, 0x33, 0x33, 0x3E, 0x30, 0x1F}, { 0x07, 0x06, 0x36, 0x6E, 0x66, 0x66, 0x67, 0x00}, { 0x0C, 0x00, 0x0E, 0x0C, 0x0C, 0x0C, 0x1E, 0x00}, { 0x30, 0x00, 0x30, 0x30, 0x30, 0x33, 0x33, 0x1E}, { 0x07, 0x06, 0x66, 0x36, 0x1E, 0x36, 0x67, 0x00}, { 0x0E, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x1E, 0x00}, { 0x00, 0x00, 0x33, 0x7F, 0x7F, 0x6B, 0x63, 0x00}, { 0x00, 0x00, 0x1F, 0x33, 0x33, 0x33, 0x33, 0x00}, { 0x00, 0x00, 0x1E, 0x33, 0x33, 0x33, 0x1E, 0x00}, { 0x00, 0x00, 0x3B, 0x66, 0x66, 0x3E, 0x06, 0x0F}, { 0x00, 0x00, 0x6E, 0x33, 0x33, 0x3E, 0x30, 0x78}, { 0x00, 0x00, 0x3B, 0x6E, 0x66, 0x06, 0x0F, 0x00}, { 0x00, 0x00, 0x3E, 0x03, 0x1E, 0x30, 0x1F, 0x00}, { 0x08, 0x0C, 0x3E, 0x0C, 0x0C, 0x2C, 0x18, 0x00}, { 0x00, 0x00, 0x33, 0x33, 0x33, 0x33, 0x6E, 0x00}, { 0x00, 0x00, 0x33, 0x33, 0x33, 0x1E, 0x0C, 0x00}, { 0x00, 0x00, 0x63, 0x6B, 0x7F, 0x7F, 0x36, 0x00}, { 0x00, 0x00, 0x63, 0x36, 0x1C, 0x36, 0x63, 0x00}, { 0x00, 0x00, 0x33, 0x33, 0x33, 0x3E, 0x30, 0x1F}, { 0x00, 0x00, 0x3F, 0x19, 0x0C, 0x26, 0x3F, 0x00}, { 0x38, 0x0C, 0x0C, 0x07, 0x0C, 0x0C, 0x38, 0x00}, { 0x18, 0x18, 0x18, 0x00, 0x18, 0x18, 0x18, 0x00}, { 0x07, 0x0C, 0x0C, 0x38, 0x0C, 0x0C, 0x07, 0x00}, { 0x6E, 0x3B, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00} }; for(int y=y0;y<y0+char_height;y++){ for(int x=x0;x<x0+char_width;x++){ if(y >=0 && y < h && x >=0 && x < w) { int dx = x-x0; int dy = y-y0; int bit = ascii_code > 0x20 && ascii_code < 0x7f ? fonts[ascii_code-0x20][dy] & (0x1 << dx) : 0; if (bit) { dst[(y*w+x)*channel+0] = r; dst[(y*w+x)*channel+1] = g; dst[(y*w+x)*channel+2] = b; } else { dst[(y*w+x)*channel+0] = br; dst[(y*w+x)*channel+1] = bg; dst[(y*w+x)*channel+2] = bb; } } } } } |] resizeRGB8 :: Int -> Int -> Bool -> I.Image I.PixelRGB8 -> I.Image I.PixelRGB8 resizeRGB8 width height keepAspectRatio input = unsafePerformIO $ do let channel = 3 :: Int (I.Image org_w org_h org_vec) = input img@(I.Image w h vec) = I.generateImage (\_ _ -> (I.PixelRGB8 0 0 0)) width height :: I.Image I.PixelRGB8 (org_fptr, org_len) = V.unsafeToForeignPtr0 org_vec org_whc = fromIntegral $ org_w * org_h * channel (fptr, len) = V.unsafeToForeignPtr0 vec whc = fromIntegral $ w * h * channel F.withForeignPtr org_fptr $ \ptr1 -> F.withForeignPtr fptr $ \ptr2 -> do let src = F.castPtr ptr1 dst = F.castPtr ptr2 iw = fromIntegral w ih = fromIntegral h iorg_w = fromIntegral org_w iorg_h = fromIntegral org_h ichannel = fromIntegral channel ckeepAspectRatio = if keepAspectRatio then 1 else 0 [C.block| void { uint8_t* src = $(uint8_t* src); uint8_t* dst = $(uint8_t* dst); int w = $(int iw); int h = $(int ih); int channel = $(int ichannel); int ow = $(int iorg_w); int oh = $(int iorg_h); int keepAspectRatio = $(int ckeepAspectRatio); if(keepAspectRatio){ int t0h = h; int t0w = ow * h / oh; int t1h = oh * w / ow; int t1w = w; if (t0w > w) { int offset = (h - (oh * w / ow))/2; for(int y=offset;y<h-offset;y++){ for(int x=0;x<w;x++){ for(int c=0;c<channel;c++){ int sy = (y-offset) * ow / w; int sx = x * ow / w; if(sy >= 0 && sy < oh){ dst[(y*w+x)*channel+c] = src[(sy*ow+sx)*channel+c]; } } } } } else { int offset = (w - (ow * h / oh))/2; for(int y=0;y<h;y++){ for(int x=offset;x<w-offset;x++){ for(int c=0;c<channel;c++){ int sy = y * oh / h; int sx = (x-offset) * oh / h; if(sx >= 0 && sx < ow){ dst[(y*w+x)*channel+c] = src[(sy*ow+sx)*channel+c]; } } } } } } else { for(int y=0;y<h;y++){ for(int x=0;x<w;x++){ for(int c=0;c<channel;c++){ int sy = y * oh / h; int sx = x * ow / w; dst[(y*w+x)*channel+c] = src[(sy*ow+sx)*channel+c]; } } } } } |] return img pixelFormat :: I.DynamicImage -> PixelFormat pixelFormat image = case image of I.ImageY8 _ -> Y8 I.ImageYF _ -> YF I.ImageYA8 _ -> YA8 I.ImageRGB8 _ -> RGB8 I.ImageRGBF _ -> RGBF I.ImageRGBA8 _ -> RGBA8 I.ImageYCbCr8 _ -> YCbCr8 I.ImageCMYK8 _ -> CMYK8 I.ImageCMYK16 _ -> CMYK16 I.ImageRGBA16 _ -> RGBA16 I.ImageRGB16 _ -> RGB16 I.ImageY16 _ -> Y16 I.ImageYA16 _ -> YA16 I.ImageY32 _ -> Y32 fromDynImage :: I.DynamicImage -> D.Tensor fromDynImage image = unsafePerformIO $ case image of I.ImageY8 (I.Image width height vec) -> createTensor width height 1 D.UInt8 1 vec I.ImageYF (I.Image width height vec) -> createTensor width height 1 D.Float 4 vec I.ImageYA8 (I.Image width height vec) -> createTensor width height 2 D.UInt8 1 vec I.ImageRGB8 (I.Image width height vec) -> createTensor width height 3 D.UInt8 1 vec I.ImageRGBF (I.Image width height vec) -> createTensor width height 3 D.Float 4 vec I.ImageRGBA8 (I.Image width height vec) -> createTensor width height 4 D.UInt8 1 vec I.ImageYCbCr8 (I.Image width height vec) -> createTensor width height 3 D.UInt8 1 vec I.ImageCMYK8 (I.Image width height vec) -> createTensor width height 4 D.UInt8 1 vec I.ImageCMYK16 (I.Image width height vec) -> createTensorU16to32 width height 4 D.Int32 vec I.ImageRGBA16 (I.Image width height vec) -> createTensorU16to32 width height 4 D.Int32 vec I.ImageRGB16 (I.Image width height vec) -> createTensorU16to32 width height 3 D.Int32 vec I.ImageY16 (I.Image width height vec) -> createTensorU16to32 width height 1 D.Int32 vec I.ImageYA16 (I.Image width height vec) -> createTensorU16to32 width height 2 D.Int32 vec I.ImageY32 (I.Image width height vec) -> createTensorU32to64 width height 1 D.Int64 vec where createTensor width height channel dtype dtype_size vec = do t <- ((cast2 LibTorch.empty_lo) :: [Int] -> D.TensorOptions -> IO D.Tensor) [1, height, width, channel] $ D.withDType dtype D.defaultOpts D.withTensor t $ \ptr1 -> do let (fptr, len) = V.unsafeToForeignPtr0 vec whc = width * height * channel * dtype_size F.withForeignPtr fptr $ \ptr2 -> do BSI.memcpy (F.castPtr ptr1) (F.castPtr ptr2) whc return t createTensorU16to32 width height channel dtype vec = do t <- ((cast2 LibTorch.empty_lo) :: [Int] -> D.TensorOptions -> IO D.Tensor) [1, height, width, channel] $ D.withDType dtype D.defaultOpts D.withTensor t $ \ptr1 -> do let (fptr, len) = V.unsafeToForeignPtr0 vec whc = fromIntegral $ width * height * channel F.withForeignPtr fptr $ \ptr2 -> do let src = F.castPtr ptr2 dst = F.castPtr ptr1 [C.block| void { uint16_t* src = $(uint16_t* src); int32_t* dst = $(int32_t* dst); for(int i=0;i<$(int whc);i++){ dst[i] = src[i]; } } |] return t createTensorU32to64 width height channel dtype vec = do t <- ((cast2 LibTorch.empty_lo) :: [Int] -> D.TensorOptions -> IO D.Tensor) [1, height, width, channel] $ D.withDType dtype D.defaultOpts D.withTensor t $ \ptr1 -> do let (fptr, len) = V.unsafeToForeignPtr0 vec whc = fromIntegral $ width * height * channel F.withForeignPtr fptr $ \ptr2 -> do let src = F.castPtr ptr2 dst = F.castPtr ptr1 [C.block| void { uint32_t* src = $(uint32_t* src); int64_t* dst = $(int64_t* dst); for(int i=0;i<$(int whc);i++){ dst[i] = src[i]; } } |] return t fromImages :: [I.Image I.PixelRGB8] -> IO D.Tensor fromImages imgs = do let num_imgs = length imgs channel = 3 (I.Image width height _) = head imgs when (num_imgs == 0) $ do throwIO $ userError "The number of images should be greater than 0." t <- ((cast2 LibTorch.empty_lo) :: [Int] -> D.TensorOptions -> IO D.Tensor) [num_imgs, height, width, channel] $ D.withDType D.UInt8 D.defaultOpts D.withTensor t $ \ptr1 -> do forM_ (zip [0 ..] imgs) $ \(idx, (I.Image width' height' vec)) -> do let (fptr, len) = V.unsafeToForeignPtr0 vec whc = width * height * channel when (len /= whc) $ do throwIO $ userError "vector's length is not the same as tensor' one." when (width /= width') $ do throwIO $ userError "image's width is not the same as first image's one" when (height /= height') $ do throwIO $ userError "image's height is not the same as first image's one" F.withForeignPtr fptr $ \ptr2 -> do BSI.memcpy (F.plusPtr (F.castPtr ptr1) (whc * idx)) ptr2 len return t writeImage :: forall p. I.Pixel p => Int -> Int -> Int -> p -> D.Tensor -> IO (I.Image p) writeImage width height channel pixel tensor = do let img@(I.Image w h vec) = I.generateImage (\_ _ -> pixel) width height :: I.Image p D.withTensor tensor $ \ptr1 -> do let (fptr, len) = V.unsafeToForeignPtr0 vec whc = width * height * channel if (len /= whc) then throwIO $ userError $ "vector's length(" ++ show len ++ ") is not the same as tensor' one." else do F.withForeignPtr fptr $ \ptr2 -> do BSI.memcpy (F.castPtr ptr2) (F.castPtr ptr1) len return img writeBitmap :: FilePath -> D.Tensor -> IO () writeBitmap file tensor = do case (D.shape tensor, D.dtype tensor) of ([1, height, width, 1], D.UInt8) -> writeImage width height 1 (0 :: I.Pixel8) tensor >>= I.writeBitmap file ([1, height, width], D.UInt8) -> writeImage width height 1 (0 :: I.Pixel8) tensor >>= I.writeBitmap file ([1, height, width, 3], D.UInt8) -> writeImage width height 3 (I.PixelRGB8 0 0 0) tensor >>= I.writeBitmap file ([height, width, 1], D.UInt8) -> writeImage width height 1 (0 :: I.Pixel8) tensor >>= I.writeBitmap file ([height, width], D.UInt8) -> writeImage width height 1 (0 :: I.Pixel8) tensor >>= I.writeBitmap file ([height, width, 3], D.UInt8) -> writeImage width height 3 (I.PixelRGB8 0 0 0) tensor >>= I.writeBitmap file format -> throwIO $ userError $ "Can not write a image. " ++ show format ++ " is unsupported format." writePng :: FilePath -> D.Tensor -> IO () writePng file tensor = do case (D.shape tensor, D.dtype tensor) of ([1, height, width, 1], D.UInt8) -> writeImage width height 1 (0 :: I.Pixel8) tensor >>= I.writePng file ([1, height, width], D.UInt8) -> writeImage width height 1 (0 :: I.Pixel8) tensor >>= I.writePng file ([1, height, width, 3], D.UInt8) -> writeImage width height 3 (I.PixelRGB8 0 0 0) tensor >>= I.writePng file ([height, width, 1], D.UInt8) -> writeImage width height 1 (0 :: I.Pixel8) tensor >>= I.writePng file ([height, width], D.UInt8) -> writeImage width height 1 (0 :: I.Pixel8) tensor >>= I.writePng file ([height, width, 3], D.UInt8) -> writeImage width height 3 (I.PixelRGB8 0 0 0) tensor >>= I.writePng file format -> throwIO $ userError $ "Can not write a image. " ++ show format ++ " is unsupported format." -- [batch, height, width, channel] -> [batch, channel, height, width] hwc2chw :: D.Tensor -> D.Tensor hwc2chw = D.permute [0, 3, 1, 2] -- [batch, channel, height, width] -> [batch, height, width, channel] chw2hwc :: D.Tensor -> D.Tensor chw2hwc = D.permute [0, 2, 3, 1] randomIndexes :: Int -> [Int] randomIndexes size = (`mod` size) <$> randoms seed where seed = mkStdGen 123
null
https://raw.githubusercontent.com/hasktorch/hasktorch/c34996b0a401a5b1b98b5774e892fde88adaa079/hasktorch/src/Torch/Vision.hs
haskell
dimensionality of the data mnist data representation indices of the dataset / Display an MNIST image tensor as ascii text [batch, height, width, channel] -> [batch, channel, height, width] [batch, channel, height, width] -> [batch, height, width, channel]
# LANGUAGE FlexibleContexts # # LANGUAGE FlexibleInstances # # LANGUAGE KindSignatures # # LANGUAGE LambdaCase # # LANGUAGE MultiParamTypeClasses # # LANGUAGE QuasiQuotes # # LANGUAGE RecordWildCards # # LANGUAGE ScopedTypeVariables # # LANGUAGE TemplateHaskell # module Torch.Vision where import qualified Codec.Picture as I import Control.Exception.Safe ( SomeException (..), throwIO, try, ) import Control.Monad ( MonadPlus, forM_, when, ) import qualified Data.ByteString as BS import qualified Data.ByteString.Internal as BSI import Data.Int import qualified Data.Vector.Storable as V import Data.Word import qualified Foreign.ForeignPtr as F import qualified Foreign.Ptr as F import GHC.Exts (IsList (fromList)) import qualified Language.C.Inline as C import Pipes import System.IO.Unsafe import System.Random (mkStdGen, randoms) import qualified Torch.DType as D import Torch.Data.Pipeline import Torch.Data.StreamedPipeline import Torch.Functional hiding (take) import qualified Torch.Functional as D import Torch.Internal.Cast import qualified Torch.Internal.Managed.TensorFactories as LibTorch import Torch.NN import Torch.Tensor import qualified Torch.Tensor as D import qualified Torch.TensorOptions as D import qualified Torch.Typed.Vision as I import Prelude hiding (max, min) import qualified Prelude as P C.include "<stdint.h>" data MNIST (m :: * -> *) = MNIST { batchSize :: Int, mnistData :: I.MnistData } instance Monad m => Datastream m Int (MNIST m) (Tensor, Tensor) where streamSamples MNIST {..} seed = Select $ for (each [1 .. numIters]) $ \iter -> do let from = (iter -1) * batchSize to = (iter * batchSize) - 1 indexes = [from .. to] target = getLabels' batchSize mnistData indexes let input = getImages' batchSize 784 mnistData indexes yield (input, target) where numIters = I.length mnistData `Prelude.div` batchSize instance Applicative m => Dataset m (MNIST m) Int (Tensor, Tensor) where getItem MNIST {..} ix = let indexes = [ix * batchSize .. (ix + 1) * batchSize - 1] imgs = getImages' batchSize 784 mnistData indexes labels = getLabels' batchSize mnistData indexes in pure (imgs, labels) keys MNIST {..} = fromList [0 .. I.length mnistData `Prelude.div` batchSize - 1] getLabels' :: Int -> I.MnistData -> [Int] -> Tensor getLabels' n mnist imageIdxs = asTensor $ map (I.getLabel mnist) . take n $ imageIdxs getImages' :: number of observations in minibatch Tensor getImages' n dataDim mnist imageIdxs = unsafePerformIO $ do let (BSI.PS fptr off len) = I.images mnist t <- (cast2 LibTorch.empty_lo :: [Int] -> D.TensorOptions -> IO D.Tensor) [n, dataDim] (D.withDType D.UInt8 D.defaultOpts) D.withTensor t $ \ptr1 -> do F.withForeignPtr fptr $ \ptr2 -> do forM_ (zip [0 .. (n -1)] imageIdxs) $ \(i, idx) -> do BSI.memcpy (F.plusPtr ptr1 (dataDim * i)) (F.plusPtr ptr2 (off + 16 + dataDim * idx)) dataDim return $ D.toType D.Float t grayScale10 = " .:-=+*#%@" grayScale70 = reverse "$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\\|()1{}[]?-_+~<>i!lI;:,\"^`'. " dispImage :: Tensor -> IO () dispImage img = do mapM ( \row -> mapM ( \col -> putChar $ grayScale !! (P.floor $ scaled !! row !! col) ) [0, downSamp .. 27] >> putStrLn "" ) [0, downSamp .. 27] pure () where downSamp = 2 grayScale = grayScale10 paletteMax = (fromIntegral $ length grayScale) - 1.0 img' = reshape [28, 28] img scaled :: [[Float]] = let (mn, mx) = (min img', max img') in asValue $ (img' - mn) / (mx - mn) * paletteMax data PixelFormat = Y8 | YF | YA8 | RGB8 | RGBF | RGBA8 | YCbCr8 | CMYK8 | CMYK16 | RGBA16 | RGB16 | Y16 | YA16 | Y32 deriving (Show, Eq) readImage :: FilePath -> IO (Either String (D.Tensor, PixelFormat)) readImage file = I.readImage file >>= \case Left err -> return $ Left err Right img' -> return $ Right $ (fromDynImage img', pixelFormat img') readImageAsRGB8 :: FilePath -> IO (Either String D.Tensor) readImageAsRGB8 file = I.readImage file >>= \case Left err -> return $ Left err Right img' -> return . Right . fromDynImage . I.ImageRGB8 . I.convertRGB8 $ img' readImageAsRGB8WithScaling :: FilePath -> Int -> Int -> Bool -> IO (Either String (I.Image I.PixelRGB8, D.Tensor)) readImageAsRGB8WithScaling file width height keepAspectRatio = I.readImage file >>= \case Left err -> return $ Left err Right img' -> do let img = (resizeRGB8 width height keepAspectRatio) . I.convertRGB8 $ img' return $ Right (img, fromDynImage . I.ImageRGB8 $ img) centerCrop :: Int -> Int -> I.Image I.PixelRGB8 -> I.Image I.PixelRGB8 centerCrop width height input = unsafePerformIO $ do let channel = 3 :: Int (I.Image org_w org_h org_vec) = input img@(I.Image w h vec) = I.generateImage (\_ _ -> (I.PixelRGB8 0 0 0)) width height :: I.Image I.PixelRGB8 (org_fptr, org_len) = V.unsafeToForeignPtr0 org_vec org_whc = fromIntegral $ org_w * org_h * channel (fptr, len) = V.unsafeToForeignPtr0 vec whc = fromIntegral $ w * h * channel F.withForeignPtr org_fptr $ \ptr1 -> F.withForeignPtr fptr $ \ptr2 -> do let src = F.castPtr ptr1 dst = F.castPtr ptr2 iw = fromIntegral w ih = fromIntegral h iorg_w = fromIntegral org_w iorg_h = fromIntegral org_h ichannel = fromIntegral channel [C.block| void { uint8_t* src = $(uint8_t* src); uint8_t* dst = $(uint8_t* dst); int w = $(int iw); int h = $(int ih); int channel = $(int ichannel); int ow = $(int iorg_w); int oh = $(int iorg_h); int offsetx = (ow - w)/2; int offsety = (oh - h)/2; for(int y=0;y<h;y++){ for(int x=0;x<w;x++){ for(int c=0;c<channel;c++){ int sy = y + offsety; int sx = x + offsetx; if(sx >= 0 && sx < ow && sy >= 0 && sy < oh){ dst[(y*w+x)*channel+c] = src[(sy*ow+sx)*channel+c]; } } } } } |] return img drawLine :: Int -> Int -> Int -> Int -> (Int, Int, Int) -> I.Image I.PixelRGB8 -> IO () drawLine x0 y0 x1 y1 (r, g, b) input = do let img@(I.Image w h vec) = input (fptr, len) = V.unsafeToForeignPtr0 vec F.withForeignPtr fptr $ \ptr2 -> do let iw = fromIntegral w ih = fromIntegral h ix0 = fromIntegral x0 iy0 = fromIntegral y0 ix1 = fromIntegral x1 iy1 = fromIntegral y1 ir = fromIntegral r ig = fromIntegral g ib = fromIntegral b dst = F.castPtr ptr2 [C.block| void { uint8_t* dst = $(uint8_t* dst); int w = $(int iw); int h = $(int ih); int x0 = $(int ix0); int y0 = $(int iy0); int x1 = $(int ix1); int y1 = $(int iy1); int r = $(int ir); int g = $(int ig); int b = $(int ib); int channel = 3; int sign_x = x1 - x0 >= 0 ? 1 : -1; int sign_y = y1 - y0 >= 0 ? 1 : -1; int abs_x = x1 - x0 >= 0 ? x1 - x0 : x0 - x1; int abs_y = y1 - y0 >= 0 ? y1 - y0 : y0 - y1; if(abs_x>=abs_y){ for(int x=x0;x!=x1;x+=sign_x){ int y = (x-x0) * (y1-y0) / (x1-x0) + y0; if(y >=0 && y < h && x >=0 && x < w) { dst[(y*w+x)*channel+0] = r; dst[(y*w+x)*channel+1] = g; dst[(y*w+x)*channel+2] = b; } } } else { for(int y=y0;y!=y1;y+=sign_y){ int x = (y-y0) * (x1-x0) / (y1-y0) + x0; if(y >=0 && y < h && x >=0 && x < w) { dst[(y*w+x)*channel+0] = r; dst[(y*w+x)*channel+1] = g; dst[(y*w+x)*channel+2] = b; } } } } |] drawRect :: Int -> Int -> Int -> Int -> (Int, Int, Int) -> I.Image I.PixelRGB8 -> IO () drawRect x0 y0 x1 y1 (r, g, b) input = do drawLine x0 y0 (x1 + 1) y0 (r, g, b) input drawLine x0 y0 x0 (y1 + 1) (r, g, b) input drawLine x0 y1 (x1 + 1) y1 (r, g, b) input drawLine x1 y0 x1 (y1 + 1) (r, g, b) input drawString :: String -> Int -> Int -> (Int, Int, Int) -> (Int, Int, Int) -> I.Image I.PixelRGB8 -> IO () drawString text x0 y0 (r, g, b) (br, bg, bb) input = do forM_ (zip [0 ..] text) $ \(i, ch) -> do drawChar (fromEnum ch) (x0 + i * 8) y0 (r, g, b) (br, bg, bb) input drawChar :: Int -> Int -> Int -> (Int, Int, Int) -> (Int, Int, Int) -> I.Image I.PixelRGB8 -> IO () drawChar ascii_code x0 y0 (r, g, b) (br, bg, bb) input = do let img@(I.Image w h vec) = input (fptr, len) = V.unsafeToForeignPtr0 vec F.withForeignPtr fptr $ \ptr2 -> do let iw = fromIntegral w ih = fromIntegral h ix0 = fromIntegral x0 iy0 = fromIntegral y0 ir = fromIntegral r ig = fromIntegral g ib = fromIntegral b ibr = fromIntegral br ibg = fromIntegral bg ibb = fromIntegral bb dst = F.castPtr ptr2 iascii_code = fromIntegral ascii_code [C.block| void { uint8_t* dst = $(uint8_t* dst); int w = $(int iw); int h = $(int ih); int x0 = $(int ix0); int y0 = $(int iy0); int r = $(int ir); int g = $(int ig); int b = $(int ib); int br = $(int ibr); int bg = $(int ibg); int bb = $(int ibb); int ascii_code = $(int iascii_code); int channel = 3; int char_width = 8; int char_height = 8; char fonts[95][8] = { // 0x20 to 0x7e { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, { 0x18, 0x3C, 0x3C, 0x18, 0x18, 0x00, 0x18, 0x00}, { 0x36, 0x36, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, { 0x36, 0x36, 0x7F, 0x36, 0x7F, 0x36, 0x36, 0x00}, { 0x0C, 0x3E, 0x03, 0x1E, 0x30, 0x1F, 0x0C, 0x00}, { 0x00, 0x63, 0x33, 0x18, 0x0C, 0x66, 0x63, 0x00}, { 0x1C, 0x36, 0x1C, 0x6E, 0x3B, 0x33, 0x6E, 0x00}, { 0x06, 0x06, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00}, { 0x18, 0x0C, 0x06, 0x06, 0x06, 0x0C, 0x18, 0x00}, { 0x06, 0x0C, 0x18, 0x18, 0x18, 0x0C, 0x06, 0x00}, { 0x00, 0x66, 0x3C, 0xFF, 0x3C, 0x66, 0x00, 0x00}, { 0x00, 0x0C, 0x0C, 0x3F, 0x0C, 0x0C, 0x00, 0x00}, { 0x00, 0x00, 0x00, 0x00, 0x00, 0x0C, 0x0C, 0x06}, { 0x00, 0x00, 0x00, 0x3F, 0x00, 0x00, 0x00, 0x00}, { 0x00, 0x00, 0x00, 0x00, 0x00, 0x0C, 0x0C, 0x00}, { 0x60, 0x30, 0x18, 0x0C, 0x06, 0x03, 0x01, 0x00}, { 0x3E, 0x63, 0x73, 0x7B, 0x6F, 0x67, 0x3E, 0x00}, { 0x0C, 0x0E, 0x0C, 0x0C, 0x0C, 0x0C, 0x3F, 0x00}, { 0x1E, 0x33, 0x30, 0x1C, 0x06, 0x33, 0x3F, 0x00}, { 0x1E, 0x33, 0x30, 0x1C, 0x30, 0x33, 0x1E, 0x00}, { 0x38, 0x3C, 0x36, 0x33, 0x7F, 0x30, 0x78, 0x00}, { 0x3F, 0x03, 0x1F, 0x30, 0x30, 0x33, 0x1E, 0x00}, { 0x1C, 0x06, 0x03, 0x1F, 0x33, 0x33, 0x1E, 0x00}, { 0x3F, 0x33, 0x30, 0x18, 0x0C, 0x0C, 0x0C, 0x00}, { 0x1E, 0x33, 0x33, 0x1E, 0x33, 0x33, 0x1E, 0x00}, { 0x1E, 0x33, 0x33, 0x3E, 0x30, 0x18, 0x0E, 0x00}, { 0x00, 0x0C, 0x0C, 0x00, 0x00, 0x0C, 0x0C, 0x00}, { 0x00, 0x0C, 0x0C, 0x00, 0x00, 0x0C, 0x0C, 0x06}, { 0x18, 0x0C, 0x06, 0x03, 0x06, 0x0C, 0x18, 0x00}, { 0x00, 0x00, 0x3F, 0x00, 0x00, 0x3F, 0x00, 0x00}, { 0x06, 0x0C, 0x18, 0x30, 0x18, 0x0C, 0x06, 0x00}, { 0x1E, 0x33, 0x30, 0x18, 0x0C, 0x00, 0x0C, 0x00}, { 0x3E, 0x63, 0x7B, 0x7B, 0x7B, 0x03, 0x1E, 0x00}, { 0x0C, 0x1E, 0x33, 0x33, 0x3F, 0x33, 0x33, 0x00}, { 0x3F, 0x66, 0x66, 0x3E, 0x66, 0x66, 0x3F, 0x00}, { 0x3C, 0x66, 0x03, 0x03, 0x03, 0x66, 0x3C, 0x00}, { 0x1F, 0x36, 0x66, 0x66, 0x66, 0x36, 0x1F, 0x00}, { 0x7F, 0x46, 0x16, 0x1E, 0x16, 0x46, 0x7F, 0x00}, { 0x7F, 0x46, 0x16, 0x1E, 0x16, 0x06, 0x0F, 0x00}, { 0x3C, 0x66, 0x03, 0x03, 0x73, 0x66, 0x7C, 0x00}, { 0x33, 0x33, 0x33, 0x3F, 0x33, 0x33, 0x33, 0x00}, { 0x1E, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x1E, 0x00}, { 0x78, 0x30, 0x30, 0x30, 0x33, 0x33, 0x1E, 0x00}, { 0x67, 0x66, 0x36, 0x1E, 0x36, 0x66, 0x67, 0x00}, { 0x0F, 0x06, 0x06, 0x06, 0x46, 0x66, 0x7F, 0x00}, { 0x63, 0x77, 0x7F, 0x7F, 0x6B, 0x63, 0x63, 0x00}, { 0x63, 0x67, 0x6F, 0x7B, 0x73, 0x63, 0x63, 0x00}, { 0x1C, 0x36, 0x63, 0x63, 0x63, 0x36, 0x1C, 0x00}, { 0x3F, 0x66, 0x66, 0x3E, 0x06, 0x06, 0x0F, 0x00}, { 0x1E, 0x33, 0x33, 0x33, 0x3B, 0x1E, 0x38, 0x00}, { 0x3F, 0x66, 0x66, 0x3E, 0x36, 0x66, 0x67, 0x00}, { 0x1E, 0x33, 0x07, 0x0E, 0x38, 0x33, 0x1E, 0x00}, { 0x3F, 0x2D, 0x0C, 0x0C, 0x0C, 0x0C, 0x1E, 0x00}, { 0x33, 0x33, 0x33, 0x33, 0x33, 0x33, 0x3F, 0x00}, { 0x33, 0x33, 0x33, 0x33, 0x33, 0x1E, 0x0C, 0x00}, { 0x63, 0x63, 0x63, 0x6B, 0x7F, 0x77, 0x63, 0x00}, { 0x63, 0x63, 0x36, 0x1C, 0x1C, 0x36, 0x63, 0x00}, { 0x33, 0x33, 0x33, 0x1E, 0x0C, 0x0C, 0x1E, 0x00}, { 0x7F, 0x63, 0x31, 0x18, 0x4C, 0x66, 0x7F, 0x00}, { 0x1E, 0x06, 0x06, 0x06, 0x06, 0x06, 0x1E, 0x00}, { 0x03, 0x06, 0x0C, 0x18, 0x30, 0x60, 0x40, 0x00}, { 0x1E, 0x18, 0x18, 0x18, 0x18, 0x18, 0x1E, 0x00}, { 0x08, 0x1C, 0x36, 0x63, 0x00, 0x00, 0x00, 0x00}, { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF}, { 0x0C, 0x0C, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00}, { 0x00, 0x00, 0x1E, 0x30, 0x3E, 0x33, 0x6E, 0x00}, { 0x07, 0x06, 0x06, 0x3E, 0x66, 0x66, 0x3B, 0x00}, { 0x00, 0x00, 0x1E, 0x33, 0x03, 0x33, 0x1E, 0x00}, { 0x38, 0x30, 0x30, 0x3e, 0x33, 0x33, 0x6E, 0x00}, { 0x00, 0x00, 0x1E, 0x33, 0x3f, 0x03, 0x1E, 0x00}, { 0x1C, 0x36, 0x06, 0x0f, 0x06, 0x06, 0x0F, 0x00}, { 0x00, 0x00, 0x6E, 0x33, 0x33, 0x3E, 0x30, 0x1F}, { 0x07, 0x06, 0x36, 0x6E, 0x66, 0x66, 0x67, 0x00}, { 0x0C, 0x00, 0x0E, 0x0C, 0x0C, 0x0C, 0x1E, 0x00}, { 0x30, 0x00, 0x30, 0x30, 0x30, 0x33, 0x33, 0x1E}, { 0x07, 0x06, 0x66, 0x36, 0x1E, 0x36, 0x67, 0x00}, { 0x0E, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x1E, 0x00}, { 0x00, 0x00, 0x33, 0x7F, 0x7F, 0x6B, 0x63, 0x00}, { 0x00, 0x00, 0x1F, 0x33, 0x33, 0x33, 0x33, 0x00}, { 0x00, 0x00, 0x1E, 0x33, 0x33, 0x33, 0x1E, 0x00}, { 0x00, 0x00, 0x3B, 0x66, 0x66, 0x3E, 0x06, 0x0F}, { 0x00, 0x00, 0x6E, 0x33, 0x33, 0x3E, 0x30, 0x78}, { 0x00, 0x00, 0x3B, 0x6E, 0x66, 0x06, 0x0F, 0x00}, { 0x00, 0x00, 0x3E, 0x03, 0x1E, 0x30, 0x1F, 0x00}, { 0x08, 0x0C, 0x3E, 0x0C, 0x0C, 0x2C, 0x18, 0x00}, { 0x00, 0x00, 0x33, 0x33, 0x33, 0x33, 0x6E, 0x00}, { 0x00, 0x00, 0x33, 0x33, 0x33, 0x1E, 0x0C, 0x00}, { 0x00, 0x00, 0x63, 0x6B, 0x7F, 0x7F, 0x36, 0x00}, { 0x00, 0x00, 0x63, 0x36, 0x1C, 0x36, 0x63, 0x00}, { 0x00, 0x00, 0x33, 0x33, 0x33, 0x3E, 0x30, 0x1F}, { 0x00, 0x00, 0x3F, 0x19, 0x0C, 0x26, 0x3F, 0x00}, { 0x38, 0x0C, 0x0C, 0x07, 0x0C, 0x0C, 0x38, 0x00}, { 0x18, 0x18, 0x18, 0x00, 0x18, 0x18, 0x18, 0x00}, { 0x07, 0x0C, 0x0C, 0x38, 0x0C, 0x0C, 0x07, 0x00}, { 0x6E, 0x3B, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00} }; for(int y=y0;y<y0+char_height;y++){ for(int x=x0;x<x0+char_width;x++){ if(y >=0 && y < h && x >=0 && x < w) { int dx = x-x0; int dy = y-y0; int bit = ascii_code > 0x20 && ascii_code < 0x7f ? fonts[ascii_code-0x20][dy] & (0x1 << dx) : 0; if (bit) { dst[(y*w+x)*channel+0] = r; dst[(y*w+x)*channel+1] = g; dst[(y*w+x)*channel+2] = b; } else { dst[(y*w+x)*channel+0] = br; dst[(y*w+x)*channel+1] = bg; dst[(y*w+x)*channel+2] = bb; } } } } } |] resizeRGB8 :: Int -> Int -> Bool -> I.Image I.PixelRGB8 -> I.Image I.PixelRGB8 resizeRGB8 width height keepAspectRatio input = unsafePerformIO $ do let channel = 3 :: Int (I.Image org_w org_h org_vec) = input img@(I.Image w h vec) = I.generateImage (\_ _ -> (I.PixelRGB8 0 0 0)) width height :: I.Image I.PixelRGB8 (org_fptr, org_len) = V.unsafeToForeignPtr0 org_vec org_whc = fromIntegral $ org_w * org_h * channel (fptr, len) = V.unsafeToForeignPtr0 vec whc = fromIntegral $ w * h * channel F.withForeignPtr org_fptr $ \ptr1 -> F.withForeignPtr fptr $ \ptr2 -> do let src = F.castPtr ptr1 dst = F.castPtr ptr2 iw = fromIntegral w ih = fromIntegral h iorg_w = fromIntegral org_w iorg_h = fromIntegral org_h ichannel = fromIntegral channel ckeepAspectRatio = if keepAspectRatio then 1 else 0 [C.block| void { uint8_t* src = $(uint8_t* src); uint8_t* dst = $(uint8_t* dst); int w = $(int iw); int h = $(int ih); int channel = $(int ichannel); int ow = $(int iorg_w); int oh = $(int iorg_h); int keepAspectRatio = $(int ckeepAspectRatio); if(keepAspectRatio){ int t0h = h; int t0w = ow * h / oh; int t1h = oh * w / ow; int t1w = w; if (t0w > w) { int offset = (h - (oh * w / ow))/2; for(int y=offset;y<h-offset;y++){ for(int x=0;x<w;x++){ for(int c=0;c<channel;c++){ int sy = (y-offset) * ow / w; int sx = x * ow / w; if(sy >= 0 && sy < oh){ dst[(y*w+x)*channel+c] = src[(sy*ow+sx)*channel+c]; } } } } } else { int offset = (w - (ow * h / oh))/2; for(int y=0;y<h;y++){ for(int x=offset;x<w-offset;x++){ for(int c=0;c<channel;c++){ int sy = y * oh / h; int sx = (x-offset) * oh / h; if(sx >= 0 && sx < ow){ dst[(y*w+x)*channel+c] = src[(sy*ow+sx)*channel+c]; } } } } } } else { for(int y=0;y<h;y++){ for(int x=0;x<w;x++){ for(int c=0;c<channel;c++){ int sy = y * oh / h; int sx = x * ow / w; dst[(y*w+x)*channel+c] = src[(sy*ow+sx)*channel+c]; } } } } } |] return img pixelFormat :: I.DynamicImage -> PixelFormat pixelFormat image = case image of I.ImageY8 _ -> Y8 I.ImageYF _ -> YF I.ImageYA8 _ -> YA8 I.ImageRGB8 _ -> RGB8 I.ImageRGBF _ -> RGBF I.ImageRGBA8 _ -> RGBA8 I.ImageYCbCr8 _ -> YCbCr8 I.ImageCMYK8 _ -> CMYK8 I.ImageCMYK16 _ -> CMYK16 I.ImageRGBA16 _ -> RGBA16 I.ImageRGB16 _ -> RGB16 I.ImageY16 _ -> Y16 I.ImageYA16 _ -> YA16 I.ImageY32 _ -> Y32 fromDynImage :: I.DynamicImage -> D.Tensor fromDynImage image = unsafePerformIO $ case image of I.ImageY8 (I.Image width height vec) -> createTensor width height 1 D.UInt8 1 vec I.ImageYF (I.Image width height vec) -> createTensor width height 1 D.Float 4 vec I.ImageYA8 (I.Image width height vec) -> createTensor width height 2 D.UInt8 1 vec I.ImageRGB8 (I.Image width height vec) -> createTensor width height 3 D.UInt8 1 vec I.ImageRGBF (I.Image width height vec) -> createTensor width height 3 D.Float 4 vec I.ImageRGBA8 (I.Image width height vec) -> createTensor width height 4 D.UInt8 1 vec I.ImageYCbCr8 (I.Image width height vec) -> createTensor width height 3 D.UInt8 1 vec I.ImageCMYK8 (I.Image width height vec) -> createTensor width height 4 D.UInt8 1 vec I.ImageCMYK16 (I.Image width height vec) -> createTensorU16to32 width height 4 D.Int32 vec I.ImageRGBA16 (I.Image width height vec) -> createTensorU16to32 width height 4 D.Int32 vec I.ImageRGB16 (I.Image width height vec) -> createTensorU16to32 width height 3 D.Int32 vec I.ImageY16 (I.Image width height vec) -> createTensorU16to32 width height 1 D.Int32 vec I.ImageYA16 (I.Image width height vec) -> createTensorU16to32 width height 2 D.Int32 vec I.ImageY32 (I.Image width height vec) -> createTensorU32to64 width height 1 D.Int64 vec where createTensor width height channel dtype dtype_size vec = do t <- ((cast2 LibTorch.empty_lo) :: [Int] -> D.TensorOptions -> IO D.Tensor) [1, height, width, channel] $ D.withDType dtype D.defaultOpts D.withTensor t $ \ptr1 -> do let (fptr, len) = V.unsafeToForeignPtr0 vec whc = width * height * channel * dtype_size F.withForeignPtr fptr $ \ptr2 -> do BSI.memcpy (F.castPtr ptr1) (F.castPtr ptr2) whc return t createTensorU16to32 width height channel dtype vec = do t <- ((cast2 LibTorch.empty_lo) :: [Int] -> D.TensorOptions -> IO D.Tensor) [1, height, width, channel] $ D.withDType dtype D.defaultOpts D.withTensor t $ \ptr1 -> do let (fptr, len) = V.unsafeToForeignPtr0 vec whc = fromIntegral $ width * height * channel F.withForeignPtr fptr $ \ptr2 -> do let src = F.castPtr ptr2 dst = F.castPtr ptr1 [C.block| void { uint16_t* src = $(uint16_t* src); int32_t* dst = $(int32_t* dst); for(int i=0;i<$(int whc);i++){ dst[i] = src[i]; } } |] return t createTensorU32to64 width height channel dtype vec = do t <- ((cast2 LibTorch.empty_lo) :: [Int] -> D.TensorOptions -> IO D.Tensor) [1, height, width, channel] $ D.withDType dtype D.defaultOpts D.withTensor t $ \ptr1 -> do let (fptr, len) = V.unsafeToForeignPtr0 vec whc = fromIntegral $ width * height * channel F.withForeignPtr fptr $ \ptr2 -> do let src = F.castPtr ptr2 dst = F.castPtr ptr1 [C.block| void { uint32_t* src = $(uint32_t* src); int64_t* dst = $(int64_t* dst); for(int i=0;i<$(int whc);i++){ dst[i] = src[i]; } } |] return t fromImages :: [I.Image I.PixelRGB8] -> IO D.Tensor fromImages imgs = do let num_imgs = length imgs channel = 3 (I.Image width height _) = head imgs when (num_imgs == 0) $ do throwIO $ userError "The number of images should be greater than 0." t <- ((cast2 LibTorch.empty_lo) :: [Int] -> D.TensorOptions -> IO D.Tensor) [num_imgs, height, width, channel] $ D.withDType D.UInt8 D.defaultOpts D.withTensor t $ \ptr1 -> do forM_ (zip [0 ..] imgs) $ \(idx, (I.Image width' height' vec)) -> do let (fptr, len) = V.unsafeToForeignPtr0 vec whc = width * height * channel when (len /= whc) $ do throwIO $ userError "vector's length is not the same as tensor' one." when (width /= width') $ do throwIO $ userError "image's width is not the same as first image's one" when (height /= height') $ do throwIO $ userError "image's height is not the same as first image's one" F.withForeignPtr fptr $ \ptr2 -> do BSI.memcpy (F.plusPtr (F.castPtr ptr1) (whc * idx)) ptr2 len return t writeImage :: forall p. I.Pixel p => Int -> Int -> Int -> p -> D.Tensor -> IO (I.Image p) writeImage width height channel pixel tensor = do let img@(I.Image w h vec) = I.generateImage (\_ _ -> pixel) width height :: I.Image p D.withTensor tensor $ \ptr1 -> do let (fptr, len) = V.unsafeToForeignPtr0 vec whc = width * height * channel if (len /= whc) then throwIO $ userError $ "vector's length(" ++ show len ++ ") is not the same as tensor' one." else do F.withForeignPtr fptr $ \ptr2 -> do BSI.memcpy (F.castPtr ptr2) (F.castPtr ptr1) len return img writeBitmap :: FilePath -> D.Tensor -> IO () writeBitmap file tensor = do case (D.shape tensor, D.dtype tensor) of ([1, height, width, 1], D.UInt8) -> writeImage width height 1 (0 :: I.Pixel8) tensor >>= I.writeBitmap file ([1, height, width], D.UInt8) -> writeImage width height 1 (0 :: I.Pixel8) tensor >>= I.writeBitmap file ([1, height, width, 3], D.UInt8) -> writeImage width height 3 (I.PixelRGB8 0 0 0) tensor >>= I.writeBitmap file ([height, width, 1], D.UInt8) -> writeImage width height 1 (0 :: I.Pixel8) tensor >>= I.writeBitmap file ([height, width], D.UInt8) -> writeImage width height 1 (0 :: I.Pixel8) tensor >>= I.writeBitmap file ([height, width, 3], D.UInt8) -> writeImage width height 3 (I.PixelRGB8 0 0 0) tensor >>= I.writeBitmap file format -> throwIO $ userError $ "Can not write a image. " ++ show format ++ " is unsupported format." writePng :: FilePath -> D.Tensor -> IO () writePng file tensor = do case (D.shape tensor, D.dtype tensor) of ([1, height, width, 1], D.UInt8) -> writeImage width height 1 (0 :: I.Pixel8) tensor >>= I.writePng file ([1, height, width], D.UInt8) -> writeImage width height 1 (0 :: I.Pixel8) tensor >>= I.writePng file ([1, height, width, 3], D.UInt8) -> writeImage width height 3 (I.PixelRGB8 0 0 0) tensor >>= I.writePng file ([height, width, 1], D.UInt8) -> writeImage width height 1 (0 :: I.Pixel8) tensor >>= I.writePng file ([height, width], D.UInt8) -> writeImage width height 1 (0 :: I.Pixel8) tensor >>= I.writePng file ([height, width, 3], D.UInt8) -> writeImage width height 3 (I.PixelRGB8 0 0 0) tensor >>= I.writePng file format -> throwIO $ userError $ "Can not write a image. " ++ show format ++ " is unsupported format." hwc2chw :: D.Tensor -> D.Tensor hwc2chw = D.permute [0, 3, 1, 2] chw2hwc :: D.Tensor -> D.Tensor chw2hwc = D.permute [0, 2, 3, 1] randomIndexes :: Int -> [Int] randomIndexes size = (`mod` size) <$> randoms seed where seed = mkStdGen 123
8071804e23bf1871b2eb59979615a5dcaff32cce2635dd45354f6146fb038362
Eduap-com/WordMat
cfftmf.lisp
;;; Compiled by f2cl version: ( " f2cl1.l , v 95098eb54f13 2013/04/01 00:45:16 toy $ " " f2cl2.l , v 95098eb54f13 2013/04/01 00:45:16 toy $ " " f2cl3.l , v 96616d88fb7e 2008/02/22 22:19:34 rtoy $ " " f2cl4.l , v 96616d88fb7e 2008/02/22 22:19:34 rtoy $ " " f2cl5.l , v 95098eb54f13 2013/04/01 00:45:16 toy $ " " f2cl6.l , v 1d5cbacbb977 2008/08/24 00:56:27 rtoy $ " " macros.l , v 1409c1352feb 2013/03/24 20:44:50 toy $ " ) ;;; Using Lisp CMU Common Lisp snapshot-2020-04 (21D Unicode) ;;; ;;; Options: ((:prune-labels nil) (:auto-save t) (:relaxed-array-decls t) ;;; (:coerce-assigns :as-needed) (:array-type ':array) ;;; (:array-slicing t) (:declare-common nil) ;;; (:float-format single-float)) (in-package "FFTPACK5") (defun cfftmf (lot jump n inc c lenc wsave lensav work lenwrk ier) (declare (type (array double-float (*)) work wsave) (type (array f2cl-lib:complex16 (*)) c) (type (f2cl-lib:integer4) ier lenwrk lensav lenc inc n jump lot)) (f2cl-lib:with-multi-array-data ((c f2cl-lib:complex16 c-%data% c-%offset%) (wsave double-float wsave-%data% wsave-%offset%) (work double-float work-%data% work-%offset%)) (prog ((iw1 0)) (declare (type (f2cl-lib:integer4) iw1)) (setf ier 0) (cond ((< lenc (f2cl-lib:int-add (f2cl-lib:int-mul (f2cl-lib:int-add lot (f2cl-lib:int-sub 1)) jump) (f2cl-lib:int-mul inc (f2cl-lib:int-add n (f2cl-lib:int-sub 1))) 1)) (setf ier 1) (xerfft "CFFTMF " 6)) ((< lensav (f2cl-lib:int-add (f2cl-lib:int-mul 2 n) (f2cl-lib:int (f2cl-lib:f2cl/ (f2cl-lib:flog (f2cl-lib:freal n)) (f2cl-lib:flog 2.0d0))) 4)) (setf ier 2) (xerfft "CFFTMF " 8)) ((< lenwrk (f2cl-lib:int-mul 2 lot n)) (setf ier 3) (xerfft "CFFTMF " 10)) ((not (xercon inc jump n lot)) (setf ier 4) (xerfft "CFFTMF " -1))) (if (= n 1) (go end_label)) (setf iw1 (f2cl-lib:int-add n n 1)) (cmfm1f lot jump n inc c work wsave (f2cl-lib:fref wsave-%data% (iw1) ((1 lensav)) wsave-%offset%) (f2cl-lib:array-slice wsave-%data% double-float ((+ iw1 1)) ((1 lensav)) wsave-%offset%)) (go end_label) end_label (return (values nil nil nil nil nil nil nil nil nil nil ier))))) (in-package #-gcl #:cl-user #+gcl "CL-USER") #+#.(cl:if (cl:find-package '#:f2cl) '(and) '(or)) (eval-when (:load-toplevel :compile-toplevel :execute) (setf (gethash 'fortran-to-lisp::cfftmf fortran-to-lisp::*f2cl-function-info*) (fortran-to-lisp::make-f2cl-finfo :arg-types '((fortran-to-lisp::integer4) (fortran-to-lisp::integer4) (fortran-to-lisp::integer4) (fortran-to-lisp::integer4) (array fortran-to-lisp::complex16 (*)) (fortran-to-lisp::integer4) (array double-float (*)) (fortran-to-lisp::integer4) (array double-float (*)) (fortran-to-lisp::integer4) (fortran-to-lisp::integer4)) :return-values '(nil nil nil nil nil nil nil nil nil nil fortran-to-lisp::ier) :calls '(fortran-to-lisp::cmfm1f fortran-to-lisp::xercon fortran-to-lisp::xerfft))))
null
https://raw.githubusercontent.com/Eduap-com/WordMat/83c9336770067f54431cc42c7147dc6ed640a339/Windows/ExternalPrograms/maxima-5.45.1/share/maxima/5.45.1/share/fftpack5/lisp/cfftmf.lisp
lisp
Compiled by f2cl version: Using Lisp CMU Common Lisp snapshot-2020-04 (21D Unicode) Options: ((:prune-labels nil) (:auto-save t) (:relaxed-array-decls t) (:coerce-assigns :as-needed) (:array-type ':array) (:array-slicing t) (:declare-common nil) (:float-format single-float))
( " f2cl1.l , v 95098eb54f13 2013/04/01 00:45:16 toy $ " " f2cl2.l , v 95098eb54f13 2013/04/01 00:45:16 toy $ " " f2cl3.l , v 96616d88fb7e 2008/02/22 22:19:34 rtoy $ " " f2cl4.l , v 96616d88fb7e 2008/02/22 22:19:34 rtoy $ " " f2cl5.l , v 95098eb54f13 2013/04/01 00:45:16 toy $ " " f2cl6.l , v 1d5cbacbb977 2008/08/24 00:56:27 rtoy $ " " macros.l , v 1409c1352feb 2013/03/24 20:44:50 toy $ " ) (in-package "FFTPACK5") (defun cfftmf (lot jump n inc c lenc wsave lensav work lenwrk ier) (declare (type (array double-float (*)) work wsave) (type (array f2cl-lib:complex16 (*)) c) (type (f2cl-lib:integer4) ier lenwrk lensav lenc inc n jump lot)) (f2cl-lib:with-multi-array-data ((c f2cl-lib:complex16 c-%data% c-%offset%) (wsave double-float wsave-%data% wsave-%offset%) (work double-float work-%data% work-%offset%)) (prog ((iw1 0)) (declare (type (f2cl-lib:integer4) iw1)) (setf ier 0) (cond ((< lenc (f2cl-lib:int-add (f2cl-lib:int-mul (f2cl-lib:int-add lot (f2cl-lib:int-sub 1)) jump) (f2cl-lib:int-mul inc (f2cl-lib:int-add n (f2cl-lib:int-sub 1))) 1)) (setf ier 1) (xerfft "CFFTMF " 6)) ((< lensav (f2cl-lib:int-add (f2cl-lib:int-mul 2 n) (f2cl-lib:int (f2cl-lib:f2cl/ (f2cl-lib:flog (f2cl-lib:freal n)) (f2cl-lib:flog 2.0d0))) 4)) (setf ier 2) (xerfft "CFFTMF " 8)) ((< lenwrk (f2cl-lib:int-mul 2 lot n)) (setf ier 3) (xerfft "CFFTMF " 10)) ((not (xercon inc jump n lot)) (setf ier 4) (xerfft "CFFTMF " -1))) (if (= n 1) (go end_label)) (setf iw1 (f2cl-lib:int-add n n 1)) (cmfm1f lot jump n inc c work wsave (f2cl-lib:fref wsave-%data% (iw1) ((1 lensav)) wsave-%offset%) (f2cl-lib:array-slice wsave-%data% double-float ((+ iw1 1)) ((1 lensav)) wsave-%offset%)) (go end_label) end_label (return (values nil nil nil nil nil nil nil nil nil nil ier))))) (in-package #-gcl #:cl-user #+gcl "CL-USER") #+#.(cl:if (cl:find-package '#:f2cl) '(and) '(or)) (eval-when (:load-toplevel :compile-toplevel :execute) (setf (gethash 'fortran-to-lisp::cfftmf fortran-to-lisp::*f2cl-function-info*) (fortran-to-lisp::make-f2cl-finfo :arg-types '((fortran-to-lisp::integer4) (fortran-to-lisp::integer4) (fortran-to-lisp::integer4) (fortran-to-lisp::integer4) (array fortran-to-lisp::complex16 (*)) (fortran-to-lisp::integer4) (array double-float (*)) (fortran-to-lisp::integer4) (array double-float (*)) (fortran-to-lisp::integer4) (fortran-to-lisp::integer4)) :return-values '(nil nil nil nil nil nil nil nil nil nil fortran-to-lisp::ier) :calls '(fortran-to-lisp::cmfm1f fortran-to-lisp::xercon fortran-to-lisp::xerfft))))
8675cbd1412de8ecd17856b0e52d24e53697d35ffe12778bfd05c1ad4c1b043e
tel/saltine
UtilProperties.hs
{-# LANGUAGE OverloadedStrings #-} module UtilProperties ( testUtils ) where import Test.Framework.Providers.QuickCheck2 import Test.Framework import Test.QuickCheck import Util import qualified Crypto.Saltine.Internal.Util as U -- | Testing the comparison of keys keyEquality :: ByteString32 -> Property keyEquality k@(ByteString32 bs1) = k === k .&. U.compare bs1 bs1 keyInequality :: ByteString32 -> ByteString32 -> Property keyInequality k1@(ByteString32 bs1) k2@(ByteString32 bs2) = k1 /= k2 ==> not $ U.compare bs1 bs2 testUtils :: Test testUtils = buildTest $ do return $ testGroup "...Utils" [ testProperty "ByteString equality" keyEquality, testProperty "ByteString inequality" keyInequality ]
null
https://raw.githubusercontent.com/tel/saltine/b00e00fa8ce8bf4ee176a9d3deead57c590fc686/tests/UtilProperties.hs
haskell
# LANGUAGE OverloadedStrings # | Testing the comparison of keys
module UtilProperties ( testUtils ) where import Test.Framework.Providers.QuickCheck2 import Test.Framework import Test.QuickCheck import Util import qualified Crypto.Saltine.Internal.Util as U keyEquality :: ByteString32 -> Property keyEquality k@(ByteString32 bs1) = k === k .&. U.compare bs1 bs1 keyInequality :: ByteString32 -> ByteString32 -> Property keyInequality k1@(ByteString32 bs1) k2@(ByteString32 bs2) = k1 /= k2 ==> not $ U.compare bs1 bs2 testUtils :: Test testUtils = buildTest $ do return $ testGroup "...Utils" [ testProperty "ByteString equality" keyEquality, testProperty "ByteString inequality" keyInequality ]
49cf46f10fb8c4616f7a768ef54f3ba72e9426192f94beaa9c3da844687ae407
antifuchs/sbcl
arith.lisp
(in-package "SB!VM") Multiplication and Division helping routines . ;;; ?? FIXME: Where are generic-* and generic-/? #+sb-assembling (define-assembly-routine multiply ((:arg x (signed-reg) nl0-offset) (:arg y (signed-reg) nl1-offset) (:res res (signed-reg) nl2-offset) (:temp tmp (unsigned-reg) nl3-offset) (:temp sign (unsigned-reg) nl4-offset)) ;; Determine the sign of the result. (inst extrs x 0 1 sign :=) (inst sub zero-tn x x) (inst extrs y 0 1 tmp :=) (inst sub zero-tn y y) (inst xor sign tmp sign) ;; Make sure X is less then Y. (inst comclr x y tmp :<<) (inst xor x y tmp) (inst xor x tmp x) (inst xor y tmp y) Blow out of here if the result is zero . (inst comb := x zero-tn done) (inst li 0 res) LOOP (inst extru x 31 1 zero-tn :ev) (inst add y res res) (inst extru x 30 1 zero-tn :ev) (inst sh1add y res res) (inst extru x 29 1 zero-tn :ev) (inst sh2add y res res) (inst extru x 28 1 zero-tn :ev) (inst sh3add y res res) (inst srl x 4 x) (inst comb :<> x zero-tn loop) (inst sll y 4 y) DONE (inst xor res sign res) (inst add res sign res)) (define-assembly-routine (truncate) ((:arg dividend signed-reg nl0-offset) (:arg divisor signed-reg nl1-offset) (:res quo signed-reg nl2-offset) (:res rem signed-reg nl3-offset)) ;; Move abs(divident) into quo. (inst move dividend quo :>=) (inst sub zero-tn quo quo) Do one divive - step with -divisor to prime V ( use rem as a temp ) (inst sub zero-tn divisor rem) (inst ds zero-tn rem zero-tn) Shift the divident / quotient one bit , setting the carry flag . (inst add quo quo quo) The first real divive - step . (inst ds zero-tn divisor rem) (inst addc quo quo quo) And 31 more of them . (dotimes (i 31) (inst ds rem divisor rem) (inst addc quo quo quo)) ;; If the remainder is negative, we need to add the absolute value of the ;; divisor. (inst comb :>= rem zero-tn remainder-positive) (inst comclr divisor zero-tn zero-tn :<) (inst add rem divisor rem :tr) (inst sub rem divisor rem) REMAINDER-POSITIVE ;; Now we have to fix the signs of quo and rem. (inst xor divisor dividend zero-tn :>=) (inst sub zero-tn quo quo) (inst move dividend zero-tn :>=) (inst sub zero-tn rem rem)) Generic arithmetic . (define-assembly-routine (generic-+ (:cost 10) (:return-style :full-call) (:translate +) (:policy :safe) (:save-p t)) ((:arg x (descriptor-reg any-reg) a0-offset) (:arg y (descriptor-reg any-reg) a1-offset) (:res res (descriptor-reg any-reg) a0-offset) (:temp temp non-descriptor-reg nl0-offset) (:temp temp1 non-descriptor-reg nl1-offset) (:temp temp2 non-descriptor-reg nl2-offset) (:temp lra descriptor-reg lra-offset) (:temp lip interior-reg lip-offset) (:temp nargs any-reg nargs-offset) (:temp ocfp any-reg ocfp-offset)) If either arg is not fixnum , use two - arg-+ to summarize (inst or x y temp) (inst extru temp 31 3 zero-tn :=) (inst b DO-STATIC-FUN :nullify t) ;; check for overflow (inst add x y temp) (inst xor temp x temp1) (inst xor temp y temp2) (inst and temp1 temp2 temp1) (inst bc :< nil temp1 zero-tn DO-OVERFLOW) (inst move temp res) (lisp-return lra :offset 1) DO-OVERFLOW ;; We did overflow, so do the bignum version (inst sra x n-fixnum-tag-bits temp1) (inst sra y n-fixnum-tag-bits temp2) (inst add temp1 temp2 temp) (with-fixed-allocation (res nil temp2 bignum-widetag (1+ bignum-digits-offset) nil) (storew temp res bignum-digits-offset other-pointer-lowtag)) (lisp-return lra :offset 1) DO-STATIC-FUN (inst ldw (static-fun-offset 'two-arg-+) null-tn lip) (inst li (fixnumize 2) nargs) (move cfp-tn ocfp) (inst bv lip) (move csp-tn cfp-tn t)) (define-assembly-routine (generic-- (:cost 10) (:return-style :full-call) (:translate -) (:policy :safe) (:save-p t)) ((:arg x (descriptor-reg any-reg) a0-offset) (:arg y (descriptor-reg any-reg) a1-offset) (:res res (descriptor-reg any-reg) a0-offset) (:temp temp non-descriptor-reg nl0-offset) (:temp temp1 non-descriptor-reg nl1-offset) (:temp temp2 non-descriptor-reg nl2-offset) (:temp lra descriptor-reg lra-offset) (:temp lip interior-reg lip-offset) (:temp nargs any-reg nargs-offset) (:temp ocfp any-reg ocfp-offset)) If either arg is not fixnum , use two - arg-+ to summarize (inst or x y temp) (inst extru temp 31 3 zero-tn :=) (inst b DO-STATIC-FUN :nullify t) (inst sub x y temp) ;; check for overflow (inst xor x y temp1) (inst xor x temp temp2) (inst and temp2 temp1 temp1) (inst bc :< nil temp1 zero-tn DO-OVERFLOW) (inst move temp res) (lisp-return lra :offset 1) DO-OVERFLOW ;; We did overflow, so do the bignum version (inst sra x n-fixnum-tag-bits temp1) (inst sra y n-fixnum-tag-bits temp2) (inst sub temp1 temp2 temp) (with-fixed-allocation (res nil temp2 bignum-widetag (1+ bignum-digits-offset) nil) (storew temp res bignum-digits-offset other-pointer-lowtag)) (lisp-return lra :offset 1) DO-STATIC-FUN (inst ldw (static-fun-offset 'two-arg--) null-tn lip) (inst li (fixnumize 2) nargs) (move cfp-tn ocfp) (inst bv lip) (move csp-tn cfp-tn t)) Comparison routines . (macrolet ((define-cond-assem-rtn (name translate static-fn cond) `(define-assembly-routine (,name (:cost 10) (:return-style :full-call) (:policy :safe) (:translate ,translate) (:save-p t)) ((:arg x (descriptor-reg any-reg) a0-offset) (:arg y (descriptor-reg any-reg) a1-offset) (:res res descriptor-reg a0-offset) (:temp lip interior-reg lip-offset) (:temp lra descriptor-reg lra-offset) (:temp nargs any-reg nargs-offset) (:temp ocfp any-reg ocfp-offset)) (inst extru x 31 2 zero-tn :=) (inst b do-static-fn :nullify t) (inst extru y 31 2 zero-tn :=) (inst b do-static-fn :nullify t) (inst comclr x y zero-tn ,cond) (inst move null-tn res :tr) (load-symbol res t) (lisp-return lra :offset 1) DO-STATIC-FN (inst ldw (static-fun-offset ',static-fn) null-tn lip) (inst li (fixnumize 2) nargs) (inst move cfp-tn ocfp) (inst bv lip) (inst move csp-tn cfp-tn)))) (define-cond-assem-rtn generic-< < two-arg-< :<) (define-cond-assem-rtn generic-> > two-arg-> :>)) (define-assembly-routine (generic-eql (:cost 10) (:return-style :full-call) (:policy :safe) (:translate eql) (:save-p t)) ((:arg x (descriptor-reg any-reg) a0-offset) (:arg y (descriptor-reg any-reg) a1-offset) (:res res descriptor-reg a0-offset) (:temp lip interior-reg lip-offset) (:temp lra descriptor-reg lra-offset) (:temp nargs any-reg nargs-offset) (:temp ocfp any-reg ocfp-offset)) (inst comb := x y return-t :nullify t) (inst extru x 31 2 zero-tn :<>) (inst b return-nil :nullify t) (inst extru y 31 2 zero-tn :=) (inst b do-static-fn :nullify t) RETURN-NIL (inst move null-tn res) (lisp-return lra :offset 1) DO-STATIC-FN (inst ldw (static-fun-offset 'eql) null-tn lip) (inst li (fixnumize 2) nargs) (inst move cfp-tn ocfp) (inst bv lip) (inst move csp-tn cfp-tn) RETURN-T (load-symbol res t)) (define-assembly-routine (generic-= (:cost 10) (:return-style :full-call) (:policy :safe) (:translate =) (:save-p t)) ((:arg x (descriptor-reg any-reg) a0-offset) (:arg y (descriptor-reg any-reg) a1-offset) (:res res descriptor-reg a0-offset) (:temp lip interior-reg lip-offset) (:temp lra descriptor-reg lra-offset) (:temp nargs any-reg nargs-offset) (:temp ocfp any-reg ocfp-offset)) (inst comb := x y return-t :nullify t) (inst extru x 31 2 zero-tn :=) (inst b do-static-fn :nullify t) (inst extru y 31 2 zero-tn :=) (inst b do-static-fn :nullify t) (inst move null-tn res) (lisp-return lra :offset 1) DO-STATIC-FN (inst ldw (static-fun-offset 'two-arg-=) null-tn lip) (inst li (fixnumize 2) nargs) (inst move cfp-tn ocfp) (inst bv lip) (inst move csp-tn cfp-tn) RETURN-T (load-symbol res t))
null
https://raw.githubusercontent.com/antifuchs/sbcl/789bf105edca031aff991ad16a5fd207812336a0/src/assembly/hppa/arith.lisp
lisp
?? FIXME: Where are generic-* and generic-/? Determine the sign of the result. Make sure X is less then Y. Move abs(divident) into quo. If the remainder is negative, we need to add the absolute value of the divisor. Now we have to fix the signs of quo and rem. check for overflow We did overflow, so do the bignum version check for overflow We did overflow, so do the bignum version
(in-package "SB!VM") Multiplication and Division helping routines . #+sb-assembling (define-assembly-routine multiply ((:arg x (signed-reg) nl0-offset) (:arg y (signed-reg) nl1-offset) (:res res (signed-reg) nl2-offset) (:temp tmp (unsigned-reg) nl3-offset) (:temp sign (unsigned-reg) nl4-offset)) (inst extrs x 0 1 sign :=) (inst sub zero-tn x x) (inst extrs y 0 1 tmp :=) (inst sub zero-tn y y) (inst xor sign tmp sign) (inst comclr x y tmp :<<) (inst xor x y tmp) (inst xor x tmp x) (inst xor y tmp y) Blow out of here if the result is zero . (inst comb := x zero-tn done) (inst li 0 res) LOOP (inst extru x 31 1 zero-tn :ev) (inst add y res res) (inst extru x 30 1 zero-tn :ev) (inst sh1add y res res) (inst extru x 29 1 zero-tn :ev) (inst sh2add y res res) (inst extru x 28 1 zero-tn :ev) (inst sh3add y res res) (inst srl x 4 x) (inst comb :<> x zero-tn loop) (inst sll y 4 y) DONE (inst xor res sign res) (inst add res sign res)) (define-assembly-routine (truncate) ((:arg dividend signed-reg nl0-offset) (:arg divisor signed-reg nl1-offset) (:res quo signed-reg nl2-offset) (:res rem signed-reg nl3-offset)) (inst move dividend quo :>=) (inst sub zero-tn quo quo) Do one divive - step with -divisor to prime V ( use rem as a temp ) (inst sub zero-tn divisor rem) (inst ds zero-tn rem zero-tn) Shift the divident / quotient one bit , setting the carry flag . (inst add quo quo quo) The first real divive - step . (inst ds zero-tn divisor rem) (inst addc quo quo quo) And 31 more of them . (dotimes (i 31) (inst ds rem divisor rem) (inst addc quo quo quo)) (inst comb :>= rem zero-tn remainder-positive) (inst comclr divisor zero-tn zero-tn :<) (inst add rem divisor rem :tr) (inst sub rem divisor rem) REMAINDER-POSITIVE (inst xor divisor dividend zero-tn :>=) (inst sub zero-tn quo quo) (inst move dividend zero-tn :>=) (inst sub zero-tn rem rem)) Generic arithmetic . (define-assembly-routine (generic-+ (:cost 10) (:return-style :full-call) (:translate +) (:policy :safe) (:save-p t)) ((:arg x (descriptor-reg any-reg) a0-offset) (:arg y (descriptor-reg any-reg) a1-offset) (:res res (descriptor-reg any-reg) a0-offset) (:temp temp non-descriptor-reg nl0-offset) (:temp temp1 non-descriptor-reg nl1-offset) (:temp temp2 non-descriptor-reg nl2-offset) (:temp lra descriptor-reg lra-offset) (:temp lip interior-reg lip-offset) (:temp nargs any-reg nargs-offset) (:temp ocfp any-reg ocfp-offset)) If either arg is not fixnum , use two - arg-+ to summarize (inst or x y temp) (inst extru temp 31 3 zero-tn :=) (inst b DO-STATIC-FUN :nullify t) (inst add x y temp) (inst xor temp x temp1) (inst xor temp y temp2) (inst and temp1 temp2 temp1) (inst bc :< nil temp1 zero-tn DO-OVERFLOW) (inst move temp res) (lisp-return lra :offset 1) DO-OVERFLOW (inst sra x n-fixnum-tag-bits temp1) (inst sra y n-fixnum-tag-bits temp2) (inst add temp1 temp2 temp) (with-fixed-allocation (res nil temp2 bignum-widetag (1+ bignum-digits-offset) nil) (storew temp res bignum-digits-offset other-pointer-lowtag)) (lisp-return lra :offset 1) DO-STATIC-FUN (inst ldw (static-fun-offset 'two-arg-+) null-tn lip) (inst li (fixnumize 2) nargs) (move cfp-tn ocfp) (inst bv lip) (move csp-tn cfp-tn t)) (define-assembly-routine (generic-- (:cost 10) (:return-style :full-call) (:translate -) (:policy :safe) (:save-p t)) ((:arg x (descriptor-reg any-reg) a0-offset) (:arg y (descriptor-reg any-reg) a1-offset) (:res res (descriptor-reg any-reg) a0-offset) (:temp temp non-descriptor-reg nl0-offset) (:temp temp1 non-descriptor-reg nl1-offset) (:temp temp2 non-descriptor-reg nl2-offset) (:temp lra descriptor-reg lra-offset) (:temp lip interior-reg lip-offset) (:temp nargs any-reg nargs-offset) (:temp ocfp any-reg ocfp-offset)) If either arg is not fixnum , use two - arg-+ to summarize (inst or x y temp) (inst extru temp 31 3 zero-tn :=) (inst b DO-STATIC-FUN :nullify t) (inst sub x y temp) (inst xor x y temp1) (inst xor x temp temp2) (inst and temp2 temp1 temp1) (inst bc :< nil temp1 zero-tn DO-OVERFLOW) (inst move temp res) (lisp-return lra :offset 1) DO-OVERFLOW (inst sra x n-fixnum-tag-bits temp1) (inst sra y n-fixnum-tag-bits temp2) (inst sub temp1 temp2 temp) (with-fixed-allocation (res nil temp2 bignum-widetag (1+ bignum-digits-offset) nil) (storew temp res bignum-digits-offset other-pointer-lowtag)) (lisp-return lra :offset 1) DO-STATIC-FUN (inst ldw (static-fun-offset 'two-arg--) null-tn lip) (inst li (fixnumize 2) nargs) (move cfp-tn ocfp) (inst bv lip) (move csp-tn cfp-tn t)) Comparison routines . (macrolet ((define-cond-assem-rtn (name translate static-fn cond) `(define-assembly-routine (,name (:cost 10) (:return-style :full-call) (:policy :safe) (:translate ,translate) (:save-p t)) ((:arg x (descriptor-reg any-reg) a0-offset) (:arg y (descriptor-reg any-reg) a1-offset) (:res res descriptor-reg a0-offset) (:temp lip interior-reg lip-offset) (:temp lra descriptor-reg lra-offset) (:temp nargs any-reg nargs-offset) (:temp ocfp any-reg ocfp-offset)) (inst extru x 31 2 zero-tn :=) (inst b do-static-fn :nullify t) (inst extru y 31 2 zero-tn :=) (inst b do-static-fn :nullify t) (inst comclr x y zero-tn ,cond) (inst move null-tn res :tr) (load-symbol res t) (lisp-return lra :offset 1) DO-STATIC-FN (inst ldw (static-fun-offset ',static-fn) null-tn lip) (inst li (fixnumize 2) nargs) (inst move cfp-tn ocfp) (inst bv lip) (inst move csp-tn cfp-tn)))) (define-cond-assem-rtn generic-< < two-arg-< :<) (define-cond-assem-rtn generic-> > two-arg-> :>)) (define-assembly-routine (generic-eql (:cost 10) (:return-style :full-call) (:policy :safe) (:translate eql) (:save-p t)) ((:arg x (descriptor-reg any-reg) a0-offset) (:arg y (descriptor-reg any-reg) a1-offset) (:res res descriptor-reg a0-offset) (:temp lip interior-reg lip-offset) (:temp lra descriptor-reg lra-offset) (:temp nargs any-reg nargs-offset) (:temp ocfp any-reg ocfp-offset)) (inst comb := x y return-t :nullify t) (inst extru x 31 2 zero-tn :<>) (inst b return-nil :nullify t) (inst extru y 31 2 zero-tn :=) (inst b do-static-fn :nullify t) RETURN-NIL (inst move null-tn res) (lisp-return lra :offset 1) DO-STATIC-FN (inst ldw (static-fun-offset 'eql) null-tn lip) (inst li (fixnumize 2) nargs) (inst move cfp-tn ocfp) (inst bv lip) (inst move csp-tn cfp-tn) RETURN-T (load-symbol res t)) (define-assembly-routine (generic-= (:cost 10) (:return-style :full-call) (:policy :safe) (:translate =) (:save-p t)) ((:arg x (descriptor-reg any-reg) a0-offset) (:arg y (descriptor-reg any-reg) a1-offset) (:res res descriptor-reg a0-offset) (:temp lip interior-reg lip-offset) (:temp lra descriptor-reg lra-offset) (:temp nargs any-reg nargs-offset) (:temp ocfp any-reg ocfp-offset)) (inst comb := x y return-t :nullify t) (inst extru x 31 2 zero-tn :=) (inst b do-static-fn :nullify t) (inst extru y 31 2 zero-tn :=) (inst b do-static-fn :nullify t) (inst move null-tn res) (lisp-return lra :offset 1) DO-STATIC-FN (inst ldw (static-fun-offset 'two-arg-=) null-tn lip) (inst li (fixnumize 2) nargs) (inst move cfp-tn ocfp) (inst bv lip) (inst move csp-tn cfp-tn) RETURN-T (load-symbol res t))
d6dc8c2b850bf97f2da52e11925c039c761eb04dda46ae4e3e4223c2e5881f6e
uncomplicate/deep-diamond
factory.clj
Copyright ( c ) . All rights reserved . ;; The use and distribution terms for this software are covered by the ;; Eclipse Public License 1.0 (-1.0.php) or later ;; which can be found in the file LICENSE at the root of this distribution. ;; By using this software in any fashion, you are agreeing to be bound by ;; the terms of this license. ;; You must not remove this notice, or any other, from this software. (ns uncomplicate.diamond.internal.cudnn.factory (:require [clojure.java.io :as io] [uncomplicate.commons [core :refer [Releaseable release let-release with-release view]] [utils :refer [dragan-says-ex]]] [uncomplicate.fluokitten.core :refer [op]] [uncomplicate.clojurecuda [core :refer :all] [toolbox :refer [read-int]]] [uncomplicate.neanderthal [cuda :refer [cuda-float cuda-double cuda-long cuda-int cuda-byte]] [block :refer [buffer offset]]] [uncomplicate.neanderthal.internal.api :refer :all :exclude [device]] [uncomplicate.diamond.tensor :refer [shape data-type layout output]] [uncomplicate.diamond.internal [protocols :refer [TensorFactory DiamondFactoryProvider NeanderthalFactoryProvider CostFactory DnnFactory RnnFactory]] [utils :refer [check-contiguous]] [cost :refer [quadratic-cost! mean-absolute-cost! crossentropy-cost!]]] [uncomplicate.diamond.internal.dnnl.factory :refer [dnnl-factory]] [uncomplicate.diamond.internal.neanderthal.directed :refer [neanderthal-fc-blueprint]] [uncomplicate.diamond.internal.cudnn [protocols :refer [HandleProvider desc]] [core :refer [cudnn-handle get-cudnn-stream ndims dims strides transform-tensor set-tensor scale-tensor add-tensor]] [tensor :refer [cudnn-tensor cudnn-transformer cudnn-batcher cudnn-shuffler cudnn-tensor-desc]] [directed :refer [cudnn-activ-blueprint cudnn-universal-cost cudnn-custom-cost cudnn-pooling-blueprint cudnn-convolution-layer-blueprint cudnn-gaussian-dropout-blueprint cudnn-batch-norm-layer-blueprint cudnn-branch-blueprint cudnn-concat-blueprint cudnn-sum-blueprint cudnn-split-blueprint]] [rnn :refer [cudnn-rnn-op-blueprint cudnn-rnn-blueprint cudnn-abbreviate-blueprint]]]) (:import jcuda.jcudnn.JCudnn)) (def ^{:private true :const true} INEFFICIENT_OPERATION_MSG "This operation would be inefficient because it does not use cuDNN capabilities. Please use dedicated tensor operations.") (def ^{:private true :const true} UNSUPPORTED_DATA_TYPE "The requested data type is not supported on the CUDA platform. Please contribute towards making it possible, or use on of the supported types.") (defn ^:private tensor-1d-equals [modl hstream x y] (with-release [equals-kernel (function modl "tensor_1d_equals") eq-flag-buf (mem-alloc Integer/BYTES)] (let [n (first (dims x))] (memset! eq-flag-buf 0) (launch! equals-kernel (grid-1d n) hstream (parameters (int n) (buffer x) (int (offset x)) (int (first (strides x))) (buffer y) (int (offset y)) (int (first (strides y))) eq-flag-buf)) (= 0 (read-int hstream eq-flag-buf))))) (defn ^:private tensor-2d-equals [modl hstream x y] (with-release [equals-kernel (function modl "tensor_2d_equals") eq-flag-buf (mem-alloc Integer/BYTES)] (let [[n c] (dims x) [nx cx] (strides x) [ny cy] (strides y)] (memset! eq-flag-buf 0) (launch! equals-kernel (grid-2d n c) hstream (parameters (int n) (int c) (buffer x) (int (offset x)) (int nx) (int cx) (buffer y) (int (offset y)) (int ny) (int cy) eq-flag-buf)) (= 0 (read-int hstream eq-flag-buf))))) (defn ^:private tensor-3d-equals [modl hstream x y] (with-release [equals-kernel (function modl "tensor_3d_equals") eq-flag-buf (mem-alloc Integer/BYTES)] (let [[n c h] (dims x) [nx cx hx] (strides x) [ny cy hy] (strides y)] (memset! eq-flag-buf 0) (launch! equals-kernel (grid-2d n c h) hstream (parameters (int n) (int c) (int h) (buffer x) (int (offset x)) (int nx) (int cx) (int hx) (buffer y) (int (offset y)) (int ny) (int cy) (int hy) eq-flag-buf)) (= 0 (read-int hstream eq-flag-buf))))) (defn ^:private tensor-4d-equals [modl hstream x y] (with-release [equals-kernel (function modl "tensor_4d_equals") eq-flag-buf (mem-alloc Integer/BYTES)] (let [[n c h w] (dims x) [nx cx hx wx] (strides x) [ny cy hy wy] (strides y)] (memset! eq-flag-buf 0) (launch! equals-kernel (grid-3d n c h) hstream (parameters (int n) (int c) (int h) (int w) (buffer x) (int (offset x)) (int nx) (int cx) (int hx) (int wx) (buffer y) (int (offset y)) (int ny) (int cy) (int hy) (int wy) eq-flag-buf)) (= 0 (read-int hstream eq-flag-buf))))) (defn ^:private tensor-5d-equals [modl hstream x y] (with-release [equals-kernel (function modl "tensor_5d_equals") eq-flag-buf (mem-alloc Integer/BYTES)] (let [[n c d h w] (dims x) [nx cx dx hx wx] (strides x) [ny cy dy hy wy] (strides y)] (memset! eq-flag-buf 0) (launch! equals-kernel (grid-3d n c h) hstream (parameters (int n) (int c) (int d) (int h) (int w) (buffer x) (int (offset x)) (int nx) (int cx) (int dx) (int hx) (int wx) (buffer y) (int (offset y)) (int ny) (int cy) (int dy) (int hy) (int wy) eq-flag-buf)) (= 0 (read-int hstream eq-flag-buf))))) (defn ^:private tensor-equals [modl hstream x y] (let [cnt (int (apply * (dims x)))] (if (< 0 cnt) (case (ndims x) 1 (tensor-1d-equals modl hstream x y) 2 (tensor-2d-equals modl hstream x y) 3 (tensor-3d-equals modl hstream x y) 4 (tensor-4d-equals modl hstream x y) 5 (tensor-5d-equals modl hstream x y) (dragan-says-ex "Equals is supported only up to 5 dimensions." {:shape (dims x)})) (= 0 (int (apply * (dims y))))))) (defn tensor-method ([method x] (let [vx (view-vctr x)] (check-contiguous x) (method (engine vx) vx))) ([method x y] (let [vx (view-vctr x)] (check-contiguous x y) (method (engine vx) vx (view-vctr y)))) ([method x y z] (let [vx (view-vctr x)] (check-contiguous x y z) (method (engine vx) vx (view-vctr y) (view-vctr z))))) (defn tensor-math ([method a y] (let [va (view-vctr a)] (check-contiguous a y) (method (engine va) va (view-vctr y)) y)) ([method a b y] (let [va (view-vctr a)] (check-contiguous a b y) (method (engine va) va (view-vctr b) (view-vctr y)) y))) (deftype TensorEngine [cudnn-hdl modl hstream cast ^long byte-cnt] BlockEngine (equals-block [_ x y] (tensor-equals modl hstream x y)) Blas (copy [_ x y] (transform-tensor cudnn-hdl (cast 1.0) x (buffer x) (* (offset y) byte-cnt) (cast 0.0) y (buffer y) (* (offset y) byte-cnt)) y) (axpy [_ alpha x y] (add-tensor cudnn-hdl (cast alpha) x (buffer x) (* (offset y) byte-cnt) (cast 1.0) y (buffer y) (* (offset y) byte-cnt)) y) (swap [_ x y] (tensor-method swap x y) x) (asum [_ x] (tensor-method asum x)) (nrm1 [_ x] (tensor-method nrm1 x)) (nrm2 [_ x] (tensor-method nrm2 x)) (nrmi [this x] (tensor-method nrmi x)) (scal [_ alpha x] (if (= 0 (offset x)) (scale-tensor cudnn-hdl (cast alpha) x (buffer x)) (scale-tensor cudnn-hdl (cast alpha) x (buffer x) (* (offset x) byte-cnt))) x) BlasPlus (amax [_ x] (tensor-method amax x)) (sum [_ x] (tensor-method sum x)) (set-all [_ value x] (if (= 0 (offset x)) (set-tensor cudnn-hdl x (buffer x) (cast value)) (set-tensor cudnn-hdl x (buffer x) (* (offset x) byte-cnt) (cast value))) x) (axpby [_ alpha x beta y] (add-tensor cudnn-hdl (cast alpha) x (buffer x) (* (offset y) byte-cnt) (cast beta) y (buffer y) (* (offset y) byte-cnt)) y) VectorMath (sqr [_ a y] (tensor-math sqr a y)) (mul [_ a b y] (tensor-math mul a b y)) (div [_ a b y] (tensor-math div a b y)) (inv [_ a y] (tensor-math inv a y)) (abs [_ a y] (tensor-math abs a y)) (linear-frac [_ a b scalea shifta scaleb shiftb y] (let [va (view-vctr a)] (linear-frac (engine va) va (view-vctr b) scalea shifta scaleb shiftb (view-vctr y)) y)) (fmod [_ a b y] (tensor-math fmod a b y) a) (frem [_ a b y] (tensor-math frem a b y)) (sqrt [_ a y] (tensor-math sqrt a y)) (inv-sqrt [_ a y] (tensor-math inv-sqrt a y)) (cbrt [_ a y] (tensor-math cbrt a y)) (inv-cbrt [_ a y] (tensor-math inv-cbrt a y)) (pow2o3 [_ a y] (tensor-math pow2o3 a y)) (pow3o2 [_ a y] (tensor-math pow3o2 a y)) (pow [_ a b y] (tensor-math pow a b y)) (powx [_ a b y] (powx (engine (view-vctr a)) (view-vctr a) b (view-vctr y)) y) (hypot [_ a b y] (tensor-math hypot a b y)) (exp [_ a y] (tensor-math exp a y)) (expm1 [_ a y] (tensor-math expm1 a y)) (log [_ a y] (tensor-math log a y)) (log10 [_ a y] (tensor-math log10 a y)) (sin [_ a y] (tensor-math sin a y)) (cos [_ a y] (tensor-math cos a y)) (tan [_ a y] (tensor-math tan a y)) (sincos [_ a y z] (tensor-math sincos a y z)) (asin [_ a y] (tensor-math asin a y)) (acos [_ a y] (tensor-math acos a y)) (atan [_ a y] (tensor-math atan a y)) (atan2 [_ a b y] (tensor-math atan a b y)) (sinh [_ a y] (tensor-math sinh a y)) (cosh [_ a y] (tensor-math cosh a y)) (tanh [_ a y] (tensor-math tanh a y)) (asinh [_ a y] (tensor-math asinh a y)) (acosh [_ a y] (tensor-math acosh a y)) (atanh [_ a y] (tensor-math atanh a y)) (erf [_ a y] (tensor-math erf a y)) (erfc [_ a y] (tensor-math erfc a y)) (erf-inv [_ a y] (tensor-math erf-inv a y)) (erfc-inv [_ a y] (tensor-math erfc-inv a y)) (cdf-norm [_ a y] (tensor-math cdf-norm a y)) (cdf-norm-inv [_ a y] (tensor-math cdf-norm-inv a y)) (gamma [_ a y] (tensor-math gamma a y)) (lgamma [_ a y] (tensor-math lgamma a y)) (expint1 [_ a y] (tensor-math expint1 a y)) (floor [_ a y] (tensor-math floor a y)) (fceil [_ a y] (tensor-math fceil a y)) (trunc [_ a y] (tensor-math trunc a y)) (round [_ a y] (tensor-math round a y)) (modf [_ a y z] (tensor-math modf a y z)) (frac [_ a y] (tensor-math frac a y)) (fmin [_ a b y] (tensor-math fmin a y)) (fmax [_ a b y] (tensor-math fmax a y)) (copy-sign [_ a b y] (tensor-math copy-sign a b y)) (sigmoid [this a y] (dragan-says-ex INEFFICIENT_OPERATION_MSG)) (ramp [this a y] (dragan-says-ex INEFFICIENT_OPERATION_MSG)) (relu [this alpha a y] (dragan-says-ex INEFFICIENT_OPERATION_MSG)) (elu [this alpha a y] (dragan-says-ex INEFFICIENT_OPERATION_MSG)) RandomNumberGenerator (rand-uniform [_ rng-stream lower upper x] (rand-uniform (engine (view-vctr x)) rng-stream lower upper (view-vctr x)) x) (rand-normal [_ rng-stream mu sigma x] (rand-normal (engine (view-vctr x)) rng-stream mu sigma (view-vctr x)) x)) (deftype CUDnnFactory [ctx hstream cudnn-hdl master native-diamond-fact neand-facts tensor-engines] Releaseable (release [_] (in-context ctx (doseq [neand-fact (vals neand-facts)] (release neand-fact)) (doseq [eng (vals tensor-engines)] (release eng)) (release cudnn-hdl)) (when master (when-not (= default-stream hstream) (release hstream)) (release ctx)) true) DiamondFactoryProvider (diamond-factory [this] this) (native-diamond-factory [_] native-diamond-fact) FlowProvider (flow [_] hstream) HandleProvider (handle [_] cudnn-hdl) NeanderthalFactoryProvider (neanderthal-factory [_ dtype] (or (get neand-facts dtype) (dragan-says-ex UNSUPPORTED_DATA_TYPE {:data-type dtype}))) TensorFactory (create-tensor-desc [this shape dtype format] (cudnn-tensor-desc shape dtype format)) (create-tensor-desc [this tz-desc] (cudnn-tensor-desc (shape tz-desc) (data-type tz-desc) (layout tz-desc))) (create-tensor [this tensor-desc init] (let-release [res (cudnn-tensor this tensor-desc)] (when init (set-all (engine res) 0 res)) res)) (create-tensor [this tensor-desc batch-index init] (let-release [res (cudnn-tensor this tensor-desc batch-index)] (when init (set-all (engine res) 0 res)) res)) (create-transformer [_ in-tz out-tz] (cudnn-transformer cudnn-hdl (view in-tz) (view out-tz))) (create-shuffler [_ src-tz dst-tz] (cudnn-shuffler cudnn-hdl (view src-tz) (view dst-tz))) (create-batcher [_ src-tz dst-tz mb-size] (cudnn-batcher cudnn-hdl (view src-tz) (view dst-tz) mb-size)) (tensor-engine [this dtype] (or (get tensor-engines dtype) (dragan-says-ex UNSUPPORTED_DATA_TYPE {:data-type dtype}))) DnnFactory (activ-blueprint [this src-desc activ coef _] (cudnn-activ-blueprint this src-desc activ coef)) (inner-product-blueprint [this src-desc dst-desc weights-type] (dragan-says-ex "cuDNN engine does not implement the inner product blueprint.")) (fc-blueprint [this src-desc dst-desc activ alpha beta weights-type] (neanderthal-fc-blueprint this src-desc dst-desc activ alpha beta weights-type)) (convolution-blueprint [this src-desc weights-desc dst-desc activ strides padding dilation alpha _] (cudnn-convolution-layer-blueprint this src-desc weights-desc dst-desc activ strides padding dilation alpha)) (pooling-blueprint [this src-desc dst-desc algo strides kernel padding] (cudnn-pooling-blueprint this src-desc dst-desc algo strides kernel padding)) (gaussian-dropout-blueprint [this src-desc sd] (cudnn-gaussian-dropout-blueprint this src-desc sd)) (batch-norm-blueprint [this src-desc activ alpha beta] (cudnn-batch-norm-layer-blueprint this src-desc activ alpha beta)) (concat-blueprint [this src-descs conc-dim dst-type] (cudnn-concat-blueprint this src-descs conc-dim dst-type)) (branch-blueprint [this src-desc branch-dim dst-descs] (cudnn-branch-blueprint this src-desc branch-dim dst-descs)) (split-blueprint [this src-desc n] (cudnn-split-blueprint this src-desc n)) (sum-blueprint [this src-descs] (cudnn-sum-blueprint this src-descs)) (create-workspace [_ byte-size] (in-context ctx (mem-alloc (max 1 (long byte-size))))) RnnFactory (rnn-op-blueprint [this src-desc dst-desc weights-type activ dir lrs src-iter? dst-iter?] (cudnn-rnn-op-blueprint this cudnn-hdl src-desc dst-desc weights-type activ dir lrs src-iter? dst-iter?)) (rnn-blueprint [fact src-desc dst-desc lrs activ _ _ weights-type src-iter? dst-iter?] (cudnn-rnn-blueprint fact cudnn-hdl src-desc dst-desc lrs activ weights-type src-iter? dst-iter?)) (abbreviate-blueprint [fact src-desc dst-type] (cudnn-abbreviate-blueprint fact src-desc dst-type)) CostFactory (quadratic-cost [_ prev-layer train-tz] (cudnn-universal-cost prev-layer train-tz quadratic-cost!)) (mean-absolute-cost [_ prev-layer train-tz] (cudnn-universal-cost prev-layer train-tz mean-absolute-cost!)) (crossentropy-cost [_ prev-layer train-tz] (cudnn-custom-cost prev-layer train-tz (partial crossentropy-cost! ((dims (output prev-layer)) 0))))) (JCudnn/setExceptionsEnabled false) (defn ^:private create-module [src dtype] (with-release [prog (compile! (program src) [(str "-DTYPE=" dtype) "-default-device"])] (module prog))) (let [src (slurp (io/resource "uncomplicate/diamond/internal/cuda/blas-plus.cu"))] (defn ^:private create-cudnn-factory [ctx hstream cudnn-hdl master] (let-release [float-modl (create-module src "float") double-modl (create-module src "double") long-modl (create-module src "long") int-modl (create-module src "int") byte-modl (create-module src "char") native-diamond-fact (dnnl-factory) float-fact (cuda-float ctx hstream) double-fact (cuda-double ctx hstream) long-fact (cuda-long ctx hstream) int-fact (cuda-int ctx hstream) byte-fact (cuda-byte ctx hstream) float-engine (->TensorEngine cudnn-hdl float-modl hstream float Float/BYTES) double-engine (->TensorEngine cudnn-hdl double-modl hstream double Double/BYTES) long-engine (->TensorEngine cudnn-hdl long-modl hstream long Long/BYTES) int-engine (->TensorEngine cudnn-hdl int-modl hstream int Integer/BYTES) byte-engine (->TensorEngine cudnn-hdl byte-modl hstream byte Byte/BYTES)] (->CUDnnFactory ctx hstream cudnn-hdl master native-diamond-fact {:float float-fact :double double-fact :long long-fact :int int-fact :byte byte-fact :uint8 byte-fact} {:float float-engine :double double-engine :int int-engine :long long-engine :byte byte-engine :uint8 byte-engine})))) (defn cudnn-factory ([ctx hstream] (in-context ctx (let-release [cudnn-hdl (cudnn-handle hstream) hstream (get-cudnn-stream cudnn-hdl)] (create-cudnn-factory ctx hstream cudnn-hdl false)))) ([] (init) (let-release [ctx (context (device))] (in-context ctx (let-release [hstream (stream) cudnn-hdl (cudnn-handle hstream)] (create-cudnn-factory ctx hstream cudnn-hdl true))))))
null
https://raw.githubusercontent.com/uncomplicate/deep-diamond/d5283602905552e3ba832245219b8b712bfba0d9/src/clojure/uncomplicate/diamond/internal/cudnn/factory.clj
clojure
The use and distribution terms for this software are covered by the Eclipse Public License 1.0 (-1.0.php) or later which can be found in the file LICENSE at the root of this distribution. By using this software in any fashion, you are agreeing to be bound by the terms of this license. You must not remove this notice, or any other, from this software.
Copyright ( c ) . All rights reserved . (ns uncomplicate.diamond.internal.cudnn.factory (:require [clojure.java.io :as io] [uncomplicate.commons [core :refer [Releaseable release let-release with-release view]] [utils :refer [dragan-says-ex]]] [uncomplicate.fluokitten.core :refer [op]] [uncomplicate.clojurecuda [core :refer :all] [toolbox :refer [read-int]]] [uncomplicate.neanderthal [cuda :refer [cuda-float cuda-double cuda-long cuda-int cuda-byte]] [block :refer [buffer offset]]] [uncomplicate.neanderthal.internal.api :refer :all :exclude [device]] [uncomplicate.diamond.tensor :refer [shape data-type layout output]] [uncomplicate.diamond.internal [protocols :refer [TensorFactory DiamondFactoryProvider NeanderthalFactoryProvider CostFactory DnnFactory RnnFactory]] [utils :refer [check-contiguous]] [cost :refer [quadratic-cost! mean-absolute-cost! crossentropy-cost!]]] [uncomplicate.diamond.internal.dnnl.factory :refer [dnnl-factory]] [uncomplicate.diamond.internal.neanderthal.directed :refer [neanderthal-fc-blueprint]] [uncomplicate.diamond.internal.cudnn [protocols :refer [HandleProvider desc]] [core :refer [cudnn-handle get-cudnn-stream ndims dims strides transform-tensor set-tensor scale-tensor add-tensor]] [tensor :refer [cudnn-tensor cudnn-transformer cudnn-batcher cudnn-shuffler cudnn-tensor-desc]] [directed :refer [cudnn-activ-blueprint cudnn-universal-cost cudnn-custom-cost cudnn-pooling-blueprint cudnn-convolution-layer-blueprint cudnn-gaussian-dropout-blueprint cudnn-batch-norm-layer-blueprint cudnn-branch-blueprint cudnn-concat-blueprint cudnn-sum-blueprint cudnn-split-blueprint]] [rnn :refer [cudnn-rnn-op-blueprint cudnn-rnn-blueprint cudnn-abbreviate-blueprint]]]) (:import jcuda.jcudnn.JCudnn)) (def ^{:private true :const true} INEFFICIENT_OPERATION_MSG "This operation would be inefficient because it does not use cuDNN capabilities. Please use dedicated tensor operations.") (def ^{:private true :const true} UNSUPPORTED_DATA_TYPE "The requested data type is not supported on the CUDA platform. Please contribute towards making it possible, or use on of the supported types.") (defn ^:private tensor-1d-equals [modl hstream x y] (with-release [equals-kernel (function modl "tensor_1d_equals") eq-flag-buf (mem-alloc Integer/BYTES)] (let [n (first (dims x))] (memset! eq-flag-buf 0) (launch! equals-kernel (grid-1d n) hstream (parameters (int n) (buffer x) (int (offset x)) (int (first (strides x))) (buffer y) (int (offset y)) (int (first (strides y))) eq-flag-buf)) (= 0 (read-int hstream eq-flag-buf))))) (defn ^:private tensor-2d-equals [modl hstream x y] (with-release [equals-kernel (function modl "tensor_2d_equals") eq-flag-buf (mem-alloc Integer/BYTES)] (let [[n c] (dims x) [nx cx] (strides x) [ny cy] (strides y)] (memset! eq-flag-buf 0) (launch! equals-kernel (grid-2d n c) hstream (parameters (int n) (int c) (buffer x) (int (offset x)) (int nx) (int cx) (buffer y) (int (offset y)) (int ny) (int cy) eq-flag-buf)) (= 0 (read-int hstream eq-flag-buf))))) (defn ^:private tensor-3d-equals [modl hstream x y] (with-release [equals-kernel (function modl "tensor_3d_equals") eq-flag-buf (mem-alloc Integer/BYTES)] (let [[n c h] (dims x) [nx cx hx] (strides x) [ny cy hy] (strides y)] (memset! eq-flag-buf 0) (launch! equals-kernel (grid-2d n c h) hstream (parameters (int n) (int c) (int h) (buffer x) (int (offset x)) (int nx) (int cx) (int hx) (buffer y) (int (offset y)) (int ny) (int cy) (int hy) eq-flag-buf)) (= 0 (read-int hstream eq-flag-buf))))) (defn ^:private tensor-4d-equals [modl hstream x y] (with-release [equals-kernel (function modl "tensor_4d_equals") eq-flag-buf (mem-alloc Integer/BYTES)] (let [[n c h w] (dims x) [nx cx hx wx] (strides x) [ny cy hy wy] (strides y)] (memset! eq-flag-buf 0) (launch! equals-kernel (grid-3d n c h) hstream (parameters (int n) (int c) (int h) (int w) (buffer x) (int (offset x)) (int nx) (int cx) (int hx) (int wx) (buffer y) (int (offset y)) (int ny) (int cy) (int hy) (int wy) eq-flag-buf)) (= 0 (read-int hstream eq-flag-buf))))) (defn ^:private tensor-5d-equals [modl hstream x y] (with-release [equals-kernel (function modl "tensor_5d_equals") eq-flag-buf (mem-alloc Integer/BYTES)] (let [[n c d h w] (dims x) [nx cx dx hx wx] (strides x) [ny cy dy hy wy] (strides y)] (memset! eq-flag-buf 0) (launch! equals-kernel (grid-3d n c h) hstream (parameters (int n) (int c) (int d) (int h) (int w) (buffer x) (int (offset x)) (int nx) (int cx) (int dx) (int hx) (int wx) (buffer y) (int (offset y)) (int ny) (int cy) (int dy) (int hy) (int wy) eq-flag-buf)) (= 0 (read-int hstream eq-flag-buf))))) (defn ^:private tensor-equals [modl hstream x y] (let [cnt (int (apply * (dims x)))] (if (< 0 cnt) (case (ndims x) 1 (tensor-1d-equals modl hstream x y) 2 (tensor-2d-equals modl hstream x y) 3 (tensor-3d-equals modl hstream x y) 4 (tensor-4d-equals modl hstream x y) 5 (tensor-5d-equals modl hstream x y) (dragan-says-ex "Equals is supported only up to 5 dimensions." {:shape (dims x)})) (= 0 (int (apply * (dims y))))))) (defn tensor-method ([method x] (let [vx (view-vctr x)] (check-contiguous x) (method (engine vx) vx))) ([method x y] (let [vx (view-vctr x)] (check-contiguous x y) (method (engine vx) vx (view-vctr y)))) ([method x y z] (let [vx (view-vctr x)] (check-contiguous x y z) (method (engine vx) vx (view-vctr y) (view-vctr z))))) (defn tensor-math ([method a y] (let [va (view-vctr a)] (check-contiguous a y) (method (engine va) va (view-vctr y)) y)) ([method a b y] (let [va (view-vctr a)] (check-contiguous a b y) (method (engine va) va (view-vctr b) (view-vctr y)) y))) (deftype TensorEngine [cudnn-hdl modl hstream cast ^long byte-cnt] BlockEngine (equals-block [_ x y] (tensor-equals modl hstream x y)) Blas (copy [_ x y] (transform-tensor cudnn-hdl (cast 1.0) x (buffer x) (* (offset y) byte-cnt) (cast 0.0) y (buffer y) (* (offset y) byte-cnt)) y) (axpy [_ alpha x y] (add-tensor cudnn-hdl (cast alpha) x (buffer x) (* (offset y) byte-cnt) (cast 1.0) y (buffer y) (* (offset y) byte-cnt)) y) (swap [_ x y] (tensor-method swap x y) x) (asum [_ x] (tensor-method asum x)) (nrm1 [_ x] (tensor-method nrm1 x)) (nrm2 [_ x] (tensor-method nrm2 x)) (nrmi [this x] (tensor-method nrmi x)) (scal [_ alpha x] (if (= 0 (offset x)) (scale-tensor cudnn-hdl (cast alpha) x (buffer x)) (scale-tensor cudnn-hdl (cast alpha) x (buffer x) (* (offset x) byte-cnt))) x) BlasPlus (amax [_ x] (tensor-method amax x)) (sum [_ x] (tensor-method sum x)) (set-all [_ value x] (if (= 0 (offset x)) (set-tensor cudnn-hdl x (buffer x) (cast value)) (set-tensor cudnn-hdl x (buffer x) (* (offset x) byte-cnt) (cast value))) x) (axpby [_ alpha x beta y] (add-tensor cudnn-hdl (cast alpha) x (buffer x) (* (offset y) byte-cnt) (cast beta) y (buffer y) (* (offset y) byte-cnt)) y) VectorMath (sqr [_ a y] (tensor-math sqr a y)) (mul [_ a b y] (tensor-math mul a b y)) (div [_ a b y] (tensor-math div a b y)) (inv [_ a y] (tensor-math inv a y)) (abs [_ a y] (tensor-math abs a y)) (linear-frac [_ a b scalea shifta scaleb shiftb y] (let [va (view-vctr a)] (linear-frac (engine va) va (view-vctr b) scalea shifta scaleb shiftb (view-vctr y)) y)) (fmod [_ a b y] (tensor-math fmod a b y) a) (frem [_ a b y] (tensor-math frem a b y)) (sqrt [_ a y] (tensor-math sqrt a y)) (inv-sqrt [_ a y] (tensor-math inv-sqrt a y)) (cbrt [_ a y] (tensor-math cbrt a y)) (inv-cbrt [_ a y] (tensor-math inv-cbrt a y)) (pow2o3 [_ a y] (tensor-math pow2o3 a y)) (pow3o2 [_ a y] (tensor-math pow3o2 a y)) (pow [_ a b y] (tensor-math pow a b y)) (powx [_ a b y] (powx (engine (view-vctr a)) (view-vctr a) b (view-vctr y)) y) (hypot [_ a b y] (tensor-math hypot a b y)) (exp [_ a y] (tensor-math exp a y)) (expm1 [_ a y] (tensor-math expm1 a y)) (log [_ a y] (tensor-math log a y)) (log10 [_ a y] (tensor-math log10 a y)) (sin [_ a y] (tensor-math sin a y)) (cos [_ a y] (tensor-math cos a y)) (tan [_ a y] (tensor-math tan a y)) (sincos [_ a y z] (tensor-math sincos a y z)) (asin [_ a y] (tensor-math asin a y)) (acos [_ a y] (tensor-math acos a y)) (atan [_ a y] (tensor-math atan a y)) (atan2 [_ a b y] (tensor-math atan a b y)) (sinh [_ a y] (tensor-math sinh a y)) (cosh [_ a y] (tensor-math cosh a y)) (tanh [_ a y] (tensor-math tanh a y)) (asinh [_ a y] (tensor-math asinh a y)) (acosh [_ a y] (tensor-math acosh a y)) (atanh [_ a y] (tensor-math atanh a y)) (erf [_ a y] (tensor-math erf a y)) (erfc [_ a y] (tensor-math erfc a y)) (erf-inv [_ a y] (tensor-math erf-inv a y)) (erfc-inv [_ a y] (tensor-math erfc-inv a y)) (cdf-norm [_ a y] (tensor-math cdf-norm a y)) (cdf-norm-inv [_ a y] (tensor-math cdf-norm-inv a y)) (gamma [_ a y] (tensor-math gamma a y)) (lgamma [_ a y] (tensor-math lgamma a y)) (expint1 [_ a y] (tensor-math expint1 a y)) (floor [_ a y] (tensor-math floor a y)) (fceil [_ a y] (tensor-math fceil a y)) (trunc [_ a y] (tensor-math trunc a y)) (round [_ a y] (tensor-math round a y)) (modf [_ a y z] (tensor-math modf a y z)) (frac [_ a y] (tensor-math frac a y)) (fmin [_ a b y] (tensor-math fmin a y)) (fmax [_ a b y] (tensor-math fmax a y)) (copy-sign [_ a b y] (tensor-math copy-sign a b y)) (sigmoid [this a y] (dragan-says-ex INEFFICIENT_OPERATION_MSG)) (ramp [this a y] (dragan-says-ex INEFFICIENT_OPERATION_MSG)) (relu [this alpha a y] (dragan-says-ex INEFFICIENT_OPERATION_MSG)) (elu [this alpha a y] (dragan-says-ex INEFFICIENT_OPERATION_MSG)) RandomNumberGenerator (rand-uniform [_ rng-stream lower upper x] (rand-uniform (engine (view-vctr x)) rng-stream lower upper (view-vctr x)) x) (rand-normal [_ rng-stream mu sigma x] (rand-normal (engine (view-vctr x)) rng-stream mu sigma (view-vctr x)) x)) (deftype CUDnnFactory [ctx hstream cudnn-hdl master native-diamond-fact neand-facts tensor-engines] Releaseable (release [_] (in-context ctx (doseq [neand-fact (vals neand-facts)] (release neand-fact)) (doseq [eng (vals tensor-engines)] (release eng)) (release cudnn-hdl)) (when master (when-not (= default-stream hstream) (release hstream)) (release ctx)) true) DiamondFactoryProvider (diamond-factory [this] this) (native-diamond-factory [_] native-diamond-fact) FlowProvider (flow [_] hstream) HandleProvider (handle [_] cudnn-hdl) NeanderthalFactoryProvider (neanderthal-factory [_ dtype] (or (get neand-facts dtype) (dragan-says-ex UNSUPPORTED_DATA_TYPE {:data-type dtype}))) TensorFactory (create-tensor-desc [this shape dtype format] (cudnn-tensor-desc shape dtype format)) (create-tensor-desc [this tz-desc] (cudnn-tensor-desc (shape tz-desc) (data-type tz-desc) (layout tz-desc))) (create-tensor [this tensor-desc init] (let-release [res (cudnn-tensor this tensor-desc)] (when init (set-all (engine res) 0 res)) res)) (create-tensor [this tensor-desc batch-index init] (let-release [res (cudnn-tensor this tensor-desc batch-index)] (when init (set-all (engine res) 0 res)) res)) (create-transformer [_ in-tz out-tz] (cudnn-transformer cudnn-hdl (view in-tz) (view out-tz))) (create-shuffler [_ src-tz dst-tz] (cudnn-shuffler cudnn-hdl (view src-tz) (view dst-tz))) (create-batcher [_ src-tz dst-tz mb-size] (cudnn-batcher cudnn-hdl (view src-tz) (view dst-tz) mb-size)) (tensor-engine [this dtype] (or (get tensor-engines dtype) (dragan-says-ex UNSUPPORTED_DATA_TYPE {:data-type dtype}))) DnnFactory (activ-blueprint [this src-desc activ coef _] (cudnn-activ-blueprint this src-desc activ coef)) (inner-product-blueprint [this src-desc dst-desc weights-type] (dragan-says-ex "cuDNN engine does not implement the inner product blueprint.")) (fc-blueprint [this src-desc dst-desc activ alpha beta weights-type] (neanderthal-fc-blueprint this src-desc dst-desc activ alpha beta weights-type)) (convolution-blueprint [this src-desc weights-desc dst-desc activ strides padding dilation alpha _] (cudnn-convolution-layer-blueprint this src-desc weights-desc dst-desc activ strides padding dilation alpha)) (pooling-blueprint [this src-desc dst-desc algo strides kernel padding] (cudnn-pooling-blueprint this src-desc dst-desc algo strides kernel padding)) (gaussian-dropout-blueprint [this src-desc sd] (cudnn-gaussian-dropout-blueprint this src-desc sd)) (batch-norm-blueprint [this src-desc activ alpha beta] (cudnn-batch-norm-layer-blueprint this src-desc activ alpha beta)) (concat-blueprint [this src-descs conc-dim dst-type] (cudnn-concat-blueprint this src-descs conc-dim dst-type)) (branch-blueprint [this src-desc branch-dim dst-descs] (cudnn-branch-blueprint this src-desc branch-dim dst-descs)) (split-blueprint [this src-desc n] (cudnn-split-blueprint this src-desc n)) (sum-blueprint [this src-descs] (cudnn-sum-blueprint this src-descs)) (create-workspace [_ byte-size] (in-context ctx (mem-alloc (max 1 (long byte-size))))) RnnFactory (rnn-op-blueprint [this src-desc dst-desc weights-type activ dir lrs src-iter? dst-iter?] (cudnn-rnn-op-blueprint this cudnn-hdl src-desc dst-desc weights-type activ dir lrs src-iter? dst-iter?)) (rnn-blueprint [fact src-desc dst-desc lrs activ _ _ weights-type src-iter? dst-iter?] (cudnn-rnn-blueprint fact cudnn-hdl src-desc dst-desc lrs activ weights-type src-iter? dst-iter?)) (abbreviate-blueprint [fact src-desc dst-type] (cudnn-abbreviate-blueprint fact src-desc dst-type)) CostFactory (quadratic-cost [_ prev-layer train-tz] (cudnn-universal-cost prev-layer train-tz quadratic-cost!)) (mean-absolute-cost [_ prev-layer train-tz] (cudnn-universal-cost prev-layer train-tz mean-absolute-cost!)) (crossentropy-cost [_ prev-layer train-tz] (cudnn-custom-cost prev-layer train-tz (partial crossentropy-cost! ((dims (output prev-layer)) 0))))) (JCudnn/setExceptionsEnabled false) (defn ^:private create-module [src dtype] (with-release [prog (compile! (program src) [(str "-DTYPE=" dtype) "-default-device"])] (module prog))) (let [src (slurp (io/resource "uncomplicate/diamond/internal/cuda/blas-plus.cu"))] (defn ^:private create-cudnn-factory [ctx hstream cudnn-hdl master] (let-release [float-modl (create-module src "float") double-modl (create-module src "double") long-modl (create-module src "long") int-modl (create-module src "int") byte-modl (create-module src "char") native-diamond-fact (dnnl-factory) float-fact (cuda-float ctx hstream) double-fact (cuda-double ctx hstream) long-fact (cuda-long ctx hstream) int-fact (cuda-int ctx hstream) byte-fact (cuda-byte ctx hstream) float-engine (->TensorEngine cudnn-hdl float-modl hstream float Float/BYTES) double-engine (->TensorEngine cudnn-hdl double-modl hstream double Double/BYTES) long-engine (->TensorEngine cudnn-hdl long-modl hstream long Long/BYTES) int-engine (->TensorEngine cudnn-hdl int-modl hstream int Integer/BYTES) byte-engine (->TensorEngine cudnn-hdl byte-modl hstream byte Byte/BYTES)] (->CUDnnFactory ctx hstream cudnn-hdl master native-diamond-fact {:float float-fact :double double-fact :long long-fact :int int-fact :byte byte-fact :uint8 byte-fact} {:float float-engine :double double-engine :int int-engine :long long-engine :byte byte-engine :uint8 byte-engine})))) (defn cudnn-factory ([ctx hstream] (in-context ctx (let-release [cudnn-hdl (cudnn-handle hstream) hstream (get-cudnn-stream cudnn-hdl)] (create-cudnn-factory ctx hstream cudnn-hdl false)))) ([] (init) (let-release [ctx (context (device))] (in-context ctx (let-release [hstream (stream) cudnn-hdl (cudnn-handle hstream)] (create-cudnn-factory ctx hstream cudnn-hdl true))))))
4969aaaba445b40a92f97465f004bb0e759a25eec7a0a765b2ddeb3063fe0a41
weavery/clarity.ml
compare.ml
(* This is free and unencumbered software released into the public domain. *) let rec equal_expressions a b = List.length a = List.length b && List.for_all2 equal_expression a b and equal_expression a b = match (a, b) with | Let (bindings1, body1), Let (bindings2, body2) -> equal_bindings bindings1 bindings2 && equal_expressions body1 body2 | Literal a, Literal b -> equal_literal a b | Match (input1, (ok_name1, ok_expr1), (err_name1, err_expr1)), Match (input2, (ok_name2, ok_expr2), (err_name2, err_expr2)) -> ok_name1 = ok_name2 && err_name1 = err_name2 && equal_expression input1 input2 && equal_expression ok_expr1 ok_expr2 && equal_expression err_expr1 err_expr2 | TupleExpression a, TupleExpression b -> equal_bindings a b | a, b -> a = b and equal_literal a b = match (a, b) with | IntLiteral a, IntLiteral b -> Integer.equal a b | UintLiteral a, UintLiteral b -> Integer.equal a b | TupleLiteral a, TupleLiteral b -> equal_literal_bindings a b | a, b -> a = b and equal_bindings a b = let equal_binding (ak, av) (bk, bv) = ak = bk && equal_expression av bv in List.length a = List.length b && List.for_all2 equal_binding a b and equal_literal_bindings a b = let equal_binding (ak, av) (bk, bv) = ak = bk && equal_literal av bv in List.length a = List.length b && List.for_all2 equal_binding a b
null
https://raw.githubusercontent.com/weavery/clarity.ml/20e48b275eaacd7fa71a7b9b7796977f0aba95cb/src/compare.ml
ocaml
This is free and unencumbered software released into the public domain.
let rec equal_expressions a b = List.length a = List.length b && List.for_all2 equal_expression a b and equal_expression a b = match (a, b) with | Let (bindings1, body1), Let (bindings2, body2) -> equal_bindings bindings1 bindings2 && equal_expressions body1 body2 | Literal a, Literal b -> equal_literal a b | Match (input1, (ok_name1, ok_expr1), (err_name1, err_expr1)), Match (input2, (ok_name2, ok_expr2), (err_name2, err_expr2)) -> ok_name1 = ok_name2 && err_name1 = err_name2 && equal_expression input1 input2 && equal_expression ok_expr1 ok_expr2 && equal_expression err_expr1 err_expr2 | TupleExpression a, TupleExpression b -> equal_bindings a b | a, b -> a = b and equal_literal a b = match (a, b) with | IntLiteral a, IntLiteral b -> Integer.equal a b | UintLiteral a, UintLiteral b -> Integer.equal a b | TupleLiteral a, TupleLiteral b -> equal_literal_bindings a b | a, b -> a = b and equal_bindings a b = let equal_binding (ak, av) (bk, bv) = ak = bk && equal_expression av bv in List.length a = List.length b && List.for_all2 equal_binding a b and equal_literal_bindings a b = let equal_binding (ak, av) (bk, bv) = ak = bk && equal_literal av bv in List.length a = List.length b && List.for_all2 equal_binding a b
fd471e19546397786fab6d23ee34104aea3f9aece140997393ce3efd4b995f55
remixlabs/wasicaml
wc_traceglobals.ml
Copyright ( C ) 2021 by Figly , Inc. This code is free software , see the file LICENSE for details . This code is free software, see the file LICENSE for details. *) open Printf open Wc_types open Wc_control open Wc_util (* analyze the initialization code and figure out which globals correspond to which global functions *) type initvalue = | Unknown | Function of { label:int } | FuncInEnv of { func_offset:int; env:initvalue array } | Block of initvalue array Function is a pointer to the letrec [ label ] . FuncInEnv is a function inside an environment . env[func_offset ] must be a Function . Block is a block of values FuncInEnv is a function inside an environment. env[func_offset] must be a Function. Block is a block of values *) let is_function = function | Function _ -> true | _ -> false type shape = { stack : initvalue list; length : int; accu : initvalue } let empty_shape = { stack = []; length = 0; accu = Unknown } let print_initvalue prefix initvalue = let rec recurse prefix initvalue = match initvalue with | Unknown -> () | Function fn -> printf "%s = letrec_%d\n" prefix fn.label | FuncInEnv fenv -> Array.iteri (fun i iv -> recurse (sprintf "%s.env[%d](%d)" prefix i fenv.func_offset) iv ) fenv.env | Block b -> Array.iteri (fun i iv -> recurse (sprintf "%s[%d]" prefix i) iv ) b in recurse prefix initvalue let rec merge_initvalues v1 v2 = match v1, v2 with | Function fn1, Function fn2 when fn1.label = fn2.label -> v1 | FuncInEnv fenv1, FuncInEnv fenv2 when fenv1.func_offset = fenv2.func_offset && Array.length fenv1.env = Array.length fenv2.env -> let env = merge_initvalue_arrays fenv1.env fenv2.env in FuncInEnv { fenv1 with env } | Block b1, Block b2 when Array.length b1 = Array.length b2 -> Block (merge_initvalue_arrays b1 b2) | _ -> Unknown and merge_initvalue_arrays a1 a2 = Array.mapi (fun i bv1 -> let bv2 = a2.(i) in merge_initvalues bv1 bv2 ) a1 let merge_stacks s1 s2 = assert(s1.length = s2.length); { stack = List.map2 merge_initvalues s1.stack s2.stack; length = s1.length; accu = merge_initvalues s1.accu s2.accu; } let rec delete n l = if n <= 0 then l else match l with | x :: l' -> delete (n-1) l' | [] -> [] let global_offset ident = assert(Ident.global ident); let name = Ident.name ident in int_of_string name let trace_globals_of_fblock globals_table fblock = let shape_table = Hashtbl.create 7 in (* maps label to stack shape of camlstack *) let update_shape_table stack labels = List.iter (fun label -> try let lstack = Hashtbl.find shape_table label in if lstack.length <> stack.length then ( eprintf "[DEBUG] Bad function: %d\n" fblock.scope.cfg_func_label; eprintf "[DEBUG] Bad label: %d\n" label; eprintf "[DEBUG] stack.length=%d lstack.length=%d\n" stack.length lstack.length; Wc_tracestack.dump fblock.block 0; assert false; ); let merged = merge_stacks stack lstack in Hashtbl.replace shape_table label merged with | Not_found -> Hashtbl.add shape_table label stack ) labels in let trace_instr shape i = match i with | I.Kacc sp -> if sp < shape.length then { shape with accu = List.nth shape.stack sp } else { shape with accu = Unknown } | Kpush -> { shape with stack = shape.accu :: shape.stack; length = shape.length + 1 } | Kpop n -> { shape with stack = delete n shape.stack; length = shape.length - n } | Kassign sp -> let stack = List.mapi (fun i x -> if i = sp then shape.accu else x) shape.stack in { shape with stack } | Kmakeblock(size, 0) when size > 0 -> let block = shape.accu :: list_prefix (size-1) shape.stack |> Array.of_list |> (fun a -> Block a) in { stack = delete (size-1) shape.stack; length = shape.length - (size-1); accu = block } | Kclosure(label, num) -> let env_fields = if num=0 then [] else shape.accu :: list_prefix (num-1) shape.stack in let env = Array.of_list (Function { label } :: Unknown :: env_fields) in let n = max (num-1) 0 in { accu = FuncInEnv { func_offset=0; env }; stack = delete n shape.stack; length = shape.length - n } | Kclosurerec(labs, num) when labs <> [] -> let num_labs = List.length labs in let env_fields = if num=0 then [] else shape.accu :: list_prefix (num-1) shape.stack in let env_fields_a = Array.of_list env_fields in let unknowns = Array.make (2 + 3 * (num_labs-1)) Unknown in let env = Array.append unknowns env_fields_a in let n = max (num-1) 0 in let funcs = List.rev labs |> List.mapi (fun i label -> let func_offset = 3 * (num_labs-i-1) in env.(func_offset) <- Function { label }; FuncInEnv {func_offset; env} ) in { stack = funcs @ delete n shape.stack; length = shape.length + - n + List.length funcs; accu = Unknown } | Ksetglobal ident -> let offset = global_offset ident in Hashtbl.replace globals_table offset shape.accu; shape | _ -> let d = Wc_traceinstr.trace_stack_instr 0 i in if d > 0 then let nstack = Array.make d Unknown |> Array.to_list in { stack = nstack @ shape.stack; length = shape.length + d; accu = Unknown } else if d < 0 then { stack = delete (-d) shape.stack; length = shape.length + d; accu = Unknown } else { shape with accu = Unknown } in let rec recurse block = Array.fold_left (fun shape instr -> match instr with | Label label -> let stack = try Hashtbl.find shape_table label with Not_found -> empty_shape in stack | Simple i -> let labels = Wc_tracestack.local_branch_labels i in update_shape_table shape labels; let stack' = trace_instr shape i in stack' | Trap { catchlabel; poplabel=Some pop } -> update_shape_table shape [ catchlabel; pop ]; shape | Trap { catchlabel; poplabel=None } -> update_shape_table shape [ catchlabel ]; shape | TryReturn -> shape | NextMain _ -> shape | Block inner -> recurse inner ) empty_shape block.instructions in ignore(recurse fblock.block) let trace_globals scode = let globals_table = Hashtbl.create 7 in (* maps global index to initvalue (Unknown not possible) *) IMap.iter (fun func_label fblock -> if fblock.scope.cfg_main then trace_globals_of_fblock globals_table fblock ) scode.functions; (* Hashtbl.iter (fun i iv -> print_initvalue (sprintf "global%d" i) iv ) globals_table; flush stdout; *) globals_table let derive_glbfun_table globals_table = let glbfun_table = Hashtbl.create 7 in let rec recurse initvalue = match initvalue with | Unknown -> () | Block b -> Array.iter recurse b | FuncInEnv { env; _ } -> Array.iteri (fun func_offset env_val -> match env_val with | Function { label } -> Hashtbl.replace glbfun_table label (func_offset, env) | _ -> () ) env | Function _ -> assert false in Hashtbl.iter (fun glb initvalue -> recurse initvalue ) globals_table; glbfun_table
null
https://raw.githubusercontent.com/remixlabs/wasicaml/81db46bec0a52a4ce4ae74ac1e4a2b0a40af5b29/src/wasicaml/wc_traceglobals.ml
ocaml
analyze the initialization code and figure out which globals correspond to which global functions maps label to stack shape of camlstack maps global index to initvalue (Unknown not possible) Hashtbl.iter (fun i iv -> print_initvalue (sprintf "global%d" i) iv ) globals_table; flush stdout;
Copyright ( C ) 2021 by Figly , Inc. This code is free software , see the file LICENSE for details . This code is free software, see the file LICENSE for details. *) open Printf open Wc_types open Wc_control open Wc_util type initvalue = | Unknown | Function of { label:int } | FuncInEnv of { func_offset:int; env:initvalue array } | Block of initvalue array Function is a pointer to the letrec [ label ] . FuncInEnv is a function inside an environment . env[func_offset ] must be a Function . Block is a block of values FuncInEnv is a function inside an environment. env[func_offset] must be a Function. Block is a block of values *) let is_function = function | Function _ -> true | _ -> false type shape = { stack : initvalue list; length : int; accu : initvalue } let empty_shape = { stack = []; length = 0; accu = Unknown } let print_initvalue prefix initvalue = let rec recurse prefix initvalue = match initvalue with | Unknown -> () | Function fn -> printf "%s = letrec_%d\n" prefix fn.label | FuncInEnv fenv -> Array.iteri (fun i iv -> recurse (sprintf "%s.env[%d](%d)" prefix i fenv.func_offset) iv ) fenv.env | Block b -> Array.iteri (fun i iv -> recurse (sprintf "%s[%d]" prefix i) iv ) b in recurse prefix initvalue let rec merge_initvalues v1 v2 = match v1, v2 with | Function fn1, Function fn2 when fn1.label = fn2.label -> v1 | FuncInEnv fenv1, FuncInEnv fenv2 when fenv1.func_offset = fenv2.func_offset && Array.length fenv1.env = Array.length fenv2.env -> let env = merge_initvalue_arrays fenv1.env fenv2.env in FuncInEnv { fenv1 with env } | Block b1, Block b2 when Array.length b1 = Array.length b2 -> Block (merge_initvalue_arrays b1 b2) | _ -> Unknown and merge_initvalue_arrays a1 a2 = Array.mapi (fun i bv1 -> let bv2 = a2.(i) in merge_initvalues bv1 bv2 ) a1 let merge_stacks s1 s2 = assert(s1.length = s2.length); { stack = List.map2 merge_initvalues s1.stack s2.stack; length = s1.length; accu = merge_initvalues s1.accu s2.accu; } let rec delete n l = if n <= 0 then l else match l with | x :: l' -> delete (n-1) l' | [] -> [] let global_offset ident = assert(Ident.global ident); let name = Ident.name ident in int_of_string name let trace_globals_of_fblock globals_table fblock = let shape_table = Hashtbl.create 7 in let update_shape_table stack labels = List.iter (fun label -> try let lstack = Hashtbl.find shape_table label in if lstack.length <> stack.length then ( eprintf "[DEBUG] Bad function: %d\n" fblock.scope.cfg_func_label; eprintf "[DEBUG] Bad label: %d\n" label; eprintf "[DEBUG] stack.length=%d lstack.length=%d\n" stack.length lstack.length; Wc_tracestack.dump fblock.block 0; assert false; ); let merged = merge_stacks stack lstack in Hashtbl.replace shape_table label merged with | Not_found -> Hashtbl.add shape_table label stack ) labels in let trace_instr shape i = match i with | I.Kacc sp -> if sp < shape.length then { shape with accu = List.nth shape.stack sp } else { shape with accu = Unknown } | Kpush -> { shape with stack = shape.accu :: shape.stack; length = shape.length + 1 } | Kpop n -> { shape with stack = delete n shape.stack; length = shape.length - n } | Kassign sp -> let stack = List.mapi (fun i x -> if i = sp then shape.accu else x) shape.stack in { shape with stack } | Kmakeblock(size, 0) when size > 0 -> let block = shape.accu :: list_prefix (size-1) shape.stack |> Array.of_list |> (fun a -> Block a) in { stack = delete (size-1) shape.stack; length = shape.length - (size-1); accu = block } | Kclosure(label, num) -> let env_fields = if num=0 then [] else shape.accu :: list_prefix (num-1) shape.stack in let env = Array.of_list (Function { label } :: Unknown :: env_fields) in let n = max (num-1) 0 in { accu = FuncInEnv { func_offset=0; env }; stack = delete n shape.stack; length = shape.length - n } | Kclosurerec(labs, num) when labs <> [] -> let num_labs = List.length labs in let env_fields = if num=0 then [] else shape.accu :: list_prefix (num-1) shape.stack in let env_fields_a = Array.of_list env_fields in let unknowns = Array.make (2 + 3 * (num_labs-1)) Unknown in let env = Array.append unknowns env_fields_a in let n = max (num-1) 0 in let funcs = List.rev labs |> List.mapi (fun i label -> let func_offset = 3 * (num_labs-i-1) in env.(func_offset) <- Function { label }; FuncInEnv {func_offset; env} ) in { stack = funcs @ delete n shape.stack; length = shape.length + - n + List.length funcs; accu = Unknown } | Ksetglobal ident -> let offset = global_offset ident in Hashtbl.replace globals_table offset shape.accu; shape | _ -> let d = Wc_traceinstr.trace_stack_instr 0 i in if d > 0 then let nstack = Array.make d Unknown |> Array.to_list in { stack = nstack @ shape.stack; length = shape.length + d; accu = Unknown } else if d < 0 then { stack = delete (-d) shape.stack; length = shape.length + d; accu = Unknown } else { shape with accu = Unknown } in let rec recurse block = Array.fold_left (fun shape instr -> match instr with | Label label -> let stack = try Hashtbl.find shape_table label with Not_found -> empty_shape in stack | Simple i -> let labels = Wc_tracestack.local_branch_labels i in update_shape_table shape labels; let stack' = trace_instr shape i in stack' | Trap { catchlabel; poplabel=Some pop } -> update_shape_table shape [ catchlabel; pop ]; shape | Trap { catchlabel; poplabel=None } -> update_shape_table shape [ catchlabel ]; shape | TryReturn -> shape | NextMain _ -> shape | Block inner -> recurse inner ) empty_shape block.instructions in ignore(recurse fblock.block) let trace_globals scode = let globals_table = Hashtbl.create 7 in IMap.iter (fun func_label fblock -> if fblock.scope.cfg_main then trace_globals_of_fblock globals_table fblock ) scode.functions; globals_table let derive_glbfun_table globals_table = let glbfun_table = Hashtbl.create 7 in let rec recurse initvalue = match initvalue with | Unknown -> () | Block b -> Array.iter recurse b | FuncInEnv { env; _ } -> Array.iteri (fun func_offset env_val -> match env_val with | Function { label } -> Hashtbl.replace glbfun_table label (func_offset, env) | _ -> () ) env | Function _ -> assert false in Hashtbl.iter (fun glb initvalue -> recurse initvalue ) globals_table; glbfun_table
7644dc2213ac2971fc694df36288e1d4088f02dc2356d867e343bbf73a2236b5
jellelicht/guix
system.scm
;;; GNU Guix --- Functional package management for GNU Copyright © 2014 , 2015 , 2016 < > Copyright © 2016 < > ;;; ;;; This file is part of GNU Guix. ;;; GNU is free software ; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation ; either version 3 of the License , or ( at ;;; your option) any later version. ;;; ;;; GNU Guix is distributed in the hope that it will be useful, but ;;; WITHOUT ANY WARRANTY; without even the implied warranty of ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;;; GNU General Public License for more details. ;;; You should have received a copy of the GNU General Public License along with GNU . If not , see < / > . (define-module (guix scripts system) #:use-module (guix config) #:use-module (guix ui) #:use-module (guix store) #:use-module (guix grafts) #:use-module (guix gexp) #:use-module (guix derivations) #:use-module (guix packages) #:use-module (guix utils) #:use-module (guix monads) #:use-module (guix records) #:use-module (guix profiles) #:use-module (guix scripts) #:use-module (guix scripts build) #:use-module (guix graph) #:use-module (guix scripts graph) #:use-module (guix build utils) #:use-module (gnu build install) #:use-module (gnu system) #:use-module (gnu system file-systems) #:use-module (gnu system linux-container) #:use-module (gnu system vm) #:use-module (gnu system grub) #:use-module (gnu services) #:use-module (gnu services shepherd) #:use-module (gnu services herd) #:use-module (gnu packages grub) #:use-module (srfi srfi-1) #:use-module (srfi srfi-11) #:use-module (srfi srfi-19) #:use-module (srfi srfi-26) #:use-module (srfi srfi-34) #:use-module (srfi srfi-35) #:use-module (srfi srfi-37) #:use-module (ice-9 match) #:export (guix-system read-operating-system)) ;;; ;;; Operating system declaration. ;;; (define %user-module ;; Module in which the machine description file is loaded. (make-user-module '((gnu system) (gnu services) (gnu system shadow)))) (define (read-operating-system file) "Read the operating-system declaration from FILE and return it." (load* file %user-module)) ;;; ;;; Installation. ;;; TODO : Factorize . (define references* (store-lift references)) (define topologically-sorted* (store-lift topologically-sorted)) (define* (copy-item item target #:key (log-port (current-error-port))) "Copy ITEM to the store under root directory TARGET and register it." (mlet* %store-monad ((refs (references* item))) (let ((dest (string-append target item)) (state (string-append target "/var/guix"))) (format log-port "copying '~a'...~%" item) ;; Remove DEST if it exists to make sure that (1) we do not fail badly ;; while trying to overwrite it (see <>), and ( 2 ) we end up with the right contents . (when (file-exists? dest) (delete-file-recursively dest)) (copy-recursively item dest #:log (%make-void-port "w")) ;; Register ITEM; as a side-effect, it resets timestamps, etc. ;; Explicitly use "TARGET/var/guix" as the state directory, to avoid ;; reproducing the user's current settings; see ;; <>. (unless (register-path item #:prefix target #:state-directory state #:references refs) (leave (_ "failed to register '~a' under '~a'~%") item target)) (return #t)))) (define* (copy-closure item target #:key (log-port (current-error-port))) "Copy ITEM and all its dependencies to the store under root directory TARGET, and register them." (mlet* %store-monad ((refs (references* item)) (to-copy (topologically-sorted* (delete-duplicates (cons item refs) string=?)))) (sequence %store-monad (map (cut copy-item <> target #:log-port log-port) to-copy)))) (define (install-grub* grub.cfg device target) "This is a variant of 'install-grub' with error handling, lifted in %STORE-MONAD" (let* ((gc-root (string-append target %gc-roots-directory "/grub.cfg")) (temp-gc-root (string-append gc-root ".new")) (delete-file (lift1 delete-file %store-monad)) (make-symlink (lift2 switch-symlinks %store-monad)) (rename (lift2 rename-file %store-monad))) (mbegin %store-monad Prepare the symlink to GRUB.CFG to make sure that it 's a GC root when ;; 'install-grub' completes (being a bit paranoid.) (make-symlink temp-gc-root grub.cfg) (munless (false-if-exception (install-grub grub.cfg device target)) (delete-file temp-gc-root) (leave (_ "failed to install GRUB on device '~a'~%") device)) Register GRUB.CFG as a GC root so that its dependencies ( background ;; image, font, etc.) are not reclaimed. (rename temp-gc-root gc-root)))) (define* (install os-drv target #:key (log-port (current-output-port)) grub? grub.cfg device) "Copy the closure of GRUB.CFG, which includes the output of OS-DRV, to directory TARGET. TARGET must be an absolute directory name since that's what 'guix-register' expects. When GRUB? is true, install GRUB on DEVICE, using GRUB.CFG." (define (maybe-copy to-copy) (with-monad %store-monad (if (string=? target "/") (begin (warning (_ "initializing the current root file system~%")) (return #t)) (begin ;; Make sure the target store exists. (mkdir-p (string-append target (%store-prefix))) ;; Copy items to the new store. (copy-closure to-copy target #:log-port log-port))))) Make sure is root - owned when running as root , but still allow ;; non-root uses (useful for testing.) See ;; <-devel/2015-05/msg00452.html>. (if (zero? (geteuid)) (chown target 0 0) (warning (_ "not running as 'root', so \ the ownership of '~a' may be incorrect!~%") target)) (chmod target #o755) (let ((os-dir (derivation->output-path os-drv)) (format (lift format %store-monad)) (populate (lift2 populate-root-file-system %store-monad))) (mbegin %store-monad Copy the closure of GRUB.CFG , which includes OS - DIR , GRUB 's ;; background image and so on. (maybe-copy grub.cfg) ;; Create a bunch of additional files. (format log-port "populating '~a'...~%" target) (populate os-dir target) (mwhen grub? (install-grub* grub.cfg device target))))) ;;; ;;; Reconfiguration. ;;; (define %system-profile ;; The system profile. (string-append %state-directory "/profiles/system")) (define-syntax-rule (save-environment-excursion body ...) "Save the current environment variables, run BODY..., and restore them." (let ((env (environ))) (dynamic-wind (const #t) (lambda () body ...) (lambda () (environ env))))) (define-syntax-rule (save-load-path-excursion body ...) "Save the current values of '%load-path' and '%load-compiled-path', run BODY..., and restore them." (let ((path %load-path) (cpath %load-compiled-path)) (dynamic-wind (const #t) (lambda () body ...) (lambda () (set! %load-path path) (set! %load-compiled-path cpath))))) (define-syntax-rule (warn-on-system-error body ...) (catch 'system-error (lambda () body ...) (lambda (key proc format-string format-args errno . rest) (warning (_ "while talking to shepherd: ~a~%") (apply format #f format-string format-args)) (with-monad %store-monad (return #f))))) (define (upgrade-shepherd-services os) "Upgrade the Shepherd (PID 1) by unloading obsolete services and loading new services specified in OS and not currently running. This is currently very conservative in that it does not stop or unload any running service. Unloading or stopping the wrong service ('udev', say) could bring the system down." (define (essential? service) (memq service '(root shepherd))) (define new-services (service-parameters (fold-services (operating-system-services os) #:target-type shepherd-root-service-type))) (define new-service-names (map (compose first shepherd-service-provision) new-services)) ;; Arrange to simply emit a warning if we cannot connect to the shepherd. (warn-on-system-error (let-values (((running stopped) (current-services))) (define to-load ;; Only load services that are either new or currently stopped. (remove (lambda (service) (memq (first (shepherd-service-provision service)) running)) new-services)) (define to-unload Unload services that are ( 1 ) no longer required , or ( 2 ) are in ;; TO-LOAD. (remove essential? (append (remove (lambda (service) (memq service new-service-names)) (append running stopped)) (filter (lambda (service) (memq service stopped)) (map shepherd-service-canonical-name to-load))))) (for-each (lambda (unload) (info (_ "unloading service '~a'...~%") unload) (unload-service unload)) to-unload) (with-monad %store-monad (munless (null? to-load) (let ((to-load-names (map shepherd-service-canonical-name to-load)) (to-start (filter shepherd-service-auto-start? to-load))) (info (_ "loading new services:~{ ~a~}...~%") to-load-names) (mlet %store-monad ((files (mapm %store-monad shepherd-service-file to-load))) ;; Here we assume that FILES are exactly those that were computed ;; as part of the derivation that built OS, which is normally the ;; case. (load-services (map derivation->output-path files)) (for-each start-service (map shepherd-service-canonical-name to-start)) (return #t)))))))) (define* (switch-to-system os #:optional (profile %system-profile)) "Make a new generation of PROFILE pointing to the directory of OS, switch to it atomically, and then run OS's activation script." (mlet* %store-monad ((drv (operating-system-derivation os)) (script (operating-system-activation-script os))) (let* ((system (derivation->output-path drv)) (number (+ 1 (generation-number profile))) (generation (generation-file-name profile number))) (symlink system generation) (switch-symlinks profile generation) (format #t (_ "activating system...~%")) ;; The activation script may change $PATH, among others, so protect ;; against that. (save-environment-excursion ;; Tell 'activate-current-system' what the new system is. (setenv "GUIX_NEW_SYSTEM" system) The activation script may modify ' % load - path ' & co. , so protect ;; against that. This is necessary to ensure that ;; 'upgrade-shepherd-services' gets to see the right modules when it ;; computes derivations with (gexp->derivation #:modules …). (save-load-path-excursion (primitive-load (derivation->output-path script)))) ;; Finally, try to update system services. (upgrade-shepherd-services os)))) (define-syntax-rule (unless-file-not-found exp) (catch 'system-error (lambda () exp) (lambda args (if (= ENOENT (system-error-errno args)) #f (apply throw args))))) (define (seconds->string seconds) "Return a string representing the date for SECONDS." (let ((time (make-time time-utc 0 seconds))) (date->string (time-utc->date time) "~Y-~m-~d ~H:~M"))) (define* (previous-grub-entries #:optional (profile %system-profile)) "Return a list of 'menu-entry' for the generations of PROFILE." (define (system->grub-entry system number time) (unless-file-not-found (let* ((file (string-append system "/parameters")) (params (call-with-input-file file read-boot-parameters)) (label (boot-parameters-label params)) (root (boot-parameters-root-device params)) (kernel (boot-parameters-kernel params)) (kernel-arguments (boot-parameters-kernel-arguments params))) (menu-entry (label (string-append label " (#" (number->string number) ", " (seconds->string time) ")")) (linux kernel) (linux-arguments (cons* (string-append "--root=" root) #~(string-append "--system=" #$system) #~(string-append "--load=" #$system "/boot") kernel-arguments)) (initrd #~(string-append #$system "/initrd")))))) (let* ((numbers (generation-numbers profile)) (systems (map (cut generation-file-name profile <>) numbers)) (times (map (lambda (system) (unless-file-not-found (stat:mtime (lstat system)))) systems))) (filter-map system->grub-entry systems numbers times))) ;;; ;;; Graphs. ;;; (define (service-node-label service) "Return a label to represent SERVICE." (let ((type (service-kind service)) (value (service-parameters service))) (string-append (symbol->string (service-type-name type)) (cond ((or (number? value) (symbol? value)) (string-append " " (object->string value))) ((string? value) (string-append " " value)) ((file-system? value) (string-append " " (file-system-mount-point value))) (else ""))))) (define (service-node-type services) "Return a node type for SERVICES. Since <service> instances are not self-contained (they express dependencies on service types, not on services), we have to create the 'edges' procedure dynamically as a function of the full list of services." (node-type (name "service") (description "the DAG of services") (identifier (lift1 object-address %store-monad)) (label service-node-label) (edges (lift1 (service-back-edges services) %store-monad)))) (define (shepherd-service-node-label service) "Return a label for a node representing a <shepherd-service>." (string-join (map symbol->string (shepherd-service-provision service)))) (define (shepherd-service-node-type services) "Return a node type for SERVICES, a list of <shepherd-service>." (node-type (name "shepherd-service") (description "the dependency graph of shepherd services") (identifier (lift1 shepherd-service-node-label %store-monad)) (label shepherd-service-node-label) (edges (lift1 (shepherd-service-back-edges services) %store-monad)))) ;;; ;;; Generations. ;;; (define* (display-system-generation number #:optional (profile %system-profile)) "Display a summary of system generation NUMBER in a human-readable format." (unless (zero? number) (let* ((generation (generation-file-name profile number)) (param-file (string-append generation "/parameters")) (params (call-with-input-file param-file read-boot-parameters)) (label (boot-parameters-label params)) (root (boot-parameters-root-device params)) (kernel (boot-parameters-kernel params))) (display-generation profile number) (format #t (_ " file name: ~a~%") generation) (format #t (_ " canonical file name: ~a~%") (readlink* generation)) TRANSLATORS : Please preserve the two - space indentation . (format #t (_ " label: ~a~%") label) (format #t (_ " root device: ~a~%") root) (format #t (_ " kernel: ~a~%") kernel)))) (define* (list-generations pattern #:optional (profile %system-profile)) "Display in a human-readable format all the system generations matching PATTERN, a string. When PATTERN is #f, display all the system generations." (cond ((not (file-exists? profile)) ; XXX: race condition (raise (condition (&profile-not-found-error (profile profile))))) ((string-null? pattern) (for-each display-system-generation (profile-generations profile))) ((matching-generations pattern profile) => (lambda (numbers) (if (null-list? numbers) (exit 1) (leave-on-EPIPE (for-each display-system-generation numbers))))) (else (leave (_ "invalid syntax: ~a~%") pattern)))) ;;; ;;; Action. ;;; (define* (system-derivation-for-action os action #:key image-size full-boot? mappings) "Return as a monadic value the derivation for OS according to ACTION." (case action ((build init reconfigure) (operating-system-derivation os)) ((container) (container-script os #:mappings mappings)) ((vm-image) (system-qemu-image os #:disk-image-size image-size)) ((vm) (system-qemu-image/shared-store-script os #:full-boot? full-boot? #:disk-image-size image-size #:mappings mappings)) ((disk-image) (system-disk-image os #:disk-image-size image-size)))) (define* (perform-action action os #:key grub? dry-run? derivations-only? use-substitutes? device target image-size full-boot? (mappings '())) "Perform ACTION for OS. GRUB? specifies whether to install GRUB; DEVICE is TARGET is the target root directory ; IMAGE - SIZE is the size of the image to be built, for the 'vm-image' and 'disk-image' actions. FULL-BOOT? is used for the 'vm' action; it determines whether to boot directly to the kernel or to the bootloader. When DERIVATIONS-ONLY? is true, print the derivation file name(s) without building anything." (define println (cut format #t "~a~%" <>)) (mlet* %store-monad ((sys (system-derivation-for-action os action #:image-size image-size #:full-boot? full-boot? #:mappings mappings)) (grub (package->derivation grub)) (grub.cfg (if (eq? 'container action) (return #f) (operating-system-grub.cfg os (if (eq? 'init action) '() (previous-grub-entries))))) ;; For 'init' and 'reconfigure', always build GRUB.CFG, even if --no - grub is passed , because GRUB.CFG because we then use it as a GC ;; root. See <>. (drvs -> (if (memq action '(init reconfigure)) (if grub? (list sys grub.cfg grub) (list sys grub.cfg)) (list sys))) (% (if derivations-only? (return (for-each (compose println derivation-file-name) drvs)) (maybe-build drvs #:dry-run? dry-run? #:use-substitutes? use-substitutes?)))) (if (or dry-run? derivations-only?) (return #f) (begin (for-each (compose println derivation->output-path) drvs) Make sure GRUB is accessible . (when grub? (let ((prefix (derivation->output-path grub))) (setenv "PATH" (string-append prefix "/bin:" prefix "/sbin:" (getenv "PATH"))))) (case action ((reconfigure) (mbegin %store-monad (switch-to-system os) (mwhen grub? (install-grub* (derivation->output-path grub.cfg) device "/")))) ((init) (newline) (format #t (_ "initializing operating system under '~a'...~%") target) (install sys (canonicalize-path target) #:grub? grub? #:grub.cfg (derivation->output-path grub.cfg) #:device device)) (else All we had to do was to build SYS . (return (derivation->output-path sys)))))))) (define (export-extension-graph os port) "Export the service extension graph of OS to PORT." (let* ((services (operating-system-services os)) (system (find (lambda (service) (eq? (service-kind service) system-service-type)) services))) (export-graph (list system) (current-output-port) #:node-type (service-node-type services) #:reverse-edges? #t))) (define (export-shepherd-graph os port) "Export the graph of shepherd services of OS to PORT." (let* ((services (operating-system-services os)) (pid1 (fold-services services #:target-type shepherd-root-service-type)) (shepherds (service-parameters pid1)) ;list of <shepherd-service> (sinks (filter (lambda (service) (null? (shepherd-service-requirement service))) shepherds))) (export-graph sinks (current-output-port) #:node-type (shepherd-service-node-type shepherds) #:reverse-edges? #t))) ;;; ;;; Options. ;;; (define (show-help) (display (_ "Usage: guix system [OPTION] ACTION [FILE] Build the operating system declared in FILE according to ACTION.\n")) (newline) (display (_ "The valid values for ACTION are:\n")) (newline) (display (_ "\ reconfigure switch to a new operating system configuration\n")) (display (_ "\ list-generations list the system generations\n")) (display (_ "\ build build the operating system without installing anything\n")) (display (_ "\ container build a container that shares the host's store\n")) (display (_ "\ vm build a virtual machine image that shares the host's store\n")) (display (_ "\ vm-image build a freestanding virtual machine image\n")) (display (_ "\ disk-image build a disk image, suitable for a USB stick\n")) (display (_ "\ init initialize a root file system to run GNU\n")) (display (_ "\ extension-graph emit the service extension graph in Dot format\n")) (display (_ "\ shepherd-graph emit the graph of shepherd services in Dot format\n")) (show-build-options-help) (display (_ " -d, --derivation return the derivation of the given system")) (display (_ " --on-error=STRATEGY apply STRATEGY when an error occurs while reading FILE")) (display (_ " --image-size=SIZE for 'vm-image', produce an image of SIZE")) (display (_ " --no-grub for 'init', do not install GRUB")) (display (_ " --share=SPEC for 'vm', share host file system according to SPEC")) (display (_ " --expose=SPEC for 'vm', expose host file system according to SPEC")) (display (_ " --full-boot for 'vm', make a full boot sequence")) (newline) (display (_ " -h, --help display this help and exit")) (display (_ " -V, --version display version information and exit")) (newline) (show-bug-report-information)) (define %options ;; Specifications of the command-line options. (cons* (option '(#\h "help") #f #f (lambda args (show-help) (exit 0))) (option '(#\V "version") #f #f (lambda args (show-version-and-exit "guix system"))) (option '(#\d "derivation") #f #f (lambda (opt name arg result) (alist-cons 'derivations-only? #t result))) (option '("on-error") #t #f (lambda (opt name arg result) (alist-cons 'on-error (string->symbol arg) result))) (option '("image-size") #t #f (lambda (opt name arg result) (alist-cons 'image-size (size->number arg) result))) (option '("no-grub") #f #f (lambda (opt name arg result) (alist-cons 'install-grub? #f result))) (option '("full-boot") #f #f (lambda (opt name arg result) (alist-cons 'full-boot? #t result))) (option '("share") #t #f (lambda (opt name arg result) (alist-cons 'file-system-mapping (specification->file-system-mapping arg #t) result))) (option '("expose") #t #f (lambda (opt name arg result) (alist-cons 'file-system-mapping (specification->file-system-mapping arg #f) result))) (option '(#\n "dry-run") #f #f (lambda (opt name arg result) (alist-cons 'dry-run? #t result))) (option '(#\s "system") #t #f (lambda (opt name arg result) (alist-cons 'system arg (alist-delete 'system result eq?)))) %standard-build-options)) (define %default-options Alist of default option values . `((system . ,(%current-system)) (substitutes? . #t) (graft? . #t) (build-hook? . #t) (max-silent-time . 3600) (verbosity . 0) (image-size . ,(* 900 (expt 2 20))) (install-grub? . #t))) ;;; ;;; Entry point. ;;; (define (process-action action args opts) "Process ACTION, a sub-command, with the arguments are listed in ARGS. ACTION must be one of the sub-commands that takes an operating system declaration as an argument (a file name.) OPTS is the raw alist of options resulting from command-line parsing." (let* ((file (match args (() #f) ((x . _) x))) (system (assoc-ref opts 'system)) (os (if file (load* file %user-module #:on-error (assoc-ref opts 'on-error)) (leave (_ "no configuration file specified~%")))) (dry? (assoc-ref opts 'dry-run?)) (grub? (assoc-ref opts 'install-grub?)) (target (match args ((first second) second) (_ #f))) (device (and grub? (grub-configuration-device (operating-system-bootloader os))))) (with-store store (set-build-options-from-command-line store opts) (run-with-store store (mbegin %store-monad (set-guile-for-build (default-guile)) (case action ((extension-graph) (export-extension-graph os (current-output-port))) ((shepherd-graph) (export-shepherd-graph os (current-output-port))) (else (perform-action action os #:dry-run? dry? #:derivations-only? (assoc-ref opts 'derivations-only?) #:use-substitutes? (assoc-ref opts 'substitutes?) #:image-size (assoc-ref opts 'image-size) #:full-boot? (assoc-ref opts 'full-boot?) #:mappings (filter-map (match-lambda (('file-system-mapping . m) m) (_ #f)) opts) #:grub? grub? #:target target #:device device)))) #:system system)))) (define (process-command command args opts) "Process COMMAND, one of the 'guix system' sub-commands. ARGS is its argument list and OPTS is the option alist." (case command ((list-generations) ;; List generations. No need to connect to the daemon, etc. (let ((pattern (match args (() "") ((pattern) pattern) (x (leave (_ "wrong number of arguments~%")))))) (list-generations pattern))) (else (process-action command args opts)))) (define (guix-system . args) (define (parse-sub-command arg result) sub - command ARG and augment RESULT accordingly . (if (assoc-ref result 'action) (alist-cons 'argument arg result) (let ((action (string->symbol arg))) (case action ((build container vm vm-image disk-image reconfigure init extension-graph shepherd-graph list-generations) (alist-cons 'action action result)) (else (leave (_ "~a: unknown action~%") action)))))) (define (match-pair car) ;; Return a procedure that matches a pair with CAR. (match-lambda ((head . tail) (and (eq? car head) tail)) (_ #f))) (define (option-arguments opts) Extract the plain arguments from OPTS . (let* ((args (reverse (filter-map (match-pair 'argument) opts))) (count (length args)) (action (assoc-ref opts 'action))) (define (fail) (leave (_ "wrong number of arguments for action '~a'~%") action)) (unless action (format (current-error-port) (_ "guix system: missing command name~%")) (format (current-error-port) (_ "Try 'guix system --help' for more information.~%")) (exit 1)) (case action ((build container vm vm-image disk-image reconfigure) (unless (= count 1) (fail))) ((init) (unless (= count 2) (fail)))) args)) (with-error-handling (let* ((opts (parse-command-line args %options (list %default-options) #:argument-handler parse-sub-command)) (args (option-arguments opts)) (command (assoc-ref opts 'action))) (parameterize ((%graft? (assoc-ref opts 'graft?))) (process-command command args opts))))) ;;; system.scm ends here
null
https://raw.githubusercontent.com/jellelicht/guix/83cfc9414fca3ab57c949e18c1ceb375a179b59c/guix/scripts/system.scm
scheme
GNU Guix --- Functional package management for GNU This file is part of GNU Guix. you can redistribute it and/or modify it either version 3 of the License , or ( at your option) any later version. GNU Guix is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. Operating system declaration. Module in which the machine description file is loaded. Installation. Remove DEST if it exists to make sure that (1) we do not fail badly while trying to overwrite it (see <>), and Register ITEM; as a side-effect, it resets timestamps, etc. Explicitly use "TARGET/var/guix" as the state directory, to avoid reproducing the user's current settings; see <>. 'install-grub' completes (being a bit paranoid.) image, font, etc.) are not reclaimed. Make sure the target store exists. Copy items to the new store. non-root uses (useful for testing.) See <-devel/2015-05/msg00452.html>. background image and so on. Create a bunch of additional files. Reconfiguration. The system profile. Arrange to simply emit a warning if we cannot connect to the shepherd. Only load services that are either new or currently stopped. TO-LOAD. Here we assume that FILES are exactly those that were computed as part of the derivation that built OS, which is normally the case. The activation script may change $PATH, among others, so protect against that. Tell 'activate-current-system' what the new system is. against that. This is necessary to ensure that 'upgrade-shepherd-services' gets to see the right modules when it computes derivations with (gexp->derivation #:modules …). Finally, try to update system services. Graphs. Generations. XXX: race condition Action. DEVICE is IMAGE - SIZE it determines whether to For 'init' and 'reconfigure', always build GRUB.CFG, even if root. See <>. list of <shepherd-service> Options. Specifications of the command-line options. Entry point. List generations. No need to connect to the daemon, etc. Return a procedure that matches a pair with CAR. system.scm ends here
Copyright © 2014 , 2015 , 2016 < > Copyright © 2016 < > under the terms of the GNU General Public License as published by You should have received a copy of the GNU General Public License along with GNU . If not , see < / > . (define-module (guix scripts system) #:use-module (guix config) #:use-module (guix ui) #:use-module (guix store) #:use-module (guix grafts) #:use-module (guix gexp) #:use-module (guix derivations) #:use-module (guix packages) #:use-module (guix utils) #:use-module (guix monads) #:use-module (guix records) #:use-module (guix profiles) #:use-module (guix scripts) #:use-module (guix scripts build) #:use-module (guix graph) #:use-module (guix scripts graph) #:use-module (guix build utils) #:use-module (gnu build install) #:use-module (gnu system) #:use-module (gnu system file-systems) #:use-module (gnu system linux-container) #:use-module (gnu system vm) #:use-module (gnu system grub) #:use-module (gnu services) #:use-module (gnu services shepherd) #:use-module (gnu services herd) #:use-module (gnu packages grub) #:use-module (srfi srfi-1) #:use-module (srfi srfi-11) #:use-module (srfi srfi-19) #:use-module (srfi srfi-26) #:use-module (srfi srfi-34) #:use-module (srfi srfi-35) #:use-module (srfi srfi-37) #:use-module (ice-9 match) #:export (guix-system read-operating-system)) (define %user-module (make-user-module '((gnu system) (gnu services) (gnu system shadow)))) (define (read-operating-system file) "Read the operating-system declaration from FILE and return it." (load* file %user-module)) TODO : Factorize . (define references* (store-lift references)) (define topologically-sorted* (store-lift topologically-sorted)) (define* (copy-item item target #:key (log-port (current-error-port))) "Copy ITEM to the store under root directory TARGET and register it." (mlet* %store-monad ((refs (references* item))) (let ((dest (string-append target item)) (state (string-append target "/var/guix"))) (format log-port "copying '~a'...~%" item) ( 2 ) we end up with the right contents . (when (file-exists? dest) (delete-file-recursively dest)) (copy-recursively item dest #:log (%make-void-port "w")) (unless (register-path item #:prefix target #:state-directory state #:references refs) (leave (_ "failed to register '~a' under '~a'~%") item target)) (return #t)))) (define* (copy-closure item target #:key (log-port (current-error-port))) "Copy ITEM and all its dependencies to the store under root directory TARGET, and register them." (mlet* %store-monad ((refs (references* item)) (to-copy (topologically-sorted* (delete-duplicates (cons item refs) string=?)))) (sequence %store-monad (map (cut copy-item <> target #:log-port log-port) to-copy)))) (define (install-grub* grub.cfg device target) "This is a variant of 'install-grub' with error handling, lifted in %STORE-MONAD" (let* ((gc-root (string-append target %gc-roots-directory "/grub.cfg")) (temp-gc-root (string-append gc-root ".new")) (delete-file (lift1 delete-file %store-monad)) (make-symlink (lift2 switch-symlinks %store-monad)) (rename (lift2 rename-file %store-monad))) (mbegin %store-monad Prepare the symlink to GRUB.CFG to make sure that it 's a GC root when (make-symlink temp-gc-root grub.cfg) (munless (false-if-exception (install-grub grub.cfg device target)) (delete-file temp-gc-root) (leave (_ "failed to install GRUB on device '~a'~%") device)) Register GRUB.CFG as a GC root so that its dependencies ( background (rename temp-gc-root gc-root)))) (define* (install os-drv target #:key (log-port (current-output-port)) grub? grub.cfg device) "Copy the closure of GRUB.CFG, which includes the output of OS-DRV, to directory TARGET. TARGET must be an absolute directory name since that's what 'guix-register' expects. When GRUB? is true, install GRUB on DEVICE, using GRUB.CFG." (define (maybe-copy to-copy) (with-monad %store-monad (if (string=? target "/") (begin (warning (_ "initializing the current root file system~%")) (return #t)) (begin (mkdir-p (string-append target (%store-prefix))) (copy-closure to-copy target #:log-port log-port))))) Make sure is root - owned when running as root , but still allow (if (zero? (geteuid)) (chown target 0 0) (warning (_ "not running as 'root', so \ the ownership of '~a' may be incorrect!~%") target)) (chmod target #o755) (let ((os-dir (derivation->output-path os-drv)) (format (lift format %store-monad)) (populate (lift2 populate-root-file-system %store-monad))) (mbegin %store-monad Copy the closure of GRUB.CFG , which includes OS - DIR , GRUB 's (maybe-copy grub.cfg) (format log-port "populating '~a'...~%" target) (populate os-dir target) (mwhen grub? (install-grub* grub.cfg device target))))) (define %system-profile (string-append %state-directory "/profiles/system")) (define-syntax-rule (save-environment-excursion body ...) "Save the current environment variables, run BODY..., and restore them." (let ((env (environ))) (dynamic-wind (const #t) (lambda () body ...) (lambda () (environ env))))) (define-syntax-rule (save-load-path-excursion body ...) "Save the current values of '%load-path' and '%load-compiled-path', run BODY..., and restore them." (let ((path %load-path) (cpath %load-compiled-path)) (dynamic-wind (const #t) (lambda () body ...) (lambda () (set! %load-path path) (set! %load-compiled-path cpath))))) (define-syntax-rule (warn-on-system-error body ...) (catch 'system-error (lambda () body ...) (lambda (key proc format-string format-args errno . rest) (warning (_ "while talking to shepherd: ~a~%") (apply format #f format-string format-args)) (with-monad %store-monad (return #f))))) (define (upgrade-shepherd-services os) "Upgrade the Shepherd (PID 1) by unloading obsolete services and loading new services specified in OS and not currently running. This is currently very conservative in that it does not stop or unload any running service. Unloading or stopping the wrong service ('udev', say) could bring the system down." (define (essential? service) (memq service '(root shepherd))) (define new-services (service-parameters (fold-services (operating-system-services os) #:target-type shepherd-root-service-type))) (define new-service-names (map (compose first shepherd-service-provision) new-services)) (warn-on-system-error (let-values (((running stopped) (current-services))) (define to-load (remove (lambda (service) (memq (first (shepherd-service-provision service)) running)) new-services)) (define to-unload Unload services that are ( 1 ) no longer required , or ( 2 ) are in (remove essential? (append (remove (lambda (service) (memq service new-service-names)) (append running stopped)) (filter (lambda (service) (memq service stopped)) (map shepherd-service-canonical-name to-load))))) (for-each (lambda (unload) (info (_ "unloading service '~a'...~%") unload) (unload-service unload)) to-unload) (with-monad %store-monad (munless (null? to-load) (let ((to-load-names (map shepherd-service-canonical-name to-load)) (to-start (filter shepherd-service-auto-start? to-load))) (info (_ "loading new services:~{ ~a~}...~%") to-load-names) (mlet %store-monad ((files (mapm %store-monad shepherd-service-file to-load))) (load-services (map derivation->output-path files)) (for-each start-service (map shepherd-service-canonical-name to-start)) (return #t)))))))) (define* (switch-to-system os #:optional (profile %system-profile)) "Make a new generation of PROFILE pointing to the directory of OS, switch to it atomically, and then run OS's activation script." (mlet* %store-monad ((drv (operating-system-derivation os)) (script (operating-system-activation-script os))) (let* ((system (derivation->output-path drv)) (number (+ 1 (generation-number profile))) (generation (generation-file-name profile number))) (symlink system generation) (switch-symlinks profile generation) (format #t (_ "activating system...~%")) (save-environment-excursion (setenv "GUIX_NEW_SYSTEM" system) The activation script may modify ' % load - path ' & co. , so protect (save-load-path-excursion (primitive-load (derivation->output-path script)))) (upgrade-shepherd-services os)))) (define-syntax-rule (unless-file-not-found exp) (catch 'system-error (lambda () exp) (lambda args (if (= ENOENT (system-error-errno args)) #f (apply throw args))))) (define (seconds->string seconds) "Return a string representing the date for SECONDS." (let ((time (make-time time-utc 0 seconds))) (date->string (time-utc->date time) "~Y-~m-~d ~H:~M"))) (define* (previous-grub-entries #:optional (profile %system-profile)) "Return a list of 'menu-entry' for the generations of PROFILE." (define (system->grub-entry system number time) (unless-file-not-found (let* ((file (string-append system "/parameters")) (params (call-with-input-file file read-boot-parameters)) (label (boot-parameters-label params)) (root (boot-parameters-root-device params)) (kernel (boot-parameters-kernel params)) (kernel-arguments (boot-parameters-kernel-arguments params))) (menu-entry (label (string-append label " (#" (number->string number) ", " (seconds->string time) ")")) (linux kernel) (linux-arguments (cons* (string-append "--root=" root) #~(string-append "--system=" #$system) #~(string-append "--load=" #$system "/boot") kernel-arguments)) (initrd #~(string-append #$system "/initrd")))))) (let* ((numbers (generation-numbers profile)) (systems (map (cut generation-file-name profile <>) numbers)) (times (map (lambda (system) (unless-file-not-found (stat:mtime (lstat system)))) systems))) (filter-map system->grub-entry systems numbers times))) (define (service-node-label service) "Return a label to represent SERVICE." (let ((type (service-kind service)) (value (service-parameters service))) (string-append (symbol->string (service-type-name type)) (cond ((or (number? value) (symbol? value)) (string-append " " (object->string value))) ((string? value) (string-append " " value)) ((file-system? value) (string-append " " (file-system-mount-point value))) (else ""))))) (define (service-node-type services) "Return a node type for SERVICES. Since <service> instances are not self-contained (they express dependencies on service types, not on services), we have to create the 'edges' procedure dynamically as a function of the full list of services." (node-type (name "service") (description "the DAG of services") (identifier (lift1 object-address %store-monad)) (label service-node-label) (edges (lift1 (service-back-edges services) %store-monad)))) (define (shepherd-service-node-label service) "Return a label for a node representing a <shepherd-service>." (string-join (map symbol->string (shepherd-service-provision service)))) (define (shepherd-service-node-type services) "Return a node type for SERVICES, a list of <shepherd-service>." (node-type (name "shepherd-service") (description "the dependency graph of shepherd services") (identifier (lift1 shepherd-service-node-label %store-monad)) (label shepherd-service-node-label) (edges (lift1 (shepherd-service-back-edges services) %store-monad)))) (define* (display-system-generation number #:optional (profile %system-profile)) "Display a summary of system generation NUMBER in a human-readable format." (unless (zero? number) (let* ((generation (generation-file-name profile number)) (param-file (string-append generation "/parameters")) (params (call-with-input-file param-file read-boot-parameters)) (label (boot-parameters-label params)) (root (boot-parameters-root-device params)) (kernel (boot-parameters-kernel params))) (display-generation profile number) (format #t (_ " file name: ~a~%") generation) (format #t (_ " canonical file name: ~a~%") (readlink* generation)) TRANSLATORS : Please preserve the two - space indentation . (format #t (_ " label: ~a~%") label) (format #t (_ " root device: ~a~%") root) (format #t (_ " kernel: ~a~%") kernel)))) (define* (list-generations pattern #:optional (profile %system-profile)) "Display in a human-readable format all the system generations matching PATTERN, a string. When PATTERN is #f, display all the system generations." (raise (condition (&profile-not-found-error (profile profile))))) ((string-null? pattern) (for-each display-system-generation (profile-generations profile))) ((matching-generations pattern profile) => (lambda (numbers) (if (null-list? numbers) (exit 1) (leave-on-EPIPE (for-each display-system-generation numbers))))) (else (leave (_ "invalid syntax: ~a~%") pattern)))) (define* (system-derivation-for-action os action #:key image-size full-boot? mappings) "Return as a monadic value the derivation for OS according to ACTION." (case action ((build init reconfigure) (operating-system-derivation os)) ((container) (container-script os #:mappings mappings)) ((vm-image) (system-qemu-image os #:disk-image-size image-size)) ((vm) (system-qemu-image/shared-store-script os #:full-boot? full-boot? #:disk-image-size image-size #:mappings mappings)) ((disk-image) (system-disk-image os #:disk-image-size image-size)))) (define* (perform-action action os #:key grub? dry-run? derivations-only? use-substitutes? device target image-size full-boot? (mappings '())) is the size of the image to be built, for the 'vm-image' and 'disk-image' boot directly to the kernel or to the bootloader. When DERIVATIONS-ONLY? is true, print the derivation file name(s) without building anything." (define println (cut format #t "~a~%" <>)) (mlet* %store-monad ((sys (system-derivation-for-action os action #:image-size image-size #:full-boot? full-boot? #:mappings mappings)) (grub (package->derivation grub)) (grub.cfg (if (eq? 'container action) (return #f) (operating-system-grub.cfg os (if (eq? 'init action) '() (previous-grub-entries))))) --no - grub is passed , because GRUB.CFG because we then use it as a GC (drvs -> (if (memq action '(init reconfigure)) (if grub? (list sys grub.cfg grub) (list sys grub.cfg)) (list sys))) (% (if derivations-only? (return (for-each (compose println derivation-file-name) drvs)) (maybe-build drvs #:dry-run? dry-run? #:use-substitutes? use-substitutes?)))) (if (or dry-run? derivations-only?) (return #f) (begin (for-each (compose println derivation->output-path) drvs) Make sure GRUB is accessible . (when grub? (let ((prefix (derivation->output-path grub))) (setenv "PATH" (string-append prefix "/bin:" prefix "/sbin:" (getenv "PATH"))))) (case action ((reconfigure) (mbegin %store-monad (switch-to-system os) (mwhen grub? (install-grub* (derivation->output-path grub.cfg) device "/")))) ((init) (newline) (format #t (_ "initializing operating system under '~a'...~%") target) (install sys (canonicalize-path target) #:grub? grub? #:grub.cfg (derivation->output-path grub.cfg) #:device device)) (else All we had to do was to build SYS . (return (derivation->output-path sys)))))))) (define (export-extension-graph os port) "Export the service extension graph of OS to PORT." (let* ((services (operating-system-services os)) (system (find (lambda (service) (eq? (service-kind service) system-service-type)) services))) (export-graph (list system) (current-output-port) #:node-type (service-node-type services) #:reverse-edges? #t))) (define (export-shepherd-graph os port) "Export the graph of shepherd services of OS to PORT." (let* ((services (operating-system-services os)) (pid1 (fold-services services #:target-type shepherd-root-service-type)) (sinks (filter (lambda (service) (null? (shepherd-service-requirement service))) shepherds))) (export-graph sinks (current-output-port) #:node-type (shepherd-service-node-type shepherds) #:reverse-edges? #t))) (define (show-help) (display (_ "Usage: guix system [OPTION] ACTION [FILE] Build the operating system declared in FILE according to ACTION.\n")) (newline) (display (_ "The valid values for ACTION are:\n")) (newline) (display (_ "\ reconfigure switch to a new operating system configuration\n")) (display (_ "\ list-generations list the system generations\n")) (display (_ "\ build build the operating system without installing anything\n")) (display (_ "\ container build a container that shares the host's store\n")) (display (_ "\ vm build a virtual machine image that shares the host's store\n")) (display (_ "\ vm-image build a freestanding virtual machine image\n")) (display (_ "\ disk-image build a disk image, suitable for a USB stick\n")) (display (_ "\ init initialize a root file system to run GNU\n")) (display (_ "\ extension-graph emit the service extension graph in Dot format\n")) (display (_ "\ shepherd-graph emit the graph of shepherd services in Dot format\n")) (show-build-options-help) (display (_ " -d, --derivation return the derivation of the given system")) (display (_ " --on-error=STRATEGY apply STRATEGY when an error occurs while reading FILE")) (display (_ " --image-size=SIZE for 'vm-image', produce an image of SIZE")) (display (_ " --no-grub for 'init', do not install GRUB")) (display (_ " --share=SPEC for 'vm', share host file system according to SPEC")) (display (_ " --expose=SPEC for 'vm', expose host file system according to SPEC")) (display (_ " --full-boot for 'vm', make a full boot sequence")) (newline) (display (_ " -h, --help display this help and exit")) (display (_ " -V, --version display version information and exit")) (newline) (show-bug-report-information)) (define %options (cons* (option '(#\h "help") #f #f (lambda args (show-help) (exit 0))) (option '(#\V "version") #f #f (lambda args (show-version-and-exit "guix system"))) (option '(#\d "derivation") #f #f (lambda (opt name arg result) (alist-cons 'derivations-only? #t result))) (option '("on-error") #t #f (lambda (opt name arg result) (alist-cons 'on-error (string->symbol arg) result))) (option '("image-size") #t #f (lambda (opt name arg result) (alist-cons 'image-size (size->number arg) result))) (option '("no-grub") #f #f (lambda (opt name arg result) (alist-cons 'install-grub? #f result))) (option '("full-boot") #f #f (lambda (opt name arg result) (alist-cons 'full-boot? #t result))) (option '("share") #t #f (lambda (opt name arg result) (alist-cons 'file-system-mapping (specification->file-system-mapping arg #t) result))) (option '("expose") #t #f (lambda (opt name arg result) (alist-cons 'file-system-mapping (specification->file-system-mapping arg #f) result))) (option '(#\n "dry-run") #f #f (lambda (opt name arg result) (alist-cons 'dry-run? #t result))) (option '(#\s "system") #t #f (lambda (opt name arg result) (alist-cons 'system arg (alist-delete 'system result eq?)))) %standard-build-options)) (define %default-options Alist of default option values . `((system . ,(%current-system)) (substitutes? . #t) (graft? . #t) (build-hook? . #t) (max-silent-time . 3600) (verbosity . 0) (image-size . ,(* 900 (expt 2 20))) (install-grub? . #t))) (define (process-action action args opts) "Process ACTION, a sub-command, with the arguments are listed in ARGS. ACTION must be one of the sub-commands that takes an operating system declaration as an argument (a file name.) OPTS is the raw alist of options resulting from command-line parsing." (let* ((file (match args (() #f) ((x . _) x))) (system (assoc-ref opts 'system)) (os (if file (load* file %user-module #:on-error (assoc-ref opts 'on-error)) (leave (_ "no configuration file specified~%")))) (dry? (assoc-ref opts 'dry-run?)) (grub? (assoc-ref opts 'install-grub?)) (target (match args ((first second) second) (_ #f))) (device (and grub? (grub-configuration-device (operating-system-bootloader os))))) (with-store store (set-build-options-from-command-line store opts) (run-with-store store (mbegin %store-monad (set-guile-for-build (default-guile)) (case action ((extension-graph) (export-extension-graph os (current-output-port))) ((shepherd-graph) (export-shepherd-graph os (current-output-port))) (else (perform-action action os #:dry-run? dry? #:derivations-only? (assoc-ref opts 'derivations-only?) #:use-substitutes? (assoc-ref opts 'substitutes?) #:image-size (assoc-ref opts 'image-size) #:full-boot? (assoc-ref opts 'full-boot?) #:mappings (filter-map (match-lambda (('file-system-mapping . m) m) (_ #f)) opts) #:grub? grub? #:target target #:device device)))) #:system system)))) (define (process-command command args opts) "Process COMMAND, one of the 'guix system' sub-commands. ARGS is its argument list and OPTS is the option alist." (case command ((list-generations) (let ((pattern (match args (() "") ((pattern) pattern) (x (leave (_ "wrong number of arguments~%")))))) (list-generations pattern))) (else (process-action command args opts)))) (define (guix-system . args) (define (parse-sub-command arg result) sub - command ARG and augment RESULT accordingly . (if (assoc-ref result 'action) (alist-cons 'argument arg result) (let ((action (string->symbol arg))) (case action ((build container vm vm-image disk-image reconfigure init extension-graph shepherd-graph list-generations) (alist-cons 'action action result)) (else (leave (_ "~a: unknown action~%") action)))))) (define (match-pair car) (match-lambda ((head . tail) (and (eq? car head) tail)) (_ #f))) (define (option-arguments opts) Extract the plain arguments from OPTS . (let* ((args (reverse (filter-map (match-pair 'argument) opts))) (count (length args)) (action (assoc-ref opts 'action))) (define (fail) (leave (_ "wrong number of arguments for action '~a'~%") action)) (unless action (format (current-error-port) (_ "guix system: missing command name~%")) (format (current-error-port) (_ "Try 'guix system --help' for more information.~%")) (exit 1)) (case action ((build container vm vm-image disk-image reconfigure) (unless (= count 1) (fail))) ((init) (unless (= count 2) (fail)))) args)) (with-error-handling (let* ((opts (parse-command-line args %options (list %default-options) #:argument-handler parse-sub-command)) (args (option-arguments opts)) (command (assoc-ref opts 'action))) (parameterize ((%graft? (assoc-ref opts 'graft?))) (process-command command args opts)))))
9c0289628167cbebbaae151eb1d72b384babba8aa2300d0432967467492a57c0
avsm/eeww
test.ml
--------------------------------------------------------------------------- Copyright ( c ) 2016 . All rights reserved . Distributed under the ISC license , see terms at the end of the file . % % NAME%% % % --------------------------------------------------------------------------- Copyright (c) 2016 KC Sivaramakrishnan. All rights reserved. Distributed under the ISC license, see terms at the end of the file. %%NAME%% %%VERSION%% ---------------------------------------------------------------------------*) # # # # # # # # Copyright ( c ) 2017 , < > # # # # # # # # ######## Copyright (c) 2017, Nicolas ASSOUAD <> ######## *) --------------------------------------------------------------------------- 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 . --------------------------------------------------------------------------- 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. ---------------------------------------------------------------------------*) let nb_iter = 100_000 let assert_kcas ref expected_v = let present_v = Kcas.get ref in assert (present_v == expected_v) module Barrier = struct type t = { counter : int Atomic.t; total : int } let make total = { counter = Atomic.make 0; total } let await { counter; total } = Atomic.incr counter; while Atomic.get counter < total do () done end test 1 let test_set () = let a = Kcas.ref 0 in assert_kcas a 0; Kcas.set a 1; assert_kcas a 1 test 2 let thread1 barrier test_finished (a1, a2) () = let c1 = [ Kcas.mk_cas a1 0 1; Kcas.mk_cas a2 0 1 ] in let c2 = [ Kcas.mk_cas a1 1 0; Kcas.mk_cas a2 1 0 ] in Barrier.await barrier; for _ = 1 to nb_iter do assert_kcas a1 0; assert_kcas a2 0; let out1 = Kcas.kCAS c1 in assert out1; assert_kcas a1 1; assert_kcas a2 1; let out2 = Kcas.kCAS c2 in assert out2 done; Atomic.set test_finished true let thread2 barrier test_finished (a1, a2) () = let c1 = [ Kcas.mk_cas a1 1 0; Kcas.mk_cas a2 0 1 ] in let c2 = [ Kcas.mk_cas a1 0 1; Kcas.mk_cas a2 1 0 ] in Barrier.await barrier; while not (Atomic.get test_finished) do let out1 = Kcas.kCAS c1 in let out2 = Kcas.kCAS c2 in assert (not out1); assert (not out2) done let thread3 barrier test_finished (a1, a2) () = let c1 = [ Kcas.mk_cas a1 0 1; Kcas.mk_cas a2 1 0 ] in let c2 = [ Kcas.mk_cas a1 1 0; Kcas.mk_cas a2 0 1 ] in Barrier.await barrier; while not (Atomic.get test_finished) do let out1 = Kcas.kCAS c1 in let out2 = Kcas.kCAS c2 in assert (not out1); assert (not out2) done let test_casn () = let barrier = Barrier.make 3 in let test_finished = Atomic.make false in let a1 = Kcas.ref 0 in let a2 = Kcas.ref 0 in let domains = [ thread1; thread2; thread3 ] in List.map (fun f -> Domain.spawn (f barrier test_finished (a1, a2))) domains |> List.iter Domain.join test 3 let thread4 barrier test_finished (a1, a2) () = Barrier.await barrier; for i = 0 to nb_iter do let c = [ Kcas.mk_cas a1 i (i + 1); Kcas.mk_cas a2 i (i + 1) ] in assert (Kcas.kCAS c) done; Atomic.set test_finished true let thread5 barrier test_finished (a1, a2) () = Barrier.await barrier; while not (Atomic.get test_finished) do let a = Kcas.get a1 in let b = Kcas.get a2 in assert (a <= b) done let test_read_casn () = let barrier = Barrier.make 2 in let test_finished = Atomic.make false in let a1 = Kcas.ref 0 in let a2 = Kcas.ref 0 in let domains = [ thread4; thread5 ] in List.map (fun f -> Domain.spawn (f barrier test_finished (a1, a2))) domains |> List.iter Domain.join test 4 let make_ref n = let rec loop n out = if n > 0 then loop (n - 1) (Kcas.ref 0 :: out) else out in loop n [] let make_kcas0 r_l = let rec loop r_l out = match r_l with h :: t -> loop t (Kcas.mk_cas h 0 1 :: out) | [] -> out in loop r_l [] let make_kcas1 r_l = let rec loop r_l out = match r_l with h :: t -> loop t (Kcas.mk_cas h 1 0 :: out) | [] -> out in loop r_l [] let test_stress n nb_loop = let r_l = make_ref n in let kcas0 = make_kcas0 r_l in let kcas1 = make_kcas1 r_l in for _ = 1 to nb_loop do assert (Kcas.kCAS kcas0); assert (Kcas.kCAS kcas1) done let () = test_set (); test_casn (); test_read_casn (); test_stress 1000 10000 # # # # #### *)
null
https://raw.githubusercontent.com/avsm/eeww/a316137bc7550870c9fd0c6a907d87e9d9810ae4/lib/kcas/test/test.ml
ocaml
--------------------------------------------------------------------------- Copyright ( c ) 2016 . All rights reserved . Distributed under the ISC license , see terms at the end of the file . % % NAME%% % % --------------------------------------------------------------------------- Copyright (c) 2016 KC Sivaramakrishnan. All rights reserved. Distributed under the ISC license, see terms at the end of the file. %%NAME%% %%VERSION%% ---------------------------------------------------------------------------*) # # # # # # # # Copyright ( c ) 2017 , < > # # # # # # # # ######## Copyright (c) 2017, Nicolas ASSOUAD <> ######## *) --------------------------------------------------------------------------- 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 . --------------------------------------------------------------------------- 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. ---------------------------------------------------------------------------*) let nb_iter = 100_000 let assert_kcas ref expected_v = let present_v = Kcas.get ref in assert (present_v == expected_v) module Barrier = struct type t = { counter : int Atomic.t; total : int } let make total = { counter = Atomic.make 0; total } let await { counter; total } = Atomic.incr counter; while Atomic.get counter < total do () done end test 1 let test_set () = let a = Kcas.ref 0 in assert_kcas a 0; Kcas.set a 1; assert_kcas a 1 test 2 let thread1 barrier test_finished (a1, a2) () = let c1 = [ Kcas.mk_cas a1 0 1; Kcas.mk_cas a2 0 1 ] in let c2 = [ Kcas.mk_cas a1 1 0; Kcas.mk_cas a2 1 0 ] in Barrier.await barrier; for _ = 1 to nb_iter do assert_kcas a1 0; assert_kcas a2 0; let out1 = Kcas.kCAS c1 in assert out1; assert_kcas a1 1; assert_kcas a2 1; let out2 = Kcas.kCAS c2 in assert out2 done; Atomic.set test_finished true let thread2 barrier test_finished (a1, a2) () = let c1 = [ Kcas.mk_cas a1 1 0; Kcas.mk_cas a2 0 1 ] in let c2 = [ Kcas.mk_cas a1 0 1; Kcas.mk_cas a2 1 0 ] in Barrier.await barrier; while not (Atomic.get test_finished) do let out1 = Kcas.kCAS c1 in let out2 = Kcas.kCAS c2 in assert (not out1); assert (not out2) done let thread3 barrier test_finished (a1, a2) () = let c1 = [ Kcas.mk_cas a1 0 1; Kcas.mk_cas a2 1 0 ] in let c2 = [ Kcas.mk_cas a1 1 0; Kcas.mk_cas a2 0 1 ] in Barrier.await barrier; while not (Atomic.get test_finished) do let out1 = Kcas.kCAS c1 in let out2 = Kcas.kCAS c2 in assert (not out1); assert (not out2) done let test_casn () = let barrier = Barrier.make 3 in let test_finished = Atomic.make false in let a1 = Kcas.ref 0 in let a2 = Kcas.ref 0 in let domains = [ thread1; thread2; thread3 ] in List.map (fun f -> Domain.spawn (f barrier test_finished (a1, a2))) domains |> List.iter Domain.join test 3 let thread4 barrier test_finished (a1, a2) () = Barrier.await barrier; for i = 0 to nb_iter do let c = [ Kcas.mk_cas a1 i (i + 1); Kcas.mk_cas a2 i (i + 1) ] in assert (Kcas.kCAS c) done; Atomic.set test_finished true let thread5 barrier test_finished (a1, a2) () = Barrier.await barrier; while not (Atomic.get test_finished) do let a = Kcas.get a1 in let b = Kcas.get a2 in assert (a <= b) done let test_read_casn () = let barrier = Barrier.make 2 in let test_finished = Atomic.make false in let a1 = Kcas.ref 0 in let a2 = Kcas.ref 0 in let domains = [ thread4; thread5 ] in List.map (fun f -> Domain.spawn (f barrier test_finished (a1, a2))) domains |> List.iter Domain.join test 4 let make_ref n = let rec loop n out = if n > 0 then loop (n - 1) (Kcas.ref 0 :: out) else out in loop n [] let make_kcas0 r_l = let rec loop r_l out = match r_l with h :: t -> loop t (Kcas.mk_cas h 0 1 :: out) | [] -> out in loop r_l [] let make_kcas1 r_l = let rec loop r_l out = match r_l with h :: t -> loop t (Kcas.mk_cas h 1 0 :: out) | [] -> out in loop r_l [] let test_stress n nb_loop = let r_l = make_ref n in let kcas0 = make_kcas0 r_l in let kcas1 = make_kcas1 r_l in for _ = 1 to nb_loop do assert (Kcas.kCAS kcas0); assert (Kcas.kCAS kcas1) done let () = test_set (); test_casn (); test_read_casn (); test_stress 1000 10000 # # # # #### *)
0fd1427b6c02d55630a12968e6e7ee72b38862556c9ff20ce9af6fe95fd1cd31
cgoldammer/chess-database-backend
SpeedTest.hs
{-# LANGUAGE OverloadedStrings, ScopedTypeVariables, TypeFamilies #-} module Main where import Services.Helpers import Services.Service import qualified Test.Helpers as TH import Database.Esqueleto hiding (get) import Services.DatabaseHelpers import Database.Persist hiding ((==.)) import Database.Persist.Sql hiding ((==.)) import Services.Types main :: IO () main = do (players, evals) <- TH.inBackend (connString dbName) dataResults let summ = summarizeEvals players evals print $ length summ getTestEvals :: TH.DataAction [EvalResult] getTestEvals = do er <- select $ from $ \(me, g) -> do where_ $ (me^.MoveEvalGameId ==. g^.GameId) return (me, g) return er dbName :: String dbName = "prod" dataResults :: TH.DataAction ([Entity Player], [EvalResult]) dataResults = do dbPlayers :: [Entity Player] <- selectList [] [] evals <- getTestEvals return (dbPlayers, evals)
null
https://raw.githubusercontent.com/cgoldammer/chess-database-backend/03b6b8d3072941e7da395eb4371ece588093e140/apps/SpeedTest.hs
haskell
# LANGUAGE OverloadedStrings, ScopedTypeVariables, TypeFamilies #
module Main where import Services.Helpers import Services.Service import qualified Test.Helpers as TH import Database.Esqueleto hiding (get) import Services.DatabaseHelpers import Database.Persist hiding ((==.)) import Database.Persist.Sql hiding ((==.)) import Services.Types main :: IO () main = do (players, evals) <- TH.inBackend (connString dbName) dataResults let summ = summarizeEvals players evals print $ length summ getTestEvals :: TH.DataAction [EvalResult] getTestEvals = do er <- select $ from $ \(me, g) -> do where_ $ (me^.MoveEvalGameId ==. g^.GameId) return (me, g) return er dbName :: String dbName = "prod" dataResults :: TH.DataAction ([Entity Player], [EvalResult]) dataResults = do dbPlayers :: [Entity Player] <- selectList [] [] evals <- getTestEvals return (dbPlayers, evals)
9fcca9c171b9c6321afa4a69d7074ca747adf2ff25a8c32ea889d20c27df3d89
LexiFi/gen_js_api
number.mli
type t = private Ojs.t val toString: t -> ?radix:int -> unit -> float [@@js.call] val toFixed: t -> ?fractionDigits:int -> unit -> float [@@js.call] val toExponential: t -> ?fractionDigits:int -> unit -> float [@@js.call] val toPrecision: t -> ?precision:int -> unit -> float [@@js.call] val valueOf: t -> float [@@js.call] (* scoped *) module [@js.scope "Number"] Scoped : sig val create: 'any -> t [@@js.create] val invoke: 'any -> float [@@js.invoke] val min_value: float [@@js.global "MIN_VALUE"] val max_value: float [@@js.global "MAX_VALUE"] val nan: float [@@js.global "NaN"] val negative_infinity: float [@@js.global "NEGATIVE_INFINITY"] val positive_infinity: float [@@js.global "POSITIVE_INFINITY"] end (* non-scoped *) module Static : sig type number = t type t = private Ojs.t val create: t -> 'any -> number [@@js.apply_newable] val apply: t -> 'any -> float [@@js.apply] val min_value: t -> float [@@js.get "MIN_VALUE"] val max_value: t -> float [@@js.get "MAX_VALUE"] val nan: t -> float [@@js.get "NaN"] val negative_infinity: t -> float [@@js.get "NEGATIVE_INFINITY"] val positive_infinity: t -> float [@@js.get "POSITIVE_INFINITY"] end val number: Static.t [@@js.global "Number"]
null
https://raw.githubusercontent.com/LexiFi/gen_js_api/69b7d0a6f79adae07b181e59b2e2053b7528143a/node-test/bindings/number.mli
ocaml
scoped non-scoped
type t = private Ojs.t val toString: t -> ?radix:int -> unit -> float [@@js.call] val toFixed: t -> ?fractionDigits:int -> unit -> float [@@js.call] val toExponential: t -> ?fractionDigits:int -> unit -> float [@@js.call] val toPrecision: t -> ?precision:int -> unit -> float [@@js.call] val valueOf: t -> float [@@js.call] module [@js.scope "Number"] Scoped : sig val create: 'any -> t [@@js.create] val invoke: 'any -> float [@@js.invoke] val min_value: float [@@js.global "MIN_VALUE"] val max_value: float [@@js.global "MAX_VALUE"] val nan: float [@@js.global "NaN"] val negative_infinity: float [@@js.global "NEGATIVE_INFINITY"] val positive_infinity: float [@@js.global "POSITIVE_INFINITY"] end module Static : sig type number = t type t = private Ojs.t val create: t -> 'any -> number [@@js.apply_newable] val apply: t -> 'any -> float [@@js.apply] val min_value: t -> float [@@js.get "MIN_VALUE"] val max_value: t -> float [@@js.get "MAX_VALUE"] val nan: t -> float [@@js.get "NaN"] val negative_infinity: t -> float [@@js.get "NEGATIVE_INFINITY"] val positive_infinity: t -> float [@@js.get "POSITIVE_INFINITY"] end val number: Static.t [@@js.global "Number"]
b4fff3bead98ba30139a23253905a03ea68fc85e7edff07710dd48684fbb47d9
tfausak/burrito
Burrito.hs
| Burrito is a library for parsing and rendering URI templates . -- According to [ RFC 6570]( / html / rfc6570 ): " A URI -- Template is a compact sequence of characters for describing a range of -- Uniform Resource Identifiers through variable expansion." Burrito implements URI templates according to the specification in that RFC . -- The term " uniform resource identifiers " ( URI ) is often used interchangeably with other related terms like " internationalized resource identifier " ( IRI ) , " uniform resource locator " ( URL ) , and " uniform resource name " ( ) . Burrito -- can be used for all of these. If you want to get technical, its input must be a valid IRI and its output will be a valid URI or URN . -- Although Burrito is primarily intended to be used with HTTP and HTTPS URIs , -- it should work with other schemes as well. -- -- If you're not already familiar with URI templates, I recommend reading the -- overview of the RFC. It's short, to the point, and easy to understand. -- -- Assuming you're familiar with URI templates, here's a simple example to show you how works : -- > > > import -- >>> let Just template = parse "{?query}" -- >>> expand [("query", stringValue "chorizo")] template -- "" -- -- In short, use @parse@ to parse templates and @expand@ to render them. module Burrito ( Parse.parse, Template.render, Expand.expand, Expand.expandWith, Match.match, TH.uriTemplate, TH.expandTH, Template.Template, Value.Value, stringValue, listValue, dictionaryValue, ) where import qualified Burrito.Internal.Expand as Expand import qualified Burrito.Internal.Match as Match import qualified Burrito.Internal.Parse as Parse import qualified Burrito.Internal.TH as TH import qualified Burrito.Internal.Type.Template as Template import qualified Burrito.Internal.Type.Value as Value import qualified Data.Bifunctor as Bifunctor import qualified Data.Map as Map import qualified Data.Text as Text -- | Constructs a string value. stringValue :: String -> Value.Value stringValue = Value.String . Text.pack -- | Constructs a list value. listValue :: [String] -> Value.Value listValue = Value.List . fmap Text.pack -- | Constructs a dictionary value. dictionaryValue :: [(String, String)] -> Value.Value dictionaryValue = Value.Dictionary . Map.fromList . fmap (Bifunctor.bimap Text.pack Text.pack)
null
https://raw.githubusercontent.com/tfausak/burrito/e4475f6bc44862a36464bd8904296d68d995ead2/source/library/Burrito.hs
haskell
Template is a compact sequence of characters for describing a range of Uniform Resource Identifiers through variable expansion." Burrito can be used for all of these. If you want to get technical, its input must it should work with other schemes as well. If you're not already familiar with URI templates, I recommend reading the overview of the RFC. It's short, to the point, and easy to understand. Assuming you're familiar with URI templates, here's a simple example to show >>> let Just template = parse "{?query}" >>> expand [("query", stringValue "chorizo")] template "" In short, use @parse@ to parse templates and @expand@ to render them. | Constructs a string value. | Constructs a list value. | Constructs a dictionary value.
| Burrito is a library for parsing and rendering URI templates . According to [ RFC 6570]( / html / rfc6570 ): " A URI implements URI templates according to the specification in that RFC . The term " uniform resource identifiers " ( URI ) is often used interchangeably with other related terms like " internationalized resource identifier " ( IRI ) , " uniform resource locator " ( URL ) , and " uniform resource name " ( ) . Burrito be a valid IRI and its output will be a valid URI or URN . Although Burrito is primarily intended to be used with HTTP and HTTPS URIs , you how works : > > > import module Burrito ( Parse.parse, Template.render, Expand.expand, Expand.expandWith, Match.match, TH.uriTemplate, TH.expandTH, Template.Template, Value.Value, stringValue, listValue, dictionaryValue, ) where import qualified Burrito.Internal.Expand as Expand import qualified Burrito.Internal.Match as Match import qualified Burrito.Internal.Parse as Parse import qualified Burrito.Internal.TH as TH import qualified Burrito.Internal.Type.Template as Template import qualified Burrito.Internal.Type.Value as Value import qualified Data.Bifunctor as Bifunctor import qualified Data.Map as Map import qualified Data.Text as Text stringValue :: String -> Value.Value stringValue = Value.String . Text.pack listValue :: [String] -> Value.Value listValue = Value.List . fmap Text.pack dictionaryValue :: [(String, String)] -> Value.Value dictionaryValue = Value.Dictionary . Map.fromList . fmap (Bifunctor.bimap Text.pack Text.pack)
5bdc70744e9db55917f46fe5bfd350874eaec6b3fdd09df2893bb172463d9de7
gergoerdi/tandoori
let-monoenv.hs
undefined = undefined toUpper :: Char -> Char toUpper = undefined foo x = let y = toUpper x in True
null
https://raw.githubusercontent.com/gergoerdi/tandoori/515142ce76b96efa75d7044c9077d85394585556/input/let-monoenv.hs
haskell
undefined = undefined toUpper :: Char -> Char toUpper = undefined foo x = let y = toUpper x in True
b09c71b65ac08b506a10c3cce8fbe767f087347e86a02e2f95ddf8ee20148ee2
meamy/feynman
Core.hs
{-# LANGUAGE Rank2Types #-} module Feynman.Core where import Data.List import Control.Monad import Data.Set (Set) import qualified Data.Set as Set import Data.Map (Map) import qualified Data.Map as Map import Feynman.Algebra.Base type ID = String type Loc = Int {- Phase angles -} Phase angles either have the form pi*(a/2^b ) reduced mod 2 , or theta data Angle = Discrete DMod2 | Continuous Double deriving (Eq, Ord) apply :: (forall a. Num a => a -> a) -> Angle -> Angle apply f (Discrete a) = Discrete $ f a apply f (Continuous a) = Continuous $ f a apply2 :: (forall a. Num a => a -> a -> a) -> Angle -> Angle -> Angle apply2 f a b = case (a,b) of (Discrete a, Discrete b) -> Discrete $ f a b (Discrete a, Continuous b) -> Continuous $ f (toDouble a) b (Continuous a, Discrete b) -> Continuous $ f a (toDouble b) (Continuous a, Continuous b) -> Continuous $ f a b where toDouble = fromRational . toRational discretize :: Angle -> DyadicRational discretize (Discrete a) = unpack a discretize (Continuous a) = toDyadic a Phase of pi*(a/2^b ) reduced mod 2 dyadicPhase :: DyadicRational -> Angle dyadicPhase = Discrete . fromDyadic -- Phase of theta continuousPhase :: Double -> Angle continuousPhase = Continuous instance Show Angle where show (Discrete a) | a == 0 = show a | a == 1 = "pi" | otherwise = "pi*" ++ show a show (Continuous a) = show a instance Num Angle where (+) = apply2 (+) (-) = apply2 (-) (*) = apply2 (*) negate = apply negate abs = apply abs signum = apply signum fromInteger = Discrete . fromInteger instance Abelian Angle where power i (Discrete a) = Discrete $ power i a power i (Continuous a) = Continuous $ (fromInteger i) * a instance Periodic Angle where order (Discrete a) = order a order (Continuous _) = 0 {- Circuits -} data Primitive = H ID | X ID | Y ID | Z ID | CNOT ID ID | CZ ID ID | S ID | Sinv ID | T ID | Tinv ID | Swap ID ID | Rz Angle ID | Rx Angle ID | Ry Angle ID | Uninterp ID [ID] deriving (Eq) data Stmt = Gate Primitive | Seq [Stmt] | Call ID [ID] | Repeat Int Stmt data Decl = Decl { name :: ID, params :: [ID], body :: Stmt } data Circuit = Circuit { qubits :: [ID], inputs :: Set ID, decls :: [Decl] } foldCirc f b c = foldl (foldStmt f . body) b (decls c) foldStmt f (Seq st) b = f (Seq st) (foldr (foldStmt f) b st) foldStmt f (Repeat i st) b = f (Repeat i st) (foldStmt f st b) foldStmt f s b = f s b getArgs :: Primitive -> [ID] getArgs gate = case gate of H x -> [x] X x -> [x] Y x -> [x] Z x -> [x] CNOT x y -> [x,y] CZ x y -> [x,y] S x -> [x] Sinv x -> [x] T x -> [x] Tinv x -> [x] Swap x y -> [x,y] Rz theta x -> [x] Rx theta x -> [x] Ry theta x -> [x] Uninterp s xs -> xs -- Transformations daggerGate :: Primitive -> Primitive daggerGate x = case x of H _ -> x X _ -> x Y _ -> x -- WARNING: this is incorrect Z _ -> x CNOT _ _ -> x CZ _ _ -> x S x -> Sinv x Sinv x -> S x T x -> Tinv x Tinv x -> T x Swap _ _ -> x Rz theta x -> Rz (-theta) x Rx theta x -> Rx (-theta) x Ry theta x -> Ry (-theta) x Uninterp s xs -> Uninterp (s ++ "*") xs dagger :: [Primitive] -> [Primitive] dagger = reverse . map daggerGate substGate :: (ID -> ID) -> Primitive -> Primitive substGate f gate = case gate of H x -> H $ f x X x -> X $ f x Y x -> Y $ f x Z x -> Z $ f x CNOT x y -> CNOT (f x) (f y) CZ x y -> CZ (f x) (f y) S x -> S $ f x Sinv x -> Sinv $ f x T x -> T $ f x Tinv x -> Tinv $ f x Swap x y -> Swap (f x) (f y) Rz theta x -> Rz theta (f x) Rx theta x -> Rx theta (f x) Ry theta x -> Ry theta (f x) Uninterp s xs -> Uninterp s (map f xs) subst :: (ID -> ID) -> [Primitive] -> [Primitive] subst f = map (substGate f) ids :: [Primitive] -> [ID] ids = Set.toList . foldr f Set.empty where f gate set = foldr Set.insert set (idsGate gate) idsGate gate = case gate of H x -> [x] X x -> [x] Y x -> [x] Z x -> [x] CNOT x y -> [x,y] CZ x y -> [x,y] S x -> [x] Sinv x -> [x] T x -> [x] Tinv x -> [x] Swap x y -> [x,y] Rz theta x -> [x] Rx theta x -> [x] Ry theta x -> [x] Uninterp s xs -> xs converge :: Eq a => (a -> a) -> a -> a converge f a | a' == a = a' | otherwise = converge f a' where a' = f a simplifyPrimitive :: [Primitive] -> [Primitive] simplifyPrimitive circ = let circ' = zip circ [0..] simplify circ = let erasures = snd $ foldl' f (Map.empty, Set.empty) circ f (frontier, erasures) (gate, uid) = let args@(x:xs) = getArgs gate checkDagger (gate', uid') | gate' == daggerGate gate = Just (gate, uid') | otherwise = Nothing checkArg (gate, uid) q = do (_, uid') <- Map.lookup q frontier if uid' == uid then Just (gate, uid) else Nothing in case Map.lookup x frontier >>= checkDagger >>= (\g -> foldM checkArg g xs) of Just (_, uid') -> (foldr Map.delete frontier args, foldr Set.insert erasures [uid, uid']) Nothing -> (foldr (\q -> Map.insert q (gate, uid)) frontier args, erasures) in filter (\(_, uid) -> not $ Set.member uid erasures) circ in fst . unzip . (converge simplify) $ circ' -- Removes all swap gates by re-indexing removeSwaps :: [Primitive] -> [Primitive] removeSwaps = reverse . go (Map.empty, []) where get ctx q = Map.findWithDefault q q ctx go (ctx, acc) [] = acc go (ctx, acc) (x:xs) = case x of Swap q1 q2 -> let (q1', q2') = (get ctx q1, get ctx q2) in go (Map.insert q1 q2' $ Map.insert q2 q1' ctx, acc) xs _ -> go (ctx, (substGate (get ctx) x):acc) xs Builtin circuits cs :: ID -> ID -> [Primitive] cs x y = [T x, T y, CNOT x y, Tinv y, CNOT x y] cz :: ID -> ID -> [Primitive] cz x y = [S x, S y, CNOT x y, Sinv y, CNOT x y] ccx :: ID -> ID -> ID -> [Primitive] ccx x y z = [H z] ++ ccz x y z ++ [H z] ccz :: ID -> ID -> ID -> [Primitive] ccz x y z = [T x, T y, T z, CNOT x y, CNOT y z, CNOT z x, Tinv x, Tinv y, T z, CNOT y x, Tinv x, CNOT y z, CNOT z x, CNOT x y] -- Printing instance Show Primitive where show (H x) = "H " ++ x show (X x) = "X " ++ x show (Z x) = "Z " ++ x show (Y x) = "Y " ++ x show (CNOT x y) = "CNOT " ++ x ++ " " ++ y show (CZ x y) = "CZ " ++ x ++ " " ++ y show (S x) = "S " ++ x show (Sinv x) = "S* " ++ x show (T x) = "T " ++ x show (Tinv x) = "T* " ++ x show (Swap x y) = "Swap " ++ x ++ " " ++ y show (Rz theta x) = "Rz(" ++ show theta ++ ") " ++ x show (Rx theta x) = "Rx(" ++ show theta ++ ") " ++ x show (Ry theta x) = "Ry(" ++ show theta ++ ") " ++ x show (Uninterp s xs) = s ++ concatMap (" " ++) xs instance Show Stmt where show (Gate gate) = show gate show (Seq lst) = intercalate "\n" (map show lst) show (Call id args) = show id ++ showLst args show (Repeat i (Call id args)) = show id ++ "^" ++ show i ++ showLst args show (Repeat i stmt) = "BEGIN^" ++ show i ++ "\n" ++ show stmt ++ "\n" ++ "END" instance Show Decl where show decl = "BEGIN " ++ putName (name decl) ++ showLst (params decl) ++ "\n" ++ show (body decl) ++ "\n" ++ "END" where putName "main" = "" putName s = s instance Show Circuit where show circ = intercalate "\n" (qubitline:inputline:body) where qubitline = ".v " ++ showLst (qubits circ) inputline = ".i " ++ showLst (filter (`Set.member` inputs circ) (qubits circ)) body = map show (decls circ) showLst = intercalate " " -- Test toffoli = Circuit { qubits = ["x", "y", "z"], inputs = Set.fromList ["x", "y", "z"], decls = [tof] } where tof = Decl { name = "main", params = [], body = Seq [ Gate $ H "z", Gate $ T "x", Gate $ T "y", Gate $ T "z", Gate $ CNOT "x" "y", Gate $ CNOT "y" "z", Gate $ CNOT "z" "x", Gate $ Tinv "x", Gate $ Tinv "y", Gate $ T "z", Gate $ CNOT "y" "x", Gate $ Tinv "x", Gate $ CNOT "y" "z", Gate $ CNOT "z" "x", Gate $ CNOT "x" "y", Gate $ H "z" ] }
null
https://raw.githubusercontent.com/meamy/feynman/2291ef5c388652dd352509da1d424e3fbd7b8da5/src/Feynman/Core.hs
haskell
# LANGUAGE Rank2Types # Phase angles Phase of theta Circuits Transformations WARNING: this is incorrect Removes all swap gates by re-indexing Printing Test
module Feynman.Core where import Data.List import Control.Monad import Data.Set (Set) import qualified Data.Set as Set import Data.Map (Map) import qualified Data.Map as Map import Feynman.Algebra.Base type ID = String type Loc = Int Phase angles either have the form pi*(a/2^b ) reduced mod 2 , or theta data Angle = Discrete DMod2 | Continuous Double deriving (Eq, Ord) apply :: (forall a. Num a => a -> a) -> Angle -> Angle apply f (Discrete a) = Discrete $ f a apply f (Continuous a) = Continuous $ f a apply2 :: (forall a. Num a => a -> a -> a) -> Angle -> Angle -> Angle apply2 f a b = case (a,b) of (Discrete a, Discrete b) -> Discrete $ f a b (Discrete a, Continuous b) -> Continuous $ f (toDouble a) b (Continuous a, Discrete b) -> Continuous $ f a (toDouble b) (Continuous a, Continuous b) -> Continuous $ f a b where toDouble = fromRational . toRational discretize :: Angle -> DyadicRational discretize (Discrete a) = unpack a discretize (Continuous a) = toDyadic a Phase of pi*(a/2^b ) reduced mod 2 dyadicPhase :: DyadicRational -> Angle dyadicPhase = Discrete . fromDyadic continuousPhase :: Double -> Angle continuousPhase = Continuous instance Show Angle where show (Discrete a) | a == 0 = show a | a == 1 = "pi" | otherwise = "pi*" ++ show a show (Continuous a) = show a instance Num Angle where (+) = apply2 (+) (-) = apply2 (-) (*) = apply2 (*) negate = apply negate abs = apply abs signum = apply signum fromInteger = Discrete . fromInteger instance Abelian Angle where power i (Discrete a) = Discrete $ power i a power i (Continuous a) = Continuous $ (fromInteger i) * a instance Periodic Angle where order (Discrete a) = order a order (Continuous _) = 0 data Primitive = H ID | X ID | Y ID | Z ID | CNOT ID ID | CZ ID ID | S ID | Sinv ID | T ID | Tinv ID | Swap ID ID | Rz Angle ID | Rx Angle ID | Ry Angle ID | Uninterp ID [ID] deriving (Eq) data Stmt = Gate Primitive | Seq [Stmt] | Call ID [ID] | Repeat Int Stmt data Decl = Decl { name :: ID, params :: [ID], body :: Stmt } data Circuit = Circuit { qubits :: [ID], inputs :: Set ID, decls :: [Decl] } foldCirc f b c = foldl (foldStmt f . body) b (decls c) foldStmt f (Seq st) b = f (Seq st) (foldr (foldStmt f) b st) foldStmt f (Repeat i st) b = f (Repeat i st) (foldStmt f st b) foldStmt f s b = f s b getArgs :: Primitive -> [ID] getArgs gate = case gate of H x -> [x] X x -> [x] Y x -> [x] Z x -> [x] CNOT x y -> [x,y] CZ x y -> [x,y] S x -> [x] Sinv x -> [x] T x -> [x] Tinv x -> [x] Swap x y -> [x,y] Rz theta x -> [x] Rx theta x -> [x] Ry theta x -> [x] Uninterp s xs -> xs daggerGate :: Primitive -> Primitive daggerGate x = case x of H _ -> x X _ -> x Z _ -> x CNOT _ _ -> x CZ _ _ -> x S x -> Sinv x Sinv x -> S x T x -> Tinv x Tinv x -> T x Swap _ _ -> x Rz theta x -> Rz (-theta) x Rx theta x -> Rx (-theta) x Ry theta x -> Ry (-theta) x Uninterp s xs -> Uninterp (s ++ "*") xs dagger :: [Primitive] -> [Primitive] dagger = reverse . map daggerGate substGate :: (ID -> ID) -> Primitive -> Primitive substGate f gate = case gate of H x -> H $ f x X x -> X $ f x Y x -> Y $ f x Z x -> Z $ f x CNOT x y -> CNOT (f x) (f y) CZ x y -> CZ (f x) (f y) S x -> S $ f x Sinv x -> Sinv $ f x T x -> T $ f x Tinv x -> Tinv $ f x Swap x y -> Swap (f x) (f y) Rz theta x -> Rz theta (f x) Rx theta x -> Rx theta (f x) Ry theta x -> Ry theta (f x) Uninterp s xs -> Uninterp s (map f xs) subst :: (ID -> ID) -> [Primitive] -> [Primitive] subst f = map (substGate f) ids :: [Primitive] -> [ID] ids = Set.toList . foldr f Set.empty where f gate set = foldr Set.insert set (idsGate gate) idsGate gate = case gate of H x -> [x] X x -> [x] Y x -> [x] Z x -> [x] CNOT x y -> [x,y] CZ x y -> [x,y] S x -> [x] Sinv x -> [x] T x -> [x] Tinv x -> [x] Swap x y -> [x,y] Rz theta x -> [x] Rx theta x -> [x] Ry theta x -> [x] Uninterp s xs -> xs converge :: Eq a => (a -> a) -> a -> a converge f a | a' == a = a' | otherwise = converge f a' where a' = f a simplifyPrimitive :: [Primitive] -> [Primitive] simplifyPrimitive circ = let circ' = zip circ [0..] simplify circ = let erasures = snd $ foldl' f (Map.empty, Set.empty) circ f (frontier, erasures) (gate, uid) = let args@(x:xs) = getArgs gate checkDagger (gate', uid') | gate' == daggerGate gate = Just (gate, uid') | otherwise = Nothing checkArg (gate, uid) q = do (_, uid') <- Map.lookup q frontier if uid' == uid then Just (gate, uid) else Nothing in case Map.lookup x frontier >>= checkDagger >>= (\g -> foldM checkArg g xs) of Just (_, uid') -> (foldr Map.delete frontier args, foldr Set.insert erasures [uid, uid']) Nothing -> (foldr (\q -> Map.insert q (gate, uid)) frontier args, erasures) in filter (\(_, uid) -> not $ Set.member uid erasures) circ in fst . unzip . (converge simplify) $ circ' removeSwaps :: [Primitive] -> [Primitive] removeSwaps = reverse . go (Map.empty, []) where get ctx q = Map.findWithDefault q q ctx go (ctx, acc) [] = acc go (ctx, acc) (x:xs) = case x of Swap q1 q2 -> let (q1', q2') = (get ctx q1, get ctx q2) in go (Map.insert q1 q2' $ Map.insert q2 q1' ctx, acc) xs _ -> go (ctx, (substGate (get ctx) x):acc) xs Builtin circuits cs :: ID -> ID -> [Primitive] cs x y = [T x, T y, CNOT x y, Tinv y, CNOT x y] cz :: ID -> ID -> [Primitive] cz x y = [S x, S y, CNOT x y, Sinv y, CNOT x y] ccx :: ID -> ID -> ID -> [Primitive] ccx x y z = [H z] ++ ccz x y z ++ [H z] ccz :: ID -> ID -> ID -> [Primitive] ccz x y z = [T x, T y, T z, CNOT x y, CNOT y z, CNOT z x, Tinv x, Tinv y, T z, CNOT y x, Tinv x, CNOT y z, CNOT z x, CNOT x y] instance Show Primitive where show (H x) = "H " ++ x show (X x) = "X " ++ x show (Z x) = "Z " ++ x show (Y x) = "Y " ++ x show (CNOT x y) = "CNOT " ++ x ++ " " ++ y show (CZ x y) = "CZ " ++ x ++ " " ++ y show (S x) = "S " ++ x show (Sinv x) = "S* " ++ x show (T x) = "T " ++ x show (Tinv x) = "T* " ++ x show (Swap x y) = "Swap " ++ x ++ " " ++ y show (Rz theta x) = "Rz(" ++ show theta ++ ") " ++ x show (Rx theta x) = "Rx(" ++ show theta ++ ") " ++ x show (Ry theta x) = "Ry(" ++ show theta ++ ") " ++ x show (Uninterp s xs) = s ++ concatMap (" " ++) xs instance Show Stmt where show (Gate gate) = show gate show (Seq lst) = intercalate "\n" (map show lst) show (Call id args) = show id ++ showLst args show (Repeat i (Call id args)) = show id ++ "^" ++ show i ++ showLst args show (Repeat i stmt) = "BEGIN^" ++ show i ++ "\n" ++ show stmt ++ "\n" ++ "END" instance Show Decl where show decl = "BEGIN " ++ putName (name decl) ++ showLst (params decl) ++ "\n" ++ show (body decl) ++ "\n" ++ "END" where putName "main" = "" putName s = s instance Show Circuit where show circ = intercalate "\n" (qubitline:inputline:body) where qubitline = ".v " ++ showLst (qubits circ) inputline = ".i " ++ showLst (filter (`Set.member` inputs circ) (qubits circ)) body = map show (decls circ) showLst = intercalate " " toffoli = Circuit { qubits = ["x", "y", "z"], inputs = Set.fromList ["x", "y", "z"], decls = [tof] } where tof = Decl { name = "main", params = [], body = Seq [ Gate $ H "z", Gate $ T "x", Gate $ T "y", Gate $ T "z", Gate $ CNOT "x" "y", Gate $ CNOT "y" "z", Gate $ CNOT "z" "x", Gate $ Tinv "x", Gate $ Tinv "y", Gate $ T "z", Gate $ CNOT "y" "x", Gate $ Tinv "x", Gate $ CNOT "y" "z", Gate $ CNOT "z" "x", Gate $ CNOT "x" "y", Gate $ H "z" ] }
ec9f6c73f7054c8308c1cf527a9ce39358bd0e183040bb32993ae6c6f8faa6d5
mikera/clisk
patterns.clj
(ns ^{:author "mikera" :doc "Library of clisk patterns generators"} clisk.patterns "Patterns and pattern generators" (:use [clisk core util node functions]) (:import java.awt.image.BufferedImage) (:import clisk.noise.Perlin) (:import clisk.noise.Simplex) (:import clisk.generator.Voronoi2D) ) (set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) (defn seed-perlin-noise! "Modify the perlin noise seed." ([] (clisk.noise.Perlin/seed)) ([s] (clisk.noise.Perlin/seed s))) (defn seed-simplex-noise! "Modify the simplex noise seed." ([] (clisk.noise.Simplex/seed)) ([s] (clisk.noise.Simplex/seed s))) (def perlin-noise "Standard 4-dimensional scalar perlin noise in range [0..1]" (node '(clisk.noise.Perlin/noise x y z t))) (def perlin-snoise "4-dimensional scalar perlin noise standardised with mean zero, range [-1..1]" (node '(clisk.noise.Perlin/snoise x y z t))) (def simplex-noise "Standard 4-dimensional scalar perlin noise in range [0..1]" (node '(clisk.noise.Simplex/noise x y z t))) (def simplex-snoise "4-dimensional scalar simplex noise standardised with mean zero, range [-1..1]" (node '(clisk.noise.Simplex/snoise x y z t))) (defn tile "Tiles a pattern in the range [0..1,0..1]" ([pattern] (warp vfrac pattern))) (def grain "Pattern returning a unique vector in [0..1)^4 range value for every point in 4D space" vector-hash) (def noise simplex-noise) (def snoise simplex-snoise) (defn make-multi-fractal "Creates a multi-fractal function from a given source function with additional parameters" ([function & {:keys [octaves lacunarity gain scale] :or {octaves 8 lacunarity 2.0 gain 0.5 scale 0.5}}] (let [octaves (long octaves) lacunarity (double lacunarity) gain (double gain) scale (double scale)] (when (< octaves 1) (error "make-multi-fractal requires octaves to be greater than or equal to one")) (apply v+ (for [octave (range 0 octaves)] (let [octave (double octave)] (warp (v* pos (Math/pow lacunarity octave)) (v* (* scale (Math/pow gain octave)) function)))))))) (def hash-cubes "4 dimensional randomly coloured unit hypercubes filling space" (warp vfloor grain)) (def colour-cubes "4 dimensional randomly coloured unit hypercubes filling space" (warp vfloor grain)) (def vnoise "4 dimensional vector perlin noise in range [0..1]^4" (vector-offsets noise)) (def vsnoise "4 dimensional vector standardised perlin noise in range [-1..1]^4" (vector-offsets snoise)) (def plasma "4 dimensional plasma, in range [0..1]" (make-multi-fractal noise)) (def splasma "4 dimensional plasma, in range [-1..1]" (make-multi-fractal snoise)) (def turbulence "Classic Perlin turbulence in one dimension" (make-multi-fractal (vabs snoise))) (def vturbulence "Classic Perlin turbulence in 4 dimensions" (make-multi-fractal (vabs vsnoise))) (def vplasma "4 dimensional vector plasma in range [0..1]^4" (vector-offsets plasma)) (def vsplasma "4 dimensional vector plasma in range [-1..1]^4" (vector-offsets splasma)) (defn turbulate "Adds random turbulence to a pattern according to a perlin noise offset" ([factor func] (offset (v* factor turbulence) func))) (defmethod clojure.core/print-dup java.awt.image.BufferedImage [^BufferedImage bi writer] (print-dup "[BufferedImage]" writer)) (defn checker "Checker pattern in (x,y) space, with 2*2 grid in [0..1,0..1] range" ([a b] (vif '(clojure.core/* (clojure.core/- (clisk.functions/frac x) 0.5) (clojure.core/- (clisk.functions/frac y) 0.5)) a b))) (defn checker-3D "Checker pattern in (x,y,z) space, with 2*2*2 grid in [0..1,0..1,0..1] range" ([a b] (vif '(clojure.core/* (clojure.core/- (clisk.functions/frac x) 0.5) (clojure.core/* (clojure.core/- (clisk.functions/frac y) 0.5) (clojure.core/- (clisk.functions/frac z) 0.5))) a b))) (defn globe "Creates a globe, returning the value of the function called on the surface of a unit sphere. (globe) alone produces z values that Can be used as a hight map" ([] (globe z 0.0)) ([function] (globe function 0.0)) ([function background] (vif (v- 1.0 (length [x y])) (warp [x y `(Math/sqrt (- 1.0 ~(:code (dot [x y] [x y]))))] function ) background))) (def ^:const DEFAULT-VORONOI-POINTS 32) (defn voronoi [& {:keys [points] :or {points DEFAULT-VORONOI-POINTS}}] (clisk.generator.Voronoi2D. (int points))) (defn voronoi-points ([& {:keys [points voronoi] :or {points DEFAULT-VORONOI-POINTS}}] (let [v-sym (gensym "voronoi") voronoi (or voronoi (clisk.generator.Voronoi2D. (int points))) obj-map {v-sym voronoi}] (vector-node (code-node `(.nearestX (static-cast clisk.generator.Voronoi2D ~v-sym) ~'x ~'y) :objects obj-map) (code-node `(.nearestY (static-cast clisk.generator.Voronoi2D ~v-sym) ~'x ~'y) :objects obj-map))))) (defn voronoi-function ([function & {:keys [points voronoi] :or {points DEFAULT-VORONOI-POINTS}}] (let [v-sym (gensym "voronoi") f-sym (gensym "func") voronoi (or voronoi (clisk.generator.Voronoi2D. (int points))) obj-map {v-sym voronoi f-sym (compile-scalar-node (component function 0))}] (code-node `(.firstSecondFunction (static-cast clisk.generator.Voronoi2D ~v-sym) ~'x ~'y ~f-sym) :objects obj-map)))) (defn voronoi-blocks "A patterns of angular blocks created from a voronoi map, in range [0..1]" [& args] (vmin 1.0 (v* 5.0 (apply voronoi-function `(Math/sqrt (- (* ~'y ~'y) (* ~'x ~'x))) args)))) (defn gridlines [& {:keys [colour background width scale] :or {colour [1 1 1 1] background [0 0 0 0] width 0.0625 scale 1.0}}] (vif (v- width (vmin (vfrac (vdivide x scale)) (vfrac (vdivide y scale)))) colour background)) (def spots "A spotted monochome pattern" (sigmoid (scale 0.23 (v* 10 (v- snoise 0.3 ))))) (def blotches "A blothchy monochome pattern" (sigmoid (scale 0.23 (v* 10 (v- splasma 0.2 )))))
null
https://raw.githubusercontent.com/mikera/clisk/44dd35fabbae68ad44f0e8ac2dec4c580203f7b9/src/main/clojure/clisk/patterns.clj
clojure
(ns ^{:author "mikera" :doc "Library of clisk patterns generators"} clisk.patterns "Patterns and pattern generators" (:use [clisk core util node functions]) (:import java.awt.image.BufferedImage) (:import clisk.noise.Perlin) (:import clisk.noise.Simplex) (:import clisk.generator.Voronoi2D) ) (set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) (defn seed-perlin-noise! "Modify the perlin noise seed." ([] (clisk.noise.Perlin/seed)) ([s] (clisk.noise.Perlin/seed s))) (defn seed-simplex-noise! "Modify the simplex noise seed." ([] (clisk.noise.Simplex/seed)) ([s] (clisk.noise.Simplex/seed s))) (def perlin-noise "Standard 4-dimensional scalar perlin noise in range [0..1]" (node '(clisk.noise.Perlin/noise x y z t))) (def perlin-snoise "4-dimensional scalar perlin noise standardised with mean zero, range [-1..1]" (node '(clisk.noise.Perlin/snoise x y z t))) (def simplex-noise "Standard 4-dimensional scalar perlin noise in range [0..1]" (node '(clisk.noise.Simplex/noise x y z t))) (def simplex-snoise "4-dimensional scalar simplex noise standardised with mean zero, range [-1..1]" (node '(clisk.noise.Simplex/snoise x y z t))) (defn tile "Tiles a pattern in the range [0..1,0..1]" ([pattern] (warp vfrac pattern))) (def grain "Pattern returning a unique vector in [0..1)^4 range value for every point in 4D space" vector-hash) (def noise simplex-noise) (def snoise simplex-snoise) (defn make-multi-fractal "Creates a multi-fractal function from a given source function with additional parameters" ([function & {:keys [octaves lacunarity gain scale] :or {octaves 8 lacunarity 2.0 gain 0.5 scale 0.5}}] (let [octaves (long octaves) lacunarity (double lacunarity) gain (double gain) scale (double scale)] (when (< octaves 1) (error "make-multi-fractal requires octaves to be greater than or equal to one")) (apply v+ (for [octave (range 0 octaves)] (let [octave (double octave)] (warp (v* pos (Math/pow lacunarity octave)) (v* (* scale (Math/pow gain octave)) function)))))))) (def hash-cubes "4 dimensional randomly coloured unit hypercubes filling space" (warp vfloor grain)) (def colour-cubes "4 dimensional randomly coloured unit hypercubes filling space" (warp vfloor grain)) (def vnoise "4 dimensional vector perlin noise in range [0..1]^4" (vector-offsets noise)) (def vsnoise "4 dimensional vector standardised perlin noise in range [-1..1]^4" (vector-offsets snoise)) (def plasma "4 dimensional plasma, in range [0..1]" (make-multi-fractal noise)) (def splasma "4 dimensional plasma, in range [-1..1]" (make-multi-fractal snoise)) (def turbulence "Classic Perlin turbulence in one dimension" (make-multi-fractal (vabs snoise))) (def vturbulence "Classic Perlin turbulence in 4 dimensions" (make-multi-fractal (vabs vsnoise))) (def vplasma "4 dimensional vector plasma in range [0..1]^4" (vector-offsets plasma)) (def vsplasma "4 dimensional vector plasma in range [-1..1]^4" (vector-offsets splasma)) (defn turbulate "Adds random turbulence to a pattern according to a perlin noise offset" ([factor func] (offset (v* factor turbulence) func))) (defmethod clojure.core/print-dup java.awt.image.BufferedImage [^BufferedImage bi writer] (print-dup "[BufferedImage]" writer)) (defn checker "Checker pattern in (x,y) space, with 2*2 grid in [0..1,0..1] range" ([a b] (vif '(clojure.core/* (clojure.core/- (clisk.functions/frac x) 0.5) (clojure.core/- (clisk.functions/frac y) 0.5)) a b))) (defn checker-3D "Checker pattern in (x,y,z) space, with 2*2*2 grid in [0..1,0..1,0..1] range" ([a b] (vif '(clojure.core/* (clojure.core/- (clisk.functions/frac x) 0.5) (clojure.core/* (clojure.core/- (clisk.functions/frac y) 0.5) (clojure.core/- (clisk.functions/frac z) 0.5))) a b))) (defn globe "Creates a globe, returning the value of the function called on the surface of a unit sphere. (globe) alone produces z values that Can be used as a hight map" ([] (globe z 0.0)) ([function] (globe function 0.0)) ([function background] (vif (v- 1.0 (length [x y])) (warp [x y `(Math/sqrt (- 1.0 ~(:code (dot [x y] [x y]))))] function ) background))) (def ^:const DEFAULT-VORONOI-POINTS 32) (defn voronoi [& {:keys [points] :or {points DEFAULT-VORONOI-POINTS}}] (clisk.generator.Voronoi2D. (int points))) (defn voronoi-points ([& {:keys [points voronoi] :or {points DEFAULT-VORONOI-POINTS}}] (let [v-sym (gensym "voronoi") voronoi (or voronoi (clisk.generator.Voronoi2D. (int points))) obj-map {v-sym voronoi}] (vector-node (code-node `(.nearestX (static-cast clisk.generator.Voronoi2D ~v-sym) ~'x ~'y) :objects obj-map) (code-node `(.nearestY (static-cast clisk.generator.Voronoi2D ~v-sym) ~'x ~'y) :objects obj-map))))) (defn voronoi-function ([function & {:keys [points voronoi] :or {points DEFAULT-VORONOI-POINTS}}] (let [v-sym (gensym "voronoi") f-sym (gensym "func") voronoi (or voronoi (clisk.generator.Voronoi2D. (int points))) obj-map {v-sym voronoi f-sym (compile-scalar-node (component function 0))}] (code-node `(.firstSecondFunction (static-cast clisk.generator.Voronoi2D ~v-sym) ~'x ~'y ~f-sym) :objects obj-map)))) (defn voronoi-blocks "A patterns of angular blocks created from a voronoi map, in range [0..1]" [& args] (vmin 1.0 (v* 5.0 (apply voronoi-function `(Math/sqrt (- (* ~'y ~'y) (* ~'x ~'x))) args)))) (defn gridlines [& {:keys [colour background width scale] :or {colour [1 1 1 1] background [0 0 0 0] width 0.0625 scale 1.0}}] (vif (v- width (vmin (vfrac (vdivide x scale)) (vfrac (vdivide y scale)))) colour background)) (def spots "A spotted monochome pattern" (sigmoid (scale 0.23 (v* 10 (v- snoise 0.3 ))))) (def blotches "A blothchy monochome pattern" (sigmoid (scale 0.23 (v* 10 (v- splasma 0.2 )))))
db2531aa39407c487e499085b005b89c5f322d68dddd8fb1d6232f430faab926
tweag/asterius
T13733.hs
module Main where delayedId :: a -> a delayedId x = x {-# INLINE [0] delayedId #-} alwaysTrue :: [Integer]-> Bool alwaysTrue xs = xs == delayedId xs {-# NOINLINE alwaysTrue #-} # RULES " [ Integer ] " forall ( xs : : [ Integer ] ) . xs = = xs = True # "[Integer] Eq Refl" forall (xs :: [Integer]). xs == xs = True #-} main = putStrLn $ if alwaysTrue undefined then "ok" else "not ok"
null
https://raw.githubusercontent.com/tweag/asterius/e7b823c87499656860f87b9b468eb0567add1de8/asterius/test/ghc-testsuite/simplCore/T13733.hs
haskell
# INLINE [0] delayedId # # NOINLINE alwaysTrue #
module Main where delayedId :: a -> a delayedId x = x alwaysTrue :: [Integer]-> Bool alwaysTrue xs = xs == delayedId xs # RULES " [ Integer ] " forall ( xs : : [ Integer ] ) . xs = = xs = True # "[Integer] Eq Refl" forall (xs :: [Integer]). xs == xs = True #-} main = putStrLn $ if alwaysTrue undefined then "ok" else "not ok"